From d8df3455d31f230c479c2ff74e14c5dd6ccae879 Mon Sep 17 00:00:00 2001 From: kmcd39 Date: Tue, 17 Jun 2025 17:39:41 -0400 Subject: [PATCH 1/8] in progress back up -- adding update_source_query and update_feature_query --- R/feature_queries.R | 107 ++++ R/shiny.R | 1095 +++++++++++++++++++------------- inst/htmlwidgets/maplibregl.js | 30 +- 3 files changed, 769 insertions(+), 463 deletions(-) create mode 100644 R/feature_queries.R diff --git a/R/feature_queries.R b/R/feature_queries.R new file mode 100644 index 0000000..5100de9 --- /dev/null +++ b/R/feature_queries.R @@ -0,0 +1,107 @@ + + +query_bbox_features <- function(map) { + + if ( + !shiny::is.reactive(map) && + !inherits( + map, + c("mapboxgl", "mapboxgl_proxy", "maplibregl", "maplibre_proxy") + ) + ) { + stop( + "Invalid map object. Expected mapboxgl, mapboxgl_proxy, maplibre or maplibre_proxy object within a Shiny context." + ) + } + + # If map is reactive (e.g., output$map in Shiny), evaluate it + if (shiny::is.reactive(map)) { + map <- map() + } + + # Determine if we're in a Shiny session + in_shiny <- shiny::isRunning() + + if (!in_shiny) { + warning( + "Getting drawn features outside of a Shiny context is not supported. Please use this function within a Shiny application." + ) + return(sf::st_sf(geometry = sf::st_sfc())) # Return an empty sf object + } + + # Get the session object + session <- shiny::getDefaultReactiveDomain() + + if (inherits(map, "mapboxgl") || inherits(map, "maplibregl")) { + # Initial map object in Shiny + map_id <- map$elementId + } else if ( + inherits(map, "mapboxgl_proxy") || inherits(map, "maplibre_proxy") + ) { + # Proxy object + map_id <- map$id + } else { + stop("Unexpected map object type.") + } + + # Send message to get drawn features + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + # For compare proxies + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + session$sendCustomMessage( + proxy_class, + list( + id = map_id, + message = list( + type = "get_drawn_features", + map = map$map_side + ) + ) + ) + } else { + # For regular proxies + proxy_class <- if (inherits(map, "mapboxgl_proxy")) "mapboxgl-proxy" else + "maplibre-proxy" + session$sendCustomMessage( + proxy_class, + list( + id = map_id, + message = list(type = "get_drawn_features") + ) + ) + } + + # Trim any module namespacing off to index the session proxy inputs + map_drawn_id <- sub( + pattern = session$ns(""), + replacement = "", + x = paste0(map_id, "_drawn_features") + ) + # Wait for response + features_json <- NULL + wait_time <- 0 + while ( + is.null(features_json) && + wait_time < 3 + ) { + # Wait up to 3 seconds + features_json <- session$input[[map_drawn_id]] + Sys.sleep(0.1) + wait_time <- wait_time + 0.1 + } + + if ( + !is.null(features_json) && + features_json != "null" && + nchar(features_json) > 0 + ) { + sf::st_make_valid(sf::st_read(features_json, quiet = TRUE)) + } else { + sf::st_sf(geometry = sf::st_sfc()) # Return an empty sf object if no features + } + +} diff --git a/R/shiny.R b/R/shiny.R index fcada0c..f4a4f98 100644 --- a/R/shiny.R +++ b/R/shiny.R @@ -8,21 +8,21 @@ #' @return A proxy object for the Mapbox GL map. #' @export mapboxgl_proxy <- function(mapId, session = shiny::getDefaultReactiveDomain()) { - if (is.null(session)) { - stop("mapboxgl_proxy must be called from within a Shiny session") - } + if (is.null(session)) { + stop("mapboxgl_proxy must be called from within a Shiny session") + } - if ( - !is.null(session$ns) && - nzchar(session$ns(NULL)) && - substring(mapId, 1, nchar(session$ns(""))) != session$ns("") - ) { - mapId <- session$ns(mapId) - } + if ( + !is.null(session$ns) && + nzchar(session$ns(NULL)) && + substring(mapId, 1, nchar(session$ns(""))) != session$ns("") + ) { + mapId <- session$ns(mapId) + } - proxy <- list(id = mapId, session = session) - class(proxy) <- "mapboxgl_proxy" - proxy + proxy <- list(id = mapId, session = session) + class(proxy) <- "mapboxgl_proxy" + proxy } #' Create a proxy object for a Maplibre GL map in Shiny @@ -35,21 +35,21 @@ mapboxgl_proxy <- function(mapId, session = shiny::getDefaultReactiveDomain()) { #' @return A proxy object for the Maplibre GL map. #' @export maplibre_proxy <- function(mapId, session = shiny::getDefaultReactiveDomain()) { - if (is.null(session)) { - stop("maplibre_proxy must be called from within a Shiny session") - } + if (is.null(session)) { + stop("maplibre_proxy must be called from within a Shiny session") + } - if ( - !is.null(session$ns) && - nzchar(session$ns(NULL)) && - substring(mapId, 1, nchar(session$ns(""))) != session$ns("") - ) { - mapId <- session$ns(mapId) - } + if ( + !is.null(session$ns) && + nzchar(session$ns(NULL)) && + substring(mapId, 1, nchar(session$ns(""))) != session$ns("") + ) { + mapId <- session$ns(mapId) + } - proxy <- list(id = mapId, session = session) - class(proxy) <- "maplibre_proxy" - proxy + proxy <- list(id = mapId, session = session) + class(proxy) <- "maplibre_proxy" + proxy } #' Set a filter on a map layer @@ -63,50 +63,50 @@ maplibre_proxy <- function(mapId, session = shiny::getDefaultReactiveDomain()) { #' @return The updated map object. #' @export set_filter <- function(map, layer_id, filter) { - if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { - if ( - inherits(map, "mapboxgl_compare_proxy") || - inherits(map, "maplibre_compare_proxy") - ) { - # For compare proxies, use the appropriate message handler - proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) - "mapboxgl-compare-proxy" else "maplibre-compare-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_filter", - layer = layer_id, - filter = filter, - map = map$map_side # Add which map to target - ) - ) - ) - } else { - # For regular proxies, use existing message handler - proxy_class <- if (inherits(map, "mapboxgl_proxy")) - "mapboxgl-proxy" else "maplibre-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_filter", - layer = layer_id, - filter = filter - ) - ) - ) - } + if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + # For compare proxies, use the appropriate message handler + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_filter", + layer = layer_id, + filter = filter, + map = map$map_side # Add which map to target + ) + ) + ) } else { - if (is.null(map$x$setFilter)) map$x$setFilter <- list() - map$x$setFilter[[length(map$x$setFilter) + 1]] <- list( + # For regular proxies, use existing message handler + proxy_class <- if (inherits(map, "mapboxgl_proxy")) + "mapboxgl-proxy" else "maplibre-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_filter", layer = layer_id, filter = filter + ) ) + ) } - return(map) + } else { + if (is.null(map$x$setFilter)) map$x$setFilter <- list() + map$x$setFilter[[length(map$x$setFilter) + 1]] <- list( + layer = layer_id, + filter = filter + ) + } + return(map) } #' Clear layers from a map using a proxy @@ -119,42 +119,42 @@ set_filter <- function(map, layer_id, filter) { #' @return The updated proxy object. #' @export clear_layer <- function(proxy, layer_id) { + if ( + !any( + inherits(proxy, "mapboxgl_proxy"), + inherits(proxy, "maplibre_proxy") + ) + ) { + stop("Invalid proxy object") + } + + # Handle vector of layer_ids by iterating through them + for (layer in layer_id) { if ( - !any( - inherits(proxy, "mapboxgl_proxy"), - inherits(proxy, "maplibre_proxy") - ) + inherits(proxy, "mapboxgl_compare_proxy") || + inherits(proxy, "maplibre_compare_proxy") ) { - stop("Invalid proxy object") + # For compare proxies + proxy_class <- if (inherits(proxy, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + message <- list( + type = "remove_layer", + layer = layer, + map = proxy$map_side + ) + } else { + # For regular proxies + proxy_class <- if (inherits(proxy, "mapboxgl_proxy")) + "mapboxgl-proxy" else "maplibre-proxy" + message <- list(type = "remove_layer", layer = layer) } - # Handle vector of layer_ids by iterating through them - for (layer in layer_id) { - if ( - inherits(proxy, "mapboxgl_compare_proxy") || - inherits(proxy, "maplibre_compare_proxy") - ) { - # For compare proxies - proxy_class <- if (inherits(proxy, "mapboxgl_compare_proxy")) - "mapboxgl-compare-proxy" else "maplibre-compare-proxy" - message <- list( - type = "remove_layer", - layer = layer, - map = proxy$map_side - ) - } else { - # For regular proxies - proxy_class <- if (inherits(proxy, "mapboxgl_proxy")) - "mapboxgl-proxy" else "maplibre-proxy" - message <- list(type = "remove_layer", layer = layer) - } - - proxy$session$sendCustomMessage( - proxy_class, - list(id = proxy$id, message = message) - ) - } - proxy + proxy$session$sendCustomMessage( + proxy_class, + list(id = proxy$id, message = message) + ) + } + proxy } #' Set a layout property on a map layer @@ -168,62 +168,62 @@ clear_layer <- function(proxy, layer_id) { #' @return The updated map object. #' @export set_layout_property <- function(map, layer_id = NULL, name, value, layer = NULL) { - # Handle backwards compatibility - if (!is.null(layer) && is.null(layer_id)) { - layer_id <- layer - warning("The 'layer' argument is deprecated. Please use 'layer_id' instead.", call. = FALSE) - } - - if (is.null(layer_id)) { - stop("layer_id is required") - } - if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { - if ( - inherits(map, "mapboxgl_compare_proxy") || - inherits(map, "maplibre_compare_proxy") - ) { - # For compare proxies - proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) - "mapboxgl-compare-proxy" else "maplibre-compare-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_layout_property", - layer = layer_id, - name = name, - value = value, - map = map$map_side - ) - ) - ) - } else { - # For regular proxies - proxy_class <- if (inherits(map, "mapboxgl_proxy")) - "mapboxgl-proxy" else "maplibre-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_layout_property", - layer = layer_id, - name = name, - value = value - ) - ) - ) - } + # Handle backwards compatibility + if (!is.null(layer) && is.null(layer_id)) { + layer_id <- layer + warning("The 'layer' argument is deprecated. Please use 'layer_id' instead.", call. = FALSE) + } + + if (is.null(layer_id)) { + stop("layer_id is required") + } + if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + # For compare proxies + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_layout_property", + layer = layer_id, + name = name, + value = value, + map = map$map_side + ) + ) + ) } else { - if (is.null(map$x$setLayoutProperty)) map$x$setLayoutProperty <- list() - map$x$setLayoutProperty[[length(map$x$setLayoutProperty) + 1]] <- list( + # For regular proxies + proxy_class <- if (inherits(map, "mapboxgl_proxy")) + "mapboxgl-proxy" else "maplibre-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_layout_property", layer = layer_id, name = name, value = value + ) ) + ) } - return(map) + } else { + if (is.null(map$x$setLayoutProperty)) map$x$setLayoutProperty <- list() + map$x$setLayoutProperty[[length(map$x$setLayoutProperty) + 1]] <- list( + layer = layer_id, + name = name, + value = value + ) + } + return(map) } #' Set a paint property on a map layer @@ -237,62 +237,62 @@ set_layout_property <- function(map, layer_id = NULL, name, value, layer = NULL) #' @return The updated map object. #' @export set_paint_property <- function(map, layer_id = NULL, name, value, layer = NULL) { - # Handle backwards compatibility - if (!is.null(layer) && is.null(layer_id)) { - layer_id <- layer - warning("The 'layer' argument is deprecated. Please use 'layer_id' instead.", call. = FALSE) - } - - if (is.null(layer_id)) { - stop("layer_id is required") - } - if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { - if ( - inherits(map, "mapboxgl_compare_proxy") || - inherits(map, "maplibre_compare_proxy") - ) { - # For compare proxies - proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) - "mapboxgl-compare-proxy" else "maplibre-compare-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_paint_property", - layer = layer_id, - name = name, - value = value, - map = map$map_side - ) - ) - ) - } else { - # For regular proxies - proxy_class <- if (inherits(map, "mapboxgl_proxy")) - "mapboxgl-proxy" else "maplibre-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_paint_property", - layer = layer_id, - name = name, - value = value - ) - ) - ) - } + # Handle backwards compatibility + if (!is.null(layer) && is.null(layer_id)) { + layer_id <- layer + warning("The 'layer' argument is deprecated. Please use 'layer_id' instead.", call. = FALSE) + } + + if (is.null(layer_id)) { + stop("layer_id is required") + } + if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + # For compare proxies + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_paint_property", + layer = layer_id, + name = name, + value = value, + map = map$map_side + ) + ) + ) } else { - if (is.null(map$x$setPaintProperty)) map$x$setPaintProperty <- list() - map$x$setPaintProperty[[length(map$x$setPaintProperty) + 1]] <- list( + # For regular proxies + proxy_class <- if (inherits(map, "mapboxgl_proxy")) + "mapboxgl-proxy" else "maplibre-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_paint_property", layer = layer_id, name = name, value = value + ) ) + ) } - return(map) + } else { + if (is.null(map$x$setPaintProperty)) map$x$setPaintProperty <- list() + map$x$setPaintProperty[[length(map$x$setPaintProperty) + 1]] <- list( + layer = layer_id, + name = name, + value = value + ) + } + return(map) } #' Clear markers from a map in a Shiny session @@ -302,39 +302,39 @@ set_paint_property <- function(map, layer_id = NULL, name, value, layer = NULL) #' @return The modified map object with the markers cleared. #' @export clear_markers <- function(map) { - if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { - if ( - inherits(map, "mapboxgl_compare_proxy") || - inherits(map, "maplibre_compare_proxy") - ) { - # For compare proxies - proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) - "mapboxgl-compare-proxy" else "maplibre-compare-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "clear_markers", - map = map$map_side - ) - ) - ) - } else { - # For regular proxies - proxy_class <- if (inherits(map, "mapboxgl_proxy")) - "mapboxgl-proxy" else "maplibre-proxy" - map$session$sendCustomMessage( - proxy_class, - list(id = map$id, message = list(type = "clear_markers")) - ) - } - } else { - stop( - "clear_markers() can only be used with mapboxgl_proxy(), maplibre_proxy(), mapboxgl_compare_proxy(), or maplibre_compare_proxy()" + if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + # For compare proxies + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "clear_markers", + map = map$map_side + ) ) + ) + } else { + # For regular proxies + proxy_class <- if (inherits(map, "mapboxgl_proxy")) + "mapboxgl-proxy" else "maplibre-proxy" + map$session$sendCustomMessage( + proxy_class, + list(id = map$id, message = list(type = "clear_markers")) + ) } - return(map) + } else { + stop( + "clear_markers() can only be used with mapboxgl_proxy(), maplibre_proxy(), mapboxgl_compare_proxy(), or maplibre_compare_proxy()" + ) + } + return(map) } #' Update the style of a map @@ -364,52 +364,52 @@ clear_markers <- function(map) { #' }) #' } set_style <- function(map, style, config = NULL, diff = TRUE, preserve_layers = TRUE) { - if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { - if ( - inherits(map, "mapboxgl_compare_proxy") || - inherits(map, "maplibre_compare_proxy") - ) { - # For compare proxies - proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) - "mapboxgl-compare-proxy" else "maplibre-compare-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_style", - style = style, - config = config, - diff = diff, - preserve_layers = preserve_layers, - map = map$map_side - ) - ) - ) - } else { - # For regular proxies - proxy_class <- if (inherits(map, "mapboxgl_proxy")) - "mapboxgl-proxy" else "maplibre-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_style", - style = style, - config = config, - diff = diff, - preserve_layers = preserve_layers - ) - ) - ) - } + if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + # For compare proxies + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_style", + style = style, + config = config, + diff = diff, + preserve_layers = preserve_layers, + map = map$map_side + ) + ) + ) } else { - stop( - "set_style can only be used with mapboxgl_proxy, maplibre_proxy, mapboxgl_compare_proxy, or maplibre_compare_proxy." + # For regular proxies + proxy_class <- if (inherits(map, "mapboxgl_proxy")) + "mapboxgl-proxy" else "maplibre-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_style", + style = style, + config = config, + diff = diff, + preserve_layers = preserve_layers + ) ) + ) } - return(map) + } else { + stop( + "set_style can only be used with mapboxgl_proxy, maplibre_proxy, mapboxgl_compare_proxy, or maplibre_compare_proxy." + ) + } + return(map) } #' Move a layer to a different z-position @@ -423,44 +423,44 @@ set_style <- function(map, style, config = NULL, diff = TRUE, preserve_layers = #' @return The updated proxy object. #' @export move_layer <- function(proxy, layer_id, before_id = NULL) { - if ( - !any( - inherits(proxy, "mapboxgl_proxy"), - inherits(proxy, "maplibre_proxy") - ) - ) { - stop("Invalid proxy object") - } - - if ( - inherits(proxy, "mapboxgl_compare_proxy") || - inherits(proxy, "maplibre_compare_proxy") - ) { - # For compare proxies - proxy_class <- if (inherits(proxy, "mapboxgl_compare_proxy")) - "mapboxgl-compare-proxy" else "maplibre-compare-proxy" - message <- list( - type = "move_layer", - layer = layer_id, - before = before_id, - map = proxy$map_side - ) - } else { - # For regular proxies - proxy_class <- if (inherits(proxy, "mapboxgl_proxy")) - "mapboxgl-proxy" else "maplibre-proxy" - message <- list( - type = "move_layer", - layer = layer_id, - before = before_id - ) - } + if ( + !any( + inherits(proxy, "mapboxgl_proxy"), + inherits(proxy, "maplibre_proxy") + ) + ) { + stop("Invalid proxy object") + } - proxy$session$sendCustomMessage( - proxy_class, - list(id = proxy$id, message = message) + if ( + inherits(proxy, "mapboxgl_compare_proxy") || + inherits(proxy, "maplibre_compare_proxy") + ) { + # For compare proxies + proxy_class <- if (inherits(proxy, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + message <- list( + type = "move_layer", + layer = layer_id, + before = before_id, + map = proxy$map_side ) - proxy + } else { + # For regular proxies + proxy_class <- if (inherits(proxy, "mapboxgl_proxy")) + "mapboxgl-proxy" else "maplibre-proxy" + message <- list( + type = "move_layer", + layer = layer_id, + before = before_id + ) + } + + proxy$session$sendCustomMessage( + proxy_class, + list(id = proxy$id, message = message) + ) + proxy } #' Set tooltip on a map layer @@ -473,57 +473,57 @@ move_layer <- function(proxy, layer_id, before_id = NULL) { #' @return The updated map object. #' @export set_tooltip <- function(map, layer_id = NULL, tooltip, layer = NULL) { - # Handle backwards compatibility - if (!is.null(layer) && is.null(layer_id)) { - layer_id <- layer - warning("The 'layer' argument is deprecated. Please use 'layer_id' instead.", call. = FALSE) - } - - if (is.null(layer_id)) { - stop("layer_id is required") - } - if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { - if ( - inherits(map, "mapboxgl_compare_proxy") || - inherits(map, "maplibre_compare_proxy") - ) { - # For compare proxies - proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) - "mapboxgl-compare-proxy" else "maplibre-compare-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_tooltip", - layer = layer_id, - tooltip = tooltip, - map = map$map_side - ) - ) - ) - } else { - # For regular proxies - proxy_class <- if (inherits(map, "mapboxgl_proxy")) - "mapboxgl-proxy" else "maplibre-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_tooltip", - layer = layer_id, - tooltip = tooltip - ) - ) - ) - } + # Handle backwards compatibility + if (!is.null(layer) && is.null(layer_id)) { + layer_id <- layer + warning("The 'layer' argument is deprecated. Please use 'layer_id' instead.", call. = FALSE) + } + + if (is.null(layer_id)) { + stop("layer_id is required") + } + if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + # For compare proxies + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_tooltip", + layer = layer_id, + tooltip = tooltip, + map = map$map_side + ) + ) + ) } else { - stop( - "set_tooltip can only be used with mapboxgl_proxy, maplibre_proxy, mapboxgl_compare_proxy, or maplibre_compare_proxy." + # For regular proxies + proxy_class <- if (inherits(map, "mapboxgl_proxy")) + "mapboxgl-proxy" else "maplibre-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_tooltip", + layer = layer_id, + tooltip = tooltip + ) ) + ) } - return(map) + } else { + stop( + "set_tooltip can only be used with mapboxgl_proxy, maplibre_proxy, mapboxgl_compare_proxy, or maplibre_compare_proxy." + ) + } + return(map) } #' Set popup on a map layer @@ -536,57 +536,57 @@ set_tooltip <- function(map, layer_id = NULL, tooltip, layer = NULL) { #' @return The updated map object. #' @export set_popup <- function(map, layer_id = NULL, popup, layer = NULL) { - # Handle backwards compatibility - if (!is.null(layer) && is.null(layer_id)) { - layer_id <- layer - warning("The 'layer' argument is deprecated. Please use 'layer_id' instead.", call. = FALSE) - } - - if (is.null(layer_id)) { - stop("layer_id is required") - } - if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { - if ( - inherits(map, "mapboxgl_compare_proxy") || - inherits(map, "maplibre_compare_proxy") - ) { - # For compare proxies - proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) - "mapboxgl-compare-proxy" else "maplibre-compare-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_popup", - layer = layer_id, - popup = popup, - map = map$map_side - ) - ) - ) - } else { - # For regular proxies - proxy_class <- if (inherits(map, "mapboxgl_proxy")) - "mapboxgl-proxy" else "maplibre-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_popup", - layer = layer_id, - popup = popup - ) - ) - ) - } + # Handle backwards compatibility + if (!is.null(layer) && is.null(layer_id)) { + layer_id <- layer + warning("The 'layer' argument is deprecated. Please use 'layer_id' instead.", call. = FALSE) + } + + if (is.null(layer_id)) { + stop("layer_id is required") + } + if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + # For compare proxies + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_popup", + layer = layer_id, + popup = popup, + map = map$map_side + ) + ) + ) } else { - stop( - "set_popup can only be used with mapboxgl_proxy, maplibre_proxy, mapboxgl_compare_proxy, or maplibre_compare_proxy." + # For regular proxies + proxy_class <- if (inherits(map, "mapboxgl_proxy")) + "mapboxgl-proxy" else "maplibre-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_popup", + layer = layer_id, + popup = popup + ) ) + ) } - return(map) + } else { + stop( + "set_popup can only be used with mapboxgl_proxy, maplibre_proxy, mapboxgl_compare_proxy, or maplibre_compare_proxy." + ) + } + return(map) } #' Set source of a map layer @@ -599,63 +599,242 @@ set_popup <- function(map, layer_id = NULL, popup, layer = NULL) { #' @return The updated map object. #' @export set_source <- function(map, layer_id = NULL, source, layer = NULL) { - # Handle backwards compatibility - if (!is.null(layer) && is.null(layer_id)) { - layer_id <- layer - warning("The 'layer' argument is deprecated. Please use 'layer_id' instead.", call. = FALSE) - } - - if (is.null(layer_id)) { - stop("layer_id is required") + # Handle backwards compatibility + if (!is.null(layer) && is.null(layer_id)) { + layer_id <- layer + warning("The 'layer' argument is deprecated. Please use 'layer_id' instead.", call. = FALSE) + } + + if (is.null(layer_id)) { + stop("layer_id is required") + } + if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { + # Convert sf objects to GeoJSON source + if (inherits(source, "sf")) { + source <- geojsonsf::sf_geojson(sf::st_transform( + source, + crs = 4326 + )) } - if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { - # Convert sf objects to GeoJSON source - if (inherits(source, "sf")) { - source <- geojsonsf::sf_geojson(sf::st_transform( - source, - crs = 4326 - )) - } - - if ( - inherits(map, "mapboxgl_compare_proxy") || - inherits(map, "maplibre_compare_proxy") - ) { - # For compare proxies - proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) - "mapboxgl-compare-proxy" else "maplibre-compare-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_source", - layer = layer_id, - source = source, - map = map$map_side - ) - ) - ) - } else { - # For regular proxies - proxy_class <- if (inherits(map, "mapboxgl_proxy")) - "mapboxgl-proxy" else "maplibre-proxy" - map$session$sendCustomMessage( - proxy_class, - list( - id = map$id, - message = list( - type = "set_source", - layer = layer_id, - source = source - ) - ) - ) - } + + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + # For compare proxies + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_source", + layer = layer_id, + source = source, + map = map$map_side + ) + ) + ) } else { - stop( - "set_source can only be used with mapboxgl_proxy, maplibre_proxy, mapboxgl_compare_proxy, or maplibre_compare_proxy." + # For regular proxies + proxy_class <- if (inherits(map, "mapboxgl_proxy")) + "mapboxgl-proxy" else "maplibre-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "set_source", + layer = layer_id, + source = source + ) ) + ) } - return(map) + } else { + stop( + "set_source can only be used with mapboxgl_proxy, maplibre_proxy, mapboxgl_compare_proxy, or maplibre_compare_proxy." + ) + } + return(map) +} + +#' Get a set of features on a map +#' +#' @param layer_id layer_id of map layer from which to query features. +#' @param geometry if NULL, uses the bbox of the current viewport. Otherwise, a +#' specific geometry can be specified to pull features overlapping that +#' geometry. +#' +#' See [queryrenderedfeatures][https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#queryrenderedfeatures] +#' +#' @return Nothing, but updates `input$map_feature_query` +#' @export query_rendered_features +#' +#query_rendered_features <- function(map, layer_id = NULL, geometry = NULL) { +update_feature_query <- function(map, layer_id = NULL, geometry = NULL + ) { + #browser() + if( !(inherits(map, "mapboxgl_proxy") || inherits(map, "maplibre_proxy")) + ) { + warning( + "Getting features in bbox outside of a Shiny context is not supported. Please use this function within a Shiny application." + ) + return(data.frame()) # Return an empty data.frame + } + + # Get the session object + session <- shiny::getDefaultReactiveDomain() + # Proxy object id + map_id <- map$id + + #browser() + + # Send message to get drawn features + message.content <- list( + type = "query_rendered_features", + layer = layer_id, + geometry = geometry + ) + + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + # For compare proxies + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + session$sendCustomMessage( + proxy_class, + list( + id = map_id, + message = + c(message.content, + map = map$map_side) + ) + ) + } else { + # For regular proxies + proxy_class <- if (inherits(map, "mapboxgl_proxy")) + "mapboxgl-proxy" else "maplibre-proxy" + session$sendCustomMessage( + proxy_class, + list( + id = map_id, + message = message.content + ) + ) + } + + #browser() + # # remove the module namespace so the input element can be constructed + # # correctly by the javascript appropriately + # map_id <- + # sub( + # pattern = session$ns(""), + # replacement = "", + # x = paste0(map_id, "_feature_query") + # ) + # + # # Wait for response + # features_json <- NULL + # wait_time <- 0 + # while ( + # is.null(features_json) && + # wait_time < 3 + # ) { + # # Wait up to 3 seconds + # features_json <- session$input[[map_id]] + # Sys.sleep(0.1) + # wait_time <- wait_time + 0.1 + # } + # + # if ( + # !is.null(features_json) && + # features_json != "null" && + # nchar(features_json) > 0 + # ) { + # features <- jsonlite::fromJSON(features_json) + # features <- features |> dplyr::distinct() + # return(features) + # } else { + # NULL + # } +} + + +#' Queries all features in a source +#' +#' Will pull all features (visible or not) from a given source and save as a +#' shiny input +#' +#' @param layer_id layer_id of map layer from which to query features. +#' @param source_id id of source layer for which to query features. Note the +#' returned features will be empty if this is left NULL and query is refering +#' to a basemap layer. +#' +#' See +#' [querySourceFeatures][https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#querysourcefeatures] +#' +#' @return Nothing, but updates `input$map_source_query` +#' @export update_source_query +#' +update_source_query <- function(map, source_id, layer_id = NULL + ) { + + #browser() + if( !(inherits(map, "mapboxgl_proxy") || inherits(map, "maplibre_proxy")) + ) { + warning( + "Getting features in bbox outside of a Shiny context is not supported. Please use this function within a Shiny application." + ) + return(data.frame()) # Return an empty data.frame + } + + # Get the session object + session <- shiny::getDefaultReactiveDomain() + # Proxy object id + map_id <- map$id + + #browser() + + # Send message to get drawn features + message.content <- list( + type = "query_source_features", + source = source_id, + layer = layer_id + ) + + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + # For compare proxies + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + session$sendCustomMessage( + proxy_class, + list( + id = map_id, + message = + c(message.content, + map = map$map_side) + ) + ) + } else { + # For regular proxies + proxy_class <- if (inherits(map, "mapboxgl_proxy")) + "mapboxgl-proxy" else "maplibre-proxy" + session$sendCustomMessage( + proxy_class, + list( + id = map_id, + message = + message.content + ) + ) + } + + } diff --git a/inst/htmlwidgets/maplibregl.js b/inst/htmlwidgets/maplibregl.js index 6ec31e8..1946d3b 100644 --- a/inst/htmlwidgets/maplibregl.js +++ b/inst/htmlwidgets/maplibregl.js @@ -1617,6 +1617,7 @@ if (HTMLWidgets.shinyMode) { } } } + if (message.type === "set_filter") { map.setFilter(message.layer, message.filter); // Track filter state for layer restoration @@ -1954,11 +1955,30 @@ if (HTMLWidgets.shinyMode) { } layerState.paintProperties[layerId][propertyName] = newValue; } else if (message.type === "query_rendered_features") { - const features = map.queryRenderedFeatures(message.geometry, { - layers: message.layers, - filter: message.filter, + //debugger; + var features = map.queryRenderedFeatures(message.geometry, { + layers: [message.layer] + //filter: message.filter, + }); + var properties = features.map(f => f.properties); + + Shiny.setInputValue( + data.id + "_feature_query", + JSON.stringify(properties), + {priority: "event"} + ); + } else if (message.type === "query_source_features") { + debugger; + var features = map.querySourceFeatures(message.source, { + sourceLayer: [message.layer] }); - Shiny.setInputValue(el.id + "_feature_query", features); + var properties = features.map(f => f.properties); + + Shiny.setInputValue( + data.id + "_source_query", + JSON.stringify(properties), + {priority: "event"} + ); } else if (message.type === "add_legend") { // Extract legend ID from HTML to track it const legendIdMatch = message.html.match(/id="([^"]+)"/); @@ -3776,4 +3796,4 @@ if (HTMLWidgets.shinyMode) { map.controls.push(customControl); } }); -} +} \ No newline at end of file From d6414c61bb1baa0273acee7329e51b795e7ff947 Mon Sep 17 00:00:00 2001 From: kmcd39 Date: Wed, 18 Jun 2025 10:14:50 -0400 Subject: [PATCH 2/8] update source and feature query functions are implemented in rough forms for maplibre --- R/shiny.R | 6 +++--- inst/htmlwidgets/maplibregl.js | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/R/shiny.R b/R/shiny.R index f4a4f98..db4b03b 100644 --- a/R/shiny.R +++ b/R/shiny.R @@ -777,10 +777,10 @@ update_feature_query <- function(map, layer_id = NULL, geometry = NULL #' See #' [querySourceFeatures][https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#querysourcefeatures] #' -#' @return Nothing, but updates `input$map_source_query` +#' @return Nothing, but updates `input$map_source_query` in shiny contexts. #' @export update_source_query #' -update_source_query <- function(map, source_id, layer_id = NULL +update_source_query <- function(map, source_id, source_layer = NULL ) { #browser() @@ -803,7 +803,7 @@ update_source_query <- function(map, source_id, layer_id = NULL message.content <- list( type = "query_source_features", source = source_id, - layer = layer_id + layer = source_layer ) if ( diff --git a/inst/htmlwidgets/maplibregl.js b/inst/htmlwidgets/maplibregl.js index 1946d3b..9088522 100644 --- a/inst/htmlwidgets/maplibregl.js +++ b/inst/htmlwidgets/maplibregl.js @@ -1972,11 +1972,11 @@ if (HTMLWidgets.shinyMode) { var features = map.querySourceFeatures(message.source, { sourceLayer: [message.layer] }); - var properties = features.map(f => f.properties); + //var properties = features.map(f => f.properties); Shiny.setInputValue( data.id + "_source_query", - JSON.stringify(properties), + JSON.stringify(features), {priority: "event"} ); } else if (message.type === "add_legend") { From 8604315f3afc654d36b90746cfdd6c8d73ed77c7 Mon Sep 17 00:00:00 2001 From: kmcd39 Date: Wed, 18 Jun 2025 10:23:41 -0400 Subject: [PATCH 3/8] deleting old fcns --- R/feature_queries.R | 107 -------------------------------------------- 1 file changed, 107 deletions(-) delete mode 100644 R/feature_queries.R diff --git a/R/feature_queries.R b/R/feature_queries.R deleted file mode 100644 index 5100de9..0000000 --- a/R/feature_queries.R +++ /dev/null @@ -1,107 +0,0 @@ - - -query_bbox_features <- function(map) { - - if ( - !shiny::is.reactive(map) && - !inherits( - map, - c("mapboxgl", "mapboxgl_proxy", "maplibregl", "maplibre_proxy") - ) - ) { - stop( - "Invalid map object. Expected mapboxgl, mapboxgl_proxy, maplibre or maplibre_proxy object within a Shiny context." - ) - } - - # If map is reactive (e.g., output$map in Shiny), evaluate it - if (shiny::is.reactive(map)) { - map <- map() - } - - # Determine if we're in a Shiny session - in_shiny <- shiny::isRunning() - - if (!in_shiny) { - warning( - "Getting drawn features outside of a Shiny context is not supported. Please use this function within a Shiny application." - ) - return(sf::st_sf(geometry = sf::st_sfc())) # Return an empty sf object - } - - # Get the session object - session <- shiny::getDefaultReactiveDomain() - - if (inherits(map, "mapboxgl") || inherits(map, "maplibregl")) { - # Initial map object in Shiny - map_id <- map$elementId - } else if ( - inherits(map, "mapboxgl_proxy") || inherits(map, "maplibre_proxy") - ) { - # Proxy object - map_id <- map$id - } else { - stop("Unexpected map object type.") - } - - # Send message to get drawn features - if ( - inherits(map, "mapboxgl_compare_proxy") || - inherits(map, "maplibre_compare_proxy") - ) { - # For compare proxies - proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) - "mapboxgl-compare-proxy" else "maplibre-compare-proxy" - session$sendCustomMessage( - proxy_class, - list( - id = map_id, - message = list( - type = "get_drawn_features", - map = map$map_side - ) - ) - ) - } else { - # For regular proxies - proxy_class <- if (inherits(map, "mapboxgl_proxy")) "mapboxgl-proxy" else - "maplibre-proxy" - session$sendCustomMessage( - proxy_class, - list( - id = map_id, - message = list(type = "get_drawn_features") - ) - ) - } - - # Trim any module namespacing off to index the session proxy inputs - map_drawn_id <- sub( - pattern = session$ns(""), - replacement = "", - x = paste0(map_id, "_drawn_features") - ) - # Wait for response - features_json <- NULL - wait_time <- 0 - while ( - is.null(features_json) && - wait_time < 3 - ) { - # Wait up to 3 seconds - features_json <- session$input[[map_drawn_id]] - Sys.sleep(0.1) - wait_time <- wait_time + 0.1 - } - - if ( - !is.null(features_json) && - features_json != "null" && - nchar(features_json) > 0 - ) { - sf::st_make_valid(sf::st_read(features_json, quiet = TRUE)) - } else { - sf::st_sf(geometry = sf::st_sfc()) # Return an empty sf object if no features - } - -} From 2be61e4c70371b5b9adb87adb342ff2d53e7c96b Mon Sep 17 00:00:00 2001 From: kmcd39 Date: Wed, 18 Jun 2025 14:01:03 -0400 Subject: [PATCH 4/8] implemented option to auto refresh features in viewport as shiny input when enabled --- R/hover.R | 50 +++++++-- inst/htmlwidgets/maplibregl.js | 194 ++++++++++++++++++--------------- 2 files changed, 148 insertions(+), 96 deletions(-) diff --git a/R/hover.R b/R/hover.R index dd54b9a..ab0a0b6 100644 --- a/R/hover.R +++ b/R/hover.R @@ -2,7 +2,7 @@ #' #' This function enables hover functionality for maplibre and mapboxgl widgets #' in Shiny applications, providing `_hover` and `_feature_hover` input values. -#' +#' #' @param map A maplibre or mapboxgl widget object. #' @param coordinates Logical. If TRUE, provides general mouse coordinates via `_hover` input. Defaults to TRUE. #' @param features Logical. If TRUE, provides feature information via `_feature_hover` input when hovering over map features. Defaults to TRUE. @@ -14,40 +14,70 @@ #' \dontrun{ #' library(shiny) #' library(mapgl) -#' +#' #' ui <- fluidPage( #' maplibreOutput("map"), #' verbatimTextOutput("hover_info") #' ) -#' +#' #' server <- function(input, output) { #' output$map <- renderMaplibre({ #' maplibre() |> #' enable_shiny_hover() #' }) -#' +#' #' output$hover_info <- renderText({ #' paste("Mouse at:", input$map_hover$lng, input$map_hover$lat) #' }) #' } -#' +#' #' shinyApp(ui, server) #' } enable_shiny_hover <- function(map, coordinates = TRUE, features = TRUE) { - + # Check if map is valid if (!inherits(map, c("maplibregl", "mapboxgl"))) { stop("Map must be a maplibre or mapboxgl widget object", call. = FALSE) } - + # Add hover configuration to the widget if (is.null(map$x$hover_events)) { map$x$hover_events <- list() } - + map$x$hover_events$enabled <- TRUE map$x$hover_events$coordinates <- coordinates map$x$hover_events$features <- features - + + return(map) +} + + +#' Enable features in viewport automatically updating shiny inputs +#' +#' This function causes a map widget in shiny to automatically refresh a shiny +#' input `_bbox_features` with all features for the given layer in the bounding +#' box of the map's viewport. +#' +#' @return The modified map object with automatic querying of viewport features +#' enabled. +#' @export enable_shiny_viewport_features +#' +enable_shiny_viewport_features <- function(map, + layer_id) { + + # Check if map is valid + if (!inherits(map, c("maplibregl", "mapboxgl"))) { + stop("Map must be a maplibre or mapboxgl widget object", call. = FALSE) + } + + # Add hover configuration to the widget + if (is.null(map$x$viewport_features)) { + map$x$viewport_features <- list() + } + + map$x$viewport_features$enabled <- TRUE + map$x$viewport_features$layer <- layer_id + return(map) -} \ No newline at end of file +} diff --git a/inst/htmlwidgets/maplibregl.js b/inst/htmlwidgets/maplibregl.js index 9088522..fe6bd2b 100644 --- a/inst/htmlwidgets/maplibregl.js +++ b/inst/htmlwidgets/maplibregl.js @@ -126,7 +126,7 @@ function onClickPopup(e, map, popupProperty, layerId) { window._mapboxPopups[layerId] = popup; // Remove reference when popup is closed - popup.on('close', function() { + popup.on('close', function () { if (window._mapboxPopups[layerId] === popup) { delete window._mapboxPopups[layerId]; } @@ -330,6 +330,30 @@ HTMLWidgets.widget({ ymax: bounds.getNorth(), }); }); + + if (x.viewport_features && x.viewport_features.enabled) { + + map.on("moveend", function (e) { + debugger; + var features = map.queryRenderedFeatures(null, { + layers: [x.viewport_features.layer] + }); + + if (features.length > 0) { + var properties = features.map(f => f.properties); + + Shiny.setInputValue( + el.id + "_bbox_features", + JSON.stringify(properties) + ); + } else { + Shiny.setInputValue( + el.id + "_bbox_features", + null + ); + } + }); + } } // Set config properties if provided @@ -626,7 +650,7 @@ HTMLWidgets.widget({ const featureState = { source: typeof layer.source === - "string" + "string" ? layer.source : layer.id, id: hoveredFeatureId, @@ -644,7 +668,7 @@ HTMLWidgets.widget({ const featureState = { source: typeof layer.source === - "string" + "string" ? layer.source : layer.id, id: hoveredFeatureId, @@ -666,7 +690,7 @@ HTMLWidgets.widget({ const featureState = { source: typeof layer.source === - "string" + "string" ? layer.source : layer.id, id: hoveredFeatureId, @@ -785,7 +809,7 @@ HTMLWidgets.widget({ // Add custom controls if any are defined if (x.custom_controls) { - Object.keys(x.custom_controls).forEach(function(key) { + Object.keys(x.custom_controls).forEach(function (key) { const controlOptions = x.custom_controls[key]; const customControlContainer = document.createElement("div"); @@ -798,10 +822,10 @@ HTMLWidgets.widget({ customControlContainer.innerHTML = controlOptions.html; const customControl = { - onAdd: function() { + onAdd: function () { return customControlContainer; }, - onRemove: function() { + onRemove: function () { if (customControlContainer.parentNode) { customControlContainer.parentNode.removeChild(customControlContainer); } @@ -834,7 +858,7 @@ HTMLWidgets.widget({ if (projectionConfig.projection) { const projection = typeof projectionConfig.projection === - "string" + "string" ? { type: projectionConfig.projection } : projectionConfig.projection; map.setProjection(projection); @@ -848,21 +872,20 @@ HTMLWidgets.widget({ forwardGeocode: async (config) => { const features = []; try { - const request = `https://nominatim.openstreetmap.org/search?q=${ - config.query - }&format=geojson&polygon_geojson=1&addressdetails=1`; + const request = `https://nominatim.openstreetmap.org/search?q=${config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; const response = await fetch(request); const geojson = await response.json(); for (const feature of geojson.features) { const center = [ feature.bbox[0] + - (feature.bbox[2] - - feature.bbox[0]) / - 2, + (feature.bbox[2] - + feature.bbox[0]) / + 2, feature.bbox[1] + - (feature.bbox[3] - - feature.bbox[1]) / - 2, + (feature.bbox[3] - + feature.bbox[1]) / + 2, ]; const point = { type: "Feature", @@ -996,7 +1019,7 @@ HTMLWidgets.widget({ // Process any queued features if (x.draw_features_queue) { - x.draw_features_queue.forEach(function(data) { + x.draw_features_queue.forEach(function (data) { if (data.clear_existing) { draw.deleteAll(); } @@ -1193,7 +1216,7 @@ HTMLWidgets.widget({ let initialView = {}; // Capture the initial view after the map has loaded and all view operations are complete - map.once('load', function() { + map.once('load', function () { initialView = { center: map.getCenter(), zoom: map.getZoom(), @@ -1510,36 +1533,36 @@ HTMLWidgets.widget({ // add hover listener for shinyMode if enabled if (x.hover_events && x.hover_events.enabled) { map.on("mousemove", function (e) { - // Feature hover events - if (x.hover_events.features) { - const features = map.queryRenderedFeatures(e.point); - - if(features.length > 0) { - const feature = features[0]; - Shiny.onInputChange(el.id + "_feature_hover", { - id: feature.id, - properties: feature.properties, - layer: feature.layer.id, - lng: e.lngLat.lng, - lat: e.lngLat.lat, - time: new Date(), - }); - } else { - Shiny.onInputChange( - el.id + "_feature_hover", - null, - ); - } - } + // Feature hover events + if (x.hover_events.features) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange( + el.id + "_feature_hover", + null, + ); + } + } - // Coordinate hover events - if (x.hover_events.coordinates) { - Shiny.onInputChange(el.id + "_hover", { - lng: e.lngLat.lng, - lat: e.lngLat.lat, - time: new Date(), - }); - } + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } }); } } @@ -1725,7 +1748,7 @@ if (HTMLWidgets.shinyMode) { const featureState = { source: typeof message.layer.source === - "string" + "string" ? message.layer.source : message.layer.id, id: hoveredFeatureId, @@ -1743,7 +1766,7 @@ if (HTMLWidgets.shinyMode) { const featureState = { source: typeof message.layer.source === - "string" + "string" ? message.layer.source : message.layer.id, id: hoveredFeatureId, @@ -1765,7 +1788,7 @@ if (HTMLWidgets.shinyMode) { const featureState = { source: typeof message.layer.source === - "string" + "string" ? message.layer.source : message.layer.id, id: hoveredFeatureId, @@ -1963,9 +1986,9 @@ if (HTMLWidgets.shinyMode) { var properties = features.map(f => f.properties); Shiny.setInputValue( - data.id + "_feature_query", + data.id + "_feature_query", JSON.stringify(properties), - {priority: "event"} + { priority: "event" } ); } else if (message.type === "query_source_features") { debugger; @@ -1975,9 +1998,9 @@ if (HTMLWidgets.shinyMode) { //var properties = features.map(f => f.properties); Shiny.setInputValue( - data.id + "_source_query", - JSON.stringify(features), - {priority: "event"} + data.id + "_source_query", + JSON.stringify(features), + { priority: "event" } ); } else if (message.type === "add_legend") { // Extract legend ID from HTML to track it @@ -2043,7 +2066,7 @@ if (HTMLWidgets.shinyMode) { const knownUserLayerIds = []; // For each layer in the current style, determine if it's a user-added layer - currentStyle.layers.forEach(function(layer) { + currentStyle.layers.forEach(function (layer) { const layerId = layer.id; // Critical: Check for nc_counties specifically since we know that's used in the test app @@ -2120,8 +2143,8 @@ if (HTMLWidgets.shinyMode) { } // Strategy 2: Check for source data URL patterns typical of R-generated data else if (source.url && typeof source.url === 'string' && - (source.url.includes("data:application/json") || - source.url.includes("blob:"))) { + (source.url.includes("data:application/json") || + source.url.includes("blob:"))) { console.log("[MapGL Debug] Found user source with data URL:", sourceId); if (!userSourceIds.includes(sourceId)) { userSourceIds.push(sourceId); @@ -2164,7 +2187,7 @@ if (HTMLWidgets.shinyMode) { // Identify layers using user-added sources or known user layer IDs // ONLY include layers that use genuinely user-added sources (not base map sources) - currentStyle.layers.forEach(function(layer) { + currentStyle.layers.forEach(function (layer) { // Check if this layer uses a genuine user source (not filtered out base map sources) const usesUserSource = userSourceIds.includes(layer.source); const isKnownUserLayer = knownUserLayerIds.includes(layer.id); @@ -2199,17 +2222,17 @@ if (HTMLWidgets.shinyMode) { window._mapglPreservedData = {}; } window._mapglPreservedData[map.getContainer().id] = { - sources: userSourceIds.map(id => ({id, source: currentStyle.sources[id]})), + sources: userSourceIds.map(id => ({ id, source: currentStyle.sources[id] })), layers: userLayers }; // Set up event listener to re-add sources and layers after style loads - const onStyleLoad = function() { + const onStyleLoad = function () { console.log("[MapGL Debug] style.load event fired"); try { // Re-add user sources - userSourceIds.forEach(function(sourceId) { + userSourceIds.forEach(function (sourceId) { try { if (!map.getSource(sourceId)) { const source = currentStyle.sources[sourceId]; @@ -2222,7 +2245,7 @@ if (HTMLWidgets.shinyMode) { }); // Re-add user layers - userLayers.forEach(function(layer) { + userLayers.forEach(function (layer) { try { if (!map.getLayer(layer.id)) { console.log("[MapGL Debug] Re-adding layer:", layer.id); @@ -2257,7 +2280,7 @@ if (HTMLWidgets.shinyMode) { // Re-add tooltip handlers const tooltipProperty = layer.tooltip || "NAME"; - const mouseMoveHandler = function(e) { + const mouseMoveHandler = function (e) { map.getCanvas().style.cursor = "pointer"; if (e.features.length > 0) { const description = e.features[0].properties[tooltipProperty]; @@ -2265,7 +2288,7 @@ if (HTMLWidgets.shinyMode) { } }; - const mouseLeaveHandler = function() { + const mouseLeaveHandler = function () { map.getCanvas().style.cursor = ""; tooltip.remove(); }; @@ -2419,7 +2442,7 @@ if (HTMLWidgets.shinyMode) { } // Create new popup handler - const clickHandler = function(e) { + const clickHandler = function (e) { onClickPopup(e, map, popupProperty, layerId); }; @@ -2484,7 +2507,7 @@ if (HTMLWidgets.shinyMode) { // Some MapLibre styles or versions may have different event timing if (userLayers.length > 0) { // Set a timeout to check if layers were added after a reasonable delay - setTimeout(function() { + setTimeout(function () { try { console.log("[MapGL Debug] Running backup layer check"); const mapId = map.getContainer().id; @@ -2497,7 +2520,7 @@ if (HTMLWidgets.shinyMode) { console.log("[MapGL Debug] Backup restoration needed for layers"); // Re-add sources first - preserved.sources.forEach(function(src) { + preserved.sources.forEach(function (src) { try { if (!map.getSource(src.id)) { console.log("[MapGL Debug] Backup: adding source", src.id); @@ -2509,7 +2532,7 @@ if (HTMLWidgets.shinyMode) { }); // Then re-add layers - preserved.layers.forEach(function(layer) { + preserved.layers.forEach(function (layer) { try { if (!map.getLayer(layer.id)) { console.log("[MapGL Debug] Backup: adding layer", layer.id); @@ -2528,7 +2551,7 @@ if (HTMLWidgets.shinyMode) { // Re-add tooltip handlers const tooltipProperty = "NAME"; - const mouseMoveHandler = function(e) { + const mouseMoveHandler = function (e) { map.getCanvas().style.cursor = "pointer"; if (e.features.length > 0) { const description = e.features[0].properties[tooltipProperty]; @@ -2536,7 +2559,7 @@ if (HTMLWidgets.shinyMode) { } }; - const mouseLeaveHandler = function() { + const mouseLeaveHandler = function () { map.getCanvas().style.cursor = ""; tooltip.remove(); }; @@ -2677,7 +2700,7 @@ if (HTMLWidgets.shinyMode) { map.off("click", layerId, window._mapboxClickHandlers[layerId]); } - const clickHandler = function(e) { + const clickHandler = function (e) { onClickPopup(e, map, popupProperty, layerId); }; @@ -2738,7 +2761,7 @@ if (HTMLWidgets.shinyMode) { }, 500); // 500ms delay - faster recovery // Add a second backup with a bit more delay in case the first one fails - setTimeout(function() { + setTimeout(function () { try { console.log("[MapGL Debug] Running second backup layer check"); const mapId = map.getContainer().id; @@ -2751,7 +2774,7 @@ if (HTMLWidgets.shinyMode) { console.log("[MapGL Debug] Second backup restoration needed"); // Re-add sources first - preserved.sources.forEach(function(src) { + preserved.sources.forEach(function (src) { try { if (!map.getSource(src.id)) { console.log("[MapGL Debug] Second backup: adding source", src.id); @@ -2763,7 +2786,7 @@ if (HTMLWidgets.shinyMode) { }); // Then re-add layers - preserved.layers.forEach(function(layer) { + preserved.layers.forEach(function (layer) { try { if (!map.getLayer(layer.id)) { console.log("[MapGL Debug] Second backup: adding layer", layer.id); @@ -2782,7 +2805,7 @@ if (HTMLWidgets.shinyMode) { // Re-add tooltip handlers const tooltipProperty = "NAME"; - const mouseMoveHandler = function(e) { + const mouseMoveHandler = function (e) { map.getCanvas().style.cursor = "pointer"; if (e.features.length > 0) { const description = e.features[0].properties[tooltipProperty]; @@ -2790,7 +2813,7 @@ if (HTMLWidgets.shinyMode) { } }; - const mouseLeaveHandler = function() { + const mouseLeaveHandler = function () { map.getCanvas().style.cursor = ""; tooltip.remove(); }; @@ -2931,7 +2954,7 @@ if (HTMLWidgets.shinyMode) { map.off("click", layerId, window._mapboxClickHandlers[layerId]); } - const clickHandler = function(e) { + const clickHandler = function (e) { onClickPopup(e, map, popupProperty, layerId); }; @@ -3295,17 +3318,16 @@ if (HTMLWidgets.shinyMode) { forwardGeocode: async (config) => { const features = []; try { - const request = `https://nominatim.openstreetmap.org/search?q=${ - config.query - }&format=geojson&polygon_geojson=1&addressdetails=1`; + const request = `https://nominatim.openstreetmap.org/search?q=${config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; const response = await fetch(request); const geojson = await response.json(); for (const feature of geojson.features) { const center = [ feature.bbox[0] + - (feature.bbox[2] - feature.bbox[0]) / 2, + (feature.bbox[2] - feature.bbox[0]) / 2, feature.bbox[1] + - (feature.bbox[3] - feature.bbox[1]) / 2, + (feature.bbox[3] - feature.bbox[1]) / 2, ]; const point = { type: "Feature", @@ -3782,10 +3804,10 @@ if (HTMLWidgets.shinyMode) { customControlContainer.innerHTML = controlOptions.html; const customControl = { - onAdd: function() { + onAdd: function () { return customControlContainer; }, - onRemove: function() { + onRemove: function () { if (customControlContainer.parentNode) { customControlContainer.parentNode.removeChild(customControlContainer); } From 0856dd29b6a6a55c1c6cd0df0c2968eef098a5ff Mon Sep 17 00:00:00 2001 From: kmcd39 Date: Wed, 18 Jun 2025 14:51:13 -0400 Subject: [PATCH 5/8] remembering to export functions --- NAMESPACE | 3 +++ man/enable_shiny_hover.Rd | 2 +- man/enable_shiny_viewport_features.Rd | 17 +++++++++++++++++ man/update_feature_query.Rd | 23 +++++++++++++++++++++++ man/update_source_query.Rd | 25 +++++++++++++++++++++++++ 5 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 man/enable_shiny_viewport_features.Rd create mode 100644 man/update_feature_query.Rd create mode 100644 man/update_source_query.Rd diff --git a/NAMESPACE b/NAMESPACE index 47e6f12..f9fcbfc 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -45,6 +45,7 @@ export(compare) export(concat) export(ease_to) export(enable_shiny_hover) +export(enable_shiny_viewport_features) export(fit_bounds) export(fly_to) export(get_breaks) @@ -74,6 +75,7 @@ export(match_expr) export(move_layer) export(number_format) export(on_section) +export(query_rendered_features) export(renderMapboxgl) export(renderMapboxglCompare) export(renderMaplibre) @@ -100,6 +102,7 @@ export(story_leaflet) export(story_map) export(story_maplibre) export(story_section) +export(update_source_query) import(base64enc) import(geojsonsf) import(grDevices) diff --git a/man/enable_shiny_hover.Rd b/man/enable_shiny_hover.Rd index da67b31..2a6e21b 100644 --- a/man/enable_shiny_hover.Rd +++ b/man/enable_shiny_hover.Rd @@ -35,7 +35,7 @@ server <- function(input, output) { maplibre() |> enable_shiny_hover() }) - + output$hover_info <- renderText({ paste("Mouse at:", input$map_hover$lng, input$map_hover$lat) }) diff --git a/man/enable_shiny_viewport_features.Rd b/man/enable_shiny_viewport_features.Rd new file mode 100644 index 0000000..1efc7fb --- /dev/null +++ b/man/enable_shiny_viewport_features.Rd @@ -0,0 +1,17 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/hover.R +\name{enable_shiny_viewport_features} +\alias{enable_shiny_viewport_features} +\title{Enable features in viewport automatically updating shiny inputs} +\usage{ +enable_shiny_viewport_features(map, layer_id) +} +\value{ +The modified map object with automatic querying of viewport features +enabled. +} +\description{ +This function causes a map widget in shiny to automatically refresh a shiny +input \verb{_bbox_features} with all features for the given layer in the bounding +box of the map's viewport. +} diff --git a/man/update_feature_query.Rd b/man/update_feature_query.Rd new file mode 100644 index 0000000..a79b5a7 --- /dev/null +++ b/man/update_feature_query.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/shiny.R +\name{update_feature_query} +\alias{update_feature_query} +\title{Get a set of features on a map} +\usage{ +update_feature_query(map, layer_id = NULL, geometry = NULL) +} +\arguments{ +\item{layer_id}{layer_id of map layer from which to query features.} + +\item{geometry}{if NULL, uses the bbox of the current viewport. Otherwise, a +specific geometry can be specified to pull features overlapping that +geometry. + +See \link[=https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#queryrenderedfeatures]{queryrenderedfeatures}} +} +\value{ +Nothing, but updates \code{input$map_feature_query} +} +\description{ +Get a set of features on a map +} diff --git a/man/update_source_query.Rd b/man/update_source_query.Rd new file mode 100644 index 0000000..1976ed4 --- /dev/null +++ b/man/update_source_query.Rd @@ -0,0 +1,25 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/shiny.R +\name{update_source_query} +\alias{update_source_query} +\title{Queries all features in a source} +\usage{ +update_source_query(map, source_id, source_layer = NULL) +} +\arguments{ +\item{source_id}{id of source layer for which to query features. Note the +returned features will be empty if this is left NULL and query is refering +to a basemap layer. + +See +\link[=https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#querysourcefeatures]{querySourceFeatures}} + +\item{layer_id}{layer_id of map layer from which to query features.} +} +\value{ +Nothing, but updates \code{input$map_source_query} in shiny contexts. +} +\description{ +Will pull all features (visible or not) from a given source and save as a +shiny input +} From 8421b6f424d231308531cb3afcfa25ffbf7c6462 Mon Sep 17 00:00:00 2001 From: kmcd39 Date: Wed, 18 Jun 2025 14:51:13 -0400 Subject: [PATCH 6/8] remembering to export functions --- NAMESPACE | 3 +++ R/shiny.R | 4 ++-- man/enable_shiny_hover.Rd | 2 +- man/enable_shiny_viewport_features.Rd | 17 +++++++++++++++++ man/update_feature_query.Rd | 23 +++++++++++++++++++++++ man/update_source_query.Rd | 25 +++++++++++++++++++++++++ 6 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 man/enable_shiny_viewport_features.Rd create mode 100644 man/update_feature_query.Rd create mode 100644 man/update_source_query.Rd diff --git a/NAMESPACE b/NAMESPACE index 47e6f12..3c0be67 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -45,6 +45,7 @@ export(compare) export(concat) export(ease_to) export(enable_shiny_hover) +export(enable_shiny_viewport_features) export(fit_bounds) export(fly_to) export(get_breaks) @@ -100,6 +101,8 @@ export(story_leaflet) export(story_map) export(story_maplibre) export(story_section) +export(update_feature_query) +export(update_source_query) import(base64enc) import(geojsonsf) import(grDevices) diff --git a/R/shiny.R b/R/shiny.R index db4b03b..974a4be 100644 --- a/R/shiny.R +++ b/R/shiny.R @@ -670,11 +670,11 @@ set_source <- function(map, layer_id = NULL, source, layer = NULL) { #' See [queryrenderedfeatures][https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#queryrenderedfeatures] #' #' @return Nothing, but updates `input$map_feature_query` -#' @export query_rendered_features +#' @export update_feature_query #' -#query_rendered_features <- function(map, layer_id = NULL, geometry = NULL) { update_feature_query <- function(map, layer_id = NULL, geometry = NULL ) { + #query_rendered_features <- function(map, layer_id = NULL, geometry = NULL) { #browser() if( !(inherits(map, "mapboxgl_proxy") || inherits(map, "maplibre_proxy")) ) { diff --git a/man/enable_shiny_hover.Rd b/man/enable_shiny_hover.Rd index da67b31..2a6e21b 100644 --- a/man/enable_shiny_hover.Rd +++ b/man/enable_shiny_hover.Rd @@ -35,7 +35,7 @@ server <- function(input, output) { maplibre() |> enable_shiny_hover() }) - + output$hover_info <- renderText({ paste("Mouse at:", input$map_hover$lng, input$map_hover$lat) }) diff --git a/man/enable_shiny_viewport_features.Rd b/man/enable_shiny_viewport_features.Rd new file mode 100644 index 0000000..1efc7fb --- /dev/null +++ b/man/enable_shiny_viewport_features.Rd @@ -0,0 +1,17 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/hover.R +\name{enable_shiny_viewport_features} +\alias{enable_shiny_viewport_features} +\title{Enable features in viewport automatically updating shiny inputs} +\usage{ +enable_shiny_viewport_features(map, layer_id) +} +\value{ +The modified map object with automatic querying of viewport features +enabled. +} +\description{ +This function causes a map widget in shiny to automatically refresh a shiny +input \verb{_bbox_features} with all features for the given layer in the bounding +box of the map's viewport. +} diff --git a/man/update_feature_query.Rd b/man/update_feature_query.Rd new file mode 100644 index 0000000..a79b5a7 --- /dev/null +++ b/man/update_feature_query.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/shiny.R +\name{update_feature_query} +\alias{update_feature_query} +\title{Get a set of features on a map} +\usage{ +update_feature_query(map, layer_id = NULL, geometry = NULL) +} +\arguments{ +\item{layer_id}{layer_id of map layer from which to query features.} + +\item{geometry}{if NULL, uses the bbox of the current viewport. Otherwise, a +specific geometry can be specified to pull features overlapping that +geometry. + +See \link[=https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#queryrenderedfeatures]{queryrenderedfeatures}} +} +\value{ +Nothing, but updates \code{input$map_feature_query} +} +\description{ +Get a set of features on a map +} diff --git a/man/update_source_query.Rd b/man/update_source_query.Rd new file mode 100644 index 0000000..1976ed4 --- /dev/null +++ b/man/update_source_query.Rd @@ -0,0 +1,25 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/shiny.R +\name{update_source_query} +\alias{update_source_query} +\title{Queries all features in a source} +\usage{ +update_source_query(map, source_id, source_layer = NULL) +} +\arguments{ +\item{source_id}{id of source layer for which to query features. Note the +returned features will be empty if this is left NULL and query is refering +to a basemap layer. + +See +\link[=https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#querysourcefeatures]{querySourceFeatures}} + +\item{layer_id}{layer_id of map layer from which to query features.} +} +\value{ +Nothing, but updates \code{input$map_source_query} in shiny contexts. +} +\description{ +Will pull all features (visible or not) from a given source and save as a +shiny input +} From 6fae735fee247165281f3aeff454a4bd35ecb13a Mon Sep 17 00:00:00 2001 From: kmcd39 Date: Wed, 25 Jun 2025 11:36:32 -0400 Subject: [PATCH 7/8] added layer argument for hover options --- R/hover.R | 14 +++++++++++--- inst/htmlwidgets/maplibregl.js | 4 +++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/R/hover.R b/R/hover.R index ab0a0b6..52c817f 100644 --- a/R/hover.R +++ b/R/hover.R @@ -4,8 +4,12 @@ #' in Shiny applications, providing `_hover` and `_feature_hover` input values. #' #' @param map A maplibre or mapboxgl widget object. -#' @param coordinates Logical. If TRUE, provides general mouse coordinates via `_hover` input. Defaults to TRUE. -#' @param features Logical. If TRUE, provides feature information via `_feature_hover` input when hovering over map features. Defaults to TRUE. +#' @param layer_id the layer id for which to retrieve hovered features, if +#' features is enabled. If NULL, will return features for all layers. +#' @param coordinates Logical. If TRUE, provides general mouse coordinates via +#' `_hover` input. Defaults to TRUE. +#' @param features Logical. If TRUE, provides feature information via +#' `_feature_hover` input when hovering over map features. Defaults to TRUE. #' #' @return The modified map object with hover events enabled. #' @export @@ -33,7 +37,10 @@ #' #' shinyApp(ui, server) #' } -enable_shiny_hover <- function(map, coordinates = TRUE, features = TRUE) { +enable_shiny_hover <- function(map, + layer_id = NULL, + coordinates = TRUE, + features = TRUE) { # Check if map is valid if (!inherits(map, c("maplibregl", "mapboxgl"))) { @@ -46,6 +53,7 @@ enable_shiny_hover <- function(map, coordinates = TRUE, features = TRUE) { } map$x$hover_events$enabled <- TRUE + map$x$hover_events$layer_id <- layer_id map$x$hover_events$coordinates <- coordinates map$x$hover_events$features <- features diff --git a/inst/htmlwidgets/maplibregl.js b/inst/htmlwidgets/maplibregl.js index af6b946..c31348b 100644 --- a/inst/htmlwidgets/maplibregl.js +++ b/inst/htmlwidgets/maplibregl.js @@ -1535,7 +1535,9 @@ HTMLWidgets.widget({ map.on("mousemove", function (e) { // Feature hover events if (x.hover_events.features) { - const features = map.queryRenderedFeatures(e.point); + + const options = x.hover_events.layer_id ? { layers: [x.hover_events.layer_id] } : undefined; + const features = map.queryRenderedFeatures(e.point, options); if (features.length > 0) { const feature = features[0]; From c4c967dafa74aebd5e59ab6ee8986f48c65277cd Mon Sep 17 00:00:00 2001 From: Kira M Date: Fri, 17 Oct 2025 14:37:28 -0400 Subject: [PATCH 8/8] other updates from upstream main? --- .../pmtiles-source-optimized-v2.js | 1102 ++++ .../mapbox-pmtiles-1.1.0/pmtiles-source.js | 459 ++ .../mapboxgl.js | 342 +- .../mapboxgl-binding-0.3.2}/mapboxgl.js | 416 +- .../mapboxgl-binding-0.3.9.9000/mapboxgl.js | 3249 +++++++++++ .../mapboxgl-binding-0.4.0.9000/mapboxgl.js | 3418 +++++++++++ .../mapboxgl-binding-0.4.0/mapboxgl.js | 3249 +++++++++++ .../mapboxgl-binding-0.4.1/mapboxgl.js | 3910 +++++++++++++ .../LICENSE.txt | 0 .../maplibre-gl-5.7.2/maplibre-gl.css | 1 + .../maplibre-gl-5.7.2/maplibre-gl.js | 59 + .../maplibregl.js | 4285 ++++++++++++++ .../maplibregl-binding-0.3.2/maplibregl.js | 4285 ++++++++++++++ .../maplibregl.js | 4337 ++++++++++++++ .../maplibregl.js | 4506 +++++++++++++++ .../maplibregl-binding-0.4.0/maplibregl.js | 4337 ++++++++++++++ .../maplibregl-binding-0.4.1/maplibregl.js | 5048 +++++++++++++++++ .../LICENSE.txt | 29 + .../maplibregl.umd.js | 14 + .../style.css | 1 + .../radius-mode-1.0.0/radius-mode.js | 311 + .../rectangle-mode-1.0.0/rectangle-mode.js | 124 + .../turf-7.2.0/turf.min.js | 37 + .../lib/freehand-mode/freehand-mode.js | 207 + .../lib/h3j-h3t/h3j_h3t.js | 3 + .../lib/mapbox-gl-draw/mapbox-gl-draw.css | 88 + .../lib/mapbox-gl-draw/mapbox-gl-draw.js | 2 + .../lib/mapbox-gl-globe-minimap/bundle.js | 1 + .../pmtiles-source-optimized-v2.js | 1102 ++++ .../lib/mapbox-pmtiles/pmtiles-source.js | 459 ++ .../maplibre-gl-compare.css | 44 + .../maplibre-gl-compare.js | 1 + .../maplibre-gl-geocoder.css | 284 + .../maplibre-gl-geocoder.min.js | 2 + .../lib/maplibre-gl}/LICENSE.txt | 0 .../lib/maplibre-gl/maplibre-gl.css | 1 + .../lib/maplibre-gl/maplibre-gl.js | 59 + .../maptiler-geocoding-control/LICENSE.txt | 29 + .../maplibregl.umd.js | 14 + .../lib/maptiler-geocoding-control/style.css | 1 + .../lib/pmtiles/pmtiles.js | 2 + .../lib/radius-mode/radius-mode.js | 311 + .../lib/rectangle-mode/rectangle-mode.js | 124 + .../lib/turf/turf.min.js | 37 + .../turf-operations-1.0.0/mapboxgl.js | 3910 +++++++++++++ .../turf-operations-1.0.0/mapboxgl.yaml | 65 + .../turf-operations-1.0.0/mapboxgl_compare.js | 3192 +++++++++++ .../mapboxgl_compare.yaml | 57 + .../turf-operations-1.0.0/maplibregl.js | 5048 +++++++++++++++++ .../turf-operations-1.0.0/maplibregl.yaml | 69 + .../maplibregl_compare.js | 4138 ++++++++++++++ .../maplibregl_compare.yaml | 67 + .../styles/filter-control.css | 65 + .../styles/layers-control.css | 123 + .../turf-operations-1.0.0/turf-operations.js | 967 ++++ .../pmtiles-source-optimized-v2.js | 1102 ++++ .../mapbox-pmtiles-1.1.0/pmtiles-source.js | 459 ++ .../mapboxgl-binding-0.3.1.9000}/mapboxgl.js | 342 +- .../mapboxgl-binding-0.3.2/mapboxgl.js | 3197 +++++++++++ .../mapboxgl-binding-0.3.9.9000/mapboxgl.js | 3249 +++++++++++ .../mapboxgl-binding-0.4.0.9000/mapboxgl.js | 3418 +++++++++++ .../mapboxgl-binding-0.4.0/mapboxgl.js | 3249 +++++++++++ .../mapboxgl-binding-0.4.1/mapboxgl.js | 3910 +++++++++++++ .../maplibre-gl-5.7.2}/LICENSE.txt | 0 .../maplibre-gl-5.7.2/maplibre-gl.css | 1 + .../maplibre-gl-5.7.2/maplibre-gl.js | 59 + .../maplibregl.js | 4285 ++++++++++++++ .../maplibregl-binding-0.3.2/maplibregl.js | 4285 ++++++++++++++ .../maplibregl.js | 4337 ++++++++++++++ .../maplibregl.js | 4506 +++++++++++++++ .../maplibregl-binding-0.4.0/maplibregl.js | 4337 ++++++++++++++ .../maplibregl-binding-0.4.1/maplibregl.js | 5048 +++++++++++++++++ .../LICENSE.txt | 29 + .../maplibregl.umd.js | 14 + .../style.css | 1 + .../radius-mode-1.0.0/radius-mode.js | 311 + .../rectangle-mode-1.0.0/rectangle-mode.js | 124 + .../turf-7.2.0/turf.min.js | 37 + .../lib/freehand-mode/freehand-mode.js | 207 + .../lib/h3j-h3t/h3j_h3t.js | 3 + .../lib/mapbox-gl-draw/mapbox-gl-draw.css | 88 + .../lib/mapbox-gl-draw/mapbox-gl-draw.js | 2 + .../lib/mapbox-gl-globe-minimap/bundle.js | 1 + .../pmtiles-source-optimized-v2.js | 1102 ++++ .../lib/mapbox-pmtiles/pmtiles-source.js | 459 ++ .../maplibre-gl-compare.css | 44 + .../maplibre-gl-compare.js | 1 + .../maplibre-gl-geocoder.css | 284 + .../maplibre-gl-geocoder.min.js | 2 + .../lib/maplibre-gl}/LICENSE.txt | 0 .../lib/maplibre-gl/maplibre-gl.css | 1 + .../lib/maplibre-gl/maplibre-gl.js | 59 + .../maptiler-geocoding-control/LICENSE.txt | 29 + .../maplibregl.umd.js | 14 + .../lib/maptiler-geocoding-control/style.css | 1 + .../lib/pmtiles/pmtiles.js | 2 + .../lib/radius-mode/radius-mode.js | 311 + .../lib/rectangle-mode/rectangle-mode.js | 124 + .../lib/turf/turf.min.js | 37 + .../turf-operations-1.0.0/mapboxgl.js | 3910 +++++++++++++ .../turf-operations-1.0.0/mapboxgl.yaml | 65 + .../turf-operations-1.0.0/mapboxgl_compare.js | 3192 +++++++++++ .../mapboxgl_compare.yaml | 57 + .../turf-operations-1.0.0/maplibregl.js | 5048 +++++++++++++++++ .../turf-operations-1.0.0/maplibregl.yaml | 69 + .../maplibregl_compare.js | 4138 ++++++++++++++ .../maplibregl_compare.yaml | 67 + .../styles/filter-control.css | 65 + .../styles/layers-control.css | 123 + .../turf-operations-1.0.0/turf-operations.js | 967 ++++ .../pmtiles-source-optimized-v2.js | 1102 ++++ .../mapbox-pmtiles-1.1.0/pmtiles-source.js | 459 ++ .../mapboxgl-binding-0.3.1.9000}/mapboxgl.js | 342 +- .../mapboxgl-binding-0.3.2/mapboxgl.js | 3197 +++++++++++ .../mapboxgl-binding-0.3.9.9000/mapboxgl.js | 3249 +++++++++++ .../mapboxgl-binding-0.4.0.9000/mapboxgl.js | 3418 +++++++++++ .../mapboxgl-binding-0.4.0/mapboxgl.js | 3249 +++++++++++ .../mapboxgl-binding-0.4.1/mapboxgl.js | 3910 +++++++++++++ .../map-design_files/pmtiles-4.3.0/pmtiles.js | 2 + .../radius-mode-1.0.0/radius-mode.js | 311 + .../rectangle-mode-1.0.0/rectangle-mode.js | 124 + .../map-design_files/turf-7.2.0/turf.min.js | 37 + .../lib/freehand-mode/freehand-mode.js | 207 + .../lib/h3j-h3t/h3j_h3t.js | 3 + .../lib/mapbox-gl-draw/mapbox-gl-draw.css | 88 + .../lib/mapbox-gl-draw/mapbox-gl-draw.js | 2 + .../lib/mapbox-gl-globe-minimap/bundle.js | 1 + .../pmtiles-source-optimized-v2.js | 1102 ++++ .../lib/mapbox-pmtiles/pmtiles-source.js | 459 ++ .../maplibre-gl-compare.css | 44 + .../maplibre-gl-compare.js | 1 + .../maplibre-gl-geocoder.css | 284 + .../maplibre-gl-geocoder.min.js | 2 + .../lib/maplibre-gl}/LICENSE.txt | 0 .../lib/maplibre-gl/maplibre-gl.css | 1 + .../lib/maplibre-gl/maplibre-gl.js | 59 + .../maptiler-geocoding-control/LICENSE.txt | 29 + .../maplibregl.umd.js | 14 + .../lib/maptiler-geocoding-control/style.css | 1 + .../lib/pmtiles/pmtiles.js | 2 + .../lib/radius-mode/radius-mode.js | 311 + .../lib/rectangle-mode/rectangle-mode.js | 124 + .../lib/turf/turf.min.js | 37 + .../turf-operations-1.0.0/mapboxgl.js | 3910 +++++++++++++ .../turf-operations-1.0.0/mapboxgl.yaml | 65 + .../turf-operations-1.0.0/mapboxgl_compare.js | 3192 +++++++++++ .../mapboxgl_compare.yaml | 57 + .../turf-operations-1.0.0/maplibregl.js | 5048 +++++++++++++++++ .../turf-operations-1.0.0/maplibregl.yaml | 69 + .../maplibregl_compare.js | 4138 ++++++++++++++ .../maplibregl_compare.yaml | 67 + .../styles/filter-control.css | 65 + .../styles/layers-control.css | 123 + .../turf-operations-1.0.0/turf-operations.js | 967 ++++ .../freehand-mode-1.0.0/freehand-mode.js | 207 + .../turf_files/h3j-h3t-0.9.2/h3j_h3t.js | 3 + .../htmlwidgets-1.6.4/htmlwidgets.js | 901 +++ .../layers-control-1.0.0/filter-control.css | 65 + .../layers-control-1.0.0/layers-control.css | 123 + .../mapbox-gl-draw-1.5.0/mapbox-gl-draw.css | 88 + .../mapbox-gl-draw-1.5.0/mapbox-gl-draw.js | 2 + .../mapbox-gl-globe-minimap-1.2.1/bundle.js | 1 + .../maplibre-gl-5.6.0}/LICENSE.txt | 0 .../maplibre-gl-5.6.0}/maplibre-gl.css | 0 .../maplibre-gl-5.6.0/maplibre-gl.js | 59 + .../maplibre-gl-5.7.2}/LICENSE.txt | 0 .../maplibre-gl-5.7.2/maplibre-gl.css | 1 + .../maplibre-gl-5.7.2/maplibre-gl.js | 59 + .../maplibre-gl-geocoder.css | 284 + .../maplibre-gl-geocoder.min.js | 2 + .../maplibregl.js | 4337 ++++++++++++++ .../maplibregl.js | 4506 +++++++++++++++ .../maplibregl-binding-0.4.0/maplibregl.js | 4337 ++++++++++++++ .../maplibregl-binding-0.4.1/maplibregl.js | 5048 +++++++++++++++++ .../LICENSE.txt | 29 + .../maplibregl.umd.js | 14 + .../style.css | 1 + .../turf_files/pmtiles-4.3.0/pmtiles.js | 2 + .../radius-mode-1.0.0/radius-mode.js | 311 + .../rectangle-mode-1.0.0/rectangle-mode.js | 124 + .../turf_files/turf-7.2.0/turf.min.js | 37 + .../lib/freehand-mode/freehand-mode.js | 207 + .../lib/h3j-h3t/h3j_h3t.js | 3 + .../lib/mapbox-gl-draw/mapbox-gl-draw.css | 88 + .../lib/mapbox-gl-draw/mapbox-gl-draw.js | 2 + .../lib/mapbox-gl-globe-minimap/bundle.js | 1 + .../pmtiles-source-optimized-v2.js | 1102 ++++ .../lib/mapbox-pmtiles/pmtiles-source.js | 459 ++ .../maplibre-gl-compare.css | 44 + .../maplibre-gl-compare.js | 1 + .../maplibre-gl-geocoder.css | 284 + .../maplibre-gl-geocoder.min.js | 2 + .../lib/maplibre-gl}/LICENSE.txt | 0 .../lib/maplibre-gl/maplibre-gl.css | 1 + .../lib/maplibre-gl/maplibre-gl.js | 59 + .../maptiler-geocoding-control/LICENSE.txt | 29 + .../maplibregl.umd.js | 14 + .../lib/maptiler-geocoding-control/style.css | 1 + .../lib/pmtiles/pmtiles.js | 2 + .../lib/radius-mode/radius-mode.js | 311 + .../lib/rectangle-mode/rectangle-mode.js | 124 + .../lib/turf/turf.min.js | 37 + .../turf-operations-1.0.0/mapboxgl.js | 3910 +++++++++++++ .../turf-operations-1.0.0/mapboxgl.yaml | 65 + .../turf-operations-1.0.0/mapboxgl_compare.js | 3192 +++++++++++ .../mapboxgl_compare.yaml | 57 + .../turf-operations-1.0.0/maplibregl.js | 5048 +++++++++++++++++ .../turf-operations-1.0.0/maplibregl.yaml | 69 + .../maplibregl_compare.js | 4138 ++++++++++++++ .../maplibregl_compare.yaml | 67 + .../styles/filter-control.css | 65 + .../styles/layers-control.css | 123 + .../turf-operations-1.0.0/turf-operations.js | 967 ++++ .../pmtiles-source-optimized-v2.js | 1102 ++++ .../lib/mapbox-pmtiles/pmtiles-source.js | 459 ++ .../maptiler-geocoding-control/LICENSE.txt | 29 + .../maplibregl.umd.js | 14 + .../lib/maptiler-geocoding-control/style.css | 1 + .../lib/radius-mode/radius-mode.js | 311 + .../lib/rectangle-mode/rectangle-mode.js | 124 + inst/htmlwidgets/lib/turf/turf.min.js | 37 + 221 files changed, 213515 insertions(+), 210 deletions(-) create mode 100644 docs/articles/getting-started_files/mapbox-pmtiles-1.1.0/pmtiles-source-optimized-v2.js create mode 100644 docs/articles/getting-started_files/mapbox-pmtiles-1.1.0/pmtiles-source.js rename docs/articles/getting-started_files/{mapboxgl-binding-0.2.9.9000 => mapboxgl-binding-0.3.1.9000}/mapboxgl.js (89%) rename docs/articles/{layers-overview_files/mapboxgl-binding-0.3 => getting-started_files/mapboxgl-binding-0.3.2}/mapboxgl.js (88%) create mode 100644 docs/articles/getting-started_files/mapboxgl-binding-0.3.9.9000/mapboxgl.js create mode 100644 docs/articles/getting-started_files/mapboxgl-binding-0.4.0.9000/mapboxgl.js create mode 100644 docs/articles/getting-started_files/mapboxgl-binding-0.4.0/mapboxgl.js create mode 100644 docs/articles/getting-started_files/mapboxgl-binding-0.4.1/mapboxgl.js rename docs/articles/getting-started_files/{maplibre-gl-4.4.1 => maplibre-gl-5.7.2}/LICENSE.txt (100%) create mode 100644 docs/articles/getting-started_files/maplibre-gl-5.7.2/maplibre-gl.css create mode 100644 docs/articles/getting-started_files/maplibre-gl-5.7.2/maplibre-gl.js create mode 100644 docs/articles/getting-started_files/maplibregl-binding-0.3.1.9000/maplibregl.js create mode 100644 docs/articles/getting-started_files/maplibregl-binding-0.3.2/maplibregl.js create mode 100644 docs/articles/getting-started_files/maplibregl-binding-0.3.9.9000/maplibregl.js create mode 100644 docs/articles/getting-started_files/maplibregl-binding-0.4.0.9000/maplibregl.js create mode 100644 docs/articles/getting-started_files/maplibregl-binding-0.4.0/maplibregl.js create mode 100644 docs/articles/getting-started_files/maplibregl-binding-0.4.1/maplibregl.js create mode 100644 docs/articles/getting-started_files/maptiler-geocoding-control-2.1.7/LICENSE.txt create mode 100644 docs/articles/getting-started_files/maptiler-geocoding-control-2.1.7/maplibregl.umd.js create mode 100644 docs/articles/getting-started_files/maptiler-geocoding-control-2.1.7/style.css create mode 100644 docs/articles/getting-started_files/radius-mode-1.0.0/radius-mode.js create mode 100644 docs/articles/getting-started_files/rectangle-mode-1.0.0/rectangle-mode.js create mode 100644 docs/articles/getting-started_files/turf-7.2.0/turf.min.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.css create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js rename docs/articles/getting-started_files/{maplibre-gl-4.6.0 => turf-operations-1.0.0/lib/maplibre-gl}/LICENSE.txt (100%) create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.css create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/lib/turf/turf.min.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl.yaml create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl_compare.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl_compare.yaml create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl.yaml create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl_compare.js create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl_compare.yaml create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/styles/filter-control.css create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/styles/layers-control.css create mode 100644 docs/articles/getting-started_files/turf-operations-1.0.0/turf-operations.js create mode 100644 docs/articles/layers-overview_files/mapbox-pmtiles-1.1.0/pmtiles-source-optimized-v2.js create mode 100644 docs/articles/layers-overview_files/mapbox-pmtiles-1.1.0/pmtiles-source.js rename docs/articles/{getting-started_files/mapboxgl-binding-0.3 => layers-overview_files/mapboxgl-binding-0.3.1.9000}/mapboxgl.js (89%) create mode 100644 docs/articles/layers-overview_files/mapboxgl-binding-0.3.2/mapboxgl.js create mode 100644 docs/articles/layers-overview_files/mapboxgl-binding-0.3.9.9000/mapboxgl.js create mode 100644 docs/articles/layers-overview_files/mapboxgl-binding-0.4.0.9000/mapboxgl.js create mode 100644 docs/articles/layers-overview_files/mapboxgl-binding-0.4.0/mapboxgl.js create mode 100644 docs/articles/layers-overview_files/mapboxgl-binding-0.4.1/mapboxgl.js rename docs/articles/{getting-started_files/maplibre-gl-4.7.1 => layers-overview_files/maplibre-gl-5.7.2}/LICENSE.txt (100%) create mode 100644 docs/articles/layers-overview_files/maplibre-gl-5.7.2/maplibre-gl.css create mode 100644 docs/articles/layers-overview_files/maplibre-gl-5.7.2/maplibre-gl.js create mode 100644 docs/articles/layers-overview_files/maplibregl-binding-0.3.1.9000/maplibregl.js create mode 100644 docs/articles/layers-overview_files/maplibregl-binding-0.3.2/maplibregl.js create mode 100644 docs/articles/layers-overview_files/maplibregl-binding-0.3.9.9000/maplibregl.js create mode 100644 docs/articles/layers-overview_files/maplibregl-binding-0.4.0.9000/maplibregl.js create mode 100644 docs/articles/layers-overview_files/maplibregl-binding-0.4.0/maplibregl.js create mode 100644 docs/articles/layers-overview_files/maplibregl-binding-0.4.1/maplibregl.js create mode 100644 docs/articles/layers-overview_files/maptiler-geocoding-control-2.1.7/LICENSE.txt create mode 100644 docs/articles/layers-overview_files/maptiler-geocoding-control-2.1.7/maplibregl.umd.js create mode 100644 docs/articles/layers-overview_files/maptiler-geocoding-control-2.1.7/style.css create mode 100644 docs/articles/layers-overview_files/radius-mode-1.0.0/radius-mode.js create mode 100644 docs/articles/layers-overview_files/rectangle-mode-1.0.0/rectangle-mode.js create mode 100644 docs/articles/layers-overview_files/turf-7.2.0/turf.min.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.css create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js rename docs/articles/{getting-started_files/maplibre-gl-5.0.0 => layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl}/LICENSE.txt (100%) create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.css create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/lib/turf/turf.min.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl.yaml create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl_compare.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl_compare.yaml create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl.yaml create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl_compare.js create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl_compare.yaml create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/styles/filter-control.css create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/styles/layers-control.css create mode 100644 docs/articles/layers-overview_files/turf-operations-1.0.0/turf-operations.js create mode 100644 docs/articles/map-design_files/mapbox-pmtiles-1.1.0/pmtiles-source-optimized-v2.js create mode 100644 docs/articles/map-design_files/mapbox-pmtiles-1.1.0/pmtiles-source.js rename docs/articles/{layers-overview_files/mapboxgl-binding-0.2.9.9000 => map-design_files/mapboxgl-binding-0.3.1.9000}/mapboxgl.js (89%) create mode 100644 docs/articles/map-design_files/mapboxgl-binding-0.3.2/mapboxgl.js create mode 100644 docs/articles/map-design_files/mapboxgl-binding-0.3.9.9000/mapboxgl.js create mode 100644 docs/articles/map-design_files/mapboxgl-binding-0.4.0.9000/mapboxgl.js create mode 100644 docs/articles/map-design_files/mapboxgl-binding-0.4.0/mapboxgl.js create mode 100644 docs/articles/map-design_files/mapboxgl-binding-0.4.1/mapboxgl.js create mode 100644 docs/articles/map-design_files/pmtiles-4.3.0/pmtiles.js create mode 100644 docs/articles/map-design_files/radius-mode-1.0.0/radius-mode.js create mode 100644 docs/articles/map-design_files/rectangle-mode-1.0.0/rectangle-mode.js create mode 100644 docs/articles/map-design_files/turf-7.2.0/turf.min.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.css create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js rename docs/articles/{getting-started_files/maplibre-gl-5.3.0 => map-design_files/turf-operations-1.0.0/lib/maplibre-gl}/LICENSE.txt (100%) create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.css create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/lib/turf/turf.min.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl.yaml create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl_compare.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl_compare.yaml create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/maplibregl.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/maplibregl.yaml create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/maplibregl_compare.js create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/maplibregl_compare.yaml create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/styles/filter-control.css create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/styles/layers-control.css create mode 100644 docs/articles/map-design_files/turf-operations-1.0.0/turf-operations.js create mode 100644 docs/articles/turf_files/freehand-mode-1.0.0/freehand-mode.js create mode 100644 docs/articles/turf_files/h3j-h3t-0.9.2/h3j_h3t.js create mode 100644 docs/articles/turf_files/htmlwidgets-1.6.4/htmlwidgets.js create mode 100644 docs/articles/turf_files/layers-control-1.0.0/filter-control.css create mode 100644 docs/articles/turf_files/layers-control-1.0.0/layers-control.css create mode 100644 docs/articles/turf_files/mapbox-gl-draw-1.5.0/mapbox-gl-draw.css create mode 100644 docs/articles/turf_files/mapbox-gl-draw-1.5.0/mapbox-gl-draw.js create mode 100644 docs/articles/turf_files/mapbox-gl-globe-minimap-1.2.1/bundle.js rename docs/articles/{getting-started_files/maplibre-gl-5.5.0 => turf_files/maplibre-gl-5.6.0}/LICENSE.txt (100%) rename docs/articles/{getting-started_files/maplibre-gl-5.3.0 => turf_files/maplibre-gl-5.6.0}/maplibre-gl.css (100%) create mode 100644 docs/articles/turf_files/maplibre-gl-5.6.0/maplibre-gl.js rename docs/articles/{layers-overview_files/maplibre-gl-4.4.1 => turf_files/maplibre-gl-5.7.2}/LICENSE.txt (100%) create mode 100644 docs/articles/turf_files/maplibre-gl-5.7.2/maplibre-gl.css create mode 100644 docs/articles/turf_files/maplibre-gl-5.7.2/maplibre-gl.js create mode 100644 docs/articles/turf_files/maplibre-gl-geocoder-1.5.0/maplibre-gl-geocoder.css create mode 100644 docs/articles/turf_files/maplibre-gl-geocoder-1.5.0/maplibre-gl-geocoder.min.js create mode 100644 docs/articles/turf_files/maplibregl-binding-0.3.9.9000/maplibregl.js create mode 100644 docs/articles/turf_files/maplibregl-binding-0.4.0.9000/maplibregl.js create mode 100644 docs/articles/turf_files/maplibregl-binding-0.4.0/maplibregl.js create mode 100644 docs/articles/turf_files/maplibregl-binding-0.4.1/maplibregl.js create mode 100644 docs/articles/turf_files/maptiler-geocoding-control-2.1.7/LICENSE.txt create mode 100644 docs/articles/turf_files/maptiler-geocoding-control-2.1.7/maplibregl.umd.js create mode 100644 docs/articles/turf_files/maptiler-geocoding-control-2.1.7/style.css create mode 100644 docs/articles/turf_files/pmtiles-4.3.0/pmtiles.js create mode 100644 docs/articles/turf_files/radius-mode-1.0.0/radius-mode.js create mode 100644 docs/articles/turf_files/rectangle-mode-1.0.0/rectangle-mode.js create mode 100644 docs/articles/turf_files/turf-7.2.0/turf.min.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.css create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js rename docs/articles/{layers-overview_files/maplibre-gl-4.6.0 => turf_files/turf-operations-1.0.0/lib/maplibre-gl}/LICENSE.txt (100%) create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.css create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/lib/turf/turf.min.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/mapboxgl.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/mapboxgl.yaml create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/mapboxgl_compare.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/mapboxgl_compare.yaml create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/maplibregl.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/maplibregl.yaml create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/maplibregl_compare.js create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/maplibregl_compare.yaml create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/styles/filter-control.css create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/styles/layers-control.css create mode 100644 docs/articles/turf_files/turf-operations-1.0.0/turf-operations.js create mode 100644 inst/htmlwidgets/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js create mode 100644 inst/htmlwidgets/lib/mapbox-pmtiles/pmtiles-source.js create mode 100644 inst/htmlwidgets/lib/maptiler-geocoding-control/LICENSE.txt create mode 100644 inst/htmlwidgets/lib/maptiler-geocoding-control/maplibregl.umd.js create mode 100644 inst/htmlwidgets/lib/maptiler-geocoding-control/style.css create mode 100644 inst/htmlwidgets/lib/radius-mode/radius-mode.js create mode 100644 inst/htmlwidgets/lib/rectangle-mode/rectangle-mode.js create mode 100644 inst/htmlwidgets/lib/turf/turf.min.js diff --git a/docs/articles/getting-started_files/mapbox-pmtiles-1.1.0/pmtiles-source-optimized-v2.js b/docs/articles/getting-started_files/mapbox-pmtiles-1.1.0/pmtiles-source-optimized-v2.js new file mode 100644 index 0000000..207d876 --- /dev/null +++ b/docs/articles/getting-started_files/mapbox-pmtiles-1.1.0/pmtiles-source-optimized-v2.js @@ -0,0 +1,1102 @@ +/** + * mapbox-pmtiles v1.1.0 - Optimized Version with Lifecycle Management + * Original source: https://github.com/am2222/mapbox-pmtiles by Majid Hojati + * License: MIT + * + * This is an optimized version of the mapbox-pmtiles library that provides + * better performance for large datasets through: + * - Configurable resource management + * - Instance-scoped worker pools and caches + * - Proper lifecycle management and cleanup + * - Reference counting for shared resources + * - Enhanced error handling and timeouts + * - Memory optimization with size-based LRU caches + * + * Last updated: 2025 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + // Global shared resources with reference counting + const GLOBAL_SHARED_RESOURCES = { + // Protocol cache - expensive to duplicate, shared with reference counting + protocolCache: new Map(), // url -> { protocol, instance, refCount } + + // Metadata cache - small and shareable + metadataCache: new Map(), // cacheKey -> data + + // Pre-calculated world sizes for common zoom levels (static, no cleanup needed) + worldSizeCache: new Array(25).fill(null).map((_, z) => Math.pow(2, z)), + + // Global cleanup registry + activeManagers: new Set(), + + // Debug/development features + debug: false, + performanceMetrics: new Map(), + }; + + /** + * Default configuration options + */ + const DEFAULT_OPTIONS = { + workerPoolSize: 4, + tileCacheSize: 1000, + tileCacheMaxMemoryMB: 100, + metadataCacheSize: 100, + enableSharedProtocols: true, + requestTimeoutMs: 30000, + enableDebugLogging: false, + enablePerformanceMetrics: false, + }; + + /** + * LRU Cache implementation with size-based eviction + */ + class LRUCache { + constructor(maxSize, maxMemoryBytes = Infinity) { + this.maxSize = maxSize; + this.maxMemoryBytes = maxMemoryBytes; + this.cache = new Map(); + this.currentMemoryBytes = 0; + } + + get(key) { + if (this.cache.has(key)) { + // Move to end (most recently used) + const value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return value.data; + } + return undefined; + } + + set(key, data, estimatedSize = 0) { + // Remove if exists + if (this.cache.has(key)) { + const existing = this.cache.get(key); + this.currentMemoryBytes -= existing.size; + this.cache.delete(key); + } + + // Evict old entries if necessary + while ( + this.cache.size >= this.maxSize || + this.currentMemoryBytes + estimatedSize > this.maxMemoryBytes + ) { + const firstKey = this.cache.keys().next().value; + if (!firstKey) break; + + const firstValue = this.cache.get(firstKey); + this.currentMemoryBytes -= firstValue.size; + this.cache.delete(firstKey); + } + + // Add new entry + this.cache.set(key, { data, size: estimatedSize }); + this.currentMemoryBytes += estimatedSize; + } + + has(key) { + return this.cache.has(key); + } + + delete(key) { + if (this.cache.has(key)) { + const value = this.cache.get(key); + this.currentMemoryBytes -= value.size; + this.cache.delete(key); + return true; + } + return false; + } + + clear() { + this.cache.clear(); + this.currentMemoryBytes = 0; + } + + get size() { + return this.cache.size; + } + + getMemoryUsage() { + return { + entries: this.cache.size, + memoryBytes: this.currentMemoryBytes, + memoryMB: this.currentMemoryBytes / (1024 * 1024), + }; + } + } + + /** + * Resource Manager - handles per-instance resources and lifecycle + */ + class PMTilesResourceManager { + constructor(options = {}) { + this.config = { ...DEFAULT_OPTIONS, ...options }; + this.destroyed = false; + this.paused = false; + this.dispatcher = null; + + // Instance-scoped resources + this.workerPool = []; + this.workerPoolIndex = 0; + this.tileCache = new LRUCache( + this.config.tileCacheSize, + this.config.tileCacheMaxMemoryMB * 1024 * 1024, + ); + this.pendingRequests = new Map(); + this.activeRequests = new Set(); + + // Performance tracking + this.metrics = { + tilesLoaded: 0, + cacheHits: 0, + cacheMisses: 0, + memoryPeakMB: 0, + averageLoadTimeMs: 0, + }; + + // Register for global cleanup + GLOBAL_SHARED_RESOURCES.activeManagers.add(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager created", this.config); + } + } + + /** + * Initialize worker pool + */ + initializeWorkerPool(dispatcher) { + if (this.destroyed) return; + + // Store dispatcher reference + if (dispatcher) { + this.dispatcher = dispatcher; + } + + if (this.workerPool.length === 0 && this.dispatcher) { + for (let i = 0; i < this.config.workerPoolSize; i++) { + try { + this.workerPool.push(this.dispatcher.getActor()); + } catch (error) { + console.warn("[PMTiles] Failed to create worker:", error); + } + } + + if (this.config.enableDebugLogging) { + console.log( + `[PMTiles] Initialized worker pool with ${this.workerPool.length} workers`, + ); + } + } + } + + /** + * Get next worker from pool (round-robin) + */ + getWorkerFromPool() { + if (this.destroyed) { + return null; + } + + // Try to initialize workers if not done yet + if (this.workerPool.length === 0 && this.dispatcher) { + this.initializeWorkerPool(this.dispatcher); + } + + if (this.workerPool.length === 0) { + if (this.config.enableDebugLogging) { + console.warn( + "[PMTiles] Worker pool is empty, dispatcher available:", + !!this.dispatcher, + ); + } + return null; + } + + const worker = this.workerPool[this.workerPoolIndex]; + this.workerPoolIndex = + (this.workerPoolIndex + 1) % this.workerPool.length; + return worker; + } + + /** + * Get or create protocol instance with reference counting + */ + getProtocol(url) { + if (this.destroyed) return null; + + if (!this.config.enableSharedProtocols) { + // Create instance-specific protocol + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + return { protocol, instance }; + } + + // Use shared protocol with reference counting + if (!GLOBAL_SHARED_RESOURCES.protocolCache.has(url)) { + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + GLOBAL_SHARED_RESOURCES.protocolCache.set(url, { + protocol, + instance, + refCount: 0, + }); + } + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + cached.refCount++; + return cached; + } + + /** + * Release protocol reference + */ + releaseProtocol(url) { + if (!this.config.enableSharedProtocols) return; + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + if (cached) { + cached.refCount--; + if (cached.refCount <= 0) { + GLOBAL_SHARED_RESOURCES.protocolCache.delete(url); + + if (this.config.enableDebugLogging) { + console.log(`[PMTiles] Released protocol for ${url}`); + } + } + } + } + + /** + * Cache key for tiles + */ + getTileCacheKey(url, z, x, y) { + return `${url}:${z}:${x}:${y}`; + } + + /** + * Add tile to cache with size estimation + */ + addToTileCache(key, data) { + if (this.destroyed) return; + + let estimatedSize = 0; + if (data instanceof ImageBitmap) { + // Rough estimation: width * height * 4 bytes per pixel + estimatedSize = data.width * data.height * 4; + } else if (data && data.byteLength) { + estimatedSize = data.byteLength; + } else { + estimatedSize = 10000; // Default estimate + } + + this.tileCache.set(key, data, estimatedSize); + + // Update peak memory usage + const memoryUsage = this.tileCache.getMemoryUsage(); + this.metrics.memoryPeakMB = Math.max( + this.metrics.memoryPeakMB, + memoryUsage.memoryMB, + ); + } + + /** + * Get cached metadata + */ + getCachedMetadata(cacheKey) { + return GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + } + + /** + * Set cached metadata + */ + setCachedMetadata(cacheKey, data) { + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, data); + } + + /** + * Pause all operations + */ + pause() { + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager paused"); + } + } + + /** + * Resume operations + */ + resume() { + this.paused = false; + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager resumed"); + } + } + + /** + * Get performance metrics + */ + getMetrics() { + return { + ...this.metrics, + tileCache: this.tileCache.getMemoryUsage(), + workerPoolSize: this.workerPool.length, + pendingRequests: this.pendingRequests.size, + isPaused: this.paused, + isDestroyed: this.destroyed, + }; + } + + /** + * Destroy and cleanup all resources + */ + destroy() { + if (this.destroyed) return; + + this.destroyed = true; + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + // Clear caches + this.tileCache.clear(); + + // Clear worker pool references + this.workerPool.length = 0; + + // Remove from global registry + GLOBAL_SHARED_RESOURCES.activeManagers.delete(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager destroyed", this.getMetrics()); + } + } + } + + /** + * Global cleanup function + */ + const cleanup = () => { + for (const manager of GLOBAL_SHARED_RESOURCES.activeManagers) { + manager.destroy(); + } + GLOBAL_SHARED_RESOURCES.protocolCache.clear(); + GLOBAL_SHARED_RESOURCES.metadataCache.clear(); + }; + + // Register global cleanup + if (typeof window !== "undefined") { + window.addEventListener("beforeunload", cleanup); + } + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + + // Pre-calculate mercator bounds + this._mercatorBounds = { + west: mercatorXFromLng(this.bounds.getWest()), + north: mercatorYFromLat(this.bounds.getNorth()), + east: mercatorXFromLng(this.bounds.getEast()), + south: mercatorYFromLat(this.bounds.getSouth()), + }; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + // Use pre-calculated world size + const worldSize = + GLOBAL_SHARED_RESOURCES.worldSizeCache[tileID.z] || + Math.pow(2, tileID.z); + + // Use pre-calculated mercator bounds + const level = { + minX: Math.floor(this._mercatorBounds.west * worldSize), + minY: Math.floor(this._mercatorBounds.north * worldSize), + maxX: Math.ceil(this._mercatorBounds.east * worldSize), + maxY: Math.ceil(this._mercatorBounds.south * worldSize), + }; + + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + /** + * Enhanced PMTiles Source with lifecycle management + */ + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + + // Extract PMTiles-specific options + const pmtilesOptions = { + workerPoolSize: options.workerPoolSize, + tileCacheSize: options.tileCacheSize, + tileCacheMaxMemoryMB: options.tileCacheMaxMemoryMB, + metadataCacheSize: options.metadataCacheSize, + enableSharedProtocols: options.enableSharedProtocols, + requestTimeoutMs: options.requestTimeoutMs, + enableDebugLogging: options.enableDebugLogging, + enablePerformanceMetrics: options.enablePerformanceMetrics, + }; + + // Initialize resource manager + this.resourceManager = new PMTilesResourceManager(pmtilesOptions); + + // Standard source properties + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = _dispatcher; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._implementation = options; + + // Initialize worker pool + this.resourceManager.initializeWorkerPool(_dispatcher); + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + return; + } + + const { url } = options; + this.url = url; + this.tileSize = 512; + + // Get protocol instance + this.protocolInfo = this.resourceManager.getProtocol(url); + if (!this.protocolInfo) { + this.fire( + new ErrorEvent(new Error(`Failed to create protocol for ${url}`)), + ); + return; + } + + this._protocol = this.protocolInfo.protocol; + this._instance = this.protocolInfo.instance; + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + } + + static async getMetadata(url) { + // Check cache first + const cacheKey = `${url}:metadata`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const metadata = await instance.getMetadata(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, metadata); + return metadata; + } + + static async getHeader(url) { + // Check cache first + const cacheKey = `${url}:header`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const header = await instance.getHeader(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, header); + return header; + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (this.resourceManager.destroyed) return; + + if (!tile.destroy) { + tile.destroy = () => {}; + } + if (!tile.abort) { + tile.abort = () => { + tile.aborted = true; + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + }; + } + } + + /** + * Pause tile loading + */ + pause() { + this.resourceManager.pause(); + } + + /** + * Resume tile loading + */ + resume() { + this.resourceManager.resume(); + } + + /** + * Get performance metrics + */ + getMetrics() { + return this.resourceManager.getMetrics(); + } + + /** + * Destroy source and cleanup resources + */ + destroy() { + if (this.protocolInfo && this.url) { + this.resourceManager.releaseProtocol(this.url); + } + + this.resourceManager.destroy(); + this._loaded = false; + } + + async load(callback) { + if (this.resourceManager.destroyed) { + const error = new Error("Source has been destroyed"); + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + // Check metadata cache first + const headerKey = `${this.url}:header`; + const metadataKey = `${this.url}:metadata`; + + let header, tileJSON; + + const cachedHeader = this.resourceManager.getCachedMetadata(headerKey); + const cachedMetadata = + this.resourceManager.getCachedMetadata(metadataKey); + + if (cachedHeader && cachedMetadata) { + header = cachedHeader; + tileJSON = cachedMetadata; + } else { + try { + // Load and cache + [header, tileJSON] = await Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]); + this.resourceManager.setCachedMetadata(headerKey, header); + this.resourceManager.setCachedMetadata(metadataKey, tileJSON); + } catch (error) { + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + } + + try { + extend(this, tileJSON); + this.header = header; + const { tileType, minZoom, maxZoom, minLon, minLat, maxLon, maxLat } = + header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes(this.tileType) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { dataType: "source", sourceDataType: "metadata" }), + ); + this.fire( + new Event("data", { dataType: "source", sourceDataType: "content" }), + ); + } catch (err2) { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + } + } + + loaded() { + return this._loaded && !this.resourceManager.destroyed; + } + + loadVectorTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + const startTime = Date.now(); + var _a2, _b2, _c; + + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + + // Update metrics + this.resourceManager.metrics.tilesLoaded++; + const loadTime = Date.now() - startTime; + this.resourceManager.metrics.averageLoadTimeMs = + (this.resourceManager.metrics.averageLoadTimeMs + loadTime) / 2; + + if (tile.aborted) return callback(null); + + // Handle abort errors gracefully + if (err2 && err2.name === "AbortError") { + return callback(null); + } + + if (err2 && err2.status !== 404) { + return callback(err2); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + // Handle abort errors gracefully + if (error && (error.name === "AbortError" || error.code === 20)) { + return done.call(this, null); + } + done.call(this, error); + return; + } + + params.data = { + cacheControl, + expires, + rawData: data, + }; + + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + // Use shared worker pool + tile.actor = this.resourceManager.getWorkerFromPool(); + + // Fallback to dispatcher if worker pool failed + if (!tile.actor && this.dispatcher) { + try { + tile.actor = this.dispatcher.getActor(); + } catch (error) { + console.warn("[PMTiles] Failed to get fallback worker:", error); + return callback(new Error("No workers available")); + } + } + + if (!tile.actor) { + return callback(new Error("No workers available")); + } + + // Create request with timeout + const requestPromise = this._protocol.tile({ ...request }, afterLoad); + + // Add timeout if configured + if (this.resourceManager.config.requestTimeoutMs > 0) { + const timeoutId = setTimeout(() => { + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + done.call(this, new Error("Request timeout")); + }, this.resourceManager.config.requestTimeoutMs); + + const originalCancel = requestPromise.cancel; + requestPromise.cancel = () => { + clearTimeout(timeoutId); + if (originalCancel) originalCancel(); + }; + } + + tile.request = requestPromise; + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + if (this.resourceManager.destroyed) return; + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + var _a2, _b2; + + // Check tile cache first + const cacheKey = this.resourceManager.getTileCacheKey( + this.url, + tile.tileID.canonical.z, + tile.tileID.canonical.x, + tile.tileID.canonical.y, + ); + + if (this.resourceManager.tileCache.has(cacheKey)) { + this.resourceManager.metrics.cacheHits++; + const cachedData = this.resourceManager.tileCache.get(cacheKey); + this.loadRasterTileData(tile, cachedData); + tile.state = "loaded"; + return callback(null); + } + + this.resourceManager.metrics.cacheMisses++; + + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + + // Optimized raster tile loading - try direct ArrayBuffer first + const arrayBuffer = data.buffer || data; + window + .createImageBitmap(arrayBuffer) + .then((imageBitmap) => { + // Cache the decoded image + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + // Fallback to blob method + const blob = new window.Blob([new Uint8Array(data)], { + type: this.contentType, + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error(`Can't decode image for ${this.id}: ${error}`), + ); + }); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + this.fixTile(tile); + const controller = new AbortController(); + + // Add timeout if configured + let timeoutId; + if (this.resourceManager.config.requestTimeoutMs > 0) { + timeoutId = setTimeout(() => { + controller.abort(); + }, this.resourceManager.config.requestTimeoutMs); + } + + tile.request = { + cancel: () => { + if (timeoutId) clearTimeout(timeoutId); + controller.abort(); + }, + }; + + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (timeoutId) clearTimeout(timeoutId); + + // Handle abort errors gracefully + if (error.name === "AbortError" || error.code === 20) { + delete tile.request; + return callback(null); + } + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Expose cleanup function + PmTilesSource.cleanup = cleanup; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; + global.PMTilesResourceManager = PMTilesResourceManager; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/getting-started_files/mapbox-pmtiles-1.1.0/pmtiles-source.js b/docs/articles/getting-started_files/mapbox-pmtiles-1.1.0/pmtiles-source.js new file mode 100644 index 0000000..2130749 --- /dev/null +++ b/docs/articles/getting-started_files/mapbox-pmtiles-1.1.0/pmtiles-source.js @@ -0,0 +1,459 @@ +/** + * mapbox-pmtiles v1.0.53 + * Original source: https://github.com/am2222/mapbox-pmtiles + * License: MIT + * + * This is a vendored copy of the mapbox-pmtiles library that provides + * PMTiles support for Mapbox GL JS by implementing a custom source type. + * + * Last updated: 2024 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + const worldSize = Math.pow(2, tileID.z); + const level = { + minX: Math.floor(mercatorXFromLng(this.bounds.getWest()) * worldSize), + minY: Math.floor(mercatorYFromLat(this.bounds.getNorth()) * worldSize), + maxX: Math.ceil(mercatorXFromLng(this.bounds.getEast()) * worldSize), + maxY: Math.ceil(mercatorYFromLat(this.bounds.getSouth()) * worldSize), + }; + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = void 0; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._dataType = "vector"; + this.dispatcher = _dispatcher; + this._implementation = options; + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + } + + const { url } = options; + this.reparseOverscaled = true; + this.scheme = "xyz"; + this.tileSize = 512; + this._loaded = false; + this.type = "vector"; + this._protocol = new pmtiles.Protocol(); + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + const pmtilesInstance = new pmtiles.PMTiles(url); + this._protocol.add(pmtilesInstance); + this._instance = pmtilesInstance; + } + + static async getMetadata(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getMetadata(); + } + + static async getHeader(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getHeader(); + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (!tile.destroy) { + tile.destroy = () => {}; + } + } + + async load(callback) { + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + return Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]) + .then(([header, tileJSON]) => { + extend(this, tileJSON); + this.header = header; + const { + specVersion, + clustered, + tileType, + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + centerZoom, + centerLon, + centerLat, + } = header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes( + this.tileType, + ) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "metadata", + }), + ); + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "content", + }), + ); + }) + .catch((err2) => { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + }); + } + + loaded() { + return this._loaded; + } + + loadVectorTile(tile, callback) { + var _a2, _b2, _c; + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + if (tile.aborted) return callback(null); + if (err2 && err2.status !== 404) { + return callback(err2); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + done.call(this, error); + return; + } + params.data = { + cacheControl, + expires, + rawData: data, + }; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + tile.actor = this._tileWorkers[url] = + this._tileWorkers[url] || this.dispatcher.getActor(); + tile.request = this._protocol.tile({ ...request }, afterLoad); + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + var _a2, _b2; + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + const blob = new window.Blob([new Uint8Array(data)], { + type: "image/png", + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error( + `Can't infer data type for ${this.id}, only raster data supported at the moment. ${error}`, + ), + ); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + this.fixTile(tile); + const controller = new AbortController(); + tile.request = { cancel: () => controller.abort() }; + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (error.code === 20) return; + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/getting-started_files/mapboxgl-binding-0.2.9.9000/mapboxgl.js b/docs/articles/getting-started_files/mapboxgl-binding-0.3.1.9000/mapboxgl.js similarity index 89% rename from docs/articles/getting-started_files/mapboxgl-binding-0.2.9.9000/mapboxgl.js rename to docs/articles/getting-started_files/mapboxgl-binding-0.3.1.9000/mapboxgl.js index b9f2563..700670b 100644 --- a/docs/articles/getting-started_files/mapboxgl-binding-0.2.9.9000/mapboxgl.js +++ b/docs/articles/getting-started_files/mapboxgl-binding-0.3.1.9000/mapboxgl.js @@ -292,6 +292,22 @@ HTMLWidgets.widget({ return; } + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + mapboxgl.accessToken = x.access_token; map = new mapboxgl.Map({ @@ -477,6 +493,18 @@ HTMLWidgets.widget({ urls: source.urls, coordinates: source.coordinates, }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); } }); } @@ -887,6 +915,85 @@ HTMLWidgets.widget({ drawBar.style.flexDirection = "row"; } } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } } // Helper function to add features from a source to draw @@ -1128,17 +1235,17 @@ HTMLWidgets.widget({ // Set the position correctly - fix position bug by using correct CSS positioning const position = x.layers_control.position || "top-left"; if (position === "top-left") { - layersControl.style.top = "10px"; - layersControl.style.left = "10px"; + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; } else if (position === "top-right") { - layersControl.style.top = "10px"; - layersControl.style.right = "10px"; + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; } else if (position === "bottom-left") { - layersControl.style.bottom = "30px"; - layersControl.style.left = "10px"; + layersControl.style.bottom = (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; } else if (position === "bottom-right") { - layersControl.style.bottom = "40px"; - layersControl.style.right = "10px"; + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; } // Apply custom colors if provided @@ -1343,38 +1450,44 @@ HTMLWidgets.widget({ // add hover listener for shinyMode if enabled if (x.hover_events && x.hover_events.enabled) { - map.on("mousemove", function (e) { - // Feature hover events - if (x.hover_events.features) { - const features = map.queryRenderedFeatures(e.point); - - if(features.length > 0) { - const feature = features[0]; - Shiny.onInputChange(el.id + "_feature_hover", { - id: feature.id, - properties: feature.properties, - layer: feature.layer.id, - lng: e.lngLat.lng, - lat: e.lngLat.lat, - time: new Date(), - }); - } else { - Shiny.onInputChange( - el.id + "_feature_hover", - null, - ); - } + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); } + } - // Coordinate hover events - if (x.hover_events.coordinates) { - Shiny.onInputChange(el.id + "_hover", { - lng: e.lngLat.lng, - lat: e.lngLat.lat, - time: new Date(), - }); - } - }); + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); } } @@ -1580,6 +1693,18 @@ if (HTMLWidgets.shinyMode) { sourceConfig[key] = message.source[key]; } }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); } } else if (message.type === "add_layer") { @@ -1846,6 +1971,52 @@ if (HTMLWidgets.shinyMode) { layerState.paintProperties[layerId] = {}; } layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); } else if (message.type === "add_legend") { // Extract legend ID from HTML to track it const legendIdMatch = message.html.match(/id="([^"]+)"/); @@ -2321,6 +2492,85 @@ if (HTMLWidgets.shinyMode) { drawBar.style.flexDirection = "row"; } } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } } else if (message.type === "get_drawn_features") { var drawControl = widget.drawControl || widget.getDraw(); if (drawControl) { @@ -2494,17 +2744,17 @@ if (HTMLWidgets.shinyMode) { // Set the position correctly const position = message.position || "top-left"; if (position === "top-left") { - layersControl.style.top = "10px"; - layersControl.style.left = "10px"; + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; } else if (position === "top-right") { - layersControl.style.top = "10px"; - layersControl.style.right = "10px"; + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; } else if (position === "bottom-left") { - layersControl.style.bottom = "30px"; - layersControl.style.left = "10px"; + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; } else if (position === "bottom-right") { - layersControl.style.bottom = "40px"; - layersControl.style.right = "10px"; + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; } // Apply custom colors if provided diff --git a/docs/articles/layers-overview_files/mapboxgl-binding-0.3/mapboxgl.js b/docs/articles/getting-started_files/mapboxgl-binding-0.3.2/mapboxgl.js similarity index 88% rename from docs/articles/layers-overview_files/mapboxgl-binding-0.3/mapboxgl.js rename to docs/articles/getting-started_files/mapboxgl-binding-0.3.2/mapboxgl.js index b9f2563..42e4216 100644 --- a/docs/articles/layers-overview_files/mapboxgl-binding-0.3/mapboxgl.js +++ b/docs/articles/getting-started_files/mapboxgl-binding-0.3.2/mapboxgl.js @@ -292,6 +292,22 @@ HTMLWidgets.widget({ return; } + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + mapboxgl.accessToken = x.access_token; map = new mapboxgl.Map({ @@ -477,6 +493,18 @@ HTMLWidgets.widget({ urls: source.urls, coordinates: source.coordinates, }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); } }); } @@ -887,6 +915,93 @@ HTMLWidgets.widget({ drawBar.style.flexDirection = "row"; } } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } } // Helper function to add features from a source to draw @@ -1128,17 +1243,25 @@ HTMLWidgets.widget({ // Set the position correctly - fix position bug by using correct CSS positioning const position = x.layers_control.position || "top-left"; if (position === "top-left") { - layersControl.style.top = "10px"; - layersControl.style.left = "10px"; + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; } else if (position === "top-right") { - layersControl.style.top = "10px"; - layersControl.style.right = "10px"; + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; } else if (position === "bottom-left") { - layersControl.style.bottom = "30px"; - layersControl.style.left = "10px"; + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; } else if (position === "bottom-right") { - layersControl.style.bottom = "40px"; - layersControl.style.right = "10px"; + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; } // Apply custom colors if provided @@ -1343,38 +1466,44 @@ HTMLWidgets.widget({ // add hover listener for shinyMode if enabled if (x.hover_events && x.hover_events.enabled) { - map.on("mousemove", function (e) { - // Feature hover events - if (x.hover_events.features) { - const features = map.queryRenderedFeatures(e.point); - - if(features.length > 0) { - const feature = features[0]; - Shiny.onInputChange(el.id + "_feature_hover", { - id: feature.id, - properties: feature.properties, - layer: feature.layer.id, - lng: e.lngLat.lng, - lat: e.lngLat.lat, - time: new Date(), - }); - } else { - Shiny.onInputChange( - el.id + "_feature_hover", - null, - ); - } + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); } + } - // Coordinate hover events - if (x.hover_events.coordinates) { - Shiny.onInputChange(el.id + "_hover", { - lng: e.lngLat.lng, - lat: e.lngLat.lat, - time: new Date(), - }); - } - }); + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); } } @@ -1580,6 +1709,18 @@ if (HTMLWidgets.shinyMode) { sourceConfig[key] = message.source[key]; } }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); } } else if (message.type === "add_layer") { @@ -1846,6 +1987,52 @@ if (HTMLWidgets.shinyMode) { layerState.paintProperties[layerId] = {}; } layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); } else if (message.type === "add_legend") { // Extract legend ID from HTML to track it const legendIdMatch = message.html.match(/id="([^"]+)"/); @@ -2321,6 +2508,91 @@ if (HTMLWidgets.shinyMode) { drawBar.style.flexDirection = "row"; } } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } } else if (message.type === "get_drawn_features") { var drawControl = widget.drawControl || widget.getDraw(); if (drawControl) { @@ -2494,17 +2766,17 @@ if (HTMLWidgets.shinyMode) { // Set the position correctly const position = message.position || "top-left"; if (position === "top-left") { - layersControl.style.top = "10px"; - layersControl.style.left = "10px"; + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; } else if (position === "top-right") { - layersControl.style.top = "10px"; - layersControl.style.right = "10px"; + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; } else if (position === "bottom-left") { - layersControl.style.bottom = "30px"; - layersControl.style.left = "10px"; + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; } else if (position === "bottom-right") { - layersControl.style.bottom = "40px"; - layersControl.style.right = "10px"; + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; } // Apply custom colors if provided @@ -2893,33 +3165,33 @@ if (HTMLWidgets.shinyMode) { // Update the geojson data sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); } - } else if (message.type === "set_rain") { - if (message.rain) { - map.setRain(message.rain); - } else { - map.setRain(null); - } - } else if (message.type === "set_snow") { - if (message.snow) { - map.setSnow(message.snow); - } else { - map.setSnow(null); - } - } else if (message.type === "set_projection") { - const projection = message.projection; - map.setProjection(projection); - } else if (message.type === "add_globe_minimap") { - const globeMinimapOptions = { - globeSize: message.options.globe_size || 100, - landColor: message.options.land_color || "#404040", - waterColor: message.options.water_color || "#090909", - markerColor: message.options.marker_color || "#1da1f2", - markerSize: message.options.marker_size || 2, - }; - const globeMinimap = new GlobeMinimap(globeMinimapOptions); - map.addControl(globeMinimap, message.position || "bottom-left"); - map.controls.push(globeMinimap); } }); } diff --git a/docs/articles/getting-started_files/mapboxgl-binding-0.3.9.9000/mapboxgl.js b/docs/articles/getting-started_files/mapboxgl-binding-0.3.9.9000/mapboxgl.js new file mode 100644 index 0000000..182e834 --- /dev/null +++ b/docs/articles/getting-started_files/mapboxgl-binding-0.3.9.9000/mapboxgl.js @@ -0,0 +1,3249 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/getting-started_files/mapboxgl-binding-0.4.0.9000/mapboxgl.js b/docs/articles/getting-started_files/mapboxgl-binding-0.4.0.9000/mapboxgl.js new file mode 100644 index 0000000..3fee4ba --- /dev/null +++ b/docs/articles/getting-started_files/mapboxgl-binding-0.4.0.9000/mapboxgl.js @@ -0,0 +1,3418 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/getting-started_files/mapboxgl-binding-0.4.0/mapboxgl.js b/docs/articles/getting-started_files/mapboxgl-binding-0.4.0/mapboxgl.js new file mode 100644 index 0000000..182e834 --- /dev/null +++ b/docs/articles/getting-started_files/mapboxgl-binding-0.4.0/mapboxgl.js @@ -0,0 +1,3249 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/getting-started_files/mapboxgl-binding-0.4.1/mapboxgl.js b/docs/articles/getting-started_files/mapboxgl-binding-0.4.1/mapboxgl.js new file mode 100644 index 0000000..c0d6d59 --- /dev/null +++ b/docs/articles/getting-started_files/mapboxgl-binding-0.4.1/mapboxgl.js @@ -0,0 +1,3910 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/getting-started_files/maplibre-gl-4.4.1/LICENSE.txt b/docs/articles/getting-started_files/maplibre-gl-5.7.2/LICENSE.txt similarity index 100% rename from docs/articles/getting-started_files/maplibre-gl-4.4.1/LICENSE.txt rename to docs/articles/getting-started_files/maplibre-gl-5.7.2/LICENSE.txt diff --git a/docs/articles/getting-started_files/maplibre-gl-5.7.2/maplibre-gl.css b/docs/articles/getting-started_files/maplibre-gl-5.7.2/maplibre-gl.css new file mode 100644 index 0000000..3f86747 --- /dev/null +++ b/docs/articles/getting-started_files/maplibre-gl-5.7.2/maplibre-gl.css @@ -0,0 +1 @@ +.maplibregl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgb(0,0,0,0)}.maplibregl-canvas{left:0;position:absolute;top:0}.maplibregl-map:fullscreen{height:100%;width:100%}.maplibregl-ctrl-group button.maplibregl-ctrl-compass{touch-action:none}.maplibregl-canvas-container.maplibregl-interactive,.maplibregl-ctrl-group button.maplibregl-ctrl-compass{cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-canvas-container.maplibregl-interactive.maplibregl-track-pointer{cursor:pointer}.maplibregl-canvas-container.maplibregl-interactive:active,.maplibregl-ctrl-group button.maplibregl-ctrl-compass:active{cursor:grabbing}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-canvas-container.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:pinch-zoom}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:none}.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures,.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-ctrl-bottom-left,.maplibregl-ctrl-bottom-right,.maplibregl-ctrl-top-left,.maplibregl-ctrl-top-right{pointer-events:none;position:absolute;z-index:2}.maplibregl-ctrl-top-left{left:0;top:0}.maplibregl-ctrl-top-right{right:0;top:0}.maplibregl-ctrl-bottom-left{bottom:0;left:0}.maplibregl-ctrl-bottom-right{bottom:0;right:0}.maplibregl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.maplibregl-ctrl-top-left .maplibregl-ctrl{float:left;margin:10px 0 0 10px}.maplibregl-ctrl-top-right .maplibregl-ctrl{float:right;margin:10px 10px 0 0}.maplibregl-ctrl-bottom-left .maplibregl-ctrl{float:left;margin:0 0 10px 10px}.maplibregl-ctrl-bottom-right .maplibregl-ctrl{float:right;margin:0 10px 10px 0}.maplibregl-ctrl-group{background:#fff;border-radius:4px}.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px rgba(0,0,0,.1)}@media (forced-colors:active){.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.maplibregl-ctrl-group button{background-color:transparent;border:0;box-sizing:border-box;cursor:pointer;display:block;height:29px;outline:none;padding:0;width:29px}.maplibregl-ctrl-group button+button{border-top:1px solid #ddd}.maplibregl-ctrl button .maplibregl-ctrl-icon{background-position:50%;background-repeat:no-repeat;display:block;height:100%;width:100%}@media (forced-colors:active){.maplibregl-ctrl-icon{background-color:transparent}.maplibregl-ctrl-group button+button{border-top:1px solid ButtonText}}.maplibregl-ctrl button::-moz-focus-inner{border:0;padding:0}.maplibregl-ctrl-attrib-button:focus,.maplibregl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl button:disabled{cursor:not-allowed}.maplibregl-ctrl button:disabled .maplibregl-ctrl-icon{opacity:.25}@media (hover:hover){.maplibregl-ctrl button:not(:disabled):hover{background-color:rgba(0,0,0,.05)}}.maplibregl-ctrl button:not(:disabled):active{background-color:rgba(0,0,0,.05)}.maplibregl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.maplibregl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.maplibregl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.maplibregl-ctrl-group button:focus:only-child{border-radius:inherit}.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-globe .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none' stroke='%23333' viewBox='0 0 22 22'%3E%3Ccircle cx='11' cy='11' r='8.5'/%3E%3Cpath d='M17.5 11c0 4.819-3.02 8.5-6.5 8.5S4.5 15.819 4.5 11 7.52 2.5 11 2.5s6.5 3.681 6.5 8.5Z'/%3E%3Cpath d='M13.5 11c0 2.447-.331 4.64-.853 6.206-.262.785-.562 1.384-.872 1.777-.314.399-.58.517-.775.517s-.461-.118-.775-.517c-.31-.393-.61-.992-.872-1.777C8.831 15.64 8.5 13.446 8.5 11s.331-4.64.853-6.206c.262-.785.562-1.384.872-1.777.314-.399.58-.517.775-.517s.461.118.775.517c.31.393.61.992.872 1.777.522 1.565.853 3.76.853 6.206Z'/%3E%3Cpath d='M11 7.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138q.07-.058.224-.138c.299-.151.763-.302 1.379-.434C7.378 5.666 9.091 5.5 11 5.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138q-.07.058-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428ZM4.486 6.436ZM11 16.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138 1.3 1.3 0 0 1 .224-.138c.299-.151.763-.302 1.379-.434C7.378 14.666 9.091 14.5 11 14.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138a1.3 1.3 0 0 1-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428Zm-6.514-1.064ZM11 12.5c-2.46 0-4.672-.222-6.255-.574-.796-.177-1.406-.38-1.805-.59a1.5 1.5 0 0 1-.39-.272.3.3 0 0 1-.047-.064.3.3 0 0 1 .048-.064c.066-.073.189-.167.389-.272.399-.21 1.009-.413 1.805-.59C6.328 9.722 8.54 9.5 11 9.5s4.672.222 6.256.574c.795.177 1.405.38 1.804.59.2.105.323.2.39.272a.3.3 0 0 1 .047.064.3.3 0 0 1-.048.064 1.4 1.4 0 0 1-.389.272c-.399.21-1.009.413-1.804.59-1.584.352-3.796.574-6.256.574Zm-8.501-1.51v.002zm0 .018v.002zm17.002.002v-.002zm0-.018v-.002z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-globe-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none' stroke='%2333b5e5' viewBox='0 0 22 22'%3E%3Ccircle cx='11' cy='11' r='8.5'/%3E%3Cpath d='M17.5 11c0 4.819-3.02 8.5-6.5 8.5S4.5 15.819 4.5 11 7.52 2.5 11 2.5s6.5 3.681 6.5 8.5Z'/%3E%3Cpath d='M13.5 11c0 2.447-.331 4.64-.853 6.206-.262.785-.562 1.384-.872 1.777-.314.399-.58.517-.775.517s-.461-.118-.775-.517c-.31-.393-.61-.992-.872-1.777C8.831 15.64 8.5 13.446 8.5 11s.331-4.64.853-6.206c.262-.785.562-1.384.872-1.777.314-.399.58-.517.775-.517s.461.118.775.517c.31.393.61.992.872 1.777.522 1.565.853 3.76.853 6.206Z'/%3E%3Cpath d='M11 7.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138q.07-.058.224-.138c.299-.151.763-.302 1.379-.434C7.378 5.666 9.091 5.5 11 5.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138q-.07.058-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428ZM4.486 6.436ZM11 16.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138 1.3 1.3 0 0 1 .224-.138c.299-.151.763-.302 1.379-.434C7.378 14.666 9.091 14.5 11 14.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138a1.3 1.3 0 0 1-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428Zm-6.514-1.064ZM11 12.5c-2.46 0-4.672-.222-6.255-.574-.796-.177-1.406-.38-1.805-.59a1.5 1.5 0 0 1-.39-.272.3.3 0 0 1-.047-.064.3.3 0 0 1 .048-.064c.066-.073.189-.167.389-.272.399-.21 1.009-.413 1.805-.59C6.328 9.722 8.54 9.5 11 9.5s4.672.222 6.256.574c.795.177 1.405.38 1.804.59.2.105.323.2.39.272a.3.3 0 0 1 .047.064.3.3 0 0 1-.048.064 1.4 1.4 0 0 1-.389.272c-.399.21-1.009.413-1.804.59-1.584.352-3.796.574-6.256.574Zm-8.501-1.51v.002zm0 .018v.002zm17.002.002v-.002zm0-.018v-.002z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%23333' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%2333b5e5' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23aaa' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-waiting .maplibregl-ctrl-icon{animation:maplibregl-spin 2s linear infinite}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23999' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23666' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}}@keyframes maplibregl-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E");background-repeat:no-repeat;cursor:pointer;display:block;height:23px;margin:0 0 -4px -4px;overflow:hidden;width:88px}a.maplibregl-ctrl-logo.maplibregl-compact{width:14px}@media (forced-colors:active){a.maplibregl-ctrl-logo{background-color:transparent;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}.maplibregl-ctrl.maplibregl-ctrl-attrib{background-color:hsla(0,0%,100%,.5);margin:0;padding:0 5px}@media screen{.maplibregl-ctrl-attrib.maplibregl-compact{background-color:#fff;border-radius:12px;box-sizing:content-box;color:#000;margin:10px;min-height:20px;padding:2px 24px 2px 0;position:relative}.maplibregl-ctrl-attrib.maplibregl-compact-show{padding:2px 28px 2px 8px;visibility:visible}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:hsla(0,0%,100%,.5);background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:rgba(0,0,0,.05)}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:hsla(0,0%,100%,.75);border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:rgba(0,0,0,.05)}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px rgba(0,0,0,.35);box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:rgba(0,0,0,.4);color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media (hover:none),(pointer:coarse){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999} \ No newline at end of file diff --git a/docs/articles/getting-started_files/maplibre-gl-5.7.2/maplibre-gl.js b/docs/articles/getting-started_files/maplibre-gl-5.7.2/maplibre-gl.js new file mode 100644 index 0000000..53dd1e0 --- /dev/null +++ b/docs/articles/getting-started_files/maplibre-gl-5.7.2/maplibre-gl.js @@ -0,0 +1,59 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v5.7.2/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory()); +})(this, (function () { 'use strict'; + +/* eslint-disable */ + +var maplibregl = {}; +var modules = {}; +function define(moduleName, _dependencies, moduleFactory) { + modules[moduleName] = moduleFactory; + + // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) + if (moduleName !== 'index') { + return; + } + + // we assume that when an index module is initializing then other modules are loaded already + var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);' + + var sharedModule = {}; + // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) + // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) + // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following + modules.shared(sharedModule); + modules.index(maplibregl, sharedModule); + + if (typeof window !== 'undefined') { + maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); + } + + return maplibregl; +}; + + + +define("shared",["exports"],(function(t){"use strict";function e(t,e,r,n){return new(r||(r=Promise))((function(i,s){function a(t){try{l(n.next(t));}catch(t){s(t);}}function o(t){try{l(n.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(a,o);}l((n=n.apply(t,e||[])).next());}))}function r(t,e){this.x=t,this.y=e;}function n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,s;"function"==typeof SuppressedError&&SuppressedError,r.prototype={clone(){return new r(this.x,this.y)},add(t){return this.clone()._add(t)},sub(t){return this.clone()._sub(t)},multByPoint(t){return this.clone()._multByPoint(t)},divByPoint(t){return this.clone()._divByPoint(t)},mult(t){return this.clone()._mult(t)},div(t){return this.clone()._div(t)},rotate(t){return this.clone()._rotate(t)},rotateAround(t,e){return this.clone()._rotateAround(t,e)},matMult(t){return this.clone()._matMult(t)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(t){return this.x===t.x&&this.y===t.y},dist(t){return Math.sqrt(this.distSqr(t))},distSqr(t){const e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle(){return Math.atan2(this.y,this.x)},angleTo(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith(t){return this.angleWithSep(t.x,t.y)},angleWithSep(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult(t){const e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add(t){return this.x+=t.x,this.y+=t.y,this},_sub(t){return this.x-=t.x,this.y-=t.y,this},_mult(t){return this.x*=t,this.y*=t,this},_div(t){return this.x/=t,this.y/=t,this},_multByPoint(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint(t){return this.x/=t.x,this.y/=t.y,this},_unit(){return this._div(this.mag()),this},_perp(){const t=this.y;return this.y=this.x,this.x=-t,this},_rotate(t){const e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround(t,e){const r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:r},r.convert=function(t){if(t instanceof r)return t;if(Array.isArray(t))return new r(+t[0],+t[1]);if(void 0!==t.x&&void 0!==t.y)return new r(+t.x,+t.y);throw new Error("Expected [x, y] or {x, y} point format")};var a=function(){if(s)return i;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return s=1,i=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},i}(),o=n(a);let l,u;function c(){return null==l&&(l="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),l}function h(){if(null==u&&(u=!1,c())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:!0});if(e){for(let r=0;r4&&void 0!==arguments[4]?arguments[4]:"zyx",s=Math.PI/360;e*=s,n*=s,r*=s;var a=Math.sin(e),o=Math.cos(e),l=Math.sin(r),u=Math.cos(r),c=Math.sin(n),h=Math.cos(n);switch(i){case "xyz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "xzy":t[0]=a*u*h-o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h+a*l*c;break;case "yxz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;case "yzx":t[0]=a*u*h+o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h-a*l*c;break;case "zxy":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "zyx":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;default:throw new Error("Unknown angle order "+i)}return t}function I(){var t=new f(2);return f!=Float32Array&&(t[0]=0,t[1]=0),t}function z(t,e){var r=new f(2);return r[0]=t,r[1]=e,r}m(),_=new f(4),f!=Float32Array&&(_[0]=0,_[1]=0,_[2]=0,_[3]=0),m(),x(1,0,0),x(0,1,0),k(),k(),d(),I();const P=8192;function C(t,e,r){return e*(P/(t.tileSize*Math.pow(2,r-t.tileID.overscaledZ)))}function E(t,e){return (t%e+e)%e}function T(t,e,r){return t*(1-r)+e*r}function B(t){if(t<=0)return 0;if(t>=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function V(t,e,r,n){const i=new o(t,e,r,n);return t=>i.solve(t)}const F=V(.25,.1,.25,1);function $(t,e,r){return Math.min(r,Math.max(e,t))}function D(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function L(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let O=1;function R(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function U(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}function j(t){return Array.isArray(t)?t.map(j):"object"==typeof t&&t?R(t,j):t}const N={};function q(t){N[t]||("undefined"!=typeof console&&console.warn(t),N[t]=!0);}function G(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function X(t){return "undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}let Z=null;function Y(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const H="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function K(t,r,n,i,s){return e(this,void 0,void 0,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const e=new VideoFrame(t,{timestamp:0});try{const a=null==e?void 0:e.format;if(!a||!a.startsWith("BGR")&&!a.startsWith("RGB"))throw new Error(`Unrecognized format ${a}`);const o=a.startsWith("BGR"),l=new Uint8ClampedArray(i*s*4);if(yield e.copyTo(l,function(t,e,r,n,i){const s=4*Math.max(-e,0),a=(Math.max(0,r)-r)*n*4+s,o=4*n,l=Math.max(0,e),u=Math.max(0,r);return {rect:{x:l,y:u,width:Math.min(t.width,e+n)-l,height:Math.min(t.height,r+i)-u},layout:[{offset:a,stride:o}]}}(t,r,n,i,s)),o)for(let t=0;t{t.removeEventListener(e,r,n);}}}function tt(t){return t*Math.PI/180}function et(t){return t/Math.PI*180}const rt={touchstart:!0,touchmove:!0,touchmoveWindow:!0,touchend:!0,touchcancel:!0},nt={dblclick:!0,click:!0,mouseover:!0,mouseout:!0,mousedown:!0,mousemove:!0,mousemoveWindow:!0,mouseup:!0,mouseupWindow:!0,contextmenu:!0,wheel:!0},it="AbortError";function st(){return new Error(it)}const at={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function ot(t){return at.REGISTERED_PROTOCOLS[t.substring(0,t.indexOf("://"))]}const lt="global-dispatcher";class ut extends Error{constructor(t,e,r,n){super(`AJAXError: ${e} (${t}): ${r}`),this.status=t,this.statusText=e,this.url=r,this.body=n;}}const ct=()=>X(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,ht=function(t,r){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const e=ot(t.url);if(e)return e(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:lt},r)}if(!(/^file:/.test(n=t.url)||/^file:/.test(ct())&&!/^\w+:/.test(n))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,r){return e(this,void 0,void 0,(function*(){const e=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:ct(),signal:r.signal});let n,i;"json"!==t.type||e.headers.has("Accept")||e.headers.set("Accept","application/json");try{n=yield fetch(e);}catch(e){throw new ut(0,e.message,t.url,new Blob)}if(!n.ok){const e=yield n.blob();throw new ut(n.status,n.statusText,t.url,e)}i="arrayBuffer"===t.type||"image"===t.type?n.arrayBuffer():"json"===t.type?n.json():n.text();const s=yield i;if(r.signal.aborted)throw st();return {data:s,cacheControl:n.headers.get("Cache-Control"),expires:n.headers.get("Expires")}}))}(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:!0,targetMapId:lt},r)}var n;return function(t,e){return new Promise(((r,n)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,!0),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||void 0===i?void 0:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{n(new Error(s.statusText));},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response);}catch(t){return void n(t)}r({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires")});}else {const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});n(new ut(s.status,s.statusText,t.url,e));}},e.signal.addEventListener("abort",(()=>{s.abort(),n(st());})),s.send(t.body);}))}(t,r)};function pt(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return !0;const e=new URL(t),r=window.location;return e.protocol===r.protocol&&e.host===r.host}function ft(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function dt(t,e,r){if(r&&r[t]){const n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}class yt{constructor(t,e={}){L(this,e),this.type=t;}}class mt extends yt{constructor(t,e={}){super("error",L({error:t},e));}}class gt{on(t,e){return this._listeners=this._listeners||{},ft(t,e,this._listeners),{unsubscribe:()=>{this.off(t,e);}}}off(t,e){return dt(t,e,this._listeners),dt(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},ft(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new yt(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)dt(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(L(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof mt&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var xt={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},state:{type:"state",default:{}},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},"font-faces":{type:"array",value:"fontFaces"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},"color-relief":{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_color-relief","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const vt=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function bt(t,e){const r={};for(const e in t)"ref"!==e&&(r[e]=t[e]);return vt.forEach((t=>{t in e&&(r[t]=e[t]);})),r}function wt(t,e){if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return !1;for(let r=0;r`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const Jt=[Vt,Ft,$t,Dt,Lt,Ot,Nt,Rt,Ht(Ut),qt,Xt,Gt,Zt,Yt];function Wt(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Wt(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of Jt)if(!Wt(t,e))return null}return `Expected ${Kt(t)} but found ${Kt(e)} instead.`}function Qt(t,e){return e.some((e=>e.kind===t.kind))}function te(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function ee(t,e){return "array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const re=.96422,ne=.82521,ie=4/29,se=6/29,ae=3*se*se,oe=se*se*se,le=Math.PI/180,ue=180/Math.PI;function ce(t){return (t%=360)<0&&(t+=360),t}function he([t,e,r,n]){let i,s;const a=fe((.2225045*(t=pe(t))+.7168786*(e=pe(e))+.0606169*(r=pe(r)))/1);t===e&&e===r?i=s=a:(i=fe((.4360747*t+.3850649*e+.1430804*r)/re),s=fe((.0139322*t+.0971045*e+.7141733*r)/ne));const o=116*a-16;return [o<0?0:o,500*(i-a),200*(a-s),n]}function pe(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function fe(t){return t>oe?Math.pow(t,1/3):t/ae+ie}function de([t,e,r,n]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,a=isNaN(r)?i:i-r/200;return i=1*me(i),s=re*me(s),a=ne*me(a),[ye(3.1338561*s-1.6168667*i-.4906146*a),ye(-.9787684*s+1.9161415*i+.033454*a),ye(.0719453*s-.2289914*i+1.4052427*a),n]}function ye(t){return (t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function me(t){return t>se?t*t*t:ae*(t-ie)}const ge=Object.hasOwn||function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};function xe(t,e){return ge(t,e)?t[e]:void 0}function ve(t){return parseInt(t.padEnd(2,t),16)/255}function be(t,e){return we(e?t/100:t,0,1)}function we(t,e,r){return Math.min(Math.max(e,t),r)}function _e(t){return !t.some(Number.isNaN)}const Se={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function Ae(t,e,r){return t+r*(e-t)}function ke(t,e,r){return t.map(((t,n)=>Ae(t,e[n],r)))}class Me{constructor(t,e,r,n=1,i=!0){this.r=t,this.g=e,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[t,e,r,n]));}static parse(t){if(t instanceof Me)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return [0,0,0,0];const e=xe(Se,t);if(e){const[t,r,n]=e;return [t/255,r/255,n/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let r=1;return [ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,r,n,i,s,a,o,l,u,c,h,p]=e,f=[i||" ",o||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[n,a,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[we(+r/e,0,1),we(+s/e,0,1),we(+l/e,0,1),h?be(+h,p):1];if(_e(t))return t}}return}}const r=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[t,e,n,i,s,a,o,l,u]=r,c=[n||" ",s||" ",o].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,we(+i,0,100),we(+a,0,100),l?be(+l,u):1];if(_e(t))return function([t,e,r,n]){function i(n){const i=(n+t/30)%12,s=e*Math.min(r,1-r);return r-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=ce(t),e/=100,r/=100,[i(0),i(8),i(4),n]}(t)}}}(t);return e?new Me(...e,!1):void 0}get rgb(){const{r:t,g:e,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[t/i,e/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,r,n,i]=he(t),s=Math.sqrt(r*r+n*n);return [Math.round(1e4*s)?ce(Math.atan2(n,r)*ue):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",he(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,r,n]=this.rgb;return `rgba(${[t,e,r].map((t=>Math.round(255*t))).join(",")},${n})`}static interpolate(t,e,r,n="rgb"){switch(n){case "rgb":{const[n,i,s,a]=ke(t.rgb,e.rgb,r);return new Me(n,i,s,a,!1)}case "hcl":{const[n,i,s,a]=t.hcl,[o,l,u,c]=e.hcl;let h,p;if(isNaN(n)||isNaN(o))isNaN(n)?isNaN(o)?h=NaN:(h=o,1!==s&&0!==s||(p=l)):(h=n,1!==u&&0!==u||(p=i));else {let t=o-n;o>n&&t>180?t-=360:o180&&(t+=360),h=n+r*t;}const[f,d,y,m]=function([t,e,r,n]){return t=isNaN(t)?0:t*le,de([r,Math.cos(t)*e,Math.sin(t)*e,n])}([h,null!=p?p:Ae(i,l,r),Ae(s,u,r),Ae(a,c,r)]);return new Me(f,d,y,m,!1)}case "lab":{const[n,i,s,a]=de(ke(t.lab,e.lab,r));return new Me(n,i,s,a,!1)}}}}Me.black=new Me(0,0,0,1),Me.white=new Me(1,1,1,1),Me.transparent=new Me(0,0,0,0),Me.red=new Me(1,0,0,1);class Ie{constructor(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const ze=["bottom","center","top"];class Pe{constructor(t,e,r,n,i,s){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i,this.verticalAlign=s;}}class Ce{constructor(t){this.sections=t;}static fromString(t){return new Ce([new Pe(t,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof Ce?t:Ce.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class Ee{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Ee)return t;if("number"==typeof t)return new Ee([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]];}return new Ee(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Ee(ke(t.values,e.values,r))}}class Te{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Te)return t;if("number"==typeof t)return new Te([t]);if(Array.isArray(t)){for(const e of t)if("number"!=typeof e)return;return new Te(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Te(ke(t.values,e.values,r))}}class Be{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Be)return t;if("string"==typeof t){const e=Me.parse(t);if(!e)return;return new Be([e])}if(!Array.isArray(t))return;const e=[];for(const r of t){if("string"!=typeof r)return;const t=Me.parse(r);if(!t)return;e.push(t);}return new Be(e)}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r,n="rgb"){const i=[];if(t.values.length!=e.values.length)throw new Error(`colorArray: Arrays have mismatched length (${t.values.length} vs. ${e.values.length}), cannot interpolate.`);for(let s=0;s=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Re(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof Le||t instanceof Me||t instanceof Ie||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De)return !0;if(Array.isArray(t)){for(const e of t)if(!Re(e))return !1;return !0}if("object"==typeof t){for(const e in t)if(!Re(t[e]))return !1;return !0}return !1}function Ue(t){if(null===t)return Vt;if("string"==typeof t)return $t;if("boolean"==typeof t)return Dt;if("number"==typeof t)return Ft;if(t instanceof Me)return Lt;if(t instanceof Le)return Ot;if(t instanceof Ie)return jt;if(t instanceof Ce)return Nt;if(t instanceof Ee)return qt;if(t instanceof Te)return Xt;if(t instanceof Be)return Gt;if(t instanceof $e)return Yt;if(t instanceof De)return Zt;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=Ue(e);if(r){if(r===t)continue;r=Ut;break}r=t;}return Ht(r||Ut,e)}return Rt}function je(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof Me||t instanceof Le||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De?t.toString():JSON.stringify(t)}class Ne{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Re(t[1]))return e.error("invalid value");const r=t[1];let n=Ue(r);const i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new Ne(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return !0}}const qe={string:$t,number:Ft,boolean:Dt,object:Rt};class Ge{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r,n=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const r=t[1];if("string"!=typeof r||!(r in qe)||"object"===r)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=qe[r],n++;}else i=Ut;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],n++;}r=Ht(i,s);}else {if(!qe[i])throw new Error(`Types doesn't contain name = ${i}`);r=qe[i];}const s=[];for(;nt.outputDefined()))}}const Xe={"to-boolean":Dt,"to-color":Lt,"to-number":Ft,"to-string":$t};class Ze{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[0];if(!Xe[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");const n=Xe[r],i=[];for(let r=1;r4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:Oe(e[0],e[1],e[2],e[3]),!r))return new Me(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new Ve(r||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "padding":{let e;for(const r of this.args){e=r.evaluate(t);const n=Ee.parse(e);if(n)return n}throw new Ve(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "numberArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Te.parse(e);if(n)return n}throw new Ve(`Could not parse numberArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "colorArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Be.parse(e);if(n)return n}throw new Ve(`Could not parse colorArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "variableAnchorOffsetCollection":{let e;for(const r of this.args){e=r.evaluate(t);const n=$e.parse(e);if(n)return n}throw new Ve(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "number":{let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new Ve(`Could not convert ${JSON.stringify(e)} to number.`)}case "formatted":return Ce.fromString(je(this.args[0].evaluate(t)));case "resolvedImage":return De.fromString(je(this.args[0].evaluate(t)));case "projectionDefinition":return this.args[0].evaluate(t);default:return je(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}const Ye=["Unknown","Point","LineString","Polygon"];class He{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null;}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?Ye[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache.get(t);return e||(e=Me.parse(t),this._parseColorCache.set(t,e)),e}}class Ke{constructor(t,e,r=[],n,i=new Bt,s=[]){this.registry=t,this.path=r,this.key=r.map((t=>`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=n,this._isConstant=e;}parse(t,e,r,n,i={}){return e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return "assert"===r?new Ge(e,[t]):"coerce"===r?new Ze(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const n=t[0];if("string"!=typeof n)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[n];if(i){let n=i.parse(t,this);if(!n)return null;if(this.expectedType){const t=this.expectedType,i=n.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind){if("projectionDefinition"===t.kind&&["string","array"].includes(i.kind)||["color","formatted","resolvedImage"].includes(t.kind)&&["value","string"].includes(i.kind)||["padding","numberArray"].includes(t.kind)&&["value","number","array"].includes(i.kind)||"colorArray"===t.kind&&["value","string","array"].includes(i.kind)||"variableAnchorOffsetCollection"===t.kind&&["value","array"].includes(i.kind))n=r(n,t,e.typeAnnotation||"coerce");else if(this.checkSubtype(t,i))return null}else n=r(n,t,e.typeAnnotation||"assert");}if(!(n instanceof Ne)&&"resolvedImage"!==n.type.kind&&this._isConstant(n)){const t=new He;try{n=new Ne(n.type,n.evaluate(t));}catch(t){return this.error(t.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Ke(this.registry,this._isConstant,n,e||null,i,this.errors)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new Tt(r,t));}checkSubtype(t,e){const r=Wt(t,e);return r&&this.error(r),r}}class Je{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new Ve(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new Ve(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return !1}}class tr{constructor(t,e){this.type=Dt,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);return r&&n?Qt(r.type,[Dt,$t,Ft,Vt,Ut])?new tr(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);if(!te(r,["string","array"]))throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return !0}}class er{constructor(t,e,r){this.type=Ft,this.needle=t,this.haystack=e,this.fromIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);if(!r||!n)return null;if(!Qt(r.type,[Dt,$t,Ft,Vt,Ut]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new er(r,n,i):null}return new er(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(t)),te(r,["string"])){const t=r.indexOf(e,n);return -1===t?-1:[...r.slice(0,t)].length}if(te(r,["array"]))return r.indexOf(e,n);throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return !1}}class rr{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(r){if(u.checkSubtype(r,Ue(t)))return null}else r=Ue(t);if(void 0!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length;}const c=e.parse(l,a,n);if(!c)return null;n=n||c.type,s.push(c);}const a=e.parse(t[1],1,Ut);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,n);return o?"value"!==a.type.kind&&e.concat(1).checkSubtype(r,a.type)?null:new rr(r,n,a,i,s,o):null}evaluate(t){const e=this.input.evaluate(t);return (Ue(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class nr{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class ir{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ft);if(!r||!n)return null;if(!Qt(r.type,[Ht(Ut),$t,Ut]))return e.error(`Expected first argument to be of type array or string, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new ir(r.type,r,n,i):null}return new ir(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);let n;if(this.endIndex&&(n=this.endIndex.evaluate(t)),te(e,["string"]))return [...e].slice(r,n).join("");if(te(e,["array"]))return e.slice(r,n);throw new Ve(`Expected first argument to be of type array or string, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return !1}}function sr(t,e){const r=t.length-1;let n,i,s=0,a=r,o=0;for(;s<=a;)if(o=Math.floor((s+a)/2),n=t[o],i=t[o+1],n<=e){if(o===r||ee))throw new Ve("Input is not a number.");a=o-1;}return 0}class ar{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',o);const u=e.parse(a,l,i);if(!u)return null;i=i||u.type,n.push([s,u]);}return new ar(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[sr(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function or(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var lr,ur,cr=function(){if(ur)return lr;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return ur=1,lr=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},lr}(),hr=or(cr);class pr{constructor(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e);}static interpolationFactor(t,e,r,n){let i=0;if("exponential"===t.name)i=fr(e,t.base,r,n);else if("linear"===t.name)i=fr(e,1,r,n);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new hr(s[0],s[1],s[2],s[3]).solve(fr(e,1,r,n));}return i}static parse(t,e){let[r,n,i,...s]=t;if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){const t=n[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:t};}else {if("cubic-bezier"!==n[0])return e.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const t=n.slice(1);if(4!==t.length||t.some((t=>"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,Ft),!i)return null;const a=[];let o=null;"interpolate-hcl"!==r&&"interpolate-lab"!==r||e.expectedType==Gt?e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType):o=Lt;for(let t=0;t=r)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,o);if(!u)return null;o=o||u.type,a.push([r,u]);}return ee(o,Ft)||ee(o,Ot)||ee(o,Lt)||ee(o,qt)||ee(o,Xt)||ee(o,Gt)||ee(o,Yt)||ee(o,Ht(Ft))?new pr(o,r,n,i,a):e.error(`Type ${Kt(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=sr(e,n),a=pr.interpolationFactor(this.interpolation,n,e[s],e[s+1]),o=r[s].evaluate(t),l=r[s+1].evaluate(t);switch(this.operator){case "interpolate":switch(this.type.kind){case "number":return Ae(o,l,a);case "color":return Me.interpolate(o,l,a);case "padding":return Ee.interpolate(o,l,a);case "colorArray":return Be.interpolate(o,l,a);case "numberArray":return Te.interpolate(o,l,a);case "variableAnchorOffsetCollection":return $e.interpolate(o,l,a);case "array":return ke(o,l,a);case "projectionDefinition":return Le.interpolate(o,l,a)}case "interpolate-hcl":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"hcl");case "colorArray":return Be.interpolate(o,l,a,"hcl")}case "interpolate-lab":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"lab");case "colorArray":return Be.interpolate(o,l,a,"lab")}}}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function fr(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}const dr={color:Me.interpolate,number:Ae,padding:Ee.interpolate,numberArray:Te.interpolate,colorArray:Be.interpolate,variableAnchorOffsetCollection:$e.interpolate,array:ke};class yr{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r=null;const n=e.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const n of t.slice(1)){const t=e.parse(n,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!t)return null;r=r||t.type,i.push(t);}if(!r)throw new Error("No output type");const s=n&&i.some((t=>Wt(n,t.type)));return new yr(s?Ut:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(t),r&&r instanceof De&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break;return r}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function mr(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function gr(t,e,r,n){return 0===n.compare(e,r)}function xr(t,e,r){const n="=="!==t&&"!="!==t;return class i{constructor(t,e,r){this.type=Dt,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const r=t[0];let s=e.parse(t[1],1,Ut);if(!s)return null;if(!mr(r,s.type))return e.concat(1).error(`"${r}" comparisons are not supported for type '${Kt(s.type)}'.`);let a=e.parse(t[2],2,Ut);if(!a)return null;if(!mr(r,a.type))return e.concat(2).error(`"${r}" comparisons are not supported for type '${Kt(a.type)}'.`);if(s.type.kind!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error(`Cannot compare types '${Kt(s.type)}' and '${Kt(a.type)}'.`);n&&("value"===s.type.kind&&"value"!==a.type.kind?s=new Ge(a.type,[s]):"value"!==s.type.kind&&"value"===a.type.kind&&(a=new Ge(s.type,[a])));let o=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error("Cannot use collator to compare non-string types.");if(o=e.parse(t[3],3,jt),!o)return null}return new i(s,a,o)}evaluate(i){const s=this.lhs.evaluate(i),a=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=Ue(s),r=Ue(a);if(e.kind!==r.kind||"string"!==e.kind&&"number"!==e.kind)throw new Ve(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=Ue(s),r=Ue(a);if("string"!==t.kind||"string"!==r.kind)return e(i,s,a)}return this.collator?r(i,s,a,this.collator.evaluate(i)):e(i,s,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return !0}}}const vr=xr("==",(function(t,e,r){return e===r}),gr),br=xr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !gr(0,e,r,n)})),wr=xr("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),Sr=xr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),Ar=xr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class kr{constructor(t,e,r){this.type=jt,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");const n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,Dt);if(!n)return null;const i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Dt);if(!i)return null;let s=null;return r.locale&&(s=e.parse(r.locale,1,$t),!s)?null:new kr(n,i,s)}evaluate(t){return new Ie(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);}outputDefined(){return !1}}class Mr{constructor(t,e,r,n,i){this.type=$t,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=e.parse(n.locale,1,$t),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,$t),!s))return null;let a=null;if(n["min-fraction-digits"]&&(a=e.parse(n["min-fraction-digits"],1,Ft),!a))return null;let o=null;return n["max-fraction-digits"]&&(o=e.parse(n["max-fraction-digits"],1,Ft),!o)?null:new Mr(r,i,s,a,o)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return !1}}class Ir{constructor(t){this.type=Nt,this.sections=t;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");const n=[];let i=!1;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&"object"==typeof s&&!Array.isArray(s)){i=!1;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,Ft),!t))return null;let r=null;if(s["text-font"]&&(r=e.parse(s["text-font"],1,Ht($t)),!r))return null;let a=null;if(s["text-color"]&&(a=e.parse(s["text-color"],1,Lt),!a))return null;let o=null;if(s["vertical-align"]){if("string"==typeof s["vertical-align"]&&!ze.includes(s["vertical-align"]))return e.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${s["vertical-align"]}' instead.`);if(o=e.parse(s["vertical-align"],1,$t),!o)return null}const l=n[n.length-1];l.scale=t,l.font=r,l.textColor=a,l.verticalAlign=o;}else {const s=e.parse(t[r],1,Ut);if(!s)return null;const a=s.type.kind;if("string"!==a&&"value"!==a&&"null"!==a&&"resolvedImage"!==a)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:s,scale:null,font:null,textColor:null,verticalAlign:null});}}return new Ir(n)}evaluate(t){return new Ce(this.sections.map((e=>{const r=e.content.evaluate(t);return Ue(r)===Zt?new Pe("",r,null,null,null,e.verticalAlign?e.verticalAlign.evaluate(t):null):new Pe(je(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null,e.verticalAlign?e.verticalAlign.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor),e.verticalAlign&&t(e.verticalAlign);}outputDefined(){return !1}}class zr{constructor(t){this.type=Zt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,$t);return r?new zr(r):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),r=De.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r}eachChild(t){t(this.input);}outputDefined(){return !1}}class Pr{constructor(t){this.type=Ft,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${Kt(r.type)} instead.`):new Pr(r):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return [...e].length;if(Array.isArray(e))return e.length;throw new Ve(`Expected value to be of type string or array, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return !1}}const Cr=8192;function Er(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*Cr),Math.round(n*i*Cr)]}function Tr(t,e){const r=Math.pow(2,e.z);return [(i=(t[0]/Cr+e.x)/r,360*i-180),(n=(t[1]/Cr+e.y)/r,360/Math.PI*Math.atan(Math.exp((180-360*n)*Math.PI/180))-90)];var n,i;}function Br(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function Vr(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function Fr(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],a=t[1]-r[1];return n*a-s*i==0&&n*s<=0&&i*a<=0}function $r(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!jr(t,e,r,n)||!jr(r,n,t,e));var i,s;}function Dr(t,e,r){for(const n of r)for(let r=0;r(i=t)[1]!=(a=o[e+1])[1]>i[1]&&i[0]<(a[0]-s[0])*(i[1]-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}var i,s,a;return n}function Or(t,e){for(const r of e)if(Lr(t,r))return !0;return !1}function Rr(t,e){for(const r of t)if(!Lr(r,e))return !1;for(let r=0;r0&&o<0||a<0&&o>0}function Nr(t,e,r){const n=[];for(let i=0;ir[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i;}Br(e,t);}function Xr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];Gr(n,e,r,i),a.push(n);}return a}function Zr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];Br(e,r),t.push(r);}a.push(t);}if(e[2]-e[0]<=i/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const n of t)Gr(n,e,r,i);}var o;return a}class Yr{constructor(t,e){this.type=Dt,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const r of e.features){const{type:e,coordinates:n}=r.geometry;"Polygon"===e&&t.push(n),"MultiPolygon"===e&&t.push(...n);}if(t.length)return new Yr(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new Yr(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new Yr(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Lr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Or(t,s))return !1}return !0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Rr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Ur(t,s))return !1}return !0}(t,this.geometries)}return !1}eachChild(){}outputDefined(){return !0}}let Hr=class{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}};function Kr(t,e,r=0,n=t.length-1,i=Wr){for(;n>r;){if(n-r>600){const s=n-r+1,a=e-r+1,o=Math.log(s),l=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*l*(s-l)/s)*(a-s/2<0?-1:1);Kr(t,e,Math.max(r,Math.floor(e-a*l/s+u)),Math.min(n,Math.floor(e+(s-a)*l/s+u)),i);}const s=t[e];let a=r,o=n;for(Jr(t,r,e),i(t[n],s)>0&&Jr(t,r,n);a0;)o--;}0===i(t[r],s)?Jr(t,r,o):(o++,Jr(t,o,n)),o<=e&&(r=o+1),e<=o&&(n=o-1);}}function Jr(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function Wr(t,e){return te?1:0}function Qr(t,e){if(t.length<=1)return [t];const r=[];let n,i;for(const e of t){const t=en(e);0!==t&&(e.area=Math.abs(t),void 0===i&&(i=t<0),i===t<0?(n&&r.push(n),n=[e]):n.push(e));}if(n&&r.push(n),e>1)for(let t=0;t1?(l=t[o+1][0],u=t[o+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function on(t,e){return e[0]-t[0]}function ln(t){return t[1]-t[0]+1}function un(t,e){return t[1]>=t[0]&&t[1]t[1])return [null,null];const r=ln(t);if(e){if(2===r)return [t,null];const e=Math.floor(r/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===r)return [t,null];const n=Math.floor(r/2)-1;return [[t[0],t[0]+n],[t[0]+n+1,t[1]]]}function hn(t,e){if(!un(e,t.length))return [1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=e[0];n<=e[1];++n)Br(r,t[n]);return r}function pn(t){const e=[1/0,1/0,-1/0,-1/0];for(const r of t)for(const t of r)Br(e,t);return e}function fn(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function dn(t,e,r){if(!fn(t)||!fn(e))return NaN;let n=0,i=0;return t[2]e[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if(Vr(i,s)){if(wn(t,e))return 0}else if(wn(e,t))return 0;let a=1/0;for(const n of t)for(let t=0,i=n.length,s=i-1;t0;){const i=a.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(ln(l)<=u){if(!un(l,t.length))return NaN;if(e){const e=bn(t,l,r,n);if(isNaN(e)||0===e)return e;s=Math.min(s,e);}else for(let e=l[0];e<=l[1];++e){const i=vn(t[e],r,n);if(s=Math.min(s,i),0===s)return 0}}else {const r=cn(l,e);Sn(a,s,n,t,o,r[0]),Sn(a,s,n,t,o,r[1]);}}return s}function Mn(t,e,r,n,i,s=1/0){let a=Math.min(s,i.distance(t[0],r[0]));if(0===a)return a;const o=new Hr([[0,[0,t.length-1],[0,r.length-1]]],on);for(;o.length>0;){const s=o.pop();if(s[0]>=a)continue;const l=s[1],u=s[2],c=e?50:100,h=n?50:100;if(ln(l)<=c&&ln(u)<=h){if(!un(l,t.length)&&un(u,r.length))return NaN;let s;if(e&&n)s=gn(t,l,r,u,i),a=Math.min(a,s);else if(e&&!n){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=yn(r[t],e,i),a=Math.min(a,s),0===a)return a}else if(!e&&n){const e=r.slice(u[0],u[1]+1);for(let r=l[0];r<=l[1];++r)if(s=yn(t[r],e,i),a=Math.min(a,s),0===a)return a}else s=xn(t,l,r,u,i),a=Math.min(a,s);}else {const s=cn(l,e),c=cn(u,n);An(o,a,i,t,r,s[0],c[0]),An(o,a,i,t,r,s[0],c[1]),An(o,a,i,t,r,s[1],c[0]),An(o,a,i,t,r,s[1],c[1]);}}return a}function In(t){return "MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class zn{constructor(t,e){this.type=Ft,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new zn(e,e.features.map((t=>In(t.geometry))).flat());if("Feature"===e.type)return new zn(e,In(e.geometry));if("type"in e&&"coordinates"in e)return new zn(e,In(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!1,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!1,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!1,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!0,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!0,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!0,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const r=t.geometry();if(0===r.length||0===r[0].length)return NaN;const n=Qr(r,0).map((e=>e.map((e=>e.map((e=>Tr([e.x,e.y],t.canonical))))))),i=new an(n[0][0][0][1]);let s=1/0;for(const t of e)for(const e of n){switch(t.type){case "Point":s=Math.min(s,kn([t.coordinates],!1,e,i,s));break;case "LineString":s=Math.min(s,kn(t.coordinates,!0,e,i,s));break;case "Polygon":s=Math.min(s,_n(e,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return !0}}class Pn{constructor(t){this.type=Ut,this.key=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=t[1];return null==r?e.error("Global state property must be defined."):"string"!=typeof r?e.error(`Global state property must be string, but found ${typeof t[1]} instead.`):new Pn(r)}evaluate(t){var e;const r=null===(e=t.globals)||void 0===e?void 0:e.globalState;return r&&0!==Object.keys(r).length?xe(r,this.key):null}eachChild(){}outputDefined(){return !1}}const Cn={"==":vr,"!=":br,">":_r,"<":wr,">=":Ar,"<=":Sr,array:Ge,at:Qe,boolean:Ge,case:nr,coalesce:yr,collator:kr,format:Ir,image:zr,in:tr,"index-of":er,interpolate:pr,"interpolate-hcl":pr,"interpolate-lab":pr,length:Pr,let:Je,literal:Ne,match:rr,number:Ge,"number-format":Mr,object:Ge,slice:ir,step:ar,string:Ge,"to-boolean":Ze,"to-color":Ze,"to-number":Ze,"to-string":Ze,var:We,within:Yr,distance:zn,"global-state":Pn};class En{constructor(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return !1}static parse(t,e){const r=t[0],n=En.definitions[r];if(!n)return e.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let o=null;for(const[n,s]of a){o=new Ke(e.registry,$n,e.path,null,e.scope);const a=[];let l=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(Kt).join(", ")})`:`(${Kt(e.type)}...)`;var e;})).join(" | "),n=[];for(let r=1;r{r=e?r&&$n(t):r&&t instanceof Ne;})),!!r&&Dn(t)&&On(t,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function Dn(t){if(t instanceof En){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}if(t instanceof Yr)return !1;if(t instanceof zn)return !1;let e=!0;return t.eachChild((t=>{e&&!Dn(t)&&(e=!1);})),e}function Ln(t){if(t instanceof En&&"feature-state"===t.name)return !1;let e=!0;return t.eachChild((t=>{e&&!Ln(t)&&(e=!1);})),e}function On(t,e){if(t instanceof En&&e.indexOf(t.name)>=0)return !1;let r=!0;return t.eachChild((t=>{r&&!On(t,e)&&(r=!1);})),r}function Rn(t){return {result:"success",value:t}}function Un(t){return {result:"error",value:t}}function jn(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Nn(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function qn(t){return !!t.expression&&t.expression.interpolated}function Gn(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Xn(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)&&Ue(t)===Rt}function Zn(t){return t}function Yn(t,e){const r=t.stops&&"object"==typeof t.stops[0][0],n=r||!(r||void 0!==t.property),i=t.type||(qn(e)?"exponential":"interval"),s=function(t){switch(t.type){case "color":return Me.parse;case "padding":return Ee.parse;case "numberArray":return Te.parse;case "colorArray":return Be.parse;default:return null}}(e);if(s&&((t=Et({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],s(t[1])]))),t.default=s(t.default?t.default:e.default)),t.colorSpace&&"rgb"!==(a=t.colorSpace)&&"hcl"!==a&&"lab"!==a)throw new Error(`Unknown color space: "${t.colorSpace}"`);var a;const o=function(t){switch(t){case "exponential":return Wn;case "interval":return Jn;case "categorical":return Kn;case "identity":return Qn;default:throw new Error(`Unknown function type "${t}"`)}}(i);let l,u;if("categorical"===i){l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0];}if(r){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>Wn({stops:i,base:t.base},e,r).evaluate(r,n)}}if(n){const r="exponential"===i?{name:"exponential",base:void 0!==t.base?t.base:1}:null;return {kind:"camera",interpolationType:r,interpolationFactor:pr.interpolationFactor.bind(void 0,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>o(t,e,r,l,u)}}return {kind:"source",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:void 0;return void 0===i?Hn(t.default,e.default):o(t,e,i,l,u)}}}function Hn(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Kn(t,e,r,n,i){return Hn(typeof r===i?n[r]:void 0,t.default,e.default)}function Jn(t,e,r){if("number"!==Gn(r))return Hn(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=sr(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function Wn(t,e,r){const n=void 0!==t.base?t.base:1;if("number"!==Gn(r))return Hn(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=sr(t.stops.map((t=>t[0])),r),a=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),o=t.stops[s][1],l=t.stops[s+1][1],u=dr[e.type]||Zn;return "function"==typeof o.evaluate?{evaluate(...e){const r=o.evaluate.apply(void 0,e),n=l.evaluate.apply(void 0,e);if(void 0!==r&&void 0!==n)return u(r,n,a,t.colorSpace)}}:u(o,l,a,t.colorSpace)}function Qn(t,e,r){switch(e.type){case "color":r=Me.parse(r);break;case "formatted":r=Ce.fromString(r.toString());break;case "resolvedImage":r=De.fromString(r.toString());break;case "padding":r=Ee.parse(r);break;case "colorArray":r=Be.parse(r);break;case "numberArray":r=Te.parse(r);break;default:Gn(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0);}return Hn(r,t.default,e.default)}En.register(Cn,{error:[{kind:"error"},[$t],(t,[e])=>{throw new Ve(e.evaluate(t))}],typeof:[$t,[Ut],(t,[e])=>Kt(Ue(e.evaluate(t)))],"to-rgba":[Ht(Ft,4),[Lt],(t,[e])=>{const[r,n,i,s]=e.evaluate(t).rgb;return [255*r,255*n,255*i,s]}],rgb:[Lt,[Ft,Ft,Ft],Tn],rgba:[Lt,[Ft,Ft,Ft,Ft],Tn],has:{type:Dt,overloads:[[[$t],(t,[e])=>Bn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Bn(e.evaluate(t),r.evaluate(t))]]},get:{type:Ut,overloads:[[[$t],(t,[e])=>Vn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Vn(e.evaluate(t),r.evaluate(t))]]},"feature-state":[Ut,[$t],(t,[e])=>Vn(e.evaluate(t),t.featureState||{})],properties:[Rt,[],t=>t.properties()],"geometry-type":[$t,[],t=>t.geometryType()],id:[Ut,[],t=>t.id()],zoom:[Ft,[],t=>t.globals.zoom],"heatmap-density":[Ft,[],t=>t.globals.heatmapDensity||0],elevation:[Ft,[],t=>t.globals.elevation||0],"line-progress":[Ft,[],t=>t.globals.lineProgress||0],accumulated:[Ut,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[Ft,Fn(Ft),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],"*":[Ft,Fn(Ft),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],"-":{type:Ft,overloads:[[[Ft,Ft],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[Ft],(t,[e])=>-e.evaluate(t)]]},"/":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],"%":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[Ft,[],()=>Math.LN2],pi:[Ft,[],()=>Math.PI],e:[Ft,[],()=>Math.E],"^":[Ft,[Ft,Ft],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[Ft,[Ft],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))],log2:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[Ft,[Ft],(t,[e])=>Math.sin(e.evaluate(t))],cos:[Ft,[Ft],(t,[e])=>Math.cos(e.evaluate(t))],tan:[Ft,[Ft],(t,[e])=>Math.tan(e.evaluate(t))],asin:[Ft,[Ft],(t,[e])=>Math.asin(e.evaluate(t))],acos:[Ft,[Ft],(t,[e])=>Math.acos(e.evaluate(t))],atan:[Ft,[Ft],(t,[e])=>Math.atan(e.evaluate(t))],min:[Ft,Fn(Ft),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[Ft,Fn(Ft),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[Ft,[Ft],(t,[e])=>Math.abs(e.evaluate(t))],round:[Ft,[Ft],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[Ft,[Ft],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[Ft,[Ft],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[Dt,[$t,Ut],(t,[e,r])=>t.properties()[e.value]===r.value],"filter-id-==":[Dt,[Ut],(t,[e])=>t.id()===e.value],"filter-type-==":[Dt,[$t],(t,[e])=>t.geometryType()===e.value],"filter-<":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],"filter-<=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],"filter->=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],"filter-has":[Dt,[Ut],(t,[e])=>e.value in t.properties()],"filter-has-id":[Dt,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[Dt,[Ht($t)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[Dt,[Ht(Ut)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[Dt,[$t,Ht(Ut)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[Dt,[$t,Ht(Ut)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(!r.evaluate(t))return !1;return !0}]]},any:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(r.evaluate(t))return !0;return !1}]]},"!":[Dt,[Dt],(t,[e])=>!e.evaluate(t)],"is-supported-script":[Dt,[$t],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return !r||r(e.evaluate(t))}],upcase:[$t,[$t],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[$t,[$t],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[$t,Fn(Ut),(t,e)=>e.map((e=>je(e.evaluate(t)))).join("")],"resolved-locale":[$t,[jt],(t,[e])=>e.evaluate(t).resolvedLocale()]});class ti{constructor(t,e,r){this.expression=t,this._warningHistory={},this._evaluator=new He,this._defaultValue=e?function(t){if("color"===t.type&&Xn(t.default))return new Me(0,0,0,0);switch(t.type){case "color":return Me.parse(t.default)||null;case "padding":return Ee.parse(t.default)||null;case "numberArray":return Te.parse(t.default)||null;case "colorArray":return Be.parse(t.default)||null;case "variableAnchorOffsetCollection":return $e.parse(t.default)||null;case "projectionDefinition":return Le.parse(t.default)||null;default:return void 0===t.default?null:t.default}}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null,this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s){this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new Ve(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function ei(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Cn}function ri(t,e,r){const n=new Ke(Cn,$n,[],e?function(t){const e={color:Lt,string:$t,number:Ft,enum:$t,boolean:Dt,formatted:Nt,padding:qt,numberArray:Xt,colorArray:Gt,projectionDefinition:Ot,resolvedImage:Zt,variableAnchorOffsetCollection:Yt};return "array"===t.type?Ht(e[t.value]||Ut,t.length):e[t.type]}(e):void 0),i=n.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return i?Rn(new ti(i,e,r)):Un(n.errors)}class ni{constructor(t,e,r){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}}class ii{constructor(t,e,r,n,i){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this.interpolationType=n,this._globalState=i;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?pr.interpolationFactor(this.interpolationType,t,e,r):0}}function si(t,e,r){const n=ri(t,e,r);if("error"===n.result)return n;const i=n.value.expression,s=Dn(i);if(!s&&!jn(e))return Un([new Tt("","data expressions not supported")]);const a=On(i,["zoom"]);if(!a&&!Nn(e))return Un([new Tt("","zoom expressions not supported")]);const o=oi(i);return o||a?o instanceof Tt?Un([o]):o instanceof pr&&!qn(e)?Un([new Tt("",'"interpolate" expressions cannot be used with this property')]):Rn(o?new ii(s?"camera":"composite",n.value,o.labels,o instanceof pr?o.interpolation:void 0,r):new ni(s?"constant":"source",n.value,r)):Un([new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class ai{constructor(t,e){this._parameters=t,this._specification=e,Et(this,Yn(this._parameters,this._specification));}static deserialize(t){return new ai(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function oi(t){let e=null;if(t instanceof Je)e=oi(t.result);else if(t instanceof yr){for(const r of t.args)if(e=oi(r),e)break}else (t instanceof ar||t instanceof pr)&&t.input instanceof En&&"zoom"===t.input.name&&(e=t);return e instanceof Tt||t.eachChild((t=>{const r=oi(t);r instanceof Tt?e=r:!e&&r?e=new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&r&&e!==r&&(e=new Tt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),e}function li(t,e=new Set){return t instanceof Pn&&e.add(t.key),t.eachChild((t=>{li(t,e);})),e}function ui(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case "has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case "in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case "!in":case "!has":case "none":return !1;case "==":case "!=":case ">":case ">=":case "<":case "<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case "any":case "all":for(const e of t.slice(1))if(!ui(e)&&"boolean"!=typeof e)return !1;return !0;default:return !0}}const ci={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function hi(t,e){if(null==t)return {filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};ui(t)||(t=di(t));const r=ri(t,ci,e);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return {filter:(t,e,n)=>r.value.evaluate(t,e,{},n),needGeometry:fi(t),getGlobalStateRefs:()=>li(r.value.expression)}}function pi(t,e){return te?1:0}function fi(t){if(!Array.isArray(t))return !1;if("within"===t[0]||"distance"===t[0])return !0;for(let e=1;e"===e||"<="===e||">="===e?yi(t[1],t[2],e):"any"===e?(r=t.slice(1),["any"].concat(r.map(di))):"all"===e?["all"].concat(t.slice(1).map(di)):"none"===e?["all"].concat(t.slice(1).map(di).map(xi)):"in"===e?mi(t[1],t.slice(2)):"!in"===e?xi(mi(t[1],t.slice(2))):"has"===e?gi(t[1]):"!has"!==e||xi(gi(t[1]));var r;}function yi(t,e,r){switch(t){case "$type":return [`filter-type-${r}`,e];case "$id":return [`filter-id-${r}`,e];default:return [`filter-${r}`,t,e]}}function mi(t,e){if(0===e.length)return !1;switch(t){case "$type":return ["filter-type-in",["literal",e]];case "$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(pi)]]:["filter-in-small",t,["literal",e]]}}function gi(t){switch(t){case "$type":return !0;case "$id":return ["filter-has-id"];default:return ["filter-has",t]}}function xi(t){return ["!",t]}function vi(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const r of t)e+=`${vi(r)},`;return `${e}]`}const r=Object.keys(t).sort();let n="{";for(let e=0;en.maximum?[new Ct(e,r,`${r} is greater than the maximum value ${n.maximum}`)]:[]}function Ii(t){const e=t.valueSpec,r=_i(t.value.type);let n,i,s,a={};const o="categorical"!==r&&void 0===t.value.property,l=!o,u="array"===Gn(t.value.stops)&&"array"===Gn(t.value.stops[0])&&"object"===Gn(t.value.stops[0][0]),c=Ai({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===r)return [new Ct(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const n=t.value;return e=e.concat(ki({key:t.key,value:n,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===Gn(n)&&0===n.length&&e.push(new Ct(t.key,n,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===r&&o&&c.push(new Ct(t.key,t.value,'missing required property "property"')),"identity"===r||t.value.stops||c.push(new Ct(t.key,t.value,'missing required property "stops"')),"exponential"===r&&t.valueSpec.expression&&!qn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!jn(t.valueSpec)?c.push(new Ct(t.key,t.value,"property functions not supported")):o&&!Nn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"zoom functions not supported"))),"categorical"!==r&&!u||void 0!==t.value.property||c.push(new Ct(t.key,t.value,'"property" property is required')),c;function h(t){let r=[];const n=t.value,o=t.key;if("array"!==Gn(n))return [new Ct(o,n,`array expected, ${Gn(n)} found`)];if(2!==n.length)return [new Ct(o,n,`array length 2 expected, length ${n.length} found`)];if(u){if("object"!==Gn(n[0]))return [new Ct(o,n,`object expected, ${Gn(n[0])} found`)];if(void 0===n[0].zoom)return [new Ct(o,n,"object stop key must have zoom")];if(void 0===n[0].value)return [new Ct(o,n,"object stop key must have value")];if(s&&s>_i(n[0].zoom))return [new Ct(o,n[0].zoom,"stop zoom values must appear in ascending order")];_i(n[0].zoom)!==s&&(s=_i(n[0].zoom),i=void 0,a={}),r=r.concat(Ai({key:`${o}[0]`,value:n[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Mi,value:p}}));}else r=r.concat(p({key:`${o}[0]`,value:n[0],validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},n));return ei(Si(n[1]))?r.concat([new Ct(`${o}[1]`,n[1],"expressions are not allowed in function stops.")]):r.concat(t.validateSpec({key:`${o}[1]`,value:n[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const o=Gn(t.value),l=_i(t.value),u=null!==t.value?t.value:s;if(n){if(o!==n)return [new Ct(t.key,u,`${o} stop domain type must match previous stop domain type ${n}`)]}else n=o;if("number"!==o&&"string"!==o&&"boolean"!==o)return [new Ct(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==o&&"categorical"!==r){let n=`number expected, ${o} found`;return jn(e)&&void 0===r&&(n+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new Ct(t.key,u,n)]}return "categorical"!==r||"number"!==o||isFinite(l)&&Math.floor(l)===l?"categorical"!==r&&"number"===o&&void 0!==i&&lnew Ct(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new Ct(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!On(r,["zoom","feature-state"]))return [new Ct(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!Dn(r))return [new Ct(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function Pi(t){const e=t.key,r=t.value,n=Gn(r);return "string"!==n?[new Ct(e,r,`color expected, ${n} found`)]:Me.parse(String(r))?[]:[new Ct(e,r,`color expected, "${r}" found`)]}function Ci(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${n.values.join(", ")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${Object.keys(n.values).join(", ")}], ${JSON.stringify(r)} found`)),i}function Ei(t){return ui(Si(t.value))?zi(Et({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):Ti(t)}function Ti(t){const e=t.value,r=t.key;if("array"!==Gn(e))return [new Ct(r,e,`array expected, ${Gn(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return [new Ct(r,e,"filter array must have at least 1 element")];switch(s=s.concat(Ci({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),_i(e[0])){case "<":case "<=":case ">":case ">=":e.length>=2&&"$type"===_i(e[1])&&s.push(new Ct(r,e,`"$type" cannot be use with operator "${e[0]}"`));case "==":case "!=":3!==e.length&&s.push(new Ct(r,e,`filter array for operator "${e[0]}" must have 3 elements`));case "in":case "!in":e.length>=2&&(i=Gn(e[1]),"string"!==i&&s.push(new Ct(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let a=2;a{t in r&&e.push(new Ct(n,r[t],`"${t}" is prohibited for ref layers`));})),i.layers.forEach((e=>{_i(e.id)===o&&(t=e);})),t?t.ref?e.push(new Ct(n,r.ref,"ref cannot reference another ref layer")):a=_i(t.type):e.push(new Ct(n,r.ref,`ref layer "${o}" not found`));}else if("background"!==a)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&_i(t.type);t?"vector"===s&&"raster"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster source`)):"raster-dem"!==s&&"hillshade"===a||"raster-dem"!==s&&"color-relief"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster-dem source`)):"raster"===s&&"raster"!==a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a vector source`)):"vector"!==s||r["source-layer"]?"raster-dem"===s&&"hillshade"!==a&&"color-relief"!==a?e.push(new Ct(n,r.source,"raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.")):"line"!==a||!r.paint||!r.paint["line-gradient"]||"geojson"===s&&t.lineMetrics||e.push(new Ct(n,r,`layer "${r.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new Ct(n,r,`layer "${r.id}" must specify a "source-layer"`)):e.push(new Ct(n,r.source,`source "${r.source}" not found`));}else e.push(new Ct(n,r,'missing required property "source"'));return e=e.concat(Ai({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:r,objectKey:"type"}),filter:Ei,layout:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Fi(Et({layerType:a},t))}}),paint:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Vi(Et({layerType:a},t))}})}})),e}function Di(t){const e=t.value,r=t.key,n=Gn(e);return "string"!==n?[new Ct(r,e,`string expected, ${n} found`)]:[]}const Li={promoteId:function({key:t,value:e}){if("string"===Gn(e))return Di({key:t,value:e});{const r=[];for(const n in e)r.push(...Di({key:`${t}.${n}`,value:e[n]}));return r}}};function Oi(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return [new Ct(r,e,'"type" is required')];const a=_i(e.type);let o;switch(a){case "vector":case "raster":return o=Ai({key:r,value:e,valueSpec:n[`source_${a.replace("-","_")}`],style:t.style,styleSpec:n,objectElementValidators:Li,validateSpec:s}),o;case "raster-dem":return o=function(t){var e;const r=null!==(e=t.sourceName)&&void 0!==e?e:"",n=t.value,i=t.styleSpec,s=i.source_raster_dem,a=t.style;let o=[];const l=Gn(n);if(void 0===n)return o;if("object"!==l)return o.push(new Ct("source_raster_dem",n,`object expected, ${l} found`)),o;const u="custom"===_i(n.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in n)!u&&c.includes(e)?o.push(new Ct(e,n[e],`In "${r}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?o=o.concat(t.validateSpec({key:e,value:n[e],valueSpec:s[e],validateSpec:t.validateSpec,style:a,styleSpec:i})):o.push(new Ct(e,n[e],`unknown property "${e}"`));return o}({sourceName:r,value:e,style:t.style,styleSpec:n,validateSpec:s}),o;case "geojson":if(o=Ai({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,validateSpec:s,objectElementValidators:Li}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],s="string"==typeof n?[n,["accumulated"],["get",t]]:n;o.push(...zi({key:`${r}.${t}.map`,value:i,expressionContext:"cluster-map"})),o.push(...zi({key:`${r}.${t}.reduce`,value:s,expressionContext:"cluster-reduce"}));}return o;case "video":return Ai({key:r,value:e,valueSpec:n.source_video,style:i,validateSpec:s,styleSpec:n});case "image":return Ai({key:r,value:e,valueSpec:n.source_image,style:i,validateSpec:s,styleSpec:n});case "canvas":return [new Ct(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Ci({key:`${r}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]}})}}function Ri(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("light",e,`object expected, ${a} found`)]),s;for(const a in e){const o=a.match(/^(.*)-transition$/);s=s.concat(o&&n[o[1]]&&n[o[1]].transition?t.validateSpec({key:a,value:e[a],valueSpec:r.transition,validateSpec:t.validateSpec,style:i,styleSpec:r}):n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);}return s}function Ui(t){const e=t.value,r=t.styleSpec,n=r.sky,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("sky",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a}function ji(t){const e=t.value,r=t.styleSpec,n=r.terrain,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("terrain",e,`object expected, ${a} found`)]),s;for(const a in e)s=s.concat(n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);return s}function Ni(t){let e=[];const r=t.value,n=t.key;if(Array.isArray(r)){const i=[],s=[];for(const a in r)r[a].id&&i.includes(r[a].id)&&e.push(new Ct(n,r,`all the sprites' ids must be unique, but ${r[a].id} is duplicated`)),i.push(r[a].id),r[a].url&&s.includes(r[a].url)&&e.push(new Ct(n,r,`all the sprites' URLs must be unique, but ${r[a].url} is duplicated`)),s.push(r[a].url),e=e.concat(Ai({key:`${n}[${a}]`,value:r[a],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:t.validateSpec}));return e}return Di({key:n,value:r})}function qi(t){return e=t.value,Boolean(e)&&e.constructor===Object?[]:[new Ct(t.key,t.value,`object expected, ${Gn(t.value)} found`)];var e;}const Gi={"*":()=>[],array:ki,boolean:function(t){const e=t.value,r=t.key,n=Gn(e);return "boolean"!==n?[new Ct(r,e,`boolean expected, ${n} found`)]:[]},number:Mi,color:Pi,constants:wi,enum:Ci,filter:Ei,function:Ii,layer:$i,object:Ai,source:Oi,light:Ri,sky:Ui,terrain:ji,projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("projection",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a},projectionDefinition:function(t){const e=t.key;let r=t.value;r=r instanceof String?r.valueOf():r;const n=Gn(r);return "array"!==n||function(t){return Array.isArray(t)&&3===t.length&&"string"==typeof t[0]&&"string"==typeof t[1]&&"number"==typeof t[2]}(r)||function(t){return !!["interpolate","step","literal"].includes(t[0])}(r)?["array","string"].includes(n)?[]:[new Ct(e,r,`projection expected, invalid type "${n}" found`)]:[new Ct(e,r,`projection expected, invalid array ${JSON.stringify(r)} found`)]},string:Di,formatted:function(t){return 0===Di(t).length?[]:zi(t)},resolvedImage:function(t){return 0===Di(t).length?[]:zi(t)},padding:function(t){const e=t.key,r=t.value;if("array"===Gn(r)){if(r.length<1||r.length>4)return [new Ct(e,r,`padding requires 1 to 4 values; ${r.length} values found`)];const n={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(r=r.concat(wi({key:"constants",value:t.constants}))),Ki(r)}function Hi(t){return function(e){return t({...e,validateSpec:Xi})}}function Ki(t){return [].concat(t).sort(((t,e)=>t.line-e.line))}function Ji(t){return function(...e){return Ki(t.apply(this,e))}}Yi.source=Ji(Hi(Oi)),Yi.sprite=Ji(Hi(Ni)),Yi.glyphs=Ji(Hi(Zi)),Yi.light=Ji(Hi(Ri)),Yi.sky=Ji(Hi(Ui)),Yi.terrain=Ji(Hi(ji)),Yi.state=Ji(Hi(qi)),Yi.layer=Ji(Hi($i)),Yi.filter=Ji(Hi(Ei)),Yi.paintProperty=Ji(Hi(Vi)),Yi.layoutProperty=Ji(Hi(Fi));const Wi=Yi,Qi=Wi.light,ts=Wi.sky,es=Wi.paintProperty,rs=Wi.layoutProperty;function ns(t,e){let r=!1;if(e&&e.length)for(const n of e)t.fire(new mt(new Error(n.message))),r=!0;return r}class is{constructor(t,e,r){const n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(let t=0;t=u[l+0]&&n>=u[l+1])?(a[h]=!0,s.push(i[h])):a[h]=!1;}}}}_forEachCell(t,e,r,n,i,s,a,o){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!o||o(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,r,n,u,s,a,o))return}}_convertFromCellCoord(t){return (t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let r=0;for(let t=0;t=0)continue;const s=t[n];i[n]=ss[r].shallow.indexOf(n)>=0?s:cs(s,e);}t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==r&&(i.$name=r),i}function hs(t){if(us(t))return t;if(Array.isArray(t))return t.map(hs);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=ls(t)||"Object";if(!ss[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:r}=ss[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const r of Object.keys(t)){if("$name"===r)continue;const i=t[r];n[r]=ss[e].shallow.indexOf(r)>=0?i:hs(i);}return n}class ps{constructor(){this.first=!0;}update(t,e){const r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Hiragana:t=>t>=12352&&t<=12447,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"CJK Unified Ideographs":t=>t>=19968&&t<=40959,"Hangul Syllables":t=>t>=44032&&t<=55215,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function ds(t){for(const e of t)if(bs(e.charCodeAt(0)))return !0;return !1}function ys(t){for(const e of t)if(!xs(e.charCodeAt(0)))return !1;return !0}function ms(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const gs=ms(["Arab","Dupl","Mong","Ougr","Syrc"]);function xs(t){return !gs.test(String.fromCodePoint(t))}const vs=ms(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function bs(t){return !(746!==t&&747!==t&&(t<4352||!(fs["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||fs["CJK Compatibility"](t)||fs["CJK Strokes"](t)||!(!fs["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||fs["Enclosed CJK Letters and Months"](t)||fs["Ideographic Description Characters"](t)||fs.Kanbun(t)||fs.Katakana(t)&&12540!==t||!(!fs["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!fs["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||fs["Vertical Forms"](t)||fs["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||vs.test(String.fromCodePoint(t)))))}function ws(t){return !(bs(t)||function(t){return !!(fs["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||fs["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||fs["Letterlike Symbols"](t)||fs["Number Forms"](t)||fs["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||fs["Control Pictures"](t)&&9251!==t||fs["Optical Character Recognition"](t)||fs["Enclosed Alphanumerics"](t)||fs["Geometric Shapes"](t)||fs["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||fs["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||fs["CJK Symbols and Punctuation"](t)||fs.Katakana(t)||fs["Private Use Area"](t)||fs["CJK Compatibility Forms"](t)||fs["Small Form Variants"](t)||fs["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}const _s=ms(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Ss(t){return _s.test(String.fromCodePoint(t))}function As(t,e){return !(!e&&Ss(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||fs.Khmer(t))}function ks(t){for(const e of t)if(Ss(e.charCodeAt(0)))return !0;return !1}const Ms=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{};}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL;}getState(){return {pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){if(Ms.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText,this.loadScriptResolve();}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(t,r){return e(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if("loading"!==t.pluginStatus)return this.setState(t),t;const e=t.pluginURL,n=new Promise((t=>{this.loadScriptResolve=t;}));r(e);const i=new Promise((t=>setTimeout((()=>t()),this.TIMEOUT)));if(yield Promise.race([n,i]),this.isParsed()){const t={pluginStatus:"loaded",pluginURL:e};return this.setState(t),t}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${e}`)}))}};class Is{constructor(t,e){this.isSupportedScript=zs,this.zoom=t,e?(this.now=e.now||0,this.fadeDuration=e.fadeDuration||0,this.zoomHistory=e.zoomHistory||new ps,this.transition=e.transition||{}):(this.now=0,this.fadeDuration=0,this.zoomHistory=new ps,this.transition={});}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}}}function zs(t){return function(t,e){for(const r of t)if(!As(r.charCodeAt(0),e))return !1;return !0}(t,"loaded"===Ms.getRTLTextPluginStatus())}class Ps{constructor(t,e,r){this.property=t,this.value=e,this.expression=function(t,e,r){if(Xn(t))return new ai(t,e);if(ei(t)){const n=si(t,e,r);if("error"===n.result)throw new Error(n.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return n.value}{let r=t;return "color"===e.type&&"string"==typeof t?r=Me.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"numberArray"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"colorArray"!==e.type||"string"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)?r=$e.parse(t):"projectionDefinition"===e.type&&"string"==typeof t&&(r=Le.parse(t)):r=Be.parse(t):r=Te.parse(t):r=Ee.parse(t),{globalStateRefs:new Set,_globalState:null,kind:"constant",evaluate:()=>r}}}(void 0===e?t.specification.default:e,t.specification,r);}isDataDriven(){return "source"===this.expression.kind||"composite"===this.expression.kind}getGlobalStateRefs(){return this.expression.globalStateRefs||new Set}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class Cs{constructor(t,e){this.property=t,this.value=new Ps(t,void 0,e);}transitioned(t,e){return new Ts(this.property,this.value,e,L({},t.transition,this.transition),t.now)}untransitioned(){return new Ts(this.property,this.value,null,{},0)}}class Es{constructor(t,e){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues),this._globalState=e;}getValue(t){return j(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].value=new Ps(this._values[t].property,null===e?void 0:j(e),this._globalState);}getTransition(t){return j(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].transition=j(e)||void 0;}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r);const n=this.getTransition(e);void 0!==n&&(t[`${e}-transition`]=n);}return t}transitioned(t,e){const r=new Bs(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new Bs(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class Ts{constructor(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(nn.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Rs{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new Is(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Is(Math.floor(e.zoom),e)),t.expression.evaluate(new Is(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Us{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)}interpolate(){return !1}}class js{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const r=t[e];r.specification.overridable&&this.overridableProperties.push(e);const n=this.defaultPropertyValues[e]=new Ps(r,void 0,void 0),i=this.defaultTransitionablePropertyValues[e]=new Cs(r,void 0);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}}}as("DataDrivenProperty",Ls),as("DataConstantProperty",Ds),as("CrossFadedDataDrivenProperty",Os),as("CrossFadedProperty",Rs),as("ColorRampProperty",Us);const Ns="-transition";class qs extends gt{constructor(t,e,r){if(super(),this.id=t.id,this.type=t.type,this._globalState=r,this._featureFilter={filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter,this._featureFilter=hi(t.filter,r)),e.layout&&(this._unevaluatedLayout=new Vs(e.layout,r)),e.paint)){this._transitionablePaint=new Es(e.paint,r);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new $s(e.paint);}}setFilter(t){this.filter=t,this._featureFilter=hi(t,this._globalState);}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}getLayoutAffectingGlobalStateRefs(){const t=new Set;if(this._unevaluatedLayout)for(const e in this._unevaluatedLayout._values){const r=this._unevaluatedLayout._values[e];for(const e of r.getGlobalStateRefs())t.add(e);}for(const e of this._featureFilter.getGlobalStateRefs())t.add(e);return t}getPaintAffectingGlobalStateRefs(){var t;const e=new globalThis.Map;if(this._transitionablePaint)for(const r in this._transitionablePaint._values){const n=this._transitionablePaint._values[r].value;for(const i of n.getGlobalStateRefs()){const s=null!==(t=e.get(i))&&void 0!==t?t:[];s.push({name:r,value:n.value}),e.set(i,s);}}return e}setLayoutProperty(t,e,r={}){null!=e&&this._validate(rs,`layers.${this.id}.layout.${t}`,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);}getPaintProperty(t){return t.endsWith(Ns)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(es,`layers.${this.id}.paint.${t}`,t,e,r))return !1;if(t.endsWith(Ns))return this._transitionablePaint.setTransition(t.slice(0,-11),e||void 0),!1;{const r=this._transitionablePaint._values[t],n="cross-faded-data-driven"===r.property.specification["property-type"],i=r.value.isDataDriven(),s=r.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const a=this._transitionablePaint._values[t].value;return a.isDataDriven()||i||n||this._handleOverridablePaintPropertyUpdate(t,s,a)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,r){return !1}isHidden(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),U(t,((t,e)=>!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return (!i||!1!==i.validate)&&ns(this,t.call(Wi,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:xt,style:{glyphs:!0,sprite:!0}}))}is3D(){return !1}isTileClipped(){return !1}hasOffscreenPass(){return !1}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof Fs&&jn(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1}}const Gs={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Xs{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class Zs{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Ys(t,e=1){let r=0,n=0;return {members:t.map((t=>{const i=Gs[t.type].BYTES_PER_ELEMENT,s=r=Hs(r,Math.max(e,i)),a=t.components||1;return n=Math.max(n,i),r+=i*a,{name:t.name,type:t.type,components:a,offset:s}})),size:Hs(r,Math.max(n,e)),alignment:e}}function Hs(t,e){return Math.ceil(t/e)*e}class Ks extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}Ks.prototype.bytesPerElement=4,as("StructArrayLayout2i4",Ks);class Js extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}Js.prototype.bytesPerElement=6,as("StructArrayLayout3i6",Js);class Ws extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}Ws.prototype.bytesPerElement=8,as("StructArrayLayout4i8",Ws);class Qs extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}Qs.prototype.bytesPerElement=12,as("StructArrayLayout2i4i12",Qs);class ta extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=4*t,l=8*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.uint8[l+4]=n,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=a,t}}ta.prototype.bytesPerElement=8,as("StructArrayLayout2i4ub8",ta);class ea extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}ea.prototype.bytesPerElement=8,as("StructArrayLayout2f8",ea);class ra extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,s,a,o,l,u)}emplace(t,e,r,n,i,s,a,o,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=r,this.uint16[h+2]=n,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=a,this.uint16[h+6]=o,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}ra.prototype.bytesPerElement=20,as("StructArrayLayout10ui20",ra);class na extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,a,o,l,u,c,h)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=a,this.uint16[f+6]=o,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}na.prototype.bytesPerElement=24,as("StructArrayLayout4i4ui4i24",na);class ia extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}ia.prototype.bytesPerElement=12,as("StructArrayLayout3f12",ia);class sa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}sa.prototype.bytesPerElement=4,as("StructArrayLayout1ul4",sa);class aa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,s,a,o,l)}emplace(t,e,r,n,i,s,a,o,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=r,this.int16[c+2]=n,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=a,this.uint32[h+3]=o,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}aa.prototype.bytesPerElement=20,as("StructArrayLayout6i1ul2ui20",aa);class oa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}oa.prototype.bytesPerElement=12,as("StructArrayLayout2i2i2i12",oa);class la extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.int16[o+6]=i,this.int16[o+7]=s,t}}la.prototype.bytesPerElement=16,as("StructArrayLayout2f1f2i16",la);class ua extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=16*t,l=4*t,u=8*t;return this.uint8[o+0]=e,this.uint8[o+1]=r,this.float32[l+1]=n,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=a,t}}ua.prototype.bytesPerElement=16,as("StructArrayLayout2ub2f2i16",ua);class ca extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}ca.prototype.bytesPerElement=6,as("StructArrayLayout3ui6",ca);class ha extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=r,this.uint16[x+2]=n,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=a,this.uint32[v+4]=o,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}ha.prototype.bytesPerElement=48,as("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",ha);class pa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I){const z=this.length;return this.resize(z+1),this.emplace(z,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I,z){const P=32*t,C=16*t;return this.int16[P+0]=e,this.int16[P+1]=r,this.int16[P+2]=n,this.int16[P+3]=i,this.int16[P+4]=s,this.int16[P+5]=a,this.int16[P+6]=o,this.int16[P+7]=l,this.uint16[P+8]=u,this.uint16[P+9]=c,this.uint16[P+10]=h,this.uint16[P+11]=p,this.uint16[P+12]=f,this.uint16[P+13]=d,this.uint16[P+14]=y,this.uint16[P+15]=m,this.uint16[P+16]=g,this.uint16[P+17]=x,this.uint16[P+18]=v,this.uint16[P+19]=b,this.uint16[P+20]=w,this.uint16[P+21]=_,this.uint16[P+22]=S,this.uint32[C+12]=A,this.float32[C+13]=k,this.float32[C+14]=M,this.uint16[P+30]=I,this.uint16[P+31]=z,t}}pa.prototype.bytesPerElement=64,as("StructArrayLayout8i15ui1ul2f2ui64",pa);class fa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}fa.prototype.bytesPerElement=4,as("StructArrayLayout1f4",fa);class da extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}da.prototype.bytesPerElement=12,as("StructArrayLayout1ui2f12",da);class ya extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t}}ya.prototype.bytesPerElement=8,as("StructArrayLayout1ul2ui8",ya);class ma extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}ma.prototype.bytesPerElement=4,as("StructArrayLayout2ui4",ma);class ga extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}ga.prototype.bytesPerElement=2,as("StructArrayLayout1ui2",ga);class xa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}xa.prototype.bytesPerElement=16,as("StructArrayLayout4f16",xa);class va extends Xs{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new r(this.anchorPointX,this.anchorPointY)}}va.prototype.size=20;class ba extends aa{get(t){return new va(this,t)}}as("CollisionBoxArray",ba);class wa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t;}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}wa.prototype.size=48;class _a extends ha{get(t){return new wa(this,t)}}as("PlacedSymbolArray",_a);class Sa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t;}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}Sa.prototype.size=64;class Aa extends pa{get(t){return new Sa(this,t)}}as("SymbolInstanceArray",Aa);class ka extends fa{getoffsetX(t){return this.float32[1*t+0]}}as("GlyphOffsetArray",ka);class Ma extends Js{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}as("SymbolLineVertexArray",Ma);class Ia extends Xs{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}Ia.prototype.size=12;class za extends da{get(t){return new Ia(this,t)}}as("TextAnchorOffsetArray",za);class Pa extends Xs{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}Pa.prototype.size=8;class Ca extends ya{get(t){return new Pa(this,t)}}as("FeatureIndexArray",Ca);class Ea extends Ks{}class Ta extends Ks{}class Ba extends Ks{}class Va extends Qs{}class Fa extends ta{}class $a extends ea{}class Da extends ra{}class La extends na{}class Oa extends ia{}class Ra extends sa{}class Ua extends oa{}class ja extends ua{}class Na extends ca{}class qa extends ma{}const Ga=Ys([{name:"a_pos",components:2,type:"Int16"}],4),{members:Xa}=Ga;class Za{constructor(t=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=t;}prepareSegment(t,e,r,n){const i=this.segments[this.segments.length-1];return t>Za.MAX_VERTEX_ARRAY_LENGTH&&q(`Max vertices per segment is ${Za.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${Za.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!i||i.vertexLength+t>Za.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n?this.createNewSegment(e,r,n):i}createNewSegment(t,e,r){const n={vertexOffset:t.length,primitiveOffset:e.length,vertexLength:0,primitiveLength:0,vaos:{}};return void 0!==r&&(n.sortKey=r),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(n),n}getOrCreateLatestSegment(t,e,r){return this.prepareSegment(0,t,e,r)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0;}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,r,n){return new Za([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function Ya(t,e){return 256*(t=$(Math.floor(t),0,255))+$(Math.floor(e),0,255)}Za.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,as("SegmentVector",Za);const Ha=Ys([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var Ka,Ja,Wa,Qa={exports:{}},to={exports:{}},eo={exports:{}},ro=function(){if(Wa)return Qa.exports;Wa=1;var t=(Ka||(Ka=1,to.exports=function(t,e){var r,n,i,s,a,o,l,u;for(n=t.length-(r=3&t.length),i=e,a=3432918353,o=461845907,u=0;u>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0}),to.exports),e=(Ja||(Ja=1,eo.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0}),eo.exports);return Qa.exports=t,Qa.exports.murmur3=t,Qa.exports.murmur2=e,Qa.exports}(),no=n(ro);class io{constructor(){this.ids=[],this.positions=[],this.indexed=!1;}add(t,e,r,n){this.ids.push(so(t)),this.positions.push(e,r,n);}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=so(t);let r=0,n=this.ids.length-1;for(;r>1;this.ids[t]>=e?n=t:r=t+1;}const i=[];for(;this.ids[r]===e;)i.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return i}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return ao(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}}static deserialize(t){const e=new io;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e}}function so(t){const e=+t;return !isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:no(String(t))}function ao(t,e,r,n){for(;r>1];let s=r-1,a=n+1;for(;;){do{s++;}while(t[s]i);if(s>=a)break;oo(t,s,a),oo(e,3*s,3*a),oo(e,3*s+1,3*a+1),oo(e,3*s+2,3*a+2);}a-r`u_${t}`)),this.type=r;}setUniform(t,e,r){t.set(r.constantOr(this.value));}getBinding(t,e,r){return "color"===this.type?new ho(t,e):new uo(t,e)}}class mo{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;}setUniform(t,e,r,n){const i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);}getBinding(t,e,r){return "u_pattern"===r.substr(0,9)?new co(t,e):new uo(t,e)}}class go{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?2:1,offset:0}))),this.paintVertexArray=new n;}populatePaintArray(t,e,r){const n=this.paintVertexArray.length,i=this.expression.evaluate(new Is(0,r),e,{},r.canonical,[],r.formattedSection);this.paintVertexArray.resize(t),this._setPaintValue(n,t,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(0,i),r,n);this._setPaintValue(t,e,s);}_setPaintValue(t,e,r){if("color"===this.type){const n=fo(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,r){const n=this.expression.evaluate(new Is(this.zoom,r),e,{},r.canonical,[],r.formattedSection),i=this.expression.evaluate(new Is(this.zoom+1,r),e,{},r.canonical,[],r.formattedSection),s=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(s,t,n,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(this.zoom,i),r,n),a=this.expression.evaluate(new Is(this.zoom+1,i),r,n);this._setPaintValue(t,e,s,a);}_setPaintValue(t,e,r,n){if("color"===this.type){const i=fo(r),s=fo(n);for(let r=t;r`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof go||r instanceof xo)for(let e=0;e!0){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new bo(n,e,r);this.needsUpload=!1,this._featureMap=new io,this._bufferOffset=0;}populatePaintArrays(t,e,r,n){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;}updatePaintArrays(t,e,r,n){for(const i of r)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,n)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}function _o(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function So(t,e,r){const n={color:{source:ea,composite:xa},number:{source:fa,composite:ea}},i=function(t){return {"line-pattern":{source:Da,composite:Da},"fill-pattern":{source:Da,composite:Da},"fill-extrusion-pattern":{source:Da,composite:Da}}[t]}(t);return i&&i[r]||n[e][r]}as("ConstantBinder",yo),as("CrossFadedConstantBinder",mo),as("SourceExpressionBinder",go),as("CrossFadedCompositeBinder",vo),as("CompositeExpressionBinder",xo),as("ProgramConfiguration",bo,{omit:["_buffers"]}),as("ProgramConfigurationSet",wo);const Ao=Math.pow(2,14)-1,ko=-Ao-1;function Mo(t){const e=P/t.extent,r=t.loadGeometry();for(let t=0;tr.x+1||sr.y+1)&&q("Geometry exceeds allowed extent, reduce your vector tile buffer size");}}return r}function Io(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?Mo(t):[]}}const zo=-32768;function Po(t,e,r,n,i){t.emplaceBack(zo+8*e+n,zo+8*r+i);}class Co{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Ta,this.indexArray=new Na,this.segments=new Za,this.programConfigurations=new wo(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){const n=this.layers[0],i=[];let s=null,a=!1,o="heatmap"===n.type;if("circle"===n.type){const t=n;s=t.layout.get("circle-sort-key"),a=!s.isConstant(),o=o||"map"===t.paint.get("circle-pitch-alignment");}const l=o?e.subdivisionGranularity.circle:1;for(const{feature:e,id:n,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=a?s.evaluate(u,{},r):void 0,h={id:n,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};i.push(h);}a&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of i){const{geometry:i,index:s,sourceLayerIndex:a}=n,o=t[s].feature;this.addFeature(n,i,s,r,l),e.featureIndex.insert(o,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Xa),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,r,n,i=1){let s;switch(i){case 1:s=[0,7];break;case 3:s=[0,2,5,7];break;case 5:s=[0,1,3,4,6,7];break;case 7:s=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${i}; valid values are 1, 3, 5, 7.`)}const a=s.length;for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=P||n<0||n>=P)continue;const i=this.segments.prepareSegment(a*a,this.layoutVertexArray,this.indexArray,t.sortKey),o=i.vertexLength;for(let t=0;t1){if(Fo(t,e))return !0;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function Oo(t,e){let r,n,i,s=!1;for(let a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s);}return s}function Ro(t,e){let r=!1;for(let n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-s.x)*(e.y-s.y)/(a.y-s.y)+s.x&&(r=!r);}return r}function Uo(t,e,r){const n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;const s=G(t,e,r[0]);return s!==G(t,e,r[1])||s!==G(t,e,r[2])||s!==G(t,e,r[3])}function jo(t,e,r){const n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function No(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function qo(t,e,n,i,s){if(!e[0]&&!e[1])return t;const a=r.convert(e)._mult(s);"viewport"===n&&a._rotate(-i);const o=[];for(let e=0;eKo(t,e,r,n)))}(l,i,a,o),f=u),Ho({queryGeometry:p,size:f,transform:i,unwrappedTileID:a,getElevation:o,pitchAlignment:h,pitchScale:c},n)}}class el extends Co{}let rl;as("HeatmapBucket",el,{omit:["layers"]});var nl={get paint(){return rl=rl||new js({"heatmap-radius":new Ls(xt.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Ls(xt.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Ds(xt.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Us(xt.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Ds(xt.paint_heatmap["heatmap-opacity"])})}};function il(t,{width:e,height:r},n,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*r*n)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*r*n}`)}else i=new Uint8Array(e*r*n);return t.width=e,t.height=r,t.data=i,t}function sl(t,{width:e,height:r},n){if(e===t.width&&r===t.height)return;const i=il({},{width:e,height:r},n);al(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,r)},n),t.width=e,t.height=r,t.data=i.data;}function al(t,e,r,n,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const a=t.data,o=e.data;if(a===o)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=a;const o=t.expression.evaluate(e);i.setPixel(n/4/r,s/4,o);};if(t.clips)for(let e=0,i=0;ethis.max&&(this.max=r),r=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)}unpack(t,e,r){return t*this.redFactor+e*this.greenFactor+r*this.blueFactor-this.baseShift}pack(t){return vl(t,this.getUnpackVector())}getPixels(){return new ll({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,a=r*this.dim+this.dim;switch(e){case -1:n=i-1;break;case 1:i=n+1;}switch(r){case -1:s=a-1;break;case 1:a=s+1;}const o=-e*this.dim,l=-r*this.dim;for(let e=s;e0)for(let i=e;i=e;i-=n)s=Zl(i/n|0,t[i],t[i+1],s);return s&&Ul(s,s.next)&&(Yl(s),s=s.next),s}function Ml(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!Ul(n,n.next)&&0!==Rl(n.prev,n,n.next))n=n.next;else {if(Yl(n),n=e=n.prev,n===n.next)break;r=!0;}}while(r||n!==e);return e}function Il(t,e,r,n,i,s,a){if(!t)return;!a&&s&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=Fl(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let s=null;for(e=0;i;){e++;let a=i,o=0;for(let t=0;t0||l>0&&a;)0!==o&&(0===l||!a||i.z<=a.z)?(n=i,i=i.nextZ,o--):(n=a,a=a.nextZ,l--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;i=a;}s.nextZ=null,r*=2;}while(e>1)}(i);}(t,n,i,s);let o=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?Pl(t,n,i,s):zl(t))e.push(l.i,t.i,u.i),Yl(t),t=u.next,o=u.next;else if((t=u)===o){a?1===a?Il(t=Cl(Ml(t),e),e,r,n,i,s,2):2===a&&El(t,e,r,n,i,s):Il(Ml(t),e,r,n,i,s,1);break}}}function zl(t){const e=t.prev,r=t,n=t.next;if(Rl(e,r,n)>=0)return !1;const i=e.x,s=r.x,a=n.x,o=e.y,l=r.y,u=n.y,c=Math.min(i,s,a),h=Math.min(o,l,u),p=Math.max(i,s,a),f=Math.max(o,l,u);let d=n.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&Ll(i,o,s,l,a,u,d.x,d.y)&&Rl(d.prev,d,d.next)>=0)return !1;d=d.next;}return !0}function Pl(t,e,r,n){const i=t.prev,s=t,a=t.next;if(Rl(i,s,a)>=0)return !1;const o=i.x,l=s.x,u=a.x,c=i.y,h=s.y,p=a.y,f=Math.min(o,l,u),d=Math.min(c,h,p),y=Math.max(o,l,u),m=Math.max(c,h,p),g=Fl(f,d,e,r,n),x=Fl(y,m,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}return !0}function Cl(t,e){let r=t;do{const n=r.prev,i=r.next.next;!Ul(n,i)&&jl(n,r,r.next,i)&&Gl(n,i)&&Gl(i,n)&&(e.push(n.i,r.i,i.i),Yl(r),Yl(r.next),r=t=i),r=r.next;}while(r!==t);return Ml(r)}function El(t,e,r,n,i,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Ol(a,t)){let o=Xl(a,t);return a=Ml(a,a.next),o=Ml(o,o.next),Il(a,e,r,n,i,s,0),void Il(o,e,r,n,i,s,0)}t=t.next;}a=a.next;}while(a!==t)}function Tl(t,e){let r=t.x-e.x;return 0===r&&(r=t.y-e.y,0===r)&&(r=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)),r}function Bl(t,e){const r=function(t,e){let r=e;const n=t.x,i=t.y;let s,a=-1/0;if(Ul(t,r))return r;do{if(Ul(t,r.next))return r.next;if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){const t=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(t<=n&&t>a&&(a=t,s=r.x=r.x&&r.x>=l&&n!==r.x&&Dl(is.x||r.x===s.x&&Vl(s,r)))&&(s=r,c=e);}r=r.next;}while(r!==o);return s}(t,e);if(!r)return e;const n=Xl(r,t);return Ml(n,n.next),Ml(r,r.next)}function Vl(t,e){return Rl(t.prev,t,e.prev)<0&&Rl(e.next,t,t.next)<0}function Fl(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function $l(t){let e=t,r=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(r-a)*(e-o)&&(r-a)*(s-o)>=(i-a)*(n-o)}function Ll(t,e,r,n,i,s,a,o){return !(t===a&&e===o)&&Dl(t,e,r,n,i,s,a,o)}function Ol(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&jl(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(Gl(t,e)&&Gl(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Rl(t.prev,t,e.prev)||Rl(t,e.prev,e))||Ul(t,e)&&Rl(t.prev,t,t.next)>0&&Rl(e.prev,e,e.next)>0)}function Rl(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Ul(t,e){return t.x===e.x&&t.y===e.y}function jl(t,e,r,n){const i=ql(Rl(t,e,r)),s=ql(Rl(t,e,n)),a=ql(Rl(r,n,t)),o=ql(Rl(r,n,e));return i!==s&&a!==o||!(0!==i||!Nl(t,r,e))||!(0!==s||!Nl(t,n,e))||!(0!==a||!Nl(r,t,n))||!(0!==o||!Nl(r,e,n))}function Nl(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function ql(t){return t>0?1:t<0?-1:0}function Gl(t,e){return Rl(t.prev,t,t.next)<0?Rl(t,e,t.next)>=0&&Rl(t,t.prev,e)>=0:Rl(t,e,t.prev)<0||Rl(t,t.next,e)<0}function Xl(t,e){const r=Hl(t.i,t.x,t.y),n=Hl(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function Zl(t,e,r,n){const i=Hl(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Yl(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 Hl(t,e,r){return {i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class Kl{constructor(t,e){if(e>t)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=t,this._minGranularity=e;}getGranularityForZoomLevel(t){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||e>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const r=0|Math.round(t),n=0|Math.round(e),i=this._getKey(r,n);if(this._vertexDictionary.has(i))return this._vertexDictionary.get(i);const s=this._vertexBuffer.length/2;return this._vertexDictionary.set(i,s),this._vertexBuffer.push(r,n),s}_subdivideTrianglesScanline(t){if(this._granularity<2)return function(t,e){const r=[];for(let n=0;n0?(r.push(i),r.push(a),r.push(s)):(r.push(i),r.push(s),r.push(a));}return r}(this._vertexBuffer,t);const e=[],r=t.length;for(let n=0;n=1||v<=0)||y&&(oi)){u>=n&&u<=i&&s.push(r[(t+1)%3]);continue}!y&&x>0&&s.push(this._vertexToIndex(a+p*x,o+f*x));const b=a+p*Math.max(x,0),w=a+p*Math.min(v,1);d||this._generateIntraEdgeVertices(s,a,o,l,u,b,w),!y&&v<1&&s.push(this._vertexToIndex(a+p*v,o+f*v)),(y||u>=n&&u<=i)&&s.push(r[(t+1)%3]),!y&&(u<=n||u>=i)&&this._generateInterEdgeVertices(s,a,o,l,u,c,h,w,n,i);}return s}_generateIntraEdgeVertices(t,e,r,n,i,s,a){const o=n-e,l=i-r,u=0===l,c=u?Math.min(e,n):Math.min(s,a),h=u?Math.max(e,n):Math.max(s,a),p=Math.floor(c/this._granularityCellSize)+1,f=Math.ceil(h/this._granularityCellSize)-1;if(u?e=p;n--){const i=n*this._granularityCellSize;t.push(this._vertexToIndex(i,r+l*(i-e)/o));}}_generateInterEdgeVertices(t,e,r,n,i,s,a,o,l,u){const c=i-r,h=s-n,p=a-i,f=(l-i)/p,d=(u-i)/p,y=Math.min(f,d),m=Math.max(f,d),g=n+h*y;let x=Math.floor(Math.min(g,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(g,o)/this._granularityCellSize)-1,b=o=1||m<=0){const t=r-a,n=s+(e-s)*Math.min((l-a)/t,(u-a)/t);x=Math.floor(Math.min(n,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(n,o)/this._granularityCellSize)-1,b=o0?u:l;if(b)for(let e=x;e<=v;e++)t.push(this._vertexToIndex(e*this._granularityCellSize,_));else for(let e=v;e>=x;e--)t.push(this._vertexToIndex(e*this._granularityCellSize,_));}_generateOutline(t){const e=[];for(const r of t){const t=ru(r,this._granularity,!0),n=this._pointArrayToIndices(t),i=[];for(let t=1;ti!=(s===Wl)?(t.push(e),t.push(r),t.push(this._vertexToIndex(n,s)),t.push(r),t.push(this._vertexToIndex(i,s)),t.push(this._vertexToIndex(n,s))):(t.push(r),t.push(e),t.push(this._vertexToIndex(n,s)),t.push(this._vertexToIndex(i,s)),t.push(r),t.push(this._vertexToIndex(n,s)));}_fillPoles(t,e,r){const n=this._vertexBuffer,i=P,s=t.length;for(let a=2;a80*r){o=t[0],l=t[1];let e=o,n=l;for(let s=r;se&&(e=r),i>n&&(n=i);}u=Math.max(e-o,n-l),u=0!==u?32767/u:0;}return Il(s,a,r,o,l,u,0),a}(r,n),e=this._convertIndices(r,t);i=this._subdivideTrianglesScanline(e);}catch(t){console.error(t);}let s=[];return e&&(s=this._generateOutline(t)),this._ensureNoPoleVertices(),this._handlePoles(i),{verticesFlattened:this._vertexBuffer,indicesTriangles:i,indicesLineList:s}}_convertIndices(t,e){const r=[];for(let n=0;n0?(Math.floor(x/o)+1)*o:(Math.ceil(x/o)-1)*o,e=y>0?(Math.floor(v/o)+1)*o:(Math.ceil(v/o)-1)*o,n=Math.abs(x-t),i=Math.abs(v-e),s=Math.abs(x-c),a=Math.abs(v-h),u=p?n/m:Number.POSITIVE_INFINITY,b=f?i/g:Number.POSITIVE_INFINITY;if((s<=n||!p)&&(a<=i||!f))break;if(u=0?a-1:s-1,i=(o+1)%s,l=t[2*e[n]],u=t[2*e[i]],c=t[2*e[a]],h=t[2*e[a]+1],p=t[2*e[o]+1];let f=!1;if(lu)f=!1;else {const r=p-h,s=-(t[2*e[o]]-c),a=h((u-c)*r+(t[2*e[i]+1]-h)*s)*a&&(f=!0);}if(f){const t=e[n],i=e[a],l=e[o];t!==i&&t!==l&&i!==l&&r.push(l,i,t),a--,a<0&&(a=s-1);}else {const t=e[i],n=e[a],l=e[o];t!==n&&t!==l&&n!==l&&r.push(l,n,t),o++,o>=s&&(o=0);}if(n===i)break}}function iu(t,e,r,n,i,s,a,o,l){const u=i.length/2,c=a&&o&&l;if(uZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,y=!0,m=!0,g=!0,c=0);const x=su(a,n,s,o,p,y,u),v=su(a,n,s,o,f,m,u),b=su(a,n,s,o,d,g,u);r.emplaceBack(c+x-l,c+v-l,c+b-l),u.primitiveLength++;}}(e,r,n,i,s,t),c&&function(t,e,r,n,i,s){const a=[];for(let t=0;tZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,d=!0,y=!0,c=0);const m=su(a,n,s,o,i,d,u),g=su(a,n,s,o,h,y,u);r.emplaceBack(c+m-l,c+g-l),u.primitiveLength++;}}}(a,r,o,i,l,t),e.forceNewSegmentOnNextPrepare(),null==a||a.forceNewSegmentOnNextPrepare();}function su(t,e,r,n,i,s,a){if(s){const s=n.count;return r(e[2*i],e[2*i+1]),t[i]=n.count,n.count++,a.vertexLength++,s}return t[i]}class au{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Ba,this.indexArray=new Na,this.indexArray2=new qa,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.segments2=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("fill",this.layers,e);const n=this.layers[0].layout.get("fill-sort-key"),i=!n.isConstant(),s=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=Io(a,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),c,r))continue;const h=i?n.evaluate(c,{},r,e.availableImages):void 0,p={id:o,properties:a.properties,type:a.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:Mo(a),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("fill",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,_l),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,r,n,i,s){for(const t of Qr(e,500)){const e=eu(t,n,s.fill.getGranularityForZoomLevel(n.z)),r=this.layoutVertexArray;iu(((t,e)=>{r.emplaceBack(t,e);}),this.segments,this.layoutVertexArray,this.indexArray,e.verticesFlattened,e.indicesTriangles,this.segments2,this.indexArray2,e.indicesLineList);}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}}let ou,lu;as("FillBucket",au,{omit:["layers","patternFeatures"]});var uu={get paint(){return lu=lu||new js({"fill-antialias":new Ds(xt.paint_fill["fill-antialias"]),"fill-opacity":new Ls(xt.paint_fill["fill-opacity"]),"fill-color":new Ls(xt.paint_fill["fill-color"]),"fill-outline-color":new Ls(xt.paint_fill["fill-outline-color"]),"fill-translate":new Ds(xt.paint_fill["fill-translate"]),"fill-translate-anchor":new Ds(xt.paint_fill["fill-translate-anchor"]),"fill-pattern":new Os(xt.paint_fill["fill-pattern"])})},get layout(){return ou=ou||new js({"fill-sort-key":new Ls(xt.layout_fill["fill-sort-key"])})}};class cu extends qs{constructor(t,e){super(t,uu,e);}recalculate(t,e){super.recalculate(t,e);const r=this.paint._values["fill-outline-color"];"constant"===r.value.kind&&void 0===r.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);}createBucket(t){return new au(t)}queryRadius(){return No(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:t,geometry:e,transform:r,pixelsToTileUnits:n}){return Bo(qo(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-r.bearingInRadians,n),e)}isTileClipped(){return !0}}const hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),pu=Ys([{name:"a_centroid",components:2,type:"Int16"}],4),{members:fu}=hu;class du{constructor(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this.id=void 0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(yu,this,e);}loadGeometry(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos,n=[];let i,s=1,a=0,o=0,l=0;for(;t.pos>3;}if(a--,1===s||2===s)o+=t.readSVarint(),l+=t.readSVarint(),1===s&&(i&&n.push(i),i=[]),i&&i.push(new r(o,l));else {if(7!==s)throw new Error(`unknown command ${s}`);i&&i.push(i[0].clone());}}return i&&n.push(i),n}bbox(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos;let r=1,n=0,i=0,s=0,a=1/0,o=-1/0,l=1/0,u=-1/0;for(;t.pos>3;}if(n--,1===r||2===r)i+=t.readSVarint(),s+=t.readSVarint(),io&&(o=i),su&&(u=s);else if(7!==r)throw new Error(`unknown command ${r}`)}return [a,l,o,u]}toGeoJSON(t,e,r){const n=this.extent*Math.pow(2,r),i=this.extent*t,s=this.extent*e,a=this.loadGeometry();function o(t){return [360*(t.x+i)/n-180,360/Math.PI*Math.atan(Math.exp((1-2*(t.y+s)/n)*Math.PI))-90]}function l(t){return t.map(o)}let u;if(1===this.type){const t=[];for(const e of a)t.push(e[0]);const e=l(t);u=1===t.length?{type:"Point",coordinates:e[0]}:{type:"MultiPoint",coordinates:e};}else if(2===this.type){const t=a.map(l);u=1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t};}else {if(3!==this.type)throw new Error("unknown feature type");{const t=function(t){const e=t.length;if(e<=1)return [t];const r=[];let n,i;for(let s=0;s=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];const e=this._pbf.readVarint()+this._pbf.pos;return new du(this._pbf,e,this.extent,this._keys,this._values)}}function xu(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){let e=null;const r=t.readVarint()+t.pos;for(;t.pos>3;e=1===r?t.readString():2===r?t.readFloat():3===r?t.readDouble():4===r?t.readVarint64():5===r?t.readVarint():6===r?t.readSVarint():7===r?t.readBoolean():null;}if(null==e)throw new Error("unknown feature value");return e}(r));}class vu{constructor(t,e){this.layers=t.readFields(bu,{},e);}}function bu(t,e,r){if(3===t){const t=new gu(r,r.readVarint()+r.pos);t.length&&(e[t.name]=t);}}const wu=Math.pow(2,13);function _u(t,e,r,n,i,s,a,o){t.emplaceBack(e,r,2*Math.floor(n*wu)+a,i*wu*2,s*wu*2,Math.round(o));}class Su{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Va,this.centroidVertexArray=new Ea,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.features=[],this.hasPattern=Sl("fill-extrusion",this.layers,e);for(const{feature:n,id:i,index:s,sourceLayerIndex:a}of t){const t=this.layers[0]._featureFilter.needGeometry,o=Io(n,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),o,r))continue;const l={id:i,sourceLayerIndex:a,index:s,geometry:t?o.geometry:Mo(n),properties:n.properties,type:n.type,patterns:{}};this.hasPattern?this.features.push(Al("fill-extrusion",this.layers,l,{zoom:this.zoom},e)):this.addFeature(l,l.geometry,s,r,{},e.subdivisionGranularity),e.featureIndex.insert(n,l.geometry,s,a,this.index,!0);}}addFeatures(t,e,r){for(const n of this.features){const{geometry:i}=n;this.addFeature(n,i,n.index,e,r,t.subdivisionGranularity);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,fu),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,pu.members,!0),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy());}addFeature(t,e,r,n,i,s){for(const r of Qr(e,500)){const e={x:0,y:0,sampleCount:0},i=this.layoutVertexArray.length;this.processPolygon(e,n,t,r,s);const a=this.layoutVertexArray.length-i,o=Math.floor(e.x/e.sampleCount),l=Math.floor(e.y/e.sampleCount);for(let t=0;t{_u(u,t,e,0,0,1,1,0);}),this.segments,this.layoutVertexArray,this.indexArray,l.verticesFlattened,l.indicesTriangles);}_generateSideFaces(t,e){let r=0;for(let n=1;nZa.MAX_VERTEX_ARRAY_LENGTH&&(e.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const a=i.sub(s)._perp()._unit(),o=s.dist(i);r+o>32768&&(r=0),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,1,r),r+=o,_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,1,r);const l=e.segment.vertexLength;this.indexArray.emplaceBack(l,l+2,l+1),this.indexArray.emplaceBack(l+1,l+2,l+3),e.segment.vertexLength+=4,e.segment.primitiveLength+=2;}}}function Au(t,e){for(let r=0;rP)||t.y===e.y&&(t.y<0||t.y>P)}function Mu(t){return t.every((t=>t.x<0))||t.every((t=>t.x>P))||t.every((t=>t.y<0))||t.every((t=>t.y>P))}let Iu;as("FillExtrusionBucket",Su,{omit:["layers","features"]});var zu={get paint(){return Iu=Iu||new js({"fill-extrusion-opacity":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Os(xt["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class Pu extends qs{constructor(t,e){super(t,zu,e);}createBucket(t){return new Su(t)}queryRadius(){return No(this.paint.get("fill-extrusion-translate"))}is3D(){return !0}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a,pixelPosMatrix:o}){const l=qo(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-s.bearingInRadians,a),u=this.paint.get("fill-extrusion-height").evaluate(e,n),c=this.paint.get("fill-extrusion-base").evaluate(e,n),h=function(t,e){const n=[];for(const i of t){const t=[i.x,i.y,0,1];A(t,t,e),n.push(new r(t[0]/t[3],t[1]/t[3]));}return n}(l,o),p=function(t,e,n,i){const s=[],a=[],o=i[8]*e,l=i[9]*e,u=i[10]*e,c=i[11]*e,h=i[8]*n,p=i[9]*n,f=i[10]*n,d=i[11]*n;for(const e of t){const t=[],n=[];for(const s of e){const e=s.x,a=s.y,y=i[0]*e+i[4]*a+i[12],m=i[1]*e+i[5]*a+i[13],g=i[2]*e+i[6]*a+i[14],x=i[3]*e+i[7]*a+i[15],v=g+u,b=x+c,w=y+h,_=m+p,S=g+f,A=x+d,k=new r((y+o)/b,(m+l)/b);k.z=v/b,t.push(k);const M=new r(w/A,_/A);M.z=S/A,n.push(M);}s.push(t),a.push(n);}return [s,a]}(i,c,u,o);return function(t,e,r){let n=1/0;Bo(r,e)&&(n=Eu(r,e[0]));for(let i=0;it.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new Fa,this.layoutVertexArray2=new $a,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("line",this.layers,e);const n=this.layers[0].layout.get("line-sort-key"),i=!n.isConstant(),s=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=i?n.evaluate(u,{},r):void 0,h={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("line",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,Fu)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Bu),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return {start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i,s){const a=this.layers[0].layout,o=a.get("line-join").evaluate(t,{}),l=a.get("line-cap"),u=a.get("line-miter-limit"),c=a.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,o,l,u,c,n,s);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}addLine(t,e,r,n,i,s,a,o){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,t=ru(t,a?o.line.getGranularityForZoomLevel(a.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[u-1].equals(t[u-2]);)u--;let c=0;for(;c0;if(w&&e>c){const t=f.dist(d);if(t>2*h){const e=f.sub(f.sub(d)._mult(h/t)._round());this.updateDistance(d,e),this.addCurrentVertex(e,m,0,0,p),d=e;}}const S=d&&y;let A=S?r:l?"butt":n;if(S&&"round"===A&&(vi&&(A="bevel"),"bevel"===A&&(v>2&&(A="flipbevel"),v100)a=g.mult(-1);else {const t=v*m.add(g).mag()/m.sub(g).mag();a._perp()._mult(t*(_?-1:1));}this.addCurrentVertex(f,a,0,0,p),this.addCurrentVertex(f,a.mult(-1),0,0,p);}else if("bevel"===A||"fakeround"===A){const t=-Math.sqrt(v*v-1),e=_?t:0,r=_?0:t;if(d&&this.addCurrentVertex(f,m,e,r,p),"fakeround"===A){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*h){const e=f.add(y.sub(f)._mult(h/t)._round());this.updateDistance(f,e),this.addCurrentVertex(e,g,0,0,p),f=e;}}}}addCurrentVertex(t,e,r,n,i,s=!1){const a=e.y*n-e.x,o=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,!1,r,i),this.addHalfVertex(t,a,o,s,!0,-n,i),this.distance>Du/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,r,n,i,s));}addHalfVertex({x:t,y:e},r,n,i,s,a,o){const l=.5*(this.lineClips?this.scaledDistance*(Du-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,u,this.e2),o.primitiveLength++),s?this.e2=u:this.e1=u;}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}}let Ou,Ru;as("LineBucket",Lu,{omit:["layers","patternFeatures"]});var Uu={get paint(){return Ru=Ru||new js({"line-opacity":new Ls(xt.paint_line["line-opacity"]),"line-color":new Ls(xt.paint_line["line-color"]),"line-translate":new Ds(xt.paint_line["line-translate"]),"line-translate-anchor":new Ds(xt.paint_line["line-translate-anchor"]),"line-width":new Ls(xt.paint_line["line-width"]),"line-gap-width":new Ls(xt.paint_line["line-gap-width"]),"line-offset":new Ls(xt.paint_line["line-offset"]),"line-blur":new Ls(xt.paint_line["line-blur"]),"line-dasharray":new Rs(xt.paint_line["line-dasharray"]),"line-pattern":new Os(xt.paint_line["line-pattern"]),"line-gradient":new Us(xt.paint_line["line-gradient"])})},get layout(){return Ou=Ou||new js({"line-cap":new Ds(xt.layout_line["line-cap"]),"line-join":new Ls(xt.layout_line["line-join"]),"line-miter-limit":new Ds(xt.layout_line["line-miter-limit"]),"line-round-limit":new Ds(xt.layout_line["line-round-limit"]),"line-sort-key":new Ls(xt.layout_line["line-sort-key"])})}};class ju extends Ls{possiblyEvaluate(t,e){return e=new Is(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=L({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}let Nu;class qu extends qs{constructor(t,e){super(t,Uu,e),this.gradientVersion=0,Nu||(Nu=new ju(Uu.paint.properties["line-width"].specification),Nu.useIntegerZoom=!0);}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return void 0!==t._styleExpression}(t)&&t._styleExpression.expression instanceof ar,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=Nu.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t);}createBucket(t){return new Lu(t)}queryRadius(t){const e=t,r=Gu(jo("line-width",this,e),jo("line-gap-width",this,e)),n=jo("line-offset",this,e);return r/2+Math.abs(n)+No(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a}){const o=qo(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-s.bearingInRadians,a),l=a/2*Gu(this.paint.get("line-width").evaluate(e,n),this.paint.get("line-gap-width").evaluate(e,n)),u=this.paint.get("line-offset").evaluate(e,n);return u&&(i=function(t,e){const n=[];for(let i=0;i=3)for(let e=0;e0?e+2*t:t}const Xu=Ys([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Zu=Ys([{name:"a_projected_pos",components:3,type:"Float32"}],4);Ys([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Yu=Ys([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Ys([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const Hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Ku=Ys([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Ju(t,e,r){return t.sections.forEach((t=>{t.text=function(t,e,r){const n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Ms.applyArabicShaping&&(t=Ms.applyArabicShaping(t)),t}(t.text,e,r);})),t}Ys([{name:"triangle",components:3,type:"Uint16"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Ys([{type:"Float32",name:"offsetX"}]),Ys([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Ys([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const Wu={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Qu=24;const tc=4294967296,ec=1/tc,rc="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class nc{constructor(t=new Uint8Array(16)){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length;}readFields(t,e,r=this.length){for(;this.pos>3,i=this.pos;this.type=7&r,t(n,e,this),this.pos===i&&this.skip(r);}return e}readMessage(t,e){return this.readFields(t,e,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*tc;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*tc;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const e=this.buf;let r,n;return n=e[this.pos++],r=127&n,n<128?r:(n=e[this.pos++],r|=(127&n)<<7,n<128?r:(n=e[this.pos++],r|=(127&n)<<14,n<128?r:(n=e[this.pos++],r|=(127&n)<<21,n<128?r:(n=e[this.pos],r|=(15&n)<<28,function(t,e,r){const n=r.buf;let i,s;if(s=n[r.pos++],i=(112&s)>>4,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<3,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<10,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<17,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<24,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(1&s)<<31,s<128)return ic(t,i,e);throw new Error("Expected varint not more than 10 bytes")}(r,t,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2==1?(t+1)/-2:t/2}readBoolean(){return Boolean(this.readVarint())}readString(){const t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&rc?rc.decode(this.buf.subarray(e,t)):function(t,e,r){let n="",i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+u>r)break;1===u?e<128&&(l=e):2===u?(s=t[i+1],128==(192&s)&&(l=(31&e)<<6|63&s,l<=127&&(l=null))):3===u?(s=t[i+1],a=t[i+2],128==(192&s)&&128==(192&a)&&(l=(15&e)<<12|(63&s)<<6|63&a,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===u&&(s=t[i+1],a=t[i+2],o=t[i+3],128==(192&s)&&128==(192&a)&&128==(192&o)&&(l=(15&e)<<18|(63&s)<<12|(63&a)<<6|63&o,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,u=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=u;}return n}(this.buf,e,t)}readBytes(){const t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e}readPackedVarint(t=[],e){const r=this.readPackedEnd();for(;this.pos127;);else if(2===e)this.pos=this.readVarint()+this.pos;else if(5===e)this.pos+=4;else {if(1!==e)throw new Error(`Unimplemented type: ${e}`);this.pos+=8;}}writeTag(t,e){this.writeVarint(t<<3|e);}realloc(t){let e=this.length||16;for(;e268435455||t<0?function(t,e){let r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(r=~(-t%4294967296),n=~(-t/4294967296),4294967295^r?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){const r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(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(t){this.writeVarint(t<0?2*-t-1:2*t);}writeBoolean(t){this.writeVarint(+t);}writeString(t){t=String(t),this.realloc(4*t.length),this.pos++;const e=this.pos;this.pos=function(t,e,r){for(let n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);const r=this.pos-e;r>=128&&sc(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4;}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8;}writeBytes(t){const e=t.length;this.writeVarint(e),this.realloc(e);for(let r=0;r=128&&sc(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;}writeMessage(t,e,r){this.writeTag(t,2),this.writeRawMessage(e,r);}writePackedVarint(t,e){e.length&&this.writeMessage(t,ac,e);}writePackedSVarint(t,e){e.length&&this.writeMessage(t,oc,e);}writePackedBoolean(t,e){e.length&&this.writeMessage(t,cc,e);}writePackedFloat(t,e){e.length&&this.writeMessage(t,lc,e);}writePackedDouble(t,e){e.length&&this.writeMessage(t,uc,e);}writePackedFixed32(t,e){e.length&&this.writeMessage(t,hc,e);}writePackedSFixed32(t,e){e.length&&this.writeMessage(t,pc,e);}writePackedFixed64(t,e){e.length&&this.writeMessage(t,fc,e);}writePackedSFixed64(t,e){e.length&&this.writeMessage(t,dc,e);}writeBytesField(t,e){this.writeTag(t,2),this.writeBytes(e);}writeFixed32Field(t,e){this.writeTag(t,5),this.writeFixed32(e);}writeSFixed32Field(t,e){this.writeTag(t,5),this.writeSFixed32(e);}writeFixed64Field(t,e){this.writeTag(t,1),this.writeFixed64(e);}writeSFixed64Field(t,e){this.writeTag(t,1),this.writeSFixed64(e);}writeVarintField(t,e){this.writeTag(t,0),this.writeVarint(e);}writeSVarintField(t,e){this.writeTag(t,0),this.writeSVarint(e);}writeStringField(t,e){this.writeTag(t,2),this.writeString(e);}writeFloatField(t,e){this.writeTag(t,5),this.writeFloat(e);}writeDoubleField(t,e){this.writeTag(t,1),this.writeDouble(e);}writeBooleanField(t,e){this.writeVarintField(t,+e);}}function ic(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function sc(t,e,r){const n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(let e=r.pos-1;e>=t;e--)r.buf[e+n]=r.buf[e];}function ac(t,e){for(let r=0;re.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();e&&t=0&&r>=t&&kc[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e);}substring(t,e){const r=new Sc;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}getMaxImageSize(t){let e=0,r=0;for(let n=0;n=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Ac(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=Sc.fromFeature(e,s);let g;p===t.ao.vertical&&m.verticalizePunctuation();const{processBidirectionalText:x,processStyledBidirectionalText:v}=Ms;if(x&&1===m.sections.length){g=[];const t=x(m.toString(),Bc(m,c,a,r,i,d));for(const e of t){const t=new Sc;t.text=e,t.sections=m.sections;for(let r=0;r=0;let u=0;for(let r=0;ru){const t=Math.ceil(s/u);i*=t/a,a=t;}return {x1:n,y1:i,x2:n+s,y2:i+a}}function Nc(t,e,r,n,i,s){const a=t.image;let o;if(a.content){const t=a.content,e=a.pixelRatio||1;o=[t[0]/e,t[1]/e,a.displaySize[0]-t[2]/e,a.displaySize[1]-t[3]/e];}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===r||"both"===r?(f=i[0]+l-n[3],h=i[0]+u+n[1]):(f=i[0]+(l+u-a.displaySize[0])/2,h=f+a.displaySize[0]);const d=e.top*s,y=e.bottom*s;return "height"===r||"both"===r?(c=i[1]+d-n[0],p=i[1]+y+n[2]):(c=i[1]+(d+y-a.displaySize[1])/2,p=c+a.displaySize[1]),{image:a,top:c,right:h,bottom:p,left:f,collisionPadding:o}}const qc=128,Gc=32640;function Xc(t,e){const{expression:r}=e;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new Is(t+1))};if("source"===r.kind)return {kind:"source"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;it.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];const r=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Xc(this.zoom,r["text-size"]),this.iconSizeData=Xc(this.zoom,r["icon-size"]);const n=this.layers[0].layout,i=n.get("symbol-sort-key"),s=n.get("symbol-z-order");this.canOverlap="never"!==Zc(n,"text-overlap","text-allow-overlap")||"never"!==Zc(n,"icon-overlap","icon-allow-overlap")||n.get("text-ignore-placement")||n.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!i.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===n.get("symbol-placement")&&(this.writingModes=n.get("text-writing-mode").map((e=>t.ao[e]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID;}createArrays(){this.text=new Wc(new wo(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new Wc(new wo(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new ka,this.lineVertexArray=new Ma,this.symbolInstances=new Aa,this.textAnchorOffsets=new za;}calculateGlyphDependencies(t,e,r,n,i){for(let s=0;s0)&&("constant"!==a.value.kind||a.value.value.length>0),c="constant"!==l.value.kind||!!l.value.value||Object.keys(l.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!u&&!c)return;const p=r.iconDependencies,f=r.glyphDependencies,d=r.availableImages,y=new Is(this.zoom);for(const{feature:r,id:o,index:l,sourceLayerIndex:m}of e){const e=i._featureFilter.needGeometry,g=Io(r,e);if(!i._featureFilter.filter(y,g,n))continue;let x,v;if(e||(g.geometry=Mo(r)),u){const t=i.getValueAndResolveTokens("text-field",g,n,d),e=Ce.factory(t),r=this.hasRTLText=this.hasRTLText||Jc(e);(!r||"unavailable"===Ms.getRTLTextPluginStatus()||r&&Ms.isParsed())&&(x=Ju(e,i,g));}if(c){const t=i.getValueAndResolveTokens("icon-image",g,n,d);v=t instanceof De?t:De.fromString(t);}if(!x&&!v)continue;const b=this.sortFeaturesByKey?h.evaluate(g,{},n):void 0;if(this.features.push({id:o,text:x,icon:v,index:l,sourceLayerIndex:m,geometry:g.geometry,properties:r.properties,type:du.types[r.type],sortKey:b}),v&&(p[v.name]=!0),x){const e=a.evaluate(g,{},n).join(","),r="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(t.ao.vertical)>=0;for(const t of x.sections)if(t.image)p[t.image.name]=!0;else {const n=ds(x.toString()),i=t.fontStack||e,s=f[i]=f[i]||{};this.calculateGlyphDependencies(t.text,s,r,this.allowVerticalPlacement,n);}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++;}function a(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function o(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return `${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}));}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(void 0!==t.segment){let r=t.dist(e[t.segment+1]),n=t.dist(e[t.segment]);const i={};for(let n=t.segment+1;n=0;r--)i[r]={x:e[r].x,y:e[r].y,tileUnitDistanceFromAnchor:n},r>0&&(n+=e[r-1].dist(e[r]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,r)=>{t>=0&&r.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t);})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}let eh,rh;as("SymbolBucket",th,{omit:["layers","collisionBoxArray","features","compareText"]}),th.MAX_GLYPHS=65535,th.addDynamicAttributes=Kc;var nh={get paint(){return rh=rh||new js({"icon-opacity":new Ls(xt.paint_symbol["icon-opacity"]),"icon-color":new Ls(xt.paint_symbol["icon-color"]),"icon-halo-color":new Ls(xt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Ls(xt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Ls(xt.paint_symbol["icon-halo-blur"]),"icon-translate":new Ds(xt.paint_symbol["icon-translate"]),"icon-translate-anchor":new Ds(xt.paint_symbol["icon-translate-anchor"]),"text-opacity":new Ls(xt.paint_symbol["text-opacity"]),"text-color":new Ls(xt.paint_symbol["text-color"],{runtimeType:Lt,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new Ls(xt.paint_symbol["text-halo-color"]),"text-halo-width":new Ls(xt.paint_symbol["text-halo-width"]),"text-halo-blur":new Ls(xt.paint_symbol["text-halo-blur"]),"text-translate":new Ds(xt.paint_symbol["text-translate"]),"text-translate-anchor":new Ds(xt.paint_symbol["text-translate-anchor"])})},get layout(){return eh=eh||new js({"symbol-placement":new Ds(xt.layout_symbol["symbol-placement"]),"symbol-spacing":new Ds(xt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Ds(xt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Ls(xt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Ds(xt.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new Ds(xt.layout_symbol["icon-allow-overlap"]),"icon-overlap":new Ds(xt.layout_symbol["icon-overlap"]),"icon-ignore-placement":new Ds(xt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Ds(xt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Ds(xt.layout_symbol["icon-rotation-alignment"]),"icon-size":new Ls(xt.layout_symbol["icon-size"]),"icon-text-fit":new Ds(xt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Ds(xt.layout_symbol["icon-text-fit-padding"]),"icon-image":new Ls(xt.layout_symbol["icon-image"]),"icon-rotate":new Ls(xt.layout_symbol["icon-rotate"]),"icon-padding":new Ls(xt.layout_symbol["icon-padding"]),"icon-keep-upright":new Ds(xt.layout_symbol["icon-keep-upright"]),"icon-offset":new Ls(xt.layout_symbol["icon-offset"]),"icon-anchor":new Ls(xt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Ds(xt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Ds(xt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Ds(xt.layout_symbol["text-rotation-alignment"]),"text-field":new Ls(xt.layout_symbol["text-field"]),"text-font":new Ls(xt.layout_symbol["text-font"]),"text-size":new Ls(xt.layout_symbol["text-size"]),"text-max-width":new Ls(xt.layout_symbol["text-max-width"]),"text-line-height":new Ds(xt.layout_symbol["text-line-height"]),"text-letter-spacing":new Ls(xt.layout_symbol["text-letter-spacing"]),"text-justify":new Ls(xt.layout_symbol["text-justify"]),"text-radial-offset":new Ls(xt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Ds(xt.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Ls(xt.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Ls(xt.layout_symbol["text-anchor"]),"text-max-angle":new Ds(xt.layout_symbol["text-max-angle"]),"text-writing-mode":new Ds(xt.layout_symbol["text-writing-mode"]),"text-rotate":new Ls(xt.layout_symbol["text-rotate"]),"text-padding":new Ds(xt.layout_symbol["text-padding"]),"text-keep-upright":new Ds(xt.layout_symbol["text-keep-upright"]),"text-transform":new Ls(xt.layout_symbol["text-transform"]),"text-offset":new Ls(xt.layout_symbol["text-offset"]),"text-allow-overlap":new Ds(xt.layout_symbol["text-allow-overlap"]),"text-overlap":new Ds(xt.layout_symbol["text-overlap"]),"text-ignore-placement":new Ds(xt.layout_symbol["text-ignore-placement"]),"text-optional":new Ds(xt.layout_symbol["text-optional"])})}};class ih{constructor(t){if(void 0===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:Vt,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return !1}serialize(){return null}}as("FormatSectionOverride",ih,{omit:["defaultValue"]});class sh extends qs{constructor(t,e){super(t,nh,e);}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const r of t)e.indexOf(r)<0&&e.push(r);this.layout._values["text-writing-mode"]=e;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||ei(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>t&&r in t?String(t[r]):""))}(e.properties,i)}createBucket(t){return new th(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of nh.paint.overridableProperties){if(!sh.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new ih(e),n=new ti(r,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new ni("source",n):new ii("composite",n,e.value.zoomStops),this.paint._values[t]=new Fs(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,r){return !(!this.layout||e.isDataDriven()||r.isDataDriven())&&sh.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get("text-field"),n=nh.paint.properties[e];let i=!1;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=!0)};if("constant"===r.value.kind&&r.value.value instanceof Ce)s(r.value.value.sections);else if("source"===r.value.kind||"composite"===r.value.kind){const t=e=>{i||(e instanceof Ne&&Ue(e.value)===Nt?s(e.value.sections):e instanceof Ir?s(e.sections):e.eachChild(t));},e=r.value;e._styleExpression&&t(e._styleExpression.expression);}return i}}let ah;var oh={get paint(){return ah=ah||new js({"background-color":new Ds(xt.paint_background["background-color"]),"background-pattern":new Rs(xt.paint_background["background-pattern"]),"background-opacity":new Ds(xt.paint_background["background-opacity"])})}};class lh extends qs{constructor(t,e){super(t,oh,e);}}let uh;var ch={get paint(){return uh=uh||new js({"raster-opacity":new Ds(xt.paint_raster["raster-opacity"]),"raster-hue-rotate":new Ds(xt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Ds(xt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Ds(xt.paint_raster["raster-brightness-max"]),"raster-saturation":new Ds(xt.paint_raster["raster-saturation"]),"raster-contrast":new Ds(xt.paint_raster["raster-contrast"]),"raster-resampling":new Ds(xt.paint_raster["raster-resampling"]),"raster-fade-duration":new Ds(xt.paint_raster["raster-fade-duration"])})}};class hh extends qs{constructor(t,e){super(t,ch,e);}}class ph extends qs{constructor(t,e){super(t,{},e),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},this.implementation=t;}is3D(){return "3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return !1}serialize(){throw new Error("Custom layers cannot be serialized")}}class fh{constructor(t){this._methodToThrottle=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle();});}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle();}),0));}remove(){delete this._channel,this._methodToThrottle=()=>{};}}const dh={once:!0},yh=6371008.8;class mh{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new mh(D(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return yh*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof mh)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new mh(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new mh(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const gh=2*Math.PI*yh;function xh(t){return gh*Math.cos(t*Math.PI/180)}function vh(t){return (180+t)/360}function bh(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function wh(t,e){return t/xh(e)}function _h(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}function Sh(t,e){return t*xh(_h(e))}class Ah{constructor(t,e,r=0){this.x=+t,this.y=+e,this.z=+r;}static fromLngLat(t,e=0){const r=mh.convert(t);return new Ah(vh(r.lng),bh(r.lat),wh(e,r.lat))}toLngLat(){return new mh(360*this.x-180,_h(this.y))}toAltitude(){return Sh(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/gh*(t=_h(this.y),1/Math.cos(t*Math.PI/180));var t;}}function kh(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}class Mh{constructor(t,e,r){if(!function(t,e,r){return !(t<0||t>25||r<0||r>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,r))throw new Error(`x=${e}, y=${r}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=r,this.key=Ph(0,t,t,e,r);}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,r){const n=(s=this.y,a=this.z,o=kh(256*(i=this.x),256*(s=Math.pow(2,a)-s-1),a),l=kh(256*(i+1),256*(s+1),a),o[0]+","+o[1]+","+l[0]+","+l[1]);var i,s,a,o,l;const u=function(t,e,r){let n,i="";for(let s=t;s>0;s--)n=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,n)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new r((t.x*e-this.x)*P,(t.y*e-this.y)*P)}toString(){return `${this.z}/${this.x}/${this.y}`}}class Ih{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Ph(t,e.z,e.z,e.x,e.y);}}class zh{constructor(t,e,r,n,i){if(this.terrainRttPosMatrix32f=null,t= z; overscaledZ = ${t}; z = ${r}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Mh(r,+n,+i),this.key=Ph(e,t,r,n,i);}clone(){return new zh(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new zh(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new zh(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const r=this.canonical.z-t;return t>this.canonical.z?Ph(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Ph(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}isChildOf(t){if(t.wrap!==this.wrap)return !1;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new zh(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new zh(e,this.wrap,e,r,n),new zh(e,this.wrap,e,r+1,n),new zh(e,this.wrap,e,r,n+1),new zh(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.ythis.maxX||this.minY>this.maxY)&&(this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0),this}shrinkBy(t){return this.expandBy(-t)}map(t){const e=new Eh;return e.extend(t(new r(this.minX,this.minY))),e.extend(t(new r(this.maxX,this.minY))),e.extend(t(new r(this.minX,this.maxY))),e.extend(t(new r(this.maxX,this.maxY))),e}static fromPoints(t){const e=new Eh;for(const r of t)e.extend(r);return e}contains(t){return t.x>=this.minX&&t.x<=this.maxX&&t.y>=this.minY&&t.y<=this.maxY}empty(){return this.minX>this.maxX}width(){return this.maxX-this.minX}height(){return this.maxY-this.minY}covers(t){return !this.empty()&&!t.empty()&&t.minX>=this.minX&&t.maxX<=this.maxX&&t.minY>=this.minY&&t.maxY<=this.maxY}intersects(t){return !this.empty()&&!t.empty()&&t.minX<=this.maxX&&t.maxX>=this.minX&&t.minY<=this.maxY&&t.maxY>=this.minY}}class Th{constructor(t){this._stringToNumber={},this._numberToString=[];for(let e=0;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class Bh{constructor(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}class Vh{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new is(P,16,0),this.grid3D=new is(P,16,0),this.featureIndexArray=new Ca,this.promoteId=e;}insert(t,e,r,n,i,s){const a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);const o=s?this.grid3D:this.grid;for(let t=0;t=0&&n[3]>=0&&o.insert(a,n[0],n[1],n[2],n[3]);}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new vu(new nc(this.rawTileData)).layers,this.sourceLayerCoder=new Th(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,n,i){this.loadVTLayers();const s=t.params,a=P/t.tileSize/t.scale,o=hi(s.filter,s.globalState),l=t.queryGeometry,u=t.queryPadding*a,c=Eh.fromPoints(l),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=Eh.fromPoints(t.cameraQueryGeometry).expandBy(u),f=this.grid3D.query(p.minX,p.minY,p.maxX,p.maxY,((e,n,i,s)=>function(t,e,n,i,s){for(const r of t)if(e<=r.x&&n<=r.y&&i>=r.x&&s>=r.y)return !0;const a=[new r(e,n),new r(e,s),new r(i,s),new r(i,n)];if(t.length>2)for(const e of a)if(Ro(t,e))return !0;for(let e=0;e(p||(p=Mo(e)),r.queryIntersectsFeature({queryGeometry:l,feature:e,featureState:n,geometry:p,zoom:this.z,transform:t.transform,pixelsToTileUnits:a,pixelPosMatrix:t.pixelPosMatrix,unwrappedTileID:this.tileID.toUnwrapped(),getElevation:t.getElevation}))));}return d}loadMatchingFeature(t,e,r,n,i,s,a,o,l,u,c){const h=this.bucketLayerIDs[e];if(s&&!h.some((t=>s.has(t))))return;const p=this.sourceLayerCoder.decode(r),f=this.vtLayers[p].feature(n);if(i.needGeometry){const t=Io(f,!0);if(!i.filter(new Is(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new Is(this.tileID.overscaledZ),f))return;const d=this.getId(f,p);for(let e=0;e{const a=e instanceof $s?e.get(s):null;return a&&a.evaluate?a.evaluate(r,n,i):a}))}function $h(t,e){return e-t}function Dh(t,e,n,i,s){const a=[];for(let o=0;o=i&&c.x>=i||(o.x>=i?o=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round():c.x>=i&&(c=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round()),o.y>=s&&c.y>=s||(o.y>=s?o=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round():c.y>=s&&(c=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round()),u&&o.equals(u[u.length-1])||(u=[o],a.push(u)),u.push(c)))));}}return a}as("FeatureIndex",Vh,{omit:["rawTileData","sourceLayerCoder"]});class Lh extends r{constructor(t,e,r,n){super(t,e),this.angle=r,void 0!==n&&(this.segment=n);}clone(){return new Lh(this.x,this.y,this.angle,this.segment)}}function Oh(t,e,r,n,i){if(void 0===e.segment||0===r)return !0;let s=e,a=e.segment+1,o=0;for(;o>-r/2;){if(a--,a<0)return !1;o-=t[a].dist(s),s=t[a];}o+=t[a].dist(t[a+1]),a++;const l=[];let u=0;for(;on;)u-=l.shift().angleDelta;if(u>i)return !1;a++,o+=e.dist(r);}return !0}function Rh(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=dr.number(n.x,i.x,c),p=dr.number(n.y,i.y,c),f=new Lh(h,p,i.angleTo(n),r);return f._round(),!a||Oh(t,f,o,a,e)?f:void 0}l+=s;}}function qh(t,e,r,n,i,s,a,o,l){const u=Uh(n,s,a),c=jh(n,i),h=c*a,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new Lh(g,x,y,e);r._round(),n&&!Oh(t,r,s,n,i)||f.push(r);}}h+=d;}return o||f.length||a||(f=Gh(t,h/2,r,n,i,s,a,!0,l)),f}function Xh(t,e,n,i){const s=[],a=t.image,o=a.pixelRatio,l=a.paddedRect.w-2,u=a.paddedRect.h-2;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=a.stretchX||[[0,l]],p=a.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=l-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,S=m,A=0,k=g;if(a.content&&i){const e=a.content,r=e[2]-e[0],n=e[3]-e[1];(a.textFitWidth||a.textFitHeight)&&(c=jc(t)),x=Zh(h,0,e[0]),b=Zh(p,0,e[1]),v=Zh(h,e[0],e[2]),w=Zh(p,e[1],e[3]),_=e[0]-x,A=e[1]-b,S=r-v,k=n-w;}const M=c.x1,I=c.y1,z=c.x2-M,P=c.y2-I,C=(t,i,s,l)=>{const u=Hh(t.stretch-x,v,z,M),c=Kh(t.fixed-_,S,t.stretch,d),h=Hh(i.stretch-b,w,P,I),p=Kh(i.fixed-A,k,i.stretch,y),f=Hh(s.stretch-x,v,z,M),m=Kh(s.fixed-_,S,s.stretch,d),g=Hh(l.stretch-b,w,P,I),C=Kh(l.fixed-A,k,l.stretch,y),E=new r(u,h),T=new r(f,h),B=new r(f,g),V=new r(u,g),F=new r(c/o,p/o),$=new r(m/o,C/o),D=e*Math.PI/180;if(D){const t=Math.sin(D),e=Math.cos(D),r=[e,-t,t,e];E._matMult(r),T._matMult(r),V._matMult(r),B._matMult(r);}const L=t.stretch+t.fixed,O=i.stretch+i.fixed;return {tl:E,tr:T,bl:V,br:B,tex:{x:a.paddedRect.x+1+L,y:a.paddedRect.y+1+O,w:s.stretch+s.fixed-L,h:l.stretch+l.fixed-O},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:F,pixelOffsetBR:$,minFontScaleX:S/o/z,minFontScaleY:k/o/P,isSDF:n}};if(i&&(a.stretchX||a.stretchY)){const t=Yh(h,m,d),e=Yh(p,g,y);for(let r=0;r0&&(n=Math.max(10,n),this.circleDiameter=n);}else {const u=(null===(h=a.image)||void 0===h?void 0:h.content)&&(a.image.textFitWidth||a.image.textFitHeight)?jc(a):{x1:a.left,y1:a.top,x2:a.right,y2:a.bottom};u.y1=u.y1*o-l[0],u.y2=u.y2*o+l[2],u.x1=u.x1*o-l[3],u.x2=u.x2*o+l[1];const p=a.collisionPadding;if(p&&(u.x1-=p[0]*o,u.y1-=p[1]*o,u.x2+=p[2]*o,u.y2+=p[3]*o),c){const t=new r(u.x1,u.y1),e=new r(u.x2,u.y1),n=new r(u.x1,u.y2),i=new r(u.x2,u.y2),s=c*Math.PI/180;t._rotate(s),e._rotate(s),n._rotate(s),i._rotate(s),u.x1=Math.min(t.x,e.x,n.x,i.x),u.x2=Math.max(t.x,e.x,n.x,i.x),u.y1=Math.min(t.y,e.y,n.y,i.y),u.y2=Math.max(t.y,e.y,n.y,i.y);}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,n,i,s);}this.boxEndIndex=t.length;}}class Wh{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}}function Qh(t,e=1,n=!1){const i=Eh.fromPoints(t[0]),s=Math.min(i.width(),i.height());let a=s/2;const o=new Wh([],tp),{minX:l,minY:u,maxX:c,maxY:h}=i;if(0===s)return new r(l,u);for(let e=l;ep.d||!p.d)&&(p=r,n&&console.log("found best %d after %d probes",Math.round(1e4*r.d)/1e4,f)),r.max-p.d<=e||(a=r.h/2,o.push(new ep(r.p.x-a,r.p.y-a,a,t)),o.push(new ep(r.p.x+a,r.p.y-a,a,t)),o.push(new ep(r.p.x-a,r.p.y+a,a,t)),o.push(new ep(r.p.x+a,r.p.y+a,a,t)),f+=4);}return n&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function tp(t,e){return e.max-t.max}function ep(t,e,n,i){this.p=new r(t,e),this.h=n,this.d=function(t,e){let r=!1,n=1/0;for(let i=0;it.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(r=!r),n=Math.min(n,Lo(t,i,o));}}return (r?1:-1)*Math.sqrt(n)}(this.p,i),this.max=this.d+this.h*Math.SQRT2;}var rp;t.aE=void 0,(rp=t.aE||(t.aE={}))[rp.center=1]="center",rp[rp.left=2]="left",rp[rp.right=3]="right",rp[rp.top=4]="top",rp[rp.bottom=5]="bottom",rp[rp["top-left"]=6]="top-left",rp[rp["top-right"]=7]="top-right",rp[rp["bottom-left"]=8]="bottom-left",rp[rp["bottom-right"]=9]="bottom-right";const np=Number.POSITIVE_INFINITY;function ip(t,e){return e[1]!==np?function(t,e,r){let n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case "top-right":case "top-left":case "top":i=r-7;break;case "bottom-right":case "bottom-left":case "bottom":i=7-r;}switch(t){case "top-right":case "bottom-right":case "right":n=-e;break;case "top-left":case "bottom-left":case "left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){let r=0,n=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case "top-right":case "top-left":n=i-7;break;case "bottom-right":case "bottom-left":n=7-i;break;case "bottom":n=7-e;break;case "top":n=e-7;}switch(t){case "top-right":case "bottom-right":r=-i;break;case "top-left":case "bottom-left":r=i;break;case "left":r=e;break;case "right":r=-e;}return [r,n]}(t,e[0])}function sp(t,e,r){var n;const i=t.layout,s=null===(n=i.get("text-variable-anchor-offset"))||void 0===n?void 0:n.evaluate(e,{},r);if(s){const t=s.values,e=[];for(let r=0;rt*Qu));n.startsWith("top")?i[1]-=7:n.startsWith("bottom")&&(i[1]+=7),e[r+1]=i;}return new $e(e)}const a=i.get("text-variable-anchor");if(a){let n;n=void 0!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},r)*Qu,np]:i.get("text-offset").evaluate(e,{},r).map((t=>t*Qu));const s=[];for(const t of a)s.push(t,ip(t,n));return new $e(s)}return null}function ap(t){switch(t){case "right":case "top-right":case "bottom-right":return "right";case "left":case "top-left":case "bottom-left":return "left"}return "center"}function op(e,r,n,i,s,a,o,l,u,c,h,p){let f=a.textMaxSize.evaluate(r,{});void 0===f&&(f=o);const d=e.layers[0].layout,y=d.get("icon-offset").evaluate(r,{},h),m=up(n.horizontal),g=o/24,x=e.tilePixelRatio*g,v=e.tilePixelRatio*f/24,b=e.tilePixelRatio*l,w=e.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*e.tilePixelRatio,S=function(t,e,r,n=1){const i=t.get("icon-padding").evaluate(e,{},r),s=i&&i.values;return [s[0]*n,s[1]*n,s[2]*n,s[3]*n]}(d,r,h,e.tilePixelRatio),A=d.get("text-max-angle")/180*Math.PI,k="viewport"!==d.get("text-rotation-alignment")&&"point"!==d.get("symbol-placement"),M="map"===d.get("icon-rotation-alignment")&&"point"!==d.get("symbol-placement"),I=d.get("symbol-placement"),z=w/2,C=d.get("icon-text-fit");let E;i&&"none"!==C&&(e.allowVerticalPlacement&&n.vertical&&(E=Nc(i,n.vertical,C,d.get("icon-text-fit-padding"),y,g)),m&&(i=Nc(i,m,C,d.get("icon-text-fit-padding"),y,g)));const T=h?p.line.getGranularityForZoomLevel(h.z):1,B=(l,p)=>{p.x<0||p.x>=P||p.y<0||p.y>=P||function(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k){const M=e.addToLineVertexArray(r,n);let I,z,P,C,E=0,T=0,B=0,V=0,F=-1,$=-1;const D={};let L=no("");if(e.allowVerticalPlacement&&i.vertical){const t=l.layout.get("text-rotate").evaluate(w,{},A)+90;P=new Jh(u,r,c,h,p,i.vertical,f,d,y,t),o&&(C=new Jh(u,r,c,h,p,o,g,x,y,t));}if(s){const n=l.layout.get("icon-rotate").evaluate(w,{}),i="none"!==l.layout.get("icon-text-fit"),a=Xh(s,n,S,i),f=o?Xh(o,n,S,i):void 0;z=new Jh(u,r,c,h,p,s,g,x,!1,n),E=4*a.length;const d=e.iconSizeData;let y=null;"source"===d.kind?(y=[qc*l.layout.get("icon-size").evaluate(w,{})],y[0]>Gc&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)):"composite"===d.kind&&(y=[qc*_.compositeIconSizes[0].evaluate(w,{},A),qc*_.compositeIconSizes[1].evaluate(w,{},A)],(y[0]>Gc||y[1]>Gc)&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)),e.addSymbols(e.icon,a,y,b,v,w,t.ao.none,r,M.lineStartIndex,M.lineLength,-1,A),F=e.icon.placedSymbolArray.length-1,f&&(T=4*f.length,e.addSymbols(e.icon,f,y,b,v,w,t.ao.vertical,r,M.lineStartIndex,M.lineLength,-1,A),$=e.icon.placedSymbolArray.length-1);}const O=Object.keys(i.horizontal);for(const n of O){const s=i.horizontal[n];if(!I){L=no(s.text);const t=l.layout.get("text-rotate").evaluate(w,{},A);I=new Jh(u,r,c,h,p,s,f,d,y,t);}const o=1===s.positionedLines.length;if(B+=lp(e,r,s,a,l,y,w,m,M,i.vertical?t.ao.horizontal:t.ao.horizontalOnly,o?O:[n],D,F,_,A),o)break}i.vertical&&(V+=lp(e,r,i.vertical,a,l,y,w,m,M,t.ao.vertical,["vertical"],D,$,_,A));const R=I?I.boxStartIndex:e.collisionBoxArray.length,U=I?I.boxEndIndex:e.collisionBoxArray.length,j=P?P.boxStartIndex:e.collisionBoxArray.length,N=P?P.boxEndIndex:e.collisionBoxArray.length,G=z?z.boxStartIndex:e.collisionBoxArray.length,X=z?z.boxEndIndex:e.collisionBoxArray.length,Z=C?C.boxStartIndex:e.collisionBoxArray.length,Y=C?C.boxEndIndex:e.collisionBoxArray.length;let H=-1;const K=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=K(I,H),H=K(P,H),H=K(z,H),H=K(C,H);const J=H>-1?1:0;J&&(H*=k/Qu),e.glyphOffsetArray.length>=th.MAX_GLYPHS&&q("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==w.sortKey&&e.addToSortKeyRanges(e.symbolInstances.length,w.sortKey);const W=sp(l,w,A),[Q,tt]=function(e,r){const n=e.length,i=null==r?void 0:r.values;if((null==i?void 0:i.length)>0)for(let r=0;r=0?D.right:-1,D.center>=0?D.center:-1,D.left>=0?D.left:-1,D.vertical||-1,F,$,L,R,U,j,N,G,X,Z,Y,c,B,V,E,T,J,0,f,H,Q,tt);}(e,p,l,n,i,s,E,e.layers[0],e.collisionBoxArray,r.index,r.sourceLayerIndex,e.index,x,[_,_,_,_],k,u,b,S,M,y,r,a,c,h,o);};if("line"===I)for(const t of Dh(r.geometry,0,0,P,P)){const r=ru(t,T),s=qh(r,w,A,n.vertical||m,i,24,v,e.overscaling,P);for(const t of s)m&&cp(e,m.text,z,t)||B(r,t);}else if("line-center"===I){for(const t of r.geometry)if(t.length>1){const e=ru(t,T),r=Nh(e,A,n.vertical||m,i,24,v);r&&B(e,r);}}else if("Polygon"===r.type)for(const t of Qr(r.geometry,0)){const e=Qh(t,16);B(ru(t[0],T,!0),new Lh(e.x,e.y,0));}else if("LineString"===r.type)for(const t of r.geometry){const e=ru(t,T);B(e,new Lh(e[0].x,e[0].y,0));}else if("Point"===r.type)for(const t of r.geometry)for(const e of t)B([e],new Lh(e.x,e.y,0));}function lp(t,e,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=function(t,e,n,i,s,a,o,l){const u=i.layout.get("text-rotate").evaluate(a,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const i of t.positionedGlyphs){if(!i.rect)continue;const a=i.rect||{};let h=4,p=!0,f=1,d=0;const y=(s||l)&&i.vertical,m=i.metrics.advance*i.scale/2;if(l&&e.verticalizable&&(d=t.lineOffset/2-(i.imageName?-(Qu-i.metrics.width*i.scale)/2:(i.scale-1)*Qu)),i.imageName){const t=o[i.imageName];p=t.sdf,f=t.pixelRatio,h=1/f;}const g=s?[i.x+m,i.y]:[0,0];let x=s?[0,0]:[i.x+m+n[0],i.y+n[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=i.metrics.isDoubleResolution?2:1,w=(i.metrics.left-h)*i.scale-m+x[0],_=(-i.metrics.top-h)*i.scale+x[1],S=w+a.w/b*i.scale/f,A=_+a.h/b*i.scale/f,k=new r(w,_),M=new r(S,_),I=new r(w,A),z=new r(S,A);if(y){const t=new r(-m,m- -17),e=-Math.PI/2,n=12-m,s=new r(22-n,-(i.imageName?n:0)),a=new r(...v);k._rotateAround(e,t)._add(s)._add(a),M._rotateAround(e,t)._add(s)._add(a),I._rotateAround(e,t)._add(s)._add(a),z._rotateAround(e,t)._add(s)._add(a);}if(u){const t=Math.sin(u),e=Math.cos(u),r=[e,-t,t,e];k._matMult(r),M._matMult(r),I._matMult(r),z._matMult(r);}const P=new r(0,0),C=new r(0,0);c.push({tl:k,tr:M,bl:I,br:z,tex:a,writingMode:e.writingMode,glyphOffset:g,sectionIndex:i.sectionIndex,isSDF:p,pixelOffsetTL:P,pixelOffsetBR:C,minFontScaleX:0,minFontScaleY:0});}return c}(0,n,l,s,a,o,i,t.allowVerticalPlacement),g=t.textSizeData;let x=null;"source"===g.kind?(x=[qc*s.layout.get("text-size").evaluate(o,{})],x[0]>Gc&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)):"composite"===g.kind&&(x=[qc*d.compositeTextSizes[0].evaluate(o,{},y),qc*d.compositeTextSizes[1].evaluate(o,{},y)],(x[0]>Gc||x[1]>Gc)&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)),t.addSymbols(t.text,m,x,l,a,o,c,e,u.lineStartIndex,u.lineLength,f,y);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*m.length}function up(t){for(const e in t)return t[e];return null}function cp(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=hp[15&r];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new pp(a,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=hp.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+s+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return fp(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,r,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:a}=this,o=[0,i.length-1,0],l=[];for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=a){for(let a=h;a<=c;a++){const o=s[2*a],u=s[2*a+1];o>=t&&o<=r&&u>=e&&u<=n&&l.push(i[a]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?r>=f:n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return l}within(t,e,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:n,coords:i,nodeSize:s}=this,a=[0,n.length-1,0],o=[],l=r*r;for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)gp(i[2*r],i[2*r+1],t,e)<=l&&o.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];gp(f,d,t,e)<=l&&o.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return o}}function fp(t,e,r,n,i,s){if(i-n<=r)return;const a=n+i>>1;dp(t,e,a,n,i,s),fp(t,e,r,n,a-1,1-s),fp(t,e,r,a+1,i,1-s);}function dp(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const a=i-n+1,o=r-n+1,l=Math.log(a),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(a-u)/a)*(o-a/2<0?-1:1);dp(t,e,r,Math.max(n,Math.floor(r-o*u/a+c)),Math.min(i,Math.floor(r+(a-o)*u/a+c)),s);}const a=e[2*r+s];let o=n,l=i;for(yp(t,e,n,r),e[2*i+s]>a&&yp(t,e,n,i);oa;)l--;}e[2*n+s]===a?yp(t,e,n,l):(l++,yp(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1);}}function yp(t,e,r,n){mp(t,r,n),mp(e,2*r,2*n),mp(e,2*r+1,2*n+1);}function mp(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function gp(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}var xp;t.cx=void 0,(xp=t.cx||(t.cx={})).create="create",xp.load="load",xp.fullLoad="fullLoad";let vp=null,bp=[];const wp=1e3/60,_p="loadTime",Sp="fullLoadTime",Ap={mark(t){performance.mark(t);},frame(t){const e=t;null!=vp&&bp.push(e-vp),vp=e;},clearMetrics(){vp=null,bp=[],performance.clearMeasures(_p),performance.clearMeasures(Sp);for(const e in t.cx)performance.clearMarks(t.cx[e]);},getPerformanceMetrics(){performance.measure(_p,t.cx.create,t.cx.load),performance.measure(Sp,t.cx.create,t.cx.fullLoad);const e=performance.getEntriesByName(_p)[0].duration,r=performance.getEntriesByName(Sp)[0].duration,n=bp.length,i=1/(bp.reduce(((t,e)=>t+e),0)/n/1e3),s=bp.filter((t=>t>wp)).reduce(((t,e)=>t+(e-wp)/wp),0);return {loadTime:e,fullLoadTime:r,fps:i,percentDroppedFrames:s/(n+s)*100,totalFrames:n}}};t.$=P,t.A=f,t.B=function([t,e,r]){return e+=90,e*=Math.PI/180,r*=Math.PI/180,{x:t*Math.cos(e)*Math.sin(r),y:t*Math.sin(e)*Math.sin(r),z:t*Math.cos(r)}},t.C=dr,t.D=Ds,t.E=gt,t.F=Is,t.G=ts,t.H=function(t){if(null==Z){const e=t.navigator?t.navigator.userAgent:null;Z=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return Z},t.I=vc,t.J=class{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new fh((()=>this.process())),this.subscription=Q(this.target,"message",(t=>this.receive(t)),!1),this.globalScope=X(self)?t:window;}registerMessageHandler(t,e){this.messageHandlers[t]=e;}sendAsync(t,e){return new Promise(((r,n)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10),s=e?Q(e.signal,"abort",(()=>{null==s||s.unsubscribe(),delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e);}),dh):null;this.resolveRejects[i]={resolve:t=>{null==s||s.unsubscribe(),r(t);},reject:t=>{null==s||s.unsubscribe(),n(t);}};const a=[],o=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:cs(t.data,a)});this.target.postMessage(o,{transfer:a});}))}receive(t){const e=t.data,r=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[r];const t=this.abortControllers[r];return delete this.abortControllers[r],void(t&&t.abort())}if(X(self)||e.mustQueue)return this.tasks[r]=e,this.taskQueue.push(r),void this.invoker.trigger();this.processTask(r,e);}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e);}processTask(t,r){return e(this,void 0,void 0,(function*(){if(""===r.type){const e=this.resolveRejects[t];if(delete this.resolveRejects[t],!e)return;return void(r.error?e.reject(hs(r.error)):e.resolve(hs(r.data)))}if(!this.messageHandlers[r.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${r.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const e=hs(r.data),n=new AbortController;this.abortControllers[t]=n;try{const i=yield this.messageHandlers[r.type](r.sourceMapId,e,n);this.completeTask(t,null,i);}catch(e){this.completeTask(t,e);}}))}completeTask(t,e,r){const n=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?cs(e):null,data:cs(r,n)};this.target.postMessage(i,{transfer:n});}remove(){this.invoker.remove(),this.subscription.unsubscribe();}},t.K=lt,t.L=function(){var t=new f(16);return f!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.M=function(t,e,r){var n,i,s,a,o,l,u,c,h,p,f,d,y=r[0],m=r[1],g=r[2];return e===t?(t[12]=e[0]*y+e[4]*m+e[8]*g+e[12],t[13]=e[1]*y+e[5]*m+e[9]*g+e[13],t[14]=e[2]*y+e[6]*m+e[10]*g+e[14],t[15]=e[3]*y+e[7]*m+e[11]*g+e[15]):(i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=n=e[0],t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=n*y+o*m+h*g+e[12],t[13]=i*y+l*m+p*g+e[13],t[14]=s*y+u*m+f*g+e[14],t[15]=a*y+c*m+d*g+e[15]),t},t.N=function(t,e,r){var n=r[0],i=r[1],s=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.O=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],y=e[12],m=e[13],g=e[14],x=e[15],v=r[0],b=r[1],w=r[2],_=r[3];return t[0]=v*n+b*o+w*h+_*y,t[1]=v*i+b*l+w*p+_*m,t[2]=v*s+b*u+w*f+_*g,t[3]=v*a+b*c+w*d+_*x,t[4]=(v=r[4])*n+(b=r[5])*o+(w=r[6])*h+(_=r[7])*y,t[5]=v*i+b*l+w*p+_*m,t[6]=v*s+b*u+w*f+_*g,t[7]=v*a+b*c+w*d+_*x,t[8]=(v=r[8])*n+(b=r[9])*o+(w=r[10])*h+(_=r[11])*y,t[9]=v*i+b*l+w*p+_*m,t[10]=v*s+b*u+w*f+_*g,t[11]=v*a+b*c+w*d+_*x,t[12]=(v=r[12])*n+(b=r[13])*o+(w=r[14])*h+(_=r[15])*y,t[13]=v*i+b*l+w*p+_*m,t[14]=v*s+b*u+w*f+_*g,t[15]=v*a+b*c+w*d+_*x,t},t.P=r,t.Q=function(t,e){const r={};for(let n=0;n!n.has(t.id)))),o.update&&(o.update=o.update.filter((t=>!n.has(t.id))));const i=new Set((null!==(r=t.add)&&void 0!==r?r:[]).map((t=>t.id)));e.remove=e.remove.filter((t=>!i.has(t)));}if(e.remove){const t=new Set(o.remove?o.remove.concat(e.remove):e.remove);o.remove=Array.from(t.values());}if(e.add){const t=o.add?o.add.concat(e.add):e.add,r=new Map(t.map((t=>[t.id,t])));o.add=Array.from(r.values());}if(e.update){const t=new Map(null===(n=o.update)||void 0===n?void 0:n.map((t=>[t.id,t])));for(const r of e.update){const e=null!==(i=t.get(r.id))&&void 0!==i?i:{id:r.id};r.newGeometry&&(e.newGeometry=r.newGeometry),r.addOrUpdateProperties&&(e.addOrUpdateProperties=(null!==(s=e.addOrUpdateProperties)&&void 0!==s?s:[]).concat(r.addOrUpdateProperties)),r.removeProperties&&(e.removeProperties=(null!==(a=e.removeProperties)&&void 0!==a?a:[]).concat(r.removeProperties)),r.removeAllProperties&&(e.removeAllProperties=!0),t.set(r.id,e);}o.update=Array.from(t.values());}return o.remove&&o.add&&(o.remove=o.remove.filter((t=>-1===o.add.findIndex((e=>e.id===t))))),o},t.a1=Ah,t.a2=Eh,t.a3=25,t.a4=Mh,t.a5=t=>{const e=window.document.createElement("video");return e.muted=!0,new Promise((r=>{e.onloadstart=()=>{r(e);};for(const r of t){const t=window.document.createElement("source");pt(r)||(e.crossOrigin="Anonymous"),t.src=r,e.appendChild(t);}}))},t.a6=Ct,t.a7=function(){return O++},t.a8=ba,t.a9=th,t.aA=function(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return [e,r,n,i]},t.aB=Qu,t.aC=C,t.aD=function(t,e,r,n,i=!1){if(!r[0]&&!r[1])return [0,0];const s=i?"map"===n?-t.bearingInRadians:0:"viewport"===n?t.bearingInRadians:0;if(s){const t=Math.sin(s),e=Math.cos(s);r=[r[0]*e-r[1]*t,r[0]*t+r[1]*e];}return [i?r[0]:C(e,r[0],t.zoom),i?r[1]:C(e,r[1],t.zoom)]},t.aF=Zc,t.aG=ap,t.aH=Vc,t.aI=pp,t.aJ=Ys,t.aK=Jl,t.aL=Ea,t.aM=Za,t.aN=Na,t.aO=D,t.aP=et,t.aQ=Sh,t.aR=b,t.aS=v,t.aT=function(t){var e=new f(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.aU=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t},t.aV=function(t,e){var r=e[0],n=e[1],i=e[2],s=r*r+n*n+i*i;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t},t.aW=w,t.aX=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.aY=function(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t},t.aZ=g,t.a_=function(t,e,r){const n=e[0]*r[0]+e[1]*r[1]+e[2]*r[2];return 0===n?null:(-(t[0]*r[0]+t[1]*r[1]+t[2]*r[2])-r[3])/n},t.aa=hi,t.ab=Io,t.ac=Bh,t.ad=function(t){const e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,r,n,i)=>{const s=n||i;return e[r]=!s||s.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t;}return e},t.ae=tt,t.af=function(t){return Math.pow(2,t)},t.ag=y,t.ah=$,t.ai=85.051129,t.aj=wh,t.ak=function(t){return Math.log(t)/Math.LN2},t.al=function(t){var e=t[0],r=t[1];return e*e+r*r},t.am=function(t,e){const r=[];for(const n in t)n in e||r.push(n);return r},t.an=function(t,e){let r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){const{interpolationType:i,minZoom:s,maxZoom:a}=t,o=i?$(pr.interpolationFactor(i,e,s,a),0,1):0;"camera"===t.kind?n=dr.number(t.minSize,t.maxSize,o):r=o;}return {uSizeT:r,uSize:n}},t.ap=function(t,{uSize:e,uSizeT:r},{lowerSize:n,upperSize:i}){return "source"===t.kind?n/qc:"composite"===t.kind?dr.number(n/qc,i/qc,r):e},t.aq=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],y=e[13],m=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,w=n*l-i*o,_=n*u-s*o,S=i*u-s*l,A=c*y-h*d,k=c*m-p*d,M=c*g-f*d,I=h*m-p*y,z=h*g-f*y,P=p*g-f*m,C=x*P-v*z+b*I+w*M-_*k+S*A;return C?(t[0]=(o*P-l*z+u*I)*(C=1/C),t[1]=(i*z-n*P-s*I)*C,t[2]=(y*S-m*_+g*w)*C,t[3]=(p*_-h*S-f*w)*C,t[4]=(l*M-a*P-u*k)*C,t[5]=(r*P-i*M+s*k)*C,t[6]=(m*b-d*S-g*v)*C,t[7]=(c*S-p*b+f*v)*C,t[8]=(a*z-o*M+u*A)*C,t[9]=(n*M-r*z-s*A)*C,t[10]=(d*_-y*b+g*x)*C,t[11]=(h*b-c*_-f*x)*C,t[12]=(o*k-a*I-l*A)*C,t[13]=(r*I-n*k+i*A)*C,t[14]=(y*v-d*w-m*x)*C,t[15]=(c*w-h*v+p*x)*C,t):null},t.ar=I,t.as=function(t){var e=t[0],r=t[1];return Math.sqrt(e*e+r*r)},t.at=function(t){return t[0]=0,t[1]=0,t},t.au=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t},t.av=Kc,t.aw=A,t.ax=function(t,e,n,i){const s=e.y-t.y,a=e.x-t.x,o=i.y-n.y,l=i.x-n.x,u=o*a-l*s;if(0===u)return null;const c=(l*(t.y-n.y)-o*(t.x-n.x))/u;return new r(t.x+c*a,t.y+c*s)},t.ay=Dh,t.az=Eo,t.b=Y,t.b$=class extends la{},t.b0=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t},t.b1=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]},t.b2=Ih,t.b3=Ph,t.b4=function(t,e,r,n,i){var s=1/Math.tan(e/2);if(t[0]=s/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=s,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0){var a=1/(n-i);t[10]=(i+n)*a,t[14]=2*i*n*a;}else t[10]=-1,t[14]=-2*n;return t},t.b5=function(t){var e=new f(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.b6=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[4],c=e[5],h=e[6],p=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i+u*n,t[1]=a*i+c*n,t[2]=o*i+h*n,t[3]=l*i+p*n,t[4]=u*i-s*n,t[5]=c*i-a*n,t[6]=h*i-o*n,t[7]=p*i-l*n,t},t.b7=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=s*i+u*n,t[5]=a*i+c*n,t[6]=o*i+h*n,t[7]=l*i+p*n,t[8]=u*i-s*n,t[9]=c*i-a*n,t[10]=h*i-o*n,t[11]=p*i-l*n,t},t.b8=function(){const t=new Float32Array(16);return y(t),t},t.b9=function(){const t=new Float64Array(16);return y(t),t},t.bA=function(t,e){const r=E(t,360),n=E(e,360),i=n-r,s=n>r?i-360:i+360;return Math.abs(i)0?a:-a},t.bD=function(t,e){const r=E(t,2*Math.PI),n=E(e,2*Math.PI);return Math.min(Math.abs(r-n),Math.abs(r-n+2*Math.PI),Math.abs(r-n-2*Math.PI))},t.bE=function(){const t={},e=xt.$version;for(const r in xt.$root){const n=xt.$root[r];if(n.required){let i=null;i="version"===r?e:"array"===n.type?[]:{},null!=i&&(t[r]=i);}}return t},t.bF=ps,t.bG=ct,t.bH=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(let n=0;n{"source"in t&&n[t.source]?r.push({command:"removeLayer",args:[t.id]}):s.push(t);})),r=r.concat(i),function(t,e,r){e=e||[];const n=(t=t||[]).map(zt),i=e.map(zt),s=t.reduce(Pt,{}),a=e.reduce(Pt,{}),o=n.slice(),l=Object.create(null);let u,c,h,p,f;for(let t=0,e=0;tp?(i=Math.acos(s),a=Math.sin(i),o=Math.sin((1-n)*i)/a,l=Math.sin(n*i)/a):(o=1-n,l=n),t[0]=o*u+l*d,t[1]=o*c+l*y,t[2]=o*h+l*m,t[3]=o*f+l*g,t},t.bd=function(t){const e=new Float64Array(9);var r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v;h=(i=(n=t)[0])*(l=i+i),p=(s=n[1])*l,d=(a=n[2])*l,y=a*(u=s+s),g=(o=n[3])*l,x=o*u,v=o*(c=a+a),(r=e)[0]=1-(f=s*u)-(m=a*c),r[3]=p-v,r[6]=d+x,r[1]=p+v,r[4]=1-h-m,r[7]=y-g,r[2]=d-x,r[5]=y+g,r[8]=1-h-f;const b=et(-Math.asin($(e[2],-1,1)));let w,_;return Math.hypot(e[5],e[8])<.001?(w=0,_=-et(Math.atan2(e[3],e[4]))):(w=et(0===e[5]&&0===e[8]?0:Math.atan2(e[5],e[8])),_=et(0===e[1]&&0===e[0]?0:Math.atan2(e[1],e[0]))),{roll:w,pitch:b+90,bearing:_}},t.be=function(t,e){return t.roll==e.roll&&t.pitch==e.pitch&&t.bearing==e.bearing},t.bf=Me,t.bg=uo,t.bh=Wl,t.bi=Ql,t.bj=Kl,t.bk=T,t.bl=B,t.bm=Le,t.bn=function(t,e,r,n,i){return T(n,i,$((t-e)/(r-e),0,1))},t.bo=E,t.bp=function(){return new Float64Array(3)},t.bq=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t},t.br=M,t.bs=function(t,e,r){var n=r[0],i=r[1],s=r[2],a=r[3],o=e[0],l=e[1],u=e[2],c=i*u-s*l,h=s*o-n*u,p=n*l-i*o;return t[0]=o+a*(c+=c)+i*(p+=p)-s*(h+=h),t[1]=l+a*h+s*c-n*p,t[2]=u+a*p+n*h-i*c,t},t.bt=function(t,e,r){const n=(i=[t[0],t[1],t[2],e[0],e[1],e[2],r[0],r[1],r[2]])[0]*((c=i[8])*(a=i[4])-(o=i[5])*(u=i[7]))+i[1]*(-c*(s=i[3])+o*(l=i[6]))+i[2]*(u*s-a*l);var i,s,a,o,l,u,c;if(0===n)return null;const h=w([],[e[0],e[1],e[2]],[r[0],r[1],r[2]]),p=w([],[r[0],r[1],r[2]],[t[0],t[1],t[2]]),f=w([],[t[0],t[1],t[2]],[e[0],e[1],e[2]]),d=b([],h,-t[3]);return v(d,d,b([],p,-e[3])),v(d,d,b([],f,-r[3])),b(d,d,1/n),d},t.bu=yh,t.bv=function(){return new Float64Array(4)},t.bw=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),s[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),s[2]=i[2],t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bx=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0],s[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),s[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.by=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),s[1]=i[1],s[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bz=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i-u*n,t[1]=a*i-c*n,t[2]=o*i-h*n,t[3]=l*i-p*n,t[8]=s*n+u*i,t[9]=a*n+c*i,t[10]=o*n+h*i,t[11]=l*n+p*i,t},t.c=st,t.c0=Ku,t.c1=class extends ca{},t.c2=cl,t.c3=function(t){return t<=1?1:Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},t.c4=ul,t.c5=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[3]*n+r[7]*i+r[11]*s+r[15];return t[0]=(r[0]*n+r[4]*i+r[8]*s+r[12])/(a=a||1),t[1]=(r[1]*n+r[5]*i+r[9]*s+r[13])/a,t[2]=(r[2]*n+r[6]*i+r[10]*s+r[14])/a,t},t.c6=class extends Ws{},t.c7=class extends ga{},t.c8=function(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[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]},t.c9=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=t[9],f=t[10],d=t[11],y=t[12],m=t[13],g=t[14],x=t[15],v=e[0],b=e[1],w=e[2],_=e[3],S=e[4],A=e[5],k=e[6],M=e[7],I=e[8],z=e[9],P=e[10],C=e[11],E=e[12],T=e[13],B=e[14],V=e[15];return Math.abs(r-v)<=p*Math.max(1,Math.abs(r),Math.abs(v))&&Math.abs(n-b)<=p*Math.max(1,Math.abs(n),Math.abs(b))&&Math.abs(i-w)<=p*Math.max(1,Math.abs(i),Math.abs(w))&&Math.abs(s-_)<=p*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(a-S)<=p*Math.max(1,Math.abs(a),Math.abs(S))&&Math.abs(o-A)<=p*Math.max(1,Math.abs(o),Math.abs(A))&&Math.abs(l-k)<=p*Math.max(1,Math.abs(l),Math.abs(k))&&Math.abs(u-M)<=p*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(c-I)<=p*Math.max(1,Math.abs(c),Math.abs(I))&&Math.abs(h-z)<=p*Math.max(1,Math.abs(h),Math.abs(z))&&Math.abs(f-P)<=p*Math.max(1,Math.abs(f),Math.abs(P))&&Math.abs(d-C)<=p*Math.max(1,Math.abs(d),Math.abs(C))&&Math.abs(y-E)<=p*Math.max(1,Math.abs(y),Math.abs(E))&&Math.abs(m-T)<=p*Math.max(1,Math.abs(m),Math.abs(T))&&Math.abs(g-B)<=p*Math.max(1,Math.abs(g),Math.abs(B))&&Math.abs(x-V)<=p*Math.max(1,Math.abs(x),Math.abs(V))},t.cA=function(t,e){at.REGISTERED_PROTOCOLS[t]=e;},t.cB=function(t){delete at.REGISTERED_PROTOCOLS[t];},t.cC=function(t,e){const r={};for(let n=0;nt*Qu));}let v=o?"center":n.get("text-justify").evaluate(i,{},e.canonical);const b="point"===n.get("symbol-placement")?n.get("text-max-width").evaluate(i,{},e.canonical)*Qu:1/0,w=()=>{e.bucket.allowVerticalPlacement&&ds(s)&&(d.vertical=Ac(y,e.glyphMap,e.glyphPositions,e.imagePositions,c,b,a,m,"left",f,g,t.ao.vertical,!0,p,h));};if(!o&&x){const r=new Set;if("auto"===v)for(let t=0;t0||(null===(i=r.addOrUpdateProperties)||void 0===i?void 0:i.length)>0);if((r.newGeometry||r.removeAllProperties||o)&&(e=Object.assign({},e),t.set(r.id,e),o&&(e.properties=Object.assign({},e.properties))),r.newGeometry&&(e.geometry=r.newGeometry),r.removeAllProperties)e.properties={};else if((null===(s=r.removeProperties)||void 0===s?void 0:s.length)>0)for(const t of r.removeProperties)Object.prototype.hasOwnProperty.call(e.properties,t)&&delete e.properties[t];if((null===(a=r.addOrUpdateProperties)||void 0===a?void 0:a.length)>0)for(const{key:t,value:n}of r.addOrUpdateProperties)e.properties[t]=n;}},t.cX=Ms,t.ca=function(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[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.cb=t=>"symbol"===t.type,t.cc=t=>"circle"===t.type,t.cd=t=>"heatmap"===t.type,t.ce=t=>"line"===t.type,t.cf=t=>"fill"===t.type,t.cg=t=>"fill-extrusion"===t.type,t.ch=t=>"hillshade"===t.type,t.ci=t=>"color-relief"===t.type,t.cj=t=>"raster"===t.type,t.ck=t=>"background"===t.type,t.cl=t=>"custom"===t.type,t.cm=V,t.cn=function(t,e,r){const n=z(e.x-r.x,e.y-r.y),i=z(t.x-r.x,t.y-r.y);var s,a;return et(Math.atan2(n[0]*i[1]-n[1]*i[0],(s=n)[0]*(a=i)[0]+s[1]*a[1]))},t.co=F,t.cp=function(t,e){return nt[e]&&(t instanceof MouseEvent||t instanceof WheelEvent)},t.cq=function(t,e){return rt[e]&&"touches"in t},t.cr=function(t){return rt[t]||nt[t]},t.cs=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t},t.ct=function(t,e){const{x:r,y:n}=Ah.fromLngLat(e);return !(t<0||t>25||n<0||n>=1||r<0||r>=1)},t.cu=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.cv=class extends Js{},t.cw=Ap,t.cy=function(t){return t.message===it},t.cz=ut,t.d=pt,t.e=L,t.f=t=>e(void 0,void 0,void 0,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),t.g=ot,t.h=t=>new Promise(((e,r)=>{const n=new Image;n.onload=()=>{e(n),URL.revokeObjectURL(n.src),n.onload=null,window.requestAnimationFrame((()=>{n.src=H;}));},n.onerror=()=>r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const i=new Blob([new Uint8Array(t)],{type:"image/png"});n.src=t.byteLength?URL.createObjectURL(i):H;})),t.i=X,t.j=(t,e)=>ht(L(t,{type:"json"}),e),t.k=mt,t.l=yt,t.m=ht,t.n=(t,e)=>ht(L(t,{type:"arrayBuffer"}),e),t.o=function(t){return new nc(t).readFields(yc,[])},t.p=xc,t.q=ol,t.r=js,t.s=Q,t.t=Es,t.u=fs,t.v=xt,t.w=q,t.x=Qi,t.y=ns,t.z=Wi;})); + +define("worker",["./shared"],(function(e){"use strict";class t{constructor(e,t){this.keyCache={},e&&this.replace(e,t);}replace(e,t){this._layerConfigs={},this._layers={},this.update(e,[],t);}update(t,i,o){for(const i of t){this._layerConfigs[i.id]=i;const t=this._layers[i.id]=e.bJ(i,o);t._featureFilter=e.aa(t.filter,o),this.keyCache[i.id]&&delete this.keyCache[i.id];}for(const e of i)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const s=e.cC(Object.values(this._layerConfigs),this.keyCache);for(const e of s){const t=e.map((e=>this._layers[e.id])),i=t[0];if("none"===i.visibility)continue;const o=i.source||"";let s=this.familiesBySource[o];s||(s=this.familiesBySource[o]={});const n=i.sourceLayer||"_geojsonTileLayer";let r=s[n];r||(r=s[n]=[]),r.push(t);}}}class i{constructor(t){const i={},o=[];for(const e in t){const s=t[e],n=i[e]={};for(const e in s){const t=s[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const i={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};o.push(i),n[e]={rect:i,metrics:t.metrics};}}const{w:s,h:n}=e.p(o),r=new e.q({width:s||1,height:n||1});for(const o in t){const s=t[o];for(const t in s){const n=s[+t];if(!n||0===n.bitmap.width||0===n.bitmap.height)continue;const a=i[o][t].rect;e.q.copy(n.bitmap,r,{x:0,y:0},{x:a.x+1,y:a.y+1},n.bitmap);}}this.image=r,this.positions=i;}}e.cD("GlyphAtlas",i);class o{constructor(t){this.tileID=new e.Z(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[];}parse(t,o,n,r,a){return e._(this,void 0,void 0,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.a8;const l=new e.cE(Object.keys(t.layers).sort()),c=new e.cF(this.tileID,this.promoteId);c.bucketLayerIDs=[];const u={},h={featureIndex:c,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:n,subdivisionGranularity:a},d=o.familiesBySource[this.source];for(const i in d){const o=t.layers[i];if(!o)continue;1===o.version&&e.w(`Vector tile source "${this.source}" layer "${i}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const r=l.encode(i),a=[];for(let e=0;e=i.maxzoom||"none"!==i.visibility&&(s(t,this.zoom,n),(u[i.id]=i.createBucket({index:c.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:r,sourceID:this.source})).populate(a,h,this.tileID.canonical),c.bucketLayerIDs.push(t.map((e=>e.id))));}}const f=e.bN(h.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?void 0:e.abort())),this.inFlightDependencies=[];let g=Promise.resolve({});if(Object.keys(f).length){const e=new AbortController;this.inFlightDependencies.push(e),g=r.sendAsync({type:"GG",data:{stacks:f,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const p=Object.keys(h.iconDependencies);let m=Promise.resolve({});if(p.length){const e=new AbortController;this.inFlightDependencies.push(e),m=r.sendAsync({type:"GI",data:{icons:p,source:this.source,tileID:this.tileID,type:"icons"}},e);}const y=Object.keys(h.patternDependencies);let v=Promise.resolve({});if(y.length){const e=new AbortController;this.inFlightDependencies.push(e),v=r.sendAsync({type:"GI",data:{icons:y,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const[w,x,b]=yield Promise.all([g,m,v]),S=new i(w),_=new e.cG(x,b);for(const t in u){const i=u[t];i instanceof e.a9?(s(i.layers,this.zoom,n),e.cH({bucket:i,glyphMap:w,glyphPositions:S.positions,imageMap:x,imagePositions:_.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:h.subdivisionGranularity})):i.hasPattern&&(i instanceof e.cI||i instanceof e.cJ||i instanceof e.cK)&&(s(i.layers,this.zoom,n),i.addFeatures(h,this.tileID.canonical,_.patternPositions));}return this.status="done",{buckets:Object.values(u).filter((e=>!e.isEmpty())),featureIndex:c,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:S.image,imageAtlas:_,glyphMap:this.returnDependencies?w:null,iconMap:this.returnDependencies?x:null,glyphPositions:this.returnDependencies?S.positions:null}}))}}function s(t,i,o){const s=new e.F(i);for(const e of t)e.recalculate(s,o);}class n{constructor(e,t,i){this.actor=e,this.layerIndex=t,this.availableImages=i,this.fetching={},this.loading={},this.loaded={};}loadVectorTile(t,i){return e._(this,void 0,void 0,(function*(){const o=yield e.n(t.request,i);try{return {vectorTile:new e.cL(new e.cM(o.data)),rawData:o.data,cacheControl:o.cacheControl,expires:o.expires}}catch(e){const i=new Uint8Array(o.data);let s=`Unable to parse the tile at ${t.request.url}, `;throw s+=31===i[0]&&139===i[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${e.message}`,new Error(s)}}))}loadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid,s=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.cN(t.request),n=new o(t);this.loading[i]=n;const r=new AbortController;n.abort=r;try{const o=yield this.loadVectorTile(t,r);if(delete this.loading[i],!o)return null;const a=o.rawData,l={};o.expires&&(l.expires=o.expires),o.cacheControl&&(l.cacheControl=o.cacheControl);const c={};if(s){const e=s.finish();e&&(c.resourceTiming=JSON.parse(JSON.stringify(e)));}n.vectorTile=o.vectorTile;const u=n.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);this.loaded[i]=n,this.fetching[i]={rawTileData:a,cacheControl:l,resourceTiming:c};try{const t=yield u;return e.e({rawTileData:a.slice(0)},t,l,c)}finally{delete this.fetching[i];}}catch(e){throw delete this.loading[i],n.status="done",this.loaded[i]=n,e}}))}reloadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid;if(!this.loaded||!this.loaded[i])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const o=this.loaded[i];if(o.showCollisionBoxes=t.showCollisionBoxes,"parsing"===o.status){const s=yield o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);let n;if(this.fetching[i]){const{rawTileData:t,cacheControl:o,resourceTiming:r}=this.fetching[i];delete this.fetching[i],n=e.e({rawTileData:t.slice(0)},s,o,r);}else n=s;return n}if("done"===o.status&&o.vectorTile)return o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity)}))}abortTile(t){return e._(this,void 0,void 0,(function*(){const e=this.loading,i=t.uid;e&&e[i]&&e[i].abort&&(e[i].abort.abort(),delete e[i]);}))}removeTile(t){return e._(this,void 0,void 0,(function*(){this.loaded&&this.loaded[t.uid]&&delete this.loaded[t.uid];}))}}class r{constructor(){this.loaded={};}loadTile(t){return e._(this,void 0,void 0,(function*(){const{uid:i,encoding:o,rawImageData:s,redFactor:n,greenFactor:r,blueFactor:a,baseShift:l}=t,c=s.width+2,u=s.height+2,h=e.b(s)?new e.R({width:c,height:u},yield e.cO(s,-1,-1,c,u)):s,d=new e.cP(i,h,o,n,r,a,l);return this.loaded=this.loaded||{},this.loaded[i]=d,d}))}removeTile(e){const t=this.loaded,i=e.uid;t&&t[i]&&delete t[i];}}var a,l,c=function(){if(l)return a;function e(e,i){if(0!==e.length){t(e[0],i);for(var o=1;o=Math.abs(a)?i-l+a:a-l+i,i=l;}i+o>=0!=!!t&&e.reverse();}return l=1,a=function t(i,o){var s,n=i&&i.type;if("FeatureCollection"===n)for(s=0;s>31}function v(e,t){const i=e.loadGeometry(),o=e.type;let s=0,n=0;for(const r of i){let i=1;1===o&&(i=r.length),t.writeVarint(m(1,i));const a=3===o?r.length-1:r.length;for(let e=0;ee},b=Math.fround||(S=new Float32Array(1),e=>(S[0]=+e,S[0]));var S;class _{constructor(e){this.options=Object.assign(Object.create(x),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:i,maxZoom:o}=this.options;t&&console.time("total time");const s=`prepare ${e.length} points`;t&&console.time(s),this.points=e;const n=[];for(let t=0;t=i;e--){const i=+Date.now();r=this.trees[e]=this._createTree(this._cluster(r,e)),t&&console.log("z%d: %d clusters in %dms",e,r.numItems,+Date.now()-i);}return t&&console.timeEnd("total time"),this}getClusters(e,t){let i=((e[0]+180)%360+360)%360-180;const o=Math.max(-90,Math.min(90,e[1]));let s=180===e[2]?180:((e[2]+180)%360+360)%360-180;const n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)i=-180,s=180;else if(i>s){const e=this.getClusters([i,o,180,n],t),r=this.getClusters([-180,o,s,n],t);return e.concat(r)}const r=this.trees[this._limitZoom(t)],a=r.range(k(i),P(n),k(s),P(o)),l=r.data,c=[];for(const e of a){const t=this.stride*e;c.push(l[t+5]>1?M(l,t,this.clusterProps):this.points[l[t+3]]);}return c}getChildren(e){const t=this._getOriginId(e),i=this._getOriginZoom(e),o="No cluster with the specified id.",s=this.trees[i];if(!s)throw new Error(o);const n=s.data;if(t*this.stride>=n.length)throw new Error(o);const r=this.options.radius/(this.options.extent*Math.pow(2,i-1)),a=s.within(n[t*this.stride],n[t*this.stride+1],r),l=[];for(const t of a){const i=t*this.stride;n[i+4]===e&&l.push(n[i+5]>1?M(n,i,this.clusterProps):this.points[n[i+3]]);}if(0===l.length)throw new Error(o);return l}getLeaves(e,t,i){const o=[];return this._appendLeaves(o,e,t=t||10,i=i||0,0),o}getTile(e,t,i){const o=this.trees[this._limitZoom(e)],s=Math.pow(2,e),{extent:n,radius:r}=this.options,a=r/n,l=(i-a)/s,c=(i+1+a)/s,u={features:[]};return this._addTileFeatures(o.range((t-a)/s,l,(t+1+a)/s,c),o.data,t,i,s,u),0===t&&this._addTileFeatures(o.range(1-a/s,l,1,c),o.data,s,i,s,u),t===s-1&&this._addTileFeatures(o.range(0,l,a/s,c),o.data,-1,i,s,u),u.features.length?u:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const i=this.getChildren(e);if(t++,1!==i.length)break;e=i[0].properties.cluster_id;}return t}_appendLeaves(e,t,i,o,s){const n=this.getChildren(t);for(const t of n){const n=t.properties;if(n&&n.cluster?s+n.point_count<=o?s+=n.point_count:s=this._appendLeaves(e,n.cluster_id,i,o,s):s1;let l,c,u;if(a)l=I(t,e,this.clusterProps),c=t[e],u=t[e+1];else {const i=this.points[t[e+3]];l=i.properties;const[o,s]=i.geometry.coordinates;c=k(o),u=P(s);}const h={type:1,geometry:[[Math.round(this.options.extent*(c*s-i)),Math.round(this.options.extent*(u*s-o))]],tags:l};let d;d=a||this.options.generateId?t[e+3]:this.points[t[e+3]].id,void 0!==d&&(h.id=d),n.features.push(h);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:i,extent:o,reduce:s,minPoints:n}=this.options,r=i/(o*Math.pow(2,t)),a=e.data,l=[],c=this.stride;for(let i=0;it&&(f+=a[i+5]);}if(f>d&&f>=n){let e,n=o*d,r=u*d,g=-1;const p=(i/c<<5)+(t+1)+this.points.length;for(const o of h){const l=o*c;if(a[l+2]<=t)continue;a[l+2]=t;const u=a[l+5];n+=a[l]*u,r+=a[l+1]*u,a[l+4]=p,s&&(e||(e=this._map(a,i,!0),g=this.clusterProps.length,this.clusterProps.push(e)),s(e,this._map(a,l)));}a[i+4]=p,l.push(n/f,r/f,1/0,p,-1,f),s&&l.push(g);}else {for(let e=0;e1)for(const e of h){const i=e*c;if(!(a[i+2]<=t)){a[i+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,i){if(e[t+5]>1){const o=this.clusterProps[e[t+6]];return i?Object.assign({},o):o}const o=this.points[e[t+3]].properties,s=this.options.map(o);return i&&s===o?Object.assign({},s):s}}function M(e,t,i){return {type:"Feature",id:e[t+3],properties:I(e,t,i),geometry:{type:"Point",coordinates:[(o=e[t],360*(o-.5)),T(e[t+1])]}};var o;}function I(e,t,i){const o=e[t+5],s=o>=1e4?`${Math.round(o/1e3)}k`:o>=1e3?Math.round(o/100)/10+"k":o,n=e[t+6],r=-1===n?{}:Object.assign({},i[n]);return Object.assign(r,{cluster:!0,cluster_id:e[t+3],point_count:o,point_count_abbreviated:s})}function k(e){return e/360+.5}function P(e){const t=Math.sin(e*Math.PI/180),i=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return i<0?0:i>1?1:i}function T(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function D(e,t,i,o){let s=o;const n=t+(i-t>>1);let r,a=i-t;const l=e[t],c=e[t+1],u=e[i],h=e[i+1];for(let o=t+3;os)r=o,s=t;else if(t===s){const e=Math.abs(o-n);eo&&(r-t>3&&D(e,t,r,o),e[r+2]=s,i-r>3&&D(e,r,i,o));}function C(e,t,i,o,s,n){let r=s-i,a=n-o;if(0!==r||0!==a){const l=((e-i)*r+(t-o)*a)/(r*r+a*a);l>1?(i=s,o=n):l>0&&(i+=r*l,o+=a*l);}return r=e-i,a=t-o,r*r+a*a}function L(e,t,i,o){const s={id:null==e?null:e,type:t,geometry:i,tags:o,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===t||"MultiPoint"===t||"LineString"===t)O(s,i);else if("Polygon"===t)O(s,i[0]);else if("MultiLineString"===t)for(const e of i)O(s,e);else if("MultiPolygon"===t)for(const e of i)O(s,e[0]);return s}function O(e,t){for(let i=0;i0&&(r+=o?(s*l-a*n)/2:Math.sqrt(Math.pow(a-s,2)+Math.pow(l-n,2))),s=a,n=l;}const a=t.length-3;t[2]=1,D(t,0,a,i),t[a+2]=1,t.size=Math.abs(r),t.start=0,t.end=t.size;}function G(e,t,i,o){for(let s=0;s1?1:i}function j(e,t,i,o,s,n,r,a){if(o/=t,n>=(i/=t)&&r=o)return null;const l=[];for(const t of e){const e=t.geometry;let n=t.type;const r=0===s?t.minX:t.minY,c=0===s?t.maxX:t.maxY;if(r>=i&&c=o)continue;let u=[];if("Point"===n||"MultiPoint"===n)N(e,u,i,o,s);else if("LineString"===n)R(e,u,i,o,s,!1,a.lineMetrics);else if("MultiLineString"===n)J(e,u,i,o,s,!1);else if("Polygon"===n)J(e,u,i,o,s,!0);else if("MultiPolygon"===n)for(const t of e){const e=[];J(t,e,i,o,s,!0),e.length&&u.push(e);}if(u.length){if(a.lineMetrics&&"LineString"===n){for(const e of u)l.push(L(t.id,n,e,t.tags));continue}"LineString"!==n&&"MultiLineString"!==n||(1===u.length?(n="LineString",u=u[0]):n="MultiLineString"),"Point"!==n&&"MultiPoint"!==n||(n=3===u.length?"Point":"MultiPoint"),l.push(L(t.id,n,u,t.tags));}}return l.length?l:null}function N(e,t,i,o,s){for(let n=0;n=i&&r<=o&&Y(t,e[n],e[n+1],e[n+2]);}}function R(e,t,i,o,s,n,r){let a=W(e);const l=0===s?q:X;let c,u,h=e.start;for(let d=0;di&&(u=l(a,f,g,m,y,i),r&&(a.start=h+c*u)):v>o?w=i&&(u=l(a,f,g,m,y,i),x=!0),w>o&&v<=o&&(u=l(a,f,g,m,y,o),x=!0),!n&&x&&(r&&(a.end=h+c*u),t.push(a),a=W(e)),r&&(h+=c);}let d=e.length-3;const f=e[d],g=e[d+1],p=0===s?f:g;p>=i&&p<=o&&Y(a,f,g,e[d+2]),d=a.length-3,n&&d>=3&&(a[d]!==a[0]||a[d+1]!==a[1])&&Y(a,a[0],a[1],a[2]),a.length&&t.push(a);}function W(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function J(e,t,i,o,s,n){for(const r of e)R(r,t,i,o,s,n,!1);}function Y(e,t,i,o){e.push(t,i,o);}function q(e,t,i,o,s,n){const r=(n-t)/(o-t);return Y(e,n,i+(s-i)*r,1),r}function X(e,t,i,o,s,n){const r=(n-i)/(s-i);return Y(e,t+(o-t)*r,n,1),r}function H(e,t){const i=[];for(let o=0;o0&&t.size<(s?r:o))return void(i.numPoints+=t.length/3);const a=[];for(let e=0;er)&&(i.numSimplified++,a.push(t[e],t[e+1])),i.numPoints++;s&&function(e,t){let i=0;for(let t=0,o=e.length,s=o-2;t0===t)for(let t=0,i=e.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");let o=function(e,t){const i=[];if("FeatureCollection"===e.type)for(let o=0;o1&&console.time("creation"),d=this.tiles[h]=U(e,t,i,o,l),this.tileCoords.push({z:t,x:i,y:o}),c)){c>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,i,o,d.numFeatures,d.numPoints,d.numSimplified),console.timeEnd("creation"));const e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++;}if(d.source=e,null==s){if(t===l.indexMaxZoom||d.numPoints<=l.indexMaxPoints)continue}else {if(t===l.maxZoom||t===s)continue;if(null!=s){const e=s-t;if(i!==n>>e||o!==r>>e)continue}}if(d.source=null,0===e.length)continue;c>1&&console.time("clipping");const f=.5*l.buffer/l.extent,g=.5-f,p=.5+f,m=1+f;let y=null,v=null,w=null,x=null,b=j(e,u,i-f,i+p,0,d.minX,d.maxX,l),S=j(e,u,i+g,i+m,0,d.minX,d.maxX,l);e=null,b&&(y=j(b,u,o-f,o+p,1,d.minY,d.maxY,l),v=j(b,u,o+g,o+m,1,d.minY,d.maxY,l),b=null),S&&(w=j(S,u,o-f,o+p,1,d.minY,d.maxY,l),x=j(S,u,o+g,o+m,1,d.minY,d.maxY,l),S=null),c>1&&console.timeEnd("clipping"),a.push(y||[],t+1,2*i,2*o),a.push(v||[],t+1,2*i,2*o+1),a.push(w||[],t+1,2*i+1,2*o),a.push(x||[],t+1,2*i+1,2*o+1);}}getTile(e,t,i){e=+e,t=+t,i=+i;const o=this.options,{extent:s,debug:n}=o;if(e<0||e>24)return null;const r=1<1&&console.log("drilling down to z%d-%d-%d",e,t,i);let l,c=e,u=t,h=i;for(;!l&&c>0;)c--,u>>=1,h>>=1,l=this.tiles[ie(c,u,h)];return l&&l.source?(n>1&&(console.log("found parent tile z%d-%d-%d",c,u,h),console.time("drilling down")),this.splitTile(l.source,c,u,h,e,t,i),n>1&&console.timeEnd("drilling down"),this.tiles[a]?B(this.tiles[a],s):null):null}}function ie(e,t,i){return 32*((1<{r.properties=e;const t={};for(const e of a)t[e]=o[e].evaluate(n,r);return t},t.reduce=(e,t)=>{r.properties=t;for(const t of a)n.accumulated=e[t],e[t]=s[t].evaluate(n,r);},t}(t)).load(i.features):function(e,t){return new te(e,t)}(i,t.geojsonVtOptions),this.loaded={};const s={data:i};if(o){const e=o.finish();e&&(s.resourceTiming={},s.resourceTiming[t.source]=JSON.parse(JSON.stringify(e)));}return s}catch(t){if(delete this._pendingRequest,e.cy(t))return {abandoned:!0};throw t}}))}getData(){return e._(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(e){const t=this.loaded;return t&&t[e.uid]?super.reloadTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){let o=yield this.loadGeoJSON(t,i);if(delete this._pendingRequest,"object"!=typeof o)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(u(o,!0),t.filter){const i=e.cT(t.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===i.result)throw new Error(i.value.map((e=>`${e.key}: ${e.message}`)).join(", "));const s=o.features.filter((e=>i.value.evaluate({zoom:0},e)));o={type:"FeatureCollection",features:s};}return o}))}loadGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){const{promoteId:o}=t;if(t.request){const s=yield e.j(t.request,i);return this._dataUpdateable=e.cV(s.data,o)?e.cU(s.data,o):void 0,s.data}if("string"==typeof t.data)try{const i=JSON.parse(t.data);return this._dataUpdateable=e.cV(i,o)?e.cU(i,o):void 0,i}catch(e){throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}if(!t.dataDiff)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${t.source}`);return e.cW(this._dataUpdateable,t.dataDiff,o),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(t){return e._(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset)}}class se{constructor(t){this.self=t,this.actor=new e.J(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=new Map,this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.cA,this.self.removeProtocol=e.cB,this.self.registerRTLTextPlugin=t=>{e.cX.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,i)=>e._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(t,i.source).removeTile(i);})))),this.actor.registerMessageHandler("GCEZ",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterExpansionZoom(i)})))),this.actor.registerMessageHandler("GCC",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterChildren(i)})))),this.actor.registerMessageHandler("GCL",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterLeaves(i)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("GD",((e,t)=>this._getWorkerSource(e,t.type,t.source).getData())),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,i)=>e._(this,void 0,void 0,(function*(){if(!this.workerSources[t]||!this.workerSources[t][i.type]||!this.workerSources[t][i.type][i.source])return;const e=this.workerSources[t][i.type][i.source];delete this.workerSources[t][i.type][i.source],void 0!==e.removeSource&&e.removeSource(i);})))),this.actor.registerMessageHandler("RM",(t=>e._(this,void 0,void 0,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t],this.globalStates.delete(t);})))),this.actor.registerMessageHandler("SR",((t,i)=>e._(this,void 0,void 0,(function*(){this.referrer=i;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,i)=>e._(this,void 0,void 0,(function*(){this.self.importScripts(i);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).update(i.layers,i.removedIds,this._getGlobalState(t));})))),this.actor.registerMessageHandler("UGS",((t,i)=>e._(this,void 0,void 0,(function*(){const e=this._getGlobalState(t);for(const t in i)e[t]=i[t];})))),this.actor.registerMessageHandler("SL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).replace(i,this._getGlobalState(t));}))));}_getGlobalState(e){let t=this.globalStates.get(e);return t||(t={},this.globalStates.set(e,t)),t}_setImages(t,i){return e._(this,void 0,void 0,(function*(){this.availableImages[t]=i;for(const e in this.workerSources[t]){const o=this.workerSources[t][e];for(const e in o)o[e].availableImages=i;}}))}_syncRTLPluginState(t,i){return e._(this,void 0,void 0,(function*(){return yield e.cX.syncState(i,this.self.importScripts)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(e){let i=this.layerIndexes[e];return i||(i=this.layerIndexes[e]=new t),i}_getWorkerSource(e,t,i){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][i]){const o={sendAsync:(t,i)=>(t.targetMapId=e,this.actor.sendAsync(t,i))};switch(t){case "vector":this.workerSources[e][t][i]=new n(o,this._getLayerIndex(e),this._getAvailableImages(e));break;case "geojson":this.workerSources[e][t][i]=new oe(o,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][i]=new this.externalWorkerSourceTypes[t](o,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][t][i]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new r),this.demWorkerSources[e][t]}}return e.i(self)&&(self.worker=new se(self)),se})); + +define("index",["exports","./shared"],(function(e,t){"use strict";var i="5.7.2";function o(){var e=new t.A(4);return t.A!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}let r,a;const s={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frame(e,i,o){const r=requestAnimationFrame((e=>{a(),i(e);})),{unsubscribe:a}=t.s(e.signal,"abort",(()=>{a(),cancelAnimationFrame(r),o(t.c());}),!1);},frameAsync(e){return new Promise(((t,i)=>{this.frame(e,t,i);}))},getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(r||(r=document.createElement("a")),r.href=e,r.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==a&&(a=matchMedia("(prefers-reduced-motion: reduce)")),a.matches)}};class n{static testProp(e){if(!n.docStyle)return e[0];for(let t=0;t{window.removeEventListener("click",n.suppressClickInternal,!0);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,o){const r=i.boundingClientRect;return new t.P((o.clientX-r.left)/i.x-e.clientLeft,(o.clientY-r.top)/i.y-e.clientTop)}static mousePos(e,t){const i=n.getScale(e);return n.getPoint(e,i,t)}static touchPos(e,t){const i=[],o=n.getScale(e);for(let r=0;r{c&&_(c),c=null,d=!0;},h.onerror=()=>{u=!0,c=null;},h.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(e){let i,o,r,a;e.resetRequestQueue=()=>{i=[],o=0,r=0,a={};},e.addThrottleControl=e=>{const t=r++;return a[t]=e,t},e.removeThrottleControl=e=>{delete a[e],n();},e.getImage=(e,o,r=!0)=>new Promise(((a,s)=>{l.supported&&(e.headers||(e.headers={}),e.headers.accept="image/webp,*/*"),t.e(e,{type:"image"}),i.push({abortController:o,requestParameters:e,supportImageRefresh:r,state:"queued",onError:e=>{s(e);},onSuccess:e=>{a(e);}}),n();}));const s=e=>t._(this,void 0,void 0,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:r,onError:a,onSuccess:s,abortController:l}=e,h=!1===r&&!t.i(self)&&!t.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),!0));o++;const u=h?c(i,l):t.m(i,l);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.b(i.data)?s(i):i.data&&s({data:yield(d=i.data,"function"==typeof createImageBitmap?t.f(d):t.h(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,a(t);}finally{o--,n();}var d;})),n=()=>{const e=(()=>{for(const e of Object.keys(a))if(a[e]())return !0;return !1})()?t.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=o;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:s(e);}},c=(e,i)=>new Promise(((o,r)=>{const a=new Image,s=e.url,n=e.credentials;n&&"include"===n?a.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.d(s))&&(a.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{a.src="",r(t.c());})),a.fetchPriority="high",a.onload=()=>{a.onerror=a.onload=null,o({data:a});},a.onerror=()=>{a.onerror=a.onload=null,i.signal.aborted||r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));},a.src=s;}));}(p||(p={})),p.resetRequestQueue();class m{constructor(e){this._transformRequestFn=null!=e?e:null;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}function f(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:o,url:r}of e){const e=`${o}${r}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:o,url:r}));}}return t}function g(e,t,i){try{const o=new URL(e);return o.pathname+=`${t}${i}`,o.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}function v(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class b extends t.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.R({width:1,height:1}),this.dirty=!0;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.R({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let o=!0;const r=i.data||i.spriteData;return this._validateStretch(i.stretchX,r&&r.width)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchX" value`))),o=!1),this._validateStretch(i.stretchY,r&&r.height)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchY" value`))),o=!1),this._validateContent(i.content,i)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "content" value`))),o=!1),o}_validateStretch(e,t){if(!e)return !0;let i=0;for(const o of e){if(o[0]{let o=!0;if(!this.isLoaded())for(const t of e)this.images[t]||(o=!1);this.isLoaded()||o?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const o of e){let e=this.getImage(o);e||(this.fire(new t.l("styleimagemissing",{id:o})),e=this.getImage(o)),e?i[o]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.w(`Image "${o}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);}return i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],o=this.getImage(e);if(!o)return null;if(i&&i.position.version===o.version)return i.position;if(i)i.position.version=o.version;else {const i={w:o.data.width+2,h:o.data.height+2,x:0,y:0},r=new t.I(i,o);this.patterns[e]={bin:i,position:r};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const i=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new t.T(e,this.atlasImage,i.RGBA),this.atlasTexture.bind(i.LINEAR,i.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:o}=t.p(e),r=this.atlasImage;r.resize({width:i||1,height:o||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],o=i.x+1,a=i.y+1,s=this.getImage(e).data,n=s.width,l=s.height;t.R.copy(s,r,{x:0,y:0},{x:o,y:a},{width:n,height:l}),t.R.copy(s,r,{x:0,y:l-1},{x:o,y:a-1},{width:n,height:1}),t.R.copy(s,r,{x:0,y:0},{x:o,y:a+l},{width:n,height:1}),t.R.copy(s,r,{x:n-1,y:0},{x:o-1,y:a},{width:1,height:l}),t.R.copy(s,r,{x:0,y:0},{x:o+n,y:a},{width:1,height:l});}this.dirty=!0;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=!0;const e=this.getImage(i);e||t.w(`Image with ID: "${i}" was not found`),v(e)&&this.updateImage(i,e);}}}const x=1e20;function y(e,t,i,o,r,a,s,n,l){for(let c=t;c-1);l++,a[l]=n,s[l]=c,s[l+1]=x;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(t.ranges[r])return {stack:e,id:i,glyph:o};if(!this.url)throw new Error("glyphsUrl is not set");if(!t.requests[r]){const i=T.loadGlyphRange(e,r,this.url,this.requestManager);t.requests[r]=i;}const a=yield t.requests[r];for(const e in a)this._doesCharSupportLocalGlyph(+e)||(t.glyphs[+e]=a[+e]);return t.ranges[r]=!0,{stack:e,id:i,glyph:a[i]||null}}))}_doesCharSupportLocalGlyph(e){return !!this.localIdeographFontFamily&&(/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(e))||t.u["CJK Unified Ideographs"](e)||t.u["Hangul Syllables"](e)||t.u.Hiragana(e)||t.u.Katakana(e)||t.u["CJK Symbols and Punctuation"](e)||t.u["Halfwidth and Fullwidth Forms"](e))}_tinySDF(e,i,o){const r=this.localIdeographFontFamily;if(!r)return;if(!this._doesCharSupportLocalGlyph(o))return;let a=e.tinySDF;if(!a){let t="400";/bold/i.test(i)?t="900":/medium/i.test(i)?t="500":/light/i.test(i)&&(t="200"),a=e.tinySDF=new T.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,lang:this.lang,fontFamily:r,fontWeight:t});}const s=a.draw(String.fromCharCode(o));return {id:o,bitmap:new t.q({width:s.width||60,height:s.height||60},s.data),metrics:{width:s.glyphWidth/2||24,height:s.glyphHeight/2||24,left:s.glyphLeft/2+.5||0,top:s.glyphTop/2-27.5||-8,advance:s.glyphAdvance/2||24,isDoubleResolution:!0}}}}T.loadGlyphRange=function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=256*i,s=a+255,n=r.transformRequest(o.replace("{fontstack}",e).replace("{range}",`${a}-${s}`),"Glyphs"),l=yield t.n(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${a}-${s}`);const c={};for(const e of t.o(l.data))c[e.id]=e;return c}))},T.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:o=.25,fontFamily:r="sans-serif",fontWeight:a="normal",fontStyle:s="normal",lang:n=null}={}){this.buffer=t,this.cutoff=o,this.radius=i,this.lang=n;const l=this.size=e+4*t,c=this._createCanvas(l),h=this.ctx=c.getContext("2d",{willReadFrequently:!0});h.font=`${s} ${a} ${e}px ${r}`,h.textBaseline="alphabetic",h.textAlign="left",h.fillStyle="black",this.gridOuter=new Float64Array(l*l),this.gridInner=new Float64Array(l*l),this.f=new Float64Array(l),this.z=new Float64Array(l+1),this.v=new Uint16Array(l);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:o,actualBoundingBoxLeft:r,actualBoundingBoxRight:a}=this.ctx.measureText(e),s=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(a-r))),l=Math.min(this.size-this.buffer,s+Math.ceil(o)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:s,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;this.lang&&(p.lang=this.lang),p.clearRect(m,m,n,l),p.fillText(e,m,m+s);const v=p.getImageData(m,m,n,l);g.fill(x,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[o]=e<0?e*e:0;}}y(g,0,0,c,h,c,this.f,this.v,this.z),y(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(s=e[++a]);const l=Math.abs(n-s.left),c=Math.abs(n-s.right),h=Math.min(l,c);let u;const d=t/i*(o+1);if(s.isDash){const e=o-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=o-Math.sqrt(h*h+d*d);this.data[r+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],o=e[t+1];i.zeroLength?e.splice(t,1):o&&o.isDash===i.isDash&&(o.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const o=this.width*this.nextRow;let r=0,a=e[r];for(let t=0;t1&&(a=e[++r]);const i=Math.abs(t-a.left),s=Math.abs(t-a.right),n=Math.min(i,s);this.data[o+t]=Math.max(0,Math.min(255,(a.isDash?n:-n)+128));}}addDash(e,i){const o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.w("LineAtlas out of space"),null;let a=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[R]}numActive(){return Object.keys(this.active).length}}const D=Math.floor(s.hardwareConcurrency/2);let A,L;function k(){return A||(A=new z),A}z.workerCount=t.H(globalThis)?Math.max(Math.min(D,3),1):1;class F{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const o=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}}function B(){return L||(L=new F(k(),t.K),L.registerMessageHandler("GR",((e,i,o)=>t.m(i,o)))),L}function O(e,i){const o=t.L();return t.M(o,o,[1,1,0]),t.N(o,o,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.O(o,o,e.calculatePosMatrix(i.toUnwrapped())):o}function j(e,t,i,o,r,a,s){var n;const l=function(e,t,i){if(e)for(const o of e){const e=t[o];if(e&&e.source===i&&"fill-extrusion"===e.type)return !0}else for(const e in t){const o=t[e];if(o.source===i&&"fill-extrusion"===o.type)return !0}return !1}(null!==(n=null==r?void 0:r.layers)&&void 0!==n?n:null,t,e.id),c=a.maxPitchScaleFactor(),h=e.tilesIn(o,c,l);h.sort(N);const u=[];for(const o of h)u.push({wrappedTileID:o.tileID.wrapped().key,queryResults:o.tile.queryRenderedFeatures(t,i,e._state,o.queryGeometry,o.cameraQueryGeometry,o.scale,r,a,c,O(e.transform,o.tileID),s?(e,t)=>s(o.tileID,e,t):void 0)});return function(e,t){for(const i in e)for(const o of e[i])U(o,t);return e}(function(e){const t={},i={};for(const o of e){const e=o.queryResults,r=o.wrappedTileID,a=i[r]=i[r]||{};for(const i in e){const o=e[i],r=a[i]=a[i]||{},s=t[i]=t[i]||[];for(const e of o)r[e.featureIndex]||(r[e.featureIndex]=!0,s.push(e));}}return t}(u),e)}function N(e,t){const i=e.tileID,o=t.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}function U(e,t){const i=e.feature,o=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=o;}function Z(e,i,o){return t._(this,void 0,void 0,(function*(){let r=e;if(e.url?r=(yield t.j(i.transformRequest(e.url,"Source"),o)).data:yield s.frameAsync(o),!r)return null;const a=t.Q(t.e(r,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in r&&r.vector_layers&&(a.vectorLayerIds=r.vector_layers.map((e=>e.id))),a}))}class G{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}extend(e){const i=this._sw,o=this._ne;let r,a;if(e instanceof t.S)r=e,a=e;else {if(!(e instanceof G))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(G.convert(e)):this.extend(t.S.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.S.convert(e)):this;if(r=e._sw,a=e._ne,!r||!a)return this}return i||o?(i.lng=Math.min(r.lng,i.lng),i.lat=Math.min(r.lat,i.lat),o.lng=Math.max(a.lng,o.lng),o.lat=Math.max(a.lat,o.lat)):(this._sw=new t.S(r.lng,r.lat),this._ne=new t.S(a.lng,a.lat)),this}getCenter(){return new t.S((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new t.S(this.getWest(),this.getNorth())}getSouthEast(){return new t.S(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(e){const{lng:i,lat:o}=t.S.convert(e);let r=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(r=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=o&&o<=this._ne.lat&&r}static convert(e){return e instanceof G?e:e?new G(e):e}static fromLngLat(e,i=0){const o=360*i/40075017,r=o/Math.cos(Math.PI/180*e.lat);return new G(new t.S(e.lng-r,e.lat-o),new t.S(e.lng+r,e.lat+o))}adjustAntiMeridian(){const e=new t.S(this._sw.lng,this._sw.lat),i=new t.S(this._ne.lng,this._ne.lat);return new G(e,e.lng>i.lng?new t.S(i.lng+360,i.lat):i)}}class V{constructor(e,t,i){this.bounds=G.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),o=Math.floor(t.V(this.bounds.getWest())*i),r=Math.floor(t.U(this.bounds.getNorth())*i),a=Math.ceil(t.V(this.bounds.getEast())*i),s=Math.ceil(t.U(this.bounds.getSouth())*i);return e.x>=o&&e.x=r&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.e({},this._options)}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};i.request.collectResourceTiming=this._collectResourceTiming;let o="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),o="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:o,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_afterTileLoadWorkerResponse(e,t){if(t&&t.resourceTiming&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return !1}}class q extends t.E{constructor(e,i,o,r){super(),this.id=e,this.dispatcher=o,this.setEventedParent(r),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.e({type:"raster"},i),t.e(this,t.Q(i,["url","scheme","tileSize"]));}load(){return t._(this,arguments,void 0,(function*(e=!1){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield Z(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,i&&(t.e(this,i),i.bounds&&(this.tileBounds=new V(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.l("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(!0);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.e({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const o=yield p.getImage(this.map._requestManager.transformRequest(i,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(o&&o.data){this.map._refreshExpiredTiles&&(o.cacheControl||o.expires)&&e.setExpiryData({cacheControl:o.cacheControl,expires:o.expires});const i=this.map.painter.context,r=i.gl,a=o.data;e.texture=this.map.painter.getTileTexture(a.width),e.texture?e.texture.update(a,{useMipmap:!0}):(e.texture=new t.T(i,a,r.RGBA,{useMipmap:!0}),e.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return !1}}class W extends q{constructor(e,i,o,r){super(e,i,o,r),this.type="raster-dem",this.maxzoom=22,this._options=t.e({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),o=this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield p.getImage(o,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const o=i.data;this.map._refreshExpiredTiles&&(i.cacheControl||i.expires)&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const r=t.b(o)&&t.W()?o:yield this.readImageNow(o),a={type:this.type,uid:e.uid,source:this.id,rawImageData:r,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!e.actor||"expired"===e.state){e.actor=this.dispatcher.getActor();const t=yield e.actor.sendAsync({type:"LDT",data:a});e.dem=t,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t._(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&t.X()){const i=e.width+2,o=e.height+2;try{return new t.R({width:i,height:o},yield t.Y(e,-1,-1,i,o))}catch(e){}}return s.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,o=Math.pow(2,i.z),r=(i.x-1+o)%o,a=0===i.x?e.wrap-1:e.wrap,s=(i.x+1+o)%o,n=i.x+1===o?e.wrap+1:e.wrap,l={};return l[new t.Z(e.overscaledZ,a,i.z,r,i.y).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y).key]={backfilled:!1},i.y>0&&(l[new t.Z(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y-1).key]={backfilled:!1}),i.y+1e.coordinates)).flat(1/0):e.coordinates.flat(1/0)}getBounds(){return t._(this,void 0,void 0,(function*(){const e=new G,t=yield this.getData();let i;switch(t.type){case "FeatureCollection":i=t.features.map((e=>this.getCoordinatesFromGeometry(e.geometry))).flat(1/0);break;case "Feature":i=this.getCoordinatesFromGeometry(t.geometry);break;default:i=this.getCoordinatesFromGeometry(t);}if(0==i.length)return e;for(let t=0;t0&&t.e(r,{resourceTiming:i}),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"metadata"}))),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"content"})));}catch(e){if(this._isUpdatingWorker=!1,this._removed)return void this.fire(new t.l("dataabort",{dataType:"source"}));this.fire(new t.k(e));}finally{(this._pendingWorkerUpdate.data||this._pendingWorkerUpdate.diff)&&this._updateWorkerData();}}))}loaded(){return !this._isUpdatingWorker&&void 0===this._pendingWorkerUpdate.data&&void 0===this._pendingWorkerUpdate.diff}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};e.abortController=new AbortController;const o=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(o,this.map.painter,"RT"===t);}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=!0;}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return !1}}class X extends t.E{constructor(e,t,i,o){super(),this.flippedWindingOrder=!1,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(o),this.options=t;}load(e){return t._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield p.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.a1.fromLngLat);var o;return this.tileID=function(e){const i=t.a2.fromPoints(e),o=i.width(),r=i.height(),a=Math.max(o,r),s=Math.max(0,Math.floor(-Math.log(a)/Math.LN2)),n=Math.pow(2,s);return new t.a4(s,Math.floor((i.minX+i.maxX)/2*n),Math.floor((i.minY+i.maxY)/2*n))}(i),this.terrainTileRanges=this._getOverlappingTileRanges(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((o=this.tileCoords)[1].x-o[0].x)*(o[2].y-o[0].y)-(o[1].y-o[0].y)*(o[2].x-o[0].x)<0,this.fire(new t.l("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new t.T(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t._(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return !1}_getOverlappingTileRanges(e){const{minX:i,minY:o,maxX:r,maxY:a}=t.a2.fromPoints(e),s={};for(let e=0;e<=t.a3;e++){const t=Math.pow(2,e),n=Math.floor(i*t),l=Math.floor(o*t),c=Math.floor(r*t),h=Math.floor(a*t);s[e]={minTileX:n,minTileY:l,maxTileX:c,maxTileY:h};}return s}}class K extends X{constructor(e,t,i,o){super(e,t,i,o),this.roundZoom=!0,this.type="video",this.options=t;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!1;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,"Source").url);try{const e=yield t.a5(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.k(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.k(new t.a6(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.T(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class Y extends X{constructor(e,i,o,r){super(e,i,o,r),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.k(new t.a6(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.k(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,o=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.T(i,this.canvas,o.RGBA,{premultiply:!0});let r=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=!0);}r&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return !0;return !1}}const Q={},J=e=>{switch(e){case "geojson":return H;case "image":return X;case "raster":return q;case "raster-dem":return W;case "vector":return $;case "video":return K;case "canvas":return Y}return Q[e]},ee="RTLPluginLoaded";class te extends t.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=B();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t._(this,arguments,void 0,(function*(e,t=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=s.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.l(ee));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let ie=null;function oe(){return ie||(ie=new te),ie}class re{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=e,this.uid=t.a7(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(e){const t=e+this.timeAdded;tt.getLayer(e))).filter(Boolean);if(0!==e.length){o.layers=e,o.stateDependentLayerIds&&(o.stateDependentLayers=o.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=o;}}return i}(e.buckets,null==i?void 0:i.style),this.hasSymbolBuckets=!1;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9){if(this.hasSymbolBuckets=!0,!o)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9&&i.hasRTLText){this.hasRTLText=!0,oe().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.a8;}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const i=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new t.T(e,this.imageAtlas.image,i.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new t.T(e,this.glyphAtlasImage,i.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,o,r,a,s,n,l,c,h){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:o,cameraQueryGeometry:r,scale:a,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:s,queryPadding:this.queryPadding*l,getElevation:h},e,t,i):{}}querySourceFeatures(e,i){const o=this.latestFeatureIndex;if(!o||!o.rawTileData)return;const r=o.loadVTLayers(),a=i&&i.sourceLayer?i.sourceLayer:"",s=r._geojsonTileLayer||r[a];if(!s)return;const n=t.aa(null==i?void 0:i.filter,null==i?void 0:i.globalState),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=!1;else if(i)if(this.expirationTime{this.remove(e,r);}),i)),this.data[o].push(r),this.order.push(o),this.order.length>this.max){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}has(e){return e.wrapped().key in this.data}getAndRemove(e){return this.has(e)?this._getAndRemoveByKey(e.wrapped().key):null}_getAndRemoveByKey(e){const t=this.data[e].shift();return t.timeout&&clearTimeout(t.timeout),0===this.data[e].length&&delete this.data[e],this.order.splice(this.order.indexOf(e),1),t.value}getByKey(e){const t=this.data[e];return t?t[0].value:null}get(e){return this.has(e)?this.data[e.wrapped().key][0].value:null}remove(e,t){if(!this.has(e))return this;const i=e.wrapped().key,o=void 0===t?0:this.data[i].indexOf(t),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(e){for(this.max=e;this.order.length>this.max;){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}filter(e){const t=[];for(const i in this.data)for(const o of this.data[i])e(o.value)||t.push(o);for(const e of t)this.remove(e.value.tileID,e);}}class se{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(e,i,o){const r=String(i);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][r]=this.stateChanges[e][r]||{},t.e(this.stateChanges[e][r],o),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==r&&(this.deletedStates[e][t]=null);}else if(this.deletedStates[e]&&null===this.deletedStates[e][r]){this.deletedStates[e][r]={};for(const t in this.state[e][r])o[t]||(this.deletedStates[e][r][t]=null);}else for(const t in o)this.deletedStates[e]&&this.deletedStates[e][r]&&null===this.deletedStates[e][r][t]&&delete this.deletedStates[e][r][t];}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const o=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&void 0!==t)null!==this.deletedStates[e][o]&&(this.deletedStates[e][o]=this.deletedStates[e][o]||{},this.deletedStates[e][o][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][o])for(i in this.deletedStates[e][o]={},this.stateChanges[e][o])this.deletedStates[e][o][i]=null;else this.deletedStates[e][o]=null;else this.deletedStates[e]=null;}getState(e,i){const o=String(i),r=t.e({},(this.state[e]||{})[o],(this.stateChanges[e]||{})[o]);if(null===this.deletedStates[e])return {};if(this.deletedStates[e]){const t=this.deletedStates[e][i];if(null===t)return {};for(const e in t)delete r[e];}return r}initializeTileState(e,t){e.setFeatureState(this.state,t);}coalesceChanges(e,i){const o={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const i={};for(const o in this.stateChanges[e])this.state[e][o]||(this.state[e][o]={}),t.e(this.state[e][o],this.stateChanges[e][o]),i[o]=this.state[e][o];o[e]=i;}for(const e in this.deletedStates){this.state[e]=this.state[e]||{};const i={};if(null===this.deletedStates[e])for(const t in this.state[e])i[t]={},this.state[e][t]={};else for(const t in this.deletedStates[e]){if(null===this.deletedStates[e][t])this.state[e][t]={};else for(const i of Object.keys(this.deletedStates[e][t]))delete this.state[e][t][i];i[t]=this.state[e][t];}o[e]=o[e]||{},t.e(o[e],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(o).length)for(const t in e)e[t].setFeatureState(o,i);}}const ne=89.25;function le(e,i){const o=t.ah(i.lat,-t.ai,t.ai);return new t.P(t.V(i.lng)*e,t.U(o)*e)}function ce(e,i){return new t.a1(i.x/e,i.y/e).toLngLat()}function he(e){return e.cameraToCenterDistance*Math.min(.85*Math.tan(t.ae(90-e.pitch)),Math.tan(t.ae(ne-e.pitch)))}function ue(e,i){const o=e.canonical,r=i/t.af(o.z),a=o.x+Math.pow(2,o.z)*e.wrap,s=t.ag(new Float64Array(16));return t.M(s,s,[a*r,o.y*r,0]),t.N(s,s,[r/t.$,r/t.$,1]),s}function de(e,i,o,r,a){const s=t.a1.fromLngLat(e,i),n=a*t.aj(1,e.lat),l=n*Math.cos(t.ae(o)),c=Math.sqrt(n*n-l*l),h=c*Math.sin(t.ae(-r)),u=c*Math.cos(t.ae(-r));return new t.a1(s.x+h,s.y+u,s.z+l)}function _e(e,t,i){const o=t.intersectsFrustum(e);if(!i||0===o)return o;const r=t.intersectsPlane(i);return 0===r?0:2===o&&2===r?2:1}function pe(e,t,i){let o=0;const r=(i-t)/10;for(let a=0;a<10;a++)o+=r*Math.pow(Math.cos(t+(a+.5)/10*(i-t)),e);return o}function me(e,i){return function(o,r,a,s,n){const l=2*((e-1)/t.ak(Math.cos(t.ae(ne-n))/Math.cos(t.ae(ne)))-1),c=Math.acos(a/s),h=2*pe(l-1,0,t.ae(n/2)),u=Math.min(t.ae(ne),c+t.ae(n/2)),d=pe(l-1,Math.min(u,c-t.ae(n/2)),u),_=Math.atan(r/a),p=Math.hypot(r,a);let m=o;return m+=t.ak(s/p/Math.max(.5,Math.cos(t.ae(n/2)))),m+=l*t.ak(Math.cos(_))/2,m-=t.ak(Math.max(1,d/h/i))/2,m}}const fe=me(9.314,3);function ge(e,i){const o=(i.roundZoom?Math.round:Math.floor)(e.zoom+t.ak(e.tileSize/i.tileSize));return Math.max(0,o)}function ve(e,i){const o=e.getCameraFrustum(),r=e.getClippingPlane(),a=e.screenPointToMercatorCoordinate(e.getCameraPoint()),s=t.a1.fromLngLat(e.center,e.elevation);a.z=s.z+Math.cos(e.pitchInRadians)*e.cameraToCenterDistance/e.worldSize;const n=e.getCoveringTilesDetailsProvider(),l=n.allowVariableZoom(e,i),c=ge(e,i),h=i.minzoom||0,u=void 0!==i.maxzoom?i.maxzoom:e.maxZoom,d=Math.min(Math.max(0,c),u),_=Math.pow(2,d),p=[_*a.x,_*a.y,0],m=[_*s.x,_*s.y,0],f=Math.hypot(s.x-a.x,s.y-a.y),g=Math.abs(s.z-a.z),v=Math.hypot(f,g),b=e=>({zoom:0,x:0,y:0,wrap:e,fullyVisible:!1}),x=[],y=[];if(e.renderWorldCopies&&n.allowWorldCopies())for(let e=1;e<=3;e++)x.push(b(-e)),x.push(b(e));for(x.push(b(0));x.length>0;){const _=x.pop(),f=_.x,b=_.y;let w=_.fullyVisible;const T={x:f,y:b,z:_.zoom},P=n.getTileBoundingVolume(T,_.wrap,e.elevation,i);if(!w){const e=_e(o,P,r);if(0===e)continue;w=2===e;}const C=n.distanceToTile2d(a.x,a.y,T,P);let I=c;l&&(I=(i.calculateTileZoom||fe)(e.zoom+t.ak(e.tileSize/i.tileSize),C,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const M=Math.min(I,u);if(_.wrap=n.getWrap(s,T,_.wrap),_.zoom>=M){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return y.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}const be=t.a2.fromPoints([new t.P(0,0),new t.P(t.$,t.$)]);class xe extends t.E{constructor(e,t,i){super(),this.id=e,this.dispatcher=i,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=!1;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,o)=>{const r=new(J(t.type))(e,t,i,o);if(r.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${r.id}`);return r})(e,t,i,this),this._tiles={},this._cache=new ae(0,(e=>this._unloadTile(e))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new se,this._didEmitContent=!1,this._updated=!1;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e);}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return !0;if(!this._updated)return !1;for(const e in this._tiles){const t=this._tiles[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}return !0}getSource(){return this._source}pause(){this._paused=!0;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,o){return t._(this,void 0,void 0,(function*(){try{yield this._source.loadTile(e),this._tileLoaded(e,i,o);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.k(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.l("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const t in this._tiles){const i=this._tiles[t];i.upload(e),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(ye).map((e=>e.key))}getRenderableIds(e){const i=[];for(const t in this._tiles)this._isIdRenderable(t,e)&&i.push(this._tiles[t]);return e?i.sort(((e,i)=>{const o=e.tileID,r=i.tileID,a=new t.P(o.canonical.x,o.canonical.y)._rotate(-this.transform.bearingInRadians),s=new t.P(r.canonical.x,r.canonical.y)._rotate(-this.transform.bearingInRadians);return o.overscaledZ-r.overscaledZ||s.y-a.y||s.x-a.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(ye).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return !!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())}reload(e){if(this._paused)this._shouldReloadOnResume=!0;else {this._cache.reset();for(const t in this._tiles)e?this._reloadTile(t,"expired"):"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading");}}_reloadTile(e,i){return t._(this,void 0,void 0,(function*(){const t=this._tiles[e];t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,o){e.timeAdded=s.now(),"expired"===o&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.l("data",{dataType:"source",tile:e,coord:e.tileID}));}_backfillDEM(e){const t=this.getRenderableIds();for(let o=0;o1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,o),e.neighboringTiles&&e.neighboringTiles[a]&&(e.neighboringTiles[a].backfilled=!0)));}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,o){for(const r in this._tiles){let a=this._tiles[r];if(o[r]||!a.hasData()||a.tileID.overscaledZ<=t||a.tileID.overscaledZ>i)continue;let s=a.tileID;for(;a&&a.tileID.overscaledZ>t+1;){const e=a.tileID.scaledTo(a.tileID.overscaledZ-1);a=this._tiles[e.key],a&&a.hasData()&&(s=e);}let n=s;for(;n.overscaledZ>t;)if(n=n.scaledTo(n.overscaledZ-1),e[n.key]||e[n.canonical.key]){o[s.key]=s;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),o=this._getLoadedTile(t);if(o)return o}}findLoadedSibling(e){return this._getLoadedTile(e)}_getLoadedTile(e){const t=this._tiles[e.key];return t&&t.hasData()?t:this._cache.getByKey(e.wrapped().key)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,o=Math.ceil(e.height/this._source.tileSize)+1,r=Math.floor(i*o*(null===this._maxTileCacheZoomLevels?t.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),a="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(a);}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e={};for(const i in this._tiles){const o=this._tiles[i];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),e[o.tileID.key]=o;}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(e,this._tiles[e]);}}_updateCoveredAndRetainedTiles(e,t,i,o,r,a){const n={},l={},c=Object.keys(e),h=s.now();for(const i of c){const o=e[i],r=this._tiles[i];if(!r||0!==r.fadeEndTime&&r.fadeEndTime<=h)continue;const a=this.findLoadedParent(o,t),s=this.findLoadedSibling(o),c=a||s||null;c&&(this._addTile(c.tileID),n[c.tileID.key]=c.tileID),l[i]=o;}this._retainLoadedChildren(l,o,i,e);for(const t in n)e[t]||(this._coveredTiles[t]=!0,e[t]=n[t]);if(a){const t={},i={};for(const e of r)this._tiles[e.key].hasData()?t[e.key]=e:i[e.key]=e;for(const o in i){const r=i[o].children(this._source.maxzoom);this._tiles[r[0].key]&&this._tiles[r[1].key]&&this._tiles[r[2].key]&&this._tiles[r[3].key]&&(t[r[0].key]=e[r[0].key]=r[0],t[r[1].key]=e[r[1].key]=r[1],t[r[2].key]=e[r[2].key]=r[2],t[r[3].key]=e[r[3].key]=r[3],delete i[o]);}for(const o in i){const r=i[o],a=this.findLoadedParent(r,this._source.minzoom),s=this.findLoadedSibling(r),n=a||s||null;if(n){t[n.tileID.key]=e[n.tileID.key]=n.tileID;for(const e in t)t[e].isChildOf(n.tileID)&&delete t[e];}}for(const e in this._tiles)t[e]||(this._coveredTiles[e]=!0);}}update(e,i){if(!this._sourceLoaded||this._paused)return;let o;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?o=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.Z(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(o=ve(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(o=o.filter((e=>this._source.hasTile(e))))):o=[];const r=ge(e,this._source),a=Math.max(r-xe.maxOverzooming,this._source.minzoom),s=Math.max(r+xe.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const e={};for(const t of o)if(t.canonical.z>this._source.minzoom){const i=t.scaledTo(t.canonical.z-1);e[i.key]=i;const o=t.scaledTo(Math.max(this._source.minzoom,Math.min(t.canonical.z,5)));e[o.key]=o;}o=o.concat(Object.values(e));}const n=0===o.length&&!this._updated&&this._didEmitContent;this._updated=!0,n&&this.fire(new t.l("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(o,r);we(this._source.type)&&this._updateCoveredAndRetainedTiles(l,a,s,r,o,i);for(const e in l)this._tiles[e].clearFadeHold();const c=t.am(this._tiles,l);for(const e of c){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const o={},r={},a=Math.max(t-xe.maxOverzooming,this._source.minzoom),s=Math.max(t+xe.maxUnderzooming,this._source.minzoom),n={};for(const i of e){const e=this._addTile(i);o[i.key]=i,e.hasData()||tthis._source.maxzoom){const e=s.children(this._source.maxzoom)[0],t=this.getTile(e);if(t&&t.hasData()){o[e.key]=e;continue}}else {const e=s.children(this._source.maxzoom);if(4===e.length&&o[e[0].key]&&o[e[1].key]&&o[e[2].key]&&o[e[3].key])continue;if(1===e.length&&o[e[0].key])continue}let n=e.wasRequested();for(let t=s.overscaledZ-1;t>=a;--t){const a=s.scaledTo(t);if(r[a.key])break;if(r[a.key]=!0,e=this.getTile(a),!e&&n&&(e=this._addTile(a)),e){const t=e.hasData();if((t||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||n)&&(o[a.key]=a),n=e.wasRequested(),t)break}}}return o}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,o=this._tiles[e].tileID;for(;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}t.push(o.key);const e=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;o=e;}for(const e of t)this._loadedParentTiles[e]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const e in this._tiles){const t=this._tiles[e].tileID,i=this._getLoadedTile(t);this._loadedSiblingTiles[t.key]=i;}}_addTile(e){let i=this._tiles[e.key];if(i)return i;i=this._cache.getAndRemove(e),i&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));const o=i;return i||(i=new re(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._tiles[e.key]=i,o||this._source.fire(new t.l("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}refreshTiles(e){for(const t in this._tiles)(this._isIdRenderable(t)||"errored"==this._tiles[t].state)&&e.some((e=>e.equals(this._tiles[t].tileID.canonical)))&&this._reloadTile(t,"expired");}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=!0,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){const t=e.sourceDataType;"source"===e.dataType&&"metadata"===t&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===t&&(this.reload(e.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0);}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e in this._tiles)this._removeTile(e);this._cache.reset();}tilesIn(e,i,o){const r=[],a=this.transform;if(!a)return r;const s=a.getCoveringTilesDetailsProvider().allowWorldCopies(),n=o?a.getCameraQueryGeometry(e):e,l=e=>a.screenPointToMercatorCoordinate(e,this.terrain),c=this.transformBbox(e,l,!s),h=this.transformBbox(n,l,!s),u=this.getIds(),d=t.a2.fromPoints(h);for(let e=0;ee.getTilePoint(new t.a1(i.x,i.y))));if(i.expandBy(_),i.intersects(be)){const t=c.map((t=>e.getTilePoint(t))),i=h.map((t=>e.getTilePoint(t)));r.push({tile:o,tileID:s?e:e.unwrapTo(0),queryGeometry:t,cameraQueryGeometry:i,scale:l});}}}return r}transformBbox(e,i,o){let r=e.map(i);if(o){const o=t.a2.fromPoints(e);o.shrinkBy(.001*Math.min(o.width(),o.height()));const a=o.map(i);t.a2.fromPoints(r).covers(a)||(r=r.map((e=>e.x>.5?new t.a1(e.x-1,e.y,e.z):e)));}return r}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._tiles[e].tileID));return this.transform&&this.transform.populateCache(t),t}hasTransition(){if(this._source.hasTransition())return !0;if(we(this._source.type)){const e=s.now();for(const t in this._tiles)if(this._tiles[t].fadeEndTime>=e)return !0}return !1}setFeatureState(e,t,i){this._state.updateState(e=e||"_geojsonTileLayer",t,i);}removeFeatureState(e,t,i){this._state.removeFeatureState(e=e||"_geojsonTileLayer",t,i);}getFeatureState(e,t){return this._state.getState(e=e||"_geojsonTileLayer",t)}setDependencies(e,t,i){const o=this._tiles[e];o&&o.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)));}}function ye(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),o=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||o-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function we(e){return "raster"===e||"image"===e||"video"===e}xe.maxOverzooming=10,xe.maxUnderzooming=3;class Te{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(r-s)/n:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))}}function Pe(e,t){let i=!0;return "always"===e||"never"!==e&&"never"!==t||(i=!1),i}class Ce{constructor(e,t,i){const o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||o<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=o){if(r)return [{key:null,x1:e,y1:t,x2:i,y2:o}];for(let e=0;e0}hitTestCircle(e,t,i,o,r){const a=e-i,s=e+i,n=t-i,l=t+i;if(s<0||a>this.width||l<0||n>this.height)return !1;const c=[];return this._forEachCell(a,n,s,l,this._queryCellCircle,c,{hitTest:!0,overlapMode:o,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},r),c.length>0}_queryCell(e,t,i,o,r,a,s,n){const{seenUids:l,hitTest:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const r=this.bboxes;for(const s of u)if(!l.box[s]){l.box[s]=!0;const u=4*s,d=this.boxKeys[s];if(e<=r[u+2]&&t<=r[u+3]&&i>=r[u+0]&&o>=r[u+1]&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))&&(a.push({key:d,x1:r[u],y1:r[u+1],x2:r[u+2],y2:r[u+3]}),c))return !0}}const d=this.circleCells[r];if(null!==d){const r=this.circles;for(const s of d)if(!l.circle[s]){l.circle[s]=!0;const u=3*s,d=this.circleKeys[s];if(this._circleAndRectCollide(r[u],r[u+1],r[u+2],e,t,i,o)&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))){const e=r[u],t=r[u+1],i=r[u+2];if(a.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return !0}}}return !1}_queryCellCircle(e,t,i,o,r,a,s,n){const{circle:l,seenUids:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=!0;const i=4*t,o=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}const d=this.circleCells[r];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=!0;const i=3*t,o=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}}_forEachCell(e,t,i,o,r,a,s,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(o);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(r.call(this,e,t,i,o,this.xCellCount*l+d,a,s,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,o,r,a){const s=o-e,n=r-t,l=i+a;return l*l>s*s+n*n}_circleAndRectCollide(e,t,i,o,r,a,s){const n=(a-o)/2,l=Math.abs(e-(o+n));if(l>n+i)return !1;const c=(s-r)/2,h=Math.abs(t-(r+c));if(h>c+i)return !1;if(l<=n||h<=c)return !0;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function Ie(e,i,r){const a=t.L();if(!e){const{vecSouth:e,vecEast:t}=Se(i),r=o();r[0]=t[0],r[1]=t[1],r[2]=e[0],r[3]=e[1],s=r,(d=(l=(n=r)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(s[0]=u*(d=1/d),s[1]=-c*d,s[2]=-h*d,s[3]=l*d),a[0]=r[0],a[1]=r[1],a[4]=r[2],a[5]=r[3];}var s,n,l,c,h,u,d;return t.N(a,a,[1/r,1/r,1]),a}function Me(e,i,o,r){if(e){const e=t.L();if(!i){const{vecSouth:t,vecEast:i}=Se(o);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.N(e,e,[r,r,1]),e}return o.pixelsToClipSpaceMatrix}function Se(e){const i=Math.cos(e.rollInRadians),o=Math.sin(e.rollInRadians),r=Math.cos(e.pitchInRadians),a=Math.cos(e.bearingInRadians),s=Math.sin(e.bearingInRadians),n=t.ar();n[0]=-a*r*o-s*i,n[1]=-s*r*o+a*i;const l=t.as(n);l<1e-9?t.at(n):t.au(n,n,1/l);const c=t.ar();c[0]=a*r*i-s*o,c[1]=s*r*i+a*o;const h=t.as(c);return h<1e-9?t.at(c):t.au(c,c,1/h),{vecEast:c,vecSouth:n}}function Ee(e,i,o,r){let a;r?(a=[e,i,r(e,i),1],t.aw(a,a,o)):(a=[e,i,0,1],qe(a,a,o));const s=a[3];return {point:new t.P(a[0]/s,a[1]/s),signedDistanceFromCamera:s,isOccluded:!1}}function Re(e,t){return .5+e/t*.5}function ze(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function De(e,i,o,r,a,s,n,l,c,h,u,d,_){const p=o?e.textSizeData:e.iconSizeData,m=t.an(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=o?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,b=o?e.text.placedSymbolArray:e.icon.placedSymbolArray,x=i.transform.width/i.transform.height;let y=!1;for(let o=0;oMath.abs(o.x-i.x)*r?{useVertical:!0}:(e===t.ao.vertical?i.yo.x)?{needsFlipping:!0}:null}function ke(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:o,symbol:r,fontSize:a,flip:s,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=a/24,_=r.lineOffsetX*d,p=r.lineOffsetY*d;let m;if(r.numGlyphs>1){const e=r.glyphStartIndex+r.numGlyphs,t=r.lineStartIndex,a=r.lineStartIndex+r.lineLength,c=Ae(d,l,_,p,s,r,u,i);if(!c)return {notEnoughRoom:!0};const f=je(c.first.point.x,c.first.point.y,i,o),g=je(c.last.point.x,c.last.point.y,i,o);if(n&&!s){const e=Le(r.writingMode,f,g,h);if(e)return e}m=[c.first];for(let o=r.glyphStartIndex+1;o0?n.point:Fe(i.tileAnchorPoint,s,e,1,i),c=je(e.x,e.y,i,o),u=je(l.x,l.y,i,o),d=Le(r.writingMode,c,u,h);if(d)return d}const e=Ge(d*l.getoffsetX(r.glyphStartIndex),_,p,s,r.segment,r.lineStartIndex,r.lineStartIndex+r.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:!0};m=[e];}for(const e of m)t.av(c,e.point,e.angle);return {}}function Fe(e,t,i,o,r){const a=e.add(e.sub(t)._unit()),s=Oe(a.x,a.y,r).point,n=i.sub(s);return i.add(n._mult(o/n.mag()))}function Be(e,i,o){const r=i.projectionCache;if(r.projections[e])return r.projections[e];const a=new t.P(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),s=Oe(a.x,a.y,i);if(s.signedDistanceFromCamera>0)return r.projections[e]=s.point,r.anyProjectionOccluded=r.anyProjectionOccluded||s.isOccluded,s.point;const n=e-o.direction;return Fe(0===o.distanceFromAnchor?i.tileAnchorPoint:new t.P(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),a,o.previousVertex,o.absOffsetX-o.distanceFromAnchor+1,i)}function Oe(e,t,i){const o=e+i.translation[0],r=t+i.translation[1];let a;return i.pitchWithMap?(a=Ee(o,r,i.pitchedLabelPlaneMatrix,i.getElevation),a.isOccluded=!1):(a=i.transform.projectTileCoordinates(o,r,i.unwrappedTileID,i.getElevation),a.point.x=(.5*a.point.x+.5)*i.width,a.point.y=(.5*-a.point.y+.5)*i.height),a}function je(e,i,o,r){if(o.pitchWithMap){const a=[e,i,0,1];return t.aw(a,a,r),o.transform.projectTileCoordinates(a[0]/a[3],a[1]/a[3],o.unwrappedTileID,o.getElevation).point}return {x:e/o.width*2-1,y:1-i/o.height*2}}function Ne(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function Ue(e,t,i){return e._unit()._perp()._mult(t*i)}function Ze(e,i,o,r,a,s,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=o.add(i);if(e+c.direction=a)return l.projectionCache.offsets[e]=h,h;const u=Be(e+c.direction,l,c),d=Ue(u.sub(o),n,c.direction),_=o.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.ax(s,h,_,p)||h,l.projectionCache.offsets[e]}function Ge(e,t,i,o,r,a,s,n,l){const c=o?e-t:e+t;let h=c>0?1:-1,u=0;o&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?a+r:a+r+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Oe(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,b=0;const x=Math.abs(c),y=[];let w;for(;v+b<=x;){if(_+=h,_=s)return null;v+=b,g=f,m=p;const e={absOffsetX:x,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=Be(_,n,e),0===i)y.push(g),w=f.sub(g);else {let t;const o=f.sub(g);t=0===o.mag()?Ue(Be(_+h,n,e).sub(f),i,h):Ue(o,i,h),m||(m=g.add(t)),p=Ze(_,t,f,a,s,m,i,n,e),y.push(m),w=p.sub(m);}b=w.mag();}const T=w._mult((x-v)/b)._add(m||g),P=u+Math.atan2(f.y-g.y,f.x-g.x);return y.push(T),{point:T,angle:l?P:0,path:y}}const Ve=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function $e(e,t){for(let i=0;i=1;e--)_.push(s.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=o.x&&i.x<=r.x&&e.y>=o.y&&i.y<=r.y?[_]:i.xr.x||i.yr.y?[]:t.ay([_],o.x,o.y,r.x,r.y);}for(const t of f){a.reset(t,.25*i);let o=0;o=a.length<=.5*i?1:Math.ceil(a.paddedLength/p)+1;for(let t=0;t{const t=Ee(e.x,e.y,o,i.getElevation),r=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return r.point.x=(.5*r.point.x+.5)*i.width,r.point.y=(.5*-r.point.y+.5)*i.height,r}))}(e,i);return function(e){let t=0,i=0,o=0,r=0;for(let a=0;ai&&(i=r,t=o));return e.slice(t,t+i)}(o)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[],o=new t.a2;for(const r of e){const e=new t.P(r.x+We,r.y+We);o.extend(e),i.push(e);}const{minX:r,minY:a,maxX:s,maxY:n}=o,l=this.grid.query(r,a,s,n).concat(this.ignoredGrid.query(r,a,s,n)),c={},h={};for(const e of l){const o=e.key;if(void 0===c[o.bucketInstanceId]&&(c[o.bucketInstanceId]={}),c[o.bucketInstanceId][o.featureIndex])continue;const r=[new t.P(e.x1,e.y1),new t.P(e.x2,e.y1),new t.P(e.x2,e.y2),new t.P(e.x1,e.y2)];t.az(i,r)&&(c[o.bucketInstanceId][o.featureIndex]=!0,void 0===h[o.bucketInstanceId]&&(h[o.bucketInstanceId]=[]),h[o.bucketInstanceId].push(o.featureIndex));}return h}insertCollisionBox(e,t,i,o,r,a){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,o,r,a){const s=i?this.ignoredGrid:this.grid,n={bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t};for(let t=0;t=this.screenRightBoundary||othis.screenBottomBoundary}isInsideGrid(e,t,i,o){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,r,c,u)));E=e.some((e=>!e.isOccluded)),S=e.map((e=>new t.P(e.x,e.y)));}else E=!0;return {box:t.aA(S),allPointsOccluded:!E}}}class Xe{constructor(e,t,i,o){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):o&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class Ke{constructor(e,t,i,o,r){this.text=new Xe(e?e.text:null,t,i,r),this.icon=new Xe(e?e.icon:null,t,o,r);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ye{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class Qe{constructor(e,t,i,o,r){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=r;}}class Je{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function et(e,i,o,r,a){const{horizontalAlign:s,verticalAlign:n}=t.aH(e);return new t.P(-(s-.5)*i+r[0]*a,-(n-.5)*o+r[1]*a)}class tt{constructor(e,t,i,o,r){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new He(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new Je(o),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=r,r&&(r.prevPlacement=void 0),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,o)=>t.getElevation(e,i,o):null}getBucketParts(e,i,o,r){const a=o.getBucket(i),s=o.latestFeatureIndex;if(!a||!s||i.id!==a.layerIds[0])return;const n=o.collisionBoxArray,l=a.layers[0].layout,c=a.layers[0].paint,h=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),u=o.tileSize/t.$,d=o.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.aC(o,1,this.transform.zoom),m=t.aD(this.collisionIndex.transform,o,c.get("text-translate"),c.get("text-translate-anchor")),f=t.aD(this.collisionIndex.transform,o,c.get("icon-translate"),c.get("icon-translate-anchor")),g=Ie(_,this.transform,p);this.retainedQueryData[a.bucketInstanceId]=new Qe(a.bucketInstanceId,s,a.sourceLayerIndex,a.index,o.tileID);const v={bucket:a,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:o.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.an(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(r)for(const t of a.sortKeyRanges){const{sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r}=t;e.push({sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v,b,x){const y=t.aE[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=et(y,o,r,w,a),P=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,s,f,u.predicate,b,T,x);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,s,g,u.predicate,b,T,x).placeable)&&P.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:o,height:r,anchor:y,textBoxScale:a,prevAnchor:e},this.markUsedJustification(p,y,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:P}}}placeLayerBucketPart(e,i,o){const{bucket:r,layout:a,translationText:s,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=a.get("text-optional"),f=a.get("icon-optional"),g=t.aF(a,"text-overlap","text-allow-overlap"),v="always"===g,b=t.aF(a,"icon-overlap","icon-allow-overlap"),x="always"===b,y="map"===a.get("text-rotation-alignment"),w="map"===a.get("text-pitch-alignment"),T="none"!==a.get("icon-text-fit"),P="viewport-y"===a.get("symbol-z-order"),C=v&&(x||!r.hasIconData()||f),I=x&&(v||!r.hasTextData()||m);!r.collisionArrays&&d&&r.deserializeCollisionBoxes(d);const M=this.retainedQueryData[r.bucketInstanceId].tileID,S=this._getTerrainElevationFunc(M),E=this.transform.getFastPathSimpleProjectionMatrix(M),R=(e,d,x)=>{var P,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new Ye(!1,!1,!1));let z=!1,D=!1,A=!0,L=null,k={box:null,placeable:!1,offscreen:null,occluded:!1},F={placeable:!1},B=null,O=null,j=null,N=0,U=0,Z=0;d.textFeatureIndex?N=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(N=e.featureIndex),d.verticalTextFeatureIndex&&(U=d.verticalTextFeatureIndex);const G=d.textBox;if(G){const i=i=>{let o=t.ao.horizontal;if(r.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,o=t,this.markUsedOrientation(r,o,e));}return o},a=(i,o)=>{if(r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of r.writingModes)if(e===t.ao.vertical?(k=o(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const o=(t,i)=>{const o=this.collisionIndex.placeCollisionBox(t,g,h,M,l,w,y,s,p.predicate,S,void 0,E);return o&&o.placeable&&(this.markUsedOrientation(r,i,e),this.placedOrientations[e.crossTileID]=i),o};a((()=>o(G,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?o(i,t.ao.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.aE[null===(R=null===(P=this.prevPlacement)||void 0===P?void 0:P.variableOffsets[e.crossTileID])||void 0===R?void 0:R.anchor];const m=(t,i,a)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===b?i:null;let x=null,P="never"===g?1:2,C="never";_&&P++;for(let i=0;im(G,d.iconBox,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.ao.vertical):{box:null,occluded:!0,offscreen:null}})),k&&(z=k.placeable,A=k.offscreen);const f=i(k&&k.placeable);if(!z&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(r,t.anchor,e,f));}}}if(B=k,z=B&&B.placeable,A=B&&B.offscreen,e.useRuntimeCollisionCircles){const i=r.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.ap(r.textSizeData,_,i),h=a.get("text-padding");O=this.collisionIndex.placeCollisionCircles(g,i,r.lineVertexArray,r.glyphOffsetArray,n,l,c,o,w,p.predicate,e.collisionCircleDiameter,h,s,S),O.circles.length&&O.collisionDetected&&!o&&t.w("Collisions detected, but collision boxes are not shown"),z=v||O.circles.length>0&&!O.collisionDetected,A=A&&O.offscreen;}if(d.iconFeatureIndex&&(Z=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,b,h,M,l,w,y,n,p.predicate,S,T&&L?L:void 0,E);F&&F.placeable&&d.verticalIconBox?(j=e(d.verticalIconBox),D=j.placeable):(j=e(d.iconBox),D=j.placeable),A=A&&j.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,$=f||0===e.numIconVertices;V||$?$?V||(D=D&&z):z=D&&z:D=z=D&&z;const q=D&&j.placeable;if(z&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,a.get("text-ignore-placement"),r.bucketInstanceId,F&&F.placeable&&U?U:N,p.ID),q&&this.collisionIndex.insertCollisionBox(j.box,b,a.get("icon-ignore-placement"),r.bucketInstanceId,Z,p.ID),O&&z&&this.collisionIndex.insertCollisionCircles(O.circles,g,a.get("text-ignore-placement"),r.bucketInstanceId,N,p.ID),o&&this.storeCollisionData(r.bucketInstanceId,x,d,B,j,O),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===r.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new Ye((z||C)&&!(null==B?void 0:B.occluded),(D||I)&&!(null==j?void 0:j.occluded),A||r.justReloaded),i[e.crossTileID]=!0;};if(P){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=r.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(r.symbolInstances.get(i),r.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=a>=0&&t!==a?0:o.crossTileID);}markUsedOrientation(e,i,o){const r=i===t.ao.horizontal||i===t.ao.horizontalOnly?i:0,a=i===t.ao.vertical?i:0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];for(const t of s)e.text.placedSymbolArray.get(t).placedOrientation=r;o.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).placedOrientation=a);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=!1;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const o=t?t.symbolFadeChange(e):1,r=t?t.opacities:{},a=t?t.variableOffsets:{},s=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],a=r[e];a?(this.opacities[e]=new Ke(a,o,t.text,t.icon),i=i||t.text!==a.text.placed||t.icon!==a.icon.placed):(this.opacities[e]=new Ke(null,o,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in r){const t=r[e];if(!this.opacities[e]){const r=new Ke(t,o,!1,!1);r.isHidden()||(this.opacities[e]=r,i=i||t.text.placed||t.icon.placed);}}for(const e in a)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=a[e]);for(const e in s)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=s[e]);if(t&&void 0===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const o of t){const t=o.getBucket(e);t&&o.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,o.tileID,i,o.collisionBoxArray);}}updateBucketOpacities(e,i,o,r){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=!1),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=!1),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const a=e.layers[0],s=a.layout,n=new Ke(null,0,!1,!1,!0),l=s.get("text-allow-overlap"),c=s.get("icon-allow-overlap"),h=a._unevaluatedLayout.hasValue("text-variable-anchor")||a._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===s.get("text-rotation-alignment"),d="map"===s.get("text-pitch-alignment"),_="none"!==s.get("icon-text-fit"),p=new Ke(null,0,l&&(c||!e.hasIconData()||s.get("icon-optional")),c&&(l||!e.hasTextData()||s.get("text-optional")),!0);!e.collisionArrays&&r&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(r);const m=(e,t,i)=>{for(let o=0;o0,v=this.placedOrientations[r.crossTileID],b=v===t.ao.vertical,x=v===t.ao.horizontal||v===t.ao.horizontalOnly;if(a>0||s>0){const t=ht(c.text);m(e.text,a,b?ut:t),m(e.text,s,x?ut:t);const i=c.text.isHidden();[r.rightJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||b?1:0);})),r.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).hidden=i||x?1:0);const o=this.variableOffsets[r.crossTileID];o&&this.markUsedJustification(e,o.anchor,r,v);const n=this.placedOrientations[r.crossTileID];n&&(this.markUsedJustification(e,"left",r,n),this.markUsedOrientation(e,n,r));}if(g){const t=ht(c.icon),i=!(_&&r.verticalPlacedIconSymbolIndex&&b);r.placedIconSymbolIndex>=0&&(m(e.icon,r.numIconVertices,i?t:ut),e.icon.placedSymbolArray.get(r.placedIconSymbolIndex).hidden=c.icon.isHidden()),r.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,r.numVerticalIconVertices,i?ut:t),e.icon.placedSymbolArray.get(r.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const y=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const o=e.collisionArrays[i];if(o){let i=new t.P(0,0);if(o.textBox||o.verticalTextBox){let t=!0;if(h){const e=this.variableOffsets[l];e?(i=et(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=!1;}if(o.textBox||o.verticalTextBox){let r;o.textBox&&(r=b),o.verticalTextBox&&(r=x),it(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||r,y.text,i.x,i.y);}}if(o.iconBox||o.verticalIconBox){const t=Boolean(!x&&o.verticalIconBox);let r;o.iconBox&&(r=t),o.verticalIconBox&&(r=!t),it(e.iconCollisionBox.collisionVertexArray,c.icon.placed,r,y.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=!0;}}function it(e,t,i,o,r,a){o&&0!==o.length||(o=[0,0,0,0]);const s=o[0]-We,n=o[1]-We,l=o[2]-We,c=o[3]-We;e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,c),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,c);}const ot=Math.pow(2,25),rt=Math.pow(2,24),at=Math.pow(2,17),st=Math.pow(2,16),nt=Math.pow(2,9),lt=Math.pow(2,8),ct=Math.pow(2,1);function ht(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*ot+t*rt+i*at+t*st+i*nt+t*lt+i*ct+t}const ut=0;class dt{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,o,r){const a=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&s.now()-o>2;for(;this._currentPlacementIndex>=0;){const o=t[e[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if("symbol"===o.type&&(!o.minzoom||o.minzoom<=a)&&(!o.maxzoom||o.maxzoom>a)){if(this._inProgressLayer||(this._inProgressLayer=new dt(o)),this._inProgressLayer.continuePlacement(i[o.source],this.placement,this._showCollisionBoxes,o,r))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(e){return this.placement.commit(e),this.placement}}const pt=512/t.$/2;class mt{constructor(e,i,o){this.tileID=e,this.bucketInstanceId=o,this._symbolsByKey={};const r=new Map;for(let e=0;e({x:Math.floor(e.anchorX*pt),y:Math.floor(e.anchorY*pt)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(o.positions.length>128){const e=new t.aI(o.positions.length,16,Uint16Array);for(const{x:t,y:i}of o.positions)e.add(t,i);e.finish(),delete o.positions,o.index=e;}this._symbolsByKey[e]=o;}}getScaledCoordinates(e,i){const{x:o,y:r,z:a}=this.tileID.canonical,{x:s,y:n,z:l}=i.canonical,c=pt/Math.pow(2,l-a),h=(n*t.$+e.anchorY)*c,u=r*t.$*pt;return {x:Math.floor((s*t.$+e.anchorX)*c-o*t.$*pt),y:Math.floor(h-u)}}findMatches(e,t,i){const o=this.tileID.canonical.ze))}}class ft{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class gt{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],o={};for(const e in i){const r=i[e];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+t),o[r.tileID.key]=r;}this.indexes[e]=o;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in r){const a=r[i];a.tileID.isChildOf(e)&&a.findMatches(t.symbolInstances,e,o);}else {const a=r[e.scaledTo(Number(i)).key];a&&a.findMatches(t.symbolInstances,e,o);}}for(let e=0;e{t[e]=!0;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var bt="void main() {fragColor=vec4(1.0);}";const xt={prelude:yt("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:yt("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:yt("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:yt("uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:yt("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:yt("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:yt(bt,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:yt("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:yt("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:yt("in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:yt("in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),colorRelief:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform int u_color_ramp_size;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {float x=(float(stop)+0.5)/float(u_color_ramp_size);vec4 data=texture(u_elevation_stops,vec2(x,0))*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int r=(u_color_ramp_size-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else\n{l=m;el_l=el_m;}}float x=(float(l)+(el-el_l)/(el_r-el_l)+0.5)/float(u_color_ramp_size);fragColor=u_opacity*texture(u_color_stops,vec2(x,0));\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_dimension;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),debug:yt("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}","in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:yt(bt,"in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:yt("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:yt("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:yt("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:yt("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:yt("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {vec2 epsilon=1.0/u_dimension;float tileSize=u_dimension.x-2.0;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))*tileSize/pow(2.0,exaggeration+(28.2562-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+0.5,deriv.y/8.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:yt("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];\n#define PI 3.141592653589793\n#define STANDARD 0\n#define COMBINED 1\n#define IGOR 2\n#define MULTIDIRECTIONAL 3\n#define BASIC 4\nfloat get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);}void igor_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float aspect=get_aspect(deriv);float azimuth=u_azimuths[0]+PI;float slope_stength=atan(length(deriv))*2.0/PI;float aspect_strength=1.0-abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);float shadow_strength=slope_stength*aspect_strength;float highlight_strength=slope_stength*(1.0-aspect_strength);fragColor=u_shadows[0]*shadow_strength+u_highlights[0]*highlight_strength;}void standard_hillshade(vec2 deriv){float azimuth=u_azimuths[0]+PI;float slope=atan(0.625*length(deriv));float aspect=get_aspect(deriv);float intensity=u_exaggeration;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadows[0],u_highlights[0],shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;}void basic_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor=u_highlights[0]*(2.0*shade-1.0);}else\n{fragColor=u_shadows[0]*(1.0-2.0*shade);}}void multidirectional_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;fragColor=vec4(0,0,0,0);for(int i=0; i < NUM_ILLUMINATION_SOURCES; i++){float cos_alt=cos(u_altitudes[i]);float sin_alt=sin(u_altitudes[i]);float cos_az=-cos(u_azimuths[i]);float sin_az=-sin(u_azimuths[i]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor+=u_highlights[i]*(2.0*shade-1.0)/float(NUM_ILLUMINATION_SOURCES);}else\n{fragColor+=u_shadows[i]*(1.0-2.0*shade)/float(NUM_ILLUMINATION_SOURCES);}}}void combined_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=acos((sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv)));cang=clamp(cang,0.0,PI/2.0);float shade=cang*atan(length(deriv))*4.0/PI/PI;float highlight=(PI/2.0-cang)*atan(length(deriv))*4.0/PI/PI;fragColor=u_shadows[0]*shade+u_highlights[0]*highlight;}void main() {vec4 pixel=texture(u_image,v_pos);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));vec2 deriv=((pixel.rg*8.0)-4.0)/scaleFactor;if (u_method==BASIC) {basic_hillshade(deriv);} else if (u_method==COMBINED) {combined_hillshade(deriv);} else if (u_method==IGOR) {igor_hillshade(deriv);} else if (u_method==MULTIDIRECTIONAL) {multidirectional_hillshade(deriv);} else if (u_method==STANDARD) {standard_hillshade(deriv);} else {standard_hillshade(deriv);}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:yt("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:yt("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0);vec4 color1=texture(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:yt("uniform sampler2D u_texture;in vec2 v_tex;in float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;fragColor=texture(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_tex;out float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:yt("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:yt("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;fragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:yt("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}","in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:yt("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}","in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:yt("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:yt("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:yt("in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}","in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:yt("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function yt(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o=t.match(/in ([\w]+) ([\w]+)/g),r=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=a?a.concat(r):r,n={};return {fragmentSource:e=e.replace(i,((e,t,i,o,r)=>(n[r]=!0,"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nin ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = u_${r};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,o,r)=>{const a="float"===o?"vec2":"vec4",s=r.match(/color/)?"color":a;return n[r]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\nout ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`})),staticAttributes:o,staticUniforms:s}}class wt{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var Tt=t.aJ([{name:"a_pos",type:"Int16",components:2}]);const Pt="#define PROJECTION_MERCATOR",Ct="mercator";class It{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return !1}get shaderVariantName(){return Ct}get shaderDefine(){return Pt}get shaderPreludeCode(){return xt.projectionMercator}get vertexShaderPreludeCode(){return xt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.aK.noSubdivision}get useGlobeControls(){return !1}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(e){}getMeshFromTileID(e,i,o,r,a){if(this._cachedMesh)return this._cachedMesh;const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(t.$,0),s.emplaceBack(0,t.$),s.emplaceBack(t.$,t.$);const n=e.createVertexBuffer(s,Tt.members),l=t.aM.simpleSegment(0,0,4,2),c=new t.aN;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new wt(n,h,l),this._cachedMesh}recalculate(){}hasTransition(){return !1}setErrorQueryLatitudeDegrees(e){}}class Mt{constructor(e=0,t=0,i=0,o=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=o;}interpolate(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.C.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.C.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.C.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.C.number(e.right,i.right,o)),this}getCenter(e,i){const o=t.ah((this.left+e-this.right)/2,0,e),r=t.ah((this.top+i-this.bottom)/2,0,i);return new t.P(o,r)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new Mt(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function St(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function Et(e){return Math.max(0,Math.floor(e))}class Rt{constructor(e,i,o,r,a,s){this._callbacks=e,this._tileSize=512,this._renderWorldCopies=void 0===s||!!s,this._minZoom=i||0,this._maxZoom=o||22,this._minPitch=null==r?0:r,this._maxPitch=null==a?60:a,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.S(0,0),this._elevation=0,this._zoom=0,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new Mt,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=!0;}apply(e,i,o){this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new Mt(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,this._cameraToCenterDistance=e.cameraToCenterDistance,this._nearZ=e.nearZ,this._farZ=e.farZ,this._autoCalculateNearFarZ=!o&&e.autoCalculateNearFarZ,i&&this._constrain(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e;}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const i=t.aO(e,-180,180)*Math.PI/180;var r,a,s,n,l,c,h,u,d;this._bearingInRadians!==i&&(this._unmodified=!1,this._bearingInRadians=i,this._calcMatrices(),this._rotationMatrix=o(),r=this._rotationMatrix,s=-this._bearingInRadians,n=(a=this._rotationMatrix)[0],l=a[1],c=a[2],h=a[3],u=Math.sin(s),d=Math.cos(s),r[0]=n*d+c*u,r[1]=l*d+h*u,r[2]=n*-u+c*d,r[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.ah(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=!1,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=!1,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.aP(this._fovInRadians)}setFov(e){e=t.ah(e,.1,150),this.fov!==e&&(this._unmodified=!1,this._fovInRadians=t.ae(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const i=this.getConstrained(this._center,e).zoom;this._zoom!==i&&(this._unmodified=!1,this._zoom=i,this._tileZoom=Math.max(0,Math.floor(i)),this._scale=t.af(i),this._constrain(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(e,t){this._autoCalculateNearFarZ=!1,this._nearZ=e,this._farZ=t,this._calcMatrices();}clearNearFarZOverride(){this._autoCalculateNearFarZ=!0,this._calcMatrices();}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices();}resize(e,t,i=!0){this._width=e,this._height=t,i&&this._constrain(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new G([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-t.ai,t.ai]);}getConstrained(e,t){return this._callbacks.getConstrained(e,t)}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{const{minX:o,minY:r,maxX:a,maxY:s}=t.a2.fromPoints(i).extend(e);return [new t.P(o,r),new t.P(a,r),new t.P(a,s),new t.P(o,s),new t.P(o,r)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const e=this._unmodified,{center:t,zoom:i}=this.getConstrained(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=!1;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.ag(new Float64Array(16));t.N(e,e,[this._width/2,-this._height/2,1]),t.M(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.ag(new Float64Array(16)),t.N(e,e,[1,-1,1]),t.M(e,e,[-1,-1,0]),t.N(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height;}this._callbacks.calcMatrices();}calculateCenterFromCameraLngLatAlt(e,i,o,r){const a=void 0!==o?o:this.bearing,s=r=void 0!==r?r:this.pitch,n=t.a1.fromLngLat(e,i),l=-Math.cos(t.ae(s)),c=Math.sin(t.ae(s)),h=c*Math.sin(t.ae(a)),u=-c*Math.cos(t.ae(a));let d=this.elevation;const _=i-d;let p;l*_>=0||Math.abs(l)<.1?(p=1e4,d=i+p*l):p=-_/l;let m,f,g=t.aQ(1,n.y),v=0;do{if(v+=1,v>10)break;f=p/g,m=new t.a1(n.x+h*f,n.y+u*f),g=1/m.meterInMercatorCoordinateUnits();}while(Math.abs(p-f*g)>1e-12);return {center:m.toLngLat(),elevation:d,zoom:t.ak(this.height/2/Math.tan(this.fovInRadians/2)/f/this.tileSize)}}recalculateZoomAndCenter(e){if(this.elevation-e==0)return;const i=t.aj(1,this.center.lat)*this.worldSize,o=this.cameraToCenterDistance/i,r=t.a1.fromLngLat(this.center,this.elevation),a=de(this.center,this.elevation,this.pitch,this.bearing,o);this._elevation=e;const s=this.calculateCenterFromCameraLngLatAlt(a.toLngLat(),t.aQ(a.z,r.y),this.bearing,this.pitch);this._elevation=s.elevation,this._center=s.center,this.setZoom(s.zoom);}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.P(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/e).toLngLat()}getMercatorTileCoordinates(e){if(!e)return [0,0,1,1];const i=e.canonical.z>=0?1<this.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[o]*this.min[o],i+=e[o]*this.max[o]):(i+=e[o]*this.min[o],t+=e[o]*this.max[o]);return t>=0?2:i<0?0:1}}class Dt{distanceToTile2d(e,t,i,o){const r=o.distanceX([e,t]),a=o.distanceY([e,t]);return Math.hypot(r,a)}getWrap(e,t,i){return i}getTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}const c=1<r}allowWorldCopies(){return !0}prepareNextFrame(){}}class At{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,o=0,r,a){const s=a?[[6,5,4],[0,1,2],[0,3,7],[2,1,5],[3,2,6],[0,4,5]]:[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]],n=Math.pow(2,o),l=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((o=>function(e,i,o,r){const a=t.aw([],e,i),s=1/a[3]/o*r;return t.aY(a,a,[s,s,1/a[3],s])}(o,e,i,n)));r&&function(e,i,o,r){const a=r?4:0,s=r?0:4;let n=0;const l=[],c=[];for(let i=0;i<4;i++){const o=t.aU([],e[i+s],e[i+a]),r=t.aZ(o);t.aR(o,o,1/r),l.push(r),c.push(o);}for(let i=0;i<4;i++){const r=t.a_(e[i+a],c[i],o);n=null!==r&&r>=0?Math.max(n,r):Math.max(n,l[i]);}const h=function(e,i){const o=t.aU([],e[i[0]],e[i[1]]),r=t.aU([],e[i[2]],e[i[1]]),a=[0,0,0,0];return t.aV(a,t.aW([],o,r)),a[3]=-t.aX(a,e[i[0]]),a}(e,i),u=function(e,i){const o=t.a$(e),r=t.b0([],e,1/o),a=t.aU([],i,t.aR([],r,t.aX(i,r))),s=t.a$(a);if(s>0){const e=Math.sqrt(1-r[3]*r[3]),o=t.aR([],r,-r[3]),n=t.aS([],o,t.aR([],a,e/s));return t.b1(i,n)}return null}(o,h);if(null!==u){const e=u/t.aX(c[0],h);n=Math.min(n,e);}for(let t=0;t<4;t++){const i=Math.min(n,l[t]);e[t+s]=[e[t+a][0]+c[t][0]*i,e[t+a][1]+c[t][1]*i,e[t+a][2]+c[t][2]*i,1];}}(l,s[0],r,a);const c=s.map((e=>{const i=t.aU([],l[e[0]],l[e[1]]),o=t.aU([],l[e[2]],l[e[1]]),r=t.aV([],t.aW([],i,o)),a=-t.aX(r,l[e[1]]);return r.concat(a)})),h=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of l)for(let t=0;t<3;t++)h[t]=Math.min(h[t],e[t]),u[t]=Math.max(u[t],e[t]);return new At(l,c,new zt(h,u))}}class Lt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e,t){}constructor(e,t,i,o,r){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)},e,t,i,o,r),this._coveringTilesDetailsProvider=new Dt;}clone(){const e=new Lt;return e.apply(this),e}apply(e,t,i){this._helper.apply(e,t,i);}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.b2(0,e)];if(this._helper._renderWorldCopies){const o=this.screenPointToMercatorCoordinate(new t.P(0,0)),r=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,0)),a=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,this._helper._height)),s=this.screenPointToMercatorCoordinate(new t.P(0,this._helper._height)),n=Math.floor(Math.min(o.x,r.x,a.x,s.x)),l=Math.floor(Math.max(o.x,r.x,a.x,s.x)),c=1;for(let o=n-c;o<=l+c;o++)0!==o&&i.push(new t.b2(o,e));}return i}getCameraFrustum(){return At.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const t=this.screenPointToLocation(this.centerPoint,e),i=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(i);}setLocationAtPoint(e,i){const o=t.aj(this.elevation,this.center.lat),r=this.screenPointToMercatorCoordinateAtZ(i,o),a=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,o),s=t.a1.fromLngLat(e),n=new t.a1(s.x-(r.x-a.x),s.y-(r.y-a.y));this.setCenter(null==n?void 0:n.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,i){return i?this.coordinatePoint(t.a1.fromLngLat(e),i.getElevationForLngLatZoom(e,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(t.a1.fromLngLat(e))}screenPointToLocation(e,t){var i;return null===(i=this.screenPointToMercatorCoordinate(e,t))||void 0===i?void 0:i.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const o=i||0,r=[e.x,e.y,0,1],a=[e.x,e.y,1,1];t.aw(r,r,this._pixelMatrixInverse),t.aw(a,a,this._pixelMatrixInverse);const s=r[3],n=a[3],l=r[1]/s,c=a[1]/n,h=r[2]/s,u=a[2]/n,d=h===u?0:(o-h)/(u-h);return new t.a1(t.C.number(r[0]/s,a[0]/n,d)/this.worldSize,t.C.number(l,c,d)/this.worldSize,o)}coordinatePoint(e,i=0,o=this._pixelMatrix){const r=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.aw(r,r,o),new t.P(r[0]/r[3],r[1]/r[3])}getBounds(){const e=Math.max(0,this._helper._height/2-he(this));return (new G).extend(this.screenPointToLocation(new t.P(0,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.P(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-he(this)}calculatePosMatrix(e,i=!1,o){var r;const a=null!==(r=e.key)&&void 0!==r?r:t.b3(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),s=i?this._alignedPosMatrixCache:this._posMatrixCache;if(s.has(a)){const e=s.get(a);return o?e.f32:e.f64}const n=ue(e,this.worldSize);t.O(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return s.set(a,l),o?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,o=this._fogMatrixCacheF32;if(o.has(i))return o.get(i);const r=ue(e,this.worldSize);return t.O(r,this._fogMatrix,r),o.set(i,new Float32Array(r)),o.get(i)}getConstrained(e,i){i=t.ah(+i,this.minZoom,this.maxZoom);const o={center:new t.S(e.lng,e.lat),zoom:i};let r=this._helper._lngRange;if(!this._helper._renderWorldCopies&&null===r){const e=180-1e-10;r=[-e,e];}const a=this.tileSize*t.af(o.zoom);let s=0,n=a,l=0,c=a,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;s=t.U(e[1])*a,n=t.U(e[0])*a,n-s<_&&(h=_/(n-s));}r&&(l=t.aO(t.V(r[0])*a,0,a),c=t.aO(t.V(r[1])*a,0,a),cn&&(g=n-e);}if(r){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.aO(p,e-a/2,e+a/2));const o=d/2;i-oc&&(f=c-o);}if(void 0!==f||void 0!==g){const e=new t.P(null!=f?f:p,null!=g?g:m);o.center=ce(a,e).wrap();}return o}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}_calculateNearFarZIfNeeded(e,i,o){if(!this._helper.autoCalculateNearFarZ)return;const r=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),a=e-r*this._helper._pixelPerMeter/Math.cos(i),s=r<0?a:e,n=Math.PI/2+this.pitchInRadians,l=t.ae(this.fov)*(Math.abs(Math.cos(t.ae(this.roll)))*this.height+Math.abs(Math.sin(t.ae(this.roll)))*this.width)/this.height*(.5+o.y/this.height),c=Math.sin(l)*s/Math.sin(t.ah(Math.PI-n-l,.01,Math.PI-.01)),h=he(this),u=Math.atan(h/this._helper.cameraToCenterDistance),d=t.ae(.75),_=u>d?2*u*(.5+o.y/(2*h)):d,p=Math.sin(_)*s/Math.sin(t.ah(Math.PI-n-_,.01,Math.PI-.01)),m=Math.min(c,p);this._helper._farZ=1.01*(Math.cos(Math.PI/2-i)*m+s),this._helper._nearZ=this._helper._height/50;}_calcMatrices(){if(!this._helper._height)return;const e=this.centerOffset,i=le(this.worldSize,this.center),o=i.x,r=i.y;this._helper._pixelPerMeter=t.aj(1,this.center.lat)*this.worldSize;const a=t.ae(Math.min(this.pitch,ne)),s=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(a));let n;this._calculateNearFarZIfNeeded(s,a,e),n=new Float64Array(16),t.b4(n,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),t.aq(this._invProjMatrix,n),n[8]=2*-e.x/this._helper._width,n[9]=2*e.y/this._helper._height,this._projectionMatrix=t.b5(n),t.N(n,n,[1,-1,1]),t.M(n,n,[0,0,-this._helper.cameraToCenterDistance]),t.b6(n,n,-this.rollInRadians),t.b7(n,n,this.pitchInRadians),t.b6(n,n,-this.bearingInRadians),t.M(n,n,[-o,-r,0]),this._mercatorMatrix=t.N([],n,[this.worldSize,this.worldSize,this.worldSize]),t.N(n,n,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n),t.M(n,n,[0,0,-this.elevation]),this._viewProjMatrix=n,this._invViewProjMatrix=t.aq([],n);const l=[0,0,-1,1];t.aw(l,l,this._invViewProjMatrix),this._cameraPosition=[l[0]/l[3],l[1]/l[3],l[2]/l[3]],this._fogMatrix=new Float64Array(16),t.b4(this._fogMatrix,this.fovInRadians,this.width/this.height,s,this._helper._farZ),this._fogMatrix[8]=2*-e.x/this.width,this._fogMatrix[9]=2*e.y/this.height,t.N(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.b6(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.b7(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.b6(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.M(this._fogMatrix,this._fogMatrix,[-o,-r,0]),t.N(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n);const c=this._helper._width%2/2,h=this._helper._height%2/2,u=Math.cos(this.bearingInRadians),d=Math.sin(-this.bearingInRadians),_=o-Math.round(o)+u*c+d*h,p=r-Math.round(r)+u*h+d*c,m=new Float64Array(n);if(t.M(m,m,[_>.5?_-1:_,p>.5?p-1:p,0]),this._alignedProjMatrix=m,n=t.aq(new Float64Array(16),this._pixelMatrix),!n)throw new Error("failed to invert matrix");this._pixelMatrixInverse=n,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.P(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.aw(i,i,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/e).toLngLat()}lngLatToCameraDepth(e,i){const o=t.a1.fromLngLat(e),r=[o.x*this.worldSize,o.y*this.worldSize,i,1];return t.aw(r,r,this._viewProjMatrix),r[2]/r[3]}getProjectionData(e){const{overscaledTileID:i,aligned:o,applyTerrainMatrix:r}=e,a=this._helper.getMercatorTileCoordinates(i),s=i?this.calculatePosMatrix(i,o,!0):null;let n;return n=i&&i.terrainRttPosMatrix32f&&r?i.terrainRttPosMatrix32f:s||t.b8(),{mainMatrix:n,tileMercatorCoords:a,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:n}}isLocationOccluded(e){return !1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,i){return 1}transformLightDirection(e){return t.aT(e)}getRayDirectionFromPixel(e){throw new Error("Not implemented.")}projectTileCoordinates(e,i,o,r){const a=this.calculatePosMatrix(o);let s;r?(s=[e,i,r(e,i),1],t.aw(s,s,a)):(s=[e,i,0,1],qe(s,s,a));const n=s[3];return {point:new t.P(s[0]/n,s[1]/n),signedDistanceFromCamera:n,isOccluded:!1}}populateCache(e){for(const t of e)this.calculatePosMatrix(t);}getMatrixForModel(e,i){const o=t.a1.fromLngLat(e,i),r=o.meterInMercatorCoordinateUnits(),a=t.b9();return t.M(a,a,[o.x,o.y,o.z]),t.b6(a,a,Math.PI),t.b7(a,a,Math.PI/2),t.N(a,a,[-r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=new t.Z(0,0,0,0,0),o=this.getProjectionData({overscaledTileID:i,applyGlobeMatrix:e}),r=ue(i,this.worldSize);t.O(r,this._viewProjMatrix,r),o.tileMercatorCoords=[0,0,1,1];const a=[t.$,t.$,this.worldSize/this._helper.pixelsPerMeter],s=t.ba();return t.N(s,r,a),o.fallbackMatrix=s,o.mainMatrix=s,o}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}}function kt(){t.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");}function Ft(e){if(e.useSlerp)if(e.k<1){const i=t.bb(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),o=t.bb(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),r=new Float64Array(4);t.bc(r,i,o,e.k);const a=t.bd(r);e.tr.setRoll(a.roll),e.tr.setPitch(a.pitch),e.tr.setBearing(a.bearing);}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(t.C.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(t.C.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(t.C.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k));}function Bt(e,i,o,r,a){const s=a.padding,n=le(a.worldSize,o.getNorthWest()),l=le(a.worldSize,o.getNorthEast()),c=le(a.worldSize,o.getSouthEast()),h=le(a.worldSize,o.getSouthWest()),u=t.ae(-r),d=n.rotate(u),_=l.rotate(u),p=c.rotate(u),m=h.rotate(u),f=new t.P(Math.max(d.x,_.x,m.x,p.x),Math.max(d.y,_.y,m.y,p.y)),g=new t.P(Math.min(d.x,_.x,m.x,p.x),Math.min(d.y,_.y,m.y,p.y)),v=f.sub(g),b=(a.width-(s.left+s.right+i.left+i.right))/v.x,x=(a.height-(s.top+s.bottom+i.top+i.bottom))/v.y;if(x<0||b<0)return void kt();const y=Math.min(t.ak(a.scale*Math.min(b,x)),e.maxZoom),w=t.P.convert(e.offset),T=new t.P((i.left-i.right)/2,(i.top-i.bottom)/2).rotate(t.ae(r)),P=w.add(T).mult(a.scale/t.af(y));return {center:ce(a.worldSize,n.add(c).div(2).sub(P)),zoom:y,bearing:r}}class Ot{get useGlobeControls(){return !1}handlePanInertia(e,t){const i=e.mag(),o=Math.abs(he(t));return {easingOffset:e.mult(Math.min(.75*o/i,1)),easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta);}handleMapControlsPan(e,t,i){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(i,e.around);}cameraForBoxAndBearing(e,t,i,o,r){return Bt(e,t,i,o,r)}handleJumpToCenterZoom(e,i){e.zoom!==(void 0!==i.zoom?+i.zoom:e.zoom)&&e.setZoom(+i.zoom),void 0!==i.center&&e.setCenter(t.S.convert(i.center));}handleEaseTo(e,i){const o=e.zoom,r=e.padding,a={roll:e.roll,pitch:e.pitch,bearing:e.bearing},s={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},n=void 0!==i.zoom,l=!e.isPaddingEqual(i.padding);let c=!1;const h=n?+i.zoom:e.zoom;let u=e.centerPoint.add(i.offsetAsPoint);const d=e.screenPointToLocation(u),{center:_,zoom:p}=e.getConstrained(t.S.convert(i.center||d),null!=h?h:o);St(e,_);const m=le(e.worldSize,d),f=le(e.worldSize,_).sub(m),g=t.af(p-o);return c=p!==o,{easeFunc:n=>{if(c&&e.setZoom(t.C.number(o,p,n)),t.be(a,s)||Ft({startEulerAngles:a,endEulerAngles:s,tr:e,k:n,useSlerp:a.roll!=s.roll}),l&&(e.interpolatePadding(r,i.padding,n),u=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const i=t.af(e.zoom-o),r=p>o?Math.min(2,g):Math.max(.5,g),a=Math.pow(r,1-n),s=ce(e.worldSize,m.add(f.mult(n*a)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?s.wrap():s,u);}},isZooming:c,elevationCenter:_}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.zoom,a=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),o?+i.zoom:r),s=a.center,n=a.zoom;St(e,s);const l=le(e.worldSize,i.locationAtOffset),c=le(e.worldSize,s).sub(l),h=c.mag(),u=t.af(n-r);let d;if(void 0!==i.minZoom){const o=Math.min(+i.minZoom,r,n),a=e.getConstrained(s,o).zoom;d=t.af(a-r);}return {easeFunc:(i,o,a,h)=>{e.setZoom(1===i?n:r+t.ak(o));const u=1===i?s:ce(e.worldSize,l.add(c.mult(a)).mult(o));e.setLocationAtPoint(e.renderWorldCopies?u.wrap():u,h);},scaleOfZoom:u,targetCenter:s,scaleOfMinZoom:d,pixelPathLength:h}}}class jt{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}jt.Replace=[1,0],jt.disabled=new jt(jt.Replace,t.bf.transparent,[!1,!1,!1,!1]),jt.unblended=new jt(jt.Replace,t.bf.transparent,[!0,!0,!0,!0]),jt.alphaBlended=new jt([1,771],t.bf.transparent,[!0,!0,!0,!0]);const Nt=2305;class Ut{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}Ut.disabled=new Ut(!1,1029,Nt),Ut.backCCW=new Ut(!0,1029,Nt),Ut.frontCCW=new Ut(!0,1028,Nt);class Zt{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Zt.ReadOnly=!1,Zt.ReadWrite=!0,Zt.disabled=new Zt(519,Zt.ReadOnly,[0,1]);const Gt=7680;class Vt{constructor(e,t,i,o,r,a){this.test=e,this.ref=t,this.mask=i,this.fail=o,this.depthFail=r,this.pass=a;}}Vt.disabled=new Vt({func:519,mask:0},0,0,Gt,Gt,Gt);const $t=new WeakMap;function qt(e){var t;if($t.has(e))return $t.get(e);{const i=null===(t=e.getParameter(e.VERSION))||void 0===t?void 0:t.startsWith("WebGL 2.0");return $t.set(e,i),i}}class Wt{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,o=i.gl;this._texFormat=o.RGBA,this._texType=o.UNSIGNED_BYTE;const r=new t.aL;r.emplaceBack(-1,-1),r.emplaceBack(2,-1),r.emplaceBack(-1,2);const a=new t.aN;a.emplaceBack(0,1,2),this._fullscreenTriangle=new wt(i.createVertexBuffer(r,Tt.members),i.createIndexBuffer(a),t.aM.simpleSegment(0,0,r.length,a.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(o.TEXTURE1);const s=o.createTexture();o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texImage2D(o.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(s),qt(o)&&(this._pbo=o.createBuffer(),o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.bufferData(o.PIXEL_PACK_BUFFER,4,o.STREAM_READ),o.bindBuffer(o.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const o=this._cachedRenderContext.context,r=o.gl;if(this._bindFramebuffer(),o.viewport.set([0,0,this._texWidth,this._texHeight]),o.clear({color:t.bf.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(o,r.TRIANGLES,Zt.disabled,Vt.disabled,jt.unblended,Ut.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&qt(r)){r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.readBuffer(r.COLOR_ATTACHMENT0),r.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),r.bindBuffer(r.PIXEL_PACK_BUFFER,null);const e=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);r.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&qt(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=Wt._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const Ht=t.$/128;function Xt(e,i){const o=void 0!==e.granularity?Math.max(e.granularity,1):1,r=o+(e.generateBorders?2:0),a=o+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),s=r+1,n=a+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=o+(e.generateBorders?1:0),u=o+(e.generateBorders||e.extendToSouthPole?1:0),d=s*n,_=r*a*6,p=s*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g=0;for(let i=c;i<=u;i++)for(let r=l;r<=h;r++){let a=r/o*t.$;-1===r&&(a=-Ht),r===o+1&&(a=t.$+Ht);let s=i/o*t.$;-1===i&&(s=e.extendToNorthPole?t.bh:-Ht),i===o+1&&(s=e.extendToSouthPole?t.bi:t.$+Ht),f[g++]=a,f[g++]=s;}const v=m?new Uint32Array(_):new Uint16Array(_);let b=0;for(let e=0;e0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return "globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy();}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e);}getMeshFromTileID(e,t,i,o,r){return this.currentProjection.getMeshFromTileID(e,t,i,o,r)}setProjection(e){this._transitionable.setValue("type",(null==e?void 0:e.type)||"mercator");}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e);}}function ei(e){const t=oi(e.worldSize,e.center.lat);return 2*Math.PI*t}function ti(e,i,o,r,a){const s=1/(1<1e-6){const r=e[0]/o,a=Math.acos(e[2]/o),s=(r>0?a:-a)/Math.PI*180;return new t.S(t.aO(s,-180,180),i)}return new t.S(0,i)}function ai(e){return Math.cos(e*Math.PI/180)}function si(e,i){const o=ai(e),r=ai(i);return t.ak(r/o)}function ni(e,i){const o=e.rotate(i.bearingInRadians),r=i.zoom+si(i.center.lat,0),a=t.bk(1/ai(i.center.lat),1/ai(Math.min(Math.abs(i.center.lat),60)),t.bn(r,7,3,0,1)),s=360/ei({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.S(i.center.lng-o.x*s*a,t.ah(i.center.lat+o.y*s,-t.ai,t.ai))}function li(e){const t=.5*e,i=Math.sin(t),o=Math.cos(t);return Math.log(i+o)-Math.log(o-i)}function ci(e,i,o,r){const a=e.lat+o*r;if(Math.abs(o)>1){const s=(Math.sign(e.lat+o)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+o)*Math.PI/180,l=li(s+r*(n-s)),c=li(s),h=li(n);return new t.S(e.lng+i*((l-c)/(h-c)),a)}return new t.S(e.lng+i*r,a)}class hi{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._boundingVolumeFactory=e;}swapBuffers(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1;}getTileBoundingVolume(e,t,i,o){const r=`${e.z}_${e.x}_${e.y}_${(null==o?void 0:o.terrain)?"t":""}`,a=this._cache.get(r);if(a)return a;const s=this._cachePrevious.get(r);if(s)return this._cache.set(r,s),s;const n=this._boundingVolumeFactory(e,t,i,o);return this._cache.set(r,n),this._hadAnyChanges=!0,n}}class ui{constructor(e,t,i,o){this.min=i,this.max=o,this.points=e,this.planes=t;}static fromAabb(e,t){const i=[];for(let o=0;o<8;o++)i.push([1&~o?e[0]:t[0],1==(o>>1&1)?t[1]:e[1],1==(o>>2&1)?t[2]:e[2]]);return new ui(i,[[-1,0,0,t[0]],[1,0,0,-e[0]],[0,-1,0,t[1]],[0,1,0,-e[1]],[0,0,-1,t[2]],[0,0,1,-e[2]]],e,t)}static fromCenterSizeAngles(e,i,o){const r=t.br([],o[0],o[1],o[2]),a=t.bs([],[i[0],0,0],r),s=t.bs([],[0,i[1],0],r),n=t.bs([],[0,0,i[2]],r),l=[...e],c=[...e];for(let t=0;t<8;t++)for(let i=0;i<3;i++){const o=e[i]+a[i]*(1&~t?-1:1)+s[i]*(1==(t>>1&1)?1:-1)+n[i]*(1==(t>>2&1)?1:-1);l[i]=Math.min(l[i],o),c[i]=Math.max(c[i],o);}const h=[];for(let i=0;i<8;i++){const o=[...e];t.aS(o,o,t.aR([],a,1&~i?-1:1)),t.aS(o,o,t.aR([],s,1==(i>>1&1)?1:-1)),t.aS(o,o,t.aR([],n,1==(i>>2&1)?1:-1)),h.push(o);}return new ui(h,[[...a,-t.aX(a,h[0])],[...s,-t.aX(s,h[0])],[...n,-t.aX(n,h[0])],[-a[0],-a[1],-a[2],-t.aX(a,h[7])],[-s[0],-s[1],-s[2],-t.aX(s,h[7])],[-n[0],-n[1],-n[2],-t.aX(n,h[7])]],l,c)}intersectsFrustum(e){let t=!0;const i=this.points.length,o=this.planes.length,r=e.planes.length,a=e.points.length;for(let o=0;o=0&&a++;}if(0===a)return 0;a=0&&o++;}if(0===o)return 0}return 1}intersectsPlane(e){const t=this.points.length;let i=0;for(let o=0;o=0&&i++;}return i===t?2:0===i?0:1}}function di(e,t,i){const o=e-t;return o<0?-o:Math.max(0,o-i)}function _i(e,t,i,o,r){const a=e-i;let s;return s=a<0?Math.min(-a,1+a-r):a>1?Math.min(Math.max(a-r,0),1-a):0,Math.max(s,di(t,o,r))}class pi{constructor(){this._boundingVolumeCache=new hi(this._computeTileBoundingVolume);}prepareNextFrame(){this._boundingVolumeCache.swapBuffers();}distanceToTile2d(e,t,i,o){const r=1<4}allowWorldCopies(){return !1}getTileBoundingVolume(e,t,i,o){return this._boundingVolumeCache.getTileBoundingVolume(e,t,i,o)}_computeTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}if(n/=t.bu,l/=t.bu,n+=1,l+=1,e.z<=0)return ui.fromAabb([-l,-l,-l],[l,l,l]);if(1===e.z)return ui.fromAabb([0===e.x?-l:0,0===e.y?0:-l,-l],[0===e.x?0:l,0===e.y?l:0,l]);{const i=[ti(0,0,e.x,e.y,e.z),ti(t.$,0,e.x,e.y,e.z),ti(t.$,t.$,e.x,e.y,e.z),ti(0,t.$,e.x,e.y,e.z)],o=[];for(const e of i)o.push(t.aR([],e,l));if(l!==n)for(const e of i)o.push(t.aR([],e,n));0===e.y&&o.push([0,1,0]),e.y===(1<=(1<{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._coveringTilesDetailsProvider=new pi;}clone(){const e=new fi;return e.apply(this),e}apply(e,t){this._globeLatitudeErrorCorrectionRadians=t||0,this._helper.apply(e);}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const e=t.bp();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(e){const{overscaledTileID:t,applyGlobeMatrix:i}=e,o=this._helper.getMercatorTileCoordinates(t);return {mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:o,clippingPlane:this._cachedClippingPlane,projectionTransition:i?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(e){const i=this.pitchInRadians,o=this.cameraToCenterDistance/e,r=Math.sin(i)*o,a=Math.cos(i)*o+1,s=1/Math.sqrt(r*r+a*a)*1;let n=-r,l=a;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];t.bw(h,h,[0,0,0],-this.bearingInRadians),t.bx(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.by(h,h,[0,0,0],this.center.lng*Math.PI/180);const u=1/t.aZ(h);return t.aR(h,h,u),[...h,-s*u]}isLocationOccluded(e){return !this.isSurfacePointVisible(ii(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,o=this._helper._center.lat*Math.PI/180,r=Math.cos(o),a=[Math.sin(i)*r,Math.sin(o),Math.cos(i)*r],s=[a[2],0,-a[0]],n=[0,0,0];t.aW(n,s,a),t.aV(s,s),t.aV(n,n);const l=[0,0,0];return t.aV(l,[s[0]*e[0]+n[0]*e[1]+a[0]*e[2],s[1]*e[0]+n[1]*e[1]+a[1]*e[2],s[2]*e[0]+n[2]*e[1]+a[2]*e[2]]),l}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(e,i,o){const r=function(e,i,o){const r=1/(1<a&&(a=i),on&&(n=o);}const h=[c.lng+s,c.lat+l,c.lng+a,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new G(h)}getConstrained(e,i){const o=t.ah(e.lat,-t.ai,t.ai),r=t.ah(+i,this.minZoom+si(0,o),this.maxZoom);return {center:new t.S(e.lng,o),zoom:r}}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,i){const o=ii(this.unprojectScreenPoint(i)),r=ii(e),a=t.bp();t.bB(a);const s=t.bp();t.by(s,o,a,-this.center.lng*Math.PI/180),t.bx(s,s,a,this.center.lat*Math.PI/180);const n=r[0]*r[0]+r[2]*r[2],l=s[0]*s[0];if(n=-g&&p<=g,b=f>=-g&&f<=g;let x,y;if(v&&b){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.bD(u,e)+t.bD(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return !1;const i=t.bv();return t.aw(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const o=t.aX(e,i),r=t.bp(),a=t.bp();t.aR(a,i,o),t.aU(r,e,a);const s=1-t.aX(r,r);if(s<0)return null;const n=t.aX(e,e)-1,l=-o+(o<0?1:-1)*Math.sqrt(s),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,o=this.getRayDirectionFromPixel(e),r=this.rayPlanetIntersection(i,o);if(r){const e=t.bp();t.aS(e,i,[o[0]*r.tMin,o[1]*r.tMin,o[2]*r.tMin]);const a=t.bp();return t.aV(a,e),ri(a)}const a=this._cachedClippingPlane,s=a[0]*o[0]+a[1]*o[1]+a[2]*o[2],n=-t.b1(a,i)/s,l=t.bp();if(n>0)t.aS(l,i,[o[0]*n,o[1]*n,o[2]*n]);else {const e=t.bp();t.aS(e,i,[2*o[0],2*o[1],2*o[2]]);const r=t.b1(this._cachedClippingPlane,e);t.aU(l,e,[this._cachedClippingPlane[0]*r,this._cachedClippingPlane[1]*r,this._cachedClippingPlane[2]*r]);}const c=function(e){const i=t.bp();return i[0]=e[0]*-e[3],i[1]=e[1]*-e[3],i[2]=e[2]*-e[3],{center:i,radius:Math.sqrt(1-e[3]*e[3])}}(a);return ri(function(e,i,o){const r=t.bp();t.aU(r,o,e);const a=t.bp();return t.bq(a,e,r,i/t.a$(r)),a}(c.center,c.radius,l))}getMatrixForModel(e,i){const o=t.S.convert(e),r=1/t.bu,a=t.b9();return t.bz(a,a,o.lng/180*Math.PI),t.b7(a,a,-o.lat/180*Math.PI),t.M(a,a,[0,0,1+i/t.bu]),t.b7(a,a,.5*Math.PI),t.N(a,a,[r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=this.getProjectionData({overscaledTileID:new t.Z(0,0,0,0,0),applyGlobeMatrix:e});return i.tileMercatorCoords=[0,0,1,1],i}getFastPathSimpleProjectionMatrix(e){}}class gi{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame(),this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame();}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._globeness=1,this._mercatorTransform=new Lt,this._verticalPerspectiveTransform=new fi;}clone(){const e=new gi;return e._globeness=this._globeness,e._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,e.apply(this),e}apply(e){this._helper.apply(e),this._mercatorTransform.apply(this),this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians);}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){const t=this._mercatorTransform.getProjectionData(e),i=this._verticalPerspectiveTransform.getProjectionData(e);return {mainMatrix:this.isGlobeRendering?i.mainMatrix:t.mainMatrix,clippingPlane:i.clippingPlane,tileMercatorCoords:i.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return t.bk(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return t.bk(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,i,o){const r=this._mercatorTransform.getPitchedTextCorrection(e,i,o),a=this._verticalPerspectiveTransform.getPitchedTextCorrection(e,i,o);return t.bk(r,a,this._globeness)}projectTileCoordinates(e,t,i,o){return this.currentTransform.projectTileCoordinates(e,t,i,o)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ);}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this._mercatorTransform.recalculateZoomAndCenter(e),this._verticalPerspectiveTransform.recalculateZoomAndCenter(e);}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e);}getBounds(){return this.currentTransform.getBounds()}getConstrained(e,t){return this.currentTransform.getConstrained(e,t)}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,t){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,t),void this.apply(this._mercatorTransform);this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform);}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getMatrixForModel(e,t){return this.currentTransform.getMatrixForModel(e,t)}getProjectionDataForCustomLayer(e=!0){const t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;const i=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return i.fallbackMatrix=t.mainMatrix,i}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}}class vi{get useGlobeControls(){return !0}handlePanInertia(e,i){const o=ni(e,i);return Math.abs(o.lng-i.center.lng)>180&&(o.lng=i.center.lng+179.5*Math.sign(o.lng-i.center.lng)),{easingCenter:o,easingOffset:new t.P(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){const o=e.around,r=i.screenPointToLocation(o);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const a=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const s=i.zoom-a;if(0===s)return;const n=t.bA(i.center.lng,r.lng),l=n/(Math.abs(n/180)+1),c=t.bA(i.center.lat,r.lat),h=i.getRayDirectionFromPixel(o),u=i.cameraPosition,d=-1*t.aX(u,h),_=t.bp();t.aS(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.aZ(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=oi(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.bn(f,.9,.5,1,.25),v=(1-t.af(-s))*Math.min(m,g),b=i.center.lat,x=i.zoom,y=new t.S(i.center.lng+l*v,t.ah(i.center.lat+c*v,-t.ai,t.ai));i.setLocationAtPoint(r,o);const w=i.center,T=t.bn(Math.abs(n),45,85,0,1),P=t.bn(f,.75,.35,0,1),C=Math.pow(Math.max(T,P),.25),I=t.bA(w.lng,y.lng),M=t.bA(w.lat,y.lat);i.setCenter(new t.S(w.lng+I*C,w.lat+M*C).wrap()),i.setZoom(x+si(b,i.center.lat));}handleMapControlsPan(e,t,i){if(!e.panDelta)return;const o=t.center.lat,r=t.zoom;t.setCenter(ni(e.panDelta,t).wrap()),t.setZoom(r+si(o,t.center.lat));}cameraForBoxAndBearing(e,i,o,r,a){const s=Bt(e,i,o,r,a),n=i.left/a.width*2-1,l=(a.width-i.right)/a.width*2-1,c=i.top/a.height*-2+1,h=(a.height-i.bottom)/a.height*-2+1,u=t.bA(o.getWest(),o.getEast())<0,d=u?o.getEast():o.getWest(),_=u?o.getWest():o.getEast(),p=Math.max(o.getNorth(),o.getSouth()),m=Math.min(o.getNorth(),o.getSouth()),f=d+.5*t.bA(d,_),g=p+.5*t.bA(p,m),v=a.clone();v.setCenter(s.center),v.setBearing(s.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(s.zoom);const b=v.modelViewProjectionMatrix,x=[ii(o.getNorthWest()),ii(o.getNorthEast()),ii(o.getSouthWest()),ii(o.getSouthEast()),ii(new t.S(_,g)),ii(new t.S(d,g)),ii(new t.S(f,p)),ii(new t.S(f,m))],y=ii(s.center);let w=Number.POSITIVE_INFINITY;for(const e of x)n<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",n))),l>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",l))),c>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",c))),h<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",h)));if(Number.isFinite(w)&&0!==w)return s.zoom=v.zoom+t.ak(w),s;kt();}handleJumpToCenterZoom(e,i){const o=e.center.lat,r=e.getConstrained(i.center?t.S.convert(i.center):e.center,e.zoom).center;e.setCenter(r.wrap());const a=void 0!==i.zoom?+i.zoom:e.zoom+si(o,r.lat);e.zoom!==a&&e.setZoom(a);}handleEaseTo(e,i){const o=e.zoom,r=e.center,a=e.padding,s={roll:e.roll,pitch:e.pitch,bearing:e.bearing},n={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},l=void 0!==i.zoom,c=!e.isPaddingEqual(i.padding);let h=!1;const u=i.center?t.S.convert(i.center):r,d=e.getConstrained(u,o).center;St(e,d);const _=e.clone();_.setCenter(d),_.setZoom(l?+i.zoom:o+si(r.lat,u.lat)),_.setBearing(i.bearing);const p=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));_.setLocationAtPoint(d,p);const m=(i.offset&&i.offsetAsPoint.mag())>0?_.center:d,f=l?+i.zoom:o+si(r.lat,m.lat),g=o+si(r.lat,0),v=f+si(m.lat,0),b=t.bA(r.lng,m.lng),x=t.bA(r.lat,m.lat),y=t.af(v-g);return h=f!==o,{easeFunc:o=>{if(t.be(s,n)||Ft({startEulerAngles:s,endEulerAngles:n,tr:e,k:o,useSlerp:s.roll!=n.roll}),c&&e.interpolatePadding(a,i.padding,o),i.around)t.w("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=v>g?Math.min(2,y):Math.max(.5,y),i=Math.pow(t,1-o),a=ci(r,b,x,o*i);e.setCenter(a.wrap());}if(h){const i=t.C.number(g,v,o)+si(0,e.center.lat);e.setZoom(i);}},isZooming:h,elevationCenter:m}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.center,a=e.zoom,s=e.padding,n=!e.isPaddingEqual(i.padding),l=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),a).center,c=o?+i.zoom:e.zoom+si(e.center.lat,l.lat),h=e.clone();h.setCenter(l),h.setZoom(c),h.setBearing(i.bearing);const u=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));h.setLocationAtPoint(l,u);const d=h.center;St(e,d);const _=function(e,i,o){const r=ii(i),a=ii(o),s=t.aX(r,a),n=Math.acos(s),l=ei(e);return n/(2*Math.PI)*l}(e,r,d),p=a+si(r.lat,0),m=c+si(d.lat,0),f=t.af(m-p);let g;if("number"==typeof i.minZoom){const o=+i.minZoom+si(d.lat,0),r=Math.min(o,p,m)+si(0,d.lat),a=e.getConstrained(d,r).zoom+si(d.lat,0);g=t.af(a-p);}const v=t.bA(r.lng,d.lng),b=t.bA(r.lat,d.lat);return {easeFunc:(o,a,l,h)=>{const u=ci(r,v,b,l);n&&e.interpolatePadding(s,i.padding,o);const _=1===o?d:u;e.setCenter(_.wrap());const m=p+t.ak(a);e.setZoom(1===o?c:m+si(0,_.lat));},scaleOfZoom:f,targetCenter:d,scaleOfMinZoom:g,pixelPathLength:_}}static solveVectorScale(e,t,i,o,r){const a="x"===o?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],s=[i[3],i[7],i[11],i[15]],n=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],l=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],c=t[0]*a[0]+t[1]*a[1]+t[2]*a[2],h=t[0]*s[0]+t[1]*s[1]+t[2]*s[2];return c+r*l===n+r*h||s[3]*(n-c)+a[3]*(h-l)+n*h==c*l?null:(c+a[3]-r*h-r*s[3])/(c-n-r*h+r*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.y(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),yi=t.bE();class wi extends t.E{constructor(e,i={}){var o,r;super(),this._rtlPluginLoaded=()=>{for(const e in this.sourceCaches){const t=this.sourceCaches[e].getSource().type;"vector"!==t&&"geojson"!==t||this.sourceCaches[e].reload();}},this.map=e,this.dispatcher=new F(k(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.imageManager=new b,this.imageManager.setEventedParent(this);const a=(null===(o=e._container)||void 0===o?void 0:o.lang)||"undefined"!=typeof document&&(null===(r=document.documentElement)||void 0===r?void 0:r.lang)||void 0;this.glyphManager=new T(e._requestManager,i.localIdeographFontFamily,a),this.lineAtlas=new E(256,512),this.crossTileSymbolIndex=new vt,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.bF,this._loaded=!1,this._availableImages=[],this._globalState={},this._resetUpdates(),this.dispatcher.broadcast("SR",t.bG()),oe().on(ee,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.sourceCaches[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}setGlobalStateProperty(e,i){var o,r,a;this._checkLoaded();const s=null===i?null!==(a=null===(r=null===(o=this.stylesheet.state)||void 0===o?void 0:o[e])||void 0===r?void 0:r.default)&&void 0!==a?a:null:i;if(t.bH(s,this._globalState[e]))return this;this._globalState[e]=s,this._applyGlobalStateChanges([e]);}getGlobalState(){return this._globalState}setGlobalState(e){this._checkLoaded();const i=[];for(const o in e)!t.bH(this._globalState[o],e[o].default)&&(i.push(o),this._globalState[o]=e[o].default);this._applyGlobalStateChanges(i);}_applyGlobalStateChanges(e){if(0===e.length)return;const t=new Set,i={};for(const o of e){i[o]=this._globalState[o];for(const e in this._layers){const i=this._layers[e],r=i.getLayoutAffectingGlobalStateRefs(),a=i.getPaintAffectingGlobalStateRefs();if(r.has(o)&&t.add(i.source),a.has(o))for(const{name:e,value:t}of a.get(o))this._updatePaintProperty(i,e,t);}}this.dispatcher.broadcast("UGS",i);for(const e in this.sourceCaches)t.has(e)&&(this._reloadSource(e),this._changed=!0);}loadURL(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const r=this.map._requestManager.transformRequest(e,"Style");this._loadStyleRequest=new AbortController;const a=this._loadStyleRequest;t.j(r,this._loadStyleRequest).then((e=>{this._loadStyleRequest=null,this._load(e.data,i,o);})).catch((e=>{this._loadStyleRequest=null,e&&!a.signal.aborted&&this.fire(new t.k(e));}));}loadJSON(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,s.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=!1!==i.validate,this._load(e,i,o);})).catch((()=>{}));}loadEmpty(){this.fire(new t.l("dataloading",{dataType:"style"})),this._load(yi,{validate:!1});}_load(e,i,o){var r,a;let s=i.transformStyle?i.transformStyle(o,e):e;if(!i.validate||!xi(this,t.z(s))){s=Object.assign({},s),this._loaded=!0,this.stylesheet=s;for(const e in s.sources)this.addSource(e,s.sources[e],{validate:!1});s.sprite?this._loadSprite(s.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(s.glyphs),this._createLayers(),this.light=new I(this.stylesheet.light),this._setProjectionInternal((null===(r=this.stylesheet.projection)||void 0===r?void 0:r.type)||"mercator"),this.sky=new S(this.stylesheet.sky),this.map.setTerrain(null!==(a=this.stylesheet.terrain)&&void 0!==a?a:null),this.fire(new t.l("data",{dataType:"style"})),this.fire(new t.l("style.load"));}}_createLayers(){var e;const i=t.bI(this.stylesheet.layers);this.setGlobalState(null!==(e=this.stylesheet.state)&&void 0!==e?e:null),this.dispatcher.broadcast("SL",i),this._order=i.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const e of i){const i=t.bJ(e,this._globalState);i.setEventedParent(this,{layer:{id:e.id}}),this._layers[e.id]=i;}}_loadSprite(e,i=!1,o=void 0){let r;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=f(e),n=o>1?"@2x":"",l={},c={};for(const{id:e,url:o}of a){const a=i.transformRequest(g(o,n,".json"),"SpriteJSON");l[e]=t.j(a,r);const s=i.transformRequest(g(o,n,".png"),"SpriteImage");c[e]=p.getImage(s,r);}return yield Promise.all([...Object.values(l),...Object.values(c)]),function(e,i){return t._(this,void 0,void 0,(function*(){const t={};for(const o in e){t[o]={};const r=s.getImageCanvasContext((yield i[o]).data),a=(yield e[o]).data;for(const e in a){const{width:i,height:s,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=a[e];t[o][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:s,x:n,y:l,context:r}};}}return t}))}(l,c)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const o=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of o)this.imageManager.removeImage(e),this._changedImages[e]=!0;for(const o in e[t]){const r="default"===t?o:`${t}:${o}`;this._spritesImagesIds[t].push(r),r in this.imageManager.images?this.imageManager.updateImage(r,e[t][o],!1):this.imageManager.addImage(r,e[t][o]),i&&(this._changedImages[r]=!0);}}})).catch((e=>{this._spriteRequest=null,r=e,this.fire(new t.k(r));})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),i&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"})),o&&o(r);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}_validateLayer(e){const i=this.sourceCaches[e.source];if(!i)return;const o=e.sourceLayer;if(!o)return;const r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.k(new Error(`Source layer "${o}" does not exist on source "${r.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(const e in this.sourceCaches)if(!this.sourceCaches[e].loaded())return !1;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=!1){const o=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.bK(o):o);const r=[];for(const a of e)if(o[a]){const e=i?t.bK(o[a]):o[a];r.push(e);}return r}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){var e,t,i;if(null===(e=this.light)||void 0===e?void 0:e.hasTransition())return !0;if(null===(t=this.sky)||void 0===t?void 0:t.hasTransition())return !0;if(null===(i=this.projection)||void 0===i?void 0:i.hasTransition())return !0;for(const e in this.sourceCaches)if(this.sourceCaches[e].hasTransition())return !0;for(const e in this._layers)if(this._layers[e].hasTransition())return !0;return !1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const o={};for(const e in this.sourceCaches){const t=this.sourceCaches[e];o[e]=t.used,t.used=!1;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.sourceCaches[i.source].used=!0);}for(const e in o){const i=this.sourceCaches[e];!!o[e]!=!!i.used&&i.fire(new t.l("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.projection.recalculate(e),this.z=e.zoom,i&&this.fire(new t.l("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,!1),removedIds:t});}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1;}setState(e,i={}){var o;this._checkLoaded();const r=this.serialize();if(e=i.transformStyle?i.transformStyle(r,e):e,(null===(o=i.validate)||void 0===o||o)&&xi(this,t.z(e)))return !1;(e=t.bK(e)).layers=t.bI(e.layers);const a=t.bL(r,e),s=this._getOperationsToPerform(a);if(s.unimplemented.length>0)throw new Error(`Unimplemented: ${s.unimplemented.join(", ")}.`);if(0===s.operations.length)return !1;for(const e of s.operations)e();return this.stylesheet=e,this._serializedLayers=null,!0}_getOperationsToPerform(e){const t=[],i=[];for(const o of e)switch(o.command){case "setCenter":case "setZoom":case "setBearing":case "setPitch":case "setRoll":continue;case "addLayer":t.push((()=>this.addLayer.apply(this,o.args)));break;case "removeLayer":t.push((()=>this.removeLayer.apply(this,o.args)));break;case "setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,o.args)));break;case "setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,o.args)));break;case "setFilter":t.push((()=>this.setFilter.apply(this,o.args)));break;case "addSource":t.push((()=>this.addSource.apply(this,o.args)));break;case "removeSource":t.push((()=>this.removeSource.apply(this,o.args)));break;case "setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,o.args)));break;case "setLight":t.push((()=>this.setLight.apply(this,o.args)));break;case "setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,o.args)));break;case "setGlyphs":t.push((()=>this.setGlyphs.apply(this,o.args)));break;case "setSprite":t.push((()=>this.setSprite.apply(this,o.args)));break;case "setTerrain":t.push((()=>this.map.setTerrain.apply(this,o.args)));break;case "setSky":t.push((()=>this.setSky.apply(this,o.args)));break;case "setProjection":this.setProjection.apply(this,o.args);break;case "setGlobalState":t.push((()=>this.setGlobalState.apply(this,o.args)));break;case "setTransition":t.push((()=>{}));break;default:i.push(o.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,o={}){if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.z.source,`sources.${e}`,i,null,o))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const r=this.sourceCaches[e]=new xe(e,i,this.dispatcher);r.style=this,r.setEventedParent(this,(()=>({isSourceLoaded:r.loaded(),source:r.serialize(),sourceId:e}))),r.onAdd(this.map),this._changed=!0;}removeSource(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.k(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],i.fire(new t.l("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=!0;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error(`There is no source with this ID=${e}`);const i=this.sourceCaches[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=!0;}getSource(e){return this.sourceCaches[e]&&this.sourceCaches[e].getSource()}addLayer(e,i,o={}){this._checkLoaded();const r=e.id;if(this.getLayer(r))return void this.fire(new t.k(new Error(`Layer "${r}" already exists on this map.`)));let a;if("custom"===e.type){if(xi(this,t.bM(e)))return;a=t.bJ(e,this._globalState);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(r,e.source),e=t.bK(e),e=t.e(e,{source:r})),this._validate(t.z.layer,`layers.${r}`,e,{arrayIndex:-1},o))return;a=t.bJ(e,this._globalState),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}});}const s=i?this._order.indexOf(i):this._order.length;if(i&&-1===s)this.fire(new t.k(new Error(`Cannot add layer "${r}" before non-existing layer "${i}".`)));else {if(this._order.splice(s,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){const e=this._removedLayers[r];delete this._removedLayers[r],e.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=!0,!this._layers[e])return void this.fire(new t.k(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const o=this._order.indexOf(e);this._order.splice(o,1);const r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.k(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.k(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,o){this._checkLoaded();const r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.k(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,o={}){this._checkLoaded();const r=this.getLayer(e);if(r){if(!t.bH(r.filter,i))return null==i?(r.setFilter(void 0),void this._updateLayer(r)):void(this._validate(t.z.filter,`layers.${r.id}.filter`,i,null,o)||(r.setFilter(t.bK(i)),this._updateLayer(r)))}else this.fire(new t.k(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.bK(this.getLayer(e).filter)}setLayoutProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.k(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getPaintProperty(i),o)||this._updatePaintProperty(a,i,o,r):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}_updatePaintProperty(e,t,i,o={}){e.setPaintProperty(t,i,o)&&this._updateLayer(e),this._changed=!0,this._updatedPaintProps[e.id]=!0,this._serializedLayers=null;}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0===a)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const s=a.getSource().type;"geojson"===s&&r?this.fire(new t.k(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==s||r?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const o=e.source,r=this.sourceCaches[o];if(void 0===r)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const a=r.getSource().type,s="vector"===a?e.sourceLayer:void 0;"vector"!==a||s?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.k(new Error("A feature id is required to remove its specific state property."))):r.removeFeatureState(s,e.id,i):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r)return "vector"!==r.getSource().type||o?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id)):void this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.k(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.bN(this.sourceCaches,(e=>e.serialize())),i=this._serializeByIds(this._order,!0),o=this.map.getTerrain()||void 0,r=this.stylesheet;return t.bO({version:r.version,name:r.name,metadata:r.metadata,light:r.light,sky:r.sky,center:r.center,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,sprite:r.sprite,glyphs:r.glyphs,transition:r.transition,projection:r.projection,sources:e,layers:i,terrain:o},(e=>void 0!==e))}_updateLayer(e){this._updatedLayers[e.id]=!0,e.source&&!this._updatedSources[e.source]&&"raster"!==this.sourceCaches[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.sourceCaches[e.source].pause()),this._serializedLayers=null,this._changed=!0;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},o=[];for(let r=this._order.length-1;r>=0;r--){const a=this._order[r];if(t(a)){i[a]=r;for(const t of e){const e=t[a];if(e)for(const t of e)o.push(t);}}}o.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const r=[];for(let a=this._order.length-1;a>=0;a--){const s=this._order[a];if(t(s))for(let e=o.length-1;e>=0;e--){const t=o[e].feature;if(i[t.layer.id]this.map.terrain.getElevation(e,t,i):void 0));return this.placement&&a.push(function(e,t,i,o,r,a,s){const n={},l=a.queryRenderedSymbols(o),c=[];for(const e of Object.keys(l).map(Number))c.push(s[e]);c.sort(N);for(const i of c){const o=i.featureIndex.lookupSymbolFeatures(l[i.bucketInstanceId],t,i.bucketIndex,i.sourceLayerIndex,{filterSpec:r.filter,globalState:r.globalState},r.layers,r.availableImages,e);for(const e in o){const t=n[e]=n[e]||[],r=o[e];r.sort(((e,t)=>{const o=i.featureSortOrder;if(o){const i=o.indexOf(e.featureIndex);return o.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of r)t.push(e);}}return function(e,t,i){for(const o in e)for(const r of e[o])U(r,i[t[o].source]);return e}(n,e,i)}(this._layers,s,this.sourceCaches,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(a)}querySourceFeatures(e,i){(null==i?void 0:i.filter)&&this._validate(t.z.filter,"querySourceFeatures.filter",i.filter,null,i);const o=this.sourceCaches[e];return o?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),o=[],r={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const o=this.crossTileSymbolIndex.addLayer(i,l[i.source],e.center.lng);a=a||o;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((r=r||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(s.now(),e.zoom))&&(this.pauseablePlacement=new _t(e,this.map.terrain,this._order,r,t,i,o,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(s.now()),n=!0),a&&this.pauseablePlacement.placement.setStale()),n||a)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,l[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(s.now())}_releaseSymbolFadeTiles(){for(const e in this.sourceCaches)this.sourceCaches[e].releaseSymbolFadeTiles();}getImages(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.z.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}addSprite(e,i,o={},r){this._checkLoaded();const a=[{id:e,url:i}],s=[...f(this.stylesheet.sprite),...a];this._validate(t.z.sprite,"sprite",s,null,o)||(this.stylesheet.sprite=s,this._loadSprite(a,!0,r));}removeSprite(e){this._checkLoaded();const i=f(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=!0;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:void 0,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}else this.fire(new t.k(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return f(this.stylesheet.sprite)}setSprite(e,i={},o){this._checkLoaded(),e&&this._validate(t.z.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,!0,o):(this._unloadSprite(),o&&o(null)));}}var Ti=t.aJ([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class Pi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;}bind(e,t,i,o,r,a,s,n,l){this.context=e;let c=this.boundPaintVertexBuffers.length!==o.length;for(let e=0;!c&&e({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:o?o.properties.get("fog-color"):t.bf.white,u_fog_ground_blend:o?o.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:a?0:o?o.calculateFogBlendOpacity(r):0,u_horizon_color:o?o.properties.get("horizon-color"):t.bf.white,u_horizon_fog_blend:o?o.properties.get("horizon-fog-blend"):1,u_is_globe_mode:a?1:0}),Ii={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function Mi(e){const t=[];for(let i=0;i({u_depth:new t.bP(e,i.u_depth),u_terrain:new t.bP(e,i.u_terrain),u_terrain_dim:new t.bg(e,i.u_terrain_dim),u_terrain_matrix:new t.bR(e,i.u_terrain_matrix),u_terrain_unpack:new t.bS(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.bg(e,i.u_terrain_exaggeration)}))(e,C),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.bR(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.bS(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.bS(e,i.u_projection_clipping_plane),u_projection_transition:new t.bg(e,i.u_projection_transition),u_projection_fallback_matrix:new t.bR(e,i.u_projection_fallback_matrix)}))(e,C),this.binderUniforms=o?o.getUniforms(e,C):[];}draw(e,t,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v){const b=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(o),e.setColorMode(r),e.setCullFace(a),n){e.activeTexture.set(b.TEXTURE2),b.bindTexture(b.TEXTURE_2D,n.depthTexture),e.activeTexture.set(b.TEXTURE3),b.bindTexture(b.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[Ii[e]].set(l[e]);if(s)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(s[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let x=0;switch(t){case b.LINES:x=2;break;case b.TRIANGLES:x=3;break;case b.LINE_STRIP:x=1;}for(const i of d.get()){const o=i.vaos||(i.vaos={});(o[c]||(o[c]=new Pi)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),b.drawElements(t,i.primitiveLength*x,b.UNSIGNED_SHORT,i.primitiveOffset*x*2);}}}function Ei(e,i,o){const r=1/t.aC(o,1,i.transform.tileZoom),a=Math.pow(2,o.tileID.overscaledZ),s=o.tileSize*Math.pow(2,i.transform.tileZoom)/a,n=s*(o.tileID.canonical.x+o.tileID.wrap*a),l=s*o.tileID.canonical.y;return {u_image:0,u_texsize:o.imageAtlasTexture.size,u_scale:[r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Ri=(e,i,o,r)=>{const a=e.style.light,s=a.properties.get("position"),n=[s.x,s.y,s.z],l=t.bV();"viewport"===a.properties.get("anchor")&&t.bW(l,e.transform.bearingInRadians),t.bX(n,n,l);const c=e.transform.transformLightDirection(n),h=a.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:o,u_fill_translate:r}},zi=(e,i,o,r,a,s,n)=>t.e(Ri(e,i,o,r),Ei(s,e,n),{u_height_factor:-Math.pow(2,a.overscaledZ)/n.tileSize/8}),Di=(e,i,o,r)=>t.e(Ei(i,e,o),{u_fill_translate:r}),Ai=(e,t)=>({u_world:e,u_fill_translate:t}),Li=(e,i,o,r,a)=>t.e(Di(e,i,o,a),{u_world:r}),ki=(e,i,o,r,a)=>{const s=e.transform;let n,l,c=0;if("map"===o.paint.get("circle-pitch-alignment")){const e=t.aC(i,1,s.zoom);n=!0,l=[e,e],c=e/(t.$*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*a;}else n=!1,l=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===o.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:r}},Fi=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),Bi=e=>({u_viewport_size:[e.width,e.height]}),Oi=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),ji=(e,i,o,r)=>{const a=t.aC(e,1,i)/(t.$*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*r;return {u_extrude_scale:t.aC(e,1,i),u_intensity:o,u_globe_extrude_scale:a}},Ni=(e,i,o,r)=>{const a=t.L();t.bY(a,0,e.width,e.height,0,0,1);const s=e.context.gl;return {u_matrix:a,u_world:[s.drawingBufferWidth,s.drawingBufferHeight],u_image:o,u_color_ramp:r,u_opacity:i.paint.get("heatmap-opacity")}},Ui=(e,t,i)=>{const o=i.paint.get("hillshade-accent-color");let r;switch(i.paint.get("hillshade-method")){case "basic":r=4;break;case "combined":r=1;break;case "igor":r=2;break;case "multidirectional":r=3;break;default:r=0;}const a=i.getIlluminationProperties();for(let t=0;t{const o=i.stride,r=t.L();return t.bY(r,0,t.$,-t.$,0,0,1),t.M(r,r,[0,-t.$,0]),{u_matrix:r,u_image:1,u_dimension:[o,o],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function Gi(e,i){const o=Math.pow(2,i.canonical.z),r=i.canonical.y;return [new t.a1(0,r/o).toLngLat().lat,new t.a1(0,(r+1)/o).toLngLat().lat]}const Vi=(e,t,i=0)=>({u_image:0,u_unpack:t.getUnpackVector(),u_dimension:[t.stride,t.stride],u_elevation_stops:1,u_color_stops:4,u_color_ramp_size:i,u_opacity:e.paint.get("color-relief-opacity")}),$i=(e,i,o,r)=>{const a=e.transform;return {u_translation:Ki(e,i,o),u_ratio:r/t.aC(i,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},qi=(e,i,o,r,a)=>t.e($i(e,i,o,r),{u_image:0,u_image_height:a}),Wi=(e,i,o,r,a)=>{const s=e.transform,n=Xi(i,s);return {u_translation:Ki(e,i,o),u_texsize:i.imageAtlasTexture.size,u_ratio:r/t.aC(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},Hi=(e,i,o,r,a,s)=>{const n=e.lineAtlas,l=Xi(i,e.transform),c="round"===o.layout.get("line-cap"),h=n.getDash(a.from,c),u=n.getDash(a.to,c),d=h.width*s.fromScale,_=u.width*s.toScale;return t.e($i(e,i,o,r),{u_patternscale_a:[l/d,-h.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*e.pixelRatio)/2,u_image:0,u_tex_y_a:h.y,u_tex_y_b:u.y,u_mix:s.t})};function Xi(e,i){return 1/t.aC(e,1,i.tileZoom)}function Ki(e,i,o){return t.aD(e.transform,i,o.paint.get("line-translate"),o.paint.get("line-translate-anchor"))}const Yi=(e,t,i,o,r)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*o.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:o.paint.get("raster-brightness-min"),u_brightness_high:o.paint.get("raster-brightness-max"),u_saturation_factor:(s=o.paint.get("raster-saturation"),s>0?1-1/(1.001-s):-s),u_contrast_factor:(a=o.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Qi(o.paint.get("raster-hue-rotate")),u_coords_top:[r[0].x,r[0].y,r[1].x,r[1].y],u_coords_bottom:[r[3].x,r[3].y,r[2].x,r[2].y]};var a,s;};function Qi(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const Ji=(e,t,i,o,r,a,s,n,l,c,h,u,d)=>{const _=s.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+o,u_is_along_line:r,u_is_variable_anchor:a,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},eo=(e,i,o,r,a,s,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.e(Ji(e,i,o,r,a,s,n,l,c,h,u,d,p),{u_gamma_scale:r?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:1})},to=(e,i,o,r,a,s,n,l,c,h,u,d,_)=>t.e(eo(e,i,o,r,a,s,n,l,c,h,!0,u,0,_),{u_texsize_icon:d,u_texture_icon:1}),io=(e,t)=>({u_opacity:e,u_color:t}),oo=(e,i,o,r,a)=>t.e(function(e,i,o,r){const a=o.imageManager.getPattern(e.from.toString()),s=o.imageManager.getPattern(e.to.toString()),{width:n,height:l}=o.imageManager.getPixelSize(),c=Math.pow(2,r.tileID.overscaledZ),h=r.tileSize*Math.pow(2,o.transform.tileZoom)/c,u=h*(r.tileID.canonical.x+r.tileID.wrap*c),d=h*r.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:s.tl,u_pattern_br_b:s.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:s.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.aC(r,1,o.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(o,a,i,r),{u_opacity:e}),ro=(e,t)=>{},ao={fillExtrusion:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_height_factor:new t.bg(e,i.u_height_factor),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.bU(e,i.u_world),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_scale_with_map:new t.bP(e,i.u_scale_with_map),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_extrude_scale:new t.bU(e,i.u_extrude_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale),u_translate:new t.bU(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.bU(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.bU(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.bQ(e,i.u_color),u_overlay:new t.bP(e,i.u_overlay),u_overlay_scale:new t.bg(e,i.u_overlay_scale)}),depth:ro,clippingMask:ro,heatmap:(e,i)=>({u_extrude_scale:new t.bg(e,i.u_extrude_scale),u_intensity:new t.bg(e,i.u_intensity),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_color_ramp:new t.bP(e,i.u_color_ramp),u_opacity:new t.bg(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.bP(e,i.u_image),u_latrange:new t.bU(e,i.u_latrange),u_exaggeration:new t.bg(e,i.u_exaggeration),u_altitudes:new t.b_(e,i.u_altitudes),u_azimuths:new t.b_(e,i.u_azimuths),u_accent:new t.bQ(e,i.u_accent),u_method:new t.bP(e,i.u_method),u_shadows:new t.bZ(e,i.u_shadows),u_highlights:new t.bZ(e,i.u_highlights)}),hillshadePrepare:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_image:new t.bP(e,i.u_image),u_dimension:new t.bU(e,i.u_dimension),u_zoom:new t.bg(e,i.u_zoom),u_unpack:new t.bS(e,i.u_unpack)}),colorRelief:(e,i)=>({u_image:new t.bP(e,i.u_image),u_unpack:new t.bS(e,i.u_unpack),u_dimension:new t.bU(e,i.u_dimension),u_elevation_stops:new t.bP(e,i.u_elevation_stops),u_color_stops:new t.bP(e,i.u_color_stops),u_color_ramp_size:new t.bP(e,i.u_color_ramp_size),u_opacity:new t.bg(e,i.u_opacity)}),line:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_image:new t.bP(e,i.u_image),u_image_height:new t.bg(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_texsize:new t.bU(e,i.u_texsize),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_image:new t.bP(e,i.u_image),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_patternscale_a:new t.bU(e,i.u_patternscale_a),u_patternscale_b:new t.bU(e,i.u_patternscale_b),u_sdfgamma:new t.bg(e,i.u_sdfgamma),u_image:new t.bP(e,i.u_image),u_tex_y_a:new t.bg(e,i.u_tex_y_a),u_tex_y_b:new t.bg(e,i.u_tex_y_b),u_mix:new t.bg(e,i.u_mix)}),raster:(e,i)=>({u_tl_parent:new t.bU(e,i.u_tl_parent),u_scale_parent:new t.bg(e,i.u_scale_parent),u_buffer_scale:new t.bg(e,i.u_buffer_scale),u_fade_t:new t.bg(e,i.u_fade_t),u_opacity:new t.bg(e,i.u_opacity),u_image0:new t.bP(e,i.u_image0),u_image1:new t.bP(e,i.u_image1),u_brightness_low:new t.bg(e,i.u_brightness_low),u_brightness_high:new t.bg(e,i.u_brightness_high),u_saturation_factor:new t.bg(e,i.u_saturation_factor),u_contrast_factor:new t.bg(e,i.u_contrast_factor),u_spin_weights:new t.bT(e,i.u_spin_weights),u_coords_top:new t.bS(e,i.u_coords_top),u_coords_bottom:new t.bS(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texsize_icon:new t.bU(e,i.u_texsize_icon),u_texture:new t.bP(e,i.u_texture),u_texture_icon:new t.bP(e,i.u_texture_icon),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_color:new t.bQ(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_image:new t.bP(e,i.u_image),u_pattern_tl_a:new t.bU(e,i.u_pattern_tl_a),u_pattern_br_a:new t.bU(e,i.u_pattern_br_a),u_pattern_tl_b:new t.bU(e,i.u_pattern_tl_b),u_pattern_br_b:new t.bU(e,i.u_pattern_br_b),u_texsize:new t.bU(e,i.u_texsize),u_mix:new t.bg(e,i.u_mix),u_pattern_size_a:new t.bU(e,i.u_pattern_size_a),u_pattern_size_b:new t.bU(e,i.u_pattern_size_b),u_scale_a:new t.bg(e,i.u_scale_a),u_scale_b:new t.bg(e,i.u_scale_b),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.bg(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_ele_delta:new t.bg(e,i.u_ele_delta),u_fog_matrix:new t.bR(e,i.u_fog_matrix),u_fog_color:new t.bQ(e,i.u_fog_color),u_fog_ground_blend:new t.bg(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.bg(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon_fog_blend:new t.bg(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.bg(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.bg(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_terrain_coords_id:new t.bg(e,i.u_terrain_coords_id),u_ele_delta:new t.bg(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.bg(e,i.u_input),u_output_expected:new t.bg(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.bT(e,i.u_sun_pos),u_atmosphere_blend:new t.bg(e,i.u_atmosphere_blend),u_globe_position:new t.bT(e,i.u_globe_position),u_globe_radius:new t.bg(e,i.u_globe_radius),u_inv_proj_matrix:new t.bR(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.bQ(e,i.u_sky_color),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon:new t.bU(e,i.u_horizon),u_horizon_normal:new t.bU(e,i.u_horizon_normal),u_sky_horizon_blend:new t.bg(e,i.u_sky_horizon_blend),u_sky_blend:new t.bg(e,i.u_sky_blend)})};class so{constructor(e,t,i){this.context=e;const o=e.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const no={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class lo{constructor(e,t,i,o){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=o,this.context=e;const r=e.gl;this.buffer=r.createBuffer(),e.bindVertexBuffer.set(this.buffer),r.bufferData(r.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(s,l.LINES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Fi(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),o.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!a||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.b$;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:S,angle:E});}else $e(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===o.layout.get("text-rotation-alignment");De(c,e,a,O,j,v,h,i,l.toUnwrapped(),f.width,f.height,U,t);}const $=a&&P||V,q=b||$?Yo:v?O:e.transform.clipSpaceToPixelsMatrix,W=p&&0!==o.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1);let H;H=p?c.iconsInText?to(T.kind,E,x,v,b,$,e,q,N,U,z,k,I):eo(T.kind,E,x,v,b,$,e,q,N,U,a,z,0,I):Ji(T.kind,E,x,v,b,$,e,q,N,U,a,z,I);const X={program:S,buffers:u,uniformValues:H,projectionData:Z,atlasTexture:D,atlasTextureIcon:F,atlasInterpolation:A,atlasInterpolationIcon:L,isSDF:p,hasHalo:W};if(y&&c.canOverlap){w=!0;const e=u.segments.get();for(const i of e)C.push({segments:new t.aM([i]),sortKey:i.sortKey,state:X,terrainData:R});}else C.push({segments:u.segments,sortKey:0,state:X,terrainData:R});}w&&C.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of C){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const r=i.uniformValues;i.hasHalo&&(r.u_is_halo=1,or(i.buffers,t.segments,o,e,i.program,T,u,d,r,i.projectionData,t.terrainData)),r.u_is_halo=0;}or(i.buffers,t.segments,o,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function or(e,t,i,o,r,a,s,n,l,c,h){const u=o.context;r.draw(u,u.gl.TRIANGLES,a,s,n,Ut.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,o.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function rr(e,i,o,r,a){const s=e.context,n=s.gl,l=Vt.disabled,c=new jt([n.ONE,n.ONE],t.bf.transparent,[!0,!0,!0,!0]),h=i.getBucket(o);if(!h)return;const u=r.key;let d=o.heatmapFbos.get(u);d||(d=sr(s,i.tileSize,i.tileSize),o.heatmapFbos.set(u,d)),s.bindFramebuffer.set(d.framebuffer),s.viewport.set([0,0,i.tileSize,i.tileSize]),s.clear({color:t.bf.transparent});const _=h.programConfigurations.get(o.id),p=e.useProgram("heatmap",_,!a),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),f=e.style.map.terrain.getTerrainData(r);p.draw(s,n.TRIANGLES,Zt.disabled,l,c,Ut.disabled,ji(i,e.transform.zoom,o.paint.get("heatmap-intensity"),1),f,m,o.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,o.paint,e.transform.zoom,_);}function ar(e,t,i,o,r){const a=e.context,s=a.gl,n=e.transform;a.setColorMode(e.colorModeForRenderPass());const l=nr(a,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,h.colorAttachment.get()),a.activeTexture.set(s.TEXTURE1),l.bind(s.LINEAR,s.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:r,applyGlobeMatrix:!o});e.useProgram("heatmapTexture").draw(a,s.TRIANGLES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Ni(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function sr(e,t,i){var o,r;const a=e.gl,s=a.createTexture();a.bindTexture(a.TEXTURE_2D,s),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR);const n=null!==(o=e.HALF_FLOAT)&&void 0!==o?o:a.UNSIGNED_BYTE,l=null!==(r=e.RGBA16F)&&void 0!==r?r:a.RGBA;a.texImage2D(a.TEXTURE_2D,0,l,t,i,0,a.RGBA,n,null);const c=e.createFramebuffer(t,i,!1,!1);return c.colorAttachment.set(s),c}function nr(e,i){return i.colorRampTexture||(i.colorRampTexture=new t.T(e,i.colorRamp,e.gl.RGBA)),i.colorRampTexture}function lr(e,t,i,o,r){if(!i||!o||!o.imageAtlas)return;const a=o.imageAtlas.patternPositions;let s=a[i.to.toString()],n=a[i.from.toString()];if(!s&&n&&(s=n),!n&&s&&(n=s),!s||!n){const e=r.getPaintProperty(t);s=a[e],n=a[e];}s&&n&&e.setConstantPatternPositions(s,n);}function cr(e,i,o,r,a,s,n,l){const c=e.context.gl,h="fill-pattern",u=o.paint.get(h),d=u&&u.constantOr(1),_=o.getCrossfadeParameters();let p,m,f,g,v;const b=e.transform,x=o.paint.get("fill-translate"),y=o.paint.get("fill-translate-anchor");n?(m=d&&!o.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",p=c.LINES):(m=d?"fillPattern":"fill",p=c.TRIANGLES);const w=u.constantOr(null);for(const u of r){const r=i.getTile(u);if(d&&!r.patternsLoaded())continue;const T=r.getBucket(o);if(!T)continue;const P=T.programConfigurations.get(o.id),C=e.useProgram(m,P),I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(u);d&&(e.context.activeTexture.set(c.TEXTURE0),r.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),P.updatePaintBuffers(_)),lr(P,h,w,r,o);const M=b.getProjectionData({overscaledTileID:u,applyGlobeMatrix:!l,applyTerrainMatrix:!0}),S=t.aD(b,r,x,y);if(n){g=T.indexBuffer2,v=T.segments2;const t=[c.drawingBufferWidth,c.drawingBufferHeight];f="fillOutlinePattern"===m&&d?Li(e,_,r,t,S):Ai(t,S);}else g=T.indexBuffer,v=T.segments,f=d?Di(e,_,r,S):{u_fill_translate:S};const E=e.stencilModeForClipping(u);C.draw(e.context,p,a,E,s,Ut.backCCW,f,I,M,o.id,T.layoutVertexBuffer,g,v,o.paint,e.transform.zoom,P);}}function hr(e,i,o,r,a,s,n,l){const c=e.context,h=c.gl,u="fill-extrusion-pattern",d=o.paint.get(u),_=d.constantOr(1),p=o.getCrossfadeParameters(),m=o.paint.get("fill-extrusion-opacity"),f=d.constantOr(null),g=e.transform;for(const d of r){const r=i.getTile(d),v=r.getBucket(o);if(!v)continue;const b=e.style.map.terrain&&e.style.map.terrain.getTerrainData(d),x=v.programConfigurations.get(o.id),y=e.useProgram(_?"fillExtrusionPattern":"fillExtrusion",x);_&&(e.context.activeTexture.set(h.TEXTURE0),r.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),x.updatePaintBuffers(p));const w=g.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!l,applyTerrainMatrix:!0});lr(x,u,f,r,o);const T=t.aD(g,r,o.paint.get("fill-extrusion-translate"),o.paint.get("fill-extrusion-translate-anchor")),P=o.paint.get("fill-extrusion-vertical-gradient"),C=_?zi(e,P,m,T,d,p,r):Ri(e,P,m,T);y.draw(c,c.gl.TRIANGLES,a,s,n,Ut.backCCW,C,b,w,o.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,o.paint,e.transform.zoom,x,e.style.map.terrain&&v.centroidVertexBuffer);}}function ur(e,t,i,o,r,a,s,n,l){var c;const h=e.style.projection,u=e.context,d=e.transform,_=u.gl,p=[`#define NUM_ILLUMINATION_SOURCES ${i.paint.get("hillshade-highlight-color").values.length}`],m=e.useProgram("hillshade",null,!1,p),f=!e.options.moving;for(const p of o){const o=t.getTile(p),g=o.fbo;if(!g)continue;const v=h.getMeshFromTileID(u,p.canonical,n,!0,"raster"),b=null===(c=e.style.map.terrain)||void 0===c?void 0:c.getTerrainData(p);u.activeTexture.set(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g.colorAttachment.get());const x=d.getProjectionData({overscaledTileID:p,aligned:f,applyGlobeMatrix:!l,applyTerrainMatrix:!0});m.draw(u,_.TRIANGLES,a,r[p.overscaledZ],s,Ut.backCCW,Ui(e,o,i),b,x,i.id,v.vertexBuffer,v.indexBuffer,v.segments);}}function dr(e,i,o,r,a,s,n,l,c){var h;const u=e.style.projection,d=e.context,_=e.transform,p=d.gl,m=e.useProgram("colorRelief"),f=!e.options.moving;let g=!0,v=0;for(const b of r){const r=i.getTile(b),x=r.dem;if(g){const e=p.getParameter(p.MAX_TEXTURE_SIZE),{elevationTexture:t,colorTexture:i}=o.getColorRampTextures(d,e,x.getUnpackVector());d.activeTexture.set(p.TEXTURE1),t.bind(p.NEAREST,p.CLAMP_TO_EDGE),d.activeTexture.set(p.TEXTURE4),i.bind(p.LINEAR,p.CLAMP_TO_EDGE),g=!1,v=t.size[0];}if(!x||!x.data)continue;const y=x.stride,w=x.getPixels();if(d.activeTexture.set(p.TEXTURE0),d.pixelStoreUnpackPremultiplyAlpha.set(!1),r.demTexture=r.demTexture||e.getTileTexture(y),r.demTexture){const e=r.demTexture;e.update(w,{premultiply:!1}),e.bind(p.LINEAR,p.CLAMP_TO_EDGE);}else r.demTexture=new t.T(d,w,p.RGBA,{premultiply:!1}),r.demTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE);const T=u.getMeshFromTileID(d,b.canonical,l,!0,"raster"),P=null===(h=e.style.map.terrain)||void 0===h?void 0:h.getTerrainData(b),C=_.getProjectionData({overscaledTileID:b,aligned:f,applyGlobeMatrix:!c,applyTerrainMatrix:!0});m.draw(d,p.TRIANGLES,s,a[b.overscaledZ],n,Ut.backCCW,Vi(o,r.dem,v),P,C,o.id,T.vertexBuffer,T.indexBuffer,T.segments);}}const _r=[new t.P(0,0),new t.P(t.$,0),new t.P(t.$,t.$),new t.P(0,t.$)];function pr(e,t,i,o,r,a,s,n,l=!1,c=!1){const h=o[o.length-1].overscaledZ,u=e.context,d=u.gl,_=e.useProgram("raster"),p=e.transform,m=e.style.projection,f=e.colorModeForRenderPass(),g=!e.options.moving;for(const v of o){const o=e.getDepthModeForSublayer(v.overscaledZ-h,1===i.paint.get("raster-opacity")?Zt.ReadWrite:Zt.ReadOnly,d.LESS),b=t.getTile(v);b.registerFadeDuration(i.paint.get("raster-fade-duration"));const x=t.findLoadedParent(v,0),y=t.findLoadedSibling(v),w=mr(b,x||y||null,t,i,e.transform,e.style.map.terrain);let T,P;const C="nearest"===i.paint.get("raster-resampling")?d.NEAREST:d.LINEAR;u.activeTexture.set(d.TEXTURE0),b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),u.activeTexture.set(d.TEXTURE1),x?(x.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),T=Math.pow(2,x.tileID.overscaledZ-b.tileID.overscaledZ),P=[b.tileID.canonical.x*T%1,b.tileID.canonical.y*T%1]):b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),b.texture.useMipmap&&u.extTextureFilterAnisotropic&&e.transform.pitch>20&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(v),M=p.getProjectionData({overscaledTileID:v,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),S=Yi(P||[0,0],T||1,w,i,n),E=m.getMeshFromTileID(u,v.canonical,a,s,"raster");_.draw(u,d.TRIANGLES,o,r?r[v.overscaledZ]:Vt.disabled,f,l?Ut.frontCCW:Ut.backCCW,S,I,M,i.id,E.vertexBuffer,E.indexBuffer,E.segments);}}function mr(e,i,o,r,a,n){const l=r.paint.get("raster-fade-duration");if(!n&&l>0){const r=s.now(),n=(r-e.timeAdded)/l,c=i?(r-i.timeAdded)/l:-1,h=o.getSource(),u=ge(a,{tileSize:h.tileSize,roundZoom:h.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-u)>Math.abs(e.tileID.overscaledZ-u),_=d&&e.refreshedUponExpiration?1:t.ah(d?n:1-c,0,1);return e.refreshedUponExpiration&&n>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-_}:{opacity:_,mix:0}}return {opacity:1,mix:0}}const fr=new t.bf(1,0,0,1),gr=new t.bf(0,1,0,1),vr=new t.bf(0,0,1,1),br=new t.bf(1,0,1,1),xr=new t.bf(0,1,1,1);function yr(e,t,i,o){Tr(e,0,t+i/2,e.transform.width,i,o);}function wr(e,t,i,o){Tr(e,t-i/2,0,i,e.transform.height,o);}function Tr(e,t,i,o,r,a){const s=e.context,n=s.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,o*e.pixelRatio,r*e.pixelRatio),s.clear({color:a}),n.disable(n.SCISSOR_TEST);}function Pr(e,i,o){const r=e.context,a=r.gl,s=e.useProgram("debug"),n=Zt.disabled,l=Vt.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(o);r.activeTexture.set(a.TEXTURE0);const d=i.getTileByID(o.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(o).tileSize,m=512/Math.min(p,512)*(o.overscaledZ/e.transform.zoom)*.5;let f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=` => ${o.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,o=e.context.gl,r=e.debugOverlayCanvas.getContext("2d");r.clearRect(0,0,i.width,i.height),r.shadowColor="white",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle="white",r.textBaseline="top",r.font="bold 36px Open Sans, sans-serif",r.fillText(t,5,5),r.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:o,applyGlobeMatrix:!0,applyTerrainMatrix:!0});s.draw(r,a.TRIANGLES,n,l,jt.alphaBlended,Ut.disabled,Oi(t.bf.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),s.draw(r,a.LINE_STRIP,n,l,c,Ut.disabled,Oi(t.bf.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function Cr(e,t,i,o){const{isRenderingGlobe:r}=o,a=e.context,s=a.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain");a.bindFramebuffer.set(null),a.viewport.set([0,0,e.width,e.height]);for(const o of i){const i=t.getTerrainMesh(o.tileID),u=e.renderToTexture.getTexture(o),d=t.getTerrainData(o.tileID);a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,u.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(o.tileID.toUnwrapped()),m=Ci(_,p,e.style.sky,n.pitch,r),f=n.getProjectionData({overscaledTileID:o.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});h.draw(a,s.TRIANGLES,c,Vt.disabled,l,Ut.backCCW,m,d,f,"terrain",i.vertexBuffer,i.indexBuffer,i.segments);}}function Ir(e,i){if(!i.mesh){const o=new t.aL;o.emplaceBack(-1,-1),o.emplaceBack(1,-1),o.emplaceBack(1,1),o.emplaceBack(-1,1);const r=new t.aN;r.emplaceBack(0,1,2),r.emplaceBack(0,2,3),i.mesh=new wt(e.createVertexBuffer(o,Tt.members),e.createIndexBuffer(r),t.aM.simpleSegment(0,0,o.length,r.length));}return i.mesh}class Mr{constructor(e,i){this.context=new Ho(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:t.ag(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=xe.maxUnderzooming+xe.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new vt;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.aL;i.emplaceBack(0,0),i.emplaceBack(t.$,0),i.emplaceBack(0,t.$),i.emplaceBack(t.$,t.$),this.tileExtentBuffer=e.createVertexBuffer(i,Tt.members),this.tileExtentSegments=t.aM.simpleSegment(0,0,4,2);const o=new t.aL;o.emplaceBack(0,0),o.emplaceBack(t.$,0),o.emplaceBack(0,t.$),o.emplaceBack(t.$,t.$),this.debugBuffer=e.createVertexBuffer(o,Tt.members),this.debugSegments=t.aM.simpleSegment(0,0,4,5);const r=new t.c6;r.emplaceBack(0,0,0,0),r.emplaceBack(t.$,0,t.$,0),r.emplaceBack(0,t.$,0,t.$),r.emplaceBack(t.$,t.$,t.$,t.$),this.rasterBoundsBuffer=e.createVertexBuffer(r,Ti.members),this.rasterBoundsSegments=t.aM.simpleSegment(0,0,4,2);const a=new t.aL;a.emplaceBack(0,0),a.emplaceBack(t.$,0),a.emplaceBack(0,t.$),a.emplaceBack(t.$,t.$),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(a,Tt.members),this.rasterBoundsSegmentsPosOnly=t.aM.simpleSegment(0,0,4,5);const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(1,0),s.emplaceBack(0,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,Tt.members),this.viewportSegments=t.aM.simpleSegment(0,0,4,2);const n=new t.c7;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.aN;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new Vt({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new wt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const o=t.L();t.bY(o,0,this.width,this.height,0,0,1),t.N(o,o,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const r={mainMatrix:o,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:o};this.useProgram("clippingMask",null,!0).draw(e,i.TRIANGLES,Zt.disabled,this.stencilClearMode,jt.disabled,Ut.disabled,null,null,r,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const o=this.context;o.setColorMode(jt.disabled),o.setDepthMode(Zt.disabled);const r={};for(const e of t)r[e.key]=this.nextStencilID++;this._renderTileMasks(r,t,i,!0),this._renderTileMasks(r,t,i,!1),this._tileClippingMaskIDs=r;}_renderTileMasks(e,t,i,o){const r=this.context,a=r.gl,s=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=s.getMeshFromTileID(this.context,c.canonical,o,!0,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!i,applyTerrainMatrix:!0});l.draw(r,a.TRIANGLES,Zt.disabled,new Vt({func:a.ALWAYS,mask:0},t,255,a.KEEP,a.KEEP,a.REPLACE),jt.disabled,i?Ut.disabled:Ut.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,o=this.transform,r=this.useProgram("depth"),a=this.getDepthModeFor3D(),s=ve(o,{tileSize:o.tileSize});for(const n of s){const s=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,!0,!0,"raster"),c=o.getProjectionData({overscaledTileID:n,applyGlobeMatrix:!0,applyTerrainMatrix:!0});r.draw(e,t.TRIANGLES,a,Vt.disabled,jt.disabled,Ut.backCCW,null,s,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new Vt({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new Vt({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(r>1){this.currentStencilSource=void 0,this.nextStencilID+r>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(this.clearStencil(),r>1){const e={},a={};for(let i=0;i0};for(const e in n){const t=n[e];t.used&&t.prepare(this.context),l[e]=t.getVisibleCoordinates(!1),c[e]=l[e].slice().reverse(),h[e]=t.getVisibleCoordinates(!0).reverse();}this.opaquePassCutoff=1/0;for(let e=0;ethis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.bf.black:t.bf.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,o=i.gl,r=((e,t,i)=>{const o=Math.cos(t.rollInRadians),r=Math.sin(t.rollInRadians),a=he(t),s=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-a*r)*i,(t.height/2+a*o)*i],u_horizon_normal:[-r,o],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:s}})(t,e.style.map.transform,e.pixelRatio),a=new Zt(o.LEQUAL,Zt.ReadWrite,[0,1]),s=Vt.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=Ir(i,t);l.draw(i,o.TRIANGLES,a,s,n,Ut.disabled,r,null,void 0,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=a.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[a[this.currentLayer]],t=n[e.source],i=l[e.source];this._renderTileClippingMasks(e,i,!1),this.renderLayer(this,t,e,i,u);}this.renderPass="translucent";let d=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:o,u_inv_proj_matrix:r}))(c,u,[p[0],p[1],p[2]],d,_),f=Ir(r,i);s.draw(r,a.TRIANGLES,n,Vt.disabled,jt.alphaBlended,Ut.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const o=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.sourceCaches[i.source]]:[])),r=o.filter((e=>"vector"===e.getSource().type)),a=o.filter((e=>"vector"!==e.getSource().type)),s=e=>{(!i||i.getSource().maxzooms(e))),i||a.forEach((e=>s(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let o=0;ou.getElevation(a,e,t):null;er(s,d,_,c,h,f,i,p,g,t.aD(h,e,n,l),a.toUnwrapped(),o);}}}(r,e,o,i,o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),a),0!==o.paint.get("icon-opacity").constantOr(1)&&ir(e,i,o,r,!1,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),o.layout.get("icon-rotation-alignment"),o.layout.get("icon-pitch-alignment"),o.layout.get("icon-keep-upright"),l,c,n),0!==o.paint.get("text-opacity").constantOr(1)&&ir(e,i,o,r,!0,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&(Ko(e,i,o,r,!0),Ko(e,i,o,r,!1));}(e,i,o,r,this.style.placement.variableOffsets,a):t.cc(o)?function(e,i,o,r,a){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:s}=a,n=o.paint.get("circle-opacity"),l=o.paint.get("circle-stroke-width"),c=o.paint.get("circle-stroke-opacity"),h=!o.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Zt.ReadOnly),m=Vt.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let a=0;ae.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:r,layoutVertexBuffer:a,indexBuffer:s,uniformValues:n,terrainData:l,projectionData:c}=t.state;r.draw(u,d.TRIANGLES,p,m,f,Ut.backCCW,n,l,c,o.id,a,s,t.segments,o.paint,e.transform.zoom,i);}}(e,i,o,r,a):t.cd(o)?function(e,i,o,r,a){if(0===o.paint.get("heatmap-opacity"))return;const s=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=a;if(e.style.map.terrain){for(const t of r){const r=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?rr(e,r,o,t,l):"translucent"===e.renderPass&&ar(e,o,t,n,l));}s.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,o,r){const a=e.context,s=a.gl,n=e.transform,l=Vt.disabled,c=new jt([s.ONE,s.ONE],t.bf.transparent,[!0,!0,!0,!0]);((function(e,i,o){const r=e.gl;e.activeTexture.set(r.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let a=o.heatmapFbos.get(t.c2);a?(r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer)):(a=sr(e,i.width/4,i.height/4),o.heatmapFbos.set(t.c2,a));}))(a,e,o),a.clear({color:t.bf.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return !1;if(!e.from||!e.to)return !0;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=!1,o=[]){this.cache=this.cache||{};const r=!!this.style.map.terrain,a=this.style.projection,s=i?xt.projectionMercator:a.shaderPreludeCode,n=i?Pt:a.shaderDefine,l=e+(t?t.cacheKey:"")+`/${i?Ct:a.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(r?"/terrain":"")+(o?`/${o.join("/")}`:"");return this.cache[l]||(this.cache[l]=new Si(this.context,xt[e],t,ao[e],this._showOverdrawInspector,r,s,n,o)),this.cache[l]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Sr(e,t){let i,o=!1,r=null,a=null;const s=()=>{r=null,o&&(e.apply(a,i),r=setTimeout(s,t),o=!1);};return (...e)=>(o=!0,a=this,i=e,r||s(),r)}class Er{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(!this._isValidHash(e))return !1;const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let o=window.location.hash.replace(i,"");o.startsWith("#&")?o=o.slice(0,1)+o.slice(2):"#"===o&&(o="");let r=window.location.href.replace(/(#.+)?$/,o);r=r.replace("&&","&"),window.history.replaceState(window.history.state,null,r);},this._updateHash=Sr(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,o=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),r=Math.pow(10,o),a=Math.round(t.lng*r)/r,s=Math.round(t.lat*r)/r,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${a}/${s}/${i}`:`${i}/${s}/${a}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const o=i.split("=")[0];return o===e?(t=!0,`${o}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return !1;try{new t.S(+e[2],+e[1]);}catch(e){return !1}const i=+e[0],o=+(e[3]||0),r=+(e[4]||0);return i>=this._map.getMinZoom()&&i<=this._map.getMaxZoom()&&o>=-180&&o<=180&&r>=this._map.getMinPitch()&&r<=this._map.getMaxPitch()}}const Rr={linearity:.3,easing:t.cm(0,0,.3,1)},zr=t.e({deceleration:2500,maxSpeed:1400},Rr),Dr=t.e({deceleration:20,maxSpeed:1400},Rr),Ar=t.e({deceleration:1e3,maxSpeed:360},Rr),Lr=t.e({deceleration:1e3,maxSpeed:90},Rr),kr=t.e({deceleration:1e3,maxSpeed:360},Rr);class Fr{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:s.now(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=s.now();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const o=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,r={};if(i.pan.mag()){const a=Or(i.pan.mag(),o,t.e({},zr,e||{})),s=i.pan.mult(a.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(s,this._map.transform);r.center=n.easingCenter,r.offset=n.easingOffset,Br(r,a);}if(i.zoom){const e=Or(i.zoom,o,Dr);r.zoom=this._map.transform.zoom+e.amount,Br(r,e);}if(i.bearing){const e=Or(i.bearing,o,Ar);r.bearing=this._map.transform.bearing+t.ah(e.amount,-179,179),Br(r,e);}if(i.pitch){const e=Or(i.pitch,o,Lr);r.pitch=this._map.transform.pitch+e.amount,Br(r,e);}if(i.roll){const e=Or(i.roll,o,kr);r.roll=this._map.transform.roll+t.ah(e.amount,-179,179),Br(r,e);}if(r.zoom||r.bearing){const e=void 0===i.pinchAround?i.around:i.pinchAround;r.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.e(r,{noMoveStart:!0})}}function Br(e,t){(!e.duration||e.durationi.unproject(e))),l=a.reduce(((e,t,i,o)=>e.add(t.div(o.length))),new t.P(0,0));super(e,{points:a,point:l,lngLats:s,lngLat:i.unproject(l),originalEvent:o}),this._defaultPrevented=!1;}}class Ur extends t.l{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=!1;}}class Zr{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new Ur(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new jr(e.type,this._map,e))}mouseup(e){this._map.fire(new jr(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new jr(e.type,this._map,e));}dblclick(e){return this._firePreventable(new jr(e.type,this._map,e))}mouseover(e){this._map.fire(new jr(e.type,this._map,e));}mouseout(e){this._map.fire(new jr(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Nr(e.type,this._map,e))}touchmove(e){this._map.fire(new Nr(e.type,this._map,e));}touchend(e){this._map.fire(new Nr(e.type,this._map,e));}touchcancel(e){this._map.fire(new Nr(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Gr{constructor(e){this._map=e;}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new jr(e.type,this._map,e));}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new jr("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new jr(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Vr{constructor(e){this._map=e;}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return {lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class $r{constructor(e,t){this._map=e,this._tr=new Vr(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(n.disableDrag(),this._startPos=this._lastPos=t,this._active=!0);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(o,r,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.l(e,{originalEvent:i}))}}function qr(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let o=0;othis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){const i=new t.P(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=qr(o,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const o=qr(i,t);for(const e in this.touches){const t=o[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Hr{constructor(e){this.singleTap=new Wr(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const o=this.singleTap.touchend(e,t,i);if(o){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(o)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}}}class Xr{constructor(e){this._tr=new Vr(e),this._zoomIn=new Hr({numTouches:1,numTaps:2}),this._zoomOut=new Hr({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const o=this._zoomIn.touchend(e,t,i),r=this._zoomOut.touchend(e,t,i),a=this._tr;return o?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom+1,around:a.unproject(o)},{originalEvent:e})}):r?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom-1,around:a.unproject(r)},{originalEvent:e})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class Kr{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0));}dragMove(e,t){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const o=Array.isArray(t)?t[0]:t;return !this._moved&&o.dist(i)!0}),t=new ta){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t;}_executeRelevantHandler(e,t,i){return e instanceof MouseEvent?t(e):"undefined"!=typeof TouchEvent&&e instanceof TouchEvent?i(e):void 0}startMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.startMove(e)),(e=>this.oneFingerTouchMoveStateManager.startMove(e)));}endMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.endMove(e)),(e=>this.oneFingerTouchMoveStateManager.endMove(e)));}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}const oa=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};class ra{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=!1,this._touches={},this._sum=new t.P(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,o){o.length>0&&(this._active=!0);const r=qr(o,i),a=new t.P(0,0),s=new t.P(0,0);let n=0;for(const e in r){const t=r[e],i=this._touches[e];i&&(a._add(t),s._add(t.sub(i)),n++,r[e]=t);}if(this._touches=r,this._shouldBePrevented(n)||!s.mag())return;const l=s.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class da extends aa{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,ua(e[0].sub(e[1]))&&(this._valid=!1);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const o=e[0].sub(this._lastPoints[0]),r=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const o=e.mag()>=2,r=t.mag()>=2;if(!o&&!r)return;if(!o||!r)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const a=e.y>0==t.y>0;return ua(e)&&ua(t)&&a}}const _a={panStep:100,bearingStep:15,pitchStep:10};class pa{constructor(e){this._tr=new Vr(e);const t=_a;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1;}reset(){this._active=!1;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,o=0,r=0,a=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),r=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),r=1);break;case 38:e.shiftKey?o=1:(e.preventDefault(),a=-1);break;case 40:e.shiftKey?o=-1:(e.preventDefault(),a=1);break;default:return}return this._rotationDisabled&&(i=0,o=0),{cameraAnimation:s=>{const n=this._tr;s.easeTo({duration:300,easeId:"keyboardHandler",easing:ma,zoom:t?Math.round(n.zoom)+t*(e.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+o*this._pitchStep,offset:[-r*this._panStep,-a*this._panStep],center:n.center},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function ma(e){return e*(2-e)}const fa=4.000244140625,ga=1/450;class va{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new Vr(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=ga;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=!1);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=s.now(),o=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%fa==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":o>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(o*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=n.mousePos(this._map.getCanvas(),e),o=this._tr;this._aroundPoint=this._aroundCenter?o.transform.locationToScreenPoint(t.S.convert(o.center)):i,this._frameId||(this._frameId=!0,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>fa?this._wheelZoomRate:this._defaultZoomRate;let o=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==o&&(o=1/o);const r="number"!=typeof this._targetZoom?e.scale:t.af(this._targetZoom);this._targetZoom=e.getConstrained(e.getCameraLngLat(),t.ak(r*o)).zoom,"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,o=this._startZoom,r=this._easing;let a,n=!1;if("wheel"===this._type&&o&&r){const e=s.now()-this._lastWheelEventTime,l=Math.min((e+5)/200,1),c=r(l);a=t.C.number(o,i,c),l<1?this._frameId||(this._frameId=!0):n=!0;}else a=i,n=!0;return this._active=!0,n&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=a,{noInertia:!0,needsRenderFrame:!n,zoomDelta:a-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.co;if(this._prevEase){const e=this._prevEase,o=(s.now()-e.start)/e.duration,r=e.easing(o+.01)-e.easing(o),a=.27/Math.sqrt(r*r+1e-4)*.01,n=Math.sqrt(.0729-a*a);i=t.cm(a,n,.25,1);}return this._prevEase={start:s.now(),duration:e,easing:i},i}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class ba{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class xa{constructor(e){this._tr=new Vr(e),this.reset();}reset(){this._active=!1;}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ya{constructor(){this._tap=new Hr({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const o=t[0],r=e.timeStamp-this._tapTime<500,a=this._tapPoint.dist(o)<30;r&&a?i.length>0&&(this._swipePoint=o,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const o=t[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,e.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const o=this._tap.touchend(e,t,i);o&&(this._tapTime=e.timeStamp,this._tapPoint=o);}}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class wa{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Ta{constructor(e,t,i,o){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=o;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Pa{constructor(e,t,i,o){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class Ca{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=!1;}isActive(){return !1}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=n.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),o=document.createElement("div");o.className="maplibregl-desktop-message",o.textContent=t,this._container.appendChild(o);const r=document.createElement("div");r.className="maplibregl-mobile-message",r.textContent=i,this._container.appendChild(r),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(n.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=!0;}disable(){this._enabled=!1,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.l("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const Ia=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Ma extends t.l{}function Sa(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class Ea{constructor(e,i){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,i)=>{if("blur"===e.type)return void this.stop(!0);this._updatingCamera=!0;const o="renderFrame"===e.type?void 0:e,r={needsRenderFrame:!1},a={},s={};for(const{handlerName:l,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let u;if(this._blockedByActive(s,h,l))c.reset();else if(c[i||e.type]){if(t.cp(e,i||e.type)){const t=n.mousePos(this._map.getCanvas(),e);u=c[i||e.type](e,t);}else if(t.cq(e,i||e.type)){const t=this._getMapTouches(e.touches),o=n.touchPos(this._map.getCanvas(),t);u=c[i||e.type](e,o,t);}else t.cr(i||e.type)||(u=c[i||e.type](e));this.mergeHandlerResult(r,a,u,l,o),u&&u.needsRenderFrame&&this._triggerRenderFrame();}(u||c.isActive())&&(s[l]=c);}const l={};for(const e in this._previousActiveHandlers)s[e]||(l[e]=o);this._previousActiveHandlers=s,(Object.keys(l).length||Sa(r))&&(this._changes.push([r,a,l]),this._triggerRenderFrame()),(Object.keys(s).length||Sa(r))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:c}=r;c&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],c(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Fr(e),this._bearingSnap=i.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(i);const o=this._el;this._listeners=[[o,"touchstart",{passive:!0}],[o,"touchmove",{passive:!1}],[o,"touchend",void 0],[o,"touchcancel",void 0],[o,"mousedown",void 0],[o,"mousemove",void 0],[o,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[o,"mouseover",void 0],[o,"mouseout",void 0],[o,"dblclick",void 0],[o,"click",void 0],[o,"keydown",{capture:!1}],[o,"keyup",void 0],[o,"wheel",{passive:!1}],[o,"contextmenu",void 0],[window,"blur",void 0]];for(const[e,t,i]of this._listeners)n.addEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)n.removeEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const i=this._map,o=i.getCanvasContainer();this._add("mapEvent",new Zr(i,e));const r=i.boxZoom=new $r(i,e);this._add("boxZoom",r),e.interactive&&e.boxZoom&&r.enable();const a=i.cooperativeGestures=new Ca(i,e.cooperativeGestures);this._add("cooperativeGestures",a),e.cooperativeGestures&&a.enable();const s=new Xr(i),l=new xa(i);i.doubleClickZoom=new ba(l,s),this._add("tapZoom",s),this._add("clickZoom",l),e.interactive&&e.doubleClickZoom&&i.doubleClickZoom.enable();const c=new ya;this._add("tapDragZoom",c);const h=i.touchPitch=new da(i);this._add("touchPitch",h),e.interactive&&e.touchPitch&&i.touchPitch.enable(e.touchPitch);const u=()=>i.project(i.getCenter()),d=function({enable:e,clickTolerance:i,aroundCenter:o=!0,minPixelCenterThreshold:r=100,rotateDegreesPerPixelMoved:a=.8},s){const l=new ea({checkCorrectEvent:e=>0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:i,move:(e,i)=>{const n=s();if(o&&Math.abs(n.y-e.y)>r)return {bearingDelta:t.cn(new t.P(e.x,i.y),i,n)};let l=(i.x-e.x)*a;return o&&i.y0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)});return new Kr({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:o,enable:e,assignEvents:oa})}(e),p=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3},o){const r=new ea({checkCorrectEvent:e=>2===n.mouseButton(e)&&e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>{const r=o();let a=(t.x-e.x)*i;return t.y0===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:i,enable:e,assignEvents:oa})}(e),f=new ra(e,i);i.dragPan=new wa(o,m,f),this._add("mousePan",m),this._add("touchPan",f,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&i.dragPan.enable(e.dragPan);const g=new ha,v=new la;i.touchZoomRotate=new Pa(o,v,g,c),this._add("touchRotate",g,["touchPan","touchZoom"]),this._add("touchZoom",v,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&i.touchZoomRotate.enable(e.touchZoomRotate);const b=i.scrollZoom=new va(i,(()=>this._triggerRenderFrame()));this._add("scrollZoom",b,["mousePan"]),e.interactive&&e.scrollZoom&&i.scrollZoom.enable(e.scrollZoom);const x=i.keyboard=new pa(i);this._add("keyboard",x),e.interactive&&e.keyboard&&i.keyboard.enable(),this._add("blockableMapEvent",new Gr(i));}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(Ia(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const o in e)if(o!==i&&(!t||t.indexOf(o)<0))return !0;return !1}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,o,r,a){if(!o)return;t.e(e,o);const s={handlerName:r,originalEvent:o.originalEvent||a};void 0!==o.zoomDelta&&(i.zoom=s),void 0!==o.panDelta&&(i.drag=s),void 0!==o.rollDelta&&(i.roll=s),void 0!==o.pitchDelta&&(i.pitch=s),void 0!==o.bearingDelta&&(i.rotate=s);}_applyChanges(){const e={},i={},o={};for(const[r,a,s]of this._changes)r.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(r.panDelta)),r.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+r.zoomDelta),r.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+r.bearingDelta),r.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+r.pitchDelta),r.rollDelta&&(e.rollDelta=(e.rollDelta||0)+r.rollDelta),void 0!==r.around&&(e.around=r.around),void 0!==r.pinchAround&&(e.pinchAround=r.pinchAround),r.noInertia&&(e.noInertia=r.noInertia),t.e(i,a),t.e(o,s);this._updateMapTransform(e,i,o),this._changes=[];}_updateMapTransform(e,t,i){const o=this._map,r=o._getTransformForUpdate(),a=o.terrain;if(!(Sa(e)||a&&this._terrainMovement))return this._fireEvents(t,i,!0);o._stop(!0);let{panDelta:s,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;void 0!==d&&(u=d),u=u||o.transform.centerPoint,a&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const _={panDelta:s,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const p=u.distSqr(r.centerPoint)<.01?r.center:r.screenPointToLocation(s?u.sub(s):u);a?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._terrainMovement||!t.drag&&!t.zoom?t.drag&&this._terrainMovement?r.setCenter(r.screenPointToLocation(r.centerPoint.sub(s))):this._map.cameraHelper.handleMapControlsPan(_,r,p):(this._terrainMovement=!0,this._map._elevationFreeze=!0,this._map.cameraHelper.handleMapControlsPan(_,r,p))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._map.cameraHelper.handleMapControlsPan(_,r,p)),o._applyUpdatedTransform(r),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0);}_fireEvents(e,i,o){const r=Ia(this._eventsInProgress),a=Ia(e),n={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(n[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!r&&a&&this._fireEvent("movestart",a.originalEvent);for(const e in n)this._fireEvent(e,n[e]);a&&this._fireEvent("move",a.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const l={};let c;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:o}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],c=i[t]||o,l[`${e}end`]=c);}for(const e in l)this._fireEvent(e,l[e]);const h=Ia(this._eventsInProgress),u=(r||a)&&!h;if(u&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(o&&u){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new Ma("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}class Ra extends t.E{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((s.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=i.bearingSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.S(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,o){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},i),o)}panTo(e,i,o){return this.easeTo(t.e({center:e},i),o)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,o){return this.easeTo(t.e({zoom:e},i),o)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.l("movestart",i)).fire(new t.l("move",i)).fire(new t.l("moveend",i))),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,o){return this.easeTo(t.e({bearing:e},i),o)}resetNorth(e,i){return this.rotateTo(0,t.e({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){f.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,o={}){this._moving=!0,i||o.moving||this.fire(new t.l("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.l("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.l("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.l("pitchstart",e)),this._rolling&&!o.rolling&&this.fire(new t.l("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0;}_updateElevation(e){void 0!==this._elevationStart&&void 0!==this._elevationCenter||this._prepareElevation(this.transform.center),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.C.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),o=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:o,zoom:r,roll:a,pitch:s,bearing:n,elevation:l}=e(t);o&&t.setCenter(o),void 0!==l&&t.setElevation(l),void 0!==r&&t.setZoom(r),void 0!==a&&t.setRoll(a),void 0!==s&&t.setPitch(s),void 0!==n&&t.setBearing(n),i.apply(t);}this.transform.apply(i);}_fireMoveEvents(e){this.fire(new t.l("move",e)),this._zooming&&this.fire(new t.l("zoom",e)),this._rotating&&this.fire(new t.l("rotate",e)),this._pitching&&this.fire(new t.l("pitch",e)),this._rolling&&this.fire(new t.l("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const o=this._zooming,r=this._rotating,a=this._pitching,s=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,o&&this.fire(new t.l("zoomend",e)),r&&this.fire(new t.l("rotateend",e)),a&&this.fire(new t.l("pitchend",e)),s&&this.fire(new t.l("rollend",e)),this.fire(new t.l("moveend",e));}flyTo(e,i){if(!e.essential&&s.prefersReducedMotion){const o=t.Q(e,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(o,i)}this.stop(),e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.co},e);const o=this._getTransformForUpdate(),r=o.bearing,a=o.pitch,n=o.roll,l=o.padding,c="bearing"in e?this._normalizeBearing(e.bearing,r):r,h="pitch"in e?+e.pitch:a,u="roll"in e?this._normalizeBearing(e.roll,n):n,d="padding"in e?e.padding:o.padding,_=t.P.convert(e.offset);let p=o.centerPoint.add(_);const m=o.screenPointToLocation(p),f=this.cameraHelper.handleFlyTo(o,{bearing:c,pitch:h,roll:u,padding:d,locationAtOffset:m,offsetAsPoint:_,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(o.width,o.height),b=v/f.scaleOfZoom,x=f.pixelPathLength;"number"==typeof f.scaleOfMinZoom&&(g=Math.sqrt(v/f.scaleOfMinZoom/x*2));const y=g*g;function w(e){const t=(b*b-v*v+(e?-1:1)*y*y*x*x)/(2*(e?b:v)*y*x);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function P(e){return (Math.exp(e)+Math.exp(-e))/2}const C=w(!1);let I=function(e){return P(C)/P(C+g*e)},M=function(e){return v*((P(C)*(T(t=C+g*e)/P(t))-T(C))/y)/x;var t;},S=(w(!0)-C)/g;if(Math.abs(x)<2e-6||!isFinite(S)){if(Math.abs(v-b)<1e-6)return this.easeTo(e,i);const t=b0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*S/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=r!==c,this._pitching=h!==a,this._rolling=u!==n,this._padding=!o.isPaddingEqual(d),this._prepareEase(i,!1),this.terrain&&this._prepareElevation(f.targetCenter),this._ease((s=>{const m=s*S,g=1/I(m),v=M(m);this._rotating&&o.setBearing(t.C.number(r,c,s)),this._pitching&&o.setPitch(t.C.number(a,h,s)),this._rolling&&o.setRoll(t.C.number(n,u,s)),this._padding&&(o.interpolatePadding(l,d,s),p=o.centerPoint.add(_)),f.easeFunc(s,g,v,p),this.terrain&&!e.freezeElevation&&this._updateElevation(s),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=s.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.aO(e,-180,180);const o=Math.abs(e-i);return Math.abs(e-360-i)MapLibre'};class Da{constructor(e=za){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=n.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=n.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=n.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.sourceCaches;for(const i in t){const o=t[i];if(o.used||o.usedForTerrain){const t=o.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let o=i+1;o=0)return !1;return !0}));const i=e.join(" | ");i!==this._attribHTML&&(this._attribHTML=i,e.length?(this._innerContainer.innerHTML=n.sanitize(i),this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Aa{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=n.create("div","maplibregl-ctrl");const t=n.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){n.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0;}}class La{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}var ka=t.aJ([{name:"a_pos3d",type:"Int16",components:3}]);class Fa extends t.E{constructor(e){super(),this._lastTilesetChange=s.now(),this.sourceCache=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize;}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null;}update(e,i){this.sourceCache.update(e,i),this._renderableTilesKeys=[];const o={};for(const r of ve(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:i,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))o[r.key]=!0,this._renderableTilesKeys.push(r.key),this._tiles[r.key]||(r.terrainRttPosMatrix32f=new Float64Array(16),t.bY(r.terrainRttPosMatrix32f,0,t.$,t.$,0,0,1),this._tiles[r.key]=new re(r,this.tileSize),this._lastTilesetChange=s.now());for(const e in this._tiles)o[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e,t){return t?this._getTerrainCoordsForTileRanges(e,t):this._getTerrainCoordsForRegularTile(e)}_getTerrainCoordsForRegularTile(e){const i={};for(const o of this._renderableTilesKeys){const r=this._tiles[o].tileID,a=e.clone(),s=t.ba();if(r.canonical.equals(e.canonical))t.bY(s,0,t.$,t.$,0,0,1);else if(r.canonical.isChildOf(e.canonical)){const i=r.canonical.z-e.canonical.z,o=r.canonical.x-(r.canonical.x>>i<>i<>i;t.bY(s,0,n,n,0,0,1),t.M(s,s,[-o*n,-a*n,0]);}else {if(!e.canonical.isChildOf(r.canonical))continue;{const i=e.canonical.z-r.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i;t.bY(s,0,t.$,t.$,0,0,1),t.M(s,s,[o*n,a*n,0]),t.N(s,s,[1/2**i,1/2**i,0]);}}a.terrainRttPosMatrix32f=new Float32Array(s),i[o]=a;}return i}_getTerrainCoordsForTileRanges(e,i){const o={};for(const r of this._renderableTilesKeys){const a=this._tiles[r].tileID;if(!this._isWithinTileRanges(a,i))continue;const s=e.clone(),n=t.ba();if(a.canonical.z===e.canonical.z){const i=e.canonical.x-a.canonical.x,o=e.canonical.y-a.canonical.y;t.bY(n,0,t.$,t.$,0,0,1),t.M(n,n,[i*t.$,o*t.$,0]);}else if(a.canonical.z>e.canonical.z){const i=a.canonical.z-e.canonical.z,o=a.canonical.x-(a.canonical.x>>i<>i<>i),l=e.canonical.y-(a.canonical.y>>i),c=t.$>>i;t.bY(n,0,c,c,0,0,1),t.M(n,n,[-o*c+s*t.$,-r*c+l*t.$,0]);}else {const i=e.canonical.z-a.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i)-a.canonical.x,l=(e.canonical.y>>i)-a.canonical.y,c=t.$<i.maxzoom&&(o=i.maxzoom),o=i.minzoom&&(!r||!r.dem);)r=this.sourceCache.getTileByID(e.scaledTo(o--).key);return r}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}_isWithinTileRanges(e,t){return t[e.canonical.z]&&e.canonical.x>=t[e.canonical.z].minTileX&&e.canonical.x<=t[e.canonical.z].maxTileX&&e.canonical.y>=t[e.canonical.z].minTileY&&e.canonical.y<=t[e.canonical.z].maxTileY}}class Ba{constructor(e,t,i){this._meshCache={},this.painter=e,this.sourceCache=new Fa(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(e,i,o,r=t.$){var a;if(!(i>=0&&i=0&&oe.canonical.z&&(e.canonical.z>=o?r=e.canonical.z-o:t.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const a=e.canonical.x-(e.canonical.x>>r<>r<>8<<4|e>>8,i[t+3]=0;const o=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),r=new t.T(e,o,e.gl.RGBA,{premultiply:!1});return r.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=r,r}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(!0);const i=new Uint8Array(4),o=this.painter.context,r=o.gl,a=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),s=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);o.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),r.readPixels(a,n-s-1,1,1,r.RGBA,r.UNSIGNED_BYTE,i),o.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.sourceCache.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<0,r=o&&0===e.canonical.y,a=o&&e.canonical.y===(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const ja={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class Na{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new Oa(e.context,30,t.sourceCache.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.sourceCaches){this._coordsAscending[t]={};const i=e.sourceCaches[t].getVisibleCoordinates(),o=e.sourceCaches[t].getSource(),r=o instanceof X?o.terrainTileRanges:null;for(const e of i){const i=this.terrain.sourceCache.getTerrainCoords(e,r);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._coordsAscendingStr={};for(const t of e._order){const i=e._layers[t],o=i.source;if(ja[i.type]&&!this._coordsAscendingStr[o]){this._coordsAscendingStr[o]={};for(const e in this._coordsAscending[o])this._coordsAscendingStr[o][e]=this._coordsAscending[o][e].map((e=>e.key)).sort().join();}}for(const e of this._renderableTiles)for(const t in this._coordsAscendingStr){const i=this._coordsAscendingStr[t][e.tileID.key];i&&i!==e.rttCoords[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return !1;const o=Object.assign(Object.assign({},i),{isRenderingToTexture:!0}),r=e.type,a=this.painter,s=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(ja[r]&&(this._prevType&&ja[this._prevType]||this._stacks.push([]),this._prevType=r,this._stacks[this._stacks.length-1].push(e.id),!s))return !0;if(ja[this._prevType]||ja[r]&&s){this._prevType=r;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const r of this._renderableTiles){if(this.pool.isFull()&&(Cr(this.painter,this.terrain,this._rttTiles,o),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(r),r.rtt[e]){const t=this.pool.getObjectForId(r.rtt[e].id);if(t.stamp===r.rtt[e].stamp){this.pool.useObject(t);continue}}const s=this.pool.getOrCreateFreeObject();this.pool.useObject(s),this.pool.stampObject(s),r.rtt[e]={id:s.id,stamp:s.stamp},a.context.bindFramebuffer.set(s.fbo.framebuffer),a.context.clear({color:t.bf.transparent,stencil:0}),a.currentStencilSource=void 0;for(let e=0;e{this.startMove(e,n.mousePos(this.element,e)),n.addEventListener(window,"mousemove",this.mousemove),n.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=e=>{this.move(e,n.mousePos(this.element,e));},this.mouseup=e=>{this._rotatePitchHandler.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),n.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.addEventListener(window,"touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHandler.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10,this.element=i;const r=new ia;this._rotatePitchHandler=new Kr({clickTolerance:3,move:(e,r)=>{const a=i.getBoundingClientRect(),s=new t.P((a.bottom-a.top)/2,(a.right-a.left)/2);return {bearingDelta:t.cn(new t.P(e.x,r.y),r,s),pitchDelta:o?-.5*(r.y-e.y):void 0}},moveStateManager:r,enable:!0,assignEvents:()=>{}}),this.map=e,n.addEventListener(i,"mousedown",this.mousedown),n.addEventListener(i,"touchstart",this.touchstart,{passive:!1}),n.addEventListener(i,"touchcancel",this.reset);}startMove(e,t){this._rotatePitchHandler.dragStart(e,t),n.disableDrag();}move(e,t){const i=this.map,{bearingDelta:o,pitchDelta:r}=this._rotatePitchHandler.dragMove(e,t)||{};o&&i.setBearing(i.getBearing()+o),r&&i.setPitch(i.getPitch()+r);}off(){const e=this.element;n.removeEventListener(e,"mousedown",this.mousedown),n.removeEventListener(e,"touchstart",this.touchstart,{passive:!1}),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend),n.removeEventListener(e,"touchcancel",this.reset),this.offTemp();}offTemp(){n.enableDrag(),n.removeEventListener(window,"mousemove",this.mousemove),n.removeEventListener(window,"mouseup",this.mouseup),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend);}}let qa;function Wa(e,i,o,r=!1){if(r||!o.getCoveringTilesDetailsProvider().allowWorldCopies())return null==e?void 0:e.wrap();const a=new t.S(e.lng,e.lat);if(e=new t.S(e.lng,e.lat),i){const r=new t.S(e.lng-360,e.lat),a=new t.S(e.lng+360,e.lat),s=o.locationToScreenPoint(e).distSqr(i);o.locationToScreenPoint(r).distSqr(i)180;){const t=o.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=o.width&&t.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==a.lng&&o.isPointOnMapSurface(o.locationToScreenPoint(e))?e:a}const Ha={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Xa(e,t,i){const o=e.classList;for(const e in Ha)o.remove(`maplibregl-${i}-anchor-${e}`);o.add(`maplibregl-${i}-anchor-${t}`);}class Ka extends t.E{constructor(e){if(super(),this._onKeyPress=e=>{const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{if(!this._map)return;const t=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?void 0:e.type)||"render"===(null==e?void 0:e.type)&&!t)&&this._map.once("render",this._update),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let i="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?i=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(i=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),n.setTransform(this._element,`${Ha[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${i}`),s.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.l("dragstart"))),this.fire(new t.l("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.l("dragend")),this._state="inactive";},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||!1,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(null==e?void 0:e.opacity,null==e?void 0:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.P.convert(e&&e.offset||[0,0]);else {this._defaultMarker=!0,this._element=n.create("div");const i=n.createNS("http://www.w3.org/2000/svg","svg"),o=41,r=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${o}px`),i.setAttributeNS(null,"width",`${r}px`),i.setAttributeNS(null,"viewBox",`0 0 ${r} ${o}`);const a=n.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"stroke","none"),a.setAttributeNS(null,"stroke-width","1"),a.setAttributeNS(null,"fill","none"),a.setAttributeNS(null,"fill-rule","evenodd");const s=n.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"fill-rule","nonzero");const l=n.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"transform","translate(3.0, 29.0)"),l.setAttributeNS(null,"fill","#000000");const c=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const e of c){const t=n.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),l.appendChild(t);}const h=n.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);const u=n.createNS("http://www.w3.org/2000/svg","path");u.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(u);const d=n.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");const _=n.createNS("http://www.w3.org/2000/svg","path");_.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(_);const p=n.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const m=n.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(8.0, 8.0)");const f=n.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#000000"),f.setAttributeNS(null,"opacity","0.25"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962");const g=n.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#FFFFFF"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962"),m.appendChild(f),m.appendChild(g),s.appendChild(l),s.appendChild(h),s.appendChild(d),s.appendChild(p),s.appendChild(m),i.appendChild(s),i.setAttributeNS(null,"height",o*this._scale+"px"),i.setAttributeNS(null,"width",r*this._scale+"px"),this._element.appendChild(i),this._offset=t.P.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),Xa(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),n.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,o=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-t],"bottom-left":[o,-1*(t-i+o)],"bottom-right":[-o,-1*(t-i+o)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=!1){var i,o;const r=null===(i=this._map)||void 0===i?void 0:i.terrain,a=this._map.transform.isLocationOccluded(this._lngLat);if(!r||a){const e=a?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const s=this._map,n=s.terrain.depthAtPoint(this._pos),l=s.terrain.getElevationForLngLatZoom(this._lngLat,s.transform.tileZoom);if(s.transform.lngLatToCameraDepth(this._lngLat,l)-n<.006)return void(this._element.style.opacity=this._opacity);const c=-this._offset.y/s.transform.pixelsPerMeter,h=Math.sin(s.getPitch()*Math.PI/180)*c,u=s.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),d=s.transform.lngLatToCameraDepth(this._lngLat,l+h)-u>.006;(null===(o=this._popup)||void 0===o?void 0:o.isOpen())&&d&&this._popup.remove(),this._element.style.opacity=d?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return (void 0===this._opacity||void 0===e&&void 0===t)&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==e&&(this._opacity=e),void 0!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(!0),this}}const Ya={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let Qa=0,Ja=!1;const es={maxWidth:100,unit:"metric"};function ts(e,t,i){const o=i&&i.maxWidth||100,r=e._container.clientHeight/2,a=e._container.clientWidth/2,s=e.unproject([a-o/2,r]),n=e.unproject([a+o/2,r]),l=Math.round(e.project(n).x-e.project(s).x),c=Math.min(o,l,e._container.clientWidth),h=s.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?is(t,c,i/5280,e._getUIString("ScaleControl.Miles")):is(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?is(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?is(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):is(t,c,h,e._getUIString("ScaleControl.Meters"));}function is(e,t,i,o){const r=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(r/i)+"px",e.innerHTML=`${r} ${o}`;}const os={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1,locationOccludedOpacity:void 0},rs=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function as(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(i,i),"top-right":new t.P(-i,i),bottom:new t.P(0,-e),"bottom-left":new t.P(i,-i),"bottom-right":new t.P(-i,-i),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){const i=t.P.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e["top-left"]||[0,0]),"top-right":t.P.convert(e["top-right"]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e["bottom-left"]||[0,0]),"bottom-right":t.P.convert(e["bottom-right"]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return as(new t.P(0,0))}const ss=i;e.AJAXError=t.cz,e.Event=t.l,e.Evented=t.E,e.LngLat=t.S,e.MercatorCoordinate=t.a1,e.Point=t.P,e.addProtocol=t.cA,e.config=t.a,e.removeProtocol=t.cB,e.AttributionControl=Da,e.BoxZoomHandler=$r,e.CanvasSource=Y,e.CooperativeGesturesHandler=Ca,e.DoubleClickZoomHandler=ba,e.DragPanHandler=wa,e.DragRotateHandler=Ta,e.EdgeInsets=Mt,e.FullscreenControl=class extends t.E{constructor(e={}){super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(e=null==t?void 0:t.shadowRoot)||void 0===e?void 0:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){n.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=n.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);n.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new t.l("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.l("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=H,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.l("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "BACKGROUND":case "BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.l("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.S(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.e({bearing:r},this.options.fitBoundsOptions),s=G.fromLngLat(i,o);this._map.fitBounds(s,a,{geolocateSource:!0});},this._updateMarker=e=>{if(e){const i=new t.S(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this._updateCircleRadiusIfNeeded();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded();},this._onError=e=>{if(this._map){if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Ja)return;this.options.trackUserLocation&&this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.l("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=n.create("button","maplibregl-ctrl-geolocate",this._container),n.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0);},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.w("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=n.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new Ka({element:this._dotElement}),this._circleElement=n.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ka({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onUpdate),this._map.on("move",this._onUpdate),this._map.on("rotate",this._onUpdate),this._map.on("pitch",this._onUpdate)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(e=>{const i=(null==e?void 0:e[0])instanceof ResizeObserverEntry;e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||i||this._map.isZooming()||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.l("trackuserlocationend")),this.fire(new t.l("userlocationlostfocus")));}));}},this.options=t.e({},Ya,e);}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t._(this,arguments,void 0,(function*(e=!1){if(void 0!==qa&&!e)return qa;if(void 0===window.navigator.permissions)return qa=!!window.navigator.geolocation,qa;try{const e=yield window.navigator.permissions.query({name:"geolocation"});qa="denied"!==e.state;}catch(e){qa=!!window.navigator.geolocation;}return qa}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),n.remove(this._container),this._map.off("zoom",this._onUpdate),this._map.off("move",this._onUpdate),this._map.off("rotate",this._onUpdate),this._map.off("pitch",this._onUpdate),this._map=void 0,Qa=0,Ja=!1;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case "WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case "ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadiusIfNeeded(){const e=this._userLocationDotMarker.getLngLat();if(!(this.options.showUserLocation&&this.options.showAccuracyCircle&&this._accuracy&&e))return;const t=this._map.project(e),i=this._map.unproject([t.x+100,t.y]),o=e.distanceTo(i)/100,r=2*this._accuracy/o;this._circleElement.style.width=`${r.toFixed(2)}px`,this._circleElement.style.height=`${r.toFixed(2)}px`;}trigger(){if(!this._setup)return t.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case "OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.l("trackuserlocationstart"));break;case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":case "BACKGROUND_ERROR":Qa--,Ja=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new t.l("trackuserlocationend"));break;case "BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.l("trackuserlocationstart")),this.fire(new t.l("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case "WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),Qa++,Qa>1?(e={maximumAge:6e5,timeout:0},Ja=!0):(e=this.options.positionOptions,Ja=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||void 0===e?void 0:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||void 0===e?void 0:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=n.create("button","maplibregl-ctrl-globe",this._container),n.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0;}},e.Hash=Er,e.ImageSource=X,e.KeyboardHandler=pa,e.LngLatBounds=G,e.LogoControl=Aa,e.Map=class extends Ra{constructor(e){var i,o;t.cw.mark(t.cx.create);const r=Object.assign(Object.assign(Object.assign({},Ga),e),{canvasContextAttributes:Object.assign(Object.assign({},Ga.canvasContextAttributes),e.canvasContextAttributes)});if(null!=r.minZoom&&null!=r.maxZoom&&r.minZoom>r.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=r.minPitch&&null!=r.maxPitch&&r.minPitch>r.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=r.minPitch&&r.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=r.maxPitch&&r.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const a=new Lt,s=new Ot;if(void 0!==r.minZoom&&a.setMinZoom(r.minZoom),void 0!==r.maxZoom&&a.setMaxZoom(r.maxZoom),void 0!==r.minPitch&&a.setMinPitch(r.minPitch),void 0!==r.maxPitch&&a.setMaxPitch(r.maxPitch),void 0!==r.renderWorldCopies&&a.setRenderWorldCopies(r.renderWorldCopies),super(a,s,{bearingSnap:r.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new La,this._controls=[],this._mapId=t.a7(),this._contextLost=e=>{e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new t.l("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._setupPainter(),this.resize(),this._update(),this.fire(new t.l("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update();},this._interactive=r.interactive,this._maxTileCacheSize=r.maxTileCacheSize,this._maxTileCacheZoomLevels=r.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},r.canvasContextAttributes),this._trackResize=!0===r.trackResize,this._bearingSnap=r.bearingSnap,this._centerClampedToGround=r.centerClampedToGround,this._refreshExpiredTiles=!0===r.refreshExpiredTiles,this._fadeDuration=r.fadeDuration,this._crossSourceCollisions=!0===r.crossSourceCollisions,this._collectResourceTiming=!0===r.collectResourceTiming,this._locale=Object.assign(Object.assign({},Ua),r.locale),this._clickTolerance=r.clickTolerance,this._overridePixelRatio=r.pixelRatio,this._maxCanvasSize=r.maxCanvasSize,this.transformCameraUpdate=r.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===r.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=p.addThrottleControl((()=>this.isMoving())),this._requestManager=new m(r.transformRequest),"string"==typeof r.container){if(this._container=document.getElementById(r.container),!this._container)throw new Error(`Container '${r.container}' not found.`)}else {if(!(r.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=r.container;}if(r.maxBounds&&this.setMaxBounds(r.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0);})),this.once("idle",(()=>{this._idleTriggered=!0;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let e=!1;const t=Sr((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{e?t(i):e=!0;})),this._resizeObserver.observe(this._container);}this.handlers=new Ea(this,r),this._hash=r.hash&&new Er("string"==typeof r.hash&&r.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:r.center,elevation:r.elevation,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,roll:r.roll}),r.bounds&&(this.resize(),this.fitBounds(r.bounds,t.e({},r.fitBoundsOptions,{duration:0}))));const n="string"==typeof r.style||!("globe"===(null===(o=null===(i=r.style)||void 0===i?void 0:i.projection)||void 0===o?void 0:o.type));this.resize(null,n),this._localIdeographFontFamily=r.localIdeographFontFamily,this._validateStyle=r.validateStyle,r.style&&this.setStyle(r.style,{localIdeographFontFamily:r.localIdeographFontFamily}),r.attributionControl&&this.addControl(new Da("boolean"==typeof r.attributionControl?void 0:r.attributionControl)),r.maplibreLogo&&this.addControl(new Aa,r.logoPosition),this.on("style.load",(()=>{if(n||this._resizeTransform(),this.transform.unmodified){const e=t.Q(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.l(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.l(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.l("sourcedataabort",e));}));}_getMapId(){return this._mapId}setGlobalStateProperty(e,t){return this.style.setGlobalStateProperty(e,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(e,i){if(void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.k(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const o=e.onAdd(this);this._controls.push(e);const r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.k(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}coveringTiles(e){return ve(this.transform,e)}calculateCameraOptionsFromTo(e,t,i,o){return null==o&&this.terrain&&(o=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(e,t,i,o)}resize(e,i=!0){const[o,r]=this._containerDimensions(),a=this._getClampedPixelRatio(o,r);if(this._resizeCanvas(o,r,a),this.painter.resize(o,r,a),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const t=this._getClampedPixelRatio(o,r);this._resizeCanvas(o,r,t),this.painter.resize(o,r,t);}this._resizeTransform(i);const s=!this._moving;return s&&(this.stop(),this.fire(new t.l("movestart",e)).fire(new t.l("move",e))),this.fire(new t.l("resize",e)),s&&this.fire(new t.l("moveend",e)),this}_resizeTransform(e=!0){var t;const[i,o]=this._containerDimensions();this.transform.resize(i,o,e),null===(t=this._requestedCameraState)||void 0===t||t.resize(i,o,e);}_getClampedPixelRatio(e,t){const{0:i,1:o}=this._maxCanvasSize,r=this.getPixelRatio(),a=e*r,s=t*r;return Math.min(a>i?i/a:1,s>o?o/s:1)*r}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&void 0!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(G.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom)return this.transform.setMinZoom(e),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(e),this._update(),this.getZoom()>e&&this.setZoom(e),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.setMinPitch(e),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch)return this.transform.setMaxPitch(e),this._update(),this.getPitch()>e&&this.setPitch(e),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.S.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||void 0===e?void 0:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||void 0===e?void 0:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||void 0===e?void 0:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e))),s=0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[];s.length?o||(o=!0,i.call(this,new jr(e,this,r.originalEvent,{features:s}))):o=!1;};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:()=>{o=!1;}}}}if("mouseleave"===e||"mouseout"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e)));(0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[]).length?o=!0:o&&(o=!1,i.call(this,new jr(e,this,r.originalEvent)));},a=t=>{o&&(o=!1,i.call(this,new jr(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:a}}}{const o=e=>{const o=t.filter((e=>this.getLayer(e))),r=0!==o.length?this.queryRenderedFeatures(e.point,{layers:o}):[];r.length&&(e.features=r,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:o}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const o=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in r.delegates)this.off(e,r.delegates[e]);return void o.splice(e,1)}}}on(e,t,i){if(void 0===i)return super.on(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);this._saveDelegatedListener(e,r);for(const e in r.delegates)this.on(e,r.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,o,i);}}}once(e,t,i){if(void 0===i)return super.once(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);for(const t in r.delegates){const a=r.delegates[t];r.delegates[t]=(...t)=>{this._removeDelegatedListener(e,o,i),a(...t);};}this._saveDelegatedListener(e,r);for(const e in r.delegates)this.once(e,r.delegates[e]);return this}off(e,t,i){return void 0===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let o;const r=e instanceof t.P||Array.isArray(e),a=r?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(r?{}:e)||{},a instanceof t.P||"number"==typeof a[0])o=[t.P.convert(a)];else {const e=t.P.convert(a[0]),i=t.P.convert(a[1]);o=[e,new t.P(i.x,e.y),i,new t.P(e.x,i.y),e];}return this.style.queryRenderedFeatures(o,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return !1!==(i=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,o;if(t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const r=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new wi(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,r):this.style.loadJSON(e,t,r),this):(null===(o=null===(i=this.style)||void 0===i?void 0:i.projection)||void 0===o||o.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new wi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){if("string"==typeof e){const o=this._requestManager.transformRequest(e,"Style");t.j(o,new AbortController).then((e=>{this._updateDiff(e.data,i);})).catch((e=>{e&&this.fire(new t.k(e));}));}else "object"==typeof e&&this._updateDiff(e,i);}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(o){t.w(`Unable to perform style diff: ${o.message||o.error||o}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():t.w("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){const i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.k(new Error(`There is no source with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.sourceCaches[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const o=this.style._layers[i];"hillshade"===o.type&&o.source===e.source&&t.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality."),"color-relief"===o.type&&o.source===e.source&&t.w("You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");}this.terrain=new Ba(this.painter,i,e),this.painter.renderToTexture=new Na(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{var i;"style"===t.dataType?this.terrain.sourceCache.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),"image"===(null===(i=t.source)||void 0===i?void 0:i.type)?this.terrain.sourceCache.freeRtt():this.terrain.sourceCache.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.l("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||void 0===e?void 0:e.options)&&void 0!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.sourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}}return !0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}setSourceTileLodParams(e,t,i){if(i){const o=this.getSource(i);if(!o)throw new Error(`There is no source with ID "${i}", cannot set LOD parameters`);o.calculateTileZoom=me(Math.max(1,e),Math.max(1,t));}else for(const i in this.style.sourceCaches)this.style.sourceCaches[i].getSource().calculateTileZoom=me(Math.max(1,e),Math.max(1,t));return this._update(!0),this}refreshTiles(e,i){const o=this.style.sourceCaches[e];if(!o)throw new Error(`There is no source cache with ID "${e}", cannot refresh tile`);void 0===i?o.reload(!0):o.refreshTiles(i.map((e=>new t.a4(e.z,e.x,e.y))));}addImage(e,i,o={}){const{pixelRatio:r=1,sdf:a=!1,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u}=o;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.b(i))){if(void 0===i.width||void 0===i.height)return this.fire(new t.k(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:o,height:s,data:d}=i,_=i;return this.style.addImage(e,{data:new t.R({width:o,height:s},new Uint8Array(d)),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:o,height:d,data:_}=s.getImageData(i);this.style.addImage(e,{data:new t.R({width:o,height:d},_),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0});}}updateImage(e,i){const o=this.style.getImage(e);if(!o)return this.fire(new t.k(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const r=i instanceof HTMLImageElement||t.b(i)?s.getImageData(i):i,{width:a,height:n,data:l}=r;if(void 0===a||void 0===n)return this.fire(new t.k(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(a!==o.data.width||n!==o.data.height)return this.fire(new t.k(new Error("The width and height of the updated image must be that same as the previous version of the image")));const c=!(i instanceof HTMLImageElement||t.b(i));return o.data.replace(l,c),this.style.updateImage(e,o),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.k(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(e);}loadImage(e){return p.getImage(this._requestManager.transformRequest(e,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(!0)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,o={}){return this.style.setPaintProperty(e,t,i,o),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,o={}){return this.style.setLayoutProperty(e,t,i,o),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(!0);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=n.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=n.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),o=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],o);const r=this._controlContainer=n.create("div","maplibregl-control-container",e),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{a[e]=n.create("div",`maplibregl-ctrl-${e} `,r);})),this._container.addEventListener("scroll",this._onMapScroll,!1);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0});let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:!0});let i=null;if(i=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e),!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new Mr(i,this.transform),l.testSupport(i);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.l("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){var i,o,r,a,n;const l=this._idleTriggered?this._fadeDuration:0,c=(null===(i=this.style.projection)||void 0===i?void 0:i.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let h=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,i=s.now();this.style.zoomHistory.update(e,i);const o=new t.F(e,{now:i,fadeDuration:l,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),r=o.crossFadingFactor();1===r&&r===this._crossFadingFactor||(h=!0,this._crossFadingFactor=r),this.style.update(o);}const u=(null===(o=this.style.projection)||void 0===o?void 0:o.transitionState)>0!==c;null===(r=this.style.projection)||void 0===r||r.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(a=this.style.projection)||void 0===a?void 0:a.transitionState,null===(n=this.style.projection)||void 0===n?void 0:n.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||u)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,l,this._crossSourceCollisions,u),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:l,showPadding:this.showPadding}),this.fire(new t.l("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,t.cw.mark(t.cx.load),this.fire(new t.l("load"))),this.style&&(this.style.hasTransitions()||h)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const d=this._sourcesDirty||this._styleDirty||this._placementDirty;return d||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.l("idle")),!this._loaded||this._fullyLoaded||d||(this._fullyLoaded=!0,t.cw.mark(t.cx.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),p.removeThrottleControl(this._imageQueueHandle),null===(e=this._resizeObserver)||void 0===e||e.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?void 0:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),n.remove(this._canvasContainer),n.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),t.cw.clearMetrics(),this._removed=!0,this.fire(new t.l("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,s.frame(this._frameRequest,(e=>{t.cw.frame(e),this._frameRequest=null;try{this._render(e);}catch(e){if(!t.cy(e)&&!function(e){return e.message===qo}(e))throw e}}),(()=>{})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return Za}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}},e.MapMouseEvent=jr,e.MapTouchEvent=Nr,e.MapWheelEvent=Ur,e.Marker=Ka,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.e({},Va,e),this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=n.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new $a(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){n.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=n.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.E{constructor(e){super(),this._updateOpacity=()=>{void 0!==this.options.locationOccludedOpacity&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:"");},this.remove=()=>(this._content&&n.remove(this._content),this._container&&(n.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new t.l("close"))),this),this._onMouseUp=e=>{this._update(e.point);},this._onMouseMove=e=>{this._update(e.point);},this._onDrag=e=>{this._update(e.point);},this._update=e=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=n.create("div","maplibregl-popup",this._map.getContainer()),this._tip=n.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer");}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),this._trackPointer&&!e)return;const t=this._flatPos=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&e?e:this._map.transform.locationToScreenPoint(this._lngLat));let i=this.options.anchor;const o=as(this.options.offset);if(!i){const e=this._container.offsetWidth,r=this._container.offsetHeight;let a;a=t.y+o.bottom.ythis._map.transform.height-r?["bottom"]:[],t.xthis._map.transform.width-e/2&&a.push("right"),i=0===a.length?"bottom":a.join("-");}let r=t.add(o[i]);this.options.subpixelPositioning||(r=r.round()),n.setTransform(this._container,`${Ha[i]} translate(${r.x}px,${r.y}px)`),Xa(this._container,i,"popup"),this._updateOpacity();},this._onClose=()=>{this.remove();},this.options=t.e(Object.create(os),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.l("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let o;for(i.innerHTML=e;o=i.firstChild,o;)t.appendChild(o);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||void 0===e?void 0:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=n.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}_createCloseButton(){this.options.closeButton&&(this._closeButton=n.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(rs);e&&e.focus();}},e.RasterDEMTileSource=W,e.RasterTileSource=q,e.ScaleControl=class{constructor(e){this._onMove=()=>{ts(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,ts(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},es),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){n.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;}},e.ScrollZoomHandler=va,e.Style=wi,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=n.create("button","maplibregl-ctrl-terrain",this._container),n.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){n.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0;}},e.TwoFingersTouchPitchHandler=da,e.TwoFingersTouchRotateHandler=ha,e.TwoFingersTouchZoomHandler=la,e.TwoFingersTouchZoomRotateHandler=Pa,e.VectorTileSource=$,e.VideoSource=K,e.addSourceType=(e,i)=>t._(void 0,void 0,void 0,(function*(){if(J(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{Q[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=A;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(R),A=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},e.createTileMesh=Xt,e.getMaxParallelImageRequests=function(){return t.a.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},e.getVersion=function(){return ss},e.getWorkerCount=function(){return z.workerCount},e.getWorkerUrl=function(){return t.a.WORKER_URL},e.importScriptInWorkers=function(e){return B().broadcast("IS",e)},e.prewarm=function(){k().acquire(R);},e.setMaxParallelImageRequests=function(e){t.a.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setRTLTextPlugin=function(e,t){return oe().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){z.workerCount=e;},e.setWorkerUrl=function(e){t.a.WORKER_URL=e;};})); + +// +// Our custom intro provides a specialized "define()" function, called by the +// AMD modules below, that sets up the worker blob URL and then executes the +// main module, storing its exported value as 'maplibregl' + + +var maplibregl$1 = maplibregl; + +return maplibregl$1; + +})); +//# sourceMappingURL=maplibre-gl.js.map diff --git a/docs/articles/getting-started_files/maplibregl-binding-0.3.1.9000/maplibregl.js b/docs/articles/getting-started_files/maplibregl-binding-0.3.1.9000/maplibregl.js new file mode 100644 index 0000000..f5481b0 --- /dev/null +++ b/docs/articles/getting-started_files/maplibregl-binding-0.3.1.9000/maplibregl.js @@ -0,0 +1,4285 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/getting-started_files/maplibregl-binding-0.3.2/maplibregl.js b/docs/articles/getting-started_files/maplibregl-binding-0.3.2/maplibregl.js new file mode 100644 index 0000000..f5481b0 --- /dev/null +++ b/docs/articles/getting-started_files/maplibregl-binding-0.3.2/maplibregl.js @@ -0,0 +1,4285 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/getting-started_files/maplibregl-binding-0.3.9.9000/maplibregl.js b/docs/articles/getting-started_files/maplibregl-binding-0.3.9.9000/maplibregl.js new file mode 100644 index 0000000..c8312af --- /dev/null +++ b/docs/articles/getting-started_files/maplibregl-binding-0.3.9.9000/maplibregl.js @@ -0,0 +1,4337 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/getting-started_files/maplibregl-binding-0.4.0.9000/maplibregl.js b/docs/articles/getting-started_files/maplibregl-binding-0.4.0.9000/maplibregl.js new file mode 100644 index 0000000..8558cc4 --- /dev/null +++ b/docs/articles/getting-started_files/maplibregl-binding-0.4.0.9000/maplibregl.js @@ -0,0 +1,4506 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/getting-started_files/maplibregl-binding-0.4.0/maplibregl.js b/docs/articles/getting-started_files/maplibregl-binding-0.4.0/maplibregl.js new file mode 100644 index 0000000..c8312af --- /dev/null +++ b/docs/articles/getting-started_files/maplibregl-binding-0.4.0/maplibregl.js @@ -0,0 +1,4337 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/getting-started_files/maplibregl-binding-0.4.1/maplibregl.js b/docs/articles/getting-started_files/maplibregl-binding-0.4.1/maplibregl.js new file mode 100644 index 0000000..5937d02 --- /dev/null +++ b/docs/articles/getting-started_files/maplibregl-binding-0.4.1/maplibregl.js @@ -0,0 +1,5048 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + const result = originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + return result; + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse( + this.getAttribute("data-layer-ids"), + ); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } + } + }); +} diff --git a/docs/articles/getting-started_files/maptiler-geocoding-control-2.1.7/LICENSE.txt b/docs/articles/getting-started_files/maptiler-geocoding-control-2.1.7/LICENSE.txt new file mode 100644 index 0000000..624d1f1 --- /dev/null +++ b/docs/articles/getting-started_files/maptiler-geocoding-control-2.1.7/LICENSE.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2023, MapTiler +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/articles/getting-started_files/maptiler-geocoding-control-2.1.7/maplibregl.umd.js b/docs/articles/getting-started_files/maptiler-geocoding-control-2.1.7/maplibregl.umd.js new file mode 100644 index 0000000..0fe7116 --- /dev/null +++ b/docs/articles/getting-started_files/maptiler-geocoding-control-2.1.7/maplibregl.umd.js @@ -0,0 +1,14 @@ +(function(j,ee){typeof exports=="object"&&typeof module<"u"?ee(exports,require("maplibre-gl")):typeof define=="function"&&define.amd?define(["exports","maplibre-gl"],ee):(j=typeof globalThis<"u"?globalThis:j||self,ee(j.maplibreglMaptilerGeocoder={},j.maplibregl))})(this,function(j,ee){"use strict";var Ws=Object.defineProperty;var bn=j=>{throw TypeError(j)};var Gs=(j,ee,me)=>ee in j?Ws(j,ee,{enumerable:!0,configurable:!0,writable:!0,value:me}):j[ee]=me;var A=(j,ee,me)=>Gs(j,typeof ee!="symbol"?ee+"":ee,me),wn=(j,ee,me)=>ee.has(j)||bn("Cannot "+me);var ue=(j,ee,me)=>(wn(j,ee,"read from private field"),me?me.call(j):ee.get(j)),Vt=(j,ee,me)=>ee.has(j)?bn("Cannot add the same private member more than once"):ee instanceof WeakSet?ee.add(j):ee.set(j,me),kt=(j,ee,me,dt)=>(wn(j,ee,"write to private field"),dt?dt.call(j,me):ee.set(j,me),me);var fn,cn;function me(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const dt=me(ee);function ne(){}function Ln(i,e){for(const t in e)i[t]=e[t];return i}function yi(i){return i()}function vi(){return Object.create(null)}function Ue(i){i.forEach(yi)}function bi(i){return typeof i=="function"}function Ke(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}let Rt;function ye(i,e){return i===e?!0:(Rt||(Rt=document.createElement("a")),Rt.href=e,i===Rt.href)}function _n(i){return Object.keys(i).length===0}function Sn(i,e,t,n){if(i){const r=wi(i,e,t,n);return i[0](r)}}function wi(i,e,t,n){return i[1]&&n?Ln(t.ctx.slice(),i[1](n(e))):t.ctx}function xn(i,e,t,n){return i[2],e.dirty}function Tn(i,e,t,n,r,u){if(r){const a=wi(e,t,n,u);i.p(a,r)}}function Mn(i){if(i.ctx.length>32){const e=[],t=i.ctx.length/32;for(let n=0;ni.removeEventListener(e,t,n)}function Nn(i){return function(e){return e.preventDefault(),i.call(this,e)}}function S(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function kn(i){return Array.from(i.childNodes)}function gt(i,e){e=""+e,i.data!==e&&(i.data=e)}function Ei(i,e){i.value=e??""}function Ie(i,e,t){i.classList.toggle(e,!!t)}function On(i,e,{bubbles:t=!1,cancelable:n=!1}={}){return new CustomEvent(i,{detail:e,bubbles:t,cancelable:n})}let mt;function pt(i){mt=i}function Li(){if(!mt)throw new Error("Function called outside component initialization");return mt}function Rn(i){Li().$$.on_destroy.push(i)}function _i(){const i=Li();return(e,t,{cancelable:n=!1}={})=>{const r=i.$$.callbacks[e];if(r){const u=On(e,t,{cancelable:n});return r.slice().forEach(a=>{a.call(i,u)}),!u.defaultPrevented}return!0}}function Pn(i,e){const t=i.$$.callbacks[e.type];t&&t.slice().forEach(n=>n.call(this,e))}const ut=[],Yt=[];let at=[];const Si=[],In=Promise.resolve();let Qt=!1;function An(){Qt||(Qt=!0,In.then(xi))}function Xt(i){at.push(i)}const Jt=new Set;let ft=0;function xi(){if(ft!==0)return;const i=mt;do{try{for(;fti.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),at=e}const It=new Set;let nt;function yt(){nt={r:0,c:[],p:nt}}function vt(){nt.r||Ue(nt.c),nt=nt.p}function re(i,e){i&&i.i&&(It.delete(i),i.i(e))}function fe(i,e,t,n){if(i&&i.o){if(It.has(i))return;It.add(i),nt.c.push(()=>{It.delete(i),n&&(t&&i.d(1),n())}),i.o(e)}else n&&n()}function Ti(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function Gn(i,e){fe(i,1,1,()=>{e.delete(i.key)})}function Dn(i,e,t,n,r,u,a,o,g,c,E,_){let M=i.length,R=u.length,k=M;const I={};for(;k--;)I[i[k].key]=k;const C=[],O=new Map,x=new Map,N=[];for(k=R;k--;){const W=_(r,u,k),s=t(W);let l=a.get(s);l?N.push(()=>l.p(W,e)):(l=c(s,W),l.c()),O.set(s,C[k]=l),s in I&&x.set(s,Math.abs(k-I[s]))}const P=new Set,B=new Set;function z(W){re(W,1),W.m(o,E),a.set(W.key,W),E=W.first,R--}for(;M&&R;){const W=C[R-1],s=i[M-1],l=W.key,f=s.key;W===s?(E=W.first,M--,R--):O.has(f)?!a.has(l)||P.has(l)?z(W):B.has(f)?M--:x.get(l)>x.get(f)?(B.add(l),z(W)):(P.add(f),M--):(g(s,a),M--)}for(;M--;){const W=i[M];O.has(W.key)||g(W,a)}for(;R;)z(C[R-1]);return Ue(N),C}function Qe(i){i&&i.c()}function qe(i,e,t){const{fragment:n,after_update:r}=i.$$;n&&n.m(e,t),Xt(()=>{const u=i.$$.on_mount.map(yi).filter(bi);i.$$.on_destroy?i.$$.on_destroy.push(...u):Ue(u),i.$$.on_mount=[]}),r.forEach(Xt)}function Fe(i,e){const t=i.$$;t.fragment!==null&&(Wn(t.after_update),Ue(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function zn(i,e){i.$$.dirty[0]===-1&&(ut.push(i),An(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<{const k=R.length?R[0]:M;return c.ctx&&r(c.ctx[_],c.ctx[_]=k)&&(!c.skip_bound&&c.bound[_]&&c.bound[_](k),E&&zn(i,_)),M}):[],c.update(),E=!0,Ue(c.before_update),c.fragment=n?n(c.ctx):!1,e.target){if(e.hydrate){const _=kn(e.target);c.fragment&&c.fragment.l(_),_.forEach($)}else c.fragment&&c.fragment.c();e.intro&&re(i.$$.fragment),qe(i,e.target,e.anchor),xi()}pt(g)}class Je{constructor(){A(this,"$$");A(this,"$$set")}$destroy(){Fe(this,1),this.$destroy=ne}$on(e,t){if(!bi(t))return ne;const n=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return n.push(t),()=>{const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}$set(e){this.$$set&&!_n(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Un="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Un);function qn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M13.12.706a.982.982 0 0 0-1.391 0L6.907 5.517 2.087.696a.982.982 0 1 0-1.391 1.39l4.821 4.821L.696 11.73a.982.982 0 1 0 1.39 1.39l4.821-4.821 4.822 4.821a.982.982 0 1 0 1.39-1.39L8.298 6.908l4.821-4.822a.988.988 0 0 0 0-1.38Z"),S(e,"viewBox","0 0 14 14"),S(e,"width","13"),S(e,"height","13"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Mi extends Je{constructor(e){super(),Xe(this,e,null,qn,Ke,{})}}function Fn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M15 0C6.705 0 0 6.705 0 15C0 23.295 6.705 30 15 30C23.295 30 30 23.295 30 15C30 6.705 23.295 0 15 0ZM22.5 20.385L20.385 22.5L15 17.115L9.615 22.5L7.5 20.385L12.885 15L7.5 9.615L9.615 7.5L15 12.885L20.385 7.5L22.5 9.615L17.115 15L22.5 20.385Z"),S(e,"viewBox","0 0 30 30"),S(e,"fill","none"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"class","svelte-d2loi5")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Ci extends Je{constructor(e){super(),Xe(this,e,null,Fn,Ke,{})}}function jn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"area.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"area.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Zn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"reverse.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"reverse.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Hn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"poi.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"poi.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Vn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"postal_code.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"postal_code.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Kn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"street.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"street.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Yn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"road.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"road.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Qn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"housenumber.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"housenumber.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Xn(i){let e,t,n,r;return{c(){e=Y("img"),ye(e.src,t=i[5])||S(e,"src",t),S(e,"alt",i[4]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(u,a){te(u,e,a),n||(r=he(e,"error",i[14]),n=!0)},p(u,a){a&32&&!ye(e.src,t=u[5])&&S(e,"src",t),a&16&&S(e,"alt",u[4]),a&128&&S(e,"title",u[7])},d(u){u&&$(e),n=!1,r()}}}function Jn(i){let e,t;return{c(){e=Y("div"),S(e,"class","sprite-icon svelte-w9y5n9"),S(e,"style",t=` + width: ${i[6].width/xe}px; + height: ${i[6].height/xe}px; + background-image: url(${i[3]}sprite${$t}.png); + background-position: -${i[6].x/xe}px -${i[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `),S(e,"title",i[7])},m(n,r){te(n,e,r)},p(n,r){r&72&&t!==(t=` + width: ${n[6].width/xe}px; + height: ${n[6].height/xe}px; + background-image: url(${n[3]}sprite${$t}.png); + background-position: -${n[6].x/xe}px -${n[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `)&&S(e,"style",t),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Ni(i){let e,t;return{c(){e=Y("span"),t=Ye(i[7]),S(e,"class","secondary svelte-w9y5n9")},m(n,r){te(n,e,r),V(e,t)},p(n,r){r&128&>(t,n[7])},d(n){n&&$(e)}}}function $n(i){let e,t,n,r,u,a,o,g,c,E=(i[8]?i[0].place_name:i[0].place_name.replace(/,.*/,""))+"",_,M,R=i[2]==="always"||i[2]!=="never"&&!i[0].address&&!i[0].id.startsWith("road.")&&!i[0].id.startsWith("address.")&&!i[0].id.startsWith("postal_code.")&&(!i[0].id.startsWith("poi.")||!i[5])&&!i[8],k,I,C=(i[8]?"":i[0].place_name.replace(/[^,]*,?\s*/,""))+"",O,x,N,P,B,z;function W(m,h){return h&1&&(t=null),h&1&&(n=null),h&1&&(r=null),h&1&&(u=null),Oe&&m[6]?Jn:m[5]?Xn:m[0].address?Qn:(t==null&&(t=!!m[0].id.startsWith("road.")),t?Yn:(n==null&&(n=!!m[0].id.startsWith("address.")),n?Kn:(r==null&&(r=!!m[0].id.startsWith("postal_code.")),r?Vn:(u==null&&(u=!!m[0].id.startsWith("poi.")),u?Hn:m[8]?Zn:jn))))}let s=W(i,-1),l=s(i),f=R&&Ni(i);return{c(){e=Y("li"),l.c(),a=we(),o=Y("span"),g=Y("span"),c=Y("span"),_=Ye(E),M=we(),f&&f.c(),k=we(),I=Y("span"),O=Ye(C),S(c,"class","primary svelte-w9y5n9"),S(g,"class","svelte-w9y5n9"),S(I,"class","line2 svelte-w9y5n9"),S(o,"class","texts svelte-w9y5n9"),S(e,"tabindex","-1"),S(e,"role","option"),S(e,"aria-selected",x=i[1]==="selected"),S(e,"aria-checked",N=i[1]==="picked"),S(e,"class",P=Pt(i[1])+" svelte-w9y5n9")},m(m,h){te(m,e,h),l.m(e,null),V(e,a),V(e,o),V(o,g),V(g,c),V(c,_),V(g,M),f&&f.m(g,null),V(o,k),V(o,I),V(I,O),B||(z=[he(e,"mouseenter",i[13]),he(e,"focus",i[15]),he(e,"click",i[16])],B=!0)},p(m,[h]){s===(s=W(m,h))&&l?l.p(m,h):(l.d(1),l=s(m),l&&(l.c(),l.m(e,a))),h&257&&E!==(E=(m[8]?m[0].place_name:m[0].place_name.replace(/,.*/,""))+"")&>(_,E),h&293&&(R=m[2]==="always"||m[2]!=="never"&&!m[0].address&&!m[0].id.startsWith("road.")&&!m[0].id.startsWith("address.")&&!m[0].id.startsWith("postal_code.")&&(!m[0].id.startsWith("poi.")||!m[5])&&!m[8]),R?f?f.p(m,h):(f=Ni(m),f.c(),f.m(g,null)):f&&(f.d(1),f=null),h&257&&C!==(C=(m[8]?"":m[0].place_name.replace(/[^,]*,?\s*/,""))+"")&>(O,C),h&2&&x!==(x=m[1]==="selected")&&S(e,"aria-selected",x),h&2&&N!==(N=m[1]==="picked")&&S(e,"aria-checked",N),h&2&&P!==(P=Pt(m[1])+" svelte-w9y5n9")&&S(e,"class",P)},i:ne,o:ne,d(m){m&&$(e),l.d(),f&&f.d(),B=!1,Ue(z)}}}const ki=typeof devicePixelRatio>"u"?1:devicePixelRatio>1.25,$t=ki?"@2x":"",xe=ki?2:1;let Oe,At;function er(i,e,t){let n,r,u,{feature:a}=e,{style:o="default"}=e,{showPlaceType:g}=e,{missingIconsCache:c}=e,{iconsBaseUrl:E}=e;const _=_i();let M,R,k,I;function C(){At??(At=fetch(`${E}sprite${$t}.json`).then(s=>s.json()).then(s=>{Oe=s}).catch(()=>{Oe=null}))}function O(){R&&c.add(R),x()}function x(){Oe!==void 0?N():(C(),At==null||At.then(N))}function N(){do{if(I--,t(4,M=n==null?void 0:n[I]),t(6,k=M?Oe==null?void 0:Oe.icons[M]:void 0),k)break;t(5,R=M?E+M.replace(/ /g,"_")+".svg":void 0)}while(I>-1&&(!R||c.has(R)))}function P(s){Pn.call(this,i,s)}const B=()=>O(),z=()=>_("select",void 0),W=s=>{document.activeElement!==s.target&&_("select",void 0)};return i.$$set=s=>{"feature"in s&&t(0,a=s.feature),"style"in s&&t(1,o=s.style),"showPlaceType"in s&&t(2,g=s.showPlaceType),"missingIconsCache"in s&&t(11,c=s.missingIconsCache),"iconsBaseUrl"in s&&t(3,E=s.iconsBaseUrl)},i.$$.update=()=>{var s,l,f,m,h;i.$$.dirty&1&&t(12,n=(s=a.properties)==null?void 0:s.categories),i.$$.dirty&1&&t(8,r=a.place_type[0]==="reverse"),i.$$.dirty&1&&t(7,u=((f=(l=a.properties)==null?void 0:l.categories)==null?void 0:f.join(", "))??((h=(m=a.properties)==null?void 0:m.place_type_name)==null?void 0:h[0])??a.place_type[0]),i.$$.dirty&4096&&(I=(n==null?void 0:n.length)??0,x())},[a,o,g,E,M,R,k,u,r,_,O,c,n,P,B,z,W]}class tr extends Je{constructor(e){super(),Xe(this,e,er,$n,Ke,{feature:0,style:1,showPlaceType:2,missingIconsCache:11,iconsBaseUrl:3})}}function ir(i){let e;return{c(){e=Y("div"),e.innerHTML='',S(e,"class","svelte-1ocfouu")},m(t,n){te(t,e,n)},p:ne,i:ne,o:ne,d(t){t&&$(e)}}}class nr extends Je{constructor(e){super(),Xe(this,e,null,ir,Ke,{})}}function rr(i){let e,t,n;return{c(){e=ke("svg"),t=ke("path"),S(t,"stroke-width","4"),S(t,"d","M 5,33.103579 C 5,17.607779 18.457,5 35,5 C 51.543,5 65,17.607779 65,33.103579 C 65,56.388679 40.4668,76.048179 36.6112,79.137779 C 36.3714,79.329879 36.2116,79.457979 36.1427,79.518879 C 35.8203,79.800879 35.4102,79.942779 35,79.942779 C 34.5899,79.942779 34.1797,79.800879 33.8575,79.518879 C 33.7886,79.457979 33.6289,79.330079 33.3893,79.138079 C 29.5346,76.049279 5,56.389379 5,33.103579 Z M 35.0001,49.386379 C 43.1917,49.386379 49.8323,42.646079 49.8323,34.331379 C 49.8323,26.016779 43.1917,19.276479 35.0001,19.276479 C 26.8085,19.276479 20.1679,26.016779 20.1679,34.331379 C 20.1679,42.646079 26.8085,49.386379 35.0001,49.386379 Z"),S(t,"class","svelte-gzo3ar"),S(e,"width",n=i[0]==="list"?20:void 0),S(e,"viewBox","0 0 70 85"),S(e,"fill","none"),S(e,"class","svelte-gzo3ar"),Ie(e,"in-map",i[0]!=="list"),Ie(e,"list-icon",i[0]==="list")},m(r,u){te(r,e,u),V(e,t)},p(r,[u]){u&1&&n!==(n=r[0]==="list"?20:void 0)&&S(e,"width",n),u&1&&Ie(e,"in-map",r[0]!=="list"),u&1&&Ie(e,"list-icon",r[0]==="list")},i:ne,o:ne,d(r){r&&$(e)}}}function sr(i,e,t){let{displayIn:n}=e;return i.$$set=r=>{"displayIn"in r&&t(0,n=r.displayIn)},[n]}class or extends Je{constructor(e){super(),Xe(this,e,sr,rr,Ke,{displayIn:0})}}function lr(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M30.003-26.765C13.46-26.765 0-14.158 0 1.337c0 23.286 24.535 42.952 28.39 46.04.24.192.402.316.471.376.323.282.732.424 1.142.424.41 0 .82-.142 1.142-.424.068-.06.231-.183.471-.376 3.856-3.09 28.39-22.754 28.39-46.04 0-15.495-13.46-28.102-30.003-28.102Zm1.757 12.469c4.38 0 7.858 1.052 10.431 3.158 2.595 2.105 3.89 4.913 3.89 8.422 0 2.34-.53 4.362-1.593 6.063-1.063 1.702-3.086 3.616-6.063 5.742-2.042 1.51-3.337 2.659-3.89 3.446-.532.787-.8 1.82-.8 3.096v1.914h-8.449V15.18c0-2.041.434-3.815 1.306-5.325.872-1.51 2.467-3.118 4.785-4.82 2.233-1.594 3.7-2.89 4.402-3.889a5.582 5.582 0 0 0 1.087-3.35c0-1.382-.51-2.435-1.531-3.158-1.02-.723-2.45-1.087-4.28-1.087-3.19 0-6.826 1.047-10.91 3.131l-3.472-6.986c4.742-2.659 9.77-3.992 15.087-3.992Zm-1.88 37.324c1.765 0 3.124.472 4.08 1.408.98.936 1.47 2.276 1.47 4.02 0 1.68-.49 3.007-1.47 3.985-.977.957-2.336 1.435-4.08 1.435-1.787 0-3.171-.465-4.15-1.4-.978-.958-1.47-2.298-1.47-4.02 0-1.787.48-3.14 1.436-4.054.957-.915 2.355-1.374 4.184-1.374Z"),S(e,"viewBox","0 0 60.006 21.412"),S(e,"width","14"),S(e,"height","20"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class ur extends Je{constructor(e){super(),Xe(this,e,null,lr,Ke,{})}}function ar(i){let e,t,n;return{c(){e=ke("svg"),t=ke("circle"),n=ke("path"),S(t,"cx","4.789"),S(t,"cy","4.787"),S(t,"r","3.85"),S(t,"class","svelte-1aq105l"),S(n,"d","M12.063 12.063 7.635 7.635"),S(n,"class","svelte-1aq105l"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"width","13"),S(e,"height","13"),S(e,"viewBox","0 0 13 13"),S(e,"class","svelte-1aq105l")},m(r,u){te(r,e,u),V(e,t),V(e,n)},p:ne,i:ne,o:ne,d(r){r&&$(e)}}}class fr extends Je{constructor(e){super(),Xe(this,e,null,ar,Ke,{})}}function cr(i,e,t){const n=e[1],r=e[0],u=n-r;return i===n&&t?i:((i-r)%u+u)%u+r}function Bt(i){const e=[...i];return e[2]Math.abs((e[0]-360+e[2])/2)?e[0]-=360:e[2]+=360),e}let bt;async function hr(i,e,t){const n=i==null?void 0:i.getCenterAndZoom();for(const r of e??[])if(!(n&&(r.minZoom!=null&&r.minZoom>n[0]||r.maxZoom!=null&&r.maxZoomDate.now()){if(!bt.coords)break e;return bt.coords}let u;try{return u=await new Promise((a,o)=>{t.signal.addEventListener("abort",()=>{o(Error("aborted"))}),navigator.geolocation.getCurrentPosition(g=>{a([g.coords.longitude,g.coords.latitude].map(c=>c.toFixed(6)).join(","))},g=>{o(g)},r)}),u}catch{}finally{r.cachedLocationExpiry&&(bt={time:Date.now(),coords:u})}if(t.signal.aborted)return}if(r.type==="server-geolocation")return"ip";if(n&&r.type==="map-center")return n[1].toFixed(6)+","+n[2].toFixed(6)}}const dr=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(EAST|WEST|[EW])?$/i,Oi=/^([+-]?[0-8]?[0-9])\s+([0-5]?[0-9]\.\d{3,})[\s,]{1,}([+-]?[0-1]?[0-9]?[0-9])\s+([0-5]?[0-9]\.\d{3,})$/,Ri=/^(NORTH|SOUTH|[NS])?[\s]*([+-]?[0-8]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(NORTH|SOUTH|[NS])?[\s]*[,/;]?[\s]*(EAST|WEST|[EW])?[\s]*([+-]?[0-1]?[0-9]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(EAST|WEST|[EW])?$/i,Pi=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(EAST|WEST|[EW])?$/i,Ii=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)\s*(EAST|WEST|[EW])?$/i,Ai=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|’’|´´|["″”\.])?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|´´|’’|["″”\.])?\s*(EAST|WEST|[EW])?$/i;function gr(i){if(!["DMS","DM","DD"].includes(i))throw new Error("invalid format specified");if(this.decimalCoordinates&&this.decimalCoordinates.trim()){const e=this.decimalCoordinates.split(",").map(R=>Number(R.trim())),t=Number(e[0]),n=Number(e[1]),r=Math.abs(t),u=Math.abs(n),a=t>0?"N":"S",o=n>0?"E":"W";let g;i=="DD"&&(g=`${r}° ${a}, ${u}° ${o}`);const c=Math.floor(r),E=Math.floor(u),_=(r-c)*60,M=(u-E)*60;if(i=="DM"){let R=Bi(_,3).toFixed(3).padStart(6,"0"),k=Bi(M,3).toFixed(3).padStart(6,"0");R.endsWith(".000")&&k.endsWith(".000")&&(R=R.replace(/\.000$/,""),k=k.replace(/\.000$/,"")),g=`${c}° ${R}' ${a}, ${E}° ${k}' ${o}`}if(i=="DMS"){const R=Math.floor(_),k=Math.floor(M);let I=((_-R)*60).toFixed(1).padStart(4,"0"),C=((M-k)*60).toFixed(1).padStart(4,"0");const O=R.toString().padStart(2,"0"),x=k.toString().padStart(2,"0");I.endsWith(".0")&&C.endsWith(".0")&&(I=I.replace(/\.0$/,""),C=C.replace(/\.0$/,"")),g=`${c}° ${O}' ${I}" ${a}, ${E}° ${x}' ${C}" ${o}`}return g}else throw new Error("no decimal coordinates to convert")}function Bi(i,e){const t=Math.pow(10,e);return Math.round((i+Number.EPSILON)*t)/t}function ei(i,e){e||(e=5),i=i.replace(/\s+/g," ").trim();let t=null,n=null,r="",u="",a=null,o=[],g=!1;if(dr.test(i))throw new Error("invalid coordinate value");if(Oi.test(i))if(o=Oi.exec(i),g=wt(o),g)t=Math.abs(o[1])+o[2]/60,Number(o[1])<0&&(t*=-1),n=Math.abs(o[3])+o[4]/60,Number(o[3])<0&&(n*=-1),a="DM";else throw new Error("invalid coordinate format");else if(Ri.test(i))if(o=Ri.exec(i),g=wt(o),g){if(t=o[2],n=o[6],t.includes(",")&&(t=t.replace(",",".")),n.includes(",")&&(n=n.replace(",",".")),a="DD",Number(Math.round(t))==Number(t))throw new Error("integer only coordinate provided");if(Number(Math.round(n))==Number(n))throw new Error("integer only coordinate provided");o[1]?(r=o[1],u=o[5]):o[4]&&(r=o[4],u=o[8])}else throw new Error("invalid decimal coordinate format");else if(Pi.test(i))if(o=Pi.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[9])),o[11]&&(n+=o[11]/60),o[13]&&(n+=o[13].replace(",",".")/3600),parseInt(o[9])<0&&(n=-1*n),o[1]?(r=o[1],u=o[8]):o[7]&&(r=o[7],u=o[14]);else throw new Error("invalid DMS coordinates format");else if(Ii.test(i))if(o=Ii.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6]/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12]/60),o[14]&&(n+=o[14]/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid DMS coordinates format");else if(Ai.test(i)){if(o=Ai.exec(i),g=wt(o),o.filter(c=>c).length<=5)throw new Error("invalid coordinates format");if(g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4].replace(",",".")/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12].replace(",",".")/60),o[14]&&(n+=o[14].replace(",",".")/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid coordinates format")}if(g){if(Math.abs(n)>=180)throw new Error("invalid longitude value");if(Math.abs(t)>=90)throw new Error("invalid latitude value");if(r&&!u||!r&&u)throw new Error("invalid coordinates value");if(r&&r==u)throw new Error("invalid coordinates format");t.toString().includes(",")&&(t=t.replace(",",".")),n.toString().includes(",")&&(n=n.replace(",","."));let c=/S|SOUTH/i;c.test(r)&&t>0&&(t=-1*t),c=/W|WEST/i,c.test(u)&&n>0&&(n=-1*n);const E=o[0].trim();let _,M;const R=/[,/;\u0020]/g,k=E.match(R);if(k==null){const O=Math.floor(i.length/2);_=E.substring(0,O).trim(),M=E.substring(O).trim()}else{let O;k.length%2==1?O=Math.floor(k.length/2):O=k.length/2-1;let x=0;if(O==0)x=E.indexOf(k[0]),_=E.substring(0,x).trim(),M=E.substring(x+1).trim();else{let N=0,P=0;for(;N<=O;)x=E.indexOf(k[N],P),P=x+1,N++;_=E.substring(0,x).trim(),M=E.substring(x+1).trim()}}const I=_.split(".");if(I.length==2&&I[1]==0&&I[1].length!=2)throw new Error("invalid coordinates format");const C=M.split(".");if(C.length==2&&C[1]==0&&C[1].length!=2)throw new Error("invalid coordinates format");if(/^\d+$/.test(_)||/^\d+$/.test(M))throw new Error("degree only coordinate/s provided");return t=Number(Number(t).toFixed(e)),n=Number(Number(n).toFixed(e)),Object.freeze({verbatimCoordinates:E,verbatimLatitude:_,verbatimLongitude:M,decimalLatitude:t,decimalLongitude:n,decimalCoordinates:`${t},${n}`,originalFormat:a,closeEnough:mr,toCoordinateFormat:gr})}else throw new Error("coordinates pattern match failed")}function wt(i){if(!isNaN(i[0]))return!1;const e=[...i];if(e.shift(),e.length%2>0)return!1;const t=/^[-+]?\d+([\.,]\d+)?$/,n=/[eastsouthnorthwest]+/i,r=e.length/2;for(let u=0;u{e.decimalLatitude?i.push(e):i.push({...e,...vr})}),[...i,...br,...wr]}const Lr=Er();ei.formats=Lr.map(i=>i.verbatimCoordinates);const _r=ei;function Gi(i,e,t){const n=i.slice();return n[97]=e[t],n[99]=t,n}function Di(i){let e,t,n,r,u;return t=new Mi({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[3]),S(e,"class","svelte-bz0zu3")},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[78]),r=!0)},p(a,o){(!n||o[0]&8)&&S(e,"title",a[3])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function zi(i){let e,t;return e=new nr({}),{c(){Qe(e.$$.fragment)},m(n,r){qe(e,n,r),t=!0},i(n){t||(re(e.$$.fragment,n),t=!0)},o(n){fe(e.$$.fragment,n),t=!1},d(n){Fe(e,n)}}}function Ui(i){let e,t,n,r,u;return t=new ur({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[10]),S(e,"class","svelte-bz0zu3"),Ie(e,"active",i[0])},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[79]),r=!0)},p(a,o){(!n||o[0]&1024)&&S(e,"title",a[10]),(!n||o[0]&1)&&Ie(e,"active",a[0])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function Sr(i){let e,t=[],n=new Map,r,u,a,o=Ti(i[13]);const g=c=>c[97].id+(c[97].address?","+c[97].address:"");for(let c=0;c{B=null}),vt()):B?(B.p(d,v),v[0]&1048576&&re(B,1)):(B=Di(d),B.c(),re(B,1),B.m(c,E)),d[20]?z?v[0]&1048576&&re(z,1):(z=zi(),z.c(),re(z,1),z.m(c,null)):z&&(yt(),fe(z,1,1,()=>{z=null}),vt()),(!O||v[0]&2)&&Ie(c,"displayable",d[1]!==""),d[6]==="button"?W?(W.p(d,v),v[0]&64&&re(W,1)):(W=Ui(d),W.c(),re(W,1),W.m(n,M)):W&&(yt(),fe(W,1,1,()=>{W=null}),vt()),l&&l.p&&(!O||v[2]&128)&&Tn(l,s,d,d[69],O?xn(s,d[69],v,null):Mn(d[69]),null);let p=k;k=h(d),k===p?~k&&m[k].p(d,v):(I&&(yt(),fe(m[p],1,1,()=>{m[p]=null}),vt()),~k?(I=m[k],I?I.p(d,v):(I=m[k]=f[k](d),I.c()),re(I,1),I.m(t,null)):I=null),(!O||v[0]&4&&C!==(C=Pt(d[2])+" svelte-bz0zu3"))&&S(t,"class",C),(!O||v[0]&38)&&Ie(t,"can-collapse",d[5]&&d[1]==="")},i(d){O||(re(P),re(u.$$.fragment,d),re(B),re(z),re(W),re(l,d),re(I),O=!0)},o(d){fe(P),fe(u.$$.fragment,d),fe(B),fe(z),fe(W),fe(l,d),fe(I),O=!1},d(d){d&&($(e),$(t)),Fe(u),i[72](null),B&&B.d(),z&&z.d(),W&&W.d(),l&&l.d(d),~k&&m[k].d(),x=!1,Ue(N)}}}function Nr(i,e,t){let n,r,u,{$$slots:a={},$$scope:o}=e;const g={continental_marine:4,country:4,major_landform:8,region:5,subregion:6,county:7,joint_municipality:8,joint_submunicipality:9,municipality:10,municipal_district:11,locality:12,neighbourhood:13,place:14,postal_code:14,road:16,poi:17,address:18,"poi.peak":15,"poi.shop":18,"poi.cafe":18,"poi.restaurant":18,"poi.aerodrome":13};let{class:c=void 0}=e,{apiKey:E=void 0}=e,{bbox:_=void 0}=e,{clearButtonTitle:M="clear"}=e,{clearOnBlur:R=!1}=e,{clearListOnPick:k=!1}=e,{keepListOpen:I=!1}=e,{collapsed:C=!1}=e,{country:O=void 0}=e,{debounceSearch:x=200}=e,{enableReverse:N="never"}=e,{errorMessage:P="Something went wrong…"}=e,{filter:B=()=>!0}=e,{flyTo:z=!0}=e,{fuzzyMatch:W=!0}=e,{language:s=void 0}=e,{limit:l=void 0}=e;const f=41415112612;let{reverseGeocodingLimit:m=f}=e,{mapController:h=void 0}=e,{minLength:d=2}=e,{noResultsMessage:v="Oops! Looks like you're trying to predict something that's not quite right. We can't seem to find what you're looking for. Maybe try double-checking your spelling or try a different search term. Keep on typing - we'll do our best to get you where you need to go!"}=e,{placeholder:p="Search"}=e,{proximity:y=[{type:"server-geolocation"}]}=e,{reverseActive:b=N==="always"}=e,{reverseButtonTitle:w="toggle reverse geocoding"}=e,{searchValue:T=""}=e,{pickedResultStyle:G="full-geometry"}=e,{showPlaceType:D="if-needed"}=e,{showResultsWhileTyping:H=!0}=e,{selectFirst:Q=!0}=e,{flyToSelected:se=!1}=e,{markerOnSelected:Z=!0}=e,{types:K=void 0}=e;const de=[];let{reverseGeocodingTypes:He=de}=e,{exhaustiveReverseGeocoding:st=!1}=e,{excludeTypes:ot=!1}=e;const Le=void 0;let{reverseGeocodingExcludeTypes:We=Le}=e,{zoom:pe=g}=e,{apiUrl:ge="https://api.maptiler.com/geocoding"}=e,{fetchParameters:ie={}}=e,{iconsBaseUrl:hn="https://cdn.maptiler.com/maptiler-geocoding-control/v2.1.7/icons/"}=e,{adjustUrlQuery:ui=()=>{}}=e,{adjustUrl:ai=()=>{}}=e;function gs(L){Pe.focus(L)}function ms(){Pe.blur()}function dn(L,le=!0,ae=!1){t(1,T=L),le?(t(15,X=-1),mn()):(pn(void 0,!ae,ae),setTimeout(()=>{Pe.focus(),Pe.select()}))}function ps(){t(13,F=void 0),t(14,U=void 0),t(15,X=-1)}function ys(){t(64,ce=[]),t(14,U=void 0)}let F,ce,U,gn="",Pe,X=-1,Ge,Zt=[],lt,ct,ht,fi,Ve=!1;const vs=new Set,tt=_i();Rn(()=>{h&&(h.setEventHandler(void 0),h.indicateReverse(!1),h.setSelectedMarker(-1),h.setFeatures(void 0,void 0,!1))});function mn(L){if(t(17,Ve=!1),ct&&(clearTimeout(ct),ct=void 0),X>-1&&F)t(14,U=F[X]),t(1,T=U.place_type[0]==="reverse"?U.place_name:U.place_name.replace(/,.*/,"")),t(19,Ge=void 0),t(64,ce=void 0),t(15,X=-1);else if(T){const le=L||!ci(T);hi(T,{exact:!0}).then(()=>{t(64,ce=F),t(14,U=void 0),le&&bs()}).catch(ae=>t(19,Ge=ae))}}function ci(L){try{return _r(L,6)}catch{return!1}}async function hi(L,{byId:le=!1,exact:ae=!1}={}){var Se,De,it;t(19,Ge=void 0),lt==null||lt.abort();const _e=new AbortController;t(20,lt=_e);try{const J=ci(L),Mt=new URL(ge+"/"+encodeURIComponent(J?J.decimalLongitude+","+J.decimalLatitude:L)+".json"),Ne=Mt.searchParams;s!==void 0&&Ne.set("language",Array.isArray(s)?s.join(","):s??"");const[mi]=(h==null?void 0:h.getCenterAndZoom())??[];let ze=(Se=!J||He===de?K:He)==null?void 0:Se.map(ve=>typeof ve=="string"?ve:mi===void 0||(ve[0]??0)<=mi&&mi<(ve[1]??1/0)?ve[2]:void 0).filter(ve=>ve!==void 0);ze&&(ze=[...new Set(ze)],Ne.set("types",ze.join(",")));const vn=!J||We===Le?ot:We;if(vn&&Ne.set("excludeTypes",String(vn)),_&&Ne.set("bbox",_.map(ve=>ve.toFixed(6)).join(",")),O&&Ne.set("country",Array.isArray(O)?O.join(","):O),!le&&!J){const ve=await hr(h,y,_e);ve&&Ne.set("proximity",ve),(ae||!H)&&Ne.set("autocomplete","false"),Ne.set("fuzzyMatch",String(W))}const Ct=m===f?l:m;Ct!==void 0&&Ct>1&&(ze==null?void 0:ze.length)!==1&&console.warn("For reverse geocoding when limit > 1 then types must contain single value."),J?(Ct===1||Ct!==void 0&&(st||(ze==null?void 0:ze.length)===1))&&Ne.set("limit",String(Ct)):l!==void 0&&Ne.set("limit",String(l)),E&&Ne.set("key",E),ui(Ne),ai(Mt);const Bs=Mt.searchParams.get("types")===""&&Mt.searchParams.get("excludeTypes")!=="true",Ht=Mt.toString();if(Ht===gn){le?(k&&t(13,F=void 0),t(14,U=Zt[0])):(t(13,F=Zt),((De=F[X])==null?void 0:De.id)!==(r==null?void 0:r.id)&&t(15,X=-1));return}gn=Ht;let Nt;if(Bs)Nt={type:"FeatureCollection",features:[]};else{const ve=await fetch(Ht,{signal:_e.signal,...ie});if(!ve.ok)throw new Error(await ve.text());Nt=await ve.json()}tt("response",{url:Ht,featureCollection:Nt}),le?(k&&t(13,F=void 0),t(14,U=Nt.features[0]),Zt=[U]):(t(13,F=Nt.features.filter(B)),J&&F.unshift({type:"Feature",properties:{},id:"reverse_"+J.decimalLongitude+"_"+J.decimalLatitude,text:J.decimalLatitude+", "+J.decimalLongitude,place_name:J.decimalLatitude+", "+J.decimalLongitude,place_type:["reverse"],center:[J.decimalLongitude,J.decimalLatitude],bbox:[J.decimalLongitude,J.decimalLatitude,J.decimalLongitude,J.decimalLatitude],geometry:{type:"Point",coordinates:[J.decimalLongitude,J.decimalLatitude]}}),Zt=F,((it=F[X])==null?void 0:it.id)!==(r==null?void 0:r.id)&&t(15,X=-1),J&&Pe.focus())}catch(J){if(J&&typeof J=="object"&&"name"in J&&J.name==="AbortError")return;throw J}finally{_e===lt&&t(20,lt=void 0)}}function bs(){var _e;if(!(ce!=null&&ce.length)||!z)return;const L=[180,90,-180,-90],le=!ce.some(Se=>!Se.matching_text);let ae;for(const Se of ce){const De=Tt(Se);if(ae=ae===void 0?De:De===void 0?ae:Math.max(ae,De),le||!Se.matching_text)for(const it of[0,1,2,3])L[it]=Math[it<2?"min":"max"](L[it],((_e=Se.bbox)==null?void 0:_e[it])??Se.center[it%2])}h&&ce.length>0&&(U&&L[0]===L[2]&&L[1]===L[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(L),50,ae))}function di(){!U||!h||(!U.bbox||U.bbox[0]===U.bbox[2]&&U.bbox[1]===U.bbox[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(U.bbox),50,Tt(U)))}function Tt(L){var ae;if(!L.bbox||L.bbox[0]!==L.bbox[2]&&L.bbox[1]!==L.bbox[3])return;const le=L.id.replace(/\..*/,"");return(Array.isArray((ae=L.properties)==null?void 0:ae.categories)?L.properties.categories.reduce((_e,Se)=>{const De=pe[le+"."+Se];return _e===void 0?De:De===void 0?_e:Math.max(_e,De)},void 0):void 0)??pe[le]}function ws(L){t(0,b=N==="always"),t(13,F=void 0),t(14,U=void 0),t(15,X=-1),dn(L[1].toFixed(6)+", "+cr(L[0],[-180,180],!0).toFixed(6),!1,!0)}function Es(L){if(!F)return;let le=L.key==="ArrowDown"?1:L.key==="ArrowUp"?-1:0;le&&(Pe.focus(),t(17,Ve=!0),L.preventDefault(),U&&X===-1&&t(15,X=F.findIndex(ae=>ae.id===(U==null?void 0:U.id))),X===(U||Q?0:-1)&&le===-1&&t(15,X=F.length),t(15,X+=le),X>=F.length&&t(15,X=-1),X<0&&(U||Q)&&t(15,X=0))}function pn(L,le=!0,ae=!1){if(t(19,Ge=void 0),t(14,U=void 0),t(17,Ve=!0),H||ae){if(ct&&clearTimeout(ct),T.length{hi(_e).catch(Se=>t(19,Ge=Se))},le?x:0)}else t(13,F=void 0),t(19,Ge=void 0)}function gi(L){U&&(U==null?void 0:U.id)===(L==null?void 0:L.id)?di():(t(14,U=L),t(1,T=L.place_name))}function yn(L){t(15,X=L)}function Ls(){(!Q||U)&&t(15,X=-1),se&&di()}const _s=()=>Pe.focus();function Ss(L){Yt[L?"unshift":"push"](()=>{Pe=L,t(18,Pe)})}function xs(){T=this.value,t(1,T),t(17,Ve),t(31,R),t(16,ht)}const Ts=()=>t(17,Ve=!0),Ms=()=>t(17,Ve=!1),Cs=()=>t(17,Ve=!0),Ns=()=>t(14,U=void 0),ks=()=>{t(1,T=""),t(14,U=void 0),Pe.focus()},Os=()=>t(0,b=!b),Rs=()=>t(19,Ge=void 0),Ps=L=>yn(L),Is=L=>gi(L),As=()=>{};return i.$$set=L=>{"class"in L&&t(2,c=L.class),"apiKey"in L&&t(29,E=L.apiKey),"bbox"in L&&t(30,_=L.bbox),"clearButtonTitle"in L&&t(3,M=L.clearButtonTitle),"clearOnBlur"in L&&t(31,R=L.clearOnBlur),"clearListOnPick"in L&&t(32,k=L.clearListOnPick),"keepListOpen"in L&&t(4,I=L.keepListOpen),"collapsed"in L&&t(5,C=L.collapsed),"country"in L&&t(33,O=L.country),"debounceSearch"in L&&t(34,x=L.debounceSearch),"enableReverse"in L&&t(6,N=L.enableReverse),"errorMessage"in L&&t(7,P=L.errorMessage),"filter"in L&&t(35,B=L.filter),"flyTo"in L&&t(36,z=L.flyTo),"fuzzyMatch"in L&&t(37,W=L.fuzzyMatch),"language"in L&&t(38,s=L.language),"limit"in L&&t(39,l=L.limit),"reverseGeocodingLimit"in L&&t(40,m=L.reverseGeocodingLimit),"mapController"in L&&t(41,h=L.mapController),"minLength"in L&&t(42,d=L.minLength),"noResultsMessage"in L&&t(8,v=L.noResultsMessage),"placeholder"in L&&t(9,p=L.placeholder),"proximity"in L&&t(43,y=L.proximity),"reverseActive"in L&&t(0,b=L.reverseActive),"reverseButtonTitle"in L&&t(10,w=L.reverseButtonTitle),"searchValue"in L&&t(1,T=L.searchValue),"pickedResultStyle"in L&&t(44,G=L.pickedResultStyle),"showPlaceType"in L&&t(11,D=L.showPlaceType),"showResultsWhileTyping"in L&&t(45,H=L.showResultsWhileTyping),"selectFirst"in L&&t(46,Q=L.selectFirst),"flyToSelected"in L&&t(47,se=L.flyToSelected),"markerOnSelected"in L&&t(48,Z=L.markerOnSelected),"types"in L&&t(49,K=L.types),"reverseGeocodingTypes"in L&&t(50,He=L.reverseGeocodingTypes),"exhaustiveReverseGeocoding"in L&&t(51,st=L.exhaustiveReverseGeocoding),"excludeTypes"in L&&t(52,ot=L.excludeTypes),"reverseGeocodingExcludeTypes"in L&&t(53,We=L.reverseGeocodingExcludeTypes),"zoom"in L&&t(54,pe=L.zoom),"apiUrl"in L&&t(55,ge=L.apiUrl),"fetchParameters"in L&&t(56,ie=L.fetchParameters),"iconsBaseUrl"in L&&t(12,hn=L.iconsBaseUrl),"adjustUrlQuery"in L&&t(57,ui=L.adjustUrlQuery),"adjustUrl"in L&&t(58,ai=L.adjustUrl),"$$scope"in L&&t(69,o=L.$$scope)},i.$$.update=()=>{if(i.$$.dirty[0]&64&&t(0,b=N==="always"),i.$$.dirty[0]&16384|i.$$.dirty[1]&8192&&G!=="marker-only"&&U&&!U.address&&U.geometry.type==="Point"&&U.place_type[0]!=="reverse"&&hi(U.id,{byId:!0}).catch(L=>t(19,Ge=L)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1058|i.$$.dirty[2]&8&&(h&&U&&U.id!==fi&&z&&(di(),k&&t(13,F=void 0),t(64,ce=void 0),t(15,X=-1)),t(65,fi=U==null?void 0:U.id)),i.$$.dirty[0]&196608|i.$$.dirty[1]&1&&setTimeout(()=>{t(16,ht=Ve),R&&!ht&&t(1,T="")}),i.$$.dirty[0]&8194|i.$$.dirty[1]&2048&&T.length{switch(L.type){case"mapClick":b&&ws(L.coordinates);break;case"markerClick":{const le=F==null?void 0:F.find(ae=>ae.id===L.id);le&&gi(le)}break;case"markerMouseEnter":ce&&t(15,X=ht?(F==null?void 0:F.findIndex(le=>le.id===L.id))??-1:-1);break;case"markerMouseLeave":ce&&t(15,X=-1);break}}),i.$$.dirty[0]&40960&&t(66,r=F==null?void 0:F[X]),i.$$.dirty[1]&66592|i.$$.dirty[2]&16&&h&&r&&z&&se&&h.flyTo(r.center,Tt(r)),i.$$.dirty[1]&8192&&t(68,n=G==="full-geometry-including-polygon-center-marker"),i.$$.dirty[1]&132096|i.$$.dirty[2]&64&&(Z||h==null||h.setFeatures(void 0,void 0,n)),i.$$.dirty[0]&16384|i.$$.dirty[1]&132096|i.$$.dirty[2]&84&&h&&Z&&!ce&&(h.setFeatures(r?[r]:void 0,U,n),h.setSelectedMarker(r?0:-1)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1024|i.$$.dirty[2]&68&&h&&h.setFeatures(ce,U,n),i.$$.dirty[0]&32768|i.$$.dirty[1]&1024|i.$$.dirty[2]&4&&ce&&h&&h.setSelectedMarker(X),i.$$.dirty[0]&2|i.$$.dirty[1]&1024&&h){const L=ci(T);h.setReverseMarker(L?[L.decimalLongitude,L.decimalLatitude]:void 0)}i.$$.dirty[2]&16&&tt("select",{feature:r}),i.$$.dirty[0]&16384&&tt("pick",{feature:U}),i.$$.dirty[0]&73744&&t(67,u=!!(F!=null&&F.length)&&(ht||I)),i.$$.dirty[2]&32&&tt("optionsvisibilitychange",{optionsVisible:u}),i.$$.dirty[0]&8192&&tt("featureslisted",{features:F}),i.$$.dirty[2]&4&&tt("featuresmarked",{features:ce}),i.$$.dirty[0]&1&&tt("reversetoggle",{reverse:b}),i.$$.dirty[0]&2&&tt("querychange",{query:T}),i.$$.dirty[0]&1|i.$$.dirty[1]&1024&&h&&h.indicateReverse(b)},[b,T,c,M,I,C,N,P,v,p,w,D,hn,F,U,X,ht,Ve,Pe,Ge,lt,vs,mn,Es,pn,gi,yn,Ls,g,E,_,R,k,O,x,B,z,W,s,l,m,h,d,y,G,H,Q,se,Z,K,He,st,ot,We,pe,ge,ie,ui,ai,gs,ms,dn,ps,ys,ce,fi,r,u,n,o,a,_s,Ss,xs,Ts,Ms,Cs,Ns,ks,Os,Rs,Ps,Is,As]}let kr=class extends Je{constructor(e){super(),Xe(this,e,Nr,Cr,Ke,{ZOOM_DEFAULTS:28,class:2,apiKey:29,bbox:30,clearButtonTitle:3,clearOnBlur:31,clearListOnPick:32,keepListOpen:4,collapsed:5,country:33,debounceSearch:34,enableReverse:6,errorMessage:7,filter:35,flyTo:36,fuzzyMatch:37,language:38,limit:39,reverseGeocodingLimit:40,mapController:41,minLength:42,noResultsMessage:8,placeholder:9,proximity:43,reverseActive:0,reverseButtonTitle:10,searchValue:1,pickedResultStyle:44,showPlaceType:11,showResultsWhileTyping:45,selectFirst:46,flyToSelected:47,markerOnSelected:48,types:49,reverseGeocodingTypes:50,exhaustiveReverseGeocoding:51,excludeTypes:52,reverseGeocodingExcludeTypes:53,zoom:54,apiUrl:55,fetchParameters:56,iconsBaseUrl:12,adjustUrlQuery:57,adjustUrl:58,focus:59,blur:60,setQuery:61,clearList:62,clearMap:63},null,[-1,-1,-1,-1])}get ZOOM_DEFAULTS(){return this.$$.ctx[28]}get focus(){return this.$$.ctx[59]}get blur(){return this.$$.ctx[60]}get setQuery(){return this.$$.ctx[61]}get clearList(){return this.$$.ctx[62]}get clearMap(){return this.$$.ctx[63]}};function Et(i,e,t={}){const n={type:"Feature"};return(t.id===0||t.id)&&(n.id=t.id),t.bbox&&(n.bbox=t.bbox),n.properties=e||{},n.geometry=i,n}function ti(i,e,t={}){for(const r of i){if(r.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(r[r.length-1].length!==r[0].length)throw new Error("First and last Position are not equivalent.");for(let u=0;u_?w.c=w.e=null:s.e=10;v/=10,d++);d>_?w.c=w.e=null:(w.e=d,w.c=[s]);return}b=String(s)}else{if(!Or.test(b=String(s)))return n(w,b,p);w.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(v=b.search(/e/i))>0?(d<0&&(d=v),d+=+b.slice(v+1),b=b.substring(0,v)):d<0&&(d=b.length)}else{if(oe(l,2,C.length,"Base"),l==10&&O)return w=new x(s),z(w,a+w.e+1,o);if(b=String(s),p=typeof s=="number"){if(s*0!=0)return n(w,b,p,l);if(w.s=1/s<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(ji+s)}else w.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(f=C.slice(0,l),d=v=0,y=b.length;vd){d=y;continue}}else if(!h&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){h=!0,v=-1,d=0;continue}return n(w,String(s),p,l)}p=!1,b=t(b,l,10,w.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(v=0;b.charCodeAt(v)===48;v++);for(y=b.length;b.charCodeAt(--y)===48;);if(b=b.slice(v,++y)){if(y-=v,p&&x.DEBUG&&y>15&&(s>Zi||s!==Te(s)))throw Error(ji+w.s*s);if((d=d-v-1)>_)w.c=w.e=null;else if(d=-1e9&&h<=Ee&&h===Te(h)){if(m[0]===0){if(h===0&&m.length===1)return!0;break e}if(l=(h+1)%q,l<1&&(l+=q),String(m[0]).length==l){for(l=0;l=Re||f!==Te(f))break e;if(f!==0)return!0}}}else if(m===null&&h===null&&(d===null||d===1||d===-1))return!0;throw Error(be+"Invalid BigNumber: "+s)},x.maximum=x.max=function(){return P(arguments,-1)},x.minimum=x.min=function(){return P(arguments,1)},x.random=function(){var s=9007199254740992,l=Math.random()*s&2097151?function(){return Te(Math.random()*s)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(f){var m,h,d,v,p,y=0,b=[],w=new x(u);if(f==null?f=a:oe(f,0,Ee),v=ii(f/q),M)if(crypto.getRandomValues){for(m=crypto.getRandomValues(new Uint32Array(v*=2));y>>11),p>=9e15?(h=crypto.getRandomValues(new Uint32Array(2)),m[y]=h[0],m[y+1]=h[1]):(b.push(p%1e14),y+=2);y=v/2}else if(crypto.randomBytes){for(m=crypto.randomBytes(v*=7);y=9e15?crypto.randomBytes(7).copy(m,y):(b.push(p%1e14),y+=7);y=v/7}else throw M=!1,Error(be+"crypto unavailable");if(!M)for(;y=10;p/=10,y++);yh-1&&(p[v+1]==null&&(p[v+1]=0),p[v+1]+=p[v]/h|0,p[v]%=h)}return p.reverse()}return function(f,m,h,d,v){var p,y,b,w,T,G,D,H,Q=f.indexOf("."),se=a,Z=o;for(Q>=0&&(w=k,k=0,f=f.replace(".",""),H=new x(m),G=H.pow(f.length-Q),k=w,H.c=l(je(Ce(G.c),G.e,"0"),10,h,s),H.e=H.c.length),D=l(f,m,h,v?(p=C,s):(p=s,C)),b=w=D.length;D[--w]==0;D.pop());if(!D[0])return p.charAt(0);if(Q<0?--b:(G.c=D,G.e=b,G.s=d,G=e(G,H,se,Z,h),D=G.c,T=G.r,b=G.e),y=b+se+1,Q=D[y],w=h/2,T=T||y<0||D[y+1]!=null,T=Z<4?(Q!=null||T)&&(Z==0||Z==(G.s<0?3:2)):Q>w||Q==w&&(Z==4||T||Z==6&&D[y-1]&1||Z==(G.s<0?8:7)),y<1||!D[0])f=T?je(p.charAt(1),-se,p.charAt(0)):p.charAt(0);else{if(D.length=y,T)for(--h;++D[--y]>h;)D[y]=0,y||(++b,D=[1].concat(D));for(w=D.length;!D[--w];);for(Q=0,f="";Q<=w;f+=p.charAt(D[Q++]));f=je(f,b,p.charAt(0))}return f}}(),e=function(){function s(m,h,d){var v,p,y,b,w=0,T=m.length,G=h%$e,D=h/$e|0;for(m=m.slice();T--;)y=m[T]%$e,b=m[T]/$e|0,v=D*y+b*G,p=G*y+v%$e*$e+w,w=(p/d|0)+(v/$e|0)+D*b,m[T]=p%d;return w&&(m=[w].concat(m)),m}function l(m,h,d,v){var p,y;if(d!=v)y=d>v?1:-1;else for(p=y=0;ph[p]?1:-1;break}return y}function f(m,h,d,v){for(var p=0;d--;)m[d]-=p,p=m[d]1;m.splice(0,1));}return function(m,h,d,v,p){var y,b,w,T,G,D,H,Q,se,Z,K,de,He,st,ot,Le,We,pe=m.s==h.s?1:-1,ge=m.c,ie=h.c;if(!ge||!ge[0]||!ie||!ie[0])return new x(!m.s||!h.s||(ge?ie&&ge[0]==ie[0]:!ie)?NaN:ge&&ge[0]==0||!ie?pe*0:pe/0);for(Q=new x(pe),se=Q.c=[],b=m.e-h.e,pe=d+b+1,p||(p=Re,b=Me(m.e/q)-Me(h.e/q),pe=pe/q|0),w=0;ie[w]==(ge[w]||0);w++);if(ie[w]>(ge[w]||0)&&b--,pe<0)se.push(1),T=!0;else{for(st=ge.length,Le=ie.length,w=0,pe+=2,G=Te(p/(ie[0]+1)),G>1&&(ie=s(ie,G,p),ge=s(ge,G,p),Le=ie.length,st=ge.length),He=Le,Z=ge.slice(0,Le),K=Z.length;K=p/2&&ot++;do{if(G=0,y=l(ie,Z,Le,K),y<0){if(de=Z[0],Le!=K&&(de=de*p+(Z[1]||0)),G=Te(de/ot),G>1)for(G>=p&&(G=p-1),D=s(ie,G,p),H=D.length,K=Z.length;l(D,Z,H,K)==1;)G--,f(D,Le=10;pe/=10,w++);z(Q,d+(Q.e=w+b*q-1)+1,v,T)}else Q.e=b,Q.r=+T;return Q}}();function N(s,l,f,m){var h,d,v,p,y;if(f==null?f=o:oe(f,0,8),!s.c)return s.toString();if(h=s.c[0],v=s.e,l==null)y=Ce(s.c),y=m==1||m==2&&(v<=g||v>=c)?Gt(y,v):je(y,v,"0");else if(s=z(new x(s),l,f),d=s.e,y=Ce(s.c),p=y.length,m==1||m==2&&(l<=d||d<=g)){for(;pp){if(--l>0)for(y+=".";l--;y+="0");}else if(l+=d-p,l>0)for(d+1==p&&(y+=".");l--;y+="0");return s.s<0&&h?"-"+y:y}function P(s,l){for(var f,m,h=1,d=new x(s[0]);h=10;h/=10,m++);return(f=m+f*q-1)>_?s.c=s.e=null:f=10;p/=10,h++);if(d=l-h,d<0)d+=q,v=l,y=T[b=0],w=Te(y/G[h-v-1]%10);else if(b=ii((d+1)/q),b>=T.length)if(m){for(;T.length<=b;T.push(0));y=w=0,h=1,d%=q,v=d-q+1}else break e;else{for(y=p=T[b],h=1;p>=10;p/=10,h++);d%=q,v=d-q+h,w=v<0?0:Te(y/G[h-v-1]%10)}if(m=m||l<0||T[b+1]!=null||(v<0?y:y%G[h-v-1]),m=f<4?(w||m)&&(f==0||f==(s.s<0?3:2)):w>5||w==5&&(f==4||m||f==6&&(d>0?v>0?y/G[h-v]:0:T[b-1])%10&1||f==(s.s<0?8:7)),l<1||!T[0])return T.length=0,m?(l-=s.e+1,T[0]=G[(q-l%q)%q],s.e=-l||0):T[0]=s.e=0,s;if(d==0?(T.length=b,p=1,b--):(T.length=b+1,p=G[q-d],T[b]=v>0?Te(y/G[h-v]%G[v])*p:0),m)for(;;)if(b==0){for(d=1,v=T[0];v>=10;v/=10,d++);for(v=T[0]+=p,p=1;v>=10;v/=10,p++);d!=p&&(s.e++,T[0]==Re&&(T[0]=1));break}else{if(T[b]+=p,T[b]!=Re)break;T[b--]=0,p=1}for(d=T.length;T[--d]===0;T.pop());}s.e>_?s.c=s.e=null:s.e=c?Gt(l,f):je(l,f,"0"),s.s<0?"-"+l:l)}return r.absoluteValue=r.abs=function(){var s=new x(this);return s.s<0&&(s.s=1),s},r.comparedTo=function(s,l){return rt(this,new x(s,l))},r.decimalPlaces=r.dp=function(s,l){var f,m,h,d=this;if(s!=null)return oe(s,0,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s+d.e+1,l);if(!(f=d.c))return null;if(m=((h=f.length-1)-Me(this.e/q))*q,h=f[h])for(;h%10==0;h/=10,m--);return m<0&&(m=0),m},r.dividedBy=r.div=function(s,l){return e(this,new x(s,l),a,o)},r.dividedToIntegerBy=r.idiv=function(s,l){return e(this,new x(s,l),0,1)},r.exponentiatedBy=r.pow=function(s,l){var f,m,h,d,v,p,y,b,w,T=this;if(s=new x(s),s.c&&!s.isInteger())throw Error(be+"Exponent not an integer: "+W(s));if(l!=null&&(l=new x(l)),p=s.e>14,!T.c||!T.c[0]||T.c[0]==1&&!T.e&&T.c.length==1||!s.c||!s.c[0])return w=new x(Math.pow(+W(T),p?s.s*(2-Wt(s)):+W(s))),l?w.mod(l):w;if(y=s.s<0,l){if(l.c?!l.c[0]:!l.s)return new x(NaN);m=!y&&T.isInteger()&&l.isInteger(),m&&(T=T.mod(l))}else{if(s.e>9&&(T.e>0||T.e<-1||(T.e==0?T.c[0]>1||p&&T.c[1]>=24e7:T.c[0]<8e13||p&&T.c[0]<=9999975e7)))return d=T.s<0&&Wt(s)?-0:0,T.e>-1&&(d=1/d),new x(y?1/d:d);k&&(d=ii(k/q+2))}for(p?(f=new x(.5),y&&(s.s=1),b=Wt(s)):(h=Math.abs(+W(s)),b=h%2),w=new x(u);;){if(b){if(w=w.times(T),!w.c)break;d?w.c.length>d&&(w.c.length=d):m&&(w=w.mod(l))}if(h){if(h=Te(h/2),h===0)break;b=h%2}else if(s=s.times(f),z(s,s.e+1,1),s.e>14)b=Wt(s);else{if(h=+W(s),h===0)break;b=h%2}T=T.times(T),d?T.c&&T.c.length>d&&(T.c.length=d):m&&(T=T.mod(l))}return m?w:(y&&(w=u.div(w)),l?w.mod(l):d?z(w,k,o,v):w)},r.integerValue=function(s){var l=new x(this);return s==null?s=o:oe(s,0,8),z(l,l.e+1,s)},r.isEqualTo=r.eq=function(s,l){return rt(this,new x(s,l))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(s,l){return rt(this,new x(s,l))>0},r.isGreaterThanOrEqualTo=r.gte=function(s,l){return(l=rt(this,new x(s,l)))===1||l===0},r.isInteger=function(){return!!this.c&&Me(this.e/q)>this.c.length-2},r.isLessThan=r.lt=function(s,l){return rt(this,new x(s,l))<0},r.isLessThanOrEqualTo=r.lte=function(s,l){return(l=rt(this,new x(s,l)))===-1||l===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(s,l){var f,m,h,d,v=this,p=v.s;if(s=new x(s,l),l=s.s,!p||!l)return new x(NaN);if(p!=l)return s.s=-l,v.plus(s);var y=v.e/q,b=s.e/q,w=v.c,T=s.c;if(!y||!b){if(!w||!T)return w?(s.s=-l,s):new x(T?v:NaN);if(!w[0]||!T[0])return T[0]?(s.s=-l,s):new x(w[0]?v:o==3?-0:0)}if(y=Me(y),b=Me(b),w=w.slice(),p=y-b){for((d=p<0)?(p=-p,h=w):(b=y,h=T),h.reverse(),l=p;l--;h.push(0));h.reverse()}else for(m=(d=(p=w.length)<(l=T.length))?p:l,p=l=0;l0)for(;l--;w[f++]=0);for(l=Re-1;m>p;){if(w[--m]=0;){for(f=0,G=de[h]%se,D=de[h]/se|0,v=y,d=h+v;d>h;)b=K[--v]%se,w=K[v]/se|0,p=D*b+w*G,b=G*b+p%se*se+H[d]+f,f=(b/Q|0)+(p/se|0)+D*w,H[d--]=b%Q;H[d]=f}return f?++m:H.splice(0,1),B(s,H,m)},r.negated=function(){var s=new x(this);return s.s=-s.s||null,s},r.plus=function(s,l){var f,m=this,h=m.s;if(s=new x(s,l),l=s.s,!h||!l)return new x(NaN);if(h!=l)return s.s=-l,m.minus(s);var d=m.e/q,v=s.e/q,p=m.c,y=s.c;if(!d||!v){if(!p||!y)return new x(h/0);if(!p[0]||!y[0])return y[0]?s:new x(p[0]?m:h*0)}if(d=Me(d),v=Me(v),p=p.slice(),h=d-v){for(h>0?(v=d,f=y):(h=-h,f=p),f.reverse();h--;f.push(0));f.reverse()}for(h=p.length,l=y.length,h-l<0&&(f=y,y=p,p=f,l=h),h=0;l;)h=(p[--l]=p[l]+y[l]+h)/Re|0,p[l]=Re===p[l]?0:p[l]%Re;return h&&(p=[h].concat(p),++v),B(s,p,v)},r.precision=r.sd=function(s,l){var f,m,h,d=this;if(s!=null&&s!==!!s)return oe(s,1,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s,l);if(!(f=d.c))return null;if(h=f.length-1,m=h*q+1,h=f[h]){for(;h%10==0;h/=10,m--);for(h=f[0];h>=10;h/=10,m++);}return s&&d.e+1>m&&(m=d.e+1),m},r.shiftedBy=function(s){return oe(s,-9007199254740991,Zi),this.times("1e"+s)},r.squareRoot=r.sqrt=function(){var s,l,f,m,h,d=this,v=d.c,p=d.s,y=d.e,b=a+4,w=new x("0.5");if(p!==1||!v||!v[0])return new x(!p||p<0&&(!v||v[0])?NaN:v?d:1/0);if(p=Math.sqrt(+W(d)),p==0||p==1/0?(l=Ce(v),(l.length+y)%2==0&&(l+="0"),p=Math.sqrt(+l),y=Me((y+1)/2)-(y<0||y%2),p==1/0?l="5e"+y:(l=p.toExponential(),l=l.slice(0,l.indexOf("e")+1)+y),f=new x(l)):f=new x(p+""),f.c[0]){for(y=f.e,p=y+b,p<3&&(p=0);;)if(h=f,f=w.times(h.plus(e(d,h,b,1))),Ce(h.c).slice(0,p)===(l=Ce(f.c)).slice(0,p))if(f.e0&&H>0){for(d=H%p||p,w=D.substr(0,d);d0&&(w+=b+D.slice(d)),G&&(w="-"+w)}m=T?w+(f.decimalSeparator||"")+((y=+f.fractionGroupSize)?T.replace(new RegExp("\\d{"+y+"}\\B","g"),"$&"+(f.fractionGroupSeparator||"")):T):w}return(f.prefix||"")+m+(f.suffix||"")},r.toFraction=function(s){var l,f,m,h,d,v,p,y,b,w,T,G,D=this,H=D.c;if(s!=null&&(p=new x(s),!p.isInteger()&&(p.c||p.s!==1)||p.lt(u)))throw Error(be+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+W(p));if(!H)return new x(D);for(l=new x(u),b=f=new x(u),m=y=new x(u),G=Ce(H),d=l.e=G.length-D.e-1,l.c[0]=ni[(v=d%q)<0?q+v:v],s=!s||p.comparedTo(l)>0?d>0?l:b:p,v=_,_=1/0,p=new x(G),y.c[0]=0;w=e(p,l,0,1),h=f.plus(w.times(m)),h.comparedTo(s)!=1;)f=m,m=h,b=y.plus(w.times(h=b)),y=h,l=p.minus(w.times(h=l)),p=h;return h=e(s.minus(f),m,0,1),y=y.plus(h.times(b)),f=f.plus(h.times(m)),y.s=b.s=D.s,d=d*2,T=e(b,m,d,o).minus(D).abs().comparedTo(e(y,f,d,o).minus(D).abs())<1?[b,m]:[y,f],_=v,T},r.toNumber=function(){return+W(this)},r.toPrecision=function(s,l){return s!=null&&oe(s,1,Ee),N(this,s,l,2)},r.toString=function(s){var l,f=this,m=f.s,h=f.e;return h===null?m?(l="Infinity",m<0&&(l="-"+l)):l="NaN":(s==null?l=h<=g||h>=c?Gt(Ce(f.c),h):je(Ce(f.c),h,"0"):s===10&&O?(f=z(new x(f),a+h+1,o),l=je(Ce(f.c),f.e,"0")):(oe(s,2,C.length,"Base"),l=t(je(Ce(f.c),h,"0"),10,s,m,!0)),m<0&&f.c[0]&&(l="-"+l)),l},r.valueOf=r.toJSON=function(){return W(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,i!=null&&x.set(i),x}function Me(i){var e=i|0;return i>0||i===e?e:e-1}function Ce(i){for(var e,t,n=1,r=i.length,u=i[0]+"";nc^t?1:-1;for(o=(g=r.length)<(c=u.length)?g:c,a=0;au[a]^t?1:-1;return g==c?0:g>c^t?1:-1}function oe(i,e,t,n){if(it||i!==Te(i))throw Error(be+(n||"Argument")+(typeof i=="number"?it?" out of range: ":" not an integer: ":" not a primitive number: ")+String(i))}function Wt(i){var e=i.c.length-1;return Me(i.e/q)==e&&i.c[e]%2!=0}function Gt(i,e){return(i.length>1?i.charAt(0)+"."+i.slice(1):i)+(e<0?"e":"e+")+e}function je(i,e,t){var n,r;if(e<0){for(r=t+".";++e;r+=t);i=r+i}else if(n=i.length,++e>n){for(r=t,e-=n;--e;r+=t);i+=r}else e0){let c=a.left;if(c==null||(g=o(c.key,i),g>0&&(a.left=c.right,c.right=a,a=c,c=a.left,c==null)))break;t==null?n=a:t.left=a,t=a,a=c}else if(g<0){let c=a.right;if(c==null||(g=o(c.key,i),g<0&&(a.right=c.left,c.left=a,a=c,c=a.right,c==null)))break;r==null?u=a:r.right=a,r=a,a=c}else break;return r!=null&&(r.right=a.left,a.left=u),t!=null&&(t.left=a.right,a.right=n),this.root!==a&&(this.root=a,this.splayCount++),g}splayMin(i){let e=i,t=e.left;for(;t!=null;){const n=t;e.left=n.right,n.right=e,e=n,t=e.left}return e}splayMax(i){let e=i,t=e.right;for(;t!=null;){const n=t;e.right=n.left,n.left=e,e=n,t=e.right}return e}_delete(i){if(this.root==null||this.splay(i)!=0)return null;let t=this.root;const n=t,r=t.left;if(this.size--,r==null)this.root=t.right;else{const u=t.right;t=this.splayMax(r),t.right=u,this.root=t}return this.modificationCount++,n}addNewRoot(i,e){this.size++,this.modificationCount++;const t=this.root;if(t==null){this.root=i;return}e<0?(i.left=t,i.right=t.right,t.right=null):(i.right=t,i.left=t.left,t.left=null),this.root=i}_first(){const i=this.root;return i==null?null:(this.root=this.splayMin(i),this.root)}_last(){const i=this.root;return i==null?null:(this.root=this.splayMax(i),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(i){return this.validKey(i)&&this.splay(i)==0}defaultCompare(){return(i,e)=>ie?1:0}wrap(){return{getRoot:()=>this.root,setRoot:i=>{this.root=i},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:i=>{this.splayCount=i},splay:i=>this.splay(i),has:i=>this.has(i)}}},Dt=class Ot extends Pr{constructor(t,n){super();A(this,"root",null);A(this,"compare");A(this,"validKey");A(this,fn,"[object Set]");this.compare=t??this.defaultCompare(),this.validKey=n??(r=>r!=null&&r!=null)}delete(t){return this.validKey(t)?this._delete(t)!=null:!1}deleteAll(t){for(const n of t)this.delete(n)}forEach(t){const n=this[Symbol.iterator]();let r;for(;r=n.next(),!r.done;)t(r.value,r.value,this)}add(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this}addAndReturn(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this.root.key}addAll(t){for(const n of t)this.add(n)}isEmpty(){return this.root==null}isNotEmpty(){return this.root!=null}single(){if(this.size==0)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(this.size==0)throw"Bad state: No element";return this._first().key}last(){if(this.size==0)throw"Bad state: No element";return this._last().key}lastBefore(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)<0)return this.root.key;let r=this.root.left;if(r==null)return null;let u=r.right;for(;u!=null;)r=u,u=r.right;return r.key}firstAfter(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)>0)return this.root.key;let r=this.root.right;if(r==null)return null;let u=r.left;for(;u!=null;)r=u,u=r.left;return r.key}retainAll(t){const n=new Ot(this.compare,this.validKey),r=this.modificationCount;for(const u of t){if(r!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(u)&&this.splay(u)==0&&n.add(this.root.key)}n.size!=this.size&&(this.root=n.root,this.size=n.size,this.modificationCount++)}lookup(t){return!this.validKey(t)||this.splay(t)!=0?null:this.root.key}intersection(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)&&n.add(r);return n}difference(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)||n.add(r);return n}union(t){const n=this.clone();return n.addAll(t),n}clone(){const t=new Ot(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(t){if(t==null)return null;function n(u,a){let o,g;do{if(o=u.left,g=u.right,o!=null){const c=new _t(o.key);a.left=c,n(o,c)}if(g!=null){const c=new _t(g.key);a.right=c,u=g,a=c}}while(g!=null)}const r=new _t(t.key);return n(t,r),r}toSet(){return this.clone()}entries(){return new Ar(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[(cn=Symbol.iterator,fn=Symbol.toStringTag,cn)](){return new Ir(this.wrap())}},Vi=class{constructor(i){A(this,"tree");A(this,"path",new Array);A(this,"modificationCount",null);A(this,"splayCount");this.tree=i,this.splayCount=i.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const i=this.path[this.path.length-1];return this.getValue(i)}rebuildPath(i){this.path.splice(0,this.path.length),this.tree.splay(i),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(i){for(;i!=null;)this.path.push(i),i=i.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(this.modificationCount==null){this.modificationCount=this.tree.getModificationCount();let t=this.tree.getRoot();for(;t!=null;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let i=this.path[this.path.length-1],e=i.right;if(e!=null){for(;e!=null;)this.path.push(e),e=e.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===i;)i=this.path.pop();return this.path.length>0}},Ir=class extends Vi{getValue(i){return i.key}},Ar=class extends Vi{getValue(i){return[i.key,i.key]}},Ki=i=>()=>i,ri=i=>{const e=i?(t,n)=>n.minus(t).abs().isLessThanOrEqualTo(i):Ki(!1);return(t,n)=>e(t,n)?0:t.comparedTo(n)};function Br(i){const e=i?(t,n,r,u,a)=>t.exponentiatedBy(2).isLessThanOrEqualTo(u.minus(n).exponentiatedBy(2).plus(a.minus(r).exponentiatedBy(2)).times(i)):Ki(!1);return(t,n,r)=>{const u=t.x,a=t.y,o=r.x,g=r.y,c=a.minus(g).times(n.x.minus(o)).minus(u.minus(o).times(n.y.minus(g)));return e(c,u,a,o,g)?0:c.comparedTo(0)}}var Wr=i=>i,Gr=i=>{if(i){const e=new Dt(ri(i)),t=new Dt(ri(i)),n=(u,a)=>a.addAndReturn(u),r=u=>({x:n(u.x,e),y:n(u.y,t)});return r({x:new Ae(0),y:new Ae(0)}),r}return Wr},si=i=>({set:e=>{Ze=si(e)},reset:()=>si(i),compare:ri(i),snap:Gr(i),orient:Br(i)}),Ze=si(),St=(i,e)=>i.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(i.ur.x)&&i.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(i.ur.y),oi=(i,e)=>{if(e.ur.x.isLessThan(i.ll.x)||i.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(i.ll.y)||i.ur.y.isLessThan(e.ll.y))return null;const t=i.ll.x.isLessThan(e.ll.x)?e.ll.x:i.ll.x,n=i.ur.x.isLessThan(e.ur.x)?i.ur.x:e.ur.x,r=i.ll.y.isLessThan(e.ll.y)?e.ll.y:i.ll.y,u=i.ur.y.isLessThan(e.ur.y)?i.ur.y:e.ur.y;return{ll:{x:t,y:r},ur:{x:n,y:u}}},zt=(i,e)=>i.x.times(e.y).minus(i.y.times(e.x)),Yi=(i,e)=>i.x.times(e.x).plus(i.y.times(e.y)),Ut=i=>Yi(i,i).sqrt(),Dr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return zt(r,n).div(Ut(r)).div(Ut(n))},zr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return Yi(r,n).div(Ut(r)).div(Ut(n))},Qi=(i,e,t)=>e.y.isZero()?null:{x:i.x.plus(e.x.div(e.y).times(t.minus(i.y))),y:t},Xi=(i,e,t)=>e.x.isZero()?null:{x:t,y:i.y.plus(e.y.div(e.x).times(t.minus(i.x)))},Ur=(i,e,t,n)=>{if(e.x.isZero())return Xi(t,n,i.x);if(n.x.isZero())return Xi(i,e,t.x);if(e.y.isZero())return Qi(t,n,i.y);if(n.y.isZero())return Qi(i,e,t.y);const r=zt(e,n);if(r.isZero())return null;const u={x:t.x.minus(i.x),y:t.y.minus(i.y)},a=zt(u,e).div(r),o=zt(u,n).div(r),g=i.x.plus(o.times(e.x)),c=t.x.plus(a.times(n.x)),E=i.y.plus(o.times(e.y)),_=t.y.plus(a.times(n.y)),M=g.plus(c).div(2),R=E.plus(_).div(2);return{x:M,y:R}},Be=class En{constructor(e,t){A(this,"point");A(this,"isLeft");A(this,"segment");A(this,"otherSE");A(this,"consumedBy");e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}static compare(e,t){const n=En.comparePoints(e.point,t.point);return n!==0?n:(e.point!==t.point&&e.link(t),e.isLeft!==t.isLeft?e.isLeft?1:-1:Ft.compare(e.segment,t.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let n=0,r=t.length;n{const u=r.otherSE;t.set(r,{sine:Dr(this.point,e.point,u.point),cosine:zr(this.point,e.point,u.point)})};return(r,u)=>{t.has(r)||n(r),t.has(u)||n(u);const{sine:a,cosine:o}=t.get(r),{sine:g,cosine:c}=t.get(u);return a.isGreaterThanOrEqualTo(0)&&g.isGreaterThanOrEqualTo(0)?o.isLessThan(c)?1:o.isGreaterThan(c)?-1:0:a.isLessThan(0)&&g.isLessThan(0)?o.isLessThan(c)?-1:o.isGreaterThan(c)?1:0:g.isLessThan(a)?-1:g.isGreaterThan(a)?1:0}}},qr=class pi{constructor(e){A(this,"events");A(this,"poly");A(this,"_isExteriorRing");A(this,"_enclosingRing");this.events=e;for(let t=0,n=e.length;t0&&(e=g)}let t=e.segment.prevInResult(),n=t?t.prevInResult():null;for(;;){if(!t)return null;if(!n)return t.ringOut;if(n.ringOut!==t.ringOut)return((r=n.ringOut)==null?void 0:r.enclosingRing())!==t.ringOut?t.ringOut:(u=t.ringOut)==null?void 0:u.enclosingRing();t=n.prevInResult(),n=t?t.prevInResult():null}}},Ji=class{constructor(i){A(this,"exteriorRing");A(this,"interiorRings");this.exteriorRing=i,i.poly=this,this.interiorRings=[]}addInterior(i){this.interiorRings.push(i),i.poly=this}getGeom(){const i=this.exteriorRing.getGeom();if(i===null)return null;const e=[i];for(let t=0,n=this.interiorRings.length;t0?(this.tree.delete(e),t.push(i)):(this.segments.push(e),e.prev=n)}else{if(n&&r){const u=n.getIntersection(r);if(u!==null){if(!n.isAnEndpoint(u)){const a=this._splitSafely(n,u);for(let o=0,g=a.length;o0)return-1;const M=t.comparePoint(e.rightSE.point);return M!==0?M:-1}if(n.isGreaterThan(r)){if(o.isLessThan(g)&&o.isLessThan(E))return-1;if(o.isGreaterThan(g)&&o.isGreaterThan(E))return 1;const _=t.comparePoint(e.leftSE.point);if(_!==0)return _;const M=e.comparePoint(t.rightSE.point);return M<0?1:M>0?-1:1}if(o.isLessThan(g))return-1;if(o.isGreaterThan(g))return 1;if(u.isLessThan(a)){const _=t.comparePoint(e.rightSE.point);if(_!==0)return _}if(u.isGreaterThan(a)){const _=e.comparePoint(t.rightSE.point);if(_<0)return 1;if(_>0)return-1}if(!u.eq(a)){const _=c.minus(o),M=u.minus(n),R=E.minus(g),k=a.minus(r);if(_.isGreaterThan(M)&&R.isLessThan(k))return 1;if(_.isLessThan(M)&&R.isGreaterThan(k))return-1}return u.isGreaterThan(a)?1:u.isLessThan(a)||c.isLessThan(E)?-1:c.isGreaterThan(E)?1:e.idt.id?1:0}static fromRing(e,t,n){let r,u,a;const o=Be.comparePoints(e,t);if(o<0)r=e,u=t,a=1;else if(o>0)r=t,u=e,a=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const g=new Be(r,!0),c=new Be(u,!1);return new Kt(g,c,[n],[a])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return Ze.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),n=e.bbox(),r=oi(t,n);if(r===null)return null;const u=this.leftSE.point,a=this.rightSE.point,o=e.leftSE.point,g=e.rightSE.point,c=St(t,o)&&this.comparePoint(o)===0,E=St(n,u)&&e.comparePoint(u)===0,_=St(t,g)&&this.comparePoint(g)===0,M=St(n,a)&&e.comparePoint(a)===0;if(E&&c)return M&&!_?a:!M&&_?g:null;if(E)return _&&u.x.eq(g.x)&&u.y.eq(g.y)?null:u;if(c)return M&&a.x.eq(o.x)&&a.y.eq(o.y)?null:o;if(M&&_)return null;if(M)return a;if(_)return g;const R=Ur(u,this.vector(),o,e.vector());return R===null||!St(r,R)?null:Ze.snap(R)}split(e){const t=[],n=e.events!==void 0,r=new Be(e,!0),u=new Be(e,!1),a=this.rightSE;this.replaceRightSE(u),t.push(u),t.push(r);const o=new Kt(r,a,this.rings.slice(),this.windings.slice());return Be.comparePoints(o.leftSE.point,o.rightSE.point)>0&&o.swapEvents(),Be.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(r.checkForConsuming(),u.checkForConsuming()),t}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,n=this.windings.length;t0){const u=t;t=n,n=u}if(t.prev===n){const u=t;t=n,n=u}for(let u=0,a=n.rings.length;ur.length===1&&r[0].isSubject;this._isInResult=n(e)!==n(t);break}}return this._isInResult}},$i=class{constructor(i,e,t){A(this,"poly");A(this,"isExterior");A(this,"segments");A(this,"bbox");if(!Array.isArray(i)||i.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=e,this.isExterior=t,this.segments=[],typeof i[0][0]!="number"||typeof i[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const n=Ze.snap({x:new Ae(i[0][0]),y:new Ae(i[0][1])});this.bbox={ll:{x:n.x,y:n.y},ur:{x:n.x,y:n.y}};let r=n;for(let u=1,a=i.length;uqt.run("union",i,e),Yr=(i,...e)=>qt.run("difference",i,e);Ze.set;function tn(i,e,t){if(i!==null)for(var n,r,u,a,o,g,c,E=0,_=0,M,R=i.type,k=R==="FeatureCollection",I=R==="Feature",C=k?i.features.length:1,O=0;O{t.push(r.coordinates)}),t.length<2)throw new Error("Must have at least 2 geometries");const n=Kr(t[0],...t.slice(1));return n.length===0?null:n.length===1?ti(n[0],e.properties):Fi(n,e.properties)}var nn=Xr;function Jr(i,e={}){if(i.bbox!=null&&e.recompute!==!0)return i.bbox;const t=[1/0,1/0,-1/0,-1/0];return tn(i,n=>{t[0]>n[0]&&(t[0]=n[0]),t[1]>n[1]&&(t[1]=n[1]),t[2]{e.push(r.coordinates)}),e.length<2)throw new Error("Must have at least two features");const t=i.features[0].properties||{},n=Yr(e[0],...e.slice(1));return n.length===0?null:n.length===1?ti(n[0],t):Fi(n,t)}var es=$r;function ts(i){if(!i)throw new Error("geojson is required");var e=[];return Qr(i,function(t){e.push(t)}),Lt(e)}var is=ts;function sn(i,e){const t=es(Lt([ti([[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]]),i]));if(!t)return;t.properties={isMask:!0};const n=Bt(rn(i)),r=(n[2]-n[0])/360/1e3,u=n[0]<-180,a=n[2]>180,o=is(i);if(o.features.length>1&&(u||a))for(const g of o.features){const c=Bt(rn(g));if(a&&c[0]<-180+r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]+=360-r;if(u&&c[2]>180-r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]-=360-r}e(Lt([o.features.length<2?i:nn(o)??i,t]))}const on={fill:{paint:{"fill-color":"#000","fill-opacity":.1},filter:["all",["==",["geometry-type"],"Polygon"],["has","isMask"]]},line:{layout:{"line-cap":"square"},paint:{"line-width":["case",["==",["geometry-type"],"Polygon"],2,3],"line-dasharray":[1,1],"line-color":"#3170fe"},filter:["!",["has","isMask"]]}},jt="mtlr-gc-full-geom",ln="mtlr-gc-full-geom-fill",un="mtlr-gc-full-geom-line";function an(i,e,t=!0,n=!0,r={},u={},a=on){let o;const g=[];let c,E,_;function M(){if(!i.loaded){i.once("load",M);return}const C=a?a===!0?on:a:void 0;if(!(C!=null&&C.fill)&&!(C!=null&&C.line))return;const O=i.getSource(jt);if(O)O.setData(_??Lt([]));else if(_)i.addSource(jt,{type:"geojson",data:_});else return;!i.getLayer(ln)&&(C!=null&&C.fill)&&i.addLayer({...C==null?void 0:C.fill,id:ln,type:"fill",source:jt}),!i.getLayer(un)&&(C!=null&&C.line)&&i.addLayer({...C==null?void 0:C.line,id:un,type:"line",source:jt})}function R(C){_=C,M()}i.on("styledata",()=>{setTimeout(()=>{_&&M()})});const k=C=>{o==null||o({type:"mapClick",coordinates:[C.lngLat.lng,C.lngLat.lat]})};function I(C=!1){if(!e)throw new Error;const O=document.createElement("div");return C&&O.classList.add("marker-interactive"),new or({props:{displayIn:"maplibre"},target:O}),new e.Marker({element:O,offset:[1,-13]})}return{setEventHandler(C){C?(o=C,i.on("click",k)):(o=void 0,i.off("click",k))},flyTo(C,O){i.flyTo({center:C,...O?{zoom:O}:{},...r})},fitBounds(C,O,x){i.fitBounds([[C[0],C[1]],[C[2],C[3]]],{padding:O,...x?{maxZoom:x}:{},...u})},indicateReverse(C){i.getCanvasContainer().style.cursor=C?"crosshair":""},setReverseMarker(C){!e||!t||(E?C?E.setLngLat(C):(E.remove(),E=void 0):C&&(t instanceof Function?E=t(i)??void 0:(E=(typeof t=="object"?new e.Marker(t):I()).setLngLat(C).addTo(i),E.getElement().classList.add("marker-reverse"))))},setFeatures(C,O,x){for(const N of g)N.remove();if(g.length=0,R(void 0),!!e){e:if(O){let N=!1;if(O.geometry.type==="GeometryCollection"){const P=O.geometry.geometries.filter(B=>B.type==="Polygon"||B.type==="MultiPolygon");t:if(P.length>0){const B=nn(Lt(P.map(z=>Et(z))));if(!B)break t;sn({...O,geometry:B.geometry},R),N=!0}else{const B=O.geometry.geometries.filter(z=>z.type==="LineString"||z.type==="MultiLineString");B.length>0&&(R({...O,geometry:{type:"GeometryCollection",geometries:B}}),N=!0)}}if(!N){if(O.geometry.type==="Polygon"||O.geometry.type==="MultiPolygon")sn(O,R);else if(O.geometry.type==="LineString"||O.geometry.type==="MultiLineString"){R(O);break e}}if(!x&&!O.geometry.type.endsWith("Point"))break e;if(t instanceof Function){const P=t(i,O);P&&g.push(P)}else t&&g.push(typeof t=="object"?new e.Marker(t):I().setLngLat(O.center).addTo(i))}if(n)for(const N of C??[]){if(N===O)continue;let P;if(n instanceof Function){if(P=n(i,N),!P)continue}else P=(typeof n=="object"?new e.Marker(n):I(!0)).setLngLat(N.center).setPopup(new e.Popup({offset:[1,-27],closeButton:!1,closeOnMove:!0,className:"maptiler-gc-popup"}).setText(N.place_type[0]==="reverse"?N.place_name:N.place_name.replace(/,.*/,""))).addTo(i);const B=P.getElement();B.addEventListener("click",z=>{z.stopPropagation(),o==null||o({type:"markerClick",id:N.id})}),B.addEventListener("mouseenter",()=>{o==null||o({type:"markerMouseEnter",id:N.id}),P.togglePopup()}),B.addEventListener("mouseleave",()=>{o==null||o({type:"markerMouseLeave",id:N.id}),P.togglePopup()}),g.push(P)}}},setSelectedMarker(C){c&&c.getElement().classList.toggle("marker-selected",!1),c=C>-1?g[C]:void 0,c==null||c.getElement().classList.toggle("marker-selected",!0)},getCenterAndZoom(){const C=i.getCenter();return[i.getZoom(),C.lng,C.lat]}}}function ns(i,e,t){var k,I,C;class n{constructor(x,N){A(this,"type");A(this,"target");this.type=N,this.target=x}}class r extends n{constructor(N,P){super(N,"select");A(this,"feature");Object.assign(this,P)}}class u extends n{constructor(N,P){super(N,"featureslisted");A(this,"features");this.features=P}}class a extends n{constructor(N,P){super(N,"featuresmarked");A(this,"features");this.features=P}}class o extends n{constructor(N,P){super(N,"optionsvisibilitychange");A(this,"optionsVisible");this.optionsVisible=P}}class g extends n{constructor(N,P){super(N,"pick");A(this,"feature");this.feature=P}}class c extends n{constructor(N,P){super(N,"querychange");A(this,"query");this.query=P}}class E extends n{constructor(N,P,B){super(N,"response");A(this,"url");A(this,"featureCollection");this.url=P,this.featureCollection=B}}class _ extends n{constructor(N,P){super(N,"reversetoggle");A(this,"reverse");this.reverse=P}}class M extends i{constructor(N={}){super();Vt(this,k);Vt(this,I);Vt(this,C);kt(this,I,N)}onAddInt(N){const P=document.createElement("div");P.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl mapboxgl-ctrl-group";const{marker:B,showResultMarkers:z,flyTo:W,fullGeometryStyle:s,...l}=ue(this,I),f=typeof W=="boolean"?{}:W,h={mapController:an(N,e,B,z,f,f,s),flyTo:W===void 0?!0:!!W,apiKey:"",...t==null?void 0:t(N,P),...l};return h.apiKey||console.warn("No MapTiler Cloud API key was provided, some or all geocoding requests may fail"),kt(this,k,new kr({target:P,props:h})),ue(this,k).$on("select",d=>{this.fire(new r(this,d.detail))}),ue(this,k).$on("pick",d=>{this.fire(new g(this,d.detail.feature))}),ue(this,k).$on("featureslisted",d=>{this.fire(new u(this,d.detail.features))}),ue(this,k).$on("featuresmarked",d=>{this.fire(new a(this,d.detail.features))}),ue(this,k).$on("response",d=>{this.fire(new E(this,d.detail.url,d.detail.featureCollection))}),ue(this,k).$on("optionsvisibilitychange",d=>{this.fire(new o(this,d.detail.optionsVisible))}),ue(this,k).$on("reversetoggle",d=>{this.fire(new _(this,d.detail.reverse))}),ue(this,k).$on("querychange",d=>{this.fire(new c(this,d.detail.query))}),kt(this,C,P),P}on(N,P){return super.on(N,P)}once(N,P){return super.once(N,P)}off(N,P){return super.off(N,P)}listens(N){return super.listens(N)}setOptions(N){var l;Object.assign(ue(this,I),N);const{marker:P,showResultMarkers:B,flyTo:z,fullGeometryStyle:W,...s}=ue(this,I);(l=ue(this,k))==null||l.$set(s)}setQuery(N,P=!0){var B;(B=ue(this,k))==null||B.setQuery(N,P)}clearMap(){var N;(N=ue(this,k))==null||N.clearMap()}clearList(){var N;(N=ue(this,k))==null||N.clearList()}setReverseMode(N){var P;(P=ue(this,k))==null||P.$set({reverseActive:N})}focus(N){var P;(P=ue(this,k))==null||P.focus(N)}blur(){var N;(N=ue(this,k))==null||N.blur()}onRemove(){var N,P,B;(N=ue(this,k))==null||N.$destroy(),kt(this,k,void 0),(B=(P=ue(this,C))==null?void 0:P.parentNode)==null||B.removeChild(ue(this,C))}}return k=new WeakMap,I=new WeakMap,C=new WeakMap,{MapLibreBasedGeocodingControl:M,events:{SelectEvent:r,FeaturesListedEvent:u,FeaturesMarkedEvent:a,OptionsVisibilityChangeEvent:o,PickEvent:g,QueryChangeEvent:c,ResponseEvent:E,ReverseToggleEvent:_}}}const{MapLibreBasedGeocodingControl:rs,events:et}=ns(dt.Evented,dt);class ss extends rs{onAdd(e){return super.onAddInt(e)}}const os=et.SelectEvent,ls=et.FeaturesListedEvent,us=et.FeaturesMarkedEvent,as=et.OptionsVisibilityChangeEvent,fs=et.PickEvent,cs=et.QueryChangeEvent,hs=et.ResponseEvent,ds=et.ReverseToggleEvent;j.FeaturesListedEvent=ls,j.FeaturesMarkedEvent=us,j.GeocodingControl=ss,j.OptionsVisibilityChangeEvent=as,j.PickEvent=fs,j.QueryChangeEvent=cs,j.ResponseEvent=hs,j.ReverseToggleEvent=ds,j.SelectEvent=os,j.createMapLibreGlMapController=an,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"})}); +//# sourceMappingURL=maplibregl.umd.js.map diff --git a/docs/articles/getting-started_files/maptiler-geocoding-control-2.1.7/style.css b/docs/articles/getting-started_files/maptiler-geocoding-control-2.1.7/style.css new file mode 100644 index 0000000..c865c17 --- /dev/null +++ b/docs/articles/getting-started_files/maptiler-geocoding-control-2.1.7/style.css @@ -0,0 +1 @@ +svg.svelte-d2loi5{display:block;fill:#e15042}.sprite-icon.svelte-w9y5n9.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75;background-repeat:no-repeat}li.svelte-w9y5n9.svelte-w9y5n9{text-align:left;cursor:default;display:grid;grid-template-columns:40px 1fr;color:var(--color-text);padding:8px 0;font-size:14px;line-height:18px;min-width:fit-content;outline:0}li.svelte-w9y5n9.svelte-w9y5n9:first-child{padding-top:10px}li.svelte-w9y5n9.svelte-w9y5n9:last-child{padding-bottom:10px}li.picked.svelte-w9y5n9.svelte-w9y5n9{background-color:#e7edff}li.picked.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#96a4c7;padding-left:4px}li.picked.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#96a4c7}li.selected.svelte-w9y5n9.svelte-w9y5n9{background-color:#f3f6ff}li.selected.svelte-w9y5n9.svelte-w9y5n9{animation:svelte-w9y5n9-backAndForth 5s linear infinite}li.selected.svelte-w9y5n9 .primary.svelte-w9y5n9{color:#2b8bfb}li.selected.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#a2adc7;padding-left:4px}li.selected.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#a2adc7}li.svelte-w9y5n9>img.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75}.texts.svelte-w9y5n9.svelte-w9y5n9{padding:0 17px 0 0}.texts.svelte-w9y5n9>.svelte-w9y5n9{white-space:nowrap;display:block;min-width:fit-content}.primary.svelte-w9y5n9.svelte-w9y5n9{font-weight:600}.secondary.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7;padding-left:4px}.line2.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7}@keyframes svelte-w9y5n9-backAndForth{0%{transform:translate(0)}10%{transform:translate(0)}45%{transform:translate(calc(-100% + 270px))}55%{transform:translate(calc(-100% + 270px))}90%{transform:translate(0)}to{transform:translate(0)}}div.svelte-1ocfouu{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);pointer-events:none;display:flex;align-items:center}.loading-icon.svelte-1ocfouu{animation:svelte-1ocfouu-rotate .8s infinite cubic-bezier(.45,.05,.55,.95)}@keyframes svelte-1ocfouu-rotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}svg.svelte-gzo3ar.svelte-gzo3ar{display:block;fill:#6b7c93;stroke:#6b7c93}.list-icon.svelte-gzo3ar.svelte-gzo3ar{grid-row:1/3;align-self:center;margin:8px}.in-map.svelte-gzo3ar.svelte-gzo3ar{height:30px}.maplibregl-canvas-container .marker-selected{z-index:1}.maplibregl-canvas-container svg.svelte-gzo3ar path.svelte-gzo3ar,.leaflet-map-pane svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#3170fe;stroke:#3170fe}.marker-selected svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#98b7ff;stroke:#3170fe}.marker-reverse svg.svelte-gzo3ar path.svelte-gzo3ar{fill:silver;stroke:gray}.marker-interactive{cursor:pointer!important}.maptiler-gc-popup>.maplibregl-popup-content{padding:2px 8px}svg.svelte-en2qvf{display:block;fill:var(--color-icon-button)}circle.svelte-1aq105l{stroke-width:1.875;fill:none}path.svelte-1aq105l{stroke-width:1.875;stroke-linecap:round}svg.svelte-1aq105l{display:block;stroke:var(--color-icon-button)}form.svelte-bz0zu3.svelte-bz0zu3{font-family:Open Sans,Ubuntu,Helvetica Neue,Arial,Helvetica,sans-serif;position:relative;background-color:#fff;z-index:10;border-radius:4px;margin:0;transition:max-width .25s;box-shadow:0 2px 5px #33335926;--color-text:#444952;--color-icon-button:#444952}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3:after,form.svelte-bz0zu3 .svelte-bz0zu3:before{box-sizing:border-box}form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:29px}form.can-collapse.svelte-bz0zu3 input.svelte-bz0zu3::placeholder{transition:opacity .25s;opacity:0}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3.svelte-bz0zu3:focus-within,form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px}form.svelte-bz0zu3 input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:focus-within input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:hover input.svelte-bz0zu3::placeholder{opacity:1}input.svelte-bz0zu3.svelte-bz0zu3{font:inherit;font-size:14px;flex-grow:1;min-height:29px;background-color:transparent;color:#444952;white-space:nowrap;overflow:hidden;border:0;margin:0;padding:0}input.svelte-bz0zu3.svelte-bz0zu3:focus{color:#444952;outline:0;outline:none;box-shadow:none}ul.svelte-bz0zu3.svelte-bz0zu3,div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{background-color:#fff;border-radius:4px;left:0;list-style:none;margin:0;padding:0;position:absolute;width:100%;top:calc(100% + 6px);overflow:hidden}ul.svelte-bz0zu3.svelte-bz0zu3{font-size:14px;line-height:16px;box-shadow:0 5px 10px #33335926}div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{font:inherit;line-height:18px;font-size:12px;display:flex;gap:16px}div.error.svelte-bz0zu3.svelte-bz0zu3{padding:16px;font-weight:600;color:#e25041;background-color:#fbeae8}div.error.svelte-bz0zu3 div.svelte-bz0zu3{flex-grow:1}div.error.svelte-bz0zu3 svg{flex-shrink:0;width:20px;height:20px}div.error.svelte-bz0zu3 button.svelte-bz0zu3{flex-shrink:0}div.error.svelte-bz0zu3 button.svelte-bz0zu3>svg{width:13px;fill:#e25041}div.error.svelte-bz0zu3 button.svelte-bz0zu3:hover svg,div.error.svelte-bz0zu3 button.svelte-bz0zu3:active svg{fill:#444952}div.no-results.svelte-bz0zu3.svelte-bz0zu3{padding:14px 24px 14px 16px;font-weight:400;color:#6b7c93;box-shadow:0 5px 10px #33335926}div.no-results.svelte-bz0zu3 svg{margin-top:4px;flex-shrink:0;width:20px;height:20px;width:30px;height:30px}.leaflet-bottom ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-left ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-right ul.options.svelte-bz0zu3.svelte-bz0zu3{top:auto;bottom:calc(100% + 6px)}button.svelte-bz0zu3.svelte-bz0zu3{padding:0;margin:0;border:0;background-color:transparent;height:auto;width:auto}button.svelte-bz0zu3.svelte-bz0zu3:hover{background-color:transparent}button.svelte-bz0zu3:hover svg,button.svelte-bz0zu3:active svg{fill:#2b8bfb}.input-group.svelte-bz0zu3.svelte-bz0zu3{display:flex;align-items:stretch;gap:7px;padding-inline:8px;border-radius:4px;overflow:hidden}.input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{outline:#2b8bfb solid 2px}.search-button.svelte-bz0zu3.svelte-bz0zu3{flex-shrink:0}.maplibregl-ctrl-geocoder:not(.maptiler-ctrl) .search-button svg{width:12px!important;transform:translate(.5px)}.clear-button-container.svelte-bz0zu3.svelte-bz0zu3{display:flex;display:none;position:relative;align-items:stretch}.clear-button-container.displayable.svelte-bz0zu3.svelte-bz0zu3{display:flex;flex-shrink:0}.maplibregl-ctrl-geocoder{position:relative;z-index:3}.maptiler-ctrl:not(:empty){box-shadow:none}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3{padding-inline:8px;border:white solid 2px}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{border:#2b8bfb solid 2px;outline:0;outline:none}.maptiler-ctrl form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:33px}.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:focus-within,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px} diff --git a/docs/articles/getting-started_files/radius-mode-1.0.0/radius-mode.js b/docs/articles/getting-started_files/radius-mode-1.0.0/radius-mode.js new file mode 100644 index 0000000..2b7b5bf --- /dev/null +++ b/docs/articles/getting-started_files/radius-mode-1.0.0/radius-mode.js @@ -0,0 +1,311 @@ +// Radius/Circle drawing mode for Mapbox GL Draw +// Creates a circle by drawing from center to edge +(function (MapboxDraw) { + const DrawLine = MapboxDraw.modes.draw_line_string; + + // Utility function to create a vertex feature + const createVertex = function (parentId, coordinates, path, selected) { + return { + type: "Feature", + properties: { + meta: "vertex", + parent: parentId, + coord_path: path, + active: selected ? "true" : "false" + }, + geometry: { + type: "Point", + coordinates: coordinates + } + }; + }; + + // Utility function to calculate distance between two points in kilometers + const calculateDistance = function (coord1, coord2) { + const lat1 = coord1[1]; + const lon1 = coord1[0]; + const lat2 = coord2[1]; + const lon2 = coord2[0]; + + const R = 6371; // Radius of the Earth in kilometers + const dLat = (lat2 - lat1) * Math.PI / 180; + const dLon = (lon2 - lon1) * Math.PI / 180; + const a = + Math.sin(dLat/2) * Math.sin(dLat/2) + + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * + Math.sin(dLon/2) * Math.sin(dLon/2); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + const distance = R * c; + + return distance; + }; + + // Utility function to create a GeoJSON circle + const createGeoJSONCircle = function (center, radiusInKm, parentId, points) { + points = points || 64; + + const coords = { + latitude: center[1], + longitude: center[0] + }; + + const km = radiusInKm; + const ret = []; + const distanceX = km / (111.32 * Math.cos((coords.latitude * Math.PI) / 180)); + const distanceY = km / 110.574; + + let theta, x, y; + for (let i = 0; i < points; i++) { + theta = (i / points) * (2 * Math.PI); + x = distanceX * Math.cos(theta); + y = distanceY * Math.sin(theta); + + ret.push([coords.longitude + x, coords.latitude + y]); + } + ret.push(ret[0]); + + return { + type: "Feature", + geometry: { + type: "Polygon", + coordinates: [ret] + }, + properties: { + parent: parentId, + meta: "radius" + } + }; + }; + + // Utility function to format distance for display + const getDisplayMeasurements = function (distanceKm) { + let metricUnits = "m"; + let metricFormat = "0,0"; + let metricMeasurement; + + let standardUnits = "feet"; + let standardFormat = "0,0"; + let standardMeasurement; + + metricMeasurement = distanceKm * 1000; // Convert to meters + if (metricMeasurement >= 1000) { + metricMeasurement = metricMeasurement / 1000; + metricUnits = "km"; + metricFormat = "0.00"; + } + + standardMeasurement = distanceKm * 1000 * 3.28084; // Convert to feet + if (standardMeasurement >= 5280) { + standardMeasurement = standardMeasurement / 5280; + standardUnits = "mi"; + standardFormat = "0.00"; + } + + // Simple number formatting (without numeral.js dependency) + const formatNumber = function(num, format) { + if (format === "0,0") { + return Math.round(num).toLocaleString(); + } else if (format === "0.00") { + return num.toFixed(2); + } + return num.toString(); + }; + + return { + metric: formatNumber(metricMeasurement, metricFormat) + " " + metricUnits, + standard: formatNumber(standardMeasurement, standardFormat) + " " + standardUnits + }; + }; + + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RadiusMode = Object.assign({}, DrawLine); + + RadiusMode.onSetup = function (opts) { + const line = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "LineString", + coordinates: [] + } + }); + + this.addFeature(line); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.activateUIButton("line"); + this.setActionableState({ trash: true }); + + return { + line: line, + currentVertexPosition: 0, + direction: "forward" + }; + }; + + RadiusMode.onClick = function (state, e) { + // This ends the drawing after the user creates a second point + if (state.currentVertexPosition === 1) { + // Update the second coordinate in place, don't add at position 0 + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + return this.changeMode("simple_select", { featureIds: [state.line.id] }); + } + + this.updateUIClasses({ mouse: "add" }); + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + + if (state.direction === "forward") { + state.currentVertexPosition += 1; + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + } else { + state.line.addCoordinate(0, e.lngLat.lng, e.lngLat.lat); + } + + return null; + }; + + RadiusMode.onMouseMove = function (state, e) { + if (state.currentVertexPosition === 1) { + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + } + }; + + // Creates the final geojson circle polygon + RadiusMode.onStop = function (state) { + doubleClickZoom.enable(this); + this.activateUIButton(); + + // Check to see if we've deleted this feature + if (this.getFeature(state.line.id) === undefined) return; + + if (state.line.isValid()) { + const lineGeoJson = state.line.toGeoJSON(); + const coords = lineGeoJson.geometry.coordinates; + + if (coords.length >= 2) { + // Calculate radius in kilometers + const radiusKm = calculateDistance(coords[0], coords[1]); + + // Create the circle polygon + const circleFeature = createGeoJSONCircle(coords[0], radiusKm, state.line.id); + + // Add radius property for reference + circleFeature.properties.radius = (radiusKm * 1000).toFixed(1); + + // Remove the meta property that was interfering + delete circleFeature.properties.meta; + delete circleFeature.properties.parent; + + // Delete the temporary line first + this.deleteFeature([state.line.id], { silent: true }); + + // Add the circle feature to the draw instance + const circleDrawFeature = this.newFeature(circleFeature); + this.addFeature(circleDrawFeature); + + this.map.fire("draw.create", { + features: [circleDrawFeature.toGeoJSON()] + }); + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + + this.changeMode("simple_select", {}, { silent: true }); + }; + + RadiusMode.toDisplayFeatures = function (state, geojson, display) { + const isActiveLine = geojson.properties.id === state.line.id; + geojson.properties.active = isActiveLine ? "true" : "false"; + + if (!isActiveLine) return display(geojson); + + // Only render the line if it has at least one real coordinate + if (geojson.geometry.coordinates.length < 2) return null; + + geojson.properties.meta = "feature"; + + // Display center vertex as a point feature + display(createVertex( + state.line.id, + geojson.geometry.coordinates[ + state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1 + ], + "" + (state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1), + false + )); + + // Display the line as it is drawn + display(geojson); + + const coords = geojson.geometry.coordinates; + if (coords.length >= 2) { + const distanceKm = calculateDistance(coords[0], coords[1]); + const displayMeasurements = getDisplayMeasurements(distanceKm); + + // Create custom feature for the current pointer position + const currentVertex = { + type: "Feature", + properties: { + meta: "currentPosition", + radiusMetric: displayMeasurements.metric, + radiusStandard: displayMeasurements.standard, + parent: state.line.id + }, + geometry: { + type: "Point", + coordinates: coords[1] + } + }; + display(currentVertex); + + // Create custom feature for radius circle + const center = coords[0]; + const circleFeature = createGeoJSONCircle(center, distanceKm, state.line.id); + display(circleFeature); + } + + return null; + }; + + RadiusMode.onTrash = function (state) { + this.deleteFeature([state.line.id], { silent: true }); + this.changeMode("simple_select"); + }; + + MapboxDraw.modes.draw_radius = RadiusMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/getting-started_files/rectangle-mode-1.0.0/rectangle-mode.js b/docs/articles/getting-started_files/rectangle-mode-1.0.0/rectangle-mode.js new file mode 100644 index 0000000..73af6d6 --- /dev/null +++ b/docs/articles/getting-started_files/rectangle-mode-1.0.0/rectangle-mode.js @@ -0,0 +1,124 @@ +// Rectangle drawing mode for Mapbox GL Draw +// Adapted from https://github.com/edgespatial/mapbox-gl-draw-rectangle-mode +(function (MapboxDraw) { + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RectangleMode = { + onSetup: function (opts) { + const rectangle = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "Polygon", + coordinates: [[]] + } + }); + + this.addFeature(rectangle); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.setActionableState({ trash: true }); + + return { + rectangle: rectangle + }; + }, + + onClick: function (state, e) { + // If we have a start point and click on a different point, complete the rectangle + if (state.startPoint && + (state.startPoint[0] !== e.lngLat.lng || state.startPoint[1] !== e.lngLat.lat)) { + this.updateUIClasses({ mouse: "pointer" }); + state.endPoint = [e.lngLat.lng, e.lngLat.lat]; + this.changeMode("simple_select", { featuresId: state.rectangle.id }); + return; + } + + // Set the start point + const startPoint = [e.lngLat.lng, e.lngLat.lat]; + state.startPoint = startPoint; + }, + + onMouseMove: function (state, e) { + // Update rectangle coordinates as the mouse moves + if (state.startPoint) { + const startX = state.startPoint[0]; + const startY = state.startPoint[1]; + const endX = e.lngLat.lng; + const endY = e.lngLat.lat; + + state.rectangle.updateCoordinate("0.0", startX, startY); + state.rectangle.updateCoordinate("0.1", endX, startY); + state.rectangle.updateCoordinate("0.2", endX, endY); + state.rectangle.updateCoordinate("0.3", startX, endY); + state.rectangle.updateCoordinate("0.4", startX, startY); + } + }, + + onKeyUp: function (state, e) { + if (e.keyCode === 27) { // Escape key + return this.changeMode("simple_select"); + } + }, + + onStop: function (state) { + doubleClickZoom.enable(this); + this.updateUIClasses({ mouse: "none" }); + this.activateUIButton(); + + if (this.getFeature(state.rectangle.id) !== undefined) { + // Remove the closing coordinate (duplicate of first) + state.rectangle.removeCoordinate("0.4"); + + if (state.rectangle.isValid()) { + this.map.fire("draw.create", { + features: [state.rectangle.toGeoJSON()] + }); + } else { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select", {}, { silent: true }); + } + } + }, + + toDisplayFeatures: function (state, geojson, display) { + const isActiveRectangle = geojson.properties.id === state.rectangle.id; + geojson.properties.active = isActiveRectangle ? "true" : "false"; + + if (!isActiveRectangle) { + return display(geojson); + } + + // Only display the rectangle if we have started drawing + if (state.startPoint) { + return display(geojson); + } + }, + + onTrash: function (state) { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select"); + } + }; + + MapboxDraw.modes.draw_rectangle = RectangleMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/getting-started_files/turf-7.2.0/turf.min.js b/docs/articles/getting-started_files/turf-7.2.0/turf.min.js new file mode 100644 index 0000000..635896d --- /dev/null +++ b/docs/articles/getting-started_files/turf-7.2.0/turf.min.js @@ -0,0 +1,37 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).turf={})}(this,(function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}function u(t,e,n){return(e=y(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function l(t){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},l(t)}function h(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&p(t,e)}function c(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(c=function(){return!!t})()}function f(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}function g(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function p(t,e){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},p(t,e)}function v(t,e){return n(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,o,s,a=[],u=!0,l=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);u=!0);}catch(t){l=!0,i=t}finally{try{if(!u&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw i}}return a}}(t,e)||_(t,e)||g()}function d(t){return function(t){if(Array.isArray(t))return e(t)}(t)||f(t)||_(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function m(t){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},m(t)}function _(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var x=6371008.8,E={centimeters:100*x,centimetres:100*x,degrees:360/(2*Math.PI),feet:3.28084*x,inches:39.37*x,kilometers:x/1e3,kilometres:x/1e3,meters:x,metres:x,miles:x/1609.344,millimeters:1e3*x,millimetres:1e3*x,nauticalmiles:x/1852,radians:1,yards:1.0936*x},k={acres:247105e-9,centimeters:1e4,centimetres:1e4,feet:10.763910417,hectares:1e-4,inches:1550.003100006,kilometers:1e-6,kilometres:1e-6,meters:1,metres:1,miles:386e-9,nauticalmiles:2.9155334959812285e-7,millimeters:1e6,millimetres:1e6,yards:1.195990046};function b(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={type:"Feature"};return(0===n.id||n.id)&&(r.id=n.id),n.bbox&&(r.bbox=n.bbox),r.properties=e||{},r.geometry=t,r}function w(t,e){switch(t){case"Point":return I(e).geometry;case"LineString":return L(e).geometry;case"Polygon":return S(e).geometry;case"MultiPoint":return O(e).geometry;case"MultiLineString":return T(e).geometry;case"MultiPolygon":return R(e).geometry;default:throw new Error(t+" is invalid")}}function I(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("coordinates is required");if(!Array.isArray(t))throw new Error("coordinates must be an Array");if(t.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!U(t[0])||!U(t[1]))throw new Error("coordinates must contain numbers");return b({type:"Point",coordinates:t},e,n)}function N(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return I(t,e)})),n)}function S(t,e){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=a(t);try{for(i.s();!(n=i.n()).done;){var o=n.value;if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(var s=0;s2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return S(t,e)})),n)}function L(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(t.length<2)throw new Error("coordinates must be an array of two or more positions");return b({type:"LineString",coordinates:t},e,n)}function P(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return L(t,e)})),n)}function C(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={type:"FeatureCollection"};return e.id&&(n.id=e.id),e.bbox&&(n.bbox=e.bbox),n.features=t,n}function T(t,e){return b({type:"MultiLineString",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function O(t,e){return b({type:"MultiPoint",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function R(t,e){return b({type:"MultiPolygon",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function A(t,e){return b({type:"GeometryCollection",geometries:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function D(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e&&!(e>=0))throw new Error("precision must be a positive number");var n=Math.pow(10,e||0);return Math.round(t*n)/n}function F(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t*n}function q(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t/n}function V(t,e){return Y(q(t,e))}function G(t){var e=t%360;return e<0&&(e+=360),e}function B(t){return(t%=360)>180?t-360:t<-180?t+360:t}function Y(t){return 180*(t%(2*Math.PI))/Math.PI}function z(t){return t%360*Math.PI/180}function j(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("length must be a positive number");return F(q(t,e),n)}function X(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"meters",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("area must be a positive number");var r=k[e];if(!r)throw new Error("invalid original units");var i=k[n];if(!i)throw new Error("invalid final units");return t/r*i}function U(t){return!isNaN(t)&&null!==t&&!Array.isArray(t)}function Z(t){return null!==t&&"object"===m(t)&&!Array.isArray(t)}function H(t){if(!t)throw new Error("bbox is required");if(!Array.isArray(t))throw new Error("bbox must be an Array");if(4!==t.length&&6!==t.length)throw new Error("bbox must be an Array of 4 or 6 numbers");t.forEach((function(t){if(!U(t))throw new Error("bbox must only contain numbers")}))}function W(t){if(!t)throw new Error("id is required");if(-1===["string","number"].indexOf(m(t)))throw new Error("id must be a number or a string")}var J=Object.freeze({__proto__:null,areaFactors:k,azimuthToBearing:B,bearingToAzimuth:G,convertArea:X,convertLength:j,degreesToRadians:z,earthRadius:x,factors:E,feature:b,featureCollection:C,geometry:w,geometryCollection:A,isNumber:U,isObject:Z,lengthToDegrees:V,lengthToRadians:q,lineString:L,lineStrings:P,multiLineString:T,multiPoint:O,multiPolygon:R,point:I,points:N,polygon:S,polygons:M,radiansToDegrees:Y,radiansToLength:F,round:D,validateBBox:H,validateId:W});function K(t){if(!t)throw new Error("coord is required");if(!Array.isArray(t)){if("Feature"===t.type&&null!==t.geometry&&"Point"===t.geometry.type)return d(t.geometry.coordinates);if("Point"===t.type)return d(t.coordinates)}if(Array.isArray(t)&&t.length>=2&&!Array.isArray(t[0])&&!Array.isArray(t[1]))return d(t);throw new Error("coord must be GeoJSON Point or an Array of numbers")}function Q(t){if(Array.isArray(t))return t;if("Feature"===t.type){if(null!==t.geometry)return t.geometry.coordinates}else if(t.coordinates)return t.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function $(t){if(t.length>1&&U(t[0])&&U(t[1]))return!0;if(Array.isArray(t[0])&&t[0].length)return $(t[0]);throw new Error("coordinates must only contain numbers")}function tt(t,e,n){if(!e||!n)throw new Error("type and name required");if(!t||t.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.type)}function et(t,e,n){if(!t)throw new Error("No feature passed");if(!n)throw new Error(".featureOf() requires a name");if(!t||"Feature"!==t.type||!t.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!t.geometry||t.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.geometry.type)}function nt(t,e,n){if(!t)throw new Error("No featureCollection passed");if(!n)throw new Error(".collectionOf() requires a name");if(!t||"FeatureCollection"!==t.type)throw new Error("Invalid input to "+n+", FeatureCollection required");var r,i=a(t.features);try{for(i.s();!(r=i.n()).done;){var o=r.value;if(!o||"Feature"!==o.type||!o.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!o.geometry||o.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+o.geometry.type)}}catch(t){i.e(t)}finally{i.f()}}function rt(t){return"Feature"===t.type?t.geometry:t}function it(t,e){return"FeatureCollection"===t.type?"FeatureCollection":"GeometryCollection"===t.type?"GeometryCollection":"Feature"===t.type&&null!==t.geometry?t.geometry.type:t.type}var ot=Object.freeze({__proto__:null,collectionOf:nt,containsNumber:$,featureOf:et,geojsonType:tt,getCoord:K,getCoords:Q,getGeom:rt,getType:it});function st(t,e){if(!0===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final)return function(t,e){var n=st(e,t);return n=(n+180)%360}(t,e);var n=K(t),r=K(e),i=z(n[0]),o=z(r[0]),s=z(n[1]),a=z(r[1]),u=Math.sin(o-i)*Math.cos(a),l=Math.cos(s)*Math.sin(a)-Math.sin(s)*Math.cos(a)*Math.cos(o-i);return Y(Math.atan2(u,l))}function at(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=K(t),o=z(i[0]),s=z(i[1]),a=z(n),u=q(e,r.units),l=Math.asin(Math.sin(s)*Math.cos(u)+Math.cos(s)*Math.sin(u)*Math.cos(a));return I([Y(o+Math.atan2(Math.sin(a)*Math.sin(u)*Math.cos(s),Math.cos(u)-Math.sin(s)*Math.sin(l))),Y(l)],r.properties)}function ut(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e),o=z(i[1]-r[1]),s=z(i[0]-r[0]),a=z(r[1]),u=z(i[1]),l=Math.pow(Math.sin(o/2),2)+Math.pow(Math.sin(s/2),2)*Math.cos(a)*Math.cos(u);return F(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)),n.units)}function lt(t,e){var n;return(n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final?ht(K(e),K(t)):ht(K(t),K(e)))>180?-(360-n):n}function ht(t,e){var n=z(t[1]),r=z(e[1]),i=z(e[0]-t[0]);i>Math.PI&&(i-=2*Math.PI),i<-Math.PI&&(i+=2*Math.PI);var o=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(n/2+Math.PI/4));return(Y(Math.atan2(i,o))+360)%360}function ct(t,e,n){if(null!==t)for(var r,i,o,s,a,u,l,h,c=0,f=0,g=t.type,p="FeatureCollection"===g,v="Feature"===g,d=p?t.features.length:1,y=0;ya||f>u||g>l)return s=o,a=n,u=f,l=g,void(i=0);var p=L([s,o],t.properties);if(!1===e(p,n,r,g,i))return!1;i++,s=o}))&&void 0}}}))}function bt(t,e,n){var r=n,i=!1;return kt(t,(function(t,o,s,a,u){r=!1===i&&void 0===n?t:e(r,t,o,s,a,u),i=!0})),r}function wt(t,e){if(!t)throw new Error("geojson is required");xt(t,(function(t,n,r){if(null!==t.geometry){var i=t.geometry.type,o=t.geometry.coordinates;switch(i){case"LineString":if(!1===e(t,n,r,0,0))return!1;break;case"Polygon":for(var s=0;s0){e+=Math.abs(Ot(t[0]));for(var n=1;n=e?(r+2)%e:r+2],a=i[0]*Tt,u=o[1]*Tt;n+=(s[0]*Tt-a)*Math.sin(u),r++}return n*Ct}function Rt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=t.bbox&&!0!==e.recompute)return t.bbox;var n=[1/0,1/0,-1/0,-1/0];return ct(t,(function(t){n[0]>t[0]&&(n[0]=t[0]),n[1]>t[1]&&(n[1]=t[1]),n[2]e[2]&&(n|=2),t[1]e[3]&&(n|=8),n}function qt(t,e){var n,r=[],i=a(t);try{for(i.s();!(n=i.n()).done;){var o=At(n.value,e);o.length>0&&(o[0][0]===o[o.length-1][0]&&o[0][1]===o[o.length-1][1]||o.push(o[0]),o.length>=4&&r.push(o))}}catch(t){i.e(t)}finally{i.f()}return r}function Vt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Number(t[0]),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]);if(6===t.length)throw new Error("@turf/bbox-polygon does not support BBox with 6 positions");var s=[n,r];return S([[s,[i,r],[i,o],[n,o],s]],e.properties,{bbox:t,id:e.id})}var Gt=function(){return s((function t(e){i(this,t),this.points=e.points||[],this.duration=e.duration||1e4,this.sharpness=e.sharpness||.85,this.centers=[],this.controls=[],this.stepLength=e.stepLength||60,this.length=this.points.length,this.delay=0;for(var n=0;nt&&(e.push(r),n=i)}return e}},{key:"vector",value:function(t){var e=this.pos(t+10),n=this.pos(t-10);return{angle:180*Math.atan2(e.y-n.y,e.x-n.x)/3.14,speed:Math.sqrt((n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y)+(n.z-e.z)*(n.z-e.z))}}},{key:"pos",value:function(t){var e=t-this.delay;e<0&&(e=0),e>this.duration&&(e=this.duration-1);var n=e/this.duration;if(n>=1)return this.points[this.length-1];var r=Math.floor((this.points.length-1)*n);return function(t,e,n,r,i){var o=function(t){var e=t*t,n=e*t;return[n,3*e*(1-t),3*t*(1-t)*(1-t),(1-t)*(1-t)*(1-t)]}(t),s={x:i.x*o[0]+r.x*o[1]+n.x*o[2]+e.x*o[3],y:i.y*o[0]+r.y*o[1]+n.y*o[2]+e.y*o[3],z:i.z*o[0]+r.z*o[1]+n.z*o[2]+e.z*o[3]};return s}((this.length-1)*n-r,this.points[r],this.controls[r][1],this.controls[r+1][0],this.points[r+1])}}])}();function Bt(t){for(var e,n,r=Q(t),i=0,o=1;o0}function Yt(t,e){for(var n=0,r=0,i=0,o=0,s=0,a=0,u=0,l=0,h=null,c=null,f=t[0],g=t[1],p=e.length;n0&&l>0)a=l,s=(h=c)[0]-f;else{if(u=c[0]-t[0],l>0&&a<=0){if((o=s*l-u*a)>0)i+=1;else if(0===o)return 0}else if(a>0&&l<=0){if((o=s*l-u*a)<0)i+=1;else if(0===o)return 0}else if(0===l&&a<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&l<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&0===l){if(u<=0&&s>=0)return 0;if(s<=0&&u>=0)return 0}h=c,a=l,s=u}}return i%2!=0}function zt(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("point is required");if(!e)throw new Error("polygon is required");var r=K(t),i=rt(e),o=i.type,s=e.bbox,a=i.coordinates;if(s&&!1===function(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}(r,s))return!1;"Polygon"===o&&(a=[a]);for(var u=!1,l=0;l2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=Q(e),o=0;oi)return!1}else if(0!==g)return!1;return Math.abs(c)===Math.abs(f)&&0===Math.abs(c)?!r&&(n[0]===t[0]&&n[1]===t[1]):r?"start"===r?Math.abs(c)>=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o0?u<=s&&s=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o<=l:l<=o&&o<=a:f>0?u<=s&&s<=h:h<=s&&s<=u}function Ut(t,e){if("Feature"===t.type&&null===t.geometry)return!1;if("Feature"===e.type&&null===e.geometry)return!1;if(!Zt(Rt(t),Rt(e)))return!1;var n,r=a(rt(e).coordinates);try{for(r.s();!(n=r.n()).done;){var i,o=a(n.value);try{for(o.s();!(i=o.n()).done;){if(!zt(i.value,t))return!1}}catch(t){o.e(t)}finally{o.f()}}}catch(t){r.e(t)}finally{r.f()}return!0}function Zt(t,e){return!(t[0]>e[0])&&(!(t[2]e[1])&&!(t[3]0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Kt;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function Kt(t,e){return te?1:0}function Qt(t,e){return t.p.x>e.p.x?1:t.p.xe.p.y?1:-1:1}function $t(t,e){return t.rightSweepEvent.p.x>e.rightSweepEvent.p.x?1:t.rightSweepEvent.p.x0?(h.isLeftEndpoint=!0,l.isLeftEndpoint=!1):(l.isLeftEndpoint=!0,h.isLeftEndpoint=!1),e.push(l),e.push(h),s=a,re+=1}}ee+=1}var oe=s((function t(e){i(this,t),this.leftSweepEvent=e,this.rightSweepEvent=e.otherEvent}));function se(t,e){if(null===t||null===e)return!1;if(t.leftSweepEvent.ringId===e.leftSweepEvent.ringId&&(t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.rightSweepEvent)||t.leftSweepEvent.isSamePoint(e.leftSweepEvent)||t.leftSweepEvent.isSamePoint(e.rightSweepEvent)))return!1;var n=t.leftSweepEvent.p.x,r=t.leftSweepEvent.p.y,i=t.rightSweepEvent.p.x,o=t.rightSweepEvent.p.y,s=e.leftSweepEvent.p.x,a=e.leftSweepEvent.p.y,u=e.rightSweepEvent.p.x,l=e.rightSweepEvent.p.y,h=(l-a)*(i-n)-(u-s)*(o-r),c=(u-s)*(r-a)-(l-a)*(n-s),f=(i-n)*(r-a)-(o-r)*(n-s);if(0===h)return!1;var g=c/h,p=f/h;return g>=0&&g<=1&&p>=0&&p<=1&&[n+g*(i-n),r+g*(o-r)]}var ae=function(t,e){var n=new Jt([],Qt);return function(t,e){if("FeatureCollection"===t.type)for(var n=t.features,r=0;r2&&void 0!==arguments[2]?arguments[2]:{},r=n.removeDuplicates,i=void 0===r||r,o=n.ignoreSelfIntersections,s=void 0===o||o,a=[];"FeatureCollection"===t.type?a=a.concat(t.features):"Feature"===t.type?a.push(t):"LineString"!==t.type&&"Polygon"!==t.type&&"MultiLineString"!==t.type&&"MultiPolygon"!==t.type||a.push(b(t)),"FeatureCollection"===e.type?a=a.concat(e.features):"Feature"===e.type?a.push(e):"LineString"!==e.type&&"Polygon"!==e.type&&"MultiLineString"!==e.type&&"MultiPolygon"!==e.type||a.push(b(e));var u=ae(C(a),s),l=[];if(i){var h={};u.forEach((function(t){var e=t.join(",");h[e]||(h[e]=!0,l.push(t))}))}else l=u;return C(l.map((function(t){return I(t)})))}function le(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t);switch(e.properties||"Feature"!==t.type||(e.properties=t.properties),n.type){case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{};return he(r,i)}(n,e);case"MultiPolygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{},o=[];return r.forEach((function(t){o.push(he(t,i))})),C(o)}(n,e);default:throw new Error("invalid poly")}}function he(t,e){return t.length>1?T(t,e):L(t[0],e)}function ce(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;switch(i){case"MultiPoint":switch(o){case"LineString":return fe(n,r);case"Polygon":return pe(n,r);default:throw new Error("feature2 "+o+" geometry not supported")}case"LineString":switch(o){case"MultiPoint":return fe(r,n);case"LineString":return function(t,e){if(ue(t,e).features.length>0)for(var n=0;n0}function pe(t,e){for(var n=!1,r=!1,i=t.coordinates.length,o=0;o=Math.abs(a)?s>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:a>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1]:Math.abs(s)>=Math.abs(a)?s>0?t[0]0?t[1]2&&void 0!==arguments[2]?arguments[2]:{ignoreSelfIntersections:!0}).ignoreSelfIntersections,r=void 0===n||n,i=!0;return xt(t,(function(t){xt(e,(function(e){if(!1===i)return!1;i=function(t,e,n){switch(t.type){case"Point":switch(e.type){case"Point":return r=t.coordinates,i=e.coordinates,!(r[0]===i[0]&&r[1]===i[1]);case"LineString":return!ye(e,t);case"Polygon":return!zt(t,e)}break;case"LineString":switch(e.type){case"Point":return!ye(t,e);case"LineString":return!function(t,e,n){var r=ue(t,e,{ignoreSelfIntersections:n});if(r.features.length>0)return!0;return!1}(t,e,n);case"Polygon":return!me(e,t,n)}break;case"Polygon":switch(e.type){case"Point":return!zt(e,t);case"LineString":return!me(t,e,n);case"Polygon":return!function(t,e,n){var r,i=a(t.coordinates[0]);try{for(i.s();!(r=i.n()).done;){if(zt(r.value,e))return!0}}catch(t){i.e(t)}finally{i.f()}var o,s=a(e.coordinates[0]);try{for(s.s();!(o=s.n()).done;){if(zt(o.value,t))return!0}}catch(t){s.e(t)}finally{s.f()}var u=ue(le(t),le(e),{ignoreSelfIntersections:n});if(u.features.length>0)return!0;return!1}(e,t,n)}}var r,i;return!1}(t.geometry,e.geometry,r)}))})),i}function ye(t,e){for(var n=0;n0}function _e(t,e,n){var r=n[0]-t[0],i=n[1]-t[1],o=e[0]-t[0],s=e[1]-t[1];return 0==r*s-i*o&&(Math.abs(o)>=Math.abs(s)?o>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:s>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1])}var xe=Object.defineProperty,Ee=function(t,e){return xe(t,"name",{value:e,configurable:!0})},ke=function(){return s((function t(e){var n,r,o;i(this,t),this.direction=!1,this.compareProperties=!0,this.precision=Math.pow(10,-(null!=(n=null==e?void 0:e.precision)?n:17)),this.direction=null!=(r=null==e?void 0:e.direction)&&r,this.compareProperties=null==(o=null==e?void 0:e.compareProperties)||o}),[{key:"compare",value:function(t,e){var n=this;if(t.type!==e.type)return!1;if(!we(t,e))return!1;switch(t.type){case"Point":return this.compareCoord(t.coordinates,e.coordinates);case"LineString":return this.compareLine(t.coordinates,e.coordinates);case"Polygon":return this.comparePolygon(t,e);case"GeometryCollection":return this.compareGeometryCollection(t,e);case"Feature":return this.compareFeature(t,e);case"FeatureCollection":return this.compareFeatureCollection(t,e);default:if(t.type.startsWith("Multi")){var r=Ie(t),i=Ie(e);return r.every((function(t){return i.some((function(e){return n.compare(t,e)}))}))}}return!1}},{key:"compareCoord",value:function(t,e){var n=this;return t.length===e.length&&t.every((function(t,r){return Math.abs(t-e[r])2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!we(t,e))return!1;var i=t,o=e;if(r&&!this.compareCoord(i[0],o[0])){var s=this.fixStartIndex(o,i);if(!s)return!1;o=s}var a=this.compareCoord(i[n],o[n]);return this.direction||a?this.comparePath(i,o):!!this.compareCoord(i[n],o[o.length-(1+n)])&&this.comparePath(i.slice().reverse(),o)}},{key:"fixStartIndex",value:function(t,e){for(var n,r=-1,i=0;i=0&&(n=[].concat(t.slice(r,t.length),t.slice(1,r+1))),n}},{key:"comparePath",value:function(t,e){var n=this;return t.every((function(t,r){return n.compareCoord(t,e[r])}))}},{key:"comparePolygon",value:function(t,e){var n=this;if(this.compareLine(t.coordinates[0],e.coordinates[0],1,!0)){var r=t.coordinates.slice(1,t.coordinates.length),i=e.coordinates.slice(1,e.coordinates.length);return r.every((function(t){return i.some((function(e){return n.compareLine(t,e,1,!0)}))}))}return!1}},{key:"compareGeometryCollection",value:function(t,e){var n=this;return we(t.geometries,e.geometries)&&this.compareBBox(t,e)&&t.geometries.every((function(t,r){return n.compare(t,e.geometries[r])}))}},{key:"compareFeature",value:function(t,e){return t.id===e.id&&(!this.compareProperties||Se(t.properties,e.properties))&&this.compareBBox(t,e)&&this.compare(t.geometry,e.geometry)}},{key:"compareFeatureCollection",value:function(t,e){var n=this;return we(t.features,e.features)&&this.compareBBox(t,e)&&t.features.every((function(t,r){return n.compare(t,e.features[r])}))}},{key:"compareBBox",value:function(t,e){return Boolean(!t.bbox&&!e.bbox)||!(!t.bbox||!e.bbox)&&this.compareCoord(t.bbox,e.bbox)}}])}();Ee(ke,"GeojsonEquality");var be=ke;function we(t,e){return t.coordinates?t.coordinates.length===e.coordinates.length:t.length===e.length}function Ie(t){return t.coordinates.map((function(e){return{type:t.type.replace("Multi",""),coordinates:e}}))}function Ne(t,e,n){return new be(n).compare(t,e)}function Se(t,e){if(null===t&&null===e)return!0;if(null===t||null===e)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(var i=0,o=n;i1&&void 0!==arguments[1]?arguments[1]:{},n="object"===m(e)?e.mutate:e;if(!t)throw new Error("geojson is required");var r=it(t),i=[];switch(r){case"LineString":i=Pe(t,r);break;case"MultiLineString":case"Polygon":Q(t).forEach((function(t){i.push(Pe(t,r))}));break;case"MultiPolygon":Q(t).forEach((function(t){var e=[];t.forEach((function(t){e.push(Pe(t,r))})),i.push(e)}));break;case"Point":return t;case"MultiPoint":var o={};Q(t).forEach((function(t){var e=t.join("-");Object.prototype.hasOwnProperty.call(o,e)||(i.push(t),o[e]=!0)}));break;default:throw new Error(r+" geometry not supported")}return t.coordinates?!0===n?(t.coordinates=i,t):{type:r,coordinates:i}:!0===n?(t.geometry.coordinates=i,t):b({type:r,coordinates:i},t.properties,{bbox:t.bbox,id:t.id})}function Pe(t,e){var n=Q(t);if(2===n.length&&!Ce(n[0],n[1]))return n;var r=[],i=n.length-1,o=r.length;r.push(n[0]);for(var s=1;s2&&Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1))}if(r.push(n[n.length-1]),o=r.length,("Polygon"===e||"MultiPolygon"===e)&&Ce(n[0],n[n.length-1])&&o<4)throw new Error("invalid polygon");return"LineString"===e&&o<3||Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1),r}function Ce(t,e){return t[0]===e[0]&&t[1]===e[1]}function Te(t,e,n){var r=n[0],i=n[1],o=t[0],s=t[1],a=e[0],u=e[1],l=a-o,h=u-s;return 0===(r-o)*h-(i-s)*l&&(Math.abs(l)>=Math.abs(h)?l>0?o<=r&&r<=a:a<=r&&r<=o:h>0?s<=i&&i<=u:u<=i&&i<=s)}function Oe(t,e){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).ignoreSelfIntersections,r=void 0===n||n,i=!1;return xt(t,(function(t){xt(e,(function(e){if(!0===i)return!0;i=!de(t.geometry,e.geometry,{ignoreSelfIntersections:r})}))})),i}function Re(t,e,n,r,i){Ae(t,e,n||0,r||t.length-1,i||Fe)}function Ae(t,e,n,r,i){for(;r>n;){if(r-n>600){var o=r-n+1,s=e-n+1,a=Math.log(o),u=.5*Math.exp(2*a/3),l=.5*Math.sqrt(a*u*(o-u)/o)*(s-o/2<0?-1:1);Ae(t,e,Math.max(n,Math.floor(e-s*u/o+l)),Math.min(r,Math.floor(e+(o-s)*u/o+l)),i)}var h=t[e],c=n,f=r;for(De(t,n,e),i(t[r],h)>0&&De(t,n,r);c0;)f--}0===i(t[n],h)?De(t,n,f):De(t,++f,r),f<=e&&(n=f+1),e<=f&&(r=f-1)}}function De(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function Fe(t,e){return te?1:0}var qe=function(){return s((function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:9;i(this,t),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}),[{key:"all",value:function(){return this._all(this.data,[])}},{key:"search",value:function(t){var e=this.data,n=[];if(!He(t,e))return n;for(var r=this.toBBox,i=[];e;){for(var o=0;o=0&&i[e].children.length>this._maxEntries;)this._split(i,e),e--;this._adjustParentBBoxes(r,i,e)}},{key:"_split",value:function(t,e){var n=t[e],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=We(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,Ge(n,this.toBBox),Ge(s,this.toBBox),e?t[e-1].children.push(s):this._splitRoot(n,s)}},{key:"_splitRoot",value:function(t,e){this.data=We([t,e]),this.data.height=t.height+1,this.data.leaf=!1,Ge(this.data,this.toBBox)}},{key:"_chooseSplitIndex",value:function(t,e,n){for(var r,i,o,s,a,u,l,h=1/0,c=1/0,f=e;f<=n-e;f++){var g=Be(t,0,f,this.toBBox),p=Be(t,f,n,this.toBBox),v=(i=g,o=p,s=void 0,a=void 0,u=void 0,l=void 0,s=Math.max(i.minX,o.minX),a=Math.max(i.minY,o.minY),u=Math.min(i.maxX,o.maxX),l=Math.min(i.maxY,o.maxY),Math.max(0,u-s)*Math.max(0,l-a)),d=Xe(g)+Xe(p);v=e;h--){var c=t.children[h];Ye(s,t.leaf?i(c):c),a+=Ue(s)}return a}},{key:"_adjustParentBBoxes",value:function(t,e,n){for(var r=n;r>=0;r--)Ye(e[r],t)}},{key:"_condense",value:function(t){for(var e,n=t.length-1;n>=0;n--)0===t[n].children.length?n>0?(e=t[n-1].children).splice(e.indexOf(t[n]),1):this.clear():Ge(t[n],this.toBBox)}}])}();function Ve(t,e,n){if(!n)return e.indexOf(t);for(var r=0;r=t.minX&&e.maxY>=t.minY}function We(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Je(t,e,n,r,i){for(var o=[e,n];o.length;)if(!((n=o.pop())-(e=o.pop())<=r)){var s=e+Math.ceil((n-e)/r/2)*r;Re(t,s,e,n,i),o.push(e,s,s,n)}}var Ke=Object.freeze({__proto__:null,default:qe});function Qe(t){var e=new qe(t);return e.insert=function(t){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.insert.call(this,t)},e.load=function(t){var e=[];return Array.isArray(t)?t.forEach((function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})):vt(t,(function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})),qe.prototype.load.call(this,e)},e.remove=function(t,e){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.remove.call(this,t,e)},e.clear=function(){return qe.prototype.clear.call(this)},e.search=function(t){return C(qe.prototype.search.call(this,this.toBBox(t)))},e.collides=function(t){return qe.prototype.collides.call(this,this.toBBox(t))},e.all=function(){return C(qe.prototype.all.call(this))},e.toJSON=function(){return qe.prototype.toJSON.call(this)},e.fromJSON=function(t){return qe.prototype.fromJSON.call(this,t)},e.toBBox=function(t){var e;if(t.bbox)e=t.bbox;else if(Array.isArray(t)&&4===t.length)e=t;else if(Array.isArray(t)&&6===t.length)e=[t[0],t[1],t[3],t[4]];else if("Feature"===t.type)e=Rt(t);else{if("FeatureCollection"!==t.type)throw new Error("invalid geojson");e=Rt(t)}return{minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}},e}function $e(t){if(!t)throw new Error("geojson is required");var e=[];return xt(t,(function(t){!function(t,e){var n=[],r=t.geometry;if(null!==r){switch(r.type){case"Polygon":n=Q(r);break;case"LineString":n=[Q(r)]}n.forEach((function(n){var r=function(t,e){var n=[];return t.reduce((function(t,r){var i=L([t,r],e);return i.bbox=function(t,e){var n=t[0],r=t[1],i=e[0],o=e[1],s=ni?n:i,l=r>o?r:o;return[s,a,u,l]}(t,r),n.push(i),r})),n}(n,t.properties);r.forEach((function(t){t.id=e.length,e.push(t)}))}))}}(t,e)})),C(e)}var tn,en,nn=Object.defineProperty,rn=Object.defineProperties,on=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertySymbols,an=Object.prototype.hasOwnProperty,un=Object.prototype.propertyIsEnumerable,ln=function(t,e,n){return e in t?nn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},hn=function(t,e){for(var n in e||(e={}))an.call(e,n)&&ln(t,n,e[n]);if(sn){var r,i=a(sn(e));try{for(i.s();!(r=i.n()).done;){n=r.value;un.call(e,n)&&ln(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},cn=function(t,e){return rn(t,on(e))};function fn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t||!e)throw new Error("lines and pt are required arguments");var r=K(e),i=I([1/0,1/0],{dist:1/0,index:-1,multiFeatureIndex:-1,location:-1}),o=0;return xt(t,(function(t,s,a){for(var u=Q(t),l=0;lR||pn(p,f)>R?ut(dn(f),dn(g))<=ut(dn(f),dn(p))?[dn(g),!0,!1]:[dn(p),!1,!0]:[dn(f),!1,!1]}function mn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function _n(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var n=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,r.get?r:{enumerable:!0,get:function(){return t[e]}})})),n}var xn=(en||(en=1,tn=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==m(e)&&"object"==m(n)){if(e.constructor!==n.constructor)return!1;var r,i,o;if(Array.isArray(e)){if((r=e.length)!=n.length)return!1;for(i=r;0!=i--;)if(!t(e[i],n[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((r=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(i=r;0!=i--;)if(!Object.prototype.hasOwnProperty.call(n,o[i]))return!1;for(i=r;0!=i--;){var s=o[i];if(!t(e[s],n[s]))return!1}return!0}return e!=e&&n!=n}),tn),En=mn(xn);function kn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r,i=n.tolerance||0,o=[],s=Qe(),a=$e(t);s.load(a);var u=[];return kt(e,(function(t){var e=!1;t&&(vt(s.search(t),(function(n){if(!1===e){var o=Q(t).sort(),s=Q(n).sort();if(En(o,s))e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(o[0],n)&&jt(o[1],n):fn(n,o[0]).properties.dist<=i&&fn(n,o[1]).properties.dist<=i)e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(s[0],t)&&jt(s[1],t):fn(t,s[0]).properties.dist<=i&&fn(t,s[1]).properties.dist<=i)if(r){var a=bn(r,n);a?r=a:u.push(n)}else r=n}})),!1===e&&r&&(o.push(r),u.length&&(o=o.concat(u),u=[]),r=void 0))})),r&&o.push(r),C(o)}function bn(t,e){var n=Q(e),r=Q(t),i=r[0],o=r[r.length-1],s=t.geometry.coordinates;if(En(n[0],i))s.unshift(n[1]);else if(En(n[0],o))s.push(n[1]);else if(En(n[1],i))s.unshift(n[0]);else{if(!En(n[1],o))return;s.push(n[0])}return t}function wn(t,e){var n=G(lt(t[0],t[1])),r=G(lt(e[0],e[1]));return n===r||(r-n)%180==0}function In(t,e){if(t.geometry&&t.geometry.type)return t.geometry.type;if(t.type)return t.type;throw new Error("Invalid GeoJSON object for "+e)}function Nn(t,e){return!!Sn(e.coordinates[0],t.coordinates)||!!Sn(e.coordinates[e.coordinates.length-1],t.coordinates)}function Sn(t,e){return t[0]===e[0]&&t[1]===e[1]}function Mn(t){return t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]}function Ln(t){for(var e=0;ee[0])&&(!(t[2]e[1])&&!(t[3]1&&void 0!==arguments[1]?arguments[1]:{},n=Rt(t);return I([(n[0]+n[2])/2,(n[1]+n[3])/2],e.properties,e)}var Dn,Fn={exports:{}};var qn=(Dn||(Dn=1,function(t,e){t.exports=function(){function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}var y=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getEndCapStyle",value:function(){return this._endCapStyle}},{key:"isSingleSided",value:function(){return this._isSingleSided}},{key:"setQuadrantSegments",value:function(t){this._quadrantSegments=t,0===this._quadrantSegments&&(this._joinStyle=e.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=e.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),t<=0&&(this._quadrantSegments=1),this._joinStyle!==e.JOIN_ROUND&&(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS)}},{key:"getJoinStyle",value:function(){return this._joinStyle}},{key:"setJoinStyle",value:function(t){this._joinStyle=t}},{key:"setSimplifyFactor",value:function(t){this._simplifyFactor=t<0?0:t}},{key:"getSimplifyFactor",value:function(){return this._simplifyFactor}},{key:"getQuadrantSegments",value:function(){return this._quadrantSegments}},{key:"setEndCapStyle",value:function(t){this._endCapStyle=t}},{key:"getMitreLimit",value:function(){return this._mitreLimit}},{key:"setMitreLimit",value:function(t){this._mitreLimit=t}},{key:"setSingleSided",value:function(t){this._isSingleSided=t}}],[{key:"constructor_",value:function(){if(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=e.CAP_ROUND,this._joinStyle=e.JOIN_ROUND,this._mitreLimit=e.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=e.DEFAULT_SIMPLIFY_FACTOR,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.setQuadrantSegments(t)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.setQuadrantSegments(n),this.setEndCapStyle(r)}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];this.setQuadrantSegments(i),this.setEndCapStyle(o),this.setJoinStyle(s),this.setMitreLimit(a)}}},{key:"bufferDistanceError",value:function(t){var e=Math.PI/2/t;return 1-Math.cos(e/2)}}]),e}();y.CAP_ROUND=1,y.CAP_FLAT=2,y.CAP_SQUARE=3,y.JOIN_ROUND=1,y.JOIN_MITRE=2,y.JOIN_BEVEL=3,y.DEFAULT_QUADRANT_SEGMENTS=8,y.DEFAULT_MITRE_LIMIT=5,y.DEFAULT_SIMPLIFY_FACTOR=.01;var _=function(e){r(o,e);var i=c(o);function o(e){var n;return t(this,o),(n=i.call(this,e)).name=Object.keys({Exception:o})[0],n}return n(o,[{key:"toString",value:function(){return this.message}}]),o}(u(Error)),x=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({IllegalArgumentException:i})[0],r}return i}(_),E=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}();function k(){}function b(){}function w(){}var I,N,S,M,L,P,C,T,O=function(){function e(){t(this,e)}return n(e,null,[{key:"equalsWithTolerance",value:function(t,e,n){return Math.abs(t-e)<=n}}]),e}(),R=function(){function e(n,r){t(this,e),this.low=r||0,this.high=n||0}return n(e,null,[{key:"toBinaryString",value:function(t){var e,n="";for(e=2147483648;e>0;e>>>=1)n+=(t.high&e)===e?"1":"0";for(e=2147483648;e>0;e>>>=1)n+=(t.low&e)===e?"1":"0";return n}}]),e}();function A(){}function D(){}A.NaN=NaN,A.isNaN=function(t){return Number.isNaN(t)},A.isInfinite=function(t){return!Number.isFinite(t)},A.MAX_VALUE=Number.MAX_VALUE,A.POSITIVE_INFINITY=Number.POSITIVE_INFINITY,A.NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,"function"==typeof Float64Array&&"function"==typeof Int32Array?(P=2146435072,C=new Float64Array(1),T=new Int32Array(C.buffer),A.doubleToLongBits=function(t){C[0]=t;var e=0|T[0],n=0|T[1];return(n&P)===P&&0!=(1048575&n)&&0!==e&&(e=0,n=2146959360),new R(n,e)},A.longBitsToDouble=function(t){return T[0]=t.low,T[1]=t.high,C[0]}):(I=1023,N=Math.log2,S=Math.floor,M=Math.pow,L=function(){for(var t=53;t>0;t--){var e=M(2,t)-1;if(S(N(e))+1===t)return e}return 0}(),A.doubleToLongBits=function(t){var e,n,r,i,o,s,a,u,l;if(t<0||1/t===Number.NEGATIVE_INFINITY?(s=1<<31,t=-t):s=0,0===t)return new R(u=s,l=0);if(t===1/0)return new R(u=2146435072|s,l=0);if(t!=t)return new R(u=2146959360,l=0);if(i=0,l=0,(e=S(t))>1)if(e<=L)(i=S(N(e)))<=20?(l=0,u=e<<20-i&1048575):(l=e%(n=M(2,r=i-20))<<32-r,u=e/n&1048575);else for(r=e,l=0;0!==(r=S(n=r/2));)i++,l>>>=1,l|=(1&u)<<31,u>>>=1,n!==r&&(u|=524288);if(a=i+I,o=0===e,e=t-e,i<52&&0!==e)for(r=0;;){if((n=2*e)>=1?(e=n-1,o?(a--,o=!1):(r<<=1,r|=1,i++)):(e=n,o?0==--a&&(i++,o=!1):(r<<=1,i++)),20===i)u|=r,r=0;else if(52===i){l|=r;break}if(1===n){i<20?u|=r<<20-i:i<52&&(l|=r<<52-i);break}}return u|=a<<20,new R(u|=s,l)},A.longBitsToDouble=function(t){var e,n,r,i,o=t.high,s=t.low,a=o&1<<31?-1:1;for(r=((2146435072&o)>>20)-I,i=0,n=1<<19,e=1;e<=20;e++)o&n&&(i+=M(2,-e)),n>>>=1;for(n=1<<31,e=21;e<=52;e++)s&n&&(i+=M(2,-e)),n>>>=1;if(-1023===r){if(0===i)return 0*a;r=-1022}else{if(1024===r)return 0===i?a/0:NaN;i+=1}return a*i*M(2,r)});var F=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({RuntimeException:i})[0],r}return i}(_),q=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){if(0===arguments.length)F.constructor_.call(this);else if(1===arguments.length){var t=arguments[0];F.constructor_.call(this,t)}}}]),o}(F),V=function(){function e(){t(this,e)}return n(e,null,[{key:"shouldNeverReachHere",value:function(){if(0===arguments.length)e.shouldNeverReachHere(null);else if(1===arguments.length){var t=arguments[0];throw new q("Should never reach here"+(null!==t?": "+t:""))}}},{key:"isTrue",value:function(){if(1===arguments.length){var t=arguments[0];e.isTrue(t,null)}else if(2===arguments.length){var n=arguments[1];if(!arguments[0])throw null===n?new q:new q(n)}}},{key:"equals",value:function(){if(2===arguments.length){var t=arguments[0],n=arguments[1];e.equals(t,n,null)}else if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2];if(!i.equals(r))throw new q("Expected "+r+" but encountered "+i+(null!==o?": "+o:""))}}}]),e}(),G=new ArrayBuffer(8),B=new Float64Array(G),Y=new Int32Array(G),z=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getM",value:function(){return A.NaN}},{key:"setOrdinate",value:function(t,n){switch(t){case e.X:this.x=n;break;case e.Y:this.y=n;break;case e.Z:this.setZ(n);break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"equals2D",value:function(){if(1===arguments.length){var t=arguments[0];return this.x===t.x&&this.y===t.y}if(2===arguments.length){var e=arguments[0],n=arguments[1];return!!O.equalsWithTolerance(this.x,e.x,n)&&!!O.equalsWithTolerance(this.y,e.y,n)}}},{key:"setM",value:function(t){throw new x("Invalid ordinate index: "+e.M)}},{key:"getZ",value:function(){return this.z}},{key:"getOrdinate",value:function(t){switch(t){case e.X:return this.x;case e.Y:return this.y;case e.Z:return this.getZ()}throw new x("Invalid ordinate index: "+t)}},{key:"equals3D",value:function(t){return this.x===t.x&&this.y===t.y&&(this.getZ()===t.getZ()||A.isNaN(this.getZ())&&A.isNaN(t.getZ()))}},{key:"equals",value:function(t){return t instanceof e&&this.equals2D(t)}},{key:"equalInZ",value:function(t,e){return O.equalsWithTolerance(this.getZ(),t.getZ(),e)}},{key:"setX",value:function(t){this.x=t}},{key:"compareTo",value:function(t){var e=t;return this.xe.x?1:this.ye.y?1:0}},{key:"getX",value:function(){return this.x}},{key:"setZ",value:function(t){this.z=t}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return V.shouldNeverReachHere("this shouldn't happen because this class is Cloneable"),null;throw t}}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+")"}},{key:"distance3D",value:function(t){var e=this.x-t.x,n=this.y-t.y,r=this.getZ()-t.getZ();return Math.sqrt(e*e+n*n+r*r)}},{key:"getY",value:function(){return this.y}},{key:"setY",value:function(t){this.y=t}},{key:"distance",value:function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*t+e.hashCode(this.x))+e.hashCode(this.y)}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}},{key:"interfaces_",get:function(){return[k,b,w]}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.z=null,0===arguments.length)e.constructor_.call(this,0,0);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.x,t.y,t.getZ())}else if(2===arguments.length){var n=arguments[0],r=arguments[1];e.constructor_.call(this,n,r,e.NULL_ORDINATE)}else if(3===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2];this.x=i,this.y=o,this.z=s}}},{key:"hashCode",value:function(t){return B[0]=t,Y[0]^Y[1]}}]),e}(),j=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compare",value:function(t,n){var r=e.compare(t.x,n.x);if(0!==r)return r;var i=e.compare(t.y,n.y);return 0!==i?i:this._dimensionsToTest<=2?0:e.compare(t.getZ(),n.getZ())}},{key:"interfaces_",get:function(){return[D]}}],[{key:"constructor_",value:function(){if(this._dimensionsToTest=2,0===arguments.length)e.constructor_.call(this,2);else if(1===arguments.length){var t=arguments[0];if(2!==t&&3!==t)throw new x("only 2 or 3 dimensions may be specified");this._dimensionsToTest=t}}},{key:"compare",value:function(t,e){return te?1:A.isNaN(t)?A.isNaN(e)?0:-1:A.isNaN(e)?1:0}}]),e}();z.DimensionalComparator=j,z.NULL_ORDINATE=A.NaN,z.X=0,z.Y=1,z.Z=2,z.M=3;var X=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getArea",value:function(){return this.getWidth()*this.getHeight()}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.isNull()?n.isNull():this._maxx===n.getMaxX()&&this._maxy===n.getMaxY()&&this._minx===n.getMinX()&&this._miny===n.getMinY()}},{key:"intersection",value:function(t){if(this.isNull()||t.isNull()||!this.intersects(t))return new e;var n=this._minx>t._minx?this._minx:t._minx,r=this._miny>t._miny?this._miny:t._miny;return new e(n,this._maxx=this._minx&&n.getMaxX()<=this._maxx&&n.getMinY()>=this._miny&&n.getMaxY()<=this._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return!this.isNull()&&r>=this._minx&&r<=this._maxx&&i>=this._miny&&i<=this._maxy}}},{key:"intersects",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return!this.isNull()&&!t.isNull()&&!(t._minx>this._maxx||t._maxxthis._maxy||t._maxythis._maxx||(r.x>i.x?r.x:i.x)this._maxy||(r.y>i.y?r.y:i.y)this._maxx||othis._maxy||sthis._maxx&&(this._maxx=n._maxx),n._minythis._maxy&&(this._maxy=n._maxy))}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.isNull()?(this._minx=r,this._maxx=r,this._miny=i,this._maxy=i):(rthis._maxx&&(this._maxx=r),ithis._maxy&&(this._maxy=i))}}},{key:"minExtent",value:function(){if(this.isNull())return 0;var t=this.getWidth(),e=this.getHeight();return te._minx?1:this._minye._miny?1:this._maxxe._maxx?1:this._maxye._maxy?1:0}},{key:"translate",value:function(t,e){if(this.isNull())return null;this.init(this.getMinX()+t,this.getMaxX()+t,this.getMinY()+e,this.getMaxY()+e)}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"Env["+this._minx+" : "+this._maxx+", "+this._miny+" : "+this._maxy+"]"}},{key:"setToNull",value:function(){this._minx=0,this._maxx=-1,this._miny=0,this._maxy=-1}},{key:"disjoint",value:function(t){return!(!this.isNull()&&!t.isNull())||t._minx>this._maxx||t._maxxthis._maxy||t._maxye?t:e}},{key:"expandBy",value:function(){if(1===arguments.length){var t=arguments[0];this.expandBy(t,t)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];if(this.isNull())return null;this._minx-=e,this._maxx+=e,this._miny-=n,this._maxy+=n,(this._minx>this._maxx||this._miny>this._maxy)&&this.setToNull()}}},{key:"contains",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.covers(t)}if(arguments[0]instanceof z){var n=arguments[0];return this.covers(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return this.covers(r,i)}}},{key:"centre",value:function(){return this.isNull()?null:new z((this.getMinX()+this.getMaxX())/2,(this.getMinY()+this.getMaxY())/2)}},{key:"init",value:function(){if(0===arguments.length)this.setToNull();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this._minx=n._minx,this._maxx=n._maxx,this._miny=n._miny,this._maxy=n._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];ot._maxx&&(e=this._minx-t._maxx);var n=0;return this._maxyt._maxy&&(n=this._miny-t._maxy),0===e?n:0===n?e:Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*(t=37*(t=37*t+z.hashCode(this._minx))+z.hashCode(this._maxx))+z.hashCode(this._miny))+z.hashCode(this._maxy)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,0===arguments.length)this.init();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];this.init(o,s,a,u)}}},{key:"intersects",value:function(){if(3===arguments.length){var t=arguments[0],e=arguments[1],n=arguments[2];return n.x>=(t.xe.x?t.x:e.x)&&n.y>=(t.ye.y?t.y:e.y)}if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=arguments[3],a=Math.min(o.x,s.x),u=Math.max(o.x,s.x),l=Math.min(r.x,i.x),h=Math.max(r.x,i.x);return!(l>u||hu||h=this.size())throw new nt;return this.array[t]}},{key:"push",value:function(t){return this.array.push(t),t}},{key:"pop",value:function(){if(0===this.array.length)throw new et;return this.array.pop()}},{key:"peek",value:function(){if(0===this.array.length)throw new et;return this.array[this.array.length-1]}},{key:"empty",value:function(){return 0===this.array.length}},{key:"isEmpty",value:function(){return this.empty()}},{key:"search",value:function(t){return this.array.indexOf(t)}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}}]),o}(rt);function ot(t,e){return t.interfaces_&&t.interfaces_.indexOf(e)>-1}var st=function(){function e(n){t(this,e),this.str=n}return n(e,[{key:"append",value:function(t){this.str+=t}},{key:"setCharAt",value:function(t,e){this.str=this.str.substr(0,t)+e+this.str.substr(t+1)}},{key:"toString",value:function(){return this.str}}]),e}(),at=function(){function e(n){t(this,e),this.value=n}return n(e,[{key:"intValue",value:function(){return this.value}},{key:"compareTo",value:function(t){return this.valuet?1:0}}],[{key:"compare",value:function(t,e){return te?1:0}},{key:"isNan",value:function(t){return Number.isNaN(t)}},{key:"valueOf",value:function(t){return new e(t)}}]),e}(),ut=function(){function e(){t(this,e)}return n(e,null,[{key:"isWhitespace",value:function(t){return t<=32&&t>=0||127===t}},{key:"toUpperCase",value:function(t){return t.toUpperCase()}}]),e}(),lt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"le",value:function(t){return this._hi9?(c=!0,f="9"):f="0"+h,a.append(f),r=r.subtract(e.valueOf(h)).multiply(e.TEN),c&&r.selfAdd(e.TEN);var g=!0,p=e.magnitude(r._hi);if(p<0&&Math.abs(p)>=u-l&&(g=!1),!g)break}return n[0]=i,a.toString()}},{key:"sqr",value:function(){return this.multiply(this)}},{key:"doubleValue",value:function(){return this._hi+this._lo}},{key:"subtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.add(t.negate())}if("number"==typeof arguments[0]){var n=arguments[0];return this.add(-n)}}},{key:"equals",value:function(){if(1===arguments.length&&arguments[0]instanceof e){var t=arguments[0];return this._hi===t._hi&&this._lo===t._lo}}},{key:"isZero",value:function(){return 0===this._hi&&0===this._lo}},{key:"selfSubtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.isNaN()?this:this.selfAdd(-t._hi,-t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.isNaN()?this:this.selfAdd(-n,0)}}},{key:"getSpecialNumberString",value:function(){return this.isZero()?"0.0":this.isNaN()?"NaN ":null}},{key:"min",value:function(t){return this.le(t)?this:t}},{key:"selfDivide",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfDivide(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfDivide(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null,c=null,f=null;return l=this._hi/r,f=(o=(h=e.SPLIT*l)-(o=h-l))*(a=(f=e.SPLIT*r)-(a=f-r))-(c=l*r)+o*(u=r-a)+(s=l-o)*a+s*u,f=l+(h=(this._hi-c-f+this._lo-l*i)/r),this._hi=f,this._lo=l-f+h,this}}},{key:"dump",value:function(){return"DD<"+this._hi+", "+this._lo+">"}},{key:"divide",value:function(){if(arguments[0]instanceof e){var t=arguments[0],n=null,r=null,i=null,o=null,s=null,a=null,u=null,l=null;return r=(s=this._hi/t._hi)-(n=(a=e.SPLIT*s)-(n=a-s)),l=n*(i=(l=e.SPLIT*t._hi)-(i=l-t._hi))-(u=s*t._hi)+n*(o=t._hi-i)+r*i+r*o,new e(l=s+(a=(this._hi-u-l+this._lo-s*t._lo)/t._hi),s-l+a)}if("number"==typeof arguments[0]){var h=arguments[0];return A.isNaN(h)?e.createNaN():e.copy(this).selfDivide(h,0)}}},{key:"ge",value:function(t){return this._hi>t._hi||this._hi===t._hi&&this._lo>=t._lo}},{key:"pow",value:function(t){if(0===t)return e.valueOf(1);var n=new e(this),r=e.valueOf(1),i=Math.abs(t);if(i>1)for(;i>0;)i%2==1&&r.selfMultiply(n),(i/=2)>0&&(n=n.sqr());else r=n;return t<0?r.reciprocal():r}},{key:"ceil",value:function(){if(this.isNaN())return e.NaN;var t=Math.ceil(this._hi),n=0;return t===this._hi&&(n=Math.ceil(this._lo)),new e(t,n)}},{key:"compareTo",value:function(t){var e=t;return this._hie._hi?1:this._loe._lo?1:0}},{key:"rint",value:function(){return this.isNaN()?this:this.add(.5).floor()}},{key:"setValue",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.init(t),this}if("number"==typeof arguments[0]){var n=arguments[0];return this.init(n),this}}},{key:"max",value:function(t){return this.ge(t)?this:t}},{key:"sqrt",value:function(){if(this.isZero())return e.valueOf(0);if(this.isNegative())return e.NaN;var t=1/Math.sqrt(this._hi),n=this._hi*t,r=e.valueOf(n),i=this.subtract(r.sqr())._hi*(.5*t);return r.add(i)}},{key:"selfAdd",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfAdd(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0],r=null,i=null,o=null,s=null,a=null,u=null;return s=(o=this._hi+n)-(a=o-this._hi),i=(u=(s=n-a+(this._hi-s))+this._lo)+(o-(r=o+u)),this._hi=r+i,this._lo=i+(r-this._hi),this}}else if(2===arguments.length){var l=arguments[0],h=arguments[1],c=null,f=null,g=null,p=null,v=null,d=null,y=null;p=this._hi+l,f=this._lo+h,v=p-(d=p-this._hi),g=f-(y=f-this._lo);var m=(c=p+(d=(v=l-d+(this._hi-v))+f))+(d=(g=h-y+(this._lo-g))+(d+(p-c))),_=d+(c-m);return this._hi=m,this._lo=_,this}}},{key:"selfMultiply",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfMultiply(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfMultiply(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null;o=(l=e.SPLIT*this._hi)-this._hi,h=e.SPLIT*r,o=l-o,s=this._hi-o,a=h-r;var c=(l=this._hi*r)+(h=o*(a=h-a)-l+o*(u=r-a)+s*a+s*u+(this._hi*i+this._lo*r)),f=h+(o=l-c);return this._hi=c,this._lo=f,this}}},{key:"selfSqr",value:function(){return this.selfMultiply(this)}},{key:"floor",value:function(){if(this.isNaN())return e.NaN;var t=Math.floor(this._hi),n=0;return t===this._hi&&(n=Math.floor(this._lo)),new e(t,n)}},{key:"negate",value:function(){return this.isNaN()?this:new e(-this._hi,-this._lo)}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return null;throw t}}},{key:"multiply",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return t.isNaN()?e.createNaN():e.copy(this).selfMultiply(t)}if("number"==typeof arguments[0]){var n=arguments[0];return A.isNaN(n)?e.createNaN():e.copy(this).selfMultiply(n,0)}}},{key:"isNaN",value:function(){return A.isNaN(this._hi)}},{key:"intValue",value:function(){return Math.trunc(this._hi)}},{key:"toString",value:function(){var t=e.magnitude(this._hi);return t>=-3&&t<=20?this.toStandardNotation():this.toSciNotation()}},{key:"toStandardNotation",value:function(){var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!0,n),i=n[0]+1,o=r;if("."===r.charAt(0))o="0"+r;else if(i<0)o="0."+e.stringOfChar("0",-i)+r;else if(-1===r.indexOf(".")){var s=i-r.length;o=r+e.stringOfChar("0",s)+".0"}return this.isNegative()?"-"+o:o}},{key:"reciprocal",value:function(){var t,n,r,i,o=null,s=null,a=null,u=null;t=(r=1/this._hi)-(o=(a=e.SPLIT*r)-(o=a-r)),s=(u=e.SPLIT*this._hi)-this._hi;var l=r+(a=(1-(i=r*this._hi)-(u=o*(s=u-s)-i+o*(n=this._hi-s)+t*s+t*n)-r*this._lo)/this._hi);return new e(l,r-l+a)}},{key:"toSciNotation",value:function(){if(this.isZero())return e.SCI_NOT_ZERO;var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!1,n),i=e.SCI_NOT_EXPONENT_CHAR+n[0];if("0"===r.charAt(0))throw new IllegalStateException("Found leading zero: "+r);var o="";r.length>1&&(o=r.substring(1));var s=r.charAt(0)+"."+o;return this.isNegative()?"-"+s+i:s+i}},{key:"abs",value:function(){return this.isNaN()?e.NaN:this.isNegative()?this.negate():new e(this)}},{key:"isPositive",value:function(){return this._hi>0||0===this._hi&&this._lo>0}},{key:"lt",value:function(t){return this._hit._hi||this._hi===t._hi&&this._lo>t._lo}},{key:"isNegative",value:function(){return this._hi<0||0===this._hi&&this._lo<0}},{key:"trunc",value:function(){return this.isNaN()?e.NaN:this.isPositive()?this.floor():this.ceil()}},{key:"signum",value:function(){return this._hi>0?1:this._hi<0?-1:this._lo>0?1:this._lo<0?-1:0}},{key:"interfaces_",get:function(){return[w,k,b]}}],[{key:"constructor_",value:function(){if(this._hi=0,this._lo=0,0===arguments.length)this.init(0);else if(1===arguments.length){if("number"==typeof arguments[0]){var t=arguments[0];this.init(t)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}else if("string"==typeof arguments[0]){var r=arguments[0];e.constructor_.call(this,e.parse(r))}}else if(2===arguments.length){var i=arguments[0],o=arguments[1];this.init(i,o)}}},{key:"determinant",value:function(){if("number"==typeof arguments[3]&&"number"==typeof arguments[2]&&"number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1],r=arguments[2],i=arguments[3];return e.determinant(e.valueOf(t),e.valueOf(n),e.valueOf(r),e.valueOf(i))}if(arguments[3]instanceof e&&arguments[2]instanceof e&&arguments[0]instanceof e&&arguments[1]instanceof e){var o=arguments[1],s=arguments[2],a=arguments[3];return arguments[0].multiply(a).selfSubtract(o.multiply(s))}}},{key:"sqr",value:function(t){return e.valueOf(t).selfMultiply(t)}},{key:"valueOf",value:function(){if("string"==typeof arguments[0]){var t=arguments[0];return e.parse(t)}if("number"==typeof arguments[0])return new e(arguments[0])}},{key:"sqrt",value:function(t){return e.valueOf(t).sqrt()}},{key:"parse",value:function(t){for(var n=0,r=t.length;ut.isWhitespace(t.charAt(n));)n++;var i=!1;if(n=r);){var c=t.charAt(n);if(n++,ut.isDigit(c)){var f=c-"0";s.selfMultiply(e.TEN),s.selfAdd(f),a++}else{if("."!==c){if("e"===c||"E"===c){var g=t.substring(n);try{l=at.parseInt(g)}catch(e){throw e instanceof NumberFormatException?new NumberFormatException("Invalid exponent "+g+" in string "+t):e}break}throw new NumberFormatException("Unexpected character '"+c+"' at position "+n+" in string "+t)}u=a,h=!0}}var p=s;h||(u=a);var v=a-u-l;if(0===v)p=s;else if(v>0){var d=e.TEN.pow(v);p=s.divide(d)}else if(v<0){var y=e.TEN.pow(-v);p=s.multiply(y)}return i?p.negate():p}},{key:"createNaN",value:function(){return new e(A.NaN,A.NaN)}},{key:"copy",value:function(t){return new e(t)}},{key:"magnitude",value:function(t){var e=Math.abs(t),n=Math.log(e)/Math.log(10),r=Math.trunc(Math.floor(n));return 10*Math.pow(10,r)<=e&&(r+=1),r}},{key:"stringOfChar",value:function(t,e){for(var n=new st,r=0;r0){if(s<=0)return e.signum(a);i=o+s}else{if(!(o<0))return e.signum(a);if(s>=0)return e.signum(a);i=-o-s}var u=e.DP_SAFE_EPSILON*i;return a>=u||-a>=u?e.signum(a):2}},{key:"signum",value:function(t){return t>0?1:t<0?-1:0}}]),e}();ht.DP_SAFE_EPSILON=1e-15;var ct=function(){function e(){t(this,e)}return n(e,[{key:"getM",value:function(t){if(this.hasM()){var e=this.getDimension()-this.getMeasures();return this.getOrdinate(t,e)}return A.NaN}},{key:"setOrdinate",value:function(t,e,n){}},{key:"getZ",value:function(t){return this.hasZ()?this.getOrdinate(t,2):A.NaN}},{key:"size",value:function(){}},{key:"getOrdinate",value:function(t,e){}},{key:"getCoordinate",value:function(){}},{key:"getCoordinateCopy",value:function(t){}},{key:"createCoordinate",value:function(){}},{key:"getDimension",value:function(){}},{key:"hasM",value:function(){return this.getMeasures()>0}},{key:"getX",value:function(t){}},{key:"hasZ",value:function(){return this.getDimension()-this.getMeasures()>2}},{key:"getMeasures",value:function(){return 0}},{key:"expandEnvelope",value:function(t){}},{key:"copy",value:function(){}},{key:"getY",value:function(t){}},{key:"toCoordinateArray",value:function(){}},{key:"interfaces_",get:function(){return[b]}}]),e}();ct.X=0,ct.Y=1,ct.Z=2,ct.M=3;var ft=function(){function e(){t(this,e)}return n(e,null,[{key:"index",value:function(t,e,n){return ht.orientationIndex(t,e,n)}},{key:"isCCW",value:function(){if(arguments[0]instanceof Array){var t=arguments[0],n=t.length-1;if(n<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var r=t[0],i=0,o=1;o<=n;o++){var s=t[o];s.y>r.y&&(r=s,i=o)}var a=i;do{(a-=1)<0&&(a=n)}while(t[a].equals2D(r)&&a!==i);var u=i;do{u=(u+1)%n}while(t[u].equals2D(r)&&u!==i);var l=t[a],h=t[u];if(l.equals2D(r)||h.equals2D(r)||l.equals2D(h))return!1;var c=e.index(l,r,h);return 0===c?l.x>h.x:c>0}if(ot(arguments[0],ct)){var f=arguments[0],g=f.size()-1;if(g<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var p=f.getCoordinate(0),v=0,d=1;d<=g;d++){var y=f.getCoordinate(d);y.y>p.y&&(p=y,v=d)}var m=null,_=v;do{(_-=1)<0&&(_=g),m=f.getCoordinate(_)}while(m.equals2D(p)&&_!==v);var E=null,k=v;do{k=(k+1)%g,E=f.getCoordinate(k)}while(E.equals2D(p)&&k!==v);if(m.equals2D(p)||E.equals2D(p)||m.equals2D(E))return!1;var b=e.index(m,p,E);return 0===b?m.x>E.x:b>0}}}]),e}();ft.CLOCKWISE=-1,ft.RIGHT=ft.CLOCKWISE,ft.COUNTERCLOCKWISE=1,ft.LEFT=ft.COUNTERCLOCKWISE,ft.COLLINEAR=0,ft.STRAIGHT=ft.COLLINEAR;var gt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this._minCoord}},{key:"getRightmostSide",value:function(t,e){var n=this.getRightmostSideOfSegment(t,e);return n<0&&(n=this.getRightmostSideOfSegment(t,e-1)),n<0&&(this._minCoord=null,this.checkForRightmostCoordinate(t)),n}},{key:"findRightmostEdgeAtVertex",value:function(){var t=this._minDe.getEdge().getCoordinates();V.isTrue(this._minIndex>0&&this._minIndexthis._minCoord.y&&n.y>this._minCoord.y&&r===ft.CLOCKWISE)&&(i=!0),i&&(this._minIndex=this._minIndex-1)}},{key:"getRightmostSideOfSegment",value:function(t,e){var n=t.getEdge().getCoordinates();if(e<0||e+1>=n.length)return-1;if(n[e].y===n[e+1].y)return-1;var r=tt.LEFT;return n[e].ythis._minCoord.x)&&(this._minDe=t,this._minIndex=n,this._minCoord=e[n])}},{key:"findRightmostEdgeAtNode",value:function(){var t=this._minDe.getNode().getEdges();this._minDe=t.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)}},{key:"findEdge",value:function(t){for(var e=t.iterator();e.hasNext();){var n=e.next();n.isForward()&&this.checkForRightmostCoordinate(n)}V.isTrue(0!==this._minIndex||this._minCoord.equals(this._minDe.getCoordinate()),"inconsistency in rightmost processing"),0===this._minIndex?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe,this.getRightmostSide(this._minDe,this._minIndex)===tt.LEFT&&(this._orientedDe=this._minDe.getSym())}}],[{key:"constructor_",value:function(){this._minIndex=-1,this._minCoord=null,this._minDe=null,this._orientedDe=null}}]),e}(),pt=function(e){r(o,e);var i=c(o);function o(e,n){var r;return t(this,o),(r=i.call(this,n?e+" [ "+n+" ]":e)).pt=n?new z(n):void 0,r.name=Object.keys({TopologyException:o})[0],r}return n(o,[{key:"getCoordinate",value:function(){return this.pt}}]),o}(F),vt=function(){function e(){t(this,e),this.array=[]}return n(e,[{key:"addLast",value:function(t){this.array.push(t)}},{key:"removeFirst",value:function(){return this.array.shift()}},{key:"isEmpty",value:function(){return 0===this.array.length}}]),e}(),dt=function(e,i){r(s,e);var o=c(s);function s(e){var n;return t(this,s),(n=o.call(this)).array=[],e instanceof H&&n.addAll(e),n}return n(s,[{key:"interfaces_",get:function(){return[rt,H]}},{key:"ensureCapacity",value:function(){}},{key:"add",value:function(t){return 1===arguments.length?this.array.push(t):this.array.splice(arguments[0],0,arguments[1]),!0}},{key:"clear",value:function(){this.array=[]}},{key:"addAll",value:function(t){var e,n=d(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.array.push(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"set",value:function(t,e){var n=this.array[t];return this.array[t]=e,n}},{key:"iterator",value:function(){return new yt(this)}},{key:"get",value:function(t){if(t<0||t>=this.size())throw new nt;return this.array[t]}},{key:"isEmpty",value:function(){return 0===this.array.length}},{key:"sort",value:function(t){t?this.array.sort((function(e,n){return t.compare(e,n)})):this.array.sort()}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}},{key:"remove",value:function(t){for(var e=0,n=this.array.length;e=1&&e.getDepth(tt.LEFT)<=0&&!e.isInteriorAreaEdge()&&e.setInResult(!0)}}},{key:"computeDepths",value:function(t){var e=new Q,n=new vt,r=t.getNode();for(n.addLast(r),e.add(r),t.setVisited(!0);!n.isEmpty();){var i=n.removeFirst();e.add(i),this.computeNodeDepth(i);for(var o=i.getEdges().iterator();o.hasNext();){var s=o.next().getSym();if(!s.isVisited()){var a=s.getNode();e.contains(a)||(n.addLast(a),e.add(a))}}}}},{key:"compareTo",value:function(t){var e=t;return this._rightMostCoord.xe._rightMostCoord.x?1:0}},{key:"getEnvelope",value:function(){if(null===this._env){for(var t=new X,e=this._dirEdgeList.iterator();e.hasNext();)for(var n=e.next().getEdge().getCoordinates(),r=0;re.x?t.x:e.x,a=t.y>e.y?t.y:e.y,u=n.xr.x?n.x:r.x,c=n.y>r.y?n.y:r.y,f=((i>u?i:u)+(sl?o:l)+(an?n:t}if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var r=arguments[0],i=arguments[1],o=arguments[2];return ro?o:r}}},{key:"wrap",value:function(t,e){return t<0?e- -t%e:t%e}},{key:"max",value:function(){if(3===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[0];return t>n&&(n=t),e>n&&(n=e),n}if(4===arguments.length){var r=arguments[1],i=arguments[2],o=arguments[3],s=arguments[0];return r>s&&(s=r),i>s&&(s=i),o>s&&(s=o),s}}},{key:"average",value:function(t,e){return(t+e)/2}}]),e}();Et.LOG_10=Math.log(10);var kt=function(){function e(){t(this,e)}return n(e,null,[{key:"segmentToSegment",value:function(t,n,r,i){if(t.equals(n))return e.pointToSegment(t,r,i);if(r.equals(i))return e.pointToSegment(i,t,n);var o=!1;if(X.intersects(t,n,r,i)){var s=(n.x-t.x)*(i.y-r.y)-(n.y-t.y)*(i.x-r.x);if(0===s)o=!0;else{var a=(t.y-r.y)*(i.x-r.x)-(t.x-r.x)*(i.y-r.y),u=((t.y-r.y)*(n.x-t.x)-(t.x-r.x)*(n.y-t.y))/s,l=a/s;(l<0||l>1||u<0||u>1)&&(o=!0)}}else o=!0;return o?Et.min(e.pointToSegment(t,r,i),e.pointToSegment(n,r,i),e.pointToSegment(r,t,n),e.pointToSegment(i,t,n)):0}},{key:"pointToSegment",value:function(t,e,n){if(e.x===n.x&&e.y===n.y)return t.distance(e);var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/r;if(i<=0)return t.distance(e);if(i>=1)return t.distance(n);var o=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(o)*Math.sqrt(r)}},{key:"pointToLinePerpendicular",value:function(t,e,n){var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(i)*Math.sqrt(r)}},{key:"pointToSegmentString",value:function(t,n){if(0===n.length)throw new x("Line array must contain at least one vertex");for(var r=t.distance(n[0]),i=0;i0)&&(o=a,i=s)}return i}}},{key:"extend",value:function(t,n,r){var i=t.create(r,n.getDimension()),o=n.size();if(e.copy(n,0,i,0,o),o>0)for(var s=o;s0)&&(e=r)}return e}}]),e}(),Mt=function(){function e(){t(this,e)}return n(e,null,[{key:"toDimensionSymbol",value:function(t){switch(t){case e.FALSE:return e.SYM_FALSE;case e.TRUE:return e.SYM_TRUE;case e.DONTCARE:return e.SYM_DONTCARE;case e.P:return e.SYM_P;case e.L:return e.SYM_L;case e.A:return e.SYM_A}throw new x("Unknown dimension value: "+t)}},{key:"toDimensionValue",value:function(t){switch(ut.toUpperCase(t)){case e.SYM_FALSE:return e.FALSE;case e.SYM_TRUE:return e.TRUE;case e.SYM_DONTCARE:return e.DONTCARE;case e.SYM_P:return e.P;case e.SYM_L:return e.L;case e.SYM_A:return e.A}throw new x("Unknown dimension symbol: "+t)}}]),e}();Mt.P=0,Mt.L=1,Mt.A=2,Mt.FALSE=-1,Mt.TRUE=-2,Mt.DONTCARE=-3,Mt.SYM_FALSE="F",Mt.SYM_TRUE="T",Mt.SYM_DONTCARE="*",Mt.SYM_P="0",Mt.SYM_L="1",Mt.SYM_A="2";var Lt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}(),Pt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t,e){}},{key:"isDone",value:function(){}},{key:"isGeometryChanged",value:function(){}}]),e}(),Ct=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"computeEnvelopeInternal",value:function(){return this.isEmpty()?new X:this._points.expandEnvelope(new X)}},{key:"isRing",value:function(){return this.isClosed()&&this.isSimple()}},{key:"getCoordinates",value:function(){return this._points.toCoordinateArray()}},{key:"copyInternal",value:function(){return new s(this._points.copy(),this._factory)}},{key:"equalsExact",value:function(){if(2===arguments.length&&"number"==typeof arguments[1]&&arguments[0]instanceof U){var t=arguments[0],e=arguments[1];if(!this.isEquivalentClass(t))return!1;var n=t;if(this._points.size()!==n._points.size())return!1;for(var r=0;r0){var n=this._points.copy();St.reverse(n),this._points=n}return null}}}},{key:"getCoordinate",value:function(){return this.isEmpty()?null:this._points.getCoordinate(0)}},{key:"getBoundaryDimension",value:function(){return this.isClosed()?Mt.FALSE:0}},{key:"isClosed",value:function(){return!this.isEmpty()&&this.getCoordinateN(0).equals2D(this.getCoordinateN(this.getNumPoints()-1))}},{key:"reverseInternal",value:function(){var t=this._points.copy();return St.reverse(t),this.getFactory().createLineString(t)}},{key:"getEndPoint",value:function(){return this.isEmpty()?null:this.getPointN(this.getNumPoints()-1)}},{key:"getTypeCode",value:function(){return U.TYPECODE_LINESTRING}},{key:"getDimension",value:function(){return 1}},{key:"getLength",value:function(){return It.ofLine(this._points)}},{key:"getNumPoints",value:function(){return this._points.size()}},{key:"compareToSameClass",value:function(){if(1===arguments.length){for(var t=arguments[0],e=0,n=0;e= 2)");this._points=t}},{key:"isCoordinate",value:function(t){for(var e=0;e=1&&this.getCoordinateSequence().size()= 4)")}},{key:"getGeometryType",value:function(){return U.TYPENAME_LINEARRING}}],[{key:"constructor_",value:function(){var t=arguments[0],e=arguments[1];Ct.constructor_.call(this,t,e),this.validateConstruction()}}]),s}(Ct);zt.MINIMUM_VALID_SIZE=4;var jt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}}],[{key:"constructor_",value:function(){if(0===arguments.length)z.constructor_.call(this);else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y)}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y)}}else if(2===arguments.length){var n=arguments[0],r=arguments[1];z.constructor_.call(this,n,r,z.NULL_ORDINATE)}}}]),o}(z);jt.X=0,jt.Y=1,jt.Z=-1,jt.M=-1;var Xt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;case o.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y;case o.M:return this._m}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y),this._m=this.getM()}}else if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2];z.constructor_.call(this,n,r,z.NULL_ORDINATE),this._m=i}}}]),o}(z);Xt.X=0,Xt.Y=1,Xt.Z=-1,Xt.M=2;var Ut=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case z.X:this.x=e;break;case z.Y:this.y=e;break;case z.Z:this.z=e;break;case z.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getOrdinate",value:function(t){switch(t){case z.X:return this.x;case z.Y:return this.y;case z.Z:return this.getZ();case z.M:return this.getM()}throw new x("Invalid ordinate index: "+t)}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e),this._m=this.getM()}}else if(4===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],s=arguments[3];z.constructor_.call(this,n,r,i),this._m=s}}}]),o}(z),Zt=function(){function e(){t(this,e)}return n(e,null,[{key:"measures",value:function(t){return t instanceof jt?0:t instanceof Xt||t instanceof Ut?1:0}},{key:"dimension",value:function(t){return t instanceof jt?2:t instanceof Xt?3:t instanceof Ut?4:3}},{key:"create",value:function(){if(1===arguments.length){var t=arguments[0];return e.create(t,0)}if(2===arguments.length){var n=arguments[0],r=arguments[1];return 2===n?new jt:3===n&&0===r?new z:3===n&&1===r?new Xt:4===n&&1===r?new Ut:new z}}}]),e}(),Ht=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getCoordinate",value:function(t){return this.get(t)}},{key:"addAll",value:function(){if(2===arguments.length&&"boolean"==typeof arguments[1]&&ot(arguments[0],H)){for(var t=arguments[1],e=!1,n=arguments[0].iterator();n.hasNext();)this.add(n.next(),t),e=!0;return e}return f(i(s.prototype),"addAll",this).apply(this,arguments)}},{key:"clone",value:function(){for(var t=f(i(s.prototype),"clone",this).call(this),e=0;e=1&&this.get(this.size()-1).equals2D(r))return null;f(i(s.prototype),"add",this).call(this,r)}else if(arguments[0]instanceof Object&&"boolean"==typeof arguments[1]){var o=arguments[0],a=arguments[1];return this.add(o,a),!0}}else if(3===arguments.length){if("boolean"==typeof arguments[2]&&arguments[0]instanceof Array&&"boolean"==typeof arguments[1]){var u=arguments[0],l=arguments[1];if(arguments[2])for(var h=0;h=0;c--)this.add(u[c],l);return!0}if("boolean"==typeof arguments[2]&&Number.isInteger(arguments[0])&&arguments[1]instanceof z){var g=arguments[0],p=arguments[1];if(!arguments[2]){var v=this.size();if(v>0){if(g>0&&this.get(g-1).equals2D(p))return null;if(g_&&(x=-1);for(var E=m;E!==_;E+=x)this.add(d[E],y);return!0}}},{key:"closeRing",value:function(){if(this.size()>0){var t=this.get(0).copy();this.add(t,!1)}}}],[{key:"constructor_",value:function(){if(0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.ensureCapacity(t.length),this.add(t,!0)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this.ensureCapacity(e.length),this.add(e,n)}}}]),s}(dt);Ht.coordArrayType=new Array(0).fill(null);var Wt=function(){function e(){t(this,e)}return n(e,null,[{key:"isRing",value:function(t){return!(t.length<4||!t[0].equals2D(t[t.length-1]))}},{key:"ptNotInList",value:function(t,n){for(var r=0;r=t?e:[]}},{key:"indexOf",value:function(t,e){for(var n=0;n0)&&(e=t[n]);return e}},{key:"extract",value:function(t,e,n){e=Et.clamp(e,0,t.length);var r=(n=Et.clamp(n,-1,t.length))-e+1;n<0&&(r=0),e>=t.length&&(r=0),nr.length)return 1;if(0===n.length)return 0;var i=Wt.compare(n,r);return Wt.isEqualReversed(n,r)?0:i}},{key:"OLDcompare",value:function(t,e){var n=t,r=e;if(n.lengthr.length)return 1;if(0===n.length)return 0;for(var i=Wt.increasingDirection(n),o=Wt.increasingDirection(r),s=i>0?0:n.length-1,a=o>0?0:n.length-1,u=0;u0){var t=new Qt(17*this._coordinates.length);t.append("("),t.append(this._coordinates[0]);for(var e=1;e3&&(t=3),t<2&&(t=2),new $t(arguments[0],t)}if(3===arguments.length){var e=arguments[2],n=arguments[1]-e;return e>1&&(e=1),n>3&&(n=3),n<2&&(n=2),new $t(arguments[0],n+e,e)}}}},{key:"interfaces_",get:function(){return[bt,w]}}],[{key:"instance",value:function(){return e.instanceObject}}]),e}();te.instanceObject=new te;var ee=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e=0?t:e}}]),e}(),oe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"readResolve",value:function(){return e.nameToTypeMap.get(this._name)}},{key:"toString",value:function(){return this._name}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){this._name=null;var t=arguments[0];this._name=t,e.nameToTypeMap.put(t,this)}}]),e}();oe.nameToTypeMap=new re,ie.Type=oe,ie.FIXED=new oe("FIXED"),ie.FLOATING=new oe("FLOATING"),ie.FLOATING_SINGLE=new oe("FLOATING SINGLE"),ie.maximumPreciseValue=9007199254740992;var se=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e1){if(u instanceof Ft)return this.createMultiPolygon(e.toPolygonArray(t));if(u instanceof Ct)return this.createMultiLineString(e.toLineStringArray(t));if(u instanceof Ot)return this.createMultiPoint(e.toPointArray(t));V.shouldNeverReachHere("Unhandled geometry type: "+u.getGeometryType())}return u}},{key:"createMultiPointFromCoords",value:function(t){return this.createMultiPoint(null!==t?this.getCoordinateSequenceFactory().create(t):null)}},{key:"createPoint",value:function(){if(0===arguments.length)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];return this.createPoint(null!==t?this.getCoordinateSequenceFactory().create([t]):null)}if(ot(arguments[0],ct))return new Ot(arguments[0],this)}}},{key:"getCoordinateSequenceFactory",value:function(){return this._coordinateSequenceFactory}},{key:"createPolygon",value:function(){if(0===arguments.length)return this.createPolygon(null,null);if(1===arguments.length){if(ot(arguments[0],ct)){var t=arguments[0];return this.createPolygon(this.createLinearRing(t))}if(arguments[0]instanceof Array){var e=arguments[0];return this.createPolygon(this.createLinearRing(e))}if(arguments[0]instanceof zt){var n=arguments[0];return this.createPolygon(n,null)}}else if(2===arguments.length)return new Ft(arguments[0],arguments[1],this)}},{key:"getSRID",value:function(){return this._SRID}},{key:"createGeometryCollection",value:function(){return 0===arguments.length?new Bt(null,this):1===arguments.length?new Bt(arguments[0],this):void 0}},{key:"getPrecisionModel",value:function(){return this._precisionModel}},{key:"createLinearRing",value:function(){if(0===arguments.length)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof Array){var t=arguments[0];return this.createLinearRing(null!==t?this.getCoordinateSequenceFactory().create(t):null)}if(ot(arguments[0],ct))return new zt(arguments[0],this)}}},{key:"createMultiPolygon",value:function(){return 0===arguments.length?new ee(null,this):1===arguments.length?new ee(arguments[0],this):void 0}},{key:"createMultiPoint",value:function(){if(0===arguments.length)return new Yt(null,this);if(1===arguments.length){if(arguments[0]instanceof Array)return new Yt(arguments[0],this);if(ot(arguments[0],ct)){var t=arguments[0];if(null===t)return this.createMultiPoint(new Array(0).fill(null));for(var e=new Array(t.size()).fill(null),n=0;n="a"&&t<="z"||t>="A"&&t<="Z"}},{key:"isNumeric_",value:function(t,e){return t>="0"&&t<="9"||"."==t&&!(void 0!==e&&e)}},{key:"isWhiteSpace_",value:function(t){return" "==t||"\t"==t||"\r"==t||"\n"==t}},{key:"nextChar_",value:function(){return this.wkt.charAt(++this.index_)}},{key:"nextToken",value:function(){var t,e=this.nextChar_(),n=this.index_,r=e;if("("==e)t=ve;else if(","==e)t=me;else if(")"==e)t=de;else if(this.isNumeric_(e)||"-"==e)t=ye,r=this.readNumber_();else if(this.isAlpha_(e))t=pe,r=this.readText_();else{if(this.isWhiteSpace_(e))return this.nextToken();if(""!==e)throw new Error("Unexpected character: "+e);t=_e}return{position:n,value:r,type:t}}},{key:"readNumber_",value:function(){var t,e=this.index_,n=!1,r=!1;do{"."==t?n=!0:"e"!=t&&"E"!=t||(r=!0),t=this.nextChar_()}while(this.isNumeric_(t,n)||!r&&("e"==t||"E"==t)||r&&("-"==t||"+"==t));return parseFloat(this.wkt.substring(e,this.index_--))}},{key:"readText_",value:function(){var t,e=this.index_;do{t=this.nextChar_()}while(this.isAlpha_(t));return this.wkt.substring(e,this.index_--).toUpperCase()}}]),e}(),ke=function(){function e(n,r){t(this,e),this.lexer_=n,this.token_,this.layout_=ue,this.factory=r}return n(e,[{key:"consume_",value:function(){this.token_=this.lexer_.nextToken()}},{key:"isTokenType",value:function(t){return this.token_.type==t}},{key:"match",value:function(t){var e=this.isTokenType(t);return e&&this.consume_(),e}},{key:"parse",value:function(){return this.consume_(),this.parseGeometry_()}},{key:"parseGeometryLayout_",value:function(){var t=ue,e=this.token_;if(this.isTokenType(pe)){var n=e.value;"Z"===n?t=le:"M"===n?t=he:"ZM"===n&&(t=ce),t!==ue&&this.consume_()}return t}},{key:"parseGeometryCollectionText_",value:function(){if(this.match(ve)){var t=[];do{t.push(this.parseGeometry_())}while(this.match(me));if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePointText_",value:function(){if(this.match(ve)){var t=this.parsePoint_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return null;throw new Error(this.formatErrorMessage_())}},{key:"parseLineStringText_",value:function(){if(this.match(ve)){var t=this.parsePointList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePolygonText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPointText_",value:function(){var t;if(this.match(ve)){if(t=this.token_.type==ve?this.parsePointTextList_():this.parsePointList_(),this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiLineStringText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPolygonText_",value:function(){if(this.match(ve)){var t=this.parsePolygonTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePoint_",value:function(){for(var t=[],e=this.layout_.length,n=0;n1?t.createPolygon(r[0],r.slice(1)):t.createPolygon(r[0])},r=this.token_;if(this.match(pe)){var i=r.value;if(this.layout_=this.parseGeometryLayout_(),"GEOMETRYCOLLECTION"==i){var o=this.parseGeometryCollectionText_();return t.createGeometryCollection(o)}switch(i){case"POINT":var s=this.parsePointText_();return s?t.createPoint(a(z,g(s))):t.createPoint();case"LINESTRING":var u=this.parseLineStringText_().map(e);return t.createLineString(u);case"LINEARRING":var l=this.parseLineStringText_().map(e);return t.createLinearRing(l);case"POLYGON":var h=this.parsePolygonText_();return h&&0!==h.length?n(h):t.createPolygon();case"MULTIPOINT":var c=this.parseMultiPointText_();if(!c||0===c.length)return t.createMultiPoint();var f=c.map(e).map((function(e){return t.createPoint(e)}));return t.createMultiPoint(f);case"MULTILINESTRING":var p=this.parseMultiLineStringText_().map((function(n){return t.createLineString(n.map(e))}));return t.createMultiLineString(p);case"MULTIPOLYGON":var v=this.parseMultiPolygonText_();if(!v||0===v.length)return t.createMultiPolygon();var d=v.map(n);return t.createMultiPolygon(d);default:throw new Error("Invalid geometry type: "+i)}}throw new Error(this.formatErrorMessage_())}}]),e}();function be(t){if(t.isEmpty())return"";var e=t.getCoordinate(),n=[e.x,e.y];return void 0===e.z||Number.isNaN(e.z)||n.push(e.z),void 0===e.m||Number.isNaN(e.m)||n.push(e.m),n.join(" ")}function we(t){for(var e=t.getCoordinates().map((function(t){var e=[t.x,t.y];return void 0===t.z||Number.isNaN(t.z)||e.push(t.z),void 0===t.m||Number.isNaN(t.m)||e.push(t.m),e})),n=[],r=0,i=e.length;r0&&(e+=" "+r),t.isEmpty()?e+" "+ge:e+" ("+n(t)+")"}var Me=function(){function e(n){t(this,e),this.geometryFactory=n||new ae,this.precisionModel=this.geometryFactory.getPrecisionModel()}return n(e,[{key:"read",value:function(t){var e=new Ee(t);return new ke(e,this.geometryFactory).parse()}},{key:"write",value:function(t){return Se(t)}}]),e}(),Le=function(){function e(n){t(this,e),this.parser=new Me(n)}return n(e,[{key:"write",value:function(t){return this.parser.write(t)}}],[{key:"toLineString",value:function(t,e){if(2!==arguments.length)throw new Error("Not implemented");return"LINESTRING ( "+t.x+" "+t.y+", "+e.x+" "+e.y+" )"}}]),e}(),Pe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getIndexAlongSegment",value:function(t,e){return this.computeIntLineIndex(),this._intLineIndex[t][e]}},{key:"getTopologySummary",value:function(){var t=new Qt;return this.isEndPoint()&&t.append(" endpoint"),this._isProper&&t.append(" proper"),this.isCollinear()&&t.append(" collinear"),t.toString()}},{key:"computeIntersection",value:function(t,e,n,r){this._inputLines[0][0]=t,this._inputLines[0][1]=e,this._inputLines[1][0]=n,this._inputLines[1][1]=r,this._result=this.computeIntersect(t,e,n,r)}},{key:"getIntersectionNum",value:function(){return this._result}},{key:"computeIntLineIndex",value:function(){if(0===arguments.length)null===this._intLineIndex&&(this._intLineIndex=Array(2).fill().map((function(){return Array(2)})),this.computeIntLineIndex(0),this.computeIntLineIndex(1));else if(1===arguments.length){var t=arguments[0];this.getEdgeDistance(t,0)>this.getEdgeDistance(t,1)?(this._intLineIndex[t][0]=0,this._intLineIndex[t][1]=1):(this._intLineIndex[t][0]=1,this._intLineIndex[t][1]=0)}}},{key:"isProper",value:function(){return this.hasIntersection()&&this._isProper}},{key:"setPrecisionModel",value:function(t){this._precisionModel=t}},{key:"isInteriorIntersection",value:function(){if(0===arguments.length)return!!this.isInteriorIntersection(0)||!!this.isInteriorIntersection(1);if(1===arguments.length){for(var t=arguments[0],e=0;ei?r:i;else{var s=Math.abs(t.x-e.x),a=Math.abs(t.y-e.y);0!==(o=r>i?s:a)||t.equals(e)||(o=Math.max(s,a))}return V.isTrue(!(0===o&&!t.equals(e)),"Bad distance calculation"),o}},{key:"nonRobustComputeEdgeDistance",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y,o=Math.sqrt(r*r+i*i);return V.isTrue(!(0===o&&!t.equals(e)),"Invalid distance calculation"),o}}]),e}();Pe.DONT_INTERSECT=0,Pe.DO_INTERSECT=1,Pe.COLLINEAR=2,Pe.NO_INTERSECTION=0,Pe.POINT_INTERSECTION=1,Pe.COLLINEAR_INTERSECTION=2;var Ce=function(e){r(s,e);var o=c(s);function s(){return t(this,s),o.call(this)}return n(s,[{key:"isInSegmentEnvelopes",value:function(t){var e=new X(this._inputLines[0][0],this._inputLines[0][1]),n=new X(this._inputLines[1][0],this._inputLines[1][1]);return e.contains(t)&&n.contains(t)}},{key:"computeIntersection",value:function(){if(3!==arguments.length)return f(i(s.prototype),"computeIntersection",this).apply(this,arguments);var t=arguments[0],e=arguments[1],n=arguments[2];if(this._isProper=!1,X.intersects(e,n,t)&&0===ft.index(e,n,t)&&0===ft.index(n,e,t))return this._isProper=!0,(t.equals(e)||t.equals(n))&&(this._isProper=!1),this._result=Pe.POINT_INTERSECTION,null;this._result=Pe.NO_INTERSECTION}},{key:"intersection",value:function(t,e,n,r){var i=this.intersectionSafe(t,e,n,r);return this.isInSegmentEnvelopes(i)||(i=new z(s.nearestEndpoint(t,e,n,r))),null!==this._precisionModel&&this._precisionModel.makePrecise(i),i}},{key:"checkDD",value:function(t,e,n,r,i){var o=ht.intersection(t,e,n,r),s=this.isInSegmentEnvelopes(o);xt.out.println("DD in env = "+s+" --------------------- "+o),i.distance(o)>1e-4&&xt.out.println("Distance = "+i.distance(o))}},{key:"intersectionSafe",value:function(t,e,n,r){var i=_t.intersection(t,e,n,r);return null===i&&(i=s.nearestEndpoint(t,e,n,r)),i}},{key:"computeCollinearIntersection",value:function(t,e,n,r){var i=X.intersects(t,e,n),o=X.intersects(t,e,r),s=X.intersects(n,r,t),a=X.intersects(n,r,e);return i&&o?(this._intPt[0]=n,this._intPt[1]=r,Pe.COLLINEAR_INTERSECTION):s&&a?(this._intPt[0]=t,this._intPt[1]=e,Pe.COLLINEAR_INTERSECTION):i&&s?(this._intPt[0]=n,this._intPt[1]=t,!n.equals(t)||o||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):i&&a?(this._intPt[0]=n,this._intPt[1]=e,!n.equals(e)||o||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&s?(this._intPt[0]=r,this._intPt[1]=t,!r.equals(t)||i||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&a?(this._intPt[0]=r,this._intPt[1]=e,!r.equals(e)||i||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):Pe.NO_INTERSECTION}},{key:"computeIntersect",value:function(t,e,n,r){if(this._isProper=!1,!X.intersects(t,e,n,r))return Pe.NO_INTERSECTION;var i=ft.index(t,e,n),o=ft.index(t,e,r);if(i>0&&o>0||i<0&&o<0)return Pe.NO_INTERSECTION;var s=ft.index(n,r,t),a=ft.index(n,r,e);return s>0&&a>0||s<0&&a<0?Pe.NO_INTERSECTION:0===i&&0===o&&0===s&&0===a?this.computeCollinearIntersection(t,e,n,r):(0===i||0===o||0===s||0===a?(this._isProper=!1,t.equals2D(n)||t.equals2D(r)?this._intPt[0]=t:e.equals2D(n)||e.equals2D(r)?this._intPt[0]=e:0===i?this._intPt[0]=new z(n):0===o?this._intPt[0]=new z(r):0===s?this._intPt[0]=new z(t):0===a&&(this._intPt[0]=new z(e))):(this._isProper=!0,this._intPt[0]=this.intersection(t,e,n,r)),Pe.POINT_INTERSECTION)}}],[{key:"nearestEndpoint",value:function(t,e,n,r){var i=t,o=kt.pointToSegment(t,n,r),s=kt.pointToSegment(e,n,r);return sr&&(n=e.x,r=t.x),this._p.x>=n&&this._p.x<=r&&(this._isPointOnSegment=!0),null}if(t.y>this._p.y&&e.y<=this._p.y||e.y>this._p.y&&t.y<=this._p.y){var i=ft.index(t,e,this._p);if(i===ft.COLLINEAR)return this._isPointOnSegment=!0,null;e.ythis.location.length){var e=new Array(3).fill(null);e[tt.ON]=this.location[tt.ON],e[tt.LEFT]=Z.NONE,e[tt.RIGHT]=Z.NONE,this.location=e}for(var n=0;n1&&t.append(Z.toLocationSymbol(this.location[tt.LEFT])),t.append(Z.toLocationSymbol(this.location[tt.ON])),this.location.length>1&&t.append(Z.toLocationSymbol(this.location[tt.RIGHT])),t.toString()}},{key:"setLocations",value:function(t,e,n){this.location[tt.ON]=t,this.location[tt.LEFT]=e,this.location[tt.RIGHT]=n}},{key:"get",value:function(t){return t1}},{key:"isAnyNull",value:function(){for(var t=0;tthis._maxNodeDegree&&(this._maxNodeDegree=e),t=this.getNext(t)}while(t!==this._startDe);this._maxNodeDegree*=2}},{key:"addPoints",value:function(t,e,n){var r=t.getCoordinates();if(e){var i=1;n&&(i=0);for(var o=i;o=0;a--)this._pts.add(r[a])}}},{key:"isHole",value:function(){return this._isHole}},{key:"setInResult",value:function(){var t=this._startDe;do{t.getEdge().setInResult(!0),t=t.getNext()}while(t!==this._startDe)}},{key:"containsPoint",value:function(t){var e=this.getLinearRing();if(!e.getEnvelopeInternal().contains(t))return!1;if(!Oe.isInRing(t,e.getCoordinates()))return!1;for(var n=this._holes.iterator();n.hasNext();)if(n.next().containsPoint(t))return!1;return!0}},{key:"addHole",value:function(t){this._holes.add(t)}},{key:"isShell",value:function(){return null===this._shell}},{key:"getLabel",value:function(){return this._label}},{key:"getEdges",value:function(){return this._edges}},{key:"getMaxNodeDegree",value:function(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree}},{key:"getShell",value:function(){return this._shell}},{key:"mergeLabel",value:function(){if(1===arguments.length){var t=arguments[0];this.mergeLabel(t,0),this.mergeLabel(t,1)}else if(2===arguments.length){var e=arguments[1],n=arguments[0].getLocation(e,tt.RIGHT);if(n===Z.NONE)return null;if(this._label.getLocation(e)===Z.NONE)return this._label.setLocation(e,n),null}}},{key:"setShell",value:function(t){this._shell=t,null!==t&&t.addHole(this)}},{key:"toPolygon",value:function(t){for(var e=new Array(this._holes.size()).fill(null),n=0;n=2,"found partial label"),this.computeIM(t)}},{key:"isInResult",value:function(){return this._isInResult}},{key:"isVisited",value:function(){return this._isVisited}}],[{key:"constructor_",value:function(){if(this._label=null,this._isInResult=!1,this._isCovered=!1,this._isCoveredSet=!1,this._isVisited=!1,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._label=t}}}]),e}(),Ge=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isIncidentEdgeInResult",value:function(){for(var t=this.getEdges().getEdges().iterator();t.hasNext();)if(t.next().getEdge().isInResult())return!0;return!1}},{key:"isIsolated",value:function(){return 1===this._label.getGeometryCount()}},{key:"getCoordinate",value:function(){return this._coord}},{key:"print",value:function(t){t.println("node "+this._coord+" lbl: "+this._label)}},{key:"computeIM",value:function(t){}},{key:"computeMergedLocation",value:function(t,e){var n=Z.NONE;if(n=this._label.getLocation(e),!t.isNull(e)){var r=t.getLocation(e);n!==Z.BOUNDARY&&(n=r)}return n}},{key:"setLabel",value:function(){if(2!==arguments.length||!Number.isInteger(arguments[1])||!Number.isInteger(arguments[0]))return f(i(s.prototype),"setLabel",this).apply(this,arguments);var t=arguments[0],e=arguments[1];null===this._label?this._label=new Ae(t,e):this._label.setLocation(t,e)}},{key:"getEdges",value:function(){return this._edges}},{key:"mergeLabel",value:function(){if(arguments[0]instanceof s){var t=arguments[0];this.mergeLabel(t._label)}else if(arguments[0]instanceof Ae)for(var e=arguments[0],n=0;n<2;n++){var r=this.computeMergedLocation(e,n);this._label.getLocation(n)===Z.NONE&&this._label.setLocation(n,r)}}},{key:"add",value:function(t){this._edges.insert(t),t.setNode(this)}},{key:"setLabelBoundary",value:function(t){if(null===this._label)return null;var e=Z.NONE;null!==this._label&&(e=this._label.getLocation(t));var n=null;switch(e){case Z.BOUNDARY:n=Z.INTERIOR;break;case Z.INTERIOR:default:n=Z.BOUNDARY}this._label.setLocation(t,n)}}],[{key:"constructor_",value:function(){this._coord=null,this._edges=null;var t=arguments[0],e=arguments[1];this._coord=t,this._edges=e,this._label=new Ae(0,Z.NONE)}}]),s}(Ve),Be=function(e){r(i,e);var n=c(i);function i(){return t(this,i),n.apply(this,arguments)}return i}(ne);function Ye(t){return null==t?0:t.color}function ze(t){return null==t?null:t.parent}function je(t,e){null!==t&&(t.color=e)}function Xe(t){return null==t?null:t.left}function Ue(t){return null==t?null:t.right}var Ze=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),(e=i.call(this)).root_=null,e.size_=0,e}return n(o,[{key:"get",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return e.value;e=e.right}}return null}},{key:"put",value:function(t,e){if(null===this.root_)return this.root_={key:t,value:e,left:null,right:null,parent:null,color:0,getValue:function(){return this.value},getKey:function(){return this.key}},this.size_=1,null;var n,r,i=this.root_;do{if(n=i,(r=t.compareTo(i.key))<0)i=i.left;else{if(!(r>0)){var o=i.value;return i.value=e,o}i=i.right}}while(null!==i);var s={key:t,left:null,right:null,value:e,parent:n,color:0,getValue:function(){return this.value},getKey:function(){return this.key}};return r<0?n.left=s:n.right=s,this.fixAfterInsertion(s),this.size_++,null}},{key:"fixAfterInsertion",value:function(t){var e;for(t.color=1;null!=t&&t!==this.root_&&1===t.parent.color;)ze(t)===Xe(ze(ze(t)))?1===Ye(e=Ue(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Ue(ze(t))&&(t=ze(t),this.rotateLeft(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateRight(ze(ze(t)))):1===Ye(e=Xe(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Xe(ze(t))&&(t=ze(t),this.rotateRight(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateLeft(ze(ze(t))));this.root_.color=0}},{key:"values",value:function(){var t=new dt,e=this.getFirstEntry();if(null!==e)for(t.add(e.value);null!==(e=o.successor(e));)t.add(e.value);return t}},{key:"entrySet",value:function(){var t=new Q,e=this.getFirstEntry();if(null!==e)for(t.add(e);null!==(e=o.successor(e));)t.add(e);return t}},{key:"rotateLeft",value:function(t){if(null!=t){var e=t.right;t.right=e.left,null!=e.left&&(e.left.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.left===t?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}}},{key:"rotateRight",value:function(t){if(null!=t){var e=t.left;t.left=e.right,null!=e.right&&(e.right.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.right===t?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}}},{key:"getFirstEntry",value:function(){var t=this.root_;if(null!=t)for(;null!=t.left;)t=t.left;return t}},{key:"size",value:function(){return this.size_}},{key:"containsKey",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return!0;e=e.right}}return!1}}],[{key:"successor",value:function(t){var e;if(null===t)return null;if(null!==t.right){for(e=t.right;null!==e.left;)e=e.left;return e}e=t.parent;for(var n=t;null!==e&&n===e.right;)n=e,e=e.parent;return e}}]),o}(Be),He=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"find",value:function(t){return this.nodeMap.get(t)}},{key:"addNode",value:function(){if(arguments[0]instanceof z){var t=arguments[0],e=this.nodeMap.get(t);return null===e&&(e=this.nodeFact.createNode(t),this.nodeMap.put(t,e)),e}if(arguments[0]instanceof Ge){var n=arguments[0],r=this.nodeMap.get(n.getCoordinate());return null===r?(this.nodeMap.put(n.getCoordinate(),n),n):(r.mergeLabel(n),r)}}},{key:"print",value:function(t){for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this.nodeMap.values().iterator()}},{key:"values",value:function(){return this.nodeMap.values()}},{key:"getBoundaryNodes",value:function(t){for(var e=new dt,n=this.iterator();n.hasNext();){var r=n.next();r.getLabel().getLocation(t)===Z.BOUNDARY&&e.add(r)}return e}},{key:"add",value:function(t){var e=t.getCoordinate();this.addNode(e).add(t)}}],[{key:"constructor_",value:function(){this.nodeMap=new Ze,this.nodeFact=null;var t=arguments[0];this.nodeFact=t}}]),e}(),We=function(){function e(){t(this,e)}return n(e,null,[{key:"isNorthern",value:function(t){return t===e.NE||t===e.NW}},{key:"isOpposite",value:function(t,e){return t!==e&&2==(t-e+4)%4}},{key:"commonHalfPlane",value:function(t,e){if(t===e)return t;if(2==(t-e+4)%4)return-1;var n=te?t:e)?3:n}},{key:"isInHalfPlane",value:function(t,n){return n===e.SE?t===e.SE||t===e.SW:t===n||t===n+1}},{key:"quadrant",value:function(){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1];if(0===t&&0===n)throw new x("Cannot compute the quadrant for point ( "+t+", "+n+" )");return t>=0?n>=0?e.NE:e.SE:n>=0?e.NW:e.SW}if(arguments[0]instanceof z&&arguments[1]instanceof z){var r=arguments[0],i=arguments[1];if(i.x===r.x&&i.y===r.y)throw new x("Cannot compute the quadrant for two identical points "+r);return i.x>=r.x?i.y>=r.y?e.NE:e.SE:i.y>=r.y?e.NW:e.SW}}}]),e}();We.NE=0,We.NW=1,We.SW=2,We.SE=3;var Je=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareDirection",value:function(t){return this._dx===t._dx&&this._dy===t._dy?0:this._quadrant>t._quadrant?1:this._quadrant2){o.linkDirectedEdgesForMinimalEdgeRings();var s=o.buildMinimalRings(),a=this.findShell(s);null!==a?(this.placePolygonHoles(a,s),e.add(a)):n.addAll(s)}else r.add(o)}return r}},{key:"buildMaximalEdgeRings",value:function(t){for(var e=new dt,n=t.iterator();n.hasNext();){var r=n.next();if(r.isInResult()&&r.getLabel().isArea()&&null===r.getEdgeRing()){var i=new qe(r,this._geometryFactory);e.add(i),i.setInResult()}}return e}},{key:"placePolygonHoles",value:function(t,e){for(var n=e.iterator();n.hasNext();){var r=n.next();r.isHole()&&r.setShell(t)}}},{key:"getPolygons",value:function(){return this.computePolygons(this._shellList)}},{key:"findShell",value:function(t){for(var e=0,n=null,r=t.iterator();r.hasNext();){var i=r.next();i.isHole()||(n=i,e++)}return V.isTrue(e<=1,"found two shells in MinimalEdgeRing list"),n}},{key:"add",value:function(){if(1===arguments.length){var t=arguments[0];this.add(t.getEdgeEnds(),t.getNodes())}else if(2===arguments.length){var e=arguments[0],n=arguments[1];$e.linkResultDirectedEdges(n);var r=this.buildMaximalEdgeRings(e),i=new dt,o=this.buildMinimalEdgeRings(r,this._shellList,i);this.sortShellsAndHoles(o,this._shellList,i),this.placeFreeHoles(this._shellList,i)}}}],[{key:"constructor_",value:function(){this._geometryFactory=null,this._shellList=new dt;var t=arguments[0];this._geometryFactory=t}},{key:"findEdgeRingContaining",value:function(t,e){for(var n=t.getLinearRing(),r=n.getEnvelopeInternal(),i=n.getCoordinateN(0),o=null,s=null,a=e.iterator();a.hasNext();){var u=a.next(),l=u.getLinearRing(),h=l.getEnvelopeInternal();if(!h.equals(r)&&h.contains(r)){i=Wt.ptNotInList(n.getCoordinates(),l.getCoordinates());var c=!1;Oe.isInRing(i,l.getCoordinates())&&(c=!0),c&&(null===o||s.contains(h))&&(s=(o=u).getLinearRing().getEnvelopeInternal())}}return o}}]),e}(),en=function(){function e(){t(this,e)}return n(e,[{key:"getBounds",value:function(){}}]),e}(),nn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getItem",value:function(){return this._item}},{key:"getBounds",value:function(){return this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){this._bounds=null,this._item=null;var t=arguments[0],e=arguments[1];this._bounds=t,this._item=e}}]),e}(),rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"poll",value:function(){if(this.isEmpty())return null;var t=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),t}},{key:"size",value:function(){return this._size}},{key:"reorder",value:function(t){for(var e=null,n=this._items.get(t);2*t<=this._size&&((e=2*t)!==this._size&&this._items.get(e+1).compareTo(this._items.get(e))<0&&e++,this._items.get(e).compareTo(n)<0);t=e)this._items.set(t,this._items.get(e));this._items.set(t,n)}},{key:"clear",value:function(){this._size=0,this._items.clear()}},{key:"peek",value:function(){return this.isEmpty()?null:this._items.get(1)}},{key:"isEmpty",value:function(){return 0===this._size}},{key:"add",value:function(t){this._items.add(null),this._size+=1;var e=this._size;for(this._items.set(0,t);t.compareTo(this._items.get(Math.trunc(e/2)))<0;e/=2)this._items.set(e,this._items.get(Math.trunc(e/2)));this._items.set(e,t)}}],[{key:"constructor_",value:function(){this._size=null,this._items=null,this._size=0,this._items=new dt,this._items.add(null)}}]),e}(),on=function(){function e(){t(this,e)}return n(e,[{key:"insert",value:function(t,e){}},{key:"remove",value:function(t,e){}},{key:"query",value:function(){}}]),e}(),sn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLevel",value:function(){return this._level}},{key:"size",value:function(){return this._childBoundables.size()}},{key:"getChildBoundables",value:function(){return this._childBoundables}},{key:"addChildBoundable",value:function(t){V.isTrue(null===this._bounds),this._childBoundables.add(t)}},{key:"isEmpty",value:function(){return this._childBoundables.isEmpty()}},{key:"getBounds",value:function(){return null===this._bounds&&(this._bounds=this.computeBounds()),this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){if(this._childBoundables=new dt,this._bounds=null,this._level=null,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._level=t}}}]),e}(),an={reverseOrder:function(){return{compare:function(t,e){return e.compareTo(t)}}},min:function(t){return an.sort(t),t.get(0)},sort:function(t,e){var n=t.toArray();e?At.sort(n,e):At.sort(n);for(var r=t.iterator(),i=0,o=n.length;ie.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,!1,t,n),null):(this.expand(this._boundable2,this._boundable1,!0,t,n),null);if(r)return this.expand(this._boundable1,this._boundable2,!1,t,n),null;if(i)return this.expand(this._boundable2,this._boundable1,!0,t,n),null;throw new x("neither boundable is composite")}},{key:"isLeaves",value:function(){return!(e.isComposite(this._boundable1)||e.isComposite(this._boundable2))}},{key:"compareTo",value:function(t){var e=t;return this._distancee._distance?1:0}},{key:"expand",value:function(t,n,r,i,o){for(var s=t.getChildBoundables().iterator();s.hasNext();){var a=s.next(),u=null;(u=r?new e(n,a,this._itemDistance):new e(a,n,this._itemDistance)).getDistance()-2),r.getLevel()===n)return i.add(r),null;for(var o=r.getChildBoundables().iterator();o.hasNext();){var s=o.next();s instanceof sn?this.boundablesAtLevel(n,s,i):(V.isTrue(s instanceof nn),-1===n&&i.add(s))}return null}}},{key:"query",value:function(){if(1===arguments.length){var t=arguments[0];this.build();var e=new dt;return this.isEmpty()||this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.queryInternal(t,this._root,e),e}if(2===arguments.length){var n=arguments[0],r=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),n)&&this.queryInternal(n,this._root,r)}}},{key:"build",value:function(){if(this._built)return null;this._root=this._itemBoundables.isEmpty()?this.createNode(0):this.createHigherLevels(this._itemBoundables,-1),this._itemBoundables=null,this._built=!0}},{key:"getRoot",value:function(){return this.build(),this._root}},{key:"remove",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];return this.build(),!!this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.remove(t,this._root,e)}if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],o=this.removeItem(r,i);if(o)return!0;for(var s=null,a=r.getChildBoundables().iterator();a.hasNext();){var u=a.next();if(this.getIntersectsOp().intersects(u.getBounds(),n)&&u instanceof sn&&(o=this.remove(n,u,i))){s=u;break}}return null!==s&&s.getChildBoundables().isEmpty()&&r.getChildBoundables().remove(s),o}}},{key:"createHigherLevels",value:function(t,e){V.isTrue(!t.isEmpty());var n=this.createParentBoundables(t,e+1);return 1===n.size()?n.get(0):this.createHigherLevels(n,e+1)}},{key:"depth",value:function(){if(0===arguments.length)return this.isEmpty()?0:(this.build(),this.depth(this._root));if(1===arguments.length){for(var t=0,e=arguments[0].getChildBoundables().iterator();e.hasNext();){var n=e.next();if(n instanceof sn){var r=this.depth(n);r>t&&(t=r)}}return t+1}}},{key:"createParentBoundables",value:function(t,e){V.isTrue(!t.isEmpty());var n=new dt;n.add(this.createNode(e));var r=new dt(t);an.sort(r,this.getComparator());for(var i=r.iterator();i.hasNext();){var o=i.next();this.lastNode(n).getChildBoundables().size()===this.getNodeCapacity()&&n.add(this.createNode(e)),this.lastNode(n).addChildBoundable(o)}return n}},{key:"isEmpty",value:function(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){if(this._root=null,this._built=!1,this._itemBoundables=new dt,this._nodeCapacity=null,0===arguments.length)e.constructor_.call(this,e.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];V.isTrue(t>1,"Node capacity must be greater than 1"),this._nodeCapacity=t}}},{key:"compareDoubles",value:function(t,e){return t>e?1:t0);for(var n=new dt,r=0;r=0;){var u=o.poll(),l=u.getDistance();if(l>=i)break;u.isLeaves()?a.size()l&&(a.poll(),a.add(u)),i=a.peek().getDistance()):u.expandToQueue(o,i)}return s.getItems(a)}}},{key:"createNode",value:function(t){return new pn(t)}},{key:"size",value:function(){return 0===arguments.length?f(i(s.prototype),"size",this).call(this):f(i(s.prototype),"size",this).apply(this,arguments)}},{key:"insert",value:function(){if(!(2===arguments.length&&arguments[1]instanceof Object&&arguments[0]instanceof X))return f(i(s.prototype),"insert",this).apply(this,arguments);var t=arguments[0],e=arguments[1];if(t.isNull())return null;f(i(s.prototype),"insert",this).call(this,t,e)}},{key:"getIntersectsOp",value:function(){return s.intersectsOp}},{key:"verticalSlices",value:function(t,e){for(var n=Math.trunc(Math.ceil(t.size()/e)),r=new Array(e).fill(null),i=t.iterator(),o=0;o0;){var s=o.poll(),a=s.getDistance();if(a>=r)break;s.isLeaves()?(r=a,i=s):s.expandToQueue(o,r)}return null===i?null:[i.getBoundable(0).getItem(),i.getBoundable(1).getItem()]}}else{if(2===arguments.length){var u=arguments[0],l=arguments[1];if(this.isEmpty()||u.isEmpty())return null;var h=new ln(this.getRoot(),u.getRoot(),l);return this.nearestNeighbour(h)}if(3===arguments.length){var c=arguments[2],f=new nn(arguments[0],arguments[1]),g=new ln(this.getRoot(),f,c);return this.nearestNeighbour(g)[0]}if(4===arguments.length){var p=arguments[2],v=arguments[3],d=new nn(arguments[0],arguments[1]),y=new ln(this.getRoot(),d,p);return this.nearestNeighbourK(y,v)}}}},{key:"isWithinDistance",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1],n=A.POSITIVE_INFINITY,r=new rn;for(r.add(t);!r.isEmpty();){var i=r.poll(),o=i.getDistance();if(o>e)return!1;if(i.maximumDistance()<=e)return!0;if(i.isLeaves()){if((n=o)<=e)return!0}else i.expandToQueue(r,n)}return!1}if(3===arguments.length){var s=arguments[0],a=arguments[1],u=arguments[2],l=new ln(this.getRoot(),s.getRoot(),a);return this.isWithinDistance(l,u)}}},{key:"interfaces_",get:function(){return[on,w]}}],[{key:"constructor_",value:function(){if(0===arguments.length)s.constructor_.call(this,s.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];cn.constructor_.call(this,t)}}},{key:"centreX",value:function(t){return s.avg(t.getMinX(),t.getMaxX())}},{key:"avg",value:function(t,e){return(t+e)/2}},{key:"getItems",value:function(t){for(var e=new Array(t.size()).fill(null),n=0;!t.isEmpty();){var r=t.poll();e[n]=r.getBoundable(0).getItem(),n++}return e}},{key:"centreY",value:function(t){return s.avg(t.getMinY(),t.getMaxY())}}]),s}(cn),pn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"computeBounds",value:function(){for(var t=null,e=this.getChildBoundables().iterator();e.hasNext();){var n=e.next();null===t?t=new X(n.getBounds()):t.expandToInclude(n.getBounds())}return t}}],[{key:"constructor_",value:function(){var t=arguments[0];sn.constructor_.call(this,t)}}]),o}(sn);gn.STRtreeNode=pn,gn.xComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreX(t.getBounds()),gn.centreX(e.getBounds()))}}]),e}()),gn.yComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreY(t.getBounds()),gn.centreY(e.getBounds()))}}]),e}()),gn.intersectsOp=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[IntersectsOp]}},{key:"intersects",value:function(t,e){return t.intersects(e)}}]),e}()),gn.DEFAULT_NODE_CAPACITY=10;var vn=function(){function e(){t(this,e)}return n(e,null,[{key:"relativeSign",value:function(t,e){return te?1:0}},{key:"compare",value:function(t,n,r){if(n.equals2D(r))return 0;var i=e.relativeSign(n.x,r.x),o=e.relativeSign(n.y,r.y);switch(t){case 0:return e.compareValue(i,o);case 1:return e.compareValue(o,i);case 2:return e.compareValue(o,-i);case 3:return e.compareValue(-i,o);case 4:return e.compareValue(-i,-o);case 5:return e.compareValue(-o,-i);case 6:return e.compareValue(-o,i);case 7:return e.compareValue(i,-o)}return V.shouldNeverReachHere("invalid octant value"),0}},{key:"compareValue",value:function(t,e){return t<0?-1:t>0?1:e<0?-1:e>0?1:0}}]),e}(),dn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this.coord}},{key:"print",value:function(t){t.print(this.coord),t.print(" seg # = "+this.segmentIndex)}},{key:"compareTo",value:function(t){var e=t;return this.segmentIndexe.segmentIndex?1:this.coord.equals2D(e.coord)?0:this._isInterior?e._isInterior?vn.compare(this._segmentOctant,this.coord,e.coord):1:-1}},{key:"isEndPoint",value:function(t){return 0===this.segmentIndex&&!this._isInterior||this.segmentIndex===t}},{key:"toString",value:function(){return this.segmentIndex+":"+this.coord.toString()}},{key:"isInterior",value:function(){return this._isInterior}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;var t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this._segString=t,this.coord=new z(e),this.segmentIndex=n,this._segmentOctant=r,this._isInterior=!e.equals2D(t.getCoordinate(n))}}]),e}(),yn=function(){function e(){t(this,e)}return n(e,[{key:"hasNext",value:function(){}},{key:"next",value:function(){}},{key:"remove",value:function(){}}]),e}(),mn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getSplitCoordinates",value:function(){var t=new Ht;this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next();this.addEdgeCoordinates(n,r,t),n=r}return t.toCoordinateArray()}},{key:"addCollapsedNodes",value:function(){var t=new dt;this.findCollapsesFromInsertedNodes(t),this.findCollapsesFromExistingVertices(t);for(var e=t.iterator();e.hasNext();){var n=e.next().intValue();this.add(this._edge.getCoordinate(n),n)}}},{key:"createSplitEdgePts",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2;if(2===n)return[new z(t.coord),new z(e.coord)];var r=this._edge.getCoordinate(e.segmentIndex),i=e.isInterior()||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this._edge.getCoordinate(a);return i&&(o[s]=new z(e.coord)),o}},{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"findCollapsesFromExistingVertices",value:function(t){for(var e=0;e=0?n>=0?r>=i?0:1:r>=i?7:6:n>=0?r>=i?3:2:r>=i?4:5}if(arguments[0]instanceof z&&arguments[1]instanceof z){var o=arguments[0],s=arguments[1],a=s.x-o.x,u=s.y-o.y;if(0===a&&0===u)throw new x("Cannot compute the octant for two identical points "+o);return e.octant(a,u)}}}]),e}(),xn=function(){function e(){t(this,e)}return n(e,[{key:"getCoordinates",value:function(){}},{key:"size",value:function(){}},{key:"getCoordinate",value:function(t){}},{key:"isClosed",value:function(){}},{key:"setData",value:function(t){}},{key:"getData",value:function(){}}]),e}(),En=function(){function e(){t(this,e)}return n(e,[{key:"addIntersection",value:function(t,e){}},{key:"interfaces_",get:function(){return[xn]}}]),e}(),kn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinates",value:function(){return this._pts}},{key:"size",value:function(){return this._pts.length}},{key:"getCoordinate",value:function(t){return this._pts[t]}},{key:"isClosed",value:function(){return this._pts[0].equals(this._pts[this._pts.length-1])}},{key:"getSegmentOctant",value:function(t){return t===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(t),this.getCoordinate(t+1))}},{key:"setData",value:function(t){this._data=t}},{key:"safeOctant",value:function(t,e){return t.equals2D(e)?0:_n.octant(t,e)}},{key:"getData",value:function(){return this._data}},{key:"addIntersection",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];this.addIntersectionNode(t,e)}else if(4===arguments.length){var n=arguments[1],r=arguments[3],i=new z(arguments[0].getIntersection(r));this.addIntersection(i,n)}}},{key:"toString",value:function(){return Le.toLineString(new $t(this._pts))}},{key:"getNodeList",value:function(){return this._nodeList}},{key:"addIntersectionNode",value:function(t,e){var n=e,r=n+1;if(r=0&&r>=0||n<=0&&r<=0?Math.max(n,r):0}if(arguments[0]instanceof z){var i=arguments[0];return ft.index(this.p0,this.p1,i)}}},{key:"toGeometry",value:function(t){return t.createLineString([this.p0,this.p1])}},{key:"isVertical",value:function(){return this.p0.x===this.p1.x}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.p0.equals(n.p0)&&this.p1.equals(n.p1)}},{key:"intersection",value:function(t){var e=new Ce;return e.computeIntersection(this.p0,this.p1,t.p0,t.p1),e.hasIntersection()?e.getIntersection(0):null}},{key:"project",value:function(){if(arguments[0]instanceof z){var t=arguments[0];if(t.equals(this.p0)||t.equals(this.p1))return new z(t);var n=this.projectionFactor(t),r=new z;return r.x=this.p0.x+n*(this.p1.x-this.p0.x),r.y=this.p0.y+n*(this.p1.y-this.p0.y),r}if(arguments[0]instanceof e){var i=arguments[0],o=this.projectionFactor(i.p0),s=this.projectionFactor(i.p1);if(o>=1&&s>=1)return null;if(o<=0&&s<=0)return null;var a=this.project(i.p0);o<0&&(a=this.p0),o>1&&(a=this.p1);var u=this.project(i.p1);return s<0&&(u=this.p0),s>1&&(u=this.p1),new e(a,u)}}},{key:"normalize",value:function(){this.p1.compareTo(this.p0)<0&&this.reverse()}},{key:"angle",value:function(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)}},{key:"getCoordinate",value:function(t){return 0===t?this.p0:this.p1}},{key:"distancePerpendicular",value:function(t){return kt.pointToLinePerpendicular(t,this.p0,this.p1)}},{key:"minY",value:function(){return Math.min(this.p0.y,this.p1.y)}},{key:"midPoint",value:function(){return e.midPoint(this.p0,this.p1)}},{key:"projectionFactor",value:function(t){if(t.equals(this.p0))return 0;if(t.equals(this.p1))return 1;var e=this.p1.x-this.p0.x,n=this.p1.y-this.p0.y,r=e*e+n*n;return r<=0?A.NaN:((t.x-this.p0.x)*e+(t.y-this.p0.y)*n)/r}},{key:"closestPoints",value:function(t){var e=this.intersection(t);if(null!==e)return[e,e];var n=new Array(2).fill(null),r=A.MAX_VALUE,i=null,o=this.closestPoint(t.p0);r=o.distance(t.p0),n[0]=o,n[1]=t.p0;var s=this.closestPoint(t.p1);(i=s.distance(t.p1))0&&e<1?this.project(t):this.p0.distance(t)1||A.isNaN(e))&&(e=1),e}},{key:"toString",value:function(){return"LINESTRING( "+this.p0.x+" "+this.p0.y+", "+this.p1.x+" "+this.p1.y+")"}},{key:"isHorizontal",value:function(){return this.p0.y===this.p1.y}},{key:"reflect",value:function(t){var e=this.p1.getY()-this.p0.getY(),n=this.p0.getX()-this.p1.getX(),r=this.p0.getY()*(this.p1.getX()-this.p0.getX())-this.p0.getX()*(this.p1.getY()-this.p0.getY()),i=e*e+n*n,o=e*e-n*n,s=t.getX(),a=t.getY();return new z((-o*s-2*e*n*a-2*e*r)/i,(o*a-2*e*n*s-2*n*r)/i)}},{key:"distance",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return kt.segmentToSegment(this.p0,this.p1,t.p0,t.p1)}if(arguments[0]instanceof z){var n=arguments[0];return kt.pointToSegment(n,this.p0,this.p1)}}},{key:"pointAlong",value:function(t){var e=new z;return e.x=this.p0.x+t*(this.p1.x-this.p0.x),e.y=this.p0.y+t*(this.p1.y-this.p0.y),e}},{key:"hashCode",value:function(){var t=A.doubleToLongBits(this.p0.x);t^=31*A.doubleToLongBits(this.p0.y);var e=Math.trunc(t)^Math.trunc(t>>32),n=A.doubleToLongBits(this.p1.x);return n^=31*A.doubleToLongBits(this.p1.y),e^Math.trunc(n)^Math.trunc(n>>32)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this.p0=null,this.p1=null,0===arguments.length)e.constructor_.call(this,new z,new z);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.p0,t.p1)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.p0=n,this.p1=r}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];e.constructor_.call(this,new z(i,o),new z(s,a))}}},{key:"midPoint",value:function(t,e){return new z((t.x+e.x)/2,(t.y+e.y)/2)}}]),e}(),wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"overlap",value:function(){if(2===arguments.length);else if(4===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[3];arguments[0].getLineSegment(t,this._overlapSeg1),e.getLineSegment(n,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}}}],[{key:"constructor_",value:function(){this._overlapSeg1=new bn,this._overlapSeg2=new bn}}]),e}(),In=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLineSegment",value:function(t,e){e.p0=this._pts[t],e.p1=this._pts[t+1]}},{key:"computeSelect",value:function(t,e,n,r){var i=this._pts[e],o=this._pts[n];if(n-e==1)return r.select(this,e),null;if(!t.intersects(i,o))return null;var s=Math.trunc((e+n)/2);e=t.length-1)return t.length-1;for(var r=We.quadrant(t[n],t[n+1]),i=e+1;in.getId()&&(n.computeOverlaps(i,t),this._nOverlaps++),this._segInt.isDone())return null}}}],[{key:"constructor_",value:function(){if(this._monoChains=new dt,this._index=new gn,this._idCounter=0,this._nodedSegStrings=null,this._nOverlaps=0,0===arguments.length);else if(1===arguments.length){var t=arguments[0];Mn.constructor_.call(this,t)}}}]),o}(Mn),Pn=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"overlap",value:function(){if(4!==arguments.length)return f(i(s.prototype),"overlap",this).apply(this,arguments);var t=arguments[1],e=arguments[2],n=arguments[3],r=arguments[0].getContext(),o=e.getContext();this._si.processIntersections(r,t,o,n)}}],[{key:"constructor_",value:function(){this._si=null;var t=arguments[0];this._si=t}}]),s}(wn);Ln.SegmentOverlapAction=Pn;var Cn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isDeletable",value:function(t,e,n,r){var i=this._inputLine[t],o=this._inputLine[e],s=this._inputLine[n];return!!this.isConcave(i,o,s)&&!!this.isShallow(i,o,s,r)&&this.isShallowSampled(i,o,t,n,r)}},{key:"deleteShallowConcavities",value:function(){for(var t=1,n=this.findNextNonDeletedIndex(t),r=this.findNextNonDeletedIndex(n),i=!1;r=0;r--)this.addPt(t[r])}},{key:"isRedundant",value:function(t){if(this._ptList.size()<1)return!1;var e=this._ptList.get(this._ptList.size()-1);return t.distance(e)Math.PI;)t-=e.PI_TIMES_2;for(;t<=-Math.PI;)t+=e.PI_TIMES_2;return t}},{key:"angle",value:function(){if(1===arguments.length){var t=arguments[0];return Math.atan2(t.y,t.x)}if(2===arguments.length){var e=arguments[0],n=arguments[1],r=n.x-e.x,i=n.y-e.y;return Math.atan2(i,r)}}},{key:"isAcute",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)>0}},{key:"isObtuse",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)<0}},{key:"interiorAngle",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return Math.abs(o-i)}},{key:"normalizePositive",value:function(t){if(t<0){for(;t<0;)t+=e.PI_TIMES_2;t>=e.PI_TIMES_2&&(t=0)}else{for(;t>=e.PI_TIMES_2;)t-=e.PI_TIMES_2;t<0&&(t=0)}return t}},{key:"angleBetween",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return e.diff(i,o)}},{key:"diff",value:function(t,e){var n=null;return(n=tMath.PI&&(n=2*Math.PI-n),n}},{key:"toRadians",value:function(t){return t*Math.PI/180}},{key:"getTurn",value:function(t,n){var r=Math.sin(n-t);return r>0?e.COUNTERCLOCKWISE:r<0?e.CLOCKWISE:e.NONE}},{key:"angleBetweenOriented",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r)-i;return o<=-Math.PI?o+e.PI_TIMES_2:o>Math.PI?o-e.PI_TIMES_2:o}}]),e}();On.PI_TIMES_2=2*Math.PI,On.PI_OVER_2=Math.PI/2,On.PI_OVER_4=Math.PI/4,On.COUNTERCLOCKWISE=ft.COUNTERCLOCKWISE,On.CLOCKWISE=ft.CLOCKWISE,On.NONE=ft.COLLINEAR;var Rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addNextSegment",value:function(t,e){if(this._s0=this._s1,this._s1=this._s2,this._s2=t,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;var n=ft.index(this._s0,this._s1,this._s2),r=n===ft.CLOCKWISE&&this._side===tt.LEFT||n===ft.COUNTERCLOCKWISE&&this._side===tt.RIGHT;0===n?this.addCollinear(e):r?this.addOutsideTurn(n,e):this.addInsideTurn(n,e)}},{key:"addLineEndCap",value:function(t,e){var n=new bn(t,e),r=new bn;this.computeOffsetSegment(n,tt.LEFT,this._distance,r);var i=new bn;this.computeOffsetSegment(n,tt.RIGHT,this._distance,i);var o=e.x-t.x,s=e.y-t.y,a=Math.atan2(s,o);switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:this._segList.addPt(r.p1),this.addDirectedFillet(e,a+Math.PI/2,a-Math.PI/2,ft.CLOCKWISE,this._distance),this._segList.addPt(i.p1);break;case y.CAP_FLAT:this._segList.addPt(r.p1),this._segList.addPt(i.p1);break;case y.CAP_SQUARE:var u=new z;u.x=Math.abs(this._distance)*Math.cos(a),u.y=Math.abs(this._distance)*Math.sin(a);var l=new z(r.p1.x+u.x,r.p1.y+u.y),h=new z(i.p1.x+u.x,i.p1.y+u.y);this._segList.addPt(l),this._segList.addPt(h)}}},{key:"getCoordinates",value:function(){return this._segList.getCoordinates()}},{key:"addMitreJoin",value:function(t,e,n,r){var i=_t.intersection(e.p0,e.p1,n.p0,n.p1);if(null!==i&&(r<=0?1:i.distance(t)/Math.abs(r))<=this._bufParams.getMitreLimit())return this._segList.addPt(i),null;this.addLimitedMitreJoin(e,n,r,this._bufParams.getMitreLimit())}},{key:"addOutsideTurn",value:function(t,n){if(this._offset0.p1.distance(this._offset1.p0)=h&&(a-=2*Math.PI),this._segList.addPt(e),this.addDirectedFillet(t,a,h,r,i),this._segList.addPt(n)}},{key:"addLastSegment",value:function(){this._segList.addPt(this._offset1.p1)}},{key:"initSideSegments",value:function(t,e,n){this._s1=t,this._s2=e,this._side=n,this._seg1.setCoordinates(t,e),this.computeOffsetSegment(this._seg1,n,this._distance,this._offset1)}},{key:"addLimitedMitreJoin",value:function(t,e,n,r){var i=this._seg0.p1,o=On.angle(i,this._seg0.p0),s=On.angleBetweenOriented(this._seg0.p0,i,this._seg1.p1)/2,a=On.normalize(o+s),u=On.normalize(a+Math.PI),l=r*n,h=n-l*Math.abs(Math.sin(s)),c=i.x+l*Math.cos(u),f=i.y+l*Math.sin(u),g=new z(c,f),p=new bn(i,g),v=p.pointAlongOffset(1,h),d=p.pointAlongOffset(1,-h);this._side===tt.LEFT?(this._segList.addPt(v),this._segList.addPt(d)):(this._segList.addPt(d),this._segList.addPt(v))}},{key:"addDirectedFillet",value:function(t,e,n,r,i){var o=r===ft.CLOCKWISE?-1:1,s=Math.abs(e-n),a=Math.trunc(s/this._filletAngleQuantum+.5);if(a<1)return null;for(var u=s/a,l=new z,h=0;h0){var r=new z((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(r);var i=new z((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(i)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}}},{key:"createCircle",value:function(t){var e=new z(t.x+this._distance,t.y);this._segList.addPt(e),this.addDirectedFillet(t,0,2*Math.PI,-1,this._distance),this._segList.closeRing()}},{key:"addBevelJoin",value:function(t,e){this._segList.addPt(t.p1),this._segList.addPt(e.p0)}},{key:"init",value:function(t){this._distance=t,this._maxCurveSegmentError=t*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new Tn,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(t*e.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)}},{key:"addCollinear",value:function(t){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2),this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===y.JOIN_BEVEL||this._bufParams.getJoinStyle()===y.JOIN_MITRE?(t&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,ft.CLOCKWISE,this._distance))}},{key:"closeRing",value:function(){this._segList.closeRing()}},{key:"hasNarrowConcaveAngle",value:function(){return this._hasNarrowConcaveAngle}}],[{key:"constructor_",value:function(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new bn,this._seg1=new bn,this._offset0=new bn,this._offset1=new bn,this._side=0,this._hasNarrowConcaveAngle=!1;var t=arguments[0],n=arguments[1],r=arguments[2];this._precisionModel=t,this._bufParams=n,this._li=new Ce,this._filletAngleQuantum=Math.PI/2/n.getQuadrantSegments(),n.getQuadrantSegments()>=8&&n.getJoinStyle()===y.JOIN_ROUND&&(this._closingSegLengthFactor=e.MAX_CLOSING_SEG_LEN_FACTOR),this.init(r)}}]),e}();Rn.OFFSET_SEGMENT_SEPARATION_FACTOR=.001,Rn.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR=.001,Rn.CURVE_VERTEX_SNAP_DISTANCE_FACTOR=1e-6,Rn.MAX_CLOSING_SEG_LEN_FACTOR=80;var An=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getOffsetCurve",value:function(t,e){if(this._distance=e,0===e)return null;var n=e<0,r=Math.abs(e),i=this.getSegGen(r);t.length<=1?this.computePointCurve(t[0],i):this.computeOffsetCurve(t,n,i);var o=i.getCoordinates();return n&&Wt.reverse(o),o}},{key:"computeSingleSidedBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){n.addSegments(t,!0);var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{n.addSegments(t,!1);var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment(),n.closeRing()}},{key:"computeRingBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);e===tt.RIGHT&&(r=-r);var i=Cn.simplify(t,r),o=i.length-1;n.initSideSegments(i[o-1],i[0],e);for(var s=1;s<=o;s++){var a=1!==s;n.addNextSegment(i[s],a)}n.closeRing()}},{key:"computeLineBufferCurve",value:function(t,e){var n=this.simplifyTolerance(this._distance),r=Cn.simplify(t,n),i=r.length-1;e.initSideSegments(r[0],r[1],tt.LEFT);for(var o=2;o<=i;o++)e.addNextSegment(r[o],!0);e.addLastSegment(),e.addLineEndCap(r[i-1],r[i]);var s=Cn.simplify(t,-n),a=s.length-1;e.initSideSegments(s[a],s[a-1],tt.LEFT);for(var u=a-2;u>=0;u--)e.addNextSegment(s[u],!0);e.addLastSegment(),e.addLineEndCap(s[1],s[0]),e.closeRing()}},{key:"computePointCurve",value:function(t,e){switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:e.createCircle(t);break;case y.CAP_SQUARE:e.createSquare(t)}}},{key:"getLineCurve",value:function(t,e){if(this._distance=e,this.isLineOffsetEmpty(e))return null;var n=Math.abs(e),r=this.getSegGen(n);if(t.length<=1)this.computePointCurve(t[0],r);else if(this._bufParams.isSingleSided()){var i=e<0;this.computeSingleSidedBufferCurve(t,i,r)}else this.computeLineBufferCurve(t,r);return r.getCoordinates()}},{key:"getBufferParameters",value:function(){return this._bufParams}},{key:"simplifyTolerance",value:function(t){return t*this._bufParams.getSimplifyFactor()}},{key:"getRingCurve",value:function(t,n,r){if(this._distance=r,t.length<=2)return this.getLineCurve(t,r);if(0===r)return e.copyCoordinates(t);var i=this.getSegGen(r);return this.computeRingBufferCurve(t,n,i),i.getCoordinates()}},{key:"computeOffsetCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment()}},{key:"isLineOffsetEmpty",value:function(t){return 0===t||t<0&&!this._bufParams.isSingleSided()}},{key:"getSegGen",value:function(t){return new Rn(this._precisionModel,this._bufParams,t)}}],[{key:"constructor_",value:function(){this._distance=0,this._precisionModel=null,this._bufParams=null;var t=arguments[0],e=arguments[1];this._precisionModel=t,this._bufParams=e}},{key:"copyCoordinates",value:function(t){for(var e=new Array(t.length).fill(null),n=0;ni.getMaxY()||this.findStabbedSegments(t,r.getDirectedEdges(),e)}return e}if(3===arguments.length)if(ot(arguments[2],rt)&&arguments[0]instanceof z&&arguments[1]instanceof Ke){for(var o=arguments[0],s=arguments[1],a=arguments[2],u=s.getEdge().getCoordinates(),l=0;lthis._seg.p1.y&&this._seg.reverse(),!(Math.max(this._seg.p0.x,this._seg.p1.x)this._seg.p1.y||ft.index(this._seg.p0,this._seg.p1,o)===ft.RIGHT)){var h=s.getDepth(tt.LEFT);this._seg.p0.equals(u[l])||(h=s.getDepth(tt.RIGHT));var c=new Fn(this._seg,h);a.add(c)}}else if(ot(arguments[2],rt)&&arguments[0]instanceof z&&ot(arguments[1],rt))for(var f=arguments[0],g=arguments[2],p=arguments[1].iterator();p.hasNext();){var v=p.next();v.isForward()&&this.findStabbedSegments(f,v,g)}}},{key:"getDepth",value:function(t){var e=this.findStabbedSegments(t);return 0===e.size()?0:an.min(e)._leftDepth}}],[{key:"constructor_",value:function(){this._subgraphs=null,this._seg=new bn;var t=arguments[0];this._subgraphs=t}}]),e}(),Fn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var e=t;if(this._upwardSeg.minX()>=e._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=e._upwardSeg.minX())return-1;var n=this._upwardSeg.orientationIndex(e._upwardSeg);return 0!==n||0!=(n=-1*e._upwardSeg.orientationIndex(this._upwardSeg))?n:this._upwardSeg.compareTo(e._upwardSeg)}},{key:"compareX",value:function(t,e){var n=t.p0.compareTo(e.p0);return 0!==n?n:t.p1.compareTo(e.p1)}},{key:"toString",value:function(){return this._upwardSeg.toString()}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._upwardSeg=null,this._leftDepth=null;var t=arguments[0],e=arguments[1];this._upwardSeg=new bn(t),this._leftDepth=e}}]),e}();Dn.DepthSegment=Fn;var qn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){_.constructor_.call(this,"Projective point not representable on the Cartesian plane.")}}]),o}(_),Vn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getY",value:function(){var t=this.y/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getX",value:function(){var t=this.x/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getCoordinate",value:function(){var t=new z;return t.x=this.getX(),t.y=this.getY(),t}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.w=null,0===arguments.length)this.x=0,this.y=0,this.w=1;else if(1===arguments.length){var t=arguments[0];this.x=t.x,this.y=t.y,this.w=1}else if(2===arguments.length){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var n=arguments[0],r=arguments[1];this.x=n,this.y=r,this.w=1}else if(arguments[0]instanceof e&&arguments[1]instanceof e){var i=arguments[0],o=arguments[1];this.x=i.y*o.w-o.y*i.w,this.y=o.x*i.w-i.x*o.w,this.w=i.x*o.y-o.x*i.y}else if(arguments[0]instanceof z&&arguments[1]instanceof z){var s=arguments[0],a=arguments[1];this.x=s.y-a.y,this.y=a.x-s.x,this.w=s.x*a.y-a.x*s.y}}else if(3===arguments.length){var u=arguments[0],l=arguments[1],h=arguments[2];this.x=u,this.y=l,this.w=h}else if(4===arguments.length){var c=arguments[0],f=arguments[1],g=arguments[2],p=arguments[3],v=c.y-f.y,d=f.x-c.x,y=c.x*f.y-f.x*c.y,m=g.y-p.y,_=p.x-g.x,x=g.x*p.y-p.x*g.y;this.x=d*x-_*y,this.y=m*y-v*x,this.w=v*_-m*d}}}]),e}(),Gn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"area",value:function(){return e.area(this.p0,this.p1,this.p2)}},{key:"signedArea",value:function(){return e.signedArea(this.p0,this.p1,this.p2)}},{key:"interpolateZ",value:function(t){if(null===t)throw new x("Supplied point is null.");return e.interpolateZ(t,this.p0,this.p1,this.p2)}},{key:"longestSideLength",value:function(){return e.longestSideLength(this.p0,this.p1,this.p2)}},{key:"isAcute",value:function(){return e.isAcute(this.p0,this.p1,this.p2)}},{key:"circumcentre",value:function(){return e.circumcentre(this.p0,this.p1,this.p2)}},{key:"area3D",value:function(){return e.area3D(this.p0,this.p1,this.p2)}},{key:"centroid",value:function(){return e.centroid(this.p0,this.p1,this.p2)}},{key:"inCentre",value:function(){return e.inCentre(this.p0,this.p1,this.p2)}}],[{key:"constructor_",value:function(){this.p0=null,this.p1=null,this.p2=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.p0=t,this.p1=e,this.p2=n}},{key:"area",value:function(t,e,n){return Math.abs(((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2)}},{key:"signedArea",value:function(t,e,n){return((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2}},{key:"det",value:function(t,e,n,r){return t*r-e*n}},{key:"interpolateZ",value:function(t,e,n,r){var i=e.x,o=e.y,s=n.x-i,a=r.x-i,u=n.y-o,l=r.y-o,h=s*l-a*u,c=t.x-i,f=t.y-o,g=(l*c-a*f)/h,p=(-u*c+s*f)/h;return e.getZ()+g*(n.getZ()-e.getZ())+p*(r.getZ()-e.getZ())}},{key:"longestSideLength",value:function(t,e,n){var r=t.distance(e),i=e.distance(n),o=n.distance(t),s=r;return i>s&&(s=i),o>s&&(s=o),s}},{key:"circumcentreDD",value:function(t,e,n){var r=lt.valueOf(t.x).subtract(n.x),i=lt.valueOf(t.y).subtract(n.y),o=lt.valueOf(e.x).subtract(n.x),s=lt.valueOf(e.y).subtract(n.y),a=lt.determinant(r,i,o,s).multiply(2),u=r.sqr().add(i.sqr()),l=o.sqr().add(s.sqr()),h=lt.determinant(i,u,s,l),c=lt.determinant(r,u,o,l),f=lt.valueOf(n.x).subtract(h.divide(a)).doubleValue(),g=lt.valueOf(n.y).add(c.divide(a)).doubleValue();return new z(f,g)}},{key:"isAcute",value:function(t,e,n){return!!On.isAcute(t,e,n)&&!!On.isAcute(e,n,t)&&!!On.isAcute(n,t,e)}},{key:"circumcentre",value:function(t,n,r){var i=r.x,o=r.y,s=t.x-i,a=t.y-o,u=n.x-i,l=n.y-o,h=2*e.det(s,a,u,l),c=e.det(a,s*s+a*a,l,u*u+l*l),f=e.det(s,s*s+a*a,u,u*u+l*l);return new z(i-c/h,o+f/h)}},{key:"perpendicularBisector",value:function(t,e){var n=e.x-t.x,r=e.y-t.y,i=new Vn(t.x+n/2,t.y+r/2,1),o=new Vn(t.x-r+n/2,t.y+n+r/2,1);return new Vn(i,o)}},{key:"angleBisector",value:function(t,e,n){var r=e.distance(t),i=r/(r+e.distance(n)),o=n.x-t.x,s=n.y-t.y;return new z(t.x+i*o,t.y+i*s)}},{key:"area3D",value:function(t,e,n){var r=e.x-t.x,i=e.y-t.y,o=e.getZ()-t.getZ(),s=n.x-t.x,a=n.y-t.y,u=n.getZ()-t.getZ(),l=i*u-o*a,h=o*s-r*u,c=r*a-i*s,f=l*l+h*h+c*c;return Math.sqrt(f)/2}},{key:"centroid",value:function(t,e,n){var r=(t.x+e.x+n.x)/3,i=(t.y+e.y+n.y)/3;return new z(r,i)}},{key:"inCentre",value:function(t,e,n){var r=e.distance(n),i=t.distance(n),o=t.distance(e),s=r+i+o,a=(r*t.x+i*e.x+o*n.x)/s,u=(r*t.y+i*e.y+o*n.y)/s;return new z(a,u)}}]),e}(),Bn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addRingSide",value:function(t,e,n,r,i){if(0===e&&t.length=zt.MINIMUM_VALID_SIZE&&ft.isCCW(t)&&(o=i,s=r,n=tt.opposite(n));var a=this._curveBuilder.getRingCurve(t,n,e);this.addCurve(a,o,s)}},{key:"addRingBothSides",value:function(t,e){this.addRingSide(t,e,tt.LEFT,Z.EXTERIOR,Z.INTERIOR),this.addRingSide(t,e,tt.RIGHT,Z.INTERIOR,Z.EXTERIOR)}},{key:"addPoint",value:function(t){if(this._distance<=0)return null;var e=t.getCoordinates(),n=this._curveBuilder.getLineCurve(e,this._distance);this.addCurve(n,Z.EXTERIOR,Z.INTERIOR)}},{key:"addPolygon",value:function(t){var e=this._distance,n=tt.LEFT;this._distance<0&&(e=-this._distance,n=tt.RIGHT);var r=t.getExteriorRing(),i=Wt.removeRepeatedPoints(r.getCoordinates());if(this._distance<0&&this.isErodedCompletely(r,this._distance))return null;if(this._distance<=0&&i.length<3)return null;this.addRingSide(i,e,n,Z.EXTERIOR,Z.INTERIOR);for(var o=0;o0&&this.isErodedCompletely(s,-this._distance)||this.addRingSide(a,e,tt.opposite(n),Z.INTERIOR,Z.EXTERIOR)}}},{key:"isTriangleErodedCompletely",value:function(t,e){var n=new Gn(t[0],t[1],t[2]),r=n.inCentre();return kt.pointToSegment(r,n.p0,n.p1)i}},{key:"addCollection",value:function(t){for(var e=0;e=this._max)throw new W;var t=this._parent.getGeometryN(this._index++);return t instanceof Bt?(this._subcollectionIterator=new e(t),this._subcollectionIterator.next()):t}},{key:"remove",value:function(){throw new J(this.getClass().getName())}},{key:"hasNext",value:function(){if(this._atStart)return!0;if(null!==this._subcollectionIterator){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)}},{key:"interfaces_",get:function(){return[yn]}}],[{key:"constructor_",value:function(){this._parent=null,this._atStart=null,this._max=null,this._index=null,this._subcollectionIterator=null;var t=arguments[0];this._parent=t,this._atStart=!0,this._index=0,this._max=t.getNumGeometries()}},{key:"isAtomic",value:function(t){return!(t instanceof Bt)}}]),e}(),jn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"locate",value:function(t){return e.locate(t,this._geom)}},{key:"interfaces_",get:function(){return[Yn]}}],[{key:"constructor_",value:function(){this._geom=null;var t=arguments[0];this._geom=t}},{key:"locatePointInPolygon",value:function(t,n){if(n.isEmpty())return Z.EXTERIOR;var r=n.getExteriorRing(),i=e.locatePointInRing(t,r);if(i!==Z.INTERIOR)return i;for(var o=0;o=0;n--){var r=this._edgeList.get(n),i=r.getSym();null===e&&(e=i),null!==t&&i.setNext(t),t=r}e.setNext(t)}},{key:"computeDepths",value:function(){if(1===arguments.length){var t=arguments[0],e=this.findIndex(t),n=t.getDepth(tt.LEFT),r=t.getDepth(tt.RIGHT),i=this.computeDepths(e+1,this._edgeList.size(),n);if(this.computeDepths(0,e,i)!==r)throw new pt("depth mismatch at "+t.getCoordinate())}else if(3===arguments.length){for(var o=arguments[1],s=arguments[2],a=arguments[0];a=0;i--){var o=this._resultAreaEdgeList.get(i),s=o.getSym();switch(null===e&&o.getEdgeRing()===t&&(e=o),r){case this._SCANNING_FOR_INCOMING:if(s.getEdgeRing()!==t)continue;n=s,r=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(o.getEdgeRing()!==t)continue;n.setNextMin(o),r=this._SCANNING_FOR_INCOMING}}r===this._LINKING_TO_OUTGOING&&(V.isTrue(null!==e,"found null for first outgoing dirEdge"),V.isTrue(e.getEdgeRing()===t,"unable to link last incoming dirEdge"),n.setNextMin(e))}},{key:"getOutgoingDegree",value:function(){if(0===arguments.length){for(var t=0,e=this.iterator();e.hasNext();)e.next().isInResult()&&t++;return t}if(1===arguments.length){for(var n=arguments[0],r=0,i=this.iterator();i.hasNext();)i.next().getEdgeRing()===n&&r++;return r}}},{key:"getLabel",value:function(){return this._label}},{key:"findCoveredLineEdges",value:function(){for(var t=Z.NONE,e=this.iterator();e.hasNext();){var n=e.next(),r=n.getSym();if(!n.isLineEdge()){if(n.isInResult()){t=Z.INTERIOR;break}if(r.isInResult()){t=Z.EXTERIOR;break}}}if(t===Z.NONE)return null;for(var i=t,o=this.iterator();o.hasNext();){var s=o.next(),a=s.getSym();s.isLineEdge()?s.getEdge().setCovered(i===Z.INTERIOR):(s.isInResult()&&(i=Z.EXTERIOR),a.isInResult()&&(i=Z.INTERIOR))}}},{key:"computeLabelling",value:function(t){f(i(s.prototype),"computeLabelling",this).call(this,t),this._label=new Ae(Z.NONE);for(var e=this.iterator();e.hasNext();)for(var n=e.next().getEdge().getLabel(),r=0;r<2;r++){var o=n.getLocation(r);o!==Z.INTERIOR&&o!==Z.BOUNDARY||this._label.setLocation(r,Z.INTERIOR)}}}],[{key:"constructor_",value:function(){this._resultAreaEdgeList=null,this._label=null,this._SCANNING_FOR_INCOMING=1,this._LINKING_TO_OUTGOING=2}}]),s}(Xn),Zn=function(e){r(o,e);var i=c(o);function o(){return t(this,o),i.call(this)}return n(o,[{key:"createNode",value:function(t){return new Ge(t,new Un)}}]),o}(Qe),Hn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var n=t;return e.compareOriented(this._pts,this._orientation,n._pts,n._orientation)}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._pts=null,this._orientation=null;var t=arguments[0];this._pts=t,this._orientation=e.orientation(t)}},{key:"orientation",value:function(t){return 1===Wt.increasingDirection(t)}},{key:"compareOriented",value:function(t,e,n,r){for(var i=e?1:-1,o=r?1:-1,s=e?t.length:-1,a=r?n.length:-1,u=e?0:t.length-1,l=r?0:n.length-1;;){var h=t[u].compareTo(n[l]);if(0!==h)return h;var c=(u+=i)===s,f=(l+=o)===a;if(c&&!f)return-1;if(!c&&f)return 1;if(c&&f)return 0}}}]),e}(),Wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.print("MULTILINESTRING ( ");for(var e=0;e0&&t.print(","),t.print("(");for(var r=n.getCoordinates(),i=0;i0&&t.print(","),t.print(r[i].x+" "+r[i].y);t.println(")")}t.print(") ")}},{key:"addAll",value:function(t){for(var e=t.iterator();e.hasNext();)this.add(e.next())}},{key:"findEdgeIndex",value:function(t){for(var e=0;et?1:this.diste?1:0}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this.coord=null,this.segmentIndex=null,this.dist=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.coord=new z(t),this.segmentIndex=e,this.dist=n}}]),e}(),$n=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this._nodeMap.values().iterator()}},{key:"addSplitEdges",value:function(t){this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next(),i=this.createSplitEdge(n,r);t.add(i),n=r}}},{key:"addEndpoints",value:function(){var t=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[t],t,0)}},{key:"createSplitEdge",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2,r=this.edge.pts[e.segmentIndex],i=e.dist>0||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this.edge.pts[a];return i&&(o[s]=e.coord),new or(o,new Ae(this.edge._label))}},{key:"add",value:function(t,e,n){var r=new Qn(t,e,n),i=this._nodeMap.get(r);return null!==i?i:(this._nodeMap.put(r,r),r)}},{key:"isIntersection",value:function(t){for(var e=this.iterator();e.hasNext();)if(e.next().coord.equals(t))return!0;return!1}}],[{key:"constructor_",value:function(){this._nodeMap=new Ze,this.edge=null;var t=arguments[0];this.edge=t}}]),e}(),tr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isIntersects",value:function(){return!this.isDisjoint()}},{key:"isCovers",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"isCoveredBy",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"set",value:function(){if(1===arguments.length)for(var t=arguments[0],e=0;e=0&&e>=0&&this.setAtLeast(t,e,n)}},{key:"isWithin",value:function(){return e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"isTouches",value:function(t,n){return t>n?this.isTouches(n,t):(t===Mt.A&&n===Mt.A||t===Mt.L&&n===Mt.L||t===Mt.L&&n===Mt.A||t===Mt.P&&n===Mt.A||t===Mt.P&&n===Mt.L)&&this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&(e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))}},{key:"isOverlaps",value:function(t,n){return t===Mt.P&&n===Mt.P||t===Mt.A&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&1===this._matrix[Z.INTERIOR][Z.INTERIOR]&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR])}},{key:"isEquals",value:function(t,n){return t===n&&e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"toString",value:function(){for(var t=new Qt("123456789"),e=0;e<3;e++)for(var n=0;n<3;n++)t.setCharAt(3*e+n,Mt.toDimensionSymbol(this._matrix[e][n]));return t.toString()}},{key:"setAll",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this._matrix[e][n]=t}},{key:"get",value:function(t,e){return this._matrix[t][e]}},{key:"transpose",value:function(){var t=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=t,t=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=t,t=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=t,this}},{key:"matches",value:function(t){if(9!==t.length)throw new x("Should be length 9: "+t);for(var n=0;n<3;n++)for(var r=0;r<3;r++)if(!e.matches(this._matrix[n][r],t.charAt(3*n+r)))return!1;return!0}},{key:"add",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this.setAtLeast(e,n,t.get(e,n))}},{key:"isDisjoint",value:function(){return this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.INTERIOR][Z.BOUNDARY]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.BOUNDARY]===Mt.FALSE}},{key:"isCrosses",value:function(t,n){return t===Mt.P&&n===Mt.L||t===Mt.P&&n===Mt.A||t===Mt.L&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR]):t===Mt.L&&n===Mt.P||t===Mt.A&&n===Mt.P||t===Mt.A&&n===Mt.L?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&0===this._matrix[Z.INTERIOR][Z.INTERIOR]}},{key:"interfaces_",get:function(){return[b]}}],[{key:"constructor_",value:function(){if(this._matrix=null,0===arguments.length)this._matrix=Array(3).fill().map((function(){return Array(3)})),this.setAll(Mt.FALSE);else if(1===arguments.length)if("string"==typeof arguments[0]){var t=arguments[0];e.constructor_.call(this),this.set(t)}else if(arguments[0]instanceof e){var n=arguments[0];e.constructor_.call(this),this._matrix[Z.INTERIOR][Z.INTERIOR]=n._matrix[Z.INTERIOR][Z.INTERIOR],this._matrix[Z.INTERIOR][Z.BOUNDARY]=n._matrix[Z.INTERIOR][Z.BOUNDARY],this._matrix[Z.INTERIOR][Z.EXTERIOR]=n._matrix[Z.INTERIOR][Z.EXTERIOR],this._matrix[Z.BOUNDARY][Z.INTERIOR]=n._matrix[Z.BOUNDARY][Z.INTERIOR],this._matrix[Z.BOUNDARY][Z.BOUNDARY]=n._matrix[Z.BOUNDARY][Z.BOUNDARY],this._matrix[Z.BOUNDARY][Z.EXTERIOR]=n._matrix[Z.BOUNDARY][Z.EXTERIOR],this._matrix[Z.EXTERIOR][Z.INTERIOR]=n._matrix[Z.EXTERIOR][Z.INTERIOR],this._matrix[Z.EXTERIOR][Z.BOUNDARY]=n._matrix[Z.EXTERIOR][Z.BOUNDARY],this._matrix[Z.EXTERIOR][Z.EXTERIOR]=n._matrix[Z.EXTERIOR][Z.EXTERIOR]}}},{key:"matches",value:function(){if(Number.isInteger(arguments[0])&&"string"==typeof arguments[1]){var t=arguments[0],n=arguments[1];return n===Mt.SYM_DONTCARE||n===Mt.SYM_TRUE&&(t>=0||t===Mt.TRUE)||n===Mt.SYM_FALSE&&t===Mt.FALSE||n===Mt.SYM_P&&t===Mt.P||n===Mt.SYM_L&&t===Mt.L||n===Mt.SYM_A&&t===Mt.A}if("string"==typeof arguments[0]&&"string"==typeof arguments[1]){var r=arguments[1];return new e(arguments[0]).matches(r)}}},{key:"isTrue",value:function(t){return t>=0||t===Mt.TRUE}}]),e}(),er=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"size",value:function(){return this._size}},{key:"addAll",value:function(t){return null===t||0===t.length?null:(this.ensureCapacity(this._size+t.length),xt.arraycopy(t,0,this._data,this._size,t.length),void(this._size+=t.length))}},{key:"ensureCapacity",value:function(t){if(t<=this._data.length)return null;var e=Math.max(t,2*this._data.length);this._data=At.copyOf(this._data,e)}},{key:"toArray",value:function(){var t=new Array(this._size).fill(null);return xt.arraycopy(this._data,0,t,0,this._size),t}},{key:"add",value:function(t){this.ensureCapacity(this._size+1),this._data[this._size]=t,++this._size}}],[{key:"constructor_",value:function(){if(this._data=null,this._size=0,0===arguments.length)e.constructor_.call(this,10);else if(1===arguments.length){var t=arguments[0];this._data=new Array(t).fill(null)}}}]),e}(),nr=function(){function e(){t(this,e)}return n(e,[{key:"getChainStartIndices",value:function(t){var e=0,n=new er(Math.trunc(t.length/2));n.add(e);do{var r=this.findChainEnd(t,e);n.add(r),e=r}while(en?e:n}},{key:"getMinX",value:function(t){var e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return ee&&(r=1),this._depth[t][n]=r}}}},{key:"getDelta",value:function(t){return this._depth[t][tt.RIGHT]-this._depth[t][tt.LEFT]}},{key:"getLocation",value:function(t,e){return this._depth[t][e]<=0?Z.EXTERIOR:Z.INTERIOR}},{key:"toString",value:function(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}},{key:"add",value:function(){if(1===arguments.length)for(var t=arguments[0],n=0;n<2;n++)for(var r=1;r<3;r++){var i=t.getLocation(n,r);i!==Z.EXTERIOR&&i!==Z.INTERIOR||(this.isNull(n,r)?this._depth[n][r]=e.depthAtLocation(i):this._depth[n][r]+=e.depthAtLocation(i))}else if(3===arguments.length){var o=arguments[0],s=arguments[1];arguments[2]===Z.INTERIOR&&this._depth[o][s]++}}}],[{key:"constructor_",value:function(){this._depth=Array(2).fill().map((function(){return Array(3)}));for(var t=0;t<2;t++)for(var n=0;n<3;n++)this._depth[t][n]=e.NULL_VALUE}},{key:"depthAtLocation",value:function(t){return t===Z.EXTERIOR?0:t===Z.INTERIOR?1:e.NULL_VALUE}}]),e}();ir.NULL_VALUE=-1;var or=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getDepth",value:function(){return this._depth}},{key:"getCollapsedEdge",value:function(){var t=new Array(2).fill(null);return t[0]=this.pts[0],t[1]=this.pts[1],new s(t,Ae.toLineLabel(this._label))}},{key:"isIsolated",value:function(){return this._isIsolated}},{key:"getCoordinates",value:function(){return this.pts}},{key:"setIsolated",value:function(t){this._isIsolated=t}},{key:"setName",value:function(t){this._name=t}},{key:"equals",value:function(t){if(!(t instanceof s))return!1;var e=t;if(this.pts.length!==e.pts.length)return!1;for(var n=!0,r=!0,i=this.pts.length,o=0;o0?this.pts[0]:null;if(1===arguments.length){var t=arguments[0];return this.pts[t]}}},{key:"print",value:function(t){t.print("edge "+this._name+": "),t.print("LINESTRING (");for(var e=0;e0&&t.print(","),t.print(this.pts[e].x+" "+this.pts[e].y);t.print(") "+this._label+" "+this._depthDelta)}},{key:"computeIM",value:function(t){s.updateIM(this._label,t)}},{key:"isCollapsed",value:function(){return!!this._label.isArea()&&3===this.pts.length&&!!this.pts[0].equals(this.pts[2])}},{key:"isClosed",value:function(){return this.pts[0].equals(this.pts[this.pts.length-1])}},{key:"getMaximumSegmentIndex",value:function(){return this.pts.length-1}},{key:"getDepthDelta",value:function(){return this._depthDelta}},{key:"getNumPoints",value:function(){return this.pts.length}},{key:"printReverse",value:function(t){t.print("edge "+this._name+": ");for(var e=this.pts.length-1;e>=0;e--)t.print(this.pts[e]+" ");t.println("")}},{key:"getMonotoneChainEdge",value:function(){return null===this._mce&&(this._mce=new rr(this)),this._mce}},{key:"getEnvelope",value:function(){if(null===this._env){this._env=new X;for(var t=0;t0&&t.append(","),t.append(this.pts[e].x+" "+this.pts[e].y);return t.append(") "+this._label+" "+this._depthDelta),t.toString()}},{key:"isPointwiseEqual",value:function(t){if(this.pts.length!==t.pts.length)return!1;for(var e=0;er||this._maxyo;if(s)return!1;var a=this.intersectsToleranceSquare(t,e);return V.isTrue(!(s&&a),"Found bad envelope test"),a}},{key:"initCorners",value:function(t){var e=.5;this._minx=t.x-e,this._maxx=t.x+e,this._miny=t.y-e,this._maxy=t.y+e,this._corner[0]=new z(this._maxx,this._maxy),this._corner[1]=new z(this._minx,this._maxy),this._corner[2]=new z(this._minx,this._miny),this._corner[3]=new z(this._maxx,this._miny)}},{key:"intersects",value:function(t,e){return 1===this._scaleFactor?this.intersectsScaled(t,e):(this.copyScaled(t,this._p0Scaled),this.copyScaled(e,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}},{key:"scale",value:function(t){return Math.round(t*this._scaleFactor)}},{key:"getCoordinate",value:function(){return this._originalPt}},{key:"copyScaled",value:function(t,e){e.x=this.scale(t.x),e.y=this.scale(t.y)}},{key:"getSafeEnvelope",value:function(){if(null===this._safeEnv){var t=e.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new X(this._originalPt.x-t,this._originalPt.x+t,this._originalPt.y-t,this._originalPt.y+t)}return this._safeEnv}},{key:"intersectsPixelClosure",value:function(t,e){return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.hasIntersection()))))}},{key:"intersectsToleranceSquare",value:function(t,e){var n=!1,r=!1;return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.isProper()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.isProper()||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.isProper()||(this._li.hasIntersection()&&(r=!0),this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.isProper()||n&&r||t.equals(this._pt)||e.equals(this._pt)))))}},{key:"addSnappedNode",value:function(t,e){var n=t.getCoordinate(e),r=t.getCoordinate(e+1);return!!this.intersects(n,r)&&(t.addIntersection(this.getCoordinate(),e),!0)}}],[{key:"constructor_",value:function(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;var t=arguments[0],e=arguments[1],n=arguments[2];if(this._originalPt=t,this._pt=t,this._scaleFactor=e,this._li=n,e<=0)throw new x("Scale factor must be non-zero");1!==e&&(this._pt=new z(this.scale(t.x),this.scale(t.y)),this._p0Scaled=new z,this._p1Scaled=new z),this.initCorners(this._pt)}}]),e}();lr.SAFE_ENV_EXPANSION_FACTOR=.75;var hr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"select",value:function(){if(1===arguments.length);else if(2===arguments.length){var t=arguments[1];arguments[0].getLineSegment(t,this.selectedSegment),this.select(this.selectedSegment)}}}],[{key:"constructor_",value:function(){this.selectedSegment=new bn}}]),e}(),cr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"snap",value:function(){if(1===arguments.length){var e=arguments[0];return this.snap(e,null,-1)}if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=r.getSafeEnvelope(),a=new fr(r,i,o);return this._index.query(s,new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[hn]}},{key:"visitItem",value:function(t){t.select(s,a)}}]),e}())),a.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var t=arguments[0];this._index=t}}]),e}(),fr=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isNodeAdded",value:function(){return this._isNodeAdded}},{key:"select",value:function(){if(!(2===arguments.length&&Number.isInteger(arguments[1])&&arguments[0]instanceof In))return f(i(s.prototype),"select",this).apply(this,arguments);var t=arguments[1],e=arguments[0].getContext();if(this._parentEdge===e&&(t===this._hotPixelVertexIndex||t+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(e,t)}}],[{key:"constructor_",value:function(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var t=arguments[0],e=arguments[1],n=arguments[2];this._hotPixel=t,this._parentEdge=e,this._hotPixelVertexIndex=n}}]),s}(hr);cr.HotPixelSnapAction=fr;var gr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"processIntersections",value:function(t,e,n,r){if(t===n&&e===r)return null;var i=t.getCoordinates()[e],o=t.getCoordinates()[e+1],s=n.getCoordinates()[r],a=n.getCoordinates()[r+1];if(this._li.computeIntersection(i,o,s,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var u=0;u=0;t--){try{this.bufferReducedPrecision(t)}catch(t){if(!(t instanceof pt))throw t;this._saveException=t}if(null!==this._resultGeometry)return null}throw this._saveException}if(1===arguments.length){var n=arguments[0],r=e.precisionScaleFactor(this._argGeom,this._distance,n),i=new ie(r);this.bufferFixedPrecision(i)}}},{key:"computeGeometry",value:function(){if(this.bufferOriginalPrecision(),null!==this._resultGeometry)return null;var t=this._argGeom.getFactory().getPrecisionModel();t.getType()===ie.FIXED?this.bufferFixedPrecision(t):this.bufferReducedPrecision()}},{key:"setQuadrantSegments",value:function(t){this._bufParams.setQuadrantSegments(t)}},{key:"bufferOriginalPrecision",value:function(){try{var t=new sr(this._bufParams);this._resultGeometry=t.buffer(this._argGeom,this._distance)}catch(t){if(!(t instanceof F))throw t;this._saveException=t}}},{key:"getResultGeometry",value:function(t){return this._distance=t,this.computeGeometry(),this._resultGeometry}},{key:"setEndCapStyle",value:function(t){this._bufParams.setEndCapStyle(t)}}],[{key:"constructor_",value:function(){if(this._argGeom=null,this._distance=null,this._bufParams=new y,this._resultGeometry=null,this._saveException=null,1===arguments.length){var t=arguments[0];this._argGeom=t}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this._argGeom=e,this._bufParams=n}}},{key:"bufferOp",value:function(){if(2===arguments.length){var t=arguments[1];return new e(arguments[0]).getResultGeometry(t)}if(3===arguments.length){if(Number.isInteger(arguments[2])&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var n=arguments[1],r=arguments[2],i=new e(arguments[0]);return i.setQuadrantSegments(r),i.getResultGeometry(n)}if(arguments[2]instanceof y&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var o=arguments[1];return new e(arguments[0],arguments[2]).getResultGeometry(o)}}else if(4===arguments.length){var s=arguments[1],a=arguments[2],u=arguments[3],l=new e(arguments[0]);return l.setQuadrantSegments(a),l.setEndCapStyle(u),l.getResultGeometry(s)}}},{key:"precisionScaleFactor",value:function(t,e,n){var r=t.getEnvelopeInternal(),i=Et.max(Math.abs(r.getMaxX()),Math.abs(r.getMaxY()),Math.abs(r.getMinX()),Math.abs(r.getMinY()))+2*(e>0?e:0),o=n-Math.trunc(Math.log(i)/Math.log(10)+1);return Math.pow(10,o)}}]),e}();vr.CAP_ROUND=y.CAP_ROUND,vr.CAP_BUTT=y.CAP_FLAT,vr.CAP_FLAT=y.CAP_FLAT,vr.CAP_SQUARE=y.CAP_SQUARE,vr.MAX_PRECISION_DIGITS=12;var dr=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],yr=function(){function e(n){t(this,e),this.geometryFactory=n||new ae}return n(e,[{key:"read",value:function(t){var e,n=(e="string"==typeof t?JSON.parse(t):t).type;if(!mr[n])throw new Error("Unknown GeoJSON type: "+e.type);return-1!==dr.indexOf(n)?mr[n].call(this,e.coordinates):"GeometryCollection"===n?mr[n].call(this,e.geometries):mr[n].call(this,e)}},{key:"write",value:function(t){var e=t.getGeometryType();if(!_r[e])throw new Error("Geometry is not supported");return _r[e].call(this,t)}}]),e}(),mr={Feature:function(t){var e={};for(var n in t)e[n]=t[n];if(t.geometry){var r=t.geometry.type;if(!mr[r])throw new Error("Unknown GeoJSON type: "+t.type);e.geometry=this.read(t.geometry)}return t.bbox&&(e.bbox=mr.bbox.call(this,t.bbox)),e},FeatureCollection:function(t){var e={};if(t.features){e.features=[];for(var n=0;n1?0:t<-1?Xn:Math.acos(t)}function ir(t){return t>1?Un:t<-1?-Un:Math.asin(t)}function or(){}function sr(t,e){t&&ur.hasOwnProperty(t.type)&&ur[t.type](t,e)}var ar={Feature:function(t,e){sr(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++rXn?t-Hn:t<-Xn?t+Hn:t,e]}function xr(t){return function(e,n){return[(e+=t)>Xn?e-Hn:e<-Xn?e+Hn:e,n]}}function Er(t){var e=xr(t);return e.invert=xr(-t),e}function kr(t,e){var n=tr(t),r=er(t),i=tr(e),o=er(e);function s(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*n+a*r;return[$n(u*i-h*o,a*n-l*r),ir(h*i+u*o)]}return s.invert=function(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*i-u*o;return[$n(u*i+l*o,a*n+h*r),ir(h*n-a*r)]},s}function br(t,e){(e=fr(e))[0]-=t,yr(e);var n=rr(-e[1]);return((-e[2]<0?-n:n)+Hn-jn)%Hn}function wr(){var t,e=[];return{point:function(e,n){t.push([e,n])},lineStart:function(){e.push(t=[])},lineEnd:or,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function Ir(t,e){return Kn(t[0]-e[0])=0;--o)i.point((h=l[o])[0],h[1]);else r(f.x,f.p.x,-1,i);f=f.p}l=(f=f.o).z,g=!g}while(!f.v);i.lineEnd()}}}function Mr(t){if(e=t.length){for(var e,n,r=0,i=t[0];++re?1:t>=e?0:NaN}function Pr(t){for(var e,n,r,i=t.length,o=-1,s=0;++o=0;)for(e=(r=t[i]).length;--e>=0;)n[--s]=r[e];return n}Gn(),Gn(),Gn(),_r.invert=_r,function(t){var e;1===t.length&&(e=t,t=function(t,n){return Lr(e(t),n)})}(Lr);var Cr=1e9,Tr=-Cr;function Or(t,e,n,r){function i(i,o){return t<=i&&i<=n&&e<=o&&o<=r}function o(i,o,a,l){var h=0,c=0;if(null==i||(h=s(i,a))!==(c=s(o,a))||u(i,o)<0^a>0)do{l.point(0===h||3===h?t:n,h>1?r:e)}while((h=(h+a+4)%4)!==c);else l.point(o[0],o[1])}function s(r,i){return Kn(r[0]-t)0?0:3:Kn(r[0]-n)0?2:1:Kn(r[1]-e)0?1:0:i>0?3:2}function a(t,e){return u(t.x,e.x)}function u(t,e){var n=s(t,1),r=s(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){var u,l,h,c,f,g,p,v,d,y,m,_=s,x=wr(),E={point:k,lineStart:function(){E.point=b,l&&l.push(h=[]);y=!0,d=!1,p=v=NaN},lineEnd:function(){u&&(b(c,f),g&&d&&x.rejoin(),u.push(x.result()));E.point=k,d&&_.lineEnd()},polygonStart:function(){_=x,u=[],l=[],m=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,i=l.length;nr&&(f-o)*(r-s)>(g-s)*(t-o)&&++e:g<=r&&(f-o)*(r-s)<(g-s)*(t-o)&&--e;return e}(),n=m&&e,i=(u=Pr(u)).length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),o(null,null,1,s),s.lineEnd()),i&&Sr(u,a,e,o,s),s.polygonEnd());_=s,u=l=h=null}};function k(t,e){i(t,e)&&_.point(t,e)}function b(o,s){var a=i(o,s);if(l&&h.push([o,s]),y)c=o,f=s,g=a,y=!1,a&&(_.lineStart(),_.point(o,s));else if(a&&d)_.point(o,s);else{var u=[p=Math.max(Tr,Math.min(Cr,p)),v=Math.max(Tr,Math.min(Cr,v))],x=[o=Math.max(Tr,Math.min(Cr,o)),s=Math.max(Tr,Math.min(Cr,s))];!function(t,e,n,r,i,o){var s,a=t[0],u=t[1],l=0,h=1,c=e[0]-a,f=e[1]-u;if(s=n-a,c||!(s>0)){if(s/=c,c<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=i-a,c||!(s<0)){if(s/=c,c<0){if(s>h)return;s>l&&(l=s)}else if(c>0){if(s0)){if(s/=f,f<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=o-u,f||!(s<0)){if(s/=f,f<0){if(s>h)return;s>l&&(l=s)}else if(f>0){if(s0&&(t[0]=a+l*c,t[1]=u+l*f),h<1&&(e[0]=a+h*c,e[1]=u+h*f),!0}}}}}(u,x,t,e,n,r)?a&&(_.lineStart(),_.point(o,s),m=!1):(d||(_.lineStart(),_.point(u[0],u[1])),_.point(x[0],x[1]),a||_.lineEnd(),m=!1)}p=o,v=s,d=a}return E}}var Rr=Gn();function Ar(t){return t}Gn(),Gn(),Gn();var Dr=1/0,Fr=Dr,qr=-Dr,Vr=qr,Gr={point:function(t,e){tqr&&(qr=t);eVr&&(Vr=e)},lineStart:or,lineEnd:or,polygonStart:or,polygonEnd:or,result:function(){var t=[[Dr,Fr],[qr,Vr]];return qr=Vr=-(Fr=Dr=1/0),t}};function Br(t,e,n,r){return function(i,o){var s,a,u,l=e(o),h=i.invert(r[0],r[1]),c=wr(),f=e(c),g=!1,p={point:v,lineStart:y,lineEnd:m,polygonStart:function(){p.point=_,p.lineStart=x,p.lineEnd=E,a=[],s=[]},polygonEnd:function(){p.point=v,p.lineStart=y,p.lineEnd=m,a=Pr(a);var t=function(t,e){var n=e[0],r=e[1],i=[er(n),-tr(n),0],o=0,s=0;Rr.reset();for(var a=0,u=t.length;a=0?1:-1,w=b*k,I=w>Xn,N=p*x;if(Rr.add($n(N*b*er(w),v*E+N*tr(w))),o+=I?k+b*Hn:k,I^f>=n^m>=n){var S=pr(fr(c),fr(y));yr(S);var M=pr(i,S);yr(M);var L=(I^k>=0?-1:1)*ir(M[2]);(r>L||r===L&&(S[0]||S[1]))&&(s+=I^k>=0?1:-1)}}return(o<-jn||o0){for(g||(o.polygonStart(),g=!0),o.lineStart(),t=0;t1&&2&i&&l.push(l.pop().concat(l.shift())),a.push(l.filter(Yr))}return p}}function Yr(t){return t.length>1}function zr(t,e){return((t=t.x)[0]<0?t[1]-Un-jn:Un-t[1])-((e=e.x)[0]<0?e[1]-Un-jn:Un-e[1])}Gn();var jr=Br((function(){return!0}),(function(t){var e,n=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,s){var a=o>0?Xn:-Xn,u=Kn(o-n);Kn(u-Xn)0?Un:-Un),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),e=0):i!==a&&u>=Xn&&(Kn(n-i)jn?Qn((er(e)*(o=tr(r))*er(n)-er(r)*(i=tr(e))*er(t))/(i*o*s)):(e+r)/2}(n,r,o,s),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),e=0),t.point(n=o,r=s),i=a},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var i;if(null==t)i=n*Un,r.point(-Xn,i),r.point(0,i),r.point(Xn,i),r.point(Xn,0),r.point(Xn,-i),r.point(0,-i),r.point(-Xn,-i),r.point(-Xn,0),r.point(-Xn,i);else if(Kn(t[0]-e[0])>jn){var o=t[0]0,i=Kn(n)>jn;function o(t,e){return tr(t)*tr(e)>n}function s(t,e,r){var i=[1,0,0],o=pr(fr(t),fr(e)),s=gr(o,o),a=o[0],u=s-a*a;if(!u)return!r&&t;var l=n*s/u,h=-n*a/u,c=pr(i,o),f=dr(i,l);vr(f,dr(o,h));var g=c,p=gr(f,g),v=gr(g,g),d=p*p-v*(gr(f,f)-1);if(!(d<0)){var y=nr(d),m=dr(g,(-p-y)/v);if(vr(m,f),m=cr(m),!r)return m;var _,x=t[0],E=e[0],k=t[1],b=e[1];E0^m[1]<(Kn(m[0]-x)Xn^(x<=m[0]&&m[0]<=E)){var N=dr(g,(-p+y)/v);return vr(N,f),[m,cr(N)]}}}function a(e,n){var i=r?t:Xn-t,o=0;return e<-i?o|=1:e>i&&(o|=2),n<-i?o|=4:n>i&&(o|=8),o}return Br(o,(function(t){var e,n,u,l,h;return{lineStart:function(){l=u=!1,h=1},point:function(c,f){var g,p=[c,f],v=o(c,f),d=r?v?0:a(c,f):v?a(c+(c<0?Xn:-Xn),f):0;if(!e&&(l=u=v)&&t.lineStart(),v!==u&&(!(g=s(e,p))||Ir(e,g)||Ir(p,g))&&(p[0]+=jn,p[1]+=jn,v=o(p[0],p[1])),v!==u)h=0,v?(t.lineStart(),g=s(p,e),t.point(g[0],g[1])):(g=s(e,p),t.point(g[0],g[1]),t.lineEnd()),e=g;else if(i&&e&&r^v){var y;d&n||!(y=s(p,e,!0))||(h=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1])))}!v||e&&Ir(e,p)||t.point(p[0],p[1]),e=p,u=v,n=d},lineEnd:function(){u&&t.lineEnd(),e=null},clean:function(){return h|(l&&u)<<1}}}),(function(n,r,i,o){!function(t,e,n,r,i,o){if(n){var s=tr(e),a=er(e),u=r*n;null==i?(i=e+r*Hn,o=e-u/2):(i=br(s,i),o=br(s,o),(r>0?io)&&(i+=r*Hn));for(var l,h=i;r>0?h>o:h4*e&&v--){var x=s+f,E=a+g,k=u+p,b=nr(x*x+E*E+k*k),w=ir(k/=b),I=Kn(Kn(k)-1)e||Kn((y*L+m*P)/_-.5)>.3||s*f+a*g+u*p2?t[2]%360*Jn:0,M()):[d*Wn,y*Wn,m*Wn]},I.precision=function(t){return arguments.length?(w=Kr(S,b=t*t),L()):nr(b)},I.fitExtent=function(t,e){return Hr(I,t,e)},I.fitSize=function(t,e){return function(t,e,n){return Hr(t,[[0,0],e],n)}(I,t,e)},function(){return e=t.apply(this,arguments),I.invert=e.invert&&N,M()}}((function(){return t}))()}function ti(t){return function(e,n){var r=tr(e),i=tr(n),o=t(r*i);return[o*i*er(e),o*er(n)]}}function ei(t){return function(e,n){var r=nr(e*e+n*n),i=t(r),o=er(i),s=tr(i);return[$n(e*o,r*s),ir(r&&n*o/r)]}}ti((function(t){return nr(2/(1+t))})).invert=ei((function(t){return 2*ir(t/2)}));var ni=ti((function(t){return(t=rr(t))&&t/er(t)}));function ri(){return $r(ni).scale(79.4188).clipAngle(179.999)}function ii(t,e){return[t,e]}ni.invert=ei((function(t){return t})),ii.invert=ii;var oi=Vn.BufferOp,si=Vn.GeoJSONReader,ai=Vn.GeoJSONWriter;function ui(t,e,n,r){var i=t.properties||{},o="Feature"===t.type?t.geometry:t;if("GeometryCollection"===o.type){var s=[];return mt(t,(function(t){var i=ui(t,e,n,r);i&&s.push(i)})),C(s)}var a=function(t){var e=An(t).geometry.coordinates,n=[-e[0],-e[1]];return ri().rotate(n).scale(x)}(o),u={type:o.type,coordinates:hi(o.coordinates,a)},l=(new si).read(u),h=F(q(e,n),"meters"),c=oi.bufferOp(l,h,r);if(!li((c=(new ai).write(c)).coordinates))return b({type:c.type,coordinates:ci(c.coordinates,a)},i)}function li(t){return Array.isArray(t[0])?li(t[0]):isNaN(t[0])}function hi(t,e){return"object"!==m(t[0])?e(t):t.map((function(t){return hi(t,e)}))}function ci(t,e){return"object"!==m(t[0])?e.invert(t):t.map((function(t){return ci(t,e)}))}function fi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return mt(t,(function(t,o,s){var a=e.weight?null==s?void 0:s[e.weight]:void 0;if(!U(a=null==a?1:a))throw new Error("weight value must be a number for feature index "+o);(a=Number(a))>0&&ct(t,(function(t){n+=t[0]*a,r+=t[1]*a,i+=a}))})),I([n/i,r/i],e.properties,e)}function gi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return ct(t,(function(t){n+=t[0],r+=t[1],i++}),!0),I([n/i,r/i],e.properties)}function pi(t,e,n,r,i){var o=r.tolerance||.001,s=0,a=0,u=0,l=0;if(vt(n,(function(e){var n,r=null==(n=e.properties)?void 0:n.weight,i=null==r?1:r;if(!U(i=Number(i)))throw new Error("weight value must be a number");if(i>0){l+=1;var o=i*ut(e,t);0===o&&(o=1);var h=i/o;s+=e.geometry.coordinates[0]*h,a+=e.geometry.coordinates[1]*h,u+=h}})),l<1)throw new Error("no features to measure");var h=s/u,c=a/u;return 1===l||0===i||Math.abs(h-e[0])0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mi;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function mi(t,e){return te?1:0}var _i,xi,Ei,ki,bi,wi=_n(Object.freeze({__proto__:null,default:yi})),Ii={exports:{}};function Ni(){if(bi)return Ii.exports;bi=1;var t=(xi||(xi=1,_i=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=(r-n)/2,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),_i),e=(ki||(ki=1,Ei=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=r-n,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),Ei);return Ii.exports=function(n,r,i,o){return r.length>0&&Array.isArray(r[0])?e(n,r,i,o):t(n,r,i,o)},Ii.exports.nested=e,Ii.exports.flat=t,Ii.exports}var Si,Mi,Li={exports:{}};Li.exports;function Pi(){return Si||(Si=1,function(t,e){!function(t){var e=134217729,n=33306690738754706e-32;function r(t,e,n,r,i){var o,s,a,u,l=e[0],h=r[0],c=0,f=0;h>l==h>-l?(o=l,l=e[++c]):(o=h,h=r[++f]);var g=0;if(cl==h>-l?(a=o-((s=l+o)-l),l=e[++c]):(a=o-((s=h+o)-h),h=r[++f]),o=s,0!==a&&(i[g++]=a);cl==h>-l?(a=o-((s=o+l)-(u=s-o))+(l-u),l=e[++c]):(a=o-((s=o+h)-(u=s-o))+(h-u),h=r[++f]),o=s,0!==a&&(i[g++]=a);for(;c0!=m>0)return _;var x=Math.abs(y+m);return Math.abs(_)>=o*x?_:-function(t,i,o,g,p,v,d){var y,m,_,x,E,k,b,w,I,N,S,M,L,P,C,T,O,R,A=t-p,D=o-p,F=i-v,q=g-v;E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=q-(I=(k=e*q)-(k-q)))-((P=A*q)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=D-(I=(k=e*D)-(k-D)))-((T=F*D)-b*I-w*I-b*N))),u[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),u[1]=L-(S+E)+(E-T),E=(R=M+S)-M,u[2]=M-(R-E)+(S-E),u[3]=R;var V=function(t,e){for(var n=e[0],r=1;r=G||-V>=G)return V;if(y=t-(A+(E=t-A))+(E-p),_=o-(D+(E=o-D))+(E-p),m=i-(F+(E=i-F))+(E-v),x=g-(q+(E=g-q))+(E-v),0===y&&0===m&&0===_&&0===x)return V;if(G=a*d+n*Math.abs(V),(V+=A*x+q*y-(F*_+D*m))>=G||-V>=G)return V;E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=q-(I=(k=e*q)-(k-q)))-((P=y*q)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=D-(I=(k=e*D)-(k-D)))-((T=m*D)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var B=r(4,u,4,f,l);E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=x-(I=(k=e*x)-(k-x)))-((P=A*x)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=_-(I=(k=e*_)-(k-_)))-((T=F*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var Y=r(B,l,4,f,h);E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=x-(I=(k=e*x)-(k-x)))-((P=y*x)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=_-(I=(k=e*_)-(k-_)))-((T=m*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var z=r(Y,h,4,f,c);return c[z-1]}(t,i,g,p,v,d,x)},t.orient2dfast=function(t,e,n,r,i,o){return(e-o)*(n-i)-(t-i)*(r-o)},Object.defineProperty(t,"__esModule",{value:!0})}(e)}(0,Li.exports)),Li.exports}var Ci=function(){if(Mi)return vi.exports;Mi=1;var t=di,e=wi,n=Ni(),r=Pi().orient2d;function i(e,r,i){r=Math.max(0,void 0===r?2:r),i=i||0;var s=function(t){for(var e=t[0],r=t[0],i=t[0],o=t[0],s=0;si[0]&&(i=a),a[1]o[1]&&(o=a)}var u=[e,r,i,o],l=u.slice();for(s=0;s=2&&h(e[e.length-2],e[e.length-1],t[n])<=0;)e.pop();e.push(t[n])}for(var r=[],i=t.length-1;i>=0;i--){for(;r.length>=2&&h(r[r.length-2],r[r.length-1],t[i])<=0;)r.pop();r.push(t[i])}return r.pop(),e.pop(),e.concat(r)}(l)}(e),a=new t(16);a.toBBox=function(t){return{minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]}},a.compareMinX=function(t,e){return t[0]-e[0]},a.compareMinY=function(t,e){return t[1]-e[1]},a.load(e);for(var u,l=[],p=0;pu||c.push({node:v,dist:d})}for(;c.length&&!c.peek().node.children;){var y=c.pop(),m=y.node,_=p(m,n,r),x=p(m,i,o);if(y.dist<_&&y.dist=e.minX&&t[0]<=e.maxX&&t[1]>=e.minY&&t[1]<=e.maxY}function l(t,e,n){for(var r,i,o,s,a=Math.min(t[0],e[0]),u=Math.min(t[1],e[1]),l=Math.max(t[0],e[0]),c=Math.max(t[1],e[1]),f=n.search({minX:a,minY:u,maxX:l,maxY:c}),g=0;g0!=h(r,i,s)>0&&h(o,s,r)>0!=h(o,s,i)>0)return!1;return!0}function h(t,e,n){return r(t[0],t[1],e[0],e[1],n[0],n[1])}function c(t){var e=t.p,n=t.next.p;return t.minX=Math.min(e[0],n[0]),t.minY=Math.min(e[1],n[1]),t.maxX=Math.max(e[0],n[0]),t.maxY=Math.max(e[1],n[1]),t}function f(t,e){var n={p:t,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return e?(n.next=e.next,n.prev=e,e.next.prev=n,e.next=n):(n.prev=n,n.next=n),n}function g(t,e){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function p(t,e,n){var r=e[0],i=e[1],o=n[0]-r,s=n[1]-i;if(0!==o||0!==s){var a=((t[0]-r)*o+(t[1]-i)*s)/(o*o+s*s);a>1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function v(t,e,n,r,i,o,s,a){var u,l,h,c,f=n-t,g=r-e,p=s-i,v=a-o,d=t-i,y=e-o,m=f*f+g*g,_=f*p+g*v,x=p*p+v*v,E=f*d+g*y,k=p*d+v*y,b=m*x-_*_,w=b,I=b;0===b?(l=0,w=1,c=k,I=x):(c=m*k-_*E,(l=_*k-x*E)<0?(l=0,c=k,I=x):l>w&&(l=w,c=k+_,I=x)),c<0?(c=0,-E<0?l=0:-E>m?l=w:(l=-E,w=m)):c>I&&(c=I,-E+_<0?l=0:-E+_>m?l=w:(l=-E+_,w=m));var N=(1-(h=0===c?0:c/I))*i+h*s-((1-(u=0===l?0:l/w))*t+u*n),S=(1-h)*o+h*a-((1-u)*e+u*r);return N*N+S*S}function d(t,e){return t[0]===e[0]?t[1]-e[1]:t[0]-e[0]}return e.default&&(e=e.default),vi.exports=i,vi.exports.default=i,vi.exports}(),Ti=mn(Ci);function Oi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e.concavity=e.concavity||1/0;var n=[];if(ct(t,(function(t){n.push([t[0],t[1]])})),!n.length)return null;var r=Ti(n,e.concavity);return r.length>3?S([r]):null}function Ri(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.steps||64,i=n.properties?n.properties:!Array.isArray(t)&&"Feature"===t.type&&t.properties?t.properties:{},o=[],s=0;s0;r.length0;){var a=t[Math.floor(Math.random()*o)],u=s?a.join("_"):""+a;n[u]||(n[u]=!0,r.push(a))}if(r.length0,u=t[Math.floor(Math.random()*s)];for(a&&u.join("_"),o.push(u);o.length0,y=[];if(s)u="kmrand"==s?r(t,e):"kmpp"==s?i(t,e):s;else for(var m={};u.lengthc&&(c=t[a].y);var g,p=l-u,v=c-h,d=p>v?p:v,y=.5*(l+u),m=.5*(c+h),_=[new so({__sentinel:!0,x:y-20*d,y:m-d},{__sentinel:!0,x:y,y:m+20*d},{__sentinel:!0,x:y+20*d,y:m-d})],x=[],E=[];a=t.length;for(;a--;){for(E.length=0,g=_.length;g--;)(p=t[a].x-_[g].x)>0&&p*p>_[g].r?(x.push(_[g]),_.splice(g,1)):p*p+(v=t[a].y-_[g].y)*v>_[g].r||(E.push(_[g].a,_[g].b,_[g].b,_[g].c,_[g].c,_[g].a),_.splice(g,1));for(uo(E),g=E.length;g;)n=E[--g],e=E[--g],r=t[a],i=n.x-e.x,o=n.y-e.y,s=2*(i*(r.y-n.y)-o*(r.x-n.x)),Math.abs(s)>f&&_.push(new so(e,n,r))}Array.prototype.push.apply(x,_),a=x.length;for(;a--;)(x[a].a.__sentinel||x[a].b.__sentinel||x[a].c.__sentinel)&&x.splice(a,1);return x}(t.features.map((function(t){var r={x:t.geometry.coordinates[0],y:t.geometry.coordinates[1]};return e?r.z=t.properties[e]:3===t.geometry.coordinates.length&&(n=!0,r.z=t.geometry.coordinates[2]),r}))).map((function(t){var e=[t.a.x,t.a.y],r=[t.b.x,t.b.y],i=[t.c.x,t.c.y],o={};return n?(e.push(t.a.z),r.push(t.b.z),i.push(t.c.z)):o={a:t.a.z,b:t.b.z,c:t.c.z},S([[e,r,i,e]],o)})))}var so=s((function t(e,n,r){i(this,t),this.a=e,this.b=n,this.c=r;var o,s,a=n.x-e.x,u=n.y-e.y,l=r.x-e.x,h=r.y-e.y,c=a*(e.x+n.x)+u*(e.y+n.y),f=l*(e.x+r.x)+h*(e.y+r.y),g=2*(a*(r.y-n.y)-u*(r.x-n.x));this.x=(h*c-u*f)/g,this.y=(a*f-l*c)/g,o=this.x-e.x,s=this.y-e.y,this.r=o*o+s*s}));function ao(t,e){return e.x-t.x}function uo(t){var e,n,r,i,o,s=t.length;t:for(;s;)for(n=t[--s],e=t[--s],r=s;r;)if(o=t[--r],e===(i=t[--r])&&n===o||e===o&&n===i){t.splice(s,2),t.splice(r,2),s-=2;continue t}}function lo(t){return t}function ho(t,e){var n=function(t){if(null==t)return lo;var e,n,r=t.scale[0],i=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,a){a||(e=n=0);var u=2,l=t.length,h=new Array(l);for(h[0]=(e+=t[0])*r+o,h[1]=(n+=t[1])*i+s;u1)for(var o,a,u=1,l=s(i[0]);ul&&(a=i[0],i[0]=i[u],i[u]=a,l=o);return i})).filter((function(t){return t.length>0}))}}var po=Object.prototype.hasOwnProperty;function vo(t,e,n,r,i,o){3===arguments.length&&(r=o=Array,i=null);for(var s=new r(t=1<=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},maybeSet:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},get:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)break;h=s[l=l+1&u]}return o},keys:function(){for(var t=[],e=0,n=s.length;e>7^xo[2]^xo[3])}function ko(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=function(){for(var t=vo(1.4*o.length,E,k,Int32Array,-1,Int32Array),e=new Int32Array(o.length),n=0,r=o.length;n=0){var o=c[n];i===e&&o===r||i===r&&o===e||(++g,f[n]=1)}else h[n]=e,c[n]=r}}function E(t){return Eo(o[t])}function k(t,e){return yo(o[t],o[e])}l=h=c=null;var b,w=function(t,e,n,r,i){3===arguments.length&&(r=Array,i=null);for(var o=new r(t=1<=t)throw new Error("full hashset");u=o[a=a+1&s]}return o[a]=r,!0},has:function(r){for(var a=e(r)&s,u=o[a],l=0;u!=i;){if(n(u,r))return!0;if(++l>=t)break;u=o[a=a+1&s]}return!1},values:function(){for(var t=[],e=0,n=o.length;e>1);er&&(r=o),si&&(i=s)}function u(t){t.forEach(a)}function l(t){t.forEach(u)}for(var h in t)o(t[h]);return r>=e&&i>=n?[e,n,r,i]:void 0}(t=Io(t)),r=function(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=s.length+a.length;for(delete t.lines,delete t.rings,r=0,i=s.length;r1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=[],i=It(t,(function(t,e){var n=function(t,e){var n,r=t.geometry.coordinates,i=e.geometry.coordinates,o=Oo(r[0]),s=Oo(r[r.length-1]),a=Oo(i[0]),u=Oo(i[i.length-1]);if(o===u)n=i.concat(r.slice(1));else if(a===s)n=r.concat(i.slice(1));else if(o===a)n=r.slice(1).reverse().concat(i);else{if(s!==u)return null;n=r.concat(i.reverse().slice(1))}return L(n)}(t,e);return n||(r.push(t),e)}));return i&&r.push(i),r.length?1===r.length?r[0]:T(r.map((function(t){return t.coordinates}))):null}function Oo(t){return t[0].toString()+","+t[1].toString()}function Ro(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=function(t){var e={};xt(t,(function(t){e[t.geometry.type]=!0}));var n=Object.keys(e);if(1===n.length)return n[0];return null}(t);if(!r)throw new Error("geojson must be homogenous");var i=t;switch(r){case"LineString":return To(i,e);case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==e.mutate&&void 0!==e.mutate||(t=Ai(t));var n=[];xt(t,(function(t){n.push(t.geometry)}));var r=Lo({geoms:A(n).geometry});return fo(r,r.objects.geoms.geometries)}(i,e);default:throw new Error(r+" is not supported")}}var Ao=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Do=Math.ceil,Fo=Math.floor,qo="[BigNumber Error] ",Vo=qo+"Number primitive has more than 15 significant digits: ",Go=1e14,Bo=14,Yo=9007199254740991,zo=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Xo=1e9;function Uo(t){var e=0|t;return t>0||t===e?e:e-1}function Zo(t){for(var e,n,r=1,i=t.length,o=t[0]+"";rl^n?1:-1;for(a=(u=i.length)<(l=o.length)?u:l,s=0;so[s]^n?1:-1;return u==l?0:u>l^n?1:-1}function Wo(t,e,n,r){if(tn||t!==Fo(t))throw Error(qo+(r||"Argument")+("number"==typeof t?tn?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Jo(t){var e=t.c.length-1;return Uo(t.e/Bo)==e&&t.c[e]%2!=0}function Ko(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Qo(t,e,n){var r,i;if(e<0){for(i=n+".";++e;i+=n);t=i+t}else if(++e>(r=t.length)){for(i=n,e-=r;--e;i+=n);t+=i}else ex?f.c=f.e=null:t.e<_?f.c=[f.e=0]:(f.e=t.e,f.c=t.c.slice()));if((l="number"==typeof t)&&0*t==0){if(f.s=1/t<0?(t=-t,-1):1,t===~~t){for(a=0,u=t;u>=10;u/=10,a++);return void(a>x?f.c=f.e=null:(f.e=a,f.c=[t]))}c=String(t)}else{if(!Ao.test(c=String(t)))return i(f,c,l);f.s=45==c.charCodeAt(0)?(c=c.slice(1),-1):1}(a=c.indexOf("."))>-1&&(c=c.replace(".","")),(u=c.search(/e/i))>0?(a<0&&(a=u),a+=+c.slice(u+1),c=c.substring(0,u)):a<0&&(a=c.length)}else{if(Wo(e,2,I.length,"Base"),10==e&&N)return C(f=new S(t),p+f.e+1,v);if(c=String(t),l="number"==typeof t){if(0*t!=0)return i(f,c,l,e);if(f.s=1/t<0?(c=c.slice(1),-1):1,S.DEBUG&&c.replace(/^0\.0*|\./,"").length>15)throw Error(Vo+t)}else f.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1;for(n=I.slice(0,e),a=u=0,h=c.length;ua){a=h;continue}}else if(!s&&(c==c.toUpperCase()&&(c=c.toLowerCase())||c==c.toLowerCase()&&(c=c.toUpperCase()))){s=!0,u=-1,a=0;continue}return i(f,String(t),l,e)}l=!1,(a=(c=r(c,e,10,f.s)).indexOf("."))>-1?c=c.replace(".",""):a=c.length}for(u=0;48===c.charCodeAt(u);u++);for(h=c.length;48===c.charCodeAt(--h););if(c=c.slice(u,++h)){if(h-=u,l&&S.DEBUG&&h>15&&(t>Yo||t!==Fo(t)))throw Error(Vo+f.s*t);if((a=a-u-1)>x)f.c=f.e=null;else if(a<_)f.c=[f.e=0];else{if(f.e=a,f.c=[],u=(a+1)%Bo,a<0&&(u+=Bo),u=y)?Ko(u,s):Qo(u,s,"0");else if(o=(t=C(new S(t),e,n)).e,a=(u=Zo(t.c)).length,1==r||2==r&&(e<=o||o<=d)){for(;aa){if(--e>0)for(u+=".";e--;u+="0");}else if((e+=o-a)>0)for(o+1==a&&(u+=".");e--;u+="0");return t.s<0&&i?"-"+u:u}function L(t,e){for(var n,r,i=1,o=new S(t[0]);i=10;i/=10,r++);return(n=r+n*Bo-1)>x?t.c=t.e=null:n<_?t.c=[t.e=0]:(t.e=n,t.c=e),t}function C(t,e,n,r){var i,o,s,a,u,l,h,c=t.c,f=zo;if(c){t:{for(i=1,a=c[0];a>=10;a/=10,i++);if((o=e-i)<0)o+=Bo,s=e,u=c[l=0],h=Fo(u/f[i-s-1]%10);else if((l=Do((o+1)/Bo))>=c.length){if(!r)break t;for(;c.length<=l;c.push(0));u=h=0,i=1,s=(o%=Bo)-Bo+1}else{for(u=a=c[l],i=1;a>=10;a/=10,i++);h=(s=(o%=Bo)-Bo+i)<0?0:Fo(u/f[i-s-1]%10)}if(r=r||e<0||null!=c[l+1]||(s<0?u:u%f[i-s-1]),r=n<4?(h||r)&&(0==n||n==(t.s<0?3:2)):h>5||5==h&&(4==n||r||6==n&&(o>0?s>0?u/f[i-s]:0:c[l-1])%10&1||n==(t.s<0?8:7)),e<1||!c[0])return c.length=0,r?(e-=t.e+1,c[0]=f[(Bo-e%Bo)%Bo],t.e=-e||0):c[0]=t.e=0,t;if(0==o?(c.length=l,a=1,l--):(c.length=l+1,a=f[Bo-o],c[l]=s>0?Fo(u/f[i-s]%f[s])*a:0),r)for(;;){if(0==l){for(o=1,s=c[0];s>=10;s/=10,o++);for(s=c[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(t.e++,c[0]==Go&&(c[0]=1));break}if(c[l]+=a,c[l]!=Go)break;c[l--]=0,a=1}for(o=c.length;0===c[--o];c.pop());}t.e>x?t.c=t.e=null:t.e<_&&(t.c=[t.e=0])}return t}function T(t){var e,n=t.e;return null===n?t.toString():(e=Zo(t.c),e=n<=d||n>=y?Ko(e,n):Qo(e,n,"0"),t.s<0?"-"+e:e)}return S.clone=t,S.ROUND_UP=0,S.ROUND_DOWN=1,S.ROUND_CEIL=2,S.ROUND_FLOOR=3,S.ROUND_HALF_UP=4,S.ROUND_HALF_DOWN=5,S.ROUND_HALF_EVEN=6,S.ROUND_HALF_CEIL=7,S.ROUND_HALF_FLOOR=8,S.EUCLID=9,S.config=S.set=function(t){var e,n;if(null!=t){if("object"!=m(t))throw Error(qo+"Object expected: "+t);if(t.hasOwnProperty(e="DECIMAL_PLACES")&&(Wo(n=t[e],0,Xo,e),p=n),t.hasOwnProperty(e="ROUNDING_MODE")&&(Wo(n=t[e],0,8,e),v=n),t.hasOwnProperty(e="EXPONENTIAL_AT")&&((n=t[e])&&n.pop?(Wo(n[0],-Xo,0,e),Wo(n[1],0,Xo,e),d=n[0],y=n[1]):(Wo(n,-Xo,Xo,e),d=-(y=n<0?-n:n))),t.hasOwnProperty(e="RANGE"))if((n=t[e])&&n.pop)Wo(n[0],-Xo,-1,e),Wo(n[1],1,Xo,e),_=n[0],x=n[1];else{if(Wo(n,-Xo,Xo,e),!n)throw Error(qo+e+" cannot be zero: "+n);_=-(x=n<0?-n:n)}if(t.hasOwnProperty(e="CRYPTO")){if((n=t[e])!==!!n)throw Error(qo+e+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw E=!n,Error(qo+"crypto unavailable");E=n}else E=n}if(t.hasOwnProperty(e="MODULO_MODE")&&(Wo(n=t[e],0,9,e),k=n),t.hasOwnProperty(e="POW_PRECISION")&&(Wo(n=t[e],0,Xo,e),b=n),t.hasOwnProperty(e="FORMAT")){if("object"!=m(n=t[e]))throw Error(qo+e+" not an object: "+n);w=n}if(t.hasOwnProperty(e="ALPHABET")){if("string"!=typeof(n=t[e])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(qo+e+" invalid: "+n);N="0123456789"==n.slice(0,10),I=n}}return{DECIMAL_PLACES:p,ROUNDING_MODE:v,EXPONENTIAL_AT:[d,y],RANGE:[_,x],CRYPTO:E,MODULO_MODE:k,POW_PRECISION:b,FORMAT:w,ALPHABET:I}},S.isBigNumber=function(t){if(!t||!0!==t._isBigNumber)return!1;if(!S.DEBUG)return!0;var e,n,r=t.c,i=t.e,o=t.s;t:if("[object Array]"=={}.toString.call(r)){if((1===o||-1===o)&&i>=-Xo&&i<=Xo&&i===Fo(i)){if(0===r[0]){if(0===i&&1===r.length)return!0;break t}if((e=(i+1)%Bo)<1&&(e+=Bo),String(r[0]).length==e){for(e=0;e=Go||n!==Fo(n))break t;if(0!==n)return!0}}}else if(null===r&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(qo+"Invalid BigNumber: "+t)},S.maximum=S.max=function(){return L(arguments,-1)},S.minimum=S.min=function(){return L(arguments,1)},S.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Fo(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(t){var e,n,r,i,o,a=0,u=[],l=new S(g);if(null==t?t=p:Wo(t,0,Xo),i=Do(t/Bo),E)if(crypto.getRandomValues){for(e=crypto.getRandomValues(new Uint32Array(i*=2));a>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),e[a]=n[0],e[a+1]=n[1]):(u.push(o%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw E=!1,Error(qo+"crypto unavailable");for(e=crypto.randomBytes(i*=7);a=9e15?crypto.randomBytes(7).copy(e,a):(u.push(o%1e14),a+=7);a=i/7}if(!E)for(;a=10;o/=10,a++);an-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(r,i,o,s,a){var u,l,h,c,f,g,d,y,m=r.indexOf("."),_=p,x=v;for(m>=0&&(c=b,b=0,r=r.replace(".",""),g=(y=new S(i)).pow(r.length-m),b=c,y.c=e(Qo(Zo(g.c),g.e,"0"),10,o,t),y.e=y.c.length),h=c=(d=e(r,i,o,a?(u=I,t):(u=t,I))).length;0==d[--c];d.pop());if(!d[0])return u.charAt(0);if(m<0?--h:(g.c=d,g.e=h,g.s=s,d=(g=n(g,y,_,x,o)).c,f=g.r,h=g.e),m=d[l=h+_+1],c=o/2,f=f||l<0||null!=d[l+1],f=x<4?(null!=m||f)&&(0==x||x==(g.s<0?3:2)):m>c||m==c&&(4==x||f||6==x&&1&d[l-1]||x==(g.s<0?8:7)),l<1||!d[0])r=f?Qo(u.charAt(1),-_,u.charAt(0)):u.charAt(0);else{if(d.length=l,f)for(--o;++d[--l]>o;)d[l]=0,l||(++h,d=[1].concat(d));for(c=d.length;!d[--c];);for(m=0,r="";m<=c;r+=u.charAt(d[m++]));r=Qo(r,h,u.charAt(0))}return r}}(),n=function(){function t(t,e,n){var r,i,o,s,a=0,u=t.length,l=e%jo,h=e/jo|0;for(t=t.slice();u--;)a=((i=l*(o=t[u]%jo)+(r=h*o+(s=t[u]/jo|0)*l)%jo*jo+a)/n|0)+(r/jo|0)+h*s,t[u]=i%n;return a&&(t=[a].concat(t)),t}function e(t,e,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;ie[i]?1:-1;break}return o}function n(t,e,n,r){for(var i=0;n--;)t[n]-=i,i=t[n]1;t.splice(0,1));}return function(r,i,o,s,a){var u,l,h,c,f,g,p,v,d,y,m,_,x,E,k,b,w,I=r.s==i.s?1:-1,N=r.c,M=i.c;if(!(N&&N[0]&&M&&M[0]))return new S(r.s&&i.s&&(N?!M||N[0]!=M[0]:M)?N&&0==N[0]||!M?0*I:I/0:NaN);for(d=(v=new S(I)).c=[],I=o+(l=r.e-i.e)+1,a||(a=Go,l=Uo(r.e/Bo)-Uo(i.e/Bo),I=I/Bo|0),h=0;M[h]==(N[h]||0);h++);if(M[h]>(N[h]||0)&&l--,I<0)d.push(1),c=!0;else{for(E=N.length,b=M.length,h=0,I+=2,(f=Fo(a/(M[0]+1)))>1&&(M=t(M,f,a),N=t(N,f,a),b=M.length,E=N.length),x=b,m=(y=N.slice(0,b)).length;m=a/2&&k++;do{if(f=0,(u=e(M,y,b,m))<0){if(_=y[0],b!=m&&(_=_*a+(y[1]||0)),(f=Fo(_/k))>1)for(f>=a&&(f=a-1),p=(g=t(M,f,a)).length,m=y.length;1==e(g,y,p,m);)f--,n(g,b=10;I/=10,h++);C(v,o+(v.e=h+l*Bo-1)+1,s,c)}else v.e=l,v.r=+c;return v}}(),a=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,l=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,c=/^\s*\+(?=[\w.])|^\s+|\s+$/g,i=function(t,e,n,r){var i,o=n?e:e.replace(c,"");if(h.test(o))t.s=isNaN(o)?null:o<0?-1:1;else{if(!n&&(o=o.replace(a,(function(t,e,n){return i="x"==(n=n.toLowerCase())?16:"b"==n?2:8,r&&r!=i?t:e})),r&&(i=r,o=o.replace(u,"$1").replace(l,"0.$1")),e!=o))return new S(o,i);if(S.DEBUG)throw Error(qo+"Not a"+(r?" base "+r:"")+" number: "+e);t.s=null}t.c=t.e=null},f.absoluteValue=f.abs=function(){var t=new S(this);return t.s<0&&(t.s=1),t},f.comparedTo=function(t,e){return Ho(this,new S(t,e))},f.decimalPlaces=f.dp=function(t,e){var n,r,i,o=this;if(null!=t)return Wo(t,0,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t+o.e+1,e);if(!(n=o.c))return null;if(r=((i=n.length-1)-Uo(this.e/Bo))*Bo,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},f.dividedBy=f.div=function(t,e){return n(this,new S(t,e),p,v)},f.dividedToIntegerBy=f.idiv=function(t,e){return n(this,new S(t,e),0,1)},f.exponentiatedBy=f.pow=function(t,e){var n,r,i,o,s,a,u,l,h=this;if((t=new S(t)).c&&!t.isInteger())throw Error(qo+"Exponent not an integer: "+T(t));if(null!=e&&(e=new S(e)),s=t.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!t.c||!t.c[0])return l=new S(Math.pow(+T(h),s?t.s*(2-Jo(t)):+T(t))),e?l.mod(e):l;if(a=t.s<0,e){if(e.c?!e.c[0]:!e.s)return new S(NaN);(r=!a&&h.isInteger()&&e.isInteger())&&(h=h.mod(e))}else{if(t.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return o=h.s<0&&Jo(t)?-0:0,h.e>-1&&(o=1/o),new S(a?1/o:o);b&&(o=Do(b/Bo+2))}for(s?(n=new S(.5),a&&(t.s=1),u=Jo(t)):u=(i=Math.abs(+T(t)))%2,l=new S(g);;){if(u){if(!(l=l.times(h)).c)break;o?l.c.length>o&&(l.c.length=o):r&&(l=l.mod(e))}if(i){if(0===(i=Fo(i/2)))break;u=i%2}else if(C(t=t.times(n),t.e+1,1),t.e>14)u=Jo(t);else{if(0===(i=+T(t)))break;u=i%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):r&&(h=h.mod(e))}return r?l:(a&&(l=g.div(l)),e?l.mod(e):o?C(l,b,v,undefined):l)},f.integerValue=function(t){var e=new S(this);return null==t?t=v:Wo(t,0,8),C(e,e.e+1,t)},f.isEqualTo=f.eq=function(t,e){return 0===Ho(this,new S(t,e))},f.isFinite=function(){return!!this.c},f.isGreaterThan=f.gt=function(t,e){return Ho(this,new S(t,e))>0},f.isGreaterThanOrEqualTo=f.gte=function(t,e){return 1===(e=Ho(this,new S(t,e)))||0===e},f.isInteger=function(){return!!this.c&&Uo(this.e/Bo)>this.c.length-2},f.isLessThan=f.lt=function(t,e){return Ho(this,new S(t,e))<0},f.isLessThanOrEqualTo=f.lte=function(t,e){return-1===(e=Ho(this,new S(t,e)))||0===e},f.isNaN=function(){return!this.s},f.isNegative=function(){return this.s<0},f.isPositive=function(){return this.s>0},f.isZero=function(){return!!this.c&&0==this.c[0]},f.minus=function(t,e){var n,r,i,o,s=this,a=s.s;if(e=(t=new S(t,e)).s,!a||!e)return new S(NaN);if(a!=e)return t.s=-e,s.plus(t);var u=s.e/Bo,l=t.e/Bo,h=s.c,c=t.c;if(!u||!l){if(!h||!c)return h?(t.s=-e,t):new S(c?s:NaN);if(!h[0]||!c[0])return c[0]?(t.s=-e,t):new S(h[0]?s:3==v?-0:0)}if(u=Uo(u),l=Uo(l),h=h.slice(),a=u-l){for((o=a<0)?(a=-a,i=h):(l=u,i=c),i.reverse(),e=a;e--;i.push(0));i.reverse()}else for(r=(o=(a=h.length)<(e=c.length))?a:e,a=e=0;e0)for(;e--;h[n++]=0);for(e=Go-1;r>a;){if(h[--r]=0;){for(n=0,f=_[i]%d,g=_[i]/d|0,o=i+(s=u);o>i;)n=((l=f*(l=m[--s]%d)+(a=g*l+(h=m[s]/d|0)*f)%d*d+p[o]+n)/v|0)+(a/d|0)+g*h,p[o--]=l%v;p[o]=n}return n?++r:p.splice(0,1),P(t,p,r)},f.negated=function(){var t=new S(this);return t.s=-t.s||null,t},f.plus=function(t,e){var n,r=this,i=r.s;if(e=(t=new S(t,e)).s,!i||!e)return new S(NaN);if(i!=e)return t.s=-e,r.minus(t);var o=r.e/Bo,s=t.e/Bo,a=r.c,u=t.c;if(!o||!s){if(!a||!u)return new S(i/0);if(!a[0]||!u[0])return u[0]?t:new S(a[0]?r:0*i)}if(o=Uo(o),s=Uo(s),a=a.slice(),i=o-s){for(i>0?(s=o,n=u):(i=-i,n=a),n.reverse();i--;n.push(0));n.reverse()}for((i=a.length)-(e=u.length)<0&&(n=u,u=a,a=n,e=i),i=0;e;)i=(a[--e]=a[e]+u[e]+i)/Go|0,a[e]=Go===a[e]?0:a[e]%Go;return i&&(a=[i].concat(a),++s),P(t,a,s)},f.precision=f.sd=function(t,e){var n,r,i,o=this;if(null!=t&&t!==!!t)return Wo(t,1,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t,e);if(!(n=o.c))return null;if(r=(i=n.length-1)*Bo+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return t&&o.e+1>r&&(r=o.e+1),r},f.shiftedBy=function(t){return Wo(t,-9007199254740991,Yo),this.times("1e"+t)},f.squareRoot=f.sqrt=function(){var t,e,r,i,o,s=this,a=s.c,u=s.s,l=s.e,h=p+4,c=new S("0.5");if(1!==u||!a||!a[0])return new S(!u||u<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(u=Math.sqrt(+T(s)))||u==1/0?(((e=Zo(a)).length+l)%2==0&&(e+="0"),u=Math.sqrt(+e),l=Uo((l+1)/2)-(l<0||l%2),r=new S(e=u==1/0?"5e"+l:(e=u.toExponential()).slice(0,e.indexOf("e")+1)+l)):r=new S(u+""),r.c[0])for((u=(l=r.e)+h)<3&&(u=0);;)if(o=r,r=c.times(o.plus(n(s,o,h,1))),Zo(o.c).slice(0,u)===(e=Zo(r.c)).slice(0,u)){if(r.e0&&p>0){for(o=p%a||a,h=g.substr(0,o);o0&&(h+=l+g.slice(o)),f&&(h="-"+h)}r=c?h+(n.decimalSeparator||"")+((u=+n.fractionGroupSize)?c.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):c):h}return(n.prefix||"")+r+(n.suffix||"")},f.toFraction=function(t){var e,r,i,o,s,a,u,l,h,c,f,p,d=this,y=d.c;if(null!=t&&(!(u=new S(t)).isInteger()&&(u.c||1!==u.s)||u.lt(g)))throw Error(qo+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+T(u));if(!y)return new S(d);for(e=new S(g),h=r=new S(g),i=l=new S(g),p=Zo(y),s=e.e=p.length-d.e-1,e.c[0]=zo[(a=s%Bo)<0?Bo+a:a],t=!t||u.comparedTo(e)>0?s>0?e:h:u,a=x,x=1/0,u=new S(p),l.c[0]=0;c=n(u,e,0,1),1!=(o=r.plus(c.times(i))).comparedTo(t);)r=i,i=o,h=l.plus(c.times(o=h)),l=o,e=u.minus(c.times(o=e)),u=o;return o=n(t.minus(r),i,0,1),l=l.plus(o.times(h)),r=r.plus(o.times(i)),l.s=h.s=d.s,f=n(h,i,s*=2,v).minus(d).abs().comparedTo(n(l,r,s,v).minus(d).abs())<1?[h,i]:[l,r],x=a,f},f.toNumber=function(){return+T(this)},f.toPrecision=function(t,e){return null!=t&&Wo(t,1,Xo),M(this,t,e,2)},f.toString=function(t){var e,n=this,i=n.s,o=n.e;return null===o?i?(e="Infinity",i<0&&(e="-"+e)):e="NaN":(null==t?e=o<=d||o>=y?Ko(Zo(n.c),o):Qo(Zo(n.c),o,"0"):10===t&&N?e=Qo(Zo((n=C(new S(n),p+o+1,v)).c),n.e,"0"):(Wo(t,2,I.length,"Base"),e=r(Qo(Zo(n.c),o,"0"),10,t,i,!0)),i<0&&n.c[0]&&(e="-"+e)),e},f.valueOf=f.toJSON=function(){return T(this)},f._isBigNumber=!0,f[Symbol.toStringTag]="BigNumber",f[Symbol.for("nodejs.util.inspect.custom")]=f.valueOf,null!=e&&S.set(e),S}(),ts=function(t){function e(t){return i(this,e),r(this,e,[t])}return h(e,t),s(e)}(s((function t(e){i(this,t),u(this,"key",void 0),u(this,"left",null),u(this,"right",null),this.key=e}))),es=function(){return s((function t(){i(this,t),u(this,"size",0),u(this,"modificationCount",0),u(this,"splayCount",0)}),[{key:"splay",value:function(t){var e=this.root;if(null==e)return this.compare(t,t),-1;for(var n,r=null,i=null,o=null,s=null,a=e,u=this.compare;;)if((n=u(a.key,t))>0){var l=a.left;if(null==l)break;if((n=u(l.key,t))>0&&(a.left=l.right,l.right=a,null==(l=(a=l).left)))break;null==r?i=a:r.left=a,r=a,a=l}else{if(!(n<0))break;var h=a.right;if(null==h)break;if((n=u(h.key,t))<0&&(a.right=h.left,h.left=a,null==(h=(a=h).right)))break;null==o?s=a:o.right=a,o=a,a=h}return null!=o&&(o.right=a.left,a.left=s),null!=r&&(r.left=a.right,a.right=i),this.root!==a&&(this.root=a,this.splayCount++),n}},{key:"splayMin",value:function(t){for(var e=t,n=e.left;null!=n;){var r=n;e.left=r.right,r.right=e,n=(e=r).left}return e}},{key:"splayMax",value:function(t){for(var e=t,n=e.right;null!=n;){var r=n;e.right=r.left,r.left=e,n=(e=r).right}return e}},{key:"_delete",value:function(t){if(null==this.root)return null;if(0!=this.splay(t))return null;var e=this.root,n=e,r=e.left;if(this.size--,null==r)this.root=e.right;else{var i=e.right;(e=this.splayMax(r)).right=i,this.root=e}return this.modificationCount++,n}},{key:"addNewRoot",value:function(t,e){this.size++,this.modificationCount++;var n=this.root;null!=n?(e<0?(t.left=n,t.right=n.right,n.right=null):(t.right=n,t.left=n.left,n.left=null),this.root=t):this.root=t}},{key:"_first",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMin(t),this.root)}},{key:"_last",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMax(t),this.root)}},{key:"clear",value:function(){this.root=null,this.size=0,this.modificationCount++}},{key:"has",value:function(t){return this.validKey(t)&&0==this.splay(t)}},{key:"defaultCompare",value:function(){return function(t,e){return te?1:0}}},{key:"wrap",value:function(){var t=this;return{getRoot:function(){return t.root},setRoot:function(e){t.root=e},getSize:function(){return t.size},getModificationCount:function(){return t.modificationCount},getSplayCount:function(){return t.splayCount},setSplayCount:function(e){t.splayCount=e},splay:function(e){return t.splay(e)},has:function(e){return t.has(e)}}}}])}(),ns=function(t){function e(t,n){var o;return i(this,e),u(o=r(this,e),"root",null),u(o,"compare",void 0),u(o,"validKey",void 0),u(o,Symbol.toStringTag,"[object Set]"),o.compare=null!=t?t:o.defaultCompare(),o.validKey=null!=n?n:function(t){return null!=t&&null!=t},o}return h(e,t),s(e,[{key:"delete",value:function(t){return!!this.validKey(t)&&null!=this._delete(t)}},{key:"deleteAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.delete(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"forEach",value:function(t){for(var e,n=this[Symbol.iterator]();!(e=n.next()).done;)t(e.value,e.value,this)}},{key:"add",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this}},{key:"addAndReturn",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this.root.key}},{key:"addAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.add(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"isEmpty",value:function(){return null==this.root}},{key:"isNotEmpty",value:function(){return null!=this.root}},{key:"single",value:function(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}},{key:"first",value:function(){if(0==this.size)throw"Bad state: No element";return this._first().key}},{key:"last",value:function(){if(0==this.size)throw"Bad state: No element";return this._last().key}},{key:"lastBefore",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)<0)return this.root.key;var e=this.root.left;if(null==e)return null;for(var n=e.right;null!=n;)n=(e=n).right;return e.key}},{key:"firstAfter",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)>0)return this.root.key;var e=this.root.right;if(null==e)return null;for(var n=e.left;null!=n;)n=(e=n).left;return e.key}},{key:"retainAll",value:function(t){var n,r=new e(this.compare,this.validKey),i=this.modificationCount,o=a(t);try{for(o.s();!(n=o.n()).done;){var s=n.value;if(i!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(s)&&0==this.splay(s)&&r.add(this.root.key)}}catch(t){o.e(t)}finally{o.f()}r.size!=this.size&&(this.root=r.root,this.size=r.size,this.modificationCount++)}},{key:"lookup",value:function(t){return this.validKey(t)?0!=this.splay(t)?null:this.root.key:null}},{key:"intersection",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)&&r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"difference",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)||r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"union",value:function(t){var e=this.clone();return e.addAll(t),e}},{key:"clone",value:function(){var t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}},{key:"copyNode",value:function(t){if(null==t)return null;var e=new ts(t.key);return function t(e,n){var r,i;do{if(r=e.left,i=e.right,null!=r){var o=new ts(r.key);n.left=o,t(r,o)}if(null!=i){var s=new ts(i.key);n.right=s,e=i,n=s}}while(null!=i)}(t,e),e}},{key:"toSet",value:function(){return this.clone()}},{key:"entries",value:function(){return new os(this.wrap())}},{key:"keys",value:function(){return this[Symbol.iterator]()}},{key:"values",value:function(){return this[Symbol.iterator]()}},{key:Symbol.iterator,value:function(){return new is(this.wrap())}}])}(es),rs=function(){return s((function t(e){i(this,t),u(this,"tree",void 0),u(this,"path",new Array),u(this,"modificationCount",null),u(this,"splayCount",void 0),this.tree=e,this.splayCount=e.getSplayCount()}),[{key:Symbol.iterator,value:function(){return this}},{key:"next",value:function(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}},{key:"current",value:function(){if(!this.path.length)return null;var t=this.path[this.path.length-1];return this.getValue(t)}},{key:"rebuildPath",value:function(t){this.path.splice(0,this.path.length),this.tree.splay(t),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}},{key:"findLeftMostDescendent",value:function(t){for(;null!=t;)this.path.push(t),t=t.left}},{key:"moveNext",value:function(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();for(var t=this.tree.getRoot();null!=t;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);var e=this.path[this.path.length-1],n=e.right;if(null!=n){for(;null!=n;)this.path.push(n),n=n.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}}])}(),is=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return t.key}}])}(rs),os=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return[t.key,t.key]}}])}(rs),ss=function(t){return function(){return t}},as=function(t){var e=t?function(e,n){return n.minus(e).abs().isLessThanOrEqualTo(t)}:ss(!1);return function(t,n){return e(t,n)?0:t.comparedTo(n)}};function us(t){var e=t?function(e,n,r,i,o){return e.exponentiatedBy(2).isLessThanOrEqualTo(i.minus(n).exponentiatedBy(2).plus(o.minus(r).exponentiatedBy(2)).times(t))}:ss(!1);return function(t,n,r){var i=t.x,o=t.y,s=r.x,a=r.y,u=o.minus(a).times(n.x.minus(s)).minus(i.minus(s).times(n.y.minus(a)));return e(u,i,o,s,a)?0:u.comparedTo(0)}}var ls=function(t){return t},hs=function(t){if(t){var e=new ns(as(t)),n=new ns(as(t)),r=function(t,e){return e.addAndReturn(t)},i=function(t){return{x:r(t.x,e),y:r(t.y,n)}};return i({x:new $o(0),y:new $o(0)}),i}return ls},cs=function(t){return{set:function(t){fs=cs(t)},reset:function(){return cs(t)},compare:as(t),snap:hs(t),orient:us(t)}},fs=cs(),gs=function(t,e){return t.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(t.ur.x)&&t.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(t.ur.y)},ps=function(t,e){if(e.ur.x.isLessThan(t.ll.x)||t.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(t.ll.y)||t.ur.y.isLessThan(e.ll.y))return null;var n=t.ll.x.isLessThan(e.ll.x)?e.ll.x:t.ll.x,r=t.ur.x.isLessThan(e.ur.x)?t.ur.x:e.ur.x;return{ll:{x:n,y:t.ll.y.isLessThan(e.ll.y)?e.ll.y:t.ll.y},ur:{x:r,y:t.ur.y.isLessThan(e.ur.y)?t.ur.y:e.ur.y}}},vs=function(t,e){return t.x.times(e.y).minus(t.y.times(e.x))},ds=function(t,e){return t.x.times(e.x).plus(t.y.times(e.y))},ys=function(t){return ds(t,t).sqrt()},ms=function(t,e,n){var r={x:e.x.minus(t.x),y:e.y.minus(t.y)},i={x:n.x.minus(t.x),y:n.y.minus(t.y)};return ds(i,r).div(ys(i)).div(ys(r))},_s=function(t,e,n){return e.y.isZero()?null:{x:t.x.plus(e.x.div(e.y).times(n.minus(t.y))),y:n}},xs=function(t,e,n){return e.x.isZero()?null:{x:n,y:t.y.plus(e.y.div(e.x).times(n.minus(t.x)))}},Es=function(){function t(e,n){i(this,t),u(this,"point",void 0),u(this,"isLeft",void 0),u(this,"segment",void 0),u(this,"otherSE",void 0),u(this,"consumedBy",void 0),void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}return s(t,[{key:"link",value:function(t){if(t.point===this.point)throw new Error("Tried to link already linked events");for(var e=t.point.events,n=0,r=e.length;n0&&(t=r)}for(var i=t.segment.prevInResult(),o=i?i.prevInResult():null;;){if(!i)return null;if(!o)return i.ringOut;var s,a;if(o.ringOut!==i.ringOut)return(null===(s=o.ringOut)||void 0===s?void 0:s.enclosingRing())!==i.ringOut?i.ringOut:null===(a=i.ringOut)||void 0===a?void 0:a.enclosingRing();i=o.prevInResult(),o=i?i.prevInResult():null}}}],[{key:"factory",value:function(e){for(var n=[],r=0,i=e.length;r1&&void 0!==arguments[1]?arguments[1]:Ls.compare;i(this,t),u(this,"queue",void 0),u(this,"tree",void 0),u(this,"segments",void 0),this.queue=e,this.tree=new ns(n),this.segments=[]}),[{key:"process",value:function(t){var e=t.segment,n=[];if(t.consumedBy)return t.isLeft?this.queue.delete(t.otherSE):this.tree.delete(e),n;t.isLeft&&this.tree.add(e);var r=e,i=e;do{r=this.tree.lastBefore(r)}while(null!=r&&null!=r.consumedBy);do{i=this.tree.firstAfter(i)}while(null!=i&&null!=i.consumedBy);if(t.isLeft){var o=null;if(r){var s=r.getIntersection(e);if(null!==s&&(e.isAnEndpoint(s)||(o=s),!r.isAnEndpoint(s)))for(var a=this._splitSafely(r,s),u=0,l=a.length;u0?(this.tree.delete(e),n.push(t)):(this.segments.push(e),e.prev=r)}else{if(r&&i){var _=r.getIntersection(i);if(null!==_){if(!r.isAnEndpoint(_))for(var x=this._splitSafely(r,_),E=0,k=x.length;E0&&a.swapEvents(),Es.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}},{key:"swapEvents",value:function(){var t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(var e=0,n=this.windings.length;e0){var o=n;n=r,r=o}if(n.prev===r){var s=n;n=r,r=s}for(var a=0,u=r.rings.length;a0)return-1;var c=e.comparePoint(t.rightSE.point);return 0!==c?c:-1}if(n.isGreaterThan(r)){if(s.isLessThan(a)&&s.isLessThan(l))return-1;if(s.isGreaterThan(a)&&s.isGreaterThan(l))return 1;var f=e.comparePoint(t.leftSE.point);if(0!==f)return f;var g=t.comparePoint(e.rightSE.point);return g<0?1:g>0?-1:1}if(s.isLessThan(a))return-1;if(s.isGreaterThan(a))return 1;if(i.isLessThan(o)){var p=e.comparePoint(t.rightSE.point);if(0!==p)return p}if(i.isGreaterThan(o)){var v=t.comparePoint(e.rightSE.point);if(v<0)return 1;if(v>0)return-1}if(!i.eq(o)){var d=u.minus(s),y=i.minus(n),m=l.minus(a),_=o.minus(r);if(d.isGreaterThan(y)&&m.isLessThan(_))return 1;if(d.isLessThan(y)&&m.isGreaterThan(_))return-1}return i.isGreaterThan(o)?1:i.isLessThan(o)||u.isLessThan(l)?-1:u.isGreaterThan(l)?1:t.ide.id?1:0}},{key:"fromRing",value:function(e,n,r){var i,o,s,a=Es.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else{if(!(a>0))throw new Error("Tried to create degenerate segment at [".concat(e.x,", ").concat(e.y,"]"));i=n,o=e,s=-1}return new t(new Es(i,!0),new Es(o,!1),[r],[s])}}])}(),Ps=function(){return s((function t(e,n,r){if(i(this,t),u(this,"poly",void 0),u(this,"isExterior",void 0),u(this,"segments",void 0),u(this,"bbox",void 0),!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");var o=fs.snap({x:new $o(e[0][0]),y:new $o(e[0][1])});this.bbox={ll:{x:o.x,y:o.y},ur:{x:o.x,y:o.y}};for(var s=o,a=1,l=e.length;a1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r2&&void 0!==arguments[2]?arguments[2]:2,r=K(t),i=K(e),o=r[0]-i[0],s=r[1]-i[1];return 1===n?Math.abs(o)+Math.abs(s):Math.pow(Math.pow(o,n)+Math.pow(s,n),1/n)}function Gs(t,e){var n,r,i=(e=e||{}).threshold||1e4,o=e.p||2,s=null!=(n=e.binary)&&n,a=e.alpha||-1,u=null!=(r=e.standardization)&&r,l=[];vt(t,(function(t){l.push(gi(t))}));for(var h=[],c=0;c3&&void 0!==arguments[3]?arguments[3]:{},i=e<0,o=j(Math.abs(e),r.units,"meters");i&&(o=-Math.abs(o));var s=K(t),a=function(t,e,n,r){r=void 0===r?x:Number(r);var i=e/r,o=t[0]*Math.PI/180,s=z(t[1]),a=z(n),u=i*Math.cos(a),l=s+u;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);var h=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),c=Math.abs(h)>1e-11?u/h:Math.cos(s),f=i*Math.sin(a)/c;return[(180*(o+f)/Math.PI+540)%360-180,180*l/Math.PI]}(s,o,n);return a[0]+=a[0]-s[0]>180?-360:s[0]-a[0]>180?360:0,I(a,r.properties)}function Ys(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e);i[0]+=i[0]-r[0]>180?-360:r[0]-i[0]>180?360:0;var o=function(t,e,n){var r=n=void 0===n?x:Number(n),i=t[1]*Math.PI/180,o=e[1]*Math.PI/180,s=o-i,a=Math.abs(e[0]-t[0])*Math.PI/180;a>Math.PI&&(a-=2*Math.PI);var u=Math.log(Math.tan(o/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),l=Math.abs(u)>1e-11?s/u:Math.cos(i);return Math.sqrt(s*s+l*l*a*a)*r}(r,i);return j(o,"meters",n.units)}function zs(t,e,n){if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.pivot,i=n.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("angle is required");if(0===e)return t;var o=null!=r?r:gi(t);return!1!==i&&void 0!==i||(t=Ai(t)),ct(t,(function(t){var n=lt(o,t)+e,r=Ys(o,t),i=Q(Bs(o,r,n));t[0]=i[0],t[1]=i[1]})),t}function js(t,e,n,r){var i=(r=r||{}).steps||64,o=r.units||"kilometers",s=r.angle||0,a=r.pivot||t,u=r.properties||{};if(!t)throw new Error("center is required");if(!e)throw new Error("xSemiAxis is required");if(!n)throw new Error("ySemiAxis is required");if(!Z(r))throw new Error("options must be an object");if(!U(i))throw new Error("steps must be a number");if(!U(s))throw new Error("angle must be a number");var l=K(t);if("degrees"!==o){var h=Bs(t,e,90,{units:o}),c=Bs(t,n,0,{units:o});e=K(h)[0]-l[0],n=K(c)[1]-l[1]}for(var f=[],g=0;g=-270&&(v=-v),p<-180&&p>=-360&&(d=-d),"degrees"===o){var y=z(s),m=v*Math.cos(y)+d*Math.sin(y),_=d*Math.cos(y)-v*Math.sin(y);v=m,d=_}f.push([v+l[0],d+l[1]])}return f.push(f[0]),"degrees"===o?S([f],u):zs(S([f],u),s,{pivot:a})}function Xs(t){var e=t*Math.PI/180;return Math.tan(e)}function Us(t){return Vt(Rt(t))}function Zs(t){var e=[];return"FeatureCollection"===t.type?vt(t,(function(t){ct(t,(function(n){e.push(I(n,t.properties))}))})):"Feature"===t.type?ct(t,(function(n){e.push(I(n,t.properties))})):ct(t,(function(t){e.push(I(t))})),C(e)}var Hs=Math.PI/180,Ws=180/Math.PI,Js=function(t,e){this.lon=t,this.lat=e,this.x=Hs*t,this.y=Hs*e};Js.prototype.view=function(){return String(this.lon).slice(0,4)+","+String(this.lat).slice(0,4)},Js.prototype.antipode=function(){var t=-1*this.lat,e=this.lon<0?180+this.lon:-1*(180-this.lon);return new Js(e,t)};var Ks=function(){this.coords=[],this.length=0};Ks.prototype.move_to=function(t){this.length++,this.coords.push(t)};var Qs=function(t){this.properties=t||{},this.geometries=[]};Qs.prototype.json=function(){if(this.geometries.length<=0)return{geometry:{type:"LineString",coordinates:null},type:"Feature",properties:this.properties};if(1===this.geometries.length)return{geometry:{type:"LineString",coordinates:this.geometries[0].coords},type:"Feature",properties:this.properties};for(var t=[],e=0;e1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must specify at least 2 geometries");var r=Rs.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)}function ea(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.stringify(n.properties||{}),i=v(t,4),o=i[0],s=i[1],a=i[2],u=i[3],l=(s+u)/2,h=(o+a)/2,c=2*e/ut([o,l],[a,l],n)*(a-o),f=2*e/ut([h,s],[h,u],n)*(u-s),g=c/2,p=2*g,d=Math.sqrt(3)/2*f,y=a-o,m=u-s,_=3/4*p,x=d,E=(y-p)/(p-g/2),k=Math.floor(E),b=(k*_-g/2-y)/2-g/2+_/2,w=Math.floor((m-d)/d),I=(m-w*d)/2,N=w*d-m>d/2;N&&(I-=d/4);for(var S=[],M=[],L=0;L<6;L++){var P=2*Math.PI/6*L;S.push(Math.cos(P)),M.push(Math.sin(P))}for(var T=[],O=0;O<=k;O++)for(var R=0;R<=w;R++){var A=O%2==1;if((0!==R||!A)&&(0!==R||!N)){var D=O*_+o-b,F=R*x+s+I;if(A&&(F-=d/2),!0===n.triangles)ra([D,F],c/2,f/2,JSON.parse(r),S,M).forEach((function(t){n.mask?ta(C([n.mask,t]))&&T.push(t):T.push(t)}));else{var q=na([D,F],c/2,f/2,JSON.parse(r),S,M);n.mask?ta(C([n.mask,q]))&&T.push(q):T.push(q)}}}return C(T)}function na(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=t[0]+e*i[a],l=t[1]+n*o[a];s.push([u,l])}return s.push(s[0].slice()),S([s],r)}function ra(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=[];u.push(t),u.push([t[0]+e*i[a],t[1]+n*o[a]]),u.push([t[0]+e*i[(a+1)%6],t[1]+n*o[(a+1)%6]]),u.push(t),s.push(S([u],r))}return s}function ia(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.mask&&!n.units&&(n.units="kilometers");for(var r=[],i=t[0],o=t[1],s=t[2],a=t[3],u=e/ut([i,o],[s,o],n)*(s-i),l=e/ut([i,o],[i,a],n)*(a-o),h=s-i,c=a-o,f=Math.floor(h/u),g=(c-Math.floor(c/l)*l)/2,p=i+(h-f*u)/2;p<=s;){for(var v=o+g;v<=a;){var d=I([p,v],n.properties);n.mask?Cn(d,n.mask)&&r.push(d):r.push(d),v+=l}p+=u}return C(r)}function oa(t,e,n){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=[],o=t[0],s=t[1],a=t[2],u=t[3],l=a-o,h=j(e,r.units,"degrees"),c=u-s,f=j(n,r.units,"degrees"),g=Math.floor(Math.abs(l)/h),p=Math.floor(Math.abs(c)/f),v=(c-p*f)/2,d=o+(l-g*h)/2,y=0;y2&&void 0!==arguments[2]?arguments[2]:{})}function aa(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=[],i=e/ut([t[0],t[1]],[t[2],t[1]],n)*(t[2]-t[0]),o=e/ut([t[0],t[1]],[t[0],t[3]],n)*(t[3]-t[1]),s=0,a=t[0];a<=t[2];){for(var u=0,l=t[1];l<=t[3];){var h=null,c=null;s%2==0&&u%2==0?(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)):s%2==0&&u%2==1?(h=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties)):u%2==0&&s%2==1?(h=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties),c=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties)):u%2==1&&s%2==1&&(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)),n.mask?(ta(C([n.mask,h]))&&r.push(h),ta(C([n.mask,c]))&&r.push(c)):(r.push(h),r.push(c)),l+=o,u++}s++,a+=i}return C(r)} +/*! + * MarchingSquaresJS + * version 1.3.3 + * https://github.com/RaumZeit/MarchingSquares.js + * + * @license GNU Affero General Public License. + * Copyright (c) 2015-2019 Ronny Lorenz + */ +function ua(t,e,n){return tr&&(i=n,n=r,r=i),tr?(t-r)/(t-e):(t-n)/(t-e)}function ha(t,e,n,r){return t1){for(;0!==o;)o>>=1,a++;r===1<1){for(;0!==s;)s>>=1,u++;i===1<0&&(this.childB=new da(t,e+o,n,r-o,s),this.lowerBound=Math.min(this.lowerBound,this.childB.lowerBound),this.upperBound=Math.max(this.upperBound,this.childB.upperBound),i-s>0&&(this.childC=new da(t,e+o,n+s,r-o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childC.lowerBound),this.upperBound=Math.max(this.upperBound,this.childC.upperBound))),i-s>0&&(this.childD=new da(t,e,n+s,o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childD.lowerBound),this.upperBound=Math.max(this.upperBound,this.childD.upperBound))}}function ya(t){var e,n;if(!t)throw new Error("data is required");if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Error("data must be scalar field, i.e. array of arrays");if(t.length<2)throw new Error("data must contain at least two rows");if((n=t[0].length)<2)throw new Error("data must contain at least two columns");for(e=1;e=e||t[s][r-1]>=e){n=!1;break}if(n&&(t[i-1][0]>=e||t[i-1][r-1]>=e)&&(n=!1),n)for(o=0;o=e||t[i-1][o]>e){n=!1;break}return n}(t,n.threshold)&&(n.linearRing?_.push([[0,0],[0,x],[E,x],[E,0],[0,0]]):_.push([[0,0],[0,x],[E,x],[E,0]])),e.forEach((function(t,N){t.forEach((function(t,S){for(r=null,i=0;i<4;i++)if(r=k[i],"object"===m(t.edges[r])){for(a=[],o=t.edges[r],u=r,l=N,h=S,c=!1,f=[N+o.path[0][0],S+o.path[0][1]],a.push(f);!c&&"object"===m((s=e[l][h]).edges[u]);)if(o=s.edges[u],delete s.edges[u],(g=o.path[1])[0]+=l,g[1]+=h,a.push(g),u=o.move.enter,l+=o.move.x,h+=o.move.y,void 0===e[l]||void 0===e[l][h]){if(!n.linearRing)break;if(p=0,v=0,l===E?(l--,p=0):l<0?(l++,p=2):h===x?(h--,p=3):h<0&&(h++,p=1),l===N&&h===S&&p===I[r]){c=!0,u=r;break}for(;;){if(d=!1,v>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[l]&&void 0!==e[l][h]&&(s=e[l][h],y=k[p],"object"===m(s.edges[y]))){o=s.edges[y],a.push(pa(l,h,p,o.path)),u=y,d=!0;break}if(d)break;if(a.push(va(l,h,p)),h+=w[p],void 0!==e[l+=b[p]]&&void 0!==e[l][h]||(0===p&&h<0||1===p&&l<0||2===p&&h===x||3===p&&l===E)&&(l-=b[p],h-=w[p],p=(p+1)%4,v++),l===N&&h===S&&p===I[r]){c=!0,u=r;break}}}!n.linearRing||a[a.length-1][0]===f[0]&&a[a.length-1][1]===f[1]||a.push(f),_.push(a)}}))})),_}(h,c,r)}a?g.push(f):g=f,"function"==typeof r.successCallback&&r.successCallback(g,t)})),g}function _a(t,e,n,r){var i,o,s,a,u,l,h=0,c=t[n+1][e],f=t[n+1][e+1],g=t[n][e+1],p=t[n][e],v=r.threshold;if(!(isNaN(p)||isNaN(g)||isNaN(f)||isNaN(c))){switch(h|=c>=v?8:0,h|=f>=v?4:0,h|=g>=v?2:0,l={cval:h=+(h|=p>=v?1:0),polygons:[],edges:{},x0:p,x1:g,x2:f,x3:c},h){case 0:r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,0]]);break;case 15:break;case 14:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.left={path:[[0,i],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[a,0]]);break;case 13:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[a,0],[1,o],[1,0]]);break;case 11:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[1,o],[s,1],[1,1]]);break;case 7:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[s,1],[0,i],[0,1]]);break;case 1:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[a,0],[0,i],[0,1],[1,1],[1,0]]);break;case 2:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,o],[a,0]]);break;case 4:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[1,o],[1,0]]);break;case 8:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[s,1],[1,1],[1,0]]);break;case 12:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[1,o],[1,0]]);break;case 9:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[a,0],[s,1],[1,1],[1,0]]);break;case 3:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[0,i],[0,1],[1,1],[1,o]]);break;case 6:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[a,0]]);break;case 10:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),u=(p+g+f+c)/4,r.polygons_full&&(uf&&(v>h&&ph&&vu&&(u=d)}var y=[];if(a&&u0&&Math.abs(x-n[_-1][0])>f){var E=parseFloat(n[_-1][0]),k=parseFloat(n[_-1][1]),b=parseFloat(n[_][0]),w=parseFloat(n[_][1]);if(E>-180&&E-180&&n[_-1][0]h&&E<180&&-180===b&&_+1h&&n[_-1][0]<180){m.push([180,n[_][1]]),_++,m.push([n[_][0],n[_][1]]);continue}if(Eh){var I=E;E=b,b=I;var N=k;k=w,w=N}if(E>h&&b=180&&Eh?180:-180,M]),(m=[]).push([n[_-1][0]>h?-180:180,M]),y.push(m)}else m=[],y.push(m);m.push([x,n[_][1]])}else m.push([n[_][0],n[_][1]])}}else{var L=[];y.push(L);for(var P=0;Pe||this.upperBound=e)&&r.push({x:this.x,y:this.y})),r},da.prototype.cellsBelowThreshold=function(t,e){var n=[];return e=void 0===e||e,this.lowerBound>t||(this.childA||this.childB||this.childC||this.childD?(this.childA&&(n=n.concat(this.childA.cellsBelowThreshold(t,e))),this.childB&&(n=n.concat(this.childB.cellsBelowThreshold(t,e))),this.childD&&(n=n.concat(this.childD.cellsBelowThreshold(t,e))),this.childC&&(n=n.concat(this.childC.cellsBelowThreshold(t,e)))):(e||this.upperBound>=t)&&n.push({x:this.x,y:this.y})),n};var xa={square:function(t,e,n,r,i,o){o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,0]])},triangle_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,a],[s,0],[0,0]])},triangle_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[1,a],[1,0]])},triangle_tr:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[1,s],[a,1],[1,1]])},triangle_tl:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[s,1]])},tetragon_t:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[1,1],[1,s]])},tetragon_r:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[a,1],[1,1],[1,0]])},tetragon_b:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,0]])},tetragon_l:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[a,0]])},tetragon_bl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[a,0]])},tetragon_br:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate_b(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[1,l]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[1,l],[1,u],[a,0]])},tetragon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rb={path:[[1,l],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}}),o.polygons&&t.polygons.push([[1,l],[s,1],[a,1],[1,u]])},tetragon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[0,l]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[a,1],[0,l],[0,u],[s,1]])},tetragon_lr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[1,u],[1,l]])},tetragon_tb:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[l,0],[s,1],[a,1],[u,0]])},pentagon_tr:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[1,a],[1,0]])},pentagon_tl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,0]])},pentagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,a],[s,0]])},pentagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[a,0],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[1,1],[1,0],[a,0]])},pentagon_tr_rl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[1,u],[1,l]])},pentagon_rb_bt:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,n,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[u,0],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[l,1],[1,1],[1,s],[a,0],[u,0]])},pentagon_bl_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[1,l],[1,0]])},pentagon_lt_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[l,0]])},pentagon_bl_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[l,0],[0,s]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[u,0],[l,0]])},pentagon_lt_rl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[u,1],[1,1],[1,l]])},pentagon_tr_bt:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,1],[a,1],[1,u],[1,0],[l,0]])},pentagon_rb_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_b(n,r,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,u],[l,0]])},hexagon_lt_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[1,l],[1,0]])},hexagon_bl_lt:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[1,1],[1,0]])},hexagon_bl_rb:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.rt={path:[[1,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[1,1],[1,l],[a,0]])},hexagon_tr_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[a,1],[1,u],[1,l],[s,0]])},hexagon_lt_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,u],[l,0]])},hexagon_bl_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,1],[u,1],[1,l],[1,0]])},heptagon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[1,1],[1,c],[a,0]])},heptagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate_a(i,r,o.minV,o.maxV),l=o.interpolate_b(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,a],[u,1],[l,1],[1,h],[1,c],[s,0]])},heptagon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[l,1],[1,h],[1,c],[a,0]])},heptagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(i,r,o.minV,o.maxV),h=o.interpolate_b(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[h,1],[1,c]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[h,1],[1,c],[1,0]])},octagon:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate_a(i,r,o.minV,o.maxV),c=o.interpolate_b(i,r,o.minV,o.maxV),f=o.interpolate_b(n,r,o.minV,o.maxV),g=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[c,1],[1,f]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,g],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[c,1],[1,f],[1,g],[a,0]])}};function Ea(t,e,n,r){var i,o,s,a=!1,u=null,l=null,h=null,c=null,f=!1,g=[],p=[],v=[];if(!t)throw new Error("data is required");if(null==e)throw new Error("lowerBound is required");if(null==n)throw new Error("bandWidth is required");if(s=function(t){var e,n,r,i,o;for(i=new fa,t=t||{},o=Object.keys(i),e=0;en||t[a][i-1]n){r=!1;break}if(r&&(t[o-1][0]n||t[o-1][i-1]n)&&(r=!1),r)for(s=0;sn||t[o-1][s]n){r=!1;break}return r}(t,n.minV,n.maxV)&&(n.linearRing?x.push([[0,0],[0,E],[k,E],[k,0],[0,0]]):x.push([[0,0],[0,E],[k,E],[k,0]])),e.forEach((function(t,M){t.forEach((function(t,L){for(r=null,o=0;o<8;o++)if(r=N[o],"object"===m(t.edges[r])){for(i=[],s=t.edges[r],l=r,h=M,c=L,f=!1,g=[M+s.path[0][0],L+s.path[0][1]],i.push(g);!f&&"object"===m((p=e[h][c]).edges[l]);)if(s=p.edges[l],delete p.edges[l],(y=s.path[1])[0]+=h,y[1]+=c,i.push(y),l=s.move.enter,h+=s.move.x,c+=s.move.y,void 0===e[h]||void 0===e[h][c]){if(v=0,d=0,h===k)h--,v=0;else if(h<0)h++,v=2;else if(c===E)c--,v=3;else{if(!(c<0))throw new Error("Left the grid somewhere in the interior!");c++,v=1}if(h===M&&c===L&&v===S[r]){f=!0,l=r;break}for(;;){if(_=!1,d>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[h]&&void 0!==e[h][c])for(p=e[h][c],a=0;ao?2:sf?128:64,s|=uf?32:16,s|=lf?8:4,o=0,i={cval:s=+(s|=hf?2:1),polygons:[],edges:{},x0:h,x1:l,x2:u,x3:a,x:e,y:n},s){case 85:xa.square(i,h,l,u,a,r);case 0:case 170:break;case 169:xa.triangle_bl(i,h,l,u,a,r);break;case 166:xa.triangle_br(i,h,l,u,a,r);break;case 154:xa.triangle_tr(i,h,l,u,a,r);break;case 106:xa.triangle_tl(i,h,l,u,a,r);break;case 1:xa.triangle_bl(i,h,l,u,a,r);break;case 4:xa.triangle_br(i,h,l,u,a,r);break;case 16:xa.triangle_tr(i,h,l,u,a,r);break;case 64:xa.triangle_tl(i,h,l,u,a,r);break;case 168:xa.tetragon_bl(i,h,l,u,a,r);break;case 162:xa.tetragon_br(i,h,l,u,a,r);break;case 138:xa.tetragon_tr(i,h,l,u,a,r);break;case 42:xa.tetragon_tl(i,h,l,u,a,r);break;case 2:xa.tetragon_bl(i,h,l,u,a,r);break;case 8:xa.tetragon_br(i,h,l,u,a,r);break;case 32:xa.tetragon_tr(i,h,l,u,a,r);break;case 128:xa.tetragon_tl(i,h,l,u,a,r);break;case 5:xa.tetragon_b(i,h,l,u,a,r);break;case 20:xa.tetragon_r(i,h,l,u,a,r);break;case 80:xa.tetragon_t(i,h,l,u,a,r);break;case 65:xa.tetragon_l(i,h,l,u,a,r);break;case 165:xa.tetragon_b(i,h,l,u,a,r);break;case 150:xa.tetragon_r(i,h,l,u,a,r);break;case 90:xa.tetragon_t(i,h,l,u,a,r);break;case 105:xa.tetragon_l(i,h,l,u,a,r);break;case 160:xa.tetragon_lr(i,h,l,u,a,r);break;case 130:xa.tetragon_tb(i,h,l,u,a,r);break;case 10:xa.tetragon_lr(i,h,l,u,a,r);break;case 40:xa.tetragon_tb(i,h,l,u,a,r);break;case 101:xa.pentagon_tr(i,h,l,u,a,r);break;case 149:xa.pentagon_tl(i,h,l,u,a,r);break;case 86:xa.pentagon_bl(i,h,l,u,a,r);break;case 89:xa.pentagon_br(i,h,l,u,a,r);break;case 69:xa.pentagon_tr(i,h,l,u,a,r);break;case 21:xa.pentagon_tl(i,h,l,u,a,r);break;case 84:xa.pentagon_bl(i,h,l,u,a,r);break;case 81:xa.pentagon_br(i,h,l,u,a,r);break;case 96:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 24:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 6:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 129:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 74:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 146:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 164:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 41:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 66:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 144:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 36:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 9:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 104:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 26:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 134:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 161:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 37:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 148:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 82:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 73:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 133:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 22:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 88:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 97:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 145:case 25:xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 70:case 100:xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 17:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 68:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 153:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 102:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 152:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 137:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 98:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 38:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 18:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 33:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 72:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 132:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 136:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r));break;case 34:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r))}return i}}var wa=Object.defineProperty,Ia=Object.getOwnPropertySymbols,Na=Object.prototype.hasOwnProperty,Sa=Object.prototype.propertyIsEnumerable,Ma=function(t,e,n){return e in t?wa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},La=function(t,e){for(var n in e||(e={}))Na.call(e,n)&&Ma(t,n,e[n]);if(Ia){var r,i=a(Ia(e));try{for(i.s();!(r=i.n()).done;){n=r.value;Sa.call(e,n)&&Ma(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t};function Pa(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.zProperty||"elevation",r=e.flip,i=e.flags;nt(t,"Point","input must contain Points");for(var o=function(t,e){var n={};vt(t,(function(t){var e=Q(t)[1];n[e]||(n[e]=[]),n[e].push(t)}));var r=Object.keys(n).map((function(t){return n[t].sort((function(t,e){return Q(t)[0]-Q(e)[0]}))})),i=r.sort((function(t,n){return e?Q(t[0])[1]-Q(n[0])[1]:Q(n[0])[1]-Q(t[0])[1]}));return i}(t,r),s=[],a=0;a=0&&l<=1&&(f.onLine1=!0),h>=0&&h<=1&&(f.onLine2=!0),!(!f.onLine1||!f.onLine2)&&[f.x,f.y])}function za(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return bt(t,(function(t,n){var r=n.geometry.coordinates;return t+ut(r[0],r[1],e)}),0)}function ja(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=i.steps||64,s=Xa(n),a=Xa(r),u=Array.isArray(t)||"Feature"!==t.type?{}:t.properties;if(s===a)return L(Ri(t,e,i).geometry.coordinates[0],u);for(var l=s,h=s=h&&c===i.length-1);c++){if(h>e&&0===o.length){if(!(s=e-h))return o.push(i[c]),L(o);a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates)}if(h>=n)return(s=n-h)?(a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates),L(o)):(o.push(i[c]),L(o));if(h>=e&&o.push(i[c]),c===i.length-1)return L(o);h+=ut(i[c],i[c+1],r)}if(h0){var a=r[e-1],u=Wa(n,a);!1!==u&&(a[1]=u,n[0]=u),s.push(a[0]),e===o.length-2&&(s.push(n[0]),s.push(n[1]))}2===o.length&&(s.push(n[0]),s.push(n[1]))}var l,h,c,f,g,p,v,d})),L(s,t.properties)}function Ka(t){var e=t[0],n=t[1],r=t[2],i=t[3];if(ut(t.slice(0,2),[r,n])>=ut(t.slice(0,2),[e,i])){var o=(n+i)/2;return[e,o-(r-e)/2,r,o+(r-e)/2]}var s=(e+r)/2;return[s-(i-n)/2,n,s+(i-n)/2,i]}function Qa(t,e){if(!Z(e=null!=e?e:{}))throw new Error("options is invalid");var n=e.precision,r=e.coordinates,i=e.mutate;if(n=null==n||isNaN(n)?6:n,r=null==r||isNaN(r)?3:r,!t)throw new Error(" is required");if("number"!=typeof n)throw new Error(" must be a number");if("number"!=typeof r)throw new Error(" must be a number");!1!==i&&void 0!==i||(t=JSON.parse(JSON.stringify(t)));var o=Math.pow(10,n);return ct(t,(function(t){!function(t,e,n){t.length>n&&t.splice(n,t.length);for(var r=0;r1&&n.push(L(l)),C(n)}function eu(t,e){if(!e.features.length)throw new Error("lines must contain features");if(1===e.features.length)return e.features[0];var n,r=1/0;return vt(e,(function(e){var i=fn(e,t).properties.dist;iu?(a.unshift(t),u=e):a.push(t)}else a.push(t)})),S(a,e);default:throw new Error("geometry type "+s+" is not supported")}}function iu(t){var e=t[0],n=e[0],r=e[1],i=t[t.length-1],o=i[0],s=i[1];return n===o&&r===s||t.push(e),t}function ou(t){return R(t)}function su(t){var e=[[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]];return t&&(e="Feature"===t.type?t.geometry.coordinates:t.coordinates),S(e)}function au(t){var e,n=0,r=a(t);try{for(r.s();!(e=r.n()).done;){n+=e.value}}catch(t){r.e(t)}finally{r.f()}return n/t.length}var uu=Object.defineProperty,lu=Object.defineProperties,hu=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,fu=Object.prototype.hasOwnProperty,gu=Object.prototype.propertyIsEnumerable,pu=function(t,e,n){return e in t?uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},vu=function(t,e){for(var n in e||(e={}))fu.call(e,n)&&pu(t,n,e[n]);if(cu){var r,i=a(cu(e));try{for(i.s();!(r=i.n()).done;){n=r.value;gu.call(e,n)&&pu(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},du=function(t,e){return lu(t,hu(e))};function yu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("targetPoint is required");if(!e)throw new Error("points is required");var r=1/0,i=0;vt(e,(function(e,o){var s=ut(t,e,n);s2&&void 0!==arguments[2]?arguments[2]:{},o=null!=(n=i.method)?n:"geodesic",s=null!=(r=i.units)?r:"kilometers";if(!t)throw new Error("pt is required");if(Array.isArray(t)?t=I(t):"Point"===t.type?t=b(t):et(t,"Point","point"),!e)throw new Error("line is required");Array.isArray(e)?e=L(e):"LineString"===e.type?e=b(e):et(e,"LineString","line");var a=1/0,u=t.geometry.coordinates;return kt(e,(function(t){if(t){var e=t.geometry.coordinates[0],n=t.geometry.coordinates[1],r=function(t,e,n,r){if("geodesic"===r.method){return fn(L([e,n]).geometry,t,{units:"degrees"}).properties.dist}var i=[n[0]-e[0],n[1]-e[1]],o=[t[0]-e[0],t[1]-e[1]],s=_u(o,i);if(s<=0)return Ys(t,e,{units:"degrees"});var a=_u(i,i);if(a<=s)return Ys(t,n,{units:"degrees"});var u=s/a,l=[e[0]+u*i[0],e[1]+u*i[1]];return Ys(t,l,{units:"degrees"})}(u,e,n,{method:o});r0)-(t<0)||+t}(r*(n[1]-e[1])-o*i)}function Lu(t,e){return e.geometry.coordinates[0].every((function(e){return zt(I(e),t)}))}var Pu=function(){return s((function t(e){i(this,t),this.id=t.buildId(e),this.coordinates=e,this.innerEdges=[],this.outerEdges=[],this.outerEdgesSorted=!1}),[{key:"removeInnerEdge",value:function(t){this.innerEdges=this.innerEdges.filter((function(e){return e.from.id!==t.from.id}))}},{key:"removeOuterEdge",value:function(t){this.outerEdges=this.outerEdges.filter((function(e){return e.to.id!==t.to.id}))}},{key:"addOuterEdge",value:function(t){this.outerEdges.push(t),this.outerEdgesSorted=!1}},{key:"sortOuterEdges",value:function(){var t=this;this.outerEdgesSorted||(this.outerEdges.sort((function(e,n){var r=e.to,i=n.to;if(r.coordinates[0]-t.coordinates[0]>=0&&i.coordinates[0]-t.coordinates[0]<0)return 1;if(r.coordinates[0]-t.coordinates[0]<0&&i.coordinates[0]-t.coordinates[0]>=0)return-1;if(r.coordinates[0]-t.coordinates[0]==0&&i.coordinates[0]-t.coordinates[0]==0)return r.coordinates[1]-t.coordinates[1]>=0||i.coordinates[1]-t.coordinates[1]>=0?r.coordinates[1]-i.coordinates[1]:i.coordinates[1]-r.coordinates[1];var o=Mu(t.coordinates,r.coordinates,i.coordinates);return o<0?1:o>0?-1:Math.pow(r.coordinates[0]-t.coordinates[0],2)+Math.pow(r.coordinates[1]-t.coordinates[1],2)-(Math.pow(i.coordinates[0]-t.coordinates[0],2)+Math.pow(i.coordinates[1]-t.coordinates[1],2))})),this.outerEdgesSorted=!0)}},{key:"getOuterEdges",value:function(){return this.sortOuterEdges(),this.outerEdges}},{key:"getOuterEdge",value:function(t){return this.sortOuterEdges(),this.outerEdges[t]}},{key:"addInnerEdge",value:function(t){this.innerEdges.push(t)}}],[{key:"buildId",value:function(t){return t.join(",")}}])}(),Cu=function(){function t(e,n){i(this,t),this.from=e,this.to=n,this.next=void 0,this.label=void 0,this.symetric=void 0,this.ring=void 0,this.from.addOuterEdge(this),this.to.addInnerEdge(this)}return s(t,[{key:"getSymetric",value:function(){return this.symetric||(this.symetric=new t(this.to,this.from),this.symetric.symetric=this),this.symetric}},{key:"deleteEdge",value:function(){this.from.removeOuterEdge(this),this.to.removeInnerEdge(this)}},{key:"isEqual",value:function(t){return this.from.id===t.from.id&&this.to.id===t.to.id}},{key:"toString",value:function(){return"Edge { ".concat(this.from.id," -> ").concat(this.to.id," }")}},{key:"toLineString",value:function(){return L([this.from.coordinates,this.to.coordinates])}},{key:"compareTo",value:function(t){return Mu(t.from.coordinates,t.to.coordinates,this.to.coordinates)}}])}(),Tu=function(){return s((function t(){i(this,t),this.edges=[],this.polygon=void 0,this.envelope=void 0}),[{key:"push",value:function(t){this.edges.push(t),this.polygon=this.envelope=void 0}},{key:"get",value:function(t){return this.edges[t]}},{key:"length",get:function(){return this.edges.length}},{key:"forEach",value:function(t){this.edges.forEach(t)}},{key:"map",value:function(t){return this.edges.map(t)}},{key:"some",value:function(t){return this.edges.some(t)}},{key:"isValid",value:function(){return!0}},{key:"isHole",value:function(){var t=this,e=this.edges.reduce((function(e,n,r){return n.from.coordinates[1]>t.edges[e].from.coordinates[1]&&(e=r),e}),0),n=(0===e?this.length:e)-1,r=(e+1)%this.length,i=Mu(this.edges[n].from.coordinates,this.edges[e].from.coordinates,this.edges[r].from.coordinates);return 0===i?this.edges[n].from.coordinates[0]>this.edges[r].from.coordinates[0]:i>0}},{key:"toMultiPoint",value:function(){return O(this.edges.map((function(t){return t.from.coordinates})))}},{key:"toPolygon",value:function(){if(this.polygon)return this.polygon;var t=this.edges.map((function(t){return t.from.coordinates}));return t.push(this.edges[0].from.coordinates),this.polygon=S([t])}},{key:"getEnvelope",value:function(){return this.envelope?this.envelope:this.envelope=Us(this.toPolygon())}},{key:"inside",value:function(t){return zt(t,this.toPolygon())}}],[{key:"findEdgeRingContaining",value:function(t,e){var n,r,i=t.getEnvelope();return e.forEach((function(e){var o,s,u,l,h,c,f=e.getEnvelope();if((r&&(n=r.getEnvelope()),s=i,u=(o=f).geometry.coordinates[0].map((function(t){return t[0]})),l=o.geometry.coordinates[0].map((function(t){return t[1]})),h=s.geometry.coordinates[0].map((function(t){return t[0]})),c=s.geometry.coordinates[0].map((function(t){return t[1]})),Math.max.apply(null,u)!==Math.max.apply(null,h)||Math.max.apply(null,l)!==Math.max.apply(null,c)||Math.min.apply(null,u)!==Math.min.apply(null,h)||Math.min.apply(null,l)!==Math.min.apply(null,c))&&Lu(f,i)){var g,p,v=a(t.map((function(t){return t.from.coordinates})));try{var d=function(){var t=p.value;e.some((function(e){return n=t,r=e.from.coordinates,n[0]===r[0]&&n[1]===r[1];var n,r}))||(g=t)};for(v.s();!(p=v.n()).done;)d()}catch(t){v.e(t)}finally{v.f()}g&&e.inside(I(g))&&(r&&!Lu(n,f)||(r=e))}})),r}}])}();var Ou=function(){function t(){i(this,t),this.edges=[],this.nodes={}}return s(t,[{key:"getNode",value:function(t){var e=Pu.buildId(t),n=this.nodes[e];return n||(n=this.nodes[e]=new Pu(t)),n}},{key:"addEdge",value:function(t,e){var n=new Cu(t,e),r=n.getSymetric();this.edges.push(n),this.edges.push(r)}},{key:"deleteDangles",value:function(){var t=this;Object.keys(this.nodes).map((function(e){return t.nodes[e]})).forEach((function(e){return t._removeIfDangle(e)}))}},{key:"_removeIfDangle",value:function(t){var e=this;if(t.innerEdges.length<=1){var n=t.getOuterEdges().map((function(t){return t.to}));this.removeNode(t),n.forEach((function(t){return e._removeIfDangle(t)}))}}},{key:"deleteCutEdges",value:function(){var t=this;this._computeNextCWEdges(),this._findLabeledEdgeRings(),this.edges.forEach((function(e){e.label===e.symetric.label&&(t.removeEdge(e.symetric),t.removeEdge(e))}))}},{key:"_computeNextCWEdges",value:function(t){var e=this;void 0===t?Object.keys(this.nodes).forEach((function(t){return e._computeNextCWEdges(e.nodes[t])})):t.getOuterEdges().forEach((function(e,n){t.getOuterEdge((0===n?t.getOuterEdges().length:n)-1).symetric.next=e}))}},{key:"_computeNextCCWEdges",value:function(t,e){for(var n,r,i=t.getOuterEdges(),o=i.length-1;o>=0;--o){var s=i[o],a=s.symetric,u=void 0,l=void 0;s.label===e&&(u=s),a.label===e&&(l=a),u&&l&&(l&&(r=l),u&&(r&&(r.next=u,r=void 0),n||(n=u)))}r&&(r.next=n)}},{key:"_findLabeledEdgeRings",value:function(){var t=[],e=0;return this.edges.forEach((function(n){if(!(n.label>=0)){t.push(n);var r=n;do{r.label=e,r=r.next}while(!n.isEqual(r));e++}})),t}},{key:"getEdgeRings",value:function(){var t=this;this._computeNextCWEdges(),this.edges.forEach((function(t){t.label=void 0})),this._findLabeledEdgeRings().forEach((function(e){t._findIntersectionNodes(e).forEach((function(n){t._computeNextCCWEdges(n,e.label)}))}));var e=[];return this.edges.forEach((function(n){n.ring||e.push(t._findEdgeRing(n))})),e}},{key:"_findIntersectionNodes",value:function(t){var e=[],n=t,r=function(){var r=0;n.from.getOuterEdges().forEach((function(e){e.label===t.label&&++r})),r>1&&e.push(n.from),n=n.next};do{r()}while(!t.isEqual(n));return e}},{key:"_findEdgeRing",value:function(t){var e=t,n=new Tu;do{n.push(e),e.ring=n,e=e.next}while(!t.isEqual(e));return n}},{key:"removeNode",value:function(t){var e=this;t.getOuterEdges().forEach((function(t){return e.removeEdge(t)})),t.innerEdges.forEach((function(t){return e.removeEdge(t)})),delete this.nodes[t.id]}},{key:"removeEdge",value:function(t){this.edges=this.edges.filter((function(e){return!e.isEqual(t)})),t.deleteEdge()}}],[{key:"fromGeoJson",value:function(e){!function(t){if(!t)throw new Error("No geojson passed");if("FeatureCollection"!==t.type&&"GeometryCollection"!==t.type&&"MultiLineString"!==t.type&&"LineString"!==t.type&&"Feature"!==t.type)throw new Error("Invalid input type '".concat(t.type,"'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature"))}(e);var n=new t;return xt(e,(function(t){et(t,"LineString","Graph::fromGeoJson"),ft(t,(function(t,e){if(t){var r=n.getNode(t),i=n.getNode(e);n.addEdge(r,i)}return e}))})),n}}])}();function Ru(t,e){var n,r;ct(t,(function(t,i,o,s,a){if(r!==a)e.push([]);else{var u=n[0],l=n[1],h=t[0],c=t[1];e[a].push([.75*u+.25*h,.75*l+.25*c]),e[a].push([.25*u+.75*h,.25*l+.75*c])}n=t,r=a}),!1),e.forEach((function(t){t.push(t[0])}))}function Au(t,e){var n,r,i;ct(t,(function(t,o,s,a,u){if(r!==a)e.push([[]]);else if(i!==u)e[a].push([]);else{var l=n[0],h=n[1],c=t[0],f=t[1];e[a][u].push([.75*l+.25*c,.75*h+.25*f]),e[a][u].push([.25*l+.75*c,.25*h+.75*f])}n=t,r=a,i=u}),!1),e.forEach((function(t){t.forEach((function(t){t.push(t[0])}))}))}function Du(t,e,n,r,i){for(var o=0;o0?qu(e,s,r)<0||(r=s):n>0&&u<=0&&(Fu(e,s,i)||(i=s)),n=u}return[r,i]}function Fu(t,e,n){return qu(t,e,n)>0}function qu(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(n[0]-t[0])*(e[1]-t[1])}function Vu(t){return Bu(t,"mercator",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Gu(t){return Bu(t,"wgs84",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Bu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=(n=n||{}).mutate;if(!t)throw new Error("geojson is required");return Array.isArray(t)&&U(t[0])?t="mercator"===e?Yu(t):zu(t):(!0!==r&&(t=Ai(t)),ct(t,(function(t){var n="mercator"===e?Yu(t):zu(t);t[0]=n[0],t[1]=n[1]}))),t}function Yu(t){var e=Math.PI/180,n=6378137,r=20037508.342789244,i=Math.abs(t[0])<=180?t[0]:t[0]-360*function(t){return t<0?-1:t>0?1:0}(t[0]),o=[n*i*e,n*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return o[0]>r&&(o[0]=r),o[0]<-r&&(o[0]=-r),o[1]>r&&(o[1]=r),o[1]<-r&&(o[1]=-r),o}function zu(t){var e=180/Math.PI,n=6378137;return[t[0]*e/n,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/n)))*e]}var ju=Object.freeze({__proto__:null,toMercator:Vu,toWgs84:Gu});var Xu={20:1.07275,15:1.13795,10:1.22385,5:1.3581,2:1.51743,1:1.62762};function Uu(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}function Zu(t){var e=[];return function t(n){return 0===n||1===n?1:e[n]>0?e[n]:e[n]=t(n-1)*n}(t)}function Hu(t){return Ju(t),Wu(t)}function Wu(t){return Array.isArray(t)?el(t):t&&t.bbox?el(t.bbox):[360*tl(),180*tl()]}function Ju(t){null!=t&&(Array.isArray(t)?H(t):null!=t.bbox&&H(t.bbox))}function Ku(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1);for(var n=[],r=0;r1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1),void 0!==e.bbox&&null!==e.bbox||(e.bbox=[-180,-90,180,90]),U(e.num_vertices)&&void 0!==e.num_vertices||(e.num_vertices=10),U(e.max_radial_length)&&void 0!==e.max_radial_length||(e.max_radial_length=10);var n=Math.abs(e.bbox[0]-e.bbox[2]),r=Math.abs(e.bbox[1]-e.bbox[3]),i=Math.min(n/2,r/2);if(e.max_radial_length>i)throw new Error("max_radial_length is greater than the radius of the bbox");for(var o=[e.bbox[0]+e.max_radial_length,e.bbox[1]+e.max_radial_length,e.bbox[2]-e.max_radial_length,e.bbox[3]-e.max_radial_length],s=[],a=function(){var t,n=[],r=d(Array(e.num_vertices+1)).map(Math.random);r.forEach((function(t,e,n){n[e]=e>0?t+n[e-1]:t})),r.forEach((function(t){t=2*t*Math.PI/r[r.length-1];var i=Math.random();n.push([i*(e.max_radial_length||10)*Math.sin(t),i*(e.max_radial_length||10)*Math.cos(t)])})),n[n.length-1]=n[0],n=n.reverse().map((t=Wu(o),function(e){return[e[0]+t[0],e[1]+t[1]]})),s.push(S([n]))},u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox;Ju(n);var r=e.num_vertices,i=e.max_length,o=e.max_rotation;null==t&&(t=1),(!U(r)||void 0===r||r<2)&&(r=10),U(i)&&void 0!==i||(i=1e-4),U(o)&&void 0!==o||(o=Math.PI/8);for(var s=[],a=0;a0;){var l=a.pop();if(l===n)return ll(l);l.closed=!0;for(var h=t.neighbors(l),c=0,f=h.length;c1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function dl(t,e,n,r,i){for(var o,s=r,a=e+1;as&&(o=a,s=u)}s>r&&(o-e>1&&dl(t,e,o,r,i),i.push(t[o]),n-o>1&&dl(t,o,n,r,i))}function yl(t,e){var n=t.length-1,r=[t[0]];return dl(t,0,n,e,r),r.push(t[n]),r}function ml(t,e,n){if(t.length<=2)return t;var r=void 0!==e?e*e:1;return t=n?t:function(t,e){for(var n,r,i,o,s,a=t[0],u=[a],l=1,h=t.length;le&&(u.push(n),a=n);return a!==n&&u.push(n),u}(t,r),t=yl(t,r)}function _l(t,e,n){return t.map((function(t){if(t.length<4)throw new Error("invalid polygon");for(var r=e,i=ml(t,r,n);!xl(i);)i=ml(t,r-=.01*r,n);return i[i.length-1][0]===i[0][0]&&i[i.length-1][1]===i[0][1]||i.push(i[0]),i}))}function xl(t){return!(t.length<3)&&!(3===t.length&&t[2][0]===t[0][0]&&t[2][1]===t[0][1])}function El(t,e){return{x:t[0]-e[0],y:t[1]-e[1]}}cl.prototype.init=function(){this.dirtyNodes=[];for(var t=0;t0&&(this.content[0]=e,this.bubbleUp(0)),t},remove:function(t){var e=this.content.indexOf(t),n=this.content.pop();e!==this.content.length-1&&(this.content[e]=n,this.scoreFunction(n)0;){var n=(t+1>>1)-1,r=this.content[n];if(!(this.scoreFunction(e)80*i){o=a=t[0],s=h=t[1];for(var _=i;_a&&(a=c),g>h&&(h=g);p=0!==(p=Math.max(a-o,h-s))?32767/p:0}return r(y,m,i,o,s,p,0),m}function e(t,e,n,r,i){var o,s;if(i===I(t,e,n,r)>0)for(o=e;o=e;o-=r)s=k(o,t[o],t[o+1],s);return s&&d(s,s.next)&&(b(s),s=s.next),s}function n(t,e){if(!t)return t;e||(e=t);var n,r=t;do{if(n=!1,r.steiner||!d(r,r.next)&&0!==v(r.prev,r,r.next))r=r.next;else{if(b(r),(r=e=r.prev)===r.next)break;n=!0}}while(n||r!==e);return e}function r(t,e,u,l,h,f,g){if(t){!g&&f&&function(t,e,n,r){var i=t;do{0===i.z&&(i.z=c(i.x,i.y,e,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,n,r,i,o,s,a,u,l=1;do{for(n=t,t=null,o=null,s=0;n;){for(s++,r=n,a=0,e=0;e0||u>0&&r;)0!==a&&(0===u||!r||n.z<=r.z)?(i=n,n=n.nextZ,a--):(i=r,r=r.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;n=r}o.nextZ=null,l*=2}while(s>1)}(i)}(t,l,h,f);for(var p,v,d=t;t.prev!==t.next;)if(p=t.prev,v=t.next,f?o(t,l,h,f):i(t))e.push(p.i/u|0),e.push(t.i/u|0),e.push(v.i/u|0),b(t),t=v.next,d=v.next;else if((t=v)===d){g?1===g?r(t=s(n(t),e,u),e,u,l,h,f,2):2===g&&a(t,e,u,l,h,f):r(n(t),e,u,l,h,f,1);break}}}function i(t){var e=t.prev,n=t,r=t.next;if(v(e,n,r)>=0)return!1;for(var i=e.x,o=n.x,s=r.x,a=e.y,u=n.y,l=r.y,h=io?i>s?i:s:o>s?o:s,p=a>u?a>l?a:l:u>l?u:l,d=r.next;d!==e;){if(d.x>=h&&d.x<=f&&d.y>=c&&d.y<=p&&g(i,a,o,u,s,l,d.x,d.y)&&v(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function o(t,e,n,r){var i=t.prev,o=t,s=t.next;if(v(i,o,s)>=0)return!1;for(var a=i.x,u=o.x,l=s.x,h=i.y,f=o.y,p=s.y,d=au?a>l?a:l:u>l?u:l,_=h>f?h>p?h:p:f>p?f:p,x=c(d,y,e,n,r),E=c(m,_,e,n,r),k=t.prevZ,b=t.nextZ;k&&k.z>=x&&b&&b.z<=E;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;if(k=k.prevZ,b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;k&&k.z>=x;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;k=k.prevZ}for(;b&&b.z<=E;){if(b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function s(t,e,r){var i=t;do{var o=i.prev,s=i.next.next;!d(o,s)&&y(o,i,i.next,s)&&x(o,s)&&x(s,o)&&(e.push(o.i/r|0),e.push(i.i/r|0),e.push(s.i/r|0),b(i),b(i.next),i=t=s),i=i.next}while(i!==t);return n(i)}function a(t,e,i,o,s,a){var u=t;do{for(var l=u.next.next;l!==u.prev;){if(u.i!==l.i&&p(u,l)){var h=E(u,l);return u=n(u,u.next),h=n(h,h.next),r(u,e,i,o,s,a,0),void r(h,e,i,o,s,a,0)}l=l.next}u=u.next}while(u!==t)}function u(t,e){return t.x-e.x}function l(t,e){var r=function(t,e){var n,r=e,i=t.x,o=t.y,s=-1/0;do{if(o<=r.y&&o>=r.next.y&&r.next.y!==r.y){var a=r.x+(o-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=i&&a>s&&(s=a,n=r.x=r.x&&r.x>=c&&i!==r.x&&g(on.x||r.x===n.x&&h(n,r)))&&(n=r,p=u)),r=r.next}while(r!==l);return n}(t,e);if(!r)return e;var i=E(r,t);return n(i,i.next),n(r,r.next)}function h(t,e){return v(t.prev,t,e.prev)<0&&v(e.next,t,t.next)<0}function c(t,e,n,r,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function f(t){var e=t,n=t;do{(e.x=(t-s)*(o-a)&&(t-s)*(r-a)>=(n-s)*(e-a)&&(n-s)*(o-a)>=(i-s)*(r-a)}function p(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&y(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(x(t,e)&&x(e,t)&&function(t,e){var n=t,r=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{n.y>o!=n.next.y>o&&n.next.y!==n.y&&i<(n.next.x-n.x)*(o-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==t);return r}(t,e)&&(v(t.prev,t,e.prev)||v(t,e.prev,e))||d(t,e)&&v(t.prev,t,t.next)>0&&v(e.prev,e,e.next)>0)}function v(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function d(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,n,r){var i=_(v(t,e,n)),o=_(v(t,e,r)),s=_(v(n,r,t)),a=_(v(n,r,e));return i!==o&&s!==a||(!(0!==i||!m(t,n,e))||(!(0!==o||!m(t,r,e))||(!(0!==s||!m(n,t,r))||!(0!==a||!m(n,e,r)))))}function m(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function _(t){return t>0?1:t<0?-1:0}function x(t,e){return v(t.prev,t,t.next)<0?v(t,e,t.next)>=0&&v(t,t.prev,e)>=0:v(t,e,t.prev)<0||v(t,t.next,e)<0}function E(t,e){var n=new w(t.i,t.x,t.y),r=new w(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,n.next=i,i.prev=n,r.next=n,n.prev=r,o.next=r,r.prev=o,r}function k(t,e,n,r){var i=new w(t,e,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function b(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 w(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function I(t,e,n,r){for(var i=0,o=e,s=n-r;o0&&(r+=t[i-1].length,n.holes.push(r))}return n},bl.exports}(),Il=mn(wl);function Nl(t){var e=function(t){for(var e=t[0][0].length,n={vertices:[],holes:[],dimensions:e},r=0,i=0;i0&&(r+=t[i-1].length,n.holes.push(r))}return n}(t),n=Il(e.vertices,e.holes,2),r=[],i=[];n.forEach((function(t,r){var o=n[r];i.push([e.vertices[2*o],e.vertices[2*o+1]])}));for(var o=0;o=1||u<=0||l>=1||l<=0))){var v=p,d=!o[v];d&&(o[v]=!0),e?i.push(e(p,t,n,h,c,u,s,a,f,g,l,d)):i.push(p)}}function v(t,e){var n,i,o,s,a=r[t][e],u=r[t][e+1];return a[0]f[e.isect].coord?-1:1}));for(l=[];x.length>0;){var I=x.pop(),N=I.isect,M=I.parent,L=I.winding,P=l.length,T=[f[N].coord],O=N;if(f[N].ringAndEdge1Walkable)var R=f[N].ringAndEdge1,A=f[N].nxtIsectAlongRingAndEdge1;else R=f[N].ringAndEdge2,A=f[N].nxtIsectAlongRingAndEdge2;for(;!Rl(f[N].coord,f[A].coord);){T.push(f[A].coord);var D=void 0;for(r=0;r1)for(e=0;e=0==e}function Ol(t){for(var e=0,n=0;n0)){if(o/=f,f<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=r-u,f||!(o<0)){if(o/=f,f<0){if(o>c)return;o>h&&(h=o)}else if(f>0){if(o0)){if(o/=g,g<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=i-l,g||!(o<0)){if(o/=g,g<0){if(o>c)return;o>h&&(h=o)}else if(g>0){if(o0||c<1)||(h>0&&(t[0]=[u+h*f,l+h*g]),c<1&&(t[1]=[u+c*f,l+c*g]),!0)}}}}}function Hl(t,e,n,r,i){var o=t[1];if(o)return!0;var s,a,u=t[0],l=t.left,h=t.right,c=l[0],f=l[1],g=h[0],p=h[1],v=(c+g)/2,d=(f+p)/2;if(p===f){if(v=r)return;if(c>g){if(u){if(u[1]>=i)return}else u=[v,n];o=[v,i]}else{if(u){if(u[1]1)if(c>g){if(u){if(u[1]>=i)return}else u=[(n-a)/s,n];o=[(i-a)/s,i]}else{if(u){if(u[1]=r)return}else u=[e,s*e+a];o=[r,s*r+a]}else{if(u){if(u[0]=-dh)){var g=u*u+l*l,p=h*h+c*c,v=(c*g-l*p)/f,d=(u*p-h*g)/f,y=$l.pop()||new th;y.arc=t,y.site=i,y.x=v+s,y.y=(y.cy=d+a)+Math.sqrt(v*v+d*d),t.circle=y;for(var m=null,_=gh._;_;)if(y.y<_.y||y.y===_.y&&y.x<=_.x){if(!_.L){m=_.P;break}_=_.L}else{if(!_.R){m=_;break}_=_.R}gh.insert(m,y),m||(Ql=y)}}}}function nh(t){var e=t.circle;e&&(e.P||(Ql=e.N),gh.remove(e),$l.push(e),Gl(e),t.circle=null)}var rh=[];function ih(){Gl(this),this.edge=this.site=this.circle=null}function oh(t){var e=rh.pop()||new ih;return e.site=t,e}function sh(t){nh(t),ch.remove(t),rh.push(t),Gl(t)}function ah(t){var e=t.circle,n=e.x,r=e.cy,i=[n,r],o=t.P,s=t.N,a=[t];sh(t);for(var u=o;u.circle&&Math.abs(n-u.circle.x)vh)a=a.L;else{if(!((i=o-hh(a,s))>vh)){r>-vh?(e=a.P,n=a):i>-vh?(e=a,n=a.N):e=n=a;break}if(!a.R){e=a;break}a=a.R}!function(t){fh[t.index]={site:t,halfedges:[]}}(t);var u=oh(t);if(ch.insert(e,u),e||n){if(e===n)return nh(e),n=oh(e.site),ch.insert(u,n),u.edge=n.edge=jl(e.site,u.site),eh(e),void eh(n);if(n){nh(e),nh(n);var l=e.site,h=l[0],c=l[1],f=t[0]-h,g=t[1]-c,p=n.site,v=p[0]-h,d=p[1]-c,y=2*(f*d-g*v),m=f*f+g*g,_=v*v+d*d,x=[(d*m-g*_)/y+h,(f*_-v*m)/y+c];Ul(n.edge,l,p,x),u.edge=jl(l,t,null,x),n.edge=jl(t,p,null,x),eh(e),eh(n)}else u.edge=jl(e.site,u.site)}}function lh(t,e){var n=t.site,r=n[0],i=n[1],o=i-e;if(!o)return r;var s=t.P;if(!s)return-1/0;var a=(n=s.site)[0],u=n[1],l=u-e;if(!l)return a;var h=a-r,c=1/o-1/l,f=h/l;return c?(-f+Math.sqrt(f*f-2*c*(h*h/(-2*l)-u+l/2+i-o/2)))/c+r:(r+a)/2}function hh(t,e){var n=t.N;if(n)return lh(n,e);var r=t.site;return r[1]===e?r[0]:1/0}var ch,fh,gh,ph,vh=1e-6,dh=1e-12;function yh(t,e){return e[1]-t[1]||e[0]-t[0]}function mh(t,e){var n,r,i,o=t.sort(yh).pop();for(ph=[],fh=new Array(t.length),ch=new Vl,gh=new Vl;;)if(i=Ql,o&&(!i||o[1]vh||Math.abs(i[0][1]-i[1][1])>vh)||delete ph[o]}(s,a,u,l),function(t,e,n,r){var i,o,s,a,u,l,h,c,f,g,p,v,d=fh.length,y=!0;for(i=0;ivh||Math.abs(v-f)>vh)&&(u.splice(a,0,ph.push(Xl(s,g,Math.abs(p-t)vh?[t,Math.abs(c-t)vh?[Math.abs(f-r)vh?[n,Math.abs(c-n)vh?[Math.abs(f-e)=a)return null;var u=t-i.site[0],l=e-i.site[1],h=u*u+l*l;do{i=o.cells[r=s],s=null,i.halfedges.forEach((function(n){var r=o.edges[n],a=r.left;if(a!==i.site&&a||(a=r.right)){var u=t-a[0],l=e-a[1],c=u*u+l*l;c2&&void 0!==arguments[2]?arguments[2]:{},r=rt(t).coordinates,i=0,o=0;o=i&&o===r.length-1);o++){if(i>=e){var s=e-i;if(s){var a=st(r[o],r[o-1])-180;return at(r[o],s,a,n)}return I(r[o])}i+=ut(r[o],r[o+1],n)}return I(r[r.length-1])},t.angle=function(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!Z(r))throw new Error("options is invalid");if(!t)throw new Error("startPoint is required");if(!e)throw new Error("midPoint is required");if(!n)throw new Error("endPoint is required");var i=t,o=e,s=n,a=G(!0!==r.mercator?st(o,i):lt(o,i)),u=G(!0!==r.mercator?st(o,s):lt(o,s));u1&&void 0!==arguments[1]?arguments[1]:{},n=e.resolution||1e4,r=e.sharpness||.85,i=[],o=rt(t).coordinates.map((function(t){return{x:t[0],y:t[1]}})),s=new Gt({duration:n,points:o,sharpness:r}),a=function(t){var e=s.pos(t);Math.floor(t/100)%2==0&&i.push([e.x,e.y])},u=0;u0;else if(n!==u>0)return!0}return!1},t.booleanContains=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type,s=n.coordinates,u=r.coordinates;switch(i){case"Point":if("Point"===o)return Ht(s,u);throw new Error("feature2 "+o+" geometry not supported");case"MultiPoint":switch(o){case"Point":return function(t,e){var n,r=!1;for(n=0;n2&&void 0!==arguments[2]?arguments[2]:{}).precision;if("number"!=typeof(n=null==n||isNaN(n)?6:n)||!(n>=0))throw new Error("precision must be a positive number");return rt(t).type===rt(e).type&&Ne(Le(t),Le(e),{precision:n})},t.booleanIntersects=Oe,t.booleanOverlap=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;if("MultiPoint"===i&&"MultiPoint"!==o||("LineString"===i||"MultiLineString"===i)&&"LineString"!==o&&"MultiLineString"!==o||("Polygon"===i||"MultiPolygon"===i)&&"Polygon"!==o&&"MultiPolygon"!==o)throw new Error("features must be of the same type");if("Point"===i)throw new Error("Point geometry not supported");if(Ne(t,e,{precision:6}))return!1;var s=0;switch(i){case"MultiPoint":for(var a=0;a0},t.booleanParallel=function(t,e){if(!t)throw new Error("line1 is required");if(!e)throw new Error("line2 is required");if("LineString"!==In(t,"line1"))throw new Error("line1 must be a LineString");if("LineString"!==In(e,"line2"))throw new Error("line2 must be a LineString");for(var n=$e(Le(t)).features,r=$e(Le(e)).features,i=0;i1;case"MultiPoint":for(var i=0;i0&&ue(S([r[0]]),S([r[i]])).features.length>1)return!1}return!0;case"MultiPolygon":for(i=0;i0&&ue(S([o[0]]),S([o[s]])).features.length>1)return!1}return!0;default:return!1}},t.booleanWithin=Cn,t.buffer=function(t,e,n){var r=(n=n||{}).units||"kilometers",i=n.steps||8;if(!t)throw new Error("geojson is required");if("object"!==m(n))throw new Error("options must be an object");if("number"!=typeof i)throw new Error("steps must be an number");if(void 0===e)throw new Error("radius is required");if(i<=0)throw new Error("steps must be greater than 0");var o=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){var n=ui(t,e,r,i);n&&o.push(n)})),C(o);case"FeatureCollection":return vt(t,(function(t){var n=ui(t,e,r,i);n&&vt(n,(function(t){t&&o.push(t)}))})),C(o)}return ui(t,e,r,i)},t.center=An,t.centerMean=fi,t.centerMedian=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.counter||10;if(!U(n))throw new Error("counter must be a number");var r=e.weight,i=fi(t,{weight:e.weight}),o=C([]);vt(t,(function(t){var e;o.features.push(gi(t,{properties:{weight:null==(e=t.properties)?void 0:e[r]}}))}));var s={tolerance:e.tolerance,medianCandidates:[]};return pi(i.geometry.coordinates,[0,0],o,s,n)},t.centerOfMass=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(it(e)){case"Point":return I(K(e),n.properties);case"Polygon":var r=[];ct(e,(function(t){r.push(t)}));var i,o,s,a,u,l,h,c,f=gi(e,{properties:n.properties}),g=f.geometry.coordinates,p=0,v=0,d=0,y=r.map((function(t){return[t[0]-g[0],t[1]-g[1]]}));for(i=0;i2&&void 0!==arguments[2]?arguments[2]:{};!0!==n.mutate&&(t=Ai(t));var r=n.minPoints||3,i=V(e,n.units),o=new to(t.features.length),s=t.features.map((function(t){return!1})),a=t.features.map((function(t){return!1})),u=t.features.map((function(t){return!1})),l=t.features.map((function(t){return-1}));o.load(t.features.map((function(t,e){var n=v(t.geometry.coordinates,2),r=n[0],i=n[1];return{minX:r,minY:i,maxX:r,maxY:i,index:e}})));var h=function(n){var r=t.features[n],s=v(r.geometry.coordinates,2),a=s[0],u=s[1],l=Math.max(u-i,-90),h=Math.min(u+i,90),c=l<0&&h>0?i:Math.abs(l)=r){var i=c;c++,s[e]=!0,function(t,e){for(var n=0;n=r&&e.push.apply(e,d(o))}a[i]||(a[i]=!0,l[i]=t)}}(i,n)}else u[e]=!0}})),t.features.forEach((function(e,n){var r=t.features[n];r.properties||(r.properties={}),l[n]>=0?(r.properties.dbscan=u[n]?"edge":"core",r.properties.cluster=l[n]):r.properties.dbscan="noise"})),t},t.clustersKmeans=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.features.length;e.numberOfClusters=e.numberOfClusters||Math.round(Math.sqrt(n/2)),e.numberOfClusters>n&&(e.numberOfClusters=n),!0!==e.mutate&&(t=Ai(t));var r=yt(t),i=r.slice(0,e.numberOfClusters),o=ro(r,e.numberOfClusters,i),s={};return o.centroids.forEach((function(t,e){s[e]=t})),vt(t,(function(t,e){var n=o.idxs[e];t.properties.cluster=n,t.properties.centroid=s[n]})),t},t.collect=function(t,e,n,r){var i=new io(6),o=e.features.map((function(t){var e;return{minX:t.geometry.coordinates[0],minY:t.geometry.coordinates[1],maxX:t.geometry.coordinates[0],maxY:t.geometry.coordinates[1],property:null==(e=t.properties)?void 0:e[n]}}));return i.load(o),t.features.forEach((function(t){t.properties||(t.properties={});var e=Rt(t),n=i.search({minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}),o=[];n.forEach((function(e){zt([e.minX,e.minY],t)&&o.push(e.property)})),t.properties[r]=o})),t},t.collectionOf=nt,t.combine=function(t){var e={MultiPoint:{coordinates:[],properties:[]},MultiLineString:{coordinates:[],properties:[]},MultiPolygon:{coordinates:[],properties:[]}};return vt(t,(function(t){var n,r,i,o;switch(null==(o=t.geometry)?void 0:o.type){case"Point":e.MultiPoint.coordinates.push(t.geometry.coordinates),e.MultiPoint.properties.push(t.properties);break;case"MultiPoint":(n=e.MultiPoint.coordinates).push.apply(n,d(t.geometry.coordinates)),e.MultiPoint.properties.push(t.properties);break;case"LineString":e.MultiLineString.coordinates.push(t.geometry.coordinates),e.MultiLineString.properties.push(t.properties);break;case"MultiLineString":(r=e.MultiLineString.coordinates).push.apply(r,d(t.geometry.coordinates)),e.MultiLineString.properties.push(t.properties);break;case"Polygon":e.MultiPolygon.coordinates.push(t.geometry.coordinates),e.MultiPolygon.properties.push(t.properties);break;case"MultiPolygon":(i=e.MultiPolygon.coordinates).push.apply(i,d(t.geometry.coordinates)),e.MultiPolygon.properties.push(t.properties)}})),C(Object.keys(e).filter((function(t){return e[t].coordinates.length})).sort().map((function(t){return b({type:t,coordinates:e[t].coordinates},{collectedProperties:e[t].properties})})))},t.concave=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.maxEdge||1/0,r=function(t){var e=[],n={};return vt(t,(function(t){if(t.geometry){var r=t.geometry.coordinates.join("-");Object.prototype.hasOwnProperty.call(n,r)||(e.push(t),n[r]=!0)}})),C(e)}(t),i=oo(r);if(i.features=i.features.filter((function(t){var r=t.geometry.coordinates[0][0],i=t.geometry.coordinates[0][1],o=t.geometry.coordinates[0][2],s=ut(r,i,e),a=ut(i,o,e),u=ut(r,o,e);return s<=n&&a<=n&&u<=n})),i.features.length<1)return null;var o=Ro(i);return 1===o.coordinates.length&&(o.coordinates=o.coordinates[0],o.type="Polygon"),b(o)},t.containsNumber=$,t.convertArea=X,t.convertLength=j,t.convex=Oi,t.coordAll=yt,t.coordEach=ct,t.coordReduce=ft,t.createBins=zi,t.degreesToRadians=z,t.destination=at,t.difference=function(t){var e=[];if(mt(t,(function(t){e.push(t.coordinates)})),e.length<2)throw new Error("Must have at least two features");var n=t.features[0].properties||{},r=As.apply(Fs,[e[0]].concat(d(e.slice(1))));return 0===r.length?null:1===r.length?S(r[0],n):R(r,n)},t.dissolve=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.propertyName;nt(t,"Polygon","dissolve");var r=[];if(!n)return qs(R(Os.apply(null,t.features.map((function(t){return t.geometry.coordinates})))));var i={};vt(t,(function(t){t.properties&&(Object.prototype.hasOwnProperty.call(i,t.properties[n])||(i[t.properties[n]]=[]),i[t.properties[n]].push(t))}));for(var o=Object.keys(i),s=0;s1&&void 0!==arguments[1]?arguments[1]:{},o=i.properties,s=null==(e=i.autoComplete)||e,a=null==(n=i.orderCoords)||n;if(null!=(r=i.mutate)&&r||(t=Ai(t)),"FeatureCollection"===t.type){var u=[];return t.features.forEach((function(t){u.push(Q(ru(t,{},s,a)))})),R(u,o)}return ru(t,o,s,a)},t.mask=function(t,e,n){var r,i=null!=(r=null==n?void 0:n.mutate)&&r,o=e;e&&!1===i&&(o=Ai(e));var s,a=su(o);return("FeatureCollection"===t.type?ou(2===(s=t).features.length?Os(s.features[0].geometry.coordinates,s.features[1].geometry.coordinates):Os.apply(Fs,s.features.map((function(t){return t.geometry.coordinates})))):"Feature"===t.type?ou(Os(t.geometry.coordinates)):ou(Os(t.coordinates))).geometry.coordinates.forEach((function(t){a.geometry.coordinates.push(t[0])})),a},t.meta=Mt,t.midpoint=function(t,e){return at(t,ut(t,e)/2,st(t,e))},t.moranIndex=function(t,e){var n,r,i=e.inputField,o=e.threshold||1e5,s=e.p||2,u=null!=(n=e.binary)&&n,l=Gs(t,{alpha:e.alpha||-1,binary:u,p:s,standardization:null==(r=e.standardization)||r,threshold:o}),h=[];vt(t,(function(t){var e=t.properties||{};h.push(e[i])}));for(var c=au(h),f=function(t){var e,n=au(t),r=0,i=a(t);try{for(i.s();!(e=i.n()).done;){var o=e.value;r+=Math.pow(o-n,2)}}catch(t){i.e(t)}finally{i.f()}return r/t.length}(h),g=0,p=0,v=0,d=0,y=l.length,m=0;m2&&void 0!==arguments[2]?arguments[2]:{},r=n.units,i=n.properties||{},o=function(t){var e=[];switch(t.geometry?t.geometry.type:t.type){case"GeometryCollection":return mt(t,(function(t){"Point"===t.type&&e.push({type:"Feature",properties:{},geometry:t})})),{type:"FeatureCollection",features:e};case"FeatureCollection":return t.features=t.features.filter((function(t){return"Point"===t.geometry.type})),t;default:throw new Error("points must be a Point Collection")}}(t);if(!o.features.length)throw new Error("points must contain features");if(!e)throw new Error("line is required");if("LineString"!==it(e))throw new Error("line must be a LineString");var s=1/0,a=null;return vt(o,(function(t){var n=mu(t,e,{units:r});n2&&void 0!==arguments[2]?arguments[2]:{},a=null!=(i=s.method)?i:"geodesic",u=null!=(o=s.units)?o:"kilometers";if(!e)throw new Error("point is required");if(!r)throw new Error("polygon or multi-polygon is required");var l,h=rt(r);if("MultiPolygon"===h.type){var c=h.coordinates.map((function(n){return t(e,S(n),{method:a,units:u})}));return Math.min.apply(Math,d(c.map(Math.abs)))*(zt(e,r)?-1:1)}if(h.coordinates.length>1){var p=h.coordinates.map((function(n){return t(e,S([n]),{method:a,units:u})})),v=n(l=p)||f(l)||_(l)||g(),y=v[0],m=v.slice(1);if(y>=0)return y;var x=Math.min.apply(Math,d(m));return x<0?Math.abs(x):Math.min(x,Math.abs(y))}var E=le(h),k=1/0;return xt(E,(function(t){k=Math.min(k,mu(e,t,{method:a,units:u}))})),zt(e,h)?-k:k},t.points=N,t.pointsWithinPolygon=Su,t.polygon=S,t.polygonSmooth=function(t,e){(e=e||{}).iterations=e.iterations||1;var n=e.iterations,r=[];if(!t)throw new Error("inputPolys is required");return mt(t,(function(t,e,i){if("Polygon"===t.type){for(var o=[[]],s=0;s0&&(u=S(o).geometry),Ru(u,a),o=a.slice(0)}r.push(S(o,i))}else{if("MultiPolygon"!==t.type)throw new Error("geometry is invalid, must be Polygon or MultiPolygon");for(var l=[[[]]],h=0;h0&&(f=R(l).geometry),Au(f,c),l=c.slice(0)}r.push(R(l,i))}})),C(r)},t.polygonTangents=function(t,e){var n,r=Q(t),i=Q(e),o=[],s=[],a=Rt(e),u=0,l=null;switch(r[0]>a[0]&&r[0]a[1]&&r[1]_&&(_=k)}for(var b=[],w=Object.keys(l).length,I=f/w,N=0,S=0;S<_+1;S++)N+=Math.exp(-I)*Math.pow(I,S)/Zu(S),b.push(N);for(var M=[],L=0,P=0;P<_+1;P++){for(var C=0,T=Object.keys(l);CR&&(R=D)}var F=Xu[r]/Math.sqrt(w),q={criticalValue:F,isRandom:!0,maxAbsoluteDifference:R,observedDistribution:M};return R>F&&(q.isRandom=!1),q},t.radiansToDegrees=Y,t.radiansToLength=F,t.random=nl,t.randomLineString=$u,t.randomPoint=Ku,t.randomPolygon=Qu,t.randomPosition=Hu,t.rectangleGrid=oa,t.rewind=function(t){var e,n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(r=r||{}))throw new Error("options is invalid");var i=null!=(e=r.mutate)&&e,o=null!=(n=r.reverse)&&n;if(!t)throw new Error(" is required");if("boolean"!=typeof o)throw new Error(" must be a boolean");if("boolean"!=typeof i)throw new Error(" must be a boolean");i||"Point"===t.type||"MultiPoint"===t.type||(t=Ai(t));var s=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){rl(t,o)})),t;case"FeatureCollection":return vt(t,(function(t){vt(rl(t,o),(function(t){s.push(t)}))})),C(s)}return rl(t,o)},t.rhumbBearing=lt,t.rhumbDestination=Bs,t.rhumbDistance=Ys,t.round=D,t.sample=function(t,e){if(!t)throw new Error("fc is required");if(null==e)throw new Error("num is required");if("number"!=typeof e)throw new Error("num must be a number");var n=C(function(t,e){var n,r,i=t.slice(0),o=t.length,s=o-e;for(;o-- >s;)n=i[r=Math.floor((o+1)*Math.random())],i[r]=i[o],i[o]=n;return i.slice(s)}(t.features,e));return n},t.sector=function(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!Z(i=i||{}))throw new Error("options is invalid");var o=i.properties;if(!t)throw new Error("center is required");if(null==n)throw new Error("bearing1 is required");if(null==r)throw new Error("bearing2 is required");if(!e)throw new Error("radius is required");if("object"!==m(i))throw new Error("options must be an object");if(sl(n)===sl(r))return Ri(t,e,i);var s=Q(t),a=ja(t,e,n,r,i),u=[[s]];return ct(a,(function(t){u[0].push(t)})),u[0].push(s),S(u,o)},t.segmentEach=kt,t.segmentReduce=bt,t.shortestPath=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.obstacles||C([]),i=n.resolution||100;if(!t)throw new Error("start is required");if(!e)throw new Error("end is required");if(i&&(!U(i)||i<=0))throw new Error("options.resolution must be a number, greater than 0");var o=K(t),s=K(e);if(t=I(o),e=I(s),"FeatureCollection"===r.type){if(0===r.features.length)return L([o,s])}else{if("Polygon"!==r.type)throw new Error("invalid obstacles");r=C([b(rt(r))])}var a=r;a.features.push(t),a.features.push(e);var u=v(Rt(al(Vt(Rt(a)),1.15)),4),l=u[0],h=u[1],c=u[2],f=u[3],g=ut([l,h],[c,h],n)/i;a.features.pop(),a.features.pop();for(var p,d,y=g/ut([l,h],[c,h],n)*(c-l),m=g/ut([l,h],[l,f],n)*(f-h),_=c-l,x=f-h,E=Math.floor(_/y),k=Math.floor(x/m),w=(_-E*y)/2,N=[],S=[],M=1/0,P=1/0,T=f-(x-k*m)/2,O=0;T>=h;){for(var R=[],A=[],D=l+w,F=0;D<=c;){var q=I([D,T]),V=pl(q,r);R.push(V?0:1),A.push(D+"|"+T);var G=ut(q,t);!V&&G1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(i=null!=i?i:{}))throw new Error("options is invalid");var o=null!=(e=i.tolerance)?e:1,s=null!=(n=i.highQuality)&&n,a=null!=(r=i.mutate)&&r;if(!t)throw new Error("geojson is required");if(o&&o<0)throw new Error("invalid tolerance");return!0!==a&&(t=Ai(t)),mt(t,(function(t){!function(t,e,n){var r=t.type;if("Point"===r||"MultiPoint"===r)return t;if(Le(t,{mutate:!0}),"GeometryCollection"!==r)switch(r){case"LineString":t.coordinates=ml(t.coordinates,e,n);break;case"MultiLineString":t.coordinates=t.coordinates.map((function(t){return ml(t,e,n)}));break;case"Polygon":t.coordinates=_l(t.coordinates,e,n);break;case"MultiPolygon":t.coordinates=t.coordinates.map((function(t){return _l(t,e,n)}))}}(t,o,s)})),t},t.square=Ka,t.squareGrid=sa,t.standardDeviationalEllipse=function(t,e){var n;if(!Z(e=e||{}))throw new Error("options is invalid");var r=e.steps||64,i=e.weight,o=e.properties||{};if(!U(r))throw new Error("steps must be a number");if(!Z(o))throw new Error("properties must be a number");var s=yt(t).length,a=fi(t,{weight:i}),u=0,l=0,h=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));u+=Math.pow(r.x,2)*n,l+=Math.pow(r.y,2)*n,h+=r.x*r.y*n}));var c=u-l,f=Math.sqrt(Math.pow(c,2)+4*Math.pow(h,2)),g=2*h,p=Math.atan((c+f)/g),v=180*p/Math.PI,d=0,y=0,m=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));d+=Math.pow(r.x*Math.cos(p)-r.y*Math.sin(p),2)*n,y+=Math.pow(r.x*Math.sin(p)+r.y*Math.cos(p),2)*n,m+=n}));var _=Math.sqrt(2*d/m),x=Math.sqrt(2*y/m),E=js(a,_,x,{units:"degrees",angle:v,steps:r,properties:o}),k=Su(t,C([E])),b={meanCenterCoordinates:Q(a),semiMajorAxis:_,semiMinorAxis:x,numberOfFeatures:s,angle:v,percentageWithinEllipse:100*yt(k).length/s};return E.properties=null!=(n=E.properties)?n:{},E.properties.standardDeviationalEllipse=b,E},t.tag=function(t,e,n,r){return t=Ai(t),e=Ai(e),vt(t,(function(t){t.properties||(t.properties={}),vt(e,(function(e){t.properties&&e.properties&&void 0===t.properties[r]&&zt(t,e)&&(t.properties[r]=e.properties[n])}))})),t},t.tesselate=function(t){if(!t.geometry||"Polygon"!==t.geometry.type&&"MultiPolygon"!==t.geometry.type)throw new Error("input must be a Polygon or MultiPolygon");var e={type:"FeatureCollection",features:[]};return"Polygon"===t.geometry.type?e.features=Nl(t.geometry.coordinates):t.geometry.coordinates.forEach((function(t){e.features=e.features.concat(Nl(t))})),e},t.tin=oo,t.toMercator=Vu,t.toWgs84=Gu,t.transformRotate=zs,t.transformScale=al,t.transformTranslate=function(t,e,n,r){if(!Z(r=r||{}))throw new Error("options is invalid");var i=r.units,o=r.zTranslation,s=r.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("distance is required");if(o&&"number"!=typeof o&&isNaN(o))throw new Error("zTranslation is not a number");if(o=void 0!==o?o:0,0===e&&0===o)return t;if(null==n||isNaN(n))throw new Error("direction is required");return e<0&&(e=-e,n+=180),!1!==s&&void 0!==s||(t=Ai(t)),ct(t,(function(t){var r=Q(Bs(t,e,n,{units:i}));t[0]=r[0],t[1]=r[1],o&&3===t.length&&(t[2]+=o)})),t},t.triangleGrid=aa,t.truncate=Qa,t.union=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must have at least 2 geometries");var r=Os.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)},t.unkinkPolygon=function(t){var e=[];return xt(t,(function(t){"Polygon"===t.geometry.type&&vt(Ll(t),(function(n){e.push(S(n.geometry.coordinates,t.properties))}))})),C(e)},t.validateBBox=H,t.validateId=W,t.voronoi=function(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox||[-180,-85,180,85];if(!t)throw new Error("points is required");if(!Array.isArray(n))throw new Error("bbox is invalid");return nt(t,"Point","points"),C(function(){var t=Fl,e=ql,n=null;function r(r){return new mh(r.map((function(n,i){var o=[Math.round(t(n,i,r)/vh)*vh,Math.round(e(n,i,r)/vh)*vh];return o.index=i,o.data=n,o})),n)}return r.polygons=function(t){return r(t).polygons()},r.links=function(t){return r(t).links()},r.triangles=function(t){return r(t).triangles()},r.x=function(e){return arguments.length?(t="function"==typeof e?e:Dl(+e),r):t},r.y=function(t){return arguments.length?(e="function"==typeof t?t:Dl(+t),r):e},r.extent=function(t){return arguments.length?(n=null==t?null:[[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]],r):n&&[[n[0][0],n[0][1]],[n[1][0],n[1][1]]]},r.size=function(t){return arguments.length?(n=null==t?null:[[0,0],[+t[0],+t[1]]],r):n&&[n[1][0]-n[0][0],n[1][1]-n[0][1]]},r}().x((function(t){return t.geometry.coordinates[0]})).y((function(t){return t.geometry.coordinates[1]})).extent([[n[0],n[1]],[n[2],n[3]]]).polygons(t.features).map((function(e,n){return Object.assign(function(t){return(t=t.slice()).push(t[0]),S([t])}(e),{properties:Fi(t.features[n].properties)})})))}})); diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js new file mode 100644 index 0000000..6b2b9e8 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js @@ -0,0 +1,207 @@ +// This code is derived from the ISC-licensed "mapbox-gl-draw-freehand-mode" plugin +// by Ben Ehmke, Eric Dong, and Joe Woodhouse. +// Source: https://github.com/bemky/mapbox-gl-draw-freehand-mode +(function (MapboxDraw) { + const { geojsonTypes, cursors, types, updateActions, modes, events } = + MapboxDraw.constants; + + const FreehandMode = {}; + + FreehandMode.onSetup = function () { + const polygon = this.newFeature({ + type: geojsonTypes.FEATURE, + properties: {}, + geometry: { + type: geojsonTypes.POLYGON, + coordinates: [[]], + }, + }); + + this.addFeature(polygon); + this.clearSelectedFeatures(); + + // Disable map dragging + setTimeout(() => { + if (!this.map || !this.map.dragPan) return; + this.map.dragPan.disable(); + }, 0); + + this.updateUIClasses({ mouse: cursors.ADD }); + this.activateUIButton(types.POLYGON); + this.setActionableState({ + trash: true, + }); + + return { + polygon, + currentVertexPosition: 0, + dragMoving: false, + isDrawing: false, + }; + }; + + FreehandMode.onDrag = FreehandMode.onTouchMove = function (state, e) { + state.dragMoving = true; + state.isDrawing = true; + this.updateUIClasses({ mouse: cursors.ADD }); + state.polygon.updateCoordinate( + `0.${state.currentVertexPosition}`, + e.lngLat.lng, + e.lngLat.lat, + ); + state.currentVertexPosition++; + state.polygon.updateCoordinate( + `0.${state.currentVertexPosition}`, + e.lngLat.lng, + e.lngLat.lat, + ); + }; + + FreehandMode.onMouseUp = function (state) { + if (state.dragMoving) { + this.simplify(state.polygon); + this.updateUIClasses({ mouse: cursors.MOVE }); + this.fireUpdate(); + this.changeMode(modes.SIMPLE_SELECT, { + featureIds: [state.polygon.id], + }); + } + }; + + FreehandMode.fireCreate = function (polygon) { + this.map.fire(events.CREATE, { + features: [polygon.toGeoJSON()], + }); + }; + + FreehandMode.fireUpdate = function () { + this.map.fire(events.UPDATE, { + action: updateActions.MOVE, + features: this.getSelected().map((f) => f.toGeoJSON()), + }); + }; + + FreehandMode.simplify = function (polygon) { + if (!this.map.simplify_freehand) return; + + const tolerance = 1 / Math.pow(1.05, 10 * this.map.getZoom()); + const simplifiedCoords = simplifyGeometry( + polygon.coordinates[0], + tolerance, + ); + polygon.setCoordinates([simplifiedCoords]); + }; + + function simplifyGeometry(points, tolerance) { + if (points.length <= 2) return points; + + const sqTolerance = tolerance * tolerance; + const last = points.length - 1; + const simplified = [points[0]]; + simplifyDPStep(points, 0, last, sqTolerance, simplified); + simplified.push(points[last]); + + return simplified; + } + + function simplifyDPStep(points, first, last, sqTolerance, simplified) { + let maxSqDist = sqTolerance; + let index; + + for (let i = first + 1; i < last; i++) { + const sqDist = getSquareSegmentDistance( + points[i], + points[first], + points[last], + ); + if (sqDist > maxSqDist) { + index = i; + maxSqDist = sqDist; + } + } + + if (maxSqDist > sqTolerance) { + if (index - first > 1) + simplifyDPStep(points, first, index, sqTolerance, simplified); + simplified.push(points[index]); + if (last - index > 1) + simplifyDPStep(points, index, last, sqTolerance, simplified); + } + } + + function getSquareSegmentDistance(p, p1, p2) { + let x = p1[0], + y = p1[1]; + let dx = p2[0] - x, + dy = p2[1] - y; + + if (dx !== 0 || dy !== 0) { + const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy); + if (t > 1) { + x = p2[0]; + y = p2[1]; + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } + + dx = p[0] - x; + dy = p[1] - y; + + return dx * dx + dy * dy; + } + + FreehandMode.onStop = function (state) { + this.updateUIClasses({ mouse: cursors.NONE }); + this.activateUIButton(); + + // Enable map dragging + setTimeout(() => { + if (!this.map || !this.map.dragPan) return; + this.map.dragPan.enable(); + }, 0); + }; + + FreehandMode.toDisplayFeatures = function (state, geojson, display) { + const isActivePolygon = geojson.properties.id === state.polygon.id; + geojson.properties.active = isActivePolygon ? "true" : "false"; + if (!isActivePolygon) return display(geojson); + + // Only render the polygon if it has at least three points + if (geojson.geometry.coordinates[0].length < 3) return; + + const coordinateCount = geojson.geometry.coordinates[0].length; + + // If we have fewer than three coordinates, we need to create a LineString instead of a Polygon + if (coordinateCount < 3) { + const lineCoordinates = [ + [ + geojson.geometry.coordinates[0][0][0], + geojson.geometry.coordinates[0][0][1], + ], + [ + geojson.geometry.coordinates[0][1][0], + geojson.geometry.coordinates[0][1][1], + ], + ]; + return display({ + type: geojsonTypes.FEATURE, + properties: geojson.properties, + geometry: { + coordinates: lineCoordinates, + type: geojsonTypes.LINE_STRING, + }, + }); + } + + return display(geojson); + }; + + FreehandMode.onTrash = function (state) { + this.deleteFeature([state.polygon.id], { silent: true }); + this.changeMode(modes.SIMPLE_SELECT); + }; + + MapboxDraw.modes.draw_freehand = FreehandMode; +})(MapboxDraw); diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js new file mode 100644 index 0000000..16631aa --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js @@ -0,0 +1,3 @@ +!function(A){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=A();else if("function"==typeof define&&define.amd)define([],A);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).h3j_h3t=A()}}((function(){return function A(e,r,t){function i(o,a){if(!r[o]){if(!e[o]){var f="function"==typeof require&&require;if(!a&&f)return f(o,!0);if(n)return n(o,!0);var s=new Error("Cannot find module '"+o+"'");throw s.code="MODULE_NOT_FOUND",s}var u=r[o]={exports:{}};e[o][0].call(u.exports,(function(A){return i(e[o][1][A]||A)}),u,u.exports,A,e,r,t)}return r[o].exports}for(var n="function"==typeof require&&require,o=0;o>3}if(n--,1===i||2===i)o+=A.readSVarint(),a+=A.readSVarint(),1===i&&(e&&f.push(e),e=[]),e.push(new t(o,a));else{if(7!==i)throw new Error("unknown command "+i);e&&e.push(e[0].clone())}}return e&&f.push(e),f},i.prototype.bbox=function(){var A=this._pbf;A.pos=this._geometry;for(var e=A.readVarint()+A.pos,r=1,t=0,i=0,n=0,o=1/0,a=-1/0,f=1/0,s=-1/0;A.pos>3}if(t--,1===r||2===r)(i+=A.readSVarint())a&&(a=i),(n+=A.readSVarint())s&&(s=n);else if(7!==r)throw new Error("unknown command "+r)}return[o,f,a,s]},i.prototype.toGeoJSON=function(A,e,r){var t,n,a=this.extent*Math.pow(2,r),f=this.extent*A,s=this.extent*e,u=this.loadGeometry(),l=i.types[this.type];function h(A){for(var e=0;e>3;e=1===t?A.readString():2===t?A.readFloat():3===t?A.readDouble():4===t?A.readVarint64():5===t?A.readVarint():6===t?A.readSVarint():7===t?A.readBoolean():null}return e}(r))}e.exports=i,i.prototype.feature=function(A){if(A<0||A>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[A];var e=this._pbf.readVarint()+this._pbf.pos;return new t(this._pbf,e,this.extent,this._keys,this._values)}},{"./vectortilefeature.js":4}],6:[function(A,e,r){!function(A,t){"object"==typeof r&&void 0!==e?e.exports=t():A.geojsonvt=t()}(this,(function(){"use strict";function A(r,t,i,n){for(var o,a=n,f=i-t>>1,s=i-t,u=r[t],l=r[t+1],h=r[i],c=r[i+1],d=t+3;da)o=d,a=g;else if(g===a){var w=Math.abs(d-f);wn&&(o-t>3&&A(r,t,o,n),r[o+2]=a,i-o>3&&A(r,o,i,n))}function e(A,e,r,t,i,n){var o=i-r,a=n-t;if(0!==o||0!==a){var f=((A-r)*o+(e-t)*a)/(o*o+a*a);f>1?(r=i,t=n):f>0&&(r+=o*f,t+=a*f)}return(o=A-r)*o+(a=e-t)*a}function r(A,e,r,i){var n={id:void 0===A?null:A,type:e,geometry:r,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(A){var e=A.geometry,r=A.type;if("Point"===r||"MultiPoint"===r||"LineString"===r)t(A,e);else if("Polygon"===r||"MultiLineString"===r)for(var i=0;i0&&(a+=i?(n*h-l*o)/2:Math.sqrt(Math.pow(l-n,2)+Math.pow(h-o,2))),n=l,o=h}var c=r.length-3;r[2]=1,A(r,0,c,t),r[c+2]=1,r.size=Math.abs(a),r.start=0,r.end=r.size}function a(A,e,r,t){for(var i=0;i1?1:r}function u(A,e,t,i,n,o,a,f){if(i/=e,o>=(t/=e)&&a=i)return null;for(var s=[],u=0;u=t&&B=i)){var b=[];if("Point"===w||"MultiPoint"===w)l(g,b,t,i,n);else if("LineString"===w)h(g,b,t,i,n,!1,f.lineMetrics);else if("MultiLineString"===w)d(g,b,t,i,n,!1);else if("Polygon"===w)d(g,b,t,i,n,!0);else if("MultiPolygon"===w)for(var v=0;v=r&&o<=t&&(e.push(A[n]),e.push(A[n+1]),e.push(A[n+2]))}}function h(A,e,r,t,i,n,o){for(var a,f,s=c(A),u=0===i?w:p,l=A.start,h=0;hr&&(f=u(s,d,B,v,m,r),o&&(s.start=l+a*f)):k>t?M=r&&(f=u(s,d,B,v,m,r),Q=!0),M>t&&k<=t&&(f=u(s,d,B,v,m,t),Q=!0),!n&&Q&&(o&&(s.end=l+a*f),e.push(s),s=c(A)),o&&(l+=a)}var y=A.length-3;d=A[y],B=A[y+1],b=A[y+2],(k=0===i?d:B)>=r&&k<=t&&g(s,d,B,b),y=s.length-3,n&&y>=3&&(s[y]!==s[0]||s[y+1]!==s[1])&&g(s,s[0],s[1],s[2]),s.length&&e.push(s)}function c(A){var e=[];return e.size=A.size,e.start=A.start,e.end=A.end,e}function d(A,e,r,t,i,n){for(var o=0;oo.maxX&&(o.maxX=u),l>o.maxY&&(o.maxY=l)}return o}function M(A,e,r,t){var i=e.geometry,n=e.type,o=[];if("Point"===n||"MultiPoint"===n)for(var a=0;a0&&e.size<(i?o:t))r.numPoints+=e.length/3;else{for(var a=[],f=0;fo)&&(r.numSimplified++,a.push(e[f]),a.push(e[f+1])),r.numPoints++;i&&function(A,e){for(var r=0,t=0,i=A.length,n=i-2;t0===e)for(t=0,i=A.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(e.promoteId&&e.generateId)throw new Error("promoteId and generateId cannot be used together.");var t=function(A,e){var r=[];if("FeatureCollection"===A.type)for(var t=0;t1&&console.time("creation"),c=this.tiles[h]=k(A,e,r,t,f),this.tileCoords.push({z:e,x:r,y:t}),s)){s>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,r,t,c.numFeatures,c.numPoints,c.numSimplified),console.timeEnd("creation"));var d="z"+e;this.stats[d]=(this.stats[d]||0)+1,this.total++}if(c.source=A,i){if(e===f.maxZoom||e===i)continue;var g=1<1&&console.time("clipping");var w,p,B,b,v,m,M=.5*f.buffer/f.extent,Q=.5-M,y=.5+M,x=1+M;w=p=B=b=null,v=u(A,l,r-M,r+y,0,c.minX,c.maxX,f),m=u(A,l,r+Q,r+x,0,c.minX,c.maxX,f),A=null,v&&(w=u(v,l,t-M,t+y,1,c.minY,c.maxY,f),p=u(v,l,t+Q,t+x,1,c.minY,c.maxY,f),v=null),m&&(B=u(m,l,t-M,t+y,1,c.minY,c.maxY,f),b=u(m,l,t+Q,t+x,1,c.minY,c.maxY,f),m=null),s>1&&console.timeEnd("clipping"),a.push(w||[],e+1,2*r,2*t),a.push(p||[],e+1,2*r,2*t+1),a.push(B||[],e+1,2*r+1,2*t),a.push(b||[],e+1,2*r+1,2*t+1)}}},y.prototype.getTile=function(A,e,r){var t=this.options,i=t.extent,n=t.debug;if(A<0||A>24)return null;var o=1<1&&console.log("drilling down to z%d-%d-%d",A,e,r);for(var f,s=A,u=e,l=r;!f&&s>0;)s--,u=Math.floor(u/2),l=Math.floor(l/2),f=this.tiles[E(s,u,l)];return f&&f.source?(n>1&&console.log("found parent tile z%d-%d-%d",s,u,l),n>1&&console.time("drilling down"),this.splitTile(f.source,s,u,l,A,e,r),n>1&&console.timeEnd("drilling down"),this.tiles[a]?v(this.tiles[a],i):null):null},function(A,e){return new y(A,e)}}))},{}],7:[function(A,e,r){var t=function(A){var e,r=void 0!==(A=A||{})?A:{},t={};for(e in r)r.hasOwnProperty(e)&&(t[e]=r[e]);var i,n=[],o="";document.currentScript&&(o=document.currentScript.src),o=0!==o.indexOf("blob:")?o.substr(0,o.lastIndexOf("/")+1):"",i=function(A,e,r){var t=new XMLHttpRequest;t.open("GET",A,!0),t.responseType="arraybuffer",t.onload=function(){if(200==t.status||0==t.status&&t.response)e(t.response);else{var i=J(A);i?e(i.buffer):r()}},t.onerror=r,t.send(null)};var a=r.print||console.log.bind(console),f=r.printErr||console.warn.bind(console);for(e in t)t.hasOwnProperty(e)&&(r[e]=t[e]);t=null,r.arguments&&(n=r.arguments);var s=0,u=function(){return s};var l=!1;function h(A){var e,t=r["_"+A];return e="Cannot call unknown function "+A+", make sure it is exported",t||fA("Assertion failed: "+e),t}function c(A,e,r,t,i){var n={string:function(A){var e=0;if(null!=A&&0!==A){var r=1+(A.length<<2);(function(A,e,r){(function(A,e,r,t){if(!(t>0))return 0;for(var i=r,n=r+t-1,o=0;o=55296&&a<=57343)a=65536+((1023&a)<<10)|1023&A.charCodeAt(++o);if(a<=127){if(r>=n)break;e[r++]=a}else if(a<=2047){if(r+1>=n)break;e[r++]=192|a>>6,e[r++]=128|63&a}else if(a<=65535){if(r+2>=n)break;e[r++]=224|a>>12,e[r++]=128|a>>6&63,e[r++]=128|63&a}else{if(r+3>=n)break;e[r++]=240|a>>18,e[r++]=128|a>>12&63,e[r++]=128|a>>6&63,e[r++]=128|63&a}}e[r]=0})(A,B,e,r)})(A,e=AA(r),r)}return e},array:function(A){var e=AA(A.length);return function(A,e){p.set(A,e)}(A,e),e}};var o=h(A),a=[],f=0;if(t)for(var s=0;s=t);)++i;if(i-e>16&&A.subarray&&d)return d.decode(A.subarray(e,i));for(var n="";e>10,56320|1023&s)}}else n+=String.fromCharCode((31&o)<<6|a)}else n+=String.fromCharCode(o)}return n}(B,A,e):""}var w,p,B,b,v,m,k;"undefined"!=typeof TextDecoder&&new TextDecoder("utf-16le");function M(A,e){return A%e>0&&(A+=e-A%e),A}function Q(A){w=A,r.HEAP8=p=new Int8Array(A),r.HEAP16=b=new Int16Array(A),r.HEAP32=v=new Int32Array(A),r.HEAPU8=B=new Uint8Array(A),r.HEAPU16=new Uint16Array(A),r.HEAPU32=new Uint32Array(A),r.HEAPF32=m=new Float32Array(A),r.HEAPF64=k=new Float64Array(A)}var y=r.TOTAL_MEMORY||33554432;function E(A){for(;A.length>0;){var e=A.shift();if("function"!=typeof e){var t=e.func;"number"==typeof t?void 0===e.arg?r.dynCall_v(t):r.dynCall_vi(t,e.arg):t(void 0===e.arg?null:e.arg)}else e()}}y=(w=r.buffer?r.buffer:new ArrayBuffer(y)).byteLength,Q(w),v[6004]=5266928;var x=[],D=[],_=[],I=[];var F=Math.abs,C=Math.ceil,P=Math.floor,U=Math.min,G=0,S=null,T=null;r.preloadedImages={},r.preloadedAudios={};var V,H,R=null,L="data:application/octet-stream;base64,";function z(A){return String.prototype.startsWith?A.startsWith(L):0===A.indexOf(L)}R="data:application/octet-stream;base64,AAAAAAAAAAACAAAAAwAAAAEAAAAFAAAABAAAAAYAAAAAAAAAAAAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAYAAAABAAAABAAAAAMAAAAGAAAABQAAAAIAAAAAAAAAAgAAAAMAAAABAAAABAAAAAYAAAAAAAAABQAAAAMAAAAGAAAABAAAAAUAAAAAAAAAAQAAAAIAAAAEAAAABQAAAAYAAAAAAAAAAgAAAAMAAAABAAAABQAAAAIAAAAAAAAAAQAAAAMAAAAGAAAABAAAAAYAAAAAAAAABQAAAAIAAAABAAAABAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAgAAAAMAAAAAAAAAAAAAAAIAAAAAAAAAAQAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAABgAAAAAAAAAFAAAAAAAAAAAAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAIAAAAAAAAABgAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAgAAAAAAAAAAAAAABgAAAAAAAAADAAAAAgAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAUAAAAEAAAAAAAAAAEAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAEAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAUAAAACAAAABAAAAAMAAAAIAAAAAQAAAAcAAAAGAAAACQAAAAAAAAADAAAAAgAAAAIAAAAGAAAACgAAAAsAAAAAAAAAAQAAAAUAAAADAAAADQAAAAEAAAAHAAAABAAAAAwAAAAAAAAABAAAAH8AAAAPAAAACAAAAAMAAAAAAAAADAAAAAUAAAACAAAAEgAAAAoAAAAIAAAAAAAAABAAAAAGAAAADgAAAAsAAAARAAAAAQAAAAkAAAACAAAABwAAABUAAAAJAAAAEwAAAAMAAAANAAAAAQAAAAgAAAAFAAAAFgAAABAAAAAEAAAAAAAAAA8AAAAJAAAAEwAAAA4AAAAUAAAAAQAAAAcAAAAGAAAACgAAAAsAAAAYAAAAFwAAAAUAAAACAAAAEgAAAAsAAAARAAAAFwAAABkAAAACAAAABgAAAAoAAAAMAAAAHAAAAA0AAAAaAAAABAAAAA8AAAADAAAADQAAABoAAAAVAAAAHQAAAAMAAAAMAAAABwAAAA4AAAB/AAAAEQAAABsAAAAJAAAAFAAAAAYAAAAPAAAAFgAAABwAAAAfAAAABAAAAAgAAAAMAAAAEAAAABIAAAAhAAAAHgAAAAgAAAAFAAAAFgAAABEAAAALAAAADgAAAAYAAAAjAAAAGQAAABsAAAASAAAAGAAAAB4AAAAgAAAABQAAAAoAAAAQAAAAEwAAACIAAAAUAAAAJAAAAAcAAAAVAAAACQAAABQAAAAOAAAAEwAAAAkAAAAoAAAAGwAAACQAAAAVAAAAJgAAABMAAAAiAAAADQAAAB0AAAAHAAAAFgAAABAAAAApAAAAIQAAAA8AAAAIAAAAHwAAABcAAAAYAAAACwAAAAoAAAAnAAAAJQAAABkAAAAYAAAAfwAAACAAAAAlAAAACgAAABcAAAASAAAAGQAAABcAAAARAAAACwAAAC0AAAAnAAAAIwAAABoAAAAqAAAAHQAAACsAAAAMAAAAHAAAAA0AAAAbAAAAKAAAACMAAAAuAAAADgAAABQAAAARAAAAHAAAAB8AAAAqAAAALAAAAAwAAAAPAAAAGgAAAB0AAAArAAAAJgAAAC8AAAANAAAAGgAAABUAAAAeAAAAIAAAADAAAAAyAAAAEAAAABIAAAAhAAAAHwAAACkAAAAsAAAANQAAAA8AAAAWAAAAHAAAACAAAAAeAAAAGAAAABIAAAA0AAAAMgAAACUAAAAhAAAAHgAAADEAAAAwAAAAFgAAABAAAAApAAAAIgAAABMAAAAmAAAAFQAAADYAAAAkAAAAMwAAACMAAAAuAAAALQAAADgAAAARAAAAGwAAABkAAAAkAAAAFAAAACIAAAATAAAANwAAACgAAAA2AAAAJQAAACcAAAA0AAAAOQAAABgAAAAXAAAAIAAAACYAAAB/AAAAIgAAADMAAAAdAAAALwAAABUAAAAnAAAAJQAAABkAAAAXAAAAOwAAADkAAAAtAAAAKAAAABsAAAAkAAAAFAAAADwAAAAuAAAANwAAACkAAAAxAAAANQAAAD0AAAAWAAAAIQAAAB8AAAAqAAAAOgAAACsAAAA+AAAAHAAAACwAAAAaAAAAKwAAAD4AAAAvAAAAQAAAABoAAAAqAAAAHQAAACwAAAA1AAAAOgAAAEEAAAAcAAAAHwAAACoAAAAtAAAAJwAAACMAAAAZAAAAPwAAADsAAAA4AAAALgAAADwAAAA4AAAARAAAABsAAAAoAAAAIwAAAC8AAAAmAAAAKwAAAB0AAABFAAAAMwAAAEAAAAAwAAAAMQAAAB4AAAAhAAAAQwAAAEIAAAAyAAAAMQAAAH8AAAA9AAAAQgAAACEAAAAwAAAAKQAAADIAAAAwAAAAIAAAAB4AAABGAAAAQwAAADQAAAAzAAAARQAAADYAAABHAAAAJgAAAC8AAAAiAAAANAAAADkAAABGAAAASgAAACAAAAAlAAAAMgAAADUAAAA9AAAAQQAAAEsAAAAfAAAAKQAAACwAAAA2AAAARwAAADcAAABJAAAAIgAAADMAAAAkAAAANwAAACgAAAA2AAAAJAAAAEgAAAA8AAAASQAAADgAAABEAAAAPwAAAE0AAAAjAAAALgAAAC0AAAA5AAAAOwAAAEoAAABOAAAAJQAAACcAAAA0AAAAOgAAAH8AAAA+AAAATAAAACwAAABBAAAAKgAAADsAAAA/AAAATgAAAE8AAAAnAAAALQAAADkAAAA8AAAASAAAAEQAAABQAAAAKAAAADcAAAAuAAAAPQAAADUAAAAxAAAAKQAAAFEAAABLAAAAQgAAAD4AAAArAAAAOgAAACoAAABSAAAAQAAAAEwAAAA/AAAAfwAAADgAAAAtAAAATwAAADsAAABNAAAAQAAAAC8AAAA+AAAAKwAAAFQAAABFAAAAUgAAAEEAAAA6AAAANQAAACwAAABWAAAATAAAAEsAAABCAAAAQwAAAFEAAABVAAAAMQAAADAAAAA9AAAAQwAAAEIAAAAyAAAAMAAAAFcAAABVAAAARgAAAEQAAAA4AAAAPAAAAC4AAABaAAAATQAAAFAAAABFAAAAMwAAAEAAAAAvAAAAWQAAAEcAAABUAAAARgAAAEMAAAA0AAAAMgAAAFMAAABXAAAASgAAAEcAAABZAAAASQAAAFsAAAAzAAAARQAAADYAAABIAAAAfwAAAEkAAAA3AAAAUAAAADwAAABYAAAASQAAAFsAAABIAAAAWAAAADYAAABHAAAANwAAAEoAAABOAAAAUwAAAFwAAAA0AAAAOQAAAEYAAABLAAAAQQAAAD0AAAA1AAAAXgAAAFYAAABRAAAATAAAAFYAAABSAAAAYAAAADoAAABBAAAAPgAAAE0AAAA/AAAARAAAADgAAABdAAAATwAAAFoAAABOAAAASgAAADsAAAA5AAAAXwAAAFwAAABPAAAATwAAAE4AAAA/AAAAOwAAAF0AAABfAAAATQAAAFAAAABEAAAASAAAADwAAABjAAAAWgAAAFgAAABRAAAAVQAAAF4AAABlAAAAPQAAAEIAAABLAAAAUgAAAGAAAABUAAAAYgAAAD4AAABMAAAAQAAAAFMAAAB/AAAASgAAAEYAAABkAAAAVwAAAFwAAABUAAAARQAAAFIAAABAAAAAYQAAAFkAAABiAAAAVQAAAFcAAABlAAAAZgAAAEIAAABDAAAAUQAAAFYAAABMAAAASwAAAEEAAABoAAAAYAAAAF4AAABXAAAAUwAAAGYAAABkAAAAQwAAAEYAAABVAAAAWAAAAEgAAABbAAAASQAAAGMAAABQAAAAaQAAAFkAAABhAAAAWwAAAGcAAABFAAAAVAAAAEcAAABaAAAATQAAAFAAAABEAAAAagAAAF0AAABjAAAAWwAAAEkAAABZAAAARwAAAGkAAABYAAAAZwAAAFwAAABTAAAATgAAAEoAAABsAAAAZAAAAF8AAABdAAAATwAAAFoAAABNAAAAbQAAAF8AAABqAAAAXgAAAFYAAABRAAAASwAAAGsAAABoAAAAZQAAAF8AAABcAAAATwAAAE4AAABtAAAAbAAAAF0AAABgAAAAaAAAAGIAAABuAAAATAAAAFYAAABSAAAAYQAAAH8AAABiAAAAVAAAAGcAAABZAAAAbwAAAGIAAABuAAAAYQAAAG8AAABSAAAAYAAAAFQAAABjAAAAUAAAAGkAAABYAAAAagAAAFoAAABxAAAAZAAAAGYAAABTAAAAVwAAAGwAAAByAAAAXAAAAGUAAABmAAAAawAAAHAAAABRAAAAVQAAAF4AAABmAAAAZQAAAFcAAABVAAAAcgAAAHAAAABkAAAAZwAAAFsAAABhAAAAWQAAAHQAAABpAAAAbwAAAGgAAABrAAAAbgAAAHMAAABWAAAAXgAAAGAAAABpAAAAWAAAAGcAAABbAAAAcQAAAGMAAAB0AAAAagAAAF0AAABjAAAAWgAAAHUAAABtAAAAcQAAAGsAAAB/AAAAZQAAAF4AAABzAAAAaAAAAHAAAABsAAAAZAAAAF8AAABcAAAAdgAAAHIAAABtAAAAbQAAAGwAAABdAAAAXwAAAHUAAAB2AAAAagAAAG4AAABiAAAAaAAAAGAAAAB3AAAAbwAAAHMAAABvAAAAYQAAAG4AAABiAAAAdAAAAGcAAAB3AAAAcAAAAGsAAABmAAAAZQAAAHgAAABzAAAAcgAAAHEAAABjAAAAdAAAAGkAAAB1AAAAagAAAHkAAAByAAAAcAAAAGQAAABmAAAAdgAAAHgAAABsAAAAcwAAAG4AAABrAAAAaAAAAHgAAAB3AAAAcAAAAHQAAABnAAAAdwAAAG8AAABxAAAAaQAAAHkAAAB1AAAAfwAAAG0AAAB2AAAAcQAAAHkAAABqAAAAdgAAAHgAAABsAAAAcgAAAHUAAAB5AAAAbQAAAHcAAABvAAAAcwAAAG4AAAB5AAAAdAAAAHgAAAB4AAAAcwAAAHIAAABwAAAAeQAAAHcAAAB2AAAAeQAAAHQAAAB4AAAAdwAAAHUAAABxAAAAdgAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAEAAAAFAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAIAAAAFAAAAAQAAAAAAAAD/////AQAAAAAAAAADAAAABAAAAAIAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAUAAAABAAAAAAAAAAAAAAABAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAAFAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAQAAAAFAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAADAAAAAAAAAAAAAAABAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAABAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAADAAAABQAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAADAAAAAAAAAAAAAAABAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAADAAAAAQAAAAAAAAABAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAMAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAADAAAABQAAAAEAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAEAAAABQAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAgAAAAUAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAABQAAAAAAAAAAAAAABQAAAAUAAAAAAAAAAAAAAP////8BAAAAAAAAAAMAAAAEAAAAAgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAABQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAABQAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAQAAAP//////////AQAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAIAAAAAAAAAAAAAAAEAAAACAAAABgAAAAQAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAABwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAoAAAACAAAAAAAAAAAAAAABAAAAAQAAAAUAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAsAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAIAAAAAAAAAAAAAAAEAAAADAAAABwAAAAYAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAHAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAABAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAOAAAAAgAAAAAAAAAAAAAAAQAAAAAAAAAJAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAwAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAgAAAAAAAAAAAAAAAQAAAAQAAAAIAAAACgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAsAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAACAAAAAAAAAAAAAAABAAAACwAAAA8AAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA4AAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAgAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAFAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAACAAAAAAAAAAAAAAABAAAADAAAABAAAAAMAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAEAAAAKAAAAEwAAAAgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAADwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAJAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAgAAAAAAAAAAAAAAAQAAAA0AAAARAAAADQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAABEAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAADQAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAIAAAAAAAAAAAAAAAEAAAAOAAAAEgAAAA8AAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAPAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAABIAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAEQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABMAAAACAAAAAAAAAAAAAAABAAAA//////////8TAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAASAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABIAAAAAAAAAGAAAAAAAAAAhAAAAAAAAAB4AAAAAAAAAIAAAAAMAAAAxAAAAAQAAADAAAAADAAAAMgAAAAMAAAAIAAAAAAAAAAUAAAAFAAAACgAAAAUAAAAWAAAAAAAAABAAAAAAAAAAEgAAAAAAAAApAAAAAQAAACEAAAAAAAAAHgAAAAAAAAAEAAAAAAAAAAAAAAAFAAAAAgAAAAUAAAAPAAAAAQAAAAgAAAAAAAAABQAAAAUAAAAfAAAAAQAAABYAAAAAAAAAEAAAAAAAAAACAAAAAAAAAAYAAAAAAAAADgAAAAAAAAAKAAAAAAAAAAsAAAAAAAAAEQAAAAMAAAAYAAAAAQAAABcAAAADAAAAGQAAAAMAAAAAAAAAAAAAAAEAAAAFAAAACQAAAAUAAAAFAAAAAAAAAAIAAAAAAAAABgAAAAAAAAASAAAAAQAAAAoAAAAAAAAACwAAAAAAAAAEAAAAAQAAAAMAAAAFAAAABwAAAAUAAAAIAAAAAQAAAAAAAAAAAAAAAQAAAAUAAAAQAAAAAQAAAAUAAAAAAAAAAgAAAAAAAAAHAAAAAAAAABUAAAAAAAAAJgAAAAAAAAAJAAAAAAAAABMAAAAAAAAAIgAAAAMAAAAOAAAAAQAAABQAAAADAAAAJAAAAAMAAAADAAAAAAAAAA0AAAAFAAAAHQAAAAUAAAABAAAAAAAAAAcAAAAAAAAAFQAAAAAAAAAGAAAAAQAAAAkAAAAAAAAAEwAAAAAAAAAEAAAAAgAAAAwAAAAFAAAAGgAAAAUAAAAAAAAAAQAAAAMAAAAAAAAADQAAAAUAAAACAAAAAQAAAAEAAAAAAAAABwAAAAAAAAAaAAAAAAAAACoAAAAAAAAAOgAAAAAAAAAdAAAAAAAAACsAAAAAAAAAPgAAAAMAAAAmAAAAAQAAAC8AAAADAAAAQAAAAAMAAAAMAAAAAAAAABwAAAAFAAAALAAAAAUAAAANAAAAAAAAABoAAAAAAAAAKgAAAAAAAAAVAAAAAQAAAB0AAAAAAAAAKwAAAAAAAAAEAAAAAwAAAA8AAAAFAAAAHwAAAAUAAAADAAAAAQAAAAwAAAAAAAAAHAAAAAUAAAAHAAAAAQAAAA0AAAAAAAAAGgAAAAAAAAAfAAAAAAAAACkAAAAAAAAAMQAAAAAAAAAsAAAAAAAAADUAAAAAAAAAPQAAAAMAAAA6AAAAAQAAAEEAAAADAAAASwAAAAMAAAAPAAAAAAAAABYAAAAFAAAAIQAAAAUAAAAcAAAAAAAAAB8AAAAAAAAAKQAAAAAAAAAqAAAAAQAAACwAAAAAAAAANQAAAAAAAAAEAAAABAAAAAgAAAAFAAAAEAAAAAUAAAAMAAAAAQAAAA8AAAAAAAAAFgAAAAUAAAAaAAAAAQAAABwAAAAAAAAAHwAAAAAAAAAyAAAAAAAAADAAAAAAAAAAMQAAAAMAAAAgAAAAAAAAAB4AAAADAAAAIQAAAAMAAAAYAAAAAwAAABIAAAADAAAAEAAAAAMAAABGAAAAAAAAAEMAAAAAAAAAQgAAAAMAAAA0AAAAAwAAADIAAAAAAAAAMAAAAAAAAAAlAAAAAwAAACAAAAAAAAAAHgAAAAMAAABTAAAAAAAAAFcAAAADAAAAVQAAAAMAAABKAAAAAwAAAEYAAAAAAAAAQwAAAAAAAAA5AAAAAQAAADQAAAADAAAAMgAAAAAAAAAZAAAAAAAAABcAAAAAAAAAGAAAAAMAAAARAAAAAAAAAAsAAAADAAAACgAAAAMAAAAOAAAAAwAAAAYAAAADAAAAAgAAAAMAAAAtAAAAAAAAACcAAAAAAAAAJQAAAAMAAAAjAAAAAwAAABkAAAAAAAAAFwAAAAAAAAAbAAAAAwAAABEAAAAAAAAACwAAAAMAAAA/AAAAAAAAADsAAAADAAAAOQAAAAMAAAA4AAAAAwAAAC0AAAAAAAAAJwAAAAAAAAAuAAAAAwAAACMAAAADAAAAGQAAAAAAAAAkAAAAAAAAABQAAAAAAAAADgAAAAMAAAAiAAAAAAAAABMAAAADAAAACQAAAAMAAAAmAAAAAwAAABUAAAADAAAABwAAAAMAAAA3AAAAAAAAACgAAAAAAAAAGwAAAAMAAAA2AAAAAwAAACQAAAAAAAAAFAAAAAAAAAAzAAAAAwAAACIAAAAAAAAAEwAAAAMAAABIAAAAAAAAADwAAAADAAAALgAAAAMAAABJAAAAAwAAADcAAAAAAAAAKAAAAAAAAABHAAAAAwAAADYAAAADAAAAJAAAAAAAAABAAAAAAAAAAC8AAAAAAAAAJgAAAAMAAAA+AAAAAAAAACsAAAADAAAAHQAAAAMAAAA6AAAAAwAAACoAAAADAAAAGgAAAAMAAABUAAAAAAAAAEUAAAAAAAAAMwAAAAMAAABSAAAAAwAAAEAAAAAAAAAALwAAAAAAAABMAAAAAwAAAD4AAAAAAAAAKwAAAAMAAABhAAAAAAAAAFkAAAADAAAARwAAAAMAAABiAAAAAwAAAFQAAAAAAAAARQAAAAAAAABgAAAAAwAAAFIAAAADAAAAQAAAAAAAAABLAAAAAAAAAEEAAAAAAAAAOgAAAAMAAAA9AAAAAAAAADUAAAADAAAALAAAAAMAAAAxAAAAAwAAACkAAAADAAAAHwAAAAMAAABeAAAAAAAAAFYAAAAAAAAATAAAAAMAAABRAAAAAwAAAEsAAAAAAAAAQQAAAAAAAABCAAAAAwAAAD0AAAAAAAAANQAAAAMAAABrAAAAAAAAAGgAAAADAAAAYAAAAAMAAABlAAAAAwAAAF4AAAAAAAAAVgAAAAAAAABVAAAAAwAAAFEAAAADAAAASwAAAAAAAAA5AAAAAAAAADsAAAAAAAAAPwAAAAMAAABKAAAAAAAAAE4AAAADAAAATwAAAAMAAABTAAAAAwAAAFwAAAADAAAAXwAAAAMAAAAlAAAAAAAAACcAAAADAAAALQAAAAMAAAA0AAAAAAAAADkAAAAAAAAAOwAAAAAAAABGAAAAAwAAAEoAAAAAAAAATgAAAAMAAAAYAAAAAAAAABcAAAADAAAAGQAAAAMAAAAgAAAAAwAAACUAAAAAAAAAJwAAAAMAAAAyAAAAAwAAADQAAAAAAAAAOQAAAAAAAAAuAAAAAAAAADwAAAAAAAAASAAAAAMAAAA4AAAAAAAAAEQAAAADAAAAUAAAAAMAAAA/AAAAAwAAAE0AAAADAAAAWgAAAAMAAAAbAAAAAAAAACgAAAADAAAANwAAAAMAAAAjAAAAAAAAAC4AAAAAAAAAPAAAAAAAAAAtAAAAAwAAADgAAAAAAAAARAAAAAMAAAAOAAAAAAAAABQAAAADAAAAJAAAAAMAAAARAAAAAwAAABsAAAAAAAAAKAAAAAMAAAAZAAAAAwAAACMAAAAAAAAALgAAAAAAAABHAAAAAAAAAFkAAAAAAAAAYQAAAAMAAABJAAAAAAAAAFsAAAADAAAAZwAAAAMAAABIAAAAAwAAAFgAAAADAAAAaQAAAAMAAAAzAAAAAAAAAEUAAAADAAAAVAAAAAMAAAA2AAAAAAAAAEcAAAAAAAAAWQAAAAAAAAA3AAAAAwAAAEkAAAAAAAAAWwAAAAMAAAAmAAAAAAAAAC8AAAADAAAAQAAAAAMAAAAiAAAAAwAAADMAAAAAAAAARQAAAAMAAAAkAAAAAwAAADYAAAAAAAAARwAAAAAAAABgAAAAAAAAAGgAAAAAAAAAawAAAAMAAABiAAAAAAAAAG4AAAADAAAAcwAAAAMAAABhAAAAAwAAAG8AAAADAAAAdwAAAAMAAABMAAAAAAAAAFYAAAADAAAAXgAAAAMAAABSAAAAAAAAAGAAAAAAAAAAaAAAAAAAAABUAAAAAwAAAGIAAAAAAAAAbgAAAAMAAAA6AAAAAAAAAEEAAAADAAAASwAAAAMAAAA+AAAAAwAAAEwAAAAAAAAAVgAAAAMAAABAAAAAAwAAAFIAAAAAAAAAYAAAAAAAAABVAAAAAAAAAFcAAAAAAAAAUwAAAAMAAABlAAAAAAAAAGYAAAADAAAAZAAAAAMAAABrAAAAAwAAAHAAAAADAAAAcgAAAAMAAABCAAAAAAAAAEMAAAADAAAARgAAAAMAAABRAAAAAAAAAFUAAAAAAAAAVwAAAAAAAABeAAAAAwAAAGUAAAAAAAAAZgAAAAMAAAAxAAAAAAAAADAAAAADAAAAMgAAAAMAAAA9AAAAAwAAAEIAAAAAAAAAQwAAAAMAAABLAAAAAwAAAFEAAAAAAAAAVQAAAAAAAABfAAAAAAAAAFwAAAAAAAAAUwAAAAAAAABPAAAAAAAAAE4AAAAAAAAASgAAAAMAAAA/AAAAAQAAADsAAAADAAAAOQAAAAMAAABtAAAAAAAAAGwAAAAAAAAAZAAAAAUAAABdAAAAAQAAAF8AAAAAAAAAXAAAAAAAAABNAAAAAQAAAE8AAAAAAAAATgAAAAAAAAB1AAAABAAAAHYAAAAFAAAAcgAAAAUAAABqAAAAAQAAAG0AAAAAAAAAbAAAAAAAAABaAAAAAQAAAF0AAAABAAAAXwAAAAAAAABaAAAAAAAAAE0AAAAAAAAAPwAAAAAAAABQAAAAAAAAAEQAAAAAAAAAOAAAAAMAAABIAAAAAQAAADwAAAADAAAALgAAAAMAAABqAAAAAAAAAF0AAAAAAAAATwAAAAUAAABjAAAAAQAAAFoAAAAAAAAATQAAAAAAAABYAAAAAQAAAFAAAAAAAAAARAAAAAAAAAB1AAAAAwAAAG0AAAAFAAAAXwAAAAUAAABxAAAAAQAAAGoAAAAAAAAAXQAAAAAAAABpAAAAAQAAAGMAAAABAAAAWgAAAAAAAABpAAAAAAAAAFgAAAAAAAAASAAAAAAAAABnAAAAAAAAAFsAAAAAAAAASQAAAAMAAABhAAAAAQAAAFkAAAADAAAARwAAAAMAAABxAAAAAAAAAGMAAAAAAAAAUAAAAAUAAAB0AAAAAQAAAGkAAAAAAAAAWAAAAAAAAABvAAAAAQAAAGcAAAAAAAAAWwAAAAAAAAB1AAAAAgAAAGoAAAAFAAAAWgAAAAUAAAB5AAAAAQAAAHEAAAAAAAAAYwAAAAAAAAB3AAAAAQAAAHQAAAABAAAAaQAAAAAAAAB3AAAAAAAAAG8AAAAAAAAAYQAAAAAAAABzAAAAAAAAAG4AAAAAAAAAYgAAAAMAAABrAAAAAQAAAGgAAAADAAAAYAAAAAMAAAB5AAAAAAAAAHQAAAAAAAAAZwAAAAUAAAB4AAAAAQAAAHcAAAAAAAAAbwAAAAAAAABwAAAAAQAAAHMAAAAAAAAAbgAAAAAAAAB1AAAAAQAAAHEAAAAFAAAAaQAAAAUAAAB2AAAAAQAAAHkAAAAAAAAAdAAAAAAAAAByAAAAAQAAAHgAAAABAAAAdwAAAAAAAAByAAAAAAAAAHAAAAAAAAAAawAAAAAAAABkAAAAAAAAAGYAAAAAAAAAZQAAAAMAAABTAAAAAQAAAFcAAAADAAAAVQAAAAMAAAB2AAAAAAAAAHgAAAAAAAAAcwAAAAUAAABsAAAAAQAAAHIAAAAAAAAAcAAAAAAAAABcAAAAAQAAAGQAAAAAAAAAZgAAAAAAAAB1AAAAAAAAAHkAAAAFAAAAdwAAAAUAAABtAAAAAQAAAHYAAAAAAAAAeAAAAAAAAABfAAAAAQAAAGwAAAABAAAAcgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAEAAAABAAAAAAAAAAAAAAABAAAAAAAAAAEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAB+ogX28rbpPxqumpJv+fM/165tC4ns9D+XaEnTqUsEQFrOtNlC4PA/3U+0XG6P9b9TdUUBxTTjP4PUp8ex1ty/B1rD/EN43z+lcDi6LLrZP/a45NWEHMY/oJ5ijLDZ+j/xw3rjxWPjP2B8A46ioQdAotff3wla2z+FMSpA1jj+v6b5Y1mtPbS/cIu8K0F457/2esiyJpDNv98k5Ts2NeA/pvljWa09tD88ClUJ60MDQPZ6yLImkM0/4ONKxa0UBcD2uOTVhBzGv5G7JRxGave/8cN648Vj47+HCwtkjAXIv6LX398JWtu/qyheaCAL9D9TdUUBxTTjv4gyTxslhwVAB1rD/EN4378EH/28teoFwH6iBfbytum/F6ztFYdK/r/Xrm0Liez0vwcS6wNGWeO/Ws602ULg8L9TCtRLiLT8P8pi5RexJsw/BlIKPVwR5T95Wyu0/QjnP5PjoT7YYcu/mBhKZ6zrwj8wRYS7NebuP3qW6geh+Ls/SLrixebL3r+pcyymN9XrPwmkNHp7xec/GWNMZVAA17+82s+x2BLiPwn2ytbJ9ek/LgEH1sMS1j8yp/2LhTfeP+SnWwtQBbu/d38gkp5X7z8ytsuHaADGPzUYObdf1+m/7IauECWhwz+cjSACjzniP76Z+wUhN9K/1+GEKzup67+/GYr/04baPw6idWOvsuc/ZedTWsRa5b/EJQOuRzi0v/OncYhHPes/h49PixY53j+i8wWfC03Nvw2idWOvsue/ZedTWsRa5T/EJQOuRzi0P/KncYhHPeu/iY9PixY53r+i8wWfC03NP9anWwtQBbs/d38gkp5X778ytsuHaADGvzUYObdf1+k/74auECWhw7+cjSACjzniv8CZ+wUhN9I/1uGEKzup6z+/GYr/04bavwmkNHp7xee/F2NMZVAA1z+82s+x2BLivwr2ytbJ9em/KwEH1sMS1r8yp/2LhTfev81i5RexJsy/BlIKPVwR5b95Wyu0/Qjnv5DjoT7YYcs/nBhKZ6zrwr8wRYS7Nebuv3OW6geh+Lu/SLrixebL3j+pcyymN9Xrv8rHIFfWehZAMBwUdlo0DECTUc17EOb2PxpVB1SWChdAzjbhb9pTDUDQhmdvECX5P9FlMKCC9+g/IIAzjELgE0DajDngMv8GQFhWDmDPjNs/y1guLh96EkAxPi8k7DIEQJCc4URlhRhA3eLKKLwkEECqpNAyTBD/P6xpjXcDiwVAFtl//cQm4z+Ibt3XKiYTQM7mCLUb3QdAoM1t8yVv7D8aLZv2Nk8UQEAJPV5nQwxAtSsfTCoE9z9TPjXLXIIWQBVanC5W9AtAYM3d7Adm9j++5mQz1FoWQBUThyaVBghAwH5muQsV7T89Q1qv82MUQJoWGOfNuBdAzrkClkmwDkDQjKq77t37Py+g0dtitsE/ZwAMTwVPEUBojepluNwBQGYbtuW+t9w/HNWIJs6MEkDTNuQUSlgEQKxktPP5TcQ/ixbLB8JjEUCwuWjXMQYCQAS/R09FkRdAowpiZjhhDkB7LmlczD/7P01iQmhhsAVAnrtTwDy84z/Z6jfQ2TgTQChOCXMnWwpAhrW3daoz8z/HYJvVPI4VQLT3ik5FcA5Angi7LOZd+z+NNVzDy5gXQBXdvVTFUA1AYNMgOeYe+T8+qHXGCwkXQKQTOKwa5AJA8gFVoEMW0T+FwzJyttIRQAEAAAD/////BwAAAP////8xAAAA/////1cBAAD/////YQkAAP////+nQQAA/////5HLAQD/////95AMAP/////B9lcAAAAAAAAAAAAAAAAAAgAAAP////8OAAAA/////2IAAAD/////rgIAAP/////CEgAA/////06DAAD/////IpcDAP/////uIRkA/////4LtrwAAAAAAAAAAAAAAAAAAAAAAAgAAAP//////////AQAAAAMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////wIAAAD//////////wEAAAAAAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA/////////////////////wEAAAD///////////////8CAAAA////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD///////////////////////////////8CAAAA////////////////AQAAAP////////////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAAAQAAAP//////////AgAAAP//////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAAEAAAD//////////wIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAgAAAAAAAAACAAAAAQAAAAEAAAACAAAAAgAAAAAAAAAFAAAABQAAAAAAAAACAAAAAgAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAABAAAAAgAAAAIAAAACAAAAAAAAAAUAAAAGAAAAAAAAAAIAAAACAAAAAwAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAIAAAAAAAAAAgAAAAEAAAADAAAAAgAAAAIAAAAAAAAABQAAAAcAAAAAAAAAAgAAAAIAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAgAAAAAAAAACAAAAAQAAAAQAAAACAAAAAgAAAAAAAAAFAAAACAAAAAAAAAACAAAAAgAAAAMAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAACAAAAAAAAAAIAAAABAAAAAAAAAAIAAAACAAAAAAAAAAUAAAAJAAAAAAAAAAIAAAACAAAAAwAAAAUAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAIAAAACAAAAAAAAAAMAAAAOAAAAAgAAAAAAAAACAAAAAwAAAAAAAAAAAAAAAgAAAAIAAAADAAAABgAAAAAAAAAAAAAAAAAAAAAAAAALAAAAAgAAAAIAAAAAAAAAAwAAAAoAAAACAAAAAAAAAAIAAAADAAAAAQAAAAAAAAACAAAAAgAAAAMAAAAHAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAACAAAAAgAAAAAAAAADAAAACwAAAAIAAAAAAAAAAgAAAAMAAAACAAAAAAAAAAIAAAACAAAAAwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADQAAAAIAAAACAAAAAAAAAAMAAAAMAAAAAgAAAAAAAAACAAAAAwAAAAMAAAAAAAAAAgAAAAIAAAADAAAACQAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAgAAAAIAAAAAAAAAAwAAAA0AAAACAAAAAAAAAAIAAAADAAAABAAAAAAAAAACAAAAAgAAAAMAAAAKAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAACAAAAAgAAAAAAAAADAAAABgAAAAIAAAAAAAAAAgAAAAMAAAAPAAAAAAAAAAIAAAACAAAAAwAAAAsAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAIAAAACAAAAAAAAAAMAAAAHAAAAAgAAAAAAAAACAAAAAwAAABAAAAAAAAAAAgAAAAIAAAADAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAgAAAAIAAAAAAAAAAwAAAAgAAAACAAAAAAAAAAIAAAADAAAAEQAAAAAAAAACAAAAAgAAAAMAAAANAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAACAAAAAgAAAAAAAAADAAAACQAAAAIAAAAAAAAAAgAAAAMAAAASAAAAAAAAAAIAAAACAAAAAwAAAA4AAAAAAAAAAAAAAAAAAAAAAAAACQAAAAIAAAACAAAAAAAAAAMAAAAFAAAAAgAAAAAAAAACAAAAAwAAABMAAAAAAAAAAgAAAAIAAAADAAAADwAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAgAAAAAAAAACAAAAAQAAABMAAAACAAAAAgAAAAAAAAAFAAAACgAAAAAAAAACAAAAAgAAAAMAAAAQAAAAAAAAAAAAAAAAAAAAAAAAABEAAAACAAAAAAAAAAIAAAABAAAADwAAAAIAAAACAAAAAAAAAAUAAAALAAAAAAAAAAIAAAACAAAAAwAAABEAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAIAAAAAAAAAAgAAAAEAAAAQAAAAAgAAAAIAAAAAAAAABQAAAAwAAAAAAAAAAgAAAAIAAAADAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAATAAAAAgAAAAAAAAACAAAAAQAAABEAAAACAAAAAgAAAAAAAAAFAAAADQAAAAAAAAACAAAAAgAAAAMAAAATAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAACAAAAAAAAAAIAAAABAAAAEgAAAAIAAAACAAAAAAAAAAUAAAAOAAAAAAAAAAIAAAACAAAAAwAAAAIAAAABAAAAAAAAAAEAAAACAAAAAAAAAAAAAAACAAAAAQAAAAAAAAABAAAAAgAAAAEAAAAAAAAAAgAAAAAAAAAFAAAABAAAAAAAAAABAAAABQAAAAAAAAAAAAAABQAAAAQAAAAAAAAAAQAAAAUAAAAEAAAAAAAAAAUAAAAAAAAAAgAAAAEAAAAAAAAAAQAAAAIAAAAAAAAAAAAAAAIAAAABAAAAAAAAAAEAAAACAAAAAQAAAAAAAAACAAAAAgAAAAAAAAABAAAAAAAAAAAAAAAFAAAABAAAAAAAAAABAAAABQAAAAAAAAAAAAAABQAAAAQAAAAAAAAAAQAAAAUAAAAEAAAAAAAAAAUAAAAFAAAAAAAAAAEAAAAAAAAAAAAAAMuhRbbsNlBBYqHW9OmHIkF9XBuqnS31QAK37uYhNMhAOSo3UUupm0DC+6pc6JxvQHV9eseEEEJAzURsCyqlFEB8BQ4NMJjnPyy3tBoS97o/xawXQznRjj89J2K2CZxhP6vX43RIIDQ/S8isgygEBz+LvFHQkmzaPjFFFO7wMq4+AADMLkTtjkIAAOgkJqxhQgAAU7B0MjRCAADwpBcVB0IAAACYP2HaQQAAAIn/Ja5BzczM4Eg6gUHNzMxMU7BTQTMzMzNfgCZBAAAAAEi3+UAAAAAAwGPNQDMzMzMzy6BAmpmZmZkxc0AzMzMzM/NFQDMzMzMzMxlAzczMzMzM7D+ygXSx2U6RQKimJOvQKnpA23hmONTHY0A/AGcxyudNQNb3K647mzZA+S56rrwWIUAm4kUQ+9UJQKre9hGzh/M/BLvoy9WG3T+LmqMf8VHGP2m3nYNV37A/gbFHcyeCmT+cBPWBckiDP61tZACjKW0/q2RbYVUYVj8uDypVyLNAP6jGS5cA5zBBwcqhBdCNGUEGEhQ/JVEDQT6WPnRbNO1AB/AWSJgT1kDfUWNCNLDAQNk+5C33OqlAchWL34QSk0DKvtDIrNV8QNF0G3kFzGVASSeWhBl6UED+/0mNGuk4QGjA/dm/1CJALPLPMql6DEDSHoDrwpP1P2jouzWST+A/egAAAAAAAABKAwAAAAAAAPoWAAAAAAAAyqAAAAAAAAB6ZQQAAAAAAErGHgAAAAAA+mvXAAAAAADK8+MFAAAAAHqqOykAAAAASqmhIAEAAAD6oGvkBwAAAMpm8T43AAAAes+ZuIIBAABKrDQMkwoAAPq1cFUFSgAAyvkUViUGAgAAAAAAAwAAAAYAAAACAAAABQAAAAEAAAAEAAAAAAAAAAAAAAAFAAAAAwAAAAEAAAAGAAAABAAAAAIAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAP////////////////////////////////////8AAAAA/////wAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAP////8AAAAAAAAAAAEAAAABAAAAAAAAAAAAAAD/////AAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAA/////wUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////AAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////////////////////////////wAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAUAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////////////////////////////8AAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAABAAAAAAAAAAAAAAABAAAAAQAAAAEAAAAAAAAAAQAAAAAAAAAFAAAAAQAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAAAAAABAAEAAAEBAAAAAAABAAAAAQAAAAEAAQAAAAAAAAAAAAAAAAAAAAAEAAAABAAAAAAAAAACAAAAAQAAAAMAAAAOAAAABgAAAAsAAAACAAAABwAAAAEAAAAYAAAABQAAAAoAAAABAAAABgAAAAAAAAAmAAAABwAAAAwAAAADAAAACAAAAAIAAAAxAAAACQAAAA4AAAAAAAAABQAAAAQAAAA6AAAACAAAAA0AAAAEAAAACQAAAAMAAAA/AAAACwAAAAYAAAAPAAAACgAAABAAAABIAAAADAAAAAcAAAAQAAAACwAAABEAAABTAAAACgAAAAUAAAATAAAADgAAAA8AAABhAAAADQAAAAgAAAARAAAADAAAABIAAABrAAAADgAAAAkAAAASAAAADQAAABMAAAB1AAAADwAAABMAAAARAAAAEgAAABAAAAAHAAAABwAAAAEAAAACAAAABAAAAAMAAAAAAAAAAAAAAAcAAAADAAAAAQAAAAIAAAAFAAAABAAAAAAAAAAAAAAAYWxnb3MuYwBfcG9seWZpbGxJbnRlcm5hbABhZGphY2VudEZhY2VEaXJbdG1wRmlqay5mYWNlXVtmaWprLmZhY2VdID09IEtJAGZhY2VpamsuYwBfZmFjZUlqa1BlbnRUb0dlb0JvdW5kYXJ5AGFkamFjZW50RmFjZURpcltjZW50ZXJJSksuZmFjZV1bZmFjZTJdID09IEtJAF9mYWNlSWprVG9HZW9Cb3VuZGFyeQBwb2x5Z29uLT5uZXh0ID09IE5VTEwAbGlua2VkR2VvLmMAYWRkTmV3TGlua2VkUG9seWdvbgBuZXh0ICE9IE5VTEwAbG9vcCAhPSBOVUxMAGFkZE5ld0xpbmtlZExvb3AAcG9seWdvbi0+Zmlyc3QgPT0gTlVMTABhZGRMaW5rZWRMb29wAGNvb3JkICE9IE5VTEwAYWRkTGlua2VkQ29vcmQAbG9vcC0+Zmlyc3QgPT0gTlVMTABpbm5lckxvb3BzICE9IE5VTEwAbm9ybWFsaXplTXVsdGlQb2x5Z29uAGJib3hlcyAhPSBOVUxMAGNhbmRpZGF0ZXMgIT0gTlVMTABmaW5kUG9seWdvbkZvckhvbGUAY2FuZGlkYXRlQkJveGVzICE9IE5VTEwAcmV2RGlyICE9IElOVkFMSURfRElHSVQAbG9jYWxpai5jAGgzVG9Mb2NhbElqawBiYXNlQ2VsbCAhPSBvcmlnaW5CYXNlQ2VsbAAhKG9yaWdpbk9uUGVudCAmJiBpbmRleE9uUGVudCkAcGVudGFnb25Sb3RhdGlvbnMgPj0gMABkaXJlY3Rpb25Sb3RhdGlvbnMgPj0gMABiYXNlQ2VsbCA9PSBvcmlnaW5CYXNlQ2VsbABiYXNlQ2VsbCAhPSBJTlZBTElEX0JBU0VfQ0VMTABsb2NhbElqa1RvSDMAIV9pc0Jhc2VDZWxsUGVudGFnb24oYmFzZUNlbGwpAGJhc2VDZWxsUm90YXRpb25zID49IDAAd2l0aGluUGVudGFnb25Sb3RhdGlvbnMgPj0gMABncmFwaC0+YnVja2V0cyAhPSBOVUxMAHZlcnRleEdyYXBoLmMAaW5pdFZlcnRleEdyYXBoAG5vZGUgIT0gTlVMTABhZGRWZXJ0ZXhOb2Rl";function Y(A){return A}function O(A){return A.replace(/\b__Z[\w\d_]+/g,(function(A){return A===A?A:A+" ["+A+"]"}))}function j(){var A=new Error;if(!A.stack){try{throw new Error(0)}catch(e){A=e}if(!A.stack)return"(no stack trace available)"}return A.stack.toString()}function N(){return p.length}function Z(A){try{var e=new ArrayBuffer(A);if(e.byteLength!=A)return;return new Int8Array(e).set(p),$(e),Q(e),1}catch(A){}}var W="function"==typeof atob?atob:function(A){var e,r,t,i,n,o,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f="",s=0;A=A.replace(/[^A-Za-z0-9\+\/\=]/g,"");do{e=a.indexOf(A.charAt(s++))<<2|(i=a.indexOf(A.charAt(s++)))>>4,r=(15&i)<<4|(n=a.indexOf(A.charAt(s++)))>>2,t=(3&n)<<6|(o=a.indexOf(A.charAt(s++))),f+=String.fromCharCode(e),64!==n&&(f+=String.fromCharCode(r)),64!==o&&(f+=String.fromCharCode(t))}while(s>2]=A,i[a+4>>2]=e,(a=0!=(0|n))&&(i[n>>2]=0),0|UA(A,e))return I=o,0|(d=1);i[d>>2]=0;A:do{if((0|r)>=1)if(a)for(l=0,h=1,c=1,f=0,a=A;;){if(!(f|l)){if(0==(0|(a=0|U(a,e,4,d)))&0==(0|(e=0|M()))){a=2;break A}if(0|UA(a,e)){a=1;break A}}if(0==(0|(a=0|U(a,e,0|i[16+(l<<2)>>2],d)))&0==(0|(e=0|M()))){a=2;break A}if(i[(A=t+(c<<3)|0)>>2]=a,i[A+4>>2]=e,i[n+(c<<2)>>2]=h,A=(0|(f=f+1|0))==(0|h),u=6==(0|(s=l+1|0)),0|UA(a,e)){a=1;break A}if((0|(h=h+(u&A&1)|0))>(0|r)){a=0;break}l=A?u?0:s:l,c=c+1|0,f=A?0:f}else for(l=0,h=1,c=1,f=0,a=A;;){if(!(f|l)){if(0==(0|(a=0|U(a,e,4,d)))&0==(0|(e=0|M()))){a=2;break A}if(0|UA(a,e)){a=1;break A}}if(0==(0|(a=0|U(a,e,0|i[16+(l<<2)>>2],d)))&0==(0|(e=0|M()))){a=2;break A}if(i[(A=t+(c<<3)|0)>>2]=a,i[A+4>>2]=e,A=(0|(f=f+1|0))==(0|h),u=6==(0|(s=l+1|0)),0|UA(a,e)){a=1;break A}if((0|(h=h+(u&A&1)|0))>(0|r)){a=0;break}l=A?u?0:s:l,c=c+1|0,f=A?0:f}else a=0}while(0);return I=o,0|(d=a)}function P(A,e,r,t,n,o,a){r|=0,t|=0,n|=0,o|=0,a|=0;var f,s,u=0,l=0,h=0,c=0,d=0;if(s=I,I=I+16|0,f=s,0==(0|(A|=0))&0==(0|(e|=0)))I=s;else{if(u=0|Me(0|A,0|e,0|o,((0|o)<0)<<31>>31|0),M(),!(0==(0|(d=0|i[(c=l=t+(u<<3)|0)>>2]))&0==(0|(c=0|i[c+4>>2]))|(h=(0|d)==(0|A)&(0|c)==(0|e))))do{h=(0|(c=0|i[(d=l=t+((u=(u+1|0)%(0|o)|0)<<3)|0)>>2]))==(0|A)&(0|(d=0|i[d+4>>2]))==(0|e)}while(!(0==(0|c)&0==(0|d)|h));u=n+(u<<2)|0,h&&(0|i[u>>2])<=(0|a)||(i[(d=l)>>2]=A,i[d+4>>2]=e,i[u>>2]=a,(0|a)>=(0|r)||(d=a+1|0,i[f>>2]=0,P(c=0|U(A,e,2,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,3,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,1,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,5,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,4,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,6,f),0|M(),r,t,n,o,d))),I=s}}function U(A,e,r,t){A|=0,e|=0,r|=0;var n,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0;if((0|i[(t|=0)>>2])>0){a=0;do{r=0|fA(r),a=a+1|0}while((0|a)<(0|i[t>>2]))}n=0|Qe(0|A,0|e,45),M(),o=127&n,f=0|GA(A,e),a=0|Qe(0|A,0|e,52),M(),a&=15;A:do{if(a)for(;;){if(h=0|Qe(0|A,0|e,0|(l=3*(15-a|0)|0)),M(),h&=7,c=0==(0|RA(a)),a=a+-1|0,u=0|ye(7,0,0|l),e&=~(0|M()),A=(l=0|ye(0|i[(c?464:48)+(28*h|0)+(r<<2)>>2],0,0|l))|A&~u,e|=0|M(),!(r=0|i[(c?672:256)+(28*h|0)+(r<<2)>>2])){r=0;break A}if(!a){s=6;break}}else s=6}while(0);6==(0|s)&&(A|=h=0|ye(0|(c=0|i[880+(28*o|0)+(r<<2)>>2]),0,45),e=0|M()|-1040385&e,r=0|i[4304+(28*o|0)+(r<<2)>>2],127==(127&c|0)&&(c=0|ye(0|i[880+(28*o|0)+20>>2],0,45),e=0|M()|-1040385&e,r=0|i[4304+(28*o|0)+20>>2],A=0|TA(c|A,e),e=0|M(),i[t>>2]=1+(0|i[t>>2]))),s=0|Qe(0|A,0|e,45),M(),s&=127;A:do{if(0|S(s)){e:do{if(1==(0|GA(A,e))){if((0|o)!=(0|s)){if(0|R(s,0|i[7728+(28*o|0)>>2])){A=0|HA(A,e),f=1,e=0|M();break}A=0|TA(A,e),f=1,e=0|M();break}switch(0|f){case 5:A=0|HA(A,e),e=0|M(),i[t>>2]=5+(0|i[t>>2]),f=0;break e;case 3:A=0|TA(A,e),e=0|M(),i[t>>2]=1+(0|i[t>>2]),f=0;break e;default:return c=0,k(0|(h=0)),0|c}}else f=0}while(0);if((0|r)>0){a=0;do{A=0|SA(A,e),e=0|M(),a=a+1|0}while((0|a)!=(0|r))}if((0|o)!=(0|s)){if(!(0|T(s))){if(0!=(0|f)|5!=(0|GA(A,e)))break;i[t>>2]=1+(0|i[t>>2]);break}switch(127&n){case 8:case 118:break A}3!=(0|GA(A,e))&&(i[t>>2]=1+(0|i[t>>2]))}}else if((0|r)>0){a=0;do{A=0|TA(A,e),e=0|M(),a=a+1|0}while((0|a)!=(0|r))}}while(0);return i[t>>2]=((0|i[t>>2])+r|0)%6|0,c=A,k(0|(h=e)),0|c}function G(A,e,r,t,o,a){e|=0,r|=0,t|=0,o|=0,a|=0;var f,s,u,l,h,c,d,g,w,p=0,B=0,b=0,v=0,m=0,k=0,Q=0,y=0,E=0,x=0,D=0,_=0,F=0,C=0;if(w=I,I=I+48|0,c=w+32|0,d=w+16|0,g=w,(0|(p=0|i[(A|=0)>>2]))<=0)return I=w,0|(_=0);f=A+4|0,s=c+8|0,u=d+8|0,l=g+8|0,h=((0|e)<0)<<31>>31,D=0;A:for(;;){E=(B=0|i[f>>2])+(D<<4)|0,i[c>>2]=i[E>>2],i[c+4>>2]=i[E+4>>2],i[c+8>>2]=i[E+8>>2],i[c+12>>2]=i[E+12>>2],(0|D)==(p+-1|0)?(i[d>>2]=i[B>>2],i[d+4>>2]=i[B+4>>2],i[d+8>>2]=i[B+8>>2],i[d+12>>2]=i[B+12>>2]):(E=B+(D+1<<4)|0,i[d>>2]=i[E>>2],i[d+4>>2]=i[E+4>>2],i[d+8>>2]=i[E+8>>2],i[d+12>>2]=i[E+12>>2]),E=0|N(c,d,r);e:do{if((0|E)>0){x=+(0|E),y=0;r:for(;;){C=+(E-y|0),F=+(0|y),n[g>>3]=+n[c>>3]*C/x+ +n[d>>3]*F/x,n[l>>3]=+n[s>>3]*C/x+ +n[u>>3]*F/x,B=0|Me(0|(k=0|LA(g,r)),0|(Q=0|M()),0|e,0|h),M(),v=0|i[(b=p=a+(B<<3)|0)>>2],b=0|i[b+4>>2];t:do{if(0==(0|v)&0==(0|b))_=14;else for(m=0;;){if((0|m)>(0|e)){p=1;break t}if((0|v)==(0|k)&(0|b)==(0|Q)){p=7;break t}if(0==(0|(v=0|i[(b=p=a+((B=(B+1|0)%(0|e)|0)<<3)|0)>>2]))&0==(0|(b=0|i[b+4>>2]))){_=14;break}m=m+1|0}}while(0);switch(14==(0|_)&&(_=0,0==(0|k)&0==(0|Q)?p=7:(i[p>>2]=k,i[p+4>>2]=Q,p=0|i[t>>2],i[(m=o+(p<<3)|0)>>2]=k,i[m+4>>2]=Q,i[t>>2]=p+1,p=0)),7&p){case 7:case 0:break;default:break r}if((0|E)<=(0|(y=y+1|0))){_=8;break e}}if(0|p){p=-1,_=20;break A}}else _=8}while(0);if(8==(0|_)&&(_=0),(0|(D=D+1|0))>=(0|(p=0|i[A>>2]))){p=0,_=20;break}}return 20==(0|_)?(I=w,0|p):0}function S(A){return 0|i[7728+(28*(A|=0)|0)+16>>2]}function T(A){return 4==(0|(A|=0))|117==(0|A)|0}function V(A){return 0|i[11152+(216*(0|i[(A|=0)>>2])|0)+(72*(0|i[A+4>>2])|0)+(24*(0|i[A+8>>2])|0)+(i[A+12>>2]<<3)>>2]}function H(A){return 0|i[11152+(216*(0|i[(A|=0)>>2])|0)+(72*(0|i[A+4>>2])|0)+(24*(0|i[A+8>>2])|0)+(i[A+12>>2]<<3)+4>>2]}function R(A,e){return e|=0,(0|i[7728+(28*(A|=0)|0)+20>>2])==(0|e)?0|(e=1):0|(e=(0|i[7728+(28*A|0)+24>>2])==(0|e))}function L(A,e){return 0|i[880+(28*(A|=0)|0)+((e|=0)<<2)>>2]}function z(A,e){return e|=0,(0|i[880+(28*(A|=0)|0)>>2])==(0|e)?0|(e=0):(0|i[880+(28*A|0)+4>>2])==(0|e)?0|(e=1):(0|i[880+(28*A|0)+8>>2])==(0|e)?0|(e=2):(0|i[880+(28*A|0)+12>>2])==(0|e)?0|(e=3):(0|i[880+(28*A|0)+16>>2])==(0|e)?0|(e=4):(0|i[880+(28*A|0)+20>>2])==(0|e)?0|(e=5):0|((0|i[880+(28*A|0)+24>>2])==(0|e)?6:7)}function Y(A){return+n[(A|=0)+16>>3]<+n[A+24>>3]|0}function O(A,e){A|=0;var r,t,i=0;return(i=+n[(e|=0)>>3])>=+n[A+8>>3]&&i<=+n[A>>3]?(r=+n[A+16>>3],i=+n[A+24>>3],e=(t=+n[e+8>>3])>=i,A=t<=r&1,r>2]=0,l=l+4|0}while((0|l)<(0|h));return NA(e,o),OA(h=0|i[(l=o)>>2],l=0|i[l+4>>2],r),jA(h,l,t),s=+DA(r,t+8|0),n[r>>3]=+n[A>>3],n[(l=r+8|0)>>3]=+n[A+16>>3],n[t>>3]=+n[A+8>>3],n[(h=t+8|0)>>3]=+n[A+24>>3],u=+DA(r,t),h=~~+B(+u*u/+Ee(+ +f(+(+n[l>>3]-+n[h>>3])/(+n[r>>3]-+n[t>>3])),3)/(s*(2.59807621135*s)*.8)),I=a,0|(0==(0|h)?1:h)}function N(A,e,r){A|=0,e|=0,r|=0;var t,n,o,a,f,s=0,u=0;a=I,I=I+288|0,t=a+264|0,n=a+96|0,u=(s=o=a)+96|0;do{i[s>>2]=0,s=s+4|0}while((0|s)<(0|u));return NA(r,o),OA(s=0|i[(u=o)>>2],u=0|i[u+4>>2],t),jA(s,u,n),f=+DA(t,n+8|0),u=~~+B(+ +DA(A,e)/(2*f)),I=a,0|(0==(0|u)?1:u)}function Z(A,e,r,t){e|=0,r|=0,t|=0,i[(A|=0)>>2]=e,i[A+4>>2]=r,i[A+8>>2]=t}function W(A,e){A|=0;var r,t,o,a,s=0,u=0,l=0,h=0,c=0,d=0,g=0;i[(a=(e|=0)+8|0)>>2]=0,t=+n[A>>3],h=+f(+t),o=+n[A+8>>3],h+=.5*(c=+f(+o)/.8660254037844386),h-=+(0|(s=~~h)),c-=+(0|(A=~~c));do{if(h<.5){if(h<.3333333333333333){if(i[e>>2]=s,c<.5*(h+1)){i[e+4>>2]=A;break}A=A+1|0,i[e+4>>2]=A;break}if(A=(1&!(c<(g=1-h)))+A|0,i[e+4>>2]=A,g<=c&c<2*h){s=s+1|0,i[e>>2]=s;break}i[e>>2]=s;break}if(!(h<.6666666666666666)){if(s=s+1|0,i[e>>2]=s,c<.5*h){i[e+4>>2]=A;break}A=A+1|0,i[e+4>>2]=A;break}if(c<1-h){if(i[e+4>>2]=A,2*h-1>2]=s;break}}else A=A+1|0,i[e+4>>2]=A;s=s+1|0,i[e>>2]=s}while(0);do{if(t<0){if(1&A){s=~~(+(0|s)-(2*(+((d=0|ve(0|s,((0|s)<0)<<31>>31|0,0|(d=(A+1|0)/2|0),((0|d)<0)<<31>>31|0))>>>0)+4294967296*+(0|M()))+1)),i[e>>2]=s;break}s=~~(+(0|s)-2*(+((d=0|ve(0|s,((0|s)<0)<<31>>31|0,0|(d=(0|A)/2|0),((0|d)<0)<<31>>31|0))>>>0)+4294967296*+(0|M()))),i[e>>2]=s;break}}while(0);d=e+4|0,o<0&&(s=s-((1|A<<1)/2|0)|0,i[e>>2]=s,A=0-A|0,i[d>>2]=A),u=A-s|0,(0|s)<0?(l=0-s|0,i[d>>2]=u,i[a>>2]=l,i[e>>2]=0,A=u,s=0):l=0,(0|A)<0&&(s=s-A|0,i[e>>2]=s,l=l-A|0,i[a>>2]=l,i[d>>2]=0,A=0),r=s-l|0,u=A-l|0,(0|l)<0&&(i[e>>2]=r,i[d>>2]=u,i[a>>2]=0,A=u,s=r,l=0),(0|(u=(0|l)<(0|(u=(0|A)<(0|s)?A:s))?l:u))<=0||(i[e>>2]=s-u,i[d>>2]=A-u,i[a>>2]=l-u)}function J(A){var e,r=0,t=0,n=0,o=0,a=0;r=0|i[(A|=0)>>2],t=0|i[(e=A+4|0)>>2],(0|r)<0&&(t=t-r|0,i[e>>2]=t,i[(a=A+8|0)>>2]=(0|i[a>>2])-r,i[A>>2]=0,r=0),(0|t)<0?(r=r-t|0,i[A>>2]=r,o=(0|i[(a=A+8|0)>>2])-t|0,i[a>>2]=o,i[e>>2]=0,t=0):(a=o=A+8|0,o=0|i[o>>2]),(0|o)<0&&(r=r-o|0,i[A>>2]=r,t=t-o|0,i[e>>2]=t,i[a>>2]=0,o=0),(0|(n=(0|o)<(0|(n=(0|t)<(0|r)?t:r))?o:n))<=0||(i[A>>2]=r-n,i[e>>2]=t-n,i[a>>2]=o-n)}function K(A,e){e|=0;var r,t;t=0|i[(A|=0)+8>>2],r=+((0|i[A+4>>2])-t|0),n[e>>3]=+((0|i[A>>2])-t|0)-.5*r,n[e+8>>3]=.8660254037844386*r}function X(A,e,r){A|=0,e|=0,i[(r|=0)>>2]=(0|i[e>>2])+(0|i[A>>2]),i[r+4>>2]=(0|i[e+4>>2])+(0|i[A+4>>2]),i[r+8>>2]=(0|i[e+8>>2])+(0|i[A+8>>2])}function q(A,e,r){A|=0,e|=0,i[(r|=0)>>2]=(0|i[A>>2])-(0|i[e>>2]),i[r+4>>2]=(0|i[A+4>>2])-(0|i[e+4>>2]),i[r+8>>2]=(0|i[A+8>>2])-(0|i[e+8>>2])}function $(A,e){e|=0;var r,t=0;t=0|b(0|i[(A|=0)>>2],e),i[A>>2]=t,r=0|b(0|i[(t=A+4|0)>>2],e),i[t>>2]=r,e=0|b(0|i[(A=A+8|0)>>2],e),i[A>>2]=e}function AA(A){var e,r,t=0,n=0,o=0,a=0,f=0;f=(0|(r=0|i[(A|=0)>>2]))<0,A=(A=(n=(0|(a=((e=(0|(o=(0|i[A+4>>2])-(f?r:0)|0))<0)?0-o|0:0)+((0|i[A+8>>2])-(f?r:0))|0))<0)?0:a)-((o=(0|(n=(0|A)<(0|(n=(0|(t=(e?0:o)-(n?a:0)|0))<(0|(a=(f?0:r)-(e?o:0)-(n?a:0)|0))?t:a))?A:n))>0)?n:0)|0,t=t-(o?n:0)|0;A:do{switch(a-(o?n:0)|0){case 0:switch(0|t){case 0:return 0|(f=0==(0|A)?0:1==(0|A)?1:7);case 1:return 0|(f=0==(0|A)?2:1==(0|A)?3:7);default:break A}case 1:switch(0|t){case 0:return 0|(f=0==(0|A)?4:1==(0|A)?5:7);case 1:if(A)break A;return 0|(A=6);default:break A}}}while(0);return 0|(f=7)}function eA(A){var e,r,t=0,n=0,o=0,a=0,f=0;n=0|i[(e=(A|=0)+8|0)>>2],o=0|we(+((3*(t=(0|i[A>>2])-n|0)|0)-(n=(0|i[(r=A+4|0)>>2])-n|0)|0)/7),i[A>>2]=o,t=0|we(+((n<<1)+t|0)/7),i[r>>2]=t,i[e>>2]=0,n=t-o|0,(0|o)<0?(f=0-o|0,i[r>>2]=n,i[e>>2]=f,i[A>>2]=0,t=n,o=0,n=f):n=0,(0|t)<0&&(o=o-t|0,i[A>>2]=o,n=n-t|0,i[e>>2]=n,i[r>>2]=0,t=0),f=o-n|0,a=t-n|0,(0|n)<0?(i[A>>2]=f,i[r>>2]=a,i[e>>2]=0,t=a,a=f,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|t)<(0|a)?t:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=t-o,i[e>>2]=n-o)}function rA(A){var e,r,t=0,n=0,o=0,a=0,f=0;n=0|i[(e=(A|=0)+8|0)>>2],o=0|we(+(((t=(0|i[A>>2])-n|0)<<1)+(n=(0|i[(r=A+4|0)>>2])-n|0)|0)/7),i[A>>2]=o,t=0|we(+((3*n|0)-t|0)/7),i[r>>2]=t,i[e>>2]=0,n=t-o|0,(0|o)<0?(f=0-o|0,i[r>>2]=n,i[e>>2]=f,i[A>>2]=0,t=n,o=0,n=f):n=0,(0|t)<0&&(o=o-t|0,i[A>>2]=o,n=n-t|0,i[e>>2]=n,i[r>>2]=0,t=0),f=o-n|0,a=t-n|0,(0|n)<0?(i[A>>2]=f,i[r>>2]=a,i[e>>2]=0,t=a,a=f,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|t)<(0|a)?t:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=t-o,i[e>>2]=n-o)}function tA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],o=0|i[(r=A+4|0)>>2],a=0|i[(t=A+8|0)>>2],f=o+(3*n|0)|0,i[A>>2]=f,o=a+(3*o|0)|0,i[r>>2]=o,n=(3*a|0)+n|0,i[t>>2]=n,a=o-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=a,i[t>>2]=n,i[A>>2]=0,o=a,a=0):a=f,(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function iA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=(3*(n=0|i[(r=A+4|0)>>2])|0)+f|0,f=(o=0|i[(t=A+8|0)>>2])+(3*f|0)|0,i[A>>2]=f,i[r>>2]=a,n=(3*o|0)+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,f=0):o=a,(0|o)<0&&(f=f-o|0,i[A>>2]=f,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=f-n|0,a=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=a,i[t>>2]=0,f=e,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|a)<(0|f)?a:f))?n:o))<=0||(i[A>>2]=f-o,i[r>>2]=a-o,i[t>>2]=n-o)}function nA(A,e){A|=0;var r,t,n,o=0,a=0,f=0;((e|=0)+-1|0)>>>0>=6||(f=(0|i[15472+(12*e|0)>>2])+(0|i[A>>2])|0,i[A>>2]=f,n=A+4|0,a=(0|i[15472+(12*e|0)+4>>2])+(0|i[n>>2])|0,i[n>>2]=a,t=A+8|0,e=(0|i[15472+(12*e|0)+8>>2])+(0|i[t>>2])|0,i[t>>2]=e,o=a-f|0,(0|f)<0?(e=e-f|0,i[n>>2]=o,i[t>>2]=e,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,e=e-o|0,i[t>>2]=e,i[n>>2]=0,o=0),r=a-e|0,f=o-e|0,(0|e)<0?(i[A>>2]=r,i[n>>2]=f,i[t>>2]=0,a=r,e=0):f=o,(0|(o=(0|e)<(0|(o=(0|f)<(0|a)?f:a))?e:o))<=0||(i[A>>2]=a-o,i[n>>2]=f-o,i[t>>2]=e-o))}function oA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=(n=0|i[(r=A+4|0)>>2])+f|0,f=(o=0|i[(t=A+8|0)>>2])+f|0,i[A>>2]=f,i[r>>2]=a,n=o+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function aA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],a=0|i[(r=A+4|0)>>2],o=0|i[(t=A+8|0)>>2],f=a+n|0,i[A>>2]=f,a=o+a|0,i[r>>2]=a,n=o+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function fA(A){switch(0|(A|=0)){case 1:A=5;break;case 5:A=4;break;case 4:A=6;break;case 6:A=2;break;case 2:A=3;break;case 3:A=1}return 0|A}function sA(A){switch(0|(A|=0)){case 1:A=3;break;case 3:A=2;break;case 2:A=6;break;case 6:A=4;break;case 4:A=5;break;case 5:A=1}return 0|A}function uA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],o=0|i[(r=A+4|0)>>2],a=0|i[(t=A+8|0)>>2],f=o+(n<<1)|0,i[A>>2]=f,o=a+(o<<1)|0,i[r>>2]=o,n=(a<<1)+n|0,i[t>>2]=n,a=o-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=a,i[t>>2]=n,i[A>>2]=0,o=a,a=0):a=f,(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function lA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=((n=0|i[(r=A+4|0)>>2])<<1)+f|0,f=(o=0|i[(t=A+8|0)>>2])+(f<<1)|0,i[A>>2]=f,i[r>>2]=a,n=(o<<1)+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,f=0):o=a,(0|o)<0&&(f=f-o|0,i[A>>2]=f,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=f-n|0,a=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=a,i[t>>2]=0,f=e,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|a)<(0|f)?a:f))?n:o))<=0||(i[A>>2]=f-o,i[r>>2]=a-o,i[t>>2]=n-o)}function hA(A,e){e|=0;var r,t,n,o=0,a=0,f=0;return n=(0|(t=(0|i[(A|=0)>>2])-(0|i[e>>2])|0))<0,r=(0|(a=(0|i[A+4>>2])-(0|i[e+4>>2])-(n?t:0)|0))<0,e=(e=(A=(0|(f=(n?0-t|0:0)+(0|i[A+8>>2])-(0|i[e+8>>2])+(r?0-a|0:0)|0))<0)?0:f)-((a=(0|(A=(0|e)<(0|(A=(0|(o=(r?0:a)-(A?f:0)|0))<(0|(f=(n?0:t)-(r?a:0)-(A?f:0)|0))?o:f))?e:A))>0)?A:0)|0,o=o-(a?A:0)|0,0|((0|(A=(0|(A=f-(a?A:0)|0))>-1?A:0-A|0))>(0|(e=(0|(o=(0|o)>-1?o:0-o|0))>(0|(e=(0|e)>-1?e:0-e|0))?o:e))?A:e)}function cA(A,e){e|=0;var r;r=0|i[(A|=0)+8>>2],i[e>>2]=(0|i[A>>2])-r,i[e+4>>2]=(0|i[A+4>>2])-r}function dA(A,e){e|=0;var r,t,n,o=0,a=0,f=0;a=0|i[(A|=0)>>2],i[e>>2]=a,A=0|i[A+4>>2],i[(t=e+4|0)>>2]=A,i[(n=e+8|0)>>2]=0,o=A-a|0,(0|a)<0?(A=0-a|0,i[t>>2]=o,i[n>>2]=A,i[e>>2]=0,a=0):(o=A,A=0),(0|o)<0&&(a=a-o|0,i[e>>2]=a,A=A-o|0,i[n>>2]=A,i[t>>2]=0,o=0),r=a-A|0,f=o-A|0,(0|A)<0?(i[e>>2]=r,i[t>>2]=f,i[n>>2]=0,o=f,f=r,A=0):f=a,(0|(a=(0|A)<(0|(a=(0|o)<(0|f)?o:f))?A:a))<=0||(i[e>>2]=f-a,i[t>>2]=o-a,i[n>>2]=A-a)}function gA(A){var e,r,t,n;r=(n=0|i[(e=(A|=0)+8|0)>>2])-(0|i[A>>2])|0,i[A>>2]=r,A=(0|i[(t=A+4|0)>>2])-n|0,i[t>>2]=A,i[e>>2]=0-(A+r)}function wA(A){var e,r,t=0,n=0,o=0,a=0,f=0;t=0-(n=0|i[(A|=0)>>2])|0,i[A>>2]=t,i[(e=A+8|0)>>2]=0,a=(o=0|i[(r=A+4|0)>>2])+n|0,(0|n)>0?(i[r>>2]=a,i[e>>2]=n,i[A>>2]=0,t=0,o=a):n=0,(0|o)<0?(f=t-o|0,i[A>>2]=f,n=n-o|0,i[e>>2]=n,i[r>>2]=0,a=f-n|0,t=0-n|0,(0|n)<0?(i[A>>2]=a,i[r>>2]=t,i[e>>2]=0,o=t,n=0):(o=0,a=f)):a=t,(0|(t=(0|n)<(0|(t=(0|o)<(0|a)?o:a))?n:t))<=0||(i[A>>2]=a-t,i[r>>2]=o-t,i[e>>2]=n-t)}function pA(A,e,r,t){e|=0,r|=0,t|=0;var o,a=0,f=0,s=0,u=0;if(o=I,I=I+32|0,function(A,e){e|=0;var r=0,t=0,i=0;r=+n[(A=A|0)>>3],t=+l(+r),r=+h(+r),n[e+16>>3]=r,r=+n[A+8>>3],i=t*+l(+r),n[e>>3]=i,r=t*+h(+r),n[e+8>>3]=r}(A|=0,f=o),i[r>>2]=0,a=+fe(15888,f),(s=+fe(15912,f))>2]=1,a=s),(s=+fe(15936,f))>2]=2,a=s),(s=+fe(15960,f))>2]=3,a=s),(s=+fe(15984,f))>2]=4,a=s),(s=+fe(16008,f))>2]=5,a=s),(s=+fe(16032,f))>2]=6,a=s),(s=+fe(16056,f))>2]=7,a=s),(s=+fe(16080,f))>2]=8,a=s),(s=+fe(16104,f))>2]=9,a=s),(s=+fe(16128,f))>2]=10,a=s),(s=+fe(16152,f))>2]=11,a=s),(s=+fe(16176,f))>2]=12,a=s),(s=+fe(16200,f))>2]=13,a=s),(s=+fe(16224,f))>2]=14,a=s),(s=+fe(16248,f))>2]=15,a=s),(s=+fe(16272,f))>2]=16,a=s),(s=+fe(16296,f))>2]=17,a=s),(s=+fe(16320,f))>2]=18,a=s),(s=+fe(16344,f))>2]=19,a=s),(s=+d(+(1-.5*a)))<1e-16)return i[t>>2]=0,i[t+4>>2]=0,i[t+8>>2]=0,i[t+12>>2]=0,void(I=o);if(r=0|i[r>>2],a=+EA((a=+n[16368+(24*r|0)>>3])-+EA(+function(A,e){A|=0;var r=0,t=0,i=0,o=0,a=0;return o=+n[(e=e|0)>>3],t=+l(+o),i=+n[e+8>>3]-+n[A+8>>3],a=t*+h(+i),r=+n[A>>3],+ +p(+a,+(+h(+o)*+l(+r)-+l(+i)*(t*+h(+r))))}(15568+(r<<4)|0,A))),u=0|RA(e)?+EA(a+-.3334731722518321):a,a=+c(+s)/.381966011250105,(0|e)>0){f=0;do{a*=2.6457513110645907,f=f+1|0}while((0|f)!=(0|e))}s=+l(+u)*a,n[t>>3]=s,u=+h(+u)*a,n[t+8>>3]=u,I=o}function BA(A,e,r,t,o){e|=0,r|=0,t|=0,o|=0;var a=0,u=0;if((a=+function(A){var e=0,r=0;return r=+n[(A=A|0)>>3],e=+n[A+8>>3],+ +s(+(r*r+e*e))}(A|=0))<1e-16)return e=15568+(e<<4)|0,i[o>>2]=i[e>>2],i[o+4>>2]=i[e+4>>2],i[o+8>>2]=i[e+8>>2],void(i[o+12>>2]=i[e+12>>2]);if(u=+p(+ +n[A+8>>3],+ +n[A>>3]),(0|r)>0){A=0;do{a/=2.6457513110645907,A=A+1|0}while((0|A)!=(0|r))}t?(a/=3,r=0==(0|RA(r)),a=+w(.381966011250105*(r?a:a/2.6457513110645907))):(a=+w(.381966011250105*a),0|RA(r)&&(u=+EA(u+.3334731722518321))),function(A,e,r,t){A|=0,e=+e,t|=0;var o=0,a=0,s=0,u=0;if((r=+r)<1e-16)return i[t>>2]=i[A>>2],i[t+4>>2]=i[A+4>>2],i[t+8>>2]=i[A+8>>2],void(i[t+12>>2]=i[A+12>>2]);a=e<0?e+6.283185307179586:e,a=e>=6.283185307179586?a+-6.283185307179586:a;do{if(!(a<1e-16)){if(o=+f(+(a+-3.141592653589793))<1e-16,e=+n[A>>3],o){e-=r,n[t>>3]=e,o=t;break}if(s=+l(+r),r=+h(+r),e=s*+h(+e)+ +l(+a)*(r*+l(+e)),e=+g(+((e=e>1?1:e)<-1?-1:e)),n[t>>3]=e,+f(+(e+-1.5707963267948966))<1e-16)return n[t>>3]=1.5707963267948966,void(n[t+8>>3]=0);if(+f(+(e+1.5707963267948966))<1e-16)return n[t>>3]=-1.5707963267948966,void(n[t+8>>3]=0);if(u=+l(+e),a=r*+h(+a)/u,r=+n[A>>3],e=(s-+h(+e)*+h(+r))/+l(+r)/u,s=a>1?1:a,e=e>1?1:e,(e=+n[A+8>>3]+ +p(+(s<-1?-1:s),+(e<-1?-1:e)))>3.141592653589793)do{e+=-6.283185307179586}while(e>3.141592653589793);if(e<-3.141592653589793)do{e+=6.283185307179586}while(e<-3.141592653589793);return void(n[t+8>>3]=e)}e=+n[A>>3]+r,n[t>>3]=e,o=t}while(0);if(+f(+(e+-1.5707963267948966))<1e-16)return n[o>>3]=1.5707963267948966,void(n[t+8>>3]=0);if(+f(+(e+1.5707963267948966))<1e-16)return n[o>>3]=-1.5707963267948966,void(n[t+8>>3]=0);if((e=+n[A+8>>3])>3.141592653589793)do{e+=-6.283185307179586}while(e>3.141592653589793);if(e<-3.141592653589793)do{e+=6.283185307179586}while(e<-3.141592653589793);n[t+8>>3]=e}(15568+(e<<4)|0,+EA(+n[16368+(24*e|0)>>3]-u),a,o)}function bA(A,e,r){e|=0,r|=0;var t,n;t=I,I=I+16|0,K((A|=0)+4|0,n=t),BA(n,0|i[A>>2],e,0,r),I=t}function vA(A,e,r,t,o){A|=0,e|=0,r|=0,t|=0,o|=0;var a,f,s,u,l,h,c,d,g,w,p,B,b,v,m,k,M,y,E,x,D,_,F=0,C=0,P=0,U=0,G=0,S=0;if(_=I,I=I+272|0,U=_+240|0,E=_,x=_+224|0,D=_+208|0,p=_+176|0,B=_+160|0,b=_+192|0,v=_+144|0,m=_+128|0,k=_+112|0,M=_+96|0,y=_+80|0,i[(F=_+256|0)>>2]=e,i[U>>2]=i[A>>2],i[U+4>>2]=i[A+4>>2],i[U+8>>2]=i[A+8>>2],i[U+12>>2]=i[A+12>>2],mA(U,F,E),i[o>>2]=0,(0|(U=t+r+(5==(0|t)&1)|0))<=(0|r))I=_;else{f=x+4|0,s=p+4|0,u=r+5|0,l=16848+((a=0|i[F>>2])<<2)|0,h=16928+(a<<2)|0,c=m+8|0,d=k+8|0,g=M+8|0,w=D+4|0,P=r;A:for(;;){C=E+(((0|P)%5|0)<<4)|0,i[D>>2]=i[C>>2],i[D+4>>2]=i[C+4>>2],i[D+8>>2]=i[C+8>>2],i[D+12>>2]=i[C+12>>2];do{}while(2==(0|kA(D,a,0,1)));if((0|P)>(0|r)&0!=(0|RA(e))){if(i[p>>2]=i[D>>2],i[p+4>>2]=i[D+4>>2],i[p+8>>2]=i[D+8>>2],i[p+12>>2]=i[D+12>>2],K(f,B),t=0|i[p>>2],F=0|i[17008+(80*t|0)+(i[x>>2]<<2)>>2],i[p>>2]=i[18608+(80*t|0)+(20*F|0)>>2],(0|(C=0|i[18608+(80*t|0)+(20*F|0)+16>>2]))>0){A=0;do{oA(s),A=A+1|0}while((0|A)<(0|C))}switch(C=18608+(80*t|0)+(20*F|0)+4|0,i[b>>2]=i[C>>2],i[b+4>>2]=i[C+4>>2],i[b+8>>2]=i[C+8>>2],$(b,3*(0|i[l>>2])|0),X(s,b,s),J(s),K(s,v),G=+(0|i[h>>2]),n[m>>3]=3*G,n[c>>3]=0,S=-1.5*G,n[k>>3]=S,n[d>>3]=2.598076211353316*G,n[M>>3]=S,n[g>>3]=-2.598076211353316*G,0|i[17008+(80*(0|i[p>>2])|0)+(i[D>>2]<<2)>>2]){case 1:A=k,t=m;break;case 3:A=M,t=k;break;case 2:A=m,t=M;break;default:A=12;break A}oe(B,v,t,A,y),BA(y,0|i[p>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])}if((0|P)<(0|u)&&(K(w,p),BA(p,0|i[D>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])),i[x>>2]=i[D>>2],i[x+4>>2]=i[D+4>>2],i[x+8>>2]=i[D+8>>2],i[x+12>>2]=i[D+12>>2],(0|(P=P+1|0))>=(0|U)){A=3;break}}3!=(0|A)?12==(0|A)&&Q(22474,22521,581,22531):I=_}}function mA(A,e,r){A|=0,e|=0,r|=0;var t,n=0,o=0,a=0,f=0,s=0;t=I,I=I+128|0,o=t,f=20208,s=(a=n=t+64|0)+60|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));f=20272,s=(a=o)+60|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));n=(s=0==(0|RA(0|i[e>>2])))?n:o,uA(o=A+4|0),lA(o),0|RA(0|i[e>>2])&&(iA(o),i[e>>2]=1+(0|i[e>>2])),i[r>>2]=i[A>>2],X(o,n,e=r+4|0),J(e),i[r+16>>2]=i[A>>2],X(o,n+12|0,e=r+20|0),J(e),i[r+32>>2]=i[A>>2],X(o,n+24|0,e=r+36|0),J(e),i[r+48>>2]=i[A>>2],X(o,n+36|0,e=r+52|0),J(e),i[r+64>>2]=i[A>>2],X(o,n+48|0,r=r+68|0),J(r),I=t}function kA(A,e,r,t){r|=0,t|=0;var n,o,a,f,s,u,l=0,h=0,c=0,d=0,g=0;if(u=I,I=I+32|0,s=u+12|0,o=u,g=(A|=0)+4|0,d=0|i[16928+((e|=0)<<2)>>2],d=(f=0!=(0|t))?3*d|0:d,l=0|i[g>>2],n=0|i[(a=A+8|0)>>2],f){if((0|(l=n+l+(t=0|i[(h=A+12|0)>>2])|0))==(0|d))return I=u,0|(g=1);c=h}else l=n+l+(t=0|i[(c=A+12|0)>>2])|0;if((0|l)<=(0|d))return I=u,0|(g=0);do{if((0|t)>0){if(t=0|i[A>>2],(0|n)>0){h=18608+(80*t|0)+60|0,t=A;break}t=18608+(80*t|0)+40|0,r?(Z(s,d,0,0),q(g,s,o),aA(o),X(o,s,g),h=t,t=A):(h=t,t=A)}else h=18608+(80*(0|i[A>>2])|0)+20|0,t=A}while(0);if(i[t>>2]=i[h>>2],(0|i[(l=h+16|0)>>2])>0){t=0;do{oA(g),t=t+1|0}while((0|t)<(0|i[l>>2]))}return A=h+4|0,i[s>>2]=i[A>>2],i[s+4>>2]=i[A+4>>2],i[s+8>>2]=i[A+8>>2],e=0|i[16848+(e<<2)>>2],$(s,f?3*e|0:e),X(g,s,g),J(g),t=f&&((0|i[a>>2])+(0|i[g>>2])+(0|i[c>>2])|0)==(0|d)?1:2,I=u,0|(g=t)}function MA(A,e){A|=0,e|=0;var r=0;do{r=0|kA(A,e,0,1)}while(2==(0|r));return 0|r}function QA(A,e,r,t,o){A|=0,e|=0,r|=0,t|=0,o|=0;var a,f,s,u,l,h,c,d,g,w,p,B,b,v,m,k,M,y,E=0,x=0,D=0,_=0,F=0;if(y=I,I=I+240|0,v=y+208|0,m=y,k=y+192|0,M=y+176|0,g=y+160|0,w=y+144|0,p=y+128|0,B=y+112|0,b=y+96|0,i[(E=y+224|0)>>2]=e,i[v>>2]=i[A>>2],i[v+4>>2]=i[A+4>>2],i[v+8>>2]=i[A+8>>2],i[v+12>>2]=i[A+12>>2],yA(v,E,m),i[o>>2]=0,(0|(d=t+r+(6==(0|t)&1)|0))<=(0|r))I=y;else{f=r+6|0,s=16928+((a=0|i[E>>2])<<2)|0,u=w+8|0,l=p+8|0,h=B+8|0,c=k+4|0,x=0,D=r,t=-1;A:for(;;){if(A=m+((E=(0|D)%6|0)<<4)|0,i[k>>2]=i[A>>2],i[k+4>>2]=i[A+4>>2],i[k+8>>2]=i[A+8>>2],i[k+12>>2]=i[A+12>>2],A=x,x=0|kA(k,a,0,1),(0|D)>(0|r)&0!=(0|RA(e))&&(1!=(0|A)&&(0|i[k>>2])!=(0|t))){switch(K(m+(((E+5|0)%6|0)<<4)+4|0,M),K(m+(E<<4)+4|0,g),_=+(0|i[s>>2]),n[w>>3]=3*_,n[u>>3]=0,F=-1.5*_,n[p>>3]=F,n[l>>3]=2.598076211353316*_,n[B>>3]=F,n[h>>3]=-2.598076211353316*_,E=0|i[v>>2],0|i[17008+(80*E|0)+(((0|t)==(0|E)?0|i[k>>2]:t)<<2)>>2]){case 1:A=p,t=w;break;case 3:A=B,t=p;break;case 2:A=w,t=B;break;default:A=8;break A}oe(M,g,t,A,b),0|ae(M,b)||0|ae(g,b)||(BA(b,0|i[v>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2]))}if((0|D)<(0|f)&&(K(c,M),BA(M,0|i[k>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])),(0|(D=D+1|0))>=(0|d)){A=3;break}t=0|i[k>>2]}3!=(0|A)?8==(0|A)&&Q(22557,22521,746,22602):I=y}}function yA(A,e,r){A|=0,e|=0,r|=0;var t,n=0,o=0,a=0,f=0,s=0;t=I,I=I+160|0,o=t,f=20336,s=(a=n=t+80|0)+72|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));f=20416,s=(a=o)+72|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));n=(s=0==(0|RA(0|i[e>>2])))?n:o,uA(o=A+4|0),lA(o),0|RA(0|i[e>>2])&&(iA(o),i[e>>2]=1+(0|i[e>>2])),i[r>>2]=i[A>>2],X(o,n,e=r+4|0),J(e),i[r+16>>2]=i[A>>2],X(o,n+12|0,e=r+20|0),J(e),i[r+32>>2]=i[A>>2],X(o,n+24|0,e=r+36|0),J(e),i[r+48>>2]=i[A>>2],X(o,n+36|0,e=r+52|0),J(e),i[r+64>>2]=i[A>>2],X(o,n+48|0,e=r+68|0),J(e),i[r+80>>2]=i[A>>2],X(o,n+60|0,r=r+84|0),J(r),I=t}function EA(A){var e;return e=(A=+A)<0?A+6.283185307179586:A,+(A>=6.283185307179586?e+-6.283185307179586:e)}function xA(A,e){return e|=0,+f(+(+n[(A|=0)>>3]-+n[e>>3]))<17453292519943298e-27?0|(e=+f(+(+n[A+8>>3]-+n[e+8>>3]))<17453292519943298e-27):0|(e=0)}function DA(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))*6371.007180918475}function _A(A,e,r){A|=0,r|=0;var t,i,o,a,f=0,u=0,d=0,g=0,B=0,b=0;return b=+n[(e|=0)>>3],o=+n[A>>3],B=+h(.5*(b-o)),d=+n[e+8>>3],i=+n[A+8>>3],g=+h(.5*(d-i)),t=+l(+o),a=+l(+b),g=2*+p(+ +s(+(g=B*B+g*(a*t*g))),+ +s(+(1-g))),B=+n[r>>3],b=+h(.5*(B-b)),f=+n[r+8>>3],d=+h(.5*(f-d)),u=+l(+B),d=2*+p(+ +s(+(d=b*b+d*(a*u*d))),+ +s(+(1-d))),B=+h(.5*(o-B)),f=+h(.5*(i-f)),f=2*+p(+ +s(+(f=B*B+f*(t*u*f))),+ +s(+(1-f))),4*+w(+ +s(+ +c(.5*(u=.5*(g+d+f)))*+c(.5*(u-g))*+c(.5*(u-d))*+c(.5*(u-f))))}function IA(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),45),M(),127&e|0}function FA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0;if(!(!0&134217728==(-16777216&(e|=0)|0)))return 0|(e=0);if(o=0|Qe(0|(A|=0),0|e,45),M(),(o&=127)>>>0>121)return 0|(e=0);r=0|Qe(0|A,0|e,52),M(),r&=15;do{if(0|r){for(i=1,t=0;;){if(n=0|Qe(0|A,0|e,3*(15-i|0)|0),M(),0!=(0|(n&=7))&(1^t)){if(1==(0|n)&0!=(0|S(o))){a=0,t=13;break}t=1}if(7==(0|n)){a=0,t=13;break}if(!(i>>>0>>0)){t=9;break}i=i+1|0}if(9==(0|t)){if(15!=(0|r))break;return 0|(a=1)}if(13==(0|t))return 0|a}}while(0);for(;;){if(a=0|Qe(0|A,0|e,3*(14-r|0)|0),M(),!(7==(7&a|0)&!0)){a=0,t=13;break}if(!(r>>>0<14)){a=1,t=13;break}r=r+1|0}return 13==(0|t)?0|a:0}function CA(A,e,r){r|=0;var t=0,i=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|(t&=15))>=(0|r)){if((0|t)!=(0|r))if(r>>>0<=15){if(A|=i=0|ye(0|r,0,52),e=0|M()|-15728641&e,(0|t)>(0|r))do{i=0|ye(7,0,3*(14-r|0)|0),r=r+1|0,A|=i,e=0|M()|e}while((0|r)<(0|t))}else e=0,A=0}else e=0,A=0;return k(0|e),0|A}function PA(A,e,r,t){r|=0,t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(f&=15))<=(0|r)){if((0|f)==(0|r))return i[(r=t)>>2]=A,void(i[r+4>>2]=e);if(n=(0|(u=0|ee(7,r-f|0)))/7|0,s=0|Qe(0|A,0|e,45),M(),0|S(127&s)){A:do{if(f)for(a=1;;){if(o=0|Qe(0|A,0|e,3*(15-a|0)|0),M(),0|(o&=7))break A;if(!(a>>>0>>0)){o=0;break}a=a+1|0}else o=0}while(0);a=0==(0|o)}else a=0;if(l=0|ye(f+1|0,0,52),o=0|M()|-15728641&e,PA(e=(l|A)&~(e=0|ye(7,0,0|(s=3*(14-f|0)|0))),f=o&~(0|M()),r,t),o=t+(n<<3)|0,!a)return PA((l=0|ye(1,0,0|s))|e,0|M()|f,r,o),l=o+(n<<3)|0,PA((u=0|ye(2,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(3,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(4,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(5,0,0|s))|e,0|M()|f,r,l),void PA((u=0|ye(6,0,0|s))|e,0|M()|f,r,l+(n<<3)|0);a=o+(n<<3)|0,(0|u)>6&&(_e(0|o,0,(l=(a>>>0>(u=o+8|0)>>>0?a:u)+-1+(0-o)|0)+8&-8|0),o=u+(l>>>3<<3)|0),PA((l=0|ye(2,0,0|s))|e,0|M()|f,r,o),l=o+(n<<3)|0,PA((u=0|ye(3,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(4,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(5,0,0|s))|e,0|M()|f,r,l),PA((u=0|ye(6,0,0|s))|e,0|M()|f,r,l+(n<<3)|0)}}function UA(A,e){var r=0,t=0,i=0;if(i=0|Qe(0|(A|=0),0|(e|=0),45),M(),!(0|S(127&i)))return 0|(i=0);i=0|Qe(0|A,0|e,52),M(),i&=15;A:do{if(i)for(t=1;;){if(r=0|Qe(0|A,0|e,3*(15-t|0)|0),M(),0|(r&=7))break A;if(!(t>>>0>>0)){r=0;break}t=t+1|0}else r=0}while(0);return 0|(i=0==(0|r)&1)}function GA(A,e){var r=0,t=0,i=0;if(i=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(i&=15))return 0|(i=0);for(t=1;;){if(r=0|Qe(0|A,0|e,3*(15-t|0)|0),M(),0|(r&=7)){t=5;break}if(!(t>>>0>>0)){r=0,t=5;break}t=t+1|0}return 5==(0|t)?0|r:0}function SA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0,f=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(f&=15))return f=A,k(0|(a=e)),0|f;for(a=1,r=0;;){t=0|ye(7,0,0|(n=3*(15-a|0)|0)),i=0|M(),o=0|Qe(0|A,0|e,0|n),M(),A=(n=0|ye(0|fA(7&o),0,0|n))|A&~t,e=(o=0|M())|e&~i;A:do{if(!r)if(0==(n&t|0)&0==(o&i|0))r=0;else if(t=0|Qe(0|A,0|e,52),M(),t&=15){r=1;e:for(;;){switch(o=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),7&o){case 1:break e;case 0:break;default:r=1;break A}if(!(r>>>0>>0)){r=1;break A}r=r+1|0}for(r=1;;){if(i=0|Qe(0|A,0|e,0|(o=3*(15-r|0)|0)),M(),n=0|ye(7,0,0|o),e&=~(0|M()),A=A&~n|(o=0|ye(0|fA(7&i),0,0|o)),e=0|e|M(),!(r>>>0>>0)){r=1;break}r=r+1|0}}else r=1}while(0);if(!(a>>>0>>0))break;a=a+1|0}return k(0|e),0|A}function TA(A,e){var r=0,t=0,i=0,n=0,o=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(t&=15))return t=A,k(0|(r=e)),0|t;for(r=1;o=0|Qe(0|A,0|e,0|(n=3*(15-r|0)|0)),M(),i=0|ye(7,0,0|n),e&=~(0|M()),A=(n=0|ye(0|fA(7&o),0,0|n))|A&~i,e=0|M()|e,r>>>0>>0;)r=r+1|0;return k(0|e),0|A}function VA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0,f=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(f&=15))return f=A,k(0|(a=e)),0|f;for(a=1,r=0;;){t=0|ye(7,0,0|(n=3*(15-a|0)|0)),i=0|M(),o=0|Qe(0|A,0|e,0|n),M(),A=(n=0|ye(0|sA(7&o),0,0|n))|A&~t,e=(o=0|M())|e&~i;A:do{if(!r)if(0==(n&t|0)&0==(o&i|0))r=0;else if(t=0|Qe(0|A,0|e,52),M(),t&=15){r=1;e:for(;;){switch(o=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),7&o){case 1:break e;case 0:break;default:r=1;break A}if(!(r>>>0>>0)){r=1;break A}r=r+1|0}for(r=1;;){if(n=0|ye(7,0,0|(i=3*(15-r|0)|0)),o=e&~(0|M()),e=0|Qe(0|A,0|e,0|i),M(),A=A&~n|(e=0|ye(0|sA(7&e),0,0|i)),e=0|o|M(),!(r>>>0>>0)){r=1;break}r=r+1|0}}else r=1}while(0);if(!(a>>>0>>0))break;a=a+1|0}return k(0|e),0|A}function HA(A,e){var r=0,t=0,i=0,n=0,o=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(t&=15))return t=A,k(0|(r=e)),0|t;for(r=1;n=0|ye(7,0,0|(o=3*(15-r|0)|0)),i=e&~(0|M()),e=0|Qe(0|A,0|e,0|o),M(),A=(e=0|ye(0|sA(7&e),0,0|o))|A&~n,e=0|M()|i,r>>>0>>0;)r=r+1|0;return k(0|e),0|A}function RA(A){return 0|(0|(A|=0))%2}function LA(A,e){A|=0;var r,t;return t=I,I=I+16|0,r=t,(e|=0)>>>0<=15&&2146435072!=(2146435072&i[A+4>>2]|0)&&2146435072!=(2146435072&i[A+8+4>>2]|0)?(!function(A,e,r){var t,i;t=I,I=I+16|0,pA(A|=0,e|=0,r|=0,i=t),W(i,r+4|0),I=t}(A,e,r),e=0|function(A,e){A|=0;var r,t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0;if(r=I,I=I+64|0,s=r+40|0,n=r+24|0,o=r+12|0,a=r,ye(0|(e|=0),0,52),t=134225919|M(),!e)return(0|i[A+4>>2])>2||(0|i[A+8>>2])>2||(0|i[A+12>>2])>2?(s=0,k(0|(f=0)),I=r,0|s):(ye(0|V(A),0,45),f=0|M()|t,s=-1,k(0|f),I=r,0|s);if(i[s>>2]=i[A>>2],i[s+4>>2]=i[A+4>>2],i[s+8>>2]=i[A+8>>2],i[s+12>>2]=i[A+12>>2],f=s+4|0,(0|e)>0)for(A=-1;i[n>>2]=i[f>>2],i[n+4>>2]=i[f+4>>2],i[n+8>>2]=i[f+8>>2],1&e?(eA(f),i[o>>2]=i[f>>2],i[o+4>>2]=i[f+4>>2],i[o+8>>2]=i[f+8>>2],tA(o)):(rA(f),i[o>>2]=i[f>>2],i[o+4>>2]=i[f+4>>2],i[o+8>>2]=i[f+8>>2],iA(o)),q(n,o,a),J(a),u=0|ye(7,0,0|(l=3*(15-e|0)|0)),t&=~(0|M()),A=(l=0|ye(0|AA(a),0,0|l))|A&~u,t=0|M()|t,(0|e)>1;)e=e+-1|0;else A=-1;A:do{if((0|i[f>>2])<=2&&(0|i[s+8>>2])<=2&&(0|i[s+12>>2])<=2){if(e=0|ye(0|(n=0|V(s)),0,45),e|=A,A=0|M()|-1040385&t,a=0|H(s),!(0|S(n))){if((0|a)<=0)break;for(o=0;;){if(n=0|Qe(0|e,0|A,52),M(),n&=15)for(t=1;s=0|Qe(0|e,0|A,0|(l=3*(15-t|0)|0)),M(),u=0|ye(7,0,0|l),A&=~(0|M()),e=e&~u|(l=0|ye(0|fA(7&s),0,0|l)),A=0|A|M(),t>>>0>>0;)t=t+1|0;if((0|(o=o+1|0))==(0|a))break A}}o=0|Qe(0|e,0|A,52),M(),o&=15;e:do{if(o){t=1;r:for(;;){switch(l=0|Qe(0|e,0|A,3*(15-t|0)|0),M(),7&l){case 1:break r;case 0:break;default:break e}if(!(t>>>0>>0))break e;t=t+1|0}if(0|R(n,0|i[s>>2]))for(t=1;u=0|ye(7,0,0|(s=3*(15-t|0)|0)),l=A&~(0|M()),A=0|Qe(0|e,0|A,0|s),M(),e=e&~u|(A=0|ye(0|sA(7&A),0,0|s)),A=0|l|M(),t>>>0>>0;)t=t+1|0;else for(t=1;s=0|Qe(0|e,0|A,0|(l=3*(15-t|0)|0)),M(),u=0|ye(7,0,0|l),A&=~(0|M()),e=e&~u|(l=0|ye(0|fA(7&s),0,0|l)),A=0|A|M(),t>>>0>>0;)t=t+1|0}}while(0);if((0|a)>0){t=0;do{e=0|SA(e,A),A=0|M(),t=t+1|0}while((0|t)!=(0|a))}}else e=0,A=0}while(0);return l=e,k(0|(u=A)),I=r,0|l}(r,e),A=0|M()):(A=0,e=0),k(0|A),I=t,0|e}function zA(A,e,r){var t,n=0,o=0,a=0;if(t=(r|=0)+4|0,o=0|Qe(0|(A|=0),0|(e|=0),52),M(),o&=15,a=0|Qe(0|A,0|e,45),M(),n=0==(0|o),0|S(127&a)){if(n)return 0|(a=1);n=1}else{if(n)return 0|(a=0);n=0==(0|i[t>>2])&&0==(0|i[r+8>>2])?0!=(0|i[r+12>>2])&1:1}for(r=1;1&r?tA(t):iA(t),a=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),nA(t,7&a),r>>>0>>0;)r=r+1|0;return 0|n}function YA(A,e,r){r|=0;var t,n,o=0,a=0,f=0,s=0,u=0,l=0;n=I,I=I+16|0,t=n,l=0|Qe(0|(A|=0),0|(e|=0),45),M(),l&=127;A:do{if(0!=(0|S(l))&&(f=0|Qe(0|A,0|e,52),M(),0!=(0|(f&=15)))){o=1;e:for(;;){switch(u=0|Qe(0|A,0|e,3*(15-o|0)|0),M(),7&u){case 5:break e;case 0:break;default:o=e;break A}if(!(o>>>0>>0)){o=e;break A}o=o+1|0}for(a=1,o=e;s=0|ye(7,0,0|(e=3*(15-a|0)|0)),u=o&~(0|M()),o=0|Qe(0|A,0|o,0|e),M(),A=A&~s|(o=0|ye(0|sA(7&o),0,0|e)),o=0|u|M(),a>>>0>>0;)a=a+1|0}else o=e}while(0);if(u=7728+(28*l|0)|0,i[r>>2]=i[u>>2],i[r+4>>2]=i[u+4>>2],i[r+8>>2]=i[u+8>>2],i[r+12>>2]=i[u+12>>2],0|zA(A,o,r)){if(s=r+4|0,i[t>>2]=i[s>>2],i[t+4>>2]=i[s+4>>2],i[t+8>>2]=i[s+8>>2],f=0|Qe(0|A,0|o,52),M(),u=15&f,1&f?(iA(s),f=u+1|0):f=u,0|S(l)){A:do{if(u)for(e=1;;){if(a=0|Qe(0|A,0|o,3*(15-e|0)|0),M(),0|(a&=7)){o=a;break A}if(!(e>>>0>>0)){o=0;break}e=e+1|0}else o=0}while(0);o=4==(0|o)&1}else o=0;if(0|kA(r,f,o,0)){if(0|S(l))do{}while(0!=(0|kA(r,f,0,0)));(0|f)!=(0|u)&&rA(s)}else(0|f)!=(0|u)&&(i[s>>2]=i[t>>2],i[s+4>>2]=i[t+4>>2],i[s+8>>2]=i[t+8>>2]);I=n}else I=n}function OA(A,e,r){r|=0;var t,i;t=I,I=I+16|0,YA(A|=0,e|=0,i=t),e=0|Qe(0|A,0|e,52),M(),bA(i,15&e,r),I=t}function jA(A,e,r){r|=0;var t,i,n=0,o=0;i=I,I=I+16|0,YA(A|=0,e|=0,t=i),n=0|Qe(0|A,0|e,45),M(),n=0==(0|S(127&n)),o=0|Qe(0|A,0|e,52),M(),o&=15;A:do{if(!n){if(0|o)for(n=1;;){if(!(0==((0|ye(7,0,3*(15-n|0)|0))&A|0)&0==((0|M())&e|0)))break A;if(!(n>>>0>>0))break;n=n+1|0}return vA(t,o,0,5,r),void(I=i)}}while(0);QA(t,o,0,6,r),I=i}function NA(A,e){e|=0;var r,t=0,n=0,o=0,a=0,f=0,s=0;if(ye(0|(A|=0),0,52),r=134225919|M(),(0|A)<1){n=0,t=0;do{0|S(n)&&(ye(0|n,0,45),f=0|r|M(),i[(A=e+(t<<3)|0)>>2]=-1,i[A+4>>2]=f,t=t+1|0),n=n+1|0}while(122!=(0|n))}else{f=0,t=0;do{if(0|S(f)){for(ye(0|f,0,45),n=1,o=-1,a=0|r|M();o&=~(s=0|ye(7,0,3*(15-n|0)|0)),a&=~(0|M()),(0|n)!=(0|A);)n=n+1|0;i[(s=e+(t<<3)|0)>>2]=o,i[s+4>>2]=a,t=t+1|0}f=f+1|0}while(122!=(0|f))}}function ZA(A,e,r,t){var n,o=0,a=0,f=0,s=0,u=0;if(n=I,I=I+64|0,f=n,(0|(A|=0))==(0|(r|=0))&(0|(e|=0))==(0|(t|=0))|!1|134217728!=(2013265920&e|0)|!1|134217728!=(2013265920&t|0))return I=n,0|(f=0);if(o=0|Qe(0|A,0|e,52),M(),o&=15,a=0|Qe(0|r,0|t,52),M(),(0|o)!=(15&a|0))return I=n,0|(f=0);if(a=o+-1|0,o>>>0>1&&(u=0|CA(A,e,a),s=0|M(),(0|u)==(0|(a=0|CA(r,t,a)))&(0|s)==(0|M()))){if(o=0|Qe(0|A,0|e,0|(a=3*(15^o)|0)),M(),o&=7,a=0|Qe(0|r,0|t,0|a),M(),0==(0|o)|0==(0|(a&=7)))return I=n,0|(u=1);if((0|i[21136+(o<<2)>>2])==(0|a))return I=n,0|(u=1);if((0|i[21168+(o<<2)>>2])==(0|a))return I=n,0|(u=1)}a=(o=f)+56|0;do{i[o>>2]=0,o=o+4|0}while((0|o)<(0|a));return F(A,e,1,f),o=(0|i[(u=f)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+8|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+16|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+24|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+32|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+40|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)?1:1&((0|i[(o=f+48|0)>>2])==(0|r)?(0|i[o+4>>2])==(0|t):0),I=n,0|(u=o)}function WA(A,e,r){r|=0;var t,n,o,a,f=0;if(o=I,I=I+16|0,n=o,f=0|Qe(0|(A|=0),0|(e|=0),56),M(),-1==(0|(e=0|function(A,e,r){r|=0;var t=0,n=0;if(t=0|UA(A=A|0,e=e|0),(r+-1|0)>>>0>5)return 0|(r=-1);if(1==(0|r)&(n=0!=(0|t)))return 0|(r=-1);return t=0|function(A,e){var r=0,t=0,n=0,o=0,a=0,f=0,s=0,u=0;if(u=I,I=I+32|0,o=u,YA(A=A|0,e=e|0,n=u+16|0),a=0|IA(A,e),s=0|GA(A,e),function(A,e){A=7728+(28*(A|=0)|0)|0,i[(e|=0)>>2]=i[A>>2],i[e+4>>2]=i[A+4>>2],i[e+8>>2]=i[A+8>>2],i[e+12>>2]=i[A+12>>2]}(a,o),e=0|function(A,e){A|=0;var r=0,t=0;if((e|=0)>>>0>20)return-1;do{if((0|i[11152+(216*e|0)>>2])!=(0|A))if((0|i[11152+(216*e|0)+8>>2])!=(0|A))if((0|i[11152+(216*e|0)+16>>2])!=(0|A))if((0|i[11152+(216*e|0)+24>>2])!=(0|A))if((0|i[11152+(216*e|0)+32>>2])!=(0|A))if((0|i[11152+(216*e|0)+40>>2])!=(0|A))if((0|i[11152+(216*e|0)+48>>2])!=(0|A))if((0|i[11152+(216*e|0)+56>>2])!=(0|A))if((0|i[11152+(216*e|0)+64>>2])!=(0|A))if((0|i[11152+(216*e|0)+72>>2])!=(0|A))if((0|i[11152+(216*e|0)+80>>2])!=(0|A))if((0|i[11152+(216*e|0)+88>>2])!=(0|A))if((0|i[11152+(216*e|0)+96>>2])!=(0|A))if((0|i[11152+(216*e|0)+104>>2])!=(0|A))if((0|i[11152+(216*e|0)+112>>2])!=(0|A))if((0|i[11152+(216*e|0)+120>>2])!=(0|A))if((0|i[11152+(216*e|0)+128>>2])!=(0|A)){if((0|i[11152+(216*e|0)+136>>2])!=(0|A)){if((0|i[11152+(216*e|0)+144>>2])==(0|A)){A=0,r=2,t=0;break}if((0|i[11152+(216*e|0)+152>>2])==(0|A)){A=0,r=2,t=1;break}if((0|i[11152+(216*e|0)+160>>2])==(0|A)){A=0,r=2,t=2;break}if((0|i[11152+(216*e|0)+168>>2])==(0|A)){A=1,r=2,t=0;break}if((0|i[11152+(216*e|0)+176>>2])==(0|A)){A=1,r=2,t=1;break}if((0|i[11152+(216*e|0)+184>>2])==(0|A)){A=1,r=2,t=2;break}if((0|i[11152+(216*e|0)+192>>2])==(0|A)){A=2,r=2,t=0;break}if((0|i[11152+(216*e|0)+200>>2])==(0|A)){A=2,r=2,t=1;break}if((0|i[11152+(216*e|0)+208>>2])==(0|A)){A=2,r=2,t=2;break}return-1}A=2,r=1,t=2}else A=2,r=1,t=1;else A=2,r=1,t=0;else A=1,r=1,t=2;else A=1,r=1,t=1;else A=1,r=1,t=0;else A=0,r=1,t=2;else A=0,r=1,t=1;else A=0,r=1,t=0;else A=2,r=0,t=2;else A=2,r=0,t=1;else A=2,r=0,t=0;else A=1,r=0,t=2;else A=1,r=0,t=1;else A=1,r=0,t=0;else A=0,r=0,t=2;else A=0,r=0,t=1;else A=0,r=0,t=0}while(0);return 0|i[11152+(216*e|0)+(72*r|0)+(24*A|0)+(t<<3)+4>>2]}(a,0|i[n>>2]),!(0|S(a)))return I=u,0|(s=e);switch(0|a){case 4:A=0,r=14;break;case 14:A=1,r=14;break;case 24:A=2,r=14;break;case 38:A=3,r=14;break;case 49:A=4,r=14;break;case 58:A=5,r=14;break;case 63:A=6,r=14;break;case 72:A=7,r=14;break;case 83:A=8,r=14;break;case 97:A=9,r=14;break;case 107:A=10,r=14;break;case 117:A=11,r=14;break;default:f=0,t=0}14==(0|r)&&(f=0|i[22096+(24*A|0)+8>>2],t=0|i[22096+(24*A|0)+16>>2]);(0|(A=0|i[n>>2]))!=(0|i[o>>2])&&(a=0|T(a))|(0|(A=0|i[n>>2]))==(0|t)&&(e=(e+1|0)%6|0);if(3==(0|s)&(0|A)==(0|t))return I=u,0|(s=(e+5|0)%6|0);if(!(5==(0|s)&(0|A)==(0|f)))return I=u,0|(s=e);return I=u,0|(s=(e+1|0)%6|0)}(A,e),n?0|(r=(5-t+(0|i[22384+(r<<2)>>2])|0)%5|0):0|(r=(6-t+(0|i[22416+(r<<2)>>2])|0)%6|0)}(t=(a=!0&268435456==(2013265920&e|0))?A:0,A=a?-2130706433&e|134217728:0,7&f))))return i[r>>2]=0,void(I=o);YA(t,A,n),f=0|Qe(0|t,0|A,52),M(),f&=15,0|UA(t,A)?vA(n,f,e,2,r):QA(n,f,e,2,r),I=o}function JA(A){A|=0;var e,r,t=0;return(e=0|be(1,12))||Q(22691,22646,49,22704),0|(t=0|i[(r=A+4|0)>>2])?(i[(t=t+8|0)>>2]=e,i[r>>2]=e,0|e):(0|i[A>>2]&&Q(22721,22646,61,22744),i[(t=A)>>2]=e,i[r>>2]=e,0|e)}function KA(A,e){A|=0,e|=0;var r,t;return(t=0|pe(24))||Q(22758,22646,78,22772),i[t>>2]=i[e>>2],i[t+4>>2]=i[e+4>>2],i[t+8>>2]=i[e+8>>2],i[t+12>>2]=i[e+12>>2],i[t+16>>2]=0,0|(r=0|i[(e=A+4|0)>>2])?(i[r+16>>2]=t,i[e>>2]=t,0|t):(0|i[A>>2]&&Q(22787,22646,82,22772),i[A>>2]=t,i[e>>2]=t,0|t)}function XA(A){var e,r,t=0,o=0,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,y=0,E=0,x=0,D=0,_=0,I=0,F=0,C=0,P=0,U=0,G=0,S=0;if(0|i[(s=(A|=0)+8|0)>>2])return 0|(S=1);if(!(a=0|i[A>>2]))return 0|(S=0);t=a,o=0;do{o=o+1|0,t=0|i[t+8>>2]}while(0!=(0|t));if(o>>>0<2)return 0|(S=0);(r=0|pe(o<<2))||Q(22807,22646,317,22826),(e=0|pe(o<<5))||Q(22848,22646,321,22826),i[A>>2]=0,i[(D=A+4|0)>>2]=0,i[s>>2]=0,o=0,U=0,x=0,w=0;A:for(;;){if(g=0|i[a>>2]){u=0,l=g;do{if(c=+n[l+8>>3],t=l,l=0|i[l+16>>2],h=+n[(s=(d=0==(0|l))?g:l)+8>>3],+f(+(c-h))>3.141592653589793){S=14;break}u+=(h-c)*(+n[t>>3]+ +n[s>>3])}while(!d);if(14==(0|S)){S=0,u=0,t=g;do{E=+n[t+8>>3],C=0|i[(P=t+16|0)>>2],y=+n[(C=0==(0|C)?g:C)+8>>3],u+=(+n[t>>3]+ +n[C>>3])*((y<0?y+6.283185307179586:y)-(E<0?E+6.283185307179586:E)),t=0|i[(0==(0|t)?a:P)>>2]}while(0!=(0|t))}u>0?(i[r+(U<<2)>>2]=a,U=U+1|0,s=x,t=w):S=19}else S=19;if(19==(0|S)){S=0;do{if(!o){if(w){s=D,l=w+8|0,t=a,o=A;break}if(0|i[A>>2]){S=27;break A}s=D,l=A,t=a,o=A;break}if(0|i[(t=o+8|0)>>2]){S=21;break A}if(!(o=0|be(1,12))){S=23;break A}i[t>>2]=o,s=o+4|0,l=o,t=w}while(0);if(i[l>>2]=a,i[s>>2]=a,l=e+(x<<5)|0,d=0|i[a>>2]){for(n[(g=e+(x<<5)+8|0)>>3]=17976931348623157e292,n[(w=e+(x<<5)+24|0)>>3]=17976931348623157e292,n[l>>3]=-17976931348623157e292,n[(p=e+(x<<5)+16|0)>>3]=-17976931348623157e292,k=17976931348623157e292,M=-17976931348623157e292,s=0,B=d,c=17976931348623157e292,v=17976931348623157e292,m=-17976931348623157e292,h=-17976931348623157e292;u=+n[B>>3],E=+n[B+8>>3],B=0|i[B+16>>2],y=+n[((b=0==(0|B))?d:B)+8>>3],u>3]=u,c=u),E>3]=E,v=E),u>m?n[l>>3]=u:u=m,E>h&&(n[p>>3]=E,h=E),k=E>0&EM?E:M,s|=+f(+(E-y))>3.141592653589793,!b;)m=u;s&&(n[p>>3]=M,n[w>>3]=k)}else i[l>>2]=0,i[l+4>>2]=0,i[l+8>>2]=0,i[l+12>>2]=0,i[l+16>>2]=0,i[l+20>>2]=0,i[l+24>>2]=0,i[l+28>>2]=0;s=x+1|0}if(a=0|i[(P=a+8|0)>>2],i[P>>2]=0,!a){S=45;break}x=s,w=t}if(21==(0|S))Q(22624,22646,35,22658);else if(23==(0|S))Q(22678,22646,37,22658);else if(27==(0|S))Q(22721,22646,61,22744);else if(45==(0|S)){A:do{if((0|U)>0){for(P=0==(0|s),F=s<<2,C=0==(0|A),I=0,t=0;;){if(_=0|i[r+(I<<2)>>2],P)S=73;else{if(!(x=0|pe(F))){S=50;break}if(!(D=0|pe(F))){S=52;break}e:do{if(C)o=0;else{for(s=0,o=0,l=A;a=e+(s<<5)|0,0|qA(0|i[l>>2],a,0|i[_>>2])?(i[x+(o<<2)>>2]=l,i[D+(o<<2)>>2]=a,b=o+1|0):b=o,l=0|i[l+8>>2];)s=s+1|0,o=b;if((0|b)>0)if(a=0|i[x>>2],1==(0|b))o=a;else for(p=0,B=-1,o=a,w=a;;){for(d=0|i[w>>2],a=0,l=0;g=(0|(s=0|i[i[x+(l<<2)>>2]>>2]))==(0|d)?a:a+(1&(0|qA(s,0|i[D+(l<<2)>>2],0|i[d>>2])))|0,(0|(l=l+1|0))!=(0|b);)a=g;if(o=(s=(0|g)>(0|B))?w:o,(0|(a=p+1|0))==(0|b))break e;p=a,B=s?g:B,w=0|i[x+(a<<2)>>2]}else o=0}}while(0);if(Be(x),Be(D),o){if(a=0|i[(s=o+4|0)>>2])o=a+8|0;else if(0|i[o>>2]){S=70;break}i[o>>2]=_,i[s>>2]=_}else S=73}if(73==(0|S)){if(S=0,0|(t=0|i[_>>2]))do{D=t,t=0|i[t+16>>2],Be(D)}while(0!=(0|t));Be(_),t=2}if((0|(I=I+1|0))>=(0|U)){G=t;break A}}50==(0|S)?Q(22863,22646,249,22882):52==(0|S)?Q(22901,22646,252,22882):70==(0|S)&&Q(22721,22646,61,22744)}else G=0}while(0);return Be(r),Be(e),0|(S=G)}return 0}function qA(A,e,r){A|=0;var t,o=0,a=0,f=0,s=0,u=0,l=0,h=0;if(!(0|O(e|=0,r|=0)))return 0|(A=0);if(e=0|Y(e),t=+n[r>>3],o=e&(o=+n[r+8>>3])<0?o+6.283185307179586:o,!(A=0|i[A>>2]))return 0|(A=0);if(e){e=0,r=A;A:for(;;){for(;s=+n[r>>3],l=+n[r+8>>3],h=0|i[(r=r+16|0)>>2],f=+n[(h=0==(0|h)?A:h)>>3],a=+n[h+8>>3],s>f?(u=s,s=l):(u=f,f=s,s=a,a=l),tu;)if(!(r=0|i[r>>2])){r=22;break A}if(o=(s=s<0?s+6.283185307179586:s)==o|(l=a<0?a+6.283185307179586:a)==o?o+-2220446049250313e-31:o,((l+=(t-f)/(u-f)*(s-l))<0?l+6.283185307179586:l)>o&&(e^=1),!(r=0|i[r>>2])){r=22;break}}if(22==(0|r))return 0|e}else{e=0,r=A;A:for(;;){for(;s=+n[r>>3],l=+n[r+8>>3],h=0|i[(r=r+16|0)>>2],f=+n[(h=0==(0|h)?A:h)>>3],a=+n[h+8>>3],s>f?(u=s,s=l):(u=f,f=s,s=a,a=l),tu;)if(!(r=0|i[r>>2])){r=22;break A}if(a+(t-f)/(u-f)*(s-a)>(o=s==o|a==o?o+-2220446049250313e-31:o)&&(e^=1),!(r=0|i[r>>2])){r=22;break}}if(22==(0|r))return 0|e}return 0}function $A(A,e,r,n,o){r|=0,n|=0,o|=0;var a,f,s,u,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0;if(u=I,I=I+32|0,v=u+16|0,s=u,l=0|Qe(0|(A|=0),0|(e|=0),52),M(),l&=15,p=0|Qe(0|r,0|n,52),M(),(0|l)!=(15&p|0))return I=u,0|(v=1);if(g=0|Qe(0|A,0|e,45),M(),g&=127,w=0|Qe(0|r,0|n,45),M(),p=(0|g)!=(0|(w&=127))){if(7==(0|(c=0|z(g,w))))return I=u,0|(v=2);7==(0|(d=0|z(w,g)))?Q(22925,22949,151,22959):(B=c,h=d)}else B=0,h=0;a=0|S(g),f=0|S(w),i[v>>2]=0,i[v+4>>2]=0,i[v+8>>2]=0,i[v+12>>2]=0;do{if(B){if(c=(0|(w=0|i[4304+(28*g|0)+(B<<2)>>2]))>0,f)if(c){g=0,d=r,c=n;do{d=0|VA(d,c),c=0|M(),1==(0|(h=0|sA(h)))&&(h=0|sA(1)),g=g+1|0}while((0|g)!=(0|w));w=h,g=d,d=c}else w=h,g=r,d=n;else if(c){g=0,d=r,c=n;do{d=0|HA(d,c),c=0|M(),h=0|sA(h),g=g+1|0}while((0|g)!=(0|w));w=h,g=d,d=c}else w=h,g=r,d=n;if(zA(g,d,v),p||Q(22972,22949,181,22959),(c=0!=(0|a))&(h=0!=(0|f))&&Q(22999,22949,182,22959),c){if(h=0|GA(A,e),0|t[22032+(7*h|0)+B>>0]){l=3;break}g=d=0|i[21200+(28*h|0)+(B<<2)>>2],b=26}else if(h){if(h=0|GA(g,d),0|t[22032+(7*h|0)+w>>0]){l=4;break}g=0,d=0|i[21200+(28*w|0)+(h<<2)>>2],b=26}else h=0;if(26==(0|b))if((0|d)<=-1&&Q(23030,22949,212,22959),(0|g)<=-1&&Q(23053,22949,213,22959),(0|d)>0){c=v+4|0,h=0;do{aA(c),h=h+1|0}while((0|h)!=(0|d));h=g}else h=g;if(i[s>>2]=0,i[s+4>>2]=0,i[s+8>>2]=0,nA(s,B),0|l)for(;0|RA(l)?tA(s):iA(s),(0|l)>1;)l=l+-1|0;if((0|h)>0){l=0;do{aA(s),l=l+1|0}while((0|l)!=(0|h))}X(b=v+4|0,s,b),J(b),b=50}else if(zA(r,n,v),0!=(0|a)&0!=(0|f))if((0|w)!=(0|g)&&Q(23077,22949,243,22959),h=0|GA(A,e),l=0|GA(r,n),0|t[22032+(7*h|0)+l>>0])l=5;else if((0|(h=0|i[21200+(28*h|0)+(l<<2)>>2]))>0){c=v+4|0,l=0;do{aA(c),l=l+1|0}while((0|l)!=(0|h));b=50}else b=50;else b=50}while(0);return 50==(0|b)&&(l=v+4|0,i[o>>2]=i[l>>2],i[o+4>>2]=i[l+4>>2],i[o+8>>2]=i[l+8>>2],l=0),I=u,0|(v=l)}function Ae(A,e,r,t){r|=0,t|=0;var n,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0;if(o=I,I=I+48|0,s=o+36|0,u=o+24|0,l=o+12|0,h=o,f=0|Qe(0|(A|=0),0|(e|=0),52),M(),f&=15,d=0|Qe(0|A,0|e,45),M(),n=0|S(d&=127),ye(0|f,0,52),p=134225919|M(),i[(w=t)>>2]=-1,i[w+4>>2]=p,!f)return(0|i[r>>2])>1||(0|i[r+4>>2])>1||(0|i[r+8>>2])>1||127==(0|(a=0|L(d,0|AA(r))))?(I=o,0|(p=1)):(g=0|ye(0|a,0,45),w=0|M(),w=-1040385&i[(d=t)+4>>2]|w,i[(p=t)>>2]=i[d>>2]|g,i[p+4>>2]=w,I=o,0|(p=0));for(i[s>>2]=i[r>>2],i[s+4>>2]=i[r+4>>2],i[s+8>>2]=i[r+8>>2];i[u>>2]=i[s>>2],i[u+4>>2]=i[s+4>>2],i[u+8>>2]=i[s+8>>2],0|RA(f)?(eA(s),i[l>>2]=i[s>>2],i[l+4>>2]=i[s+4>>2],i[l+8>>2]=i[s+8>>2],tA(l)):(rA(s),i[l>>2]=i[s>>2],i[l+4>>2]=i[s+4>>2],i[l+8>>2]=i[s+8>>2],iA(l)),q(u,l,h),J(h),B=0|i[(w=t)>>2],w=0|i[w+4>>2],r=0|ye(7,0,0|(b=3*(15-f|0)|0)),w&=~(0|M()),b=0|ye(0|AA(h),0,0|b),w=0|M()|w,i[(p=t)>>2]=b|B&~r,i[p+4>>2]=w,(0|f)>1;)f=f+-1|0;A:do{if((0|i[s>>2])<=1&&(0|i[s+4>>2])<=1&&(0|i[s+8>>2])<=1){h=127==(0|(u=0|L(d,f=0|AA(s))))?0:0|S(u);e:do{if(f){if(n){if(s=21408+(28*(0|GA(A,e))|0)+(f<<2)|0,(0|(s=0|i[s>>2]))>0){r=0;do{f=0|fA(f),r=r+1|0}while((0|r)!=(0|s))}if(1==(0|f)){a=3;break A}127==(0|(r=0|L(d,f)))&&Q(23104,22949,376,23134),0|S(r)?Q(23147,22949,377,23134):(g=s,c=f,a=r)}else g=0,c=f,a=u;if((0|(l=0|i[4304+(28*d|0)+(c<<2)>>2]))<=-1&&Q(23178,22949,384,23134),!h){if((0|g)<=-1&&Q(23030,22949,417,23134),0|g){f=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];do{r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,f=f+1|0}while((0|f)<(0|g))}if((0|l)<=0){f=54;break}for(f=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];;)if(r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,(0|(f=f+1|0))==(0|l)){f=54;break e}}if(7==(0|(u=0|z(a,d)))&&Q(22925,22949,393,23134),r=0|i[(f=t)>>2],f=0|i[f+4>>2],(0|l)>0){s=0;do{r=0|TA(r,f),f=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=f,s=s+1|0}while((0|s)!=(0|l))}if(r=0|GA(r,f),b=0|T(a),(0|(r=0|i[(b?21824:21616)+(28*u|0)+(r<<2)>>2]))<=-1&&Q(23030,22949,412,23134),r){f=0,s=0|i[(u=t)>>2],u=0|i[u+4>>2];do{s=0|SA(s,u),u=0|M(),i[(b=t)>>2]=s,i[b+4>>2]=u,f=f+1|0}while((0|f)<(0|r));f=54}else f=54}else if(0!=(0|n)&0!=(0|h))if(f=21408+(28*(b=0|GA(A,e))|0)+((0|GA(0|i[(f=t)>>2],0|i[f+4>>2]))<<2)|0,(0|(f=0|i[f>>2]))<=-1&&Q(23201,22949,433,23134),f){a=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];do{r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,a=a+1|0}while((0|a)<(0|f));a=u,f=54}else a=u,f=55;else a=u,f=54}while(0);if(54==(0|f)&&h&&(f=55),55==(0|f)&&1==(0|GA(0|i[(b=t)>>2],0|i[b+4>>2]))){a=4;break}p=0|i[(b=t)>>2],b=-1040385&i[b+4>>2],B=0|ye(0|a,0,45),b=0|b|M(),i[(a=t)>>2]=p|B,i[a+4>>2]=b,a=0}else a=2}while(0);return I=o,0|(b=a)}function ee(A,e){var r=0;if(!(e|=0))return 0|(r=1);r=A|=0,A=1;do{A=0|b(0==(1&e|0)?1:r,A),e>>=1,r=0|b(r,r)}while(0!=(0|e));return 0|A}function re(A,e,r){A|=0;var t,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0;if(!(0|O(e|=0,r|=0)))return 0|(d=0);if(e=0|Y(e),o=+n[r>>3],a=e&(a=+n[r+8>>3])<0?a+6.283185307179586:a,(0|(d=0|i[A>>2]))<=0)return 0|(d=0);if(t=0|i[A+4>>2],e){e=0,r=-1,A=0;A:for(;;){for(c=A;u=+n[t+(c<<4)>>3],h=+n[t+(c<<4)+8>>3],s=+n[t+((A=(r+2|0)%(0|d)|0)<<4)>>3],f=+n[t+(A<<4)+8>>3],u>s?(l=u,u=h):(l=s,s=u,u=f,f=h),ol;){if(!((0|(r=c+1|0))<(0|d))){r=22;break A}A=c,c=r,r=A}if(a=(u=u<0?u+6.283185307179586:u)==a|(h=f<0?f+6.283185307179586:f)==a?a+-2220446049250313e-31:a,((h+=(o-s)/(l-s)*(u-h))<0?h+6.283185307179586:h)>a&&(e^=1),(0|(A=c+1|0))>=(0|d)){r=22;break}r=c}if(22==(0|r))return 0|e}else{e=0,r=-1,A=0;A:for(;;){for(c=A;u=+n[t+(c<<4)>>3],h=+n[t+(c<<4)+8>>3],s=+n[t+((A=(r+2|0)%(0|d)|0)<<4)>>3],f=+n[t+(A<<4)+8>>3],u>s?(l=u,u=h):(l=s,s=u,u=f,f=h),ol;){if(!((0|(r=c+1|0))<(0|d))){r=22;break A}A=c,c=r,r=A}if(f+(o-s)/(l-s)*(u-f)>(a=u==a|f==a?a+-2220446049250313e-31:a)&&(e^=1),(0|(A=c+1|0))>=(0|d)){r=22;break}r=c}if(22==(0|r))return 0|e}return 0}function te(A,e){e|=0;var r,t,o,a,s,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0;if(!(t=0|i[(A|=0)>>2]))return i[e>>2]=0,i[e+4>>2]=0,i[e+8>>2]=0,i[e+12>>2]=0,i[e+16>>2]=0,i[e+20>>2]=0,i[e+24>>2]=0,void(i[e+28>>2]=0);if(n[(o=e+8|0)>>3]=17976931348623157e292,n[(a=e+24|0)>>3]=17976931348623157e292,n[e>>3]=-17976931348623157e292,n[(s=e+16|0)>>3]=-17976931348623157e292,!((0|t)<=0)){for(r=0|i[A+4>>2],p=17976931348623157e292,B=-17976931348623157e292,b=0,A=-1,c=17976931348623157e292,d=17976931348623157e292,w=-17976931348623157e292,l=-17976931348623157e292,v=0;u=+n[r+(v<<4)>>3],g=+n[r+(v<<4)+8>>3],h=+n[r+(((0|(A=A+2|0))==(0|t)?0:A)<<4)+8>>3],u>3]=u,c=u),g>3]=g,d=g),u>w?n[e>>3]=u:u=w,g>l&&(n[s>>3]=g,l=g),p=g>0&gB?g:B,b|=+f(+(g-h))>3.141592653589793,(0|(A=v+1|0))!=(0|t);)m=v,w=u,v=A,A=m;b&&(n[s>>3]=B,n[a>>3]=p)}}function ie(A,e){e|=0;var r,t=0,o=0,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,Q=0,y=0,E=0;if(B=0|i[(A|=0)>>2]){if(n[(b=e+8|0)>>3]=17976931348623157e292,n[(v=e+24|0)>>3]=17976931348623157e292,n[e>>3]=-17976931348623157e292,n[(m=e+16|0)>>3]=-17976931348623157e292,(0|B)>0){for(a=0|i[A+4>>2],w=17976931348623157e292,p=-17976931348623157e292,o=0,t=-1,h=17976931348623157e292,c=17976931348623157e292,g=-17976931348623157e292,u=-17976931348623157e292,k=0;s=+n[a+(k<<4)>>3],d=+n[a+(k<<4)+8>>3],l=+n[a+(((0|(y=t+2|0))==(0|B)?0:y)<<4)+8>>3],s>3]=s,h=s),d>3]=d,c=d),s>g?n[e>>3]=s:s=g,d>u&&(n[m>>3]=d,u=d),w=d>0&dp?d:p,o|=+f(+(d-l))>3.141592653589793,(0|(t=k+1|0))!=(0|B);)y=k,g=s,k=t,t=y;o&&(n[m>>3]=p,n[v>>3]=w)}}else i[e>>2]=0,i[e+4>>2]=0,i[e+8>>2]=0,i[e+12>>2]=0,i[e+16>>2]=0,i[e+20>>2]=0,i[e+24>>2]=0,i[e+28>>2]=0;if(!((0|(t=0|i[(y=A+8|0)>>2]))<=0)){r=A+12|0,Q=0;do{if(a=0|i[r>>2],o=Q,v=e+((Q=Q+1|0)<<5)|0,m=0|i[a+(o<<3)>>2]){if(n[(k=e+(Q<<5)+8|0)>>3]=17976931348623157e292,n[(A=e+(Q<<5)+24|0)>>3]=17976931348623157e292,n[v>>3]=-17976931348623157e292,n[(M=e+(Q<<5)+16|0)>>3]=-17976931348623157e292,(0|m)>0){for(B=0|i[a+(o<<3)+4>>2],w=17976931348623157e292,p=-17976931348623157e292,a=0,o=-1,b=0,h=17976931348623157e292,c=17976931348623157e292,d=-17976931348623157e292,u=-17976931348623157e292;s=+n[B+(b<<4)>>3],g=+n[B+(b<<4)+8>>3],l=+n[B+(((0|(o=o+2|0))==(0|m)?0:o)<<4)+8>>3],s>3]=s,h=s),g>3]=g,c=g),s>d?n[v>>3]=s:s=d,g>u&&(n[M>>3]=g,u=g),w=g>0&gp?g:p,a|=+f(+(g-l))>3.141592653589793,(0|(o=b+1|0))!=(0|m);)E=b,b=o,d=s,o=E;a&&(n[M>>3]=p,n[A>>3]=w)}}else i[v>>2]=0,i[v+4>>2]=0,i[v+8>>2]=0,i[v+12>>2]=0,i[v+16>>2]=0,i[v+20>>2]=0,i[v+24>>2]=0,i[v+28>>2]=0,t=0|i[y>>2]}while((0|Q)<(0|t))}}function ne(A,e,r){var t=0,n=0,o=0;if(!(0|re(A|=0,e|=0,r|=0)))return 0|(n=0);if((0|i[(n=A+8|0)>>2])<=0)return 0|(n=1);for(t=A+12|0,A=0;;){if(o=A,A=A+1|0,0|re((0|i[t>>2])+(o<<3)|0,e+(A<<5)|0,r)){A=0,t=6;break}if((0|A)>=(0|i[n>>2])){A=1,t=6;break}}return 6==(0|t)?0|A:0}function oe(A,e,r,t,i){e|=0,r|=0,t|=0,i|=0;var o,a,f,s,u,l,h,c=0;s=+n[(A|=0)>>3],f=+n[e>>3]-s,a=+n[A+8>>3],o=+n[e+8>>3]-a,l=+n[r>>3],c=((c=+n[t>>3]-l)*(a-(h=+n[r+8>>3]))-(s-l)*(u=+n[t+8>>3]-h))/(f*u-o*c),n[i>>3]=s+f*c,n[i+8>>3]=a+o*c}function ae(A,e){return e|=0,+n[(A|=0)>>3]!=+n[e>>3]?0|(e=0):0|(e=+n[A+8>>3]==+n[e+8>>3])}function fe(A,e){e|=0;var r,t,i;return+((i=+n[(A|=0)>>3]-+n[e>>3])*i+(t=+n[A+8>>3]-+n[e+8>>3])*t+(r=+n[A+16>>3]-+n[e+16>>3])*r)}function se(A,e,r){A|=0,r|=0;var t=0;(0|(e|=0))>0?(t=0|be(e,4),i[A>>2]=t,t||Q(23230,23253,40,23267)):i[A>>2]=0,i[A+4>>2]=e,i[A+8>>2]=0,i[A+12>>2]=r}function ue(A){var e,r,t,o=0,a=0,s=0,l=0;e=(A|=0)+4|0,r=A+12|0,t=A+8|0;A:for(;;){for(a=0|i[e>>2],o=0;;){if((0|o)>=(0|a))break A;if(s=0|i[A>>2],l=0|i[s+(o<<2)>>2])break;o=o+1|0}o=s+(~~(+f(+ +u(10,+ +(15-(0|i[r>>2])|0))*(+n[l>>3]+ +n[l+8>>3]))%+(0|a))>>>0<<2)|0,a=0|i[o>>2];e:do{if(0|a){if(s=l+32|0,(0|a)==(0|l))i[o>>2]=i[s>>2];else{if(!(o=0|i[(a=a+32|0)>>2]))break;for(;(0|o)!=(0|l);)if(!(o=0|i[(a=o+32|0)>>2]))break e;i[a>>2]=i[s>>2]}Be(l),i[t>>2]=(0|i[t>>2])-1}}while(0)}Be(0|i[A>>2])}function le(A){var e,r=0,t=0;for(e=0|i[(A|=0)+4>>2],t=0;;){if((0|t)>=(0|e)){r=0,t=4;break}if(r=0|i[(0|i[A>>2])+(t<<2)>>2]){t=4;break}t=t+1|0}return 4==(0|t)?0|r:0}function he(A,e){e|=0;var r=0,t=0,o=0,a=0;if(r=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,r=(0|i[A>>2])+(r<<2)|0,!(t=0|i[r>>2]))return 0|(a=1);a=e+32|0;do{if((0|t)!=(0|e)){if(!(r=0|i[t+32>>2]))return 0|(a=1);for(o=r;;){if((0|o)==(0|e)){o=8;break}if(!(r=0|i[o+32>>2])){r=1,o=10;break}t=o,o=r}if(8==(0|o)){i[t+32>>2]=i[a>>2];break}if(10==(0|o))return 0|r}else i[r>>2]=i[a>>2]}while(0);return Be(e),i[(a=A+8|0)>>2]=(0|i[a>>2])-1,0|(a=0)}function ce(A,e,r){A|=0,e|=0,r|=0;var t,o=0,a=0,s=0;(t=0|pe(40))||Q(23283,23253,98,23296),i[t>>2]=i[e>>2],i[t+4>>2]=i[e+4>>2],i[t+8>>2]=i[e+8>>2],i[t+12>>2]=i[e+12>>2],i[(a=t+16|0)>>2]=i[r>>2],i[a+4>>2]=i[r+4>>2],i[a+8>>2]=i[r+8>>2],i[a+12>>2]=i[r+12>>2],i[t+32>>2]=0,a=~~(+f(+ +u(10,+ +(15-(0|i[A+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,a=(0|i[A>>2])+(a<<2)|0,o=0|i[a>>2];do{if(o){for(;!(0|xA(o,e)&&0|xA(o+16|0,r));)if(a=0|i[o+32>>2],!(0|i[(o=0==(0|a)?o:a)+32>>2])){s=10;break}if(10==(0|s)){i[o+32>>2]=t;break}return Be(t),0|(s=o)}i[a>>2]=t}while(0);return i[(s=A+8|0)>>2]=1+(0|i[s>>2]),0|(s=t)}function de(A,e,r){e|=0,r|=0;var t=0,o=0;if(o=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,!(o=0|i[(0|i[A>>2])+(o<<2)>>2]))return 0|(r=0);if(!r){for(A=o;;){if(0|xA(A,e)){t=10;break}if(!(A=0|i[A+32>>2])){A=0,t=10;break}}if(10==(0|t))return 0|A}for(A=o;;){if(0|xA(A,e)&&0|xA(A+16|0,r)){t=10;break}if(!(A=0|i[A+32>>2])){A=0,t=10;break}}return 10==(0|t)?0|A:0}function ge(A,e){e|=0;var r=0;if(r=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,!(A=0|i[(0|i[A>>2])+(r<<2)>>2]))return 0|(r=0);for(;;){if(0|xA(A,e)){e=5;break}if(!(A=0|i[A+32>>2])){A=0,e=5;break}}return 5==(0|e)?0|A:0}function we(A){return 0|~~+function(A){return+ +Ie(+(A=+A))}(A=+A)}function pe(A){A|=0;var e,r=0,t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0;e=I,I=I+16|0,d=e;do{if(A>>>0<245){if(A=(l=A>>>0<11?16:A+11&-8)>>>3,3&(t=(c=0|i[5829])>>>A)|0)return n=0|i[(t=(A=23356+((r=(1&t^1)+A|0)<<1<<2)|0)+8|0)>>2],(0|(a=0|i[(o=n+8|0)>>2]))==(0|A)?i[5829]=c&~(1<>2]=A,i[t>>2]=a),k=r<<3,i[n+4>>2]=3|k,i[(k=n+k+4|0)>>2]=1|i[k>>2],I=e,0|(k=o);if(l>>>0>(h=0|i[5831])>>>0){if(0|t)return r=((r=t<>>=s=r>>>12&16)>>>5&8)|s|(a=(r>>>=t)>>>2&4)|(A=(r>>>=a)>>>1&2)|(n=(r>>>=A)>>>1&1))+(r>>>n)|0)<<1<<2)|0)+8|0)>>2],(0|(t=0|i[(s=a+8|0)>>2]))==(0|r)?(A=c&~(1<>2]=r,i[A>>2]=t,A=c),f=(k=n<<3)-l|0,i[a+4>>2]=3|l,i[(o=a+l|0)+4>>2]=1|f,i[a+k>>2]=f,0|h&&(n=0|i[5834],t=23356+((r=h>>>3)<<1<<2)|0,A&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=n,i[r+12>>2]=n,i[n+8>>2]=r,i[n+12>>2]=t),i[5831]=f,i[5834]=o,I=e,0|(k=s);if(a=0|i[5830]){for(t=(a&0-a)-1|0,t=u=0|i[23620+(((n=(t>>>=o=t>>>12&16)>>>5&8)|o|(f=(t>>>=n)>>>2&4)|(s=(t>>>=f)>>>1&2)|(u=(t>>>=s)>>>1&1))+(t>>>u)<<2)>>2],s=u,u=(-8&i[u+4>>2])-l|0;(A=0|i[t+16>>2])||(A=0|i[t+20>>2]);)t=A,s=(o=(f=(-8&i[A+4>>2])-l|0)>>>0>>0)?A:s,u=o?f:u;if((f=s+l|0)>>>0>s>>>0){o=0|i[s+24>>2],r=0|i[s+12>>2];do{if((0|r)==(0|s)){if(!(r=0|i[(A=s+20|0)>>2])&&!(r=0|i[(A=s+16|0)>>2])){t=0;break}for(;;)if(t=0|i[(n=r+20|0)>>2])r=t,A=n;else{if(!(t=0|i[(n=r+16|0)>>2]))break;r=t,A=n}i[A>>2]=0,t=r}else t=0|i[s+8>>2],i[t+12>>2]=r,i[r+8>>2]=t,t=r}while(0);do{if(0|o){if(r=0|i[s+28>>2],(0|s)==(0|i[(A=23620+(r<<2)|0)>>2])){if(i[A>>2]=t,!t){i[5830]=a&~(1<>2])==(0|s)?k:o+20|0)>>2]=t,!t)break;i[t+24>>2]=o,0|(r=0|i[s+16>>2])&&(i[t+16>>2]=r,i[r+24>>2]=t),0|(r=0|i[s+20>>2])&&(i[t+20>>2]=r,i[r+24>>2]=t)}}while(0);return u>>>0<16?(k=u+l|0,i[s+4>>2]=3|k,i[(k=s+k+4|0)>>2]=1|i[k>>2]):(i[s+4>>2]=3|l,i[f+4>>2]=1|u,i[f+u>>2]=u,0|h&&(n=0|i[5834],t=23356+((r=h>>>3)<<1<<2)|0,(r=1<>2]:(i[5829]=r|c,r=t,A=t+8|0),i[A>>2]=n,i[r+12>>2]=n,i[n+8>>2]=r,i[n+12>>2]=t),i[5831]=u,i[5834]=f),I=e,0|(k=s+8|0)}c=l}else c=l}else c=l}else if(A>>>0<=4294967231)if(l=-8&(A=A+11|0),n=0|i[5830]){o=0-l|0,u=(A>>>=8)?l>>>0>16777215?31:l>>>((u=14-((s=((p=A<<(c=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|c|(u=((p<<=s)+245760|0)>>>16&2))+(p<>>15)|0)+7|0)&1|u<<1:0,t=0|i[23620+(u<<2)>>2];A:do{if(t)for(A=0,s=l<<(31==(0|u)?0:25-(u>>>1)|0),a=0;;){if((f=(-8&i[t+4>>2])-l|0)>>>0>>0){if(!f){A=t,o=0,p=65;break A}A=t,o=f}if(a=0==(0|(p=0|i[t+20>>2]))|(0|p)==(0|(t=0|i[t+16+(s>>>31<<2)>>2]))?a:p,!t){t=a,p=61;break}s<<=1}else t=0,A=0,p=61}while(0);if(61==(0|p)){if(0==(0|t)&0==(0|A)){if(!(A=((A=2<>>=f=c>>>12&16)>>>5&8)|f|(s=(c>>>=a)>>>2&4)|(u=(c>>>=s)>>>1&2)|(t=(c>>>=u)>>>1&1))+(c>>>t)<<2)>>2]}t?p=65:(s=A,f=o)}if(65==(0|p))for(a=t;;){if(o=(t=(c=(-8&i[a+4>>2])-l|0)>>>0>>0)?c:o,A=t?a:A,(t=0|i[a+16>>2])||(t=0|i[a+20>>2]),!t){s=A,f=o;break}a=t}if(0!=(0|s)&&f>>>0<((0|i[5831])-l|0)>>>0&&(h=s+l|0)>>>0>s>>>0){a=0|i[s+24>>2],r=0|i[s+12>>2];do{if((0|r)==(0|s)){if(!(r=0|i[(A=s+20|0)>>2])&&!(r=0|i[(A=s+16|0)>>2])){r=0;break}for(;;)if(t=0|i[(o=r+20|0)>>2])r=t,A=o;else{if(!(t=0|i[(o=r+16|0)>>2]))break;r=t,A=o}i[A>>2]=0}else k=0|i[s+8>>2],i[k+12>>2]=r,i[r+8>>2]=k}while(0);do{if(a){if(A=0|i[s+28>>2],(0|s)==(0|i[(t=23620+(A<<2)|0)>>2])){if(i[t>>2]=r,!r){n&=~(1<>2])==(0|s)?k:a+20|0)>>2]=r,!r)break;i[r+24>>2]=a,0|(A=0|i[s+16>>2])&&(i[r+16>>2]=A,i[A+24>>2]=r),(A=0|i[s+20>>2])&&(i[r+20>>2]=A,i[A+24>>2]=r)}}while(0);A:do{if(f>>>0<16)k=f+l|0,i[s+4>>2]=3|k,i[(k=s+k+4|0)>>2]=1|i[k>>2];else{if(i[s+4>>2]=3|l,i[h+4>>2]=1|f,i[h+f>>2]=f,r=f>>>3,f>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=h,i[r+12>>2]=h,i[h+8>>2]=r,i[h+12>>2]=t;break}if(r=23620+((t=(r=f>>>8)?f>>>0>16777215?31:f>>>((t=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(t=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|t<<1:0)<<2)|0,i[h+28>>2]=t,i[(A=h+16|0)+4>>2]=0,i[A>>2]=0,!(n&(A=1<>2]=h,i[h+24>>2]=r,i[h+12>>2]=h,i[h+8>>2]=h;break}r=0|i[r>>2];e:do{if((-8&i[r+4>>2]|0)!=(0|f)){for(n=f<<(31==(0|t)?0:25-(t>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|f)){r=A;break e}n<<=1,r=A}i[t>>2]=h,i[h+24>>2]=r,i[h+12>>2]=h,i[h+8>>2]=h;break A}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=h,i[m>>2]=h,i[h+8>>2]=k,i[h+12>>2]=r,i[h+24>>2]=0}}while(0);return I=e,0|(k=s+8|0)}c=l}else c=l;else c=-1}while(0);if((t=0|i[5831])>>>0>=c>>>0)return r=t-c|0,A=0|i[5834],r>>>0>15?(k=A+c|0,i[5834]=k,i[5831]=r,i[k+4>>2]=1|r,i[A+t>>2]=r,i[A+4>>2]=3|c):(i[5831]=0,i[5834]=0,i[A+4>>2]=3|t,i[(k=A+t+4|0)>>2]=1|i[k>>2]),I=e,0|(k=A+8|0);if((f=0|i[5832])>>>0>c>>>0)return v=f-c|0,i[5832]=v,m=(k=0|i[5835])+c|0,i[5835]=m,i[m+4>>2]=1|v,i[k+4>>2]=3|c,I=e,0|(k=k+8|0);if(0|i[5947]?A=0|i[5949]:(i[5949]=4096,i[5948]=4096,i[5950]=-1,i[5951]=-1,i[5952]=0,i[5940]=0,i[5947]=-16&d^1431655768,A=4096),s=c+48|0,(l=(a=A+(u=c+47|0)|0)&(o=0-A|0))>>>0<=c>>>0)return I=e,0|(k=0);if(0|(A=0|i[5939])&&(d=(h=0|i[5937])+l|0)>>>0<=h>>>0|d>>>0>A>>>0)return I=e,0|(k=0);A:do{if(4&i[5940])r=0,p=143;else{t=0|i[5835];e:do{if(t){for(n=23764;!((d=0|i[n>>2])>>>0<=t>>>0&&(d+(0|i[n+4>>2])|0)>>>0>t>>>0);){if(!(A=0|i[n+8>>2])){p=128;break e}n=A}if((r=a-f&o)>>>0<2147483647)if((0|(A=0|Fe(0|r)))==((0|i[n>>2])+(0|i[n+4>>2])|0)){if(-1!=(0|A)){f=r,a=A,p=145;break A}}else n=A,p=136;else r=0}else p=128}while(0);do{if(128==(0|p))if(-1!=(0|(t=0|Fe(0)))&&(r=t,w=(r=(0==((w=(g=0|i[5948])+-1|0)&r|0)?0:(w+r&0-g)-r|0)+l|0)+(g=0|i[5937])|0,r>>>0>c>>>0&r>>>0<2147483647)){if(0|(d=0|i[5939])&&w>>>0<=g>>>0|w>>>0>d>>>0){r=0;break}if((0|(A=0|Fe(0|r)))==(0|t)){f=r,a=t,p=145;break A}n=A,p=136}else r=0}while(0);do{if(136==(0|p)){if(t=0-r|0,!(s>>>0>r>>>0&r>>>0<2147483647&-1!=(0|n))){if(-1==(0|n)){r=0;break}f=r,a=n,p=145;break A}if((A=u-r+(A=0|i[5949])&0-A)>>>0>=2147483647){f=r,a=n,p=145;break A}if(-1==(0|Fe(0|A))){Fe(0|t),r=0;break}f=A+r|0,a=n,p=145;break A}}while(0);i[5940]=4|i[5940],p=143}}while(0);if(143==(0|p)&&l>>>0<2147483647&&!(-1==(0|(v=0|Fe(0|l)))|1^(b=(B=(w=0|Fe(0))-v|0)>>>0>(c+40|0)>>>0)|v>>>0>>0&-1!=(0|v)&-1!=(0|w)^1)&&(f=b?B:r,a=v,p=145),145==(0|p)){r=(0|i[5937])+f|0,i[5937]=r,r>>>0>(0|i[5938])>>>0&&(i[5938]=r),u=0|i[5835];A:do{if(u){for(r=23764;;){if((0|a)==((A=0|i[r>>2])+(t=0|i[r+4>>2])|0)){p=154;break}if(!(n=0|i[r+8>>2]))break;r=n}if(154==(0|p)&&(m=r+4|0,0==(8&i[r+12>>2]|0))&&a>>>0>u>>>0&A>>>0<=u>>>0){i[m>>2]=t+f,m=u+(v=0==(7&(v=u+8|0)|0)?0:0-v&7)|0,v=(k=(0|i[5832])+f|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[u+k+4>>2]=40,i[5836]=i[5951];break}for(a>>>0<(0|i[5833])>>>0&&(i[5833]=a),t=a+f|0,r=23764;;){if((0|i[r>>2])==(0|t)){p=162;break}if(!(A=0|i[r+8>>2]))break;r=A}if(162==(0|p)&&0==(8&i[r+12>>2]|0)){i[r>>2]=a,i[(h=r+4|0)>>2]=(0|i[h>>2])+f,l=(h=a+(0==(7&(h=a+8|0)|0)?0:0-h&7)|0)+c|0,s=(r=t+(0==(7&(r=t+8|0)|0)?0:0-r&7)|0)-h-c|0,i[h+4>>2]=3|c;e:do{if((0|u)==(0|r))k=(0|i[5832])+s|0,i[5832]=k,i[5835]=l,i[l+4>>2]=1|k;else{if((0|i[5834])==(0|r)){k=(0|i[5831])+s|0,i[5831]=k,i[5834]=l,i[l+4>>2]=1|k,i[l+k>>2]=k;break}if(1==(3&(A=0|i[r+4>>2])|0)){f=-8&A,n=A>>>3;r:do{if(A>>>0<256){if(A=0|i[r+8>>2],(0|(t=0|i[r+12>>2]))==(0|A)){i[5829]=i[5829]&~(1<>2]=t,i[t+8>>2]=A;break}a=0|i[r+24>>2],A=0|i[r+12>>2];do{if((0|A)==(0|r)){if(A=0|i[(n=(t=r+16|0)+4|0)>>2])t=n;else if(!(A=0|i[t>>2])){A=0;break}for(;;)if(n=0|i[(o=A+20|0)>>2])A=n,t=o;else{if(!(n=0|i[(o=A+16|0)>>2]))break;A=n,t=o}i[t>>2]=0}else k=0|i[r+8>>2],i[k+12>>2]=A,i[A+8>>2]=k}while(0);if(!a)break;n=23620+((t=0|i[r+28>>2])<<2)|0;do{if((0|i[n>>2])==(0|r)){if(i[n>>2]=A,0|A)break;i[5830]=i[5830]&~(1<>2])==(0|r)?k:a+20|0)>>2]=A,!A)break r}while(0);if(i[A+24>>2]=a,0|(n=0|i[(t=r+16|0)>>2])&&(i[A+16>>2]=n,i[n+24>>2]=A),!(t=0|i[t+4>>2]))break;i[A+20>>2]=t,i[t+24>>2]=A}while(0);r=r+f|0,o=f+s|0}else o=s;if(i[(r=r+4|0)>>2]=-2&i[r>>2],i[l+4>>2]=1|o,i[l+o>>2]=o,r=o>>>3,o>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=l,i[r+12>>2]=l,i[l+8>>2]=r,i[l+12>>2]=t;break}r=o>>>8;do{if(r){if(o>>>0>16777215){n=31;break}n=o>>>((n=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(n=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|n<<1}else n=0}while(0);if(r=23620+(n<<2)|0,i[l+28>>2]=n,i[(A=l+16|0)+4>>2]=0,i[A>>2]=0,!((A=0|i[5830])&(t=1<>2]=l,i[l+24>>2]=r,i[l+12>>2]=l,i[l+8>>2]=l;break}r=0|i[r>>2];r:do{if((-8&i[r+4>>2]|0)!=(0|o)){for(n=o<<(31==(0|n)?0:25-(n>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|o)){r=A;break r}n<<=1,r=A}i[t>>2]=l,i[l+24>>2]=r,i[l+12>>2]=l,i[l+8>>2]=l;break e}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=l,i[m>>2]=l,i[l+8>>2]=k,i[l+12>>2]=r,i[l+24>>2]=0}}while(0);return I=e,0|(k=h+8|0)}for(r=23764;!((A=0|i[r>>2])>>>0<=u>>>0&&(k=A+(0|i[r+4>>2])|0)>>>0>u>>>0);)r=0|i[r+8>>2];r=(A=(A=(o=k+-47|0)+(0==(7&(A=o+8|0)|0)?0:0-A&7)|0)>>>0<(o=u+16|0)>>>0?u:A)+8|0,m=a+(v=0==(7&(v=a+8|0)|0)?0:0-v&7)|0,v=(t=f+-40|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[a+t+4>>2]=40,i[5836]=i[5951],i[(t=A+4|0)>>2]=27,i[r>>2]=i[5941],i[r+4>>2]=i[5942],i[r+8>>2]=i[5943],i[r+12>>2]=i[5944],i[5941]=a,i[5942]=f,i[5944]=0,i[5943]=r,r=A+24|0;do{m=r,i[(r=r+4|0)>>2]=7}while((m+8|0)>>>0>>0);if((0|A)!=(0|u)){if(a=A-u|0,i[t>>2]=-2&i[t>>2],i[u+4>>2]=1|a,i[A>>2]=a,r=a>>>3,a>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=u,i[r+12>>2]=u,i[u+8>>2]=r,i[u+12>>2]=t;break}if(t=23620+((n=(r=a>>>8)?a>>>0>16777215?31:a>>>((n=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(n=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|n<<1:0)<<2)|0,i[u+28>>2]=n,i[u+20>>2]=0,i[o>>2]=0,!((r=0|i[5830])&(A=1<>2]=u,i[u+24>>2]=t,i[u+12>>2]=u,i[u+8>>2]=u;break}r=0|i[t>>2];e:do{if((-8&i[r+4>>2]|0)!=(0|a)){for(n=a<<(31==(0|n)?0:25-(n>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|a)){r=A;break e}n<<=1,r=A}i[t>>2]=u,i[u+24>>2]=r,i[u+12>>2]=u,i[u+8>>2]=u;break A}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=u,i[m>>2]=u,i[u+8>>2]=k,i[u+12>>2]=r,i[u+24>>2]=0}}else 0==(0|(k=0|i[5833]))|a>>>0>>0&&(i[5833]=a),i[5941]=a,i[5942]=f,i[5944]=0,i[5838]=i[5947],i[5837]=-1,i[5842]=23356,i[5841]=23356,i[5844]=23364,i[5843]=23364,i[5846]=23372,i[5845]=23372,i[5848]=23380,i[5847]=23380,i[5850]=23388,i[5849]=23388,i[5852]=23396,i[5851]=23396,i[5854]=23404,i[5853]=23404,i[5856]=23412,i[5855]=23412,i[5858]=23420,i[5857]=23420,i[5860]=23428,i[5859]=23428,i[5862]=23436,i[5861]=23436,i[5864]=23444,i[5863]=23444,i[5866]=23452,i[5865]=23452,i[5868]=23460,i[5867]=23460,i[5870]=23468,i[5869]=23468,i[5872]=23476,i[5871]=23476,i[5874]=23484,i[5873]=23484,i[5876]=23492,i[5875]=23492,i[5878]=23500,i[5877]=23500,i[5880]=23508,i[5879]=23508,i[5882]=23516,i[5881]=23516,i[5884]=23524,i[5883]=23524,i[5886]=23532,i[5885]=23532,i[5888]=23540,i[5887]=23540,i[5890]=23548,i[5889]=23548,i[5892]=23556,i[5891]=23556,i[5894]=23564,i[5893]=23564,i[5896]=23572,i[5895]=23572,i[5898]=23580,i[5897]=23580,i[5900]=23588,i[5899]=23588,i[5902]=23596,i[5901]=23596,i[5904]=23604,i[5903]=23604,m=a+(v=0==(7&(v=a+8|0)|0)?0:0-v&7)|0,v=(k=f+-40|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[a+k+4>>2]=40,i[5836]=i[5951]}while(0);if((r=0|i[5832])>>>0>c>>>0)return v=r-c|0,i[5832]=v,m=(k=0|i[5835])+c|0,i[5835]=m,i[m+4>>2]=1|v,i[k+4>>2]=3|c,I=e,0|(k=k+8|0)}return i[(k=23312)>>2]=12,I=e,0|(k=0)}function Be(A){var e=0,r=0,t=0,n=0,o=0,a=0,f=0,s=0;if(A|=0){r=A+-8|0,n=0|i[5833],s=r+(e=-8&(A=0|i[A+-4>>2]))|0;do{if(1&A)f=r,a=r;else{if(t=0|i[r>>2],!(3&A))return;if(o=t+e|0,(a=r+(0-t)|0)>>>0>>0)return;if((0|i[5834])==(0|a)){if(3!=(3&(e=0|i[(A=s+4|0)>>2])|0)){f=a,e=o;break}return i[5831]=o,i[A>>2]=-2&e,i[a+4>>2]=1|o,void(i[a+o>>2]=o)}if(r=t>>>3,t>>>0<256){if(A=0|i[a+8>>2],(0|(e=0|i[a+12>>2]))==(0|A)){i[5829]=i[5829]&~(1<>2]=e,i[e+8>>2]=A,f=a,e=o;break}n=0|i[a+24>>2],A=0|i[a+12>>2];do{if((0|A)==(0|a)){if(A=0|i[(r=(e=a+16|0)+4|0)>>2])e=r;else if(!(A=0|i[e>>2])){A=0;break}for(;;)if(r=0|i[(t=A+20|0)>>2])A=r,e=t;else{if(!(r=0|i[(t=A+16|0)>>2]))break;A=r,e=t}i[e>>2]=0}else f=0|i[a+8>>2],i[f+12>>2]=A,i[A+8>>2]=f}while(0);if(n){if(e=0|i[a+28>>2],(0|i[(r=23620+(e<<2)|0)>>2])==(0|a)){if(i[r>>2]=A,!A){i[5830]=i[5830]&~(1<>2])==(0|a)?f:n+20|0)>>2]=A,!A){f=a,e=o;break}i[A+24>>2]=n,0|(r=0|i[(e=a+16|0)>>2])&&(i[A+16>>2]=r,i[r+24>>2]=A),(e=0|i[e+4>>2])?(i[A+20>>2]=e,i[e+24>>2]=A,f=a,e=o):(f=a,e=o)}else f=a,e=o}}while(0);if(!(a>>>0>=s>>>0)&&1&(t=0|i[(A=s+4|0)>>2])){if(2&t)i[A>>2]=-2&t,i[f+4>>2]=1|e,i[a+e>>2]=e,n=e;else{if((0|i[5835])==(0|s)){if(s=(0|i[5832])+e|0,i[5832]=s,i[5835]=f,i[f+4>>2]=1|s,(0|f)!=(0|i[5834]))return;return i[5834]=0,void(i[5831]=0)}if((0|i[5834])==(0|s))return s=(0|i[5831])+e|0,i[5831]=s,i[5834]=a,i[f+4>>2]=1|s,void(i[a+s>>2]=s);n=(-8&t)+e|0,r=t>>>3;do{if(t>>>0<256){if(e=0|i[s+8>>2],(0|(A=0|i[s+12>>2]))==(0|e)){i[5829]=i[5829]&~(1<>2]=A,i[A+8>>2]=e;break}o=0|i[s+24>>2],A=0|i[s+12>>2];do{if((0|A)==(0|s)){if(A=0|i[(r=(e=s+16|0)+4|0)>>2])e=r;else if(!(A=0|i[e>>2])){r=0;break}for(;;)if(r=0|i[(t=A+20|0)>>2])A=r,e=t;else{if(!(r=0|i[(t=A+16|0)>>2]))break;A=r,e=t}i[e>>2]=0,r=A}else r=0|i[s+8>>2],i[r+12>>2]=A,i[A+8>>2]=r,r=A}while(0);if(0|o){if(A=0|i[s+28>>2],(0|i[(e=23620+(A<<2)|0)>>2])==(0|s)){if(i[e>>2]=r,!r){i[5830]=i[5830]&~(1<>2])==(0|s)?t:o+20|0)>>2]=r,!r)break;i[r+24>>2]=o,0|(e=0|i[(A=s+16|0)>>2])&&(i[r+16>>2]=e,i[e+24>>2]=r),0|(A=0|i[A+4>>2])&&(i[r+20>>2]=A,i[A+24>>2]=r)}}while(0);if(i[f+4>>2]=1|n,i[a+n>>2]=n,(0|f)==(0|i[5834]))return void(i[5831]=n)}if(A=n>>>3,n>>>0<256)return r=23356+(A<<1<<2)|0,(e=0|i[5829])&(A=1<>2]:(i[5829]=e|A,A=r,e=r+8|0),i[e>>2]=f,i[A+12>>2]=f,i[f+8>>2]=A,void(i[f+12>>2]=r);A=23620+((t=(A=n>>>8)?n>>>0>16777215?31:n>>>((t=14-((o=((s=A<<(a=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|a|(t=((s<<=o)+245760|0)>>>16&2))+(s<>>15)|0)+7|0)&1|t<<1:0)<<2)|0,i[f+28>>2]=t,i[f+20>>2]=0,i[f+16>>2]=0,e=0|i[5830],r=1<>2];e:do{if((-8&i[A+4>>2]|0)!=(0|n)){for(t=n<<(31==(0|t)?0:25-(t>>>1)|0);e=0|i[(r=A+16+(t>>>31<<2)|0)>>2];){if((-8&i[e+4>>2]|0)==(0|n)){A=e;break e}t<<=1,A=e}i[r>>2]=f,i[f+24>>2]=A,i[f+12>>2]=f,i[f+8>>2]=f;break A}}while(0);s=0|i[(a=A+8|0)>>2],i[s+12>>2]=f,i[a>>2]=f,i[f+8>>2]=s,i[f+12>>2]=A,i[f+24>>2]=0}else i[5830]=e|r,i[A>>2]=f,i[f+24>>2]=A,i[f+12>>2]=f,i[f+8>>2]=f}while(0);if(s=(0|i[5837])-1|0,i[5837]=s,!(0|s)){for(A=23772;A=0|i[A>>2];)A=A+8|0;i[5837]=-1}}}}function be(A,e){e|=0;var r=0;return(A|=0)?(r=0|b(e,A),(e|A)>>>0>65535&&(r=(0|(r>>>0)/(A>>>0))==(0|e)?r:-1)):r=0,(A=0|pe(r))&&3&i[A+-4>>2]?(_e(0|A,0,0|r),0|A):0|A}function ve(A,e,r,t){return 0|(k(0|(t=(e|=0)-(t|=0)-((r|=0)>>>0>(A|=0)>>>0|0)>>>0)),A-r>>>0|0)}function me(A){return 0|((A|=0)?31-(0|m(A^A-1))|0:32)}function ke(A,e,r,t,n){n|=0;var o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0;if(l=A|=0,a=r|=0,f=c=t|=0,!(u=s=e|=0))return o=0!=(0|n),f?o?(i[n>>2]=0|A,i[n+4>>2]=0&e,n=0,0|(k(0|(c=0)),n)):(n=0,0|(k(0|(c=0)),n)):(o&&(i[n>>2]=(l>>>0)%(a>>>0),i[n+4>>2]=0),n=(l>>>0)/(a>>>0)>>>0,0|(k(0|(c=0)),n));o=0==(0|f);do{if(a){if(!o){if((o=(0|m(0|f))-(0|m(0|u))|0)>>>0<=31){a=h=o+1|0,A=l>>>(h>>>0)&(e=o-31>>31)|u<<(f=31-o|0),e&=u>>>(h>>>0),o=0,f=l<>2]=0|A,i[n+4>>2]=s|0&e,n=0,0|(k(0|(c=0)),n)):(n=0,0|(k(0|(c=0)),n))}if((o=a-1|0)&a|0){a=f=33+(0|m(0|a))-(0|m(0|u))|0,A=(h=32-f|0)-1>>31&u>>>((d=f-32|0)>>>0)|(u<>>(f>>>0))&(e=d>>31),e&=u>>>(f>>>0),o=l<<(g=64-f|0)&(s=h>>31),f=(u<>>(d>>>0))&s|l<>31;break}return 0|n&&(i[n>>2]=o&l,i[n+4>>2]=0),1==(0|a)?(g=0|A,0|(k(0|(d=s|0&e)),g)):(d=u>>>((g=0|me(0|a))>>>0)|0,g=u<<32-g|l>>>(g>>>0)|0,0|(k(0|d),g))}if(o)return 0|n&&(i[n>>2]=(u>>>0)%(a>>>0),i[n+4>>2]=0),g=(u>>>0)/(a>>>0)>>>0,0|(k(0|(d=0)),g);if(!l)return 0|n&&(i[n>>2]=0,i[n+4>>2]=(u>>>0)%(f>>>0)),g=(u>>>0)/(f>>>0)>>>0,0|(k(0|(d=0)),g);if(!((o=f-1|0)&f))return 0|n&&(i[n>>2]=0|A,i[n+4>>2]=o&u|0&e),d=0,g=u>>>((0|me(0|f))>>>0),0|(k(0|d),g);if((o=(0|m(0|f))-(0|m(0|u))|0)>>>0<=30){a=e=o+1|0,A=u<<(f=31-o|0)|l>>>(e>>>0),e=u>>>(e>>>0),o=0,f=l<>2]=0|A,i[n+4>>2]=s|0&e,g=0,0|(k(0|(d=0)),g)):(g=0,0|(k(0|(d=0)),g))}while(0);if(a){u=0|function(A,e,r,t){return 0|(k((e|=0)+(t|=0)+((r=(A|=0)+(r|=0)>>>0)>>>0>>0|0)>>>0|0),0|r)}(0|(h=0|r),0|(l=c|0&t),-1,-1),r=0|M(),s=f,f=0;do{t=s,s=o>>>31|s<<1,o=f|o<<1,ve(0|u,0|r,0|(t=A<<1|t>>>31|0),0|(c=A>>>31|e<<1|0)),f=1&(d=(g=0|M())>>31|((0|g)<0?-1:0)<<1),A=0|ve(0|t,0|c,d&h|0,(((0|g)<0?-1:0)>>31|((0|g)<0?-1:0)<<1)&l|0),e=0|M(),a=a-1|0}while(0!=(0|a));u=s,s=0}else u=f,s=0,f=0;return a=0,0|n&&(i[n>>2]=A,i[n+4>>2]=e),g=-2&(o<<1|0)|f,0|(k(0|(d=(0|o)>>>31|(u|a)<<1|0&(a<<1|o>>>31)|s)),g)}function Me(A,e,r,t){var n,o;return o=I,I=I+16|0,ke(A|=0,e|=0,r|=0,t|=0,n=0|o),I=o,0|(k(0|i[n+4>>2]),0|i[n>>2])}function Qe(A,e,r){return A|=0,e|=0,(0|(r|=0))<32?(k(e>>>r|0),A>>>r|(e&(1<>>r-32|0)}function ye(A,e,r){return A|=0,e|=0,(0|(r|=0))<32?(k(e<>>32-r|0),A<=0?+a(A+.5):+B(A-.5)}function De(A,e,r){A|=0,e|=0;var n,o,a=0;if((0|(r|=0))>=8192)return x(0|A,0|e,0|r),0|A;if(o=0|A,n=A+r|0,(3&A)==(3&e)){for(;3&A;){if(!r)return 0|o;t[A>>0]=0|t[e>>0],A=A+1|0,e=e+1|0,r=r-1|0}for(a=(r=-4&n|0)-64|0;(0|A)<=(0|a);)i[A>>2]=i[e>>2],i[A+4>>2]=i[e+4>>2],i[A+8>>2]=i[e+8>>2],i[A+12>>2]=i[e+12>>2],i[A+16>>2]=i[e+16>>2],i[A+20>>2]=i[e+20>>2],i[A+24>>2]=i[e+24>>2],i[A+28>>2]=i[e+28>>2],i[A+32>>2]=i[e+32>>2],i[A+36>>2]=i[e+36>>2],i[A+40>>2]=i[e+40>>2],i[A+44>>2]=i[e+44>>2],i[A+48>>2]=i[e+48>>2],i[A+52>>2]=i[e+52>>2],i[A+56>>2]=i[e+56>>2],i[A+60>>2]=i[e+60>>2],A=A+64|0,e=e+64|0;for(;(0|A)<(0|r);)i[A>>2]=i[e>>2],A=A+4|0,e=e+4|0}else for(r=n-4|0;(0|A)<(0|r);)t[A>>0]=0|t[e>>0],t[A+1>>0]=0|t[e+1>>0],t[A+2>>0]=0|t[e+2>>0],t[A+3>>0]=0|t[e+3>>0],A=A+4|0,e=e+4|0;for(;(0|A)<(0|n);)t[A>>0]=0|t[e>>0],A=A+1|0,e=e+1|0;return 0|o}function _e(A,e,r){e|=0;var n,o=0,a=0,f=0;if(n=(A|=0)+(r|=0)|0,e&=255,(0|r)>=67){for(;3&A;)t[A>>0]=e,A=A+1|0;for(f=e|e<<8|e<<16|e<<24,a=(o=-4&n|0)-64|0;(0|A)<=(0|a);)i[A>>2]=f,i[A+4>>2]=f,i[A+8>>2]=f,i[A+12>>2]=f,i[A+16>>2]=f,i[A+20>>2]=f,i[A+24>>2]=f,i[A+28>>2]=f,i[A+32>>2]=f,i[A+36>>2]=f,i[A+40>>2]=f,i[A+44>>2]=f,i[A+48>>2]=f,i[A+52>>2]=f,i[A+56>>2]=f,i[A+60>>2]=f,A=A+64|0;for(;(0|A)<(0|o);)i[A>>2]=f,A=A+4|0}for(;(0|A)<(0|n);)t[A>>0]=e,A=A+1|0;return n-r|0}function Ie(A){return(A=+A)>=0?+a(A+.5):+B(A-.5)}function Fe(A){A|=0;var e,r,t;return t=0|E(),(0|A)>0&(0|(e=(r=0|i[o>>2])+A|0))<(0|r)|(0|e)<0?(_(0|e),y(12),-1):(0|e)>(0|t)&&!(0|D(0|e))?(y(12),-1):(i[o>>2]=e,0|r)}return{___uremdi3:Me,_bitshift64Lshr:Qe,_bitshift64Shl:ye,_calloc:be,_cellAreaKm2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))>0){if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1!=(0|e)){A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e))}}else o=0;return I=n,6371.007180918475*o*6371.007180918475},_cellAreaM2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))>0){if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1!=(0|e)){A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e))}}else o=0;return I=n,6371.007180918475*o*6371.007180918475*1e3*1e3},_cellAreaRads2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))<=0)return I=n,+(o=0);if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1==(0|e))return I=n,+o;A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e));return I=n,+o},_compact:function(A,e,r){e|=0;var t,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,Q=0,y=0,E=0;if(!(r|=0))return 0|(y=0);if(n=0|i[(o=A|=0)>>2],!0&0==(15728640&(o=0|i[o+4>>2])|0)){if((0|r)<=0)return 0|(y=0);if(i[(y=e)>>2]=n,i[y+4>>2]=o,1==(0|r))return 0|(y=0);n=1;do{Q=0|i[(k=A+(n<<3)|0)+4>>2],i[(y=e+(n<<3)|0)>>2]=i[k>>2],i[y+4>>2]=Q,n=n+1|0}while((0|n)!=(0|r));return 0|(n=0)}if(!(Q=0|pe(k=r<<3)))return 0|(y=-3);if(De(0|Q,0|A,0|k),!(t=0|be(r,8)))return Be(Q),0|(y=-3);n=r;A:for(;;){v=0|Qe(0|(h=0|i[(f=Q)>>2]),0|(f=0|i[f+4>>2]),52),M(),m=(v&=15)+-1|0,b=(0|n)>0;e:do{if(b){if(B=((0|n)<0)<<31>>31,w=0|ye(0|m,0,52),p=0|M(),m>>>0>15)for(o=0,A=h,r=f;;){if(!(0==(0|A)&0==(0|r))){if(a=0|Qe(0|A,0|r,52),M(),s=(0|(a&=15))<(0|m),a=(0|a)==(0|m),r=0|Me(0|(l=s?0:a?A:0),0|(A=s?0:a?r:0),0|n,0|B),M(),0==(0|(u=0|i[(s=a=t+(r<<3)|0)>>2]))&0==(0|(s=0|i[s+4>>2])))r=l;else for(w=0,g=r,d=s,r=l;;){if((0|w)>(0|n)){y=41;break A}if((0|u)==(0|r)&(-117440513&d|0)==(0|A)){l=0|Qe(0|u,0|d,56),M(),c=(l&=7)+1|0,p=0|Qe(0|u,0|d,45),M();r:do{if(0|S(127&p)){if(u=0|Qe(0|u,0|d,52),M(),!(u&=15)){s=6;break}for(s=1;;){if(!(0==((p=0|ye(7,0,3*(15-s|0)|0))&r|0)&0==((0|M())&A|0))){s=7;break r}if(!(s>>>0>>0)){s=6;break}s=s+1|0}}else s=7}while(0);if((l+2|0)>>>0>s>>>0){y=51;break A}p=0|ye(0|c,0,56),A=0|M()|-117440513&A,i[(s=a)>>2]=0,i[s+4>>2]=0,s=g,r|=p}else s=(g+1|0)%(0|n)|0;if(0==(0|(u=0|i[(d=a=t+(s<<3)|0)>>2]))&0==(0|(d=0|i[d+4>>2])))break;w=w+1|0,g=s}i[(p=a)>>2]=r,i[p+4>>2]=A}if((0|(o=o+1|0))>=(0|n))break e;A=0|i[(r=Q+(o<<3)|0)>>2],r=0|i[r+4>>2]}for(o=0,A=h,r=f;;){if(!(0==(0|A)&0==(0|r))){if(s=0|Qe(0|A,0|r,52),M(),(0|(s&=15))>=(0|m)){if((0|s)!=(0|m)&&(A|=w,r=-15728641&r|p,s>>>0>=v>>>0)){a=m;do{g=0|ye(7,0,3*(14-a|0)|0),a=a+1|0,A|=g,r=0|M()|r}while(a>>>0>>0)}}else A=0,r=0;if(s=0|Me(0|A,0|r,0|n,0|B),M(),!(0==(0|(l=0|i[(u=a=t+(s<<3)|0)>>2]))&0==(0|(u=0|i[u+4>>2]))))for(g=0;;){if((0|g)>(0|n)){y=41;break A}if((0|l)==(0|A)&(-117440513&u|0)==(0|r)){c=0|Qe(0|l,0|u,56),M(),d=(c&=7)+1|0,E=0|Qe(0|l,0|u,45),M();r:do{if(0|S(127&E)){if(l=0|Qe(0|l,0|u,52),M(),!(l&=15)){u=6;break}for(u=1;;){if(!(0==((E=0|ye(7,0,3*(15-u|0)|0))&A|0)&0==((0|M())&r|0))){u=7;break r}if(!(u>>>0>>0)){u=6;break}u=u+1|0}}else u=7}while(0);if((c+2|0)>>>0>u>>>0){y=51;break A}E=0|ye(0|d,0,56),r=0|M()|-117440513&r,i[(d=a)>>2]=0,i[d+4>>2]=0,A|=E}else s=(s+1|0)%(0|n)|0;if(0==(0|(l=0|i[(u=a=t+(s<<3)|0)>>2]))&0==(0|(u=0|i[u+4>>2])))break;g=g+1|0}i[(E=a)>>2]=A,i[E+4>>2]=r}if((0|(o=o+1|0))>=(0|n))break e;A=0|i[(r=Q+(o<<3)|0)>>2],r=0|i[r+4>>2]}}}while(0);if((n+5|0)>>>0<11){y=99;break}if(!(p=0|be((0|n)/6|0,8))){y=58;break}e:do{if(b){g=0,d=0;do{if(!(0==(0|(o=0|i[(A=s=t+(g<<3)|0)>>2]))&0==(0|(A=0|i[A+4>>2])))){u=0|Qe(0|o,0|A,56),M(),r=(u&=7)+1|0,l=-117440513&A,E=0|Qe(0|o,0|A,45),M();r:do{if(0|S(127&E)){if(c=0|Qe(0|o,0|A,52),M(),0|(c&=15))for(a=1;;){if(!(0==(o&(E=0|ye(7,0,3*(15-a|0)|0))|0)&0==(l&(0|M())|0)))break r;if(!(a>>>0>>0))break;a=a+1|0}o|=A=0|ye(0|r,0,56),A=0|M()|l,i[(r=s)>>2]=o,i[r+4>>2]=A,r=u+2|0}}while(0);7==(0|r)&&(i[(E=p+(d<<3)|0)>>2]=o,i[E+4>>2]=-117440513&A,d=d+1|0)}g=g+1|0}while((0|g)!=(0|n));if(b){if(w=((0|n)<0)<<31>>31,c=0|ye(0|m,0,52),g=0|M(),m>>>0>15)for(A=0,o=0;;){do{if(!(0==(0|h)&0==(0|f))){for(u=0|Qe(0|h,0|f,52),M(),a=(0|(u&=15))<(0|m),u=(0|u)==(0|m),a=0|Me(0|(s=a?0:u?h:0),0|(u=a?0:u?f:0),0|n,0|w),M(),r=0;;){if((0|r)>(0|n)){y=98;break A}if((-117440513&(l=0|i[(E=t+(a<<3)|0)+4>>2])|0)==(0|u)&&(0|i[E>>2])==(0|s)){y=70;break}if((0|i[(E=t+((a=(a+1|0)%(0|n)|0)<<3)|0)>>2])==(0|s)&&(0|i[E+4>>2])==(0|u))break;r=r+1|0}if(70==(0|y)&&(y=0,!0&100663296==(117440512&l|0)))break;i[(E=e+(o<<3)|0)>>2]=h,i[E+4>>2]=f,o=o+1|0}}while(0);if((0|(A=A+1|0))>=(0|n)){n=d;break e}h=0|i[(f=Q+(A<<3)|0)>>2],f=0|i[f+4>>2]}for(A=0,o=0;;){do{if(!(0==(0|h)&0==(0|f))){if(u=0|Qe(0|h,0|f,52),M(),(0|(u&=15))>=(0|m))if((0|u)!=(0|m))if(r=h|c,a=-15728641&f|g,u>>>0>>0)u=a;else{s=m;do{E=0|ye(7,0,3*(14-s|0)|0),s=s+1|0,r|=E,a=0|M()|a}while(s>>>0>>0);u=a}else r=h,u=f;else r=0,u=0;for(s=0|Me(0|r,0|u,0|n,0|w),M(),a=0;;){if((0|a)>(0|n)){y=98;break A}if((-117440513&(l=0|i[(E=t+(s<<3)|0)+4>>2])|0)==(0|u)&&(0|i[E>>2])==(0|r)){y=93;break}if((0|i[(E=t+((s=(s+1|0)%(0|n)|0)<<3)|0)>>2])==(0|r)&&(0|i[E+4>>2])==(0|u))break;a=a+1|0}if(93==(0|y)&&(y=0,!0&100663296==(117440512&l|0)))break;i[(E=e+(o<<3)|0)>>2]=h,i[E+4>>2]=f,o=o+1|0}}while(0);if((0|(A=A+1|0))>=(0|n)){n=d;break e}h=0|i[(f=Q+(A<<3)|0)>>2],f=0|i[f+4>>2]}}else o=0,n=d}else o=0,n=0}while(0);if(_e(0|t,0,0|k),De(0|Q,0|p,n<<3|0),Be(p),!n)break;e=e+(o<<3)|0}return 41==(0|y)?(Be(Q),Be(t),0|(E=-1)):51==(0|y)?(Be(Q),Be(t),0|(E=-2)):58==(0|y)?(Be(Q),Be(t),0|(E=-3)):98==(0|y)?(Be(p),Be(Q),Be(t),0|(E=-1)):(99==(0|y)&&De(0|e,0|Q,n<<3|0),Be(Q),Be(t),0|(E=0))},_destroyLinkedPolygon:function(A){var e=0,r=0,t=0,n=0;if(A|=0)for(t=1;;){if(0|(e=0|i[A>>2]))do{if(0|(r=0|i[e>>2]))do{n=r,r=0|i[r+16>>2],Be(n)}while(0!=(0|r));n=e,e=0|i[e+8>>2],Be(n)}while(0!=(0|e));if(e=A,A=0|i[A+8>>2],t||Be(e),!A)break;t=0}},_edgeLengthKm:function(A){return+ +n[20752+((A|=0)<<3)>>3]},_edgeLengthM:function(A){return+ +n[20880+((A|=0)<<3)>>3]},_emscripten_replace_memory:function(A){return t=new Int8Array(A),new Uint8Array(A),i=new Int32Array(A),new Float32Array(A),n=new Float64Array(A),r=A,!0},_exactEdgeLengthKm:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+c)*+l(+a)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)!=(0|e));return I=t,+(d=6371.007180918475*o)},_exactEdgeLengthM:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+c)*+l(+a)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)!=(0|e));return I=t,+(d=6371.007180918475*o*1e3)},_exactEdgeLengthRads:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+a)*+l(+c)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)<(0|e));return I=t,+o},_experimentalH3ToLocalIj:function(A,e,r,t,i){var n,o;return i|=0,o=I,I=I+16|0,(A=0|$A(A|=0,e|=0,r|=0,t|=0,n=o))||(cA(n,i),A=0),I=o,0|A},_experimentalLocalIjToH3:function(A,e,r,t){var i,n;return A|=0,e|=0,t|=0,i=I,I=I+16|0,dA(r|=0,n=i),t=0|Ae(A,e,n,t),I=i,0|t},_free:Be,_geoToH3:LA,_getDestinationH3IndexFromUnidirectionalEdge:function(A,e){A|=0;var r,t,n=0;return r=I,I=I+16|0,n=r,!0&268435456==(2013265920&(e|=0)|0)?(t=0|Qe(0|A,0|e,56),M(),i[n>>2]=0,n=0|U(A,-2130706433&e|134217728,7&t,n),e=0|M(),k(0|e),I=r,0|n):(n=0,k(0|(e=0)),I=r,0|n)},_getH3IndexesFromUnidirectionalEdge:function(A,e,r){A|=0;var t,n,o,a,f=0;o=I,I=I+16|0,t=o,a=!0&268435456==(2013265920&(e|=0)|0),n=-2130706433&e|134217728,i[(f=r|=0)>>2]=a?A:0,i[f+4>>2]=a?n:0,a?(e=0|Qe(0|A,0|e,56),M(),i[t>>2]=0,A=0|U(A,n,7&e,t),e=0|M()):(A=0,e=0),i[(f=r+8|0)>>2]=A,i[f+4>>2]=e,I=o},_getH3UnidirectionalEdge:function(A,e,r,t){var n,o,a=0,f=0,s=0,u=0,l=0;if(o=I,I=I+16|0,n=o,!(0|ZA(A|=0,e|=0,r|=0,t|=0)))return u=0,k(0|(s=0)),I=o,0|u;for(s=-2130706433&e,a=(a=0==(0|UA(A,e)))?1:2;i[n>>2]=0,f=a+1|0,!((0|(l=0|U(A,e,a,n)))==(0|r)&(0|M())==(0|t));){if(!(f>>>0<7)){a=0,A=0,u=6;break}a=f}return 6==(0|u)?(k(0|a),I=o,0|A):(l=0|ye(0|a,0,56),u=0|s|M()|268435456,l|=A,k(0|u),I=o,0|l)},_getH3UnidirectionalEdgeBoundary:WA,_getH3UnidirectionalEdgesFromHexagon:function(A,e,r){r|=0;var t,n=0;t=0==(0|UA(A|=0,e|=0)),e&=-2130706433,i[(n=r)>>2]=t?A:0,i[n+4>>2]=t?285212672|e:0,i[(n=r+8|0)>>2]=A,i[n+4>>2]=301989888|e,i[(n=r+16|0)>>2]=A,i[n+4>>2]=318767104|e,i[(n=r+24|0)>>2]=A,i[n+4>>2]=335544320|e,i[(n=r+32|0)>>2]=A,i[n+4>>2]=352321536|e,i[(r=r+40|0)>>2]=A,i[r+4>>2]=369098752|e},_getOriginH3IndexFromUnidirectionalEdge:function(A,e){var r;return A|=0,k(0|((r=!0&268435456==(2013265920&(e|=0)|0))?-2130706433&e|134217728:0)),0|(r?A:0)},_getPentagonIndexes:NA,_getRes0Indexes:function(A){A|=0;var e=0,r=0,t=0;e=0;do{ye(0|e,0,45),t=134225919|M(),i[(r=A+(e<<3)|0)>>2]=-1,i[r+4>>2]=t,e=e+1|0}while(122!=(0|e))},_h3Distance:function(A,e,r,t){var i,n,o;return r|=0,t|=0,o=I,I=I+32|0,n=o,A=0==(0|$A(A|=0,e|=0,A,e,i=o+12|0))&&0==(0|$A(A,e,r,t,n))?0|hA(i,n):-1,I=o,0|A},_h3GetBaseCell:IA,_h3GetFaces:function A(e,r,t){t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0;n=I,I=I+128|0,h=n+112|0,f=n+96|0,c=n,a=0|Qe(0|(e|=0),0|(r|=0),52),M(),u=15&a,i[h>>2]=u,s=0|Qe(0|e,0|r,45),M(),s&=127;A:do{if(0|S(s)){if(0|u)for(o=1;;){if(!(0==((l=0|ye(7,0,3*(15-o|0)|0))&e|0)&0==((0|M())&r|0))){a=0;break A}if(!(o>>>0>>0))break;o=o+1|0}if(!(1&a))return l=0|ye(u+1|0,0,52),c=0|M()|-15728641&r,A((l|e)&~(h=0|ye(7,0,3*(14-u|0)|0)),c&~(0|M()),t),void(I=n);a=1}else a=0}while(0);YA(e,r,f),a?(mA(f,h,c),l=5):(yA(f,h,c),l=6);A:do{if(0|S(s))if(u)for(o=1;;){if(!(0==((s=0|ye(7,0,3*(15-o|0)|0))&e|0)&0==((0|M())&r|0))){o=8;break A}if(!(o>>>0>>0)){o=20;break}o=o+1|0}else o=20;else o=8}while(0);if(_e(0|t,-1,0|o),a){a=0;do{for(MA(f=c+(a<<4)|0,0|i[h>>2]),f=0|i[f>>2],o=0;!(-1==(0|(u=0|i[(s=t+(o<<2)|0)>>2]))|(0|u)==(0|f));)o=o+1|0;i[s>>2]=f,a=a+1|0}while((0|a)!=(0|l))}else{a=0;do{for(kA(f=c+(a<<4)|0,0|i[h>>2],0,1),f=0|i[f>>2],o=0;!(-1==(0|(u=0|i[(s=t+(o<<2)|0)>>2]))|(0|u)==(0|f));)o=o+1|0;i[s>>2]=f,a=a+1|0}while((0|a)!=(0|l))}I=n},_h3GetResolution:function(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),52),M(),15&e|0},_h3IndexesAreNeighbors:ZA,_h3IsPentagon:UA,_h3IsResClassIII:function(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),52),M(),1&e|0},_h3IsValid:FA,_h3Line:function(A,e,r,t,n){r|=0,t|=0,n|=0;var o,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,Q=0;if(o=I,I=I+48|0,s=o+12|0,M=o,0==(0|$A(A|=0,e|=0,A,e,a=o+24|0))&&0==(0|$A(A,e,r,t,s))){if((0|(k=0|hA(a,s)))<0)return I=o,0|(M=k);for(i[a>>2]=0,i[a+4>>2]=0,i[a+8>>2]=0,i[s>>2]=0,i[s+4>>2]=0,i[s+8>>2]=0,$A(A,e,A,e,a),$A(A,e,r,t,s),gA(a),gA(s),k?(w=+(0|k),m=a,r=c=0|i[a>>2],t=d=0|i[(b=a+4|0)>>2],a=g=0|i[(v=a+8|0)>>2],p=+((0|i[s>>2])-c|0)/w,B=+((0|i[s+4>>2])-d|0)/w,w=+((0|i[s+8>>2])-g|0)/w):(b=t=a+4|0,v=g=a+8|0,m=a,r=0|i[a>>2],t=0|i[t>>2],a=0|i[g>>2],p=0,B=0,w=0),i[M>>2]=r,i[(g=M+4|0)>>2]=t,i[(d=M+8|0)>>2]=a,c=0;;){Q=p*(l=+(0|c))+ +(0|r),u=B*l+ +(0|i[b>>2]),l=w*l+ +(0|i[v>>2]),t=~~+xe(+Q),s=~~+xe(+u),r=~~+xe(+l),Q=+f(+(+(0|t)-Q)),u=+f(+(+(0|s)-u)),l=+f(+(+(0|r)-l));do{if(!(Q>u&Q>l)){if(h=0-t|0,u>l){a=h-r|0;break}a=s,r=h-s|0;break}t=0-(s+r)|0,a=s}while(0);if(i[M>>2]=t,i[g>>2]=a,i[d>>2]=r,wA(M),Ae(A,e,M,n+(c<<3)|0),(0|c)==(0|k))break;c=c+1|0,r=0|i[m>>2]}return I=o,0|(M=0)}return I=o,0|(M=-1)},_h3LineSize:function(A,e,r,t){var i,n,o;return r|=0,t|=0,o=I,I=I+32|0,n=o,A=0==(0|$A(A|=0,e|=0,A,e,i=o+12|0))&&0==(0|$A(A,e,r,t,n))?0|hA(i,n):-1,I=o,(A>>>31^1)+A|0},_h3SetToLinkedGeo:function(A,e,r){r|=0;var t,n,o,a=0;if(o=I,I=I+32|0,t=o,function(A,e,r){A|=0,r|=0;var t,n,o=0,a=0,f=0,s=0,u=0;if(n=I,I=I+176|0,t=n,(0|(e|=0))<1)return se(r,0,0),void(I=n);s=0|Qe(0|i[(s=A)>>2],0|i[s+4>>2],52),M(),se(r,(0|e)>6?e:6,15&s),s=0;do{if(jA(0|i[(o=A+(s<<3)|0)>>2],0|i[o+4>>2],t),(0|(o=0|i[t>>2]))>0){u=0;do{f=t+8+(u<<4)|0,(a=0|de(r,o=t+8+(((0|(u=u+1|0))%(0|o)|0)<<4)|0,f))?he(r,a):ce(r,f,o),o=0|i[t>>2]}while((0|u)<(0|o))}s=s+1|0}while((0|s)!=(0|e));I=n}(A|=0,e|=0,n=o+16|0),i[r>>2]=0,i[r+4>>2]=0,i[r+8>>2]=0,!(A=0|le(n)))return XA(r),ue(n),void(I=o);do{e=0|JA(r);do{KA(e,A),a=A+16|0,i[t>>2]=i[a>>2],i[t+4>>2]=i[a+4>>2],i[t+8>>2]=i[a+8>>2],i[t+12>>2]=i[a+12>>2],he(n,A),A=0|ge(n,t)}while(0!=(0|A));A=0|le(n)}while(0!=(0|A));XA(r),ue(n),I=o},_h3ToCenterChild:function(A,e,r){r|=0;var t=0,i=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(t&=15))<=(0|r)){if((0|t)!=(0|r)&&(A|=i=0|ye(0|r,0,52),e=0|M()|-15728641&e,(0|t)<(0|r)))do{i=0|ye(7,0,3*(14-t|0)|0),t=t+1|0,A&=~i,e&=~(0|M())}while((0|t)<(0|r))}else e=0,A=0;return k(0|e),0|A},_h3ToChildren:PA,_h3ToGeo:OA,_h3ToGeoBoundary:jA,_h3ToParent:CA,_h3UnidirectionalEdgeIsValid:function(A,e){var r=0;if(!(!0&268435456==(2013265920&(e|=0)|0)))return 0|(r=0);switch(r=0|Qe(0|(A|=0),0|e,56),M(),7&r){case 0:case 7:return 0|(r=0)}return!0&16777216==(117440512&e|0)&0!=(0|UA(A,r=-2130706433&e|134217728))?0|(r=0):0|(r=0|FA(A,r))},_hexAreaKm2:function(A){return+ +n[20496+((A|=0)<<3)>>3]},_hexAreaM2:function(A){return+ +n[20624+((A|=0)<<3)>>3]},_hexRing:function(A,e,r,t){A|=0,e|=0,t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0,h=0;if(n=I,I=I+16|0,h=n,!(r|=0))return i[(h=t)>>2]=A,i[h+4>>2]=e,I=n,0|(h=0);i[h>>2]=0;A:do{if(0|UA(A,e))A=1;else{if(a=(0|r)>0){o=0,l=A;do{if(0==(0|(l=0|U(l,e,4,h)))&0==(0|(e=0|M()))){A=2;break A}if(o=o+1|0,0|UA(l,e)){A=1;break A}}while((0|o)<(0|r));if(i[(u=t)>>2]=l,i[u+4>>2]=e,u=r+-1|0,a){a=0,f=1,o=l,A=e;do{if(0==(0|(o=0|U(o,A,2,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(f<<3)|0)>>2]=o,i[s+4>>2]=A,f=f+1|0,0|UA(o,A)){A=1;break A}a=a+1|0}while((0|a)<(0|r));s=0,a=f;do{if(0==(0|(o=0|U(o,A,3,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(f=t+(a<<3)|0)>>2]=o,i[f+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}s=s+1|0}while((0|s)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,1,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,5,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,4,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));for(f=0;;){if(0==(0|(o=0|U(o,A,6,h)))&0==(0|(A=0|M()))){A=2;break A}if((0|f)!=(0|u)){if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,0|UA(o,A)){A=1;break A}a=a+1|0}if((0|(f=f+1|0))>=(0|r)){f=l,a=e;break}}}else f=l,o=l,a=e,A=e}else i[(f=t)>>2]=A,i[f+4>>2]=e,f=A,o=A,a=e,A=e;A=1&((0|f)!=(0|o)|(0|a)!=(0|A))}}while(0);return I=n,0|(h=A)},_i64Subtract:ve,_kRing:F,_kRingDistances:function(A,e,r,t,i){var n;if(0|C(A|=0,e|=0,r|=0,t|=0,i|=0)){if(_e(0|t,0,(n=1+(0|b(3*r|0,r+1|0))|0)<<3|0),0|i)return _e(0|i,0,n<<2|0),void P(A,e,r,t,i,n,0);(i=0|be(n,4))&&(P(A,e,r,t,i,n,0),Be(i))}},_llvm_minnum_f64:Ee,_llvm_round_f64:xe,_malloc:pe,_maxFaceCount:function(A,e){var r=0,t=0;if(t=0|Qe(0|(A|=0),0|(e|=0),45),M(),!(0|S(127&t)))return 0|(t=2);if(t=0|Qe(0|A,0|e,52),M(),!(t&=15))return 0|(t=5);for(r=1;;){if(!(0==((0|ye(7,0,3*(15-r|0)|0))&A|0)&0==((0|M())&e|0))){r=2,A=6;break}if(!(r>>>0>>0)){r=5,A=6;break}r=r+1|0}return 6==(0|A)?0|r:0},_maxH3ToChildrenSize:function(A,e,r){return r|=0,A=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(A&=15))<=(0|r)?0|(r=0|ee(7,r-A|0)):0|(r=0)},_maxKringSize:function(A){return 1+(0|b(3*(A|=0)|0,A+1|0))|0},_maxPolyfillSize:function(A,e){e|=0;var r,t=0,n=0,o=0,a=0,f=0;if(r=I,I=I+48|0,o=r+8|0,n=r,a=0|i[(f=A|=0)+4>>2],i[(t=n)>>2]=i[f>>2],i[t+4>>2]=a,te(n,o),o=0|j(o,e),e=0|i[n>>2],(0|(n=0|i[A+8>>2]))<=0)return I=r,0|(f=(f=(a=(0|o)<(0|(f=e)))?f:o)+12|0);t=0|i[A+12>>2],A=0;do{e=(0|i[t+(A<<3)>>2])+e|0,A=A+1|0}while((0|A)<(0|n));return I=r,0|(f=(f=(f=(0|o)<(0|e))?e:o)+12|0)},_maxUncompactSize:function(A,e,r){A|=0,r|=0;var t=0,n=0,o=0,a=0;if((0|(e|=0))<=0)return 0|(r=0);if((0|r)>=16){for(t=0;;){if(!(0==(0|i[(a=A+(t<<3)|0)>>2])&0==(0|i[a+4>>2]))){t=-1,n=13;break}if((0|(t=t+1|0))>=(0|e)){t=0,n=13;break}}if(13==(0|n))return 0|t}t=0,a=0;A:for(;;){o=0|i[(n=A+(a<<3)|0)>>2],n=0|i[n+4>>2];do{if(!(0==(0|o)&0==(0|n))){if(n=0|Qe(0|o,0|n,52),M(),(0|(n&=15))>(0|r)){t=-1,n=13;break A}if((0|n)==(0|r)){t=t+1|0;break}t=(0|ee(7,r-n|0))+t|0;break}}while(0);if((0|(a=a+1|0))>=(0|e)){n=13;break}}return 13==(0|n)?0|t:0},_memcpy:De,_memset:_e,_numHexagons:function(A){var e;return A=0|i[(e=21008+((A|=0)<<3)|0)>>2],k(0|i[e+4>>2]),0|A},_pentagonIndexCount:function(){return 12},_pointDistKm:DA,_pointDistM:function(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))*6371.007180918475*1e3},_pointDistRads:function(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))},_polyfill:function(A,e,r){var t,n=0,o=0,a=0,f=0,s=0;if(t=I,I=I+48|0,n=t+8|0,o=t,0|function(A,e,r){e|=0,r|=0;var t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,y=0,E=0,x=0,D=0,_=0,F=0,U=0,S=0,T=0,V=0,H=0;H=I,I=I+112|0,U=H+80|0,s=H+72|0,S=H,T=H+56|0,(V=0|pe(32+(i[(u=(A=A|0)+8|0)>>2]<<5)|0))||Q(22848,22448,800,22456);if(ie(A,V),t=0|i[(o=A)+4>>2],i[(f=s)>>2]=i[o>>2],i[f+4>>2]=t,te(s,U),f=0|j(U,e),t=0|i[s>>2],(0|(o=0|i[u>>2]))>0){a=0|i[A+12>>2],n=0;do{t=(0|i[a+(n<<3)>>2])+t|0,n=n+1|0}while((0|n)!=(0|o))}if(n=0|be(F=(f=(0|f)<(0|t)?t:f)+12|0,8),l=0|be(F,8),i[U>>2]=0,_=0|i[(D=A)+4>>2],i[(t=s)>>2]=i[D>>2],i[t+4>>2]=_,0|(t=0|G(s,F,e,U,n,l)))return Be(n),Be(l),Be(V),I=H,0|(V=t);A:do{if((0|i[u>>2])>0){for(o=A+12|0,t=0;a=0|G((0|i[o>>2])+(t<<3)|0,F,e,U,n,l),t=t+1|0,!(0|a);)if((0|t)>=(0|i[u>>2]))break A;return Be(n),Be(l),Be(V),I=H,0|(V=a)}}while(0);(0|f)>-12&&_e(0|l,0,((0|F)>1?F:1)<<3|0);A:do{if((0|i[U>>2])>0){_=((0|F)<0)<<31>>31,m=n,k=l,y=n,E=n,x=l,D=n,t=n,p=n,B=l,b=l,v=l,n=l;e:for(;;){for(w=0|i[U>>2],d=0,g=0,o=0;;){f=(a=S)+56|0;do{i[a>>2]=0,a=a+4|0}while((0|a)<(0|f));if(0|C(s=0|i[(e=m+(d<<3)|0)>>2],e=0|i[e+4>>2],1,S,0)){f=(a=S)+56|0;do{i[a>>2]=0,a=a+4|0}while((0|a)<(0|f));0|(a=0|be(7,4))&&(P(s,e,1,S,a,7,0),Be(a))}c=0;do{l=0|i[(h=S+(c<<3)|0)>>2],h=0|i[h+4>>2];r:do{if(!(0==(0|l)&0==(0|h))){if(s=0|Me(0|l,0|h,0|F,0|_),M(),!(0==(0|(e=0|i[(f=a=r+(s<<3)|0)>>2]))&0==(0|(f=0|i[f+4>>2]))))for(u=0;;){if((0|u)>(0|F))break e;if((0|e)==(0|l)&(0|f)==(0|h))break r;if(0==(0|(e=0|i[(f=a=r+((s=(s+1|0)%(0|F)|0)<<3)|0)>>2]))&0==(0|(f=0|i[f+4>>2])))break;u=u+1|0}0==(0|l)&0==(0|h)||(OA(l,h,T),0|ne(A,V,T)&&(i[(u=a)>>2]=l,i[u+4>>2]=h,i[(u=k+(o<<3)|0)>>2]=l,i[u+4>>2]=h,o=o+1|0))}}while(0);c=c+1|0}while(c>>>0<7);if((0|(g=g+1|0))>=(0|w))break;d=d+1|0}if((0|w)>0&&_e(0|y,0,w<<3|0),i[U>>2]=o,!((0|o)>0))break A;l=n,h=v,c=D,d=b,g=B,w=k,n=p,v=t,b=E,B=y,p=l,t=h,D=x,x=c,E=d,y=g,k=m,m=w}return Be(E),Be(x),Be(V),I=H,0|(V=-1)}t=l}while(0);return Be(V),Be(n),Be(t),I=H,0|(V=0)}(A|=0,e|=0,r|=0)){if(a=0|i[(s=A)+4>>2],i[(f=o)>>2]=i[s>>2],i[f+4>>2]=a,te(o,n),f=0|j(n,e),e=0|i[o>>2],(0|(a=0|i[A+8>>2]))>0){o=0|i[A+12>>2],n=0;do{e=(0|i[o+(n<<3)>>2])+e|0,n=n+1|0}while((0|n)!=(0|a))}(0|(e=(0|f)<(0|e)?e:f))<=-12||_e(0|r,0,8+(((0|(s=e+11|0))>0?s:0)<<3)|0),I=t}else I=t},_res0IndexCount:function(){return 122},_round:Ie,_sbrk:Fe,_sizeOfCoordIJ:function(){return 8},_sizeOfGeoBoundary:function(){return 168},_sizeOfGeoCoord:function(){return 16},_sizeOfGeoPolygon:function(){return 16},_sizeOfGeofence:function(){return 8},_sizeOfH3Index:function(){return 8},_sizeOfLinkedGeoPolygon:function(){return 12},_uncompact:function(A,e,r,t,n){A|=0,r|=0,t|=0,n|=0;var o=0,a=0,f=0,s=0,u=0,l=0;if((0|(e|=0))<=0)return 0|(n=0);if((0|n)>=16){for(o=0;;){if(!(0==(0|i[(l=A+(o<<3)|0)>>2])&0==(0|i[l+4>>2]))){o=14;break}if((0|(o=o+1|0))>=(0|e)){a=0,o=16;break}}if(14==(0|o))return 0|((0|t)>0?-2:-1);if(16==(0|o))return 0|a}o=0,l=0;A:for(;;){a=0|i[(f=u=A+(l<<3)|0)>>2],f=0|i[f+4>>2];do{if(!(0==(0|a)&0==(0|f))){if((0|o)>=(0|t)){a=-1,o=16;break A}if(s=0|Qe(0|a,0|f,52),M(),(0|(s&=15))>(0|n)){a=-2,o=16;break A}if((0|s)==(0|n)){i[(u=r+(o<<3)|0)>>2]=a,i[u+4>>2]=f,o=o+1|0;break}if((0|(a=(0|ee(7,n-s|0))+o|0))>(0|t)){a=-1,o=16;break A}PA(0|i[u>>2],0|i[u+4>>2],n,r+(o<<3)|0),o=a}}while(0);if((0|(l=l+1|0))>=(0|e)){a=0,o=16;break}}return 16==(0|o)?0|a:0},establishStackSpace:function(A,e){I=A|=0},stackAlloc:function(A){var e;return e=I,I=(I=I+(A|=0)|0)+15&-16,0|e},stackRestore:function(A){I=A|=0},stackSave:function(){return 0|I}}}({Math:Math,Int8Array:Int8Array,Int32Array:Int32Array,Uint8Array:Uint8Array,Float32Array:Float32Array,Float64Array:Float64Array},{a:fA,b:function(A){s=A},c:u,d:function(A,e,r,t){fA("Assertion failed: "+g(A)+", at: "+[e?g(e):"unknown filename",r,t?g(t):"unknown function"])},e:function(A){return r.___errno_location&&(v[r.___errno_location()>>2]=A),A},f:N,g:function(A,e,r){B.set(B.subarray(e,e+r),A)},h:function(A){var e=N(),r=16777216,t=2130706432;if(A>t)return!1;for(var i=Math.max(e,16777216);i>0]=e;break;case"i16":b[A>>1]=e;break;case"i32":v[A>>2]=e;break;case"i64":H=[e>>>0,(V=e,+F(V)>=1?V>0?(0|U(+P(V/4294967296),4294967295))>>>0:~~+C((V-+(~~V>>>0))/4294967296)>>>0:0)],v[A>>2]=H[0],v[A+4>>2]=H[1];break;case"float":m[A>>2]=e;break;case"double":k[A>>3]=e;break;default:fA("invalid type for setValue: "+r)}},r.getValue=function(A,e,r){switch("*"===(e=e||"i8").charAt(e.length-1)&&(e="i32"),e){case"i1":case"i8":return p[A>>0];case"i16":return b[A>>1];case"i32":case"i64":return v[A>>2];case"float":return m[A>>2];case"double":return k[A>>3];default:fA("invalid type for getValue: "+e)}return null},r.getTempRet0=u,R){z(R)||(K=R,R=r.locateFile?r.locateFile(K,o):o+K),G++,r.monitorRunDependencies&&r.monitorRunDependencies(G);var tA=function(A){A.byteLength&&(A=new Uint8Array(A)),B.set(A,8),r.memoryInitializerRequest&&delete r.memoryInitializerRequest.response,function(A){if(G--,r.monitorRunDependencies&&r.monitorRunDependencies(G),0==G&&(null!==S&&(clearInterval(S),S=null),T)){var e=T;T=null,e()}}()},iA=function(){i(R,tA,(function(){throw"could not load memory initializer "+R}))},nA=J(R);if(nA)tA(nA.buffer);else if(r.memoryInitializerRequest){var oA=function(){var A=r.memoryInitializerRequest,e=A.response;if(200!==A.status&&0!==A.status){var t=J(r.memoryInitializerRequestURL);if(!t)return console.warn("a problem seems to have happened with Module.memoryInitializerRequest, status: "+A.status+", retrying "+R),void iA();e=t.buffer}tA(e)};r.memoryInitializerRequest.response?setTimeout(oA,0):r.memoryInitializerRequest.addEventListener("load",oA)}else iA()}function aA(A){function e(){X||(X=!0,l||(E(D),E(_),r.onRuntimeInitialized&&r.onRuntimeInitialized(),function(){if(r.postRun)for("function"==typeof r.postRun&&(r.postRun=[r.postRun]);r.postRun.length;)A=r.postRun.shift(),I.unshift(A);var A;E(I)}()))}A=A||n,G>0||(!function(){if(r.preRun)for("function"==typeof r.preRun&&(r.preRun=[r.preRun]);r.preRun.length;)A=r.preRun.shift(),x.unshift(A);var A;E(x)}(),G>0||(r.setStatus?(r.setStatus("Running..."),setTimeout((function(){setTimeout((function(){r.setStatus("")}),1),e()}),1)):e()))}function fA(A){throw r.onAbort&&r.onAbort(A),a(A+=""),f(A),l=!0,"abort("+A+"). Build with -s ASSERTIONS=1 for more info."}if(T=function A(){X||aA(),X||(T=A)},r.run=aA,r.abort=fA,r.preInit)for("function"==typeof r.preInit&&(r.preInit=[r.preInit]);r.preInit.length>0;)r.preInit.pop()();return aA(),A}("object"==typeof t?t:{}),i="number",n={};[["sizeOfH3Index",i],["sizeOfGeoCoord",i],["sizeOfGeoBoundary",i],["sizeOfGeoPolygon",i],["sizeOfGeofence",i],["sizeOfLinkedGeoPolygon",i],["sizeOfCoordIJ",i],["h3IsValid",i,[i,i]],["geoToH3",i,[i,i,i]],["h3ToGeo",null,[i,i,i]],["h3ToGeoBoundary",null,[i,i,i]],["maxKringSize",i,[i]],["kRing",null,[i,i,i,i]],["kRingDistances",null,[i,i,i,i,i]],["hexRing",null,[i,i,i,i]],["maxPolyfillSize",i,[i,i]],["polyfill",null,[i,i,i]],["h3SetToLinkedGeo",null,[i,i,i]],["destroyLinkedPolygon",null,[i]],["compact",i,[i,i,i]],["uncompact",i,[i,i,i,i,i]],["maxUncompactSize",i,[i,i,i]],["h3IsPentagon",i,[i,i]],["h3IsResClassIII",i,[i,i]],["h3GetBaseCell",i,[i,i]],["h3GetResolution",i,[i,i]],["maxFaceCount",i,[i,i]],["h3GetFaces",null,[i,i,i]],["h3ToParent",i,[i,i,i]],["h3ToChildren",null,[i,i,i,i]],["h3ToCenterChild",i,[i,i,i]],["maxH3ToChildrenSize",i,[i,i,i]],["h3IndexesAreNeighbors",i,[i,i,i,i]],["getH3UnidirectionalEdge",i,[i,i,i,i]],["getOriginH3IndexFromUnidirectionalEdge",i,[i,i]],["getDestinationH3IndexFromUnidirectionalEdge",i,[i,i]],["h3UnidirectionalEdgeIsValid",i,[i,i]],["getH3IndexesFromUnidirectionalEdge",null,[i,i,i]],["getH3UnidirectionalEdgesFromHexagon",null,[i,i,i]],["getH3UnidirectionalEdgeBoundary",null,[i,i,i]],["h3Distance",i,[i,i,i,i]],["h3Line",i,[i,i,i,i,i]],["h3LineSize",i,[i,i,i,i]],["experimentalH3ToLocalIj",i,[i,i,i,i,i]],["experimentalLocalIjToH3",i,[i,i,i,i]],["hexAreaM2",i,[i]],["hexAreaKm2",i,[i]],["edgeLengthM",i,[i]],["edgeLengthKm",i,[i]],["pointDistM",i,[i,i]],["pointDistKm",i,[i,i]],["pointDistRads",i,[i,i]],["cellAreaM2",i,[i,i]],["cellAreaKm2",i,[i,i]],["cellAreaRads2",i,[i,i]],["exactEdgeLengthM",i,[i,i]],["exactEdgeLengthKm",i,[i,i]],["exactEdgeLengthRads",i,[i,i]],["numHexagons",i,[i]],["getRes0Indexes",null,[i]],["res0IndexCount",i],["getPentagonIndexes",null,[i,i]],["pentagonIndexCount",i]].forEach((function(A){n[A[0]]=t.cwrap.apply(t,A)}));var o=16,a=n.sizeOfH3Index(),f=n.sizeOfGeoCoord(),s=n.sizeOfGeoBoundary(),u=n.sizeOfGeoPolygon(),l=n.sizeOfGeofence(),h=n.sizeOfLinkedGeoPolygon(),c=n.sizeOfCoordIJ(),d={m:"m",m2:"m2",km:"km",km2:"km2",rads:"rads",rads2:"rads2"};function g(A){if("number"!=typeof A||A<0||A>15||Math.floor(A)!==A)throw new Error("Invalid resolution: "+A)}var w=/[^0-9a-fA-F]/;function p(A){if(Array.isArray(A)&&2===A.length&&Number.isInteger(A[0])&&Number.isInteger(A[1]))return A;if("string"!=typeof A||w.test(A))return[0,0];var e=parseInt(A.substring(0,A.length-8),o);return[parseInt(A.substring(A.length-8),o),e]}function B(A){if(A>=0)return A.toString(o);var e=v(8,(A&=2147483647).toString(o));return e=(parseInt(e[0],o)+8).toString(o)+e.substring(1)}function b(A,e){return B(e)+v(8,B(A))}function v(A,e){for(var r=A-e.length,t="",i=0;i=0&&r.push(n)}return r}(a,o);return t._free(a),f},r.h3GetResolution=function(A){var e=p(A),r=e[0],t=e[1];return n.h3IsValid(r,t)?n.h3GetResolution(r,t):-1},r.geoToH3=function(A,e,r){var i=t._malloc(f);t.HEAPF64.set([A,e].map(U),i/8);var o=M(n.geoToH3(i,r));return t._free(i),o},r.h3ToGeo=function(A){var e=t._malloc(f),r=p(A),i=r[0],o=r[1];n.h3ToGeo(i,o,e);var a=I(e);return t._free(e),a},r.h3ToGeoBoundary=function(A,e){var r=t._malloc(s),i=p(A),o=i[0],a=i[1];n.h3ToGeoBoundary(o,a,r);var f=C(r,e,e);return t._free(r),f},r.h3ToParent=function(A,e){var r=p(A),t=r[0],i=r[1];return M(n.h3ToParent(t,i,e))},r.h3ToChildren=function(A,e){if(!P(A))return[];var r=p(A),i=r[0],o=r[1],f=n.maxH3ToChildrenSize(i,o,e),s=t._calloc(f,a);n.h3ToChildren(i,o,e,s);var u=E(s,f);return t._free(s),u},r.h3ToCenterChild=function(A,e){var r=p(A),t=r[0],i=r[1];return M(n.h3ToCenterChild(t,i,e))},r.kRing=function(A,e){var r=p(A),i=r[0],o=r[1],f=n.maxKringSize(e),s=t._calloc(f,a);n.kRing(i,o,e,s);var u=E(s,f);return t._free(s),u},r.kRingDistances=function(A,e){var r=p(A),i=r[0],o=r[1],f=n.maxKringSize(e),s=t._calloc(f,a),u=t._calloc(f,4);n.kRingDistances(i,o,e,s,u);for(var l=[],h=0;h0){r=t._calloc(i,l);for(var f=0;f0){for(var n=t.getValue(A+r,"i32"),o=0;o */ +r.read=function(A,e,r,t,i){var n,o,a=8*i-t-1,f=(1<>1,u=-7,l=r?i-1:0,h=r?-1:1,c=A[e+l];for(l+=h,n=c&(1<<-u)-1,c>>=-u,u+=a;u>0;n=256*n+A[e+l],l+=h,u-=8);for(o=n&(1<<-u)-1,n>>=-u,u+=t;u>0;o=256*o+A[e+l],l+=h,u-=8);if(0===n)n=1-s;else{if(n===f)return o?NaN:1/0*(c?-1:1);o+=Math.pow(2,t),n-=s}return(c?-1:1)*o*Math.pow(2,n-t)},r.write=function(A,e,r,t,i,n){var o,a,f,s=8*n-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,c=t?0:n-1,d=t?1:-1,g=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=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(f=Math.pow(2,-o))<1&&(o--,f*=2),(e+=o+l>=1?h/f:h*Math.pow(2,1-l))*f>=2&&(o++,f/=2),o+l>=u?(a=0,o=u):o+l>=1?(a=(e*f-1)*Math.pow(2,i),o+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),o=0));i>=8;A[r+c]=255&a,c+=d,a/=256,i-=8);for(o=o<0;A[r+c]=255&o,c+=d,o/=256,s-=8);A[r+c-d]|=128*g}},{}],9:[function(A,e,r){"use strict";e.exports=i;var t=A("ieee754");function i(A){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(A)?A:new Uint8Array(A||0),this.pos=0,this.type=0,this.length=this.buf.length}i.Varint=0,i.Fixed64=1,i.Bytes=2,i.Fixed32=5;var n=4294967296,o=1/n,a="undefined"==typeof TextDecoder?null:new TextDecoder("utf8");function f(A){return A.type===i.Bytes?A.readVarint()+A.pos:A.pos+1}function s(A,e,r){return r?4294967296*e+(A>>>0):4294967296*(e>>>0)+(A>>>0)}function u(A,e,r){var t=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(t);for(var i=r.pos-1;i>=A;i--)r.buf[i+t]=r.buf[i]}function l(A,e){for(var r=0;r>>8,A[r+2]=e>>>16,A[r+3]=e>>>24}function k(A,e){return(A[e]|A[e+1]<<8|A[e+2]<<16)+(A[e+3]<<24)}i.prototype={destroy:function(){this.buf=null},readFields:function(A,e,r){for(r=r||this.length;this.pos>3,n=this.pos;this.type=7&t,A(i,e,this),this.pos===n&&this.skip(t)}return e},readMessage:function(A,e){return this.readFields(A,e,this.readVarint()+this.pos)},readFixed32:function(){var A=v(this.buf,this.pos);return this.pos+=4,A},readSFixed32:function(){var A=k(this.buf,this.pos);return this.pos+=4,A},readFixed64:function(){var A=v(this.buf,this.pos)+v(this.buf,this.pos+4)*n;return this.pos+=8,A},readSFixed64:function(){var A=v(this.buf,this.pos)+k(this.buf,this.pos+4)*n;return this.pos+=8,A},readFloat:function(){var A=t.read(this.buf,this.pos,!0,23,4);return this.pos+=4,A},readDouble:function(){var A=t.read(this.buf,this.pos,!0,52,8);return this.pos+=8,A},readVarint:function(A){var e,r,t=this.buf;return e=127&(r=t[this.pos++]),r<128?e:(e|=(127&(r=t[this.pos++]))<<7,r<128?e:(e|=(127&(r=t[this.pos++]))<<14,r<128?e:(e|=(127&(r=t[this.pos++]))<<21,r<128?e:function(A,e,r){var t,i,n=r.buf;if(i=n[r.pos++],t=(112&i)>>4,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<3,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<10,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<17,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<24,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(1&i)<<31,i<128)return s(A,t,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=t[this.pos]))<<28,A,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var A=this.readVarint();return A%2==1?(A+1)/-2:A/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var A=this.readVarint()+this.pos,e=this.pos;return this.pos=A,A-e>=12&&a?function(A,e,r){return a.decode(A.subarray(e,r))}(this.buf,e,A):function(A,e,r){var t="",i=e;for(;i239?4:f>223?3:f>191?2:1;if(i+u>r)break;1===u?f<128&&(s=f):2===u?128==(192&(n=A[i+1]))&&(s=(31&f)<<6|63&n)<=127&&(s=null):3===u?(n=A[i+1],o=A[i+2],128==(192&n)&&128==(192&o)&&((s=(15&f)<<12|(63&n)<<6|63&o)<=2047||s>=55296&&s<=57343)&&(s=null)):4===u&&(n=A[i+1],o=A[i+2],a=A[i+3],128==(192&n)&&128==(192&o)&&128==(192&a)&&((s=(15&f)<<18|(63&n)<<12|(63&o)<<6|63&a)<=65535||s>=1114112)&&(s=null)),null===s?(s=65533,u=1):s>65535&&(s-=65536,t+=String.fromCharCode(s>>>10&1023|55296),s=56320|1023&s),t+=String.fromCharCode(s),i+=u}return t}(this.buf,e,A)},readBytes:function(){var A=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,A);return this.pos=A,e},readPackedVarint:function(A,e){if(this.type!==i.Bytes)return A.push(this.readVarint(e));var r=f(this);for(A=A||[];this.pos127;);else if(e===i.Bytes)this.pos=this.readVarint()+this.pos;else if(e===i.Fixed32)this.pos+=4;else{if(e!==i.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(A,e){this.writeVarint(A<<3|e)},realloc:function(A){for(var e=this.length||16;e268435455||A<0?function(A,e){var r,t;A>=0?(r=A%4294967296|0,t=A/4294967296|0):(t=~(-A/4294967296),4294967295^(r=~(-A%4294967296))?r=r+1|0:(r=0,t=t+1|0));if(A>=0x10000000000000000||A<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(A,e,r){r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos]=127&A}(r,0,e),function(A,e){var r=(7&A)<<4;if(e.buf[e.pos++]|=r|((A>>>=3)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;e.buf[e.pos++]=127&A}(t,e)}(A,this):(this.realloc(4),this.buf[this.pos++]=127&A|(A>127?128:0),A<=127||(this.buf[this.pos++]=127&(A>>>=7)|(A>127?128:0),A<=127||(this.buf[this.pos++]=127&(A>>>=7)|(A>127?128:0),A<=127||(this.buf[this.pos++]=A>>>7&127))))},writeSVarint:function(A){this.writeVarint(A<0?2*-A-1:2*A)},writeBoolean:function(A){this.writeVarint(Boolean(A))},writeString:function(A){A=String(A),this.realloc(4*A.length),this.pos++;var e=this.pos;this.pos=function(A,e,r){for(var t,i,n=0;n55295&&t<57344){if(!i){t>56319||n+1===e.length?(A[r++]=239,A[r++]=191,A[r++]=189):i=t;continue}if(t<56320){A[r++]=239,A[r++]=191,A[r++]=189,i=t;continue}t=i-55296<<10|t-56320|65536,i=null}else i&&(A[r++]=239,A[r++]=191,A[r++]=189,i=null);t<128?A[r++]=t:(t<2048?A[r++]=t>>6|192:(t<65536?A[r++]=t>>12|224:(A[r++]=t>>18|240,A[r++]=t>>12&63|128),A[r++]=t>>6&63|128),A[r++]=63&t|128)}return r}(this.buf,A,this.pos);var r=this.pos-e;r>=128&&u(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r},writeFloat:function(A){this.realloc(4),t.write(this.buf,A,this.pos,!0,23,4),this.pos+=4},writeDouble:function(A){this.realloc(8),t.write(this.buf,A,this.pos,!0,52,8),this.pos+=8},writeBytes:function(A){var e=A.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&u(r,t,this),this.pos=r-1,this.writeVarint(t),this.pos+=t},writeMessage:function(A,e,r){this.writeTag(A,i.Bytes),this.writeRawMessage(e,r)},writePackedVarint:function(A,e){e.length&&this.writeMessage(A,l,e)},writePackedSVarint:function(A,e){e.length&&this.writeMessage(A,h,e)},writePackedBoolean:function(A,e){e.length&&this.writeMessage(A,g,e)},writePackedFloat:function(A,e){e.length&&this.writeMessage(A,c,e)},writePackedDouble:function(A,e){e.length&&this.writeMessage(A,d,e)},writePackedFixed32:function(A,e){e.length&&this.writeMessage(A,w,e)},writePackedSFixed32:function(A,e){e.length&&this.writeMessage(A,p,e)},writePackedFixed64:function(A,e){e.length&&this.writeMessage(A,B,e)},writePackedSFixed64:function(A,e){e.length&&this.writeMessage(A,b,e)},writeBytesField:function(A,e){this.writeTag(A,i.Bytes),this.writeBytes(e)},writeFixed32Field:function(A,e){this.writeTag(A,i.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(A,e){this.writeTag(A,i.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(A,e){this.writeTag(A,i.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(A,e){this.writeTag(A,i.Fixed64),this.writeSFixed64(e)},writeVarintField:function(A,e){this.writeTag(A,i.Varint),this.writeVarint(e)},writeSVarintField:function(A,e){this.writeTag(A,i.Varint),this.writeSVarint(e)},writeStringField:function(A,e){this.writeTag(A,i.Bytes),this.writeString(e)},writeFloatField:function(A,e){this.writeTag(A,i.Fixed32),this.writeFloat(e)},writeDoubleField:function(A,e){this.writeTag(A,i.Fixed64),this.writeDouble(e)},writeBooleanField:function(A,e){this.writeVarintField(A,Boolean(e))}}},{ieee754:8}],10:[function(A,e,r){var t=A("pbf"),i=A("./lib/geojson_wrapper");function n(A){var e=new t;return function(A,e){for(var r in A.layers)e.writeMessage(3,o,A.layers[r])}(A,e),e.finish()}function o(A,e){var r;e.writeVarintField(15,A.version||1),e.writeStringField(1,A.name||""),e.writeVarintField(5,A.extent||4096);var t={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r>31}function l(A,e){for(var r=A.loadGeometry(),t=A.type,i=0,n=0,o=r.length,a=0;anew Promise(((r,t)=>{var i;r((i=e,{type:"FeatureCollection",features:A.cells.map((A=>{const e={properties:A,geometry:{type:i.geometry_type,coordinates:i.generate(A.h3id)}};return i.promoteID||(e.id=parseInt(A.h3id,16)),e}))}))})),a=A=>{const e=["type","data","maxzoom","attribution","buffer","filter","tolerance","cluster","clusterRadius","clusterMaxZoom","clusterMinPoints","clusterProperties","lineMetrics","generateId","promoteId"];return f(A,((A,r)=>e.includes(A)))},f=(A,e)=>Object.fromEntries(Object.entries(A).filter((([A,r])=>e(A,r))));t.Map.prototype.addH3TSource=function(A,e){const r=Object.assign({},n,e,{type:"vector",format:"pbf"});r.generate=A=>"Polygon"===r.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),r.promoteId&&(r.promoteId="h3id"),t.addProtocol("h3tiles",((A,e)=>{const t=`http${!1===r.https?"":"s"}://${A.url.split("://")[1]}`,n=A.url.split(/\/|\./i),a=n.length,f=n.slice(a-4,a-1).map((A=>1*A)),s=new AbortController,u=s.signal;let l;r.timeout>0&&setTimeout((()=>s.abort()),r.timeout),fetch(t,{signal:u}).then((A=>{if(A.ok)return l=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,r))).then((A=>{const t=i.tovt(A).getTile(...f),n={};n[r.sourcelayer]=t;const o=i.topbf.fromGeojsonVt(n,{version:2});r.debug&&console.log(`${f}: ${A.features.length} features, ${(performance.now()-l).toFixed(0)} ms`),e(null,o,null,null)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Tile .../${f.join("/")}.h3t is taking too long to fetch`),e(new Error(A))}))})),this.addSource(A,(A=>{const e=["type","url","tiles","bounds","scheme","minzoom","maxzoom","attribution","promoteId","volatile"];return f(A,((A,r)=>e.includes(A)))})(r))};t.Map.prototype.addH3JSource=function(A,e){const r=new AbortController,t=r.signal,f=Object.assign({},n,e,{type:"geojson"});let s;if(f.generate=A=>"Polygon"===f.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),f.promoteId&&(f.promoteId="h3id"),f.timeout>0&&setTimeout((()=>r.abort()),f.timeout),"string"==typeof f.data)return f.timeout>0&&setTimeout((()=>r.abort()),f.timeout),new Promise(((e,r)=>{fetch(f.data,{signal:t}).then((A=>{if(A.ok)return s=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,f))).then((r=>{f.data=r,this.addSource(A,a(f)),f.debug&&console.log(`${r.features.length} features, ${(performance.now()-s).toFixed(0)} ms`),e(this)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Source file ${f.data} is taking too long to fetch`),console.error(A.message)}))}));o(f.data,f).then((e=>(f.data=e,this.addSource(A,a(f)),new Promise(((A,e)=>A(this))))))};t.Map.prototype.setH3JData=function(A,e,r){const t=Object.assign({},n,r);t.generate=A=>"Polygon"===t.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),t.promoteId&&(t.promoteId="h3id");const a=new AbortController,f=a.signal,s=this.getSource(A);let u;"string"==typeof e?(t.timeout>0&&setTimeout((()=>a.abort()),t.timeout),fetch(e,{signal:f}).then((A=>{if(A.ok)return u=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,t))).then((A=>{s.setData(A),t.debug&&console.log(`${A.features.length} features, ${(performance.now()-u).toFixed(0)} ms`)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Data file ${e} is taking too long to fetch`),console.error(A.message)}))):o(e,t).then((A=>s.setData(A)))}},{"geojson-vt":6,"h3-js":7,"vt-pbf":10}]},{},[12])(12)})); \ No newline at end of file diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css new file mode 100644 index 0000000..0347a27 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css @@ -0,0 +1,88 @@ + +/* Override default control style */ +.mapbox-gl-draw_ctrl-bottom-left, +.mapbox-gl-draw_ctrl-top-left { + margin-left:0; + border-radius:0 4px 4px 0; +} +.mapbox-gl-draw_ctrl-top-right, +.mapbox-gl-draw_ctrl-bottom-right { + margin-right:0; + border-radius:4px 0 0 4px; +} + +.mapbox-gl-draw_ctrl-draw-btn { + border-color:rgba(0,0,0,0.9); + color:rgba(255,255,255,0.5); + width:30px; + height:30px; +} + +.mapbox-gl-draw_ctrl-draw-btn.active, +.mapbox-gl-draw_ctrl-draw-btn.active:hover { + background-color:rgb(0 0 0/5%); +} +.mapbox-gl-draw_ctrl-draw-btn { + background-repeat: no-repeat; + background-position: center; +} + +.mapbox-gl-draw_point { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m10 2c-3.3 0-6 2.7-6 6s6 9 6 9 6-5.7 6-9-2.7-6-6-6zm0 2c2.1 0 3.8 1.7 3.8 3.8 0 1.5-1.8 3.9-2.9 5.2h-1.7c-1.1-1.4-2.9-3.8-2.9-5.2-.1-2.1 1.6-3.8 3.7-3.8z"/>%3C/svg>'); +} +.mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m15 12.3v-4.6c.6-.3 1-1 1-1.7 0-1.1-.9-2-2-2-.7 0-1.4.4-1.7 1h-4.6c-.3-.6-1-1-1.7-1-1.1 0-2 .9-2 2 0 .7.4 1.4 1 1.7v4.6c-.6.3-1 1-1 1.7 0 1.1.9 2 2 2 .7 0 1.4-.4 1.7-1h4.6c.3.6 1 1 1.7 1 1.1 0 2-.9 2-2 0-.7-.4-1.4-1-1.7zm-8-.3v-4l1-1h4l1 1v4l-1 1h-4z"/>%3C/svg>'); +} +.mapbox-gl-draw_line { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m13.5 3.5c-1.4 0-2.5 1.1-2.5 2.5 0 .3 0 .6.2.9l-3.8 3.8c-.3-.1-.6-.2-.9-.2-1.4 0-2.5 1.1-2.5 2.5s1.1 2.5 2.5 2.5 2.5-1.1 2.5-2.5c0-.3 0-.6-.2-.9l3.8-3.8c.3.1.6.2.9.2 1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5z"/>%3C/svg>'); +} +.mapbox-gl-draw_trash { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="M10,3.4 c-0.8,0-1.5,0.5-1.8,1.2H5l-1,1v1h12v-1l-1-1h-3.2C11.5,3.9,10.8,3.4,10,3.4z M5,8v7c0,1,1,2,2,2h6c1,0,2-1,2-2V8h-2v5.5h-1.5V8h-3 v5.5H7V8H5z"/>%3C/svg>'); +} +.mapbox-gl-draw_uncombine { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m12 2c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l1 1c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-1-1c-.2-.2-.4-.3-.7-.3zm4 4c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l1 1c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-1-1c-.2-.2-.4-.3-.7-.3zm-7 1c-1 0-1 1-.5 1.5.3.3 1 1 1 1l-1 1s-.5.5 0 1 1 0 1 0l1-1 1 1c.5.5 1.5.5 1.5-.5v-4zm-5 3c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l4.9 4.9c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-4.9-4.9c-.1-.2-.4-.3-.7-.3z"/>%3C/svg>'); +} +.mapbox-gl-draw_combine { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="M12.1,2c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l4.9,4.9c0.4,0.4,1,0.4,1.4,0l1-1 c0.4-0.4,0.4-1,0-1.4l-4.9-4.9C12.6,2.1,12.3,2,12.1,2z M8,8C7,8,7,9,7.5,9.5c0.3,0.3,1,1,1,1l-1,1c0,0-0.5,0.5,0,1s1,0,1,0l1-1l1,1 C11,13,12,13,12,12V8H8z M4,10c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l1,1c0.4,0.4,1,0.4,1.4,0l1-1c0.4-0.4,0.4-1,0-1.4 l-1-1C4.5,10.1,4.3,10,4,10z M8,14c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l1,1c0.4,0.4,1,0.4,1.4,0l1-1 c0.4-0.4,0.4-1,0-1.4l-1-1C8.5,14.1,8.3,14,8,14z"/>%3C/svg>'); +} + +.mapboxgl-map.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: pointer; +} +.mapboxgl-map.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mouse-add .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: crosshair; +} +.mapboxgl-map.mouse-move.mode-direct_select .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: grab; + cursor: -moz-grab; + cursor: -webkit-grab; +} +.mapboxgl-map.mode-direct_select.feature-vertex.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mode-direct_select.feature-midpoint.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: cell; +} +.mapboxgl-map.mode-direct_select.feature-feature.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mode-static.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: grab; + cursor: -moz-grab; + cursor: -webkit-grab; +} + +.mapbox-gl-draw_boxselect { + pointer-events: none; + position: absolute; + top: 0; + left: 0; + width: 0; + height: 0; + background: rgba(0,0,0,.1); + border: 2px dotted #fff; + opacity: 0.5; +} diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js new file mode 100644 index 0000000..271f1f7 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js @@ -0,0 +1,2 @@ +var e,t;e=this,t=function(){const e=function(e,t){const o={drag:[],click:[],mousemove:[],mousedown:[],mouseup:[],mouseout:[],keydown:[],keyup:[],touchstart:[],touchmove:[],touchend:[],tap:[]},n={on(e,t,n){if(void 0===o[e])throw new Error(`Invalid event type: ${e}`);o[e].push({selector:t,fn:n})},render(e){t.store.featureChanged(e)}},r=function(e,r){const i=o[e];let s=i.length;for(;s--;){const e=i[s];if(e.selector(r)){e.fn.call(n,r)||t.store.render(),t.ui.updateMapClasses();break}}};return e.start.call(n),{render:e.render,stop(){e.stop&&e.stop()},trash(){e.trash&&(e.trash(),t.store.render())},combineFeatures(){e.combineFeatures&&e.combineFeatures()},uncombineFeatures(){e.uncombineFeatures&&e.uncombineFeatures()},drag(e){r("drag",e)},click(e){r("click",e)},mousemove(e){r("mousemove",e)},mousedown(e){r("mousedown",e)},mouseup(e){r("mouseup",e)},mouseout(e){r("mouseout",e)},keydown(e){r("keydown",e)},keyup(e){r("keyup",e)},touchstart(e){r("touchstart",e)},touchmove(e){r("touchmove",e)},touchend(e){r("touchend",e)},tap(e){r("tap",e)}}};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var o,n,r={},i={};function s(){return o||(o=1,i.RADIUS=6378137,i.FLATTENING=1/298.257223563,i.POLAR_RADIUS=6356752.3142),i}var a=function(){if(n)return r;n=1;var e=s();function t(e){var t=0;if(e&&e.length>0){t+=Math.abs(o(e[0]));for(var n=1;n2){for(c=0;c(e.geometry.type===h.POLYGON&&(e.area=c.geometry({type:h.FEATURE,property:{},geometry:e.geometry})),e))).sort(S).map((e=>(delete e.area,e)))}function L(e,t=0){return[[e.point.x-t,e.point.y-t],[e.point.x+t,e.point.y+t]]}function M(e){if(this._items={},this._nums={},this._length=e?e.length:0,e)for(let t=0,o=e.length;t{e.push({k:t,v:this._items[t]})})),Object.keys(this._nums).forEach((t=>{e.push({k:JSON.parse(t),v:this._nums[t]})})),e.sort(((e,t)=>e.v-t.v)).map((e=>e.k))},M.prototype.clear=function(){return this._length=0,this._items={},this._nums={},this};const N=[y.FEATURE,y.MIDPOINT,y.VERTEX];var b={click:function(e,t,o){return x(e,t,o,o.options.clickBuffer)},touch:function(e,t,o){return x(e,t,o,o.options.touchBuffer)}};function x(e,t,o,n){if(null===o.map)return[];const r=e?L(e,n):t,i={};o.options.styles&&(i.layers=o.options.styles.map((e=>e.id)).filter((e=>null!=o.map.getLayer(e))));const s=o.map.queryRenderedFeatures(r,i).filter((e=>-1!==N.indexOf(e.properties.meta))),a=new M,c=[];return s.forEach((e=>{const t=e.properties.id;a.has(t)||(a.add(t),c.push(e))})),O(c)}function A(e,t){const o=b.click(e,null,t),n={mouse:d.NONE};return o[0]&&(n.mouse=o[0].properties.active===E.ACTIVE?d.MOVE:d.POINTER,n.feature=o[0].properties.meta),-1!==t.events.currentModeName().indexOf("draw")&&(n.mouse=d.ADD),t.ui.queueMapClasses(n),t.ui.updateMapClasses(),o[0]}function P(e,t){const o=e.x-t.x,n=e.y-t.y;return Math.sqrt(o*o+n*n)}const F=4,R=12,w=500;function D(e,t,o={}){const n=null!=o.fineTolerance?o.fineTolerance:F,r=null!=o.grossTolerance?o.grossTolerance:R,i=null!=o.interval?o.interval:w;e.point=e.point||t.point,e.time=e.time||t.time;const s=P(e.point,t.point);return s(o=t)=>{let n="",r=0|o;for(;r--;)n+=e[Math.random()*e.length|0];return n})("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",32);function B(){return G()}const j=function(e,t){this.ctx=e,this.properties=t.properties||{},this.coordinates=t.geometry.coordinates,this.id=t.id||B(),this.type=t.geometry.type};j.prototype.changed=function(){this.ctx.store.featureChanged(this.id)},j.prototype.incomingCoords=function(e){this.setCoordinates(e)},j.prototype.setCoordinates=function(e){this.coordinates=e,this.changed()},j.prototype.getCoordinates=function(){return JSON.parse(JSON.stringify(this.coordinates))},j.prototype.setProperty=function(e,t){this.properties[e]=t},j.prototype.toGeoJSON=function(){return JSON.parse(JSON.stringify({id:this.id,type:h.FEATURE,properties:this.properties,geometry:{coordinates:this.getCoordinates(),type:this.type}}))},j.prototype.internal=function(e){const t={id:this.id,meta:y.FEATURE,"meta:type":this.type,active:E.INACTIVE,mode:e};if(this.ctx.options.userProperties)for(const e in this.properties)t[`user_${e}`]=this.properties[e];return{type:h.FEATURE,properties:t,geometry:{coordinates:this.getCoordinates(),type:this.type}}};const J=function(e,t){j.call(this,e,t)};(J.prototype=Object.create(j.prototype)).isValid=function(){return"number"==typeof this.coordinates[0]&&"number"==typeof this.coordinates[1]},J.prototype.updateCoordinate=function(e,t,o){this.coordinates=3===arguments.length?[t,o]:[e,t],this.changed()},J.prototype.getCoordinate=function(){return this.getCoordinates()};const $=function(e,t){j.call(this,e,t)};($.prototype=Object.create(j.prototype)).isValid=function(){return this.coordinates.length>1},$.prototype.addCoordinate=function(e,t,o){this.changed();const n=parseInt(e,10);this.coordinates.splice(n,0,[t,o])},$.prototype.getCoordinate=function(e){const t=parseInt(e,10);return JSON.parse(JSON.stringify(this.coordinates[t]))},$.prototype.removeCoordinate=function(e){this.changed(),this.coordinates.splice(parseInt(e,10),1)},$.prototype.updateCoordinate=function(e,t,o){const n=parseInt(e,10);this.coordinates[n]=[t,o],this.changed()};const Y=function(e,t){j.call(this,e,t),this.coordinates=this.coordinates.map((e=>e.slice(0,-1)))};(Y.prototype=Object.create(j.prototype)).isValid=function(){return 0!==this.coordinates.length&&this.coordinates.every((e=>e.length>2))},Y.prototype.incomingCoords=function(e){this.coordinates=e.map((e=>e.slice(0,-1))),this.changed()},Y.prototype.setCoordinates=function(e){this.coordinates=e,this.changed()},Y.prototype.addCoordinate=function(e,t,o){this.changed();const n=e.split(".").map((e=>parseInt(e,10)));this.coordinates[n[0]].splice(n[1],0,[t,o])},Y.prototype.removeCoordinate=function(e){this.changed();const t=e.split(".").map((e=>parseInt(e,10))),o=this.coordinates[t[0]];o&&(o.splice(t[1],1),o.length<3&&this.coordinates.splice(t[0],1))},Y.prototype.getCoordinate=function(e){const t=e.split(".").map((e=>parseInt(e,10))),o=this.coordinates[t[0]];return JSON.parse(JSON.stringify(o[t[1]]))},Y.prototype.getCoordinates=function(){return this.coordinates.map((e=>e.concat([e[0]])))},Y.prototype.updateCoordinate=function(e,t,o){this.changed();const n=e.split("."),r=parseInt(n[0],10),i=parseInt(n[1],10);void 0===this.coordinates[r]&&(this.coordinates[r]=[]),this.coordinates[r][i]=[t,o]};const H={MultiPoint:J,MultiLineString:$,MultiPolygon:Y},X=(e,t,o,n,r)=>{const i=o.split("."),s=parseInt(i[0],10),a=i[1]?i.slice(1).join("."):null;return e[s][t](a,n,r)},q=function(e,t){if(j.call(this,e,t),delete this.coordinates,this.model=H[t.geometry.type],void 0===this.model)throw new TypeError(`${t.geometry.type} is not a valid type`);this.features=this._coordinatesToFeatures(t.geometry.coordinates)};function Z(e){this.map=e.map,this.drawConfig=JSON.parse(JSON.stringify(e.options||{})),this._ctx=e}(q.prototype=Object.create(j.prototype))._coordinatesToFeatures=function(e){const t=this.model.bind(this);return e.map((e=>new t(this.ctx,{id:B(),type:h.FEATURE,properties:{},geometry:{coordinates:e,type:this.type.replace("Multi","")}})))},q.prototype.isValid=function(){return this.features.every((e=>e.isValid()))},q.prototype.setCoordinates=function(e){this.features=this._coordinatesToFeatures(e),this.changed()},q.prototype.getCoordinate=function(e){return X(this.features,"getCoordinate",e)},q.prototype.getCoordinates=function(){return JSON.parse(JSON.stringify(this.features.map((e=>e.type===h.POLYGON?e.getCoordinates():e.coordinates))))},q.prototype.updateCoordinate=function(e,t,o){X(this.features,"updateCoordinate",e,t,o),this.changed()},q.prototype.addCoordinate=function(e,t,o){X(this.features,"addCoordinate",e,t,o),this.changed()},q.prototype.removeCoordinate=function(e){X(this.features,"removeCoordinate",e),this.changed()},q.prototype.getFeatures=function(){return this.features},Z.prototype.setSelected=function(e){return this._ctx.store.setSelected(e)},Z.prototype.setSelectedCoordinates=function(e){this._ctx.store.setSelectedCoordinates(e),e.reduce(((e,t)=>(void 0===e[t.feature_id]&&(e[t.feature_id]=!0,this._ctx.store.get(t.feature_id).changed()),e)),{})},Z.prototype.getSelected=function(){return this._ctx.store.getSelected()},Z.prototype.getSelectedIds=function(){return this._ctx.store.getSelectedIds()},Z.prototype.isSelected=function(e){return this._ctx.store.isSelected(e)},Z.prototype.getFeature=function(e){return this._ctx.store.get(e)},Z.prototype.select=function(e){return this._ctx.store.select(e)},Z.prototype.deselect=function(e){return this._ctx.store.deselect(e)},Z.prototype.deleteFeature=function(e,t={}){return this._ctx.store.delete(e,t)},Z.prototype.addFeature=function(e,t={}){return this._ctx.store.add(e,t)},Z.prototype.clearSelectedFeatures=function(){return this._ctx.store.clearSelected()},Z.prototype.clearSelectedCoordinates=function(){return this._ctx.store.clearSelectedCoordinates()},Z.prototype.setActionableState=function(e={}){const t={trash:e.trash||!1,combineFeatures:e.combineFeatures||!1,uncombineFeatures:e.uncombineFeatures||!1};return this._ctx.events.actionable(t)},Z.prototype.changeMode=function(e,t={},o={}){return this._ctx.events.changeMode(e,t,o)},Z.prototype.fire=function(e,t){return this._ctx.events.fire(e,t)},Z.prototype.updateUIClasses=function(e){return this._ctx.ui.queueMapClasses(e)},Z.prototype.activateUIButton=function(e){return this._ctx.ui.setActiveButton(e)},Z.prototype.featuresAt=function(e,t,o="click"){if("click"!==o&&"touch"!==o)throw new Error("invalid buffer type");return b[o](e,t,this._ctx)},Z.prototype.newFeature=function(e){const t=e.geometry.type;return t===h.POINT?new J(this._ctx,e):t===h.LINE_STRING?new $(this._ctx,e):t===h.POLYGON?new Y(this._ctx,e):new q(this._ctx,e)},Z.prototype.isInstanceOf=function(e,t){if(e===h.POINT)return t instanceof J;if(e===h.LINE_STRING)return t instanceof $;if(e===h.POLYGON)return t instanceof Y;if("MultiFeature"===e)return t instanceof q;throw new Error(`Unknown feature class: ${e}`)},Z.prototype.doRender=function(e){return this._ctx.store.featureChanged(e)},Z.prototype.onSetup=function(){},Z.prototype.onDrag=function(){},Z.prototype.onClick=function(){},Z.prototype.onMouseMove=function(){},Z.prototype.onMouseDown=function(){},Z.prototype.onMouseUp=function(){},Z.prototype.onMouseOut=function(){},Z.prototype.onKeyUp=function(){},Z.prototype.onKeyDown=function(){},Z.prototype.onTouchStart=function(){},Z.prototype.onTouchMove=function(){},Z.prototype.onTouchEnd=function(){},Z.prototype.onTap=function(){},Z.prototype.onStop=function(){},Z.prototype.onTrash=function(){},Z.prototype.onCombineFeature=function(){},Z.prototype.onUncombineFeature=function(){},Z.prototype.toDisplayFeatures=function(){throw new Error("You must overwrite toDisplayFeatures")};const W={drag:"onDrag",click:"onClick",mousemove:"onMouseMove",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseout:"onMouseOut",keyup:"onKeyUp",keydown:"onKeyDown",touchstart:"onTouchStart",touchmove:"onTouchMove",touchend:"onTouchEnd",tap:"onTap"},K=Object.keys(W);function z(e){const t=Object.keys(e);return function(o,n={}){let r={};const i=t.reduce(((t,o)=>(t[o]=e[o],t)),new Z(o));return{start(){r=i.onSetup(n),K.forEach((t=>{const o=W[t];let n=()=>!1;var s;e[o]&&(n=()=>!0),this.on(t,n,(s=o,e=>i[s](r,e)))}))},stop(){i.onStop(r)},trash(){i.onTrash(r)},combineFeatures(){i.onCombineFeatures(r)},uncombineFeatures(){i.onUncombineFeatures(r)},render(e,t){i.toDisplayFeatures(r,e,t)}}}}function Q(e){return[].concat(e).filter((e=>void 0!==e))}function ee(){const e=this;if(!e.ctx.map||void 0===e.ctx.map.getSource(l.HOT))return a();const t=e.ctx.events.currentModeName();e.ctx.ui.queueMapClasses({mode:t});let o=[],n=[];e.isDirty?n=e.getAllIds():(o=e.getChangedIds().filter((t=>void 0!==e.get(t))),n=e.sources.hot.filter((t=>t.properties.id&&-1===o.indexOf(t.properties.id)&&void 0!==e.get(t.properties.id))).map((e=>e.properties.id))),e.sources.hot=[];const r=e.sources.cold.length;e.sources.cold=e.isDirty?[]:e.sources.cold.filter((e=>{const t=e.properties.id||e.properties.parent;return-1===o.indexOf(t)}));const i=r!==e.sources.cold.length||n.length>0;function s(o,n){const r=e.get(o).internal(t);e.ctx.events.currentModeRender(r,(o=>{o.properties.mode=t,e.sources[n].push(o)}))}function a(){e.isDirty=!1,e.clearChangedIds()}o.forEach((e=>s(e,"hot"))),n.forEach((e=>s(e,"cold"))),i&&e.ctx.map.getSource(l.COLD).setData({type:h.FEATURE_COLLECTION,features:e.sources.cold}),e.ctx.map.getSource(l.HOT).setData({type:h.FEATURE_COLLECTION,features:e.sources.hot}),a()}function te(e){let t;this._features={},this._featureIds=new M,this._selectedFeatureIds=new M,this._selectedCoordinates=[],this._changedFeatureIds=new M,this._emitSelectionChange=!1,this._mapInitialConfig={},this.ctx=e,this.sources={hot:[],cold:[]},this.render=()=>{t||(t=requestAnimationFrame((()=>{t=null,ee.call(this),this._emitSelectionChange&&(this.ctx.events.fire(g.SELECTION_CHANGE,{features:this.getSelected().map((e=>e.toGeoJSON())),points:this.getSelectedCoordinates().map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e.coordinates}})))}),this._emitSelectionChange=!1),this.ctx.events.fire(g.RENDER,{})})))},this.isDirty=!1}function oe(e,t={}){const o=e._selectedCoordinates.filter((t=>e._selectedFeatureIds.has(t.feature_id)));e._selectedCoordinates.length===o.length||t.silent||(e._emitSelectionChange=!0),e._selectedCoordinates=o}te.prototype.createRenderBatch=function(){const e=this.render;let t=0;return this.render=function(){t++},()=>{this.render=e,t>0&&this.render()}},te.prototype.setDirty=function(){return this.isDirty=!0,this},te.prototype.featureCreated=function(e,t={}){if(this._changedFeatureIds.add(e),!0!==(null!=t.silent?t.silent:this.ctx.options.suppressAPIEvents)){const t=this.get(e);this.ctx.events.fire(g.CREATE,{features:[t.toGeoJSON()]})}return this},te.prototype.featureChanged=function(e,t={}){return this._changedFeatureIds.add(e),!0!==(null!=t.silent?t.silent:this.ctx.options.suppressAPIEvents)&&this.ctx.events.fire(g.UPDATE,{action:t.action?t.action:m.CHANGE_COORDINATES,features:[this.get(e).toGeoJSON()]}),this},te.prototype.getChangedIds=function(){return this._changedFeatureIds.values()},te.prototype.clearChangedIds=function(){return this._changedFeatureIds.clear(),this},te.prototype.getAllIds=function(){return this._featureIds.values()},te.prototype.add=function(e,t={}){return this._features[e.id]=e,this._featureIds.add(e.id),this.featureCreated(e.id,{silent:t.silent}),this},te.prototype.delete=function(e,t={}){const o=[];return Q(e).forEach((e=>{this._featureIds.has(e)&&(this._featureIds.delete(e),this._selectedFeatureIds.delete(e),t.silent||-1===o.indexOf(this._features[e])&&o.push(this._features[e].toGeoJSON()),delete this._features[e],this.isDirty=!0)})),o.length&&this.ctx.events.fire(g.DELETE,{features:o}),oe(this,t),this},te.prototype.get=function(e){return this._features[e]},te.prototype.getAll=function(){return Object.keys(this._features).map((e=>this._features[e]))},te.prototype.select=function(e,t={}){return Q(e).forEach((e=>{this._selectedFeatureIds.has(e)||(this._selectedFeatureIds.add(e),this._changedFeatureIds.add(e),t.silent||(this._emitSelectionChange=!0))})),this},te.prototype.deselect=function(e,t={}){return Q(e).forEach((e=>{this._selectedFeatureIds.has(e)&&(this._selectedFeatureIds.delete(e),this._changedFeatureIds.add(e),t.silent||(this._emitSelectionChange=!0))})),oe(this,t),this},te.prototype.clearSelected=function(e={}){return this.deselect(this._selectedFeatureIds.values(),{silent:e.silent}),this},te.prototype.setSelected=function(e,t={}){return e=Q(e),this.deselect(this._selectedFeatureIds.values().filter((t=>-1===e.indexOf(t))),{silent:t.silent}),this.select(e.filter((e=>!this._selectedFeatureIds.has(e))),{silent:t.silent}),this},te.prototype.setSelectedCoordinates=function(e){return this._selectedCoordinates=e,this._emitSelectionChange=!0,this},te.prototype.clearSelectedCoordinates=function(){return this._selectedCoordinates=[],this._emitSelectionChange=!0,this},te.prototype.getSelectedIds=function(){return this._selectedFeatureIds.values()},te.prototype.getSelected=function(){return this.getSelectedIds().map((e=>this.get(e)))},te.prototype.getSelectedCoordinates=function(){return this._selectedCoordinates.map((e=>({coordinates:this.get(e.feature_id).getCoordinate(e.coord_path)})))},te.prototype.isSelected=function(e){return this._selectedFeatureIds.has(e)},te.prototype.setFeatureProperty=function(e,t,o,n={}){this.get(e).setProperty(t,o),this.featureChanged(e,{silent:n.silent,action:m.CHANGE_PROPERTIES})},te.prototype.storeMapConfig=function(){T.forEach((e=>{this.ctx.map[e]&&(this._mapInitialConfig[e]=this.ctx.map[e].isEnabled())}))},te.prototype.restoreMapConfig=function(){Object.keys(this._mapInitialConfig).forEach((e=>{this._mapInitialConfig[e]?this.ctx.map[e].enable():this.ctx.map[e].disable()}))},te.prototype.getInitialConfigValue=function(e){return void 0===this._mapInitialConfig[e]||this._mapInitialConfig[e]};const ne=["mode","feature","mouse"];function re(t){let o=null,n=null;const r={onRemove(){return t.map.off("load",r.connect),clearInterval(n),r.removeLayers(),t.store.restoreMapConfig(),t.ui.removeButtons(),t.events.removeEventListeners(),t.ui.clearMapClasses(),t.boxZoomInitial&&t.map.boxZoom.enable(),t.map=null,t.container=null,t.store=null,o&&o.parentNode&&o.parentNode.removeChild(o),o=null,this},connect(){t.map.off("load",r.connect),clearInterval(n),r.addLayers(),t.store.storeMapConfig(),t.events.addEventListeners()},onAdd(i){if(t.map=i,t.events=function(t){const o=Object.keys(t.options.modes).reduce(((e,o)=>(e[o]=z(t.options.modes[o]),e)),{});let n={},r={};const i={};let s=null,a=null;i.drag=function(e,o){o({point:e.point,time:(new Date).getTime()})?(t.ui.queueMapClasses({mouse:d.DRAG}),a.drag(e)):e.originalEvent.stopPropagation()},i.mousedrag=function(e){i.drag(e,(e=>!D(n,e)))},i.touchdrag=function(e){i.drag(e,(e=>!V(r,e)))},i.mousemove=function(e){if(1===(void 0!==e.originalEvent.buttons?e.originalEvent.buttons:e.originalEvent.which))return i.mousedrag(e);const o=A(e,t);e.featureTarget=o,a.mousemove(e)},i.mousedown=function(e){n={time:(new Date).getTime(),point:e.point};const o=A(e,t);e.featureTarget=o,a.mousedown(e)},i.mouseup=function(e){const o=A(e,t);e.featureTarget=o,D(n,{point:e.point,time:(new Date).getTime()})?a.click(e):a.mouseup(e)},i.mouseout=function(e){a.mouseout(e)},i.touchstart=function(e){if(!t.options.touchEnabled)return;r={time:(new Date).getTime(),point:e.point};const o=b.touch(e,null,t)[0];e.featureTarget=o,a.touchstart(e)},i.touchmove=function(e){if(t.options.touchEnabled)return a.touchmove(e),i.touchdrag(e)},i.touchend=function(e){if(e.originalEvent.preventDefault(),!t.options.touchEnabled)return;const o=b.touch(e,null,t)[0];e.featureTarget=o,V(r,{time:(new Date).getTime(),point:e.point})?a.tap(e):a.touchend(e)};const c=e=>!(8===e||46===e||e>=48&&e<=57);function l(n,r,i={}){a.stop();const c=o[n];if(void 0===c)throw new Error(`${n} is not valid`);s=n;const u=c(t,r);a=e(u,t),i.silent||t.map.fire(g.MODE_CHANGE,{mode:n}),t.store.setDirty(),t.store.render()}i.keydown=function(e){(e.srcElement||e.target).classList.contains(u.CANVAS)&&(8!==e.keyCode&&46!==e.keyCode||!t.options.controls.trash?c(e.keyCode)?a.keydown(e):49===e.keyCode&&t.options.controls.point?l(f.DRAW_POINT):50===e.keyCode&&t.options.controls.line_string?l(f.DRAW_LINE_STRING):51===e.keyCode&&t.options.controls.polygon&&l(f.DRAW_POLYGON):(e.preventDefault(),a.trash()))},i.keyup=function(e){c(e.keyCode)&&a.keyup(e)},i.zoomend=function(){t.store.changeZoom()},i.data=function(e){if("style"===e.dataType){const{setup:e,map:o,options:n,store:r}=t;n.styles.some((e=>o.getLayer(e.id)))||(e.addLayers(),r.setDirty(),r.render())}};const p={trash:!1,combineFeatures:!1,uncombineFeatures:!1};return{start(){s=t.options.defaultMode,a=e(o[s](t),t)},changeMode:l,actionable:function(e){let o=!1;Object.keys(e).forEach((t=>{if(void 0===p[t])throw new Error("Invalid action type");p[t]!==e[t]&&(o=!0),p[t]=e[t]})),o&&t.map.fire(g.ACTIONABLE,{actions:p})},currentModeName:()=>s,currentModeRender:(e,t)=>a.render(e,t),fire(e,o){t.map&&t.map.fire(e,o)},addEventListeners(){t.map.on("mousemove",i.mousemove),t.map.on("mousedown",i.mousedown),t.map.on("mouseup",i.mouseup),t.map.on("data",i.data),t.map.on("touchmove",i.touchmove),t.map.on("touchstart",i.touchstart),t.map.on("touchend",i.touchend),t.container.addEventListener("mouseout",i.mouseout),t.options.keybindings&&(t.container.addEventListener("keydown",i.keydown),t.container.addEventListener("keyup",i.keyup))},removeEventListeners(){t.map.off("mousemove",i.mousemove),t.map.off("mousedown",i.mousedown),t.map.off("mouseup",i.mouseup),t.map.off("data",i.data),t.map.off("touchmove",i.touchmove),t.map.off("touchstart",i.touchstart),t.map.off("touchend",i.touchend),t.container.removeEventListener("mouseout",i.mouseout),t.options.keybindings&&(t.container.removeEventListener("keydown",i.keydown),t.container.removeEventListener("keyup",i.keyup))},trash(e){a.trash(e)},combineFeatures(){a.combineFeatures()},uncombineFeatures(){a.uncombineFeatures()},getMode:()=>s}}(t),t.ui=function(e){const t={};let o=null,n={mode:null,feature:null,mouse:null},r={mode:null,feature:null,mouse:null};function i(e){r=Object.assign(r,e)}function s(){if(!e.container)return;const t=[],o=[];ne.forEach((e=>{r[e]!==n[e]&&(t.push(`${e}-${n[e]}`),null!==r[e]&&o.push(`${e}-${r[e]}`))})),t.length>0&&e.container.classList.remove(...t),o.length>0&&e.container.classList.add(...o),n=Object.assign(n,r)}function a(e,t={}){const n=document.createElement("button");return n.className=`${u.CONTROL_BUTTON} ${t.className}`,n.setAttribute("title",t.title),t.container.appendChild(n),n.addEventListener("click",(n=>{if(n.preventDefault(),n.stopPropagation(),n.target===o)return c(),void t.onDeactivate();l(e),t.onActivate()}),!0),n}function c(){o&&(o.classList.remove(u.ACTIVE_BUTTON),o=null)}function l(e){c();const n=t[e];n&&n&&"trash"!==e&&(n.classList.add(u.ACTIVE_BUTTON),o=n)}return{setActiveButton:l,queueMapClasses:i,updateMapClasses:s,clearMapClasses:function(){i({mode:null,feature:null,mouse:null}),s()},addButtons:function(){const o=e.options.controls,n=document.createElement("div");return n.className=`${u.CONTROL_GROUP} ${u.CONTROL_BASE}`,o?(o[p.LINE]&&(t[p.LINE]=a(p.LINE,{container:n,className:u.CONTROL_BUTTON_LINE,title:"LineString tool "+(e.options.keybindings?"(l)":""),onActivate:()=>e.events.changeMode(f.DRAW_LINE_STRING),onDeactivate:()=>e.events.trash()})),o[p.POLYGON]&&(t[p.POLYGON]=a(p.POLYGON,{container:n,className:u.CONTROL_BUTTON_POLYGON,title:"Polygon tool "+(e.options.keybindings?"(p)":""),onActivate:()=>e.events.changeMode(f.DRAW_POLYGON),onDeactivate:()=>e.events.trash()})),o[p.POINT]&&(t[p.POINT]=a(p.POINT,{container:n,className:u.CONTROL_BUTTON_POINT,title:"Marker tool "+(e.options.keybindings?"(m)":""),onActivate:()=>e.events.changeMode(f.DRAW_POINT),onDeactivate:()=>e.events.trash()})),o.trash&&(t.trash=a("trash",{container:n,className:u.CONTROL_BUTTON_TRASH,title:"Delete",onActivate:()=>{e.events.trash()}})),o.combine_features&&(t.combine_features=a("combineFeatures",{container:n,className:u.CONTROL_BUTTON_COMBINE_FEATURES,title:"Combine",onActivate:()=>{e.events.combineFeatures()}})),o.uncombine_features&&(t.uncombine_features=a("uncombineFeatures",{container:n,className:u.CONTROL_BUTTON_UNCOMBINE_FEATURES,title:"Uncombine",onActivate:()=>{e.events.uncombineFeatures()}})),n):n},removeButtons:function(){Object.keys(t).forEach((e=>{const o=t[e];o.parentNode&&o.parentNode.removeChild(o),delete t[e]}))}}}(t),t.container=i.getContainer(),t.store=new te(t),o=t.ui.addButtons(),t.options.boxSelect){t.boxZoomInitial=i.boxZoom.isEnabled(),i.boxZoom.disable();const e=i.dragPan.isEnabled();i.dragPan.disable(),i.dragPan.enable(),e||i.dragPan.disable()}return i.loaded()?r.connect():(i.on("load",r.connect),n=setInterval((()=>{i.loaded()&&r.connect()}),16)),t.events.start(),o},addLayers(){t.map.addSource(l.COLD,{data:{type:h.FEATURE_COLLECTION,features:[]},type:"geojson"}),t.map.addSource(l.HOT,{data:{type:h.FEATURE_COLLECTION,features:[]},type:"geojson"}),t.options.styles.forEach((e=>{t.map.addLayer(e)})),t.store.setDirty(!0),t.store.render()},removeLayers(){t.options.styles.forEach((e=>{t.map.getLayer(e.id)&&t.map.removeLayer(e.id)})),t.map.getSource(l.COLD)&&t.map.removeSource(l.COLD),t.map.getSource(l.HOT)&&t.map.removeSource(l.HOT)}};return t.setup=r,r}const ie="#3bb2d0",se="#fbb03b",ae="#fff";var ce=[{id:"gl-draw-polygon-fill",type:"fill",filter:["all",["==","$type","Polygon"]],paint:{"fill-color":["case",["==",["get","active"],"true"],se,ie],"fill-opacity":.1}},{id:"gl-draw-lines",type:"line",filter:["any",["==","$type","LineString"],["==","$type","Polygon"]],layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":["case",["==",["get","active"],"true"],se,ie],"line-dasharray":["case",["==",["get","active"],"true"],[.2,2],[2,0]],"line-width":2}},{id:"gl-draw-point-outer",type:"circle",filter:["all",["==","$type","Point"],["==","meta","feature"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],7,5],"circle-color":ae}},{id:"gl-draw-point-inner",type:"circle",filter:["all",["==","$type","Point"],["==","meta","feature"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],5,3],"circle-color":["case",["==",["get","active"],"true"],se,ie]}},{id:"gl-draw-vertex-outer",type:"circle",filter:["all",["==","$type","Point"],["==","meta","vertex"],["!=","mode","simple_select"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],7,5],"circle-color":ae}},{id:"gl-draw-vertex-inner",type:"circle",filter:["all",["==","$type","Point"],["==","meta","vertex"],["!=","mode","simple_select"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],5,3],"circle-color":se}},{id:"gl-draw-midpoint",type:"circle",filter:["all",["==","meta","midpoint"]],paint:{"circle-radius":3,"circle-color":se}}];function ue(e){return function(t){const o=t.featureTarget;return!!o&&!!o.properties&&o.properties.meta===e}}function le(e){return!!e.originalEvent&&!!e.originalEvent.shiftKey&&0===e.originalEvent.button}function de(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.active===E.ACTIVE&&e.featureTarget.properties.meta===y.FEATURE}function pe(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.active===E.INACTIVE&&e.featureTarget.properties.meta===y.FEATURE}function he(e){return void 0===e.featureTarget}function fe(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.meta===y.FEATURE}function ge(e){const t=e.featureTarget;return!!t&&!!t.properties&&t.properties.meta===y.VERTEX}function me(e){return!!e.originalEvent&&!0===e.originalEvent.shiftKey}function ye(e){return 27===e.keyCode}function Ee(e){return 13===e.keyCode}var Te=Object.freeze({__proto__:null,isActiveFeature:de,isEnterKey:Ee,isEscapeKey:ye,isFeature:fe,isInactiveFeature:pe,isOfMetaType:ue,isShiftDown:me,isShiftMousedown:le,isTrue:function(){return!0},isVertex:ge,noTarget:he});function Ce(e,t){this.x=e,this.y=t}function _e(e,t){const o=t.getBoundingClientRect();return new Ce(e.clientX-o.left-(t.clientLeft||0),e.clientY-o.top-(t.clientTop||0))}function ve(e,t,o,n){return{type:h.FEATURE,properties:{meta:y.VERTEX,parent:e,coord_path:o,active:n?E.ACTIVE:E.INACTIVE},geometry:{type:h.POINT,coordinates:t}}}function Ie(e,t,o){const n=t.geometry.coordinates,r=o.geometry.coordinates;if(n[1]>_||n[1]_||r[1]{const u=null!=o?`${o}.${a}`:String(a),l=ve(i,e,u,c(u));if(t.midpoints&&r){const e=Ie(i,r,l);e&&s.push(e)}r=l;const d=JSON.stringify(e);n!==d&&s.push(l),0===a&&(n=d)}))}function c(e){return!!t.selectedPaths&&-1!==t.selectedPaths.indexOf(e)}return n===h.POINT?s.push(ve(i,r,o,c(o))):n===h.POLYGON?r.forEach(((e,t)=>{a(e,null!==o?`${o}.${t}`:String(t))})):n===h.LINE_STRING?a(r,o):0===n.indexOf(h.MULTI_PREFIX)&&function(){const o=n.replace(h.MULTI_PREFIX,"");r.forEach(((n,r)=>{const i={type:h.FEATURE,properties:e.properties,geometry:{type:o,coordinates:n}};s=s.concat(Se(i,t,r))}))}(),s}Ce.prototype={clone(){return new Ce(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){const t=e.x-this.x,o=e.y-this.y;return t*t+o*o},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){const t=e[0]*this.x+e[1]*this.y,o=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=o,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){const e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){const t=Math.cos(e),o=Math.sin(e),n=t*this.x-o*this.y,r=o*this.x+t*this.y;return this.x=n,this.y=r,this},_rotateAround(e,t){const o=Math.cos(e),n=Math.sin(e),r=t.x+o*(this.x-t.x)-n*(this.y-t.y),i=t.y+n*(this.x-t.x)+o*(this.y-t.y);return this.x=r,this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:Ce},Ce.convert=function(e){if(e instanceof Ce)return e;if(Array.isArray(e))return new Ce(+e[0],+e[1]);if(void 0!==e.x&&void 0!==e.y)return new Ce(+e.x,+e.y);throw new Error("Expected [x, y] or {x, y} point format")};var Oe={enable(e){setTimeout((()=>{e.map&&e.map.doubleClickZoom&&e._ctx&&e._ctx.store&&e._ctx.store.getInitialConfigValue&&e._ctx.store.getInitialConfigValue("doubleClickZoom")&&e.map.doubleClickZoom.enable()}),0)},disable(e){setTimeout((()=>{e.map&&e.map.doubleClickZoom&&e.map.doubleClickZoom.disable()}),0)}};const{LAT_MIN:Le,LAT_MAX:Me,LAT_RENDERED_MIN:Ne,LAT_RENDERED_MAX:be,LNG_MIN:xe,LNG_MAX:Ae}=v;function Pe(e,t){let o=Le,n=Me,r=Le,i=Me,s=Ae,a=xe;e.forEach((e=>{const t=function(e){const t={Point:0,LineString:1,Polygon:2,MultiPoint:1,MultiLineString:2,MultiPolygon:3}[e.geometry.type],o=[e.geometry.coordinates].flat(t),n=o.map((e=>e[0])),r=o.map((e=>e[1])),i=e=>Math.min.apply(null,e),s=e=>Math.max.apply(null,e);return[i(n),i(r),s(n),s(r)]}(e),c=t[1],u=t[3],l=t[0],d=t[2];c>o&&(o=c),ur&&(r=u),ca&&(a=d)}));const c=t;return o+c.lat>be&&(c.lat=be-o),r+c.lat>Me&&(c.lat=Me-r),n+c.lat=Ae&&(c.lng-=360*Math.ceil(Math.abs(c.lng)/360)),c}function Fe(e,t){const o=Pe(e.map((e=>e.toGeoJSON())),t);e.forEach((e=>{const t=e.getCoordinates(),n=e=>{const t={lng:e[0]+o.lng,lat:e[1]+o.lat};return[t.lng,t.lat]},r=e=>e.map((e=>n(e))),i=e=>e.map((e=>r(e)));let s;e.type===h.POINT?s=n(t):e.type===h.LINE_STRING||e.type===h.MULTI_POINT?s=t.map(n):e.type===h.POLYGON||e.type===h.MULTI_LINE_STRING?s=t.map(r):e.type===h.MULTI_POLYGON&&(s=t.map(i)),e.incomingCoords(s)}))}const Re={onSetup:function(e){const t={dragMoveLocation:null,boxSelectStartLocation:null,boxSelectElement:void 0,boxSelecting:!1,canBoxSelect:!1,dragMoving:!1,canDragMove:!1,initialDragPanState:this.map.dragPan.isEnabled(),initiallySelectedFeatureIds:e.featureIds||[]};return this.setSelected(t.initiallySelectedFeatureIds.filter((e=>void 0!==this.getFeature(e)))),this.fireActionable(),this.setActionableState({combineFeatures:!0,uncombineFeatures:!0,trash:!0}),t},fireUpdate:function(){this.fire(g.UPDATE,{action:m.MOVE,features:this.getSelected().map((e=>e.toGeoJSON()))})},fireActionable:function(){const e=this.getSelected(),t=e.filter((e=>this.isInstanceOf("MultiFeature",e)));let o=!1;if(e.length>1){o=!0;const t=e[0].type.replace("Multi","");e.forEach((e=>{e.type.replace("Multi","")!==t&&(o=!1)}))}const n=t.length>0,r=e.length>0;this.setActionableState({combineFeatures:o,uncombineFeatures:n,trash:r})},getUniqueIds:function(e){return e.length?e.map((e=>e.properties.id)).filter((e=>void 0!==e)).reduce(((e,t)=>(e.add(t),e)),new M).values():[]},stopExtendedInteractions:function(e){e.boxSelectElement&&(e.boxSelectElement.parentNode&&e.boxSelectElement.parentNode.removeChild(e.boxSelectElement),e.boxSelectElement=null),(e.canDragMove||e.canBoxSelect)&&!0===e.initialDragPanState&&this.map.dragPan.enable(),e.boxSelecting=!1,e.canBoxSelect=!1,e.dragMoving=!1,e.canDragMove=!1},onStop:function(){Oe.enable(this)},onMouseMove:function(e,t){return fe(t)&&e.dragMoving&&this.fireUpdate(),this.stopExtendedInteractions(e),!0},onMouseOut:function(e){return!e.dragMoving||this.fireUpdate()}};Re.onTap=Re.onClick=function(e,t){return he(t)?this.clickAnywhere(e,t):ue(y.VERTEX)(t)?this.clickOnVertex(e,t):fe(t)?this.clickOnFeature(e,t):void 0},Re.clickAnywhere=function(e){const t=this.getSelectedIds();t.length&&(this.clearSelectedFeatures(),t.forEach((e=>this.doRender(e)))),Oe.enable(this),this.stopExtendedInteractions(e)},Re.clickOnVertex=function(e,t){this.changeMode(f.DIRECT_SELECT,{featureId:t.featureTarget.properties.parent,coordPath:t.featureTarget.properties.coord_path,startPos:t.lngLat}),this.updateUIClasses({mouse:d.MOVE})},Re.startOnActiveFeature=function(e,t){this.stopExtendedInteractions(e),this.map.dragPan.disable(),this.doRender(t.featureTarget.properties.id),e.canDragMove=!0,e.dragMoveLocation=t.lngLat},Re.clickOnFeature=function(e,t){Oe.disable(this),this.stopExtendedInteractions(e);const o=me(t),n=this.getSelectedIds(),r=t.featureTarget.properties.id,i=this.isSelected(r);if(!o&&i&&this.getFeature(r).type!==h.POINT)return this.changeMode(f.DIRECT_SELECT,{featureId:r});i&&o?(this.deselect(r),this.updateUIClasses({mouse:d.POINTER}),1===n.length&&Oe.enable(this)):!i&&o?(this.select(r),this.updateUIClasses({mouse:d.MOVE})):i||o||(n.forEach((e=>this.doRender(e))),this.setSelected(r),this.updateUIClasses({mouse:d.MOVE})),this.doRender(r)},Re.onMouseDown=function(e,t){return e.initialDragPanState=this.map.dragPan.isEnabled(),de(t)?this.startOnActiveFeature(e,t):this.drawConfig.boxSelect&&le(t)?this.startBoxSelect(e,t):void 0},Re.startBoxSelect=function(e,t){this.stopExtendedInteractions(e),this.map.dragPan.disable(),e.boxSelectStartLocation=_e(t.originalEvent,this.map.getContainer()),e.canBoxSelect=!0},Re.onTouchStart=function(e,t){if(de(t))return this.startOnActiveFeature(e,t)},Re.onDrag=function(e,t){return e.canDragMove?this.dragMove(e,t):this.drawConfig.boxSelect&&e.canBoxSelect?this.whileBoxSelect(e,t):void 0},Re.whileBoxSelect=function(e,t){e.boxSelecting=!0,this.updateUIClasses({mouse:d.ADD}),e.boxSelectElement||(e.boxSelectElement=document.createElement("div"),e.boxSelectElement.classList.add(u.BOX_SELECT),this.map.getContainer().appendChild(e.boxSelectElement));const o=_e(t.originalEvent,this.map.getContainer()),n=Math.min(e.boxSelectStartLocation.x,o.x),r=Math.max(e.boxSelectStartLocation.x,o.x),i=Math.min(e.boxSelectStartLocation.y,o.y),s=Math.max(e.boxSelectStartLocation.y,o.y),a=`translate(${n}px, ${i}px)`;e.boxSelectElement.style.transform=a,e.boxSelectElement.style.WebkitTransform=a,e.boxSelectElement.style.width=r-n+"px",e.boxSelectElement.style.height=s-i+"px"},Re.dragMove=function(e,t){e.dragMoving=!0,t.originalEvent.stopPropagation();const o={lng:t.lngLat.lng-e.dragMoveLocation.lng,lat:t.lngLat.lat-e.dragMoveLocation.lat};Fe(this.getSelected(),o),e.dragMoveLocation=t.lngLat},Re.onTouchEnd=Re.onMouseUp=function(e,t){if(e.dragMoving)this.fireUpdate();else if(e.boxSelecting){const o=[e.boxSelectStartLocation,_e(t.originalEvent,this.map.getContainer())],n=this.featuresAt(null,o,"click"),r=this.getUniqueIds(n).filter((e=>!this.isSelected(e)));r.length&&(this.select(r),r.forEach((e=>this.doRender(e))),this.updateUIClasses({mouse:d.MOVE}))}this.stopExtendedInteractions(e)},Re.toDisplayFeatures=function(e,t,o){t.properties.active=this.isSelected(t.properties.id)?E.ACTIVE:E.INACTIVE,o(t),this.fireActionable(),t.properties.active===E.ACTIVE&&t.geometry.type!==h.POINT&&Se(t).forEach(o)},Re.onTrash=function(){this.deleteFeature(this.getSelectedIds()),this.fireActionable()},Re.onCombineFeatures=function(){const e=this.getSelected();if(0===e.length||e.length<2)return;const t=[],o=[],n=e[0].type.replace("Multi","");for(let r=0;r{t.push(e)})):t.push(i.getCoordinates()),o.push(i.toGeoJSON())}if(o.length>1){const e=this.newFeature({type:h.FEATURE,properties:o[0].properties,geometry:{type:`Multi${n}`,coordinates:t}});this.addFeature(e),this.deleteFeature(this.getSelectedIds(),{silent:!0}),this.setSelected([e.id]),this.fire(g.COMBINE_FEATURES,{createdFeatures:[e.toGeoJSON()],deletedFeatures:o})}this.fireActionable()},Re.onUncombineFeatures=function(){const e=this.getSelected();if(0===e.length)return;const t=[],o=[];for(let n=0;n{this.addFeature(e),e.properties=r.properties,t.push(e.toGeoJSON()),this.select([e.id])})),this.deleteFeature(r.id,{silent:!0}),o.push(r.toGeoJSON()))}t.length>1&&this.fire(g.UNCOMBINE_FEATURES,{createdFeatures:t,deletedFeatures:o}),this.fireActionable()};const we=ue(y.VERTEX),De=ue(y.MIDPOINT),Ue={fireUpdate:function(){this.fire(g.UPDATE,{action:m.CHANGE_COORDINATES,features:this.getSelected().map((e=>e.toGeoJSON()))})},fireActionable:function(e){this.setActionableState({combineFeatures:!1,uncombineFeatures:!1,trash:e.selectedCoordPaths.length>0})},startDragging:function(e,t){e.initialDragPanState=this.map.dragPan.isEnabled(),this.map.dragPan.disable(),e.canDragMove=!0,e.dragMoveLocation=t.lngLat},stopDragging:function(e){e.canDragMove&&!0===e.initialDragPanState&&this.map.dragPan.enable(),e.dragMoving=!1,e.canDragMove=!1,e.dragMoveLocation=null},onVertex:function(e,t){this.startDragging(e,t);const o=t.featureTarget.properties,n=e.selectedCoordPaths.indexOf(o.coord_path);me(t)||-1!==n?me(t)&&-1===n&&e.selectedCoordPaths.push(o.coord_path):e.selectedCoordPaths=[o.coord_path];const r=this.pathsToCoordinates(e.featureId,e.selectedCoordPaths);this.setSelectedCoordinates(r)},onMidpoint:function(e,t){this.startDragging(e,t);const o=t.featureTarget.properties;e.feature.addCoordinate(o.coord_path,o.lng,o.lat),this.fireUpdate(),e.selectedCoordPaths=[o.coord_path]},pathsToCoordinates:function(e,t){return t.map((t=>({feature_id:e,coord_path:t})))},onFeature:function(e,t){0===e.selectedCoordPaths.length?this.startDragging(e,t):this.stopDragging(e)},dragFeature:function(e,t,o){Fe(this.getSelected(),o),e.dragMoveLocation=t.lngLat},dragVertex:function(e,t,o){const n=e.selectedCoordPaths.map((t=>e.feature.getCoordinate(t))),r=Pe(n.map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e}}))),o);for(let t=0;tt.localeCompare(e,"en",{numeric:!0}))).forEach((t=>e.feature.removeCoordinate(t))),this.fireUpdate(),e.selectedCoordPaths=[],this.clearSelectedCoordinates(),this.fireActionable(e),!1===e.feature.isValid()&&(this.deleteFeature([e.featureId]),this.changeMode(f.SIMPLE_SELECT,{}))},onMouseMove:function(e,t){const o=de(t),n=we(t),r=De(t),i=0===e.selectedCoordPaths.length;return o&&i||n&&!i?this.updateUIClasses({mouse:d.MOVE}):this.updateUIClasses({mouse:d.NONE}),(n||o||r)&&e.dragMoving&&this.fireUpdate(),this.stopDragging(e),!0},onMouseOut:function(e){return e.dragMoving&&this.fireUpdate(),!0}};Ue.onTouchStart=Ue.onMouseDown=function(e,t){return we(t)?this.onVertex(e,t):de(t)?this.onFeature(e,t):De(t)?this.onMidpoint(e,t):void 0},Ue.onDrag=function(e,t){if(!0!==e.canDragMove)return;e.dragMoving=!0,t.originalEvent.stopPropagation();const o={lng:t.lngLat.lng-e.dragMoveLocation.lng,lat:t.lngLat.lat-e.dragMoveLocation.lat};e.selectedCoordPaths.length>0?this.dragVertex(e,t,o):this.dragFeature(e,t,o),e.dragMoveLocation=t.lngLat},Ue.onClick=function(e,t){return he(t)?this.clickNoTarget(e,t):de(t)?this.clickActiveFeature(e,t):pe(t)?this.clickInactive(e,t):void this.stopDragging(e)},Ue.onTap=function(e,t){return he(t)?this.clickNoTarget(e,t):de(t)?this.clickActiveFeature(e,t):pe(t)?this.clickInactive(e,t):void 0},Ue.onTouchEnd=Ue.onMouseUp=function(e){e.dragMoving&&this.fireUpdate(),this.stopDragging(e)};const ke={};function Ve(e,t){return!!e.lngLat&&e.lngLat.lng===t[0]&&e.lngLat.lat===t[1]}ke.onSetup=function(){const e=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:[]}});return this.addFeature(e),this.clearSelectedFeatures(),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.POINT),this.setActionableState({trash:!0}),{point:e}},ke.stopDrawingAndRemove=function(e){this.deleteFeature([e.point.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)},ke.onTap=ke.onClick=function(e,t){this.updateUIClasses({mouse:d.MOVE}),e.point.updateCoordinate("",t.lngLat.lng,t.lngLat.lat),this.fire(g.CREATE,{features:[e.point.toGeoJSON()]}),this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.point.id]})},ke.onStop=function(e){this.activateUIButton(),e.point.getCoordinate().length||this.deleteFeature([e.point.id],{silent:!0})},ke.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.point.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t)},ke.onTrash=ke.stopDrawingAndRemove,ke.onKeyUp=function(e,t){if(ye(t)||Ee(t))return this.stopDrawingAndRemove(e,t)};const Ge={onSetup:function(){const e=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.POLYGON,coordinates:[[]]}});return this.addFeature(e),this.clearSelectedFeatures(),Oe.disable(this),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.POLYGON),this.setActionableState({trash:!0}),{polygon:e,currentVertexPosition:0}},clickAnywhere:function(e,t){if(e.currentVertexPosition>0&&Ve(t,e.polygon.coordinates[0][e.currentVertexPosition-1]))return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]});this.updateUIClasses({mouse:d.ADD}),e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat),e.currentVertexPosition++,e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat)},clickOnVertex:function(e){return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]})},onMouseMove:function(e,t){e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat),ge(t)&&this.updateUIClasses({mouse:d.POINTER})}};Ge.onTap=Ge.onClick=function(e,t){return ge(t)?this.clickOnVertex(e,t):this.clickAnywhere(e,t)},Ge.onKeyUp=function(e,t){ye(t)?(this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)):Ee(t)&&this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]})},Ge.onStop=function(e){this.updateUIClasses({mouse:d.NONE}),Oe.enable(this),this.activateUIButton(),void 0!==this.getFeature(e.polygon.id)&&(e.polygon.removeCoordinate(`0.${e.currentVertexPosition}`),e.polygon.isValid()?this.fire(g.CREATE,{features:[e.polygon.toGeoJSON()]}):(this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT,{},{silent:!0})))},Ge.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.polygon.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t);if(0===t.geometry.coordinates.length)return;const r=t.geometry.coordinates[0].length;if(!(r<3)){if(t.properties.meta=y.FEATURE,o(ve(e.polygon.id,t.geometry.coordinates[0][0],"0.0",!1)),r>3){const n=t.geometry.coordinates[0].length-3;o(ve(e.polygon.id,t.geometry.coordinates[0][n],`0.${n}`,!1))}if(r<=4){const e=[[t.geometry.coordinates[0][0][0],t.geometry.coordinates[0][0][1]],[t.geometry.coordinates[0][1][0],t.geometry.coordinates[0][1][1]]];if(o({type:h.FEATURE,properties:t.properties,geometry:{coordinates:e,type:h.LINE_STRING}}),3===r)return}return o(t)}},Ge.onTrash=function(e){this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)};const Be={onSetup:function(e){const t=(e=e||{}).featureId;let o,n,r="forward";if(t){if(o=this.getFeature(t),!o)throw new Error("Could not find a feature with the provided featureId");let i=e.from;if(i&&"Feature"===i.type&&i.geometry&&"Point"===i.geometry.type&&(i=i.geometry),i&&"Point"===i.type&&i.coordinates&&2===i.coordinates.length&&(i=i.coordinates),!i||!Array.isArray(i))throw new Error("Please use the `from` property to indicate which point to continue the line from");const s=o.coordinates.length-1;if(o.coordinates[s][0]===i[0]&&o.coordinates[s][1]===i[1])n=s+1,o.addCoordinate(n,...o.coordinates[s]);else{if(o.coordinates[0][0]!==i[0]||o.coordinates[0][1]!==i[1])throw new Error("`from` should match the point at either the start or the end of the provided LineString");r="backwards",n=0,o.addCoordinate(n,...o.coordinates[0])}}else o=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.LINE_STRING,coordinates:[]}}),n=0,this.addFeature(o);return this.clearSelectedFeatures(),Oe.disable(this),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.LINE),this.setActionableState({trash:!0}),{line:o,currentVertexPosition:n,direction:r}},clickAnywhere:function(e,t){if(e.currentVertexPosition>0&&Ve(t,e.line.coordinates[e.currentVertexPosition-1])||"backwards"===e.direction&&Ve(t,e.line.coordinates[e.currentVertexPosition+1]))return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]});this.updateUIClasses({mouse:d.ADD}),e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat),"forward"===e.direction?(e.currentVertexPosition++,e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat)):e.line.addCoordinate(0,t.lngLat.lng,t.lngLat.lat)},clickOnVertex:function(e){return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]})},onMouseMove:function(e,t){e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat),ge(t)&&this.updateUIClasses({mouse:d.POINTER})}};Be.onTap=Be.onClick=function(e,t){if(ge(t))return this.clickOnVertex(e,t);this.clickAnywhere(e,t)},Be.onKeyUp=function(e,t){Ee(t)?this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]}):ye(t)&&(this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT))},Be.onStop=function(e){Oe.enable(this),this.activateUIButton(),void 0!==this.getFeature(e.line.id)&&(e.line.removeCoordinate(`${e.currentVertexPosition}`),e.line.isValid()?this.fire(g.CREATE,{features:[e.line.toGeoJSON()]}):(this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT,{},{silent:!0})))},Be.onTrash=function(e){this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)},Be.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.line.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t);t.geometry.coordinates.length<2||(t.properties.meta=y.FEATURE,o(ve(e.line.id,t.geometry.coordinates["forward"===e.direction?t.geometry.coordinates.length-2:1],""+("forward"===e.direction?t.geometry.coordinates.length-2:1),!1)),o(t))};var je={simple_select:Re,direct_select:Ue,draw_point:ke,draw_polygon:Ge,draw_line_string:Be};const Je={defaultMode:f.SIMPLE_SELECT,keybindings:!0,touchEnabled:!0,clickBuffer:2,touchBuffer:25,boxSelect:!0,displayControlsDefault:!0,styles:ce,modes:je,controls:{},userProperties:!1,suppressAPIEvents:!0},$e={point:!0,line_string:!0,polygon:!0,trash:!0,combine_features:!0,uncombine_features:!0},Ye={point:!1,line_string:!1,polygon:!1,trash:!1,combine_features:!1,uncombine_features:!1};function He(e,t){return e.map((e=>e.source?e:Object.assign({},e,{id:`${e.id}.${t}`,source:"hot"===t?l.HOT:l.COLD})))}var Xe,qe,Ze,We,Ke=t(qe?Xe:(qe=1,Xe=function e(t,o){if(t===o)return!0;if(t&&o&&"object"==typeof t&&"object"==typeof o){if(t.constructor!==o.constructor)return!1;var n,r,i;if(Array.isArray(t)){if((n=t.length)!=o.length)return!1;for(r=n;0!=r--;)if(!e(t[r],o[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===o.source&&t.flags===o.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===o.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===o.toString();if((n=(i=Object.keys(t)).length)!==Object.keys(o).length)return!1;for(r=n;0!=r--;)if(!Object.prototype.hasOwnProperty.call(o,i[r]))return!1;for(r=n;0!=r--;){var s=i[r];if(!e(t[s],o[s]))return!1}return!0}return t!=t&&o!=o})),ze=function(){if(We)return Ze;We=1,Ze=function(t){if(!t||!t.type)return null;var o=e[t.type];return o?"geometry"===o?{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:t}]}:"feature"===o?{type:"FeatureCollection",features:[t]}:"featurecollection"===o?t:void 0:null};var e={Point:"geometry",MultiPoint:"geometry",LineString:"geometry",MultiLineString:"geometry",Polygon:"geometry",MultiPolygon:"geometry",GeometryCollection:"geometry",Feature:"feature",FeatureCollection:"featurecollection"};return Ze}(),Qe=t(ze);function et(e,t){return e.length===t.length&&JSON.stringify(e.map((e=>e)).sort())===JSON.stringify(t.map((e=>e)).sort())}const tt={Polygon:Y,LineString:$,Point:J,MultiPolygon:q,MultiLineString:q,MultiPoint:q};var ot=Object.freeze({__proto__:null,CommonSelectors:Te,ModeHandler:e,StringSet:M,constrainFeatureMovement:Pe,createMidPoint:Ie,createSupplementaryPoints:Se,createVertex:ve,doubleClickZoom:Oe,euclideanDistance:P,featuresAt:b,getFeatureAtAndSetCursors:A,isClick:D,isEventAtCoordinates:Ve,isTap:V,mapEventToBoundingBox:L,moveFeatures:Fe,sortFeatures:O,stringSetsAreEqual:et,theme:ce,toDenseArray:Q});const nt=function(e,t){const o={options:e=function(e={}){let t=Object.assign({},e);return e.controls||(t.controls={}),!1===e.displayControlsDefault?t.controls=Object.assign({},Ye,e.controls):t.controls=Object.assign({},$e,e.controls),t=Object.assign({},Je,t),t.styles=He(t.styles,"cold").concat(He(t.styles,"hot")),t}(e)};t=function(e,t){t.modes=f;const o=void 0===e.options.suppressAPIEvents||!!e.options.suppressAPIEvents;return t.getFeatureIdsAt=function(t){return b.click({point:t},null,e).map((e=>e.properties.id))},t.getSelectedIds=function(){return e.store.getSelectedIds()},t.getSelected=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getSelectedIds().map((t=>e.store.get(t))).map((e=>e.toGeoJSON()))}},t.getSelectedPoints=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getSelectedCoordinates().map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e.coordinates}})))}},t.set=function(o){if(void 0===o.type||o.type!==h.FEATURE_COLLECTION||!Array.isArray(o.features))throw new Error("Invalid FeatureCollection");const n=e.store.createRenderBatch();let r=e.store.getAllIds().slice();const i=t.add(o),s=new M(i);return r=r.filter((e=>!s.has(e))),r.length&&t.delete(r),n(),i},t.add=function(t){const n=JSON.parse(JSON.stringify(Qe(t))).features.map((t=>{if(t.id=t.id||B(),null===t.geometry)throw new Error("Invalid geometry: null");if(void 0===e.store.get(t.id)||e.store.get(t.id).type!==t.geometry.type){const n=tt[t.geometry.type];if(void 0===n)throw new Error(`Invalid geometry type: ${t.geometry.type}.`);const r=new n(e,t);e.store.add(r,{silent:o})}else{const n=e.store.get(t.id),r=n.properties;n.properties=t.properties,Ke(r,t.properties)||e.store.featureChanged(n.id,{silent:o}),Ke(n.getCoordinates(),t.geometry.coordinates)||n.incomingCoords(t.geometry.coordinates)}return t.id}));return e.store.render(),n},t.get=function(t){const o=e.store.get(t);if(o)return o.toGeoJSON()},t.getAll=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getAll().map((e=>e.toGeoJSON()))}},t.delete=function(n){return e.store.delete(n,{silent:o}),t.getMode()!==f.DIRECT_SELECT||e.store.getSelectedIds().length?e.store.render():e.events.changeMode(f.SIMPLE_SELECT,void 0,{silent:o}),t},t.deleteAll=function(){return e.store.delete(e.store.getAllIds(),{silent:o}),t.getMode()===f.DIRECT_SELECT?e.events.changeMode(f.SIMPLE_SELECT,void 0,{silent:o}):e.store.render(),t},t.changeMode=function(n,r={}){return n===f.SIMPLE_SELECT&&t.getMode()===f.SIMPLE_SELECT?(et(r.featureIds||[],e.store.getSelectedIds())||(e.store.setSelected(r.featureIds,{silent:o}),e.store.render()),t):(n===f.DIRECT_SELECT&&t.getMode()===f.DIRECT_SELECT&&r.featureId===e.store.getSelectedIds()[0]||e.events.changeMode(n,r,{silent:o}),t)},t.getMode=function(){return e.events.getMode()},t.trash=function(){return e.events.trash({silent:o}),t},t.combineFeatures=function(){return e.events.combineFeatures({silent:o}),t},t.uncombineFeatures=function(){return e.events.uncombineFeatures({silent:o}),t},t.setFeatureProperty=function(n,r,i){return e.store.setFeatureProperty(n,r,i,{silent:o}),t},t}(o,t),o.api=t;const n=re(o);return t.onAdd=n.onAdd,t.onRemove=n.onRemove,t.types=p,t.options=e,t};function rt(e){nt(e,this)}return rt.modes=je,rt.constants=v,rt.lib=ot,rt},"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).MapboxDraw=t(); +//# sourceMappingURL=mapbox-gl-draw.js.map diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js new file mode 100644 index 0000000..e2b91ff --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js @@ -0,0 +1 @@ +var MapboxGLGlobeMinimap=function(){"use strict";class t{constructor(){this._partials=new Float64Array(32),this._n=0}add(t){const n=this._partials;let e=0;for(let r=0;r0){for(o=t[--i];i>0&&(n=o,e=t[--i],o=n+e,r=e-(o-n),!r););i>0&&(r<0&&t[i-1]<0||r>0&&t[i-1]>0)&&(e=2*r,n=o+e,e==n-o&&(o=n))}return o}}function n(t){return Array.from(function*(t){for(const n of t)yield*n}(t))}var e={value:()=>{}};function r(){for(var t,n=0,e=arguments.length,r={};n=0&&(n=t.slice(e+1),t=t.slice(0,e)),t&&!r.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))),l=-1,s=a.length;if(!(arguments.length<2)){if(null!=n&&"function"!=typeof n)throw new Error("invalid callback: "+n);for(;++l0)for(var e,r,i=new Array(e),o=0;o=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),l.hasOwnProperty(n)?{space:l[n],local:t}:t}function c(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===a&&n.documentElement.namespaceURI===a?n.createElement(t):n.createElementNS(e,t)}}function f(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function h(t){var n=s(t);return(n.local?f:c)(n)}function p(){}function d(t){return null==t?p:function(){return this.querySelector(t)}}function v(){return[]}function g(t){return null==t?v:function(){return this.querySelectorAll(t)}}function y(t){return function(){return null==(n=t.apply(this,arguments))?[]:Array.isArray(n)?n:Array.from(n);var n}}function _(t){return function(){return this.matches(t)}}function m(t){return function(n){return n.matches(t)}}var w=Array.prototype.find;function b(){return this.firstElementChild}var x=Array.prototype.filter;function E(){return Array.from(this.children)}function S(t){return new Array(t.length)}function N(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}function k(t,n,e,r,i,o){for(var u,a=0,l=n.length,s=o.length;an?1:t>=n?0:NaN}function P(t){return function(){this.removeAttribute(t)}}function j(t){return function(){this.removeAttributeNS(t.space,t.local)}}function R(t,n){return function(){this.setAttribute(t,n)}}function T(t,n){return function(){this.setAttributeNS(t.space,t.local,n)}}function q(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttribute(t):this.setAttribute(t,e)}}function O(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}}function L(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function X(t){return function(){this.style.removeProperty(t)}}function z(t,n,e){return function(){this.style.setProperty(t,n,e)}}function D(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}function H(t,n){return t.style.getPropertyValue(n)||L(t).getComputedStyle(t,null).getPropertyValue(n)}function I(t){return function(){delete this[t]}}function Y(t,n){return function(){this[t]=n}}function B(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}function F(t){return t.trim().split(/^|\s+/)}function V(t){return t.classList||new G(t)}function G(t){this._node=t,this._names=F(t.getAttribute("class")||"")}function U(t,n){for(var e=V(t),r=-1,i=n.length;++r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var gt=[null];function yt(t,n){this._groups=t,this._parents=n}function _t(){return new yt([[document.documentElement]],gt)}function mt(t){return"string"==typeof t?new yt([[document.querySelector(t)]],[document.documentElement]):new yt([[t]],gt)}function wt(t,n,e){t.prototype=n.prototype=e,e.constructor=t}function bt(t,n){var e=Object.create(t.prototype);for(var r in n)e[r]=n[r];return e}function xt(){}yt.prototype=_t.prototype={constructor:yt,select:function(t){"function"!=typeof t&&(t=d(t));for(var n=this._groups,e=n.length,r=new Array(e),i=0;i=b&&(b=w+1);!(m=y[b])&&++b=0;)(r=i[o])&&(u&&4^r.compareDocumentPosition(u)&&u.parentNode.insertBefore(r,u),u=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=C);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?X:"function"==typeof n?D:z)(t,n,null==e?"":e)):H(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?I:"function"==typeof n?B:Y)(t,n)):this.node()[t]},classed:function(t,n){var e=F(t+"");if(arguments.length<2){for(var r=V(this.node()),i=-1,o=e.length;++i=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}}))}(t+""),u=o.length;if(!(arguments.length<2)){for(a=n?ht:ft,r=0;r>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):8===e?Dt(n>>24&255,n>>16&255,n>>8&255,(255&n)/255):4===e?Dt(n>>12&15|n>>8&240,n>>8&15|n>>4&240,n>>4&15|240&n,((15&n)<<4|15&n)/255):null):(n=$t.exec(t))?new It(n[1],n[2],n[3],1):(n=Ct.exec(t))?new It(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=Pt.exec(t))?Dt(n[1],n[2],n[3],n[4]):(n=jt.exec(t))?Dt(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=Rt.exec(t))?Ut(n[1],n[2]/100,n[3]/100,1):(n=Tt.exec(t))?Ut(n[1],n[2]/100,n[3]/100,n[4]):qt.hasOwnProperty(t)?zt(qt[t]):"transparent"===t?new It(NaN,NaN,NaN,0):null}function zt(t){return new It(t>>16&255,t>>8&255,255&t,1)}function Dt(t,n,e,r){return r<=0&&(t=n=e=NaN),new It(t,n,e,r)}function Ht(t,n,e,r){return 1===arguments.length?((i=t)instanceof xt||(i=Xt(i)),i?new It((i=i.rgb()).r,i.g,i.b,i.opacity):new It):new It(t,n,e,null==r?1:r);var i}function It(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function Yt(){return`#${Gt(this.r)}${Gt(this.g)}${Gt(this.b)}`}function Bt(){const t=Ft(this.opacity);return`${1===t?"rgb(":"rgba("}${Vt(this.r)}, ${Vt(this.g)}, ${Vt(this.b)}${1===t?")":`, ${t})`}`}function Ft(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Vt(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Gt(t){return((t=Vt(t))<16?"0":"")+t.toString(16)}function Ut(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new Wt(t,n,e,r)}function Zt(t){if(t instanceof Wt)return new Wt(t.h,t.s,t.l,t.opacity);if(t instanceof xt||(t=Xt(t)),!t)return new Wt;if(t instanceof Wt)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),u=NaN,a=o-i,l=(o+i)/2;return a?(u=n===o?(e-r)/a+6*(e0&&l<1?0:u,new Wt(u,a,l,t.opacity)}function Wt(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function Kt(t){return(t=(t||0)%360)<0?t+360:t}function Jt(t){return Math.max(0,Math.min(1,t||0))}function Qt(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}wt(xt,Xt,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:Ot,formatHex:Ot,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return Zt(this).formatHsl()},formatRgb:Lt,toString:Lt}),wt(It,Ht,bt(xt,{brighter(t){return t=null==t?St:Math.pow(St,t),new It(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?Et:Math.pow(Et,t),new It(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new It(Vt(this.r),Vt(this.g),Vt(this.b),Ft(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Yt,formatHex:Yt,formatHex8:function(){return`#${Gt(this.r)}${Gt(this.g)}${Gt(this.b)}${Gt(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:Bt,toString:Bt})),wt(Wt,(function(t,n,e,r){return 1===arguments.length?Zt(t):new Wt(t,n,e,null==r?1:r)}),bt(xt,{brighter(t){return t=null==t?St:Math.pow(St,t),new Wt(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?Et:Math.pow(Et,t),new Wt(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new It(Qt(t>=240?t-240:t+120,i,r),Qt(t,i,r),Qt(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new Wt(Kt(this.h),Jt(this.s),Jt(this.l),Ft(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=Ft(this.opacity);return`${1===t?"hsl(":"hsla("}${Kt(this.h)}, ${100*Jt(this.s)}%, ${100*Jt(this.l)}%${1===t?")":`, ${t})`}`}}));var tn=t=>()=>t;function nn(t){return 1==(t=+t)?en:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):tn(isNaN(n)?e:n)}}function en(t,n){var e=n-t;return e?function(t,n){return function(e){return t+e*n}}(t,e):tn(isNaN(t)?n:t)}var rn=function t(n){var e=nn(n);function r(t,n){var r=e((t=Ht(t)).r,(n=Ht(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),u=en(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=u(n),t+""}}return r.gamma=t,r}(1);function on(t,n){n||(n=[]);var e,r=t?Math.min(n.length,t.length):0,i=n.slice();return function(o){for(e=0;eo&&(i=n.slice(o,i),a[u]?a[u]+=i:a[++u]=i),(e=e[0])===(r=r[0])?a[u]?a[u]+=r:a[++u]=r:(a[++u]=null,l.push({i:u,x:ln(e,r)})),o=fn.lastIndex;return o180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:ln(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,u.rotate,a,l),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:ln(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,u.skewX,a,l),function(t,n,e,r,o,u){if(t!==e||n!==r){var a=o.push(i(o)+"scale(",null,",",null,")");u.push({i:a-4,x:ln(t,e)},{i:a-2,x:ln(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,u.scaleX,u.scaleY,a,l),o=u=null,function(t){for(var n,e=-1,r=l.length;++e=0&&n._call.call(void 0,t),n=n._next;--En}()}finally{En=0,function(){var t,n,e=mn,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:mn=n);wn=t,Xn(r)}(),An=0}}function Ln(){var t=Cn.now(),n=t-Mn;n>kn&&($n-=n,Mn=t)}function Xn(t){En||(Sn&&(Sn=clearTimeout(Sn)),t-An>24?(t<1/0&&(Sn=setTimeout(On,t-Cn.now()-$n)),Nn&&(Nn=clearInterval(Nn))):(Nn||(Mn=Cn.now(),Nn=setInterval(Ln,kn)),En=1,Pn(On)))}function zn(t,n,e){var r=new Tn;return n=null==n?0:+n,r.restart((e=>{r.stop(),t(e+n)}),n,e),r}Tn.prototype=qn.prototype={constructor:Tn,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?jn():+e)+(null==n?0:+n),this._next||wn===this||(wn?wn._next=this:mn=this,wn=this),this._call=t,this._time=e,Xn()},stop:function(){this._call&&(this._call=null,this._time=1/0,Xn())}};var Dn=r("start","end","cancel","interrupt"),Hn=[],In=0,Yn=1,Bn=2,Fn=3,Vn=4,Gn=5,Un=6;function Zn(t,n,e,r,i,o){var u=t.__transition;if(u){if(e in u)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(t){e.state=Yn,e.timer.restart(u,e.delay,e.time),e.delay<=t&&u(t-e.delay)}function u(o){var s,c,f,h;if(e.state!==Yn)return l();for(s in i)if((h=i[s]).name===e.name){if(h.state===Fn)return zn(u);h.state===Vn?(h.state=Un,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[s]):+sIn)throw new Error("too late; already scheduled");return e}function Kn(t,n){var e=Jn(t,n);if(e.state>Fn)throw new Error("too late; already running");return e}function Jn(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function Qn(t,n){var e,r;return function(){var i=Kn(this,t),o=i.tween;if(o!==e)for(var u=0,a=(r=e=o).length;u=0&&(t=t.slice(0,n)),!t||"start"===t}))}(n)?Wn:Kn;return function(){var u=o(this,t),a=u.on;a!==r&&(i=(r=a).copy()).on(n,e),u.on=i}}(e,t,n))},attr:function(t,n){var e=s(t),r="transform"===e?xn:ee;return this.attrTween(t,"function"==typeof n?(e.local?le:ae)(e,r,ne(this,"attr."+t,n)):null==n?(e.local?ie:re)(e):(e.local?ue:oe)(e,r,n))},attrTween:function(t,n){var e="attr."+t;if(arguments.length<2)return(e=this.tween(e))&&e._value;if(null==n)return this.tween(e,null);if("function"!=typeof n)throw new Error;var r=s(t);return this.tween(e,(r.local?se:ce)(r,n))},style:function(t,n,e){var r="transform"==(t+="")?bn:ee;return null==n?this.styleTween(t,function(t,n){var e,r,i;return function(){var o=H(this,t),u=(this.style.removeProperty(t),H(this,t));return o===u?null:o===e&&u===r?i:i=n(e=o,r=u)}}(t,r)).on("end.style."+t,ge(t)):"function"==typeof n?this.styleTween(t,function(t,n,e){var r,i,o;return function(){var u=H(this,t),a=e(this),l=a+"";return null==a&&(this.style.removeProperty(t),l=a=H(this,t)),u===l?null:u===r&&l===i?o:(i=l,o=n(r=u,a))}}(t,r,ne(this,"style."+t,n))).each(function(t,n){var e,r,i,o,u="style."+n,a="end."+u;return function(){var l=Kn(this,t),s=l.on,c=null==l.value[u]?o||(o=ge(n)):void 0;s===e&&i===c||(r=(e=s).copy()).on(a,i=c),l.on=r}}(this._id,t)):this.styleTween(t,function(t,n,e){var r,i,o=e+"";return function(){var u=H(this,t);return u===o?null:u===r?i:i=n(r=u,e)}}(t,r,n),e).on("end.style."+t,null)},styleTween:function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,function(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&function(t,n,e){return function(r){this.style.setProperty(t,n.call(this,r),e)}}(t,o,e)),r}return o._value=n,o}(t,n,null==e?"":e))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var n=t(this);this.textContent=null==n?"":n}}(ne(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},textTween:function(t){var n="text";if(arguments.length<1)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;return this.tween(n,function(t){var n,e;function r(){var r=t.apply(this,arguments);return r!==e&&(n=(e=r)&&function(t){return function(n){this.textContent=t.call(this,n)}}(r)),n}return r._value=t,r}(t))},remove:function(){return this.on("end.remove",function(t){return function(){var n=this.parentNode;for(var e in this.__transition)if(+e!==t)return;n&&n.removeChild(this)}}(this._id))},tween:function(t,n){var e=this._id;if(t+="",arguments.length<2){for(var r,i=Jn(this.node(),e).tween,o=0,u=i.length;oBn&&e.state0?1:t<0?-1:0},Xe=Math.sqrt;function ze(t){return t>1?Me:t<-1?-Me:Math.asin(t)}function De(){}function He(t,n){t&&Ye.hasOwnProperty(t.type)&&Ye[t.type](t,n)}var Ie={Feature:function(t,n){He(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++rke&&(t-=Math.round(t/$e)*$e),[t,n]}function er(t){return function(n,e){return je(n+=t)>ke&&(n-=Math.round(n/$e)*$e),[n,e]}}function rr(t){var n=er(t);return n.invert=er(-t),n}function ir(t,n){var e=qe(t),r=Oe(t),i=qe(n),o=Oe(n);function u(t,n){var u=qe(n),a=qe(t)*u,l=Oe(t)*u,s=Oe(n),c=s*e+a*r;return[Te(l*i-c*o,a*e-s*r),ze(c*i+l*o)]}return u.invert=function(t,n){var u=qe(n),a=qe(t)*u,l=Oe(t)*u,s=Oe(n),c=s*i-l*o;return[Te(l*i+s*o,a*e+c*r),ze(c*e-a*r)]},u}function or(t,n){(n=Ue(n))[0]-=t,Qe(n);var e,r=(e=-n[1])>1?0:e<-1?ke:Math.acos(e);return((-n[2]<0?-r:r)+$e-Se)%$e}function ur(){var t,n=[];return{point:function(n,e,r){t.push([n,e,r])},lineStart:function(){n.push(t=[])},lineEnd:De,rejoin:function(){n.length>1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function ar(t,n){return je(t[0]-n[0])=0;--o)i.point((c=s[o])[0],c[1]);else r(h.x,h.p.x,-1,i);h=h.p}s=(h=h.o).z,p=!p}while(!h.v);i.lineEnd()}}}function cr(t){if(n=t.length){for(var n,e,r=0,i=t[0];++r=0?1:-1,M=k*N,A=M>ke,$=y*E;if(s.add(Te($*k*Oe(M),_*S+$*qe(M))),a+=A?N+k*$e:N,A^v>=r^b>=r){var C=We(Ue(d),Ue(w));Qe(C);var P=We(u,C);Qe(P);var j=(A^N>=0?-1:1)*ze(P[2]);(i>j||i===j&&(C[0]||C[1]))&&(l+=A^N>=0?1:-1)}}return(a<-Se||a0){for(p||(u.polygonStart(),p=!0),u.lineStart(),t=0;t1&&2&i&&o.push(o.pop().concat(o.shift())),l.push(o.filter(pr))}return d}}function pr(t){return t.length>1}function dr(t,n){return((t=t.x)[0]<0?t[1]-Me-Se:Me-t[1])-((n=n.x)[0]<0?n[1]-Me-Se:Me-n[1])}nr.invert=nr;var vr=hr((function(){return!0}),(function(t){var n,e=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),n=1},point:function(o,u){var a=o>0?ke:-ke,l=je(o-e);je(l-ke)0?Me:-Me),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),n=0):i!==a&&l>=ke&&(je(e-i)Se?Re((Oe(n)*(o=qe(r))*Oe(e)-Oe(r)*(i=qe(n))*Oe(t))/(i*o*u)):(n+r)/2}(e,r,o,u),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),n=0),t.point(e=o,r=u),i=a},lineEnd:function(){t.lineEnd(),e=r=NaN},clean:function(){return 2-n}}}),(function(t,n,e,r){var i;if(null==t)i=e*Me,r.point(-ke,i),r.point(0,i),r.point(ke,i),r.point(ke,0),r.point(ke,-i),r.point(0,-i),r.point(-ke,-i),r.point(-ke,0),r.point(-ke,i);else if(je(t[0]-n[0])>Se){var o=t[0]0,i=je(n)>Se;function o(t,e){return qe(t)*qe(e)>n}function u(t,e,r){var i=[1,0,0],o=We(Ue(t),Ue(e)),u=Ze(o,o),a=o[0],l=u-a*a;if(!l)return!r&&t;var s=n*u/l,c=-n*a/l,f=We(i,o),h=Je(i,s);Ke(h,Je(o,c));var p=f,d=Ze(h,p),v=Ze(p,p),g=d*d-v*(Ze(h,h)-1);if(!(g<0)){var y=Xe(g),_=Je(p,(-d-y)/v);if(Ke(_,h),_=Ge(_),!r)return _;var m,w=t[0],b=e[0],x=t[1],E=e[1];b0^_[1]<(je(_[0]-w)ke^(w<=_[0]&&_[0]<=b)){var k=Je(p,(-d+y)/v);return Ke(k,h),[_,Ge(k)]}}}function a(n,e){var i=r?t:ke-t,o=0;return n<-i?o|=1:n>i&&(o|=2),e<-i?o|=4:e>i&&(o|=8),o}return hr(o,(function(t){var n,e,l,s,c;return{lineStart:function(){s=l=!1,c=1},point:function(f,h){var p,d=[f,h],v=o(f,h),g=r?v?0:a(f,h):v?a(f+(f<0?ke:-ke),h):0;if(!n&&(s=l=v)&&t.lineStart(),v!==l&&(!(p=u(n,d))||ar(n,p)||ar(d,p))&&(d[2]=1),v!==l)c=0,v?(t.lineStart(),p=u(d,n),t.point(p[0],p[1])):(p=u(n,d),t.point(p[0],p[1],2),t.lineEnd()),n=p;else if(i&&n&&r^v){var y;g&e||!(y=u(d,n,!0))||(c=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1],3)))}!v||n&&ar(n,d)||t.point(d[0],d[1]),n=d,l=v,e=g},lineEnd:function(){l&&t.lineEnd(),n=null},clean:function(){return c|(s&&l)<<1}}}),(function(n,r,i,o){!function(t,n,e,r,i,o){if(e){var u=qe(n),a=Oe(n),l=r*e;null==i?(i=n+r*$e,o=n-l/2):(i=or(u,i),o=or(u,o),(r>0?io)&&(i+=r*$e));for(var s,c=i;r>0?c>o:c0)do{l.point(0===c||3===c?t:r,c>1?i:e)}while((c=(c+u+4)%4)!==f);else l.point(o[0],o[1])}function a(n,i){return je(n[0]-t)0?0:3:je(n[0]-r)0?2:1:je(n[1]-e)0?1:0:i>0?3:2}function l(t,n){return s(t.x,n.x)}function s(t,n){var e=a(t,1),r=a(n,1);return e!==r?e-r:0===e?n[1]-t[1]:1===e?t[0]-n[0]:2===e?t[1]-n[1]:n[0]-t[0]}return function(a){var s,c,f,h,p,d,v,g,y,_,m,w=a,b=ur(),x={point:E,lineStart:function(){x.point=S,c&&c.push(f=[]);_=!0,y=!1,v=g=NaN},lineEnd:function(){s&&(S(h,p),d&&y&&b.rejoin(),s.push(b.result()));x.point=E,y&&w.lineEnd()},polygonStart:function(){w=b,s=[],c=[],m=!0},polygonEnd:function(){var e=function(){for(var n=0,e=0,r=c.length;ei&&(h-o)*(i-u)>(p-u)*(t-o)&&++n:p<=i&&(h-o)*(i-u)<(p-u)*(t-o)&&--n;return n}(),r=m&&e,o=(s=n(s)).length;(r||o)&&(a.polygonStart(),r&&(a.lineStart(),u(null,null,1,a),a.lineEnd()),o&&sr(s,l,e,u,a),a.polygonEnd());w=a,s=c=f=null}};function E(t,n){o(t,n)&&w.point(t,n)}function S(n,u){var a=o(n,u);if(c&&f.push([n,u]),_)h=n,p=u,d=a,_=!1,a&&(w.lineStart(),w.point(n,u));else if(a&&y)w.point(n,u);else{var l=[v=Math.max(_r,Math.min(yr,v)),g=Math.max(_r,Math.min(yr,g))],s=[n=Math.max(_r,Math.min(yr,n)),u=Math.max(_r,Math.min(yr,u))];!function(t,n,e,r,i,o){var u,a=t[0],l=t[1],s=0,c=1,f=n[0]-a,h=n[1]-l;if(u=e-a,f||!(u>0)){if(u/=f,f<0){if(u0){if(u>c)return;u>s&&(s=u)}if(u=i-a,f||!(u<0)){if(u/=f,f<0){if(u>c)return;u>s&&(s=u)}else if(f>0){if(u0)){if(u/=h,h<0){if(u0){if(u>c)return;u>s&&(s=u)}if(u=o-l,h||!(u<0)){if(u/=h,h<0){if(u>c)return;u>s&&(s=u)}else if(h>0){if(u0&&(t[0]=a+s*f,t[1]=l+s*h),c<1&&(n[0]=a+c*f,n[1]=l+c*h),!0}}}}}(l,s,t,e,r,i)?a&&(w.lineStart(),w.point(n,u),m=!1):(y||(w.lineStart(),w.point(l[0],l[1])),w.point(s[0],s[1]),a||w.lineEnd(),m=!1)}v=n,g=u,y=a}return x}}var wr,br,xr,Er,Sr=t=>t,Nr=new t,kr=new t,Mr={point:De,lineStart:De,lineEnd:De,polygonStart:function(){Mr.lineStart=Ar,Mr.lineEnd=Pr},polygonEnd:function(){Mr.lineStart=Mr.lineEnd=Mr.point=De,Nr.add(je(kr)),kr=new t},result:function(){var n=Nr/2;return Nr=new t,n}};function Ar(){Mr.point=$r}function $r(t,n){Mr.point=Cr,wr=xr=t,br=Er=n}function Cr(t,n){kr.add(Er*t-xr*n),xr=t,Er=n}function Pr(){Cr(wr,br)}var jr=1/0,Rr=jr,Tr=-jr,qr=Tr,Or={point:function(t,n){tTr&&(Tr=t);nqr&&(qr=n)},lineStart:De,lineEnd:De,polygonStart:De,polygonEnd:De,result:function(){var t=[[jr,Rr],[Tr,qr]];return Tr=qr=-(Rr=jr=1/0),t}};var Lr,Xr,zr,Dr,Hr=0,Ir=0,Yr=0,Br=0,Fr=0,Vr=0,Gr=0,Ur=0,Zr=0,Wr={point:Kr,lineStart:Jr,lineEnd:ni,polygonStart:function(){Wr.lineStart=ei,Wr.lineEnd=ri},polygonEnd:function(){Wr.point=Kr,Wr.lineStart=Jr,Wr.lineEnd=ni},result:function(){var t=Zr?[Gr/Zr,Ur/Zr]:Vr?[Br/Vr,Fr/Vr]:Yr?[Hr/Yr,Ir/Yr]:[NaN,NaN];return Hr=Ir=Yr=Br=Fr=Vr=Gr=Ur=Zr=0,t}};function Kr(t,n){Hr+=t,Ir+=n,++Yr}function Jr(){Wr.point=Qr}function Qr(t,n){Wr.point=ti,Kr(zr=t,Dr=n)}function ti(t,n){var e=t-zr,r=n-Dr,i=Xe(e*e+r*r);Br+=i*(zr+t)/2,Fr+=i*(Dr+n)/2,Vr+=i,Kr(zr=t,Dr=n)}function ni(){Wr.point=Kr}function ei(){Wr.point=ii}function ri(){oi(Lr,Xr)}function ii(t,n){Wr.point=oi,Kr(Lr=zr=t,Xr=Dr=n)}function oi(t,n){var e=t-zr,r=n-Dr,i=Xe(e*e+r*r);Br+=i*(zr+t)/2,Fr+=i*(Dr+n)/2,Vr+=i,Gr+=(i=Dr*t-zr*n)*(zr+t),Ur+=i*(Dr+n),Zr+=3*i,Kr(zr=t,Dr=n)}function ui(t){this._context=t}ui.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._context.moveTo(t,n),this._point=1;break;case 1:this._context.lineTo(t,n);break;default:this._context.moveTo(t+this._radius,n),this._context.arc(t,n,this._radius,0,$e)}},result:De};var ai,li,si,ci,fi,hi=new t,pi={point:De,lineStart:function(){pi.point=di},lineEnd:function(){ai&&vi(li,si),pi.point=De},polygonStart:function(){ai=!0},polygonEnd:function(){ai=null},result:function(){var n=+hi;return hi=new t,n}};function di(t,n){pi.point=vi,li=ci=t,si=fi=n}function vi(t,n){ci-=t,fi-=n,hi.add(Xe(ci*ci+fi*fi)),ci=t,fi=n}let gi,yi,_i,mi;class wi{constructor(t){this._append=null==t?bi:function(t){const n=Math.floor(t);if(!(n>=0))throw new RangeError(`invalid digits: ${t}`);if(n>15)return bi;if(n!==gi){const t=10**n;gi=n,yi=function(n){let e=1;this._+=n[0];for(const r=n.length;e4*n&&v--){var w=u+h,b=a+p,x=l+d,E=Xe(w*w+b*b+x*x),S=ze(x/=E),N=je(je(x)-1)n||je((y*$+_*C)/m-.5)>.3||u*h+a*p+l*d2?t[2]%360*Pe:0,$()):[g*Ce,y*Ce,_*Ce]},M.angle=function(t){return arguments.length?(m=t%360*Pe,$()):m*Ce},M.reflectX=function(t){return arguments.length?(w=t?-1:1,$()):w<0},M.reflectY=function(t){return arguments.length?(b=t?-1:1,$()):b<0},M.precision=function(t){return arguments.length?(u=Ai(a,k=t*t),C()):Xe(k)},M.fitExtent=function(t,n){return Ni(M,t,n)},M.fitSize=function(t,n){return function(t,n,e){return Ni(t,[[0,0],n],e)}(M,t,n)},M.fitWidth=function(t,n){return function(t,n,e){return Si(t,(function(e){var r=+n,i=r/(e[1][0]-e[0][0]),o=(r-i*(e[1][0]+e[0][0]))/2,u=-i*e[0][1];t.scale(150*i).translate([o,u])}),e)}(M,t,n)},M.fitHeight=function(t,n){return function(t,n,e){return Si(t,(function(e){var r=+n,i=r/(e[1][1]-e[0][1]),o=-i*e[0][0],u=(r-i*(e[1][1]+e[0][1]))/2;t.scale(150*i).translate([o,u])}),e)}(M,t,n)},function(){return n=t.apply(this,arguments),M.invert=n.invert&&A,$()}}((function(){return t}))()}function Ri(t,n){return[qe(n)*Oe(t),Oe(n)]}function Ti(t,n,e){this.k=t,this.x=n,this.y=e}function qi(t){return t}function Oi(t,n){var e=n.id,r=n.bbox,i=null==n.properties?{}:n.properties,o=function(t,n){var e=function(t){if(null==t)return qi;var n,e,r=t.scale[0],i=t.scale[1],o=t.translate[0],u=t.translate[1];return function(t,a){a||(n=e=0);var l=2,s=t.length,c=new Array(s);for(c[0]=(n+=t[0])*r+o,c[1]=(e+=t[1])*i+u;l=0))throw new RangeError(`invalid digits: ${t}`);i=n}return null===n&&(r=new wi(i)),u},u.projection(t).digits(i).context(n)}(this.projection,r),this.globe={type:"Sphere"},this.land=(o=Li,"GeometryCollection"===(u=Li.objects.land).type?{type:"FeatureCollection",features:u.geometries.map((function(t){return Oi(o,t)}))}:Oi(o,u)),this._update(),n.on("move",this._update.bind(this))},_draw_marker:function(){const{globeSize:t,markerSize:n,markerColor:e}=this.options;mt(Xi).append("svg").attr("width",t).attr("height",t).attr("style","position: absolute; left: 0; top: 0;").append("path").attr("opacity",0).attr("d","M5.36018 5.33333C5.36018 4.59722 5.61972 3.96875 6.13881 3.44792C6.65789 2.92708 7.28426 2.66667 8.0179 2.66667C8.75154 2.66667 9.3779 2.92708 9.89699 3.44792C10.4161 3.96875 10.6756 4.59722 10.6756 5.33333C10.6756 6.06944 10.4161 6.69792 9.89699 7.21875C9.3779 7.73958 8.75154 8 8.0179 8C7.28426 8 6.65789 7.73958 6.13881 7.21875C5.61972 6.69792 5.36018 6.06944 5.36018 5.33333ZM2.70246 5.33333C2.70246 6.09028 2.81666 6.7118 3.04506 7.19792L6.824 15.2604C6.93474 15.4896 7.09911 15.6701 7.31713 15.8021C7.53515 15.934 7.76874 16 8.0179 16C8.26706 16 8.50065 15.934 8.71866 15.8021C8.93668 15.6701 9.09759 15.4896 9.20141 15.2604L12.9907 7.19792C13.2191 6.71181 13.3333 6.09028 13.3333 5.33333C13.3333 3.86111 12.8142 2.60417 11.7761 1.5625C10.7379 0.520833 9.48518 -8.13254e-07 8.0179 -9.41527e-07C6.55062 -1.0698e-06 5.29789 0.520832 4.25972 1.5625C3.22155 2.60417 2.70246 3.86111 2.70246 5.33333Z").attr("transform",`scale(${n}, ${n}), translate(${t*(1/n)/2-8}, ${t*(1/n)/2-16})`).attr("style","fill:"+e).transition().duration(100).attr("opacity",1)},_update:function(){const t=this,n=this._parentMap.getCenter();me().duration(this.initialTween?1e3:1).tween("rotate",(function(){const e=pn(t.projection.rotate(),[-n.lng,-n.lat]);return function(n){t.projection.rotate(e(n)),t.context.clearRect(0,0,t.canvas.width,t.canvas.height),t.context.fillStyle=t.options.waterColor,t.context.beginPath(),t.path(t.globe),t.context.fill(),t.context.fillStyle=t.options.landColor,t.context.beginPath(),t.path(t.land),t.context.fill()}})).on("end",(()=>{t.initialTween&&(t._draw_marker(),t.initialTween=!1)}))},_createContainer:function(t){const{globeSize:n,id:e}=this.options,r=document.createElement("div");return r.className="mapboxgl-ctrl-globe-minimap mapboxgl-ctrl",r.setAttribute("style","width: "+n+"; height: "+n+";"),r.addEventListener("contextmenu",this._preventDefault),t.getContainer().appendChild(r),""!==e&&(r.id=e),r},_preventDefault:function(t){t.preventDefault()}},window.GlobeMinimap=zi,zi}(); diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js new file mode 100644 index 0000000..207d876 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js @@ -0,0 +1,1102 @@ +/** + * mapbox-pmtiles v1.1.0 - Optimized Version with Lifecycle Management + * Original source: https://github.com/am2222/mapbox-pmtiles by Majid Hojati + * License: MIT + * + * This is an optimized version of the mapbox-pmtiles library that provides + * better performance for large datasets through: + * - Configurable resource management + * - Instance-scoped worker pools and caches + * - Proper lifecycle management and cleanup + * - Reference counting for shared resources + * - Enhanced error handling and timeouts + * - Memory optimization with size-based LRU caches + * + * Last updated: 2025 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + // Global shared resources with reference counting + const GLOBAL_SHARED_RESOURCES = { + // Protocol cache - expensive to duplicate, shared with reference counting + protocolCache: new Map(), // url -> { protocol, instance, refCount } + + // Metadata cache - small and shareable + metadataCache: new Map(), // cacheKey -> data + + // Pre-calculated world sizes for common zoom levels (static, no cleanup needed) + worldSizeCache: new Array(25).fill(null).map((_, z) => Math.pow(2, z)), + + // Global cleanup registry + activeManagers: new Set(), + + // Debug/development features + debug: false, + performanceMetrics: new Map(), + }; + + /** + * Default configuration options + */ + const DEFAULT_OPTIONS = { + workerPoolSize: 4, + tileCacheSize: 1000, + tileCacheMaxMemoryMB: 100, + metadataCacheSize: 100, + enableSharedProtocols: true, + requestTimeoutMs: 30000, + enableDebugLogging: false, + enablePerformanceMetrics: false, + }; + + /** + * LRU Cache implementation with size-based eviction + */ + class LRUCache { + constructor(maxSize, maxMemoryBytes = Infinity) { + this.maxSize = maxSize; + this.maxMemoryBytes = maxMemoryBytes; + this.cache = new Map(); + this.currentMemoryBytes = 0; + } + + get(key) { + if (this.cache.has(key)) { + // Move to end (most recently used) + const value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return value.data; + } + return undefined; + } + + set(key, data, estimatedSize = 0) { + // Remove if exists + if (this.cache.has(key)) { + const existing = this.cache.get(key); + this.currentMemoryBytes -= existing.size; + this.cache.delete(key); + } + + // Evict old entries if necessary + while ( + this.cache.size >= this.maxSize || + this.currentMemoryBytes + estimatedSize > this.maxMemoryBytes + ) { + const firstKey = this.cache.keys().next().value; + if (!firstKey) break; + + const firstValue = this.cache.get(firstKey); + this.currentMemoryBytes -= firstValue.size; + this.cache.delete(firstKey); + } + + // Add new entry + this.cache.set(key, { data, size: estimatedSize }); + this.currentMemoryBytes += estimatedSize; + } + + has(key) { + return this.cache.has(key); + } + + delete(key) { + if (this.cache.has(key)) { + const value = this.cache.get(key); + this.currentMemoryBytes -= value.size; + this.cache.delete(key); + return true; + } + return false; + } + + clear() { + this.cache.clear(); + this.currentMemoryBytes = 0; + } + + get size() { + return this.cache.size; + } + + getMemoryUsage() { + return { + entries: this.cache.size, + memoryBytes: this.currentMemoryBytes, + memoryMB: this.currentMemoryBytes / (1024 * 1024), + }; + } + } + + /** + * Resource Manager - handles per-instance resources and lifecycle + */ + class PMTilesResourceManager { + constructor(options = {}) { + this.config = { ...DEFAULT_OPTIONS, ...options }; + this.destroyed = false; + this.paused = false; + this.dispatcher = null; + + // Instance-scoped resources + this.workerPool = []; + this.workerPoolIndex = 0; + this.tileCache = new LRUCache( + this.config.tileCacheSize, + this.config.tileCacheMaxMemoryMB * 1024 * 1024, + ); + this.pendingRequests = new Map(); + this.activeRequests = new Set(); + + // Performance tracking + this.metrics = { + tilesLoaded: 0, + cacheHits: 0, + cacheMisses: 0, + memoryPeakMB: 0, + averageLoadTimeMs: 0, + }; + + // Register for global cleanup + GLOBAL_SHARED_RESOURCES.activeManagers.add(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager created", this.config); + } + } + + /** + * Initialize worker pool + */ + initializeWorkerPool(dispatcher) { + if (this.destroyed) return; + + // Store dispatcher reference + if (dispatcher) { + this.dispatcher = dispatcher; + } + + if (this.workerPool.length === 0 && this.dispatcher) { + for (let i = 0; i < this.config.workerPoolSize; i++) { + try { + this.workerPool.push(this.dispatcher.getActor()); + } catch (error) { + console.warn("[PMTiles] Failed to create worker:", error); + } + } + + if (this.config.enableDebugLogging) { + console.log( + `[PMTiles] Initialized worker pool with ${this.workerPool.length} workers`, + ); + } + } + } + + /** + * Get next worker from pool (round-robin) + */ + getWorkerFromPool() { + if (this.destroyed) { + return null; + } + + // Try to initialize workers if not done yet + if (this.workerPool.length === 0 && this.dispatcher) { + this.initializeWorkerPool(this.dispatcher); + } + + if (this.workerPool.length === 0) { + if (this.config.enableDebugLogging) { + console.warn( + "[PMTiles] Worker pool is empty, dispatcher available:", + !!this.dispatcher, + ); + } + return null; + } + + const worker = this.workerPool[this.workerPoolIndex]; + this.workerPoolIndex = + (this.workerPoolIndex + 1) % this.workerPool.length; + return worker; + } + + /** + * Get or create protocol instance with reference counting + */ + getProtocol(url) { + if (this.destroyed) return null; + + if (!this.config.enableSharedProtocols) { + // Create instance-specific protocol + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + return { protocol, instance }; + } + + // Use shared protocol with reference counting + if (!GLOBAL_SHARED_RESOURCES.protocolCache.has(url)) { + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + GLOBAL_SHARED_RESOURCES.protocolCache.set(url, { + protocol, + instance, + refCount: 0, + }); + } + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + cached.refCount++; + return cached; + } + + /** + * Release protocol reference + */ + releaseProtocol(url) { + if (!this.config.enableSharedProtocols) return; + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + if (cached) { + cached.refCount--; + if (cached.refCount <= 0) { + GLOBAL_SHARED_RESOURCES.protocolCache.delete(url); + + if (this.config.enableDebugLogging) { + console.log(`[PMTiles] Released protocol for ${url}`); + } + } + } + } + + /** + * Cache key for tiles + */ + getTileCacheKey(url, z, x, y) { + return `${url}:${z}:${x}:${y}`; + } + + /** + * Add tile to cache with size estimation + */ + addToTileCache(key, data) { + if (this.destroyed) return; + + let estimatedSize = 0; + if (data instanceof ImageBitmap) { + // Rough estimation: width * height * 4 bytes per pixel + estimatedSize = data.width * data.height * 4; + } else if (data && data.byteLength) { + estimatedSize = data.byteLength; + } else { + estimatedSize = 10000; // Default estimate + } + + this.tileCache.set(key, data, estimatedSize); + + // Update peak memory usage + const memoryUsage = this.tileCache.getMemoryUsage(); + this.metrics.memoryPeakMB = Math.max( + this.metrics.memoryPeakMB, + memoryUsage.memoryMB, + ); + } + + /** + * Get cached metadata + */ + getCachedMetadata(cacheKey) { + return GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + } + + /** + * Set cached metadata + */ + setCachedMetadata(cacheKey, data) { + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, data); + } + + /** + * Pause all operations + */ + pause() { + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager paused"); + } + } + + /** + * Resume operations + */ + resume() { + this.paused = false; + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager resumed"); + } + } + + /** + * Get performance metrics + */ + getMetrics() { + return { + ...this.metrics, + tileCache: this.tileCache.getMemoryUsage(), + workerPoolSize: this.workerPool.length, + pendingRequests: this.pendingRequests.size, + isPaused: this.paused, + isDestroyed: this.destroyed, + }; + } + + /** + * Destroy and cleanup all resources + */ + destroy() { + if (this.destroyed) return; + + this.destroyed = true; + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + // Clear caches + this.tileCache.clear(); + + // Clear worker pool references + this.workerPool.length = 0; + + // Remove from global registry + GLOBAL_SHARED_RESOURCES.activeManagers.delete(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager destroyed", this.getMetrics()); + } + } + } + + /** + * Global cleanup function + */ + const cleanup = () => { + for (const manager of GLOBAL_SHARED_RESOURCES.activeManagers) { + manager.destroy(); + } + GLOBAL_SHARED_RESOURCES.protocolCache.clear(); + GLOBAL_SHARED_RESOURCES.metadataCache.clear(); + }; + + // Register global cleanup + if (typeof window !== "undefined") { + window.addEventListener("beforeunload", cleanup); + } + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + + // Pre-calculate mercator bounds + this._mercatorBounds = { + west: mercatorXFromLng(this.bounds.getWest()), + north: mercatorYFromLat(this.bounds.getNorth()), + east: mercatorXFromLng(this.bounds.getEast()), + south: mercatorYFromLat(this.bounds.getSouth()), + }; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + // Use pre-calculated world size + const worldSize = + GLOBAL_SHARED_RESOURCES.worldSizeCache[tileID.z] || + Math.pow(2, tileID.z); + + // Use pre-calculated mercator bounds + const level = { + minX: Math.floor(this._mercatorBounds.west * worldSize), + minY: Math.floor(this._mercatorBounds.north * worldSize), + maxX: Math.ceil(this._mercatorBounds.east * worldSize), + maxY: Math.ceil(this._mercatorBounds.south * worldSize), + }; + + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + /** + * Enhanced PMTiles Source with lifecycle management + */ + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + + // Extract PMTiles-specific options + const pmtilesOptions = { + workerPoolSize: options.workerPoolSize, + tileCacheSize: options.tileCacheSize, + tileCacheMaxMemoryMB: options.tileCacheMaxMemoryMB, + metadataCacheSize: options.metadataCacheSize, + enableSharedProtocols: options.enableSharedProtocols, + requestTimeoutMs: options.requestTimeoutMs, + enableDebugLogging: options.enableDebugLogging, + enablePerformanceMetrics: options.enablePerformanceMetrics, + }; + + // Initialize resource manager + this.resourceManager = new PMTilesResourceManager(pmtilesOptions); + + // Standard source properties + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = _dispatcher; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._implementation = options; + + // Initialize worker pool + this.resourceManager.initializeWorkerPool(_dispatcher); + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + return; + } + + const { url } = options; + this.url = url; + this.tileSize = 512; + + // Get protocol instance + this.protocolInfo = this.resourceManager.getProtocol(url); + if (!this.protocolInfo) { + this.fire( + new ErrorEvent(new Error(`Failed to create protocol for ${url}`)), + ); + return; + } + + this._protocol = this.protocolInfo.protocol; + this._instance = this.protocolInfo.instance; + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + } + + static async getMetadata(url) { + // Check cache first + const cacheKey = `${url}:metadata`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const metadata = await instance.getMetadata(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, metadata); + return metadata; + } + + static async getHeader(url) { + // Check cache first + const cacheKey = `${url}:header`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const header = await instance.getHeader(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, header); + return header; + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (this.resourceManager.destroyed) return; + + if (!tile.destroy) { + tile.destroy = () => {}; + } + if (!tile.abort) { + tile.abort = () => { + tile.aborted = true; + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + }; + } + } + + /** + * Pause tile loading + */ + pause() { + this.resourceManager.pause(); + } + + /** + * Resume tile loading + */ + resume() { + this.resourceManager.resume(); + } + + /** + * Get performance metrics + */ + getMetrics() { + return this.resourceManager.getMetrics(); + } + + /** + * Destroy source and cleanup resources + */ + destroy() { + if (this.protocolInfo && this.url) { + this.resourceManager.releaseProtocol(this.url); + } + + this.resourceManager.destroy(); + this._loaded = false; + } + + async load(callback) { + if (this.resourceManager.destroyed) { + const error = new Error("Source has been destroyed"); + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + // Check metadata cache first + const headerKey = `${this.url}:header`; + const metadataKey = `${this.url}:metadata`; + + let header, tileJSON; + + const cachedHeader = this.resourceManager.getCachedMetadata(headerKey); + const cachedMetadata = + this.resourceManager.getCachedMetadata(metadataKey); + + if (cachedHeader && cachedMetadata) { + header = cachedHeader; + tileJSON = cachedMetadata; + } else { + try { + // Load and cache + [header, tileJSON] = await Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]); + this.resourceManager.setCachedMetadata(headerKey, header); + this.resourceManager.setCachedMetadata(metadataKey, tileJSON); + } catch (error) { + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + } + + try { + extend(this, tileJSON); + this.header = header; + const { tileType, minZoom, maxZoom, minLon, minLat, maxLon, maxLat } = + header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes(this.tileType) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { dataType: "source", sourceDataType: "metadata" }), + ); + this.fire( + new Event("data", { dataType: "source", sourceDataType: "content" }), + ); + } catch (err2) { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + } + } + + loaded() { + return this._loaded && !this.resourceManager.destroyed; + } + + loadVectorTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + const startTime = Date.now(); + var _a2, _b2, _c; + + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + + // Update metrics + this.resourceManager.metrics.tilesLoaded++; + const loadTime = Date.now() - startTime; + this.resourceManager.metrics.averageLoadTimeMs = + (this.resourceManager.metrics.averageLoadTimeMs + loadTime) / 2; + + if (tile.aborted) return callback(null); + + // Handle abort errors gracefully + if (err2 && err2.name === "AbortError") { + return callback(null); + } + + if (err2 && err2.status !== 404) { + return callback(err2); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + // Handle abort errors gracefully + if (error && (error.name === "AbortError" || error.code === 20)) { + return done.call(this, null); + } + done.call(this, error); + return; + } + + params.data = { + cacheControl, + expires, + rawData: data, + }; + + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + // Use shared worker pool + tile.actor = this.resourceManager.getWorkerFromPool(); + + // Fallback to dispatcher if worker pool failed + if (!tile.actor && this.dispatcher) { + try { + tile.actor = this.dispatcher.getActor(); + } catch (error) { + console.warn("[PMTiles] Failed to get fallback worker:", error); + return callback(new Error("No workers available")); + } + } + + if (!tile.actor) { + return callback(new Error("No workers available")); + } + + // Create request with timeout + const requestPromise = this._protocol.tile({ ...request }, afterLoad); + + // Add timeout if configured + if (this.resourceManager.config.requestTimeoutMs > 0) { + const timeoutId = setTimeout(() => { + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + done.call(this, new Error("Request timeout")); + }, this.resourceManager.config.requestTimeoutMs); + + const originalCancel = requestPromise.cancel; + requestPromise.cancel = () => { + clearTimeout(timeoutId); + if (originalCancel) originalCancel(); + }; + } + + tile.request = requestPromise; + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + if (this.resourceManager.destroyed) return; + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + var _a2, _b2; + + // Check tile cache first + const cacheKey = this.resourceManager.getTileCacheKey( + this.url, + tile.tileID.canonical.z, + tile.tileID.canonical.x, + tile.tileID.canonical.y, + ); + + if (this.resourceManager.tileCache.has(cacheKey)) { + this.resourceManager.metrics.cacheHits++; + const cachedData = this.resourceManager.tileCache.get(cacheKey); + this.loadRasterTileData(tile, cachedData); + tile.state = "loaded"; + return callback(null); + } + + this.resourceManager.metrics.cacheMisses++; + + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + + // Optimized raster tile loading - try direct ArrayBuffer first + const arrayBuffer = data.buffer || data; + window + .createImageBitmap(arrayBuffer) + .then((imageBitmap) => { + // Cache the decoded image + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + // Fallback to blob method + const blob = new window.Blob([new Uint8Array(data)], { + type: this.contentType, + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error(`Can't decode image for ${this.id}: ${error}`), + ); + }); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + this.fixTile(tile); + const controller = new AbortController(); + + // Add timeout if configured + let timeoutId; + if (this.resourceManager.config.requestTimeoutMs > 0) { + timeoutId = setTimeout(() => { + controller.abort(); + }, this.resourceManager.config.requestTimeoutMs); + } + + tile.request = { + cancel: () => { + if (timeoutId) clearTimeout(timeoutId); + controller.abort(); + }, + }; + + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (timeoutId) clearTimeout(timeoutId); + + // Handle abort errors gracefully + if (error.name === "AbortError" || error.code === 20) { + delete tile.request; + return callback(null); + } + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Expose cleanup function + PmTilesSource.cleanup = cleanup; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; + global.PMTilesResourceManager = PMTilesResourceManager; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js new file mode 100644 index 0000000..2130749 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js @@ -0,0 +1,459 @@ +/** + * mapbox-pmtiles v1.0.53 + * Original source: https://github.com/am2222/mapbox-pmtiles + * License: MIT + * + * This is a vendored copy of the mapbox-pmtiles library that provides + * PMTiles support for Mapbox GL JS by implementing a custom source type. + * + * Last updated: 2024 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + const worldSize = Math.pow(2, tileID.z); + const level = { + minX: Math.floor(mercatorXFromLng(this.bounds.getWest()) * worldSize), + minY: Math.floor(mercatorYFromLat(this.bounds.getNorth()) * worldSize), + maxX: Math.ceil(mercatorXFromLng(this.bounds.getEast()) * worldSize), + maxY: Math.ceil(mercatorYFromLat(this.bounds.getSouth()) * worldSize), + }; + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = void 0; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._dataType = "vector"; + this.dispatcher = _dispatcher; + this._implementation = options; + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + } + + const { url } = options; + this.reparseOverscaled = true; + this.scheme = "xyz"; + this.tileSize = 512; + this._loaded = false; + this.type = "vector"; + this._protocol = new pmtiles.Protocol(); + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + const pmtilesInstance = new pmtiles.PMTiles(url); + this._protocol.add(pmtilesInstance); + this._instance = pmtilesInstance; + } + + static async getMetadata(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getMetadata(); + } + + static async getHeader(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getHeader(); + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (!tile.destroy) { + tile.destroy = () => {}; + } + } + + async load(callback) { + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + return Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]) + .then(([header, tileJSON]) => { + extend(this, tileJSON); + this.header = header; + const { + specVersion, + clustered, + tileType, + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + centerZoom, + centerLon, + centerLat, + } = header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes( + this.tileType, + ) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "metadata", + }), + ); + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "content", + }), + ); + }) + .catch((err2) => { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + }); + } + + loaded() { + return this._loaded; + } + + loadVectorTile(tile, callback) { + var _a2, _b2, _c; + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + if (tile.aborted) return callback(null); + if (err2 && err2.status !== 404) { + return callback(err2); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + done.call(this, error); + return; + } + params.data = { + cacheControl, + expires, + rawData: data, + }; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + tile.actor = this._tileWorkers[url] = + this._tileWorkers[url] || this.dispatcher.getActor(); + tile.request = this._protocol.tile({ ...request }, afterLoad); + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + var _a2, _b2; + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + const blob = new window.Blob([new Uint8Array(data)], { + type: "image/png", + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error( + `Can't infer data type for ${this.id}, only raster data supported at the moment. ${error}`, + ), + ); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + this.fixTile(tile); + const controller = new AbortController(); + tile.request = { cancel: () => controller.abort() }; + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (error.code === 20) return; + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css new file mode 100644 index 0000000..16b2196 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css @@ -0,0 +1,44 @@ +.maplibregl-compare { + background-color: #fff; + position: absolute; + width: 2px; + height: 100%; + z-index: 1; +} +.maplibregl-compare .compare-swiper-vertical { + background-color: #3887be; + box-shadow: inset 0 0 0 2px #fff; + display: inline-block; + border-radius: 50%; + position: absolute; + width: 60px; + height: 60px; + top: 50%; + left: -30px; + margin: -30px 1px 0; + color: #fff; + cursor: ew-resize; + background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgd2lkdGg9IjYwIiAgIGhlaWdodD0iNjAiICAgdmVyc2lvbj0iMS4xIiAgIHZpZXdCb3g9IjAgMCA2MCA2MCIgICBpZD0ic3ZnNTQzNCIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxK2RldmVsK29zeG1lbnUgcjEyOTExIiAgIHNvZGlwb2RpOmRvY25hbWU9Imwtci5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE1NDQ0Ij4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgICAgPGRjOnRpdGxlPjwvZGM6dGl0bGU+ICAgICAgPC9jYzpXb3JrPiAgICA8L3JkZjpSREY+ICA8L21ldGFkYXRhPiAgPGRlZnMgICAgIGlkPSJkZWZzNTQ0MiIgLz4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTI4NiIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9Ijc1MSIgICAgIGlkPSJuYW1lZHZpZXc1NDQwIiAgICAgc2hvd2dyaWQ9InRydWUiICAgICBpbmtzY2FwZTp6b29tPSI0IiAgICAgaW5rc2NhcGU6Y3g9IjI1Ljg4OTgzMSIgICAgIGlua3NjYXBlOmN5PSIzNC4zODE4MzMiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyMyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjAiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJzdmc1NDM0IiAgICAgaW5rc2NhcGU6b2JqZWN0LW5vZGVzPSJ0cnVlIiAgICAgaW5rc2NhcGU6c25hcC1zbW9vdGgtbm9kZXM9InRydWUiPiAgICA8aW5rc2NhcGU6Z3JpZCAgICAgICB0eXBlPSJ4eWdyaWQiICAgICAgIGlkPSJncmlkNTk4OSIgLz4gIDwvc29kaXBvZGk6bmFtZWR2aWV3PiAgPHBhdGggICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjFweDtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIiAgICAgZD0iTSAyNSAyNCBMIDE2IDMwIEwgMjUgMzYgTCAyNSAyNCB6IE0gMzUgMjQgTCAzNSAzNiBMIDQ0IDMwIEwgMzUgMjQgeiAiICAgICBpZD0icGF0aDU5OTUiIC8+PC9zdmc+); +} + +.maplibregl-compare-horizontal { + position: relative; + width: 100%; + height: 2px; +} +.maplibregl-compare .compare-swiper-horizontal { + background-color: #3887be; + box-shadow: inset 0 0 0 2px #fff; + display: inline-block; + border-radius: 50%; + position: absolute; + width: 60px; + height: 60px; + top: 50%; + left: 50%; + margin: -30px 1px 0; + color: #fff; + cursor: ns-resize; + background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgd2lkdGg9IjYwIiAgIGhlaWdodD0iNjAiICAgdmVyc2lvbj0iMS4xIiAgIHZpZXdCb3g9IjAgMCA2MCA2MCIgICBpZD0ic3ZnNTQzNCIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxK2RldmVsK29zeG1lbnUgcjEyOTExIiAgIHNvZGlwb2RpOmRvY25hbWU9Imwtci5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE1NDQ0Ij4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgICAgPGRjOnRpdGxlPjwvZGM6dGl0bGU+ICAgICAgPC9jYzpXb3JrPiAgICA8L3JkZjpSREY+ICA8L21ldGFkYXRhPiAgPGRlZnMgICAgIGlkPSJkZWZzNTQ0MiIgLz4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTI4NiIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9Ijc1MSIgICAgIGlkPSJuYW1lZHZpZXc1NDQwIiAgICAgc2hvd2dyaWQ9InRydWUiICAgICBpbmtzY2FwZTp6b29tPSI0IiAgICAgaW5rc2NhcGU6Y3g9IjI1Ljg4OTgzMSIgICAgIGlua3NjYXBlOmN5PSIzNC4zODE4MzMiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyMyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjAiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJzdmc1NDM0IiAgICAgaW5rc2NhcGU6b2JqZWN0LW5vZGVzPSJ0cnVlIiAgICAgaW5rc2NhcGU6c25hcC1zbW9vdGgtbm9kZXM9InRydWUiPiAgICA8aW5rc2NhcGU6Z3JpZCAgICAgICB0eXBlPSJ4eWdyaWQiICAgICAgIGlkPSJncmlkNTk4OSIgLz4gIDwvc29kaXBvZGk6bmFtZWR2aWV3PiAgPHBhdGggICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjFweDtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIiAgICAgZD0iTSAyNSAyNCBMIDE2IDMwIEwgMjUgMzYgTCAyNSAyNCB6IE0gMzUgMjQgTCAzNSAzNiBMIDQ0IDMwIEwgMzUgMjQgeiAiICAgICBpZD0icGF0aDU5OTUiIC8+PC9zdmc+); + transform: rotate(90deg); +} diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js new file mode 100644 index 0000000..71e47d5 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js @@ -0,0 +1 @@ +!function o(i,r,s){function h(t,e){if(!r[t]){if(!i[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(u)return u(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=r[t]={exports:{}},i[t][0].call(n.exports,function(e){return h(i[t][1][e]||e)},n,n.exports,o,i,r,s)}return r[t].exports}for(var u="function"==typeof require&&require,e=0;ethis._bounds.width?this._bounds.width:e},_getY:function(e){e=(e=e.touches?e.touches[0]:e).clientY-this._bounds.top;return e=(e=e<0?0:e)>this._bounds.height?this._bounds.height:e},setSlider:function(e){this._setPosition(e)},on:function(e,t){return this._ev.on(e,t),this},fire:function(e,t){return this._ev.emit(e,t),this},off:function(e,t){return this._ev.removeListener(e,t),this},remove:function(){this._clearSync(),this._mapB.off("resize",this._onResize);var e=this._mapA.getContainer();e&&(e.style.clip=null,e.removeEventListener("mousemove",this._onMove));e=this._mapB.getContainer();e&&(e.style.clip=null,e.removeEventListener("mousemove",this._onMove)),this._swiper.removeEventListener("mousedown",this._onDown),this._swiper.removeEventListener("touchstart",this._onDown),this._controlContainer.remove()}},window.maplibregl?maplibregl.Compare=o:void 0!==t&&(t.exports=o)},{"@mapbox/mapbox-gl-sync-move":2,events:3}],2:[function(e,t,n){t.exports=function(){var e=arguments.length;if(1===e)t=arguments[0];else for(var t=[],n=0;nn&&!r.warned&&(r.warned=!0,(n=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit")).name="MaxListenersExceededWarning",n.emitter=e,n.type=t,n.count=r.length,n=n,console&&console.warn&&console.warn(n))),e}function l(e,t,n){e={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},t=function(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}.bind(e);return t.listener=n,e.wrapFn=t}function p(e,t,n){e=e._events;if(void 0===e)return[];t=e[t];return void 0===t?[]:"function"==typeof t?n?[t.listener||t]:[t]:n?function(e){for(var t=new Array(e.length),n=0;n * { + z-index: 2; + position: absolute; + right: 8px; + top: 7px; + display: none; +} + +.maplibregl-ctrl-geocoder, +.maplibregl-ctrl-geocoder .suggestions { + box-shadow: 0 0 10px 2px rgba(0, 0, 0, 0.1); +} + +/* Collapsed */ +.maplibregl-ctrl-geocoder.maplibregl-ctrl-geocoder--collapsed { + width: 50px; + min-width: 50px; + transition: width 0.25s, min-width 0.25s; +} + +/* Suggestions */ +.maplibregl-ctrl-geocoder .suggestions { + background-color: #fff; + border-radius: 4px; + left: 0; + list-style: none; + margin: 0; + padding: 0; + position: absolute; + width: 100%; + top: 110%; /* fallback */ + top: calc(100% + 6px); + z-index: 1000; + overflow: hidden; + font-size: 15px; +} + +.maplibregl-ctrl-bottom-left .suggestions, +.maplibregl-ctrl-bottom-right .suggestions { + top: auto; + bottom: 100%; +} + +.maplibregl-ctrl-geocoder .suggestions > li > a { + cursor: default; + display: block; + padding: 6px 12px; + color: #404040; +} + +.maplibregl-ctrl-geocoder .suggestions > .active > a, +.maplibregl-ctrl-geocoder .suggestions > li > a:hover { + color: #404040; + background-color: #f3f3f3; + text-decoration: none; + cursor: pointer; +} + +.maplibregl-ctrl-geocoder--suggestion { + display: flex; + flex-direction: row; + align-items: center; +} + +.maplibre-ctrl-geocoder--suggestion-icon { + min-width: 30px; + min-height: 24px; + max-width: 30px; + max-height: 24px; + padding-right: 12px; +} + +.maplibregl-ctrl-geocoder--suggestion-info { + display: flex; + flex-direction: column; +} + +.maplibregl-ctrl-geocoder--suggestion-match { + font-weight: bold; +} + +.maplibregl-ctrl-geocoder--suggestion-title, +.maplibregl-ctrl-geocoder--suggestion-address { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +.maplibregl-ctrl-geocoder--result { + display: flex; + flex-direction: row; + align-items: center; +} + +.maplibre-ctrl-geocoder--result-icon { + min-width: 30px; + min-height: 24px; + max-width: 30px; + max-height: 24px; + padding-right: 12px; +} + +.maplibregl-ctrl-geocoder--result-title { + font-weight: bold; +} + +.maplibregl-ctrl-geocoder--result-title, +.maplibregl-ctrl-geocoder--result-address { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +/* Icons */ +.maplibregl-ctrl-geocoder--icon { + display: inline-block; + vertical-align: middle; + speak: none; + fill: #757575; + top: 15px; +} + +.maplibregl-ctrl-geocoder--icon-search { + position: absolute; + top: 13px; + left: 12px; + width: 23px; + height: 23px; +} + +.maplibregl-ctrl-geocoder--button { + padding: 0; + margin: 0; + border: none; + cursor: pointer; + background: #fff; + line-height: 1; +} + +.maplibregl-ctrl-geocoder--icon-close { + width: 20px; + height: 20px; + margin-top: 8px; + margin-right: 3px; +} + +.maplibregl-ctrl-geocoder--button:hover .maplibregl-ctrl-geocoder--icon-close { + fill: #909090; +} + +.maplibregl-ctrl-geocoder--icon-loading { + width: 26px; + height: 26px; + margin-top: 5px; + margin-right: 0px; + -moz-animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); + -webkit-animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); + animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); +} + +/* Animation */ +@-webkit-keyframes rotate { + from { + -webkit-transform: rotate(0); + transform: rotate(0); + } + to { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +@keyframes rotate { + from { + -webkit-transform: rotate(0); + transform: rotate(0); + } + to { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +/* Media queries*/ +@media screen and (min-width: 640px) { + .maplibregl-ctrl-geocoder.maplibregl-ctrl-geocoder--collapsed { + width: 36px; + min-width: 36px; + } + + .maplibregl-ctrl-geocoder { + width: 33.3333%; + font-size: 15px; + line-height: 20px; + max-width: 360px; + } + .maplibregl-ctrl-geocoder .suggestions { + font-size: 13px; + } + + .maplibregl-ctrl-geocoder--icon { + top: 8px; + } + + .maplibregl-ctrl-geocoder--icon-close { + width: 16px; + height: 16px; + margin-top: 3px; + margin-right: 0; + } + + .maplibregl-ctrl-geocoder--icon-search { + left: 7px; + width: 20px; + height: 20px; + } + + .maplibregl-ctrl-geocoder--input { + height: 36px; + padding: 6px 35px; + } + + .maplibregl-ctrl-geocoder--icon-loading { + width: 26px; + height: 26px; + margin-top: -2px; + margin-right: -5px; + } + + .maplibre-gl-geocoder--error { + color: #909090; + padding: 6px 12px; + font-size: 16px; + text-align: center; + } +} diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js new file mode 100644 index 0000000..e285a1a --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js @@ -0,0 +1,2 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.MaplibreGeocoder=t()}}(function(){return function(){function t(e,i,n){function s(o,l){if(!i[o]){if(!e[o]){var a="function"==typeof require&&require;if(!l&&a)return a(o,!0);if(r)return r(o,!0);var h=new Error("Cannot find module '"+o+"'");throw h.code="MODULE_NOT_FOUND",h}var u=i[o]={exports:{}};e[o][0].call(u.exports,function(t){return s(e[o][1][t]||t)},u,u.exports,t,e,i,n)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o
'+e[0]+'
'+e.splice(1,e.length).join(",")+"
"}var i=t.text,n=i.toLowerCase().indexOf(this.query.toLowerCase()),s=this.query.length;return'
'+i.substring(0,n)+''+i.substring(n,n+s)+""+i.substring(n+s)+"
"},popupRender:function(t){var e=t.place_name.split(",");return'"},showResultMarkers:!0,debounceSearch:200},addTo:function(t){function e(t,e){if(!document.body.contains(e))throw new Error("Element provided to #addTo() exists, but is not in the DOM");var i=t.onAdd();e.appendChild(i)}if(t._controlContainer)t.addControl(this);else if(t instanceof HTMLElement)e(this,t);else{if("string"!=typeof t)throw new Error("Error: addTo must be a maplibre-gl-js map, an html element, or a CSS selector query for a single html element");var i=document.querySelectorAll(t);if(0===i.length)throw new Error("Element ",t,"not found.");if(i.length>1)throw new Error("Geocoder can only be added to a single html element");e(this,i[0])}},onAdd:function(t){if(t&&"string"!=typeof t&&(this._map=t),this.setLanguage(),this.options.localGeocoderOnly&&!this.options.localGeocoder)throw new Error("A localGeocoder function must be specified to use localGeocoderOnly mode");this._onChange=this._onChange.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPaste=this._onPaste.bind(this),this._onBlur=this._onBlur.bind(this),this._showButton=this._showButton.bind(this),this._hideButton=this._hideButton.bind(this),this._onQueryResult=this._onQueryResult.bind(this),this.clear=this.clear.bind(this),this._updateProximity=this._updateProximity.bind(this),this._collapse=this._collapse.bind(this),this._unCollapse=this._unCollapse.bind(this),this._clear=this._clear.bind(this),this._clearOnBlur=this._clearOnBlur.bind(this);var e=this.container=document.createElement("div");e.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl";var i=this.createIcon("search",'');this._inputEl=document.createElement("input"),this._inputEl.type="text",this._inputEl.className="mapboxgl-ctrl-geocoder--input maplibregl-ctrl-geocoder--input",this.setPlaceholder(),this.options.collapsed&&(this._collapse(),this.container.addEventListener("mouseenter",this._unCollapse),this.container.addEventListener("mouseleave",this._collapse),this._inputEl.addEventListener("focus",this._unCollapse)),(this.options.collapsed||this.options.clearOnBlur)&&this._inputEl.addEventListener("blur",this._onBlur),this._inputEl.addEventListener("keydown",r(this._onKeyDown,this.options.debounceSearch)),this._inputEl.addEventListener("paste",this._onPaste),this._inputEl.addEventListener("change",this._onChange),this.container.addEventListener("mouseenter",this._showButton),this.container.addEventListener("mouseleave",this._hideButton);var n=document.createElement("div");n.classList.add("mapboxgl-ctrl-geocoder--pin-right","maplibregl-ctrl-geocoder--pin-right"),this._clearEl=document.createElement("button"),this._clearEl.setAttribute("aria-label","Clear"),this._clearEl.addEventListener("click",this.clear),this._clearEl.className="mapboxgl-ctrl-geocoder--button maplibregl-ctrl-geocoder--button";var o=this.createIcon("close",'');return this._clearEl.appendChild(o),this._loadingEl=this.createIcon("loading",''),n.appendChild(this._clearEl),n.appendChild(this._loadingEl),e.appendChild(i),e.appendChild(this._inputEl),e.appendChild(n),this._typeahead=new s(this._inputEl,[],{filter:!1,minLength:this.options.minLength,limit:this.options.limit,noInitialSelection:!0}),this.setRenderFunction(this.options.render),this._typeahead.getItemValue=this.options.getItemValue,this.mapMarker=null,this.resultMarkers=[],this._handleMarker=this._handleMarker.bind(this),this._handleResultMarkers=this._handleResultMarkers.bind(this),this._map&&(this.options.trackProximity&&(this._updateProximity(),this._map.on("moveend",this._updateProximity)),this._maplibregl=this.options.maplibregl,!this._maplibregl&&this.options.marker&&(console.error("No maplibregl detected in options. Map markers are disabled. Please set options.maplibregl."),this.options.marker=!1)),e},createIcon:function(t,e){var i=document.createElementNS("http://www.w3.org/2000/svg","svg");if(i.setAttribute("class","mapboxgl-ctrl-geocoder--icon mapboxgl-ctrl-geocoder--icon-"+t+" maplibregl-ctrl-geocoder--icon maplibregl-ctrl-geocoder--icon-"+t),i.setAttribute("viewBox","0 0 18 18"),i.setAttribute("xml:space","preserve"),i.setAttribute("width",18),i.setAttribute("height",18),"innerHTML"in i)i.innerHTML=e;else{var n=document.createElement("div");n.innerHTML=""+e.valueOf().toString()+"";var s=n.firstChild,r=s.firstChild;i.appendChild(r)}return i},onRemove:function(){return this.container.parentNode.removeChild(this.container),this.options.trackProximity&&this._map&&this._map.off("moveend",this._updateProximity),this._removeMarker(),this._map=null,this},_onPaste:function(t){var e=(t.clipboardData||window.clipboardData).getData("text");e.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(e)},_onKeyDown:function(t){if(27===t.keyCode&&this.options.clearAndBlurOnEsc)return this._clear(t),this._inputEl.blur();var e=t.target&&t.target.shadowRoot?t.target.shadowRoot.activeElement:t.target;if(!(e?e.value:""))return this.fresh=!0,9!==t.keyCode&&this.clear(t),this._clearEl.style.display="none";if(!t.metaKey&&-1===[9,27,37,39,38,40].indexOf(t.keyCode)){if(13===t.keyCode){if(this.options.showResultsWhileTyping)return void(null==this._typeahead.selected&&this.geocoderApi.getSuggestions?this._geocode(e.value,!0):null==this._typeahead.selected&&this.options.showResultMarkers&&this._fitBoundsForMarkers());this._typeahead.selected||this._geocode(e.value)}e.value.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(e.value)}},_showButton:function(){this._inputEl.value.length>0&&(this._clearEl.style.display="block")},_hideButton:function(){this._typeahead.selected&&(this._clearEl.style.display="none")},_onBlur:function(t){this.options.clearOnBlur&&this._clearOnBlur(t),this.options.collapsed&&this._collapse()},_onChange:function(){var t=this._typeahead.selected;if(t&&!t.geometry)t.placeId?this._geocode(t.placeId,!0,!0):this._geocode(t.text,!0);else if(t&&JSON.stringify(t)!==this.lastSelected){if(this._clearEl.style.display="none",this.options.flyTo){var e;if(this._removeResultMarkers(),t.properties&&a[t.properties.short_code])e=o({},this.options.flyTo),this._map&&this._map.fitBounds(a[t.properties.short_code].bbox,e);else if(t.bbox){var i=t.bbox;e=o({},this.options.flyTo),this._map&&this._map.fitBounds([[i[0],i[1]],[i[2],i[3]]],e)}else{var n={zoom:this.options.zoom};e=o({},n,this.options.flyTo),t.center?e.center=t.center:t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(e.center=t.geometry.coordinates),this._map&&this._map.flyTo(e)}}this.options.marker&&this._maplibregl&&this._handleMarker(t),this._inputEl.focus(),this._inputEl.scrollLeft=0,this._inputEl.setSelectionRange(0,0),this.lastSelected=JSON.stringify(t),this._typeahead.selected=null,this._eventEmitter.emit("result",{result:t})}},_getConfigForRequest:function(){var t=["bbox","limit","proximity","countries","types","language","reverseMode"],e=this;return t.reduce(function(t,i){return e.options[i]&&(["countries","types","language"].indexOf(i)>-1?t[i]=e.options[i].split(/[\s,]+/):t[i]=e.options[i],"proximity"===i&&e.options[i]&&"number"==typeof e.options[i].longitude&&"number"==typeof e.options[i].latitude&&(t[i]=[e.options[i].longitude,e.options[i].latitude])),t},{})},_geocode:function(t,e,i){this._loadingEl.style.display="block",this._eventEmitter.emit("loading",{query:t}),this.inputString=t;var n,s=null,r=this._getConfigForRequest();if(this.options.localGeocoderOnly)n=Promise.resolve();else if(this.options.reverseGeocode&&/(-?\d+\.?\d*)[, ]+(-?\d+\.?\d*)[ ]*$/.test(t)){var l=t.split(/[\s(,)?]+/).map(function(t){return parseFloat(t,10)}).reverse();r.types&&r.types[0],r=o(r,{query:l,limit:1}),"proximity"in r&&delete r.proximity,n=this.geocoderApi.reverseGeocode(r)}else r=o(r,{query:t}),n=this.geocoderApi.getSuggestions?e?this.geocoderApi.searchByPlaceId&&i?this.geocoderApi.searchByPlaceId(r):this.geocoderApi.forwardGeocode(r):this.geocoderApi.getSuggestions(r):this.geocoderApi.forwardGeocode(r);var a=[];this.options.localGeocoder&&((a=this.options.localGeocoder(t))||(a=[]));var h=[];return n.catch(function(t){s=t}.bind(this)).then(function(e){this._loadingEl.style.display="none";var i={};return i=e||{type:"FeatureCollection",features:[]},i.config=r,this.fresh&&(this.fresh=!1),i.features=i.features?a.concat(i.features):a,this.options.externalGeocoder?(h=this.options.externalGeocoder(t,i.features,r)||[],h.then(function(t){return i.features=i.features?t.concat(i.features):t,i},function(){return i})):i}.bind(this)).then(function(t){if(s)throw s;this.options.filter&&t.features.length&&(t.features=t.features.filter(this.options.filter));var i=[];i=t.suggestions?t.suggestions:t.place?[t.place]:t.features,i.length?(this._clearEl.style.display="block",this._typeahead.update(i),(!this.options.showResultsWhileTyping||e)&&this.options.showResultMarkers&&(t.features.length>0||t.place)&&this._fitBoundsForMarkers(),this._eventEmitter.emit("results",t)):(this._clearEl.style.display="none",this._typeahead.selected=null,this._renderNoResults(),this._eventEmitter.emit("results",t))}.bind(this)).catch(function(t){this._loadingEl.style.display="none",a.length&&this.options.localGeocoder||h.length&&this.options.externalGeocoder?(this._clearEl.style.display="block",this._typeahead.update(a)):(this._clearEl.style.display="none",this._typeahead.selected=null,this._renderError()),this._eventEmitter.emit("results",{features:a}),this._eventEmitter.emit("error",{error:t})}.bind(this)),n},_clear:function(t){t&&t.preventDefault(),this._inputEl.value="",this._typeahead.selected=null,this._typeahead.clear(),this._onChange(),this._clearEl.style.display="none",this._removeMarker(),this._removeResultMarkers(),this.lastSelected=null,this._eventEmitter.emit("clear"),this.fresh=!0},clear:function(t){this._clear(t),this._inputEl.focus()},_clearOnBlur:function(t){var e=this;t.relatedTarget&&e._clear(t)},_onQueryResult:function(t){var e=t;if(e.features.length){var i=e.features[0];this._typeahead.selected=i,this._inputEl.value=i.place_name,this._onChange()}},_updateProximity:function(){if(this._map)if(this._map.getZoom()>9){var t=this._map.getCenter().wrap();this.setProximity({longitude:t.lng,latitude:t.lat})}else this.setProximity(null)},_collapse:function(){this._inputEl.value||this._inputEl===document.activeElement||this.container.classList.add("mapboxgl-ctrl-geocoder--collapsed","maplibregl-ctrl-geocoder--collapsed")},_unCollapse:function(){this.container.classList.remove("mapboxgl-ctrl-geocoder--collapsed","maplibregl-ctrl-geocoder--collapsed")},query:function(t){return this._geocode(t).then(this._onQueryResult),this},_renderError:function(){this._renderMessage("
There was an error reaching the server
")},_renderNoResults:function(){this._renderMessage("
No results found
")},_renderMessage:function(t){this._typeahead.update([]),this._typeahead.selected=null,this._typeahead.clear(),this._typeahead.renderError(t)},_getPlaceholderText:function(){if(this.options.placeholder)return this.options.placeholder;if(this.options.language){var t=this.options.language.split(",")[0],e=u.language(t),i=h.placeholder[e];if(i)return i}return"Search"},_fitBoundsForMarkers:function(){if(!(this._typeahead.data.length<1)){var t=this._typeahead.data.filter(function(t){return"string"!=typeof t}).slice(0,this.options.limit);if(this._clearEl.style.display="none",this.options.flyTo&&this._maplibregl&&this._map){var e={padding:100},i=o({},e,this.options.flyTo),n=new this._maplibregl.LngLatBounds;t.forEach(function(t){n.extend(t.geometry.coordinates)}),this._map.fitBounds(n.toArray(),i)}return t.length>0&&this._maplibregl&&this._handleResultMarkers(t),this}},setInput:function(t){return this._inputEl.value=t,this._typeahead.selected=null,this._typeahead.clear(),t.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(t),this},setProximity:function(t){return this.options.proximity=t,this},getProximity:function(){return this.options.proximity},setRenderFunction:function(t){return t&&"function"==typeof t&&(this._typeahead.render=t),this},getRenderFunction:function(){return this._typeahead.render},setLanguage:function(t){var e=navigator.language||navigator.userLanguage||navigator.browserLanguage;return this.options.language=t||this.options.language||e,this},getLanguage:function(){return this.options.language},getZoom:function(){return this.options.zoom},setZoom:function(t){return this.options.zoom=t,this},getFlyTo:function(){return this.options.flyTo},setFlyTo:function(t){return this.options.flyTo=t,this},getPlaceholder:function(){return this.options.placeholder},setPlaceholder:function(t){return this.placeholder=t||this._getPlaceholderText(),this._inputEl.placeholder=this.placeholder,this._inputEl.setAttribute("aria-label",this.placeholder),this},getBbox:function(){return this.options.bbox},setBbox:function(t){return this.options.bbox=t,this},getCountries:function(){return this.options.countries},setCountries:function(t){return this.options.countries=t,this},getTypes:function(){return this.options.types},setTypes:function(t){return this.options.types=t,this},getMinLength:function(){return this.options.minLength},setMinLength:function(t){return this.options.minLength=t,this._typeahead&&(this._typeahead.options.minLength=t),this},getLimit:function(){return this.options.limit},setLimit:function(t){return this.options.limit=t,this._typeahead&&(this._typeahead.options.limit=t),this},getFilter:function(){return this.options.filter},setFilter:function(t){return this.options.filter=t,this},setGeocoderApi:function(t){return this.geocoderApi=t,this},getGeocoderApi:function(){return this.geocoderApi},_handleMarker:function(t){if(this._map){this._removeMarker();var e={color:"#4668F2"},i=o({},e,this.options.marker);this.mapMarker=new this._maplibregl.Marker(i);var n;if(this.options.popup){var s={},r=o({},s,this.options.popup);n=new this._maplibregl.Popup(r).setHTML(this.options.popupRender(t))}return t.center?(this.mapMarker.setLngLat(t.center).addTo(this._map),this.options.popup&&this.mapMarker.setPopup(n)):t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(this.mapMarker.setLngLat(t.geometry.coordinates).addTo(this._map),this.options.popup&&this.mapMarker.setPopup(n)),this}},_removeMarker:function(){this.mapMarker&&(this.mapMarker.remove(),this.mapMarker=null)},_handleResultMarkers:function(t){if(this._map){this._removeResultMarkers();var e={color:"#4668F2"},i=o({},e,this.options.showResultMarkers);return t.forEach(function(t){if(this.options.showResultMarkers&&this.options.showResultMarkers.element){var e=this.options.showResultMarkers.element.cloneNode(!0);i=o(i,{element:e})}var n,s=new this._maplibregl.Marker(o({},i,{element:e}));if(this.options.popup){var r={},l=o({},r,this.options.popup);n=new this._maplibregl.Popup(l).setHTML(this.options.popupRender(t))}t.center?(s.setLngLat(t.center).addTo(this._map),this.options.popup&&s.setPopup(n)):t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(s.setLngLat(t.geometry.coordinates).addTo(this._map),this.options.popup&&s.setPopup(n)),this.resultMarkers.push(s)}.bind(this)),this}},_removeResultMarkers:function(){this.resultMarkers&&this.resultMarkers.length>0&&(this.resultMarkers.forEach(function(t){t.remove()}),this.resultMarkers=[])},on:function(t,e){return this._eventEmitter.on(t,e),this},off:function(t,e){return this._eventEmitter.removeListener(t,e),this}},e.exports=n},{"./exceptions":1,"./localization":3,events:4,"lodash.debounce":6,subtag:7,"suggestions-list":8,xtend:11}],3:[function(t,e,i){"use strict";var n={de:"Suche",it:"Ricerca",en:"Search",nl:"Zoeken",fr:"Chercher",ca:"Cerca",he:"לחפש",ja:"サーチ",lv:"Meklēt",pt:"Procurar",sr:"Претрага",zh:"搜索",cs:"Vyhledávání",hu:"Keresés",ka:"ძიება",nb:"Søke",sk:"Vyhľadávanie",th:"ค้นหา",fi:"Hae",is:"Leita",ko:"수색",pl:"Szukaj",sl:"Iskanje",fa:"جستجو",ru:"Поиск"};e.exports={placeholder:n}},{}],4:[function(t,e,i){function n(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=w(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}function s(t){return void 0===t._maxListeners?n.defaultMaxListeners:t._maxListeners}function r(t,e,i){if(e)t.call(i);else for(var n=t.length,s=m(t,n),r=0;r0&&l.length>r){l.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+l.length+' "'+String(e)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=l.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",a.name,a.message)}}else l=o[e]=i,++t._eventsCount;return t}function c(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var t=new Array(arguments.length),e=0;e1&&(e=arguments[1]),e instanceof Error)throw e;var d=new Error('Unhandled "error" event. ('+e+")");throw d.context=e,d}if(!(i=c[t]))return!1;var f="function"==typeof i;switch(n=arguments.length){case 1:r(i,f,this);break;case 2:o(i,f,this,arguments[1]);break;case 3:l(i,f,this,arguments[1],arguments[2]);break;case 4:a(i,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(n-1),u=1;u=0;r--)if(i[r]===e||i[r].listener===e){o=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():g(i,s),1===i.length&&(n[t]=i[0]),n.removeListener&&this.emit("removeListener",t,o||e)}return this},n.prototype.removeAllListeners=function(t){var e,i,n;if(!(i=this._events))return this;if(!i.removeListener)return 0===arguments.length?(this._events=w(null),this._eventsCount=0):i[t]&&(0==--this._eventsCount?this._events=w(null):delete i[t]),this;if(0===arguments.length){var s,r=x(i);for(n=0;n=0;n--)this.removeListener(t,e[n]);return this},n.prototype.listeners=function(t){return d(this,t,!0)},n.prototype.rawListeners=function(t){return d(this,t,!1)},n.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):f.call(t,e)},n.prototype.listenerCount=f,n.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],5:[function(t,e,i){!function(){var t=this,n={};void 0!==i?e.exports=n:t.fuzzy=n,n.simpleFilter=function(t,e){return e.filter(function(e){return n.test(t,e)})},n.test=function(t,e){return null!==n.match(t,e)},n.match=function(t,e,i){i=i||{};var n,s=0,r=[],o=e.length,l=0,a=0,h=i.pre||"",u=i.post||"",c=i.caseSensitive&&e||e.toLowerCase();t=i.caseSensitive&&t||t.toLowerCase();for(var p=0;p=e||i<0||C&&n>=v}function u(){var t=x();if(h(t))return c(t);_=setTimeout(u,a(t))}function c(t){return _=void 0,M&&g?s(t):(g=m=void 0,y)}function p(){void 0!==_&&clearTimeout(_),L=0,g=E=m=_=void 0}function d(){return void 0===_?y:c(x())}function f(){var t=x(),i=h(t);if(g=arguments,m=this,E=t,i){if(void 0===_)return r(E);if(C)return _=setTimeout(u,e),s(E)}return void 0===_&&(_=setTimeout(u,e)),y}var g,m,v,y,_,E,L=0,k=!1,C=!1,M=!0;if("function"!=typeof t)throw new TypeError(l);return e=o(e)||0,n(i)&&(k=!!i.leading,C="maxWait"in i,v=C?b(o(i.maxWait)||0,e):v,M="trailing"in i?!!i.trailing:M),f.cancel=p,f.flush=d,f}function n(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function s(t){return!!t&&"object"==typeof t}function r(t){return"symbol"==typeof t||s(t)&&_.call(t)==h}function o(t){if("number"==typeof t)return t;if(r(t))return a;if(n(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=n(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(u,"");var i=p.test(t);return i||d.test(t)?f(t.slice(2),i?2:8):c.test(t)?a:+t}var l="Expected a function",a=NaN,h="[object Symbol]",u=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,d=/^0o[0-7]+$/i,f=parseInt,g="object"==typeof t&&t&&t.Object===Object&&t,m="object"==typeof self&&self&&self.Object===Object&&self,v=g||m||Function("return this")(),y=Object.prototype,_=y.toString,b=Math.max,w=Math.min,x=function(){return v.Date.now()};e.exports=i}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],7:[function(t,e,i){!function(t,i,n){void 0!==e&&e.exports?e.exports=n():t.subtag=n()}(this,0,function(){function t(t){return t.match(o)||[]}function e(e){return t(e).filter(function(t,e){return t&&e})}function i(e){return e=t(e),{language:e[1]||r,extlang:e[2]||r,script:e[3]||r,region:e[4]||r}}function n(t,e,i){Object.defineProperty(t,e,{value:i,enumerable:!0})}function s(e,s,o){function l(i){return t(i)[e]||r}n(l,"pattern",s),n(i,o,l)}var r="",o=/^([a-zA-Z]{2,3})(?:[_-]+([a-zA-Z]{3})(?=$|[_-]+))?(?:[_-]+([a-zA-Z]{4})(?=$|[_-]+))?(?:[_-]+([a-zA-Z]{2}|[0-9]{3})(?=$|[_-]+))?/;return s(1,/^[a-zA-Z]{2,3}$/,"language"),s(2,/^[a-zA-Z]{3}$/,"extlang"),s(3,/^[a-zA-Z]{4}$/,"script"),s(4,/^[a-zA-Z]{2}$|^[0-9]{3}$/,"region"),n(i,"split",e),i})},{}],8:[function(t,e,i){"use strict";var n=t("./src/suggestions");e.exports=n,"undefined"!=typeof window&&(window.Suggestions=n)},{"./src/suggestions":10}],9:[function(t,e,i){"use strict";var n=function(t){return this.component=t,this.items=[],this.active=t.options.noInitialSelection?-1:0,this.wrapper=document.createElement("div"),this.wrapper.className="suggestions-wrapper",this.element=document.createElement("ul"),this.element.className="suggestions",this.wrapper.appendChild(this.element),this.selectingListItem=!1,t.el.parentNode.insertBefore(this.wrapper,t.el.nextSibling),this};n.prototype.show=function(){this.element.style.display="block"},n.prototype.hide=function(){this.element.style.display="none"},n.prototype.add=function(t){this.items.push(t)},n.prototype.clear=function(){this.items=[],this.active=this.component.options.noInitialSelection?-1:0},n.prototype.isEmpty=function(){return!this.items.length},n.prototype.isVisible=function(){return"block"===this.element.style.display},n.prototype.draw=function(){if(this.element.innerHTML="", +0===this.items.length)return void this.hide();for(var t=0;t=this.items.length-1?0:this.active+1)},n.prototype.drawError=function(t){var e=document.createElement("li");e.innerHTML=t,this.element.appendChild(e),this.show()},e.exports=n},{}],10:[function(t,e,i){"use strict";var n=t("xtend"),s=t("fuzzy"),r=t("./list"),o=function(t,e,i){return i=i||{},this.options=n({minLength:2,limit:5,filter:!0,hideOnBlur:!0,noInitialSelection:!0},i),this.el=t,this.data=e||[],this.list=new r(this),this.query="",this.selected=null,this.list.draw(),this.el.addEventListener("keyup",function(t){this.handleKeyUp(t.keyCode,t)}.bind(this),!1),this.el.addEventListener("keydown",function(t){this.handleKeyDown(t)}.bind(this)),this.el.addEventListener("focus",function(){this.handleFocus()}.bind(this)),this.el.addEventListener("blur",function(){this.handleBlur()}.bind(this)),this.el.addEventListener("paste",function(t){this.handlePaste(t)}.bind(this)),this.render=this.options.render?this.options.render.bind(this):this.render.bind(this),this.getItemValue=this.options.getItemValue?this.options.getItemValue.bind(this):this.getItemValue.bind(this),this};o.prototype.handleKeyUp=function(t,e){if(40!==t&&38!==t&&27!==t&&9!==t)return 13===t?void(this.list.items[this.list.active]&&(this.list.handleMouseUp(this.list.items[this.list.active]),e.stopPropagation())):void this.handleInputChange(this.el.value)},o.prototype.handleKeyDown=function(t){switch(t.keyCode){case 13:this.list.active>=0&&(this.list.selectingListItem=!0);break;case 9:this.list.isEmpty()||(this.list.isVisible()&&t.preventDefault(),this.value(this.list.active>=0?this.list.items[this.list.active].original:null),this.list.hide());break;case 27:this.list.isEmpty()||this.list.hide();break;case 38:this.list.previous();break;case 40:this.list.next()}},o.prototype.handleBlur=function(){!this.list.selectingListItem&&this.options.hideOnBlur&&this.list.hide()},o.prototype.handlePaste=function(t){if(t.clipboardData)this.handleInputChange(t.clipboardData.getData("Text"));else{var e=this;setTimeout(function(){e.handleInputChange(t.target.value)},100)}},o.prototype.handleInputChange=function(t){if(this.query=this.normalize(t),this.list.clear(),this.query.length-1},o.prototype.value=function(t){if(this.selected=t,this.el.value=this.getItemValue(t||{place_name:this.query}),document.createEvent){var e=document.createEvent("HTMLEvents");e.initEvent("change",!0,!1),this.el.dispatchEvent(e)}else this.el.fireEvent("onchange")},o.prototype.getCandidates=function(t){var e,i={pre:"",post:"",extract:function(t){return this.getItemValue(t)}.bind(this)};this.options.filter?(e=s.filter(this.query,this.data,i),e=e.map(function(t){return{original:t.original,string:this.render(t.original,t.string)}}.bind(this))):e=this.data.map(function(t){return{original:t,string:this.render(t)}}.bind(this)),t(e)},o.prototype.getItemValue=function(t){return t},o.prototype.render=function(t,e){if(e)return e;for(var i=t.original?this.getItemValue(t.original):this.getItemValue(t),n=this.normalize(i),s=n.lastIndexOf(this.query);s>-1;){var r=s+this.query.length;i=i.slice(0,s)+""+i.slice(s,r)+""+i.slice(r),s=n.slice(0,s).lastIndexOf(this.query)}return i},o.prototype.renderError=function(t){this.list.drawError(t)},e.exports=o},{"./list":9,fuzzy:5,xtend:11}],11:[function(t,e,i){function n(){for(var t={},e=0;e.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:hsla(0,0%,100%,.5);background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:rgba(0,0,0,.05)}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:hsla(0,0%,100%,.75);border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:rgba(0,0,0,.05)}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px rgba(0,0,0,.35);box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:rgba(0,0,0,.4);color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media (hover:none),(pointer:coarse){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999} \ No newline at end of file diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js new file mode 100644 index 0000000..53dd1e0 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js @@ -0,0 +1,59 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v5.7.2/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory()); +})(this, (function () { 'use strict'; + +/* eslint-disable */ + +var maplibregl = {}; +var modules = {}; +function define(moduleName, _dependencies, moduleFactory) { + modules[moduleName] = moduleFactory; + + // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) + if (moduleName !== 'index') { + return; + } + + // we assume that when an index module is initializing then other modules are loaded already + var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);' + + var sharedModule = {}; + // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) + // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) + // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following + modules.shared(sharedModule); + modules.index(maplibregl, sharedModule); + + if (typeof window !== 'undefined') { + maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); + } + + return maplibregl; +}; + + + +define("shared",["exports"],(function(t){"use strict";function e(t,e,r,n){return new(r||(r=Promise))((function(i,s){function a(t){try{l(n.next(t));}catch(t){s(t);}}function o(t){try{l(n.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(a,o);}l((n=n.apply(t,e||[])).next());}))}function r(t,e){this.x=t,this.y=e;}function n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,s;"function"==typeof SuppressedError&&SuppressedError,r.prototype={clone(){return new r(this.x,this.y)},add(t){return this.clone()._add(t)},sub(t){return this.clone()._sub(t)},multByPoint(t){return this.clone()._multByPoint(t)},divByPoint(t){return this.clone()._divByPoint(t)},mult(t){return this.clone()._mult(t)},div(t){return this.clone()._div(t)},rotate(t){return this.clone()._rotate(t)},rotateAround(t,e){return this.clone()._rotateAround(t,e)},matMult(t){return this.clone()._matMult(t)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(t){return this.x===t.x&&this.y===t.y},dist(t){return Math.sqrt(this.distSqr(t))},distSqr(t){const e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle(){return Math.atan2(this.y,this.x)},angleTo(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith(t){return this.angleWithSep(t.x,t.y)},angleWithSep(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult(t){const e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add(t){return this.x+=t.x,this.y+=t.y,this},_sub(t){return this.x-=t.x,this.y-=t.y,this},_mult(t){return this.x*=t,this.y*=t,this},_div(t){return this.x/=t,this.y/=t,this},_multByPoint(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint(t){return this.x/=t.x,this.y/=t.y,this},_unit(){return this._div(this.mag()),this},_perp(){const t=this.y;return this.y=this.x,this.x=-t,this},_rotate(t){const e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround(t,e){const r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:r},r.convert=function(t){if(t instanceof r)return t;if(Array.isArray(t))return new r(+t[0],+t[1]);if(void 0!==t.x&&void 0!==t.y)return new r(+t.x,+t.y);throw new Error("Expected [x, y] or {x, y} point format")};var a=function(){if(s)return i;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return s=1,i=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},i}(),o=n(a);let l,u;function c(){return null==l&&(l="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),l}function h(){if(null==u&&(u=!1,c())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:!0});if(e){for(let r=0;r4&&void 0!==arguments[4]?arguments[4]:"zyx",s=Math.PI/360;e*=s,n*=s,r*=s;var a=Math.sin(e),o=Math.cos(e),l=Math.sin(r),u=Math.cos(r),c=Math.sin(n),h=Math.cos(n);switch(i){case "xyz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "xzy":t[0]=a*u*h-o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h+a*l*c;break;case "yxz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;case "yzx":t[0]=a*u*h+o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h-a*l*c;break;case "zxy":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "zyx":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;default:throw new Error("Unknown angle order "+i)}return t}function I(){var t=new f(2);return f!=Float32Array&&(t[0]=0,t[1]=0),t}function z(t,e){var r=new f(2);return r[0]=t,r[1]=e,r}m(),_=new f(4),f!=Float32Array&&(_[0]=0,_[1]=0,_[2]=0,_[3]=0),m(),x(1,0,0),x(0,1,0),k(),k(),d(),I();const P=8192;function C(t,e,r){return e*(P/(t.tileSize*Math.pow(2,r-t.tileID.overscaledZ)))}function E(t,e){return (t%e+e)%e}function T(t,e,r){return t*(1-r)+e*r}function B(t){if(t<=0)return 0;if(t>=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function V(t,e,r,n){const i=new o(t,e,r,n);return t=>i.solve(t)}const F=V(.25,.1,.25,1);function $(t,e,r){return Math.min(r,Math.max(e,t))}function D(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function L(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let O=1;function R(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function U(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}function j(t){return Array.isArray(t)?t.map(j):"object"==typeof t&&t?R(t,j):t}const N={};function q(t){N[t]||("undefined"!=typeof console&&console.warn(t),N[t]=!0);}function G(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function X(t){return "undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}let Z=null;function Y(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const H="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function K(t,r,n,i,s){return e(this,void 0,void 0,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const e=new VideoFrame(t,{timestamp:0});try{const a=null==e?void 0:e.format;if(!a||!a.startsWith("BGR")&&!a.startsWith("RGB"))throw new Error(`Unrecognized format ${a}`);const o=a.startsWith("BGR"),l=new Uint8ClampedArray(i*s*4);if(yield e.copyTo(l,function(t,e,r,n,i){const s=4*Math.max(-e,0),a=(Math.max(0,r)-r)*n*4+s,o=4*n,l=Math.max(0,e),u=Math.max(0,r);return {rect:{x:l,y:u,width:Math.min(t.width,e+n)-l,height:Math.min(t.height,r+i)-u},layout:[{offset:a,stride:o}]}}(t,r,n,i,s)),o)for(let t=0;t{t.removeEventListener(e,r,n);}}}function tt(t){return t*Math.PI/180}function et(t){return t/Math.PI*180}const rt={touchstart:!0,touchmove:!0,touchmoveWindow:!0,touchend:!0,touchcancel:!0},nt={dblclick:!0,click:!0,mouseover:!0,mouseout:!0,mousedown:!0,mousemove:!0,mousemoveWindow:!0,mouseup:!0,mouseupWindow:!0,contextmenu:!0,wheel:!0},it="AbortError";function st(){return new Error(it)}const at={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function ot(t){return at.REGISTERED_PROTOCOLS[t.substring(0,t.indexOf("://"))]}const lt="global-dispatcher";class ut extends Error{constructor(t,e,r,n){super(`AJAXError: ${e} (${t}): ${r}`),this.status=t,this.statusText=e,this.url=r,this.body=n;}}const ct=()=>X(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,ht=function(t,r){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const e=ot(t.url);if(e)return e(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:lt},r)}if(!(/^file:/.test(n=t.url)||/^file:/.test(ct())&&!/^\w+:/.test(n))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,r){return e(this,void 0,void 0,(function*(){const e=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:ct(),signal:r.signal});let n,i;"json"!==t.type||e.headers.has("Accept")||e.headers.set("Accept","application/json");try{n=yield fetch(e);}catch(e){throw new ut(0,e.message,t.url,new Blob)}if(!n.ok){const e=yield n.blob();throw new ut(n.status,n.statusText,t.url,e)}i="arrayBuffer"===t.type||"image"===t.type?n.arrayBuffer():"json"===t.type?n.json():n.text();const s=yield i;if(r.signal.aborted)throw st();return {data:s,cacheControl:n.headers.get("Cache-Control"),expires:n.headers.get("Expires")}}))}(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:!0,targetMapId:lt},r)}var n;return function(t,e){return new Promise(((r,n)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,!0),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||void 0===i?void 0:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{n(new Error(s.statusText));},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response);}catch(t){return void n(t)}r({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires")});}else {const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});n(new ut(s.status,s.statusText,t.url,e));}},e.signal.addEventListener("abort",(()=>{s.abort(),n(st());})),s.send(t.body);}))}(t,r)};function pt(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return !0;const e=new URL(t),r=window.location;return e.protocol===r.protocol&&e.host===r.host}function ft(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function dt(t,e,r){if(r&&r[t]){const n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}class yt{constructor(t,e={}){L(this,e),this.type=t;}}class mt extends yt{constructor(t,e={}){super("error",L({error:t},e));}}class gt{on(t,e){return this._listeners=this._listeners||{},ft(t,e,this._listeners),{unsubscribe:()=>{this.off(t,e);}}}off(t,e){return dt(t,e,this._listeners),dt(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},ft(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new yt(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)dt(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(L(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof mt&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var xt={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},state:{type:"state",default:{}},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},"font-faces":{type:"array",value:"fontFaces"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},"color-relief":{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_color-relief","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const vt=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function bt(t,e){const r={};for(const e in t)"ref"!==e&&(r[e]=t[e]);return vt.forEach((t=>{t in e&&(r[t]=e[t]);})),r}function wt(t,e){if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return !1;for(let r=0;r`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const Jt=[Vt,Ft,$t,Dt,Lt,Ot,Nt,Rt,Ht(Ut),qt,Xt,Gt,Zt,Yt];function Wt(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Wt(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of Jt)if(!Wt(t,e))return null}return `Expected ${Kt(t)} but found ${Kt(e)} instead.`}function Qt(t,e){return e.some((e=>e.kind===t.kind))}function te(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function ee(t,e){return "array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const re=.96422,ne=.82521,ie=4/29,se=6/29,ae=3*se*se,oe=se*se*se,le=Math.PI/180,ue=180/Math.PI;function ce(t){return (t%=360)<0&&(t+=360),t}function he([t,e,r,n]){let i,s;const a=fe((.2225045*(t=pe(t))+.7168786*(e=pe(e))+.0606169*(r=pe(r)))/1);t===e&&e===r?i=s=a:(i=fe((.4360747*t+.3850649*e+.1430804*r)/re),s=fe((.0139322*t+.0971045*e+.7141733*r)/ne));const o=116*a-16;return [o<0?0:o,500*(i-a),200*(a-s),n]}function pe(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function fe(t){return t>oe?Math.pow(t,1/3):t/ae+ie}function de([t,e,r,n]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,a=isNaN(r)?i:i-r/200;return i=1*me(i),s=re*me(s),a=ne*me(a),[ye(3.1338561*s-1.6168667*i-.4906146*a),ye(-.9787684*s+1.9161415*i+.033454*a),ye(.0719453*s-.2289914*i+1.4052427*a),n]}function ye(t){return (t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function me(t){return t>se?t*t*t:ae*(t-ie)}const ge=Object.hasOwn||function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};function xe(t,e){return ge(t,e)?t[e]:void 0}function ve(t){return parseInt(t.padEnd(2,t),16)/255}function be(t,e){return we(e?t/100:t,0,1)}function we(t,e,r){return Math.min(Math.max(e,t),r)}function _e(t){return !t.some(Number.isNaN)}const Se={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function Ae(t,e,r){return t+r*(e-t)}function ke(t,e,r){return t.map(((t,n)=>Ae(t,e[n],r)))}class Me{constructor(t,e,r,n=1,i=!0){this.r=t,this.g=e,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[t,e,r,n]));}static parse(t){if(t instanceof Me)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return [0,0,0,0];const e=xe(Se,t);if(e){const[t,r,n]=e;return [t/255,r/255,n/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let r=1;return [ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,r,n,i,s,a,o,l,u,c,h,p]=e,f=[i||" ",o||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[n,a,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[we(+r/e,0,1),we(+s/e,0,1),we(+l/e,0,1),h?be(+h,p):1];if(_e(t))return t}}return}}const r=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[t,e,n,i,s,a,o,l,u]=r,c=[n||" ",s||" ",o].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,we(+i,0,100),we(+a,0,100),l?be(+l,u):1];if(_e(t))return function([t,e,r,n]){function i(n){const i=(n+t/30)%12,s=e*Math.min(r,1-r);return r-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=ce(t),e/=100,r/=100,[i(0),i(8),i(4),n]}(t)}}}(t);return e?new Me(...e,!1):void 0}get rgb(){const{r:t,g:e,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[t/i,e/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,r,n,i]=he(t),s=Math.sqrt(r*r+n*n);return [Math.round(1e4*s)?ce(Math.atan2(n,r)*ue):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",he(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,r,n]=this.rgb;return `rgba(${[t,e,r].map((t=>Math.round(255*t))).join(",")},${n})`}static interpolate(t,e,r,n="rgb"){switch(n){case "rgb":{const[n,i,s,a]=ke(t.rgb,e.rgb,r);return new Me(n,i,s,a,!1)}case "hcl":{const[n,i,s,a]=t.hcl,[o,l,u,c]=e.hcl;let h,p;if(isNaN(n)||isNaN(o))isNaN(n)?isNaN(o)?h=NaN:(h=o,1!==s&&0!==s||(p=l)):(h=n,1!==u&&0!==u||(p=i));else {let t=o-n;o>n&&t>180?t-=360:o180&&(t+=360),h=n+r*t;}const[f,d,y,m]=function([t,e,r,n]){return t=isNaN(t)?0:t*le,de([r,Math.cos(t)*e,Math.sin(t)*e,n])}([h,null!=p?p:Ae(i,l,r),Ae(s,u,r),Ae(a,c,r)]);return new Me(f,d,y,m,!1)}case "lab":{const[n,i,s,a]=de(ke(t.lab,e.lab,r));return new Me(n,i,s,a,!1)}}}}Me.black=new Me(0,0,0,1),Me.white=new Me(1,1,1,1),Me.transparent=new Me(0,0,0,0),Me.red=new Me(1,0,0,1);class Ie{constructor(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const ze=["bottom","center","top"];class Pe{constructor(t,e,r,n,i,s){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i,this.verticalAlign=s;}}class Ce{constructor(t){this.sections=t;}static fromString(t){return new Ce([new Pe(t,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof Ce?t:Ce.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class Ee{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Ee)return t;if("number"==typeof t)return new Ee([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]];}return new Ee(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Ee(ke(t.values,e.values,r))}}class Te{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Te)return t;if("number"==typeof t)return new Te([t]);if(Array.isArray(t)){for(const e of t)if("number"!=typeof e)return;return new Te(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Te(ke(t.values,e.values,r))}}class Be{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Be)return t;if("string"==typeof t){const e=Me.parse(t);if(!e)return;return new Be([e])}if(!Array.isArray(t))return;const e=[];for(const r of t){if("string"!=typeof r)return;const t=Me.parse(r);if(!t)return;e.push(t);}return new Be(e)}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r,n="rgb"){const i=[];if(t.values.length!=e.values.length)throw new Error(`colorArray: Arrays have mismatched length (${t.values.length} vs. ${e.values.length}), cannot interpolate.`);for(let s=0;s=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Re(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof Le||t instanceof Me||t instanceof Ie||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De)return !0;if(Array.isArray(t)){for(const e of t)if(!Re(e))return !1;return !0}if("object"==typeof t){for(const e in t)if(!Re(t[e]))return !1;return !0}return !1}function Ue(t){if(null===t)return Vt;if("string"==typeof t)return $t;if("boolean"==typeof t)return Dt;if("number"==typeof t)return Ft;if(t instanceof Me)return Lt;if(t instanceof Le)return Ot;if(t instanceof Ie)return jt;if(t instanceof Ce)return Nt;if(t instanceof Ee)return qt;if(t instanceof Te)return Xt;if(t instanceof Be)return Gt;if(t instanceof $e)return Yt;if(t instanceof De)return Zt;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=Ue(e);if(r){if(r===t)continue;r=Ut;break}r=t;}return Ht(r||Ut,e)}return Rt}function je(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof Me||t instanceof Le||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De?t.toString():JSON.stringify(t)}class Ne{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Re(t[1]))return e.error("invalid value");const r=t[1];let n=Ue(r);const i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new Ne(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return !0}}const qe={string:$t,number:Ft,boolean:Dt,object:Rt};class Ge{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r,n=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const r=t[1];if("string"!=typeof r||!(r in qe)||"object"===r)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=qe[r],n++;}else i=Ut;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],n++;}r=Ht(i,s);}else {if(!qe[i])throw new Error(`Types doesn't contain name = ${i}`);r=qe[i];}const s=[];for(;nt.outputDefined()))}}const Xe={"to-boolean":Dt,"to-color":Lt,"to-number":Ft,"to-string":$t};class Ze{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[0];if(!Xe[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");const n=Xe[r],i=[];for(let r=1;r4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:Oe(e[0],e[1],e[2],e[3]),!r))return new Me(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new Ve(r||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "padding":{let e;for(const r of this.args){e=r.evaluate(t);const n=Ee.parse(e);if(n)return n}throw new Ve(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "numberArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Te.parse(e);if(n)return n}throw new Ve(`Could not parse numberArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "colorArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Be.parse(e);if(n)return n}throw new Ve(`Could not parse colorArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "variableAnchorOffsetCollection":{let e;for(const r of this.args){e=r.evaluate(t);const n=$e.parse(e);if(n)return n}throw new Ve(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "number":{let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new Ve(`Could not convert ${JSON.stringify(e)} to number.`)}case "formatted":return Ce.fromString(je(this.args[0].evaluate(t)));case "resolvedImage":return De.fromString(je(this.args[0].evaluate(t)));case "projectionDefinition":return this.args[0].evaluate(t);default:return je(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}const Ye=["Unknown","Point","LineString","Polygon"];class He{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null;}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?Ye[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache.get(t);return e||(e=Me.parse(t),this._parseColorCache.set(t,e)),e}}class Ke{constructor(t,e,r=[],n,i=new Bt,s=[]){this.registry=t,this.path=r,this.key=r.map((t=>`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=n,this._isConstant=e;}parse(t,e,r,n,i={}){return e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return "assert"===r?new Ge(e,[t]):"coerce"===r?new Ze(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const n=t[0];if("string"!=typeof n)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[n];if(i){let n=i.parse(t,this);if(!n)return null;if(this.expectedType){const t=this.expectedType,i=n.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind){if("projectionDefinition"===t.kind&&["string","array"].includes(i.kind)||["color","formatted","resolvedImage"].includes(t.kind)&&["value","string"].includes(i.kind)||["padding","numberArray"].includes(t.kind)&&["value","number","array"].includes(i.kind)||"colorArray"===t.kind&&["value","string","array"].includes(i.kind)||"variableAnchorOffsetCollection"===t.kind&&["value","array"].includes(i.kind))n=r(n,t,e.typeAnnotation||"coerce");else if(this.checkSubtype(t,i))return null}else n=r(n,t,e.typeAnnotation||"assert");}if(!(n instanceof Ne)&&"resolvedImage"!==n.type.kind&&this._isConstant(n)){const t=new He;try{n=new Ne(n.type,n.evaluate(t));}catch(t){return this.error(t.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Ke(this.registry,this._isConstant,n,e||null,i,this.errors)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new Tt(r,t));}checkSubtype(t,e){const r=Wt(t,e);return r&&this.error(r),r}}class Je{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new Ve(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new Ve(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return !1}}class tr{constructor(t,e){this.type=Dt,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);return r&&n?Qt(r.type,[Dt,$t,Ft,Vt,Ut])?new tr(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);if(!te(r,["string","array"]))throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return !0}}class er{constructor(t,e,r){this.type=Ft,this.needle=t,this.haystack=e,this.fromIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);if(!r||!n)return null;if(!Qt(r.type,[Dt,$t,Ft,Vt,Ut]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new er(r,n,i):null}return new er(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(t)),te(r,["string"])){const t=r.indexOf(e,n);return -1===t?-1:[...r.slice(0,t)].length}if(te(r,["array"]))return r.indexOf(e,n);throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return !1}}class rr{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(r){if(u.checkSubtype(r,Ue(t)))return null}else r=Ue(t);if(void 0!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length;}const c=e.parse(l,a,n);if(!c)return null;n=n||c.type,s.push(c);}const a=e.parse(t[1],1,Ut);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,n);return o?"value"!==a.type.kind&&e.concat(1).checkSubtype(r,a.type)?null:new rr(r,n,a,i,s,o):null}evaluate(t){const e=this.input.evaluate(t);return (Ue(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class nr{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class ir{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ft);if(!r||!n)return null;if(!Qt(r.type,[Ht(Ut),$t,Ut]))return e.error(`Expected first argument to be of type array or string, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new ir(r.type,r,n,i):null}return new ir(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);let n;if(this.endIndex&&(n=this.endIndex.evaluate(t)),te(e,["string"]))return [...e].slice(r,n).join("");if(te(e,["array"]))return e.slice(r,n);throw new Ve(`Expected first argument to be of type array or string, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return !1}}function sr(t,e){const r=t.length-1;let n,i,s=0,a=r,o=0;for(;s<=a;)if(o=Math.floor((s+a)/2),n=t[o],i=t[o+1],n<=e){if(o===r||ee))throw new Ve("Input is not a number.");a=o-1;}return 0}class ar{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',o);const u=e.parse(a,l,i);if(!u)return null;i=i||u.type,n.push([s,u]);}return new ar(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[sr(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function or(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var lr,ur,cr=function(){if(ur)return lr;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return ur=1,lr=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},lr}(),hr=or(cr);class pr{constructor(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e);}static interpolationFactor(t,e,r,n){let i=0;if("exponential"===t.name)i=fr(e,t.base,r,n);else if("linear"===t.name)i=fr(e,1,r,n);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new hr(s[0],s[1],s[2],s[3]).solve(fr(e,1,r,n));}return i}static parse(t,e){let[r,n,i,...s]=t;if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){const t=n[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:t};}else {if("cubic-bezier"!==n[0])return e.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const t=n.slice(1);if(4!==t.length||t.some((t=>"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,Ft),!i)return null;const a=[];let o=null;"interpolate-hcl"!==r&&"interpolate-lab"!==r||e.expectedType==Gt?e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType):o=Lt;for(let t=0;t=r)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,o);if(!u)return null;o=o||u.type,a.push([r,u]);}return ee(o,Ft)||ee(o,Ot)||ee(o,Lt)||ee(o,qt)||ee(o,Xt)||ee(o,Gt)||ee(o,Yt)||ee(o,Ht(Ft))?new pr(o,r,n,i,a):e.error(`Type ${Kt(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=sr(e,n),a=pr.interpolationFactor(this.interpolation,n,e[s],e[s+1]),o=r[s].evaluate(t),l=r[s+1].evaluate(t);switch(this.operator){case "interpolate":switch(this.type.kind){case "number":return Ae(o,l,a);case "color":return Me.interpolate(o,l,a);case "padding":return Ee.interpolate(o,l,a);case "colorArray":return Be.interpolate(o,l,a);case "numberArray":return Te.interpolate(o,l,a);case "variableAnchorOffsetCollection":return $e.interpolate(o,l,a);case "array":return ke(o,l,a);case "projectionDefinition":return Le.interpolate(o,l,a)}case "interpolate-hcl":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"hcl");case "colorArray":return Be.interpolate(o,l,a,"hcl")}case "interpolate-lab":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"lab");case "colorArray":return Be.interpolate(o,l,a,"lab")}}}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function fr(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}const dr={color:Me.interpolate,number:Ae,padding:Ee.interpolate,numberArray:Te.interpolate,colorArray:Be.interpolate,variableAnchorOffsetCollection:$e.interpolate,array:ke};class yr{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r=null;const n=e.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const n of t.slice(1)){const t=e.parse(n,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!t)return null;r=r||t.type,i.push(t);}if(!r)throw new Error("No output type");const s=n&&i.some((t=>Wt(n,t.type)));return new yr(s?Ut:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(t),r&&r instanceof De&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break;return r}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function mr(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function gr(t,e,r,n){return 0===n.compare(e,r)}function xr(t,e,r){const n="=="!==t&&"!="!==t;return class i{constructor(t,e,r){this.type=Dt,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const r=t[0];let s=e.parse(t[1],1,Ut);if(!s)return null;if(!mr(r,s.type))return e.concat(1).error(`"${r}" comparisons are not supported for type '${Kt(s.type)}'.`);let a=e.parse(t[2],2,Ut);if(!a)return null;if(!mr(r,a.type))return e.concat(2).error(`"${r}" comparisons are not supported for type '${Kt(a.type)}'.`);if(s.type.kind!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error(`Cannot compare types '${Kt(s.type)}' and '${Kt(a.type)}'.`);n&&("value"===s.type.kind&&"value"!==a.type.kind?s=new Ge(a.type,[s]):"value"!==s.type.kind&&"value"===a.type.kind&&(a=new Ge(s.type,[a])));let o=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error("Cannot use collator to compare non-string types.");if(o=e.parse(t[3],3,jt),!o)return null}return new i(s,a,o)}evaluate(i){const s=this.lhs.evaluate(i),a=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=Ue(s),r=Ue(a);if(e.kind!==r.kind||"string"!==e.kind&&"number"!==e.kind)throw new Ve(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=Ue(s),r=Ue(a);if("string"!==t.kind||"string"!==r.kind)return e(i,s,a)}return this.collator?r(i,s,a,this.collator.evaluate(i)):e(i,s,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return !0}}}const vr=xr("==",(function(t,e,r){return e===r}),gr),br=xr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !gr(0,e,r,n)})),wr=xr("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),Sr=xr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),Ar=xr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class kr{constructor(t,e,r){this.type=jt,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");const n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,Dt);if(!n)return null;const i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Dt);if(!i)return null;let s=null;return r.locale&&(s=e.parse(r.locale,1,$t),!s)?null:new kr(n,i,s)}evaluate(t){return new Ie(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);}outputDefined(){return !1}}class Mr{constructor(t,e,r,n,i){this.type=$t,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=e.parse(n.locale,1,$t),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,$t),!s))return null;let a=null;if(n["min-fraction-digits"]&&(a=e.parse(n["min-fraction-digits"],1,Ft),!a))return null;let o=null;return n["max-fraction-digits"]&&(o=e.parse(n["max-fraction-digits"],1,Ft),!o)?null:new Mr(r,i,s,a,o)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return !1}}class Ir{constructor(t){this.type=Nt,this.sections=t;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");const n=[];let i=!1;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&"object"==typeof s&&!Array.isArray(s)){i=!1;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,Ft),!t))return null;let r=null;if(s["text-font"]&&(r=e.parse(s["text-font"],1,Ht($t)),!r))return null;let a=null;if(s["text-color"]&&(a=e.parse(s["text-color"],1,Lt),!a))return null;let o=null;if(s["vertical-align"]){if("string"==typeof s["vertical-align"]&&!ze.includes(s["vertical-align"]))return e.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${s["vertical-align"]}' instead.`);if(o=e.parse(s["vertical-align"],1,$t),!o)return null}const l=n[n.length-1];l.scale=t,l.font=r,l.textColor=a,l.verticalAlign=o;}else {const s=e.parse(t[r],1,Ut);if(!s)return null;const a=s.type.kind;if("string"!==a&&"value"!==a&&"null"!==a&&"resolvedImage"!==a)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:s,scale:null,font:null,textColor:null,verticalAlign:null});}}return new Ir(n)}evaluate(t){return new Ce(this.sections.map((e=>{const r=e.content.evaluate(t);return Ue(r)===Zt?new Pe("",r,null,null,null,e.verticalAlign?e.verticalAlign.evaluate(t):null):new Pe(je(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null,e.verticalAlign?e.verticalAlign.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor),e.verticalAlign&&t(e.verticalAlign);}outputDefined(){return !1}}class zr{constructor(t){this.type=Zt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,$t);return r?new zr(r):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),r=De.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r}eachChild(t){t(this.input);}outputDefined(){return !1}}class Pr{constructor(t){this.type=Ft,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${Kt(r.type)} instead.`):new Pr(r):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return [...e].length;if(Array.isArray(e))return e.length;throw new Ve(`Expected value to be of type string or array, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return !1}}const Cr=8192;function Er(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*Cr),Math.round(n*i*Cr)]}function Tr(t,e){const r=Math.pow(2,e.z);return [(i=(t[0]/Cr+e.x)/r,360*i-180),(n=(t[1]/Cr+e.y)/r,360/Math.PI*Math.atan(Math.exp((180-360*n)*Math.PI/180))-90)];var n,i;}function Br(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function Vr(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function Fr(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],a=t[1]-r[1];return n*a-s*i==0&&n*s<=0&&i*a<=0}function $r(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!jr(t,e,r,n)||!jr(r,n,t,e));var i,s;}function Dr(t,e,r){for(const n of r)for(let r=0;r(i=t)[1]!=(a=o[e+1])[1]>i[1]&&i[0]<(a[0]-s[0])*(i[1]-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}var i,s,a;return n}function Or(t,e){for(const r of e)if(Lr(t,r))return !0;return !1}function Rr(t,e){for(const r of t)if(!Lr(r,e))return !1;for(let r=0;r0&&o<0||a<0&&o>0}function Nr(t,e,r){const n=[];for(let i=0;ir[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i;}Br(e,t);}function Xr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];Gr(n,e,r,i),a.push(n);}return a}function Zr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];Br(e,r),t.push(r);}a.push(t);}if(e[2]-e[0]<=i/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const n of t)Gr(n,e,r,i);}var o;return a}class Yr{constructor(t,e){this.type=Dt,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const r of e.features){const{type:e,coordinates:n}=r.geometry;"Polygon"===e&&t.push(n),"MultiPolygon"===e&&t.push(...n);}if(t.length)return new Yr(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new Yr(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new Yr(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Lr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Or(t,s))return !1}return !0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Rr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Ur(t,s))return !1}return !0}(t,this.geometries)}return !1}eachChild(){}outputDefined(){return !0}}let Hr=class{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}};function Kr(t,e,r=0,n=t.length-1,i=Wr){for(;n>r;){if(n-r>600){const s=n-r+1,a=e-r+1,o=Math.log(s),l=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*l*(s-l)/s)*(a-s/2<0?-1:1);Kr(t,e,Math.max(r,Math.floor(e-a*l/s+u)),Math.min(n,Math.floor(e+(s-a)*l/s+u)),i);}const s=t[e];let a=r,o=n;for(Jr(t,r,e),i(t[n],s)>0&&Jr(t,r,n);a0;)o--;}0===i(t[r],s)?Jr(t,r,o):(o++,Jr(t,o,n)),o<=e&&(r=o+1),e<=o&&(n=o-1);}}function Jr(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function Wr(t,e){return te?1:0}function Qr(t,e){if(t.length<=1)return [t];const r=[];let n,i;for(const e of t){const t=en(e);0!==t&&(e.area=Math.abs(t),void 0===i&&(i=t<0),i===t<0?(n&&r.push(n),n=[e]):n.push(e));}if(n&&r.push(n),e>1)for(let t=0;t1?(l=t[o+1][0],u=t[o+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function on(t,e){return e[0]-t[0]}function ln(t){return t[1]-t[0]+1}function un(t,e){return t[1]>=t[0]&&t[1]t[1])return [null,null];const r=ln(t);if(e){if(2===r)return [t,null];const e=Math.floor(r/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===r)return [t,null];const n=Math.floor(r/2)-1;return [[t[0],t[0]+n],[t[0]+n+1,t[1]]]}function hn(t,e){if(!un(e,t.length))return [1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=e[0];n<=e[1];++n)Br(r,t[n]);return r}function pn(t){const e=[1/0,1/0,-1/0,-1/0];for(const r of t)for(const t of r)Br(e,t);return e}function fn(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function dn(t,e,r){if(!fn(t)||!fn(e))return NaN;let n=0,i=0;return t[2]e[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if(Vr(i,s)){if(wn(t,e))return 0}else if(wn(e,t))return 0;let a=1/0;for(const n of t)for(let t=0,i=n.length,s=i-1;t0;){const i=a.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(ln(l)<=u){if(!un(l,t.length))return NaN;if(e){const e=bn(t,l,r,n);if(isNaN(e)||0===e)return e;s=Math.min(s,e);}else for(let e=l[0];e<=l[1];++e){const i=vn(t[e],r,n);if(s=Math.min(s,i),0===s)return 0}}else {const r=cn(l,e);Sn(a,s,n,t,o,r[0]),Sn(a,s,n,t,o,r[1]);}}return s}function Mn(t,e,r,n,i,s=1/0){let a=Math.min(s,i.distance(t[0],r[0]));if(0===a)return a;const o=new Hr([[0,[0,t.length-1],[0,r.length-1]]],on);for(;o.length>0;){const s=o.pop();if(s[0]>=a)continue;const l=s[1],u=s[2],c=e?50:100,h=n?50:100;if(ln(l)<=c&&ln(u)<=h){if(!un(l,t.length)&&un(u,r.length))return NaN;let s;if(e&&n)s=gn(t,l,r,u,i),a=Math.min(a,s);else if(e&&!n){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=yn(r[t],e,i),a=Math.min(a,s),0===a)return a}else if(!e&&n){const e=r.slice(u[0],u[1]+1);for(let r=l[0];r<=l[1];++r)if(s=yn(t[r],e,i),a=Math.min(a,s),0===a)return a}else s=xn(t,l,r,u,i),a=Math.min(a,s);}else {const s=cn(l,e),c=cn(u,n);An(o,a,i,t,r,s[0],c[0]),An(o,a,i,t,r,s[0],c[1]),An(o,a,i,t,r,s[1],c[0]),An(o,a,i,t,r,s[1],c[1]);}}return a}function In(t){return "MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class zn{constructor(t,e){this.type=Ft,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new zn(e,e.features.map((t=>In(t.geometry))).flat());if("Feature"===e.type)return new zn(e,In(e.geometry));if("type"in e&&"coordinates"in e)return new zn(e,In(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!1,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!1,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!1,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!0,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!0,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!0,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const r=t.geometry();if(0===r.length||0===r[0].length)return NaN;const n=Qr(r,0).map((e=>e.map((e=>e.map((e=>Tr([e.x,e.y],t.canonical))))))),i=new an(n[0][0][0][1]);let s=1/0;for(const t of e)for(const e of n){switch(t.type){case "Point":s=Math.min(s,kn([t.coordinates],!1,e,i,s));break;case "LineString":s=Math.min(s,kn(t.coordinates,!0,e,i,s));break;case "Polygon":s=Math.min(s,_n(e,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return !0}}class Pn{constructor(t){this.type=Ut,this.key=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=t[1];return null==r?e.error("Global state property must be defined."):"string"!=typeof r?e.error(`Global state property must be string, but found ${typeof t[1]} instead.`):new Pn(r)}evaluate(t){var e;const r=null===(e=t.globals)||void 0===e?void 0:e.globalState;return r&&0!==Object.keys(r).length?xe(r,this.key):null}eachChild(){}outputDefined(){return !1}}const Cn={"==":vr,"!=":br,">":_r,"<":wr,">=":Ar,"<=":Sr,array:Ge,at:Qe,boolean:Ge,case:nr,coalesce:yr,collator:kr,format:Ir,image:zr,in:tr,"index-of":er,interpolate:pr,"interpolate-hcl":pr,"interpolate-lab":pr,length:Pr,let:Je,literal:Ne,match:rr,number:Ge,"number-format":Mr,object:Ge,slice:ir,step:ar,string:Ge,"to-boolean":Ze,"to-color":Ze,"to-number":Ze,"to-string":Ze,var:We,within:Yr,distance:zn,"global-state":Pn};class En{constructor(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return !1}static parse(t,e){const r=t[0],n=En.definitions[r];if(!n)return e.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let o=null;for(const[n,s]of a){o=new Ke(e.registry,$n,e.path,null,e.scope);const a=[];let l=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(Kt).join(", ")})`:`(${Kt(e.type)}...)`;var e;})).join(" | "),n=[];for(let r=1;r{r=e?r&&$n(t):r&&t instanceof Ne;})),!!r&&Dn(t)&&On(t,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function Dn(t){if(t instanceof En){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}if(t instanceof Yr)return !1;if(t instanceof zn)return !1;let e=!0;return t.eachChild((t=>{e&&!Dn(t)&&(e=!1);})),e}function Ln(t){if(t instanceof En&&"feature-state"===t.name)return !1;let e=!0;return t.eachChild((t=>{e&&!Ln(t)&&(e=!1);})),e}function On(t,e){if(t instanceof En&&e.indexOf(t.name)>=0)return !1;let r=!0;return t.eachChild((t=>{r&&!On(t,e)&&(r=!1);})),r}function Rn(t){return {result:"success",value:t}}function Un(t){return {result:"error",value:t}}function jn(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Nn(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function qn(t){return !!t.expression&&t.expression.interpolated}function Gn(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Xn(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)&&Ue(t)===Rt}function Zn(t){return t}function Yn(t,e){const r=t.stops&&"object"==typeof t.stops[0][0],n=r||!(r||void 0!==t.property),i=t.type||(qn(e)?"exponential":"interval"),s=function(t){switch(t.type){case "color":return Me.parse;case "padding":return Ee.parse;case "numberArray":return Te.parse;case "colorArray":return Be.parse;default:return null}}(e);if(s&&((t=Et({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],s(t[1])]))),t.default=s(t.default?t.default:e.default)),t.colorSpace&&"rgb"!==(a=t.colorSpace)&&"hcl"!==a&&"lab"!==a)throw new Error(`Unknown color space: "${t.colorSpace}"`);var a;const o=function(t){switch(t){case "exponential":return Wn;case "interval":return Jn;case "categorical":return Kn;case "identity":return Qn;default:throw new Error(`Unknown function type "${t}"`)}}(i);let l,u;if("categorical"===i){l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0];}if(r){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>Wn({stops:i,base:t.base},e,r).evaluate(r,n)}}if(n){const r="exponential"===i?{name:"exponential",base:void 0!==t.base?t.base:1}:null;return {kind:"camera",interpolationType:r,interpolationFactor:pr.interpolationFactor.bind(void 0,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>o(t,e,r,l,u)}}return {kind:"source",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:void 0;return void 0===i?Hn(t.default,e.default):o(t,e,i,l,u)}}}function Hn(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Kn(t,e,r,n,i){return Hn(typeof r===i?n[r]:void 0,t.default,e.default)}function Jn(t,e,r){if("number"!==Gn(r))return Hn(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=sr(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function Wn(t,e,r){const n=void 0!==t.base?t.base:1;if("number"!==Gn(r))return Hn(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=sr(t.stops.map((t=>t[0])),r),a=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),o=t.stops[s][1],l=t.stops[s+1][1],u=dr[e.type]||Zn;return "function"==typeof o.evaluate?{evaluate(...e){const r=o.evaluate.apply(void 0,e),n=l.evaluate.apply(void 0,e);if(void 0!==r&&void 0!==n)return u(r,n,a,t.colorSpace)}}:u(o,l,a,t.colorSpace)}function Qn(t,e,r){switch(e.type){case "color":r=Me.parse(r);break;case "formatted":r=Ce.fromString(r.toString());break;case "resolvedImage":r=De.fromString(r.toString());break;case "padding":r=Ee.parse(r);break;case "colorArray":r=Be.parse(r);break;case "numberArray":r=Te.parse(r);break;default:Gn(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0);}return Hn(r,t.default,e.default)}En.register(Cn,{error:[{kind:"error"},[$t],(t,[e])=>{throw new Ve(e.evaluate(t))}],typeof:[$t,[Ut],(t,[e])=>Kt(Ue(e.evaluate(t)))],"to-rgba":[Ht(Ft,4),[Lt],(t,[e])=>{const[r,n,i,s]=e.evaluate(t).rgb;return [255*r,255*n,255*i,s]}],rgb:[Lt,[Ft,Ft,Ft],Tn],rgba:[Lt,[Ft,Ft,Ft,Ft],Tn],has:{type:Dt,overloads:[[[$t],(t,[e])=>Bn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Bn(e.evaluate(t),r.evaluate(t))]]},get:{type:Ut,overloads:[[[$t],(t,[e])=>Vn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Vn(e.evaluate(t),r.evaluate(t))]]},"feature-state":[Ut,[$t],(t,[e])=>Vn(e.evaluate(t),t.featureState||{})],properties:[Rt,[],t=>t.properties()],"geometry-type":[$t,[],t=>t.geometryType()],id:[Ut,[],t=>t.id()],zoom:[Ft,[],t=>t.globals.zoom],"heatmap-density":[Ft,[],t=>t.globals.heatmapDensity||0],elevation:[Ft,[],t=>t.globals.elevation||0],"line-progress":[Ft,[],t=>t.globals.lineProgress||0],accumulated:[Ut,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[Ft,Fn(Ft),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],"*":[Ft,Fn(Ft),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],"-":{type:Ft,overloads:[[[Ft,Ft],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[Ft],(t,[e])=>-e.evaluate(t)]]},"/":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],"%":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[Ft,[],()=>Math.LN2],pi:[Ft,[],()=>Math.PI],e:[Ft,[],()=>Math.E],"^":[Ft,[Ft,Ft],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[Ft,[Ft],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))],log2:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[Ft,[Ft],(t,[e])=>Math.sin(e.evaluate(t))],cos:[Ft,[Ft],(t,[e])=>Math.cos(e.evaluate(t))],tan:[Ft,[Ft],(t,[e])=>Math.tan(e.evaluate(t))],asin:[Ft,[Ft],(t,[e])=>Math.asin(e.evaluate(t))],acos:[Ft,[Ft],(t,[e])=>Math.acos(e.evaluate(t))],atan:[Ft,[Ft],(t,[e])=>Math.atan(e.evaluate(t))],min:[Ft,Fn(Ft),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[Ft,Fn(Ft),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[Ft,[Ft],(t,[e])=>Math.abs(e.evaluate(t))],round:[Ft,[Ft],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[Ft,[Ft],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[Ft,[Ft],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[Dt,[$t,Ut],(t,[e,r])=>t.properties()[e.value]===r.value],"filter-id-==":[Dt,[Ut],(t,[e])=>t.id()===e.value],"filter-type-==":[Dt,[$t],(t,[e])=>t.geometryType()===e.value],"filter-<":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],"filter-<=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],"filter->=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],"filter-has":[Dt,[Ut],(t,[e])=>e.value in t.properties()],"filter-has-id":[Dt,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[Dt,[Ht($t)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[Dt,[Ht(Ut)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[Dt,[$t,Ht(Ut)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[Dt,[$t,Ht(Ut)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(!r.evaluate(t))return !1;return !0}]]},any:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(r.evaluate(t))return !0;return !1}]]},"!":[Dt,[Dt],(t,[e])=>!e.evaluate(t)],"is-supported-script":[Dt,[$t],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return !r||r(e.evaluate(t))}],upcase:[$t,[$t],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[$t,[$t],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[$t,Fn(Ut),(t,e)=>e.map((e=>je(e.evaluate(t)))).join("")],"resolved-locale":[$t,[jt],(t,[e])=>e.evaluate(t).resolvedLocale()]});class ti{constructor(t,e,r){this.expression=t,this._warningHistory={},this._evaluator=new He,this._defaultValue=e?function(t){if("color"===t.type&&Xn(t.default))return new Me(0,0,0,0);switch(t.type){case "color":return Me.parse(t.default)||null;case "padding":return Ee.parse(t.default)||null;case "numberArray":return Te.parse(t.default)||null;case "colorArray":return Be.parse(t.default)||null;case "variableAnchorOffsetCollection":return $e.parse(t.default)||null;case "projectionDefinition":return Le.parse(t.default)||null;default:return void 0===t.default?null:t.default}}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null,this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s){this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new Ve(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function ei(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Cn}function ri(t,e,r){const n=new Ke(Cn,$n,[],e?function(t){const e={color:Lt,string:$t,number:Ft,enum:$t,boolean:Dt,formatted:Nt,padding:qt,numberArray:Xt,colorArray:Gt,projectionDefinition:Ot,resolvedImage:Zt,variableAnchorOffsetCollection:Yt};return "array"===t.type?Ht(e[t.value]||Ut,t.length):e[t.type]}(e):void 0),i=n.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return i?Rn(new ti(i,e,r)):Un(n.errors)}class ni{constructor(t,e,r){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}}class ii{constructor(t,e,r,n,i){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this.interpolationType=n,this._globalState=i;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?pr.interpolationFactor(this.interpolationType,t,e,r):0}}function si(t,e,r){const n=ri(t,e,r);if("error"===n.result)return n;const i=n.value.expression,s=Dn(i);if(!s&&!jn(e))return Un([new Tt("","data expressions not supported")]);const a=On(i,["zoom"]);if(!a&&!Nn(e))return Un([new Tt("","zoom expressions not supported")]);const o=oi(i);return o||a?o instanceof Tt?Un([o]):o instanceof pr&&!qn(e)?Un([new Tt("",'"interpolate" expressions cannot be used with this property')]):Rn(o?new ii(s?"camera":"composite",n.value,o.labels,o instanceof pr?o.interpolation:void 0,r):new ni(s?"constant":"source",n.value,r)):Un([new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class ai{constructor(t,e){this._parameters=t,this._specification=e,Et(this,Yn(this._parameters,this._specification));}static deserialize(t){return new ai(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function oi(t){let e=null;if(t instanceof Je)e=oi(t.result);else if(t instanceof yr){for(const r of t.args)if(e=oi(r),e)break}else (t instanceof ar||t instanceof pr)&&t.input instanceof En&&"zoom"===t.input.name&&(e=t);return e instanceof Tt||t.eachChild((t=>{const r=oi(t);r instanceof Tt?e=r:!e&&r?e=new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&r&&e!==r&&(e=new Tt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),e}function li(t,e=new Set){return t instanceof Pn&&e.add(t.key),t.eachChild((t=>{li(t,e);})),e}function ui(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case "has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case "in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case "!in":case "!has":case "none":return !1;case "==":case "!=":case ">":case ">=":case "<":case "<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case "any":case "all":for(const e of t.slice(1))if(!ui(e)&&"boolean"!=typeof e)return !1;return !0;default:return !0}}const ci={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function hi(t,e){if(null==t)return {filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};ui(t)||(t=di(t));const r=ri(t,ci,e);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return {filter:(t,e,n)=>r.value.evaluate(t,e,{},n),needGeometry:fi(t),getGlobalStateRefs:()=>li(r.value.expression)}}function pi(t,e){return te?1:0}function fi(t){if(!Array.isArray(t))return !1;if("within"===t[0]||"distance"===t[0])return !0;for(let e=1;e"===e||"<="===e||">="===e?yi(t[1],t[2],e):"any"===e?(r=t.slice(1),["any"].concat(r.map(di))):"all"===e?["all"].concat(t.slice(1).map(di)):"none"===e?["all"].concat(t.slice(1).map(di).map(xi)):"in"===e?mi(t[1],t.slice(2)):"!in"===e?xi(mi(t[1],t.slice(2))):"has"===e?gi(t[1]):"!has"!==e||xi(gi(t[1]));var r;}function yi(t,e,r){switch(t){case "$type":return [`filter-type-${r}`,e];case "$id":return [`filter-id-${r}`,e];default:return [`filter-${r}`,t,e]}}function mi(t,e){if(0===e.length)return !1;switch(t){case "$type":return ["filter-type-in",["literal",e]];case "$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(pi)]]:["filter-in-small",t,["literal",e]]}}function gi(t){switch(t){case "$type":return !0;case "$id":return ["filter-has-id"];default:return ["filter-has",t]}}function xi(t){return ["!",t]}function vi(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const r of t)e+=`${vi(r)},`;return `${e}]`}const r=Object.keys(t).sort();let n="{";for(let e=0;en.maximum?[new Ct(e,r,`${r} is greater than the maximum value ${n.maximum}`)]:[]}function Ii(t){const e=t.valueSpec,r=_i(t.value.type);let n,i,s,a={};const o="categorical"!==r&&void 0===t.value.property,l=!o,u="array"===Gn(t.value.stops)&&"array"===Gn(t.value.stops[0])&&"object"===Gn(t.value.stops[0][0]),c=Ai({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===r)return [new Ct(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const n=t.value;return e=e.concat(ki({key:t.key,value:n,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===Gn(n)&&0===n.length&&e.push(new Ct(t.key,n,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===r&&o&&c.push(new Ct(t.key,t.value,'missing required property "property"')),"identity"===r||t.value.stops||c.push(new Ct(t.key,t.value,'missing required property "stops"')),"exponential"===r&&t.valueSpec.expression&&!qn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!jn(t.valueSpec)?c.push(new Ct(t.key,t.value,"property functions not supported")):o&&!Nn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"zoom functions not supported"))),"categorical"!==r&&!u||void 0!==t.value.property||c.push(new Ct(t.key,t.value,'"property" property is required')),c;function h(t){let r=[];const n=t.value,o=t.key;if("array"!==Gn(n))return [new Ct(o,n,`array expected, ${Gn(n)} found`)];if(2!==n.length)return [new Ct(o,n,`array length 2 expected, length ${n.length} found`)];if(u){if("object"!==Gn(n[0]))return [new Ct(o,n,`object expected, ${Gn(n[0])} found`)];if(void 0===n[0].zoom)return [new Ct(o,n,"object stop key must have zoom")];if(void 0===n[0].value)return [new Ct(o,n,"object stop key must have value")];if(s&&s>_i(n[0].zoom))return [new Ct(o,n[0].zoom,"stop zoom values must appear in ascending order")];_i(n[0].zoom)!==s&&(s=_i(n[0].zoom),i=void 0,a={}),r=r.concat(Ai({key:`${o}[0]`,value:n[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Mi,value:p}}));}else r=r.concat(p({key:`${o}[0]`,value:n[0],validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},n));return ei(Si(n[1]))?r.concat([new Ct(`${o}[1]`,n[1],"expressions are not allowed in function stops.")]):r.concat(t.validateSpec({key:`${o}[1]`,value:n[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const o=Gn(t.value),l=_i(t.value),u=null!==t.value?t.value:s;if(n){if(o!==n)return [new Ct(t.key,u,`${o} stop domain type must match previous stop domain type ${n}`)]}else n=o;if("number"!==o&&"string"!==o&&"boolean"!==o)return [new Ct(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==o&&"categorical"!==r){let n=`number expected, ${o} found`;return jn(e)&&void 0===r&&(n+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new Ct(t.key,u,n)]}return "categorical"!==r||"number"!==o||isFinite(l)&&Math.floor(l)===l?"categorical"!==r&&"number"===o&&void 0!==i&&lnew Ct(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new Ct(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!On(r,["zoom","feature-state"]))return [new Ct(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!Dn(r))return [new Ct(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function Pi(t){const e=t.key,r=t.value,n=Gn(r);return "string"!==n?[new Ct(e,r,`color expected, ${n} found`)]:Me.parse(String(r))?[]:[new Ct(e,r,`color expected, "${r}" found`)]}function Ci(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${n.values.join(", ")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${Object.keys(n.values).join(", ")}], ${JSON.stringify(r)} found`)),i}function Ei(t){return ui(Si(t.value))?zi(Et({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):Ti(t)}function Ti(t){const e=t.value,r=t.key;if("array"!==Gn(e))return [new Ct(r,e,`array expected, ${Gn(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return [new Ct(r,e,"filter array must have at least 1 element")];switch(s=s.concat(Ci({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),_i(e[0])){case "<":case "<=":case ">":case ">=":e.length>=2&&"$type"===_i(e[1])&&s.push(new Ct(r,e,`"$type" cannot be use with operator "${e[0]}"`));case "==":case "!=":3!==e.length&&s.push(new Ct(r,e,`filter array for operator "${e[0]}" must have 3 elements`));case "in":case "!in":e.length>=2&&(i=Gn(e[1]),"string"!==i&&s.push(new Ct(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let a=2;a{t in r&&e.push(new Ct(n,r[t],`"${t}" is prohibited for ref layers`));})),i.layers.forEach((e=>{_i(e.id)===o&&(t=e);})),t?t.ref?e.push(new Ct(n,r.ref,"ref cannot reference another ref layer")):a=_i(t.type):e.push(new Ct(n,r.ref,`ref layer "${o}" not found`));}else if("background"!==a)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&_i(t.type);t?"vector"===s&&"raster"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster source`)):"raster-dem"!==s&&"hillshade"===a||"raster-dem"!==s&&"color-relief"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster-dem source`)):"raster"===s&&"raster"!==a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a vector source`)):"vector"!==s||r["source-layer"]?"raster-dem"===s&&"hillshade"!==a&&"color-relief"!==a?e.push(new Ct(n,r.source,"raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.")):"line"!==a||!r.paint||!r.paint["line-gradient"]||"geojson"===s&&t.lineMetrics||e.push(new Ct(n,r,`layer "${r.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new Ct(n,r,`layer "${r.id}" must specify a "source-layer"`)):e.push(new Ct(n,r.source,`source "${r.source}" not found`));}else e.push(new Ct(n,r,'missing required property "source"'));return e=e.concat(Ai({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:r,objectKey:"type"}),filter:Ei,layout:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Fi(Et({layerType:a},t))}}),paint:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Vi(Et({layerType:a},t))}})}})),e}function Di(t){const e=t.value,r=t.key,n=Gn(e);return "string"!==n?[new Ct(r,e,`string expected, ${n} found`)]:[]}const Li={promoteId:function({key:t,value:e}){if("string"===Gn(e))return Di({key:t,value:e});{const r=[];for(const n in e)r.push(...Di({key:`${t}.${n}`,value:e[n]}));return r}}};function Oi(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return [new Ct(r,e,'"type" is required')];const a=_i(e.type);let o;switch(a){case "vector":case "raster":return o=Ai({key:r,value:e,valueSpec:n[`source_${a.replace("-","_")}`],style:t.style,styleSpec:n,objectElementValidators:Li,validateSpec:s}),o;case "raster-dem":return o=function(t){var e;const r=null!==(e=t.sourceName)&&void 0!==e?e:"",n=t.value,i=t.styleSpec,s=i.source_raster_dem,a=t.style;let o=[];const l=Gn(n);if(void 0===n)return o;if("object"!==l)return o.push(new Ct("source_raster_dem",n,`object expected, ${l} found`)),o;const u="custom"===_i(n.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in n)!u&&c.includes(e)?o.push(new Ct(e,n[e],`In "${r}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?o=o.concat(t.validateSpec({key:e,value:n[e],valueSpec:s[e],validateSpec:t.validateSpec,style:a,styleSpec:i})):o.push(new Ct(e,n[e],`unknown property "${e}"`));return o}({sourceName:r,value:e,style:t.style,styleSpec:n,validateSpec:s}),o;case "geojson":if(o=Ai({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,validateSpec:s,objectElementValidators:Li}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],s="string"==typeof n?[n,["accumulated"],["get",t]]:n;o.push(...zi({key:`${r}.${t}.map`,value:i,expressionContext:"cluster-map"})),o.push(...zi({key:`${r}.${t}.reduce`,value:s,expressionContext:"cluster-reduce"}));}return o;case "video":return Ai({key:r,value:e,valueSpec:n.source_video,style:i,validateSpec:s,styleSpec:n});case "image":return Ai({key:r,value:e,valueSpec:n.source_image,style:i,validateSpec:s,styleSpec:n});case "canvas":return [new Ct(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Ci({key:`${r}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]}})}}function Ri(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("light",e,`object expected, ${a} found`)]),s;for(const a in e){const o=a.match(/^(.*)-transition$/);s=s.concat(o&&n[o[1]]&&n[o[1]].transition?t.validateSpec({key:a,value:e[a],valueSpec:r.transition,validateSpec:t.validateSpec,style:i,styleSpec:r}):n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);}return s}function Ui(t){const e=t.value,r=t.styleSpec,n=r.sky,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("sky",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a}function ji(t){const e=t.value,r=t.styleSpec,n=r.terrain,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("terrain",e,`object expected, ${a} found`)]),s;for(const a in e)s=s.concat(n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);return s}function Ni(t){let e=[];const r=t.value,n=t.key;if(Array.isArray(r)){const i=[],s=[];for(const a in r)r[a].id&&i.includes(r[a].id)&&e.push(new Ct(n,r,`all the sprites' ids must be unique, but ${r[a].id} is duplicated`)),i.push(r[a].id),r[a].url&&s.includes(r[a].url)&&e.push(new Ct(n,r,`all the sprites' URLs must be unique, but ${r[a].url} is duplicated`)),s.push(r[a].url),e=e.concat(Ai({key:`${n}[${a}]`,value:r[a],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:t.validateSpec}));return e}return Di({key:n,value:r})}function qi(t){return e=t.value,Boolean(e)&&e.constructor===Object?[]:[new Ct(t.key,t.value,`object expected, ${Gn(t.value)} found`)];var e;}const Gi={"*":()=>[],array:ki,boolean:function(t){const e=t.value,r=t.key,n=Gn(e);return "boolean"!==n?[new Ct(r,e,`boolean expected, ${n} found`)]:[]},number:Mi,color:Pi,constants:wi,enum:Ci,filter:Ei,function:Ii,layer:$i,object:Ai,source:Oi,light:Ri,sky:Ui,terrain:ji,projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("projection",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a},projectionDefinition:function(t){const e=t.key;let r=t.value;r=r instanceof String?r.valueOf():r;const n=Gn(r);return "array"!==n||function(t){return Array.isArray(t)&&3===t.length&&"string"==typeof t[0]&&"string"==typeof t[1]&&"number"==typeof t[2]}(r)||function(t){return !!["interpolate","step","literal"].includes(t[0])}(r)?["array","string"].includes(n)?[]:[new Ct(e,r,`projection expected, invalid type "${n}" found`)]:[new Ct(e,r,`projection expected, invalid array ${JSON.stringify(r)} found`)]},string:Di,formatted:function(t){return 0===Di(t).length?[]:zi(t)},resolvedImage:function(t){return 0===Di(t).length?[]:zi(t)},padding:function(t){const e=t.key,r=t.value;if("array"===Gn(r)){if(r.length<1||r.length>4)return [new Ct(e,r,`padding requires 1 to 4 values; ${r.length} values found`)];const n={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(r=r.concat(wi({key:"constants",value:t.constants}))),Ki(r)}function Hi(t){return function(e){return t({...e,validateSpec:Xi})}}function Ki(t){return [].concat(t).sort(((t,e)=>t.line-e.line))}function Ji(t){return function(...e){return Ki(t.apply(this,e))}}Yi.source=Ji(Hi(Oi)),Yi.sprite=Ji(Hi(Ni)),Yi.glyphs=Ji(Hi(Zi)),Yi.light=Ji(Hi(Ri)),Yi.sky=Ji(Hi(Ui)),Yi.terrain=Ji(Hi(ji)),Yi.state=Ji(Hi(qi)),Yi.layer=Ji(Hi($i)),Yi.filter=Ji(Hi(Ei)),Yi.paintProperty=Ji(Hi(Vi)),Yi.layoutProperty=Ji(Hi(Fi));const Wi=Yi,Qi=Wi.light,ts=Wi.sky,es=Wi.paintProperty,rs=Wi.layoutProperty;function ns(t,e){let r=!1;if(e&&e.length)for(const n of e)t.fire(new mt(new Error(n.message))),r=!0;return r}class is{constructor(t,e,r){const n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(let t=0;t=u[l+0]&&n>=u[l+1])?(a[h]=!0,s.push(i[h])):a[h]=!1;}}}}_forEachCell(t,e,r,n,i,s,a,o){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!o||o(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,r,n,u,s,a,o))return}}_convertFromCellCoord(t){return (t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let r=0;for(let t=0;t=0)continue;const s=t[n];i[n]=ss[r].shallow.indexOf(n)>=0?s:cs(s,e);}t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==r&&(i.$name=r),i}function hs(t){if(us(t))return t;if(Array.isArray(t))return t.map(hs);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=ls(t)||"Object";if(!ss[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:r}=ss[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const r of Object.keys(t)){if("$name"===r)continue;const i=t[r];n[r]=ss[e].shallow.indexOf(r)>=0?i:hs(i);}return n}class ps{constructor(){this.first=!0;}update(t,e){const r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Hiragana:t=>t>=12352&&t<=12447,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"CJK Unified Ideographs":t=>t>=19968&&t<=40959,"Hangul Syllables":t=>t>=44032&&t<=55215,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function ds(t){for(const e of t)if(bs(e.charCodeAt(0)))return !0;return !1}function ys(t){for(const e of t)if(!xs(e.charCodeAt(0)))return !1;return !0}function ms(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const gs=ms(["Arab","Dupl","Mong","Ougr","Syrc"]);function xs(t){return !gs.test(String.fromCodePoint(t))}const vs=ms(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function bs(t){return !(746!==t&&747!==t&&(t<4352||!(fs["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||fs["CJK Compatibility"](t)||fs["CJK Strokes"](t)||!(!fs["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||fs["Enclosed CJK Letters and Months"](t)||fs["Ideographic Description Characters"](t)||fs.Kanbun(t)||fs.Katakana(t)&&12540!==t||!(!fs["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!fs["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||fs["Vertical Forms"](t)||fs["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||vs.test(String.fromCodePoint(t)))))}function ws(t){return !(bs(t)||function(t){return !!(fs["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||fs["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||fs["Letterlike Symbols"](t)||fs["Number Forms"](t)||fs["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||fs["Control Pictures"](t)&&9251!==t||fs["Optical Character Recognition"](t)||fs["Enclosed Alphanumerics"](t)||fs["Geometric Shapes"](t)||fs["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||fs["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||fs["CJK Symbols and Punctuation"](t)||fs.Katakana(t)||fs["Private Use Area"](t)||fs["CJK Compatibility Forms"](t)||fs["Small Form Variants"](t)||fs["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}const _s=ms(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Ss(t){return _s.test(String.fromCodePoint(t))}function As(t,e){return !(!e&&Ss(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||fs.Khmer(t))}function ks(t){for(const e of t)if(Ss(e.charCodeAt(0)))return !0;return !1}const Ms=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{};}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL;}getState(){return {pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){if(Ms.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText,this.loadScriptResolve();}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(t,r){return e(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if("loading"!==t.pluginStatus)return this.setState(t),t;const e=t.pluginURL,n=new Promise((t=>{this.loadScriptResolve=t;}));r(e);const i=new Promise((t=>setTimeout((()=>t()),this.TIMEOUT)));if(yield Promise.race([n,i]),this.isParsed()){const t={pluginStatus:"loaded",pluginURL:e};return this.setState(t),t}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${e}`)}))}};class Is{constructor(t,e){this.isSupportedScript=zs,this.zoom=t,e?(this.now=e.now||0,this.fadeDuration=e.fadeDuration||0,this.zoomHistory=e.zoomHistory||new ps,this.transition=e.transition||{}):(this.now=0,this.fadeDuration=0,this.zoomHistory=new ps,this.transition={});}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}}}function zs(t){return function(t,e){for(const r of t)if(!As(r.charCodeAt(0),e))return !1;return !0}(t,"loaded"===Ms.getRTLTextPluginStatus())}class Ps{constructor(t,e,r){this.property=t,this.value=e,this.expression=function(t,e,r){if(Xn(t))return new ai(t,e);if(ei(t)){const n=si(t,e,r);if("error"===n.result)throw new Error(n.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return n.value}{let r=t;return "color"===e.type&&"string"==typeof t?r=Me.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"numberArray"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"colorArray"!==e.type||"string"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)?r=$e.parse(t):"projectionDefinition"===e.type&&"string"==typeof t&&(r=Le.parse(t)):r=Be.parse(t):r=Te.parse(t):r=Ee.parse(t),{globalStateRefs:new Set,_globalState:null,kind:"constant",evaluate:()=>r}}}(void 0===e?t.specification.default:e,t.specification,r);}isDataDriven(){return "source"===this.expression.kind||"composite"===this.expression.kind}getGlobalStateRefs(){return this.expression.globalStateRefs||new Set}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class Cs{constructor(t,e){this.property=t,this.value=new Ps(t,void 0,e);}transitioned(t,e){return new Ts(this.property,this.value,e,L({},t.transition,this.transition),t.now)}untransitioned(){return new Ts(this.property,this.value,null,{},0)}}class Es{constructor(t,e){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues),this._globalState=e;}getValue(t){return j(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].value=new Ps(this._values[t].property,null===e?void 0:j(e),this._globalState);}getTransition(t){return j(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].transition=j(e)||void 0;}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r);const n=this.getTransition(e);void 0!==n&&(t[`${e}-transition`]=n);}return t}transitioned(t,e){const r=new Bs(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new Bs(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class Ts{constructor(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(nn.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Rs{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new Is(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Is(Math.floor(e.zoom),e)),t.expression.evaluate(new Is(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Us{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)}interpolate(){return !1}}class js{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const r=t[e];r.specification.overridable&&this.overridableProperties.push(e);const n=this.defaultPropertyValues[e]=new Ps(r,void 0,void 0),i=this.defaultTransitionablePropertyValues[e]=new Cs(r,void 0);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}}}as("DataDrivenProperty",Ls),as("DataConstantProperty",Ds),as("CrossFadedDataDrivenProperty",Os),as("CrossFadedProperty",Rs),as("ColorRampProperty",Us);const Ns="-transition";class qs extends gt{constructor(t,e,r){if(super(),this.id=t.id,this.type=t.type,this._globalState=r,this._featureFilter={filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter,this._featureFilter=hi(t.filter,r)),e.layout&&(this._unevaluatedLayout=new Vs(e.layout,r)),e.paint)){this._transitionablePaint=new Es(e.paint,r);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new $s(e.paint);}}setFilter(t){this.filter=t,this._featureFilter=hi(t,this._globalState);}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}getLayoutAffectingGlobalStateRefs(){const t=new Set;if(this._unevaluatedLayout)for(const e in this._unevaluatedLayout._values){const r=this._unevaluatedLayout._values[e];for(const e of r.getGlobalStateRefs())t.add(e);}for(const e of this._featureFilter.getGlobalStateRefs())t.add(e);return t}getPaintAffectingGlobalStateRefs(){var t;const e=new globalThis.Map;if(this._transitionablePaint)for(const r in this._transitionablePaint._values){const n=this._transitionablePaint._values[r].value;for(const i of n.getGlobalStateRefs()){const s=null!==(t=e.get(i))&&void 0!==t?t:[];s.push({name:r,value:n.value}),e.set(i,s);}}return e}setLayoutProperty(t,e,r={}){null!=e&&this._validate(rs,`layers.${this.id}.layout.${t}`,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);}getPaintProperty(t){return t.endsWith(Ns)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(es,`layers.${this.id}.paint.${t}`,t,e,r))return !1;if(t.endsWith(Ns))return this._transitionablePaint.setTransition(t.slice(0,-11),e||void 0),!1;{const r=this._transitionablePaint._values[t],n="cross-faded-data-driven"===r.property.specification["property-type"],i=r.value.isDataDriven(),s=r.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const a=this._transitionablePaint._values[t].value;return a.isDataDriven()||i||n||this._handleOverridablePaintPropertyUpdate(t,s,a)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,r){return !1}isHidden(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),U(t,((t,e)=>!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return (!i||!1!==i.validate)&&ns(this,t.call(Wi,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:xt,style:{glyphs:!0,sprite:!0}}))}is3D(){return !1}isTileClipped(){return !1}hasOffscreenPass(){return !1}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof Fs&&jn(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1}}const Gs={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Xs{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class Zs{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Ys(t,e=1){let r=0,n=0;return {members:t.map((t=>{const i=Gs[t.type].BYTES_PER_ELEMENT,s=r=Hs(r,Math.max(e,i)),a=t.components||1;return n=Math.max(n,i),r+=i*a,{name:t.name,type:t.type,components:a,offset:s}})),size:Hs(r,Math.max(n,e)),alignment:e}}function Hs(t,e){return Math.ceil(t/e)*e}class Ks extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}Ks.prototype.bytesPerElement=4,as("StructArrayLayout2i4",Ks);class Js extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}Js.prototype.bytesPerElement=6,as("StructArrayLayout3i6",Js);class Ws extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}Ws.prototype.bytesPerElement=8,as("StructArrayLayout4i8",Ws);class Qs extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}Qs.prototype.bytesPerElement=12,as("StructArrayLayout2i4i12",Qs);class ta extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=4*t,l=8*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.uint8[l+4]=n,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=a,t}}ta.prototype.bytesPerElement=8,as("StructArrayLayout2i4ub8",ta);class ea extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}ea.prototype.bytesPerElement=8,as("StructArrayLayout2f8",ea);class ra extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,s,a,o,l,u)}emplace(t,e,r,n,i,s,a,o,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=r,this.uint16[h+2]=n,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=a,this.uint16[h+6]=o,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}ra.prototype.bytesPerElement=20,as("StructArrayLayout10ui20",ra);class na extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,a,o,l,u,c,h)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=a,this.uint16[f+6]=o,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}na.prototype.bytesPerElement=24,as("StructArrayLayout4i4ui4i24",na);class ia extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}ia.prototype.bytesPerElement=12,as("StructArrayLayout3f12",ia);class sa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}sa.prototype.bytesPerElement=4,as("StructArrayLayout1ul4",sa);class aa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,s,a,o,l)}emplace(t,e,r,n,i,s,a,o,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=r,this.int16[c+2]=n,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=a,this.uint32[h+3]=o,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}aa.prototype.bytesPerElement=20,as("StructArrayLayout6i1ul2ui20",aa);class oa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}oa.prototype.bytesPerElement=12,as("StructArrayLayout2i2i2i12",oa);class la extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.int16[o+6]=i,this.int16[o+7]=s,t}}la.prototype.bytesPerElement=16,as("StructArrayLayout2f1f2i16",la);class ua extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=16*t,l=4*t,u=8*t;return this.uint8[o+0]=e,this.uint8[o+1]=r,this.float32[l+1]=n,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=a,t}}ua.prototype.bytesPerElement=16,as("StructArrayLayout2ub2f2i16",ua);class ca extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}ca.prototype.bytesPerElement=6,as("StructArrayLayout3ui6",ca);class ha extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=r,this.uint16[x+2]=n,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=a,this.uint32[v+4]=o,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}ha.prototype.bytesPerElement=48,as("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",ha);class pa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I){const z=this.length;return this.resize(z+1),this.emplace(z,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I,z){const P=32*t,C=16*t;return this.int16[P+0]=e,this.int16[P+1]=r,this.int16[P+2]=n,this.int16[P+3]=i,this.int16[P+4]=s,this.int16[P+5]=a,this.int16[P+6]=o,this.int16[P+7]=l,this.uint16[P+8]=u,this.uint16[P+9]=c,this.uint16[P+10]=h,this.uint16[P+11]=p,this.uint16[P+12]=f,this.uint16[P+13]=d,this.uint16[P+14]=y,this.uint16[P+15]=m,this.uint16[P+16]=g,this.uint16[P+17]=x,this.uint16[P+18]=v,this.uint16[P+19]=b,this.uint16[P+20]=w,this.uint16[P+21]=_,this.uint16[P+22]=S,this.uint32[C+12]=A,this.float32[C+13]=k,this.float32[C+14]=M,this.uint16[P+30]=I,this.uint16[P+31]=z,t}}pa.prototype.bytesPerElement=64,as("StructArrayLayout8i15ui1ul2f2ui64",pa);class fa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}fa.prototype.bytesPerElement=4,as("StructArrayLayout1f4",fa);class da extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}da.prototype.bytesPerElement=12,as("StructArrayLayout1ui2f12",da);class ya extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t}}ya.prototype.bytesPerElement=8,as("StructArrayLayout1ul2ui8",ya);class ma extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}ma.prototype.bytesPerElement=4,as("StructArrayLayout2ui4",ma);class ga extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}ga.prototype.bytesPerElement=2,as("StructArrayLayout1ui2",ga);class xa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}xa.prototype.bytesPerElement=16,as("StructArrayLayout4f16",xa);class va extends Xs{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new r(this.anchorPointX,this.anchorPointY)}}va.prototype.size=20;class ba extends aa{get(t){return new va(this,t)}}as("CollisionBoxArray",ba);class wa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t;}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}wa.prototype.size=48;class _a extends ha{get(t){return new wa(this,t)}}as("PlacedSymbolArray",_a);class Sa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t;}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}Sa.prototype.size=64;class Aa extends pa{get(t){return new Sa(this,t)}}as("SymbolInstanceArray",Aa);class ka extends fa{getoffsetX(t){return this.float32[1*t+0]}}as("GlyphOffsetArray",ka);class Ma extends Js{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}as("SymbolLineVertexArray",Ma);class Ia extends Xs{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}Ia.prototype.size=12;class za extends da{get(t){return new Ia(this,t)}}as("TextAnchorOffsetArray",za);class Pa extends Xs{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}Pa.prototype.size=8;class Ca extends ya{get(t){return new Pa(this,t)}}as("FeatureIndexArray",Ca);class Ea extends Ks{}class Ta extends Ks{}class Ba extends Ks{}class Va extends Qs{}class Fa extends ta{}class $a extends ea{}class Da extends ra{}class La extends na{}class Oa extends ia{}class Ra extends sa{}class Ua extends oa{}class ja extends ua{}class Na extends ca{}class qa extends ma{}const Ga=Ys([{name:"a_pos",components:2,type:"Int16"}],4),{members:Xa}=Ga;class Za{constructor(t=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=t;}prepareSegment(t,e,r,n){const i=this.segments[this.segments.length-1];return t>Za.MAX_VERTEX_ARRAY_LENGTH&&q(`Max vertices per segment is ${Za.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${Za.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!i||i.vertexLength+t>Za.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n?this.createNewSegment(e,r,n):i}createNewSegment(t,e,r){const n={vertexOffset:t.length,primitiveOffset:e.length,vertexLength:0,primitiveLength:0,vaos:{}};return void 0!==r&&(n.sortKey=r),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(n),n}getOrCreateLatestSegment(t,e,r){return this.prepareSegment(0,t,e,r)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0;}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,r,n){return new Za([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function Ya(t,e){return 256*(t=$(Math.floor(t),0,255))+$(Math.floor(e),0,255)}Za.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,as("SegmentVector",Za);const Ha=Ys([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var Ka,Ja,Wa,Qa={exports:{}},to={exports:{}},eo={exports:{}},ro=function(){if(Wa)return Qa.exports;Wa=1;var t=(Ka||(Ka=1,to.exports=function(t,e){var r,n,i,s,a,o,l,u;for(n=t.length-(r=3&t.length),i=e,a=3432918353,o=461845907,u=0;u>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0}),to.exports),e=(Ja||(Ja=1,eo.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0}),eo.exports);return Qa.exports=t,Qa.exports.murmur3=t,Qa.exports.murmur2=e,Qa.exports}(),no=n(ro);class io{constructor(){this.ids=[],this.positions=[],this.indexed=!1;}add(t,e,r,n){this.ids.push(so(t)),this.positions.push(e,r,n);}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=so(t);let r=0,n=this.ids.length-1;for(;r>1;this.ids[t]>=e?n=t:r=t+1;}const i=[];for(;this.ids[r]===e;)i.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return i}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return ao(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}}static deserialize(t){const e=new io;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e}}function so(t){const e=+t;return !isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:no(String(t))}function ao(t,e,r,n){for(;r>1];let s=r-1,a=n+1;for(;;){do{s++;}while(t[s]i);if(s>=a)break;oo(t,s,a),oo(e,3*s,3*a),oo(e,3*s+1,3*a+1),oo(e,3*s+2,3*a+2);}a-r`u_${t}`)),this.type=r;}setUniform(t,e,r){t.set(r.constantOr(this.value));}getBinding(t,e,r){return "color"===this.type?new ho(t,e):new uo(t,e)}}class mo{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;}setUniform(t,e,r,n){const i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);}getBinding(t,e,r){return "u_pattern"===r.substr(0,9)?new co(t,e):new uo(t,e)}}class go{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?2:1,offset:0}))),this.paintVertexArray=new n;}populatePaintArray(t,e,r){const n=this.paintVertexArray.length,i=this.expression.evaluate(new Is(0,r),e,{},r.canonical,[],r.formattedSection);this.paintVertexArray.resize(t),this._setPaintValue(n,t,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(0,i),r,n);this._setPaintValue(t,e,s);}_setPaintValue(t,e,r){if("color"===this.type){const n=fo(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,r){const n=this.expression.evaluate(new Is(this.zoom,r),e,{},r.canonical,[],r.formattedSection),i=this.expression.evaluate(new Is(this.zoom+1,r),e,{},r.canonical,[],r.formattedSection),s=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(s,t,n,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(this.zoom,i),r,n),a=this.expression.evaluate(new Is(this.zoom+1,i),r,n);this._setPaintValue(t,e,s,a);}_setPaintValue(t,e,r,n){if("color"===this.type){const i=fo(r),s=fo(n);for(let r=t;r`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof go||r instanceof xo)for(let e=0;e!0){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new bo(n,e,r);this.needsUpload=!1,this._featureMap=new io,this._bufferOffset=0;}populatePaintArrays(t,e,r,n){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;}updatePaintArrays(t,e,r,n){for(const i of r)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,n)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}function _o(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function So(t,e,r){const n={color:{source:ea,composite:xa},number:{source:fa,composite:ea}},i=function(t){return {"line-pattern":{source:Da,composite:Da},"fill-pattern":{source:Da,composite:Da},"fill-extrusion-pattern":{source:Da,composite:Da}}[t]}(t);return i&&i[r]||n[e][r]}as("ConstantBinder",yo),as("CrossFadedConstantBinder",mo),as("SourceExpressionBinder",go),as("CrossFadedCompositeBinder",vo),as("CompositeExpressionBinder",xo),as("ProgramConfiguration",bo,{omit:["_buffers"]}),as("ProgramConfigurationSet",wo);const Ao=Math.pow(2,14)-1,ko=-Ao-1;function Mo(t){const e=P/t.extent,r=t.loadGeometry();for(let t=0;tr.x+1||sr.y+1)&&q("Geometry exceeds allowed extent, reduce your vector tile buffer size");}}return r}function Io(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?Mo(t):[]}}const zo=-32768;function Po(t,e,r,n,i){t.emplaceBack(zo+8*e+n,zo+8*r+i);}class Co{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Ta,this.indexArray=new Na,this.segments=new Za,this.programConfigurations=new wo(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){const n=this.layers[0],i=[];let s=null,a=!1,o="heatmap"===n.type;if("circle"===n.type){const t=n;s=t.layout.get("circle-sort-key"),a=!s.isConstant(),o=o||"map"===t.paint.get("circle-pitch-alignment");}const l=o?e.subdivisionGranularity.circle:1;for(const{feature:e,id:n,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=a?s.evaluate(u,{},r):void 0,h={id:n,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};i.push(h);}a&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of i){const{geometry:i,index:s,sourceLayerIndex:a}=n,o=t[s].feature;this.addFeature(n,i,s,r,l),e.featureIndex.insert(o,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Xa),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,r,n,i=1){let s;switch(i){case 1:s=[0,7];break;case 3:s=[0,2,5,7];break;case 5:s=[0,1,3,4,6,7];break;case 7:s=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${i}; valid values are 1, 3, 5, 7.`)}const a=s.length;for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=P||n<0||n>=P)continue;const i=this.segments.prepareSegment(a*a,this.layoutVertexArray,this.indexArray,t.sortKey),o=i.vertexLength;for(let t=0;t1){if(Fo(t,e))return !0;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function Oo(t,e){let r,n,i,s=!1;for(let a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s);}return s}function Ro(t,e){let r=!1;for(let n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-s.x)*(e.y-s.y)/(a.y-s.y)+s.x&&(r=!r);}return r}function Uo(t,e,r){const n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;const s=G(t,e,r[0]);return s!==G(t,e,r[1])||s!==G(t,e,r[2])||s!==G(t,e,r[3])}function jo(t,e,r){const n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function No(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function qo(t,e,n,i,s){if(!e[0]&&!e[1])return t;const a=r.convert(e)._mult(s);"viewport"===n&&a._rotate(-i);const o=[];for(let e=0;eKo(t,e,r,n)))}(l,i,a,o),f=u),Ho({queryGeometry:p,size:f,transform:i,unwrappedTileID:a,getElevation:o,pitchAlignment:h,pitchScale:c},n)}}class el extends Co{}let rl;as("HeatmapBucket",el,{omit:["layers"]});var nl={get paint(){return rl=rl||new js({"heatmap-radius":new Ls(xt.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Ls(xt.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Ds(xt.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Us(xt.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Ds(xt.paint_heatmap["heatmap-opacity"])})}};function il(t,{width:e,height:r},n,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*r*n)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*r*n}`)}else i=new Uint8Array(e*r*n);return t.width=e,t.height=r,t.data=i,t}function sl(t,{width:e,height:r},n){if(e===t.width&&r===t.height)return;const i=il({},{width:e,height:r},n);al(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,r)},n),t.width=e,t.height=r,t.data=i.data;}function al(t,e,r,n,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const a=t.data,o=e.data;if(a===o)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=a;const o=t.expression.evaluate(e);i.setPixel(n/4/r,s/4,o);};if(t.clips)for(let e=0,i=0;ethis.max&&(this.max=r),r=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)}unpack(t,e,r){return t*this.redFactor+e*this.greenFactor+r*this.blueFactor-this.baseShift}pack(t){return vl(t,this.getUnpackVector())}getPixels(){return new ll({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,a=r*this.dim+this.dim;switch(e){case -1:n=i-1;break;case 1:i=n+1;}switch(r){case -1:s=a-1;break;case 1:a=s+1;}const o=-e*this.dim,l=-r*this.dim;for(let e=s;e0)for(let i=e;i=e;i-=n)s=Zl(i/n|0,t[i],t[i+1],s);return s&&Ul(s,s.next)&&(Yl(s),s=s.next),s}function Ml(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!Ul(n,n.next)&&0!==Rl(n.prev,n,n.next))n=n.next;else {if(Yl(n),n=e=n.prev,n===n.next)break;r=!0;}}while(r||n!==e);return e}function Il(t,e,r,n,i,s,a){if(!t)return;!a&&s&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=Fl(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let s=null;for(e=0;i;){e++;let a=i,o=0;for(let t=0;t0||l>0&&a;)0!==o&&(0===l||!a||i.z<=a.z)?(n=i,i=i.nextZ,o--):(n=a,a=a.nextZ,l--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;i=a;}s.nextZ=null,r*=2;}while(e>1)}(i);}(t,n,i,s);let o=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?Pl(t,n,i,s):zl(t))e.push(l.i,t.i,u.i),Yl(t),t=u.next,o=u.next;else if((t=u)===o){a?1===a?Il(t=Cl(Ml(t),e),e,r,n,i,s,2):2===a&&El(t,e,r,n,i,s):Il(Ml(t),e,r,n,i,s,1);break}}}function zl(t){const e=t.prev,r=t,n=t.next;if(Rl(e,r,n)>=0)return !1;const i=e.x,s=r.x,a=n.x,o=e.y,l=r.y,u=n.y,c=Math.min(i,s,a),h=Math.min(o,l,u),p=Math.max(i,s,a),f=Math.max(o,l,u);let d=n.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&Ll(i,o,s,l,a,u,d.x,d.y)&&Rl(d.prev,d,d.next)>=0)return !1;d=d.next;}return !0}function Pl(t,e,r,n){const i=t.prev,s=t,a=t.next;if(Rl(i,s,a)>=0)return !1;const o=i.x,l=s.x,u=a.x,c=i.y,h=s.y,p=a.y,f=Math.min(o,l,u),d=Math.min(c,h,p),y=Math.max(o,l,u),m=Math.max(c,h,p),g=Fl(f,d,e,r,n),x=Fl(y,m,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}return !0}function Cl(t,e){let r=t;do{const n=r.prev,i=r.next.next;!Ul(n,i)&&jl(n,r,r.next,i)&&Gl(n,i)&&Gl(i,n)&&(e.push(n.i,r.i,i.i),Yl(r),Yl(r.next),r=t=i),r=r.next;}while(r!==t);return Ml(r)}function El(t,e,r,n,i,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Ol(a,t)){let o=Xl(a,t);return a=Ml(a,a.next),o=Ml(o,o.next),Il(a,e,r,n,i,s,0),void Il(o,e,r,n,i,s,0)}t=t.next;}a=a.next;}while(a!==t)}function Tl(t,e){let r=t.x-e.x;return 0===r&&(r=t.y-e.y,0===r)&&(r=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)),r}function Bl(t,e){const r=function(t,e){let r=e;const n=t.x,i=t.y;let s,a=-1/0;if(Ul(t,r))return r;do{if(Ul(t,r.next))return r.next;if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){const t=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(t<=n&&t>a&&(a=t,s=r.x=r.x&&r.x>=l&&n!==r.x&&Dl(is.x||r.x===s.x&&Vl(s,r)))&&(s=r,c=e);}r=r.next;}while(r!==o);return s}(t,e);if(!r)return e;const n=Xl(r,t);return Ml(n,n.next),Ml(r,r.next)}function Vl(t,e){return Rl(t.prev,t,e.prev)<0&&Rl(e.next,t,t.next)<0}function Fl(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function $l(t){let e=t,r=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(r-a)*(e-o)&&(r-a)*(s-o)>=(i-a)*(n-o)}function Ll(t,e,r,n,i,s,a,o){return !(t===a&&e===o)&&Dl(t,e,r,n,i,s,a,o)}function Ol(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&jl(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(Gl(t,e)&&Gl(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Rl(t.prev,t,e.prev)||Rl(t,e.prev,e))||Ul(t,e)&&Rl(t.prev,t,t.next)>0&&Rl(e.prev,e,e.next)>0)}function Rl(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Ul(t,e){return t.x===e.x&&t.y===e.y}function jl(t,e,r,n){const i=ql(Rl(t,e,r)),s=ql(Rl(t,e,n)),a=ql(Rl(r,n,t)),o=ql(Rl(r,n,e));return i!==s&&a!==o||!(0!==i||!Nl(t,r,e))||!(0!==s||!Nl(t,n,e))||!(0!==a||!Nl(r,t,n))||!(0!==o||!Nl(r,e,n))}function Nl(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function ql(t){return t>0?1:t<0?-1:0}function Gl(t,e){return Rl(t.prev,t,t.next)<0?Rl(t,e,t.next)>=0&&Rl(t,t.prev,e)>=0:Rl(t,e,t.prev)<0||Rl(t,t.next,e)<0}function Xl(t,e){const r=Hl(t.i,t.x,t.y),n=Hl(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function Zl(t,e,r,n){const i=Hl(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Yl(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 Hl(t,e,r){return {i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class Kl{constructor(t,e){if(e>t)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=t,this._minGranularity=e;}getGranularityForZoomLevel(t){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||e>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const r=0|Math.round(t),n=0|Math.round(e),i=this._getKey(r,n);if(this._vertexDictionary.has(i))return this._vertexDictionary.get(i);const s=this._vertexBuffer.length/2;return this._vertexDictionary.set(i,s),this._vertexBuffer.push(r,n),s}_subdivideTrianglesScanline(t){if(this._granularity<2)return function(t,e){const r=[];for(let n=0;n0?(r.push(i),r.push(a),r.push(s)):(r.push(i),r.push(s),r.push(a));}return r}(this._vertexBuffer,t);const e=[],r=t.length;for(let n=0;n=1||v<=0)||y&&(oi)){u>=n&&u<=i&&s.push(r[(t+1)%3]);continue}!y&&x>0&&s.push(this._vertexToIndex(a+p*x,o+f*x));const b=a+p*Math.max(x,0),w=a+p*Math.min(v,1);d||this._generateIntraEdgeVertices(s,a,o,l,u,b,w),!y&&v<1&&s.push(this._vertexToIndex(a+p*v,o+f*v)),(y||u>=n&&u<=i)&&s.push(r[(t+1)%3]),!y&&(u<=n||u>=i)&&this._generateInterEdgeVertices(s,a,o,l,u,c,h,w,n,i);}return s}_generateIntraEdgeVertices(t,e,r,n,i,s,a){const o=n-e,l=i-r,u=0===l,c=u?Math.min(e,n):Math.min(s,a),h=u?Math.max(e,n):Math.max(s,a),p=Math.floor(c/this._granularityCellSize)+1,f=Math.ceil(h/this._granularityCellSize)-1;if(u?e=p;n--){const i=n*this._granularityCellSize;t.push(this._vertexToIndex(i,r+l*(i-e)/o));}}_generateInterEdgeVertices(t,e,r,n,i,s,a,o,l,u){const c=i-r,h=s-n,p=a-i,f=(l-i)/p,d=(u-i)/p,y=Math.min(f,d),m=Math.max(f,d),g=n+h*y;let x=Math.floor(Math.min(g,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(g,o)/this._granularityCellSize)-1,b=o=1||m<=0){const t=r-a,n=s+(e-s)*Math.min((l-a)/t,(u-a)/t);x=Math.floor(Math.min(n,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(n,o)/this._granularityCellSize)-1,b=o0?u:l;if(b)for(let e=x;e<=v;e++)t.push(this._vertexToIndex(e*this._granularityCellSize,_));else for(let e=v;e>=x;e--)t.push(this._vertexToIndex(e*this._granularityCellSize,_));}_generateOutline(t){const e=[];for(const r of t){const t=ru(r,this._granularity,!0),n=this._pointArrayToIndices(t),i=[];for(let t=1;ti!=(s===Wl)?(t.push(e),t.push(r),t.push(this._vertexToIndex(n,s)),t.push(r),t.push(this._vertexToIndex(i,s)),t.push(this._vertexToIndex(n,s))):(t.push(r),t.push(e),t.push(this._vertexToIndex(n,s)),t.push(this._vertexToIndex(i,s)),t.push(r),t.push(this._vertexToIndex(n,s)));}_fillPoles(t,e,r){const n=this._vertexBuffer,i=P,s=t.length;for(let a=2;a80*r){o=t[0],l=t[1];let e=o,n=l;for(let s=r;se&&(e=r),i>n&&(n=i);}u=Math.max(e-o,n-l),u=0!==u?32767/u:0;}return Il(s,a,r,o,l,u,0),a}(r,n),e=this._convertIndices(r,t);i=this._subdivideTrianglesScanline(e);}catch(t){console.error(t);}let s=[];return e&&(s=this._generateOutline(t)),this._ensureNoPoleVertices(),this._handlePoles(i),{verticesFlattened:this._vertexBuffer,indicesTriangles:i,indicesLineList:s}}_convertIndices(t,e){const r=[];for(let n=0;n0?(Math.floor(x/o)+1)*o:(Math.ceil(x/o)-1)*o,e=y>0?(Math.floor(v/o)+1)*o:(Math.ceil(v/o)-1)*o,n=Math.abs(x-t),i=Math.abs(v-e),s=Math.abs(x-c),a=Math.abs(v-h),u=p?n/m:Number.POSITIVE_INFINITY,b=f?i/g:Number.POSITIVE_INFINITY;if((s<=n||!p)&&(a<=i||!f))break;if(u=0?a-1:s-1,i=(o+1)%s,l=t[2*e[n]],u=t[2*e[i]],c=t[2*e[a]],h=t[2*e[a]+1],p=t[2*e[o]+1];let f=!1;if(lu)f=!1;else {const r=p-h,s=-(t[2*e[o]]-c),a=h((u-c)*r+(t[2*e[i]+1]-h)*s)*a&&(f=!0);}if(f){const t=e[n],i=e[a],l=e[o];t!==i&&t!==l&&i!==l&&r.push(l,i,t),a--,a<0&&(a=s-1);}else {const t=e[i],n=e[a],l=e[o];t!==n&&t!==l&&n!==l&&r.push(l,n,t),o++,o>=s&&(o=0);}if(n===i)break}}function iu(t,e,r,n,i,s,a,o,l){const u=i.length/2,c=a&&o&&l;if(uZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,y=!0,m=!0,g=!0,c=0);const x=su(a,n,s,o,p,y,u),v=su(a,n,s,o,f,m,u),b=su(a,n,s,o,d,g,u);r.emplaceBack(c+x-l,c+v-l,c+b-l),u.primitiveLength++;}}(e,r,n,i,s,t),c&&function(t,e,r,n,i,s){const a=[];for(let t=0;tZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,d=!0,y=!0,c=0);const m=su(a,n,s,o,i,d,u),g=su(a,n,s,o,h,y,u);r.emplaceBack(c+m-l,c+g-l),u.primitiveLength++;}}}(a,r,o,i,l,t),e.forceNewSegmentOnNextPrepare(),null==a||a.forceNewSegmentOnNextPrepare();}function su(t,e,r,n,i,s,a){if(s){const s=n.count;return r(e[2*i],e[2*i+1]),t[i]=n.count,n.count++,a.vertexLength++,s}return t[i]}class au{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Ba,this.indexArray=new Na,this.indexArray2=new qa,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.segments2=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("fill",this.layers,e);const n=this.layers[0].layout.get("fill-sort-key"),i=!n.isConstant(),s=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=Io(a,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),c,r))continue;const h=i?n.evaluate(c,{},r,e.availableImages):void 0,p={id:o,properties:a.properties,type:a.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:Mo(a),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("fill",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,_l),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,r,n,i,s){for(const t of Qr(e,500)){const e=eu(t,n,s.fill.getGranularityForZoomLevel(n.z)),r=this.layoutVertexArray;iu(((t,e)=>{r.emplaceBack(t,e);}),this.segments,this.layoutVertexArray,this.indexArray,e.verticesFlattened,e.indicesTriangles,this.segments2,this.indexArray2,e.indicesLineList);}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}}let ou,lu;as("FillBucket",au,{omit:["layers","patternFeatures"]});var uu={get paint(){return lu=lu||new js({"fill-antialias":new Ds(xt.paint_fill["fill-antialias"]),"fill-opacity":new Ls(xt.paint_fill["fill-opacity"]),"fill-color":new Ls(xt.paint_fill["fill-color"]),"fill-outline-color":new Ls(xt.paint_fill["fill-outline-color"]),"fill-translate":new Ds(xt.paint_fill["fill-translate"]),"fill-translate-anchor":new Ds(xt.paint_fill["fill-translate-anchor"]),"fill-pattern":new Os(xt.paint_fill["fill-pattern"])})},get layout(){return ou=ou||new js({"fill-sort-key":new Ls(xt.layout_fill["fill-sort-key"])})}};class cu extends qs{constructor(t,e){super(t,uu,e);}recalculate(t,e){super.recalculate(t,e);const r=this.paint._values["fill-outline-color"];"constant"===r.value.kind&&void 0===r.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);}createBucket(t){return new au(t)}queryRadius(){return No(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:t,geometry:e,transform:r,pixelsToTileUnits:n}){return Bo(qo(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-r.bearingInRadians,n),e)}isTileClipped(){return !0}}const hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),pu=Ys([{name:"a_centroid",components:2,type:"Int16"}],4),{members:fu}=hu;class du{constructor(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this.id=void 0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(yu,this,e);}loadGeometry(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos,n=[];let i,s=1,a=0,o=0,l=0;for(;t.pos>3;}if(a--,1===s||2===s)o+=t.readSVarint(),l+=t.readSVarint(),1===s&&(i&&n.push(i),i=[]),i&&i.push(new r(o,l));else {if(7!==s)throw new Error(`unknown command ${s}`);i&&i.push(i[0].clone());}}return i&&n.push(i),n}bbox(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos;let r=1,n=0,i=0,s=0,a=1/0,o=-1/0,l=1/0,u=-1/0;for(;t.pos>3;}if(n--,1===r||2===r)i+=t.readSVarint(),s+=t.readSVarint(),io&&(o=i),su&&(u=s);else if(7!==r)throw new Error(`unknown command ${r}`)}return [a,l,o,u]}toGeoJSON(t,e,r){const n=this.extent*Math.pow(2,r),i=this.extent*t,s=this.extent*e,a=this.loadGeometry();function o(t){return [360*(t.x+i)/n-180,360/Math.PI*Math.atan(Math.exp((1-2*(t.y+s)/n)*Math.PI))-90]}function l(t){return t.map(o)}let u;if(1===this.type){const t=[];for(const e of a)t.push(e[0]);const e=l(t);u=1===t.length?{type:"Point",coordinates:e[0]}:{type:"MultiPoint",coordinates:e};}else if(2===this.type){const t=a.map(l);u=1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t};}else {if(3!==this.type)throw new Error("unknown feature type");{const t=function(t){const e=t.length;if(e<=1)return [t];const r=[];let n,i;for(let s=0;s=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];const e=this._pbf.readVarint()+this._pbf.pos;return new du(this._pbf,e,this.extent,this._keys,this._values)}}function xu(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){let e=null;const r=t.readVarint()+t.pos;for(;t.pos>3;e=1===r?t.readString():2===r?t.readFloat():3===r?t.readDouble():4===r?t.readVarint64():5===r?t.readVarint():6===r?t.readSVarint():7===r?t.readBoolean():null;}if(null==e)throw new Error("unknown feature value");return e}(r));}class vu{constructor(t,e){this.layers=t.readFields(bu,{},e);}}function bu(t,e,r){if(3===t){const t=new gu(r,r.readVarint()+r.pos);t.length&&(e[t.name]=t);}}const wu=Math.pow(2,13);function _u(t,e,r,n,i,s,a,o){t.emplaceBack(e,r,2*Math.floor(n*wu)+a,i*wu*2,s*wu*2,Math.round(o));}class Su{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Va,this.centroidVertexArray=new Ea,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.features=[],this.hasPattern=Sl("fill-extrusion",this.layers,e);for(const{feature:n,id:i,index:s,sourceLayerIndex:a}of t){const t=this.layers[0]._featureFilter.needGeometry,o=Io(n,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),o,r))continue;const l={id:i,sourceLayerIndex:a,index:s,geometry:t?o.geometry:Mo(n),properties:n.properties,type:n.type,patterns:{}};this.hasPattern?this.features.push(Al("fill-extrusion",this.layers,l,{zoom:this.zoom},e)):this.addFeature(l,l.geometry,s,r,{},e.subdivisionGranularity),e.featureIndex.insert(n,l.geometry,s,a,this.index,!0);}}addFeatures(t,e,r){for(const n of this.features){const{geometry:i}=n;this.addFeature(n,i,n.index,e,r,t.subdivisionGranularity);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,fu),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,pu.members,!0),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy());}addFeature(t,e,r,n,i,s){for(const r of Qr(e,500)){const e={x:0,y:0,sampleCount:0},i=this.layoutVertexArray.length;this.processPolygon(e,n,t,r,s);const a=this.layoutVertexArray.length-i,o=Math.floor(e.x/e.sampleCount),l=Math.floor(e.y/e.sampleCount);for(let t=0;t{_u(u,t,e,0,0,1,1,0);}),this.segments,this.layoutVertexArray,this.indexArray,l.verticesFlattened,l.indicesTriangles);}_generateSideFaces(t,e){let r=0;for(let n=1;nZa.MAX_VERTEX_ARRAY_LENGTH&&(e.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const a=i.sub(s)._perp()._unit(),o=s.dist(i);r+o>32768&&(r=0),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,1,r),r+=o,_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,1,r);const l=e.segment.vertexLength;this.indexArray.emplaceBack(l,l+2,l+1),this.indexArray.emplaceBack(l+1,l+2,l+3),e.segment.vertexLength+=4,e.segment.primitiveLength+=2;}}}function Au(t,e){for(let r=0;rP)||t.y===e.y&&(t.y<0||t.y>P)}function Mu(t){return t.every((t=>t.x<0))||t.every((t=>t.x>P))||t.every((t=>t.y<0))||t.every((t=>t.y>P))}let Iu;as("FillExtrusionBucket",Su,{omit:["layers","features"]});var zu={get paint(){return Iu=Iu||new js({"fill-extrusion-opacity":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Os(xt["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class Pu extends qs{constructor(t,e){super(t,zu,e);}createBucket(t){return new Su(t)}queryRadius(){return No(this.paint.get("fill-extrusion-translate"))}is3D(){return !0}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a,pixelPosMatrix:o}){const l=qo(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-s.bearingInRadians,a),u=this.paint.get("fill-extrusion-height").evaluate(e,n),c=this.paint.get("fill-extrusion-base").evaluate(e,n),h=function(t,e){const n=[];for(const i of t){const t=[i.x,i.y,0,1];A(t,t,e),n.push(new r(t[0]/t[3],t[1]/t[3]));}return n}(l,o),p=function(t,e,n,i){const s=[],a=[],o=i[8]*e,l=i[9]*e,u=i[10]*e,c=i[11]*e,h=i[8]*n,p=i[9]*n,f=i[10]*n,d=i[11]*n;for(const e of t){const t=[],n=[];for(const s of e){const e=s.x,a=s.y,y=i[0]*e+i[4]*a+i[12],m=i[1]*e+i[5]*a+i[13],g=i[2]*e+i[6]*a+i[14],x=i[3]*e+i[7]*a+i[15],v=g+u,b=x+c,w=y+h,_=m+p,S=g+f,A=x+d,k=new r((y+o)/b,(m+l)/b);k.z=v/b,t.push(k);const M=new r(w/A,_/A);M.z=S/A,n.push(M);}s.push(t),a.push(n);}return [s,a]}(i,c,u,o);return function(t,e,r){let n=1/0;Bo(r,e)&&(n=Eu(r,e[0]));for(let i=0;it.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new Fa,this.layoutVertexArray2=new $a,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("line",this.layers,e);const n=this.layers[0].layout.get("line-sort-key"),i=!n.isConstant(),s=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=i?n.evaluate(u,{},r):void 0,h={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("line",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,Fu)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Bu),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return {start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i,s){const a=this.layers[0].layout,o=a.get("line-join").evaluate(t,{}),l=a.get("line-cap"),u=a.get("line-miter-limit"),c=a.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,o,l,u,c,n,s);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}addLine(t,e,r,n,i,s,a,o){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,t=ru(t,a?o.line.getGranularityForZoomLevel(a.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[u-1].equals(t[u-2]);)u--;let c=0;for(;c0;if(w&&e>c){const t=f.dist(d);if(t>2*h){const e=f.sub(f.sub(d)._mult(h/t)._round());this.updateDistance(d,e),this.addCurrentVertex(e,m,0,0,p),d=e;}}const S=d&&y;let A=S?r:l?"butt":n;if(S&&"round"===A&&(vi&&(A="bevel"),"bevel"===A&&(v>2&&(A="flipbevel"),v100)a=g.mult(-1);else {const t=v*m.add(g).mag()/m.sub(g).mag();a._perp()._mult(t*(_?-1:1));}this.addCurrentVertex(f,a,0,0,p),this.addCurrentVertex(f,a.mult(-1),0,0,p);}else if("bevel"===A||"fakeround"===A){const t=-Math.sqrt(v*v-1),e=_?t:0,r=_?0:t;if(d&&this.addCurrentVertex(f,m,e,r,p),"fakeround"===A){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*h){const e=f.add(y.sub(f)._mult(h/t)._round());this.updateDistance(f,e),this.addCurrentVertex(e,g,0,0,p),f=e;}}}}addCurrentVertex(t,e,r,n,i,s=!1){const a=e.y*n-e.x,o=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,!1,r,i),this.addHalfVertex(t,a,o,s,!0,-n,i),this.distance>Du/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,r,n,i,s));}addHalfVertex({x:t,y:e},r,n,i,s,a,o){const l=.5*(this.lineClips?this.scaledDistance*(Du-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,u,this.e2),o.primitiveLength++),s?this.e2=u:this.e1=u;}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}}let Ou,Ru;as("LineBucket",Lu,{omit:["layers","patternFeatures"]});var Uu={get paint(){return Ru=Ru||new js({"line-opacity":new Ls(xt.paint_line["line-opacity"]),"line-color":new Ls(xt.paint_line["line-color"]),"line-translate":new Ds(xt.paint_line["line-translate"]),"line-translate-anchor":new Ds(xt.paint_line["line-translate-anchor"]),"line-width":new Ls(xt.paint_line["line-width"]),"line-gap-width":new Ls(xt.paint_line["line-gap-width"]),"line-offset":new Ls(xt.paint_line["line-offset"]),"line-blur":new Ls(xt.paint_line["line-blur"]),"line-dasharray":new Rs(xt.paint_line["line-dasharray"]),"line-pattern":new Os(xt.paint_line["line-pattern"]),"line-gradient":new Us(xt.paint_line["line-gradient"])})},get layout(){return Ou=Ou||new js({"line-cap":new Ds(xt.layout_line["line-cap"]),"line-join":new Ls(xt.layout_line["line-join"]),"line-miter-limit":new Ds(xt.layout_line["line-miter-limit"]),"line-round-limit":new Ds(xt.layout_line["line-round-limit"]),"line-sort-key":new Ls(xt.layout_line["line-sort-key"])})}};class ju extends Ls{possiblyEvaluate(t,e){return e=new Is(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=L({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}let Nu;class qu extends qs{constructor(t,e){super(t,Uu,e),this.gradientVersion=0,Nu||(Nu=new ju(Uu.paint.properties["line-width"].specification),Nu.useIntegerZoom=!0);}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return void 0!==t._styleExpression}(t)&&t._styleExpression.expression instanceof ar,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=Nu.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t);}createBucket(t){return new Lu(t)}queryRadius(t){const e=t,r=Gu(jo("line-width",this,e),jo("line-gap-width",this,e)),n=jo("line-offset",this,e);return r/2+Math.abs(n)+No(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a}){const o=qo(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-s.bearingInRadians,a),l=a/2*Gu(this.paint.get("line-width").evaluate(e,n),this.paint.get("line-gap-width").evaluate(e,n)),u=this.paint.get("line-offset").evaluate(e,n);return u&&(i=function(t,e){const n=[];for(let i=0;i=3)for(let e=0;e0?e+2*t:t}const Xu=Ys([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Zu=Ys([{name:"a_projected_pos",components:3,type:"Float32"}],4);Ys([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Yu=Ys([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Ys([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const Hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Ku=Ys([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Ju(t,e,r){return t.sections.forEach((t=>{t.text=function(t,e,r){const n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Ms.applyArabicShaping&&(t=Ms.applyArabicShaping(t)),t}(t.text,e,r);})),t}Ys([{name:"triangle",components:3,type:"Uint16"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Ys([{type:"Float32",name:"offsetX"}]),Ys([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Ys([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const Wu={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Qu=24;const tc=4294967296,ec=1/tc,rc="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class nc{constructor(t=new Uint8Array(16)){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length;}readFields(t,e,r=this.length){for(;this.pos>3,i=this.pos;this.type=7&r,t(n,e,this),this.pos===i&&this.skip(r);}return e}readMessage(t,e){return this.readFields(t,e,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*tc;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*tc;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const e=this.buf;let r,n;return n=e[this.pos++],r=127&n,n<128?r:(n=e[this.pos++],r|=(127&n)<<7,n<128?r:(n=e[this.pos++],r|=(127&n)<<14,n<128?r:(n=e[this.pos++],r|=(127&n)<<21,n<128?r:(n=e[this.pos],r|=(15&n)<<28,function(t,e,r){const n=r.buf;let i,s;if(s=n[r.pos++],i=(112&s)>>4,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<3,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<10,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<17,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<24,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(1&s)<<31,s<128)return ic(t,i,e);throw new Error("Expected varint not more than 10 bytes")}(r,t,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2==1?(t+1)/-2:t/2}readBoolean(){return Boolean(this.readVarint())}readString(){const t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&rc?rc.decode(this.buf.subarray(e,t)):function(t,e,r){let n="",i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+u>r)break;1===u?e<128&&(l=e):2===u?(s=t[i+1],128==(192&s)&&(l=(31&e)<<6|63&s,l<=127&&(l=null))):3===u?(s=t[i+1],a=t[i+2],128==(192&s)&&128==(192&a)&&(l=(15&e)<<12|(63&s)<<6|63&a,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===u&&(s=t[i+1],a=t[i+2],o=t[i+3],128==(192&s)&&128==(192&a)&&128==(192&o)&&(l=(15&e)<<18|(63&s)<<12|(63&a)<<6|63&o,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,u=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=u;}return n}(this.buf,e,t)}readBytes(){const t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e}readPackedVarint(t=[],e){const r=this.readPackedEnd();for(;this.pos127;);else if(2===e)this.pos=this.readVarint()+this.pos;else if(5===e)this.pos+=4;else {if(1!==e)throw new Error(`Unimplemented type: ${e}`);this.pos+=8;}}writeTag(t,e){this.writeVarint(t<<3|e);}realloc(t){let e=this.length||16;for(;e268435455||t<0?function(t,e){let r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(r=~(-t%4294967296),n=~(-t/4294967296),4294967295^r?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){const r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(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(t){this.writeVarint(t<0?2*-t-1:2*t);}writeBoolean(t){this.writeVarint(+t);}writeString(t){t=String(t),this.realloc(4*t.length),this.pos++;const e=this.pos;this.pos=function(t,e,r){for(let n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);const r=this.pos-e;r>=128&&sc(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4;}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8;}writeBytes(t){const e=t.length;this.writeVarint(e),this.realloc(e);for(let r=0;r=128&&sc(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;}writeMessage(t,e,r){this.writeTag(t,2),this.writeRawMessage(e,r);}writePackedVarint(t,e){e.length&&this.writeMessage(t,ac,e);}writePackedSVarint(t,e){e.length&&this.writeMessage(t,oc,e);}writePackedBoolean(t,e){e.length&&this.writeMessage(t,cc,e);}writePackedFloat(t,e){e.length&&this.writeMessage(t,lc,e);}writePackedDouble(t,e){e.length&&this.writeMessage(t,uc,e);}writePackedFixed32(t,e){e.length&&this.writeMessage(t,hc,e);}writePackedSFixed32(t,e){e.length&&this.writeMessage(t,pc,e);}writePackedFixed64(t,e){e.length&&this.writeMessage(t,fc,e);}writePackedSFixed64(t,e){e.length&&this.writeMessage(t,dc,e);}writeBytesField(t,e){this.writeTag(t,2),this.writeBytes(e);}writeFixed32Field(t,e){this.writeTag(t,5),this.writeFixed32(e);}writeSFixed32Field(t,e){this.writeTag(t,5),this.writeSFixed32(e);}writeFixed64Field(t,e){this.writeTag(t,1),this.writeFixed64(e);}writeSFixed64Field(t,e){this.writeTag(t,1),this.writeSFixed64(e);}writeVarintField(t,e){this.writeTag(t,0),this.writeVarint(e);}writeSVarintField(t,e){this.writeTag(t,0),this.writeSVarint(e);}writeStringField(t,e){this.writeTag(t,2),this.writeString(e);}writeFloatField(t,e){this.writeTag(t,5),this.writeFloat(e);}writeDoubleField(t,e){this.writeTag(t,1),this.writeDouble(e);}writeBooleanField(t,e){this.writeVarintField(t,+e);}}function ic(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function sc(t,e,r){const n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(let e=r.pos-1;e>=t;e--)r.buf[e+n]=r.buf[e];}function ac(t,e){for(let r=0;re.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();e&&t=0&&r>=t&&kc[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e);}substring(t,e){const r=new Sc;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}getMaxImageSize(t){let e=0,r=0;for(let n=0;n=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Ac(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=Sc.fromFeature(e,s);let g;p===t.ao.vertical&&m.verticalizePunctuation();const{processBidirectionalText:x,processStyledBidirectionalText:v}=Ms;if(x&&1===m.sections.length){g=[];const t=x(m.toString(),Bc(m,c,a,r,i,d));for(const e of t){const t=new Sc;t.text=e,t.sections=m.sections;for(let r=0;r=0;let u=0;for(let r=0;ru){const t=Math.ceil(s/u);i*=t/a,a=t;}return {x1:n,y1:i,x2:n+s,y2:i+a}}function Nc(t,e,r,n,i,s){const a=t.image;let o;if(a.content){const t=a.content,e=a.pixelRatio||1;o=[t[0]/e,t[1]/e,a.displaySize[0]-t[2]/e,a.displaySize[1]-t[3]/e];}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===r||"both"===r?(f=i[0]+l-n[3],h=i[0]+u+n[1]):(f=i[0]+(l+u-a.displaySize[0])/2,h=f+a.displaySize[0]);const d=e.top*s,y=e.bottom*s;return "height"===r||"both"===r?(c=i[1]+d-n[0],p=i[1]+y+n[2]):(c=i[1]+(d+y-a.displaySize[1])/2,p=c+a.displaySize[1]),{image:a,top:c,right:h,bottom:p,left:f,collisionPadding:o}}const qc=128,Gc=32640;function Xc(t,e){const{expression:r}=e;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new Is(t+1))};if("source"===r.kind)return {kind:"source"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;it.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];const r=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Xc(this.zoom,r["text-size"]),this.iconSizeData=Xc(this.zoom,r["icon-size"]);const n=this.layers[0].layout,i=n.get("symbol-sort-key"),s=n.get("symbol-z-order");this.canOverlap="never"!==Zc(n,"text-overlap","text-allow-overlap")||"never"!==Zc(n,"icon-overlap","icon-allow-overlap")||n.get("text-ignore-placement")||n.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!i.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===n.get("symbol-placement")&&(this.writingModes=n.get("text-writing-mode").map((e=>t.ao[e]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID;}createArrays(){this.text=new Wc(new wo(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new Wc(new wo(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new ka,this.lineVertexArray=new Ma,this.symbolInstances=new Aa,this.textAnchorOffsets=new za;}calculateGlyphDependencies(t,e,r,n,i){for(let s=0;s0)&&("constant"!==a.value.kind||a.value.value.length>0),c="constant"!==l.value.kind||!!l.value.value||Object.keys(l.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!u&&!c)return;const p=r.iconDependencies,f=r.glyphDependencies,d=r.availableImages,y=new Is(this.zoom);for(const{feature:r,id:o,index:l,sourceLayerIndex:m}of e){const e=i._featureFilter.needGeometry,g=Io(r,e);if(!i._featureFilter.filter(y,g,n))continue;let x,v;if(e||(g.geometry=Mo(r)),u){const t=i.getValueAndResolveTokens("text-field",g,n,d),e=Ce.factory(t),r=this.hasRTLText=this.hasRTLText||Jc(e);(!r||"unavailable"===Ms.getRTLTextPluginStatus()||r&&Ms.isParsed())&&(x=Ju(e,i,g));}if(c){const t=i.getValueAndResolveTokens("icon-image",g,n,d);v=t instanceof De?t:De.fromString(t);}if(!x&&!v)continue;const b=this.sortFeaturesByKey?h.evaluate(g,{},n):void 0;if(this.features.push({id:o,text:x,icon:v,index:l,sourceLayerIndex:m,geometry:g.geometry,properties:r.properties,type:du.types[r.type],sortKey:b}),v&&(p[v.name]=!0),x){const e=a.evaluate(g,{},n).join(","),r="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(t.ao.vertical)>=0;for(const t of x.sections)if(t.image)p[t.image.name]=!0;else {const n=ds(x.toString()),i=t.fontStack||e,s=f[i]=f[i]||{};this.calculateGlyphDependencies(t.text,s,r,this.allowVerticalPlacement,n);}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++;}function a(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function o(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return `${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}));}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(void 0!==t.segment){let r=t.dist(e[t.segment+1]),n=t.dist(e[t.segment]);const i={};for(let n=t.segment+1;n=0;r--)i[r]={x:e[r].x,y:e[r].y,tileUnitDistanceFromAnchor:n},r>0&&(n+=e[r-1].dist(e[r]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,r)=>{t>=0&&r.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t);})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}let eh,rh;as("SymbolBucket",th,{omit:["layers","collisionBoxArray","features","compareText"]}),th.MAX_GLYPHS=65535,th.addDynamicAttributes=Kc;var nh={get paint(){return rh=rh||new js({"icon-opacity":new Ls(xt.paint_symbol["icon-opacity"]),"icon-color":new Ls(xt.paint_symbol["icon-color"]),"icon-halo-color":new Ls(xt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Ls(xt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Ls(xt.paint_symbol["icon-halo-blur"]),"icon-translate":new Ds(xt.paint_symbol["icon-translate"]),"icon-translate-anchor":new Ds(xt.paint_symbol["icon-translate-anchor"]),"text-opacity":new Ls(xt.paint_symbol["text-opacity"]),"text-color":new Ls(xt.paint_symbol["text-color"],{runtimeType:Lt,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new Ls(xt.paint_symbol["text-halo-color"]),"text-halo-width":new Ls(xt.paint_symbol["text-halo-width"]),"text-halo-blur":new Ls(xt.paint_symbol["text-halo-blur"]),"text-translate":new Ds(xt.paint_symbol["text-translate"]),"text-translate-anchor":new Ds(xt.paint_symbol["text-translate-anchor"])})},get layout(){return eh=eh||new js({"symbol-placement":new Ds(xt.layout_symbol["symbol-placement"]),"symbol-spacing":new Ds(xt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Ds(xt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Ls(xt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Ds(xt.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new Ds(xt.layout_symbol["icon-allow-overlap"]),"icon-overlap":new Ds(xt.layout_symbol["icon-overlap"]),"icon-ignore-placement":new Ds(xt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Ds(xt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Ds(xt.layout_symbol["icon-rotation-alignment"]),"icon-size":new Ls(xt.layout_symbol["icon-size"]),"icon-text-fit":new Ds(xt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Ds(xt.layout_symbol["icon-text-fit-padding"]),"icon-image":new Ls(xt.layout_symbol["icon-image"]),"icon-rotate":new Ls(xt.layout_symbol["icon-rotate"]),"icon-padding":new Ls(xt.layout_symbol["icon-padding"]),"icon-keep-upright":new Ds(xt.layout_symbol["icon-keep-upright"]),"icon-offset":new Ls(xt.layout_symbol["icon-offset"]),"icon-anchor":new Ls(xt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Ds(xt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Ds(xt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Ds(xt.layout_symbol["text-rotation-alignment"]),"text-field":new Ls(xt.layout_symbol["text-field"]),"text-font":new Ls(xt.layout_symbol["text-font"]),"text-size":new Ls(xt.layout_symbol["text-size"]),"text-max-width":new Ls(xt.layout_symbol["text-max-width"]),"text-line-height":new Ds(xt.layout_symbol["text-line-height"]),"text-letter-spacing":new Ls(xt.layout_symbol["text-letter-spacing"]),"text-justify":new Ls(xt.layout_symbol["text-justify"]),"text-radial-offset":new Ls(xt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Ds(xt.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Ls(xt.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Ls(xt.layout_symbol["text-anchor"]),"text-max-angle":new Ds(xt.layout_symbol["text-max-angle"]),"text-writing-mode":new Ds(xt.layout_symbol["text-writing-mode"]),"text-rotate":new Ls(xt.layout_symbol["text-rotate"]),"text-padding":new Ds(xt.layout_symbol["text-padding"]),"text-keep-upright":new Ds(xt.layout_symbol["text-keep-upright"]),"text-transform":new Ls(xt.layout_symbol["text-transform"]),"text-offset":new Ls(xt.layout_symbol["text-offset"]),"text-allow-overlap":new Ds(xt.layout_symbol["text-allow-overlap"]),"text-overlap":new Ds(xt.layout_symbol["text-overlap"]),"text-ignore-placement":new Ds(xt.layout_symbol["text-ignore-placement"]),"text-optional":new Ds(xt.layout_symbol["text-optional"])})}};class ih{constructor(t){if(void 0===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:Vt,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return !1}serialize(){return null}}as("FormatSectionOverride",ih,{omit:["defaultValue"]});class sh extends qs{constructor(t,e){super(t,nh,e);}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const r of t)e.indexOf(r)<0&&e.push(r);this.layout._values["text-writing-mode"]=e;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||ei(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>t&&r in t?String(t[r]):""))}(e.properties,i)}createBucket(t){return new th(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of nh.paint.overridableProperties){if(!sh.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new ih(e),n=new ti(r,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new ni("source",n):new ii("composite",n,e.value.zoomStops),this.paint._values[t]=new Fs(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,r){return !(!this.layout||e.isDataDriven()||r.isDataDriven())&&sh.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get("text-field"),n=nh.paint.properties[e];let i=!1;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=!0)};if("constant"===r.value.kind&&r.value.value instanceof Ce)s(r.value.value.sections);else if("source"===r.value.kind||"composite"===r.value.kind){const t=e=>{i||(e instanceof Ne&&Ue(e.value)===Nt?s(e.value.sections):e instanceof Ir?s(e.sections):e.eachChild(t));},e=r.value;e._styleExpression&&t(e._styleExpression.expression);}return i}}let ah;var oh={get paint(){return ah=ah||new js({"background-color":new Ds(xt.paint_background["background-color"]),"background-pattern":new Rs(xt.paint_background["background-pattern"]),"background-opacity":new Ds(xt.paint_background["background-opacity"])})}};class lh extends qs{constructor(t,e){super(t,oh,e);}}let uh;var ch={get paint(){return uh=uh||new js({"raster-opacity":new Ds(xt.paint_raster["raster-opacity"]),"raster-hue-rotate":new Ds(xt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Ds(xt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Ds(xt.paint_raster["raster-brightness-max"]),"raster-saturation":new Ds(xt.paint_raster["raster-saturation"]),"raster-contrast":new Ds(xt.paint_raster["raster-contrast"]),"raster-resampling":new Ds(xt.paint_raster["raster-resampling"]),"raster-fade-duration":new Ds(xt.paint_raster["raster-fade-duration"])})}};class hh extends qs{constructor(t,e){super(t,ch,e);}}class ph extends qs{constructor(t,e){super(t,{},e),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},this.implementation=t;}is3D(){return "3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return !1}serialize(){throw new Error("Custom layers cannot be serialized")}}class fh{constructor(t){this._methodToThrottle=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle();});}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle();}),0));}remove(){delete this._channel,this._methodToThrottle=()=>{};}}const dh={once:!0},yh=6371008.8;class mh{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new mh(D(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return yh*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof mh)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new mh(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new mh(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const gh=2*Math.PI*yh;function xh(t){return gh*Math.cos(t*Math.PI/180)}function vh(t){return (180+t)/360}function bh(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function wh(t,e){return t/xh(e)}function _h(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}function Sh(t,e){return t*xh(_h(e))}class Ah{constructor(t,e,r=0){this.x=+t,this.y=+e,this.z=+r;}static fromLngLat(t,e=0){const r=mh.convert(t);return new Ah(vh(r.lng),bh(r.lat),wh(e,r.lat))}toLngLat(){return new mh(360*this.x-180,_h(this.y))}toAltitude(){return Sh(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/gh*(t=_h(this.y),1/Math.cos(t*Math.PI/180));var t;}}function kh(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}class Mh{constructor(t,e,r){if(!function(t,e,r){return !(t<0||t>25||r<0||r>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,r))throw new Error(`x=${e}, y=${r}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=r,this.key=Ph(0,t,t,e,r);}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,r){const n=(s=this.y,a=this.z,o=kh(256*(i=this.x),256*(s=Math.pow(2,a)-s-1),a),l=kh(256*(i+1),256*(s+1),a),o[0]+","+o[1]+","+l[0]+","+l[1]);var i,s,a,o,l;const u=function(t,e,r){let n,i="";for(let s=t;s>0;s--)n=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,n)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new r((t.x*e-this.x)*P,(t.y*e-this.y)*P)}toString(){return `${this.z}/${this.x}/${this.y}`}}class Ih{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Ph(t,e.z,e.z,e.x,e.y);}}class zh{constructor(t,e,r,n,i){if(this.terrainRttPosMatrix32f=null,t= z; overscaledZ = ${t}; z = ${r}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Mh(r,+n,+i),this.key=Ph(e,t,r,n,i);}clone(){return new zh(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new zh(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new zh(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const r=this.canonical.z-t;return t>this.canonical.z?Ph(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Ph(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}isChildOf(t){if(t.wrap!==this.wrap)return !1;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new zh(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new zh(e,this.wrap,e,r,n),new zh(e,this.wrap,e,r+1,n),new zh(e,this.wrap,e,r,n+1),new zh(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.ythis.maxX||this.minY>this.maxY)&&(this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0),this}shrinkBy(t){return this.expandBy(-t)}map(t){const e=new Eh;return e.extend(t(new r(this.minX,this.minY))),e.extend(t(new r(this.maxX,this.minY))),e.extend(t(new r(this.minX,this.maxY))),e.extend(t(new r(this.maxX,this.maxY))),e}static fromPoints(t){const e=new Eh;for(const r of t)e.extend(r);return e}contains(t){return t.x>=this.minX&&t.x<=this.maxX&&t.y>=this.minY&&t.y<=this.maxY}empty(){return this.minX>this.maxX}width(){return this.maxX-this.minX}height(){return this.maxY-this.minY}covers(t){return !this.empty()&&!t.empty()&&t.minX>=this.minX&&t.maxX<=this.maxX&&t.minY>=this.minY&&t.maxY<=this.maxY}intersects(t){return !this.empty()&&!t.empty()&&t.minX<=this.maxX&&t.maxX>=this.minX&&t.minY<=this.maxY&&t.maxY>=this.minY}}class Th{constructor(t){this._stringToNumber={},this._numberToString=[];for(let e=0;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class Bh{constructor(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}class Vh{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new is(P,16,0),this.grid3D=new is(P,16,0),this.featureIndexArray=new Ca,this.promoteId=e;}insert(t,e,r,n,i,s){const a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);const o=s?this.grid3D:this.grid;for(let t=0;t=0&&n[3]>=0&&o.insert(a,n[0],n[1],n[2],n[3]);}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new vu(new nc(this.rawTileData)).layers,this.sourceLayerCoder=new Th(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,n,i){this.loadVTLayers();const s=t.params,a=P/t.tileSize/t.scale,o=hi(s.filter,s.globalState),l=t.queryGeometry,u=t.queryPadding*a,c=Eh.fromPoints(l),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=Eh.fromPoints(t.cameraQueryGeometry).expandBy(u),f=this.grid3D.query(p.minX,p.minY,p.maxX,p.maxY,((e,n,i,s)=>function(t,e,n,i,s){for(const r of t)if(e<=r.x&&n<=r.y&&i>=r.x&&s>=r.y)return !0;const a=[new r(e,n),new r(e,s),new r(i,s),new r(i,n)];if(t.length>2)for(const e of a)if(Ro(t,e))return !0;for(let e=0;e(p||(p=Mo(e)),r.queryIntersectsFeature({queryGeometry:l,feature:e,featureState:n,geometry:p,zoom:this.z,transform:t.transform,pixelsToTileUnits:a,pixelPosMatrix:t.pixelPosMatrix,unwrappedTileID:this.tileID.toUnwrapped(),getElevation:t.getElevation}))));}return d}loadMatchingFeature(t,e,r,n,i,s,a,o,l,u,c){const h=this.bucketLayerIDs[e];if(s&&!h.some((t=>s.has(t))))return;const p=this.sourceLayerCoder.decode(r),f=this.vtLayers[p].feature(n);if(i.needGeometry){const t=Io(f,!0);if(!i.filter(new Is(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new Is(this.tileID.overscaledZ),f))return;const d=this.getId(f,p);for(let e=0;e{const a=e instanceof $s?e.get(s):null;return a&&a.evaluate?a.evaluate(r,n,i):a}))}function $h(t,e){return e-t}function Dh(t,e,n,i,s){const a=[];for(let o=0;o=i&&c.x>=i||(o.x>=i?o=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round():c.x>=i&&(c=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round()),o.y>=s&&c.y>=s||(o.y>=s?o=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round():c.y>=s&&(c=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round()),u&&o.equals(u[u.length-1])||(u=[o],a.push(u)),u.push(c)))));}}return a}as("FeatureIndex",Vh,{omit:["rawTileData","sourceLayerCoder"]});class Lh extends r{constructor(t,e,r,n){super(t,e),this.angle=r,void 0!==n&&(this.segment=n);}clone(){return new Lh(this.x,this.y,this.angle,this.segment)}}function Oh(t,e,r,n,i){if(void 0===e.segment||0===r)return !0;let s=e,a=e.segment+1,o=0;for(;o>-r/2;){if(a--,a<0)return !1;o-=t[a].dist(s),s=t[a];}o+=t[a].dist(t[a+1]),a++;const l=[];let u=0;for(;on;)u-=l.shift().angleDelta;if(u>i)return !1;a++,o+=e.dist(r);}return !0}function Rh(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=dr.number(n.x,i.x,c),p=dr.number(n.y,i.y,c),f=new Lh(h,p,i.angleTo(n),r);return f._round(),!a||Oh(t,f,o,a,e)?f:void 0}l+=s;}}function qh(t,e,r,n,i,s,a,o,l){const u=Uh(n,s,a),c=jh(n,i),h=c*a,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new Lh(g,x,y,e);r._round(),n&&!Oh(t,r,s,n,i)||f.push(r);}}h+=d;}return o||f.length||a||(f=Gh(t,h/2,r,n,i,s,a,!0,l)),f}function Xh(t,e,n,i){const s=[],a=t.image,o=a.pixelRatio,l=a.paddedRect.w-2,u=a.paddedRect.h-2;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=a.stretchX||[[0,l]],p=a.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=l-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,S=m,A=0,k=g;if(a.content&&i){const e=a.content,r=e[2]-e[0],n=e[3]-e[1];(a.textFitWidth||a.textFitHeight)&&(c=jc(t)),x=Zh(h,0,e[0]),b=Zh(p,0,e[1]),v=Zh(h,e[0],e[2]),w=Zh(p,e[1],e[3]),_=e[0]-x,A=e[1]-b,S=r-v,k=n-w;}const M=c.x1,I=c.y1,z=c.x2-M,P=c.y2-I,C=(t,i,s,l)=>{const u=Hh(t.stretch-x,v,z,M),c=Kh(t.fixed-_,S,t.stretch,d),h=Hh(i.stretch-b,w,P,I),p=Kh(i.fixed-A,k,i.stretch,y),f=Hh(s.stretch-x,v,z,M),m=Kh(s.fixed-_,S,s.stretch,d),g=Hh(l.stretch-b,w,P,I),C=Kh(l.fixed-A,k,l.stretch,y),E=new r(u,h),T=new r(f,h),B=new r(f,g),V=new r(u,g),F=new r(c/o,p/o),$=new r(m/o,C/o),D=e*Math.PI/180;if(D){const t=Math.sin(D),e=Math.cos(D),r=[e,-t,t,e];E._matMult(r),T._matMult(r),V._matMult(r),B._matMult(r);}const L=t.stretch+t.fixed,O=i.stretch+i.fixed;return {tl:E,tr:T,bl:V,br:B,tex:{x:a.paddedRect.x+1+L,y:a.paddedRect.y+1+O,w:s.stretch+s.fixed-L,h:l.stretch+l.fixed-O},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:F,pixelOffsetBR:$,minFontScaleX:S/o/z,minFontScaleY:k/o/P,isSDF:n}};if(i&&(a.stretchX||a.stretchY)){const t=Yh(h,m,d),e=Yh(p,g,y);for(let r=0;r0&&(n=Math.max(10,n),this.circleDiameter=n);}else {const u=(null===(h=a.image)||void 0===h?void 0:h.content)&&(a.image.textFitWidth||a.image.textFitHeight)?jc(a):{x1:a.left,y1:a.top,x2:a.right,y2:a.bottom};u.y1=u.y1*o-l[0],u.y2=u.y2*o+l[2],u.x1=u.x1*o-l[3],u.x2=u.x2*o+l[1];const p=a.collisionPadding;if(p&&(u.x1-=p[0]*o,u.y1-=p[1]*o,u.x2+=p[2]*o,u.y2+=p[3]*o),c){const t=new r(u.x1,u.y1),e=new r(u.x2,u.y1),n=new r(u.x1,u.y2),i=new r(u.x2,u.y2),s=c*Math.PI/180;t._rotate(s),e._rotate(s),n._rotate(s),i._rotate(s),u.x1=Math.min(t.x,e.x,n.x,i.x),u.x2=Math.max(t.x,e.x,n.x,i.x),u.y1=Math.min(t.y,e.y,n.y,i.y),u.y2=Math.max(t.y,e.y,n.y,i.y);}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,n,i,s);}this.boxEndIndex=t.length;}}class Wh{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}}function Qh(t,e=1,n=!1){const i=Eh.fromPoints(t[0]),s=Math.min(i.width(),i.height());let a=s/2;const o=new Wh([],tp),{minX:l,minY:u,maxX:c,maxY:h}=i;if(0===s)return new r(l,u);for(let e=l;ep.d||!p.d)&&(p=r,n&&console.log("found best %d after %d probes",Math.round(1e4*r.d)/1e4,f)),r.max-p.d<=e||(a=r.h/2,o.push(new ep(r.p.x-a,r.p.y-a,a,t)),o.push(new ep(r.p.x+a,r.p.y-a,a,t)),o.push(new ep(r.p.x-a,r.p.y+a,a,t)),o.push(new ep(r.p.x+a,r.p.y+a,a,t)),f+=4);}return n&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function tp(t,e){return e.max-t.max}function ep(t,e,n,i){this.p=new r(t,e),this.h=n,this.d=function(t,e){let r=!1,n=1/0;for(let i=0;it.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(r=!r),n=Math.min(n,Lo(t,i,o));}}return (r?1:-1)*Math.sqrt(n)}(this.p,i),this.max=this.d+this.h*Math.SQRT2;}var rp;t.aE=void 0,(rp=t.aE||(t.aE={}))[rp.center=1]="center",rp[rp.left=2]="left",rp[rp.right=3]="right",rp[rp.top=4]="top",rp[rp.bottom=5]="bottom",rp[rp["top-left"]=6]="top-left",rp[rp["top-right"]=7]="top-right",rp[rp["bottom-left"]=8]="bottom-left",rp[rp["bottom-right"]=9]="bottom-right";const np=Number.POSITIVE_INFINITY;function ip(t,e){return e[1]!==np?function(t,e,r){let n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case "top-right":case "top-left":case "top":i=r-7;break;case "bottom-right":case "bottom-left":case "bottom":i=7-r;}switch(t){case "top-right":case "bottom-right":case "right":n=-e;break;case "top-left":case "bottom-left":case "left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){let r=0,n=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case "top-right":case "top-left":n=i-7;break;case "bottom-right":case "bottom-left":n=7-i;break;case "bottom":n=7-e;break;case "top":n=e-7;}switch(t){case "top-right":case "bottom-right":r=-i;break;case "top-left":case "bottom-left":r=i;break;case "left":r=e;break;case "right":r=-e;}return [r,n]}(t,e[0])}function sp(t,e,r){var n;const i=t.layout,s=null===(n=i.get("text-variable-anchor-offset"))||void 0===n?void 0:n.evaluate(e,{},r);if(s){const t=s.values,e=[];for(let r=0;rt*Qu));n.startsWith("top")?i[1]-=7:n.startsWith("bottom")&&(i[1]+=7),e[r+1]=i;}return new $e(e)}const a=i.get("text-variable-anchor");if(a){let n;n=void 0!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},r)*Qu,np]:i.get("text-offset").evaluate(e,{},r).map((t=>t*Qu));const s=[];for(const t of a)s.push(t,ip(t,n));return new $e(s)}return null}function ap(t){switch(t){case "right":case "top-right":case "bottom-right":return "right";case "left":case "top-left":case "bottom-left":return "left"}return "center"}function op(e,r,n,i,s,a,o,l,u,c,h,p){let f=a.textMaxSize.evaluate(r,{});void 0===f&&(f=o);const d=e.layers[0].layout,y=d.get("icon-offset").evaluate(r,{},h),m=up(n.horizontal),g=o/24,x=e.tilePixelRatio*g,v=e.tilePixelRatio*f/24,b=e.tilePixelRatio*l,w=e.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*e.tilePixelRatio,S=function(t,e,r,n=1){const i=t.get("icon-padding").evaluate(e,{},r),s=i&&i.values;return [s[0]*n,s[1]*n,s[2]*n,s[3]*n]}(d,r,h,e.tilePixelRatio),A=d.get("text-max-angle")/180*Math.PI,k="viewport"!==d.get("text-rotation-alignment")&&"point"!==d.get("symbol-placement"),M="map"===d.get("icon-rotation-alignment")&&"point"!==d.get("symbol-placement"),I=d.get("symbol-placement"),z=w/2,C=d.get("icon-text-fit");let E;i&&"none"!==C&&(e.allowVerticalPlacement&&n.vertical&&(E=Nc(i,n.vertical,C,d.get("icon-text-fit-padding"),y,g)),m&&(i=Nc(i,m,C,d.get("icon-text-fit-padding"),y,g)));const T=h?p.line.getGranularityForZoomLevel(h.z):1,B=(l,p)=>{p.x<0||p.x>=P||p.y<0||p.y>=P||function(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k){const M=e.addToLineVertexArray(r,n);let I,z,P,C,E=0,T=0,B=0,V=0,F=-1,$=-1;const D={};let L=no("");if(e.allowVerticalPlacement&&i.vertical){const t=l.layout.get("text-rotate").evaluate(w,{},A)+90;P=new Jh(u,r,c,h,p,i.vertical,f,d,y,t),o&&(C=new Jh(u,r,c,h,p,o,g,x,y,t));}if(s){const n=l.layout.get("icon-rotate").evaluate(w,{}),i="none"!==l.layout.get("icon-text-fit"),a=Xh(s,n,S,i),f=o?Xh(o,n,S,i):void 0;z=new Jh(u,r,c,h,p,s,g,x,!1,n),E=4*a.length;const d=e.iconSizeData;let y=null;"source"===d.kind?(y=[qc*l.layout.get("icon-size").evaluate(w,{})],y[0]>Gc&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)):"composite"===d.kind&&(y=[qc*_.compositeIconSizes[0].evaluate(w,{},A),qc*_.compositeIconSizes[1].evaluate(w,{},A)],(y[0]>Gc||y[1]>Gc)&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)),e.addSymbols(e.icon,a,y,b,v,w,t.ao.none,r,M.lineStartIndex,M.lineLength,-1,A),F=e.icon.placedSymbolArray.length-1,f&&(T=4*f.length,e.addSymbols(e.icon,f,y,b,v,w,t.ao.vertical,r,M.lineStartIndex,M.lineLength,-1,A),$=e.icon.placedSymbolArray.length-1);}const O=Object.keys(i.horizontal);for(const n of O){const s=i.horizontal[n];if(!I){L=no(s.text);const t=l.layout.get("text-rotate").evaluate(w,{},A);I=new Jh(u,r,c,h,p,s,f,d,y,t);}const o=1===s.positionedLines.length;if(B+=lp(e,r,s,a,l,y,w,m,M,i.vertical?t.ao.horizontal:t.ao.horizontalOnly,o?O:[n],D,F,_,A),o)break}i.vertical&&(V+=lp(e,r,i.vertical,a,l,y,w,m,M,t.ao.vertical,["vertical"],D,$,_,A));const R=I?I.boxStartIndex:e.collisionBoxArray.length,U=I?I.boxEndIndex:e.collisionBoxArray.length,j=P?P.boxStartIndex:e.collisionBoxArray.length,N=P?P.boxEndIndex:e.collisionBoxArray.length,G=z?z.boxStartIndex:e.collisionBoxArray.length,X=z?z.boxEndIndex:e.collisionBoxArray.length,Z=C?C.boxStartIndex:e.collisionBoxArray.length,Y=C?C.boxEndIndex:e.collisionBoxArray.length;let H=-1;const K=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=K(I,H),H=K(P,H),H=K(z,H),H=K(C,H);const J=H>-1?1:0;J&&(H*=k/Qu),e.glyphOffsetArray.length>=th.MAX_GLYPHS&&q("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==w.sortKey&&e.addToSortKeyRanges(e.symbolInstances.length,w.sortKey);const W=sp(l,w,A),[Q,tt]=function(e,r){const n=e.length,i=null==r?void 0:r.values;if((null==i?void 0:i.length)>0)for(let r=0;r=0?D.right:-1,D.center>=0?D.center:-1,D.left>=0?D.left:-1,D.vertical||-1,F,$,L,R,U,j,N,G,X,Z,Y,c,B,V,E,T,J,0,f,H,Q,tt);}(e,p,l,n,i,s,E,e.layers[0],e.collisionBoxArray,r.index,r.sourceLayerIndex,e.index,x,[_,_,_,_],k,u,b,S,M,y,r,a,c,h,o);};if("line"===I)for(const t of Dh(r.geometry,0,0,P,P)){const r=ru(t,T),s=qh(r,w,A,n.vertical||m,i,24,v,e.overscaling,P);for(const t of s)m&&cp(e,m.text,z,t)||B(r,t);}else if("line-center"===I){for(const t of r.geometry)if(t.length>1){const e=ru(t,T),r=Nh(e,A,n.vertical||m,i,24,v);r&&B(e,r);}}else if("Polygon"===r.type)for(const t of Qr(r.geometry,0)){const e=Qh(t,16);B(ru(t[0],T,!0),new Lh(e.x,e.y,0));}else if("LineString"===r.type)for(const t of r.geometry){const e=ru(t,T);B(e,new Lh(e[0].x,e[0].y,0));}else if("Point"===r.type)for(const t of r.geometry)for(const e of t)B([e],new Lh(e.x,e.y,0));}function lp(t,e,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=function(t,e,n,i,s,a,o,l){const u=i.layout.get("text-rotate").evaluate(a,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const i of t.positionedGlyphs){if(!i.rect)continue;const a=i.rect||{};let h=4,p=!0,f=1,d=0;const y=(s||l)&&i.vertical,m=i.metrics.advance*i.scale/2;if(l&&e.verticalizable&&(d=t.lineOffset/2-(i.imageName?-(Qu-i.metrics.width*i.scale)/2:(i.scale-1)*Qu)),i.imageName){const t=o[i.imageName];p=t.sdf,f=t.pixelRatio,h=1/f;}const g=s?[i.x+m,i.y]:[0,0];let x=s?[0,0]:[i.x+m+n[0],i.y+n[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=i.metrics.isDoubleResolution?2:1,w=(i.metrics.left-h)*i.scale-m+x[0],_=(-i.metrics.top-h)*i.scale+x[1],S=w+a.w/b*i.scale/f,A=_+a.h/b*i.scale/f,k=new r(w,_),M=new r(S,_),I=new r(w,A),z=new r(S,A);if(y){const t=new r(-m,m- -17),e=-Math.PI/2,n=12-m,s=new r(22-n,-(i.imageName?n:0)),a=new r(...v);k._rotateAround(e,t)._add(s)._add(a),M._rotateAround(e,t)._add(s)._add(a),I._rotateAround(e,t)._add(s)._add(a),z._rotateAround(e,t)._add(s)._add(a);}if(u){const t=Math.sin(u),e=Math.cos(u),r=[e,-t,t,e];k._matMult(r),M._matMult(r),I._matMult(r),z._matMult(r);}const P=new r(0,0),C=new r(0,0);c.push({tl:k,tr:M,bl:I,br:z,tex:a,writingMode:e.writingMode,glyphOffset:g,sectionIndex:i.sectionIndex,isSDF:p,pixelOffsetTL:P,pixelOffsetBR:C,minFontScaleX:0,minFontScaleY:0});}return c}(0,n,l,s,a,o,i,t.allowVerticalPlacement),g=t.textSizeData;let x=null;"source"===g.kind?(x=[qc*s.layout.get("text-size").evaluate(o,{})],x[0]>Gc&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)):"composite"===g.kind&&(x=[qc*d.compositeTextSizes[0].evaluate(o,{},y),qc*d.compositeTextSizes[1].evaluate(o,{},y)],(x[0]>Gc||x[1]>Gc)&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)),t.addSymbols(t.text,m,x,l,a,o,c,e,u.lineStartIndex,u.lineLength,f,y);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*m.length}function up(t){for(const e in t)return t[e];return null}function cp(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=hp[15&r];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new pp(a,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=hp.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+s+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return fp(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,r,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:a}=this,o=[0,i.length-1,0],l=[];for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=a){for(let a=h;a<=c;a++){const o=s[2*a],u=s[2*a+1];o>=t&&o<=r&&u>=e&&u<=n&&l.push(i[a]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?r>=f:n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return l}within(t,e,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:n,coords:i,nodeSize:s}=this,a=[0,n.length-1,0],o=[],l=r*r;for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)gp(i[2*r],i[2*r+1],t,e)<=l&&o.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];gp(f,d,t,e)<=l&&o.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return o}}function fp(t,e,r,n,i,s){if(i-n<=r)return;const a=n+i>>1;dp(t,e,a,n,i,s),fp(t,e,r,n,a-1,1-s),fp(t,e,r,a+1,i,1-s);}function dp(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const a=i-n+1,o=r-n+1,l=Math.log(a),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(a-u)/a)*(o-a/2<0?-1:1);dp(t,e,r,Math.max(n,Math.floor(r-o*u/a+c)),Math.min(i,Math.floor(r+(a-o)*u/a+c)),s);}const a=e[2*r+s];let o=n,l=i;for(yp(t,e,n,r),e[2*i+s]>a&&yp(t,e,n,i);oa;)l--;}e[2*n+s]===a?yp(t,e,n,l):(l++,yp(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1);}}function yp(t,e,r,n){mp(t,r,n),mp(e,2*r,2*n),mp(e,2*r+1,2*n+1);}function mp(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function gp(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}var xp;t.cx=void 0,(xp=t.cx||(t.cx={})).create="create",xp.load="load",xp.fullLoad="fullLoad";let vp=null,bp=[];const wp=1e3/60,_p="loadTime",Sp="fullLoadTime",Ap={mark(t){performance.mark(t);},frame(t){const e=t;null!=vp&&bp.push(e-vp),vp=e;},clearMetrics(){vp=null,bp=[],performance.clearMeasures(_p),performance.clearMeasures(Sp);for(const e in t.cx)performance.clearMarks(t.cx[e]);},getPerformanceMetrics(){performance.measure(_p,t.cx.create,t.cx.load),performance.measure(Sp,t.cx.create,t.cx.fullLoad);const e=performance.getEntriesByName(_p)[0].duration,r=performance.getEntriesByName(Sp)[0].duration,n=bp.length,i=1/(bp.reduce(((t,e)=>t+e),0)/n/1e3),s=bp.filter((t=>t>wp)).reduce(((t,e)=>t+(e-wp)/wp),0);return {loadTime:e,fullLoadTime:r,fps:i,percentDroppedFrames:s/(n+s)*100,totalFrames:n}}};t.$=P,t.A=f,t.B=function([t,e,r]){return e+=90,e*=Math.PI/180,r*=Math.PI/180,{x:t*Math.cos(e)*Math.sin(r),y:t*Math.sin(e)*Math.sin(r),z:t*Math.cos(r)}},t.C=dr,t.D=Ds,t.E=gt,t.F=Is,t.G=ts,t.H=function(t){if(null==Z){const e=t.navigator?t.navigator.userAgent:null;Z=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return Z},t.I=vc,t.J=class{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new fh((()=>this.process())),this.subscription=Q(this.target,"message",(t=>this.receive(t)),!1),this.globalScope=X(self)?t:window;}registerMessageHandler(t,e){this.messageHandlers[t]=e;}sendAsync(t,e){return new Promise(((r,n)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10),s=e?Q(e.signal,"abort",(()=>{null==s||s.unsubscribe(),delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e);}),dh):null;this.resolveRejects[i]={resolve:t=>{null==s||s.unsubscribe(),r(t);},reject:t=>{null==s||s.unsubscribe(),n(t);}};const a=[],o=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:cs(t.data,a)});this.target.postMessage(o,{transfer:a});}))}receive(t){const e=t.data,r=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[r];const t=this.abortControllers[r];return delete this.abortControllers[r],void(t&&t.abort())}if(X(self)||e.mustQueue)return this.tasks[r]=e,this.taskQueue.push(r),void this.invoker.trigger();this.processTask(r,e);}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e);}processTask(t,r){return e(this,void 0,void 0,(function*(){if(""===r.type){const e=this.resolveRejects[t];if(delete this.resolveRejects[t],!e)return;return void(r.error?e.reject(hs(r.error)):e.resolve(hs(r.data)))}if(!this.messageHandlers[r.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${r.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const e=hs(r.data),n=new AbortController;this.abortControllers[t]=n;try{const i=yield this.messageHandlers[r.type](r.sourceMapId,e,n);this.completeTask(t,null,i);}catch(e){this.completeTask(t,e);}}))}completeTask(t,e,r){const n=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?cs(e):null,data:cs(r,n)};this.target.postMessage(i,{transfer:n});}remove(){this.invoker.remove(),this.subscription.unsubscribe();}},t.K=lt,t.L=function(){var t=new f(16);return f!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.M=function(t,e,r){var n,i,s,a,o,l,u,c,h,p,f,d,y=r[0],m=r[1],g=r[2];return e===t?(t[12]=e[0]*y+e[4]*m+e[8]*g+e[12],t[13]=e[1]*y+e[5]*m+e[9]*g+e[13],t[14]=e[2]*y+e[6]*m+e[10]*g+e[14],t[15]=e[3]*y+e[7]*m+e[11]*g+e[15]):(i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=n=e[0],t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=n*y+o*m+h*g+e[12],t[13]=i*y+l*m+p*g+e[13],t[14]=s*y+u*m+f*g+e[14],t[15]=a*y+c*m+d*g+e[15]),t},t.N=function(t,e,r){var n=r[0],i=r[1],s=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.O=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],y=e[12],m=e[13],g=e[14],x=e[15],v=r[0],b=r[1],w=r[2],_=r[3];return t[0]=v*n+b*o+w*h+_*y,t[1]=v*i+b*l+w*p+_*m,t[2]=v*s+b*u+w*f+_*g,t[3]=v*a+b*c+w*d+_*x,t[4]=(v=r[4])*n+(b=r[5])*o+(w=r[6])*h+(_=r[7])*y,t[5]=v*i+b*l+w*p+_*m,t[6]=v*s+b*u+w*f+_*g,t[7]=v*a+b*c+w*d+_*x,t[8]=(v=r[8])*n+(b=r[9])*o+(w=r[10])*h+(_=r[11])*y,t[9]=v*i+b*l+w*p+_*m,t[10]=v*s+b*u+w*f+_*g,t[11]=v*a+b*c+w*d+_*x,t[12]=(v=r[12])*n+(b=r[13])*o+(w=r[14])*h+(_=r[15])*y,t[13]=v*i+b*l+w*p+_*m,t[14]=v*s+b*u+w*f+_*g,t[15]=v*a+b*c+w*d+_*x,t},t.P=r,t.Q=function(t,e){const r={};for(let n=0;n!n.has(t.id)))),o.update&&(o.update=o.update.filter((t=>!n.has(t.id))));const i=new Set((null!==(r=t.add)&&void 0!==r?r:[]).map((t=>t.id)));e.remove=e.remove.filter((t=>!i.has(t)));}if(e.remove){const t=new Set(o.remove?o.remove.concat(e.remove):e.remove);o.remove=Array.from(t.values());}if(e.add){const t=o.add?o.add.concat(e.add):e.add,r=new Map(t.map((t=>[t.id,t])));o.add=Array.from(r.values());}if(e.update){const t=new Map(null===(n=o.update)||void 0===n?void 0:n.map((t=>[t.id,t])));for(const r of e.update){const e=null!==(i=t.get(r.id))&&void 0!==i?i:{id:r.id};r.newGeometry&&(e.newGeometry=r.newGeometry),r.addOrUpdateProperties&&(e.addOrUpdateProperties=(null!==(s=e.addOrUpdateProperties)&&void 0!==s?s:[]).concat(r.addOrUpdateProperties)),r.removeProperties&&(e.removeProperties=(null!==(a=e.removeProperties)&&void 0!==a?a:[]).concat(r.removeProperties)),r.removeAllProperties&&(e.removeAllProperties=!0),t.set(r.id,e);}o.update=Array.from(t.values());}return o.remove&&o.add&&(o.remove=o.remove.filter((t=>-1===o.add.findIndex((e=>e.id===t))))),o},t.a1=Ah,t.a2=Eh,t.a3=25,t.a4=Mh,t.a5=t=>{const e=window.document.createElement("video");return e.muted=!0,new Promise((r=>{e.onloadstart=()=>{r(e);};for(const r of t){const t=window.document.createElement("source");pt(r)||(e.crossOrigin="Anonymous"),t.src=r,e.appendChild(t);}}))},t.a6=Ct,t.a7=function(){return O++},t.a8=ba,t.a9=th,t.aA=function(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return [e,r,n,i]},t.aB=Qu,t.aC=C,t.aD=function(t,e,r,n,i=!1){if(!r[0]&&!r[1])return [0,0];const s=i?"map"===n?-t.bearingInRadians:0:"viewport"===n?t.bearingInRadians:0;if(s){const t=Math.sin(s),e=Math.cos(s);r=[r[0]*e-r[1]*t,r[0]*t+r[1]*e];}return [i?r[0]:C(e,r[0],t.zoom),i?r[1]:C(e,r[1],t.zoom)]},t.aF=Zc,t.aG=ap,t.aH=Vc,t.aI=pp,t.aJ=Ys,t.aK=Jl,t.aL=Ea,t.aM=Za,t.aN=Na,t.aO=D,t.aP=et,t.aQ=Sh,t.aR=b,t.aS=v,t.aT=function(t){var e=new f(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.aU=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t},t.aV=function(t,e){var r=e[0],n=e[1],i=e[2],s=r*r+n*n+i*i;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t},t.aW=w,t.aX=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.aY=function(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t},t.aZ=g,t.a_=function(t,e,r){const n=e[0]*r[0]+e[1]*r[1]+e[2]*r[2];return 0===n?null:(-(t[0]*r[0]+t[1]*r[1]+t[2]*r[2])-r[3])/n},t.aa=hi,t.ab=Io,t.ac=Bh,t.ad=function(t){const e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,r,n,i)=>{const s=n||i;return e[r]=!s||s.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t;}return e},t.ae=tt,t.af=function(t){return Math.pow(2,t)},t.ag=y,t.ah=$,t.ai=85.051129,t.aj=wh,t.ak=function(t){return Math.log(t)/Math.LN2},t.al=function(t){var e=t[0],r=t[1];return e*e+r*r},t.am=function(t,e){const r=[];for(const n in t)n in e||r.push(n);return r},t.an=function(t,e){let r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){const{interpolationType:i,minZoom:s,maxZoom:a}=t,o=i?$(pr.interpolationFactor(i,e,s,a),0,1):0;"camera"===t.kind?n=dr.number(t.minSize,t.maxSize,o):r=o;}return {uSizeT:r,uSize:n}},t.ap=function(t,{uSize:e,uSizeT:r},{lowerSize:n,upperSize:i}){return "source"===t.kind?n/qc:"composite"===t.kind?dr.number(n/qc,i/qc,r):e},t.aq=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],y=e[13],m=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,w=n*l-i*o,_=n*u-s*o,S=i*u-s*l,A=c*y-h*d,k=c*m-p*d,M=c*g-f*d,I=h*m-p*y,z=h*g-f*y,P=p*g-f*m,C=x*P-v*z+b*I+w*M-_*k+S*A;return C?(t[0]=(o*P-l*z+u*I)*(C=1/C),t[1]=(i*z-n*P-s*I)*C,t[2]=(y*S-m*_+g*w)*C,t[3]=(p*_-h*S-f*w)*C,t[4]=(l*M-a*P-u*k)*C,t[5]=(r*P-i*M+s*k)*C,t[6]=(m*b-d*S-g*v)*C,t[7]=(c*S-p*b+f*v)*C,t[8]=(a*z-o*M+u*A)*C,t[9]=(n*M-r*z-s*A)*C,t[10]=(d*_-y*b+g*x)*C,t[11]=(h*b-c*_-f*x)*C,t[12]=(o*k-a*I-l*A)*C,t[13]=(r*I-n*k+i*A)*C,t[14]=(y*v-d*w-m*x)*C,t[15]=(c*w-h*v+p*x)*C,t):null},t.ar=I,t.as=function(t){var e=t[0],r=t[1];return Math.sqrt(e*e+r*r)},t.at=function(t){return t[0]=0,t[1]=0,t},t.au=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t},t.av=Kc,t.aw=A,t.ax=function(t,e,n,i){const s=e.y-t.y,a=e.x-t.x,o=i.y-n.y,l=i.x-n.x,u=o*a-l*s;if(0===u)return null;const c=(l*(t.y-n.y)-o*(t.x-n.x))/u;return new r(t.x+c*a,t.y+c*s)},t.ay=Dh,t.az=Eo,t.b=Y,t.b$=class extends la{},t.b0=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t},t.b1=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]},t.b2=Ih,t.b3=Ph,t.b4=function(t,e,r,n,i){var s=1/Math.tan(e/2);if(t[0]=s/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=s,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0){var a=1/(n-i);t[10]=(i+n)*a,t[14]=2*i*n*a;}else t[10]=-1,t[14]=-2*n;return t},t.b5=function(t){var e=new f(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.b6=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[4],c=e[5],h=e[6],p=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i+u*n,t[1]=a*i+c*n,t[2]=o*i+h*n,t[3]=l*i+p*n,t[4]=u*i-s*n,t[5]=c*i-a*n,t[6]=h*i-o*n,t[7]=p*i-l*n,t},t.b7=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=s*i+u*n,t[5]=a*i+c*n,t[6]=o*i+h*n,t[7]=l*i+p*n,t[8]=u*i-s*n,t[9]=c*i-a*n,t[10]=h*i-o*n,t[11]=p*i-l*n,t},t.b8=function(){const t=new Float32Array(16);return y(t),t},t.b9=function(){const t=new Float64Array(16);return y(t),t},t.bA=function(t,e){const r=E(t,360),n=E(e,360),i=n-r,s=n>r?i-360:i+360;return Math.abs(i)0?a:-a},t.bD=function(t,e){const r=E(t,2*Math.PI),n=E(e,2*Math.PI);return Math.min(Math.abs(r-n),Math.abs(r-n+2*Math.PI),Math.abs(r-n-2*Math.PI))},t.bE=function(){const t={},e=xt.$version;for(const r in xt.$root){const n=xt.$root[r];if(n.required){let i=null;i="version"===r?e:"array"===n.type?[]:{},null!=i&&(t[r]=i);}}return t},t.bF=ps,t.bG=ct,t.bH=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(let n=0;n{"source"in t&&n[t.source]?r.push({command:"removeLayer",args:[t.id]}):s.push(t);})),r=r.concat(i),function(t,e,r){e=e||[];const n=(t=t||[]).map(zt),i=e.map(zt),s=t.reduce(Pt,{}),a=e.reduce(Pt,{}),o=n.slice(),l=Object.create(null);let u,c,h,p,f;for(let t=0,e=0;tp?(i=Math.acos(s),a=Math.sin(i),o=Math.sin((1-n)*i)/a,l=Math.sin(n*i)/a):(o=1-n,l=n),t[0]=o*u+l*d,t[1]=o*c+l*y,t[2]=o*h+l*m,t[3]=o*f+l*g,t},t.bd=function(t){const e=new Float64Array(9);var r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v;h=(i=(n=t)[0])*(l=i+i),p=(s=n[1])*l,d=(a=n[2])*l,y=a*(u=s+s),g=(o=n[3])*l,x=o*u,v=o*(c=a+a),(r=e)[0]=1-(f=s*u)-(m=a*c),r[3]=p-v,r[6]=d+x,r[1]=p+v,r[4]=1-h-m,r[7]=y-g,r[2]=d-x,r[5]=y+g,r[8]=1-h-f;const b=et(-Math.asin($(e[2],-1,1)));let w,_;return Math.hypot(e[5],e[8])<.001?(w=0,_=-et(Math.atan2(e[3],e[4]))):(w=et(0===e[5]&&0===e[8]?0:Math.atan2(e[5],e[8])),_=et(0===e[1]&&0===e[0]?0:Math.atan2(e[1],e[0]))),{roll:w,pitch:b+90,bearing:_}},t.be=function(t,e){return t.roll==e.roll&&t.pitch==e.pitch&&t.bearing==e.bearing},t.bf=Me,t.bg=uo,t.bh=Wl,t.bi=Ql,t.bj=Kl,t.bk=T,t.bl=B,t.bm=Le,t.bn=function(t,e,r,n,i){return T(n,i,$((t-e)/(r-e),0,1))},t.bo=E,t.bp=function(){return new Float64Array(3)},t.bq=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t},t.br=M,t.bs=function(t,e,r){var n=r[0],i=r[1],s=r[2],a=r[3],o=e[0],l=e[1],u=e[2],c=i*u-s*l,h=s*o-n*u,p=n*l-i*o;return t[0]=o+a*(c+=c)+i*(p+=p)-s*(h+=h),t[1]=l+a*h+s*c-n*p,t[2]=u+a*p+n*h-i*c,t},t.bt=function(t,e,r){const n=(i=[t[0],t[1],t[2],e[0],e[1],e[2],r[0],r[1],r[2]])[0]*((c=i[8])*(a=i[4])-(o=i[5])*(u=i[7]))+i[1]*(-c*(s=i[3])+o*(l=i[6]))+i[2]*(u*s-a*l);var i,s,a,o,l,u,c;if(0===n)return null;const h=w([],[e[0],e[1],e[2]],[r[0],r[1],r[2]]),p=w([],[r[0],r[1],r[2]],[t[0],t[1],t[2]]),f=w([],[t[0],t[1],t[2]],[e[0],e[1],e[2]]),d=b([],h,-t[3]);return v(d,d,b([],p,-e[3])),v(d,d,b([],f,-r[3])),b(d,d,1/n),d},t.bu=yh,t.bv=function(){return new Float64Array(4)},t.bw=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),s[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),s[2]=i[2],t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bx=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0],s[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),s[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.by=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),s[1]=i[1],s[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bz=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i-u*n,t[1]=a*i-c*n,t[2]=o*i-h*n,t[3]=l*i-p*n,t[8]=s*n+u*i,t[9]=a*n+c*i,t[10]=o*n+h*i,t[11]=l*n+p*i,t},t.c=st,t.c0=Ku,t.c1=class extends ca{},t.c2=cl,t.c3=function(t){return t<=1?1:Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},t.c4=ul,t.c5=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[3]*n+r[7]*i+r[11]*s+r[15];return t[0]=(r[0]*n+r[4]*i+r[8]*s+r[12])/(a=a||1),t[1]=(r[1]*n+r[5]*i+r[9]*s+r[13])/a,t[2]=(r[2]*n+r[6]*i+r[10]*s+r[14])/a,t},t.c6=class extends Ws{},t.c7=class extends ga{},t.c8=function(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[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]},t.c9=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=t[9],f=t[10],d=t[11],y=t[12],m=t[13],g=t[14],x=t[15],v=e[0],b=e[1],w=e[2],_=e[3],S=e[4],A=e[5],k=e[6],M=e[7],I=e[8],z=e[9],P=e[10],C=e[11],E=e[12],T=e[13],B=e[14],V=e[15];return Math.abs(r-v)<=p*Math.max(1,Math.abs(r),Math.abs(v))&&Math.abs(n-b)<=p*Math.max(1,Math.abs(n),Math.abs(b))&&Math.abs(i-w)<=p*Math.max(1,Math.abs(i),Math.abs(w))&&Math.abs(s-_)<=p*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(a-S)<=p*Math.max(1,Math.abs(a),Math.abs(S))&&Math.abs(o-A)<=p*Math.max(1,Math.abs(o),Math.abs(A))&&Math.abs(l-k)<=p*Math.max(1,Math.abs(l),Math.abs(k))&&Math.abs(u-M)<=p*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(c-I)<=p*Math.max(1,Math.abs(c),Math.abs(I))&&Math.abs(h-z)<=p*Math.max(1,Math.abs(h),Math.abs(z))&&Math.abs(f-P)<=p*Math.max(1,Math.abs(f),Math.abs(P))&&Math.abs(d-C)<=p*Math.max(1,Math.abs(d),Math.abs(C))&&Math.abs(y-E)<=p*Math.max(1,Math.abs(y),Math.abs(E))&&Math.abs(m-T)<=p*Math.max(1,Math.abs(m),Math.abs(T))&&Math.abs(g-B)<=p*Math.max(1,Math.abs(g),Math.abs(B))&&Math.abs(x-V)<=p*Math.max(1,Math.abs(x),Math.abs(V))},t.cA=function(t,e){at.REGISTERED_PROTOCOLS[t]=e;},t.cB=function(t){delete at.REGISTERED_PROTOCOLS[t];},t.cC=function(t,e){const r={};for(let n=0;nt*Qu));}let v=o?"center":n.get("text-justify").evaluate(i,{},e.canonical);const b="point"===n.get("symbol-placement")?n.get("text-max-width").evaluate(i,{},e.canonical)*Qu:1/0,w=()=>{e.bucket.allowVerticalPlacement&&ds(s)&&(d.vertical=Ac(y,e.glyphMap,e.glyphPositions,e.imagePositions,c,b,a,m,"left",f,g,t.ao.vertical,!0,p,h));};if(!o&&x){const r=new Set;if("auto"===v)for(let t=0;t0||(null===(i=r.addOrUpdateProperties)||void 0===i?void 0:i.length)>0);if((r.newGeometry||r.removeAllProperties||o)&&(e=Object.assign({},e),t.set(r.id,e),o&&(e.properties=Object.assign({},e.properties))),r.newGeometry&&(e.geometry=r.newGeometry),r.removeAllProperties)e.properties={};else if((null===(s=r.removeProperties)||void 0===s?void 0:s.length)>0)for(const t of r.removeProperties)Object.prototype.hasOwnProperty.call(e.properties,t)&&delete e.properties[t];if((null===(a=r.addOrUpdateProperties)||void 0===a?void 0:a.length)>0)for(const{key:t,value:n}of r.addOrUpdateProperties)e.properties[t]=n;}},t.cX=Ms,t.ca=function(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[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.cb=t=>"symbol"===t.type,t.cc=t=>"circle"===t.type,t.cd=t=>"heatmap"===t.type,t.ce=t=>"line"===t.type,t.cf=t=>"fill"===t.type,t.cg=t=>"fill-extrusion"===t.type,t.ch=t=>"hillshade"===t.type,t.ci=t=>"color-relief"===t.type,t.cj=t=>"raster"===t.type,t.ck=t=>"background"===t.type,t.cl=t=>"custom"===t.type,t.cm=V,t.cn=function(t,e,r){const n=z(e.x-r.x,e.y-r.y),i=z(t.x-r.x,t.y-r.y);var s,a;return et(Math.atan2(n[0]*i[1]-n[1]*i[0],(s=n)[0]*(a=i)[0]+s[1]*a[1]))},t.co=F,t.cp=function(t,e){return nt[e]&&(t instanceof MouseEvent||t instanceof WheelEvent)},t.cq=function(t,e){return rt[e]&&"touches"in t},t.cr=function(t){return rt[t]||nt[t]},t.cs=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t},t.ct=function(t,e){const{x:r,y:n}=Ah.fromLngLat(e);return !(t<0||t>25||n<0||n>=1||r<0||r>=1)},t.cu=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.cv=class extends Js{},t.cw=Ap,t.cy=function(t){return t.message===it},t.cz=ut,t.d=pt,t.e=L,t.f=t=>e(void 0,void 0,void 0,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),t.g=ot,t.h=t=>new Promise(((e,r)=>{const n=new Image;n.onload=()=>{e(n),URL.revokeObjectURL(n.src),n.onload=null,window.requestAnimationFrame((()=>{n.src=H;}));},n.onerror=()=>r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const i=new Blob([new Uint8Array(t)],{type:"image/png"});n.src=t.byteLength?URL.createObjectURL(i):H;})),t.i=X,t.j=(t,e)=>ht(L(t,{type:"json"}),e),t.k=mt,t.l=yt,t.m=ht,t.n=(t,e)=>ht(L(t,{type:"arrayBuffer"}),e),t.o=function(t){return new nc(t).readFields(yc,[])},t.p=xc,t.q=ol,t.r=js,t.s=Q,t.t=Es,t.u=fs,t.v=xt,t.w=q,t.x=Qi,t.y=ns,t.z=Wi;})); + +define("worker",["./shared"],(function(e){"use strict";class t{constructor(e,t){this.keyCache={},e&&this.replace(e,t);}replace(e,t){this._layerConfigs={},this._layers={},this.update(e,[],t);}update(t,i,o){for(const i of t){this._layerConfigs[i.id]=i;const t=this._layers[i.id]=e.bJ(i,o);t._featureFilter=e.aa(t.filter,o),this.keyCache[i.id]&&delete this.keyCache[i.id];}for(const e of i)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const s=e.cC(Object.values(this._layerConfigs),this.keyCache);for(const e of s){const t=e.map((e=>this._layers[e.id])),i=t[0];if("none"===i.visibility)continue;const o=i.source||"";let s=this.familiesBySource[o];s||(s=this.familiesBySource[o]={});const n=i.sourceLayer||"_geojsonTileLayer";let r=s[n];r||(r=s[n]=[]),r.push(t);}}}class i{constructor(t){const i={},o=[];for(const e in t){const s=t[e],n=i[e]={};for(const e in s){const t=s[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const i={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};o.push(i),n[e]={rect:i,metrics:t.metrics};}}const{w:s,h:n}=e.p(o),r=new e.q({width:s||1,height:n||1});for(const o in t){const s=t[o];for(const t in s){const n=s[+t];if(!n||0===n.bitmap.width||0===n.bitmap.height)continue;const a=i[o][t].rect;e.q.copy(n.bitmap,r,{x:0,y:0},{x:a.x+1,y:a.y+1},n.bitmap);}}this.image=r,this.positions=i;}}e.cD("GlyphAtlas",i);class o{constructor(t){this.tileID=new e.Z(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[];}parse(t,o,n,r,a){return e._(this,void 0,void 0,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.a8;const l=new e.cE(Object.keys(t.layers).sort()),c=new e.cF(this.tileID,this.promoteId);c.bucketLayerIDs=[];const u={},h={featureIndex:c,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:n,subdivisionGranularity:a},d=o.familiesBySource[this.source];for(const i in d){const o=t.layers[i];if(!o)continue;1===o.version&&e.w(`Vector tile source "${this.source}" layer "${i}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const r=l.encode(i),a=[];for(let e=0;e=i.maxzoom||"none"!==i.visibility&&(s(t,this.zoom,n),(u[i.id]=i.createBucket({index:c.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:r,sourceID:this.source})).populate(a,h,this.tileID.canonical),c.bucketLayerIDs.push(t.map((e=>e.id))));}}const f=e.bN(h.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?void 0:e.abort())),this.inFlightDependencies=[];let g=Promise.resolve({});if(Object.keys(f).length){const e=new AbortController;this.inFlightDependencies.push(e),g=r.sendAsync({type:"GG",data:{stacks:f,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const p=Object.keys(h.iconDependencies);let m=Promise.resolve({});if(p.length){const e=new AbortController;this.inFlightDependencies.push(e),m=r.sendAsync({type:"GI",data:{icons:p,source:this.source,tileID:this.tileID,type:"icons"}},e);}const y=Object.keys(h.patternDependencies);let v=Promise.resolve({});if(y.length){const e=new AbortController;this.inFlightDependencies.push(e),v=r.sendAsync({type:"GI",data:{icons:y,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const[w,x,b]=yield Promise.all([g,m,v]),S=new i(w),_=new e.cG(x,b);for(const t in u){const i=u[t];i instanceof e.a9?(s(i.layers,this.zoom,n),e.cH({bucket:i,glyphMap:w,glyphPositions:S.positions,imageMap:x,imagePositions:_.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:h.subdivisionGranularity})):i.hasPattern&&(i instanceof e.cI||i instanceof e.cJ||i instanceof e.cK)&&(s(i.layers,this.zoom,n),i.addFeatures(h,this.tileID.canonical,_.patternPositions));}return this.status="done",{buckets:Object.values(u).filter((e=>!e.isEmpty())),featureIndex:c,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:S.image,imageAtlas:_,glyphMap:this.returnDependencies?w:null,iconMap:this.returnDependencies?x:null,glyphPositions:this.returnDependencies?S.positions:null}}))}}function s(t,i,o){const s=new e.F(i);for(const e of t)e.recalculate(s,o);}class n{constructor(e,t,i){this.actor=e,this.layerIndex=t,this.availableImages=i,this.fetching={},this.loading={},this.loaded={};}loadVectorTile(t,i){return e._(this,void 0,void 0,(function*(){const o=yield e.n(t.request,i);try{return {vectorTile:new e.cL(new e.cM(o.data)),rawData:o.data,cacheControl:o.cacheControl,expires:o.expires}}catch(e){const i=new Uint8Array(o.data);let s=`Unable to parse the tile at ${t.request.url}, `;throw s+=31===i[0]&&139===i[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${e.message}`,new Error(s)}}))}loadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid,s=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.cN(t.request),n=new o(t);this.loading[i]=n;const r=new AbortController;n.abort=r;try{const o=yield this.loadVectorTile(t,r);if(delete this.loading[i],!o)return null;const a=o.rawData,l={};o.expires&&(l.expires=o.expires),o.cacheControl&&(l.cacheControl=o.cacheControl);const c={};if(s){const e=s.finish();e&&(c.resourceTiming=JSON.parse(JSON.stringify(e)));}n.vectorTile=o.vectorTile;const u=n.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);this.loaded[i]=n,this.fetching[i]={rawTileData:a,cacheControl:l,resourceTiming:c};try{const t=yield u;return e.e({rawTileData:a.slice(0)},t,l,c)}finally{delete this.fetching[i];}}catch(e){throw delete this.loading[i],n.status="done",this.loaded[i]=n,e}}))}reloadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid;if(!this.loaded||!this.loaded[i])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const o=this.loaded[i];if(o.showCollisionBoxes=t.showCollisionBoxes,"parsing"===o.status){const s=yield o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);let n;if(this.fetching[i]){const{rawTileData:t,cacheControl:o,resourceTiming:r}=this.fetching[i];delete this.fetching[i],n=e.e({rawTileData:t.slice(0)},s,o,r);}else n=s;return n}if("done"===o.status&&o.vectorTile)return o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity)}))}abortTile(t){return e._(this,void 0,void 0,(function*(){const e=this.loading,i=t.uid;e&&e[i]&&e[i].abort&&(e[i].abort.abort(),delete e[i]);}))}removeTile(t){return e._(this,void 0,void 0,(function*(){this.loaded&&this.loaded[t.uid]&&delete this.loaded[t.uid];}))}}class r{constructor(){this.loaded={};}loadTile(t){return e._(this,void 0,void 0,(function*(){const{uid:i,encoding:o,rawImageData:s,redFactor:n,greenFactor:r,blueFactor:a,baseShift:l}=t,c=s.width+2,u=s.height+2,h=e.b(s)?new e.R({width:c,height:u},yield e.cO(s,-1,-1,c,u)):s,d=new e.cP(i,h,o,n,r,a,l);return this.loaded=this.loaded||{},this.loaded[i]=d,d}))}removeTile(e){const t=this.loaded,i=e.uid;t&&t[i]&&delete t[i];}}var a,l,c=function(){if(l)return a;function e(e,i){if(0!==e.length){t(e[0],i);for(var o=1;o=Math.abs(a)?i-l+a:a-l+i,i=l;}i+o>=0!=!!t&&e.reverse();}return l=1,a=function t(i,o){var s,n=i&&i.type;if("FeatureCollection"===n)for(s=0;s>31}function v(e,t){const i=e.loadGeometry(),o=e.type;let s=0,n=0;for(const r of i){let i=1;1===o&&(i=r.length),t.writeVarint(m(1,i));const a=3===o?r.length-1:r.length;for(let e=0;ee},b=Math.fround||(S=new Float32Array(1),e=>(S[0]=+e,S[0]));var S;class _{constructor(e){this.options=Object.assign(Object.create(x),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:i,maxZoom:o}=this.options;t&&console.time("total time");const s=`prepare ${e.length} points`;t&&console.time(s),this.points=e;const n=[];for(let t=0;t=i;e--){const i=+Date.now();r=this.trees[e]=this._createTree(this._cluster(r,e)),t&&console.log("z%d: %d clusters in %dms",e,r.numItems,+Date.now()-i);}return t&&console.timeEnd("total time"),this}getClusters(e,t){let i=((e[0]+180)%360+360)%360-180;const o=Math.max(-90,Math.min(90,e[1]));let s=180===e[2]?180:((e[2]+180)%360+360)%360-180;const n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)i=-180,s=180;else if(i>s){const e=this.getClusters([i,o,180,n],t),r=this.getClusters([-180,o,s,n],t);return e.concat(r)}const r=this.trees[this._limitZoom(t)],a=r.range(k(i),P(n),k(s),P(o)),l=r.data,c=[];for(const e of a){const t=this.stride*e;c.push(l[t+5]>1?M(l,t,this.clusterProps):this.points[l[t+3]]);}return c}getChildren(e){const t=this._getOriginId(e),i=this._getOriginZoom(e),o="No cluster with the specified id.",s=this.trees[i];if(!s)throw new Error(o);const n=s.data;if(t*this.stride>=n.length)throw new Error(o);const r=this.options.radius/(this.options.extent*Math.pow(2,i-1)),a=s.within(n[t*this.stride],n[t*this.stride+1],r),l=[];for(const t of a){const i=t*this.stride;n[i+4]===e&&l.push(n[i+5]>1?M(n,i,this.clusterProps):this.points[n[i+3]]);}if(0===l.length)throw new Error(o);return l}getLeaves(e,t,i){const o=[];return this._appendLeaves(o,e,t=t||10,i=i||0,0),o}getTile(e,t,i){const o=this.trees[this._limitZoom(e)],s=Math.pow(2,e),{extent:n,radius:r}=this.options,a=r/n,l=(i-a)/s,c=(i+1+a)/s,u={features:[]};return this._addTileFeatures(o.range((t-a)/s,l,(t+1+a)/s,c),o.data,t,i,s,u),0===t&&this._addTileFeatures(o.range(1-a/s,l,1,c),o.data,s,i,s,u),t===s-1&&this._addTileFeatures(o.range(0,l,a/s,c),o.data,-1,i,s,u),u.features.length?u:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const i=this.getChildren(e);if(t++,1!==i.length)break;e=i[0].properties.cluster_id;}return t}_appendLeaves(e,t,i,o,s){const n=this.getChildren(t);for(const t of n){const n=t.properties;if(n&&n.cluster?s+n.point_count<=o?s+=n.point_count:s=this._appendLeaves(e,n.cluster_id,i,o,s):s1;let l,c,u;if(a)l=I(t,e,this.clusterProps),c=t[e],u=t[e+1];else {const i=this.points[t[e+3]];l=i.properties;const[o,s]=i.geometry.coordinates;c=k(o),u=P(s);}const h={type:1,geometry:[[Math.round(this.options.extent*(c*s-i)),Math.round(this.options.extent*(u*s-o))]],tags:l};let d;d=a||this.options.generateId?t[e+3]:this.points[t[e+3]].id,void 0!==d&&(h.id=d),n.features.push(h);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:i,extent:o,reduce:s,minPoints:n}=this.options,r=i/(o*Math.pow(2,t)),a=e.data,l=[],c=this.stride;for(let i=0;it&&(f+=a[i+5]);}if(f>d&&f>=n){let e,n=o*d,r=u*d,g=-1;const p=(i/c<<5)+(t+1)+this.points.length;for(const o of h){const l=o*c;if(a[l+2]<=t)continue;a[l+2]=t;const u=a[l+5];n+=a[l]*u,r+=a[l+1]*u,a[l+4]=p,s&&(e||(e=this._map(a,i,!0),g=this.clusterProps.length,this.clusterProps.push(e)),s(e,this._map(a,l)));}a[i+4]=p,l.push(n/f,r/f,1/0,p,-1,f),s&&l.push(g);}else {for(let e=0;e1)for(const e of h){const i=e*c;if(!(a[i+2]<=t)){a[i+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,i){if(e[t+5]>1){const o=this.clusterProps[e[t+6]];return i?Object.assign({},o):o}const o=this.points[e[t+3]].properties,s=this.options.map(o);return i&&s===o?Object.assign({},s):s}}function M(e,t,i){return {type:"Feature",id:e[t+3],properties:I(e,t,i),geometry:{type:"Point",coordinates:[(o=e[t],360*(o-.5)),T(e[t+1])]}};var o;}function I(e,t,i){const o=e[t+5],s=o>=1e4?`${Math.round(o/1e3)}k`:o>=1e3?Math.round(o/100)/10+"k":o,n=e[t+6],r=-1===n?{}:Object.assign({},i[n]);return Object.assign(r,{cluster:!0,cluster_id:e[t+3],point_count:o,point_count_abbreviated:s})}function k(e){return e/360+.5}function P(e){const t=Math.sin(e*Math.PI/180),i=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return i<0?0:i>1?1:i}function T(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function D(e,t,i,o){let s=o;const n=t+(i-t>>1);let r,a=i-t;const l=e[t],c=e[t+1],u=e[i],h=e[i+1];for(let o=t+3;os)r=o,s=t;else if(t===s){const e=Math.abs(o-n);eo&&(r-t>3&&D(e,t,r,o),e[r+2]=s,i-r>3&&D(e,r,i,o));}function C(e,t,i,o,s,n){let r=s-i,a=n-o;if(0!==r||0!==a){const l=((e-i)*r+(t-o)*a)/(r*r+a*a);l>1?(i=s,o=n):l>0&&(i+=r*l,o+=a*l);}return r=e-i,a=t-o,r*r+a*a}function L(e,t,i,o){const s={id:null==e?null:e,type:t,geometry:i,tags:o,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===t||"MultiPoint"===t||"LineString"===t)O(s,i);else if("Polygon"===t)O(s,i[0]);else if("MultiLineString"===t)for(const e of i)O(s,e);else if("MultiPolygon"===t)for(const e of i)O(s,e[0]);return s}function O(e,t){for(let i=0;i0&&(r+=o?(s*l-a*n)/2:Math.sqrt(Math.pow(a-s,2)+Math.pow(l-n,2))),s=a,n=l;}const a=t.length-3;t[2]=1,D(t,0,a,i),t[a+2]=1,t.size=Math.abs(r),t.start=0,t.end=t.size;}function G(e,t,i,o){for(let s=0;s1?1:i}function j(e,t,i,o,s,n,r,a){if(o/=t,n>=(i/=t)&&r=o)return null;const l=[];for(const t of e){const e=t.geometry;let n=t.type;const r=0===s?t.minX:t.minY,c=0===s?t.maxX:t.maxY;if(r>=i&&c=o)continue;let u=[];if("Point"===n||"MultiPoint"===n)N(e,u,i,o,s);else if("LineString"===n)R(e,u,i,o,s,!1,a.lineMetrics);else if("MultiLineString"===n)J(e,u,i,o,s,!1);else if("Polygon"===n)J(e,u,i,o,s,!0);else if("MultiPolygon"===n)for(const t of e){const e=[];J(t,e,i,o,s,!0),e.length&&u.push(e);}if(u.length){if(a.lineMetrics&&"LineString"===n){for(const e of u)l.push(L(t.id,n,e,t.tags));continue}"LineString"!==n&&"MultiLineString"!==n||(1===u.length?(n="LineString",u=u[0]):n="MultiLineString"),"Point"!==n&&"MultiPoint"!==n||(n=3===u.length?"Point":"MultiPoint"),l.push(L(t.id,n,u,t.tags));}}return l.length?l:null}function N(e,t,i,o,s){for(let n=0;n=i&&r<=o&&Y(t,e[n],e[n+1],e[n+2]);}}function R(e,t,i,o,s,n,r){let a=W(e);const l=0===s?q:X;let c,u,h=e.start;for(let d=0;di&&(u=l(a,f,g,m,y,i),r&&(a.start=h+c*u)):v>o?w=i&&(u=l(a,f,g,m,y,i),x=!0),w>o&&v<=o&&(u=l(a,f,g,m,y,o),x=!0),!n&&x&&(r&&(a.end=h+c*u),t.push(a),a=W(e)),r&&(h+=c);}let d=e.length-3;const f=e[d],g=e[d+1],p=0===s?f:g;p>=i&&p<=o&&Y(a,f,g,e[d+2]),d=a.length-3,n&&d>=3&&(a[d]!==a[0]||a[d+1]!==a[1])&&Y(a,a[0],a[1],a[2]),a.length&&t.push(a);}function W(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function J(e,t,i,o,s,n){for(const r of e)R(r,t,i,o,s,n,!1);}function Y(e,t,i,o){e.push(t,i,o);}function q(e,t,i,o,s,n){const r=(n-t)/(o-t);return Y(e,n,i+(s-i)*r,1),r}function X(e,t,i,o,s,n){const r=(n-i)/(s-i);return Y(e,t+(o-t)*r,n,1),r}function H(e,t){const i=[];for(let o=0;o0&&t.size<(s?r:o))return void(i.numPoints+=t.length/3);const a=[];for(let e=0;er)&&(i.numSimplified++,a.push(t[e],t[e+1])),i.numPoints++;s&&function(e,t){let i=0;for(let t=0,o=e.length,s=o-2;t0===t)for(let t=0,i=e.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");let o=function(e,t){const i=[];if("FeatureCollection"===e.type)for(let o=0;o1&&console.time("creation"),d=this.tiles[h]=U(e,t,i,o,l),this.tileCoords.push({z:t,x:i,y:o}),c)){c>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,i,o,d.numFeatures,d.numPoints,d.numSimplified),console.timeEnd("creation"));const e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++;}if(d.source=e,null==s){if(t===l.indexMaxZoom||d.numPoints<=l.indexMaxPoints)continue}else {if(t===l.maxZoom||t===s)continue;if(null!=s){const e=s-t;if(i!==n>>e||o!==r>>e)continue}}if(d.source=null,0===e.length)continue;c>1&&console.time("clipping");const f=.5*l.buffer/l.extent,g=.5-f,p=.5+f,m=1+f;let y=null,v=null,w=null,x=null,b=j(e,u,i-f,i+p,0,d.minX,d.maxX,l),S=j(e,u,i+g,i+m,0,d.minX,d.maxX,l);e=null,b&&(y=j(b,u,o-f,o+p,1,d.minY,d.maxY,l),v=j(b,u,o+g,o+m,1,d.minY,d.maxY,l),b=null),S&&(w=j(S,u,o-f,o+p,1,d.minY,d.maxY,l),x=j(S,u,o+g,o+m,1,d.minY,d.maxY,l),S=null),c>1&&console.timeEnd("clipping"),a.push(y||[],t+1,2*i,2*o),a.push(v||[],t+1,2*i,2*o+1),a.push(w||[],t+1,2*i+1,2*o),a.push(x||[],t+1,2*i+1,2*o+1);}}getTile(e,t,i){e=+e,t=+t,i=+i;const o=this.options,{extent:s,debug:n}=o;if(e<0||e>24)return null;const r=1<1&&console.log("drilling down to z%d-%d-%d",e,t,i);let l,c=e,u=t,h=i;for(;!l&&c>0;)c--,u>>=1,h>>=1,l=this.tiles[ie(c,u,h)];return l&&l.source?(n>1&&(console.log("found parent tile z%d-%d-%d",c,u,h),console.time("drilling down")),this.splitTile(l.source,c,u,h,e,t,i),n>1&&console.timeEnd("drilling down"),this.tiles[a]?B(this.tiles[a],s):null):null}}function ie(e,t,i){return 32*((1<{r.properties=e;const t={};for(const e of a)t[e]=o[e].evaluate(n,r);return t},t.reduce=(e,t)=>{r.properties=t;for(const t of a)n.accumulated=e[t],e[t]=s[t].evaluate(n,r);},t}(t)).load(i.features):function(e,t){return new te(e,t)}(i,t.geojsonVtOptions),this.loaded={};const s={data:i};if(o){const e=o.finish();e&&(s.resourceTiming={},s.resourceTiming[t.source]=JSON.parse(JSON.stringify(e)));}return s}catch(t){if(delete this._pendingRequest,e.cy(t))return {abandoned:!0};throw t}}))}getData(){return e._(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(e){const t=this.loaded;return t&&t[e.uid]?super.reloadTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){let o=yield this.loadGeoJSON(t,i);if(delete this._pendingRequest,"object"!=typeof o)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(u(o,!0),t.filter){const i=e.cT(t.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===i.result)throw new Error(i.value.map((e=>`${e.key}: ${e.message}`)).join(", "));const s=o.features.filter((e=>i.value.evaluate({zoom:0},e)));o={type:"FeatureCollection",features:s};}return o}))}loadGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){const{promoteId:o}=t;if(t.request){const s=yield e.j(t.request,i);return this._dataUpdateable=e.cV(s.data,o)?e.cU(s.data,o):void 0,s.data}if("string"==typeof t.data)try{const i=JSON.parse(t.data);return this._dataUpdateable=e.cV(i,o)?e.cU(i,o):void 0,i}catch(e){throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}if(!t.dataDiff)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${t.source}`);return e.cW(this._dataUpdateable,t.dataDiff,o),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(t){return e._(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset)}}class se{constructor(t){this.self=t,this.actor=new e.J(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=new Map,this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.cA,this.self.removeProtocol=e.cB,this.self.registerRTLTextPlugin=t=>{e.cX.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,i)=>e._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(t,i.source).removeTile(i);})))),this.actor.registerMessageHandler("GCEZ",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterExpansionZoom(i)})))),this.actor.registerMessageHandler("GCC",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterChildren(i)})))),this.actor.registerMessageHandler("GCL",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterLeaves(i)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("GD",((e,t)=>this._getWorkerSource(e,t.type,t.source).getData())),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,i)=>e._(this,void 0,void 0,(function*(){if(!this.workerSources[t]||!this.workerSources[t][i.type]||!this.workerSources[t][i.type][i.source])return;const e=this.workerSources[t][i.type][i.source];delete this.workerSources[t][i.type][i.source],void 0!==e.removeSource&&e.removeSource(i);})))),this.actor.registerMessageHandler("RM",(t=>e._(this,void 0,void 0,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t],this.globalStates.delete(t);})))),this.actor.registerMessageHandler("SR",((t,i)=>e._(this,void 0,void 0,(function*(){this.referrer=i;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,i)=>e._(this,void 0,void 0,(function*(){this.self.importScripts(i);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).update(i.layers,i.removedIds,this._getGlobalState(t));})))),this.actor.registerMessageHandler("UGS",((t,i)=>e._(this,void 0,void 0,(function*(){const e=this._getGlobalState(t);for(const t in i)e[t]=i[t];})))),this.actor.registerMessageHandler("SL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).replace(i,this._getGlobalState(t));}))));}_getGlobalState(e){let t=this.globalStates.get(e);return t||(t={},this.globalStates.set(e,t)),t}_setImages(t,i){return e._(this,void 0,void 0,(function*(){this.availableImages[t]=i;for(const e in this.workerSources[t]){const o=this.workerSources[t][e];for(const e in o)o[e].availableImages=i;}}))}_syncRTLPluginState(t,i){return e._(this,void 0,void 0,(function*(){return yield e.cX.syncState(i,this.self.importScripts)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(e){let i=this.layerIndexes[e];return i||(i=this.layerIndexes[e]=new t),i}_getWorkerSource(e,t,i){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][i]){const o={sendAsync:(t,i)=>(t.targetMapId=e,this.actor.sendAsync(t,i))};switch(t){case "vector":this.workerSources[e][t][i]=new n(o,this._getLayerIndex(e),this._getAvailableImages(e));break;case "geojson":this.workerSources[e][t][i]=new oe(o,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][i]=new this.externalWorkerSourceTypes[t](o,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][t][i]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new r),this.demWorkerSources[e][t]}}return e.i(self)&&(self.worker=new se(self)),se})); + +define("index",["exports","./shared"],(function(e,t){"use strict";var i="5.7.2";function o(){var e=new t.A(4);return t.A!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}let r,a;const s={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frame(e,i,o){const r=requestAnimationFrame((e=>{a(),i(e);})),{unsubscribe:a}=t.s(e.signal,"abort",(()=>{a(),cancelAnimationFrame(r),o(t.c());}),!1);},frameAsync(e){return new Promise(((t,i)=>{this.frame(e,t,i);}))},getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(r||(r=document.createElement("a")),r.href=e,r.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==a&&(a=matchMedia("(prefers-reduced-motion: reduce)")),a.matches)}};class n{static testProp(e){if(!n.docStyle)return e[0];for(let t=0;t{window.removeEventListener("click",n.suppressClickInternal,!0);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,o){const r=i.boundingClientRect;return new t.P((o.clientX-r.left)/i.x-e.clientLeft,(o.clientY-r.top)/i.y-e.clientTop)}static mousePos(e,t){const i=n.getScale(e);return n.getPoint(e,i,t)}static touchPos(e,t){const i=[],o=n.getScale(e);for(let r=0;r{c&&_(c),c=null,d=!0;},h.onerror=()=>{u=!0,c=null;},h.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(e){let i,o,r,a;e.resetRequestQueue=()=>{i=[],o=0,r=0,a={};},e.addThrottleControl=e=>{const t=r++;return a[t]=e,t},e.removeThrottleControl=e=>{delete a[e],n();},e.getImage=(e,o,r=!0)=>new Promise(((a,s)=>{l.supported&&(e.headers||(e.headers={}),e.headers.accept="image/webp,*/*"),t.e(e,{type:"image"}),i.push({abortController:o,requestParameters:e,supportImageRefresh:r,state:"queued",onError:e=>{s(e);},onSuccess:e=>{a(e);}}),n();}));const s=e=>t._(this,void 0,void 0,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:r,onError:a,onSuccess:s,abortController:l}=e,h=!1===r&&!t.i(self)&&!t.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),!0));o++;const u=h?c(i,l):t.m(i,l);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.b(i.data)?s(i):i.data&&s({data:yield(d=i.data,"function"==typeof createImageBitmap?t.f(d):t.h(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,a(t);}finally{o--,n();}var d;})),n=()=>{const e=(()=>{for(const e of Object.keys(a))if(a[e]())return !0;return !1})()?t.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=o;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:s(e);}},c=(e,i)=>new Promise(((o,r)=>{const a=new Image,s=e.url,n=e.credentials;n&&"include"===n?a.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.d(s))&&(a.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{a.src="",r(t.c());})),a.fetchPriority="high",a.onload=()=>{a.onerror=a.onload=null,o({data:a});},a.onerror=()=>{a.onerror=a.onload=null,i.signal.aborted||r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));},a.src=s;}));}(p||(p={})),p.resetRequestQueue();class m{constructor(e){this._transformRequestFn=null!=e?e:null;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}function f(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:o,url:r}of e){const e=`${o}${r}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:o,url:r}));}}return t}function g(e,t,i){try{const o=new URL(e);return o.pathname+=`${t}${i}`,o.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}function v(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class b extends t.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.R({width:1,height:1}),this.dirty=!0;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.R({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let o=!0;const r=i.data||i.spriteData;return this._validateStretch(i.stretchX,r&&r.width)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchX" value`))),o=!1),this._validateStretch(i.stretchY,r&&r.height)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchY" value`))),o=!1),this._validateContent(i.content,i)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "content" value`))),o=!1),o}_validateStretch(e,t){if(!e)return !0;let i=0;for(const o of e){if(o[0]{let o=!0;if(!this.isLoaded())for(const t of e)this.images[t]||(o=!1);this.isLoaded()||o?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const o of e){let e=this.getImage(o);e||(this.fire(new t.l("styleimagemissing",{id:o})),e=this.getImage(o)),e?i[o]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.w(`Image "${o}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);}return i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],o=this.getImage(e);if(!o)return null;if(i&&i.position.version===o.version)return i.position;if(i)i.position.version=o.version;else {const i={w:o.data.width+2,h:o.data.height+2,x:0,y:0},r=new t.I(i,o);this.patterns[e]={bin:i,position:r};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const i=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new t.T(e,this.atlasImage,i.RGBA),this.atlasTexture.bind(i.LINEAR,i.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:o}=t.p(e),r=this.atlasImage;r.resize({width:i||1,height:o||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],o=i.x+1,a=i.y+1,s=this.getImage(e).data,n=s.width,l=s.height;t.R.copy(s,r,{x:0,y:0},{x:o,y:a},{width:n,height:l}),t.R.copy(s,r,{x:0,y:l-1},{x:o,y:a-1},{width:n,height:1}),t.R.copy(s,r,{x:0,y:0},{x:o,y:a+l},{width:n,height:1}),t.R.copy(s,r,{x:n-1,y:0},{x:o-1,y:a},{width:1,height:l}),t.R.copy(s,r,{x:0,y:0},{x:o+n,y:a},{width:1,height:l});}this.dirty=!0;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=!0;const e=this.getImage(i);e||t.w(`Image with ID: "${i}" was not found`),v(e)&&this.updateImage(i,e);}}}const x=1e20;function y(e,t,i,o,r,a,s,n,l){for(let c=t;c-1);l++,a[l]=n,s[l]=c,s[l+1]=x;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(t.ranges[r])return {stack:e,id:i,glyph:o};if(!this.url)throw new Error("glyphsUrl is not set");if(!t.requests[r]){const i=T.loadGlyphRange(e,r,this.url,this.requestManager);t.requests[r]=i;}const a=yield t.requests[r];for(const e in a)this._doesCharSupportLocalGlyph(+e)||(t.glyphs[+e]=a[+e]);return t.ranges[r]=!0,{stack:e,id:i,glyph:a[i]||null}}))}_doesCharSupportLocalGlyph(e){return !!this.localIdeographFontFamily&&(/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(e))||t.u["CJK Unified Ideographs"](e)||t.u["Hangul Syllables"](e)||t.u.Hiragana(e)||t.u.Katakana(e)||t.u["CJK Symbols and Punctuation"](e)||t.u["Halfwidth and Fullwidth Forms"](e))}_tinySDF(e,i,o){const r=this.localIdeographFontFamily;if(!r)return;if(!this._doesCharSupportLocalGlyph(o))return;let a=e.tinySDF;if(!a){let t="400";/bold/i.test(i)?t="900":/medium/i.test(i)?t="500":/light/i.test(i)&&(t="200"),a=e.tinySDF=new T.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,lang:this.lang,fontFamily:r,fontWeight:t});}const s=a.draw(String.fromCharCode(o));return {id:o,bitmap:new t.q({width:s.width||60,height:s.height||60},s.data),metrics:{width:s.glyphWidth/2||24,height:s.glyphHeight/2||24,left:s.glyphLeft/2+.5||0,top:s.glyphTop/2-27.5||-8,advance:s.glyphAdvance/2||24,isDoubleResolution:!0}}}}T.loadGlyphRange=function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=256*i,s=a+255,n=r.transformRequest(o.replace("{fontstack}",e).replace("{range}",`${a}-${s}`),"Glyphs"),l=yield t.n(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${a}-${s}`);const c={};for(const e of t.o(l.data))c[e.id]=e;return c}))},T.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:o=.25,fontFamily:r="sans-serif",fontWeight:a="normal",fontStyle:s="normal",lang:n=null}={}){this.buffer=t,this.cutoff=o,this.radius=i,this.lang=n;const l=this.size=e+4*t,c=this._createCanvas(l),h=this.ctx=c.getContext("2d",{willReadFrequently:!0});h.font=`${s} ${a} ${e}px ${r}`,h.textBaseline="alphabetic",h.textAlign="left",h.fillStyle="black",this.gridOuter=new Float64Array(l*l),this.gridInner=new Float64Array(l*l),this.f=new Float64Array(l),this.z=new Float64Array(l+1),this.v=new Uint16Array(l);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:o,actualBoundingBoxLeft:r,actualBoundingBoxRight:a}=this.ctx.measureText(e),s=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(a-r))),l=Math.min(this.size-this.buffer,s+Math.ceil(o)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:s,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;this.lang&&(p.lang=this.lang),p.clearRect(m,m,n,l),p.fillText(e,m,m+s);const v=p.getImageData(m,m,n,l);g.fill(x,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[o]=e<0?e*e:0;}}y(g,0,0,c,h,c,this.f,this.v,this.z),y(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(s=e[++a]);const l=Math.abs(n-s.left),c=Math.abs(n-s.right),h=Math.min(l,c);let u;const d=t/i*(o+1);if(s.isDash){const e=o-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=o-Math.sqrt(h*h+d*d);this.data[r+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],o=e[t+1];i.zeroLength?e.splice(t,1):o&&o.isDash===i.isDash&&(o.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const o=this.width*this.nextRow;let r=0,a=e[r];for(let t=0;t1&&(a=e[++r]);const i=Math.abs(t-a.left),s=Math.abs(t-a.right),n=Math.min(i,s);this.data[o+t]=Math.max(0,Math.min(255,(a.isDash?n:-n)+128));}}addDash(e,i){const o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.w("LineAtlas out of space"),null;let a=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[R]}numActive(){return Object.keys(this.active).length}}const D=Math.floor(s.hardwareConcurrency/2);let A,L;function k(){return A||(A=new z),A}z.workerCount=t.H(globalThis)?Math.max(Math.min(D,3),1):1;class F{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const o=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}}function B(){return L||(L=new F(k(),t.K),L.registerMessageHandler("GR",((e,i,o)=>t.m(i,o)))),L}function O(e,i){const o=t.L();return t.M(o,o,[1,1,0]),t.N(o,o,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.O(o,o,e.calculatePosMatrix(i.toUnwrapped())):o}function j(e,t,i,o,r,a,s){var n;const l=function(e,t,i){if(e)for(const o of e){const e=t[o];if(e&&e.source===i&&"fill-extrusion"===e.type)return !0}else for(const e in t){const o=t[e];if(o.source===i&&"fill-extrusion"===o.type)return !0}return !1}(null!==(n=null==r?void 0:r.layers)&&void 0!==n?n:null,t,e.id),c=a.maxPitchScaleFactor(),h=e.tilesIn(o,c,l);h.sort(N);const u=[];for(const o of h)u.push({wrappedTileID:o.tileID.wrapped().key,queryResults:o.tile.queryRenderedFeatures(t,i,e._state,o.queryGeometry,o.cameraQueryGeometry,o.scale,r,a,c,O(e.transform,o.tileID),s?(e,t)=>s(o.tileID,e,t):void 0)});return function(e,t){for(const i in e)for(const o of e[i])U(o,t);return e}(function(e){const t={},i={};for(const o of e){const e=o.queryResults,r=o.wrappedTileID,a=i[r]=i[r]||{};for(const i in e){const o=e[i],r=a[i]=a[i]||{},s=t[i]=t[i]||[];for(const e of o)r[e.featureIndex]||(r[e.featureIndex]=!0,s.push(e));}}return t}(u),e)}function N(e,t){const i=e.tileID,o=t.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}function U(e,t){const i=e.feature,o=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=o;}function Z(e,i,o){return t._(this,void 0,void 0,(function*(){let r=e;if(e.url?r=(yield t.j(i.transformRequest(e.url,"Source"),o)).data:yield s.frameAsync(o),!r)return null;const a=t.Q(t.e(r,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in r&&r.vector_layers&&(a.vectorLayerIds=r.vector_layers.map((e=>e.id))),a}))}class G{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}extend(e){const i=this._sw,o=this._ne;let r,a;if(e instanceof t.S)r=e,a=e;else {if(!(e instanceof G))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(G.convert(e)):this.extend(t.S.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.S.convert(e)):this;if(r=e._sw,a=e._ne,!r||!a)return this}return i||o?(i.lng=Math.min(r.lng,i.lng),i.lat=Math.min(r.lat,i.lat),o.lng=Math.max(a.lng,o.lng),o.lat=Math.max(a.lat,o.lat)):(this._sw=new t.S(r.lng,r.lat),this._ne=new t.S(a.lng,a.lat)),this}getCenter(){return new t.S((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new t.S(this.getWest(),this.getNorth())}getSouthEast(){return new t.S(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(e){const{lng:i,lat:o}=t.S.convert(e);let r=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(r=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=o&&o<=this._ne.lat&&r}static convert(e){return e instanceof G?e:e?new G(e):e}static fromLngLat(e,i=0){const o=360*i/40075017,r=o/Math.cos(Math.PI/180*e.lat);return new G(new t.S(e.lng-r,e.lat-o),new t.S(e.lng+r,e.lat+o))}adjustAntiMeridian(){const e=new t.S(this._sw.lng,this._sw.lat),i=new t.S(this._ne.lng,this._ne.lat);return new G(e,e.lng>i.lng?new t.S(i.lng+360,i.lat):i)}}class V{constructor(e,t,i){this.bounds=G.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),o=Math.floor(t.V(this.bounds.getWest())*i),r=Math.floor(t.U(this.bounds.getNorth())*i),a=Math.ceil(t.V(this.bounds.getEast())*i),s=Math.ceil(t.U(this.bounds.getSouth())*i);return e.x>=o&&e.x=r&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.e({},this._options)}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};i.request.collectResourceTiming=this._collectResourceTiming;let o="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),o="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:o,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_afterTileLoadWorkerResponse(e,t){if(t&&t.resourceTiming&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return !1}}class q extends t.E{constructor(e,i,o,r){super(),this.id=e,this.dispatcher=o,this.setEventedParent(r),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.e({type:"raster"},i),t.e(this,t.Q(i,["url","scheme","tileSize"]));}load(){return t._(this,arguments,void 0,(function*(e=!1){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield Z(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,i&&(t.e(this,i),i.bounds&&(this.tileBounds=new V(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.l("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(!0);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.e({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const o=yield p.getImage(this.map._requestManager.transformRequest(i,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(o&&o.data){this.map._refreshExpiredTiles&&(o.cacheControl||o.expires)&&e.setExpiryData({cacheControl:o.cacheControl,expires:o.expires});const i=this.map.painter.context,r=i.gl,a=o.data;e.texture=this.map.painter.getTileTexture(a.width),e.texture?e.texture.update(a,{useMipmap:!0}):(e.texture=new t.T(i,a,r.RGBA,{useMipmap:!0}),e.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return !1}}class W extends q{constructor(e,i,o,r){super(e,i,o,r),this.type="raster-dem",this.maxzoom=22,this._options=t.e({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),o=this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield p.getImage(o,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const o=i.data;this.map._refreshExpiredTiles&&(i.cacheControl||i.expires)&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const r=t.b(o)&&t.W()?o:yield this.readImageNow(o),a={type:this.type,uid:e.uid,source:this.id,rawImageData:r,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!e.actor||"expired"===e.state){e.actor=this.dispatcher.getActor();const t=yield e.actor.sendAsync({type:"LDT",data:a});e.dem=t,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t._(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&t.X()){const i=e.width+2,o=e.height+2;try{return new t.R({width:i,height:o},yield t.Y(e,-1,-1,i,o))}catch(e){}}return s.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,o=Math.pow(2,i.z),r=(i.x-1+o)%o,a=0===i.x?e.wrap-1:e.wrap,s=(i.x+1+o)%o,n=i.x+1===o?e.wrap+1:e.wrap,l={};return l[new t.Z(e.overscaledZ,a,i.z,r,i.y).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y).key]={backfilled:!1},i.y>0&&(l[new t.Z(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y-1).key]={backfilled:!1}),i.y+1e.coordinates)).flat(1/0):e.coordinates.flat(1/0)}getBounds(){return t._(this,void 0,void 0,(function*(){const e=new G,t=yield this.getData();let i;switch(t.type){case "FeatureCollection":i=t.features.map((e=>this.getCoordinatesFromGeometry(e.geometry))).flat(1/0);break;case "Feature":i=this.getCoordinatesFromGeometry(t.geometry);break;default:i=this.getCoordinatesFromGeometry(t);}if(0==i.length)return e;for(let t=0;t0&&t.e(r,{resourceTiming:i}),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"metadata"}))),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"content"})));}catch(e){if(this._isUpdatingWorker=!1,this._removed)return void this.fire(new t.l("dataabort",{dataType:"source"}));this.fire(new t.k(e));}finally{(this._pendingWorkerUpdate.data||this._pendingWorkerUpdate.diff)&&this._updateWorkerData();}}))}loaded(){return !this._isUpdatingWorker&&void 0===this._pendingWorkerUpdate.data&&void 0===this._pendingWorkerUpdate.diff}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};e.abortController=new AbortController;const o=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(o,this.map.painter,"RT"===t);}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=!0;}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return !1}}class X extends t.E{constructor(e,t,i,o){super(),this.flippedWindingOrder=!1,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(o),this.options=t;}load(e){return t._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield p.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.a1.fromLngLat);var o;return this.tileID=function(e){const i=t.a2.fromPoints(e),o=i.width(),r=i.height(),a=Math.max(o,r),s=Math.max(0,Math.floor(-Math.log(a)/Math.LN2)),n=Math.pow(2,s);return new t.a4(s,Math.floor((i.minX+i.maxX)/2*n),Math.floor((i.minY+i.maxY)/2*n))}(i),this.terrainTileRanges=this._getOverlappingTileRanges(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((o=this.tileCoords)[1].x-o[0].x)*(o[2].y-o[0].y)-(o[1].y-o[0].y)*(o[2].x-o[0].x)<0,this.fire(new t.l("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new t.T(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t._(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return !1}_getOverlappingTileRanges(e){const{minX:i,minY:o,maxX:r,maxY:a}=t.a2.fromPoints(e),s={};for(let e=0;e<=t.a3;e++){const t=Math.pow(2,e),n=Math.floor(i*t),l=Math.floor(o*t),c=Math.floor(r*t),h=Math.floor(a*t);s[e]={minTileX:n,minTileY:l,maxTileX:c,maxTileY:h};}return s}}class K extends X{constructor(e,t,i,o){super(e,t,i,o),this.roundZoom=!0,this.type="video",this.options=t;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!1;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,"Source").url);try{const e=yield t.a5(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.k(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.k(new t.a6(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.T(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class Y extends X{constructor(e,i,o,r){super(e,i,o,r),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.k(new t.a6(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.k(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,o=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.T(i,this.canvas,o.RGBA,{premultiply:!0});let r=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=!0);}r&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return !0;return !1}}const Q={},J=e=>{switch(e){case "geojson":return H;case "image":return X;case "raster":return q;case "raster-dem":return W;case "vector":return $;case "video":return K;case "canvas":return Y}return Q[e]},ee="RTLPluginLoaded";class te extends t.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=B();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t._(this,arguments,void 0,(function*(e,t=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=s.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.l(ee));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let ie=null;function oe(){return ie||(ie=new te),ie}class re{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=e,this.uid=t.a7(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(e){const t=e+this.timeAdded;tt.getLayer(e))).filter(Boolean);if(0!==e.length){o.layers=e,o.stateDependentLayerIds&&(o.stateDependentLayers=o.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=o;}}return i}(e.buckets,null==i?void 0:i.style),this.hasSymbolBuckets=!1;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9){if(this.hasSymbolBuckets=!0,!o)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9&&i.hasRTLText){this.hasRTLText=!0,oe().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.a8;}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const i=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new t.T(e,this.imageAtlas.image,i.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new t.T(e,this.glyphAtlasImage,i.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,o,r,a,s,n,l,c,h){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:o,cameraQueryGeometry:r,scale:a,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:s,queryPadding:this.queryPadding*l,getElevation:h},e,t,i):{}}querySourceFeatures(e,i){const o=this.latestFeatureIndex;if(!o||!o.rawTileData)return;const r=o.loadVTLayers(),a=i&&i.sourceLayer?i.sourceLayer:"",s=r._geojsonTileLayer||r[a];if(!s)return;const n=t.aa(null==i?void 0:i.filter,null==i?void 0:i.globalState),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=!1;else if(i)if(this.expirationTime{this.remove(e,r);}),i)),this.data[o].push(r),this.order.push(o),this.order.length>this.max){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}has(e){return e.wrapped().key in this.data}getAndRemove(e){return this.has(e)?this._getAndRemoveByKey(e.wrapped().key):null}_getAndRemoveByKey(e){const t=this.data[e].shift();return t.timeout&&clearTimeout(t.timeout),0===this.data[e].length&&delete this.data[e],this.order.splice(this.order.indexOf(e),1),t.value}getByKey(e){const t=this.data[e];return t?t[0].value:null}get(e){return this.has(e)?this.data[e.wrapped().key][0].value:null}remove(e,t){if(!this.has(e))return this;const i=e.wrapped().key,o=void 0===t?0:this.data[i].indexOf(t),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(e){for(this.max=e;this.order.length>this.max;){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}filter(e){const t=[];for(const i in this.data)for(const o of this.data[i])e(o.value)||t.push(o);for(const e of t)this.remove(e.value.tileID,e);}}class se{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(e,i,o){const r=String(i);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][r]=this.stateChanges[e][r]||{},t.e(this.stateChanges[e][r],o),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==r&&(this.deletedStates[e][t]=null);}else if(this.deletedStates[e]&&null===this.deletedStates[e][r]){this.deletedStates[e][r]={};for(const t in this.state[e][r])o[t]||(this.deletedStates[e][r][t]=null);}else for(const t in o)this.deletedStates[e]&&this.deletedStates[e][r]&&null===this.deletedStates[e][r][t]&&delete this.deletedStates[e][r][t];}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const o=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&void 0!==t)null!==this.deletedStates[e][o]&&(this.deletedStates[e][o]=this.deletedStates[e][o]||{},this.deletedStates[e][o][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][o])for(i in this.deletedStates[e][o]={},this.stateChanges[e][o])this.deletedStates[e][o][i]=null;else this.deletedStates[e][o]=null;else this.deletedStates[e]=null;}getState(e,i){const o=String(i),r=t.e({},(this.state[e]||{})[o],(this.stateChanges[e]||{})[o]);if(null===this.deletedStates[e])return {};if(this.deletedStates[e]){const t=this.deletedStates[e][i];if(null===t)return {};for(const e in t)delete r[e];}return r}initializeTileState(e,t){e.setFeatureState(this.state,t);}coalesceChanges(e,i){const o={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const i={};for(const o in this.stateChanges[e])this.state[e][o]||(this.state[e][o]={}),t.e(this.state[e][o],this.stateChanges[e][o]),i[o]=this.state[e][o];o[e]=i;}for(const e in this.deletedStates){this.state[e]=this.state[e]||{};const i={};if(null===this.deletedStates[e])for(const t in this.state[e])i[t]={},this.state[e][t]={};else for(const t in this.deletedStates[e]){if(null===this.deletedStates[e][t])this.state[e][t]={};else for(const i of Object.keys(this.deletedStates[e][t]))delete this.state[e][t][i];i[t]=this.state[e][t];}o[e]=o[e]||{},t.e(o[e],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(o).length)for(const t in e)e[t].setFeatureState(o,i);}}const ne=89.25;function le(e,i){const o=t.ah(i.lat,-t.ai,t.ai);return new t.P(t.V(i.lng)*e,t.U(o)*e)}function ce(e,i){return new t.a1(i.x/e,i.y/e).toLngLat()}function he(e){return e.cameraToCenterDistance*Math.min(.85*Math.tan(t.ae(90-e.pitch)),Math.tan(t.ae(ne-e.pitch)))}function ue(e,i){const o=e.canonical,r=i/t.af(o.z),a=o.x+Math.pow(2,o.z)*e.wrap,s=t.ag(new Float64Array(16));return t.M(s,s,[a*r,o.y*r,0]),t.N(s,s,[r/t.$,r/t.$,1]),s}function de(e,i,o,r,a){const s=t.a1.fromLngLat(e,i),n=a*t.aj(1,e.lat),l=n*Math.cos(t.ae(o)),c=Math.sqrt(n*n-l*l),h=c*Math.sin(t.ae(-r)),u=c*Math.cos(t.ae(-r));return new t.a1(s.x+h,s.y+u,s.z+l)}function _e(e,t,i){const o=t.intersectsFrustum(e);if(!i||0===o)return o;const r=t.intersectsPlane(i);return 0===r?0:2===o&&2===r?2:1}function pe(e,t,i){let o=0;const r=(i-t)/10;for(let a=0;a<10;a++)o+=r*Math.pow(Math.cos(t+(a+.5)/10*(i-t)),e);return o}function me(e,i){return function(o,r,a,s,n){const l=2*((e-1)/t.ak(Math.cos(t.ae(ne-n))/Math.cos(t.ae(ne)))-1),c=Math.acos(a/s),h=2*pe(l-1,0,t.ae(n/2)),u=Math.min(t.ae(ne),c+t.ae(n/2)),d=pe(l-1,Math.min(u,c-t.ae(n/2)),u),_=Math.atan(r/a),p=Math.hypot(r,a);let m=o;return m+=t.ak(s/p/Math.max(.5,Math.cos(t.ae(n/2)))),m+=l*t.ak(Math.cos(_))/2,m-=t.ak(Math.max(1,d/h/i))/2,m}}const fe=me(9.314,3);function ge(e,i){const o=(i.roundZoom?Math.round:Math.floor)(e.zoom+t.ak(e.tileSize/i.tileSize));return Math.max(0,o)}function ve(e,i){const o=e.getCameraFrustum(),r=e.getClippingPlane(),a=e.screenPointToMercatorCoordinate(e.getCameraPoint()),s=t.a1.fromLngLat(e.center,e.elevation);a.z=s.z+Math.cos(e.pitchInRadians)*e.cameraToCenterDistance/e.worldSize;const n=e.getCoveringTilesDetailsProvider(),l=n.allowVariableZoom(e,i),c=ge(e,i),h=i.minzoom||0,u=void 0!==i.maxzoom?i.maxzoom:e.maxZoom,d=Math.min(Math.max(0,c),u),_=Math.pow(2,d),p=[_*a.x,_*a.y,0],m=[_*s.x,_*s.y,0],f=Math.hypot(s.x-a.x,s.y-a.y),g=Math.abs(s.z-a.z),v=Math.hypot(f,g),b=e=>({zoom:0,x:0,y:0,wrap:e,fullyVisible:!1}),x=[],y=[];if(e.renderWorldCopies&&n.allowWorldCopies())for(let e=1;e<=3;e++)x.push(b(-e)),x.push(b(e));for(x.push(b(0));x.length>0;){const _=x.pop(),f=_.x,b=_.y;let w=_.fullyVisible;const T={x:f,y:b,z:_.zoom},P=n.getTileBoundingVolume(T,_.wrap,e.elevation,i);if(!w){const e=_e(o,P,r);if(0===e)continue;w=2===e;}const C=n.distanceToTile2d(a.x,a.y,T,P);let I=c;l&&(I=(i.calculateTileZoom||fe)(e.zoom+t.ak(e.tileSize/i.tileSize),C,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const M=Math.min(I,u);if(_.wrap=n.getWrap(s,T,_.wrap),_.zoom>=M){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return y.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}const be=t.a2.fromPoints([new t.P(0,0),new t.P(t.$,t.$)]);class xe extends t.E{constructor(e,t,i){super(),this.id=e,this.dispatcher=i,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=!1;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,o)=>{const r=new(J(t.type))(e,t,i,o);if(r.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${r.id}`);return r})(e,t,i,this),this._tiles={},this._cache=new ae(0,(e=>this._unloadTile(e))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new se,this._didEmitContent=!1,this._updated=!1;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e);}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return !0;if(!this._updated)return !1;for(const e in this._tiles){const t=this._tiles[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}return !0}getSource(){return this._source}pause(){this._paused=!0;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,o){return t._(this,void 0,void 0,(function*(){try{yield this._source.loadTile(e),this._tileLoaded(e,i,o);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.k(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.l("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const t in this._tiles){const i=this._tiles[t];i.upload(e),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(ye).map((e=>e.key))}getRenderableIds(e){const i=[];for(const t in this._tiles)this._isIdRenderable(t,e)&&i.push(this._tiles[t]);return e?i.sort(((e,i)=>{const o=e.tileID,r=i.tileID,a=new t.P(o.canonical.x,o.canonical.y)._rotate(-this.transform.bearingInRadians),s=new t.P(r.canonical.x,r.canonical.y)._rotate(-this.transform.bearingInRadians);return o.overscaledZ-r.overscaledZ||s.y-a.y||s.x-a.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(ye).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return !!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())}reload(e){if(this._paused)this._shouldReloadOnResume=!0;else {this._cache.reset();for(const t in this._tiles)e?this._reloadTile(t,"expired"):"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading");}}_reloadTile(e,i){return t._(this,void 0,void 0,(function*(){const t=this._tiles[e];t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,o){e.timeAdded=s.now(),"expired"===o&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.l("data",{dataType:"source",tile:e,coord:e.tileID}));}_backfillDEM(e){const t=this.getRenderableIds();for(let o=0;o1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,o),e.neighboringTiles&&e.neighboringTiles[a]&&(e.neighboringTiles[a].backfilled=!0)));}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,o){for(const r in this._tiles){let a=this._tiles[r];if(o[r]||!a.hasData()||a.tileID.overscaledZ<=t||a.tileID.overscaledZ>i)continue;let s=a.tileID;for(;a&&a.tileID.overscaledZ>t+1;){const e=a.tileID.scaledTo(a.tileID.overscaledZ-1);a=this._tiles[e.key],a&&a.hasData()&&(s=e);}let n=s;for(;n.overscaledZ>t;)if(n=n.scaledTo(n.overscaledZ-1),e[n.key]||e[n.canonical.key]){o[s.key]=s;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),o=this._getLoadedTile(t);if(o)return o}}findLoadedSibling(e){return this._getLoadedTile(e)}_getLoadedTile(e){const t=this._tiles[e.key];return t&&t.hasData()?t:this._cache.getByKey(e.wrapped().key)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,o=Math.ceil(e.height/this._source.tileSize)+1,r=Math.floor(i*o*(null===this._maxTileCacheZoomLevels?t.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),a="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(a);}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e={};for(const i in this._tiles){const o=this._tiles[i];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),e[o.tileID.key]=o;}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(e,this._tiles[e]);}}_updateCoveredAndRetainedTiles(e,t,i,o,r,a){const n={},l={},c=Object.keys(e),h=s.now();for(const i of c){const o=e[i],r=this._tiles[i];if(!r||0!==r.fadeEndTime&&r.fadeEndTime<=h)continue;const a=this.findLoadedParent(o,t),s=this.findLoadedSibling(o),c=a||s||null;c&&(this._addTile(c.tileID),n[c.tileID.key]=c.tileID),l[i]=o;}this._retainLoadedChildren(l,o,i,e);for(const t in n)e[t]||(this._coveredTiles[t]=!0,e[t]=n[t]);if(a){const t={},i={};for(const e of r)this._tiles[e.key].hasData()?t[e.key]=e:i[e.key]=e;for(const o in i){const r=i[o].children(this._source.maxzoom);this._tiles[r[0].key]&&this._tiles[r[1].key]&&this._tiles[r[2].key]&&this._tiles[r[3].key]&&(t[r[0].key]=e[r[0].key]=r[0],t[r[1].key]=e[r[1].key]=r[1],t[r[2].key]=e[r[2].key]=r[2],t[r[3].key]=e[r[3].key]=r[3],delete i[o]);}for(const o in i){const r=i[o],a=this.findLoadedParent(r,this._source.minzoom),s=this.findLoadedSibling(r),n=a||s||null;if(n){t[n.tileID.key]=e[n.tileID.key]=n.tileID;for(const e in t)t[e].isChildOf(n.tileID)&&delete t[e];}}for(const e in this._tiles)t[e]||(this._coveredTiles[e]=!0);}}update(e,i){if(!this._sourceLoaded||this._paused)return;let o;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?o=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.Z(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(o=ve(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(o=o.filter((e=>this._source.hasTile(e))))):o=[];const r=ge(e,this._source),a=Math.max(r-xe.maxOverzooming,this._source.minzoom),s=Math.max(r+xe.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const e={};for(const t of o)if(t.canonical.z>this._source.minzoom){const i=t.scaledTo(t.canonical.z-1);e[i.key]=i;const o=t.scaledTo(Math.max(this._source.minzoom,Math.min(t.canonical.z,5)));e[o.key]=o;}o=o.concat(Object.values(e));}const n=0===o.length&&!this._updated&&this._didEmitContent;this._updated=!0,n&&this.fire(new t.l("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(o,r);we(this._source.type)&&this._updateCoveredAndRetainedTiles(l,a,s,r,o,i);for(const e in l)this._tiles[e].clearFadeHold();const c=t.am(this._tiles,l);for(const e of c){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const o={},r={},a=Math.max(t-xe.maxOverzooming,this._source.minzoom),s=Math.max(t+xe.maxUnderzooming,this._source.minzoom),n={};for(const i of e){const e=this._addTile(i);o[i.key]=i,e.hasData()||tthis._source.maxzoom){const e=s.children(this._source.maxzoom)[0],t=this.getTile(e);if(t&&t.hasData()){o[e.key]=e;continue}}else {const e=s.children(this._source.maxzoom);if(4===e.length&&o[e[0].key]&&o[e[1].key]&&o[e[2].key]&&o[e[3].key])continue;if(1===e.length&&o[e[0].key])continue}let n=e.wasRequested();for(let t=s.overscaledZ-1;t>=a;--t){const a=s.scaledTo(t);if(r[a.key])break;if(r[a.key]=!0,e=this.getTile(a),!e&&n&&(e=this._addTile(a)),e){const t=e.hasData();if((t||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||n)&&(o[a.key]=a),n=e.wasRequested(),t)break}}}return o}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,o=this._tiles[e].tileID;for(;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}t.push(o.key);const e=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;o=e;}for(const e of t)this._loadedParentTiles[e]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const e in this._tiles){const t=this._tiles[e].tileID,i=this._getLoadedTile(t);this._loadedSiblingTiles[t.key]=i;}}_addTile(e){let i=this._tiles[e.key];if(i)return i;i=this._cache.getAndRemove(e),i&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));const o=i;return i||(i=new re(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._tiles[e.key]=i,o||this._source.fire(new t.l("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}refreshTiles(e){for(const t in this._tiles)(this._isIdRenderable(t)||"errored"==this._tiles[t].state)&&e.some((e=>e.equals(this._tiles[t].tileID.canonical)))&&this._reloadTile(t,"expired");}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=!0,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){const t=e.sourceDataType;"source"===e.dataType&&"metadata"===t&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===t&&(this.reload(e.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0);}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e in this._tiles)this._removeTile(e);this._cache.reset();}tilesIn(e,i,o){const r=[],a=this.transform;if(!a)return r;const s=a.getCoveringTilesDetailsProvider().allowWorldCopies(),n=o?a.getCameraQueryGeometry(e):e,l=e=>a.screenPointToMercatorCoordinate(e,this.terrain),c=this.transformBbox(e,l,!s),h=this.transformBbox(n,l,!s),u=this.getIds(),d=t.a2.fromPoints(h);for(let e=0;ee.getTilePoint(new t.a1(i.x,i.y))));if(i.expandBy(_),i.intersects(be)){const t=c.map((t=>e.getTilePoint(t))),i=h.map((t=>e.getTilePoint(t)));r.push({tile:o,tileID:s?e:e.unwrapTo(0),queryGeometry:t,cameraQueryGeometry:i,scale:l});}}}return r}transformBbox(e,i,o){let r=e.map(i);if(o){const o=t.a2.fromPoints(e);o.shrinkBy(.001*Math.min(o.width(),o.height()));const a=o.map(i);t.a2.fromPoints(r).covers(a)||(r=r.map((e=>e.x>.5?new t.a1(e.x-1,e.y,e.z):e)));}return r}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._tiles[e].tileID));return this.transform&&this.transform.populateCache(t),t}hasTransition(){if(this._source.hasTransition())return !0;if(we(this._source.type)){const e=s.now();for(const t in this._tiles)if(this._tiles[t].fadeEndTime>=e)return !0}return !1}setFeatureState(e,t,i){this._state.updateState(e=e||"_geojsonTileLayer",t,i);}removeFeatureState(e,t,i){this._state.removeFeatureState(e=e||"_geojsonTileLayer",t,i);}getFeatureState(e,t){return this._state.getState(e=e||"_geojsonTileLayer",t)}setDependencies(e,t,i){const o=this._tiles[e];o&&o.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)));}}function ye(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),o=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||o-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function we(e){return "raster"===e||"image"===e||"video"===e}xe.maxOverzooming=10,xe.maxUnderzooming=3;class Te{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(r-s)/n:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))}}function Pe(e,t){let i=!0;return "always"===e||"never"!==e&&"never"!==t||(i=!1),i}class Ce{constructor(e,t,i){const o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||o<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=o){if(r)return [{key:null,x1:e,y1:t,x2:i,y2:o}];for(let e=0;e0}hitTestCircle(e,t,i,o,r){const a=e-i,s=e+i,n=t-i,l=t+i;if(s<0||a>this.width||l<0||n>this.height)return !1;const c=[];return this._forEachCell(a,n,s,l,this._queryCellCircle,c,{hitTest:!0,overlapMode:o,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},r),c.length>0}_queryCell(e,t,i,o,r,a,s,n){const{seenUids:l,hitTest:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const r=this.bboxes;for(const s of u)if(!l.box[s]){l.box[s]=!0;const u=4*s,d=this.boxKeys[s];if(e<=r[u+2]&&t<=r[u+3]&&i>=r[u+0]&&o>=r[u+1]&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))&&(a.push({key:d,x1:r[u],y1:r[u+1],x2:r[u+2],y2:r[u+3]}),c))return !0}}const d=this.circleCells[r];if(null!==d){const r=this.circles;for(const s of d)if(!l.circle[s]){l.circle[s]=!0;const u=3*s,d=this.circleKeys[s];if(this._circleAndRectCollide(r[u],r[u+1],r[u+2],e,t,i,o)&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))){const e=r[u],t=r[u+1],i=r[u+2];if(a.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return !0}}}return !1}_queryCellCircle(e,t,i,o,r,a,s,n){const{circle:l,seenUids:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=!0;const i=4*t,o=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}const d=this.circleCells[r];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=!0;const i=3*t,o=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}}_forEachCell(e,t,i,o,r,a,s,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(o);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(r.call(this,e,t,i,o,this.xCellCount*l+d,a,s,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,o,r,a){const s=o-e,n=r-t,l=i+a;return l*l>s*s+n*n}_circleAndRectCollide(e,t,i,o,r,a,s){const n=(a-o)/2,l=Math.abs(e-(o+n));if(l>n+i)return !1;const c=(s-r)/2,h=Math.abs(t-(r+c));if(h>c+i)return !1;if(l<=n||h<=c)return !0;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function Ie(e,i,r){const a=t.L();if(!e){const{vecSouth:e,vecEast:t}=Se(i),r=o();r[0]=t[0],r[1]=t[1],r[2]=e[0],r[3]=e[1],s=r,(d=(l=(n=r)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(s[0]=u*(d=1/d),s[1]=-c*d,s[2]=-h*d,s[3]=l*d),a[0]=r[0],a[1]=r[1],a[4]=r[2],a[5]=r[3];}var s,n,l,c,h,u,d;return t.N(a,a,[1/r,1/r,1]),a}function Me(e,i,o,r){if(e){const e=t.L();if(!i){const{vecSouth:t,vecEast:i}=Se(o);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.N(e,e,[r,r,1]),e}return o.pixelsToClipSpaceMatrix}function Se(e){const i=Math.cos(e.rollInRadians),o=Math.sin(e.rollInRadians),r=Math.cos(e.pitchInRadians),a=Math.cos(e.bearingInRadians),s=Math.sin(e.bearingInRadians),n=t.ar();n[0]=-a*r*o-s*i,n[1]=-s*r*o+a*i;const l=t.as(n);l<1e-9?t.at(n):t.au(n,n,1/l);const c=t.ar();c[0]=a*r*i-s*o,c[1]=s*r*i+a*o;const h=t.as(c);return h<1e-9?t.at(c):t.au(c,c,1/h),{vecEast:c,vecSouth:n}}function Ee(e,i,o,r){let a;r?(a=[e,i,r(e,i),1],t.aw(a,a,o)):(a=[e,i,0,1],qe(a,a,o));const s=a[3];return {point:new t.P(a[0]/s,a[1]/s),signedDistanceFromCamera:s,isOccluded:!1}}function Re(e,t){return .5+e/t*.5}function ze(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function De(e,i,o,r,a,s,n,l,c,h,u,d,_){const p=o?e.textSizeData:e.iconSizeData,m=t.an(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=o?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,b=o?e.text.placedSymbolArray:e.icon.placedSymbolArray,x=i.transform.width/i.transform.height;let y=!1;for(let o=0;oMath.abs(o.x-i.x)*r?{useVertical:!0}:(e===t.ao.vertical?i.yo.x)?{needsFlipping:!0}:null}function ke(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:o,symbol:r,fontSize:a,flip:s,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=a/24,_=r.lineOffsetX*d,p=r.lineOffsetY*d;let m;if(r.numGlyphs>1){const e=r.glyphStartIndex+r.numGlyphs,t=r.lineStartIndex,a=r.lineStartIndex+r.lineLength,c=Ae(d,l,_,p,s,r,u,i);if(!c)return {notEnoughRoom:!0};const f=je(c.first.point.x,c.first.point.y,i,o),g=je(c.last.point.x,c.last.point.y,i,o);if(n&&!s){const e=Le(r.writingMode,f,g,h);if(e)return e}m=[c.first];for(let o=r.glyphStartIndex+1;o0?n.point:Fe(i.tileAnchorPoint,s,e,1,i),c=je(e.x,e.y,i,o),u=je(l.x,l.y,i,o),d=Le(r.writingMode,c,u,h);if(d)return d}const e=Ge(d*l.getoffsetX(r.glyphStartIndex),_,p,s,r.segment,r.lineStartIndex,r.lineStartIndex+r.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:!0};m=[e];}for(const e of m)t.av(c,e.point,e.angle);return {}}function Fe(e,t,i,o,r){const a=e.add(e.sub(t)._unit()),s=Oe(a.x,a.y,r).point,n=i.sub(s);return i.add(n._mult(o/n.mag()))}function Be(e,i,o){const r=i.projectionCache;if(r.projections[e])return r.projections[e];const a=new t.P(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),s=Oe(a.x,a.y,i);if(s.signedDistanceFromCamera>0)return r.projections[e]=s.point,r.anyProjectionOccluded=r.anyProjectionOccluded||s.isOccluded,s.point;const n=e-o.direction;return Fe(0===o.distanceFromAnchor?i.tileAnchorPoint:new t.P(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),a,o.previousVertex,o.absOffsetX-o.distanceFromAnchor+1,i)}function Oe(e,t,i){const o=e+i.translation[0],r=t+i.translation[1];let a;return i.pitchWithMap?(a=Ee(o,r,i.pitchedLabelPlaneMatrix,i.getElevation),a.isOccluded=!1):(a=i.transform.projectTileCoordinates(o,r,i.unwrappedTileID,i.getElevation),a.point.x=(.5*a.point.x+.5)*i.width,a.point.y=(.5*-a.point.y+.5)*i.height),a}function je(e,i,o,r){if(o.pitchWithMap){const a=[e,i,0,1];return t.aw(a,a,r),o.transform.projectTileCoordinates(a[0]/a[3],a[1]/a[3],o.unwrappedTileID,o.getElevation).point}return {x:e/o.width*2-1,y:1-i/o.height*2}}function Ne(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function Ue(e,t,i){return e._unit()._perp()._mult(t*i)}function Ze(e,i,o,r,a,s,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=o.add(i);if(e+c.direction=a)return l.projectionCache.offsets[e]=h,h;const u=Be(e+c.direction,l,c),d=Ue(u.sub(o),n,c.direction),_=o.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.ax(s,h,_,p)||h,l.projectionCache.offsets[e]}function Ge(e,t,i,o,r,a,s,n,l){const c=o?e-t:e+t;let h=c>0?1:-1,u=0;o&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?a+r:a+r+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Oe(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,b=0;const x=Math.abs(c),y=[];let w;for(;v+b<=x;){if(_+=h,_=s)return null;v+=b,g=f,m=p;const e={absOffsetX:x,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=Be(_,n,e),0===i)y.push(g),w=f.sub(g);else {let t;const o=f.sub(g);t=0===o.mag()?Ue(Be(_+h,n,e).sub(f),i,h):Ue(o,i,h),m||(m=g.add(t)),p=Ze(_,t,f,a,s,m,i,n,e),y.push(m),w=p.sub(m);}b=w.mag();}const T=w._mult((x-v)/b)._add(m||g),P=u+Math.atan2(f.y-g.y,f.x-g.x);return y.push(T),{point:T,angle:l?P:0,path:y}}const Ve=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function $e(e,t){for(let i=0;i=1;e--)_.push(s.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=o.x&&i.x<=r.x&&e.y>=o.y&&i.y<=r.y?[_]:i.xr.x||i.yr.y?[]:t.ay([_],o.x,o.y,r.x,r.y);}for(const t of f){a.reset(t,.25*i);let o=0;o=a.length<=.5*i?1:Math.ceil(a.paddedLength/p)+1;for(let t=0;t{const t=Ee(e.x,e.y,o,i.getElevation),r=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return r.point.x=(.5*r.point.x+.5)*i.width,r.point.y=(.5*-r.point.y+.5)*i.height,r}))}(e,i);return function(e){let t=0,i=0,o=0,r=0;for(let a=0;ai&&(i=r,t=o));return e.slice(t,t+i)}(o)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[],o=new t.a2;for(const r of e){const e=new t.P(r.x+We,r.y+We);o.extend(e),i.push(e);}const{minX:r,minY:a,maxX:s,maxY:n}=o,l=this.grid.query(r,a,s,n).concat(this.ignoredGrid.query(r,a,s,n)),c={},h={};for(const e of l){const o=e.key;if(void 0===c[o.bucketInstanceId]&&(c[o.bucketInstanceId]={}),c[o.bucketInstanceId][o.featureIndex])continue;const r=[new t.P(e.x1,e.y1),new t.P(e.x2,e.y1),new t.P(e.x2,e.y2),new t.P(e.x1,e.y2)];t.az(i,r)&&(c[o.bucketInstanceId][o.featureIndex]=!0,void 0===h[o.bucketInstanceId]&&(h[o.bucketInstanceId]=[]),h[o.bucketInstanceId].push(o.featureIndex));}return h}insertCollisionBox(e,t,i,o,r,a){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,o,r,a){const s=i?this.ignoredGrid:this.grid,n={bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t};for(let t=0;t=this.screenRightBoundary||othis.screenBottomBoundary}isInsideGrid(e,t,i,o){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,r,c,u)));E=e.some((e=>!e.isOccluded)),S=e.map((e=>new t.P(e.x,e.y)));}else E=!0;return {box:t.aA(S),allPointsOccluded:!E}}}class Xe{constructor(e,t,i,o){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):o&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class Ke{constructor(e,t,i,o,r){this.text=new Xe(e?e.text:null,t,i,r),this.icon=new Xe(e?e.icon:null,t,o,r);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ye{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class Qe{constructor(e,t,i,o,r){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=r;}}class Je{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function et(e,i,o,r,a){const{horizontalAlign:s,verticalAlign:n}=t.aH(e);return new t.P(-(s-.5)*i+r[0]*a,-(n-.5)*o+r[1]*a)}class tt{constructor(e,t,i,o,r){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new He(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new Je(o),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=r,r&&(r.prevPlacement=void 0),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,o)=>t.getElevation(e,i,o):null}getBucketParts(e,i,o,r){const a=o.getBucket(i),s=o.latestFeatureIndex;if(!a||!s||i.id!==a.layerIds[0])return;const n=o.collisionBoxArray,l=a.layers[0].layout,c=a.layers[0].paint,h=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),u=o.tileSize/t.$,d=o.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.aC(o,1,this.transform.zoom),m=t.aD(this.collisionIndex.transform,o,c.get("text-translate"),c.get("text-translate-anchor")),f=t.aD(this.collisionIndex.transform,o,c.get("icon-translate"),c.get("icon-translate-anchor")),g=Ie(_,this.transform,p);this.retainedQueryData[a.bucketInstanceId]=new Qe(a.bucketInstanceId,s,a.sourceLayerIndex,a.index,o.tileID);const v={bucket:a,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:o.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.an(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(r)for(const t of a.sortKeyRanges){const{sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r}=t;e.push({sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v,b,x){const y=t.aE[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=et(y,o,r,w,a),P=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,s,f,u.predicate,b,T,x);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,s,g,u.predicate,b,T,x).placeable)&&P.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:o,height:r,anchor:y,textBoxScale:a,prevAnchor:e},this.markUsedJustification(p,y,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:P}}}placeLayerBucketPart(e,i,o){const{bucket:r,layout:a,translationText:s,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=a.get("text-optional"),f=a.get("icon-optional"),g=t.aF(a,"text-overlap","text-allow-overlap"),v="always"===g,b=t.aF(a,"icon-overlap","icon-allow-overlap"),x="always"===b,y="map"===a.get("text-rotation-alignment"),w="map"===a.get("text-pitch-alignment"),T="none"!==a.get("icon-text-fit"),P="viewport-y"===a.get("symbol-z-order"),C=v&&(x||!r.hasIconData()||f),I=x&&(v||!r.hasTextData()||m);!r.collisionArrays&&d&&r.deserializeCollisionBoxes(d);const M=this.retainedQueryData[r.bucketInstanceId].tileID,S=this._getTerrainElevationFunc(M),E=this.transform.getFastPathSimpleProjectionMatrix(M),R=(e,d,x)=>{var P,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new Ye(!1,!1,!1));let z=!1,D=!1,A=!0,L=null,k={box:null,placeable:!1,offscreen:null,occluded:!1},F={placeable:!1},B=null,O=null,j=null,N=0,U=0,Z=0;d.textFeatureIndex?N=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(N=e.featureIndex),d.verticalTextFeatureIndex&&(U=d.verticalTextFeatureIndex);const G=d.textBox;if(G){const i=i=>{let o=t.ao.horizontal;if(r.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,o=t,this.markUsedOrientation(r,o,e));}return o},a=(i,o)=>{if(r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of r.writingModes)if(e===t.ao.vertical?(k=o(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const o=(t,i)=>{const o=this.collisionIndex.placeCollisionBox(t,g,h,M,l,w,y,s,p.predicate,S,void 0,E);return o&&o.placeable&&(this.markUsedOrientation(r,i,e),this.placedOrientations[e.crossTileID]=i),o};a((()=>o(G,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?o(i,t.ao.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.aE[null===(R=null===(P=this.prevPlacement)||void 0===P?void 0:P.variableOffsets[e.crossTileID])||void 0===R?void 0:R.anchor];const m=(t,i,a)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===b?i:null;let x=null,P="never"===g?1:2,C="never";_&&P++;for(let i=0;im(G,d.iconBox,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.ao.vertical):{box:null,occluded:!0,offscreen:null}})),k&&(z=k.placeable,A=k.offscreen);const f=i(k&&k.placeable);if(!z&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(r,t.anchor,e,f));}}}if(B=k,z=B&&B.placeable,A=B&&B.offscreen,e.useRuntimeCollisionCircles){const i=r.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.ap(r.textSizeData,_,i),h=a.get("text-padding");O=this.collisionIndex.placeCollisionCircles(g,i,r.lineVertexArray,r.glyphOffsetArray,n,l,c,o,w,p.predicate,e.collisionCircleDiameter,h,s,S),O.circles.length&&O.collisionDetected&&!o&&t.w("Collisions detected, but collision boxes are not shown"),z=v||O.circles.length>0&&!O.collisionDetected,A=A&&O.offscreen;}if(d.iconFeatureIndex&&(Z=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,b,h,M,l,w,y,n,p.predicate,S,T&&L?L:void 0,E);F&&F.placeable&&d.verticalIconBox?(j=e(d.verticalIconBox),D=j.placeable):(j=e(d.iconBox),D=j.placeable),A=A&&j.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,$=f||0===e.numIconVertices;V||$?$?V||(D=D&&z):z=D&&z:D=z=D&&z;const q=D&&j.placeable;if(z&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,a.get("text-ignore-placement"),r.bucketInstanceId,F&&F.placeable&&U?U:N,p.ID),q&&this.collisionIndex.insertCollisionBox(j.box,b,a.get("icon-ignore-placement"),r.bucketInstanceId,Z,p.ID),O&&z&&this.collisionIndex.insertCollisionCircles(O.circles,g,a.get("text-ignore-placement"),r.bucketInstanceId,N,p.ID),o&&this.storeCollisionData(r.bucketInstanceId,x,d,B,j,O),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===r.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new Ye((z||C)&&!(null==B?void 0:B.occluded),(D||I)&&!(null==j?void 0:j.occluded),A||r.justReloaded),i[e.crossTileID]=!0;};if(P){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=r.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(r.symbolInstances.get(i),r.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=a>=0&&t!==a?0:o.crossTileID);}markUsedOrientation(e,i,o){const r=i===t.ao.horizontal||i===t.ao.horizontalOnly?i:0,a=i===t.ao.vertical?i:0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];for(const t of s)e.text.placedSymbolArray.get(t).placedOrientation=r;o.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).placedOrientation=a);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=!1;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const o=t?t.symbolFadeChange(e):1,r=t?t.opacities:{},a=t?t.variableOffsets:{},s=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],a=r[e];a?(this.opacities[e]=new Ke(a,o,t.text,t.icon),i=i||t.text!==a.text.placed||t.icon!==a.icon.placed):(this.opacities[e]=new Ke(null,o,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in r){const t=r[e];if(!this.opacities[e]){const r=new Ke(t,o,!1,!1);r.isHidden()||(this.opacities[e]=r,i=i||t.text.placed||t.icon.placed);}}for(const e in a)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=a[e]);for(const e in s)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=s[e]);if(t&&void 0===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const o of t){const t=o.getBucket(e);t&&o.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,o.tileID,i,o.collisionBoxArray);}}updateBucketOpacities(e,i,o,r){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=!1),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=!1),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const a=e.layers[0],s=a.layout,n=new Ke(null,0,!1,!1,!0),l=s.get("text-allow-overlap"),c=s.get("icon-allow-overlap"),h=a._unevaluatedLayout.hasValue("text-variable-anchor")||a._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===s.get("text-rotation-alignment"),d="map"===s.get("text-pitch-alignment"),_="none"!==s.get("icon-text-fit"),p=new Ke(null,0,l&&(c||!e.hasIconData()||s.get("icon-optional")),c&&(l||!e.hasTextData()||s.get("text-optional")),!0);!e.collisionArrays&&r&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(r);const m=(e,t,i)=>{for(let o=0;o0,v=this.placedOrientations[r.crossTileID],b=v===t.ao.vertical,x=v===t.ao.horizontal||v===t.ao.horizontalOnly;if(a>0||s>0){const t=ht(c.text);m(e.text,a,b?ut:t),m(e.text,s,x?ut:t);const i=c.text.isHidden();[r.rightJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||b?1:0);})),r.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).hidden=i||x?1:0);const o=this.variableOffsets[r.crossTileID];o&&this.markUsedJustification(e,o.anchor,r,v);const n=this.placedOrientations[r.crossTileID];n&&(this.markUsedJustification(e,"left",r,n),this.markUsedOrientation(e,n,r));}if(g){const t=ht(c.icon),i=!(_&&r.verticalPlacedIconSymbolIndex&&b);r.placedIconSymbolIndex>=0&&(m(e.icon,r.numIconVertices,i?t:ut),e.icon.placedSymbolArray.get(r.placedIconSymbolIndex).hidden=c.icon.isHidden()),r.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,r.numVerticalIconVertices,i?ut:t),e.icon.placedSymbolArray.get(r.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const y=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const o=e.collisionArrays[i];if(o){let i=new t.P(0,0);if(o.textBox||o.verticalTextBox){let t=!0;if(h){const e=this.variableOffsets[l];e?(i=et(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=!1;}if(o.textBox||o.verticalTextBox){let r;o.textBox&&(r=b),o.verticalTextBox&&(r=x),it(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||r,y.text,i.x,i.y);}}if(o.iconBox||o.verticalIconBox){const t=Boolean(!x&&o.verticalIconBox);let r;o.iconBox&&(r=t),o.verticalIconBox&&(r=!t),it(e.iconCollisionBox.collisionVertexArray,c.icon.placed,r,y.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=!0;}}function it(e,t,i,o,r,a){o&&0!==o.length||(o=[0,0,0,0]);const s=o[0]-We,n=o[1]-We,l=o[2]-We,c=o[3]-We;e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,c),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,c);}const ot=Math.pow(2,25),rt=Math.pow(2,24),at=Math.pow(2,17),st=Math.pow(2,16),nt=Math.pow(2,9),lt=Math.pow(2,8),ct=Math.pow(2,1);function ht(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*ot+t*rt+i*at+t*st+i*nt+t*lt+i*ct+t}const ut=0;class dt{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,o,r){const a=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&s.now()-o>2;for(;this._currentPlacementIndex>=0;){const o=t[e[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if("symbol"===o.type&&(!o.minzoom||o.minzoom<=a)&&(!o.maxzoom||o.maxzoom>a)){if(this._inProgressLayer||(this._inProgressLayer=new dt(o)),this._inProgressLayer.continuePlacement(i[o.source],this.placement,this._showCollisionBoxes,o,r))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(e){return this.placement.commit(e),this.placement}}const pt=512/t.$/2;class mt{constructor(e,i,o){this.tileID=e,this.bucketInstanceId=o,this._symbolsByKey={};const r=new Map;for(let e=0;e({x:Math.floor(e.anchorX*pt),y:Math.floor(e.anchorY*pt)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(o.positions.length>128){const e=new t.aI(o.positions.length,16,Uint16Array);for(const{x:t,y:i}of o.positions)e.add(t,i);e.finish(),delete o.positions,o.index=e;}this._symbolsByKey[e]=o;}}getScaledCoordinates(e,i){const{x:o,y:r,z:a}=this.tileID.canonical,{x:s,y:n,z:l}=i.canonical,c=pt/Math.pow(2,l-a),h=(n*t.$+e.anchorY)*c,u=r*t.$*pt;return {x:Math.floor((s*t.$+e.anchorX)*c-o*t.$*pt),y:Math.floor(h-u)}}findMatches(e,t,i){const o=this.tileID.canonical.ze))}}class ft{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class gt{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],o={};for(const e in i){const r=i[e];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+t),o[r.tileID.key]=r;}this.indexes[e]=o;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in r){const a=r[i];a.tileID.isChildOf(e)&&a.findMatches(t.symbolInstances,e,o);}else {const a=r[e.scaledTo(Number(i)).key];a&&a.findMatches(t.symbolInstances,e,o);}}for(let e=0;e{t[e]=!0;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var bt="void main() {fragColor=vec4(1.0);}";const xt={prelude:yt("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:yt("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:yt("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:yt("uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:yt("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:yt("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:yt(bt,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:yt("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:yt("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:yt("in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:yt("in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),colorRelief:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform int u_color_ramp_size;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {float x=(float(stop)+0.5)/float(u_color_ramp_size);vec4 data=texture(u_elevation_stops,vec2(x,0))*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int r=(u_color_ramp_size-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else\n{l=m;el_l=el_m;}}float x=(float(l)+(el-el_l)/(el_r-el_l)+0.5)/float(u_color_ramp_size);fragColor=u_opacity*texture(u_color_stops,vec2(x,0));\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_dimension;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),debug:yt("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}","in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:yt(bt,"in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:yt("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:yt("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:yt("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:yt("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:yt("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {vec2 epsilon=1.0/u_dimension;float tileSize=u_dimension.x-2.0;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))*tileSize/pow(2.0,exaggeration+(28.2562-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+0.5,deriv.y/8.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:yt("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];\n#define PI 3.141592653589793\n#define STANDARD 0\n#define COMBINED 1\n#define IGOR 2\n#define MULTIDIRECTIONAL 3\n#define BASIC 4\nfloat get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);}void igor_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float aspect=get_aspect(deriv);float azimuth=u_azimuths[0]+PI;float slope_stength=atan(length(deriv))*2.0/PI;float aspect_strength=1.0-abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);float shadow_strength=slope_stength*aspect_strength;float highlight_strength=slope_stength*(1.0-aspect_strength);fragColor=u_shadows[0]*shadow_strength+u_highlights[0]*highlight_strength;}void standard_hillshade(vec2 deriv){float azimuth=u_azimuths[0]+PI;float slope=atan(0.625*length(deriv));float aspect=get_aspect(deriv);float intensity=u_exaggeration;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadows[0],u_highlights[0],shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;}void basic_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor=u_highlights[0]*(2.0*shade-1.0);}else\n{fragColor=u_shadows[0]*(1.0-2.0*shade);}}void multidirectional_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;fragColor=vec4(0,0,0,0);for(int i=0; i < NUM_ILLUMINATION_SOURCES; i++){float cos_alt=cos(u_altitudes[i]);float sin_alt=sin(u_altitudes[i]);float cos_az=-cos(u_azimuths[i]);float sin_az=-sin(u_azimuths[i]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor+=u_highlights[i]*(2.0*shade-1.0)/float(NUM_ILLUMINATION_SOURCES);}else\n{fragColor+=u_shadows[i]*(1.0-2.0*shade)/float(NUM_ILLUMINATION_SOURCES);}}}void combined_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=acos((sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv)));cang=clamp(cang,0.0,PI/2.0);float shade=cang*atan(length(deriv))*4.0/PI/PI;float highlight=(PI/2.0-cang)*atan(length(deriv))*4.0/PI/PI;fragColor=u_shadows[0]*shade+u_highlights[0]*highlight;}void main() {vec4 pixel=texture(u_image,v_pos);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));vec2 deriv=((pixel.rg*8.0)-4.0)/scaleFactor;if (u_method==BASIC) {basic_hillshade(deriv);} else if (u_method==COMBINED) {combined_hillshade(deriv);} else if (u_method==IGOR) {igor_hillshade(deriv);} else if (u_method==MULTIDIRECTIONAL) {multidirectional_hillshade(deriv);} else if (u_method==STANDARD) {standard_hillshade(deriv);} else {standard_hillshade(deriv);}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:yt("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:yt("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0);vec4 color1=texture(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:yt("uniform sampler2D u_texture;in vec2 v_tex;in float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;fragColor=texture(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_tex;out float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:yt("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:yt("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;fragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:yt("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}","in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:yt("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}","in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:yt("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:yt("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:yt("in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}","in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:yt("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function yt(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o=t.match(/in ([\w]+) ([\w]+)/g),r=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=a?a.concat(r):r,n={};return {fragmentSource:e=e.replace(i,((e,t,i,o,r)=>(n[r]=!0,"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nin ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = u_${r};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,o,r)=>{const a="float"===o?"vec2":"vec4",s=r.match(/color/)?"color":a;return n[r]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\nout ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`})),staticAttributes:o,staticUniforms:s}}class wt{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var Tt=t.aJ([{name:"a_pos",type:"Int16",components:2}]);const Pt="#define PROJECTION_MERCATOR",Ct="mercator";class It{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return !1}get shaderVariantName(){return Ct}get shaderDefine(){return Pt}get shaderPreludeCode(){return xt.projectionMercator}get vertexShaderPreludeCode(){return xt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.aK.noSubdivision}get useGlobeControls(){return !1}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(e){}getMeshFromTileID(e,i,o,r,a){if(this._cachedMesh)return this._cachedMesh;const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(t.$,0),s.emplaceBack(0,t.$),s.emplaceBack(t.$,t.$);const n=e.createVertexBuffer(s,Tt.members),l=t.aM.simpleSegment(0,0,4,2),c=new t.aN;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new wt(n,h,l),this._cachedMesh}recalculate(){}hasTransition(){return !1}setErrorQueryLatitudeDegrees(e){}}class Mt{constructor(e=0,t=0,i=0,o=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=o;}interpolate(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.C.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.C.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.C.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.C.number(e.right,i.right,o)),this}getCenter(e,i){const o=t.ah((this.left+e-this.right)/2,0,e),r=t.ah((this.top+i-this.bottom)/2,0,i);return new t.P(o,r)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new Mt(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function St(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function Et(e){return Math.max(0,Math.floor(e))}class Rt{constructor(e,i,o,r,a,s){this._callbacks=e,this._tileSize=512,this._renderWorldCopies=void 0===s||!!s,this._minZoom=i||0,this._maxZoom=o||22,this._minPitch=null==r?0:r,this._maxPitch=null==a?60:a,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.S(0,0),this._elevation=0,this._zoom=0,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new Mt,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=!0;}apply(e,i,o){this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new Mt(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,this._cameraToCenterDistance=e.cameraToCenterDistance,this._nearZ=e.nearZ,this._farZ=e.farZ,this._autoCalculateNearFarZ=!o&&e.autoCalculateNearFarZ,i&&this._constrain(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e;}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const i=t.aO(e,-180,180)*Math.PI/180;var r,a,s,n,l,c,h,u,d;this._bearingInRadians!==i&&(this._unmodified=!1,this._bearingInRadians=i,this._calcMatrices(),this._rotationMatrix=o(),r=this._rotationMatrix,s=-this._bearingInRadians,n=(a=this._rotationMatrix)[0],l=a[1],c=a[2],h=a[3],u=Math.sin(s),d=Math.cos(s),r[0]=n*d+c*u,r[1]=l*d+h*u,r[2]=n*-u+c*d,r[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.ah(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=!1,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=!1,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.aP(this._fovInRadians)}setFov(e){e=t.ah(e,.1,150),this.fov!==e&&(this._unmodified=!1,this._fovInRadians=t.ae(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const i=this.getConstrained(this._center,e).zoom;this._zoom!==i&&(this._unmodified=!1,this._zoom=i,this._tileZoom=Math.max(0,Math.floor(i)),this._scale=t.af(i),this._constrain(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(e,t){this._autoCalculateNearFarZ=!1,this._nearZ=e,this._farZ=t,this._calcMatrices();}clearNearFarZOverride(){this._autoCalculateNearFarZ=!0,this._calcMatrices();}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices();}resize(e,t,i=!0){this._width=e,this._height=t,i&&this._constrain(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new G([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-t.ai,t.ai]);}getConstrained(e,t){return this._callbacks.getConstrained(e,t)}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{const{minX:o,minY:r,maxX:a,maxY:s}=t.a2.fromPoints(i).extend(e);return [new t.P(o,r),new t.P(a,r),new t.P(a,s),new t.P(o,s),new t.P(o,r)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const e=this._unmodified,{center:t,zoom:i}=this.getConstrained(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=!1;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.ag(new Float64Array(16));t.N(e,e,[this._width/2,-this._height/2,1]),t.M(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.ag(new Float64Array(16)),t.N(e,e,[1,-1,1]),t.M(e,e,[-1,-1,0]),t.N(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height;}this._callbacks.calcMatrices();}calculateCenterFromCameraLngLatAlt(e,i,o,r){const a=void 0!==o?o:this.bearing,s=r=void 0!==r?r:this.pitch,n=t.a1.fromLngLat(e,i),l=-Math.cos(t.ae(s)),c=Math.sin(t.ae(s)),h=c*Math.sin(t.ae(a)),u=-c*Math.cos(t.ae(a));let d=this.elevation;const _=i-d;let p;l*_>=0||Math.abs(l)<.1?(p=1e4,d=i+p*l):p=-_/l;let m,f,g=t.aQ(1,n.y),v=0;do{if(v+=1,v>10)break;f=p/g,m=new t.a1(n.x+h*f,n.y+u*f),g=1/m.meterInMercatorCoordinateUnits();}while(Math.abs(p-f*g)>1e-12);return {center:m.toLngLat(),elevation:d,zoom:t.ak(this.height/2/Math.tan(this.fovInRadians/2)/f/this.tileSize)}}recalculateZoomAndCenter(e){if(this.elevation-e==0)return;const i=t.aj(1,this.center.lat)*this.worldSize,o=this.cameraToCenterDistance/i,r=t.a1.fromLngLat(this.center,this.elevation),a=de(this.center,this.elevation,this.pitch,this.bearing,o);this._elevation=e;const s=this.calculateCenterFromCameraLngLatAlt(a.toLngLat(),t.aQ(a.z,r.y),this.bearing,this.pitch);this._elevation=s.elevation,this._center=s.center,this.setZoom(s.zoom);}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.P(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/e).toLngLat()}getMercatorTileCoordinates(e){if(!e)return [0,0,1,1];const i=e.canonical.z>=0?1<this.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[o]*this.min[o],i+=e[o]*this.max[o]):(i+=e[o]*this.min[o],t+=e[o]*this.max[o]);return t>=0?2:i<0?0:1}}class Dt{distanceToTile2d(e,t,i,o){const r=o.distanceX([e,t]),a=o.distanceY([e,t]);return Math.hypot(r,a)}getWrap(e,t,i){return i}getTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}const c=1<r}allowWorldCopies(){return !0}prepareNextFrame(){}}class At{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,o=0,r,a){const s=a?[[6,5,4],[0,1,2],[0,3,7],[2,1,5],[3,2,6],[0,4,5]]:[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]],n=Math.pow(2,o),l=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((o=>function(e,i,o,r){const a=t.aw([],e,i),s=1/a[3]/o*r;return t.aY(a,a,[s,s,1/a[3],s])}(o,e,i,n)));r&&function(e,i,o,r){const a=r?4:0,s=r?0:4;let n=0;const l=[],c=[];for(let i=0;i<4;i++){const o=t.aU([],e[i+s],e[i+a]),r=t.aZ(o);t.aR(o,o,1/r),l.push(r),c.push(o);}for(let i=0;i<4;i++){const r=t.a_(e[i+a],c[i],o);n=null!==r&&r>=0?Math.max(n,r):Math.max(n,l[i]);}const h=function(e,i){const o=t.aU([],e[i[0]],e[i[1]]),r=t.aU([],e[i[2]],e[i[1]]),a=[0,0,0,0];return t.aV(a,t.aW([],o,r)),a[3]=-t.aX(a,e[i[0]]),a}(e,i),u=function(e,i){const o=t.a$(e),r=t.b0([],e,1/o),a=t.aU([],i,t.aR([],r,t.aX(i,r))),s=t.a$(a);if(s>0){const e=Math.sqrt(1-r[3]*r[3]),o=t.aR([],r,-r[3]),n=t.aS([],o,t.aR([],a,e/s));return t.b1(i,n)}return null}(o,h);if(null!==u){const e=u/t.aX(c[0],h);n=Math.min(n,e);}for(let t=0;t<4;t++){const i=Math.min(n,l[t]);e[t+s]=[e[t+a][0]+c[t][0]*i,e[t+a][1]+c[t][1]*i,e[t+a][2]+c[t][2]*i,1];}}(l,s[0],r,a);const c=s.map((e=>{const i=t.aU([],l[e[0]],l[e[1]]),o=t.aU([],l[e[2]],l[e[1]]),r=t.aV([],t.aW([],i,o)),a=-t.aX(r,l[e[1]]);return r.concat(a)})),h=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of l)for(let t=0;t<3;t++)h[t]=Math.min(h[t],e[t]),u[t]=Math.max(u[t],e[t]);return new At(l,c,new zt(h,u))}}class Lt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e,t){}constructor(e,t,i,o,r){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)},e,t,i,o,r),this._coveringTilesDetailsProvider=new Dt;}clone(){const e=new Lt;return e.apply(this),e}apply(e,t,i){this._helper.apply(e,t,i);}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.b2(0,e)];if(this._helper._renderWorldCopies){const o=this.screenPointToMercatorCoordinate(new t.P(0,0)),r=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,0)),a=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,this._helper._height)),s=this.screenPointToMercatorCoordinate(new t.P(0,this._helper._height)),n=Math.floor(Math.min(o.x,r.x,a.x,s.x)),l=Math.floor(Math.max(o.x,r.x,a.x,s.x)),c=1;for(let o=n-c;o<=l+c;o++)0!==o&&i.push(new t.b2(o,e));}return i}getCameraFrustum(){return At.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const t=this.screenPointToLocation(this.centerPoint,e),i=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(i);}setLocationAtPoint(e,i){const o=t.aj(this.elevation,this.center.lat),r=this.screenPointToMercatorCoordinateAtZ(i,o),a=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,o),s=t.a1.fromLngLat(e),n=new t.a1(s.x-(r.x-a.x),s.y-(r.y-a.y));this.setCenter(null==n?void 0:n.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,i){return i?this.coordinatePoint(t.a1.fromLngLat(e),i.getElevationForLngLatZoom(e,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(t.a1.fromLngLat(e))}screenPointToLocation(e,t){var i;return null===(i=this.screenPointToMercatorCoordinate(e,t))||void 0===i?void 0:i.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const o=i||0,r=[e.x,e.y,0,1],a=[e.x,e.y,1,1];t.aw(r,r,this._pixelMatrixInverse),t.aw(a,a,this._pixelMatrixInverse);const s=r[3],n=a[3],l=r[1]/s,c=a[1]/n,h=r[2]/s,u=a[2]/n,d=h===u?0:(o-h)/(u-h);return new t.a1(t.C.number(r[0]/s,a[0]/n,d)/this.worldSize,t.C.number(l,c,d)/this.worldSize,o)}coordinatePoint(e,i=0,o=this._pixelMatrix){const r=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.aw(r,r,o),new t.P(r[0]/r[3],r[1]/r[3])}getBounds(){const e=Math.max(0,this._helper._height/2-he(this));return (new G).extend(this.screenPointToLocation(new t.P(0,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.P(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-he(this)}calculatePosMatrix(e,i=!1,o){var r;const a=null!==(r=e.key)&&void 0!==r?r:t.b3(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),s=i?this._alignedPosMatrixCache:this._posMatrixCache;if(s.has(a)){const e=s.get(a);return o?e.f32:e.f64}const n=ue(e,this.worldSize);t.O(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return s.set(a,l),o?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,o=this._fogMatrixCacheF32;if(o.has(i))return o.get(i);const r=ue(e,this.worldSize);return t.O(r,this._fogMatrix,r),o.set(i,new Float32Array(r)),o.get(i)}getConstrained(e,i){i=t.ah(+i,this.minZoom,this.maxZoom);const o={center:new t.S(e.lng,e.lat),zoom:i};let r=this._helper._lngRange;if(!this._helper._renderWorldCopies&&null===r){const e=180-1e-10;r=[-e,e];}const a=this.tileSize*t.af(o.zoom);let s=0,n=a,l=0,c=a,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;s=t.U(e[1])*a,n=t.U(e[0])*a,n-s<_&&(h=_/(n-s));}r&&(l=t.aO(t.V(r[0])*a,0,a),c=t.aO(t.V(r[1])*a,0,a),cn&&(g=n-e);}if(r){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.aO(p,e-a/2,e+a/2));const o=d/2;i-oc&&(f=c-o);}if(void 0!==f||void 0!==g){const e=new t.P(null!=f?f:p,null!=g?g:m);o.center=ce(a,e).wrap();}return o}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}_calculateNearFarZIfNeeded(e,i,o){if(!this._helper.autoCalculateNearFarZ)return;const r=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),a=e-r*this._helper._pixelPerMeter/Math.cos(i),s=r<0?a:e,n=Math.PI/2+this.pitchInRadians,l=t.ae(this.fov)*(Math.abs(Math.cos(t.ae(this.roll)))*this.height+Math.abs(Math.sin(t.ae(this.roll)))*this.width)/this.height*(.5+o.y/this.height),c=Math.sin(l)*s/Math.sin(t.ah(Math.PI-n-l,.01,Math.PI-.01)),h=he(this),u=Math.atan(h/this._helper.cameraToCenterDistance),d=t.ae(.75),_=u>d?2*u*(.5+o.y/(2*h)):d,p=Math.sin(_)*s/Math.sin(t.ah(Math.PI-n-_,.01,Math.PI-.01)),m=Math.min(c,p);this._helper._farZ=1.01*(Math.cos(Math.PI/2-i)*m+s),this._helper._nearZ=this._helper._height/50;}_calcMatrices(){if(!this._helper._height)return;const e=this.centerOffset,i=le(this.worldSize,this.center),o=i.x,r=i.y;this._helper._pixelPerMeter=t.aj(1,this.center.lat)*this.worldSize;const a=t.ae(Math.min(this.pitch,ne)),s=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(a));let n;this._calculateNearFarZIfNeeded(s,a,e),n=new Float64Array(16),t.b4(n,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),t.aq(this._invProjMatrix,n),n[8]=2*-e.x/this._helper._width,n[9]=2*e.y/this._helper._height,this._projectionMatrix=t.b5(n),t.N(n,n,[1,-1,1]),t.M(n,n,[0,0,-this._helper.cameraToCenterDistance]),t.b6(n,n,-this.rollInRadians),t.b7(n,n,this.pitchInRadians),t.b6(n,n,-this.bearingInRadians),t.M(n,n,[-o,-r,0]),this._mercatorMatrix=t.N([],n,[this.worldSize,this.worldSize,this.worldSize]),t.N(n,n,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n),t.M(n,n,[0,0,-this.elevation]),this._viewProjMatrix=n,this._invViewProjMatrix=t.aq([],n);const l=[0,0,-1,1];t.aw(l,l,this._invViewProjMatrix),this._cameraPosition=[l[0]/l[3],l[1]/l[3],l[2]/l[3]],this._fogMatrix=new Float64Array(16),t.b4(this._fogMatrix,this.fovInRadians,this.width/this.height,s,this._helper._farZ),this._fogMatrix[8]=2*-e.x/this.width,this._fogMatrix[9]=2*e.y/this.height,t.N(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.b6(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.b7(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.b6(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.M(this._fogMatrix,this._fogMatrix,[-o,-r,0]),t.N(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n);const c=this._helper._width%2/2,h=this._helper._height%2/2,u=Math.cos(this.bearingInRadians),d=Math.sin(-this.bearingInRadians),_=o-Math.round(o)+u*c+d*h,p=r-Math.round(r)+u*h+d*c,m=new Float64Array(n);if(t.M(m,m,[_>.5?_-1:_,p>.5?p-1:p,0]),this._alignedProjMatrix=m,n=t.aq(new Float64Array(16),this._pixelMatrix),!n)throw new Error("failed to invert matrix");this._pixelMatrixInverse=n,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.P(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.aw(i,i,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/e).toLngLat()}lngLatToCameraDepth(e,i){const o=t.a1.fromLngLat(e),r=[o.x*this.worldSize,o.y*this.worldSize,i,1];return t.aw(r,r,this._viewProjMatrix),r[2]/r[3]}getProjectionData(e){const{overscaledTileID:i,aligned:o,applyTerrainMatrix:r}=e,a=this._helper.getMercatorTileCoordinates(i),s=i?this.calculatePosMatrix(i,o,!0):null;let n;return n=i&&i.terrainRttPosMatrix32f&&r?i.terrainRttPosMatrix32f:s||t.b8(),{mainMatrix:n,tileMercatorCoords:a,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:n}}isLocationOccluded(e){return !1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,i){return 1}transformLightDirection(e){return t.aT(e)}getRayDirectionFromPixel(e){throw new Error("Not implemented.")}projectTileCoordinates(e,i,o,r){const a=this.calculatePosMatrix(o);let s;r?(s=[e,i,r(e,i),1],t.aw(s,s,a)):(s=[e,i,0,1],qe(s,s,a));const n=s[3];return {point:new t.P(s[0]/n,s[1]/n),signedDistanceFromCamera:n,isOccluded:!1}}populateCache(e){for(const t of e)this.calculatePosMatrix(t);}getMatrixForModel(e,i){const o=t.a1.fromLngLat(e,i),r=o.meterInMercatorCoordinateUnits(),a=t.b9();return t.M(a,a,[o.x,o.y,o.z]),t.b6(a,a,Math.PI),t.b7(a,a,Math.PI/2),t.N(a,a,[-r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=new t.Z(0,0,0,0,0),o=this.getProjectionData({overscaledTileID:i,applyGlobeMatrix:e}),r=ue(i,this.worldSize);t.O(r,this._viewProjMatrix,r),o.tileMercatorCoords=[0,0,1,1];const a=[t.$,t.$,this.worldSize/this._helper.pixelsPerMeter],s=t.ba();return t.N(s,r,a),o.fallbackMatrix=s,o.mainMatrix=s,o}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}}function kt(){t.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");}function Ft(e){if(e.useSlerp)if(e.k<1){const i=t.bb(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),o=t.bb(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),r=new Float64Array(4);t.bc(r,i,o,e.k);const a=t.bd(r);e.tr.setRoll(a.roll),e.tr.setPitch(a.pitch),e.tr.setBearing(a.bearing);}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(t.C.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(t.C.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(t.C.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k));}function Bt(e,i,o,r,a){const s=a.padding,n=le(a.worldSize,o.getNorthWest()),l=le(a.worldSize,o.getNorthEast()),c=le(a.worldSize,o.getSouthEast()),h=le(a.worldSize,o.getSouthWest()),u=t.ae(-r),d=n.rotate(u),_=l.rotate(u),p=c.rotate(u),m=h.rotate(u),f=new t.P(Math.max(d.x,_.x,m.x,p.x),Math.max(d.y,_.y,m.y,p.y)),g=new t.P(Math.min(d.x,_.x,m.x,p.x),Math.min(d.y,_.y,m.y,p.y)),v=f.sub(g),b=(a.width-(s.left+s.right+i.left+i.right))/v.x,x=(a.height-(s.top+s.bottom+i.top+i.bottom))/v.y;if(x<0||b<0)return void kt();const y=Math.min(t.ak(a.scale*Math.min(b,x)),e.maxZoom),w=t.P.convert(e.offset),T=new t.P((i.left-i.right)/2,(i.top-i.bottom)/2).rotate(t.ae(r)),P=w.add(T).mult(a.scale/t.af(y));return {center:ce(a.worldSize,n.add(c).div(2).sub(P)),zoom:y,bearing:r}}class Ot{get useGlobeControls(){return !1}handlePanInertia(e,t){const i=e.mag(),o=Math.abs(he(t));return {easingOffset:e.mult(Math.min(.75*o/i,1)),easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta);}handleMapControlsPan(e,t,i){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(i,e.around);}cameraForBoxAndBearing(e,t,i,o,r){return Bt(e,t,i,o,r)}handleJumpToCenterZoom(e,i){e.zoom!==(void 0!==i.zoom?+i.zoom:e.zoom)&&e.setZoom(+i.zoom),void 0!==i.center&&e.setCenter(t.S.convert(i.center));}handleEaseTo(e,i){const o=e.zoom,r=e.padding,a={roll:e.roll,pitch:e.pitch,bearing:e.bearing},s={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},n=void 0!==i.zoom,l=!e.isPaddingEqual(i.padding);let c=!1;const h=n?+i.zoom:e.zoom;let u=e.centerPoint.add(i.offsetAsPoint);const d=e.screenPointToLocation(u),{center:_,zoom:p}=e.getConstrained(t.S.convert(i.center||d),null!=h?h:o);St(e,_);const m=le(e.worldSize,d),f=le(e.worldSize,_).sub(m),g=t.af(p-o);return c=p!==o,{easeFunc:n=>{if(c&&e.setZoom(t.C.number(o,p,n)),t.be(a,s)||Ft({startEulerAngles:a,endEulerAngles:s,tr:e,k:n,useSlerp:a.roll!=s.roll}),l&&(e.interpolatePadding(r,i.padding,n),u=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const i=t.af(e.zoom-o),r=p>o?Math.min(2,g):Math.max(.5,g),a=Math.pow(r,1-n),s=ce(e.worldSize,m.add(f.mult(n*a)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?s.wrap():s,u);}},isZooming:c,elevationCenter:_}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.zoom,a=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),o?+i.zoom:r),s=a.center,n=a.zoom;St(e,s);const l=le(e.worldSize,i.locationAtOffset),c=le(e.worldSize,s).sub(l),h=c.mag(),u=t.af(n-r);let d;if(void 0!==i.minZoom){const o=Math.min(+i.minZoom,r,n),a=e.getConstrained(s,o).zoom;d=t.af(a-r);}return {easeFunc:(i,o,a,h)=>{e.setZoom(1===i?n:r+t.ak(o));const u=1===i?s:ce(e.worldSize,l.add(c.mult(a)).mult(o));e.setLocationAtPoint(e.renderWorldCopies?u.wrap():u,h);},scaleOfZoom:u,targetCenter:s,scaleOfMinZoom:d,pixelPathLength:h}}}class jt{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}jt.Replace=[1,0],jt.disabled=new jt(jt.Replace,t.bf.transparent,[!1,!1,!1,!1]),jt.unblended=new jt(jt.Replace,t.bf.transparent,[!0,!0,!0,!0]),jt.alphaBlended=new jt([1,771],t.bf.transparent,[!0,!0,!0,!0]);const Nt=2305;class Ut{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}Ut.disabled=new Ut(!1,1029,Nt),Ut.backCCW=new Ut(!0,1029,Nt),Ut.frontCCW=new Ut(!0,1028,Nt);class Zt{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Zt.ReadOnly=!1,Zt.ReadWrite=!0,Zt.disabled=new Zt(519,Zt.ReadOnly,[0,1]);const Gt=7680;class Vt{constructor(e,t,i,o,r,a){this.test=e,this.ref=t,this.mask=i,this.fail=o,this.depthFail=r,this.pass=a;}}Vt.disabled=new Vt({func:519,mask:0},0,0,Gt,Gt,Gt);const $t=new WeakMap;function qt(e){var t;if($t.has(e))return $t.get(e);{const i=null===(t=e.getParameter(e.VERSION))||void 0===t?void 0:t.startsWith("WebGL 2.0");return $t.set(e,i),i}}class Wt{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,o=i.gl;this._texFormat=o.RGBA,this._texType=o.UNSIGNED_BYTE;const r=new t.aL;r.emplaceBack(-1,-1),r.emplaceBack(2,-1),r.emplaceBack(-1,2);const a=new t.aN;a.emplaceBack(0,1,2),this._fullscreenTriangle=new wt(i.createVertexBuffer(r,Tt.members),i.createIndexBuffer(a),t.aM.simpleSegment(0,0,r.length,a.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(o.TEXTURE1);const s=o.createTexture();o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texImage2D(o.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(s),qt(o)&&(this._pbo=o.createBuffer(),o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.bufferData(o.PIXEL_PACK_BUFFER,4,o.STREAM_READ),o.bindBuffer(o.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const o=this._cachedRenderContext.context,r=o.gl;if(this._bindFramebuffer(),o.viewport.set([0,0,this._texWidth,this._texHeight]),o.clear({color:t.bf.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(o,r.TRIANGLES,Zt.disabled,Vt.disabled,jt.unblended,Ut.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&qt(r)){r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.readBuffer(r.COLOR_ATTACHMENT0),r.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),r.bindBuffer(r.PIXEL_PACK_BUFFER,null);const e=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);r.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&qt(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=Wt._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const Ht=t.$/128;function Xt(e,i){const o=void 0!==e.granularity?Math.max(e.granularity,1):1,r=o+(e.generateBorders?2:0),a=o+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),s=r+1,n=a+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=o+(e.generateBorders?1:0),u=o+(e.generateBorders||e.extendToSouthPole?1:0),d=s*n,_=r*a*6,p=s*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g=0;for(let i=c;i<=u;i++)for(let r=l;r<=h;r++){let a=r/o*t.$;-1===r&&(a=-Ht),r===o+1&&(a=t.$+Ht);let s=i/o*t.$;-1===i&&(s=e.extendToNorthPole?t.bh:-Ht),i===o+1&&(s=e.extendToSouthPole?t.bi:t.$+Ht),f[g++]=a,f[g++]=s;}const v=m?new Uint32Array(_):new Uint16Array(_);let b=0;for(let e=0;e0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return "globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy();}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e);}getMeshFromTileID(e,t,i,o,r){return this.currentProjection.getMeshFromTileID(e,t,i,o,r)}setProjection(e){this._transitionable.setValue("type",(null==e?void 0:e.type)||"mercator");}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e);}}function ei(e){const t=oi(e.worldSize,e.center.lat);return 2*Math.PI*t}function ti(e,i,o,r,a){const s=1/(1<1e-6){const r=e[0]/o,a=Math.acos(e[2]/o),s=(r>0?a:-a)/Math.PI*180;return new t.S(t.aO(s,-180,180),i)}return new t.S(0,i)}function ai(e){return Math.cos(e*Math.PI/180)}function si(e,i){const o=ai(e),r=ai(i);return t.ak(r/o)}function ni(e,i){const o=e.rotate(i.bearingInRadians),r=i.zoom+si(i.center.lat,0),a=t.bk(1/ai(i.center.lat),1/ai(Math.min(Math.abs(i.center.lat),60)),t.bn(r,7,3,0,1)),s=360/ei({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.S(i.center.lng-o.x*s*a,t.ah(i.center.lat+o.y*s,-t.ai,t.ai))}function li(e){const t=.5*e,i=Math.sin(t),o=Math.cos(t);return Math.log(i+o)-Math.log(o-i)}function ci(e,i,o,r){const a=e.lat+o*r;if(Math.abs(o)>1){const s=(Math.sign(e.lat+o)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+o)*Math.PI/180,l=li(s+r*(n-s)),c=li(s),h=li(n);return new t.S(e.lng+i*((l-c)/(h-c)),a)}return new t.S(e.lng+i*r,a)}class hi{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._boundingVolumeFactory=e;}swapBuffers(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1;}getTileBoundingVolume(e,t,i,o){const r=`${e.z}_${e.x}_${e.y}_${(null==o?void 0:o.terrain)?"t":""}`,a=this._cache.get(r);if(a)return a;const s=this._cachePrevious.get(r);if(s)return this._cache.set(r,s),s;const n=this._boundingVolumeFactory(e,t,i,o);return this._cache.set(r,n),this._hadAnyChanges=!0,n}}class ui{constructor(e,t,i,o){this.min=i,this.max=o,this.points=e,this.planes=t;}static fromAabb(e,t){const i=[];for(let o=0;o<8;o++)i.push([1&~o?e[0]:t[0],1==(o>>1&1)?t[1]:e[1],1==(o>>2&1)?t[2]:e[2]]);return new ui(i,[[-1,0,0,t[0]],[1,0,0,-e[0]],[0,-1,0,t[1]],[0,1,0,-e[1]],[0,0,-1,t[2]],[0,0,1,-e[2]]],e,t)}static fromCenterSizeAngles(e,i,o){const r=t.br([],o[0],o[1],o[2]),a=t.bs([],[i[0],0,0],r),s=t.bs([],[0,i[1],0],r),n=t.bs([],[0,0,i[2]],r),l=[...e],c=[...e];for(let t=0;t<8;t++)for(let i=0;i<3;i++){const o=e[i]+a[i]*(1&~t?-1:1)+s[i]*(1==(t>>1&1)?1:-1)+n[i]*(1==(t>>2&1)?1:-1);l[i]=Math.min(l[i],o),c[i]=Math.max(c[i],o);}const h=[];for(let i=0;i<8;i++){const o=[...e];t.aS(o,o,t.aR([],a,1&~i?-1:1)),t.aS(o,o,t.aR([],s,1==(i>>1&1)?1:-1)),t.aS(o,o,t.aR([],n,1==(i>>2&1)?1:-1)),h.push(o);}return new ui(h,[[...a,-t.aX(a,h[0])],[...s,-t.aX(s,h[0])],[...n,-t.aX(n,h[0])],[-a[0],-a[1],-a[2],-t.aX(a,h[7])],[-s[0],-s[1],-s[2],-t.aX(s,h[7])],[-n[0],-n[1],-n[2],-t.aX(n,h[7])]],l,c)}intersectsFrustum(e){let t=!0;const i=this.points.length,o=this.planes.length,r=e.planes.length,a=e.points.length;for(let o=0;o=0&&a++;}if(0===a)return 0;a=0&&o++;}if(0===o)return 0}return 1}intersectsPlane(e){const t=this.points.length;let i=0;for(let o=0;o=0&&i++;}return i===t?2:0===i?0:1}}function di(e,t,i){const o=e-t;return o<0?-o:Math.max(0,o-i)}function _i(e,t,i,o,r){const a=e-i;let s;return s=a<0?Math.min(-a,1+a-r):a>1?Math.min(Math.max(a-r,0),1-a):0,Math.max(s,di(t,o,r))}class pi{constructor(){this._boundingVolumeCache=new hi(this._computeTileBoundingVolume);}prepareNextFrame(){this._boundingVolumeCache.swapBuffers();}distanceToTile2d(e,t,i,o){const r=1<4}allowWorldCopies(){return !1}getTileBoundingVolume(e,t,i,o){return this._boundingVolumeCache.getTileBoundingVolume(e,t,i,o)}_computeTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}if(n/=t.bu,l/=t.bu,n+=1,l+=1,e.z<=0)return ui.fromAabb([-l,-l,-l],[l,l,l]);if(1===e.z)return ui.fromAabb([0===e.x?-l:0,0===e.y?0:-l,-l],[0===e.x?0:l,0===e.y?l:0,l]);{const i=[ti(0,0,e.x,e.y,e.z),ti(t.$,0,e.x,e.y,e.z),ti(t.$,t.$,e.x,e.y,e.z),ti(0,t.$,e.x,e.y,e.z)],o=[];for(const e of i)o.push(t.aR([],e,l));if(l!==n)for(const e of i)o.push(t.aR([],e,n));0===e.y&&o.push([0,1,0]),e.y===(1<=(1<{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._coveringTilesDetailsProvider=new pi;}clone(){const e=new fi;return e.apply(this),e}apply(e,t){this._globeLatitudeErrorCorrectionRadians=t||0,this._helper.apply(e);}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const e=t.bp();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(e){const{overscaledTileID:t,applyGlobeMatrix:i}=e,o=this._helper.getMercatorTileCoordinates(t);return {mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:o,clippingPlane:this._cachedClippingPlane,projectionTransition:i?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(e){const i=this.pitchInRadians,o=this.cameraToCenterDistance/e,r=Math.sin(i)*o,a=Math.cos(i)*o+1,s=1/Math.sqrt(r*r+a*a)*1;let n=-r,l=a;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];t.bw(h,h,[0,0,0],-this.bearingInRadians),t.bx(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.by(h,h,[0,0,0],this.center.lng*Math.PI/180);const u=1/t.aZ(h);return t.aR(h,h,u),[...h,-s*u]}isLocationOccluded(e){return !this.isSurfacePointVisible(ii(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,o=this._helper._center.lat*Math.PI/180,r=Math.cos(o),a=[Math.sin(i)*r,Math.sin(o),Math.cos(i)*r],s=[a[2],0,-a[0]],n=[0,0,0];t.aW(n,s,a),t.aV(s,s),t.aV(n,n);const l=[0,0,0];return t.aV(l,[s[0]*e[0]+n[0]*e[1]+a[0]*e[2],s[1]*e[0]+n[1]*e[1]+a[1]*e[2],s[2]*e[0]+n[2]*e[1]+a[2]*e[2]]),l}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(e,i,o){const r=function(e,i,o){const r=1/(1<a&&(a=i),on&&(n=o);}const h=[c.lng+s,c.lat+l,c.lng+a,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new G(h)}getConstrained(e,i){const o=t.ah(e.lat,-t.ai,t.ai),r=t.ah(+i,this.minZoom+si(0,o),this.maxZoom);return {center:new t.S(e.lng,o),zoom:r}}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,i){const o=ii(this.unprojectScreenPoint(i)),r=ii(e),a=t.bp();t.bB(a);const s=t.bp();t.by(s,o,a,-this.center.lng*Math.PI/180),t.bx(s,s,a,this.center.lat*Math.PI/180);const n=r[0]*r[0]+r[2]*r[2],l=s[0]*s[0];if(n=-g&&p<=g,b=f>=-g&&f<=g;let x,y;if(v&&b){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.bD(u,e)+t.bD(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return !1;const i=t.bv();return t.aw(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const o=t.aX(e,i),r=t.bp(),a=t.bp();t.aR(a,i,o),t.aU(r,e,a);const s=1-t.aX(r,r);if(s<0)return null;const n=t.aX(e,e)-1,l=-o+(o<0?1:-1)*Math.sqrt(s),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,o=this.getRayDirectionFromPixel(e),r=this.rayPlanetIntersection(i,o);if(r){const e=t.bp();t.aS(e,i,[o[0]*r.tMin,o[1]*r.tMin,o[2]*r.tMin]);const a=t.bp();return t.aV(a,e),ri(a)}const a=this._cachedClippingPlane,s=a[0]*o[0]+a[1]*o[1]+a[2]*o[2],n=-t.b1(a,i)/s,l=t.bp();if(n>0)t.aS(l,i,[o[0]*n,o[1]*n,o[2]*n]);else {const e=t.bp();t.aS(e,i,[2*o[0],2*o[1],2*o[2]]);const r=t.b1(this._cachedClippingPlane,e);t.aU(l,e,[this._cachedClippingPlane[0]*r,this._cachedClippingPlane[1]*r,this._cachedClippingPlane[2]*r]);}const c=function(e){const i=t.bp();return i[0]=e[0]*-e[3],i[1]=e[1]*-e[3],i[2]=e[2]*-e[3],{center:i,radius:Math.sqrt(1-e[3]*e[3])}}(a);return ri(function(e,i,o){const r=t.bp();t.aU(r,o,e);const a=t.bp();return t.bq(a,e,r,i/t.a$(r)),a}(c.center,c.radius,l))}getMatrixForModel(e,i){const o=t.S.convert(e),r=1/t.bu,a=t.b9();return t.bz(a,a,o.lng/180*Math.PI),t.b7(a,a,-o.lat/180*Math.PI),t.M(a,a,[0,0,1+i/t.bu]),t.b7(a,a,.5*Math.PI),t.N(a,a,[r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=this.getProjectionData({overscaledTileID:new t.Z(0,0,0,0,0),applyGlobeMatrix:e});return i.tileMercatorCoords=[0,0,1,1],i}getFastPathSimpleProjectionMatrix(e){}}class gi{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame(),this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame();}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._globeness=1,this._mercatorTransform=new Lt,this._verticalPerspectiveTransform=new fi;}clone(){const e=new gi;return e._globeness=this._globeness,e._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,e.apply(this),e}apply(e){this._helper.apply(e),this._mercatorTransform.apply(this),this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians);}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){const t=this._mercatorTransform.getProjectionData(e),i=this._verticalPerspectiveTransform.getProjectionData(e);return {mainMatrix:this.isGlobeRendering?i.mainMatrix:t.mainMatrix,clippingPlane:i.clippingPlane,tileMercatorCoords:i.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return t.bk(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return t.bk(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,i,o){const r=this._mercatorTransform.getPitchedTextCorrection(e,i,o),a=this._verticalPerspectiveTransform.getPitchedTextCorrection(e,i,o);return t.bk(r,a,this._globeness)}projectTileCoordinates(e,t,i,o){return this.currentTransform.projectTileCoordinates(e,t,i,o)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ);}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this._mercatorTransform.recalculateZoomAndCenter(e),this._verticalPerspectiveTransform.recalculateZoomAndCenter(e);}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e);}getBounds(){return this.currentTransform.getBounds()}getConstrained(e,t){return this.currentTransform.getConstrained(e,t)}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,t){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,t),void this.apply(this._mercatorTransform);this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform);}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getMatrixForModel(e,t){return this.currentTransform.getMatrixForModel(e,t)}getProjectionDataForCustomLayer(e=!0){const t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;const i=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return i.fallbackMatrix=t.mainMatrix,i}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}}class vi{get useGlobeControls(){return !0}handlePanInertia(e,i){const o=ni(e,i);return Math.abs(o.lng-i.center.lng)>180&&(o.lng=i.center.lng+179.5*Math.sign(o.lng-i.center.lng)),{easingCenter:o,easingOffset:new t.P(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){const o=e.around,r=i.screenPointToLocation(o);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const a=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const s=i.zoom-a;if(0===s)return;const n=t.bA(i.center.lng,r.lng),l=n/(Math.abs(n/180)+1),c=t.bA(i.center.lat,r.lat),h=i.getRayDirectionFromPixel(o),u=i.cameraPosition,d=-1*t.aX(u,h),_=t.bp();t.aS(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.aZ(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=oi(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.bn(f,.9,.5,1,.25),v=(1-t.af(-s))*Math.min(m,g),b=i.center.lat,x=i.zoom,y=new t.S(i.center.lng+l*v,t.ah(i.center.lat+c*v,-t.ai,t.ai));i.setLocationAtPoint(r,o);const w=i.center,T=t.bn(Math.abs(n),45,85,0,1),P=t.bn(f,.75,.35,0,1),C=Math.pow(Math.max(T,P),.25),I=t.bA(w.lng,y.lng),M=t.bA(w.lat,y.lat);i.setCenter(new t.S(w.lng+I*C,w.lat+M*C).wrap()),i.setZoom(x+si(b,i.center.lat));}handleMapControlsPan(e,t,i){if(!e.panDelta)return;const o=t.center.lat,r=t.zoom;t.setCenter(ni(e.panDelta,t).wrap()),t.setZoom(r+si(o,t.center.lat));}cameraForBoxAndBearing(e,i,o,r,a){const s=Bt(e,i,o,r,a),n=i.left/a.width*2-1,l=(a.width-i.right)/a.width*2-1,c=i.top/a.height*-2+1,h=(a.height-i.bottom)/a.height*-2+1,u=t.bA(o.getWest(),o.getEast())<0,d=u?o.getEast():o.getWest(),_=u?o.getWest():o.getEast(),p=Math.max(o.getNorth(),o.getSouth()),m=Math.min(o.getNorth(),o.getSouth()),f=d+.5*t.bA(d,_),g=p+.5*t.bA(p,m),v=a.clone();v.setCenter(s.center),v.setBearing(s.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(s.zoom);const b=v.modelViewProjectionMatrix,x=[ii(o.getNorthWest()),ii(o.getNorthEast()),ii(o.getSouthWest()),ii(o.getSouthEast()),ii(new t.S(_,g)),ii(new t.S(d,g)),ii(new t.S(f,p)),ii(new t.S(f,m))],y=ii(s.center);let w=Number.POSITIVE_INFINITY;for(const e of x)n<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",n))),l>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",l))),c>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",c))),h<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",h)));if(Number.isFinite(w)&&0!==w)return s.zoom=v.zoom+t.ak(w),s;kt();}handleJumpToCenterZoom(e,i){const o=e.center.lat,r=e.getConstrained(i.center?t.S.convert(i.center):e.center,e.zoom).center;e.setCenter(r.wrap());const a=void 0!==i.zoom?+i.zoom:e.zoom+si(o,r.lat);e.zoom!==a&&e.setZoom(a);}handleEaseTo(e,i){const o=e.zoom,r=e.center,a=e.padding,s={roll:e.roll,pitch:e.pitch,bearing:e.bearing},n={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},l=void 0!==i.zoom,c=!e.isPaddingEqual(i.padding);let h=!1;const u=i.center?t.S.convert(i.center):r,d=e.getConstrained(u,o).center;St(e,d);const _=e.clone();_.setCenter(d),_.setZoom(l?+i.zoom:o+si(r.lat,u.lat)),_.setBearing(i.bearing);const p=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));_.setLocationAtPoint(d,p);const m=(i.offset&&i.offsetAsPoint.mag())>0?_.center:d,f=l?+i.zoom:o+si(r.lat,m.lat),g=o+si(r.lat,0),v=f+si(m.lat,0),b=t.bA(r.lng,m.lng),x=t.bA(r.lat,m.lat),y=t.af(v-g);return h=f!==o,{easeFunc:o=>{if(t.be(s,n)||Ft({startEulerAngles:s,endEulerAngles:n,tr:e,k:o,useSlerp:s.roll!=n.roll}),c&&e.interpolatePadding(a,i.padding,o),i.around)t.w("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=v>g?Math.min(2,y):Math.max(.5,y),i=Math.pow(t,1-o),a=ci(r,b,x,o*i);e.setCenter(a.wrap());}if(h){const i=t.C.number(g,v,o)+si(0,e.center.lat);e.setZoom(i);}},isZooming:h,elevationCenter:m}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.center,a=e.zoom,s=e.padding,n=!e.isPaddingEqual(i.padding),l=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),a).center,c=o?+i.zoom:e.zoom+si(e.center.lat,l.lat),h=e.clone();h.setCenter(l),h.setZoom(c),h.setBearing(i.bearing);const u=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));h.setLocationAtPoint(l,u);const d=h.center;St(e,d);const _=function(e,i,o){const r=ii(i),a=ii(o),s=t.aX(r,a),n=Math.acos(s),l=ei(e);return n/(2*Math.PI)*l}(e,r,d),p=a+si(r.lat,0),m=c+si(d.lat,0),f=t.af(m-p);let g;if("number"==typeof i.minZoom){const o=+i.minZoom+si(d.lat,0),r=Math.min(o,p,m)+si(0,d.lat),a=e.getConstrained(d,r).zoom+si(d.lat,0);g=t.af(a-p);}const v=t.bA(r.lng,d.lng),b=t.bA(r.lat,d.lat);return {easeFunc:(o,a,l,h)=>{const u=ci(r,v,b,l);n&&e.interpolatePadding(s,i.padding,o);const _=1===o?d:u;e.setCenter(_.wrap());const m=p+t.ak(a);e.setZoom(1===o?c:m+si(0,_.lat));},scaleOfZoom:f,targetCenter:d,scaleOfMinZoom:g,pixelPathLength:_}}static solveVectorScale(e,t,i,o,r){const a="x"===o?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],s=[i[3],i[7],i[11],i[15]],n=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],l=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],c=t[0]*a[0]+t[1]*a[1]+t[2]*a[2],h=t[0]*s[0]+t[1]*s[1]+t[2]*s[2];return c+r*l===n+r*h||s[3]*(n-c)+a[3]*(h-l)+n*h==c*l?null:(c+a[3]-r*h-r*s[3])/(c-n-r*h+r*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.y(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),yi=t.bE();class wi extends t.E{constructor(e,i={}){var o,r;super(),this._rtlPluginLoaded=()=>{for(const e in this.sourceCaches){const t=this.sourceCaches[e].getSource().type;"vector"!==t&&"geojson"!==t||this.sourceCaches[e].reload();}},this.map=e,this.dispatcher=new F(k(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.imageManager=new b,this.imageManager.setEventedParent(this);const a=(null===(o=e._container)||void 0===o?void 0:o.lang)||"undefined"!=typeof document&&(null===(r=document.documentElement)||void 0===r?void 0:r.lang)||void 0;this.glyphManager=new T(e._requestManager,i.localIdeographFontFamily,a),this.lineAtlas=new E(256,512),this.crossTileSymbolIndex=new vt,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.bF,this._loaded=!1,this._availableImages=[],this._globalState={},this._resetUpdates(),this.dispatcher.broadcast("SR",t.bG()),oe().on(ee,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.sourceCaches[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}setGlobalStateProperty(e,i){var o,r,a;this._checkLoaded();const s=null===i?null!==(a=null===(r=null===(o=this.stylesheet.state)||void 0===o?void 0:o[e])||void 0===r?void 0:r.default)&&void 0!==a?a:null:i;if(t.bH(s,this._globalState[e]))return this;this._globalState[e]=s,this._applyGlobalStateChanges([e]);}getGlobalState(){return this._globalState}setGlobalState(e){this._checkLoaded();const i=[];for(const o in e)!t.bH(this._globalState[o],e[o].default)&&(i.push(o),this._globalState[o]=e[o].default);this._applyGlobalStateChanges(i);}_applyGlobalStateChanges(e){if(0===e.length)return;const t=new Set,i={};for(const o of e){i[o]=this._globalState[o];for(const e in this._layers){const i=this._layers[e],r=i.getLayoutAffectingGlobalStateRefs(),a=i.getPaintAffectingGlobalStateRefs();if(r.has(o)&&t.add(i.source),a.has(o))for(const{name:e,value:t}of a.get(o))this._updatePaintProperty(i,e,t);}}this.dispatcher.broadcast("UGS",i);for(const e in this.sourceCaches)t.has(e)&&(this._reloadSource(e),this._changed=!0);}loadURL(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const r=this.map._requestManager.transformRequest(e,"Style");this._loadStyleRequest=new AbortController;const a=this._loadStyleRequest;t.j(r,this._loadStyleRequest).then((e=>{this._loadStyleRequest=null,this._load(e.data,i,o);})).catch((e=>{this._loadStyleRequest=null,e&&!a.signal.aborted&&this.fire(new t.k(e));}));}loadJSON(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,s.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=!1!==i.validate,this._load(e,i,o);})).catch((()=>{}));}loadEmpty(){this.fire(new t.l("dataloading",{dataType:"style"})),this._load(yi,{validate:!1});}_load(e,i,o){var r,a;let s=i.transformStyle?i.transformStyle(o,e):e;if(!i.validate||!xi(this,t.z(s))){s=Object.assign({},s),this._loaded=!0,this.stylesheet=s;for(const e in s.sources)this.addSource(e,s.sources[e],{validate:!1});s.sprite?this._loadSprite(s.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(s.glyphs),this._createLayers(),this.light=new I(this.stylesheet.light),this._setProjectionInternal((null===(r=this.stylesheet.projection)||void 0===r?void 0:r.type)||"mercator"),this.sky=new S(this.stylesheet.sky),this.map.setTerrain(null!==(a=this.stylesheet.terrain)&&void 0!==a?a:null),this.fire(new t.l("data",{dataType:"style"})),this.fire(new t.l("style.load"));}}_createLayers(){var e;const i=t.bI(this.stylesheet.layers);this.setGlobalState(null!==(e=this.stylesheet.state)&&void 0!==e?e:null),this.dispatcher.broadcast("SL",i),this._order=i.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const e of i){const i=t.bJ(e,this._globalState);i.setEventedParent(this,{layer:{id:e.id}}),this._layers[e.id]=i;}}_loadSprite(e,i=!1,o=void 0){let r;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=f(e),n=o>1?"@2x":"",l={},c={};for(const{id:e,url:o}of a){const a=i.transformRequest(g(o,n,".json"),"SpriteJSON");l[e]=t.j(a,r);const s=i.transformRequest(g(o,n,".png"),"SpriteImage");c[e]=p.getImage(s,r);}return yield Promise.all([...Object.values(l),...Object.values(c)]),function(e,i){return t._(this,void 0,void 0,(function*(){const t={};for(const o in e){t[o]={};const r=s.getImageCanvasContext((yield i[o]).data),a=(yield e[o]).data;for(const e in a){const{width:i,height:s,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=a[e];t[o][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:s,x:n,y:l,context:r}};}}return t}))}(l,c)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const o=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of o)this.imageManager.removeImage(e),this._changedImages[e]=!0;for(const o in e[t]){const r="default"===t?o:`${t}:${o}`;this._spritesImagesIds[t].push(r),r in this.imageManager.images?this.imageManager.updateImage(r,e[t][o],!1):this.imageManager.addImage(r,e[t][o]),i&&(this._changedImages[r]=!0);}}})).catch((e=>{this._spriteRequest=null,r=e,this.fire(new t.k(r));})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),i&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"})),o&&o(r);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}_validateLayer(e){const i=this.sourceCaches[e.source];if(!i)return;const o=e.sourceLayer;if(!o)return;const r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.k(new Error(`Source layer "${o}" does not exist on source "${r.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(const e in this.sourceCaches)if(!this.sourceCaches[e].loaded())return !1;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=!1){const o=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.bK(o):o);const r=[];for(const a of e)if(o[a]){const e=i?t.bK(o[a]):o[a];r.push(e);}return r}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){var e,t,i;if(null===(e=this.light)||void 0===e?void 0:e.hasTransition())return !0;if(null===(t=this.sky)||void 0===t?void 0:t.hasTransition())return !0;if(null===(i=this.projection)||void 0===i?void 0:i.hasTransition())return !0;for(const e in this.sourceCaches)if(this.sourceCaches[e].hasTransition())return !0;for(const e in this._layers)if(this._layers[e].hasTransition())return !0;return !1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const o={};for(const e in this.sourceCaches){const t=this.sourceCaches[e];o[e]=t.used,t.used=!1;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.sourceCaches[i.source].used=!0);}for(const e in o){const i=this.sourceCaches[e];!!o[e]!=!!i.used&&i.fire(new t.l("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.projection.recalculate(e),this.z=e.zoom,i&&this.fire(new t.l("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,!1),removedIds:t});}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1;}setState(e,i={}){var o;this._checkLoaded();const r=this.serialize();if(e=i.transformStyle?i.transformStyle(r,e):e,(null===(o=i.validate)||void 0===o||o)&&xi(this,t.z(e)))return !1;(e=t.bK(e)).layers=t.bI(e.layers);const a=t.bL(r,e),s=this._getOperationsToPerform(a);if(s.unimplemented.length>0)throw new Error(`Unimplemented: ${s.unimplemented.join(", ")}.`);if(0===s.operations.length)return !1;for(const e of s.operations)e();return this.stylesheet=e,this._serializedLayers=null,!0}_getOperationsToPerform(e){const t=[],i=[];for(const o of e)switch(o.command){case "setCenter":case "setZoom":case "setBearing":case "setPitch":case "setRoll":continue;case "addLayer":t.push((()=>this.addLayer.apply(this,o.args)));break;case "removeLayer":t.push((()=>this.removeLayer.apply(this,o.args)));break;case "setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,o.args)));break;case "setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,o.args)));break;case "setFilter":t.push((()=>this.setFilter.apply(this,o.args)));break;case "addSource":t.push((()=>this.addSource.apply(this,o.args)));break;case "removeSource":t.push((()=>this.removeSource.apply(this,o.args)));break;case "setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,o.args)));break;case "setLight":t.push((()=>this.setLight.apply(this,o.args)));break;case "setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,o.args)));break;case "setGlyphs":t.push((()=>this.setGlyphs.apply(this,o.args)));break;case "setSprite":t.push((()=>this.setSprite.apply(this,o.args)));break;case "setTerrain":t.push((()=>this.map.setTerrain.apply(this,o.args)));break;case "setSky":t.push((()=>this.setSky.apply(this,o.args)));break;case "setProjection":this.setProjection.apply(this,o.args);break;case "setGlobalState":t.push((()=>this.setGlobalState.apply(this,o.args)));break;case "setTransition":t.push((()=>{}));break;default:i.push(o.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,o={}){if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.z.source,`sources.${e}`,i,null,o))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const r=this.sourceCaches[e]=new xe(e,i,this.dispatcher);r.style=this,r.setEventedParent(this,(()=>({isSourceLoaded:r.loaded(),source:r.serialize(),sourceId:e}))),r.onAdd(this.map),this._changed=!0;}removeSource(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.k(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],i.fire(new t.l("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=!0;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error(`There is no source with this ID=${e}`);const i=this.sourceCaches[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=!0;}getSource(e){return this.sourceCaches[e]&&this.sourceCaches[e].getSource()}addLayer(e,i,o={}){this._checkLoaded();const r=e.id;if(this.getLayer(r))return void this.fire(new t.k(new Error(`Layer "${r}" already exists on this map.`)));let a;if("custom"===e.type){if(xi(this,t.bM(e)))return;a=t.bJ(e,this._globalState);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(r,e.source),e=t.bK(e),e=t.e(e,{source:r})),this._validate(t.z.layer,`layers.${r}`,e,{arrayIndex:-1},o))return;a=t.bJ(e,this._globalState),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}});}const s=i?this._order.indexOf(i):this._order.length;if(i&&-1===s)this.fire(new t.k(new Error(`Cannot add layer "${r}" before non-existing layer "${i}".`)));else {if(this._order.splice(s,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){const e=this._removedLayers[r];delete this._removedLayers[r],e.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=!0,!this._layers[e])return void this.fire(new t.k(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const o=this._order.indexOf(e);this._order.splice(o,1);const r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.k(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.k(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,o){this._checkLoaded();const r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.k(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,o={}){this._checkLoaded();const r=this.getLayer(e);if(r){if(!t.bH(r.filter,i))return null==i?(r.setFilter(void 0),void this._updateLayer(r)):void(this._validate(t.z.filter,`layers.${r.id}.filter`,i,null,o)||(r.setFilter(t.bK(i)),this._updateLayer(r)))}else this.fire(new t.k(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.bK(this.getLayer(e).filter)}setLayoutProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.k(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getPaintProperty(i),o)||this._updatePaintProperty(a,i,o,r):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}_updatePaintProperty(e,t,i,o={}){e.setPaintProperty(t,i,o)&&this._updateLayer(e),this._changed=!0,this._updatedPaintProps[e.id]=!0,this._serializedLayers=null;}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0===a)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const s=a.getSource().type;"geojson"===s&&r?this.fire(new t.k(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==s||r?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const o=e.source,r=this.sourceCaches[o];if(void 0===r)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const a=r.getSource().type,s="vector"===a?e.sourceLayer:void 0;"vector"!==a||s?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.k(new Error("A feature id is required to remove its specific state property."))):r.removeFeatureState(s,e.id,i):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r)return "vector"!==r.getSource().type||o?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id)):void this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.k(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.bN(this.sourceCaches,(e=>e.serialize())),i=this._serializeByIds(this._order,!0),o=this.map.getTerrain()||void 0,r=this.stylesheet;return t.bO({version:r.version,name:r.name,metadata:r.metadata,light:r.light,sky:r.sky,center:r.center,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,sprite:r.sprite,glyphs:r.glyphs,transition:r.transition,projection:r.projection,sources:e,layers:i,terrain:o},(e=>void 0!==e))}_updateLayer(e){this._updatedLayers[e.id]=!0,e.source&&!this._updatedSources[e.source]&&"raster"!==this.sourceCaches[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.sourceCaches[e.source].pause()),this._serializedLayers=null,this._changed=!0;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},o=[];for(let r=this._order.length-1;r>=0;r--){const a=this._order[r];if(t(a)){i[a]=r;for(const t of e){const e=t[a];if(e)for(const t of e)o.push(t);}}}o.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const r=[];for(let a=this._order.length-1;a>=0;a--){const s=this._order[a];if(t(s))for(let e=o.length-1;e>=0;e--){const t=o[e].feature;if(i[t.layer.id]this.map.terrain.getElevation(e,t,i):void 0));return this.placement&&a.push(function(e,t,i,o,r,a,s){const n={},l=a.queryRenderedSymbols(o),c=[];for(const e of Object.keys(l).map(Number))c.push(s[e]);c.sort(N);for(const i of c){const o=i.featureIndex.lookupSymbolFeatures(l[i.bucketInstanceId],t,i.bucketIndex,i.sourceLayerIndex,{filterSpec:r.filter,globalState:r.globalState},r.layers,r.availableImages,e);for(const e in o){const t=n[e]=n[e]||[],r=o[e];r.sort(((e,t)=>{const o=i.featureSortOrder;if(o){const i=o.indexOf(e.featureIndex);return o.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of r)t.push(e);}}return function(e,t,i){for(const o in e)for(const r of e[o])U(r,i[t[o].source]);return e}(n,e,i)}(this._layers,s,this.sourceCaches,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(a)}querySourceFeatures(e,i){(null==i?void 0:i.filter)&&this._validate(t.z.filter,"querySourceFeatures.filter",i.filter,null,i);const o=this.sourceCaches[e];return o?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),o=[],r={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const o=this.crossTileSymbolIndex.addLayer(i,l[i.source],e.center.lng);a=a||o;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((r=r||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(s.now(),e.zoom))&&(this.pauseablePlacement=new _t(e,this.map.terrain,this._order,r,t,i,o,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(s.now()),n=!0),a&&this.pauseablePlacement.placement.setStale()),n||a)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,l[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(s.now())}_releaseSymbolFadeTiles(){for(const e in this.sourceCaches)this.sourceCaches[e].releaseSymbolFadeTiles();}getImages(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.z.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}addSprite(e,i,o={},r){this._checkLoaded();const a=[{id:e,url:i}],s=[...f(this.stylesheet.sprite),...a];this._validate(t.z.sprite,"sprite",s,null,o)||(this.stylesheet.sprite=s,this._loadSprite(a,!0,r));}removeSprite(e){this._checkLoaded();const i=f(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=!0;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:void 0,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}else this.fire(new t.k(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return f(this.stylesheet.sprite)}setSprite(e,i={},o){this._checkLoaded(),e&&this._validate(t.z.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,!0,o):(this._unloadSprite(),o&&o(null)));}}var Ti=t.aJ([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class Pi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;}bind(e,t,i,o,r,a,s,n,l){this.context=e;let c=this.boundPaintVertexBuffers.length!==o.length;for(let e=0;!c&&e({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:o?o.properties.get("fog-color"):t.bf.white,u_fog_ground_blend:o?o.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:a?0:o?o.calculateFogBlendOpacity(r):0,u_horizon_color:o?o.properties.get("horizon-color"):t.bf.white,u_horizon_fog_blend:o?o.properties.get("horizon-fog-blend"):1,u_is_globe_mode:a?1:0}),Ii={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function Mi(e){const t=[];for(let i=0;i({u_depth:new t.bP(e,i.u_depth),u_terrain:new t.bP(e,i.u_terrain),u_terrain_dim:new t.bg(e,i.u_terrain_dim),u_terrain_matrix:new t.bR(e,i.u_terrain_matrix),u_terrain_unpack:new t.bS(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.bg(e,i.u_terrain_exaggeration)}))(e,C),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.bR(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.bS(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.bS(e,i.u_projection_clipping_plane),u_projection_transition:new t.bg(e,i.u_projection_transition),u_projection_fallback_matrix:new t.bR(e,i.u_projection_fallback_matrix)}))(e,C),this.binderUniforms=o?o.getUniforms(e,C):[];}draw(e,t,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v){const b=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(o),e.setColorMode(r),e.setCullFace(a),n){e.activeTexture.set(b.TEXTURE2),b.bindTexture(b.TEXTURE_2D,n.depthTexture),e.activeTexture.set(b.TEXTURE3),b.bindTexture(b.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[Ii[e]].set(l[e]);if(s)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(s[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let x=0;switch(t){case b.LINES:x=2;break;case b.TRIANGLES:x=3;break;case b.LINE_STRIP:x=1;}for(const i of d.get()){const o=i.vaos||(i.vaos={});(o[c]||(o[c]=new Pi)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),b.drawElements(t,i.primitiveLength*x,b.UNSIGNED_SHORT,i.primitiveOffset*x*2);}}}function Ei(e,i,o){const r=1/t.aC(o,1,i.transform.tileZoom),a=Math.pow(2,o.tileID.overscaledZ),s=o.tileSize*Math.pow(2,i.transform.tileZoom)/a,n=s*(o.tileID.canonical.x+o.tileID.wrap*a),l=s*o.tileID.canonical.y;return {u_image:0,u_texsize:o.imageAtlasTexture.size,u_scale:[r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Ri=(e,i,o,r)=>{const a=e.style.light,s=a.properties.get("position"),n=[s.x,s.y,s.z],l=t.bV();"viewport"===a.properties.get("anchor")&&t.bW(l,e.transform.bearingInRadians),t.bX(n,n,l);const c=e.transform.transformLightDirection(n),h=a.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:o,u_fill_translate:r}},zi=(e,i,o,r,a,s,n)=>t.e(Ri(e,i,o,r),Ei(s,e,n),{u_height_factor:-Math.pow(2,a.overscaledZ)/n.tileSize/8}),Di=(e,i,o,r)=>t.e(Ei(i,e,o),{u_fill_translate:r}),Ai=(e,t)=>({u_world:e,u_fill_translate:t}),Li=(e,i,o,r,a)=>t.e(Di(e,i,o,a),{u_world:r}),ki=(e,i,o,r,a)=>{const s=e.transform;let n,l,c=0;if("map"===o.paint.get("circle-pitch-alignment")){const e=t.aC(i,1,s.zoom);n=!0,l=[e,e],c=e/(t.$*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*a;}else n=!1,l=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===o.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:r}},Fi=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),Bi=e=>({u_viewport_size:[e.width,e.height]}),Oi=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),ji=(e,i,o,r)=>{const a=t.aC(e,1,i)/(t.$*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*r;return {u_extrude_scale:t.aC(e,1,i),u_intensity:o,u_globe_extrude_scale:a}},Ni=(e,i,o,r)=>{const a=t.L();t.bY(a,0,e.width,e.height,0,0,1);const s=e.context.gl;return {u_matrix:a,u_world:[s.drawingBufferWidth,s.drawingBufferHeight],u_image:o,u_color_ramp:r,u_opacity:i.paint.get("heatmap-opacity")}},Ui=(e,t,i)=>{const o=i.paint.get("hillshade-accent-color");let r;switch(i.paint.get("hillshade-method")){case "basic":r=4;break;case "combined":r=1;break;case "igor":r=2;break;case "multidirectional":r=3;break;default:r=0;}const a=i.getIlluminationProperties();for(let t=0;t{const o=i.stride,r=t.L();return t.bY(r,0,t.$,-t.$,0,0,1),t.M(r,r,[0,-t.$,0]),{u_matrix:r,u_image:1,u_dimension:[o,o],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function Gi(e,i){const o=Math.pow(2,i.canonical.z),r=i.canonical.y;return [new t.a1(0,r/o).toLngLat().lat,new t.a1(0,(r+1)/o).toLngLat().lat]}const Vi=(e,t,i=0)=>({u_image:0,u_unpack:t.getUnpackVector(),u_dimension:[t.stride,t.stride],u_elevation_stops:1,u_color_stops:4,u_color_ramp_size:i,u_opacity:e.paint.get("color-relief-opacity")}),$i=(e,i,o,r)=>{const a=e.transform;return {u_translation:Ki(e,i,o),u_ratio:r/t.aC(i,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},qi=(e,i,o,r,a)=>t.e($i(e,i,o,r),{u_image:0,u_image_height:a}),Wi=(e,i,o,r,a)=>{const s=e.transform,n=Xi(i,s);return {u_translation:Ki(e,i,o),u_texsize:i.imageAtlasTexture.size,u_ratio:r/t.aC(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},Hi=(e,i,o,r,a,s)=>{const n=e.lineAtlas,l=Xi(i,e.transform),c="round"===o.layout.get("line-cap"),h=n.getDash(a.from,c),u=n.getDash(a.to,c),d=h.width*s.fromScale,_=u.width*s.toScale;return t.e($i(e,i,o,r),{u_patternscale_a:[l/d,-h.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*e.pixelRatio)/2,u_image:0,u_tex_y_a:h.y,u_tex_y_b:u.y,u_mix:s.t})};function Xi(e,i){return 1/t.aC(e,1,i.tileZoom)}function Ki(e,i,o){return t.aD(e.transform,i,o.paint.get("line-translate"),o.paint.get("line-translate-anchor"))}const Yi=(e,t,i,o,r)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*o.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:o.paint.get("raster-brightness-min"),u_brightness_high:o.paint.get("raster-brightness-max"),u_saturation_factor:(s=o.paint.get("raster-saturation"),s>0?1-1/(1.001-s):-s),u_contrast_factor:(a=o.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Qi(o.paint.get("raster-hue-rotate")),u_coords_top:[r[0].x,r[0].y,r[1].x,r[1].y],u_coords_bottom:[r[3].x,r[3].y,r[2].x,r[2].y]};var a,s;};function Qi(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const Ji=(e,t,i,o,r,a,s,n,l,c,h,u,d)=>{const _=s.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+o,u_is_along_line:r,u_is_variable_anchor:a,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},eo=(e,i,o,r,a,s,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.e(Ji(e,i,o,r,a,s,n,l,c,h,u,d,p),{u_gamma_scale:r?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:1})},to=(e,i,o,r,a,s,n,l,c,h,u,d,_)=>t.e(eo(e,i,o,r,a,s,n,l,c,h,!0,u,0,_),{u_texsize_icon:d,u_texture_icon:1}),io=(e,t)=>({u_opacity:e,u_color:t}),oo=(e,i,o,r,a)=>t.e(function(e,i,o,r){const a=o.imageManager.getPattern(e.from.toString()),s=o.imageManager.getPattern(e.to.toString()),{width:n,height:l}=o.imageManager.getPixelSize(),c=Math.pow(2,r.tileID.overscaledZ),h=r.tileSize*Math.pow(2,o.transform.tileZoom)/c,u=h*(r.tileID.canonical.x+r.tileID.wrap*c),d=h*r.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:s.tl,u_pattern_br_b:s.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:s.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.aC(r,1,o.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(o,a,i,r),{u_opacity:e}),ro=(e,t)=>{},ao={fillExtrusion:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_height_factor:new t.bg(e,i.u_height_factor),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.bU(e,i.u_world),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_scale_with_map:new t.bP(e,i.u_scale_with_map),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_extrude_scale:new t.bU(e,i.u_extrude_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale),u_translate:new t.bU(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.bU(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.bU(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.bQ(e,i.u_color),u_overlay:new t.bP(e,i.u_overlay),u_overlay_scale:new t.bg(e,i.u_overlay_scale)}),depth:ro,clippingMask:ro,heatmap:(e,i)=>({u_extrude_scale:new t.bg(e,i.u_extrude_scale),u_intensity:new t.bg(e,i.u_intensity),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_color_ramp:new t.bP(e,i.u_color_ramp),u_opacity:new t.bg(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.bP(e,i.u_image),u_latrange:new t.bU(e,i.u_latrange),u_exaggeration:new t.bg(e,i.u_exaggeration),u_altitudes:new t.b_(e,i.u_altitudes),u_azimuths:new t.b_(e,i.u_azimuths),u_accent:new t.bQ(e,i.u_accent),u_method:new t.bP(e,i.u_method),u_shadows:new t.bZ(e,i.u_shadows),u_highlights:new t.bZ(e,i.u_highlights)}),hillshadePrepare:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_image:new t.bP(e,i.u_image),u_dimension:new t.bU(e,i.u_dimension),u_zoom:new t.bg(e,i.u_zoom),u_unpack:new t.bS(e,i.u_unpack)}),colorRelief:(e,i)=>({u_image:new t.bP(e,i.u_image),u_unpack:new t.bS(e,i.u_unpack),u_dimension:new t.bU(e,i.u_dimension),u_elevation_stops:new t.bP(e,i.u_elevation_stops),u_color_stops:new t.bP(e,i.u_color_stops),u_color_ramp_size:new t.bP(e,i.u_color_ramp_size),u_opacity:new t.bg(e,i.u_opacity)}),line:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_image:new t.bP(e,i.u_image),u_image_height:new t.bg(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_texsize:new t.bU(e,i.u_texsize),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_image:new t.bP(e,i.u_image),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_patternscale_a:new t.bU(e,i.u_patternscale_a),u_patternscale_b:new t.bU(e,i.u_patternscale_b),u_sdfgamma:new t.bg(e,i.u_sdfgamma),u_image:new t.bP(e,i.u_image),u_tex_y_a:new t.bg(e,i.u_tex_y_a),u_tex_y_b:new t.bg(e,i.u_tex_y_b),u_mix:new t.bg(e,i.u_mix)}),raster:(e,i)=>({u_tl_parent:new t.bU(e,i.u_tl_parent),u_scale_parent:new t.bg(e,i.u_scale_parent),u_buffer_scale:new t.bg(e,i.u_buffer_scale),u_fade_t:new t.bg(e,i.u_fade_t),u_opacity:new t.bg(e,i.u_opacity),u_image0:new t.bP(e,i.u_image0),u_image1:new t.bP(e,i.u_image1),u_brightness_low:new t.bg(e,i.u_brightness_low),u_brightness_high:new t.bg(e,i.u_brightness_high),u_saturation_factor:new t.bg(e,i.u_saturation_factor),u_contrast_factor:new t.bg(e,i.u_contrast_factor),u_spin_weights:new t.bT(e,i.u_spin_weights),u_coords_top:new t.bS(e,i.u_coords_top),u_coords_bottom:new t.bS(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texsize_icon:new t.bU(e,i.u_texsize_icon),u_texture:new t.bP(e,i.u_texture),u_texture_icon:new t.bP(e,i.u_texture_icon),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_color:new t.bQ(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_image:new t.bP(e,i.u_image),u_pattern_tl_a:new t.bU(e,i.u_pattern_tl_a),u_pattern_br_a:new t.bU(e,i.u_pattern_br_a),u_pattern_tl_b:new t.bU(e,i.u_pattern_tl_b),u_pattern_br_b:new t.bU(e,i.u_pattern_br_b),u_texsize:new t.bU(e,i.u_texsize),u_mix:new t.bg(e,i.u_mix),u_pattern_size_a:new t.bU(e,i.u_pattern_size_a),u_pattern_size_b:new t.bU(e,i.u_pattern_size_b),u_scale_a:new t.bg(e,i.u_scale_a),u_scale_b:new t.bg(e,i.u_scale_b),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.bg(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_ele_delta:new t.bg(e,i.u_ele_delta),u_fog_matrix:new t.bR(e,i.u_fog_matrix),u_fog_color:new t.bQ(e,i.u_fog_color),u_fog_ground_blend:new t.bg(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.bg(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon_fog_blend:new t.bg(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.bg(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.bg(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_terrain_coords_id:new t.bg(e,i.u_terrain_coords_id),u_ele_delta:new t.bg(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.bg(e,i.u_input),u_output_expected:new t.bg(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.bT(e,i.u_sun_pos),u_atmosphere_blend:new t.bg(e,i.u_atmosphere_blend),u_globe_position:new t.bT(e,i.u_globe_position),u_globe_radius:new t.bg(e,i.u_globe_radius),u_inv_proj_matrix:new t.bR(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.bQ(e,i.u_sky_color),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon:new t.bU(e,i.u_horizon),u_horizon_normal:new t.bU(e,i.u_horizon_normal),u_sky_horizon_blend:new t.bg(e,i.u_sky_horizon_blend),u_sky_blend:new t.bg(e,i.u_sky_blend)})};class so{constructor(e,t,i){this.context=e;const o=e.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const no={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class lo{constructor(e,t,i,o){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=o,this.context=e;const r=e.gl;this.buffer=r.createBuffer(),e.bindVertexBuffer.set(this.buffer),r.bufferData(r.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(s,l.LINES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Fi(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),o.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!a||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.b$;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:S,angle:E});}else $e(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===o.layout.get("text-rotation-alignment");De(c,e,a,O,j,v,h,i,l.toUnwrapped(),f.width,f.height,U,t);}const $=a&&P||V,q=b||$?Yo:v?O:e.transform.clipSpaceToPixelsMatrix,W=p&&0!==o.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1);let H;H=p?c.iconsInText?to(T.kind,E,x,v,b,$,e,q,N,U,z,k,I):eo(T.kind,E,x,v,b,$,e,q,N,U,a,z,0,I):Ji(T.kind,E,x,v,b,$,e,q,N,U,a,z,I);const X={program:S,buffers:u,uniformValues:H,projectionData:Z,atlasTexture:D,atlasTextureIcon:F,atlasInterpolation:A,atlasInterpolationIcon:L,isSDF:p,hasHalo:W};if(y&&c.canOverlap){w=!0;const e=u.segments.get();for(const i of e)C.push({segments:new t.aM([i]),sortKey:i.sortKey,state:X,terrainData:R});}else C.push({segments:u.segments,sortKey:0,state:X,terrainData:R});}w&&C.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of C){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const r=i.uniformValues;i.hasHalo&&(r.u_is_halo=1,or(i.buffers,t.segments,o,e,i.program,T,u,d,r,i.projectionData,t.terrainData)),r.u_is_halo=0;}or(i.buffers,t.segments,o,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function or(e,t,i,o,r,a,s,n,l,c,h){const u=o.context;r.draw(u,u.gl.TRIANGLES,a,s,n,Ut.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,o.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function rr(e,i,o,r,a){const s=e.context,n=s.gl,l=Vt.disabled,c=new jt([n.ONE,n.ONE],t.bf.transparent,[!0,!0,!0,!0]),h=i.getBucket(o);if(!h)return;const u=r.key;let d=o.heatmapFbos.get(u);d||(d=sr(s,i.tileSize,i.tileSize),o.heatmapFbos.set(u,d)),s.bindFramebuffer.set(d.framebuffer),s.viewport.set([0,0,i.tileSize,i.tileSize]),s.clear({color:t.bf.transparent});const _=h.programConfigurations.get(o.id),p=e.useProgram("heatmap",_,!a),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),f=e.style.map.terrain.getTerrainData(r);p.draw(s,n.TRIANGLES,Zt.disabled,l,c,Ut.disabled,ji(i,e.transform.zoom,o.paint.get("heatmap-intensity"),1),f,m,o.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,o.paint,e.transform.zoom,_);}function ar(e,t,i,o,r){const a=e.context,s=a.gl,n=e.transform;a.setColorMode(e.colorModeForRenderPass());const l=nr(a,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,h.colorAttachment.get()),a.activeTexture.set(s.TEXTURE1),l.bind(s.LINEAR,s.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:r,applyGlobeMatrix:!o});e.useProgram("heatmapTexture").draw(a,s.TRIANGLES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Ni(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function sr(e,t,i){var o,r;const a=e.gl,s=a.createTexture();a.bindTexture(a.TEXTURE_2D,s),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR);const n=null!==(o=e.HALF_FLOAT)&&void 0!==o?o:a.UNSIGNED_BYTE,l=null!==(r=e.RGBA16F)&&void 0!==r?r:a.RGBA;a.texImage2D(a.TEXTURE_2D,0,l,t,i,0,a.RGBA,n,null);const c=e.createFramebuffer(t,i,!1,!1);return c.colorAttachment.set(s),c}function nr(e,i){return i.colorRampTexture||(i.colorRampTexture=new t.T(e,i.colorRamp,e.gl.RGBA)),i.colorRampTexture}function lr(e,t,i,o,r){if(!i||!o||!o.imageAtlas)return;const a=o.imageAtlas.patternPositions;let s=a[i.to.toString()],n=a[i.from.toString()];if(!s&&n&&(s=n),!n&&s&&(n=s),!s||!n){const e=r.getPaintProperty(t);s=a[e],n=a[e];}s&&n&&e.setConstantPatternPositions(s,n);}function cr(e,i,o,r,a,s,n,l){const c=e.context.gl,h="fill-pattern",u=o.paint.get(h),d=u&&u.constantOr(1),_=o.getCrossfadeParameters();let p,m,f,g,v;const b=e.transform,x=o.paint.get("fill-translate"),y=o.paint.get("fill-translate-anchor");n?(m=d&&!o.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",p=c.LINES):(m=d?"fillPattern":"fill",p=c.TRIANGLES);const w=u.constantOr(null);for(const u of r){const r=i.getTile(u);if(d&&!r.patternsLoaded())continue;const T=r.getBucket(o);if(!T)continue;const P=T.programConfigurations.get(o.id),C=e.useProgram(m,P),I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(u);d&&(e.context.activeTexture.set(c.TEXTURE0),r.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),P.updatePaintBuffers(_)),lr(P,h,w,r,o);const M=b.getProjectionData({overscaledTileID:u,applyGlobeMatrix:!l,applyTerrainMatrix:!0}),S=t.aD(b,r,x,y);if(n){g=T.indexBuffer2,v=T.segments2;const t=[c.drawingBufferWidth,c.drawingBufferHeight];f="fillOutlinePattern"===m&&d?Li(e,_,r,t,S):Ai(t,S);}else g=T.indexBuffer,v=T.segments,f=d?Di(e,_,r,S):{u_fill_translate:S};const E=e.stencilModeForClipping(u);C.draw(e.context,p,a,E,s,Ut.backCCW,f,I,M,o.id,T.layoutVertexBuffer,g,v,o.paint,e.transform.zoom,P);}}function hr(e,i,o,r,a,s,n,l){const c=e.context,h=c.gl,u="fill-extrusion-pattern",d=o.paint.get(u),_=d.constantOr(1),p=o.getCrossfadeParameters(),m=o.paint.get("fill-extrusion-opacity"),f=d.constantOr(null),g=e.transform;for(const d of r){const r=i.getTile(d),v=r.getBucket(o);if(!v)continue;const b=e.style.map.terrain&&e.style.map.terrain.getTerrainData(d),x=v.programConfigurations.get(o.id),y=e.useProgram(_?"fillExtrusionPattern":"fillExtrusion",x);_&&(e.context.activeTexture.set(h.TEXTURE0),r.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),x.updatePaintBuffers(p));const w=g.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!l,applyTerrainMatrix:!0});lr(x,u,f,r,o);const T=t.aD(g,r,o.paint.get("fill-extrusion-translate"),o.paint.get("fill-extrusion-translate-anchor")),P=o.paint.get("fill-extrusion-vertical-gradient"),C=_?zi(e,P,m,T,d,p,r):Ri(e,P,m,T);y.draw(c,c.gl.TRIANGLES,a,s,n,Ut.backCCW,C,b,w,o.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,o.paint,e.transform.zoom,x,e.style.map.terrain&&v.centroidVertexBuffer);}}function ur(e,t,i,o,r,a,s,n,l){var c;const h=e.style.projection,u=e.context,d=e.transform,_=u.gl,p=[`#define NUM_ILLUMINATION_SOURCES ${i.paint.get("hillshade-highlight-color").values.length}`],m=e.useProgram("hillshade",null,!1,p),f=!e.options.moving;for(const p of o){const o=t.getTile(p),g=o.fbo;if(!g)continue;const v=h.getMeshFromTileID(u,p.canonical,n,!0,"raster"),b=null===(c=e.style.map.terrain)||void 0===c?void 0:c.getTerrainData(p);u.activeTexture.set(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g.colorAttachment.get());const x=d.getProjectionData({overscaledTileID:p,aligned:f,applyGlobeMatrix:!l,applyTerrainMatrix:!0});m.draw(u,_.TRIANGLES,a,r[p.overscaledZ],s,Ut.backCCW,Ui(e,o,i),b,x,i.id,v.vertexBuffer,v.indexBuffer,v.segments);}}function dr(e,i,o,r,a,s,n,l,c){var h;const u=e.style.projection,d=e.context,_=e.transform,p=d.gl,m=e.useProgram("colorRelief"),f=!e.options.moving;let g=!0,v=0;for(const b of r){const r=i.getTile(b),x=r.dem;if(g){const e=p.getParameter(p.MAX_TEXTURE_SIZE),{elevationTexture:t,colorTexture:i}=o.getColorRampTextures(d,e,x.getUnpackVector());d.activeTexture.set(p.TEXTURE1),t.bind(p.NEAREST,p.CLAMP_TO_EDGE),d.activeTexture.set(p.TEXTURE4),i.bind(p.LINEAR,p.CLAMP_TO_EDGE),g=!1,v=t.size[0];}if(!x||!x.data)continue;const y=x.stride,w=x.getPixels();if(d.activeTexture.set(p.TEXTURE0),d.pixelStoreUnpackPremultiplyAlpha.set(!1),r.demTexture=r.demTexture||e.getTileTexture(y),r.demTexture){const e=r.demTexture;e.update(w,{premultiply:!1}),e.bind(p.LINEAR,p.CLAMP_TO_EDGE);}else r.demTexture=new t.T(d,w,p.RGBA,{premultiply:!1}),r.demTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE);const T=u.getMeshFromTileID(d,b.canonical,l,!0,"raster"),P=null===(h=e.style.map.terrain)||void 0===h?void 0:h.getTerrainData(b),C=_.getProjectionData({overscaledTileID:b,aligned:f,applyGlobeMatrix:!c,applyTerrainMatrix:!0});m.draw(d,p.TRIANGLES,s,a[b.overscaledZ],n,Ut.backCCW,Vi(o,r.dem,v),P,C,o.id,T.vertexBuffer,T.indexBuffer,T.segments);}}const _r=[new t.P(0,0),new t.P(t.$,0),new t.P(t.$,t.$),new t.P(0,t.$)];function pr(e,t,i,o,r,a,s,n,l=!1,c=!1){const h=o[o.length-1].overscaledZ,u=e.context,d=u.gl,_=e.useProgram("raster"),p=e.transform,m=e.style.projection,f=e.colorModeForRenderPass(),g=!e.options.moving;for(const v of o){const o=e.getDepthModeForSublayer(v.overscaledZ-h,1===i.paint.get("raster-opacity")?Zt.ReadWrite:Zt.ReadOnly,d.LESS),b=t.getTile(v);b.registerFadeDuration(i.paint.get("raster-fade-duration"));const x=t.findLoadedParent(v,0),y=t.findLoadedSibling(v),w=mr(b,x||y||null,t,i,e.transform,e.style.map.terrain);let T,P;const C="nearest"===i.paint.get("raster-resampling")?d.NEAREST:d.LINEAR;u.activeTexture.set(d.TEXTURE0),b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),u.activeTexture.set(d.TEXTURE1),x?(x.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),T=Math.pow(2,x.tileID.overscaledZ-b.tileID.overscaledZ),P=[b.tileID.canonical.x*T%1,b.tileID.canonical.y*T%1]):b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),b.texture.useMipmap&&u.extTextureFilterAnisotropic&&e.transform.pitch>20&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(v),M=p.getProjectionData({overscaledTileID:v,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),S=Yi(P||[0,0],T||1,w,i,n),E=m.getMeshFromTileID(u,v.canonical,a,s,"raster");_.draw(u,d.TRIANGLES,o,r?r[v.overscaledZ]:Vt.disabled,f,l?Ut.frontCCW:Ut.backCCW,S,I,M,i.id,E.vertexBuffer,E.indexBuffer,E.segments);}}function mr(e,i,o,r,a,n){const l=r.paint.get("raster-fade-duration");if(!n&&l>0){const r=s.now(),n=(r-e.timeAdded)/l,c=i?(r-i.timeAdded)/l:-1,h=o.getSource(),u=ge(a,{tileSize:h.tileSize,roundZoom:h.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-u)>Math.abs(e.tileID.overscaledZ-u),_=d&&e.refreshedUponExpiration?1:t.ah(d?n:1-c,0,1);return e.refreshedUponExpiration&&n>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-_}:{opacity:_,mix:0}}return {opacity:1,mix:0}}const fr=new t.bf(1,0,0,1),gr=new t.bf(0,1,0,1),vr=new t.bf(0,0,1,1),br=new t.bf(1,0,1,1),xr=new t.bf(0,1,1,1);function yr(e,t,i,o){Tr(e,0,t+i/2,e.transform.width,i,o);}function wr(e,t,i,o){Tr(e,t-i/2,0,i,e.transform.height,o);}function Tr(e,t,i,o,r,a){const s=e.context,n=s.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,o*e.pixelRatio,r*e.pixelRatio),s.clear({color:a}),n.disable(n.SCISSOR_TEST);}function Pr(e,i,o){const r=e.context,a=r.gl,s=e.useProgram("debug"),n=Zt.disabled,l=Vt.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(o);r.activeTexture.set(a.TEXTURE0);const d=i.getTileByID(o.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(o).tileSize,m=512/Math.min(p,512)*(o.overscaledZ/e.transform.zoom)*.5;let f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=` => ${o.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,o=e.context.gl,r=e.debugOverlayCanvas.getContext("2d");r.clearRect(0,0,i.width,i.height),r.shadowColor="white",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle="white",r.textBaseline="top",r.font="bold 36px Open Sans, sans-serif",r.fillText(t,5,5),r.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:o,applyGlobeMatrix:!0,applyTerrainMatrix:!0});s.draw(r,a.TRIANGLES,n,l,jt.alphaBlended,Ut.disabled,Oi(t.bf.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),s.draw(r,a.LINE_STRIP,n,l,c,Ut.disabled,Oi(t.bf.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function Cr(e,t,i,o){const{isRenderingGlobe:r}=o,a=e.context,s=a.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain");a.bindFramebuffer.set(null),a.viewport.set([0,0,e.width,e.height]);for(const o of i){const i=t.getTerrainMesh(o.tileID),u=e.renderToTexture.getTexture(o),d=t.getTerrainData(o.tileID);a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,u.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(o.tileID.toUnwrapped()),m=Ci(_,p,e.style.sky,n.pitch,r),f=n.getProjectionData({overscaledTileID:o.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});h.draw(a,s.TRIANGLES,c,Vt.disabled,l,Ut.backCCW,m,d,f,"terrain",i.vertexBuffer,i.indexBuffer,i.segments);}}function Ir(e,i){if(!i.mesh){const o=new t.aL;o.emplaceBack(-1,-1),o.emplaceBack(1,-1),o.emplaceBack(1,1),o.emplaceBack(-1,1);const r=new t.aN;r.emplaceBack(0,1,2),r.emplaceBack(0,2,3),i.mesh=new wt(e.createVertexBuffer(o,Tt.members),e.createIndexBuffer(r),t.aM.simpleSegment(0,0,o.length,r.length));}return i.mesh}class Mr{constructor(e,i){this.context=new Ho(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:t.ag(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=xe.maxUnderzooming+xe.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new vt;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.aL;i.emplaceBack(0,0),i.emplaceBack(t.$,0),i.emplaceBack(0,t.$),i.emplaceBack(t.$,t.$),this.tileExtentBuffer=e.createVertexBuffer(i,Tt.members),this.tileExtentSegments=t.aM.simpleSegment(0,0,4,2);const o=new t.aL;o.emplaceBack(0,0),o.emplaceBack(t.$,0),o.emplaceBack(0,t.$),o.emplaceBack(t.$,t.$),this.debugBuffer=e.createVertexBuffer(o,Tt.members),this.debugSegments=t.aM.simpleSegment(0,0,4,5);const r=new t.c6;r.emplaceBack(0,0,0,0),r.emplaceBack(t.$,0,t.$,0),r.emplaceBack(0,t.$,0,t.$),r.emplaceBack(t.$,t.$,t.$,t.$),this.rasterBoundsBuffer=e.createVertexBuffer(r,Ti.members),this.rasterBoundsSegments=t.aM.simpleSegment(0,0,4,2);const a=new t.aL;a.emplaceBack(0,0),a.emplaceBack(t.$,0),a.emplaceBack(0,t.$),a.emplaceBack(t.$,t.$),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(a,Tt.members),this.rasterBoundsSegmentsPosOnly=t.aM.simpleSegment(0,0,4,5);const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(1,0),s.emplaceBack(0,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,Tt.members),this.viewportSegments=t.aM.simpleSegment(0,0,4,2);const n=new t.c7;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.aN;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new Vt({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new wt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const o=t.L();t.bY(o,0,this.width,this.height,0,0,1),t.N(o,o,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const r={mainMatrix:o,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:o};this.useProgram("clippingMask",null,!0).draw(e,i.TRIANGLES,Zt.disabled,this.stencilClearMode,jt.disabled,Ut.disabled,null,null,r,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const o=this.context;o.setColorMode(jt.disabled),o.setDepthMode(Zt.disabled);const r={};for(const e of t)r[e.key]=this.nextStencilID++;this._renderTileMasks(r,t,i,!0),this._renderTileMasks(r,t,i,!1),this._tileClippingMaskIDs=r;}_renderTileMasks(e,t,i,o){const r=this.context,a=r.gl,s=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=s.getMeshFromTileID(this.context,c.canonical,o,!0,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!i,applyTerrainMatrix:!0});l.draw(r,a.TRIANGLES,Zt.disabled,new Vt({func:a.ALWAYS,mask:0},t,255,a.KEEP,a.KEEP,a.REPLACE),jt.disabled,i?Ut.disabled:Ut.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,o=this.transform,r=this.useProgram("depth"),a=this.getDepthModeFor3D(),s=ve(o,{tileSize:o.tileSize});for(const n of s){const s=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,!0,!0,"raster"),c=o.getProjectionData({overscaledTileID:n,applyGlobeMatrix:!0,applyTerrainMatrix:!0});r.draw(e,t.TRIANGLES,a,Vt.disabled,jt.disabled,Ut.backCCW,null,s,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new Vt({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new Vt({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(r>1){this.currentStencilSource=void 0,this.nextStencilID+r>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(this.clearStencil(),r>1){const e={},a={};for(let i=0;i0};for(const e in n){const t=n[e];t.used&&t.prepare(this.context),l[e]=t.getVisibleCoordinates(!1),c[e]=l[e].slice().reverse(),h[e]=t.getVisibleCoordinates(!0).reverse();}this.opaquePassCutoff=1/0;for(let e=0;ethis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.bf.black:t.bf.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,o=i.gl,r=((e,t,i)=>{const o=Math.cos(t.rollInRadians),r=Math.sin(t.rollInRadians),a=he(t),s=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-a*r)*i,(t.height/2+a*o)*i],u_horizon_normal:[-r,o],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:s}})(t,e.style.map.transform,e.pixelRatio),a=new Zt(o.LEQUAL,Zt.ReadWrite,[0,1]),s=Vt.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=Ir(i,t);l.draw(i,o.TRIANGLES,a,s,n,Ut.disabled,r,null,void 0,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=a.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[a[this.currentLayer]],t=n[e.source],i=l[e.source];this._renderTileClippingMasks(e,i,!1),this.renderLayer(this,t,e,i,u);}this.renderPass="translucent";let d=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:o,u_inv_proj_matrix:r}))(c,u,[p[0],p[1],p[2]],d,_),f=Ir(r,i);s.draw(r,a.TRIANGLES,n,Vt.disabled,jt.alphaBlended,Ut.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const o=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.sourceCaches[i.source]]:[])),r=o.filter((e=>"vector"===e.getSource().type)),a=o.filter((e=>"vector"!==e.getSource().type)),s=e=>{(!i||i.getSource().maxzooms(e))),i||a.forEach((e=>s(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let o=0;ou.getElevation(a,e,t):null;er(s,d,_,c,h,f,i,p,g,t.aD(h,e,n,l),a.toUnwrapped(),o);}}}(r,e,o,i,o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),a),0!==o.paint.get("icon-opacity").constantOr(1)&&ir(e,i,o,r,!1,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),o.layout.get("icon-rotation-alignment"),o.layout.get("icon-pitch-alignment"),o.layout.get("icon-keep-upright"),l,c,n),0!==o.paint.get("text-opacity").constantOr(1)&&ir(e,i,o,r,!0,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&(Ko(e,i,o,r,!0),Ko(e,i,o,r,!1));}(e,i,o,r,this.style.placement.variableOffsets,a):t.cc(o)?function(e,i,o,r,a){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:s}=a,n=o.paint.get("circle-opacity"),l=o.paint.get("circle-stroke-width"),c=o.paint.get("circle-stroke-opacity"),h=!o.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Zt.ReadOnly),m=Vt.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let a=0;ae.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:r,layoutVertexBuffer:a,indexBuffer:s,uniformValues:n,terrainData:l,projectionData:c}=t.state;r.draw(u,d.TRIANGLES,p,m,f,Ut.backCCW,n,l,c,o.id,a,s,t.segments,o.paint,e.transform.zoom,i);}}(e,i,o,r,a):t.cd(o)?function(e,i,o,r,a){if(0===o.paint.get("heatmap-opacity"))return;const s=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=a;if(e.style.map.terrain){for(const t of r){const r=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?rr(e,r,o,t,l):"translucent"===e.renderPass&&ar(e,o,t,n,l));}s.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,o,r){const a=e.context,s=a.gl,n=e.transform,l=Vt.disabled,c=new jt([s.ONE,s.ONE],t.bf.transparent,[!0,!0,!0,!0]);((function(e,i,o){const r=e.gl;e.activeTexture.set(r.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let a=o.heatmapFbos.get(t.c2);a?(r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer)):(a=sr(e,i.width/4,i.height/4),o.heatmapFbos.set(t.c2,a));}))(a,e,o),a.clear({color:t.bf.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return !1;if(!e.from||!e.to)return !0;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=!1,o=[]){this.cache=this.cache||{};const r=!!this.style.map.terrain,a=this.style.projection,s=i?xt.projectionMercator:a.shaderPreludeCode,n=i?Pt:a.shaderDefine,l=e+(t?t.cacheKey:"")+`/${i?Ct:a.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(r?"/terrain":"")+(o?`/${o.join("/")}`:"");return this.cache[l]||(this.cache[l]=new Si(this.context,xt[e],t,ao[e],this._showOverdrawInspector,r,s,n,o)),this.cache[l]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Sr(e,t){let i,o=!1,r=null,a=null;const s=()=>{r=null,o&&(e.apply(a,i),r=setTimeout(s,t),o=!1);};return (...e)=>(o=!0,a=this,i=e,r||s(),r)}class Er{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(!this._isValidHash(e))return !1;const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let o=window.location.hash.replace(i,"");o.startsWith("#&")?o=o.slice(0,1)+o.slice(2):"#"===o&&(o="");let r=window.location.href.replace(/(#.+)?$/,o);r=r.replace("&&","&"),window.history.replaceState(window.history.state,null,r);},this._updateHash=Sr(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,o=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),r=Math.pow(10,o),a=Math.round(t.lng*r)/r,s=Math.round(t.lat*r)/r,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${a}/${s}/${i}`:`${i}/${s}/${a}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const o=i.split("=")[0];return o===e?(t=!0,`${o}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return !1;try{new t.S(+e[2],+e[1]);}catch(e){return !1}const i=+e[0],o=+(e[3]||0),r=+(e[4]||0);return i>=this._map.getMinZoom()&&i<=this._map.getMaxZoom()&&o>=-180&&o<=180&&r>=this._map.getMinPitch()&&r<=this._map.getMaxPitch()}}const Rr={linearity:.3,easing:t.cm(0,0,.3,1)},zr=t.e({deceleration:2500,maxSpeed:1400},Rr),Dr=t.e({deceleration:20,maxSpeed:1400},Rr),Ar=t.e({deceleration:1e3,maxSpeed:360},Rr),Lr=t.e({deceleration:1e3,maxSpeed:90},Rr),kr=t.e({deceleration:1e3,maxSpeed:360},Rr);class Fr{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:s.now(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=s.now();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const o=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,r={};if(i.pan.mag()){const a=Or(i.pan.mag(),o,t.e({},zr,e||{})),s=i.pan.mult(a.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(s,this._map.transform);r.center=n.easingCenter,r.offset=n.easingOffset,Br(r,a);}if(i.zoom){const e=Or(i.zoom,o,Dr);r.zoom=this._map.transform.zoom+e.amount,Br(r,e);}if(i.bearing){const e=Or(i.bearing,o,Ar);r.bearing=this._map.transform.bearing+t.ah(e.amount,-179,179),Br(r,e);}if(i.pitch){const e=Or(i.pitch,o,Lr);r.pitch=this._map.transform.pitch+e.amount,Br(r,e);}if(i.roll){const e=Or(i.roll,o,kr);r.roll=this._map.transform.roll+t.ah(e.amount,-179,179),Br(r,e);}if(r.zoom||r.bearing){const e=void 0===i.pinchAround?i.around:i.pinchAround;r.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.e(r,{noMoveStart:!0})}}function Br(e,t){(!e.duration||e.durationi.unproject(e))),l=a.reduce(((e,t,i,o)=>e.add(t.div(o.length))),new t.P(0,0));super(e,{points:a,point:l,lngLats:s,lngLat:i.unproject(l),originalEvent:o}),this._defaultPrevented=!1;}}class Ur extends t.l{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=!1;}}class Zr{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new Ur(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new jr(e.type,this._map,e))}mouseup(e){this._map.fire(new jr(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new jr(e.type,this._map,e));}dblclick(e){return this._firePreventable(new jr(e.type,this._map,e))}mouseover(e){this._map.fire(new jr(e.type,this._map,e));}mouseout(e){this._map.fire(new jr(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Nr(e.type,this._map,e))}touchmove(e){this._map.fire(new Nr(e.type,this._map,e));}touchend(e){this._map.fire(new Nr(e.type,this._map,e));}touchcancel(e){this._map.fire(new Nr(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Gr{constructor(e){this._map=e;}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new jr(e.type,this._map,e));}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new jr("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new jr(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Vr{constructor(e){this._map=e;}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return {lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class $r{constructor(e,t){this._map=e,this._tr=new Vr(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(n.disableDrag(),this._startPos=this._lastPos=t,this._active=!0);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(o,r,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.l(e,{originalEvent:i}))}}function qr(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let o=0;othis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){const i=new t.P(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=qr(o,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const o=qr(i,t);for(const e in this.touches){const t=o[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Hr{constructor(e){this.singleTap=new Wr(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const o=this.singleTap.touchend(e,t,i);if(o){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(o)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}}}class Xr{constructor(e){this._tr=new Vr(e),this._zoomIn=new Hr({numTouches:1,numTaps:2}),this._zoomOut=new Hr({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const o=this._zoomIn.touchend(e,t,i),r=this._zoomOut.touchend(e,t,i),a=this._tr;return o?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom+1,around:a.unproject(o)},{originalEvent:e})}):r?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom-1,around:a.unproject(r)},{originalEvent:e})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class Kr{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0));}dragMove(e,t){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const o=Array.isArray(t)?t[0]:t;return !this._moved&&o.dist(i)!0}),t=new ta){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t;}_executeRelevantHandler(e,t,i){return e instanceof MouseEvent?t(e):"undefined"!=typeof TouchEvent&&e instanceof TouchEvent?i(e):void 0}startMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.startMove(e)),(e=>this.oneFingerTouchMoveStateManager.startMove(e)));}endMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.endMove(e)),(e=>this.oneFingerTouchMoveStateManager.endMove(e)));}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}const oa=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};class ra{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=!1,this._touches={},this._sum=new t.P(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,o){o.length>0&&(this._active=!0);const r=qr(o,i),a=new t.P(0,0),s=new t.P(0,0);let n=0;for(const e in r){const t=r[e],i=this._touches[e];i&&(a._add(t),s._add(t.sub(i)),n++,r[e]=t);}if(this._touches=r,this._shouldBePrevented(n)||!s.mag())return;const l=s.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class da extends aa{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,ua(e[0].sub(e[1]))&&(this._valid=!1);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const o=e[0].sub(this._lastPoints[0]),r=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const o=e.mag()>=2,r=t.mag()>=2;if(!o&&!r)return;if(!o||!r)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const a=e.y>0==t.y>0;return ua(e)&&ua(t)&&a}}const _a={panStep:100,bearingStep:15,pitchStep:10};class pa{constructor(e){this._tr=new Vr(e);const t=_a;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1;}reset(){this._active=!1;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,o=0,r=0,a=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),r=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),r=1);break;case 38:e.shiftKey?o=1:(e.preventDefault(),a=-1);break;case 40:e.shiftKey?o=-1:(e.preventDefault(),a=1);break;default:return}return this._rotationDisabled&&(i=0,o=0),{cameraAnimation:s=>{const n=this._tr;s.easeTo({duration:300,easeId:"keyboardHandler",easing:ma,zoom:t?Math.round(n.zoom)+t*(e.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+o*this._pitchStep,offset:[-r*this._panStep,-a*this._panStep],center:n.center},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function ma(e){return e*(2-e)}const fa=4.000244140625,ga=1/450;class va{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new Vr(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=ga;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=!1);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=s.now(),o=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%fa==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":o>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(o*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=n.mousePos(this._map.getCanvas(),e),o=this._tr;this._aroundPoint=this._aroundCenter?o.transform.locationToScreenPoint(t.S.convert(o.center)):i,this._frameId||(this._frameId=!0,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>fa?this._wheelZoomRate:this._defaultZoomRate;let o=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==o&&(o=1/o);const r="number"!=typeof this._targetZoom?e.scale:t.af(this._targetZoom);this._targetZoom=e.getConstrained(e.getCameraLngLat(),t.ak(r*o)).zoom,"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,o=this._startZoom,r=this._easing;let a,n=!1;if("wheel"===this._type&&o&&r){const e=s.now()-this._lastWheelEventTime,l=Math.min((e+5)/200,1),c=r(l);a=t.C.number(o,i,c),l<1?this._frameId||(this._frameId=!0):n=!0;}else a=i,n=!0;return this._active=!0,n&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=a,{noInertia:!0,needsRenderFrame:!n,zoomDelta:a-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.co;if(this._prevEase){const e=this._prevEase,o=(s.now()-e.start)/e.duration,r=e.easing(o+.01)-e.easing(o),a=.27/Math.sqrt(r*r+1e-4)*.01,n=Math.sqrt(.0729-a*a);i=t.cm(a,n,.25,1);}return this._prevEase={start:s.now(),duration:e,easing:i},i}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class ba{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class xa{constructor(e){this._tr=new Vr(e),this.reset();}reset(){this._active=!1;}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ya{constructor(){this._tap=new Hr({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const o=t[0],r=e.timeStamp-this._tapTime<500,a=this._tapPoint.dist(o)<30;r&&a?i.length>0&&(this._swipePoint=o,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const o=t[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,e.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const o=this._tap.touchend(e,t,i);o&&(this._tapTime=e.timeStamp,this._tapPoint=o);}}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class wa{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Ta{constructor(e,t,i,o){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=o;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Pa{constructor(e,t,i,o){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class Ca{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=!1;}isActive(){return !1}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=n.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),o=document.createElement("div");o.className="maplibregl-desktop-message",o.textContent=t,this._container.appendChild(o);const r=document.createElement("div");r.className="maplibregl-mobile-message",r.textContent=i,this._container.appendChild(r),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(n.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=!0;}disable(){this._enabled=!1,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.l("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const Ia=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Ma extends t.l{}function Sa(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class Ea{constructor(e,i){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,i)=>{if("blur"===e.type)return void this.stop(!0);this._updatingCamera=!0;const o="renderFrame"===e.type?void 0:e,r={needsRenderFrame:!1},a={},s={};for(const{handlerName:l,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let u;if(this._blockedByActive(s,h,l))c.reset();else if(c[i||e.type]){if(t.cp(e,i||e.type)){const t=n.mousePos(this._map.getCanvas(),e);u=c[i||e.type](e,t);}else if(t.cq(e,i||e.type)){const t=this._getMapTouches(e.touches),o=n.touchPos(this._map.getCanvas(),t);u=c[i||e.type](e,o,t);}else t.cr(i||e.type)||(u=c[i||e.type](e));this.mergeHandlerResult(r,a,u,l,o),u&&u.needsRenderFrame&&this._triggerRenderFrame();}(u||c.isActive())&&(s[l]=c);}const l={};for(const e in this._previousActiveHandlers)s[e]||(l[e]=o);this._previousActiveHandlers=s,(Object.keys(l).length||Sa(r))&&(this._changes.push([r,a,l]),this._triggerRenderFrame()),(Object.keys(s).length||Sa(r))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:c}=r;c&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],c(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Fr(e),this._bearingSnap=i.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(i);const o=this._el;this._listeners=[[o,"touchstart",{passive:!0}],[o,"touchmove",{passive:!1}],[o,"touchend",void 0],[o,"touchcancel",void 0],[o,"mousedown",void 0],[o,"mousemove",void 0],[o,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[o,"mouseover",void 0],[o,"mouseout",void 0],[o,"dblclick",void 0],[o,"click",void 0],[o,"keydown",{capture:!1}],[o,"keyup",void 0],[o,"wheel",{passive:!1}],[o,"contextmenu",void 0],[window,"blur",void 0]];for(const[e,t,i]of this._listeners)n.addEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)n.removeEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const i=this._map,o=i.getCanvasContainer();this._add("mapEvent",new Zr(i,e));const r=i.boxZoom=new $r(i,e);this._add("boxZoom",r),e.interactive&&e.boxZoom&&r.enable();const a=i.cooperativeGestures=new Ca(i,e.cooperativeGestures);this._add("cooperativeGestures",a),e.cooperativeGestures&&a.enable();const s=new Xr(i),l=new xa(i);i.doubleClickZoom=new ba(l,s),this._add("tapZoom",s),this._add("clickZoom",l),e.interactive&&e.doubleClickZoom&&i.doubleClickZoom.enable();const c=new ya;this._add("tapDragZoom",c);const h=i.touchPitch=new da(i);this._add("touchPitch",h),e.interactive&&e.touchPitch&&i.touchPitch.enable(e.touchPitch);const u=()=>i.project(i.getCenter()),d=function({enable:e,clickTolerance:i,aroundCenter:o=!0,minPixelCenterThreshold:r=100,rotateDegreesPerPixelMoved:a=.8},s){const l=new ea({checkCorrectEvent:e=>0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:i,move:(e,i)=>{const n=s();if(o&&Math.abs(n.y-e.y)>r)return {bearingDelta:t.cn(new t.P(e.x,i.y),i,n)};let l=(i.x-e.x)*a;return o&&i.y0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)});return new Kr({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:o,enable:e,assignEvents:oa})}(e),p=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3},o){const r=new ea({checkCorrectEvent:e=>2===n.mouseButton(e)&&e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>{const r=o();let a=(t.x-e.x)*i;return t.y0===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:i,enable:e,assignEvents:oa})}(e),f=new ra(e,i);i.dragPan=new wa(o,m,f),this._add("mousePan",m),this._add("touchPan",f,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&i.dragPan.enable(e.dragPan);const g=new ha,v=new la;i.touchZoomRotate=new Pa(o,v,g,c),this._add("touchRotate",g,["touchPan","touchZoom"]),this._add("touchZoom",v,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&i.touchZoomRotate.enable(e.touchZoomRotate);const b=i.scrollZoom=new va(i,(()=>this._triggerRenderFrame()));this._add("scrollZoom",b,["mousePan"]),e.interactive&&e.scrollZoom&&i.scrollZoom.enable(e.scrollZoom);const x=i.keyboard=new pa(i);this._add("keyboard",x),e.interactive&&e.keyboard&&i.keyboard.enable(),this._add("blockableMapEvent",new Gr(i));}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(Ia(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const o in e)if(o!==i&&(!t||t.indexOf(o)<0))return !0;return !1}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,o,r,a){if(!o)return;t.e(e,o);const s={handlerName:r,originalEvent:o.originalEvent||a};void 0!==o.zoomDelta&&(i.zoom=s),void 0!==o.panDelta&&(i.drag=s),void 0!==o.rollDelta&&(i.roll=s),void 0!==o.pitchDelta&&(i.pitch=s),void 0!==o.bearingDelta&&(i.rotate=s);}_applyChanges(){const e={},i={},o={};for(const[r,a,s]of this._changes)r.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(r.panDelta)),r.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+r.zoomDelta),r.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+r.bearingDelta),r.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+r.pitchDelta),r.rollDelta&&(e.rollDelta=(e.rollDelta||0)+r.rollDelta),void 0!==r.around&&(e.around=r.around),void 0!==r.pinchAround&&(e.pinchAround=r.pinchAround),r.noInertia&&(e.noInertia=r.noInertia),t.e(i,a),t.e(o,s);this._updateMapTransform(e,i,o),this._changes=[];}_updateMapTransform(e,t,i){const o=this._map,r=o._getTransformForUpdate(),a=o.terrain;if(!(Sa(e)||a&&this._terrainMovement))return this._fireEvents(t,i,!0);o._stop(!0);let{panDelta:s,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;void 0!==d&&(u=d),u=u||o.transform.centerPoint,a&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const _={panDelta:s,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const p=u.distSqr(r.centerPoint)<.01?r.center:r.screenPointToLocation(s?u.sub(s):u);a?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._terrainMovement||!t.drag&&!t.zoom?t.drag&&this._terrainMovement?r.setCenter(r.screenPointToLocation(r.centerPoint.sub(s))):this._map.cameraHelper.handleMapControlsPan(_,r,p):(this._terrainMovement=!0,this._map._elevationFreeze=!0,this._map.cameraHelper.handleMapControlsPan(_,r,p))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._map.cameraHelper.handleMapControlsPan(_,r,p)),o._applyUpdatedTransform(r),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0);}_fireEvents(e,i,o){const r=Ia(this._eventsInProgress),a=Ia(e),n={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(n[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!r&&a&&this._fireEvent("movestart",a.originalEvent);for(const e in n)this._fireEvent(e,n[e]);a&&this._fireEvent("move",a.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const l={};let c;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:o}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],c=i[t]||o,l[`${e}end`]=c);}for(const e in l)this._fireEvent(e,l[e]);const h=Ia(this._eventsInProgress),u=(r||a)&&!h;if(u&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(o&&u){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new Ma("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}class Ra extends t.E{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((s.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=i.bearingSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.S(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,o){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},i),o)}panTo(e,i,o){return this.easeTo(t.e({center:e},i),o)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,o){return this.easeTo(t.e({zoom:e},i),o)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.l("movestart",i)).fire(new t.l("move",i)).fire(new t.l("moveend",i))),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,o){return this.easeTo(t.e({bearing:e},i),o)}resetNorth(e,i){return this.rotateTo(0,t.e({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){f.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,o={}){this._moving=!0,i||o.moving||this.fire(new t.l("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.l("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.l("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.l("pitchstart",e)),this._rolling&&!o.rolling&&this.fire(new t.l("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0;}_updateElevation(e){void 0!==this._elevationStart&&void 0!==this._elevationCenter||this._prepareElevation(this.transform.center),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.C.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),o=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:o,zoom:r,roll:a,pitch:s,bearing:n,elevation:l}=e(t);o&&t.setCenter(o),void 0!==l&&t.setElevation(l),void 0!==r&&t.setZoom(r),void 0!==a&&t.setRoll(a),void 0!==s&&t.setPitch(s),void 0!==n&&t.setBearing(n),i.apply(t);}this.transform.apply(i);}_fireMoveEvents(e){this.fire(new t.l("move",e)),this._zooming&&this.fire(new t.l("zoom",e)),this._rotating&&this.fire(new t.l("rotate",e)),this._pitching&&this.fire(new t.l("pitch",e)),this._rolling&&this.fire(new t.l("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const o=this._zooming,r=this._rotating,a=this._pitching,s=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,o&&this.fire(new t.l("zoomend",e)),r&&this.fire(new t.l("rotateend",e)),a&&this.fire(new t.l("pitchend",e)),s&&this.fire(new t.l("rollend",e)),this.fire(new t.l("moveend",e));}flyTo(e,i){if(!e.essential&&s.prefersReducedMotion){const o=t.Q(e,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(o,i)}this.stop(),e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.co},e);const o=this._getTransformForUpdate(),r=o.bearing,a=o.pitch,n=o.roll,l=o.padding,c="bearing"in e?this._normalizeBearing(e.bearing,r):r,h="pitch"in e?+e.pitch:a,u="roll"in e?this._normalizeBearing(e.roll,n):n,d="padding"in e?e.padding:o.padding,_=t.P.convert(e.offset);let p=o.centerPoint.add(_);const m=o.screenPointToLocation(p),f=this.cameraHelper.handleFlyTo(o,{bearing:c,pitch:h,roll:u,padding:d,locationAtOffset:m,offsetAsPoint:_,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(o.width,o.height),b=v/f.scaleOfZoom,x=f.pixelPathLength;"number"==typeof f.scaleOfMinZoom&&(g=Math.sqrt(v/f.scaleOfMinZoom/x*2));const y=g*g;function w(e){const t=(b*b-v*v+(e?-1:1)*y*y*x*x)/(2*(e?b:v)*y*x);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function P(e){return (Math.exp(e)+Math.exp(-e))/2}const C=w(!1);let I=function(e){return P(C)/P(C+g*e)},M=function(e){return v*((P(C)*(T(t=C+g*e)/P(t))-T(C))/y)/x;var t;},S=(w(!0)-C)/g;if(Math.abs(x)<2e-6||!isFinite(S)){if(Math.abs(v-b)<1e-6)return this.easeTo(e,i);const t=b0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*S/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=r!==c,this._pitching=h!==a,this._rolling=u!==n,this._padding=!o.isPaddingEqual(d),this._prepareEase(i,!1),this.terrain&&this._prepareElevation(f.targetCenter),this._ease((s=>{const m=s*S,g=1/I(m),v=M(m);this._rotating&&o.setBearing(t.C.number(r,c,s)),this._pitching&&o.setPitch(t.C.number(a,h,s)),this._rolling&&o.setRoll(t.C.number(n,u,s)),this._padding&&(o.interpolatePadding(l,d,s),p=o.centerPoint.add(_)),f.easeFunc(s,g,v,p),this.terrain&&!e.freezeElevation&&this._updateElevation(s),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=s.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.aO(e,-180,180);const o=Math.abs(e-i);return Math.abs(e-360-i)MapLibre
'};class Da{constructor(e=za){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=n.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=n.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=n.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.sourceCaches;for(const i in t){const o=t[i];if(o.used||o.usedForTerrain){const t=o.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let o=i+1;o=0)return !1;return !0}));const i=e.join(" | ");i!==this._attribHTML&&(this._attribHTML=i,e.length?(this._innerContainer.innerHTML=n.sanitize(i),this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Aa{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=n.create("div","maplibregl-ctrl");const t=n.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){n.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0;}}class La{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}var ka=t.aJ([{name:"a_pos3d",type:"Int16",components:3}]);class Fa extends t.E{constructor(e){super(),this._lastTilesetChange=s.now(),this.sourceCache=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize;}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null;}update(e,i){this.sourceCache.update(e,i),this._renderableTilesKeys=[];const o={};for(const r of ve(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:i,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))o[r.key]=!0,this._renderableTilesKeys.push(r.key),this._tiles[r.key]||(r.terrainRttPosMatrix32f=new Float64Array(16),t.bY(r.terrainRttPosMatrix32f,0,t.$,t.$,0,0,1),this._tiles[r.key]=new re(r,this.tileSize),this._lastTilesetChange=s.now());for(const e in this._tiles)o[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e,t){return t?this._getTerrainCoordsForTileRanges(e,t):this._getTerrainCoordsForRegularTile(e)}_getTerrainCoordsForRegularTile(e){const i={};for(const o of this._renderableTilesKeys){const r=this._tiles[o].tileID,a=e.clone(),s=t.ba();if(r.canonical.equals(e.canonical))t.bY(s,0,t.$,t.$,0,0,1);else if(r.canonical.isChildOf(e.canonical)){const i=r.canonical.z-e.canonical.z,o=r.canonical.x-(r.canonical.x>>i<>i<>i;t.bY(s,0,n,n,0,0,1),t.M(s,s,[-o*n,-a*n,0]);}else {if(!e.canonical.isChildOf(r.canonical))continue;{const i=e.canonical.z-r.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i;t.bY(s,0,t.$,t.$,0,0,1),t.M(s,s,[o*n,a*n,0]),t.N(s,s,[1/2**i,1/2**i,0]);}}a.terrainRttPosMatrix32f=new Float32Array(s),i[o]=a;}return i}_getTerrainCoordsForTileRanges(e,i){const o={};for(const r of this._renderableTilesKeys){const a=this._tiles[r].tileID;if(!this._isWithinTileRanges(a,i))continue;const s=e.clone(),n=t.ba();if(a.canonical.z===e.canonical.z){const i=e.canonical.x-a.canonical.x,o=e.canonical.y-a.canonical.y;t.bY(n,0,t.$,t.$,0,0,1),t.M(n,n,[i*t.$,o*t.$,0]);}else if(a.canonical.z>e.canonical.z){const i=a.canonical.z-e.canonical.z,o=a.canonical.x-(a.canonical.x>>i<>i<>i),l=e.canonical.y-(a.canonical.y>>i),c=t.$>>i;t.bY(n,0,c,c,0,0,1),t.M(n,n,[-o*c+s*t.$,-r*c+l*t.$,0]);}else {const i=e.canonical.z-a.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i)-a.canonical.x,l=(e.canonical.y>>i)-a.canonical.y,c=t.$<i.maxzoom&&(o=i.maxzoom),o=i.minzoom&&(!r||!r.dem);)r=this.sourceCache.getTileByID(e.scaledTo(o--).key);return r}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}_isWithinTileRanges(e,t){return t[e.canonical.z]&&e.canonical.x>=t[e.canonical.z].minTileX&&e.canonical.x<=t[e.canonical.z].maxTileX&&e.canonical.y>=t[e.canonical.z].minTileY&&e.canonical.y<=t[e.canonical.z].maxTileY}}class Ba{constructor(e,t,i){this._meshCache={},this.painter=e,this.sourceCache=new Fa(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(e,i,o,r=t.$){var a;if(!(i>=0&&i=0&&oe.canonical.z&&(e.canonical.z>=o?r=e.canonical.z-o:t.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const a=e.canonical.x-(e.canonical.x>>r<>r<>8<<4|e>>8,i[t+3]=0;const o=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),r=new t.T(e,o,e.gl.RGBA,{premultiply:!1});return r.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=r,r}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(!0);const i=new Uint8Array(4),o=this.painter.context,r=o.gl,a=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),s=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);o.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),r.readPixels(a,n-s-1,1,1,r.RGBA,r.UNSIGNED_BYTE,i),o.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.sourceCache.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<0,r=o&&0===e.canonical.y,a=o&&e.canonical.y===(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const ja={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class Na{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new Oa(e.context,30,t.sourceCache.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.sourceCaches){this._coordsAscending[t]={};const i=e.sourceCaches[t].getVisibleCoordinates(),o=e.sourceCaches[t].getSource(),r=o instanceof X?o.terrainTileRanges:null;for(const e of i){const i=this.terrain.sourceCache.getTerrainCoords(e,r);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._coordsAscendingStr={};for(const t of e._order){const i=e._layers[t],o=i.source;if(ja[i.type]&&!this._coordsAscendingStr[o]){this._coordsAscendingStr[o]={};for(const e in this._coordsAscending[o])this._coordsAscendingStr[o][e]=this._coordsAscending[o][e].map((e=>e.key)).sort().join();}}for(const e of this._renderableTiles)for(const t in this._coordsAscendingStr){const i=this._coordsAscendingStr[t][e.tileID.key];i&&i!==e.rttCoords[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return !1;const o=Object.assign(Object.assign({},i),{isRenderingToTexture:!0}),r=e.type,a=this.painter,s=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(ja[r]&&(this._prevType&&ja[this._prevType]||this._stacks.push([]),this._prevType=r,this._stacks[this._stacks.length-1].push(e.id),!s))return !0;if(ja[this._prevType]||ja[r]&&s){this._prevType=r;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const r of this._renderableTiles){if(this.pool.isFull()&&(Cr(this.painter,this.terrain,this._rttTiles,o),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(r),r.rtt[e]){const t=this.pool.getObjectForId(r.rtt[e].id);if(t.stamp===r.rtt[e].stamp){this.pool.useObject(t);continue}}const s=this.pool.getOrCreateFreeObject();this.pool.useObject(s),this.pool.stampObject(s),r.rtt[e]={id:s.id,stamp:s.stamp},a.context.bindFramebuffer.set(s.fbo.framebuffer),a.context.clear({color:t.bf.transparent,stencil:0}),a.currentStencilSource=void 0;for(let e=0;e{this.startMove(e,n.mousePos(this.element,e)),n.addEventListener(window,"mousemove",this.mousemove),n.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=e=>{this.move(e,n.mousePos(this.element,e));},this.mouseup=e=>{this._rotatePitchHandler.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),n.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.addEventListener(window,"touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHandler.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10,this.element=i;const r=new ia;this._rotatePitchHandler=new Kr({clickTolerance:3,move:(e,r)=>{const a=i.getBoundingClientRect(),s=new t.P((a.bottom-a.top)/2,(a.right-a.left)/2);return {bearingDelta:t.cn(new t.P(e.x,r.y),r,s),pitchDelta:o?-.5*(r.y-e.y):void 0}},moveStateManager:r,enable:!0,assignEvents:()=>{}}),this.map=e,n.addEventListener(i,"mousedown",this.mousedown),n.addEventListener(i,"touchstart",this.touchstart,{passive:!1}),n.addEventListener(i,"touchcancel",this.reset);}startMove(e,t){this._rotatePitchHandler.dragStart(e,t),n.disableDrag();}move(e,t){const i=this.map,{bearingDelta:o,pitchDelta:r}=this._rotatePitchHandler.dragMove(e,t)||{};o&&i.setBearing(i.getBearing()+o),r&&i.setPitch(i.getPitch()+r);}off(){const e=this.element;n.removeEventListener(e,"mousedown",this.mousedown),n.removeEventListener(e,"touchstart",this.touchstart,{passive:!1}),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend),n.removeEventListener(e,"touchcancel",this.reset),this.offTemp();}offTemp(){n.enableDrag(),n.removeEventListener(window,"mousemove",this.mousemove),n.removeEventListener(window,"mouseup",this.mouseup),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend);}}let qa;function Wa(e,i,o,r=!1){if(r||!o.getCoveringTilesDetailsProvider().allowWorldCopies())return null==e?void 0:e.wrap();const a=new t.S(e.lng,e.lat);if(e=new t.S(e.lng,e.lat),i){const r=new t.S(e.lng-360,e.lat),a=new t.S(e.lng+360,e.lat),s=o.locationToScreenPoint(e).distSqr(i);o.locationToScreenPoint(r).distSqr(i)180;){const t=o.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=o.width&&t.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==a.lng&&o.isPointOnMapSurface(o.locationToScreenPoint(e))?e:a}const Ha={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Xa(e,t,i){const o=e.classList;for(const e in Ha)o.remove(`maplibregl-${i}-anchor-${e}`);o.add(`maplibregl-${i}-anchor-${t}`);}class Ka extends t.E{constructor(e){if(super(),this._onKeyPress=e=>{const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{if(!this._map)return;const t=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?void 0:e.type)||"render"===(null==e?void 0:e.type)&&!t)&&this._map.once("render",this._update),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let i="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?i=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(i=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),n.setTransform(this._element,`${Ha[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${i}`),s.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.l("dragstart"))),this.fire(new t.l("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.l("dragend")),this._state="inactive";},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||!1,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(null==e?void 0:e.opacity,null==e?void 0:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.P.convert(e&&e.offset||[0,0]);else {this._defaultMarker=!0,this._element=n.create("div");const i=n.createNS("http://www.w3.org/2000/svg","svg"),o=41,r=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${o}px`),i.setAttributeNS(null,"width",`${r}px`),i.setAttributeNS(null,"viewBox",`0 0 ${r} ${o}`);const a=n.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"stroke","none"),a.setAttributeNS(null,"stroke-width","1"),a.setAttributeNS(null,"fill","none"),a.setAttributeNS(null,"fill-rule","evenodd");const s=n.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"fill-rule","nonzero");const l=n.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"transform","translate(3.0, 29.0)"),l.setAttributeNS(null,"fill","#000000");const c=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const e of c){const t=n.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),l.appendChild(t);}const h=n.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);const u=n.createNS("http://www.w3.org/2000/svg","path");u.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(u);const d=n.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");const _=n.createNS("http://www.w3.org/2000/svg","path");_.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(_);const p=n.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const m=n.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(8.0, 8.0)");const f=n.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#000000"),f.setAttributeNS(null,"opacity","0.25"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962");const g=n.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#FFFFFF"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962"),m.appendChild(f),m.appendChild(g),s.appendChild(l),s.appendChild(h),s.appendChild(d),s.appendChild(p),s.appendChild(m),i.appendChild(s),i.setAttributeNS(null,"height",o*this._scale+"px"),i.setAttributeNS(null,"width",r*this._scale+"px"),this._element.appendChild(i),this._offset=t.P.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),Xa(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),n.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,o=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-t],"bottom-left":[o,-1*(t-i+o)],"bottom-right":[-o,-1*(t-i+o)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=!1){var i,o;const r=null===(i=this._map)||void 0===i?void 0:i.terrain,a=this._map.transform.isLocationOccluded(this._lngLat);if(!r||a){const e=a?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const s=this._map,n=s.terrain.depthAtPoint(this._pos),l=s.terrain.getElevationForLngLatZoom(this._lngLat,s.transform.tileZoom);if(s.transform.lngLatToCameraDepth(this._lngLat,l)-n<.006)return void(this._element.style.opacity=this._opacity);const c=-this._offset.y/s.transform.pixelsPerMeter,h=Math.sin(s.getPitch()*Math.PI/180)*c,u=s.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),d=s.transform.lngLatToCameraDepth(this._lngLat,l+h)-u>.006;(null===(o=this._popup)||void 0===o?void 0:o.isOpen())&&d&&this._popup.remove(),this._element.style.opacity=d?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return (void 0===this._opacity||void 0===e&&void 0===t)&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==e&&(this._opacity=e),void 0!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(!0),this}}const Ya={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let Qa=0,Ja=!1;const es={maxWidth:100,unit:"metric"};function ts(e,t,i){const o=i&&i.maxWidth||100,r=e._container.clientHeight/2,a=e._container.clientWidth/2,s=e.unproject([a-o/2,r]),n=e.unproject([a+o/2,r]),l=Math.round(e.project(n).x-e.project(s).x),c=Math.min(o,l,e._container.clientWidth),h=s.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?is(t,c,i/5280,e._getUIString("ScaleControl.Miles")):is(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?is(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?is(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):is(t,c,h,e._getUIString("ScaleControl.Meters"));}function is(e,t,i,o){const r=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(r/i)+"px",e.innerHTML=`${r} ${o}`;}const os={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1,locationOccludedOpacity:void 0},rs=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function as(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(i,i),"top-right":new t.P(-i,i),bottom:new t.P(0,-e),"bottom-left":new t.P(i,-i),"bottom-right":new t.P(-i,-i),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){const i=t.P.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e["top-left"]||[0,0]),"top-right":t.P.convert(e["top-right"]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e["bottom-left"]||[0,0]),"bottom-right":t.P.convert(e["bottom-right"]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return as(new t.P(0,0))}const ss=i;e.AJAXError=t.cz,e.Event=t.l,e.Evented=t.E,e.LngLat=t.S,e.MercatorCoordinate=t.a1,e.Point=t.P,e.addProtocol=t.cA,e.config=t.a,e.removeProtocol=t.cB,e.AttributionControl=Da,e.BoxZoomHandler=$r,e.CanvasSource=Y,e.CooperativeGesturesHandler=Ca,e.DoubleClickZoomHandler=ba,e.DragPanHandler=wa,e.DragRotateHandler=Ta,e.EdgeInsets=Mt,e.FullscreenControl=class extends t.E{constructor(e={}){super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(e=null==t?void 0:t.shadowRoot)||void 0===e?void 0:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){n.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=n.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);n.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new t.l("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.l("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=H,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.l("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "BACKGROUND":case "BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.l("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.S(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.e({bearing:r},this.options.fitBoundsOptions),s=G.fromLngLat(i,o);this._map.fitBounds(s,a,{geolocateSource:!0});},this._updateMarker=e=>{if(e){const i=new t.S(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this._updateCircleRadiusIfNeeded();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded();},this._onError=e=>{if(this._map){if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Ja)return;this.options.trackUserLocation&&this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.l("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=n.create("button","maplibregl-ctrl-geolocate",this._container),n.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0);},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.w("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=n.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new Ka({element:this._dotElement}),this._circleElement=n.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ka({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onUpdate),this._map.on("move",this._onUpdate),this._map.on("rotate",this._onUpdate),this._map.on("pitch",this._onUpdate)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(e=>{const i=(null==e?void 0:e[0])instanceof ResizeObserverEntry;e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||i||this._map.isZooming()||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.l("trackuserlocationend")),this.fire(new t.l("userlocationlostfocus")));}));}},this.options=t.e({},Ya,e);}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t._(this,arguments,void 0,(function*(e=!1){if(void 0!==qa&&!e)return qa;if(void 0===window.navigator.permissions)return qa=!!window.navigator.geolocation,qa;try{const e=yield window.navigator.permissions.query({name:"geolocation"});qa="denied"!==e.state;}catch(e){qa=!!window.navigator.geolocation;}return qa}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),n.remove(this._container),this._map.off("zoom",this._onUpdate),this._map.off("move",this._onUpdate),this._map.off("rotate",this._onUpdate),this._map.off("pitch",this._onUpdate),this._map=void 0,Qa=0,Ja=!1;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case "WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case "ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadiusIfNeeded(){const e=this._userLocationDotMarker.getLngLat();if(!(this.options.showUserLocation&&this.options.showAccuracyCircle&&this._accuracy&&e))return;const t=this._map.project(e),i=this._map.unproject([t.x+100,t.y]),o=e.distanceTo(i)/100,r=2*this._accuracy/o;this._circleElement.style.width=`${r.toFixed(2)}px`,this._circleElement.style.height=`${r.toFixed(2)}px`;}trigger(){if(!this._setup)return t.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case "OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.l("trackuserlocationstart"));break;case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":case "BACKGROUND_ERROR":Qa--,Ja=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new t.l("trackuserlocationend"));break;case "BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.l("trackuserlocationstart")),this.fire(new t.l("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case "WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),Qa++,Qa>1?(e={maximumAge:6e5,timeout:0},Ja=!0):(e=this.options.positionOptions,Ja=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||void 0===e?void 0:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||void 0===e?void 0:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=n.create("button","maplibregl-ctrl-globe",this._container),n.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0;}},e.Hash=Er,e.ImageSource=X,e.KeyboardHandler=pa,e.LngLatBounds=G,e.LogoControl=Aa,e.Map=class extends Ra{constructor(e){var i,o;t.cw.mark(t.cx.create);const r=Object.assign(Object.assign(Object.assign({},Ga),e),{canvasContextAttributes:Object.assign(Object.assign({},Ga.canvasContextAttributes),e.canvasContextAttributes)});if(null!=r.minZoom&&null!=r.maxZoom&&r.minZoom>r.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=r.minPitch&&null!=r.maxPitch&&r.minPitch>r.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=r.minPitch&&r.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=r.maxPitch&&r.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const a=new Lt,s=new Ot;if(void 0!==r.minZoom&&a.setMinZoom(r.minZoom),void 0!==r.maxZoom&&a.setMaxZoom(r.maxZoom),void 0!==r.minPitch&&a.setMinPitch(r.minPitch),void 0!==r.maxPitch&&a.setMaxPitch(r.maxPitch),void 0!==r.renderWorldCopies&&a.setRenderWorldCopies(r.renderWorldCopies),super(a,s,{bearingSnap:r.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new La,this._controls=[],this._mapId=t.a7(),this._contextLost=e=>{e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new t.l("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._setupPainter(),this.resize(),this._update(),this.fire(new t.l("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update();},this._interactive=r.interactive,this._maxTileCacheSize=r.maxTileCacheSize,this._maxTileCacheZoomLevels=r.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},r.canvasContextAttributes),this._trackResize=!0===r.trackResize,this._bearingSnap=r.bearingSnap,this._centerClampedToGround=r.centerClampedToGround,this._refreshExpiredTiles=!0===r.refreshExpiredTiles,this._fadeDuration=r.fadeDuration,this._crossSourceCollisions=!0===r.crossSourceCollisions,this._collectResourceTiming=!0===r.collectResourceTiming,this._locale=Object.assign(Object.assign({},Ua),r.locale),this._clickTolerance=r.clickTolerance,this._overridePixelRatio=r.pixelRatio,this._maxCanvasSize=r.maxCanvasSize,this.transformCameraUpdate=r.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===r.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=p.addThrottleControl((()=>this.isMoving())),this._requestManager=new m(r.transformRequest),"string"==typeof r.container){if(this._container=document.getElementById(r.container),!this._container)throw new Error(`Container '${r.container}' not found.`)}else {if(!(r.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=r.container;}if(r.maxBounds&&this.setMaxBounds(r.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0);})),this.once("idle",(()=>{this._idleTriggered=!0;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let e=!1;const t=Sr((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{e?t(i):e=!0;})),this._resizeObserver.observe(this._container);}this.handlers=new Ea(this,r),this._hash=r.hash&&new Er("string"==typeof r.hash&&r.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:r.center,elevation:r.elevation,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,roll:r.roll}),r.bounds&&(this.resize(),this.fitBounds(r.bounds,t.e({},r.fitBoundsOptions,{duration:0}))));const n="string"==typeof r.style||!("globe"===(null===(o=null===(i=r.style)||void 0===i?void 0:i.projection)||void 0===o?void 0:o.type));this.resize(null,n),this._localIdeographFontFamily=r.localIdeographFontFamily,this._validateStyle=r.validateStyle,r.style&&this.setStyle(r.style,{localIdeographFontFamily:r.localIdeographFontFamily}),r.attributionControl&&this.addControl(new Da("boolean"==typeof r.attributionControl?void 0:r.attributionControl)),r.maplibreLogo&&this.addControl(new Aa,r.logoPosition),this.on("style.load",(()=>{if(n||this._resizeTransform(),this.transform.unmodified){const e=t.Q(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.l(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.l(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.l("sourcedataabort",e));}));}_getMapId(){return this._mapId}setGlobalStateProperty(e,t){return this.style.setGlobalStateProperty(e,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(e,i){if(void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.k(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const o=e.onAdd(this);this._controls.push(e);const r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.k(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}coveringTiles(e){return ve(this.transform,e)}calculateCameraOptionsFromTo(e,t,i,o){return null==o&&this.terrain&&(o=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(e,t,i,o)}resize(e,i=!0){const[o,r]=this._containerDimensions(),a=this._getClampedPixelRatio(o,r);if(this._resizeCanvas(o,r,a),this.painter.resize(o,r,a),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const t=this._getClampedPixelRatio(o,r);this._resizeCanvas(o,r,t),this.painter.resize(o,r,t);}this._resizeTransform(i);const s=!this._moving;return s&&(this.stop(),this.fire(new t.l("movestart",e)).fire(new t.l("move",e))),this.fire(new t.l("resize",e)),s&&this.fire(new t.l("moveend",e)),this}_resizeTransform(e=!0){var t;const[i,o]=this._containerDimensions();this.transform.resize(i,o,e),null===(t=this._requestedCameraState)||void 0===t||t.resize(i,o,e);}_getClampedPixelRatio(e,t){const{0:i,1:o}=this._maxCanvasSize,r=this.getPixelRatio(),a=e*r,s=t*r;return Math.min(a>i?i/a:1,s>o?o/s:1)*r}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&void 0!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(G.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom)return this.transform.setMinZoom(e),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(e),this._update(),this.getZoom()>e&&this.setZoom(e),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.setMinPitch(e),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch)return this.transform.setMaxPitch(e),this._update(),this.getPitch()>e&&this.setPitch(e),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.S.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||void 0===e?void 0:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||void 0===e?void 0:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||void 0===e?void 0:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e))),s=0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[];s.length?o||(o=!0,i.call(this,new jr(e,this,r.originalEvent,{features:s}))):o=!1;};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:()=>{o=!1;}}}}if("mouseleave"===e||"mouseout"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e)));(0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[]).length?o=!0:o&&(o=!1,i.call(this,new jr(e,this,r.originalEvent)));},a=t=>{o&&(o=!1,i.call(this,new jr(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:a}}}{const o=e=>{const o=t.filter((e=>this.getLayer(e))),r=0!==o.length?this.queryRenderedFeatures(e.point,{layers:o}):[];r.length&&(e.features=r,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:o}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const o=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in r.delegates)this.off(e,r.delegates[e]);return void o.splice(e,1)}}}on(e,t,i){if(void 0===i)return super.on(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);this._saveDelegatedListener(e,r);for(const e in r.delegates)this.on(e,r.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,o,i);}}}once(e,t,i){if(void 0===i)return super.once(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);for(const t in r.delegates){const a=r.delegates[t];r.delegates[t]=(...t)=>{this._removeDelegatedListener(e,o,i),a(...t);};}this._saveDelegatedListener(e,r);for(const e in r.delegates)this.once(e,r.delegates[e]);return this}off(e,t,i){return void 0===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let o;const r=e instanceof t.P||Array.isArray(e),a=r?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(r?{}:e)||{},a instanceof t.P||"number"==typeof a[0])o=[t.P.convert(a)];else {const e=t.P.convert(a[0]),i=t.P.convert(a[1]);o=[e,new t.P(i.x,e.y),i,new t.P(e.x,i.y),e];}return this.style.queryRenderedFeatures(o,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return !1!==(i=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,o;if(t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const r=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new wi(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,r):this.style.loadJSON(e,t,r),this):(null===(o=null===(i=this.style)||void 0===i?void 0:i.projection)||void 0===o||o.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new wi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){if("string"==typeof e){const o=this._requestManager.transformRequest(e,"Style");t.j(o,new AbortController).then((e=>{this._updateDiff(e.data,i);})).catch((e=>{e&&this.fire(new t.k(e));}));}else "object"==typeof e&&this._updateDiff(e,i);}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(o){t.w(`Unable to perform style diff: ${o.message||o.error||o}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():t.w("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){const i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.k(new Error(`There is no source with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.sourceCaches[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const o=this.style._layers[i];"hillshade"===o.type&&o.source===e.source&&t.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality."),"color-relief"===o.type&&o.source===e.source&&t.w("You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");}this.terrain=new Ba(this.painter,i,e),this.painter.renderToTexture=new Na(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{var i;"style"===t.dataType?this.terrain.sourceCache.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),"image"===(null===(i=t.source)||void 0===i?void 0:i.type)?this.terrain.sourceCache.freeRtt():this.terrain.sourceCache.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.l("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||void 0===e?void 0:e.options)&&void 0!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.sourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}}return !0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}setSourceTileLodParams(e,t,i){if(i){const o=this.getSource(i);if(!o)throw new Error(`There is no source with ID "${i}", cannot set LOD parameters`);o.calculateTileZoom=me(Math.max(1,e),Math.max(1,t));}else for(const i in this.style.sourceCaches)this.style.sourceCaches[i].getSource().calculateTileZoom=me(Math.max(1,e),Math.max(1,t));return this._update(!0),this}refreshTiles(e,i){const o=this.style.sourceCaches[e];if(!o)throw new Error(`There is no source cache with ID "${e}", cannot refresh tile`);void 0===i?o.reload(!0):o.refreshTiles(i.map((e=>new t.a4(e.z,e.x,e.y))));}addImage(e,i,o={}){const{pixelRatio:r=1,sdf:a=!1,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u}=o;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.b(i))){if(void 0===i.width||void 0===i.height)return this.fire(new t.k(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:o,height:s,data:d}=i,_=i;return this.style.addImage(e,{data:new t.R({width:o,height:s},new Uint8Array(d)),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:o,height:d,data:_}=s.getImageData(i);this.style.addImage(e,{data:new t.R({width:o,height:d},_),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0});}}updateImage(e,i){const o=this.style.getImage(e);if(!o)return this.fire(new t.k(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const r=i instanceof HTMLImageElement||t.b(i)?s.getImageData(i):i,{width:a,height:n,data:l}=r;if(void 0===a||void 0===n)return this.fire(new t.k(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(a!==o.data.width||n!==o.data.height)return this.fire(new t.k(new Error("The width and height of the updated image must be that same as the previous version of the image")));const c=!(i instanceof HTMLImageElement||t.b(i));return o.data.replace(l,c),this.style.updateImage(e,o),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.k(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(e);}loadImage(e){return p.getImage(this._requestManager.transformRequest(e,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(!0)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,o={}){return this.style.setPaintProperty(e,t,i,o),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,o={}){return this.style.setLayoutProperty(e,t,i,o),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(!0);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=n.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=n.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),o=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],o);const r=this._controlContainer=n.create("div","maplibregl-control-container",e),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{a[e]=n.create("div",`maplibregl-ctrl-${e} `,r);})),this._container.addEventListener("scroll",this._onMapScroll,!1);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0});let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:!0});let i=null;if(i=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e),!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new Mr(i,this.transform),l.testSupport(i);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.l("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){var i,o,r,a,n;const l=this._idleTriggered?this._fadeDuration:0,c=(null===(i=this.style.projection)||void 0===i?void 0:i.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let h=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,i=s.now();this.style.zoomHistory.update(e,i);const o=new t.F(e,{now:i,fadeDuration:l,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),r=o.crossFadingFactor();1===r&&r===this._crossFadingFactor||(h=!0,this._crossFadingFactor=r),this.style.update(o);}const u=(null===(o=this.style.projection)||void 0===o?void 0:o.transitionState)>0!==c;null===(r=this.style.projection)||void 0===r||r.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(a=this.style.projection)||void 0===a?void 0:a.transitionState,null===(n=this.style.projection)||void 0===n?void 0:n.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||u)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,l,this._crossSourceCollisions,u),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:l,showPadding:this.showPadding}),this.fire(new t.l("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,t.cw.mark(t.cx.load),this.fire(new t.l("load"))),this.style&&(this.style.hasTransitions()||h)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const d=this._sourcesDirty||this._styleDirty||this._placementDirty;return d||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.l("idle")),!this._loaded||this._fullyLoaded||d||(this._fullyLoaded=!0,t.cw.mark(t.cx.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),p.removeThrottleControl(this._imageQueueHandle),null===(e=this._resizeObserver)||void 0===e||e.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?void 0:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),n.remove(this._canvasContainer),n.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),t.cw.clearMetrics(),this._removed=!0,this.fire(new t.l("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,s.frame(this._frameRequest,(e=>{t.cw.frame(e),this._frameRequest=null;try{this._render(e);}catch(e){if(!t.cy(e)&&!function(e){return e.message===qo}(e))throw e}}),(()=>{})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return Za}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}},e.MapMouseEvent=jr,e.MapTouchEvent=Nr,e.MapWheelEvent=Ur,e.Marker=Ka,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.e({},Va,e),this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=n.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new $a(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){n.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=n.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.E{constructor(e){super(),this._updateOpacity=()=>{void 0!==this.options.locationOccludedOpacity&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:"");},this.remove=()=>(this._content&&n.remove(this._content),this._container&&(n.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new t.l("close"))),this),this._onMouseUp=e=>{this._update(e.point);},this._onMouseMove=e=>{this._update(e.point);},this._onDrag=e=>{this._update(e.point);},this._update=e=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=n.create("div","maplibregl-popup",this._map.getContainer()),this._tip=n.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer");}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),this._trackPointer&&!e)return;const t=this._flatPos=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&e?e:this._map.transform.locationToScreenPoint(this._lngLat));let i=this.options.anchor;const o=as(this.options.offset);if(!i){const e=this._container.offsetWidth,r=this._container.offsetHeight;let a;a=t.y+o.bottom.ythis._map.transform.height-r?["bottom"]:[],t.xthis._map.transform.width-e/2&&a.push("right"),i=0===a.length?"bottom":a.join("-");}let r=t.add(o[i]);this.options.subpixelPositioning||(r=r.round()),n.setTransform(this._container,`${Ha[i]} translate(${r.x}px,${r.y}px)`),Xa(this._container,i,"popup"),this._updateOpacity();},this._onClose=()=>{this.remove();},this.options=t.e(Object.create(os),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.l("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let o;for(i.innerHTML=e;o=i.firstChild,o;)t.appendChild(o);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||void 0===e?void 0:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=n.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}_createCloseButton(){this.options.closeButton&&(this._closeButton=n.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(rs);e&&e.focus();}},e.RasterDEMTileSource=W,e.RasterTileSource=q,e.ScaleControl=class{constructor(e){this._onMove=()=>{ts(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,ts(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},es),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){n.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;}},e.ScrollZoomHandler=va,e.Style=wi,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=n.create("button","maplibregl-ctrl-terrain",this._container),n.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){n.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0;}},e.TwoFingersTouchPitchHandler=da,e.TwoFingersTouchRotateHandler=ha,e.TwoFingersTouchZoomHandler=la,e.TwoFingersTouchZoomRotateHandler=Pa,e.VectorTileSource=$,e.VideoSource=K,e.addSourceType=(e,i)=>t._(void 0,void 0,void 0,(function*(){if(J(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{Q[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=A;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(R),A=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},e.createTileMesh=Xt,e.getMaxParallelImageRequests=function(){return t.a.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},e.getVersion=function(){return ss},e.getWorkerCount=function(){return z.workerCount},e.getWorkerUrl=function(){return t.a.WORKER_URL},e.importScriptInWorkers=function(e){return B().broadcast("IS",e)},e.prewarm=function(){k().acquire(R);},e.setMaxParallelImageRequests=function(e){t.a.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setRTLTextPlugin=function(e,t){return oe().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){z.workerCount=e;},e.setWorkerUrl=function(e){t.a.WORKER_URL=e;};})); + +// +// Our custom intro provides a specialized "define()" function, called by the +// AMD modules below, that sets up the worker blob URL and then executes the +// main module, storing its exported value as 'maplibregl' + + +var maplibregl$1 = maplibregl; + +return maplibregl$1; + +})); +//# sourceMappingURL=maplibre-gl.js.map diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt new file mode 100644 index 0000000..624d1f1 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2023, MapTiler +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js new file mode 100644 index 0000000..0fe7116 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js @@ -0,0 +1,14 @@ +(function(j,ee){typeof exports=="object"&&typeof module<"u"?ee(exports,require("maplibre-gl")):typeof define=="function"&&define.amd?define(["exports","maplibre-gl"],ee):(j=typeof globalThis<"u"?globalThis:j||self,ee(j.maplibreglMaptilerGeocoder={},j.maplibregl))})(this,function(j,ee){"use strict";var Ws=Object.defineProperty;var bn=j=>{throw TypeError(j)};var Gs=(j,ee,me)=>ee in j?Ws(j,ee,{enumerable:!0,configurable:!0,writable:!0,value:me}):j[ee]=me;var A=(j,ee,me)=>Gs(j,typeof ee!="symbol"?ee+"":ee,me),wn=(j,ee,me)=>ee.has(j)||bn("Cannot "+me);var ue=(j,ee,me)=>(wn(j,ee,"read from private field"),me?me.call(j):ee.get(j)),Vt=(j,ee,me)=>ee.has(j)?bn("Cannot add the same private member more than once"):ee instanceof WeakSet?ee.add(j):ee.set(j,me),kt=(j,ee,me,dt)=>(wn(j,ee,"write to private field"),dt?dt.call(j,me):ee.set(j,me),me);var fn,cn;function me(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const dt=me(ee);function ne(){}function Ln(i,e){for(const t in e)i[t]=e[t];return i}function yi(i){return i()}function vi(){return Object.create(null)}function Ue(i){i.forEach(yi)}function bi(i){return typeof i=="function"}function Ke(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}let Rt;function ye(i,e){return i===e?!0:(Rt||(Rt=document.createElement("a")),Rt.href=e,i===Rt.href)}function _n(i){return Object.keys(i).length===0}function Sn(i,e,t,n){if(i){const r=wi(i,e,t,n);return i[0](r)}}function wi(i,e,t,n){return i[1]&&n?Ln(t.ctx.slice(),i[1](n(e))):t.ctx}function xn(i,e,t,n){return i[2],e.dirty}function Tn(i,e,t,n,r,u){if(r){const a=wi(e,t,n,u);i.p(a,r)}}function Mn(i){if(i.ctx.length>32){const e=[],t=i.ctx.length/32;for(let n=0;ni.removeEventListener(e,t,n)}function Nn(i){return function(e){return e.preventDefault(),i.call(this,e)}}function S(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function kn(i){return Array.from(i.childNodes)}function gt(i,e){e=""+e,i.data!==e&&(i.data=e)}function Ei(i,e){i.value=e??""}function Ie(i,e,t){i.classList.toggle(e,!!t)}function On(i,e,{bubbles:t=!1,cancelable:n=!1}={}){return new CustomEvent(i,{detail:e,bubbles:t,cancelable:n})}let mt;function pt(i){mt=i}function Li(){if(!mt)throw new Error("Function called outside component initialization");return mt}function Rn(i){Li().$$.on_destroy.push(i)}function _i(){const i=Li();return(e,t,{cancelable:n=!1}={})=>{const r=i.$$.callbacks[e];if(r){const u=On(e,t,{cancelable:n});return r.slice().forEach(a=>{a.call(i,u)}),!u.defaultPrevented}return!0}}function Pn(i,e){const t=i.$$.callbacks[e.type];t&&t.slice().forEach(n=>n.call(this,e))}const ut=[],Yt=[];let at=[];const Si=[],In=Promise.resolve();let Qt=!1;function An(){Qt||(Qt=!0,In.then(xi))}function Xt(i){at.push(i)}const Jt=new Set;let ft=0;function xi(){if(ft!==0)return;const i=mt;do{try{for(;fti.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),at=e}const It=new Set;let nt;function yt(){nt={r:0,c:[],p:nt}}function vt(){nt.r||Ue(nt.c),nt=nt.p}function re(i,e){i&&i.i&&(It.delete(i),i.i(e))}function fe(i,e,t,n){if(i&&i.o){if(It.has(i))return;It.add(i),nt.c.push(()=>{It.delete(i),n&&(t&&i.d(1),n())}),i.o(e)}else n&&n()}function Ti(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function Gn(i,e){fe(i,1,1,()=>{e.delete(i.key)})}function Dn(i,e,t,n,r,u,a,o,g,c,E,_){let M=i.length,R=u.length,k=M;const I={};for(;k--;)I[i[k].key]=k;const C=[],O=new Map,x=new Map,N=[];for(k=R;k--;){const W=_(r,u,k),s=t(W);let l=a.get(s);l?N.push(()=>l.p(W,e)):(l=c(s,W),l.c()),O.set(s,C[k]=l),s in I&&x.set(s,Math.abs(k-I[s]))}const P=new Set,B=new Set;function z(W){re(W,1),W.m(o,E),a.set(W.key,W),E=W.first,R--}for(;M&&R;){const W=C[R-1],s=i[M-1],l=W.key,f=s.key;W===s?(E=W.first,M--,R--):O.has(f)?!a.has(l)||P.has(l)?z(W):B.has(f)?M--:x.get(l)>x.get(f)?(B.add(l),z(W)):(P.add(f),M--):(g(s,a),M--)}for(;M--;){const W=i[M];O.has(W.key)||g(W,a)}for(;R;)z(C[R-1]);return Ue(N),C}function Qe(i){i&&i.c()}function qe(i,e,t){const{fragment:n,after_update:r}=i.$$;n&&n.m(e,t),Xt(()=>{const u=i.$$.on_mount.map(yi).filter(bi);i.$$.on_destroy?i.$$.on_destroy.push(...u):Ue(u),i.$$.on_mount=[]}),r.forEach(Xt)}function Fe(i,e){const t=i.$$;t.fragment!==null&&(Wn(t.after_update),Ue(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function zn(i,e){i.$$.dirty[0]===-1&&(ut.push(i),An(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<{const k=R.length?R[0]:M;return c.ctx&&r(c.ctx[_],c.ctx[_]=k)&&(!c.skip_bound&&c.bound[_]&&c.bound[_](k),E&&zn(i,_)),M}):[],c.update(),E=!0,Ue(c.before_update),c.fragment=n?n(c.ctx):!1,e.target){if(e.hydrate){const _=kn(e.target);c.fragment&&c.fragment.l(_),_.forEach($)}else c.fragment&&c.fragment.c();e.intro&&re(i.$$.fragment),qe(i,e.target,e.anchor),xi()}pt(g)}class Je{constructor(){A(this,"$$");A(this,"$$set")}$destroy(){Fe(this,1),this.$destroy=ne}$on(e,t){if(!bi(t))return ne;const n=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return n.push(t),()=>{const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}$set(e){this.$$set&&!_n(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Un="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Un);function qn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M13.12.706a.982.982 0 0 0-1.391 0L6.907 5.517 2.087.696a.982.982 0 1 0-1.391 1.39l4.821 4.821L.696 11.73a.982.982 0 1 0 1.39 1.39l4.821-4.821 4.822 4.821a.982.982 0 1 0 1.39-1.39L8.298 6.908l4.821-4.822a.988.988 0 0 0 0-1.38Z"),S(e,"viewBox","0 0 14 14"),S(e,"width","13"),S(e,"height","13"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Mi extends Je{constructor(e){super(),Xe(this,e,null,qn,Ke,{})}}function Fn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M15 0C6.705 0 0 6.705 0 15C0 23.295 6.705 30 15 30C23.295 30 30 23.295 30 15C30 6.705 23.295 0 15 0ZM22.5 20.385L20.385 22.5L15 17.115L9.615 22.5L7.5 20.385L12.885 15L7.5 9.615L9.615 7.5L15 12.885L20.385 7.5L22.5 9.615L17.115 15L22.5 20.385Z"),S(e,"viewBox","0 0 30 30"),S(e,"fill","none"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"class","svelte-d2loi5")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Ci extends Je{constructor(e){super(),Xe(this,e,null,Fn,Ke,{})}}function jn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"area.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"area.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Zn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"reverse.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"reverse.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Hn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"poi.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"poi.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Vn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"postal_code.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"postal_code.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Kn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"street.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"street.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Yn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"road.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"road.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Qn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"housenumber.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"housenumber.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Xn(i){let e,t,n,r;return{c(){e=Y("img"),ye(e.src,t=i[5])||S(e,"src",t),S(e,"alt",i[4]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(u,a){te(u,e,a),n||(r=he(e,"error",i[14]),n=!0)},p(u,a){a&32&&!ye(e.src,t=u[5])&&S(e,"src",t),a&16&&S(e,"alt",u[4]),a&128&&S(e,"title",u[7])},d(u){u&&$(e),n=!1,r()}}}function Jn(i){let e,t;return{c(){e=Y("div"),S(e,"class","sprite-icon svelte-w9y5n9"),S(e,"style",t=` + width: ${i[6].width/xe}px; + height: ${i[6].height/xe}px; + background-image: url(${i[3]}sprite${$t}.png); + background-position: -${i[6].x/xe}px -${i[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `),S(e,"title",i[7])},m(n,r){te(n,e,r)},p(n,r){r&72&&t!==(t=` + width: ${n[6].width/xe}px; + height: ${n[6].height/xe}px; + background-image: url(${n[3]}sprite${$t}.png); + background-position: -${n[6].x/xe}px -${n[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `)&&S(e,"style",t),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Ni(i){let e,t;return{c(){e=Y("span"),t=Ye(i[7]),S(e,"class","secondary svelte-w9y5n9")},m(n,r){te(n,e,r),V(e,t)},p(n,r){r&128&>(t,n[7])},d(n){n&&$(e)}}}function $n(i){let e,t,n,r,u,a,o,g,c,E=(i[8]?i[0].place_name:i[0].place_name.replace(/,.*/,""))+"",_,M,R=i[2]==="always"||i[2]!=="never"&&!i[0].address&&!i[0].id.startsWith("road.")&&!i[0].id.startsWith("address.")&&!i[0].id.startsWith("postal_code.")&&(!i[0].id.startsWith("poi.")||!i[5])&&!i[8],k,I,C=(i[8]?"":i[0].place_name.replace(/[^,]*,?\s*/,""))+"",O,x,N,P,B,z;function W(m,h){return h&1&&(t=null),h&1&&(n=null),h&1&&(r=null),h&1&&(u=null),Oe&&m[6]?Jn:m[5]?Xn:m[0].address?Qn:(t==null&&(t=!!m[0].id.startsWith("road.")),t?Yn:(n==null&&(n=!!m[0].id.startsWith("address.")),n?Kn:(r==null&&(r=!!m[0].id.startsWith("postal_code.")),r?Vn:(u==null&&(u=!!m[0].id.startsWith("poi.")),u?Hn:m[8]?Zn:jn))))}let s=W(i,-1),l=s(i),f=R&&Ni(i);return{c(){e=Y("li"),l.c(),a=we(),o=Y("span"),g=Y("span"),c=Y("span"),_=Ye(E),M=we(),f&&f.c(),k=we(),I=Y("span"),O=Ye(C),S(c,"class","primary svelte-w9y5n9"),S(g,"class","svelte-w9y5n9"),S(I,"class","line2 svelte-w9y5n9"),S(o,"class","texts svelte-w9y5n9"),S(e,"tabindex","-1"),S(e,"role","option"),S(e,"aria-selected",x=i[1]==="selected"),S(e,"aria-checked",N=i[1]==="picked"),S(e,"class",P=Pt(i[1])+" svelte-w9y5n9")},m(m,h){te(m,e,h),l.m(e,null),V(e,a),V(e,o),V(o,g),V(g,c),V(c,_),V(g,M),f&&f.m(g,null),V(o,k),V(o,I),V(I,O),B||(z=[he(e,"mouseenter",i[13]),he(e,"focus",i[15]),he(e,"click",i[16])],B=!0)},p(m,[h]){s===(s=W(m,h))&&l?l.p(m,h):(l.d(1),l=s(m),l&&(l.c(),l.m(e,a))),h&257&&E!==(E=(m[8]?m[0].place_name:m[0].place_name.replace(/,.*/,""))+"")&>(_,E),h&293&&(R=m[2]==="always"||m[2]!=="never"&&!m[0].address&&!m[0].id.startsWith("road.")&&!m[0].id.startsWith("address.")&&!m[0].id.startsWith("postal_code.")&&(!m[0].id.startsWith("poi.")||!m[5])&&!m[8]),R?f?f.p(m,h):(f=Ni(m),f.c(),f.m(g,null)):f&&(f.d(1),f=null),h&257&&C!==(C=(m[8]?"":m[0].place_name.replace(/[^,]*,?\s*/,""))+"")&>(O,C),h&2&&x!==(x=m[1]==="selected")&&S(e,"aria-selected",x),h&2&&N!==(N=m[1]==="picked")&&S(e,"aria-checked",N),h&2&&P!==(P=Pt(m[1])+" svelte-w9y5n9")&&S(e,"class",P)},i:ne,o:ne,d(m){m&&$(e),l.d(),f&&f.d(),B=!1,Ue(z)}}}const ki=typeof devicePixelRatio>"u"?1:devicePixelRatio>1.25,$t=ki?"@2x":"",xe=ki?2:1;let Oe,At;function er(i,e,t){let n,r,u,{feature:a}=e,{style:o="default"}=e,{showPlaceType:g}=e,{missingIconsCache:c}=e,{iconsBaseUrl:E}=e;const _=_i();let M,R,k,I;function C(){At??(At=fetch(`${E}sprite${$t}.json`).then(s=>s.json()).then(s=>{Oe=s}).catch(()=>{Oe=null}))}function O(){R&&c.add(R),x()}function x(){Oe!==void 0?N():(C(),At==null||At.then(N))}function N(){do{if(I--,t(4,M=n==null?void 0:n[I]),t(6,k=M?Oe==null?void 0:Oe.icons[M]:void 0),k)break;t(5,R=M?E+M.replace(/ /g,"_")+".svg":void 0)}while(I>-1&&(!R||c.has(R)))}function P(s){Pn.call(this,i,s)}const B=()=>O(),z=()=>_("select",void 0),W=s=>{document.activeElement!==s.target&&_("select",void 0)};return i.$$set=s=>{"feature"in s&&t(0,a=s.feature),"style"in s&&t(1,o=s.style),"showPlaceType"in s&&t(2,g=s.showPlaceType),"missingIconsCache"in s&&t(11,c=s.missingIconsCache),"iconsBaseUrl"in s&&t(3,E=s.iconsBaseUrl)},i.$$.update=()=>{var s,l,f,m,h;i.$$.dirty&1&&t(12,n=(s=a.properties)==null?void 0:s.categories),i.$$.dirty&1&&t(8,r=a.place_type[0]==="reverse"),i.$$.dirty&1&&t(7,u=((f=(l=a.properties)==null?void 0:l.categories)==null?void 0:f.join(", "))??((h=(m=a.properties)==null?void 0:m.place_type_name)==null?void 0:h[0])??a.place_type[0]),i.$$.dirty&4096&&(I=(n==null?void 0:n.length)??0,x())},[a,o,g,E,M,R,k,u,r,_,O,c,n,P,B,z,W]}class tr extends Je{constructor(e){super(),Xe(this,e,er,$n,Ke,{feature:0,style:1,showPlaceType:2,missingIconsCache:11,iconsBaseUrl:3})}}function ir(i){let e;return{c(){e=Y("div"),e.innerHTML='',S(e,"class","svelte-1ocfouu")},m(t,n){te(t,e,n)},p:ne,i:ne,o:ne,d(t){t&&$(e)}}}class nr extends Je{constructor(e){super(),Xe(this,e,null,ir,Ke,{})}}function rr(i){let e,t,n;return{c(){e=ke("svg"),t=ke("path"),S(t,"stroke-width","4"),S(t,"d","M 5,33.103579 C 5,17.607779 18.457,5 35,5 C 51.543,5 65,17.607779 65,33.103579 C 65,56.388679 40.4668,76.048179 36.6112,79.137779 C 36.3714,79.329879 36.2116,79.457979 36.1427,79.518879 C 35.8203,79.800879 35.4102,79.942779 35,79.942779 C 34.5899,79.942779 34.1797,79.800879 33.8575,79.518879 C 33.7886,79.457979 33.6289,79.330079 33.3893,79.138079 C 29.5346,76.049279 5,56.389379 5,33.103579 Z M 35.0001,49.386379 C 43.1917,49.386379 49.8323,42.646079 49.8323,34.331379 C 49.8323,26.016779 43.1917,19.276479 35.0001,19.276479 C 26.8085,19.276479 20.1679,26.016779 20.1679,34.331379 C 20.1679,42.646079 26.8085,49.386379 35.0001,49.386379 Z"),S(t,"class","svelte-gzo3ar"),S(e,"width",n=i[0]==="list"?20:void 0),S(e,"viewBox","0 0 70 85"),S(e,"fill","none"),S(e,"class","svelte-gzo3ar"),Ie(e,"in-map",i[0]!=="list"),Ie(e,"list-icon",i[0]==="list")},m(r,u){te(r,e,u),V(e,t)},p(r,[u]){u&1&&n!==(n=r[0]==="list"?20:void 0)&&S(e,"width",n),u&1&&Ie(e,"in-map",r[0]!=="list"),u&1&&Ie(e,"list-icon",r[0]==="list")},i:ne,o:ne,d(r){r&&$(e)}}}function sr(i,e,t){let{displayIn:n}=e;return i.$$set=r=>{"displayIn"in r&&t(0,n=r.displayIn)},[n]}class or extends Je{constructor(e){super(),Xe(this,e,sr,rr,Ke,{displayIn:0})}}function lr(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M30.003-26.765C13.46-26.765 0-14.158 0 1.337c0 23.286 24.535 42.952 28.39 46.04.24.192.402.316.471.376.323.282.732.424 1.142.424.41 0 .82-.142 1.142-.424.068-.06.231-.183.471-.376 3.856-3.09 28.39-22.754 28.39-46.04 0-15.495-13.46-28.102-30.003-28.102Zm1.757 12.469c4.38 0 7.858 1.052 10.431 3.158 2.595 2.105 3.89 4.913 3.89 8.422 0 2.34-.53 4.362-1.593 6.063-1.063 1.702-3.086 3.616-6.063 5.742-2.042 1.51-3.337 2.659-3.89 3.446-.532.787-.8 1.82-.8 3.096v1.914h-8.449V15.18c0-2.041.434-3.815 1.306-5.325.872-1.51 2.467-3.118 4.785-4.82 2.233-1.594 3.7-2.89 4.402-3.889a5.582 5.582 0 0 0 1.087-3.35c0-1.382-.51-2.435-1.531-3.158-1.02-.723-2.45-1.087-4.28-1.087-3.19 0-6.826 1.047-10.91 3.131l-3.472-6.986c4.742-2.659 9.77-3.992 15.087-3.992Zm-1.88 37.324c1.765 0 3.124.472 4.08 1.408.98.936 1.47 2.276 1.47 4.02 0 1.68-.49 3.007-1.47 3.985-.977.957-2.336 1.435-4.08 1.435-1.787 0-3.171-.465-4.15-1.4-.978-.958-1.47-2.298-1.47-4.02 0-1.787.48-3.14 1.436-4.054.957-.915 2.355-1.374 4.184-1.374Z"),S(e,"viewBox","0 0 60.006 21.412"),S(e,"width","14"),S(e,"height","20"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class ur extends Je{constructor(e){super(),Xe(this,e,null,lr,Ke,{})}}function ar(i){let e,t,n;return{c(){e=ke("svg"),t=ke("circle"),n=ke("path"),S(t,"cx","4.789"),S(t,"cy","4.787"),S(t,"r","3.85"),S(t,"class","svelte-1aq105l"),S(n,"d","M12.063 12.063 7.635 7.635"),S(n,"class","svelte-1aq105l"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"width","13"),S(e,"height","13"),S(e,"viewBox","0 0 13 13"),S(e,"class","svelte-1aq105l")},m(r,u){te(r,e,u),V(e,t),V(e,n)},p:ne,i:ne,o:ne,d(r){r&&$(e)}}}class fr extends Je{constructor(e){super(),Xe(this,e,null,ar,Ke,{})}}function cr(i,e,t){const n=e[1],r=e[0],u=n-r;return i===n&&t?i:((i-r)%u+u)%u+r}function Bt(i){const e=[...i];return e[2]Math.abs((e[0]-360+e[2])/2)?e[0]-=360:e[2]+=360),e}let bt;async function hr(i,e,t){const n=i==null?void 0:i.getCenterAndZoom();for(const r of e??[])if(!(n&&(r.minZoom!=null&&r.minZoom>n[0]||r.maxZoom!=null&&r.maxZoomDate.now()){if(!bt.coords)break e;return bt.coords}let u;try{return u=await new Promise((a,o)=>{t.signal.addEventListener("abort",()=>{o(Error("aborted"))}),navigator.geolocation.getCurrentPosition(g=>{a([g.coords.longitude,g.coords.latitude].map(c=>c.toFixed(6)).join(","))},g=>{o(g)},r)}),u}catch{}finally{r.cachedLocationExpiry&&(bt={time:Date.now(),coords:u})}if(t.signal.aborted)return}if(r.type==="server-geolocation")return"ip";if(n&&r.type==="map-center")return n[1].toFixed(6)+","+n[2].toFixed(6)}}const dr=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(EAST|WEST|[EW])?$/i,Oi=/^([+-]?[0-8]?[0-9])\s+([0-5]?[0-9]\.\d{3,})[\s,]{1,}([+-]?[0-1]?[0-9]?[0-9])\s+([0-5]?[0-9]\.\d{3,})$/,Ri=/^(NORTH|SOUTH|[NS])?[\s]*([+-]?[0-8]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(NORTH|SOUTH|[NS])?[\s]*[,/;]?[\s]*(EAST|WEST|[EW])?[\s]*([+-]?[0-1]?[0-9]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(EAST|WEST|[EW])?$/i,Pi=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(EAST|WEST|[EW])?$/i,Ii=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)\s*(EAST|WEST|[EW])?$/i,Ai=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|’’|´´|["″”\.])?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|´´|’’|["″”\.])?\s*(EAST|WEST|[EW])?$/i;function gr(i){if(!["DMS","DM","DD"].includes(i))throw new Error("invalid format specified");if(this.decimalCoordinates&&this.decimalCoordinates.trim()){const e=this.decimalCoordinates.split(",").map(R=>Number(R.trim())),t=Number(e[0]),n=Number(e[1]),r=Math.abs(t),u=Math.abs(n),a=t>0?"N":"S",o=n>0?"E":"W";let g;i=="DD"&&(g=`${r}° ${a}, ${u}° ${o}`);const c=Math.floor(r),E=Math.floor(u),_=(r-c)*60,M=(u-E)*60;if(i=="DM"){let R=Bi(_,3).toFixed(3).padStart(6,"0"),k=Bi(M,3).toFixed(3).padStart(6,"0");R.endsWith(".000")&&k.endsWith(".000")&&(R=R.replace(/\.000$/,""),k=k.replace(/\.000$/,"")),g=`${c}° ${R}' ${a}, ${E}° ${k}' ${o}`}if(i=="DMS"){const R=Math.floor(_),k=Math.floor(M);let I=((_-R)*60).toFixed(1).padStart(4,"0"),C=((M-k)*60).toFixed(1).padStart(4,"0");const O=R.toString().padStart(2,"0"),x=k.toString().padStart(2,"0");I.endsWith(".0")&&C.endsWith(".0")&&(I=I.replace(/\.0$/,""),C=C.replace(/\.0$/,"")),g=`${c}° ${O}' ${I}" ${a}, ${E}° ${x}' ${C}" ${o}`}return g}else throw new Error("no decimal coordinates to convert")}function Bi(i,e){const t=Math.pow(10,e);return Math.round((i+Number.EPSILON)*t)/t}function ei(i,e){e||(e=5),i=i.replace(/\s+/g," ").trim();let t=null,n=null,r="",u="",a=null,o=[],g=!1;if(dr.test(i))throw new Error("invalid coordinate value");if(Oi.test(i))if(o=Oi.exec(i),g=wt(o),g)t=Math.abs(o[1])+o[2]/60,Number(o[1])<0&&(t*=-1),n=Math.abs(o[3])+o[4]/60,Number(o[3])<0&&(n*=-1),a="DM";else throw new Error("invalid coordinate format");else if(Ri.test(i))if(o=Ri.exec(i),g=wt(o),g){if(t=o[2],n=o[6],t.includes(",")&&(t=t.replace(",",".")),n.includes(",")&&(n=n.replace(",",".")),a="DD",Number(Math.round(t))==Number(t))throw new Error("integer only coordinate provided");if(Number(Math.round(n))==Number(n))throw new Error("integer only coordinate provided");o[1]?(r=o[1],u=o[5]):o[4]&&(r=o[4],u=o[8])}else throw new Error("invalid decimal coordinate format");else if(Pi.test(i))if(o=Pi.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[9])),o[11]&&(n+=o[11]/60),o[13]&&(n+=o[13].replace(",",".")/3600),parseInt(o[9])<0&&(n=-1*n),o[1]?(r=o[1],u=o[8]):o[7]&&(r=o[7],u=o[14]);else throw new Error("invalid DMS coordinates format");else if(Ii.test(i))if(o=Ii.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6]/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12]/60),o[14]&&(n+=o[14]/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid DMS coordinates format");else if(Ai.test(i)){if(o=Ai.exec(i),g=wt(o),o.filter(c=>c).length<=5)throw new Error("invalid coordinates format");if(g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4].replace(",",".")/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12].replace(",",".")/60),o[14]&&(n+=o[14].replace(",",".")/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid coordinates format")}if(g){if(Math.abs(n)>=180)throw new Error("invalid longitude value");if(Math.abs(t)>=90)throw new Error("invalid latitude value");if(r&&!u||!r&&u)throw new Error("invalid coordinates value");if(r&&r==u)throw new Error("invalid coordinates format");t.toString().includes(",")&&(t=t.replace(",",".")),n.toString().includes(",")&&(n=n.replace(",","."));let c=/S|SOUTH/i;c.test(r)&&t>0&&(t=-1*t),c=/W|WEST/i,c.test(u)&&n>0&&(n=-1*n);const E=o[0].trim();let _,M;const R=/[,/;\u0020]/g,k=E.match(R);if(k==null){const O=Math.floor(i.length/2);_=E.substring(0,O).trim(),M=E.substring(O).trim()}else{let O;k.length%2==1?O=Math.floor(k.length/2):O=k.length/2-1;let x=0;if(O==0)x=E.indexOf(k[0]),_=E.substring(0,x).trim(),M=E.substring(x+1).trim();else{let N=0,P=0;for(;N<=O;)x=E.indexOf(k[N],P),P=x+1,N++;_=E.substring(0,x).trim(),M=E.substring(x+1).trim()}}const I=_.split(".");if(I.length==2&&I[1]==0&&I[1].length!=2)throw new Error("invalid coordinates format");const C=M.split(".");if(C.length==2&&C[1]==0&&C[1].length!=2)throw new Error("invalid coordinates format");if(/^\d+$/.test(_)||/^\d+$/.test(M))throw new Error("degree only coordinate/s provided");return t=Number(Number(t).toFixed(e)),n=Number(Number(n).toFixed(e)),Object.freeze({verbatimCoordinates:E,verbatimLatitude:_,verbatimLongitude:M,decimalLatitude:t,decimalLongitude:n,decimalCoordinates:`${t},${n}`,originalFormat:a,closeEnough:mr,toCoordinateFormat:gr})}else throw new Error("coordinates pattern match failed")}function wt(i){if(!isNaN(i[0]))return!1;const e=[...i];if(e.shift(),e.length%2>0)return!1;const t=/^[-+]?\d+([\.,]\d+)?$/,n=/[eastsouthnorthwest]+/i,r=e.length/2;for(let u=0;u{e.decimalLatitude?i.push(e):i.push({...e,...vr})}),[...i,...br,...wr]}const Lr=Er();ei.formats=Lr.map(i=>i.verbatimCoordinates);const _r=ei;function Gi(i,e,t){const n=i.slice();return n[97]=e[t],n[99]=t,n}function Di(i){let e,t,n,r,u;return t=new Mi({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[3]),S(e,"class","svelte-bz0zu3")},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[78]),r=!0)},p(a,o){(!n||o[0]&8)&&S(e,"title",a[3])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function zi(i){let e,t;return e=new nr({}),{c(){Qe(e.$$.fragment)},m(n,r){qe(e,n,r),t=!0},i(n){t||(re(e.$$.fragment,n),t=!0)},o(n){fe(e.$$.fragment,n),t=!1},d(n){Fe(e,n)}}}function Ui(i){let e,t,n,r,u;return t=new ur({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[10]),S(e,"class","svelte-bz0zu3"),Ie(e,"active",i[0])},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[79]),r=!0)},p(a,o){(!n||o[0]&1024)&&S(e,"title",a[10]),(!n||o[0]&1)&&Ie(e,"active",a[0])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function Sr(i){let e,t=[],n=new Map,r,u,a,o=Ti(i[13]);const g=c=>c[97].id+(c[97].address?","+c[97].address:"");for(let c=0;c{B=null}),vt()):B?(B.p(d,v),v[0]&1048576&&re(B,1)):(B=Di(d),B.c(),re(B,1),B.m(c,E)),d[20]?z?v[0]&1048576&&re(z,1):(z=zi(),z.c(),re(z,1),z.m(c,null)):z&&(yt(),fe(z,1,1,()=>{z=null}),vt()),(!O||v[0]&2)&&Ie(c,"displayable",d[1]!==""),d[6]==="button"?W?(W.p(d,v),v[0]&64&&re(W,1)):(W=Ui(d),W.c(),re(W,1),W.m(n,M)):W&&(yt(),fe(W,1,1,()=>{W=null}),vt()),l&&l.p&&(!O||v[2]&128)&&Tn(l,s,d,d[69],O?xn(s,d[69],v,null):Mn(d[69]),null);let p=k;k=h(d),k===p?~k&&m[k].p(d,v):(I&&(yt(),fe(m[p],1,1,()=>{m[p]=null}),vt()),~k?(I=m[k],I?I.p(d,v):(I=m[k]=f[k](d),I.c()),re(I,1),I.m(t,null)):I=null),(!O||v[0]&4&&C!==(C=Pt(d[2])+" svelte-bz0zu3"))&&S(t,"class",C),(!O||v[0]&38)&&Ie(t,"can-collapse",d[5]&&d[1]==="")},i(d){O||(re(P),re(u.$$.fragment,d),re(B),re(z),re(W),re(l,d),re(I),O=!0)},o(d){fe(P),fe(u.$$.fragment,d),fe(B),fe(z),fe(W),fe(l,d),fe(I),O=!1},d(d){d&&($(e),$(t)),Fe(u),i[72](null),B&&B.d(),z&&z.d(),W&&W.d(),l&&l.d(d),~k&&m[k].d(),x=!1,Ue(N)}}}function Nr(i,e,t){let n,r,u,{$$slots:a={},$$scope:o}=e;const g={continental_marine:4,country:4,major_landform:8,region:5,subregion:6,county:7,joint_municipality:8,joint_submunicipality:9,municipality:10,municipal_district:11,locality:12,neighbourhood:13,place:14,postal_code:14,road:16,poi:17,address:18,"poi.peak":15,"poi.shop":18,"poi.cafe":18,"poi.restaurant":18,"poi.aerodrome":13};let{class:c=void 0}=e,{apiKey:E=void 0}=e,{bbox:_=void 0}=e,{clearButtonTitle:M="clear"}=e,{clearOnBlur:R=!1}=e,{clearListOnPick:k=!1}=e,{keepListOpen:I=!1}=e,{collapsed:C=!1}=e,{country:O=void 0}=e,{debounceSearch:x=200}=e,{enableReverse:N="never"}=e,{errorMessage:P="Something went wrong…"}=e,{filter:B=()=>!0}=e,{flyTo:z=!0}=e,{fuzzyMatch:W=!0}=e,{language:s=void 0}=e,{limit:l=void 0}=e;const f=41415112612;let{reverseGeocodingLimit:m=f}=e,{mapController:h=void 0}=e,{minLength:d=2}=e,{noResultsMessage:v="Oops! Looks like you're trying to predict something that's not quite right. We can't seem to find what you're looking for. Maybe try double-checking your spelling or try a different search term. Keep on typing - we'll do our best to get you where you need to go!"}=e,{placeholder:p="Search"}=e,{proximity:y=[{type:"server-geolocation"}]}=e,{reverseActive:b=N==="always"}=e,{reverseButtonTitle:w="toggle reverse geocoding"}=e,{searchValue:T=""}=e,{pickedResultStyle:G="full-geometry"}=e,{showPlaceType:D="if-needed"}=e,{showResultsWhileTyping:H=!0}=e,{selectFirst:Q=!0}=e,{flyToSelected:se=!1}=e,{markerOnSelected:Z=!0}=e,{types:K=void 0}=e;const de=[];let{reverseGeocodingTypes:He=de}=e,{exhaustiveReverseGeocoding:st=!1}=e,{excludeTypes:ot=!1}=e;const Le=void 0;let{reverseGeocodingExcludeTypes:We=Le}=e,{zoom:pe=g}=e,{apiUrl:ge="https://api.maptiler.com/geocoding"}=e,{fetchParameters:ie={}}=e,{iconsBaseUrl:hn="https://cdn.maptiler.com/maptiler-geocoding-control/v2.1.7/icons/"}=e,{adjustUrlQuery:ui=()=>{}}=e,{adjustUrl:ai=()=>{}}=e;function gs(L){Pe.focus(L)}function ms(){Pe.blur()}function dn(L,le=!0,ae=!1){t(1,T=L),le?(t(15,X=-1),mn()):(pn(void 0,!ae,ae),setTimeout(()=>{Pe.focus(),Pe.select()}))}function ps(){t(13,F=void 0),t(14,U=void 0),t(15,X=-1)}function ys(){t(64,ce=[]),t(14,U=void 0)}let F,ce,U,gn="",Pe,X=-1,Ge,Zt=[],lt,ct,ht,fi,Ve=!1;const vs=new Set,tt=_i();Rn(()=>{h&&(h.setEventHandler(void 0),h.indicateReverse(!1),h.setSelectedMarker(-1),h.setFeatures(void 0,void 0,!1))});function mn(L){if(t(17,Ve=!1),ct&&(clearTimeout(ct),ct=void 0),X>-1&&F)t(14,U=F[X]),t(1,T=U.place_type[0]==="reverse"?U.place_name:U.place_name.replace(/,.*/,"")),t(19,Ge=void 0),t(64,ce=void 0),t(15,X=-1);else if(T){const le=L||!ci(T);hi(T,{exact:!0}).then(()=>{t(64,ce=F),t(14,U=void 0),le&&bs()}).catch(ae=>t(19,Ge=ae))}}function ci(L){try{return _r(L,6)}catch{return!1}}async function hi(L,{byId:le=!1,exact:ae=!1}={}){var Se,De,it;t(19,Ge=void 0),lt==null||lt.abort();const _e=new AbortController;t(20,lt=_e);try{const J=ci(L),Mt=new URL(ge+"/"+encodeURIComponent(J?J.decimalLongitude+","+J.decimalLatitude:L)+".json"),Ne=Mt.searchParams;s!==void 0&&Ne.set("language",Array.isArray(s)?s.join(","):s??"");const[mi]=(h==null?void 0:h.getCenterAndZoom())??[];let ze=(Se=!J||He===de?K:He)==null?void 0:Se.map(ve=>typeof ve=="string"?ve:mi===void 0||(ve[0]??0)<=mi&&mi<(ve[1]??1/0)?ve[2]:void 0).filter(ve=>ve!==void 0);ze&&(ze=[...new Set(ze)],Ne.set("types",ze.join(",")));const vn=!J||We===Le?ot:We;if(vn&&Ne.set("excludeTypes",String(vn)),_&&Ne.set("bbox",_.map(ve=>ve.toFixed(6)).join(",")),O&&Ne.set("country",Array.isArray(O)?O.join(","):O),!le&&!J){const ve=await hr(h,y,_e);ve&&Ne.set("proximity",ve),(ae||!H)&&Ne.set("autocomplete","false"),Ne.set("fuzzyMatch",String(W))}const Ct=m===f?l:m;Ct!==void 0&&Ct>1&&(ze==null?void 0:ze.length)!==1&&console.warn("For reverse geocoding when limit > 1 then types must contain single value."),J?(Ct===1||Ct!==void 0&&(st||(ze==null?void 0:ze.length)===1))&&Ne.set("limit",String(Ct)):l!==void 0&&Ne.set("limit",String(l)),E&&Ne.set("key",E),ui(Ne),ai(Mt);const Bs=Mt.searchParams.get("types")===""&&Mt.searchParams.get("excludeTypes")!=="true",Ht=Mt.toString();if(Ht===gn){le?(k&&t(13,F=void 0),t(14,U=Zt[0])):(t(13,F=Zt),((De=F[X])==null?void 0:De.id)!==(r==null?void 0:r.id)&&t(15,X=-1));return}gn=Ht;let Nt;if(Bs)Nt={type:"FeatureCollection",features:[]};else{const ve=await fetch(Ht,{signal:_e.signal,...ie});if(!ve.ok)throw new Error(await ve.text());Nt=await ve.json()}tt("response",{url:Ht,featureCollection:Nt}),le?(k&&t(13,F=void 0),t(14,U=Nt.features[0]),Zt=[U]):(t(13,F=Nt.features.filter(B)),J&&F.unshift({type:"Feature",properties:{},id:"reverse_"+J.decimalLongitude+"_"+J.decimalLatitude,text:J.decimalLatitude+", "+J.decimalLongitude,place_name:J.decimalLatitude+", "+J.decimalLongitude,place_type:["reverse"],center:[J.decimalLongitude,J.decimalLatitude],bbox:[J.decimalLongitude,J.decimalLatitude,J.decimalLongitude,J.decimalLatitude],geometry:{type:"Point",coordinates:[J.decimalLongitude,J.decimalLatitude]}}),Zt=F,((it=F[X])==null?void 0:it.id)!==(r==null?void 0:r.id)&&t(15,X=-1),J&&Pe.focus())}catch(J){if(J&&typeof J=="object"&&"name"in J&&J.name==="AbortError")return;throw J}finally{_e===lt&&t(20,lt=void 0)}}function bs(){var _e;if(!(ce!=null&&ce.length)||!z)return;const L=[180,90,-180,-90],le=!ce.some(Se=>!Se.matching_text);let ae;for(const Se of ce){const De=Tt(Se);if(ae=ae===void 0?De:De===void 0?ae:Math.max(ae,De),le||!Se.matching_text)for(const it of[0,1,2,3])L[it]=Math[it<2?"min":"max"](L[it],((_e=Se.bbox)==null?void 0:_e[it])??Se.center[it%2])}h&&ce.length>0&&(U&&L[0]===L[2]&&L[1]===L[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(L),50,ae))}function di(){!U||!h||(!U.bbox||U.bbox[0]===U.bbox[2]&&U.bbox[1]===U.bbox[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(U.bbox),50,Tt(U)))}function Tt(L){var ae;if(!L.bbox||L.bbox[0]!==L.bbox[2]&&L.bbox[1]!==L.bbox[3])return;const le=L.id.replace(/\..*/,"");return(Array.isArray((ae=L.properties)==null?void 0:ae.categories)?L.properties.categories.reduce((_e,Se)=>{const De=pe[le+"."+Se];return _e===void 0?De:De===void 0?_e:Math.max(_e,De)},void 0):void 0)??pe[le]}function ws(L){t(0,b=N==="always"),t(13,F=void 0),t(14,U=void 0),t(15,X=-1),dn(L[1].toFixed(6)+", "+cr(L[0],[-180,180],!0).toFixed(6),!1,!0)}function Es(L){if(!F)return;let le=L.key==="ArrowDown"?1:L.key==="ArrowUp"?-1:0;le&&(Pe.focus(),t(17,Ve=!0),L.preventDefault(),U&&X===-1&&t(15,X=F.findIndex(ae=>ae.id===(U==null?void 0:U.id))),X===(U||Q?0:-1)&&le===-1&&t(15,X=F.length),t(15,X+=le),X>=F.length&&t(15,X=-1),X<0&&(U||Q)&&t(15,X=0))}function pn(L,le=!0,ae=!1){if(t(19,Ge=void 0),t(14,U=void 0),t(17,Ve=!0),H||ae){if(ct&&clearTimeout(ct),T.length{hi(_e).catch(Se=>t(19,Ge=Se))},le?x:0)}else t(13,F=void 0),t(19,Ge=void 0)}function gi(L){U&&(U==null?void 0:U.id)===(L==null?void 0:L.id)?di():(t(14,U=L),t(1,T=L.place_name))}function yn(L){t(15,X=L)}function Ls(){(!Q||U)&&t(15,X=-1),se&&di()}const _s=()=>Pe.focus();function Ss(L){Yt[L?"unshift":"push"](()=>{Pe=L,t(18,Pe)})}function xs(){T=this.value,t(1,T),t(17,Ve),t(31,R),t(16,ht)}const Ts=()=>t(17,Ve=!0),Ms=()=>t(17,Ve=!1),Cs=()=>t(17,Ve=!0),Ns=()=>t(14,U=void 0),ks=()=>{t(1,T=""),t(14,U=void 0),Pe.focus()},Os=()=>t(0,b=!b),Rs=()=>t(19,Ge=void 0),Ps=L=>yn(L),Is=L=>gi(L),As=()=>{};return i.$$set=L=>{"class"in L&&t(2,c=L.class),"apiKey"in L&&t(29,E=L.apiKey),"bbox"in L&&t(30,_=L.bbox),"clearButtonTitle"in L&&t(3,M=L.clearButtonTitle),"clearOnBlur"in L&&t(31,R=L.clearOnBlur),"clearListOnPick"in L&&t(32,k=L.clearListOnPick),"keepListOpen"in L&&t(4,I=L.keepListOpen),"collapsed"in L&&t(5,C=L.collapsed),"country"in L&&t(33,O=L.country),"debounceSearch"in L&&t(34,x=L.debounceSearch),"enableReverse"in L&&t(6,N=L.enableReverse),"errorMessage"in L&&t(7,P=L.errorMessage),"filter"in L&&t(35,B=L.filter),"flyTo"in L&&t(36,z=L.flyTo),"fuzzyMatch"in L&&t(37,W=L.fuzzyMatch),"language"in L&&t(38,s=L.language),"limit"in L&&t(39,l=L.limit),"reverseGeocodingLimit"in L&&t(40,m=L.reverseGeocodingLimit),"mapController"in L&&t(41,h=L.mapController),"minLength"in L&&t(42,d=L.minLength),"noResultsMessage"in L&&t(8,v=L.noResultsMessage),"placeholder"in L&&t(9,p=L.placeholder),"proximity"in L&&t(43,y=L.proximity),"reverseActive"in L&&t(0,b=L.reverseActive),"reverseButtonTitle"in L&&t(10,w=L.reverseButtonTitle),"searchValue"in L&&t(1,T=L.searchValue),"pickedResultStyle"in L&&t(44,G=L.pickedResultStyle),"showPlaceType"in L&&t(11,D=L.showPlaceType),"showResultsWhileTyping"in L&&t(45,H=L.showResultsWhileTyping),"selectFirst"in L&&t(46,Q=L.selectFirst),"flyToSelected"in L&&t(47,se=L.flyToSelected),"markerOnSelected"in L&&t(48,Z=L.markerOnSelected),"types"in L&&t(49,K=L.types),"reverseGeocodingTypes"in L&&t(50,He=L.reverseGeocodingTypes),"exhaustiveReverseGeocoding"in L&&t(51,st=L.exhaustiveReverseGeocoding),"excludeTypes"in L&&t(52,ot=L.excludeTypes),"reverseGeocodingExcludeTypes"in L&&t(53,We=L.reverseGeocodingExcludeTypes),"zoom"in L&&t(54,pe=L.zoom),"apiUrl"in L&&t(55,ge=L.apiUrl),"fetchParameters"in L&&t(56,ie=L.fetchParameters),"iconsBaseUrl"in L&&t(12,hn=L.iconsBaseUrl),"adjustUrlQuery"in L&&t(57,ui=L.adjustUrlQuery),"adjustUrl"in L&&t(58,ai=L.adjustUrl),"$$scope"in L&&t(69,o=L.$$scope)},i.$$.update=()=>{if(i.$$.dirty[0]&64&&t(0,b=N==="always"),i.$$.dirty[0]&16384|i.$$.dirty[1]&8192&&G!=="marker-only"&&U&&!U.address&&U.geometry.type==="Point"&&U.place_type[0]!=="reverse"&&hi(U.id,{byId:!0}).catch(L=>t(19,Ge=L)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1058|i.$$.dirty[2]&8&&(h&&U&&U.id!==fi&&z&&(di(),k&&t(13,F=void 0),t(64,ce=void 0),t(15,X=-1)),t(65,fi=U==null?void 0:U.id)),i.$$.dirty[0]&196608|i.$$.dirty[1]&1&&setTimeout(()=>{t(16,ht=Ve),R&&!ht&&t(1,T="")}),i.$$.dirty[0]&8194|i.$$.dirty[1]&2048&&T.length{switch(L.type){case"mapClick":b&&ws(L.coordinates);break;case"markerClick":{const le=F==null?void 0:F.find(ae=>ae.id===L.id);le&&gi(le)}break;case"markerMouseEnter":ce&&t(15,X=ht?(F==null?void 0:F.findIndex(le=>le.id===L.id))??-1:-1);break;case"markerMouseLeave":ce&&t(15,X=-1);break}}),i.$$.dirty[0]&40960&&t(66,r=F==null?void 0:F[X]),i.$$.dirty[1]&66592|i.$$.dirty[2]&16&&h&&r&&z&&se&&h.flyTo(r.center,Tt(r)),i.$$.dirty[1]&8192&&t(68,n=G==="full-geometry-including-polygon-center-marker"),i.$$.dirty[1]&132096|i.$$.dirty[2]&64&&(Z||h==null||h.setFeatures(void 0,void 0,n)),i.$$.dirty[0]&16384|i.$$.dirty[1]&132096|i.$$.dirty[2]&84&&h&&Z&&!ce&&(h.setFeatures(r?[r]:void 0,U,n),h.setSelectedMarker(r?0:-1)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1024|i.$$.dirty[2]&68&&h&&h.setFeatures(ce,U,n),i.$$.dirty[0]&32768|i.$$.dirty[1]&1024|i.$$.dirty[2]&4&&ce&&h&&h.setSelectedMarker(X),i.$$.dirty[0]&2|i.$$.dirty[1]&1024&&h){const L=ci(T);h.setReverseMarker(L?[L.decimalLongitude,L.decimalLatitude]:void 0)}i.$$.dirty[2]&16&&tt("select",{feature:r}),i.$$.dirty[0]&16384&&tt("pick",{feature:U}),i.$$.dirty[0]&73744&&t(67,u=!!(F!=null&&F.length)&&(ht||I)),i.$$.dirty[2]&32&&tt("optionsvisibilitychange",{optionsVisible:u}),i.$$.dirty[0]&8192&&tt("featureslisted",{features:F}),i.$$.dirty[2]&4&&tt("featuresmarked",{features:ce}),i.$$.dirty[0]&1&&tt("reversetoggle",{reverse:b}),i.$$.dirty[0]&2&&tt("querychange",{query:T}),i.$$.dirty[0]&1|i.$$.dirty[1]&1024&&h&&h.indicateReverse(b)},[b,T,c,M,I,C,N,P,v,p,w,D,hn,F,U,X,ht,Ve,Pe,Ge,lt,vs,mn,Es,pn,gi,yn,Ls,g,E,_,R,k,O,x,B,z,W,s,l,m,h,d,y,G,H,Q,se,Z,K,He,st,ot,We,pe,ge,ie,ui,ai,gs,ms,dn,ps,ys,ce,fi,r,u,n,o,a,_s,Ss,xs,Ts,Ms,Cs,Ns,ks,Os,Rs,Ps,Is,As]}let kr=class extends Je{constructor(e){super(),Xe(this,e,Nr,Cr,Ke,{ZOOM_DEFAULTS:28,class:2,apiKey:29,bbox:30,clearButtonTitle:3,clearOnBlur:31,clearListOnPick:32,keepListOpen:4,collapsed:5,country:33,debounceSearch:34,enableReverse:6,errorMessage:7,filter:35,flyTo:36,fuzzyMatch:37,language:38,limit:39,reverseGeocodingLimit:40,mapController:41,minLength:42,noResultsMessage:8,placeholder:9,proximity:43,reverseActive:0,reverseButtonTitle:10,searchValue:1,pickedResultStyle:44,showPlaceType:11,showResultsWhileTyping:45,selectFirst:46,flyToSelected:47,markerOnSelected:48,types:49,reverseGeocodingTypes:50,exhaustiveReverseGeocoding:51,excludeTypes:52,reverseGeocodingExcludeTypes:53,zoom:54,apiUrl:55,fetchParameters:56,iconsBaseUrl:12,adjustUrlQuery:57,adjustUrl:58,focus:59,blur:60,setQuery:61,clearList:62,clearMap:63},null,[-1,-1,-1,-1])}get ZOOM_DEFAULTS(){return this.$$.ctx[28]}get focus(){return this.$$.ctx[59]}get blur(){return this.$$.ctx[60]}get setQuery(){return this.$$.ctx[61]}get clearList(){return this.$$.ctx[62]}get clearMap(){return this.$$.ctx[63]}};function Et(i,e,t={}){const n={type:"Feature"};return(t.id===0||t.id)&&(n.id=t.id),t.bbox&&(n.bbox=t.bbox),n.properties=e||{},n.geometry=i,n}function ti(i,e,t={}){for(const r of i){if(r.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(r[r.length-1].length!==r[0].length)throw new Error("First and last Position are not equivalent.");for(let u=0;u_?w.c=w.e=null:s.e=10;v/=10,d++);d>_?w.c=w.e=null:(w.e=d,w.c=[s]);return}b=String(s)}else{if(!Or.test(b=String(s)))return n(w,b,p);w.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(v=b.search(/e/i))>0?(d<0&&(d=v),d+=+b.slice(v+1),b=b.substring(0,v)):d<0&&(d=b.length)}else{if(oe(l,2,C.length,"Base"),l==10&&O)return w=new x(s),z(w,a+w.e+1,o);if(b=String(s),p=typeof s=="number"){if(s*0!=0)return n(w,b,p,l);if(w.s=1/s<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(ji+s)}else w.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(f=C.slice(0,l),d=v=0,y=b.length;vd){d=y;continue}}else if(!h&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){h=!0,v=-1,d=0;continue}return n(w,String(s),p,l)}p=!1,b=t(b,l,10,w.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(v=0;b.charCodeAt(v)===48;v++);for(y=b.length;b.charCodeAt(--y)===48;);if(b=b.slice(v,++y)){if(y-=v,p&&x.DEBUG&&y>15&&(s>Zi||s!==Te(s)))throw Error(ji+w.s*s);if((d=d-v-1)>_)w.c=w.e=null;else if(d=-1e9&&h<=Ee&&h===Te(h)){if(m[0]===0){if(h===0&&m.length===1)return!0;break e}if(l=(h+1)%q,l<1&&(l+=q),String(m[0]).length==l){for(l=0;l=Re||f!==Te(f))break e;if(f!==0)return!0}}}else if(m===null&&h===null&&(d===null||d===1||d===-1))return!0;throw Error(be+"Invalid BigNumber: "+s)},x.maximum=x.max=function(){return P(arguments,-1)},x.minimum=x.min=function(){return P(arguments,1)},x.random=function(){var s=9007199254740992,l=Math.random()*s&2097151?function(){return Te(Math.random()*s)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(f){var m,h,d,v,p,y=0,b=[],w=new x(u);if(f==null?f=a:oe(f,0,Ee),v=ii(f/q),M)if(crypto.getRandomValues){for(m=crypto.getRandomValues(new Uint32Array(v*=2));y>>11),p>=9e15?(h=crypto.getRandomValues(new Uint32Array(2)),m[y]=h[0],m[y+1]=h[1]):(b.push(p%1e14),y+=2);y=v/2}else if(crypto.randomBytes){for(m=crypto.randomBytes(v*=7);y=9e15?crypto.randomBytes(7).copy(m,y):(b.push(p%1e14),y+=7);y=v/7}else throw M=!1,Error(be+"crypto unavailable");if(!M)for(;y=10;p/=10,y++);yh-1&&(p[v+1]==null&&(p[v+1]=0),p[v+1]+=p[v]/h|0,p[v]%=h)}return p.reverse()}return function(f,m,h,d,v){var p,y,b,w,T,G,D,H,Q=f.indexOf("."),se=a,Z=o;for(Q>=0&&(w=k,k=0,f=f.replace(".",""),H=new x(m),G=H.pow(f.length-Q),k=w,H.c=l(je(Ce(G.c),G.e,"0"),10,h,s),H.e=H.c.length),D=l(f,m,h,v?(p=C,s):(p=s,C)),b=w=D.length;D[--w]==0;D.pop());if(!D[0])return p.charAt(0);if(Q<0?--b:(G.c=D,G.e=b,G.s=d,G=e(G,H,se,Z,h),D=G.c,T=G.r,b=G.e),y=b+se+1,Q=D[y],w=h/2,T=T||y<0||D[y+1]!=null,T=Z<4?(Q!=null||T)&&(Z==0||Z==(G.s<0?3:2)):Q>w||Q==w&&(Z==4||T||Z==6&&D[y-1]&1||Z==(G.s<0?8:7)),y<1||!D[0])f=T?je(p.charAt(1),-se,p.charAt(0)):p.charAt(0);else{if(D.length=y,T)for(--h;++D[--y]>h;)D[y]=0,y||(++b,D=[1].concat(D));for(w=D.length;!D[--w];);for(Q=0,f="";Q<=w;f+=p.charAt(D[Q++]));f=je(f,b,p.charAt(0))}return f}}(),e=function(){function s(m,h,d){var v,p,y,b,w=0,T=m.length,G=h%$e,D=h/$e|0;for(m=m.slice();T--;)y=m[T]%$e,b=m[T]/$e|0,v=D*y+b*G,p=G*y+v%$e*$e+w,w=(p/d|0)+(v/$e|0)+D*b,m[T]=p%d;return w&&(m=[w].concat(m)),m}function l(m,h,d,v){var p,y;if(d!=v)y=d>v?1:-1;else for(p=y=0;ph[p]?1:-1;break}return y}function f(m,h,d,v){for(var p=0;d--;)m[d]-=p,p=m[d]1;m.splice(0,1));}return function(m,h,d,v,p){var y,b,w,T,G,D,H,Q,se,Z,K,de,He,st,ot,Le,We,pe=m.s==h.s?1:-1,ge=m.c,ie=h.c;if(!ge||!ge[0]||!ie||!ie[0])return new x(!m.s||!h.s||(ge?ie&&ge[0]==ie[0]:!ie)?NaN:ge&&ge[0]==0||!ie?pe*0:pe/0);for(Q=new x(pe),se=Q.c=[],b=m.e-h.e,pe=d+b+1,p||(p=Re,b=Me(m.e/q)-Me(h.e/q),pe=pe/q|0),w=0;ie[w]==(ge[w]||0);w++);if(ie[w]>(ge[w]||0)&&b--,pe<0)se.push(1),T=!0;else{for(st=ge.length,Le=ie.length,w=0,pe+=2,G=Te(p/(ie[0]+1)),G>1&&(ie=s(ie,G,p),ge=s(ge,G,p),Le=ie.length,st=ge.length),He=Le,Z=ge.slice(0,Le),K=Z.length;K=p/2&&ot++;do{if(G=0,y=l(ie,Z,Le,K),y<0){if(de=Z[0],Le!=K&&(de=de*p+(Z[1]||0)),G=Te(de/ot),G>1)for(G>=p&&(G=p-1),D=s(ie,G,p),H=D.length,K=Z.length;l(D,Z,H,K)==1;)G--,f(D,Le=10;pe/=10,w++);z(Q,d+(Q.e=w+b*q-1)+1,v,T)}else Q.e=b,Q.r=+T;return Q}}();function N(s,l,f,m){var h,d,v,p,y;if(f==null?f=o:oe(f,0,8),!s.c)return s.toString();if(h=s.c[0],v=s.e,l==null)y=Ce(s.c),y=m==1||m==2&&(v<=g||v>=c)?Gt(y,v):je(y,v,"0");else if(s=z(new x(s),l,f),d=s.e,y=Ce(s.c),p=y.length,m==1||m==2&&(l<=d||d<=g)){for(;pp){if(--l>0)for(y+=".";l--;y+="0");}else if(l+=d-p,l>0)for(d+1==p&&(y+=".");l--;y+="0");return s.s<0&&h?"-"+y:y}function P(s,l){for(var f,m,h=1,d=new x(s[0]);h=10;h/=10,m++);return(f=m+f*q-1)>_?s.c=s.e=null:f=10;p/=10,h++);if(d=l-h,d<0)d+=q,v=l,y=T[b=0],w=Te(y/G[h-v-1]%10);else if(b=ii((d+1)/q),b>=T.length)if(m){for(;T.length<=b;T.push(0));y=w=0,h=1,d%=q,v=d-q+1}else break e;else{for(y=p=T[b],h=1;p>=10;p/=10,h++);d%=q,v=d-q+h,w=v<0?0:Te(y/G[h-v-1]%10)}if(m=m||l<0||T[b+1]!=null||(v<0?y:y%G[h-v-1]),m=f<4?(w||m)&&(f==0||f==(s.s<0?3:2)):w>5||w==5&&(f==4||m||f==6&&(d>0?v>0?y/G[h-v]:0:T[b-1])%10&1||f==(s.s<0?8:7)),l<1||!T[0])return T.length=0,m?(l-=s.e+1,T[0]=G[(q-l%q)%q],s.e=-l||0):T[0]=s.e=0,s;if(d==0?(T.length=b,p=1,b--):(T.length=b+1,p=G[q-d],T[b]=v>0?Te(y/G[h-v]%G[v])*p:0),m)for(;;)if(b==0){for(d=1,v=T[0];v>=10;v/=10,d++);for(v=T[0]+=p,p=1;v>=10;v/=10,p++);d!=p&&(s.e++,T[0]==Re&&(T[0]=1));break}else{if(T[b]+=p,T[b]!=Re)break;T[b--]=0,p=1}for(d=T.length;T[--d]===0;T.pop());}s.e>_?s.c=s.e=null:s.e=c?Gt(l,f):je(l,f,"0"),s.s<0?"-"+l:l)}return r.absoluteValue=r.abs=function(){var s=new x(this);return s.s<0&&(s.s=1),s},r.comparedTo=function(s,l){return rt(this,new x(s,l))},r.decimalPlaces=r.dp=function(s,l){var f,m,h,d=this;if(s!=null)return oe(s,0,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s+d.e+1,l);if(!(f=d.c))return null;if(m=((h=f.length-1)-Me(this.e/q))*q,h=f[h])for(;h%10==0;h/=10,m--);return m<0&&(m=0),m},r.dividedBy=r.div=function(s,l){return e(this,new x(s,l),a,o)},r.dividedToIntegerBy=r.idiv=function(s,l){return e(this,new x(s,l),0,1)},r.exponentiatedBy=r.pow=function(s,l){var f,m,h,d,v,p,y,b,w,T=this;if(s=new x(s),s.c&&!s.isInteger())throw Error(be+"Exponent not an integer: "+W(s));if(l!=null&&(l=new x(l)),p=s.e>14,!T.c||!T.c[0]||T.c[0]==1&&!T.e&&T.c.length==1||!s.c||!s.c[0])return w=new x(Math.pow(+W(T),p?s.s*(2-Wt(s)):+W(s))),l?w.mod(l):w;if(y=s.s<0,l){if(l.c?!l.c[0]:!l.s)return new x(NaN);m=!y&&T.isInteger()&&l.isInteger(),m&&(T=T.mod(l))}else{if(s.e>9&&(T.e>0||T.e<-1||(T.e==0?T.c[0]>1||p&&T.c[1]>=24e7:T.c[0]<8e13||p&&T.c[0]<=9999975e7)))return d=T.s<0&&Wt(s)?-0:0,T.e>-1&&(d=1/d),new x(y?1/d:d);k&&(d=ii(k/q+2))}for(p?(f=new x(.5),y&&(s.s=1),b=Wt(s)):(h=Math.abs(+W(s)),b=h%2),w=new x(u);;){if(b){if(w=w.times(T),!w.c)break;d?w.c.length>d&&(w.c.length=d):m&&(w=w.mod(l))}if(h){if(h=Te(h/2),h===0)break;b=h%2}else if(s=s.times(f),z(s,s.e+1,1),s.e>14)b=Wt(s);else{if(h=+W(s),h===0)break;b=h%2}T=T.times(T),d?T.c&&T.c.length>d&&(T.c.length=d):m&&(T=T.mod(l))}return m?w:(y&&(w=u.div(w)),l?w.mod(l):d?z(w,k,o,v):w)},r.integerValue=function(s){var l=new x(this);return s==null?s=o:oe(s,0,8),z(l,l.e+1,s)},r.isEqualTo=r.eq=function(s,l){return rt(this,new x(s,l))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(s,l){return rt(this,new x(s,l))>0},r.isGreaterThanOrEqualTo=r.gte=function(s,l){return(l=rt(this,new x(s,l)))===1||l===0},r.isInteger=function(){return!!this.c&&Me(this.e/q)>this.c.length-2},r.isLessThan=r.lt=function(s,l){return rt(this,new x(s,l))<0},r.isLessThanOrEqualTo=r.lte=function(s,l){return(l=rt(this,new x(s,l)))===-1||l===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(s,l){var f,m,h,d,v=this,p=v.s;if(s=new x(s,l),l=s.s,!p||!l)return new x(NaN);if(p!=l)return s.s=-l,v.plus(s);var y=v.e/q,b=s.e/q,w=v.c,T=s.c;if(!y||!b){if(!w||!T)return w?(s.s=-l,s):new x(T?v:NaN);if(!w[0]||!T[0])return T[0]?(s.s=-l,s):new x(w[0]?v:o==3?-0:0)}if(y=Me(y),b=Me(b),w=w.slice(),p=y-b){for((d=p<0)?(p=-p,h=w):(b=y,h=T),h.reverse(),l=p;l--;h.push(0));h.reverse()}else for(m=(d=(p=w.length)<(l=T.length))?p:l,p=l=0;l0)for(;l--;w[f++]=0);for(l=Re-1;m>p;){if(w[--m]=0;){for(f=0,G=de[h]%se,D=de[h]/se|0,v=y,d=h+v;d>h;)b=K[--v]%se,w=K[v]/se|0,p=D*b+w*G,b=G*b+p%se*se+H[d]+f,f=(b/Q|0)+(p/se|0)+D*w,H[d--]=b%Q;H[d]=f}return f?++m:H.splice(0,1),B(s,H,m)},r.negated=function(){var s=new x(this);return s.s=-s.s||null,s},r.plus=function(s,l){var f,m=this,h=m.s;if(s=new x(s,l),l=s.s,!h||!l)return new x(NaN);if(h!=l)return s.s=-l,m.minus(s);var d=m.e/q,v=s.e/q,p=m.c,y=s.c;if(!d||!v){if(!p||!y)return new x(h/0);if(!p[0]||!y[0])return y[0]?s:new x(p[0]?m:h*0)}if(d=Me(d),v=Me(v),p=p.slice(),h=d-v){for(h>0?(v=d,f=y):(h=-h,f=p),f.reverse();h--;f.push(0));f.reverse()}for(h=p.length,l=y.length,h-l<0&&(f=y,y=p,p=f,l=h),h=0;l;)h=(p[--l]=p[l]+y[l]+h)/Re|0,p[l]=Re===p[l]?0:p[l]%Re;return h&&(p=[h].concat(p),++v),B(s,p,v)},r.precision=r.sd=function(s,l){var f,m,h,d=this;if(s!=null&&s!==!!s)return oe(s,1,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s,l);if(!(f=d.c))return null;if(h=f.length-1,m=h*q+1,h=f[h]){for(;h%10==0;h/=10,m--);for(h=f[0];h>=10;h/=10,m++);}return s&&d.e+1>m&&(m=d.e+1),m},r.shiftedBy=function(s){return oe(s,-9007199254740991,Zi),this.times("1e"+s)},r.squareRoot=r.sqrt=function(){var s,l,f,m,h,d=this,v=d.c,p=d.s,y=d.e,b=a+4,w=new x("0.5");if(p!==1||!v||!v[0])return new x(!p||p<0&&(!v||v[0])?NaN:v?d:1/0);if(p=Math.sqrt(+W(d)),p==0||p==1/0?(l=Ce(v),(l.length+y)%2==0&&(l+="0"),p=Math.sqrt(+l),y=Me((y+1)/2)-(y<0||y%2),p==1/0?l="5e"+y:(l=p.toExponential(),l=l.slice(0,l.indexOf("e")+1)+y),f=new x(l)):f=new x(p+""),f.c[0]){for(y=f.e,p=y+b,p<3&&(p=0);;)if(h=f,f=w.times(h.plus(e(d,h,b,1))),Ce(h.c).slice(0,p)===(l=Ce(f.c)).slice(0,p))if(f.e0&&H>0){for(d=H%p||p,w=D.substr(0,d);d0&&(w+=b+D.slice(d)),G&&(w="-"+w)}m=T?w+(f.decimalSeparator||"")+((y=+f.fractionGroupSize)?T.replace(new RegExp("\\d{"+y+"}\\B","g"),"$&"+(f.fractionGroupSeparator||"")):T):w}return(f.prefix||"")+m+(f.suffix||"")},r.toFraction=function(s){var l,f,m,h,d,v,p,y,b,w,T,G,D=this,H=D.c;if(s!=null&&(p=new x(s),!p.isInteger()&&(p.c||p.s!==1)||p.lt(u)))throw Error(be+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+W(p));if(!H)return new x(D);for(l=new x(u),b=f=new x(u),m=y=new x(u),G=Ce(H),d=l.e=G.length-D.e-1,l.c[0]=ni[(v=d%q)<0?q+v:v],s=!s||p.comparedTo(l)>0?d>0?l:b:p,v=_,_=1/0,p=new x(G),y.c[0]=0;w=e(p,l,0,1),h=f.plus(w.times(m)),h.comparedTo(s)!=1;)f=m,m=h,b=y.plus(w.times(h=b)),y=h,l=p.minus(w.times(h=l)),p=h;return h=e(s.minus(f),m,0,1),y=y.plus(h.times(b)),f=f.plus(h.times(m)),y.s=b.s=D.s,d=d*2,T=e(b,m,d,o).minus(D).abs().comparedTo(e(y,f,d,o).minus(D).abs())<1?[b,m]:[y,f],_=v,T},r.toNumber=function(){return+W(this)},r.toPrecision=function(s,l){return s!=null&&oe(s,1,Ee),N(this,s,l,2)},r.toString=function(s){var l,f=this,m=f.s,h=f.e;return h===null?m?(l="Infinity",m<0&&(l="-"+l)):l="NaN":(s==null?l=h<=g||h>=c?Gt(Ce(f.c),h):je(Ce(f.c),h,"0"):s===10&&O?(f=z(new x(f),a+h+1,o),l=je(Ce(f.c),f.e,"0")):(oe(s,2,C.length,"Base"),l=t(je(Ce(f.c),h,"0"),10,s,m,!0)),m<0&&f.c[0]&&(l="-"+l)),l},r.valueOf=r.toJSON=function(){return W(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,i!=null&&x.set(i),x}function Me(i){var e=i|0;return i>0||i===e?e:e-1}function Ce(i){for(var e,t,n=1,r=i.length,u=i[0]+"";nc^t?1:-1;for(o=(g=r.length)<(c=u.length)?g:c,a=0;au[a]^t?1:-1;return g==c?0:g>c^t?1:-1}function oe(i,e,t,n){if(it||i!==Te(i))throw Error(be+(n||"Argument")+(typeof i=="number"?it?" out of range: ":" not an integer: ":" not a primitive number: ")+String(i))}function Wt(i){var e=i.c.length-1;return Me(i.e/q)==e&&i.c[e]%2!=0}function Gt(i,e){return(i.length>1?i.charAt(0)+"."+i.slice(1):i)+(e<0?"e":"e+")+e}function je(i,e,t){var n,r;if(e<0){for(r=t+".";++e;r+=t);i=r+i}else if(n=i.length,++e>n){for(r=t,e-=n;--e;r+=t);i+=r}else e0){let c=a.left;if(c==null||(g=o(c.key,i),g>0&&(a.left=c.right,c.right=a,a=c,c=a.left,c==null)))break;t==null?n=a:t.left=a,t=a,a=c}else if(g<0){let c=a.right;if(c==null||(g=o(c.key,i),g<0&&(a.right=c.left,c.left=a,a=c,c=a.right,c==null)))break;r==null?u=a:r.right=a,r=a,a=c}else break;return r!=null&&(r.right=a.left,a.left=u),t!=null&&(t.left=a.right,a.right=n),this.root!==a&&(this.root=a,this.splayCount++),g}splayMin(i){let e=i,t=e.left;for(;t!=null;){const n=t;e.left=n.right,n.right=e,e=n,t=e.left}return e}splayMax(i){let e=i,t=e.right;for(;t!=null;){const n=t;e.right=n.left,n.left=e,e=n,t=e.right}return e}_delete(i){if(this.root==null||this.splay(i)!=0)return null;let t=this.root;const n=t,r=t.left;if(this.size--,r==null)this.root=t.right;else{const u=t.right;t=this.splayMax(r),t.right=u,this.root=t}return this.modificationCount++,n}addNewRoot(i,e){this.size++,this.modificationCount++;const t=this.root;if(t==null){this.root=i;return}e<0?(i.left=t,i.right=t.right,t.right=null):(i.right=t,i.left=t.left,t.left=null),this.root=i}_first(){const i=this.root;return i==null?null:(this.root=this.splayMin(i),this.root)}_last(){const i=this.root;return i==null?null:(this.root=this.splayMax(i),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(i){return this.validKey(i)&&this.splay(i)==0}defaultCompare(){return(i,e)=>ie?1:0}wrap(){return{getRoot:()=>this.root,setRoot:i=>{this.root=i},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:i=>{this.splayCount=i},splay:i=>this.splay(i),has:i=>this.has(i)}}},Dt=class Ot extends Pr{constructor(t,n){super();A(this,"root",null);A(this,"compare");A(this,"validKey");A(this,fn,"[object Set]");this.compare=t??this.defaultCompare(),this.validKey=n??(r=>r!=null&&r!=null)}delete(t){return this.validKey(t)?this._delete(t)!=null:!1}deleteAll(t){for(const n of t)this.delete(n)}forEach(t){const n=this[Symbol.iterator]();let r;for(;r=n.next(),!r.done;)t(r.value,r.value,this)}add(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this}addAndReturn(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this.root.key}addAll(t){for(const n of t)this.add(n)}isEmpty(){return this.root==null}isNotEmpty(){return this.root!=null}single(){if(this.size==0)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(this.size==0)throw"Bad state: No element";return this._first().key}last(){if(this.size==0)throw"Bad state: No element";return this._last().key}lastBefore(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)<0)return this.root.key;let r=this.root.left;if(r==null)return null;let u=r.right;for(;u!=null;)r=u,u=r.right;return r.key}firstAfter(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)>0)return this.root.key;let r=this.root.right;if(r==null)return null;let u=r.left;for(;u!=null;)r=u,u=r.left;return r.key}retainAll(t){const n=new Ot(this.compare,this.validKey),r=this.modificationCount;for(const u of t){if(r!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(u)&&this.splay(u)==0&&n.add(this.root.key)}n.size!=this.size&&(this.root=n.root,this.size=n.size,this.modificationCount++)}lookup(t){return!this.validKey(t)||this.splay(t)!=0?null:this.root.key}intersection(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)&&n.add(r);return n}difference(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)||n.add(r);return n}union(t){const n=this.clone();return n.addAll(t),n}clone(){const t=new Ot(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(t){if(t==null)return null;function n(u,a){let o,g;do{if(o=u.left,g=u.right,o!=null){const c=new _t(o.key);a.left=c,n(o,c)}if(g!=null){const c=new _t(g.key);a.right=c,u=g,a=c}}while(g!=null)}const r=new _t(t.key);return n(t,r),r}toSet(){return this.clone()}entries(){return new Ar(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[(cn=Symbol.iterator,fn=Symbol.toStringTag,cn)](){return new Ir(this.wrap())}},Vi=class{constructor(i){A(this,"tree");A(this,"path",new Array);A(this,"modificationCount",null);A(this,"splayCount");this.tree=i,this.splayCount=i.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const i=this.path[this.path.length-1];return this.getValue(i)}rebuildPath(i){this.path.splice(0,this.path.length),this.tree.splay(i),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(i){for(;i!=null;)this.path.push(i),i=i.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(this.modificationCount==null){this.modificationCount=this.tree.getModificationCount();let t=this.tree.getRoot();for(;t!=null;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let i=this.path[this.path.length-1],e=i.right;if(e!=null){for(;e!=null;)this.path.push(e),e=e.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===i;)i=this.path.pop();return this.path.length>0}},Ir=class extends Vi{getValue(i){return i.key}},Ar=class extends Vi{getValue(i){return[i.key,i.key]}},Ki=i=>()=>i,ri=i=>{const e=i?(t,n)=>n.minus(t).abs().isLessThanOrEqualTo(i):Ki(!1);return(t,n)=>e(t,n)?0:t.comparedTo(n)};function Br(i){const e=i?(t,n,r,u,a)=>t.exponentiatedBy(2).isLessThanOrEqualTo(u.minus(n).exponentiatedBy(2).plus(a.minus(r).exponentiatedBy(2)).times(i)):Ki(!1);return(t,n,r)=>{const u=t.x,a=t.y,o=r.x,g=r.y,c=a.minus(g).times(n.x.minus(o)).minus(u.minus(o).times(n.y.minus(g)));return e(c,u,a,o,g)?0:c.comparedTo(0)}}var Wr=i=>i,Gr=i=>{if(i){const e=new Dt(ri(i)),t=new Dt(ri(i)),n=(u,a)=>a.addAndReturn(u),r=u=>({x:n(u.x,e),y:n(u.y,t)});return r({x:new Ae(0),y:new Ae(0)}),r}return Wr},si=i=>({set:e=>{Ze=si(e)},reset:()=>si(i),compare:ri(i),snap:Gr(i),orient:Br(i)}),Ze=si(),St=(i,e)=>i.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(i.ur.x)&&i.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(i.ur.y),oi=(i,e)=>{if(e.ur.x.isLessThan(i.ll.x)||i.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(i.ll.y)||i.ur.y.isLessThan(e.ll.y))return null;const t=i.ll.x.isLessThan(e.ll.x)?e.ll.x:i.ll.x,n=i.ur.x.isLessThan(e.ur.x)?i.ur.x:e.ur.x,r=i.ll.y.isLessThan(e.ll.y)?e.ll.y:i.ll.y,u=i.ur.y.isLessThan(e.ur.y)?i.ur.y:e.ur.y;return{ll:{x:t,y:r},ur:{x:n,y:u}}},zt=(i,e)=>i.x.times(e.y).minus(i.y.times(e.x)),Yi=(i,e)=>i.x.times(e.x).plus(i.y.times(e.y)),Ut=i=>Yi(i,i).sqrt(),Dr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return zt(r,n).div(Ut(r)).div(Ut(n))},zr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return Yi(r,n).div(Ut(r)).div(Ut(n))},Qi=(i,e,t)=>e.y.isZero()?null:{x:i.x.plus(e.x.div(e.y).times(t.minus(i.y))),y:t},Xi=(i,e,t)=>e.x.isZero()?null:{x:t,y:i.y.plus(e.y.div(e.x).times(t.minus(i.x)))},Ur=(i,e,t,n)=>{if(e.x.isZero())return Xi(t,n,i.x);if(n.x.isZero())return Xi(i,e,t.x);if(e.y.isZero())return Qi(t,n,i.y);if(n.y.isZero())return Qi(i,e,t.y);const r=zt(e,n);if(r.isZero())return null;const u={x:t.x.minus(i.x),y:t.y.minus(i.y)},a=zt(u,e).div(r),o=zt(u,n).div(r),g=i.x.plus(o.times(e.x)),c=t.x.plus(a.times(n.x)),E=i.y.plus(o.times(e.y)),_=t.y.plus(a.times(n.y)),M=g.plus(c).div(2),R=E.plus(_).div(2);return{x:M,y:R}},Be=class En{constructor(e,t){A(this,"point");A(this,"isLeft");A(this,"segment");A(this,"otherSE");A(this,"consumedBy");e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}static compare(e,t){const n=En.comparePoints(e.point,t.point);return n!==0?n:(e.point!==t.point&&e.link(t),e.isLeft!==t.isLeft?e.isLeft?1:-1:Ft.compare(e.segment,t.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let n=0,r=t.length;n{const u=r.otherSE;t.set(r,{sine:Dr(this.point,e.point,u.point),cosine:zr(this.point,e.point,u.point)})};return(r,u)=>{t.has(r)||n(r),t.has(u)||n(u);const{sine:a,cosine:o}=t.get(r),{sine:g,cosine:c}=t.get(u);return a.isGreaterThanOrEqualTo(0)&&g.isGreaterThanOrEqualTo(0)?o.isLessThan(c)?1:o.isGreaterThan(c)?-1:0:a.isLessThan(0)&&g.isLessThan(0)?o.isLessThan(c)?-1:o.isGreaterThan(c)?1:0:g.isLessThan(a)?-1:g.isGreaterThan(a)?1:0}}},qr=class pi{constructor(e){A(this,"events");A(this,"poly");A(this,"_isExteriorRing");A(this,"_enclosingRing");this.events=e;for(let t=0,n=e.length;t0&&(e=g)}let t=e.segment.prevInResult(),n=t?t.prevInResult():null;for(;;){if(!t)return null;if(!n)return t.ringOut;if(n.ringOut!==t.ringOut)return((r=n.ringOut)==null?void 0:r.enclosingRing())!==t.ringOut?t.ringOut:(u=t.ringOut)==null?void 0:u.enclosingRing();t=n.prevInResult(),n=t?t.prevInResult():null}}},Ji=class{constructor(i){A(this,"exteriorRing");A(this,"interiorRings");this.exteriorRing=i,i.poly=this,this.interiorRings=[]}addInterior(i){this.interiorRings.push(i),i.poly=this}getGeom(){const i=this.exteriorRing.getGeom();if(i===null)return null;const e=[i];for(let t=0,n=this.interiorRings.length;t0?(this.tree.delete(e),t.push(i)):(this.segments.push(e),e.prev=n)}else{if(n&&r){const u=n.getIntersection(r);if(u!==null){if(!n.isAnEndpoint(u)){const a=this._splitSafely(n,u);for(let o=0,g=a.length;o0)return-1;const M=t.comparePoint(e.rightSE.point);return M!==0?M:-1}if(n.isGreaterThan(r)){if(o.isLessThan(g)&&o.isLessThan(E))return-1;if(o.isGreaterThan(g)&&o.isGreaterThan(E))return 1;const _=t.comparePoint(e.leftSE.point);if(_!==0)return _;const M=e.comparePoint(t.rightSE.point);return M<0?1:M>0?-1:1}if(o.isLessThan(g))return-1;if(o.isGreaterThan(g))return 1;if(u.isLessThan(a)){const _=t.comparePoint(e.rightSE.point);if(_!==0)return _}if(u.isGreaterThan(a)){const _=e.comparePoint(t.rightSE.point);if(_<0)return 1;if(_>0)return-1}if(!u.eq(a)){const _=c.minus(o),M=u.minus(n),R=E.minus(g),k=a.minus(r);if(_.isGreaterThan(M)&&R.isLessThan(k))return 1;if(_.isLessThan(M)&&R.isGreaterThan(k))return-1}return u.isGreaterThan(a)?1:u.isLessThan(a)||c.isLessThan(E)?-1:c.isGreaterThan(E)?1:e.idt.id?1:0}static fromRing(e,t,n){let r,u,a;const o=Be.comparePoints(e,t);if(o<0)r=e,u=t,a=1;else if(o>0)r=t,u=e,a=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const g=new Be(r,!0),c=new Be(u,!1);return new Kt(g,c,[n],[a])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return Ze.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),n=e.bbox(),r=oi(t,n);if(r===null)return null;const u=this.leftSE.point,a=this.rightSE.point,o=e.leftSE.point,g=e.rightSE.point,c=St(t,o)&&this.comparePoint(o)===0,E=St(n,u)&&e.comparePoint(u)===0,_=St(t,g)&&this.comparePoint(g)===0,M=St(n,a)&&e.comparePoint(a)===0;if(E&&c)return M&&!_?a:!M&&_?g:null;if(E)return _&&u.x.eq(g.x)&&u.y.eq(g.y)?null:u;if(c)return M&&a.x.eq(o.x)&&a.y.eq(o.y)?null:o;if(M&&_)return null;if(M)return a;if(_)return g;const R=Ur(u,this.vector(),o,e.vector());return R===null||!St(r,R)?null:Ze.snap(R)}split(e){const t=[],n=e.events!==void 0,r=new Be(e,!0),u=new Be(e,!1),a=this.rightSE;this.replaceRightSE(u),t.push(u),t.push(r);const o=new Kt(r,a,this.rings.slice(),this.windings.slice());return Be.comparePoints(o.leftSE.point,o.rightSE.point)>0&&o.swapEvents(),Be.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(r.checkForConsuming(),u.checkForConsuming()),t}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,n=this.windings.length;t0){const u=t;t=n,n=u}if(t.prev===n){const u=t;t=n,n=u}for(let u=0,a=n.rings.length;ur.length===1&&r[0].isSubject;this._isInResult=n(e)!==n(t);break}}return this._isInResult}},$i=class{constructor(i,e,t){A(this,"poly");A(this,"isExterior");A(this,"segments");A(this,"bbox");if(!Array.isArray(i)||i.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=e,this.isExterior=t,this.segments=[],typeof i[0][0]!="number"||typeof i[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const n=Ze.snap({x:new Ae(i[0][0]),y:new Ae(i[0][1])});this.bbox={ll:{x:n.x,y:n.y},ur:{x:n.x,y:n.y}};let r=n;for(let u=1,a=i.length;uqt.run("union",i,e),Yr=(i,...e)=>qt.run("difference",i,e);Ze.set;function tn(i,e,t){if(i!==null)for(var n,r,u,a,o,g,c,E=0,_=0,M,R=i.type,k=R==="FeatureCollection",I=R==="Feature",C=k?i.features.length:1,O=0;O{t.push(r.coordinates)}),t.length<2)throw new Error("Must have at least 2 geometries");const n=Kr(t[0],...t.slice(1));return n.length===0?null:n.length===1?ti(n[0],e.properties):Fi(n,e.properties)}var nn=Xr;function Jr(i,e={}){if(i.bbox!=null&&e.recompute!==!0)return i.bbox;const t=[1/0,1/0,-1/0,-1/0];return tn(i,n=>{t[0]>n[0]&&(t[0]=n[0]),t[1]>n[1]&&(t[1]=n[1]),t[2]{e.push(r.coordinates)}),e.length<2)throw new Error("Must have at least two features");const t=i.features[0].properties||{},n=Yr(e[0],...e.slice(1));return n.length===0?null:n.length===1?ti(n[0],t):Fi(n,t)}var es=$r;function ts(i){if(!i)throw new Error("geojson is required");var e=[];return Qr(i,function(t){e.push(t)}),Lt(e)}var is=ts;function sn(i,e){const t=es(Lt([ti([[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]]),i]));if(!t)return;t.properties={isMask:!0};const n=Bt(rn(i)),r=(n[2]-n[0])/360/1e3,u=n[0]<-180,a=n[2]>180,o=is(i);if(o.features.length>1&&(u||a))for(const g of o.features){const c=Bt(rn(g));if(a&&c[0]<-180+r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]+=360-r;if(u&&c[2]>180-r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]-=360-r}e(Lt([o.features.length<2?i:nn(o)??i,t]))}const on={fill:{paint:{"fill-color":"#000","fill-opacity":.1},filter:["all",["==",["geometry-type"],"Polygon"],["has","isMask"]]},line:{layout:{"line-cap":"square"},paint:{"line-width":["case",["==",["geometry-type"],"Polygon"],2,3],"line-dasharray":[1,1],"line-color":"#3170fe"},filter:["!",["has","isMask"]]}},jt="mtlr-gc-full-geom",ln="mtlr-gc-full-geom-fill",un="mtlr-gc-full-geom-line";function an(i,e,t=!0,n=!0,r={},u={},a=on){let o;const g=[];let c,E,_;function M(){if(!i.loaded){i.once("load",M);return}const C=a?a===!0?on:a:void 0;if(!(C!=null&&C.fill)&&!(C!=null&&C.line))return;const O=i.getSource(jt);if(O)O.setData(_??Lt([]));else if(_)i.addSource(jt,{type:"geojson",data:_});else return;!i.getLayer(ln)&&(C!=null&&C.fill)&&i.addLayer({...C==null?void 0:C.fill,id:ln,type:"fill",source:jt}),!i.getLayer(un)&&(C!=null&&C.line)&&i.addLayer({...C==null?void 0:C.line,id:un,type:"line",source:jt})}function R(C){_=C,M()}i.on("styledata",()=>{setTimeout(()=>{_&&M()})});const k=C=>{o==null||o({type:"mapClick",coordinates:[C.lngLat.lng,C.lngLat.lat]})};function I(C=!1){if(!e)throw new Error;const O=document.createElement("div");return C&&O.classList.add("marker-interactive"),new or({props:{displayIn:"maplibre"},target:O}),new e.Marker({element:O,offset:[1,-13]})}return{setEventHandler(C){C?(o=C,i.on("click",k)):(o=void 0,i.off("click",k))},flyTo(C,O){i.flyTo({center:C,...O?{zoom:O}:{},...r})},fitBounds(C,O,x){i.fitBounds([[C[0],C[1]],[C[2],C[3]]],{padding:O,...x?{maxZoom:x}:{},...u})},indicateReverse(C){i.getCanvasContainer().style.cursor=C?"crosshair":""},setReverseMarker(C){!e||!t||(E?C?E.setLngLat(C):(E.remove(),E=void 0):C&&(t instanceof Function?E=t(i)??void 0:(E=(typeof t=="object"?new e.Marker(t):I()).setLngLat(C).addTo(i),E.getElement().classList.add("marker-reverse"))))},setFeatures(C,O,x){for(const N of g)N.remove();if(g.length=0,R(void 0),!!e){e:if(O){let N=!1;if(O.geometry.type==="GeometryCollection"){const P=O.geometry.geometries.filter(B=>B.type==="Polygon"||B.type==="MultiPolygon");t:if(P.length>0){const B=nn(Lt(P.map(z=>Et(z))));if(!B)break t;sn({...O,geometry:B.geometry},R),N=!0}else{const B=O.geometry.geometries.filter(z=>z.type==="LineString"||z.type==="MultiLineString");B.length>0&&(R({...O,geometry:{type:"GeometryCollection",geometries:B}}),N=!0)}}if(!N){if(O.geometry.type==="Polygon"||O.geometry.type==="MultiPolygon")sn(O,R);else if(O.geometry.type==="LineString"||O.geometry.type==="MultiLineString"){R(O);break e}}if(!x&&!O.geometry.type.endsWith("Point"))break e;if(t instanceof Function){const P=t(i,O);P&&g.push(P)}else t&&g.push(typeof t=="object"?new e.Marker(t):I().setLngLat(O.center).addTo(i))}if(n)for(const N of C??[]){if(N===O)continue;let P;if(n instanceof Function){if(P=n(i,N),!P)continue}else P=(typeof n=="object"?new e.Marker(n):I(!0)).setLngLat(N.center).setPopup(new e.Popup({offset:[1,-27],closeButton:!1,closeOnMove:!0,className:"maptiler-gc-popup"}).setText(N.place_type[0]==="reverse"?N.place_name:N.place_name.replace(/,.*/,""))).addTo(i);const B=P.getElement();B.addEventListener("click",z=>{z.stopPropagation(),o==null||o({type:"markerClick",id:N.id})}),B.addEventListener("mouseenter",()=>{o==null||o({type:"markerMouseEnter",id:N.id}),P.togglePopup()}),B.addEventListener("mouseleave",()=>{o==null||o({type:"markerMouseLeave",id:N.id}),P.togglePopup()}),g.push(P)}}},setSelectedMarker(C){c&&c.getElement().classList.toggle("marker-selected",!1),c=C>-1?g[C]:void 0,c==null||c.getElement().classList.toggle("marker-selected",!0)},getCenterAndZoom(){const C=i.getCenter();return[i.getZoom(),C.lng,C.lat]}}}function ns(i,e,t){var k,I,C;class n{constructor(x,N){A(this,"type");A(this,"target");this.type=N,this.target=x}}class r extends n{constructor(N,P){super(N,"select");A(this,"feature");Object.assign(this,P)}}class u extends n{constructor(N,P){super(N,"featureslisted");A(this,"features");this.features=P}}class a extends n{constructor(N,P){super(N,"featuresmarked");A(this,"features");this.features=P}}class o extends n{constructor(N,P){super(N,"optionsvisibilitychange");A(this,"optionsVisible");this.optionsVisible=P}}class g extends n{constructor(N,P){super(N,"pick");A(this,"feature");this.feature=P}}class c extends n{constructor(N,P){super(N,"querychange");A(this,"query");this.query=P}}class E extends n{constructor(N,P,B){super(N,"response");A(this,"url");A(this,"featureCollection");this.url=P,this.featureCollection=B}}class _ extends n{constructor(N,P){super(N,"reversetoggle");A(this,"reverse");this.reverse=P}}class M extends i{constructor(N={}){super();Vt(this,k);Vt(this,I);Vt(this,C);kt(this,I,N)}onAddInt(N){const P=document.createElement("div");P.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl mapboxgl-ctrl-group";const{marker:B,showResultMarkers:z,flyTo:W,fullGeometryStyle:s,...l}=ue(this,I),f=typeof W=="boolean"?{}:W,h={mapController:an(N,e,B,z,f,f,s),flyTo:W===void 0?!0:!!W,apiKey:"",...t==null?void 0:t(N,P),...l};return h.apiKey||console.warn("No MapTiler Cloud API key was provided, some or all geocoding requests may fail"),kt(this,k,new kr({target:P,props:h})),ue(this,k).$on("select",d=>{this.fire(new r(this,d.detail))}),ue(this,k).$on("pick",d=>{this.fire(new g(this,d.detail.feature))}),ue(this,k).$on("featureslisted",d=>{this.fire(new u(this,d.detail.features))}),ue(this,k).$on("featuresmarked",d=>{this.fire(new a(this,d.detail.features))}),ue(this,k).$on("response",d=>{this.fire(new E(this,d.detail.url,d.detail.featureCollection))}),ue(this,k).$on("optionsvisibilitychange",d=>{this.fire(new o(this,d.detail.optionsVisible))}),ue(this,k).$on("reversetoggle",d=>{this.fire(new _(this,d.detail.reverse))}),ue(this,k).$on("querychange",d=>{this.fire(new c(this,d.detail.query))}),kt(this,C,P),P}on(N,P){return super.on(N,P)}once(N,P){return super.once(N,P)}off(N,P){return super.off(N,P)}listens(N){return super.listens(N)}setOptions(N){var l;Object.assign(ue(this,I),N);const{marker:P,showResultMarkers:B,flyTo:z,fullGeometryStyle:W,...s}=ue(this,I);(l=ue(this,k))==null||l.$set(s)}setQuery(N,P=!0){var B;(B=ue(this,k))==null||B.setQuery(N,P)}clearMap(){var N;(N=ue(this,k))==null||N.clearMap()}clearList(){var N;(N=ue(this,k))==null||N.clearList()}setReverseMode(N){var P;(P=ue(this,k))==null||P.$set({reverseActive:N})}focus(N){var P;(P=ue(this,k))==null||P.focus(N)}blur(){var N;(N=ue(this,k))==null||N.blur()}onRemove(){var N,P,B;(N=ue(this,k))==null||N.$destroy(),kt(this,k,void 0),(B=(P=ue(this,C))==null?void 0:P.parentNode)==null||B.removeChild(ue(this,C))}}return k=new WeakMap,I=new WeakMap,C=new WeakMap,{MapLibreBasedGeocodingControl:M,events:{SelectEvent:r,FeaturesListedEvent:u,FeaturesMarkedEvent:a,OptionsVisibilityChangeEvent:o,PickEvent:g,QueryChangeEvent:c,ResponseEvent:E,ReverseToggleEvent:_}}}const{MapLibreBasedGeocodingControl:rs,events:et}=ns(dt.Evented,dt);class ss extends rs{onAdd(e){return super.onAddInt(e)}}const os=et.SelectEvent,ls=et.FeaturesListedEvent,us=et.FeaturesMarkedEvent,as=et.OptionsVisibilityChangeEvent,fs=et.PickEvent,cs=et.QueryChangeEvent,hs=et.ResponseEvent,ds=et.ReverseToggleEvent;j.FeaturesListedEvent=ls,j.FeaturesMarkedEvent=us,j.GeocodingControl=ss,j.OptionsVisibilityChangeEvent=as,j.PickEvent=fs,j.QueryChangeEvent=cs,j.ResponseEvent=hs,j.ReverseToggleEvent=ds,j.SelectEvent=os,j.createMapLibreGlMapController=an,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"})}); +//# sourceMappingURL=maplibregl.umd.js.map diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css new file mode 100644 index 0000000..c865c17 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css @@ -0,0 +1 @@ +svg.svelte-d2loi5{display:block;fill:#e15042}.sprite-icon.svelte-w9y5n9.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75;background-repeat:no-repeat}li.svelte-w9y5n9.svelte-w9y5n9{text-align:left;cursor:default;display:grid;grid-template-columns:40px 1fr;color:var(--color-text);padding:8px 0;font-size:14px;line-height:18px;min-width:fit-content;outline:0}li.svelte-w9y5n9.svelte-w9y5n9:first-child{padding-top:10px}li.svelte-w9y5n9.svelte-w9y5n9:last-child{padding-bottom:10px}li.picked.svelte-w9y5n9.svelte-w9y5n9{background-color:#e7edff}li.picked.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#96a4c7;padding-left:4px}li.picked.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#96a4c7}li.selected.svelte-w9y5n9.svelte-w9y5n9{background-color:#f3f6ff}li.selected.svelte-w9y5n9.svelte-w9y5n9{animation:svelte-w9y5n9-backAndForth 5s linear infinite}li.selected.svelte-w9y5n9 .primary.svelte-w9y5n9{color:#2b8bfb}li.selected.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#a2adc7;padding-left:4px}li.selected.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#a2adc7}li.svelte-w9y5n9>img.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75}.texts.svelte-w9y5n9.svelte-w9y5n9{padding:0 17px 0 0}.texts.svelte-w9y5n9>.svelte-w9y5n9{white-space:nowrap;display:block;min-width:fit-content}.primary.svelte-w9y5n9.svelte-w9y5n9{font-weight:600}.secondary.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7;padding-left:4px}.line2.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7}@keyframes svelte-w9y5n9-backAndForth{0%{transform:translate(0)}10%{transform:translate(0)}45%{transform:translate(calc(-100% + 270px))}55%{transform:translate(calc(-100% + 270px))}90%{transform:translate(0)}to{transform:translate(0)}}div.svelte-1ocfouu{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);pointer-events:none;display:flex;align-items:center}.loading-icon.svelte-1ocfouu{animation:svelte-1ocfouu-rotate .8s infinite cubic-bezier(.45,.05,.55,.95)}@keyframes svelte-1ocfouu-rotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}svg.svelte-gzo3ar.svelte-gzo3ar{display:block;fill:#6b7c93;stroke:#6b7c93}.list-icon.svelte-gzo3ar.svelte-gzo3ar{grid-row:1/3;align-self:center;margin:8px}.in-map.svelte-gzo3ar.svelte-gzo3ar{height:30px}.maplibregl-canvas-container .marker-selected{z-index:1}.maplibregl-canvas-container svg.svelte-gzo3ar path.svelte-gzo3ar,.leaflet-map-pane svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#3170fe;stroke:#3170fe}.marker-selected svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#98b7ff;stroke:#3170fe}.marker-reverse svg.svelte-gzo3ar path.svelte-gzo3ar{fill:silver;stroke:gray}.marker-interactive{cursor:pointer!important}.maptiler-gc-popup>.maplibregl-popup-content{padding:2px 8px}svg.svelte-en2qvf{display:block;fill:var(--color-icon-button)}circle.svelte-1aq105l{stroke-width:1.875;fill:none}path.svelte-1aq105l{stroke-width:1.875;stroke-linecap:round}svg.svelte-1aq105l{display:block;stroke:var(--color-icon-button)}form.svelte-bz0zu3.svelte-bz0zu3{font-family:Open Sans,Ubuntu,Helvetica Neue,Arial,Helvetica,sans-serif;position:relative;background-color:#fff;z-index:10;border-radius:4px;margin:0;transition:max-width .25s;box-shadow:0 2px 5px #33335926;--color-text:#444952;--color-icon-button:#444952}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3:after,form.svelte-bz0zu3 .svelte-bz0zu3:before{box-sizing:border-box}form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:29px}form.can-collapse.svelte-bz0zu3 input.svelte-bz0zu3::placeholder{transition:opacity .25s;opacity:0}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3.svelte-bz0zu3:focus-within,form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px}form.svelte-bz0zu3 input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:focus-within input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:hover input.svelte-bz0zu3::placeholder{opacity:1}input.svelte-bz0zu3.svelte-bz0zu3{font:inherit;font-size:14px;flex-grow:1;min-height:29px;background-color:transparent;color:#444952;white-space:nowrap;overflow:hidden;border:0;margin:0;padding:0}input.svelte-bz0zu3.svelte-bz0zu3:focus{color:#444952;outline:0;outline:none;box-shadow:none}ul.svelte-bz0zu3.svelte-bz0zu3,div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{background-color:#fff;border-radius:4px;left:0;list-style:none;margin:0;padding:0;position:absolute;width:100%;top:calc(100% + 6px);overflow:hidden}ul.svelte-bz0zu3.svelte-bz0zu3{font-size:14px;line-height:16px;box-shadow:0 5px 10px #33335926}div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{font:inherit;line-height:18px;font-size:12px;display:flex;gap:16px}div.error.svelte-bz0zu3.svelte-bz0zu3{padding:16px;font-weight:600;color:#e25041;background-color:#fbeae8}div.error.svelte-bz0zu3 div.svelte-bz0zu3{flex-grow:1}div.error.svelte-bz0zu3 svg{flex-shrink:0;width:20px;height:20px}div.error.svelte-bz0zu3 button.svelte-bz0zu3{flex-shrink:0}div.error.svelte-bz0zu3 button.svelte-bz0zu3>svg{width:13px;fill:#e25041}div.error.svelte-bz0zu3 button.svelte-bz0zu3:hover svg,div.error.svelte-bz0zu3 button.svelte-bz0zu3:active svg{fill:#444952}div.no-results.svelte-bz0zu3.svelte-bz0zu3{padding:14px 24px 14px 16px;font-weight:400;color:#6b7c93;box-shadow:0 5px 10px #33335926}div.no-results.svelte-bz0zu3 svg{margin-top:4px;flex-shrink:0;width:20px;height:20px;width:30px;height:30px}.leaflet-bottom ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-left ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-right ul.options.svelte-bz0zu3.svelte-bz0zu3{top:auto;bottom:calc(100% + 6px)}button.svelte-bz0zu3.svelte-bz0zu3{padding:0;margin:0;border:0;background-color:transparent;height:auto;width:auto}button.svelte-bz0zu3.svelte-bz0zu3:hover{background-color:transparent}button.svelte-bz0zu3:hover svg,button.svelte-bz0zu3:active svg{fill:#2b8bfb}.input-group.svelte-bz0zu3.svelte-bz0zu3{display:flex;align-items:stretch;gap:7px;padding-inline:8px;border-radius:4px;overflow:hidden}.input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{outline:#2b8bfb solid 2px}.search-button.svelte-bz0zu3.svelte-bz0zu3{flex-shrink:0}.maplibregl-ctrl-geocoder:not(.maptiler-ctrl) .search-button svg{width:12px!important;transform:translate(.5px)}.clear-button-container.svelte-bz0zu3.svelte-bz0zu3{display:flex;display:none;position:relative;align-items:stretch}.clear-button-container.displayable.svelte-bz0zu3.svelte-bz0zu3{display:flex;flex-shrink:0}.maplibregl-ctrl-geocoder{position:relative;z-index:3}.maptiler-ctrl:not(:empty){box-shadow:none}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3{padding-inline:8px;border:white solid 2px}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{border:#2b8bfb solid 2px;outline:0;outline:none}.maptiler-ctrl form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:33px}.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:focus-within,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px} diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js new file mode 100644 index 0000000..1a901ee --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js @@ -0,0 +1,2 @@ +"use strict";var pmtiles=(()=>{var k=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var U=Math.pow;var f=(r,e)=>k(r,"name",{value:e,configurable:!0});var Xe=(r,e)=>{for(var t in e)k(r,t,{get:e[t],enumerable:!0})},_e=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ye(e))!Qe.call(r,i)&&i!==t&&k(r,i,{get:()=>e[i],enumerable:!(n=Je(e,i))||n.enumerable});return r};var et=r=>_e(k({},"__esModule",{value:!0}),r);var m=(r,e,t)=>new Promise((n,i)=>{var a=h=>{try{u(t.next(h))}catch(l){i(l)}},s=h=>{try{u(t.throw(h))}catch(l){i(l)}},u=h=>h.done?n(h.value):Promise.resolve(h.value).then(a,s);u((t=t.apply(r,e)).next())});var Dt={};Xe(Dt,{Compression:()=>Oe,EtagMismatch:()=>B,FetchSource:()=>K,FileSource:()=>oe,PMTiles:()=>P,Protocol:()=>ie,ResolvedValueCache:()=>ue,SharedPromiseCache:()=>G,TileType:()=>se,bytesToHeader:()=>$e,findTile:()=>Fe,getUint64:()=>b,leafletRasterLayer:()=>wt,readVarint:()=>R,tileIdToZxy:()=>Tt,tileTypeExt:()=>Ze,zxyToTileId:()=>Ie});var w=Uint8Array,E=Uint16Array,tt=Int32Array,Me=new w([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ue=new w([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),rt=new w([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ee=f(function(r,e){for(var t=new E(31),n=0;n<31;++n)t[n]=e+=1<>1|(g&21845)<<1,T=(T&52428)>>2|(T&13107)<<2,T=(T&61680)>>4|(T&3855)<<4,re[g]=((T&65280)>>8|(T&255)<<8)>>1;var T,g,F=f(function(r,e,t){for(var n=r.length,i=0,a=new E(e);i>h]=l}else for(u=new E(n),i=0;i>15-r[i]);return u},"hMap"),$=new w(288);for(g=0;g<144;++g)$[g]=8;var g;for(g=144;g<256;++g)$[g]=9;var g;for(g=256;g<280;++g)$[g]=7;var g;for(g=280;g<288;++g)$[g]=8;var g,Re=new w(32);for(g=0;g<32;++g)Re[g]=5;var g;var at=F($,9,1);var st=F(Re,5,1),ee=f(function(r){for(var e=r[0],t=1;te&&(e=r[t]);return e},"max"),z=f(function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},"bits"),te=f(function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},"bits16"),ot=f(function(r){return(r+7)/8|0},"shft"),ut=f(function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new w(r.subarray(e,t))},"slc");var ft=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],y=f(function(r,e,t){var n=new Error(e||ft[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,y),!t)throw n;return n},"err"),ne=f(function(r,e,t,n){var i=r.length,a=n?n.length:0;if(!i||e.f&&!e.l)return t||new w(0);var s=!t,u=s||e.i!=2,h=e.i;s&&(t=new w(i*3));var l=f(function(Te){var Ce=t.length;if(Te>Ce){var De=new w(Math.max(Ce*2,Te));De.set(t),t=De}},"cbuf"),c=e.f||0,o=e.p||0,v=e.b||0,d=e.l,p=e.d,H=e.m,I=e.n,q=i*8;do{if(!d){c=z(r,o,1);var j=z(r,o+1,3);if(o+=3,j)if(j==1)d=at,p=st,H=9,I=5;else if(j==2){var J=z(r,o,31)+257,me=z(r,o+10,15)+4,de=J+z(r,o+5,31)+1;o+=14;for(var O=new w(de),Y=new w(19),x=0;x>4;if(A<16)O[x++]=A;else{var D=0,V=0;for(A==16?(V=3+z(r,o,3),o+=2,D=O[x-1]):A==17?(V=3+z(r,o,7),o+=3):A==18&&(V=11+z(r,o,127),o+=7);V--;)O[x++]=D}}var xe=O.subarray(0,J),C=O.subarray(J);H=ee(xe),I=ee(C),d=F(xe,H,1),p=F(C,I,1)}else y(1);else{var A=ot(o)+4,W=r[A-4]|r[A-3]<<8,N=A+W;if(N>i){h&&y(0);break}u&&l(v+W),t.set(r.subarray(A,N),v),e.b=v+=W,e.p=o=N*8,e.f=c;continue}if(o>q){h&&y(0);break}}u&&l(v+131072);for(var je=(1<>4;if(o+=D&15,o>q){h&&y(0);break}if(D||y(2),M<256)t[v++]=M;else if(M==256){Q=o,d=null;break}else{var be=M-254;if(M>264){var x=M-257,Z=Me[x];be=z(r,o,(1<>4;X||y(3),o+=X&15;var C=it[_];if(_>3){var Z=Ue[_];C+=te(r,o)&(1<q){h&&y(0);break}u&&l(v+131072);var ze=v+be;if(v>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},"gzs"),ct=f(function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0},"gzl");var vt=f(function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&y(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&y(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2},"zls");function gt(r,e){return ne(r,{i:2},e&&e.out,e&&e.dictionary)}f(gt,"inflateSync");function pt(r,e){var t=ht(r);return t+8>r.length&&y(6,"invalid gzip data"),ne(r.subarray(t,-8),{i:2},e&&e.out||new w(ct(r)),e&&e.dictionary)}f(pt,"gunzipSync");function mt(r,e){return ne(r.subarray(vt(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}f(mt,"unzlibSync");function Be(r,e){return r[0]==31&&r[1]==139&&r[2]==8?pt(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?gt(r,e):mt(r,e)}f(Be,"decompressSync");var dt=typeof TextDecoder!="undefined"&&new TextDecoder,yt=0;try{dt.decode(lt,{stream:!0}),yt=1}catch(r){}var wt=f((r,e)=>{let t=!1,n="",i=L.GridLayer.extend({createTile:f((a,s)=>{let u=document.createElement("img"),h=new AbortController,l=h.signal;return u.cancel=()=>{h.abort()},t||(r.getHeader().then(c=>{c.tileType===1?console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):c.tileType===2?n="image/png":c.tileType===3?n="image/jpeg":c.tileType===4?n="image/webp":c.tileType===5&&(n="image/avif")}),t=!0),r.getZxy(a.z,a.x,a.y,l).then(c=>{if(c){let o=new Blob([c.data],{type:n}),v=window.URL.createObjectURL(o);u.src=v,u.cancel=void 0,s(void 0,u)}}).catch(c=>{if(c.name!=="AbortError")throw c}),u},"createTile"),_removeTile:f(function(a){let s=this._tiles[a];s&&(s.el.cancel&&s.el.cancel(),s.el.width=0,s.el.height=0,s.el.deleted=!0,L.DomUtil.remove(s.el),delete this._tiles[a],this.fire("tileunload",{tile:s.el,coords:this._keyToTileCoords(a)}))},"_removeTile")});return new i(e)},"leafletRasterLayer"),xt=f(r=>(e,t)=>{if(t instanceof AbortController)return r(e,t);let n=new AbortController;return r(e,n).then(i=>t(void 0,i.data,i.cacheControl||"",i.expires||""),i=>t(i)).catch(i=>t(i)),{cancel:f(()=>n.abort(),"cancel")}},"v3compat"),ae=class ae{constructor(e){this.tilev4=f((e,t)=>m(this,null,function*(){if(e.type==="json"){let v=e.url.substr(10),d=this.tiles.get(v);if(d||(d=new P(v),this.tiles.set(v,d)),this.metadata)return{data:yield d.getTileJson(e.url)};let p=yield d.getHeader();return(p.minLon>=p.maxLon||p.minLat>=p.maxLat)&&console.error(`Bounds of PMTiles archive ${p.minLon},${p.minLat},${p.maxLon},${p.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:p.minZoom,maxzoom:p.maxZoom,bounds:[p.minLon,p.minLat,p.maxLon,p.maxLat]}}}let n=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),i=e.url.match(n);if(!i)throw new Error("Invalid PMTiles protocol URL");let a=i[1],s=this.tiles.get(a);s||(s=new P(a),this.tiles.set(a,s));let u=i[2],h=i[3],l=i[4],c=yield s.getHeader(),o=yield s==null?void 0:s.getZxy(+u,+h,+l,t.signal);if(o)return{data:new Uint8Array(o.data),cacheControl:o.cacheControl,expires:o.expires};if(c.tileType===1){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4");this.tile=xt(this.tilev4);this.tiles=new Map,this.metadata=(e==null?void 0:e.metadata)||!1,this.errorOnMissingTile=(e==null?void 0:e.errorOnMissingTile)||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};f(ae,"Protocol");var ie=ae;function S(r,e){return(e>>>0)*4294967296+(r>>>0)}f(S,"toNum");function bt(r,e){let t=e.buf,n=t[e.pos++],i=(n&112)>>4;if(n<128||(n=t[e.pos++],i|=(n&127)<<3,n<128)||(n=t[e.pos++],i|=(n&127)<<10,n<128)||(n=t[e.pos++],i|=(n&127)<<17,n<128)||(n=t[e.pos++],i|=(n&127)<<24,n<128)||(n=t[e.pos++],i|=(n&1)<<31,n<128))return S(r,i);throw new Error("Expected varint not more than 10 bytes")}f(bt,"readVarintRemainder");function R(r){let e=r.buf,t=e[r.pos++],n=t&127;return t<128||(t=e[r.pos++],n|=(t&127)<<7,t<128)||(t=e[r.pos++],n|=(t&127)<<14,t<128)||(t=e[r.pos++],n|=(t&127)<<21,t<128)?n:(t=e[r.pos],n|=(t&15)<<28,bt(n,r))}f(R,"readVarint");function He(r,e,t,n){if(n===0){t===1&&(e[0]=r-1-e[0],e[1]=r-1-e[1]);let i=e[0];e[0]=e[1],e[1]=i}}f(He,"rotate");function zt(r,e){let t=U(2,r),n=e,i=e,a=e,s=[0,0],u=1;for(;u26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>U(2,r)-1||t>U(2,r)-1)throw new Error("tile x/y outside zoom level bounds");let n=At[r],i=U(2,r),a=0,s=0,u=0,h=[e,t],l=i/2;for(;l>0;)a=(h[0]&l)>0?1:0,s=(h[1]&l)>0?1:0,u+=l*l*(3*a^s),He(l,h,a,s),l=l/2;return n+u}f(Ie,"zxyToTileId");function Tt(r){let e=0,t=0;for(let n=0;n<27;n++){let i=(1<r)return zt(n,r-e);e+=i}throw new Error("Tile zoom level exceeds max safe number limit (26)")}f(Tt,"tileIdToZxy");var Oe=(a=>(a[a.Unknown=0]="Unknown",a[a.None=1]="None",a[a.Gzip=2]="Gzip",a[a.Brotli=3]="Brotli",a[a.Zstd=4]="Zstd",a))(Oe||{});function fe(r,e){return m(this,null,function*(){if(e===1||e===0)return r;if(e===2){if(typeof globalThis.DecompressionStream=="undefined")return Be(new Uint8Array(r));let t=new Response(r).body;if(!t)throw new Error("Failed to read response stream");let n=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(n).arrayBuffer()}throw new Error("Compression method not supported")})}f(fe,"defaultDecompress");var se=(s=>(s[s.Unknown=0]="Unknown",s[s.Mvt=1]="Mvt",s[s.Png=2]="Png",s[s.Jpeg=3]="Jpeg",s[s.Webp=4]="Webp",s[s.Avif=5]="Avif",s))(se||{});function Ze(r){return r===1?".mvt":r===2?".png":r===3?".jpg":r===4?".webp":r===5?".avif":""}f(Ze,"tileTypeExt");var Ct=127;function Fe(r,e){let t=0,n=r.length-1;for(;t<=n;){let i=n+t>>1,a=e-r[i].tileId;if(a>0)t=i+1;else if(a<0)n=i-1;else return r[i]}return n>=0&&(r[n].runLength===0||e-r[n].tileId-1,a=/Chrome|Chromium|Edg|OPR|Brave/.test(n);this.chromeWindowsNoCache=!1,i&&a&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,n,i){return m(this,null,function*(){let a,s;n?s=n:(a=new AbortController,s=a.signal);let u=new Headers(this.customHeaders);u.set("range",`bytes=${e}-${e+t-1}`);let h;this.mustReload?h="reload":this.chromeWindowsNoCache&&(h="no-store");let l=yield fetch(this.url,{signal:s,cache:h,headers:u});if(e===0&&l.status===416){let d=l.headers.get("Content-Range");if(!d||!d.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let p=+d.substr(8);l=yield fetch(this.url,{signal:s,cache:"reload",headers:{range:`bytes=0-${p-1}`}})}let c=l.headers.get("Etag");if(c!=null&&c.startsWith("W/")&&(c=null),l.status===416||i&&c&&c!==i)throw this.mustReload=!0,new B(`Server returned non-matching ETag ${i} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(l.status>=300)throw new Error(`Bad response code: ${l.status}`);let o=l.headers.get("Content-Length");if(l.status===200&&(!o||+o>t))throw a&&a.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield l.arrayBuffer(),etag:c||void 0,cacheControl:l.headers.get("Cache-Control")||void 0,expires:l.headers.get("Expires")||void 0}})}};f(he,"FetchSource");var K=he;function b(r,e){let t=r.getUint32(e+4,!0),n=r.getUint32(e+0,!0);return t*U(2,32)+n}f(b,"getUint64");function $e(r,e){let t=new DataView(r),n=t.getUint8(7);if(n>3)throw new Error(`Archive is spec version ${n} but this library supports up to spec version 3`);return{specVersion:n,rootDirectoryOffset:b(t,8),rootDirectoryLength:b(t,16),jsonMetadataOffset:b(t,24),jsonMetadataLength:b(t,32),leafDirectoryOffset:b(t,40),leafDirectoryLength:b(t,48),tileDataOffset:b(t,56),tileDataLength:b(t,64),numAddressedTiles:b(t,72),numTileEntries:b(t,80),numTileContents:b(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}f($e,"bytesToHeader");function Ve(r){let e={buf:new Uint8Array(r),pos:0},t=R(e),n=[],i=0;for(let a=0;a0?n[a].offset=n[a-1].offset+n[a-1].length:n[a].offset=s-1}return n}f(Ve,"deserializeIndex");var ce=class ce extends Error{};f(ce,"EtagMismatch");var B=ce;function ke(r,e){return m(this,null,function*(){let t=yield r.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let i=t.data.slice(0,Ct),a=$e(i,t.etag),s=t.data.slice(a.rootDirectoryOffset,a.rootDirectoryOffset+a.rootDirectoryLength),u=`${r.getKey()}|${a.etag||""}|${a.rootDirectoryOffset}|${a.rootDirectoryLength}`,h=Ve(yield e(s,a.internalCompression));return[a,[u,h.length,h]]})}f(ke,"getHeaderAndRoot");function Ke(r,e,t,n,i){return m(this,null,function*(){let a=yield r.getBytes(t,n,void 0,i.etag),s=yield e(a.data,i.internalCompression),u=Ve(s);if(u.length===0)throw new Error("Empty directory is invalid");return u})}f(Ke,"getDirectory");var ve=class ve{constructor(e=100,t=!0,n=fe){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return m(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,n.data;let i=yield ke(e,this.decompress);return i[1]&&this.cache.set(i[1][0],{lastUsed:this.counter++,data:i[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:i[0]}),this.prune(),i[0]})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,s.data;let u=yield Ke(e,this.decompress,t,n,i);return this.cache.set(a,{lastUsed:this.counter++,data:u}),this.prune(),u})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{ke(e,this.decompress).then(u=>{u[1]&&this.cache.set(u[1][0],{lastUsed:this.counter++,data:Promise.resolve(u[1][2])}),a(u[0]),this.prune()}).catch(u=>{s(u)})});return this.cache.set(t,{lastUsed:this.counter++,data:i}),i})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,yield s.data;let u=new Promise((h,l)=>{Ke(e,this.decompress,t,n,i).then(c=>{h(c),this.prune()}).catch(c=>{l(c)})});return this.cache.set(a,{lastUsed:this.counter++,data:u}),u})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{this.getHeader(e).then(s=>{i(),this.invalidations.delete(t)}).catch(s=>{a(s)})});this.invalidations.set(t,n)})}};f(ge,"SharedPromiseCache");var G=ge,pe=class pe{constructor(e,t,n){typeof e=="string"?this.source=new K(e):this.source=e,n?this.decompress=n:this.decompress=fe,t?this.cache=t:this.cache=new G}getHeader(){return m(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,n,i){return m(this,null,function*(){let a=Ie(e,t,n),s=yield this.cache.getHeader(this.source);if(es.maxZoom)return;let u=s.rootDirectoryOffset,h=s.rootDirectoryLength;for(let l=0;l<=3;l++){let c=yield this.cache.getDirectory(this.source,u,h,s),o=Fe(c,a);if(o){if(o.runLength>0){let v=yield this.source.getBytes(s.tileDataOffset+o.offset,o.length,i,s.etag);return{data:yield this.decompress(v.data,s.tileCompression),cacheControl:v.cacheControl,expires:v.expires}}u=s.leafDirectoryOffset+o.offset,h=o.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,n,i){return m(this,null,function*(){try{return yield this.getZxyAttempt(e,t,n,i)}catch(a){if(a instanceof B)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,n,i);throw a}})}getMetadataAttempt(){return m(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),n=yield this.decompress(t.data,e.internalCompression),i=new TextDecoder("utf-8");return JSON.parse(i.decode(n))})}getMetadata(){return m(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof B)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return m(this,null,function*(){let t=yield this.getHeader(),n=yield this.getMetadata(),i=Ze(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${i}`],vector_layers:n.vector_layers,attribution:n.attribution,description:n.description,name:n.name,version:n.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};f(pe,"PMTiles");var P=pe;return et(Dt);})(); +//# sourceMappingURL=pmtiles.js.map \ No newline at end of file diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js new file mode 100644 index 0000000..2b7b5bf --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js @@ -0,0 +1,311 @@ +// Radius/Circle drawing mode for Mapbox GL Draw +// Creates a circle by drawing from center to edge +(function (MapboxDraw) { + const DrawLine = MapboxDraw.modes.draw_line_string; + + // Utility function to create a vertex feature + const createVertex = function (parentId, coordinates, path, selected) { + return { + type: "Feature", + properties: { + meta: "vertex", + parent: parentId, + coord_path: path, + active: selected ? "true" : "false" + }, + geometry: { + type: "Point", + coordinates: coordinates + } + }; + }; + + // Utility function to calculate distance between two points in kilometers + const calculateDistance = function (coord1, coord2) { + const lat1 = coord1[1]; + const lon1 = coord1[0]; + const lat2 = coord2[1]; + const lon2 = coord2[0]; + + const R = 6371; // Radius of the Earth in kilometers + const dLat = (lat2 - lat1) * Math.PI / 180; + const dLon = (lon2 - lon1) * Math.PI / 180; + const a = + Math.sin(dLat/2) * Math.sin(dLat/2) + + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * + Math.sin(dLon/2) * Math.sin(dLon/2); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + const distance = R * c; + + return distance; + }; + + // Utility function to create a GeoJSON circle + const createGeoJSONCircle = function (center, radiusInKm, parentId, points) { + points = points || 64; + + const coords = { + latitude: center[1], + longitude: center[0] + }; + + const km = radiusInKm; + const ret = []; + const distanceX = km / (111.32 * Math.cos((coords.latitude * Math.PI) / 180)); + const distanceY = km / 110.574; + + let theta, x, y; + for (let i = 0; i < points; i++) { + theta = (i / points) * (2 * Math.PI); + x = distanceX * Math.cos(theta); + y = distanceY * Math.sin(theta); + + ret.push([coords.longitude + x, coords.latitude + y]); + } + ret.push(ret[0]); + + return { + type: "Feature", + geometry: { + type: "Polygon", + coordinates: [ret] + }, + properties: { + parent: parentId, + meta: "radius" + } + }; + }; + + // Utility function to format distance for display + const getDisplayMeasurements = function (distanceKm) { + let metricUnits = "m"; + let metricFormat = "0,0"; + let metricMeasurement; + + let standardUnits = "feet"; + let standardFormat = "0,0"; + let standardMeasurement; + + metricMeasurement = distanceKm * 1000; // Convert to meters + if (metricMeasurement >= 1000) { + metricMeasurement = metricMeasurement / 1000; + metricUnits = "km"; + metricFormat = "0.00"; + } + + standardMeasurement = distanceKm * 1000 * 3.28084; // Convert to feet + if (standardMeasurement >= 5280) { + standardMeasurement = standardMeasurement / 5280; + standardUnits = "mi"; + standardFormat = "0.00"; + } + + // Simple number formatting (without numeral.js dependency) + const formatNumber = function(num, format) { + if (format === "0,0") { + return Math.round(num).toLocaleString(); + } else if (format === "0.00") { + return num.toFixed(2); + } + return num.toString(); + }; + + return { + metric: formatNumber(metricMeasurement, metricFormat) + " " + metricUnits, + standard: formatNumber(standardMeasurement, standardFormat) + " " + standardUnits + }; + }; + + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RadiusMode = Object.assign({}, DrawLine); + + RadiusMode.onSetup = function (opts) { + const line = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "LineString", + coordinates: [] + } + }); + + this.addFeature(line); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.activateUIButton("line"); + this.setActionableState({ trash: true }); + + return { + line: line, + currentVertexPosition: 0, + direction: "forward" + }; + }; + + RadiusMode.onClick = function (state, e) { + // This ends the drawing after the user creates a second point + if (state.currentVertexPosition === 1) { + // Update the second coordinate in place, don't add at position 0 + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + return this.changeMode("simple_select", { featureIds: [state.line.id] }); + } + + this.updateUIClasses({ mouse: "add" }); + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + + if (state.direction === "forward") { + state.currentVertexPosition += 1; + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + } else { + state.line.addCoordinate(0, e.lngLat.lng, e.lngLat.lat); + } + + return null; + }; + + RadiusMode.onMouseMove = function (state, e) { + if (state.currentVertexPosition === 1) { + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + } + }; + + // Creates the final geojson circle polygon + RadiusMode.onStop = function (state) { + doubleClickZoom.enable(this); + this.activateUIButton(); + + // Check to see if we've deleted this feature + if (this.getFeature(state.line.id) === undefined) return; + + if (state.line.isValid()) { + const lineGeoJson = state.line.toGeoJSON(); + const coords = lineGeoJson.geometry.coordinates; + + if (coords.length >= 2) { + // Calculate radius in kilometers + const radiusKm = calculateDistance(coords[0], coords[1]); + + // Create the circle polygon + const circleFeature = createGeoJSONCircle(coords[0], radiusKm, state.line.id); + + // Add radius property for reference + circleFeature.properties.radius = (radiusKm * 1000).toFixed(1); + + // Remove the meta property that was interfering + delete circleFeature.properties.meta; + delete circleFeature.properties.parent; + + // Delete the temporary line first + this.deleteFeature([state.line.id], { silent: true }); + + // Add the circle feature to the draw instance + const circleDrawFeature = this.newFeature(circleFeature); + this.addFeature(circleDrawFeature); + + this.map.fire("draw.create", { + features: [circleDrawFeature.toGeoJSON()] + }); + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + + this.changeMode("simple_select", {}, { silent: true }); + }; + + RadiusMode.toDisplayFeatures = function (state, geojson, display) { + const isActiveLine = geojson.properties.id === state.line.id; + geojson.properties.active = isActiveLine ? "true" : "false"; + + if (!isActiveLine) return display(geojson); + + // Only render the line if it has at least one real coordinate + if (geojson.geometry.coordinates.length < 2) return null; + + geojson.properties.meta = "feature"; + + // Display center vertex as a point feature + display(createVertex( + state.line.id, + geojson.geometry.coordinates[ + state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1 + ], + "" + (state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1), + false + )); + + // Display the line as it is drawn + display(geojson); + + const coords = geojson.geometry.coordinates; + if (coords.length >= 2) { + const distanceKm = calculateDistance(coords[0], coords[1]); + const displayMeasurements = getDisplayMeasurements(distanceKm); + + // Create custom feature for the current pointer position + const currentVertex = { + type: "Feature", + properties: { + meta: "currentPosition", + radiusMetric: displayMeasurements.metric, + radiusStandard: displayMeasurements.standard, + parent: state.line.id + }, + geometry: { + type: "Point", + coordinates: coords[1] + } + }; + display(currentVertex); + + // Create custom feature for radius circle + const center = coords[0]; + const circleFeature = createGeoJSONCircle(center, distanceKm, state.line.id); + display(circleFeature); + } + + return null; + }; + + RadiusMode.onTrash = function (state) { + this.deleteFeature([state.line.id], { silent: true }); + this.changeMode("simple_select"); + }; + + MapboxDraw.modes.draw_radius = RadiusMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js new file mode 100644 index 0000000..73af6d6 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js @@ -0,0 +1,124 @@ +// Rectangle drawing mode for Mapbox GL Draw +// Adapted from https://github.com/edgespatial/mapbox-gl-draw-rectangle-mode +(function (MapboxDraw) { + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RectangleMode = { + onSetup: function (opts) { + const rectangle = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "Polygon", + coordinates: [[]] + } + }); + + this.addFeature(rectangle); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.setActionableState({ trash: true }); + + return { + rectangle: rectangle + }; + }, + + onClick: function (state, e) { + // If we have a start point and click on a different point, complete the rectangle + if (state.startPoint && + (state.startPoint[0] !== e.lngLat.lng || state.startPoint[1] !== e.lngLat.lat)) { + this.updateUIClasses({ mouse: "pointer" }); + state.endPoint = [e.lngLat.lng, e.lngLat.lat]; + this.changeMode("simple_select", { featuresId: state.rectangle.id }); + return; + } + + // Set the start point + const startPoint = [e.lngLat.lng, e.lngLat.lat]; + state.startPoint = startPoint; + }, + + onMouseMove: function (state, e) { + // Update rectangle coordinates as the mouse moves + if (state.startPoint) { + const startX = state.startPoint[0]; + const startY = state.startPoint[1]; + const endX = e.lngLat.lng; + const endY = e.lngLat.lat; + + state.rectangle.updateCoordinate("0.0", startX, startY); + state.rectangle.updateCoordinate("0.1", endX, startY); + state.rectangle.updateCoordinate("0.2", endX, endY); + state.rectangle.updateCoordinate("0.3", startX, endY); + state.rectangle.updateCoordinate("0.4", startX, startY); + } + }, + + onKeyUp: function (state, e) { + if (e.keyCode === 27) { // Escape key + return this.changeMode("simple_select"); + } + }, + + onStop: function (state) { + doubleClickZoom.enable(this); + this.updateUIClasses({ mouse: "none" }); + this.activateUIButton(); + + if (this.getFeature(state.rectangle.id) !== undefined) { + // Remove the closing coordinate (duplicate of first) + state.rectangle.removeCoordinate("0.4"); + + if (state.rectangle.isValid()) { + this.map.fire("draw.create", { + features: [state.rectangle.toGeoJSON()] + }); + } else { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select", {}, { silent: true }); + } + } + }, + + toDisplayFeatures: function (state, geojson, display) { + const isActiveRectangle = geojson.properties.id === state.rectangle.id; + geojson.properties.active = isActiveRectangle ? "true" : "false"; + + if (!isActiveRectangle) { + return display(geojson); + } + + // Only display the rectangle if we have started drawing + if (state.startPoint) { + return display(geojson); + } + }, + + onTrash: function (state) { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select"); + } + }; + + MapboxDraw.modes.draw_rectangle = RectangleMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/lib/turf/turf.min.js b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/turf/turf.min.js new file mode 100644 index 0000000..635896d --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/lib/turf/turf.min.js @@ -0,0 +1,37 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).turf={})}(this,(function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}function u(t,e,n){return(e=y(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function l(t){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},l(t)}function h(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&p(t,e)}function c(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(c=function(){return!!t})()}function f(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}function g(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function p(t,e){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},p(t,e)}function v(t,e){return n(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,o,s,a=[],u=!0,l=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);u=!0);}catch(t){l=!0,i=t}finally{try{if(!u&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw i}}return a}}(t,e)||_(t,e)||g()}function d(t){return function(t){if(Array.isArray(t))return e(t)}(t)||f(t)||_(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function m(t){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},m(t)}function _(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var x=6371008.8,E={centimeters:100*x,centimetres:100*x,degrees:360/(2*Math.PI),feet:3.28084*x,inches:39.37*x,kilometers:x/1e3,kilometres:x/1e3,meters:x,metres:x,miles:x/1609.344,millimeters:1e3*x,millimetres:1e3*x,nauticalmiles:x/1852,radians:1,yards:1.0936*x},k={acres:247105e-9,centimeters:1e4,centimetres:1e4,feet:10.763910417,hectares:1e-4,inches:1550.003100006,kilometers:1e-6,kilometres:1e-6,meters:1,metres:1,miles:386e-9,nauticalmiles:2.9155334959812285e-7,millimeters:1e6,millimetres:1e6,yards:1.195990046};function b(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={type:"Feature"};return(0===n.id||n.id)&&(r.id=n.id),n.bbox&&(r.bbox=n.bbox),r.properties=e||{},r.geometry=t,r}function w(t,e){switch(t){case"Point":return I(e).geometry;case"LineString":return L(e).geometry;case"Polygon":return S(e).geometry;case"MultiPoint":return O(e).geometry;case"MultiLineString":return T(e).geometry;case"MultiPolygon":return R(e).geometry;default:throw new Error(t+" is invalid")}}function I(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("coordinates is required");if(!Array.isArray(t))throw new Error("coordinates must be an Array");if(t.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!U(t[0])||!U(t[1]))throw new Error("coordinates must contain numbers");return b({type:"Point",coordinates:t},e,n)}function N(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return I(t,e)})),n)}function S(t,e){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=a(t);try{for(i.s();!(n=i.n()).done;){var o=n.value;if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(var s=0;s2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return S(t,e)})),n)}function L(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(t.length<2)throw new Error("coordinates must be an array of two or more positions");return b({type:"LineString",coordinates:t},e,n)}function P(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return L(t,e)})),n)}function C(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={type:"FeatureCollection"};return e.id&&(n.id=e.id),e.bbox&&(n.bbox=e.bbox),n.features=t,n}function T(t,e){return b({type:"MultiLineString",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function O(t,e){return b({type:"MultiPoint",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function R(t,e){return b({type:"MultiPolygon",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function A(t,e){return b({type:"GeometryCollection",geometries:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function D(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e&&!(e>=0))throw new Error("precision must be a positive number");var n=Math.pow(10,e||0);return Math.round(t*n)/n}function F(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t*n}function q(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t/n}function V(t,e){return Y(q(t,e))}function G(t){var e=t%360;return e<0&&(e+=360),e}function B(t){return(t%=360)>180?t-360:t<-180?t+360:t}function Y(t){return 180*(t%(2*Math.PI))/Math.PI}function z(t){return t%360*Math.PI/180}function j(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("length must be a positive number");return F(q(t,e),n)}function X(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"meters",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("area must be a positive number");var r=k[e];if(!r)throw new Error("invalid original units");var i=k[n];if(!i)throw new Error("invalid final units");return t/r*i}function U(t){return!isNaN(t)&&null!==t&&!Array.isArray(t)}function Z(t){return null!==t&&"object"===m(t)&&!Array.isArray(t)}function H(t){if(!t)throw new Error("bbox is required");if(!Array.isArray(t))throw new Error("bbox must be an Array");if(4!==t.length&&6!==t.length)throw new Error("bbox must be an Array of 4 or 6 numbers");t.forEach((function(t){if(!U(t))throw new Error("bbox must only contain numbers")}))}function W(t){if(!t)throw new Error("id is required");if(-1===["string","number"].indexOf(m(t)))throw new Error("id must be a number or a string")}var J=Object.freeze({__proto__:null,areaFactors:k,azimuthToBearing:B,bearingToAzimuth:G,convertArea:X,convertLength:j,degreesToRadians:z,earthRadius:x,factors:E,feature:b,featureCollection:C,geometry:w,geometryCollection:A,isNumber:U,isObject:Z,lengthToDegrees:V,lengthToRadians:q,lineString:L,lineStrings:P,multiLineString:T,multiPoint:O,multiPolygon:R,point:I,points:N,polygon:S,polygons:M,radiansToDegrees:Y,radiansToLength:F,round:D,validateBBox:H,validateId:W});function K(t){if(!t)throw new Error("coord is required");if(!Array.isArray(t)){if("Feature"===t.type&&null!==t.geometry&&"Point"===t.geometry.type)return d(t.geometry.coordinates);if("Point"===t.type)return d(t.coordinates)}if(Array.isArray(t)&&t.length>=2&&!Array.isArray(t[0])&&!Array.isArray(t[1]))return d(t);throw new Error("coord must be GeoJSON Point or an Array of numbers")}function Q(t){if(Array.isArray(t))return t;if("Feature"===t.type){if(null!==t.geometry)return t.geometry.coordinates}else if(t.coordinates)return t.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function $(t){if(t.length>1&&U(t[0])&&U(t[1]))return!0;if(Array.isArray(t[0])&&t[0].length)return $(t[0]);throw new Error("coordinates must only contain numbers")}function tt(t,e,n){if(!e||!n)throw new Error("type and name required");if(!t||t.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.type)}function et(t,e,n){if(!t)throw new Error("No feature passed");if(!n)throw new Error(".featureOf() requires a name");if(!t||"Feature"!==t.type||!t.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!t.geometry||t.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.geometry.type)}function nt(t,e,n){if(!t)throw new Error("No featureCollection passed");if(!n)throw new Error(".collectionOf() requires a name");if(!t||"FeatureCollection"!==t.type)throw new Error("Invalid input to "+n+", FeatureCollection required");var r,i=a(t.features);try{for(i.s();!(r=i.n()).done;){var o=r.value;if(!o||"Feature"!==o.type||!o.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!o.geometry||o.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+o.geometry.type)}}catch(t){i.e(t)}finally{i.f()}}function rt(t){return"Feature"===t.type?t.geometry:t}function it(t,e){return"FeatureCollection"===t.type?"FeatureCollection":"GeometryCollection"===t.type?"GeometryCollection":"Feature"===t.type&&null!==t.geometry?t.geometry.type:t.type}var ot=Object.freeze({__proto__:null,collectionOf:nt,containsNumber:$,featureOf:et,geojsonType:tt,getCoord:K,getCoords:Q,getGeom:rt,getType:it});function st(t,e){if(!0===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final)return function(t,e){var n=st(e,t);return n=(n+180)%360}(t,e);var n=K(t),r=K(e),i=z(n[0]),o=z(r[0]),s=z(n[1]),a=z(r[1]),u=Math.sin(o-i)*Math.cos(a),l=Math.cos(s)*Math.sin(a)-Math.sin(s)*Math.cos(a)*Math.cos(o-i);return Y(Math.atan2(u,l))}function at(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=K(t),o=z(i[0]),s=z(i[1]),a=z(n),u=q(e,r.units),l=Math.asin(Math.sin(s)*Math.cos(u)+Math.cos(s)*Math.sin(u)*Math.cos(a));return I([Y(o+Math.atan2(Math.sin(a)*Math.sin(u)*Math.cos(s),Math.cos(u)-Math.sin(s)*Math.sin(l))),Y(l)],r.properties)}function ut(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e),o=z(i[1]-r[1]),s=z(i[0]-r[0]),a=z(r[1]),u=z(i[1]),l=Math.pow(Math.sin(o/2),2)+Math.pow(Math.sin(s/2),2)*Math.cos(a)*Math.cos(u);return F(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)),n.units)}function lt(t,e){var n;return(n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final?ht(K(e),K(t)):ht(K(t),K(e)))>180?-(360-n):n}function ht(t,e){var n=z(t[1]),r=z(e[1]),i=z(e[0]-t[0]);i>Math.PI&&(i-=2*Math.PI),i<-Math.PI&&(i+=2*Math.PI);var o=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(n/2+Math.PI/4));return(Y(Math.atan2(i,o))+360)%360}function ct(t,e,n){if(null!==t)for(var r,i,o,s,a,u,l,h,c=0,f=0,g=t.type,p="FeatureCollection"===g,v="Feature"===g,d=p?t.features.length:1,y=0;ya||f>u||g>l)return s=o,a=n,u=f,l=g,void(i=0);var p=L([s,o],t.properties);if(!1===e(p,n,r,g,i))return!1;i++,s=o}))&&void 0}}}))}function bt(t,e,n){var r=n,i=!1;return kt(t,(function(t,o,s,a,u){r=!1===i&&void 0===n?t:e(r,t,o,s,a,u),i=!0})),r}function wt(t,e){if(!t)throw new Error("geojson is required");xt(t,(function(t,n,r){if(null!==t.geometry){var i=t.geometry.type,o=t.geometry.coordinates;switch(i){case"LineString":if(!1===e(t,n,r,0,0))return!1;break;case"Polygon":for(var s=0;s0){e+=Math.abs(Ot(t[0]));for(var n=1;n=e?(r+2)%e:r+2],a=i[0]*Tt,u=o[1]*Tt;n+=(s[0]*Tt-a)*Math.sin(u),r++}return n*Ct}function Rt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=t.bbox&&!0!==e.recompute)return t.bbox;var n=[1/0,1/0,-1/0,-1/0];return ct(t,(function(t){n[0]>t[0]&&(n[0]=t[0]),n[1]>t[1]&&(n[1]=t[1]),n[2]e[2]&&(n|=2),t[1]e[3]&&(n|=8),n}function qt(t,e){var n,r=[],i=a(t);try{for(i.s();!(n=i.n()).done;){var o=At(n.value,e);o.length>0&&(o[0][0]===o[o.length-1][0]&&o[0][1]===o[o.length-1][1]||o.push(o[0]),o.length>=4&&r.push(o))}}catch(t){i.e(t)}finally{i.f()}return r}function Vt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Number(t[0]),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]);if(6===t.length)throw new Error("@turf/bbox-polygon does not support BBox with 6 positions");var s=[n,r];return S([[s,[i,r],[i,o],[n,o],s]],e.properties,{bbox:t,id:e.id})}var Gt=function(){return s((function t(e){i(this,t),this.points=e.points||[],this.duration=e.duration||1e4,this.sharpness=e.sharpness||.85,this.centers=[],this.controls=[],this.stepLength=e.stepLength||60,this.length=this.points.length,this.delay=0;for(var n=0;nt&&(e.push(r),n=i)}return e}},{key:"vector",value:function(t){var e=this.pos(t+10),n=this.pos(t-10);return{angle:180*Math.atan2(e.y-n.y,e.x-n.x)/3.14,speed:Math.sqrt((n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y)+(n.z-e.z)*(n.z-e.z))}}},{key:"pos",value:function(t){var e=t-this.delay;e<0&&(e=0),e>this.duration&&(e=this.duration-1);var n=e/this.duration;if(n>=1)return this.points[this.length-1];var r=Math.floor((this.points.length-1)*n);return function(t,e,n,r,i){var o=function(t){var e=t*t,n=e*t;return[n,3*e*(1-t),3*t*(1-t)*(1-t),(1-t)*(1-t)*(1-t)]}(t),s={x:i.x*o[0]+r.x*o[1]+n.x*o[2]+e.x*o[3],y:i.y*o[0]+r.y*o[1]+n.y*o[2]+e.y*o[3],z:i.z*o[0]+r.z*o[1]+n.z*o[2]+e.z*o[3]};return s}((this.length-1)*n-r,this.points[r],this.controls[r][1],this.controls[r+1][0],this.points[r+1])}}])}();function Bt(t){for(var e,n,r=Q(t),i=0,o=1;o0}function Yt(t,e){for(var n=0,r=0,i=0,o=0,s=0,a=0,u=0,l=0,h=null,c=null,f=t[0],g=t[1],p=e.length;n0&&l>0)a=l,s=(h=c)[0]-f;else{if(u=c[0]-t[0],l>0&&a<=0){if((o=s*l-u*a)>0)i+=1;else if(0===o)return 0}else if(a>0&&l<=0){if((o=s*l-u*a)<0)i+=1;else if(0===o)return 0}else if(0===l&&a<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&l<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&0===l){if(u<=0&&s>=0)return 0;if(s<=0&&u>=0)return 0}h=c,a=l,s=u}}return i%2!=0}function zt(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("point is required");if(!e)throw new Error("polygon is required");var r=K(t),i=rt(e),o=i.type,s=e.bbox,a=i.coordinates;if(s&&!1===function(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}(r,s))return!1;"Polygon"===o&&(a=[a]);for(var u=!1,l=0;l2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=Q(e),o=0;oi)return!1}else if(0!==g)return!1;return Math.abs(c)===Math.abs(f)&&0===Math.abs(c)?!r&&(n[0]===t[0]&&n[1]===t[1]):r?"start"===r?Math.abs(c)>=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o0?u<=s&&s=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o<=l:l<=o&&o<=a:f>0?u<=s&&s<=h:h<=s&&s<=u}function Ut(t,e){if("Feature"===t.type&&null===t.geometry)return!1;if("Feature"===e.type&&null===e.geometry)return!1;if(!Zt(Rt(t),Rt(e)))return!1;var n,r=a(rt(e).coordinates);try{for(r.s();!(n=r.n()).done;){var i,o=a(n.value);try{for(o.s();!(i=o.n()).done;){if(!zt(i.value,t))return!1}}catch(t){o.e(t)}finally{o.f()}}}catch(t){r.e(t)}finally{r.f()}return!0}function Zt(t,e){return!(t[0]>e[0])&&(!(t[2]e[1])&&!(t[3]0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Kt;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function Kt(t,e){return te?1:0}function Qt(t,e){return t.p.x>e.p.x?1:t.p.xe.p.y?1:-1:1}function $t(t,e){return t.rightSweepEvent.p.x>e.rightSweepEvent.p.x?1:t.rightSweepEvent.p.x0?(h.isLeftEndpoint=!0,l.isLeftEndpoint=!1):(l.isLeftEndpoint=!0,h.isLeftEndpoint=!1),e.push(l),e.push(h),s=a,re+=1}}ee+=1}var oe=s((function t(e){i(this,t),this.leftSweepEvent=e,this.rightSweepEvent=e.otherEvent}));function se(t,e){if(null===t||null===e)return!1;if(t.leftSweepEvent.ringId===e.leftSweepEvent.ringId&&(t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.rightSweepEvent)||t.leftSweepEvent.isSamePoint(e.leftSweepEvent)||t.leftSweepEvent.isSamePoint(e.rightSweepEvent)))return!1;var n=t.leftSweepEvent.p.x,r=t.leftSweepEvent.p.y,i=t.rightSweepEvent.p.x,o=t.rightSweepEvent.p.y,s=e.leftSweepEvent.p.x,a=e.leftSweepEvent.p.y,u=e.rightSweepEvent.p.x,l=e.rightSweepEvent.p.y,h=(l-a)*(i-n)-(u-s)*(o-r),c=(u-s)*(r-a)-(l-a)*(n-s),f=(i-n)*(r-a)-(o-r)*(n-s);if(0===h)return!1;var g=c/h,p=f/h;return g>=0&&g<=1&&p>=0&&p<=1&&[n+g*(i-n),r+g*(o-r)]}var ae=function(t,e){var n=new Jt([],Qt);return function(t,e){if("FeatureCollection"===t.type)for(var n=t.features,r=0;r2&&void 0!==arguments[2]?arguments[2]:{},r=n.removeDuplicates,i=void 0===r||r,o=n.ignoreSelfIntersections,s=void 0===o||o,a=[];"FeatureCollection"===t.type?a=a.concat(t.features):"Feature"===t.type?a.push(t):"LineString"!==t.type&&"Polygon"!==t.type&&"MultiLineString"!==t.type&&"MultiPolygon"!==t.type||a.push(b(t)),"FeatureCollection"===e.type?a=a.concat(e.features):"Feature"===e.type?a.push(e):"LineString"!==e.type&&"Polygon"!==e.type&&"MultiLineString"!==e.type&&"MultiPolygon"!==e.type||a.push(b(e));var u=ae(C(a),s),l=[];if(i){var h={};u.forEach((function(t){var e=t.join(",");h[e]||(h[e]=!0,l.push(t))}))}else l=u;return C(l.map((function(t){return I(t)})))}function le(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t);switch(e.properties||"Feature"!==t.type||(e.properties=t.properties),n.type){case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{};return he(r,i)}(n,e);case"MultiPolygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{},o=[];return r.forEach((function(t){o.push(he(t,i))})),C(o)}(n,e);default:throw new Error("invalid poly")}}function he(t,e){return t.length>1?T(t,e):L(t[0],e)}function ce(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;switch(i){case"MultiPoint":switch(o){case"LineString":return fe(n,r);case"Polygon":return pe(n,r);default:throw new Error("feature2 "+o+" geometry not supported")}case"LineString":switch(o){case"MultiPoint":return fe(r,n);case"LineString":return function(t,e){if(ue(t,e).features.length>0)for(var n=0;n0}function pe(t,e){for(var n=!1,r=!1,i=t.coordinates.length,o=0;o=Math.abs(a)?s>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:a>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1]:Math.abs(s)>=Math.abs(a)?s>0?t[0]0?t[1]2&&void 0!==arguments[2]?arguments[2]:{ignoreSelfIntersections:!0}).ignoreSelfIntersections,r=void 0===n||n,i=!0;return xt(t,(function(t){xt(e,(function(e){if(!1===i)return!1;i=function(t,e,n){switch(t.type){case"Point":switch(e.type){case"Point":return r=t.coordinates,i=e.coordinates,!(r[0]===i[0]&&r[1]===i[1]);case"LineString":return!ye(e,t);case"Polygon":return!zt(t,e)}break;case"LineString":switch(e.type){case"Point":return!ye(t,e);case"LineString":return!function(t,e,n){var r=ue(t,e,{ignoreSelfIntersections:n});if(r.features.length>0)return!0;return!1}(t,e,n);case"Polygon":return!me(e,t,n)}break;case"Polygon":switch(e.type){case"Point":return!zt(e,t);case"LineString":return!me(t,e,n);case"Polygon":return!function(t,e,n){var r,i=a(t.coordinates[0]);try{for(i.s();!(r=i.n()).done;){if(zt(r.value,e))return!0}}catch(t){i.e(t)}finally{i.f()}var o,s=a(e.coordinates[0]);try{for(s.s();!(o=s.n()).done;){if(zt(o.value,t))return!0}}catch(t){s.e(t)}finally{s.f()}var u=ue(le(t),le(e),{ignoreSelfIntersections:n});if(u.features.length>0)return!0;return!1}(e,t,n)}}var r,i;return!1}(t.geometry,e.geometry,r)}))})),i}function ye(t,e){for(var n=0;n0}function _e(t,e,n){var r=n[0]-t[0],i=n[1]-t[1],o=e[0]-t[0],s=e[1]-t[1];return 0==r*s-i*o&&(Math.abs(o)>=Math.abs(s)?o>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:s>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1])}var xe=Object.defineProperty,Ee=function(t,e){return xe(t,"name",{value:e,configurable:!0})},ke=function(){return s((function t(e){var n,r,o;i(this,t),this.direction=!1,this.compareProperties=!0,this.precision=Math.pow(10,-(null!=(n=null==e?void 0:e.precision)?n:17)),this.direction=null!=(r=null==e?void 0:e.direction)&&r,this.compareProperties=null==(o=null==e?void 0:e.compareProperties)||o}),[{key:"compare",value:function(t,e){var n=this;if(t.type!==e.type)return!1;if(!we(t,e))return!1;switch(t.type){case"Point":return this.compareCoord(t.coordinates,e.coordinates);case"LineString":return this.compareLine(t.coordinates,e.coordinates);case"Polygon":return this.comparePolygon(t,e);case"GeometryCollection":return this.compareGeometryCollection(t,e);case"Feature":return this.compareFeature(t,e);case"FeatureCollection":return this.compareFeatureCollection(t,e);default:if(t.type.startsWith("Multi")){var r=Ie(t),i=Ie(e);return r.every((function(t){return i.some((function(e){return n.compare(t,e)}))}))}}return!1}},{key:"compareCoord",value:function(t,e){var n=this;return t.length===e.length&&t.every((function(t,r){return Math.abs(t-e[r])2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!we(t,e))return!1;var i=t,o=e;if(r&&!this.compareCoord(i[0],o[0])){var s=this.fixStartIndex(o,i);if(!s)return!1;o=s}var a=this.compareCoord(i[n],o[n]);return this.direction||a?this.comparePath(i,o):!!this.compareCoord(i[n],o[o.length-(1+n)])&&this.comparePath(i.slice().reverse(),o)}},{key:"fixStartIndex",value:function(t,e){for(var n,r=-1,i=0;i=0&&(n=[].concat(t.slice(r,t.length),t.slice(1,r+1))),n}},{key:"comparePath",value:function(t,e){var n=this;return t.every((function(t,r){return n.compareCoord(t,e[r])}))}},{key:"comparePolygon",value:function(t,e){var n=this;if(this.compareLine(t.coordinates[0],e.coordinates[0],1,!0)){var r=t.coordinates.slice(1,t.coordinates.length),i=e.coordinates.slice(1,e.coordinates.length);return r.every((function(t){return i.some((function(e){return n.compareLine(t,e,1,!0)}))}))}return!1}},{key:"compareGeometryCollection",value:function(t,e){var n=this;return we(t.geometries,e.geometries)&&this.compareBBox(t,e)&&t.geometries.every((function(t,r){return n.compare(t,e.geometries[r])}))}},{key:"compareFeature",value:function(t,e){return t.id===e.id&&(!this.compareProperties||Se(t.properties,e.properties))&&this.compareBBox(t,e)&&this.compare(t.geometry,e.geometry)}},{key:"compareFeatureCollection",value:function(t,e){var n=this;return we(t.features,e.features)&&this.compareBBox(t,e)&&t.features.every((function(t,r){return n.compare(t,e.features[r])}))}},{key:"compareBBox",value:function(t,e){return Boolean(!t.bbox&&!e.bbox)||!(!t.bbox||!e.bbox)&&this.compareCoord(t.bbox,e.bbox)}}])}();Ee(ke,"GeojsonEquality");var be=ke;function we(t,e){return t.coordinates?t.coordinates.length===e.coordinates.length:t.length===e.length}function Ie(t){return t.coordinates.map((function(e){return{type:t.type.replace("Multi",""),coordinates:e}}))}function Ne(t,e,n){return new be(n).compare(t,e)}function Se(t,e){if(null===t&&null===e)return!0;if(null===t||null===e)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(var i=0,o=n;i1&&void 0!==arguments[1]?arguments[1]:{},n="object"===m(e)?e.mutate:e;if(!t)throw new Error("geojson is required");var r=it(t),i=[];switch(r){case"LineString":i=Pe(t,r);break;case"MultiLineString":case"Polygon":Q(t).forEach((function(t){i.push(Pe(t,r))}));break;case"MultiPolygon":Q(t).forEach((function(t){var e=[];t.forEach((function(t){e.push(Pe(t,r))})),i.push(e)}));break;case"Point":return t;case"MultiPoint":var o={};Q(t).forEach((function(t){var e=t.join("-");Object.prototype.hasOwnProperty.call(o,e)||(i.push(t),o[e]=!0)}));break;default:throw new Error(r+" geometry not supported")}return t.coordinates?!0===n?(t.coordinates=i,t):{type:r,coordinates:i}:!0===n?(t.geometry.coordinates=i,t):b({type:r,coordinates:i},t.properties,{bbox:t.bbox,id:t.id})}function Pe(t,e){var n=Q(t);if(2===n.length&&!Ce(n[0],n[1]))return n;var r=[],i=n.length-1,o=r.length;r.push(n[0]);for(var s=1;s2&&Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1))}if(r.push(n[n.length-1]),o=r.length,("Polygon"===e||"MultiPolygon"===e)&&Ce(n[0],n[n.length-1])&&o<4)throw new Error("invalid polygon");return"LineString"===e&&o<3||Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1),r}function Ce(t,e){return t[0]===e[0]&&t[1]===e[1]}function Te(t,e,n){var r=n[0],i=n[1],o=t[0],s=t[1],a=e[0],u=e[1],l=a-o,h=u-s;return 0===(r-o)*h-(i-s)*l&&(Math.abs(l)>=Math.abs(h)?l>0?o<=r&&r<=a:a<=r&&r<=o:h>0?s<=i&&i<=u:u<=i&&i<=s)}function Oe(t,e){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).ignoreSelfIntersections,r=void 0===n||n,i=!1;return xt(t,(function(t){xt(e,(function(e){if(!0===i)return!0;i=!de(t.geometry,e.geometry,{ignoreSelfIntersections:r})}))})),i}function Re(t,e,n,r,i){Ae(t,e,n||0,r||t.length-1,i||Fe)}function Ae(t,e,n,r,i){for(;r>n;){if(r-n>600){var o=r-n+1,s=e-n+1,a=Math.log(o),u=.5*Math.exp(2*a/3),l=.5*Math.sqrt(a*u*(o-u)/o)*(s-o/2<0?-1:1);Ae(t,e,Math.max(n,Math.floor(e-s*u/o+l)),Math.min(r,Math.floor(e+(o-s)*u/o+l)),i)}var h=t[e],c=n,f=r;for(De(t,n,e),i(t[r],h)>0&&De(t,n,r);c0;)f--}0===i(t[n],h)?De(t,n,f):De(t,++f,r),f<=e&&(n=f+1),e<=f&&(r=f-1)}}function De(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function Fe(t,e){return te?1:0}var qe=function(){return s((function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:9;i(this,t),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}),[{key:"all",value:function(){return this._all(this.data,[])}},{key:"search",value:function(t){var e=this.data,n=[];if(!He(t,e))return n;for(var r=this.toBBox,i=[];e;){for(var o=0;o=0&&i[e].children.length>this._maxEntries;)this._split(i,e),e--;this._adjustParentBBoxes(r,i,e)}},{key:"_split",value:function(t,e){var n=t[e],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=We(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,Ge(n,this.toBBox),Ge(s,this.toBBox),e?t[e-1].children.push(s):this._splitRoot(n,s)}},{key:"_splitRoot",value:function(t,e){this.data=We([t,e]),this.data.height=t.height+1,this.data.leaf=!1,Ge(this.data,this.toBBox)}},{key:"_chooseSplitIndex",value:function(t,e,n){for(var r,i,o,s,a,u,l,h=1/0,c=1/0,f=e;f<=n-e;f++){var g=Be(t,0,f,this.toBBox),p=Be(t,f,n,this.toBBox),v=(i=g,o=p,s=void 0,a=void 0,u=void 0,l=void 0,s=Math.max(i.minX,o.minX),a=Math.max(i.minY,o.minY),u=Math.min(i.maxX,o.maxX),l=Math.min(i.maxY,o.maxY),Math.max(0,u-s)*Math.max(0,l-a)),d=Xe(g)+Xe(p);v=e;h--){var c=t.children[h];Ye(s,t.leaf?i(c):c),a+=Ue(s)}return a}},{key:"_adjustParentBBoxes",value:function(t,e,n){for(var r=n;r>=0;r--)Ye(e[r],t)}},{key:"_condense",value:function(t){for(var e,n=t.length-1;n>=0;n--)0===t[n].children.length?n>0?(e=t[n-1].children).splice(e.indexOf(t[n]),1):this.clear():Ge(t[n],this.toBBox)}}])}();function Ve(t,e,n){if(!n)return e.indexOf(t);for(var r=0;r=t.minX&&e.maxY>=t.minY}function We(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Je(t,e,n,r,i){for(var o=[e,n];o.length;)if(!((n=o.pop())-(e=o.pop())<=r)){var s=e+Math.ceil((n-e)/r/2)*r;Re(t,s,e,n,i),o.push(e,s,s,n)}}var Ke=Object.freeze({__proto__:null,default:qe});function Qe(t){var e=new qe(t);return e.insert=function(t){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.insert.call(this,t)},e.load=function(t){var e=[];return Array.isArray(t)?t.forEach((function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})):vt(t,(function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})),qe.prototype.load.call(this,e)},e.remove=function(t,e){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.remove.call(this,t,e)},e.clear=function(){return qe.prototype.clear.call(this)},e.search=function(t){return C(qe.prototype.search.call(this,this.toBBox(t)))},e.collides=function(t){return qe.prototype.collides.call(this,this.toBBox(t))},e.all=function(){return C(qe.prototype.all.call(this))},e.toJSON=function(){return qe.prototype.toJSON.call(this)},e.fromJSON=function(t){return qe.prototype.fromJSON.call(this,t)},e.toBBox=function(t){var e;if(t.bbox)e=t.bbox;else if(Array.isArray(t)&&4===t.length)e=t;else if(Array.isArray(t)&&6===t.length)e=[t[0],t[1],t[3],t[4]];else if("Feature"===t.type)e=Rt(t);else{if("FeatureCollection"!==t.type)throw new Error("invalid geojson");e=Rt(t)}return{minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}},e}function $e(t){if(!t)throw new Error("geojson is required");var e=[];return xt(t,(function(t){!function(t,e){var n=[],r=t.geometry;if(null!==r){switch(r.type){case"Polygon":n=Q(r);break;case"LineString":n=[Q(r)]}n.forEach((function(n){var r=function(t,e){var n=[];return t.reduce((function(t,r){var i=L([t,r],e);return i.bbox=function(t,e){var n=t[0],r=t[1],i=e[0],o=e[1],s=ni?n:i,l=r>o?r:o;return[s,a,u,l]}(t,r),n.push(i),r})),n}(n,t.properties);r.forEach((function(t){t.id=e.length,e.push(t)}))}))}}(t,e)})),C(e)}var tn,en,nn=Object.defineProperty,rn=Object.defineProperties,on=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertySymbols,an=Object.prototype.hasOwnProperty,un=Object.prototype.propertyIsEnumerable,ln=function(t,e,n){return e in t?nn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},hn=function(t,e){for(var n in e||(e={}))an.call(e,n)&&ln(t,n,e[n]);if(sn){var r,i=a(sn(e));try{for(i.s();!(r=i.n()).done;){n=r.value;un.call(e,n)&&ln(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},cn=function(t,e){return rn(t,on(e))};function fn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t||!e)throw new Error("lines and pt are required arguments");var r=K(e),i=I([1/0,1/0],{dist:1/0,index:-1,multiFeatureIndex:-1,location:-1}),o=0;return xt(t,(function(t,s,a){for(var u=Q(t),l=0;lR||pn(p,f)>R?ut(dn(f),dn(g))<=ut(dn(f),dn(p))?[dn(g),!0,!1]:[dn(p),!1,!0]:[dn(f),!1,!1]}function mn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function _n(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var n=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,r.get?r:{enumerable:!0,get:function(){return t[e]}})})),n}var xn=(en||(en=1,tn=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==m(e)&&"object"==m(n)){if(e.constructor!==n.constructor)return!1;var r,i,o;if(Array.isArray(e)){if((r=e.length)!=n.length)return!1;for(i=r;0!=i--;)if(!t(e[i],n[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((r=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(i=r;0!=i--;)if(!Object.prototype.hasOwnProperty.call(n,o[i]))return!1;for(i=r;0!=i--;){var s=o[i];if(!t(e[s],n[s]))return!1}return!0}return e!=e&&n!=n}),tn),En=mn(xn);function kn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r,i=n.tolerance||0,o=[],s=Qe(),a=$e(t);s.load(a);var u=[];return kt(e,(function(t){var e=!1;t&&(vt(s.search(t),(function(n){if(!1===e){var o=Q(t).sort(),s=Q(n).sort();if(En(o,s))e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(o[0],n)&&jt(o[1],n):fn(n,o[0]).properties.dist<=i&&fn(n,o[1]).properties.dist<=i)e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(s[0],t)&&jt(s[1],t):fn(t,s[0]).properties.dist<=i&&fn(t,s[1]).properties.dist<=i)if(r){var a=bn(r,n);a?r=a:u.push(n)}else r=n}})),!1===e&&r&&(o.push(r),u.length&&(o=o.concat(u),u=[]),r=void 0))})),r&&o.push(r),C(o)}function bn(t,e){var n=Q(e),r=Q(t),i=r[0],o=r[r.length-1],s=t.geometry.coordinates;if(En(n[0],i))s.unshift(n[1]);else if(En(n[0],o))s.push(n[1]);else if(En(n[1],i))s.unshift(n[0]);else{if(!En(n[1],o))return;s.push(n[0])}return t}function wn(t,e){var n=G(lt(t[0],t[1])),r=G(lt(e[0],e[1]));return n===r||(r-n)%180==0}function In(t,e){if(t.geometry&&t.geometry.type)return t.geometry.type;if(t.type)return t.type;throw new Error("Invalid GeoJSON object for "+e)}function Nn(t,e){return!!Sn(e.coordinates[0],t.coordinates)||!!Sn(e.coordinates[e.coordinates.length-1],t.coordinates)}function Sn(t,e){return t[0]===e[0]&&t[1]===e[1]}function Mn(t){return t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]}function Ln(t){for(var e=0;ee[0])&&(!(t[2]e[1])&&!(t[3]1&&void 0!==arguments[1]?arguments[1]:{},n=Rt(t);return I([(n[0]+n[2])/2,(n[1]+n[3])/2],e.properties,e)}var Dn,Fn={exports:{}};var qn=(Dn||(Dn=1,function(t,e){t.exports=function(){function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}var y=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getEndCapStyle",value:function(){return this._endCapStyle}},{key:"isSingleSided",value:function(){return this._isSingleSided}},{key:"setQuadrantSegments",value:function(t){this._quadrantSegments=t,0===this._quadrantSegments&&(this._joinStyle=e.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=e.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),t<=0&&(this._quadrantSegments=1),this._joinStyle!==e.JOIN_ROUND&&(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS)}},{key:"getJoinStyle",value:function(){return this._joinStyle}},{key:"setJoinStyle",value:function(t){this._joinStyle=t}},{key:"setSimplifyFactor",value:function(t){this._simplifyFactor=t<0?0:t}},{key:"getSimplifyFactor",value:function(){return this._simplifyFactor}},{key:"getQuadrantSegments",value:function(){return this._quadrantSegments}},{key:"setEndCapStyle",value:function(t){this._endCapStyle=t}},{key:"getMitreLimit",value:function(){return this._mitreLimit}},{key:"setMitreLimit",value:function(t){this._mitreLimit=t}},{key:"setSingleSided",value:function(t){this._isSingleSided=t}}],[{key:"constructor_",value:function(){if(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=e.CAP_ROUND,this._joinStyle=e.JOIN_ROUND,this._mitreLimit=e.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=e.DEFAULT_SIMPLIFY_FACTOR,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.setQuadrantSegments(t)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.setQuadrantSegments(n),this.setEndCapStyle(r)}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];this.setQuadrantSegments(i),this.setEndCapStyle(o),this.setJoinStyle(s),this.setMitreLimit(a)}}},{key:"bufferDistanceError",value:function(t){var e=Math.PI/2/t;return 1-Math.cos(e/2)}}]),e}();y.CAP_ROUND=1,y.CAP_FLAT=2,y.CAP_SQUARE=3,y.JOIN_ROUND=1,y.JOIN_MITRE=2,y.JOIN_BEVEL=3,y.DEFAULT_QUADRANT_SEGMENTS=8,y.DEFAULT_MITRE_LIMIT=5,y.DEFAULT_SIMPLIFY_FACTOR=.01;var _=function(e){r(o,e);var i=c(o);function o(e){var n;return t(this,o),(n=i.call(this,e)).name=Object.keys({Exception:o})[0],n}return n(o,[{key:"toString",value:function(){return this.message}}]),o}(u(Error)),x=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({IllegalArgumentException:i})[0],r}return i}(_),E=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}();function k(){}function b(){}function w(){}var I,N,S,M,L,P,C,T,O=function(){function e(){t(this,e)}return n(e,null,[{key:"equalsWithTolerance",value:function(t,e,n){return Math.abs(t-e)<=n}}]),e}(),R=function(){function e(n,r){t(this,e),this.low=r||0,this.high=n||0}return n(e,null,[{key:"toBinaryString",value:function(t){var e,n="";for(e=2147483648;e>0;e>>>=1)n+=(t.high&e)===e?"1":"0";for(e=2147483648;e>0;e>>>=1)n+=(t.low&e)===e?"1":"0";return n}}]),e}();function A(){}function D(){}A.NaN=NaN,A.isNaN=function(t){return Number.isNaN(t)},A.isInfinite=function(t){return!Number.isFinite(t)},A.MAX_VALUE=Number.MAX_VALUE,A.POSITIVE_INFINITY=Number.POSITIVE_INFINITY,A.NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,"function"==typeof Float64Array&&"function"==typeof Int32Array?(P=2146435072,C=new Float64Array(1),T=new Int32Array(C.buffer),A.doubleToLongBits=function(t){C[0]=t;var e=0|T[0],n=0|T[1];return(n&P)===P&&0!=(1048575&n)&&0!==e&&(e=0,n=2146959360),new R(n,e)},A.longBitsToDouble=function(t){return T[0]=t.low,T[1]=t.high,C[0]}):(I=1023,N=Math.log2,S=Math.floor,M=Math.pow,L=function(){for(var t=53;t>0;t--){var e=M(2,t)-1;if(S(N(e))+1===t)return e}return 0}(),A.doubleToLongBits=function(t){var e,n,r,i,o,s,a,u,l;if(t<0||1/t===Number.NEGATIVE_INFINITY?(s=1<<31,t=-t):s=0,0===t)return new R(u=s,l=0);if(t===1/0)return new R(u=2146435072|s,l=0);if(t!=t)return new R(u=2146959360,l=0);if(i=0,l=0,(e=S(t))>1)if(e<=L)(i=S(N(e)))<=20?(l=0,u=e<<20-i&1048575):(l=e%(n=M(2,r=i-20))<<32-r,u=e/n&1048575);else for(r=e,l=0;0!==(r=S(n=r/2));)i++,l>>>=1,l|=(1&u)<<31,u>>>=1,n!==r&&(u|=524288);if(a=i+I,o=0===e,e=t-e,i<52&&0!==e)for(r=0;;){if((n=2*e)>=1?(e=n-1,o?(a--,o=!1):(r<<=1,r|=1,i++)):(e=n,o?0==--a&&(i++,o=!1):(r<<=1,i++)),20===i)u|=r,r=0;else if(52===i){l|=r;break}if(1===n){i<20?u|=r<<20-i:i<52&&(l|=r<<52-i);break}}return u|=a<<20,new R(u|=s,l)},A.longBitsToDouble=function(t){var e,n,r,i,o=t.high,s=t.low,a=o&1<<31?-1:1;for(r=((2146435072&o)>>20)-I,i=0,n=1<<19,e=1;e<=20;e++)o&n&&(i+=M(2,-e)),n>>>=1;for(n=1<<31,e=21;e<=52;e++)s&n&&(i+=M(2,-e)),n>>>=1;if(-1023===r){if(0===i)return 0*a;r=-1022}else{if(1024===r)return 0===i?a/0:NaN;i+=1}return a*i*M(2,r)});var F=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({RuntimeException:i})[0],r}return i}(_),q=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){if(0===arguments.length)F.constructor_.call(this);else if(1===arguments.length){var t=arguments[0];F.constructor_.call(this,t)}}}]),o}(F),V=function(){function e(){t(this,e)}return n(e,null,[{key:"shouldNeverReachHere",value:function(){if(0===arguments.length)e.shouldNeverReachHere(null);else if(1===arguments.length){var t=arguments[0];throw new q("Should never reach here"+(null!==t?": "+t:""))}}},{key:"isTrue",value:function(){if(1===arguments.length){var t=arguments[0];e.isTrue(t,null)}else if(2===arguments.length){var n=arguments[1];if(!arguments[0])throw null===n?new q:new q(n)}}},{key:"equals",value:function(){if(2===arguments.length){var t=arguments[0],n=arguments[1];e.equals(t,n,null)}else if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2];if(!i.equals(r))throw new q("Expected "+r+" but encountered "+i+(null!==o?": "+o:""))}}}]),e}(),G=new ArrayBuffer(8),B=new Float64Array(G),Y=new Int32Array(G),z=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getM",value:function(){return A.NaN}},{key:"setOrdinate",value:function(t,n){switch(t){case e.X:this.x=n;break;case e.Y:this.y=n;break;case e.Z:this.setZ(n);break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"equals2D",value:function(){if(1===arguments.length){var t=arguments[0];return this.x===t.x&&this.y===t.y}if(2===arguments.length){var e=arguments[0],n=arguments[1];return!!O.equalsWithTolerance(this.x,e.x,n)&&!!O.equalsWithTolerance(this.y,e.y,n)}}},{key:"setM",value:function(t){throw new x("Invalid ordinate index: "+e.M)}},{key:"getZ",value:function(){return this.z}},{key:"getOrdinate",value:function(t){switch(t){case e.X:return this.x;case e.Y:return this.y;case e.Z:return this.getZ()}throw new x("Invalid ordinate index: "+t)}},{key:"equals3D",value:function(t){return this.x===t.x&&this.y===t.y&&(this.getZ()===t.getZ()||A.isNaN(this.getZ())&&A.isNaN(t.getZ()))}},{key:"equals",value:function(t){return t instanceof e&&this.equals2D(t)}},{key:"equalInZ",value:function(t,e){return O.equalsWithTolerance(this.getZ(),t.getZ(),e)}},{key:"setX",value:function(t){this.x=t}},{key:"compareTo",value:function(t){var e=t;return this.xe.x?1:this.ye.y?1:0}},{key:"getX",value:function(){return this.x}},{key:"setZ",value:function(t){this.z=t}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return V.shouldNeverReachHere("this shouldn't happen because this class is Cloneable"),null;throw t}}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+")"}},{key:"distance3D",value:function(t){var e=this.x-t.x,n=this.y-t.y,r=this.getZ()-t.getZ();return Math.sqrt(e*e+n*n+r*r)}},{key:"getY",value:function(){return this.y}},{key:"setY",value:function(t){this.y=t}},{key:"distance",value:function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*t+e.hashCode(this.x))+e.hashCode(this.y)}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}},{key:"interfaces_",get:function(){return[k,b,w]}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.z=null,0===arguments.length)e.constructor_.call(this,0,0);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.x,t.y,t.getZ())}else if(2===arguments.length){var n=arguments[0],r=arguments[1];e.constructor_.call(this,n,r,e.NULL_ORDINATE)}else if(3===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2];this.x=i,this.y=o,this.z=s}}},{key:"hashCode",value:function(t){return B[0]=t,Y[0]^Y[1]}}]),e}(),j=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compare",value:function(t,n){var r=e.compare(t.x,n.x);if(0!==r)return r;var i=e.compare(t.y,n.y);return 0!==i?i:this._dimensionsToTest<=2?0:e.compare(t.getZ(),n.getZ())}},{key:"interfaces_",get:function(){return[D]}}],[{key:"constructor_",value:function(){if(this._dimensionsToTest=2,0===arguments.length)e.constructor_.call(this,2);else if(1===arguments.length){var t=arguments[0];if(2!==t&&3!==t)throw new x("only 2 or 3 dimensions may be specified");this._dimensionsToTest=t}}},{key:"compare",value:function(t,e){return te?1:A.isNaN(t)?A.isNaN(e)?0:-1:A.isNaN(e)?1:0}}]),e}();z.DimensionalComparator=j,z.NULL_ORDINATE=A.NaN,z.X=0,z.Y=1,z.Z=2,z.M=3;var X=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getArea",value:function(){return this.getWidth()*this.getHeight()}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.isNull()?n.isNull():this._maxx===n.getMaxX()&&this._maxy===n.getMaxY()&&this._minx===n.getMinX()&&this._miny===n.getMinY()}},{key:"intersection",value:function(t){if(this.isNull()||t.isNull()||!this.intersects(t))return new e;var n=this._minx>t._minx?this._minx:t._minx,r=this._miny>t._miny?this._miny:t._miny;return new e(n,this._maxx=this._minx&&n.getMaxX()<=this._maxx&&n.getMinY()>=this._miny&&n.getMaxY()<=this._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return!this.isNull()&&r>=this._minx&&r<=this._maxx&&i>=this._miny&&i<=this._maxy}}},{key:"intersects",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return!this.isNull()&&!t.isNull()&&!(t._minx>this._maxx||t._maxxthis._maxy||t._maxythis._maxx||(r.x>i.x?r.x:i.x)this._maxy||(r.y>i.y?r.y:i.y)this._maxx||othis._maxy||sthis._maxx&&(this._maxx=n._maxx),n._minythis._maxy&&(this._maxy=n._maxy))}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.isNull()?(this._minx=r,this._maxx=r,this._miny=i,this._maxy=i):(rthis._maxx&&(this._maxx=r),ithis._maxy&&(this._maxy=i))}}},{key:"minExtent",value:function(){if(this.isNull())return 0;var t=this.getWidth(),e=this.getHeight();return te._minx?1:this._minye._miny?1:this._maxxe._maxx?1:this._maxye._maxy?1:0}},{key:"translate",value:function(t,e){if(this.isNull())return null;this.init(this.getMinX()+t,this.getMaxX()+t,this.getMinY()+e,this.getMaxY()+e)}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"Env["+this._minx+" : "+this._maxx+", "+this._miny+" : "+this._maxy+"]"}},{key:"setToNull",value:function(){this._minx=0,this._maxx=-1,this._miny=0,this._maxy=-1}},{key:"disjoint",value:function(t){return!(!this.isNull()&&!t.isNull())||t._minx>this._maxx||t._maxxthis._maxy||t._maxye?t:e}},{key:"expandBy",value:function(){if(1===arguments.length){var t=arguments[0];this.expandBy(t,t)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];if(this.isNull())return null;this._minx-=e,this._maxx+=e,this._miny-=n,this._maxy+=n,(this._minx>this._maxx||this._miny>this._maxy)&&this.setToNull()}}},{key:"contains",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.covers(t)}if(arguments[0]instanceof z){var n=arguments[0];return this.covers(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return this.covers(r,i)}}},{key:"centre",value:function(){return this.isNull()?null:new z((this.getMinX()+this.getMaxX())/2,(this.getMinY()+this.getMaxY())/2)}},{key:"init",value:function(){if(0===arguments.length)this.setToNull();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this._minx=n._minx,this._maxx=n._maxx,this._miny=n._miny,this._maxy=n._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];ot._maxx&&(e=this._minx-t._maxx);var n=0;return this._maxyt._maxy&&(n=this._miny-t._maxy),0===e?n:0===n?e:Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*(t=37*(t=37*t+z.hashCode(this._minx))+z.hashCode(this._maxx))+z.hashCode(this._miny))+z.hashCode(this._maxy)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,0===arguments.length)this.init();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];this.init(o,s,a,u)}}},{key:"intersects",value:function(){if(3===arguments.length){var t=arguments[0],e=arguments[1],n=arguments[2];return n.x>=(t.xe.x?t.x:e.x)&&n.y>=(t.ye.y?t.y:e.y)}if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=arguments[3],a=Math.min(o.x,s.x),u=Math.max(o.x,s.x),l=Math.min(r.x,i.x),h=Math.max(r.x,i.x);return!(l>u||hu||h=this.size())throw new nt;return this.array[t]}},{key:"push",value:function(t){return this.array.push(t),t}},{key:"pop",value:function(){if(0===this.array.length)throw new et;return this.array.pop()}},{key:"peek",value:function(){if(0===this.array.length)throw new et;return this.array[this.array.length-1]}},{key:"empty",value:function(){return 0===this.array.length}},{key:"isEmpty",value:function(){return this.empty()}},{key:"search",value:function(t){return this.array.indexOf(t)}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}}]),o}(rt);function ot(t,e){return t.interfaces_&&t.interfaces_.indexOf(e)>-1}var st=function(){function e(n){t(this,e),this.str=n}return n(e,[{key:"append",value:function(t){this.str+=t}},{key:"setCharAt",value:function(t,e){this.str=this.str.substr(0,t)+e+this.str.substr(t+1)}},{key:"toString",value:function(){return this.str}}]),e}(),at=function(){function e(n){t(this,e),this.value=n}return n(e,[{key:"intValue",value:function(){return this.value}},{key:"compareTo",value:function(t){return this.valuet?1:0}}],[{key:"compare",value:function(t,e){return te?1:0}},{key:"isNan",value:function(t){return Number.isNaN(t)}},{key:"valueOf",value:function(t){return new e(t)}}]),e}(),ut=function(){function e(){t(this,e)}return n(e,null,[{key:"isWhitespace",value:function(t){return t<=32&&t>=0||127===t}},{key:"toUpperCase",value:function(t){return t.toUpperCase()}}]),e}(),lt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"le",value:function(t){return this._hi9?(c=!0,f="9"):f="0"+h,a.append(f),r=r.subtract(e.valueOf(h)).multiply(e.TEN),c&&r.selfAdd(e.TEN);var g=!0,p=e.magnitude(r._hi);if(p<0&&Math.abs(p)>=u-l&&(g=!1),!g)break}return n[0]=i,a.toString()}},{key:"sqr",value:function(){return this.multiply(this)}},{key:"doubleValue",value:function(){return this._hi+this._lo}},{key:"subtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.add(t.negate())}if("number"==typeof arguments[0]){var n=arguments[0];return this.add(-n)}}},{key:"equals",value:function(){if(1===arguments.length&&arguments[0]instanceof e){var t=arguments[0];return this._hi===t._hi&&this._lo===t._lo}}},{key:"isZero",value:function(){return 0===this._hi&&0===this._lo}},{key:"selfSubtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.isNaN()?this:this.selfAdd(-t._hi,-t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.isNaN()?this:this.selfAdd(-n,0)}}},{key:"getSpecialNumberString",value:function(){return this.isZero()?"0.0":this.isNaN()?"NaN ":null}},{key:"min",value:function(t){return this.le(t)?this:t}},{key:"selfDivide",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfDivide(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfDivide(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null,c=null,f=null;return l=this._hi/r,f=(o=(h=e.SPLIT*l)-(o=h-l))*(a=(f=e.SPLIT*r)-(a=f-r))-(c=l*r)+o*(u=r-a)+(s=l-o)*a+s*u,f=l+(h=(this._hi-c-f+this._lo-l*i)/r),this._hi=f,this._lo=l-f+h,this}}},{key:"dump",value:function(){return"DD<"+this._hi+", "+this._lo+">"}},{key:"divide",value:function(){if(arguments[0]instanceof e){var t=arguments[0],n=null,r=null,i=null,o=null,s=null,a=null,u=null,l=null;return r=(s=this._hi/t._hi)-(n=(a=e.SPLIT*s)-(n=a-s)),l=n*(i=(l=e.SPLIT*t._hi)-(i=l-t._hi))-(u=s*t._hi)+n*(o=t._hi-i)+r*i+r*o,new e(l=s+(a=(this._hi-u-l+this._lo-s*t._lo)/t._hi),s-l+a)}if("number"==typeof arguments[0]){var h=arguments[0];return A.isNaN(h)?e.createNaN():e.copy(this).selfDivide(h,0)}}},{key:"ge",value:function(t){return this._hi>t._hi||this._hi===t._hi&&this._lo>=t._lo}},{key:"pow",value:function(t){if(0===t)return e.valueOf(1);var n=new e(this),r=e.valueOf(1),i=Math.abs(t);if(i>1)for(;i>0;)i%2==1&&r.selfMultiply(n),(i/=2)>0&&(n=n.sqr());else r=n;return t<0?r.reciprocal():r}},{key:"ceil",value:function(){if(this.isNaN())return e.NaN;var t=Math.ceil(this._hi),n=0;return t===this._hi&&(n=Math.ceil(this._lo)),new e(t,n)}},{key:"compareTo",value:function(t){var e=t;return this._hie._hi?1:this._loe._lo?1:0}},{key:"rint",value:function(){return this.isNaN()?this:this.add(.5).floor()}},{key:"setValue",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.init(t),this}if("number"==typeof arguments[0]){var n=arguments[0];return this.init(n),this}}},{key:"max",value:function(t){return this.ge(t)?this:t}},{key:"sqrt",value:function(){if(this.isZero())return e.valueOf(0);if(this.isNegative())return e.NaN;var t=1/Math.sqrt(this._hi),n=this._hi*t,r=e.valueOf(n),i=this.subtract(r.sqr())._hi*(.5*t);return r.add(i)}},{key:"selfAdd",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfAdd(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0],r=null,i=null,o=null,s=null,a=null,u=null;return s=(o=this._hi+n)-(a=o-this._hi),i=(u=(s=n-a+(this._hi-s))+this._lo)+(o-(r=o+u)),this._hi=r+i,this._lo=i+(r-this._hi),this}}else if(2===arguments.length){var l=arguments[0],h=arguments[1],c=null,f=null,g=null,p=null,v=null,d=null,y=null;p=this._hi+l,f=this._lo+h,v=p-(d=p-this._hi),g=f-(y=f-this._lo);var m=(c=p+(d=(v=l-d+(this._hi-v))+f))+(d=(g=h-y+(this._lo-g))+(d+(p-c))),_=d+(c-m);return this._hi=m,this._lo=_,this}}},{key:"selfMultiply",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfMultiply(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfMultiply(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null;o=(l=e.SPLIT*this._hi)-this._hi,h=e.SPLIT*r,o=l-o,s=this._hi-o,a=h-r;var c=(l=this._hi*r)+(h=o*(a=h-a)-l+o*(u=r-a)+s*a+s*u+(this._hi*i+this._lo*r)),f=h+(o=l-c);return this._hi=c,this._lo=f,this}}},{key:"selfSqr",value:function(){return this.selfMultiply(this)}},{key:"floor",value:function(){if(this.isNaN())return e.NaN;var t=Math.floor(this._hi),n=0;return t===this._hi&&(n=Math.floor(this._lo)),new e(t,n)}},{key:"negate",value:function(){return this.isNaN()?this:new e(-this._hi,-this._lo)}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return null;throw t}}},{key:"multiply",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return t.isNaN()?e.createNaN():e.copy(this).selfMultiply(t)}if("number"==typeof arguments[0]){var n=arguments[0];return A.isNaN(n)?e.createNaN():e.copy(this).selfMultiply(n,0)}}},{key:"isNaN",value:function(){return A.isNaN(this._hi)}},{key:"intValue",value:function(){return Math.trunc(this._hi)}},{key:"toString",value:function(){var t=e.magnitude(this._hi);return t>=-3&&t<=20?this.toStandardNotation():this.toSciNotation()}},{key:"toStandardNotation",value:function(){var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!0,n),i=n[0]+1,o=r;if("."===r.charAt(0))o="0"+r;else if(i<0)o="0."+e.stringOfChar("0",-i)+r;else if(-1===r.indexOf(".")){var s=i-r.length;o=r+e.stringOfChar("0",s)+".0"}return this.isNegative()?"-"+o:o}},{key:"reciprocal",value:function(){var t,n,r,i,o=null,s=null,a=null,u=null;t=(r=1/this._hi)-(o=(a=e.SPLIT*r)-(o=a-r)),s=(u=e.SPLIT*this._hi)-this._hi;var l=r+(a=(1-(i=r*this._hi)-(u=o*(s=u-s)-i+o*(n=this._hi-s)+t*s+t*n)-r*this._lo)/this._hi);return new e(l,r-l+a)}},{key:"toSciNotation",value:function(){if(this.isZero())return e.SCI_NOT_ZERO;var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!1,n),i=e.SCI_NOT_EXPONENT_CHAR+n[0];if("0"===r.charAt(0))throw new IllegalStateException("Found leading zero: "+r);var o="";r.length>1&&(o=r.substring(1));var s=r.charAt(0)+"."+o;return this.isNegative()?"-"+s+i:s+i}},{key:"abs",value:function(){return this.isNaN()?e.NaN:this.isNegative()?this.negate():new e(this)}},{key:"isPositive",value:function(){return this._hi>0||0===this._hi&&this._lo>0}},{key:"lt",value:function(t){return this._hit._hi||this._hi===t._hi&&this._lo>t._lo}},{key:"isNegative",value:function(){return this._hi<0||0===this._hi&&this._lo<0}},{key:"trunc",value:function(){return this.isNaN()?e.NaN:this.isPositive()?this.floor():this.ceil()}},{key:"signum",value:function(){return this._hi>0?1:this._hi<0?-1:this._lo>0?1:this._lo<0?-1:0}},{key:"interfaces_",get:function(){return[w,k,b]}}],[{key:"constructor_",value:function(){if(this._hi=0,this._lo=0,0===arguments.length)this.init(0);else if(1===arguments.length){if("number"==typeof arguments[0]){var t=arguments[0];this.init(t)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}else if("string"==typeof arguments[0]){var r=arguments[0];e.constructor_.call(this,e.parse(r))}}else if(2===arguments.length){var i=arguments[0],o=arguments[1];this.init(i,o)}}},{key:"determinant",value:function(){if("number"==typeof arguments[3]&&"number"==typeof arguments[2]&&"number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1],r=arguments[2],i=arguments[3];return e.determinant(e.valueOf(t),e.valueOf(n),e.valueOf(r),e.valueOf(i))}if(arguments[3]instanceof e&&arguments[2]instanceof e&&arguments[0]instanceof e&&arguments[1]instanceof e){var o=arguments[1],s=arguments[2],a=arguments[3];return arguments[0].multiply(a).selfSubtract(o.multiply(s))}}},{key:"sqr",value:function(t){return e.valueOf(t).selfMultiply(t)}},{key:"valueOf",value:function(){if("string"==typeof arguments[0]){var t=arguments[0];return e.parse(t)}if("number"==typeof arguments[0])return new e(arguments[0])}},{key:"sqrt",value:function(t){return e.valueOf(t).sqrt()}},{key:"parse",value:function(t){for(var n=0,r=t.length;ut.isWhitespace(t.charAt(n));)n++;var i=!1;if(n=r);){var c=t.charAt(n);if(n++,ut.isDigit(c)){var f=c-"0";s.selfMultiply(e.TEN),s.selfAdd(f),a++}else{if("."!==c){if("e"===c||"E"===c){var g=t.substring(n);try{l=at.parseInt(g)}catch(e){throw e instanceof NumberFormatException?new NumberFormatException("Invalid exponent "+g+" in string "+t):e}break}throw new NumberFormatException("Unexpected character '"+c+"' at position "+n+" in string "+t)}u=a,h=!0}}var p=s;h||(u=a);var v=a-u-l;if(0===v)p=s;else if(v>0){var d=e.TEN.pow(v);p=s.divide(d)}else if(v<0){var y=e.TEN.pow(-v);p=s.multiply(y)}return i?p.negate():p}},{key:"createNaN",value:function(){return new e(A.NaN,A.NaN)}},{key:"copy",value:function(t){return new e(t)}},{key:"magnitude",value:function(t){var e=Math.abs(t),n=Math.log(e)/Math.log(10),r=Math.trunc(Math.floor(n));return 10*Math.pow(10,r)<=e&&(r+=1),r}},{key:"stringOfChar",value:function(t,e){for(var n=new st,r=0;r0){if(s<=0)return e.signum(a);i=o+s}else{if(!(o<0))return e.signum(a);if(s>=0)return e.signum(a);i=-o-s}var u=e.DP_SAFE_EPSILON*i;return a>=u||-a>=u?e.signum(a):2}},{key:"signum",value:function(t){return t>0?1:t<0?-1:0}}]),e}();ht.DP_SAFE_EPSILON=1e-15;var ct=function(){function e(){t(this,e)}return n(e,[{key:"getM",value:function(t){if(this.hasM()){var e=this.getDimension()-this.getMeasures();return this.getOrdinate(t,e)}return A.NaN}},{key:"setOrdinate",value:function(t,e,n){}},{key:"getZ",value:function(t){return this.hasZ()?this.getOrdinate(t,2):A.NaN}},{key:"size",value:function(){}},{key:"getOrdinate",value:function(t,e){}},{key:"getCoordinate",value:function(){}},{key:"getCoordinateCopy",value:function(t){}},{key:"createCoordinate",value:function(){}},{key:"getDimension",value:function(){}},{key:"hasM",value:function(){return this.getMeasures()>0}},{key:"getX",value:function(t){}},{key:"hasZ",value:function(){return this.getDimension()-this.getMeasures()>2}},{key:"getMeasures",value:function(){return 0}},{key:"expandEnvelope",value:function(t){}},{key:"copy",value:function(){}},{key:"getY",value:function(t){}},{key:"toCoordinateArray",value:function(){}},{key:"interfaces_",get:function(){return[b]}}]),e}();ct.X=0,ct.Y=1,ct.Z=2,ct.M=3;var ft=function(){function e(){t(this,e)}return n(e,null,[{key:"index",value:function(t,e,n){return ht.orientationIndex(t,e,n)}},{key:"isCCW",value:function(){if(arguments[0]instanceof Array){var t=arguments[0],n=t.length-1;if(n<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var r=t[0],i=0,o=1;o<=n;o++){var s=t[o];s.y>r.y&&(r=s,i=o)}var a=i;do{(a-=1)<0&&(a=n)}while(t[a].equals2D(r)&&a!==i);var u=i;do{u=(u+1)%n}while(t[u].equals2D(r)&&u!==i);var l=t[a],h=t[u];if(l.equals2D(r)||h.equals2D(r)||l.equals2D(h))return!1;var c=e.index(l,r,h);return 0===c?l.x>h.x:c>0}if(ot(arguments[0],ct)){var f=arguments[0],g=f.size()-1;if(g<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var p=f.getCoordinate(0),v=0,d=1;d<=g;d++){var y=f.getCoordinate(d);y.y>p.y&&(p=y,v=d)}var m=null,_=v;do{(_-=1)<0&&(_=g),m=f.getCoordinate(_)}while(m.equals2D(p)&&_!==v);var E=null,k=v;do{k=(k+1)%g,E=f.getCoordinate(k)}while(E.equals2D(p)&&k!==v);if(m.equals2D(p)||E.equals2D(p)||m.equals2D(E))return!1;var b=e.index(m,p,E);return 0===b?m.x>E.x:b>0}}}]),e}();ft.CLOCKWISE=-1,ft.RIGHT=ft.CLOCKWISE,ft.COUNTERCLOCKWISE=1,ft.LEFT=ft.COUNTERCLOCKWISE,ft.COLLINEAR=0,ft.STRAIGHT=ft.COLLINEAR;var gt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this._minCoord}},{key:"getRightmostSide",value:function(t,e){var n=this.getRightmostSideOfSegment(t,e);return n<0&&(n=this.getRightmostSideOfSegment(t,e-1)),n<0&&(this._minCoord=null,this.checkForRightmostCoordinate(t)),n}},{key:"findRightmostEdgeAtVertex",value:function(){var t=this._minDe.getEdge().getCoordinates();V.isTrue(this._minIndex>0&&this._minIndexthis._minCoord.y&&n.y>this._minCoord.y&&r===ft.CLOCKWISE)&&(i=!0),i&&(this._minIndex=this._minIndex-1)}},{key:"getRightmostSideOfSegment",value:function(t,e){var n=t.getEdge().getCoordinates();if(e<0||e+1>=n.length)return-1;if(n[e].y===n[e+1].y)return-1;var r=tt.LEFT;return n[e].ythis._minCoord.x)&&(this._minDe=t,this._minIndex=n,this._minCoord=e[n])}},{key:"findRightmostEdgeAtNode",value:function(){var t=this._minDe.getNode().getEdges();this._minDe=t.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)}},{key:"findEdge",value:function(t){for(var e=t.iterator();e.hasNext();){var n=e.next();n.isForward()&&this.checkForRightmostCoordinate(n)}V.isTrue(0!==this._minIndex||this._minCoord.equals(this._minDe.getCoordinate()),"inconsistency in rightmost processing"),0===this._minIndex?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe,this.getRightmostSide(this._minDe,this._minIndex)===tt.LEFT&&(this._orientedDe=this._minDe.getSym())}}],[{key:"constructor_",value:function(){this._minIndex=-1,this._minCoord=null,this._minDe=null,this._orientedDe=null}}]),e}(),pt=function(e){r(o,e);var i=c(o);function o(e,n){var r;return t(this,o),(r=i.call(this,n?e+" [ "+n+" ]":e)).pt=n?new z(n):void 0,r.name=Object.keys({TopologyException:o})[0],r}return n(o,[{key:"getCoordinate",value:function(){return this.pt}}]),o}(F),vt=function(){function e(){t(this,e),this.array=[]}return n(e,[{key:"addLast",value:function(t){this.array.push(t)}},{key:"removeFirst",value:function(){return this.array.shift()}},{key:"isEmpty",value:function(){return 0===this.array.length}}]),e}(),dt=function(e,i){r(s,e);var o=c(s);function s(e){var n;return t(this,s),(n=o.call(this)).array=[],e instanceof H&&n.addAll(e),n}return n(s,[{key:"interfaces_",get:function(){return[rt,H]}},{key:"ensureCapacity",value:function(){}},{key:"add",value:function(t){return 1===arguments.length?this.array.push(t):this.array.splice(arguments[0],0,arguments[1]),!0}},{key:"clear",value:function(){this.array=[]}},{key:"addAll",value:function(t){var e,n=d(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.array.push(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"set",value:function(t,e){var n=this.array[t];return this.array[t]=e,n}},{key:"iterator",value:function(){return new yt(this)}},{key:"get",value:function(t){if(t<0||t>=this.size())throw new nt;return this.array[t]}},{key:"isEmpty",value:function(){return 0===this.array.length}},{key:"sort",value:function(t){t?this.array.sort((function(e,n){return t.compare(e,n)})):this.array.sort()}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}},{key:"remove",value:function(t){for(var e=0,n=this.array.length;e=1&&e.getDepth(tt.LEFT)<=0&&!e.isInteriorAreaEdge()&&e.setInResult(!0)}}},{key:"computeDepths",value:function(t){var e=new Q,n=new vt,r=t.getNode();for(n.addLast(r),e.add(r),t.setVisited(!0);!n.isEmpty();){var i=n.removeFirst();e.add(i),this.computeNodeDepth(i);for(var o=i.getEdges().iterator();o.hasNext();){var s=o.next().getSym();if(!s.isVisited()){var a=s.getNode();e.contains(a)||(n.addLast(a),e.add(a))}}}}},{key:"compareTo",value:function(t){var e=t;return this._rightMostCoord.xe._rightMostCoord.x?1:0}},{key:"getEnvelope",value:function(){if(null===this._env){for(var t=new X,e=this._dirEdgeList.iterator();e.hasNext();)for(var n=e.next().getEdge().getCoordinates(),r=0;re.x?t.x:e.x,a=t.y>e.y?t.y:e.y,u=n.xr.x?n.x:r.x,c=n.y>r.y?n.y:r.y,f=((i>u?i:u)+(sl?o:l)+(an?n:t}if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var r=arguments[0],i=arguments[1],o=arguments[2];return ro?o:r}}},{key:"wrap",value:function(t,e){return t<0?e- -t%e:t%e}},{key:"max",value:function(){if(3===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[0];return t>n&&(n=t),e>n&&(n=e),n}if(4===arguments.length){var r=arguments[1],i=arguments[2],o=arguments[3],s=arguments[0];return r>s&&(s=r),i>s&&(s=i),o>s&&(s=o),s}}},{key:"average",value:function(t,e){return(t+e)/2}}]),e}();Et.LOG_10=Math.log(10);var kt=function(){function e(){t(this,e)}return n(e,null,[{key:"segmentToSegment",value:function(t,n,r,i){if(t.equals(n))return e.pointToSegment(t,r,i);if(r.equals(i))return e.pointToSegment(i,t,n);var o=!1;if(X.intersects(t,n,r,i)){var s=(n.x-t.x)*(i.y-r.y)-(n.y-t.y)*(i.x-r.x);if(0===s)o=!0;else{var a=(t.y-r.y)*(i.x-r.x)-(t.x-r.x)*(i.y-r.y),u=((t.y-r.y)*(n.x-t.x)-(t.x-r.x)*(n.y-t.y))/s,l=a/s;(l<0||l>1||u<0||u>1)&&(o=!0)}}else o=!0;return o?Et.min(e.pointToSegment(t,r,i),e.pointToSegment(n,r,i),e.pointToSegment(r,t,n),e.pointToSegment(i,t,n)):0}},{key:"pointToSegment",value:function(t,e,n){if(e.x===n.x&&e.y===n.y)return t.distance(e);var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/r;if(i<=0)return t.distance(e);if(i>=1)return t.distance(n);var o=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(o)*Math.sqrt(r)}},{key:"pointToLinePerpendicular",value:function(t,e,n){var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(i)*Math.sqrt(r)}},{key:"pointToSegmentString",value:function(t,n){if(0===n.length)throw new x("Line array must contain at least one vertex");for(var r=t.distance(n[0]),i=0;i0)&&(o=a,i=s)}return i}}},{key:"extend",value:function(t,n,r){var i=t.create(r,n.getDimension()),o=n.size();if(e.copy(n,0,i,0,o),o>0)for(var s=o;s0)&&(e=r)}return e}}]),e}(),Mt=function(){function e(){t(this,e)}return n(e,null,[{key:"toDimensionSymbol",value:function(t){switch(t){case e.FALSE:return e.SYM_FALSE;case e.TRUE:return e.SYM_TRUE;case e.DONTCARE:return e.SYM_DONTCARE;case e.P:return e.SYM_P;case e.L:return e.SYM_L;case e.A:return e.SYM_A}throw new x("Unknown dimension value: "+t)}},{key:"toDimensionValue",value:function(t){switch(ut.toUpperCase(t)){case e.SYM_FALSE:return e.FALSE;case e.SYM_TRUE:return e.TRUE;case e.SYM_DONTCARE:return e.DONTCARE;case e.SYM_P:return e.P;case e.SYM_L:return e.L;case e.SYM_A:return e.A}throw new x("Unknown dimension symbol: "+t)}}]),e}();Mt.P=0,Mt.L=1,Mt.A=2,Mt.FALSE=-1,Mt.TRUE=-2,Mt.DONTCARE=-3,Mt.SYM_FALSE="F",Mt.SYM_TRUE="T",Mt.SYM_DONTCARE="*",Mt.SYM_P="0",Mt.SYM_L="1",Mt.SYM_A="2";var Lt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}(),Pt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t,e){}},{key:"isDone",value:function(){}},{key:"isGeometryChanged",value:function(){}}]),e}(),Ct=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"computeEnvelopeInternal",value:function(){return this.isEmpty()?new X:this._points.expandEnvelope(new X)}},{key:"isRing",value:function(){return this.isClosed()&&this.isSimple()}},{key:"getCoordinates",value:function(){return this._points.toCoordinateArray()}},{key:"copyInternal",value:function(){return new s(this._points.copy(),this._factory)}},{key:"equalsExact",value:function(){if(2===arguments.length&&"number"==typeof arguments[1]&&arguments[0]instanceof U){var t=arguments[0],e=arguments[1];if(!this.isEquivalentClass(t))return!1;var n=t;if(this._points.size()!==n._points.size())return!1;for(var r=0;r0){var n=this._points.copy();St.reverse(n),this._points=n}return null}}}},{key:"getCoordinate",value:function(){return this.isEmpty()?null:this._points.getCoordinate(0)}},{key:"getBoundaryDimension",value:function(){return this.isClosed()?Mt.FALSE:0}},{key:"isClosed",value:function(){return!this.isEmpty()&&this.getCoordinateN(0).equals2D(this.getCoordinateN(this.getNumPoints()-1))}},{key:"reverseInternal",value:function(){var t=this._points.copy();return St.reverse(t),this.getFactory().createLineString(t)}},{key:"getEndPoint",value:function(){return this.isEmpty()?null:this.getPointN(this.getNumPoints()-1)}},{key:"getTypeCode",value:function(){return U.TYPECODE_LINESTRING}},{key:"getDimension",value:function(){return 1}},{key:"getLength",value:function(){return It.ofLine(this._points)}},{key:"getNumPoints",value:function(){return this._points.size()}},{key:"compareToSameClass",value:function(){if(1===arguments.length){for(var t=arguments[0],e=0,n=0;e= 2)");this._points=t}},{key:"isCoordinate",value:function(t){for(var e=0;e=1&&this.getCoordinateSequence().size()= 4)")}},{key:"getGeometryType",value:function(){return U.TYPENAME_LINEARRING}}],[{key:"constructor_",value:function(){var t=arguments[0],e=arguments[1];Ct.constructor_.call(this,t,e),this.validateConstruction()}}]),s}(Ct);zt.MINIMUM_VALID_SIZE=4;var jt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}}],[{key:"constructor_",value:function(){if(0===arguments.length)z.constructor_.call(this);else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y)}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y)}}else if(2===arguments.length){var n=arguments[0],r=arguments[1];z.constructor_.call(this,n,r,z.NULL_ORDINATE)}}}]),o}(z);jt.X=0,jt.Y=1,jt.Z=-1,jt.M=-1;var Xt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;case o.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y;case o.M:return this._m}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y),this._m=this.getM()}}else if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2];z.constructor_.call(this,n,r,z.NULL_ORDINATE),this._m=i}}}]),o}(z);Xt.X=0,Xt.Y=1,Xt.Z=-1,Xt.M=2;var Ut=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case z.X:this.x=e;break;case z.Y:this.y=e;break;case z.Z:this.z=e;break;case z.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getOrdinate",value:function(t){switch(t){case z.X:return this.x;case z.Y:return this.y;case z.Z:return this.getZ();case z.M:return this.getM()}throw new x("Invalid ordinate index: "+t)}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e),this._m=this.getM()}}else if(4===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],s=arguments[3];z.constructor_.call(this,n,r,i),this._m=s}}}]),o}(z),Zt=function(){function e(){t(this,e)}return n(e,null,[{key:"measures",value:function(t){return t instanceof jt?0:t instanceof Xt||t instanceof Ut?1:0}},{key:"dimension",value:function(t){return t instanceof jt?2:t instanceof Xt?3:t instanceof Ut?4:3}},{key:"create",value:function(){if(1===arguments.length){var t=arguments[0];return e.create(t,0)}if(2===arguments.length){var n=arguments[0],r=arguments[1];return 2===n?new jt:3===n&&0===r?new z:3===n&&1===r?new Xt:4===n&&1===r?new Ut:new z}}}]),e}(),Ht=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getCoordinate",value:function(t){return this.get(t)}},{key:"addAll",value:function(){if(2===arguments.length&&"boolean"==typeof arguments[1]&&ot(arguments[0],H)){for(var t=arguments[1],e=!1,n=arguments[0].iterator();n.hasNext();)this.add(n.next(),t),e=!0;return e}return f(i(s.prototype),"addAll",this).apply(this,arguments)}},{key:"clone",value:function(){for(var t=f(i(s.prototype),"clone",this).call(this),e=0;e=1&&this.get(this.size()-1).equals2D(r))return null;f(i(s.prototype),"add",this).call(this,r)}else if(arguments[0]instanceof Object&&"boolean"==typeof arguments[1]){var o=arguments[0],a=arguments[1];return this.add(o,a),!0}}else if(3===arguments.length){if("boolean"==typeof arguments[2]&&arguments[0]instanceof Array&&"boolean"==typeof arguments[1]){var u=arguments[0],l=arguments[1];if(arguments[2])for(var h=0;h=0;c--)this.add(u[c],l);return!0}if("boolean"==typeof arguments[2]&&Number.isInteger(arguments[0])&&arguments[1]instanceof z){var g=arguments[0],p=arguments[1];if(!arguments[2]){var v=this.size();if(v>0){if(g>0&&this.get(g-1).equals2D(p))return null;if(g_&&(x=-1);for(var E=m;E!==_;E+=x)this.add(d[E],y);return!0}}},{key:"closeRing",value:function(){if(this.size()>0){var t=this.get(0).copy();this.add(t,!1)}}}],[{key:"constructor_",value:function(){if(0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.ensureCapacity(t.length),this.add(t,!0)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this.ensureCapacity(e.length),this.add(e,n)}}}]),s}(dt);Ht.coordArrayType=new Array(0).fill(null);var Wt=function(){function e(){t(this,e)}return n(e,null,[{key:"isRing",value:function(t){return!(t.length<4||!t[0].equals2D(t[t.length-1]))}},{key:"ptNotInList",value:function(t,n){for(var r=0;r=t?e:[]}},{key:"indexOf",value:function(t,e){for(var n=0;n0)&&(e=t[n]);return e}},{key:"extract",value:function(t,e,n){e=Et.clamp(e,0,t.length);var r=(n=Et.clamp(n,-1,t.length))-e+1;n<0&&(r=0),e>=t.length&&(r=0),nr.length)return 1;if(0===n.length)return 0;var i=Wt.compare(n,r);return Wt.isEqualReversed(n,r)?0:i}},{key:"OLDcompare",value:function(t,e){var n=t,r=e;if(n.lengthr.length)return 1;if(0===n.length)return 0;for(var i=Wt.increasingDirection(n),o=Wt.increasingDirection(r),s=i>0?0:n.length-1,a=o>0?0:n.length-1,u=0;u0){var t=new Qt(17*this._coordinates.length);t.append("("),t.append(this._coordinates[0]);for(var e=1;e3&&(t=3),t<2&&(t=2),new $t(arguments[0],t)}if(3===arguments.length){var e=arguments[2],n=arguments[1]-e;return e>1&&(e=1),n>3&&(n=3),n<2&&(n=2),new $t(arguments[0],n+e,e)}}}},{key:"interfaces_",get:function(){return[bt,w]}}],[{key:"instance",value:function(){return e.instanceObject}}]),e}();te.instanceObject=new te;var ee=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e=0?t:e}}]),e}(),oe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"readResolve",value:function(){return e.nameToTypeMap.get(this._name)}},{key:"toString",value:function(){return this._name}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){this._name=null;var t=arguments[0];this._name=t,e.nameToTypeMap.put(t,this)}}]),e}();oe.nameToTypeMap=new re,ie.Type=oe,ie.FIXED=new oe("FIXED"),ie.FLOATING=new oe("FLOATING"),ie.FLOATING_SINGLE=new oe("FLOATING SINGLE"),ie.maximumPreciseValue=9007199254740992;var se=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e1){if(u instanceof Ft)return this.createMultiPolygon(e.toPolygonArray(t));if(u instanceof Ct)return this.createMultiLineString(e.toLineStringArray(t));if(u instanceof Ot)return this.createMultiPoint(e.toPointArray(t));V.shouldNeverReachHere("Unhandled geometry type: "+u.getGeometryType())}return u}},{key:"createMultiPointFromCoords",value:function(t){return this.createMultiPoint(null!==t?this.getCoordinateSequenceFactory().create(t):null)}},{key:"createPoint",value:function(){if(0===arguments.length)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];return this.createPoint(null!==t?this.getCoordinateSequenceFactory().create([t]):null)}if(ot(arguments[0],ct))return new Ot(arguments[0],this)}}},{key:"getCoordinateSequenceFactory",value:function(){return this._coordinateSequenceFactory}},{key:"createPolygon",value:function(){if(0===arguments.length)return this.createPolygon(null,null);if(1===arguments.length){if(ot(arguments[0],ct)){var t=arguments[0];return this.createPolygon(this.createLinearRing(t))}if(arguments[0]instanceof Array){var e=arguments[0];return this.createPolygon(this.createLinearRing(e))}if(arguments[0]instanceof zt){var n=arguments[0];return this.createPolygon(n,null)}}else if(2===arguments.length)return new Ft(arguments[0],arguments[1],this)}},{key:"getSRID",value:function(){return this._SRID}},{key:"createGeometryCollection",value:function(){return 0===arguments.length?new Bt(null,this):1===arguments.length?new Bt(arguments[0],this):void 0}},{key:"getPrecisionModel",value:function(){return this._precisionModel}},{key:"createLinearRing",value:function(){if(0===arguments.length)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof Array){var t=arguments[0];return this.createLinearRing(null!==t?this.getCoordinateSequenceFactory().create(t):null)}if(ot(arguments[0],ct))return new zt(arguments[0],this)}}},{key:"createMultiPolygon",value:function(){return 0===arguments.length?new ee(null,this):1===arguments.length?new ee(arguments[0],this):void 0}},{key:"createMultiPoint",value:function(){if(0===arguments.length)return new Yt(null,this);if(1===arguments.length){if(arguments[0]instanceof Array)return new Yt(arguments[0],this);if(ot(arguments[0],ct)){var t=arguments[0];if(null===t)return this.createMultiPoint(new Array(0).fill(null));for(var e=new Array(t.size()).fill(null),n=0;n="a"&&t<="z"||t>="A"&&t<="Z"}},{key:"isNumeric_",value:function(t,e){return t>="0"&&t<="9"||"."==t&&!(void 0!==e&&e)}},{key:"isWhiteSpace_",value:function(t){return" "==t||"\t"==t||"\r"==t||"\n"==t}},{key:"nextChar_",value:function(){return this.wkt.charAt(++this.index_)}},{key:"nextToken",value:function(){var t,e=this.nextChar_(),n=this.index_,r=e;if("("==e)t=ve;else if(","==e)t=me;else if(")"==e)t=de;else if(this.isNumeric_(e)||"-"==e)t=ye,r=this.readNumber_();else if(this.isAlpha_(e))t=pe,r=this.readText_();else{if(this.isWhiteSpace_(e))return this.nextToken();if(""!==e)throw new Error("Unexpected character: "+e);t=_e}return{position:n,value:r,type:t}}},{key:"readNumber_",value:function(){var t,e=this.index_,n=!1,r=!1;do{"."==t?n=!0:"e"!=t&&"E"!=t||(r=!0),t=this.nextChar_()}while(this.isNumeric_(t,n)||!r&&("e"==t||"E"==t)||r&&("-"==t||"+"==t));return parseFloat(this.wkt.substring(e,this.index_--))}},{key:"readText_",value:function(){var t,e=this.index_;do{t=this.nextChar_()}while(this.isAlpha_(t));return this.wkt.substring(e,this.index_--).toUpperCase()}}]),e}(),ke=function(){function e(n,r){t(this,e),this.lexer_=n,this.token_,this.layout_=ue,this.factory=r}return n(e,[{key:"consume_",value:function(){this.token_=this.lexer_.nextToken()}},{key:"isTokenType",value:function(t){return this.token_.type==t}},{key:"match",value:function(t){var e=this.isTokenType(t);return e&&this.consume_(),e}},{key:"parse",value:function(){return this.consume_(),this.parseGeometry_()}},{key:"parseGeometryLayout_",value:function(){var t=ue,e=this.token_;if(this.isTokenType(pe)){var n=e.value;"Z"===n?t=le:"M"===n?t=he:"ZM"===n&&(t=ce),t!==ue&&this.consume_()}return t}},{key:"parseGeometryCollectionText_",value:function(){if(this.match(ve)){var t=[];do{t.push(this.parseGeometry_())}while(this.match(me));if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePointText_",value:function(){if(this.match(ve)){var t=this.parsePoint_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return null;throw new Error(this.formatErrorMessage_())}},{key:"parseLineStringText_",value:function(){if(this.match(ve)){var t=this.parsePointList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePolygonText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPointText_",value:function(){var t;if(this.match(ve)){if(t=this.token_.type==ve?this.parsePointTextList_():this.parsePointList_(),this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiLineStringText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPolygonText_",value:function(){if(this.match(ve)){var t=this.parsePolygonTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePoint_",value:function(){for(var t=[],e=this.layout_.length,n=0;n1?t.createPolygon(r[0],r.slice(1)):t.createPolygon(r[0])},r=this.token_;if(this.match(pe)){var i=r.value;if(this.layout_=this.parseGeometryLayout_(),"GEOMETRYCOLLECTION"==i){var o=this.parseGeometryCollectionText_();return t.createGeometryCollection(o)}switch(i){case"POINT":var s=this.parsePointText_();return s?t.createPoint(a(z,g(s))):t.createPoint();case"LINESTRING":var u=this.parseLineStringText_().map(e);return t.createLineString(u);case"LINEARRING":var l=this.parseLineStringText_().map(e);return t.createLinearRing(l);case"POLYGON":var h=this.parsePolygonText_();return h&&0!==h.length?n(h):t.createPolygon();case"MULTIPOINT":var c=this.parseMultiPointText_();if(!c||0===c.length)return t.createMultiPoint();var f=c.map(e).map((function(e){return t.createPoint(e)}));return t.createMultiPoint(f);case"MULTILINESTRING":var p=this.parseMultiLineStringText_().map((function(n){return t.createLineString(n.map(e))}));return t.createMultiLineString(p);case"MULTIPOLYGON":var v=this.parseMultiPolygonText_();if(!v||0===v.length)return t.createMultiPolygon();var d=v.map(n);return t.createMultiPolygon(d);default:throw new Error("Invalid geometry type: "+i)}}throw new Error(this.formatErrorMessage_())}}]),e}();function be(t){if(t.isEmpty())return"";var e=t.getCoordinate(),n=[e.x,e.y];return void 0===e.z||Number.isNaN(e.z)||n.push(e.z),void 0===e.m||Number.isNaN(e.m)||n.push(e.m),n.join(" ")}function we(t){for(var e=t.getCoordinates().map((function(t){var e=[t.x,t.y];return void 0===t.z||Number.isNaN(t.z)||e.push(t.z),void 0===t.m||Number.isNaN(t.m)||e.push(t.m),e})),n=[],r=0,i=e.length;r0&&(e+=" "+r),t.isEmpty()?e+" "+ge:e+" ("+n(t)+")"}var Me=function(){function e(n){t(this,e),this.geometryFactory=n||new ae,this.precisionModel=this.geometryFactory.getPrecisionModel()}return n(e,[{key:"read",value:function(t){var e=new Ee(t);return new ke(e,this.geometryFactory).parse()}},{key:"write",value:function(t){return Se(t)}}]),e}(),Le=function(){function e(n){t(this,e),this.parser=new Me(n)}return n(e,[{key:"write",value:function(t){return this.parser.write(t)}}],[{key:"toLineString",value:function(t,e){if(2!==arguments.length)throw new Error("Not implemented");return"LINESTRING ( "+t.x+" "+t.y+", "+e.x+" "+e.y+" )"}}]),e}(),Pe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getIndexAlongSegment",value:function(t,e){return this.computeIntLineIndex(),this._intLineIndex[t][e]}},{key:"getTopologySummary",value:function(){var t=new Qt;return this.isEndPoint()&&t.append(" endpoint"),this._isProper&&t.append(" proper"),this.isCollinear()&&t.append(" collinear"),t.toString()}},{key:"computeIntersection",value:function(t,e,n,r){this._inputLines[0][0]=t,this._inputLines[0][1]=e,this._inputLines[1][0]=n,this._inputLines[1][1]=r,this._result=this.computeIntersect(t,e,n,r)}},{key:"getIntersectionNum",value:function(){return this._result}},{key:"computeIntLineIndex",value:function(){if(0===arguments.length)null===this._intLineIndex&&(this._intLineIndex=Array(2).fill().map((function(){return Array(2)})),this.computeIntLineIndex(0),this.computeIntLineIndex(1));else if(1===arguments.length){var t=arguments[0];this.getEdgeDistance(t,0)>this.getEdgeDistance(t,1)?(this._intLineIndex[t][0]=0,this._intLineIndex[t][1]=1):(this._intLineIndex[t][0]=1,this._intLineIndex[t][1]=0)}}},{key:"isProper",value:function(){return this.hasIntersection()&&this._isProper}},{key:"setPrecisionModel",value:function(t){this._precisionModel=t}},{key:"isInteriorIntersection",value:function(){if(0===arguments.length)return!!this.isInteriorIntersection(0)||!!this.isInteriorIntersection(1);if(1===arguments.length){for(var t=arguments[0],e=0;ei?r:i;else{var s=Math.abs(t.x-e.x),a=Math.abs(t.y-e.y);0!==(o=r>i?s:a)||t.equals(e)||(o=Math.max(s,a))}return V.isTrue(!(0===o&&!t.equals(e)),"Bad distance calculation"),o}},{key:"nonRobustComputeEdgeDistance",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y,o=Math.sqrt(r*r+i*i);return V.isTrue(!(0===o&&!t.equals(e)),"Invalid distance calculation"),o}}]),e}();Pe.DONT_INTERSECT=0,Pe.DO_INTERSECT=1,Pe.COLLINEAR=2,Pe.NO_INTERSECTION=0,Pe.POINT_INTERSECTION=1,Pe.COLLINEAR_INTERSECTION=2;var Ce=function(e){r(s,e);var o=c(s);function s(){return t(this,s),o.call(this)}return n(s,[{key:"isInSegmentEnvelopes",value:function(t){var e=new X(this._inputLines[0][0],this._inputLines[0][1]),n=new X(this._inputLines[1][0],this._inputLines[1][1]);return e.contains(t)&&n.contains(t)}},{key:"computeIntersection",value:function(){if(3!==arguments.length)return f(i(s.prototype),"computeIntersection",this).apply(this,arguments);var t=arguments[0],e=arguments[1],n=arguments[2];if(this._isProper=!1,X.intersects(e,n,t)&&0===ft.index(e,n,t)&&0===ft.index(n,e,t))return this._isProper=!0,(t.equals(e)||t.equals(n))&&(this._isProper=!1),this._result=Pe.POINT_INTERSECTION,null;this._result=Pe.NO_INTERSECTION}},{key:"intersection",value:function(t,e,n,r){var i=this.intersectionSafe(t,e,n,r);return this.isInSegmentEnvelopes(i)||(i=new z(s.nearestEndpoint(t,e,n,r))),null!==this._precisionModel&&this._precisionModel.makePrecise(i),i}},{key:"checkDD",value:function(t,e,n,r,i){var o=ht.intersection(t,e,n,r),s=this.isInSegmentEnvelopes(o);xt.out.println("DD in env = "+s+" --------------------- "+o),i.distance(o)>1e-4&&xt.out.println("Distance = "+i.distance(o))}},{key:"intersectionSafe",value:function(t,e,n,r){var i=_t.intersection(t,e,n,r);return null===i&&(i=s.nearestEndpoint(t,e,n,r)),i}},{key:"computeCollinearIntersection",value:function(t,e,n,r){var i=X.intersects(t,e,n),o=X.intersects(t,e,r),s=X.intersects(n,r,t),a=X.intersects(n,r,e);return i&&o?(this._intPt[0]=n,this._intPt[1]=r,Pe.COLLINEAR_INTERSECTION):s&&a?(this._intPt[0]=t,this._intPt[1]=e,Pe.COLLINEAR_INTERSECTION):i&&s?(this._intPt[0]=n,this._intPt[1]=t,!n.equals(t)||o||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):i&&a?(this._intPt[0]=n,this._intPt[1]=e,!n.equals(e)||o||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&s?(this._intPt[0]=r,this._intPt[1]=t,!r.equals(t)||i||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&a?(this._intPt[0]=r,this._intPt[1]=e,!r.equals(e)||i||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):Pe.NO_INTERSECTION}},{key:"computeIntersect",value:function(t,e,n,r){if(this._isProper=!1,!X.intersects(t,e,n,r))return Pe.NO_INTERSECTION;var i=ft.index(t,e,n),o=ft.index(t,e,r);if(i>0&&o>0||i<0&&o<0)return Pe.NO_INTERSECTION;var s=ft.index(n,r,t),a=ft.index(n,r,e);return s>0&&a>0||s<0&&a<0?Pe.NO_INTERSECTION:0===i&&0===o&&0===s&&0===a?this.computeCollinearIntersection(t,e,n,r):(0===i||0===o||0===s||0===a?(this._isProper=!1,t.equals2D(n)||t.equals2D(r)?this._intPt[0]=t:e.equals2D(n)||e.equals2D(r)?this._intPt[0]=e:0===i?this._intPt[0]=new z(n):0===o?this._intPt[0]=new z(r):0===s?this._intPt[0]=new z(t):0===a&&(this._intPt[0]=new z(e))):(this._isProper=!0,this._intPt[0]=this.intersection(t,e,n,r)),Pe.POINT_INTERSECTION)}}],[{key:"nearestEndpoint",value:function(t,e,n,r){var i=t,o=kt.pointToSegment(t,n,r),s=kt.pointToSegment(e,n,r);return sr&&(n=e.x,r=t.x),this._p.x>=n&&this._p.x<=r&&(this._isPointOnSegment=!0),null}if(t.y>this._p.y&&e.y<=this._p.y||e.y>this._p.y&&t.y<=this._p.y){var i=ft.index(t,e,this._p);if(i===ft.COLLINEAR)return this._isPointOnSegment=!0,null;e.ythis.location.length){var e=new Array(3).fill(null);e[tt.ON]=this.location[tt.ON],e[tt.LEFT]=Z.NONE,e[tt.RIGHT]=Z.NONE,this.location=e}for(var n=0;n1&&t.append(Z.toLocationSymbol(this.location[tt.LEFT])),t.append(Z.toLocationSymbol(this.location[tt.ON])),this.location.length>1&&t.append(Z.toLocationSymbol(this.location[tt.RIGHT])),t.toString()}},{key:"setLocations",value:function(t,e,n){this.location[tt.ON]=t,this.location[tt.LEFT]=e,this.location[tt.RIGHT]=n}},{key:"get",value:function(t){return t1}},{key:"isAnyNull",value:function(){for(var t=0;tthis._maxNodeDegree&&(this._maxNodeDegree=e),t=this.getNext(t)}while(t!==this._startDe);this._maxNodeDegree*=2}},{key:"addPoints",value:function(t,e,n){var r=t.getCoordinates();if(e){var i=1;n&&(i=0);for(var o=i;o=0;a--)this._pts.add(r[a])}}},{key:"isHole",value:function(){return this._isHole}},{key:"setInResult",value:function(){var t=this._startDe;do{t.getEdge().setInResult(!0),t=t.getNext()}while(t!==this._startDe)}},{key:"containsPoint",value:function(t){var e=this.getLinearRing();if(!e.getEnvelopeInternal().contains(t))return!1;if(!Oe.isInRing(t,e.getCoordinates()))return!1;for(var n=this._holes.iterator();n.hasNext();)if(n.next().containsPoint(t))return!1;return!0}},{key:"addHole",value:function(t){this._holes.add(t)}},{key:"isShell",value:function(){return null===this._shell}},{key:"getLabel",value:function(){return this._label}},{key:"getEdges",value:function(){return this._edges}},{key:"getMaxNodeDegree",value:function(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree}},{key:"getShell",value:function(){return this._shell}},{key:"mergeLabel",value:function(){if(1===arguments.length){var t=arguments[0];this.mergeLabel(t,0),this.mergeLabel(t,1)}else if(2===arguments.length){var e=arguments[1],n=arguments[0].getLocation(e,tt.RIGHT);if(n===Z.NONE)return null;if(this._label.getLocation(e)===Z.NONE)return this._label.setLocation(e,n),null}}},{key:"setShell",value:function(t){this._shell=t,null!==t&&t.addHole(this)}},{key:"toPolygon",value:function(t){for(var e=new Array(this._holes.size()).fill(null),n=0;n=2,"found partial label"),this.computeIM(t)}},{key:"isInResult",value:function(){return this._isInResult}},{key:"isVisited",value:function(){return this._isVisited}}],[{key:"constructor_",value:function(){if(this._label=null,this._isInResult=!1,this._isCovered=!1,this._isCoveredSet=!1,this._isVisited=!1,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._label=t}}}]),e}(),Ge=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isIncidentEdgeInResult",value:function(){for(var t=this.getEdges().getEdges().iterator();t.hasNext();)if(t.next().getEdge().isInResult())return!0;return!1}},{key:"isIsolated",value:function(){return 1===this._label.getGeometryCount()}},{key:"getCoordinate",value:function(){return this._coord}},{key:"print",value:function(t){t.println("node "+this._coord+" lbl: "+this._label)}},{key:"computeIM",value:function(t){}},{key:"computeMergedLocation",value:function(t,e){var n=Z.NONE;if(n=this._label.getLocation(e),!t.isNull(e)){var r=t.getLocation(e);n!==Z.BOUNDARY&&(n=r)}return n}},{key:"setLabel",value:function(){if(2!==arguments.length||!Number.isInteger(arguments[1])||!Number.isInteger(arguments[0]))return f(i(s.prototype),"setLabel",this).apply(this,arguments);var t=arguments[0],e=arguments[1];null===this._label?this._label=new Ae(t,e):this._label.setLocation(t,e)}},{key:"getEdges",value:function(){return this._edges}},{key:"mergeLabel",value:function(){if(arguments[0]instanceof s){var t=arguments[0];this.mergeLabel(t._label)}else if(arguments[0]instanceof Ae)for(var e=arguments[0],n=0;n<2;n++){var r=this.computeMergedLocation(e,n);this._label.getLocation(n)===Z.NONE&&this._label.setLocation(n,r)}}},{key:"add",value:function(t){this._edges.insert(t),t.setNode(this)}},{key:"setLabelBoundary",value:function(t){if(null===this._label)return null;var e=Z.NONE;null!==this._label&&(e=this._label.getLocation(t));var n=null;switch(e){case Z.BOUNDARY:n=Z.INTERIOR;break;case Z.INTERIOR:default:n=Z.BOUNDARY}this._label.setLocation(t,n)}}],[{key:"constructor_",value:function(){this._coord=null,this._edges=null;var t=arguments[0],e=arguments[1];this._coord=t,this._edges=e,this._label=new Ae(0,Z.NONE)}}]),s}(Ve),Be=function(e){r(i,e);var n=c(i);function i(){return t(this,i),n.apply(this,arguments)}return i}(ne);function Ye(t){return null==t?0:t.color}function ze(t){return null==t?null:t.parent}function je(t,e){null!==t&&(t.color=e)}function Xe(t){return null==t?null:t.left}function Ue(t){return null==t?null:t.right}var Ze=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),(e=i.call(this)).root_=null,e.size_=0,e}return n(o,[{key:"get",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return e.value;e=e.right}}return null}},{key:"put",value:function(t,e){if(null===this.root_)return this.root_={key:t,value:e,left:null,right:null,parent:null,color:0,getValue:function(){return this.value},getKey:function(){return this.key}},this.size_=1,null;var n,r,i=this.root_;do{if(n=i,(r=t.compareTo(i.key))<0)i=i.left;else{if(!(r>0)){var o=i.value;return i.value=e,o}i=i.right}}while(null!==i);var s={key:t,left:null,right:null,value:e,parent:n,color:0,getValue:function(){return this.value},getKey:function(){return this.key}};return r<0?n.left=s:n.right=s,this.fixAfterInsertion(s),this.size_++,null}},{key:"fixAfterInsertion",value:function(t){var e;for(t.color=1;null!=t&&t!==this.root_&&1===t.parent.color;)ze(t)===Xe(ze(ze(t)))?1===Ye(e=Ue(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Ue(ze(t))&&(t=ze(t),this.rotateLeft(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateRight(ze(ze(t)))):1===Ye(e=Xe(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Xe(ze(t))&&(t=ze(t),this.rotateRight(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateLeft(ze(ze(t))));this.root_.color=0}},{key:"values",value:function(){var t=new dt,e=this.getFirstEntry();if(null!==e)for(t.add(e.value);null!==(e=o.successor(e));)t.add(e.value);return t}},{key:"entrySet",value:function(){var t=new Q,e=this.getFirstEntry();if(null!==e)for(t.add(e);null!==(e=o.successor(e));)t.add(e);return t}},{key:"rotateLeft",value:function(t){if(null!=t){var e=t.right;t.right=e.left,null!=e.left&&(e.left.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.left===t?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}}},{key:"rotateRight",value:function(t){if(null!=t){var e=t.left;t.left=e.right,null!=e.right&&(e.right.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.right===t?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}}},{key:"getFirstEntry",value:function(){var t=this.root_;if(null!=t)for(;null!=t.left;)t=t.left;return t}},{key:"size",value:function(){return this.size_}},{key:"containsKey",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return!0;e=e.right}}return!1}}],[{key:"successor",value:function(t){var e;if(null===t)return null;if(null!==t.right){for(e=t.right;null!==e.left;)e=e.left;return e}e=t.parent;for(var n=t;null!==e&&n===e.right;)n=e,e=e.parent;return e}}]),o}(Be),He=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"find",value:function(t){return this.nodeMap.get(t)}},{key:"addNode",value:function(){if(arguments[0]instanceof z){var t=arguments[0],e=this.nodeMap.get(t);return null===e&&(e=this.nodeFact.createNode(t),this.nodeMap.put(t,e)),e}if(arguments[0]instanceof Ge){var n=arguments[0],r=this.nodeMap.get(n.getCoordinate());return null===r?(this.nodeMap.put(n.getCoordinate(),n),n):(r.mergeLabel(n),r)}}},{key:"print",value:function(t){for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this.nodeMap.values().iterator()}},{key:"values",value:function(){return this.nodeMap.values()}},{key:"getBoundaryNodes",value:function(t){for(var e=new dt,n=this.iterator();n.hasNext();){var r=n.next();r.getLabel().getLocation(t)===Z.BOUNDARY&&e.add(r)}return e}},{key:"add",value:function(t){var e=t.getCoordinate();this.addNode(e).add(t)}}],[{key:"constructor_",value:function(){this.nodeMap=new Ze,this.nodeFact=null;var t=arguments[0];this.nodeFact=t}}]),e}(),We=function(){function e(){t(this,e)}return n(e,null,[{key:"isNorthern",value:function(t){return t===e.NE||t===e.NW}},{key:"isOpposite",value:function(t,e){return t!==e&&2==(t-e+4)%4}},{key:"commonHalfPlane",value:function(t,e){if(t===e)return t;if(2==(t-e+4)%4)return-1;var n=te?t:e)?3:n}},{key:"isInHalfPlane",value:function(t,n){return n===e.SE?t===e.SE||t===e.SW:t===n||t===n+1}},{key:"quadrant",value:function(){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1];if(0===t&&0===n)throw new x("Cannot compute the quadrant for point ( "+t+", "+n+" )");return t>=0?n>=0?e.NE:e.SE:n>=0?e.NW:e.SW}if(arguments[0]instanceof z&&arguments[1]instanceof z){var r=arguments[0],i=arguments[1];if(i.x===r.x&&i.y===r.y)throw new x("Cannot compute the quadrant for two identical points "+r);return i.x>=r.x?i.y>=r.y?e.NE:e.SE:i.y>=r.y?e.NW:e.SW}}}]),e}();We.NE=0,We.NW=1,We.SW=2,We.SE=3;var Je=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareDirection",value:function(t){return this._dx===t._dx&&this._dy===t._dy?0:this._quadrant>t._quadrant?1:this._quadrant2){o.linkDirectedEdgesForMinimalEdgeRings();var s=o.buildMinimalRings(),a=this.findShell(s);null!==a?(this.placePolygonHoles(a,s),e.add(a)):n.addAll(s)}else r.add(o)}return r}},{key:"buildMaximalEdgeRings",value:function(t){for(var e=new dt,n=t.iterator();n.hasNext();){var r=n.next();if(r.isInResult()&&r.getLabel().isArea()&&null===r.getEdgeRing()){var i=new qe(r,this._geometryFactory);e.add(i),i.setInResult()}}return e}},{key:"placePolygonHoles",value:function(t,e){for(var n=e.iterator();n.hasNext();){var r=n.next();r.isHole()&&r.setShell(t)}}},{key:"getPolygons",value:function(){return this.computePolygons(this._shellList)}},{key:"findShell",value:function(t){for(var e=0,n=null,r=t.iterator();r.hasNext();){var i=r.next();i.isHole()||(n=i,e++)}return V.isTrue(e<=1,"found two shells in MinimalEdgeRing list"),n}},{key:"add",value:function(){if(1===arguments.length){var t=arguments[0];this.add(t.getEdgeEnds(),t.getNodes())}else if(2===arguments.length){var e=arguments[0],n=arguments[1];$e.linkResultDirectedEdges(n);var r=this.buildMaximalEdgeRings(e),i=new dt,o=this.buildMinimalEdgeRings(r,this._shellList,i);this.sortShellsAndHoles(o,this._shellList,i),this.placeFreeHoles(this._shellList,i)}}}],[{key:"constructor_",value:function(){this._geometryFactory=null,this._shellList=new dt;var t=arguments[0];this._geometryFactory=t}},{key:"findEdgeRingContaining",value:function(t,e){for(var n=t.getLinearRing(),r=n.getEnvelopeInternal(),i=n.getCoordinateN(0),o=null,s=null,a=e.iterator();a.hasNext();){var u=a.next(),l=u.getLinearRing(),h=l.getEnvelopeInternal();if(!h.equals(r)&&h.contains(r)){i=Wt.ptNotInList(n.getCoordinates(),l.getCoordinates());var c=!1;Oe.isInRing(i,l.getCoordinates())&&(c=!0),c&&(null===o||s.contains(h))&&(s=(o=u).getLinearRing().getEnvelopeInternal())}}return o}}]),e}(),en=function(){function e(){t(this,e)}return n(e,[{key:"getBounds",value:function(){}}]),e}(),nn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getItem",value:function(){return this._item}},{key:"getBounds",value:function(){return this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){this._bounds=null,this._item=null;var t=arguments[0],e=arguments[1];this._bounds=t,this._item=e}}]),e}(),rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"poll",value:function(){if(this.isEmpty())return null;var t=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),t}},{key:"size",value:function(){return this._size}},{key:"reorder",value:function(t){for(var e=null,n=this._items.get(t);2*t<=this._size&&((e=2*t)!==this._size&&this._items.get(e+1).compareTo(this._items.get(e))<0&&e++,this._items.get(e).compareTo(n)<0);t=e)this._items.set(t,this._items.get(e));this._items.set(t,n)}},{key:"clear",value:function(){this._size=0,this._items.clear()}},{key:"peek",value:function(){return this.isEmpty()?null:this._items.get(1)}},{key:"isEmpty",value:function(){return 0===this._size}},{key:"add",value:function(t){this._items.add(null),this._size+=1;var e=this._size;for(this._items.set(0,t);t.compareTo(this._items.get(Math.trunc(e/2)))<0;e/=2)this._items.set(e,this._items.get(Math.trunc(e/2)));this._items.set(e,t)}}],[{key:"constructor_",value:function(){this._size=null,this._items=null,this._size=0,this._items=new dt,this._items.add(null)}}]),e}(),on=function(){function e(){t(this,e)}return n(e,[{key:"insert",value:function(t,e){}},{key:"remove",value:function(t,e){}},{key:"query",value:function(){}}]),e}(),sn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLevel",value:function(){return this._level}},{key:"size",value:function(){return this._childBoundables.size()}},{key:"getChildBoundables",value:function(){return this._childBoundables}},{key:"addChildBoundable",value:function(t){V.isTrue(null===this._bounds),this._childBoundables.add(t)}},{key:"isEmpty",value:function(){return this._childBoundables.isEmpty()}},{key:"getBounds",value:function(){return null===this._bounds&&(this._bounds=this.computeBounds()),this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){if(this._childBoundables=new dt,this._bounds=null,this._level=null,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._level=t}}}]),e}(),an={reverseOrder:function(){return{compare:function(t,e){return e.compareTo(t)}}},min:function(t){return an.sort(t),t.get(0)},sort:function(t,e){var n=t.toArray();e?At.sort(n,e):At.sort(n);for(var r=t.iterator(),i=0,o=n.length;ie.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,!1,t,n),null):(this.expand(this._boundable2,this._boundable1,!0,t,n),null);if(r)return this.expand(this._boundable1,this._boundable2,!1,t,n),null;if(i)return this.expand(this._boundable2,this._boundable1,!0,t,n),null;throw new x("neither boundable is composite")}},{key:"isLeaves",value:function(){return!(e.isComposite(this._boundable1)||e.isComposite(this._boundable2))}},{key:"compareTo",value:function(t){var e=t;return this._distancee._distance?1:0}},{key:"expand",value:function(t,n,r,i,o){for(var s=t.getChildBoundables().iterator();s.hasNext();){var a=s.next(),u=null;(u=r?new e(n,a,this._itemDistance):new e(a,n,this._itemDistance)).getDistance()-2),r.getLevel()===n)return i.add(r),null;for(var o=r.getChildBoundables().iterator();o.hasNext();){var s=o.next();s instanceof sn?this.boundablesAtLevel(n,s,i):(V.isTrue(s instanceof nn),-1===n&&i.add(s))}return null}}},{key:"query",value:function(){if(1===arguments.length){var t=arguments[0];this.build();var e=new dt;return this.isEmpty()||this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.queryInternal(t,this._root,e),e}if(2===arguments.length){var n=arguments[0],r=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),n)&&this.queryInternal(n,this._root,r)}}},{key:"build",value:function(){if(this._built)return null;this._root=this._itemBoundables.isEmpty()?this.createNode(0):this.createHigherLevels(this._itemBoundables,-1),this._itemBoundables=null,this._built=!0}},{key:"getRoot",value:function(){return this.build(),this._root}},{key:"remove",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];return this.build(),!!this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.remove(t,this._root,e)}if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],o=this.removeItem(r,i);if(o)return!0;for(var s=null,a=r.getChildBoundables().iterator();a.hasNext();){var u=a.next();if(this.getIntersectsOp().intersects(u.getBounds(),n)&&u instanceof sn&&(o=this.remove(n,u,i))){s=u;break}}return null!==s&&s.getChildBoundables().isEmpty()&&r.getChildBoundables().remove(s),o}}},{key:"createHigherLevels",value:function(t,e){V.isTrue(!t.isEmpty());var n=this.createParentBoundables(t,e+1);return 1===n.size()?n.get(0):this.createHigherLevels(n,e+1)}},{key:"depth",value:function(){if(0===arguments.length)return this.isEmpty()?0:(this.build(),this.depth(this._root));if(1===arguments.length){for(var t=0,e=arguments[0].getChildBoundables().iterator();e.hasNext();){var n=e.next();if(n instanceof sn){var r=this.depth(n);r>t&&(t=r)}}return t+1}}},{key:"createParentBoundables",value:function(t,e){V.isTrue(!t.isEmpty());var n=new dt;n.add(this.createNode(e));var r=new dt(t);an.sort(r,this.getComparator());for(var i=r.iterator();i.hasNext();){var o=i.next();this.lastNode(n).getChildBoundables().size()===this.getNodeCapacity()&&n.add(this.createNode(e)),this.lastNode(n).addChildBoundable(o)}return n}},{key:"isEmpty",value:function(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){if(this._root=null,this._built=!1,this._itemBoundables=new dt,this._nodeCapacity=null,0===arguments.length)e.constructor_.call(this,e.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];V.isTrue(t>1,"Node capacity must be greater than 1"),this._nodeCapacity=t}}},{key:"compareDoubles",value:function(t,e){return t>e?1:t0);for(var n=new dt,r=0;r=0;){var u=o.poll(),l=u.getDistance();if(l>=i)break;u.isLeaves()?a.size()l&&(a.poll(),a.add(u)),i=a.peek().getDistance()):u.expandToQueue(o,i)}return s.getItems(a)}}},{key:"createNode",value:function(t){return new pn(t)}},{key:"size",value:function(){return 0===arguments.length?f(i(s.prototype),"size",this).call(this):f(i(s.prototype),"size",this).apply(this,arguments)}},{key:"insert",value:function(){if(!(2===arguments.length&&arguments[1]instanceof Object&&arguments[0]instanceof X))return f(i(s.prototype),"insert",this).apply(this,arguments);var t=arguments[0],e=arguments[1];if(t.isNull())return null;f(i(s.prototype),"insert",this).call(this,t,e)}},{key:"getIntersectsOp",value:function(){return s.intersectsOp}},{key:"verticalSlices",value:function(t,e){for(var n=Math.trunc(Math.ceil(t.size()/e)),r=new Array(e).fill(null),i=t.iterator(),o=0;o0;){var s=o.poll(),a=s.getDistance();if(a>=r)break;s.isLeaves()?(r=a,i=s):s.expandToQueue(o,r)}return null===i?null:[i.getBoundable(0).getItem(),i.getBoundable(1).getItem()]}}else{if(2===arguments.length){var u=arguments[0],l=arguments[1];if(this.isEmpty()||u.isEmpty())return null;var h=new ln(this.getRoot(),u.getRoot(),l);return this.nearestNeighbour(h)}if(3===arguments.length){var c=arguments[2],f=new nn(arguments[0],arguments[1]),g=new ln(this.getRoot(),f,c);return this.nearestNeighbour(g)[0]}if(4===arguments.length){var p=arguments[2],v=arguments[3],d=new nn(arguments[0],arguments[1]),y=new ln(this.getRoot(),d,p);return this.nearestNeighbourK(y,v)}}}},{key:"isWithinDistance",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1],n=A.POSITIVE_INFINITY,r=new rn;for(r.add(t);!r.isEmpty();){var i=r.poll(),o=i.getDistance();if(o>e)return!1;if(i.maximumDistance()<=e)return!0;if(i.isLeaves()){if((n=o)<=e)return!0}else i.expandToQueue(r,n)}return!1}if(3===arguments.length){var s=arguments[0],a=arguments[1],u=arguments[2],l=new ln(this.getRoot(),s.getRoot(),a);return this.isWithinDistance(l,u)}}},{key:"interfaces_",get:function(){return[on,w]}}],[{key:"constructor_",value:function(){if(0===arguments.length)s.constructor_.call(this,s.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];cn.constructor_.call(this,t)}}},{key:"centreX",value:function(t){return s.avg(t.getMinX(),t.getMaxX())}},{key:"avg",value:function(t,e){return(t+e)/2}},{key:"getItems",value:function(t){for(var e=new Array(t.size()).fill(null),n=0;!t.isEmpty();){var r=t.poll();e[n]=r.getBoundable(0).getItem(),n++}return e}},{key:"centreY",value:function(t){return s.avg(t.getMinY(),t.getMaxY())}}]),s}(cn),pn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"computeBounds",value:function(){for(var t=null,e=this.getChildBoundables().iterator();e.hasNext();){var n=e.next();null===t?t=new X(n.getBounds()):t.expandToInclude(n.getBounds())}return t}}],[{key:"constructor_",value:function(){var t=arguments[0];sn.constructor_.call(this,t)}}]),o}(sn);gn.STRtreeNode=pn,gn.xComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreX(t.getBounds()),gn.centreX(e.getBounds()))}}]),e}()),gn.yComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreY(t.getBounds()),gn.centreY(e.getBounds()))}}]),e}()),gn.intersectsOp=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[IntersectsOp]}},{key:"intersects",value:function(t,e){return t.intersects(e)}}]),e}()),gn.DEFAULT_NODE_CAPACITY=10;var vn=function(){function e(){t(this,e)}return n(e,null,[{key:"relativeSign",value:function(t,e){return te?1:0}},{key:"compare",value:function(t,n,r){if(n.equals2D(r))return 0;var i=e.relativeSign(n.x,r.x),o=e.relativeSign(n.y,r.y);switch(t){case 0:return e.compareValue(i,o);case 1:return e.compareValue(o,i);case 2:return e.compareValue(o,-i);case 3:return e.compareValue(-i,o);case 4:return e.compareValue(-i,-o);case 5:return e.compareValue(-o,-i);case 6:return e.compareValue(-o,i);case 7:return e.compareValue(i,-o)}return V.shouldNeverReachHere("invalid octant value"),0}},{key:"compareValue",value:function(t,e){return t<0?-1:t>0?1:e<0?-1:e>0?1:0}}]),e}(),dn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this.coord}},{key:"print",value:function(t){t.print(this.coord),t.print(" seg # = "+this.segmentIndex)}},{key:"compareTo",value:function(t){var e=t;return this.segmentIndexe.segmentIndex?1:this.coord.equals2D(e.coord)?0:this._isInterior?e._isInterior?vn.compare(this._segmentOctant,this.coord,e.coord):1:-1}},{key:"isEndPoint",value:function(t){return 0===this.segmentIndex&&!this._isInterior||this.segmentIndex===t}},{key:"toString",value:function(){return this.segmentIndex+":"+this.coord.toString()}},{key:"isInterior",value:function(){return this._isInterior}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;var t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this._segString=t,this.coord=new z(e),this.segmentIndex=n,this._segmentOctant=r,this._isInterior=!e.equals2D(t.getCoordinate(n))}}]),e}(),yn=function(){function e(){t(this,e)}return n(e,[{key:"hasNext",value:function(){}},{key:"next",value:function(){}},{key:"remove",value:function(){}}]),e}(),mn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getSplitCoordinates",value:function(){var t=new Ht;this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next();this.addEdgeCoordinates(n,r,t),n=r}return t.toCoordinateArray()}},{key:"addCollapsedNodes",value:function(){var t=new dt;this.findCollapsesFromInsertedNodes(t),this.findCollapsesFromExistingVertices(t);for(var e=t.iterator();e.hasNext();){var n=e.next().intValue();this.add(this._edge.getCoordinate(n),n)}}},{key:"createSplitEdgePts",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2;if(2===n)return[new z(t.coord),new z(e.coord)];var r=this._edge.getCoordinate(e.segmentIndex),i=e.isInterior()||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this._edge.getCoordinate(a);return i&&(o[s]=new z(e.coord)),o}},{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"findCollapsesFromExistingVertices",value:function(t){for(var e=0;e=0?n>=0?r>=i?0:1:r>=i?7:6:n>=0?r>=i?3:2:r>=i?4:5}if(arguments[0]instanceof z&&arguments[1]instanceof z){var o=arguments[0],s=arguments[1],a=s.x-o.x,u=s.y-o.y;if(0===a&&0===u)throw new x("Cannot compute the octant for two identical points "+o);return e.octant(a,u)}}}]),e}(),xn=function(){function e(){t(this,e)}return n(e,[{key:"getCoordinates",value:function(){}},{key:"size",value:function(){}},{key:"getCoordinate",value:function(t){}},{key:"isClosed",value:function(){}},{key:"setData",value:function(t){}},{key:"getData",value:function(){}}]),e}(),En=function(){function e(){t(this,e)}return n(e,[{key:"addIntersection",value:function(t,e){}},{key:"interfaces_",get:function(){return[xn]}}]),e}(),kn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinates",value:function(){return this._pts}},{key:"size",value:function(){return this._pts.length}},{key:"getCoordinate",value:function(t){return this._pts[t]}},{key:"isClosed",value:function(){return this._pts[0].equals(this._pts[this._pts.length-1])}},{key:"getSegmentOctant",value:function(t){return t===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(t),this.getCoordinate(t+1))}},{key:"setData",value:function(t){this._data=t}},{key:"safeOctant",value:function(t,e){return t.equals2D(e)?0:_n.octant(t,e)}},{key:"getData",value:function(){return this._data}},{key:"addIntersection",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];this.addIntersectionNode(t,e)}else if(4===arguments.length){var n=arguments[1],r=arguments[3],i=new z(arguments[0].getIntersection(r));this.addIntersection(i,n)}}},{key:"toString",value:function(){return Le.toLineString(new $t(this._pts))}},{key:"getNodeList",value:function(){return this._nodeList}},{key:"addIntersectionNode",value:function(t,e){var n=e,r=n+1;if(r=0&&r>=0||n<=0&&r<=0?Math.max(n,r):0}if(arguments[0]instanceof z){var i=arguments[0];return ft.index(this.p0,this.p1,i)}}},{key:"toGeometry",value:function(t){return t.createLineString([this.p0,this.p1])}},{key:"isVertical",value:function(){return this.p0.x===this.p1.x}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.p0.equals(n.p0)&&this.p1.equals(n.p1)}},{key:"intersection",value:function(t){var e=new Ce;return e.computeIntersection(this.p0,this.p1,t.p0,t.p1),e.hasIntersection()?e.getIntersection(0):null}},{key:"project",value:function(){if(arguments[0]instanceof z){var t=arguments[0];if(t.equals(this.p0)||t.equals(this.p1))return new z(t);var n=this.projectionFactor(t),r=new z;return r.x=this.p0.x+n*(this.p1.x-this.p0.x),r.y=this.p0.y+n*(this.p1.y-this.p0.y),r}if(arguments[0]instanceof e){var i=arguments[0],o=this.projectionFactor(i.p0),s=this.projectionFactor(i.p1);if(o>=1&&s>=1)return null;if(o<=0&&s<=0)return null;var a=this.project(i.p0);o<0&&(a=this.p0),o>1&&(a=this.p1);var u=this.project(i.p1);return s<0&&(u=this.p0),s>1&&(u=this.p1),new e(a,u)}}},{key:"normalize",value:function(){this.p1.compareTo(this.p0)<0&&this.reverse()}},{key:"angle",value:function(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)}},{key:"getCoordinate",value:function(t){return 0===t?this.p0:this.p1}},{key:"distancePerpendicular",value:function(t){return kt.pointToLinePerpendicular(t,this.p0,this.p1)}},{key:"minY",value:function(){return Math.min(this.p0.y,this.p1.y)}},{key:"midPoint",value:function(){return e.midPoint(this.p0,this.p1)}},{key:"projectionFactor",value:function(t){if(t.equals(this.p0))return 0;if(t.equals(this.p1))return 1;var e=this.p1.x-this.p0.x,n=this.p1.y-this.p0.y,r=e*e+n*n;return r<=0?A.NaN:((t.x-this.p0.x)*e+(t.y-this.p0.y)*n)/r}},{key:"closestPoints",value:function(t){var e=this.intersection(t);if(null!==e)return[e,e];var n=new Array(2).fill(null),r=A.MAX_VALUE,i=null,o=this.closestPoint(t.p0);r=o.distance(t.p0),n[0]=o,n[1]=t.p0;var s=this.closestPoint(t.p1);(i=s.distance(t.p1))0&&e<1?this.project(t):this.p0.distance(t)1||A.isNaN(e))&&(e=1),e}},{key:"toString",value:function(){return"LINESTRING( "+this.p0.x+" "+this.p0.y+", "+this.p1.x+" "+this.p1.y+")"}},{key:"isHorizontal",value:function(){return this.p0.y===this.p1.y}},{key:"reflect",value:function(t){var e=this.p1.getY()-this.p0.getY(),n=this.p0.getX()-this.p1.getX(),r=this.p0.getY()*(this.p1.getX()-this.p0.getX())-this.p0.getX()*(this.p1.getY()-this.p0.getY()),i=e*e+n*n,o=e*e-n*n,s=t.getX(),a=t.getY();return new z((-o*s-2*e*n*a-2*e*r)/i,(o*a-2*e*n*s-2*n*r)/i)}},{key:"distance",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return kt.segmentToSegment(this.p0,this.p1,t.p0,t.p1)}if(arguments[0]instanceof z){var n=arguments[0];return kt.pointToSegment(n,this.p0,this.p1)}}},{key:"pointAlong",value:function(t){var e=new z;return e.x=this.p0.x+t*(this.p1.x-this.p0.x),e.y=this.p0.y+t*(this.p1.y-this.p0.y),e}},{key:"hashCode",value:function(){var t=A.doubleToLongBits(this.p0.x);t^=31*A.doubleToLongBits(this.p0.y);var e=Math.trunc(t)^Math.trunc(t>>32),n=A.doubleToLongBits(this.p1.x);return n^=31*A.doubleToLongBits(this.p1.y),e^Math.trunc(n)^Math.trunc(n>>32)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this.p0=null,this.p1=null,0===arguments.length)e.constructor_.call(this,new z,new z);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.p0,t.p1)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.p0=n,this.p1=r}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];e.constructor_.call(this,new z(i,o),new z(s,a))}}},{key:"midPoint",value:function(t,e){return new z((t.x+e.x)/2,(t.y+e.y)/2)}}]),e}(),wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"overlap",value:function(){if(2===arguments.length);else if(4===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[3];arguments[0].getLineSegment(t,this._overlapSeg1),e.getLineSegment(n,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}}}],[{key:"constructor_",value:function(){this._overlapSeg1=new bn,this._overlapSeg2=new bn}}]),e}(),In=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLineSegment",value:function(t,e){e.p0=this._pts[t],e.p1=this._pts[t+1]}},{key:"computeSelect",value:function(t,e,n,r){var i=this._pts[e],o=this._pts[n];if(n-e==1)return r.select(this,e),null;if(!t.intersects(i,o))return null;var s=Math.trunc((e+n)/2);e=t.length-1)return t.length-1;for(var r=We.quadrant(t[n],t[n+1]),i=e+1;in.getId()&&(n.computeOverlaps(i,t),this._nOverlaps++),this._segInt.isDone())return null}}}],[{key:"constructor_",value:function(){if(this._monoChains=new dt,this._index=new gn,this._idCounter=0,this._nodedSegStrings=null,this._nOverlaps=0,0===arguments.length);else if(1===arguments.length){var t=arguments[0];Mn.constructor_.call(this,t)}}}]),o}(Mn),Pn=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"overlap",value:function(){if(4!==arguments.length)return f(i(s.prototype),"overlap",this).apply(this,arguments);var t=arguments[1],e=arguments[2],n=arguments[3],r=arguments[0].getContext(),o=e.getContext();this._si.processIntersections(r,t,o,n)}}],[{key:"constructor_",value:function(){this._si=null;var t=arguments[0];this._si=t}}]),s}(wn);Ln.SegmentOverlapAction=Pn;var Cn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isDeletable",value:function(t,e,n,r){var i=this._inputLine[t],o=this._inputLine[e],s=this._inputLine[n];return!!this.isConcave(i,o,s)&&!!this.isShallow(i,o,s,r)&&this.isShallowSampled(i,o,t,n,r)}},{key:"deleteShallowConcavities",value:function(){for(var t=1,n=this.findNextNonDeletedIndex(t),r=this.findNextNonDeletedIndex(n),i=!1;r=0;r--)this.addPt(t[r])}},{key:"isRedundant",value:function(t){if(this._ptList.size()<1)return!1;var e=this._ptList.get(this._ptList.size()-1);return t.distance(e)Math.PI;)t-=e.PI_TIMES_2;for(;t<=-Math.PI;)t+=e.PI_TIMES_2;return t}},{key:"angle",value:function(){if(1===arguments.length){var t=arguments[0];return Math.atan2(t.y,t.x)}if(2===arguments.length){var e=arguments[0],n=arguments[1],r=n.x-e.x,i=n.y-e.y;return Math.atan2(i,r)}}},{key:"isAcute",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)>0}},{key:"isObtuse",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)<0}},{key:"interiorAngle",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return Math.abs(o-i)}},{key:"normalizePositive",value:function(t){if(t<0){for(;t<0;)t+=e.PI_TIMES_2;t>=e.PI_TIMES_2&&(t=0)}else{for(;t>=e.PI_TIMES_2;)t-=e.PI_TIMES_2;t<0&&(t=0)}return t}},{key:"angleBetween",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return e.diff(i,o)}},{key:"diff",value:function(t,e){var n=null;return(n=tMath.PI&&(n=2*Math.PI-n),n}},{key:"toRadians",value:function(t){return t*Math.PI/180}},{key:"getTurn",value:function(t,n){var r=Math.sin(n-t);return r>0?e.COUNTERCLOCKWISE:r<0?e.CLOCKWISE:e.NONE}},{key:"angleBetweenOriented",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r)-i;return o<=-Math.PI?o+e.PI_TIMES_2:o>Math.PI?o-e.PI_TIMES_2:o}}]),e}();On.PI_TIMES_2=2*Math.PI,On.PI_OVER_2=Math.PI/2,On.PI_OVER_4=Math.PI/4,On.COUNTERCLOCKWISE=ft.COUNTERCLOCKWISE,On.CLOCKWISE=ft.CLOCKWISE,On.NONE=ft.COLLINEAR;var Rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addNextSegment",value:function(t,e){if(this._s0=this._s1,this._s1=this._s2,this._s2=t,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;var n=ft.index(this._s0,this._s1,this._s2),r=n===ft.CLOCKWISE&&this._side===tt.LEFT||n===ft.COUNTERCLOCKWISE&&this._side===tt.RIGHT;0===n?this.addCollinear(e):r?this.addOutsideTurn(n,e):this.addInsideTurn(n,e)}},{key:"addLineEndCap",value:function(t,e){var n=new bn(t,e),r=new bn;this.computeOffsetSegment(n,tt.LEFT,this._distance,r);var i=new bn;this.computeOffsetSegment(n,tt.RIGHT,this._distance,i);var o=e.x-t.x,s=e.y-t.y,a=Math.atan2(s,o);switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:this._segList.addPt(r.p1),this.addDirectedFillet(e,a+Math.PI/2,a-Math.PI/2,ft.CLOCKWISE,this._distance),this._segList.addPt(i.p1);break;case y.CAP_FLAT:this._segList.addPt(r.p1),this._segList.addPt(i.p1);break;case y.CAP_SQUARE:var u=new z;u.x=Math.abs(this._distance)*Math.cos(a),u.y=Math.abs(this._distance)*Math.sin(a);var l=new z(r.p1.x+u.x,r.p1.y+u.y),h=new z(i.p1.x+u.x,i.p1.y+u.y);this._segList.addPt(l),this._segList.addPt(h)}}},{key:"getCoordinates",value:function(){return this._segList.getCoordinates()}},{key:"addMitreJoin",value:function(t,e,n,r){var i=_t.intersection(e.p0,e.p1,n.p0,n.p1);if(null!==i&&(r<=0?1:i.distance(t)/Math.abs(r))<=this._bufParams.getMitreLimit())return this._segList.addPt(i),null;this.addLimitedMitreJoin(e,n,r,this._bufParams.getMitreLimit())}},{key:"addOutsideTurn",value:function(t,n){if(this._offset0.p1.distance(this._offset1.p0)=h&&(a-=2*Math.PI),this._segList.addPt(e),this.addDirectedFillet(t,a,h,r,i),this._segList.addPt(n)}},{key:"addLastSegment",value:function(){this._segList.addPt(this._offset1.p1)}},{key:"initSideSegments",value:function(t,e,n){this._s1=t,this._s2=e,this._side=n,this._seg1.setCoordinates(t,e),this.computeOffsetSegment(this._seg1,n,this._distance,this._offset1)}},{key:"addLimitedMitreJoin",value:function(t,e,n,r){var i=this._seg0.p1,o=On.angle(i,this._seg0.p0),s=On.angleBetweenOriented(this._seg0.p0,i,this._seg1.p1)/2,a=On.normalize(o+s),u=On.normalize(a+Math.PI),l=r*n,h=n-l*Math.abs(Math.sin(s)),c=i.x+l*Math.cos(u),f=i.y+l*Math.sin(u),g=new z(c,f),p=new bn(i,g),v=p.pointAlongOffset(1,h),d=p.pointAlongOffset(1,-h);this._side===tt.LEFT?(this._segList.addPt(v),this._segList.addPt(d)):(this._segList.addPt(d),this._segList.addPt(v))}},{key:"addDirectedFillet",value:function(t,e,n,r,i){var o=r===ft.CLOCKWISE?-1:1,s=Math.abs(e-n),a=Math.trunc(s/this._filletAngleQuantum+.5);if(a<1)return null;for(var u=s/a,l=new z,h=0;h0){var r=new z((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(r);var i=new z((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(i)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}}},{key:"createCircle",value:function(t){var e=new z(t.x+this._distance,t.y);this._segList.addPt(e),this.addDirectedFillet(t,0,2*Math.PI,-1,this._distance),this._segList.closeRing()}},{key:"addBevelJoin",value:function(t,e){this._segList.addPt(t.p1),this._segList.addPt(e.p0)}},{key:"init",value:function(t){this._distance=t,this._maxCurveSegmentError=t*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new Tn,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(t*e.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)}},{key:"addCollinear",value:function(t){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2),this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===y.JOIN_BEVEL||this._bufParams.getJoinStyle()===y.JOIN_MITRE?(t&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,ft.CLOCKWISE,this._distance))}},{key:"closeRing",value:function(){this._segList.closeRing()}},{key:"hasNarrowConcaveAngle",value:function(){return this._hasNarrowConcaveAngle}}],[{key:"constructor_",value:function(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new bn,this._seg1=new bn,this._offset0=new bn,this._offset1=new bn,this._side=0,this._hasNarrowConcaveAngle=!1;var t=arguments[0],n=arguments[1],r=arguments[2];this._precisionModel=t,this._bufParams=n,this._li=new Ce,this._filletAngleQuantum=Math.PI/2/n.getQuadrantSegments(),n.getQuadrantSegments()>=8&&n.getJoinStyle()===y.JOIN_ROUND&&(this._closingSegLengthFactor=e.MAX_CLOSING_SEG_LEN_FACTOR),this.init(r)}}]),e}();Rn.OFFSET_SEGMENT_SEPARATION_FACTOR=.001,Rn.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR=.001,Rn.CURVE_VERTEX_SNAP_DISTANCE_FACTOR=1e-6,Rn.MAX_CLOSING_SEG_LEN_FACTOR=80;var An=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getOffsetCurve",value:function(t,e){if(this._distance=e,0===e)return null;var n=e<0,r=Math.abs(e),i=this.getSegGen(r);t.length<=1?this.computePointCurve(t[0],i):this.computeOffsetCurve(t,n,i);var o=i.getCoordinates();return n&&Wt.reverse(o),o}},{key:"computeSingleSidedBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){n.addSegments(t,!0);var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{n.addSegments(t,!1);var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment(),n.closeRing()}},{key:"computeRingBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);e===tt.RIGHT&&(r=-r);var i=Cn.simplify(t,r),o=i.length-1;n.initSideSegments(i[o-1],i[0],e);for(var s=1;s<=o;s++){var a=1!==s;n.addNextSegment(i[s],a)}n.closeRing()}},{key:"computeLineBufferCurve",value:function(t,e){var n=this.simplifyTolerance(this._distance),r=Cn.simplify(t,n),i=r.length-1;e.initSideSegments(r[0],r[1],tt.LEFT);for(var o=2;o<=i;o++)e.addNextSegment(r[o],!0);e.addLastSegment(),e.addLineEndCap(r[i-1],r[i]);var s=Cn.simplify(t,-n),a=s.length-1;e.initSideSegments(s[a],s[a-1],tt.LEFT);for(var u=a-2;u>=0;u--)e.addNextSegment(s[u],!0);e.addLastSegment(),e.addLineEndCap(s[1],s[0]),e.closeRing()}},{key:"computePointCurve",value:function(t,e){switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:e.createCircle(t);break;case y.CAP_SQUARE:e.createSquare(t)}}},{key:"getLineCurve",value:function(t,e){if(this._distance=e,this.isLineOffsetEmpty(e))return null;var n=Math.abs(e),r=this.getSegGen(n);if(t.length<=1)this.computePointCurve(t[0],r);else if(this._bufParams.isSingleSided()){var i=e<0;this.computeSingleSidedBufferCurve(t,i,r)}else this.computeLineBufferCurve(t,r);return r.getCoordinates()}},{key:"getBufferParameters",value:function(){return this._bufParams}},{key:"simplifyTolerance",value:function(t){return t*this._bufParams.getSimplifyFactor()}},{key:"getRingCurve",value:function(t,n,r){if(this._distance=r,t.length<=2)return this.getLineCurve(t,r);if(0===r)return e.copyCoordinates(t);var i=this.getSegGen(r);return this.computeRingBufferCurve(t,n,i),i.getCoordinates()}},{key:"computeOffsetCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment()}},{key:"isLineOffsetEmpty",value:function(t){return 0===t||t<0&&!this._bufParams.isSingleSided()}},{key:"getSegGen",value:function(t){return new Rn(this._precisionModel,this._bufParams,t)}}],[{key:"constructor_",value:function(){this._distance=0,this._precisionModel=null,this._bufParams=null;var t=arguments[0],e=arguments[1];this._precisionModel=t,this._bufParams=e}},{key:"copyCoordinates",value:function(t){for(var e=new Array(t.length).fill(null),n=0;ni.getMaxY()||this.findStabbedSegments(t,r.getDirectedEdges(),e)}return e}if(3===arguments.length)if(ot(arguments[2],rt)&&arguments[0]instanceof z&&arguments[1]instanceof Ke){for(var o=arguments[0],s=arguments[1],a=arguments[2],u=s.getEdge().getCoordinates(),l=0;lthis._seg.p1.y&&this._seg.reverse(),!(Math.max(this._seg.p0.x,this._seg.p1.x)this._seg.p1.y||ft.index(this._seg.p0,this._seg.p1,o)===ft.RIGHT)){var h=s.getDepth(tt.LEFT);this._seg.p0.equals(u[l])||(h=s.getDepth(tt.RIGHT));var c=new Fn(this._seg,h);a.add(c)}}else if(ot(arguments[2],rt)&&arguments[0]instanceof z&&ot(arguments[1],rt))for(var f=arguments[0],g=arguments[2],p=arguments[1].iterator();p.hasNext();){var v=p.next();v.isForward()&&this.findStabbedSegments(f,v,g)}}},{key:"getDepth",value:function(t){var e=this.findStabbedSegments(t);return 0===e.size()?0:an.min(e)._leftDepth}}],[{key:"constructor_",value:function(){this._subgraphs=null,this._seg=new bn;var t=arguments[0];this._subgraphs=t}}]),e}(),Fn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var e=t;if(this._upwardSeg.minX()>=e._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=e._upwardSeg.minX())return-1;var n=this._upwardSeg.orientationIndex(e._upwardSeg);return 0!==n||0!=(n=-1*e._upwardSeg.orientationIndex(this._upwardSeg))?n:this._upwardSeg.compareTo(e._upwardSeg)}},{key:"compareX",value:function(t,e){var n=t.p0.compareTo(e.p0);return 0!==n?n:t.p1.compareTo(e.p1)}},{key:"toString",value:function(){return this._upwardSeg.toString()}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._upwardSeg=null,this._leftDepth=null;var t=arguments[0],e=arguments[1];this._upwardSeg=new bn(t),this._leftDepth=e}}]),e}();Dn.DepthSegment=Fn;var qn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){_.constructor_.call(this,"Projective point not representable on the Cartesian plane.")}}]),o}(_),Vn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getY",value:function(){var t=this.y/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getX",value:function(){var t=this.x/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getCoordinate",value:function(){var t=new z;return t.x=this.getX(),t.y=this.getY(),t}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.w=null,0===arguments.length)this.x=0,this.y=0,this.w=1;else if(1===arguments.length){var t=arguments[0];this.x=t.x,this.y=t.y,this.w=1}else if(2===arguments.length){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var n=arguments[0],r=arguments[1];this.x=n,this.y=r,this.w=1}else if(arguments[0]instanceof e&&arguments[1]instanceof e){var i=arguments[0],o=arguments[1];this.x=i.y*o.w-o.y*i.w,this.y=o.x*i.w-i.x*o.w,this.w=i.x*o.y-o.x*i.y}else if(arguments[0]instanceof z&&arguments[1]instanceof z){var s=arguments[0],a=arguments[1];this.x=s.y-a.y,this.y=a.x-s.x,this.w=s.x*a.y-a.x*s.y}}else if(3===arguments.length){var u=arguments[0],l=arguments[1],h=arguments[2];this.x=u,this.y=l,this.w=h}else if(4===arguments.length){var c=arguments[0],f=arguments[1],g=arguments[2],p=arguments[3],v=c.y-f.y,d=f.x-c.x,y=c.x*f.y-f.x*c.y,m=g.y-p.y,_=p.x-g.x,x=g.x*p.y-p.x*g.y;this.x=d*x-_*y,this.y=m*y-v*x,this.w=v*_-m*d}}}]),e}(),Gn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"area",value:function(){return e.area(this.p0,this.p1,this.p2)}},{key:"signedArea",value:function(){return e.signedArea(this.p0,this.p1,this.p2)}},{key:"interpolateZ",value:function(t){if(null===t)throw new x("Supplied point is null.");return e.interpolateZ(t,this.p0,this.p1,this.p2)}},{key:"longestSideLength",value:function(){return e.longestSideLength(this.p0,this.p1,this.p2)}},{key:"isAcute",value:function(){return e.isAcute(this.p0,this.p1,this.p2)}},{key:"circumcentre",value:function(){return e.circumcentre(this.p0,this.p1,this.p2)}},{key:"area3D",value:function(){return e.area3D(this.p0,this.p1,this.p2)}},{key:"centroid",value:function(){return e.centroid(this.p0,this.p1,this.p2)}},{key:"inCentre",value:function(){return e.inCentre(this.p0,this.p1,this.p2)}}],[{key:"constructor_",value:function(){this.p0=null,this.p1=null,this.p2=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.p0=t,this.p1=e,this.p2=n}},{key:"area",value:function(t,e,n){return Math.abs(((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2)}},{key:"signedArea",value:function(t,e,n){return((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2}},{key:"det",value:function(t,e,n,r){return t*r-e*n}},{key:"interpolateZ",value:function(t,e,n,r){var i=e.x,o=e.y,s=n.x-i,a=r.x-i,u=n.y-o,l=r.y-o,h=s*l-a*u,c=t.x-i,f=t.y-o,g=(l*c-a*f)/h,p=(-u*c+s*f)/h;return e.getZ()+g*(n.getZ()-e.getZ())+p*(r.getZ()-e.getZ())}},{key:"longestSideLength",value:function(t,e,n){var r=t.distance(e),i=e.distance(n),o=n.distance(t),s=r;return i>s&&(s=i),o>s&&(s=o),s}},{key:"circumcentreDD",value:function(t,e,n){var r=lt.valueOf(t.x).subtract(n.x),i=lt.valueOf(t.y).subtract(n.y),o=lt.valueOf(e.x).subtract(n.x),s=lt.valueOf(e.y).subtract(n.y),a=lt.determinant(r,i,o,s).multiply(2),u=r.sqr().add(i.sqr()),l=o.sqr().add(s.sqr()),h=lt.determinant(i,u,s,l),c=lt.determinant(r,u,o,l),f=lt.valueOf(n.x).subtract(h.divide(a)).doubleValue(),g=lt.valueOf(n.y).add(c.divide(a)).doubleValue();return new z(f,g)}},{key:"isAcute",value:function(t,e,n){return!!On.isAcute(t,e,n)&&!!On.isAcute(e,n,t)&&!!On.isAcute(n,t,e)}},{key:"circumcentre",value:function(t,n,r){var i=r.x,o=r.y,s=t.x-i,a=t.y-o,u=n.x-i,l=n.y-o,h=2*e.det(s,a,u,l),c=e.det(a,s*s+a*a,l,u*u+l*l),f=e.det(s,s*s+a*a,u,u*u+l*l);return new z(i-c/h,o+f/h)}},{key:"perpendicularBisector",value:function(t,e){var n=e.x-t.x,r=e.y-t.y,i=new Vn(t.x+n/2,t.y+r/2,1),o=new Vn(t.x-r+n/2,t.y+n+r/2,1);return new Vn(i,o)}},{key:"angleBisector",value:function(t,e,n){var r=e.distance(t),i=r/(r+e.distance(n)),o=n.x-t.x,s=n.y-t.y;return new z(t.x+i*o,t.y+i*s)}},{key:"area3D",value:function(t,e,n){var r=e.x-t.x,i=e.y-t.y,o=e.getZ()-t.getZ(),s=n.x-t.x,a=n.y-t.y,u=n.getZ()-t.getZ(),l=i*u-o*a,h=o*s-r*u,c=r*a-i*s,f=l*l+h*h+c*c;return Math.sqrt(f)/2}},{key:"centroid",value:function(t,e,n){var r=(t.x+e.x+n.x)/3,i=(t.y+e.y+n.y)/3;return new z(r,i)}},{key:"inCentre",value:function(t,e,n){var r=e.distance(n),i=t.distance(n),o=t.distance(e),s=r+i+o,a=(r*t.x+i*e.x+o*n.x)/s,u=(r*t.y+i*e.y+o*n.y)/s;return new z(a,u)}}]),e}(),Bn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addRingSide",value:function(t,e,n,r,i){if(0===e&&t.length=zt.MINIMUM_VALID_SIZE&&ft.isCCW(t)&&(o=i,s=r,n=tt.opposite(n));var a=this._curveBuilder.getRingCurve(t,n,e);this.addCurve(a,o,s)}},{key:"addRingBothSides",value:function(t,e){this.addRingSide(t,e,tt.LEFT,Z.EXTERIOR,Z.INTERIOR),this.addRingSide(t,e,tt.RIGHT,Z.INTERIOR,Z.EXTERIOR)}},{key:"addPoint",value:function(t){if(this._distance<=0)return null;var e=t.getCoordinates(),n=this._curveBuilder.getLineCurve(e,this._distance);this.addCurve(n,Z.EXTERIOR,Z.INTERIOR)}},{key:"addPolygon",value:function(t){var e=this._distance,n=tt.LEFT;this._distance<0&&(e=-this._distance,n=tt.RIGHT);var r=t.getExteriorRing(),i=Wt.removeRepeatedPoints(r.getCoordinates());if(this._distance<0&&this.isErodedCompletely(r,this._distance))return null;if(this._distance<=0&&i.length<3)return null;this.addRingSide(i,e,n,Z.EXTERIOR,Z.INTERIOR);for(var o=0;o0&&this.isErodedCompletely(s,-this._distance)||this.addRingSide(a,e,tt.opposite(n),Z.INTERIOR,Z.EXTERIOR)}}},{key:"isTriangleErodedCompletely",value:function(t,e){var n=new Gn(t[0],t[1],t[2]),r=n.inCentre();return kt.pointToSegment(r,n.p0,n.p1)i}},{key:"addCollection",value:function(t){for(var e=0;e=this._max)throw new W;var t=this._parent.getGeometryN(this._index++);return t instanceof Bt?(this._subcollectionIterator=new e(t),this._subcollectionIterator.next()):t}},{key:"remove",value:function(){throw new J(this.getClass().getName())}},{key:"hasNext",value:function(){if(this._atStart)return!0;if(null!==this._subcollectionIterator){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)}},{key:"interfaces_",get:function(){return[yn]}}],[{key:"constructor_",value:function(){this._parent=null,this._atStart=null,this._max=null,this._index=null,this._subcollectionIterator=null;var t=arguments[0];this._parent=t,this._atStart=!0,this._index=0,this._max=t.getNumGeometries()}},{key:"isAtomic",value:function(t){return!(t instanceof Bt)}}]),e}(),jn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"locate",value:function(t){return e.locate(t,this._geom)}},{key:"interfaces_",get:function(){return[Yn]}}],[{key:"constructor_",value:function(){this._geom=null;var t=arguments[0];this._geom=t}},{key:"locatePointInPolygon",value:function(t,n){if(n.isEmpty())return Z.EXTERIOR;var r=n.getExteriorRing(),i=e.locatePointInRing(t,r);if(i!==Z.INTERIOR)return i;for(var o=0;o=0;n--){var r=this._edgeList.get(n),i=r.getSym();null===e&&(e=i),null!==t&&i.setNext(t),t=r}e.setNext(t)}},{key:"computeDepths",value:function(){if(1===arguments.length){var t=arguments[0],e=this.findIndex(t),n=t.getDepth(tt.LEFT),r=t.getDepth(tt.RIGHT),i=this.computeDepths(e+1,this._edgeList.size(),n);if(this.computeDepths(0,e,i)!==r)throw new pt("depth mismatch at "+t.getCoordinate())}else if(3===arguments.length){for(var o=arguments[1],s=arguments[2],a=arguments[0];a=0;i--){var o=this._resultAreaEdgeList.get(i),s=o.getSym();switch(null===e&&o.getEdgeRing()===t&&(e=o),r){case this._SCANNING_FOR_INCOMING:if(s.getEdgeRing()!==t)continue;n=s,r=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(o.getEdgeRing()!==t)continue;n.setNextMin(o),r=this._SCANNING_FOR_INCOMING}}r===this._LINKING_TO_OUTGOING&&(V.isTrue(null!==e,"found null for first outgoing dirEdge"),V.isTrue(e.getEdgeRing()===t,"unable to link last incoming dirEdge"),n.setNextMin(e))}},{key:"getOutgoingDegree",value:function(){if(0===arguments.length){for(var t=0,e=this.iterator();e.hasNext();)e.next().isInResult()&&t++;return t}if(1===arguments.length){for(var n=arguments[0],r=0,i=this.iterator();i.hasNext();)i.next().getEdgeRing()===n&&r++;return r}}},{key:"getLabel",value:function(){return this._label}},{key:"findCoveredLineEdges",value:function(){for(var t=Z.NONE,e=this.iterator();e.hasNext();){var n=e.next(),r=n.getSym();if(!n.isLineEdge()){if(n.isInResult()){t=Z.INTERIOR;break}if(r.isInResult()){t=Z.EXTERIOR;break}}}if(t===Z.NONE)return null;for(var i=t,o=this.iterator();o.hasNext();){var s=o.next(),a=s.getSym();s.isLineEdge()?s.getEdge().setCovered(i===Z.INTERIOR):(s.isInResult()&&(i=Z.EXTERIOR),a.isInResult()&&(i=Z.INTERIOR))}}},{key:"computeLabelling",value:function(t){f(i(s.prototype),"computeLabelling",this).call(this,t),this._label=new Ae(Z.NONE);for(var e=this.iterator();e.hasNext();)for(var n=e.next().getEdge().getLabel(),r=0;r<2;r++){var o=n.getLocation(r);o!==Z.INTERIOR&&o!==Z.BOUNDARY||this._label.setLocation(r,Z.INTERIOR)}}}],[{key:"constructor_",value:function(){this._resultAreaEdgeList=null,this._label=null,this._SCANNING_FOR_INCOMING=1,this._LINKING_TO_OUTGOING=2}}]),s}(Xn),Zn=function(e){r(o,e);var i=c(o);function o(){return t(this,o),i.call(this)}return n(o,[{key:"createNode",value:function(t){return new Ge(t,new Un)}}]),o}(Qe),Hn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var n=t;return e.compareOriented(this._pts,this._orientation,n._pts,n._orientation)}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._pts=null,this._orientation=null;var t=arguments[0];this._pts=t,this._orientation=e.orientation(t)}},{key:"orientation",value:function(t){return 1===Wt.increasingDirection(t)}},{key:"compareOriented",value:function(t,e,n,r){for(var i=e?1:-1,o=r?1:-1,s=e?t.length:-1,a=r?n.length:-1,u=e?0:t.length-1,l=r?0:n.length-1;;){var h=t[u].compareTo(n[l]);if(0!==h)return h;var c=(u+=i)===s,f=(l+=o)===a;if(c&&!f)return-1;if(!c&&f)return 1;if(c&&f)return 0}}}]),e}(),Wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.print("MULTILINESTRING ( ");for(var e=0;e0&&t.print(","),t.print("(");for(var r=n.getCoordinates(),i=0;i0&&t.print(","),t.print(r[i].x+" "+r[i].y);t.println(")")}t.print(") ")}},{key:"addAll",value:function(t){for(var e=t.iterator();e.hasNext();)this.add(e.next())}},{key:"findEdgeIndex",value:function(t){for(var e=0;et?1:this.diste?1:0}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this.coord=null,this.segmentIndex=null,this.dist=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.coord=new z(t),this.segmentIndex=e,this.dist=n}}]),e}(),$n=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this._nodeMap.values().iterator()}},{key:"addSplitEdges",value:function(t){this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next(),i=this.createSplitEdge(n,r);t.add(i),n=r}}},{key:"addEndpoints",value:function(){var t=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[t],t,0)}},{key:"createSplitEdge",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2,r=this.edge.pts[e.segmentIndex],i=e.dist>0||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this.edge.pts[a];return i&&(o[s]=e.coord),new or(o,new Ae(this.edge._label))}},{key:"add",value:function(t,e,n){var r=new Qn(t,e,n),i=this._nodeMap.get(r);return null!==i?i:(this._nodeMap.put(r,r),r)}},{key:"isIntersection",value:function(t){for(var e=this.iterator();e.hasNext();)if(e.next().coord.equals(t))return!0;return!1}}],[{key:"constructor_",value:function(){this._nodeMap=new Ze,this.edge=null;var t=arguments[0];this.edge=t}}]),e}(),tr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isIntersects",value:function(){return!this.isDisjoint()}},{key:"isCovers",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"isCoveredBy",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"set",value:function(){if(1===arguments.length)for(var t=arguments[0],e=0;e=0&&e>=0&&this.setAtLeast(t,e,n)}},{key:"isWithin",value:function(){return e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"isTouches",value:function(t,n){return t>n?this.isTouches(n,t):(t===Mt.A&&n===Mt.A||t===Mt.L&&n===Mt.L||t===Mt.L&&n===Mt.A||t===Mt.P&&n===Mt.A||t===Mt.P&&n===Mt.L)&&this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&(e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))}},{key:"isOverlaps",value:function(t,n){return t===Mt.P&&n===Mt.P||t===Mt.A&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&1===this._matrix[Z.INTERIOR][Z.INTERIOR]&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR])}},{key:"isEquals",value:function(t,n){return t===n&&e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"toString",value:function(){for(var t=new Qt("123456789"),e=0;e<3;e++)for(var n=0;n<3;n++)t.setCharAt(3*e+n,Mt.toDimensionSymbol(this._matrix[e][n]));return t.toString()}},{key:"setAll",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this._matrix[e][n]=t}},{key:"get",value:function(t,e){return this._matrix[t][e]}},{key:"transpose",value:function(){var t=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=t,t=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=t,t=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=t,this}},{key:"matches",value:function(t){if(9!==t.length)throw new x("Should be length 9: "+t);for(var n=0;n<3;n++)for(var r=0;r<3;r++)if(!e.matches(this._matrix[n][r],t.charAt(3*n+r)))return!1;return!0}},{key:"add",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this.setAtLeast(e,n,t.get(e,n))}},{key:"isDisjoint",value:function(){return this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.INTERIOR][Z.BOUNDARY]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.BOUNDARY]===Mt.FALSE}},{key:"isCrosses",value:function(t,n){return t===Mt.P&&n===Mt.L||t===Mt.P&&n===Mt.A||t===Mt.L&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR]):t===Mt.L&&n===Mt.P||t===Mt.A&&n===Mt.P||t===Mt.A&&n===Mt.L?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&0===this._matrix[Z.INTERIOR][Z.INTERIOR]}},{key:"interfaces_",get:function(){return[b]}}],[{key:"constructor_",value:function(){if(this._matrix=null,0===arguments.length)this._matrix=Array(3).fill().map((function(){return Array(3)})),this.setAll(Mt.FALSE);else if(1===arguments.length)if("string"==typeof arguments[0]){var t=arguments[0];e.constructor_.call(this),this.set(t)}else if(arguments[0]instanceof e){var n=arguments[0];e.constructor_.call(this),this._matrix[Z.INTERIOR][Z.INTERIOR]=n._matrix[Z.INTERIOR][Z.INTERIOR],this._matrix[Z.INTERIOR][Z.BOUNDARY]=n._matrix[Z.INTERIOR][Z.BOUNDARY],this._matrix[Z.INTERIOR][Z.EXTERIOR]=n._matrix[Z.INTERIOR][Z.EXTERIOR],this._matrix[Z.BOUNDARY][Z.INTERIOR]=n._matrix[Z.BOUNDARY][Z.INTERIOR],this._matrix[Z.BOUNDARY][Z.BOUNDARY]=n._matrix[Z.BOUNDARY][Z.BOUNDARY],this._matrix[Z.BOUNDARY][Z.EXTERIOR]=n._matrix[Z.BOUNDARY][Z.EXTERIOR],this._matrix[Z.EXTERIOR][Z.INTERIOR]=n._matrix[Z.EXTERIOR][Z.INTERIOR],this._matrix[Z.EXTERIOR][Z.BOUNDARY]=n._matrix[Z.EXTERIOR][Z.BOUNDARY],this._matrix[Z.EXTERIOR][Z.EXTERIOR]=n._matrix[Z.EXTERIOR][Z.EXTERIOR]}}},{key:"matches",value:function(){if(Number.isInteger(arguments[0])&&"string"==typeof arguments[1]){var t=arguments[0],n=arguments[1];return n===Mt.SYM_DONTCARE||n===Mt.SYM_TRUE&&(t>=0||t===Mt.TRUE)||n===Mt.SYM_FALSE&&t===Mt.FALSE||n===Mt.SYM_P&&t===Mt.P||n===Mt.SYM_L&&t===Mt.L||n===Mt.SYM_A&&t===Mt.A}if("string"==typeof arguments[0]&&"string"==typeof arguments[1]){var r=arguments[1];return new e(arguments[0]).matches(r)}}},{key:"isTrue",value:function(t){return t>=0||t===Mt.TRUE}}]),e}(),er=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"size",value:function(){return this._size}},{key:"addAll",value:function(t){return null===t||0===t.length?null:(this.ensureCapacity(this._size+t.length),xt.arraycopy(t,0,this._data,this._size,t.length),void(this._size+=t.length))}},{key:"ensureCapacity",value:function(t){if(t<=this._data.length)return null;var e=Math.max(t,2*this._data.length);this._data=At.copyOf(this._data,e)}},{key:"toArray",value:function(){var t=new Array(this._size).fill(null);return xt.arraycopy(this._data,0,t,0,this._size),t}},{key:"add",value:function(t){this.ensureCapacity(this._size+1),this._data[this._size]=t,++this._size}}],[{key:"constructor_",value:function(){if(this._data=null,this._size=0,0===arguments.length)e.constructor_.call(this,10);else if(1===arguments.length){var t=arguments[0];this._data=new Array(t).fill(null)}}}]),e}(),nr=function(){function e(){t(this,e)}return n(e,[{key:"getChainStartIndices",value:function(t){var e=0,n=new er(Math.trunc(t.length/2));n.add(e);do{var r=this.findChainEnd(t,e);n.add(r),e=r}while(en?e:n}},{key:"getMinX",value:function(t){var e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return ee&&(r=1),this._depth[t][n]=r}}}},{key:"getDelta",value:function(t){return this._depth[t][tt.RIGHT]-this._depth[t][tt.LEFT]}},{key:"getLocation",value:function(t,e){return this._depth[t][e]<=0?Z.EXTERIOR:Z.INTERIOR}},{key:"toString",value:function(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}},{key:"add",value:function(){if(1===arguments.length)for(var t=arguments[0],n=0;n<2;n++)for(var r=1;r<3;r++){var i=t.getLocation(n,r);i!==Z.EXTERIOR&&i!==Z.INTERIOR||(this.isNull(n,r)?this._depth[n][r]=e.depthAtLocation(i):this._depth[n][r]+=e.depthAtLocation(i))}else if(3===arguments.length){var o=arguments[0],s=arguments[1];arguments[2]===Z.INTERIOR&&this._depth[o][s]++}}}],[{key:"constructor_",value:function(){this._depth=Array(2).fill().map((function(){return Array(3)}));for(var t=0;t<2;t++)for(var n=0;n<3;n++)this._depth[t][n]=e.NULL_VALUE}},{key:"depthAtLocation",value:function(t){return t===Z.EXTERIOR?0:t===Z.INTERIOR?1:e.NULL_VALUE}}]),e}();ir.NULL_VALUE=-1;var or=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getDepth",value:function(){return this._depth}},{key:"getCollapsedEdge",value:function(){var t=new Array(2).fill(null);return t[0]=this.pts[0],t[1]=this.pts[1],new s(t,Ae.toLineLabel(this._label))}},{key:"isIsolated",value:function(){return this._isIsolated}},{key:"getCoordinates",value:function(){return this.pts}},{key:"setIsolated",value:function(t){this._isIsolated=t}},{key:"setName",value:function(t){this._name=t}},{key:"equals",value:function(t){if(!(t instanceof s))return!1;var e=t;if(this.pts.length!==e.pts.length)return!1;for(var n=!0,r=!0,i=this.pts.length,o=0;o0?this.pts[0]:null;if(1===arguments.length){var t=arguments[0];return this.pts[t]}}},{key:"print",value:function(t){t.print("edge "+this._name+": "),t.print("LINESTRING (");for(var e=0;e0&&t.print(","),t.print(this.pts[e].x+" "+this.pts[e].y);t.print(") "+this._label+" "+this._depthDelta)}},{key:"computeIM",value:function(t){s.updateIM(this._label,t)}},{key:"isCollapsed",value:function(){return!!this._label.isArea()&&3===this.pts.length&&!!this.pts[0].equals(this.pts[2])}},{key:"isClosed",value:function(){return this.pts[0].equals(this.pts[this.pts.length-1])}},{key:"getMaximumSegmentIndex",value:function(){return this.pts.length-1}},{key:"getDepthDelta",value:function(){return this._depthDelta}},{key:"getNumPoints",value:function(){return this.pts.length}},{key:"printReverse",value:function(t){t.print("edge "+this._name+": ");for(var e=this.pts.length-1;e>=0;e--)t.print(this.pts[e]+" ");t.println("")}},{key:"getMonotoneChainEdge",value:function(){return null===this._mce&&(this._mce=new rr(this)),this._mce}},{key:"getEnvelope",value:function(){if(null===this._env){this._env=new X;for(var t=0;t0&&t.append(","),t.append(this.pts[e].x+" "+this.pts[e].y);return t.append(") "+this._label+" "+this._depthDelta),t.toString()}},{key:"isPointwiseEqual",value:function(t){if(this.pts.length!==t.pts.length)return!1;for(var e=0;er||this._maxyo;if(s)return!1;var a=this.intersectsToleranceSquare(t,e);return V.isTrue(!(s&&a),"Found bad envelope test"),a}},{key:"initCorners",value:function(t){var e=.5;this._minx=t.x-e,this._maxx=t.x+e,this._miny=t.y-e,this._maxy=t.y+e,this._corner[0]=new z(this._maxx,this._maxy),this._corner[1]=new z(this._minx,this._maxy),this._corner[2]=new z(this._minx,this._miny),this._corner[3]=new z(this._maxx,this._miny)}},{key:"intersects",value:function(t,e){return 1===this._scaleFactor?this.intersectsScaled(t,e):(this.copyScaled(t,this._p0Scaled),this.copyScaled(e,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}},{key:"scale",value:function(t){return Math.round(t*this._scaleFactor)}},{key:"getCoordinate",value:function(){return this._originalPt}},{key:"copyScaled",value:function(t,e){e.x=this.scale(t.x),e.y=this.scale(t.y)}},{key:"getSafeEnvelope",value:function(){if(null===this._safeEnv){var t=e.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new X(this._originalPt.x-t,this._originalPt.x+t,this._originalPt.y-t,this._originalPt.y+t)}return this._safeEnv}},{key:"intersectsPixelClosure",value:function(t,e){return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.hasIntersection()))))}},{key:"intersectsToleranceSquare",value:function(t,e){var n=!1,r=!1;return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.isProper()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.isProper()||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.isProper()||(this._li.hasIntersection()&&(r=!0),this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.isProper()||n&&r||t.equals(this._pt)||e.equals(this._pt)))))}},{key:"addSnappedNode",value:function(t,e){var n=t.getCoordinate(e),r=t.getCoordinate(e+1);return!!this.intersects(n,r)&&(t.addIntersection(this.getCoordinate(),e),!0)}}],[{key:"constructor_",value:function(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;var t=arguments[0],e=arguments[1],n=arguments[2];if(this._originalPt=t,this._pt=t,this._scaleFactor=e,this._li=n,e<=0)throw new x("Scale factor must be non-zero");1!==e&&(this._pt=new z(this.scale(t.x),this.scale(t.y)),this._p0Scaled=new z,this._p1Scaled=new z),this.initCorners(this._pt)}}]),e}();lr.SAFE_ENV_EXPANSION_FACTOR=.75;var hr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"select",value:function(){if(1===arguments.length);else if(2===arguments.length){var t=arguments[1];arguments[0].getLineSegment(t,this.selectedSegment),this.select(this.selectedSegment)}}}],[{key:"constructor_",value:function(){this.selectedSegment=new bn}}]),e}(),cr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"snap",value:function(){if(1===arguments.length){var e=arguments[0];return this.snap(e,null,-1)}if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=r.getSafeEnvelope(),a=new fr(r,i,o);return this._index.query(s,new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[hn]}},{key:"visitItem",value:function(t){t.select(s,a)}}]),e}())),a.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var t=arguments[0];this._index=t}}]),e}(),fr=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isNodeAdded",value:function(){return this._isNodeAdded}},{key:"select",value:function(){if(!(2===arguments.length&&Number.isInteger(arguments[1])&&arguments[0]instanceof In))return f(i(s.prototype),"select",this).apply(this,arguments);var t=arguments[1],e=arguments[0].getContext();if(this._parentEdge===e&&(t===this._hotPixelVertexIndex||t+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(e,t)}}],[{key:"constructor_",value:function(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var t=arguments[0],e=arguments[1],n=arguments[2];this._hotPixel=t,this._parentEdge=e,this._hotPixelVertexIndex=n}}]),s}(hr);cr.HotPixelSnapAction=fr;var gr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"processIntersections",value:function(t,e,n,r){if(t===n&&e===r)return null;var i=t.getCoordinates()[e],o=t.getCoordinates()[e+1],s=n.getCoordinates()[r],a=n.getCoordinates()[r+1];if(this._li.computeIntersection(i,o,s,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var u=0;u=0;t--){try{this.bufferReducedPrecision(t)}catch(t){if(!(t instanceof pt))throw t;this._saveException=t}if(null!==this._resultGeometry)return null}throw this._saveException}if(1===arguments.length){var n=arguments[0],r=e.precisionScaleFactor(this._argGeom,this._distance,n),i=new ie(r);this.bufferFixedPrecision(i)}}},{key:"computeGeometry",value:function(){if(this.bufferOriginalPrecision(),null!==this._resultGeometry)return null;var t=this._argGeom.getFactory().getPrecisionModel();t.getType()===ie.FIXED?this.bufferFixedPrecision(t):this.bufferReducedPrecision()}},{key:"setQuadrantSegments",value:function(t){this._bufParams.setQuadrantSegments(t)}},{key:"bufferOriginalPrecision",value:function(){try{var t=new sr(this._bufParams);this._resultGeometry=t.buffer(this._argGeom,this._distance)}catch(t){if(!(t instanceof F))throw t;this._saveException=t}}},{key:"getResultGeometry",value:function(t){return this._distance=t,this.computeGeometry(),this._resultGeometry}},{key:"setEndCapStyle",value:function(t){this._bufParams.setEndCapStyle(t)}}],[{key:"constructor_",value:function(){if(this._argGeom=null,this._distance=null,this._bufParams=new y,this._resultGeometry=null,this._saveException=null,1===arguments.length){var t=arguments[0];this._argGeom=t}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this._argGeom=e,this._bufParams=n}}},{key:"bufferOp",value:function(){if(2===arguments.length){var t=arguments[1];return new e(arguments[0]).getResultGeometry(t)}if(3===arguments.length){if(Number.isInteger(arguments[2])&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var n=arguments[1],r=arguments[2],i=new e(arguments[0]);return i.setQuadrantSegments(r),i.getResultGeometry(n)}if(arguments[2]instanceof y&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var o=arguments[1];return new e(arguments[0],arguments[2]).getResultGeometry(o)}}else if(4===arguments.length){var s=arguments[1],a=arguments[2],u=arguments[3],l=new e(arguments[0]);return l.setQuadrantSegments(a),l.setEndCapStyle(u),l.getResultGeometry(s)}}},{key:"precisionScaleFactor",value:function(t,e,n){var r=t.getEnvelopeInternal(),i=Et.max(Math.abs(r.getMaxX()),Math.abs(r.getMaxY()),Math.abs(r.getMinX()),Math.abs(r.getMinY()))+2*(e>0?e:0),o=n-Math.trunc(Math.log(i)/Math.log(10)+1);return Math.pow(10,o)}}]),e}();vr.CAP_ROUND=y.CAP_ROUND,vr.CAP_BUTT=y.CAP_FLAT,vr.CAP_FLAT=y.CAP_FLAT,vr.CAP_SQUARE=y.CAP_SQUARE,vr.MAX_PRECISION_DIGITS=12;var dr=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],yr=function(){function e(n){t(this,e),this.geometryFactory=n||new ae}return n(e,[{key:"read",value:function(t){var e,n=(e="string"==typeof t?JSON.parse(t):t).type;if(!mr[n])throw new Error("Unknown GeoJSON type: "+e.type);return-1!==dr.indexOf(n)?mr[n].call(this,e.coordinates):"GeometryCollection"===n?mr[n].call(this,e.geometries):mr[n].call(this,e)}},{key:"write",value:function(t){var e=t.getGeometryType();if(!_r[e])throw new Error("Geometry is not supported");return _r[e].call(this,t)}}]),e}(),mr={Feature:function(t){var e={};for(var n in t)e[n]=t[n];if(t.geometry){var r=t.geometry.type;if(!mr[r])throw new Error("Unknown GeoJSON type: "+t.type);e.geometry=this.read(t.geometry)}return t.bbox&&(e.bbox=mr.bbox.call(this,t.bbox)),e},FeatureCollection:function(t){var e={};if(t.features){e.features=[];for(var n=0;n1?0:t<-1?Xn:Math.acos(t)}function ir(t){return t>1?Un:t<-1?-Un:Math.asin(t)}function or(){}function sr(t,e){t&&ur.hasOwnProperty(t.type)&&ur[t.type](t,e)}var ar={Feature:function(t,e){sr(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++rXn?t-Hn:t<-Xn?t+Hn:t,e]}function xr(t){return function(e,n){return[(e+=t)>Xn?e-Hn:e<-Xn?e+Hn:e,n]}}function Er(t){var e=xr(t);return e.invert=xr(-t),e}function kr(t,e){var n=tr(t),r=er(t),i=tr(e),o=er(e);function s(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*n+a*r;return[$n(u*i-h*o,a*n-l*r),ir(h*i+u*o)]}return s.invert=function(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*i-u*o;return[$n(u*i+l*o,a*n+h*r),ir(h*n-a*r)]},s}function br(t,e){(e=fr(e))[0]-=t,yr(e);var n=rr(-e[1]);return((-e[2]<0?-n:n)+Hn-jn)%Hn}function wr(){var t,e=[];return{point:function(e,n){t.push([e,n])},lineStart:function(){e.push(t=[])},lineEnd:or,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function Ir(t,e){return Kn(t[0]-e[0])=0;--o)i.point((h=l[o])[0],h[1]);else r(f.x,f.p.x,-1,i);f=f.p}l=(f=f.o).z,g=!g}while(!f.v);i.lineEnd()}}}function Mr(t){if(e=t.length){for(var e,n,r=0,i=t[0];++re?1:t>=e?0:NaN}function Pr(t){for(var e,n,r,i=t.length,o=-1,s=0;++o=0;)for(e=(r=t[i]).length;--e>=0;)n[--s]=r[e];return n}Gn(),Gn(),Gn(),_r.invert=_r,function(t){var e;1===t.length&&(e=t,t=function(t,n){return Lr(e(t),n)})}(Lr);var Cr=1e9,Tr=-Cr;function Or(t,e,n,r){function i(i,o){return t<=i&&i<=n&&e<=o&&o<=r}function o(i,o,a,l){var h=0,c=0;if(null==i||(h=s(i,a))!==(c=s(o,a))||u(i,o)<0^a>0)do{l.point(0===h||3===h?t:n,h>1?r:e)}while((h=(h+a+4)%4)!==c);else l.point(o[0],o[1])}function s(r,i){return Kn(r[0]-t)0?0:3:Kn(r[0]-n)0?2:1:Kn(r[1]-e)0?1:0:i>0?3:2}function a(t,e){return u(t.x,e.x)}function u(t,e){var n=s(t,1),r=s(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){var u,l,h,c,f,g,p,v,d,y,m,_=s,x=wr(),E={point:k,lineStart:function(){E.point=b,l&&l.push(h=[]);y=!0,d=!1,p=v=NaN},lineEnd:function(){u&&(b(c,f),g&&d&&x.rejoin(),u.push(x.result()));E.point=k,d&&_.lineEnd()},polygonStart:function(){_=x,u=[],l=[],m=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,i=l.length;nr&&(f-o)*(r-s)>(g-s)*(t-o)&&++e:g<=r&&(f-o)*(r-s)<(g-s)*(t-o)&&--e;return e}(),n=m&&e,i=(u=Pr(u)).length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),o(null,null,1,s),s.lineEnd()),i&&Sr(u,a,e,o,s),s.polygonEnd());_=s,u=l=h=null}};function k(t,e){i(t,e)&&_.point(t,e)}function b(o,s){var a=i(o,s);if(l&&h.push([o,s]),y)c=o,f=s,g=a,y=!1,a&&(_.lineStart(),_.point(o,s));else if(a&&d)_.point(o,s);else{var u=[p=Math.max(Tr,Math.min(Cr,p)),v=Math.max(Tr,Math.min(Cr,v))],x=[o=Math.max(Tr,Math.min(Cr,o)),s=Math.max(Tr,Math.min(Cr,s))];!function(t,e,n,r,i,o){var s,a=t[0],u=t[1],l=0,h=1,c=e[0]-a,f=e[1]-u;if(s=n-a,c||!(s>0)){if(s/=c,c<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=i-a,c||!(s<0)){if(s/=c,c<0){if(s>h)return;s>l&&(l=s)}else if(c>0){if(s0)){if(s/=f,f<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=o-u,f||!(s<0)){if(s/=f,f<0){if(s>h)return;s>l&&(l=s)}else if(f>0){if(s0&&(t[0]=a+l*c,t[1]=u+l*f),h<1&&(e[0]=a+h*c,e[1]=u+h*f),!0}}}}}(u,x,t,e,n,r)?a&&(_.lineStart(),_.point(o,s),m=!1):(d||(_.lineStart(),_.point(u[0],u[1])),_.point(x[0],x[1]),a||_.lineEnd(),m=!1)}p=o,v=s,d=a}return E}}var Rr=Gn();function Ar(t){return t}Gn(),Gn(),Gn();var Dr=1/0,Fr=Dr,qr=-Dr,Vr=qr,Gr={point:function(t,e){tqr&&(qr=t);eVr&&(Vr=e)},lineStart:or,lineEnd:or,polygonStart:or,polygonEnd:or,result:function(){var t=[[Dr,Fr],[qr,Vr]];return qr=Vr=-(Fr=Dr=1/0),t}};function Br(t,e,n,r){return function(i,o){var s,a,u,l=e(o),h=i.invert(r[0],r[1]),c=wr(),f=e(c),g=!1,p={point:v,lineStart:y,lineEnd:m,polygonStart:function(){p.point=_,p.lineStart=x,p.lineEnd=E,a=[],s=[]},polygonEnd:function(){p.point=v,p.lineStart=y,p.lineEnd=m,a=Pr(a);var t=function(t,e){var n=e[0],r=e[1],i=[er(n),-tr(n),0],o=0,s=0;Rr.reset();for(var a=0,u=t.length;a=0?1:-1,w=b*k,I=w>Xn,N=p*x;if(Rr.add($n(N*b*er(w),v*E+N*tr(w))),o+=I?k+b*Hn:k,I^f>=n^m>=n){var S=pr(fr(c),fr(y));yr(S);var M=pr(i,S);yr(M);var L=(I^k>=0?-1:1)*ir(M[2]);(r>L||r===L&&(S[0]||S[1]))&&(s+=I^k>=0?1:-1)}}return(o<-jn||o0){for(g||(o.polygonStart(),g=!0),o.lineStart(),t=0;t1&&2&i&&l.push(l.pop().concat(l.shift())),a.push(l.filter(Yr))}return p}}function Yr(t){return t.length>1}function zr(t,e){return((t=t.x)[0]<0?t[1]-Un-jn:Un-t[1])-((e=e.x)[0]<0?e[1]-Un-jn:Un-e[1])}Gn();var jr=Br((function(){return!0}),(function(t){var e,n=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,s){var a=o>0?Xn:-Xn,u=Kn(o-n);Kn(u-Xn)0?Un:-Un),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),e=0):i!==a&&u>=Xn&&(Kn(n-i)jn?Qn((er(e)*(o=tr(r))*er(n)-er(r)*(i=tr(e))*er(t))/(i*o*s)):(e+r)/2}(n,r,o,s),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),e=0),t.point(n=o,r=s),i=a},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var i;if(null==t)i=n*Un,r.point(-Xn,i),r.point(0,i),r.point(Xn,i),r.point(Xn,0),r.point(Xn,-i),r.point(0,-i),r.point(-Xn,-i),r.point(-Xn,0),r.point(-Xn,i);else if(Kn(t[0]-e[0])>jn){var o=t[0]0,i=Kn(n)>jn;function o(t,e){return tr(t)*tr(e)>n}function s(t,e,r){var i=[1,0,0],o=pr(fr(t),fr(e)),s=gr(o,o),a=o[0],u=s-a*a;if(!u)return!r&&t;var l=n*s/u,h=-n*a/u,c=pr(i,o),f=dr(i,l);vr(f,dr(o,h));var g=c,p=gr(f,g),v=gr(g,g),d=p*p-v*(gr(f,f)-1);if(!(d<0)){var y=nr(d),m=dr(g,(-p-y)/v);if(vr(m,f),m=cr(m),!r)return m;var _,x=t[0],E=e[0],k=t[1],b=e[1];E0^m[1]<(Kn(m[0]-x)Xn^(x<=m[0]&&m[0]<=E)){var N=dr(g,(-p+y)/v);return vr(N,f),[m,cr(N)]}}}function a(e,n){var i=r?t:Xn-t,o=0;return e<-i?o|=1:e>i&&(o|=2),n<-i?o|=4:n>i&&(o|=8),o}return Br(o,(function(t){var e,n,u,l,h;return{lineStart:function(){l=u=!1,h=1},point:function(c,f){var g,p=[c,f],v=o(c,f),d=r?v?0:a(c,f):v?a(c+(c<0?Xn:-Xn),f):0;if(!e&&(l=u=v)&&t.lineStart(),v!==u&&(!(g=s(e,p))||Ir(e,g)||Ir(p,g))&&(p[0]+=jn,p[1]+=jn,v=o(p[0],p[1])),v!==u)h=0,v?(t.lineStart(),g=s(p,e),t.point(g[0],g[1])):(g=s(e,p),t.point(g[0],g[1]),t.lineEnd()),e=g;else if(i&&e&&r^v){var y;d&n||!(y=s(p,e,!0))||(h=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1])))}!v||e&&Ir(e,p)||t.point(p[0],p[1]),e=p,u=v,n=d},lineEnd:function(){u&&t.lineEnd(),e=null},clean:function(){return h|(l&&u)<<1}}}),(function(n,r,i,o){!function(t,e,n,r,i,o){if(n){var s=tr(e),a=er(e),u=r*n;null==i?(i=e+r*Hn,o=e-u/2):(i=br(s,i),o=br(s,o),(r>0?io)&&(i+=r*Hn));for(var l,h=i;r>0?h>o:h4*e&&v--){var x=s+f,E=a+g,k=u+p,b=nr(x*x+E*E+k*k),w=ir(k/=b),I=Kn(Kn(k)-1)e||Kn((y*L+m*P)/_-.5)>.3||s*f+a*g+u*p2?t[2]%360*Jn:0,M()):[d*Wn,y*Wn,m*Wn]},I.precision=function(t){return arguments.length?(w=Kr(S,b=t*t),L()):nr(b)},I.fitExtent=function(t,e){return Hr(I,t,e)},I.fitSize=function(t,e){return function(t,e,n){return Hr(t,[[0,0],e],n)}(I,t,e)},function(){return e=t.apply(this,arguments),I.invert=e.invert&&N,M()}}((function(){return t}))()}function ti(t){return function(e,n){var r=tr(e),i=tr(n),o=t(r*i);return[o*i*er(e),o*er(n)]}}function ei(t){return function(e,n){var r=nr(e*e+n*n),i=t(r),o=er(i),s=tr(i);return[$n(e*o,r*s),ir(r&&n*o/r)]}}ti((function(t){return nr(2/(1+t))})).invert=ei((function(t){return 2*ir(t/2)}));var ni=ti((function(t){return(t=rr(t))&&t/er(t)}));function ri(){return $r(ni).scale(79.4188).clipAngle(179.999)}function ii(t,e){return[t,e]}ni.invert=ei((function(t){return t})),ii.invert=ii;var oi=Vn.BufferOp,si=Vn.GeoJSONReader,ai=Vn.GeoJSONWriter;function ui(t,e,n,r){var i=t.properties||{},o="Feature"===t.type?t.geometry:t;if("GeometryCollection"===o.type){var s=[];return mt(t,(function(t){var i=ui(t,e,n,r);i&&s.push(i)})),C(s)}var a=function(t){var e=An(t).geometry.coordinates,n=[-e[0],-e[1]];return ri().rotate(n).scale(x)}(o),u={type:o.type,coordinates:hi(o.coordinates,a)},l=(new si).read(u),h=F(q(e,n),"meters"),c=oi.bufferOp(l,h,r);if(!li((c=(new ai).write(c)).coordinates))return b({type:c.type,coordinates:ci(c.coordinates,a)},i)}function li(t){return Array.isArray(t[0])?li(t[0]):isNaN(t[0])}function hi(t,e){return"object"!==m(t[0])?e(t):t.map((function(t){return hi(t,e)}))}function ci(t,e){return"object"!==m(t[0])?e.invert(t):t.map((function(t){return ci(t,e)}))}function fi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return mt(t,(function(t,o,s){var a=e.weight?null==s?void 0:s[e.weight]:void 0;if(!U(a=null==a?1:a))throw new Error("weight value must be a number for feature index "+o);(a=Number(a))>0&&ct(t,(function(t){n+=t[0]*a,r+=t[1]*a,i+=a}))})),I([n/i,r/i],e.properties,e)}function gi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return ct(t,(function(t){n+=t[0],r+=t[1],i++}),!0),I([n/i,r/i],e.properties)}function pi(t,e,n,r,i){var o=r.tolerance||.001,s=0,a=0,u=0,l=0;if(vt(n,(function(e){var n,r=null==(n=e.properties)?void 0:n.weight,i=null==r?1:r;if(!U(i=Number(i)))throw new Error("weight value must be a number");if(i>0){l+=1;var o=i*ut(e,t);0===o&&(o=1);var h=i/o;s+=e.geometry.coordinates[0]*h,a+=e.geometry.coordinates[1]*h,u+=h}})),l<1)throw new Error("no features to measure");var h=s/u,c=a/u;return 1===l||0===i||Math.abs(h-e[0])0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mi;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function mi(t,e){return te?1:0}var _i,xi,Ei,ki,bi,wi=_n(Object.freeze({__proto__:null,default:yi})),Ii={exports:{}};function Ni(){if(bi)return Ii.exports;bi=1;var t=(xi||(xi=1,_i=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=(r-n)/2,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),_i),e=(ki||(ki=1,Ei=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=r-n,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),Ei);return Ii.exports=function(n,r,i,o){return r.length>0&&Array.isArray(r[0])?e(n,r,i,o):t(n,r,i,o)},Ii.exports.nested=e,Ii.exports.flat=t,Ii.exports}var Si,Mi,Li={exports:{}};Li.exports;function Pi(){return Si||(Si=1,function(t,e){!function(t){var e=134217729,n=33306690738754706e-32;function r(t,e,n,r,i){var o,s,a,u,l=e[0],h=r[0],c=0,f=0;h>l==h>-l?(o=l,l=e[++c]):(o=h,h=r[++f]);var g=0;if(cl==h>-l?(a=o-((s=l+o)-l),l=e[++c]):(a=o-((s=h+o)-h),h=r[++f]),o=s,0!==a&&(i[g++]=a);cl==h>-l?(a=o-((s=o+l)-(u=s-o))+(l-u),l=e[++c]):(a=o-((s=o+h)-(u=s-o))+(h-u),h=r[++f]),o=s,0!==a&&(i[g++]=a);for(;c0!=m>0)return _;var x=Math.abs(y+m);return Math.abs(_)>=o*x?_:-function(t,i,o,g,p,v,d){var y,m,_,x,E,k,b,w,I,N,S,M,L,P,C,T,O,R,A=t-p,D=o-p,F=i-v,q=g-v;E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=q-(I=(k=e*q)-(k-q)))-((P=A*q)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=D-(I=(k=e*D)-(k-D)))-((T=F*D)-b*I-w*I-b*N))),u[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),u[1]=L-(S+E)+(E-T),E=(R=M+S)-M,u[2]=M-(R-E)+(S-E),u[3]=R;var V=function(t,e){for(var n=e[0],r=1;r=G||-V>=G)return V;if(y=t-(A+(E=t-A))+(E-p),_=o-(D+(E=o-D))+(E-p),m=i-(F+(E=i-F))+(E-v),x=g-(q+(E=g-q))+(E-v),0===y&&0===m&&0===_&&0===x)return V;if(G=a*d+n*Math.abs(V),(V+=A*x+q*y-(F*_+D*m))>=G||-V>=G)return V;E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=q-(I=(k=e*q)-(k-q)))-((P=y*q)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=D-(I=(k=e*D)-(k-D)))-((T=m*D)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var B=r(4,u,4,f,l);E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=x-(I=(k=e*x)-(k-x)))-((P=A*x)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=_-(I=(k=e*_)-(k-_)))-((T=F*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var Y=r(B,l,4,f,h);E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=x-(I=(k=e*x)-(k-x)))-((P=y*x)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=_-(I=(k=e*_)-(k-_)))-((T=m*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var z=r(Y,h,4,f,c);return c[z-1]}(t,i,g,p,v,d,x)},t.orient2dfast=function(t,e,n,r,i,o){return(e-o)*(n-i)-(t-i)*(r-o)},Object.defineProperty(t,"__esModule",{value:!0})}(e)}(0,Li.exports)),Li.exports}var Ci=function(){if(Mi)return vi.exports;Mi=1;var t=di,e=wi,n=Ni(),r=Pi().orient2d;function i(e,r,i){r=Math.max(0,void 0===r?2:r),i=i||0;var s=function(t){for(var e=t[0],r=t[0],i=t[0],o=t[0],s=0;si[0]&&(i=a),a[1]o[1]&&(o=a)}var u=[e,r,i,o],l=u.slice();for(s=0;s=2&&h(e[e.length-2],e[e.length-1],t[n])<=0;)e.pop();e.push(t[n])}for(var r=[],i=t.length-1;i>=0;i--){for(;r.length>=2&&h(r[r.length-2],r[r.length-1],t[i])<=0;)r.pop();r.push(t[i])}return r.pop(),e.pop(),e.concat(r)}(l)}(e),a=new t(16);a.toBBox=function(t){return{minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]}},a.compareMinX=function(t,e){return t[0]-e[0]},a.compareMinY=function(t,e){return t[1]-e[1]},a.load(e);for(var u,l=[],p=0;pu||c.push({node:v,dist:d})}for(;c.length&&!c.peek().node.children;){var y=c.pop(),m=y.node,_=p(m,n,r),x=p(m,i,o);if(y.dist<_&&y.dist=e.minX&&t[0]<=e.maxX&&t[1]>=e.minY&&t[1]<=e.maxY}function l(t,e,n){for(var r,i,o,s,a=Math.min(t[0],e[0]),u=Math.min(t[1],e[1]),l=Math.max(t[0],e[0]),c=Math.max(t[1],e[1]),f=n.search({minX:a,minY:u,maxX:l,maxY:c}),g=0;g0!=h(r,i,s)>0&&h(o,s,r)>0!=h(o,s,i)>0)return!1;return!0}function h(t,e,n){return r(t[0],t[1],e[0],e[1],n[0],n[1])}function c(t){var e=t.p,n=t.next.p;return t.minX=Math.min(e[0],n[0]),t.minY=Math.min(e[1],n[1]),t.maxX=Math.max(e[0],n[0]),t.maxY=Math.max(e[1],n[1]),t}function f(t,e){var n={p:t,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return e?(n.next=e.next,n.prev=e,e.next.prev=n,e.next=n):(n.prev=n,n.next=n),n}function g(t,e){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function p(t,e,n){var r=e[0],i=e[1],o=n[0]-r,s=n[1]-i;if(0!==o||0!==s){var a=((t[0]-r)*o+(t[1]-i)*s)/(o*o+s*s);a>1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function v(t,e,n,r,i,o,s,a){var u,l,h,c,f=n-t,g=r-e,p=s-i,v=a-o,d=t-i,y=e-o,m=f*f+g*g,_=f*p+g*v,x=p*p+v*v,E=f*d+g*y,k=p*d+v*y,b=m*x-_*_,w=b,I=b;0===b?(l=0,w=1,c=k,I=x):(c=m*k-_*E,(l=_*k-x*E)<0?(l=0,c=k,I=x):l>w&&(l=w,c=k+_,I=x)),c<0?(c=0,-E<0?l=0:-E>m?l=w:(l=-E,w=m)):c>I&&(c=I,-E+_<0?l=0:-E+_>m?l=w:(l=-E+_,w=m));var N=(1-(h=0===c?0:c/I))*i+h*s-((1-(u=0===l?0:l/w))*t+u*n),S=(1-h)*o+h*a-((1-u)*e+u*r);return N*N+S*S}function d(t,e){return t[0]===e[0]?t[1]-e[1]:t[0]-e[0]}return e.default&&(e=e.default),vi.exports=i,vi.exports.default=i,vi.exports}(),Ti=mn(Ci);function Oi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e.concavity=e.concavity||1/0;var n=[];if(ct(t,(function(t){n.push([t[0],t[1]])})),!n.length)return null;var r=Ti(n,e.concavity);return r.length>3?S([r]):null}function Ri(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.steps||64,i=n.properties?n.properties:!Array.isArray(t)&&"Feature"===t.type&&t.properties?t.properties:{},o=[],s=0;s0;r.length0;){var a=t[Math.floor(Math.random()*o)],u=s?a.join("_"):""+a;n[u]||(n[u]=!0,r.push(a))}if(r.length0,u=t[Math.floor(Math.random()*s)];for(a&&u.join("_"),o.push(u);o.length0,y=[];if(s)u="kmrand"==s?r(t,e):"kmpp"==s?i(t,e):s;else for(var m={};u.lengthc&&(c=t[a].y);var g,p=l-u,v=c-h,d=p>v?p:v,y=.5*(l+u),m=.5*(c+h),_=[new so({__sentinel:!0,x:y-20*d,y:m-d},{__sentinel:!0,x:y,y:m+20*d},{__sentinel:!0,x:y+20*d,y:m-d})],x=[],E=[];a=t.length;for(;a--;){for(E.length=0,g=_.length;g--;)(p=t[a].x-_[g].x)>0&&p*p>_[g].r?(x.push(_[g]),_.splice(g,1)):p*p+(v=t[a].y-_[g].y)*v>_[g].r||(E.push(_[g].a,_[g].b,_[g].b,_[g].c,_[g].c,_[g].a),_.splice(g,1));for(uo(E),g=E.length;g;)n=E[--g],e=E[--g],r=t[a],i=n.x-e.x,o=n.y-e.y,s=2*(i*(r.y-n.y)-o*(r.x-n.x)),Math.abs(s)>f&&_.push(new so(e,n,r))}Array.prototype.push.apply(x,_),a=x.length;for(;a--;)(x[a].a.__sentinel||x[a].b.__sentinel||x[a].c.__sentinel)&&x.splice(a,1);return x}(t.features.map((function(t){var r={x:t.geometry.coordinates[0],y:t.geometry.coordinates[1]};return e?r.z=t.properties[e]:3===t.geometry.coordinates.length&&(n=!0,r.z=t.geometry.coordinates[2]),r}))).map((function(t){var e=[t.a.x,t.a.y],r=[t.b.x,t.b.y],i=[t.c.x,t.c.y],o={};return n?(e.push(t.a.z),r.push(t.b.z),i.push(t.c.z)):o={a:t.a.z,b:t.b.z,c:t.c.z},S([[e,r,i,e]],o)})))}var so=s((function t(e,n,r){i(this,t),this.a=e,this.b=n,this.c=r;var o,s,a=n.x-e.x,u=n.y-e.y,l=r.x-e.x,h=r.y-e.y,c=a*(e.x+n.x)+u*(e.y+n.y),f=l*(e.x+r.x)+h*(e.y+r.y),g=2*(a*(r.y-n.y)-u*(r.x-n.x));this.x=(h*c-u*f)/g,this.y=(a*f-l*c)/g,o=this.x-e.x,s=this.y-e.y,this.r=o*o+s*s}));function ao(t,e){return e.x-t.x}function uo(t){var e,n,r,i,o,s=t.length;t:for(;s;)for(n=t[--s],e=t[--s],r=s;r;)if(o=t[--r],e===(i=t[--r])&&n===o||e===o&&n===i){t.splice(s,2),t.splice(r,2),s-=2;continue t}}function lo(t){return t}function ho(t,e){var n=function(t){if(null==t)return lo;var e,n,r=t.scale[0],i=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,a){a||(e=n=0);var u=2,l=t.length,h=new Array(l);for(h[0]=(e+=t[0])*r+o,h[1]=(n+=t[1])*i+s;u1)for(var o,a,u=1,l=s(i[0]);ul&&(a=i[0],i[0]=i[u],i[u]=a,l=o);return i})).filter((function(t){return t.length>0}))}}var po=Object.prototype.hasOwnProperty;function vo(t,e,n,r,i,o){3===arguments.length&&(r=o=Array,i=null);for(var s=new r(t=1<=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},maybeSet:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},get:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)break;h=s[l=l+1&u]}return o},keys:function(){for(var t=[],e=0,n=s.length;e>7^xo[2]^xo[3])}function ko(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=function(){for(var t=vo(1.4*o.length,E,k,Int32Array,-1,Int32Array),e=new Int32Array(o.length),n=0,r=o.length;n=0){var o=c[n];i===e&&o===r||i===r&&o===e||(++g,f[n]=1)}else h[n]=e,c[n]=r}}function E(t){return Eo(o[t])}function k(t,e){return yo(o[t],o[e])}l=h=c=null;var b,w=function(t,e,n,r,i){3===arguments.length&&(r=Array,i=null);for(var o=new r(t=1<=t)throw new Error("full hashset");u=o[a=a+1&s]}return o[a]=r,!0},has:function(r){for(var a=e(r)&s,u=o[a],l=0;u!=i;){if(n(u,r))return!0;if(++l>=t)break;u=o[a=a+1&s]}return!1},values:function(){for(var t=[],e=0,n=o.length;e>1);er&&(r=o),si&&(i=s)}function u(t){t.forEach(a)}function l(t){t.forEach(u)}for(var h in t)o(t[h]);return r>=e&&i>=n?[e,n,r,i]:void 0}(t=Io(t)),r=function(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=s.length+a.length;for(delete t.lines,delete t.rings,r=0,i=s.length;r1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=[],i=It(t,(function(t,e){var n=function(t,e){var n,r=t.geometry.coordinates,i=e.geometry.coordinates,o=Oo(r[0]),s=Oo(r[r.length-1]),a=Oo(i[0]),u=Oo(i[i.length-1]);if(o===u)n=i.concat(r.slice(1));else if(a===s)n=r.concat(i.slice(1));else if(o===a)n=r.slice(1).reverse().concat(i);else{if(s!==u)return null;n=r.concat(i.reverse().slice(1))}return L(n)}(t,e);return n||(r.push(t),e)}));return i&&r.push(i),r.length?1===r.length?r[0]:T(r.map((function(t){return t.coordinates}))):null}function Oo(t){return t[0].toString()+","+t[1].toString()}function Ro(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=function(t){var e={};xt(t,(function(t){e[t.geometry.type]=!0}));var n=Object.keys(e);if(1===n.length)return n[0];return null}(t);if(!r)throw new Error("geojson must be homogenous");var i=t;switch(r){case"LineString":return To(i,e);case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==e.mutate&&void 0!==e.mutate||(t=Ai(t));var n=[];xt(t,(function(t){n.push(t.geometry)}));var r=Lo({geoms:A(n).geometry});return fo(r,r.objects.geoms.geometries)}(i,e);default:throw new Error(r+" is not supported")}}var Ao=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Do=Math.ceil,Fo=Math.floor,qo="[BigNumber Error] ",Vo=qo+"Number primitive has more than 15 significant digits: ",Go=1e14,Bo=14,Yo=9007199254740991,zo=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Xo=1e9;function Uo(t){var e=0|t;return t>0||t===e?e:e-1}function Zo(t){for(var e,n,r=1,i=t.length,o=t[0]+"";rl^n?1:-1;for(a=(u=i.length)<(l=o.length)?u:l,s=0;so[s]^n?1:-1;return u==l?0:u>l^n?1:-1}function Wo(t,e,n,r){if(tn||t!==Fo(t))throw Error(qo+(r||"Argument")+("number"==typeof t?tn?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Jo(t){var e=t.c.length-1;return Uo(t.e/Bo)==e&&t.c[e]%2!=0}function Ko(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Qo(t,e,n){var r,i;if(e<0){for(i=n+".";++e;i+=n);t=i+t}else if(++e>(r=t.length)){for(i=n,e-=r;--e;i+=n);t+=i}else ex?f.c=f.e=null:t.e<_?f.c=[f.e=0]:(f.e=t.e,f.c=t.c.slice()));if((l="number"==typeof t)&&0*t==0){if(f.s=1/t<0?(t=-t,-1):1,t===~~t){for(a=0,u=t;u>=10;u/=10,a++);return void(a>x?f.c=f.e=null:(f.e=a,f.c=[t]))}c=String(t)}else{if(!Ao.test(c=String(t)))return i(f,c,l);f.s=45==c.charCodeAt(0)?(c=c.slice(1),-1):1}(a=c.indexOf("."))>-1&&(c=c.replace(".","")),(u=c.search(/e/i))>0?(a<0&&(a=u),a+=+c.slice(u+1),c=c.substring(0,u)):a<0&&(a=c.length)}else{if(Wo(e,2,I.length,"Base"),10==e&&N)return C(f=new S(t),p+f.e+1,v);if(c=String(t),l="number"==typeof t){if(0*t!=0)return i(f,c,l,e);if(f.s=1/t<0?(c=c.slice(1),-1):1,S.DEBUG&&c.replace(/^0\.0*|\./,"").length>15)throw Error(Vo+t)}else f.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1;for(n=I.slice(0,e),a=u=0,h=c.length;ua){a=h;continue}}else if(!s&&(c==c.toUpperCase()&&(c=c.toLowerCase())||c==c.toLowerCase()&&(c=c.toUpperCase()))){s=!0,u=-1,a=0;continue}return i(f,String(t),l,e)}l=!1,(a=(c=r(c,e,10,f.s)).indexOf("."))>-1?c=c.replace(".",""):a=c.length}for(u=0;48===c.charCodeAt(u);u++);for(h=c.length;48===c.charCodeAt(--h););if(c=c.slice(u,++h)){if(h-=u,l&&S.DEBUG&&h>15&&(t>Yo||t!==Fo(t)))throw Error(Vo+f.s*t);if((a=a-u-1)>x)f.c=f.e=null;else if(a<_)f.c=[f.e=0];else{if(f.e=a,f.c=[],u=(a+1)%Bo,a<0&&(u+=Bo),u=y)?Ko(u,s):Qo(u,s,"0");else if(o=(t=C(new S(t),e,n)).e,a=(u=Zo(t.c)).length,1==r||2==r&&(e<=o||o<=d)){for(;aa){if(--e>0)for(u+=".";e--;u+="0");}else if((e+=o-a)>0)for(o+1==a&&(u+=".");e--;u+="0");return t.s<0&&i?"-"+u:u}function L(t,e){for(var n,r,i=1,o=new S(t[0]);i=10;i/=10,r++);return(n=r+n*Bo-1)>x?t.c=t.e=null:n<_?t.c=[t.e=0]:(t.e=n,t.c=e),t}function C(t,e,n,r){var i,o,s,a,u,l,h,c=t.c,f=zo;if(c){t:{for(i=1,a=c[0];a>=10;a/=10,i++);if((o=e-i)<0)o+=Bo,s=e,u=c[l=0],h=Fo(u/f[i-s-1]%10);else if((l=Do((o+1)/Bo))>=c.length){if(!r)break t;for(;c.length<=l;c.push(0));u=h=0,i=1,s=(o%=Bo)-Bo+1}else{for(u=a=c[l],i=1;a>=10;a/=10,i++);h=(s=(o%=Bo)-Bo+i)<0?0:Fo(u/f[i-s-1]%10)}if(r=r||e<0||null!=c[l+1]||(s<0?u:u%f[i-s-1]),r=n<4?(h||r)&&(0==n||n==(t.s<0?3:2)):h>5||5==h&&(4==n||r||6==n&&(o>0?s>0?u/f[i-s]:0:c[l-1])%10&1||n==(t.s<0?8:7)),e<1||!c[0])return c.length=0,r?(e-=t.e+1,c[0]=f[(Bo-e%Bo)%Bo],t.e=-e||0):c[0]=t.e=0,t;if(0==o?(c.length=l,a=1,l--):(c.length=l+1,a=f[Bo-o],c[l]=s>0?Fo(u/f[i-s]%f[s])*a:0),r)for(;;){if(0==l){for(o=1,s=c[0];s>=10;s/=10,o++);for(s=c[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(t.e++,c[0]==Go&&(c[0]=1));break}if(c[l]+=a,c[l]!=Go)break;c[l--]=0,a=1}for(o=c.length;0===c[--o];c.pop());}t.e>x?t.c=t.e=null:t.e<_&&(t.c=[t.e=0])}return t}function T(t){var e,n=t.e;return null===n?t.toString():(e=Zo(t.c),e=n<=d||n>=y?Ko(e,n):Qo(e,n,"0"),t.s<0?"-"+e:e)}return S.clone=t,S.ROUND_UP=0,S.ROUND_DOWN=1,S.ROUND_CEIL=2,S.ROUND_FLOOR=3,S.ROUND_HALF_UP=4,S.ROUND_HALF_DOWN=5,S.ROUND_HALF_EVEN=6,S.ROUND_HALF_CEIL=7,S.ROUND_HALF_FLOOR=8,S.EUCLID=9,S.config=S.set=function(t){var e,n;if(null!=t){if("object"!=m(t))throw Error(qo+"Object expected: "+t);if(t.hasOwnProperty(e="DECIMAL_PLACES")&&(Wo(n=t[e],0,Xo,e),p=n),t.hasOwnProperty(e="ROUNDING_MODE")&&(Wo(n=t[e],0,8,e),v=n),t.hasOwnProperty(e="EXPONENTIAL_AT")&&((n=t[e])&&n.pop?(Wo(n[0],-Xo,0,e),Wo(n[1],0,Xo,e),d=n[0],y=n[1]):(Wo(n,-Xo,Xo,e),d=-(y=n<0?-n:n))),t.hasOwnProperty(e="RANGE"))if((n=t[e])&&n.pop)Wo(n[0],-Xo,-1,e),Wo(n[1],1,Xo,e),_=n[0],x=n[1];else{if(Wo(n,-Xo,Xo,e),!n)throw Error(qo+e+" cannot be zero: "+n);_=-(x=n<0?-n:n)}if(t.hasOwnProperty(e="CRYPTO")){if((n=t[e])!==!!n)throw Error(qo+e+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw E=!n,Error(qo+"crypto unavailable");E=n}else E=n}if(t.hasOwnProperty(e="MODULO_MODE")&&(Wo(n=t[e],0,9,e),k=n),t.hasOwnProperty(e="POW_PRECISION")&&(Wo(n=t[e],0,Xo,e),b=n),t.hasOwnProperty(e="FORMAT")){if("object"!=m(n=t[e]))throw Error(qo+e+" not an object: "+n);w=n}if(t.hasOwnProperty(e="ALPHABET")){if("string"!=typeof(n=t[e])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(qo+e+" invalid: "+n);N="0123456789"==n.slice(0,10),I=n}}return{DECIMAL_PLACES:p,ROUNDING_MODE:v,EXPONENTIAL_AT:[d,y],RANGE:[_,x],CRYPTO:E,MODULO_MODE:k,POW_PRECISION:b,FORMAT:w,ALPHABET:I}},S.isBigNumber=function(t){if(!t||!0!==t._isBigNumber)return!1;if(!S.DEBUG)return!0;var e,n,r=t.c,i=t.e,o=t.s;t:if("[object Array]"=={}.toString.call(r)){if((1===o||-1===o)&&i>=-Xo&&i<=Xo&&i===Fo(i)){if(0===r[0]){if(0===i&&1===r.length)return!0;break t}if((e=(i+1)%Bo)<1&&(e+=Bo),String(r[0]).length==e){for(e=0;e=Go||n!==Fo(n))break t;if(0!==n)return!0}}}else if(null===r&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(qo+"Invalid BigNumber: "+t)},S.maximum=S.max=function(){return L(arguments,-1)},S.minimum=S.min=function(){return L(arguments,1)},S.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Fo(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(t){var e,n,r,i,o,a=0,u=[],l=new S(g);if(null==t?t=p:Wo(t,0,Xo),i=Do(t/Bo),E)if(crypto.getRandomValues){for(e=crypto.getRandomValues(new Uint32Array(i*=2));a>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),e[a]=n[0],e[a+1]=n[1]):(u.push(o%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw E=!1,Error(qo+"crypto unavailable");for(e=crypto.randomBytes(i*=7);a=9e15?crypto.randomBytes(7).copy(e,a):(u.push(o%1e14),a+=7);a=i/7}if(!E)for(;a=10;o/=10,a++);an-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(r,i,o,s,a){var u,l,h,c,f,g,d,y,m=r.indexOf("."),_=p,x=v;for(m>=0&&(c=b,b=0,r=r.replace(".",""),g=(y=new S(i)).pow(r.length-m),b=c,y.c=e(Qo(Zo(g.c),g.e,"0"),10,o,t),y.e=y.c.length),h=c=(d=e(r,i,o,a?(u=I,t):(u=t,I))).length;0==d[--c];d.pop());if(!d[0])return u.charAt(0);if(m<0?--h:(g.c=d,g.e=h,g.s=s,d=(g=n(g,y,_,x,o)).c,f=g.r,h=g.e),m=d[l=h+_+1],c=o/2,f=f||l<0||null!=d[l+1],f=x<4?(null!=m||f)&&(0==x||x==(g.s<0?3:2)):m>c||m==c&&(4==x||f||6==x&&1&d[l-1]||x==(g.s<0?8:7)),l<1||!d[0])r=f?Qo(u.charAt(1),-_,u.charAt(0)):u.charAt(0);else{if(d.length=l,f)for(--o;++d[--l]>o;)d[l]=0,l||(++h,d=[1].concat(d));for(c=d.length;!d[--c];);for(m=0,r="";m<=c;r+=u.charAt(d[m++]));r=Qo(r,h,u.charAt(0))}return r}}(),n=function(){function t(t,e,n){var r,i,o,s,a=0,u=t.length,l=e%jo,h=e/jo|0;for(t=t.slice();u--;)a=((i=l*(o=t[u]%jo)+(r=h*o+(s=t[u]/jo|0)*l)%jo*jo+a)/n|0)+(r/jo|0)+h*s,t[u]=i%n;return a&&(t=[a].concat(t)),t}function e(t,e,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;ie[i]?1:-1;break}return o}function n(t,e,n,r){for(var i=0;n--;)t[n]-=i,i=t[n]1;t.splice(0,1));}return function(r,i,o,s,a){var u,l,h,c,f,g,p,v,d,y,m,_,x,E,k,b,w,I=r.s==i.s?1:-1,N=r.c,M=i.c;if(!(N&&N[0]&&M&&M[0]))return new S(r.s&&i.s&&(N?!M||N[0]!=M[0]:M)?N&&0==N[0]||!M?0*I:I/0:NaN);for(d=(v=new S(I)).c=[],I=o+(l=r.e-i.e)+1,a||(a=Go,l=Uo(r.e/Bo)-Uo(i.e/Bo),I=I/Bo|0),h=0;M[h]==(N[h]||0);h++);if(M[h]>(N[h]||0)&&l--,I<0)d.push(1),c=!0;else{for(E=N.length,b=M.length,h=0,I+=2,(f=Fo(a/(M[0]+1)))>1&&(M=t(M,f,a),N=t(N,f,a),b=M.length,E=N.length),x=b,m=(y=N.slice(0,b)).length;m=a/2&&k++;do{if(f=0,(u=e(M,y,b,m))<0){if(_=y[0],b!=m&&(_=_*a+(y[1]||0)),(f=Fo(_/k))>1)for(f>=a&&(f=a-1),p=(g=t(M,f,a)).length,m=y.length;1==e(g,y,p,m);)f--,n(g,b=10;I/=10,h++);C(v,o+(v.e=h+l*Bo-1)+1,s,c)}else v.e=l,v.r=+c;return v}}(),a=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,l=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,c=/^\s*\+(?=[\w.])|^\s+|\s+$/g,i=function(t,e,n,r){var i,o=n?e:e.replace(c,"");if(h.test(o))t.s=isNaN(o)?null:o<0?-1:1;else{if(!n&&(o=o.replace(a,(function(t,e,n){return i="x"==(n=n.toLowerCase())?16:"b"==n?2:8,r&&r!=i?t:e})),r&&(i=r,o=o.replace(u,"$1").replace(l,"0.$1")),e!=o))return new S(o,i);if(S.DEBUG)throw Error(qo+"Not a"+(r?" base "+r:"")+" number: "+e);t.s=null}t.c=t.e=null},f.absoluteValue=f.abs=function(){var t=new S(this);return t.s<0&&(t.s=1),t},f.comparedTo=function(t,e){return Ho(this,new S(t,e))},f.decimalPlaces=f.dp=function(t,e){var n,r,i,o=this;if(null!=t)return Wo(t,0,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t+o.e+1,e);if(!(n=o.c))return null;if(r=((i=n.length-1)-Uo(this.e/Bo))*Bo,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},f.dividedBy=f.div=function(t,e){return n(this,new S(t,e),p,v)},f.dividedToIntegerBy=f.idiv=function(t,e){return n(this,new S(t,e),0,1)},f.exponentiatedBy=f.pow=function(t,e){var n,r,i,o,s,a,u,l,h=this;if((t=new S(t)).c&&!t.isInteger())throw Error(qo+"Exponent not an integer: "+T(t));if(null!=e&&(e=new S(e)),s=t.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!t.c||!t.c[0])return l=new S(Math.pow(+T(h),s?t.s*(2-Jo(t)):+T(t))),e?l.mod(e):l;if(a=t.s<0,e){if(e.c?!e.c[0]:!e.s)return new S(NaN);(r=!a&&h.isInteger()&&e.isInteger())&&(h=h.mod(e))}else{if(t.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return o=h.s<0&&Jo(t)?-0:0,h.e>-1&&(o=1/o),new S(a?1/o:o);b&&(o=Do(b/Bo+2))}for(s?(n=new S(.5),a&&(t.s=1),u=Jo(t)):u=(i=Math.abs(+T(t)))%2,l=new S(g);;){if(u){if(!(l=l.times(h)).c)break;o?l.c.length>o&&(l.c.length=o):r&&(l=l.mod(e))}if(i){if(0===(i=Fo(i/2)))break;u=i%2}else if(C(t=t.times(n),t.e+1,1),t.e>14)u=Jo(t);else{if(0===(i=+T(t)))break;u=i%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):r&&(h=h.mod(e))}return r?l:(a&&(l=g.div(l)),e?l.mod(e):o?C(l,b,v,undefined):l)},f.integerValue=function(t){var e=new S(this);return null==t?t=v:Wo(t,0,8),C(e,e.e+1,t)},f.isEqualTo=f.eq=function(t,e){return 0===Ho(this,new S(t,e))},f.isFinite=function(){return!!this.c},f.isGreaterThan=f.gt=function(t,e){return Ho(this,new S(t,e))>0},f.isGreaterThanOrEqualTo=f.gte=function(t,e){return 1===(e=Ho(this,new S(t,e)))||0===e},f.isInteger=function(){return!!this.c&&Uo(this.e/Bo)>this.c.length-2},f.isLessThan=f.lt=function(t,e){return Ho(this,new S(t,e))<0},f.isLessThanOrEqualTo=f.lte=function(t,e){return-1===(e=Ho(this,new S(t,e)))||0===e},f.isNaN=function(){return!this.s},f.isNegative=function(){return this.s<0},f.isPositive=function(){return this.s>0},f.isZero=function(){return!!this.c&&0==this.c[0]},f.minus=function(t,e){var n,r,i,o,s=this,a=s.s;if(e=(t=new S(t,e)).s,!a||!e)return new S(NaN);if(a!=e)return t.s=-e,s.plus(t);var u=s.e/Bo,l=t.e/Bo,h=s.c,c=t.c;if(!u||!l){if(!h||!c)return h?(t.s=-e,t):new S(c?s:NaN);if(!h[0]||!c[0])return c[0]?(t.s=-e,t):new S(h[0]?s:3==v?-0:0)}if(u=Uo(u),l=Uo(l),h=h.slice(),a=u-l){for((o=a<0)?(a=-a,i=h):(l=u,i=c),i.reverse(),e=a;e--;i.push(0));i.reverse()}else for(r=(o=(a=h.length)<(e=c.length))?a:e,a=e=0;e0)for(;e--;h[n++]=0);for(e=Go-1;r>a;){if(h[--r]=0;){for(n=0,f=_[i]%d,g=_[i]/d|0,o=i+(s=u);o>i;)n=((l=f*(l=m[--s]%d)+(a=g*l+(h=m[s]/d|0)*f)%d*d+p[o]+n)/v|0)+(a/d|0)+g*h,p[o--]=l%v;p[o]=n}return n?++r:p.splice(0,1),P(t,p,r)},f.negated=function(){var t=new S(this);return t.s=-t.s||null,t},f.plus=function(t,e){var n,r=this,i=r.s;if(e=(t=new S(t,e)).s,!i||!e)return new S(NaN);if(i!=e)return t.s=-e,r.minus(t);var o=r.e/Bo,s=t.e/Bo,a=r.c,u=t.c;if(!o||!s){if(!a||!u)return new S(i/0);if(!a[0]||!u[0])return u[0]?t:new S(a[0]?r:0*i)}if(o=Uo(o),s=Uo(s),a=a.slice(),i=o-s){for(i>0?(s=o,n=u):(i=-i,n=a),n.reverse();i--;n.push(0));n.reverse()}for((i=a.length)-(e=u.length)<0&&(n=u,u=a,a=n,e=i),i=0;e;)i=(a[--e]=a[e]+u[e]+i)/Go|0,a[e]=Go===a[e]?0:a[e]%Go;return i&&(a=[i].concat(a),++s),P(t,a,s)},f.precision=f.sd=function(t,e){var n,r,i,o=this;if(null!=t&&t!==!!t)return Wo(t,1,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t,e);if(!(n=o.c))return null;if(r=(i=n.length-1)*Bo+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return t&&o.e+1>r&&(r=o.e+1),r},f.shiftedBy=function(t){return Wo(t,-9007199254740991,Yo),this.times("1e"+t)},f.squareRoot=f.sqrt=function(){var t,e,r,i,o,s=this,a=s.c,u=s.s,l=s.e,h=p+4,c=new S("0.5");if(1!==u||!a||!a[0])return new S(!u||u<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(u=Math.sqrt(+T(s)))||u==1/0?(((e=Zo(a)).length+l)%2==0&&(e+="0"),u=Math.sqrt(+e),l=Uo((l+1)/2)-(l<0||l%2),r=new S(e=u==1/0?"5e"+l:(e=u.toExponential()).slice(0,e.indexOf("e")+1)+l)):r=new S(u+""),r.c[0])for((u=(l=r.e)+h)<3&&(u=0);;)if(o=r,r=c.times(o.plus(n(s,o,h,1))),Zo(o.c).slice(0,u)===(e=Zo(r.c)).slice(0,u)){if(r.e0&&p>0){for(o=p%a||a,h=g.substr(0,o);o0&&(h+=l+g.slice(o)),f&&(h="-"+h)}r=c?h+(n.decimalSeparator||"")+((u=+n.fractionGroupSize)?c.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):c):h}return(n.prefix||"")+r+(n.suffix||"")},f.toFraction=function(t){var e,r,i,o,s,a,u,l,h,c,f,p,d=this,y=d.c;if(null!=t&&(!(u=new S(t)).isInteger()&&(u.c||1!==u.s)||u.lt(g)))throw Error(qo+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+T(u));if(!y)return new S(d);for(e=new S(g),h=r=new S(g),i=l=new S(g),p=Zo(y),s=e.e=p.length-d.e-1,e.c[0]=zo[(a=s%Bo)<0?Bo+a:a],t=!t||u.comparedTo(e)>0?s>0?e:h:u,a=x,x=1/0,u=new S(p),l.c[0]=0;c=n(u,e,0,1),1!=(o=r.plus(c.times(i))).comparedTo(t);)r=i,i=o,h=l.plus(c.times(o=h)),l=o,e=u.minus(c.times(o=e)),u=o;return o=n(t.minus(r),i,0,1),l=l.plus(o.times(h)),r=r.plus(o.times(i)),l.s=h.s=d.s,f=n(h,i,s*=2,v).minus(d).abs().comparedTo(n(l,r,s,v).minus(d).abs())<1?[h,i]:[l,r],x=a,f},f.toNumber=function(){return+T(this)},f.toPrecision=function(t,e){return null!=t&&Wo(t,1,Xo),M(this,t,e,2)},f.toString=function(t){var e,n=this,i=n.s,o=n.e;return null===o?i?(e="Infinity",i<0&&(e="-"+e)):e="NaN":(null==t?e=o<=d||o>=y?Ko(Zo(n.c),o):Qo(Zo(n.c),o,"0"):10===t&&N?e=Qo(Zo((n=C(new S(n),p+o+1,v)).c),n.e,"0"):(Wo(t,2,I.length,"Base"),e=r(Qo(Zo(n.c),o,"0"),10,t,i,!0)),i<0&&n.c[0]&&(e="-"+e)),e},f.valueOf=f.toJSON=function(){return T(this)},f._isBigNumber=!0,f[Symbol.toStringTag]="BigNumber",f[Symbol.for("nodejs.util.inspect.custom")]=f.valueOf,null!=e&&S.set(e),S}(),ts=function(t){function e(t){return i(this,e),r(this,e,[t])}return h(e,t),s(e)}(s((function t(e){i(this,t),u(this,"key",void 0),u(this,"left",null),u(this,"right",null),this.key=e}))),es=function(){return s((function t(){i(this,t),u(this,"size",0),u(this,"modificationCount",0),u(this,"splayCount",0)}),[{key:"splay",value:function(t){var e=this.root;if(null==e)return this.compare(t,t),-1;for(var n,r=null,i=null,o=null,s=null,a=e,u=this.compare;;)if((n=u(a.key,t))>0){var l=a.left;if(null==l)break;if((n=u(l.key,t))>0&&(a.left=l.right,l.right=a,null==(l=(a=l).left)))break;null==r?i=a:r.left=a,r=a,a=l}else{if(!(n<0))break;var h=a.right;if(null==h)break;if((n=u(h.key,t))<0&&(a.right=h.left,h.left=a,null==(h=(a=h).right)))break;null==o?s=a:o.right=a,o=a,a=h}return null!=o&&(o.right=a.left,a.left=s),null!=r&&(r.left=a.right,a.right=i),this.root!==a&&(this.root=a,this.splayCount++),n}},{key:"splayMin",value:function(t){for(var e=t,n=e.left;null!=n;){var r=n;e.left=r.right,r.right=e,n=(e=r).left}return e}},{key:"splayMax",value:function(t){for(var e=t,n=e.right;null!=n;){var r=n;e.right=r.left,r.left=e,n=(e=r).right}return e}},{key:"_delete",value:function(t){if(null==this.root)return null;if(0!=this.splay(t))return null;var e=this.root,n=e,r=e.left;if(this.size--,null==r)this.root=e.right;else{var i=e.right;(e=this.splayMax(r)).right=i,this.root=e}return this.modificationCount++,n}},{key:"addNewRoot",value:function(t,e){this.size++,this.modificationCount++;var n=this.root;null!=n?(e<0?(t.left=n,t.right=n.right,n.right=null):(t.right=n,t.left=n.left,n.left=null),this.root=t):this.root=t}},{key:"_first",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMin(t),this.root)}},{key:"_last",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMax(t),this.root)}},{key:"clear",value:function(){this.root=null,this.size=0,this.modificationCount++}},{key:"has",value:function(t){return this.validKey(t)&&0==this.splay(t)}},{key:"defaultCompare",value:function(){return function(t,e){return te?1:0}}},{key:"wrap",value:function(){var t=this;return{getRoot:function(){return t.root},setRoot:function(e){t.root=e},getSize:function(){return t.size},getModificationCount:function(){return t.modificationCount},getSplayCount:function(){return t.splayCount},setSplayCount:function(e){t.splayCount=e},splay:function(e){return t.splay(e)},has:function(e){return t.has(e)}}}}])}(),ns=function(t){function e(t,n){var o;return i(this,e),u(o=r(this,e),"root",null),u(o,"compare",void 0),u(o,"validKey",void 0),u(o,Symbol.toStringTag,"[object Set]"),o.compare=null!=t?t:o.defaultCompare(),o.validKey=null!=n?n:function(t){return null!=t&&null!=t},o}return h(e,t),s(e,[{key:"delete",value:function(t){return!!this.validKey(t)&&null!=this._delete(t)}},{key:"deleteAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.delete(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"forEach",value:function(t){for(var e,n=this[Symbol.iterator]();!(e=n.next()).done;)t(e.value,e.value,this)}},{key:"add",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this}},{key:"addAndReturn",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this.root.key}},{key:"addAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.add(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"isEmpty",value:function(){return null==this.root}},{key:"isNotEmpty",value:function(){return null!=this.root}},{key:"single",value:function(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}},{key:"first",value:function(){if(0==this.size)throw"Bad state: No element";return this._first().key}},{key:"last",value:function(){if(0==this.size)throw"Bad state: No element";return this._last().key}},{key:"lastBefore",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)<0)return this.root.key;var e=this.root.left;if(null==e)return null;for(var n=e.right;null!=n;)n=(e=n).right;return e.key}},{key:"firstAfter",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)>0)return this.root.key;var e=this.root.right;if(null==e)return null;for(var n=e.left;null!=n;)n=(e=n).left;return e.key}},{key:"retainAll",value:function(t){var n,r=new e(this.compare,this.validKey),i=this.modificationCount,o=a(t);try{for(o.s();!(n=o.n()).done;){var s=n.value;if(i!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(s)&&0==this.splay(s)&&r.add(this.root.key)}}catch(t){o.e(t)}finally{o.f()}r.size!=this.size&&(this.root=r.root,this.size=r.size,this.modificationCount++)}},{key:"lookup",value:function(t){return this.validKey(t)?0!=this.splay(t)?null:this.root.key:null}},{key:"intersection",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)&&r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"difference",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)||r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"union",value:function(t){var e=this.clone();return e.addAll(t),e}},{key:"clone",value:function(){var t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}},{key:"copyNode",value:function(t){if(null==t)return null;var e=new ts(t.key);return function t(e,n){var r,i;do{if(r=e.left,i=e.right,null!=r){var o=new ts(r.key);n.left=o,t(r,o)}if(null!=i){var s=new ts(i.key);n.right=s,e=i,n=s}}while(null!=i)}(t,e),e}},{key:"toSet",value:function(){return this.clone()}},{key:"entries",value:function(){return new os(this.wrap())}},{key:"keys",value:function(){return this[Symbol.iterator]()}},{key:"values",value:function(){return this[Symbol.iterator]()}},{key:Symbol.iterator,value:function(){return new is(this.wrap())}}])}(es),rs=function(){return s((function t(e){i(this,t),u(this,"tree",void 0),u(this,"path",new Array),u(this,"modificationCount",null),u(this,"splayCount",void 0),this.tree=e,this.splayCount=e.getSplayCount()}),[{key:Symbol.iterator,value:function(){return this}},{key:"next",value:function(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}},{key:"current",value:function(){if(!this.path.length)return null;var t=this.path[this.path.length-1];return this.getValue(t)}},{key:"rebuildPath",value:function(t){this.path.splice(0,this.path.length),this.tree.splay(t),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}},{key:"findLeftMostDescendent",value:function(t){for(;null!=t;)this.path.push(t),t=t.left}},{key:"moveNext",value:function(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();for(var t=this.tree.getRoot();null!=t;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);var e=this.path[this.path.length-1],n=e.right;if(null!=n){for(;null!=n;)this.path.push(n),n=n.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}}])}(),is=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return t.key}}])}(rs),os=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return[t.key,t.key]}}])}(rs),ss=function(t){return function(){return t}},as=function(t){var e=t?function(e,n){return n.minus(e).abs().isLessThanOrEqualTo(t)}:ss(!1);return function(t,n){return e(t,n)?0:t.comparedTo(n)}};function us(t){var e=t?function(e,n,r,i,o){return e.exponentiatedBy(2).isLessThanOrEqualTo(i.minus(n).exponentiatedBy(2).plus(o.minus(r).exponentiatedBy(2)).times(t))}:ss(!1);return function(t,n,r){var i=t.x,o=t.y,s=r.x,a=r.y,u=o.minus(a).times(n.x.minus(s)).minus(i.minus(s).times(n.y.minus(a)));return e(u,i,o,s,a)?0:u.comparedTo(0)}}var ls=function(t){return t},hs=function(t){if(t){var e=new ns(as(t)),n=new ns(as(t)),r=function(t,e){return e.addAndReturn(t)},i=function(t){return{x:r(t.x,e),y:r(t.y,n)}};return i({x:new $o(0),y:new $o(0)}),i}return ls},cs=function(t){return{set:function(t){fs=cs(t)},reset:function(){return cs(t)},compare:as(t),snap:hs(t),orient:us(t)}},fs=cs(),gs=function(t,e){return t.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(t.ur.x)&&t.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(t.ur.y)},ps=function(t,e){if(e.ur.x.isLessThan(t.ll.x)||t.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(t.ll.y)||t.ur.y.isLessThan(e.ll.y))return null;var n=t.ll.x.isLessThan(e.ll.x)?e.ll.x:t.ll.x,r=t.ur.x.isLessThan(e.ur.x)?t.ur.x:e.ur.x;return{ll:{x:n,y:t.ll.y.isLessThan(e.ll.y)?e.ll.y:t.ll.y},ur:{x:r,y:t.ur.y.isLessThan(e.ur.y)?t.ur.y:e.ur.y}}},vs=function(t,e){return t.x.times(e.y).minus(t.y.times(e.x))},ds=function(t,e){return t.x.times(e.x).plus(t.y.times(e.y))},ys=function(t){return ds(t,t).sqrt()},ms=function(t,e,n){var r={x:e.x.minus(t.x),y:e.y.minus(t.y)},i={x:n.x.minus(t.x),y:n.y.minus(t.y)};return ds(i,r).div(ys(i)).div(ys(r))},_s=function(t,e,n){return e.y.isZero()?null:{x:t.x.plus(e.x.div(e.y).times(n.minus(t.y))),y:n}},xs=function(t,e,n){return e.x.isZero()?null:{x:n,y:t.y.plus(e.y.div(e.x).times(n.minus(t.x)))}},Es=function(){function t(e,n){i(this,t),u(this,"point",void 0),u(this,"isLeft",void 0),u(this,"segment",void 0),u(this,"otherSE",void 0),u(this,"consumedBy",void 0),void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}return s(t,[{key:"link",value:function(t){if(t.point===this.point)throw new Error("Tried to link already linked events");for(var e=t.point.events,n=0,r=e.length;n0&&(t=r)}for(var i=t.segment.prevInResult(),o=i?i.prevInResult():null;;){if(!i)return null;if(!o)return i.ringOut;var s,a;if(o.ringOut!==i.ringOut)return(null===(s=o.ringOut)||void 0===s?void 0:s.enclosingRing())!==i.ringOut?i.ringOut:null===(a=i.ringOut)||void 0===a?void 0:a.enclosingRing();i=o.prevInResult(),o=i?i.prevInResult():null}}}],[{key:"factory",value:function(e){for(var n=[],r=0,i=e.length;r1&&void 0!==arguments[1]?arguments[1]:Ls.compare;i(this,t),u(this,"queue",void 0),u(this,"tree",void 0),u(this,"segments",void 0),this.queue=e,this.tree=new ns(n),this.segments=[]}),[{key:"process",value:function(t){var e=t.segment,n=[];if(t.consumedBy)return t.isLeft?this.queue.delete(t.otherSE):this.tree.delete(e),n;t.isLeft&&this.tree.add(e);var r=e,i=e;do{r=this.tree.lastBefore(r)}while(null!=r&&null!=r.consumedBy);do{i=this.tree.firstAfter(i)}while(null!=i&&null!=i.consumedBy);if(t.isLeft){var o=null;if(r){var s=r.getIntersection(e);if(null!==s&&(e.isAnEndpoint(s)||(o=s),!r.isAnEndpoint(s)))for(var a=this._splitSafely(r,s),u=0,l=a.length;u0?(this.tree.delete(e),n.push(t)):(this.segments.push(e),e.prev=r)}else{if(r&&i){var _=r.getIntersection(i);if(null!==_){if(!r.isAnEndpoint(_))for(var x=this._splitSafely(r,_),E=0,k=x.length;E0&&a.swapEvents(),Es.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}},{key:"swapEvents",value:function(){var t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(var e=0,n=this.windings.length;e0){var o=n;n=r,r=o}if(n.prev===r){var s=n;n=r,r=s}for(var a=0,u=r.rings.length;a0)return-1;var c=e.comparePoint(t.rightSE.point);return 0!==c?c:-1}if(n.isGreaterThan(r)){if(s.isLessThan(a)&&s.isLessThan(l))return-1;if(s.isGreaterThan(a)&&s.isGreaterThan(l))return 1;var f=e.comparePoint(t.leftSE.point);if(0!==f)return f;var g=t.comparePoint(e.rightSE.point);return g<0?1:g>0?-1:1}if(s.isLessThan(a))return-1;if(s.isGreaterThan(a))return 1;if(i.isLessThan(o)){var p=e.comparePoint(t.rightSE.point);if(0!==p)return p}if(i.isGreaterThan(o)){var v=t.comparePoint(e.rightSE.point);if(v<0)return 1;if(v>0)return-1}if(!i.eq(o)){var d=u.minus(s),y=i.minus(n),m=l.minus(a),_=o.minus(r);if(d.isGreaterThan(y)&&m.isLessThan(_))return 1;if(d.isLessThan(y)&&m.isGreaterThan(_))return-1}return i.isGreaterThan(o)?1:i.isLessThan(o)||u.isLessThan(l)?-1:u.isGreaterThan(l)?1:t.ide.id?1:0}},{key:"fromRing",value:function(e,n,r){var i,o,s,a=Es.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else{if(!(a>0))throw new Error("Tried to create degenerate segment at [".concat(e.x,", ").concat(e.y,"]"));i=n,o=e,s=-1}return new t(new Es(i,!0),new Es(o,!1),[r],[s])}}])}(),Ps=function(){return s((function t(e,n,r){if(i(this,t),u(this,"poly",void 0),u(this,"isExterior",void 0),u(this,"segments",void 0),u(this,"bbox",void 0),!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");var o=fs.snap({x:new $o(e[0][0]),y:new $o(e[0][1])});this.bbox={ll:{x:o.x,y:o.y},ur:{x:o.x,y:o.y}};for(var s=o,a=1,l=e.length;a1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r2&&void 0!==arguments[2]?arguments[2]:2,r=K(t),i=K(e),o=r[0]-i[0],s=r[1]-i[1];return 1===n?Math.abs(o)+Math.abs(s):Math.pow(Math.pow(o,n)+Math.pow(s,n),1/n)}function Gs(t,e){var n,r,i=(e=e||{}).threshold||1e4,o=e.p||2,s=null!=(n=e.binary)&&n,a=e.alpha||-1,u=null!=(r=e.standardization)&&r,l=[];vt(t,(function(t){l.push(gi(t))}));for(var h=[],c=0;c3&&void 0!==arguments[3]?arguments[3]:{},i=e<0,o=j(Math.abs(e),r.units,"meters");i&&(o=-Math.abs(o));var s=K(t),a=function(t,e,n,r){r=void 0===r?x:Number(r);var i=e/r,o=t[0]*Math.PI/180,s=z(t[1]),a=z(n),u=i*Math.cos(a),l=s+u;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);var h=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),c=Math.abs(h)>1e-11?u/h:Math.cos(s),f=i*Math.sin(a)/c;return[(180*(o+f)/Math.PI+540)%360-180,180*l/Math.PI]}(s,o,n);return a[0]+=a[0]-s[0]>180?-360:s[0]-a[0]>180?360:0,I(a,r.properties)}function Ys(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e);i[0]+=i[0]-r[0]>180?-360:r[0]-i[0]>180?360:0;var o=function(t,e,n){var r=n=void 0===n?x:Number(n),i=t[1]*Math.PI/180,o=e[1]*Math.PI/180,s=o-i,a=Math.abs(e[0]-t[0])*Math.PI/180;a>Math.PI&&(a-=2*Math.PI);var u=Math.log(Math.tan(o/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),l=Math.abs(u)>1e-11?s/u:Math.cos(i);return Math.sqrt(s*s+l*l*a*a)*r}(r,i);return j(o,"meters",n.units)}function zs(t,e,n){if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.pivot,i=n.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("angle is required");if(0===e)return t;var o=null!=r?r:gi(t);return!1!==i&&void 0!==i||(t=Ai(t)),ct(t,(function(t){var n=lt(o,t)+e,r=Ys(o,t),i=Q(Bs(o,r,n));t[0]=i[0],t[1]=i[1]})),t}function js(t,e,n,r){var i=(r=r||{}).steps||64,o=r.units||"kilometers",s=r.angle||0,a=r.pivot||t,u=r.properties||{};if(!t)throw new Error("center is required");if(!e)throw new Error("xSemiAxis is required");if(!n)throw new Error("ySemiAxis is required");if(!Z(r))throw new Error("options must be an object");if(!U(i))throw new Error("steps must be a number");if(!U(s))throw new Error("angle must be a number");var l=K(t);if("degrees"!==o){var h=Bs(t,e,90,{units:o}),c=Bs(t,n,0,{units:o});e=K(h)[0]-l[0],n=K(c)[1]-l[1]}for(var f=[],g=0;g=-270&&(v=-v),p<-180&&p>=-360&&(d=-d),"degrees"===o){var y=z(s),m=v*Math.cos(y)+d*Math.sin(y),_=d*Math.cos(y)-v*Math.sin(y);v=m,d=_}f.push([v+l[0],d+l[1]])}return f.push(f[0]),"degrees"===o?S([f],u):zs(S([f],u),s,{pivot:a})}function Xs(t){var e=t*Math.PI/180;return Math.tan(e)}function Us(t){return Vt(Rt(t))}function Zs(t){var e=[];return"FeatureCollection"===t.type?vt(t,(function(t){ct(t,(function(n){e.push(I(n,t.properties))}))})):"Feature"===t.type?ct(t,(function(n){e.push(I(n,t.properties))})):ct(t,(function(t){e.push(I(t))})),C(e)}var Hs=Math.PI/180,Ws=180/Math.PI,Js=function(t,e){this.lon=t,this.lat=e,this.x=Hs*t,this.y=Hs*e};Js.prototype.view=function(){return String(this.lon).slice(0,4)+","+String(this.lat).slice(0,4)},Js.prototype.antipode=function(){var t=-1*this.lat,e=this.lon<0?180+this.lon:-1*(180-this.lon);return new Js(e,t)};var Ks=function(){this.coords=[],this.length=0};Ks.prototype.move_to=function(t){this.length++,this.coords.push(t)};var Qs=function(t){this.properties=t||{},this.geometries=[]};Qs.prototype.json=function(){if(this.geometries.length<=0)return{geometry:{type:"LineString",coordinates:null},type:"Feature",properties:this.properties};if(1===this.geometries.length)return{geometry:{type:"LineString",coordinates:this.geometries[0].coords},type:"Feature",properties:this.properties};for(var t=[],e=0;e1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must specify at least 2 geometries");var r=Rs.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)}function ea(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.stringify(n.properties||{}),i=v(t,4),o=i[0],s=i[1],a=i[2],u=i[3],l=(s+u)/2,h=(o+a)/2,c=2*e/ut([o,l],[a,l],n)*(a-o),f=2*e/ut([h,s],[h,u],n)*(u-s),g=c/2,p=2*g,d=Math.sqrt(3)/2*f,y=a-o,m=u-s,_=3/4*p,x=d,E=(y-p)/(p-g/2),k=Math.floor(E),b=(k*_-g/2-y)/2-g/2+_/2,w=Math.floor((m-d)/d),I=(m-w*d)/2,N=w*d-m>d/2;N&&(I-=d/4);for(var S=[],M=[],L=0;L<6;L++){var P=2*Math.PI/6*L;S.push(Math.cos(P)),M.push(Math.sin(P))}for(var T=[],O=0;O<=k;O++)for(var R=0;R<=w;R++){var A=O%2==1;if((0!==R||!A)&&(0!==R||!N)){var D=O*_+o-b,F=R*x+s+I;if(A&&(F-=d/2),!0===n.triangles)ra([D,F],c/2,f/2,JSON.parse(r),S,M).forEach((function(t){n.mask?ta(C([n.mask,t]))&&T.push(t):T.push(t)}));else{var q=na([D,F],c/2,f/2,JSON.parse(r),S,M);n.mask?ta(C([n.mask,q]))&&T.push(q):T.push(q)}}}return C(T)}function na(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=t[0]+e*i[a],l=t[1]+n*o[a];s.push([u,l])}return s.push(s[0].slice()),S([s],r)}function ra(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=[];u.push(t),u.push([t[0]+e*i[a],t[1]+n*o[a]]),u.push([t[0]+e*i[(a+1)%6],t[1]+n*o[(a+1)%6]]),u.push(t),s.push(S([u],r))}return s}function ia(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.mask&&!n.units&&(n.units="kilometers");for(var r=[],i=t[0],o=t[1],s=t[2],a=t[3],u=e/ut([i,o],[s,o],n)*(s-i),l=e/ut([i,o],[i,a],n)*(a-o),h=s-i,c=a-o,f=Math.floor(h/u),g=(c-Math.floor(c/l)*l)/2,p=i+(h-f*u)/2;p<=s;){for(var v=o+g;v<=a;){var d=I([p,v],n.properties);n.mask?Cn(d,n.mask)&&r.push(d):r.push(d),v+=l}p+=u}return C(r)}function oa(t,e,n){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=[],o=t[0],s=t[1],a=t[2],u=t[3],l=a-o,h=j(e,r.units,"degrees"),c=u-s,f=j(n,r.units,"degrees"),g=Math.floor(Math.abs(l)/h),p=Math.floor(Math.abs(c)/f),v=(c-p*f)/2,d=o+(l-g*h)/2,y=0;y2&&void 0!==arguments[2]?arguments[2]:{})}function aa(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=[],i=e/ut([t[0],t[1]],[t[2],t[1]],n)*(t[2]-t[0]),o=e/ut([t[0],t[1]],[t[0],t[3]],n)*(t[3]-t[1]),s=0,a=t[0];a<=t[2];){for(var u=0,l=t[1];l<=t[3];){var h=null,c=null;s%2==0&&u%2==0?(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)):s%2==0&&u%2==1?(h=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties)):u%2==0&&s%2==1?(h=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties),c=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties)):u%2==1&&s%2==1&&(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)),n.mask?(ta(C([n.mask,h]))&&r.push(h),ta(C([n.mask,c]))&&r.push(c)):(r.push(h),r.push(c)),l+=o,u++}s++,a+=i}return C(r)} +/*! + * MarchingSquaresJS + * version 1.3.3 + * https://github.com/RaumZeit/MarchingSquares.js + * + * @license GNU Affero General Public License. + * Copyright (c) 2015-2019 Ronny Lorenz + */ +function ua(t,e,n){return tr&&(i=n,n=r,r=i),tr?(t-r)/(t-e):(t-n)/(t-e)}function ha(t,e,n,r){return t1){for(;0!==o;)o>>=1,a++;r===1<1){for(;0!==s;)s>>=1,u++;i===1<0&&(this.childB=new da(t,e+o,n,r-o,s),this.lowerBound=Math.min(this.lowerBound,this.childB.lowerBound),this.upperBound=Math.max(this.upperBound,this.childB.upperBound),i-s>0&&(this.childC=new da(t,e+o,n+s,r-o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childC.lowerBound),this.upperBound=Math.max(this.upperBound,this.childC.upperBound))),i-s>0&&(this.childD=new da(t,e,n+s,o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childD.lowerBound),this.upperBound=Math.max(this.upperBound,this.childD.upperBound))}}function ya(t){var e,n;if(!t)throw new Error("data is required");if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Error("data must be scalar field, i.e. array of arrays");if(t.length<2)throw new Error("data must contain at least two rows");if((n=t[0].length)<2)throw new Error("data must contain at least two columns");for(e=1;e=e||t[s][r-1]>=e){n=!1;break}if(n&&(t[i-1][0]>=e||t[i-1][r-1]>=e)&&(n=!1),n)for(o=0;o=e||t[i-1][o]>e){n=!1;break}return n}(t,n.threshold)&&(n.linearRing?_.push([[0,0],[0,x],[E,x],[E,0],[0,0]]):_.push([[0,0],[0,x],[E,x],[E,0]])),e.forEach((function(t,N){t.forEach((function(t,S){for(r=null,i=0;i<4;i++)if(r=k[i],"object"===m(t.edges[r])){for(a=[],o=t.edges[r],u=r,l=N,h=S,c=!1,f=[N+o.path[0][0],S+o.path[0][1]],a.push(f);!c&&"object"===m((s=e[l][h]).edges[u]);)if(o=s.edges[u],delete s.edges[u],(g=o.path[1])[0]+=l,g[1]+=h,a.push(g),u=o.move.enter,l+=o.move.x,h+=o.move.y,void 0===e[l]||void 0===e[l][h]){if(!n.linearRing)break;if(p=0,v=0,l===E?(l--,p=0):l<0?(l++,p=2):h===x?(h--,p=3):h<0&&(h++,p=1),l===N&&h===S&&p===I[r]){c=!0,u=r;break}for(;;){if(d=!1,v>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[l]&&void 0!==e[l][h]&&(s=e[l][h],y=k[p],"object"===m(s.edges[y]))){o=s.edges[y],a.push(pa(l,h,p,o.path)),u=y,d=!0;break}if(d)break;if(a.push(va(l,h,p)),h+=w[p],void 0!==e[l+=b[p]]&&void 0!==e[l][h]||(0===p&&h<0||1===p&&l<0||2===p&&h===x||3===p&&l===E)&&(l-=b[p],h-=w[p],p=(p+1)%4,v++),l===N&&h===S&&p===I[r]){c=!0,u=r;break}}}!n.linearRing||a[a.length-1][0]===f[0]&&a[a.length-1][1]===f[1]||a.push(f),_.push(a)}}))})),_}(h,c,r)}a?g.push(f):g=f,"function"==typeof r.successCallback&&r.successCallback(g,t)})),g}function _a(t,e,n,r){var i,o,s,a,u,l,h=0,c=t[n+1][e],f=t[n+1][e+1],g=t[n][e+1],p=t[n][e],v=r.threshold;if(!(isNaN(p)||isNaN(g)||isNaN(f)||isNaN(c))){switch(h|=c>=v?8:0,h|=f>=v?4:0,h|=g>=v?2:0,l={cval:h=+(h|=p>=v?1:0),polygons:[],edges:{},x0:p,x1:g,x2:f,x3:c},h){case 0:r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,0]]);break;case 15:break;case 14:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.left={path:[[0,i],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[a,0]]);break;case 13:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[a,0],[1,o],[1,0]]);break;case 11:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[1,o],[s,1],[1,1]]);break;case 7:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[s,1],[0,i],[0,1]]);break;case 1:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[a,0],[0,i],[0,1],[1,1],[1,0]]);break;case 2:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,o],[a,0]]);break;case 4:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[1,o],[1,0]]);break;case 8:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[s,1],[1,1],[1,0]]);break;case 12:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[1,o],[1,0]]);break;case 9:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[a,0],[s,1],[1,1],[1,0]]);break;case 3:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[0,i],[0,1],[1,1],[1,o]]);break;case 6:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[a,0]]);break;case 10:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),u=(p+g+f+c)/4,r.polygons_full&&(uf&&(v>h&&ph&&vu&&(u=d)}var y=[];if(a&&u0&&Math.abs(x-n[_-1][0])>f){var E=parseFloat(n[_-1][0]),k=parseFloat(n[_-1][1]),b=parseFloat(n[_][0]),w=parseFloat(n[_][1]);if(E>-180&&E-180&&n[_-1][0]h&&E<180&&-180===b&&_+1h&&n[_-1][0]<180){m.push([180,n[_][1]]),_++,m.push([n[_][0],n[_][1]]);continue}if(Eh){var I=E;E=b,b=I;var N=k;k=w,w=N}if(E>h&&b=180&&Eh?180:-180,M]),(m=[]).push([n[_-1][0]>h?-180:180,M]),y.push(m)}else m=[],y.push(m);m.push([x,n[_][1]])}else m.push([n[_][0],n[_][1]])}}else{var L=[];y.push(L);for(var P=0;Pe||this.upperBound=e)&&r.push({x:this.x,y:this.y})),r},da.prototype.cellsBelowThreshold=function(t,e){var n=[];return e=void 0===e||e,this.lowerBound>t||(this.childA||this.childB||this.childC||this.childD?(this.childA&&(n=n.concat(this.childA.cellsBelowThreshold(t,e))),this.childB&&(n=n.concat(this.childB.cellsBelowThreshold(t,e))),this.childD&&(n=n.concat(this.childD.cellsBelowThreshold(t,e))),this.childC&&(n=n.concat(this.childC.cellsBelowThreshold(t,e)))):(e||this.upperBound>=t)&&n.push({x:this.x,y:this.y})),n};var xa={square:function(t,e,n,r,i,o){o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,0]])},triangle_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,a],[s,0],[0,0]])},triangle_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[1,a],[1,0]])},triangle_tr:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[1,s],[a,1],[1,1]])},triangle_tl:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[s,1]])},tetragon_t:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[1,1],[1,s]])},tetragon_r:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[a,1],[1,1],[1,0]])},tetragon_b:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,0]])},tetragon_l:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[a,0]])},tetragon_bl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[a,0]])},tetragon_br:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate_b(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[1,l]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[1,l],[1,u],[a,0]])},tetragon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rb={path:[[1,l],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}}),o.polygons&&t.polygons.push([[1,l],[s,1],[a,1],[1,u]])},tetragon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[0,l]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[a,1],[0,l],[0,u],[s,1]])},tetragon_lr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[1,u],[1,l]])},tetragon_tb:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[l,0],[s,1],[a,1],[u,0]])},pentagon_tr:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[1,a],[1,0]])},pentagon_tl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,0]])},pentagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,a],[s,0]])},pentagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[a,0],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[1,1],[1,0],[a,0]])},pentagon_tr_rl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[1,u],[1,l]])},pentagon_rb_bt:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,n,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[u,0],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[l,1],[1,1],[1,s],[a,0],[u,0]])},pentagon_bl_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[1,l],[1,0]])},pentagon_lt_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[l,0]])},pentagon_bl_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[l,0],[0,s]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[u,0],[l,0]])},pentagon_lt_rl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[u,1],[1,1],[1,l]])},pentagon_tr_bt:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,1],[a,1],[1,u],[1,0],[l,0]])},pentagon_rb_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_b(n,r,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,u],[l,0]])},hexagon_lt_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[1,l],[1,0]])},hexagon_bl_lt:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[1,1],[1,0]])},hexagon_bl_rb:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.rt={path:[[1,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[1,1],[1,l],[a,0]])},hexagon_tr_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[a,1],[1,u],[1,l],[s,0]])},hexagon_lt_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,u],[l,0]])},hexagon_bl_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,1],[u,1],[1,l],[1,0]])},heptagon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[1,1],[1,c],[a,0]])},heptagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate_a(i,r,o.minV,o.maxV),l=o.interpolate_b(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,a],[u,1],[l,1],[1,h],[1,c],[s,0]])},heptagon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[l,1],[1,h],[1,c],[a,0]])},heptagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(i,r,o.minV,o.maxV),h=o.interpolate_b(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[h,1],[1,c]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[h,1],[1,c],[1,0]])},octagon:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate_a(i,r,o.minV,o.maxV),c=o.interpolate_b(i,r,o.minV,o.maxV),f=o.interpolate_b(n,r,o.minV,o.maxV),g=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[c,1],[1,f]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,g],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[c,1],[1,f],[1,g],[a,0]])}};function Ea(t,e,n,r){var i,o,s,a=!1,u=null,l=null,h=null,c=null,f=!1,g=[],p=[],v=[];if(!t)throw new Error("data is required");if(null==e)throw new Error("lowerBound is required");if(null==n)throw new Error("bandWidth is required");if(s=function(t){var e,n,r,i,o;for(i=new fa,t=t||{},o=Object.keys(i),e=0;en||t[a][i-1]n){r=!1;break}if(r&&(t[o-1][0]n||t[o-1][i-1]n)&&(r=!1),r)for(s=0;sn||t[o-1][s]n){r=!1;break}return r}(t,n.minV,n.maxV)&&(n.linearRing?x.push([[0,0],[0,E],[k,E],[k,0],[0,0]]):x.push([[0,0],[0,E],[k,E],[k,0]])),e.forEach((function(t,M){t.forEach((function(t,L){for(r=null,o=0;o<8;o++)if(r=N[o],"object"===m(t.edges[r])){for(i=[],s=t.edges[r],l=r,h=M,c=L,f=!1,g=[M+s.path[0][0],L+s.path[0][1]],i.push(g);!f&&"object"===m((p=e[h][c]).edges[l]);)if(s=p.edges[l],delete p.edges[l],(y=s.path[1])[0]+=h,y[1]+=c,i.push(y),l=s.move.enter,h+=s.move.x,c+=s.move.y,void 0===e[h]||void 0===e[h][c]){if(v=0,d=0,h===k)h--,v=0;else if(h<0)h++,v=2;else if(c===E)c--,v=3;else{if(!(c<0))throw new Error("Left the grid somewhere in the interior!");c++,v=1}if(h===M&&c===L&&v===S[r]){f=!0,l=r;break}for(;;){if(_=!1,d>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[h]&&void 0!==e[h][c])for(p=e[h][c],a=0;ao?2:sf?128:64,s|=uf?32:16,s|=lf?8:4,o=0,i={cval:s=+(s|=hf?2:1),polygons:[],edges:{},x0:h,x1:l,x2:u,x3:a,x:e,y:n},s){case 85:xa.square(i,h,l,u,a,r);case 0:case 170:break;case 169:xa.triangle_bl(i,h,l,u,a,r);break;case 166:xa.triangle_br(i,h,l,u,a,r);break;case 154:xa.triangle_tr(i,h,l,u,a,r);break;case 106:xa.triangle_tl(i,h,l,u,a,r);break;case 1:xa.triangle_bl(i,h,l,u,a,r);break;case 4:xa.triangle_br(i,h,l,u,a,r);break;case 16:xa.triangle_tr(i,h,l,u,a,r);break;case 64:xa.triangle_tl(i,h,l,u,a,r);break;case 168:xa.tetragon_bl(i,h,l,u,a,r);break;case 162:xa.tetragon_br(i,h,l,u,a,r);break;case 138:xa.tetragon_tr(i,h,l,u,a,r);break;case 42:xa.tetragon_tl(i,h,l,u,a,r);break;case 2:xa.tetragon_bl(i,h,l,u,a,r);break;case 8:xa.tetragon_br(i,h,l,u,a,r);break;case 32:xa.tetragon_tr(i,h,l,u,a,r);break;case 128:xa.tetragon_tl(i,h,l,u,a,r);break;case 5:xa.tetragon_b(i,h,l,u,a,r);break;case 20:xa.tetragon_r(i,h,l,u,a,r);break;case 80:xa.tetragon_t(i,h,l,u,a,r);break;case 65:xa.tetragon_l(i,h,l,u,a,r);break;case 165:xa.tetragon_b(i,h,l,u,a,r);break;case 150:xa.tetragon_r(i,h,l,u,a,r);break;case 90:xa.tetragon_t(i,h,l,u,a,r);break;case 105:xa.tetragon_l(i,h,l,u,a,r);break;case 160:xa.tetragon_lr(i,h,l,u,a,r);break;case 130:xa.tetragon_tb(i,h,l,u,a,r);break;case 10:xa.tetragon_lr(i,h,l,u,a,r);break;case 40:xa.tetragon_tb(i,h,l,u,a,r);break;case 101:xa.pentagon_tr(i,h,l,u,a,r);break;case 149:xa.pentagon_tl(i,h,l,u,a,r);break;case 86:xa.pentagon_bl(i,h,l,u,a,r);break;case 89:xa.pentagon_br(i,h,l,u,a,r);break;case 69:xa.pentagon_tr(i,h,l,u,a,r);break;case 21:xa.pentagon_tl(i,h,l,u,a,r);break;case 84:xa.pentagon_bl(i,h,l,u,a,r);break;case 81:xa.pentagon_br(i,h,l,u,a,r);break;case 96:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 24:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 6:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 129:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 74:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 146:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 164:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 41:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 66:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 144:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 36:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 9:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 104:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 26:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 134:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 161:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 37:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 148:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 82:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 73:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 133:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 22:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 88:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 97:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 145:case 25:xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 70:case 100:xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 17:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 68:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 153:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 102:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 152:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 137:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 98:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 38:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 18:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 33:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 72:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 132:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 136:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r));break;case 34:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r))}return i}}var wa=Object.defineProperty,Ia=Object.getOwnPropertySymbols,Na=Object.prototype.hasOwnProperty,Sa=Object.prototype.propertyIsEnumerable,Ma=function(t,e,n){return e in t?wa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},La=function(t,e){for(var n in e||(e={}))Na.call(e,n)&&Ma(t,n,e[n]);if(Ia){var r,i=a(Ia(e));try{for(i.s();!(r=i.n()).done;){n=r.value;Sa.call(e,n)&&Ma(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t};function Pa(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.zProperty||"elevation",r=e.flip,i=e.flags;nt(t,"Point","input must contain Points");for(var o=function(t,e){var n={};vt(t,(function(t){var e=Q(t)[1];n[e]||(n[e]=[]),n[e].push(t)}));var r=Object.keys(n).map((function(t){return n[t].sort((function(t,e){return Q(t)[0]-Q(e)[0]}))})),i=r.sort((function(t,n){return e?Q(t[0])[1]-Q(n[0])[1]:Q(n[0])[1]-Q(t[0])[1]}));return i}(t,r),s=[],a=0;a=0&&l<=1&&(f.onLine1=!0),h>=0&&h<=1&&(f.onLine2=!0),!(!f.onLine1||!f.onLine2)&&[f.x,f.y])}function za(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return bt(t,(function(t,n){var r=n.geometry.coordinates;return t+ut(r[0],r[1],e)}),0)}function ja(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=i.steps||64,s=Xa(n),a=Xa(r),u=Array.isArray(t)||"Feature"!==t.type?{}:t.properties;if(s===a)return L(Ri(t,e,i).geometry.coordinates[0],u);for(var l=s,h=s=h&&c===i.length-1);c++){if(h>e&&0===o.length){if(!(s=e-h))return o.push(i[c]),L(o);a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates)}if(h>=n)return(s=n-h)?(a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates),L(o)):(o.push(i[c]),L(o));if(h>=e&&o.push(i[c]),c===i.length-1)return L(o);h+=ut(i[c],i[c+1],r)}if(h0){var a=r[e-1],u=Wa(n,a);!1!==u&&(a[1]=u,n[0]=u),s.push(a[0]),e===o.length-2&&(s.push(n[0]),s.push(n[1]))}2===o.length&&(s.push(n[0]),s.push(n[1]))}var l,h,c,f,g,p,v,d})),L(s,t.properties)}function Ka(t){var e=t[0],n=t[1],r=t[2],i=t[3];if(ut(t.slice(0,2),[r,n])>=ut(t.slice(0,2),[e,i])){var o=(n+i)/2;return[e,o-(r-e)/2,r,o+(r-e)/2]}var s=(e+r)/2;return[s-(i-n)/2,n,s+(i-n)/2,i]}function Qa(t,e){if(!Z(e=null!=e?e:{}))throw new Error("options is invalid");var n=e.precision,r=e.coordinates,i=e.mutate;if(n=null==n||isNaN(n)?6:n,r=null==r||isNaN(r)?3:r,!t)throw new Error(" is required");if("number"!=typeof n)throw new Error(" must be a number");if("number"!=typeof r)throw new Error(" must be a number");!1!==i&&void 0!==i||(t=JSON.parse(JSON.stringify(t)));var o=Math.pow(10,n);return ct(t,(function(t){!function(t,e,n){t.length>n&&t.splice(n,t.length);for(var r=0;r1&&n.push(L(l)),C(n)}function eu(t,e){if(!e.features.length)throw new Error("lines must contain features");if(1===e.features.length)return e.features[0];var n,r=1/0;return vt(e,(function(e){var i=fn(e,t).properties.dist;iu?(a.unshift(t),u=e):a.push(t)}else a.push(t)})),S(a,e);default:throw new Error("geometry type "+s+" is not supported")}}function iu(t){var e=t[0],n=e[0],r=e[1],i=t[t.length-1],o=i[0],s=i[1];return n===o&&r===s||t.push(e),t}function ou(t){return R(t)}function su(t){var e=[[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]];return t&&(e="Feature"===t.type?t.geometry.coordinates:t.coordinates),S(e)}function au(t){var e,n=0,r=a(t);try{for(r.s();!(e=r.n()).done;){n+=e.value}}catch(t){r.e(t)}finally{r.f()}return n/t.length}var uu=Object.defineProperty,lu=Object.defineProperties,hu=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,fu=Object.prototype.hasOwnProperty,gu=Object.prototype.propertyIsEnumerable,pu=function(t,e,n){return e in t?uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},vu=function(t,e){for(var n in e||(e={}))fu.call(e,n)&&pu(t,n,e[n]);if(cu){var r,i=a(cu(e));try{for(i.s();!(r=i.n()).done;){n=r.value;gu.call(e,n)&&pu(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},du=function(t,e){return lu(t,hu(e))};function yu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("targetPoint is required");if(!e)throw new Error("points is required");var r=1/0,i=0;vt(e,(function(e,o){var s=ut(t,e,n);s2&&void 0!==arguments[2]?arguments[2]:{},o=null!=(n=i.method)?n:"geodesic",s=null!=(r=i.units)?r:"kilometers";if(!t)throw new Error("pt is required");if(Array.isArray(t)?t=I(t):"Point"===t.type?t=b(t):et(t,"Point","point"),!e)throw new Error("line is required");Array.isArray(e)?e=L(e):"LineString"===e.type?e=b(e):et(e,"LineString","line");var a=1/0,u=t.geometry.coordinates;return kt(e,(function(t){if(t){var e=t.geometry.coordinates[0],n=t.geometry.coordinates[1],r=function(t,e,n,r){if("geodesic"===r.method){return fn(L([e,n]).geometry,t,{units:"degrees"}).properties.dist}var i=[n[0]-e[0],n[1]-e[1]],o=[t[0]-e[0],t[1]-e[1]],s=_u(o,i);if(s<=0)return Ys(t,e,{units:"degrees"});var a=_u(i,i);if(a<=s)return Ys(t,n,{units:"degrees"});var u=s/a,l=[e[0]+u*i[0],e[1]+u*i[1]];return Ys(t,l,{units:"degrees"})}(u,e,n,{method:o});r0)-(t<0)||+t}(r*(n[1]-e[1])-o*i)}function Lu(t,e){return e.geometry.coordinates[0].every((function(e){return zt(I(e),t)}))}var Pu=function(){return s((function t(e){i(this,t),this.id=t.buildId(e),this.coordinates=e,this.innerEdges=[],this.outerEdges=[],this.outerEdgesSorted=!1}),[{key:"removeInnerEdge",value:function(t){this.innerEdges=this.innerEdges.filter((function(e){return e.from.id!==t.from.id}))}},{key:"removeOuterEdge",value:function(t){this.outerEdges=this.outerEdges.filter((function(e){return e.to.id!==t.to.id}))}},{key:"addOuterEdge",value:function(t){this.outerEdges.push(t),this.outerEdgesSorted=!1}},{key:"sortOuterEdges",value:function(){var t=this;this.outerEdgesSorted||(this.outerEdges.sort((function(e,n){var r=e.to,i=n.to;if(r.coordinates[0]-t.coordinates[0]>=0&&i.coordinates[0]-t.coordinates[0]<0)return 1;if(r.coordinates[0]-t.coordinates[0]<0&&i.coordinates[0]-t.coordinates[0]>=0)return-1;if(r.coordinates[0]-t.coordinates[0]==0&&i.coordinates[0]-t.coordinates[0]==0)return r.coordinates[1]-t.coordinates[1]>=0||i.coordinates[1]-t.coordinates[1]>=0?r.coordinates[1]-i.coordinates[1]:i.coordinates[1]-r.coordinates[1];var o=Mu(t.coordinates,r.coordinates,i.coordinates);return o<0?1:o>0?-1:Math.pow(r.coordinates[0]-t.coordinates[0],2)+Math.pow(r.coordinates[1]-t.coordinates[1],2)-(Math.pow(i.coordinates[0]-t.coordinates[0],2)+Math.pow(i.coordinates[1]-t.coordinates[1],2))})),this.outerEdgesSorted=!0)}},{key:"getOuterEdges",value:function(){return this.sortOuterEdges(),this.outerEdges}},{key:"getOuterEdge",value:function(t){return this.sortOuterEdges(),this.outerEdges[t]}},{key:"addInnerEdge",value:function(t){this.innerEdges.push(t)}}],[{key:"buildId",value:function(t){return t.join(",")}}])}(),Cu=function(){function t(e,n){i(this,t),this.from=e,this.to=n,this.next=void 0,this.label=void 0,this.symetric=void 0,this.ring=void 0,this.from.addOuterEdge(this),this.to.addInnerEdge(this)}return s(t,[{key:"getSymetric",value:function(){return this.symetric||(this.symetric=new t(this.to,this.from),this.symetric.symetric=this),this.symetric}},{key:"deleteEdge",value:function(){this.from.removeOuterEdge(this),this.to.removeInnerEdge(this)}},{key:"isEqual",value:function(t){return this.from.id===t.from.id&&this.to.id===t.to.id}},{key:"toString",value:function(){return"Edge { ".concat(this.from.id," -> ").concat(this.to.id," }")}},{key:"toLineString",value:function(){return L([this.from.coordinates,this.to.coordinates])}},{key:"compareTo",value:function(t){return Mu(t.from.coordinates,t.to.coordinates,this.to.coordinates)}}])}(),Tu=function(){return s((function t(){i(this,t),this.edges=[],this.polygon=void 0,this.envelope=void 0}),[{key:"push",value:function(t){this.edges.push(t),this.polygon=this.envelope=void 0}},{key:"get",value:function(t){return this.edges[t]}},{key:"length",get:function(){return this.edges.length}},{key:"forEach",value:function(t){this.edges.forEach(t)}},{key:"map",value:function(t){return this.edges.map(t)}},{key:"some",value:function(t){return this.edges.some(t)}},{key:"isValid",value:function(){return!0}},{key:"isHole",value:function(){var t=this,e=this.edges.reduce((function(e,n,r){return n.from.coordinates[1]>t.edges[e].from.coordinates[1]&&(e=r),e}),0),n=(0===e?this.length:e)-1,r=(e+1)%this.length,i=Mu(this.edges[n].from.coordinates,this.edges[e].from.coordinates,this.edges[r].from.coordinates);return 0===i?this.edges[n].from.coordinates[0]>this.edges[r].from.coordinates[0]:i>0}},{key:"toMultiPoint",value:function(){return O(this.edges.map((function(t){return t.from.coordinates})))}},{key:"toPolygon",value:function(){if(this.polygon)return this.polygon;var t=this.edges.map((function(t){return t.from.coordinates}));return t.push(this.edges[0].from.coordinates),this.polygon=S([t])}},{key:"getEnvelope",value:function(){return this.envelope?this.envelope:this.envelope=Us(this.toPolygon())}},{key:"inside",value:function(t){return zt(t,this.toPolygon())}}],[{key:"findEdgeRingContaining",value:function(t,e){var n,r,i=t.getEnvelope();return e.forEach((function(e){var o,s,u,l,h,c,f=e.getEnvelope();if((r&&(n=r.getEnvelope()),s=i,u=(o=f).geometry.coordinates[0].map((function(t){return t[0]})),l=o.geometry.coordinates[0].map((function(t){return t[1]})),h=s.geometry.coordinates[0].map((function(t){return t[0]})),c=s.geometry.coordinates[0].map((function(t){return t[1]})),Math.max.apply(null,u)!==Math.max.apply(null,h)||Math.max.apply(null,l)!==Math.max.apply(null,c)||Math.min.apply(null,u)!==Math.min.apply(null,h)||Math.min.apply(null,l)!==Math.min.apply(null,c))&&Lu(f,i)){var g,p,v=a(t.map((function(t){return t.from.coordinates})));try{var d=function(){var t=p.value;e.some((function(e){return n=t,r=e.from.coordinates,n[0]===r[0]&&n[1]===r[1];var n,r}))||(g=t)};for(v.s();!(p=v.n()).done;)d()}catch(t){v.e(t)}finally{v.f()}g&&e.inside(I(g))&&(r&&!Lu(n,f)||(r=e))}})),r}}])}();var Ou=function(){function t(){i(this,t),this.edges=[],this.nodes={}}return s(t,[{key:"getNode",value:function(t){var e=Pu.buildId(t),n=this.nodes[e];return n||(n=this.nodes[e]=new Pu(t)),n}},{key:"addEdge",value:function(t,e){var n=new Cu(t,e),r=n.getSymetric();this.edges.push(n),this.edges.push(r)}},{key:"deleteDangles",value:function(){var t=this;Object.keys(this.nodes).map((function(e){return t.nodes[e]})).forEach((function(e){return t._removeIfDangle(e)}))}},{key:"_removeIfDangle",value:function(t){var e=this;if(t.innerEdges.length<=1){var n=t.getOuterEdges().map((function(t){return t.to}));this.removeNode(t),n.forEach((function(t){return e._removeIfDangle(t)}))}}},{key:"deleteCutEdges",value:function(){var t=this;this._computeNextCWEdges(),this._findLabeledEdgeRings(),this.edges.forEach((function(e){e.label===e.symetric.label&&(t.removeEdge(e.symetric),t.removeEdge(e))}))}},{key:"_computeNextCWEdges",value:function(t){var e=this;void 0===t?Object.keys(this.nodes).forEach((function(t){return e._computeNextCWEdges(e.nodes[t])})):t.getOuterEdges().forEach((function(e,n){t.getOuterEdge((0===n?t.getOuterEdges().length:n)-1).symetric.next=e}))}},{key:"_computeNextCCWEdges",value:function(t,e){for(var n,r,i=t.getOuterEdges(),o=i.length-1;o>=0;--o){var s=i[o],a=s.symetric,u=void 0,l=void 0;s.label===e&&(u=s),a.label===e&&(l=a),u&&l&&(l&&(r=l),u&&(r&&(r.next=u,r=void 0),n||(n=u)))}r&&(r.next=n)}},{key:"_findLabeledEdgeRings",value:function(){var t=[],e=0;return this.edges.forEach((function(n){if(!(n.label>=0)){t.push(n);var r=n;do{r.label=e,r=r.next}while(!n.isEqual(r));e++}})),t}},{key:"getEdgeRings",value:function(){var t=this;this._computeNextCWEdges(),this.edges.forEach((function(t){t.label=void 0})),this._findLabeledEdgeRings().forEach((function(e){t._findIntersectionNodes(e).forEach((function(n){t._computeNextCCWEdges(n,e.label)}))}));var e=[];return this.edges.forEach((function(n){n.ring||e.push(t._findEdgeRing(n))})),e}},{key:"_findIntersectionNodes",value:function(t){var e=[],n=t,r=function(){var r=0;n.from.getOuterEdges().forEach((function(e){e.label===t.label&&++r})),r>1&&e.push(n.from),n=n.next};do{r()}while(!t.isEqual(n));return e}},{key:"_findEdgeRing",value:function(t){var e=t,n=new Tu;do{n.push(e),e.ring=n,e=e.next}while(!t.isEqual(e));return n}},{key:"removeNode",value:function(t){var e=this;t.getOuterEdges().forEach((function(t){return e.removeEdge(t)})),t.innerEdges.forEach((function(t){return e.removeEdge(t)})),delete this.nodes[t.id]}},{key:"removeEdge",value:function(t){this.edges=this.edges.filter((function(e){return!e.isEqual(t)})),t.deleteEdge()}}],[{key:"fromGeoJson",value:function(e){!function(t){if(!t)throw new Error("No geojson passed");if("FeatureCollection"!==t.type&&"GeometryCollection"!==t.type&&"MultiLineString"!==t.type&&"LineString"!==t.type&&"Feature"!==t.type)throw new Error("Invalid input type '".concat(t.type,"'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature"))}(e);var n=new t;return xt(e,(function(t){et(t,"LineString","Graph::fromGeoJson"),ft(t,(function(t,e){if(t){var r=n.getNode(t),i=n.getNode(e);n.addEdge(r,i)}return e}))})),n}}])}();function Ru(t,e){var n,r;ct(t,(function(t,i,o,s,a){if(r!==a)e.push([]);else{var u=n[0],l=n[1],h=t[0],c=t[1];e[a].push([.75*u+.25*h,.75*l+.25*c]),e[a].push([.25*u+.75*h,.25*l+.75*c])}n=t,r=a}),!1),e.forEach((function(t){t.push(t[0])}))}function Au(t,e){var n,r,i;ct(t,(function(t,o,s,a,u){if(r!==a)e.push([[]]);else if(i!==u)e[a].push([]);else{var l=n[0],h=n[1],c=t[0],f=t[1];e[a][u].push([.75*l+.25*c,.75*h+.25*f]),e[a][u].push([.25*l+.75*c,.25*h+.75*f])}n=t,r=a,i=u}),!1),e.forEach((function(t){t.forEach((function(t){t.push(t[0])}))}))}function Du(t,e,n,r,i){for(var o=0;o0?qu(e,s,r)<0||(r=s):n>0&&u<=0&&(Fu(e,s,i)||(i=s)),n=u}return[r,i]}function Fu(t,e,n){return qu(t,e,n)>0}function qu(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(n[0]-t[0])*(e[1]-t[1])}function Vu(t){return Bu(t,"mercator",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Gu(t){return Bu(t,"wgs84",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Bu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=(n=n||{}).mutate;if(!t)throw new Error("geojson is required");return Array.isArray(t)&&U(t[0])?t="mercator"===e?Yu(t):zu(t):(!0!==r&&(t=Ai(t)),ct(t,(function(t){var n="mercator"===e?Yu(t):zu(t);t[0]=n[0],t[1]=n[1]}))),t}function Yu(t){var e=Math.PI/180,n=6378137,r=20037508.342789244,i=Math.abs(t[0])<=180?t[0]:t[0]-360*function(t){return t<0?-1:t>0?1:0}(t[0]),o=[n*i*e,n*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return o[0]>r&&(o[0]=r),o[0]<-r&&(o[0]=-r),o[1]>r&&(o[1]=r),o[1]<-r&&(o[1]=-r),o}function zu(t){var e=180/Math.PI,n=6378137;return[t[0]*e/n,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/n)))*e]}var ju=Object.freeze({__proto__:null,toMercator:Vu,toWgs84:Gu});var Xu={20:1.07275,15:1.13795,10:1.22385,5:1.3581,2:1.51743,1:1.62762};function Uu(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}function Zu(t){var e=[];return function t(n){return 0===n||1===n?1:e[n]>0?e[n]:e[n]=t(n-1)*n}(t)}function Hu(t){return Ju(t),Wu(t)}function Wu(t){return Array.isArray(t)?el(t):t&&t.bbox?el(t.bbox):[360*tl(),180*tl()]}function Ju(t){null!=t&&(Array.isArray(t)?H(t):null!=t.bbox&&H(t.bbox))}function Ku(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1);for(var n=[],r=0;r1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1),void 0!==e.bbox&&null!==e.bbox||(e.bbox=[-180,-90,180,90]),U(e.num_vertices)&&void 0!==e.num_vertices||(e.num_vertices=10),U(e.max_radial_length)&&void 0!==e.max_radial_length||(e.max_radial_length=10);var n=Math.abs(e.bbox[0]-e.bbox[2]),r=Math.abs(e.bbox[1]-e.bbox[3]),i=Math.min(n/2,r/2);if(e.max_radial_length>i)throw new Error("max_radial_length is greater than the radius of the bbox");for(var o=[e.bbox[0]+e.max_radial_length,e.bbox[1]+e.max_radial_length,e.bbox[2]-e.max_radial_length,e.bbox[3]-e.max_radial_length],s=[],a=function(){var t,n=[],r=d(Array(e.num_vertices+1)).map(Math.random);r.forEach((function(t,e,n){n[e]=e>0?t+n[e-1]:t})),r.forEach((function(t){t=2*t*Math.PI/r[r.length-1];var i=Math.random();n.push([i*(e.max_radial_length||10)*Math.sin(t),i*(e.max_radial_length||10)*Math.cos(t)])})),n[n.length-1]=n[0],n=n.reverse().map((t=Wu(o),function(e){return[e[0]+t[0],e[1]+t[1]]})),s.push(S([n]))},u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox;Ju(n);var r=e.num_vertices,i=e.max_length,o=e.max_rotation;null==t&&(t=1),(!U(r)||void 0===r||r<2)&&(r=10),U(i)&&void 0!==i||(i=1e-4),U(o)&&void 0!==o||(o=Math.PI/8);for(var s=[],a=0;a0;){var l=a.pop();if(l===n)return ll(l);l.closed=!0;for(var h=t.neighbors(l),c=0,f=h.length;c1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function dl(t,e,n,r,i){for(var o,s=r,a=e+1;as&&(o=a,s=u)}s>r&&(o-e>1&&dl(t,e,o,r,i),i.push(t[o]),n-o>1&&dl(t,o,n,r,i))}function yl(t,e){var n=t.length-1,r=[t[0]];return dl(t,0,n,e,r),r.push(t[n]),r}function ml(t,e,n){if(t.length<=2)return t;var r=void 0!==e?e*e:1;return t=n?t:function(t,e){for(var n,r,i,o,s,a=t[0],u=[a],l=1,h=t.length;le&&(u.push(n),a=n);return a!==n&&u.push(n),u}(t,r),t=yl(t,r)}function _l(t,e,n){return t.map((function(t){if(t.length<4)throw new Error("invalid polygon");for(var r=e,i=ml(t,r,n);!xl(i);)i=ml(t,r-=.01*r,n);return i[i.length-1][0]===i[0][0]&&i[i.length-1][1]===i[0][1]||i.push(i[0]),i}))}function xl(t){return!(t.length<3)&&!(3===t.length&&t[2][0]===t[0][0]&&t[2][1]===t[0][1])}function El(t,e){return{x:t[0]-e[0],y:t[1]-e[1]}}cl.prototype.init=function(){this.dirtyNodes=[];for(var t=0;t0&&(this.content[0]=e,this.bubbleUp(0)),t},remove:function(t){var e=this.content.indexOf(t),n=this.content.pop();e!==this.content.length-1&&(this.content[e]=n,this.scoreFunction(n)0;){var n=(t+1>>1)-1,r=this.content[n];if(!(this.scoreFunction(e)80*i){o=a=t[0],s=h=t[1];for(var _=i;_a&&(a=c),g>h&&(h=g);p=0!==(p=Math.max(a-o,h-s))?32767/p:0}return r(y,m,i,o,s,p,0),m}function e(t,e,n,r,i){var o,s;if(i===I(t,e,n,r)>0)for(o=e;o=e;o-=r)s=k(o,t[o],t[o+1],s);return s&&d(s,s.next)&&(b(s),s=s.next),s}function n(t,e){if(!t)return t;e||(e=t);var n,r=t;do{if(n=!1,r.steiner||!d(r,r.next)&&0!==v(r.prev,r,r.next))r=r.next;else{if(b(r),(r=e=r.prev)===r.next)break;n=!0}}while(n||r!==e);return e}function r(t,e,u,l,h,f,g){if(t){!g&&f&&function(t,e,n,r){var i=t;do{0===i.z&&(i.z=c(i.x,i.y,e,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,n,r,i,o,s,a,u,l=1;do{for(n=t,t=null,o=null,s=0;n;){for(s++,r=n,a=0,e=0;e0||u>0&&r;)0!==a&&(0===u||!r||n.z<=r.z)?(i=n,n=n.nextZ,a--):(i=r,r=r.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;n=r}o.nextZ=null,l*=2}while(s>1)}(i)}(t,l,h,f);for(var p,v,d=t;t.prev!==t.next;)if(p=t.prev,v=t.next,f?o(t,l,h,f):i(t))e.push(p.i/u|0),e.push(t.i/u|0),e.push(v.i/u|0),b(t),t=v.next,d=v.next;else if((t=v)===d){g?1===g?r(t=s(n(t),e,u),e,u,l,h,f,2):2===g&&a(t,e,u,l,h,f):r(n(t),e,u,l,h,f,1);break}}}function i(t){var e=t.prev,n=t,r=t.next;if(v(e,n,r)>=0)return!1;for(var i=e.x,o=n.x,s=r.x,a=e.y,u=n.y,l=r.y,h=io?i>s?i:s:o>s?o:s,p=a>u?a>l?a:l:u>l?u:l,d=r.next;d!==e;){if(d.x>=h&&d.x<=f&&d.y>=c&&d.y<=p&&g(i,a,o,u,s,l,d.x,d.y)&&v(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function o(t,e,n,r){var i=t.prev,o=t,s=t.next;if(v(i,o,s)>=0)return!1;for(var a=i.x,u=o.x,l=s.x,h=i.y,f=o.y,p=s.y,d=au?a>l?a:l:u>l?u:l,_=h>f?h>p?h:p:f>p?f:p,x=c(d,y,e,n,r),E=c(m,_,e,n,r),k=t.prevZ,b=t.nextZ;k&&k.z>=x&&b&&b.z<=E;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;if(k=k.prevZ,b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;k&&k.z>=x;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;k=k.prevZ}for(;b&&b.z<=E;){if(b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function s(t,e,r){var i=t;do{var o=i.prev,s=i.next.next;!d(o,s)&&y(o,i,i.next,s)&&x(o,s)&&x(s,o)&&(e.push(o.i/r|0),e.push(i.i/r|0),e.push(s.i/r|0),b(i),b(i.next),i=t=s),i=i.next}while(i!==t);return n(i)}function a(t,e,i,o,s,a){var u=t;do{for(var l=u.next.next;l!==u.prev;){if(u.i!==l.i&&p(u,l)){var h=E(u,l);return u=n(u,u.next),h=n(h,h.next),r(u,e,i,o,s,a,0),void r(h,e,i,o,s,a,0)}l=l.next}u=u.next}while(u!==t)}function u(t,e){return t.x-e.x}function l(t,e){var r=function(t,e){var n,r=e,i=t.x,o=t.y,s=-1/0;do{if(o<=r.y&&o>=r.next.y&&r.next.y!==r.y){var a=r.x+(o-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=i&&a>s&&(s=a,n=r.x=r.x&&r.x>=c&&i!==r.x&&g(on.x||r.x===n.x&&h(n,r)))&&(n=r,p=u)),r=r.next}while(r!==l);return n}(t,e);if(!r)return e;var i=E(r,t);return n(i,i.next),n(r,r.next)}function h(t,e){return v(t.prev,t,e.prev)<0&&v(e.next,t,t.next)<0}function c(t,e,n,r,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function f(t){var e=t,n=t;do{(e.x=(t-s)*(o-a)&&(t-s)*(r-a)>=(n-s)*(e-a)&&(n-s)*(o-a)>=(i-s)*(r-a)}function p(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&y(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(x(t,e)&&x(e,t)&&function(t,e){var n=t,r=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{n.y>o!=n.next.y>o&&n.next.y!==n.y&&i<(n.next.x-n.x)*(o-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==t);return r}(t,e)&&(v(t.prev,t,e.prev)||v(t,e.prev,e))||d(t,e)&&v(t.prev,t,t.next)>0&&v(e.prev,e,e.next)>0)}function v(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function d(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,n,r){var i=_(v(t,e,n)),o=_(v(t,e,r)),s=_(v(n,r,t)),a=_(v(n,r,e));return i!==o&&s!==a||(!(0!==i||!m(t,n,e))||(!(0!==o||!m(t,r,e))||(!(0!==s||!m(n,t,r))||!(0!==a||!m(n,e,r)))))}function m(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function _(t){return t>0?1:t<0?-1:0}function x(t,e){return v(t.prev,t,t.next)<0?v(t,e,t.next)>=0&&v(t,t.prev,e)>=0:v(t,e,t.prev)<0||v(t,t.next,e)<0}function E(t,e){var n=new w(t.i,t.x,t.y),r=new w(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,n.next=i,i.prev=n,r.next=n,n.prev=r,o.next=r,r.prev=o,r}function k(t,e,n,r){var i=new w(t,e,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function b(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 w(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function I(t,e,n,r){for(var i=0,o=e,s=n-r;o0&&(r+=t[i-1].length,n.holes.push(r))}return n},bl.exports}(),Il=mn(wl);function Nl(t){var e=function(t){for(var e=t[0][0].length,n={vertices:[],holes:[],dimensions:e},r=0,i=0;i0&&(r+=t[i-1].length,n.holes.push(r))}return n}(t),n=Il(e.vertices,e.holes,2),r=[],i=[];n.forEach((function(t,r){var o=n[r];i.push([e.vertices[2*o],e.vertices[2*o+1]])}));for(var o=0;o=1||u<=0||l>=1||l<=0))){var v=p,d=!o[v];d&&(o[v]=!0),e?i.push(e(p,t,n,h,c,u,s,a,f,g,l,d)):i.push(p)}}function v(t,e){var n,i,o,s,a=r[t][e],u=r[t][e+1];return a[0]f[e.isect].coord?-1:1}));for(l=[];x.length>0;){var I=x.pop(),N=I.isect,M=I.parent,L=I.winding,P=l.length,T=[f[N].coord],O=N;if(f[N].ringAndEdge1Walkable)var R=f[N].ringAndEdge1,A=f[N].nxtIsectAlongRingAndEdge1;else R=f[N].ringAndEdge2,A=f[N].nxtIsectAlongRingAndEdge2;for(;!Rl(f[N].coord,f[A].coord);){T.push(f[A].coord);var D=void 0;for(r=0;r1)for(e=0;e=0==e}function Ol(t){for(var e=0,n=0;n0)){if(o/=f,f<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=r-u,f||!(o<0)){if(o/=f,f<0){if(o>c)return;o>h&&(h=o)}else if(f>0){if(o0)){if(o/=g,g<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=i-l,g||!(o<0)){if(o/=g,g<0){if(o>c)return;o>h&&(h=o)}else if(g>0){if(o0||c<1)||(h>0&&(t[0]=[u+h*f,l+h*g]),c<1&&(t[1]=[u+c*f,l+c*g]),!0)}}}}}function Hl(t,e,n,r,i){var o=t[1];if(o)return!0;var s,a,u=t[0],l=t.left,h=t.right,c=l[0],f=l[1],g=h[0],p=h[1],v=(c+g)/2,d=(f+p)/2;if(p===f){if(v=r)return;if(c>g){if(u){if(u[1]>=i)return}else u=[v,n];o=[v,i]}else{if(u){if(u[1]1)if(c>g){if(u){if(u[1]>=i)return}else u=[(n-a)/s,n];o=[(i-a)/s,i]}else{if(u){if(u[1]=r)return}else u=[e,s*e+a];o=[r,s*r+a]}else{if(u){if(u[0]=-dh)){var g=u*u+l*l,p=h*h+c*c,v=(c*g-l*p)/f,d=(u*p-h*g)/f,y=$l.pop()||new th;y.arc=t,y.site=i,y.x=v+s,y.y=(y.cy=d+a)+Math.sqrt(v*v+d*d),t.circle=y;for(var m=null,_=gh._;_;)if(y.y<_.y||y.y===_.y&&y.x<=_.x){if(!_.L){m=_.P;break}_=_.L}else{if(!_.R){m=_;break}_=_.R}gh.insert(m,y),m||(Ql=y)}}}}function nh(t){var e=t.circle;e&&(e.P||(Ql=e.N),gh.remove(e),$l.push(e),Gl(e),t.circle=null)}var rh=[];function ih(){Gl(this),this.edge=this.site=this.circle=null}function oh(t){var e=rh.pop()||new ih;return e.site=t,e}function sh(t){nh(t),ch.remove(t),rh.push(t),Gl(t)}function ah(t){var e=t.circle,n=e.x,r=e.cy,i=[n,r],o=t.P,s=t.N,a=[t];sh(t);for(var u=o;u.circle&&Math.abs(n-u.circle.x)vh)a=a.L;else{if(!((i=o-hh(a,s))>vh)){r>-vh?(e=a.P,n=a):i>-vh?(e=a,n=a.N):e=n=a;break}if(!a.R){e=a;break}a=a.R}!function(t){fh[t.index]={site:t,halfedges:[]}}(t);var u=oh(t);if(ch.insert(e,u),e||n){if(e===n)return nh(e),n=oh(e.site),ch.insert(u,n),u.edge=n.edge=jl(e.site,u.site),eh(e),void eh(n);if(n){nh(e),nh(n);var l=e.site,h=l[0],c=l[1],f=t[0]-h,g=t[1]-c,p=n.site,v=p[0]-h,d=p[1]-c,y=2*(f*d-g*v),m=f*f+g*g,_=v*v+d*d,x=[(d*m-g*_)/y+h,(f*_-v*m)/y+c];Ul(n.edge,l,p,x),u.edge=jl(l,t,null,x),n.edge=jl(t,p,null,x),eh(e),eh(n)}else u.edge=jl(e.site,u.site)}}function lh(t,e){var n=t.site,r=n[0],i=n[1],o=i-e;if(!o)return r;var s=t.P;if(!s)return-1/0;var a=(n=s.site)[0],u=n[1],l=u-e;if(!l)return a;var h=a-r,c=1/o-1/l,f=h/l;return c?(-f+Math.sqrt(f*f-2*c*(h*h/(-2*l)-u+l/2+i-o/2)))/c+r:(r+a)/2}function hh(t,e){var n=t.N;if(n)return lh(n,e);var r=t.site;return r[1]===e?r[0]:1/0}var ch,fh,gh,ph,vh=1e-6,dh=1e-12;function yh(t,e){return e[1]-t[1]||e[0]-t[0]}function mh(t,e){var n,r,i,o=t.sort(yh).pop();for(ph=[],fh=new Array(t.length),ch=new Vl,gh=new Vl;;)if(i=Ql,o&&(!i||o[1]vh||Math.abs(i[0][1]-i[1][1])>vh)||delete ph[o]}(s,a,u,l),function(t,e,n,r){var i,o,s,a,u,l,h,c,f,g,p,v,d=fh.length,y=!0;for(i=0;ivh||Math.abs(v-f)>vh)&&(u.splice(a,0,ph.push(Xl(s,g,Math.abs(p-t)vh?[t,Math.abs(c-t)vh?[Math.abs(f-r)vh?[n,Math.abs(c-n)vh?[Math.abs(f-e)=a)return null;var u=t-i.site[0],l=e-i.site[1],h=u*u+l*l;do{i=o.cells[r=s],s=null,i.halfedges.forEach((function(n){var r=o.edges[n],a=r.left;if(a!==i.site&&a||(a=r.right)){var u=t-a[0],l=e-a[1],c=u*u+l*l;c2&&void 0!==arguments[2]?arguments[2]:{},r=rt(t).coordinates,i=0,o=0;o=i&&o===r.length-1);o++){if(i>=e){var s=e-i;if(s){var a=st(r[o],r[o-1])-180;return at(r[o],s,a,n)}return I(r[o])}i+=ut(r[o],r[o+1],n)}return I(r[r.length-1])},t.angle=function(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!Z(r))throw new Error("options is invalid");if(!t)throw new Error("startPoint is required");if(!e)throw new Error("midPoint is required");if(!n)throw new Error("endPoint is required");var i=t,o=e,s=n,a=G(!0!==r.mercator?st(o,i):lt(o,i)),u=G(!0!==r.mercator?st(o,s):lt(o,s));u1&&void 0!==arguments[1]?arguments[1]:{},n=e.resolution||1e4,r=e.sharpness||.85,i=[],o=rt(t).coordinates.map((function(t){return{x:t[0],y:t[1]}})),s=new Gt({duration:n,points:o,sharpness:r}),a=function(t){var e=s.pos(t);Math.floor(t/100)%2==0&&i.push([e.x,e.y])},u=0;u0;else if(n!==u>0)return!0}return!1},t.booleanContains=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type,s=n.coordinates,u=r.coordinates;switch(i){case"Point":if("Point"===o)return Ht(s,u);throw new Error("feature2 "+o+" geometry not supported");case"MultiPoint":switch(o){case"Point":return function(t,e){var n,r=!1;for(n=0;n2&&void 0!==arguments[2]?arguments[2]:{}).precision;if("number"!=typeof(n=null==n||isNaN(n)?6:n)||!(n>=0))throw new Error("precision must be a positive number");return rt(t).type===rt(e).type&&Ne(Le(t),Le(e),{precision:n})},t.booleanIntersects=Oe,t.booleanOverlap=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;if("MultiPoint"===i&&"MultiPoint"!==o||("LineString"===i||"MultiLineString"===i)&&"LineString"!==o&&"MultiLineString"!==o||("Polygon"===i||"MultiPolygon"===i)&&"Polygon"!==o&&"MultiPolygon"!==o)throw new Error("features must be of the same type");if("Point"===i)throw new Error("Point geometry not supported");if(Ne(t,e,{precision:6}))return!1;var s=0;switch(i){case"MultiPoint":for(var a=0;a0},t.booleanParallel=function(t,e){if(!t)throw new Error("line1 is required");if(!e)throw new Error("line2 is required");if("LineString"!==In(t,"line1"))throw new Error("line1 must be a LineString");if("LineString"!==In(e,"line2"))throw new Error("line2 must be a LineString");for(var n=$e(Le(t)).features,r=$e(Le(e)).features,i=0;i1;case"MultiPoint":for(var i=0;i0&&ue(S([r[0]]),S([r[i]])).features.length>1)return!1}return!0;case"MultiPolygon":for(i=0;i0&&ue(S([o[0]]),S([o[s]])).features.length>1)return!1}return!0;default:return!1}},t.booleanWithin=Cn,t.buffer=function(t,e,n){var r=(n=n||{}).units||"kilometers",i=n.steps||8;if(!t)throw new Error("geojson is required");if("object"!==m(n))throw new Error("options must be an object");if("number"!=typeof i)throw new Error("steps must be an number");if(void 0===e)throw new Error("radius is required");if(i<=0)throw new Error("steps must be greater than 0");var o=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){var n=ui(t,e,r,i);n&&o.push(n)})),C(o);case"FeatureCollection":return vt(t,(function(t){var n=ui(t,e,r,i);n&&vt(n,(function(t){t&&o.push(t)}))})),C(o)}return ui(t,e,r,i)},t.center=An,t.centerMean=fi,t.centerMedian=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.counter||10;if(!U(n))throw new Error("counter must be a number");var r=e.weight,i=fi(t,{weight:e.weight}),o=C([]);vt(t,(function(t){var e;o.features.push(gi(t,{properties:{weight:null==(e=t.properties)?void 0:e[r]}}))}));var s={tolerance:e.tolerance,medianCandidates:[]};return pi(i.geometry.coordinates,[0,0],o,s,n)},t.centerOfMass=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(it(e)){case"Point":return I(K(e),n.properties);case"Polygon":var r=[];ct(e,(function(t){r.push(t)}));var i,o,s,a,u,l,h,c,f=gi(e,{properties:n.properties}),g=f.geometry.coordinates,p=0,v=0,d=0,y=r.map((function(t){return[t[0]-g[0],t[1]-g[1]]}));for(i=0;i2&&void 0!==arguments[2]?arguments[2]:{};!0!==n.mutate&&(t=Ai(t));var r=n.minPoints||3,i=V(e,n.units),o=new to(t.features.length),s=t.features.map((function(t){return!1})),a=t.features.map((function(t){return!1})),u=t.features.map((function(t){return!1})),l=t.features.map((function(t){return-1}));o.load(t.features.map((function(t,e){var n=v(t.geometry.coordinates,2),r=n[0],i=n[1];return{minX:r,minY:i,maxX:r,maxY:i,index:e}})));var h=function(n){var r=t.features[n],s=v(r.geometry.coordinates,2),a=s[0],u=s[1],l=Math.max(u-i,-90),h=Math.min(u+i,90),c=l<0&&h>0?i:Math.abs(l)=r){var i=c;c++,s[e]=!0,function(t,e){for(var n=0;n=r&&e.push.apply(e,d(o))}a[i]||(a[i]=!0,l[i]=t)}}(i,n)}else u[e]=!0}})),t.features.forEach((function(e,n){var r=t.features[n];r.properties||(r.properties={}),l[n]>=0?(r.properties.dbscan=u[n]?"edge":"core",r.properties.cluster=l[n]):r.properties.dbscan="noise"})),t},t.clustersKmeans=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.features.length;e.numberOfClusters=e.numberOfClusters||Math.round(Math.sqrt(n/2)),e.numberOfClusters>n&&(e.numberOfClusters=n),!0!==e.mutate&&(t=Ai(t));var r=yt(t),i=r.slice(0,e.numberOfClusters),o=ro(r,e.numberOfClusters,i),s={};return o.centroids.forEach((function(t,e){s[e]=t})),vt(t,(function(t,e){var n=o.idxs[e];t.properties.cluster=n,t.properties.centroid=s[n]})),t},t.collect=function(t,e,n,r){var i=new io(6),o=e.features.map((function(t){var e;return{minX:t.geometry.coordinates[0],minY:t.geometry.coordinates[1],maxX:t.geometry.coordinates[0],maxY:t.geometry.coordinates[1],property:null==(e=t.properties)?void 0:e[n]}}));return i.load(o),t.features.forEach((function(t){t.properties||(t.properties={});var e=Rt(t),n=i.search({minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}),o=[];n.forEach((function(e){zt([e.minX,e.minY],t)&&o.push(e.property)})),t.properties[r]=o})),t},t.collectionOf=nt,t.combine=function(t){var e={MultiPoint:{coordinates:[],properties:[]},MultiLineString:{coordinates:[],properties:[]},MultiPolygon:{coordinates:[],properties:[]}};return vt(t,(function(t){var n,r,i,o;switch(null==(o=t.geometry)?void 0:o.type){case"Point":e.MultiPoint.coordinates.push(t.geometry.coordinates),e.MultiPoint.properties.push(t.properties);break;case"MultiPoint":(n=e.MultiPoint.coordinates).push.apply(n,d(t.geometry.coordinates)),e.MultiPoint.properties.push(t.properties);break;case"LineString":e.MultiLineString.coordinates.push(t.geometry.coordinates),e.MultiLineString.properties.push(t.properties);break;case"MultiLineString":(r=e.MultiLineString.coordinates).push.apply(r,d(t.geometry.coordinates)),e.MultiLineString.properties.push(t.properties);break;case"Polygon":e.MultiPolygon.coordinates.push(t.geometry.coordinates),e.MultiPolygon.properties.push(t.properties);break;case"MultiPolygon":(i=e.MultiPolygon.coordinates).push.apply(i,d(t.geometry.coordinates)),e.MultiPolygon.properties.push(t.properties)}})),C(Object.keys(e).filter((function(t){return e[t].coordinates.length})).sort().map((function(t){return b({type:t,coordinates:e[t].coordinates},{collectedProperties:e[t].properties})})))},t.concave=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.maxEdge||1/0,r=function(t){var e=[],n={};return vt(t,(function(t){if(t.geometry){var r=t.geometry.coordinates.join("-");Object.prototype.hasOwnProperty.call(n,r)||(e.push(t),n[r]=!0)}})),C(e)}(t),i=oo(r);if(i.features=i.features.filter((function(t){var r=t.geometry.coordinates[0][0],i=t.geometry.coordinates[0][1],o=t.geometry.coordinates[0][2],s=ut(r,i,e),a=ut(i,o,e),u=ut(r,o,e);return s<=n&&a<=n&&u<=n})),i.features.length<1)return null;var o=Ro(i);return 1===o.coordinates.length&&(o.coordinates=o.coordinates[0],o.type="Polygon"),b(o)},t.containsNumber=$,t.convertArea=X,t.convertLength=j,t.convex=Oi,t.coordAll=yt,t.coordEach=ct,t.coordReduce=ft,t.createBins=zi,t.degreesToRadians=z,t.destination=at,t.difference=function(t){var e=[];if(mt(t,(function(t){e.push(t.coordinates)})),e.length<2)throw new Error("Must have at least two features");var n=t.features[0].properties||{},r=As.apply(Fs,[e[0]].concat(d(e.slice(1))));return 0===r.length?null:1===r.length?S(r[0],n):R(r,n)},t.dissolve=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.propertyName;nt(t,"Polygon","dissolve");var r=[];if(!n)return qs(R(Os.apply(null,t.features.map((function(t){return t.geometry.coordinates})))));var i={};vt(t,(function(t){t.properties&&(Object.prototype.hasOwnProperty.call(i,t.properties[n])||(i[t.properties[n]]=[]),i[t.properties[n]].push(t))}));for(var o=Object.keys(i),s=0;s1&&void 0!==arguments[1]?arguments[1]:{},o=i.properties,s=null==(e=i.autoComplete)||e,a=null==(n=i.orderCoords)||n;if(null!=(r=i.mutate)&&r||(t=Ai(t)),"FeatureCollection"===t.type){var u=[];return t.features.forEach((function(t){u.push(Q(ru(t,{},s,a)))})),R(u,o)}return ru(t,o,s,a)},t.mask=function(t,e,n){var r,i=null!=(r=null==n?void 0:n.mutate)&&r,o=e;e&&!1===i&&(o=Ai(e));var s,a=su(o);return("FeatureCollection"===t.type?ou(2===(s=t).features.length?Os(s.features[0].geometry.coordinates,s.features[1].geometry.coordinates):Os.apply(Fs,s.features.map((function(t){return t.geometry.coordinates})))):"Feature"===t.type?ou(Os(t.geometry.coordinates)):ou(Os(t.coordinates))).geometry.coordinates.forEach((function(t){a.geometry.coordinates.push(t[0])})),a},t.meta=Mt,t.midpoint=function(t,e){return at(t,ut(t,e)/2,st(t,e))},t.moranIndex=function(t,e){var n,r,i=e.inputField,o=e.threshold||1e5,s=e.p||2,u=null!=(n=e.binary)&&n,l=Gs(t,{alpha:e.alpha||-1,binary:u,p:s,standardization:null==(r=e.standardization)||r,threshold:o}),h=[];vt(t,(function(t){var e=t.properties||{};h.push(e[i])}));for(var c=au(h),f=function(t){var e,n=au(t),r=0,i=a(t);try{for(i.s();!(e=i.n()).done;){var o=e.value;r+=Math.pow(o-n,2)}}catch(t){i.e(t)}finally{i.f()}return r/t.length}(h),g=0,p=0,v=0,d=0,y=l.length,m=0;m2&&void 0!==arguments[2]?arguments[2]:{},r=n.units,i=n.properties||{},o=function(t){var e=[];switch(t.geometry?t.geometry.type:t.type){case"GeometryCollection":return mt(t,(function(t){"Point"===t.type&&e.push({type:"Feature",properties:{},geometry:t})})),{type:"FeatureCollection",features:e};case"FeatureCollection":return t.features=t.features.filter((function(t){return"Point"===t.geometry.type})),t;default:throw new Error("points must be a Point Collection")}}(t);if(!o.features.length)throw new Error("points must contain features");if(!e)throw new Error("line is required");if("LineString"!==it(e))throw new Error("line must be a LineString");var s=1/0,a=null;return vt(o,(function(t){var n=mu(t,e,{units:r});n2&&void 0!==arguments[2]?arguments[2]:{},a=null!=(i=s.method)?i:"geodesic",u=null!=(o=s.units)?o:"kilometers";if(!e)throw new Error("point is required");if(!r)throw new Error("polygon or multi-polygon is required");var l,h=rt(r);if("MultiPolygon"===h.type){var c=h.coordinates.map((function(n){return t(e,S(n),{method:a,units:u})}));return Math.min.apply(Math,d(c.map(Math.abs)))*(zt(e,r)?-1:1)}if(h.coordinates.length>1){var p=h.coordinates.map((function(n){return t(e,S([n]),{method:a,units:u})})),v=n(l=p)||f(l)||_(l)||g(),y=v[0],m=v.slice(1);if(y>=0)return y;var x=Math.min.apply(Math,d(m));return x<0?Math.abs(x):Math.min(x,Math.abs(y))}var E=le(h),k=1/0;return xt(E,(function(t){k=Math.min(k,mu(e,t,{method:a,units:u}))})),zt(e,h)?-k:k},t.points=N,t.pointsWithinPolygon=Su,t.polygon=S,t.polygonSmooth=function(t,e){(e=e||{}).iterations=e.iterations||1;var n=e.iterations,r=[];if(!t)throw new Error("inputPolys is required");return mt(t,(function(t,e,i){if("Polygon"===t.type){for(var o=[[]],s=0;s0&&(u=S(o).geometry),Ru(u,a),o=a.slice(0)}r.push(S(o,i))}else{if("MultiPolygon"!==t.type)throw new Error("geometry is invalid, must be Polygon or MultiPolygon");for(var l=[[[]]],h=0;h0&&(f=R(l).geometry),Au(f,c),l=c.slice(0)}r.push(R(l,i))}})),C(r)},t.polygonTangents=function(t,e){var n,r=Q(t),i=Q(e),o=[],s=[],a=Rt(e),u=0,l=null;switch(r[0]>a[0]&&r[0]a[1]&&r[1]_&&(_=k)}for(var b=[],w=Object.keys(l).length,I=f/w,N=0,S=0;S<_+1;S++)N+=Math.exp(-I)*Math.pow(I,S)/Zu(S),b.push(N);for(var M=[],L=0,P=0;P<_+1;P++){for(var C=0,T=Object.keys(l);CR&&(R=D)}var F=Xu[r]/Math.sqrt(w),q={criticalValue:F,isRandom:!0,maxAbsoluteDifference:R,observedDistribution:M};return R>F&&(q.isRandom=!1),q},t.radiansToDegrees=Y,t.radiansToLength=F,t.random=nl,t.randomLineString=$u,t.randomPoint=Ku,t.randomPolygon=Qu,t.randomPosition=Hu,t.rectangleGrid=oa,t.rewind=function(t){var e,n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(r=r||{}))throw new Error("options is invalid");var i=null!=(e=r.mutate)&&e,o=null!=(n=r.reverse)&&n;if(!t)throw new Error(" is required");if("boolean"!=typeof o)throw new Error(" must be a boolean");if("boolean"!=typeof i)throw new Error(" must be a boolean");i||"Point"===t.type||"MultiPoint"===t.type||(t=Ai(t));var s=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){rl(t,o)})),t;case"FeatureCollection":return vt(t,(function(t){vt(rl(t,o),(function(t){s.push(t)}))})),C(s)}return rl(t,o)},t.rhumbBearing=lt,t.rhumbDestination=Bs,t.rhumbDistance=Ys,t.round=D,t.sample=function(t,e){if(!t)throw new Error("fc is required");if(null==e)throw new Error("num is required");if("number"!=typeof e)throw new Error("num must be a number");var n=C(function(t,e){var n,r,i=t.slice(0),o=t.length,s=o-e;for(;o-- >s;)n=i[r=Math.floor((o+1)*Math.random())],i[r]=i[o],i[o]=n;return i.slice(s)}(t.features,e));return n},t.sector=function(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!Z(i=i||{}))throw new Error("options is invalid");var o=i.properties;if(!t)throw new Error("center is required");if(null==n)throw new Error("bearing1 is required");if(null==r)throw new Error("bearing2 is required");if(!e)throw new Error("radius is required");if("object"!==m(i))throw new Error("options must be an object");if(sl(n)===sl(r))return Ri(t,e,i);var s=Q(t),a=ja(t,e,n,r,i),u=[[s]];return ct(a,(function(t){u[0].push(t)})),u[0].push(s),S(u,o)},t.segmentEach=kt,t.segmentReduce=bt,t.shortestPath=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.obstacles||C([]),i=n.resolution||100;if(!t)throw new Error("start is required");if(!e)throw new Error("end is required");if(i&&(!U(i)||i<=0))throw new Error("options.resolution must be a number, greater than 0");var o=K(t),s=K(e);if(t=I(o),e=I(s),"FeatureCollection"===r.type){if(0===r.features.length)return L([o,s])}else{if("Polygon"!==r.type)throw new Error("invalid obstacles");r=C([b(rt(r))])}var a=r;a.features.push(t),a.features.push(e);var u=v(Rt(al(Vt(Rt(a)),1.15)),4),l=u[0],h=u[1],c=u[2],f=u[3],g=ut([l,h],[c,h],n)/i;a.features.pop(),a.features.pop();for(var p,d,y=g/ut([l,h],[c,h],n)*(c-l),m=g/ut([l,h],[l,f],n)*(f-h),_=c-l,x=f-h,E=Math.floor(_/y),k=Math.floor(x/m),w=(_-E*y)/2,N=[],S=[],M=1/0,P=1/0,T=f-(x-k*m)/2,O=0;T>=h;){for(var R=[],A=[],D=l+w,F=0;D<=c;){var q=I([D,T]),V=pl(q,r);R.push(V?0:1),A.push(D+"|"+T);var G=ut(q,t);!V&&G1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(i=null!=i?i:{}))throw new Error("options is invalid");var o=null!=(e=i.tolerance)?e:1,s=null!=(n=i.highQuality)&&n,a=null!=(r=i.mutate)&&r;if(!t)throw new Error("geojson is required");if(o&&o<0)throw new Error("invalid tolerance");return!0!==a&&(t=Ai(t)),mt(t,(function(t){!function(t,e,n){var r=t.type;if("Point"===r||"MultiPoint"===r)return t;if(Le(t,{mutate:!0}),"GeometryCollection"!==r)switch(r){case"LineString":t.coordinates=ml(t.coordinates,e,n);break;case"MultiLineString":t.coordinates=t.coordinates.map((function(t){return ml(t,e,n)}));break;case"Polygon":t.coordinates=_l(t.coordinates,e,n);break;case"MultiPolygon":t.coordinates=t.coordinates.map((function(t){return _l(t,e,n)}))}}(t,o,s)})),t},t.square=Ka,t.squareGrid=sa,t.standardDeviationalEllipse=function(t,e){var n;if(!Z(e=e||{}))throw new Error("options is invalid");var r=e.steps||64,i=e.weight,o=e.properties||{};if(!U(r))throw new Error("steps must be a number");if(!Z(o))throw new Error("properties must be a number");var s=yt(t).length,a=fi(t,{weight:i}),u=0,l=0,h=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));u+=Math.pow(r.x,2)*n,l+=Math.pow(r.y,2)*n,h+=r.x*r.y*n}));var c=u-l,f=Math.sqrt(Math.pow(c,2)+4*Math.pow(h,2)),g=2*h,p=Math.atan((c+f)/g),v=180*p/Math.PI,d=0,y=0,m=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));d+=Math.pow(r.x*Math.cos(p)-r.y*Math.sin(p),2)*n,y+=Math.pow(r.x*Math.sin(p)+r.y*Math.cos(p),2)*n,m+=n}));var _=Math.sqrt(2*d/m),x=Math.sqrt(2*y/m),E=js(a,_,x,{units:"degrees",angle:v,steps:r,properties:o}),k=Su(t,C([E])),b={meanCenterCoordinates:Q(a),semiMajorAxis:_,semiMinorAxis:x,numberOfFeatures:s,angle:v,percentageWithinEllipse:100*yt(k).length/s};return E.properties=null!=(n=E.properties)?n:{},E.properties.standardDeviationalEllipse=b,E},t.tag=function(t,e,n,r){return t=Ai(t),e=Ai(e),vt(t,(function(t){t.properties||(t.properties={}),vt(e,(function(e){t.properties&&e.properties&&void 0===t.properties[r]&&zt(t,e)&&(t.properties[r]=e.properties[n])}))})),t},t.tesselate=function(t){if(!t.geometry||"Polygon"!==t.geometry.type&&"MultiPolygon"!==t.geometry.type)throw new Error("input must be a Polygon or MultiPolygon");var e={type:"FeatureCollection",features:[]};return"Polygon"===t.geometry.type?e.features=Nl(t.geometry.coordinates):t.geometry.coordinates.forEach((function(t){e.features=e.features.concat(Nl(t))})),e},t.tin=oo,t.toMercator=Vu,t.toWgs84=Gu,t.transformRotate=zs,t.transformScale=al,t.transformTranslate=function(t,e,n,r){if(!Z(r=r||{}))throw new Error("options is invalid");var i=r.units,o=r.zTranslation,s=r.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("distance is required");if(o&&"number"!=typeof o&&isNaN(o))throw new Error("zTranslation is not a number");if(o=void 0!==o?o:0,0===e&&0===o)return t;if(null==n||isNaN(n))throw new Error("direction is required");return e<0&&(e=-e,n+=180),!1!==s&&void 0!==s||(t=Ai(t)),ct(t,(function(t){var r=Q(Bs(t,e,n,{units:i}));t[0]=r[0],t[1]=r[1],o&&3===t.length&&(t[2]+=o)})),t},t.triangleGrid=aa,t.truncate=Qa,t.union=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must have at least 2 geometries");var r=Os.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)},t.unkinkPolygon=function(t){var e=[];return xt(t,(function(t){"Polygon"===t.geometry.type&&vt(Ll(t),(function(n){e.push(S(n.geometry.coordinates,t.properties))}))})),C(e)},t.validateBBox=H,t.validateId=W,t.voronoi=function(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox||[-180,-85,180,85];if(!t)throw new Error("points is required");if(!Array.isArray(n))throw new Error("bbox is invalid");return nt(t,"Point","points"),C(function(){var t=Fl,e=ql,n=null;function r(r){return new mh(r.map((function(n,i){var o=[Math.round(t(n,i,r)/vh)*vh,Math.round(e(n,i,r)/vh)*vh];return o.index=i,o.data=n,o})),n)}return r.polygons=function(t){return r(t).polygons()},r.links=function(t){return r(t).links()},r.triangles=function(t){return r(t).triangles()},r.x=function(e){return arguments.length?(t="function"==typeof e?e:Dl(+e),r):t},r.y=function(t){return arguments.length?(e="function"==typeof t?t:Dl(+t),r):e},r.extent=function(t){return arguments.length?(n=null==t?null:[[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]],r):n&&[[n[0][0],n[0][1]],[n[1][0],n[1][1]]]},r.size=function(t){return arguments.length?(n=null==t?null:[[0,0],[+t[0],+t[1]]],r):n&&[n[1][0]-n[0][0],n[1][1]-n[0][1]]},r}().x((function(t){return t.geometry.coordinates[0]})).y((function(t){return t.geometry.coordinates[1]})).extent([[n[0],n[1]],[n[2],n[3]]]).polygons(t.features).map((function(e,n){return Object.assign(function(t){return(t=t.slice()).push(t[0]),S([t])}(e),{properties:Fi(t.features[n].properties)})})))}})); diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl.js b/docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl.js new file mode 100644 index 0000000..c0d6d59 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl.js @@ -0,0 +1,3910 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl.yaml b/docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl.yaml new file mode 100644 index 0000000..6a5c2f7 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl.yaml @@ -0,0 +1,65 @@ +dependencies: + - name: mapbox-gl-js + version: "3.15.0" + src: + href: "https://api.mapbox.com/mapbox-gl-js/v3.15.0/" + script: + - "mapbox-gl.js" + stylesheet: + - "mapbox-gl.css" + - name: mapbox-gl-draw + version: "1.5.0" + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.5.0/" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: mapbox-gl-geocoder + version: 5.0.0 + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/" + script: + - "mapbox-gl-geocoder.min.js" + stylesheet: + - "mapbox-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: mapbox-pmtiles + version: 1.1.0 + src: "htmlwidgets/lib/mapbox-pmtiles" + script: + - "pmtiles-source-optimized-v2.js" + - name: turf + version: "7.2.0" + src: "htmlwidgets/lib/turf" + script: + - "turf.min.js" + - name: turf-operations + version: "1.0.0" + src: "htmlwidgets" + script: + - "turf-operations.js" diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl_compare.js b/docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl_compare.js new file mode 100644 index 0000000..780fbd6 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl_compare.js @@ -0,0 +1,3192 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +HTMLWidgets.widget({ + name: "mapboxgl_compare", + + type: "output", + + factory: function (el, width, height) { + // Store maps and compare object to allow access during Shiny updates + let beforeMap, afterMap, compareControl, draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + if (typeof mapboxgl.Compare === "undefined") { + console.error("Mapbox GL Compare plugin is not loaded."); + return; + } + + // Register PMTiles source type if available + if (typeof MapboxPmTilesSource !== "undefined" && typeof pmtiles !== "undefined") { + try { + mapboxgl.Style.setSourceType(PMTILES_SOURCE_TYPE, MapboxPmTilesSource); + console.log("PMTiles support enabled for Mapbox GL JS Compare"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + // Create container divs for the maps + const beforeContainerId = `${el.id}-before`; + const afterContainerId = `${el.id}-after`; + + // Different HTML structure based on mode + if (x.mode === "sync") { + // Side-by-side sync mode + const containerStyle = + x.orientation === "horizontal" + ? `display: flex; flex-direction: column; width: 100%; height: 100%;` + : `display: flex; flex-direction: row; width: 100%; height: 100%;`; + + const mapStyle = + x.orientation === "horizontal" + ? `width: 100%; height: 50%; position: relative;` + : `width: 50%; height: 100%; position: relative;`; + + el.innerHTML = ` +
+
+
+
+ `; + } else { + // Default swipe mode + el.innerHTML = ` +
+
+ `; + } + + beforeMap = new mapboxgl.Map({ + container: beforeContainerId, + style: x.map1.style, + center: x.map1.center, + zoom: x.map1.zoom, + bearing: x.map1.bearing, + pitch: x.map1.pitch, + projection: x.map1.projection, + accessToken: x.map1.access_token, + ...x.map1.additional_params, + }); + + afterMap = new mapboxgl.Map({ + container: afterContainerId, + style: x.map2.style, + center: x.map2.center, + zoom: x.map2.zoom, + bearing: x.map2.bearing, + pitch: x.map2.pitch, + projection: x.map2.projection, + accessToken: x.map2.access_token, + ...x.map2.additional_params, + }); + + // Set the global access token + mapboxgl.accessToken = x.map1.access_token; + + if (x.mode === "swipe") { + // Only create the swiper in swipe mode + compareControl = new mapboxgl.Compare( + beforeMap, + afterMap, + `#${el.id}`, + { + mousemove: x.mousemove, + orientation: x.orientation, + }, + ); + + // Apply custom swiper color if provided + if (x.swiper_color) { + const swiperSelector = + x.orientation === "vertical" + ? ".mapboxgl-compare .compare-swiper-vertical" + : ".mapboxgl-compare .compare-swiper-horizontal"; + + const styleEl = document.createElement("style"); + styleEl.innerHTML = `${swiperSelector} { background-color: ${x.swiper_color}; }`; + document.head.appendChild(styleEl); + } + } else { + // For sync mode, we directly leverage the sync-move module's approach + + // Function to synchronize maps as seen in the mapbox-gl-sync-move module + const syncMaps = () => { + // Array of maps to sync + const maps = [beforeMap, afterMap]; + // Array of move event handlers + const moveHandlers = []; + + // Setup the sync between maps + maps.forEach((map, index) => { + // Create a handler for each map that syncs all other maps + moveHandlers[index] = (e) => { + // Disable all move events temporarily + maps.forEach((m, i) => { + m.off("move", moveHandlers[i]); + }); + + // Get the state from the map that triggered the event + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Apply this state to all other maps + maps + .filter((m, i) => i !== index) + .forEach((m) => { + m.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + }); + + // Re-enable move events + maps.forEach((m, i) => { + m.on("move", moveHandlers[i]); + }); + }; + + // Add the move handler to each map + map.on("move", moveHandlers[index]); + }); + }; + + // Initialize the sync + syncMaps(); + } + + // Ensure both maps resize correctly + beforeMap.on("load", function () { + beforeMap.resize(); + applyMapModifications(beforeMap, x.map1); + + // Setup Shiny event handlers for the before map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(beforeMap, el.id, "before"); + } + }); + + afterMap.on("load", function () { + afterMap.resize(); + applyMapModifications(afterMap, x.map2); + + // Setup Shiny event handlers for the after map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(afterMap, el.id, "after"); + } + + // Add compare-level legends after both maps are loaded + if (x.compare_legends && Array.isArray(x.compare_legends)) { + x.compare_legends.forEach(function(legendInfo) { + // Add CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendInfo.css; + legendCss.setAttribute("data-mapgl-legend-css", el.id); + document.head.appendChild(legendCss); + + // Create legend element + const legend = document.createElement("div"); + legend.innerHTML = legendInfo.html; + legend.classList.add("mapboxgl-legend"); + + // Append to the appropriate container based on target + if (legendInfo.target === "compare") { + // Append to the main compare container + el.appendChild(legend); + } else if (legendInfo.target === "before") { + // Append to the before map container + beforeMap.getContainer().appendChild(legend); + } else if (legendInfo.target === "after") { + // Append to the after map container + afterMap.getContainer().appendChild(legend); + } + }); + } + }); + + // Handle Shiny messages + if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler( + "mapboxgl-compare-proxy", + function (data) { + if (data.id !== el.id) return; + + // Get the message and determine which map to target + var message = data.message; + var map = message.map === "before" ? beforeMap : afterMap; + + if (!map) return; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Process the message based on type + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup( + e, + map, + message.layer.popup, + message.layer.id, + ); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = + clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + message.layer.tooltip, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error( + "Failed to add layer via proxy: ", + message.layer, + e, + ); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if ( + window._mapboxPopups && + window._mapboxPopups[message.layer_id] + ) { + window._mapboxPopups[message.layer_id].remove(); + delete window._mapboxPopups[message.layer_id]; + } + + if (map.getLayer(message.layer_id)) { + // Remove tooltip handlers + if ( + window._mapboxHandlers && + window._mapboxHandlers[message.layer_id] + ) { + const handlers = window._mapboxHandlers[message.layer_id]; + if (handlers.mousemove) { + map.off( + "mousemove", + message.layer_id, + handlers.mousemove, + ); + } + if (handlers.mouseleave) { + map.off( + "mouseleave", + message.layer_id, + handlers.mouseleave, + ); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer_id]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer_id] + ) { + map.off( + "click", + message.layer_id, + window._mapboxClickHandlers[message.layer_id], + ); + delete window._mapboxClickHandlers[message.layer_id]; + } + + // Remove the layer + map.removeLayer(message.layer_id); + } + if (map.getSource(message.layer_id)) { + map.removeSource(message.layer_id); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer_id]; + delete layerState.paintProperties[message.layer_id]; + delete layerState.layoutProperties[message.layer_id]; + delete layerState.tooltips[message.layer_id]; + delete layerState.popups[message.layer_id]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty( + message.layer, + message.name, + message.value, + ); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "add_legend") { + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + + // Append legend to the correct map container + const targetContainer = map.getContainer(); + targetContainer.appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Save the current view state + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Apply the new style + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + map.off("mousemove", layerId); + map.off("mouseleave", layerId); + + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on("mousemove", layerId, function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }); + + map.on("mouseleave", layerId, function () { + onMouseLeaveTooltip(map, tooltip); + }); + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + delete window._mapboxClickHandlers[layerId]; + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + + // Restore the view state after the style has loaded + map.once("style.load", function () { + map.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + + // Re-apply map modifications + if (map === beforeMap) { + applyMapModifications(map, x.map1); + } else { + applyMapModifications(map, x.map2); + } + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "navigation", control: nav }); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + customControlContainer.innerHTML = controlOptions.html; + customControlContainer.className = "mapboxgl-ctrl"; + if (controlOptions.className) { + customControlContainer.className += " " + controlOptions.className; + } + + // Create the custom control object + const customControl = { + onAdd: function(map) { + return customControlContainer; + }, + onRemove: function() { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild(customControlContainer); + } + } + }; + + map.addControl(customControl, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + + // Store control with proper type + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = + "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + const resetControlObj = { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }; + + map.addControl(resetControlObj, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "reset", control: resetControlObj }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(draw, message.source, map); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + if (map._mapgl_draw) { + const features = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + if (draw) { + if (map._mapgl_draw) map._mapgl_draw.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + if (draw) { + if (message.data.clear_existing) { + if (map._mapgl_draw) map._mapgl_draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "fullscreen", control: fullscreen }); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "scale", control: scaleControl }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(data.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(data.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(data.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(data.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "geolocate", control: geolocate }); + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "geocoder", control: geocoder }); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + + // Handle use_icon parameter + let className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + + if (message.use_icon) { + className += " icon-only"; + } + + layersControl.className = className; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `.layers-control { background-color: ${colors.background} !important; }`; + } + if (colors.text) { + css += `.layers-control a { color: ${colors.text} !important; }`; + } + if (colors.activeBackground) { + css += `.layers-control a.active { background-color: ${colors.activeBackground} !important; }`; + } + if (colors.activeText) { + css += `.layers-control a.active { color: ${colors.activeText} !important; }`; + } + if (colors.hoverBackground) { + css += `.layers-control a:hover { background-color: ${colors.hoverBackground} !important; }`; + } + if (colors.hoverText) { + css += `.layers-control a:hover { color: ${colors.hoverText} !important; }`; + } + if (colors.toggleButtonBackground) { + css += `.layers-control .toggle-button { background-color: ${colors.toggleButtonBackground} + !important; }`; + } + if (colors.toggleButtonText) { + css += `.layers-control .toggle-button { color: ${colors.toggleButtonText} !important; }`; + } + + styleEl.innerHTML = css; + document.head.appendChild(styleEl); + } + + document.getElementById(data.id).appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + message.layers || + map.getStyle().layers.map((layer) => layer.id); + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + toggleButton.textContent = "Layers"; + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "layers", control: layersControl }); + } else if (message.type === "add_globe_minimap") { + // Add the globe minimap control + const minimap = new MapboxGlobeMinimap({ + center: map.getCenter(), + zoom: map.getZoom(), + bearing: map.getBearing(), + pitch: map.getPitch(), + globeSize: message.globe_size, + landColor: message.land_color, + waterColor: message.water_color, + markerColor: message.marker_color, + markerSize: message.marker_size, + }); + + map.addControl(minimap, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "globe_minimap", control: minimap }); + } else if (message.type === "set_rain") { + if (message.rain) { + map.setRain(message.rain); + } else { + map.setRain(null); + } + } else if (message.type === "set_snow") { + if (message.snow) { + map.setSnow(message.snow); + } else { + map.setSnow(null); + } + } else if (message.type === "set_projection") { + map.setProjection(message.projection); + } else if (message.type === "set_source") { + if (map.getLayer(message.layer)) { + const sourceId = map.getLayer(message.layer).source; + map.getSource(sourceId).setData(JSON.parse(message.source)); + } + } else if (message.type === "set_tooltip") { + // Track tooltip state + layerState.tooltips[message.layer] = message.tooltip; + + if (map.getLayer(message.layer)) { + // Remove any existing tooltip handlers + map.off("mousemove", message.layer); + map.off("mouseleave", message.layer); + + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on("mousemove", message.layer, function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[message.tooltip]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }); + + map.on("mouseleave", message.layer, function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }); + } + } else if (message.type === "set_popup") { + // Track popup state + layerState.popups[message.layer] = message.popup; + + if (map.getLayer(message.layer)) { + // Remove any existing popup click handlers for this layer + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove any existing popup for this layer + if ( + window._mapboxPopups && + window._mapboxPopups[message.layer] + ) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Create new click handler for popup + const clickHandler = function (e) { + onClickPopup(e, map, message.popup, message.layer); + }; + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer] = clickHandler; + + // Add click handler + map.on("click", message.layer, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer, function () { + map.getCanvas().style.cursor = ""; + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } + } else if (message.type === "set_opacity") { + // Set opacity for all fill layers + const style = map.getStyle(); + if (style && style.layers) { + style.layers.forEach(function (layer) { + if (layer.type === "fill" && map.getLayer(layer.id)) { + map.setPaintProperty( + layer.id, + "fill-opacity", + message.opacity, + ); + } + }); + } + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection) + ); + } else if (message.type === "clear_controls") { + // Handle clear_controls for compare widgets + if (!message.controls || message.controls.length === 0) { + // Clear all controls + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + } + } + }, + ); + } + + function setupShinyEvents(map, parentId, mapType) { + // Set view state on move end + map.on("moveend", function () { + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_view", { + center: [center.lng, center.lat], + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + } + }); + + // Send clicked point coordinates to Shiny + map.on("click", function (e) { + // Check if this map's draw control is active and in a drawing mode + let isDrawing = false; + if (map._mapgl_draw && map._mapgl_draw.getMode) { + const mode = map._mapgl_draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + // Filter out draw layers + const nonDrawFeatures = features.filter(feature => + !feature.layer.id.includes('gl-draw') && + !feature.source.includes('gl-draw') + ); + + if (nonDrawFeatures.length > 0) { + const feature = nonDrawFeatures[0]; + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }); + } + } else { + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_feature_click", null); + } + } + } + + // Always send regular click event + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }); + } + }); + + // Add hover events if enabled for this map + const mapConfig = (mapType === "before") ? x.map1 : x.map2; + if (mapConfig.hover_events && mapConfig.hover_events.enabled) { + map.on("mousemove", function (e) { + if (window.Shiny) { + // Feature hover events + if (mapConfig.hover_events.features) { + const options = mapConfig.hover_events.layer_id + ? { layers: Array.isArray(mapConfig.hover_events.layer_id) + ? mapConfig.hover_events.layer_id + : mapConfig.hover_events.layer_id.split(',').map(id => id.trim()) } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if(features.length > 0) { + const feature = features[0]; + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } else { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + null + ); + } + } + + // Coordinate hover events + if (mapConfig.hover_events.coordinates) { + Shiny.setInputValue( + parentId + "_" + mapType + "_hover", + { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } + } + }); + } + } + + function applyMapModifications(map, mapData) { + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + // Note: tooltip handlers are already defined at the top of the file + + // Set config properties if provided + if (mapData.config_properties) { + mapData.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + // Process H3J sources if provided + if (mapData.h3j_sources) { + mapData.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + }); + } + + if (mapData.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + mapData.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setText(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + } + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + } + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (mapData.sources) { + mapData.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceConfig = { + type: "vector", + url: source.url, + }; + if (source.promoteId) { + sourceConfig.promoteId = source.promoteId; + } + map.addSource(source.id, sourceConfig); + } else if (source.type === "geojson") { + const geojsonData = source.data; + map.addSource(source.id, { + type: "geojson", + data: geojsonData, + generateId: true, + }); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + // Add layers if provided + if (mapData.layers) { + mapData.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + map.on("click", layer.id, function (e) { + const description = e.features[0].properties[layer.popup]; + + new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = e.features[0].id; + map.setFeatureState( + { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: true }, + ); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Set terrain if provided + if (mapData.terrain) { + map.setTerrain({ + source: mapData.terrain.source, + exaggeration: mapData.terrain.exaggeration, + }); + } + + // Set fog + if (mapData.fog) { + map.setFog(mapData.fog); + } + + // Set rain effect if provided + if (mapData.rain) { + map.setRain(mapData.rain); + } + + // Set snow effect if provided + if (mapData.snow) { + map.setSnow(mapData.snow); + } + + if (mapData.fitBounds) { + map.fitBounds(mapData.fitBounds.bounds, mapData.fitBounds.options); + } + if (mapData.flyTo) { + map.flyTo(mapData.flyTo); + } + if (mapData.easeTo) { + map.easeTo(mapData.easeTo); + } + if (mapData.setCenter) { + map.setCenter(mapData.setCenter); + } + if (mapData.setZoom) { + map.setZoom(mapData.setZoom); + } + + // Apply moveLayer operations if provided + if (mapData.moveLayer) { + mapData.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + if (mapData.jumpTo) { + map.jumpTo(mapData.jumpTo); + } + + // Add custom images if provided + if (mapData.images && Array.isArray(mapData.images)) { + mapData.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (mapData.images) { + console.error("mapData.images is not an array:", mapData.images); + } + + // Remove existing legends only from this specific map container + const mapContainer = map.getContainer(); + const existingLegends = mapContainer.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + + // Don't remove all legend styles globally - they might belong to other maps + // Only remove styles when the entire widget is being recreated + + if (mapData.legend_html && mapData.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = mapData.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", el.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = mapData.legend_html; + legend.classList.add("mapboxgl-legend"); + + // Append legend to the correct map container instead of main container + const mapContainer = map.getContainer(); + mapContainer.appendChild(legend); + } + + // Add fullscreen control if enabled + if ( + mapData.fullscreen_control && + mapData.fullscreen_control.enabled + ) { + const position = mapData.fullscreen_control.position || "top-right"; + map.addControl(new mapboxgl.FullscreenControl(), position); + } + + // Add navigation control if enabled + if (mapData.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: mapData.navigation_control.show_compass, + showZoom: mapData.navigation_control.show_zoom, + visualizePitch: mapData.navigation_control.visualize_pitch, + }); + map.addControl(nav, mapData.navigation_control.position); + } + + // Add scale control if enabled + if (mapData.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: mapData.scale_control.maxWidth, + unit: mapData.scale_control.unit, + }); + map.addControl(scaleControl, mapData.scale_control.position); + map.controls.push(scaleControl); + } + + // Add geolocate control if enabled + if (mapData.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: mapData.geolocate_control.positionOptions, + trackUserLocation: mapData.geolocate_control.trackUserLocation, + showAccuracyCircle: mapData.geolocate_control.showAccuracyCircle, + showUserLocation: mapData.geolocate_control.showUserLocation, + showUserHeading: mapData.geolocate_control.showUserHeading, + fitBoundsOptions: mapData.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, mapData.geolocate_control.position); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Helper function to generate draw styles based on parameters + function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "midpoint"], + ], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: [ + "all", + ["==", "meta", "vertex"], + ["==", "$type", "Point"], + ], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: [ + "all", + ["==", "meta", "vertex"], + ["==", "$type", "Point"], + ], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } + } + + // Add geocoder control if enabled + if (mapData.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...mapData.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + mapData.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + + // Add draw control if enabled + if (mapData.draw_control) { + if (mapData.draw_control && mapData.draw_control.enabled) { + let drawOptions = mapData.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (mapData.draw_control.styling) { + const generatedStyles = generateDrawStyles( + mapData.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (mapData.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + mapData.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (mapData.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (mapData.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, mapData.draw_control.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add custom mode buttons and styling + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + + // Add rectangle styling and button + if (mapData.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + drawControl.changeMode('draw_rectangle'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + } + + // Add radius styling and button + if (mapData.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + drawControl.changeMode('draw_radius'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + } + }, 100); + + // Add initial features if provided + if (mapData.draw_control.source) { + addSourceFeaturesToDraw(drawControl, mapData.draw_control.source, map); + } + + // Process any queued features + if (mapData.draw_features_queue) { + mapData.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + if (map._mapgl_draw) map._mapgl_draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (mapData.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (mapData.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${mapData.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + // Helper function for updating drawn features + function updateDrawnFeatures() { + if (HTMLWidgets.shinyMode && map._mapgl_draw) { + const features = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(features), + ); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + } + + // Add reset control if enabled + if (mapData.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: mapData.reset_control.animate, + }; + + if (mapData.reset_control.duration) { + initialView.duration = mapData.reset_control.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + mapData.reset_control.position, + ); + } + + // Add the layers control if provided + if (mapData.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = mapData.layers_control.control_id; + + // Handle use_icon parameter + let className = mapData.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + + layersControl.className = className; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = mapData.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + mapData.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = mapData.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (mapData.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + if (mapData.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + } + }, + + resize: function (width, height) { + // Code to handle resizing if necessary + }, + }; + }, +}); diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl_compare.yaml b/docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl_compare.yaml new file mode 100644 index 0000000..55f1563 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/mapboxgl_compare.yaml @@ -0,0 +1,57 @@ +dependencies: + - name: mapbox-gl-js + version: "3.15.0" + src: + href: "https://api.mapbox.com/mapbox-gl-js/" + script: + - "v3.15.0/mapbox-gl.js" + - "plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.js" + stylesheet: + - "v3.15.0/mapbox-gl.css" + - "plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.css" + - name: mapbox-gl-draw + version: "1.4.3" + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: mapbox-gl-geocoder + version: 5.0.0 + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/" + script: + - "mapbox-gl-geocoder.min.js" + stylesheet: + - "mapbox-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: mapbox-pmtiles + version: 1.1.0 + src: "htmlwidgets/lib/mapbox-pmtiles" + script: + - "pmtiles-source-optimized-v2.js" diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl.js b/docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl.js new file mode 100644 index 0000000..5937d02 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl.js @@ -0,0 +1,5048 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + const result = originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + return result; + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse( + this.getAttribute("data-layer-ids"), + ); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } + } + }); +} diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl.yaml b/docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl.yaml new file mode 100644 index 0000000..f6679e5 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl.yaml @@ -0,0 +1,69 @@ +dependencies: + - name: maplibre-gl + version: "5.7.2" + src: "htmlwidgets/lib/maplibre-gl" + script: + - "maplibre-gl.js" + stylesheet: + - "maplibre-gl.css" + - name: mapbox-gl-draw + version: "1.5.0" + src: "htmlwidgets/lib/mapbox-gl-draw" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: maplibre-gl-geocoder + version: 1.5.0 + src: "htmlwidgets/lib/maplibre-gl-geocoder" + script: + - "maplibre-gl-geocoder.min.js" + stylesheet: + - "maplibre-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: h3j-h3t + version: 0.9.2 + src: "htmlwidgets/lib/h3j-h3t" + script: + - "h3j_h3t.js" + - name: maptiler-geocoding-control + version: 2.1.7 + src: "htmlwidgets/lib/maptiler-geocoding-control" + script: + - "maplibregl.umd.js" + stylesheet: + - "style.css" + - name: turf + version: "7.2.0" + src: "htmlwidgets/lib/turf" + script: + - "turf.min.js" + - name: turf-operations + version: "1.0.0" + src: "htmlwidgets" + script: + - "turf-operations.js" diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl_compare.js b/docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl_compare.js new file mode 100644 index 0000000..a0e0caf --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl_compare.js @@ -0,0 +1,4138 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case 'get': + return properties[expression[1]]; + case 'concat': + return expression.slice(1).map(item => evaluateExpression(item, properties)).join(''); + case 'to-string': + return String(evaluateExpression(expression[1], properties)); + case 'to-number': + return Number(evaluateExpression(expression[1], properties)); + case 'number-format': + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || 'en-US'; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty('min-fraction-digits')) { + formatOptions.minimumFractionDigits = options['min-fraction-digits']; + } + if (options.hasOwnProperty('max-fraction-digits')) { + formatOptions.maximumFractionDigits = options['max-fraction-digits']; + } + if (options.hasOwnProperty('min-integer-digits')) { + formatOptions.minimumIntegerDigits = options['min-integer-digits']; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty('useGrouping')) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(tooltipProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._maplibrePopups && window._maplibrePopups[layerId]) { + window._maplibrePopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._maplibrePopups) { + window._maplibrePopups = {}; + } + window._maplibrePopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on('close', function() { + if (window._maplibrePopups[layerId] === popup) { + delete window._maplibrePopups[layerId]; + } + }); +} + +HTMLWidgets.widget({ + name: "maplibregl_compare", + + type: "output", + + factory: function (el, width, height) { + // Store maps and compare object to allow access during Shiny updates + let beforeMap, afterMap, compareControl, draw; + + return { + renderValue: function (x) { + + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + if (typeof maplibregl.Compare === "undefined") { + console.error("Maplibre GL Compare plugin is not loaded."); + return; + } + + // Add PMTiles support + if (typeof pmtiles !== "undefined") { + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + } + + // Create container divs for the maps + const beforeContainerId = `${el.id}-before`; + const afterContainerId = `${el.id}-after`; + + // Different HTML structure based on mode + if (x.mode === "sync") { + // Side-by-side sync mode + const containerStyle = + x.orientation === "horizontal" + ? `display: flex; flex-direction: column; width: 100%; height: 100%;` + : `display: flex; flex-direction: row; width: 100%; height: 100%;`; + + const mapStyle = + x.orientation === "horizontal" + ? `width: 100%; height: 50%; position: relative;` + : `width: 50%; height: 100%; position: relative;`; + + el.innerHTML = ` +
+
+
+
+ `; + } else { + // Default swipe mode + el.innerHTML = ` +
+
+ `; + } + + beforeMap = new maplibregl.Map({ + container: beforeContainerId, + style: x.map1.style, + center: x.map1.center, + zoom: x.map1.zoom, + bearing: x.map1.bearing, + pitch: x.map1.pitch, + accessToken: x.map1.access_token, + ...x.map1.additional_params, + }); + + // Initialize controls array + beforeMap.controls = []; + + afterMap = new maplibregl.Map({ + container: afterContainerId, + style: x.map2.style, + center: x.map2.center, + zoom: x.map2.zoom, + bearing: x.map2.bearing, + pitch: x.map2.pitch, + accessToken: x.map2.access_token, + ...x.map2.additional_params, + }); + + // Initialize controls array + afterMap.controls = []; + + if (x.mode === "swipe") { + // Only create the swiper in swipe mode + compareControl = new maplibregl.Compare( + beforeMap, + afterMap, + `#${el.id}`, + { + mousemove: x.mousemove, + orientation: x.orientation, + }, + ); + + // Apply custom swiper color if provided + if (x.swiper_color) { + const swiperSelector = x.orientation === "vertical" ? + ".maplibregl-compare .compare-swiper-vertical" : + ".maplibregl-compare .compare-swiper-horizontal"; + + const styleEl = document.createElement('style'); + styleEl.innerHTML = `${swiperSelector} { background-color: ${x.swiper_color}; }`; + document.head.appendChild(styleEl); + } + } else { + // For sync mode, we directly leverage the sync-move module's approach + + // Function to synchronize maps as seen in the mapbox-gl-sync-move module + const syncMaps = () => { + // Array of maps to sync + const maps = [beforeMap, afterMap]; + // Array of move event handlers + const moveHandlers = []; + + // Setup the sync between maps + maps.forEach((map, index) => { + // Create a handler for each map that syncs all other maps + moveHandlers[index] = (e) => { + // Disable all move events temporarily + maps.forEach((m, i) => { + m.off("move", moveHandlers[i]); + }); + + // Get the state from the map that triggered the event + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Apply this state to all other maps + maps.filter((m, i) => i !== index).forEach( + (m) => { + m.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + }, + ); + + // Re-enable move events + maps.forEach((m, i) => { + m.on("move", moveHandlers[i]); + }); + }; + + // Add the move handler to each map + map.on("move", moveHandlers[index]); + }); + }; + + // Initialize the sync + syncMaps(); + } + + // Ensure both maps resize correctly + beforeMap.on("load", function () { + beforeMap.resize(); + applyMapModifications(beforeMap, x.map1); + + // Setup Shiny event handlers for the before map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(beforeMap, el.id, "before"); + } + }); + + afterMap.on("load", function () { + afterMap.resize(); + applyMapModifications(afterMap, x.map2); + + // Setup Shiny event handlers for the after map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(afterMap, el.id, "after"); + } + + // Add compare-level legends after both maps are loaded + if (x.compare_legends && Array.isArray(x.compare_legends)) { + x.compare_legends.forEach(function(legendInfo) { + // Add CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendInfo.css; + legendCss.setAttribute("data-mapgl-legend-css", el.id); + document.head.appendChild(legendCss); + + // Create legend element + const legend = document.createElement("div"); + legend.innerHTML = legendInfo.html; + legend.classList.add("mapboxgl-legend"); + + // Append to the appropriate container based on target + if (legendInfo.target === "compare") { + // Append to the main compare container + el.appendChild(legend); + } else if (legendInfo.target === "before") { + // Append to the before map container + beforeMap.getContainer().appendChild(legend); + } else if (legendInfo.target === "after") { + // Append to the after map container + afterMap.getContainer().appendChild(legend); + } + }); + } + }); + + // Define updateDrawnFeatures function for the draw tool + window.updateDrawnFeatures = function () { + if (draw) { + const features = draw.getAll(); + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(features), + ); + } + }; + + // Handle Shiny messages + if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler( + "maplibre-compare-proxy", + function (data) { + if (data.id !== el.id) return; + + // Get the message and determine which map to target + var message = data.message; + var map = + message.map === "before" ? beforeMap : afterMap; + + if (!map) return; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {} // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Process the message based on type + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "promoteId") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "data" && key !== "generateId") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "tiles" && key !== "tileSize" && key !== "maxzoom") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if ( + message.source.type === "raster-dem" + ) { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "tileSize" && key !== "maxzoom") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "coordinates") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "urls" && key !== "coordinates") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function(key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer( + message.layer, + message.layer.before_id, + ); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on( + "click", + message.layer.id, + clickHandler + ); + + // Change cursor to pointer when hovering over the layer + map.on( + "mouseenter", + message.layer.id, + function () { + map.getCanvas().style.cursor = + "pointer"; + }, + ); + + // Change cursor back to default when leaving the layer + map.on( + "mouseleave", + message.layer.id, + function () { + map.getCanvas().style.cursor = + ""; + }, + ); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + message.layer.tooltip, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on( + "mousemove", + message.layer.id, + mouseMoveHandler, + ); + map.on( + "mouseleave", + message.layer.id, + mouseLeaveHandler, + ); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[ + message.layer.id + ] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [ + key, + value, + ] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace( + /_/g, + "-", + ); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on( + "mousemove", + message.layer.id, + function (e) { + if (e.features.length > 0) { + if ( + hoveredFeatureId !== + null + ) { + const featureState = { + source: + typeof message + .layer + .source === + "string" + ? message + .layer + .source + : message + .layer + .id, + id: hoveredFeatureId, + }; + if ( + message.layer + .source_layer + ) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState( + featureState, + { + hover: false, + }, + ); + } + hoveredFeatureId = + e.features[0].id; + const featureState = { + source: + typeof message.layer + .source === + "string" + ? message.layer + .source + : message.layer + .id, + id: hoveredFeatureId, + }; + if ( + message.layer + .source_layer + ) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState( + featureState, + { + hover: true, + }, + ); + } + }, + ); + + map.on( + "mouseleave", + message.layer.id, + function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer + .source === + "string" + ? message.layer + .source + : message.layer + .id, + id: hoveredFeatureId, + }; + if ( + message.layer + .source_layer + ) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState( + featureState, + { + hover: false, + }, + ); + } + hoveredFeatureId = null; + }, + ); + + Object.keys(jsHoverOptions).forEach( + function (key) { + const originalPaint = + map.getPaintProperty( + message.layer.id, + key, + ) || + message.layer.paint[key]; + map.setPaintProperty( + message.layer.id, + key, + [ + "case", + [ + "boolean", + [ + "feature-state", + "hover", + ], + false, + ], + jsHoverOptions[key], + originalPaint, + ], + ); + }, + ); + } + } catch (e) { + console.error( + "Failed to add layer via proxy: ", + message.layer, + e, + ); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer_id and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer_id key + if (window._mapboxPopups[message.layer_id]) { + window._mapboxPopups[message.layer_id].remove(); + delete window._mapboxPopups[message.layer_id]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if (message.layer && message.layer.id && window._mapboxPopups[message.layer.id]) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer_id)) { + // Remove tooltip handlers + if ( + window._mapboxHandlers && + window._mapboxHandlers[message.layer_id] + ) { + const handlers = + window._mapboxHandlers[ + message.layer_id + ]; + if (handlers.mousemove) { + map.off( + "mousemove", + message.layer_id, + handlers.mousemove, + ); + } + if (handlers.mouseleave) { + map.off( + "mouseleave", + message.layer_id, + handlers.mouseleave, + ); + } + // Clean up the reference + delete window._mapboxHandlers[ + message.layer_id + ]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer_id key + if (window._mapboxClickHandlers[message.layer_id]) { + map.off( + "click", + message.layer_id, + window._mapboxClickHandlers[message.layer_id] + ); + delete window._mapboxClickHandlers[message.layer_id]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if (message.layer && message.layer.id && window._mapboxClickHandlers[message.layer.id]) { + map.off( + "click", + message.layer_id, + window._mapboxClickHandlers[message.layer.id] + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer_id); + } + if (map.getSource(message.layer_id)) { + map.removeSource(message.layer_id); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer_id]; + delete layerState.paintProperties[message.layer_id]; + delete layerState.layoutProperties[message.layer_id]; + delete layerState.tooltips[message.layer_id]; + delete layerState.popups[message.layer_id]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty( + message.layer, + message.name, + message.value, + ); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find( + (layer) => layer.id === layerId, + ); + const currentPaintProperty = + map.getPaintProperty(layerId, propertyName); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + [ + "boolean", + ["feature-state", "hover"], + false, + ], + hoverValue, + newValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + // No hover options, just set the new value directly + map.setPaintProperty( + layerId, + propertyName, + newValue, + ); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "add_legend") { + if (!message.add) { + const existingLegends = + document.querySelectorAll( + `#${data.id} .maplibregl-legend`, + ); + existingLegends.forEach((legend) => + legend.remove(), + ); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll(`style[data-mapgl-legend-css="${data.id}"]`); + legendStyles.forEach((style) => style.remove()); + } + + const legendCss = + document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute('data-mapgl-legend-css', data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("maplibregl-legend"); + + // Append legend to the correct map container + const targetContainer = map.getContainer(); + targetContainer.appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Save the current view state + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log("[MapGL Debug] Current style sources:", Object.keys(currentStyle.sources)); + console.log("[MapGL Debug] Current style layers:", currentStyle.layers.map(l => l.id)); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function(layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log("[MapGL Debug] Found source from test layer:", layer.source); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + + // If the paint property has a hover case, it's user-added + (layer.paint && Object.values(layer.paint).some(value => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover")) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = layerSource && layerSource.type === "vector" && ( + layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler") + ); + + if (!isBaseMapSource) { + console.log("[MapGL Debug] Found user source from layer:", layer.source); + userSourceIds.push(layer.source); + } else { + console.log("[MapGL Debug] Not adding base map source from layer:", layer.source); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if (source.url && typeof source.url === 'string' && + (source.url.includes("data:application/json") || + source.url.includes("blob:"))) { + console.log("[MapGL Debug] Found user source with data URL:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !(sourceId.startsWith("maptiler") && !sourceId.includes("user")) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) // Filter basemap sources but keep user ones + ) { + console.log("[MapGL Debug] Found user source via filtering:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find(l => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function(layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = layerSource && layerSource.type === "vector" && ( + layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler") + ); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log("[MapGL Debug] Including user layer:", layer.id, "source:", layer.source); + } else if (isBaseMapSource) { + console.log("[MapGL Debug] Excluding base map layer:", layer.id, "source:", layer.source); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function() { + // Re-add user sources + userSourceIds.forEach(function(sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function(layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log("[MapGL Debug] Re-adding mousemove handler for:", layer.id); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log("[MapGL Debug] Re-adding mouseleave handler for:", layer.id); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log("[MapGL Debug] Restoring tooltip for:", layerId); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function(e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = e.features[0].properties[tooltipProperty]; + tooltip.setLngLat(e.lngLat).setHTML(description).addTo(map); + } + }; + + const mouseLeaveHandler = function() { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if (Array.isArray(value) && value[0] === "case" && + Array.isArray(value[1]) && value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && value[1][1][1] === "hover") { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log("[MapGL Debug] Restoring tracked layer modifications"); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log("[MapGL Debug] Restoring filter for layer:", layerId); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log("[MapGL Debug] Restoring paint property:", layerId, propertyName, savedValue); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty(layerId, propertyName); + if (currentValue && Array.isArray(currentValue) && currentValue[0] === "case") { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log("[MapGL Debug] Restoring layout property:", layerId, propertyName, properties[propertyName]); + map.setLayoutProperty(layerId, propertyName, properties[propertyName]); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log("[MapGL Debug] Restoring tooltip:", layerId, tooltipProperty); + + // Remove existing tooltip handlers first + map.off("mousemove", layerId); + map.off("mouseleave", layerId); + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on("mousemove", layerId, function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }); + + map.on("mouseleave", layerId, function () { + onMouseLeaveTooltip(map, tooltip); + }); + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log("[MapGL Debug] Restoring popup:", layerId, popupProperty); + + // Remove existing popup handlers first + if (window._maplibreClickHandlers && window._maplibreClickHandlers[layerId]) { + map.off("click", layerId, window._maplibreClickHandlers[layerId]); + delete window._maplibreClickHandlers[layerId]; + } + + const clickHandler = function(e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + if (!window._maplibreClickHandlers) { + window._maplibreClickHandlers = {}; + } + window._maplibreClickHandlers[layerId] = clickHandler; + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off('style.load', onStyleLoad); + }; + + map.on('style.load', onStyleLoad); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map(id => ({id, source: currentStyle.sources[id]})), + layers: userLayers + }; + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function() { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = window._mapglPreservedData && window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log("[MapGL Debug] Backup restoration needed for layers"); + + // Re-add sources first + preserved.sources.forEach(function(src) { + try { + if (!map.getSource(src.id)) { + console.log("[MapGL Debug] Backup: adding source", src.id); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error("[MapGL Debug] Backup: error adding source", src.id, err); + } + }); + + // Then re-add layers + preserved.layers.forEach(function(layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Backup: adding layer", layer.id); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log("[MapGL Debug] Backup: restoring tooltip for", layer.id); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function(e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = e.features[0].properties[tooltipProperty]; + tooltip.setLngLat(e.lngLat).setHTML(description).addTo(map); + } + }; + + const mouseLeaveHandler = function() { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if (Array.isArray(value) && value[0] === "case" && + Array.isArray(value[1]) && value[1][0] === "boolean" && + value[1][1] && Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && value[1][1][1] === "hover") { + // This is a hover-enabled paint property + console.log("[MapGL Debug] Backup: restoring hover style for", layer.id, key); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Backup: error adding layer", layer.id, err); + } + }); + } else { + console.log("[MapGL Debug] Backup check: layers already restored properly"); + } + } + } catch (err) { + console.error("[MapGL Debug] Error in backup restoration:", err); + } + }, 500); // 500ms delay - faster recovery + } + } + + // Apply the new style + map.setStyle(message.style, { + diff: message.diff, + }); + + if (message.config) { + Object.keys(message.config).forEach( + function (key) { + map.setConfigProperty( + "basemap", + key, + message.config[key], + ); + }, + ); + } + + // Restore the view state after the style has loaded + map.once("style.load", function () { + map.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + + // Re-apply map modifications + if (map === beforeMap) { + applyMapModifications(map, x.map1); + } else { + applyMapModifications(map, x.map2); + } + }); + } else if ( + message.type === "add_navigation_control" + ) { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: + message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl.maplibregl-ctrl-group:not(.maplibre-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + map.controls.push({ type: "navigation", control: nav }); + } else if (message.type === "add_reset_control") { + const resetControl = + document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute( + "aria-label", + "Reset", + ); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = + "background-color 0.2s"; + resetControl.addEventListener( + "mouseover", + function () { + this.style.backgroundColor = "#f0f0f0"; + }, + ); + resetControl.addEventListener( + "mouseout", + function () { + this.style.backgroundColor = "white"; + }, + ); + + const resetContainer = + document.createElement("div"); + resetContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild( + resetContainer, + ); + }, + }, + message.position, + ); + // Add to controls array + map.controls.push(resetControl); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + if (message.freehand) { + drawOptions = Object.assign( + {}, + drawOptions, + { + modes: Object.assign( + {}, + MapboxDraw.modes, + { + draw_polygon: + MapboxDraw.modes + .draw_freehand, + }, + ), + }, + ); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on( + "draw.create", + window.updateDrawnFeatures, + ); + map.on( + "draw.delete", + window.updateDrawnFeatures, + ); + map.on( + "draw.update", + window.updateDrawnFeatures, + ); + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group", + ); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + } else if (message.type === "get_drawn_features") { + if (draw) { + const features = draw + ? draw.getAll() + : null; + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if ( + message.type === "clear_drawn_features" + ) { + if (draw) { + draw.deleteAll(); + // Update the drawn features + window.updateDrawnFeatures(); + } + } else if (message.type === "add_markers") { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: + marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker( + markerOptions, + ) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue( + data.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + + mapMarker.on("dragend", function () { + const lngLat = + mapMarker.getLngLat(); + Shiny.setInputValue( + data.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + }); + } + + window.maplibreglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreglMarkers) { + window.maplibreglMarkers.forEach( + function (marker) { + marker.remove(); + }, + ); + window.maplibreglMarkers = []; + } + } else if ( + message.type === "add_fullscreen_control" + ) { + const position = + message.position || "top-right"; + const fullscreen = + new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = + new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl( + scaleControl, + message.options.position, + ); + map.controls.push(scaleControl); + } else if ( + message.type === "add_geolocate_control" + ) { + const geolocate = + new maplibregl.GeolocateControl({ + positionOptions: + message.options.positionOptions, + trackUserLocation: + message.options.trackUserLocation, + showAccuracyCircle: + message.options.showAccuracyCircle, + showUserLocation: + message.options.showUserLocation, + showUserHeading: + message.options.showUserHeading, + fitBoundsOptions: + message.options.fitBoundsOptions, + }); + map.addControl( + geolocate, + message.options.position, + ); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue( + data.id + "_geolocate", + { + coords: event.coords, + time: new Date(), + }, + ); + }); + + geolocate.on( + "trackuserlocationstart", + function () { + Shiny.setInputValue( + data.id + "_geolocate_tracking", + { + status: "start", + time: new Date(), + }, + ); + }, + ); + + geolocate.on( + "trackuserlocationend", + function () { + Shiny.setInputValue( + data.id + "_geolocate_tracking", + { + status: "end", + time: new Date(), + }, + ); + }, + ); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue( + data.id + "_geolocate_error", + { + message: + "Location permission denied", + time: new Date(), + }, + ); + } + }); + } + } else if ( + message.type === "add_geocoder_control" + ) { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = + await fetch(request); + const geojson = + await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - + feature.bbox[0]) / + 2, + feature.bbox[1] + + (feature.bbox[3] - + feature.bbox[1]) / + 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: + feature.properties + .display_name, + properties: + feature.properties, + text: feature.properties + .display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error( + `Failed to forwardGeocode with error: ${e}`, + ); + } + + return { + features, + }; + }, + }; + + const geocoderOptions = { + maplibregl: maplibregl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if ( + typeof geocoderOptions.collapsed === + "undefined" + ) + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder( + geocoderApi, + geocoderOptions, + ); + } + + map.addControl( + geocoder, + message.options.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } else if (message.type === "add_layers_control") { + const layersControl = + document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = + document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `.layers-control { background-color: ${colors.background} !important; }`; + } + if (colors.text) { + css += `.layers-control a { color: ${colors.text} !important; }`; + } + if (colors.activeBackground) { + css += `.layers-control a.active { background-color: ${colors.activeBackground} !important; }`; + } + if (colors.activeText) { + css += `.layers-control a.active { color: ${colors.activeText} !important; }`; + } + if (colors.hoverBackground) { + css += `.layers-control a:hover { background-color: ${colors.hoverBackground} !important; }`; + } + if (colors.hoverText) { + css += `.layers-control a:hover { color: ${colors.hoverText} !important; }`; + } + if (colors.toggleButtonBackground) { + css += `.layers-control .toggle-button { background-color: ${colors.toggleButtonBackground} + !important; }`; + } + if (colors.toggleButtonText) { + css += `.layers-control .toggle-button { color: ${colors.toggleButtonText} !important; }`; + } + + styleEl.innerHTML = css; + document.head.appendChild(styleEl); + } + + document + .getElementById(data.id) + .appendChild(layersControl); + + const layersList = + document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + message.layers || + map + .getStyle() + .layers.map((layer) => layer.id); + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = + map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty( + clickedLayer, + "visibility", + "none", + ); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (message.collapsible) { + const toggleButton = + document.createElement("div"); + toggleButton.className = "toggle-button"; + toggleButton.textContent = "Layers"; + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore( + toggleButton, + layersList, + ); + } + } else if (message.type === "add_globe_minimap") { + // Add the globe minimap control if supported + if (typeof MapboxGlobeMinimap !== "undefined") { + const minimap = new MapboxGlobeMinimap({ + center: map.getCenter(), + zoom: map.getZoom(), + bearing: map.getBearing(), + pitch: map.getPitch(), + globeSize: message.globe_size, + landColor: message.land_color, + waterColor: message.water_color, + markerColor: message.marker_color, + markerSize: message.marker_size, + }); + + map.addControl(minimap, message.position); + } else { + console.warn( + "MapboxGlobeMinimap is not defined", + ); + } + } else if (message.type === "add_globe_control") { + // Add the globe control + const globeControl = + new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign( + {}, + drawOptions, + { + modes: Object.assign( + {}, + MapboxDraw.modes, + { + draw_polygon: + MapboxDraw.modes + .draw_freehand, + }, + ), + // defaultMode: 'draw_polygon' # Don't set the default yet + }, + ); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: '#fbb03b', + point_color: '#3bb2d0', + line_color: '#3bb2d0', + fill_color: '#3bb2d0', + fill_opacity: 0.1, + line_width: 2 + }); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(draw, message.source, map); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + if (draw) { + const features = draw + ? draw.getAll() + : null; + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if ( + message.type === "clear_drawn_features" + ) { + if (draw) { + draw.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + if (draw) { + if (message.data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn('Draw control not initialized'); + } + } else if (message.type === "set_projection") { + // Only if maplibre supports projection + if (typeof map.setProjection === "function") { + map.setProjection(message.projection); + } + } else if (message.type === "set_source") { + if (map.getLayer(message.layer)) { + const sourceId = map.getLayer( + message.layer, + ).source; + map.getSource(sourceId).setData( + JSON.parse(message.source), + ); + } + } else if (message.type === "set_tooltip") { + // Track tooltip state + layerState.tooltips[message.layer] = message.tooltip; + + if (map.getLayer(message.layer)) { + // Remove any existing tooltip handlers + map.off("mousemove", message.layer); + map.off("mouseleave", message.layer); + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on( + "mousemove", + message.layer, + function (e) { + map.getCanvas().style.cursor = + "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[ + message.tooltip + ]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }, + ); + + map.on( + "mouseleave", + message.layer, + function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }, + ); + } + } else if (message.type === "set_popup") { + // Track popup state + layerState.popups[message.layer] = message.popup; + + if (map.getLayer(message.layer)) { + // Remove any existing popup click handlers for this layer + if (window._maplibreClickHandlers && window._maplibreClickHandlers[message.layer]) { + map.off("click", message.layer, window._maplibreClickHandlers[message.layer]); + delete window._maplibreClickHandlers[message.layer]; + } + + // Remove any existing popup for this layer + if (window._maplibrePopups && window._maplibrePopups[message.layer]) { + window._maplibrePopups[message.layer].remove(); + delete window._maplibrePopups[message.layer]; + } + + // Create new click handler for popup + const clickHandler = function (e) { + onClickPopup(e, map, message.popup, message.layer); + }; + + // Store handler reference + if (!window._maplibreClickHandlers) { + window._maplibreClickHandlers = {}; + } + window._maplibreClickHandlers[message.layer] = clickHandler; + + // Add click handler + map.on("click", message.layer, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer, function () { + map.getCanvas().style.cursor = ""; + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer( + message.layer, + message.before, + ); + } else { + map.moveLayer(message.layer); + } + } + } else if (message.type === "set_opacity") { + // Set opacity for all fill layers + const style = map.getStyle(); + if (style && style.layers) { + style.layers.forEach(function (layer) { + if ( + layer.type === "fill" && + map.getLayer(layer.id) + ) { + map.setPaintProperty( + layer.id, + "fill-opacity", + message.opacity, + ); + } + }); + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection) + ); + } else if (message.type === "clear_controls") { + // Handle clear_controls for compare widgets + if (!message.controls || message.controls.length === 0) { + // Clear all controls + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + } + } + }, + ); + } + + function setupShinyEvents(map, parentId, mapType) { + // Set view state on move end + map.on("moveend", function () { + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_view", + { + center: [center.lng, center.lat], + zoom: zoom, + bearing: bearing, + pitch: pitch, + }, + ); + } + }); + + // Send clicked point coordinates to Shiny + map.on("click", function (e) { + // Check if this map's draw control is active and in a drawing mode + let isDrawing = false; + if (map._mapgl_draw && map._mapgl_draw.getMode) { + const mode = map._mapgl_draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + console.log(`[${mapType}] Draw mode: ${mode}, isDrawing: ${isDrawing}`); + } else { + console.log(`[${mapType}] No draw control found`); + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + // Filter out draw layers + const nonDrawFeatures = features.filter(feature => + !feature.layer.id.includes('gl-draw') && + !feature.source.includes('gl-draw') + ); + console.log(`[${mapType}] Features found: ${features.length}, non-draw: ${nonDrawFeatures.length}`); + + if (nonDrawFeatures.length > 0) { + const feature = nonDrawFeatures[0]; + console.log(`[${mapType}] Feature click detected, layer: ${feature.layer.id}`); + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_click", + { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }, + ); + } + } else { + console.log(`[${mapType}] No non-draw features found at click point`); + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_click", + null + ); + } + } + } else { + console.log(`[${mapType}] Feature click suppressed - currently drawing`); + } + + // Always send regular click event + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_click", + { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }, + ); + } + }); + + // Add hover events if enabled for this map + const mapConfig = (mapType === "before") ? x.map1 : x.map2; + if (mapConfig.hover_events && mapConfig.hover_events.enabled) { + map.on("mousemove", function (e) { + if (window.Shiny) { + // Feature hover events + if (mapConfig.hover_events.features) { + const options = mapConfig.hover_events.layer_id + ? { layers: Array.isArray(mapConfig.hover_events.layer_id) + ? mapConfig.hover_events.layer_id + : mapConfig.hover_events.layer_id.split(',').map(id => id.trim()) } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if(features.length > 0) { + const feature = features[0]; + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } else { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + null + ); + } + } + + // Coordinate hover events + if (mapConfig.hover_events.coordinates) { + Shiny.setInputValue( + parentId + "_" + mapType + "_hover", + { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } + } + }); + } + } + + function applyMapModifications(map, mapData) { + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + // Define the tooltip handler functions to match the ones in maplibregl.js + function onMouseMoveTooltip( + e, + map, + tooltipPopup, + tooltipProperty, + ) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(tooltipProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } + } + + function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } + + function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case 'get': + return properties[expression[1]]; + case 'concat': + return expression.slice(1).map(item => evaluateExpression(item, properties)).join(''); + case 'to-string': + return String(evaluateExpression(expression[1], properties)); + case 'to-number': + return Number(evaluateExpression(expression[1], properties)); + default: + // For literals and other simple values + return expression; + } + } + + function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._maplibrePopups && window._maplibrePopups[layerId]) { + window._maplibrePopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._maplibrePopups) { + window._maplibrePopups = {}; + } + window._maplibrePopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on('close', function() { + if (window._maplibrePopups[layerId] === popup) { + delete window._maplibrePopups[layerId]; + } + }); + } + + // Set config properties if provided + if (mapData.config_properties) { + mapData.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + // Process H3J sources if provided + if (mapData.h3j_sources) { + mapData.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + }); + } + + if (mapData.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + mapData.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker( + markerOptions, + ) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setText(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + } + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + } + }); + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (mapData.sources) { + mapData.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceConfig = { + type: "vector", + url: source.url, + }; + if (source.promoteId) { + sourceConfig.promoteId = source.promoteId; + } + map.addSource(source.id, sourceConfig); + } else if (source.type === "geojson") { + map.addSource(source.id, { + type: "geojson", + data: source.data, + generateId: source.generateId !== false, + }); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + // Add layers if provided + if (mapData.layers) { + mapData.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = + layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + map.on("click", layer.id, function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = + "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + layer.tooltip, + ); + }; + + // Create a reference to the mouseleave handler function + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references + map.on( + "mousemove", + layer.id, + mouseMoveHandler, + ); + map.on( + "mouseleave", + layer.id, + mouseLeaveHandler, + ); + + // Store these handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === + "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = e.features[0].id; + map.setFeatureState( + { + source: + typeof layer.source === + "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: true }, + ); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === + "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach( + function (key) { + const originalPaint = + map.getPaintProperty( + layer.id, + key, + ) || layer.paint[key]; + map.setPaintProperty( + layer.id, + key, + [ + "case", + [ + "boolean", + [ + "feature-state", + "hover", + ], + false, + ], + jsHoverOptions[key], + originalPaint, + ], + ); + }, + ); + } + } catch (e) { + console.error( + "Failed to add layer: ", + layer, + e, + ); + } + }); + } + + // Set terrain if provided + if (mapData.terrain) { + map.setTerrain({ + source: mapData.terrain.source, + exaggeration: mapData.terrain.exaggeration, + }); + } + + // Set fog + if (mapData.fog) { + map.setFog(mapData.fog); + } + + if (mapData.fitBounds) { + map.fitBounds( + mapData.fitBounds.bounds, + mapData.fitBounds.options, + ); + } + if (mapData.flyTo) { + map.flyTo(mapData.flyTo); + } + if (mapData.easeTo) { + map.easeTo(mapData.easeTo); + } + if (mapData.setCenter) { + map.setCenter(mapData.setCenter); + } + if (mapData.setZoom) { + map.setZoom(mapData.setZoom); + } + + // Apply moveLayer operations if provided + if (mapData.moveLayer) { + mapData.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + if (mapData.jumpTo) { + map.jumpTo(mapData.jumpTo); + } + + // Add custom images if provided + if (mapData.images && Array.isArray(mapData.images)) { + mapData.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage( + imageInfo.url, + ); + if (!map.hasImage(imageInfo.id)) { + map.addImage( + imageInfo.id, + image.data, + imageInfo.options, + ); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (mapData.images) { + console.error( + "mapData.images is not an array:", + mapData.images, + ); + } + + // Remove existing legends only from this specific map container + const mapContainer = map.getContainer(); + const existingLegends = mapContainer.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + + if (mapData.legend_html && mapData.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = mapData.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = mapData.legend_html; + legend.classList.add("mapboxgl-legend"); + + // Append legend to the correct map container instead of main container + mapContainer.appendChild(legend); + } + + // Add fullscreen control if enabled + if ( + mapData.fullscreen_control && + mapData.fullscreen_control.enabled + ) { + const position = + mapData.fullscreen_control.position || "top-right"; + map.addControl( + new maplibregl.FullscreenControl(), + position, + ); + } + + // Helper function to generate draw styles based on parameters + function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + 'id': 'gl-draw-point-active', + 'type': 'circle', + 'filter': ['all', + ['==', '$type', 'Point'], + ['==', 'meta', 'feature'], + ['==', 'active', 'true']], + 'paint': { + 'circle-radius': styling.vertex_radius + 2, + 'circle-color': styling.active_color + } + }, + { + 'id': 'gl-draw-point', + 'type': 'circle', + 'filter': ['all', + ['==', '$type', 'Point'], + ['==', 'meta', 'feature'], + ['==', 'active', 'false']], + 'paint': { + 'circle-radius': styling.vertex_radius, + 'circle-color': styling.point_color + } + }, + // Line styles + { + 'id': 'gl-draw-line', + 'type': 'line', + 'filter': ['all', ['==', '$type', 'LineString']], + 'layout': { + 'line-cap': 'round', + 'line-join': 'round' + }, + 'paint': { + 'line-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.line_color + ], + 'line-width': styling.line_width + } + }, + // Polygon fill + { + 'id': 'gl-draw-polygon-fill', + 'type': 'fill', + 'filter': ['all', ['==', '$type', 'Polygon']], + 'paint': { + 'fill-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.fill_color + ], + 'fill-outline-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.fill_color + ], + 'fill-opacity': styling.fill_opacity + } + }, + // Polygon outline + { + 'id': 'gl-draw-polygon-stroke', + 'type': 'line', + 'filter': ['all', ['==', '$type', 'Polygon']], + 'layout': { + 'line-cap': 'round', + 'line-join': 'round' + }, + 'paint': { + 'line-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.line_color + ], + 'line-width': styling.line_width + } + }, + // Midpoints + { + 'id': 'gl-draw-polygon-midpoint', + 'type': 'circle', + 'filter': ['all', + ['==', '$type', 'Point'], + ['==', 'meta', 'midpoint']], + 'paint': { + 'circle-radius': 3, + 'circle-color': styling.active_color + } + }, + // Vertex point halos + { + 'id': 'gl-draw-vertex-halo-active', + 'type': 'circle', + 'filter': ['all', + ['==', 'meta', 'vertex'], + ['==', '$type', 'Point']], + 'paint': { + 'circle-radius': ['case', + ['==', ['get', 'active'], 'true'], styling.vertex_radius + 4, + styling.vertex_radius + 2 + ], + 'circle-color': '#FFF' + } + }, + // Vertex points + { + 'id': 'gl-draw-vertex-active', + 'type': 'circle', + 'filter': ['all', + ['==', 'meta', 'vertex'], + ['==', '$type', 'Point']], + 'paint': { + 'circle-radius': ['case', + ['==', ['get', 'active'], 'true'], styling.vertex_radius + 2, + styling.vertex_radius + ], + 'circle-color': styling.active_color + } + } + ]; + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn('Source not found or has no data:', sourceId); + } + } + + if (mapData.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: mapData.scale_control.maxWidth, + unit: mapData.scale_control.unit, + }); + map.addControl( + scaleControl, + mapData.scale_control.position, + ); + map.controls.push(scaleControl); + } + + // Add navigation control if enabled + if (mapData.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: + mapData.navigation_control.show_compass, + showZoom: mapData.navigation_control.show_zoom, + visualizePitch: + mapData.navigation_control.visualize_pitch, + }); + map.addControl( + nav, + mapData.navigation_control.position, + ); + map.controls.push({ type: "navigation", control: nav }); + } + + // Add geolocate control if enabled + if (mapData.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: + mapData.geolocate_control.positionOptions, + trackUserLocation: + mapData.geolocate_control.trackUserLocation, + showAccuracyCircle: + mapData.geolocate_control.showAccuracyCircle, + showUserLocation: + mapData.geolocate_control.showUserLocation, + showUserHeading: + mapData.geolocate_control.showUserHeading, + fitBoundsOptions: + mapData.geolocate_control.fitBoundsOptions, + }); + map.addControl( + geolocate, + mapData.geolocate_control.position, + ); + + map.controls.push(geolocate); + } + + // Add globe control if enabled + if (mapData.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl( + globeControl, + mapData.globe_control.position, + ); + map.controls.push(globeControl); + } + + // Add draw control if enabled + if (mapData.draw_control && mapData.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = mapData.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (mapData.draw_control.styling) { + const generatedStyles = generateDrawStyles(mapData.draw_control.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (mapData.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + mapData.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (mapData.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (mapData.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: '#fbb03b', + point_color: '#3bb2d0', + line_color: '#3bb2d0', + fill_color: '#3bb2d0', + fill_opacity: 0.1, + line_width: 2 + }); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, mapData.draw_control.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add custom mode buttons and styling + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + + // Add rectangle styling and button + if (mapData.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + drawControl.changeMode('draw_rectangle'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + } + + // Add radius styling and button + if (mapData.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + drawControl.changeMode('draw_radius'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + } + }, 100); + + // Add initial features if provided + if (mapData.draw_control.source) { + addSourceFeaturesToDraw(drawControl, mapData.draw_control.source, map); + } + + // Process any queued features + if (mapData.draw_features_queue) { + mapData.draw_features_queue.forEach(function(data) { + if (data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, data.source, map); + }); + } + + // Apply orientation styling + if (mapData.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (mapData.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${mapData.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + + // Helper function for updating drawn features + function updateDrawnFeatures() { + if (HTMLWidgets.shinyMode && draw) { + const features = draw.getAll(); + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(features), + ); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + } + + if (mapData.geolocate_control && HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue( + el.id + "_geolocate_error", + { + message: "Location permission denied", + time: new Date(), + }, + ); + } + }); + } + + // Add geocoder control if enabled + if (mapData.geocoder_control) { + const provider = mapData.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: mapData.geocoder_control.api_key, + maplibregl: maplibregl, + ...mapData.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - + feature.bbox[0]) / + 2, + feature.bbox[1] + + (feature.bbox[3] - + feature.bbox[1]) / + 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: + feature.properties.display_name, + properties: feature.properties, + text: feature.properties + .display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error( + `Failed to forwardGeocode with error: ${e}`, + ); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...mapData.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder( + geocoderApi, + geocoderOptions, + ); + } + + map.addControl( + geocoder, + mapData.geocoder_control.position || "top-right", + ); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + // Add reset control if enabled + if (mapData.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: mapData.reset_control.animate, + }; + + if (mapData.reset_control.duration) { + initialView.duration = + mapData.reset_control.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild( + resetContainer, + ); + }, + }, + mapData.reset_control.position, + ); + } + + + function updateDrawnFeatures() { + if (map._mapgl_draw) { + var drawnFeatures = map._mapgl_draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + // Add the layers control if provided + if (mapData.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = mapData.layers_control.control_id; + + // Handle use_icon parameter + let className = mapData.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + + layersControl.className = className; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = + mapData.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + mapData.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = mapData.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty( + clickedLayer, + "visibility", + "none", + ); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (mapData.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + if (mapData.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore( + toggleButton, + layersList, + ); + } + } + + // Set projection if provided (after all other setup is complete) + if (mapData.setProjection && mapData.setProjection.length > 0) { + mapData.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection in compare view:", e); + } + } + }); + } + } + }, + + resize: function (width, height) { + // Code to handle resizing if necessary + }, + }; + }, +}); diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl_compare.yaml b/docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl_compare.yaml new file mode 100644 index 0000000..a72887c --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/maplibregl_compare.yaml @@ -0,0 +1,67 @@ +dependencies: + - name: maplibre-gl + version: "5.7.2" + src: "htmlwidgets/lib/maplibre-gl" + script: + - "maplibre-gl.js" + stylesheet: + - "maplibre-gl.css" + - name: maplibre-gl-compare + version: "0.5" + src: "htmlwidgets/lib/maplibre-gl-compare" + script: + - "maplibre-gl-compare.js" + stylesheet: + - "maplibre-gl-compare.css" + - name: mapbox-gl-draw + version: "1.5.0" + src: "htmlwidgets/lib/mapbox-gl-draw" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: maplibre-gl-geocoder + version: 1.5.0 + src: "htmlwidgets/lib/maplibre-gl-geocoder" + script: + - "maplibre-gl-geocoder.min.js" + stylesheet: + - "maplibre-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: h3j-h3t + version: 0.9.2 + src: "htmlwidgets/lib/h3j-h3t" + script: + - "h3j_h3t.js" + - name: maptiler-geocoding-control + version: 2.1.7 + src: + href: "https://cdn.maptiler.com/maptiler-geocoding-control/v2.1.7/" + script: + - "maplibregl.umd.js" + stylesheet: + - "style.css" diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/styles/filter-control.css b/docs/articles/getting-started_files/turf-operations-1.0.0/styles/filter-control.css new file mode 100644 index 0000000..e6096c3 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/styles/filter-control.css @@ -0,0 +1,65 @@ +.filter-control { + background: #fff; + position: absolute; + z-index: 1; + border-radius: 3px; + width: 200px; + border: 1px solid rgba(0, 0, 0, 0.4); + font-family: 'Open Sans', sans-serif; + margin: 10px; + padding: 10px; +} + +.filter-control .filter-title { + font-weight: bold; + margin-bottom: 10px; + text-align: center; +} + +.filter-control input[type="range"] { + width: 100%; + margin: 10px 0; +} + +.filter-control .range-value { + text-align: center; + margin-top: 5px; +} + +.filter-control .checkbox-group { + display: flex; + flex-direction: column; + gap: 5px; +} + +.filter-control .checkbox-group label { + display: flex; + align-items: center; + gap: 5px; +} + +.filter-control .toggle-button { + background: darkgrey; + color: #ffffff; + text-align: center; + cursor: pointer; + padding: 5px 0; + border-radius: 3px 3px 0 0; + margin: -10px -10px 10px -10px; +} + +.filter-control .toggle-button:hover { + background: grey; +} + +.filter-control .filter-content { + display: block; +} + +.filter-control.collapsible .filter-content { + display: none; +} + +.filter-control.collapsible.open .filter-content { + display: block; +} \ No newline at end of file diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/styles/layers-control.css b/docs/articles/getting-started_files/turf-operations-1.0.0/styles/layers-control.css new file mode 100644 index 0000000..8551228 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/styles/layers-control.css @@ -0,0 +1,123 @@ +.layers-control { + background: #fff; + position: absolute; + z-index: 1; + border-radius: 4px; + width: 120px; + border: 1px solid rgba(0, 0, 0, 0.15); + font-family: "Open Sans", sans-serif; + margin: 0px; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15); + overflow: hidden; + transition: all 0.2s ease-in-out; +} + +.layers-control a { + font-size: 13px; + color: #404040; + display: block; + margin: 0; + padding: 10px; + text-decoration: none; + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + text-align: center; + transition: all 0.15s ease-in-out; + font-weight: normal; +} + +.layers-control a:last-child { + border: none; +} + +.layers-control a:hover { + background-color: #f8f8f8; + color: #1a1a1a; +} + +.layers-control a.active { + background-color: #4a90e2; + color: #ffffff; + font-weight: 500; +} + +.layers-control a.active:hover { + background: #3b7ed2; +} + +.layers-control .toggle-button { + display: none; + background: #4a90e2; + color: #ffffff; + text-align: center; + cursor: pointer; + padding: 8px 0; + border-radius: 4px 4px 0 0; + font-weight: 500; + letter-spacing: 0.3px; + box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.05) inset; + transition: all 0.15s ease-in-out; +} + +.layers-control .toggle-button:hover { + background: #3b7ed2; +} + +.layers-control .layers-list { + display: block; +} + +.layers-control.collapsible .toggle-button { + display: block; + border-bottom: 1px solid rgba(0, 0, 0, 0.25); +} + +.layers-control.collapsible .layers-list { + display: none; + opacity: 0; + max-height: 0; + transition: + opacity 0.25s ease, + max-height 0.25s ease; +} + +.layers-control.collapsible.open .layers-list { + display: block; + opacity: 1; + max-height: 500px; /* Large enough value to accommodate all content */ +} + +/* Compact icon styling */ +.layers-control.collapsible.icon-only { + width: auto; + min-width: 36px; + border-radius: 4px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); + transform: translateZ( + 0 + ); /* Force hardware acceleration for smoother animations */ +} + +.layers-control.collapsible.icon-only .toggle-button { + border-radius: 4px; + padding: 8px; + width: 36px; + height: 36px; + box-sizing: border-box; + margin: 0; + border-bottom: none; + display: flex; + align-items: center; + justify-content: center; + box-shadow: none; +} + +.layers-control.collapsible.icon-only.open { + width: 120px; + box-shadow: 0 3px 10px rgba(0, 0, 0, 0.25); +} + +.layers-control.collapsible.icon-only.open .toggle-button { + border-radius: 4px 4px 0 0; + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + width: 100%; +} diff --git a/docs/articles/getting-started_files/turf-operations-1.0.0/turf-operations.js b/docs/articles/getting-started_files/turf-operations-1.0.0/turf-operations.js new file mode 100644 index 0000000..2b4e514 --- /dev/null +++ b/docs/articles/getting-started_files/turf-operations-1.0.0/turf-operations.js @@ -0,0 +1,967 @@ +// Turf.js operations module for mapgl +// Shared operations that work with both mapboxgl and maplibre maps + +// Process turf operations on map initialization (for static maps) +function processTurfOperationsOnLoad(map, turfOperations, widgetId) { + if (!turfOperations || turfOperations.length === 0) return; + + // Wait for map to be fully loaded, then execute operations + map.on('load', function() { + // Add a small delay to ensure all layers are loaded + setTimeout(function() { + turfOperations.forEach(function(operation) { + try { + handleTurfOperation(map, operation, widgetId); + } catch (error) { + console.error(`Error processing turf operation ${operation.type}:`, error); + } + }); + }, 100); + }); +} + +// Main handler for all turf operations +function handleTurfOperation(map, message, widgetId) { + try { + switch (message.type) { + case "turf_buffer": + executeTurfBuffer(map, message, widgetId); + break; + case "turf_union": + executeTurfUnion(map, message, widgetId); + break; + case "turf_intersect": + executeTurfIntersect(map, message, widgetId); + break; + case "turf_difference": + executeTurfDifference(map, message, widgetId); + break; + case "turf_convex_hull": + executeTurfConvexHull(map, message, widgetId); + break; + case "turf_concave_hull": + executeTurfConcaveHull(map, message, widgetId); + break; + case "turf_voronoi": + executeTurfVoronoi(map, message, widgetId); + break; + case "turf_distance": + executeTurfDistance(map, message, widgetId); + break; + case "turf_area": + executeTurfArea(map, message, widgetId); + break; + case "turf_centroid": + executeTurfCentroid(map, message, widgetId); + break; + case "turf_center_of_mass": + executeTurfCenterOfMass(map, message, widgetId); + break; + case "turf_filter": + executeTurfFilter(map, message, widgetId); + break; + default: + console.warn(`Unknown turf operation: ${message.type}`); + } + } catch (error) { + console.error(`Error executing turf operation ${message.type}:`, error); + if (HTMLWidgets.shinyMode && message.send_to_r) { + Shiny.setInputValue(widgetId + "_turf_error", { + operation: message.type, + error: error.message, + timestamp: Date.now() + }); + } + } +} + +// Helper function to get input data for turf operations +function getInputData(map, message) { + // If coordinates provided, create point or points client-side + if (message.coordinates) { + // Handle single coordinate pair + if (typeof message.coordinates[0] === 'number') { + return turf.point(message.coordinates); + } + // Handle multiple coordinate pairs + if (Array.isArray(message.coordinates[0])) { + const points = message.coordinates.map(coord => turf.point(coord)); + return { + type: "FeatureCollection", + features: points + }; + } + } + + // If GeoJSON data provided directly + if (message.data) { + // Check if data is already an object (shouldn't happen) or string + if (typeof message.data === 'string') { + return JSON.parse(message.data); + } else { + // If it's already an object, return as-is + return message.data; + } + } + + // If layer_id provided, get from existing layer + if (message.layer_id) { + return getSourceData(map, message.layer_id); + } + + throw new Error("No valid input data provided (coordinates, data, or layer_id)"); +} + +// Helper function to get source data from a layer +function getSourceData(map, layerId) { + // First try to get from existing source + const source = map.getSource(layerId); + if (source) { + // Check for _data property (GeoJSON sources) + if (source._data) { + return source._data; + } + // Check for data property + if (source.data) { + return source.data; + } + } + + // Try with _source suffix (common pattern in mapgl) + const sourceWithSuffix = map.getSource(layerId + "_source"); + if (sourceWithSuffix) { + if (sourceWithSuffix._data) { + return sourceWithSuffix._data; + } + if (sourceWithSuffix.data) { + return sourceWithSuffix.data; + } + } + + // Query rendered features as fallback + try { + const features = map.queryRenderedFeatures({ layers: [layerId] }); + if (features.length > 0) { + return { + type: "FeatureCollection", + features: features + }; + } + } catch (e) { + // Layer might not exist, continue to error + } + + throw new Error(`Could not find source data for layer: ${layerId}`); +} + +// Helper function to add result source to map +function addResultSource(map, result, sourceId) { + if (!sourceId) return; + + // Ensure result is valid GeoJSON + if (!result) { + result = { + type: "FeatureCollection", + features: [] + }; + } + + // Check if source exists, update data or create new + const existingSource = map.getSource(sourceId); + if (existingSource) { + // Update existing source data + existingSource.setData(result); + } else { + // Add new source with result data + map.addSource(sourceId, { + type: "geojson", + data: result, + generateId: true + }); + } +} + +// Helper function to send result to R via Shiny input +function sendResultToR(widgetId, operation, result, metadata = {}, inputId = null) { + if (HTMLWidgets.shinyMode && inputId) { + Shiny.setInputValue(widgetId + "_turf_" + inputId, { + operation: operation, + result: result, + metadata: metadata, + timestamp: Date.now() + }); + } +} + +// Buffer operation +function executeTurfBuffer(map, message, widgetId) { + const inputData = getInputData(map, message); + + const buffered = turf.buffer(inputData, message.radius, { + units: message.units || "meters" + }); + + if (message.source_id) { + addResultSource(map, buffered, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "buffer", buffered, { + radius: message.radius, + units: message.units || "meters" + }, message.input_id); + } +} + +// Union operation +function executeTurfUnion(map, message, widgetId) { + const inputData = getInputData(map, message); + + let result; + if (inputData.type === "FeatureCollection" && inputData.features.length > 1) { + // Use turf.union with properly formatted FeatureCollection + const union = turf.union(turf.featureCollection(inputData.features)); + + result = union ? { + type: "FeatureCollection", + features: [union] + } : { + type: "FeatureCollection", + features: [] + }; + } else if (inputData.type === "FeatureCollection" && inputData.features.length === 1) { + // Single feature, return as-is + result = { + type: "FeatureCollection", + features: [inputData.features[0]] + }; + } else { + // Single feature, return as-is in FeatureCollection + result = { + type: "FeatureCollection", + features: [inputData] + }; + } + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "union", result, {}, message.input_id); + } +} + +// Intersect operation +function executeTurfIntersect(map, message, widgetId) { + const sourceData1 = getInputData(map, message); + + // Get second geometry data + let sourceData2; + if (message.data_2) { + // Handle data_2 directly + if (typeof message.data_2 === 'string') { + sourceData2 = JSON.parse(message.data_2); + } else { + sourceData2 = message.data_2; + } + } else if (message.layer_id_2) { + // Handle layer_id_2 as before + sourceData2 = getSourceData(map, message.layer_id_2); + } else { + throw new Error("Either data_2 or layer_id_2 must be provided for intersect operation"); + } + + // Extract features arrays + const features1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features : [sourceData1]; + const features2 = sourceData2.type === "FeatureCollection" ? + sourceData2.features : [sourceData2]; + + // Collect all intersection results + const resultFeatures = []; + + features1.forEach((feature1, index1) => { + if (!feature1 || !feature1.geometry) { + console.warn(`Skipping invalid feature at index ${index1}`); + return; + } + + features2.forEach((feature2, index2) => { + if (!feature2 || !feature2.geometry) { + return; + } + + // Use booleanIntersects for efficient filtering + if (turf.booleanIntersects(feature1, feature2)) { + try { + // Use turf.intersect with options to preserve properties + const intersection = turf.intersect( + turf.featureCollection([feature1, feature2]), + { properties: feature1.properties } + ); + + if (intersection) { + // Ensure properties are preserved (fallback if options didn't work) + if (!intersection.properties || Object.keys(intersection.properties).length === 0) { + intersection.properties = { ...feature1.properties }; + } + resultFeatures.push(intersection); + } + } catch (error) { + console.error(`Error intersecting features ${index1} and ${index2}:`, error); + } + } + }); + }); + + const result = { + type: "FeatureCollection", + features: resultFeatures + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "intersect", result, {}, message.input_id); + } +} + +// Difference operation +function executeTurfDifference(map, message, widgetId) { + const sourceData1 = getInputData(map, message); + + // Get second geometry data + let sourceData2; + if (message.data_2) { + // Handle data_2 directly + if (typeof message.data_2 === 'string') { + sourceData2 = JSON.parse(message.data_2); + } else { + sourceData2 = message.data_2; + } + } else if (message.layer_id_2) { + // Handle layer_id_2 as before + sourceData2 = getSourceData(map, message.layer_id_2); + } else { + throw new Error("Either data_2 or layer_id_2 must be provided for difference operation"); + } + + // Extract features arrays + const features1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features : [sourceData1]; + const features2 = sourceData2.type === "FeatureCollection" ? + sourceData2.features : [sourceData2]; + + // Process each feature in features1 + const resultFeatures = []; + + features1.forEach((feature1, index) => { + if (!feature1 || !feature1.geometry) { + console.warn(`Skipping invalid feature at index ${index}`); + return; + } + + // Start with the original feature + let currentFeature = feature1; + + // Apply difference with each feature from features2 + for (const feature2 of features2) { + if (!feature2 || !feature2.geometry || !currentFeature) { + continue; + } + + // Use booleanIntersects for efficient filtering + if (turf.booleanIntersects(currentFeature, feature2)) { + try { + const diff = turf.difference(turf.featureCollection([currentFeature, feature2])); + + if (diff) { + // Preserve properties from the original feature + diff.properties = { ...feature1.properties }; + currentFeature = diff; + } else { + // Feature was completely erased + currentFeature = null; + break; + } + } catch (error) { + console.error("Error in difference operation:", error); + // Keep the current feature unchanged on error + } + } + // If no intersection, currentFeature remains unchanged + } + + // Add the result if it still exists + if (currentFeature) { + resultFeatures.push(currentFeature); + } + }); + + const result = { + type: "FeatureCollection", + features: resultFeatures + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "difference", result, {}, message.input_id); + } +} + +// Convex hull operation +function executeTurfConvexHull(map, message, widgetId) { + const inputData = getInputData(map, message); + + // Ensure we have valid input data + if (!inputData) { + console.warn("No input data for convex hull"); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + // Check for minimum points if it's a FeatureCollection + if (inputData.type === "FeatureCollection" && inputData.features.length < 3) { + console.warn("Convex hull requires at least 3 points, got:", inputData.features.length); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + const hull = turf.convex(inputData); + + const result = hull ? { + type: "FeatureCollection", + features: [hull] + } : { + type: "FeatureCollection", + features: [] + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "convex_hull", result, {}, message.input_id); + } +} + +// Concave hull operation +function executeTurfConcaveHull(map, message, widgetId) { + const inputData = getInputData(map, message); + + // Ensure we have a FeatureCollection of Points for turf.concave + let pointCollection; + if (inputData.type === "FeatureCollection") { + // Filter to only Point geometries and ensure it's a proper FeatureCollection + const pointFeatures = inputData.features.filter(feature => + feature.geometry && feature.geometry.type === "Point" + ); + pointCollection = turf.featureCollection(pointFeatures); + } else if (inputData.type === "Feature" && inputData.geometry.type === "Point") { + // Single point - wrap in FeatureCollection + pointCollection = turf.featureCollection([inputData]); + } else { + console.warn("Concave hull requires Point geometries, received:", inputData); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + // Check if we have enough points (need at least 3 for a hull) + if (!pointCollection.features || pointCollection.features.length < 3) { + console.warn("Concave hull requires at least 3 points, got:", pointCollection.features?.length || 0); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + // Smart max_edge calculation with fallback + let hull = null; + let actualMaxEdge = message.max_edge; + + if (message.max_edge) { + // User specified max_edge, try it first + hull = turf.concave(pointCollection, { + maxEdge: message.max_edge, + units: message.units || "kilometers" + }); + } + + // If no hull or user didn't specify max_edge, try to find optimal value + if (!hull) { + // Calculate distances between all points to find reasonable max_edge + const distances = []; + const features = pointCollection.features; + + for (let i = 0; i < features.length; i++) { + for (let j = i + 1; j < features.length; j++) { + const dist = turf.distance(features[i], features[j], { + units: message.units || "kilometers" + }); + distances.push(dist); + } + } + + // Sort distances and try different percentiles as max_edge + distances.sort((a, b) => a - b); + const percentiles = [0.6, 0.7, 0.8, 0.9]; // Try 60th, 70th, 80th, 90th percentiles + + for (const percentile of percentiles) { + const index = Math.floor(distances.length * percentile); + const testMaxEdge = distances[index]; + + hull = turf.concave(pointCollection, { + maxEdge: testMaxEdge, + units: message.units || "kilometers" + }); + + if (hull) { + actualMaxEdge = testMaxEdge; + console.log(`Auto-calculated max_edge: ${testMaxEdge.toFixed(2)} ${message.units || "kilometers"}`); + break; + } + } + + // Final fallback - use convex hull if concave fails + if (!hull) { + console.warn("Concave hull failed, falling back to convex hull"); + hull = turf.convex(pointCollection); + actualMaxEdge = "convex_fallback"; + } + } + + const result = hull ? { + type: "FeatureCollection", + features: [hull] + } : { + type: "FeatureCollection", + features: [] + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "concave_hull", result, { + max_edge: message.max_edge, + units: message.units || "kilometers" + }, message.input_id); + } +} + +// Voronoi operation +function executeTurfVoronoi(map, message, widgetId) { + const inputData = getInputData(map, message); + + const options = {}; + let finalBbox = null; + let clippingData = null; + + // Handle bbox parameter + if (message.bbox) { + // Direct bbox array [minX, minY, maxX, maxY] + options.bbox = message.bbox; + finalBbox = message.bbox; + } else if (message.bbox_layer_id) { + // Extract bbox from layer + try { + const bboxSourceData = getSourceData(map, message.bbox_layer_id); + if (bboxSourceData) { + // Calculate bbox from layer data + const bbox = turf.bbox(bboxSourceData); + options.bbox = bbox; + finalBbox = bbox; + // Keep the layer data for potential intersection clipping + clippingData = bboxSourceData; + } + } catch (error) { + console.warn(`Could not extract bbox from layer ${message.bbox_layer_id}:`, error); + } + } + + let voronoi = turf.voronoi(inputData, options); + + // If we have clipping data (from bbox_layer_id), intersect each Voronoi polygon + if (voronoi && clippingData && clippingData.type === "FeatureCollection") { + const clippedFeatures = []; + + for (const voronoiFeature of voronoi.features) { + try { + // Try to intersect with each feature in the clipping layer + for (const clipFeature of clippingData.features) { + const intersection = turf.intersect(turf.featureCollection([voronoiFeature, clipFeature])); + if (intersection) { + clippedFeatures.push(intersection); + } + } + } catch (error) { + // If intersection fails, keep original feature + clippedFeatures.push(voronoiFeature); + } + } + + voronoi = { + type: "FeatureCollection", + features: clippedFeatures + }; + } + + // If property parameter is provided, use turf.collect to transfer attributes from points to polygons + if (voronoi && message.property && inputData.type === "FeatureCollection") { + try { + // Use turf.collect to gather point properties within each Voronoi polygon + const collected = turf.collect(voronoi, inputData, message.property, `${message.property}_collected`); + + // Since each Voronoi polygon should contain exactly one point, extract the single value from the array + for (const feature of collected.features) { + const collectedValues = feature.properties[`${message.property}_collected`]; + if (collectedValues && collectedValues.length > 0) { + // Take the first (and should be only) value and assign it directly to the property name + feature.properties[message.property] = collectedValues[0]; + // Remove the temporary array property + delete feature.properties[`${message.property}_collected`]; + } + } + + voronoi = collected; + } catch (error) { + console.warn(`Failed to collect property '${message.property}' from points to Voronoi polygons:`, error); + // Continue with uncollected voronoi if collection fails + } + } + + if (message.source_id && voronoi) { + addResultSource(map, voronoi, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "voronoi", voronoi, { + bbox: finalBbox, + bbox_layer_id: message.bbox_layer_id + }, message.input_id); + } +} + +// Distance operation +function executeTurfDistance(map, message, widgetId) { + let feature1, feature2; + + // Get first feature + if (message.coordinates) { + feature1 = turf.point(message.coordinates); + } else if (message.data) { + const sourceData1 = JSON.parse(message.data); + feature1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features[0] : sourceData1; + } else if (message.layer_id) { + const sourceData1 = getSourceData(map, message.layer_id); + feature1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features[0] : sourceData1; + } + + // Get second feature + if (message.coordinates_2) { + feature2 = turf.point(message.coordinates_2); + } else if (message.layer_id_2) { + const sourceData2 = getSourceData(map, message.layer_id_2); + feature2 = sourceData2.type === "FeatureCollection" ? + sourceData2.features[0] : sourceData2; + } + + const distance = turf.distance(feature1, feature2, { + units: message.units || "kilometers" + }); + + if (message.input_id) { + sendResultToR(widgetId, "distance", distance, { + units: message.units || "kilometers" + }, message.input_id); + } +} + +// Area operation +function executeTurfArea(map, message, widgetId) { + const inputData = getInputData(map, message); + + const area = turf.area(inputData); + + if (message.input_id) { + sendResultToR(widgetId, "area", area, { + units: "square_meters" + }, message.input_id); + } +} + +// Centroid operation (using turf.centroid - vertex average method) +function executeTurfCentroid(map, message, widgetId) { + const inputData = getInputData(map, message); + + const centroids = []; + + // Handle both single features and FeatureCollections + const features = inputData.type === "FeatureCollection" ? inputData.features : [inputData]; + + // Calculate centroid for each individual feature using turf.centroid + for (const feature of features) { + const centroid = turf.centroid(feature); + + // Preserve all properties from the source feature + if (feature.properties) { + centroid.properties = { ...feature.properties }; + } + + centroids.push(centroid); + } + + const result = { + type: "FeatureCollection", + features: centroids + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "centroid", result, {}, message.input_id); + } +} + +// Center of Mass operation (replaces centroid for better accuracy) +function executeTurfCenterOfMass(map, message, widgetId) { + const inputData = getInputData(map, message); + + const centers = []; + + // Handle both single features and FeatureCollections + const features = inputData.type === "FeatureCollection" ? inputData.features : [inputData]; + + // Calculate center of mass for each individual feature + for (const feature of features) { + const centerOfMass = turf.centerOfMass(feature, {}); + + // Preserve all properties from the source feature + if (feature.properties) { + centerOfMass.properties = { ...feature.properties }; + } + + centers.push(centerOfMass); + } + + const result = { + type: "FeatureCollection", + features: centers + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "center_of_mass", result, {}, message.input_id); + } +} + +// Filter operation +function executeTurfFilter(map, message, widgetId) { + const sourceData = getInputData(map, message); + + // Get filter geometry data + let filterData; + if (message.filter_data) { + // Handle filter_data directly + if (typeof message.filter_data === 'string') { + filterData = JSON.parse(message.filter_data); + } else { + filterData = message.filter_data; + } + } else if (message.filter_layer_id) { + // Handle filter_layer_id as before + filterData = getSourceData(map, message.filter_layer_id); + } else { + throw new Error("Either filter_data or filter_layer_id must be provided for filter operation"); + } + + // Extract features arrays + const features = sourceData.type === "FeatureCollection" ? + sourceData.features : [sourceData]; + const filterFeatures = filterData.type === "FeatureCollection" ? + filterData.features : [filterData]; + + // Collect filtered results + const resultFeatures = []; + + features.forEach((feature, index) => { + if (!feature || !feature.geometry) { + console.warn(`Skipping invalid feature at index ${index}`); + return; + } + + // Check if this feature matches the predicate against any filter feature + let matches = false; + + for (const filterFeature of filterFeatures) { + if (!filterFeature || !filterFeature.geometry) { + continue; + } + + try { + // Handle MultiPolygon geometries for within/contains predicates + if ((feature.geometry.type === 'MultiPolygon' || filterFeature.geometry.type === 'MultiPolygon') && + (message.predicate === 'within' || message.predicate === 'contains')) { + + // MultiPolygon handling for 'within' + if (message.predicate === 'within') { + if (feature.geometry.type === 'MultiPolygon') { + // All parts of the MultiPolygon must be within the filter + const polygons = feature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: feature.properties + })); + matches = polygons.every(poly => { + try { + return turf.booleanWithin(poly, filterFeature); + } catch (e) { + return false; + } + }); + } else if (filterFeature.geometry.type === 'MultiPolygon') { + // Feature must be within at least one part of the MultiPolygon + const polygons = filterFeature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: filterFeature.properties + })); + matches = polygons.some(poly => { + try { + return turf.booleanWithin(feature, poly); + } catch (e) { + return false; + } + }); + } + } + // MultiPolygon handling for 'contains' + else if (message.predicate === 'contains') { + if (feature.geometry.type === 'MultiPolygon') { + // At least one part of the MultiPolygon must contain the filter + const polygons = feature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: feature.properties + })); + matches = polygons.some(poly => { + try { + return turf.booleanContains(poly, filterFeature); + } catch (e) { + return false; + } + }); + } else if (filterFeature.geometry.type === 'MultiPolygon') { + // Feature must be contained by at least one part of the MultiPolygon + const polygons = filterFeature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: filterFeature.properties + })); + matches = polygons.some(poly => { + try { + return turf.booleanContains(poly, feature); + } catch (e) { + return false; + } + }); + } + } + } else { + // Use the appropriate boolean function based on predicate + switch (message.predicate) { + case "intersects": + matches = turf.booleanIntersects(feature, filterFeature); + break; + case "within": + matches = turf.booleanWithin(feature, filterFeature); + break; + case "contains": + matches = turf.booleanContains(feature, filterFeature); + break; + case "crosses": + matches = turf.booleanCrosses(feature, filterFeature); + break; + case "disjoint": + matches = turf.booleanDisjoint(feature, filterFeature); + break; + default: + console.warn(`Unknown predicate: ${message.predicate}`); + continue; + } + } + + if (matches) { + break; // Found a match, no need to check other filter features + } + } catch (error) { + console.error(`Error testing predicate ${message.predicate}:`, error); + continue; + } + } + + // If this feature matches the predicate, add it to results + if (matches) { + // Preserve all properties from the original feature + const resultFeature = { + ...feature, + properties: { ...feature.properties } + }; + resultFeatures.push(resultFeature); + } + }); + + const result = { + type: "FeatureCollection", + features: resultFeatures + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "filter", result, { + predicate: message.predicate, + filtered_count: resultFeatures.length, + total_count: features.length + }, message.input_id); + } +} \ No newline at end of file diff --git a/docs/articles/layers-overview_files/mapbox-pmtiles-1.1.0/pmtiles-source-optimized-v2.js b/docs/articles/layers-overview_files/mapbox-pmtiles-1.1.0/pmtiles-source-optimized-v2.js new file mode 100644 index 0000000..207d876 --- /dev/null +++ b/docs/articles/layers-overview_files/mapbox-pmtiles-1.1.0/pmtiles-source-optimized-v2.js @@ -0,0 +1,1102 @@ +/** + * mapbox-pmtiles v1.1.0 - Optimized Version with Lifecycle Management + * Original source: https://github.com/am2222/mapbox-pmtiles by Majid Hojati + * License: MIT + * + * This is an optimized version of the mapbox-pmtiles library that provides + * better performance for large datasets through: + * - Configurable resource management + * - Instance-scoped worker pools and caches + * - Proper lifecycle management and cleanup + * - Reference counting for shared resources + * - Enhanced error handling and timeouts + * - Memory optimization with size-based LRU caches + * + * Last updated: 2025 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + // Global shared resources with reference counting + const GLOBAL_SHARED_RESOURCES = { + // Protocol cache - expensive to duplicate, shared with reference counting + protocolCache: new Map(), // url -> { protocol, instance, refCount } + + // Metadata cache - small and shareable + metadataCache: new Map(), // cacheKey -> data + + // Pre-calculated world sizes for common zoom levels (static, no cleanup needed) + worldSizeCache: new Array(25).fill(null).map((_, z) => Math.pow(2, z)), + + // Global cleanup registry + activeManagers: new Set(), + + // Debug/development features + debug: false, + performanceMetrics: new Map(), + }; + + /** + * Default configuration options + */ + const DEFAULT_OPTIONS = { + workerPoolSize: 4, + tileCacheSize: 1000, + tileCacheMaxMemoryMB: 100, + metadataCacheSize: 100, + enableSharedProtocols: true, + requestTimeoutMs: 30000, + enableDebugLogging: false, + enablePerformanceMetrics: false, + }; + + /** + * LRU Cache implementation with size-based eviction + */ + class LRUCache { + constructor(maxSize, maxMemoryBytes = Infinity) { + this.maxSize = maxSize; + this.maxMemoryBytes = maxMemoryBytes; + this.cache = new Map(); + this.currentMemoryBytes = 0; + } + + get(key) { + if (this.cache.has(key)) { + // Move to end (most recently used) + const value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return value.data; + } + return undefined; + } + + set(key, data, estimatedSize = 0) { + // Remove if exists + if (this.cache.has(key)) { + const existing = this.cache.get(key); + this.currentMemoryBytes -= existing.size; + this.cache.delete(key); + } + + // Evict old entries if necessary + while ( + this.cache.size >= this.maxSize || + this.currentMemoryBytes + estimatedSize > this.maxMemoryBytes + ) { + const firstKey = this.cache.keys().next().value; + if (!firstKey) break; + + const firstValue = this.cache.get(firstKey); + this.currentMemoryBytes -= firstValue.size; + this.cache.delete(firstKey); + } + + // Add new entry + this.cache.set(key, { data, size: estimatedSize }); + this.currentMemoryBytes += estimatedSize; + } + + has(key) { + return this.cache.has(key); + } + + delete(key) { + if (this.cache.has(key)) { + const value = this.cache.get(key); + this.currentMemoryBytes -= value.size; + this.cache.delete(key); + return true; + } + return false; + } + + clear() { + this.cache.clear(); + this.currentMemoryBytes = 0; + } + + get size() { + return this.cache.size; + } + + getMemoryUsage() { + return { + entries: this.cache.size, + memoryBytes: this.currentMemoryBytes, + memoryMB: this.currentMemoryBytes / (1024 * 1024), + }; + } + } + + /** + * Resource Manager - handles per-instance resources and lifecycle + */ + class PMTilesResourceManager { + constructor(options = {}) { + this.config = { ...DEFAULT_OPTIONS, ...options }; + this.destroyed = false; + this.paused = false; + this.dispatcher = null; + + // Instance-scoped resources + this.workerPool = []; + this.workerPoolIndex = 0; + this.tileCache = new LRUCache( + this.config.tileCacheSize, + this.config.tileCacheMaxMemoryMB * 1024 * 1024, + ); + this.pendingRequests = new Map(); + this.activeRequests = new Set(); + + // Performance tracking + this.metrics = { + tilesLoaded: 0, + cacheHits: 0, + cacheMisses: 0, + memoryPeakMB: 0, + averageLoadTimeMs: 0, + }; + + // Register for global cleanup + GLOBAL_SHARED_RESOURCES.activeManagers.add(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager created", this.config); + } + } + + /** + * Initialize worker pool + */ + initializeWorkerPool(dispatcher) { + if (this.destroyed) return; + + // Store dispatcher reference + if (dispatcher) { + this.dispatcher = dispatcher; + } + + if (this.workerPool.length === 0 && this.dispatcher) { + for (let i = 0; i < this.config.workerPoolSize; i++) { + try { + this.workerPool.push(this.dispatcher.getActor()); + } catch (error) { + console.warn("[PMTiles] Failed to create worker:", error); + } + } + + if (this.config.enableDebugLogging) { + console.log( + `[PMTiles] Initialized worker pool with ${this.workerPool.length} workers`, + ); + } + } + } + + /** + * Get next worker from pool (round-robin) + */ + getWorkerFromPool() { + if (this.destroyed) { + return null; + } + + // Try to initialize workers if not done yet + if (this.workerPool.length === 0 && this.dispatcher) { + this.initializeWorkerPool(this.dispatcher); + } + + if (this.workerPool.length === 0) { + if (this.config.enableDebugLogging) { + console.warn( + "[PMTiles] Worker pool is empty, dispatcher available:", + !!this.dispatcher, + ); + } + return null; + } + + const worker = this.workerPool[this.workerPoolIndex]; + this.workerPoolIndex = + (this.workerPoolIndex + 1) % this.workerPool.length; + return worker; + } + + /** + * Get or create protocol instance with reference counting + */ + getProtocol(url) { + if (this.destroyed) return null; + + if (!this.config.enableSharedProtocols) { + // Create instance-specific protocol + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + return { protocol, instance }; + } + + // Use shared protocol with reference counting + if (!GLOBAL_SHARED_RESOURCES.protocolCache.has(url)) { + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + GLOBAL_SHARED_RESOURCES.protocolCache.set(url, { + protocol, + instance, + refCount: 0, + }); + } + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + cached.refCount++; + return cached; + } + + /** + * Release protocol reference + */ + releaseProtocol(url) { + if (!this.config.enableSharedProtocols) return; + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + if (cached) { + cached.refCount--; + if (cached.refCount <= 0) { + GLOBAL_SHARED_RESOURCES.protocolCache.delete(url); + + if (this.config.enableDebugLogging) { + console.log(`[PMTiles] Released protocol for ${url}`); + } + } + } + } + + /** + * Cache key for tiles + */ + getTileCacheKey(url, z, x, y) { + return `${url}:${z}:${x}:${y}`; + } + + /** + * Add tile to cache with size estimation + */ + addToTileCache(key, data) { + if (this.destroyed) return; + + let estimatedSize = 0; + if (data instanceof ImageBitmap) { + // Rough estimation: width * height * 4 bytes per pixel + estimatedSize = data.width * data.height * 4; + } else if (data && data.byteLength) { + estimatedSize = data.byteLength; + } else { + estimatedSize = 10000; // Default estimate + } + + this.tileCache.set(key, data, estimatedSize); + + // Update peak memory usage + const memoryUsage = this.tileCache.getMemoryUsage(); + this.metrics.memoryPeakMB = Math.max( + this.metrics.memoryPeakMB, + memoryUsage.memoryMB, + ); + } + + /** + * Get cached metadata + */ + getCachedMetadata(cacheKey) { + return GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + } + + /** + * Set cached metadata + */ + setCachedMetadata(cacheKey, data) { + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, data); + } + + /** + * Pause all operations + */ + pause() { + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager paused"); + } + } + + /** + * Resume operations + */ + resume() { + this.paused = false; + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager resumed"); + } + } + + /** + * Get performance metrics + */ + getMetrics() { + return { + ...this.metrics, + tileCache: this.tileCache.getMemoryUsage(), + workerPoolSize: this.workerPool.length, + pendingRequests: this.pendingRequests.size, + isPaused: this.paused, + isDestroyed: this.destroyed, + }; + } + + /** + * Destroy and cleanup all resources + */ + destroy() { + if (this.destroyed) return; + + this.destroyed = true; + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + // Clear caches + this.tileCache.clear(); + + // Clear worker pool references + this.workerPool.length = 0; + + // Remove from global registry + GLOBAL_SHARED_RESOURCES.activeManagers.delete(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager destroyed", this.getMetrics()); + } + } + } + + /** + * Global cleanup function + */ + const cleanup = () => { + for (const manager of GLOBAL_SHARED_RESOURCES.activeManagers) { + manager.destroy(); + } + GLOBAL_SHARED_RESOURCES.protocolCache.clear(); + GLOBAL_SHARED_RESOURCES.metadataCache.clear(); + }; + + // Register global cleanup + if (typeof window !== "undefined") { + window.addEventListener("beforeunload", cleanup); + } + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + + // Pre-calculate mercator bounds + this._mercatorBounds = { + west: mercatorXFromLng(this.bounds.getWest()), + north: mercatorYFromLat(this.bounds.getNorth()), + east: mercatorXFromLng(this.bounds.getEast()), + south: mercatorYFromLat(this.bounds.getSouth()), + }; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + // Use pre-calculated world size + const worldSize = + GLOBAL_SHARED_RESOURCES.worldSizeCache[tileID.z] || + Math.pow(2, tileID.z); + + // Use pre-calculated mercator bounds + const level = { + minX: Math.floor(this._mercatorBounds.west * worldSize), + minY: Math.floor(this._mercatorBounds.north * worldSize), + maxX: Math.ceil(this._mercatorBounds.east * worldSize), + maxY: Math.ceil(this._mercatorBounds.south * worldSize), + }; + + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + /** + * Enhanced PMTiles Source with lifecycle management + */ + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + + // Extract PMTiles-specific options + const pmtilesOptions = { + workerPoolSize: options.workerPoolSize, + tileCacheSize: options.tileCacheSize, + tileCacheMaxMemoryMB: options.tileCacheMaxMemoryMB, + metadataCacheSize: options.metadataCacheSize, + enableSharedProtocols: options.enableSharedProtocols, + requestTimeoutMs: options.requestTimeoutMs, + enableDebugLogging: options.enableDebugLogging, + enablePerformanceMetrics: options.enablePerformanceMetrics, + }; + + // Initialize resource manager + this.resourceManager = new PMTilesResourceManager(pmtilesOptions); + + // Standard source properties + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = _dispatcher; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._implementation = options; + + // Initialize worker pool + this.resourceManager.initializeWorkerPool(_dispatcher); + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + return; + } + + const { url } = options; + this.url = url; + this.tileSize = 512; + + // Get protocol instance + this.protocolInfo = this.resourceManager.getProtocol(url); + if (!this.protocolInfo) { + this.fire( + new ErrorEvent(new Error(`Failed to create protocol for ${url}`)), + ); + return; + } + + this._protocol = this.protocolInfo.protocol; + this._instance = this.protocolInfo.instance; + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + } + + static async getMetadata(url) { + // Check cache first + const cacheKey = `${url}:metadata`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const metadata = await instance.getMetadata(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, metadata); + return metadata; + } + + static async getHeader(url) { + // Check cache first + const cacheKey = `${url}:header`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const header = await instance.getHeader(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, header); + return header; + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (this.resourceManager.destroyed) return; + + if (!tile.destroy) { + tile.destroy = () => {}; + } + if (!tile.abort) { + tile.abort = () => { + tile.aborted = true; + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + }; + } + } + + /** + * Pause tile loading + */ + pause() { + this.resourceManager.pause(); + } + + /** + * Resume tile loading + */ + resume() { + this.resourceManager.resume(); + } + + /** + * Get performance metrics + */ + getMetrics() { + return this.resourceManager.getMetrics(); + } + + /** + * Destroy source and cleanup resources + */ + destroy() { + if (this.protocolInfo && this.url) { + this.resourceManager.releaseProtocol(this.url); + } + + this.resourceManager.destroy(); + this._loaded = false; + } + + async load(callback) { + if (this.resourceManager.destroyed) { + const error = new Error("Source has been destroyed"); + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + // Check metadata cache first + const headerKey = `${this.url}:header`; + const metadataKey = `${this.url}:metadata`; + + let header, tileJSON; + + const cachedHeader = this.resourceManager.getCachedMetadata(headerKey); + const cachedMetadata = + this.resourceManager.getCachedMetadata(metadataKey); + + if (cachedHeader && cachedMetadata) { + header = cachedHeader; + tileJSON = cachedMetadata; + } else { + try { + // Load and cache + [header, tileJSON] = await Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]); + this.resourceManager.setCachedMetadata(headerKey, header); + this.resourceManager.setCachedMetadata(metadataKey, tileJSON); + } catch (error) { + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + } + + try { + extend(this, tileJSON); + this.header = header; + const { tileType, minZoom, maxZoom, minLon, minLat, maxLon, maxLat } = + header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes(this.tileType) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { dataType: "source", sourceDataType: "metadata" }), + ); + this.fire( + new Event("data", { dataType: "source", sourceDataType: "content" }), + ); + } catch (err2) { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + } + } + + loaded() { + return this._loaded && !this.resourceManager.destroyed; + } + + loadVectorTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + const startTime = Date.now(); + var _a2, _b2, _c; + + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + + // Update metrics + this.resourceManager.metrics.tilesLoaded++; + const loadTime = Date.now() - startTime; + this.resourceManager.metrics.averageLoadTimeMs = + (this.resourceManager.metrics.averageLoadTimeMs + loadTime) / 2; + + if (tile.aborted) return callback(null); + + // Handle abort errors gracefully + if (err2 && err2.name === "AbortError") { + return callback(null); + } + + if (err2 && err2.status !== 404) { + return callback(err2); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + // Handle abort errors gracefully + if (error && (error.name === "AbortError" || error.code === 20)) { + return done.call(this, null); + } + done.call(this, error); + return; + } + + params.data = { + cacheControl, + expires, + rawData: data, + }; + + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + // Use shared worker pool + tile.actor = this.resourceManager.getWorkerFromPool(); + + // Fallback to dispatcher if worker pool failed + if (!tile.actor && this.dispatcher) { + try { + tile.actor = this.dispatcher.getActor(); + } catch (error) { + console.warn("[PMTiles] Failed to get fallback worker:", error); + return callback(new Error("No workers available")); + } + } + + if (!tile.actor) { + return callback(new Error("No workers available")); + } + + // Create request with timeout + const requestPromise = this._protocol.tile({ ...request }, afterLoad); + + // Add timeout if configured + if (this.resourceManager.config.requestTimeoutMs > 0) { + const timeoutId = setTimeout(() => { + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + done.call(this, new Error("Request timeout")); + }, this.resourceManager.config.requestTimeoutMs); + + const originalCancel = requestPromise.cancel; + requestPromise.cancel = () => { + clearTimeout(timeoutId); + if (originalCancel) originalCancel(); + }; + } + + tile.request = requestPromise; + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + if (this.resourceManager.destroyed) return; + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + var _a2, _b2; + + // Check tile cache first + const cacheKey = this.resourceManager.getTileCacheKey( + this.url, + tile.tileID.canonical.z, + tile.tileID.canonical.x, + tile.tileID.canonical.y, + ); + + if (this.resourceManager.tileCache.has(cacheKey)) { + this.resourceManager.metrics.cacheHits++; + const cachedData = this.resourceManager.tileCache.get(cacheKey); + this.loadRasterTileData(tile, cachedData); + tile.state = "loaded"; + return callback(null); + } + + this.resourceManager.metrics.cacheMisses++; + + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + + // Optimized raster tile loading - try direct ArrayBuffer first + const arrayBuffer = data.buffer || data; + window + .createImageBitmap(arrayBuffer) + .then((imageBitmap) => { + // Cache the decoded image + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + // Fallback to blob method + const blob = new window.Blob([new Uint8Array(data)], { + type: this.contentType, + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error(`Can't decode image for ${this.id}: ${error}`), + ); + }); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + this.fixTile(tile); + const controller = new AbortController(); + + // Add timeout if configured + let timeoutId; + if (this.resourceManager.config.requestTimeoutMs > 0) { + timeoutId = setTimeout(() => { + controller.abort(); + }, this.resourceManager.config.requestTimeoutMs); + } + + tile.request = { + cancel: () => { + if (timeoutId) clearTimeout(timeoutId); + controller.abort(); + }, + }; + + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (timeoutId) clearTimeout(timeoutId); + + // Handle abort errors gracefully + if (error.name === "AbortError" || error.code === 20) { + delete tile.request; + return callback(null); + } + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Expose cleanup function + PmTilesSource.cleanup = cleanup; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; + global.PMTilesResourceManager = PMTilesResourceManager; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/layers-overview_files/mapbox-pmtiles-1.1.0/pmtiles-source.js b/docs/articles/layers-overview_files/mapbox-pmtiles-1.1.0/pmtiles-source.js new file mode 100644 index 0000000..2130749 --- /dev/null +++ b/docs/articles/layers-overview_files/mapbox-pmtiles-1.1.0/pmtiles-source.js @@ -0,0 +1,459 @@ +/** + * mapbox-pmtiles v1.0.53 + * Original source: https://github.com/am2222/mapbox-pmtiles + * License: MIT + * + * This is a vendored copy of the mapbox-pmtiles library that provides + * PMTiles support for Mapbox GL JS by implementing a custom source type. + * + * Last updated: 2024 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + const worldSize = Math.pow(2, tileID.z); + const level = { + minX: Math.floor(mercatorXFromLng(this.bounds.getWest()) * worldSize), + minY: Math.floor(mercatorYFromLat(this.bounds.getNorth()) * worldSize), + maxX: Math.ceil(mercatorXFromLng(this.bounds.getEast()) * worldSize), + maxY: Math.ceil(mercatorYFromLat(this.bounds.getSouth()) * worldSize), + }; + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = void 0; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._dataType = "vector"; + this.dispatcher = _dispatcher; + this._implementation = options; + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + } + + const { url } = options; + this.reparseOverscaled = true; + this.scheme = "xyz"; + this.tileSize = 512; + this._loaded = false; + this.type = "vector"; + this._protocol = new pmtiles.Protocol(); + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + const pmtilesInstance = new pmtiles.PMTiles(url); + this._protocol.add(pmtilesInstance); + this._instance = pmtilesInstance; + } + + static async getMetadata(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getMetadata(); + } + + static async getHeader(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getHeader(); + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (!tile.destroy) { + tile.destroy = () => {}; + } + } + + async load(callback) { + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + return Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]) + .then(([header, tileJSON]) => { + extend(this, tileJSON); + this.header = header; + const { + specVersion, + clustered, + tileType, + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + centerZoom, + centerLon, + centerLat, + } = header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes( + this.tileType, + ) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "metadata", + }), + ); + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "content", + }), + ); + }) + .catch((err2) => { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + }); + } + + loaded() { + return this._loaded; + } + + loadVectorTile(tile, callback) { + var _a2, _b2, _c; + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + if (tile.aborted) return callback(null); + if (err2 && err2.status !== 404) { + return callback(err2); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + done.call(this, error); + return; + } + params.data = { + cacheControl, + expires, + rawData: data, + }; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + tile.actor = this._tileWorkers[url] = + this._tileWorkers[url] || this.dispatcher.getActor(); + tile.request = this._protocol.tile({ ...request }, afterLoad); + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + var _a2, _b2; + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + const blob = new window.Blob([new Uint8Array(data)], { + type: "image/png", + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error( + `Can't infer data type for ${this.id}, only raster data supported at the moment. ${error}`, + ), + ); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + this.fixTile(tile); + const controller = new AbortController(); + tile.request = { cancel: () => controller.abort() }; + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (error.code === 20) return; + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/getting-started_files/mapboxgl-binding-0.3/mapboxgl.js b/docs/articles/layers-overview_files/mapboxgl-binding-0.3.1.9000/mapboxgl.js similarity index 89% rename from docs/articles/getting-started_files/mapboxgl-binding-0.3/mapboxgl.js rename to docs/articles/layers-overview_files/mapboxgl-binding-0.3.1.9000/mapboxgl.js index b9f2563..700670b 100644 --- a/docs/articles/getting-started_files/mapboxgl-binding-0.3/mapboxgl.js +++ b/docs/articles/layers-overview_files/mapboxgl-binding-0.3.1.9000/mapboxgl.js @@ -292,6 +292,22 @@ HTMLWidgets.widget({ return; } + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + mapboxgl.accessToken = x.access_token; map = new mapboxgl.Map({ @@ -477,6 +493,18 @@ HTMLWidgets.widget({ urls: source.urls, coordinates: source.coordinates, }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); } }); } @@ -887,6 +915,85 @@ HTMLWidgets.widget({ drawBar.style.flexDirection = "row"; } } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } } // Helper function to add features from a source to draw @@ -1128,17 +1235,17 @@ HTMLWidgets.widget({ // Set the position correctly - fix position bug by using correct CSS positioning const position = x.layers_control.position || "top-left"; if (position === "top-left") { - layersControl.style.top = "10px"; - layersControl.style.left = "10px"; + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; } else if (position === "top-right") { - layersControl.style.top = "10px"; - layersControl.style.right = "10px"; + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; } else if (position === "bottom-left") { - layersControl.style.bottom = "30px"; - layersControl.style.left = "10px"; + layersControl.style.bottom = (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; } else if (position === "bottom-right") { - layersControl.style.bottom = "40px"; - layersControl.style.right = "10px"; + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; } // Apply custom colors if provided @@ -1343,38 +1450,44 @@ HTMLWidgets.widget({ // add hover listener for shinyMode if enabled if (x.hover_events && x.hover_events.enabled) { - map.on("mousemove", function (e) { - // Feature hover events - if (x.hover_events.features) { - const features = map.queryRenderedFeatures(e.point); - - if(features.length > 0) { - const feature = features[0]; - Shiny.onInputChange(el.id + "_feature_hover", { - id: feature.id, - properties: feature.properties, - layer: feature.layer.id, - lng: e.lngLat.lng, - lat: e.lngLat.lat, - time: new Date(), - }); - } else { - Shiny.onInputChange( - el.id + "_feature_hover", - null, - ); - } + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); } + } - // Coordinate hover events - if (x.hover_events.coordinates) { - Shiny.onInputChange(el.id + "_hover", { - lng: e.lngLat.lng, - lat: e.lngLat.lat, - time: new Date(), - }); - } - }); + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); } } @@ -1580,6 +1693,18 @@ if (HTMLWidgets.shinyMode) { sourceConfig[key] = message.source[key]; } }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); } } else if (message.type === "add_layer") { @@ -1846,6 +1971,52 @@ if (HTMLWidgets.shinyMode) { layerState.paintProperties[layerId] = {}; } layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); } else if (message.type === "add_legend") { // Extract legend ID from HTML to track it const legendIdMatch = message.html.match(/id="([^"]+)"/); @@ -2321,6 +2492,85 @@ if (HTMLWidgets.shinyMode) { drawBar.style.flexDirection = "row"; } } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } } else if (message.type === "get_drawn_features") { var drawControl = widget.drawControl || widget.getDraw(); if (drawControl) { @@ -2494,17 +2744,17 @@ if (HTMLWidgets.shinyMode) { // Set the position correctly const position = message.position || "top-left"; if (position === "top-left") { - layersControl.style.top = "10px"; - layersControl.style.left = "10px"; + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; } else if (position === "top-right") { - layersControl.style.top = "10px"; - layersControl.style.right = "10px"; + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; } else if (position === "bottom-left") { - layersControl.style.bottom = "30px"; - layersControl.style.left = "10px"; + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; } else if (position === "bottom-right") { - layersControl.style.bottom = "40px"; - layersControl.style.right = "10px"; + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; } // Apply custom colors if provided diff --git a/docs/articles/layers-overview_files/mapboxgl-binding-0.3.2/mapboxgl.js b/docs/articles/layers-overview_files/mapboxgl-binding-0.3.2/mapboxgl.js new file mode 100644 index 0000000..42e4216 --- /dev/null +++ b/docs/articles/layers-overview_files/mapboxgl-binding-0.3.2/mapboxgl.js @@ -0,0 +1,3197 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/layers-overview_files/mapboxgl-binding-0.3.9.9000/mapboxgl.js b/docs/articles/layers-overview_files/mapboxgl-binding-0.3.9.9000/mapboxgl.js new file mode 100644 index 0000000..182e834 --- /dev/null +++ b/docs/articles/layers-overview_files/mapboxgl-binding-0.3.9.9000/mapboxgl.js @@ -0,0 +1,3249 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/layers-overview_files/mapboxgl-binding-0.4.0.9000/mapboxgl.js b/docs/articles/layers-overview_files/mapboxgl-binding-0.4.0.9000/mapboxgl.js new file mode 100644 index 0000000..3fee4ba --- /dev/null +++ b/docs/articles/layers-overview_files/mapboxgl-binding-0.4.0.9000/mapboxgl.js @@ -0,0 +1,3418 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/layers-overview_files/mapboxgl-binding-0.4.0/mapboxgl.js b/docs/articles/layers-overview_files/mapboxgl-binding-0.4.0/mapboxgl.js new file mode 100644 index 0000000..182e834 --- /dev/null +++ b/docs/articles/layers-overview_files/mapboxgl-binding-0.4.0/mapboxgl.js @@ -0,0 +1,3249 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/layers-overview_files/mapboxgl-binding-0.4.1/mapboxgl.js b/docs/articles/layers-overview_files/mapboxgl-binding-0.4.1/mapboxgl.js new file mode 100644 index 0000000..c0d6d59 --- /dev/null +++ b/docs/articles/layers-overview_files/mapboxgl-binding-0.4.1/mapboxgl.js @@ -0,0 +1,3910 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/getting-started_files/maplibre-gl-4.7.1/LICENSE.txt b/docs/articles/layers-overview_files/maplibre-gl-5.7.2/LICENSE.txt similarity index 100% rename from docs/articles/getting-started_files/maplibre-gl-4.7.1/LICENSE.txt rename to docs/articles/layers-overview_files/maplibre-gl-5.7.2/LICENSE.txt diff --git a/docs/articles/layers-overview_files/maplibre-gl-5.7.2/maplibre-gl.css b/docs/articles/layers-overview_files/maplibre-gl-5.7.2/maplibre-gl.css new file mode 100644 index 0000000..3f86747 --- /dev/null +++ b/docs/articles/layers-overview_files/maplibre-gl-5.7.2/maplibre-gl.css @@ -0,0 +1 @@ +.maplibregl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgb(0,0,0,0)}.maplibregl-canvas{left:0;position:absolute;top:0}.maplibregl-map:fullscreen{height:100%;width:100%}.maplibregl-ctrl-group button.maplibregl-ctrl-compass{touch-action:none}.maplibregl-canvas-container.maplibregl-interactive,.maplibregl-ctrl-group button.maplibregl-ctrl-compass{cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-canvas-container.maplibregl-interactive.maplibregl-track-pointer{cursor:pointer}.maplibregl-canvas-container.maplibregl-interactive:active,.maplibregl-ctrl-group button.maplibregl-ctrl-compass:active{cursor:grabbing}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-canvas-container.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:pinch-zoom}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:none}.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures,.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-ctrl-bottom-left,.maplibregl-ctrl-bottom-right,.maplibregl-ctrl-top-left,.maplibregl-ctrl-top-right{pointer-events:none;position:absolute;z-index:2}.maplibregl-ctrl-top-left{left:0;top:0}.maplibregl-ctrl-top-right{right:0;top:0}.maplibregl-ctrl-bottom-left{bottom:0;left:0}.maplibregl-ctrl-bottom-right{bottom:0;right:0}.maplibregl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.maplibregl-ctrl-top-left .maplibregl-ctrl{float:left;margin:10px 0 0 10px}.maplibregl-ctrl-top-right .maplibregl-ctrl{float:right;margin:10px 10px 0 0}.maplibregl-ctrl-bottom-left .maplibregl-ctrl{float:left;margin:0 0 10px 10px}.maplibregl-ctrl-bottom-right .maplibregl-ctrl{float:right;margin:0 10px 10px 0}.maplibregl-ctrl-group{background:#fff;border-radius:4px}.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px rgba(0,0,0,.1)}@media (forced-colors:active){.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.maplibregl-ctrl-group button{background-color:transparent;border:0;box-sizing:border-box;cursor:pointer;display:block;height:29px;outline:none;padding:0;width:29px}.maplibregl-ctrl-group button+button{border-top:1px solid #ddd}.maplibregl-ctrl button .maplibregl-ctrl-icon{background-position:50%;background-repeat:no-repeat;display:block;height:100%;width:100%}@media (forced-colors:active){.maplibregl-ctrl-icon{background-color:transparent}.maplibregl-ctrl-group button+button{border-top:1px solid ButtonText}}.maplibregl-ctrl button::-moz-focus-inner{border:0;padding:0}.maplibregl-ctrl-attrib-button:focus,.maplibregl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl button:disabled{cursor:not-allowed}.maplibregl-ctrl button:disabled .maplibregl-ctrl-icon{opacity:.25}@media (hover:hover){.maplibregl-ctrl button:not(:disabled):hover{background-color:rgba(0,0,0,.05)}}.maplibregl-ctrl button:not(:disabled):active{background-color:rgba(0,0,0,.05)}.maplibregl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.maplibregl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.maplibregl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.maplibregl-ctrl-group button:focus:only-child{border-radius:inherit}.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-globe .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none' stroke='%23333' viewBox='0 0 22 22'%3E%3Ccircle cx='11' cy='11' r='8.5'/%3E%3Cpath d='M17.5 11c0 4.819-3.02 8.5-6.5 8.5S4.5 15.819 4.5 11 7.52 2.5 11 2.5s6.5 3.681 6.5 8.5Z'/%3E%3Cpath d='M13.5 11c0 2.447-.331 4.64-.853 6.206-.262.785-.562 1.384-.872 1.777-.314.399-.58.517-.775.517s-.461-.118-.775-.517c-.31-.393-.61-.992-.872-1.777C8.831 15.64 8.5 13.446 8.5 11s.331-4.64.853-6.206c.262-.785.562-1.384.872-1.777.314-.399.58-.517.775-.517s.461.118.775.517c.31.393.61.992.872 1.777.522 1.565.853 3.76.853 6.206Z'/%3E%3Cpath d='M11 7.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138q.07-.058.224-.138c.299-.151.763-.302 1.379-.434C7.378 5.666 9.091 5.5 11 5.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138q-.07.058-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428ZM4.486 6.436ZM11 16.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138 1.3 1.3 0 0 1 .224-.138c.299-.151.763-.302 1.379-.434C7.378 14.666 9.091 14.5 11 14.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138a1.3 1.3 0 0 1-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428Zm-6.514-1.064ZM11 12.5c-2.46 0-4.672-.222-6.255-.574-.796-.177-1.406-.38-1.805-.59a1.5 1.5 0 0 1-.39-.272.3.3 0 0 1-.047-.064.3.3 0 0 1 .048-.064c.066-.073.189-.167.389-.272.399-.21 1.009-.413 1.805-.59C6.328 9.722 8.54 9.5 11 9.5s4.672.222 6.256.574c.795.177 1.405.38 1.804.59.2.105.323.2.39.272a.3.3 0 0 1 .047.064.3.3 0 0 1-.048.064 1.4 1.4 0 0 1-.389.272c-.399.21-1.009.413-1.804.59-1.584.352-3.796.574-6.256.574Zm-8.501-1.51v.002zm0 .018v.002zm17.002.002v-.002zm0-.018v-.002z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-globe-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none' stroke='%2333b5e5' viewBox='0 0 22 22'%3E%3Ccircle cx='11' cy='11' r='8.5'/%3E%3Cpath d='M17.5 11c0 4.819-3.02 8.5-6.5 8.5S4.5 15.819 4.5 11 7.52 2.5 11 2.5s6.5 3.681 6.5 8.5Z'/%3E%3Cpath d='M13.5 11c0 2.447-.331 4.64-.853 6.206-.262.785-.562 1.384-.872 1.777-.314.399-.58.517-.775.517s-.461-.118-.775-.517c-.31-.393-.61-.992-.872-1.777C8.831 15.64 8.5 13.446 8.5 11s.331-4.64.853-6.206c.262-.785.562-1.384.872-1.777.314-.399.58-.517.775-.517s.461.118.775.517c.31.393.61.992.872 1.777.522 1.565.853 3.76.853 6.206Z'/%3E%3Cpath d='M11 7.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138q.07-.058.224-.138c.299-.151.763-.302 1.379-.434C7.378 5.666 9.091 5.5 11 5.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138q-.07.058-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428ZM4.486 6.436ZM11 16.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138 1.3 1.3 0 0 1 .224-.138c.299-.151.763-.302 1.379-.434C7.378 14.666 9.091 14.5 11 14.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138a1.3 1.3 0 0 1-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428Zm-6.514-1.064ZM11 12.5c-2.46 0-4.672-.222-6.255-.574-.796-.177-1.406-.38-1.805-.59a1.5 1.5 0 0 1-.39-.272.3.3 0 0 1-.047-.064.3.3 0 0 1 .048-.064c.066-.073.189-.167.389-.272.399-.21 1.009-.413 1.805-.59C6.328 9.722 8.54 9.5 11 9.5s4.672.222 6.256.574c.795.177 1.405.38 1.804.59.2.105.323.2.39.272a.3.3 0 0 1 .047.064.3.3 0 0 1-.048.064 1.4 1.4 0 0 1-.389.272c-.399.21-1.009.413-1.804.59-1.584.352-3.796.574-6.256.574Zm-8.501-1.51v.002zm0 .018v.002zm17.002.002v-.002zm0-.018v-.002z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%23333' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%2333b5e5' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23aaa' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-waiting .maplibregl-ctrl-icon{animation:maplibregl-spin 2s linear infinite}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23999' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23666' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}}@keyframes maplibregl-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E");background-repeat:no-repeat;cursor:pointer;display:block;height:23px;margin:0 0 -4px -4px;overflow:hidden;width:88px}a.maplibregl-ctrl-logo.maplibregl-compact{width:14px}@media (forced-colors:active){a.maplibregl-ctrl-logo{background-color:transparent;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}.maplibregl-ctrl.maplibregl-ctrl-attrib{background-color:hsla(0,0%,100%,.5);margin:0;padding:0 5px}@media screen{.maplibregl-ctrl-attrib.maplibregl-compact{background-color:#fff;border-radius:12px;box-sizing:content-box;color:#000;margin:10px;min-height:20px;padding:2px 24px 2px 0;position:relative}.maplibregl-ctrl-attrib.maplibregl-compact-show{padding:2px 28px 2px 8px;visibility:visible}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:hsla(0,0%,100%,.5);background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:rgba(0,0,0,.05)}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:hsla(0,0%,100%,.75);border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:rgba(0,0,0,.05)}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px rgba(0,0,0,.35);box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:rgba(0,0,0,.4);color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media (hover:none),(pointer:coarse){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999} \ No newline at end of file diff --git a/docs/articles/layers-overview_files/maplibre-gl-5.7.2/maplibre-gl.js b/docs/articles/layers-overview_files/maplibre-gl-5.7.2/maplibre-gl.js new file mode 100644 index 0000000..53dd1e0 --- /dev/null +++ b/docs/articles/layers-overview_files/maplibre-gl-5.7.2/maplibre-gl.js @@ -0,0 +1,59 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v5.7.2/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory()); +})(this, (function () { 'use strict'; + +/* eslint-disable */ + +var maplibregl = {}; +var modules = {}; +function define(moduleName, _dependencies, moduleFactory) { + modules[moduleName] = moduleFactory; + + // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) + if (moduleName !== 'index') { + return; + } + + // we assume that when an index module is initializing then other modules are loaded already + var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);' + + var sharedModule = {}; + // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) + // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) + // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following + modules.shared(sharedModule); + modules.index(maplibregl, sharedModule); + + if (typeof window !== 'undefined') { + maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); + } + + return maplibregl; +}; + + + +define("shared",["exports"],(function(t){"use strict";function e(t,e,r,n){return new(r||(r=Promise))((function(i,s){function a(t){try{l(n.next(t));}catch(t){s(t);}}function o(t){try{l(n.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(a,o);}l((n=n.apply(t,e||[])).next());}))}function r(t,e){this.x=t,this.y=e;}function n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,s;"function"==typeof SuppressedError&&SuppressedError,r.prototype={clone(){return new r(this.x,this.y)},add(t){return this.clone()._add(t)},sub(t){return this.clone()._sub(t)},multByPoint(t){return this.clone()._multByPoint(t)},divByPoint(t){return this.clone()._divByPoint(t)},mult(t){return this.clone()._mult(t)},div(t){return this.clone()._div(t)},rotate(t){return this.clone()._rotate(t)},rotateAround(t,e){return this.clone()._rotateAround(t,e)},matMult(t){return this.clone()._matMult(t)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(t){return this.x===t.x&&this.y===t.y},dist(t){return Math.sqrt(this.distSqr(t))},distSqr(t){const e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle(){return Math.atan2(this.y,this.x)},angleTo(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith(t){return this.angleWithSep(t.x,t.y)},angleWithSep(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult(t){const e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add(t){return this.x+=t.x,this.y+=t.y,this},_sub(t){return this.x-=t.x,this.y-=t.y,this},_mult(t){return this.x*=t,this.y*=t,this},_div(t){return this.x/=t,this.y/=t,this},_multByPoint(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint(t){return this.x/=t.x,this.y/=t.y,this},_unit(){return this._div(this.mag()),this},_perp(){const t=this.y;return this.y=this.x,this.x=-t,this},_rotate(t){const e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround(t,e){const r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:r},r.convert=function(t){if(t instanceof r)return t;if(Array.isArray(t))return new r(+t[0],+t[1]);if(void 0!==t.x&&void 0!==t.y)return new r(+t.x,+t.y);throw new Error("Expected [x, y] or {x, y} point format")};var a=function(){if(s)return i;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return s=1,i=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},i}(),o=n(a);let l,u;function c(){return null==l&&(l="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),l}function h(){if(null==u&&(u=!1,c())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:!0});if(e){for(let r=0;r4&&void 0!==arguments[4]?arguments[4]:"zyx",s=Math.PI/360;e*=s,n*=s,r*=s;var a=Math.sin(e),o=Math.cos(e),l=Math.sin(r),u=Math.cos(r),c=Math.sin(n),h=Math.cos(n);switch(i){case "xyz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "xzy":t[0]=a*u*h-o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h+a*l*c;break;case "yxz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;case "yzx":t[0]=a*u*h+o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h-a*l*c;break;case "zxy":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "zyx":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;default:throw new Error("Unknown angle order "+i)}return t}function I(){var t=new f(2);return f!=Float32Array&&(t[0]=0,t[1]=0),t}function z(t,e){var r=new f(2);return r[0]=t,r[1]=e,r}m(),_=new f(4),f!=Float32Array&&(_[0]=0,_[1]=0,_[2]=0,_[3]=0),m(),x(1,0,0),x(0,1,0),k(),k(),d(),I();const P=8192;function C(t,e,r){return e*(P/(t.tileSize*Math.pow(2,r-t.tileID.overscaledZ)))}function E(t,e){return (t%e+e)%e}function T(t,e,r){return t*(1-r)+e*r}function B(t){if(t<=0)return 0;if(t>=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function V(t,e,r,n){const i=new o(t,e,r,n);return t=>i.solve(t)}const F=V(.25,.1,.25,1);function $(t,e,r){return Math.min(r,Math.max(e,t))}function D(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function L(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let O=1;function R(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function U(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}function j(t){return Array.isArray(t)?t.map(j):"object"==typeof t&&t?R(t,j):t}const N={};function q(t){N[t]||("undefined"!=typeof console&&console.warn(t),N[t]=!0);}function G(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function X(t){return "undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}let Z=null;function Y(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const H="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function K(t,r,n,i,s){return e(this,void 0,void 0,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const e=new VideoFrame(t,{timestamp:0});try{const a=null==e?void 0:e.format;if(!a||!a.startsWith("BGR")&&!a.startsWith("RGB"))throw new Error(`Unrecognized format ${a}`);const o=a.startsWith("BGR"),l=new Uint8ClampedArray(i*s*4);if(yield e.copyTo(l,function(t,e,r,n,i){const s=4*Math.max(-e,0),a=(Math.max(0,r)-r)*n*4+s,o=4*n,l=Math.max(0,e),u=Math.max(0,r);return {rect:{x:l,y:u,width:Math.min(t.width,e+n)-l,height:Math.min(t.height,r+i)-u},layout:[{offset:a,stride:o}]}}(t,r,n,i,s)),o)for(let t=0;t{t.removeEventListener(e,r,n);}}}function tt(t){return t*Math.PI/180}function et(t){return t/Math.PI*180}const rt={touchstart:!0,touchmove:!0,touchmoveWindow:!0,touchend:!0,touchcancel:!0},nt={dblclick:!0,click:!0,mouseover:!0,mouseout:!0,mousedown:!0,mousemove:!0,mousemoveWindow:!0,mouseup:!0,mouseupWindow:!0,contextmenu:!0,wheel:!0},it="AbortError";function st(){return new Error(it)}const at={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function ot(t){return at.REGISTERED_PROTOCOLS[t.substring(0,t.indexOf("://"))]}const lt="global-dispatcher";class ut extends Error{constructor(t,e,r,n){super(`AJAXError: ${e} (${t}): ${r}`),this.status=t,this.statusText=e,this.url=r,this.body=n;}}const ct=()=>X(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,ht=function(t,r){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const e=ot(t.url);if(e)return e(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:lt},r)}if(!(/^file:/.test(n=t.url)||/^file:/.test(ct())&&!/^\w+:/.test(n))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,r){return e(this,void 0,void 0,(function*(){const e=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:ct(),signal:r.signal});let n,i;"json"!==t.type||e.headers.has("Accept")||e.headers.set("Accept","application/json");try{n=yield fetch(e);}catch(e){throw new ut(0,e.message,t.url,new Blob)}if(!n.ok){const e=yield n.blob();throw new ut(n.status,n.statusText,t.url,e)}i="arrayBuffer"===t.type||"image"===t.type?n.arrayBuffer():"json"===t.type?n.json():n.text();const s=yield i;if(r.signal.aborted)throw st();return {data:s,cacheControl:n.headers.get("Cache-Control"),expires:n.headers.get("Expires")}}))}(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:!0,targetMapId:lt},r)}var n;return function(t,e){return new Promise(((r,n)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,!0),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||void 0===i?void 0:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{n(new Error(s.statusText));},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response);}catch(t){return void n(t)}r({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires")});}else {const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});n(new ut(s.status,s.statusText,t.url,e));}},e.signal.addEventListener("abort",(()=>{s.abort(),n(st());})),s.send(t.body);}))}(t,r)};function pt(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return !0;const e=new URL(t),r=window.location;return e.protocol===r.protocol&&e.host===r.host}function ft(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function dt(t,e,r){if(r&&r[t]){const n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}class yt{constructor(t,e={}){L(this,e),this.type=t;}}class mt extends yt{constructor(t,e={}){super("error",L({error:t},e));}}class gt{on(t,e){return this._listeners=this._listeners||{},ft(t,e,this._listeners),{unsubscribe:()=>{this.off(t,e);}}}off(t,e){return dt(t,e,this._listeners),dt(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},ft(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new yt(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)dt(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(L(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof mt&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var xt={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},state:{type:"state",default:{}},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},"font-faces":{type:"array",value:"fontFaces"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},"color-relief":{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_color-relief","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const vt=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function bt(t,e){const r={};for(const e in t)"ref"!==e&&(r[e]=t[e]);return vt.forEach((t=>{t in e&&(r[t]=e[t]);})),r}function wt(t,e){if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return !1;for(let r=0;r`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const Jt=[Vt,Ft,$t,Dt,Lt,Ot,Nt,Rt,Ht(Ut),qt,Xt,Gt,Zt,Yt];function Wt(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Wt(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of Jt)if(!Wt(t,e))return null}return `Expected ${Kt(t)} but found ${Kt(e)} instead.`}function Qt(t,e){return e.some((e=>e.kind===t.kind))}function te(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function ee(t,e){return "array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const re=.96422,ne=.82521,ie=4/29,se=6/29,ae=3*se*se,oe=se*se*se,le=Math.PI/180,ue=180/Math.PI;function ce(t){return (t%=360)<0&&(t+=360),t}function he([t,e,r,n]){let i,s;const a=fe((.2225045*(t=pe(t))+.7168786*(e=pe(e))+.0606169*(r=pe(r)))/1);t===e&&e===r?i=s=a:(i=fe((.4360747*t+.3850649*e+.1430804*r)/re),s=fe((.0139322*t+.0971045*e+.7141733*r)/ne));const o=116*a-16;return [o<0?0:o,500*(i-a),200*(a-s),n]}function pe(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function fe(t){return t>oe?Math.pow(t,1/3):t/ae+ie}function de([t,e,r,n]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,a=isNaN(r)?i:i-r/200;return i=1*me(i),s=re*me(s),a=ne*me(a),[ye(3.1338561*s-1.6168667*i-.4906146*a),ye(-.9787684*s+1.9161415*i+.033454*a),ye(.0719453*s-.2289914*i+1.4052427*a),n]}function ye(t){return (t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function me(t){return t>se?t*t*t:ae*(t-ie)}const ge=Object.hasOwn||function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};function xe(t,e){return ge(t,e)?t[e]:void 0}function ve(t){return parseInt(t.padEnd(2,t),16)/255}function be(t,e){return we(e?t/100:t,0,1)}function we(t,e,r){return Math.min(Math.max(e,t),r)}function _e(t){return !t.some(Number.isNaN)}const Se={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function Ae(t,e,r){return t+r*(e-t)}function ke(t,e,r){return t.map(((t,n)=>Ae(t,e[n],r)))}class Me{constructor(t,e,r,n=1,i=!0){this.r=t,this.g=e,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[t,e,r,n]));}static parse(t){if(t instanceof Me)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return [0,0,0,0];const e=xe(Se,t);if(e){const[t,r,n]=e;return [t/255,r/255,n/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let r=1;return [ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,r,n,i,s,a,o,l,u,c,h,p]=e,f=[i||" ",o||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[n,a,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[we(+r/e,0,1),we(+s/e,0,1),we(+l/e,0,1),h?be(+h,p):1];if(_e(t))return t}}return}}const r=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[t,e,n,i,s,a,o,l,u]=r,c=[n||" ",s||" ",o].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,we(+i,0,100),we(+a,0,100),l?be(+l,u):1];if(_e(t))return function([t,e,r,n]){function i(n){const i=(n+t/30)%12,s=e*Math.min(r,1-r);return r-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=ce(t),e/=100,r/=100,[i(0),i(8),i(4),n]}(t)}}}(t);return e?new Me(...e,!1):void 0}get rgb(){const{r:t,g:e,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[t/i,e/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,r,n,i]=he(t),s=Math.sqrt(r*r+n*n);return [Math.round(1e4*s)?ce(Math.atan2(n,r)*ue):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",he(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,r,n]=this.rgb;return `rgba(${[t,e,r].map((t=>Math.round(255*t))).join(",")},${n})`}static interpolate(t,e,r,n="rgb"){switch(n){case "rgb":{const[n,i,s,a]=ke(t.rgb,e.rgb,r);return new Me(n,i,s,a,!1)}case "hcl":{const[n,i,s,a]=t.hcl,[o,l,u,c]=e.hcl;let h,p;if(isNaN(n)||isNaN(o))isNaN(n)?isNaN(o)?h=NaN:(h=o,1!==s&&0!==s||(p=l)):(h=n,1!==u&&0!==u||(p=i));else {let t=o-n;o>n&&t>180?t-=360:o180&&(t+=360),h=n+r*t;}const[f,d,y,m]=function([t,e,r,n]){return t=isNaN(t)?0:t*le,de([r,Math.cos(t)*e,Math.sin(t)*e,n])}([h,null!=p?p:Ae(i,l,r),Ae(s,u,r),Ae(a,c,r)]);return new Me(f,d,y,m,!1)}case "lab":{const[n,i,s,a]=de(ke(t.lab,e.lab,r));return new Me(n,i,s,a,!1)}}}}Me.black=new Me(0,0,0,1),Me.white=new Me(1,1,1,1),Me.transparent=new Me(0,0,0,0),Me.red=new Me(1,0,0,1);class Ie{constructor(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const ze=["bottom","center","top"];class Pe{constructor(t,e,r,n,i,s){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i,this.verticalAlign=s;}}class Ce{constructor(t){this.sections=t;}static fromString(t){return new Ce([new Pe(t,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof Ce?t:Ce.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class Ee{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Ee)return t;if("number"==typeof t)return new Ee([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]];}return new Ee(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Ee(ke(t.values,e.values,r))}}class Te{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Te)return t;if("number"==typeof t)return new Te([t]);if(Array.isArray(t)){for(const e of t)if("number"!=typeof e)return;return new Te(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Te(ke(t.values,e.values,r))}}class Be{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Be)return t;if("string"==typeof t){const e=Me.parse(t);if(!e)return;return new Be([e])}if(!Array.isArray(t))return;const e=[];for(const r of t){if("string"!=typeof r)return;const t=Me.parse(r);if(!t)return;e.push(t);}return new Be(e)}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r,n="rgb"){const i=[];if(t.values.length!=e.values.length)throw new Error(`colorArray: Arrays have mismatched length (${t.values.length} vs. ${e.values.length}), cannot interpolate.`);for(let s=0;s=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Re(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof Le||t instanceof Me||t instanceof Ie||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De)return !0;if(Array.isArray(t)){for(const e of t)if(!Re(e))return !1;return !0}if("object"==typeof t){for(const e in t)if(!Re(t[e]))return !1;return !0}return !1}function Ue(t){if(null===t)return Vt;if("string"==typeof t)return $t;if("boolean"==typeof t)return Dt;if("number"==typeof t)return Ft;if(t instanceof Me)return Lt;if(t instanceof Le)return Ot;if(t instanceof Ie)return jt;if(t instanceof Ce)return Nt;if(t instanceof Ee)return qt;if(t instanceof Te)return Xt;if(t instanceof Be)return Gt;if(t instanceof $e)return Yt;if(t instanceof De)return Zt;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=Ue(e);if(r){if(r===t)continue;r=Ut;break}r=t;}return Ht(r||Ut,e)}return Rt}function je(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof Me||t instanceof Le||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De?t.toString():JSON.stringify(t)}class Ne{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Re(t[1]))return e.error("invalid value");const r=t[1];let n=Ue(r);const i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new Ne(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return !0}}const qe={string:$t,number:Ft,boolean:Dt,object:Rt};class Ge{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r,n=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const r=t[1];if("string"!=typeof r||!(r in qe)||"object"===r)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=qe[r],n++;}else i=Ut;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],n++;}r=Ht(i,s);}else {if(!qe[i])throw new Error(`Types doesn't contain name = ${i}`);r=qe[i];}const s=[];for(;nt.outputDefined()))}}const Xe={"to-boolean":Dt,"to-color":Lt,"to-number":Ft,"to-string":$t};class Ze{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[0];if(!Xe[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");const n=Xe[r],i=[];for(let r=1;r4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:Oe(e[0],e[1],e[2],e[3]),!r))return new Me(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new Ve(r||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "padding":{let e;for(const r of this.args){e=r.evaluate(t);const n=Ee.parse(e);if(n)return n}throw new Ve(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "numberArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Te.parse(e);if(n)return n}throw new Ve(`Could not parse numberArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "colorArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Be.parse(e);if(n)return n}throw new Ve(`Could not parse colorArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "variableAnchorOffsetCollection":{let e;for(const r of this.args){e=r.evaluate(t);const n=$e.parse(e);if(n)return n}throw new Ve(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "number":{let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new Ve(`Could not convert ${JSON.stringify(e)} to number.`)}case "formatted":return Ce.fromString(je(this.args[0].evaluate(t)));case "resolvedImage":return De.fromString(je(this.args[0].evaluate(t)));case "projectionDefinition":return this.args[0].evaluate(t);default:return je(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}const Ye=["Unknown","Point","LineString","Polygon"];class He{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null;}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?Ye[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache.get(t);return e||(e=Me.parse(t),this._parseColorCache.set(t,e)),e}}class Ke{constructor(t,e,r=[],n,i=new Bt,s=[]){this.registry=t,this.path=r,this.key=r.map((t=>`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=n,this._isConstant=e;}parse(t,e,r,n,i={}){return e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return "assert"===r?new Ge(e,[t]):"coerce"===r?new Ze(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const n=t[0];if("string"!=typeof n)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[n];if(i){let n=i.parse(t,this);if(!n)return null;if(this.expectedType){const t=this.expectedType,i=n.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind){if("projectionDefinition"===t.kind&&["string","array"].includes(i.kind)||["color","formatted","resolvedImage"].includes(t.kind)&&["value","string"].includes(i.kind)||["padding","numberArray"].includes(t.kind)&&["value","number","array"].includes(i.kind)||"colorArray"===t.kind&&["value","string","array"].includes(i.kind)||"variableAnchorOffsetCollection"===t.kind&&["value","array"].includes(i.kind))n=r(n,t,e.typeAnnotation||"coerce");else if(this.checkSubtype(t,i))return null}else n=r(n,t,e.typeAnnotation||"assert");}if(!(n instanceof Ne)&&"resolvedImage"!==n.type.kind&&this._isConstant(n)){const t=new He;try{n=new Ne(n.type,n.evaluate(t));}catch(t){return this.error(t.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Ke(this.registry,this._isConstant,n,e||null,i,this.errors)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new Tt(r,t));}checkSubtype(t,e){const r=Wt(t,e);return r&&this.error(r),r}}class Je{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new Ve(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new Ve(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return !1}}class tr{constructor(t,e){this.type=Dt,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);return r&&n?Qt(r.type,[Dt,$t,Ft,Vt,Ut])?new tr(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);if(!te(r,["string","array"]))throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return !0}}class er{constructor(t,e,r){this.type=Ft,this.needle=t,this.haystack=e,this.fromIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);if(!r||!n)return null;if(!Qt(r.type,[Dt,$t,Ft,Vt,Ut]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new er(r,n,i):null}return new er(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(t)),te(r,["string"])){const t=r.indexOf(e,n);return -1===t?-1:[...r.slice(0,t)].length}if(te(r,["array"]))return r.indexOf(e,n);throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return !1}}class rr{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(r){if(u.checkSubtype(r,Ue(t)))return null}else r=Ue(t);if(void 0!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length;}const c=e.parse(l,a,n);if(!c)return null;n=n||c.type,s.push(c);}const a=e.parse(t[1],1,Ut);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,n);return o?"value"!==a.type.kind&&e.concat(1).checkSubtype(r,a.type)?null:new rr(r,n,a,i,s,o):null}evaluate(t){const e=this.input.evaluate(t);return (Ue(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class nr{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class ir{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ft);if(!r||!n)return null;if(!Qt(r.type,[Ht(Ut),$t,Ut]))return e.error(`Expected first argument to be of type array or string, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new ir(r.type,r,n,i):null}return new ir(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);let n;if(this.endIndex&&(n=this.endIndex.evaluate(t)),te(e,["string"]))return [...e].slice(r,n).join("");if(te(e,["array"]))return e.slice(r,n);throw new Ve(`Expected first argument to be of type array or string, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return !1}}function sr(t,e){const r=t.length-1;let n,i,s=0,a=r,o=0;for(;s<=a;)if(o=Math.floor((s+a)/2),n=t[o],i=t[o+1],n<=e){if(o===r||ee))throw new Ve("Input is not a number.");a=o-1;}return 0}class ar{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',o);const u=e.parse(a,l,i);if(!u)return null;i=i||u.type,n.push([s,u]);}return new ar(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[sr(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function or(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var lr,ur,cr=function(){if(ur)return lr;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return ur=1,lr=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},lr}(),hr=or(cr);class pr{constructor(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e);}static interpolationFactor(t,e,r,n){let i=0;if("exponential"===t.name)i=fr(e,t.base,r,n);else if("linear"===t.name)i=fr(e,1,r,n);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new hr(s[0],s[1],s[2],s[3]).solve(fr(e,1,r,n));}return i}static parse(t,e){let[r,n,i,...s]=t;if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){const t=n[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:t};}else {if("cubic-bezier"!==n[0])return e.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const t=n.slice(1);if(4!==t.length||t.some((t=>"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,Ft),!i)return null;const a=[];let o=null;"interpolate-hcl"!==r&&"interpolate-lab"!==r||e.expectedType==Gt?e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType):o=Lt;for(let t=0;t=r)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,o);if(!u)return null;o=o||u.type,a.push([r,u]);}return ee(o,Ft)||ee(o,Ot)||ee(o,Lt)||ee(o,qt)||ee(o,Xt)||ee(o,Gt)||ee(o,Yt)||ee(o,Ht(Ft))?new pr(o,r,n,i,a):e.error(`Type ${Kt(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=sr(e,n),a=pr.interpolationFactor(this.interpolation,n,e[s],e[s+1]),o=r[s].evaluate(t),l=r[s+1].evaluate(t);switch(this.operator){case "interpolate":switch(this.type.kind){case "number":return Ae(o,l,a);case "color":return Me.interpolate(o,l,a);case "padding":return Ee.interpolate(o,l,a);case "colorArray":return Be.interpolate(o,l,a);case "numberArray":return Te.interpolate(o,l,a);case "variableAnchorOffsetCollection":return $e.interpolate(o,l,a);case "array":return ke(o,l,a);case "projectionDefinition":return Le.interpolate(o,l,a)}case "interpolate-hcl":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"hcl");case "colorArray":return Be.interpolate(o,l,a,"hcl")}case "interpolate-lab":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"lab");case "colorArray":return Be.interpolate(o,l,a,"lab")}}}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function fr(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}const dr={color:Me.interpolate,number:Ae,padding:Ee.interpolate,numberArray:Te.interpolate,colorArray:Be.interpolate,variableAnchorOffsetCollection:$e.interpolate,array:ke};class yr{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r=null;const n=e.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const n of t.slice(1)){const t=e.parse(n,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!t)return null;r=r||t.type,i.push(t);}if(!r)throw new Error("No output type");const s=n&&i.some((t=>Wt(n,t.type)));return new yr(s?Ut:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(t),r&&r instanceof De&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break;return r}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function mr(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function gr(t,e,r,n){return 0===n.compare(e,r)}function xr(t,e,r){const n="=="!==t&&"!="!==t;return class i{constructor(t,e,r){this.type=Dt,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const r=t[0];let s=e.parse(t[1],1,Ut);if(!s)return null;if(!mr(r,s.type))return e.concat(1).error(`"${r}" comparisons are not supported for type '${Kt(s.type)}'.`);let a=e.parse(t[2],2,Ut);if(!a)return null;if(!mr(r,a.type))return e.concat(2).error(`"${r}" comparisons are not supported for type '${Kt(a.type)}'.`);if(s.type.kind!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error(`Cannot compare types '${Kt(s.type)}' and '${Kt(a.type)}'.`);n&&("value"===s.type.kind&&"value"!==a.type.kind?s=new Ge(a.type,[s]):"value"!==s.type.kind&&"value"===a.type.kind&&(a=new Ge(s.type,[a])));let o=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error("Cannot use collator to compare non-string types.");if(o=e.parse(t[3],3,jt),!o)return null}return new i(s,a,o)}evaluate(i){const s=this.lhs.evaluate(i),a=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=Ue(s),r=Ue(a);if(e.kind!==r.kind||"string"!==e.kind&&"number"!==e.kind)throw new Ve(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=Ue(s),r=Ue(a);if("string"!==t.kind||"string"!==r.kind)return e(i,s,a)}return this.collator?r(i,s,a,this.collator.evaluate(i)):e(i,s,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return !0}}}const vr=xr("==",(function(t,e,r){return e===r}),gr),br=xr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !gr(0,e,r,n)})),wr=xr("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),Sr=xr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),Ar=xr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class kr{constructor(t,e,r){this.type=jt,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");const n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,Dt);if(!n)return null;const i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Dt);if(!i)return null;let s=null;return r.locale&&(s=e.parse(r.locale,1,$t),!s)?null:new kr(n,i,s)}evaluate(t){return new Ie(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);}outputDefined(){return !1}}class Mr{constructor(t,e,r,n,i){this.type=$t,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=e.parse(n.locale,1,$t),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,$t),!s))return null;let a=null;if(n["min-fraction-digits"]&&(a=e.parse(n["min-fraction-digits"],1,Ft),!a))return null;let o=null;return n["max-fraction-digits"]&&(o=e.parse(n["max-fraction-digits"],1,Ft),!o)?null:new Mr(r,i,s,a,o)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return !1}}class Ir{constructor(t){this.type=Nt,this.sections=t;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");const n=[];let i=!1;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&"object"==typeof s&&!Array.isArray(s)){i=!1;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,Ft),!t))return null;let r=null;if(s["text-font"]&&(r=e.parse(s["text-font"],1,Ht($t)),!r))return null;let a=null;if(s["text-color"]&&(a=e.parse(s["text-color"],1,Lt),!a))return null;let o=null;if(s["vertical-align"]){if("string"==typeof s["vertical-align"]&&!ze.includes(s["vertical-align"]))return e.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${s["vertical-align"]}' instead.`);if(o=e.parse(s["vertical-align"],1,$t),!o)return null}const l=n[n.length-1];l.scale=t,l.font=r,l.textColor=a,l.verticalAlign=o;}else {const s=e.parse(t[r],1,Ut);if(!s)return null;const a=s.type.kind;if("string"!==a&&"value"!==a&&"null"!==a&&"resolvedImage"!==a)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:s,scale:null,font:null,textColor:null,verticalAlign:null});}}return new Ir(n)}evaluate(t){return new Ce(this.sections.map((e=>{const r=e.content.evaluate(t);return Ue(r)===Zt?new Pe("",r,null,null,null,e.verticalAlign?e.verticalAlign.evaluate(t):null):new Pe(je(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null,e.verticalAlign?e.verticalAlign.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor),e.verticalAlign&&t(e.verticalAlign);}outputDefined(){return !1}}class zr{constructor(t){this.type=Zt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,$t);return r?new zr(r):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),r=De.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r}eachChild(t){t(this.input);}outputDefined(){return !1}}class Pr{constructor(t){this.type=Ft,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${Kt(r.type)} instead.`):new Pr(r):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return [...e].length;if(Array.isArray(e))return e.length;throw new Ve(`Expected value to be of type string or array, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return !1}}const Cr=8192;function Er(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*Cr),Math.round(n*i*Cr)]}function Tr(t,e){const r=Math.pow(2,e.z);return [(i=(t[0]/Cr+e.x)/r,360*i-180),(n=(t[1]/Cr+e.y)/r,360/Math.PI*Math.atan(Math.exp((180-360*n)*Math.PI/180))-90)];var n,i;}function Br(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function Vr(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function Fr(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],a=t[1]-r[1];return n*a-s*i==0&&n*s<=0&&i*a<=0}function $r(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!jr(t,e,r,n)||!jr(r,n,t,e));var i,s;}function Dr(t,e,r){for(const n of r)for(let r=0;r(i=t)[1]!=(a=o[e+1])[1]>i[1]&&i[0]<(a[0]-s[0])*(i[1]-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}var i,s,a;return n}function Or(t,e){for(const r of e)if(Lr(t,r))return !0;return !1}function Rr(t,e){for(const r of t)if(!Lr(r,e))return !1;for(let r=0;r0&&o<0||a<0&&o>0}function Nr(t,e,r){const n=[];for(let i=0;ir[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i;}Br(e,t);}function Xr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];Gr(n,e,r,i),a.push(n);}return a}function Zr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];Br(e,r),t.push(r);}a.push(t);}if(e[2]-e[0]<=i/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const n of t)Gr(n,e,r,i);}var o;return a}class Yr{constructor(t,e){this.type=Dt,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const r of e.features){const{type:e,coordinates:n}=r.geometry;"Polygon"===e&&t.push(n),"MultiPolygon"===e&&t.push(...n);}if(t.length)return new Yr(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new Yr(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new Yr(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Lr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Or(t,s))return !1}return !0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Rr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Ur(t,s))return !1}return !0}(t,this.geometries)}return !1}eachChild(){}outputDefined(){return !0}}let Hr=class{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}};function Kr(t,e,r=0,n=t.length-1,i=Wr){for(;n>r;){if(n-r>600){const s=n-r+1,a=e-r+1,o=Math.log(s),l=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*l*(s-l)/s)*(a-s/2<0?-1:1);Kr(t,e,Math.max(r,Math.floor(e-a*l/s+u)),Math.min(n,Math.floor(e+(s-a)*l/s+u)),i);}const s=t[e];let a=r,o=n;for(Jr(t,r,e),i(t[n],s)>0&&Jr(t,r,n);a0;)o--;}0===i(t[r],s)?Jr(t,r,o):(o++,Jr(t,o,n)),o<=e&&(r=o+1),e<=o&&(n=o-1);}}function Jr(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function Wr(t,e){return te?1:0}function Qr(t,e){if(t.length<=1)return [t];const r=[];let n,i;for(const e of t){const t=en(e);0!==t&&(e.area=Math.abs(t),void 0===i&&(i=t<0),i===t<0?(n&&r.push(n),n=[e]):n.push(e));}if(n&&r.push(n),e>1)for(let t=0;t1?(l=t[o+1][0],u=t[o+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function on(t,e){return e[0]-t[0]}function ln(t){return t[1]-t[0]+1}function un(t,e){return t[1]>=t[0]&&t[1]t[1])return [null,null];const r=ln(t);if(e){if(2===r)return [t,null];const e=Math.floor(r/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===r)return [t,null];const n=Math.floor(r/2)-1;return [[t[0],t[0]+n],[t[0]+n+1,t[1]]]}function hn(t,e){if(!un(e,t.length))return [1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=e[0];n<=e[1];++n)Br(r,t[n]);return r}function pn(t){const e=[1/0,1/0,-1/0,-1/0];for(const r of t)for(const t of r)Br(e,t);return e}function fn(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function dn(t,e,r){if(!fn(t)||!fn(e))return NaN;let n=0,i=0;return t[2]e[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if(Vr(i,s)){if(wn(t,e))return 0}else if(wn(e,t))return 0;let a=1/0;for(const n of t)for(let t=0,i=n.length,s=i-1;t0;){const i=a.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(ln(l)<=u){if(!un(l,t.length))return NaN;if(e){const e=bn(t,l,r,n);if(isNaN(e)||0===e)return e;s=Math.min(s,e);}else for(let e=l[0];e<=l[1];++e){const i=vn(t[e],r,n);if(s=Math.min(s,i),0===s)return 0}}else {const r=cn(l,e);Sn(a,s,n,t,o,r[0]),Sn(a,s,n,t,o,r[1]);}}return s}function Mn(t,e,r,n,i,s=1/0){let a=Math.min(s,i.distance(t[0],r[0]));if(0===a)return a;const o=new Hr([[0,[0,t.length-1],[0,r.length-1]]],on);for(;o.length>0;){const s=o.pop();if(s[0]>=a)continue;const l=s[1],u=s[2],c=e?50:100,h=n?50:100;if(ln(l)<=c&&ln(u)<=h){if(!un(l,t.length)&&un(u,r.length))return NaN;let s;if(e&&n)s=gn(t,l,r,u,i),a=Math.min(a,s);else if(e&&!n){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=yn(r[t],e,i),a=Math.min(a,s),0===a)return a}else if(!e&&n){const e=r.slice(u[0],u[1]+1);for(let r=l[0];r<=l[1];++r)if(s=yn(t[r],e,i),a=Math.min(a,s),0===a)return a}else s=xn(t,l,r,u,i),a=Math.min(a,s);}else {const s=cn(l,e),c=cn(u,n);An(o,a,i,t,r,s[0],c[0]),An(o,a,i,t,r,s[0],c[1]),An(o,a,i,t,r,s[1],c[0]),An(o,a,i,t,r,s[1],c[1]);}}return a}function In(t){return "MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class zn{constructor(t,e){this.type=Ft,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new zn(e,e.features.map((t=>In(t.geometry))).flat());if("Feature"===e.type)return new zn(e,In(e.geometry));if("type"in e&&"coordinates"in e)return new zn(e,In(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!1,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!1,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!1,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!0,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!0,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!0,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const r=t.geometry();if(0===r.length||0===r[0].length)return NaN;const n=Qr(r,0).map((e=>e.map((e=>e.map((e=>Tr([e.x,e.y],t.canonical))))))),i=new an(n[0][0][0][1]);let s=1/0;for(const t of e)for(const e of n){switch(t.type){case "Point":s=Math.min(s,kn([t.coordinates],!1,e,i,s));break;case "LineString":s=Math.min(s,kn(t.coordinates,!0,e,i,s));break;case "Polygon":s=Math.min(s,_n(e,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return !0}}class Pn{constructor(t){this.type=Ut,this.key=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=t[1];return null==r?e.error("Global state property must be defined."):"string"!=typeof r?e.error(`Global state property must be string, but found ${typeof t[1]} instead.`):new Pn(r)}evaluate(t){var e;const r=null===(e=t.globals)||void 0===e?void 0:e.globalState;return r&&0!==Object.keys(r).length?xe(r,this.key):null}eachChild(){}outputDefined(){return !1}}const Cn={"==":vr,"!=":br,">":_r,"<":wr,">=":Ar,"<=":Sr,array:Ge,at:Qe,boolean:Ge,case:nr,coalesce:yr,collator:kr,format:Ir,image:zr,in:tr,"index-of":er,interpolate:pr,"interpolate-hcl":pr,"interpolate-lab":pr,length:Pr,let:Je,literal:Ne,match:rr,number:Ge,"number-format":Mr,object:Ge,slice:ir,step:ar,string:Ge,"to-boolean":Ze,"to-color":Ze,"to-number":Ze,"to-string":Ze,var:We,within:Yr,distance:zn,"global-state":Pn};class En{constructor(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return !1}static parse(t,e){const r=t[0],n=En.definitions[r];if(!n)return e.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let o=null;for(const[n,s]of a){o=new Ke(e.registry,$n,e.path,null,e.scope);const a=[];let l=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(Kt).join(", ")})`:`(${Kt(e.type)}...)`;var e;})).join(" | "),n=[];for(let r=1;r{r=e?r&&$n(t):r&&t instanceof Ne;})),!!r&&Dn(t)&&On(t,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function Dn(t){if(t instanceof En){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}if(t instanceof Yr)return !1;if(t instanceof zn)return !1;let e=!0;return t.eachChild((t=>{e&&!Dn(t)&&(e=!1);})),e}function Ln(t){if(t instanceof En&&"feature-state"===t.name)return !1;let e=!0;return t.eachChild((t=>{e&&!Ln(t)&&(e=!1);})),e}function On(t,e){if(t instanceof En&&e.indexOf(t.name)>=0)return !1;let r=!0;return t.eachChild((t=>{r&&!On(t,e)&&(r=!1);})),r}function Rn(t){return {result:"success",value:t}}function Un(t){return {result:"error",value:t}}function jn(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Nn(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function qn(t){return !!t.expression&&t.expression.interpolated}function Gn(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Xn(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)&&Ue(t)===Rt}function Zn(t){return t}function Yn(t,e){const r=t.stops&&"object"==typeof t.stops[0][0],n=r||!(r||void 0!==t.property),i=t.type||(qn(e)?"exponential":"interval"),s=function(t){switch(t.type){case "color":return Me.parse;case "padding":return Ee.parse;case "numberArray":return Te.parse;case "colorArray":return Be.parse;default:return null}}(e);if(s&&((t=Et({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],s(t[1])]))),t.default=s(t.default?t.default:e.default)),t.colorSpace&&"rgb"!==(a=t.colorSpace)&&"hcl"!==a&&"lab"!==a)throw new Error(`Unknown color space: "${t.colorSpace}"`);var a;const o=function(t){switch(t){case "exponential":return Wn;case "interval":return Jn;case "categorical":return Kn;case "identity":return Qn;default:throw new Error(`Unknown function type "${t}"`)}}(i);let l,u;if("categorical"===i){l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0];}if(r){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>Wn({stops:i,base:t.base},e,r).evaluate(r,n)}}if(n){const r="exponential"===i?{name:"exponential",base:void 0!==t.base?t.base:1}:null;return {kind:"camera",interpolationType:r,interpolationFactor:pr.interpolationFactor.bind(void 0,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>o(t,e,r,l,u)}}return {kind:"source",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:void 0;return void 0===i?Hn(t.default,e.default):o(t,e,i,l,u)}}}function Hn(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Kn(t,e,r,n,i){return Hn(typeof r===i?n[r]:void 0,t.default,e.default)}function Jn(t,e,r){if("number"!==Gn(r))return Hn(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=sr(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function Wn(t,e,r){const n=void 0!==t.base?t.base:1;if("number"!==Gn(r))return Hn(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=sr(t.stops.map((t=>t[0])),r),a=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),o=t.stops[s][1],l=t.stops[s+1][1],u=dr[e.type]||Zn;return "function"==typeof o.evaluate?{evaluate(...e){const r=o.evaluate.apply(void 0,e),n=l.evaluate.apply(void 0,e);if(void 0!==r&&void 0!==n)return u(r,n,a,t.colorSpace)}}:u(o,l,a,t.colorSpace)}function Qn(t,e,r){switch(e.type){case "color":r=Me.parse(r);break;case "formatted":r=Ce.fromString(r.toString());break;case "resolvedImage":r=De.fromString(r.toString());break;case "padding":r=Ee.parse(r);break;case "colorArray":r=Be.parse(r);break;case "numberArray":r=Te.parse(r);break;default:Gn(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0);}return Hn(r,t.default,e.default)}En.register(Cn,{error:[{kind:"error"},[$t],(t,[e])=>{throw new Ve(e.evaluate(t))}],typeof:[$t,[Ut],(t,[e])=>Kt(Ue(e.evaluate(t)))],"to-rgba":[Ht(Ft,4),[Lt],(t,[e])=>{const[r,n,i,s]=e.evaluate(t).rgb;return [255*r,255*n,255*i,s]}],rgb:[Lt,[Ft,Ft,Ft],Tn],rgba:[Lt,[Ft,Ft,Ft,Ft],Tn],has:{type:Dt,overloads:[[[$t],(t,[e])=>Bn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Bn(e.evaluate(t),r.evaluate(t))]]},get:{type:Ut,overloads:[[[$t],(t,[e])=>Vn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Vn(e.evaluate(t),r.evaluate(t))]]},"feature-state":[Ut,[$t],(t,[e])=>Vn(e.evaluate(t),t.featureState||{})],properties:[Rt,[],t=>t.properties()],"geometry-type":[$t,[],t=>t.geometryType()],id:[Ut,[],t=>t.id()],zoom:[Ft,[],t=>t.globals.zoom],"heatmap-density":[Ft,[],t=>t.globals.heatmapDensity||0],elevation:[Ft,[],t=>t.globals.elevation||0],"line-progress":[Ft,[],t=>t.globals.lineProgress||0],accumulated:[Ut,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[Ft,Fn(Ft),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],"*":[Ft,Fn(Ft),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],"-":{type:Ft,overloads:[[[Ft,Ft],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[Ft],(t,[e])=>-e.evaluate(t)]]},"/":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],"%":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[Ft,[],()=>Math.LN2],pi:[Ft,[],()=>Math.PI],e:[Ft,[],()=>Math.E],"^":[Ft,[Ft,Ft],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[Ft,[Ft],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))],log2:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[Ft,[Ft],(t,[e])=>Math.sin(e.evaluate(t))],cos:[Ft,[Ft],(t,[e])=>Math.cos(e.evaluate(t))],tan:[Ft,[Ft],(t,[e])=>Math.tan(e.evaluate(t))],asin:[Ft,[Ft],(t,[e])=>Math.asin(e.evaluate(t))],acos:[Ft,[Ft],(t,[e])=>Math.acos(e.evaluate(t))],atan:[Ft,[Ft],(t,[e])=>Math.atan(e.evaluate(t))],min:[Ft,Fn(Ft),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[Ft,Fn(Ft),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[Ft,[Ft],(t,[e])=>Math.abs(e.evaluate(t))],round:[Ft,[Ft],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[Ft,[Ft],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[Ft,[Ft],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[Dt,[$t,Ut],(t,[e,r])=>t.properties()[e.value]===r.value],"filter-id-==":[Dt,[Ut],(t,[e])=>t.id()===e.value],"filter-type-==":[Dt,[$t],(t,[e])=>t.geometryType()===e.value],"filter-<":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],"filter-<=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],"filter->=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],"filter-has":[Dt,[Ut],(t,[e])=>e.value in t.properties()],"filter-has-id":[Dt,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[Dt,[Ht($t)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[Dt,[Ht(Ut)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[Dt,[$t,Ht(Ut)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[Dt,[$t,Ht(Ut)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(!r.evaluate(t))return !1;return !0}]]},any:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(r.evaluate(t))return !0;return !1}]]},"!":[Dt,[Dt],(t,[e])=>!e.evaluate(t)],"is-supported-script":[Dt,[$t],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return !r||r(e.evaluate(t))}],upcase:[$t,[$t],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[$t,[$t],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[$t,Fn(Ut),(t,e)=>e.map((e=>je(e.evaluate(t)))).join("")],"resolved-locale":[$t,[jt],(t,[e])=>e.evaluate(t).resolvedLocale()]});class ti{constructor(t,e,r){this.expression=t,this._warningHistory={},this._evaluator=new He,this._defaultValue=e?function(t){if("color"===t.type&&Xn(t.default))return new Me(0,0,0,0);switch(t.type){case "color":return Me.parse(t.default)||null;case "padding":return Ee.parse(t.default)||null;case "numberArray":return Te.parse(t.default)||null;case "colorArray":return Be.parse(t.default)||null;case "variableAnchorOffsetCollection":return $e.parse(t.default)||null;case "projectionDefinition":return Le.parse(t.default)||null;default:return void 0===t.default?null:t.default}}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null,this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s){this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new Ve(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function ei(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Cn}function ri(t,e,r){const n=new Ke(Cn,$n,[],e?function(t){const e={color:Lt,string:$t,number:Ft,enum:$t,boolean:Dt,formatted:Nt,padding:qt,numberArray:Xt,colorArray:Gt,projectionDefinition:Ot,resolvedImage:Zt,variableAnchorOffsetCollection:Yt};return "array"===t.type?Ht(e[t.value]||Ut,t.length):e[t.type]}(e):void 0),i=n.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return i?Rn(new ti(i,e,r)):Un(n.errors)}class ni{constructor(t,e,r){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}}class ii{constructor(t,e,r,n,i){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this.interpolationType=n,this._globalState=i;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?pr.interpolationFactor(this.interpolationType,t,e,r):0}}function si(t,e,r){const n=ri(t,e,r);if("error"===n.result)return n;const i=n.value.expression,s=Dn(i);if(!s&&!jn(e))return Un([new Tt("","data expressions not supported")]);const a=On(i,["zoom"]);if(!a&&!Nn(e))return Un([new Tt("","zoom expressions not supported")]);const o=oi(i);return o||a?o instanceof Tt?Un([o]):o instanceof pr&&!qn(e)?Un([new Tt("",'"interpolate" expressions cannot be used with this property')]):Rn(o?new ii(s?"camera":"composite",n.value,o.labels,o instanceof pr?o.interpolation:void 0,r):new ni(s?"constant":"source",n.value,r)):Un([new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class ai{constructor(t,e){this._parameters=t,this._specification=e,Et(this,Yn(this._parameters,this._specification));}static deserialize(t){return new ai(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function oi(t){let e=null;if(t instanceof Je)e=oi(t.result);else if(t instanceof yr){for(const r of t.args)if(e=oi(r),e)break}else (t instanceof ar||t instanceof pr)&&t.input instanceof En&&"zoom"===t.input.name&&(e=t);return e instanceof Tt||t.eachChild((t=>{const r=oi(t);r instanceof Tt?e=r:!e&&r?e=new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&r&&e!==r&&(e=new Tt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),e}function li(t,e=new Set){return t instanceof Pn&&e.add(t.key),t.eachChild((t=>{li(t,e);})),e}function ui(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case "has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case "in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case "!in":case "!has":case "none":return !1;case "==":case "!=":case ">":case ">=":case "<":case "<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case "any":case "all":for(const e of t.slice(1))if(!ui(e)&&"boolean"!=typeof e)return !1;return !0;default:return !0}}const ci={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function hi(t,e){if(null==t)return {filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};ui(t)||(t=di(t));const r=ri(t,ci,e);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return {filter:(t,e,n)=>r.value.evaluate(t,e,{},n),needGeometry:fi(t),getGlobalStateRefs:()=>li(r.value.expression)}}function pi(t,e){return te?1:0}function fi(t){if(!Array.isArray(t))return !1;if("within"===t[0]||"distance"===t[0])return !0;for(let e=1;e"===e||"<="===e||">="===e?yi(t[1],t[2],e):"any"===e?(r=t.slice(1),["any"].concat(r.map(di))):"all"===e?["all"].concat(t.slice(1).map(di)):"none"===e?["all"].concat(t.slice(1).map(di).map(xi)):"in"===e?mi(t[1],t.slice(2)):"!in"===e?xi(mi(t[1],t.slice(2))):"has"===e?gi(t[1]):"!has"!==e||xi(gi(t[1]));var r;}function yi(t,e,r){switch(t){case "$type":return [`filter-type-${r}`,e];case "$id":return [`filter-id-${r}`,e];default:return [`filter-${r}`,t,e]}}function mi(t,e){if(0===e.length)return !1;switch(t){case "$type":return ["filter-type-in",["literal",e]];case "$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(pi)]]:["filter-in-small",t,["literal",e]]}}function gi(t){switch(t){case "$type":return !0;case "$id":return ["filter-has-id"];default:return ["filter-has",t]}}function xi(t){return ["!",t]}function vi(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const r of t)e+=`${vi(r)},`;return `${e}]`}const r=Object.keys(t).sort();let n="{";for(let e=0;en.maximum?[new Ct(e,r,`${r} is greater than the maximum value ${n.maximum}`)]:[]}function Ii(t){const e=t.valueSpec,r=_i(t.value.type);let n,i,s,a={};const o="categorical"!==r&&void 0===t.value.property,l=!o,u="array"===Gn(t.value.stops)&&"array"===Gn(t.value.stops[0])&&"object"===Gn(t.value.stops[0][0]),c=Ai({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===r)return [new Ct(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const n=t.value;return e=e.concat(ki({key:t.key,value:n,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===Gn(n)&&0===n.length&&e.push(new Ct(t.key,n,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===r&&o&&c.push(new Ct(t.key,t.value,'missing required property "property"')),"identity"===r||t.value.stops||c.push(new Ct(t.key,t.value,'missing required property "stops"')),"exponential"===r&&t.valueSpec.expression&&!qn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!jn(t.valueSpec)?c.push(new Ct(t.key,t.value,"property functions not supported")):o&&!Nn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"zoom functions not supported"))),"categorical"!==r&&!u||void 0!==t.value.property||c.push(new Ct(t.key,t.value,'"property" property is required')),c;function h(t){let r=[];const n=t.value,o=t.key;if("array"!==Gn(n))return [new Ct(o,n,`array expected, ${Gn(n)} found`)];if(2!==n.length)return [new Ct(o,n,`array length 2 expected, length ${n.length} found`)];if(u){if("object"!==Gn(n[0]))return [new Ct(o,n,`object expected, ${Gn(n[0])} found`)];if(void 0===n[0].zoom)return [new Ct(o,n,"object stop key must have zoom")];if(void 0===n[0].value)return [new Ct(o,n,"object stop key must have value")];if(s&&s>_i(n[0].zoom))return [new Ct(o,n[0].zoom,"stop zoom values must appear in ascending order")];_i(n[0].zoom)!==s&&(s=_i(n[0].zoom),i=void 0,a={}),r=r.concat(Ai({key:`${o}[0]`,value:n[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Mi,value:p}}));}else r=r.concat(p({key:`${o}[0]`,value:n[0],validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},n));return ei(Si(n[1]))?r.concat([new Ct(`${o}[1]`,n[1],"expressions are not allowed in function stops.")]):r.concat(t.validateSpec({key:`${o}[1]`,value:n[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const o=Gn(t.value),l=_i(t.value),u=null!==t.value?t.value:s;if(n){if(o!==n)return [new Ct(t.key,u,`${o} stop domain type must match previous stop domain type ${n}`)]}else n=o;if("number"!==o&&"string"!==o&&"boolean"!==o)return [new Ct(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==o&&"categorical"!==r){let n=`number expected, ${o} found`;return jn(e)&&void 0===r&&(n+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new Ct(t.key,u,n)]}return "categorical"!==r||"number"!==o||isFinite(l)&&Math.floor(l)===l?"categorical"!==r&&"number"===o&&void 0!==i&&lnew Ct(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new Ct(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!On(r,["zoom","feature-state"]))return [new Ct(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!Dn(r))return [new Ct(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function Pi(t){const e=t.key,r=t.value,n=Gn(r);return "string"!==n?[new Ct(e,r,`color expected, ${n} found`)]:Me.parse(String(r))?[]:[new Ct(e,r,`color expected, "${r}" found`)]}function Ci(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${n.values.join(", ")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${Object.keys(n.values).join(", ")}], ${JSON.stringify(r)} found`)),i}function Ei(t){return ui(Si(t.value))?zi(Et({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):Ti(t)}function Ti(t){const e=t.value,r=t.key;if("array"!==Gn(e))return [new Ct(r,e,`array expected, ${Gn(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return [new Ct(r,e,"filter array must have at least 1 element")];switch(s=s.concat(Ci({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),_i(e[0])){case "<":case "<=":case ">":case ">=":e.length>=2&&"$type"===_i(e[1])&&s.push(new Ct(r,e,`"$type" cannot be use with operator "${e[0]}"`));case "==":case "!=":3!==e.length&&s.push(new Ct(r,e,`filter array for operator "${e[0]}" must have 3 elements`));case "in":case "!in":e.length>=2&&(i=Gn(e[1]),"string"!==i&&s.push(new Ct(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let a=2;a{t in r&&e.push(new Ct(n,r[t],`"${t}" is prohibited for ref layers`));})),i.layers.forEach((e=>{_i(e.id)===o&&(t=e);})),t?t.ref?e.push(new Ct(n,r.ref,"ref cannot reference another ref layer")):a=_i(t.type):e.push(new Ct(n,r.ref,`ref layer "${o}" not found`));}else if("background"!==a)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&_i(t.type);t?"vector"===s&&"raster"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster source`)):"raster-dem"!==s&&"hillshade"===a||"raster-dem"!==s&&"color-relief"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster-dem source`)):"raster"===s&&"raster"!==a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a vector source`)):"vector"!==s||r["source-layer"]?"raster-dem"===s&&"hillshade"!==a&&"color-relief"!==a?e.push(new Ct(n,r.source,"raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.")):"line"!==a||!r.paint||!r.paint["line-gradient"]||"geojson"===s&&t.lineMetrics||e.push(new Ct(n,r,`layer "${r.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new Ct(n,r,`layer "${r.id}" must specify a "source-layer"`)):e.push(new Ct(n,r.source,`source "${r.source}" not found`));}else e.push(new Ct(n,r,'missing required property "source"'));return e=e.concat(Ai({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:r,objectKey:"type"}),filter:Ei,layout:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Fi(Et({layerType:a},t))}}),paint:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Vi(Et({layerType:a},t))}})}})),e}function Di(t){const e=t.value,r=t.key,n=Gn(e);return "string"!==n?[new Ct(r,e,`string expected, ${n} found`)]:[]}const Li={promoteId:function({key:t,value:e}){if("string"===Gn(e))return Di({key:t,value:e});{const r=[];for(const n in e)r.push(...Di({key:`${t}.${n}`,value:e[n]}));return r}}};function Oi(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return [new Ct(r,e,'"type" is required')];const a=_i(e.type);let o;switch(a){case "vector":case "raster":return o=Ai({key:r,value:e,valueSpec:n[`source_${a.replace("-","_")}`],style:t.style,styleSpec:n,objectElementValidators:Li,validateSpec:s}),o;case "raster-dem":return o=function(t){var e;const r=null!==(e=t.sourceName)&&void 0!==e?e:"",n=t.value,i=t.styleSpec,s=i.source_raster_dem,a=t.style;let o=[];const l=Gn(n);if(void 0===n)return o;if("object"!==l)return o.push(new Ct("source_raster_dem",n,`object expected, ${l} found`)),o;const u="custom"===_i(n.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in n)!u&&c.includes(e)?o.push(new Ct(e,n[e],`In "${r}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?o=o.concat(t.validateSpec({key:e,value:n[e],valueSpec:s[e],validateSpec:t.validateSpec,style:a,styleSpec:i})):o.push(new Ct(e,n[e],`unknown property "${e}"`));return o}({sourceName:r,value:e,style:t.style,styleSpec:n,validateSpec:s}),o;case "geojson":if(o=Ai({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,validateSpec:s,objectElementValidators:Li}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],s="string"==typeof n?[n,["accumulated"],["get",t]]:n;o.push(...zi({key:`${r}.${t}.map`,value:i,expressionContext:"cluster-map"})),o.push(...zi({key:`${r}.${t}.reduce`,value:s,expressionContext:"cluster-reduce"}));}return o;case "video":return Ai({key:r,value:e,valueSpec:n.source_video,style:i,validateSpec:s,styleSpec:n});case "image":return Ai({key:r,value:e,valueSpec:n.source_image,style:i,validateSpec:s,styleSpec:n});case "canvas":return [new Ct(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Ci({key:`${r}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]}})}}function Ri(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("light",e,`object expected, ${a} found`)]),s;for(const a in e){const o=a.match(/^(.*)-transition$/);s=s.concat(o&&n[o[1]]&&n[o[1]].transition?t.validateSpec({key:a,value:e[a],valueSpec:r.transition,validateSpec:t.validateSpec,style:i,styleSpec:r}):n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);}return s}function Ui(t){const e=t.value,r=t.styleSpec,n=r.sky,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("sky",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a}function ji(t){const e=t.value,r=t.styleSpec,n=r.terrain,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("terrain",e,`object expected, ${a} found`)]),s;for(const a in e)s=s.concat(n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);return s}function Ni(t){let e=[];const r=t.value,n=t.key;if(Array.isArray(r)){const i=[],s=[];for(const a in r)r[a].id&&i.includes(r[a].id)&&e.push(new Ct(n,r,`all the sprites' ids must be unique, but ${r[a].id} is duplicated`)),i.push(r[a].id),r[a].url&&s.includes(r[a].url)&&e.push(new Ct(n,r,`all the sprites' URLs must be unique, but ${r[a].url} is duplicated`)),s.push(r[a].url),e=e.concat(Ai({key:`${n}[${a}]`,value:r[a],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:t.validateSpec}));return e}return Di({key:n,value:r})}function qi(t){return e=t.value,Boolean(e)&&e.constructor===Object?[]:[new Ct(t.key,t.value,`object expected, ${Gn(t.value)} found`)];var e;}const Gi={"*":()=>[],array:ki,boolean:function(t){const e=t.value,r=t.key,n=Gn(e);return "boolean"!==n?[new Ct(r,e,`boolean expected, ${n} found`)]:[]},number:Mi,color:Pi,constants:wi,enum:Ci,filter:Ei,function:Ii,layer:$i,object:Ai,source:Oi,light:Ri,sky:Ui,terrain:ji,projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("projection",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a},projectionDefinition:function(t){const e=t.key;let r=t.value;r=r instanceof String?r.valueOf():r;const n=Gn(r);return "array"!==n||function(t){return Array.isArray(t)&&3===t.length&&"string"==typeof t[0]&&"string"==typeof t[1]&&"number"==typeof t[2]}(r)||function(t){return !!["interpolate","step","literal"].includes(t[0])}(r)?["array","string"].includes(n)?[]:[new Ct(e,r,`projection expected, invalid type "${n}" found`)]:[new Ct(e,r,`projection expected, invalid array ${JSON.stringify(r)} found`)]},string:Di,formatted:function(t){return 0===Di(t).length?[]:zi(t)},resolvedImage:function(t){return 0===Di(t).length?[]:zi(t)},padding:function(t){const e=t.key,r=t.value;if("array"===Gn(r)){if(r.length<1||r.length>4)return [new Ct(e,r,`padding requires 1 to 4 values; ${r.length} values found`)];const n={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(r=r.concat(wi({key:"constants",value:t.constants}))),Ki(r)}function Hi(t){return function(e){return t({...e,validateSpec:Xi})}}function Ki(t){return [].concat(t).sort(((t,e)=>t.line-e.line))}function Ji(t){return function(...e){return Ki(t.apply(this,e))}}Yi.source=Ji(Hi(Oi)),Yi.sprite=Ji(Hi(Ni)),Yi.glyphs=Ji(Hi(Zi)),Yi.light=Ji(Hi(Ri)),Yi.sky=Ji(Hi(Ui)),Yi.terrain=Ji(Hi(ji)),Yi.state=Ji(Hi(qi)),Yi.layer=Ji(Hi($i)),Yi.filter=Ji(Hi(Ei)),Yi.paintProperty=Ji(Hi(Vi)),Yi.layoutProperty=Ji(Hi(Fi));const Wi=Yi,Qi=Wi.light,ts=Wi.sky,es=Wi.paintProperty,rs=Wi.layoutProperty;function ns(t,e){let r=!1;if(e&&e.length)for(const n of e)t.fire(new mt(new Error(n.message))),r=!0;return r}class is{constructor(t,e,r){const n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(let t=0;t=u[l+0]&&n>=u[l+1])?(a[h]=!0,s.push(i[h])):a[h]=!1;}}}}_forEachCell(t,e,r,n,i,s,a,o){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!o||o(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,r,n,u,s,a,o))return}}_convertFromCellCoord(t){return (t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let r=0;for(let t=0;t=0)continue;const s=t[n];i[n]=ss[r].shallow.indexOf(n)>=0?s:cs(s,e);}t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==r&&(i.$name=r),i}function hs(t){if(us(t))return t;if(Array.isArray(t))return t.map(hs);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=ls(t)||"Object";if(!ss[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:r}=ss[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const r of Object.keys(t)){if("$name"===r)continue;const i=t[r];n[r]=ss[e].shallow.indexOf(r)>=0?i:hs(i);}return n}class ps{constructor(){this.first=!0;}update(t,e){const r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Hiragana:t=>t>=12352&&t<=12447,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"CJK Unified Ideographs":t=>t>=19968&&t<=40959,"Hangul Syllables":t=>t>=44032&&t<=55215,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function ds(t){for(const e of t)if(bs(e.charCodeAt(0)))return !0;return !1}function ys(t){for(const e of t)if(!xs(e.charCodeAt(0)))return !1;return !0}function ms(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const gs=ms(["Arab","Dupl","Mong","Ougr","Syrc"]);function xs(t){return !gs.test(String.fromCodePoint(t))}const vs=ms(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function bs(t){return !(746!==t&&747!==t&&(t<4352||!(fs["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||fs["CJK Compatibility"](t)||fs["CJK Strokes"](t)||!(!fs["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||fs["Enclosed CJK Letters and Months"](t)||fs["Ideographic Description Characters"](t)||fs.Kanbun(t)||fs.Katakana(t)&&12540!==t||!(!fs["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!fs["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||fs["Vertical Forms"](t)||fs["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||vs.test(String.fromCodePoint(t)))))}function ws(t){return !(bs(t)||function(t){return !!(fs["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||fs["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||fs["Letterlike Symbols"](t)||fs["Number Forms"](t)||fs["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||fs["Control Pictures"](t)&&9251!==t||fs["Optical Character Recognition"](t)||fs["Enclosed Alphanumerics"](t)||fs["Geometric Shapes"](t)||fs["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||fs["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||fs["CJK Symbols and Punctuation"](t)||fs.Katakana(t)||fs["Private Use Area"](t)||fs["CJK Compatibility Forms"](t)||fs["Small Form Variants"](t)||fs["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}const _s=ms(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Ss(t){return _s.test(String.fromCodePoint(t))}function As(t,e){return !(!e&&Ss(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||fs.Khmer(t))}function ks(t){for(const e of t)if(Ss(e.charCodeAt(0)))return !0;return !1}const Ms=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{};}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL;}getState(){return {pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){if(Ms.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText,this.loadScriptResolve();}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(t,r){return e(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if("loading"!==t.pluginStatus)return this.setState(t),t;const e=t.pluginURL,n=new Promise((t=>{this.loadScriptResolve=t;}));r(e);const i=new Promise((t=>setTimeout((()=>t()),this.TIMEOUT)));if(yield Promise.race([n,i]),this.isParsed()){const t={pluginStatus:"loaded",pluginURL:e};return this.setState(t),t}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${e}`)}))}};class Is{constructor(t,e){this.isSupportedScript=zs,this.zoom=t,e?(this.now=e.now||0,this.fadeDuration=e.fadeDuration||0,this.zoomHistory=e.zoomHistory||new ps,this.transition=e.transition||{}):(this.now=0,this.fadeDuration=0,this.zoomHistory=new ps,this.transition={});}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}}}function zs(t){return function(t,e){for(const r of t)if(!As(r.charCodeAt(0),e))return !1;return !0}(t,"loaded"===Ms.getRTLTextPluginStatus())}class Ps{constructor(t,e,r){this.property=t,this.value=e,this.expression=function(t,e,r){if(Xn(t))return new ai(t,e);if(ei(t)){const n=si(t,e,r);if("error"===n.result)throw new Error(n.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return n.value}{let r=t;return "color"===e.type&&"string"==typeof t?r=Me.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"numberArray"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"colorArray"!==e.type||"string"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)?r=$e.parse(t):"projectionDefinition"===e.type&&"string"==typeof t&&(r=Le.parse(t)):r=Be.parse(t):r=Te.parse(t):r=Ee.parse(t),{globalStateRefs:new Set,_globalState:null,kind:"constant",evaluate:()=>r}}}(void 0===e?t.specification.default:e,t.specification,r);}isDataDriven(){return "source"===this.expression.kind||"composite"===this.expression.kind}getGlobalStateRefs(){return this.expression.globalStateRefs||new Set}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class Cs{constructor(t,e){this.property=t,this.value=new Ps(t,void 0,e);}transitioned(t,e){return new Ts(this.property,this.value,e,L({},t.transition,this.transition),t.now)}untransitioned(){return new Ts(this.property,this.value,null,{},0)}}class Es{constructor(t,e){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues),this._globalState=e;}getValue(t){return j(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].value=new Ps(this._values[t].property,null===e?void 0:j(e),this._globalState);}getTransition(t){return j(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].transition=j(e)||void 0;}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r);const n=this.getTransition(e);void 0!==n&&(t[`${e}-transition`]=n);}return t}transitioned(t,e){const r=new Bs(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new Bs(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class Ts{constructor(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(nn.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Rs{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new Is(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Is(Math.floor(e.zoom),e)),t.expression.evaluate(new Is(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Us{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)}interpolate(){return !1}}class js{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const r=t[e];r.specification.overridable&&this.overridableProperties.push(e);const n=this.defaultPropertyValues[e]=new Ps(r,void 0,void 0),i=this.defaultTransitionablePropertyValues[e]=new Cs(r,void 0);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}}}as("DataDrivenProperty",Ls),as("DataConstantProperty",Ds),as("CrossFadedDataDrivenProperty",Os),as("CrossFadedProperty",Rs),as("ColorRampProperty",Us);const Ns="-transition";class qs extends gt{constructor(t,e,r){if(super(),this.id=t.id,this.type=t.type,this._globalState=r,this._featureFilter={filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter,this._featureFilter=hi(t.filter,r)),e.layout&&(this._unevaluatedLayout=new Vs(e.layout,r)),e.paint)){this._transitionablePaint=new Es(e.paint,r);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new $s(e.paint);}}setFilter(t){this.filter=t,this._featureFilter=hi(t,this._globalState);}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}getLayoutAffectingGlobalStateRefs(){const t=new Set;if(this._unevaluatedLayout)for(const e in this._unevaluatedLayout._values){const r=this._unevaluatedLayout._values[e];for(const e of r.getGlobalStateRefs())t.add(e);}for(const e of this._featureFilter.getGlobalStateRefs())t.add(e);return t}getPaintAffectingGlobalStateRefs(){var t;const e=new globalThis.Map;if(this._transitionablePaint)for(const r in this._transitionablePaint._values){const n=this._transitionablePaint._values[r].value;for(const i of n.getGlobalStateRefs()){const s=null!==(t=e.get(i))&&void 0!==t?t:[];s.push({name:r,value:n.value}),e.set(i,s);}}return e}setLayoutProperty(t,e,r={}){null!=e&&this._validate(rs,`layers.${this.id}.layout.${t}`,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);}getPaintProperty(t){return t.endsWith(Ns)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(es,`layers.${this.id}.paint.${t}`,t,e,r))return !1;if(t.endsWith(Ns))return this._transitionablePaint.setTransition(t.slice(0,-11),e||void 0),!1;{const r=this._transitionablePaint._values[t],n="cross-faded-data-driven"===r.property.specification["property-type"],i=r.value.isDataDriven(),s=r.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const a=this._transitionablePaint._values[t].value;return a.isDataDriven()||i||n||this._handleOverridablePaintPropertyUpdate(t,s,a)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,r){return !1}isHidden(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),U(t,((t,e)=>!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return (!i||!1!==i.validate)&&ns(this,t.call(Wi,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:xt,style:{glyphs:!0,sprite:!0}}))}is3D(){return !1}isTileClipped(){return !1}hasOffscreenPass(){return !1}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof Fs&&jn(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1}}const Gs={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Xs{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class Zs{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Ys(t,e=1){let r=0,n=0;return {members:t.map((t=>{const i=Gs[t.type].BYTES_PER_ELEMENT,s=r=Hs(r,Math.max(e,i)),a=t.components||1;return n=Math.max(n,i),r+=i*a,{name:t.name,type:t.type,components:a,offset:s}})),size:Hs(r,Math.max(n,e)),alignment:e}}function Hs(t,e){return Math.ceil(t/e)*e}class Ks extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}Ks.prototype.bytesPerElement=4,as("StructArrayLayout2i4",Ks);class Js extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}Js.prototype.bytesPerElement=6,as("StructArrayLayout3i6",Js);class Ws extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}Ws.prototype.bytesPerElement=8,as("StructArrayLayout4i8",Ws);class Qs extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}Qs.prototype.bytesPerElement=12,as("StructArrayLayout2i4i12",Qs);class ta extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=4*t,l=8*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.uint8[l+4]=n,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=a,t}}ta.prototype.bytesPerElement=8,as("StructArrayLayout2i4ub8",ta);class ea extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}ea.prototype.bytesPerElement=8,as("StructArrayLayout2f8",ea);class ra extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,s,a,o,l,u)}emplace(t,e,r,n,i,s,a,o,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=r,this.uint16[h+2]=n,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=a,this.uint16[h+6]=o,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}ra.prototype.bytesPerElement=20,as("StructArrayLayout10ui20",ra);class na extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,a,o,l,u,c,h)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=a,this.uint16[f+6]=o,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}na.prototype.bytesPerElement=24,as("StructArrayLayout4i4ui4i24",na);class ia extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}ia.prototype.bytesPerElement=12,as("StructArrayLayout3f12",ia);class sa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}sa.prototype.bytesPerElement=4,as("StructArrayLayout1ul4",sa);class aa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,s,a,o,l)}emplace(t,e,r,n,i,s,a,o,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=r,this.int16[c+2]=n,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=a,this.uint32[h+3]=o,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}aa.prototype.bytesPerElement=20,as("StructArrayLayout6i1ul2ui20",aa);class oa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}oa.prototype.bytesPerElement=12,as("StructArrayLayout2i2i2i12",oa);class la extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.int16[o+6]=i,this.int16[o+7]=s,t}}la.prototype.bytesPerElement=16,as("StructArrayLayout2f1f2i16",la);class ua extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=16*t,l=4*t,u=8*t;return this.uint8[o+0]=e,this.uint8[o+1]=r,this.float32[l+1]=n,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=a,t}}ua.prototype.bytesPerElement=16,as("StructArrayLayout2ub2f2i16",ua);class ca extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}ca.prototype.bytesPerElement=6,as("StructArrayLayout3ui6",ca);class ha extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=r,this.uint16[x+2]=n,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=a,this.uint32[v+4]=o,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}ha.prototype.bytesPerElement=48,as("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",ha);class pa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I){const z=this.length;return this.resize(z+1),this.emplace(z,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I,z){const P=32*t,C=16*t;return this.int16[P+0]=e,this.int16[P+1]=r,this.int16[P+2]=n,this.int16[P+3]=i,this.int16[P+4]=s,this.int16[P+5]=a,this.int16[P+6]=o,this.int16[P+7]=l,this.uint16[P+8]=u,this.uint16[P+9]=c,this.uint16[P+10]=h,this.uint16[P+11]=p,this.uint16[P+12]=f,this.uint16[P+13]=d,this.uint16[P+14]=y,this.uint16[P+15]=m,this.uint16[P+16]=g,this.uint16[P+17]=x,this.uint16[P+18]=v,this.uint16[P+19]=b,this.uint16[P+20]=w,this.uint16[P+21]=_,this.uint16[P+22]=S,this.uint32[C+12]=A,this.float32[C+13]=k,this.float32[C+14]=M,this.uint16[P+30]=I,this.uint16[P+31]=z,t}}pa.prototype.bytesPerElement=64,as("StructArrayLayout8i15ui1ul2f2ui64",pa);class fa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}fa.prototype.bytesPerElement=4,as("StructArrayLayout1f4",fa);class da extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}da.prototype.bytesPerElement=12,as("StructArrayLayout1ui2f12",da);class ya extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t}}ya.prototype.bytesPerElement=8,as("StructArrayLayout1ul2ui8",ya);class ma extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}ma.prototype.bytesPerElement=4,as("StructArrayLayout2ui4",ma);class ga extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}ga.prototype.bytesPerElement=2,as("StructArrayLayout1ui2",ga);class xa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}xa.prototype.bytesPerElement=16,as("StructArrayLayout4f16",xa);class va extends Xs{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new r(this.anchorPointX,this.anchorPointY)}}va.prototype.size=20;class ba extends aa{get(t){return new va(this,t)}}as("CollisionBoxArray",ba);class wa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t;}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}wa.prototype.size=48;class _a extends ha{get(t){return new wa(this,t)}}as("PlacedSymbolArray",_a);class Sa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t;}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}Sa.prototype.size=64;class Aa extends pa{get(t){return new Sa(this,t)}}as("SymbolInstanceArray",Aa);class ka extends fa{getoffsetX(t){return this.float32[1*t+0]}}as("GlyphOffsetArray",ka);class Ma extends Js{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}as("SymbolLineVertexArray",Ma);class Ia extends Xs{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}Ia.prototype.size=12;class za extends da{get(t){return new Ia(this,t)}}as("TextAnchorOffsetArray",za);class Pa extends Xs{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}Pa.prototype.size=8;class Ca extends ya{get(t){return new Pa(this,t)}}as("FeatureIndexArray",Ca);class Ea extends Ks{}class Ta extends Ks{}class Ba extends Ks{}class Va extends Qs{}class Fa extends ta{}class $a extends ea{}class Da extends ra{}class La extends na{}class Oa extends ia{}class Ra extends sa{}class Ua extends oa{}class ja extends ua{}class Na extends ca{}class qa extends ma{}const Ga=Ys([{name:"a_pos",components:2,type:"Int16"}],4),{members:Xa}=Ga;class Za{constructor(t=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=t;}prepareSegment(t,e,r,n){const i=this.segments[this.segments.length-1];return t>Za.MAX_VERTEX_ARRAY_LENGTH&&q(`Max vertices per segment is ${Za.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${Za.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!i||i.vertexLength+t>Za.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n?this.createNewSegment(e,r,n):i}createNewSegment(t,e,r){const n={vertexOffset:t.length,primitiveOffset:e.length,vertexLength:0,primitiveLength:0,vaos:{}};return void 0!==r&&(n.sortKey=r),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(n),n}getOrCreateLatestSegment(t,e,r){return this.prepareSegment(0,t,e,r)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0;}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,r,n){return new Za([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function Ya(t,e){return 256*(t=$(Math.floor(t),0,255))+$(Math.floor(e),0,255)}Za.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,as("SegmentVector",Za);const Ha=Ys([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var Ka,Ja,Wa,Qa={exports:{}},to={exports:{}},eo={exports:{}},ro=function(){if(Wa)return Qa.exports;Wa=1;var t=(Ka||(Ka=1,to.exports=function(t,e){var r,n,i,s,a,o,l,u;for(n=t.length-(r=3&t.length),i=e,a=3432918353,o=461845907,u=0;u>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0}),to.exports),e=(Ja||(Ja=1,eo.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0}),eo.exports);return Qa.exports=t,Qa.exports.murmur3=t,Qa.exports.murmur2=e,Qa.exports}(),no=n(ro);class io{constructor(){this.ids=[],this.positions=[],this.indexed=!1;}add(t,e,r,n){this.ids.push(so(t)),this.positions.push(e,r,n);}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=so(t);let r=0,n=this.ids.length-1;for(;r>1;this.ids[t]>=e?n=t:r=t+1;}const i=[];for(;this.ids[r]===e;)i.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return i}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return ao(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}}static deserialize(t){const e=new io;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e}}function so(t){const e=+t;return !isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:no(String(t))}function ao(t,e,r,n){for(;r>1];let s=r-1,a=n+1;for(;;){do{s++;}while(t[s]i);if(s>=a)break;oo(t,s,a),oo(e,3*s,3*a),oo(e,3*s+1,3*a+1),oo(e,3*s+2,3*a+2);}a-r`u_${t}`)),this.type=r;}setUniform(t,e,r){t.set(r.constantOr(this.value));}getBinding(t,e,r){return "color"===this.type?new ho(t,e):new uo(t,e)}}class mo{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;}setUniform(t,e,r,n){const i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);}getBinding(t,e,r){return "u_pattern"===r.substr(0,9)?new co(t,e):new uo(t,e)}}class go{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?2:1,offset:0}))),this.paintVertexArray=new n;}populatePaintArray(t,e,r){const n=this.paintVertexArray.length,i=this.expression.evaluate(new Is(0,r),e,{},r.canonical,[],r.formattedSection);this.paintVertexArray.resize(t),this._setPaintValue(n,t,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(0,i),r,n);this._setPaintValue(t,e,s);}_setPaintValue(t,e,r){if("color"===this.type){const n=fo(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,r){const n=this.expression.evaluate(new Is(this.zoom,r),e,{},r.canonical,[],r.formattedSection),i=this.expression.evaluate(new Is(this.zoom+1,r),e,{},r.canonical,[],r.formattedSection),s=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(s,t,n,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(this.zoom,i),r,n),a=this.expression.evaluate(new Is(this.zoom+1,i),r,n);this._setPaintValue(t,e,s,a);}_setPaintValue(t,e,r,n){if("color"===this.type){const i=fo(r),s=fo(n);for(let r=t;r`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof go||r instanceof xo)for(let e=0;e!0){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new bo(n,e,r);this.needsUpload=!1,this._featureMap=new io,this._bufferOffset=0;}populatePaintArrays(t,e,r,n){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;}updatePaintArrays(t,e,r,n){for(const i of r)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,n)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}function _o(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function So(t,e,r){const n={color:{source:ea,composite:xa},number:{source:fa,composite:ea}},i=function(t){return {"line-pattern":{source:Da,composite:Da},"fill-pattern":{source:Da,composite:Da},"fill-extrusion-pattern":{source:Da,composite:Da}}[t]}(t);return i&&i[r]||n[e][r]}as("ConstantBinder",yo),as("CrossFadedConstantBinder",mo),as("SourceExpressionBinder",go),as("CrossFadedCompositeBinder",vo),as("CompositeExpressionBinder",xo),as("ProgramConfiguration",bo,{omit:["_buffers"]}),as("ProgramConfigurationSet",wo);const Ao=Math.pow(2,14)-1,ko=-Ao-1;function Mo(t){const e=P/t.extent,r=t.loadGeometry();for(let t=0;tr.x+1||sr.y+1)&&q("Geometry exceeds allowed extent, reduce your vector tile buffer size");}}return r}function Io(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?Mo(t):[]}}const zo=-32768;function Po(t,e,r,n,i){t.emplaceBack(zo+8*e+n,zo+8*r+i);}class Co{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Ta,this.indexArray=new Na,this.segments=new Za,this.programConfigurations=new wo(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){const n=this.layers[0],i=[];let s=null,a=!1,o="heatmap"===n.type;if("circle"===n.type){const t=n;s=t.layout.get("circle-sort-key"),a=!s.isConstant(),o=o||"map"===t.paint.get("circle-pitch-alignment");}const l=o?e.subdivisionGranularity.circle:1;for(const{feature:e,id:n,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=a?s.evaluate(u,{},r):void 0,h={id:n,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};i.push(h);}a&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of i){const{geometry:i,index:s,sourceLayerIndex:a}=n,o=t[s].feature;this.addFeature(n,i,s,r,l),e.featureIndex.insert(o,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Xa),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,r,n,i=1){let s;switch(i){case 1:s=[0,7];break;case 3:s=[0,2,5,7];break;case 5:s=[0,1,3,4,6,7];break;case 7:s=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${i}; valid values are 1, 3, 5, 7.`)}const a=s.length;for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=P||n<0||n>=P)continue;const i=this.segments.prepareSegment(a*a,this.layoutVertexArray,this.indexArray,t.sortKey),o=i.vertexLength;for(let t=0;t1){if(Fo(t,e))return !0;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function Oo(t,e){let r,n,i,s=!1;for(let a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s);}return s}function Ro(t,e){let r=!1;for(let n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-s.x)*(e.y-s.y)/(a.y-s.y)+s.x&&(r=!r);}return r}function Uo(t,e,r){const n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;const s=G(t,e,r[0]);return s!==G(t,e,r[1])||s!==G(t,e,r[2])||s!==G(t,e,r[3])}function jo(t,e,r){const n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function No(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function qo(t,e,n,i,s){if(!e[0]&&!e[1])return t;const a=r.convert(e)._mult(s);"viewport"===n&&a._rotate(-i);const o=[];for(let e=0;eKo(t,e,r,n)))}(l,i,a,o),f=u),Ho({queryGeometry:p,size:f,transform:i,unwrappedTileID:a,getElevation:o,pitchAlignment:h,pitchScale:c},n)}}class el extends Co{}let rl;as("HeatmapBucket",el,{omit:["layers"]});var nl={get paint(){return rl=rl||new js({"heatmap-radius":new Ls(xt.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Ls(xt.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Ds(xt.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Us(xt.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Ds(xt.paint_heatmap["heatmap-opacity"])})}};function il(t,{width:e,height:r},n,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*r*n)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*r*n}`)}else i=new Uint8Array(e*r*n);return t.width=e,t.height=r,t.data=i,t}function sl(t,{width:e,height:r},n){if(e===t.width&&r===t.height)return;const i=il({},{width:e,height:r},n);al(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,r)},n),t.width=e,t.height=r,t.data=i.data;}function al(t,e,r,n,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const a=t.data,o=e.data;if(a===o)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=a;const o=t.expression.evaluate(e);i.setPixel(n/4/r,s/4,o);};if(t.clips)for(let e=0,i=0;ethis.max&&(this.max=r),r=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)}unpack(t,e,r){return t*this.redFactor+e*this.greenFactor+r*this.blueFactor-this.baseShift}pack(t){return vl(t,this.getUnpackVector())}getPixels(){return new ll({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,a=r*this.dim+this.dim;switch(e){case -1:n=i-1;break;case 1:i=n+1;}switch(r){case -1:s=a-1;break;case 1:a=s+1;}const o=-e*this.dim,l=-r*this.dim;for(let e=s;e0)for(let i=e;i=e;i-=n)s=Zl(i/n|0,t[i],t[i+1],s);return s&&Ul(s,s.next)&&(Yl(s),s=s.next),s}function Ml(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!Ul(n,n.next)&&0!==Rl(n.prev,n,n.next))n=n.next;else {if(Yl(n),n=e=n.prev,n===n.next)break;r=!0;}}while(r||n!==e);return e}function Il(t,e,r,n,i,s,a){if(!t)return;!a&&s&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=Fl(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let s=null;for(e=0;i;){e++;let a=i,o=0;for(let t=0;t0||l>0&&a;)0!==o&&(0===l||!a||i.z<=a.z)?(n=i,i=i.nextZ,o--):(n=a,a=a.nextZ,l--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;i=a;}s.nextZ=null,r*=2;}while(e>1)}(i);}(t,n,i,s);let o=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?Pl(t,n,i,s):zl(t))e.push(l.i,t.i,u.i),Yl(t),t=u.next,o=u.next;else if((t=u)===o){a?1===a?Il(t=Cl(Ml(t),e),e,r,n,i,s,2):2===a&&El(t,e,r,n,i,s):Il(Ml(t),e,r,n,i,s,1);break}}}function zl(t){const e=t.prev,r=t,n=t.next;if(Rl(e,r,n)>=0)return !1;const i=e.x,s=r.x,a=n.x,o=e.y,l=r.y,u=n.y,c=Math.min(i,s,a),h=Math.min(o,l,u),p=Math.max(i,s,a),f=Math.max(o,l,u);let d=n.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&Ll(i,o,s,l,a,u,d.x,d.y)&&Rl(d.prev,d,d.next)>=0)return !1;d=d.next;}return !0}function Pl(t,e,r,n){const i=t.prev,s=t,a=t.next;if(Rl(i,s,a)>=0)return !1;const o=i.x,l=s.x,u=a.x,c=i.y,h=s.y,p=a.y,f=Math.min(o,l,u),d=Math.min(c,h,p),y=Math.max(o,l,u),m=Math.max(c,h,p),g=Fl(f,d,e,r,n),x=Fl(y,m,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}return !0}function Cl(t,e){let r=t;do{const n=r.prev,i=r.next.next;!Ul(n,i)&&jl(n,r,r.next,i)&&Gl(n,i)&&Gl(i,n)&&(e.push(n.i,r.i,i.i),Yl(r),Yl(r.next),r=t=i),r=r.next;}while(r!==t);return Ml(r)}function El(t,e,r,n,i,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Ol(a,t)){let o=Xl(a,t);return a=Ml(a,a.next),o=Ml(o,o.next),Il(a,e,r,n,i,s,0),void Il(o,e,r,n,i,s,0)}t=t.next;}a=a.next;}while(a!==t)}function Tl(t,e){let r=t.x-e.x;return 0===r&&(r=t.y-e.y,0===r)&&(r=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)),r}function Bl(t,e){const r=function(t,e){let r=e;const n=t.x,i=t.y;let s,a=-1/0;if(Ul(t,r))return r;do{if(Ul(t,r.next))return r.next;if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){const t=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(t<=n&&t>a&&(a=t,s=r.x=r.x&&r.x>=l&&n!==r.x&&Dl(is.x||r.x===s.x&&Vl(s,r)))&&(s=r,c=e);}r=r.next;}while(r!==o);return s}(t,e);if(!r)return e;const n=Xl(r,t);return Ml(n,n.next),Ml(r,r.next)}function Vl(t,e){return Rl(t.prev,t,e.prev)<0&&Rl(e.next,t,t.next)<0}function Fl(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function $l(t){let e=t,r=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(r-a)*(e-o)&&(r-a)*(s-o)>=(i-a)*(n-o)}function Ll(t,e,r,n,i,s,a,o){return !(t===a&&e===o)&&Dl(t,e,r,n,i,s,a,o)}function Ol(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&jl(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(Gl(t,e)&&Gl(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Rl(t.prev,t,e.prev)||Rl(t,e.prev,e))||Ul(t,e)&&Rl(t.prev,t,t.next)>0&&Rl(e.prev,e,e.next)>0)}function Rl(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Ul(t,e){return t.x===e.x&&t.y===e.y}function jl(t,e,r,n){const i=ql(Rl(t,e,r)),s=ql(Rl(t,e,n)),a=ql(Rl(r,n,t)),o=ql(Rl(r,n,e));return i!==s&&a!==o||!(0!==i||!Nl(t,r,e))||!(0!==s||!Nl(t,n,e))||!(0!==a||!Nl(r,t,n))||!(0!==o||!Nl(r,e,n))}function Nl(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function ql(t){return t>0?1:t<0?-1:0}function Gl(t,e){return Rl(t.prev,t,t.next)<0?Rl(t,e,t.next)>=0&&Rl(t,t.prev,e)>=0:Rl(t,e,t.prev)<0||Rl(t,t.next,e)<0}function Xl(t,e){const r=Hl(t.i,t.x,t.y),n=Hl(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function Zl(t,e,r,n){const i=Hl(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Yl(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 Hl(t,e,r){return {i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class Kl{constructor(t,e){if(e>t)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=t,this._minGranularity=e;}getGranularityForZoomLevel(t){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||e>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const r=0|Math.round(t),n=0|Math.round(e),i=this._getKey(r,n);if(this._vertexDictionary.has(i))return this._vertexDictionary.get(i);const s=this._vertexBuffer.length/2;return this._vertexDictionary.set(i,s),this._vertexBuffer.push(r,n),s}_subdivideTrianglesScanline(t){if(this._granularity<2)return function(t,e){const r=[];for(let n=0;n0?(r.push(i),r.push(a),r.push(s)):(r.push(i),r.push(s),r.push(a));}return r}(this._vertexBuffer,t);const e=[],r=t.length;for(let n=0;n=1||v<=0)||y&&(oi)){u>=n&&u<=i&&s.push(r[(t+1)%3]);continue}!y&&x>0&&s.push(this._vertexToIndex(a+p*x,o+f*x));const b=a+p*Math.max(x,0),w=a+p*Math.min(v,1);d||this._generateIntraEdgeVertices(s,a,o,l,u,b,w),!y&&v<1&&s.push(this._vertexToIndex(a+p*v,o+f*v)),(y||u>=n&&u<=i)&&s.push(r[(t+1)%3]),!y&&(u<=n||u>=i)&&this._generateInterEdgeVertices(s,a,o,l,u,c,h,w,n,i);}return s}_generateIntraEdgeVertices(t,e,r,n,i,s,a){const o=n-e,l=i-r,u=0===l,c=u?Math.min(e,n):Math.min(s,a),h=u?Math.max(e,n):Math.max(s,a),p=Math.floor(c/this._granularityCellSize)+1,f=Math.ceil(h/this._granularityCellSize)-1;if(u?e=p;n--){const i=n*this._granularityCellSize;t.push(this._vertexToIndex(i,r+l*(i-e)/o));}}_generateInterEdgeVertices(t,e,r,n,i,s,a,o,l,u){const c=i-r,h=s-n,p=a-i,f=(l-i)/p,d=(u-i)/p,y=Math.min(f,d),m=Math.max(f,d),g=n+h*y;let x=Math.floor(Math.min(g,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(g,o)/this._granularityCellSize)-1,b=o=1||m<=0){const t=r-a,n=s+(e-s)*Math.min((l-a)/t,(u-a)/t);x=Math.floor(Math.min(n,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(n,o)/this._granularityCellSize)-1,b=o0?u:l;if(b)for(let e=x;e<=v;e++)t.push(this._vertexToIndex(e*this._granularityCellSize,_));else for(let e=v;e>=x;e--)t.push(this._vertexToIndex(e*this._granularityCellSize,_));}_generateOutline(t){const e=[];for(const r of t){const t=ru(r,this._granularity,!0),n=this._pointArrayToIndices(t),i=[];for(let t=1;ti!=(s===Wl)?(t.push(e),t.push(r),t.push(this._vertexToIndex(n,s)),t.push(r),t.push(this._vertexToIndex(i,s)),t.push(this._vertexToIndex(n,s))):(t.push(r),t.push(e),t.push(this._vertexToIndex(n,s)),t.push(this._vertexToIndex(i,s)),t.push(r),t.push(this._vertexToIndex(n,s)));}_fillPoles(t,e,r){const n=this._vertexBuffer,i=P,s=t.length;for(let a=2;a80*r){o=t[0],l=t[1];let e=o,n=l;for(let s=r;se&&(e=r),i>n&&(n=i);}u=Math.max(e-o,n-l),u=0!==u?32767/u:0;}return Il(s,a,r,o,l,u,0),a}(r,n),e=this._convertIndices(r,t);i=this._subdivideTrianglesScanline(e);}catch(t){console.error(t);}let s=[];return e&&(s=this._generateOutline(t)),this._ensureNoPoleVertices(),this._handlePoles(i),{verticesFlattened:this._vertexBuffer,indicesTriangles:i,indicesLineList:s}}_convertIndices(t,e){const r=[];for(let n=0;n0?(Math.floor(x/o)+1)*o:(Math.ceil(x/o)-1)*o,e=y>0?(Math.floor(v/o)+1)*o:(Math.ceil(v/o)-1)*o,n=Math.abs(x-t),i=Math.abs(v-e),s=Math.abs(x-c),a=Math.abs(v-h),u=p?n/m:Number.POSITIVE_INFINITY,b=f?i/g:Number.POSITIVE_INFINITY;if((s<=n||!p)&&(a<=i||!f))break;if(u=0?a-1:s-1,i=(o+1)%s,l=t[2*e[n]],u=t[2*e[i]],c=t[2*e[a]],h=t[2*e[a]+1],p=t[2*e[o]+1];let f=!1;if(lu)f=!1;else {const r=p-h,s=-(t[2*e[o]]-c),a=h((u-c)*r+(t[2*e[i]+1]-h)*s)*a&&(f=!0);}if(f){const t=e[n],i=e[a],l=e[o];t!==i&&t!==l&&i!==l&&r.push(l,i,t),a--,a<0&&(a=s-1);}else {const t=e[i],n=e[a],l=e[o];t!==n&&t!==l&&n!==l&&r.push(l,n,t),o++,o>=s&&(o=0);}if(n===i)break}}function iu(t,e,r,n,i,s,a,o,l){const u=i.length/2,c=a&&o&&l;if(uZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,y=!0,m=!0,g=!0,c=0);const x=su(a,n,s,o,p,y,u),v=su(a,n,s,o,f,m,u),b=su(a,n,s,o,d,g,u);r.emplaceBack(c+x-l,c+v-l,c+b-l),u.primitiveLength++;}}(e,r,n,i,s,t),c&&function(t,e,r,n,i,s){const a=[];for(let t=0;tZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,d=!0,y=!0,c=0);const m=su(a,n,s,o,i,d,u),g=su(a,n,s,o,h,y,u);r.emplaceBack(c+m-l,c+g-l),u.primitiveLength++;}}}(a,r,o,i,l,t),e.forceNewSegmentOnNextPrepare(),null==a||a.forceNewSegmentOnNextPrepare();}function su(t,e,r,n,i,s,a){if(s){const s=n.count;return r(e[2*i],e[2*i+1]),t[i]=n.count,n.count++,a.vertexLength++,s}return t[i]}class au{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Ba,this.indexArray=new Na,this.indexArray2=new qa,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.segments2=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("fill",this.layers,e);const n=this.layers[0].layout.get("fill-sort-key"),i=!n.isConstant(),s=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=Io(a,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),c,r))continue;const h=i?n.evaluate(c,{},r,e.availableImages):void 0,p={id:o,properties:a.properties,type:a.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:Mo(a),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("fill",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,_l),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,r,n,i,s){for(const t of Qr(e,500)){const e=eu(t,n,s.fill.getGranularityForZoomLevel(n.z)),r=this.layoutVertexArray;iu(((t,e)=>{r.emplaceBack(t,e);}),this.segments,this.layoutVertexArray,this.indexArray,e.verticesFlattened,e.indicesTriangles,this.segments2,this.indexArray2,e.indicesLineList);}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}}let ou,lu;as("FillBucket",au,{omit:["layers","patternFeatures"]});var uu={get paint(){return lu=lu||new js({"fill-antialias":new Ds(xt.paint_fill["fill-antialias"]),"fill-opacity":new Ls(xt.paint_fill["fill-opacity"]),"fill-color":new Ls(xt.paint_fill["fill-color"]),"fill-outline-color":new Ls(xt.paint_fill["fill-outline-color"]),"fill-translate":new Ds(xt.paint_fill["fill-translate"]),"fill-translate-anchor":new Ds(xt.paint_fill["fill-translate-anchor"]),"fill-pattern":new Os(xt.paint_fill["fill-pattern"])})},get layout(){return ou=ou||new js({"fill-sort-key":new Ls(xt.layout_fill["fill-sort-key"])})}};class cu extends qs{constructor(t,e){super(t,uu,e);}recalculate(t,e){super.recalculate(t,e);const r=this.paint._values["fill-outline-color"];"constant"===r.value.kind&&void 0===r.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);}createBucket(t){return new au(t)}queryRadius(){return No(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:t,geometry:e,transform:r,pixelsToTileUnits:n}){return Bo(qo(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-r.bearingInRadians,n),e)}isTileClipped(){return !0}}const hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),pu=Ys([{name:"a_centroid",components:2,type:"Int16"}],4),{members:fu}=hu;class du{constructor(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this.id=void 0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(yu,this,e);}loadGeometry(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos,n=[];let i,s=1,a=0,o=0,l=0;for(;t.pos>3;}if(a--,1===s||2===s)o+=t.readSVarint(),l+=t.readSVarint(),1===s&&(i&&n.push(i),i=[]),i&&i.push(new r(o,l));else {if(7!==s)throw new Error(`unknown command ${s}`);i&&i.push(i[0].clone());}}return i&&n.push(i),n}bbox(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos;let r=1,n=0,i=0,s=0,a=1/0,o=-1/0,l=1/0,u=-1/0;for(;t.pos>3;}if(n--,1===r||2===r)i+=t.readSVarint(),s+=t.readSVarint(),io&&(o=i),su&&(u=s);else if(7!==r)throw new Error(`unknown command ${r}`)}return [a,l,o,u]}toGeoJSON(t,e,r){const n=this.extent*Math.pow(2,r),i=this.extent*t,s=this.extent*e,a=this.loadGeometry();function o(t){return [360*(t.x+i)/n-180,360/Math.PI*Math.atan(Math.exp((1-2*(t.y+s)/n)*Math.PI))-90]}function l(t){return t.map(o)}let u;if(1===this.type){const t=[];for(const e of a)t.push(e[0]);const e=l(t);u=1===t.length?{type:"Point",coordinates:e[0]}:{type:"MultiPoint",coordinates:e};}else if(2===this.type){const t=a.map(l);u=1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t};}else {if(3!==this.type)throw new Error("unknown feature type");{const t=function(t){const e=t.length;if(e<=1)return [t];const r=[];let n,i;for(let s=0;s=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];const e=this._pbf.readVarint()+this._pbf.pos;return new du(this._pbf,e,this.extent,this._keys,this._values)}}function xu(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){let e=null;const r=t.readVarint()+t.pos;for(;t.pos>3;e=1===r?t.readString():2===r?t.readFloat():3===r?t.readDouble():4===r?t.readVarint64():5===r?t.readVarint():6===r?t.readSVarint():7===r?t.readBoolean():null;}if(null==e)throw new Error("unknown feature value");return e}(r));}class vu{constructor(t,e){this.layers=t.readFields(bu,{},e);}}function bu(t,e,r){if(3===t){const t=new gu(r,r.readVarint()+r.pos);t.length&&(e[t.name]=t);}}const wu=Math.pow(2,13);function _u(t,e,r,n,i,s,a,o){t.emplaceBack(e,r,2*Math.floor(n*wu)+a,i*wu*2,s*wu*2,Math.round(o));}class Su{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Va,this.centroidVertexArray=new Ea,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.features=[],this.hasPattern=Sl("fill-extrusion",this.layers,e);for(const{feature:n,id:i,index:s,sourceLayerIndex:a}of t){const t=this.layers[0]._featureFilter.needGeometry,o=Io(n,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),o,r))continue;const l={id:i,sourceLayerIndex:a,index:s,geometry:t?o.geometry:Mo(n),properties:n.properties,type:n.type,patterns:{}};this.hasPattern?this.features.push(Al("fill-extrusion",this.layers,l,{zoom:this.zoom},e)):this.addFeature(l,l.geometry,s,r,{},e.subdivisionGranularity),e.featureIndex.insert(n,l.geometry,s,a,this.index,!0);}}addFeatures(t,e,r){for(const n of this.features){const{geometry:i}=n;this.addFeature(n,i,n.index,e,r,t.subdivisionGranularity);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,fu),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,pu.members,!0),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy());}addFeature(t,e,r,n,i,s){for(const r of Qr(e,500)){const e={x:0,y:0,sampleCount:0},i=this.layoutVertexArray.length;this.processPolygon(e,n,t,r,s);const a=this.layoutVertexArray.length-i,o=Math.floor(e.x/e.sampleCount),l=Math.floor(e.y/e.sampleCount);for(let t=0;t{_u(u,t,e,0,0,1,1,0);}),this.segments,this.layoutVertexArray,this.indexArray,l.verticesFlattened,l.indicesTriangles);}_generateSideFaces(t,e){let r=0;for(let n=1;nZa.MAX_VERTEX_ARRAY_LENGTH&&(e.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const a=i.sub(s)._perp()._unit(),o=s.dist(i);r+o>32768&&(r=0),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,1,r),r+=o,_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,1,r);const l=e.segment.vertexLength;this.indexArray.emplaceBack(l,l+2,l+1),this.indexArray.emplaceBack(l+1,l+2,l+3),e.segment.vertexLength+=4,e.segment.primitiveLength+=2;}}}function Au(t,e){for(let r=0;rP)||t.y===e.y&&(t.y<0||t.y>P)}function Mu(t){return t.every((t=>t.x<0))||t.every((t=>t.x>P))||t.every((t=>t.y<0))||t.every((t=>t.y>P))}let Iu;as("FillExtrusionBucket",Su,{omit:["layers","features"]});var zu={get paint(){return Iu=Iu||new js({"fill-extrusion-opacity":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Os(xt["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class Pu extends qs{constructor(t,e){super(t,zu,e);}createBucket(t){return new Su(t)}queryRadius(){return No(this.paint.get("fill-extrusion-translate"))}is3D(){return !0}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a,pixelPosMatrix:o}){const l=qo(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-s.bearingInRadians,a),u=this.paint.get("fill-extrusion-height").evaluate(e,n),c=this.paint.get("fill-extrusion-base").evaluate(e,n),h=function(t,e){const n=[];for(const i of t){const t=[i.x,i.y,0,1];A(t,t,e),n.push(new r(t[0]/t[3],t[1]/t[3]));}return n}(l,o),p=function(t,e,n,i){const s=[],a=[],o=i[8]*e,l=i[9]*e,u=i[10]*e,c=i[11]*e,h=i[8]*n,p=i[9]*n,f=i[10]*n,d=i[11]*n;for(const e of t){const t=[],n=[];for(const s of e){const e=s.x,a=s.y,y=i[0]*e+i[4]*a+i[12],m=i[1]*e+i[5]*a+i[13],g=i[2]*e+i[6]*a+i[14],x=i[3]*e+i[7]*a+i[15],v=g+u,b=x+c,w=y+h,_=m+p,S=g+f,A=x+d,k=new r((y+o)/b,(m+l)/b);k.z=v/b,t.push(k);const M=new r(w/A,_/A);M.z=S/A,n.push(M);}s.push(t),a.push(n);}return [s,a]}(i,c,u,o);return function(t,e,r){let n=1/0;Bo(r,e)&&(n=Eu(r,e[0]));for(let i=0;it.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new Fa,this.layoutVertexArray2=new $a,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("line",this.layers,e);const n=this.layers[0].layout.get("line-sort-key"),i=!n.isConstant(),s=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=i?n.evaluate(u,{},r):void 0,h={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("line",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,Fu)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Bu),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return {start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i,s){const a=this.layers[0].layout,o=a.get("line-join").evaluate(t,{}),l=a.get("line-cap"),u=a.get("line-miter-limit"),c=a.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,o,l,u,c,n,s);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}addLine(t,e,r,n,i,s,a,o){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,t=ru(t,a?o.line.getGranularityForZoomLevel(a.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[u-1].equals(t[u-2]);)u--;let c=0;for(;c0;if(w&&e>c){const t=f.dist(d);if(t>2*h){const e=f.sub(f.sub(d)._mult(h/t)._round());this.updateDistance(d,e),this.addCurrentVertex(e,m,0,0,p),d=e;}}const S=d&&y;let A=S?r:l?"butt":n;if(S&&"round"===A&&(vi&&(A="bevel"),"bevel"===A&&(v>2&&(A="flipbevel"),v100)a=g.mult(-1);else {const t=v*m.add(g).mag()/m.sub(g).mag();a._perp()._mult(t*(_?-1:1));}this.addCurrentVertex(f,a,0,0,p),this.addCurrentVertex(f,a.mult(-1),0,0,p);}else if("bevel"===A||"fakeround"===A){const t=-Math.sqrt(v*v-1),e=_?t:0,r=_?0:t;if(d&&this.addCurrentVertex(f,m,e,r,p),"fakeround"===A){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*h){const e=f.add(y.sub(f)._mult(h/t)._round());this.updateDistance(f,e),this.addCurrentVertex(e,g,0,0,p),f=e;}}}}addCurrentVertex(t,e,r,n,i,s=!1){const a=e.y*n-e.x,o=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,!1,r,i),this.addHalfVertex(t,a,o,s,!0,-n,i),this.distance>Du/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,r,n,i,s));}addHalfVertex({x:t,y:e},r,n,i,s,a,o){const l=.5*(this.lineClips?this.scaledDistance*(Du-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,u,this.e2),o.primitiveLength++),s?this.e2=u:this.e1=u;}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}}let Ou,Ru;as("LineBucket",Lu,{omit:["layers","patternFeatures"]});var Uu={get paint(){return Ru=Ru||new js({"line-opacity":new Ls(xt.paint_line["line-opacity"]),"line-color":new Ls(xt.paint_line["line-color"]),"line-translate":new Ds(xt.paint_line["line-translate"]),"line-translate-anchor":new Ds(xt.paint_line["line-translate-anchor"]),"line-width":new Ls(xt.paint_line["line-width"]),"line-gap-width":new Ls(xt.paint_line["line-gap-width"]),"line-offset":new Ls(xt.paint_line["line-offset"]),"line-blur":new Ls(xt.paint_line["line-blur"]),"line-dasharray":new Rs(xt.paint_line["line-dasharray"]),"line-pattern":new Os(xt.paint_line["line-pattern"]),"line-gradient":new Us(xt.paint_line["line-gradient"])})},get layout(){return Ou=Ou||new js({"line-cap":new Ds(xt.layout_line["line-cap"]),"line-join":new Ls(xt.layout_line["line-join"]),"line-miter-limit":new Ds(xt.layout_line["line-miter-limit"]),"line-round-limit":new Ds(xt.layout_line["line-round-limit"]),"line-sort-key":new Ls(xt.layout_line["line-sort-key"])})}};class ju extends Ls{possiblyEvaluate(t,e){return e=new Is(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=L({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}let Nu;class qu extends qs{constructor(t,e){super(t,Uu,e),this.gradientVersion=0,Nu||(Nu=new ju(Uu.paint.properties["line-width"].specification),Nu.useIntegerZoom=!0);}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return void 0!==t._styleExpression}(t)&&t._styleExpression.expression instanceof ar,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=Nu.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t);}createBucket(t){return new Lu(t)}queryRadius(t){const e=t,r=Gu(jo("line-width",this,e),jo("line-gap-width",this,e)),n=jo("line-offset",this,e);return r/2+Math.abs(n)+No(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a}){const o=qo(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-s.bearingInRadians,a),l=a/2*Gu(this.paint.get("line-width").evaluate(e,n),this.paint.get("line-gap-width").evaluate(e,n)),u=this.paint.get("line-offset").evaluate(e,n);return u&&(i=function(t,e){const n=[];for(let i=0;i=3)for(let e=0;e0?e+2*t:t}const Xu=Ys([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Zu=Ys([{name:"a_projected_pos",components:3,type:"Float32"}],4);Ys([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Yu=Ys([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Ys([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const Hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Ku=Ys([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Ju(t,e,r){return t.sections.forEach((t=>{t.text=function(t,e,r){const n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Ms.applyArabicShaping&&(t=Ms.applyArabicShaping(t)),t}(t.text,e,r);})),t}Ys([{name:"triangle",components:3,type:"Uint16"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Ys([{type:"Float32",name:"offsetX"}]),Ys([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Ys([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const Wu={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Qu=24;const tc=4294967296,ec=1/tc,rc="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class nc{constructor(t=new Uint8Array(16)){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length;}readFields(t,e,r=this.length){for(;this.pos>3,i=this.pos;this.type=7&r,t(n,e,this),this.pos===i&&this.skip(r);}return e}readMessage(t,e){return this.readFields(t,e,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*tc;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*tc;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const e=this.buf;let r,n;return n=e[this.pos++],r=127&n,n<128?r:(n=e[this.pos++],r|=(127&n)<<7,n<128?r:(n=e[this.pos++],r|=(127&n)<<14,n<128?r:(n=e[this.pos++],r|=(127&n)<<21,n<128?r:(n=e[this.pos],r|=(15&n)<<28,function(t,e,r){const n=r.buf;let i,s;if(s=n[r.pos++],i=(112&s)>>4,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<3,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<10,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<17,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<24,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(1&s)<<31,s<128)return ic(t,i,e);throw new Error("Expected varint not more than 10 bytes")}(r,t,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2==1?(t+1)/-2:t/2}readBoolean(){return Boolean(this.readVarint())}readString(){const t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&rc?rc.decode(this.buf.subarray(e,t)):function(t,e,r){let n="",i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+u>r)break;1===u?e<128&&(l=e):2===u?(s=t[i+1],128==(192&s)&&(l=(31&e)<<6|63&s,l<=127&&(l=null))):3===u?(s=t[i+1],a=t[i+2],128==(192&s)&&128==(192&a)&&(l=(15&e)<<12|(63&s)<<6|63&a,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===u&&(s=t[i+1],a=t[i+2],o=t[i+3],128==(192&s)&&128==(192&a)&&128==(192&o)&&(l=(15&e)<<18|(63&s)<<12|(63&a)<<6|63&o,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,u=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=u;}return n}(this.buf,e,t)}readBytes(){const t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e}readPackedVarint(t=[],e){const r=this.readPackedEnd();for(;this.pos127;);else if(2===e)this.pos=this.readVarint()+this.pos;else if(5===e)this.pos+=4;else {if(1!==e)throw new Error(`Unimplemented type: ${e}`);this.pos+=8;}}writeTag(t,e){this.writeVarint(t<<3|e);}realloc(t){let e=this.length||16;for(;e268435455||t<0?function(t,e){let r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(r=~(-t%4294967296),n=~(-t/4294967296),4294967295^r?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){const r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(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(t){this.writeVarint(t<0?2*-t-1:2*t);}writeBoolean(t){this.writeVarint(+t);}writeString(t){t=String(t),this.realloc(4*t.length),this.pos++;const e=this.pos;this.pos=function(t,e,r){for(let n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);const r=this.pos-e;r>=128&&sc(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4;}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8;}writeBytes(t){const e=t.length;this.writeVarint(e),this.realloc(e);for(let r=0;r=128&&sc(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;}writeMessage(t,e,r){this.writeTag(t,2),this.writeRawMessage(e,r);}writePackedVarint(t,e){e.length&&this.writeMessage(t,ac,e);}writePackedSVarint(t,e){e.length&&this.writeMessage(t,oc,e);}writePackedBoolean(t,e){e.length&&this.writeMessage(t,cc,e);}writePackedFloat(t,e){e.length&&this.writeMessage(t,lc,e);}writePackedDouble(t,e){e.length&&this.writeMessage(t,uc,e);}writePackedFixed32(t,e){e.length&&this.writeMessage(t,hc,e);}writePackedSFixed32(t,e){e.length&&this.writeMessage(t,pc,e);}writePackedFixed64(t,e){e.length&&this.writeMessage(t,fc,e);}writePackedSFixed64(t,e){e.length&&this.writeMessage(t,dc,e);}writeBytesField(t,e){this.writeTag(t,2),this.writeBytes(e);}writeFixed32Field(t,e){this.writeTag(t,5),this.writeFixed32(e);}writeSFixed32Field(t,e){this.writeTag(t,5),this.writeSFixed32(e);}writeFixed64Field(t,e){this.writeTag(t,1),this.writeFixed64(e);}writeSFixed64Field(t,e){this.writeTag(t,1),this.writeSFixed64(e);}writeVarintField(t,e){this.writeTag(t,0),this.writeVarint(e);}writeSVarintField(t,e){this.writeTag(t,0),this.writeSVarint(e);}writeStringField(t,e){this.writeTag(t,2),this.writeString(e);}writeFloatField(t,e){this.writeTag(t,5),this.writeFloat(e);}writeDoubleField(t,e){this.writeTag(t,1),this.writeDouble(e);}writeBooleanField(t,e){this.writeVarintField(t,+e);}}function ic(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function sc(t,e,r){const n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(let e=r.pos-1;e>=t;e--)r.buf[e+n]=r.buf[e];}function ac(t,e){for(let r=0;re.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();e&&t=0&&r>=t&&kc[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e);}substring(t,e){const r=new Sc;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}getMaxImageSize(t){let e=0,r=0;for(let n=0;n=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Ac(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=Sc.fromFeature(e,s);let g;p===t.ao.vertical&&m.verticalizePunctuation();const{processBidirectionalText:x,processStyledBidirectionalText:v}=Ms;if(x&&1===m.sections.length){g=[];const t=x(m.toString(),Bc(m,c,a,r,i,d));for(const e of t){const t=new Sc;t.text=e,t.sections=m.sections;for(let r=0;r=0;let u=0;for(let r=0;ru){const t=Math.ceil(s/u);i*=t/a,a=t;}return {x1:n,y1:i,x2:n+s,y2:i+a}}function Nc(t,e,r,n,i,s){const a=t.image;let o;if(a.content){const t=a.content,e=a.pixelRatio||1;o=[t[0]/e,t[1]/e,a.displaySize[0]-t[2]/e,a.displaySize[1]-t[3]/e];}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===r||"both"===r?(f=i[0]+l-n[3],h=i[0]+u+n[1]):(f=i[0]+(l+u-a.displaySize[0])/2,h=f+a.displaySize[0]);const d=e.top*s,y=e.bottom*s;return "height"===r||"both"===r?(c=i[1]+d-n[0],p=i[1]+y+n[2]):(c=i[1]+(d+y-a.displaySize[1])/2,p=c+a.displaySize[1]),{image:a,top:c,right:h,bottom:p,left:f,collisionPadding:o}}const qc=128,Gc=32640;function Xc(t,e){const{expression:r}=e;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new Is(t+1))};if("source"===r.kind)return {kind:"source"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;it.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];const r=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Xc(this.zoom,r["text-size"]),this.iconSizeData=Xc(this.zoom,r["icon-size"]);const n=this.layers[0].layout,i=n.get("symbol-sort-key"),s=n.get("symbol-z-order");this.canOverlap="never"!==Zc(n,"text-overlap","text-allow-overlap")||"never"!==Zc(n,"icon-overlap","icon-allow-overlap")||n.get("text-ignore-placement")||n.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!i.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===n.get("symbol-placement")&&(this.writingModes=n.get("text-writing-mode").map((e=>t.ao[e]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID;}createArrays(){this.text=new Wc(new wo(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new Wc(new wo(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new ka,this.lineVertexArray=new Ma,this.symbolInstances=new Aa,this.textAnchorOffsets=new za;}calculateGlyphDependencies(t,e,r,n,i){for(let s=0;s0)&&("constant"!==a.value.kind||a.value.value.length>0),c="constant"!==l.value.kind||!!l.value.value||Object.keys(l.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!u&&!c)return;const p=r.iconDependencies,f=r.glyphDependencies,d=r.availableImages,y=new Is(this.zoom);for(const{feature:r,id:o,index:l,sourceLayerIndex:m}of e){const e=i._featureFilter.needGeometry,g=Io(r,e);if(!i._featureFilter.filter(y,g,n))continue;let x,v;if(e||(g.geometry=Mo(r)),u){const t=i.getValueAndResolveTokens("text-field",g,n,d),e=Ce.factory(t),r=this.hasRTLText=this.hasRTLText||Jc(e);(!r||"unavailable"===Ms.getRTLTextPluginStatus()||r&&Ms.isParsed())&&(x=Ju(e,i,g));}if(c){const t=i.getValueAndResolveTokens("icon-image",g,n,d);v=t instanceof De?t:De.fromString(t);}if(!x&&!v)continue;const b=this.sortFeaturesByKey?h.evaluate(g,{},n):void 0;if(this.features.push({id:o,text:x,icon:v,index:l,sourceLayerIndex:m,geometry:g.geometry,properties:r.properties,type:du.types[r.type],sortKey:b}),v&&(p[v.name]=!0),x){const e=a.evaluate(g,{},n).join(","),r="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(t.ao.vertical)>=0;for(const t of x.sections)if(t.image)p[t.image.name]=!0;else {const n=ds(x.toString()),i=t.fontStack||e,s=f[i]=f[i]||{};this.calculateGlyphDependencies(t.text,s,r,this.allowVerticalPlacement,n);}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++;}function a(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function o(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return `${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}));}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(void 0!==t.segment){let r=t.dist(e[t.segment+1]),n=t.dist(e[t.segment]);const i={};for(let n=t.segment+1;n=0;r--)i[r]={x:e[r].x,y:e[r].y,tileUnitDistanceFromAnchor:n},r>0&&(n+=e[r-1].dist(e[r]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,r)=>{t>=0&&r.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t);})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}let eh,rh;as("SymbolBucket",th,{omit:["layers","collisionBoxArray","features","compareText"]}),th.MAX_GLYPHS=65535,th.addDynamicAttributes=Kc;var nh={get paint(){return rh=rh||new js({"icon-opacity":new Ls(xt.paint_symbol["icon-opacity"]),"icon-color":new Ls(xt.paint_symbol["icon-color"]),"icon-halo-color":new Ls(xt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Ls(xt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Ls(xt.paint_symbol["icon-halo-blur"]),"icon-translate":new Ds(xt.paint_symbol["icon-translate"]),"icon-translate-anchor":new Ds(xt.paint_symbol["icon-translate-anchor"]),"text-opacity":new Ls(xt.paint_symbol["text-opacity"]),"text-color":new Ls(xt.paint_symbol["text-color"],{runtimeType:Lt,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new Ls(xt.paint_symbol["text-halo-color"]),"text-halo-width":new Ls(xt.paint_symbol["text-halo-width"]),"text-halo-blur":new Ls(xt.paint_symbol["text-halo-blur"]),"text-translate":new Ds(xt.paint_symbol["text-translate"]),"text-translate-anchor":new Ds(xt.paint_symbol["text-translate-anchor"])})},get layout(){return eh=eh||new js({"symbol-placement":new Ds(xt.layout_symbol["symbol-placement"]),"symbol-spacing":new Ds(xt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Ds(xt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Ls(xt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Ds(xt.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new Ds(xt.layout_symbol["icon-allow-overlap"]),"icon-overlap":new Ds(xt.layout_symbol["icon-overlap"]),"icon-ignore-placement":new Ds(xt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Ds(xt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Ds(xt.layout_symbol["icon-rotation-alignment"]),"icon-size":new Ls(xt.layout_symbol["icon-size"]),"icon-text-fit":new Ds(xt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Ds(xt.layout_symbol["icon-text-fit-padding"]),"icon-image":new Ls(xt.layout_symbol["icon-image"]),"icon-rotate":new Ls(xt.layout_symbol["icon-rotate"]),"icon-padding":new Ls(xt.layout_symbol["icon-padding"]),"icon-keep-upright":new Ds(xt.layout_symbol["icon-keep-upright"]),"icon-offset":new Ls(xt.layout_symbol["icon-offset"]),"icon-anchor":new Ls(xt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Ds(xt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Ds(xt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Ds(xt.layout_symbol["text-rotation-alignment"]),"text-field":new Ls(xt.layout_symbol["text-field"]),"text-font":new Ls(xt.layout_symbol["text-font"]),"text-size":new Ls(xt.layout_symbol["text-size"]),"text-max-width":new Ls(xt.layout_symbol["text-max-width"]),"text-line-height":new Ds(xt.layout_symbol["text-line-height"]),"text-letter-spacing":new Ls(xt.layout_symbol["text-letter-spacing"]),"text-justify":new Ls(xt.layout_symbol["text-justify"]),"text-radial-offset":new Ls(xt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Ds(xt.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Ls(xt.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Ls(xt.layout_symbol["text-anchor"]),"text-max-angle":new Ds(xt.layout_symbol["text-max-angle"]),"text-writing-mode":new Ds(xt.layout_symbol["text-writing-mode"]),"text-rotate":new Ls(xt.layout_symbol["text-rotate"]),"text-padding":new Ds(xt.layout_symbol["text-padding"]),"text-keep-upright":new Ds(xt.layout_symbol["text-keep-upright"]),"text-transform":new Ls(xt.layout_symbol["text-transform"]),"text-offset":new Ls(xt.layout_symbol["text-offset"]),"text-allow-overlap":new Ds(xt.layout_symbol["text-allow-overlap"]),"text-overlap":new Ds(xt.layout_symbol["text-overlap"]),"text-ignore-placement":new Ds(xt.layout_symbol["text-ignore-placement"]),"text-optional":new Ds(xt.layout_symbol["text-optional"])})}};class ih{constructor(t){if(void 0===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:Vt,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return !1}serialize(){return null}}as("FormatSectionOverride",ih,{omit:["defaultValue"]});class sh extends qs{constructor(t,e){super(t,nh,e);}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const r of t)e.indexOf(r)<0&&e.push(r);this.layout._values["text-writing-mode"]=e;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||ei(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>t&&r in t?String(t[r]):""))}(e.properties,i)}createBucket(t){return new th(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of nh.paint.overridableProperties){if(!sh.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new ih(e),n=new ti(r,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new ni("source",n):new ii("composite",n,e.value.zoomStops),this.paint._values[t]=new Fs(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,r){return !(!this.layout||e.isDataDriven()||r.isDataDriven())&&sh.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get("text-field"),n=nh.paint.properties[e];let i=!1;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=!0)};if("constant"===r.value.kind&&r.value.value instanceof Ce)s(r.value.value.sections);else if("source"===r.value.kind||"composite"===r.value.kind){const t=e=>{i||(e instanceof Ne&&Ue(e.value)===Nt?s(e.value.sections):e instanceof Ir?s(e.sections):e.eachChild(t));},e=r.value;e._styleExpression&&t(e._styleExpression.expression);}return i}}let ah;var oh={get paint(){return ah=ah||new js({"background-color":new Ds(xt.paint_background["background-color"]),"background-pattern":new Rs(xt.paint_background["background-pattern"]),"background-opacity":new Ds(xt.paint_background["background-opacity"])})}};class lh extends qs{constructor(t,e){super(t,oh,e);}}let uh;var ch={get paint(){return uh=uh||new js({"raster-opacity":new Ds(xt.paint_raster["raster-opacity"]),"raster-hue-rotate":new Ds(xt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Ds(xt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Ds(xt.paint_raster["raster-brightness-max"]),"raster-saturation":new Ds(xt.paint_raster["raster-saturation"]),"raster-contrast":new Ds(xt.paint_raster["raster-contrast"]),"raster-resampling":new Ds(xt.paint_raster["raster-resampling"]),"raster-fade-duration":new Ds(xt.paint_raster["raster-fade-duration"])})}};class hh extends qs{constructor(t,e){super(t,ch,e);}}class ph extends qs{constructor(t,e){super(t,{},e),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},this.implementation=t;}is3D(){return "3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return !1}serialize(){throw new Error("Custom layers cannot be serialized")}}class fh{constructor(t){this._methodToThrottle=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle();});}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle();}),0));}remove(){delete this._channel,this._methodToThrottle=()=>{};}}const dh={once:!0},yh=6371008.8;class mh{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new mh(D(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return yh*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof mh)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new mh(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new mh(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const gh=2*Math.PI*yh;function xh(t){return gh*Math.cos(t*Math.PI/180)}function vh(t){return (180+t)/360}function bh(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function wh(t,e){return t/xh(e)}function _h(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}function Sh(t,e){return t*xh(_h(e))}class Ah{constructor(t,e,r=0){this.x=+t,this.y=+e,this.z=+r;}static fromLngLat(t,e=0){const r=mh.convert(t);return new Ah(vh(r.lng),bh(r.lat),wh(e,r.lat))}toLngLat(){return new mh(360*this.x-180,_h(this.y))}toAltitude(){return Sh(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/gh*(t=_h(this.y),1/Math.cos(t*Math.PI/180));var t;}}function kh(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}class Mh{constructor(t,e,r){if(!function(t,e,r){return !(t<0||t>25||r<0||r>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,r))throw new Error(`x=${e}, y=${r}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=r,this.key=Ph(0,t,t,e,r);}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,r){const n=(s=this.y,a=this.z,o=kh(256*(i=this.x),256*(s=Math.pow(2,a)-s-1),a),l=kh(256*(i+1),256*(s+1),a),o[0]+","+o[1]+","+l[0]+","+l[1]);var i,s,a,o,l;const u=function(t,e,r){let n,i="";for(let s=t;s>0;s--)n=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,n)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new r((t.x*e-this.x)*P,(t.y*e-this.y)*P)}toString(){return `${this.z}/${this.x}/${this.y}`}}class Ih{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Ph(t,e.z,e.z,e.x,e.y);}}class zh{constructor(t,e,r,n,i){if(this.terrainRttPosMatrix32f=null,t= z; overscaledZ = ${t}; z = ${r}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Mh(r,+n,+i),this.key=Ph(e,t,r,n,i);}clone(){return new zh(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new zh(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new zh(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const r=this.canonical.z-t;return t>this.canonical.z?Ph(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Ph(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}isChildOf(t){if(t.wrap!==this.wrap)return !1;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new zh(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new zh(e,this.wrap,e,r,n),new zh(e,this.wrap,e,r+1,n),new zh(e,this.wrap,e,r,n+1),new zh(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.ythis.maxX||this.minY>this.maxY)&&(this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0),this}shrinkBy(t){return this.expandBy(-t)}map(t){const e=new Eh;return e.extend(t(new r(this.minX,this.minY))),e.extend(t(new r(this.maxX,this.minY))),e.extend(t(new r(this.minX,this.maxY))),e.extend(t(new r(this.maxX,this.maxY))),e}static fromPoints(t){const e=new Eh;for(const r of t)e.extend(r);return e}contains(t){return t.x>=this.minX&&t.x<=this.maxX&&t.y>=this.minY&&t.y<=this.maxY}empty(){return this.minX>this.maxX}width(){return this.maxX-this.minX}height(){return this.maxY-this.minY}covers(t){return !this.empty()&&!t.empty()&&t.minX>=this.minX&&t.maxX<=this.maxX&&t.minY>=this.minY&&t.maxY<=this.maxY}intersects(t){return !this.empty()&&!t.empty()&&t.minX<=this.maxX&&t.maxX>=this.minX&&t.minY<=this.maxY&&t.maxY>=this.minY}}class Th{constructor(t){this._stringToNumber={},this._numberToString=[];for(let e=0;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class Bh{constructor(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}class Vh{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new is(P,16,0),this.grid3D=new is(P,16,0),this.featureIndexArray=new Ca,this.promoteId=e;}insert(t,e,r,n,i,s){const a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);const o=s?this.grid3D:this.grid;for(let t=0;t=0&&n[3]>=0&&o.insert(a,n[0],n[1],n[2],n[3]);}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new vu(new nc(this.rawTileData)).layers,this.sourceLayerCoder=new Th(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,n,i){this.loadVTLayers();const s=t.params,a=P/t.tileSize/t.scale,o=hi(s.filter,s.globalState),l=t.queryGeometry,u=t.queryPadding*a,c=Eh.fromPoints(l),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=Eh.fromPoints(t.cameraQueryGeometry).expandBy(u),f=this.grid3D.query(p.minX,p.minY,p.maxX,p.maxY,((e,n,i,s)=>function(t,e,n,i,s){for(const r of t)if(e<=r.x&&n<=r.y&&i>=r.x&&s>=r.y)return !0;const a=[new r(e,n),new r(e,s),new r(i,s),new r(i,n)];if(t.length>2)for(const e of a)if(Ro(t,e))return !0;for(let e=0;e(p||(p=Mo(e)),r.queryIntersectsFeature({queryGeometry:l,feature:e,featureState:n,geometry:p,zoom:this.z,transform:t.transform,pixelsToTileUnits:a,pixelPosMatrix:t.pixelPosMatrix,unwrappedTileID:this.tileID.toUnwrapped(),getElevation:t.getElevation}))));}return d}loadMatchingFeature(t,e,r,n,i,s,a,o,l,u,c){const h=this.bucketLayerIDs[e];if(s&&!h.some((t=>s.has(t))))return;const p=this.sourceLayerCoder.decode(r),f=this.vtLayers[p].feature(n);if(i.needGeometry){const t=Io(f,!0);if(!i.filter(new Is(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new Is(this.tileID.overscaledZ),f))return;const d=this.getId(f,p);for(let e=0;e{const a=e instanceof $s?e.get(s):null;return a&&a.evaluate?a.evaluate(r,n,i):a}))}function $h(t,e){return e-t}function Dh(t,e,n,i,s){const a=[];for(let o=0;o=i&&c.x>=i||(o.x>=i?o=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round():c.x>=i&&(c=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round()),o.y>=s&&c.y>=s||(o.y>=s?o=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round():c.y>=s&&(c=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round()),u&&o.equals(u[u.length-1])||(u=[o],a.push(u)),u.push(c)))));}}return a}as("FeatureIndex",Vh,{omit:["rawTileData","sourceLayerCoder"]});class Lh extends r{constructor(t,e,r,n){super(t,e),this.angle=r,void 0!==n&&(this.segment=n);}clone(){return new Lh(this.x,this.y,this.angle,this.segment)}}function Oh(t,e,r,n,i){if(void 0===e.segment||0===r)return !0;let s=e,a=e.segment+1,o=0;for(;o>-r/2;){if(a--,a<0)return !1;o-=t[a].dist(s),s=t[a];}o+=t[a].dist(t[a+1]),a++;const l=[];let u=0;for(;on;)u-=l.shift().angleDelta;if(u>i)return !1;a++,o+=e.dist(r);}return !0}function Rh(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=dr.number(n.x,i.x,c),p=dr.number(n.y,i.y,c),f=new Lh(h,p,i.angleTo(n),r);return f._round(),!a||Oh(t,f,o,a,e)?f:void 0}l+=s;}}function qh(t,e,r,n,i,s,a,o,l){const u=Uh(n,s,a),c=jh(n,i),h=c*a,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new Lh(g,x,y,e);r._round(),n&&!Oh(t,r,s,n,i)||f.push(r);}}h+=d;}return o||f.length||a||(f=Gh(t,h/2,r,n,i,s,a,!0,l)),f}function Xh(t,e,n,i){const s=[],a=t.image,o=a.pixelRatio,l=a.paddedRect.w-2,u=a.paddedRect.h-2;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=a.stretchX||[[0,l]],p=a.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=l-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,S=m,A=0,k=g;if(a.content&&i){const e=a.content,r=e[2]-e[0],n=e[3]-e[1];(a.textFitWidth||a.textFitHeight)&&(c=jc(t)),x=Zh(h,0,e[0]),b=Zh(p,0,e[1]),v=Zh(h,e[0],e[2]),w=Zh(p,e[1],e[3]),_=e[0]-x,A=e[1]-b,S=r-v,k=n-w;}const M=c.x1,I=c.y1,z=c.x2-M,P=c.y2-I,C=(t,i,s,l)=>{const u=Hh(t.stretch-x,v,z,M),c=Kh(t.fixed-_,S,t.stretch,d),h=Hh(i.stretch-b,w,P,I),p=Kh(i.fixed-A,k,i.stretch,y),f=Hh(s.stretch-x,v,z,M),m=Kh(s.fixed-_,S,s.stretch,d),g=Hh(l.stretch-b,w,P,I),C=Kh(l.fixed-A,k,l.stretch,y),E=new r(u,h),T=new r(f,h),B=new r(f,g),V=new r(u,g),F=new r(c/o,p/o),$=new r(m/o,C/o),D=e*Math.PI/180;if(D){const t=Math.sin(D),e=Math.cos(D),r=[e,-t,t,e];E._matMult(r),T._matMult(r),V._matMult(r),B._matMult(r);}const L=t.stretch+t.fixed,O=i.stretch+i.fixed;return {tl:E,tr:T,bl:V,br:B,tex:{x:a.paddedRect.x+1+L,y:a.paddedRect.y+1+O,w:s.stretch+s.fixed-L,h:l.stretch+l.fixed-O},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:F,pixelOffsetBR:$,minFontScaleX:S/o/z,minFontScaleY:k/o/P,isSDF:n}};if(i&&(a.stretchX||a.stretchY)){const t=Yh(h,m,d),e=Yh(p,g,y);for(let r=0;r0&&(n=Math.max(10,n),this.circleDiameter=n);}else {const u=(null===(h=a.image)||void 0===h?void 0:h.content)&&(a.image.textFitWidth||a.image.textFitHeight)?jc(a):{x1:a.left,y1:a.top,x2:a.right,y2:a.bottom};u.y1=u.y1*o-l[0],u.y2=u.y2*o+l[2],u.x1=u.x1*o-l[3],u.x2=u.x2*o+l[1];const p=a.collisionPadding;if(p&&(u.x1-=p[0]*o,u.y1-=p[1]*o,u.x2+=p[2]*o,u.y2+=p[3]*o),c){const t=new r(u.x1,u.y1),e=new r(u.x2,u.y1),n=new r(u.x1,u.y2),i=new r(u.x2,u.y2),s=c*Math.PI/180;t._rotate(s),e._rotate(s),n._rotate(s),i._rotate(s),u.x1=Math.min(t.x,e.x,n.x,i.x),u.x2=Math.max(t.x,e.x,n.x,i.x),u.y1=Math.min(t.y,e.y,n.y,i.y),u.y2=Math.max(t.y,e.y,n.y,i.y);}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,n,i,s);}this.boxEndIndex=t.length;}}class Wh{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}}function Qh(t,e=1,n=!1){const i=Eh.fromPoints(t[0]),s=Math.min(i.width(),i.height());let a=s/2;const o=new Wh([],tp),{minX:l,minY:u,maxX:c,maxY:h}=i;if(0===s)return new r(l,u);for(let e=l;ep.d||!p.d)&&(p=r,n&&console.log("found best %d after %d probes",Math.round(1e4*r.d)/1e4,f)),r.max-p.d<=e||(a=r.h/2,o.push(new ep(r.p.x-a,r.p.y-a,a,t)),o.push(new ep(r.p.x+a,r.p.y-a,a,t)),o.push(new ep(r.p.x-a,r.p.y+a,a,t)),o.push(new ep(r.p.x+a,r.p.y+a,a,t)),f+=4);}return n&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function tp(t,e){return e.max-t.max}function ep(t,e,n,i){this.p=new r(t,e),this.h=n,this.d=function(t,e){let r=!1,n=1/0;for(let i=0;it.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(r=!r),n=Math.min(n,Lo(t,i,o));}}return (r?1:-1)*Math.sqrt(n)}(this.p,i),this.max=this.d+this.h*Math.SQRT2;}var rp;t.aE=void 0,(rp=t.aE||(t.aE={}))[rp.center=1]="center",rp[rp.left=2]="left",rp[rp.right=3]="right",rp[rp.top=4]="top",rp[rp.bottom=5]="bottom",rp[rp["top-left"]=6]="top-left",rp[rp["top-right"]=7]="top-right",rp[rp["bottom-left"]=8]="bottom-left",rp[rp["bottom-right"]=9]="bottom-right";const np=Number.POSITIVE_INFINITY;function ip(t,e){return e[1]!==np?function(t,e,r){let n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case "top-right":case "top-left":case "top":i=r-7;break;case "bottom-right":case "bottom-left":case "bottom":i=7-r;}switch(t){case "top-right":case "bottom-right":case "right":n=-e;break;case "top-left":case "bottom-left":case "left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){let r=0,n=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case "top-right":case "top-left":n=i-7;break;case "bottom-right":case "bottom-left":n=7-i;break;case "bottom":n=7-e;break;case "top":n=e-7;}switch(t){case "top-right":case "bottom-right":r=-i;break;case "top-left":case "bottom-left":r=i;break;case "left":r=e;break;case "right":r=-e;}return [r,n]}(t,e[0])}function sp(t,e,r){var n;const i=t.layout,s=null===(n=i.get("text-variable-anchor-offset"))||void 0===n?void 0:n.evaluate(e,{},r);if(s){const t=s.values,e=[];for(let r=0;rt*Qu));n.startsWith("top")?i[1]-=7:n.startsWith("bottom")&&(i[1]+=7),e[r+1]=i;}return new $e(e)}const a=i.get("text-variable-anchor");if(a){let n;n=void 0!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},r)*Qu,np]:i.get("text-offset").evaluate(e,{},r).map((t=>t*Qu));const s=[];for(const t of a)s.push(t,ip(t,n));return new $e(s)}return null}function ap(t){switch(t){case "right":case "top-right":case "bottom-right":return "right";case "left":case "top-left":case "bottom-left":return "left"}return "center"}function op(e,r,n,i,s,a,o,l,u,c,h,p){let f=a.textMaxSize.evaluate(r,{});void 0===f&&(f=o);const d=e.layers[0].layout,y=d.get("icon-offset").evaluate(r,{},h),m=up(n.horizontal),g=o/24,x=e.tilePixelRatio*g,v=e.tilePixelRatio*f/24,b=e.tilePixelRatio*l,w=e.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*e.tilePixelRatio,S=function(t,e,r,n=1){const i=t.get("icon-padding").evaluate(e,{},r),s=i&&i.values;return [s[0]*n,s[1]*n,s[2]*n,s[3]*n]}(d,r,h,e.tilePixelRatio),A=d.get("text-max-angle")/180*Math.PI,k="viewport"!==d.get("text-rotation-alignment")&&"point"!==d.get("symbol-placement"),M="map"===d.get("icon-rotation-alignment")&&"point"!==d.get("symbol-placement"),I=d.get("symbol-placement"),z=w/2,C=d.get("icon-text-fit");let E;i&&"none"!==C&&(e.allowVerticalPlacement&&n.vertical&&(E=Nc(i,n.vertical,C,d.get("icon-text-fit-padding"),y,g)),m&&(i=Nc(i,m,C,d.get("icon-text-fit-padding"),y,g)));const T=h?p.line.getGranularityForZoomLevel(h.z):1,B=(l,p)=>{p.x<0||p.x>=P||p.y<0||p.y>=P||function(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k){const M=e.addToLineVertexArray(r,n);let I,z,P,C,E=0,T=0,B=0,V=0,F=-1,$=-1;const D={};let L=no("");if(e.allowVerticalPlacement&&i.vertical){const t=l.layout.get("text-rotate").evaluate(w,{},A)+90;P=new Jh(u,r,c,h,p,i.vertical,f,d,y,t),o&&(C=new Jh(u,r,c,h,p,o,g,x,y,t));}if(s){const n=l.layout.get("icon-rotate").evaluate(w,{}),i="none"!==l.layout.get("icon-text-fit"),a=Xh(s,n,S,i),f=o?Xh(o,n,S,i):void 0;z=new Jh(u,r,c,h,p,s,g,x,!1,n),E=4*a.length;const d=e.iconSizeData;let y=null;"source"===d.kind?(y=[qc*l.layout.get("icon-size").evaluate(w,{})],y[0]>Gc&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)):"composite"===d.kind&&(y=[qc*_.compositeIconSizes[0].evaluate(w,{},A),qc*_.compositeIconSizes[1].evaluate(w,{},A)],(y[0]>Gc||y[1]>Gc)&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)),e.addSymbols(e.icon,a,y,b,v,w,t.ao.none,r,M.lineStartIndex,M.lineLength,-1,A),F=e.icon.placedSymbolArray.length-1,f&&(T=4*f.length,e.addSymbols(e.icon,f,y,b,v,w,t.ao.vertical,r,M.lineStartIndex,M.lineLength,-1,A),$=e.icon.placedSymbolArray.length-1);}const O=Object.keys(i.horizontal);for(const n of O){const s=i.horizontal[n];if(!I){L=no(s.text);const t=l.layout.get("text-rotate").evaluate(w,{},A);I=new Jh(u,r,c,h,p,s,f,d,y,t);}const o=1===s.positionedLines.length;if(B+=lp(e,r,s,a,l,y,w,m,M,i.vertical?t.ao.horizontal:t.ao.horizontalOnly,o?O:[n],D,F,_,A),o)break}i.vertical&&(V+=lp(e,r,i.vertical,a,l,y,w,m,M,t.ao.vertical,["vertical"],D,$,_,A));const R=I?I.boxStartIndex:e.collisionBoxArray.length,U=I?I.boxEndIndex:e.collisionBoxArray.length,j=P?P.boxStartIndex:e.collisionBoxArray.length,N=P?P.boxEndIndex:e.collisionBoxArray.length,G=z?z.boxStartIndex:e.collisionBoxArray.length,X=z?z.boxEndIndex:e.collisionBoxArray.length,Z=C?C.boxStartIndex:e.collisionBoxArray.length,Y=C?C.boxEndIndex:e.collisionBoxArray.length;let H=-1;const K=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=K(I,H),H=K(P,H),H=K(z,H),H=K(C,H);const J=H>-1?1:0;J&&(H*=k/Qu),e.glyphOffsetArray.length>=th.MAX_GLYPHS&&q("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==w.sortKey&&e.addToSortKeyRanges(e.symbolInstances.length,w.sortKey);const W=sp(l,w,A),[Q,tt]=function(e,r){const n=e.length,i=null==r?void 0:r.values;if((null==i?void 0:i.length)>0)for(let r=0;r=0?D.right:-1,D.center>=0?D.center:-1,D.left>=0?D.left:-1,D.vertical||-1,F,$,L,R,U,j,N,G,X,Z,Y,c,B,V,E,T,J,0,f,H,Q,tt);}(e,p,l,n,i,s,E,e.layers[0],e.collisionBoxArray,r.index,r.sourceLayerIndex,e.index,x,[_,_,_,_],k,u,b,S,M,y,r,a,c,h,o);};if("line"===I)for(const t of Dh(r.geometry,0,0,P,P)){const r=ru(t,T),s=qh(r,w,A,n.vertical||m,i,24,v,e.overscaling,P);for(const t of s)m&&cp(e,m.text,z,t)||B(r,t);}else if("line-center"===I){for(const t of r.geometry)if(t.length>1){const e=ru(t,T),r=Nh(e,A,n.vertical||m,i,24,v);r&&B(e,r);}}else if("Polygon"===r.type)for(const t of Qr(r.geometry,0)){const e=Qh(t,16);B(ru(t[0],T,!0),new Lh(e.x,e.y,0));}else if("LineString"===r.type)for(const t of r.geometry){const e=ru(t,T);B(e,new Lh(e[0].x,e[0].y,0));}else if("Point"===r.type)for(const t of r.geometry)for(const e of t)B([e],new Lh(e.x,e.y,0));}function lp(t,e,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=function(t,e,n,i,s,a,o,l){const u=i.layout.get("text-rotate").evaluate(a,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const i of t.positionedGlyphs){if(!i.rect)continue;const a=i.rect||{};let h=4,p=!0,f=1,d=0;const y=(s||l)&&i.vertical,m=i.metrics.advance*i.scale/2;if(l&&e.verticalizable&&(d=t.lineOffset/2-(i.imageName?-(Qu-i.metrics.width*i.scale)/2:(i.scale-1)*Qu)),i.imageName){const t=o[i.imageName];p=t.sdf,f=t.pixelRatio,h=1/f;}const g=s?[i.x+m,i.y]:[0,0];let x=s?[0,0]:[i.x+m+n[0],i.y+n[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=i.metrics.isDoubleResolution?2:1,w=(i.metrics.left-h)*i.scale-m+x[0],_=(-i.metrics.top-h)*i.scale+x[1],S=w+a.w/b*i.scale/f,A=_+a.h/b*i.scale/f,k=new r(w,_),M=new r(S,_),I=new r(w,A),z=new r(S,A);if(y){const t=new r(-m,m- -17),e=-Math.PI/2,n=12-m,s=new r(22-n,-(i.imageName?n:0)),a=new r(...v);k._rotateAround(e,t)._add(s)._add(a),M._rotateAround(e,t)._add(s)._add(a),I._rotateAround(e,t)._add(s)._add(a),z._rotateAround(e,t)._add(s)._add(a);}if(u){const t=Math.sin(u),e=Math.cos(u),r=[e,-t,t,e];k._matMult(r),M._matMult(r),I._matMult(r),z._matMult(r);}const P=new r(0,0),C=new r(0,0);c.push({tl:k,tr:M,bl:I,br:z,tex:a,writingMode:e.writingMode,glyphOffset:g,sectionIndex:i.sectionIndex,isSDF:p,pixelOffsetTL:P,pixelOffsetBR:C,minFontScaleX:0,minFontScaleY:0});}return c}(0,n,l,s,a,o,i,t.allowVerticalPlacement),g=t.textSizeData;let x=null;"source"===g.kind?(x=[qc*s.layout.get("text-size").evaluate(o,{})],x[0]>Gc&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)):"composite"===g.kind&&(x=[qc*d.compositeTextSizes[0].evaluate(o,{},y),qc*d.compositeTextSizes[1].evaluate(o,{},y)],(x[0]>Gc||x[1]>Gc)&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)),t.addSymbols(t.text,m,x,l,a,o,c,e,u.lineStartIndex,u.lineLength,f,y);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*m.length}function up(t){for(const e in t)return t[e];return null}function cp(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=hp[15&r];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new pp(a,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=hp.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+s+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return fp(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,r,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:a}=this,o=[0,i.length-1,0],l=[];for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=a){for(let a=h;a<=c;a++){const o=s[2*a],u=s[2*a+1];o>=t&&o<=r&&u>=e&&u<=n&&l.push(i[a]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?r>=f:n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return l}within(t,e,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:n,coords:i,nodeSize:s}=this,a=[0,n.length-1,0],o=[],l=r*r;for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)gp(i[2*r],i[2*r+1],t,e)<=l&&o.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];gp(f,d,t,e)<=l&&o.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return o}}function fp(t,e,r,n,i,s){if(i-n<=r)return;const a=n+i>>1;dp(t,e,a,n,i,s),fp(t,e,r,n,a-1,1-s),fp(t,e,r,a+1,i,1-s);}function dp(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const a=i-n+1,o=r-n+1,l=Math.log(a),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(a-u)/a)*(o-a/2<0?-1:1);dp(t,e,r,Math.max(n,Math.floor(r-o*u/a+c)),Math.min(i,Math.floor(r+(a-o)*u/a+c)),s);}const a=e[2*r+s];let o=n,l=i;for(yp(t,e,n,r),e[2*i+s]>a&&yp(t,e,n,i);oa;)l--;}e[2*n+s]===a?yp(t,e,n,l):(l++,yp(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1);}}function yp(t,e,r,n){mp(t,r,n),mp(e,2*r,2*n),mp(e,2*r+1,2*n+1);}function mp(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function gp(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}var xp;t.cx=void 0,(xp=t.cx||(t.cx={})).create="create",xp.load="load",xp.fullLoad="fullLoad";let vp=null,bp=[];const wp=1e3/60,_p="loadTime",Sp="fullLoadTime",Ap={mark(t){performance.mark(t);},frame(t){const e=t;null!=vp&&bp.push(e-vp),vp=e;},clearMetrics(){vp=null,bp=[],performance.clearMeasures(_p),performance.clearMeasures(Sp);for(const e in t.cx)performance.clearMarks(t.cx[e]);},getPerformanceMetrics(){performance.measure(_p,t.cx.create,t.cx.load),performance.measure(Sp,t.cx.create,t.cx.fullLoad);const e=performance.getEntriesByName(_p)[0].duration,r=performance.getEntriesByName(Sp)[0].duration,n=bp.length,i=1/(bp.reduce(((t,e)=>t+e),0)/n/1e3),s=bp.filter((t=>t>wp)).reduce(((t,e)=>t+(e-wp)/wp),0);return {loadTime:e,fullLoadTime:r,fps:i,percentDroppedFrames:s/(n+s)*100,totalFrames:n}}};t.$=P,t.A=f,t.B=function([t,e,r]){return e+=90,e*=Math.PI/180,r*=Math.PI/180,{x:t*Math.cos(e)*Math.sin(r),y:t*Math.sin(e)*Math.sin(r),z:t*Math.cos(r)}},t.C=dr,t.D=Ds,t.E=gt,t.F=Is,t.G=ts,t.H=function(t){if(null==Z){const e=t.navigator?t.navigator.userAgent:null;Z=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return Z},t.I=vc,t.J=class{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new fh((()=>this.process())),this.subscription=Q(this.target,"message",(t=>this.receive(t)),!1),this.globalScope=X(self)?t:window;}registerMessageHandler(t,e){this.messageHandlers[t]=e;}sendAsync(t,e){return new Promise(((r,n)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10),s=e?Q(e.signal,"abort",(()=>{null==s||s.unsubscribe(),delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e);}),dh):null;this.resolveRejects[i]={resolve:t=>{null==s||s.unsubscribe(),r(t);},reject:t=>{null==s||s.unsubscribe(),n(t);}};const a=[],o=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:cs(t.data,a)});this.target.postMessage(o,{transfer:a});}))}receive(t){const e=t.data,r=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[r];const t=this.abortControllers[r];return delete this.abortControllers[r],void(t&&t.abort())}if(X(self)||e.mustQueue)return this.tasks[r]=e,this.taskQueue.push(r),void this.invoker.trigger();this.processTask(r,e);}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e);}processTask(t,r){return e(this,void 0,void 0,(function*(){if(""===r.type){const e=this.resolveRejects[t];if(delete this.resolveRejects[t],!e)return;return void(r.error?e.reject(hs(r.error)):e.resolve(hs(r.data)))}if(!this.messageHandlers[r.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${r.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const e=hs(r.data),n=new AbortController;this.abortControllers[t]=n;try{const i=yield this.messageHandlers[r.type](r.sourceMapId,e,n);this.completeTask(t,null,i);}catch(e){this.completeTask(t,e);}}))}completeTask(t,e,r){const n=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?cs(e):null,data:cs(r,n)};this.target.postMessage(i,{transfer:n});}remove(){this.invoker.remove(),this.subscription.unsubscribe();}},t.K=lt,t.L=function(){var t=new f(16);return f!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.M=function(t,e,r){var n,i,s,a,o,l,u,c,h,p,f,d,y=r[0],m=r[1],g=r[2];return e===t?(t[12]=e[0]*y+e[4]*m+e[8]*g+e[12],t[13]=e[1]*y+e[5]*m+e[9]*g+e[13],t[14]=e[2]*y+e[6]*m+e[10]*g+e[14],t[15]=e[3]*y+e[7]*m+e[11]*g+e[15]):(i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=n=e[0],t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=n*y+o*m+h*g+e[12],t[13]=i*y+l*m+p*g+e[13],t[14]=s*y+u*m+f*g+e[14],t[15]=a*y+c*m+d*g+e[15]),t},t.N=function(t,e,r){var n=r[0],i=r[1],s=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.O=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],y=e[12],m=e[13],g=e[14],x=e[15],v=r[0],b=r[1],w=r[2],_=r[3];return t[0]=v*n+b*o+w*h+_*y,t[1]=v*i+b*l+w*p+_*m,t[2]=v*s+b*u+w*f+_*g,t[3]=v*a+b*c+w*d+_*x,t[4]=(v=r[4])*n+(b=r[5])*o+(w=r[6])*h+(_=r[7])*y,t[5]=v*i+b*l+w*p+_*m,t[6]=v*s+b*u+w*f+_*g,t[7]=v*a+b*c+w*d+_*x,t[8]=(v=r[8])*n+(b=r[9])*o+(w=r[10])*h+(_=r[11])*y,t[9]=v*i+b*l+w*p+_*m,t[10]=v*s+b*u+w*f+_*g,t[11]=v*a+b*c+w*d+_*x,t[12]=(v=r[12])*n+(b=r[13])*o+(w=r[14])*h+(_=r[15])*y,t[13]=v*i+b*l+w*p+_*m,t[14]=v*s+b*u+w*f+_*g,t[15]=v*a+b*c+w*d+_*x,t},t.P=r,t.Q=function(t,e){const r={};for(let n=0;n!n.has(t.id)))),o.update&&(o.update=o.update.filter((t=>!n.has(t.id))));const i=new Set((null!==(r=t.add)&&void 0!==r?r:[]).map((t=>t.id)));e.remove=e.remove.filter((t=>!i.has(t)));}if(e.remove){const t=new Set(o.remove?o.remove.concat(e.remove):e.remove);o.remove=Array.from(t.values());}if(e.add){const t=o.add?o.add.concat(e.add):e.add,r=new Map(t.map((t=>[t.id,t])));o.add=Array.from(r.values());}if(e.update){const t=new Map(null===(n=o.update)||void 0===n?void 0:n.map((t=>[t.id,t])));for(const r of e.update){const e=null!==(i=t.get(r.id))&&void 0!==i?i:{id:r.id};r.newGeometry&&(e.newGeometry=r.newGeometry),r.addOrUpdateProperties&&(e.addOrUpdateProperties=(null!==(s=e.addOrUpdateProperties)&&void 0!==s?s:[]).concat(r.addOrUpdateProperties)),r.removeProperties&&(e.removeProperties=(null!==(a=e.removeProperties)&&void 0!==a?a:[]).concat(r.removeProperties)),r.removeAllProperties&&(e.removeAllProperties=!0),t.set(r.id,e);}o.update=Array.from(t.values());}return o.remove&&o.add&&(o.remove=o.remove.filter((t=>-1===o.add.findIndex((e=>e.id===t))))),o},t.a1=Ah,t.a2=Eh,t.a3=25,t.a4=Mh,t.a5=t=>{const e=window.document.createElement("video");return e.muted=!0,new Promise((r=>{e.onloadstart=()=>{r(e);};for(const r of t){const t=window.document.createElement("source");pt(r)||(e.crossOrigin="Anonymous"),t.src=r,e.appendChild(t);}}))},t.a6=Ct,t.a7=function(){return O++},t.a8=ba,t.a9=th,t.aA=function(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return [e,r,n,i]},t.aB=Qu,t.aC=C,t.aD=function(t,e,r,n,i=!1){if(!r[0]&&!r[1])return [0,0];const s=i?"map"===n?-t.bearingInRadians:0:"viewport"===n?t.bearingInRadians:0;if(s){const t=Math.sin(s),e=Math.cos(s);r=[r[0]*e-r[1]*t,r[0]*t+r[1]*e];}return [i?r[0]:C(e,r[0],t.zoom),i?r[1]:C(e,r[1],t.zoom)]},t.aF=Zc,t.aG=ap,t.aH=Vc,t.aI=pp,t.aJ=Ys,t.aK=Jl,t.aL=Ea,t.aM=Za,t.aN=Na,t.aO=D,t.aP=et,t.aQ=Sh,t.aR=b,t.aS=v,t.aT=function(t){var e=new f(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.aU=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t},t.aV=function(t,e){var r=e[0],n=e[1],i=e[2],s=r*r+n*n+i*i;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t},t.aW=w,t.aX=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.aY=function(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t},t.aZ=g,t.a_=function(t,e,r){const n=e[0]*r[0]+e[1]*r[1]+e[2]*r[2];return 0===n?null:(-(t[0]*r[0]+t[1]*r[1]+t[2]*r[2])-r[3])/n},t.aa=hi,t.ab=Io,t.ac=Bh,t.ad=function(t){const e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,r,n,i)=>{const s=n||i;return e[r]=!s||s.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t;}return e},t.ae=tt,t.af=function(t){return Math.pow(2,t)},t.ag=y,t.ah=$,t.ai=85.051129,t.aj=wh,t.ak=function(t){return Math.log(t)/Math.LN2},t.al=function(t){var e=t[0],r=t[1];return e*e+r*r},t.am=function(t,e){const r=[];for(const n in t)n in e||r.push(n);return r},t.an=function(t,e){let r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){const{interpolationType:i,minZoom:s,maxZoom:a}=t,o=i?$(pr.interpolationFactor(i,e,s,a),0,1):0;"camera"===t.kind?n=dr.number(t.minSize,t.maxSize,o):r=o;}return {uSizeT:r,uSize:n}},t.ap=function(t,{uSize:e,uSizeT:r},{lowerSize:n,upperSize:i}){return "source"===t.kind?n/qc:"composite"===t.kind?dr.number(n/qc,i/qc,r):e},t.aq=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],y=e[13],m=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,w=n*l-i*o,_=n*u-s*o,S=i*u-s*l,A=c*y-h*d,k=c*m-p*d,M=c*g-f*d,I=h*m-p*y,z=h*g-f*y,P=p*g-f*m,C=x*P-v*z+b*I+w*M-_*k+S*A;return C?(t[0]=(o*P-l*z+u*I)*(C=1/C),t[1]=(i*z-n*P-s*I)*C,t[2]=(y*S-m*_+g*w)*C,t[3]=(p*_-h*S-f*w)*C,t[4]=(l*M-a*P-u*k)*C,t[5]=(r*P-i*M+s*k)*C,t[6]=(m*b-d*S-g*v)*C,t[7]=(c*S-p*b+f*v)*C,t[8]=(a*z-o*M+u*A)*C,t[9]=(n*M-r*z-s*A)*C,t[10]=(d*_-y*b+g*x)*C,t[11]=(h*b-c*_-f*x)*C,t[12]=(o*k-a*I-l*A)*C,t[13]=(r*I-n*k+i*A)*C,t[14]=(y*v-d*w-m*x)*C,t[15]=(c*w-h*v+p*x)*C,t):null},t.ar=I,t.as=function(t){var e=t[0],r=t[1];return Math.sqrt(e*e+r*r)},t.at=function(t){return t[0]=0,t[1]=0,t},t.au=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t},t.av=Kc,t.aw=A,t.ax=function(t,e,n,i){const s=e.y-t.y,a=e.x-t.x,o=i.y-n.y,l=i.x-n.x,u=o*a-l*s;if(0===u)return null;const c=(l*(t.y-n.y)-o*(t.x-n.x))/u;return new r(t.x+c*a,t.y+c*s)},t.ay=Dh,t.az=Eo,t.b=Y,t.b$=class extends la{},t.b0=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t},t.b1=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]},t.b2=Ih,t.b3=Ph,t.b4=function(t,e,r,n,i){var s=1/Math.tan(e/2);if(t[0]=s/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=s,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0){var a=1/(n-i);t[10]=(i+n)*a,t[14]=2*i*n*a;}else t[10]=-1,t[14]=-2*n;return t},t.b5=function(t){var e=new f(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.b6=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[4],c=e[5],h=e[6],p=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i+u*n,t[1]=a*i+c*n,t[2]=o*i+h*n,t[3]=l*i+p*n,t[4]=u*i-s*n,t[5]=c*i-a*n,t[6]=h*i-o*n,t[7]=p*i-l*n,t},t.b7=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=s*i+u*n,t[5]=a*i+c*n,t[6]=o*i+h*n,t[7]=l*i+p*n,t[8]=u*i-s*n,t[9]=c*i-a*n,t[10]=h*i-o*n,t[11]=p*i-l*n,t},t.b8=function(){const t=new Float32Array(16);return y(t),t},t.b9=function(){const t=new Float64Array(16);return y(t),t},t.bA=function(t,e){const r=E(t,360),n=E(e,360),i=n-r,s=n>r?i-360:i+360;return Math.abs(i)0?a:-a},t.bD=function(t,e){const r=E(t,2*Math.PI),n=E(e,2*Math.PI);return Math.min(Math.abs(r-n),Math.abs(r-n+2*Math.PI),Math.abs(r-n-2*Math.PI))},t.bE=function(){const t={},e=xt.$version;for(const r in xt.$root){const n=xt.$root[r];if(n.required){let i=null;i="version"===r?e:"array"===n.type?[]:{},null!=i&&(t[r]=i);}}return t},t.bF=ps,t.bG=ct,t.bH=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(let n=0;n{"source"in t&&n[t.source]?r.push({command:"removeLayer",args:[t.id]}):s.push(t);})),r=r.concat(i),function(t,e,r){e=e||[];const n=(t=t||[]).map(zt),i=e.map(zt),s=t.reduce(Pt,{}),a=e.reduce(Pt,{}),o=n.slice(),l=Object.create(null);let u,c,h,p,f;for(let t=0,e=0;tp?(i=Math.acos(s),a=Math.sin(i),o=Math.sin((1-n)*i)/a,l=Math.sin(n*i)/a):(o=1-n,l=n),t[0]=o*u+l*d,t[1]=o*c+l*y,t[2]=o*h+l*m,t[3]=o*f+l*g,t},t.bd=function(t){const e=new Float64Array(9);var r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v;h=(i=(n=t)[0])*(l=i+i),p=(s=n[1])*l,d=(a=n[2])*l,y=a*(u=s+s),g=(o=n[3])*l,x=o*u,v=o*(c=a+a),(r=e)[0]=1-(f=s*u)-(m=a*c),r[3]=p-v,r[6]=d+x,r[1]=p+v,r[4]=1-h-m,r[7]=y-g,r[2]=d-x,r[5]=y+g,r[8]=1-h-f;const b=et(-Math.asin($(e[2],-1,1)));let w,_;return Math.hypot(e[5],e[8])<.001?(w=0,_=-et(Math.atan2(e[3],e[4]))):(w=et(0===e[5]&&0===e[8]?0:Math.atan2(e[5],e[8])),_=et(0===e[1]&&0===e[0]?0:Math.atan2(e[1],e[0]))),{roll:w,pitch:b+90,bearing:_}},t.be=function(t,e){return t.roll==e.roll&&t.pitch==e.pitch&&t.bearing==e.bearing},t.bf=Me,t.bg=uo,t.bh=Wl,t.bi=Ql,t.bj=Kl,t.bk=T,t.bl=B,t.bm=Le,t.bn=function(t,e,r,n,i){return T(n,i,$((t-e)/(r-e),0,1))},t.bo=E,t.bp=function(){return new Float64Array(3)},t.bq=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t},t.br=M,t.bs=function(t,e,r){var n=r[0],i=r[1],s=r[2],a=r[3],o=e[0],l=e[1],u=e[2],c=i*u-s*l,h=s*o-n*u,p=n*l-i*o;return t[0]=o+a*(c+=c)+i*(p+=p)-s*(h+=h),t[1]=l+a*h+s*c-n*p,t[2]=u+a*p+n*h-i*c,t},t.bt=function(t,e,r){const n=(i=[t[0],t[1],t[2],e[0],e[1],e[2],r[0],r[1],r[2]])[0]*((c=i[8])*(a=i[4])-(o=i[5])*(u=i[7]))+i[1]*(-c*(s=i[3])+o*(l=i[6]))+i[2]*(u*s-a*l);var i,s,a,o,l,u,c;if(0===n)return null;const h=w([],[e[0],e[1],e[2]],[r[0],r[1],r[2]]),p=w([],[r[0],r[1],r[2]],[t[0],t[1],t[2]]),f=w([],[t[0],t[1],t[2]],[e[0],e[1],e[2]]),d=b([],h,-t[3]);return v(d,d,b([],p,-e[3])),v(d,d,b([],f,-r[3])),b(d,d,1/n),d},t.bu=yh,t.bv=function(){return new Float64Array(4)},t.bw=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),s[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),s[2]=i[2],t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bx=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0],s[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),s[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.by=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),s[1]=i[1],s[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bz=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i-u*n,t[1]=a*i-c*n,t[2]=o*i-h*n,t[3]=l*i-p*n,t[8]=s*n+u*i,t[9]=a*n+c*i,t[10]=o*n+h*i,t[11]=l*n+p*i,t},t.c=st,t.c0=Ku,t.c1=class extends ca{},t.c2=cl,t.c3=function(t){return t<=1?1:Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},t.c4=ul,t.c5=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[3]*n+r[7]*i+r[11]*s+r[15];return t[0]=(r[0]*n+r[4]*i+r[8]*s+r[12])/(a=a||1),t[1]=(r[1]*n+r[5]*i+r[9]*s+r[13])/a,t[2]=(r[2]*n+r[6]*i+r[10]*s+r[14])/a,t},t.c6=class extends Ws{},t.c7=class extends ga{},t.c8=function(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[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]},t.c9=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=t[9],f=t[10],d=t[11],y=t[12],m=t[13],g=t[14],x=t[15],v=e[0],b=e[1],w=e[2],_=e[3],S=e[4],A=e[5],k=e[6],M=e[7],I=e[8],z=e[9],P=e[10],C=e[11],E=e[12],T=e[13],B=e[14],V=e[15];return Math.abs(r-v)<=p*Math.max(1,Math.abs(r),Math.abs(v))&&Math.abs(n-b)<=p*Math.max(1,Math.abs(n),Math.abs(b))&&Math.abs(i-w)<=p*Math.max(1,Math.abs(i),Math.abs(w))&&Math.abs(s-_)<=p*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(a-S)<=p*Math.max(1,Math.abs(a),Math.abs(S))&&Math.abs(o-A)<=p*Math.max(1,Math.abs(o),Math.abs(A))&&Math.abs(l-k)<=p*Math.max(1,Math.abs(l),Math.abs(k))&&Math.abs(u-M)<=p*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(c-I)<=p*Math.max(1,Math.abs(c),Math.abs(I))&&Math.abs(h-z)<=p*Math.max(1,Math.abs(h),Math.abs(z))&&Math.abs(f-P)<=p*Math.max(1,Math.abs(f),Math.abs(P))&&Math.abs(d-C)<=p*Math.max(1,Math.abs(d),Math.abs(C))&&Math.abs(y-E)<=p*Math.max(1,Math.abs(y),Math.abs(E))&&Math.abs(m-T)<=p*Math.max(1,Math.abs(m),Math.abs(T))&&Math.abs(g-B)<=p*Math.max(1,Math.abs(g),Math.abs(B))&&Math.abs(x-V)<=p*Math.max(1,Math.abs(x),Math.abs(V))},t.cA=function(t,e){at.REGISTERED_PROTOCOLS[t]=e;},t.cB=function(t){delete at.REGISTERED_PROTOCOLS[t];},t.cC=function(t,e){const r={};for(let n=0;nt*Qu));}let v=o?"center":n.get("text-justify").evaluate(i,{},e.canonical);const b="point"===n.get("symbol-placement")?n.get("text-max-width").evaluate(i,{},e.canonical)*Qu:1/0,w=()=>{e.bucket.allowVerticalPlacement&&ds(s)&&(d.vertical=Ac(y,e.glyphMap,e.glyphPositions,e.imagePositions,c,b,a,m,"left",f,g,t.ao.vertical,!0,p,h));};if(!o&&x){const r=new Set;if("auto"===v)for(let t=0;t0||(null===(i=r.addOrUpdateProperties)||void 0===i?void 0:i.length)>0);if((r.newGeometry||r.removeAllProperties||o)&&(e=Object.assign({},e),t.set(r.id,e),o&&(e.properties=Object.assign({},e.properties))),r.newGeometry&&(e.geometry=r.newGeometry),r.removeAllProperties)e.properties={};else if((null===(s=r.removeProperties)||void 0===s?void 0:s.length)>0)for(const t of r.removeProperties)Object.prototype.hasOwnProperty.call(e.properties,t)&&delete e.properties[t];if((null===(a=r.addOrUpdateProperties)||void 0===a?void 0:a.length)>0)for(const{key:t,value:n}of r.addOrUpdateProperties)e.properties[t]=n;}},t.cX=Ms,t.ca=function(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[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.cb=t=>"symbol"===t.type,t.cc=t=>"circle"===t.type,t.cd=t=>"heatmap"===t.type,t.ce=t=>"line"===t.type,t.cf=t=>"fill"===t.type,t.cg=t=>"fill-extrusion"===t.type,t.ch=t=>"hillshade"===t.type,t.ci=t=>"color-relief"===t.type,t.cj=t=>"raster"===t.type,t.ck=t=>"background"===t.type,t.cl=t=>"custom"===t.type,t.cm=V,t.cn=function(t,e,r){const n=z(e.x-r.x,e.y-r.y),i=z(t.x-r.x,t.y-r.y);var s,a;return et(Math.atan2(n[0]*i[1]-n[1]*i[0],(s=n)[0]*(a=i)[0]+s[1]*a[1]))},t.co=F,t.cp=function(t,e){return nt[e]&&(t instanceof MouseEvent||t instanceof WheelEvent)},t.cq=function(t,e){return rt[e]&&"touches"in t},t.cr=function(t){return rt[t]||nt[t]},t.cs=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t},t.ct=function(t,e){const{x:r,y:n}=Ah.fromLngLat(e);return !(t<0||t>25||n<0||n>=1||r<0||r>=1)},t.cu=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.cv=class extends Js{},t.cw=Ap,t.cy=function(t){return t.message===it},t.cz=ut,t.d=pt,t.e=L,t.f=t=>e(void 0,void 0,void 0,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),t.g=ot,t.h=t=>new Promise(((e,r)=>{const n=new Image;n.onload=()=>{e(n),URL.revokeObjectURL(n.src),n.onload=null,window.requestAnimationFrame((()=>{n.src=H;}));},n.onerror=()=>r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const i=new Blob([new Uint8Array(t)],{type:"image/png"});n.src=t.byteLength?URL.createObjectURL(i):H;})),t.i=X,t.j=(t,e)=>ht(L(t,{type:"json"}),e),t.k=mt,t.l=yt,t.m=ht,t.n=(t,e)=>ht(L(t,{type:"arrayBuffer"}),e),t.o=function(t){return new nc(t).readFields(yc,[])},t.p=xc,t.q=ol,t.r=js,t.s=Q,t.t=Es,t.u=fs,t.v=xt,t.w=q,t.x=Qi,t.y=ns,t.z=Wi;})); + +define("worker",["./shared"],(function(e){"use strict";class t{constructor(e,t){this.keyCache={},e&&this.replace(e,t);}replace(e,t){this._layerConfigs={},this._layers={},this.update(e,[],t);}update(t,i,o){for(const i of t){this._layerConfigs[i.id]=i;const t=this._layers[i.id]=e.bJ(i,o);t._featureFilter=e.aa(t.filter,o),this.keyCache[i.id]&&delete this.keyCache[i.id];}for(const e of i)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const s=e.cC(Object.values(this._layerConfigs),this.keyCache);for(const e of s){const t=e.map((e=>this._layers[e.id])),i=t[0];if("none"===i.visibility)continue;const o=i.source||"";let s=this.familiesBySource[o];s||(s=this.familiesBySource[o]={});const n=i.sourceLayer||"_geojsonTileLayer";let r=s[n];r||(r=s[n]=[]),r.push(t);}}}class i{constructor(t){const i={},o=[];for(const e in t){const s=t[e],n=i[e]={};for(const e in s){const t=s[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const i={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};o.push(i),n[e]={rect:i,metrics:t.metrics};}}const{w:s,h:n}=e.p(o),r=new e.q({width:s||1,height:n||1});for(const o in t){const s=t[o];for(const t in s){const n=s[+t];if(!n||0===n.bitmap.width||0===n.bitmap.height)continue;const a=i[o][t].rect;e.q.copy(n.bitmap,r,{x:0,y:0},{x:a.x+1,y:a.y+1},n.bitmap);}}this.image=r,this.positions=i;}}e.cD("GlyphAtlas",i);class o{constructor(t){this.tileID=new e.Z(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[];}parse(t,o,n,r,a){return e._(this,void 0,void 0,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.a8;const l=new e.cE(Object.keys(t.layers).sort()),c=new e.cF(this.tileID,this.promoteId);c.bucketLayerIDs=[];const u={},h={featureIndex:c,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:n,subdivisionGranularity:a},d=o.familiesBySource[this.source];for(const i in d){const o=t.layers[i];if(!o)continue;1===o.version&&e.w(`Vector tile source "${this.source}" layer "${i}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const r=l.encode(i),a=[];for(let e=0;e=i.maxzoom||"none"!==i.visibility&&(s(t,this.zoom,n),(u[i.id]=i.createBucket({index:c.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:r,sourceID:this.source})).populate(a,h,this.tileID.canonical),c.bucketLayerIDs.push(t.map((e=>e.id))));}}const f=e.bN(h.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?void 0:e.abort())),this.inFlightDependencies=[];let g=Promise.resolve({});if(Object.keys(f).length){const e=new AbortController;this.inFlightDependencies.push(e),g=r.sendAsync({type:"GG",data:{stacks:f,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const p=Object.keys(h.iconDependencies);let m=Promise.resolve({});if(p.length){const e=new AbortController;this.inFlightDependencies.push(e),m=r.sendAsync({type:"GI",data:{icons:p,source:this.source,tileID:this.tileID,type:"icons"}},e);}const y=Object.keys(h.patternDependencies);let v=Promise.resolve({});if(y.length){const e=new AbortController;this.inFlightDependencies.push(e),v=r.sendAsync({type:"GI",data:{icons:y,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const[w,x,b]=yield Promise.all([g,m,v]),S=new i(w),_=new e.cG(x,b);for(const t in u){const i=u[t];i instanceof e.a9?(s(i.layers,this.zoom,n),e.cH({bucket:i,glyphMap:w,glyphPositions:S.positions,imageMap:x,imagePositions:_.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:h.subdivisionGranularity})):i.hasPattern&&(i instanceof e.cI||i instanceof e.cJ||i instanceof e.cK)&&(s(i.layers,this.zoom,n),i.addFeatures(h,this.tileID.canonical,_.patternPositions));}return this.status="done",{buckets:Object.values(u).filter((e=>!e.isEmpty())),featureIndex:c,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:S.image,imageAtlas:_,glyphMap:this.returnDependencies?w:null,iconMap:this.returnDependencies?x:null,glyphPositions:this.returnDependencies?S.positions:null}}))}}function s(t,i,o){const s=new e.F(i);for(const e of t)e.recalculate(s,o);}class n{constructor(e,t,i){this.actor=e,this.layerIndex=t,this.availableImages=i,this.fetching={},this.loading={},this.loaded={};}loadVectorTile(t,i){return e._(this,void 0,void 0,(function*(){const o=yield e.n(t.request,i);try{return {vectorTile:new e.cL(new e.cM(o.data)),rawData:o.data,cacheControl:o.cacheControl,expires:o.expires}}catch(e){const i=new Uint8Array(o.data);let s=`Unable to parse the tile at ${t.request.url}, `;throw s+=31===i[0]&&139===i[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${e.message}`,new Error(s)}}))}loadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid,s=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.cN(t.request),n=new o(t);this.loading[i]=n;const r=new AbortController;n.abort=r;try{const o=yield this.loadVectorTile(t,r);if(delete this.loading[i],!o)return null;const a=o.rawData,l={};o.expires&&(l.expires=o.expires),o.cacheControl&&(l.cacheControl=o.cacheControl);const c={};if(s){const e=s.finish();e&&(c.resourceTiming=JSON.parse(JSON.stringify(e)));}n.vectorTile=o.vectorTile;const u=n.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);this.loaded[i]=n,this.fetching[i]={rawTileData:a,cacheControl:l,resourceTiming:c};try{const t=yield u;return e.e({rawTileData:a.slice(0)},t,l,c)}finally{delete this.fetching[i];}}catch(e){throw delete this.loading[i],n.status="done",this.loaded[i]=n,e}}))}reloadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid;if(!this.loaded||!this.loaded[i])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const o=this.loaded[i];if(o.showCollisionBoxes=t.showCollisionBoxes,"parsing"===o.status){const s=yield o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);let n;if(this.fetching[i]){const{rawTileData:t,cacheControl:o,resourceTiming:r}=this.fetching[i];delete this.fetching[i],n=e.e({rawTileData:t.slice(0)},s,o,r);}else n=s;return n}if("done"===o.status&&o.vectorTile)return o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity)}))}abortTile(t){return e._(this,void 0,void 0,(function*(){const e=this.loading,i=t.uid;e&&e[i]&&e[i].abort&&(e[i].abort.abort(),delete e[i]);}))}removeTile(t){return e._(this,void 0,void 0,(function*(){this.loaded&&this.loaded[t.uid]&&delete this.loaded[t.uid];}))}}class r{constructor(){this.loaded={};}loadTile(t){return e._(this,void 0,void 0,(function*(){const{uid:i,encoding:o,rawImageData:s,redFactor:n,greenFactor:r,blueFactor:a,baseShift:l}=t,c=s.width+2,u=s.height+2,h=e.b(s)?new e.R({width:c,height:u},yield e.cO(s,-1,-1,c,u)):s,d=new e.cP(i,h,o,n,r,a,l);return this.loaded=this.loaded||{},this.loaded[i]=d,d}))}removeTile(e){const t=this.loaded,i=e.uid;t&&t[i]&&delete t[i];}}var a,l,c=function(){if(l)return a;function e(e,i){if(0!==e.length){t(e[0],i);for(var o=1;o=Math.abs(a)?i-l+a:a-l+i,i=l;}i+o>=0!=!!t&&e.reverse();}return l=1,a=function t(i,o){var s,n=i&&i.type;if("FeatureCollection"===n)for(s=0;s>31}function v(e,t){const i=e.loadGeometry(),o=e.type;let s=0,n=0;for(const r of i){let i=1;1===o&&(i=r.length),t.writeVarint(m(1,i));const a=3===o?r.length-1:r.length;for(let e=0;ee},b=Math.fround||(S=new Float32Array(1),e=>(S[0]=+e,S[0]));var S;class _{constructor(e){this.options=Object.assign(Object.create(x),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:i,maxZoom:o}=this.options;t&&console.time("total time");const s=`prepare ${e.length} points`;t&&console.time(s),this.points=e;const n=[];for(let t=0;t=i;e--){const i=+Date.now();r=this.trees[e]=this._createTree(this._cluster(r,e)),t&&console.log("z%d: %d clusters in %dms",e,r.numItems,+Date.now()-i);}return t&&console.timeEnd("total time"),this}getClusters(e,t){let i=((e[0]+180)%360+360)%360-180;const o=Math.max(-90,Math.min(90,e[1]));let s=180===e[2]?180:((e[2]+180)%360+360)%360-180;const n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)i=-180,s=180;else if(i>s){const e=this.getClusters([i,o,180,n],t),r=this.getClusters([-180,o,s,n],t);return e.concat(r)}const r=this.trees[this._limitZoom(t)],a=r.range(k(i),P(n),k(s),P(o)),l=r.data,c=[];for(const e of a){const t=this.stride*e;c.push(l[t+5]>1?M(l,t,this.clusterProps):this.points[l[t+3]]);}return c}getChildren(e){const t=this._getOriginId(e),i=this._getOriginZoom(e),o="No cluster with the specified id.",s=this.trees[i];if(!s)throw new Error(o);const n=s.data;if(t*this.stride>=n.length)throw new Error(o);const r=this.options.radius/(this.options.extent*Math.pow(2,i-1)),a=s.within(n[t*this.stride],n[t*this.stride+1],r),l=[];for(const t of a){const i=t*this.stride;n[i+4]===e&&l.push(n[i+5]>1?M(n,i,this.clusterProps):this.points[n[i+3]]);}if(0===l.length)throw new Error(o);return l}getLeaves(e,t,i){const o=[];return this._appendLeaves(o,e,t=t||10,i=i||0,0),o}getTile(e,t,i){const o=this.trees[this._limitZoom(e)],s=Math.pow(2,e),{extent:n,radius:r}=this.options,a=r/n,l=(i-a)/s,c=(i+1+a)/s,u={features:[]};return this._addTileFeatures(o.range((t-a)/s,l,(t+1+a)/s,c),o.data,t,i,s,u),0===t&&this._addTileFeatures(o.range(1-a/s,l,1,c),o.data,s,i,s,u),t===s-1&&this._addTileFeatures(o.range(0,l,a/s,c),o.data,-1,i,s,u),u.features.length?u:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const i=this.getChildren(e);if(t++,1!==i.length)break;e=i[0].properties.cluster_id;}return t}_appendLeaves(e,t,i,o,s){const n=this.getChildren(t);for(const t of n){const n=t.properties;if(n&&n.cluster?s+n.point_count<=o?s+=n.point_count:s=this._appendLeaves(e,n.cluster_id,i,o,s):s1;let l,c,u;if(a)l=I(t,e,this.clusterProps),c=t[e],u=t[e+1];else {const i=this.points[t[e+3]];l=i.properties;const[o,s]=i.geometry.coordinates;c=k(o),u=P(s);}const h={type:1,geometry:[[Math.round(this.options.extent*(c*s-i)),Math.round(this.options.extent*(u*s-o))]],tags:l};let d;d=a||this.options.generateId?t[e+3]:this.points[t[e+3]].id,void 0!==d&&(h.id=d),n.features.push(h);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:i,extent:o,reduce:s,minPoints:n}=this.options,r=i/(o*Math.pow(2,t)),a=e.data,l=[],c=this.stride;for(let i=0;it&&(f+=a[i+5]);}if(f>d&&f>=n){let e,n=o*d,r=u*d,g=-1;const p=(i/c<<5)+(t+1)+this.points.length;for(const o of h){const l=o*c;if(a[l+2]<=t)continue;a[l+2]=t;const u=a[l+5];n+=a[l]*u,r+=a[l+1]*u,a[l+4]=p,s&&(e||(e=this._map(a,i,!0),g=this.clusterProps.length,this.clusterProps.push(e)),s(e,this._map(a,l)));}a[i+4]=p,l.push(n/f,r/f,1/0,p,-1,f),s&&l.push(g);}else {for(let e=0;e1)for(const e of h){const i=e*c;if(!(a[i+2]<=t)){a[i+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,i){if(e[t+5]>1){const o=this.clusterProps[e[t+6]];return i?Object.assign({},o):o}const o=this.points[e[t+3]].properties,s=this.options.map(o);return i&&s===o?Object.assign({},s):s}}function M(e,t,i){return {type:"Feature",id:e[t+3],properties:I(e,t,i),geometry:{type:"Point",coordinates:[(o=e[t],360*(o-.5)),T(e[t+1])]}};var o;}function I(e,t,i){const o=e[t+5],s=o>=1e4?`${Math.round(o/1e3)}k`:o>=1e3?Math.round(o/100)/10+"k":o,n=e[t+6],r=-1===n?{}:Object.assign({},i[n]);return Object.assign(r,{cluster:!0,cluster_id:e[t+3],point_count:o,point_count_abbreviated:s})}function k(e){return e/360+.5}function P(e){const t=Math.sin(e*Math.PI/180),i=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return i<0?0:i>1?1:i}function T(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function D(e,t,i,o){let s=o;const n=t+(i-t>>1);let r,a=i-t;const l=e[t],c=e[t+1],u=e[i],h=e[i+1];for(let o=t+3;os)r=o,s=t;else if(t===s){const e=Math.abs(o-n);eo&&(r-t>3&&D(e,t,r,o),e[r+2]=s,i-r>3&&D(e,r,i,o));}function C(e,t,i,o,s,n){let r=s-i,a=n-o;if(0!==r||0!==a){const l=((e-i)*r+(t-o)*a)/(r*r+a*a);l>1?(i=s,o=n):l>0&&(i+=r*l,o+=a*l);}return r=e-i,a=t-o,r*r+a*a}function L(e,t,i,o){const s={id:null==e?null:e,type:t,geometry:i,tags:o,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===t||"MultiPoint"===t||"LineString"===t)O(s,i);else if("Polygon"===t)O(s,i[0]);else if("MultiLineString"===t)for(const e of i)O(s,e);else if("MultiPolygon"===t)for(const e of i)O(s,e[0]);return s}function O(e,t){for(let i=0;i0&&(r+=o?(s*l-a*n)/2:Math.sqrt(Math.pow(a-s,2)+Math.pow(l-n,2))),s=a,n=l;}const a=t.length-3;t[2]=1,D(t,0,a,i),t[a+2]=1,t.size=Math.abs(r),t.start=0,t.end=t.size;}function G(e,t,i,o){for(let s=0;s1?1:i}function j(e,t,i,o,s,n,r,a){if(o/=t,n>=(i/=t)&&r=o)return null;const l=[];for(const t of e){const e=t.geometry;let n=t.type;const r=0===s?t.minX:t.minY,c=0===s?t.maxX:t.maxY;if(r>=i&&c=o)continue;let u=[];if("Point"===n||"MultiPoint"===n)N(e,u,i,o,s);else if("LineString"===n)R(e,u,i,o,s,!1,a.lineMetrics);else if("MultiLineString"===n)J(e,u,i,o,s,!1);else if("Polygon"===n)J(e,u,i,o,s,!0);else if("MultiPolygon"===n)for(const t of e){const e=[];J(t,e,i,o,s,!0),e.length&&u.push(e);}if(u.length){if(a.lineMetrics&&"LineString"===n){for(const e of u)l.push(L(t.id,n,e,t.tags));continue}"LineString"!==n&&"MultiLineString"!==n||(1===u.length?(n="LineString",u=u[0]):n="MultiLineString"),"Point"!==n&&"MultiPoint"!==n||(n=3===u.length?"Point":"MultiPoint"),l.push(L(t.id,n,u,t.tags));}}return l.length?l:null}function N(e,t,i,o,s){for(let n=0;n=i&&r<=o&&Y(t,e[n],e[n+1],e[n+2]);}}function R(e,t,i,o,s,n,r){let a=W(e);const l=0===s?q:X;let c,u,h=e.start;for(let d=0;di&&(u=l(a,f,g,m,y,i),r&&(a.start=h+c*u)):v>o?w=i&&(u=l(a,f,g,m,y,i),x=!0),w>o&&v<=o&&(u=l(a,f,g,m,y,o),x=!0),!n&&x&&(r&&(a.end=h+c*u),t.push(a),a=W(e)),r&&(h+=c);}let d=e.length-3;const f=e[d],g=e[d+1],p=0===s?f:g;p>=i&&p<=o&&Y(a,f,g,e[d+2]),d=a.length-3,n&&d>=3&&(a[d]!==a[0]||a[d+1]!==a[1])&&Y(a,a[0],a[1],a[2]),a.length&&t.push(a);}function W(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function J(e,t,i,o,s,n){for(const r of e)R(r,t,i,o,s,n,!1);}function Y(e,t,i,o){e.push(t,i,o);}function q(e,t,i,o,s,n){const r=(n-t)/(o-t);return Y(e,n,i+(s-i)*r,1),r}function X(e,t,i,o,s,n){const r=(n-i)/(s-i);return Y(e,t+(o-t)*r,n,1),r}function H(e,t){const i=[];for(let o=0;o0&&t.size<(s?r:o))return void(i.numPoints+=t.length/3);const a=[];for(let e=0;er)&&(i.numSimplified++,a.push(t[e],t[e+1])),i.numPoints++;s&&function(e,t){let i=0;for(let t=0,o=e.length,s=o-2;t0===t)for(let t=0,i=e.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");let o=function(e,t){const i=[];if("FeatureCollection"===e.type)for(let o=0;o1&&console.time("creation"),d=this.tiles[h]=U(e,t,i,o,l),this.tileCoords.push({z:t,x:i,y:o}),c)){c>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,i,o,d.numFeatures,d.numPoints,d.numSimplified),console.timeEnd("creation"));const e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++;}if(d.source=e,null==s){if(t===l.indexMaxZoom||d.numPoints<=l.indexMaxPoints)continue}else {if(t===l.maxZoom||t===s)continue;if(null!=s){const e=s-t;if(i!==n>>e||o!==r>>e)continue}}if(d.source=null,0===e.length)continue;c>1&&console.time("clipping");const f=.5*l.buffer/l.extent,g=.5-f,p=.5+f,m=1+f;let y=null,v=null,w=null,x=null,b=j(e,u,i-f,i+p,0,d.minX,d.maxX,l),S=j(e,u,i+g,i+m,0,d.minX,d.maxX,l);e=null,b&&(y=j(b,u,o-f,o+p,1,d.minY,d.maxY,l),v=j(b,u,o+g,o+m,1,d.minY,d.maxY,l),b=null),S&&(w=j(S,u,o-f,o+p,1,d.minY,d.maxY,l),x=j(S,u,o+g,o+m,1,d.minY,d.maxY,l),S=null),c>1&&console.timeEnd("clipping"),a.push(y||[],t+1,2*i,2*o),a.push(v||[],t+1,2*i,2*o+1),a.push(w||[],t+1,2*i+1,2*o),a.push(x||[],t+1,2*i+1,2*o+1);}}getTile(e,t,i){e=+e,t=+t,i=+i;const o=this.options,{extent:s,debug:n}=o;if(e<0||e>24)return null;const r=1<1&&console.log("drilling down to z%d-%d-%d",e,t,i);let l,c=e,u=t,h=i;for(;!l&&c>0;)c--,u>>=1,h>>=1,l=this.tiles[ie(c,u,h)];return l&&l.source?(n>1&&(console.log("found parent tile z%d-%d-%d",c,u,h),console.time("drilling down")),this.splitTile(l.source,c,u,h,e,t,i),n>1&&console.timeEnd("drilling down"),this.tiles[a]?B(this.tiles[a],s):null):null}}function ie(e,t,i){return 32*((1<{r.properties=e;const t={};for(const e of a)t[e]=o[e].evaluate(n,r);return t},t.reduce=(e,t)=>{r.properties=t;for(const t of a)n.accumulated=e[t],e[t]=s[t].evaluate(n,r);},t}(t)).load(i.features):function(e,t){return new te(e,t)}(i,t.geojsonVtOptions),this.loaded={};const s={data:i};if(o){const e=o.finish();e&&(s.resourceTiming={},s.resourceTiming[t.source]=JSON.parse(JSON.stringify(e)));}return s}catch(t){if(delete this._pendingRequest,e.cy(t))return {abandoned:!0};throw t}}))}getData(){return e._(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(e){const t=this.loaded;return t&&t[e.uid]?super.reloadTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){let o=yield this.loadGeoJSON(t,i);if(delete this._pendingRequest,"object"!=typeof o)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(u(o,!0),t.filter){const i=e.cT(t.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===i.result)throw new Error(i.value.map((e=>`${e.key}: ${e.message}`)).join(", "));const s=o.features.filter((e=>i.value.evaluate({zoom:0},e)));o={type:"FeatureCollection",features:s};}return o}))}loadGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){const{promoteId:o}=t;if(t.request){const s=yield e.j(t.request,i);return this._dataUpdateable=e.cV(s.data,o)?e.cU(s.data,o):void 0,s.data}if("string"==typeof t.data)try{const i=JSON.parse(t.data);return this._dataUpdateable=e.cV(i,o)?e.cU(i,o):void 0,i}catch(e){throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}if(!t.dataDiff)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${t.source}`);return e.cW(this._dataUpdateable,t.dataDiff,o),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(t){return e._(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset)}}class se{constructor(t){this.self=t,this.actor=new e.J(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=new Map,this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.cA,this.self.removeProtocol=e.cB,this.self.registerRTLTextPlugin=t=>{e.cX.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,i)=>e._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(t,i.source).removeTile(i);})))),this.actor.registerMessageHandler("GCEZ",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterExpansionZoom(i)})))),this.actor.registerMessageHandler("GCC",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterChildren(i)})))),this.actor.registerMessageHandler("GCL",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterLeaves(i)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("GD",((e,t)=>this._getWorkerSource(e,t.type,t.source).getData())),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,i)=>e._(this,void 0,void 0,(function*(){if(!this.workerSources[t]||!this.workerSources[t][i.type]||!this.workerSources[t][i.type][i.source])return;const e=this.workerSources[t][i.type][i.source];delete this.workerSources[t][i.type][i.source],void 0!==e.removeSource&&e.removeSource(i);})))),this.actor.registerMessageHandler("RM",(t=>e._(this,void 0,void 0,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t],this.globalStates.delete(t);})))),this.actor.registerMessageHandler("SR",((t,i)=>e._(this,void 0,void 0,(function*(){this.referrer=i;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,i)=>e._(this,void 0,void 0,(function*(){this.self.importScripts(i);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).update(i.layers,i.removedIds,this._getGlobalState(t));})))),this.actor.registerMessageHandler("UGS",((t,i)=>e._(this,void 0,void 0,(function*(){const e=this._getGlobalState(t);for(const t in i)e[t]=i[t];})))),this.actor.registerMessageHandler("SL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).replace(i,this._getGlobalState(t));}))));}_getGlobalState(e){let t=this.globalStates.get(e);return t||(t={},this.globalStates.set(e,t)),t}_setImages(t,i){return e._(this,void 0,void 0,(function*(){this.availableImages[t]=i;for(const e in this.workerSources[t]){const o=this.workerSources[t][e];for(const e in o)o[e].availableImages=i;}}))}_syncRTLPluginState(t,i){return e._(this,void 0,void 0,(function*(){return yield e.cX.syncState(i,this.self.importScripts)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(e){let i=this.layerIndexes[e];return i||(i=this.layerIndexes[e]=new t),i}_getWorkerSource(e,t,i){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][i]){const o={sendAsync:(t,i)=>(t.targetMapId=e,this.actor.sendAsync(t,i))};switch(t){case "vector":this.workerSources[e][t][i]=new n(o,this._getLayerIndex(e),this._getAvailableImages(e));break;case "geojson":this.workerSources[e][t][i]=new oe(o,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][i]=new this.externalWorkerSourceTypes[t](o,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][t][i]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new r),this.demWorkerSources[e][t]}}return e.i(self)&&(self.worker=new se(self)),se})); + +define("index",["exports","./shared"],(function(e,t){"use strict";var i="5.7.2";function o(){var e=new t.A(4);return t.A!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}let r,a;const s={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frame(e,i,o){const r=requestAnimationFrame((e=>{a(),i(e);})),{unsubscribe:a}=t.s(e.signal,"abort",(()=>{a(),cancelAnimationFrame(r),o(t.c());}),!1);},frameAsync(e){return new Promise(((t,i)=>{this.frame(e,t,i);}))},getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(r||(r=document.createElement("a")),r.href=e,r.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==a&&(a=matchMedia("(prefers-reduced-motion: reduce)")),a.matches)}};class n{static testProp(e){if(!n.docStyle)return e[0];for(let t=0;t{window.removeEventListener("click",n.suppressClickInternal,!0);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,o){const r=i.boundingClientRect;return new t.P((o.clientX-r.left)/i.x-e.clientLeft,(o.clientY-r.top)/i.y-e.clientTop)}static mousePos(e,t){const i=n.getScale(e);return n.getPoint(e,i,t)}static touchPos(e,t){const i=[],o=n.getScale(e);for(let r=0;r{c&&_(c),c=null,d=!0;},h.onerror=()=>{u=!0,c=null;},h.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(e){let i,o,r,a;e.resetRequestQueue=()=>{i=[],o=0,r=0,a={};},e.addThrottleControl=e=>{const t=r++;return a[t]=e,t},e.removeThrottleControl=e=>{delete a[e],n();},e.getImage=(e,o,r=!0)=>new Promise(((a,s)=>{l.supported&&(e.headers||(e.headers={}),e.headers.accept="image/webp,*/*"),t.e(e,{type:"image"}),i.push({abortController:o,requestParameters:e,supportImageRefresh:r,state:"queued",onError:e=>{s(e);},onSuccess:e=>{a(e);}}),n();}));const s=e=>t._(this,void 0,void 0,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:r,onError:a,onSuccess:s,abortController:l}=e,h=!1===r&&!t.i(self)&&!t.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),!0));o++;const u=h?c(i,l):t.m(i,l);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.b(i.data)?s(i):i.data&&s({data:yield(d=i.data,"function"==typeof createImageBitmap?t.f(d):t.h(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,a(t);}finally{o--,n();}var d;})),n=()=>{const e=(()=>{for(const e of Object.keys(a))if(a[e]())return !0;return !1})()?t.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=o;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:s(e);}},c=(e,i)=>new Promise(((o,r)=>{const a=new Image,s=e.url,n=e.credentials;n&&"include"===n?a.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.d(s))&&(a.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{a.src="",r(t.c());})),a.fetchPriority="high",a.onload=()=>{a.onerror=a.onload=null,o({data:a});},a.onerror=()=>{a.onerror=a.onload=null,i.signal.aborted||r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));},a.src=s;}));}(p||(p={})),p.resetRequestQueue();class m{constructor(e){this._transformRequestFn=null!=e?e:null;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}function f(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:o,url:r}of e){const e=`${o}${r}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:o,url:r}));}}return t}function g(e,t,i){try{const o=new URL(e);return o.pathname+=`${t}${i}`,o.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}function v(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class b extends t.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.R({width:1,height:1}),this.dirty=!0;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.R({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let o=!0;const r=i.data||i.spriteData;return this._validateStretch(i.stretchX,r&&r.width)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchX" value`))),o=!1),this._validateStretch(i.stretchY,r&&r.height)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchY" value`))),o=!1),this._validateContent(i.content,i)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "content" value`))),o=!1),o}_validateStretch(e,t){if(!e)return !0;let i=0;for(const o of e){if(o[0]{let o=!0;if(!this.isLoaded())for(const t of e)this.images[t]||(o=!1);this.isLoaded()||o?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const o of e){let e=this.getImage(o);e||(this.fire(new t.l("styleimagemissing",{id:o})),e=this.getImage(o)),e?i[o]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.w(`Image "${o}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);}return i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],o=this.getImage(e);if(!o)return null;if(i&&i.position.version===o.version)return i.position;if(i)i.position.version=o.version;else {const i={w:o.data.width+2,h:o.data.height+2,x:0,y:0},r=new t.I(i,o);this.patterns[e]={bin:i,position:r};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const i=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new t.T(e,this.atlasImage,i.RGBA),this.atlasTexture.bind(i.LINEAR,i.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:o}=t.p(e),r=this.atlasImage;r.resize({width:i||1,height:o||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],o=i.x+1,a=i.y+1,s=this.getImage(e).data,n=s.width,l=s.height;t.R.copy(s,r,{x:0,y:0},{x:o,y:a},{width:n,height:l}),t.R.copy(s,r,{x:0,y:l-1},{x:o,y:a-1},{width:n,height:1}),t.R.copy(s,r,{x:0,y:0},{x:o,y:a+l},{width:n,height:1}),t.R.copy(s,r,{x:n-1,y:0},{x:o-1,y:a},{width:1,height:l}),t.R.copy(s,r,{x:0,y:0},{x:o+n,y:a},{width:1,height:l});}this.dirty=!0;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=!0;const e=this.getImage(i);e||t.w(`Image with ID: "${i}" was not found`),v(e)&&this.updateImage(i,e);}}}const x=1e20;function y(e,t,i,o,r,a,s,n,l){for(let c=t;c-1);l++,a[l]=n,s[l]=c,s[l+1]=x;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(t.ranges[r])return {stack:e,id:i,glyph:o};if(!this.url)throw new Error("glyphsUrl is not set");if(!t.requests[r]){const i=T.loadGlyphRange(e,r,this.url,this.requestManager);t.requests[r]=i;}const a=yield t.requests[r];for(const e in a)this._doesCharSupportLocalGlyph(+e)||(t.glyphs[+e]=a[+e]);return t.ranges[r]=!0,{stack:e,id:i,glyph:a[i]||null}}))}_doesCharSupportLocalGlyph(e){return !!this.localIdeographFontFamily&&(/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(e))||t.u["CJK Unified Ideographs"](e)||t.u["Hangul Syllables"](e)||t.u.Hiragana(e)||t.u.Katakana(e)||t.u["CJK Symbols and Punctuation"](e)||t.u["Halfwidth and Fullwidth Forms"](e))}_tinySDF(e,i,o){const r=this.localIdeographFontFamily;if(!r)return;if(!this._doesCharSupportLocalGlyph(o))return;let a=e.tinySDF;if(!a){let t="400";/bold/i.test(i)?t="900":/medium/i.test(i)?t="500":/light/i.test(i)&&(t="200"),a=e.tinySDF=new T.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,lang:this.lang,fontFamily:r,fontWeight:t});}const s=a.draw(String.fromCharCode(o));return {id:o,bitmap:new t.q({width:s.width||60,height:s.height||60},s.data),metrics:{width:s.glyphWidth/2||24,height:s.glyphHeight/2||24,left:s.glyphLeft/2+.5||0,top:s.glyphTop/2-27.5||-8,advance:s.glyphAdvance/2||24,isDoubleResolution:!0}}}}T.loadGlyphRange=function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=256*i,s=a+255,n=r.transformRequest(o.replace("{fontstack}",e).replace("{range}",`${a}-${s}`),"Glyphs"),l=yield t.n(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${a}-${s}`);const c={};for(const e of t.o(l.data))c[e.id]=e;return c}))},T.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:o=.25,fontFamily:r="sans-serif",fontWeight:a="normal",fontStyle:s="normal",lang:n=null}={}){this.buffer=t,this.cutoff=o,this.radius=i,this.lang=n;const l=this.size=e+4*t,c=this._createCanvas(l),h=this.ctx=c.getContext("2d",{willReadFrequently:!0});h.font=`${s} ${a} ${e}px ${r}`,h.textBaseline="alphabetic",h.textAlign="left",h.fillStyle="black",this.gridOuter=new Float64Array(l*l),this.gridInner=new Float64Array(l*l),this.f=new Float64Array(l),this.z=new Float64Array(l+1),this.v=new Uint16Array(l);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:o,actualBoundingBoxLeft:r,actualBoundingBoxRight:a}=this.ctx.measureText(e),s=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(a-r))),l=Math.min(this.size-this.buffer,s+Math.ceil(o)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:s,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;this.lang&&(p.lang=this.lang),p.clearRect(m,m,n,l),p.fillText(e,m,m+s);const v=p.getImageData(m,m,n,l);g.fill(x,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[o]=e<0?e*e:0;}}y(g,0,0,c,h,c,this.f,this.v,this.z),y(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(s=e[++a]);const l=Math.abs(n-s.left),c=Math.abs(n-s.right),h=Math.min(l,c);let u;const d=t/i*(o+1);if(s.isDash){const e=o-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=o-Math.sqrt(h*h+d*d);this.data[r+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],o=e[t+1];i.zeroLength?e.splice(t,1):o&&o.isDash===i.isDash&&(o.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const o=this.width*this.nextRow;let r=0,a=e[r];for(let t=0;t1&&(a=e[++r]);const i=Math.abs(t-a.left),s=Math.abs(t-a.right),n=Math.min(i,s);this.data[o+t]=Math.max(0,Math.min(255,(a.isDash?n:-n)+128));}}addDash(e,i){const o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.w("LineAtlas out of space"),null;let a=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[R]}numActive(){return Object.keys(this.active).length}}const D=Math.floor(s.hardwareConcurrency/2);let A,L;function k(){return A||(A=new z),A}z.workerCount=t.H(globalThis)?Math.max(Math.min(D,3),1):1;class F{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const o=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}}function B(){return L||(L=new F(k(),t.K),L.registerMessageHandler("GR",((e,i,o)=>t.m(i,o)))),L}function O(e,i){const o=t.L();return t.M(o,o,[1,1,0]),t.N(o,o,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.O(o,o,e.calculatePosMatrix(i.toUnwrapped())):o}function j(e,t,i,o,r,a,s){var n;const l=function(e,t,i){if(e)for(const o of e){const e=t[o];if(e&&e.source===i&&"fill-extrusion"===e.type)return !0}else for(const e in t){const o=t[e];if(o.source===i&&"fill-extrusion"===o.type)return !0}return !1}(null!==(n=null==r?void 0:r.layers)&&void 0!==n?n:null,t,e.id),c=a.maxPitchScaleFactor(),h=e.tilesIn(o,c,l);h.sort(N);const u=[];for(const o of h)u.push({wrappedTileID:o.tileID.wrapped().key,queryResults:o.tile.queryRenderedFeatures(t,i,e._state,o.queryGeometry,o.cameraQueryGeometry,o.scale,r,a,c,O(e.transform,o.tileID),s?(e,t)=>s(o.tileID,e,t):void 0)});return function(e,t){for(const i in e)for(const o of e[i])U(o,t);return e}(function(e){const t={},i={};for(const o of e){const e=o.queryResults,r=o.wrappedTileID,a=i[r]=i[r]||{};for(const i in e){const o=e[i],r=a[i]=a[i]||{},s=t[i]=t[i]||[];for(const e of o)r[e.featureIndex]||(r[e.featureIndex]=!0,s.push(e));}}return t}(u),e)}function N(e,t){const i=e.tileID,o=t.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}function U(e,t){const i=e.feature,o=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=o;}function Z(e,i,o){return t._(this,void 0,void 0,(function*(){let r=e;if(e.url?r=(yield t.j(i.transformRequest(e.url,"Source"),o)).data:yield s.frameAsync(o),!r)return null;const a=t.Q(t.e(r,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in r&&r.vector_layers&&(a.vectorLayerIds=r.vector_layers.map((e=>e.id))),a}))}class G{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}extend(e){const i=this._sw,o=this._ne;let r,a;if(e instanceof t.S)r=e,a=e;else {if(!(e instanceof G))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(G.convert(e)):this.extend(t.S.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.S.convert(e)):this;if(r=e._sw,a=e._ne,!r||!a)return this}return i||o?(i.lng=Math.min(r.lng,i.lng),i.lat=Math.min(r.lat,i.lat),o.lng=Math.max(a.lng,o.lng),o.lat=Math.max(a.lat,o.lat)):(this._sw=new t.S(r.lng,r.lat),this._ne=new t.S(a.lng,a.lat)),this}getCenter(){return new t.S((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new t.S(this.getWest(),this.getNorth())}getSouthEast(){return new t.S(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(e){const{lng:i,lat:o}=t.S.convert(e);let r=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(r=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=o&&o<=this._ne.lat&&r}static convert(e){return e instanceof G?e:e?new G(e):e}static fromLngLat(e,i=0){const o=360*i/40075017,r=o/Math.cos(Math.PI/180*e.lat);return new G(new t.S(e.lng-r,e.lat-o),new t.S(e.lng+r,e.lat+o))}adjustAntiMeridian(){const e=new t.S(this._sw.lng,this._sw.lat),i=new t.S(this._ne.lng,this._ne.lat);return new G(e,e.lng>i.lng?new t.S(i.lng+360,i.lat):i)}}class V{constructor(e,t,i){this.bounds=G.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),o=Math.floor(t.V(this.bounds.getWest())*i),r=Math.floor(t.U(this.bounds.getNorth())*i),a=Math.ceil(t.V(this.bounds.getEast())*i),s=Math.ceil(t.U(this.bounds.getSouth())*i);return e.x>=o&&e.x=r&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.e({},this._options)}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};i.request.collectResourceTiming=this._collectResourceTiming;let o="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),o="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:o,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_afterTileLoadWorkerResponse(e,t){if(t&&t.resourceTiming&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return !1}}class q extends t.E{constructor(e,i,o,r){super(),this.id=e,this.dispatcher=o,this.setEventedParent(r),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.e({type:"raster"},i),t.e(this,t.Q(i,["url","scheme","tileSize"]));}load(){return t._(this,arguments,void 0,(function*(e=!1){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield Z(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,i&&(t.e(this,i),i.bounds&&(this.tileBounds=new V(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.l("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(!0);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.e({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const o=yield p.getImage(this.map._requestManager.transformRequest(i,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(o&&o.data){this.map._refreshExpiredTiles&&(o.cacheControl||o.expires)&&e.setExpiryData({cacheControl:o.cacheControl,expires:o.expires});const i=this.map.painter.context,r=i.gl,a=o.data;e.texture=this.map.painter.getTileTexture(a.width),e.texture?e.texture.update(a,{useMipmap:!0}):(e.texture=new t.T(i,a,r.RGBA,{useMipmap:!0}),e.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return !1}}class W extends q{constructor(e,i,o,r){super(e,i,o,r),this.type="raster-dem",this.maxzoom=22,this._options=t.e({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),o=this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield p.getImage(o,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const o=i.data;this.map._refreshExpiredTiles&&(i.cacheControl||i.expires)&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const r=t.b(o)&&t.W()?o:yield this.readImageNow(o),a={type:this.type,uid:e.uid,source:this.id,rawImageData:r,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!e.actor||"expired"===e.state){e.actor=this.dispatcher.getActor();const t=yield e.actor.sendAsync({type:"LDT",data:a});e.dem=t,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t._(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&t.X()){const i=e.width+2,o=e.height+2;try{return new t.R({width:i,height:o},yield t.Y(e,-1,-1,i,o))}catch(e){}}return s.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,o=Math.pow(2,i.z),r=(i.x-1+o)%o,a=0===i.x?e.wrap-1:e.wrap,s=(i.x+1+o)%o,n=i.x+1===o?e.wrap+1:e.wrap,l={};return l[new t.Z(e.overscaledZ,a,i.z,r,i.y).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y).key]={backfilled:!1},i.y>0&&(l[new t.Z(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y-1).key]={backfilled:!1}),i.y+1e.coordinates)).flat(1/0):e.coordinates.flat(1/0)}getBounds(){return t._(this,void 0,void 0,(function*(){const e=new G,t=yield this.getData();let i;switch(t.type){case "FeatureCollection":i=t.features.map((e=>this.getCoordinatesFromGeometry(e.geometry))).flat(1/0);break;case "Feature":i=this.getCoordinatesFromGeometry(t.geometry);break;default:i=this.getCoordinatesFromGeometry(t);}if(0==i.length)return e;for(let t=0;t0&&t.e(r,{resourceTiming:i}),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"metadata"}))),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"content"})));}catch(e){if(this._isUpdatingWorker=!1,this._removed)return void this.fire(new t.l("dataabort",{dataType:"source"}));this.fire(new t.k(e));}finally{(this._pendingWorkerUpdate.data||this._pendingWorkerUpdate.diff)&&this._updateWorkerData();}}))}loaded(){return !this._isUpdatingWorker&&void 0===this._pendingWorkerUpdate.data&&void 0===this._pendingWorkerUpdate.diff}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};e.abortController=new AbortController;const o=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(o,this.map.painter,"RT"===t);}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=!0;}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return !1}}class X extends t.E{constructor(e,t,i,o){super(),this.flippedWindingOrder=!1,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(o),this.options=t;}load(e){return t._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield p.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.a1.fromLngLat);var o;return this.tileID=function(e){const i=t.a2.fromPoints(e),o=i.width(),r=i.height(),a=Math.max(o,r),s=Math.max(0,Math.floor(-Math.log(a)/Math.LN2)),n=Math.pow(2,s);return new t.a4(s,Math.floor((i.minX+i.maxX)/2*n),Math.floor((i.minY+i.maxY)/2*n))}(i),this.terrainTileRanges=this._getOverlappingTileRanges(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((o=this.tileCoords)[1].x-o[0].x)*(o[2].y-o[0].y)-(o[1].y-o[0].y)*(o[2].x-o[0].x)<0,this.fire(new t.l("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new t.T(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t._(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return !1}_getOverlappingTileRanges(e){const{minX:i,minY:o,maxX:r,maxY:a}=t.a2.fromPoints(e),s={};for(let e=0;e<=t.a3;e++){const t=Math.pow(2,e),n=Math.floor(i*t),l=Math.floor(o*t),c=Math.floor(r*t),h=Math.floor(a*t);s[e]={minTileX:n,minTileY:l,maxTileX:c,maxTileY:h};}return s}}class K extends X{constructor(e,t,i,o){super(e,t,i,o),this.roundZoom=!0,this.type="video",this.options=t;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!1;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,"Source").url);try{const e=yield t.a5(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.k(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.k(new t.a6(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.T(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class Y extends X{constructor(e,i,o,r){super(e,i,o,r),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.k(new t.a6(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.k(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,o=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.T(i,this.canvas,o.RGBA,{premultiply:!0});let r=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=!0);}r&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return !0;return !1}}const Q={},J=e=>{switch(e){case "geojson":return H;case "image":return X;case "raster":return q;case "raster-dem":return W;case "vector":return $;case "video":return K;case "canvas":return Y}return Q[e]},ee="RTLPluginLoaded";class te extends t.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=B();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t._(this,arguments,void 0,(function*(e,t=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=s.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.l(ee));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let ie=null;function oe(){return ie||(ie=new te),ie}class re{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=e,this.uid=t.a7(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(e){const t=e+this.timeAdded;tt.getLayer(e))).filter(Boolean);if(0!==e.length){o.layers=e,o.stateDependentLayerIds&&(o.stateDependentLayers=o.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=o;}}return i}(e.buckets,null==i?void 0:i.style),this.hasSymbolBuckets=!1;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9){if(this.hasSymbolBuckets=!0,!o)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9&&i.hasRTLText){this.hasRTLText=!0,oe().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.a8;}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const i=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new t.T(e,this.imageAtlas.image,i.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new t.T(e,this.glyphAtlasImage,i.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,o,r,a,s,n,l,c,h){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:o,cameraQueryGeometry:r,scale:a,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:s,queryPadding:this.queryPadding*l,getElevation:h},e,t,i):{}}querySourceFeatures(e,i){const o=this.latestFeatureIndex;if(!o||!o.rawTileData)return;const r=o.loadVTLayers(),a=i&&i.sourceLayer?i.sourceLayer:"",s=r._geojsonTileLayer||r[a];if(!s)return;const n=t.aa(null==i?void 0:i.filter,null==i?void 0:i.globalState),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=!1;else if(i)if(this.expirationTime{this.remove(e,r);}),i)),this.data[o].push(r),this.order.push(o),this.order.length>this.max){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}has(e){return e.wrapped().key in this.data}getAndRemove(e){return this.has(e)?this._getAndRemoveByKey(e.wrapped().key):null}_getAndRemoveByKey(e){const t=this.data[e].shift();return t.timeout&&clearTimeout(t.timeout),0===this.data[e].length&&delete this.data[e],this.order.splice(this.order.indexOf(e),1),t.value}getByKey(e){const t=this.data[e];return t?t[0].value:null}get(e){return this.has(e)?this.data[e.wrapped().key][0].value:null}remove(e,t){if(!this.has(e))return this;const i=e.wrapped().key,o=void 0===t?0:this.data[i].indexOf(t),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(e){for(this.max=e;this.order.length>this.max;){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}filter(e){const t=[];for(const i in this.data)for(const o of this.data[i])e(o.value)||t.push(o);for(const e of t)this.remove(e.value.tileID,e);}}class se{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(e,i,o){const r=String(i);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][r]=this.stateChanges[e][r]||{},t.e(this.stateChanges[e][r],o),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==r&&(this.deletedStates[e][t]=null);}else if(this.deletedStates[e]&&null===this.deletedStates[e][r]){this.deletedStates[e][r]={};for(const t in this.state[e][r])o[t]||(this.deletedStates[e][r][t]=null);}else for(const t in o)this.deletedStates[e]&&this.deletedStates[e][r]&&null===this.deletedStates[e][r][t]&&delete this.deletedStates[e][r][t];}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const o=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&void 0!==t)null!==this.deletedStates[e][o]&&(this.deletedStates[e][o]=this.deletedStates[e][o]||{},this.deletedStates[e][o][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][o])for(i in this.deletedStates[e][o]={},this.stateChanges[e][o])this.deletedStates[e][o][i]=null;else this.deletedStates[e][o]=null;else this.deletedStates[e]=null;}getState(e,i){const o=String(i),r=t.e({},(this.state[e]||{})[o],(this.stateChanges[e]||{})[o]);if(null===this.deletedStates[e])return {};if(this.deletedStates[e]){const t=this.deletedStates[e][i];if(null===t)return {};for(const e in t)delete r[e];}return r}initializeTileState(e,t){e.setFeatureState(this.state,t);}coalesceChanges(e,i){const o={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const i={};for(const o in this.stateChanges[e])this.state[e][o]||(this.state[e][o]={}),t.e(this.state[e][o],this.stateChanges[e][o]),i[o]=this.state[e][o];o[e]=i;}for(const e in this.deletedStates){this.state[e]=this.state[e]||{};const i={};if(null===this.deletedStates[e])for(const t in this.state[e])i[t]={},this.state[e][t]={};else for(const t in this.deletedStates[e]){if(null===this.deletedStates[e][t])this.state[e][t]={};else for(const i of Object.keys(this.deletedStates[e][t]))delete this.state[e][t][i];i[t]=this.state[e][t];}o[e]=o[e]||{},t.e(o[e],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(o).length)for(const t in e)e[t].setFeatureState(o,i);}}const ne=89.25;function le(e,i){const o=t.ah(i.lat,-t.ai,t.ai);return new t.P(t.V(i.lng)*e,t.U(o)*e)}function ce(e,i){return new t.a1(i.x/e,i.y/e).toLngLat()}function he(e){return e.cameraToCenterDistance*Math.min(.85*Math.tan(t.ae(90-e.pitch)),Math.tan(t.ae(ne-e.pitch)))}function ue(e,i){const o=e.canonical,r=i/t.af(o.z),a=o.x+Math.pow(2,o.z)*e.wrap,s=t.ag(new Float64Array(16));return t.M(s,s,[a*r,o.y*r,0]),t.N(s,s,[r/t.$,r/t.$,1]),s}function de(e,i,o,r,a){const s=t.a1.fromLngLat(e,i),n=a*t.aj(1,e.lat),l=n*Math.cos(t.ae(o)),c=Math.sqrt(n*n-l*l),h=c*Math.sin(t.ae(-r)),u=c*Math.cos(t.ae(-r));return new t.a1(s.x+h,s.y+u,s.z+l)}function _e(e,t,i){const o=t.intersectsFrustum(e);if(!i||0===o)return o;const r=t.intersectsPlane(i);return 0===r?0:2===o&&2===r?2:1}function pe(e,t,i){let o=0;const r=(i-t)/10;for(let a=0;a<10;a++)o+=r*Math.pow(Math.cos(t+(a+.5)/10*(i-t)),e);return o}function me(e,i){return function(o,r,a,s,n){const l=2*((e-1)/t.ak(Math.cos(t.ae(ne-n))/Math.cos(t.ae(ne)))-1),c=Math.acos(a/s),h=2*pe(l-1,0,t.ae(n/2)),u=Math.min(t.ae(ne),c+t.ae(n/2)),d=pe(l-1,Math.min(u,c-t.ae(n/2)),u),_=Math.atan(r/a),p=Math.hypot(r,a);let m=o;return m+=t.ak(s/p/Math.max(.5,Math.cos(t.ae(n/2)))),m+=l*t.ak(Math.cos(_))/2,m-=t.ak(Math.max(1,d/h/i))/2,m}}const fe=me(9.314,3);function ge(e,i){const o=(i.roundZoom?Math.round:Math.floor)(e.zoom+t.ak(e.tileSize/i.tileSize));return Math.max(0,o)}function ve(e,i){const o=e.getCameraFrustum(),r=e.getClippingPlane(),a=e.screenPointToMercatorCoordinate(e.getCameraPoint()),s=t.a1.fromLngLat(e.center,e.elevation);a.z=s.z+Math.cos(e.pitchInRadians)*e.cameraToCenterDistance/e.worldSize;const n=e.getCoveringTilesDetailsProvider(),l=n.allowVariableZoom(e,i),c=ge(e,i),h=i.minzoom||0,u=void 0!==i.maxzoom?i.maxzoom:e.maxZoom,d=Math.min(Math.max(0,c),u),_=Math.pow(2,d),p=[_*a.x,_*a.y,0],m=[_*s.x,_*s.y,0],f=Math.hypot(s.x-a.x,s.y-a.y),g=Math.abs(s.z-a.z),v=Math.hypot(f,g),b=e=>({zoom:0,x:0,y:0,wrap:e,fullyVisible:!1}),x=[],y=[];if(e.renderWorldCopies&&n.allowWorldCopies())for(let e=1;e<=3;e++)x.push(b(-e)),x.push(b(e));for(x.push(b(0));x.length>0;){const _=x.pop(),f=_.x,b=_.y;let w=_.fullyVisible;const T={x:f,y:b,z:_.zoom},P=n.getTileBoundingVolume(T,_.wrap,e.elevation,i);if(!w){const e=_e(o,P,r);if(0===e)continue;w=2===e;}const C=n.distanceToTile2d(a.x,a.y,T,P);let I=c;l&&(I=(i.calculateTileZoom||fe)(e.zoom+t.ak(e.tileSize/i.tileSize),C,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const M=Math.min(I,u);if(_.wrap=n.getWrap(s,T,_.wrap),_.zoom>=M){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return y.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}const be=t.a2.fromPoints([new t.P(0,0),new t.P(t.$,t.$)]);class xe extends t.E{constructor(e,t,i){super(),this.id=e,this.dispatcher=i,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=!1;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,o)=>{const r=new(J(t.type))(e,t,i,o);if(r.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${r.id}`);return r})(e,t,i,this),this._tiles={},this._cache=new ae(0,(e=>this._unloadTile(e))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new se,this._didEmitContent=!1,this._updated=!1;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e);}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return !0;if(!this._updated)return !1;for(const e in this._tiles){const t=this._tiles[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}return !0}getSource(){return this._source}pause(){this._paused=!0;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,o){return t._(this,void 0,void 0,(function*(){try{yield this._source.loadTile(e),this._tileLoaded(e,i,o);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.k(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.l("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const t in this._tiles){const i=this._tiles[t];i.upload(e),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(ye).map((e=>e.key))}getRenderableIds(e){const i=[];for(const t in this._tiles)this._isIdRenderable(t,e)&&i.push(this._tiles[t]);return e?i.sort(((e,i)=>{const o=e.tileID,r=i.tileID,a=new t.P(o.canonical.x,o.canonical.y)._rotate(-this.transform.bearingInRadians),s=new t.P(r.canonical.x,r.canonical.y)._rotate(-this.transform.bearingInRadians);return o.overscaledZ-r.overscaledZ||s.y-a.y||s.x-a.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(ye).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return !!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())}reload(e){if(this._paused)this._shouldReloadOnResume=!0;else {this._cache.reset();for(const t in this._tiles)e?this._reloadTile(t,"expired"):"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading");}}_reloadTile(e,i){return t._(this,void 0,void 0,(function*(){const t=this._tiles[e];t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,o){e.timeAdded=s.now(),"expired"===o&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.l("data",{dataType:"source",tile:e,coord:e.tileID}));}_backfillDEM(e){const t=this.getRenderableIds();for(let o=0;o1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,o),e.neighboringTiles&&e.neighboringTiles[a]&&(e.neighboringTiles[a].backfilled=!0)));}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,o){for(const r in this._tiles){let a=this._tiles[r];if(o[r]||!a.hasData()||a.tileID.overscaledZ<=t||a.tileID.overscaledZ>i)continue;let s=a.tileID;for(;a&&a.tileID.overscaledZ>t+1;){const e=a.tileID.scaledTo(a.tileID.overscaledZ-1);a=this._tiles[e.key],a&&a.hasData()&&(s=e);}let n=s;for(;n.overscaledZ>t;)if(n=n.scaledTo(n.overscaledZ-1),e[n.key]||e[n.canonical.key]){o[s.key]=s;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),o=this._getLoadedTile(t);if(o)return o}}findLoadedSibling(e){return this._getLoadedTile(e)}_getLoadedTile(e){const t=this._tiles[e.key];return t&&t.hasData()?t:this._cache.getByKey(e.wrapped().key)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,o=Math.ceil(e.height/this._source.tileSize)+1,r=Math.floor(i*o*(null===this._maxTileCacheZoomLevels?t.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),a="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(a);}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e={};for(const i in this._tiles){const o=this._tiles[i];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),e[o.tileID.key]=o;}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(e,this._tiles[e]);}}_updateCoveredAndRetainedTiles(e,t,i,o,r,a){const n={},l={},c=Object.keys(e),h=s.now();for(const i of c){const o=e[i],r=this._tiles[i];if(!r||0!==r.fadeEndTime&&r.fadeEndTime<=h)continue;const a=this.findLoadedParent(o,t),s=this.findLoadedSibling(o),c=a||s||null;c&&(this._addTile(c.tileID),n[c.tileID.key]=c.tileID),l[i]=o;}this._retainLoadedChildren(l,o,i,e);for(const t in n)e[t]||(this._coveredTiles[t]=!0,e[t]=n[t]);if(a){const t={},i={};for(const e of r)this._tiles[e.key].hasData()?t[e.key]=e:i[e.key]=e;for(const o in i){const r=i[o].children(this._source.maxzoom);this._tiles[r[0].key]&&this._tiles[r[1].key]&&this._tiles[r[2].key]&&this._tiles[r[3].key]&&(t[r[0].key]=e[r[0].key]=r[0],t[r[1].key]=e[r[1].key]=r[1],t[r[2].key]=e[r[2].key]=r[2],t[r[3].key]=e[r[3].key]=r[3],delete i[o]);}for(const o in i){const r=i[o],a=this.findLoadedParent(r,this._source.minzoom),s=this.findLoadedSibling(r),n=a||s||null;if(n){t[n.tileID.key]=e[n.tileID.key]=n.tileID;for(const e in t)t[e].isChildOf(n.tileID)&&delete t[e];}}for(const e in this._tiles)t[e]||(this._coveredTiles[e]=!0);}}update(e,i){if(!this._sourceLoaded||this._paused)return;let o;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?o=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.Z(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(o=ve(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(o=o.filter((e=>this._source.hasTile(e))))):o=[];const r=ge(e,this._source),a=Math.max(r-xe.maxOverzooming,this._source.minzoom),s=Math.max(r+xe.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const e={};for(const t of o)if(t.canonical.z>this._source.minzoom){const i=t.scaledTo(t.canonical.z-1);e[i.key]=i;const o=t.scaledTo(Math.max(this._source.minzoom,Math.min(t.canonical.z,5)));e[o.key]=o;}o=o.concat(Object.values(e));}const n=0===o.length&&!this._updated&&this._didEmitContent;this._updated=!0,n&&this.fire(new t.l("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(o,r);we(this._source.type)&&this._updateCoveredAndRetainedTiles(l,a,s,r,o,i);for(const e in l)this._tiles[e].clearFadeHold();const c=t.am(this._tiles,l);for(const e of c){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const o={},r={},a=Math.max(t-xe.maxOverzooming,this._source.minzoom),s=Math.max(t+xe.maxUnderzooming,this._source.minzoom),n={};for(const i of e){const e=this._addTile(i);o[i.key]=i,e.hasData()||tthis._source.maxzoom){const e=s.children(this._source.maxzoom)[0],t=this.getTile(e);if(t&&t.hasData()){o[e.key]=e;continue}}else {const e=s.children(this._source.maxzoom);if(4===e.length&&o[e[0].key]&&o[e[1].key]&&o[e[2].key]&&o[e[3].key])continue;if(1===e.length&&o[e[0].key])continue}let n=e.wasRequested();for(let t=s.overscaledZ-1;t>=a;--t){const a=s.scaledTo(t);if(r[a.key])break;if(r[a.key]=!0,e=this.getTile(a),!e&&n&&(e=this._addTile(a)),e){const t=e.hasData();if((t||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||n)&&(o[a.key]=a),n=e.wasRequested(),t)break}}}return o}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,o=this._tiles[e].tileID;for(;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}t.push(o.key);const e=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;o=e;}for(const e of t)this._loadedParentTiles[e]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const e in this._tiles){const t=this._tiles[e].tileID,i=this._getLoadedTile(t);this._loadedSiblingTiles[t.key]=i;}}_addTile(e){let i=this._tiles[e.key];if(i)return i;i=this._cache.getAndRemove(e),i&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));const o=i;return i||(i=new re(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._tiles[e.key]=i,o||this._source.fire(new t.l("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}refreshTiles(e){for(const t in this._tiles)(this._isIdRenderable(t)||"errored"==this._tiles[t].state)&&e.some((e=>e.equals(this._tiles[t].tileID.canonical)))&&this._reloadTile(t,"expired");}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=!0,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){const t=e.sourceDataType;"source"===e.dataType&&"metadata"===t&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===t&&(this.reload(e.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0);}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e in this._tiles)this._removeTile(e);this._cache.reset();}tilesIn(e,i,o){const r=[],a=this.transform;if(!a)return r;const s=a.getCoveringTilesDetailsProvider().allowWorldCopies(),n=o?a.getCameraQueryGeometry(e):e,l=e=>a.screenPointToMercatorCoordinate(e,this.terrain),c=this.transformBbox(e,l,!s),h=this.transformBbox(n,l,!s),u=this.getIds(),d=t.a2.fromPoints(h);for(let e=0;ee.getTilePoint(new t.a1(i.x,i.y))));if(i.expandBy(_),i.intersects(be)){const t=c.map((t=>e.getTilePoint(t))),i=h.map((t=>e.getTilePoint(t)));r.push({tile:o,tileID:s?e:e.unwrapTo(0),queryGeometry:t,cameraQueryGeometry:i,scale:l});}}}return r}transformBbox(e,i,o){let r=e.map(i);if(o){const o=t.a2.fromPoints(e);o.shrinkBy(.001*Math.min(o.width(),o.height()));const a=o.map(i);t.a2.fromPoints(r).covers(a)||(r=r.map((e=>e.x>.5?new t.a1(e.x-1,e.y,e.z):e)));}return r}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._tiles[e].tileID));return this.transform&&this.transform.populateCache(t),t}hasTransition(){if(this._source.hasTransition())return !0;if(we(this._source.type)){const e=s.now();for(const t in this._tiles)if(this._tiles[t].fadeEndTime>=e)return !0}return !1}setFeatureState(e,t,i){this._state.updateState(e=e||"_geojsonTileLayer",t,i);}removeFeatureState(e,t,i){this._state.removeFeatureState(e=e||"_geojsonTileLayer",t,i);}getFeatureState(e,t){return this._state.getState(e=e||"_geojsonTileLayer",t)}setDependencies(e,t,i){const o=this._tiles[e];o&&o.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)));}}function ye(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),o=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||o-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function we(e){return "raster"===e||"image"===e||"video"===e}xe.maxOverzooming=10,xe.maxUnderzooming=3;class Te{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(r-s)/n:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))}}function Pe(e,t){let i=!0;return "always"===e||"never"!==e&&"never"!==t||(i=!1),i}class Ce{constructor(e,t,i){const o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||o<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=o){if(r)return [{key:null,x1:e,y1:t,x2:i,y2:o}];for(let e=0;e0}hitTestCircle(e,t,i,o,r){const a=e-i,s=e+i,n=t-i,l=t+i;if(s<0||a>this.width||l<0||n>this.height)return !1;const c=[];return this._forEachCell(a,n,s,l,this._queryCellCircle,c,{hitTest:!0,overlapMode:o,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},r),c.length>0}_queryCell(e,t,i,o,r,a,s,n){const{seenUids:l,hitTest:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const r=this.bboxes;for(const s of u)if(!l.box[s]){l.box[s]=!0;const u=4*s,d=this.boxKeys[s];if(e<=r[u+2]&&t<=r[u+3]&&i>=r[u+0]&&o>=r[u+1]&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))&&(a.push({key:d,x1:r[u],y1:r[u+1],x2:r[u+2],y2:r[u+3]}),c))return !0}}const d=this.circleCells[r];if(null!==d){const r=this.circles;for(const s of d)if(!l.circle[s]){l.circle[s]=!0;const u=3*s,d=this.circleKeys[s];if(this._circleAndRectCollide(r[u],r[u+1],r[u+2],e,t,i,o)&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))){const e=r[u],t=r[u+1],i=r[u+2];if(a.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return !0}}}return !1}_queryCellCircle(e,t,i,o,r,a,s,n){const{circle:l,seenUids:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=!0;const i=4*t,o=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}const d=this.circleCells[r];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=!0;const i=3*t,o=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}}_forEachCell(e,t,i,o,r,a,s,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(o);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(r.call(this,e,t,i,o,this.xCellCount*l+d,a,s,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,o,r,a){const s=o-e,n=r-t,l=i+a;return l*l>s*s+n*n}_circleAndRectCollide(e,t,i,o,r,a,s){const n=(a-o)/2,l=Math.abs(e-(o+n));if(l>n+i)return !1;const c=(s-r)/2,h=Math.abs(t-(r+c));if(h>c+i)return !1;if(l<=n||h<=c)return !0;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function Ie(e,i,r){const a=t.L();if(!e){const{vecSouth:e,vecEast:t}=Se(i),r=o();r[0]=t[0],r[1]=t[1],r[2]=e[0],r[3]=e[1],s=r,(d=(l=(n=r)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(s[0]=u*(d=1/d),s[1]=-c*d,s[2]=-h*d,s[3]=l*d),a[0]=r[0],a[1]=r[1],a[4]=r[2],a[5]=r[3];}var s,n,l,c,h,u,d;return t.N(a,a,[1/r,1/r,1]),a}function Me(e,i,o,r){if(e){const e=t.L();if(!i){const{vecSouth:t,vecEast:i}=Se(o);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.N(e,e,[r,r,1]),e}return o.pixelsToClipSpaceMatrix}function Se(e){const i=Math.cos(e.rollInRadians),o=Math.sin(e.rollInRadians),r=Math.cos(e.pitchInRadians),a=Math.cos(e.bearingInRadians),s=Math.sin(e.bearingInRadians),n=t.ar();n[0]=-a*r*o-s*i,n[1]=-s*r*o+a*i;const l=t.as(n);l<1e-9?t.at(n):t.au(n,n,1/l);const c=t.ar();c[0]=a*r*i-s*o,c[1]=s*r*i+a*o;const h=t.as(c);return h<1e-9?t.at(c):t.au(c,c,1/h),{vecEast:c,vecSouth:n}}function Ee(e,i,o,r){let a;r?(a=[e,i,r(e,i),1],t.aw(a,a,o)):(a=[e,i,0,1],qe(a,a,o));const s=a[3];return {point:new t.P(a[0]/s,a[1]/s),signedDistanceFromCamera:s,isOccluded:!1}}function Re(e,t){return .5+e/t*.5}function ze(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function De(e,i,o,r,a,s,n,l,c,h,u,d,_){const p=o?e.textSizeData:e.iconSizeData,m=t.an(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=o?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,b=o?e.text.placedSymbolArray:e.icon.placedSymbolArray,x=i.transform.width/i.transform.height;let y=!1;for(let o=0;oMath.abs(o.x-i.x)*r?{useVertical:!0}:(e===t.ao.vertical?i.yo.x)?{needsFlipping:!0}:null}function ke(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:o,symbol:r,fontSize:a,flip:s,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=a/24,_=r.lineOffsetX*d,p=r.lineOffsetY*d;let m;if(r.numGlyphs>1){const e=r.glyphStartIndex+r.numGlyphs,t=r.lineStartIndex,a=r.lineStartIndex+r.lineLength,c=Ae(d,l,_,p,s,r,u,i);if(!c)return {notEnoughRoom:!0};const f=je(c.first.point.x,c.first.point.y,i,o),g=je(c.last.point.x,c.last.point.y,i,o);if(n&&!s){const e=Le(r.writingMode,f,g,h);if(e)return e}m=[c.first];for(let o=r.glyphStartIndex+1;o0?n.point:Fe(i.tileAnchorPoint,s,e,1,i),c=je(e.x,e.y,i,o),u=je(l.x,l.y,i,o),d=Le(r.writingMode,c,u,h);if(d)return d}const e=Ge(d*l.getoffsetX(r.glyphStartIndex),_,p,s,r.segment,r.lineStartIndex,r.lineStartIndex+r.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:!0};m=[e];}for(const e of m)t.av(c,e.point,e.angle);return {}}function Fe(e,t,i,o,r){const a=e.add(e.sub(t)._unit()),s=Oe(a.x,a.y,r).point,n=i.sub(s);return i.add(n._mult(o/n.mag()))}function Be(e,i,o){const r=i.projectionCache;if(r.projections[e])return r.projections[e];const a=new t.P(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),s=Oe(a.x,a.y,i);if(s.signedDistanceFromCamera>0)return r.projections[e]=s.point,r.anyProjectionOccluded=r.anyProjectionOccluded||s.isOccluded,s.point;const n=e-o.direction;return Fe(0===o.distanceFromAnchor?i.tileAnchorPoint:new t.P(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),a,o.previousVertex,o.absOffsetX-o.distanceFromAnchor+1,i)}function Oe(e,t,i){const o=e+i.translation[0],r=t+i.translation[1];let a;return i.pitchWithMap?(a=Ee(o,r,i.pitchedLabelPlaneMatrix,i.getElevation),a.isOccluded=!1):(a=i.transform.projectTileCoordinates(o,r,i.unwrappedTileID,i.getElevation),a.point.x=(.5*a.point.x+.5)*i.width,a.point.y=(.5*-a.point.y+.5)*i.height),a}function je(e,i,o,r){if(o.pitchWithMap){const a=[e,i,0,1];return t.aw(a,a,r),o.transform.projectTileCoordinates(a[0]/a[3],a[1]/a[3],o.unwrappedTileID,o.getElevation).point}return {x:e/o.width*2-1,y:1-i/o.height*2}}function Ne(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function Ue(e,t,i){return e._unit()._perp()._mult(t*i)}function Ze(e,i,o,r,a,s,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=o.add(i);if(e+c.direction=a)return l.projectionCache.offsets[e]=h,h;const u=Be(e+c.direction,l,c),d=Ue(u.sub(o),n,c.direction),_=o.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.ax(s,h,_,p)||h,l.projectionCache.offsets[e]}function Ge(e,t,i,o,r,a,s,n,l){const c=o?e-t:e+t;let h=c>0?1:-1,u=0;o&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?a+r:a+r+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Oe(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,b=0;const x=Math.abs(c),y=[];let w;for(;v+b<=x;){if(_+=h,_=s)return null;v+=b,g=f,m=p;const e={absOffsetX:x,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=Be(_,n,e),0===i)y.push(g),w=f.sub(g);else {let t;const o=f.sub(g);t=0===o.mag()?Ue(Be(_+h,n,e).sub(f),i,h):Ue(o,i,h),m||(m=g.add(t)),p=Ze(_,t,f,a,s,m,i,n,e),y.push(m),w=p.sub(m);}b=w.mag();}const T=w._mult((x-v)/b)._add(m||g),P=u+Math.atan2(f.y-g.y,f.x-g.x);return y.push(T),{point:T,angle:l?P:0,path:y}}const Ve=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function $e(e,t){for(let i=0;i=1;e--)_.push(s.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=o.x&&i.x<=r.x&&e.y>=o.y&&i.y<=r.y?[_]:i.xr.x||i.yr.y?[]:t.ay([_],o.x,o.y,r.x,r.y);}for(const t of f){a.reset(t,.25*i);let o=0;o=a.length<=.5*i?1:Math.ceil(a.paddedLength/p)+1;for(let t=0;t{const t=Ee(e.x,e.y,o,i.getElevation),r=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return r.point.x=(.5*r.point.x+.5)*i.width,r.point.y=(.5*-r.point.y+.5)*i.height,r}))}(e,i);return function(e){let t=0,i=0,o=0,r=0;for(let a=0;ai&&(i=r,t=o));return e.slice(t,t+i)}(o)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[],o=new t.a2;for(const r of e){const e=new t.P(r.x+We,r.y+We);o.extend(e),i.push(e);}const{minX:r,minY:a,maxX:s,maxY:n}=o,l=this.grid.query(r,a,s,n).concat(this.ignoredGrid.query(r,a,s,n)),c={},h={};for(const e of l){const o=e.key;if(void 0===c[o.bucketInstanceId]&&(c[o.bucketInstanceId]={}),c[o.bucketInstanceId][o.featureIndex])continue;const r=[new t.P(e.x1,e.y1),new t.P(e.x2,e.y1),new t.P(e.x2,e.y2),new t.P(e.x1,e.y2)];t.az(i,r)&&(c[o.bucketInstanceId][o.featureIndex]=!0,void 0===h[o.bucketInstanceId]&&(h[o.bucketInstanceId]=[]),h[o.bucketInstanceId].push(o.featureIndex));}return h}insertCollisionBox(e,t,i,o,r,a){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,o,r,a){const s=i?this.ignoredGrid:this.grid,n={bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t};for(let t=0;t=this.screenRightBoundary||othis.screenBottomBoundary}isInsideGrid(e,t,i,o){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,r,c,u)));E=e.some((e=>!e.isOccluded)),S=e.map((e=>new t.P(e.x,e.y)));}else E=!0;return {box:t.aA(S),allPointsOccluded:!E}}}class Xe{constructor(e,t,i,o){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):o&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class Ke{constructor(e,t,i,o,r){this.text=new Xe(e?e.text:null,t,i,r),this.icon=new Xe(e?e.icon:null,t,o,r);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ye{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class Qe{constructor(e,t,i,o,r){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=r;}}class Je{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function et(e,i,o,r,a){const{horizontalAlign:s,verticalAlign:n}=t.aH(e);return new t.P(-(s-.5)*i+r[0]*a,-(n-.5)*o+r[1]*a)}class tt{constructor(e,t,i,o,r){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new He(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new Je(o),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=r,r&&(r.prevPlacement=void 0),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,o)=>t.getElevation(e,i,o):null}getBucketParts(e,i,o,r){const a=o.getBucket(i),s=o.latestFeatureIndex;if(!a||!s||i.id!==a.layerIds[0])return;const n=o.collisionBoxArray,l=a.layers[0].layout,c=a.layers[0].paint,h=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),u=o.tileSize/t.$,d=o.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.aC(o,1,this.transform.zoom),m=t.aD(this.collisionIndex.transform,o,c.get("text-translate"),c.get("text-translate-anchor")),f=t.aD(this.collisionIndex.transform,o,c.get("icon-translate"),c.get("icon-translate-anchor")),g=Ie(_,this.transform,p);this.retainedQueryData[a.bucketInstanceId]=new Qe(a.bucketInstanceId,s,a.sourceLayerIndex,a.index,o.tileID);const v={bucket:a,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:o.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.an(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(r)for(const t of a.sortKeyRanges){const{sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r}=t;e.push({sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v,b,x){const y=t.aE[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=et(y,o,r,w,a),P=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,s,f,u.predicate,b,T,x);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,s,g,u.predicate,b,T,x).placeable)&&P.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:o,height:r,anchor:y,textBoxScale:a,prevAnchor:e},this.markUsedJustification(p,y,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:P}}}placeLayerBucketPart(e,i,o){const{bucket:r,layout:a,translationText:s,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=a.get("text-optional"),f=a.get("icon-optional"),g=t.aF(a,"text-overlap","text-allow-overlap"),v="always"===g,b=t.aF(a,"icon-overlap","icon-allow-overlap"),x="always"===b,y="map"===a.get("text-rotation-alignment"),w="map"===a.get("text-pitch-alignment"),T="none"!==a.get("icon-text-fit"),P="viewport-y"===a.get("symbol-z-order"),C=v&&(x||!r.hasIconData()||f),I=x&&(v||!r.hasTextData()||m);!r.collisionArrays&&d&&r.deserializeCollisionBoxes(d);const M=this.retainedQueryData[r.bucketInstanceId].tileID,S=this._getTerrainElevationFunc(M),E=this.transform.getFastPathSimpleProjectionMatrix(M),R=(e,d,x)=>{var P,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new Ye(!1,!1,!1));let z=!1,D=!1,A=!0,L=null,k={box:null,placeable:!1,offscreen:null,occluded:!1},F={placeable:!1},B=null,O=null,j=null,N=0,U=0,Z=0;d.textFeatureIndex?N=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(N=e.featureIndex),d.verticalTextFeatureIndex&&(U=d.verticalTextFeatureIndex);const G=d.textBox;if(G){const i=i=>{let o=t.ao.horizontal;if(r.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,o=t,this.markUsedOrientation(r,o,e));}return o},a=(i,o)=>{if(r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of r.writingModes)if(e===t.ao.vertical?(k=o(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const o=(t,i)=>{const o=this.collisionIndex.placeCollisionBox(t,g,h,M,l,w,y,s,p.predicate,S,void 0,E);return o&&o.placeable&&(this.markUsedOrientation(r,i,e),this.placedOrientations[e.crossTileID]=i),o};a((()=>o(G,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?o(i,t.ao.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.aE[null===(R=null===(P=this.prevPlacement)||void 0===P?void 0:P.variableOffsets[e.crossTileID])||void 0===R?void 0:R.anchor];const m=(t,i,a)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===b?i:null;let x=null,P="never"===g?1:2,C="never";_&&P++;for(let i=0;im(G,d.iconBox,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.ao.vertical):{box:null,occluded:!0,offscreen:null}})),k&&(z=k.placeable,A=k.offscreen);const f=i(k&&k.placeable);if(!z&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(r,t.anchor,e,f));}}}if(B=k,z=B&&B.placeable,A=B&&B.offscreen,e.useRuntimeCollisionCircles){const i=r.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.ap(r.textSizeData,_,i),h=a.get("text-padding");O=this.collisionIndex.placeCollisionCircles(g,i,r.lineVertexArray,r.glyphOffsetArray,n,l,c,o,w,p.predicate,e.collisionCircleDiameter,h,s,S),O.circles.length&&O.collisionDetected&&!o&&t.w("Collisions detected, but collision boxes are not shown"),z=v||O.circles.length>0&&!O.collisionDetected,A=A&&O.offscreen;}if(d.iconFeatureIndex&&(Z=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,b,h,M,l,w,y,n,p.predicate,S,T&&L?L:void 0,E);F&&F.placeable&&d.verticalIconBox?(j=e(d.verticalIconBox),D=j.placeable):(j=e(d.iconBox),D=j.placeable),A=A&&j.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,$=f||0===e.numIconVertices;V||$?$?V||(D=D&&z):z=D&&z:D=z=D&&z;const q=D&&j.placeable;if(z&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,a.get("text-ignore-placement"),r.bucketInstanceId,F&&F.placeable&&U?U:N,p.ID),q&&this.collisionIndex.insertCollisionBox(j.box,b,a.get("icon-ignore-placement"),r.bucketInstanceId,Z,p.ID),O&&z&&this.collisionIndex.insertCollisionCircles(O.circles,g,a.get("text-ignore-placement"),r.bucketInstanceId,N,p.ID),o&&this.storeCollisionData(r.bucketInstanceId,x,d,B,j,O),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===r.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new Ye((z||C)&&!(null==B?void 0:B.occluded),(D||I)&&!(null==j?void 0:j.occluded),A||r.justReloaded),i[e.crossTileID]=!0;};if(P){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=r.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(r.symbolInstances.get(i),r.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=a>=0&&t!==a?0:o.crossTileID);}markUsedOrientation(e,i,o){const r=i===t.ao.horizontal||i===t.ao.horizontalOnly?i:0,a=i===t.ao.vertical?i:0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];for(const t of s)e.text.placedSymbolArray.get(t).placedOrientation=r;o.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).placedOrientation=a);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=!1;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const o=t?t.symbolFadeChange(e):1,r=t?t.opacities:{},a=t?t.variableOffsets:{},s=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],a=r[e];a?(this.opacities[e]=new Ke(a,o,t.text,t.icon),i=i||t.text!==a.text.placed||t.icon!==a.icon.placed):(this.opacities[e]=new Ke(null,o,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in r){const t=r[e];if(!this.opacities[e]){const r=new Ke(t,o,!1,!1);r.isHidden()||(this.opacities[e]=r,i=i||t.text.placed||t.icon.placed);}}for(const e in a)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=a[e]);for(const e in s)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=s[e]);if(t&&void 0===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const o of t){const t=o.getBucket(e);t&&o.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,o.tileID,i,o.collisionBoxArray);}}updateBucketOpacities(e,i,o,r){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=!1),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=!1),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const a=e.layers[0],s=a.layout,n=new Ke(null,0,!1,!1,!0),l=s.get("text-allow-overlap"),c=s.get("icon-allow-overlap"),h=a._unevaluatedLayout.hasValue("text-variable-anchor")||a._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===s.get("text-rotation-alignment"),d="map"===s.get("text-pitch-alignment"),_="none"!==s.get("icon-text-fit"),p=new Ke(null,0,l&&(c||!e.hasIconData()||s.get("icon-optional")),c&&(l||!e.hasTextData()||s.get("text-optional")),!0);!e.collisionArrays&&r&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(r);const m=(e,t,i)=>{for(let o=0;o0,v=this.placedOrientations[r.crossTileID],b=v===t.ao.vertical,x=v===t.ao.horizontal||v===t.ao.horizontalOnly;if(a>0||s>0){const t=ht(c.text);m(e.text,a,b?ut:t),m(e.text,s,x?ut:t);const i=c.text.isHidden();[r.rightJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||b?1:0);})),r.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).hidden=i||x?1:0);const o=this.variableOffsets[r.crossTileID];o&&this.markUsedJustification(e,o.anchor,r,v);const n=this.placedOrientations[r.crossTileID];n&&(this.markUsedJustification(e,"left",r,n),this.markUsedOrientation(e,n,r));}if(g){const t=ht(c.icon),i=!(_&&r.verticalPlacedIconSymbolIndex&&b);r.placedIconSymbolIndex>=0&&(m(e.icon,r.numIconVertices,i?t:ut),e.icon.placedSymbolArray.get(r.placedIconSymbolIndex).hidden=c.icon.isHidden()),r.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,r.numVerticalIconVertices,i?ut:t),e.icon.placedSymbolArray.get(r.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const y=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const o=e.collisionArrays[i];if(o){let i=new t.P(0,0);if(o.textBox||o.verticalTextBox){let t=!0;if(h){const e=this.variableOffsets[l];e?(i=et(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=!1;}if(o.textBox||o.verticalTextBox){let r;o.textBox&&(r=b),o.verticalTextBox&&(r=x),it(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||r,y.text,i.x,i.y);}}if(o.iconBox||o.verticalIconBox){const t=Boolean(!x&&o.verticalIconBox);let r;o.iconBox&&(r=t),o.verticalIconBox&&(r=!t),it(e.iconCollisionBox.collisionVertexArray,c.icon.placed,r,y.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=!0;}}function it(e,t,i,o,r,a){o&&0!==o.length||(o=[0,0,0,0]);const s=o[0]-We,n=o[1]-We,l=o[2]-We,c=o[3]-We;e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,c),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,c);}const ot=Math.pow(2,25),rt=Math.pow(2,24),at=Math.pow(2,17),st=Math.pow(2,16),nt=Math.pow(2,9),lt=Math.pow(2,8),ct=Math.pow(2,1);function ht(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*ot+t*rt+i*at+t*st+i*nt+t*lt+i*ct+t}const ut=0;class dt{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,o,r){const a=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&s.now()-o>2;for(;this._currentPlacementIndex>=0;){const o=t[e[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if("symbol"===o.type&&(!o.minzoom||o.minzoom<=a)&&(!o.maxzoom||o.maxzoom>a)){if(this._inProgressLayer||(this._inProgressLayer=new dt(o)),this._inProgressLayer.continuePlacement(i[o.source],this.placement,this._showCollisionBoxes,o,r))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(e){return this.placement.commit(e),this.placement}}const pt=512/t.$/2;class mt{constructor(e,i,o){this.tileID=e,this.bucketInstanceId=o,this._symbolsByKey={};const r=new Map;for(let e=0;e({x:Math.floor(e.anchorX*pt),y:Math.floor(e.anchorY*pt)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(o.positions.length>128){const e=new t.aI(o.positions.length,16,Uint16Array);for(const{x:t,y:i}of o.positions)e.add(t,i);e.finish(),delete o.positions,o.index=e;}this._symbolsByKey[e]=o;}}getScaledCoordinates(e,i){const{x:o,y:r,z:a}=this.tileID.canonical,{x:s,y:n,z:l}=i.canonical,c=pt/Math.pow(2,l-a),h=(n*t.$+e.anchorY)*c,u=r*t.$*pt;return {x:Math.floor((s*t.$+e.anchorX)*c-o*t.$*pt),y:Math.floor(h-u)}}findMatches(e,t,i){const o=this.tileID.canonical.ze))}}class ft{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class gt{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],o={};for(const e in i){const r=i[e];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+t),o[r.tileID.key]=r;}this.indexes[e]=o;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in r){const a=r[i];a.tileID.isChildOf(e)&&a.findMatches(t.symbolInstances,e,o);}else {const a=r[e.scaledTo(Number(i)).key];a&&a.findMatches(t.symbolInstances,e,o);}}for(let e=0;e{t[e]=!0;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var bt="void main() {fragColor=vec4(1.0);}";const xt={prelude:yt("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:yt("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:yt("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:yt("uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:yt("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:yt("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:yt(bt,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:yt("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:yt("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:yt("in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:yt("in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),colorRelief:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform int u_color_ramp_size;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {float x=(float(stop)+0.5)/float(u_color_ramp_size);vec4 data=texture(u_elevation_stops,vec2(x,0))*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int r=(u_color_ramp_size-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else\n{l=m;el_l=el_m;}}float x=(float(l)+(el-el_l)/(el_r-el_l)+0.5)/float(u_color_ramp_size);fragColor=u_opacity*texture(u_color_stops,vec2(x,0));\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_dimension;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),debug:yt("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}","in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:yt(bt,"in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:yt("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:yt("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:yt("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:yt("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:yt("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {vec2 epsilon=1.0/u_dimension;float tileSize=u_dimension.x-2.0;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))*tileSize/pow(2.0,exaggeration+(28.2562-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+0.5,deriv.y/8.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:yt("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];\n#define PI 3.141592653589793\n#define STANDARD 0\n#define COMBINED 1\n#define IGOR 2\n#define MULTIDIRECTIONAL 3\n#define BASIC 4\nfloat get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);}void igor_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float aspect=get_aspect(deriv);float azimuth=u_azimuths[0]+PI;float slope_stength=atan(length(deriv))*2.0/PI;float aspect_strength=1.0-abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);float shadow_strength=slope_stength*aspect_strength;float highlight_strength=slope_stength*(1.0-aspect_strength);fragColor=u_shadows[0]*shadow_strength+u_highlights[0]*highlight_strength;}void standard_hillshade(vec2 deriv){float azimuth=u_azimuths[0]+PI;float slope=atan(0.625*length(deriv));float aspect=get_aspect(deriv);float intensity=u_exaggeration;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadows[0],u_highlights[0],shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;}void basic_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor=u_highlights[0]*(2.0*shade-1.0);}else\n{fragColor=u_shadows[0]*(1.0-2.0*shade);}}void multidirectional_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;fragColor=vec4(0,0,0,0);for(int i=0; i < NUM_ILLUMINATION_SOURCES; i++){float cos_alt=cos(u_altitudes[i]);float sin_alt=sin(u_altitudes[i]);float cos_az=-cos(u_azimuths[i]);float sin_az=-sin(u_azimuths[i]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor+=u_highlights[i]*(2.0*shade-1.0)/float(NUM_ILLUMINATION_SOURCES);}else\n{fragColor+=u_shadows[i]*(1.0-2.0*shade)/float(NUM_ILLUMINATION_SOURCES);}}}void combined_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=acos((sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv)));cang=clamp(cang,0.0,PI/2.0);float shade=cang*atan(length(deriv))*4.0/PI/PI;float highlight=(PI/2.0-cang)*atan(length(deriv))*4.0/PI/PI;fragColor=u_shadows[0]*shade+u_highlights[0]*highlight;}void main() {vec4 pixel=texture(u_image,v_pos);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));vec2 deriv=((pixel.rg*8.0)-4.0)/scaleFactor;if (u_method==BASIC) {basic_hillshade(deriv);} else if (u_method==COMBINED) {combined_hillshade(deriv);} else if (u_method==IGOR) {igor_hillshade(deriv);} else if (u_method==MULTIDIRECTIONAL) {multidirectional_hillshade(deriv);} else if (u_method==STANDARD) {standard_hillshade(deriv);} else {standard_hillshade(deriv);}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:yt("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:yt("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0);vec4 color1=texture(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:yt("uniform sampler2D u_texture;in vec2 v_tex;in float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;fragColor=texture(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_tex;out float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:yt("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:yt("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;fragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:yt("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}","in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:yt("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}","in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:yt("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:yt("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:yt("in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}","in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:yt("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function yt(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o=t.match(/in ([\w]+) ([\w]+)/g),r=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=a?a.concat(r):r,n={};return {fragmentSource:e=e.replace(i,((e,t,i,o,r)=>(n[r]=!0,"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nin ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = u_${r};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,o,r)=>{const a="float"===o?"vec2":"vec4",s=r.match(/color/)?"color":a;return n[r]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\nout ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`})),staticAttributes:o,staticUniforms:s}}class wt{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var Tt=t.aJ([{name:"a_pos",type:"Int16",components:2}]);const Pt="#define PROJECTION_MERCATOR",Ct="mercator";class It{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return !1}get shaderVariantName(){return Ct}get shaderDefine(){return Pt}get shaderPreludeCode(){return xt.projectionMercator}get vertexShaderPreludeCode(){return xt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.aK.noSubdivision}get useGlobeControls(){return !1}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(e){}getMeshFromTileID(e,i,o,r,a){if(this._cachedMesh)return this._cachedMesh;const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(t.$,0),s.emplaceBack(0,t.$),s.emplaceBack(t.$,t.$);const n=e.createVertexBuffer(s,Tt.members),l=t.aM.simpleSegment(0,0,4,2),c=new t.aN;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new wt(n,h,l),this._cachedMesh}recalculate(){}hasTransition(){return !1}setErrorQueryLatitudeDegrees(e){}}class Mt{constructor(e=0,t=0,i=0,o=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=o;}interpolate(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.C.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.C.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.C.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.C.number(e.right,i.right,o)),this}getCenter(e,i){const o=t.ah((this.left+e-this.right)/2,0,e),r=t.ah((this.top+i-this.bottom)/2,0,i);return new t.P(o,r)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new Mt(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function St(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function Et(e){return Math.max(0,Math.floor(e))}class Rt{constructor(e,i,o,r,a,s){this._callbacks=e,this._tileSize=512,this._renderWorldCopies=void 0===s||!!s,this._minZoom=i||0,this._maxZoom=o||22,this._minPitch=null==r?0:r,this._maxPitch=null==a?60:a,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.S(0,0),this._elevation=0,this._zoom=0,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new Mt,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=!0;}apply(e,i,o){this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new Mt(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,this._cameraToCenterDistance=e.cameraToCenterDistance,this._nearZ=e.nearZ,this._farZ=e.farZ,this._autoCalculateNearFarZ=!o&&e.autoCalculateNearFarZ,i&&this._constrain(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e;}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const i=t.aO(e,-180,180)*Math.PI/180;var r,a,s,n,l,c,h,u,d;this._bearingInRadians!==i&&(this._unmodified=!1,this._bearingInRadians=i,this._calcMatrices(),this._rotationMatrix=o(),r=this._rotationMatrix,s=-this._bearingInRadians,n=(a=this._rotationMatrix)[0],l=a[1],c=a[2],h=a[3],u=Math.sin(s),d=Math.cos(s),r[0]=n*d+c*u,r[1]=l*d+h*u,r[2]=n*-u+c*d,r[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.ah(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=!1,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=!1,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.aP(this._fovInRadians)}setFov(e){e=t.ah(e,.1,150),this.fov!==e&&(this._unmodified=!1,this._fovInRadians=t.ae(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const i=this.getConstrained(this._center,e).zoom;this._zoom!==i&&(this._unmodified=!1,this._zoom=i,this._tileZoom=Math.max(0,Math.floor(i)),this._scale=t.af(i),this._constrain(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(e,t){this._autoCalculateNearFarZ=!1,this._nearZ=e,this._farZ=t,this._calcMatrices();}clearNearFarZOverride(){this._autoCalculateNearFarZ=!0,this._calcMatrices();}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices();}resize(e,t,i=!0){this._width=e,this._height=t,i&&this._constrain(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new G([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-t.ai,t.ai]);}getConstrained(e,t){return this._callbacks.getConstrained(e,t)}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{const{minX:o,minY:r,maxX:a,maxY:s}=t.a2.fromPoints(i).extend(e);return [new t.P(o,r),new t.P(a,r),new t.P(a,s),new t.P(o,s),new t.P(o,r)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const e=this._unmodified,{center:t,zoom:i}=this.getConstrained(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=!1;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.ag(new Float64Array(16));t.N(e,e,[this._width/2,-this._height/2,1]),t.M(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.ag(new Float64Array(16)),t.N(e,e,[1,-1,1]),t.M(e,e,[-1,-1,0]),t.N(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height;}this._callbacks.calcMatrices();}calculateCenterFromCameraLngLatAlt(e,i,o,r){const a=void 0!==o?o:this.bearing,s=r=void 0!==r?r:this.pitch,n=t.a1.fromLngLat(e,i),l=-Math.cos(t.ae(s)),c=Math.sin(t.ae(s)),h=c*Math.sin(t.ae(a)),u=-c*Math.cos(t.ae(a));let d=this.elevation;const _=i-d;let p;l*_>=0||Math.abs(l)<.1?(p=1e4,d=i+p*l):p=-_/l;let m,f,g=t.aQ(1,n.y),v=0;do{if(v+=1,v>10)break;f=p/g,m=new t.a1(n.x+h*f,n.y+u*f),g=1/m.meterInMercatorCoordinateUnits();}while(Math.abs(p-f*g)>1e-12);return {center:m.toLngLat(),elevation:d,zoom:t.ak(this.height/2/Math.tan(this.fovInRadians/2)/f/this.tileSize)}}recalculateZoomAndCenter(e){if(this.elevation-e==0)return;const i=t.aj(1,this.center.lat)*this.worldSize,o=this.cameraToCenterDistance/i,r=t.a1.fromLngLat(this.center,this.elevation),a=de(this.center,this.elevation,this.pitch,this.bearing,o);this._elevation=e;const s=this.calculateCenterFromCameraLngLatAlt(a.toLngLat(),t.aQ(a.z,r.y),this.bearing,this.pitch);this._elevation=s.elevation,this._center=s.center,this.setZoom(s.zoom);}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.P(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/e).toLngLat()}getMercatorTileCoordinates(e){if(!e)return [0,0,1,1];const i=e.canonical.z>=0?1<this.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[o]*this.min[o],i+=e[o]*this.max[o]):(i+=e[o]*this.min[o],t+=e[o]*this.max[o]);return t>=0?2:i<0?0:1}}class Dt{distanceToTile2d(e,t,i,o){const r=o.distanceX([e,t]),a=o.distanceY([e,t]);return Math.hypot(r,a)}getWrap(e,t,i){return i}getTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}const c=1<r}allowWorldCopies(){return !0}prepareNextFrame(){}}class At{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,o=0,r,a){const s=a?[[6,5,4],[0,1,2],[0,3,7],[2,1,5],[3,2,6],[0,4,5]]:[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]],n=Math.pow(2,o),l=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((o=>function(e,i,o,r){const a=t.aw([],e,i),s=1/a[3]/o*r;return t.aY(a,a,[s,s,1/a[3],s])}(o,e,i,n)));r&&function(e,i,o,r){const a=r?4:0,s=r?0:4;let n=0;const l=[],c=[];for(let i=0;i<4;i++){const o=t.aU([],e[i+s],e[i+a]),r=t.aZ(o);t.aR(o,o,1/r),l.push(r),c.push(o);}for(let i=0;i<4;i++){const r=t.a_(e[i+a],c[i],o);n=null!==r&&r>=0?Math.max(n,r):Math.max(n,l[i]);}const h=function(e,i){const o=t.aU([],e[i[0]],e[i[1]]),r=t.aU([],e[i[2]],e[i[1]]),a=[0,0,0,0];return t.aV(a,t.aW([],o,r)),a[3]=-t.aX(a,e[i[0]]),a}(e,i),u=function(e,i){const o=t.a$(e),r=t.b0([],e,1/o),a=t.aU([],i,t.aR([],r,t.aX(i,r))),s=t.a$(a);if(s>0){const e=Math.sqrt(1-r[3]*r[3]),o=t.aR([],r,-r[3]),n=t.aS([],o,t.aR([],a,e/s));return t.b1(i,n)}return null}(o,h);if(null!==u){const e=u/t.aX(c[0],h);n=Math.min(n,e);}for(let t=0;t<4;t++){const i=Math.min(n,l[t]);e[t+s]=[e[t+a][0]+c[t][0]*i,e[t+a][1]+c[t][1]*i,e[t+a][2]+c[t][2]*i,1];}}(l,s[0],r,a);const c=s.map((e=>{const i=t.aU([],l[e[0]],l[e[1]]),o=t.aU([],l[e[2]],l[e[1]]),r=t.aV([],t.aW([],i,o)),a=-t.aX(r,l[e[1]]);return r.concat(a)})),h=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of l)for(let t=0;t<3;t++)h[t]=Math.min(h[t],e[t]),u[t]=Math.max(u[t],e[t]);return new At(l,c,new zt(h,u))}}class Lt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e,t){}constructor(e,t,i,o,r){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)},e,t,i,o,r),this._coveringTilesDetailsProvider=new Dt;}clone(){const e=new Lt;return e.apply(this),e}apply(e,t,i){this._helper.apply(e,t,i);}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.b2(0,e)];if(this._helper._renderWorldCopies){const o=this.screenPointToMercatorCoordinate(new t.P(0,0)),r=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,0)),a=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,this._helper._height)),s=this.screenPointToMercatorCoordinate(new t.P(0,this._helper._height)),n=Math.floor(Math.min(o.x,r.x,a.x,s.x)),l=Math.floor(Math.max(o.x,r.x,a.x,s.x)),c=1;for(let o=n-c;o<=l+c;o++)0!==o&&i.push(new t.b2(o,e));}return i}getCameraFrustum(){return At.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const t=this.screenPointToLocation(this.centerPoint,e),i=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(i);}setLocationAtPoint(e,i){const o=t.aj(this.elevation,this.center.lat),r=this.screenPointToMercatorCoordinateAtZ(i,o),a=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,o),s=t.a1.fromLngLat(e),n=new t.a1(s.x-(r.x-a.x),s.y-(r.y-a.y));this.setCenter(null==n?void 0:n.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,i){return i?this.coordinatePoint(t.a1.fromLngLat(e),i.getElevationForLngLatZoom(e,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(t.a1.fromLngLat(e))}screenPointToLocation(e,t){var i;return null===(i=this.screenPointToMercatorCoordinate(e,t))||void 0===i?void 0:i.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const o=i||0,r=[e.x,e.y,0,1],a=[e.x,e.y,1,1];t.aw(r,r,this._pixelMatrixInverse),t.aw(a,a,this._pixelMatrixInverse);const s=r[3],n=a[3],l=r[1]/s,c=a[1]/n,h=r[2]/s,u=a[2]/n,d=h===u?0:(o-h)/(u-h);return new t.a1(t.C.number(r[0]/s,a[0]/n,d)/this.worldSize,t.C.number(l,c,d)/this.worldSize,o)}coordinatePoint(e,i=0,o=this._pixelMatrix){const r=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.aw(r,r,o),new t.P(r[0]/r[3],r[1]/r[3])}getBounds(){const e=Math.max(0,this._helper._height/2-he(this));return (new G).extend(this.screenPointToLocation(new t.P(0,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.P(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-he(this)}calculatePosMatrix(e,i=!1,o){var r;const a=null!==(r=e.key)&&void 0!==r?r:t.b3(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),s=i?this._alignedPosMatrixCache:this._posMatrixCache;if(s.has(a)){const e=s.get(a);return o?e.f32:e.f64}const n=ue(e,this.worldSize);t.O(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return s.set(a,l),o?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,o=this._fogMatrixCacheF32;if(o.has(i))return o.get(i);const r=ue(e,this.worldSize);return t.O(r,this._fogMatrix,r),o.set(i,new Float32Array(r)),o.get(i)}getConstrained(e,i){i=t.ah(+i,this.minZoom,this.maxZoom);const o={center:new t.S(e.lng,e.lat),zoom:i};let r=this._helper._lngRange;if(!this._helper._renderWorldCopies&&null===r){const e=180-1e-10;r=[-e,e];}const a=this.tileSize*t.af(o.zoom);let s=0,n=a,l=0,c=a,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;s=t.U(e[1])*a,n=t.U(e[0])*a,n-s<_&&(h=_/(n-s));}r&&(l=t.aO(t.V(r[0])*a,0,a),c=t.aO(t.V(r[1])*a,0,a),cn&&(g=n-e);}if(r){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.aO(p,e-a/2,e+a/2));const o=d/2;i-oc&&(f=c-o);}if(void 0!==f||void 0!==g){const e=new t.P(null!=f?f:p,null!=g?g:m);o.center=ce(a,e).wrap();}return o}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}_calculateNearFarZIfNeeded(e,i,o){if(!this._helper.autoCalculateNearFarZ)return;const r=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),a=e-r*this._helper._pixelPerMeter/Math.cos(i),s=r<0?a:e,n=Math.PI/2+this.pitchInRadians,l=t.ae(this.fov)*(Math.abs(Math.cos(t.ae(this.roll)))*this.height+Math.abs(Math.sin(t.ae(this.roll)))*this.width)/this.height*(.5+o.y/this.height),c=Math.sin(l)*s/Math.sin(t.ah(Math.PI-n-l,.01,Math.PI-.01)),h=he(this),u=Math.atan(h/this._helper.cameraToCenterDistance),d=t.ae(.75),_=u>d?2*u*(.5+o.y/(2*h)):d,p=Math.sin(_)*s/Math.sin(t.ah(Math.PI-n-_,.01,Math.PI-.01)),m=Math.min(c,p);this._helper._farZ=1.01*(Math.cos(Math.PI/2-i)*m+s),this._helper._nearZ=this._helper._height/50;}_calcMatrices(){if(!this._helper._height)return;const e=this.centerOffset,i=le(this.worldSize,this.center),o=i.x,r=i.y;this._helper._pixelPerMeter=t.aj(1,this.center.lat)*this.worldSize;const a=t.ae(Math.min(this.pitch,ne)),s=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(a));let n;this._calculateNearFarZIfNeeded(s,a,e),n=new Float64Array(16),t.b4(n,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),t.aq(this._invProjMatrix,n),n[8]=2*-e.x/this._helper._width,n[9]=2*e.y/this._helper._height,this._projectionMatrix=t.b5(n),t.N(n,n,[1,-1,1]),t.M(n,n,[0,0,-this._helper.cameraToCenterDistance]),t.b6(n,n,-this.rollInRadians),t.b7(n,n,this.pitchInRadians),t.b6(n,n,-this.bearingInRadians),t.M(n,n,[-o,-r,0]),this._mercatorMatrix=t.N([],n,[this.worldSize,this.worldSize,this.worldSize]),t.N(n,n,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n),t.M(n,n,[0,0,-this.elevation]),this._viewProjMatrix=n,this._invViewProjMatrix=t.aq([],n);const l=[0,0,-1,1];t.aw(l,l,this._invViewProjMatrix),this._cameraPosition=[l[0]/l[3],l[1]/l[3],l[2]/l[3]],this._fogMatrix=new Float64Array(16),t.b4(this._fogMatrix,this.fovInRadians,this.width/this.height,s,this._helper._farZ),this._fogMatrix[8]=2*-e.x/this.width,this._fogMatrix[9]=2*e.y/this.height,t.N(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.b6(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.b7(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.b6(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.M(this._fogMatrix,this._fogMatrix,[-o,-r,0]),t.N(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n);const c=this._helper._width%2/2,h=this._helper._height%2/2,u=Math.cos(this.bearingInRadians),d=Math.sin(-this.bearingInRadians),_=o-Math.round(o)+u*c+d*h,p=r-Math.round(r)+u*h+d*c,m=new Float64Array(n);if(t.M(m,m,[_>.5?_-1:_,p>.5?p-1:p,0]),this._alignedProjMatrix=m,n=t.aq(new Float64Array(16),this._pixelMatrix),!n)throw new Error("failed to invert matrix");this._pixelMatrixInverse=n,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.P(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.aw(i,i,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/e).toLngLat()}lngLatToCameraDepth(e,i){const o=t.a1.fromLngLat(e),r=[o.x*this.worldSize,o.y*this.worldSize,i,1];return t.aw(r,r,this._viewProjMatrix),r[2]/r[3]}getProjectionData(e){const{overscaledTileID:i,aligned:o,applyTerrainMatrix:r}=e,a=this._helper.getMercatorTileCoordinates(i),s=i?this.calculatePosMatrix(i,o,!0):null;let n;return n=i&&i.terrainRttPosMatrix32f&&r?i.terrainRttPosMatrix32f:s||t.b8(),{mainMatrix:n,tileMercatorCoords:a,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:n}}isLocationOccluded(e){return !1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,i){return 1}transformLightDirection(e){return t.aT(e)}getRayDirectionFromPixel(e){throw new Error("Not implemented.")}projectTileCoordinates(e,i,o,r){const a=this.calculatePosMatrix(o);let s;r?(s=[e,i,r(e,i),1],t.aw(s,s,a)):(s=[e,i,0,1],qe(s,s,a));const n=s[3];return {point:new t.P(s[0]/n,s[1]/n),signedDistanceFromCamera:n,isOccluded:!1}}populateCache(e){for(const t of e)this.calculatePosMatrix(t);}getMatrixForModel(e,i){const o=t.a1.fromLngLat(e,i),r=o.meterInMercatorCoordinateUnits(),a=t.b9();return t.M(a,a,[o.x,o.y,o.z]),t.b6(a,a,Math.PI),t.b7(a,a,Math.PI/2),t.N(a,a,[-r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=new t.Z(0,0,0,0,0),o=this.getProjectionData({overscaledTileID:i,applyGlobeMatrix:e}),r=ue(i,this.worldSize);t.O(r,this._viewProjMatrix,r),o.tileMercatorCoords=[0,0,1,1];const a=[t.$,t.$,this.worldSize/this._helper.pixelsPerMeter],s=t.ba();return t.N(s,r,a),o.fallbackMatrix=s,o.mainMatrix=s,o}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}}function kt(){t.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");}function Ft(e){if(e.useSlerp)if(e.k<1){const i=t.bb(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),o=t.bb(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),r=new Float64Array(4);t.bc(r,i,o,e.k);const a=t.bd(r);e.tr.setRoll(a.roll),e.tr.setPitch(a.pitch),e.tr.setBearing(a.bearing);}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(t.C.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(t.C.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(t.C.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k));}function Bt(e,i,o,r,a){const s=a.padding,n=le(a.worldSize,o.getNorthWest()),l=le(a.worldSize,o.getNorthEast()),c=le(a.worldSize,o.getSouthEast()),h=le(a.worldSize,o.getSouthWest()),u=t.ae(-r),d=n.rotate(u),_=l.rotate(u),p=c.rotate(u),m=h.rotate(u),f=new t.P(Math.max(d.x,_.x,m.x,p.x),Math.max(d.y,_.y,m.y,p.y)),g=new t.P(Math.min(d.x,_.x,m.x,p.x),Math.min(d.y,_.y,m.y,p.y)),v=f.sub(g),b=(a.width-(s.left+s.right+i.left+i.right))/v.x,x=(a.height-(s.top+s.bottom+i.top+i.bottom))/v.y;if(x<0||b<0)return void kt();const y=Math.min(t.ak(a.scale*Math.min(b,x)),e.maxZoom),w=t.P.convert(e.offset),T=new t.P((i.left-i.right)/2,(i.top-i.bottom)/2).rotate(t.ae(r)),P=w.add(T).mult(a.scale/t.af(y));return {center:ce(a.worldSize,n.add(c).div(2).sub(P)),zoom:y,bearing:r}}class Ot{get useGlobeControls(){return !1}handlePanInertia(e,t){const i=e.mag(),o=Math.abs(he(t));return {easingOffset:e.mult(Math.min(.75*o/i,1)),easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta);}handleMapControlsPan(e,t,i){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(i,e.around);}cameraForBoxAndBearing(e,t,i,o,r){return Bt(e,t,i,o,r)}handleJumpToCenterZoom(e,i){e.zoom!==(void 0!==i.zoom?+i.zoom:e.zoom)&&e.setZoom(+i.zoom),void 0!==i.center&&e.setCenter(t.S.convert(i.center));}handleEaseTo(e,i){const o=e.zoom,r=e.padding,a={roll:e.roll,pitch:e.pitch,bearing:e.bearing},s={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},n=void 0!==i.zoom,l=!e.isPaddingEqual(i.padding);let c=!1;const h=n?+i.zoom:e.zoom;let u=e.centerPoint.add(i.offsetAsPoint);const d=e.screenPointToLocation(u),{center:_,zoom:p}=e.getConstrained(t.S.convert(i.center||d),null!=h?h:o);St(e,_);const m=le(e.worldSize,d),f=le(e.worldSize,_).sub(m),g=t.af(p-o);return c=p!==o,{easeFunc:n=>{if(c&&e.setZoom(t.C.number(o,p,n)),t.be(a,s)||Ft({startEulerAngles:a,endEulerAngles:s,tr:e,k:n,useSlerp:a.roll!=s.roll}),l&&(e.interpolatePadding(r,i.padding,n),u=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const i=t.af(e.zoom-o),r=p>o?Math.min(2,g):Math.max(.5,g),a=Math.pow(r,1-n),s=ce(e.worldSize,m.add(f.mult(n*a)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?s.wrap():s,u);}},isZooming:c,elevationCenter:_}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.zoom,a=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),o?+i.zoom:r),s=a.center,n=a.zoom;St(e,s);const l=le(e.worldSize,i.locationAtOffset),c=le(e.worldSize,s).sub(l),h=c.mag(),u=t.af(n-r);let d;if(void 0!==i.minZoom){const o=Math.min(+i.minZoom,r,n),a=e.getConstrained(s,o).zoom;d=t.af(a-r);}return {easeFunc:(i,o,a,h)=>{e.setZoom(1===i?n:r+t.ak(o));const u=1===i?s:ce(e.worldSize,l.add(c.mult(a)).mult(o));e.setLocationAtPoint(e.renderWorldCopies?u.wrap():u,h);},scaleOfZoom:u,targetCenter:s,scaleOfMinZoom:d,pixelPathLength:h}}}class jt{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}jt.Replace=[1,0],jt.disabled=new jt(jt.Replace,t.bf.transparent,[!1,!1,!1,!1]),jt.unblended=new jt(jt.Replace,t.bf.transparent,[!0,!0,!0,!0]),jt.alphaBlended=new jt([1,771],t.bf.transparent,[!0,!0,!0,!0]);const Nt=2305;class Ut{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}Ut.disabled=new Ut(!1,1029,Nt),Ut.backCCW=new Ut(!0,1029,Nt),Ut.frontCCW=new Ut(!0,1028,Nt);class Zt{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Zt.ReadOnly=!1,Zt.ReadWrite=!0,Zt.disabled=new Zt(519,Zt.ReadOnly,[0,1]);const Gt=7680;class Vt{constructor(e,t,i,o,r,a){this.test=e,this.ref=t,this.mask=i,this.fail=o,this.depthFail=r,this.pass=a;}}Vt.disabled=new Vt({func:519,mask:0},0,0,Gt,Gt,Gt);const $t=new WeakMap;function qt(e){var t;if($t.has(e))return $t.get(e);{const i=null===(t=e.getParameter(e.VERSION))||void 0===t?void 0:t.startsWith("WebGL 2.0");return $t.set(e,i),i}}class Wt{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,o=i.gl;this._texFormat=o.RGBA,this._texType=o.UNSIGNED_BYTE;const r=new t.aL;r.emplaceBack(-1,-1),r.emplaceBack(2,-1),r.emplaceBack(-1,2);const a=new t.aN;a.emplaceBack(0,1,2),this._fullscreenTriangle=new wt(i.createVertexBuffer(r,Tt.members),i.createIndexBuffer(a),t.aM.simpleSegment(0,0,r.length,a.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(o.TEXTURE1);const s=o.createTexture();o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texImage2D(o.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(s),qt(o)&&(this._pbo=o.createBuffer(),o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.bufferData(o.PIXEL_PACK_BUFFER,4,o.STREAM_READ),o.bindBuffer(o.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const o=this._cachedRenderContext.context,r=o.gl;if(this._bindFramebuffer(),o.viewport.set([0,0,this._texWidth,this._texHeight]),o.clear({color:t.bf.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(o,r.TRIANGLES,Zt.disabled,Vt.disabled,jt.unblended,Ut.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&qt(r)){r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.readBuffer(r.COLOR_ATTACHMENT0),r.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),r.bindBuffer(r.PIXEL_PACK_BUFFER,null);const e=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);r.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&qt(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=Wt._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const Ht=t.$/128;function Xt(e,i){const o=void 0!==e.granularity?Math.max(e.granularity,1):1,r=o+(e.generateBorders?2:0),a=o+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),s=r+1,n=a+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=o+(e.generateBorders?1:0),u=o+(e.generateBorders||e.extendToSouthPole?1:0),d=s*n,_=r*a*6,p=s*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g=0;for(let i=c;i<=u;i++)for(let r=l;r<=h;r++){let a=r/o*t.$;-1===r&&(a=-Ht),r===o+1&&(a=t.$+Ht);let s=i/o*t.$;-1===i&&(s=e.extendToNorthPole?t.bh:-Ht),i===o+1&&(s=e.extendToSouthPole?t.bi:t.$+Ht),f[g++]=a,f[g++]=s;}const v=m?new Uint32Array(_):new Uint16Array(_);let b=0;for(let e=0;e0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return "globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy();}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e);}getMeshFromTileID(e,t,i,o,r){return this.currentProjection.getMeshFromTileID(e,t,i,o,r)}setProjection(e){this._transitionable.setValue("type",(null==e?void 0:e.type)||"mercator");}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e);}}function ei(e){const t=oi(e.worldSize,e.center.lat);return 2*Math.PI*t}function ti(e,i,o,r,a){const s=1/(1<1e-6){const r=e[0]/o,a=Math.acos(e[2]/o),s=(r>0?a:-a)/Math.PI*180;return new t.S(t.aO(s,-180,180),i)}return new t.S(0,i)}function ai(e){return Math.cos(e*Math.PI/180)}function si(e,i){const o=ai(e),r=ai(i);return t.ak(r/o)}function ni(e,i){const o=e.rotate(i.bearingInRadians),r=i.zoom+si(i.center.lat,0),a=t.bk(1/ai(i.center.lat),1/ai(Math.min(Math.abs(i.center.lat),60)),t.bn(r,7,3,0,1)),s=360/ei({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.S(i.center.lng-o.x*s*a,t.ah(i.center.lat+o.y*s,-t.ai,t.ai))}function li(e){const t=.5*e,i=Math.sin(t),o=Math.cos(t);return Math.log(i+o)-Math.log(o-i)}function ci(e,i,o,r){const a=e.lat+o*r;if(Math.abs(o)>1){const s=(Math.sign(e.lat+o)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+o)*Math.PI/180,l=li(s+r*(n-s)),c=li(s),h=li(n);return new t.S(e.lng+i*((l-c)/(h-c)),a)}return new t.S(e.lng+i*r,a)}class hi{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._boundingVolumeFactory=e;}swapBuffers(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1;}getTileBoundingVolume(e,t,i,o){const r=`${e.z}_${e.x}_${e.y}_${(null==o?void 0:o.terrain)?"t":""}`,a=this._cache.get(r);if(a)return a;const s=this._cachePrevious.get(r);if(s)return this._cache.set(r,s),s;const n=this._boundingVolumeFactory(e,t,i,o);return this._cache.set(r,n),this._hadAnyChanges=!0,n}}class ui{constructor(e,t,i,o){this.min=i,this.max=o,this.points=e,this.planes=t;}static fromAabb(e,t){const i=[];for(let o=0;o<8;o++)i.push([1&~o?e[0]:t[0],1==(o>>1&1)?t[1]:e[1],1==(o>>2&1)?t[2]:e[2]]);return new ui(i,[[-1,0,0,t[0]],[1,0,0,-e[0]],[0,-1,0,t[1]],[0,1,0,-e[1]],[0,0,-1,t[2]],[0,0,1,-e[2]]],e,t)}static fromCenterSizeAngles(e,i,o){const r=t.br([],o[0],o[1],o[2]),a=t.bs([],[i[0],0,0],r),s=t.bs([],[0,i[1],0],r),n=t.bs([],[0,0,i[2]],r),l=[...e],c=[...e];for(let t=0;t<8;t++)for(let i=0;i<3;i++){const o=e[i]+a[i]*(1&~t?-1:1)+s[i]*(1==(t>>1&1)?1:-1)+n[i]*(1==(t>>2&1)?1:-1);l[i]=Math.min(l[i],o),c[i]=Math.max(c[i],o);}const h=[];for(let i=0;i<8;i++){const o=[...e];t.aS(o,o,t.aR([],a,1&~i?-1:1)),t.aS(o,o,t.aR([],s,1==(i>>1&1)?1:-1)),t.aS(o,o,t.aR([],n,1==(i>>2&1)?1:-1)),h.push(o);}return new ui(h,[[...a,-t.aX(a,h[0])],[...s,-t.aX(s,h[0])],[...n,-t.aX(n,h[0])],[-a[0],-a[1],-a[2],-t.aX(a,h[7])],[-s[0],-s[1],-s[2],-t.aX(s,h[7])],[-n[0],-n[1],-n[2],-t.aX(n,h[7])]],l,c)}intersectsFrustum(e){let t=!0;const i=this.points.length,o=this.planes.length,r=e.planes.length,a=e.points.length;for(let o=0;o=0&&a++;}if(0===a)return 0;a=0&&o++;}if(0===o)return 0}return 1}intersectsPlane(e){const t=this.points.length;let i=0;for(let o=0;o=0&&i++;}return i===t?2:0===i?0:1}}function di(e,t,i){const o=e-t;return o<0?-o:Math.max(0,o-i)}function _i(e,t,i,o,r){const a=e-i;let s;return s=a<0?Math.min(-a,1+a-r):a>1?Math.min(Math.max(a-r,0),1-a):0,Math.max(s,di(t,o,r))}class pi{constructor(){this._boundingVolumeCache=new hi(this._computeTileBoundingVolume);}prepareNextFrame(){this._boundingVolumeCache.swapBuffers();}distanceToTile2d(e,t,i,o){const r=1<4}allowWorldCopies(){return !1}getTileBoundingVolume(e,t,i,o){return this._boundingVolumeCache.getTileBoundingVolume(e,t,i,o)}_computeTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}if(n/=t.bu,l/=t.bu,n+=1,l+=1,e.z<=0)return ui.fromAabb([-l,-l,-l],[l,l,l]);if(1===e.z)return ui.fromAabb([0===e.x?-l:0,0===e.y?0:-l,-l],[0===e.x?0:l,0===e.y?l:0,l]);{const i=[ti(0,0,e.x,e.y,e.z),ti(t.$,0,e.x,e.y,e.z),ti(t.$,t.$,e.x,e.y,e.z),ti(0,t.$,e.x,e.y,e.z)],o=[];for(const e of i)o.push(t.aR([],e,l));if(l!==n)for(const e of i)o.push(t.aR([],e,n));0===e.y&&o.push([0,1,0]),e.y===(1<=(1<{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._coveringTilesDetailsProvider=new pi;}clone(){const e=new fi;return e.apply(this),e}apply(e,t){this._globeLatitudeErrorCorrectionRadians=t||0,this._helper.apply(e);}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const e=t.bp();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(e){const{overscaledTileID:t,applyGlobeMatrix:i}=e,o=this._helper.getMercatorTileCoordinates(t);return {mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:o,clippingPlane:this._cachedClippingPlane,projectionTransition:i?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(e){const i=this.pitchInRadians,o=this.cameraToCenterDistance/e,r=Math.sin(i)*o,a=Math.cos(i)*o+1,s=1/Math.sqrt(r*r+a*a)*1;let n=-r,l=a;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];t.bw(h,h,[0,0,0],-this.bearingInRadians),t.bx(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.by(h,h,[0,0,0],this.center.lng*Math.PI/180);const u=1/t.aZ(h);return t.aR(h,h,u),[...h,-s*u]}isLocationOccluded(e){return !this.isSurfacePointVisible(ii(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,o=this._helper._center.lat*Math.PI/180,r=Math.cos(o),a=[Math.sin(i)*r,Math.sin(o),Math.cos(i)*r],s=[a[2],0,-a[0]],n=[0,0,0];t.aW(n,s,a),t.aV(s,s),t.aV(n,n);const l=[0,0,0];return t.aV(l,[s[0]*e[0]+n[0]*e[1]+a[0]*e[2],s[1]*e[0]+n[1]*e[1]+a[1]*e[2],s[2]*e[0]+n[2]*e[1]+a[2]*e[2]]),l}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(e,i,o){const r=function(e,i,o){const r=1/(1<a&&(a=i),on&&(n=o);}const h=[c.lng+s,c.lat+l,c.lng+a,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new G(h)}getConstrained(e,i){const o=t.ah(e.lat,-t.ai,t.ai),r=t.ah(+i,this.minZoom+si(0,o),this.maxZoom);return {center:new t.S(e.lng,o),zoom:r}}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,i){const o=ii(this.unprojectScreenPoint(i)),r=ii(e),a=t.bp();t.bB(a);const s=t.bp();t.by(s,o,a,-this.center.lng*Math.PI/180),t.bx(s,s,a,this.center.lat*Math.PI/180);const n=r[0]*r[0]+r[2]*r[2],l=s[0]*s[0];if(n=-g&&p<=g,b=f>=-g&&f<=g;let x,y;if(v&&b){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.bD(u,e)+t.bD(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return !1;const i=t.bv();return t.aw(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const o=t.aX(e,i),r=t.bp(),a=t.bp();t.aR(a,i,o),t.aU(r,e,a);const s=1-t.aX(r,r);if(s<0)return null;const n=t.aX(e,e)-1,l=-o+(o<0?1:-1)*Math.sqrt(s),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,o=this.getRayDirectionFromPixel(e),r=this.rayPlanetIntersection(i,o);if(r){const e=t.bp();t.aS(e,i,[o[0]*r.tMin,o[1]*r.tMin,o[2]*r.tMin]);const a=t.bp();return t.aV(a,e),ri(a)}const a=this._cachedClippingPlane,s=a[0]*o[0]+a[1]*o[1]+a[2]*o[2],n=-t.b1(a,i)/s,l=t.bp();if(n>0)t.aS(l,i,[o[0]*n,o[1]*n,o[2]*n]);else {const e=t.bp();t.aS(e,i,[2*o[0],2*o[1],2*o[2]]);const r=t.b1(this._cachedClippingPlane,e);t.aU(l,e,[this._cachedClippingPlane[0]*r,this._cachedClippingPlane[1]*r,this._cachedClippingPlane[2]*r]);}const c=function(e){const i=t.bp();return i[0]=e[0]*-e[3],i[1]=e[1]*-e[3],i[2]=e[2]*-e[3],{center:i,radius:Math.sqrt(1-e[3]*e[3])}}(a);return ri(function(e,i,o){const r=t.bp();t.aU(r,o,e);const a=t.bp();return t.bq(a,e,r,i/t.a$(r)),a}(c.center,c.radius,l))}getMatrixForModel(e,i){const o=t.S.convert(e),r=1/t.bu,a=t.b9();return t.bz(a,a,o.lng/180*Math.PI),t.b7(a,a,-o.lat/180*Math.PI),t.M(a,a,[0,0,1+i/t.bu]),t.b7(a,a,.5*Math.PI),t.N(a,a,[r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=this.getProjectionData({overscaledTileID:new t.Z(0,0,0,0,0),applyGlobeMatrix:e});return i.tileMercatorCoords=[0,0,1,1],i}getFastPathSimpleProjectionMatrix(e){}}class gi{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame(),this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame();}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._globeness=1,this._mercatorTransform=new Lt,this._verticalPerspectiveTransform=new fi;}clone(){const e=new gi;return e._globeness=this._globeness,e._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,e.apply(this),e}apply(e){this._helper.apply(e),this._mercatorTransform.apply(this),this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians);}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){const t=this._mercatorTransform.getProjectionData(e),i=this._verticalPerspectiveTransform.getProjectionData(e);return {mainMatrix:this.isGlobeRendering?i.mainMatrix:t.mainMatrix,clippingPlane:i.clippingPlane,tileMercatorCoords:i.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return t.bk(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return t.bk(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,i,o){const r=this._mercatorTransform.getPitchedTextCorrection(e,i,o),a=this._verticalPerspectiveTransform.getPitchedTextCorrection(e,i,o);return t.bk(r,a,this._globeness)}projectTileCoordinates(e,t,i,o){return this.currentTransform.projectTileCoordinates(e,t,i,o)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ);}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this._mercatorTransform.recalculateZoomAndCenter(e),this._verticalPerspectiveTransform.recalculateZoomAndCenter(e);}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e);}getBounds(){return this.currentTransform.getBounds()}getConstrained(e,t){return this.currentTransform.getConstrained(e,t)}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,t){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,t),void this.apply(this._mercatorTransform);this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform);}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getMatrixForModel(e,t){return this.currentTransform.getMatrixForModel(e,t)}getProjectionDataForCustomLayer(e=!0){const t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;const i=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return i.fallbackMatrix=t.mainMatrix,i}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}}class vi{get useGlobeControls(){return !0}handlePanInertia(e,i){const o=ni(e,i);return Math.abs(o.lng-i.center.lng)>180&&(o.lng=i.center.lng+179.5*Math.sign(o.lng-i.center.lng)),{easingCenter:o,easingOffset:new t.P(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){const o=e.around,r=i.screenPointToLocation(o);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const a=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const s=i.zoom-a;if(0===s)return;const n=t.bA(i.center.lng,r.lng),l=n/(Math.abs(n/180)+1),c=t.bA(i.center.lat,r.lat),h=i.getRayDirectionFromPixel(o),u=i.cameraPosition,d=-1*t.aX(u,h),_=t.bp();t.aS(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.aZ(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=oi(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.bn(f,.9,.5,1,.25),v=(1-t.af(-s))*Math.min(m,g),b=i.center.lat,x=i.zoom,y=new t.S(i.center.lng+l*v,t.ah(i.center.lat+c*v,-t.ai,t.ai));i.setLocationAtPoint(r,o);const w=i.center,T=t.bn(Math.abs(n),45,85,0,1),P=t.bn(f,.75,.35,0,1),C=Math.pow(Math.max(T,P),.25),I=t.bA(w.lng,y.lng),M=t.bA(w.lat,y.lat);i.setCenter(new t.S(w.lng+I*C,w.lat+M*C).wrap()),i.setZoom(x+si(b,i.center.lat));}handleMapControlsPan(e,t,i){if(!e.panDelta)return;const o=t.center.lat,r=t.zoom;t.setCenter(ni(e.panDelta,t).wrap()),t.setZoom(r+si(o,t.center.lat));}cameraForBoxAndBearing(e,i,o,r,a){const s=Bt(e,i,o,r,a),n=i.left/a.width*2-1,l=(a.width-i.right)/a.width*2-1,c=i.top/a.height*-2+1,h=(a.height-i.bottom)/a.height*-2+1,u=t.bA(o.getWest(),o.getEast())<0,d=u?o.getEast():o.getWest(),_=u?o.getWest():o.getEast(),p=Math.max(o.getNorth(),o.getSouth()),m=Math.min(o.getNorth(),o.getSouth()),f=d+.5*t.bA(d,_),g=p+.5*t.bA(p,m),v=a.clone();v.setCenter(s.center),v.setBearing(s.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(s.zoom);const b=v.modelViewProjectionMatrix,x=[ii(o.getNorthWest()),ii(o.getNorthEast()),ii(o.getSouthWest()),ii(o.getSouthEast()),ii(new t.S(_,g)),ii(new t.S(d,g)),ii(new t.S(f,p)),ii(new t.S(f,m))],y=ii(s.center);let w=Number.POSITIVE_INFINITY;for(const e of x)n<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",n))),l>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",l))),c>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",c))),h<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",h)));if(Number.isFinite(w)&&0!==w)return s.zoom=v.zoom+t.ak(w),s;kt();}handleJumpToCenterZoom(e,i){const o=e.center.lat,r=e.getConstrained(i.center?t.S.convert(i.center):e.center,e.zoom).center;e.setCenter(r.wrap());const a=void 0!==i.zoom?+i.zoom:e.zoom+si(o,r.lat);e.zoom!==a&&e.setZoom(a);}handleEaseTo(e,i){const o=e.zoom,r=e.center,a=e.padding,s={roll:e.roll,pitch:e.pitch,bearing:e.bearing},n={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},l=void 0!==i.zoom,c=!e.isPaddingEqual(i.padding);let h=!1;const u=i.center?t.S.convert(i.center):r,d=e.getConstrained(u,o).center;St(e,d);const _=e.clone();_.setCenter(d),_.setZoom(l?+i.zoom:o+si(r.lat,u.lat)),_.setBearing(i.bearing);const p=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));_.setLocationAtPoint(d,p);const m=(i.offset&&i.offsetAsPoint.mag())>0?_.center:d,f=l?+i.zoom:o+si(r.lat,m.lat),g=o+si(r.lat,0),v=f+si(m.lat,0),b=t.bA(r.lng,m.lng),x=t.bA(r.lat,m.lat),y=t.af(v-g);return h=f!==o,{easeFunc:o=>{if(t.be(s,n)||Ft({startEulerAngles:s,endEulerAngles:n,tr:e,k:o,useSlerp:s.roll!=n.roll}),c&&e.interpolatePadding(a,i.padding,o),i.around)t.w("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=v>g?Math.min(2,y):Math.max(.5,y),i=Math.pow(t,1-o),a=ci(r,b,x,o*i);e.setCenter(a.wrap());}if(h){const i=t.C.number(g,v,o)+si(0,e.center.lat);e.setZoom(i);}},isZooming:h,elevationCenter:m}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.center,a=e.zoom,s=e.padding,n=!e.isPaddingEqual(i.padding),l=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),a).center,c=o?+i.zoom:e.zoom+si(e.center.lat,l.lat),h=e.clone();h.setCenter(l),h.setZoom(c),h.setBearing(i.bearing);const u=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));h.setLocationAtPoint(l,u);const d=h.center;St(e,d);const _=function(e,i,o){const r=ii(i),a=ii(o),s=t.aX(r,a),n=Math.acos(s),l=ei(e);return n/(2*Math.PI)*l}(e,r,d),p=a+si(r.lat,0),m=c+si(d.lat,0),f=t.af(m-p);let g;if("number"==typeof i.minZoom){const o=+i.minZoom+si(d.lat,0),r=Math.min(o,p,m)+si(0,d.lat),a=e.getConstrained(d,r).zoom+si(d.lat,0);g=t.af(a-p);}const v=t.bA(r.lng,d.lng),b=t.bA(r.lat,d.lat);return {easeFunc:(o,a,l,h)=>{const u=ci(r,v,b,l);n&&e.interpolatePadding(s,i.padding,o);const _=1===o?d:u;e.setCenter(_.wrap());const m=p+t.ak(a);e.setZoom(1===o?c:m+si(0,_.lat));},scaleOfZoom:f,targetCenter:d,scaleOfMinZoom:g,pixelPathLength:_}}static solveVectorScale(e,t,i,o,r){const a="x"===o?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],s=[i[3],i[7],i[11],i[15]],n=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],l=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],c=t[0]*a[0]+t[1]*a[1]+t[2]*a[2],h=t[0]*s[0]+t[1]*s[1]+t[2]*s[2];return c+r*l===n+r*h||s[3]*(n-c)+a[3]*(h-l)+n*h==c*l?null:(c+a[3]-r*h-r*s[3])/(c-n-r*h+r*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.y(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),yi=t.bE();class wi extends t.E{constructor(e,i={}){var o,r;super(),this._rtlPluginLoaded=()=>{for(const e in this.sourceCaches){const t=this.sourceCaches[e].getSource().type;"vector"!==t&&"geojson"!==t||this.sourceCaches[e].reload();}},this.map=e,this.dispatcher=new F(k(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.imageManager=new b,this.imageManager.setEventedParent(this);const a=(null===(o=e._container)||void 0===o?void 0:o.lang)||"undefined"!=typeof document&&(null===(r=document.documentElement)||void 0===r?void 0:r.lang)||void 0;this.glyphManager=new T(e._requestManager,i.localIdeographFontFamily,a),this.lineAtlas=new E(256,512),this.crossTileSymbolIndex=new vt,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.bF,this._loaded=!1,this._availableImages=[],this._globalState={},this._resetUpdates(),this.dispatcher.broadcast("SR",t.bG()),oe().on(ee,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.sourceCaches[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}setGlobalStateProperty(e,i){var o,r,a;this._checkLoaded();const s=null===i?null!==(a=null===(r=null===(o=this.stylesheet.state)||void 0===o?void 0:o[e])||void 0===r?void 0:r.default)&&void 0!==a?a:null:i;if(t.bH(s,this._globalState[e]))return this;this._globalState[e]=s,this._applyGlobalStateChanges([e]);}getGlobalState(){return this._globalState}setGlobalState(e){this._checkLoaded();const i=[];for(const o in e)!t.bH(this._globalState[o],e[o].default)&&(i.push(o),this._globalState[o]=e[o].default);this._applyGlobalStateChanges(i);}_applyGlobalStateChanges(e){if(0===e.length)return;const t=new Set,i={};for(const o of e){i[o]=this._globalState[o];for(const e in this._layers){const i=this._layers[e],r=i.getLayoutAffectingGlobalStateRefs(),a=i.getPaintAffectingGlobalStateRefs();if(r.has(o)&&t.add(i.source),a.has(o))for(const{name:e,value:t}of a.get(o))this._updatePaintProperty(i,e,t);}}this.dispatcher.broadcast("UGS",i);for(const e in this.sourceCaches)t.has(e)&&(this._reloadSource(e),this._changed=!0);}loadURL(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const r=this.map._requestManager.transformRequest(e,"Style");this._loadStyleRequest=new AbortController;const a=this._loadStyleRequest;t.j(r,this._loadStyleRequest).then((e=>{this._loadStyleRequest=null,this._load(e.data,i,o);})).catch((e=>{this._loadStyleRequest=null,e&&!a.signal.aborted&&this.fire(new t.k(e));}));}loadJSON(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,s.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=!1!==i.validate,this._load(e,i,o);})).catch((()=>{}));}loadEmpty(){this.fire(new t.l("dataloading",{dataType:"style"})),this._load(yi,{validate:!1});}_load(e,i,o){var r,a;let s=i.transformStyle?i.transformStyle(o,e):e;if(!i.validate||!xi(this,t.z(s))){s=Object.assign({},s),this._loaded=!0,this.stylesheet=s;for(const e in s.sources)this.addSource(e,s.sources[e],{validate:!1});s.sprite?this._loadSprite(s.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(s.glyphs),this._createLayers(),this.light=new I(this.stylesheet.light),this._setProjectionInternal((null===(r=this.stylesheet.projection)||void 0===r?void 0:r.type)||"mercator"),this.sky=new S(this.stylesheet.sky),this.map.setTerrain(null!==(a=this.stylesheet.terrain)&&void 0!==a?a:null),this.fire(new t.l("data",{dataType:"style"})),this.fire(new t.l("style.load"));}}_createLayers(){var e;const i=t.bI(this.stylesheet.layers);this.setGlobalState(null!==(e=this.stylesheet.state)&&void 0!==e?e:null),this.dispatcher.broadcast("SL",i),this._order=i.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const e of i){const i=t.bJ(e,this._globalState);i.setEventedParent(this,{layer:{id:e.id}}),this._layers[e.id]=i;}}_loadSprite(e,i=!1,o=void 0){let r;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=f(e),n=o>1?"@2x":"",l={},c={};for(const{id:e,url:o}of a){const a=i.transformRequest(g(o,n,".json"),"SpriteJSON");l[e]=t.j(a,r);const s=i.transformRequest(g(o,n,".png"),"SpriteImage");c[e]=p.getImage(s,r);}return yield Promise.all([...Object.values(l),...Object.values(c)]),function(e,i){return t._(this,void 0,void 0,(function*(){const t={};for(const o in e){t[o]={};const r=s.getImageCanvasContext((yield i[o]).data),a=(yield e[o]).data;for(const e in a){const{width:i,height:s,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=a[e];t[o][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:s,x:n,y:l,context:r}};}}return t}))}(l,c)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const o=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of o)this.imageManager.removeImage(e),this._changedImages[e]=!0;for(const o in e[t]){const r="default"===t?o:`${t}:${o}`;this._spritesImagesIds[t].push(r),r in this.imageManager.images?this.imageManager.updateImage(r,e[t][o],!1):this.imageManager.addImage(r,e[t][o]),i&&(this._changedImages[r]=!0);}}})).catch((e=>{this._spriteRequest=null,r=e,this.fire(new t.k(r));})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),i&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"})),o&&o(r);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}_validateLayer(e){const i=this.sourceCaches[e.source];if(!i)return;const o=e.sourceLayer;if(!o)return;const r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.k(new Error(`Source layer "${o}" does not exist on source "${r.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(const e in this.sourceCaches)if(!this.sourceCaches[e].loaded())return !1;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=!1){const o=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.bK(o):o);const r=[];for(const a of e)if(o[a]){const e=i?t.bK(o[a]):o[a];r.push(e);}return r}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){var e,t,i;if(null===(e=this.light)||void 0===e?void 0:e.hasTransition())return !0;if(null===(t=this.sky)||void 0===t?void 0:t.hasTransition())return !0;if(null===(i=this.projection)||void 0===i?void 0:i.hasTransition())return !0;for(const e in this.sourceCaches)if(this.sourceCaches[e].hasTransition())return !0;for(const e in this._layers)if(this._layers[e].hasTransition())return !0;return !1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const o={};for(const e in this.sourceCaches){const t=this.sourceCaches[e];o[e]=t.used,t.used=!1;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.sourceCaches[i.source].used=!0);}for(const e in o){const i=this.sourceCaches[e];!!o[e]!=!!i.used&&i.fire(new t.l("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.projection.recalculate(e),this.z=e.zoom,i&&this.fire(new t.l("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,!1),removedIds:t});}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1;}setState(e,i={}){var o;this._checkLoaded();const r=this.serialize();if(e=i.transformStyle?i.transformStyle(r,e):e,(null===(o=i.validate)||void 0===o||o)&&xi(this,t.z(e)))return !1;(e=t.bK(e)).layers=t.bI(e.layers);const a=t.bL(r,e),s=this._getOperationsToPerform(a);if(s.unimplemented.length>0)throw new Error(`Unimplemented: ${s.unimplemented.join(", ")}.`);if(0===s.operations.length)return !1;for(const e of s.operations)e();return this.stylesheet=e,this._serializedLayers=null,!0}_getOperationsToPerform(e){const t=[],i=[];for(const o of e)switch(o.command){case "setCenter":case "setZoom":case "setBearing":case "setPitch":case "setRoll":continue;case "addLayer":t.push((()=>this.addLayer.apply(this,o.args)));break;case "removeLayer":t.push((()=>this.removeLayer.apply(this,o.args)));break;case "setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,o.args)));break;case "setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,o.args)));break;case "setFilter":t.push((()=>this.setFilter.apply(this,o.args)));break;case "addSource":t.push((()=>this.addSource.apply(this,o.args)));break;case "removeSource":t.push((()=>this.removeSource.apply(this,o.args)));break;case "setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,o.args)));break;case "setLight":t.push((()=>this.setLight.apply(this,o.args)));break;case "setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,o.args)));break;case "setGlyphs":t.push((()=>this.setGlyphs.apply(this,o.args)));break;case "setSprite":t.push((()=>this.setSprite.apply(this,o.args)));break;case "setTerrain":t.push((()=>this.map.setTerrain.apply(this,o.args)));break;case "setSky":t.push((()=>this.setSky.apply(this,o.args)));break;case "setProjection":this.setProjection.apply(this,o.args);break;case "setGlobalState":t.push((()=>this.setGlobalState.apply(this,o.args)));break;case "setTransition":t.push((()=>{}));break;default:i.push(o.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,o={}){if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.z.source,`sources.${e}`,i,null,o))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const r=this.sourceCaches[e]=new xe(e,i,this.dispatcher);r.style=this,r.setEventedParent(this,(()=>({isSourceLoaded:r.loaded(),source:r.serialize(),sourceId:e}))),r.onAdd(this.map),this._changed=!0;}removeSource(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.k(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],i.fire(new t.l("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=!0;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error(`There is no source with this ID=${e}`);const i=this.sourceCaches[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=!0;}getSource(e){return this.sourceCaches[e]&&this.sourceCaches[e].getSource()}addLayer(e,i,o={}){this._checkLoaded();const r=e.id;if(this.getLayer(r))return void this.fire(new t.k(new Error(`Layer "${r}" already exists on this map.`)));let a;if("custom"===e.type){if(xi(this,t.bM(e)))return;a=t.bJ(e,this._globalState);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(r,e.source),e=t.bK(e),e=t.e(e,{source:r})),this._validate(t.z.layer,`layers.${r}`,e,{arrayIndex:-1},o))return;a=t.bJ(e,this._globalState),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}});}const s=i?this._order.indexOf(i):this._order.length;if(i&&-1===s)this.fire(new t.k(new Error(`Cannot add layer "${r}" before non-existing layer "${i}".`)));else {if(this._order.splice(s,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){const e=this._removedLayers[r];delete this._removedLayers[r],e.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=!0,!this._layers[e])return void this.fire(new t.k(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const o=this._order.indexOf(e);this._order.splice(o,1);const r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.k(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.k(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,o){this._checkLoaded();const r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.k(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,o={}){this._checkLoaded();const r=this.getLayer(e);if(r){if(!t.bH(r.filter,i))return null==i?(r.setFilter(void 0),void this._updateLayer(r)):void(this._validate(t.z.filter,`layers.${r.id}.filter`,i,null,o)||(r.setFilter(t.bK(i)),this._updateLayer(r)))}else this.fire(new t.k(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.bK(this.getLayer(e).filter)}setLayoutProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.k(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getPaintProperty(i),o)||this._updatePaintProperty(a,i,o,r):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}_updatePaintProperty(e,t,i,o={}){e.setPaintProperty(t,i,o)&&this._updateLayer(e),this._changed=!0,this._updatedPaintProps[e.id]=!0,this._serializedLayers=null;}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0===a)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const s=a.getSource().type;"geojson"===s&&r?this.fire(new t.k(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==s||r?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const o=e.source,r=this.sourceCaches[o];if(void 0===r)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const a=r.getSource().type,s="vector"===a?e.sourceLayer:void 0;"vector"!==a||s?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.k(new Error("A feature id is required to remove its specific state property."))):r.removeFeatureState(s,e.id,i):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r)return "vector"!==r.getSource().type||o?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id)):void this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.k(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.bN(this.sourceCaches,(e=>e.serialize())),i=this._serializeByIds(this._order,!0),o=this.map.getTerrain()||void 0,r=this.stylesheet;return t.bO({version:r.version,name:r.name,metadata:r.metadata,light:r.light,sky:r.sky,center:r.center,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,sprite:r.sprite,glyphs:r.glyphs,transition:r.transition,projection:r.projection,sources:e,layers:i,terrain:o},(e=>void 0!==e))}_updateLayer(e){this._updatedLayers[e.id]=!0,e.source&&!this._updatedSources[e.source]&&"raster"!==this.sourceCaches[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.sourceCaches[e.source].pause()),this._serializedLayers=null,this._changed=!0;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},o=[];for(let r=this._order.length-1;r>=0;r--){const a=this._order[r];if(t(a)){i[a]=r;for(const t of e){const e=t[a];if(e)for(const t of e)o.push(t);}}}o.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const r=[];for(let a=this._order.length-1;a>=0;a--){const s=this._order[a];if(t(s))for(let e=o.length-1;e>=0;e--){const t=o[e].feature;if(i[t.layer.id]this.map.terrain.getElevation(e,t,i):void 0));return this.placement&&a.push(function(e,t,i,o,r,a,s){const n={},l=a.queryRenderedSymbols(o),c=[];for(const e of Object.keys(l).map(Number))c.push(s[e]);c.sort(N);for(const i of c){const o=i.featureIndex.lookupSymbolFeatures(l[i.bucketInstanceId],t,i.bucketIndex,i.sourceLayerIndex,{filterSpec:r.filter,globalState:r.globalState},r.layers,r.availableImages,e);for(const e in o){const t=n[e]=n[e]||[],r=o[e];r.sort(((e,t)=>{const o=i.featureSortOrder;if(o){const i=o.indexOf(e.featureIndex);return o.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of r)t.push(e);}}return function(e,t,i){for(const o in e)for(const r of e[o])U(r,i[t[o].source]);return e}(n,e,i)}(this._layers,s,this.sourceCaches,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(a)}querySourceFeatures(e,i){(null==i?void 0:i.filter)&&this._validate(t.z.filter,"querySourceFeatures.filter",i.filter,null,i);const o=this.sourceCaches[e];return o?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),o=[],r={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const o=this.crossTileSymbolIndex.addLayer(i,l[i.source],e.center.lng);a=a||o;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((r=r||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(s.now(),e.zoom))&&(this.pauseablePlacement=new _t(e,this.map.terrain,this._order,r,t,i,o,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(s.now()),n=!0),a&&this.pauseablePlacement.placement.setStale()),n||a)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,l[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(s.now())}_releaseSymbolFadeTiles(){for(const e in this.sourceCaches)this.sourceCaches[e].releaseSymbolFadeTiles();}getImages(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.z.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}addSprite(e,i,o={},r){this._checkLoaded();const a=[{id:e,url:i}],s=[...f(this.stylesheet.sprite),...a];this._validate(t.z.sprite,"sprite",s,null,o)||(this.stylesheet.sprite=s,this._loadSprite(a,!0,r));}removeSprite(e){this._checkLoaded();const i=f(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=!0;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:void 0,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}else this.fire(new t.k(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return f(this.stylesheet.sprite)}setSprite(e,i={},o){this._checkLoaded(),e&&this._validate(t.z.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,!0,o):(this._unloadSprite(),o&&o(null)));}}var Ti=t.aJ([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class Pi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;}bind(e,t,i,o,r,a,s,n,l){this.context=e;let c=this.boundPaintVertexBuffers.length!==o.length;for(let e=0;!c&&e({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:o?o.properties.get("fog-color"):t.bf.white,u_fog_ground_blend:o?o.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:a?0:o?o.calculateFogBlendOpacity(r):0,u_horizon_color:o?o.properties.get("horizon-color"):t.bf.white,u_horizon_fog_blend:o?o.properties.get("horizon-fog-blend"):1,u_is_globe_mode:a?1:0}),Ii={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function Mi(e){const t=[];for(let i=0;i({u_depth:new t.bP(e,i.u_depth),u_terrain:new t.bP(e,i.u_terrain),u_terrain_dim:new t.bg(e,i.u_terrain_dim),u_terrain_matrix:new t.bR(e,i.u_terrain_matrix),u_terrain_unpack:new t.bS(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.bg(e,i.u_terrain_exaggeration)}))(e,C),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.bR(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.bS(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.bS(e,i.u_projection_clipping_plane),u_projection_transition:new t.bg(e,i.u_projection_transition),u_projection_fallback_matrix:new t.bR(e,i.u_projection_fallback_matrix)}))(e,C),this.binderUniforms=o?o.getUniforms(e,C):[];}draw(e,t,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v){const b=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(o),e.setColorMode(r),e.setCullFace(a),n){e.activeTexture.set(b.TEXTURE2),b.bindTexture(b.TEXTURE_2D,n.depthTexture),e.activeTexture.set(b.TEXTURE3),b.bindTexture(b.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[Ii[e]].set(l[e]);if(s)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(s[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let x=0;switch(t){case b.LINES:x=2;break;case b.TRIANGLES:x=3;break;case b.LINE_STRIP:x=1;}for(const i of d.get()){const o=i.vaos||(i.vaos={});(o[c]||(o[c]=new Pi)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),b.drawElements(t,i.primitiveLength*x,b.UNSIGNED_SHORT,i.primitiveOffset*x*2);}}}function Ei(e,i,o){const r=1/t.aC(o,1,i.transform.tileZoom),a=Math.pow(2,o.tileID.overscaledZ),s=o.tileSize*Math.pow(2,i.transform.tileZoom)/a,n=s*(o.tileID.canonical.x+o.tileID.wrap*a),l=s*o.tileID.canonical.y;return {u_image:0,u_texsize:o.imageAtlasTexture.size,u_scale:[r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Ri=(e,i,o,r)=>{const a=e.style.light,s=a.properties.get("position"),n=[s.x,s.y,s.z],l=t.bV();"viewport"===a.properties.get("anchor")&&t.bW(l,e.transform.bearingInRadians),t.bX(n,n,l);const c=e.transform.transformLightDirection(n),h=a.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:o,u_fill_translate:r}},zi=(e,i,o,r,a,s,n)=>t.e(Ri(e,i,o,r),Ei(s,e,n),{u_height_factor:-Math.pow(2,a.overscaledZ)/n.tileSize/8}),Di=(e,i,o,r)=>t.e(Ei(i,e,o),{u_fill_translate:r}),Ai=(e,t)=>({u_world:e,u_fill_translate:t}),Li=(e,i,o,r,a)=>t.e(Di(e,i,o,a),{u_world:r}),ki=(e,i,o,r,a)=>{const s=e.transform;let n,l,c=0;if("map"===o.paint.get("circle-pitch-alignment")){const e=t.aC(i,1,s.zoom);n=!0,l=[e,e],c=e/(t.$*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*a;}else n=!1,l=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===o.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:r}},Fi=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),Bi=e=>({u_viewport_size:[e.width,e.height]}),Oi=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),ji=(e,i,o,r)=>{const a=t.aC(e,1,i)/(t.$*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*r;return {u_extrude_scale:t.aC(e,1,i),u_intensity:o,u_globe_extrude_scale:a}},Ni=(e,i,o,r)=>{const a=t.L();t.bY(a,0,e.width,e.height,0,0,1);const s=e.context.gl;return {u_matrix:a,u_world:[s.drawingBufferWidth,s.drawingBufferHeight],u_image:o,u_color_ramp:r,u_opacity:i.paint.get("heatmap-opacity")}},Ui=(e,t,i)=>{const o=i.paint.get("hillshade-accent-color");let r;switch(i.paint.get("hillshade-method")){case "basic":r=4;break;case "combined":r=1;break;case "igor":r=2;break;case "multidirectional":r=3;break;default:r=0;}const a=i.getIlluminationProperties();for(let t=0;t{const o=i.stride,r=t.L();return t.bY(r,0,t.$,-t.$,0,0,1),t.M(r,r,[0,-t.$,0]),{u_matrix:r,u_image:1,u_dimension:[o,o],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function Gi(e,i){const o=Math.pow(2,i.canonical.z),r=i.canonical.y;return [new t.a1(0,r/o).toLngLat().lat,new t.a1(0,(r+1)/o).toLngLat().lat]}const Vi=(e,t,i=0)=>({u_image:0,u_unpack:t.getUnpackVector(),u_dimension:[t.stride,t.stride],u_elevation_stops:1,u_color_stops:4,u_color_ramp_size:i,u_opacity:e.paint.get("color-relief-opacity")}),$i=(e,i,o,r)=>{const a=e.transform;return {u_translation:Ki(e,i,o),u_ratio:r/t.aC(i,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},qi=(e,i,o,r,a)=>t.e($i(e,i,o,r),{u_image:0,u_image_height:a}),Wi=(e,i,o,r,a)=>{const s=e.transform,n=Xi(i,s);return {u_translation:Ki(e,i,o),u_texsize:i.imageAtlasTexture.size,u_ratio:r/t.aC(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},Hi=(e,i,o,r,a,s)=>{const n=e.lineAtlas,l=Xi(i,e.transform),c="round"===o.layout.get("line-cap"),h=n.getDash(a.from,c),u=n.getDash(a.to,c),d=h.width*s.fromScale,_=u.width*s.toScale;return t.e($i(e,i,o,r),{u_patternscale_a:[l/d,-h.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*e.pixelRatio)/2,u_image:0,u_tex_y_a:h.y,u_tex_y_b:u.y,u_mix:s.t})};function Xi(e,i){return 1/t.aC(e,1,i.tileZoom)}function Ki(e,i,o){return t.aD(e.transform,i,o.paint.get("line-translate"),o.paint.get("line-translate-anchor"))}const Yi=(e,t,i,o,r)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*o.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:o.paint.get("raster-brightness-min"),u_brightness_high:o.paint.get("raster-brightness-max"),u_saturation_factor:(s=o.paint.get("raster-saturation"),s>0?1-1/(1.001-s):-s),u_contrast_factor:(a=o.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Qi(o.paint.get("raster-hue-rotate")),u_coords_top:[r[0].x,r[0].y,r[1].x,r[1].y],u_coords_bottom:[r[3].x,r[3].y,r[2].x,r[2].y]};var a,s;};function Qi(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const Ji=(e,t,i,o,r,a,s,n,l,c,h,u,d)=>{const _=s.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+o,u_is_along_line:r,u_is_variable_anchor:a,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},eo=(e,i,o,r,a,s,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.e(Ji(e,i,o,r,a,s,n,l,c,h,u,d,p),{u_gamma_scale:r?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:1})},to=(e,i,o,r,a,s,n,l,c,h,u,d,_)=>t.e(eo(e,i,o,r,a,s,n,l,c,h,!0,u,0,_),{u_texsize_icon:d,u_texture_icon:1}),io=(e,t)=>({u_opacity:e,u_color:t}),oo=(e,i,o,r,a)=>t.e(function(e,i,o,r){const a=o.imageManager.getPattern(e.from.toString()),s=o.imageManager.getPattern(e.to.toString()),{width:n,height:l}=o.imageManager.getPixelSize(),c=Math.pow(2,r.tileID.overscaledZ),h=r.tileSize*Math.pow(2,o.transform.tileZoom)/c,u=h*(r.tileID.canonical.x+r.tileID.wrap*c),d=h*r.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:s.tl,u_pattern_br_b:s.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:s.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.aC(r,1,o.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(o,a,i,r),{u_opacity:e}),ro=(e,t)=>{},ao={fillExtrusion:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_height_factor:new t.bg(e,i.u_height_factor),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.bU(e,i.u_world),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_scale_with_map:new t.bP(e,i.u_scale_with_map),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_extrude_scale:new t.bU(e,i.u_extrude_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale),u_translate:new t.bU(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.bU(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.bU(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.bQ(e,i.u_color),u_overlay:new t.bP(e,i.u_overlay),u_overlay_scale:new t.bg(e,i.u_overlay_scale)}),depth:ro,clippingMask:ro,heatmap:(e,i)=>({u_extrude_scale:new t.bg(e,i.u_extrude_scale),u_intensity:new t.bg(e,i.u_intensity),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_color_ramp:new t.bP(e,i.u_color_ramp),u_opacity:new t.bg(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.bP(e,i.u_image),u_latrange:new t.bU(e,i.u_latrange),u_exaggeration:new t.bg(e,i.u_exaggeration),u_altitudes:new t.b_(e,i.u_altitudes),u_azimuths:new t.b_(e,i.u_azimuths),u_accent:new t.bQ(e,i.u_accent),u_method:new t.bP(e,i.u_method),u_shadows:new t.bZ(e,i.u_shadows),u_highlights:new t.bZ(e,i.u_highlights)}),hillshadePrepare:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_image:new t.bP(e,i.u_image),u_dimension:new t.bU(e,i.u_dimension),u_zoom:new t.bg(e,i.u_zoom),u_unpack:new t.bS(e,i.u_unpack)}),colorRelief:(e,i)=>({u_image:new t.bP(e,i.u_image),u_unpack:new t.bS(e,i.u_unpack),u_dimension:new t.bU(e,i.u_dimension),u_elevation_stops:new t.bP(e,i.u_elevation_stops),u_color_stops:new t.bP(e,i.u_color_stops),u_color_ramp_size:new t.bP(e,i.u_color_ramp_size),u_opacity:new t.bg(e,i.u_opacity)}),line:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_image:new t.bP(e,i.u_image),u_image_height:new t.bg(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_texsize:new t.bU(e,i.u_texsize),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_image:new t.bP(e,i.u_image),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_patternscale_a:new t.bU(e,i.u_patternscale_a),u_patternscale_b:new t.bU(e,i.u_patternscale_b),u_sdfgamma:new t.bg(e,i.u_sdfgamma),u_image:new t.bP(e,i.u_image),u_tex_y_a:new t.bg(e,i.u_tex_y_a),u_tex_y_b:new t.bg(e,i.u_tex_y_b),u_mix:new t.bg(e,i.u_mix)}),raster:(e,i)=>({u_tl_parent:new t.bU(e,i.u_tl_parent),u_scale_parent:new t.bg(e,i.u_scale_parent),u_buffer_scale:new t.bg(e,i.u_buffer_scale),u_fade_t:new t.bg(e,i.u_fade_t),u_opacity:new t.bg(e,i.u_opacity),u_image0:new t.bP(e,i.u_image0),u_image1:new t.bP(e,i.u_image1),u_brightness_low:new t.bg(e,i.u_brightness_low),u_brightness_high:new t.bg(e,i.u_brightness_high),u_saturation_factor:new t.bg(e,i.u_saturation_factor),u_contrast_factor:new t.bg(e,i.u_contrast_factor),u_spin_weights:new t.bT(e,i.u_spin_weights),u_coords_top:new t.bS(e,i.u_coords_top),u_coords_bottom:new t.bS(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texsize_icon:new t.bU(e,i.u_texsize_icon),u_texture:new t.bP(e,i.u_texture),u_texture_icon:new t.bP(e,i.u_texture_icon),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_color:new t.bQ(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_image:new t.bP(e,i.u_image),u_pattern_tl_a:new t.bU(e,i.u_pattern_tl_a),u_pattern_br_a:new t.bU(e,i.u_pattern_br_a),u_pattern_tl_b:new t.bU(e,i.u_pattern_tl_b),u_pattern_br_b:new t.bU(e,i.u_pattern_br_b),u_texsize:new t.bU(e,i.u_texsize),u_mix:new t.bg(e,i.u_mix),u_pattern_size_a:new t.bU(e,i.u_pattern_size_a),u_pattern_size_b:new t.bU(e,i.u_pattern_size_b),u_scale_a:new t.bg(e,i.u_scale_a),u_scale_b:new t.bg(e,i.u_scale_b),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.bg(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_ele_delta:new t.bg(e,i.u_ele_delta),u_fog_matrix:new t.bR(e,i.u_fog_matrix),u_fog_color:new t.bQ(e,i.u_fog_color),u_fog_ground_blend:new t.bg(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.bg(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon_fog_blend:new t.bg(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.bg(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.bg(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_terrain_coords_id:new t.bg(e,i.u_terrain_coords_id),u_ele_delta:new t.bg(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.bg(e,i.u_input),u_output_expected:new t.bg(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.bT(e,i.u_sun_pos),u_atmosphere_blend:new t.bg(e,i.u_atmosphere_blend),u_globe_position:new t.bT(e,i.u_globe_position),u_globe_radius:new t.bg(e,i.u_globe_radius),u_inv_proj_matrix:new t.bR(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.bQ(e,i.u_sky_color),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon:new t.bU(e,i.u_horizon),u_horizon_normal:new t.bU(e,i.u_horizon_normal),u_sky_horizon_blend:new t.bg(e,i.u_sky_horizon_blend),u_sky_blend:new t.bg(e,i.u_sky_blend)})};class so{constructor(e,t,i){this.context=e;const o=e.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const no={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class lo{constructor(e,t,i,o){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=o,this.context=e;const r=e.gl;this.buffer=r.createBuffer(),e.bindVertexBuffer.set(this.buffer),r.bufferData(r.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(s,l.LINES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Fi(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),o.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!a||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.b$;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:S,angle:E});}else $e(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===o.layout.get("text-rotation-alignment");De(c,e,a,O,j,v,h,i,l.toUnwrapped(),f.width,f.height,U,t);}const $=a&&P||V,q=b||$?Yo:v?O:e.transform.clipSpaceToPixelsMatrix,W=p&&0!==o.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1);let H;H=p?c.iconsInText?to(T.kind,E,x,v,b,$,e,q,N,U,z,k,I):eo(T.kind,E,x,v,b,$,e,q,N,U,a,z,0,I):Ji(T.kind,E,x,v,b,$,e,q,N,U,a,z,I);const X={program:S,buffers:u,uniformValues:H,projectionData:Z,atlasTexture:D,atlasTextureIcon:F,atlasInterpolation:A,atlasInterpolationIcon:L,isSDF:p,hasHalo:W};if(y&&c.canOverlap){w=!0;const e=u.segments.get();for(const i of e)C.push({segments:new t.aM([i]),sortKey:i.sortKey,state:X,terrainData:R});}else C.push({segments:u.segments,sortKey:0,state:X,terrainData:R});}w&&C.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of C){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const r=i.uniformValues;i.hasHalo&&(r.u_is_halo=1,or(i.buffers,t.segments,o,e,i.program,T,u,d,r,i.projectionData,t.terrainData)),r.u_is_halo=0;}or(i.buffers,t.segments,o,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function or(e,t,i,o,r,a,s,n,l,c,h){const u=o.context;r.draw(u,u.gl.TRIANGLES,a,s,n,Ut.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,o.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function rr(e,i,o,r,a){const s=e.context,n=s.gl,l=Vt.disabled,c=new jt([n.ONE,n.ONE],t.bf.transparent,[!0,!0,!0,!0]),h=i.getBucket(o);if(!h)return;const u=r.key;let d=o.heatmapFbos.get(u);d||(d=sr(s,i.tileSize,i.tileSize),o.heatmapFbos.set(u,d)),s.bindFramebuffer.set(d.framebuffer),s.viewport.set([0,0,i.tileSize,i.tileSize]),s.clear({color:t.bf.transparent});const _=h.programConfigurations.get(o.id),p=e.useProgram("heatmap",_,!a),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),f=e.style.map.terrain.getTerrainData(r);p.draw(s,n.TRIANGLES,Zt.disabled,l,c,Ut.disabled,ji(i,e.transform.zoom,o.paint.get("heatmap-intensity"),1),f,m,o.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,o.paint,e.transform.zoom,_);}function ar(e,t,i,o,r){const a=e.context,s=a.gl,n=e.transform;a.setColorMode(e.colorModeForRenderPass());const l=nr(a,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,h.colorAttachment.get()),a.activeTexture.set(s.TEXTURE1),l.bind(s.LINEAR,s.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:r,applyGlobeMatrix:!o});e.useProgram("heatmapTexture").draw(a,s.TRIANGLES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Ni(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function sr(e,t,i){var o,r;const a=e.gl,s=a.createTexture();a.bindTexture(a.TEXTURE_2D,s),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR);const n=null!==(o=e.HALF_FLOAT)&&void 0!==o?o:a.UNSIGNED_BYTE,l=null!==(r=e.RGBA16F)&&void 0!==r?r:a.RGBA;a.texImage2D(a.TEXTURE_2D,0,l,t,i,0,a.RGBA,n,null);const c=e.createFramebuffer(t,i,!1,!1);return c.colorAttachment.set(s),c}function nr(e,i){return i.colorRampTexture||(i.colorRampTexture=new t.T(e,i.colorRamp,e.gl.RGBA)),i.colorRampTexture}function lr(e,t,i,o,r){if(!i||!o||!o.imageAtlas)return;const a=o.imageAtlas.patternPositions;let s=a[i.to.toString()],n=a[i.from.toString()];if(!s&&n&&(s=n),!n&&s&&(n=s),!s||!n){const e=r.getPaintProperty(t);s=a[e],n=a[e];}s&&n&&e.setConstantPatternPositions(s,n);}function cr(e,i,o,r,a,s,n,l){const c=e.context.gl,h="fill-pattern",u=o.paint.get(h),d=u&&u.constantOr(1),_=o.getCrossfadeParameters();let p,m,f,g,v;const b=e.transform,x=o.paint.get("fill-translate"),y=o.paint.get("fill-translate-anchor");n?(m=d&&!o.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",p=c.LINES):(m=d?"fillPattern":"fill",p=c.TRIANGLES);const w=u.constantOr(null);for(const u of r){const r=i.getTile(u);if(d&&!r.patternsLoaded())continue;const T=r.getBucket(o);if(!T)continue;const P=T.programConfigurations.get(o.id),C=e.useProgram(m,P),I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(u);d&&(e.context.activeTexture.set(c.TEXTURE0),r.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),P.updatePaintBuffers(_)),lr(P,h,w,r,o);const M=b.getProjectionData({overscaledTileID:u,applyGlobeMatrix:!l,applyTerrainMatrix:!0}),S=t.aD(b,r,x,y);if(n){g=T.indexBuffer2,v=T.segments2;const t=[c.drawingBufferWidth,c.drawingBufferHeight];f="fillOutlinePattern"===m&&d?Li(e,_,r,t,S):Ai(t,S);}else g=T.indexBuffer,v=T.segments,f=d?Di(e,_,r,S):{u_fill_translate:S};const E=e.stencilModeForClipping(u);C.draw(e.context,p,a,E,s,Ut.backCCW,f,I,M,o.id,T.layoutVertexBuffer,g,v,o.paint,e.transform.zoom,P);}}function hr(e,i,o,r,a,s,n,l){const c=e.context,h=c.gl,u="fill-extrusion-pattern",d=o.paint.get(u),_=d.constantOr(1),p=o.getCrossfadeParameters(),m=o.paint.get("fill-extrusion-opacity"),f=d.constantOr(null),g=e.transform;for(const d of r){const r=i.getTile(d),v=r.getBucket(o);if(!v)continue;const b=e.style.map.terrain&&e.style.map.terrain.getTerrainData(d),x=v.programConfigurations.get(o.id),y=e.useProgram(_?"fillExtrusionPattern":"fillExtrusion",x);_&&(e.context.activeTexture.set(h.TEXTURE0),r.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),x.updatePaintBuffers(p));const w=g.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!l,applyTerrainMatrix:!0});lr(x,u,f,r,o);const T=t.aD(g,r,o.paint.get("fill-extrusion-translate"),o.paint.get("fill-extrusion-translate-anchor")),P=o.paint.get("fill-extrusion-vertical-gradient"),C=_?zi(e,P,m,T,d,p,r):Ri(e,P,m,T);y.draw(c,c.gl.TRIANGLES,a,s,n,Ut.backCCW,C,b,w,o.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,o.paint,e.transform.zoom,x,e.style.map.terrain&&v.centroidVertexBuffer);}}function ur(e,t,i,o,r,a,s,n,l){var c;const h=e.style.projection,u=e.context,d=e.transform,_=u.gl,p=[`#define NUM_ILLUMINATION_SOURCES ${i.paint.get("hillshade-highlight-color").values.length}`],m=e.useProgram("hillshade",null,!1,p),f=!e.options.moving;for(const p of o){const o=t.getTile(p),g=o.fbo;if(!g)continue;const v=h.getMeshFromTileID(u,p.canonical,n,!0,"raster"),b=null===(c=e.style.map.terrain)||void 0===c?void 0:c.getTerrainData(p);u.activeTexture.set(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g.colorAttachment.get());const x=d.getProjectionData({overscaledTileID:p,aligned:f,applyGlobeMatrix:!l,applyTerrainMatrix:!0});m.draw(u,_.TRIANGLES,a,r[p.overscaledZ],s,Ut.backCCW,Ui(e,o,i),b,x,i.id,v.vertexBuffer,v.indexBuffer,v.segments);}}function dr(e,i,o,r,a,s,n,l,c){var h;const u=e.style.projection,d=e.context,_=e.transform,p=d.gl,m=e.useProgram("colorRelief"),f=!e.options.moving;let g=!0,v=0;for(const b of r){const r=i.getTile(b),x=r.dem;if(g){const e=p.getParameter(p.MAX_TEXTURE_SIZE),{elevationTexture:t,colorTexture:i}=o.getColorRampTextures(d,e,x.getUnpackVector());d.activeTexture.set(p.TEXTURE1),t.bind(p.NEAREST,p.CLAMP_TO_EDGE),d.activeTexture.set(p.TEXTURE4),i.bind(p.LINEAR,p.CLAMP_TO_EDGE),g=!1,v=t.size[0];}if(!x||!x.data)continue;const y=x.stride,w=x.getPixels();if(d.activeTexture.set(p.TEXTURE0),d.pixelStoreUnpackPremultiplyAlpha.set(!1),r.demTexture=r.demTexture||e.getTileTexture(y),r.demTexture){const e=r.demTexture;e.update(w,{premultiply:!1}),e.bind(p.LINEAR,p.CLAMP_TO_EDGE);}else r.demTexture=new t.T(d,w,p.RGBA,{premultiply:!1}),r.demTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE);const T=u.getMeshFromTileID(d,b.canonical,l,!0,"raster"),P=null===(h=e.style.map.terrain)||void 0===h?void 0:h.getTerrainData(b),C=_.getProjectionData({overscaledTileID:b,aligned:f,applyGlobeMatrix:!c,applyTerrainMatrix:!0});m.draw(d,p.TRIANGLES,s,a[b.overscaledZ],n,Ut.backCCW,Vi(o,r.dem,v),P,C,o.id,T.vertexBuffer,T.indexBuffer,T.segments);}}const _r=[new t.P(0,0),new t.P(t.$,0),new t.P(t.$,t.$),new t.P(0,t.$)];function pr(e,t,i,o,r,a,s,n,l=!1,c=!1){const h=o[o.length-1].overscaledZ,u=e.context,d=u.gl,_=e.useProgram("raster"),p=e.transform,m=e.style.projection,f=e.colorModeForRenderPass(),g=!e.options.moving;for(const v of o){const o=e.getDepthModeForSublayer(v.overscaledZ-h,1===i.paint.get("raster-opacity")?Zt.ReadWrite:Zt.ReadOnly,d.LESS),b=t.getTile(v);b.registerFadeDuration(i.paint.get("raster-fade-duration"));const x=t.findLoadedParent(v,0),y=t.findLoadedSibling(v),w=mr(b,x||y||null,t,i,e.transform,e.style.map.terrain);let T,P;const C="nearest"===i.paint.get("raster-resampling")?d.NEAREST:d.LINEAR;u.activeTexture.set(d.TEXTURE0),b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),u.activeTexture.set(d.TEXTURE1),x?(x.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),T=Math.pow(2,x.tileID.overscaledZ-b.tileID.overscaledZ),P=[b.tileID.canonical.x*T%1,b.tileID.canonical.y*T%1]):b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),b.texture.useMipmap&&u.extTextureFilterAnisotropic&&e.transform.pitch>20&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(v),M=p.getProjectionData({overscaledTileID:v,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),S=Yi(P||[0,0],T||1,w,i,n),E=m.getMeshFromTileID(u,v.canonical,a,s,"raster");_.draw(u,d.TRIANGLES,o,r?r[v.overscaledZ]:Vt.disabled,f,l?Ut.frontCCW:Ut.backCCW,S,I,M,i.id,E.vertexBuffer,E.indexBuffer,E.segments);}}function mr(e,i,o,r,a,n){const l=r.paint.get("raster-fade-duration");if(!n&&l>0){const r=s.now(),n=(r-e.timeAdded)/l,c=i?(r-i.timeAdded)/l:-1,h=o.getSource(),u=ge(a,{tileSize:h.tileSize,roundZoom:h.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-u)>Math.abs(e.tileID.overscaledZ-u),_=d&&e.refreshedUponExpiration?1:t.ah(d?n:1-c,0,1);return e.refreshedUponExpiration&&n>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-_}:{opacity:_,mix:0}}return {opacity:1,mix:0}}const fr=new t.bf(1,0,0,1),gr=new t.bf(0,1,0,1),vr=new t.bf(0,0,1,1),br=new t.bf(1,0,1,1),xr=new t.bf(0,1,1,1);function yr(e,t,i,o){Tr(e,0,t+i/2,e.transform.width,i,o);}function wr(e,t,i,o){Tr(e,t-i/2,0,i,e.transform.height,o);}function Tr(e,t,i,o,r,a){const s=e.context,n=s.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,o*e.pixelRatio,r*e.pixelRatio),s.clear({color:a}),n.disable(n.SCISSOR_TEST);}function Pr(e,i,o){const r=e.context,a=r.gl,s=e.useProgram("debug"),n=Zt.disabled,l=Vt.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(o);r.activeTexture.set(a.TEXTURE0);const d=i.getTileByID(o.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(o).tileSize,m=512/Math.min(p,512)*(o.overscaledZ/e.transform.zoom)*.5;let f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=` => ${o.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,o=e.context.gl,r=e.debugOverlayCanvas.getContext("2d");r.clearRect(0,0,i.width,i.height),r.shadowColor="white",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle="white",r.textBaseline="top",r.font="bold 36px Open Sans, sans-serif",r.fillText(t,5,5),r.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:o,applyGlobeMatrix:!0,applyTerrainMatrix:!0});s.draw(r,a.TRIANGLES,n,l,jt.alphaBlended,Ut.disabled,Oi(t.bf.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),s.draw(r,a.LINE_STRIP,n,l,c,Ut.disabled,Oi(t.bf.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function Cr(e,t,i,o){const{isRenderingGlobe:r}=o,a=e.context,s=a.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain");a.bindFramebuffer.set(null),a.viewport.set([0,0,e.width,e.height]);for(const o of i){const i=t.getTerrainMesh(o.tileID),u=e.renderToTexture.getTexture(o),d=t.getTerrainData(o.tileID);a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,u.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(o.tileID.toUnwrapped()),m=Ci(_,p,e.style.sky,n.pitch,r),f=n.getProjectionData({overscaledTileID:o.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});h.draw(a,s.TRIANGLES,c,Vt.disabled,l,Ut.backCCW,m,d,f,"terrain",i.vertexBuffer,i.indexBuffer,i.segments);}}function Ir(e,i){if(!i.mesh){const o=new t.aL;o.emplaceBack(-1,-1),o.emplaceBack(1,-1),o.emplaceBack(1,1),o.emplaceBack(-1,1);const r=new t.aN;r.emplaceBack(0,1,2),r.emplaceBack(0,2,3),i.mesh=new wt(e.createVertexBuffer(o,Tt.members),e.createIndexBuffer(r),t.aM.simpleSegment(0,0,o.length,r.length));}return i.mesh}class Mr{constructor(e,i){this.context=new Ho(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:t.ag(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=xe.maxUnderzooming+xe.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new vt;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.aL;i.emplaceBack(0,0),i.emplaceBack(t.$,0),i.emplaceBack(0,t.$),i.emplaceBack(t.$,t.$),this.tileExtentBuffer=e.createVertexBuffer(i,Tt.members),this.tileExtentSegments=t.aM.simpleSegment(0,0,4,2);const o=new t.aL;o.emplaceBack(0,0),o.emplaceBack(t.$,0),o.emplaceBack(0,t.$),o.emplaceBack(t.$,t.$),this.debugBuffer=e.createVertexBuffer(o,Tt.members),this.debugSegments=t.aM.simpleSegment(0,0,4,5);const r=new t.c6;r.emplaceBack(0,0,0,0),r.emplaceBack(t.$,0,t.$,0),r.emplaceBack(0,t.$,0,t.$),r.emplaceBack(t.$,t.$,t.$,t.$),this.rasterBoundsBuffer=e.createVertexBuffer(r,Ti.members),this.rasterBoundsSegments=t.aM.simpleSegment(0,0,4,2);const a=new t.aL;a.emplaceBack(0,0),a.emplaceBack(t.$,0),a.emplaceBack(0,t.$),a.emplaceBack(t.$,t.$),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(a,Tt.members),this.rasterBoundsSegmentsPosOnly=t.aM.simpleSegment(0,0,4,5);const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(1,0),s.emplaceBack(0,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,Tt.members),this.viewportSegments=t.aM.simpleSegment(0,0,4,2);const n=new t.c7;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.aN;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new Vt({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new wt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const o=t.L();t.bY(o,0,this.width,this.height,0,0,1),t.N(o,o,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const r={mainMatrix:o,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:o};this.useProgram("clippingMask",null,!0).draw(e,i.TRIANGLES,Zt.disabled,this.stencilClearMode,jt.disabled,Ut.disabled,null,null,r,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const o=this.context;o.setColorMode(jt.disabled),o.setDepthMode(Zt.disabled);const r={};for(const e of t)r[e.key]=this.nextStencilID++;this._renderTileMasks(r,t,i,!0),this._renderTileMasks(r,t,i,!1),this._tileClippingMaskIDs=r;}_renderTileMasks(e,t,i,o){const r=this.context,a=r.gl,s=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=s.getMeshFromTileID(this.context,c.canonical,o,!0,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!i,applyTerrainMatrix:!0});l.draw(r,a.TRIANGLES,Zt.disabled,new Vt({func:a.ALWAYS,mask:0},t,255,a.KEEP,a.KEEP,a.REPLACE),jt.disabled,i?Ut.disabled:Ut.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,o=this.transform,r=this.useProgram("depth"),a=this.getDepthModeFor3D(),s=ve(o,{tileSize:o.tileSize});for(const n of s){const s=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,!0,!0,"raster"),c=o.getProjectionData({overscaledTileID:n,applyGlobeMatrix:!0,applyTerrainMatrix:!0});r.draw(e,t.TRIANGLES,a,Vt.disabled,jt.disabled,Ut.backCCW,null,s,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new Vt({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new Vt({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(r>1){this.currentStencilSource=void 0,this.nextStencilID+r>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(this.clearStencil(),r>1){const e={},a={};for(let i=0;i0};for(const e in n){const t=n[e];t.used&&t.prepare(this.context),l[e]=t.getVisibleCoordinates(!1),c[e]=l[e].slice().reverse(),h[e]=t.getVisibleCoordinates(!0).reverse();}this.opaquePassCutoff=1/0;for(let e=0;ethis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.bf.black:t.bf.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,o=i.gl,r=((e,t,i)=>{const o=Math.cos(t.rollInRadians),r=Math.sin(t.rollInRadians),a=he(t),s=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-a*r)*i,(t.height/2+a*o)*i],u_horizon_normal:[-r,o],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:s}})(t,e.style.map.transform,e.pixelRatio),a=new Zt(o.LEQUAL,Zt.ReadWrite,[0,1]),s=Vt.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=Ir(i,t);l.draw(i,o.TRIANGLES,a,s,n,Ut.disabled,r,null,void 0,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=a.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[a[this.currentLayer]],t=n[e.source],i=l[e.source];this._renderTileClippingMasks(e,i,!1),this.renderLayer(this,t,e,i,u);}this.renderPass="translucent";let d=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:o,u_inv_proj_matrix:r}))(c,u,[p[0],p[1],p[2]],d,_),f=Ir(r,i);s.draw(r,a.TRIANGLES,n,Vt.disabled,jt.alphaBlended,Ut.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const o=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.sourceCaches[i.source]]:[])),r=o.filter((e=>"vector"===e.getSource().type)),a=o.filter((e=>"vector"!==e.getSource().type)),s=e=>{(!i||i.getSource().maxzooms(e))),i||a.forEach((e=>s(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let o=0;ou.getElevation(a,e,t):null;er(s,d,_,c,h,f,i,p,g,t.aD(h,e,n,l),a.toUnwrapped(),o);}}}(r,e,o,i,o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),a),0!==o.paint.get("icon-opacity").constantOr(1)&&ir(e,i,o,r,!1,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),o.layout.get("icon-rotation-alignment"),o.layout.get("icon-pitch-alignment"),o.layout.get("icon-keep-upright"),l,c,n),0!==o.paint.get("text-opacity").constantOr(1)&&ir(e,i,o,r,!0,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&(Ko(e,i,o,r,!0),Ko(e,i,o,r,!1));}(e,i,o,r,this.style.placement.variableOffsets,a):t.cc(o)?function(e,i,o,r,a){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:s}=a,n=o.paint.get("circle-opacity"),l=o.paint.get("circle-stroke-width"),c=o.paint.get("circle-stroke-opacity"),h=!o.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Zt.ReadOnly),m=Vt.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let a=0;ae.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:r,layoutVertexBuffer:a,indexBuffer:s,uniformValues:n,terrainData:l,projectionData:c}=t.state;r.draw(u,d.TRIANGLES,p,m,f,Ut.backCCW,n,l,c,o.id,a,s,t.segments,o.paint,e.transform.zoom,i);}}(e,i,o,r,a):t.cd(o)?function(e,i,o,r,a){if(0===o.paint.get("heatmap-opacity"))return;const s=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=a;if(e.style.map.terrain){for(const t of r){const r=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?rr(e,r,o,t,l):"translucent"===e.renderPass&&ar(e,o,t,n,l));}s.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,o,r){const a=e.context,s=a.gl,n=e.transform,l=Vt.disabled,c=new jt([s.ONE,s.ONE],t.bf.transparent,[!0,!0,!0,!0]);((function(e,i,o){const r=e.gl;e.activeTexture.set(r.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let a=o.heatmapFbos.get(t.c2);a?(r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer)):(a=sr(e,i.width/4,i.height/4),o.heatmapFbos.set(t.c2,a));}))(a,e,o),a.clear({color:t.bf.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return !1;if(!e.from||!e.to)return !0;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=!1,o=[]){this.cache=this.cache||{};const r=!!this.style.map.terrain,a=this.style.projection,s=i?xt.projectionMercator:a.shaderPreludeCode,n=i?Pt:a.shaderDefine,l=e+(t?t.cacheKey:"")+`/${i?Ct:a.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(r?"/terrain":"")+(o?`/${o.join("/")}`:"");return this.cache[l]||(this.cache[l]=new Si(this.context,xt[e],t,ao[e],this._showOverdrawInspector,r,s,n,o)),this.cache[l]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Sr(e,t){let i,o=!1,r=null,a=null;const s=()=>{r=null,o&&(e.apply(a,i),r=setTimeout(s,t),o=!1);};return (...e)=>(o=!0,a=this,i=e,r||s(),r)}class Er{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(!this._isValidHash(e))return !1;const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let o=window.location.hash.replace(i,"");o.startsWith("#&")?o=o.slice(0,1)+o.slice(2):"#"===o&&(o="");let r=window.location.href.replace(/(#.+)?$/,o);r=r.replace("&&","&"),window.history.replaceState(window.history.state,null,r);},this._updateHash=Sr(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,o=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),r=Math.pow(10,o),a=Math.round(t.lng*r)/r,s=Math.round(t.lat*r)/r,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${a}/${s}/${i}`:`${i}/${s}/${a}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const o=i.split("=")[0];return o===e?(t=!0,`${o}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return !1;try{new t.S(+e[2],+e[1]);}catch(e){return !1}const i=+e[0],o=+(e[3]||0),r=+(e[4]||0);return i>=this._map.getMinZoom()&&i<=this._map.getMaxZoom()&&o>=-180&&o<=180&&r>=this._map.getMinPitch()&&r<=this._map.getMaxPitch()}}const Rr={linearity:.3,easing:t.cm(0,0,.3,1)},zr=t.e({deceleration:2500,maxSpeed:1400},Rr),Dr=t.e({deceleration:20,maxSpeed:1400},Rr),Ar=t.e({deceleration:1e3,maxSpeed:360},Rr),Lr=t.e({deceleration:1e3,maxSpeed:90},Rr),kr=t.e({deceleration:1e3,maxSpeed:360},Rr);class Fr{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:s.now(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=s.now();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const o=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,r={};if(i.pan.mag()){const a=Or(i.pan.mag(),o,t.e({},zr,e||{})),s=i.pan.mult(a.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(s,this._map.transform);r.center=n.easingCenter,r.offset=n.easingOffset,Br(r,a);}if(i.zoom){const e=Or(i.zoom,o,Dr);r.zoom=this._map.transform.zoom+e.amount,Br(r,e);}if(i.bearing){const e=Or(i.bearing,o,Ar);r.bearing=this._map.transform.bearing+t.ah(e.amount,-179,179),Br(r,e);}if(i.pitch){const e=Or(i.pitch,o,Lr);r.pitch=this._map.transform.pitch+e.amount,Br(r,e);}if(i.roll){const e=Or(i.roll,o,kr);r.roll=this._map.transform.roll+t.ah(e.amount,-179,179),Br(r,e);}if(r.zoom||r.bearing){const e=void 0===i.pinchAround?i.around:i.pinchAround;r.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.e(r,{noMoveStart:!0})}}function Br(e,t){(!e.duration||e.durationi.unproject(e))),l=a.reduce(((e,t,i,o)=>e.add(t.div(o.length))),new t.P(0,0));super(e,{points:a,point:l,lngLats:s,lngLat:i.unproject(l),originalEvent:o}),this._defaultPrevented=!1;}}class Ur extends t.l{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=!1;}}class Zr{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new Ur(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new jr(e.type,this._map,e))}mouseup(e){this._map.fire(new jr(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new jr(e.type,this._map,e));}dblclick(e){return this._firePreventable(new jr(e.type,this._map,e))}mouseover(e){this._map.fire(new jr(e.type,this._map,e));}mouseout(e){this._map.fire(new jr(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Nr(e.type,this._map,e))}touchmove(e){this._map.fire(new Nr(e.type,this._map,e));}touchend(e){this._map.fire(new Nr(e.type,this._map,e));}touchcancel(e){this._map.fire(new Nr(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Gr{constructor(e){this._map=e;}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new jr(e.type,this._map,e));}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new jr("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new jr(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Vr{constructor(e){this._map=e;}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return {lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class $r{constructor(e,t){this._map=e,this._tr=new Vr(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(n.disableDrag(),this._startPos=this._lastPos=t,this._active=!0);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(o,r,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.l(e,{originalEvent:i}))}}function qr(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let o=0;othis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){const i=new t.P(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=qr(o,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const o=qr(i,t);for(const e in this.touches){const t=o[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Hr{constructor(e){this.singleTap=new Wr(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const o=this.singleTap.touchend(e,t,i);if(o){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(o)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}}}class Xr{constructor(e){this._tr=new Vr(e),this._zoomIn=new Hr({numTouches:1,numTaps:2}),this._zoomOut=new Hr({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const o=this._zoomIn.touchend(e,t,i),r=this._zoomOut.touchend(e,t,i),a=this._tr;return o?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom+1,around:a.unproject(o)},{originalEvent:e})}):r?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom-1,around:a.unproject(r)},{originalEvent:e})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class Kr{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0));}dragMove(e,t){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const o=Array.isArray(t)?t[0]:t;return !this._moved&&o.dist(i)!0}),t=new ta){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t;}_executeRelevantHandler(e,t,i){return e instanceof MouseEvent?t(e):"undefined"!=typeof TouchEvent&&e instanceof TouchEvent?i(e):void 0}startMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.startMove(e)),(e=>this.oneFingerTouchMoveStateManager.startMove(e)));}endMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.endMove(e)),(e=>this.oneFingerTouchMoveStateManager.endMove(e)));}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}const oa=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};class ra{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=!1,this._touches={},this._sum=new t.P(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,o){o.length>0&&(this._active=!0);const r=qr(o,i),a=new t.P(0,0),s=new t.P(0,0);let n=0;for(const e in r){const t=r[e],i=this._touches[e];i&&(a._add(t),s._add(t.sub(i)),n++,r[e]=t);}if(this._touches=r,this._shouldBePrevented(n)||!s.mag())return;const l=s.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class da extends aa{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,ua(e[0].sub(e[1]))&&(this._valid=!1);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const o=e[0].sub(this._lastPoints[0]),r=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const o=e.mag()>=2,r=t.mag()>=2;if(!o&&!r)return;if(!o||!r)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const a=e.y>0==t.y>0;return ua(e)&&ua(t)&&a}}const _a={panStep:100,bearingStep:15,pitchStep:10};class pa{constructor(e){this._tr=new Vr(e);const t=_a;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1;}reset(){this._active=!1;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,o=0,r=0,a=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),r=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),r=1);break;case 38:e.shiftKey?o=1:(e.preventDefault(),a=-1);break;case 40:e.shiftKey?o=-1:(e.preventDefault(),a=1);break;default:return}return this._rotationDisabled&&(i=0,o=0),{cameraAnimation:s=>{const n=this._tr;s.easeTo({duration:300,easeId:"keyboardHandler",easing:ma,zoom:t?Math.round(n.zoom)+t*(e.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+o*this._pitchStep,offset:[-r*this._panStep,-a*this._panStep],center:n.center},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function ma(e){return e*(2-e)}const fa=4.000244140625,ga=1/450;class va{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new Vr(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=ga;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=!1);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=s.now(),o=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%fa==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":o>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(o*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=n.mousePos(this._map.getCanvas(),e),o=this._tr;this._aroundPoint=this._aroundCenter?o.transform.locationToScreenPoint(t.S.convert(o.center)):i,this._frameId||(this._frameId=!0,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>fa?this._wheelZoomRate:this._defaultZoomRate;let o=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==o&&(o=1/o);const r="number"!=typeof this._targetZoom?e.scale:t.af(this._targetZoom);this._targetZoom=e.getConstrained(e.getCameraLngLat(),t.ak(r*o)).zoom,"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,o=this._startZoom,r=this._easing;let a,n=!1;if("wheel"===this._type&&o&&r){const e=s.now()-this._lastWheelEventTime,l=Math.min((e+5)/200,1),c=r(l);a=t.C.number(o,i,c),l<1?this._frameId||(this._frameId=!0):n=!0;}else a=i,n=!0;return this._active=!0,n&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=a,{noInertia:!0,needsRenderFrame:!n,zoomDelta:a-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.co;if(this._prevEase){const e=this._prevEase,o=(s.now()-e.start)/e.duration,r=e.easing(o+.01)-e.easing(o),a=.27/Math.sqrt(r*r+1e-4)*.01,n=Math.sqrt(.0729-a*a);i=t.cm(a,n,.25,1);}return this._prevEase={start:s.now(),duration:e,easing:i},i}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class ba{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class xa{constructor(e){this._tr=new Vr(e),this.reset();}reset(){this._active=!1;}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ya{constructor(){this._tap=new Hr({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const o=t[0],r=e.timeStamp-this._tapTime<500,a=this._tapPoint.dist(o)<30;r&&a?i.length>0&&(this._swipePoint=o,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const o=t[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,e.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const o=this._tap.touchend(e,t,i);o&&(this._tapTime=e.timeStamp,this._tapPoint=o);}}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class wa{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Ta{constructor(e,t,i,o){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=o;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Pa{constructor(e,t,i,o){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class Ca{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=!1;}isActive(){return !1}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=n.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),o=document.createElement("div");o.className="maplibregl-desktop-message",o.textContent=t,this._container.appendChild(o);const r=document.createElement("div");r.className="maplibregl-mobile-message",r.textContent=i,this._container.appendChild(r),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(n.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=!0;}disable(){this._enabled=!1,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.l("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const Ia=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Ma extends t.l{}function Sa(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class Ea{constructor(e,i){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,i)=>{if("blur"===e.type)return void this.stop(!0);this._updatingCamera=!0;const o="renderFrame"===e.type?void 0:e,r={needsRenderFrame:!1},a={},s={};for(const{handlerName:l,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let u;if(this._blockedByActive(s,h,l))c.reset();else if(c[i||e.type]){if(t.cp(e,i||e.type)){const t=n.mousePos(this._map.getCanvas(),e);u=c[i||e.type](e,t);}else if(t.cq(e,i||e.type)){const t=this._getMapTouches(e.touches),o=n.touchPos(this._map.getCanvas(),t);u=c[i||e.type](e,o,t);}else t.cr(i||e.type)||(u=c[i||e.type](e));this.mergeHandlerResult(r,a,u,l,o),u&&u.needsRenderFrame&&this._triggerRenderFrame();}(u||c.isActive())&&(s[l]=c);}const l={};for(const e in this._previousActiveHandlers)s[e]||(l[e]=o);this._previousActiveHandlers=s,(Object.keys(l).length||Sa(r))&&(this._changes.push([r,a,l]),this._triggerRenderFrame()),(Object.keys(s).length||Sa(r))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:c}=r;c&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],c(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Fr(e),this._bearingSnap=i.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(i);const o=this._el;this._listeners=[[o,"touchstart",{passive:!0}],[o,"touchmove",{passive:!1}],[o,"touchend",void 0],[o,"touchcancel",void 0],[o,"mousedown",void 0],[o,"mousemove",void 0],[o,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[o,"mouseover",void 0],[o,"mouseout",void 0],[o,"dblclick",void 0],[o,"click",void 0],[o,"keydown",{capture:!1}],[o,"keyup",void 0],[o,"wheel",{passive:!1}],[o,"contextmenu",void 0],[window,"blur",void 0]];for(const[e,t,i]of this._listeners)n.addEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)n.removeEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const i=this._map,o=i.getCanvasContainer();this._add("mapEvent",new Zr(i,e));const r=i.boxZoom=new $r(i,e);this._add("boxZoom",r),e.interactive&&e.boxZoom&&r.enable();const a=i.cooperativeGestures=new Ca(i,e.cooperativeGestures);this._add("cooperativeGestures",a),e.cooperativeGestures&&a.enable();const s=new Xr(i),l=new xa(i);i.doubleClickZoom=new ba(l,s),this._add("tapZoom",s),this._add("clickZoom",l),e.interactive&&e.doubleClickZoom&&i.doubleClickZoom.enable();const c=new ya;this._add("tapDragZoom",c);const h=i.touchPitch=new da(i);this._add("touchPitch",h),e.interactive&&e.touchPitch&&i.touchPitch.enable(e.touchPitch);const u=()=>i.project(i.getCenter()),d=function({enable:e,clickTolerance:i,aroundCenter:o=!0,minPixelCenterThreshold:r=100,rotateDegreesPerPixelMoved:a=.8},s){const l=new ea({checkCorrectEvent:e=>0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:i,move:(e,i)=>{const n=s();if(o&&Math.abs(n.y-e.y)>r)return {bearingDelta:t.cn(new t.P(e.x,i.y),i,n)};let l=(i.x-e.x)*a;return o&&i.y0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)});return new Kr({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:o,enable:e,assignEvents:oa})}(e),p=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3},o){const r=new ea({checkCorrectEvent:e=>2===n.mouseButton(e)&&e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>{const r=o();let a=(t.x-e.x)*i;return t.y0===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:i,enable:e,assignEvents:oa})}(e),f=new ra(e,i);i.dragPan=new wa(o,m,f),this._add("mousePan",m),this._add("touchPan",f,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&i.dragPan.enable(e.dragPan);const g=new ha,v=new la;i.touchZoomRotate=new Pa(o,v,g,c),this._add("touchRotate",g,["touchPan","touchZoom"]),this._add("touchZoom",v,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&i.touchZoomRotate.enable(e.touchZoomRotate);const b=i.scrollZoom=new va(i,(()=>this._triggerRenderFrame()));this._add("scrollZoom",b,["mousePan"]),e.interactive&&e.scrollZoom&&i.scrollZoom.enable(e.scrollZoom);const x=i.keyboard=new pa(i);this._add("keyboard",x),e.interactive&&e.keyboard&&i.keyboard.enable(),this._add("blockableMapEvent",new Gr(i));}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(Ia(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const o in e)if(o!==i&&(!t||t.indexOf(o)<0))return !0;return !1}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,o,r,a){if(!o)return;t.e(e,o);const s={handlerName:r,originalEvent:o.originalEvent||a};void 0!==o.zoomDelta&&(i.zoom=s),void 0!==o.panDelta&&(i.drag=s),void 0!==o.rollDelta&&(i.roll=s),void 0!==o.pitchDelta&&(i.pitch=s),void 0!==o.bearingDelta&&(i.rotate=s);}_applyChanges(){const e={},i={},o={};for(const[r,a,s]of this._changes)r.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(r.panDelta)),r.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+r.zoomDelta),r.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+r.bearingDelta),r.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+r.pitchDelta),r.rollDelta&&(e.rollDelta=(e.rollDelta||0)+r.rollDelta),void 0!==r.around&&(e.around=r.around),void 0!==r.pinchAround&&(e.pinchAround=r.pinchAround),r.noInertia&&(e.noInertia=r.noInertia),t.e(i,a),t.e(o,s);this._updateMapTransform(e,i,o),this._changes=[];}_updateMapTransform(e,t,i){const o=this._map,r=o._getTransformForUpdate(),a=o.terrain;if(!(Sa(e)||a&&this._terrainMovement))return this._fireEvents(t,i,!0);o._stop(!0);let{panDelta:s,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;void 0!==d&&(u=d),u=u||o.transform.centerPoint,a&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const _={panDelta:s,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const p=u.distSqr(r.centerPoint)<.01?r.center:r.screenPointToLocation(s?u.sub(s):u);a?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._terrainMovement||!t.drag&&!t.zoom?t.drag&&this._terrainMovement?r.setCenter(r.screenPointToLocation(r.centerPoint.sub(s))):this._map.cameraHelper.handleMapControlsPan(_,r,p):(this._terrainMovement=!0,this._map._elevationFreeze=!0,this._map.cameraHelper.handleMapControlsPan(_,r,p))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._map.cameraHelper.handleMapControlsPan(_,r,p)),o._applyUpdatedTransform(r),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0);}_fireEvents(e,i,o){const r=Ia(this._eventsInProgress),a=Ia(e),n={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(n[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!r&&a&&this._fireEvent("movestart",a.originalEvent);for(const e in n)this._fireEvent(e,n[e]);a&&this._fireEvent("move",a.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const l={};let c;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:o}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],c=i[t]||o,l[`${e}end`]=c);}for(const e in l)this._fireEvent(e,l[e]);const h=Ia(this._eventsInProgress),u=(r||a)&&!h;if(u&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(o&&u){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new Ma("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}class Ra extends t.E{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((s.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=i.bearingSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.S(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,o){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},i),o)}panTo(e,i,o){return this.easeTo(t.e({center:e},i),o)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,o){return this.easeTo(t.e({zoom:e},i),o)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.l("movestart",i)).fire(new t.l("move",i)).fire(new t.l("moveend",i))),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,o){return this.easeTo(t.e({bearing:e},i),o)}resetNorth(e,i){return this.rotateTo(0,t.e({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){f.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,o={}){this._moving=!0,i||o.moving||this.fire(new t.l("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.l("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.l("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.l("pitchstart",e)),this._rolling&&!o.rolling&&this.fire(new t.l("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0;}_updateElevation(e){void 0!==this._elevationStart&&void 0!==this._elevationCenter||this._prepareElevation(this.transform.center),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.C.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),o=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:o,zoom:r,roll:a,pitch:s,bearing:n,elevation:l}=e(t);o&&t.setCenter(o),void 0!==l&&t.setElevation(l),void 0!==r&&t.setZoom(r),void 0!==a&&t.setRoll(a),void 0!==s&&t.setPitch(s),void 0!==n&&t.setBearing(n),i.apply(t);}this.transform.apply(i);}_fireMoveEvents(e){this.fire(new t.l("move",e)),this._zooming&&this.fire(new t.l("zoom",e)),this._rotating&&this.fire(new t.l("rotate",e)),this._pitching&&this.fire(new t.l("pitch",e)),this._rolling&&this.fire(new t.l("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const o=this._zooming,r=this._rotating,a=this._pitching,s=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,o&&this.fire(new t.l("zoomend",e)),r&&this.fire(new t.l("rotateend",e)),a&&this.fire(new t.l("pitchend",e)),s&&this.fire(new t.l("rollend",e)),this.fire(new t.l("moveend",e));}flyTo(e,i){if(!e.essential&&s.prefersReducedMotion){const o=t.Q(e,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(o,i)}this.stop(),e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.co},e);const o=this._getTransformForUpdate(),r=o.bearing,a=o.pitch,n=o.roll,l=o.padding,c="bearing"in e?this._normalizeBearing(e.bearing,r):r,h="pitch"in e?+e.pitch:a,u="roll"in e?this._normalizeBearing(e.roll,n):n,d="padding"in e?e.padding:o.padding,_=t.P.convert(e.offset);let p=o.centerPoint.add(_);const m=o.screenPointToLocation(p),f=this.cameraHelper.handleFlyTo(o,{bearing:c,pitch:h,roll:u,padding:d,locationAtOffset:m,offsetAsPoint:_,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(o.width,o.height),b=v/f.scaleOfZoom,x=f.pixelPathLength;"number"==typeof f.scaleOfMinZoom&&(g=Math.sqrt(v/f.scaleOfMinZoom/x*2));const y=g*g;function w(e){const t=(b*b-v*v+(e?-1:1)*y*y*x*x)/(2*(e?b:v)*y*x);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function P(e){return (Math.exp(e)+Math.exp(-e))/2}const C=w(!1);let I=function(e){return P(C)/P(C+g*e)},M=function(e){return v*((P(C)*(T(t=C+g*e)/P(t))-T(C))/y)/x;var t;},S=(w(!0)-C)/g;if(Math.abs(x)<2e-6||!isFinite(S)){if(Math.abs(v-b)<1e-6)return this.easeTo(e,i);const t=b0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*S/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=r!==c,this._pitching=h!==a,this._rolling=u!==n,this._padding=!o.isPaddingEqual(d),this._prepareEase(i,!1),this.terrain&&this._prepareElevation(f.targetCenter),this._ease((s=>{const m=s*S,g=1/I(m),v=M(m);this._rotating&&o.setBearing(t.C.number(r,c,s)),this._pitching&&o.setPitch(t.C.number(a,h,s)),this._rolling&&o.setRoll(t.C.number(n,u,s)),this._padding&&(o.interpolatePadding(l,d,s),p=o.centerPoint.add(_)),f.easeFunc(s,g,v,p),this.terrain&&!e.freezeElevation&&this._updateElevation(s),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=s.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.aO(e,-180,180);const o=Math.abs(e-i);return Math.abs(e-360-i)MapLibre'};class Da{constructor(e=za){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=n.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=n.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=n.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.sourceCaches;for(const i in t){const o=t[i];if(o.used||o.usedForTerrain){const t=o.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let o=i+1;o=0)return !1;return !0}));const i=e.join(" | ");i!==this._attribHTML&&(this._attribHTML=i,e.length?(this._innerContainer.innerHTML=n.sanitize(i),this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Aa{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=n.create("div","maplibregl-ctrl");const t=n.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){n.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0;}}class La{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}var ka=t.aJ([{name:"a_pos3d",type:"Int16",components:3}]);class Fa extends t.E{constructor(e){super(),this._lastTilesetChange=s.now(),this.sourceCache=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize;}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null;}update(e,i){this.sourceCache.update(e,i),this._renderableTilesKeys=[];const o={};for(const r of ve(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:i,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))o[r.key]=!0,this._renderableTilesKeys.push(r.key),this._tiles[r.key]||(r.terrainRttPosMatrix32f=new Float64Array(16),t.bY(r.terrainRttPosMatrix32f,0,t.$,t.$,0,0,1),this._tiles[r.key]=new re(r,this.tileSize),this._lastTilesetChange=s.now());for(const e in this._tiles)o[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e,t){return t?this._getTerrainCoordsForTileRanges(e,t):this._getTerrainCoordsForRegularTile(e)}_getTerrainCoordsForRegularTile(e){const i={};for(const o of this._renderableTilesKeys){const r=this._tiles[o].tileID,a=e.clone(),s=t.ba();if(r.canonical.equals(e.canonical))t.bY(s,0,t.$,t.$,0,0,1);else if(r.canonical.isChildOf(e.canonical)){const i=r.canonical.z-e.canonical.z,o=r.canonical.x-(r.canonical.x>>i<>i<>i;t.bY(s,0,n,n,0,0,1),t.M(s,s,[-o*n,-a*n,0]);}else {if(!e.canonical.isChildOf(r.canonical))continue;{const i=e.canonical.z-r.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i;t.bY(s,0,t.$,t.$,0,0,1),t.M(s,s,[o*n,a*n,0]),t.N(s,s,[1/2**i,1/2**i,0]);}}a.terrainRttPosMatrix32f=new Float32Array(s),i[o]=a;}return i}_getTerrainCoordsForTileRanges(e,i){const o={};for(const r of this._renderableTilesKeys){const a=this._tiles[r].tileID;if(!this._isWithinTileRanges(a,i))continue;const s=e.clone(),n=t.ba();if(a.canonical.z===e.canonical.z){const i=e.canonical.x-a.canonical.x,o=e.canonical.y-a.canonical.y;t.bY(n,0,t.$,t.$,0,0,1),t.M(n,n,[i*t.$,o*t.$,0]);}else if(a.canonical.z>e.canonical.z){const i=a.canonical.z-e.canonical.z,o=a.canonical.x-(a.canonical.x>>i<>i<>i),l=e.canonical.y-(a.canonical.y>>i),c=t.$>>i;t.bY(n,0,c,c,0,0,1),t.M(n,n,[-o*c+s*t.$,-r*c+l*t.$,0]);}else {const i=e.canonical.z-a.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i)-a.canonical.x,l=(e.canonical.y>>i)-a.canonical.y,c=t.$<i.maxzoom&&(o=i.maxzoom),o=i.minzoom&&(!r||!r.dem);)r=this.sourceCache.getTileByID(e.scaledTo(o--).key);return r}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}_isWithinTileRanges(e,t){return t[e.canonical.z]&&e.canonical.x>=t[e.canonical.z].minTileX&&e.canonical.x<=t[e.canonical.z].maxTileX&&e.canonical.y>=t[e.canonical.z].minTileY&&e.canonical.y<=t[e.canonical.z].maxTileY}}class Ba{constructor(e,t,i){this._meshCache={},this.painter=e,this.sourceCache=new Fa(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(e,i,o,r=t.$){var a;if(!(i>=0&&i=0&&oe.canonical.z&&(e.canonical.z>=o?r=e.canonical.z-o:t.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const a=e.canonical.x-(e.canonical.x>>r<>r<>8<<4|e>>8,i[t+3]=0;const o=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),r=new t.T(e,o,e.gl.RGBA,{premultiply:!1});return r.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=r,r}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(!0);const i=new Uint8Array(4),o=this.painter.context,r=o.gl,a=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),s=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);o.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),r.readPixels(a,n-s-1,1,1,r.RGBA,r.UNSIGNED_BYTE,i),o.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.sourceCache.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<0,r=o&&0===e.canonical.y,a=o&&e.canonical.y===(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const ja={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class Na{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new Oa(e.context,30,t.sourceCache.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.sourceCaches){this._coordsAscending[t]={};const i=e.sourceCaches[t].getVisibleCoordinates(),o=e.sourceCaches[t].getSource(),r=o instanceof X?o.terrainTileRanges:null;for(const e of i){const i=this.terrain.sourceCache.getTerrainCoords(e,r);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._coordsAscendingStr={};for(const t of e._order){const i=e._layers[t],o=i.source;if(ja[i.type]&&!this._coordsAscendingStr[o]){this._coordsAscendingStr[o]={};for(const e in this._coordsAscending[o])this._coordsAscendingStr[o][e]=this._coordsAscending[o][e].map((e=>e.key)).sort().join();}}for(const e of this._renderableTiles)for(const t in this._coordsAscendingStr){const i=this._coordsAscendingStr[t][e.tileID.key];i&&i!==e.rttCoords[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return !1;const o=Object.assign(Object.assign({},i),{isRenderingToTexture:!0}),r=e.type,a=this.painter,s=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(ja[r]&&(this._prevType&&ja[this._prevType]||this._stacks.push([]),this._prevType=r,this._stacks[this._stacks.length-1].push(e.id),!s))return !0;if(ja[this._prevType]||ja[r]&&s){this._prevType=r;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const r of this._renderableTiles){if(this.pool.isFull()&&(Cr(this.painter,this.terrain,this._rttTiles,o),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(r),r.rtt[e]){const t=this.pool.getObjectForId(r.rtt[e].id);if(t.stamp===r.rtt[e].stamp){this.pool.useObject(t);continue}}const s=this.pool.getOrCreateFreeObject();this.pool.useObject(s),this.pool.stampObject(s),r.rtt[e]={id:s.id,stamp:s.stamp},a.context.bindFramebuffer.set(s.fbo.framebuffer),a.context.clear({color:t.bf.transparent,stencil:0}),a.currentStencilSource=void 0;for(let e=0;e{this.startMove(e,n.mousePos(this.element,e)),n.addEventListener(window,"mousemove",this.mousemove),n.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=e=>{this.move(e,n.mousePos(this.element,e));},this.mouseup=e=>{this._rotatePitchHandler.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),n.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.addEventListener(window,"touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHandler.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10,this.element=i;const r=new ia;this._rotatePitchHandler=new Kr({clickTolerance:3,move:(e,r)=>{const a=i.getBoundingClientRect(),s=new t.P((a.bottom-a.top)/2,(a.right-a.left)/2);return {bearingDelta:t.cn(new t.P(e.x,r.y),r,s),pitchDelta:o?-.5*(r.y-e.y):void 0}},moveStateManager:r,enable:!0,assignEvents:()=>{}}),this.map=e,n.addEventListener(i,"mousedown",this.mousedown),n.addEventListener(i,"touchstart",this.touchstart,{passive:!1}),n.addEventListener(i,"touchcancel",this.reset);}startMove(e,t){this._rotatePitchHandler.dragStart(e,t),n.disableDrag();}move(e,t){const i=this.map,{bearingDelta:o,pitchDelta:r}=this._rotatePitchHandler.dragMove(e,t)||{};o&&i.setBearing(i.getBearing()+o),r&&i.setPitch(i.getPitch()+r);}off(){const e=this.element;n.removeEventListener(e,"mousedown",this.mousedown),n.removeEventListener(e,"touchstart",this.touchstart,{passive:!1}),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend),n.removeEventListener(e,"touchcancel",this.reset),this.offTemp();}offTemp(){n.enableDrag(),n.removeEventListener(window,"mousemove",this.mousemove),n.removeEventListener(window,"mouseup",this.mouseup),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend);}}let qa;function Wa(e,i,o,r=!1){if(r||!o.getCoveringTilesDetailsProvider().allowWorldCopies())return null==e?void 0:e.wrap();const a=new t.S(e.lng,e.lat);if(e=new t.S(e.lng,e.lat),i){const r=new t.S(e.lng-360,e.lat),a=new t.S(e.lng+360,e.lat),s=o.locationToScreenPoint(e).distSqr(i);o.locationToScreenPoint(r).distSqr(i)180;){const t=o.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=o.width&&t.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==a.lng&&o.isPointOnMapSurface(o.locationToScreenPoint(e))?e:a}const Ha={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Xa(e,t,i){const o=e.classList;for(const e in Ha)o.remove(`maplibregl-${i}-anchor-${e}`);o.add(`maplibregl-${i}-anchor-${t}`);}class Ka extends t.E{constructor(e){if(super(),this._onKeyPress=e=>{const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{if(!this._map)return;const t=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?void 0:e.type)||"render"===(null==e?void 0:e.type)&&!t)&&this._map.once("render",this._update),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let i="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?i=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(i=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),n.setTransform(this._element,`${Ha[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${i}`),s.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.l("dragstart"))),this.fire(new t.l("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.l("dragend")),this._state="inactive";},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||!1,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(null==e?void 0:e.opacity,null==e?void 0:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.P.convert(e&&e.offset||[0,0]);else {this._defaultMarker=!0,this._element=n.create("div");const i=n.createNS("http://www.w3.org/2000/svg","svg"),o=41,r=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${o}px`),i.setAttributeNS(null,"width",`${r}px`),i.setAttributeNS(null,"viewBox",`0 0 ${r} ${o}`);const a=n.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"stroke","none"),a.setAttributeNS(null,"stroke-width","1"),a.setAttributeNS(null,"fill","none"),a.setAttributeNS(null,"fill-rule","evenodd");const s=n.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"fill-rule","nonzero");const l=n.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"transform","translate(3.0, 29.0)"),l.setAttributeNS(null,"fill","#000000");const c=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const e of c){const t=n.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),l.appendChild(t);}const h=n.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);const u=n.createNS("http://www.w3.org/2000/svg","path");u.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(u);const d=n.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");const _=n.createNS("http://www.w3.org/2000/svg","path");_.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(_);const p=n.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const m=n.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(8.0, 8.0)");const f=n.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#000000"),f.setAttributeNS(null,"opacity","0.25"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962");const g=n.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#FFFFFF"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962"),m.appendChild(f),m.appendChild(g),s.appendChild(l),s.appendChild(h),s.appendChild(d),s.appendChild(p),s.appendChild(m),i.appendChild(s),i.setAttributeNS(null,"height",o*this._scale+"px"),i.setAttributeNS(null,"width",r*this._scale+"px"),this._element.appendChild(i),this._offset=t.P.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),Xa(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),n.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,o=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-t],"bottom-left":[o,-1*(t-i+o)],"bottom-right":[-o,-1*(t-i+o)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=!1){var i,o;const r=null===(i=this._map)||void 0===i?void 0:i.terrain,a=this._map.transform.isLocationOccluded(this._lngLat);if(!r||a){const e=a?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const s=this._map,n=s.terrain.depthAtPoint(this._pos),l=s.terrain.getElevationForLngLatZoom(this._lngLat,s.transform.tileZoom);if(s.transform.lngLatToCameraDepth(this._lngLat,l)-n<.006)return void(this._element.style.opacity=this._opacity);const c=-this._offset.y/s.transform.pixelsPerMeter,h=Math.sin(s.getPitch()*Math.PI/180)*c,u=s.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),d=s.transform.lngLatToCameraDepth(this._lngLat,l+h)-u>.006;(null===(o=this._popup)||void 0===o?void 0:o.isOpen())&&d&&this._popup.remove(),this._element.style.opacity=d?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return (void 0===this._opacity||void 0===e&&void 0===t)&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==e&&(this._opacity=e),void 0!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(!0),this}}const Ya={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let Qa=0,Ja=!1;const es={maxWidth:100,unit:"metric"};function ts(e,t,i){const o=i&&i.maxWidth||100,r=e._container.clientHeight/2,a=e._container.clientWidth/2,s=e.unproject([a-o/2,r]),n=e.unproject([a+o/2,r]),l=Math.round(e.project(n).x-e.project(s).x),c=Math.min(o,l,e._container.clientWidth),h=s.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?is(t,c,i/5280,e._getUIString("ScaleControl.Miles")):is(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?is(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?is(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):is(t,c,h,e._getUIString("ScaleControl.Meters"));}function is(e,t,i,o){const r=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(r/i)+"px",e.innerHTML=`${r} ${o}`;}const os={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1,locationOccludedOpacity:void 0},rs=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function as(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(i,i),"top-right":new t.P(-i,i),bottom:new t.P(0,-e),"bottom-left":new t.P(i,-i),"bottom-right":new t.P(-i,-i),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){const i=t.P.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e["top-left"]||[0,0]),"top-right":t.P.convert(e["top-right"]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e["bottom-left"]||[0,0]),"bottom-right":t.P.convert(e["bottom-right"]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return as(new t.P(0,0))}const ss=i;e.AJAXError=t.cz,e.Event=t.l,e.Evented=t.E,e.LngLat=t.S,e.MercatorCoordinate=t.a1,e.Point=t.P,e.addProtocol=t.cA,e.config=t.a,e.removeProtocol=t.cB,e.AttributionControl=Da,e.BoxZoomHandler=$r,e.CanvasSource=Y,e.CooperativeGesturesHandler=Ca,e.DoubleClickZoomHandler=ba,e.DragPanHandler=wa,e.DragRotateHandler=Ta,e.EdgeInsets=Mt,e.FullscreenControl=class extends t.E{constructor(e={}){super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(e=null==t?void 0:t.shadowRoot)||void 0===e?void 0:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){n.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=n.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);n.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new t.l("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.l("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=H,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.l("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "BACKGROUND":case "BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.l("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.S(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.e({bearing:r},this.options.fitBoundsOptions),s=G.fromLngLat(i,o);this._map.fitBounds(s,a,{geolocateSource:!0});},this._updateMarker=e=>{if(e){const i=new t.S(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this._updateCircleRadiusIfNeeded();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded();},this._onError=e=>{if(this._map){if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Ja)return;this.options.trackUserLocation&&this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.l("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=n.create("button","maplibregl-ctrl-geolocate",this._container),n.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0);},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.w("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=n.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new Ka({element:this._dotElement}),this._circleElement=n.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ka({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onUpdate),this._map.on("move",this._onUpdate),this._map.on("rotate",this._onUpdate),this._map.on("pitch",this._onUpdate)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(e=>{const i=(null==e?void 0:e[0])instanceof ResizeObserverEntry;e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||i||this._map.isZooming()||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.l("trackuserlocationend")),this.fire(new t.l("userlocationlostfocus")));}));}},this.options=t.e({},Ya,e);}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t._(this,arguments,void 0,(function*(e=!1){if(void 0!==qa&&!e)return qa;if(void 0===window.navigator.permissions)return qa=!!window.navigator.geolocation,qa;try{const e=yield window.navigator.permissions.query({name:"geolocation"});qa="denied"!==e.state;}catch(e){qa=!!window.navigator.geolocation;}return qa}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),n.remove(this._container),this._map.off("zoom",this._onUpdate),this._map.off("move",this._onUpdate),this._map.off("rotate",this._onUpdate),this._map.off("pitch",this._onUpdate),this._map=void 0,Qa=0,Ja=!1;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case "WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case "ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadiusIfNeeded(){const e=this._userLocationDotMarker.getLngLat();if(!(this.options.showUserLocation&&this.options.showAccuracyCircle&&this._accuracy&&e))return;const t=this._map.project(e),i=this._map.unproject([t.x+100,t.y]),o=e.distanceTo(i)/100,r=2*this._accuracy/o;this._circleElement.style.width=`${r.toFixed(2)}px`,this._circleElement.style.height=`${r.toFixed(2)}px`;}trigger(){if(!this._setup)return t.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case "OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.l("trackuserlocationstart"));break;case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":case "BACKGROUND_ERROR":Qa--,Ja=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new t.l("trackuserlocationend"));break;case "BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.l("trackuserlocationstart")),this.fire(new t.l("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case "WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),Qa++,Qa>1?(e={maximumAge:6e5,timeout:0},Ja=!0):(e=this.options.positionOptions,Ja=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||void 0===e?void 0:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||void 0===e?void 0:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=n.create("button","maplibregl-ctrl-globe",this._container),n.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0;}},e.Hash=Er,e.ImageSource=X,e.KeyboardHandler=pa,e.LngLatBounds=G,e.LogoControl=Aa,e.Map=class extends Ra{constructor(e){var i,o;t.cw.mark(t.cx.create);const r=Object.assign(Object.assign(Object.assign({},Ga),e),{canvasContextAttributes:Object.assign(Object.assign({},Ga.canvasContextAttributes),e.canvasContextAttributes)});if(null!=r.minZoom&&null!=r.maxZoom&&r.minZoom>r.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=r.minPitch&&null!=r.maxPitch&&r.minPitch>r.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=r.minPitch&&r.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=r.maxPitch&&r.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const a=new Lt,s=new Ot;if(void 0!==r.minZoom&&a.setMinZoom(r.minZoom),void 0!==r.maxZoom&&a.setMaxZoom(r.maxZoom),void 0!==r.minPitch&&a.setMinPitch(r.minPitch),void 0!==r.maxPitch&&a.setMaxPitch(r.maxPitch),void 0!==r.renderWorldCopies&&a.setRenderWorldCopies(r.renderWorldCopies),super(a,s,{bearingSnap:r.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new La,this._controls=[],this._mapId=t.a7(),this._contextLost=e=>{e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new t.l("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._setupPainter(),this.resize(),this._update(),this.fire(new t.l("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update();},this._interactive=r.interactive,this._maxTileCacheSize=r.maxTileCacheSize,this._maxTileCacheZoomLevels=r.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},r.canvasContextAttributes),this._trackResize=!0===r.trackResize,this._bearingSnap=r.bearingSnap,this._centerClampedToGround=r.centerClampedToGround,this._refreshExpiredTiles=!0===r.refreshExpiredTiles,this._fadeDuration=r.fadeDuration,this._crossSourceCollisions=!0===r.crossSourceCollisions,this._collectResourceTiming=!0===r.collectResourceTiming,this._locale=Object.assign(Object.assign({},Ua),r.locale),this._clickTolerance=r.clickTolerance,this._overridePixelRatio=r.pixelRatio,this._maxCanvasSize=r.maxCanvasSize,this.transformCameraUpdate=r.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===r.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=p.addThrottleControl((()=>this.isMoving())),this._requestManager=new m(r.transformRequest),"string"==typeof r.container){if(this._container=document.getElementById(r.container),!this._container)throw new Error(`Container '${r.container}' not found.`)}else {if(!(r.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=r.container;}if(r.maxBounds&&this.setMaxBounds(r.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0);})),this.once("idle",(()=>{this._idleTriggered=!0;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let e=!1;const t=Sr((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{e?t(i):e=!0;})),this._resizeObserver.observe(this._container);}this.handlers=new Ea(this,r),this._hash=r.hash&&new Er("string"==typeof r.hash&&r.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:r.center,elevation:r.elevation,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,roll:r.roll}),r.bounds&&(this.resize(),this.fitBounds(r.bounds,t.e({},r.fitBoundsOptions,{duration:0}))));const n="string"==typeof r.style||!("globe"===(null===(o=null===(i=r.style)||void 0===i?void 0:i.projection)||void 0===o?void 0:o.type));this.resize(null,n),this._localIdeographFontFamily=r.localIdeographFontFamily,this._validateStyle=r.validateStyle,r.style&&this.setStyle(r.style,{localIdeographFontFamily:r.localIdeographFontFamily}),r.attributionControl&&this.addControl(new Da("boolean"==typeof r.attributionControl?void 0:r.attributionControl)),r.maplibreLogo&&this.addControl(new Aa,r.logoPosition),this.on("style.load",(()=>{if(n||this._resizeTransform(),this.transform.unmodified){const e=t.Q(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.l(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.l(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.l("sourcedataabort",e));}));}_getMapId(){return this._mapId}setGlobalStateProperty(e,t){return this.style.setGlobalStateProperty(e,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(e,i){if(void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.k(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const o=e.onAdd(this);this._controls.push(e);const r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.k(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}coveringTiles(e){return ve(this.transform,e)}calculateCameraOptionsFromTo(e,t,i,o){return null==o&&this.terrain&&(o=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(e,t,i,o)}resize(e,i=!0){const[o,r]=this._containerDimensions(),a=this._getClampedPixelRatio(o,r);if(this._resizeCanvas(o,r,a),this.painter.resize(o,r,a),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const t=this._getClampedPixelRatio(o,r);this._resizeCanvas(o,r,t),this.painter.resize(o,r,t);}this._resizeTransform(i);const s=!this._moving;return s&&(this.stop(),this.fire(new t.l("movestart",e)).fire(new t.l("move",e))),this.fire(new t.l("resize",e)),s&&this.fire(new t.l("moveend",e)),this}_resizeTransform(e=!0){var t;const[i,o]=this._containerDimensions();this.transform.resize(i,o,e),null===(t=this._requestedCameraState)||void 0===t||t.resize(i,o,e);}_getClampedPixelRatio(e,t){const{0:i,1:o}=this._maxCanvasSize,r=this.getPixelRatio(),a=e*r,s=t*r;return Math.min(a>i?i/a:1,s>o?o/s:1)*r}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&void 0!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(G.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom)return this.transform.setMinZoom(e),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(e),this._update(),this.getZoom()>e&&this.setZoom(e),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.setMinPitch(e),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch)return this.transform.setMaxPitch(e),this._update(),this.getPitch()>e&&this.setPitch(e),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.S.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||void 0===e?void 0:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||void 0===e?void 0:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||void 0===e?void 0:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e))),s=0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[];s.length?o||(o=!0,i.call(this,new jr(e,this,r.originalEvent,{features:s}))):o=!1;};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:()=>{o=!1;}}}}if("mouseleave"===e||"mouseout"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e)));(0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[]).length?o=!0:o&&(o=!1,i.call(this,new jr(e,this,r.originalEvent)));},a=t=>{o&&(o=!1,i.call(this,new jr(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:a}}}{const o=e=>{const o=t.filter((e=>this.getLayer(e))),r=0!==o.length?this.queryRenderedFeatures(e.point,{layers:o}):[];r.length&&(e.features=r,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:o}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const o=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in r.delegates)this.off(e,r.delegates[e]);return void o.splice(e,1)}}}on(e,t,i){if(void 0===i)return super.on(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);this._saveDelegatedListener(e,r);for(const e in r.delegates)this.on(e,r.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,o,i);}}}once(e,t,i){if(void 0===i)return super.once(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);for(const t in r.delegates){const a=r.delegates[t];r.delegates[t]=(...t)=>{this._removeDelegatedListener(e,o,i),a(...t);};}this._saveDelegatedListener(e,r);for(const e in r.delegates)this.once(e,r.delegates[e]);return this}off(e,t,i){return void 0===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let o;const r=e instanceof t.P||Array.isArray(e),a=r?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(r?{}:e)||{},a instanceof t.P||"number"==typeof a[0])o=[t.P.convert(a)];else {const e=t.P.convert(a[0]),i=t.P.convert(a[1]);o=[e,new t.P(i.x,e.y),i,new t.P(e.x,i.y),e];}return this.style.queryRenderedFeatures(o,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return !1!==(i=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,o;if(t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const r=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new wi(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,r):this.style.loadJSON(e,t,r),this):(null===(o=null===(i=this.style)||void 0===i?void 0:i.projection)||void 0===o||o.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new wi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){if("string"==typeof e){const o=this._requestManager.transformRequest(e,"Style");t.j(o,new AbortController).then((e=>{this._updateDiff(e.data,i);})).catch((e=>{e&&this.fire(new t.k(e));}));}else "object"==typeof e&&this._updateDiff(e,i);}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(o){t.w(`Unable to perform style diff: ${o.message||o.error||o}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():t.w("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){const i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.k(new Error(`There is no source with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.sourceCaches[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const o=this.style._layers[i];"hillshade"===o.type&&o.source===e.source&&t.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality."),"color-relief"===o.type&&o.source===e.source&&t.w("You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");}this.terrain=new Ba(this.painter,i,e),this.painter.renderToTexture=new Na(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{var i;"style"===t.dataType?this.terrain.sourceCache.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),"image"===(null===(i=t.source)||void 0===i?void 0:i.type)?this.terrain.sourceCache.freeRtt():this.terrain.sourceCache.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.l("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||void 0===e?void 0:e.options)&&void 0!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.sourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}}return !0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}setSourceTileLodParams(e,t,i){if(i){const o=this.getSource(i);if(!o)throw new Error(`There is no source with ID "${i}", cannot set LOD parameters`);o.calculateTileZoom=me(Math.max(1,e),Math.max(1,t));}else for(const i in this.style.sourceCaches)this.style.sourceCaches[i].getSource().calculateTileZoom=me(Math.max(1,e),Math.max(1,t));return this._update(!0),this}refreshTiles(e,i){const o=this.style.sourceCaches[e];if(!o)throw new Error(`There is no source cache with ID "${e}", cannot refresh tile`);void 0===i?o.reload(!0):o.refreshTiles(i.map((e=>new t.a4(e.z,e.x,e.y))));}addImage(e,i,o={}){const{pixelRatio:r=1,sdf:a=!1,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u}=o;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.b(i))){if(void 0===i.width||void 0===i.height)return this.fire(new t.k(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:o,height:s,data:d}=i,_=i;return this.style.addImage(e,{data:new t.R({width:o,height:s},new Uint8Array(d)),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:o,height:d,data:_}=s.getImageData(i);this.style.addImage(e,{data:new t.R({width:o,height:d},_),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0});}}updateImage(e,i){const o=this.style.getImage(e);if(!o)return this.fire(new t.k(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const r=i instanceof HTMLImageElement||t.b(i)?s.getImageData(i):i,{width:a,height:n,data:l}=r;if(void 0===a||void 0===n)return this.fire(new t.k(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(a!==o.data.width||n!==o.data.height)return this.fire(new t.k(new Error("The width and height of the updated image must be that same as the previous version of the image")));const c=!(i instanceof HTMLImageElement||t.b(i));return o.data.replace(l,c),this.style.updateImage(e,o),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.k(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(e);}loadImage(e){return p.getImage(this._requestManager.transformRequest(e,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(!0)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,o={}){return this.style.setPaintProperty(e,t,i,o),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,o={}){return this.style.setLayoutProperty(e,t,i,o),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(!0);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=n.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=n.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),o=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],o);const r=this._controlContainer=n.create("div","maplibregl-control-container",e),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{a[e]=n.create("div",`maplibregl-ctrl-${e} `,r);})),this._container.addEventListener("scroll",this._onMapScroll,!1);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0});let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:!0});let i=null;if(i=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e),!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new Mr(i,this.transform),l.testSupport(i);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.l("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){var i,o,r,a,n;const l=this._idleTriggered?this._fadeDuration:0,c=(null===(i=this.style.projection)||void 0===i?void 0:i.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let h=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,i=s.now();this.style.zoomHistory.update(e,i);const o=new t.F(e,{now:i,fadeDuration:l,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),r=o.crossFadingFactor();1===r&&r===this._crossFadingFactor||(h=!0,this._crossFadingFactor=r),this.style.update(o);}const u=(null===(o=this.style.projection)||void 0===o?void 0:o.transitionState)>0!==c;null===(r=this.style.projection)||void 0===r||r.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(a=this.style.projection)||void 0===a?void 0:a.transitionState,null===(n=this.style.projection)||void 0===n?void 0:n.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||u)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,l,this._crossSourceCollisions,u),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:l,showPadding:this.showPadding}),this.fire(new t.l("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,t.cw.mark(t.cx.load),this.fire(new t.l("load"))),this.style&&(this.style.hasTransitions()||h)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const d=this._sourcesDirty||this._styleDirty||this._placementDirty;return d||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.l("idle")),!this._loaded||this._fullyLoaded||d||(this._fullyLoaded=!0,t.cw.mark(t.cx.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),p.removeThrottleControl(this._imageQueueHandle),null===(e=this._resizeObserver)||void 0===e||e.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?void 0:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),n.remove(this._canvasContainer),n.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),t.cw.clearMetrics(),this._removed=!0,this.fire(new t.l("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,s.frame(this._frameRequest,(e=>{t.cw.frame(e),this._frameRequest=null;try{this._render(e);}catch(e){if(!t.cy(e)&&!function(e){return e.message===qo}(e))throw e}}),(()=>{})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return Za}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}},e.MapMouseEvent=jr,e.MapTouchEvent=Nr,e.MapWheelEvent=Ur,e.Marker=Ka,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.e({},Va,e),this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=n.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new $a(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){n.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=n.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.E{constructor(e){super(),this._updateOpacity=()=>{void 0!==this.options.locationOccludedOpacity&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:"");},this.remove=()=>(this._content&&n.remove(this._content),this._container&&(n.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new t.l("close"))),this),this._onMouseUp=e=>{this._update(e.point);},this._onMouseMove=e=>{this._update(e.point);},this._onDrag=e=>{this._update(e.point);},this._update=e=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=n.create("div","maplibregl-popup",this._map.getContainer()),this._tip=n.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer");}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),this._trackPointer&&!e)return;const t=this._flatPos=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&e?e:this._map.transform.locationToScreenPoint(this._lngLat));let i=this.options.anchor;const o=as(this.options.offset);if(!i){const e=this._container.offsetWidth,r=this._container.offsetHeight;let a;a=t.y+o.bottom.ythis._map.transform.height-r?["bottom"]:[],t.xthis._map.transform.width-e/2&&a.push("right"),i=0===a.length?"bottom":a.join("-");}let r=t.add(o[i]);this.options.subpixelPositioning||(r=r.round()),n.setTransform(this._container,`${Ha[i]} translate(${r.x}px,${r.y}px)`),Xa(this._container,i,"popup"),this._updateOpacity();},this._onClose=()=>{this.remove();},this.options=t.e(Object.create(os),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.l("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let o;for(i.innerHTML=e;o=i.firstChild,o;)t.appendChild(o);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||void 0===e?void 0:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=n.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}_createCloseButton(){this.options.closeButton&&(this._closeButton=n.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(rs);e&&e.focus();}},e.RasterDEMTileSource=W,e.RasterTileSource=q,e.ScaleControl=class{constructor(e){this._onMove=()=>{ts(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,ts(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},es),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){n.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;}},e.ScrollZoomHandler=va,e.Style=wi,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=n.create("button","maplibregl-ctrl-terrain",this._container),n.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){n.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0;}},e.TwoFingersTouchPitchHandler=da,e.TwoFingersTouchRotateHandler=ha,e.TwoFingersTouchZoomHandler=la,e.TwoFingersTouchZoomRotateHandler=Pa,e.VectorTileSource=$,e.VideoSource=K,e.addSourceType=(e,i)=>t._(void 0,void 0,void 0,(function*(){if(J(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{Q[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=A;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(R),A=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},e.createTileMesh=Xt,e.getMaxParallelImageRequests=function(){return t.a.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},e.getVersion=function(){return ss},e.getWorkerCount=function(){return z.workerCount},e.getWorkerUrl=function(){return t.a.WORKER_URL},e.importScriptInWorkers=function(e){return B().broadcast("IS",e)},e.prewarm=function(){k().acquire(R);},e.setMaxParallelImageRequests=function(e){t.a.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setRTLTextPlugin=function(e,t){return oe().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){z.workerCount=e;},e.setWorkerUrl=function(e){t.a.WORKER_URL=e;};})); + +// +// Our custom intro provides a specialized "define()" function, called by the +// AMD modules below, that sets up the worker blob URL and then executes the +// main module, storing its exported value as 'maplibregl' + + +var maplibregl$1 = maplibregl; + +return maplibregl$1; + +})); +//# sourceMappingURL=maplibre-gl.js.map diff --git a/docs/articles/layers-overview_files/maplibregl-binding-0.3.1.9000/maplibregl.js b/docs/articles/layers-overview_files/maplibregl-binding-0.3.1.9000/maplibregl.js new file mode 100644 index 0000000..f5481b0 --- /dev/null +++ b/docs/articles/layers-overview_files/maplibregl-binding-0.3.1.9000/maplibregl.js @@ -0,0 +1,4285 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/layers-overview_files/maplibregl-binding-0.3.2/maplibregl.js b/docs/articles/layers-overview_files/maplibregl-binding-0.3.2/maplibregl.js new file mode 100644 index 0000000..f5481b0 --- /dev/null +++ b/docs/articles/layers-overview_files/maplibregl-binding-0.3.2/maplibregl.js @@ -0,0 +1,4285 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/layers-overview_files/maplibregl-binding-0.3.9.9000/maplibregl.js b/docs/articles/layers-overview_files/maplibregl-binding-0.3.9.9000/maplibregl.js new file mode 100644 index 0000000..c8312af --- /dev/null +++ b/docs/articles/layers-overview_files/maplibregl-binding-0.3.9.9000/maplibregl.js @@ -0,0 +1,4337 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/layers-overview_files/maplibregl-binding-0.4.0.9000/maplibregl.js b/docs/articles/layers-overview_files/maplibregl-binding-0.4.0.9000/maplibregl.js new file mode 100644 index 0000000..8558cc4 --- /dev/null +++ b/docs/articles/layers-overview_files/maplibregl-binding-0.4.0.9000/maplibregl.js @@ -0,0 +1,4506 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/layers-overview_files/maplibregl-binding-0.4.0/maplibregl.js b/docs/articles/layers-overview_files/maplibregl-binding-0.4.0/maplibregl.js new file mode 100644 index 0000000..c8312af --- /dev/null +++ b/docs/articles/layers-overview_files/maplibregl-binding-0.4.0/maplibregl.js @@ -0,0 +1,4337 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/layers-overview_files/maplibregl-binding-0.4.1/maplibregl.js b/docs/articles/layers-overview_files/maplibregl-binding-0.4.1/maplibregl.js new file mode 100644 index 0000000..5937d02 --- /dev/null +++ b/docs/articles/layers-overview_files/maplibregl-binding-0.4.1/maplibregl.js @@ -0,0 +1,5048 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + const result = originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + return result; + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse( + this.getAttribute("data-layer-ids"), + ); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } + } + }); +} diff --git a/docs/articles/layers-overview_files/maptiler-geocoding-control-2.1.7/LICENSE.txt b/docs/articles/layers-overview_files/maptiler-geocoding-control-2.1.7/LICENSE.txt new file mode 100644 index 0000000..624d1f1 --- /dev/null +++ b/docs/articles/layers-overview_files/maptiler-geocoding-control-2.1.7/LICENSE.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2023, MapTiler +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/articles/layers-overview_files/maptiler-geocoding-control-2.1.7/maplibregl.umd.js b/docs/articles/layers-overview_files/maptiler-geocoding-control-2.1.7/maplibregl.umd.js new file mode 100644 index 0000000..0fe7116 --- /dev/null +++ b/docs/articles/layers-overview_files/maptiler-geocoding-control-2.1.7/maplibregl.umd.js @@ -0,0 +1,14 @@ +(function(j,ee){typeof exports=="object"&&typeof module<"u"?ee(exports,require("maplibre-gl")):typeof define=="function"&&define.amd?define(["exports","maplibre-gl"],ee):(j=typeof globalThis<"u"?globalThis:j||self,ee(j.maplibreglMaptilerGeocoder={},j.maplibregl))})(this,function(j,ee){"use strict";var Ws=Object.defineProperty;var bn=j=>{throw TypeError(j)};var Gs=(j,ee,me)=>ee in j?Ws(j,ee,{enumerable:!0,configurable:!0,writable:!0,value:me}):j[ee]=me;var A=(j,ee,me)=>Gs(j,typeof ee!="symbol"?ee+"":ee,me),wn=(j,ee,me)=>ee.has(j)||bn("Cannot "+me);var ue=(j,ee,me)=>(wn(j,ee,"read from private field"),me?me.call(j):ee.get(j)),Vt=(j,ee,me)=>ee.has(j)?bn("Cannot add the same private member more than once"):ee instanceof WeakSet?ee.add(j):ee.set(j,me),kt=(j,ee,me,dt)=>(wn(j,ee,"write to private field"),dt?dt.call(j,me):ee.set(j,me),me);var fn,cn;function me(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const dt=me(ee);function ne(){}function Ln(i,e){for(const t in e)i[t]=e[t];return i}function yi(i){return i()}function vi(){return Object.create(null)}function Ue(i){i.forEach(yi)}function bi(i){return typeof i=="function"}function Ke(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}let Rt;function ye(i,e){return i===e?!0:(Rt||(Rt=document.createElement("a")),Rt.href=e,i===Rt.href)}function _n(i){return Object.keys(i).length===0}function Sn(i,e,t,n){if(i){const r=wi(i,e,t,n);return i[0](r)}}function wi(i,e,t,n){return i[1]&&n?Ln(t.ctx.slice(),i[1](n(e))):t.ctx}function xn(i,e,t,n){return i[2],e.dirty}function Tn(i,e,t,n,r,u){if(r){const a=wi(e,t,n,u);i.p(a,r)}}function Mn(i){if(i.ctx.length>32){const e=[],t=i.ctx.length/32;for(let n=0;ni.removeEventListener(e,t,n)}function Nn(i){return function(e){return e.preventDefault(),i.call(this,e)}}function S(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function kn(i){return Array.from(i.childNodes)}function gt(i,e){e=""+e,i.data!==e&&(i.data=e)}function Ei(i,e){i.value=e??""}function Ie(i,e,t){i.classList.toggle(e,!!t)}function On(i,e,{bubbles:t=!1,cancelable:n=!1}={}){return new CustomEvent(i,{detail:e,bubbles:t,cancelable:n})}let mt;function pt(i){mt=i}function Li(){if(!mt)throw new Error("Function called outside component initialization");return mt}function Rn(i){Li().$$.on_destroy.push(i)}function _i(){const i=Li();return(e,t,{cancelable:n=!1}={})=>{const r=i.$$.callbacks[e];if(r){const u=On(e,t,{cancelable:n});return r.slice().forEach(a=>{a.call(i,u)}),!u.defaultPrevented}return!0}}function Pn(i,e){const t=i.$$.callbacks[e.type];t&&t.slice().forEach(n=>n.call(this,e))}const ut=[],Yt=[];let at=[];const Si=[],In=Promise.resolve();let Qt=!1;function An(){Qt||(Qt=!0,In.then(xi))}function Xt(i){at.push(i)}const Jt=new Set;let ft=0;function xi(){if(ft!==0)return;const i=mt;do{try{for(;fti.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),at=e}const It=new Set;let nt;function yt(){nt={r:0,c:[],p:nt}}function vt(){nt.r||Ue(nt.c),nt=nt.p}function re(i,e){i&&i.i&&(It.delete(i),i.i(e))}function fe(i,e,t,n){if(i&&i.o){if(It.has(i))return;It.add(i),nt.c.push(()=>{It.delete(i),n&&(t&&i.d(1),n())}),i.o(e)}else n&&n()}function Ti(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function Gn(i,e){fe(i,1,1,()=>{e.delete(i.key)})}function Dn(i,e,t,n,r,u,a,o,g,c,E,_){let M=i.length,R=u.length,k=M;const I={};for(;k--;)I[i[k].key]=k;const C=[],O=new Map,x=new Map,N=[];for(k=R;k--;){const W=_(r,u,k),s=t(W);let l=a.get(s);l?N.push(()=>l.p(W,e)):(l=c(s,W),l.c()),O.set(s,C[k]=l),s in I&&x.set(s,Math.abs(k-I[s]))}const P=new Set,B=new Set;function z(W){re(W,1),W.m(o,E),a.set(W.key,W),E=W.first,R--}for(;M&&R;){const W=C[R-1],s=i[M-1],l=W.key,f=s.key;W===s?(E=W.first,M--,R--):O.has(f)?!a.has(l)||P.has(l)?z(W):B.has(f)?M--:x.get(l)>x.get(f)?(B.add(l),z(W)):(P.add(f),M--):(g(s,a),M--)}for(;M--;){const W=i[M];O.has(W.key)||g(W,a)}for(;R;)z(C[R-1]);return Ue(N),C}function Qe(i){i&&i.c()}function qe(i,e,t){const{fragment:n,after_update:r}=i.$$;n&&n.m(e,t),Xt(()=>{const u=i.$$.on_mount.map(yi).filter(bi);i.$$.on_destroy?i.$$.on_destroy.push(...u):Ue(u),i.$$.on_mount=[]}),r.forEach(Xt)}function Fe(i,e){const t=i.$$;t.fragment!==null&&(Wn(t.after_update),Ue(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function zn(i,e){i.$$.dirty[0]===-1&&(ut.push(i),An(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<{const k=R.length?R[0]:M;return c.ctx&&r(c.ctx[_],c.ctx[_]=k)&&(!c.skip_bound&&c.bound[_]&&c.bound[_](k),E&&zn(i,_)),M}):[],c.update(),E=!0,Ue(c.before_update),c.fragment=n?n(c.ctx):!1,e.target){if(e.hydrate){const _=kn(e.target);c.fragment&&c.fragment.l(_),_.forEach($)}else c.fragment&&c.fragment.c();e.intro&&re(i.$$.fragment),qe(i,e.target,e.anchor),xi()}pt(g)}class Je{constructor(){A(this,"$$");A(this,"$$set")}$destroy(){Fe(this,1),this.$destroy=ne}$on(e,t){if(!bi(t))return ne;const n=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return n.push(t),()=>{const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}$set(e){this.$$set&&!_n(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Un="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Un);function qn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M13.12.706a.982.982 0 0 0-1.391 0L6.907 5.517 2.087.696a.982.982 0 1 0-1.391 1.39l4.821 4.821L.696 11.73a.982.982 0 1 0 1.39 1.39l4.821-4.821 4.822 4.821a.982.982 0 1 0 1.39-1.39L8.298 6.908l4.821-4.822a.988.988 0 0 0 0-1.38Z"),S(e,"viewBox","0 0 14 14"),S(e,"width","13"),S(e,"height","13"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Mi extends Je{constructor(e){super(),Xe(this,e,null,qn,Ke,{})}}function Fn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M15 0C6.705 0 0 6.705 0 15C0 23.295 6.705 30 15 30C23.295 30 30 23.295 30 15C30 6.705 23.295 0 15 0ZM22.5 20.385L20.385 22.5L15 17.115L9.615 22.5L7.5 20.385L12.885 15L7.5 9.615L9.615 7.5L15 12.885L20.385 7.5L22.5 9.615L17.115 15L22.5 20.385Z"),S(e,"viewBox","0 0 30 30"),S(e,"fill","none"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"class","svelte-d2loi5")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Ci extends Je{constructor(e){super(),Xe(this,e,null,Fn,Ke,{})}}function jn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"area.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"area.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Zn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"reverse.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"reverse.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Hn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"poi.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"poi.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Vn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"postal_code.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"postal_code.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Kn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"street.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"street.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Yn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"road.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"road.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Qn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"housenumber.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"housenumber.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Xn(i){let e,t,n,r;return{c(){e=Y("img"),ye(e.src,t=i[5])||S(e,"src",t),S(e,"alt",i[4]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(u,a){te(u,e,a),n||(r=he(e,"error",i[14]),n=!0)},p(u,a){a&32&&!ye(e.src,t=u[5])&&S(e,"src",t),a&16&&S(e,"alt",u[4]),a&128&&S(e,"title",u[7])},d(u){u&&$(e),n=!1,r()}}}function Jn(i){let e,t;return{c(){e=Y("div"),S(e,"class","sprite-icon svelte-w9y5n9"),S(e,"style",t=` + width: ${i[6].width/xe}px; + height: ${i[6].height/xe}px; + background-image: url(${i[3]}sprite${$t}.png); + background-position: -${i[6].x/xe}px -${i[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `),S(e,"title",i[7])},m(n,r){te(n,e,r)},p(n,r){r&72&&t!==(t=` + width: ${n[6].width/xe}px; + height: ${n[6].height/xe}px; + background-image: url(${n[3]}sprite${$t}.png); + background-position: -${n[6].x/xe}px -${n[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `)&&S(e,"style",t),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Ni(i){let e,t;return{c(){e=Y("span"),t=Ye(i[7]),S(e,"class","secondary svelte-w9y5n9")},m(n,r){te(n,e,r),V(e,t)},p(n,r){r&128&>(t,n[7])},d(n){n&&$(e)}}}function $n(i){let e,t,n,r,u,a,o,g,c,E=(i[8]?i[0].place_name:i[0].place_name.replace(/,.*/,""))+"",_,M,R=i[2]==="always"||i[2]!=="never"&&!i[0].address&&!i[0].id.startsWith("road.")&&!i[0].id.startsWith("address.")&&!i[0].id.startsWith("postal_code.")&&(!i[0].id.startsWith("poi.")||!i[5])&&!i[8],k,I,C=(i[8]?"":i[0].place_name.replace(/[^,]*,?\s*/,""))+"",O,x,N,P,B,z;function W(m,h){return h&1&&(t=null),h&1&&(n=null),h&1&&(r=null),h&1&&(u=null),Oe&&m[6]?Jn:m[5]?Xn:m[0].address?Qn:(t==null&&(t=!!m[0].id.startsWith("road.")),t?Yn:(n==null&&(n=!!m[0].id.startsWith("address.")),n?Kn:(r==null&&(r=!!m[0].id.startsWith("postal_code.")),r?Vn:(u==null&&(u=!!m[0].id.startsWith("poi.")),u?Hn:m[8]?Zn:jn))))}let s=W(i,-1),l=s(i),f=R&&Ni(i);return{c(){e=Y("li"),l.c(),a=we(),o=Y("span"),g=Y("span"),c=Y("span"),_=Ye(E),M=we(),f&&f.c(),k=we(),I=Y("span"),O=Ye(C),S(c,"class","primary svelte-w9y5n9"),S(g,"class","svelte-w9y5n9"),S(I,"class","line2 svelte-w9y5n9"),S(o,"class","texts svelte-w9y5n9"),S(e,"tabindex","-1"),S(e,"role","option"),S(e,"aria-selected",x=i[1]==="selected"),S(e,"aria-checked",N=i[1]==="picked"),S(e,"class",P=Pt(i[1])+" svelte-w9y5n9")},m(m,h){te(m,e,h),l.m(e,null),V(e,a),V(e,o),V(o,g),V(g,c),V(c,_),V(g,M),f&&f.m(g,null),V(o,k),V(o,I),V(I,O),B||(z=[he(e,"mouseenter",i[13]),he(e,"focus",i[15]),he(e,"click",i[16])],B=!0)},p(m,[h]){s===(s=W(m,h))&&l?l.p(m,h):(l.d(1),l=s(m),l&&(l.c(),l.m(e,a))),h&257&&E!==(E=(m[8]?m[0].place_name:m[0].place_name.replace(/,.*/,""))+"")&>(_,E),h&293&&(R=m[2]==="always"||m[2]!=="never"&&!m[0].address&&!m[0].id.startsWith("road.")&&!m[0].id.startsWith("address.")&&!m[0].id.startsWith("postal_code.")&&(!m[0].id.startsWith("poi.")||!m[5])&&!m[8]),R?f?f.p(m,h):(f=Ni(m),f.c(),f.m(g,null)):f&&(f.d(1),f=null),h&257&&C!==(C=(m[8]?"":m[0].place_name.replace(/[^,]*,?\s*/,""))+"")&>(O,C),h&2&&x!==(x=m[1]==="selected")&&S(e,"aria-selected",x),h&2&&N!==(N=m[1]==="picked")&&S(e,"aria-checked",N),h&2&&P!==(P=Pt(m[1])+" svelte-w9y5n9")&&S(e,"class",P)},i:ne,o:ne,d(m){m&&$(e),l.d(),f&&f.d(),B=!1,Ue(z)}}}const ki=typeof devicePixelRatio>"u"?1:devicePixelRatio>1.25,$t=ki?"@2x":"",xe=ki?2:1;let Oe,At;function er(i,e,t){let n,r,u,{feature:a}=e,{style:o="default"}=e,{showPlaceType:g}=e,{missingIconsCache:c}=e,{iconsBaseUrl:E}=e;const _=_i();let M,R,k,I;function C(){At??(At=fetch(`${E}sprite${$t}.json`).then(s=>s.json()).then(s=>{Oe=s}).catch(()=>{Oe=null}))}function O(){R&&c.add(R),x()}function x(){Oe!==void 0?N():(C(),At==null||At.then(N))}function N(){do{if(I--,t(4,M=n==null?void 0:n[I]),t(6,k=M?Oe==null?void 0:Oe.icons[M]:void 0),k)break;t(5,R=M?E+M.replace(/ /g,"_")+".svg":void 0)}while(I>-1&&(!R||c.has(R)))}function P(s){Pn.call(this,i,s)}const B=()=>O(),z=()=>_("select",void 0),W=s=>{document.activeElement!==s.target&&_("select",void 0)};return i.$$set=s=>{"feature"in s&&t(0,a=s.feature),"style"in s&&t(1,o=s.style),"showPlaceType"in s&&t(2,g=s.showPlaceType),"missingIconsCache"in s&&t(11,c=s.missingIconsCache),"iconsBaseUrl"in s&&t(3,E=s.iconsBaseUrl)},i.$$.update=()=>{var s,l,f,m,h;i.$$.dirty&1&&t(12,n=(s=a.properties)==null?void 0:s.categories),i.$$.dirty&1&&t(8,r=a.place_type[0]==="reverse"),i.$$.dirty&1&&t(7,u=((f=(l=a.properties)==null?void 0:l.categories)==null?void 0:f.join(", "))??((h=(m=a.properties)==null?void 0:m.place_type_name)==null?void 0:h[0])??a.place_type[0]),i.$$.dirty&4096&&(I=(n==null?void 0:n.length)??0,x())},[a,o,g,E,M,R,k,u,r,_,O,c,n,P,B,z,W]}class tr extends Je{constructor(e){super(),Xe(this,e,er,$n,Ke,{feature:0,style:1,showPlaceType:2,missingIconsCache:11,iconsBaseUrl:3})}}function ir(i){let e;return{c(){e=Y("div"),e.innerHTML='',S(e,"class","svelte-1ocfouu")},m(t,n){te(t,e,n)},p:ne,i:ne,o:ne,d(t){t&&$(e)}}}class nr extends Je{constructor(e){super(),Xe(this,e,null,ir,Ke,{})}}function rr(i){let e,t,n;return{c(){e=ke("svg"),t=ke("path"),S(t,"stroke-width","4"),S(t,"d","M 5,33.103579 C 5,17.607779 18.457,5 35,5 C 51.543,5 65,17.607779 65,33.103579 C 65,56.388679 40.4668,76.048179 36.6112,79.137779 C 36.3714,79.329879 36.2116,79.457979 36.1427,79.518879 C 35.8203,79.800879 35.4102,79.942779 35,79.942779 C 34.5899,79.942779 34.1797,79.800879 33.8575,79.518879 C 33.7886,79.457979 33.6289,79.330079 33.3893,79.138079 C 29.5346,76.049279 5,56.389379 5,33.103579 Z M 35.0001,49.386379 C 43.1917,49.386379 49.8323,42.646079 49.8323,34.331379 C 49.8323,26.016779 43.1917,19.276479 35.0001,19.276479 C 26.8085,19.276479 20.1679,26.016779 20.1679,34.331379 C 20.1679,42.646079 26.8085,49.386379 35.0001,49.386379 Z"),S(t,"class","svelte-gzo3ar"),S(e,"width",n=i[0]==="list"?20:void 0),S(e,"viewBox","0 0 70 85"),S(e,"fill","none"),S(e,"class","svelte-gzo3ar"),Ie(e,"in-map",i[0]!=="list"),Ie(e,"list-icon",i[0]==="list")},m(r,u){te(r,e,u),V(e,t)},p(r,[u]){u&1&&n!==(n=r[0]==="list"?20:void 0)&&S(e,"width",n),u&1&&Ie(e,"in-map",r[0]!=="list"),u&1&&Ie(e,"list-icon",r[0]==="list")},i:ne,o:ne,d(r){r&&$(e)}}}function sr(i,e,t){let{displayIn:n}=e;return i.$$set=r=>{"displayIn"in r&&t(0,n=r.displayIn)},[n]}class or extends Je{constructor(e){super(),Xe(this,e,sr,rr,Ke,{displayIn:0})}}function lr(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M30.003-26.765C13.46-26.765 0-14.158 0 1.337c0 23.286 24.535 42.952 28.39 46.04.24.192.402.316.471.376.323.282.732.424 1.142.424.41 0 .82-.142 1.142-.424.068-.06.231-.183.471-.376 3.856-3.09 28.39-22.754 28.39-46.04 0-15.495-13.46-28.102-30.003-28.102Zm1.757 12.469c4.38 0 7.858 1.052 10.431 3.158 2.595 2.105 3.89 4.913 3.89 8.422 0 2.34-.53 4.362-1.593 6.063-1.063 1.702-3.086 3.616-6.063 5.742-2.042 1.51-3.337 2.659-3.89 3.446-.532.787-.8 1.82-.8 3.096v1.914h-8.449V15.18c0-2.041.434-3.815 1.306-5.325.872-1.51 2.467-3.118 4.785-4.82 2.233-1.594 3.7-2.89 4.402-3.889a5.582 5.582 0 0 0 1.087-3.35c0-1.382-.51-2.435-1.531-3.158-1.02-.723-2.45-1.087-4.28-1.087-3.19 0-6.826 1.047-10.91 3.131l-3.472-6.986c4.742-2.659 9.77-3.992 15.087-3.992Zm-1.88 37.324c1.765 0 3.124.472 4.08 1.408.98.936 1.47 2.276 1.47 4.02 0 1.68-.49 3.007-1.47 3.985-.977.957-2.336 1.435-4.08 1.435-1.787 0-3.171-.465-4.15-1.4-.978-.958-1.47-2.298-1.47-4.02 0-1.787.48-3.14 1.436-4.054.957-.915 2.355-1.374 4.184-1.374Z"),S(e,"viewBox","0 0 60.006 21.412"),S(e,"width","14"),S(e,"height","20"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class ur extends Je{constructor(e){super(),Xe(this,e,null,lr,Ke,{})}}function ar(i){let e,t,n;return{c(){e=ke("svg"),t=ke("circle"),n=ke("path"),S(t,"cx","4.789"),S(t,"cy","4.787"),S(t,"r","3.85"),S(t,"class","svelte-1aq105l"),S(n,"d","M12.063 12.063 7.635 7.635"),S(n,"class","svelte-1aq105l"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"width","13"),S(e,"height","13"),S(e,"viewBox","0 0 13 13"),S(e,"class","svelte-1aq105l")},m(r,u){te(r,e,u),V(e,t),V(e,n)},p:ne,i:ne,o:ne,d(r){r&&$(e)}}}class fr extends Je{constructor(e){super(),Xe(this,e,null,ar,Ke,{})}}function cr(i,e,t){const n=e[1],r=e[0],u=n-r;return i===n&&t?i:((i-r)%u+u)%u+r}function Bt(i){const e=[...i];return e[2]Math.abs((e[0]-360+e[2])/2)?e[0]-=360:e[2]+=360),e}let bt;async function hr(i,e,t){const n=i==null?void 0:i.getCenterAndZoom();for(const r of e??[])if(!(n&&(r.minZoom!=null&&r.minZoom>n[0]||r.maxZoom!=null&&r.maxZoomDate.now()){if(!bt.coords)break e;return bt.coords}let u;try{return u=await new Promise((a,o)=>{t.signal.addEventListener("abort",()=>{o(Error("aborted"))}),navigator.geolocation.getCurrentPosition(g=>{a([g.coords.longitude,g.coords.latitude].map(c=>c.toFixed(6)).join(","))},g=>{o(g)},r)}),u}catch{}finally{r.cachedLocationExpiry&&(bt={time:Date.now(),coords:u})}if(t.signal.aborted)return}if(r.type==="server-geolocation")return"ip";if(n&&r.type==="map-center")return n[1].toFixed(6)+","+n[2].toFixed(6)}}const dr=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(EAST|WEST|[EW])?$/i,Oi=/^([+-]?[0-8]?[0-9])\s+([0-5]?[0-9]\.\d{3,})[\s,]{1,}([+-]?[0-1]?[0-9]?[0-9])\s+([0-5]?[0-9]\.\d{3,})$/,Ri=/^(NORTH|SOUTH|[NS])?[\s]*([+-]?[0-8]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(NORTH|SOUTH|[NS])?[\s]*[,/;]?[\s]*(EAST|WEST|[EW])?[\s]*([+-]?[0-1]?[0-9]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(EAST|WEST|[EW])?$/i,Pi=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(EAST|WEST|[EW])?$/i,Ii=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)\s*(EAST|WEST|[EW])?$/i,Ai=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|’’|´´|["″”\.])?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|´´|’’|["″”\.])?\s*(EAST|WEST|[EW])?$/i;function gr(i){if(!["DMS","DM","DD"].includes(i))throw new Error("invalid format specified");if(this.decimalCoordinates&&this.decimalCoordinates.trim()){const e=this.decimalCoordinates.split(",").map(R=>Number(R.trim())),t=Number(e[0]),n=Number(e[1]),r=Math.abs(t),u=Math.abs(n),a=t>0?"N":"S",o=n>0?"E":"W";let g;i=="DD"&&(g=`${r}° ${a}, ${u}° ${o}`);const c=Math.floor(r),E=Math.floor(u),_=(r-c)*60,M=(u-E)*60;if(i=="DM"){let R=Bi(_,3).toFixed(3).padStart(6,"0"),k=Bi(M,3).toFixed(3).padStart(6,"0");R.endsWith(".000")&&k.endsWith(".000")&&(R=R.replace(/\.000$/,""),k=k.replace(/\.000$/,"")),g=`${c}° ${R}' ${a}, ${E}° ${k}' ${o}`}if(i=="DMS"){const R=Math.floor(_),k=Math.floor(M);let I=((_-R)*60).toFixed(1).padStart(4,"0"),C=((M-k)*60).toFixed(1).padStart(4,"0");const O=R.toString().padStart(2,"0"),x=k.toString().padStart(2,"0");I.endsWith(".0")&&C.endsWith(".0")&&(I=I.replace(/\.0$/,""),C=C.replace(/\.0$/,"")),g=`${c}° ${O}' ${I}" ${a}, ${E}° ${x}' ${C}" ${o}`}return g}else throw new Error("no decimal coordinates to convert")}function Bi(i,e){const t=Math.pow(10,e);return Math.round((i+Number.EPSILON)*t)/t}function ei(i,e){e||(e=5),i=i.replace(/\s+/g," ").trim();let t=null,n=null,r="",u="",a=null,o=[],g=!1;if(dr.test(i))throw new Error("invalid coordinate value");if(Oi.test(i))if(o=Oi.exec(i),g=wt(o),g)t=Math.abs(o[1])+o[2]/60,Number(o[1])<0&&(t*=-1),n=Math.abs(o[3])+o[4]/60,Number(o[3])<0&&(n*=-1),a="DM";else throw new Error("invalid coordinate format");else if(Ri.test(i))if(o=Ri.exec(i),g=wt(o),g){if(t=o[2],n=o[6],t.includes(",")&&(t=t.replace(",",".")),n.includes(",")&&(n=n.replace(",",".")),a="DD",Number(Math.round(t))==Number(t))throw new Error("integer only coordinate provided");if(Number(Math.round(n))==Number(n))throw new Error("integer only coordinate provided");o[1]?(r=o[1],u=o[5]):o[4]&&(r=o[4],u=o[8])}else throw new Error("invalid decimal coordinate format");else if(Pi.test(i))if(o=Pi.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[9])),o[11]&&(n+=o[11]/60),o[13]&&(n+=o[13].replace(",",".")/3600),parseInt(o[9])<0&&(n=-1*n),o[1]?(r=o[1],u=o[8]):o[7]&&(r=o[7],u=o[14]);else throw new Error("invalid DMS coordinates format");else if(Ii.test(i))if(o=Ii.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6]/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12]/60),o[14]&&(n+=o[14]/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid DMS coordinates format");else if(Ai.test(i)){if(o=Ai.exec(i),g=wt(o),o.filter(c=>c).length<=5)throw new Error("invalid coordinates format");if(g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4].replace(",",".")/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12].replace(",",".")/60),o[14]&&(n+=o[14].replace(",",".")/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid coordinates format")}if(g){if(Math.abs(n)>=180)throw new Error("invalid longitude value");if(Math.abs(t)>=90)throw new Error("invalid latitude value");if(r&&!u||!r&&u)throw new Error("invalid coordinates value");if(r&&r==u)throw new Error("invalid coordinates format");t.toString().includes(",")&&(t=t.replace(",",".")),n.toString().includes(",")&&(n=n.replace(",","."));let c=/S|SOUTH/i;c.test(r)&&t>0&&(t=-1*t),c=/W|WEST/i,c.test(u)&&n>0&&(n=-1*n);const E=o[0].trim();let _,M;const R=/[,/;\u0020]/g,k=E.match(R);if(k==null){const O=Math.floor(i.length/2);_=E.substring(0,O).trim(),M=E.substring(O).trim()}else{let O;k.length%2==1?O=Math.floor(k.length/2):O=k.length/2-1;let x=0;if(O==0)x=E.indexOf(k[0]),_=E.substring(0,x).trim(),M=E.substring(x+1).trim();else{let N=0,P=0;for(;N<=O;)x=E.indexOf(k[N],P),P=x+1,N++;_=E.substring(0,x).trim(),M=E.substring(x+1).trim()}}const I=_.split(".");if(I.length==2&&I[1]==0&&I[1].length!=2)throw new Error("invalid coordinates format");const C=M.split(".");if(C.length==2&&C[1]==0&&C[1].length!=2)throw new Error("invalid coordinates format");if(/^\d+$/.test(_)||/^\d+$/.test(M))throw new Error("degree only coordinate/s provided");return t=Number(Number(t).toFixed(e)),n=Number(Number(n).toFixed(e)),Object.freeze({verbatimCoordinates:E,verbatimLatitude:_,verbatimLongitude:M,decimalLatitude:t,decimalLongitude:n,decimalCoordinates:`${t},${n}`,originalFormat:a,closeEnough:mr,toCoordinateFormat:gr})}else throw new Error("coordinates pattern match failed")}function wt(i){if(!isNaN(i[0]))return!1;const e=[...i];if(e.shift(),e.length%2>0)return!1;const t=/^[-+]?\d+([\.,]\d+)?$/,n=/[eastsouthnorthwest]+/i,r=e.length/2;for(let u=0;u{e.decimalLatitude?i.push(e):i.push({...e,...vr})}),[...i,...br,...wr]}const Lr=Er();ei.formats=Lr.map(i=>i.verbatimCoordinates);const _r=ei;function Gi(i,e,t){const n=i.slice();return n[97]=e[t],n[99]=t,n}function Di(i){let e,t,n,r,u;return t=new Mi({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[3]),S(e,"class","svelte-bz0zu3")},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[78]),r=!0)},p(a,o){(!n||o[0]&8)&&S(e,"title",a[3])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function zi(i){let e,t;return e=new nr({}),{c(){Qe(e.$$.fragment)},m(n,r){qe(e,n,r),t=!0},i(n){t||(re(e.$$.fragment,n),t=!0)},o(n){fe(e.$$.fragment,n),t=!1},d(n){Fe(e,n)}}}function Ui(i){let e,t,n,r,u;return t=new ur({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[10]),S(e,"class","svelte-bz0zu3"),Ie(e,"active",i[0])},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[79]),r=!0)},p(a,o){(!n||o[0]&1024)&&S(e,"title",a[10]),(!n||o[0]&1)&&Ie(e,"active",a[0])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function Sr(i){let e,t=[],n=new Map,r,u,a,o=Ti(i[13]);const g=c=>c[97].id+(c[97].address?","+c[97].address:"");for(let c=0;c{B=null}),vt()):B?(B.p(d,v),v[0]&1048576&&re(B,1)):(B=Di(d),B.c(),re(B,1),B.m(c,E)),d[20]?z?v[0]&1048576&&re(z,1):(z=zi(),z.c(),re(z,1),z.m(c,null)):z&&(yt(),fe(z,1,1,()=>{z=null}),vt()),(!O||v[0]&2)&&Ie(c,"displayable",d[1]!==""),d[6]==="button"?W?(W.p(d,v),v[0]&64&&re(W,1)):(W=Ui(d),W.c(),re(W,1),W.m(n,M)):W&&(yt(),fe(W,1,1,()=>{W=null}),vt()),l&&l.p&&(!O||v[2]&128)&&Tn(l,s,d,d[69],O?xn(s,d[69],v,null):Mn(d[69]),null);let p=k;k=h(d),k===p?~k&&m[k].p(d,v):(I&&(yt(),fe(m[p],1,1,()=>{m[p]=null}),vt()),~k?(I=m[k],I?I.p(d,v):(I=m[k]=f[k](d),I.c()),re(I,1),I.m(t,null)):I=null),(!O||v[0]&4&&C!==(C=Pt(d[2])+" svelte-bz0zu3"))&&S(t,"class",C),(!O||v[0]&38)&&Ie(t,"can-collapse",d[5]&&d[1]==="")},i(d){O||(re(P),re(u.$$.fragment,d),re(B),re(z),re(W),re(l,d),re(I),O=!0)},o(d){fe(P),fe(u.$$.fragment,d),fe(B),fe(z),fe(W),fe(l,d),fe(I),O=!1},d(d){d&&($(e),$(t)),Fe(u),i[72](null),B&&B.d(),z&&z.d(),W&&W.d(),l&&l.d(d),~k&&m[k].d(),x=!1,Ue(N)}}}function Nr(i,e,t){let n,r,u,{$$slots:a={},$$scope:o}=e;const g={continental_marine:4,country:4,major_landform:8,region:5,subregion:6,county:7,joint_municipality:8,joint_submunicipality:9,municipality:10,municipal_district:11,locality:12,neighbourhood:13,place:14,postal_code:14,road:16,poi:17,address:18,"poi.peak":15,"poi.shop":18,"poi.cafe":18,"poi.restaurant":18,"poi.aerodrome":13};let{class:c=void 0}=e,{apiKey:E=void 0}=e,{bbox:_=void 0}=e,{clearButtonTitle:M="clear"}=e,{clearOnBlur:R=!1}=e,{clearListOnPick:k=!1}=e,{keepListOpen:I=!1}=e,{collapsed:C=!1}=e,{country:O=void 0}=e,{debounceSearch:x=200}=e,{enableReverse:N="never"}=e,{errorMessage:P="Something went wrong…"}=e,{filter:B=()=>!0}=e,{flyTo:z=!0}=e,{fuzzyMatch:W=!0}=e,{language:s=void 0}=e,{limit:l=void 0}=e;const f=41415112612;let{reverseGeocodingLimit:m=f}=e,{mapController:h=void 0}=e,{minLength:d=2}=e,{noResultsMessage:v="Oops! Looks like you're trying to predict something that's not quite right. We can't seem to find what you're looking for. Maybe try double-checking your spelling or try a different search term. Keep on typing - we'll do our best to get you where you need to go!"}=e,{placeholder:p="Search"}=e,{proximity:y=[{type:"server-geolocation"}]}=e,{reverseActive:b=N==="always"}=e,{reverseButtonTitle:w="toggle reverse geocoding"}=e,{searchValue:T=""}=e,{pickedResultStyle:G="full-geometry"}=e,{showPlaceType:D="if-needed"}=e,{showResultsWhileTyping:H=!0}=e,{selectFirst:Q=!0}=e,{flyToSelected:se=!1}=e,{markerOnSelected:Z=!0}=e,{types:K=void 0}=e;const de=[];let{reverseGeocodingTypes:He=de}=e,{exhaustiveReverseGeocoding:st=!1}=e,{excludeTypes:ot=!1}=e;const Le=void 0;let{reverseGeocodingExcludeTypes:We=Le}=e,{zoom:pe=g}=e,{apiUrl:ge="https://api.maptiler.com/geocoding"}=e,{fetchParameters:ie={}}=e,{iconsBaseUrl:hn="https://cdn.maptiler.com/maptiler-geocoding-control/v2.1.7/icons/"}=e,{adjustUrlQuery:ui=()=>{}}=e,{adjustUrl:ai=()=>{}}=e;function gs(L){Pe.focus(L)}function ms(){Pe.blur()}function dn(L,le=!0,ae=!1){t(1,T=L),le?(t(15,X=-1),mn()):(pn(void 0,!ae,ae),setTimeout(()=>{Pe.focus(),Pe.select()}))}function ps(){t(13,F=void 0),t(14,U=void 0),t(15,X=-1)}function ys(){t(64,ce=[]),t(14,U=void 0)}let F,ce,U,gn="",Pe,X=-1,Ge,Zt=[],lt,ct,ht,fi,Ve=!1;const vs=new Set,tt=_i();Rn(()=>{h&&(h.setEventHandler(void 0),h.indicateReverse(!1),h.setSelectedMarker(-1),h.setFeatures(void 0,void 0,!1))});function mn(L){if(t(17,Ve=!1),ct&&(clearTimeout(ct),ct=void 0),X>-1&&F)t(14,U=F[X]),t(1,T=U.place_type[0]==="reverse"?U.place_name:U.place_name.replace(/,.*/,"")),t(19,Ge=void 0),t(64,ce=void 0),t(15,X=-1);else if(T){const le=L||!ci(T);hi(T,{exact:!0}).then(()=>{t(64,ce=F),t(14,U=void 0),le&&bs()}).catch(ae=>t(19,Ge=ae))}}function ci(L){try{return _r(L,6)}catch{return!1}}async function hi(L,{byId:le=!1,exact:ae=!1}={}){var Se,De,it;t(19,Ge=void 0),lt==null||lt.abort();const _e=new AbortController;t(20,lt=_e);try{const J=ci(L),Mt=new URL(ge+"/"+encodeURIComponent(J?J.decimalLongitude+","+J.decimalLatitude:L)+".json"),Ne=Mt.searchParams;s!==void 0&&Ne.set("language",Array.isArray(s)?s.join(","):s??"");const[mi]=(h==null?void 0:h.getCenterAndZoom())??[];let ze=(Se=!J||He===de?K:He)==null?void 0:Se.map(ve=>typeof ve=="string"?ve:mi===void 0||(ve[0]??0)<=mi&&mi<(ve[1]??1/0)?ve[2]:void 0).filter(ve=>ve!==void 0);ze&&(ze=[...new Set(ze)],Ne.set("types",ze.join(",")));const vn=!J||We===Le?ot:We;if(vn&&Ne.set("excludeTypes",String(vn)),_&&Ne.set("bbox",_.map(ve=>ve.toFixed(6)).join(",")),O&&Ne.set("country",Array.isArray(O)?O.join(","):O),!le&&!J){const ve=await hr(h,y,_e);ve&&Ne.set("proximity",ve),(ae||!H)&&Ne.set("autocomplete","false"),Ne.set("fuzzyMatch",String(W))}const Ct=m===f?l:m;Ct!==void 0&&Ct>1&&(ze==null?void 0:ze.length)!==1&&console.warn("For reverse geocoding when limit > 1 then types must contain single value."),J?(Ct===1||Ct!==void 0&&(st||(ze==null?void 0:ze.length)===1))&&Ne.set("limit",String(Ct)):l!==void 0&&Ne.set("limit",String(l)),E&&Ne.set("key",E),ui(Ne),ai(Mt);const Bs=Mt.searchParams.get("types")===""&&Mt.searchParams.get("excludeTypes")!=="true",Ht=Mt.toString();if(Ht===gn){le?(k&&t(13,F=void 0),t(14,U=Zt[0])):(t(13,F=Zt),((De=F[X])==null?void 0:De.id)!==(r==null?void 0:r.id)&&t(15,X=-1));return}gn=Ht;let Nt;if(Bs)Nt={type:"FeatureCollection",features:[]};else{const ve=await fetch(Ht,{signal:_e.signal,...ie});if(!ve.ok)throw new Error(await ve.text());Nt=await ve.json()}tt("response",{url:Ht,featureCollection:Nt}),le?(k&&t(13,F=void 0),t(14,U=Nt.features[0]),Zt=[U]):(t(13,F=Nt.features.filter(B)),J&&F.unshift({type:"Feature",properties:{},id:"reverse_"+J.decimalLongitude+"_"+J.decimalLatitude,text:J.decimalLatitude+", "+J.decimalLongitude,place_name:J.decimalLatitude+", "+J.decimalLongitude,place_type:["reverse"],center:[J.decimalLongitude,J.decimalLatitude],bbox:[J.decimalLongitude,J.decimalLatitude,J.decimalLongitude,J.decimalLatitude],geometry:{type:"Point",coordinates:[J.decimalLongitude,J.decimalLatitude]}}),Zt=F,((it=F[X])==null?void 0:it.id)!==(r==null?void 0:r.id)&&t(15,X=-1),J&&Pe.focus())}catch(J){if(J&&typeof J=="object"&&"name"in J&&J.name==="AbortError")return;throw J}finally{_e===lt&&t(20,lt=void 0)}}function bs(){var _e;if(!(ce!=null&&ce.length)||!z)return;const L=[180,90,-180,-90],le=!ce.some(Se=>!Se.matching_text);let ae;for(const Se of ce){const De=Tt(Se);if(ae=ae===void 0?De:De===void 0?ae:Math.max(ae,De),le||!Se.matching_text)for(const it of[0,1,2,3])L[it]=Math[it<2?"min":"max"](L[it],((_e=Se.bbox)==null?void 0:_e[it])??Se.center[it%2])}h&&ce.length>0&&(U&&L[0]===L[2]&&L[1]===L[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(L),50,ae))}function di(){!U||!h||(!U.bbox||U.bbox[0]===U.bbox[2]&&U.bbox[1]===U.bbox[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(U.bbox),50,Tt(U)))}function Tt(L){var ae;if(!L.bbox||L.bbox[0]!==L.bbox[2]&&L.bbox[1]!==L.bbox[3])return;const le=L.id.replace(/\..*/,"");return(Array.isArray((ae=L.properties)==null?void 0:ae.categories)?L.properties.categories.reduce((_e,Se)=>{const De=pe[le+"."+Se];return _e===void 0?De:De===void 0?_e:Math.max(_e,De)},void 0):void 0)??pe[le]}function ws(L){t(0,b=N==="always"),t(13,F=void 0),t(14,U=void 0),t(15,X=-1),dn(L[1].toFixed(6)+", "+cr(L[0],[-180,180],!0).toFixed(6),!1,!0)}function Es(L){if(!F)return;let le=L.key==="ArrowDown"?1:L.key==="ArrowUp"?-1:0;le&&(Pe.focus(),t(17,Ve=!0),L.preventDefault(),U&&X===-1&&t(15,X=F.findIndex(ae=>ae.id===(U==null?void 0:U.id))),X===(U||Q?0:-1)&&le===-1&&t(15,X=F.length),t(15,X+=le),X>=F.length&&t(15,X=-1),X<0&&(U||Q)&&t(15,X=0))}function pn(L,le=!0,ae=!1){if(t(19,Ge=void 0),t(14,U=void 0),t(17,Ve=!0),H||ae){if(ct&&clearTimeout(ct),T.length{hi(_e).catch(Se=>t(19,Ge=Se))},le?x:0)}else t(13,F=void 0),t(19,Ge=void 0)}function gi(L){U&&(U==null?void 0:U.id)===(L==null?void 0:L.id)?di():(t(14,U=L),t(1,T=L.place_name))}function yn(L){t(15,X=L)}function Ls(){(!Q||U)&&t(15,X=-1),se&&di()}const _s=()=>Pe.focus();function Ss(L){Yt[L?"unshift":"push"](()=>{Pe=L,t(18,Pe)})}function xs(){T=this.value,t(1,T),t(17,Ve),t(31,R),t(16,ht)}const Ts=()=>t(17,Ve=!0),Ms=()=>t(17,Ve=!1),Cs=()=>t(17,Ve=!0),Ns=()=>t(14,U=void 0),ks=()=>{t(1,T=""),t(14,U=void 0),Pe.focus()},Os=()=>t(0,b=!b),Rs=()=>t(19,Ge=void 0),Ps=L=>yn(L),Is=L=>gi(L),As=()=>{};return i.$$set=L=>{"class"in L&&t(2,c=L.class),"apiKey"in L&&t(29,E=L.apiKey),"bbox"in L&&t(30,_=L.bbox),"clearButtonTitle"in L&&t(3,M=L.clearButtonTitle),"clearOnBlur"in L&&t(31,R=L.clearOnBlur),"clearListOnPick"in L&&t(32,k=L.clearListOnPick),"keepListOpen"in L&&t(4,I=L.keepListOpen),"collapsed"in L&&t(5,C=L.collapsed),"country"in L&&t(33,O=L.country),"debounceSearch"in L&&t(34,x=L.debounceSearch),"enableReverse"in L&&t(6,N=L.enableReverse),"errorMessage"in L&&t(7,P=L.errorMessage),"filter"in L&&t(35,B=L.filter),"flyTo"in L&&t(36,z=L.flyTo),"fuzzyMatch"in L&&t(37,W=L.fuzzyMatch),"language"in L&&t(38,s=L.language),"limit"in L&&t(39,l=L.limit),"reverseGeocodingLimit"in L&&t(40,m=L.reverseGeocodingLimit),"mapController"in L&&t(41,h=L.mapController),"minLength"in L&&t(42,d=L.minLength),"noResultsMessage"in L&&t(8,v=L.noResultsMessage),"placeholder"in L&&t(9,p=L.placeholder),"proximity"in L&&t(43,y=L.proximity),"reverseActive"in L&&t(0,b=L.reverseActive),"reverseButtonTitle"in L&&t(10,w=L.reverseButtonTitle),"searchValue"in L&&t(1,T=L.searchValue),"pickedResultStyle"in L&&t(44,G=L.pickedResultStyle),"showPlaceType"in L&&t(11,D=L.showPlaceType),"showResultsWhileTyping"in L&&t(45,H=L.showResultsWhileTyping),"selectFirst"in L&&t(46,Q=L.selectFirst),"flyToSelected"in L&&t(47,se=L.flyToSelected),"markerOnSelected"in L&&t(48,Z=L.markerOnSelected),"types"in L&&t(49,K=L.types),"reverseGeocodingTypes"in L&&t(50,He=L.reverseGeocodingTypes),"exhaustiveReverseGeocoding"in L&&t(51,st=L.exhaustiveReverseGeocoding),"excludeTypes"in L&&t(52,ot=L.excludeTypes),"reverseGeocodingExcludeTypes"in L&&t(53,We=L.reverseGeocodingExcludeTypes),"zoom"in L&&t(54,pe=L.zoom),"apiUrl"in L&&t(55,ge=L.apiUrl),"fetchParameters"in L&&t(56,ie=L.fetchParameters),"iconsBaseUrl"in L&&t(12,hn=L.iconsBaseUrl),"adjustUrlQuery"in L&&t(57,ui=L.adjustUrlQuery),"adjustUrl"in L&&t(58,ai=L.adjustUrl),"$$scope"in L&&t(69,o=L.$$scope)},i.$$.update=()=>{if(i.$$.dirty[0]&64&&t(0,b=N==="always"),i.$$.dirty[0]&16384|i.$$.dirty[1]&8192&&G!=="marker-only"&&U&&!U.address&&U.geometry.type==="Point"&&U.place_type[0]!=="reverse"&&hi(U.id,{byId:!0}).catch(L=>t(19,Ge=L)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1058|i.$$.dirty[2]&8&&(h&&U&&U.id!==fi&&z&&(di(),k&&t(13,F=void 0),t(64,ce=void 0),t(15,X=-1)),t(65,fi=U==null?void 0:U.id)),i.$$.dirty[0]&196608|i.$$.dirty[1]&1&&setTimeout(()=>{t(16,ht=Ve),R&&!ht&&t(1,T="")}),i.$$.dirty[0]&8194|i.$$.dirty[1]&2048&&T.length{switch(L.type){case"mapClick":b&&ws(L.coordinates);break;case"markerClick":{const le=F==null?void 0:F.find(ae=>ae.id===L.id);le&&gi(le)}break;case"markerMouseEnter":ce&&t(15,X=ht?(F==null?void 0:F.findIndex(le=>le.id===L.id))??-1:-1);break;case"markerMouseLeave":ce&&t(15,X=-1);break}}),i.$$.dirty[0]&40960&&t(66,r=F==null?void 0:F[X]),i.$$.dirty[1]&66592|i.$$.dirty[2]&16&&h&&r&&z&&se&&h.flyTo(r.center,Tt(r)),i.$$.dirty[1]&8192&&t(68,n=G==="full-geometry-including-polygon-center-marker"),i.$$.dirty[1]&132096|i.$$.dirty[2]&64&&(Z||h==null||h.setFeatures(void 0,void 0,n)),i.$$.dirty[0]&16384|i.$$.dirty[1]&132096|i.$$.dirty[2]&84&&h&&Z&&!ce&&(h.setFeatures(r?[r]:void 0,U,n),h.setSelectedMarker(r?0:-1)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1024|i.$$.dirty[2]&68&&h&&h.setFeatures(ce,U,n),i.$$.dirty[0]&32768|i.$$.dirty[1]&1024|i.$$.dirty[2]&4&&ce&&h&&h.setSelectedMarker(X),i.$$.dirty[0]&2|i.$$.dirty[1]&1024&&h){const L=ci(T);h.setReverseMarker(L?[L.decimalLongitude,L.decimalLatitude]:void 0)}i.$$.dirty[2]&16&&tt("select",{feature:r}),i.$$.dirty[0]&16384&&tt("pick",{feature:U}),i.$$.dirty[0]&73744&&t(67,u=!!(F!=null&&F.length)&&(ht||I)),i.$$.dirty[2]&32&&tt("optionsvisibilitychange",{optionsVisible:u}),i.$$.dirty[0]&8192&&tt("featureslisted",{features:F}),i.$$.dirty[2]&4&&tt("featuresmarked",{features:ce}),i.$$.dirty[0]&1&&tt("reversetoggle",{reverse:b}),i.$$.dirty[0]&2&&tt("querychange",{query:T}),i.$$.dirty[0]&1|i.$$.dirty[1]&1024&&h&&h.indicateReverse(b)},[b,T,c,M,I,C,N,P,v,p,w,D,hn,F,U,X,ht,Ve,Pe,Ge,lt,vs,mn,Es,pn,gi,yn,Ls,g,E,_,R,k,O,x,B,z,W,s,l,m,h,d,y,G,H,Q,se,Z,K,He,st,ot,We,pe,ge,ie,ui,ai,gs,ms,dn,ps,ys,ce,fi,r,u,n,o,a,_s,Ss,xs,Ts,Ms,Cs,Ns,ks,Os,Rs,Ps,Is,As]}let kr=class extends Je{constructor(e){super(),Xe(this,e,Nr,Cr,Ke,{ZOOM_DEFAULTS:28,class:2,apiKey:29,bbox:30,clearButtonTitle:3,clearOnBlur:31,clearListOnPick:32,keepListOpen:4,collapsed:5,country:33,debounceSearch:34,enableReverse:6,errorMessage:7,filter:35,flyTo:36,fuzzyMatch:37,language:38,limit:39,reverseGeocodingLimit:40,mapController:41,minLength:42,noResultsMessage:8,placeholder:9,proximity:43,reverseActive:0,reverseButtonTitle:10,searchValue:1,pickedResultStyle:44,showPlaceType:11,showResultsWhileTyping:45,selectFirst:46,flyToSelected:47,markerOnSelected:48,types:49,reverseGeocodingTypes:50,exhaustiveReverseGeocoding:51,excludeTypes:52,reverseGeocodingExcludeTypes:53,zoom:54,apiUrl:55,fetchParameters:56,iconsBaseUrl:12,adjustUrlQuery:57,adjustUrl:58,focus:59,blur:60,setQuery:61,clearList:62,clearMap:63},null,[-1,-1,-1,-1])}get ZOOM_DEFAULTS(){return this.$$.ctx[28]}get focus(){return this.$$.ctx[59]}get blur(){return this.$$.ctx[60]}get setQuery(){return this.$$.ctx[61]}get clearList(){return this.$$.ctx[62]}get clearMap(){return this.$$.ctx[63]}};function Et(i,e,t={}){const n={type:"Feature"};return(t.id===0||t.id)&&(n.id=t.id),t.bbox&&(n.bbox=t.bbox),n.properties=e||{},n.geometry=i,n}function ti(i,e,t={}){for(const r of i){if(r.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(r[r.length-1].length!==r[0].length)throw new Error("First and last Position are not equivalent.");for(let u=0;u_?w.c=w.e=null:s.e=10;v/=10,d++);d>_?w.c=w.e=null:(w.e=d,w.c=[s]);return}b=String(s)}else{if(!Or.test(b=String(s)))return n(w,b,p);w.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(v=b.search(/e/i))>0?(d<0&&(d=v),d+=+b.slice(v+1),b=b.substring(0,v)):d<0&&(d=b.length)}else{if(oe(l,2,C.length,"Base"),l==10&&O)return w=new x(s),z(w,a+w.e+1,o);if(b=String(s),p=typeof s=="number"){if(s*0!=0)return n(w,b,p,l);if(w.s=1/s<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(ji+s)}else w.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(f=C.slice(0,l),d=v=0,y=b.length;vd){d=y;continue}}else if(!h&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){h=!0,v=-1,d=0;continue}return n(w,String(s),p,l)}p=!1,b=t(b,l,10,w.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(v=0;b.charCodeAt(v)===48;v++);for(y=b.length;b.charCodeAt(--y)===48;);if(b=b.slice(v,++y)){if(y-=v,p&&x.DEBUG&&y>15&&(s>Zi||s!==Te(s)))throw Error(ji+w.s*s);if((d=d-v-1)>_)w.c=w.e=null;else if(d=-1e9&&h<=Ee&&h===Te(h)){if(m[0]===0){if(h===0&&m.length===1)return!0;break e}if(l=(h+1)%q,l<1&&(l+=q),String(m[0]).length==l){for(l=0;l=Re||f!==Te(f))break e;if(f!==0)return!0}}}else if(m===null&&h===null&&(d===null||d===1||d===-1))return!0;throw Error(be+"Invalid BigNumber: "+s)},x.maximum=x.max=function(){return P(arguments,-1)},x.minimum=x.min=function(){return P(arguments,1)},x.random=function(){var s=9007199254740992,l=Math.random()*s&2097151?function(){return Te(Math.random()*s)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(f){var m,h,d,v,p,y=0,b=[],w=new x(u);if(f==null?f=a:oe(f,0,Ee),v=ii(f/q),M)if(crypto.getRandomValues){for(m=crypto.getRandomValues(new Uint32Array(v*=2));y>>11),p>=9e15?(h=crypto.getRandomValues(new Uint32Array(2)),m[y]=h[0],m[y+1]=h[1]):(b.push(p%1e14),y+=2);y=v/2}else if(crypto.randomBytes){for(m=crypto.randomBytes(v*=7);y=9e15?crypto.randomBytes(7).copy(m,y):(b.push(p%1e14),y+=7);y=v/7}else throw M=!1,Error(be+"crypto unavailable");if(!M)for(;y=10;p/=10,y++);yh-1&&(p[v+1]==null&&(p[v+1]=0),p[v+1]+=p[v]/h|0,p[v]%=h)}return p.reverse()}return function(f,m,h,d,v){var p,y,b,w,T,G,D,H,Q=f.indexOf("."),se=a,Z=o;for(Q>=0&&(w=k,k=0,f=f.replace(".",""),H=new x(m),G=H.pow(f.length-Q),k=w,H.c=l(je(Ce(G.c),G.e,"0"),10,h,s),H.e=H.c.length),D=l(f,m,h,v?(p=C,s):(p=s,C)),b=w=D.length;D[--w]==0;D.pop());if(!D[0])return p.charAt(0);if(Q<0?--b:(G.c=D,G.e=b,G.s=d,G=e(G,H,se,Z,h),D=G.c,T=G.r,b=G.e),y=b+se+1,Q=D[y],w=h/2,T=T||y<0||D[y+1]!=null,T=Z<4?(Q!=null||T)&&(Z==0||Z==(G.s<0?3:2)):Q>w||Q==w&&(Z==4||T||Z==6&&D[y-1]&1||Z==(G.s<0?8:7)),y<1||!D[0])f=T?je(p.charAt(1),-se,p.charAt(0)):p.charAt(0);else{if(D.length=y,T)for(--h;++D[--y]>h;)D[y]=0,y||(++b,D=[1].concat(D));for(w=D.length;!D[--w];);for(Q=0,f="";Q<=w;f+=p.charAt(D[Q++]));f=je(f,b,p.charAt(0))}return f}}(),e=function(){function s(m,h,d){var v,p,y,b,w=0,T=m.length,G=h%$e,D=h/$e|0;for(m=m.slice();T--;)y=m[T]%$e,b=m[T]/$e|0,v=D*y+b*G,p=G*y+v%$e*$e+w,w=(p/d|0)+(v/$e|0)+D*b,m[T]=p%d;return w&&(m=[w].concat(m)),m}function l(m,h,d,v){var p,y;if(d!=v)y=d>v?1:-1;else for(p=y=0;ph[p]?1:-1;break}return y}function f(m,h,d,v){for(var p=0;d--;)m[d]-=p,p=m[d]1;m.splice(0,1));}return function(m,h,d,v,p){var y,b,w,T,G,D,H,Q,se,Z,K,de,He,st,ot,Le,We,pe=m.s==h.s?1:-1,ge=m.c,ie=h.c;if(!ge||!ge[0]||!ie||!ie[0])return new x(!m.s||!h.s||(ge?ie&&ge[0]==ie[0]:!ie)?NaN:ge&&ge[0]==0||!ie?pe*0:pe/0);for(Q=new x(pe),se=Q.c=[],b=m.e-h.e,pe=d+b+1,p||(p=Re,b=Me(m.e/q)-Me(h.e/q),pe=pe/q|0),w=0;ie[w]==(ge[w]||0);w++);if(ie[w]>(ge[w]||0)&&b--,pe<0)se.push(1),T=!0;else{for(st=ge.length,Le=ie.length,w=0,pe+=2,G=Te(p/(ie[0]+1)),G>1&&(ie=s(ie,G,p),ge=s(ge,G,p),Le=ie.length,st=ge.length),He=Le,Z=ge.slice(0,Le),K=Z.length;K=p/2&&ot++;do{if(G=0,y=l(ie,Z,Le,K),y<0){if(de=Z[0],Le!=K&&(de=de*p+(Z[1]||0)),G=Te(de/ot),G>1)for(G>=p&&(G=p-1),D=s(ie,G,p),H=D.length,K=Z.length;l(D,Z,H,K)==1;)G--,f(D,Le=10;pe/=10,w++);z(Q,d+(Q.e=w+b*q-1)+1,v,T)}else Q.e=b,Q.r=+T;return Q}}();function N(s,l,f,m){var h,d,v,p,y;if(f==null?f=o:oe(f,0,8),!s.c)return s.toString();if(h=s.c[0],v=s.e,l==null)y=Ce(s.c),y=m==1||m==2&&(v<=g||v>=c)?Gt(y,v):je(y,v,"0");else if(s=z(new x(s),l,f),d=s.e,y=Ce(s.c),p=y.length,m==1||m==2&&(l<=d||d<=g)){for(;pp){if(--l>0)for(y+=".";l--;y+="0");}else if(l+=d-p,l>0)for(d+1==p&&(y+=".");l--;y+="0");return s.s<0&&h?"-"+y:y}function P(s,l){for(var f,m,h=1,d=new x(s[0]);h=10;h/=10,m++);return(f=m+f*q-1)>_?s.c=s.e=null:f=10;p/=10,h++);if(d=l-h,d<0)d+=q,v=l,y=T[b=0],w=Te(y/G[h-v-1]%10);else if(b=ii((d+1)/q),b>=T.length)if(m){for(;T.length<=b;T.push(0));y=w=0,h=1,d%=q,v=d-q+1}else break e;else{for(y=p=T[b],h=1;p>=10;p/=10,h++);d%=q,v=d-q+h,w=v<0?0:Te(y/G[h-v-1]%10)}if(m=m||l<0||T[b+1]!=null||(v<0?y:y%G[h-v-1]),m=f<4?(w||m)&&(f==0||f==(s.s<0?3:2)):w>5||w==5&&(f==4||m||f==6&&(d>0?v>0?y/G[h-v]:0:T[b-1])%10&1||f==(s.s<0?8:7)),l<1||!T[0])return T.length=0,m?(l-=s.e+1,T[0]=G[(q-l%q)%q],s.e=-l||0):T[0]=s.e=0,s;if(d==0?(T.length=b,p=1,b--):(T.length=b+1,p=G[q-d],T[b]=v>0?Te(y/G[h-v]%G[v])*p:0),m)for(;;)if(b==0){for(d=1,v=T[0];v>=10;v/=10,d++);for(v=T[0]+=p,p=1;v>=10;v/=10,p++);d!=p&&(s.e++,T[0]==Re&&(T[0]=1));break}else{if(T[b]+=p,T[b]!=Re)break;T[b--]=0,p=1}for(d=T.length;T[--d]===0;T.pop());}s.e>_?s.c=s.e=null:s.e=c?Gt(l,f):je(l,f,"0"),s.s<0?"-"+l:l)}return r.absoluteValue=r.abs=function(){var s=new x(this);return s.s<0&&(s.s=1),s},r.comparedTo=function(s,l){return rt(this,new x(s,l))},r.decimalPlaces=r.dp=function(s,l){var f,m,h,d=this;if(s!=null)return oe(s,0,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s+d.e+1,l);if(!(f=d.c))return null;if(m=((h=f.length-1)-Me(this.e/q))*q,h=f[h])for(;h%10==0;h/=10,m--);return m<0&&(m=0),m},r.dividedBy=r.div=function(s,l){return e(this,new x(s,l),a,o)},r.dividedToIntegerBy=r.idiv=function(s,l){return e(this,new x(s,l),0,1)},r.exponentiatedBy=r.pow=function(s,l){var f,m,h,d,v,p,y,b,w,T=this;if(s=new x(s),s.c&&!s.isInteger())throw Error(be+"Exponent not an integer: "+W(s));if(l!=null&&(l=new x(l)),p=s.e>14,!T.c||!T.c[0]||T.c[0]==1&&!T.e&&T.c.length==1||!s.c||!s.c[0])return w=new x(Math.pow(+W(T),p?s.s*(2-Wt(s)):+W(s))),l?w.mod(l):w;if(y=s.s<0,l){if(l.c?!l.c[0]:!l.s)return new x(NaN);m=!y&&T.isInteger()&&l.isInteger(),m&&(T=T.mod(l))}else{if(s.e>9&&(T.e>0||T.e<-1||(T.e==0?T.c[0]>1||p&&T.c[1]>=24e7:T.c[0]<8e13||p&&T.c[0]<=9999975e7)))return d=T.s<0&&Wt(s)?-0:0,T.e>-1&&(d=1/d),new x(y?1/d:d);k&&(d=ii(k/q+2))}for(p?(f=new x(.5),y&&(s.s=1),b=Wt(s)):(h=Math.abs(+W(s)),b=h%2),w=new x(u);;){if(b){if(w=w.times(T),!w.c)break;d?w.c.length>d&&(w.c.length=d):m&&(w=w.mod(l))}if(h){if(h=Te(h/2),h===0)break;b=h%2}else if(s=s.times(f),z(s,s.e+1,1),s.e>14)b=Wt(s);else{if(h=+W(s),h===0)break;b=h%2}T=T.times(T),d?T.c&&T.c.length>d&&(T.c.length=d):m&&(T=T.mod(l))}return m?w:(y&&(w=u.div(w)),l?w.mod(l):d?z(w,k,o,v):w)},r.integerValue=function(s){var l=new x(this);return s==null?s=o:oe(s,0,8),z(l,l.e+1,s)},r.isEqualTo=r.eq=function(s,l){return rt(this,new x(s,l))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(s,l){return rt(this,new x(s,l))>0},r.isGreaterThanOrEqualTo=r.gte=function(s,l){return(l=rt(this,new x(s,l)))===1||l===0},r.isInteger=function(){return!!this.c&&Me(this.e/q)>this.c.length-2},r.isLessThan=r.lt=function(s,l){return rt(this,new x(s,l))<0},r.isLessThanOrEqualTo=r.lte=function(s,l){return(l=rt(this,new x(s,l)))===-1||l===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(s,l){var f,m,h,d,v=this,p=v.s;if(s=new x(s,l),l=s.s,!p||!l)return new x(NaN);if(p!=l)return s.s=-l,v.plus(s);var y=v.e/q,b=s.e/q,w=v.c,T=s.c;if(!y||!b){if(!w||!T)return w?(s.s=-l,s):new x(T?v:NaN);if(!w[0]||!T[0])return T[0]?(s.s=-l,s):new x(w[0]?v:o==3?-0:0)}if(y=Me(y),b=Me(b),w=w.slice(),p=y-b){for((d=p<0)?(p=-p,h=w):(b=y,h=T),h.reverse(),l=p;l--;h.push(0));h.reverse()}else for(m=(d=(p=w.length)<(l=T.length))?p:l,p=l=0;l0)for(;l--;w[f++]=0);for(l=Re-1;m>p;){if(w[--m]=0;){for(f=0,G=de[h]%se,D=de[h]/se|0,v=y,d=h+v;d>h;)b=K[--v]%se,w=K[v]/se|0,p=D*b+w*G,b=G*b+p%se*se+H[d]+f,f=(b/Q|0)+(p/se|0)+D*w,H[d--]=b%Q;H[d]=f}return f?++m:H.splice(0,1),B(s,H,m)},r.negated=function(){var s=new x(this);return s.s=-s.s||null,s},r.plus=function(s,l){var f,m=this,h=m.s;if(s=new x(s,l),l=s.s,!h||!l)return new x(NaN);if(h!=l)return s.s=-l,m.minus(s);var d=m.e/q,v=s.e/q,p=m.c,y=s.c;if(!d||!v){if(!p||!y)return new x(h/0);if(!p[0]||!y[0])return y[0]?s:new x(p[0]?m:h*0)}if(d=Me(d),v=Me(v),p=p.slice(),h=d-v){for(h>0?(v=d,f=y):(h=-h,f=p),f.reverse();h--;f.push(0));f.reverse()}for(h=p.length,l=y.length,h-l<0&&(f=y,y=p,p=f,l=h),h=0;l;)h=(p[--l]=p[l]+y[l]+h)/Re|0,p[l]=Re===p[l]?0:p[l]%Re;return h&&(p=[h].concat(p),++v),B(s,p,v)},r.precision=r.sd=function(s,l){var f,m,h,d=this;if(s!=null&&s!==!!s)return oe(s,1,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s,l);if(!(f=d.c))return null;if(h=f.length-1,m=h*q+1,h=f[h]){for(;h%10==0;h/=10,m--);for(h=f[0];h>=10;h/=10,m++);}return s&&d.e+1>m&&(m=d.e+1),m},r.shiftedBy=function(s){return oe(s,-9007199254740991,Zi),this.times("1e"+s)},r.squareRoot=r.sqrt=function(){var s,l,f,m,h,d=this,v=d.c,p=d.s,y=d.e,b=a+4,w=new x("0.5");if(p!==1||!v||!v[0])return new x(!p||p<0&&(!v||v[0])?NaN:v?d:1/0);if(p=Math.sqrt(+W(d)),p==0||p==1/0?(l=Ce(v),(l.length+y)%2==0&&(l+="0"),p=Math.sqrt(+l),y=Me((y+1)/2)-(y<0||y%2),p==1/0?l="5e"+y:(l=p.toExponential(),l=l.slice(0,l.indexOf("e")+1)+y),f=new x(l)):f=new x(p+""),f.c[0]){for(y=f.e,p=y+b,p<3&&(p=0);;)if(h=f,f=w.times(h.plus(e(d,h,b,1))),Ce(h.c).slice(0,p)===(l=Ce(f.c)).slice(0,p))if(f.e0&&H>0){for(d=H%p||p,w=D.substr(0,d);d0&&(w+=b+D.slice(d)),G&&(w="-"+w)}m=T?w+(f.decimalSeparator||"")+((y=+f.fractionGroupSize)?T.replace(new RegExp("\\d{"+y+"}\\B","g"),"$&"+(f.fractionGroupSeparator||"")):T):w}return(f.prefix||"")+m+(f.suffix||"")},r.toFraction=function(s){var l,f,m,h,d,v,p,y,b,w,T,G,D=this,H=D.c;if(s!=null&&(p=new x(s),!p.isInteger()&&(p.c||p.s!==1)||p.lt(u)))throw Error(be+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+W(p));if(!H)return new x(D);for(l=new x(u),b=f=new x(u),m=y=new x(u),G=Ce(H),d=l.e=G.length-D.e-1,l.c[0]=ni[(v=d%q)<0?q+v:v],s=!s||p.comparedTo(l)>0?d>0?l:b:p,v=_,_=1/0,p=new x(G),y.c[0]=0;w=e(p,l,0,1),h=f.plus(w.times(m)),h.comparedTo(s)!=1;)f=m,m=h,b=y.plus(w.times(h=b)),y=h,l=p.minus(w.times(h=l)),p=h;return h=e(s.minus(f),m,0,1),y=y.plus(h.times(b)),f=f.plus(h.times(m)),y.s=b.s=D.s,d=d*2,T=e(b,m,d,o).minus(D).abs().comparedTo(e(y,f,d,o).minus(D).abs())<1?[b,m]:[y,f],_=v,T},r.toNumber=function(){return+W(this)},r.toPrecision=function(s,l){return s!=null&&oe(s,1,Ee),N(this,s,l,2)},r.toString=function(s){var l,f=this,m=f.s,h=f.e;return h===null?m?(l="Infinity",m<0&&(l="-"+l)):l="NaN":(s==null?l=h<=g||h>=c?Gt(Ce(f.c),h):je(Ce(f.c),h,"0"):s===10&&O?(f=z(new x(f),a+h+1,o),l=je(Ce(f.c),f.e,"0")):(oe(s,2,C.length,"Base"),l=t(je(Ce(f.c),h,"0"),10,s,m,!0)),m<0&&f.c[0]&&(l="-"+l)),l},r.valueOf=r.toJSON=function(){return W(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,i!=null&&x.set(i),x}function Me(i){var e=i|0;return i>0||i===e?e:e-1}function Ce(i){for(var e,t,n=1,r=i.length,u=i[0]+"";nc^t?1:-1;for(o=(g=r.length)<(c=u.length)?g:c,a=0;au[a]^t?1:-1;return g==c?0:g>c^t?1:-1}function oe(i,e,t,n){if(it||i!==Te(i))throw Error(be+(n||"Argument")+(typeof i=="number"?it?" out of range: ":" not an integer: ":" not a primitive number: ")+String(i))}function Wt(i){var e=i.c.length-1;return Me(i.e/q)==e&&i.c[e]%2!=0}function Gt(i,e){return(i.length>1?i.charAt(0)+"."+i.slice(1):i)+(e<0?"e":"e+")+e}function je(i,e,t){var n,r;if(e<0){for(r=t+".";++e;r+=t);i=r+i}else if(n=i.length,++e>n){for(r=t,e-=n;--e;r+=t);i+=r}else e0){let c=a.left;if(c==null||(g=o(c.key,i),g>0&&(a.left=c.right,c.right=a,a=c,c=a.left,c==null)))break;t==null?n=a:t.left=a,t=a,a=c}else if(g<0){let c=a.right;if(c==null||(g=o(c.key,i),g<0&&(a.right=c.left,c.left=a,a=c,c=a.right,c==null)))break;r==null?u=a:r.right=a,r=a,a=c}else break;return r!=null&&(r.right=a.left,a.left=u),t!=null&&(t.left=a.right,a.right=n),this.root!==a&&(this.root=a,this.splayCount++),g}splayMin(i){let e=i,t=e.left;for(;t!=null;){const n=t;e.left=n.right,n.right=e,e=n,t=e.left}return e}splayMax(i){let e=i,t=e.right;for(;t!=null;){const n=t;e.right=n.left,n.left=e,e=n,t=e.right}return e}_delete(i){if(this.root==null||this.splay(i)!=0)return null;let t=this.root;const n=t,r=t.left;if(this.size--,r==null)this.root=t.right;else{const u=t.right;t=this.splayMax(r),t.right=u,this.root=t}return this.modificationCount++,n}addNewRoot(i,e){this.size++,this.modificationCount++;const t=this.root;if(t==null){this.root=i;return}e<0?(i.left=t,i.right=t.right,t.right=null):(i.right=t,i.left=t.left,t.left=null),this.root=i}_first(){const i=this.root;return i==null?null:(this.root=this.splayMin(i),this.root)}_last(){const i=this.root;return i==null?null:(this.root=this.splayMax(i),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(i){return this.validKey(i)&&this.splay(i)==0}defaultCompare(){return(i,e)=>ie?1:0}wrap(){return{getRoot:()=>this.root,setRoot:i=>{this.root=i},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:i=>{this.splayCount=i},splay:i=>this.splay(i),has:i=>this.has(i)}}},Dt=class Ot extends Pr{constructor(t,n){super();A(this,"root",null);A(this,"compare");A(this,"validKey");A(this,fn,"[object Set]");this.compare=t??this.defaultCompare(),this.validKey=n??(r=>r!=null&&r!=null)}delete(t){return this.validKey(t)?this._delete(t)!=null:!1}deleteAll(t){for(const n of t)this.delete(n)}forEach(t){const n=this[Symbol.iterator]();let r;for(;r=n.next(),!r.done;)t(r.value,r.value,this)}add(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this}addAndReturn(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this.root.key}addAll(t){for(const n of t)this.add(n)}isEmpty(){return this.root==null}isNotEmpty(){return this.root!=null}single(){if(this.size==0)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(this.size==0)throw"Bad state: No element";return this._first().key}last(){if(this.size==0)throw"Bad state: No element";return this._last().key}lastBefore(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)<0)return this.root.key;let r=this.root.left;if(r==null)return null;let u=r.right;for(;u!=null;)r=u,u=r.right;return r.key}firstAfter(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)>0)return this.root.key;let r=this.root.right;if(r==null)return null;let u=r.left;for(;u!=null;)r=u,u=r.left;return r.key}retainAll(t){const n=new Ot(this.compare,this.validKey),r=this.modificationCount;for(const u of t){if(r!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(u)&&this.splay(u)==0&&n.add(this.root.key)}n.size!=this.size&&(this.root=n.root,this.size=n.size,this.modificationCount++)}lookup(t){return!this.validKey(t)||this.splay(t)!=0?null:this.root.key}intersection(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)&&n.add(r);return n}difference(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)||n.add(r);return n}union(t){const n=this.clone();return n.addAll(t),n}clone(){const t=new Ot(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(t){if(t==null)return null;function n(u,a){let o,g;do{if(o=u.left,g=u.right,o!=null){const c=new _t(o.key);a.left=c,n(o,c)}if(g!=null){const c=new _t(g.key);a.right=c,u=g,a=c}}while(g!=null)}const r=new _t(t.key);return n(t,r),r}toSet(){return this.clone()}entries(){return new Ar(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[(cn=Symbol.iterator,fn=Symbol.toStringTag,cn)](){return new Ir(this.wrap())}},Vi=class{constructor(i){A(this,"tree");A(this,"path",new Array);A(this,"modificationCount",null);A(this,"splayCount");this.tree=i,this.splayCount=i.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const i=this.path[this.path.length-1];return this.getValue(i)}rebuildPath(i){this.path.splice(0,this.path.length),this.tree.splay(i),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(i){for(;i!=null;)this.path.push(i),i=i.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(this.modificationCount==null){this.modificationCount=this.tree.getModificationCount();let t=this.tree.getRoot();for(;t!=null;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let i=this.path[this.path.length-1],e=i.right;if(e!=null){for(;e!=null;)this.path.push(e),e=e.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===i;)i=this.path.pop();return this.path.length>0}},Ir=class extends Vi{getValue(i){return i.key}},Ar=class extends Vi{getValue(i){return[i.key,i.key]}},Ki=i=>()=>i,ri=i=>{const e=i?(t,n)=>n.minus(t).abs().isLessThanOrEqualTo(i):Ki(!1);return(t,n)=>e(t,n)?0:t.comparedTo(n)};function Br(i){const e=i?(t,n,r,u,a)=>t.exponentiatedBy(2).isLessThanOrEqualTo(u.minus(n).exponentiatedBy(2).plus(a.minus(r).exponentiatedBy(2)).times(i)):Ki(!1);return(t,n,r)=>{const u=t.x,a=t.y,o=r.x,g=r.y,c=a.minus(g).times(n.x.minus(o)).minus(u.minus(o).times(n.y.minus(g)));return e(c,u,a,o,g)?0:c.comparedTo(0)}}var Wr=i=>i,Gr=i=>{if(i){const e=new Dt(ri(i)),t=new Dt(ri(i)),n=(u,a)=>a.addAndReturn(u),r=u=>({x:n(u.x,e),y:n(u.y,t)});return r({x:new Ae(0),y:new Ae(0)}),r}return Wr},si=i=>({set:e=>{Ze=si(e)},reset:()=>si(i),compare:ri(i),snap:Gr(i),orient:Br(i)}),Ze=si(),St=(i,e)=>i.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(i.ur.x)&&i.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(i.ur.y),oi=(i,e)=>{if(e.ur.x.isLessThan(i.ll.x)||i.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(i.ll.y)||i.ur.y.isLessThan(e.ll.y))return null;const t=i.ll.x.isLessThan(e.ll.x)?e.ll.x:i.ll.x,n=i.ur.x.isLessThan(e.ur.x)?i.ur.x:e.ur.x,r=i.ll.y.isLessThan(e.ll.y)?e.ll.y:i.ll.y,u=i.ur.y.isLessThan(e.ur.y)?i.ur.y:e.ur.y;return{ll:{x:t,y:r},ur:{x:n,y:u}}},zt=(i,e)=>i.x.times(e.y).minus(i.y.times(e.x)),Yi=(i,e)=>i.x.times(e.x).plus(i.y.times(e.y)),Ut=i=>Yi(i,i).sqrt(),Dr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return zt(r,n).div(Ut(r)).div(Ut(n))},zr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return Yi(r,n).div(Ut(r)).div(Ut(n))},Qi=(i,e,t)=>e.y.isZero()?null:{x:i.x.plus(e.x.div(e.y).times(t.minus(i.y))),y:t},Xi=(i,e,t)=>e.x.isZero()?null:{x:t,y:i.y.plus(e.y.div(e.x).times(t.minus(i.x)))},Ur=(i,e,t,n)=>{if(e.x.isZero())return Xi(t,n,i.x);if(n.x.isZero())return Xi(i,e,t.x);if(e.y.isZero())return Qi(t,n,i.y);if(n.y.isZero())return Qi(i,e,t.y);const r=zt(e,n);if(r.isZero())return null;const u={x:t.x.minus(i.x),y:t.y.minus(i.y)},a=zt(u,e).div(r),o=zt(u,n).div(r),g=i.x.plus(o.times(e.x)),c=t.x.plus(a.times(n.x)),E=i.y.plus(o.times(e.y)),_=t.y.plus(a.times(n.y)),M=g.plus(c).div(2),R=E.plus(_).div(2);return{x:M,y:R}},Be=class En{constructor(e,t){A(this,"point");A(this,"isLeft");A(this,"segment");A(this,"otherSE");A(this,"consumedBy");e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}static compare(e,t){const n=En.comparePoints(e.point,t.point);return n!==0?n:(e.point!==t.point&&e.link(t),e.isLeft!==t.isLeft?e.isLeft?1:-1:Ft.compare(e.segment,t.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let n=0,r=t.length;n{const u=r.otherSE;t.set(r,{sine:Dr(this.point,e.point,u.point),cosine:zr(this.point,e.point,u.point)})};return(r,u)=>{t.has(r)||n(r),t.has(u)||n(u);const{sine:a,cosine:o}=t.get(r),{sine:g,cosine:c}=t.get(u);return a.isGreaterThanOrEqualTo(0)&&g.isGreaterThanOrEqualTo(0)?o.isLessThan(c)?1:o.isGreaterThan(c)?-1:0:a.isLessThan(0)&&g.isLessThan(0)?o.isLessThan(c)?-1:o.isGreaterThan(c)?1:0:g.isLessThan(a)?-1:g.isGreaterThan(a)?1:0}}},qr=class pi{constructor(e){A(this,"events");A(this,"poly");A(this,"_isExteriorRing");A(this,"_enclosingRing");this.events=e;for(let t=0,n=e.length;t0&&(e=g)}let t=e.segment.prevInResult(),n=t?t.prevInResult():null;for(;;){if(!t)return null;if(!n)return t.ringOut;if(n.ringOut!==t.ringOut)return((r=n.ringOut)==null?void 0:r.enclosingRing())!==t.ringOut?t.ringOut:(u=t.ringOut)==null?void 0:u.enclosingRing();t=n.prevInResult(),n=t?t.prevInResult():null}}},Ji=class{constructor(i){A(this,"exteriorRing");A(this,"interiorRings");this.exteriorRing=i,i.poly=this,this.interiorRings=[]}addInterior(i){this.interiorRings.push(i),i.poly=this}getGeom(){const i=this.exteriorRing.getGeom();if(i===null)return null;const e=[i];for(let t=0,n=this.interiorRings.length;t0?(this.tree.delete(e),t.push(i)):(this.segments.push(e),e.prev=n)}else{if(n&&r){const u=n.getIntersection(r);if(u!==null){if(!n.isAnEndpoint(u)){const a=this._splitSafely(n,u);for(let o=0,g=a.length;o0)return-1;const M=t.comparePoint(e.rightSE.point);return M!==0?M:-1}if(n.isGreaterThan(r)){if(o.isLessThan(g)&&o.isLessThan(E))return-1;if(o.isGreaterThan(g)&&o.isGreaterThan(E))return 1;const _=t.comparePoint(e.leftSE.point);if(_!==0)return _;const M=e.comparePoint(t.rightSE.point);return M<0?1:M>0?-1:1}if(o.isLessThan(g))return-1;if(o.isGreaterThan(g))return 1;if(u.isLessThan(a)){const _=t.comparePoint(e.rightSE.point);if(_!==0)return _}if(u.isGreaterThan(a)){const _=e.comparePoint(t.rightSE.point);if(_<0)return 1;if(_>0)return-1}if(!u.eq(a)){const _=c.minus(o),M=u.minus(n),R=E.minus(g),k=a.minus(r);if(_.isGreaterThan(M)&&R.isLessThan(k))return 1;if(_.isLessThan(M)&&R.isGreaterThan(k))return-1}return u.isGreaterThan(a)?1:u.isLessThan(a)||c.isLessThan(E)?-1:c.isGreaterThan(E)?1:e.idt.id?1:0}static fromRing(e,t,n){let r,u,a;const o=Be.comparePoints(e,t);if(o<0)r=e,u=t,a=1;else if(o>0)r=t,u=e,a=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const g=new Be(r,!0),c=new Be(u,!1);return new Kt(g,c,[n],[a])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return Ze.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),n=e.bbox(),r=oi(t,n);if(r===null)return null;const u=this.leftSE.point,a=this.rightSE.point,o=e.leftSE.point,g=e.rightSE.point,c=St(t,o)&&this.comparePoint(o)===0,E=St(n,u)&&e.comparePoint(u)===0,_=St(t,g)&&this.comparePoint(g)===0,M=St(n,a)&&e.comparePoint(a)===0;if(E&&c)return M&&!_?a:!M&&_?g:null;if(E)return _&&u.x.eq(g.x)&&u.y.eq(g.y)?null:u;if(c)return M&&a.x.eq(o.x)&&a.y.eq(o.y)?null:o;if(M&&_)return null;if(M)return a;if(_)return g;const R=Ur(u,this.vector(),o,e.vector());return R===null||!St(r,R)?null:Ze.snap(R)}split(e){const t=[],n=e.events!==void 0,r=new Be(e,!0),u=new Be(e,!1),a=this.rightSE;this.replaceRightSE(u),t.push(u),t.push(r);const o=new Kt(r,a,this.rings.slice(),this.windings.slice());return Be.comparePoints(o.leftSE.point,o.rightSE.point)>0&&o.swapEvents(),Be.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(r.checkForConsuming(),u.checkForConsuming()),t}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,n=this.windings.length;t0){const u=t;t=n,n=u}if(t.prev===n){const u=t;t=n,n=u}for(let u=0,a=n.rings.length;ur.length===1&&r[0].isSubject;this._isInResult=n(e)!==n(t);break}}return this._isInResult}},$i=class{constructor(i,e,t){A(this,"poly");A(this,"isExterior");A(this,"segments");A(this,"bbox");if(!Array.isArray(i)||i.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=e,this.isExterior=t,this.segments=[],typeof i[0][0]!="number"||typeof i[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const n=Ze.snap({x:new Ae(i[0][0]),y:new Ae(i[0][1])});this.bbox={ll:{x:n.x,y:n.y},ur:{x:n.x,y:n.y}};let r=n;for(let u=1,a=i.length;uqt.run("union",i,e),Yr=(i,...e)=>qt.run("difference",i,e);Ze.set;function tn(i,e,t){if(i!==null)for(var n,r,u,a,o,g,c,E=0,_=0,M,R=i.type,k=R==="FeatureCollection",I=R==="Feature",C=k?i.features.length:1,O=0;O{t.push(r.coordinates)}),t.length<2)throw new Error("Must have at least 2 geometries");const n=Kr(t[0],...t.slice(1));return n.length===0?null:n.length===1?ti(n[0],e.properties):Fi(n,e.properties)}var nn=Xr;function Jr(i,e={}){if(i.bbox!=null&&e.recompute!==!0)return i.bbox;const t=[1/0,1/0,-1/0,-1/0];return tn(i,n=>{t[0]>n[0]&&(t[0]=n[0]),t[1]>n[1]&&(t[1]=n[1]),t[2]{e.push(r.coordinates)}),e.length<2)throw new Error("Must have at least two features");const t=i.features[0].properties||{},n=Yr(e[0],...e.slice(1));return n.length===0?null:n.length===1?ti(n[0],t):Fi(n,t)}var es=$r;function ts(i){if(!i)throw new Error("geojson is required");var e=[];return Qr(i,function(t){e.push(t)}),Lt(e)}var is=ts;function sn(i,e){const t=es(Lt([ti([[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]]),i]));if(!t)return;t.properties={isMask:!0};const n=Bt(rn(i)),r=(n[2]-n[0])/360/1e3,u=n[0]<-180,a=n[2]>180,o=is(i);if(o.features.length>1&&(u||a))for(const g of o.features){const c=Bt(rn(g));if(a&&c[0]<-180+r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]+=360-r;if(u&&c[2]>180-r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]-=360-r}e(Lt([o.features.length<2?i:nn(o)??i,t]))}const on={fill:{paint:{"fill-color":"#000","fill-opacity":.1},filter:["all",["==",["geometry-type"],"Polygon"],["has","isMask"]]},line:{layout:{"line-cap":"square"},paint:{"line-width":["case",["==",["geometry-type"],"Polygon"],2,3],"line-dasharray":[1,1],"line-color":"#3170fe"},filter:["!",["has","isMask"]]}},jt="mtlr-gc-full-geom",ln="mtlr-gc-full-geom-fill",un="mtlr-gc-full-geom-line";function an(i,e,t=!0,n=!0,r={},u={},a=on){let o;const g=[];let c,E,_;function M(){if(!i.loaded){i.once("load",M);return}const C=a?a===!0?on:a:void 0;if(!(C!=null&&C.fill)&&!(C!=null&&C.line))return;const O=i.getSource(jt);if(O)O.setData(_??Lt([]));else if(_)i.addSource(jt,{type:"geojson",data:_});else return;!i.getLayer(ln)&&(C!=null&&C.fill)&&i.addLayer({...C==null?void 0:C.fill,id:ln,type:"fill",source:jt}),!i.getLayer(un)&&(C!=null&&C.line)&&i.addLayer({...C==null?void 0:C.line,id:un,type:"line",source:jt})}function R(C){_=C,M()}i.on("styledata",()=>{setTimeout(()=>{_&&M()})});const k=C=>{o==null||o({type:"mapClick",coordinates:[C.lngLat.lng,C.lngLat.lat]})};function I(C=!1){if(!e)throw new Error;const O=document.createElement("div");return C&&O.classList.add("marker-interactive"),new or({props:{displayIn:"maplibre"},target:O}),new e.Marker({element:O,offset:[1,-13]})}return{setEventHandler(C){C?(o=C,i.on("click",k)):(o=void 0,i.off("click",k))},flyTo(C,O){i.flyTo({center:C,...O?{zoom:O}:{},...r})},fitBounds(C,O,x){i.fitBounds([[C[0],C[1]],[C[2],C[3]]],{padding:O,...x?{maxZoom:x}:{},...u})},indicateReverse(C){i.getCanvasContainer().style.cursor=C?"crosshair":""},setReverseMarker(C){!e||!t||(E?C?E.setLngLat(C):(E.remove(),E=void 0):C&&(t instanceof Function?E=t(i)??void 0:(E=(typeof t=="object"?new e.Marker(t):I()).setLngLat(C).addTo(i),E.getElement().classList.add("marker-reverse"))))},setFeatures(C,O,x){for(const N of g)N.remove();if(g.length=0,R(void 0),!!e){e:if(O){let N=!1;if(O.geometry.type==="GeometryCollection"){const P=O.geometry.geometries.filter(B=>B.type==="Polygon"||B.type==="MultiPolygon");t:if(P.length>0){const B=nn(Lt(P.map(z=>Et(z))));if(!B)break t;sn({...O,geometry:B.geometry},R),N=!0}else{const B=O.geometry.geometries.filter(z=>z.type==="LineString"||z.type==="MultiLineString");B.length>0&&(R({...O,geometry:{type:"GeometryCollection",geometries:B}}),N=!0)}}if(!N){if(O.geometry.type==="Polygon"||O.geometry.type==="MultiPolygon")sn(O,R);else if(O.geometry.type==="LineString"||O.geometry.type==="MultiLineString"){R(O);break e}}if(!x&&!O.geometry.type.endsWith("Point"))break e;if(t instanceof Function){const P=t(i,O);P&&g.push(P)}else t&&g.push(typeof t=="object"?new e.Marker(t):I().setLngLat(O.center).addTo(i))}if(n)for(const N of C??[]){if(N===O)continue;let P;if(n instanceof Function){if(P=n(i,N),!P)continue}else P=(typeof n=="object"?new e.Marker(n):I(!0)).setLngLat(N.center).setPopup(new e.Popup({offset:[1,-27],closeButton:!1,closeOnMove:!0,className:"maptiler-gc-popup"}).setText(N.place_type[0]==="reverse"?N.place_name:N.place_name.replace(/,.*/,""))).addTo(i);const B=P.getElement();B.addEventListener("click",z=>{z.stopPropagation(),o==null||o({type:"markerClick",id:N.id})}),B.addEventListener("mouseenter",()=>{o==null||o({type:"markerMouseEnter",id:N.id}),P.togglePopup()}),B.addEventListener("mouseleave",()=>{o==null||o({type:"markerMouseLeave",id:N.id}),P.togglePopup()}),g.push(P)}}},setSelectedMarker(C){c&&c.getElement().classList.toggle("marker-selected",!1),c=C>-1?g[C]:void 0,c==null||c.getElement().classList.toggle("marker-selected",!0)},getCenterAndZoom(){const C=i.getCenter();return[i.getZoom(),C.lng,C.lat]}}}function ns(i,e,t){var k,I,C;class n{constructor(x,N){A(this,"type");A(this,"target");this.type=N,this.target=x}}class r extends n{constructor(N,P){super(N,"select");A(this,"feature");Object.assign(this,P)}}class u extends n{constructor(N,P){super(N,"featureslisted");A(this,"features");this.features=P}}class a extends n{constructor(N,P){super(N,"featuresmarked");A(this,"features");this.features=P}}class o extends n{constructor(N,P){super(N,"optionsvisibilitychange");A(this,"optionsVisible");this.optionsVisible=P}}class g extends n{constructor(N,P){super(N,"pick");A(this,"feature");this.feature=P}}class c extends n{constructor(N,P){super(N,"querychange");A(this,"query");this.query=P}}class E extends n{constructor(N,P,B){super(N,"response");A(this,"url");A(this,"featureCollection");this.url=P,this.featureCollection=B}}class _ extends n{constructor(N,P){super(N,"reversetoggle");A(this,"reverse");this.reverse=P}}class M extends i{constructor(N={}){super();Vt(this,k);Vt(this,I);Vt(this,C);kt(this,I,N)}onAddInt(N){const P=document.createElement("div");P.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl mapboxgl-ctrl-group";const{marker:B,showResultMarkers:z,flyTo:W,fullGeometryStyle:s,...l}=ue(this,I),f=typeof W=="boolean"?{}:W,h={mapController:an(N,e,B,z,f,f,s),flyTo:W===void 0?!0:!!W,apiKey:"",...t==null?void 0:t(N,P),...l};return h.apiKey||console.warn("No MapTiler Cloud API key was provided, some or all geocoding requests may fail"),kt(this,k,new kr({target:P,props:h})),ue(this,k).$on("select",d=>{this.fire(new r(this,d.detail))}),ue(this,k).$on("pick",d=>{this.fire(new g(this,d.detail.feature))}),ue(this,k).$on("featureslisted",d=>{this.fire(new u(this,d.detail.features))}),ue(this,k).$on("featuresmarked",d=>{this.fire(new a(this,d.detail.features))}),ue(this,k).$on("response",d=>{this.fire(new E(this,d.detail.url,d.detail.featureCollection))}),ue(this,k).$on("optionsvisibilitychange",d=>{this.fire(new o(this,d.detail.optionsVisible))}),ue(this,k).$on("reversetoggle",d=>{this.fire(new _(this,d.detail.reverse))}),ue(this,k).$on("querychange",d=>{this.fire(new c(this,d.detail.query))}),kt(this,C,P),P}on(N,P){return super.on(N,P)}once(N,P){return super.once(N,P)}off(N,P){return super.off(N,P)}listens(N){return super.listens(N)}setOptions(N){var l;Object.assign(ue(this,I),N);const{marker:P,showResultMarkers:B,flyTo:z,fullGeometryStyle:W,...s}=ue(this,I);(l=ue(this,k))==null||l.$set(s)}setQuery(N,P=!0){var B;(B=ue(this,k))==null||B.setQuery(N,P)}clearMap(){var N;(N=ue(this,k))==null||N.clearMap()}clearList(){var N;(N=ue(this,k))==null||N.clearList()}setReverseMode(N){var P;(P=ue(this,k))==null||P.$set({reverseActive:N})}focus(N){var P;(P=ue(this,k))==null||P.focus(N)}blur(){var N;(N=ue(this,k))==null||N.blur()}onRemove(){var N,P,B;(N=ue(this,k))==null||N.$destroy(),kt(this,k,void 0),(B=(P=ue(this,C))==null?void 0:P.parentNode)==null||B.removeChild(ue(this,C))}}return k=new WeakMap,I=new WeakMap,C=new WeakMap,{MapLibreBasedGeocodingControl:M,events:{SelectEvent:r,FeaturesListedEvent:u,FeaturesMarkedEvent:a,OptionsVisibilityChangeEvent:o,PickEvent:g,QueryChangeEvent:c,ResponseEvent:E,ReverseToggleEvent:_}}}const{MapLibreBasedGeocodingControl:rs,events:et}=ns(dt.Evented,dt);class ss extends rs{onAdd(e){return super.onAddInt(e)}}const os=et.SelectEvent,ls=et.FeaturesListedEvent,us=et.FeaturesMarkedEvent,as=et.OptionsVisibilityChangeEvent,fs=et.PickEvent,cs=et.QueryChangeEvent,hs=et.ResponseEvent,ds=et.ReverseToggleEvent;j.FeaturesListedEvent=ls,j.FeaturesMarkedEvent=us,j.GeocodingControl=ss,j.OptionsVisibilityChangeEvent=as,j.PickEvent=fs,j.QueryChangeEvent=cs,j.ResponseEvent=hs,j.ReverseToggleEvent=ds,j.SelectEvent=os,j.createMapLibreGlMapController=an,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"})}); +//# sourceMappingURL=maplibregl.umd.js.map diff --git a/docs/articles/layers-overview_files/maptiler-geocoding-control-2.1.7/style.css b/docs/articles/layers-overview_files/maptiler-geocoding-control-2.1.7/style.css new file mode 100644 index 0000000..c865c17 --- /dev/null +++ b/docs/articles/layers-overview_files/maptiler-geocoding-control-2.1.7/style.css @@ -0,0 +1 @@ +svg.svelte-d2loi5{display:block;fill:#e15042}.sprite-icon.svelte-w9y5n9.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75;background-repeat:no-repeat}li.svelte-w9y5n9.svelte-w9y5n9{text-align:left;cursor:default;display:grid;grid-template-columns:40px 1fr;color:var(--color-text);padding:8px 0;font-size:14px;line-height:18px;min-width:fit-content;outline:0}li.svelte-w9y5n9.svelte-w9y5n9:first-child{padding-top:10px}li.svelte-w9y5n9.svelte-w9y5n9:last-child{padding-bottom:10px}li.picked.svelte-w9y5n9.svelte-w9y5n9{background-color:#e7edff}li.picked.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#96a4c7;padding-left:4px}li.picked.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#96a4c7}li.selected.svelte-w9y5n9.svelte-w9y5n9{background-color:#f3f6ff}li.selected.svelte-w9y5n9.svelte-w9y5n9{animation:svelte-w9y5n9-backAndForth 5s linear infinite}li.selected.svelte-w9y5n9 .primary.svelte-w9y5n9{color:#2b8bfb}li.selected.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#a2adc7;padding-left:4px}li.selected.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#a2adc7}li.svelte-w9y5n9>img.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75}.texts.svelte-w9y5n9.svelte-w9y5n9{padding:0 17px 0 0}.texts.svelte-w9y5n9>.svelte-w9y5n9{white-space:nowrap;display:block;min-width:fit-content}.primary.svelte-w9y5n9.svelte-w9y5n9{font-weight:600}.secondary.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7;padding-left:4px}.line2.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7}@keyframes svelte-w9y5n9-backAndForth{0%{transform:translate(0)}10%{transform:translate(0)}45%{transform:translate(calc(-100% + 270px))}55%{transform:translate(calc(-100% + 270px))}90%{transform:translate(0)}to{transform:translate(0)}}div.svelte-1ocfouu{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);pointer-events:none;display:flex;align-items:center}.loading-icon.svelte-1ocfouu{animation:svelte-1ocfouu-rotate .8s infinite cubic-bezier(.45,.05,.55,.95)}@keyframes svelte-1ocfouu-rotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}svg.svelte-gzo3ar.svelte-gzo3ar{display:block;fill:#6b7c93;stroke:#6b7c93}.list-icon.svelte-gzo3ar.svelte-gzo3ar{grid-row:1/3;align-self:center;margin:8px}.in-map.svelte-gzo3ar.svelte-gzo3ar{height:30px}.maplibregl-canvas-container .marker-selected{z-index:1}.maplibregl-canvas-container svg.svelte-gzo3ar path.svelte-gzo3ar,.leaflet-map-pane svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#3170fe;stroke:#3170fe}.marker-selected svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#98b7ff;stroke:#3170fe}.marker-reverse svg.svelte-gzo3ar path.svelte-gzo3ar{fill:silver;stroke:gray}.marker-interactive{cursor:pointer!important}.maptiler-gc-popup>.maplibregl-popup-content{padding:2px 8px}svg.svelte-en2qvf{display:block;fill:var(--color-icon-button)}circle.svelte-1aq105l{stroke-width:1.875;fill:none}path.svelte-1aq105l{stroke-width:1.875;stroke-linecap:round}svg.svelte-1aq105l{display:block;stroke:var(--color-icon-button)}form.svelte-bz0zu3.svelte-bz0zu3{font-family:Open Sans,Ubuntu,Helvetica Neue,Arial,Helvetica,sans-serif;position:relative;background-color:#fff;z-index:10;border-radius:4px;margin:0;transition:max-width .25s;box-shadow:0 2px 5px #33335926;--color-text:#444952;--color-icon-button:#444952}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3:after,form.svelte-bz0zu3 .svelte-bz0zu3:before{box-sizing:border-box}form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:29px}form.can-collapse.svelte-bz0zu3 input.svelte-bz0zu3::placeholder{transition:opacity .25s;opacity:0}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3.svelte-bz0zu3:focus-within,form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px}form.svelte-bz0zu3 input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:focus-within input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:hover input.svelte-bz0zu3::placeholder{opacity:1}input.svelte-bz0zu3.svelte-bz0zu3{font:inherit;font-size:14px;flex-grow:1;min-height:29px;background-color:transparent;color:#444952;white-space:nowrap;overflow:hidden;border:0;margin:0;padding:0}input.svelte-bz0zu3.svelte-bz0zu3:focus{color:#444952;outline:0;outline:none;box-shadow:none}ul.svelte-bz0zu3.svelte-bz0zu3,div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{background-color:#fff;border-radius:4px;left:0;list-style:none;margin:0;padding:0;position:absolute;width:100%;top:calc(100% + 6px);overflow:hidden}ul.svelte-bz0zu3.svelte-bz0zu3{font-size:14px;line-height:16px;box-shadow:0 5px 10px #33335926}div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{font:inherit;line-height:18px;font-size:12px;display:flex;gap:16px}div.error.svelte-bz0zu3.svelte-bz0zu3{padding:16px;font-weight:600;color:#e25041;background-color:#fbeae8}div.error.svelte-bz0zu3 div.svelte-bz0zu3{flex-grow:1}div.error.svelte-bz0zu3 svg{flex-shrink:0;width:20px;height:20px}div.error.svelte-bz0zu3 button.svelte-bz0zu3{flex-shrink:0}div.error.svelte-bz0zu3 button.svelte-bz0zu3>svg{width:13px;fill:#e25041}div.error.svelte-bz0zu3 button.svelte-bz0zu3:hover svg,div.error.svelte-bz0zu3 button.svelte-bz0zu3:active svg{fill:#444952}div.no-results.svelte-bz0zu3.svelte-bz0zu3{padding:14px 24px 14px 16px;font-weight:400;color:#6b7c93;box-shadow:0 5px 10px #33335926}div.no-results.svelte-bz0zu3 svg{margin-top:4px;flex-shrink:0;width:20px;height:20px;width:30px;height:30px}.leaflet-bottom ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-left ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-right ul.options.svelte-bz0zu3.svelte-bz0zu3{top:auto;bottom:calc(100% + 6px)}button.svelte-bz0zu3.svelte-bz0zu3{padding:0;margin:0;border:0;background-color:transparent;height:auto;width:auto}button.svelte-bz0zu3.svelte-bz0zu3:hover{background-color:transparent}button.svelte-bz0zu3:hover svg,button.svelte-bz0zu3:active svg{fill:#2b8bfb}.input-group.svelte-bz0zu3.svelte-bz0zu3{display:flex;align-items:stretch;gap:7px;padding-inline:8px;border-radius:4px;overflow:hidden}.input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{outline:#2b8bfb solid 2px}.search-button.svelte-bz0zu3.svelte-bz0zu3{flex-shrink:0}.maplibregl-ctrl-geocoder:not(.maptiler-ctrl) .search-button svg{width:12px!important;transform:translate(.5px)}.clear-button-container.svelte-bz0zu3.svelte-bz0zu3{display:flex;display:none;position:relative;align-items:stretch}.clear-button-container.displayable.svelte-bz0zu3.svelte-bz0zu3{display:flex;flex-shrink:0}.maplibregl-ctrl-geocoder{position:relative;z-index:3}.maptiler-ctrl:not(:empty){box-shadow:none}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3{padding-inline:8px;border:white solid 2px}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{border:#2b8bfb solid 2px;outline:0;outline:none}.maptiler-ctrl form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:33px}.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:focus-within,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px} diff --git a/docs/articles/layers-overview_files/radius-mode-1.0.0/radius-mode.js b/docs/articles/layers-overview_files/radius-mode-1.0.0/radius-mode.js new file mode 100644 index 0000000..2b7b5bf --- /dev/null +++ b/docs/articles/layers-overview_files/radius-mode-1.0.0/radius-mode.js @@ -0,0 +1,311 @@ +// Radius/Circle drawing mode for Mapbox GL Draw +// Creates a circle by drawing from center to edge +(function (MapboxDraw) { + const DrawLine = MapboxDraw.modes.draw_line_string; + + // Utility function to create a vertex feature + const createVertex = function (parentId, coordinates, path, selected) { + return { + type: "Feature", + properties: { + meta: "vertex", + parent: parentId, + coord_path: path, + active: selected ? "true" : "false" + }, + geometry: { + type: "Point", + coordinates: coordinates + } + }; + }; + + // Utility function to calculate distance between two points in kilometers + const calculateDistance = function (coord1, coord2) { + const lat1 = coord1[1]; + const lon1 = coord1[0]; + const lat2 = coord2[1]; + const lon2 = coord2[0]; + + const R = 6371; // Radius of the Earth in kilometers + const dLat = (lat2 - lat1) * Math.PI / 180; + const dLon = (lon2 - lon1) * Math.PI / 180; + const a = + Math.sin(dLat/2) * Math.sin(dLat/2) + + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * + Math.sin(dLon/2) * Math.sin(dLon/2); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + const distance = R * c; + + return distance; + }; + + // Utility function to create a GeoJSON circle + const createGeoJSONCircle = function (center, radiusInKm, parentId, points) { + points = points || 64; + + const coords = { + latitude: center[1], + longitude: center[0] + }; + + const km = radiusInKm; + const ret = []; + const distanceX = km / (111.32 * Math.cos((coords.latitude * Math.PI) / 180)); + const distanceY = km / 110.574; + + let theta, x, y; + for (let i = 0; i < points; i++) { + theta = (i / points) * (2 * Math.PI); + x = distanceX * Math.cos(theta); + y = distanceY * Math.sin(theta); + + ret.push([coords.longitude + x, coords.latitude + y]); + } + ret.push(ret[0]); + + return { + type: "Feature", + geometry: { + type: "Polygon", + coordinates: [ret] + }, + properties: { + parent: parentId, + meta: "radius" + } + }; + }; + + // Utility function to format distance for display + const getDisplayMeasurements = function (distanceKm) { + let metricUnits = "m"; + let metricFormat = "0,0"; + let metricMeasurement; + + let standardUnits = "feet"; + let standardFormat = "0,0"; + let standardMeasurement; + + metricMeasurement = distanceKm * 1000; // Convert to meters + if (metricMeasurement >= 1000) { + metricMeasurement = metricMeasurement / 1000; + metricUnits = "km"; + metricFormat = "0.00"; + } + + standardMeasurement = distanceKm * 1000 * 3.28084; // Convert to feet + if (standardMeasurement >= 5280) { + standardMeasurement = standardMeasurement / 5280; + standardUnits = "mi"; + standardFormat = "0.00"; + } + + // Simple number formatting (without numeral.js dependency) + const formatNumber = function(num, format) { + if (format === "0,0") { + return Math.round(num).toLocaleString(); + } else if (format === "0.00") { + return num.toFixed(2); + } + return num.toString(); + }; + + return { + metric: formatNumber(metricMeasurement, metricFormat) + " " + metricUnits, + standard: formatNumber(standardMeasurement, standardFormat) + " " + standardUnits + }; + }; + + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RadiusMode = Object.assign({}, DrawLine); + + RadiusMode.onSetup = function (opts) { + const line = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "LineString", + coordinates: [] + } + }); + + this.addFeature(line); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.activateUIButton("line"); + this.setActionableState({ trash: true }); + + return { + line: line, + currentVertexPosition: 0, + direction: "forward" + }; + }; + + RadiusMode.onClick = function (state, e) { + // This ends the drawing after the user creates a second point + if (state.currentVertexPosition === 1) { + // Update the second coordinate in place, don't add at position 0 + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + return this.changeMode("simple_select", { featureIds: [state.line.id] }); + } + + this.updateUIClasses({ mouse: "add" }); + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + + if (state.direction === "forward") { + state.currentVertexPosition += 1; + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + } else { + state.line.addCoordinate(0, e.lngLat.lng, e.lngLat.lat); + } + + return null; + }; + + RadiusMode.onMouseMove = function (state, e) { + if (state.currentVertexPosition === 1) { + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + } + }; + + // Creates the final geojson circle polygon + RadiusMode.onStop = function (state) { + doubleClickZoom.enable(this); + this.activateUIButton(); + + // Check to see if we've deleted this feature + if (this.getFeature(state.line.id) === undefined) return; + + if (state.line.isValid()) { + const lineGeoJson = state.line.toGeoJSON(); + const coords = lineGeoJson.geometry.coordinates; + + if (coords.length >= 2) { + // Calculate radius in kilometers + const radiusKm = calculateDistance(coords[0], coords[1]); + + // Create the circle polygon + const circleFeature = createGeoJSONCircle(coords[0], radiusKm, state.line.id); + + // Add radius property for reference + circleFeature.properties.radius = (radiusKm * 1000).toFixed(1); + + // Remove the meta property that was interfering + delete circleFeature.properties.meta; + delete circleFeature.properties.parent; + + // Delete the temporary line first + this.deleteFeature([state.line.id], { silent: true }); + + // Add the circle feature to the draw instance + const circleDrawFeature = this.newFeature(circleFeature); + this.addFeature(circleDrawFeature); + + this.map.fire("draw.create", { + features: [circleDrawFeature.toGeoJSON()] + }); + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + + this.changeMode("simple_select", {}, { silent: true }); + }; + + RadiusMode.toDisplayFeatures = function (state, geojson, display) { + const isActiveLine = geojson.properties.id === state.line.id; + geojson.properties.active = isActiveLine ? "true" : "false"; + + if (!isActiveLine) return display(geojson); + + // Only render the line if it has at least one real coordinate + if (geojson.geometry.coordinates.length < 2) return null; + + geojson.properties.meta = "feature"; + + // Display center vertex as a point feature + display(createVertex( + state.line.id, + geojson.geometry.coordinates[ + state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1 + ], + "" + (state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1), + false + )); + + // Display the line as it is drawn + display(geojson); + + const coords = geojson.geometry.coordinates; + if (coords.length >= 2) { + const distanceKm = calculateDistance(coords[0], coords[1]); + const displayMeasurements = getDisplayMeasurements(distanceKm); + + // Create custom feature for the current pointer position + const currentVertex = { + type: "Feature", + properties: { + meta: "currentPosition", + radiusMetric: displayMeasurements.metric, + radiusStandard: displayMeasurements.standard, + parent: state.line.id + }, + geometry: { + type: "Point", + coordinates: coords[1] + } + }; + display(currentVertex); + + // Create custom feature for radius circle + const center = coords[0]; + const circleFeature = createGeoJSONCircle(center, distanceKm, state.line.id); + display(circleFeature); + } + + return null; + }; + + RadiusMode.onTrash = function (state) { + this.deleteFeature([state.line.id], { silent: true }); + this.changeMode("simple_select"); + }; + + MapboxDraw.modes.draw_radius = RadiusMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/layers-overview_files/rectangle-mode-1.0.0/rectangle-mode.js b/docs/articles/layers-overview_files/rectangle-mode-1.0.0/rectangle-mode.js new file mode 100644 index 0000000..73af6d6 --- /dev/null +++ b/docs/articles/layers-overview_files/rectangle-mode-1.0.0/rectangle-mode.js @@ -0,0 +1,124 @@ +// Rectangle drawing mode for Mapbox GL Draw +// Adapted from https://github.com/edgespatial/mapbox-gl-draw-rectangle-mode +(function (MapboxDraw) { + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RectangleMode = { + onSetup: function (opts) { + const rectangle = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "Polygon", + coordinates: [[]] + } + }); + + this.addFeature(rectangle); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.setActionableState({ trash: true }); + + return { + rectangle: rectangle + }; + }, + + onClick: function (state, e) { + // If we have a start point and click on a different point, complete the rectangle + if (state.startPoint && + (state.startPoint[0] !== e.lngLat.lng || state.startPoint[1] !== e.lngLat.lat)) { + this.updateUIClasses({ mouse: "pointer" }); + state.endPoint = [e.lngLat.lng, e.lngLat.lat]; + this.changeMode("simple_select", { featuresId: state.rectangle.id }); + return; + } + + // Set the start point + const startPoint = [e.lngLat.lng, e.lngLat.lat]; + state.startPoint = startPoint; + }, + + onMouseMove: function (state, e) { + // Update rectangle coordinates as the mouse moves + if (state.startPoint) { + const startX = state.startPoint[0]; + const startY = state.startPoint[1]; + const endX = e.lngLat.lng; + const endY = e.lngLat.lat; + + state.rectangle.updateCoordinate("0.0", startX, startY); + state.rectangle.updateCoordinate("0.1", endX, startY); + state.rectangle.updateCoordinate("0.2", endX, endY); + state.rectangle.updateCoordinate("0.3", startX, endY); + state.rectangle.updateCoordinate("0.4", startX, startY); + } + }, + + onKeyUp: function (state, e) { + if (e.keyCode === 27) { // Escape key + return this.changeMode("simple_select"); + } + }, + + onStop: function (state) { + doubleClickZoom.enable(this); + this.updateUIClasses({ mouse: "none" }); + this.activateUIButton(); + + if (this.getFeature(state.rectangle.id) !== undefined) { + // Remove the closing coordinate (duplicate of first) + state.rectangle.removeCoordinate("0.4"); + + if (state.rectangle.isValid()) { + this.map.fire("draw.create", { + features: [state.rectangle.toGeoJSON()] + }); + } else { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select", {}, { silent: true }); + } + } + }, + + toDisplayFeatures: function (state, geojson, display) { + const isActiveRectangle = geojson.properties.id === state.rectangle.id; + geojson.properties.active = isActiveRectangle ? "true" : "false"; + + if (!isActiveRectangle) { + return display(geojson); + } + + // Only display the rectangle if we have started drawing + if (state.startPoint) { + return display(geojson); + } + }, + + onTrash: function (state) { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select"); + } + }; + + MapboxDraw.modes.draw_rectangle = RectangleMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/layers-overview_files/turf-7.2.0/turf.min.js b/docs/articles/layers-overview_files/turf-7.2.0/turf.min.js new file mode 100644 index 0000000..635896d --- /dev/null +++ b/docs/articles/layers-overview_files/turf-7.2.0/turf.min.js @@ -0,0 +1,37 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).turf={})}(this,(function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}function u(t,e,n){return(e=y(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function l(t){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},l(t)}function h(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&p(t,e)}function c(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(c=function(){return!!t})()}function f(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}function g(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function p(t,e){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},p(t,e)}function v(t,e){return n(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,o,s,a=[],u=!0,l=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);u=!0);}catch(t){l=!0,i=t}finally{try{if(!u&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw i}}return a}}(t,e)||_(t,e)||g()}function d(t){return function(t){if(Array.isArray(t))return e(t)}(t)||f(t)||_(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function m(t){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},m(t)}function _(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var x=6371008.8,E={centimeters:100*x,centimetres:100*x,degrees:360/(2*Math.PI),feet:3.28084*x,inches:39.37*x,kilometers:x/1e3,kilometres:x/1e3,meters:x,metres:x,miles:x/1609.344,millimeters:1e3*x,millimetres:1e3*x,nauticalmiles:x/1852,radians:1,yards:1.0936*x},k={acres:247105e-9,centimeters:1e4,centimetres:1e4,feet:10.763910417,hectares:1e-4,inches:1550.003100006,kilometers:1e-6,kilometres:1e-6,meters:1,metres:1,miles:386e-9,nauticalmiles:2.9155334959812285e-7,millimeters:1e6,millimetres:1e6,yards:1.195990046};function b(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={type:"Feature"};return(0===n.id||n.id)&&(r.id=n.id),n.bbox&&(r.bbox=n.bbox),r.properties=e||{},r.geometry=t,r}function w(t,e){switch(t){case"Point":return I(e).geometry;case"LineString":return L(e).geometry;case"Polygon":return S(e).geometry;case"MultiPoint":return O(e).geometry;case"MultiLineString":return T(e).geometry;case"MultiPolygon":return R(e).geometry;default:throw new Error(t+" is invalid")}}function I(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("coordinates is required");if(!Array.isArray(t))throw new Error("coordinates must be an Array");if(t.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!U(t[0])||!U(t[1]))throw new Error("coordinates must contain numbers");return b({type:"Point",coordinates:t},e,n)}function N(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return I(t,e)})),n)}function S(t,e){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=a(t);try{for(i.s();!(n=i.n()).done;){var o=n.value;if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(var s=0;s2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return S(t,e)})),n)}function L(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(t.length<2)throw new Error("coordinates must be an array of two or more positions");return b({type:"LineString",coordinates:t},e,n)}function P(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return L(t,e)})),n)}function C(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={type:"FeatureCollection"};return e.id&&(n.id=e.id),e.bbox&&(n.bbox=e.bbox),n.features=t,n}function T(t,e){return b({type:"MultiLineString",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function O(t,e){return b({type:"MultiPoint",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function R(t,e){return b({type:"MultiPolygon",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function A(t,e){return b({type:"GeometryCollection",geometries:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function D(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e&&!(e>=0))throw new Error("precision must be a positive number");var n=Math.pow(10,e||0);return Math.round(t*n)/n}function F(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t*n}function q(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t/n}function V(t,e){return Y(q(t,e))}function G(t){var e=t%360;return e<0&&(e+=360),e}function B(t){return(t%=360)>180?t-360:t<-180?t+360:t}function Y(t){return 180*(t%(2*Math.PI))/Math.PI}function z(t){return t%360*Math.PI/180}function j(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("length must be a positive number");return F(q(t,e),n)}function X(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"meters",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("area must be a positive number");var r=k[e];if(!r)throw new Error("invalid original units");var i=k[n];if(!i)throw new Error("invalid final units");return t/r*i}function U(t){return!isNaN(t)&&null!==t&&!Array.isArray(t)}function Z(t){return null!==t&&"object"===m(t)&&!Array.isArray(t)}function H(t){if(!t)throw new Error("bbox is required");if(!Array.isArray(t))throw new Error("bbox must be an Array");if(4!==t.length&&6!==t.length)throw new Error("bbox must be an Array of 4 or 6 numbers");t.forEach((function(t){if(!U(t))throw new Error("bbox must only contain numbers")}))}function W(t){if(!t)throw new Error("id is required");if(-1===["string","number"].indexOf(m(t)))throw new Error("id must be a number or a string")}var J=Object.freeze({__proto__:null,areaFactors:k,azimuthToBearing:B,bearingToAzimuth:G,convertArea:X,convertLength:j,degreesToRadians:z,earthRadius:x,factors:E,feature:b,featureCollection:C,geometry:w,geometryCollection:A,isNumber:U,isObject:Z,lengthToDegrees:V,lengthToRadians:q,lineString:L,lineStrings:P,multiLineString:T,multiPoint:O,multiPolygon:R,point:I,points:N,polygon:S,polygons:M,radiansToDegrees:Y,radiansToLength:F,round:D,validateBBox:H,validateId:W});function K(t){if(!t)throw new Error("coord is required");if(!Array.isArray(t)){if("Feature"===t.type&&null!==t.geometry&&"Point"===t.geometry.type)return d(t.geometry.coordinates);if("Point"===t.type)return d(t.coordinates)}if(Array.isArray(t)&&t.length>=2&&!Array.isArray(t[0])&&!Array.isArray(t[1]))return d(t);throw new Error("coord must be GeoJSON Point or an Array of numbers")}function Q(t){if(Array.isArray(t))return t;if("Feature"===t.type){if(null!==t.geometry)return t.geometry.coordinates}else if(t.coordinates)return t.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function $(t){if(t.length>1&&U(t[0])&&U(t[1]))return!0;if(Array.isArray(t[0])&&t[0].length)return $(t[0]);throw new Error("coordinates must only contain numbers")}function tt(t,e,n){if(!e||!n)throw new Error("type and name required");if(!t||t.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.type)}function et(t,e,n){if(!t)throw new Error("No feature passed");if(!n)throw new Error(".featureOf() requires a name");if(!t||"Feature"!==t.type||!t.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!t.geometry||t.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.geometry.type)}function nt(t,e,n){if(!t)throw new Error("No featureCollection passed");if(!n)throw new Error(".collectionOf() requires a name");if(!t||"FeatureCollection"!==t.type)throw new Error("Invalid input to "+n+", FeatureCollection required");var r,i=a(t.features);try{for(i.s();!(r=i.n()).done;){var o=r.value;if(!o||"Feature"!==o.type||!o.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!o.geometry||o.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+o.geometry.type)}}catch(t){i.e(t)}finally{i.f()}}function rt(t){return"Feature"===t.type?t.geometry:t}function it(t,e){return"FeatureCollection"===t.type?"FeatureCollection":"GeometryCollection"===t.type?"GeometryCollection":"Feature"===t.type&&null!==t.geometry?t.geometry.type:t.type}var ot=Object.freeze({__proto__:null,collectionOf:nt,containsNumber:$,featureOf:et,geojsonType:tt,getCoord:K,getCoords:Q,getGeom:rt,getType:it});function st(t,e){if(!0===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final)return function(t,e){var n=st(e,t);return n=(n+180)%360}(t,e);var n=K(t),r=K(e),i=z(n[0]),o=z(r[0]),s=z(n[1]),a=z(r[1]),u=Math.sin(o-i)*Math.cos(a),l=Math.cos(s)*Math.sin(a)-Math.sin(s)*Math.cos(a)*Math.cos(o-i);return Y(Math.atan2(u,l))}function at(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=K(t),o=z(i[0]),s=z(i[1]),a=z(n),u=q(e,r.units),l=Math.asin(Math.sin(s)*Math.cos(u)+Math.cos(s)*Math.sin(u)*Math.cos(a));return I([Y(o+Math.atan2(Math.sin(a)*Math.sin(u)*Math.cos(s),Math.cos(u)-Math.sin(s)*Math.sin(l))),Y(l)],r.properties)}function ut(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e),o=z(i[1]-r[1]),s=z(i[0]-r[0]),a=z(r[1]),u=z(i[1]),l=Math.pow(Math.sin(o/2),2)+Math.pow(Math.sin(s/2),2)*Math.cos(a)*Math.cos(u);return F(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)),n.units)}function lt(t,e){var n;return(n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final?ht(K(e),K(t)):ht(K(t),K(e)))>180?-(360-n):n}function ht(t,e){var n=z(t[1]),r=z(e[1]),i=z(e[0]-t[0]);i>Math.PI&&(i-=2*Math.PI),i<-Math.PI&&(i+=2*Math.PI);var o=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(n/2+Math.PI/4));return(Y(Math.atan2(i,o))+360)%360}function ct(t,e,n){if(null!==t)for(var r,i,o,s,a,u,l,h,c=0,f=0,g=t.type,p="FeatureCollection"===g,v="Feature"===g,d=p?t.features.length:1,y=0;ya||f>u||g>l)return s=o,a=n,u=f,l=g,void(i=0);var p=L([s,o],t.properties);if(!1===e(p,n,r,g,i))return!1;i++,s=o}))&&void 0}}}))}function bt(t,e,n){var r=n,i=!1;return kt(t,(function(t,o,s,a,u){r=!1===i&&void 0===n?t:e(r,t,o,s,a,u),i=!0})),r}function wt(t,e){if(!t)throw new Error("geojson is required");xt(t,(function(t,n,r){if(null!==t.geometry){var i=t.geometry.type,o=t.geometry.coordinates;switch(i){case"LineString":if(!1===e(t,n,r,0,0))return!1;break;case"Polygon":for(var s=0;s0){e+=Math.abs(Ot(t[0]));for(var n=1;n=e?(r+2)%e:r+2],a=i[0]*Tt,u=o[1]*Tt;n+=(s[0]*Tt-a)*Math.sin(u),r++}return n*Ct}function Rt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=t.bbox&&!0!==e.recompute)return t.bbox;var n=[1/0,1/0,-1/0,-1/0];return ct(t,(function(t){n[0]>t[0]&&(n[0]=t[0]),n[1]>t[1]&&(n[1]=t[1]),n[2]e[2]&&(n|=2),t[1]e[3]&&(n|=8),n}function qt(t,e){var n,r=[],i=a(t);try{for(i.s();!(n=i.n()).done;){var o=At(n.value,e);o.length>0&&(o[0][0]===o[o.length-1][0]&&o[0][1]===o[o.length-1][1]||o.push(o[0]),o.length>=4&&r.push(o))}}catch(t){i.e(t)}finally{i.f()}return r}function Vt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Number(t[0]),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]);if(6===t.length)throw new Error("@turf/bbox-polygon does not support BBox with 6 positions");var s=[n,r];return S([[s,[i,r],[i,o],[n,o],s]],e.properties,{bbox:t,id:e.id})}var Gt=function(){return s((function t(e){i(this,t),this.points=e.points||[],this.duration=e.duration||1e4,this.sharpness=e.sharpness||.85,this.centers=[],this.controls=[],this.stepLength=e.stepLength||60,this.length=this.points.length,this.delay=0;for(var n=0;nt&&(e.push(r),n=i)}return e}},{key:"vector",value:function(t){var e=this.pos(t+10),n=this.pos(t-10);return{angle:180*Math.atan2(e.y-n.y,e.x-n.x)/3.14,speed:Math.sqrt((n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y)+(n.z-e.z)*(n.z-e.z))}}},{key:"pos",value:function(t){var e=t-this.delay;e<0&&(e=0),e>this.duration&&(e=this.duration-1);var n=e/this.duration;if(n>=1)return this.points[this.length-1];var r=Math.floor((this.points.length-1)*n);return function(t,e,n,r,i){var o=function(t){var e=t*t,n=e*t;return[n,3*e*(1-t),3*t*(1-t)*(1-t),(1-t)*(1-t)*(1-t)]}(t),s={x:i.x*o[0]+r.x*o[1]+n.x*o[2]+e.x*o[3],y:i.y*o[0]+r.y*o[1]+n.y*o[2]+e.y*o[3],z:i.z*o[0]+r.z*o[1]+n.z*o[2]+e.z*o[3]};return s}((this.length-1)*n-r,this.points[r],this.controls[r][1],this.controls[r+1][0],this.points[r+1])}}])}();function Bt(t){for(var e,n,r=Q(t),i=0,o=1;o0}function Yt(t,e){for(var n=0,r=0,i=0,o=0,s=0,a=0,u=0,l=0,h=null,c=null,f=t[0],g=t[1],p=e.length;n0&&l>0)a=l,s=(h=c)[0]-f;else{if(u=c[0]-t[0],l>0&&a<=0){if((o=s*l-u*a)>0)i+=1;else if(0===o)return 0}else if(a>0&&l<=0){if((o=s*l-u*a)<0)i+=1;else if(0===o)return 0}else if(0===l&&a<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&l<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&0===l){if(u<=0&&s>=0)return 0;if(s<=0&&u>=0)return 0}h=c,a=l,s=u}}return i%2!=0}function zt(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("point is required");if(!e)throw new Error("polygon is required");var r=K(t),i=rt(e),o=i.type,s=e.bbox,a=i.coordinates;if(s&&!1===function(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}(r,s))return!1;"Polygon"===o&&(a=[a]);for(var u=!1,l=0;l2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=Q(e),o=0;oi)return!1}else if(0!==g)return!1;return Math.abs(c)===Math.abs(f)&&0===Math.abs(c)?!r&&(n[0]===t[0]&&n[1]===t[1]):r?"start"===r?Math.abs(c)>=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o0?u<=s&&s=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o<=l:l<=o&&o<=a:f>0?u<=s&&s<=h:h<=s&&s<=u}function Ut(t,e){if("Feature"===t.type&&null===t.geometry)return!1;if("Feature"===e.type&&null===e.geometry)return!1;if(!Zt(Rt(t),Rt(e)))return!1;var n,r=a(rt(e).coordinates);try{for(r.s();!(n=r.n()).done;){var i,o=a(n.value);try{for(o.s();!(i=o.n()).done;){if(!zt(i.value,t))return!1}}catch(t){o.e(t)}finally{o.f()}}}catch(t){r.e(t)}finally{r.f()}return!0}function Zt(t,e){return!(t[0]>e[0])&&(!(t[2]e[1])&&!(t[3]0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Kt;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function Kt(t,e){return te?1:0}function Qt(t,e){return t.p.x>e.p.x?1:t.p.xe.p.y?1:-1:1}function $t(t,e){return t.rightSweepEvent.p.x>e.rightSweepEvent.p.x?1:t.rightSweepEvent.p.x0?(h.isLeftEndpoint=!0,l.isLeftEndpoint=!1):(l.isLeftEndpoint=!0,h.isLeftEndpoint=!1),e.push(l),e.push(h),s=a,re+=1}}ee+=1}var oe=s((function t(e){i(this,t),this.leftSweepEvent=e,this.rightSweepEvent=e.otherEvent}));function se(t,e){if(null===t||null===e)return!1;if(t.leftSweepEvent.ringId===e.leftSweepEvent.ringId&&(t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.rightSweepEvent)||t.leftSweepEvent.isSamePoint(e.leftSweepEvent)||t.leftSweepEvent.isSamePoint(e.rightSweepEvent)))return!1;var n=t.leftSweepEvent.p.x,r=t.leftSweepEvent.p.y,i=t.rightSweepEvent.p.x,o=t.rightSweepEvent.p.y,s=e.leftSweepEvent.p.x,a=e.leftSweepEvent.p.y,u=e.rightSweepEvent.p.x,l=e.rightSweepEvent.p.y,h=(l-a)*(i-n)-(u-s)*(o-r),c=(u-s)*(r-a)-(l-a)*(n-s),f=(i-n)*(r-a)-(o-r)*(n-s);if(0===h)return!1;var g=c/h,p=f/h;return g>=0&&g<=1&&p>=0&&p<=1&&[n+g*(i-n),r+g*(o-r)]}var ae=function(t,e){var n=new Jt([],Qt);return function(t,e){if("FeatureCollection"===t.type)for(var n=t.features,r=0;r2&&void 0!==arguments[2]?arguments[2]:{},r=n.removeDuplicates,i=void 0===r||r,o=n.ignoreSelfIntersections,s=void 0===o||o,a=[];"FeatureCollection"===t.type?a=a.concat(t.features):"Feature"===t.type?a.push(t):"LineString"!==t.type&&"Polygon"!==t.type&&"MultiLineString"!==t.type&&"MultiPolygon"!==t.type||a.push(b(t)),"FeatureCollection"===e.type?a=a.concat(e.features):"Feature"===e.type?a.push(e):"LineString"!==e.type&&"Polygon"!==e.type&&"MultiLineString"!==e.type&&"MultiPolygon"!==e.type||a.push(b(e));var u=ae(C(a),s),l=[];if(i){var h={};u.forEach((function(t){var e=t.join(",");h[e]||(h[e]=!0,l.push(t))}))}else l=u;return C(l.map((function(t){return I(t)})))}function le(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t);switch(e.properties||"Feature"!==t.type||(e.properties=t.properties),n.type){case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{};return he(r,i)}(n,e);case"MultiPolygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{},o=[];return r.forEach((function(t){o.push(he(t,i))})),C(o)}(n,e);default:throw new Error("invalid poly")}}function he(t,e){return t.length>1?T(t,e):L(t[0],e)}function ce(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;switch(i){case"MultiPoint":switch(o){case"LineString":return fe(n,r);case"Polygon":return pe(n,r);default:throw new Error("feature2 "+o+" geometry not supported")}case"LineString":switch(o){case"MultiPoint":return fe(r,n);case"LineString":return function(t,e){if(ue(t,e).features.length>0)for(var n=0;n0}function pe(t,e){for(var n=!1,r=!1,i=t.coordinates.length,o=0;o=Math.abs(a)?s>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:a>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1]:Math.abs(s)>=Math.abs(a)?s>0?t[0]0?t[1]2&&void 0!==arguments[2]?arguments[2]:{ignoreSelfIntersections:!0}).ignoreSelfIntersections,r=void 0===n||n,i=!0;return xt(t,(function(t){xt(e,(function(e){if(!1===i)return!1;i=function(t,e,n){switch(t.type){case"Point":switch(e.type){case"Point":return r=t.coordinates,i=e.coordinates,!(r[0]===i[0]&&r[1]===i[1]);case"LineString":return!ye(e,t);case"Polygon":return!zt(t,e)}break;case"LineString":switch(e.type){case"Point":return!ye(t,e);case"LineString":return!function(t,e,n){var r=ue(t,e,{ignoreSelfIntersections:n});if(r.features.length>0)return!0;return!1}(t,e,n);case"Polygon":return!me(e,t,n)}break;case"Polygon":switch(e.type){case"Point":return!zt(e,t);case"LineString":return!me(t,e,n);case"Polygon":return!function(t,e,n){var r,i=a(t.coordinates[0]);try{for(i.s();!(r=i.n()).done;){if(zt(r.value,e))return!0}}catch(t){i.e(t)}finally{i.f()}var o,s=a(e.coordinates[0]);try{for(s.s();!(o=s.n()).done;){if(zt(o.value,t))return!0}}catch(t){s.e(t)}finally{s.f()}var u=ue(le(t),le(e),{ignoreSelfIntersections:n});if(u.features.length>0)return!0;return!1}(e,t,n)}}var r,i;return!1}(t.geometry,e.geometry,r)}))})),i}function ye(t,e){for(var n=0;n0}function _e(t,e,n){var r=n[0]-t[0],i=n[1]-t[1],o=e[0]-t[0],s=e[1]-t[1];return 0==r*s-i*o&&(Math.abs(o)>=Math.abs(s)?o>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:s>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1])}var xe=Object.defineProperty,Ee=function(t,e){return xe(t,"name",{value:e,configurable:!0})},ke=function(){return s((function t(e){var n,r,o;i(this,t),this.direction=!1,this.compareProperties=!0,this.precision=Math.pow(10,-(null!=(n=null==e?void 0:e.precision)?n:17)),this.direction=null!=(r=null==e?void 0:e.direction)&&r,this.compareProperties=null==(o=null==e?void 0:e.compareProperties)||o}),[{key:"compare",value:function(t,e){var n=this;if(t.type!==e.type)return!1;if(!we(t,e))return!1;switch(t.type){case"Point":return this.compareCoord(t.coordinates,e.coordinates);case"LineString":return this.compareLine(t.coordinates,e.coordinates);case"Polygon":return this.comparePolygon(t,e);case"GeometryCollection":return this.compareGeometryCollection(t,e);case"Feature":return this.compareFeature(t,e);case"FeatureCollection":return this.compareFeatureCollection(t,e);default:if(t.type.startsWith("Multi")){var r=Ie(t),i=Ie(e);return r.every((function(t){return i.some((function(e){return n.compare(t,e)}))}))}}return!1}},{key:"compareCoord",value:function(t,e){var n=this;return t.length===e.length&&t.every((function(t,r){return Math.abs(t-e[r])2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!we(t,e))return!1;var i=t,o=e;if(r&&!this.compareCoord(i[0],o[0])){var s=this.fixStartIndex(o,i);if(!s)return!1;o=s}var a=this.compareCoord(i[n],o[n]);return this.direction||a?this.comparePath(i,o):!!this.compareCoord(i[n],o[o.length-(1+n)])&&this.comparePath(i.slice().reverse(),o)}},{key:"fixStartIndex",value:function(t,e){for(var n,r=-1,i=0;i=0&&(n=[].concat(t.slice(r,t.length),t.slice(1,r+1))),n}},{key:"comparePath",value:function(t,e){var n=this;return t.every((function(t,r){return n.compareCoord(t,e[r])}))}},{key:"comparePolygon",value:function(t,e){var n=this;if(this.compareLine(t.coordinates[0],e.coordinates[0],1,!0)){var r=t.coordinates.slice(1,t.coordinates.length),i=e.coordinates.slice(1,e.coordinates.length);return r.every((function(t){return i.some((function(e){return n.compareLine(t,e,1,!0)}))}))}return!1}},{key:"compareGeometryCollection",value:function(t,e){var n=this;return we(t.geometries,e.geometries)&&this.compareBBox(t,e)&&t.geometries.every((function(t,r){return n.compare(t,e.geometries[r])}))}},{key:"compareFeature",value:function(t,e){return t.id===e.id&&(!this.compareProperties||Se(t.properties,e.properties))&&this.compareBBox(t,e)&&this.compare(t.geometry,e.geometry)}},{key:"compareFeatureCollection",value:function(t,e){var n=this;return we(t.features,e.features)&&this.compareBBox(t,e)&&t.features.every((function(t,r){return n.compare(t,e.features[r])}))}},{key:"compareBBox",value:function(t,e){return Boolean(!t.bbox&&!e.bbox)||!(!t.bbox||!e.bbox)&&this.compareCoord(t.bbox,e.bbox)}}])}();Ee(ke,"GeojsonEquality");var be=ke;function we(t,e){return t.coordinates?t.coordinates.length===e.coordinates.length:t.length===e.length}function Ie(t){return t.coordinates.map((function(e){return{type:t.type.replace("Multi",""),coordinates:e}}))}function Ne(t,e,n){return new be(n).compare(t,e)}function Se(t,e){if(null===t&&null===e)return!0;if(null===t||null===e)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(var i=0,o=n;i1&&void 0!==arguments[1]?arguments[1]:{},n="object"===m(e)?e.mutate:e;if(!t)throw new Error("geojson is required");var r=it(t),i=[];switch(r){case"LineString":i=Pe(t,r);break;case"MultiLineString":case"Polygon":Q(t).forEach((function(t){i.push(Pe(t,r))}));break;case"MultiPolygon":Q(t).forEach((function(t){var e=[];t.forEach((function(t){e.push(Pe(t,r))})),i.push(e)}));break;case"Point":return t;case"MultiPoint":var o={};Q(t).forEach((function(t){var e=t.join("-");Object.prototype.hasOwnProperty.call(o,e)||(i.push(t),o[e]=!0)}));break;default:throw new Error(r+" geometry not supported")}return t.coordinates?!0===n?(t.coordinates=i,t):{type:r,coordinates:i}:!0===n?(t.geometry.coordinates=i,t):b({type:r,coordinates:i},t.properties,{bbox:t.bbox,id:t.id})}function Pe(t,e){var n=Q(t);if(2===n.length&&!Ce(n[0],n[1]))return n;var r=[],i=n.length-1,o=r.length;r.push(n[0]);for(var s=1;s2&&Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1))}if(r.push(n[n.length-1]),o=r.length,("Polygon"===e||"MultiPolygon"===e)&&Ce(n[0],n[n.length-1])&&o<4)throw new Error("invalid polygon");return"LineString"===e&&o<3||Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1),r}function Ce(t,e){return t[0]===e[0]&&t[1]===e[1]}function Te(t,e,n){var r=n[0],i=n[1],o=t[0],s=t[1],a=e[0],u=e[1],l=a-o,h=u-s;return 0===(r-o)*h-(i-s)*l&&(Math.abs(l)>=Math.abs(h)?l>0?o<=r&&r<=a:a<=r&&r<=o:h>0?s<=i&&i<=u:u<=i&&i<=s)}function Oe(t,e){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).ignoreSelfIntersections,r=void 0===n||n,i=!1;return xt(t,(function(t){xt(e,(function(e){if(!0===i)return!0;i=!de(t.geometry,e.geometry,{ignoreSelfIntersections:r})}))})),i}function Re(t,e,n,r,i){Ae(t,e,n||0,r||t.length-1,i||Fe)}function Ae(t,e,n,r,i){for(;r>n;){if(r-n>600){var o=r-n+1,s=e-n+1,a=Math.log(o),u=.5*Math.exp(2*a/3),l=.5*Math.sqrt(a*u*(o-u)/o)*(s-o/2<0?-1:1);Ae(t,e,Math.max(n,Math.floor(e-s*u/o+l)),Math.min(r,Math.floor(e+(o-s)*u/o+l)),i)}var h=t[e],c=n,f=r;for(De(t,n,e),i(t[r],h)>0&&De(t,n,r);c0;)f--}0===i(t[n],h)?De(t,n,f):De(t,++f,r),f<=e&&(n=f+1),e<=f&&(r=f-1)}}function De(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function Fe(t,e){return te?1:0}var qe=function(){return s((function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:9;i(this,t),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}),[{key:"all",value:function(){return this._all(this.data,[])}},{key:"search",value:function(t){var e=this.data,n=[];if(!He(t,e))return n;for(var r=this.toBBox,i=[];e;){for(var o=0;o=0&&i[e].children.length>this._maxEntries;)this._split(i,e),e--;this._adjustParentBBoxes(r,i,e)}},{key:"_split",value:function(t,e){var n=t[e],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=We(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,Ge(n,this.toBBox),Ge(s,this.toBBox),e?t[e-1].children.push(s):this._splitRoot(n,s)}},{key:"_splitRoot",value:function(t,e){this.data=We([t,e]),this.data.height=t.height+1,this.data.leaf=!1,Ge(this.data,this.toBBox)}},{key:"_chooseSplitIndex",value:function(t,e,n){for(var r,i,o,s,a,u,l,h=1/0,c=1/0,f=e;f<=n-e;f++){var g=Be(t,0,f,this.toBBox),p=Be(t,f,n,this.toBBox),v=(i=g,o=p,s=void 0,a=void 0,u=void 0,l=void 0,s=Math.max(i.minX,o.minX),a=Math.max(i.minY,o.minY),u=Math.min(i.maxX,o.maxX),l=Math.min(i.maxY,o.maxY),Math.max(0,u-s)*Math.max(0,l-a)),d=Xe(g)+Xe(p);v=e;h--){var c=t.children[h];Ye(s,t.leaf?i(c):c),a+=Ue(s)}return a}},{key:"_adjustParentBBoxes",value:function(t,e,n){for(var r=n;r>=0;r--)Ye(e[r],t)}},{key:"_condense",value:function(t){for(var e,n=t.length-1;n>=0;n--)0===t[n].children.length?n>0?(e=t[n-1].children).splice(e.indexOf(t[n]),1):this.clear():Ge(t[n],this.toBBox)}}])}();function Ve(t,e,n){if(!n)return e.indexOf(t);for(var r=0;r=t.minX&&e.maxY>=t.minY}function We(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Je(t,e,n,r,i){for(var o=[e,n];o.length;)if(!((n=o.pop())-(e=o.pop())<=r)){var s=e+Math.ceil((n-e)/r/2)*r;Re(t,s,e,n,i),o.push(e,s,s,n)}}var Ke=Object.freeze({__proto__:null,default:qe});function Qe(t){var e=new qe(t);return e.insert=function(t){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.insert.call(this,t)},e.load=function(t){var e=[];return Array.isArray(t)?t.forEach((function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})):vt(t,(function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})),qe.prototype.load.call(this,e)},e.remove=function(t,e){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.remove.call(this,t,e)},e.clear=function(){return qe.prototype.clear.call(this)},e.search=function(t){return C(qe.prototype.search.call(this,this.toBBox(t)))},e.collides=function(t){return qe.prototype.collides.call(this,this.toBBox(t))},e.all=function(){return C(qe.prototype.all.call(this))},e.toJSON=function(){return qe.prototype.toJSON.call(this)},e.fromJSON=function(t){return qe.prototype.fromJSON.call(this,t)},e.toBBox=function(t){var e;if(t.bbox)e=t.bbox;else if(Array.isArray(t)&&4===t.length)e=t;else if(Array.isArray(t)&&6===t.length)e=[t[0],t[1],t[3],t[4]];else if("Feature"===t.type)e=Rt(t);else{if("FeatureCollection"!==t.type)throw new Error("invalid geojson");e=Rt(t)}return{minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}},e}function $e(t){if(!t)throw new Error("geojson is required");var e=[];return xt(t,(function(t){!function(t,e){var n=[],r=t.geometry;if(null!==r){switch(r.type){case"Polygon":n=Q(r);break;case"LineString":n=[Q(r)]}n.forEach((function(n){var r=function(t,e){var n=[];return t.reduce((function(t,r){var i=L([t,r],e);return i.bbox=function(t,e){var n=t[0],r=t[1],i=e[0],o=e[1],s=ni?n:i,l=r>o?r:o;return[s,a,u,l]}(t,r),n.push(i),r})),n}(n,t.properties);r.forEach((function(t){t.id=e.length,e.push(t)}))}))}}(t,e)})),C(e)}var tn,en,nn=Object.defineProperty,rn=Object.defineProperties,on=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertySymbols,an=Object.prototype.hasOwnProperty,un=Object.prototype.propertyIsEnumerable,ln=function(t,e,n){return e in t?nn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},hn=function(t,e){for(var n in e||(e={}))an.call(e,n)&&ln(t,n,e[n]);if(sn){var r,i=a(sn(e));try{for(i.s();!(r=i.n()).done;){n=r.value;un.call(e,n)&&ln(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},cn=function(t,e){return rn(t,on(e))};function fn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t||!e)throw new Error("lines and pt are required arguments");var r=K(e),i=I([1/0,1/0],{dist:1/0,index:-1,multiFeatureIndex:-1,location:-1}),o=0;return xt(t,(function(t,s,a){for(var u=Q(t),l=0;lR||pn(p,f)>R?ut(dn(f),dn(g))<=ut(dn(f),dn(p))?[dn(g),!0,!1]:[dn(p),!1,!0]:[dn(f),!1,!1]}function mn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function _n(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var n=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,r.get?r:{enumerable:!0,get:function(){return t[e]}})})),n}var xn=(en||(en=1,tn=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==m(e)&&"object"==m(n)){if(e.constructor!==n.constructor)return!1;var r,i,o;if(Array.isArray(e)){if((r=e.length)!=n.length)return!1;for(i=r;0!=i--;)if(!t(e[i],n[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((r=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(i=r;0!=i--;)if(!Object.prototype.hasOwnProperty.call(n,o[i]))return!1;for(i=r;0!=i--;){var s=o[i];if(!t(e[s],n[s]))return!1}return!0}return e!=e&&n!=n}),tn),En=mn(xn);function kn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r,i=n.tolerance||0,o=[],s=Qe(),a=$e(t);s.load(a);var u=[];return kt(e,(function(t){var e=!1;t&&(vt(s.search(t),(function(n){if(!1===e){var o=Q(t).sort(),s=Q(n).sort();if(En(o,s))e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(o[0],n)&&jt(o[1],n):fn(n,o[0]).properties.dist<=i&&fn(n,o[1]).properties.dist<=i)e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(s[0],t)&&jt(s[1],t):fn(t,s[0]).properties.dist<=i&&fn(t,s[1]).properties.dist<=i)if(r){var a=bn(r,n);a?r=a:u.push(n)}else r=n}})),!1===e&&r&&(o.push(r),u.length&&(o=o.concat(u),u=[]),r=void 0))})),r&&o.push(r),C(o)}function bn(t,e){var n=Q(e),r=Q(t),i=r[0],o=r[r.length-1],s=t.geometry.coordinates;if(En(n[0],i))s.unshift(n[1]);else if(En(n[0],o))s.push(n[1]);else if(En(n[1],i))s.unshift(n[0]);else{if(!En(n[1],o))return;s.push(n[0])}return t}function wn(t,e){var n=G(lt(t[0],t[1])),r=G(lt(e[0],e[1]));return n===r||(r-n)%180==0}function In(t,e){if(t.geometry&&t.geometry.type)return t.geometry.type;if(t.type)return t.type;throw new Error("Invalid GeoJSON object for "+e)}function Nn(t,e){return!!Sn(e.coordinates[0],t.coordinates)||!!Sn(e.coordinates[e.coordinates.length-1],t.coordinates)}function Sn(t,e){return t[0]===e[0]&&t[1]===e[1]}function Mn(t){return t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]}function Ln(t){for(var e=0;ee[0])&&(!(t[2]e[1])&&!(t[3]1&&void 0!==arguments[1]?arguments[1]:{},n=Rt(t);return I([(n[0]+n[2])/2,(n[1]+n[3])/2],e.properties,e)}var Dn,Fn={exports:{}};var qn=(Dn||(Dn=1,function(t,e){t.exports=function(){function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}var y=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getEndCapStyle",value:function(){return this._endCapStyle}},{key:"isSingleSided",value:function(){return this._isSingleSided}},{key:"setQuadrantSegments",value:function(t){this._quadrantSegments=t,0===this._quadrantSegments&&(this._joinStyle=e.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=e.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),t<=0&&(this._quadrantSegments=1),this._joinStyle!==e.JOIN_ROUND&&(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS)}},{key:"getJoinStyle",value:function(){return this._joinStyle}},{key:"setJoinStyle",value:function(t){this._joinStyle=t}},{key:"setSimplifyFactor",value:function(t){this._simplifyFactor=t<0?0:t}},{key:"getSimplifyFactor",value:function(){return this._simplifyFactor}},{key:"getQuadrantSegments",value:function(){return this._quadrantSegments}},{key:"setEndCapStyle",value:function(t){this._endCapStyle=t}},{key:"getMitreLimit",value:function(){return this._mitreLimit}},{key:"setMitreLimit",value:function(t){this._mitreLimit=t}},{key:"setSingleSided",value:function(t){this._isSingleSided=t}}],[{key:"constructor_",value:function(){if(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=e.CAP_ROUND,this._joinStyle=e.JOIN_ROUND,this._mitreLimit=e.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=e.DEFAULT_SIMPLIFY_FACTOR,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.setQuadrantSegments(t)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.setQuadrantSegments(n),this.setEndCapStyle(r)}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];this.setQuadrantSegments(i),this.setEndCapStyle(o),this.setJoinStyle(s),this.setMitreLimit(a)}}},{key:"bufferDistanceError",value:function(t){var e=Math.PI/2/t;return 1-Math.cos(e/2)}}]),e}();y.CAP_ROUND=1,y.CAP_FLAT=2,y.CAP_SQUARE=3,y.JOIN_ROUND=1,y.JOIN_MITRE=2,y.JOIN_BEVEL=3,y.DEFAULT_QUADRANT_SEGMENTS=8,y.DEFAULT_MITRE_LIMIT=5,y.DEFAULT_SIMPLIFY_FACTOR=.01;var _=function(e){r(o,e);var i=c(o);function o(e){var n;return t(this,o),(n=i.call(this,e)).name=Object.keys({Exception:o})[0],n}return n(o,[{key:"toString",value:function(){return this.message}}]),o}(u(Error)),x=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({IllegalArgumentException:i})[0],r}return i}(_),E=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}();function k(){}function b(){}function w(){}var I,N,S,M,L,P,C,T,O=function(){function e(){t(this,e)}return n(e,null,[{key:"equalsWithTolerance",value:function(t,e,n){return Math.abs(t-e)<=n}}]),e}(),R=function(){function e(n,r){t(this,e),this.low=r||0,this.high=n||0}return n(e,null,[{key:"toBinaryString",value:function(t){var e,n="";for(e=2147483648;e>0;e>>>=1)n+=(t.high&e)===e?"1":"0";for(e=2147483648;e>0;e>>>=1)n+=(t.low&e)===e?"1":"0";return n}}]),e}();function A(){}function D(){}A.NaN=NaN,A.isNaN=function(t){return Number.isNaN(t)},A.isInfinite=function(t){return!Number.isFinite(t)},A.MAX_VALUE=Number.MAX_VALUE,A.POSITIVE_INFINITY=Number.POSITIVE_INFINITY,A.NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,"function"==typeof Float64Array&&"function"==typeof Int32Array?(P=2146435072,C=new Float64Array(1),T=new Int32Array(C.buffer),A.doubleToLongBits=function(t){C[0]=t;var e=0|T[0],n=0|T[1];return(n&P)===P&&0!=(1048575&n)&&0!==e&&(e=0,n=2146959360),new R(n,e)},A.longBitsToDouble=function(t){return T[0]=t.low,T[1]=t.high,C[0]}):(I=1023,N=Math.log2,S=Math.floor,M=Math.pow,L=function(){for(var t=53;t>0;t--){var e=M(2,t)-1;if(S(N(e))+1===t)return e}return 0}(),A.doubleToLongBits=function(t){var e,n,r,i,o,s,a,u,l;if(t<0||1/t===Number.NEGATIVE_INFINITY?(s=1<<31,t=-t):s=0,0===t)return new R(u=s,l=0);if(t===1/0)return new R(u=2146435072|s,l=0);if(t!=t)return new R(u=2146959360,l=0);if(i=0,l=0,(e=S(t))>1)if(e<=L)(i=S(N(e)))<=20?(l=0,u=e<<20-i&1048575):(l=e%(n=M(2,r=i-20))<<32-r,u=e/n&1048575);else for(r=e,l=0;0!==(r=S(n=r/2));)i++,l>>>=1,l|=(1&u)<<31,u>>>=1,n!==r&&(u|=524288);if(a=i+I,o=0===e,e=t-e,i<52&&0!==e)for(r=0;;){if((n=2*e)>=1?(e=n-1,o?(a--,o=!1):(r<<=1,r|=1,i++)):(e=n,o?0==--a&&(i++,o=!1):(r<<=1,i++)),20===i)u|=r,r=0;else if(52===i){l|=r;break}if(1===n){i<20?u|=r<<20-i:i<52&&(l|=r<<52-i);break}}return u|=a<<20,new R(u|=s,l)},A.longBitsToDouble=function(t){var e,n,r,i,o=t.high,s=t.low,a=o&1<<31?-1:1;for(r=((2146435072&o)>>20)-I,i=0,n=1<<19,e=1;e<=20;e++)o&n&&(i+=M(2,-e)),n>>>=1;for(n=1<<31,e=21;e<=52;e++)s&n&&(i+=M(2,-e)),n>>>=1;if(-1023===r){if(0===i)return 0*a;r=-1022}else{if(1024===r)return 0===i?a/0:NaN;i+=1}return a*i*M(2,r)});var F=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({RuntimeException:i})[0],r}return i}(_),q=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){if(0===arguments.length)F.constructor_.call(this);else if(1===arguments.length){var t=arguments[0];F.constructor_.call(this,t)}}}]),o}(F),V=function(){function e(){t(this,e)}return n(e,null,[{key:"shouldNeverReachHere",value:function(){if(0===arguments.length)e.shouldNeverReachHere(null);else if(1===arguments.length){var t=arguments[0];throw new q("Should never reach here"+(null!==t?": "+t:""))}}},{key:"isTrue",value:function(){if(1===arguments.length){var t=arguments[0];e.isTrue(t,null)}else if(2===arguments.length){var n=arguments[1];if(!arguments[0])throw null===n?new q:new q(n)}}},{key:"equals",value:function(){if(2===arguments.length){var t=arguments[0],n=arguments[1];e.equals(t,n,null)}else if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2];if(!i.equals(r))throw new q("Expected "+r+" but encountered "+i+(null!==o?": "+o:""))}}}]),e}(),G=new ArrayBuffer(8),B=new Float64Array(G),Y=new Int32Array(G),z=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getM",value:function(){return A.NaN}},{key:"setOrdinate",value:function(t,n){switch(t){case e.X:this.x=n;break;case e.Y:this.y=n;break;case e.Z:this.setZ(n);break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"equals2D",value:function(){if(1===arguments.length){var t=arguments[0];return this.x===t.x&&this.y===t.y}if(2===arguments.length){var e=arguments[0],n=arguments[1];return!!O.equalsWithTolerance(this.x,e.x,n)&&!!O.equalsWithTolerance(this.y,e.y,n)}}},{key:"setM",value:function(t){throw new x("Invalid ordinate index: "+e.M)}},{key:"getZ",value:function(){return this.z}},{key:"getOrdinate",value:function(t){switch(t){case e.X:return this.x;case e.Y:return this.y;case e.Z:return this.getZ()}throw new x("Invalid ordinate index: "+t)}},{key:"equals3D",value:function(t){return this.x===t.x&&this.y===t.y&&(this.getZ()===t.getZ()||A.isNaN(this.getZ())&&A.isNaN(t.getZ()))}},{key:"equals",value:function(t){return t instanceof e&&this.equals2D(t)}},{key:"equalInZ",value:function(t,e){return O.equalsWithTolerance(this.getZ(),t.getZ(),e)}},{key:"setX",value:function(t){this.x=t}},{key:"compareTo",value:function(t){var e=t;return this.xe.x?1:this.ye.y?1:0}},{key:"getX",value:function(){return this.x}},{key:"setZ",value:function(t){this.z=t}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return V.shouldNeverReachHere("this shouldn't happen because this class is Cloneable"),null;throw t}}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+")"}},{key:"distance3D",value:function(t){var e=this.x-t.x,n=this.y-t.y,r=this.getZ()-t.getZ();return Math.sqrt(e*e+n*n+r*r)}},{key:"getY",value:function(){return this.y}},{key:"setY",value:function(t){this.y=t}},{key:"distance",value:function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*t+e.hashCode(this.x))+e.hashCode(this.y)}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}},{key:"interfaces_",get:function(){return[k,b,w]}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.z=null,0===arguments.length)e.constructor_.call(this,0,0);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.x,t.y,t.getZ())}else if(2===arguments.length){var n=arguments[0],r=arguments[1];e.constructor_.call(this,n,r,e.NULL_ORDINATE)}else if(3===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2];this.x=i,this.y=o,this.z=s}}},{key:"hashCode",value:function(t){return B[0]=t,Y[0]^Y[1]}}]),e}(),j=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compare",value:function(t,n){var r=e.compare(t.x,n.x);if(0!==r)return r;var i=e.compare(t.y,n.y);return 0!==i?i:this._dimensionsToTest<=2?0:e.compare(t.getZ(),n.getZ())}},{key:"interfaces_",get:function(){return[D]}}],[{key:"constructor_",value:function(){if(this._dimensionsToTest=2,0===arguments.length)e.constructor_.call(this,2);else if(1===arguments.length){var t=arguments[0];if(2!==t&&3!==t)throw new x("only 2 or 3 dimensions may be specified");this._dimensionsToTest=t}}},{key:"compare",value:function(t,e){return te?1:A.isNaN(t)?A.isNaN(e)?0:-1:A.isNaN(e)?1:0}}]),e}();z.DimensionalComparator=j,z.NULL_ORDINATE=A.NaN,z.X=0,z.Y=1,z.Z=2,z.M=3;var X=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getArea",value:function(){return this.getWidth()*this.getHeight()}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.isNull()?n.isNull():this._maxx===n.getMaxX()&&this._maxy===n.getMaxY()&&this._minx===n.getMinX()&&this._miny===n.getMinY()}},{key:"intersection",value:function(t){if(this.isNull()||t.isNull()||!this.intersects(t))return new e;var n=this._minx>t._minx?this._minx:t._minx,r=this._miny>t._miny?this._miny:t._miny;return new e(n,this._maxx=this._minx&&n.getMaxX()<=this._maxx&&n.getMinY()>=this._miny&&n.getMaxY()<=this._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return!this.isNull()&&r>=this._minx&&r<=this._maxx&&i>=this._miny&&i<=this._maxy}}},{key:"intersects",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return!this.isNull()&&!t.isNull()&&!(t._minx>this._maxx||t._maxxthis._maxy||t._maxythis._maxx||(r.x>i.x?r.x:i.x)this._maxy||(r.y>i.y?r.y:i.y)this._maxx||othis._maxy||sthis._maxx&&(this._maxx=n._maxx),n._minythis._maxy&&(this._maxy=n._maxy))}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.isNull()?(this._minx=r,this._maxx=r,this._miny=i,this._maxy=i):(rthis._maxx&&(this._maxx=r),ithis._maxy&&(this._maxy=i))}}},{key:"minExtent",value:function(){if(this.isNull())return 0;var t=this.getWidth(),e=this.getHeight();return te._minx?1:this._minye._miny?1:this._maxxe._maxx?1:this._maxye._maxy?1:0}},{key:"translate",value:function(t,e){if(this.isNull())return null;this.init(this.getMinX()+t,this.getMaxX()+t,this.getMinY()+e,this.getMaxY()+e)}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"Env["+this._minx+" : "+this._maxx+", "+this._miny+" : "+this._maxy+"]"}},{key:"setToNull",value:function(){this._minx=0,this._maxx=-1,this._miny=0,this._maxy=-1}},{key:"disjoint",value:function(t){return!(!this.isNull()&&!t.isNull())||t._minx>this._maxx||t._maxxthis._maxy||t._maxye?t:e}},{key:"expandBy",value:function(){if(1===arguments.length){var t=arguments[0];this.expandBy(t,t)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];if(this.isNull())return null;this._minx-=e,this._maxx+=e,this._miny-=n,this._maxy+=n,(this._minx>this._maxx||this._miny>this._maxy)&&this.setToNull()}}},{key:"contains",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.covers(t)}if(arguments[0]instanceof z){var n=arguments[0];return this.covers(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return this.covers(r,i)}}},{key:"centre",value:function(){return this.isNull()?null:new z((this.getMinX()+this.getMaxX())/2,(this.getMinY()+this.getMaxY())/2)}},{key:"init",value:function(){if(0===arguments.length)this.setToNull();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this._minx=n._minx,this._maxx=n._maxx,this._miny=n._miny,this._maxy=n._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];ot._maxx&&(e=this._minx-t._maxx);var n=0;return this._maxyt._maxy&&(n=this._miny-t._maxy),0===e?n:0===n?e:Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*(t=37*(t=37*t+z.hashCode(this._minx))+z.hashCode(this._maxx))+z.hashCode(this._miny))+z.hashCode(this._maxy)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,0===arguments.length)this.init();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];this.init(o,s,a,u)}}},{key:"intersects",value:function(){if(3===arguments.length){var t=arguments[0],e=arguments[1],n=arguments[2];return n.x>=(t.xe.x?t.x:e.x)&&n.y>=(t.ye.y?t.y:e.y)}if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=arguments[3],a=Math.min(o.x,s.x),u=Math.max(o.x,s.x),l=Math.min(r.x,i.x),h=Math.max(r.x,i.x);return!(l>u||hu||h=this.size())throw new nt;return this.array[t]}},{key:"push",value:function(t){return this.array.push(t),t}},{key:"pop",value:function(){if(0===this.array.length)throw new et;return this.array.pop()}},{key:"peek",value:function(){if(0===this.array.length)throw new et;return this.array[this.array.length-1]}},{key:"empty",value:function(){return 0===this.array.length}},{key:"isEmpty",value:function(){return this.empty()}},{key:"search",value:function(t){return this.array.indexOf(t)}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}}]),o}(rt);function ot(t,e){return t.interfaces_&&t.interfaces_.indexOf(e)>-1}var st=function(){function e(n){t(this,e),this.str=n}return n(e,[{key:"append",value:function(t){this.str+=t}},{key:"setCharAt",value:function(t,e){this.str=this.str.substr(0,t)+e+this.str.substr(t+1)}},{key:"toString",value:function(){return this.str}}]),e}(),at=function(){function e(n){t(this,e),this.value=n}return n(e,[{key:"intValue",value:function(){return this.value}},{key:"compareTo",value:function(t){return this.valuet?1:0}}],[{key:"compare",value:function(t,e){return te?1:0}},{key:"isNan",value:function(t){return Number.isNaN(t)}},{key:"valueOf",value:function(t){return new e(t)}}]),e}(),ut=function(){function e(){t(this,e)}return n(e,null,[{key:"isWhitespace",value:function(t){return t<=32&&t>=0||127===t}},{key:"toUpperCase",value:function(t){return t.toUpperCase()}}]),e}(),lt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"le",value:function(t){return this._hi9?(c=!0,f="9"):f="0"+h,a.append(f),r=r.subtract(e.valueOf(h)).multiply(e.TEN),c&&r.selfAdd(e.TEN);var g=!0,p=e.magnitude(r._hi);if(p<0&&Math.abs(p)>=u-l&&(g=!1),!g)break}return n[0]=i,a.toString()}},{key:"sqr",value:function(){return this.multiply(this)}},{key:"doubleValue",value:function(){return this._hi+this._lo}},{key:"subtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.add(t.negate())}if("number"==typeof arguments[0]){var n=arguments[0];return this.add(-n)}}},{key:"equals",value:function(){if(1===arguments.length&&arguments[0]instanceof e){var t=arguments[0];return this._hi===t._hi&&this._lo===t._lo}}},{key:"isZero",value:function(){return 0===this._hi&&0===this._lo}},{key:"selfSubtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.isNaN()?this:this.selfAdd(-t._hi,-t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.isNaN()?this:this.selfAdd(-n,0)}}},{key:"getSpecialNumberString",value:function(){return this.isZero()?"0.0":this.isNaN()?"NaN ":null}},{key:"min",value:function(t){return this.le(t)?this:t}},{key:"selfDivide",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfDivide(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfDivide(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null,c=null,f=null;return l=this._hi/r,f=(o=(h=e.SPLIT*l)-(o=h-l))*(a=(f=e.SPLIT*r)-(a=f-r))-(c=l*r)+o*(u=r-a)+(s=l-o)*a+s*u,f=l+(h=(this._hi-c-f+this._lo-l*i)/r),this._hi=f,this._lo=l-f+h,this}}},{key:"dump",value:function(){return"DD<"+this._hi+", "+this._lo+">"}},{key:"divide",value:function(){if(arguments[0]instanceof e){var t=arguments[0],n=null,r=null,i=null,o=null,s=null,a=null,u=null,l=null;return r=(s=this._hi/t._hi)-(n=(a=e.SPLIT*s)-(n=a-s)),l=n*(i=(l=e.SPLIT*t._hi)-(i=l-t._hi))-(u=s*t._hi)+n*(o=t._hi-i)+r*i+r*o,new e(l=s+(a=(this._hi-u-l+this._lo-s*t._lo)/t._hi),s-l+a)}if("number"==typeof arguments[0]){var h=arguments[0];return A.isNaN(h)?e.createNaN():e.copy(this).selfDivide(h,0)}}},{key:"ge",value:function(t){return this._hi>t._hi||this._hi===t._hi&&this._lo>=t._lo}},{key:"pow",value:function(t){if(0===t)return e.valueOf(1);var n=new e(this),r=e.valueOf(1),i=Math.abs(t);if(i>1)for(;i>0;)i%2==1&&r.selfMultiply(n),(i/=2)>0&&(n=n.sqr());else r=n;return t<0?r.reciprocal():r}},{key:"ceil",value:function(){if(this.isNaN())return e.NaN;var t=Math.ceil(this._hi),n=0;return t===this._hi&&(n=Math.ceil(this._lo)),new e(t,n)}},{key:"compareTo",value:function(t){var e=t;return this._hie._hi?1:this._loe._lo?1:0}},{key:"rint",value:function(){return this.isNaN()?this:this.add(.5).floor()}},{key:"setValue",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.init(t),this}if("number"==typeof arguments[0]){var n=arguments[0];return this.init(n),this}}},{key:"max",value:function(t){return this.ge(t)?this:t}},{key:"sqrt",value:function(){if(this.isZero())return e.valueOf(0);if(this.isNegative())return e.NaN;var t=1/Math.sqrt(this._hi),n=this._hi*t,r=e.valueOf(n),i=this.subtract(r.sqr())._hi*(.5*t);return r.add(i)}},{key:"selfAdd",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfAdd(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0],r=null,i=null,o=null,s=null,a=null,u=null;return s=(o=this._hi+n)-(a=o-this._hi),i=(u=(s=n-a+(this._hi-s))+this._lo)+(o-(r=o+u)),this._hi=r+i,this._lo=i+(r-this._hi),this}}else if(2===arguments.length){var l=arguments[0],h=arguments[1],c=null,f=null,g=null,p=null,v=null,d=null,y=null;p=this._hi+l,f=this._lo+h,v=p-(d=p-this._hi),g=f-(y=f-this._lo);var m=(c=p+(d=(v=l-d+(this._hi-v))+f))+(d=(g=h-y+(this._lo-g))+(d+(p-c))),_=d+(c-m);return this._hi=m,this._lo=_,this}}},{key:"selfMultiply",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfMultiply(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfMultiply(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null;o=(l=e.SPLIT*this._hi)-this._hi,h=e.SPLIT*r,o=l-o,s=this._hi-o,a=h-r;var c=(l=this._hi*r)+(h=o*(a=h-a)-l+o*(u=r-a)+s*a+s*u+(this._hi*i+this._lo*r)),f=h+(o=l-c);return this._hi=c,this._lo=f,this}}},{key:"selfSqr",value:function(){return this.selfMultiply(this)}},{key:"floor",value:function(){if(this.isNaN())return e.NaN;var t=Math.floor(this._hi),n=0;return t===this._hi&&(n=Math.floor(this._lo)),new e(t,n)}},{key:"negate",value:function(){return this.isNaN()?this:new e(-this._hi,-this._lo)}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return null;throw t}}},{key:"multiply",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return t.isNaN()?e.createNaN():e.copy(this).selfMultiply(t)}if("number"==typeof arguments[0]){var n=arguments[0];return A.isNaN(n)?e.createNaN():e.copy(this).selfMultiply(n,0)}}},{key:"isNaN",value:function(){return A.isNaN(this._hi)}},{key:"intValue",value:function(){return Math.trunc(this._hi)}},{key:"toString",value:function(){var t=e.magnitude(this._hi);return t>=-3&&t<=20?this.toStandardNotation():this.toSciNotation()}},{key:"toStandardNotation",value:function(){var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!0,n),i=n[0]+1,o=r;if("."===r.charAt(0))o="0"+r;else if(i<0)o="0."+e.stringOfChar("0",-i)+r;else if(-1===r.indexOf(".")){var s=i-r.length;o=r+e.stringOfChar("0",s)+".0"}return this.isNegative()?"-"+o:o}},{key:"reciprocal",value:function(){var t,n,r,i,o=null,s=null,a=null,u=null;t=(r=1/this._hi)-(o=(a=e.SPLIT*r)-(o=a-r)),s=(u=e.SPLIT*this._hi)-this._hi;var l=r+(a=(1-(i=r*this._hi)-(u=o*(s=u-s)-i+o*(n=this._hi-s)+t*s+t*n)-r*this._lo)/this._hi);return new e(l,r-l+a)}},{key:"toSciNotation",value:function(){if(this.isZero())return e.SCI_NOT_ZERO;var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!1,n),i=e.SCI_NOT_EXPONENT_CHAR+n[0];if("0"===r.charAt(0))throw new IllegalStateException("Found leading zero: "+r);var o="";r.length>1&&(o=r.substring(1));var s=r.charAt(0)+"."+o;return this.isNegative()?"-"+s+i:s+i}},{key:"abs",value:function(){return this.isNaN()?e.NaN:this.isNegative()?this.negate():new e(this)}},{key:"isPositive",value:function(){return this._hi>0||0===this._hi&&this._lo>0}},{key:"lt",value:function(t){return this._hit._hi||this._hi===t._hi&&this._lo>t._lo}},{key:"isNegative",value:function(){return this._hi<0||0===this._hi&&this._lo<0}},{key:"trunc",value:function(){return this.isNaN()?e.NaN:this.isPositive()?this.floor():this.ceil()}},{key:"signum",value:function(){return this._hi>0?1:this._hi<0?-1:this._lo>0?1:this._lo<0?-1:0}},{key:"interfaces_",get:function(){return[w,k,b]}}],[{key:"constructor_",value:function(){if(this._hi=0,this._lo=0,0===arguments.length)this.init(0);else if(1===arguments.length){if("number"==typeof arguments[0]){var t=arguments[0];this.init(t)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}else if("string"==typeof arguments[0]){var r=arguments[0];e.constructor_.call(this,e.parse(r))}}else if(2===arguments.length){var i=arguments[0],o=arguments[1];this.init(i,o)}}},{key:"determinant",value:function(){if("number"==typeof arguments[3]&&"number"==typeof arguments[2]&&"number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1],r=arguments[2],i=arguments[3];return e.determinant(e.valueOf(t),e.valueOf(n),e.valueOf(r),e.valueOf(i))}if(arguments[3]instanceof e&&arguments[2]instanceof e&&arguments[0]instanceof e&&arguments[1]instanceof e){var o=arguments[1],s=arguments[2],a=arguments[3];return arguments[0].multiply(a).selfSubtract(o.multiply(s))}}},{key:"sqr",value:function(t){return e.valueOf(t).selfMultiply(t)}},{key:"valueOf",value:function(){if("string"==typeof arguments[0]){var t=arguments[0];return e.parse(t)}if("number"==typeof arguments[0])return new e(arguments[0])}},{key:"sqrt",value:function(t){return e.valueOf(t).sqrt()}},{key:"parse",value:function(t){for(var n=0,r=t.length;ut.isWhitespace(t.charAt(n));)n++;var i=!1;if(n=r);){var c=t.charAt(n);if(n++,ut.isDigit(c)){var f=c-"0";s.selfMultiply(e.TEN),s.selfAdd(f),a++}else{if("."!==c){if("e"===c||"E"===c){var g=t.substring(n);try{l=at.parseInt(g)}catch(e){throw e instanceof NumberFormatException?new NumberFormatException("Invalid exponent "+g+" in string "+t):e}break}throw new NumberFormatException("Unexpected character '"+c+"' at position "+n+" in string "+t)}u=a,h=!0}}var p=s;h||(u=a);var v=a-u-l;if(0===v)p=s;else if(v>0){var d=e.TEN.pow(v);p=s.divide(d)}else if(v<0){var y=e.TEN.pow(-v);p=s.multiply(y)}return i?p.negate():p}},{key:"createNaN",value:function(){return new e(A.NaN,A.NaN)}},{key:"copy",value:function(t){return new e(t)}},{key:"magnitude",value:function(t){var e=Math.abs(t),n=Math.log(e)/Math.log(10),r=Math.trunc(Math.floor(n));return 10*Math.pow(10,r)<=e&&(r+=1),r}},{key:"stringOfChar",value:function(t,e){for(var n=new st,r=0;r0){if(s<=0)return e.signum(a);i=o+s}else{if(!(o<0))return e.signum(a);if(s>=0)return e.signum(a);i=-o-s}var u=e.DP_SAFE_EPSILON*i;return a>=u||-a>=u?e.signum(a):2}},{key:"signum",value:function(t){return t>0?1:t<0?-1:0}}]),e}();ht.DP_SAFE_EPSILON=1e-15;var ct=function(){function e(){t(this,e)}return n(e,[{key:"getM",value:function(t){if(this.hasM()){var e=this.getDimension()-this.getMeasures();return this.getOrdinate(t,e)}return A.NaN}},{key:"setOrdinate",value:function(t,e,n){}},{key:"getZ",value:function(t){return this.hasZ()?this.getOrdinate(t,2):A.NaN}},{key:"size",value:function(){}},{key:"getOrdinate",value:function(t,e){}},{key:"getCoordinate",value:function(){}},{key:"getCoordinateCopy",value:function(t){}},{key:"createCoordinate",value:function(){}},{key:"getDimension",value:function(){}},{key:"hasM",value:function(){return this.getMeasures()>0}},{key:"getX",value:function(t){}},{key:"hasZ",value:function(){return this.getDimension()-this.getMeasures()>2}},{key:"getMeasures",value:function(){return 0}},{key:"expandEnvelope",value:function(t){}},{key:"copy",value:function(){}},{key:"getY",value:function(t){}},{key:"toCoordinateArray",value:function(){}},{key:"interfaces_",get:function(){return[b]}}]),e}();ct.X=0,ct.Y=1,ct.Z=2,ct.M=3;var ft=function(){function e(){t(this,e)}return n(e,null,[{key:"index",value:function(t,e,n){return ht.orientationIndex(t,e,n)}},{key:"isCCW",value:function(){if(arguments[0]instanceof Array){var t=arguments[0],n=t.length-1;if(n<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var r=t[0],i=0,o=1;o<=n;o++){var s=t[o];s.y>r.y&&(r=s,i=o)}var a=i;do{(a-=1)<0&&(a=n)}while(t[a].equals2D(r)&&a!==i);var u=i;do{u=(u+1)%n}while(t[u].equals2D(r)&&u!==i);var l=t[a],h=t[u];if(l.equals2D(r)||h.equals2D(r)||l.equals2D(h))return!1;var c=e.index(l,r,h);return 0===c?l.x>h.x:c>0}if(ot(arguments[0],ct)){var f=arguments[0],g=f.size()-1;if(g<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var p=f.getCoordinate(0),v=0,d=1;d<=g;d++){var y=f.getCoordinate(d);y.y>p.y&&(p=y,v=d)}var m=null,_=v;do{(_-=1)<0&&(_=g),m=f.getCoordinate(_)}while(m.equals2D(p)&&_!==v);var E=null,k=v;do{k=(k+1)%g,E=f.getCoordinate(k)}while(E.equals2D(p)&&k!==v);if(m.equals2D(p)||E.equals2D(p)||m.equals2D(E))return!1;var b=e.index(m,p,E);return 0===b?m.x>E.x:b>0}}}]),e}();ft.CLOCKWISE=-1,ft.RIGHT=ft.CLOCKWISE,ft.COUNTERCLOCKWISE=1,ft.LEFT=ft.COUNTERCLOCKWISE,ft.COLLINEAR=0,ft.STRAIGHT=ft.COLLINEAR;var gt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this._minCoord}},{key:"getRightmostSide",value:function(t,e){var n=this.getRightmostSideOfSegment(t,e);return n<0&&(n=this.getRightmostSideOfSegment(t,e-1)),n<0&&(this._minCoord=null,this.checkForRightmostCoordinate(t)),n}},{key:"findRightmostEdgeAtVertex",value:function(){var t=this._minDe.getEdge().getCoordinates();V.isTrue(this._minIndex>0&&this._minIndexthis._minCoord.y&&n.y>this._minCoord.y&&r===ft.CLOCKWISE)&&(i=!0),i&&(this._minIndex=this._minIndex-1)}},{key:"getRightmostSideOfSegment",value:function(t,e){var n=t.getEdge().getCoordinates();if(e<0||e+1>=n.length)return-1;if(n[e].y===n[e+1].y)return-1;var r=tt.LEFT;return n[e].ythis._minCoord.x)&&(this._minDe=t,this._minIndex=n,this._minCoord=e[n])}},{key:"findRightmostEdgeAtNode",value:function(){var t=this._minDe.getNode().getEdges();this._minDe=t.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)}},{key:"findEdge",value:function(t){for(var e=t.iterator();e.hasNext();){var n=e.next();n.isForward()&&this.checkForRightmostCoordinate(n)}V.isTrue(0!==this._minIndex||this._minCoord.equals(this._minDe.getCoordinate()),"inconsistency in rightmost processing"),0===this._minIndex?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe,this.getRightmostSide(this._minDe,this._minIndex)===tt.LEFT&&(this._orientedDe=this._minDe.getSym())}}],[{key:"constructor_",value:function(){this._minIndex=-1,this._minCoord=null,this._minDe=null,this._orientedDe=null}}]),e}(),pt=function(e){r(o,e);var i=c(o);function o(e,n){var r;return t(this,o),(r=i.call(this,n?e+" [ "+n+" ]":e)).pt=n?new z(n):void 0,r.name=Object.keys({TopologyException:o})[0],r}return n(o,[{key:"getCoordinate",value:function(){return this.pt}}]),o}(F),vt=function(){function e(){t(this,e),this.array=[]}return n(e,[{key:"addLast",value:function(t){this.array.push(t)}},{key:"removeFirst",value:function(){return this.array.shift()}},{key:"isEmpty",value:function(){return 0===this.array.length}}]),e}(),dt=function(e,i){r(s,e);var o=c(s);function s(e){var n;return t(this,s),(n=o.call(this)).array=[],e instanceof H&&n.addAll(e),n}return n(s,[{key:"interfaces_",get:function(){return[rt,H]}},{key:"ensureCapacity",value:function(){}},{key:"add",value:function(t){return 1===arguments.length?this.array.push(t):this.array.splice(arguments[0],0,arguments[1]),!0}},{key:"clear",value:function(){this.array=[]}},{key:"addAll",value:function(t){var e,n=d(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.array.push(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"set",value:function(t,e){var n=this.array[t];return this.array[t]=e,n}},{key:"iterator",value:function(){return new yt(this)}},{key:"get",value:function(t){if(t<0||t>=this.size())throw new nt;return this.array[t]}},{key:"isEmpty",value:function(){return 0===this.array.length}},{key:"sort",value:function(t){t?this.array.sort((function(e,n){return t.compare(e,n)})):this.array.sort()}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}},{key:"remove",value:function(t){for(var e=0,n=this.array.length;e=1&&e.getDepth(tt.LEFT)<=0&&!e.isInteriorAreaEdge()&&e.setInResult(!0)}}},{key:"computeDepths",value:function(t){var e=new Q,n=new vt,r=t.getNode();for(n.addLast(r),e.add(r),t.setVisited(!0);!n.isEmpty();){var i=n.removeFirst();e.add(i),this.computeNodeDepth(i);for(var o=i.getEdges().iterator();o.hasNext();){var s=o.next().getSym();if(!s.isVisited()){var a=s.getNode();e.contains(a)||(n.addLast(a),e.add(a))}}}}},{key:"compareTo",value:function(t){var e=t;return this._rightMostCoord.xe._rightMostCoord.x?1:0}},{key:"getEnvelope",value:function(){if(null===this._env){for(var t=new X,e=this._dirEdgeList.iterator();e.hasNext();)for(var n=e.next().getEdge().getCoordinates(),r=0;re.x?t.x:e.x,a=t.y>e.y?t.y:e.y,u=n.xr.x?n.x:r.x,c=n.y>r.y?n.y:r.y,f=((i>u?i:u)+(sl?o:l)+(an?n:t}if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var r=arguments[0],i=arguments[1],o=arguments[2];return ro?o:r}}},{key:"wrap",value:function(t,e){return t<0?e- -t%e:t%e}},{key:"max",value:function(){if(3===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[0];return t>n&&(n=t),e>n&&(n=e),n}if(4===arguments.length){var r=arguments[1],i=arguments[2],o=arguments[3],s=arguments[0];return r>s&&(s=r),i>s&&(s=i),o>s&&(s=o),s}}},{key:"average",value:function(t,e){return(t+e)/2}}]),e}();Et.LOG_10=Math.log(10);var kt=function(){function e(){t(this,e)}return n(e,null,[{key:"segmentToSegment",value:function(t,n,r,i){if(t.equals(n))return e.pointToSegment(t,r,i);if(r.equals(i))return e.pointToSegment(i,t,n);var o=!1;if(X.intersects(t,n,r,i)){var s=(n.x-t.x)*(i.y-r.y)-(n.y-t.y)*(i.x-r.x);if(0===s)o=!0;else{var a=(t.y-r.y)*(i.x-r.x)-(t.x-r.x)*(i.y-r.y),u=((t.y-r.y)*(n.x-t.x)-(t.x-r.x)*(n.y-t.y))/s,l=a/s;(l<0||l>1||u<0||u>1)&&(o=!0)}}else o=!0;return o?Et.min(e.pointToSegment(t,r,i),e.pointToSegment(n,r,i),e.pointToSegment(r,t,n),e.pointToSegment(i,t,n)):0}},{key:"pointToSegment",value:function(t,e,n){if(e.x===n.x&&e.y===n.y)return t.distance(e);var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/r;if(i<=0)return t.distance(e);if(i>=1)return t.distance(n);var o=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(o)*Math.sqrt(r)}},{key:"pointToLinePerpendicular",value:function(t,e,n){var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(i)*Math.sqrt(r)}},{key:"pointToSegmentString",value:function(t,n){if(0===n.length)throw new x("Line array must contain at least one vertex");for(var r=t.distance(n[0]),i=0;i0)&&(o=a,i=s)}return i}}},{key:"extend",value:function(t,n,r){var i=t.create(r,n.getDimension()),o=n.size();if(e.copy(n,0,i,0,o),o>0)for(var s=o;s0)&&(e=r)}return e}}]),e}(),Mt=function(){function e(){t(this,e)}return n(e,null,[{key:"toDimensionSymbol",value:function(t){switch(t){case e.FALSE:return e.SYM_FALSE;case e.TRUE:return e.SYM_TRUE;case e.DONTCARE:return e.SYM_DONTCARE;case e.P:return e.SYM_P;case e.L:return e.SYM_L;case e.A:return e.SYM_A}throw new x("Unknown dimension value: "+t)}},{key:"toDimensionValue",value:function(t){switch(ut.toUpperCase(t)){case e.SYM_FALSE:return e.FALSE;case e.SYM_TRUE:return e.TRUE;case e.SYM_DONTCARE:return e.DONTCARE;case e.SYM_P:return e.P;case e.SYM_L:return e.L;case e.SYM_A:return e.A}throw new x("Unknown dimension symbol: "+t)}}]),e}();Mt.P=0,Mt.L=1,Mt.A=2,Mt.FALSE=-1,Mt.TRUE=-2,Mt.DONTCARE=-3,Mt.SYM_FALSE="F",Mt.SYM_TRUE="T",Mt.SYM_DONTCARE="*",Mt.SYM_P="0",Mt.SYM_L="1",Mt.SYM_A="2";var Lt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}(),Pt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t,e){}},{key:"isDone",value:function(){}},{key:"isGeometryChanged",value:function(){}}]),e}(),Ct=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"computeEnvelopeInternal",value:function(){return this.isEmpty()?new X:this._points.expandEnvelope(new X)}},{key:"isRing",value:function(){return this.isClosed()&&this.isSimple()}},{key:"getCoordinates",value:function(){return this._points.toCoordinateArray()}},{key:"copyInternal",value:function(){return new s(this._points.copy(),this._factory)}},{key:"equalsExact",value:function(){if(2===arguments.length&&"number"==typeof arguments[1]&&arguments[0]instanceof U){var t=arguments[0],e=arguments[1];if(!this.isEquivalentClass(t))return!1;var n=t;if(this._points.size()!==n._points.size())return!1;for(var r=0;r0){var n=this._points.copy();St.reverse(n),this._points=n}return null}}}},{key:"getCoordinate",value:function(){return this.isEmpty()?null:this._points.getCoordinate(0)}},{key:"getBoundaryDimension",value:function(){return this.isClosed()?Mt.FALSE:0}},{key:"isClosed",value:function(){return!this.isEmpty()&&this.getCoordinateN(0).equals2D(this.getCoordinateN(this.getNumPoints()-1))}},{key:"reverseInternal",value:function(){var t=this._points.copy();return St.reverse(t),this.getFactory().createLineString(t)}},{key:"getEndPoint",value:function(){return this.isEmpty()?null:this.getPointN(this.getNumPoints()-1)}},{key:"getTypeCode",value:function(){return U.TYPECODE_LINESTRING}},{key:"getDimension",value:function(){return 1}},{key:"getLength",value:function(){return It.ofLine(this._points)}},{key:"getNumPoints",value:function(){return this._points.size()}},{key:"compareToSameClass",value:function(){if(1===arguments.length){for(var t=arguments[0],e=0,n=0;e= 2)");this._points=t}},{key:"isCoordinate",value:function(t){for(var e=0;e=1&&this.getCoordinateSequence().size()= 4)")}},{key:"getGeometryType",value:function(){return U.TYPENAME_LINEARRING}}],[{key:"constructor_",value:function(){var t=arguments[0],e=arguments[1];Ct.constructor_.call(this,t,e),this.validateConstruction()}}]),s}(Ct);zt.MINIMUM_VALID_SIZE=4;var jt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}}],[{key:"constructor_",value:function(){if(0===arguments.length)z.constructor_.call(this);else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y)}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y)}}else if(2===arguments.length){var n=arguments[0],r=arguments[1];z.constructor_.call(this,n,r,z.NULL_ORDINATE)}}}]),o}(z);jt.X=0,jt.Y=1,jt.Z=-1,jt.M=-1;var Xt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;case o.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y;case o.M:return this._m}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y),this._m=this.getM()}}else if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2];z.constructor_.call(this,n,r,z.NULL_ORDINATE),this._m=i}}}]),o}(z);Xt.X=0,Xt.Y=1,Xt.Z=-1,Xt.M=2;var Ut=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case z.X:this.x=e;break;case z.Y:this.y=e;break;case z.Z:this.z=e;break;case z.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getOrdinate",value:function(t){switch(t){case z.X:return this.x;case z.Y:return this.y;case z.Z:return this.getZ();case z.M:return this.getM()}throw new x("Invalid ordinate index: "+t)}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e),this._m=this.getM()}}else if(4===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],s=arguments[3];z.constructor_.call(this,n,r,i),this._m=s}}}]),o}(z),Zt=function(){function e(){t(this,e)}return n(e,null,[{key:"measures",value:function(t){return t instanceof jt?0:t instanceof Xt||t instanceof Ut?1:0}},{key:"dimension",value:function(t){return t instanceof jt?2:t instanceof Xt?3:t instanceof Ut?4:3}},{key:"create",value:function(){if(1===arguments.length){var t=arguments[0];return e.create(t,0)}if(2===arguments.length){var n=arguments[0],r=arguments[1];return 2===n?new jt:3===n&&0===r?new z:3===n&&1===r?new Xt:4===n&&1===r?new Ut:new z}}}]),e}(),Ht=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getCoordinate",value:function(t){return this.get(t)}},{key:"addAll",value:function(){if(2===arguments.length&&"boolean"==typeof arguments[1]&&ot(arguments[0],H)){for(var t=arguments[1],e=!1,n=arguments[0].iterator();n.hasNext();)this.add(n.next(),t),e=!0;return e}return f(i(s.prototype),"addAll",this).apply(this,arguments)}},{key:"clone",value:function(){for(var t=f(i(s.prototype),"clone",this).call(this),e=0;e=1&&this.get(this.size()-1).equals2D(r))return null;f(i(s.prototype),"add",this).call(this,r)}else if(arguments[0]instanceof Object&&"boolean"==typeof arguments[1]){var o=arguments[0],a=arguments[1];return this.add(o,a),!0}}else if(3===arguments.length){if("boolean"==typeof arguments[2]&&arguments[0]instanceof Array&&"boolean"==typeof arguments[1]){var u=arguments[0],l=arguments[1];if(arguments[2])for(var h=0;h=0;c--)this.add(u[c],l);return!0}if("boolean"==typeof arguments[2]&&Number.isInteger(arguments[0])&&arguments[1]instanceof z){var g=arguments[0],p=arguments[1];if(!arguments[2]){var v=this.size();if(v>0){if(g>0&&this.get(g-1).equals2D(p))return null;if(g_&&(x=-1);for(var E=m;E!==_;E+=x)this.add(d[E],y);return!0}}},{key:"closeRing",value:function(){if(this.size()>0){var t=this.get(0).copy();this.add(t,!1)}}}],[{key:"constructor_",value:function(){if(0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.ensureCapacity(t.length),this.add(t,!0)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this.ensureCapacity(e.length),this.add(e,n)}}}]),s}(dt);Ht.coordArrayType=new Array(0).fill(null);var Wt=function(){function e(){t(this,e)}return n(e,null,[{key:"isRing",value:function(t){return!(t.length<4||!t[0].equals2D(t[t.length-1]))}},{key:"ptNotInList",value:function(t,n){for(var r=0;r=t?e:[]}},{key:"indexOf",value:function(t,e){for(var n=0;n0)&&(e=t[n]);return e}},{key:"extract",value:function(t,e,n){e=Et.clamp(e,0,t.length);var r=(n=Et.clamp(n,-1,t.length))-e+1;n<0&&(r=0),e>=t.length&&(r=0),nr.length)return 1;if(0===n.length)return 0;var i=Wt.compare(n,r);return Wt.isEqualReversed(n,r)?0:i}},{key:"OLDcompare",value:function(t,e){var n=t,r=e;if(n.lengthr.length)return 1;if(0===n.length)return 0;for(var i=Wt.increasingDirection(n),o=Wt.increasingDirection(r),s=i>0?0:n.length-1,a=o>0?0:n.length-1,u=0;u0){var t=new Qt(17*this._coordinates.length);t.append("("),t.append(this._coordinates[0]);for(var e=1;e3&&(t=3),t<2&&(t=2),new $t(arguments[0],t)}if(3===arguments.length){var e=arguments[2],n=arguments[1]-e;return e>1&&(e=1),n>3&&(n=3),n<2&&(n=2),new $t(arguments[0],n+e,e)}}}},{key:"interfaces_",get:function(){return[bt,w]}}],[{key:"instance",value:function(){return e.instanceObject}}]),e}();te.instanceObject=new te;var ee=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e=0?t:e}}]),e}(),oe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"readResolve",value:function(){return e.nameToTypeMap.get(this._name)}},{key:"toString",value:function(){return this._name}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){this._name=null;var t=arguments[0];this._name=t,e.nameToTypeMap.put(t,this)}}]),e}();oe.nameToTypeMap=new re,ie.Type=oe,ie.FIXED=new oe("FIXED"),ie.FLOATING=new oe("FLOATING"),ie.FLOATING_SINGLE=new oe("FLOATING SINGLE"),ie.maximumPreciseValue=9007199254740992;var se=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e1){if(u instanceof Ft)return this.createMultiPolygon(e.toPolygonArray(t));if(u instanceof Ct)return this.createMultiLineString(e.toLineStringArray(t));if(u instanceof Ot)return this.createMultiPoint(e.toPointArray(t));V.shouldNeverReachHere("Unhandled geometry type: "+u.getGeometryType())}return u}},{key:"createMultiPointFromCoords",value:function(t){return this.createMultiPoint(null!==t?this.getCoordinateSequenceFactory().create(t):null)}},{key:"createPoint",value:function(){if(0===arguments.length)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];return this.createPoint(null!==t?this.getCoordinateSequenceFactory().create([t]):null)}if(ot(arguments[0],ct))return new Ot(arguments[0],this)}}},{key:"getCoordinateSequenceFactory",value:function(){return this._coordinateSequenceFactory}},{key:"createPolygon",value:function(){if(0===arguments.length)return this.createPolygon(null,null);if(1===arguments.length){if(ot(arguments[0],ct)){var t=arguments[0];return this.createPolygon(this.createLinearRing(t))}if(arguments[0]instanceof Array){var e=arguments[0];return this.createPolygon(this.createLinearRing(e))}if(arguments[0]instanceof zt){var n=arguments[0];return this.createPolygon(n,null)}}else if(2===arguments.length)return new Ft(arguments[0],arguments[1],this)}},{key:"getSRID",value:function(){return this._SRID}},{key:"createGeometryCollection",value:function(){return 0===arguments.length?new Bt(null,this):1===arguments.length?new Bt(arguments[0],this):void 0}},{key:"getPrecisionModel",value:function(){return this._precisionModel}},{key:"createLinearRing",value:function(){if(0===arguments.length)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof Array){var t=arguments[0];return this.createLinearRing(null!==t?this.getCoordinateSequenceFactory().create(t):null)}if(ot(arguments[0],ct))return new zt(arguments[0],this)}}},{key:"createMultiPolygon",value:function(){return 0===arguments.length?new ee(null,this):1===arguments.length?new ee(arguments[0],this):void 0}},{key:"createMultiPoint",value:function(){if(0===arguments.length)return new Yt(null,this);if(1===arguments.length){if(arguments[0]instanceof Array)return new Yt(arguments[0],this);if(ot(arguments[0],ct)){var t=arguments[0];if(null===t)return this.createMultiPoint(new Array(0).fill(null));for(var e=new Array(t.size()).fill(null),n=0;n="a"&&t<="z"||t>="A"&&t<="Z"}},{key:"isNumeric_",value:function(t,e){return t>="0"&&t<="9"||"."==t&&!(void 0!==e&&e)}},{key:"isWhiteSpace_",value:function(t){return" "==t||"\t"==t||"\r"==t||"\n"==t}},{key:"nextChar_",value:function(){return this.wkt.charAt(++this.index_)}},{key:"nextToken",value:function(){var t,e=this.nextChar_(),n=this.index_,r=e;if("("==e)t=ve;else if(","==e)t=me;else if(")"==e)t=de;else if(this.isNumeric_(e)||"-"==e)t=ye,r=this.readNumber_();else if(this.isAlpha_(e))t=pe,r=this.readText_();else{if(this.isWhiteSpace_(e))return this.nextToken();if(""!==e)throw new Error("Unexpected character: "+e);t=_e}return{position:n,value:r,type:t}}},{key:"readNumber_",value:function(){var t,e=this.index_,n=!1,r=!1;do{"."==t?n=!0:"e"!=t&&"E"!=t||(r=!0),t=this.nextChar_()}while(this.isNumeric_(t,n)||!r&&("e"==t||"E"==t)||r&&("-"==t||"+"==t));return parseFloat(this.wkt.substring(e,this.index_--))}},{key:"readText_",value:function(){var t,e=this.index_;do{t=this.nextChar_()}while(this.isAlpha_(t));return this.wkt.substring(e,this.index_--).toUpperCase()}}]),e}(),ke=function(){function e(n,r){t(this,e),this.lexer_=n,this.token_,this.layout_=ue,this.factory=r}return n(e,[{key:"consume_",value:function(){this.token_=this.lexer_.nextToken()}},{key:"isTokenType",value:function(t){return this.token_.type==t}},{key:"match",value:function(t){var e=this.isTokenType(t);return e&&this.consume_(),e}},{key:"parse",value:function(){return this.consume_(),this.parseGeometry_()}},{key:"parseGeometryLayout_",value:function(){var t=ue,e=this.token_;if(this.isTokenType(pe)){var n=e.value;"Z"===n?t=le:"M"===n?t=he:"ZM"===n&&(t=ce),t!==ue&&this.consume_()}return t}},{key:"parseGeometryCollectionText_",value:function(){if(this.match(ve)){var t=[];do{t.push(this.parseGeometry_())}while(this.match(me));if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePointText_",value:function(){if(this.match(ve)){var t=this.parsePoint_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return null;throw new Error(this.formatErrorMessage_())}},{key:"parseLineStringText_",value:function(){if(this.match(ve)){var t=this.parsePointList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePolygonText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPointText_",value:function(){var t;if(this.match(ve)){if(t=this.token_.type==ve?this.parsePointTextList_():this.parsePointList_(),this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiLineStringText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPolygonText_",value:function(){if(this.match(ve)){var t=this.parsePolygonTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePoint_",value:function(){for(var t=[],e=this.layout_.length,n=0;n1?t.createPolygon(r[0],r.slice(1)):t.createPolygon(r[0])},r=this.token_;if(this.match(pe)){var i=r.value;if(this.layout_=this.parseGeometryLayout_(),"GEOMETRYCOLLECTION"==i){var o=this.parseGeometryCollectionText_();return t.createGeometryCollection(o)}switch(i){case"POINT":var s=this.parsePointText_();return s?t.createPoint(a(z,g(s))):t.createPoint();case"LINESTRING":var u=this.parseLineStringText_().map(e);return t.createLineString(u);case"LINEARRING":var l=this.parseLineStringText_().map(e);return t.createLinearRing(l);case"POLYGON":var h=this.parsePolygonText_();return h&&0!==h.length?n(h):t.createPolygon();case"MULTIPOINT":var c=this.parseMultiPointText_();if(!c||0===c.length)return t.createMultiPoint();var f=c.map(e).map((function(e){return t.createPoint(e)}));return t.createMultiPoint(f);case"MULTILINESTRING":var p=this.parseMultiLineStringText_().map((function(n){return t.createLineString(n.map(e))}));return t.createMultiLineString(p);case"MULTIPOLYGON":var v=this.parseMultiPolygonText_();if(!v||0===v.length)return t.createMultiPolygon();var d=v.map(n);return t.createMultiPolygon(d);default:throw new Error("Invalid geometry type: "+i)}}throw new Error(this.formatErrorMessage_())}}]),e}();function be(t){if(t.isEmpty())return"";var e=t.getCoordinate(),n=[e.x,e.y];return void 0===e.z||Number.isNaN(e.z)||n.push(e.z),void 0===e.m||Number.isNaN(e.m)||n.push(e.m),n.join(" ")}function we(t){for(var e=t.getCoordinates().map((function(t){var e=[t.x,t.y];return void 0===t.z||Number.isNaN(t.z)||e.push(t.z),void 0===t.m||Number.isNaN(t.m)||e.push(t.m),e})),n=[],r=0,i=e.length;r0&&(e+=" "+r),t.isEmpty()?e+" "+ge:e+" ("+n(t)+")"}var Me=function(){function e(n){t(this,e),this.geometryFactory=n||new ae,this.precisionModel=this.geometryFactory.getPrecisionModel()}return n(e,[{key:"read",value:function(t){var e=new Ee(t);return new ke(e,this.geometryFactory).parse()}},{key:"write",value:function(t){return Se(t)}}]),e}(),Le=function(){function e(n){t(this,e),this.parser=new Me(n)}return n(e,[{key:"write",value:function(t){return this.parser.write(t)}}],[{key:"toLineString",value:function(t,e){if(2!==arguments.length)throw new Error("Not implemented");return"LINESTRING ( "+t.x+" "+t.y+", "+e.x+" "+e.y+" )"}}]),e}(),Pe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getIndexAlongSegment",value:function(t,e){return this.computeIntLineIndex(),this._intLineIndex[t][e]}},{key:"getTopologySummary",value:function(){var t=new Qt;return this.isEndPoint()&&t.append(" endpoint"),this._isProper&&t.append(" proper"),this.isCollinear()&&t.append(" collinear"),t.toString()}},{key:"computeIntersection",value:function(t,e,n,r){this._inputLines[0][0]=t,this._inputLines[0][1]=e,this._inputLines[1][0]=n,this._inputLines[1][1]=r,this._result=this.computeIntersect(t,e,n,r)}},{key:"getIntersectionNum",value:function(){return this._result}},{key:"computeIntLineIndex",value:function(){if(0===arguments.length)null===this._intLineIndex&&(this._intLineIndex=Array(2).fill().map((function(){return Array(2)})),this.computeIntLineIndex(0),this.computeIntLineIndex(1));else if(1===arguments.length){var t=arguments[0];this.getEdgeDistance(t,0)>this.getEdgeDistance(t,1)?(this._intLineIndex[t][0]=0,this._intLineIndex[t][1]=1):(this._intLineIndex[t][0]=1,this._intLineIndex[t][1]=0)}}},{key:"isProper",value:function(){return this.hasIntersection()&&this._isProper}},{key:"setPrecisionModel",value:function(t){this._precisionModel=t}},{key:"isInteriorIntersection",value:function(){if(0===arguments.length)return!!this.isInteriorIntersection(0)||!!this.isInteriorIntersection(1);if(1===arguments.length){for(var t=arguments[0],e=0;ei?r:i;else{var s=Math.abs(t.x-e.x),a=Math.abs(t.y-e.y);0!==(o=r>i?s:a)||t.equals(e)||(o=Math.max(s,a))}return V.isTrue(!(0===o&&!t.equals(e)),"Bad distance calculation"),o}},{key:"nonRobustComputeEdgeDistance",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y,o=Math.sqrt(r*r+i*i);return V.isTrue(!(0===o&&!t.equals(e)),"Invalid distance calculation"),o}}]),e}();Pe.DONT_INTERSECT=0,Pe.DO_INTERSECT=1,Pe.COLLINEAR=2,Pe.NO_INTERSECTION=0,Pe.POINT_INTERSECTION=1,Pe.COLLINEAR_INTERSECTION=2;var Ce=function(e){r(s,e);var o=c(s);function s(){return t(this,s),o.call(this)}return n(s,[{key:"isInSegmentEnvelopes",value:function(t){var e=new X(this._inputLines[0][0],this._inputLines[0][1]),n=new X(this._inputLines[1][0],this._inputLines[1][1]);return e.contains(t)&&n.contains(t)}},{key:"computeIntersection",value:function(){if(3!==arguments.length)return f(i(s.prototype),"computeIntersection",this).apply(this,arguments);var t=arguments[0],e=arguments[1],n=arguments[2];if(this._isProper=!1,X.intersects(e,n,t)&&0===ft.index(e,n,t)&&0===ft.index(n,e,t))return this._isProper=!0,(t.equals(e)||t.equals(n))&&(this._isProper=!1),this._result=Pe.POINT_INTERSECTION,null;this._result=Pe.NO_INTERSECTION}},{key:"intersection",value:function(t,e,n,r){var i=this.intersectionSafe(t,e,n,r);return this.isInSegmentEnvelopes(i)||(i=new z(s.nearestEndpoint(t,e,n,r))),null!==this._precisionModel&&this._precisionModel.makePrecise(i),i}},{key:"checkDD",value:function(t,e,n,r,i){var o=ht.intersection(t,e,n,r),s=this.isInSegmentEnvelopes(o);xt.out.println("DD in env = "+s+" --------------------- "+o),i.distance(o)>1e-4&&xt.out.println("Distance = "+i.distance(o))}},{key:"intersectionSafe",value:function(t,e,n,r){var i=_t.intersection(t,e,n,r);return null===i&&(i=s.nearestEndpoint(t,e,n,r)),i}},{key:"computeCollinearIntersection",value:function(t,e,n,r){var i=X.intersects(t,e,n),o=X.intersects(t,e,r),s=X.intersects(n,r,t),a=X.intersects(n,r,e);return i&&o?(this._intPt[0]=n,this._intPt[1]=r,Pe.COLLINEAR_INTERSECTION):s&&a?(this._intPt[0]=t,this._intPt[1]=e,Pe.COLLINEAR_INTERSECTION):i&&s?(this._intPt[0]=n,this._intPt[1]=t,!n.equals(t)||o||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):i&&a?(this._intPt[0]=n,this._intPt[1]=e,!n.equals(e)||o||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&s?(this._intPt[0]=r,this._intPt[1]=t,!r.equals(t)||i||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&a?(this._intPt[0]=r,this._intPt[1]=e,!r.equals(e)||i||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):Pe.NO_INTERSECTION}},{key:"computeIntersect",value:function(t,e,n,r){if(this._isProper=!1,!X.intersects(t,e,n,r))return Pe.NO_INTERSECTION;var i=ft.index(t,e,n),o=ft.index(t,e,r);if(i>0&&o>0||i<0&&o<0)return Pe.NO_INTERSECTION;var s=ft.index(n,r,t),a=ft.index(n,r,e);return s>0&&a>0||s<0&&a<0?Pe.NO_INTERSECTION:0===i&&0===o&&0===s&&0===a?this.computeCollinearIntersection(t,e,n,r):(0===i||0===o||0===s||0===a?(this._isProper=!1,t.equals2D(n)||t.equals2D(r)?this._intPt[0]=t:e.equals2D(n)||e.equals2D(r)?this._intPt[0]=e:0===i?this._intPt[0]=new z(n):0===o?this._intPt[0]=new z(r):0===s?this._intPt[0]=new z(t):0===a&&(this._intPt[0]=new z(e))):(this._isProper=!0,this._intPt[0]=this.intersection(t,e,n,r)),Pe.POINT_INTERSECTION)}}],[{key:"nearestEndpoint",value:function(t,e,n,r){var i=t,o=kt.pointToSegment(t,n,r),s=kt.pointToSegment(e,n,r);return sr&&(n=e.x,r=t.x),this._p.x>=n&&this._p.x<=r&&(this._isPointOnSegment=!0),null}if(t.y>this._p.y&&e.y<=this._p.y||e.y>this._p.y&&t.y<=this._p.y){var i=ft.index(t,e,this._p);if(i===ft.COLLINEAR)return this._isPointOnSegment=!0,null;e.ythis.location.length){var e=new Array(3).fill(null);e[tt.ON]=this.location[tt.ON],e[tt.LEFT]=Z.NONE,e[tt.RIGHT]=Z.NONE,this.location=e}for(var n=0;n1&&t.append(Z.toLocationSymbol(this.location[tt.LEFT])),t.append(Z.toLocationSymbol(this.location[tt.ON])),this.location.length>1&&t.append(Z.toLocationSymbol(this.location[tt.RIGHT])),t.toString()}},{key:"setLocations",value:function(t,e,n){this.location[tt.ON]=t,this.location[tt.LEFT]=e,this.location[tt.RIGHT]=n}},{key:"get",value:function(t){return t1}},{key:"isAnyNull",value:function(){for(var t=0;tthis._maxNodeDegree&&(this._maxNodeDegree=e),t=this.getNext(t)}while(t!==this._startDe);this._maxNodeDegree*=2}},{key:"addPoints",value:function(t,e,n){var r=t.getCoordinates();if(e){var i=1;n&&(i=0);for(var o=i;o=0;a--)this._pts.add(r[a])}}},{key:"isHole",value:function(){return this._isHole}},{key:"setInResult",value:function(){var t=this._startDe;do{t.getEdge().setInResult(!0),t=t.getNext()}while(t!==this._startDe)}},{key:"containsPoint",value:function(t){var e=this.getLinearRing();if(!e.getEnvelopeInternal().contains(t))return!1;if(!Oe.isInRing(t,e.getCoordinates()))return!1;for(var n=this._holes.iterator();n.hasNext();)if(n.next().containsPoint(t))return!1;return!0}},{key:"addHole",value:function(t){this._holes.add(t)}},{key:"isShell",value:function(){return null===this._shell}},{key:"getLabel",value:function(){return this._label}},{key:"getEdges",value:function(){return this._edges}},{key:"getMaxNodeDegree",value:function(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree}},{key:"getShell",value:function(){return this._shell}},{key:"mergeLabel",value:function(){if(1===arguments.length){var t=arguments[0];this.mergeLabel(t,0),this.mergeLabel(t,1)}else if(2===arguments.length){var e=arguments[1],n=arguments[0].getLocation(e,tt.RIGHT);if(n===Z.NONE)return null;if(this._label.getLocation(e)===Z.NONE)return this._label.setLocation(e,n),null}}},{key:"setShell",value:function(t){this._shell=t,null!==t&&t.addHole(this)}},{key:"toPolygon",value:function(t){for(var e=new Array(this._holes.size()).fill(null),n=0;n=2,"found partial label"),this.computeIM(t)}},{key:"isInResult",value:function(){return this._isInResult}},{key:"isVisited",value:function(){return this._isVisited}}],[{key:"constructor_",value:function(){if(this._label=null,this._isInResult=!1,this._isCovered=!1,this._isCoveredSet=!1,this._isVisited=!1,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._label=t}}}]),e}(),Ge=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isIncidentEdgeInResult",value:function(){for(var t=this.getEdges().getEdges().iterator();t.hasNext();)if(t.next().getEdge().isInResult())return!0;return!1}},{key:"isIsolated",value:function(){return 1===this._label.getGeometryCount()}},{key:"getCoordinate",value:function(){return this._coord}},{key:"print",value:function(t){t.println("node "+this._coord+" lbl: "+this._label)}},{key:"computeIM",value:function(t){}},{key:"computeMergedLocation",value:function(t,e){var n=Z.NONE;if(n=this._label.getLocation(e),!t.isNull(e)){var r=t.getLocation(e);n!==Z.BOUNDARY&&(n=r)}return n}},{key:"setLabel",value:function(){if(2!==arguments.length||!Number.isInteger(arguments[1])||!Number.isInteger(arguments[0]))return f(i(s.prototype),"setLabel",this).apply(this,arguments);var t=arguments[0],e=arguments[1];null===this._label?this._label=new Ae(t,e):this._label.setLocation(t,e)}},{key:"getEdges",value:function(){return this._edges}},{key:"mergeLabel",value:function(){if(arguments[0]instanceof s){var t=arguments[0];this.mergeLabel(t._label)}else if(arguments[0]instanceof Ae)for(var e=arguments[0],n=0;n<2;n++){var r=this.computeMergedLocation(e,n);this._label.getLocation(n)===Z.NONE&&this._label.setLocation(n,r)}}},{key:"add",value:function(t){this._edges.insert(t),t.setNode(this)}},{key:"setLabelBoundary",value:function(t){if(null===this._label)return null;var e=Z.NONE;null!==this._label&&(e=this._label.getLocation(t));var n=null;switch(e){case Z.BOUNDARY:n=Z.INTERIOR;break;case Z.INTERIOR:default:n=Z.BOUNDARY}this._label.setLocation(t,n)}}],[{key:"constructor_",value:function(){this._coord=null,this._edges=null;var t=arguments[0],e=arguments[1];this._coord=t,this._edges=e,this._label=new Ae(0,Z.NONE)}}]),s}(Ve),Be=function(e){r(i,e);var n=c(i);function i(){return t(this,i),n.apply(this,arguments)}return i}(ne);function Ye(t){return null==t?0:t.color}function ze(t){return null==t?null:t.parent}function je(t,e){null!==t&&(t.color=e)}function Xe(t){return null==t?null:t.left}function Ue(t){return null==t?null:t.right}var Ze=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),(e=i.call(this)).root_=null,e.size_=0,e}return n(o,[{key:"get",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return e.value;e=e.right}}return null}},{key:"put",value:function(t,e){if(null===this.root_)return this.root_={key:t,value:e,left:null,right:null,parent:null,color:0,getValue:function(){return this.value},getKey:function(){return this.key}},this.size_=1,null;var n,r,i=this.root_;do{if(n=i,(r=t.compareTo(i.key))<0)i=i.left;else{if(!(r>0)){var o=i.value;return i.value=e,o}i=i.right}}while(null!==i);var s={key:t,left:null,right:null,value:e,parent:n,color:0,getValue:function(){return this.value},getKey:function(){return this.key}};return r<0?n.left=s:n.right=s,this.fixAfterInsertion(s),this.size_++,null}},{key:"fixAfterInsertion",value:function(t){var e;for(t.color=1;null!=t&&t!==this.root_&&1===t.parent.color;)ze(t)===Xe(ze(ze(t)))?1===Ye(e=Ue(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Ue(ze(t))&&(t=ze(t),this.rotateLeft(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateRight(ze(ze(t)))):1===Ye(e=Xe(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Xe(ze(t))&&(t=ze(t),this.rotateRight(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateLeft(ze(ze(t))));this.root_.color=0}},{key:"values",value:function(){var t=new dt,e=this.getFirstEntry();if(null!==e)for(t.add(e.value);null!==(e=o.successor(e));)t.add(e.value);return t}},{key:"entrySet",value:function(){var t=new Q,e=this.getFirstEntry();if(null!==e)for(t.add(e);null!==(e=o.successor(e));)t.add(e);return t}},{key:"rotateLeft",value:function(t){if(null!=t){var e=t.right;t.right=e.left,null!=e.left&&(e.left.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.left===t?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}}},{key:"rotateRight",value:function(t){if(null!=t){var e=t.left;t.left=e.right,null!=e.right&&(e.right.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.right===t?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}}},{key:"getFirstEntry",value:function(){var t=this.root_;if(null!=t)for(;null!=t.left;)t=t.left;return t}},{key:"size",value:function(){return this.size_}},{key:"containsKey",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return!0;e=e.right}}return!1}}],[{key:"successor",value:function(t){var e;if(null===t)return null;if(null!==t.right){for(e=t.right;null!==e.left;)e=e.left;return e}e=t.parent;for(var n=t;null!==e&&n===e.right;)n=e,e=e.parent;return e}}]),o}(Be),He=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"find",value:function(t){return this.nodeMap.get(t)}},{key:"addNode",value:function(){if(arguments[0]instanceof z){var t=arguments[0],e=this.nodeMap.get(t);return null===e&&(e=this.nodeFact.createNode(t),this.nodeMap.put(t,e)),e}if(arguments[0]instanceof Ge){var n=arguments[0],r=this.nodeMap.get(n.getCoordinate());return null===r?(this.nodeMap.put(n.getCoordinate(),n),n):(r.mergeLabel(n),r)}}},{key:"print",value:function(t){for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this.nodeMap.values().iterator()}},{key:"values",value:function(){return this.nodeMap.values()}},{key:"getBoundaryNodes",value:function(t){for(var e=new dt,n=this.iterator();n.hasNext();){var r=n.next();r.getLabel().getLocation(t)===Z.BOUNDARY&&e.add(r)}return e}},{key:"add",value:function(t){var e=t.getCoordinate();this.addNode(e).add(t)}}],[{key:"constructor_",value:function(){this.nodeMap=new Ze,this.nodeFact=null;var t=arguments[0];this.nodeFact=t}}]),e}(),We=function(){function e(){t(this,e)}return n(e,null,[{key:"isNorthern",value:function(t){return t===e.NE||t===e.NW}},{key:"isOpposite",value:function(t,e){return t!==e&&2==(t-e+4)%4}},{key:"commonHalfPlane",value:function(t,e){if(t===e)return t;if(2==(t-e+4)%4)return-1;var n=te?t:e)?3:n}},{key:"isInHalfPlane",value:function(t,n){return n===e.SE?t===e.SE||t===e.SW:t===n||t===n+1}},{key:"quadrant",value:function(){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1];if(0===t&&0===n)throw new x("Cannot compute the quadrant for point ( "+t+", "+n+" )");return t>=0?n>=0?e.NE:e.SE:n>=0?e.NW:e.SW}if(arguments[0]instanceof z&&arguments[1]instanceof z){var r=arguments[0],i=arguments[1];if(i.x===r.x&&i.y===r.y)throw new x("Cannot compute the quadrant for two identical points "+r);return i.x>=r.x?i.y>=r.y?e.NE:e.SE:i.y>=r.y?e.NW:e.SW}}}]),e}();We.NE=0,We.NW=1,We.SW=2,We.SE=3;var Je=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareDirection",value:function(t){return this._dx===t._dx&&this._dy===t._dy?0:this._quadrant>t._quadrant?1:this._quadrant2){o.linkDirectedEdgesForMinimalEdgeRings();var s=o.buildMinimalRings(),a=this.findShell(s);null!==a?(this.placePolygonHoles(a,s),e.add(a)):n.addAll(s)}else r.add(o)}return r}},{key:"buildMaximalEdgeRings",value:function(t){for(var e=new dt,n=t.iterator();n.hasNext();){var r=n.next();if(r.isInResult()&&r.getLabel().isArea()&&null===r.getEdgeRing()){var i=new qe(r,this._geometryFactory);e.add(i),i.setInResult()}}return e}},{key:"placePolygonHoles",value:function(t,e){for(var n=e.iterator();n.hasNext();){var r=n.next();r.isHole()&&r.setShell(t)}}},{key:"getPolygons",value:function(){return this.computePolygons(this._shellList)}},{key:"findShell",value:function(t){for(var e=0,n=null,r=t.iterator();r.hasNext();){var i=r.next();i.isHole()||(n=i,e++)}return V.isTrue(e<=1,"found two shells in MinimalEdgeRing list"),n}},{key:"add",value:function(){if(1===arguments.length){var t=arguments[0];this.add(t.getEdgeEnds(),t.getNodes())}else if(2===arguments.length){var e=arguments[0],n=arguments[1];$e.linkResultDirectedEdges(n);var r=this.buildMaximalEdgeRings(e),i=new dt,o=this.buildMinimalEdgeRings(r,this._shellList,i);this.sortShellsAndHoles(o,this._shellList,i),this.placeFreeHoles(this._shellList,i)}}}],[{key:"constructor_",value:function(){this._geometryFactory=null,this._shellList=new dt;var t=arguments[0];this._geometryFactory=t}},{key:"findEdgeRingContaining",value:function(t,e){for(var n=t.getLinearRing(),r=n.getEnvelopeInternal(),i=n.getCoordinateN(0),o=null,s=null,a=e.iterator();a.hasNext();){var u=a.next(),l=u.getLinearRing(),h=l.getEnvelopeInternal();if(!h.equals(r)&&h.contains(r)){i=Wt.ptNotInList(n.getCoordinates(),l.getCoordinates());var c=!1;Oe.isInRing(i,l.getCoordinates())&&(c=!0),c&&(null===o||s.contains(h))&&(s=(o=u).getLinearRing().getEnvelopeInternal())}}return o}}]),e}(),en=function(){function e(){t(this,e)}return n(e,[{key:"getBounds",value:function(){}}]),e}(),nn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getItem",value:function(){return this._item}},{key:"getBounds",value:function(){return this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){this._bounds=null,this._item=null;var t=arguments[0],e=arguments[1];this._bounds=t,this._item=e}}]),e}(),rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"poll",value:function(){if(this.isEmpty())return null;var t=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),t}},{key:"size",value:function(){return this._size}},{key:"reorder",value:function(t){for(var e=null,n=this._items.get(t);2*t<=this._size&&((e=2*t)!==this._size&&this._items.get(e+1).compareTo(this._items.get(e))<0&&e++,this._items.get(e).compareTo(n)<0);t=e)this._items.set(t,this._items.get(e));this._items.set(t,n)}},{key:"clear",value:function(){this._size=0,this._items.clear()}},{key:"peek",value:function(){return this.isEmpty()?null:this._items.get(1)}},{key:"isEmpty",value:function(){return 0===this._size}},{key:"add",value:function(t){this._items.add(null),this._size+=1;var e=this._size;for(this._items.set(0,t);t.compareTo(this._items.get(Math.trunc(e/2)))<0;e/=2)this._items.set(e,this._items.get(Math.trunc(e/2)));this._items.set(e,t)}}],[{key:"constructor_",value:function(){this._size=null,this._items=null,this._size=0,this._items=new dt,this._items.add(null)}}]),e}(),on=function(){function e(){t(this,e)}return n(e,[{key:"insert",value:function(t,e){}},{key:"remove",value:function(t,e){}},{key:"query",value:function(){}}]),e}(),sn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLevel",value:function(){return this._level}},{key:"size",value:function(){return this._childBoundables.size()}},{key:"getChildBoundables",value:function(){return this._childBoundables}},{key:"addChildBoundable",value:function(t){V.isTrue(null===this._bounds),this._childBoundables.add(t)}},{key:"isEmpty",value:function(){return this._childBoundables.isEmpty()}},{key:"getBounds",value:function(){return null===this._bounds&&(this._bounds=this.computeBounds()),this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){if(this._childBoundables=new dt,this._bounds=null,this._level=null,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._level=t}}}]),e}(),an={reverseOrder:function(){return{compare:function(t,e){return e.compareTo(t)}}},min:function(t){return an.sort(t),t.get(0)},sort:function(t,e){var n=t.toArray();e?At.sort(n,e):At.sort(n);for(var r=t.iterator(),i=0,o=n.length;ie.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,!1,t,n),null):(this.expand(this._boundable2,this._boundable1,!0,t,n),null);if(r)return this.expand(this._boundable1,this._boundable2,!1,t,n),null;if(i)return this.expand(this._boundable2,this._boundable1,!0,t,n),null;throw new x("neither boundable is composite")}},{key:"isLeaves",value:function(){return!(e.isComposite(this._boundable1)||e.isComposite(this._boundable2))}},{key:"compareTo",value:function(t){var e=t;return this._distancee._distance?1:0}},{key:"expand",value:function(t,n,r,i,o){for(var s=t.getChildBoundables().iterator();s.hasNext();){var a=s.next(),u=null;(u=r?new e(n,a,this._itemDistance):new e(a,n,this._itemDistance)).getDistance()-2),r.getLevel()===n)return i.add(r),null;for(var o=r.getChildBoundables().iterator();o.hasNext();){var s=o.next();s instanceof sn?this.boundablesAtLevel(n,s,i):(V.isTrue(s instanceof nn),-1===n&&i.add(s))}return null}}},{key:"query",value:function(){if(1===arguments.length){var t=arguments[0];this.build();var e=new dt;return this.isEmpty()||this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.queryInternal(t,this._root,e),e}if(2===arguments.length){var n=arguments[0],r=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),n)&&this.queryInternal(n,this._root,r)}}},{key:"build",value:function(){if(this._built)return null;this._root=this._itemBoundables.isEmpty()?this.createNode(0):this.createHigherLevels(this._itemBoundables,-1),this._itemBoundables=null,this._built=!0}},{key:"getRoot",value:function(){return this.build(),this._root}},{key:"remove",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];return this.build(),!!this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.remove(t,this._root,e)}if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],o=this.removeItem(r,i);if(o)return!0;for(var s=null,a=r.getChildBoundables().iterator();a.hasNext();){var u=a.next();if(this.getIntersectsOp().intersects(u.getBounds(),n)&&u instanceof sn&&(o=this.remove(n,u,i))){s=u;break}}return null!==s&&s.getChildBoundables().isEmpty()&&r.getChildBoundables().remove(s),o}}},{key:"createHigherLevels",value:function(t,e){V.isTrue(!t.isEmpty());var n=this.createParentBoundables(t,e+1);return 1===n.size()?n.get(0):this.createHigherLevels(n,e+1)}},{key:"depth",value:function(){if(0===arguments.length)return this.isEmpty()?0:(this.build(),this.depth(this._root));if(1===arguments.length){for(var t=0,e=arguments[0].getChildBoundables().iterator();e.hasNext();){var n=e.next();if(n instanceof sn){var r=this.depth(n);r>t&&(t=r)}}return t+1}}},{key:"createParentBoundables",value:function(t,e){V.isTrue(!t.isEmpty());var n=new dt;n.add(this.createNode(e));var r=new dt(t);an.sort(r,this.getComparator());for(var i=r.iterator();i.hasNext();){var o=i.next();this.lastNode(n).getChildBoundables().size()===this.getNodeCapacity()&&n.add(this.createNode(e)),this.lastNode(n).addChildBoundable(o)}return n}},{key:"isEmpty",value:function(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){if(this._root=null,this._built=!1,this._itemBoundables=new dt,this._nodeCapacity=null,0===arguments.length)e.constructor_.call(this,e.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];V.isTrue(t>1,"Node capacity must be greater than 1"),this._nodeCapacity=t}}},{key:"compareDoubles",value:function(t,e){return t>e?1:t0);for(var n=new dt,r=0;r=0;){var u=o.poll(),l=u.getDistance();if(l>=i)break;u.isLeaves()?a.size()l&&(a.poll(),a.add(u)),i=a.peek().getDistance()):u.expandToQueue(o,i)}return s.getItems(a)}}},{key:"createNode",value:function(t){return new pn(t)}},{key:"size",value:function(){return 0===arguments.length?f(i(s.prototype),"size",this).call(this):f(i(s.prototype),"size",this).apply(this,arguments)}},{key:"insert",value:function(){if(!(2===arguments.length&&arguments[1]instanceof Object&&arguments[0]instanceof X))return f(i(s.prototype),"insert",this).apply(this,arguments);var t=arguments[0],e=arguments[1];if(t.isNull())return null;f(i(s.prototype),"insert",this).call(this,t,e)}},{key:"getIntersectsOp",value:function(){return s.intersectsOp}},{key:"verticalSlices",value:function(t,e){for(var n=Math.trunc(Math.ceil(t.size()/e)),r=new Array(e).fill(null),i=t.iterator(),o=0;o0;){var s=o.poll(),a=s.getDistance();if(a>=r)break;s.isLeaves()?(r=a,i=s):s.expandToQueue(o,r)}return null===i?null:[i.getBoundable(0).getItem(),i.getBoundable(1).getItem()]}}else{if(2===arguments.length){var u=arguments[0],l=arguments[1];if(this.isEmpty()||u.isEmpty())return null;var h=new ln(this.getRoot(),u.getRoot(),l);return this.nearestNeighbour(h)}if(3===arguments.length){var c=arguments[2],f=new nn(arguments[0],arguments[1]),g=new ln(this.getRoot(),f,c);return this.nearestNeighbour(g)[0]}if(4===arguments.length){var p=arguments[2],v=arguments[3],d=new nn(arguments[0],arguments[1]),y=new ln(this.getRoot(),d,p);return this.nearestNeighbourK(y,v)}}}},{key:"isWithinDistance",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1],n=A.POSITIVE_INFINITY,r=new rn;for(r.add(t);!r.isEmpty();){var i=r.poll(),o=i.getDistance();if(o>e)return!1;if(i.maximumDistance()<=e)return!0;if(i.isLeaves()){if((n=o)<=e)return!0}else i.expandToQueue(r,n)}return!1}if(3===arguments.length){var s=arguments[0],a=arguments[1],u=arguments[2],l=new ln(this.getRoot(),s.getRoot(),a);return this.isWithinDistance(l,u)}}},{key:"interfaces_",get:function(){return[on,w]}}],[{key:"constructor_",value:function(){if(0===arguments.length)s.constructor_.call(this,s.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];cn.constructor_.call(this,t)}}},{key:"centreX",value:function(t){return s.avg(t.getMinX(),t.getMaxX())}},{key:"avg",value:function(t,e){return(t+e)/2}},{key:"getItems",value:function(t){for(var e=new Array(t.size()).fill(null),n=0;!t.isEmpty();){var r=t.poll();e[n]=r.getBoundable(0).getItem(),n++}return e}},{key:"centreY",value:function(t){return s.avg(t.getMinY(),t.getMaxY())}}]),s}(cn),pn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"computeBounds",value:function(){for(var t=null,e=this.getChildBoundables().iterator();e.hasNext();){var n=e.next();null===t?t=new X(n.getBounds()):t.expandToInclude(n.getBounds())}return t}}],[{key:"constructor_",value:function(){var t=arguments[0];sn.constructor_.call(this,t)}}]),o}(sn);gn.STRtreeNode=pn,gn.xComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreX(t.getBounds()),gn.centreX(e.getBounds()))}}]),e}()),gn.yComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreY(t.getBounds()),gn.centreY(e.getBounds()))}}]),e}()),gn.intersectsOp=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[IntersectsOp]}},{key:"intersects",value:function(t,e){return t.intersects(e)}}]),e}()),gn.DEFAULT_NODE_CAPACITY=10;var vn=function(){function e(){t(this,e)}return n(e,null,[{key:"relativeSign",value:function(t,e){return te?1:0}},{key:"compare",value:function(t,n,r){if(n.equals2D(r))return 0;var i=e.relativeSign(n.x,r.x),o=e.relativeSign(n.y,r.y);switch(t){case 0:return e.compareValue(i,o);case 1:return e.compareValue(o,i);case 2:return e.compareValue(o,-i);case 3:return e.compareValue(-i,o);case 4:return e.compareValue(-i,-o);case 5:return e.compareValue(-o,-i);case 6:return e.compareValue(-o,i);case 7:return e.compareValue(i,-o)}return V.shouldNeverReachHere("invalid octant value"),0}},{key:"compareValue",value:function(t,e){return t<0?-1:t>0?1:e<0?-1:e>0?1:0}}]),e}(),dn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this.coord}},{key:"print",value:function(t){t.print(this.coord),t.print(" seg # = "+this.segmentIndex)}},{key:"compareTo",value:function(t){var e=t;return this.segmentIndexe.segmentIndex?1:this.coord.equals2D(e.coord)?0:this._isInterior?e._isInterior?vn.compare(this._segmentOctant,this.coord,e.coord):1:-1}},{key:"isEndPoint",value:function(t){return 0===this.segmentIndex&&!this._isInterior||this.segmentIndex===t}},{key:"toString",value:function(){return this.segmentIndex+":"+this.coord.toString()}},{key:"isInterior",value:function(){return this._isInterior}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;var t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this._segString=t,this.coord=new z(e),this.segmentIndex=n,this._segmentOctant=r,this._isInterior=!e.equals2D(t.getCoordinate(n))}}]),e}(),yn=function(){function e(){t(this,e)}return n(e,[{key:"hasNext",value:function(){}},{key:"next",value:function(){}},{key:"remove",value:function(){}}]),e}(),mn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getSplitCoordinates",value:function(){var t=new Ht;this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next();this.addEdgeCoordinates(n,r,t),n=r}return t.toCoordinateArray()}},{key:"addCollapsedNodes",value:function(){var t=new dt;this.findCollapsesFromInsertedNodes(t),this.findCollapsesFromExistingVertices(t);for(var e=t.iterator();e.hasNext();){var n=e.next().intValue();this.add(this._edge.getCoordinate(n),n)}}},{key:"createSplitEdgePts",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2;if(2===n)return[new z(t.coord),new z(e.coord)];var r=this._edge.getCoordinate(e.segmentIndex),i=e.isInterior()||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this._edge.getCoordinate(a);return i&&(o[s]=new z(e.coord)),o}},{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"findCollapsesFromExistingVertices",value:function(t){for(var e=0;e=0?n>=0?r>=i?0:1:r>=i?7:6:n>=0?r>=i?3:2:r>=i?4:5}if(arguments[0]instanceof z&&arguments[1]instanceof z){var o=arguments[0],s=arguments[1],a=s.x-o.x,u=s.y-o.y;if(0===a&&0===u)throw new x("Cannot compute the octant for two identical points "+o);return e.octant(a,u)}}}]),e}(),xn=function(){function e(){t(this,e)}return n(e,[{key:"getCoordinates",value:function(){}},{key:"size",value:function(){}},{key:"getCoordinate",value:function(t){}},{key:"isClosed",value:function(){}},{key:"setData",value:function(t){}},{key:"getData",value:function(){}}]),e}(),En=function(){function e(){t(this,e)}return n(e,[{key:"addIntersection",value:function(t,e){}},{key:"interfaces_",get:function(){return[xn]}}]),e}(),kn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinates",value:function(){return this._pts}},{key:"size",value:function(){return this._pts.length}},{key:"getCoordinate",value:function(t){return this._pts[t]}},{key:"isClosed",value:function(){return this._pts[0].equals(this._pts[this._pts.length-1])}},{key:"getSegmentOctant",value:function(t){return t===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(t),this.getCoordinate(t+1))}},{key:"setData",value:function(t){this._data=t}},{key:"safeOctant",value:function(t,e){return t.equals2D(e)?0:_n.octant(t,e)}},{key:"getData",value:function(){return this._data}},{key:"addIntersection",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];this.addIntersectionNode(t,e)}else if(4===arguments.length){var n=arguments[1],r=arguments[3],i=new z(arguments[0].getIntersection(r));this.addIntersection(i,n)}}},{key:"toString",value:function(){return Le.toLineString(new $t(this._pts))}},{key:"getNodeList",value:function(){return this._nodeList}},{key:"addIntersectionNode",value:function(t,e){var n=e,r=n+1;if(r=0&&r>=0||n<=0&&r<=0?Math.max(n,r):0}if(arguments[0]instanceof z){var i=arguments[0];return ft.index(this.p0,this.p1,i)}}},{key:"toGeometry",value:function(t){return t.createLineString([this.p0,this.p1])}},{key:"isVertical",value:function(){return this.p0.x===this.p1.x}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.p0.equals(n.p0)&&this.p1.equals(n.p1)}},{key:"intersection",value:function(t){var e=new Ce;return e.computeIntersection(this.p0,this.p1,t.p0,t.p1),e.hasIntersection()?e.getIntersection(0):null}},{key:"project",value:function(){if(arguments[0]instanceof z){var t=arguments[0];if(t.equals(this.p0)||t.equals(this.p1))return new z(t);var n=this.projectionFactor(t),r=new z;return r.x=this.p0.x+n*(this.p1.x-this.p0.x),r.y=this.p0.y+n*(this.p1.y-this.p0.y),r}if(arguments[0]instanceof e){var i=arguments[0],o=this.projectionFactor(i.p0),s=this.projectionFactor(i.p1);if(o>=1&&s>=1)return null;if(o<=0&&s<=0)return null;var a=this.project(i.p0);o<0&&(a=this.p0),o>1&&(a=this.p1);var u=this.project(i.p1);return s<0&&(u=this.p0),s>1&&(u=this.p1),new e(a,u)}}},{key:"normalize",value:function(){this.p1.compareTo(this.p0)<0&&this.reverse()}},{key:"angle",value:function(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)}},{key:"getCoordinate",value:function(t){return 0===t?this.p0:this.p1}},{key:"distancePerpendicular",value:function(t){return kt.pointToLinePerpendicular(t,this.p0,this.p1)}},{key:"minY",value:function(){return Math.min(this.p0.y,this.p1.y)}},{key:"midPoint",value:function(){return e.midPoint(this.p0,this.p1)}},{key:"projectionFactor",value:function(t){if(t.equals(this.p0))return 0;if(t.equals(this.p1))return 1;var e=this.p1.x-this.p0.x,n=this.p1.y-this.p0.y,r=e*e+n*n;return r<=0?A.NaN:((t.x-this.p0.x)*e+(t.y-this.p0.y)*n)/r}},{key:"closestPoints",value:function(t){var e=this.intersection(t);if(null!==e)return[e,e];var n=new Array(2).fill(null),r=A.MAX_VALUE,i=null,o=this.closestPoint(t.p0);r=o.distance(t.p0),n[0]=o,n[1]=t.p0;var s=this.closestPoint(t.p1);(i=s.distance(t.p1))0&&e<1?this.project(t):this.p0.distance(t)1||A.isNaN(e))&&(e=1),e}},{key:"toString",value:function(){return"LINESTRING( "+this.p0.x+" "+this.p0.y+", "+this.p1.x+" "+this.p1.y+")"}},{key:"isHorizontal",value:function(){return this.p0.y===this.p1.y}},{key:"reflect",value:function(t){var e=this.p1.getY()-this.p0.getY(),n=this.p0.getX()-this.p1.getX(),r=this.p0.getY()*(this.p1.getX()-this.p0.getX())-this.p0.getX()*(this.p1.getY()-this.p0.getY()),i=e*e+n*n,o=e*e-n*n,s=t.getX(),a=t.getY();return new z((-o*s-2*e*n*a-2*e*r)/i,(o*a-2*e*n*s-2*n*r)/i)}},{key:"distance",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return kt.segmentToSegment(this.p0,this.p1,t.p0,t.p1)}if(arguments[0]instanceof z){var n=arguments[0];return kt.pointToSegment(n,this.p0,this.p1)}}},{key:"pointAlong",value:function(t){var e=new z;return e.x=this.p0.x+t*(this.p1.x-this.p0.x),e.y=this.p0.y+t*(this.p1.y-this.p0.y),e}},{key:"hashCode",value:function(){var t=A.doubleToLongBits(this.p0.x);t^=31*A.doubleToLongBits(this.p0.y);var e=Math.trunc(t)^Math.trunc(t>>32),n=A.doubleToLongBits(this.p1.x);return n^=31*A.doubleToLongBits(this.p1.y),e^Math.trunc(n)^Math.trunc(n>>32)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this.p0=null,this.p1=null,0===arguments.length)e.constructor_.call(this,new z,new z);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.p0,t.p1)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.p0=n,this.p1=r}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];e.constructor_.call(this,new z(i,o),new z(s,a))}}},{key:"midPoint",value:function(t,e){return new z((t.x+e.x)/2,(t.y+e.y)/2)}}]),e}(),wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"overlap",value:function(){if(2===arguments.length);else if(4===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[3];arguments[0].getLineSegment(t,this._overlapSeg1),e.getLineSegment(n,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}}}],[{key:"constructor_",value:function(){this._overlapSeg1=new bn,this._overlapSeg2=new bn}}]),e}(),In=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLineSegment",value:function(t,e){e.p0=this._pts[t],e.p1=this._pts[t+1]}},{key:"computeSelect",value:function(t,e,n,r){var i=this._pts[e],o=this._pts[n];if(n-e==1)return r.select(this,e),null;if(!t.intersects(i,o))return null;var s=Math.trunc((e+n)/2);e=t.length-1)return t.length-1;for(var r=We.quadrant(t[n],t[n+1]),i=e+1;in.getId()&&(n.computeOverlaps(i,t),this._nOverlaps++),this._segInt.isDone())return null}}}],[{key:"constructor_",value:function(){if(this._monoChains=new dt,this._index=new gn,this._idCounter=0,this._nodedSegStrings=null,this._nOverlaps=0,0===arguments.length);else if(1===arguments.length){var t=arguments[0];Mn.constructor_.call(this,t)}}}]),o}(Mn),Pn=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"overlap",value:function(){if(4!==arguments.length)return f(i(s.prototype),"overlap",this).apply(this,arguments);var t=arguments[1],e=arguments[2],n=arguments[3],r=arguments[0].getContext(),o=e.getContext();this._si.processIntersections(r,t,o,n)}}],[{key:"constructor_",value:function(){this._si=null;var t=arguments[0];this._si=t}}]),s}(wn);Ln.SegmentOverlapAction=Pn;var Cn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isDeletable",value:function(t,e,n,r){var i=this._inputLine[t],o=this._inputLine[e],s=this._inputLine[n];return!!this.isConcave(i,o,s)&&!!this.isShallow(i,o,s,r)&&this.isShallowSampled(i,o,t,n,r)}},{key:"deleteShallowConcavities",value:function(){for(var t=1,n=this.findNextNonDeletedIndex(t),r=this.findNextNonDeletedIndex(n),i=!1;r=0;r--)this.addPt(t[r])}},{key:"isRedundant",value:function(t){if(this._ptList.size()<1)return!1;var e=this._ptList.get(this._ptList.size()-1);return t.distance(e)Math.PI;)t-=e.PI_TIMES_2;for(;t<=-Math.PI;)t+=e.PI_TIMES_2;return t}},{key:"angle",value:function(){if(1===arguments.length){var t=arguments[0];return Math.atan2(t.y,t.x)}if(2===arguments.length){var e=arguments[0],n=arguments[1],r=n.x-e.x,i=n.y-e.y;return Math.atan2(i,r)}}},{key:"isAcute",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)>0}},{key:"isObtuse",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)<0}},{key:"interiorAngle",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return Math.abs(o-i)}},{key:"normalizePositive",value:function(t){if(t<0){for(;t<0;)t+=e.PI_TIMES_2;t>=e.PI_TIMES_2&&(t=0)}else{for(;t>=e.PI_TIMES_2;)t-=e.PI_TIMES_2;t<0&&(t=0)}return t}},{key:"angleBetween",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return e.diff(i,o)}},{key:"diff",value:function(t,e){var n=null;return(n=tMath.PI&&(n=2*Math.PI-n),n}},{key:"toRadians",value:function(t){return t*Math.PI/180}},{key:"getTurn",value:function(t,n){var r=Math.sin(n-t);return r>0?e.COUNTERCLOCKWISE:r<0?e.CLOCKWISE:e.NONE}},{key:"angleBetweenOriented",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r)-i;return o<=-Math.PI?o+e.PI_TIMES_2:o>Math.PI?o-e.PI_TIMES_2:o}}]),e}();On.PI_TIMES_2=2*Math.PI,On.PI_OVER_2=Math.PI/2,On.PI_OVER_4=Math.PI/4,On.COUNTERCLOCKWISE=ft.COUNTERCLOCKWISE,On.CLOCKWISE=ft.CLOCKWISE,On.NONE=ft.COLLINEAR;var Rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addNextSegment",value:function(t,e){if(this._s0=this._s1,this._s1=this._s2,this._s2=t,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;var n=ft.index(this._s0,this._s1,this._s2),r=n===ft.CLOCKWISE&&this._side===tt.LEFT||n===ft.COUNTERCLOCKWISE&&this._side===tt.RIGHT;0===n?this.addCollinear(e):r?this.addOutsideTurn(n,e):this.addInsideTurn(n,e)}},{key:"addLineEndCap",value:function(t,e){var n=new bn(t,e),r=new bn;this.computeOffsetSegment(n,tt.LEFT,this._distance,r);var i=new bn;this.computeOffsetSegment(n,tt.RIGHT,this._distance,i);var o=e.x-t.x,s=e.y-t.y,a=Math.atan2(s,o);switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:this._segList.addPt(r.p1),this.addDirectedFillet(e,a+Math.PI/2,a-Math.PI/2,ft.CLOCKWISE,this._distance),this._segList.addPt(i.p1);break;case y.CAP_FLAT:this._segList.addPt(r.p1),this._segList.addPt(i.p1);break;case y.CAP_SQUARE:var u=new z;u.x=Math.abs(this._distance)*Math.cos(a),u.y=Math.abs(this._distance)*Math.sin(a);var l=new z(r.p1.x+u.x,r.p1.y+u.y),h=new z(i.p1.x+u.x,i.p1.y+u.y);this._segList.addPt(l),this._segList.addPt(h)}}},{key:"getCoordinates",value:function(){return this._segList.getCoordinates()}},{key:"addMitreJoin",value:function(t,e,n,r){var i=_t.intersection(e.p0,e.p1,n.p0,n.p1);if(null!==i&&(r<=0?1:i.distance(t)/Math.abs(r))<=this._bufParams.getMitreLimit())return this._segList.addPt(i),null;this.addLimitedMitreJoin(e,n,r,this._bufParams.getMitreLimit())}},{key:"addOutsideTurn",value:function(t,n){if(this._offset0.p1.distance(this._offset1.p0)=h&&(a-=2*Math.PI),this._segList.addPt(e),this.addDirectedFillet(t,a,h,r,i),this._segList.addPt(n)}},{key:"addLastSegment",value:function(){this._segList.addPt(this._offset1.p1)}},{key:"initSideSegments",value:function(t,e,n){this._s1=t,this._s2=e,this._side=n,this._seg1.setCoordinates(t,e),this.computeOffsetSegment(this._seg1,n,this._distance,this._offset1)}},{key:"addLimitedMitreJoin",value:function(t,e,n,r){var i=this._seg0.p1,o=On.angle(i,this._seg0.p0),s=On.angleBetweenOriented(this._seg0.p0,i,this._seg1.p1)/2,a=On.normalize(o+s),u=On.normalize(a+Math.PI),l=r*n,h=n-l*Math.abs(Math.sin(s)),c=i.x+l*Math.cos(u),f=i.y+l*Math.sin(u),g=new z(c,f),p=new bn(i,g),v=p.pointAlongOffset(1,h),d=p.pointAlongOffset(1,-h);this._side===tt.LEFT?(this._segList.addPt(v),this._segList.addPt(d)):(this._segList.addPt(d),this._segList.addPt(v))}},{key:"addDirectedFillet",value:function(t,e,n,r,i){var o=r===ft.CLOCKWISE?-1:1,s=Math.abs(e-n),a=Math.trunc(s/this._filletAngleQuantum+.5);if(a<1)return null;for(var u=s/a,l=new z,h=0;h0){var r=new z((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(r);var i=new z((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(i)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}}},{key:"createCircle",value:function(t){var e=new z(t.x+this._distance,t.y);this._segList.addPt(e),this.addDirectedFillet(t,0,2*Math.PI,-1,this._distance),this._segList.closeRing()}},{key:"addBevelJoin",value:function(t,e){this._segList.addPt(t.p1),this._segList.addPt(e.p0)}},{key:"init",value:function(t){this._distance=t,this._maxCurveSegmentError=t*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new Tn,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(t*e.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)}},{key:"addCollinear",value:function(t){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2),this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===y.JOIN_BEVEL||this._bufParams.getJoinStyle()===y.JOIN_MITRE?(t&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,ft.CLOCKWISE,this._distance))}},{key:"closeRing",value:function(){this._segList.closeRing()}},{key:"hasNarrowConcaveAngle",value:function(){return this._hasNarrowConcaveAngle}}],[{key:"constructor_",value:function(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new bn,this._seg1=new bn,this._offset0=new bn,this._offset1=new bn,this._side=0,this._hasNarrowConcaveAngle=!1;var t=arguments[0],n=arguments[1],r=arguments[2];this._precisionModel=t,this._bufParams=n,this._li=new Ce,this._filletAngleQuantum=Math.PI/2/n.getQuadrantSegments(),n.getQuadrantSegments()>=8&&n.getJoinStyle()===y.JOIN_ROUND&&(this._closingSegLengthFactor=e.MAX_CLOSING_SEG_LEN_FACTOR),this.init(r)}}]),e}();Rn.OFFSET_SEGMENT_SEPARATION_FACTOR=.001,Rn.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR=.001,Rn.CURVE_VERTEX_SNAP_DISTANCE_FACTOR=1e-6,Rn.MAX_CLOSING_SEG_LEN_FACTOR=80;var An=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getOffsetCurve",value:function(t,e){if(this._distance=e,0===e)return null;var n=e<0,r=Math.abs(e),i=this.getSegGen(r);t.length<=1?this.computePointCurve(t[0],i):this.computeOffsetCurve(t,n,i);var o=i.getCoordinates();return n&&Wt.reverse(o),o}},{key:"computeSingleSidedBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){n.addSegments(t,!0);var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{n.addSegments(t,!1);var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment(),n.closeRing()}},{key:"computeRingBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);e===tt.RIGHT&&(r=-r);var i=Cn.simplify(t,r),o=i.length-1;n.initSideSegments(i[o-1],i[0],e);for(var s=1;s<=o;s++){var a=1!==s;n.addNextSegment(i[s],a)}n.closeRing()}},{key:"computeLineBufferCurve",value:function(t,e){var n=this.simplifyTolerance(this._distance),r=Cn.simplify(t,n),i=r.length-1;e.initSideSegments(r[0],r[1],tt.LEFT);for(var o=2;o<=i;o++)e.addNextSegment(r[o],!0);e.addLastSegment(),e.addLineEndCap(r[i-1],r[i]);var s=Cn.simplify(t,-n),a=s.length-1;e.initSideSegments(s[a],s[a-1],tt.LEFT);for(var u=a-2;u>=0;u--)e.addNextSegment(s[u],!0);e.addLastSegment(),e.addLineEndCap(s[1],s[0]),e.closeRing()}},{key:"computePointCurve",value:function(t,e){switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:e.createCircle(t);break;case y.CAP_SQUARE:e.createSquare(t)}}},{key:"getLineCurve",value:function(t,e){if(this._distance=e,this.isLineOffsetEmpty(e))return null;var n=Math.abs(e),r=this.getSegGen(n);if(t.length<=1)this.computePointCurve(t[0],r);else if(this._bufParams.isSingleSided()){var i=e<0;this.computeSingleSidedBufferCurve(t,i,r)}else this.computeLineBufferCurve(t,r);return r.getCoordinates()}},{key:"getBufferParameters",value:function(){return this._bufParams}},{key:"simplifyTolerance",value:function(t){return t*this._bufParams.getSimplifyFactor()}},{key:"getRingCurve",value:function(t,n,r){if(this._distance=r,t.length<=2)return this.getLineCurve(t,r);if(0===r)return e.copyCoordinates(t);var i=this.getSegGen(r);return this.computeRingBufferCurve(t,n,i),i.getCoordinates()}},{key:"computeOffsetCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment()}},{key:"isLineOffsetEmpty",value:function(t){return 0===t||t<0&&!this._bufParams.isSingleSided()}},{key:"getSegGen",value:function(t){return new Rn(this._precisionModel,this._bufParams,t)}}],[{key:"constructor_",value:function(){this._distance=0,this._precisionModel=null,this._bufParams=null;var t=arguments[0],e=arguments[1];this._precisionModel=t,this._bufParams=e}},{key:"copyCoordinates",value:function(t){for(var e=new Array(t.length).fill(null),n=0;ni.getMaxY()||this.findStabbedSegments(t,r.getDirectedEdges(),e)}return e}if(3===arguments.length)if(ot(arguments[2],rt)&&arguments[0]instanceof z&&arguments[1]instanceof Ke){for(var o=arguments[0],s=arguments[1],a=arguments[2],u=s.getEdge().getCoordinates(),l=0;lthis._seg.p1.y&&this._seg.reverse(),!(Math.max(this._seg.p0.x,this._seg.p1.x)this._seg.p1.y||ft.index(this._seg.p0,this._seg.p1,o)===ft.RIGHT)){var h=s.getDepth(tt.LEFT);this._seg.p0.equals(u[l])||(h=s.getDepth(tt.RIGHT));var c=new Fn(this._seg,h);a.add(c)}}else if(ot(arguments[2],rt)&&arguments[0]instanceof z&&ot(arguments[1],rt))for(var f=arguments[0],g=arguments[2],p=arguments[1].iterator();p.hasNext();){var v=p.next();v.isForward()&&this.findStabbedSegments(f,v,g)}}},{key:"getDepth",value:function(t){var e=this.findStabbedSegments(t);return 0===e.size()?0:an.min(e)._leftDepth}}],[{key:"constructor_",value:function(){this._subgraphs=null,this._seg=new bn;var t=arguments[0];this._subgraphs=t}}]),e}(),Fn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var e=t;if(this._upwardSeg.minX()>=e._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=e._upwardSeg.minX())return-1;var n=this._upwardSeg.orientationIndex(e._upwardSeg);return 0!==n||0!=(n=-1*e._upwardSeg.orientationIndex(this._upwardSeg))?n:this._upwardSeg.compareTo(e._upwardSeg)}},{key:"compareX",value:function(t,e){var n=t.p0.compareTo(e.p0);return 0!==n?n:t.p1.compareTo(e.p1)}},{key:"toString",value:function(){return this._upwardSeg.toString()}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._upwardSeg=null,this._leftDepth=null;var t=arguments[0],e=arguments[1];this._upwardSeg=new bn(t),this._leftDepth=e}}]),e}();Dn.DepthSegment=Fn;var qn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){_.constructor_.call(this,"Projective point not representable on the Cartesian plane.")}}]),o}(_),Vn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getY",value:function(){var t=this.y/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getX",value:function(){var t=this.x/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getCoordinate",value:function(){var t=new z;return t.x=this.getX(),t.y=this.getY(),t}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.w=null,0===arguments.length)this.x=0,this.y=0,this.w=1;else if(1===arguments.length){var t=arguments[0];this.x=t.x,this.y=t.y,this.w=1}else if(2===arguments.length){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var n=arguments[0],r=arguments[1];this.x=n,this.y=r,this.w=1}else if(arguments[0]instanceof e&&arguments[1]instanceof e){var i=arguments[0],o=arguments[1];this.x=i.y*o.w-o.y*i.w,this.y=o.x*i.w-i.x*o.w,this.w=i.x*o.y-o.x*i.y}else if(arguments[0]instanceof z&&arguments[1]instanceof z){var s=arguments[0],a=arguments[1];this.x=s.y-a.y,this.y=a.x-s.x,this.w=s.x*a.y-a.x*s.y}}else if(3===arguments.length){var u=arguments[0],l=arguments[1],h=arguments[2];this.x=u,this.y=l,this.w=h}else if(4===arguments.length){var c=arguments[0],f=arguments[1],g=arguments[2],p=arguments[3],v=c.y-f.y,d=f.x-c.x,y=c.x*f.y-f.x*c.y,m=g.y-p.y,_=p.x-g.x,x=g.x*p.y-p.x*g.y;this.x=d*x-_*y,this.y=m*y-v*x,this.w=v*_-m*d}}}]),e}(),Gn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"area",value:function(){return e.area(this.p0,this.p1,this.p2)}},{key:"signedArea",value:function(){return e.signedArea(this.p0,this.p1,this.p2)}},{key:"interpolateZ",value:function(t){if(null===t)throw new x("Supplied point is null.");return e.interpolateZ(t,this.p0,this.p1,this.p2)}},{key:"longestSideLength",value:function(){return e.longestSideLength(this.p0,this.p1,this.p2)}},{key:"isAcute",value:function(){return e.isAcute(this.p0,this.p1,this.p2)}},{key:"circumcentre",value:function(){return e.circumcentre(this.p0,this.p1,this.p2)}},{key:"area3D",value:function(){return e.area3D(this.p0,this.p1,this.p2)}},{key:"centroid",value:function(){return e.centroid(this.p0,this.p1,this.p2)}},{key:"inCentre",value:function(){return e.inCentre(this.p0,this.p1,this.p2)}}],[{key:"constructor_",value:function(){this.p0=null,this.p1=null,this.p2=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.p0=t,this.p1=e,this.p2=n}},{key:"area",value:function(t,e,n){return Math.abs(((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2)}},{key:"signedArea",value:function(t,e,n){return((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2}},{key:"det",value:function(t,e,n,r){return t*r-e*n}},{key:"interpolateZ",value:function(t,e,n,r){var i=e.x,o=e.y,s=n.x-i,a=r.x-i,u=n.y-o,l=r.y-o,h=s*l-a*u,c=t.x-i,f=t.y-o,g=(l*c-a*f)/h,p=(-u*c+s*f)/h;return e.getZ()+g*(n.getZ()-e.getZ())+p*(r.getZ()-e.getZ())}},{key:"longestSideLength",value:function(t,e,n){var r=t.distance(e),i=e.distance(n),o=n.distance(t),s=r;return i>s&&(s=i),o>s&&(s=o),s}},{key:"circumcentreDD",value:function(t,e,n){var r=lt.valueOf(t.x).subtract(n.x),i=lt.valueOf(t.y).subtract(n.y),o=lt.valueOf(e.x).subtract(n.x),s=lt.valueOf(e.y).subtract(n.y),a=lt.determinant(r,i,o,s).multiply(2),u=r.sqr().add(i.sqr()),l=o.sqr().add(s.sqr()),h=lt.determinant(i,u,s,l),c=lt.determinant(r,u,o,l),f=lt.valueOf(n.x).subtract(h.divide(a)).doubleValue(),g=lt.valueOf(n.y).add(c.divide(a)).doubleValue();return new z(f,g)}},{key:"isAcute",value:function(t,e,n){return!!On.isAcute(t,e,n)&&!!On.isAcute(e,n,t)&&!!On.isAcute(n,t,e)}},{key:"circumcentre",value:function(t,n,r){var i=r.x,o=r.y,s=t.x-i,a=t.y-o,u=n.x-i,l=n.y-o,h=2*e.det(s,a,u,l),c=e.det(a,s*s+a*a,l,u*u+l*l),f=e.det(s,s*s+a*a,u,u*u+l*l);return new z(i-c/h,o+f/h)}},{key:"perpendicularBisector",value:function(t,e){var n=e.x-t.x,r=e.y-t.y,i=new Vn(t.x+n/2,t.y+r/2,1),o=new Vn(t.x-r+n/2,t.y+n+r/2,1);return new Vn(i,o)}},{key:"angleBisector",value:function(t,e,n){var r=e.distance(t),i=r/(r+e.distance(n)),o=n.x-t.x,s=n.y-t.y;return new z(t.x+i*o,t.y+i*s)}},{key:"area3D",value:function(t,e,n){var r=e.x-t.x,i=e.y-t.y,o=e.getZ()-t.getZ(),s=n.x-t.x,a=n.y-t.y,u=n.getZ()-t.getZ(),l=i*u-o*a,h=o*s-r*u,c=r*a-i*s,f=l*l+h*h+c*c;return Math.sqrt(f)/2}},{key:"centroid",value:function(t,e,n){var r=(t.x+e.x+n.x)/3,i=(t.y+e.y+n.y)/3;return new z(r,i)}},{key:"inCentre",value:function(t,e,n){var r=e.distance(n),i=t.distance(n),o=t.distance(e),s=r+i+o,a=(r*t.x+i*e.x+o*n.x)/s,u=(r*t.y+i*e.y+o*n.y)/s;return new z(a,u)}}]),e}(),Bn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addRingSide",value:function(t,e,n,r,i){if(0===e&&t.length=zt.MINIMUM_VALID_SIZE&&ft.isCCW(t)&&(o=i,s=r,n=tt.opposite(n));var a=this._curveBuilder.getRingCurve(t,n,e);this.addCurve(a,o,s)}},{key:"addRingBothSides",value:function(t,e){this.addRingSide(t,e,tt.LEFT,Z.EXTERIOR,Z.INTERIOR),this.addRingSide(t,e,tt.RIGHT,Z.INTERIOR,Z.EXTERIOR)}},{key:"addPoint",value:function(t){if(this._distance<=0)return null;var e=t.getCoordinates(),n=this._curveBuilder.getLineCurve(e,this._distance);this.addCurve(n,Z.EXTERIOR,Z.INTERIOR)}},{key:"addPolygon",value:function(t){var e=this._distance,n=tt.LEFT;this._distance<0&&(e=-this._distance,n=tt.RIGHT);var r=t.getExteriorRing(),i=Wt.removeRepeatedPoints(r.getCoordinates());if(this._distance<0&&this.isErodedCompletely(r,this._distance))return null;if(this._distance<=0&&i.length<3)return null;this.addRingSide(i,e,n,Z.EXTERIOR,Z.INTERIOR);for(var o=0;o0&&this.isErodedCompletely(s,-this._distance)||this.addRingSide(a,e,tt.opposite(n),Z.INTERIOR,Z.EXTERIOR)}}},{key:"isTriangleErodedCompletely",value:function(t,e){var n=new Gn(t[0],t[1],t[2]),r=n.inCentre();return kt.pointToSegment(r,n.p0,n.p1)i}},{key:"addCollection",value:function(t){for(var e=0;e=this._max)throw new W;var t=this._parent.getGeometryN(this._index++);return t instanceof Bt?(this._subcollectionIterator=new e(t),this._subcollectionIterator.next()):t}},{key:"remove",value:function(){throw new J(this.getClass().getName())}},{key:"hasNext",value:function(){if(this._atStart)return!0;if(null!==this._subcollectionIterator){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)}},{key:"interfaces_",get:function(){return[yn]}}],[{key:"constructor_",value:function(){this._parent=null,this._atStart=null,this._max=null,this._index=null,this._subcollectionIterator=null;var t=arguments[0];this._parent=t,this._atStart=!0,this._index=0,this._max=t.getNumGeometries()}},{key:"isAtomic",value:function(t){return!(t instanceof Bt)}}]),e}(),jn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"locate",value:function(t){return e.locate(t,this._geom)}},{key:"interfaces_",get:function(){return[Yn]}}],[{key:"constructor_",value:function(){this._geom=null;var t=arguments[0];this._geom=t}},{key:"locatePointInPolygon",value:function(t,n){if(n.isEmpty())return Z.EXTERIOR;var r=n.getExteriorRing(),i=e.locatePointInRing(t,r);if(i!==Z.INTERIOR)return i;for(var o=0;o=0;n--){var r=this._edgeList.get(n),i=r.getSym();null===e&&(e=i),null!==t&&i.setNext(t),t=r}e.setNext(t)}},{key:"computeDepths",value:function(){if(1===arguments.length){var t=arguments[0],e=this.findIndex(t),n=t.getDepth(tt.LEFT),r=t.getDepth(tt.RIGHT),i=this.computeDepths(e+1,this._edgeList.size(),n);if(this.computeDepths(0,e,i)!==r)throw new pt("depth mismatch at "+t.getCoordinate())}else if(3===arguments.length){for(var o=arguments[1],s=arguments[2],a=arguments[0];a=0;i--){var o=this._resultAreaEdgeList.get(i),s=o.getSym();switch(null===e&&o.getEdgeRing()===t&&(e=o),r){case this._SCANNING_FOR_INCOMING:if(s.getEdgeRing()!==t)continue;n=s,r=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(o.getEdgeRing()!==t)continue;n.setNextMin(o),r=this._SCANNING_FOR_INCOMING}}r===this._LINKING_TO_OUTGOING&&(V.isTrue(null!==e,"found null for first outgoing dirEdge"),V.isTrue(e.getEdgeRing()===t,"unable to link last incoming dirEdge"),n.setNextMin(e))}},{key:"getOutgoingDegree",value:function(){if(0===arguments.length){for(var t=0,e=this.iterator();e.hasNext();)e.next().isInResult()&&t++;return t}if(1===arguments.length){for(var n=arguments[0],r=0,i=this.iterator();i.hasNext();)i.next().getEdgeRing()===n&&r++;return r}}},{key:"getLabel",value:function(){return this._label}},{key:"findCoveredLineEdges",value:function(){for(var t=Z.NONE,e=this.iterator();e.hasNext();){var n=e.next(),r=n.getSym();if(!n.isLineEdge()){if(n.isInResult()){t=Z.INTERIOR;break}if(r.isInResult()){t=Z.EXTERIOR;break}}}if(t===Z.NONE)return null;for(var i=t,o=this.iterator();o.hasNext();){var s=o.next(),a=s.getSym();s.isLineEdge()?s.getEdge().setCovered(i===Z.INTERIOR):(s.isInResult()&&(i=Z.EXTERIOR),a.isInResult()&&(i=Z.INTERIOR))}}},{key:"computeLabelling",value:function(t){f(i(s.prototype),"computeLabelling",this).call(this,t),this._label=new Ae(Z.NONE);for(var e=this.iterator();e.hasNext();)for(var n=e.next().getEdge().getLabel(),r=0;r<2;r++){var o=n.getLocation(r);o!==Z.INTERIOR&&o!==Z.BOUNDARY||this._label.setLocation(r,Z.INTERIOR)}}}],[{key:"constructor_",value:function(){this._resultAreaEdgeList=null,this._label=null,this._SCANNING_FOR_INCOMING=1,this._LINKING_TO_OUTGOING=2}}]),s}(Xn),Zn=function(e){r(o,e);var i=c(o);function o(){return t(this,o),i.call(this)}return n(o,[{key:"createNode",value:function(t){return new Ge(t,new Un)}}]),o}(Qe),Hn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var n=t;return e.compareOriented(this._pts,this._orientation,n._pts,n._orientation)}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._pts=null,this._orientation=null;var t=arguments[0];this._pts=t,this._orientation=e.orientation(t)}},{key:"orientation",value:function(t){return 1===Wt.increasingDirection(t)}},{key:"compareOriented",value:function(t,e,n,r){for(var i=e?1:-1,o=r?1:-1,s=e?t.length:-1,a=r?n.length:-1,u=e?0:t.length-1,l=r?0:n.length-1;;){var h=t[u].compareTo(n[l]);if(0!==h)return h;var c=(u+=i)===s,f=(l+=o)===a;if(c&&!f)return-1;if(!c&&f)return 1;if(c&&f)return 0}}}]),e}(),Wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.print("MULTILINESTRING ( ");for(var e=0;e0&&t.print(","),t.print("(");for(var r=n.getCoordinates(),i=0;i0&&t.print(","),t.print(r[i].x+" "+r[i].y);t.println(")")}t.print(") ")}},{key:"addAll",value:function(t){for(var e=t.iterator();e.hasNext();)this.add(e.next())}},{key:"findEdgeIndex",value:function(t){for(var e=0;et?1:this.diste?1:0}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this.coord=null,this.segmentIndex=null,this.dist=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.coord=new z(t),this.segmentIndex=e,this.dist=n}}]),e}(),$n=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this._nodeMap.values().iterator()}},{key:"addSplitEdges",value:function(t){this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next(),i=this.createSplitEdge(n,r);t.add(i),n=r}}},{key:"addEndpoints",value:function(){var t=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[t],t,0)}},{key:"createSplitEdge",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2,r=this.edge.pts[e.segmentIndex],i=e.dist>0||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this.edge.pts[a];return i&&(o[s]=e.coord),new or(o,new Ae(this.edge._label))}},{key:"add",value:function(t,e,n){var r=new Qn(t,e,n),i=this._nodeMap.get(r);return null!==i?i:(this._nodeMap.put(r,r),r)}},{key:"isIntersection",value:function(t){for(var e=this.iterator();e.hasNext();)if(e.next().coord.equals(t))return!0;return!1}}],[{key:"constructor_",value:function(){this._nodeMap=new Ze,this.edge=null;var t=arguments[0];this.edge=t}}]),e}(),tr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isIntersects",value:function(){return!this.isDisjoint()}},{key:"isCovers",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"isCoveredBy",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"set",value:function(){if(1===arguments.length)for(var t=arguments[0],e=0;e=0&&e>=0&&this.setAtLeast(t,e,n)}},{key:"isWithin",value:function(){return e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"isTouches",value:function(t,n){return t>n?this.isTouches(n,t):(t===Mt.A&&n===Mt.A||t===Mt.L&&n===Mt.L||t===Mt.L&&n===Mt.A||t===Mt.P&&n===Mt.A||t===Mt.P&&n===Mt.L)&&this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&(e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))}},{key:"isOverlaps",value:function(t,n){return t===Mt.P&&n===Mt.P||t===Mt.A&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&1===this._matrix[Z.INTERIOR][Z.INTERIOR]&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR])}},{key:"isEquals",value:function(t,n){return t===n&&e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"toString",value:function(){for(var t=new Qt("123456789"),e=0;e<3;e++)for(var n=0;n<3;n++)t.setCharAt(3*e+n,Mt.toDimensionSymbol(this._matrix[e][n]));return t.toString()}},{key:"setAll",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this._matrix[e][n]=t}},{key:"get",value:function(t,e){return this._matrix[t][e]}},{key:"transpose",value:function(){var t=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=t,t=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=t,t=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=t,this}},{key:"matches",value:function(t){if(9!==t.length)throw new x("Should be length 9: "+t);for(var n=0;n<3;n++)for(var r=0;r<3;r++)if(!e.matches(this._matrix[n][r],t.charAt(3*n+r)))return!1;return!0}},{key:"add",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this.setAtLeast(e,n,t.get(e,n))}},{key:"isDisjoint",value:function(){return this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.INTERIOR][Z.BOUNDARY]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.BOUNDARY]===Mt.FALSE}},{key:"isCrosses",value:function(t,n){return t===Mt.P&&n===Mt.L||t===Mt.P&&n===Mt.A||t===Mt.L&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR]):t===Mt.L&&n===Mt.P||t===Mt.A&&n===Mt.P||t===Mt.A&&n===Mt.L?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&0===this._matrix[Z.INTERIOR][Z.INTERIOR]}},{key:"interfaces_",get:function(){return[b]}}],[{key:"constructor_",value:function(){if(this._matrix=null,0===arguments.length)this._matrix=Array(3).fill().map((function(){return Array(3)})),this.setAll(Mt.FALSE);else if(1===arguments.length)if("string"==typeof arguments[0]){var t=arguments[0];e.constructor_.call(this),this.set(t)}else if(arguments[0]instanceof e){var n=arguments[0];e.constructor_.call(this),this._matrix[Z.INTERIOR][Z.INTERIOR]=n._matrix[Z.INTERIOR][Z.INTERIOR],this._matrix[Z.INTERIOR][Z.BOUNDARY]=n._matrix[Z.INTERIOR][Z.BOUNDARY],this._matrix[Z.INTERIOR][Z.EXTERIOR]=n._matrix[Z.INTERIOR][Z.EXTERIOR],this._matrix[Z.BOUNDARY][Z.INTERIOR]=n._matrix[Z.BOUNDARY][Z.INTERIOR],this._matrix[Z.BOUNDARY][Z.BOUNDARY]=n._matrix[Z.BOUNDARY][Z.BOUNDARY],this._matrix[Z.BOUNDARY][Z.EXTERIOR]=n._matrix[Z.BOUNDARY][Z.EXTERIOR],this._matrix[Z.EXTERIOR][Z.INTERIOR]=n._matrix[Z.EXTERIOR][Z.INTERIOR],this._matrix[Z.EXTERIOR][Z.BOUNDARY]=n._matrix[Z.EXTERIOR][Z.BOUNDARY],this._matrix[Z.EXTERIOR][Z.EXTERIOR]=n._matrix[Z.EXTERIOR][Z.EXTERIOR]}}},{key:"matches",value:function(){if(Number.isInteger(arguments[0])&&"string"==typeof arguments[1]){var t=arguments[0],n=arguments[1];return n===Mt.SYM_DONTCARE||n===Mt.SYM_TRUE&&(t>=0||t===Mt.TRUE)||n===Mt.SYM_FALSE&&t===Mt.FALSE||n===Mt.SYM_P&&t===Mt.P||n===Mt.SYM_L&&t===Mt.L||n===Mt.SYM_A&&t===Mt.A}if("string"==typeof arguments[0]&&"string"==typeof arguments[1]){var r=arguments[1];return new e(arguments[0]).matches(r)}}},{key:"isTrue",value:function(t){return t>=0||t===Mt.TRUE}}]),e}(),er=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"size",value:function(){return this._size}},{key:"addAll",value:function(t){return null===t||0===t.length?null:(this.ensureCapacity(this._size+t.length),xt.arraycopy(t,0,this._data,this._size,t.length),void(this._size+=t.length))}},{key:"ensureCapacity",value:function(t){if(t<=this._data.length)return null;var e=Math.max(t,2*this._data.length);this._data=At.copyOf(this._data,e)}},{key:"toArray",value:function(){var t=new Array(this._size).fill(null);return xt.arraycopy(this._data,0,t,0,this._size),t}},{key:"add",value:function(t){this.ensureCapacity(this._size+1),this._data[this._size]=t,++this._size}}],[{key:"constructor_",value:function(){if(this._data=null,this._size=0,0===arguments.length)e.constructor_.call(this,10);else if(1===arguments.length){var t=arguments[0];this._data=new Array(t).fill(null)}}}]),e}(),nr=function(){function e(){t(this,e)}return n(e,[{key:"getChainStartIndices",value:function(t){var e=0,n=new er(Math.trunc(t.length/2));n.add(e);do{var r=this.findChainEnd(t,e);n.add(r),e=r}while(en?e:n}},{key:"getMinX",value:function(t){var e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return ee&&(r=1),this._depth[t][n]=r}}}},{key:"getDelta",value:function(t){return this._depth[t][tt.RIGHT]-this._depth[t][tt.LEFT]}},{key:"getLocation",value:function(t,e){return this._depth[t][e]<=0?Z.EXTERIOR:Z.INTERIOR}},{key:"toString",value:function(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}},{key:"add",value:function(){if(1===arguments.length)for(var t=arguments[0],n=0;n<2;n++)for(var r=1;r<3;r++){var i=t.getLocation(n,r);i!==Z.EXTERIOR&&i!==Z.INTERIOR||(this.isNull(n,r)?this._depth[n][r]=e.depthAtLocation(i):this._depth[n][r]+=e.depthAtLocation(i))}else if(3===arguments.length){var o=arguments[0],s=arguments[1];arguments[2]===Z.INTERIOR&&this._depth[o][s]++}}}],[{key:"constructor_",value:function(){this._depth=Array(2).fill().map((function(){return Array(3)}));for(var t=0;t<2;t++)for(var n=0;n<3;n++)this._depth[t][n]=e.NULL_VALUE}},{key:"depthAtLocation",value:function(t){return t===Z.EXTERIOR?0:t===Z.INTERIOR?1:e.NULL_VALUE}}]),e}();ir.NULL_VALUE=-1;var or=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getDepth",value:function(){return this._depth}},{key:"getCollapsedEdge",value:function(){var t=new Array(2).fill(null);return t[0]=this.pts[0],t[1]=this.pts[1],new s(t,Ae.toLineLabel(this._label))}},{key:"isIsolated",value:function(){return this._isIsolated}},{key:"getCoordinates",value:function(){return this.pts}},{key:"setIsolated",value:function(t){this._isIsolated=t}},{key:"setName",value:function(t){this._name=t}},{key:"equals",value:function(t){if(!(t instanceof s))return!1;var e=t;if(this.pts.length!==e.pts.length)return!1;for(var n=!0,r=!0,i=this.pts.length,o=0;o0?this.pts[0]:null;if(1===arguments.length){var t=arguments[0];return this.pts[t]}}},{key:"print",value:function(t){t.print("edge "+this._name+": "),t.print("LINESTRING (");for(var e=0;e0&&t.print(","),t.print(this.pts[e].x+" "+this.pts[e].y);t.print(") "+this._label+" "+this._depthDelta)}},{key:"computeIM",value:function(t){s.updateIM(this._label,t)}},{key:"isCollapsed",value:function(){return!!this._label.isArea()&&3===this.pts.length&&!!this.pts[0].equals(this.pts[2])}},{key:"isClosed",value:function(){return this.pts[0].equals(this.pts[this.pts.length-1])}},{key:"getMaximumSegmentIndex",value:function(){return this.pts.length-1}},{key:"getDepthDelta",value:function(){return this._depthDelta}},{key:"getNumPoints",value:function(){return this.pts.length}},{key:"printReverse",value:function(t){t.print("edge "+this._name+": ");for(var e=this.pts.length-1;e>=0;e--)t.print(this.pts[e]+" ");t.println("")}},{key:"getMonotoneChainEdge",value:function(){return null===this._mce&&(this._mce=new rr(this)),this._mce}},{key:"getEnvelope",value:function(){if(null===this._env){this._env=new X;for(var t=0;t0&&t.append(","),t.append(this.pts[e].x+" "+this.pts[e].y);return t.append(") "+this._label+" "+this._depthDelta),t.toString()}},{key:"isPointwiseEqual",value:function(t){if(this.pts.length!==t.pts.length)return!1;for(var e=0;er||this._maxyo;if(s)return!1;var a=this.intersectsToleranceSquare(t,e);return V.isTrue(!(s&&a),"Found bad envelope test"),a}},{key:"initCorners",value:function(t){var e=.5;this._minx=t.x-e,this._maxx=t.x+e,this._miny=t.y-e,this._maxy=t.y+e,this._corner[0]=new z(this._maxx,this._maxy),this._corner[1]=new z(this._minx,this._maxy),this._corner[2]=new z(this._minx,this._miny),this._corner[3]=new z(this._maxx,this._miny)}},{key:"intersects",value:function(t,e){return 1===this._scaleFactor?this.intersectsScaled(t,e):(this.copyScaled(t,this._p0Scaled),this.copyScaled(e,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}},{key:"scale",value:function(t){return Math.round(t*this._scaleFactor)}},{key:"getCoordinate",value:function(){return this._originalPt}},{key:"copyScaled",value:function(t,e){e.x=this.scale(t.x),e.y=this.scale(t.y)}},{key:"getSafeEnvelope",value:function(){if(null===this._safeEnv){var t=e.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new X(this._originalPt.x-t,this._originalPt.x+t,this._originalPt.y-t,this._originalPt.y+t)}return this._safeEnv}},{key:"intersectsPixelClosure",value:function(t,e){return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.hasIntersection()))))}},{key:"intersectsToleranceSquare",value:function(t,e){var n=!1,r=!1;return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.isProper()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.isProper()||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.isProper()||(this._li.hasIntersection()&&(r=!0),this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.isProper()||n&&r||t.equals(this._pt)||e.equals(this._pt)))))}},{key:"addSnappedNode",value:function(t,e){var n=t.getCoordinate(e),r=t.getCoordinate(e+1);return!!this.intersects(n,r)&&(t.addIntersection(this.getCoordinate(),e),!0)}}],[{key:"constructor_",value:function(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;var t=arguments[0],e=arguments[1],n=arguments[2];if(this._originalPt=t,this._pt=t,this._scaleFactor=e,this._li=n,e<=0)throw new x("Scale factor must be non-zero");1!==e&&(this._pt=new z(this.scale(t.x),this.scale(t.y)),this._p0Scaled=new z,this._p1Scaled=new z),this.initCorners(this._pt)}}]),e}();lr.SAFE_ENV_EXPANSION_FACTOR=.75;var hr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"select",value:function(){if(1===arguments.length);else if(2===arguments.length){var t=arguments[1];arguments[0].getLineSegment(t,this.selectedSegment),this.select(this.selectedSegment)}}}],[{key:"constructor_",value:function(){this.selectedSegment=new bn}}]),e}(),cr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"snap",value:function(){if(1===arguments.length){var e=arguments[0];return this.snap(e,null,-1)}if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=r.getSafeEnvelope(),a=new fr(r,i,o);return this._index.query(s,new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[hn]}},{key:"visitItem",value:function(t){t.select(s,a)}}]),e}())),a.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var t=arguments[0];this._index=t}}]),e}(),fr=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isNodeAdded",value:function(){return this._isNodeAdded}},{key:"select",value:function(){if(!(2===arguments.length&&Number.isInteger(arguments[1])&&arguments[0]instanceof In))return f(i(s.prototype),"select",this).apply(this,arguments);var t=arguments[1],e=arguments[0].getContext();if(this._parentEdge===e&&(t===this._hotPixelVertexIndex||t+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(e,t)}}],[{key:"constructor_",value:function(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var t=arguments[0],e=arguments[1],n=arguments[2];this._hotPixel=t,this._parentEdge=e,this._hotPixelVertexIndex=n}}]),s}(hr);cr.HotPixelSnapAction=fr;var gr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"processIntersections",value:function(t,e,n,r){if(t===n&&e===r)return null;var i=t.getCoordinates()[e],o=t.getCoordinates()[e+1],s=n.getCoordinates()[r],a=n.getCoordinates()[r+1];if(this._li.computeIntersection(i,o,s,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var u=0;u=0;t--){try{this.bufferReducedPrecision(t)}catch(t){if(!(t instanceof pt))throw t;this._saveException=t}if(null!==this._resultGeometry)return null}throw this._saveException}if(1===arguments.length){var n=arguments[0],r=e.precisionScaleFactor(this._argGeom,this._distance,n),i=new ie(r);this.bufferFixedPrecision(i)}}},{key:"computeGeometry",value:function(){if(this.bufferOriginalPrecision(),null!==this._resultGeometry)return null;var t=this._argGeom.getFactory().getPrecisionModel();t.getType()===ie.FIXED?this.bufferFixedPrecision(t):this.bufferReducedPrecision()}},{key:"setQuadrantSegments",value:function(t){this._bufParams.setQuadrantSegments(t)}},{key:"bufferOriginalPrecision",value:function(){try{var t=new sr(this._bufParams);this._resultGeometry=t.buffer(this._argGeom,this._distance)}catch(t){if(!(t instanceof F))throw t;this._saveException=t}}},{key:"getResultGeometry",value:function(t){return this._distance=t,this.computeGeometry(),this._resultGeometry}},{key:"setEndCapStyle",value:function(t){this._bufParams.setEndCapStyle(t)}}],[{key:"constructor_",value:function(){if(this._argGeom=null,this._distance=null,this._bufParams=new y,this._resultGeometry=null,this._saveException=null,1===arguments.length){var t=arguments[0];this._argGeom=t}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this._argGeom=e,this._bufParams=n}}},{key:"bufferOp",value:function(){if(2===arguments.length){var t=arguments[1];return new e(arguments[0]).getResultGeometry(t)}if(3===arguments.length){if(Number.isInteger(arguments[2])&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var n=arguments[1],r=arguments[2],i=new e(arguments[0]);return i.setQuadrantSegments(r),i.getResultGeometry(n)}if(arguments[2]instanceof y&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var o=arguments[1];return new e(arguments[0],arguments[2]).getResultGeometry(o)}}else if(4===arguments.length){var s=arguments[1],a=arguments[2],u=arguments[3],l=new e(arguments[0]);return l.setQuadrantSegments(a),l.setEndCapStyle(u),l.getResultGeometry(s)}}},{key:"precisionScaleFactor",value:function(t,e,n){var r=t.getEnvelopeInternal(),i=Et.max(Math.abs(r.getMaxX()),Math.abs(r.getMaxY()),Math.abs(r.getMinX()),Math.abs(r.getMinY()))+2*(e>0?e:0),o=n-Math.trunc(Math.log(i)/Math.log(10)+1);return Math.pow(10,o)}}]),e}();vr.CAP_ROUND=y.CAP_ROUND,vr.CAP_BUTT=y.CAP_FLAT,vr.CAP_FLAT=y.CAP_FLAT,vr.CAP_SQUARE=y.CAP_SQUARE,vr.MAX_PRECISION_DIGITS=12;var dr=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],yr=function(){function e(n){t(this,e),this.geometryFactory=n||new ae}return n(e,[{key:"read",value:function(t){var e,n=(e="string"==typeof t?JSON.parse(t):t).type;if(!mr[n])throw new Error("Unknown GeoJSON type: "+e.type);return-1!==dr.indexOf(n)?mr[n].call(this,e.coordinates):"GeometryCollection"===n?mr[n].call(this,e.geometries):mr[n].call(this,e)}},{key:"write",value:function(t){var e=t.getGeometryType();if(!_r[e])throw new Error("Geometry is not supported");return _r[e].call(this,t)}}]),e}(),mr={Feature:function(t){var e={};for(var n in t)e[n]=t[n];if(t.geometry){var r=t.geometry.type;if(!mr[r])throw new Error("Unknown GeoJSON type: "+t.type);e.geometry=this.read(t.geometry)}return t.bbox&&(e.bbox=mr.bbox.call(this,t.bbox)),e},FeatureCollection:function(t){var e={};if(t.features){e.features=[];for(var n=0;n1?0:t<-1?Xn:Math.acos(t)}function ir(t){return t>1?Un:t<-1?-Un:Math.asin(t)}function or(){}function sr(t,e){t&&ur.hasOwnProperty(t.type)&&ur[t.type](t,e)}var ar={Feature:function(t,e){sr(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++rXn?t-Hn:t<-Xn?t+Hn:t,e]}function xr(t){return function(e,n){return[(e+=t)>Xn?e-Hn:e<-Xn?e+Hn:e,n]}}function Er(t){var e=xr(t);return e.invert=xr(-t),e}function kr(t,e){var n=tr(t),r=er(t),i=tr(e),o=er(e);function s(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*n+a*r;return[$n(u*i-h*o,a*n-l*r),ir(h*i+u*o)]}return s.invert=function(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*i-u*o;return[$n(u*i+l*o,a*n+h*r),ir(h*n-a*r)]},s}function br(t,e){(e=fr(e))[0]-=t,yr(e);var n=rr(-e[1]);return((-e[2]<0?-n:n)+Hn-jn)%Hn}function wr(){var t,e=[];return{point:function(e,n){t.push([e,n])},lineStart:function(){e.push(t=[])},lineEnd:or,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function Ir(t,e){return Kn(t[0]-e[0])=0;--o)i.point((h=l[o])[0],h[1]);else r(f.x,f.p.x,-1,i);f=f.p}l=(f=f.o).z,g=!g}while(!f.v);i.lineEnd()}}}function Mr(t){if(e=t.length){for(var e,n,r=0,i=t[0];++re?1:t>=e?0:NaN}function Pr(t){for(var e,n,r,i=t.length,o=-1,s=0;++o=0;)for(e=(r=t[i]).length;--e>=0;)n[--s]=r[e];return n}Gn(),Gn(),Gn(),_r.invert=_r,function(t){var e;1===t.length&&(e=t,t=function(t,n){return Lr(e(t),n)})}(Lr);var Cr=1e9,Tr=-Cr;function Or(t,e,n,r){function i(i,o){return t<=i&&i<=n&&e<=o&&o<=r}function o(i,o,a,l){var h=0,c=0;if(null==i||(h=s(i,a))!==(c=s(o,a))||u(i,o)<0^a>0)do{l.point(0===h||3===h?t:n,h>1?r:e)}while((h=(h+a+4)%4)!==c);else l.point(o[0],o[1])}function s(r,i){return Kn(r[0]-t)0?0:3:Kn(r[0]-n)0?2:1:Kn(r[1]-e)0?1:0:i>0?3:2}function a(t,e){return u(t.x,e.x)}function u(t,e){var n=s(t,1),r=s(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){var u,l,h,c,f,g,p,v,d,y,m,_=s,x=wr(),E={point:k,lineStart:function(){E.point=b,l&&l.push(h=[]);y=!0,d=!1,p=v=NaN},lineEnd:function(){u&&(b(c,f),g&&d&&x.rejoin(),u.push(x.result()));E.point=k,d&&_.lineEnd()},polygonStart:function(){_=x,u=[],l=[],m=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,i=l.length;nr&&(f-o)*(r-s)>(g-s)*(t-o)&&++e:g<=r&&(f-o)*(r-s)<(g-s)*(t-o)&&--e;return e}(),n=m&&e,i=(u=Pr(u)).length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),o(null,null,1,s),s.lineEnd()),i&&Sr(u,a,e,o,s),s.polygonEnd());_=s,u=l=h=null}};function k(t,e){i(t,e)&&_.point(t,e)}function b(o,s){var a=i(o,s);if(l&&h.push([o,s]),y)c=o,f=s,g=a,y=!1,a&&(_.lineStart(),_.point(o,s));else if(a&&d)_.point(o,s);else{var u=[p=Math.max(Tr,Math.min(Cr,p)),v=Math.max(Tr,Math.min(Cr,v))],x=[o=Math.max(Tr,Math.min(Cr,o)),s=Math.max(Tr,Math.min(Cr,s))];!function(t,e,n,r,i,o){var s,a=t[0],u=t[1],l=0,h=1,c=e[0]-a,f=e[1]-u;if(s=n-a,c||!(s>0)){if(s/=c,c<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=i-a,c||!(s<0)){if(s/=c,c<0){if(s>h)return;s>l&&(l=s)}else if(c>0){if(s0)){if(s/=f,f<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=o-u,f||!(s<0)){if(s/=f,f<0){if(s>h)return;s>l&&(l=s)}else if(f>0){if(s0&&(t[0]=a+l*c,t[1]=u+l*f),h<1&&(e[0]=a+h*c,e[1]=u+h*f),!0}}}}}(u,x,t,e,n,r)?a&&(_.lineStart(),_.point(o,s),m=!1):(d||(_.lineStart(),_.point(u[0],u[1])),_.point(x[0],x[1]),a||_.lineEnd(),m=!1)}p=o,v=s,d=a}return E}}var Rr=Gn();function Ar(t){return t}Gn(),Gn(),Gn();var Dr=1/0,Fr=Dr,qr=-Dr,Vr=qr,Gr={point:function(t,e){tqr&&(qr=t);eVr&&(Vr=e)},lineStart:or,lineEnd:or,polygonStart:or,polygonEnd:or,result:function(){var t=[[Dr,Fr],[qr,Vr]];return qr=Vr=-(Fr=Dr=1/0),t}};function Br(t,e,n,r){return function(i,o){var s,a,u,l=e(o),h=i.invert(r[0],r[1]),c=wr(),f=e(c),g=!1,p={point:v,lineStart:y,lineEnd:m,polygonStart:function(){p.point=_,p.lineStart=x,p.lineEnd=E,a=[],s=[]},polygonEnd:function(){p.point=v,p.lineStart=y,p.lineEnd=m,a=Pr(a);var t=function(t,e){var n=e[0],r=e[1],i=[er(n),-tr(n),0],o=0,s=0;Rr.reset();for(var a=0,u=t.length;a=0?1:-1,w=b*k,I=w>Xn,N=p*x;if(Rr.add($n(N*b*er(w),v*E+N*tr(w))),o+=I?k+b*Hn:k,I^f>=n^m>=n){var S=pr(fr(c),fr(y));yr(S);var M=pr(i,S);yr(M);var L=(I^k>=0?-1:1)*ir(M[2]);(r>L||r===L&&(S[0]||S[1]))&&(s+=I^k>=0?1:-1)}}return(o<-jn||o0){for(g||(o.polygonStart(),g=!0),o.lineStart(),t=0;t1&&2&i&&l.push(l.pop().concat(l.shift())),a.push(l.filter(Yr))}return p}}function Yr(t){return t.length>1}function zr(t,e){return((t=t.x)[0]<0?t[1]-Un-jn:Un-t[1])-((e=e.x)[0]<0?e[1]-Un-jn:Un-e[1])}Gn();var jr=Br((function(){return!0}),(function(t){var e,n=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,s){var a=o>0?Xn:-Xn,u=Kn(o-n);Kn(u-Xn)0?Un:-Un),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),e=0):i!==a&&u>=Xn&&(Kn(n-i)jn?Qn((er(e)*(o=tr(r))*er(n)-er(r)*(i=tr(e))*er(t))/(i*o*s)):(e+r)/2}(n,r,o,s),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),e=0),t.point(n=o,r=s),i=a},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var i;if(null==t)i=n*Un,r.point(-Xn,i),r.point(0,i),r.point(Xn,i),r.point(Xn,0),r.point(Xn,-i),r.point(0,-i),r.point(-Xn,-i),r.point(-Xn,0),r.point(-Xn,i);else if(Kn(t[0]-e[0])>jn){var o=t[0]0,i=Kn(n)>jn;function o(t,e){return tr(t)*tr(e)>n}function s(t,e,r){var i=[1,0,0],o=pr(fr(t),fr(e)),s=gr(o,o),a=o[0],u=s-a*a;if(!u)return!r&&t;var l=n*s/u,h=-n*a/u,c=pr(i,o),f=dr(i,l);vr(f,dr(o,h));var g=c,p=gr(f,g),v=gr(g,g),d=p*p-v*(gr(f,f)-1);if(!(d<0)){var y=nr(d),m=dr(g,(-p-y)/v);if(vr(m,f),m=cr(m),!r)return m;var _,x=t[0],E=e[0],k=t[1],b=e[1];E0^m[1]<(Kn(m[0]-x)Xn^(x<=m[0]&&m[0]<=E)){var N=dr(g,(-p+y)/v);return vr(N,f),[m,cr(N)]}}}function a(e,n){var i=r?t:Xn-t,o=0;return e<-i?o|=1:e>i&&(o|=2),n<-i?o|=4:n>i&&(o|=8),o}return Br(o,(function(t){var e,n,u,l,h;return{lineStart:function(){l=u=!1,h=1},point:function(c,f){var g,p=[c,f],v=o(c,f),d=r?v?0:a(c,f):v?a(c+(c<0?Xn:-Xn),f):0;if(!e&&(l=u=v)&&t.lineStart(),v!==u&&(!(g=s(e,p))||Ir(e,g)||Ir(p,g))&&(p[0]+=jn,p[1]+=jn,v=o(p[0],p[1])),v!==u)h=0,v?(t.lineStart(),g=s(p,e),t.point(g[0],g[1])):(g=s(e,p),t.point(g[0],g[1]),t.lineEnd()),e=g;else if(i&&e&&r^v){var y;d&n||!(y=s(p,e,!0))||(h=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1])))}!v||e&&Ir(e,p)||t.point(p[0],p[1]),e=p,u=v,n=d},lineEnd:function(){u&&t.lineEnd(),e=null},clean:function(){return h|(l&&u)<<1}}}),(function(n,r,i,o){!function(t,e,n,r,i,o){if(n){var s=tr(e),a=er(e),u=r*n;null==i?(i=e+r*Hn,o=e-u/2):(i=br(s,i),o=br(s,o),(r>0?io)&&(i+=r*Hn));for(var l,h=i;r>0?h>o:h4*e&&v--){var x=s+f,E=a+g,k=u+p,b=nr(x*x+E*E+k*k),w=ir(k/=b),I=Kn(Kn(k)-1)e||Kn((y*L+m*P)/_-.5)>.3||s*f+a*g+u*p2?t[2]%360*Jn:0,M()):[d*Wn,y*Wn,m*Wn]},I.precision=function(t){return arguments.length?(w=Kr(S,b=t*t),L()):nr(b)},I.fitExtent=function(t,e){return Hr(I,t,e)},I.fitSize=function(t,e){return function(t,e,n){return Hr(t,[[0,0],e],n)}(I,t,e)},function(){return e=t.apply(this,arguments),I.invert=e.invert&&N,M()}}((function(){return t}))()}function ti(t){return function(e,n){var r=tr(e),i=tr(n),o=t(r*i);return[o*i*er(e),o*er(n)]}}function ei(t){return function(e,n){var r=nr(e*e+n*n),i=t(r),o=er(i),s=tr(i);return[$n(e*o,r*s),ir(r&&n*o/r)]}}ti((function(t){return nr(2/(1+t))})).invert=ei((function(t){return 2*ir(t/2)}));var ni=ti((function(t){return(t=rr(t))&&t/er(t)}));function ri(){return $r(ni).scale(79.4188).clipAngle(179.999)}function ii(t,e){return[t,e]}ni.invert=ei((function(t){return t})),ii.invert=ii;var oi=Vn.BufferOp,si=Vn.GeoJSONReader,ai=Vn.GeoJSONWriter;function ui(t,e,n,r){var i=t.properties||{},o="Feature"===t.type?t.geometry:t;if("GeometryCollection"===o.type){var s=[];return mt(t,(function(t){var i=ui(t,e,n,r);i&&s.push(i)})),C(s)}var a=function(t){var e=An(t).geometry.coordinates,n=[-e[0],-e[1]];return ri().rotate(n).scale(x)}(o),u={type:o.type,coordinates:hi(o.coordinates,a)},l=(new si).read(u),h=F(q(e,n),"meters"),c=oi.bufferOp(l,h,r);if(!li((c=(new ai).write(c)).coordinates))return b({type:c.type,coordinates:ci(c.coordinates,a)},i)}function li(t){return Array.isArray(t[0])?li(t[0]):isNaN(t[0])}function hi(t,e){return"object"!==m(t[0])?e(t):t.map((function(t){return hi(t,e)}))}function ci(t,e){return"object"!==m(t[0])?e.invert(t):t.map((function(t){return ci(t,e)}))}function fi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return mt(t,(function(t,o,s){var a=e.weight?null==s?void 0:s[e.weight]:void 0;if(!U(a=null==a?1:a))throw new Error("weight value must be a number for feature index "+o);(a=Number(a))>0&&ct(t,(function(t){n+=t[0]*a,r+=t[1]*a,i+=a}))})),I([n/i,r/i],e.properties,e)}function gi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return ct(t,(function(t){n+=t[0],r+=t[1],i++}),!0),I([n/i,r/i],e.properties)}function pi(t,e,n,r,i){var o=r.tolerance||.001,s=0,a=0,u=0,l=0;if(vt(n,(function(e){var n,r=null==(n=e.properties)?void 0:n.weight,i=null==r?1:r;if(!U(i=Number(i)))throw new Error("weight value must be a number");if(i>0){l+=1;var o=i*ut(e,t);0===o&&(o=1);var h=i/o;s+=e.geometry.coordinates[0]*h,a+=e.geometry.coordinates[1]*h,u+=h}})),l<1)throw new Error("no features to measure");var h=s/u,c=a/u;return 1===l||0===i||Math.abs(h-e[0])0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mi;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function mi(t,e){return te?1:0}var _i,xi,Ei,ki,bi,wi=_n(Object.freeze({__proto__:null,default:yi})),Ii={exports:{}};function Ni(){if(bi)return Ii.exports;bi=1;var t=(xi||(xi=1,_i=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=(r-n)/2,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),_i),e=(ki||(ki=1,Ei=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=r-n,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),Ei);return Ii.exports=function(n,r,i,o){return r.length>0&&Array.isArray(r[0])?e(n,r,i,o):t(n,r,i,o)},Ii.exports.nested=e,Ii.exports.flat=t,Ii.exports}var Si,Mi,Li={exports:{}};Li.exports;function Pi(){return Si||(Si=1,function(t,e){!function(t){var e=134217729,n=33306690738754706e-32;function r(t,e,n,r,i){var o,s,a,u,l=e[0],h=r[0],c=0,f=0;h>l==h>-l?(o=l,l=e[++c]):(o=h,h=r[++f]);var g=0;if(cl==h>-l?(a=o-((s=l+o)-l),l=e[++c]):(a=o-((s=h+o)-h),h=r[++f]),o=s,0!==a&&(i[g++]=a);cl==h>-l?(a=o-((s=o+l)-(u=s-o))+(l-u),l=e[++c]):(a=o-((s=o+h)-(u=s-o))+(h-u),h=r[++f]),o=s,0!==a&&(i[g++]=a);for(;c0!=m>0)return _;var x=Math.abs(y+m);return Math.abs(_)>=o*x?_:-function(t,i,o,g,p,v,d){var y,m,_,x,E,k,b,w,I,N,S,M,L,P,C,T,O,R,A=t-p,D=o-p,F=i-v,q=g-v;E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=q-(I=(k=e*q)-(k-q)))-((P=A*q)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=D-(I=(k=e*D)-(k-D)))-((T=F*D)-b*I-w*I-b*N))),u[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),u[1]=L-(S+E)+(E-T),E=(R=M+S)-M,u[2]=M-(R-E)+(S-E),u[3]=R;var V=function(t,e){for(var n=e[0],r=1;r=G||-V>=G)return V;if(y=t-(A+(E=t-A))+(E-p),_=o-(D+(E=o-D))+(E-p),m=i-(F+(E=i-F))+(E-v),x=g-(q+(E=g-q))+(E-v),0===y&&0===m&&0===_&&0===x)return V;if(G=a*d+n*Math.abs(V),(V+=A*x+q*y-(F*_+D*m))>=G||-V>=G)return V;E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=q-(I=(k=e*q)-(k-q)))-((P=y*q)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=D-(I=(k=e*D)-(k-D)))-((T=m*D)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var B=r(4,u,4,f,l);E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=x-(I=(k=e*x)-(k-x)))-((P=A*x)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=_-(I=(k=e*_)-(k-_)))-((T=F*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var Y=r(B,l,4,f,h);E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=x-(I=(k=e*x)-(k-x)))-((P=y*x)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=_-(I=(k=e*_)-(k-_)))-((T=m*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var z=r(Y,h,4,f,c);return c[z-1]}(t,i,g,p,v,d,x)},t.orient2dfast=function(t,e,n,r,i,o){return(e-o)*(n-i)-(t-i)*(r-o)},Object.defineProperty(t,"__esModule",{value:!0})}(e)}(0,Li.exports)),Li.exports}var Ci=function(){if(Mi)return vi.exports;Mi=1;var t=di,e=wi,n=Ni(),r=Pi().orient2d;function i(e,r,i){r=Math.max(0,void 0===r?2:r),i=i||0;var s=function(t){for(var e=t[0],r=t[0],i=t[0],o=t[0],s=0;si[0]&&(i=a),a[1]o[1]&&(o=a)}var u=[e,r,i,o],l=u.slice();for(s=0;s=2&&h(e[e.length-2],e[e.length-1],t[n])<=0;)e.pop();e.push(t[n])}for(var r=[],i=t.length-1;i>=0;i--){for(;r.length>=2&&h(r[r.length-2],r[r.length-1],t[i])<=0;)r.pop();r.push(t[i])}return r.pop(),e.pop(),e.concat(r)}(l)}(e),a=new t(16);a.toBBox=function(t){return{minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]}},a.compareMinX=function(t,e){return t[0]-e[0]},a.compareMinY=function(t,e){return t[1]-e[1]},a.load(e);for(var u,l=[],p=0;pu||c.push({node:v,dist:d})}for(;c.length&&!c.peek().node.children;){var y=c.pop(),m=y.node,_=p(m,n,r),x=p(m,i,o);if(y.dist<_&&y.dist=e.minX&&t[0]<=e.maxX&&t[1]>=e.minY&&t[1]<=e.maxY}function l(t,e,n){for(var r,i,o,s,a=Math.min(t[0],e[0]),u=Math.min(t[1],e[1]),l=Math.max(t[0],e[0]),c=Math.max(t[1],e[1]),f=n.search({minX:a,minY:u,maxX:l,maxY:c}),g=0;g0!=h(r,i,s)>0&&h(o,s,r)>0!=h(o,s,i)>0)return!1;return!0}function h(t,e,n){return r(t[0],t[1],e[0],e[1],n[0],n[1])}function c(t){var e=t.p,n=t.next.p;return t.minX=Math.min(e[0],n[0]),t.minY=Math.min(e[1],n[1]),t.maxX=Math.max(e[0],n[0]),t.maxY=Math.max(e[1],n[1]),t}function f(t,e){var n={p:t,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return e?(n.next=e.next,n.prev=e,e.next.prev=n,e.next=n):(n.prev=n,n.next=n),n}function g(t,e){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function p(t,e,n){var r=e[0],i=e[1],o=n[0]-r,s=n[1]-i;if(0!==o||0!==s){var a=((t[0]-r)*o+(t[1]-i)*s)/(o*o+s*s);a>1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function v(t,e,n,r,i,o,s,a){var u,l,h,c,f=n-t,g=r-e,p=s-i,v=a-o,d=t-i,y=e-o,m=f*f+g*g,_=f*p+g*v,x=p*p+v*v,E=f*d+g*y,k=p*d+v*y,b=m*x-_*_,w=b,I=b;0===b?(l=0,w=1,c=k,I=x):(c=m*k-_*E,(l=_*k-x*E)<0?(l=0,c=k,I=x):l>w&&(l=w,c=k+_,I=x)),c<0?(c=0,-E<0?l=0:-E>m?l=w:(l=-E,w=m)):c>I&&(c=I,-E+_<0?l=0:-E+_>m?l=w:(l=-E+_,w=m));var N=(1-(h=0===c?0:c/I))*i+h*s-((1-(u=0===l?0:l/w))*t+u*n),S=(1-h)*o+h*a-((1-u)*e+u*r);return N*N+S*S}function d(t,e){return t[0]===e[0]?t[1]-e[1]:t[0]-e[0]}return e.default&&(e=e.default),vi.exports=i,vi.exports.default=i,vi.exports}(),Ti=mn(Ci);function Oi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e.concavity=e.concavity||1/0;var n=[];if(ct(t,(function(t){n.push([t[0],t[1]])})),!n.length)return null;var r=Ti(n,e.concavity);return r.length>3?S([r]):null}function Ri(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.steps||64,i=n.properties?n.properties:!Array.isArray(t)&&"Feature"===t.type&&t.properties?t.properties:{},o=[],s=0;s0;r.length0;){var a=t[Math.floor(Math.random()*o)],u=s?a.join("_"):""+a;n[u]||(n[u]=!0,r.push(a))}if(r.length0,u=t[Math.floor(Math.random()*s)];for(a&&u.join("_"),o.push(u);o.length0,y=[];if(s)u="kmrand"==s?r(t,e):"kmpp"==s?i(t,e):s;else for(var m={};u.lengthc&&(c=t[a].y);var g,p=l-u,v=c-h,d=p>v?p:v,y=.5*(l+u),m=.5*(c+h),_=[new so({__sentinel:!0,x:y-20*d,y:m-d},{__sentinel:!0,x:y,y:m+20*d},{__sentinel:!0,x:y+20*d,y:m-d})],x=[],E=[];a=t.length;for(;a--;){for(E.length=0,g=_.length;g--;)(p=t[a].x-_[g].x)>0&&p*p>_[g].r?(x.push(_[g]),_.splice(g,1)):p*p+(v=t[a].y-_[g].y)*v>_[g].r||(E.push(_[g].a,_[g].b,_[g].b,_[g].c,_[g].c,_[g].a),_.splice(g,1));for(uo(E),g=E.length;g;)n=E[--g],e=E[--g],r=t[a],i=n.x-e.x,o=n.y-e.y,s=2*(i*(r.y-n.y)-o*(r.x-n.x)),Math.abs(s)>f&&_.push(new so(e,n,r))}Array.prototype.push.apply(x,_),a=x.length;for(;a--;)(x[a].a.__sentinel||x[a].b.__sentinel||x[a].c.__sentinel)&&x.splice(a,1);return x}(t.features.map((function(t){var r={x:t.geometry.coordinates[0],y:t.geometry.coordinates[1]};return e?r.z=t.properties[e]:3===t.geometry.coordinates.length&&(n=!0,r.z=t.geometry.coordinates[2]),r}))).map((function(t){var e=[t.a.x,t.a.y],r=[t.b.x,t.b.y],i=[t.c.x,t.c.y],o={};return n?(e.push(t.a.z),r.push(t.b.z),i.push(t.c.z)):o={a:t.a.z,b:t.b.z,c:t.c.z},S([[e,r,i,e]],o)})))}var so=s((function t(e,n,r){i(this,t),this.a=e,this.b=n,this.c=r;var o,s,a=n.x-e.x,u=n.y-e.y,l=r.x-e.x,h=r.y-e.y,c=a*(e.x+n.x)+u*(e.y+n.y),f=l*(e.x+r.x)+h*(e.y+r.y),g=2*(a*(r.y-n.y)-u*(r.x-n.x));this.x=(h*c-u*f)/g,this.y=(a*f-l*c)/g,o=this.x-e.x,s=this.y-e.y,this.r=o*o+s*s}));function ao(t,e){return e.x-t.x}function uo(t){var e,n,r,i,o,s=t.length;t:for(;s;)for(n=t[--s],e=t[--s],r=s;r;)if(o=t[--r],e===(i=t[--r])&&n===o||e===o&&n===i){t.splice(s,2),t.splice(r,2),s-=2;continue t}}function lo(t){return t}function ho(t,e){var n=function(t){if(null==t)return lo;var e,n,r=t.scale[0],i=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,a){a||(e=n=0);var u=2,l=t.length,h=new Array(l);for(h[0]=(e+=t[0])*r+o,h[1]=(n+=t[1])*i+s;u1)for(var o,a,u=1,l=s(i[0]);ul&&(a=i[0],i[0]=i[u],i[u]=a,l=o);return i})).filter((function(t){return t.length>0}))}}var po=Object.prototype.hasOwnProperty;function vo(t,e,n,r,i,o){3===arguments.length&&(r=o=Array,i=null);for(var s=new r(t=1<=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},maybeSet:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},get:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)break;h=s[l=l+1&u]}return o},keys:function(){for(var t=[],e=0,n=s.length;e>7^xo[2]^xo[3])}function ko(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=function(){for(var t=vo(1.4*o.length,E,k,Int32Array,-1,Int32Array),e=new Int32Array(o.length),n=0,r=o.length;n=0){var o=c[n];i===e&&o===r||i===r&&o===e||(++g,f[n]=1)}else h[n]=e,c[n]=r}}function E(t){return Eo(o[t])}function k(t,e){return yo(o[t],o[e])}l=h=c=null;var b,w=function(t,e,n,r,i){3===arguments.length&&(r=Array,i=null);for(var o=new r(t=1<=t)throw new Error("full hashset");u=o[a=a+1&s]}return o[a]=r,!0},has:function(r){for(var a=e(r)&s,u=o[a],l=0;u!=i;){if(n(u,r))return!0;if(++l>=t)break;u=o[a=a+1&s]}return!1},values:function(){for(var t=[],e=0,n=o.length;e>1);er&&(r=o),si&&(i=s)}function u(t){t.forEach(a)}function l(t){t.forEach(u)}for(var h in t)o(t[h]);return r>=e&&i>=n?[e,n,r,i]:void 0}(t=Io(t)),r=function(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=s.length+a.length;for(delete t.lines,delete t.rings,r=0,i=s.length;r1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=[],i=It(t,(function(t,e){var n=function(t,e){var n,r=t.geometry.coordinates,i=e.geometry.coordinates,o=Oo(r[0]),s=Oo(r[r.length-1]),a=Oo(i[0]),u=Oo(i[i.length-1]);if(o===u)n=i.concat(r.slice(1));else if(a===s)n=r.concat(i.slice(1));else if(o===a)n=r.slice(1).reverse().concat(i);else{if(s!==u)return null;n=r.concat(i.reverse().slice(1))}return L(n)}(t,e);return n||(r.push(t),e)}));return i&&r.push(i),r.length?1===r.length?r[0]:T(r.map((function(t){return t.coordinates}))):null}function Oo(t){return t[0].toString()+","+t[1].toString()}function Ro(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=function(t){var e={};xt(t,(function(t){e[t.geometry.type]=!0}));var n=Object.keys(e);if(1===n.length)return n[0];return null}(t);if(!r)throw new Error("geojson must be homogenous");var i=t;switch(r){case"LineString":return To(i,e);case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==e.mutate&&void 0!==e.mutate||(t=Ai(t));var n=[];xt(t,(function(t){n.push(t.geometry)}));var r=Lo({geoms:A(n).geometry});return fo(r,r.objects.geoms.geometries)}(i,e);default:throw new Error(r+" is not supported")}}var Ao=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Do=Math.ceil,Fo=Math.floor,qo="[BigNumber Error] ",Vo=qo+"Number primitive has more than 15 significant digits: ",Go=1e14,Bo=14,Yo=9007199254740991,zo=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Xo=1e9;function Uo(t){var e=0|t;return t>0||t===e?e:e-1}function Zo(t){for(var e,n,r=1,i=t.length,o=t[0]+"";rl^n?1:-1;for(a=(u=i.length)<(l=o.length)?u:l,s=0;so[s]^n?1:-1;return u==l?0:u>l^n?1:-1}function Wo(t,e,n,r){if(tn||t!==Fo(t))throw Error(qo+(r||"Argument")+("number"==typeof t?tn?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Jo(t){var e=t.c.length-1;return Uo(t.e/Bo)==e&&t.c[e]%2!=0}function Ko(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Qo(t,e,n){var r,i;if(e<0){for(i=n+".";++e;i+=n);t=i+t}else if(++e>(r=t.length)){for(i=n,e-=r;--e;i+=n);t+=i}else ex?f.c=f.e=null:t.e<_?f.c=[f.e=0]:(f.e=t.e,f.c=t.c.slice()));if((l="number"==typeof t)&&0*t==0){if(f.s=1/t<0?(t=-t,-1):1,t===~~t){for(a=0,u=t;u>=10;u/=10,a++);return void(a>x?f.c=f.e=null:(f.e=a,f.c=[t]))}c=String(t)}else{if(!Ao.test(c=String(t)))return i(f,c,l);f.s=45==c.charCodeAt(0)?(c=c.slice(1),-1):1}(a=c.indexOf("."))>-1&&(c=c.replace(".","")),(u=c.search(/e/i))>0?(a<0&&(a=u),a+=+c.slice(u+1),c=c.substring(0,u)):a<0&&(a=c.length)}else{if(Wo(e,2,I.length,"Base"),10==e&&N)return C(f=new S(t),p+f.e+1,v);if(c=String(t),l="number"==typeof t){if(0*t!=0)return i(f,c,l,e);if(f.s=1/t<0?(c=c.slice(1),-1):1,S.DEBUG&&c.replace(/^0\.0*|\./,"").length>15)throw Error(Vo+t)}else f.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1;for(n=I.slice(0,e),a=u=0,h=c.length;ua){a=h;continue}}else if(!s&&(c==c.toUpperCase()&&(c=c.toLowerCase())||c==c.toLowerCase()&&(c=c.toUpperCase()))){s=!0,u=-1,a=0;continue}return i(f,String(t),l,e)}l=!1,(a=(c=r(c,e,10,f.s)).indexOf("."))>-1?c=c.replace(".",""):a=c.length}for(u=0;48===c.charCodeAt(u);u++);for(h=c.length;48===c.charCodeAt(--h););if(c=c.slice(u,++h)){if(h-=u,l&&S.DEBUG&&h>15&&(t>Yo||t!==Fo(t)))throw Error(Vo+f.s*t);if((a=a-u-1)>x)f.c=f.e=null;else if(a<_)f.c=[f.e=0];else{if(f.e=a,f.c=[],u=(a+1)%Bo,a<0&&(u+=Bo),u=y)?Ko(u,s):Qo(u,s,"0");else if(o=(t=C(new S(t),e,n)).e,a=(u=Zo(t.c)).length,1==r||2==r&&(e<=o||o<=d)){for(;aa){if(--e>0)for(u+=".";e--;u+="0");}else if((e+=o-a)>0)for(o+1==a&&(u+=".");e--;u+="0");return t.s<0&&i?"-"+u:u}function L(t,e){for(var n,r,i=1,o=new S(t[0]);i=10;i/=10,r++);return(n=r+n*Bo-1)>x?t.c=t.e=null:n<_?t.c=[t.e=0]:(t.e=n,t.c=e),t}function C(t,e,n,r){var i,o,s,a,u,l,h,c=t.c,f=zo;if(c){t:{for(i=1,a=c[0];a>=10;a/=10,i++);if((o=e-i)<0)o+=Bo,s=e,u=c[l=0],h=Fo(u/f[i-s-1]%10);else if((l=Do((o+1)/Bo))>=c.length){if(!r)break t;for(;c.length<=l;c.push(0));u=h=0,i=1,s=(o%=Bo)-Bo+1}else{for(u=a=c[l],i=1;a>=10;a/=10,i++);h=(s=(o%=Bo)-Bo+i)<0?0:Fo(u/f[i-s-1]%10)}if(r=r||e<0||null!=c[l+1]||(s<0?u:u%f[i-s-1]),r=n<4?(h||r)&&(0==n||n==(t.s<0?3:2)):h>5||5==h&&(4==n||r||6==n&&(o>0?s>0?u/f[i-s]:0:c[l-1])%10&1||n==(t.s<0?8:7)),e<1||!c[0])return c.length=0,r?(e-=t.e+1,c[0]=f[(Bo-e%Bo)%Bo],t.e=-e||0):c[0]=t.e=0,t;if(0==o?(c.length=l,a=1,l--):(c.length=l+1,a=f[Bo-o],c[l]=s>0?Fo(u/f[i-s]%f[s])*a:0),r)for(;;){if(0==l){for(o=1,s=c[0];s>=10;s/=10,o++);for(s=c[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(t.e++,c[0]==Go&&(c[0]=1));break}if(c[l]+=a,c[l]!=Go)break;c[l--]=0,a=1}for(o=c.length;0===c[--o];c.pop());}t.e>x?t.c=t.e=null:t.e<_&&(t.c=[t.e=0])}return t}function T(t){var e,n=t.e;return null===n?t.toString():(e=Zo(t.c),e=n<=d||n>=y?Ko(e,n):Qo(e,n,"0"),t.s<0?"-"+e:e)}return S.clone=t,S.ROUND_UP=0,S.ROUND_DOWN=1,S.ROUND_CEIL=2,S.ROUND_FLOOR=3,S.ROUND_HALF_UP=4,S.ROUND_HALF_DOWN=5,S.ROUND_HALF_EVEN=6,S.ROUND_HALF_CEIL=7,S.ROUND_HALF_FLOOR=8,S.EUCLID=9,S.config=S.set=function(t){var e,n;if(null!=t){if("object"!=m(t))throw Error(qo+"Object expected: "+t);if(t.hasOwnProperty(e="DECIMAL_PLACES")&&(Wo(n=t[e],0,Xo,e),p=n),t.hasOwnProperty(e="ROUNDING_MODE")&&(Wo(n=t[e],0,8,e),v=n),t.hasOwnProperty(e="EXPONENTIAL_AT")&&((n=t[e])&&n.pop?(Wo(n[0],-Xo,0,e),Wo(n[1],0,Xo,e),d=n[0],y=n[1]):(Wo(n,-Xo,Xo,e),d=-(y=n<0?-n:n))),t.hasOwnProperty(e="RANGE"))if((n=t[e])&&n.pop)Wo(n[0],-Xo,-1,e),Wo(n[1],1,Xo,e),_=n[0],x=n[1];else{if(Wo(n,-Xo,Xo,e),!n)throw Error(qo+e+" cannot be zero: "+n);_=-(x=n<0?-n:n)}if(t.hasOwnProperty(e="CRYPTO")){if((n=t[e])!==!!n)throw Error(qo+e+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw E=!n,Error(qo+"crypto unavailable");E=n}else E=n}if(t.hasOwnProperty(e="MODULO_MODE")&&(Wo(n=t[e],0,9,e),k=n),t.hasOwnProperty(e="POW_PRECISION")&&(Wo(n=t[e],0,Xo,e),b=n),t.hasOwnProperty(e="FORMAT")){if("object"!=m(n=t[e]))throw Error(qo+e+" not an object: "+n);w=n}if(t.hasOwnProperty(e="ALPHABET")){if("string"!=typeof(n=t[e])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(qo+e+" invalid: "+n);N="0123456789"==n.slice(0,10),I=n}}return{DECIMAL_PLACES:p,ROUNDING_MODE:v,EXPONENTIAL_AT:[d,y],RANGE:[_,x],CRYPTO:E,MODULO_MODE:k,POW_PRECISION:b,FORMAT:w,ALPHABET:I}},S.isBigNumber=function(t){if(!t||!0!==t._isBigNumber)return!1;if(!S.DEBUG)return!0;var e,n,r=t.c,i=t.e,o=t.s;t:if("[object Array]"=={}.toString.call(r)){if((1===o||-1===o)&&i>=-Xo&&i<=Xo&&i===Fo(i)){if(0===r[0]){if(0===i&&1===r.length)return!0;break t}if((e=(i+1)%Bo)<1&&(e+=Bo),String(r[0]).length==e){for(e=0;e=Go||n!==Fo(n))break t;if(0!==n)return!0}}}else if(null===r&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(qo+"Invalid BigNumber: "+t)},S.maximum=S.max=function(){return L(arguments,-1)},S.minimum=S.min=function(){return L(arguments,1)},S.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Fo(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(t){var e,n,r,i,o,a=0,u=[],l=new S(g);if(null==t?t=p:Wo(t,0,Xo),i=Do(t/Bo),E)if(crypto.getRandomValues){for(e=crypto.getRandomValues(new Uint32Array(i*=2));a>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),e[a]=n[0],e[a+1]=n[1]):(u.push(o%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw E=!1,Error(qo+"crypto unavailable");for(e=crypto.randomBytes(i*=7);a=9e15?crypto.randomBytes(7).copy(e,a):(u.push(o%1e14),a+=7);a=i/7}if(!E)for(;a=10;o/=10,a++);an-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(r,i,o,s,a){var u,l,h,c,f,g,d,y,m=r.indexOf("."),_=p,x=v;for(m>=0&&(c=b,b=0,r=r.replace(".",""),g=(y=new S(i)).pow(r.length-m),b=c,y.c=e(Qo(Zo(g.c),g.e,"0"),10,o,t),y.e=y.c.length),h=c=(d=e(r,i,o,a?(u=I,t):(u=t,I))).length;0==d[--c];d.pop());if(!d[0])return u.charAt(0);if(m<0?--h:(g.c=d,g.e=h,g.s=s,d=(g=n(g,y,_,x,o)).c,f=g.r,h=g.e),m=d[l=h+_+1],c=o/2,f=f||l<0||null!=d[l+1],f=x<4?(null!=m||f)&&(0==x||x==(g.s<0?3:2)):m>c||m==c&&(4==x||f||6==x&&1&d[l-1]||x==(g.s<0?8:7)),l<1||!d[0])r=f?Qo(u.charAt(1),-_,u.charAt(0)):u.charAt(0);else{if(d.length=l,f)for(--o;++d[--l]>o;)d[l]=0,l||(++h,d=[1].concat(d));for(c=d.length;!d[--c];);for(m=0,r="";m<=c;r+=u.charAt(d[m++]));r=Qo(r,h,u.charAt(0))}return r}}(),n=function(){function t(t,e,n){var r,i,o,s,a=0,u=t.length,l=e%jo,h=e/jo|0;for(t=t.slice();u--;)a=((i=l*(o=t[u]%jo)+(r=h*o+(s=t[u]/jo|0)*l)%jo*jo+a)/n|0)+(r/jo|0)+h*s,t[u]=i%n;return a&&(t=[a].concat(t)),t}function e(t,e,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;ie[i]?1:-1;break}return o}function n(t,e,n,r){for(var i=0;n--;)t[n]-=i,i=t[n]1;t.splice(0,1));}return function(r,i,o,s,a){var u,l,h,c,f,g,p,v,d,y,m,_,x,E,k,b,w,I=r.s==i.s?1:-1,N=r.c,M=i.c;if(!(N&&N[0]&&M&&M[0]))return new S(r.s&&i.s&&(N?!M||N[0]!=M[0]:M)?N&&0==N[0]||!M?0*I:I/0:NaN);for(d=(v=new S(I)).c=[],I=o+(l=r.e-i.e)+1,a||(a=Go,l=Uo(r.e/Bo)-Uo(i.e/Bo),I=I/Bo|0),h=0;M[h]==(N[h]||0);h++);if(M[h]>(N[h]||0)&&l--,I<0)d.push(1),c=!0;else{for(E=N.length,b=M.length,h=0,I+=2,(f=Fo(a/(M[0]+1)))>1&&(M=t(M,f,a),N=t(N,f,a),b=M.length,E=N.length),x=b,m=(y=N.slice(0,b)).length;m=a/2&&k++;do{if(f=0,(u=e(M,y,b,m))<0){if(_=y[0],b!=m&&(_=_*a+(y[1]||0)),(f=Fo(_/k))>1)for(f>=a&&(f=a-1),p=(g=t(M,f,a)).length,m=y.length;1==e(g,y,p,m);)f--,n(g,b=10;I/=10,h++);C(v,o+(v.e=h+l*Bo-1)+1,s,c)}else v.e=l,v.r=+c;return v}}(),a=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,l=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,c=/^\s*\+(?=[\w.])|^\s+|\s+$/g,i=function(t,e,n,r){var i,o=n?e:e.replace(c,"");if(h.test(o))t.s=isNaN(o)?null:o<0?-1:1;else{if(!n&&(o=o.replace(a,(function(t,e,n){return i="x"==(n=n.toLowerCase())?16:"b"==n?2:8,r&&r!=i?t:e})),r&&(i=r,o=o.replace(u,"$1").replace(l,"0.$1")),e!=o))return new S(o,i);if(S.DEBUG)throw Error(qo+"Not a"+(r?" base "+r:"")+" number: "+e);t.s=null}t.c=t.e=null},f.absoluteValue=f.abs=function(){var t=new S(this);return t.s<0&&(t.s=1),t},f.comparedTo=function(t,e){return Ho(this,new S(t,e))},f.decimalPlaces=f.dp=function(t,e){var n,r,i,o=this;if(null!=t)return Wo(t,0,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t+o.e+1,e);if(!(n=o.c))return null;if(r=((i=n.length-1)-Uo(this.e/Bo))*Bo,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},f.dividedBy=f.div=function(t,e){return n(this,new S(t,e),p,v)},f.dividedToIntegerBy=f.idiv=function(t,e){return n(this,new S(t,e),0,1)},f.exponentiatedBy=f.pow=function(t,e){var n,r,i,o,s,a,u,l,h=this;if((t=new S(t)).c&&!t.isInteger())throw Error(qo+"Exponent not an integer: "+T(t));if(null!=e&&(e=new S(e)),s=t.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!t.c||!t.c[0])return l=new S(Math.pow(+T(h),s?t.s*(2-Jo(t)):+T(t))),e?l.mod(e):l;if(a=t.s<0,e){if(e.c?!e.c[0]:!e.s)return new S(NaN);(r=!a&&h.isInteger()&&e.isInteger())&&(h=h.mod(e))}else{if(t.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return o=h.s<0&&Jo(t)?-0:0,h.e>-1&&(o=1/o),new S(a?1/o:o);b&&(o=Do(b/Bo+2))}for(s?(n=new S(.5),a&&(t.s=1),u=Jo(t)):u=(i=Math.abs(+T(t)))%2,l=new S(g);;){if(u){if(!(l=l.times(h)).c)break;o?l.c.length>o&&(l.c.length=o):r&&(l=l.mod(e))}if(i){if(0===(i=Fo(i/2)))break;u=i%2}else if(C(t=t.times(n),t.e+1,1),t.e>14)u=Jo(t);else{if(0===(i=+T(t)))break;u=i%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):r&&(h=h.mod(e))}return r?l:(a&&(l=g.div(l)),e?l.mod(e):o?C(l,b,v,undefined):l)},f.integerValue=function(t){var e=new S(this);return null==t?t=v:Wo(t,0,8),C(e,e.e+1,t)},f.isEqualTo=f.eq=function(t,e){return 0===Ho(this,new S(t,e))},f.isFinite=function(){return!!this.c},f.isGreaterThan=f.gt=function(t,e){return Ho(this,new S(t,e))>0},f.isGreaterThanOrEqualTo=f.gte=function(t,e){return 1===(e=Ho(this,new S(t,e)))||0===e},f.isInteger=function(){return!!this.c&&Uo(this.e/Bo)>this.c.length-2},f.isLessThan=f.lt=function(t,e){return Ho(this,new S(t,e))<0},f.isLessThanOrEqualTo=f.lte=function(t,e){return-1===(e=Ho(this,new S(t,e)))||0===e},f.isNaN=function(){return!this.s},f.isNegative=function(){return this.s<0},f.isPositive=function(){return this.s>0},f.isZero=function(){return!!this.c&&0==this.c[0]},f.minus=function(t,e){var n,r,i,o,s=this,a=s.s;if(e=(t=new S(t,e)).s,!a||!e)return new S(NaN);if(a!=e)return t.s=-e,s.plus(t);var u=s.e/Bo,l=t.e/Bo,h=s.c,c=t.c;if(!u||!l){if(!h||!c)return h?(t.s=-e,t):new S(c?s:NaN);if(!h[0]||!c[0])return c[0]?(t.s=-e,t):new S(h[0]?s:3==v?-0:0)}if(u=Uo(u),l=Uo(l),h=h.slice(),a=u-l){for((o=a<0)?(a=-a,i=h):(l=u,i=c),i.reverse(),e=a;e--;i.push(0));i.reverse()}else for(r=(o=(a=h.length)<(e=c.length))?a:e,a=e=0;e0)for(;e--;h[n++]=0);for(e=Go-1;r>a;){if(h[--r]=0;){for(n=0,f=_[i]%d,g=_[i]/d|0,o=i+(s=u);o>i;)n=((l=f*(l=m[--s]%d)+(a=g*l+(h=m[s]/d|0)*f)%d*d+p[o]+n)/v|0)+(a/d|0)+g*h,p[o--]=l%v;p[o]=n}return n?++r:p.splice(0,1),P(t,p,r)},f.negated=function(){var t=new S(this);return t.s=-t.s||null,t},f.plus=function(t,e){var n,r=this,i=r.s;if(e=(t=new S(t,e)).s,!i||!e)return new S(NaN);if(i!=e)return t.s=-e,r.minus(t);var o=r.e/Bo,s=t.e/Bo,a=r.c,u=t.c;if(!o||!s){if(!a||!u)return new S(i/0);if(!a[0]||!u[0])return u[0]?t:new S(a[0]?r:0*i)}if(o=Uo(o),s=Uo(s),a=a.slice(),i=o-s){for(i>0?(s=o,n=u):(i=-i,n=a),n.reverse();i--;n.push(0));n.reverse()}for((i=a.length)-(e=u.length)<0&&(n=u,u=a,a=n,e=i),i=0;e;)i=(a[--e]=a[e]+u[e]+i)/Go|0,a[e]=Go===a[e]?0:a[e]%Go;return i&&(a=[i].concat(a),++s),P(t,a,s)},f.precision=f.sd=function(t,e){var n,r,i,o=this;if(null!=t&&t!==!!t)return Wo(t,1,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t,e);if(!(n=o.c))return null;if(r=(i=n.length-1)*Bo+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return t&&o.e+1>r&&(r=o.e+1),r},f.shiftedBy=function(t){return Wo(t,-9007199254740991,Yo),this.times("1e"+t)},f.squareRoot=f.sqrt=function(){var t,e,r,i,o,s=this,a=s.c,u=s.s,l=s.e,h=p+4,c=new S("0.5");if(1!==u||!a||!a[0])return new S(!u||u<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(u=Math.sqrt(+T(s)))||u==1/0?(((e=Zo(a)).length+l)%2==0&&(e+="0"),u=Math.sqrt(+e),l=Uo((l+1)/2)-(l<0||l%2),r=new S(e=u==1/0?"5e"+l:(e=u.toExponential()).slice(0,e.indexOf("e")+1)+l)):r=new S(u+""),r.c[0])for((u=(l=r.e)+h)<3&&(u=0);;)if(o=r,r=c.times(o.plus(n(s,o,h,1))),Zo(o.c).slice(0,u)===(e=Zo(r.c)).slice(0,u)){if(r.e0&&p>0){for(o=p%a||a,h=g.substr(0,o);o0&&(h+=l+g.slice(o)),f&&(h="-"+h)}r=c?h+(n.decimalSeparator||"")+((u=+n.fractionGroupSize)?c.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):c):h}return(n.prefix||"")+r+(n.suffix||"")},f.toFraction=function(t){var e,r,i,o,s,a,u,l,h,c,f,p,d=this,y=d.c;if(null!=t&&(!(u=new S(t)).isInteger()&&(u.c||1!==u.s)||u.lt(g)))throw Error(qo+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+T(u));if(!y)return new S(d);for(e=new S(g),h=r=new S(g),i=l=new S(g),p=Zo(y),s=e.e=p.length-d.e-1,e.c[0]=zo[(a=s%Bo)<0?Bo+a:a],t=!t||u.comparedTo(e)>0?s>0?e:h:u,a=x,x=1/0,u=new S(p),l.c[0]=0;c=n(u,e,0,1),1!=(o=r.plus(c.times(i))).comparedTo(t);)r=i,i=o,h=l.plus(c.times(o=h)),l=o,e=u.minus(c.times(o=e)),u=o;return o=n(t.minus(r),i,0,1),l=l.plus(o.times(h)),r=r.plus(o.times(i)),l.s=h.s=d.s,f=n(h,i,s*=2,v).minus(d).abs().comparedTo(n(l,r,s,v).minus(d).abs())<1?[h,i]:[l,r],x=a,f},f.toNumber=function(){return+T(this)},f.toPrecision=function(t,e){return null!=t&&Wo(t,1,Xo),M(this,t,e,2)},f.toString=function(t){var e,n=this,i=n.s,o=n.e;return null===o?i?(e="Infinity",i<0&&(e="-"+e)):e="NaN":(null==t?e=o<=d||o>=y?Ko(Zo(n.c),o):Qo(Zo(n.c),o,"0"):10===t&&N?e=Qo(Zo((n=C(new S(n),p+o+1,v)).c),n.e,"0"):(Wo(t,2,I.length,"Base"),e=r(Qo(Zo(n.c),o,"0"),10,t,i,!0)),i<0&&n.c[0]&&(e="-"+e)),e},f.valueOf=f.toJSON=function(){return T(this)},f._isBigNumber=!0,f[Symbol.toStringTag]="BigNumber",f[Symbol.for("nodejs.util.inspect.custom")]=f.valueOf,null!=e&&S.set(e),S}(),ts=function(t){function e(t){return i(this,e),r(this,e,[t])}return h(e,t),s(e)}(s((function t(e){i(this,t),u(this,"key",void 0),u(this,"left",null),u(this,"right",null),this.key=e}))),es=function(){return s((function t(){i(this,t),u(this,"size",0),u(this,"modificationCount",0),u(this,"splayCount",0)}),[{key:"splay",value:function(t){var e=this.root;if(null==e)return this.compare(t,t),-1;for(var n,r=null,i=null,o=null,s=null,a=e,u=this.compare;;)if((n=u(a.key,t))>0){var l=a.left;if(null==l)break;if((n=u(l.key,t))>0&&(a.left=l.right,l.right=a,null==(l=(a=l).left)))break;null==r?i=a:r.left=a,r=a,a=l}else{if(!(n<0))break;var h=a.right;if(null==h)break;if((n=u(h.key,t))<0&&(a.right=h.left,h.left=a,null==(h=(a=h).right)))break;null==o?s=a:o.right=a,o=a,a=h}return null!=o&&(o.right=a.left,a.left=s),null!=r&&(r.left=a.right,a.right=i),this.root!==a&&(this.root=a,this.splayCount++),n}},{key:"splayMin",value:function(t){for(var e=t,n=e.left;null!=n;){var r=n;e.left=r.right,r.right=e,n=(e=r).left}return e}},{key:"splayMax",value:function(t){for(var e=t,n=e.right;null!=n;){var r=n;e.right=r.left,r.left=e,n=(e=r).right}return e}},{key:"_delete",value:function(t){if(null==this.root)return null;if(0!=this.splay(t))return null;var e=this.root,n=e,r=e.left;if(this.size--,null==r)this.root=e.right;else{var i=e.right;(e=this.splayMax(r)).right=i,this.root=e}return this.modificationCount++,n}},{key:"addNewRoot",value:function(t,e){this.size++,this.modificationCount++;var n=this.root;null!=n?(e<0?(t.left=n,t.right=n.right,n.right=null):(t.right=n,t.left=n.left,n.left=null),this.root=t):this.root=t}},{key:"_first",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMin(t),this.root)}},{key:"_last",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMax(t),this.root)}},{key:"clear",value:function(){this.root=null,this.size=0,this.modificationCount++}},{key:"has",value:function(t){return this.validKey(t)&&0==this.splay(t)}},{key:"defaultCompare",value:function(){return function(t,e){return te?1:0}}},{key:"wrap",value:function(){var t=this;return{getRoot:function(){return t.root},setRoot:function(e){t.root=e},getSize:function(){return t.size},getModificationCount:function(){return t.modificationCount},getSplayCount:function(){return t.splayCount},setSplayCount:function(e){t.splayCount=e},splay:function(e){return t.splay(e)},has:function(e){return t.has(e)}}}}])}(),ns=function(t){function e(t,n){var o;return i(this,e),u(o=r(this,e),"root",null),u(o,"compare",void 0),u(o,"validKey",void 0),u(o,Symbol.toStringTag,"[object Set]"),o.compare=null!=t?t:o.defaultCompare(),o.validKey=null!=n?n:function(t){return null!=t&&null!=t},o}return h(e,t),s(e,[{key:"delete",value:function(t){return!!this.validKey(t)&&null!=this._delete(t)}},{key:"deleteAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.delete(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"forEach",value:function(t){for(var e,n=this[Symbol.iterator]();!(e=n.next()).done;)t(e.value,e.value,this)}},{key:"add",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this}},{key:"addAndReturn",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this.root.key}},{key:"addAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.add(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"isEmpty",value:function(){return null==this.root}},{key:"isNotEmpty",value:function(){return null!=this.root}},{key:"single",value:function(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}},{key:"first",value:function(){if(0==this.size)throw"Bad state: No element";return this._first().key}},{key:"last",value:function(){if(0==this.size)throw"Bad state: No element";return this._last().key}},{key:"lastBefore",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)<0)return this.root.key;var e=this.root.left;if(null==e)return null;for(var n=e.right;null!=n;)n=(e=n).right;return e.key}},{key:"firstAfter",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)>0)return this.root.key;var e=this.root.right;if(null==e)return null;for(var n=e.left;null!=n;)n=(e=n).left;return e.key}},{key:"retainAll",value:function(t){var n,r=new e(this.compare,this.validKey),i=this.modificationCount,o=a(t);try{for(o.s();!(n=o.n()).done;){var s=n.value;if(i!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(s)&&0==this.splay(s)&&r.add(this.root.key)}}catch(t){o.e(t)}finally{o.f()}r.size!=this.size&&(this.root=r.root,this.size=r.size,this.modificationCount++)}},{key:"lookup",value:function(t){return this.validKey(t)?0!=this.splay(t)?null:this.root.key:null}},{key:"intersection",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)&&r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"difference",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)||r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"union",value:function(t){var e=this.clone();return e.addAll(t),e}},{key:"clone",value:function(){var t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}},{key:"copyNode",value:function(t){if(null==t)return null;var e=new ts(t.key);return function t(e,n){var r,i;do{if(r=e.left,i=e.right,null!=r){var o=new ts(r.key);n.left=o,t(r,o)}if(null!=i){var s=new ts(i.key);n.right=s,e=i,n=s}}while(null!=i)}(t,e),e}},{key:"toSet",value:function(){return this.clone()}},{key:"entries",value:function(){return new os(this.wrap())}},{key:"keys",value:function(){return this[Symbol.iterator]()}},{key:"values",value:function(){return this[Symbol.iterator]()}},{key:Symbol.iterator,value:function(){return new is(this.wrap())}}])}(es),rs=function(){return s((function t(e){i(this,t),u(this,"tree",void 0),u(this,"path",new Array),u(this,"modificationCount",null),u(this,"splayCount",void 0),this.tree=e,this.splayCount=e.getSplayCount()}),[{key:Symbol.iterator,value:function(){return this}},{key:"next",value:function(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}},{key:"current",value:function(){if(!this.path.length)return null;var t=this.path[this.path.length-1];return this.getValue(t)}},{key:"rebuildPath",value:function(t){this.path.splice(0,this.path.length),this.tree.splay(t),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}},{key:"findLeftMostDescendent",value:function(t){for(;null!=t;)this.path.push(t),t=t.left}},{key:"moveNext",value:function(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();for(var t=this.tree.getRoot();null!=t;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);var e=this.path[this.path.length-1],n=e.right;if(null!=n){for(;null!=n;)this.path.push(n),n=n.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}}])}(),is=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return t.key}}])}(rs),os=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return[t.key,t.key]}}])}(rs),ss=function(t){return function(){return t}},as=function(t){var e=t?function(e,n){return n.minus(e).abs().isLessThanOrEqualTo(t)}:ss(!1);return function(t,n){return e(t,n)?0:t.comparedTo(n)}};function us(t){var e=t?function(e,n,r,i,o){return e.exponentiatedBy(2).isLessThanOrEqualTo(i.minus(n).exponentiatedBy(2).plus(o.minus(r).exponentiatedBy(2)).times(t))}:ss(!1);return function(t,n,r){var i=t.x,o=t.y,s=r.x,a=r.y,u=o.minus(a).times(n.x.minus(s)).minus(i.minus(s).times(n.y.minus(a)));return e(u,i,o,s,a)?0:u.comparedTo(0)}}var ls=function(t){return t},hs=function(t){if(t){var e=new ns(as(t)),n=new ns(as(t)),r=function(t,e){return e.addAndReturn(t)},i=function(t){return{x:r(t.x,e),y:r(t.y,n)}};return i({x:new $o(0),y:new $o(0)}),i}return ls},cs=function(t){return{set:function(t){fs=cs(t)},reset:function(){return cs(t)},compare:as(t),snap:hs(t),orient:us(t)}},fs=cs(),gs=function(t,e){return t.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(t.ur.x)&&t.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(t.ur.y)},ps=function(t,e){if(e.ur.x.isLessThan(t.ll.x)||t.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(t.ll.y)||t.ur.y.isLessThan(e.ll.y))return null;var n=t.ll.x.isLessThan(e.ll.x)?e.ll.x:t.ll.x,r=t.ur.x.isLessThan(e.ur.x)?t.ur.x:e.ur.x;return{ll:{x:n,y:t.ll.y.isLessThan(e.ll.y)?e.ll.y:t.ll.y},ur:{x:r,y:t.ur.y.isLessThan(e.ur.y)?t.ur.y:e.ur.y}}},vs=function(t,e){return t.x.times(e.y).minus(t.y.times(e.x))},ds=function(t,e){return t.x.times(e.x).plus(t.y.times(e.y))},ys=function(t){return ds(t,t).sqrt()},ms=function(t,e,n){var r={x:e.x.minus(t.x),y:e.y.minus(t.y)},i={x:n.x.minus(t.x),y:n.y.minus(t.y)};return ds(i,r).div(ys(i)).div(ys(r))},_s=function(t,e,n){return e.y.isZero()?null:{x:t.x.plus(e.x.div(e.y).times(n.minus(t.y))),y:n}},xs=function(t,e,n){return e.x.isZero()?null:{x:n,y:t.y.plus(e.y.div(e.x).times(n.minus(t.x)))}},Es=function(){function t(e,n){i(this,t),u(this,"point",void 0),u(this,"isLeft",void 0),u(this,"segment",void 0),u(this,"otherSE",void 0),u(this,"consumedBy",void 0),void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}return s(t,[{key:"link",value:function(t){if(t.point===this.point)throw new Error("Tried to link already linked events");for(var e=t.point.events,n=0,r=e.length;n0&&(t=r)}for(var i=t.segment.prevInResult(),o=i?i.prevInResult():null;;){if(!i)return null;if(!o)return i.ringOut;var s,a;if(o.ringOut!==i.ringOut)return(null===(s=o.ringOut)||void 0===s?void 0:s.enclosingRing())!==i.ringOut?i.ringOut:null===(a=i.ringOut)||void 0===a?void 0:a.enclosingRing();i=o.prevInResult(),o=i?i.prevInResult():null}}}],[{key:"factory",value:function(e){for(var n=[],r=0,i=e.length;r1&&void 0!==arguments[1]?arguments[1]:Ls.compare;i(this,t),u(this,"queue",void 0),u(this,"tree",void 0),u(this,"segments",void 0),this.queue=e,this.tree=new ns(n),this.segments=[]}),[{key:"process",value:function(t){var e=t.segment,n=[];if(t.consumedBy)return t.isLeft?this.queue.delete(t.otherSE):this.tree.delete(e),n;t.isLeft&&this.tree.add(e);var r=e,i=e;do{r=this.tree.lastBefore(r)}while(null!=r&&null!=r.consumedBy);do{i=this.tree.firstAfter(i)}while(null!=i&&null!=i.consumedBy);if(t.isLeft){var o=null;if(r){var s=r.getIntersection(e);if(null!==s&&(e.isAnEndpoint(s)||(o=s),!r.isAnEndpoint(s)))for(var a=this._splitSafely(r,s),u=0,l=a.length;u0?(this.tree.delete(e),n.push(t)):(this.segments.push(e),e.prev=r)}else{if(r&&i){var _=r.getIntersection(i);if(null!==_){if(!r.isAnEndpoint(_))for(var x=this._splitSafely(r,_),E=0,k=x.length;E0&&a.swapEvents(),Es.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}},{key:"swapEvents",value:function(){var t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(var e=0,n=this.windings.length;e0){var o=n;n=r,r=o}if(n.prev===r){var s=n;n=r,r=s}for(var a=0,u=r.rings.length;a0)return-1;var c=e.comparePoint(t.rightSE.point);return 0!==c?c:-1}if(n.isGreaterThan(r)){if(s.isLessThan(a)&&s.isLessThan(l))return-1;if(s.isGreaterThan(a)&&s.isGreaterThan(l))return 1;var f=e.comparePoint(t.leftSE.point);if(0!==f)return f;var g=t.comparePoint(e.rightSE.point);return g<0?1:g>0?-1:1}if(s.isLessThan(a))return-1;if(s.isGreaterThan(a))return 1;if(i.isLessThan(o)){var p=e.comparePoint(t.rightSE.point);if(0!==p)return p}if(i.isGreaterThan(o)){var v=t.comparePoint(e.rightSE.point);if(v<0)return 1;if(v>0)return-1}if(!i.eq(o)){var d=u.minus(s),y=i.minus(n),m=l.minus(a),_=o.minus(r);if(d.isGreaterThan(y)&&m.isLessThan(_))return 1;if(d.isLessThan(y)&&m.isGreaterThan(_))return-1}return i.isGreaterThan(o)?1:i.isLessThan(o)||u.isLessThan(l)?-1:u.isGreaterThan(l)?1:t.ide.id?1:0}},{key:"fromRing",value:function(e,n,r){var i,o,s,a=Es.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else{if(!(a>0))throw new Error("Tried to create degenerate segment at [".concat(e.x,", ").concat(e.y,"]"));i=n,o=e,s=-1}return new t(new Es(i,!0),new Es(o,!1),[r],[s])}}])}(),Ps=function(){return s((function t(e,n,r){if(i(this,t),u(this,"poly",void 0),u(this,"isExterior",void 0),u(this,"segments",void 0),u(this,"bbox",void 0),!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");var o=fs.snap({x:new $o(e[0][0]),y:new $o(e[0][1])});this.bbox={ll:{x:o.x,y:o.y},ur:{x:o.x,y:o.y}};for(var s=o,a=1,l=e.length;a1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r2&&void 0!==arguments[2]?arguments[2]:2,r=K(t),i=K(e),o=r[0]-i[0],s=r[1]-i[1];return 1===n?Math.abs(o)+Math.abs(s):Math.pow(Math.pow(o,n)+Math.pow(s,n),1/n)}function Gs(t,e){var n,r,i=(e=e||{}).threshold||1e4,o=e.p||2,s=null!=(n=e.binary)&&n,a=e.alpha||-1,u=null!=(r=e.standardization)&&r,l=[];vt(t,(function(t){l.push(gi(t))}));for(var h=[],c=0;c3&&void 0!==arguments[3]?arguments[3]:{},i=e<0,o=j(Math.abs(e),r.units,"meters");i&&(o=-Math.abs(o));var s=K(t),a=function(t,e,n,r){r=void 0===r?x:Number(r);var i=e/r,o=t[0]*Math.PI/180,s=z(t[1]),a=z(n),u=i*Math.cos(a),l=s+u;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);var h=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),c=Math.abs(h)>1e-11?u/h:Math.cos(s),f=i*Math.sin(a)/c;return[(180*(o+f)/Math.PI+540)%360-180,180*l/Math.PI]}(s,o,n);return a[0]+=a[0]-s[0]>180?-360:s[0]-a[0]>180?360:0,I(a,r.properties)}function Ys(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e);i[0]+=i[0]-r[0]>180?-360:r[0]-i[0]>180?360:0;var o=function(t,e,n){var r=n=void 0===n?x:Number(n),i=t[1]*Math.PI/180,o=e[1]*Math.PI/180,s=o-i,a=Math.abs(e[0]-t[0])*Math.PI/180;a>Math.PI&&(a-=2*Math.PI);var u=Math.log(Math.tan(o/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),l=Math.abs(u)>1e-11?s/u:Math.cos(i);return Math.sqrt(s*s+l*l*a*a)*r}(r,i);return j(o,"meters",n.units)}function zs(t,e,n){if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.pivot,i=n.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("angle is required");if(0===e)return t;var o=null!=r?r:gi(t);return!1!==i&&void 0!==i||(t=Ai(t)),ct(t,(function(t){var n=lt(o,t)+e,r=Ys(o,t),i=Q(Bs(o,r,n));t[0]=i[0],t[1]=i[1]})),t}function js(t,e,n,r){var i=(r=r||{}).steps||64,o=r.units||"kilometers",s=r.angle||0,a=r.pivot||t,u=r.properties||{};if(!t)throw new Error("center is required");if(!e)throw new Error("xSemiAxis is required");if(!n)throw new Error("ySemiAxis is required");if(!Z(r))throw new Error("options must be an object");if(!U(i))throw new Error("steps must be a number");if(!U(s))throw new Error("angle must be a number");var l=K(t);if("degrees"!==o){var h=Bs(t,e,90,{units:o}),c=Bs(t,n,0,{units:o});e=K(h)[0]-l[0],n=K(c)[1]-l[1]}for(var f=[],g=0;g=-270&&(v=-v),p<-180&&p>=-360&&(d=-d),"degrees"===o){var y=z(s),m=v*Math.cos(y)+d*Math.sin(y),_=d*Math.cos(y)-v*Math.sin(y);v=m,d=_}f.push([v+l[0],d+l[1]])}return f.push(f[0]),"degrees"===o?S([f],u):zs(S([f],u),s,{pivot:a})}function Xs(t){var e=t*Math.PI/180;return Math.tan(e)}function Us(t){return Vt(Rt(t))}function Zs(t){var e=[];return"FeatureCollection"===t.type?vt(t,(function(t){ct(t,(function(n){e.push(I(n,t.properties))}))})):"Feature"===t.type?ct(t,(function(n){e.push(I(n,t.properties))})):ct(t,(function(t){e.push(I(t))})),C(e)}var Hs=Math.PI/180,Ws=180/Math.PI,Js=function(t,e){this.lon=t,this.lat=e,this.x=Hs*t,this.y=Hs*e};Js.prototype.view=function(){return String(this.lon).slice(0,4)+","+String(this.lat).slice(0,4)},Js.prototype.antipode=function(){var t=-1*this.lat,e=this.lon<0?180+this.lon:-1*(180-this.lon);return new Js(e,t)};var Ks=function(){this.coords=[],this.length=0};Ks.prototype.move_to=function(t){this.length++,this.coords.push(t)};var Qs=function(t){this.properties=t||{},this.geometries=[]};Qs.prototype.json=function(){if(this.geometries.length<=0)return{geometry:{type:"LineString",coordinates:null},type:"Feature",properties:this.properties};if(1===this.geometries.length)return{geometry:{type:"LineString",coordinates:this.geometries[0].coords},type:"Feature",properties:this.properties};for(var t=[],e=0;e1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must specify at least 2 geometries");var r=Rs.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)}function ea(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.stringify(n.properties||{}),i=v(t,4),o=i[0],s=i[1],a=i[2],u=i[3],l=(s+u)/2,h=(o+a)/2,c=2*e/ut([o,l],[a,l],n)*(a-o),f=2*e/ut([h,s],[h,u],n)*(u-s),g=c/2,p=2*g,d=Math.sqrt(3)/2*f,y=a-o,m=u-s,_=3/4*p,x=d,E=(y-p)/(p-g/2),k=Math.floor(E),b=(k*_-g/2-y)/2-g/2+_/2,w=Math.floor((m-d)/d),I=(m-w*d)/2,N=w*d-m>d/2;N&&(I-=d/4);for(var S=[],M=[],L=0;L<6;L++){var P=2*Math.PI/6*L;S.push(Math.cos(P)),M.push(Math.sin(P))}for(var T=[],O=0;O<=k;O++)for(var R=0;R<=w;R++){var A=O%2==1;if((0!==R||!A)&&(0!==R||!N)){var D=O*_+o-b,F=R*x+s+I;if(A&&(F-=d/2),!0===n.triangles)ra([D,F],c/2,f/2,JSON.parse(r),S,M).forEach((function(t){n.mask?ta(C([n.mask,t]))&&T.push(t):T.push(t)}));else{var q=na([D,F],c/2,f/2,JSON.parse(r),S,M);n.mask?ta(C([n.mask,q]))&&T.push(q):T.push(q)}}}return C(T)}function na(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=t[0]+e*i[a],l=t[1]+n*o[a];s.push([u,l])}return s.push(s[0].slice()),S([s],r)}function ra(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=[];u.push(t),u.push([t[0]+e*i[a],t[1]+n*o[a]]),u.push([t[0]+e*i[(a+1)%6],t[1]+n*o[(a+1)%6]]),u.push(t),s.push(S([u],r))}return s}function ia(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.mask&&!n.units&&(n.units="kilometers");for(var r=[],i=t[0],o=t[1],s=t[2],a=t[3],u=e/ut([i,o],[s,o],n)*(s-i),l=e/ut([i,o],[i,a],n)*(a-o),h=s-i,c=a-o,f=Math.floor(h/u),g=(c-Math.floor(c/l)*l)/2,p=i+(h-f*u)/2;p<=s;){for(var v=o+g;v<=a;){var d=I([p,v],n.properties);n.mask?Cn(d,n.mask)&&r.push(d):r.push(d),v+=l}p+=u}return C(r)}function oa(t,e,n){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=[],o=t[0],s=t[1],a=t[2],u=t[3],l=a-o,h=j(e,r.units,"degrees"),c=u-s,f=j(n,r.units,"degrees"),g=Math.floor(Math.abs(l)/h),p=Math.floor(Math.abs(c)/f),v=(c-p*f)/2,d=o+(l-g*h)/2,y=0;y2&&void 0!==arguments[2]?arguments[2]:{})}function aa(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=[],i=e/ut([t[0],t[1]],[t[2],t[1]],n)*(t[2]-t[0]),o=e/ut([t[0],t[1]],[t[0],t[3]],n)*(t[3]-t[1]),s=0,a=t[0];a<=t[2];){for(var u=0,l=t[1];l<=t[3];){var h=null,c=null;s%2==0&&u%2==0?(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)):s%2==0&&u%2==1?(h=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties)):u%2==0&&s%2==1?(h=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties),c=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties)):u%2==1&&s%2==1&&(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)),n.mask?(ta(C([n.mask,h]))&&r.push(h),ta(C([n.mask,c]))&&r.push(c)):(r.push(h),r.push(c)),l+=o,u++}s++,a+=i}return C(r)} +/*! + * MarchingSquaresJS + * version 1.3.3 + * https://github.com/RaumZeit/MarchingSquares.js + * + * @license GNU Affero General Public License. + * Copyright (c) 2015-2019 Ronny Lorenz + */ +function ua(t,e,n){return tr&&(i=n,n=r,r=i),tr?(t-r)/(t-e):(t-n)/(t-e)}function ha(t,e,n,r){return t1){for(;0!==o;)o>>=1,a++;r===1<1){for(;0!==s;)s>>=1,u++;i===1<0&&(this.childB=new da(t,e+o,n,r-o,s),this.lowerBound=Math.min(this.lowerBound,this.childB.lowerBound),this.upperBound=Math.max(this.upperBound,this.childB.upperBound),i-s>0&&(this.childC=new da(t,e+o,n+s,r-o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childC.lowerBound),this.upperBound=Math.max(this.upperBound,this.childC.upperBound))),i-s>0&&(this.childD=new da(t,e,n+s,o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childD.lowerBound),this.upperBound=Math.max(this.upperBound,this.childD.upperBound))}}function ya(t){var e,n;if(!t)throw new Error("data is required");if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Error("data must be scalar field, i.e. array of arrays");if(t.length<2)throw new Error("data must contain at least two rows");if((n=t[0].length)<2)throw new Error("data must contain at least two columns");for(e=1;e=e||t[s][r-1]>=e){n=!1;break}if(n&&(t[i-1][0]>=e||t[i-1][r-1]>=e)&&(n=!1),n)for(o=0;o=e||t[i-1][o]>e){n=!1;break}return n}(t,n.threshold)&&(n.linearRing?_.push([[0,0],[0,x],[E,x],[E,0],[0,0]]):_.push([[0,0],[0,x],[E,x],[E,0]])),e.forEach((function(t,N){t.forEach((function(t,S){for(r=null,i=0;i<4;i++)if(r=k[i],"object"===m(t.edges[r])){for(a=[],o=t.edges[r],u=r,l=N,h=S,c=!1,f=[N+o.path[0][0],S+o.path[0][1]],a.push(f);!c&&"object"===m((s=e[l][h]).edges[u]);)if(o=s.edges[u],delete s.edges[u],(g=o.path[1])[0]+=l,g[1]+=h,a.push(g),u=o.move.enter,l+=o.move.x,h+=o.move.y,void 0===e[l]||void 0===e[l][h]){if(!n.linearRing)break;if(p=0,v=0,l===E?(l--,p=0):l<0?(l++,p=2):h===x?(h--,p=3):h<0&&(h++,p=1),l===N&&h===S&&p===I[r]){c=!0,u=r;break}for(;;){if(d=!1,v>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[l]&&void 0!==e[l][h]&&(s=e[l][h],y=k[p],"object"===m(s.edges[y]))){o=s.edges[y],a.push(pa(l,h,p,o.path)),u=y,d=!0;break}if(d)break;if(a.push(va(l,h,p)),h+=w[p],void 0!==e[l+=b[p]]&&void 0!==e[l][h]||(0===p&&h<0||1===p&&l<0||2===p&&h===x||3===p&&l===E)&&(l-=b[p],h-=w[p],p=(p+1)%4,v++),l===N&&h===S&&p===I[r]){c=!0,u=r;break}}}!n.linearRing||a[a.length-1][0]===f[0]&&a[a.length-1][1]===f[1]||a.push(f),_.push(a)}}))})),_}(h,c,r)}a?g.push(f):g=f,"function"==typeof r.successCallback&&r.successCallback(g,t)})),g}function _a(t,e,n,r){var i,o,s,a,u,l,h=0,c=t[n+1][e],f=t[n+1][e+1],g=t[n][e+1],p=t[n][e],v=r.threshold;if(!(isNaN(p)||isNaN(g)||isNaN(f)||isNaN(c))){switch(h|=c>=v?8:0,h|=f>=v?4:0,h|=g>=v?2:0,l={cval:h=+(h|=p>=v?1:0),polygons:[],edges:{},x0:p,x1:g,x2:f,x3:c},h){case 0:r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,0]]);break;case 15:break;case 14:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.left={path:[[0,i],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[a,0]]);break;case 13:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[a,0],[1,o],[1,0]]);break;case 11:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[1,o],[s,1],[1,1]]);break;case 7:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[s,1],[0,i],[0,1]]);break;case 1:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[a,0],[0,i],[0,1],[1,1],[1,0]]);break;case 2:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,o],[a,0]]);break;case 4:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[1,o],[1,0]]);break;case 8:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[s,1],[1,1],[1,0]]);break;case 12:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[1,o],[1,0]]);break;case 9:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[a,0],[s,1],[1,1],[1,0]]);break;case 3:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[0,i],[0,1],[1,1],[1,o]]);break;case 6:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[a,0]]);break;case 10:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),u=(p+g+f+c)/4,r.polygons_full&&(uf&&(v>h&&ph&&vu&&(u=d)}var y=[];if(a&&u0&&Math.abs(x-n[_-1][0])>f){var E=parseFloat(n[_-1][0]),k=parseFloat(n[_-1][1]),b=parseFloat(n[_][0]),w=parseFloat(n[_][1]);if(E>-180&&E-180&&n[_-1][0]h&&E<180&&-180===b&&_+1h&&n[_-1][0]<180){m.push([180,n[_][1]]),_++,m.push([n[_][0],n[_][1]]);continue}if(Eh){var I=E;E=b,b=I;var N=k;k=w,w=N}if(E>h&&b=180&&Eh?180:-180,M]),(m=[]).push([n[_-1][0]>h?-180:180,M]),y.push(m)}else m=[],y.push(m);m.push([x,n[_][1]])}else m.push([n[_][0],n[_][1]])}}else{var L=[];y.push(L);for(var P=0;Pe||this.upperBound=e)&&r.push({x:this.x,y:this.y})),r},da.prototype.cellsBelowThreshold=function(t,e){var n=[];return e=void 0===e||e,this.lowerBound>t||(this.childA||this.childB||this.childC||this.childD?(this.childA&&(n=n.concat(this.childA.cellsBelowThreshold(t,e))),this.childB&&(n=n.concat(this.childB.cellsBelowThreshold(t,e))),this.childD&&(n=n.concat(this.childD.cellsBelowThreshold(t,e))),this.childC&&(n=n.concat(this.childC.cellsBelowThreshold(t,e)))):(e||this.upperBound>=t)&&n.push({x:this.x,y:this.y})),n};var xa={square:function(t,e,n,r,i,o){o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,0]])},triangle_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,a],[s,0],[0,0]])},triangle_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[1,a],[1,0]])},triangle_tr:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[1,s],[a,1],[1,1]])},triangle_tl:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[s,1]])},tetragon_t:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[1,1],[1,s]])},tetragon_r:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[a,1],[1,1],[1,0]])},tetragon_b:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,0]])},tetragon_l:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[a,0]])},tetragon_bl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[a,0]])},tetragon_br:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate_b(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[1,l]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[1,l],[1,u],[a,0]])},tetragon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rb={path:[[1,l],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}}),o.polygons&&t.polygons.push([[1,l],[s,1],[a,1],[1,u]])},tetragon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[0,l]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[a,1],[0,l],[0,u],[s,1]])},tetragon_lr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[1,u],[1,l]])},tetragon_tb:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[l,0],[s,1],[a,1],[u,0]])},pentagon_tr:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[1,a],[1,0]])},pentagon_tl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,0]])},pentagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,a],[s,0]])},pentagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[a,0],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[1,1],[1,0],[a,0]])},pentagon_tr_rl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[1,u],[1,l]])},pentagon_rb_bt:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,n,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[u,0],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[l,1],[1,1],[1,s],[a,0],[u,0]])},pentagon_bl_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[1,l],[1,0]])},pentagon_lt_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[l,0]])},pentagon_bl_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[l,0],[0,s]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[u,0],[l,0]])},pentagon_lt_rl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[u,1],[1,1],[1,l]])},pentagon_tr_bt:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,1],[a,1],[1,u],[1,0],[l,0]])},pentagon_rb_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_b(n,r,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,u],[l,0]])},hexagon_lt_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[1,l],[1,0]])},hexagon_bl_lt:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[1,1],[1,0]])},hexagon_bl_rb:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.rt={path:[[1,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[1,1],[1,l],[a,0]])},hexagon_tr_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[a,1],[1,u],[1,l],[s,0]])},hexagon_lt_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,u],[l,0]])},hexagon_bl_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,1],[u,1],[1,l],[1,0]])},heptagon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[1,1],[1,c],[a,0]])},heptagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate_a(i,r,o.minV,o.maxV),l=o.interpolate_b(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,a],[u,1],[l,1],[1,h],[1,c],[s,0]])},heptagon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[l,1],[1,h],[1,c],[a,0]])},heptagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(i,r,o.minV,o.maxV),h=o.interpolate_b(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[h,1],[1,c]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[h,1],[1,c],[1,0]])},octagon:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate_a(i,r,o.minV,o.maxV),c=o.interpolate_b(i,r,o.minV,o.maxV),f=o.interpolate_b(n,r,o.minV,o.maxV),g=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[c,1],[1,f]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,g],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[c,1],[1,f],[1,g],[a,0]])}};function Ea(t,e,n,r){var i,o,s,a=!1,u=null,l=null,h=null,c=null,f=!1,g=[],p=[],v=[];if(!t)throw new Error("data is required");if(null==e)throw new Error("lowerBound is required");if(null==n)throw new Error("bandWidth is required");if(s=function(t){var e,n,r,i,o;for(i=new fa,t=t||{},o=Object.keys(i),e=0;en||t[a][i-1]n){r=!1;break}if(r&&(t[o-1][0]n||t[o-1][i-1]n)&&(r=!1),r)for(s=0;sn||t[o-1][s]n){r=!1;break}return r}(t,n.minV,n.maxV)&&(n.linearRing?x.push([[0,0],[0,E],[k,E],[k,0],[0,0]]):x.push([[0,0],[0,E],[k,E],[k,0]])),e.forEach((function(t,M){t.forEach((function(t,L){for(r=null,o=0;o<8;o++)if(r=N[o],"object"===m(t.edges[r])){for(i=[],s=t.edges[r],l=r,h=M,c=L,f=!1,g=[M+s.path[0][0],L+s.path[0][1]],i.push(g);!f&&"object"===m((p=e[h][c]).edges[l]);)if(s=p.edges[l],delete p.edges[l],(y=s.path[1])[0]+=h,y[1]+=c,i.push(y),l=s.move.enter,h+=s.move.x,c+=s.move.y,void 0===e[h]||void 0===e[h][c]){if(v=0,d=0,h===k)h--,v=0;else if(h<0)h++,v=2;else if(c===E)c--,v=3;else{if(!(c<0))throw new Error("Left the grid somewhere in the interior!");c++,v=1}if(h===M&&c===L&&v===S[r]){f=!0,l=r;break}for(;;){if(_=!1,d>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[h]&&void 0!==e[h][c])for(p=e[h][c],a=0;ao?2:sf?128:64,s|=uf?32:16,s|=lf?8:4,o=0,i={cval:s=+(s|=hf?2:1),polygons:[],edges:{},x0:h,x1:l,x2:u,x3:a,x:e,y:n},s){case 85:xa.square(i,h,l,u,a,r);case 0:case 170:break;case 169:xa.triangle_bl(i,h,l,u,a,r);break;case 166:xa.triangle_br(i,h,l,u,a,r);break;case 154:xa.triangle_tr(i,h,l,u,a,r);break;case 106:xa.triangle_tl(i,h,l,u,a,r);break;case 1:xa.triangle_bl(i,h,l,u,a,r);break;case 4:xa.triangle_br(i,h,l,u,a,r);break;case 16:xa.triangle_tr(i,h,l,u,a,r);break;case 64:xa.triangle_tl(i,h,l,u,a,r);break;case 168:xa.tetragon_bl(i,h,l,u,a,r);break;case 162:xa.tetragon_br(i,h,l,u,a,r);break;case 138:xa.tetragon_tr(i,h,l,u,a,r);break;case 42:xa.tetragon_tl(i,h,l,u,a,r);break;case 2:xa.tetragon_bl(i,h,l,u,a,r);break;case 8:xa.tetragon_br(i,h,l,u,a,r);break;case 32:xa.tetragon_tr(i,h,l,u,a,r);break;case 128:xa.tetragon_tl(i,h,l,u,a,r);break;case 5:xa.tetragon_b(i,h,l,u,a,r);break;case 20:xa.tetragon_r(i,h,l,u,a,r);break;case 80:xa.tetragon_t(i,h,l,u,a,r);break;case 65:xa.tetragon_l(i,h,l,u,a,r);break;case 165:xa.tetragon_b(i,h,l,u,a,r);break;case 150:xa.tetragon_r(i,h,l,u,a,r);break;case 90:xa.tetragon_t(i,h,l,u,a,r);break;case 105:xa.tetragon_l(i,h,l,u,a,r);break;case 160:xa.tetragon_lr(i,h,l,u,a,r);break;case 130:xa.tetragon_tb(i,h,l,u,a,r);break;case 10:xa.tetragon_lr(i,h,l,u,a,r);break;case 40:xa.tetragon_tb(i,h,l,u,a,r);break;case 101:xa.pentagon_tr(i,h,l,u,a,r);break;case 149:xa.pentagon_tl(i,h,l,u,a,r);break;case 86:xa.pentagon_bl(i,h,l,u,a,r);break;case 89:xa.pentagon_br(i,h,l,u,a,r);break;case 69:xa.pentagon_tr(i,h,l,u,a,r);break;case 21:xa.pentagon_tl(i,h,l,u,a,r);break;case 84:xa.pentagon_bl(i,h,l,u,a,r);break;case 81:xa.pentagon_br(i,h,l,u,a,r);break;case 96:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 24:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 6:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 129:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 74:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 146:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 164:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 41:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 66:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 144:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 36:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 9:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 104:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 26:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 134:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 161:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 37:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 148:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 82:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 73:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 133:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 22:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 88:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 97:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 145:case 25:xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 70:case 100:xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 17:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 68:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 153:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 102:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 152:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 137:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 98:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 38:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 18:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 33:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 72:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 132:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 136:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r));break;case 34:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r))}return i}}var wa=Object.defineProperty,Ia=Object.getOwnPropertySymbols,Na=Object.prototype.hasOwnProperty,Sa=Object.prototype.propertyIsEnumerable,Ma=function(t,e,n){return e in t?wa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},La=function(t,e){for(var n in e||(e={}))Na.call(e,n)&&Ma(t,n,e[n]);if(Ia){var r,i=a(Ia(e));try{for(i.s();!(r=i.n()).done;){n=r.value;Sa.call(e,n)&&Ma(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t};function Pa(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.zProperty||"elevation",r=e.flip,i=e.flags;nt(t,"Point","input must contain Points");for(var o=function(t,e){var n={};vt(t,(function(t){var e=Q(t)[1];n[e]||(n[e]=[]),n[e].push(t)}));var r=Object.keys(n).map((function(t){return n[t].sort((function(t,e){return Q(t)[0]-Q(e)[0]}))})),i=r.sort((function(t,n){return e?Q(t[0])[1]-Q(n[0])[1]:Q(n[0])[1]-Q(t[0])[1]}));return i}(t,r),s=[],a=0;a=0&&l<=1&&(f.onLine1=!0),h>=0&&h<=1&&(f.onLine2=!0),!(!f.onLine1||!f.onLine2)&&[f.x,f.y])}function za(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return bt(t,(function(t,n){var r=n.geometry.coordinates;return t+ut(r[0],r[1],e)}),0)}function ja(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=i.steps||64,s=Xa(n),a=Xa(r),u=Array.isArray(t)||"Feature"!==t.type?{}:t.properties;if(s===a)return L(Ri(t,e,i).geometry.coordinates[0],u);for(var l=s,h=s=h&&c===i.length-1);c++){if(h>e&&0===o.length){if(!(s=e-h))return o.push(i[c]),L(o);a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates)}if(h>=n)return(s=n-h)?(a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates),L(o)):(o.push(i[c]),L(o));if(h>=e&&o.push(i[c]),c===i.length-1)return L(o);h+=ut(i[c],i[c+1],r)}if(h0){var a=r[e-1],u=Wa(n,a);!1!==u&&(a[1]=u,n[0]=u),s.push(a[0]),e===o.length-2&&(s.push(n[0]),s.push(n[1]))}2===o.length&&(s.push(n[0]),s.push(n[1]))}var l,h,c,f,g,p,v,d})),L(s,t.properties)}function Ka(t){var e=t[0],n=t[1],r=t[2],i=t[3];if(ut(t.slice(0,2),[r,n])>=ut(t.slice(0,2),[e,i])){var o=(n+i)/2;return[e,o-(r-e)/2,r,o+(r-e)/2]}var s=(e+r)/2;return[s-(i-n)/2,n,s+(i-n)/2,i]}function Qa(t,e){if(!Z(e=null!=e?e:{}))throw new Error("options is invalid");var n=e.precision,r=e.coordinates,i=e.mutate;if(n=null==n||isNaN(n)?6:n,r=null==r||isNaN(r)?3:r,!t)throw new Error(" is required");if("number"!=typeof n)throw new Error(" must be a number");if("number"!=typeof r)throw new Error(" must be a number");!1!==i&&void 0!==i||(t=JSON.parse(JSON.stringify(t)));var o=Math.pow(10,n);return ct(t,(function(t){!function(t,e,n){t.length>n&&t.splice(n,t.length);for(var r=0;r1&&n.push(L(l)),C(n)}function eu(t,e){if(!e.features.length)throw new Error("lines must contain features");if(1===e.features.length)return e.features[0];var n,r=1/0;return vt(e,(function(e){var i=fn(e,t).properties.dist;iu?(a.unshift(t),u=e):a.push(t)}else a.push(t)})),S(a,e);default:throw new Error("geometry type "+s+" is not supported")}}function iu(t){var e=t[0],n=e[0],r=e[1],i=t[t.length-1],o=i[0],s=i[1];return n===o&&r===s||t.push(e),t}function ou(t){return R(t)}function su(t){var e=[[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]];return t&&(e="Feature"===t.type?t.geometry.coordinates:t.coordinates),S(e)}function au(t){var e,n=0,r=a(t);try{for(r.s();!(e=r.n()).done;){n+=e.value}}catch(t){r.e(t)}finally{r.f()}return n/t.length}var uu=Object.defineProperty,lu=Object.defineProperties,hu=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,fu=Object.prototype.hasOwnProperty,gu=Object.prototype.propertyIsEnumerable,pu=function(t,e,n){return e in t?uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},vu=function(t,e){for(var n in e||(e={}))fu.call(e,n)&&pu(t,n,e[n]);if(cu){var r,i=a(cu(e));try{for(i.s();!(r=i.n()).done;){n=r.value;gu.call(e,n)&&pu(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},du=function(t,e){return lu(t,hu(e))};function yu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("targetPoint is required");if(!e)throw new Error("points is required");var r=1/0,i=0;vt(e,(function(e,o){var s=ut(t,e,n);s2&&void 0!==arguments[2]?arguments[2]:{},o=null!=(n=i.method)?n:"geodesic",s=null!=(r=i.units)?r:"kilometers";if(!t)throw new Error("pt is required");if(Array.isArray(t)?t=I(t):"Point"===t.type?t=b(t):et(t,"Point","point"),!e)throw new Error("line is required");Array.isArray(e)?e=L(e):"LineString"===e.type?e=b(e):et(e,"LineString","line");var a=1/0,u=t.geometry.coordinates;return kt(e,(function(t){if(t){var e=t.geometry.coordinates[0],n=t.geometry.coordinates[1],r=function(t,e,n,r){if("geodesic"===r.method){return fn(L([e,n]).geometry,t,{units:"degrees"}).properties.dist}var i=[n[0]-e[0],n[1]-e[1]],o=[t[0]-e[0],t[1]-e[1]],s=_u(o,i);if(s<=0)return Ys(t,e,{units:"degrees"});var a=_u(i,i);if(a<=s)return Ys(t,n,{units:"degrees"});var u=s/a,l=[e[0]+u*i[0],e[1]+u*i[1]];return Ys(t,l,{units:"degrees"})}(u,e,n,{method:o});r0)-(t<0)||+t}(r*(n[1]-e[1])-o*i)}function Lu(t,e){return e.geometry.coordinates[0].every((function(e){return zt(I(e),t)}))}var Pu=function(){return s((function t(e){i(this,t),this.id=t.buildId(e),this.coordinates=e,this.innerEdges=[],this.outerEdges=[],this.outerEdgesSorted=!1}),[{key:"removeInnerEdge",value:function(t){this.innerEdges=this.innerEdges.filter((function(e){return e.from.id!==t.from.id}))}},{key:"removeOuterEdge",value:function(t){this.outerEdges=this.outerEdges.filter((function(e){return e.to.id!==t.to.id}))}},{key:"addOuterEdge",value:function(t){this.outerEdges.push(t),this.outerEdgesSorted=!1}},{key:"sortOuterEdges",value:function(){var t=this;this.outerEdgesSorted||(this.outerEdges.sort((function(e,n){var r=e.to,i=n.to;if(r.coordinates[0]-t.coordinates[0]>=0&&i.coordinates[0]-t.coordinates[0]<0)return 1;if(r.coordinates[0]-t.coordinates[0]<0&&i.coordinates[0]-t.coordinates[0]>=0)return-1;if(r.coordinates[0]-t.coordinates[0]==0&&i.coordinates[0]-t.coordinates[0]==0)return r.coordinates[1]-t.coordinates[1]>=0||i.coordinates[1]-t.coordinates[1]>=0?r.coordinates[1]-i.coordinates[1]:i.coordinates[1]-r.coordinates[1];var o=Mu(t.coordinates,r.coordinates,i.coordinates);return o<0?1:o>0?-1:Math.pow(r.coordinates[0]-t.coordinates[0],2)+Math.pow(r.coordinates[1]-t.coordinates[1],2)-(Math.pow(i.coordinates[0]-t.coordinates[0],2)+Math.pow(i.coordinates[1]-t.coordinates[1],2))})),this.outerEdgesSorted=!0)}},{key:"getOuterEdges",value:function(){return this.sortOuterEdges(),this.outerEdges}},{key:"getOuterEdge",value:function(t){return this.sortOuterEdges(),this.outerEdges[t]}},{key:"addInnerEdge",value:function(t){this.innerEdges.push(t)}}],[{key:"buildId",value:function(t){return t.join(",")}}])}(),Cu=function(){function t(e,n){i(this,t),this.from=e,this.to=n,this.next=void 0,this.label=void 0,this.symetric=void 0,this.ring=void 0,this.from.addOuterEdge(this),this.to.addInnerEdge(this)}return s(t,[{key:"getSymetric",value:function(){return this.symetric||(this.symetric=new t(this.to,this.from),this.symetric.symetric=this),this.symetric}},{key:"deleteEdge",value:function(){this.from.removeOuterEdge(this),this.to.removeInnerEdge(this)}},{key:"isEqual",value:function(t){return this.from.id===t.from.id&&this.to.id===t.to.id}},{key:"toString",value:function(){return"Edge { ".concat(this.from.id," -> ").concat(this.to.id," }")}},{key:"toLineString",value:function(){return L([this.from.coordinates,this.to.coordinates])}},{key:"compareTo",value:function(t){return Mu(t.from.coordinates,t.to.coordinates,this.to.coordinates)}}])}(),Tu=function(){return s((function t(){i(this,t),this.edges=[],this.polygon=void 0,this.envelope=void 0}),[{key:"push",value:function(t){this.edges.push(t),this.polygon=this.envelope=void 0}},{key:"get",value:function(t){return this.edges[t]}},{key:"length",get:function(){return this.edges.length}},{key:"forEach",value:function(t){this.edges.forEach(t)}},{key:"map",value:function(t){return this.edges.map(t)}},{key:"some",value:function(t){return this.edges.some(t)}},{key:"isValid",value:function(){return!0}},{key:"isHole",value:function(){var t=this,e=this.edges.reduce((function(e,n,r){return n.from.coordinates[1]>t.edges[e].from.coordinates[1]&&(e=r),e}),0),n=(0===e?this.length:e)-1,r=(e+1)%this.length,i=Mu(this.edges[n].from.coordinates,this.edges[e].from.coordinates,this.edges[r].from.coordinates);return 0===i?this.edges[n].from.coordinates[0]>this.edges[r].from.coordinates[0]:i>0}},{key:"toMultiPoint",value:function(){return O(this.edges.map((function(t){return t.from.coordinates})))}},{key:"toPolygon",value:function(){if(this.polygon)return this.polygon;var t=this.edges.map((function(t){return t.from.coordinates}));return t.push(this.edges[0].from.coordinates),this.polygon=S([t])}},{key:"getEnvelope",value:function(){return this.envelope?this.envelope:this.envelope=Us(this.toPolygon())}},{key:"inside",value:function(t){return zt(t,this.toPolygon())}}],[{key:"findEdgeRingContaining",value:function(t,e){var n,r,i=t.getEnvelope();return e.forEach((function(e){var o,s,u,l,h,c,f=e.getEnvelope();if((r&&(n=r.getEnvelope()),s=i,u=(o=f).geometry.coordinates[0].map((function(t){return t[0]})),l=o.geometry.coordinates[0].map((function(t){return t[1]})),h=s.geometry.coordinates[0].map((function(t){return t[0]})),c=s.geometry.coordinates[0].map((function(t){return t[1]})),Math.max.apply(null,u)!==Math.max.apply(null,h)||Math.max.apply(null,l)!==Math.max.apply(null,c)||Math.min.apply(null,u)!==Math.min.apply(null,h)||Math.min.apply(null,l)!==Math.min.apply(null,c))&&Lu(f,i)){var g,p,v=a(t.map((function(t){return t.from.coordinates})));try{var d=function(){var t=p.value;e.some((function(e){return n=t,r=e.from.coordinates,n[0]===r[0]&&n[1]===r[1];var n,r}))||(g=t)};for(v.s();!(p=v.n()).done;)d()}catch(t){v.e(t)}finally{v.f()}g&&e.inside(I(g))&&(r&&!Lu(n,f)||(r=e))}})),r}}])}();var Ou=function(){function t(){i(this,t),this.edges=[],this.nodes={}}return s(t,[{key:"getNode",value:function(t){var e=Pu.buildId(t),n=this.nodes[e];return n||(n=this.nodes[e]=new Pu(t)),n}},{key:"addEdge",value:function(t,e){var n=new Cu(t,e),r=n.getSymetric();this.edges.push(n),this.edges.push(r)}},{key:"deleteDangles",value:function(){var t=this;Object.keys(this.nodes).map((function(e){return t.nodes[e]})).forEach((function(e){return t._removeIfDangle(e)}))}},{key:"_removeIfDangle",value:function(t){var e=this;if(t.innerEdges.length<=1){var n=t.getOuterEdges().map((function(t){return t.to}));this.removeNode(t),n.forEach((function(t){return e._removeIfDangle(t)}))}}},{key:"deleteCutEdges",value:function(){var t=this;this._computeNextCWEdges(),this._findLabeledEdgeRings(),this.edges.forEach((function(e){e.label===e.symetric.label&&(t.removeEdge(e.symetric),t.removeEdge(e))}))}},{key:"_computeNextCWEdges",value:function(t){var e=this;void 0===t?Object.keys(this.nodes).forEach((function(t){return e._computeNextCWEdges(e.nodes[t])})):t.getOuterEdges().forEach((function(e,n){t.getOuterEdge((0===n?t.getOuterEdges().length:n)-1).symetric.next=e}))}},{key:"_computeNextCCWEdges",value:function(t,e){for(var n,r,i=t.getOuterEdges(),o=i.length-1;o>=0;--o){var s=i[o],a=s.symetric,u=void 0,l=void 0;s.label===e&&(u=s),a.label===e&&(l=a),u&&l&&(l&&(r=l),u&&(r&&(r.next=u,r=void 0),n||(n=u)))}r&&(r.next=n)}},{key:"_findLabeledEdgeRings",value:function(){var t=[],e=0;return this.edges.forEach((function(n){if(!(n.label>=0)){t.push(n);var r=n;do{r.label=e,r=r.next}while(!n.isEqual(r));e++}})),t}},{key:"getEdgeRings",value:function(){var t=this;this._computeNextCWEdges(),this.edges.forEach((function(t){t.label=void 0})),this._findLabeledEdgeRings().forEach((function(e){t._findIntersectionNodes(e).forEach((function(n){t._computeNextCCWEdges(n,e.label)}))}));var e=[];return this.edges.forEach((function(n){n.ring||e.push(t._findEdgeRing(n))})),e}},{key:"_findIntersectionNodes",value:function(t){var e=[],n=t,r=function(){var r=0;n.from.getOuterEdges().forEach((function(e){e.label===t.label&&++r})),r>1&&e.push(n.from),n=n.next};do{r()}while(!t.isEqual(n));return e}},{key:"_findEdgeRing",value:function(t){var e=t,n=new Tu;do{n.push(e),e.ring=n,e=e.next}while(!t.isEqual(e));return n}},{key:"removeNode",value:function(t){var e=this;t.getOuterEdges().forEach((function(t){return e.removeEdge(t)})),t.innerEdges.forEach((function(t){return e.removeEdge(t)})),delete this.nodes[t.id]}},{key:"removeEdge",value:function(t){this.edges=this.edges.filter((function(e){return!e.isEqual(t)})),t.deleteEdge()}}],[{key:"fromGeoJson",value:function(e){!function(t){if(!t)throw new Error("No geojson passed");if("FeatureCollection"!==t.type&&"GeometryCollection"!==t.type&&"MultiLineString"!==t.type&&"LineString"!==t.type&&"Feature"!==t.type)throw new Error("Invalid input type '".concat(t.type,"'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature"))}(e);var n=new t;return xt(e,(function(t){et(t,"LineString","Graph::fromGeoJson"),ft(t,(function(t,e){if(t){var r=n.getNode(t),i=n.getNode(e);n.addEdge(r,i)}return e}))})),n}}])}();function Ru(t,e){var n,r;ct(t,(function(t,i,o,s,a){if(r!==a)e.push([]);else{var u=n[0],l=n[1],h=t[0],c=t[1];e[a].push([.75*u+.25*h,.75*l+.25*c]),e[a].push([.25*u+.75*h,.25*l+.75*c])}n=t,r=a}),!1),e.forEach((function(t){t.push(t[0])}))}function Au(t,e){var n,r,i;ct(t,(function(t,o,s,a,u){if(r!==a)e.push([[]]);else if(i!==u)e[a].push([]);else{var l=n[0],h=n[1],c=t[0],f=t[1];e[a][u].push([.75*l+.25*c,.75*h+.25*f]),e[a][u].push([.25*l+.75*c,.25*h+.75*f])}n=t,r=a,i=u}),!1),e.forEach((function(t){t.forEach((function(t){t.push(t[0])}))}))}function Du(t,e,n,r,i){for(var o=0;o0?qu(e,s,r)<0||(r=s):n>0&&u<=0&&(Fu(e,s,i)||(i=s)),n=u}return[r,i]}function Fu(t,e,n){return qu(t,e,n)>0}function qu(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(n[0]-t[0])*(e[1]-t[1])}function Vu(t){return Bu(t,"mercator",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Gu(t){return Bu(t,"wgs84",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Bu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=(n=n||{}).mutate;if(!t)throw new Error("geojson is required");return Array.isArray(t)&&U(t[0])?t="mercator"===e?Yu(t):zu(t):(!0!==r&&(t=Ai(t)),ct(t,(function(t){var n="mercator"===e?Yu(t):zu(t);t[0]=n[0],t[1]=n[1]}))),t}function Yu(t){var e=Math.PI/180,n=6378137,r=20037508.342789244,i=Math.abs(t[0])<=180?t[0]:t[0]-360*function(t){return t<0?-1:t>0?1:0}(t[0]),o=[n*i*e,n*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return o[0]>r&&(o[0]=r),o[0]<-r&&(o[0]=-r),o[1]>r&&(o[1]=r),o[1]<-r&&(o[1]=-r),o}function zu(t){var e=180/Math.PI,n=6378137;return[t[0]*e/n,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/n)))*e]}var ju=Object.freeze({__proto__:null,toMercator:Vu,toWgs84:Gu});var Xu={20:1.07275,15:1.13795,10:1.22385,5:1.3581,2:1.51743,1:1.62762};function Uu(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}function Zu(t){var e=[];return function t(n){return 0===n||1===n?1:e[n]>0?e[n]:e[n]=t(n-1)*n}(t)}function Hu(t){return Ju(t),Wu(t)}function Wu(t){return Array.isArray(t)?el(t):t&&t.bbox?el(t.bbox):[360*tl(),180*tl()]}function Ju(t){null!=t&&(Array.isArray(t)?H(t):null!=t.bbox&&H(t.bbox))}function Ku(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1);for(var n=[],r=0;r1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1),void 0!==e.bbox&&null!==e.bbox||(e.bbox=[-180,-90,180,90]),U(e.num_vertices)&&void 0!==e.num_vertices||(e.num_vertices=10),U(e.max_radial_length)&&void 0!==e.max_radial_length||(e.max_radial_length=10);var n=Math.abs(e.bbox[0]-e.bbox[2]),r=Math.abs(e.bbox[1]-e.bbox[3]),i=Math.min(n/2,r/2);if(e.max_radial_length>i)throw new Error("max_radial_length is greater than the radius of the bbox");for(var o=[e.bbox[0]+e.max_radial_length,e.bbox[1]+e.max_radial_length,e.bbox[2]-e.max_radial_length,e.bbox[3]-e.max_radial_length],s=[],a=function(){var t,n=[],r=d(Array(e.num_vertices+1)).map(Math.random);r.forEach((function(t,e,n){n[e]=e>0?t+n[e-1]:t})),r.forEach((function(t){t=2*t*Math.PI/r[r.length-1];var i=Math.random();n.push([i*(e.max_radial_length||10)*Math.sin(t),i*(e.max_radial_length||10)*Math.cos(t)])})),n[n.length-1]=n[0],n=n.reverse().map((t=Wu(o),function(e){return[e[0]+t[0],e[1]+t[1]]})),s.push(S([n]))},u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox;Ju(n);var r=e.num_vertices,i=e.max_length,o=e.max_rotation;null==t&&(t=1),(!U(r)||void 0===r||r<2)&&(r=10),U(i)&&void 0!==i||(i=1e-4),U(o)&&void 0!==o||(o=Math.PI/8);for(var s=[],a=0;a0;){var l=a.pop();if(l===n)return ll(l);l.closed=!0;for(var h=t.neighbors(l),c=0,f=h.length;c1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function dl(t,e,n,r,i){for(var o,s=r,a=e+1;as&&(o=a,s=u)}s>r&&(o-e>1&&dl(t,e,o,r,i),i.push(t[o]),n-o>1&&dl(t,o,n,r,i))}function yl(t,e){var n=t.length-1,r=[t[0]];return dl(t,0,n,e,r),r.push(t[n]),r}function ml(t,e,n){if(t.length<=2)return t;var r=void 0!==e?e*e:1;return t=n?t:function(t,e){for(var n,r,i,o,s,a=t[0],u=[a],l=1,h=t.length;le&&(u.push(n),a=n);return a!==n&&u.push(n),u}(t,r),t=yl(t,r)}function _l(t,e,n){return t.map((function(t){if(t.length<4)throw new Error("invalid polygon");for(var r=e,i=ml(t,r,n);!xl(i);)i=ml(t,r-=.01*r,n);return i[i.length-1][0]===i[0][0]&&i[i.length-1][1]===i[0][1]||i.push(i[0]),i}))}function xl(t){return!(t.length<3)&&!(3===t.length&&t[2][0]===t[0][0]&&t[2][1]===t[0][1])}function El(t,e){return{x:t[0]-e[0],y:t[1]-e[1]}}cl.prototype.init=function(){this.dirtyNodes=[];for(var t=0;t0&&(this.content[0]=e,this.bubbleUp(0)),t},remove:function(t){var e=this.content.indexOf(t),n=this.content.pop();e!==this.content.length-1&&(this.content[e]=n,this.scoreFunction(n)0;){var n=(t+1>>1)-1,r=this.content[n];if(!(this.scoreFunction(e)80*i){o=a=t[0],s=h=t[1];for(var _=i;_a&&(a=c),g>h&&(h=g);p=0!==(p=Math.max(a-o,h-s))?32767/p:0}return r(y,m,i,o,s,p,0),m}function e(t,e,n,r,i){var o,s;if(i===I(t,e,n,r)>0)for(o=e;o=e;o-=r)s=k(o,t[o],t[o+1],s);return s&&d(s,s.next)&&(b(s),s=s.next),s}function n(t,e){if(!t)return t;e||(e=t);var n,r=t;do{if(n=!1,r.steiner||!d(r,r.next)&&0!==v(r.prev,r,r.next))r=r.next;else{if(b(r),(r=e=r.prev)===r.next)break;n=!0}}while(n||r!==e);return e}function r(t,e,u,l,h,f,g){if(t){!g&&f&&function(t,e,n,r){var i=t;do{0===i.z&&(i.z=c(i.x,i.y,e,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,n,r,i,o,s,a,u,l=1;do{for(n=t,t=null,o=null,s=0;n;){for(s++,r=n,a=0,e=0;e0||u>0&&r;)0!==a&&(0===u||!r||n.z<=r.z)?(i=n,n=n.nextZ,a--):(i=r,r=r.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;n=r}o.nextZ=null,l*=2}while(s>1)}(i)}(t,l,h,f);for(var p,v,d=t;t.prev!==t.next;)if(p=t.prev,v=t.next,f?o(t,l,h,f):i(t))e.push(p.i/u|0),e.push(t.i/u|0),e.push(v.i/u|0),b(t),t=v.next,d=v.next;else if((t=v)===d){g?1===g?r(t=s(n(t),e,u),e,u,l,h,f,2):2===g&&a(t,e,u,l,h,f):r(n(t),e,u,l,h,f,1);break}}}function i(t){var e=t.prev,n=t,r=t.next;if(v(e,n,r)>=0)return!1;for(var i=e.x,o=n.x,s=r.x,a=e.y,u=n.y,l=r.y,h=io?i>s?i:s:o>s?o:s,p=a>u?a>l?a:l:u>l?u:l,d=r.next;d!==e;){if(d.x>=h&&d.x<=f&&d.y>=c&&d.y<=p&&g(i,a,o,u,s,l,d.x,d.y)&&v(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function o(t,e,n,r){var i=t.prev,o=t,s=t.next;if(v(i,o,s)>=0)return!1;for(var a=i.x,u=o.x,l=s.x,h=i.y,f=o.y,p=s.y,d=au?a>l?a:l:u>l?u:l,_=h>f?h>p?h:p:f>p?f:p,x=c(d,y,e,n,r),E=c(m,_,e,n,r),k=t.prevZ,b=t.nextZ;k&&k.z>=x&&b&&b.z<=E;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;if(k=k.prevZ,b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;k&&k.z>=x;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;k=k.prevZ}for(;b&&b.z<=E;){if(b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function s(t,e,r){var i=t;do{var o=i.prev,s=i.next.next;!d(o,s)&&y(o,i,i.next,s)&&x(o,s)&&x(s,o)&&(e.push(o.i/r|0),e.push(i.i/r|0),e.push(s.i/r|0),b(i),b(i.next),i=t=s),i=i.next}while(i!==t);return n(i)}function a(t,e,i,o,s,a){var u=t;do{for(var l=u.next.next;l!==u.prev;){if(u.i!==l.i&&p(u,l)){var h=E(u,l);return u=n(u,u.next),h=n(h,h.next),r(u,e,i,o,s,a,0),void r(h,e,i,o,s,a,0)}l=l.next}u=u.next}while(u!==t)}function u(t,e){return t.x-e.x}function l(t,e){var r=function(t,e){var n,r=e,i=t.x,o=t.y,s=-1/0;do{if(o<=r.y&&o>=r.next.y&&r.next.y!==r.y){var a=r.x+(o-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=i&&a>s&&(s=a,n=r.x=r.x&&r.x>=c&&i!==r.x&&g(on.x||r.x===n.x&&h(n,r)))&&(n=r,p=u)),r=r.next}while(r!==l);return n}(t,e);if(!r)return e;var i=E(r,t);return n(i,i.next),n(r,r.next)}function h(t,e){return v(t.prev,t,e.prev)<0&&v(e.next,t,t.next)<0}function c(t,e,n,r,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function f(t){var e=t,n=t;do{(e.x=(t-s)*(o-a)&&(t-s)*(r-a)>=(n-s)*(e-a)&&(n-s)*(o-a)>=(i-s)*(r-a)}function p(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&y(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(x(t,e)&&x(e,t)&&function(t,e){var n=t,r=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{n.y>o!=n.next.y>o&&n.next.y!==n.y&&i<(n.next.x-n.x)*(o-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==t);return r}(t,e)&&(v(t.prev,t,e.prev)||v(t,e.prev,e))||d(t,e)&&v(t.prev,t,t.next)>0&&v(e.prev,e,e.next)>0)}function v(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function d(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,n,r){var i=_(v(t,e,n)),o=_(v(t,e,r)),s=_(v(n,r,t)),a=_(v(n,r,e));return i!==o&&s!==a||(!(0!==i||!m(t,n,e))||(!(0!==o||!m(t,r,e))||(!(0!==s||!m(n,t,r))||!(0!==a||!m(n,e,r)))))}function m(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function _(t){return t>0?1:t<0?-1:0}function x(t,e){return v(t.prev,t,t.next)<0?v(t,e,t.next)>=0&&v(t,t.prev,e)>=0:v(t,e,t.prev)<0||v(t,t.next,e)<0}function E(t,e){var n=new w(t.i,t.x,t.y),r=new w(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,n.next=i,i.prev=n,r.next=n,n.prev=r,o.next=r,r.prev=o,r}function k(t,e,n,r){var i=new w(t,e,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function b(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 w(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function I(t,e,n,r){for(var i=0,o=e,s=n-r;o0&&(r+=t[i-1].length,n.holes.push(r))}return n},bl.exports}(),Il=mn(wl);function Nl(t){var e=function(t){for(var e=t[0][0].length,n={vertices:[],holes:[],dimensions:e},r=0,i=0;i0&&(r+=t[i-1].length,n.holes.push(r))}return n}(t),n=Il(e.vertices,e.holes,2),r=[],i=[];n.forEach((function(t,r){var o=n[r];i.push([e.vertices[2*o],e.vertices[2*o+1]])}));for(var o=0;o=1||u<=0||l>=1||l<=0))){var v=p,d=!o[v];d&&(o[v]=!0),e?i.push(e(p,t,n,h,c,u,s,a,f,g,l,d)):i.push(p)}}function v(t,e){var n,i,o,s,a=r[t][e],u=r[t][e+1];return a[0]f[e.isect].coord?-1:1}));for(l=[];x.length>0;){var I=x.pop(),N=I.isect,M=I.parent,L=I.winding,P=l.length,T=[f[N].coord],O=N;if(f[N].ringAndEdge1Walkable)var R=f[N].ringAndEdge1,A=f[N].nxtIsectAlongRingAndEdge1;else R=f[N].ringAndEdge2,A=f[N].nxtIsectAlongRingAndEdge2;for(;!Rl(f[N].coord,f[A].coord);){T.push(f[A].coord);var D=void 0;for(r=0;r1)for(e=0;e=0==e}function Ol(t){for(var e=0,n=0;n0)){if(o/=f,f<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=r-u,f||!(o<0)){if(o/=f,f<0){if(o>c)return;o>h&&(h=o)}else if(f>0){if(o0)){if(o/=g,g<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=i-l,g||!(o<0)){if(o/=g,g<0){if(o>c)return;o>h&&(h=o)}else if(g>0){if(o0||c<1)||(h>0&&(t[0]=[u+h*f,l+h*g]),c<1&&(t[1]=[u+c*f,l+c*g]),!0)}}}}}function Hl(t,e,n,r,i){var o=t[1];if(o)return!0;var s,a,u=t[0],l=t.left,h=t.right,c=l[0],f=l[1],g=h[0],p=h[1],v=(c+g)/2,d=(f+p)/2;if(p===f){if(v=r)return;if(c>g){if(u){if(u[1]>=i)return}else u=[v,n];o=[v,i]}else{if(u){if(u[1]1)if(c>g){if(u){if(u[1]>=i)return}else u=[(n-a)/s,n];o=[(i-a)/s,i]}else{if(u){if(u[1]=r)return}else u=[e,s*e+a];o=[r,s*r+a]}else{if(u){if(u[0]=-dh)){var g=u*u+l*l,p=h*h+c*c,v=(c*g-l*p)/f,d=(u*p-h*g)/f,y=$l.pop()||new th;y.arc=t,y.site=i,y.x=v+s,y.y=(y.cy=d+a)+Math.sqrt(v*v+d*d),t.circle=y;for(var m=null,_=gh._;_;)if(y.y<_.y||y.y===_.y&&y.x<=_.x){if(!_.L){m=_.P;break}_=_.L}else{if(!_.R){m=_;break}_=_.R}gh.insert(m,y),m||(Ql=y)}}}}function nh(t){var e=t.circle;e&&(e.P||(Ql=e.N),gh.remove(e),$l.push(e),Gl(e),t.circle=null)}var rh=[];function ih(){Gl(this),this.edge=this.site=this.circle=null}function oh(t){var e=rh.pop()||new ih;return e.site=t,e}function sh(t){nh(t),ch.remove(t),rh.push(t),Gl(t)}function ah(t){var e=t.circle,n=e.x,r=e.cy,i=[n,r],o=t.P,s=t.N,a=[t];sh(t);for(var u=o;u.circle&&Math.abs(n-u.circle.x)vh)a=a.L;else{if(!((i=o-hh(a,s))>vh)){r>-vh?(e=a.P,n=a):i>-vh?(e=a,n=a.N):e=n=a;break}if(!a.R){e=a;break}a=a.R}!function(t){fh[t.index]={site:t,halfedges:[]}}(t);var u=oh(t);if(ch.insert(e,u),e||n){if(e===n)return nh(e),n=oh(e.site),ch.insert(u,n),u.edge=n.edge=jl(e.site,u.site),eh(e),void eh(n);if(n){nh(e),nh(n);var l=e.site,h=l[0],c=l[1],f=t[0]-h,g=t[1]-c,p=n.site,v=p[0]-h,d=p[1]-c,y=2*(f*d-g*v),m=f*f+g*g,_=v*v+d*d,x=[(d*m-g*_)/y+h,(f*_-v*m)/y+c];Ul(n.edge,l,p,x),u.edge=jl(l,t,null,x),n.edge=jl(t,p,null,x),eh(e),eh(n)}else u.edge=jl(e.site,u.site)}}function lh(t,e){var n=t.site,r=n[0],i=n[1],o=i-e;if(!o)return r;var s=t.P;if(!s)return-1/0;var a=(n=s.site)[0],u=n[1],l=u-e;if(!l)return a;var h=a-r,c=1/o-1/l,f=h/l;return c?(-f+Math.sqrt(f*f-2*c*(h*h/(-2*l)-u+l/2+i-o/2)))/c+r:(r+a)/2}function hh(t,e){var n=t.N;if(n)return lh(n,e);var r=t.site;return r[1]===e?r[0]:1/0}var ch,fh,gh,ph,vh=1e-6,dh=1e-12;function yh(t,e){return e[1]-t[1]||e[0]-t[0]}function mh(t,e){var n,r,i,o=t.sort(yh).pop();for(ph=[],fh=new Array(t.length),ch=new Vl,gh=new Vl;;)if(i=Ql,o&&(!i||o[1]vh||Math.abs(i[0][1]-i[1][1])>vh)||delete ph[o]}(s,a,u,l),function(t,e,n,r){var i,o,s,a,u,l,h,c,f,g,p,v,d=fh.length,y=!0;for(i=0;ivh||Math.abs(v-f)>vh)&&(u.splice(a,0,ph.push(Xl(s,g,Math.abs(p-t)vh?[t,Math.abs(c-t)vh?[Math.abs(f-r)vh?[n,Math.abs(c-n)vh?[Math.abs(f-e)=a)return null;var u=t-i.site[0],l=e-i.site[1],h=u*u+l*l;do{i=o.cells[r=s],s=null,i.halfedges.forEach((function(n){var r=o.edges[n],a=r.left;if(a!==i.site&&a||(a=r.right)){var u=t-a[0],l=e-a[1],c=u*u+l*l;c2&&void 0!==arguments[2]?arguments[2]:{},r=rt(t).coordinates,i=0,o=0;o=i&&o===r.length-1);o++){if(i>=e){var s=e-i;if(s){var a=st(r[o],r[o-1])-180;return at(r[o],s,a,n)}return I(r[o])}i+=ut(r[o],r[o+1],n)}return I(r[r.length-1])},t.angle=function(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!Z(r))throw new Error("options is invalid");if(!t)throw new Error("startPoint is required");if(!e)throw new Error("midPoint is required");if(!n)throw new Error("endPoint is required");var i=t,o=e,s=n,a=G(!0!==r.mercator?st(o,i):lt(o,i)),u=G(!0!==r.mercator?st(o,s):lt(o,s));u1&&void 0!==arguments[1]?arguments[1]:{},n=e.resolution||1e4,r=e.sharpness||.85,i=[],o=rt(t).coordinates.map((function(t){return{x:t[0],y:t[1]}})),s=new Gt({duration:n,points:o,sharpness:r}),a=function(t){var e=s.pos(t);Math.floor(t/100)%2==0&&i.push([e.x,e.y])},u=0;u0;else if(n!==u>0)return!0}return!1},t.booleanContains=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type,s=n.coordinates,u=r.coordinates;switch(i){case"Point":if("Point"===o)return Ht(s,u);throw new Error("feature2 "+o+" geometry not supported");case"MultiPoint":switch(o){case"Point":return function(t,e){var n,r=!1;for(n=0;n2&&void 0!==arguments[2]?arguments[2]:{}).precision;if("number"!=typeof(n=null==n||isNaN(n)?6:n)||!(n>=0))throw new Error("precision must be a positive number");return rt(t).type===rt(e).type&&Ne(Le(t),Le(e),{precision:n})},t.booleanIntersects=Oe,t.booleanOverlap=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;if("MultiPoint"===i&&"MultiPoint"!==o||("LineString"===i||"MultiLineString"===i)&&"LineString"!==o&&"MultiLineString"!==o||("Polygon"===i||"MultiPolygon"===i)&&"Polygon"!==o&&"MultiPolygon"!==o)throw new Error("features must be of the same type");if("Point"===i)throw new Error("Point geometry not supported");if(Ne(t,e,{precision:6}))return!1;var s=0;switch(i){case"MultiPoint":for(var a=0;a0},t.booleanParallel=function(t,e){if(!t)throw new Error("line1 is required");if(!e)throw new Error("line2 is required");if("LineString"!==In(t,"line1"))throw new Error("line1 must be a LineString");if("LineString"!==In(e,"line2"))throw new Error("line2 must be a LineString");for(var n=$e(Le(t)).features,r=$e(Le(e)).features,i=0;i1;case"MultiPoint":for(var i=0;i0&&ue(S([r[0]]),S([r[i]])).features.length>1)return!1}return!0;case"MultiPolygon":for(i=0;i0&&ue(S([o[0]]),S([o[s]])).features.length>1)return!1}return!0;default:return!1}},t.booleanWithin=Cn,t.buffer=function(t,e,n){var r=(n=n||{}).units||"kilometers",i=n.steps||8;if(!t)throw new Error("geojson is required");if("object"!==m(n))throw new Error("options must be an object");if("number"!=typeof i)throw new Error("steps must be an number");if(void 0===e)throw new Error("radius is required");if(i<=0)throw new Error("steps must be greater than 0");var o=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){var n=ui(t,e,r,i);n&&o.push(n)})),C(o);case"FeatureCollection":return vt(t,(function(t){var n=ui(t,e,r,i);n&&vt(n,(function(t){t&&o.push(t)}))})),C(o)}return ui(t,e,r,i)},t.center=An,t.centerMean=fi,t.centerMedian=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.counter||10;if(!U(n))throw new Error("counter must be a number");var r=e.weight,i=fi(t,{weight:e.weight}),o=C([]);vt(t,(function(t){var e;o.features.push(gi(t,{properties:{weight:null==(e=t.properties)?void 0:e[r]}}))}));var s={tolerance:e.tolerance,medianCandidates:[]};return pi(i.geometry.coordinates,[0,0],o,s,n)},t.centerOfMass=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(it(e)){case"Point":return I(K(e),n.properties);case"Polygon":var r=[];ct(e,(function(t){r.push(t)}));var i,o,s,a,u,l,h,c,f=gi(e,{properties:n.properties}),g=f.geometry.coordinates,p=0,v=0,d=0,y=r.map((function(t){return[t[0]-g[0],t[1]-g[1]]}));for(i=0;i2&&void 0!==arguments[2]?arguments[2]:{};!0!==n.mutate&&(t=Ai(t));var r=n.minPoints||3,i=V(e,n.units),o=new to(t.features.length),s=t.features.map((function(t){return!1})),a=t.features.map((function(t){return!1})),u=t.features.map((function(t){return!1})),l=t.features.map((function(t){return-1}));o.load(t.features.map((function(t,e){var n=v(t.geometry.coordinates,2),r=n[0],i=n[1];return{minX:r,minY:i,maxX:r,maxY:i,index:e}})));var h=function(n){var r=t.features[n],s=v(r.geometry.coordinates,2),a=s[0],u=s[1],l=Math.max(u-i,-90),h=Math.min(u+i,90),c=l<0&&h>0?i:Math.abs(l)=r){var i=c;c++,s[e]=!0,function(t,e){for(var n=0;n=r&&e.push.apply(e,d(o))}a[i]||(a[i]=!0,l[i]=t)}}(i,n)}else u[e]=!0}})),t.features.forEach((function(e,n){var r=t.features[n];r.properties||(r.properties={}),l[n]>=0?(r.properties.dbscan=u[n]?"edge":"core",r.properties.cluster=l[n]):r.properties.dbscan="noise"})),t},t.clustersKmeans=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.features.length;e.numberOfClusters=e.numberOfClusters||Math.round(Math.sqrt(n/2)),e.numberOfClusters>n&&(e.numberOfClusters=n),!0!==e.mutate&&(t=Ai(t));var r=yt(t),i=r.slice(0,e.numberOfClusters),o=ro(r,e.numberOfClusters,i),s={};return o.centroids.forEach((function(t,e){s[e]=t})),vt(t,(function(t,e){var n=o.idxs[e];t.properties.cluster=n,t.properties.centroid=s[n]})),t},t.collect=function(t,e,n,r){var i=new io(6),o=e.features.map((function(t){var e;return{minX:t.geometry.coordinates[0],minY:t.geometry.coordinates[1],maxX:t.geometry.coordinates[0],maxY:t.geometry.coordinates[1],property:null==(e=t.properties)?void 0:e[n]}}));return i.load(o),t.features.forEach((function(t){t.properties||(t.properties={});var e=Rt(t),n=i.search({minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}),o=[];n.forEach((function(e){zt([e.minX,e.minY],t)&&o.push(e.property)})),t.properties[r]=o})),t},t.collectionOf=nt,t.combine=function(t){var e={MultiPoint:{coordinates:[],properties:[]},MultiLineString:{coordinates:[],properties:[]},MultiPolygon:{coordinates:[],properties:[]}};return vt(t,(function(t){var n,r,i,o;switch(null==(o=t.geometry)?void 0:o.type){case"Point":e.MultiPoint.coordinates.push(t.geometry.coordinates),e.MultiPoint.properties.push(t.properties);break;case"MultiPoint":(n=e.MultiPoint.coordinates).push.apply(n,d(t.geometry.coordinates)),e.MultiPoint.properties.push(t.properties);break;case"LineString":e.MultiLineString.coordinates.push(t.geometry.coordinates),e.MultiLineString.properties.push(t.properties);break;case"MultiLineString":(r=e.MultiLineString.coordinates).push.apply(r,d(t.geometry.coordinates)),e.MultiLineString.properties.push(t.properties);break;case"Polygon":e.MultiPolygon.coordinates.push(t.geometry.coordinates),e.MultiPolygon.properties.push(t.properties);break;case"MultiPolygon":(i=e.MultiPolygon.coordinates).push.apply(i,d(t.geometry.coordinates)),e.MultiPolygon.properties.push(t.properties)}})),C(Object.keys(e).filter((function(t){return e[t].coordinates.length})).sort().map((function(t){return b({type:t,coordinates:e[t].coordinates},{collectedProperties:e[t].properties})})))},t.concave=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.maxEdge||1/0,r=function(t){var e=[],n={};return vt(t,(function(t){if(t.geometry){var r=t.geometry.coordinates.join("-");Object.prototype.hasOwnProperty.call(n,r)||(e.push(t),n[r]=!0)}})),C(e)}(t),i=oo(r);if(i.features=i.features.filter((function(t){var r=t.geometry.coordinates[0][0],i=t.geometry.coordinates[0][1],o=t.geometry.coordinates[0][2],s=ut(r,i,e),a=ut(i,o,e),u=ut(r,o,e);return s<=n&&a<=n&&u<=n})),i.features.length<1)return null;var o=Ro(i);return 1===o.coordinates.length&&(o.coordinates=o.coordinates[0],o.type="Polygon"),b(o)},t.containsNumber=$,t.convertArea=X,t.convertLength=j,t.convex=Oi,t.coordAll=yt,t.coordEach=ct,t.coordReduce=ft,t.createBins=zi,t.degreesToRadians=z,t.destination=at,t.difference=function(t){var e=[];if(mt(t,(function(t){e.push(t.coordinates)})),e.length<2)throw new Error("Must have at least two features");var n=t.features[0].properties||{},r=As.apply(Fs,[e[0]].concat(d(e.slice(1))));return 0===r.length?null:1===r.length?S(r[0],n):R(r,n)},t.dissolve=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.propertyName;nt(t,"Polygon","dissolve");var r=[];if(!n)return qs(R(Os.apply(null,t.features.map((function(t){return t.geometry.coordinates})))));var i={};vt(t,(function(t){t.properties&&(Object.prototype.hasOwnProperty.call(i,t.properties[n])||(i[t.properties[n]]=[]),i[t.properties[n]].push(t))}));for(var o=Object.keys(i),s=0;s1&&void 0!==arguments[1]?arguments[1]:{},o=i.properties,s=null==(e=i.autoComplete)||e,a=null==(n=i.orderCoords)||n;if(null!=(r=i.mutate)&&r||(t=Ai(t)),"FeatureCollection"===t.type){var u=[];return t.features.forEach((function(t){u.push(Q(ru(t,{},s,a)))})),R(u,o)}return ru(t,o,s,a)},t.mask=function(t,e,n){var r,i=null!=(r=null==n?void 0:n.mutate)&&r,o=e;e&&!1===i&&(o=Ai(e));var s,a=su(o);return("FeatureCollection"===t.type?ou(2===(s=t).features.length?Os(s.features[0].geometry.coordinates,s.features[1].geometry.coordinates):Os.apply(Fs,s.features.map((function(t){return t.geometry.coordinates})))):"Feature"===t.type?ou(Os(t.geometry.coordinates)):ou(Os(t.coordinates))).geometry.coordinates.forEach((function(t){a.geometry.coordinates.push(t[0])})),a},t.meta=Mt,t.midpoint=function(t,e){return at(t,ut(t,e)/2,st(t,e))},t.moranIndex=function(t,e){var n,r,i=e.inputField,o=e.threshold||1e5,s=e.p||2,u=null!=(n=e.binary)&&n,l=Gs(t,{alpha:e.alpha||-1,binary:u,p:s,standardization:null==(r=e.standardization)||r,threshold:o}),h=[];vt(t,(function(t){var e=t.properties||{};h.push(e[i])}));for(var c=au(h),f=function(t){var e,n=au(t),r=0,i=a(t);try{for(i.s();!(e=i.n()).done;){var o=e.value;r+=Math.pow(o-n,2)}}catch(t){i.e(t)}finally{i.f()}return r/t.length}(h),g=0,p=0,v=0,d=0,y=l.length,m=0;m2&&void 0!==arguments[2]?arguments[2]:{},r=n.units,i=n.properties||{},o=function(t){var e=[];switch(t.geometry?t.geometry.type:t.type){case"GeometryCollection":return mt(t,(function(t){"Point"===t.type&&e.push({type:"Feature",properties:{},geometry:t})})),{type:"FeatureCollection",features:e};case"FeatureCollection":return t.features=t.features.filter((function(t){return"Point"===t.geometry.type})),t;default:throw new Error("points must be a Point Collection")}}(t);if(!o.features.length)throw new Error("points must contain features");if(!e)throw new Error("line is required");if("LineString"!==it(e))throw new Error("line must be a LineString");var s=1/0,a=null;return vt(o,(function(t){var n=mu(t,e,{units:r});n2&&void 0!==arguments[2]?arguments[2]:{},a=null!=(i=s.method)?i:"geodesic",u=null!=(o=s.units)?o:"kilometers";if(!e)throw new Error("point is required");if(!r)throw new Error("polygon or multi-polygon is required");var l,h=rt(r);if("MultiPolygon"===h.type){var c=h.coordinates.map((function(n){return t(e,S(n),{method:a,units:u})}));return Math.min.apply(Math,d(c.map(Math.abs)))*(zt(e,r)?-1:1)}if(h.coordinates.length>1){var p=h.coordinates.map((function(n){return t(e,S([n]),{method:a,units:u})})),v=n(l=p)||f(l)||_(l)||g(),y=v[0],m=v.slice(1);if(y>=0)return y;var x=Math.min.apply(Math,d(m));return x<0?Math.abs(x):Math.min(x,Math.abs(y))}var E=le(h),k=1/0;return xt(E,(function(t){k=Math.min(k,mu(e,t,{method:a,units:u}))})),zt(e,h)?-k:k},t.points=N,t.pointsWithinPolygon=Su,t.polygon=S,t.polygonSmooth=function(t,e){(e=e||{}).iterations=e.iterations||1;var n=e.iterations,r=[];if(!t)throw new Error("inputPolys is required");return mt(t,(function(t,e,i){if("Polygon"===t.type){for(var o=[[]],s=0;s0&&(u=S(o).geometry),Ru(u,a),o=a.slice(0)}r.push(S(o,i))}else{if("MultiPolygon"!==t.type)throw new Error("geometry is invalid, must be Polygon or MultiPolygon");for(var l=[[[]]],h=0;h0&&(f=R(l).geometry),Au(f,c),l=c.slice(0)}r.push(R(l,i))}})),C(r)},t.polygonTangents=function(t,e){var n,r=Q(t),i=Q(e),o=[],s=[],a=Rt(e),u=0,l=null;switch(r[0]>a[0]&&r[0]a[1]&&r[1]_&&(_=k)}for(var b=[],w=Object.keys(l).length,I=f/w,N=0,S=0;S<_+1;S++)N+=Math.exp(-I)*Math.pow(I,S)/Zu(S),b.push(N);for(var M=[],L=0,P=0;P<_+1;P++){for(var C=0,T=Object.keys(l);CR&&(R=D)}var F=Xu[r]/Math.sqrt(w),q={criticalValue:F,isRandom:!0,maxAbsoluteDifference:R,observedDistribution:M};return R>F&&(q.isRandom=!1),q},t.radiansToDegrees=Y,t.radiansToLength=F,t.random=nl,t.randomLineString=$u,t.randomPoint=Ku,t.randomPolygon=Qu,t.randomPosition=Hu,t.rectangleGrid=oa,t.rewind=function(t){var e,n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(r=r||{}))throw new Error("options is invalid");var i=null!=(e=r.mutate)&&e,o=null!=(n=r.reverse)&&n;if(!t)throw new Error(" is required");if("boolean"!=typeof o)throw new Error(" must be a boolean");if("boolean"!=typeof i)throw new Error(" must be a boolean");i||"Point"===t.type||"MultiPoint"===t.type||(t=Ai(t));var s=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){rl(t,o)})),t;case"FeatureCollection":return vt(t,(function(t){vt(rl(t,o),(function(t){s.push(t)}))})),C(s)}return rl(t,o)},t.rhumbBearing=lt,t.rhumbDestination=Bs,t.rhumbDistance=Ys,t.round=D,t.sample=function(t,e){if(!t)throw new Error("fc is required");if(null==e)throw new Error("num is required");if("number"!=typeof e)throw new Error("num must be a number");var n=C(function(t,e){var n,r,i=t.slice(0),o=t.length,s=o-e;for(;o-- >s;)n=i[r=Math.floor((o+1)*Math.random())],i[r]=i[o],i[o]=n;return i.slice(s)}(t.features,e));return n},t.sector=function(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!Z(i=i||{}))throw new Error("options is invalid");var o=i.properties;if(!t)throw new Error("center is required");if(null==n)throw new Error("bearing1 is required");if(null==r)throw new Error("bearing2 is required");if(!e)throw new Error("radius is required");if("object"!==m(i))throw new Error("options must be an object");if(sl(n)===sl(r))return Ri(t,e,i);var s=Q(t),a=ja(t,e,n,r,i),u=[[s]];return ct(a,(function(t){u[0].push(t)})),u[0].push(s),S(u,o)},t.segmentEach=kt,t.segmentReduce=bt,t.shortestPath=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.obstacles||C([]),i=n.resolution||100;if(!t)throw new Error("start is required");if(!e)throw new Error("end is required");if(i&&(!U(i)||i<=0))throw new Error("options.resolution must be a number, greater than 0");var o=K(t),s=K(e);if(t=I(o),e=I(s),"FeatureCollection"===r.type){if(0===r.features.length)return L([o,s])}else{if("Polygon"!==r.type)throw new Error("invalid obstacles");r=C([b(rt(r))])}var a=r;a.features.push(t),a.features.push(e);var u=v(Rt(al(Vt(Rt(a)),1.15)),4),l=u[0],h=u[1],c=u[2],f=u[3],g=ut([l,h],[c,h],n)/i;a.features.pop(),a.features.pop();for(var p,d,y=g/ut([l,h],[c,h],n)*(c-l),m=g/ut([l,h],[l,f],n)*(f-h),_=c-l,x=f-h,E=Math.floor(_/y),k=Math.floor(x/m),w=(_-E*y)/2,N=[],S=[],M=1/0,P=1/0,T=f-(x-k*m)/2,O=0;T>=h;){for(var R=[],A=[],D=l+w,F=0;D<=c;){var q=I([D,T]),V=pl(q,r);R.push(V?0:1),A.push(D+"|"+T);var G=ut(q,t);!V&&G1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(i=null!=i?i:{}))throw new Error("options is invalid");var o=null!=(e=i.tolerance)?e:1,s=null!=(n=i.highQuality)&&n,a=null!=(r=i.mutate)&&r;if(!t)throw new Error("geojson is required");if(o&&o<0)throw new Error("invalid tolerance");return!0!==a&&(t=Ai(t)),mt(t,(function(t){!function(t,e,n){var r=t.type;if("Point"===r||"MultiPoint"===r)return t;if(Le(t,{mutate:!0}),"GeometryCollection"!==r)switch(r){case"LineString":t.coordinates=ml(t.coordinates,e,n);break;case"MultiLineString":t.coordinates=t.coordinates.map((function(t){return ml(t,e,n)}));break;case"Polygon":t.coordinates=_l(t.coordinates,e,n);break;case"MultiPolygon":t.coordinates=t.coordinates.map((function(t){return _l(t,e,n)}))}}(t,o,s)})),t},t.square=Ka,t.squareGrid=sa,t.standardDeviationalEllipse=function(t,e){var n;if(!Z(e=e||{}))throw new Error("options is invalid");var r=e.steps||64,i=e.weight,o=e.properties||{};if(!U(r))throw new Error("steps must be a number");if(!Z(o))throw new Error("properties must be a number");var s=yt(t).length,a=fi(t,{weight:i}),u=0,l=0,h=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));u+=Math.pow(r.x,2)*n,l+=Math.pow(r.y,2)*n,h+=r.x*r.y*n}));var c=u-l,f=Math.sqrt(Math.pow(c,2)+4*Math.pow(h,2)),g=2*h,p=Math.atan((c+f)/g),v=180*p/Math.PI,d=0,y=0,m=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));d+=Math.pow(r.x*Math.cos(p)-r.y*Math.sin(p),2)*n,y+=Math.pow(r.x*Math.sin(p)+r.y*Math.cos(p),2)*n,m+=n}));var _=Math.sqrt(2*d/m),x=Math.sqrt(2*y/m),E=js(a,_,x,{units:"degrees",angle:v,steps:r,properties:o}),k=Su(t,C([E])),b={meanCenterCoordinates:Q(a),semiMajorAxis:_,semiMinorAxis:x,numberOfFeatures:s,angle:v,percentageWithinEllipse:100*yt(k).length/s};return E.properties=null!=(n=E.properties)?n:{},E.properties.standardDeviationalEllipse=b,E},t.tag=function(t,e,n,r){return t=Ai(t),e=Ai(e),vt(t,(function(t){t.properties||(t.properties={}),vt(e,(function(e){t.properties&&e.properties&&void 0===t.properties[r]&&zt(t,e)&&(t.properties[r]=e.properties[n])}))})),t},t.tesselate=function(t){if(!t.geometry||"Polygon"!==t.geometry.type&&"MultiPolygon"!==t.geometry.type)throw new Error("input must be a Polygon or MultiPolygon");var e={type:"FeatureCollection",features:[]};return"Polygon"===t.geometry.type?e.features=Nl(t.geometry.coordinates):t.geometry.coordinates.forEach((function(t){e.features=e.features.concat(Nl(t))})),e},t.tin=oo,t.toMercator=Vu,t.toWgs84=Gu,t.transformRotate=zs,t.transformScale=al,t.transformTranslate=function(t,e,n,r){if(!Z(r=r||{}))throw new Error("options is invalid");var i=r.units,o=r.zTranslation,s=r.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("distance is required");if(o&&"number"!=typeof o&&isNaN(o))throw new Error("zTranslation is not a number");if(o=void 0!==o?o:0,0===e&&0===o)return t;if(null==n||isNaN(n))throw new Error("direction is required");return e<0&&(e=-e,n+=180),!1!==s&&void 0!==s||(t=Ai(t)),ct(t,(function(t){var r=Q(Bs(t,e,n,{units:i}));t[0]=r[0],t[1]=r[1],o&&3===t.length&&(t[2]+=o)})),t},t.triangleGrid=aa,t.truncate=Qa,t.union=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must have at least 2 geometries");var r=Os.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)},t.unkinkPolygon=function(t){var e=[];return xt(t,(function(t){"Polygon"===t.geometry.type&&vt(Ll(t),(function(n){e.push(S(n.geometry.coordinates,t.properties))}))})),C(e)},t.validateBBox=H,t.validateId=W,t.voronoi=function(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox||[-180,-85,180,85];if(!t)throw new Error("points is required");if(!Array.isArray(n))throw new Error("bbox is invalid");return nt(t,"Point","points"),C(function(){var t=Fl,e=ql,n=null;function r(r){return new mh(r.map((function(n,i){var o=[Math.round(t(n,i,r)/vh)*vh,Math.round(e(n,i,r)/vh)*vh];return o.index=i,o.data=n,o})),n)}return r.polygons=function(t){return r(t).polygons()},r.links=function(t){return r(t).links()},r.triangles=function(t){return r(t).triangles()},r.x=function(e){return arguments.length?(t="function"==typeof e?e:Dl(+e),r):t},r.y=function(t){return arguments.length?(e="function"==typeof t?t:Dl(+t),r):e},r.extent=function(t){return arguments.length?(n=null==t?null:[[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]],r):n&&[[n[0][0],n[0][1]],[n[1][0],n[1][1]]]},r.size=function(t){return arguments.length?(n=null==t?null:[[0,0],[+t[0],+t[1]]],r):n&&[n[1][0]-n[0][0],n[1][1]-n[0][1]]},r}().x((function(t){return t.geometry.coordinates[0]})).y((function(t){return t.geometry.coordinates[1]})).extent([[n[0],n[1]],[n[2],n[3]]]).polygons(t.features).map((function(e,n){return Object.assign(function(t){return(t=t.slice()).push(t[0]),S([t])}(e),{properties:Fi(t.features[n].properties)})})))}})); diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js new file mode 100644 index 0000000..6b2b9e8 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js @@ -0,0 +1,207 @@ +// This code is derived from the ISC-licensed "mapbox-gl-draw-freehand-mode" plugin +// by Ben Ehmke, Eric Dong, and Joe Woodhouse. +// Source: https://github.com/bemky/mapbox-gl-draw-freehand-mode +(function (MapboxDraw) { + const { geojsonTypes, cursors, types, updateActions, modes, events } = + MapboxDraw.constants; + + const FreehandMode = {}; + + FreehandMode.onSetup = function () { + const polygon = this.newFeature({ + type: geojsonTypes.FEATURE, + properties: {}, + geometry: { + type: geojsonTypes.POLYGON, + coordinates: [[]], + }, + }); + + this.addFeature(polygon); + this.clearSelectedFeatures(); + + // Disable map dragging + setTimeout(() => { + if (!this.map || !this.map.dragPan) return; + this.map.dragPan.disable(); + }, 0); + + this.updateUIClasses({ mouse: cursors.ADD }); + this.activateUIButton(types.POLYGON); + this.setActionableState({ + trash: true, + }); + + return { + polygon, + currentVertexPosition: 0, + dragMoving: false, + isDrawing: false, + }; + }; + + FreehandMode.onDrag = FreehandMode.onTouchMove = function (state, e) { + state.dragMoving = true; + state.isDrawing = true; + this.updateUIClasses({ mouse: cursors.ADD }); + state.polygon.updateCoordinate( + `0.${state.currentVertexPosition}`, + e.lngLat.lng, + e.lngLat.lat, + ); + state.currentVertexPosition++; + state.polygon.updateCoordinate( + `0.${state.currentVertexPosition}`, + e.lngLat.lng, + e.lngLat.lat, + ); + }; + + FreehandMode.onMouseUp = function (state) { + if (state.dragMoving) { + this.simplify(state.polygon); + this.updateUIClasses({ mouse: cursors.MOVE }); + this.fireUpdate(); + this.changeMode(modes.SIMPLE_SELECT, { + featureIds: [state.polygon.id], + }); + } + }; + + FreehandMode.fireCreate = function (polygon) { + this.map.fire(events.CREATE, { + features: [polygon.toGeoJSON()], + }); + }; + + FreehandMode.fireUpdate = function () { + this.map.fire(events.UPDATE, { + action: updateActions.MOVE, + features: this.getSelected().map((f) => f.toGeoJSON()), + }); + }; + + FreehandMode.simplify = function (polygon) { + if (!this.map.simplify_freehand) return; + + const tolerance = 1 / Math.pow(1.05, 10 * this.map.getZoom()); + const simplifiedCoords = simplifyGeometry( + polygon.coordinates[0], + tolerance, + ); + polygon.setCoordinates([simplifiedCoords]); + }; + + function simplifyGeometry(points, tolerance) { + if (points.length <= 2) return points; + + const sqTolerance = tolerance * tolerance; + const last = points.length - 1; + const simplified = [points[0]]; + simplifyDPStep(points, 0, last, sqTolerance, simplified); + simplified.push(points[last]); + + return simplified; + } + + function simplifyDPStep(points, first, last, sqTolerance, simplified) { + let maxSqDist = sqTolerance; + let index; + + for (let i = first + 1; i < last; i++) { + const sqDist = getSquareSegmentDistance( + points[i], + points[first], + points[last], + ); + if (sqDist > maxSqDist) { + index = i; + maxSqDist = sqDist; + } + } + + if (maxSqDist > sqTolerance) { + if (index - first > 1) + simplifyDPStep(points, first, index, sqTolerance, simplified); + simplified.push(points[index]); + if (last - index > 1) + simplifyDPStep(points, index, last, sqTolerance, simplified); + } + } + + function getSquareSegmentDistance(p, p1, p2) { + let x = p1[0], + y = p1[1]; + let dx = p2[0] - x, + dy = p2[1] - y; + + if (dx !== 0 || dy !== 0) { + const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy); + if (t > 1) { + x = p2[0]; + y = p2[1]; + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } + + dx = p[0] - x; + dy = p[1] - y; + + return dx * dx + dy * dy; + } + + FreehandMode.onStop = function (state) { + this.updateUIClasses({ mouse: cursors.NONE }); + this.activateUIButton(); + + // Enable map dragging + setTimeout(() => { + if (!this.map || !this.map.dragPan) return; + this.map.dragPan.enable(); + }, 0); + }; + + FreehandMode.toDisplayFeatures = function (state, geojson, display) { + const isActivePolygon = geojson.properties.id === state.polygon.id; + geojson.properties.active = isActivePolygon ? "true" : "false"; + if (!isActivePolygon) return display(geojson); + + // Only render the polygon if it has at least three points + if (geojson.geometry.coordinates[0].length < 3) return; + + const coordinateCount = geojson.geometry.coordinates[0].length; + + // If we have fewer than three coordinates, we need to create a LineString instead of a Polygon + if (coordinateCount < 3) { + const lineCoordinates = [ + [ + geojson.geometry.coordinates[0][0][0], + geojson.geometry.coordinates[0][0][1], + ], + [ + geojson.geometry.coordinates[0][1][0], + geojson.geometry.coordinates[0][1][1], + ], + ]; + return display({ + type: geojsonTypes.FEATURE, + properties: geojson.properties, + geometry: { + coordinates: lineCoordinates, + type: geojsonTypes.LINE_STRING, + }, + }); + } + + return display(geojson); + }; + + FreehandMode.onTrash = function (state) { + this.deleteFeature([state.polygon.id], { silent: true }); + this.changeMode(modes.SIMPLE_SELECT); + }; + + MapboxDraw.modes.draw_freehand = FreehandMode; +})(MapboxDraw); diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js new file mode 100644 index 0000000..16631aa --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js @@ -0,0 +1,3 @@ +!function(A){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=A();else if("function"==typeof define&&define.amd)define([],A);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).h3j_h3t=A()}}((function(){return function A(e,r,t){function i(o,a){if(!r[o]){if(!e[o]){var f="function"==typeof require&&require;if(!a&&f)return f(o,!0);if(n)return n(o,!0);var s=new Error("Cannot find module '"+o+"'");throw s.code="MODULE_NOT_FOUND",s}var u=r[o]={exports:{}};e[o][0].call(u.exports,(function(A){return i(e[o][1][A]||A)}),u,u.exports,A,e,r,t)}return r[o].exports}for(var n="function"==typeof require&&require,o=0;o>3}if(n--,1===i||2===i)o+=A.readSVarint(),a+=A.readSVarint(),1===i&&(e&&f.push(e),e=[]),e.push(new t(o,a));else{if(7!==i)throw new Error("unknown command "+i);e&&e.push(e[0].clone())}}return e&&f.push(e),f},i.prototype.bbox=function(){var A=this._pbf;A.pos=this._geometry;for(var e=A.readVarint()+A.pos,r=1,t=0,i=0,n=0,o=1/0,a=-1/0,f=1/0,s=-1/0;A.pos>3}if(t--,1===r||2===r)(i+=A.readSVarint())a&&(a=i),(n+=A.readSVarint())s&&(s=n);else if(7!==r)throw new Error("unknown command "+r)}return[o,f,a,s]},i.prototype.toGeoJSON=function(A,e,r){var t,n,a=this.extent*Math.pow(2,r),f=this.extent*A,s=this.extent*e,u=this.loadGeometry(),l=i.types[this.type];function h(A){for(var e=0;e>3;e=1===t?A.readString():2===t?A.readFloat():3===t?A.readDouble():4===t?A.readVarint64():5===t?A.readVarint():6===t?A.readSVarint():7===t?A.readBoolean():null}return e}(r))}e.exports=i,i.prototype.feature=function(A){if(A<0||A>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[A];var e=this._pbf.readVarint()+this._pbf.pos;return new t(this._pbf,e,this.extent,this._keys,this._values)}},{"./vectortilefeature.js":4}],6:[function(A,e,r){!function(A,t){"object"==typeof r&&void 0!==e?e.exports=t():A.geojsonvt=t()}(this,(function(){"use strict";function A(r,t,i,n){for(var o,a=n,f=i-t>>1,s=i-t,u=r[t],l=r[t+1],h=r[i],c=r[i+1],d=t+3;da)o=d,a=g;else if(g===a){var w=Math.abs(d-f);wn&&(o-t>3&&A(r,t,o,n),r[o+2]=a,i-o>3&&A(r,o,i,n))}function e(A,e,r,t,i,n){var o=i-r,a=n-t;if(0!==o||0!==a){var f=((A-r)*o+(e-t)*a)/(o*o+a*a);f>1?(r=i,t=n):f>0&&(r+=o*f,t+=a*f)}return(o=A-r)*o+(a=e-t)*a}function r(A,e,r,i){var n={id:void 0===A?null:A,type:e,geometry:r,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(A){var e=A.geometry,r=A.type;if("Point"===r||"MultiPoint"===r||"LineString"===r)t(A,e);else if("Polygon"===r||"MultiLineString"===r)for(var i=0;i0&&(a+=i?(n*h-l*o)/2:Math.sqrt(Math.pow(l-n,2)+Math.pow(h-o,2))),n=l,o=h}var c=r.length-3;r[2]=1,A(r,0,c,t),r[c+2]=1,r.size=Math.abs(a),r.start=0,r.end=r.size}function a(A,e,r,t){for(var i=0;i1?1:r}function u(A,e,t,i,n,o,a,f){if(i/=e,o>=(t/=e)&&a=i)return null;for(var s=[],u=0;u=t&&B=i)){var b=[];if("Point"===w||"MultiPoint"===w)l(g,b,t,i,n);else if("LineString"===w)h(g,b,t,i,n,!1,f.lineMetrics);else if("MultiLineString"===w)d(g,b,t,i,n,!1);else if("Polygon"===w)d(g,b,t,i,n,!0);else if("MultiPolygon"===w)for(var v=0;v=r&&o<=t&&(e.push(A[n]),e.push(A[n+1]),e.push(A[n+2]))}}function h(A,e,r,t,i,n,o){for(var a,f,s=c(A),u=0===i?w:p,l=A.start,h=0;hr&&(f=u(s,d,B,v,m,r),o&&(s.start=l+a*f)):k>t?M=r&&(f=u(s,d,B,v,m,r),Q=!0),M>t&&k<=t&&(f=u(s,d,B,v,m,t),Q=!0),!n&&Q&&(o&&(s.end=l+a*f),e.push(s),s=c(A)),o&&(l+=a)}var y=A.length-3;d=A[y],B=A[y+1],b=A[y+2],(k=0===i?d:B)>=r&&k<=t&&g(s,d,B,b),y=s.length-3,n&&y>=3&&(s[y]!==s[0]||s[y+1]!==s[1])&&g(s,s[0],s[1],s[2]),s.length&&e.push(s)}function c(A){var e=[];return e.size=A.size,e.start=A.start,e.end=A.end,e}function d(A,e,r,t,i,n){for(var o=0;oo.maxX&&(o.maxX=u),l>o.maxY&&(o.maxY=l)}return o}function M(A,e,r,t){var i=e.geometry,n=e.type,o=[];if("Point"===n||"MultiPoint"===n)for(var a=0;a0&&e.size<(i?o:t))r.numPoints+=e.length/3;else{for(var a=[],f=0;fo)&&(r.numSimplified++,a.push(e[f]),a.push(e[f+1])),r.numPoints++;i&&function(A,e){for(var r=0,t=0,i=A.length,n=i-2;t0===e)for(t=0,i=A.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(e.promoteId&&e.generateId)throw new Error("promoteId and generateId cannot be used together.");var t=function(A,e){var r=[];if("FeatureCollection"===A.type)for(var t=0;t1&&console.time("creation"),c=this.tiles[h]=k(A,e,r,t,f),this.tileCoords.push({z:e,x:r,y:t}),s)){s>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,r,t,c.numFeatures,c.numPoints,c.numSimplified),console.timeEnd("creation"));var d="z"+e;this.stats[d]=(this.stats[d]||0)+1,this.total++}if(c.source=A,i){if(e===f.maxZoom||e===i)continue;var g=1<1&&console.time("clipping");var w,p,B,b,v,m,M=.5*f.buffer/f.extent,Q=.5-M,y=.5+M,x=1+M;w=p=B=b=null,v=u(A,l,r-M,r+y,0,c.minX,c.maxX,f),m=u(A,l,r+Q,r+x,0,c.minX,c.maxX,f),A=null,v&&(w=u(v,l,t-M,t+y,1,c.minY,c.maxY,f),p=u(v,l,t+Q,t+x,1,c.minY,c.maxY,f),v=null),m&&(B=u(m,l,t-M,t+y,1,c.minY,c.maxY,f),b=u(m,l,t+Q,t+x,1,c.minY,c.maxY,f),m=null),s>1&&console.timeEnd("clipping"),a.push(w||[],e+1,2*r,2*t),a.push(p||[],e+1,2*r,2*t+1),a.push(B||[],e+1,2*r+1,2*t),a.push(b||[],e+1,2*r+1,2*t+1)}}},y.prototype.getTile=function(A,e,r){var t=this.options,i=t.extent,n=t.debug;if(A<0||A>24)return null;var o=1<1&&console.log("drilling down to z%d-%d-%d",A,e,r);for(var f,s=A,u=e,l=r;!f&&s>0;)s--,u=Math.floor(u/2),l=Math.floor(l/2),f=this.tiles[E(s,u,l)];return f&&f.source?(n>1&&console.log("found parent tile z%d-%d-%d",s,u,l),n>1&&console.time("drilling down"),this.splitTile(f.source,s,u,l,A,e,r),n>1&&console.timeEnd("drilling down"),this.tiles[a]?v(this.tiles[a],i):null):null},function(A,e){return new y(A,e)}}))},{}],7:[function(A,e,r){var t=function(A){var e,r=void 0!==(A=A||{})?A:{},t={};for(e in r)r.hasOwnProperty(e)&&(t[e]=r[e]);var i,n=[],o="";document.currentScript&&(o=document.currentScript.src),o=0!==o.indexOf("blob:")?o.substr(0,o.lastIndexOf("/")+1):"",i=function(A,e,r){var t=new XMLHttpRequest;t.open("GET",A,!0),t.responseType="arraybuffer",t.onload=function(){if(200==t.status||0==t.status&&t.response)e(t.response);else{var i=J(A);i?e(i.buffer):r()}},t.onerror=r,t.send(null)};var a=r.print||console.log.bind(console),f=r.printErr||console.warn.bind(console);for(e in t)t.hasOwnProperty(e)&&(r[e]=t[e]);t=null,r.arguments&&(n=r.arguments);var s=0,u=function(){return s};var l=!1;function h(A){var e,t=r["_"+A];return e="Cannot call unknown function "+A+", make sure it is exported",t||fA("Assertion failed: "+e),t}function c(A,e,r,t,i){var n={string:function(A){var e=0;if(null!=A&&0!==A){var r=1+(A.length<<2);(function(A,e,r){(function(A,e,r,t){if(!(t>0))return 0;for(var i=r,n=r+t-1,o=0;o=55296&&a<=57343)a=65536+((1023&a)<<10)|1023&A.charCodeAt(++o);if(a<=127){if(r>=n)break;e[r++]=a}else if(a<=2047){if(r+1>=n)break;e[r++]=192|a>>6,e[r++]=128|63&a}else if(a<=65535){if(r+2>=n)break;e[r++]=224|a>>12,e[r++]=128|a>>6&63,e[r++]=128|63&a}else{if(r+3>=n)break;e[r++]=240|a>>18,e[r++]=128|a>>12&63,e[r++]=128|a>>6&63,e[r++]=128|63&a}}e[r]=0})(A,B,e,r)})(A,e=AA(r),r)}return e},array:function(A){var e=AA(A.length);return function(A,e){p.set(A,e)}(A,e),e}};var o=h(A),a=[],f=0;if(t)for(var s=0;s=t);)++i;if(i-e>16&&A.subarray&&d)return d.decode(A.subarray(e,i));for(var n="";e>10,56320|1023&s)}}else n+=String.fromCharCode((31&o)<<6|a)}else n+=String.fromCharCode(o)}return n}(B,A,e):""}var w,p,B,b,v,m,k;"undefined"!=typeof TextDecoder&&new TextDecoder("utf-16le");function M(A,e){return A%e>0&&(A+=e-A%e),A}function Q(A){w=A,r.HEAP8=p=new Int8Array(A),r.HEAP16=b=new Int16Array(A),r.HEAP32=v=new Int32Array(A),r.HEAPU8=B=new Uint8Array(A),r.HEAPU16=new Uint16Array(A),r.HEAPU32=new Uint32Array(A),r.HEAPF32=m=new Float32Array(A),r.HEAPF64=k=new Float64Array(A)}var y=r.TOTAL_MEMORY||33554432;function E(A){for(;A.length>0;){var e=A.shift();if("function"!=typeof e){var t=e.func;"number"==typeof t?void 0===e.arg?r.dynCall_v(t):r.dynCall_vi(t,e.arg):t(void 0===e.arg?null:e.arg)}else e()}}y=(w=r.buffer?r.buffer:new ArrayBuffer(y)).byteLength,Q(w),v[6004]=5266928;var x=[],D=[],_=[],I=[];var F=Math.abs,C=Math.ceil,P=Math.floor,U=Math.min,G=0,S=null,T=null;r.preloadedImages={},r.preloadedAudios={};var V,H,R=null,L="data:application/octet-stream;base64,";function z(A){return String.prototype.startsWith?A.startsWith(L):0===A.indexOf(L)}R="data:application/octet-stream;base64,AAAAAAAAAAACAAAAAwAAAAEAAAAFAAAABAAAAAYAAAAAAAAAAAAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAYAAAABAAAABAAAAAMAAAAGAAAABQAAAAIAAAAAAAAAAgAAAAMAAAABAAAABAAAAAYAAAAAAAAABQAAAAMAAAAGAAAABAAAAAUAAAAAAAAAAQAAAAIAAAAEAAAABQAAAAYAAAAAAAAAAgAAAAMAAAABAAAABQAAAAIAAAAAAAAAAQAAAAMAAAAGAAAABAAAAAYAAAAAAAAABQAAAAIAAAABAAAABAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAgAAAAMAAAAAAAAAAAAAAAIAAAAAAAAAAQAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAABgAAAAAAAAAFAAAAAAAAAAAAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAIAAAAAAAAABgAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAgAAAAAAAAAAAAAABgAAAAAAAAADAAAAAgAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAUAAAAEAAAAAAAAAAEAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAEAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAUAAAACAAAABAAAAAMAAAAIAAAAAQAAAAcAAAAGAAAACQAAAAAAAAADAAAAAgAAAAIAAAAGAAAACgAAAAsAAAAAAAAAAQAAAAUAAAADAAAADQAAAAEAAAAHAAAABAAAAAwAAAAAAAAABAAAAH8AAAAPAAAACAAAAAMAAAAAAAAADAAAAAUAAAACAAAAEgAAAAoAAAAIAAAAAAAAABAAAAAGAAAADgAAAAsAAAARAAAAAQAAAAkAAAACAAAABwAAABUAAAAJAAAAEwAAAAMAAAANAAAAAQAAAAgAAAAFAAAAFgAAABAAAAAEAAAAAAAAAA8AAAAJAAAAEwAAAA4AAAAUAAAAAQAAAAcAAAAGAAAACgAAAAsAAAAYAAAAFwAAAAUAAAACAAAAEgAAAAsAAAARAAAAFwAAABkAAAACAAAABgAAAAoAAAAMAAAAHAAAAA0AAAAaAAAABAAAAA8AAAADAAAADQAAABoAAAAVAAAAHQAAAAMAAAAMAAAABwAAAA4AAAB/AAAAEQAAABsAAAAJAAAAFAAAAAYAAAAPAAAAFgAAABwAAAAfAAAABAAAAAgAAAAMAAAAEAAAABIAAAAhAAAAHgAAAAgAAAAFAAAAFgAAABEAAAALAAAADgAAAAYAAAAjAAAAGQAAABsAAAASAAAAGAAAAB4AAAAgAAAABQAAAAoAAAAQAAAAEwAAACIAAAAUAAAAJAAAAAcAAAAVAAAACQAAABQAAAAOAAAAEwAAAAkAAAAoAAAAGwAAACQAAAAVAAAAJgAAABMAAAAiAAAADQAAAB0AAAAHAAAAFgAAABAAAAApAAAAIQAAAA8AAAAIAAAAHwAAABcAAAAYAAAACwAAAAoAAAAnAAAAJQAAABkAAAAYAAAAfwAAACAAAAAlAAAACgAAABcAAAASAAAAGQAAABcAAAARAAAACwAAAC0AAAAnAAAAIwAAABoAAAAqAAAAHQAAACsAAAAMAAAAHAAAAA0AAAAbAAAAKAAAACMAAAAuAAAADgAAABQAAAARAAAAHAAAAB8AAAAqAAAALAAAAAwAAAAPAAAAGgAAAB0AAAArAAAAJgAAAC8AAAANAAAAGgAAABUAAAAeAAAAIAAAADAAAAAyAAAAEAAAABIAAAAhAAAAHwAAACkAAAAsAAAANQAAAA8AAAAWAAAAHAAAACAAAAAeAAAAGAAAABIAAAA0AAAAMgAAACUAAAAhAAAAHgAAADEAAAAwAAAAFgAAABAAAAApAAAAIgAAABMAAAAmAAAAFQAAADYAAAAkAAAAMwAAACMAAAAuAAAALQAAADgAAAARAAAAGwAAABkAAAAkAAAAFAAAACIAAAATAAAANwAAACgAAAA2AAAAJQAAACcAAAA0AAAAOQAAABgAAAAXAAAAIAAAACYAAAB/AAAAIgAAADMAAAAdAAAALwAAABUAAAAnAAAAJQAAABkAAAAXAAAAOwAAADkAAAAtAAAAKAAAABsAAAAkAAAAFAAAADwAAAAuAAAANwAAACkAAAAxAAAANQAAAD0AAAAWAAAAIQAAAB8AAAAqAAAAOgAAACsAAAA+AAAAHAAAACwAAAAaAAAAKwAAAD4AAAAvAAAAQAAAABoAAAAqAAAAHQAAACwAAAA1AAAAOgAAAEEAAAAcAAAAHwAAACoAAAAtAAAAJwAAACMAAAAZAAAAPwAAADsAAAA4AAAALgAAADwAAAA4AAAARAAAABsAAAAoAAAAIwAAAC8AAAAmAAAAKwAAAB0AAABFAAAAMwAAAEAAAAAwAAAAMQAAAB4AAAAhAAAAQwAAAEIAAAAyAAAAMQAAAH8AAAA9AAAAQgAAACEAAAAwAAAAKQAAADIAAAAwAAAAIAAAAB4AAABGAAAAQwAAADQAAAAzAAAARQAAADYAAABHAAAAJgAAAC8AAAAiAAAANAAAADkAAABGAAAASgAAACAAAAAlAAAAMgAAADUAAAA9AAAAQQAAAEsAAAAfAAAAKQAAACwAAAA2AAAARwAAADcAAABJAAAAIgAAADMAAAAkAAAANwAAACgAAAA2AAAAJAAAAEgAAAA8AAAASQAAADgAAABEAAAAPwAAAE0AAAAjAAAALgAAAC0AAAA5AAAAOwAAAEoAAABOAAAAJQAAACcAAAA0AAAAOgAAAH8AAAA+AAAATAAAACwAAABBAAAAKgAAADsAAAA/AAAATgAAAE8AAAAnAAAALQAAADkAAAA8AAAASAAAAEQAAABQAAAAKAAAADcAAAAuAAAAPQAAADUAAAAxAAAAKQAAAFEAAABLAAAAQgAAAD4AAAArAAAAOgAAACoAAABSAAAAQAAAAEwAAAA/AAAAfwAAADgAAAAtAAAATwAAADsAAABNAAAAQAAAAC8AAAA+AAAAKwAAAFQAAABFAAAAUgAAAEEAAAA6AAAANQAAACwAAABWAAAATAAAAEsAAABCAAAAQwAAAFEAAABVAAAAMQAAADAAAAA9AAAAQwAAAEIAAAAyAAAAMAAAAFcAAABVAAAARgAAAEQAAAA4AAAAPAAAAC4AAABaAAAATQAAAFAAAABFAAAAMwAAAEAAAAAvAAAAWQAAAEcAAABUAAAARgAAAEMAAAA0AAAAMgAAAFMAAABXAAAASgAAAEcAAABZAAAASQAAAFsAAAAzAAAARQAAADYAAABIAAAAfwAAAEkAAAA3AAAAUAAAADwAAABYAAAASQAAAFsAAABIAAAAWAAAADYAAABHAAAANwAAAEoAAABOAAAAUwAAAFwAAAA0AAAAOQAAAEYAAABLAAAAQQAAAD0AAAA1AAAAXgAAAFYAAABRAAAATAAAAFYAAABSAAAAYAAAADoAAABBAAAAPgAAAE0AAAA/AAAARAAAADgAAABdAAAATwAAAFoAAABOAAAASgAAADsAAAA5AAAAXwAAAFwAAABPAAAATwAAAE4AAAA/AAAAOwAAAF0AAABfAAAATQAAAFAAAABEAAAASAAAADwAAABjAAAAWgAAAFgAAABRAAAAVQAAAF4AAABlAAAAPQAAAEIAAABLAAAAUgAAAGAAAABUAAAAYgAAAD4AAABMAAAAQAAAAFMAAAB/AAAASgAAAEYAAABkAAAAVwAAAFwAAABUAAAARQAAAFIAAABAAAAAYQAAAFkAAABiAAAAVQAAAFcAAABlAAAAZgAAAEIAAABDAAAAUQAAAFYAAABMAAAASwAAAEEAAABoAAAAYAAAAF4AAABXAAAAUwAAAGYAAABkAAAAQwAAAEYAAABVAAAAWAAAAEgAAABbAAAASQAAAGMAAABQAAAAaQAAAFkAAABhAAAAWwAAAGcAAABFAAAAVAAAAEcAAABaAAAATQAAAFAAAABEAAAAagAAAF0AAABjAAAAWwAAAEkAAABZAAAARwAAAGkAAABYAAAAZwAAAFwAAABTAAAATgAAAEoAAABsAAAAZAAAAF8AAABdAAAATwAAAFoAAABNAAAAbQAAAF8AAABqAAAAXgAAAFYAAABRAAAASwAAAGsAAABoAAAAZQAAAF8AAABcAAAATwAAAE4AAABtAAAAbAAAAF0AAABgAAAAaAAAAGIAAABuAAAATAAAAFYAAABSAAAAYQAAAH8AAABiAAAAVAAAAGcAAABZAAAAbwAAAGIAAABuAAAAYQAAAG8AAABSAAAAYAAAAFQAAABjAAAAUAAAAGkAAABYAAAAagAAAFoAAABxAAAAZAAAAGYAAABTAAAAVwAAAGwAAAByAAAAXAAAAGUAAABmAAAAawAAAHAAAABRAAAAVQAAAF4AAABmAAAAZQAAAFcAAABVAAAAcgAAAHAAAABkAAAAZwAAAFsAAABhAAAAWQAAAHQAAABpAAAAbwAAAGgAAABrAAAAbgAAAHMAAABWAAAAXgAAAGAAAABpAAAAWAAAAGcAAABbAAAAcQAAAGMAAAB0AAAAagAAAF0AAABjAAAAWgAAAHUAAABtAAAAcQAAAGsAAAB/AAAAZQAAAF4AAABzAAAAaAAAAHAAAABsAAAAZAAAAF8AAABcAAAAdgAAAHIAAABtAAAAbQAAAGwAAABdAAAAXwAAAHUAAAB2AAAAagAAAG4AAABiAAAAaAAAAGAAAAB3AAAAbwAAAHMAAABvAAAAYQAAAG4AAABiAAAAdAAAAGcAAAB3AAAAcAAAAGsAAABmAAAAZQAAAHgAAABzAAAAcgAAAHEAAABjAAAAdAAAAGkAAAB1AAAAagAAAHkAAAByAAAAcAAAAGQAAABmAAAAdgAAAHgAAABsAAAAcwAAAG4AAABrAAAAaAAAAHgAAAB3AAAAcAAAAHQAAABnAAAAdwAAAG8AAABxAAAAaQAAAHkAAAB1AAAAfwAAAG0AAAB2AAAAcQAAAHkAAABqAAAAdgAAAHgAAABsAAAAcgAAAHUAAAB5AAAAbQAAAHcAAABvAAAAcwAAAG4AAAB5AAAAdAAAAHgAAAB4AAAAcwAAAHIAAABwAAAAeQAAAHcAAAB2AAAAeQAAAHQAAAB4AAAAdwAAAHUAAABxAAAAdgAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAEAAAAFAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAIAAAAFAAAAAQAAAAAAAAD/////AQAAAAAAAAADAAAABAAAAAIAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAUAAAABAAAAAAAAAAAAAAABAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAAFAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAQAAAAFAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAADAAAAAAAAAAAAAAABAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAABAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAADAAAABQAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAADAAAAAAAAAAAAAAABAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAADAAAAAQAAAAAAAAABAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAMAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAADAAAABQAAAAEAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAEAAAABQAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAgAAAAUAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAABQAAAAAAAAAAAAAABQAAAAUAAAAAAAAAAAAAAP////8BAAAAAAAAAAMAAAAEAAAAAgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAABQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAABQAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAQAAAP//////////AQAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAIAAAAAAAAAAAAAAAEAAAACAAAABgAAAAQAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAABwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAoAAAACAAAAAAAAAAAAAAABAAAAAQAAAAUAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAsAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAIAAAAAAAAAAAAAAAEAAAADAAAABwAAAAYAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAHAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAABAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAOAAAAAgAAAAAAAAAAAAAAAQAAAAAAAAAJAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAwAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAgAAAAAAAAAAAAAAAQAAAAQAAAAIAAAACgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAsAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAACAAAAAAAAAAAAAAABAAAACwAAAA8AAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA4AAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAgAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAFAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAACAAAAAAAAAAAAAAABAAAADAAAABAAAAAMAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAEAAAAKAAAAEwAAAAgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAADwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAJAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAgAAAAAAAAAAAAAAAQAAAA0AAAARAAAADQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAABEAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAADQAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAIAAAAAAAAAAAAAAAEAAAAOAAAAEgAAAA8AAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAPAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAABIAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAEQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABMAAAACAAAAAAAAAAAAAAABAAAA//////////8TAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAASAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABIAAAAAAAAAGAAAAAAAAAAhAAAAAAAAAB4AAAAAAAAAIAAAAAMAAAAxAAAAAQAAADAAAAADAAAAMgAAAAMAAAAIAAAAAAAAAAUAAAAFAAAACgAAAAUAAAAWAAAAAAAAABAAAAAAAAAAEgAAAAAAAAApAAAAAQAAACEAAAAAAAAAHgAAAAAAAAAEAAAAAAAAAAAAAAAFAAAAAgAAAAUAAAAPAAAAAQAAAAgAAAAAAAAABQAAAAUAAAAfAAAAAQAAABYAAAAAAAAAEAAAAAAAAAACAAAAAAAAAAYAAAAAAAAADgAAAAAAAAAKAAAAAAAAAAsAAAAAAAAAEQAAAAMAAAAYAAAAAQAAABcAAAADAAAAGQAAAAMAAAAAAAAAAAAAAAEAAAAFAAAACQAAAAUAAAAFAAAAAAAAAAIAAAAAAAAABgAAAAAAAAASAAAAAQAAAAoAAAAAAAAACwAAAAAAAAAEAAAAAQAAAAMAAAAFAAAABwAAAAUAAAAIAAAAAQAAAAAAAAAAAAAAAQAAAAUAAAAQAAAAAQAAAAUAAAAAAAAAAgAAAAAAAAAHAAAAAAAAABUAAAAAAAAAJgAAAAAAAAAJAAAAAAAAABMAAAAAAAAAIgAAAAMAAAAOAAAAAQAAABQAAAADAAAAJAAAAAMAAAADAAAAAAAAAA0AAAAFAAAAHQAAAAUAAAABAAAAAAAAAAcAAAAAAAAAFQAAAAAAAAAGAAAAAQAAAAkAAAAAAAAAEwAAAAAAAAAEAAAAAgAAAAwAAAAFAAAAGgAAAAUAAAAAAAAAAQAAAAMAAAAAAAAADQAAAAUAAAACAAAAAQAAAAEAAAAAAAAABwAAAAAAAAAaAAAAAAAAACoAAAAAAAAAOgAAAAAAAAAdAAAAAAAAACsAAAAAAAAAPgAAAAMAAAAmAAAAAQAAAC8AAAADAAAAQAAAAAMAAAAMAAAAAAAAABwAAAAFAAAALAAAAAUAAAANAAAAAAAAABoAAAAAAAAAKgAAAAAAAAAVAAAAAQAAAB0AAAAAAAAAKwAAAAAAAAAEAAAAAwAAAA8AAAAFAAAAHwAAAAUAAAADAAAAAQAAAAwAAAAAAAAAHAAAAAUAAAAHAAAAAQAAAA0AAAAAAAAAGgAAAAAAAAAfAAAAAAAAACkAAAAAAAAAMQAAAAAAAAAsAAAAAAAAADUAAAAAAAAAPQAAAAMAAAA6AAAAAQAAAEEAAAADAAAASwAAAAMAAAAPAAAAAAAAABYAAAAFAAAAIQAAAAUAAAAcAAAAAAAAAB8AAAAAAAAAKQAAAAAAAAAqAAAAAQAAACwAAAAAAAAANQAAAAAAAAAEAAAABAAAAAgAAAAFAAAAEAAAAAUAAAAMAAAAAQAAAA8AAAAAAAAAFgAAAAUAAAAaAAAAAQAAABwAAAAAAAAAHwAAAAAAAAAyAAAAAAAAADAAAAAAAAAAMQAAAAMAAAAgAAAAAAAAAB4AAAADAAAAIQAAAAMAAAAYAAAAAwAAABIAAAADAAAAEAAAAAMAAABGAAAAAAAAAEMAAAAAAAAAQgAAAAMAAAA0AAAAAwAAADIAAAAAAAAAMAAAAAAAAAAlAAAAAwAAACAAAAAAAAAAHgAAAAMAAABTAAAAAAAAAFcAAAADAAAAVQAAAAMAAABKAAAAAwAAAEYAAAAAAAAAQwAAAAAAAAA5AAAAAQAAADQAAAADAAAAMgAAAAAAAAAZAAAAAAAAABcAAAAAAAAAGAAAAAMAAAARAAAAAAAAAAsAAAADAAAACgAAAAMAAAAOAAAAAwAAAAYAAAADAAAAAgAAAAMAAAAtAAAAAAAAACcAAAAAAAAAJQAAAAMAAAAjAAAAAwAAABkAAAAAAAAAFwAAAAAAAAAbAAAAAwAAABEAAAAAAAAACwAAAAMAAAA/AAAAAAAAADsAAAADAAAAOQAAAAMAAAA4AAAAAwAAAC0AAAAAAAAAJwAAAAAAAAAuAAAAAwAAACMAAAADAAAAGQAAAAAAAAAkAAAAAAAAABQAAAAAAAAADgAAAAMAAAAiAAAAAAAAABMAAAADAAAACQAAAAMAAAAmAAAAAwAAABUAAAADAAAABwAAAAMAAAA3AAAAAAAAACgAAAAAAAAAGwAAAAMAAAA2AAAAAwAAACQAAAAAAAAAFAAAAAAAAAAzAAAAAwAAACIAAAAAAAAAEwAAAAMAAABIAAAAAAAAADwAAAADAAAALgAAAAMAAABJAAAAAwAAADcAAAAAAAAAKAAAAAAAAABHAAAAAwAAADYAAAADAAAAJAAAAAAAAABAAAAAAAAAAC8AAAAAAAAAJgAAAAMAAAA+AAAAAAAAACsAAAADAAAAHQAAAAMAAAA6AAAAAwAAACoAAAADAAAAGgAAAAMAAABUAAAAAAAAAEUAAAAAAAAAMwAAAAMAAABSAAAAAwAAAEAAAAAAAAAALwAAAAAAAABMAAAAAwAAAD4AAAAAAAAAKwAAAAMAAABhAAAAAAAAAFkAAAADAAAARwAAAAMAAABiAAAAAwAAAFQAAAAAAAAARQAAAAAAAABgAAAAAwAAAFIAAAADAAAAQAAAAAAAAABLAAAAAAAAAEEAAAAAAAAAOgAAAAMAAAA9AAAAAAAAADUAAAADAAAALAAAAAMAAAAxAAAAAwAAACkAAAADAAAAHwAAAAMAAABeAAAAAAAAAFYAAAAAAAAATAAAAAMAAABRAAAAAwAAAEsAAAAAAAAAQQAAAAAAAABCAAAAAwAAAD0AAAAAAAAANQAAAAMAAABrAAAAAAAAAGgAAAADAAAAYAAAAAMAAABlAAAAAwAAAF4AAAAAAAAAVgAAAAAAAABVAAAAAwAAAFEAAAADAAAASwAAAAAAAAA5AAAAAAAAADsAAAAAAAAAPwAAAAMAAABKAAAAAAAAAE4AAAADAAAATwAAAAMAAABTAAAAAwAAAFwAAAADAAAAXwAAAAMAAAAlAAAAAAAAACcAAAADAAAALQAAAAMAAAA0AAAAAAAAADkAAAAAAAAAOwAAAAAAAABGAAAAAwAAAEoAAAAAAAAATgAAAAMAAAAYAAAAAAAAABcAAAADAAAAGQAAAAMAAAAgAAAAAwAAACUAAAAAAAAAJwAAAAMAAAAyAAAAAwAAADQAAAAAAAAAOQAAAAAAAAAuAAAAAAAAADwAAAAAAAAASAAAAAMAAAA4AAAAAAAAAEQAAAADAAAAUAAAAAMAAAA/AAAAAwAAAE0AAAADAAAAWgAAAAMAAAAbAAAAAAAAACgAAAADAAAANwAAAAMAAAAjAAAAAAAAAC4AAAAAAAAAPAAAAAAAAAAtAAAAAwAAADgAAAAAAAAARAAAAAMAAAAOAAAAAAAAABQAAAADAAAAJAAAAAMAAAARAAAAAwAAABsAAAAAAAAAKAAAAAMAAAAZAAAAAwAAACMAAAAAAAAALgAAAAAAAABHAAAAAAAAAFkAAAAAAAAAYQAAAAMAAABJAAAAAAAAAFsAAAADAAAAZwAAAAMAAABIAAAAAwAAAFgAAAADAAAAaQAAAAMAAAAzAAAAAAAAAEUAAAADAAAAVAAAAAMAAAA2AAAAAAAAAEcAAAAAAAAAWQAAAAAAAAA3AAAAAwAAAEkAAAAAAAAAWwAAAAMAAAAmAAAAAAAAAC8AAAADAAAAQAAAAAMAAAAiAAAAAwAAADMAAAAAAAAARQAAAAMAAAAkAAAAAwAAADYAAAAAAAAARwAAAAAAAABgAAAAAAAAAGgAAAAAAAAAawAAAAMAAABiAAAAAAAAAG4AAAADAAAAcwAAAAMAAABhAAAAAwAAAG8AAAADAAAAdwAAAAMAAABMAAAAAAAAAFYAAAADAAAAXgAAAAMAAABSAAAAAAAAAGAAAAAAAAAAaAAAAAAAAABUAAAAAwAAAGIAAAAAAAAAbgAAAAMAAAA6AAAAAAAAAEEAAAADAAAASwAAAAMAAAA+AAAAAwAAAEwAAAAAAAAAVgAAAAMAAABAAAAAAwAAAFIAAAAAAAAAYAAAAAAAAABVAAAAAAAAAFcAAAAAAAAAUwAAAAMAAABlAAAAAAAAAGYAAAADAAAAZAAAAAMAAABrAAAAAwAAAHAAAAADAAAAcgAAAAMAAABCAAAAAAAAAEMAAAADAAAARgAAAAMAAABRAAAAAAAAAFUAAAAAAAAAVwAAAAAAAABeAAAAAwAAAGUAAAAAAAAAZgAAAAMAAAAxAAAAAAAAADAAAAADAAAAMgAAAAMAAAA9AAAAAwAAAEIAAAAAAAAAQwAAAAMAAABLAAAAAwAAAFEAAAAAAAAAVQAAAAAAAABfAAAAAAAAAFwAAAAAAAAAUwAAAAAAAABPAAAAAAAAAE4AAAAAAAAASgAAAAMAAAA/AAAAAQAAADsAAAADAAAAOQAAAAMAAABtAAAAAAAAAGwAAAAAAAAAZAAAAAUAAABdAAAAAQAAAF8AAAAAAAAAXAAAAAAAAABNAAAAAQAAAE8AAAAAAAAATgAAAAAAAAB1AAAABAAAAHYAAAAFAAAAcgAAAAUAAABqAAAAAQAAAG0AAAAAAAAAbAAAAAAAAABaAAAAAQAAAF0AAAABAAAAXwAAAAAAAABaAAAAAAAAAE0AAAAAAAAAPwAAAAAAAABQAAAAAAAAAEQAAAAAAAAAOAAAAAMAAABIAAAAAQAAADwAAAADAAAALgAAAAMAAABqAAAAAAAAAF0AAAAAAAAATwAAAAUAAABjAAAAAQAAAFoAAAAAAAAATQAAAAAAAABYAAAAAQAAAFAAAAAAAAAARAAAAAAAAAB1AAAAAwAAAG0AAAAFAAAAXwAAAAUAAABxAAAAAQAAAGoAAAAAAAAAXQAAAAAAAABpAAAAAQAAAGMAAAABAAAAWgAAAAAAAABpAAAAAAAAAFgAAAAAAAAASAAAAAAAAABnAAAAAAAAAFsAAAAAAAAASQAAAAMAAABhAAAAAQAAAFkAAAADAAAARwAAAAMAAABxAAAAAAAAAGMAAAAAAAAAUAAAAAUAAAB0AAAAAQAAAGkAAAAAAAAAWAAAAAAAAABvAAAAAQAAAGcAAAAAAAAAWwAAAAAAAAB1AAAAAgAAAGoAAAAFAAAAWgAAAAUAAAB5AAAAAQAAAHEAAAAAAAAAYwAAAAAAAAB3AAAAAQAAAHQAAAABAAAAaQAAAAAAAAB3AAAAAAAAAG8AAAAAAAAAYQAAAAAAAABzAAAAAAAAAG4AAAAAAAAAYgAAAAMAAABrAAAAAQAAAGgAAAADAAAAYAAAAAMAAAB5AAAAAAAAAHQAAAAAAAAAZwAAAAUAAAB4AAAAAQAAAHcAAAAAAAAAbwAAAAAAAABwAAAAAQAAAHMAAAAAAAAAbgAAAAAAAAB1AAAAAQAAAHEAAAAFAAAAaQAAAAUAAAB2AAAAAQAAAHkAAAAAAAAAdAAAAAAAAAByAAAAAQAAAHgAAAABAAAAdwAAAAAAAAByAAAAAAAAAHAAAAAAAAAAawAAAAAAAABkAAAAAAAAAGYAAAAAAAAAZQAAAAMAAABTAAAAAQAAAFcAAAADAAAAVQAAAAMAAAB2AAAAAAAAAHgAAAAAAAAAcwAAAAUAAABsAAAAAQAAAHIAAAAAAAAAcAAAAAAAAABcAAAAAQAAAGQAAAAAAAAAZgAAAAAAAAB1AAAAAAAAAHkAAAAFAAAAdwAAAAUAAABtAAAAAQAAAHYAAAAAAAAAeAAAAAAAAABfAAAAAQAAAGwAAAABAAAAcgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAEAAAABAAAAAAAAAAAAAAABAAAAAAAAAAEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAB+ogX28rbpPxqumpJv+fM/165tC4ns9D+XaEnTqUsEQFrOtNlC4PA/3U+0XG6P9b9TdUUBxTTjP4PUp8ex1ty/B1rD/EN43z+lcDi6LLrZP/a45NWEHMY/oJ5ijLDZ+j/xw3rjxWPjP2B8A46ioQdAotff3wla2z+FMSpA1jj+v6b5Y1mtPbS/cIu8K0F457/2esiyJpDNv98k5Ts2NeA/pvljWa09tD88ClUJ60MDQPZ6yLImkM0/4ONKxa0UBcD2uOTVhBzGv5G7JRxGave/8cN648Vj47+HCwtkjAXIv6LX398JWtu/qyheaCAL9D9TdUUBxTTjv4gyTxslhwVAB1rD/EN4378EH/28teoFwH6iBfbytum/F6ztFYdK/r/Xrm0Liez0vwcS6wNGWeO/Ws602ULg8L9TCtRLiLT8P8pi5RexJsw/BlIKPVwR5T95Wyu0/QjnP5PjoT7YYcu/mBhKZ6zrwj8wRYS7NebuP3qW6geh+Ls/SLrixebL3r+pcyymN9XrPwmkNHp7xec/GWNMZVAA17+82s+x2BLiPwn2ytbJ9ek/LgEH1sMS1j8yp/2LhTfeP+SnWwtQBbu/d38gkp5X7z8ytsuHaADGPzUYObdf1+m/7IauECWhwz+cjSACjzniP76Z+wUhN9K/1+GEKzup67+/GYr/04baPw6idWOvsuc/ZedTWsRa5b/EJQOuRzi0v/OncYhHPes/h49PixY53j+i8wWfC03Nvw2idWOvsue/ZedTWsRa5T/EJQOuRzi0P/KncYhHPeu/iY9PixY53r+i8wWfC03NP9anWwtQBbs/d38gkp5X778ytsuHaADGvzUYObdf1+k/74auECWhw7+cjSACjzniv8CZ+wUhN9I/1uGEKzup6z+/GYr/04bavwmkNHp7xee/F2NMZVAA1z+82s+x2BLivwr2ytbJ9em/KwEH1sMS1r8yp/2LhTfev81i5RexJsy/BlIKPVwR5b95Wyu0/Qjnv5DjoT7YYcs/nBhKZ6zrwr8wRYS7Nebuv3OW6geh+Lu/SLrixebL3j+pcyymN9Xrv8rHIFfWehZAMBwUdlo0DECTUc17EOb2PxpVB1SWChdAzjbhb9pTDUDQhmdvECX5P9FlMKCC9+g/IIAzjELgE0DajDngMv8GQFhWDmDPjNs/y1guLh96EkAxPi8k7DIEQJCc4URlhRhA3eLKKLwkEECqpNAyTBD/P6xpjXcDiwVAFtl//cQm4z+Ibt3XKiYTQM7mCLUb3QdAoM1t8yVv7D8aLZv2Nk8UQEAJPV5nQwxAtSsfTCoE9z9TPjXLXIIWQBVanC5W9AtAYM3d7Adm9j++5mQz1FoWQBUThyaVBghAwH5muQsV7T89Q1qv82MUQJoWGOfNuBdAzrkClkmwDkDQjKq77t37Py+g0dtitsE/ZwAMTwVPEUBojepluNwBQGYbtuW+t9w/HNWIJs6MEkDTNuQUSlgEQKxktPP5TcQ/ixbLB8JjEUCwuWjXMQYCQAS/R09FkRdAowpiZjhhDkB7LmlczD/7P01iQmhhsAVAnrtTwDy84z/Z6jfQ2TgTQChOCXMnWwpAhrW3daoz8z/HYJvVPI4VQLT3ik5FcA5Angi7LOZd+z+NNVzDy5gXQBXdvVTFUA1AYNMgOeYe+T8+qHXGCwkXQKQTOKwa5AJA8gFVoEMW0T+FwzJyttIRQAEAAAD/////BwAAAP////8xAAAA/////1cBAAD/////YQkAAP////+nQQAA/////5HLAQD/////95AMAP/////B9lcAAAAAAAAAAAAAAAAAAgAAAP////8OAAAA/////2IAAAD/////rgIAAP/////CEgAA/////06DAAD/////IpcDAP/////uIRkA/////4LtrwAAAAAAAAAAAAAAAAAAAAAAAgAAAP//////////AQAAAAMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////wIAAAD//////////wEAAAAAAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA/////////////////////wEAAAD///////////////8CAAAA////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD///////////////////////////////8CAAAA////////////////AQAAAP////////////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAAAQAAAP//////////AgAAAP//////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAAEAAAD//////////wIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAgAAAAAAAAACAAAAAQAAAAEAAAACAAAAAgAAAAAAAAAFAAAABQAAAAAAAAACAAAAAgAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAABAAAAAgAAAAIAAAACAAAAAAAAAAUAAAAGAAAAAAAAAAIAAAACAAAAAwAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAIAAAAAAAAAAgAAAAEAAAADAAAAAgAAAAIAAAAAAAAABQAAAAcAAAAAAAAAAgAAAAIAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAgAAAAAAAAACAAAAAQAAAAQAAAACAAAAAgAAAAAAAAAFAAAACAAAAAAAAAACAAAAAgAAAAMAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAACAAAAAAAAAAIAAAABAAAAAAAAAAIAAAACAAAAAAAAAAUAAAAJAAAAAAAAAAIAAAACAAAAAwAAAAUAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAIAAAACAAAAAAAAAAMAAAAOAAAAAgAAAAAAAAACAAAAAwAAAAAAAAAAAAAAAgAAAAIAAAADAAAABgAAAAAAAAAAAAAAAAAAAAAAAAALAAAAAgAAAAIAAAAAAAAAAwAAAAoAAAACAAAAAAAAAAIAAAADAAAAAQAAAAAAAAACAAAAAgAAAAMAAAAHAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAACAAAAAgAAAAAAAAADAAAACwAAAAIAAAAAAAAAAgAAAAMAAAACAAAAAAAAAAIAAAACAAAAAwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADQAAAAIAAAACAAAAAAAAAAMAAAAMAAAAAgAAAAAAAAACAAAAAwAAAAMAAAAAAAAAAgAAAAIAAAADAAAACQAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAgAAAAIAAAAAAAAAAwAAAA0AAAACAAAAAAAAAAIAAAADAAAABAAAAAAAAAACAAAAAgAAAAMAAAAKAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAACAAAAAgAAAAAAAAADAAAABgAAAAIAAAAAAAAAAgAAAAMAAAAPAAAAAAAAAAIAAAACAAAAAwAAAAsAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAIAAAACAAAAAAAAAAMAAAAHAAAAAgAAAAAAAAACAAAAAwAAABAAAAAAAAAAAgAAAAIAAAADAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAgAAAAIAAAAAAAAAAwAAAAgAAAACAAAAAAAAAAIAAAADAAAAEQAAAAAAAAACAAAAAgAAAAMAAAANAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAACAAAAAgAAAAAAAAADAAAACQAAAAIAAAAAAAAAAgAAAAMAAAASAAAAAAAAAAIAAAACAAAAAwAAAA4AAAAAAAAAAAAAAAAAAAAAAAAACQAAAAIAAAACAAAAAAAAAAMAAAAFAAAAAgAAAAAAAAACAAAAAwAAABMAAAAAAAAAAgAAAAIAAAADAAAADwAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAgAAAAAAAAACAAAAAQAAABMAAAACAAAAAgAAAAAAAAAFAAAACgAAAAAAAAACAAAAAgAAAAMAAAAQAAAAAAAAAAAAAAAAAAAAAAAAABEAAAACAAAAAAAAAAIAAAABAAAADwAAAAIAAAACAAAAAAAAAAUAAAALAAAAAAAAAAIAAAACAAAAAwAAABEAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAIAAAAAAAAAAgAAAAEAAAAQAAAAAgAAAAIAAAAAAAAABQAAAAwAAAAAAAAAAgAAAAIAAAADAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAATAAAAAgAAAAAAAAACAAAAAQAAABEAAAACAAAAAgAAAAAAAAAFAAAADQAAAAAAAAACAAAAAgAAAAMAAAATAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAACAAAAAAAAAAIAAAABAAAAEgAAAAIAAAACAAAAAAAAAAUAAAAOAAAAAAAAAAIAAAACAAAAAwAAAAIAAAABAAAAAAAAAAEAAAACAAAAAAAAAAAAAAACAAAAAQAAAAAAAAABAAAAAgAAAAEAAAAAAAAAAgAAAAAAAAAFAAAABAAAAAAAAAABAAAABQAAAAAAAAAAAAAABQAAAAQAAAAAAAAAAQAAAAUAAAAEAAAAAAAAAAUAAAAAAAAAAgAAAAEAAAAAAAAAAQAAAAIAAAAAAAAAAAAAAAIAAAABAAAAAAAAAAEAAAACAAAAAQAAAAAAAAACAAAAAgAAAAAAAAABAAAAAAAAAAAAAAAFAAAABAAAAAAAAAABAAAABQAAAAAAAAAAAAAABQAAAAQAAAAAAAAAAQAAAAUAAAAEAAAAAAAAAAUAAAAFAAAAAAAAAAEAAAAAAAAAAAAAAMuhRbbsNlBBYqHW9OmHIkF9XBuqnS31QAK37uYhNMhAOSo3UUupm0DC+6pc6JxvQHV9eseEEEJAzURsCyqlFEB8BQ4NMJjnPyy3tBoS97o/xawXQznRjj89J2K2CZxhP6vX43RIIDQ/S8isgygEBz+LvFHQkmzaPjFFFO7wMq4+AADMLkTtjkIAAOgkJqxhQgAAU7B0MjRCAADwpBcVB0IAAACYP2HaQQAAAIn/Ja5BzczM4Eg6gUHNzMxMU7BTQTMzMzNfgCZBAAAAAEi3+UAAAAAAwGPNQDMzMzMzy6BAmpmZmZkxc0AzMzMzM/NFQDMzMzMzMxlAzczMzMzM7D+ygXSx2U6RQKimJOvQKnpA23hmONTHY0A/AGcxyudNQNb3K647mzZA+S56rrwWIUAm4kUQ+9UJQKre9hGzh/M/BLvoy9WG3T+LmqMf8VHGP2m3nYNV37A/gbFHcyeCmT+cBPWBckiDP61tZACjKW0/q2RbYVUYVj8uDypVyLNAP6jGS5cA5zBBwcqhBdCNGUEGEhQ/JVEDQT6WPnRbNO1AB/AWSJgT1kDfUWNCNLDAQNk+5C33OqlAchWL34QSk0DKvtDIrNV8QNF0G3kFzGVASSeWhBl6UED+/0mNGuk4QGjA/dm/1CJALPLPMql6DEDSHoDrwpP1P2jouzWST+A/egAAAAAAAABKAwAAAAAAAPoWAAAAAAAAyqAAAAAAAAB6ZQQAAAAAAErGHgAAAAAA+mvXAAAAAADK8+MFAAAAAHqqOykAAAAASqmhIAEAAAD6oGvkBwAAAMpm8T43AAAAes+ZuIIBAABKrDQMkwoAAPq1cFUFSgAAyvkUViUGAgAAAAAAAwAAAAYAAAACAAAABQAAAAEAAAAEAAAAAAAAAAAAAAAFAAAAAwAAAAEAAAAGAAAABAAAAAIAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAP////////////////////////////////////8AAAAA/////wAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAP////8AAAAAAAAAAAEAAAABAAAAAAAAAAAAAAD/////AAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAA/////wUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////AAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////////////////////////////wAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAUAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////////////////////////////8AAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAABAAAAAAAAAAAAAAABAAAAAQAAAAEAAAAAAAAAAQAAAAAAAAAFAAAAAQAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAAAAAABAAEAAAEBAAAAAAABAAAAAQAAAAEAAQAAAAAAAAAAAAAAAAAAAAAEAAAABAAAAAAAAAACAAAAAQAAAAMAAAAOAAAABgAAAAsAAAACAAAABwAAAAEAAAAYAAAABQAAAAoAAAABAAAABgAAAAAAAAAmAAAABwAAAAwAAAADAAAACAAAAAIAAAAxAAAACQAAAA4AAAAAAAAABQAAAAQAAAA6AAAACAAAAA0AAAAEAAAACQAAAAMAAAA/AAAACwAAAAYAAAAPAAAACgAAABAAAABIAAAADAAAAAcAAAAQAAAACwAAABEAAABTAAAACgAAAAUAAAATAAAADgAAAA8AAABhAAAADQAAAAgAAAARAAAADAAAABIAAABrAAAADgAAAAkAAAASAAAADQAAABMAAAB1AAAADwAAABMAAAARAAAAEgAAABAAAAAHAAAABwAAAAEAAAACAAAABAAAAAMAAAAAAAAAAAAAAAcAAAADAAAAAQAAAAIAAAAFAAAABAAAAAAAAAAAAAAAYWxnb3MuYwBfcG9seWZpbGxJbnRlcm5hbABhZGphY2VudEZhY2VEaXJbdG1wRmlqay5mYWNlXVtmaWprLmZhY2VdID09IEtJAGZhY2VpamsuYwBfZmFjZUlqa1BlbnRUb0dlb0JvdW5kYXJ5AGFkamFjZW50RmFjZURpcltjZW50ZXJJSksuZmFjZV1bZmFjZTJdID09IEtJAF9mYWNlSWprVG9HZW9Cb3VuZGFyeQBwb2x5Z29uLT5uZXh0ID09IE5VTEwAbGlua2VkR2VvLmMAYWRkTmV3TGlua2VkUG9seWdvbgBuZXh0ICE9IE5VTEwAbG9vcCAhPSBOVUxMAGFkZE5ld0xpbmtlZExvb3AAcG9seWdvbi0+Zmlyc3QgPT0gTlVMTABhZGRMaW5rZWRMb29wAGNvb3JkICE9IE5VTEwAYWRkTGlua2VkQ29vcmQAbG9vcC0+Zmlyc3QgPT0gTlVMTABpbm5lckxvb3BzICE9IE5VTEwAbm9ybWFsaXplTXVsdGlQb2x5Z29uAGJib3hlcyAhPSBOVUxMAGNhbmRpZGF0ZXMgIT0gTlVMTABmaW5kUG9seWdvbkZvckhvbGUAY2FuZGlkYXRlQkJveGVzICE9IE5VTEwAcmV2RGlyICE9IElOVkFMSURfRElHSVQAbG9jYWxpai5jAGgzVG9Mb2NhbElqawBiYXNlQ2VsbCAhPSBvcmlnaW5CYXNlQ2VsbAAhKG9yaWdpbk9uUGVudCAmJiBpbmRleE9uUGVudCkAcGVudGFnb25Sb3RhdGlvbnMgPj0gMABkaXJlY3Rpb25Sb3RhdGlvbnMgPj0gMABiYXNlQ2VsbCA9PSBvcmlnaW5CYXNlQ2VsbABiYXNlQ2VsbCAhPSBJTlZBTElEX0JBU0VfQ0VMTABsb2NhbElqa1RvSDMAIV9pc0Jhc2VDZWxsUGVudGFnb24oYmFzZUNlbGwpAGJhc2VDZWxsUm90YXRpb25zID49IDAAd2l0aGluUGVudGFnb25Sb3RhdGlvbnMgPj0gMABncmFwaC0+YnVja2V0cyAhPSBOVUxMAHZlcnRleEdyYXBoLmMAaW5pdFZlcnRleEdyYXBoAG5vZGUgIT0gTlVMTABhZGRWZXJ0ZXhOb2Rl";function Y(A){return A}function O(A){return A.replace(/\b__Z[\w\d_]+/g,(function(A){return A===A?A:A+" ["+A+"]"}))}function j(){var A=new Error;if(!A.stack){try{throw new Error(0)}catch(e){A=e}if(!A.stack)return"(no stack trace available)"}return A.stack.toString()}function N(){return p.length}function Z(A){try{var e=new ArrayBuffer(A);if(e.byteLength!=A)return;return new Int8Array(e).set(p),$(e),Q(e),1}catch(A){}}var W="function"==typeof atob?atob:function(A){var e,r,t,i,n,o,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f="",s=0;A=A.replace(/[^A-Za-z0-9\+\/\=]/g,"");do{e=a.indexOf(A.charAt(s++))<<2|(i=a.indexOf(A.charAt(s++)))>>4,r=(15&i)<<4|(n=a.indexOf(A.charAt(s++)))>>2,t=(3&n)<<6|(o=a.indexOf(A.charAt(s++))),f+=String.fromCharCode(e),64!==n&&(f+=String.fromCharCode(r)),64!==o&&(f+=String.fromCharCode(t))}while(s>2]=A,i[a+4>>2]=e,(a=0!=(0|n))&&(i[n>>2]=0),0|UA(A,e))return I=o,0|(d=1);i[d>>2]=0;A:do{if((0|r)>=1)if(a)for(l=0,h=1,c=1,f=0,a=A;;){if(!(f|l)){if(0==(0|(a=0|U(a,e,4,d)))&0==(0|(e=0|M()))){a=2;break A}if(0|UA(a,e)){a=1;break A}}if(0==(0|(a=0|U(a,e,0|i[16+(l<<2)>>2],d)))&0==(0|(e=0|M()))){a=2;break A}if(i[(A=t+(c<<3)|0)>>2]=a,i[A+4>>2]=e,i[n+(c<<2)>>2]=h,A=(0|(f=f+1|0))==(0|h),u=6==(0|(s=l+1|0)),0|UA(a,e)){a=1;break A}if((0|(h=h+(u&A&1)|0))>(0|r)){a=0;break}l=A?u?0:s:l,c=c+1|0,f=A?0:f}else for(l=0,h=1,c=1,f=0,a=A;;){if(!(f|l)){if(0==(0|(a=0|U(a,e,4,d)))&0==(0|(e=0|M()))){a=2;break A}if(0|UA(a,e)){a=1;break A}}if(0==(0|(a=0|U(a,e,0|i[16+(l<<2)>>2],d)))&0==(0|(e=0|M()))){a=2;break A}if(i[(A=t+(c<<3)|0)>>2]=a,i[A+4>>2]=e,A=(0|(f=f+1|0))==(0|h),u=6==(0|(s=l+1|0)),0|UA(a,e)){a=1;break A}if((0|(h=h+(u&A&1)|0))>(0|r)){a=0;break}l=A?u?0:s:l,c=c+1|0,f=A?0:f}else a=0}while(0);return I=o,0|(d=a)}function P(A,e,r,t,n,o,a){r|=0,t|=0,n|=0,o|=0,a|=0;var f,s,u=0,l=0,h=0,c=0,d=0;if(s=I,I=I+16|0,f=s,0==(0|(A|=0))&0==(0|(e|=0)))I=s;else{if(u=0|Me(0|A,0|e,0|o,((0|o)<0)<<31>>31|0),M(),!(0==(0|(d=0|i[(c=l=t+(u<<3)|0)>>2]))&0==(0|(c=0|i[c+4>>2]))|(h=(0|d)==(0|A)&(0|c)==(0|e))))do{h=(0|(c=0|i[(d=l=t+((u=(u+1|0)%(0|o)|0)<<3)|0)>>2]))==(0|A)&(0|(d=0|i[d+4>>2]))==(0|e)}while(!(0==(0|c)&0==(0|d)|h));u=n+(u<<2)|0,h&&(0|i[u>>2])<=(0|a)||(i[(d=l)>>2]=A,i[d+4>>2]=e,i[u>>2]=a,(0|a)>=(0|r)||(d=a+1|0,i[f>>2]=0,P(c=0|U(A,e,2,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,3,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,1,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,5,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,4,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,6,f),0|M(),r,t,n,o,d))),I=s}}function U(A,e,r,t){A|=0,e|=0,r|=0;var n,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0;if((0|i[(t|=0)>>2])>0){a=0;do{r=0|fA(r),a=a+1|0}while((0|a)<(0|i[t>>2]))}n=0|Qe(0|A,0|e,45),M(),o=127&n,f=0|GA(A,e),a=0|Qe(0|A,0|e,52),M(),a&=15;A:do{if(a)for(;;){if(h=0|Qe(0|A,0|e,0|(l=3*(15-a|0)|0)),M(),h&=7,c=0==(0|RA(a)),a=a+-1|0,u=0|ye(7,0,0|l),e&=~(0|M()),A=(l=0|ye(0|i[(c?464:48)+(28*h|0)+(r<<2)>>2],0,0|l))|A&~u,e|=0|M(),!(r=0|i[(c?672:256)+(28*h|0)+(r<<2)>>2])){r=0;break A}if(!a){s=6;break}}else s=6}while(0);6==(0|s)&&(A|=h=0|ye(0|(c=0|i[880+(28*o|0)+(r<<2)>>2]),0,45),e=0|M()|-1040385&e,r=0|i[4304+(28*o|0)+(r<<2)>>2],127==(127&c|0)&&(c=0|ye(0|i[880+(28*o|0)+20>>2],0,45),e=0|M()|-1040385&e,r=0|i[4304+(28*o|0)+20>>2],A=0|TA(c|A,e),e=0|M(),i[t>>2]=1+(0|i[t>>2]))),s=0|Qe(0|A,0|e,45),M(),s&=127;A:do{if(0|S(s)){e:do{if(1==(0|GA(A,e))){if((0|o)!=(0|s)){if(0|R(s,0|i[7728+(28*o|0)>>2])){A=0|HA(A,e),f=1,e=0|M();break}A=0|TA(A,e),f=1,e=0|M();break}switch(0|f){case 5:A=0|HA(A,e),e=0|M(),i[t>>2]=5+(0|i[t>>2]),f=0;break e;case 3:A=0|TA(A,e),e=0|M(),i[t>>2]=1+(0|i[t>>2]),f=0;break e;default:return c=0,k(0|(h=0)),0|c}}else f=0}while(0);if((0|r)>0){a=0;do{A=0|SA(A,e),e=0|M(),a=a+1|0}while((0|a)!=(0|r))}if((0|o)!=(0|s)){if(!(0|T(s))){if(0!=(0|f)|5!=(0|GA(A,e)))break;i[t>>2]=1+(0|i[t>>2]);break}switch(127&n){case 8:case 118:break A}3!=(0|GA(A,e))&&(i[t>>2]=1+(0|i[t>>2]))}}else if((0|r)>0){a=0;do{A=0|TA(A,e),e=0|M(),a=a+1|0}while((0|a)!=(0|r))}}while(0);return i[t>>2]=((0|i[t>>2])+r|0)%6|0,c=A,k(0|(h=e)),0|c}function G(A,e,r,t,o,a){e|=0,r|=0,t|=0,o|=0,a|=0;var f,s,u,l,h,c,d,g,w,p=0,B=0,b=0,v=0,m=0,k=0,Q=0,y=0,E=0,x=0,D=0,_=0,F=0,C=0;if(w=I,I=I+48|0,c=w+32|0,d=w+16|0,g=w,(0|(p=0|i[(A|=0)>>2]))<=0)return I=w,0|(_=0);f=A+4|0,s=c+8|0,u=d+8|0,l=g+8|0,h=((0|e)<0)<<31>>31,D=0;A:for(;;){E=(B=0|i[f>>2])+(D<<4)|0,i[c>>2]=i[E>>2],i[c+4>>2]=i[E+4>>2],i[c+8>>2]=i[E+8>>2],i[c+12>>2]=i[E+12>>2],(0|D)==(p+-1|0)?(i[d>>2]=i[B>>2],i[d+4>>2]=i[B+4>>2],i[d+8>>2]=i[B+8>>2],i[d+12>>2]=i[B+12>>2]):(E=B+(D+1<<4)|0,i[d>>2]=i[E>>2],i[d+4>>2]=i[E+4>>2],i[d+8>>2]=i[E+8>>2],i[d+12>>2]=i[E+12>>2]),E=0|N(c,d,r);e:do{if((0|E)>0){x=+(0|E),y=0;r:for(;;){C=+(E-y|0),F=+(0|y),n[g>>3]=+n[c>>3]*C/x+ +n[d>>3]*F/x,n[l>>3]=+n[s>>3]*C/x+ +n[u>>3]*F/x,B=0|Me(0|(k=0|LA(g,r)),0|(Q=0|M()),0|e,0|h),M(),v=0|i[(b=p=a+(B<<3)|0)>>2],b=0|i[b+4>>2];t:do{if(0==(0|v)&0==(0|b))_=14;else for(m=0;;){if((0|m)>(0|e)){p=1;break t}if((0|v)==(0|k)&(0|b)==(0|Q)){p=7;break t}if(0==(0|(v=0|i[(b=p=a+((B=(B+1|0)%(0|e)|0)<<3)|0)>>2]))&0==(0|(b=0|i[b+4>>2]))){_=14;break}m=m+1|0}}while(0);switch(14==(0|_)&&(_=0,0==(0|k)&0==(0|Q)?p=7:(i[p>>2]=k,i[p+4>>2]=Q,p=0|i[t>>2],i[(m=o+(p<<3)|0)>>2]=k,i[m+4>>2]=Q,i[t>>2]=p+1,p=0)),7&p){case 7:case 0:break;default:break r}if((0|E)<=(0|(y=y+1|0))){_=8;break e}}if(0|p){p=-1,_=20;break A}}else _=8}while(0);if(8==(0|_)&&(_=0),(0|(D=D+1|0))>=(0|(p=0|i[A>>2]))){p=0,_=20;break}}return 20==(0|_)?(I=w,0|p):0}function S(A){return 0|i[7728+(28*(A|=0)|0)+16>>2]}function T(A){return 4==(0|(A|=0))|117==(0|A)|0}function V(A){return 0|i[11152+(216*(0|i[(A|=0)>>2])|0)+(72*(0|i[A+4>>2])|0)+(24*(0|i[A+8>>2])|0)+(i[A+12>>2]<<3)>>2]}function H(A){return 0|i[11152+(216*(0|i[(A|=0)>>2])|0)+(72*(0|i[A+4>>2])|0)+(24*(0|i[A+8>>2])|0)+(i[A+12>>2]<<3)+4>>2]}function R(A,e){return e|=0,(0|i[7728+(28*(A|=0)|0)+20>>2])==(0|e)?0|(e=1):0|(e=(0|i[7728+(28*A|0)+24>>2])==(0|e))}function L(A,e){return 0|i[880+(28*(A|=0)|0)+((e|=0)<<2)>>2]}function z(A,e){return e|=0,(0|i[880+(28*(A|=0)|0)>>2])==(0|e)?0|(e=0):(0|i[880+(28*A|0)+4>>2])==(0|e)?0|(e=1):(0|i[880+(28*A|0)+8>>2])==(0|e)?0|(e=2):(0|i[880+(28*A|0)+12>>2])==(0|e)?0|(e=3):(0|i[880+(28*A|0)+16>>2])==(0|e)?0|(e=4):(0|i[880+(28*A|0)+20>>2])==(0|e)?0|(e=5):0|((0|i[880+(28*A|0)+24>>2])==(0|e)?6:7)}function Y(A){return+n[(A|=0)+16>>3]<+n[A+24>>3]|0}function O(A,e){A|=0;var r,t,i=0;return(i=+n[(e|=0)>>3])>=+n[A+8>>3]&&i<=+n[A>>3]?(r=+n[A+16>>3],i=+n[A+24>>3],e=(t=+n[e+8>>3])>=i,A=t<=r&1,r>2]=0,l=l+4|0}while((0|l)<(0|h));return NA(e,o),OA(h=0|i[(l=o)>>2],l=0|i[l+4>>2],r),jA(h,l,t),s=+DA(r,t+8|0),n[r>>3]=+n[A>>3],n[(l=r+8|0)>>3]=+n[A+16>>3],n[t>>3]=+n[A+8>>3],n[(h=t+8|0)>>3]=+n[A+24>>3],u=+DA(r,t),h=~~+B(+u*u/+Ee(+ +f(+(+n[l>>3]-+n[h>>3])/(+n[r>>3]-+n[t>>3])),3)/(s*(2.59807621135*s)*.8)),I=a,0|(0==(0|h)?1:h)}function N(A,e,r){A|=0,e|=0,r|=0;var t,n,o,a,f,s=0,u=0;a=I,I=I+288|0,t=a+264|0,n=a+96|0,u=(s=o=a)+96|0;do{i[s>>2]=0,s=s+4|0}while((0|s)<(0|u));return NA(r,o),OA(s=0|i[(u=o)>>2],u=0|i[u+4>>2],t),jA(s,u,n),f=+DA(t,n+8|0),u=~~+B(+ +DA(A,e)/(2*f)),I=a,0|(0==(0|u)?1:u)}function Z(A,e,r,t){e|=0,r|=0,t|=0,i[(A|=0)>>2]=e,i[A+4>>2]=r,i[A+8>>2]=t}function W(A,e){A|=0;var r,t,o,a,s=0,u=0,l=0,h=0,c=0,d=0,g=0;i[(a=(e|=0)+8|0)>>2]=0,t=+n[A>>3],h=+f(+t),o=+n[A+8>>3],h+=.5*(c=+f(+o)/.8660254037844386),h-=+(0|(s=~~h)),c-=+(0|(A=~~c));do{if(h<.5){if(h<.3333333333333333){if(i[e>>2]=s,c<.5*(h+1)){i[e+4>>2]=A;break}A=A+1|0,i[e+4>>2]=A;break}if(A=(1&!(c<(g=1-h)))+A|0,i[e+4>>2]=A,g<=c&c<2*h){s=s+1|0,i[e>>2]=s;break}i[e>>2]=s;break}if(!(h<.6666666666666666)){if(s=s+1|0,i[e>>2]=s,c<.5*h){i[e+4>>2]=A;break}A=A+1|0,i[e+4>>2]=A;break}if(c<1-h){if(i[e+4>>2]=A,2*h-1>2]=s;break}}else A=A+1|0,i[e+4>>2]=A;s=s+1|0,i[e>>2]=s}while(0);do{if(t<0){if(1&A){s=~~(+(0|s)-(2*(+((d=0|ve(0|s,((0|s)<0)<<31>>31|0,0|(d=(A+1|0)/2|0),((0|d)<0)<<31>>31|0))>>>0)+4294967296*+(0|M()))+1)),i[e>>2]=s;break}s=~~(+(0|s)-2*(+((d=0|ve(0|s,((0|s)<0)<<31>>31|0,0|(d=(0|A)/2|0),((0|d)<0)<<31>>31|0))>>>0)+4294967296*+(0|M()))),i[e>>2]=s;break}}while(0);d=e+4|0,o<0&&(s=s-((1|A<<1)/2|0)|0,i[e>>2]=s,A=0-A|0,i[d>>2]=A),u=A-s|0,(0|s)<0?(l=0-s|0,i[d>>2]=u,i[a>>2]=l,i[e>>2]=0,A=u,s=0):l=0,(0|A)<0&&(s=s-A|0,i[e>>2]=s,l=l-A|0,i[a>>2]=l,i[d>>2]=0,A=0),r=s-l|0,u=A-l|0,(0|l)<0&&(i[e>>2]=r,i[d>>2]=u,i[a>>2]=0,A=u,s=r,l=0),(0|(u=(0|l)<(0|(u=(0|A)<(0|s)?A:s))?l:u))<=0||(i[e>>2]=s-u,i[d>>2]=A-u,i[a>>2]=l-u)}function J(A){var e,r=0,t=0,n=0,o=0,a=0;r=0|i[(A|=0)>>2],t=0|i[(e=A+4|0)>>2],(0|r)<0&&(t=t-r|0,i[e>>2]=t,i[(a=A+8|0)>>2]=(0|i[a>>2])-r,i[A>>2]=0,r=0),(0|t)<0?(r=r-t|0,i[A>>2]=r,o=(0|i[(a=A+8|0)>>2])-t|0,i[a>>2]=o,i[e>>2]=0,t=0):(a=o=A+8|0,o=0|i[o>>2]),(0|o)<0&&(r=r-o|0,i[A>>2]=r,t=t-o|0,i[e>>2]=t,i[a>>2]=0,o=0),(0|(n=(0|o)<(0|(n=(0|t)<(0|r)?t:r))?o:n))<=0||(i[A>>2]=r-n,i[e>>2]=t-n,i[a>>2]=o-n)}function K(A,e){e|=0;var r,t;t=0|i[(A|=0)+8>>2],r=+((0|i[A+4>>2])-t|0),n[e>>3]=+((0|i[A>>2])-t|0)-.5*r,n[e+8>>3]=.8660254037844386*r}function X(A,e,r){A|=0,e|=0,i[(r|=0)>>2]=(0|i[e>>2])+(0|i[A>>2]),i[r+4>>2]=(0|i[e+4>>2])+(0|i[A+4>>2]),i[r+8>>2]=(0|i[e+8>>2])+(0|i[A+8>>2])}function q(A,e,r){A|=0,e|=0,i[(r|=0)>>2]=(0|i[A>>2])-(0|i[e>>2]),i[r+4>>2]=(0|i[A+4>>2])-(0|i[e+4>>2]),i[r+8>>2]=(0|i[A+8>>2])-(0|i[e+8>>2])}function $(A,e){e|=0;var r,t=0;t=0|b(0|i[(A|=0)>>2],e),i[A>>2]=t,r=0|b(0|i[(t=A+4|0)>>2],e),i[t>>2]=r,e=0|b(0|i[(A=A+8|0)>>2],e),i[A>>2]=e}function AA(A){var e,r,t=0,n=0,o=0,a=0,f=0;f=(0|(r=0|i[(A|=0)>>2]))<0,A=(A=(n=(0|(a=((e=(0|(o=(0|i[A+4>>2])-(f?r:0)|0))<0)?0-o|0:0)+((0|i[A+8>>2])-(f?r:0))|0))<0)?0:a)-((o=(0|(n=(0|A)<(0|(n=(0|(t=(e?0:o)-(n?a:0)|0))<(0|(a=(f?0:r)-(e?o:0)-(n?a:0)|0))?t:a))?A:n))>0)?n:0)|0,t=t-(o?n:0)|0;A:do{switch(a-(o?n:0)|0){case 0:switch(0|t){case 0:return 0|(f=0==(0|A)?0:1==(0|A)?1:7);case 1:return 0|(f=0==(0|A)?2:1==(0|A)?3:7);default:break A}case 1:switch(0|t){case 0:return 0|(f=0==(0|A)?4:1==(0|A)?5:7);case 1:if(A)break A;return 0|(A=6);default:break A}}}while(0);return 0|(f=7)}function eA(A){var e,r,t=0,n=0,o=0,a=0,f=0;n=0|i[(e=(A|=0)+8|0)>>2],o=0|we(+((3*(t=(0|i[A>>2])-n|0)|0)-(n=(0|i[(r=A+4|0)>>2])-n|0)|0)/7),i[A>>2]=o,t=0|we(+((n<<1)+t|0)/7),i[r>>2]=t,i[e>>2]=0,n=t-o|0,(0|o)<0?(f=0-o|0,i[r>>2]=n,i[e>>2]=f,i[A>>2]=0,t=n,o=0,n=f):n=0,(0|t)<0&&(o=o-t|0,i[A>>2]=o,n=n-t|0,i[e>>2]=n,i[r>>2]=0,t=0),f=o-n|0,a=t-n|0,(0|n)<0?(i[A>>2]=f,i[r>>2]=a,i[e>>2]=0,t=a,a=f,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|t)<(0|a)?t:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=t-o,i[e>>2]=n-o)}function rA(A){var e,r,t=0,n=0,o=0,a=0,f=0;n=0|i[(e=(A|=0)+8|0)>>2],o=0|we(+(((t=(0|i[A>>2])-n|0)<<1)+(n=(0|i[(r=A+4|0)>>2])-n|0)|0)/7),i[A>>2]=o,t=0|we(+((3*n|0)-t|0)/7),i[r>>2]=t,i[e>>2]=0,n=t-o|0,(0|o)<0?(f=0-o|0,i[r>>2]=n,i[e>>2]=f,i[A>>2]=0,t=n,o=0,n=f):n=0,(0|t)<0&&(o=o-t|0,i[A>>2]=o,n=n-t|0,i[e>>2]=n,i[r>>2]=0,t=0),f=o-n|0,a=t-n|0,(0|n)<0?(i[A>>2]=f,i[r>>2]=a,i[e>>2]=0,t=a,a=f,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|t)<(0|a)?t:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=t-o,i[e>>2]=n-o)}function tA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],o=0|i[(r=A+4|0)>>2],a=0|i[(t=A+8|0)>>2],f=o+(3*n|0)|0,i[A>>2]=f,o=a+(3*o|0)|0,i[r>>2]=o,n=(3*a|0)+n|0,i[t>>2]=n,a=o-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=a,i[t>>2]=n,i[A>>2]=0,o=a,a=0):a=f,(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function iA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=(3*(n=0|i[(r=A+4|0)>>2])|0)+f|0,f=(o=0|i[(t=A+8|0)>>2])+(3*f|0)|0,i[A>>2]=f,i[r>>2]=a,n=(3*o|0)+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,f=0):o=a,(0|o)<0&&(f=f-o|0,i[A>>2]=f,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=f-n|0,a=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=a,i[t>>2]=0,f=e,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|a)<(0|f)?a:f))?n:o))<=0||(i[A>>2]=f-o,i[r>>2]=a-o,i[t>>2]=n-o)}function nA(A,e){A|=0;var r,t,n,o=0,a=0,f=0;((e|=0)+-1|0)>>>0>=6||(f=(0|i[15472+(12*e|0)>>2])+(0|i[A>>2])|0,i[A>>2]=f,n=A+4|0,a=(0|i[15472+(12*e|0)+4>>2])+(0|i[n>>2])|0,i[n>>2]=a,t=A+8|0,e=(0|i[15472+(12*e|0)+8>>2])+(0|i[t>>2])|0,i[t>>2]=e,o=a-f|0,(0|f)<0?(e=e-f|0,i[n>>2]=o,i[t>>2]=e,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,e=e-o|0,i[t>>2]=e,i[n>>2]=0,o=0),r=a-e|0,f=o-e|0,(0|e)<0?(i[A>>2]=r,i[n>>2]=f,i[t>>2]=0,a=r,e=0):f=o,(0|(o=(0|e)<(0|(o=(0|f)<(0|a)?f:a))?e:o))<=0||(i[A>>2]=a-o,i[n>>2]=f-o,i[t>>2]=e-o))}function oA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=(n=0|i[(r=A+4|0)>>2])+f|0,f=(o=0|i[(t=A+8|0)>>2])+f|0,i[A>>2]=f,i[r>>2]=a,n=o+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function aA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],a=0|i[(r=A+4|0)>>2],o=0|i[(t=A+8|0)>>2],f=a+n|0,i[A>>2]=f,a=o+a|0,i[r>>2]=a,n=o+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function fA(A){switch(0|(A|=0)){case 1:A=5;break;case 5:A=4;break;case 4:A=6;break;case 6:A=2;break;case 2:A=3;break;case 3:A=1}return 0|A}function sA(A){switch(0|(A|=0)){case 1:A=3;break;case 3:A=2;break;case 2:A=6;break;case 6:A=4;break;case 4:A=5;break;case 5:A=1}return 0|A}function uA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],o=0|i[(r=A+4|0)>>2],a=0|i[(t=A+8|0)>>2],f=o+(n<<1)|0,i[A>>2]=f,o=a+(o<<1)|0,i[r>>2]=o,n=(a<<1)+n|0,i[t>>2]=n,a=o-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=a,i[t>>2]=n,i[A>>2]=0,o=a,a=0):a=f,(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function lA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=((n=0|i[(r=A+4|0)>>2])<<1)+f|0,f=(o=0|i[(t=A+8|0)>>2])+(f<<1)|0,i[A>>2]=f,i[r>>2]=a,n=(o<<1)+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,f=0):o=a,(0|o)<0&&(f=f-o|0,i[A>>2]=f,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=f-n|0,a=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=a,i[t>>2]=0,f=e,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|a)<(0|f)?a:f))?n:o))<=0||(i[A>>2]=f-o,i[r>>2]=a-o,i[t>>2]=n-o)}function hA(A,e){e|=0;var r,t,n,o=0,a=0,f=0;return n=(0|(t=(0|i[(A|=0)>>2])-(0|i[e>>2])|0))<0,r=(0|(a=(0|i[A+4>>2])-(0|i[e+4>>2])-(n?t:0)|0))<0,e=(e=(A=(0|(f=(n?0-t|0:0)+(0|i[A+8>>2])-(0|i[e+8>>2])+(r?0-a|0:0)|0))<0)?0:f)-((a=(0|(A=(0|e)<(0|(A=(0|(o=(r?0:a)-(A?f:0)|0))<(0|(f=(n?0:t)-(r?a:0)-(A?f:0)|0))?o:f))?e:A))>0)?A:0)|0,o=o-(a?A:0)|0,0|((0|(A=(0|(A=f-(a?A:0)|0))>-1?A:0-A|0))>(0|(e=(0|(o=(0|o)>-1?o:0-o|0))>(0|(e=(0|e)>-1?e:0-e|0))?o:e))?A:e)}function cA(A,e){e|=0;var r;r=0|i[(A|=0)+8>>2],i[e>>2]=(0|i[A>>2])-r,i[e+4>>2]=(0|i[A+4>>2])-r}function dA(A,e){e|=0;var r,t,n,o=0,a=0,f=0;a=0|i[(A|=0)>>2],i[e>>2]=a,A=0|i[A+4>>2],i[(t=e+4|0)>>2]=A,i[(n=e+8|0)>>2]=0,o=A-a|0,(0|a)<0?(A=0-a|0,i[t>>2]=o,i[n>>2]=A,i[e>>2]=0,a=0):(o=A,A=0),(0|o)<0&&(a=a-o|0,i[e>>2]=a,A=A-o|0,i[n>>2]=A,i[t>>2]=0,o=0),r=a-A|0,f=o-A|0,(0|A)<0?(i[e>>2]=r,i[t>>2]=f,i[n>>2]=0,o=f,f=r,A=0):f=a,(0|(a=(0|A)<(0|(a=(0|o)<(0|f)?o:f))?A:a))<=0||(i[e>>2]=f-a,i[t>>2]=o-a,i[n>>2]=A-a)}function gA(A){var e,r,t,n;r=(n=0|i[(e=(A|=0)+8|0)>>2])-(0|i[A>>2])|0,i[A>>2]=r,A=(0|i[(t=A+4|0)>>2])-n|0,i[t>>2]=A,i[e>>2]=0-(A+r)}function wA(A){var e,r,t=0,n=0,o=0,a=0,f=0;t=0-(n=0|i[(A|=0)>>2])|0,i[A>>2]=t,i[(e=A+8|0)>>2]=0,a=(o=0|i[(r=A+4|0)>>2])+n|0,(0|n)>0?(i[r>>2]=a,i[e>>2]=n,i[A>>2]=0,t=0,o=a):n=0,(0|o)<0?(f=t-o|0,i[A>>2]=f,n=n-o|0,i[e>>2]=n,i[r>>2]=0,a=f-n|0,t=0-n|0,(0|n)<0?(i[A>>2]=a,i[r>>2]=t,i[e>>2]=0,o=t,n=0):(o=0,a=f)):a=t,(0|(t=(0|n)<(0|(t=(0|o)<(0|a)?o:a))?n:t))<=0||(i[A>>2]=a-t,i[r>>2]=o-t,i[e>>2]=n-t)}function pA(A,e,r,t){e|=0,r|=0,t|=0;var o,a=0,f=0,s=0,u=0;if(o=I,I=I+32|0,function(A,e){e|=0;var r=0,t=0,i=0;r=+n[(A=A|0)>>3],t=+l(+r),r=+h(+r),n[e+16>>3]=r,r=+n[A+8>>3],i=t*+l(+r),n[e>>3]=i,r=t*+h(+r),n[e+8>>3]=r}(A|=0,f=o),i[r>>2]=0,a=+fe(15888,f),(s=+fe(15912,f))>2]=1,a=s),(s=+fe(15936,f))>2]=2,a=s),(s=+fe(15960,f))>2]=3,a=s),(s=+fe(15984,f))>2]=4,a=s),(s=+fe(16008,f))>2]=5,a=s),(s=+fe(16032,f))>2]=6,a=s),(s=+fe(16056,f))>2]=7,a=s),(s=+fe(16080,f))>2]=8,a=s),(s=+fe(16104,f))>2]=9,a=s),(s=+fe(16128,f))>2]=10,a=s),(s=+fe(16152,f))>2]=11,a=s),(s=+fe(16176,f))>2]=12,a=s),(s=+fe(16200,f))>2]=13,a=s),(s=+fe(16224,f))>2]=14,a=s),(s=+fe(16248,f))>2]=15,a=s),(s=+fe(16272,f))>2]=16,a=s),(s=+fe(16296,f))>2]=17,a=s),(s=+fe(16320,f))>2]=18,a=s),(s=+fe(16344,f))>2]=19,a=s),(s=+d(+(1-.5*a)))<1e-16)return i[t>>2]=0,i[t+4>>2]=0,i[t+8>>2]=0,i[t+12>>2]=0,void(I=o);if(r=0|i[r>>2],a=+EA((a=+n[16368+(24*r|0)>>3])-+EA(+function(A,e){A|=0;var r=0,t=0,i=0,o=0,a=0;return o=+n[(e=e|0)>>3],t=+l(+o),i=+n[e+8>>3]-+n[A+8>>3],a=t*+h(+i),r=+n[A>>3],+ +p(+a,+(+h(+o)*+l(+r)-+l(+i)*(t*+h(+r))))}(15568+(r<<4)|0,A))),u=0|RA(e)?+EA(a+-.3334731722518321):a,a=+c(+s)/.381966011250105,(0|e)>0){f=0;do{a*=2.6457513110645907,f=f+1|0}while((0|f)!=(0|e))}s=+l(+u)*a,n[t>>3]=s,u=+h(+u)*a,n[t+8>>3]=u,I=o}function BA(A,e,r,t,o){e|=0,r|=0,t|=0,o|=0;var a=0,u=0;if((a=+function(A){var e=0,r=0;return r=+n[(A=A|0)>>3],e=+n[A+8>>3],+ +s(+(r*r+e*e))}(A|=0))<1e-16)return e=15568+(e<<4)|0,i[o>>2]=i[e>>2],i[o+4>>2]=i[e+4>>2],i[o+8>>2]=i[e+8>>2],void(i[o+12>>2]=i[e+12>>2]);if(u=+p(+ +n[A+8>>3],+ +n[A>>3]),(0|r)>0){A=0;do{a/=2.6457513110645907,A=A+1|0}while((0|A)!=(0|r))}t?(a/=3,r=0==(0|RA(r)),a=+w(.381966011250105*(r?a:a/2.6457513110645907))):(a=+w(.381966011250105*a),0|RA(r)&&(u=+EA(u+.3334731722518321))),function(A,e,r,t){A|=0,e=+e,t|=0;var o=0,a=0,s=0,u=0;if((r=+r)<1e-16)return i[t>>2]=i[A>>2],i[t+4>>2]=i[A+4>>2],i[t+8>>2]=i[A+8>>2],void(i[t+12>>2]=i[A+12>>2]);a=e<0?e+6.283185307179586:e,a=e>=6.283185307179586?a+-6.283185307179586:a;do{if(!(a<1e-16)){if(o=+f(+(a+-3.141592653589793))<1e-16,e=+n[A>>3],o){e-=r,n[t>>3]=e,o=t;break}if(s=+l(+r),r=+h(+r),e=s*+h(+e)+ +l(+a)*(r*+l(+e)),e=+g(+((e=e>1?1:e)<-1?-1:e)),n[t>>3]=e,+f(+(e+-1.5707963267948966))<1e-16)return n[t>>3]=1.5707963267948966,void(n[t+8>>3]=0);if(+f(+(e+1.5707963267948966))<1e-16)return n[t>>3]=-1.5707963267948966,void(n[t+8>>3]=0);if(u=+l(+e),a=r*+h(+a)/u,r=+n[A>>3],e=(s-+h(+e)*+h(+r))/+l(+r)/u,s=a>1?1:a,e=e>1?1:e,(e=+n[A+8>>3]+ +p(+(s<-1?-1:s),+(e<-1?-1:e)))>3.141592653589793)do{e+=-6.283185307179586}while(e>3.141592653589793);if(e<-3.141592653589793)do{e+=6.283185307179586}while(e<-3.141592653589793);return void(n[t+8>>3]=e)}e=+n[A>>3]+r,n[t>>3]=e,o=t}while(0);if(+f(+(e+-1.5707963267948966))<1e-16)return n[o>>3]=1.5707963267948966,void(n[t+8>>3]=0);if(+f(+(e+1.5707963267948966))<1e-16)return n[o>>3]=-1.5707963267948966,void(n[t+8>>3]=0);if((e=+n[A+8>>3])>3.141592653589793)do{e+=-6.283185307179586}while(e>3.141592653589793);if(e<-3.141592653589793)do{e+=6.283185307179586}while(e<-3.141592653589793);n[t+8>>3]=e}(15568+(e<<4)|0,+EA(+n[16368+(24*e|0)>>3]-u),a,o)}function bA(A,e,r){e|=0,r|=0;var t,n;t=I,I=I+16|0,K((A|=0)+4|0,n=t),BA(n,0|i[A>>2],e,0,r),I=t}function vA(A,e,r,t,o){A|=0,e|=0,r|=0,t|=0,o|=0;var a,f,s,u,l,h,c,d,g,w,p,B,b,v,m,k,M,y,E,x,D,_,F=0,C=0,P=0,U=0,G=0,S=0;if(_=I,I=I+272|0,U=_+240|0,E=_,x=_+224|0,D=_+208|0,p=_+176|0,B=_+160|0,b=_+192|0,v=_+144|0,m=_+128|0,k=_+112|0,M=_+96|0,y=_+80|0,i[(F=_+256|0)>>2]=e,i[U>>2]=i[A>>2],i[U+4>>2]=i[A+4>>2],i[U+8>>2]=i[A+8>>2],i[U+12>>2]=i[A+12>>2],mA(U,F,E),i[o>>2]=0,(0|(U=t+r+(5==(0|t)&1)|0))<=(0|r))I=_;else{f=x+4|0,s=p+4|0,u=r+5|0,l=16848+((a=0|i[F>>2])<<2)|0,h=16928+(a<<2)|0,c=m+8|0,d=k+8|0,g=M+8|0,w=D+4|0,P=r;A:for(;;){C=E+(((0|P)%5|0)<<4)|0,i[D>>2]=i[C>>2],i[D+4>>2]=i[C+4>>2],i[D+8>>2]=i[C+8>>2],i[D+12>>2]=i[C+12>>2];do{}while(2==(0|kA(D,a,0,1)));if((0|P)>(0|r)&0!=(0|RA(e))){if(i[p>>2]=i[D>>2],i[p+4>>2]=i[D+4>>2],i[p+8>>2]=i[D+8>>2],i[p+12>>2]=i[D+12>>2],K(f,B),t=0|i[p>>2],F=0|i[17008+(80*t|0)+(i[x>>2]<<2)>>2],i[p>>2]=i[18608+(80*t|0)+(20*F|0)>>2],(0|(C=0|i[18608+(80*t|0)+(20*F|0)+16>>2]))>0){A=0;do{oA(s),A=A+1|0}while((0|A)<(0|C))}switch(C=18608+(80*t|0)+(20*F|0)+4|0,i[b>>2]=i[C>>2],i[b+4>>2]=i[C+4>>2],i[b+8>>2]=i[C+8>>2],$(b,3*(0|i[l>>2])|0),X(s,b,s),J(s),K(s,v),G=+(0|i[h>>2]),n[m>>3]=3*G,n[c>>3]=0,S=-1.5*G,n[k>>3]=S,n[d>>3]=2.598076211353316*G,n[M>>3]=S,n[g>>3]=-2.598076211353316*G,0|i[17008+(80*(0|i[p>>2])|0)+(i[D>>2]<<2)>>2]){case 1:A=k,t=m;break;case 3:A=M,t=k;break;case 2:A=m,t=M;break;default:A=12;break A}oe(B,v,t,A,y),BA(y,0|i[p>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])}if((0|P)<(0|u)&&(K(w,p),BA(p,0|i[D>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])),i[x>>2]=i[D>>2],i[x+4>>2]=i[D+4>>2],i[x+8>>2]=i[D+8>>2],i[x+12>>2]=i[D+12>>2],(0|(P=P+1|0))>=(0|U)){A=3;break}}3!=(0|A)?12==(0|A)&&Q(22474,22521,581,22531):I=_}}function mA(A,e,r){A|=0,e|=0,r|=0;var t,n=0,o=0,a=0,f=0,s=0;t=I,I=I+128|0,o=t,f=20208,s=(a=n=t+64|0)+60|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));f=20272,s=(a=o)+60|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));n=(s=0==(0|RA(0|i[e>>2])))?n:o,uA(o=A+4|0),lA(o),0|RA(0|i[e>>2])&&(iA(o),i[e>>2]=1+(0|i[e>>2])),i[r>>2]=i[A>>2],X(o,n,e=r+4|0),J(e),i[r+16>>2]=i[A>>2],X(o,n+12|0,e=r+20|0),J(e),i[r+32>>2]=i[A>>2],X(o,n+24|0,e=r+36|0),J(e),i[r+48>>2]=i[A>>2],X(o,n+36|0,e=r+52|0),J(e),i[r+64>>2]=i[A>>2],X(o,n+48|0,r=r+68|0),J(r),I=t}function kA(A,e,r,t){r|=0,t|=0;var n,o,a,f,s,u,l=0,h=0,c=0,d=0,g=0;if(u=I,I=I+32|0,s=u+12|0,o=u,g=(A|=0)+4|0,d=0|i[16928+((e|=0)<<2)>>2],d=(f=0!=(0|t))?3*d|0:d,l=0|i[g>>2],n=0|i[(a=A+8|0)>>2],f){if((0|(l=n+l+(t=0|i[(h=A+12|0)>>2])|0))==(0|d))return I=u,0|(g=1);c=h}else l=n+l+(t=0|i[(c=A+12|0)>>2])|0;if((0|l)<=(0|d))return I=u,0|(g=0);do{if((0|t)>0){if(t=0|i[A>>2],(0|n)>0){h=18608+(80*t|0)+60|0,t=A;break}t=18608+(80*t|0)+40|0,r?(Z(s,d,0,0),q(g,s,o),aA(o),X(o,s,g),h=t,t=A):(h=t,t=A)}else h=18608+(80*(0|i[A>>2])|0)+20|0,t=A}while(0);if(i[t>>2]=i[h>>2],(0|i[(l=h+16|0)>>2])>0){t=0;do{oA(g),t=t+1|0}while((0|t)<(0|i[l>>2]))}return A=h+4|0,i[s>>2]=i[A>>2],i[s+4>>2]=i[A+4>>2],i[s+8>>2]=i[A+8>>2],e=0|i[16848+(e<<2)>>2],$(s,f?3*e|0:e),X(g,s,g),J(g),t=f&&((0|i[a>>2])+(0|i[g>>2])+(0|i[c>>2])|0)==(0|d)?1:2,I=u,0|(g=t)}function MA(A,e){A|=0,e|=0;var r=0;do{r=0|kA(A,e,0,1)}while(2==(0|r));return 0|r}function QA(A,e,r,t,o){A|=0,e|=0,r|=0,t|=0,o|=0;var a,f,s,u,l,h,c,d,g,w,p,B,b,v,m,k,M,y,E=0,x=0,D=0,_=0,F=0;if(y=I,I=I+240|0,v=y+208|0,m=y,k=y+192|0,M=y+176|0,g=y+160|0,w=y+144|0,p=y+128|0,B=y+112|0,b=y+96|0,i[(E=y+224|0)>>2]=e,i[v>>2]=i[A>>2],i[v+4>>2]=i[A+4>>2],i[v+8>>2]=i[A+8>>2],i[v+12>>2]=i[A+12>>2],yA(v,E,m),i[o>>2]=0,(0|(d=t+r+(6==(0|t)&1)|0))<=(0|r))I=y;else{f=r+6|0,s=16928+((a=0|i[E>>2])<<2)|0,u=w+8|0,l=p+8|0,h=B+8|0,c=k+4|0,x=0,D=r,t=-1;A:for(;;){if(A=m+((E=(0|D)%6|0)<<4)|0,i[k>>2]=i[A>>2],i[k+4>>2]=i[A+4>>2],i[k+8>>2]=i[A+8>>2],i[k+12>>2]=i[A+12>>2],A=x,x=0|kA(k,a,0,1),(0|D)>(0|r)&0!=(0|RA(e))&&(1!=(0|A)&&(0|i[k>>2])!=(0|t))){switch(K(m+(((E+5|0)%6|0)<<4)+4|0,M),K(m+(E<<4)+4|0,g),_=+(0|i[s>>2]),n[w>>3]=3*_,n[u>>3]=0,F=-1.5*_,n[p>>3]=F,n[l>>3]=2.598076211353316*_,n[B>>3]=F,n[h>>3]=-2.598076211353316*_,E=0|i[v>>2],0|i[17008+(80*E|0)+(((0|t)==(0|E)?0|i[k>>2]:t)<<2)>>2]){case 1:A=p,t=w;break;case 3:A=B,t=p;break;case 2:A=w,t=B;break;default:A=8;break A}oe(M,g,t,A,b),0|ae(M,b)||0|ae(g,b)||(BA(b,0|i[v>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2]))}if((0|D)<(0|f)&&(K(c,M),BA(M,0|i[k>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])),(0|(D=D+1|0))>=(0|d)){A=3;break}t=0|i[k>>2]}3!=(0|A)?8==(0|A)&&Q(22557,22521,746,22602):I=y}}function yA(A,e,r){A|=0,e|=0,r|=0;var t,n=0,o=0,a=0,f=0,s=0;t=I,I=I+160|0,o=t,f=20336,s=(a=n=t+80|0)+72|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));f=20416,s=(a=o)+72|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));n=(s=0==(0|RA(0|i[e>>2])))?n:o,uA(o=A+4|0),lA(o),0|RA(0|i[e>>2])&&(iA(o),i[e>>2]=1+(0|i[e>>2])),i[r>>2]=i[A>>2],X(o,n,e=r+4|0),J(e),i[r+16>>2]=i[A>>2],X(o,n+12|0,e=r+20|0),J(e),i[r+32>>2]=i[A>>2],X(o,n+24|0,e=r+36|0),J(e),i[r+48>>2]=i[A>>2],X(o,n+36|0,e=r+52|0),J(e),i[r+64>>2]=i[A>>2],X(o,n+48|0,e=r+68|0),J(e),i[r+80>>2]=i[A>>2],X(o,n+60|0,r=r+84|0),J(r),I=t}function EA(A){var e;return e=(A=+A)<0?A+6.283185307179586:A,+(A>=6.283185307179586?e+-6.283185307179586:e)}function xA(A,e){return e|=0,+f(+(+n[(A|=0)>>3]-+n[e>>3]))<17453292519943298e-27?0|(e=+f(+(+n[A+8>>3]-+n[e+8>>3]))<17453292519943298e-27):0|(e=0)}function DA(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))*6371.007180918475}function _A(A,e,r){A|=0,r|=0;var t,i,o,a,f=0,u=0,d=0,g=0,B=0,b=0;return b=+n[(e|=0)>>3],o=+n[A>>3],B=+h(.5*(b-o)),d=+n[e+8>>3],i=+n[A+8>>3],g=+h(.5*(d-i)),t=+l(+o),a=+l(+b),g=2*+p(+ +s(+(g=B*B+g*(a*t*g))),+ +s(+(1-g))),B=+n[r>>3],b=+h(.5*(B-b)),f=+n[r+8>>3],d=+h(.5*(f-d)),u=+l(+B),d=2*+p(+ +s(+(d=b*b+d*(a*u*d))),+ +s(+(1-d))),B=+h(.5*(o-B)),f=+h(.5*(i-f)),f=2*+p(+ +s(+(f=B*B+f*(t*u*f))),+ +s(+(1-f))),4*+w(+ +s(+ +c(.5*(u=.5*(g+d+f)))*+c(.5*(u-g))*+c(.5*(u-d))*+c(.5*(u-f))))}function IA(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),45),M(),127&e|0}function FA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0;if(!(!0&134217728==(-16777216&(e|=0)|0)))return 0|(e=0);if(o=0|Qe(0|(A|=0),0|e,45),M(),(o&=127)>>>0>121)return 0|(e=0);r=0|Qe(0|A,0|e,52),M(),r&=15;do{if(0|r){for(i=1,t=0;;){if(n=0|Qe(0|A,0|e,3*(15-i|0)|0),M(),0!=(0|(n&=7))&(1^t)){if(1==(0|n)&0!=(0|S(o))){a=0,t=13;break}t=1}if(7==(0|n)){a=0,t=13;break}if(!(i>>>0>>0)){t=9;break}i=i+1|0}if(9==(0|t)){if(15!=(0|r))break;return 0|(a=1)}if(13==(0|t))return 0|a}}while(0);for(;;){if(a=0|Qe(0|A,0|e,3*(14-r|0)|0),M(),!(7==(7&a|0)&!0)){a=0,t=13;break}if(!(r>>>0<14)){a=1,t=13;break}r=r+1|0}return 13==(0|t)?0|a:0}function CA(A,e,r){r|=0;var t=0,i=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|(t&=15))>=(0|r)){if((0|t)!=(0|r))if(r>>>0<=15){if(A|=i=0|ye(0|r,0,52),e=0|M()|-15728641&e,(0|t)>(0|r))do{i=0|ye(7,0,3*(14-r|0)|0),r=r+1|0,A|=i,e=0|M()|e}while((0|r)<(0|t))}else e=0,A=0}else e=0,A=0;return k(0|e),0|A}function PA(A,e,r,t){r|=0,t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(f&=15))<=(0|r)){if((0|f)==(0|r))return i[(r=t)>>2]=A,void(i[r+4>>2]=e);if(n=(0|(u=0|ee(7,r-f|0)))/7|0,s=0|Qe(0|A,0|e,45),M(),0|S(127&s)){A:do{if(f)for(a=1;;){if(o=0|Qe(0|A,0|e,3*(15-a|0)|0),M(),0|(o&=7))break A;if(!(a>>>0>>0)){o=0;break}a=a+1|0}else o=0}while(0);a=0==(0|o)}else a=0;if(l=0|ye(f+1|0,0,52),o=0|M()|-15728641&e,PA(e=(l|A)&~(e=0|ye(7,0,0|(s=3*(14-f|0)|0))),f=o&~(0|M()),r,t),o=t+(n<<3)|0,!a)return PA((l=0|ye(1,0,0|s))|e,0|M()|f,r,o),l=o+(n<<3)|0,PA((u=0|ye(2,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(3,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(4,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(5,0,0|s))|e,0|M()|f,r,l),void PA((u=0|ye(6,0,0|s))|e,0|M()|f,r,l+(n<<3)|0);a=o+(n<<3)|0,(0|u)>6&&(_e(0|o,0,(l=(a>>>0>(u=o+8|0)>>>0?a:u)+-1+(0-o)|0)+8&-8|0),o=u+(l>>>3<<3)|0),PA((l=0|ye(2,0,0|s))|e,0|M()|f,r,o),l=o+(n<<3)|0,PA((u=0|ye(3,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(4,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(5,0,0|s))|e,0|M()|f,r,l),PA((u=0|ye(6,0,0|s))|e,0|M()|f,r,l+(n<<3)|0)}}function UA(A,e){var r=0,t=0,i=0;if(i=0|Qe(0|(A|=0),0|(e|=0),45),M(),!(0|S(127&i)))return 0|(i=0);i=0|Qe(0|A,0|e,52),M(),i&=15;A:do{if(i)for(t=1;;){if(r=0|Qe(0|A,0|e,3*(15-t|0)|0),M(),0|(r&=7))break A;if(!(t>>>0>>0)){r=0;break}t=t+1|0}else r=0}while(0);return 0|(i=0==(0|r)&1)}function GA(A,e){var r=0,t=0,i=0;if(i=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(i&=15))return 0|(i=0);for(t=1;;){if(r=0|Qe(0|A,0|e,3*(15-t|0)|0),M(),0|(r&=7)){t=5;break}if(!(t>>>0>>0)){r=0,t=5;break}t=t+1|0}return 5==(0|t)?0|r:0}function SA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0,f=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(f&=15))return f=A,k(0|(a=e)),0|f;for(a=1,r=0;;){t=0|ye(7,0,0|(n=3*(15-a|0)|0)),i=0|M(),o=0|Qe(0|A,0|e,0|n),M(),A=(n=0|ye(0|fA(7&o),0,0|n))|A&~t,e=(o=0|M())|e&~i;A:do{if(!r)if(0==(n&t|0)&0==(o&i|0))r=0;else if(t=0|Qe(0|A,0|e,52),M(),t&=15){r=1;e:for(;;){switch(o=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),7&o){case 1:break e;case 0:break;default:r=1;break A}if(!(r>>>0>>0)){r=1;break A}r=r+1|0}for(r=1;;){if(i=0|Qe(0|A,0|e,0|(o=3*(15-r|0)|0)),M(),n=0|ye(7,0,0|o),e&=~(0|M()),A=A&~n|(o=0|ye(0|fA(7&i),0,0|o)),e=0|e|M(),!(r>>>0>>0)){r=1;break}r=r+1|0}}else r=1}while(0);if(!(a>>>0>>0))break;a=a+1|0}return k(0|e),0|A}function TA(A,e){var r=0,t=0,i=0,n=0,o=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(t&=15))return t=A,k(0|(r=e)),0|t;for(r=1;o=0|Qe(0|A,0|e,0|(n=3*(15-r|0)|0)),M(),i=0|ye(7,0,0|n),e&=~(0|M()),A=(n=0|ye(0|fA(7&o),0,0|n))|A&~i,e=0|M()|e,r>>>0>>0;)r=r+1|0;return k(0|e),0|A}function VA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0,f=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(f&=15))return f=A,k(0|(a=e)),0|f;for(a=1,r=0;;){t=0|ye(7,0,0|(n=3*(15-a|0)|0)),i=0|M(),o=0|Qe(0|A,0|e,0|n),M(),A=(n=0|ye(0|sA(7&o),0,0|n))|A&~t,e=(o=0|M())|e&~i;A:do{if(!r)if(0==(n&t|0)&0==(o&i|0))r=0;else if(t=0|Qe(0|A,0|e,52),M(),t&=15){r=1;e:for(;;){switch(o=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),7&o){case 1:break e;case 0:break;default:r=1;break A}if(!(r>>>0>>0)){r=1;break A}r=r+1|0}for(r=1;;){if(n=0|ye(7,0,0|(i=3*(15-r|0)|0)),o=e&~(0|M()),e=0|Qe(0|A,0|e,0|i),M(),A=A&~n|(e=0|ye(0|sA(7&e),0,0|i)),e=0|o|M(),!(r>>>0>>0)){r=1;break}r=r+1|0}}else r=1}while(0);if(!(a>>>0>>0))break;a=a+1|0}return k(0|e),0|A}function HA(A,e){var r=0,t=0,i=0,n=0,o=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(t&=15))return t=A,k(0|(r=e)),0|t;for(r=1;n=0|ye(7,0,0|(o=3*(15-r|0)|0)),i=e&~(0|M()),e=0|Qe(0|A,0|e,0|o),M(),A=(e=0|ye(0|sA(7&e),0,0|o))|A&~n,e=0|M()|i,r>>>0>>0;)r=r+1|0;return k(0|e),0|A}function RA(A){return 0|(0|(A|=0))%2}function LA(A,e){A|=0;var r,t;return t=I,I=I+16|0,r=t,(e|=0)>>>0<=15&&2146435072!=(2146435072&i[A+4>>2]|0)&&2146435072!=(2146435072&i[A+8+4>>2]|0)?(!function(A,e,r){var t,i;t=I,I=I+16|0,pA(A|=0,e|=0,r|=0,i=t),W(i,r+4|0),I=t}(A,e,r),e=0|function(A,e){A|=0;var r,t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0;if(r=I,I=I+64|0,s=r+40|0,n=r+24|0,o=r+12|0,a=r,ye(0|(e|=0),0,52),t=134225919|M(),!e)return(0|i[A+4>>2])>2||(0|i[A+8>>2])>2||(0|i[A+12>>2])>2?(s=0,k(0|(f=0)),I=r,0|s):(ye(0|V(A),0,45),f=0|M()|t,s=-1,k(0|f),I=r,0|s);if(i[s>>2]=i[A>>2],i[s+4>>2]=i[A+4>>2],i[s+8>>2]=i[A+8>>2],i[s+12>>2]=i[A+12>>2],f=s+4|0,(0|e)>0)for(A=-1;i[n>>2]=i[f>>2],i[n+4>>2]=i[f+4>>2],i[n+8>>2]=i[f+8>>2],1&e?(eA(f),i[o>>2]=i[f>>2],i[o+4>>2]=i[f+4>>2],i[o+8>>2]=i[f+8>>2],tA(o)):(rA(f),i[o>>2]=i[f>>2],i[o+4>>2]=i[f+4>>2],i[o+8>>2]=i[f+8>>2],iA(o)),q(n,o,a),J(a),u=0|ye(7,0,0|(l=3*(15-e|0)|0)),t&=~(0|M()),A=(l=0|ye(0|AA(a),0,0|l))|A&~u,t=0|M()|t,(0|e)>1;)e=e+-1|0;else A=-1;A:do{if((0|i[f>>2])<=2&&(0|i[s+8>>2])<=2&&(0|i[s+12>>2])<=2){if(e=0|ye(0|(n=0|V(s)),0,45),e|=A,A=0|M()|-1040385&t,a=0|H(s),!(0|S(n))){if((0|a)<=0)break;for(o=0;;){if(n=0|Qe(0|e,0|A,52),M(),n&=15)for(t=1;s=0|Qe(0|e,0|A,0|(l=3*(15-t|0)|0)),M(),u=0|ye(7,0,0|l),A&=~(0|M()),e=e&~u|(l=0|ye(0|fA(7&s),0,0|l)),A=0|A|M(),t>>>0>>0;)t=t+1|0;if((0|(o=o+1|0))==(0|a))break A}}o=0|Qe(0|e,0|A,52),M(),o&=15;e:do{if(o){t=1;r:for(;;){switch(l=0|Qe(0|e,0|A,3*(15-t|0)|0),M(),7&l){case 1:break r;case 0:break;default:break e}if(!(t>>>0>>0))break e;t=t+1|0}if(0|R(n,0|i[s>>2]))for(t=1;u=0|ye(7,0,0|(s=3*(15-t|0)|0)),l=A&~(0|M()),A=0|Qe(0|e,0|A,0|s),M(),e=e&~u|(A=0|ye(0|sA(7&A),0,0|s)),A=0|l|M(),t>>>0>>0;)t=t+1|0;else for(t=1;s=0|Qe(0|e,0|A,0|(l=3*(15-t|0)|0)),M(),u=0|ye(7,0,0|l),A&=~(0|M()),e=e&~u|(l=0|ye(0|fA(7&s),0,0|l)),A=0|A|M(),t>>>0>>0;)t=t+1|0}}while(0);if((0|a)>0){t=0;do{e=0|SA(e,A),A=0|M(),t=t+1|0}while((0|t)!=(0|a))}}else e=0,A=0}while(0);return l=e,k(0|(u=A)),I=r,0|l}(r,e),A=0|M()):(A=0,e=0),k(0|A),I=t,0|e}function zA(A,e,r){var t,n=0,o=0,a=0;if(t=(r|=0)+4|0,o=0|Qe(0|(A|=0),0|(e|=0),52),M(),o&=15,a=0|Qe(0|A,0|e,45),M(),n=0==(0|o),0|S(127&a)){if(n)return 0|(a=1);n=1}else{if(n)return 0|(a=0);n=0==(0|i[t>>2])&&0==(0|i[r+8>>2])?0!=(0|i[r+12>>2])&1:1}for(r=1;1&r?tA(t):iA(t),a=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),nA(t,7&a),r>>>0>>0;)r=r+1|0;return 0|n}function YA(A,e,r){r|=0;var t,n,o=0,a=0,f=0,s=0,u=0,l=0;n=I,I=I+16|0,t=n,l=0|Qe(0|(A|=0),0|(e|=0),45),M(),l&=127;A:do{if(0!=(0|S(l))&&(f=0|Qe(0|A,0|e,52),M(),0!=(0|(f&=15)))){o=1;e:for(;;){switch(u=0|Qe(0|A,0|e,3*(15-o|0)|0),M(),7&u){case 5:break e;case 0:break;default:o=e;break A}if(!(o>>>0>>0)){o=e;break A}o=o+1|0}for(a=1,o=e;s=0|ye(7,0,0|(e=3*(15-a|0)|0)),u=o&~(0|M()),o=0|Qe(0|A,0|o,0|e),M(),A=A&~s|(o=0|ye(0|sA(7&o),0,0|e)),o=0|u|M(),a>>>0>>0;)a=a+1|0}else o=e}while(0);if(u=7728+(28*l|0)|0,i[r>>2]=i[u>>2],i[r+4>>2]=i[u+4>>2],i[r+8>>2]=i[u+8>>2],i[r+12>>2]=i[u+12>>2],0|zA(A,o,r)){if(s=r+4|0,i[t>>2]=i[s>>2],i[t+4>>2]=i[s+4>>2],i[t+8>>2]=i[s+8>>2],f=0|Qe(0|A,0|o,52),M(),u=15&f,1&f?(iA(s),f=u+1|0):f=u,0|S(l)){A:do{if(u)for(e=1;;){if(a=0|Qe(0|A,0|o,3*(15-e|0)|0),M(),0|(a&=7)){o=a;break A}if(!(e>>>0>>0)){o=0;break}e=e+1|0}else o=0}while(0);o=4==(0|o)&1}else o=0;if(0|kA(r,f,o,0)){if(0|S(l))do{}while(0!=(0|kA(r,f,0,0)));(0|f)!=(0|u)&&rA(s)}else(0|f)!=(0|u)&&(i[s>>2]=i[t>>2],i[s+4>>2]=i[t+4>>2],i[s+8>>2]=i[t+8>>2]);I=n}else I=n}function OA(A,e,r){r|=0;var t,i;t=I,I=I+16|0,YA(A|=0,e|=0,i=t),e=0|Qe(0|A,0|e,52),M(),bA(i,15&e,r),I=t}function jA(A,e,r){r|=0;var t,i,n=0,o=0;i=I,I=I+16|0,YA(A|=0,e|=0,t=i),n=0|Qe(0|A,0|e,45),M(),n=0==(0|S(127&n)),o=0|Qe(0|A,0|e,52),M(),o&=15;A:do{if(!n){if(0|o)for(n=1;;){if(!(0==((0|ye(7,0,3*(15-n|0)|0))&A|0)&0==((0|M())&e|0)))break A;if(!(n>>>0>>0))break;n=n+1|0}return vA(t,o,0,5,r),void(I=i)}}while(0);QA(t,o,0,6,r),I=i}function NA(A,e){e|=0;var r,t=0,n=0,o=0,a=0,f=0,s=0;if(ye(0|(A|=0),0,52),r=134225919|M(),(0|A)<1){n=0,t=0;do{0|S(n)&&(ye(0|n,0,45),f=0|r|M(),i[(A=e+(t<<3)|0)>>2]=-1,i[A+4>>2]=f,t=t+1|0),n=n+1|0}while(122!=(0|n))}else{f=0,t=0;do{if(0|S(f)){for(ye(0|f,0,45),n=1,o=-1,a=0|r|M();o&=~(s=0|ye(7,0,3*(15-n|0)|0)),a&=~(0|M()),(0|n)!=(0|A);)n=n+1|0;i[(s=e+(t<<3)|0)>>2]=o,i[s+4>>2]=a,t=t+1|0}f=f+1|0}while(122!=(0|f))}}function ZA(A,e,r,t){var n,o=0,a=0,f=0,s=0,u=0;if(n=I,I=I+64|0,f=n,(0|(A|=0))==(0|(r|=0))&(0|(e|=0))==(0|(t|=0))|!1|134217728!=(2013265920&e|0)|!1|134217728!=(2013265920&t|0))return I=n,0|(f=0);if(o=0|Qe(0|A,0|e,52),M(),o&=15,a=0|Qe(0|r,0|t,52),M(),(0|o)!=(15&a|0))return I=n,0|(f=0);if(a=o+-1|0,o>>>0>1&&(u=0|CA(A,e,a),s=0|M(),(0|u)==(0|(a=0|CA(r,t,a)))&(0|s)==(0|M()))){if(o=0|Qe(0|A,0|e,0|(a=3*(15^o)|0)),M(),o&=7,a=0|Qe(0|r,0|t,0|a),M(),0==(0|o)|0==(0|(a&=7)))return I=n,0|(u=1);if((0|i[21136+(o<<2)>>2])==(0|a))return I=n,0|(u=1);if((0|i[21168+(o<<2)>>2])==(0|a))return I=n,0|(u=1)}a=(o=f)+56|0;do{i[o>>2]=0,o=o+4|0}while((0|o)<(0|a));return F(A,e,1,f),o=(0|i[(u=f)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+8|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+16|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+24|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+32|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+40|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)?1:1&((0|i[(o=f+48|0)>>2])==(0|r)?(0|i[o+4>>2])==(0|t):0),I=n,0|(u=o)}function WA(A,e,r){r|=0;var t,n,o,a,f=0;if(o=I,I=I+16|0,n=o,f=0|Qe(0|(A|=0),0|(e|=0),56),M(),-1==(0|(e=0|function(A,e,r){r|=0;var t=0,n=0;if(t=0|UA(A=A|0,e=e|0),(r+-1|0)>>>0>5)return 0|(r=-1);if(1==(0|r)&(n=0!=(0|t)))return 0|(r=-1);return t=0|function(A,e){var r=0,t=0,n=0,o=0,a=0,f=0,s=0,u=0;if(u=I,I=I+32|0,o=u,YA(A=A|0,e=e|0,n=u+16|0),a=0|IA(A,e),s=0|GA(A,e),function(A,e){A=7728+(28*(A|=0)|0)|0,i[(e|=0)>>2]=i[A>>2],i[e+4>>2]=i[A+4>>2],i[e+8>>2]=i[A+8>>2],i[e+12>>2]=i[A+12>>2]}(a,o),e=0|function(A,e){A|=0;var r=0,t=0;if((e|=0)>>>0>20)return-1;do{if((0|i[11152+(216*e|0)>>2])!=(0|A))if((0|i[11152+(216*e|0)+8>>2])!=(0|A))if((0|i[11152+(216*e|0)+16>>2])!=(0|A))if((0|i[11152+(216*e|0)+24>>2])!=(0|A))if((0|i[11152+(216*e|0)+32>>2])!=(0|A))if((0|i[11152+(216*e|0)+40>>2])!=(0|A))if((0|i[11152+(216*e|0)+48>>2])!=(0|A))if((0|i[11152+(216*e|0)+56>>2])!=(0|A))if((0|i[11152+(216*e|0)+64>>2])!=(0|A))if((0|i[11152+(216*e|0)+72>>2])!=(0|A))if((0|i[11152+(216*e|0)+80>>2])!=(0|A))if((0|i[11152+(216*e|0)+88>>2])!=(0|A))if((0|i[11152+(216*e|0)+96>>2])!=(0|A))if((0|i[11152+(216*e|0)+104>>2])!=(0|A))if((0|i[11152+(216*e|0)+112>>2])!=(0|A))if((0|i[11152+(216*e|0)+120>>2])!=(0|A))if((0|i[11152+(216*e|0)+128>>2])!=(0|A)){if((0|i[11152+(216*e|0)+136>>2])!=(0|A)){if((0|i[11152+(216*e|0)+144>>2])==(0|A)){A=0,r=2,t=0;break}if((0|i[11152+(216*e|0)+152>>2])==(0|A)){A=0,r=2,t=1;break}if((0|i[11152+(216*e|0)+160>>2])==(0|A)){A=0,r=2,t=2;break}if((0|i[11152+(216*e|0)+168>>2])==(0|A)){A=1,r=2,t=0;break}if((0|i[11152+(216*e|0)+176>>2])==(0|A)){A=1,r=2,t=1;break}if((0|i[11152+(216*e|0)+184>>2])==(0|A)){A=1,r=2,t=2;break}if((0|i[11152+(216*e|0)+192>>2])==(0|A)){A=2,r=2,t=0;break}if((0|i[11152+(216*e|0)+200>>2])==(0|A)){A=2,r=2,t=1;break}if((0|i[11152+(216*e|0)+208>>2])==(0|A)){A=2,r=2,t=2;break}return-1}A=2,r=1,t=2}else A=2,r=1,t=1;else A=2,r=1,t=0;else A=1,r=1,t=2;else A=1,r=1,t=1;else A=1,r=1,t=0;else A=0,r=1,t=2;else A=0,r=1,t=1;else A=0,r=1,t=0;else A=2,r=0,t=2;else A=2,r=0,t=1;else A=2,r=0,t=0;else A=1,r=0,t=2;else A=1,r=0,t=1;else A=1,r=0,t=0;else A=0,r=0,t=2;else A=0,r=0,t=1;else A=0,r=0,t=0}while(0);return 0|i[11152+(216*e|0)+(72*r|0)+(24*A|0)+(t<<3)+4>>2]}(a,0|i[n>>2]),!(0|S(a)))return I=u,0|(s=e);switch(0|a){case 4:A=0,r=14;break;case 14:A=1,r=14;break;case 24:A=2,r=14;break;case 38:A=3,r=14;break;case 49:A=4,r=14;break;case 58:A=5,r=14;break;case 63:A=6,r=14;break;case 72:A=7,r=14;break;case 83:A=8,r=14;break;case 97:A=9,r=14;break;case 107:A=10,r=14;break;case 117:A=11,r=14;break;default:f=0,t=0}14==(0|r)&&(f=0|i[22096+(24*A|0)+8>>2],t=0|i[22096+(24*A|0)+16>>2]);(0|(A=0|i[n>>2]))!=(0|i[o>>2])&&(a=0|T(a))|(0|(A=0|i[n>>2]))==(0|t)&&(e=(e+1|0)%6|0);if(3==(0|s)&(0|A)==(0|t))return I=u,0|(s=(e+5|0)%6|0);if(!(5==(0|s)&(0|A)==(0|f)))return I=u,0|(s=e);return I=u,0|(s=(e+1|0)%6|0)}(A,e),n?0|(r=(5-t+(0|i[22384+(r<<2)>>2])|0)%5|0):0|(r=(6-t+(0|i[22416+(r<<2)>>2])|0)%6|0)}(t=(a=!0&268435456==(2013265920&e|0))?A:0,A=a?-2130706433&e|134217728:0,7&f))))return i[r>>2]=0,void(I=o);YA(t,A,n),f=0|Qe(0|t,0|A,52),M(),f&=15,0|UA(t,A)?vA(n,f,e,2,r):QA(n,f,e,2,r),I=o}function JA(A){A|=0;var e,r,t=0;return(e=0|be(1,12))||Q(22691,22646,49,22704),0|(t=0|i[(r=A+4|0)>>2])?(i[(t=t+8|0)>>2]=e,i[r>>2]=e,0|e):(0|i[A>>2]&&Q(22721,22646,61,22744),i[(t=A)>>2]=e,i[r>>2]=e,0|e)}function KA(A,e){A|=0,e|=0;var r,t;return(t=0|pe(24))||Q(22758,22646,78,22772),i[t>>2]=i[e>>2],i[t+4>>2]=i[e+4>>2],i[t+8>>2]=i[e+8>>2],i[t+12>>2]=i[e+12>>2],i[t+16>>2]=0,0|(r=0|i[(e=A+4|0)>>2])?(i[r+16>>2]=t,i[e>>2]=t,0|t):(0|i[A>>2]&&Q(22787,22646,82,22772),i[A>>2]=t,i[e>>2]=t,0|t)}function XA(A){var e,r,t=0,o=0,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,y=0,E=0,x=0,D=0,_=0,I=0,F=0,C=0,P=0,U=0,G=0,S=0;if(0|i[(s=(A|=0)+8|0)>>2])return 0|(S=1);if(!(a=0|i[A>>2]))return 0|(S=0);t=a,o=0;do{o=o+1|0,t=0|i[t+8>>2]}while(0!=(0|t));if(o>>>0<2)return 0|(S=0);(r=0|pe(o<<2))||Q(22807,22646,317,22826),(e=0|pe(o<<5))||Q(22848,22646,321,22826),i[A>>2]=0,i[(D=A+4|0)>>2]=0,i[s>>2]=0,o=0,U=0,x=0,w=0;A:for(;;){if(g=0|i[a>>2]){u=0,l=g;do{if(c=+n[l+8>>3],t=l,l=0|i[l+16>>2],h=+n[(s=(d=0==(0|l))?g:l)+8>>3],+f(+(c-h))>3.141592653589793){S=14;break}u+=(h-c)*(+n[t>>3]+ +n[s>>3])}while(!d);if(14==(0|S)){S=0,u=0,t=g;do{E=+n[t+8>>3],C=0|i[(P=t+16|0)>>2],y=+n[(C=0==(0|C)?g:C)+8>>3],u+=(+n[t>>3]+ +n[C>>3])*((y<0?y+6.283185307179586:y)-(E<0?E+6.283185307179586:E)),t=0|i[(0==(0|t)?a:P)>>2]}while(0!=(0|t))}u>0?(i[r+(U<<2)>>2]=a,U=U+1|0,s=x,t=w):S=19}else S=19;if(19==(0|S)){S=0;do{if(!o){if(w){s=D,l=w+8|0,t=a,o=A;break}if(0|i[A>>2]){S=27;break A}s=D,l=A,t=a,o=A;break}if(0|i[(t=o+8|0)>>2]){S=21;break A}if(!(o=0|be(1,12))){S=23;break A}i[t>>2]=o,s=o+4|0,l=o,t=w}while(0);if(i[l>>2]=a,i[s>>2]=a,l=e+(x<<5)|0,d=0|i[a>>2]){for(n[(g=e+(x<<5)+8|0)>>3]=17976931348623157e292,n[(w=e+(x<<5)+24|0)>>3]=17976931348623157e292,n[l>>3]=-17976931348623157e292,n[(p=e+(x<<5)+16|0)>>3]=-17976931348623157e292,k=17976931348623157e292,M=-17976931348623157e292,s=0,B=d,c=17976931348623157e292,v=17976931348623157e292,m=-17976931348623157e292,h=-17976931348623157e292;u=+n[B>>3],E=+n[B+8>>3],B=0|i[B+16>>2],y=+n[((b=0==(0|B))?d:B)+8>>3],u>3]=u,c=u),E>3]=E,v=E),u>m?n[l>>3]=u:u=m,E>h&&(n[p>>3]=E,h=E),k=E>0&EM?E:M,s|=+f(+(E-y))>3.141592653589793,!b;)m=u;s&&(n[p>>3]=M,n[w>>3]=k)}else i[l>>2]=0,i[l+4>>2]=0,i[l+8>>2]=0,i[l+12>>2]=0,i[l+16>>2]=0,i[l+20>>2]=0,i[l+24>>2]=0,i[l+28>>2]=0;s=x+1|0}if(a=0|i[(P=a+8|0)>>2],i[P>>2]=0,!a){S=45;break}x=s,w=t}if(21==(0|S))Q(22624,22646,35,22658);else if(23==(0|S))Q(22678,22646,37,22658);else if(27==(0|S))Q(22721,22646,61,22744);else if(45==(0|S)){A:do{if((0|U)>0){for(P=0==(0|s),F=s<<2,C=0==(0|A),I=0,t=0;;){if(_=0|i[r+(I<<2)>>2],P)S=73;else{if(!(x=0|pe(F))){S=50;break}if(!(D=0|pe(F))){S=52;break}e:do{if(C)o=0;else{for(s=0,o=0,l=A;a=e+(s<<5)|0,0|qA(0|i[l>>2],a,0|i[_>>2])?(i[x+(o<<2)>>2]=l,i[D+(o<<2)>>2]=a,b=o+1|0):b=o,l=0|i[l+8>>2];)s=s+1|0,o=b;if((0|b)>0)if(a=0|i[x>>2],1==(0|b))o=a;else for(p=0,B=-1,o=a,w=a;;){for(d=0|i[w>>2],a=0,l=0;g=(0|(s=0|i[i[x+(l<<2)>>2]>>2]))==(0|d)?a:a+(1&(0|qA(s,0|i[D+(l<<2)>>2],0|i[d>>2])))|0,(0|(l=l+1|0))!=(0|b);)a=g;if(o=(s=(0|g)>(0|B))?w:o,(0|(a=p+1|0))==(0|b))break e;p=a,B=s?g:B,w=0|i[x+(a<<2)>>2]}else o=0}}while(0);if(Be(x),Be(D),o){if(a=0|i[(s=o+4|0)>>2])o=a+8|0;else if(0|i[o>>2]){S=70;break}i[o>>2]=_,i[s>>2]=_}else S=73}if(73==(0|S)){if(S=0,0|(t=0|i[_>>2]))do{D=t,t=0|i[t+16>>2],Be(D)}while(0!=(0|t));Be(_),t=2}if((0|(I=I+1|0))>=(0|U)){G=t;break A}}50==(0|S)?Q(22863,22646,249,22882):52==(0|S)?Q(22901,22646,252,22882):70==(0|S)&&Q(22721,22646,61,22744)}else G=0}while(0);return Be(r),Be(e),0|(S=G)}return 0}function qA(A,e,r){A|=0;var t,o=0,a=0,f=0,s=0,u=0,l=0,h=0;if(!(0|O(e|=0,r|=0)))return 0|(A=0);if(e=0|Y(e),t=+n[r>>3],o=e&(o=+n[r+8>>3])<0?o+6.283185307179586:o,!(A=0|i[A>>2]))return 0|(A=0);if(e){e=0,r=A;A:for(;;){for(;s=+n[r>>3],l=+n[r+8>>3],h=0|i[(r=r+16|0)>>2],f=+n[(h=0==(0|h)?A:h)>>3],a=+n[h+8>>3],s>f?(u=s,s=l):(u=f,f=s,s=a,a=l),tu;)if(!(r=0|i[r>>2])){r=22;break A}if(o=(s=s<0?s+6.283185307179586:s)==o|(l=a<0?a+6.283185307179586:a)==o?o+-2220446049250313e-31:o,((l+=(t-f)/(u-f)*(s-l))<0?l+6.283185307179586:l)>o&&(e^=1),!(r=0|i[r>>2])){r=22;break}}if(22==(0|r))return 0|e}else{e=0,r=A;A:for(;;){for(;s=+n[r>>3],l=+n[r+8>>3],h=0|i[(r=r+16|0)>>2],f=+n[(h=0==(0|h)?A:h)>>3],a=+n[h+8>>3],s>f?(u=s,s=l):(u=f,f=s,s=a,a=l),tu;)if(!(r=0|i[r>>2])){r=22;break A}if(a+(t-f)/(u-f)*(s-a)>(o=s==o|a==o?o+-2220446049250313e-31:o)&&(e^=1),!(r=0|i[r>>2])){r=22;break}}if(22==(0|r))return 0|e}return 0}function $A(A,e,r,n,o){r|=0,n|=0,o|=0;var a,f,s,u,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0;if(u=I,I=I+32|0,v=u+16|0,s=u,l=0|Qe(0|(A|=0),0|(e|=0),52),M(),l&=15,p=0|Qe(0|r,0|n,52),M(),(0|l)!=(15&p|0))return I=u,0|(v=1);if(g=0|Qe(0|A,0|e,45),M(),g&=127,w=0|Qe(0|r,0|n,45),M(),p=(0|g)!=(0|(w&=127))){if(7==(0|(c=0|z(g,w))))return I=u,0|(v=2);7==(0|(d=0|z(w,g)))?Q(22925,22949,151,22959):(B=c,h=d)}else B=0,h=0;a=0|S(g),f=0|S(w),i[v>>2]=0,i[v+4>>2]=0,i[v+8>>2]=0,i[v+12>>2]=0;do{if(B){if(c=(0|(w=0|i[4304+(28*g|0)+(B<<2)>>2]))>0,f)if(c){g=0,d=r,c=n;do{d=0|VA(d,c),c=0|M(),1==(0|(h=0|sA(h)))&&(h=0|sA(1)),g=g+1|0}while((0|g)!=(0|w));w=h,g=d,d=c}else w=h,g=r,d=n;else if(c){g=0,d=r,c=n;do{d=0|HA(d,c),c=0|M(),h=0|sA(h),g=g+1|0}while((0|g)!=(0|w));w=h,g=d,d=c}else w=h,g=r,d=n;if(zA(g,d,v),p||Q(22972,22949,181,22959),(c=0!=(0|a))&(h=0!=(0|f))&&Q(22999,22949,182,22959),c){if(h=0|GA(A,e),0|t[22032+(7*h|0)+B>>0]){l=3;break}g=d=0|i[21200+(28*h|0)+(B<<2)>>2],b=26}else if(h){if(h=0|GA(g,d),0|t[22032+(7*h|0)+w>>0]){l=4;break}g=0,d=0|i[21200+(28*w|0)+(h<<2)>>2],b=26}else h=0;if(26==(0|b))if((0|d)<=-1&&Q(23030,22949,212,22959),(0|g)<=-1&&Q(23053,22949,213,22959),(0|d)>0){c=v+4|0,h=0;do{aA(c),h=h+1|0}while((0|h)!=(0|d));h=g}else h=g;if(i[s>>2]=0,i[s+4>>2]=0,i[s+8>>2]=0,nA(s,B),0|l)for(;0|RA(l)?tA(s):iA(s),(0|l)>1;)l=l+-1|0;if((0|h)>0){l=0;do{aA(s),l=l+1|0}while((0|l)!=(0|h))}X(b=v+4|0,s,b),J(b),b=50}else if(zA(r,n,v),0!=(0|a)&0!=(0|f))if((0|w)!=(0|g)&&Q(23077,22949,243,22959),h=0|GA(A,e),l=0|GA(r,n),0|t[22032+(7*h|0)+l>>0])l=5;else if((0|(h=0|i[21200+(28*h|0)+(l<<2)>>2]))>0){c=v+4|0,l=0;do{aA(c),l=l+1|0}while((0|l)!=(0|h));b=50}else b=50;else b=50}while(0);return 50==(0|b)&&(l=v+4|0,i[o>>2]=i[l>>2],i[o+4>>2]=i[l+4>>2],i[o+8>>2]=i[l+8>>2],l=0),I=u,0|(v=l)}function Ae(A,e,r,t){r|=0,t|=0;var n,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0;if(o=I,I=I+48|0,s=o+36|0,u=o+24|0,l=o+12|0,h=o,f=0|Qe(0|(A|=0),0|(e|=0),52),M(),f&=15,d=0|Qe(0|A,0|e,45),M(),n=0|S(d&=127),ye(0|f,0,52),p=134225919|M(),i[(w=t)>>2]=-1,i[w+4>>2]=p,!f)return(0|i[r>>2])>1||(0|i[r+4>>2])>1||(0|i[r+8>>2])>1||127==(0|(a=0|L(d,0|AA(r))))?(I=o,0|(p=1)):(g=0|ye(0|a,0,45),w=0|M(),w=-1040385&i[(d=t)+4>>2]|w,i[(p=t)>>2]=i[d>>2]|g,i[p+4>>2]=w,I=o,0|(p=0));for(i[s>>2]=i[r>>2],i[s+4>>2]=i[r+4>>2],i[s+8>>2]=i[r+8>>2];i[u>>2]=i[s>>2],i[u+4>>2]=i[s+4>>2],i[u+8>>2]=i[s+8>>2],0|RA(f)?(eA(s),i[l>>2]=i[s>>2],i[l+4>>2]=i[s+4>>2],i[l+8>>2]=i[s+8>>2],tA(l)):(rA(s),i[l>>2]=i[s>>2],i[l+4>>2]=i[s+4>>2],i[l+8>>2]=i[s+8>>2],iA(l)),q(u,l,h),J(h),B=0|i[(w=t)>>2],w=0|i[w+4>>2],r=0|ye(7,0,0|(b=3*(15-f|0)|0)),w&=~(0|M()),b=0|ye(0|AA(h),0,0|b),w=0|M()|w,i[(p=t)>>2]=b|B&~r,i[p+4>>2]=w,(0|f)>1;)f=f+-1|0;A:do{if((0|i[s>>2])<=1&&(0|i[s+4>>2])<=1&&(0|i[s+8>>2])<=1){h=127==(0|(u=0|L(d,f=0|AA(s))))?0:0|S(u);e:do{if(f){if(n){if(s=21408+(28*(0|GA(A,e))|0)+(f<<2)|0,(0|(s=0|i[s>>2]))>0){r=0;do{f=0|fA(f),r=r+1|0}while((0|r)!=(0|s))}if(1==(0|f)){a=3;break A}127==(0|(r=0|L(d,f)))&&Q(23104,22949,376,23134),0|S(r)?Q(23147,22949,377,23134):(g=s,c=f,a=r)}else g=0,c=f,a=u;if((0|(l=0|i[4304+(28*d|0)+(c<<2)>>2]))<=-1&&Q(23178,22949,384,23134),!h){if((0|g)<=-1&&Q(23030,22949,417,23134),0|g){f=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];do{r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,f=f+1|0}while((0|f)<(0|g))}if((0|l)<=0){f=54;break}for(f=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];;)if(r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,(0|(f=f+1|0))==(0|l)){f=54;break e}}if(7==(0|(u=0|z(a,d)))&&Q(22925,22949,393,23134),r=0|i[(f=t)>>2],f=0|i[f+4>>2],(0|l)>0){s=0;do{r=0|TA(r,f),f=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=f,s=s+1|0}while((0|s)!=(0|l))}if(r=0|GA(r,f),b=0|T(a),(0|(r=0|i[(b?21824:21616)+(28*u|0)+(r<<2)>>2]))<=-1&&Q(23030,22949,412,23134),r){f=0,s=0|i[(u=t)>>2],u=0|i[u+4>>2];do{s=0|SA(s,u),u=0|M(),i[(b=t)>>2]=s,i[b+4>>2]=u,f=f+1|0}while((0|f)<(0|r));f=54}else f=54}else if(0!=(0|n)&0!=(0|h))if(f=21408+(28*(b=0|GA(A,e))|0)+((0|GA(0|i[(f=t)>>2],0|i[f+4>>2]))<<2)|0,(0|(f=0|i[f>>2]))<=-1&&Q(23201,22949,433,23134),f){a=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];do{r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,a=a+1|0}while((0|a)<(0|f));a=u,f=54}else a=u,f=55;else a=u,f=54}while(0);if(54==(0|f)&&h&&(f=55),55==(0|f)&&1==(0|GA(0|i[(b=t)>>2],0|i[b+4>>2]))){a=4;break}p=0|i[(b=t)>>2],b=-1040385&i[b+4>>2],B=0|ye(0|a,0,45),b=0|b|M(),i[(a=t)>>2]=p|B,i[a+4>>2]=b,a=0}else a=2}while(0);return I=o,0|(b=a)}function ee(A,e){var r=0;if(!(e|=0))return 0|(r=1);r=A|=0,A=1;do{A=0|b(0==(1&e|0)?1:r,A),e>>=1,r=0|b(r,r)}while(0!=(0|e));return 0|A}function re(A,e,r){A|=0;var t,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0;if(!(0|O(e|=0,r|=0)))return 0|(d=0);if(e=0|Y(e),o=+n[r>>3],a=e&(a=+n[r+8>>3])<0?a+6.283185307179586:a,(0|(d=0|i[A>>2]))<=0)return 0|(d=0);if(t=0|i[A+4>>2],e){e=0,r=-1,A=0;A:for(;;){for(c=A;u=+n[t+(c<<4)>>3],h=+n[t+(c<<4)+8>>3],s=+n[t+((A=(r+2|0)%(0|d)|0)<<4)>>3],f=+n[t+(A<<4)+8>>3],u>s?(l=u,u=h):(l=s,s=u,u=f,f=h),ol;){if(!((0|(r=c+1|0))<(0|d))){r=22;break A}A=c,c=r,r=A}if(a=(u=u<0?u+6.283185307179586:u)==a|(h=f<0?f+6.283185307179586:f)==a?a+-2220446049250313e-31:a,((h+=(o-s)/(l-s)*(u-h))<0?h+6.283185307179586:h)>a&&(e^=1),(0|(A=c+1|0))>=(0|d)){r=22;break}r=c}if(22==(0|r))return 0|e}else{e=0,r=-1,A=0;A:for(;;){for(c=A;u=+n[t+(c<<4)>>3],h=+n[t+(c<<4)+8>>3],s=+n[t+((A=(r+2|0)%(0|d)|0)<<4)>>3],f=+n[t+(A<<4)+8>>3],u>s?(l=u,u=h):(l=s,s=u,u=f,f=h),ol;){if(!((0|(r=c+1|0))<(0|d))){r=22;break A}A=c,c=r,r=A}if(f+(o-s)/(l-s)*(u-f)>(a=u==a|f==a?a+-2220446049250313e-31:a)&&(e^=1),(0|(A=c+1|0))>=(0|d)){r=22;break}r=c}if(22==(0|r))return 0|e}return 0}function te(A,e){e|=0;var r,t,o,a,s,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0;if(!(t=0|i[(A|=0)>>2]))return i[e>>2]=0,i[e+4>>2]=0,i[e+8>>2]=0,i[e+12>>2]=0,i[e+16>>2]=0,i[e+20>>2]=0,i[e+24>>2]=0,void(i[e+28>>2]=0);if(n[(o=e+8|0)>>3]=17976931348623157e292,n[(a=e+24|0)>>3]=17976931348623157e292,n[e>>3]=-17976931348623157e292,n[(s=e+16|0)>>3]=-17976931348623157e292,!((0|t)<=0)){for(r=0|i[A+4>>2],p=17976931348623157e292,B=-17976931348623157e292,b=0,A=-1,c=17976931348623157e292,d=17976931348623157e292,w=-17976931348623157e292,l=-17976931348623157e292,v=0;u=+n[r+(v<<4)>>3],g=+n[r+(v<<4)+8>>3],h=+n[r+(((0|(A=A+2|0))==(0|t)?0:A)<<4)+8>>3],u>3]=u,c=u),g>3]=g,d=g),u>w?n[e>>3]=u:u=w,g>l&&(n[s>>3]=g,l=g),p=g>0&gB?g:B,b|=+f(+(g-h))>3.141592653589793,(0|(A=v+1|0))!=(0|t);)m=v,w=u,v=A,A=m;b&&(n[s>>3]=B,n[a>>3]=p)}}function ie(A,e){e|=0;var r,t=0,o=0,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,Q=0,y=0,E=0;if(B=0|i[(A|=0)>>2]){if(n[(b=e+8|0)>>3]=17976931348623157e292,n[(v=e+24|0)>>3]=17976931348623157e292,n[e>>3]=-17976931348623157e292,n[(m=e+16|0)>>3]=-17976931348623157e292,(0|B)>0){for(a=0|i[A+4>>2],w=17976931348623157e292,p=-17976931348623157e292,o=0,t=-1,h=17976931348623157e292,c=17976931348623157e292,g=-17976931348623157e292,u=-17976931348623157e292,k=0;s=+n[a+(k<<4)>>3],d=+n[a+(k<<4)+8>>3],l=+n[a+(((0|(y=t+2|0))==(0|B)?0:y)<<4)+8>>3],s>3]=s,h=s),d>3]=d,c=d),s>g?n[e>>3]=s:s=g,d>u&&(n[m>>3]=d,u=d),w=d>0&dp?d:p,o|=+f(+(d-l))>3.141592653589793,(0|(t=k+1|0))!=(0|B);)y=k,g=s,k=t,t=y;o&&(n[m>>3]=p,n[v>>3]=w)}}else i[e>>2]=0,i[e+4>>2]=0,i[e+8>>2]=0,i[e+12>>2]=0,i[e+16>>2]=0,i[e+20>>2]=0,i[e+24>>2]=0,i[e+28>>2]=0;if(!((0|(t=0|i[(y=A+8|0)>>2]))<=0)){r=A+12|0,Q=0;do{if(a=0|i[r>>2],o=Q,v=e+((Q=Q+1|0)<<5)|0,m=0|i[a+(o<<3)>>2]){if(n[(k=e+(Q<<5)+8|0)>>3]=17976931348623157e292,n[(A=e+(Q<<5)+24|0)>>3]=17976931348623157e292,n[v>>3]=-17976931348623157e292,n[(M=e+(Q<<5)+16|0)>>3]=-17976931348623157e292,(0|m)>0){for(B=0|i[a+(o<<3)+4>>2],w=17976931348623157e292,p=-17976931348623157e292,a=0,o=-1,b=0,h=17976931348623157e292,c=17976931348623157e292,d=-17976931348623157e292,u=-17976931348623157e292;s=+n[B+(b<<4)>>3],g=+n[B+(b<<4)+8>>3],l=+n[B+(((0|(o=o+2|0))==(0|m)?0:o)<<4)+8>>3],s>3]=s,h=s),g>3]=g,c=g),s>d?n[v>>3]=s:s=d,g>u&&(n[M>>3]=g,u=g),w=g>0&gp?g:p,a|=+f(+(g-l))>3.141592653589793,(0|(o=b+1|0))!=(0|m);)E=b,b=o,d=s,o=E;a&&(n[M>>3]=p,n[A>>3]=w)}}else i[v>>2]=0,i[v+4>>2]=0,i[v+8>>2]=0,i[v+12>>2]=0,i[v+16>>2]=0,i[v+20>>2]=0,i[v+24>>2]=0,i[v+28>>2]=0,t=0|i[y>>2]}while((0|Q)<(0|t))}}function ne(A,e,r){var t=0,n=0,o=0;if(!(0|re(A|=0,e|=0,r|=0)))return 0|(n=0);if((0|i[(n=A+8|0)>>2])<=0)return 0|(n=1);for(t=A+12|0,A=0;;){if(o=A,A=A+1|0,0|re((0|i[t>>2])+(o<<3)|0,e+(A<<5)|0,r)){A=0,t=6;break}if((0|A)>=(0|i[n>>2])){A=1,t=6;break}}return 6==(0|t)?0|A:0}function oe(A,e,r,t,i){e|=0,r|=0,t|=0,i|=0;var o,a,f,s,u,l,h,c=0;s=+n[(A|=0)>>3],f=+n[e>>3]-s,a=+n[A+8>>3],o=+n[e+8>>3]-a,l=+n[r>>3],c=((c=+n[t>>3]-l)*(a-(h=+n[r+8>>3]))-(s-l)*(u=+n[t+8>>3]-h))/(f*u-o*c),n[i>>3]=s+f*c,n[i+8>>3]=a+o*c}function ae(A,e){return e|=0,+n[(A|=0)>>3]!=+n[e>>3]?0|(e=0):0|(e=+n[A+8>>3]==+n[e+8>>3])}function fe(A,e){e|=0;var r,t,i;return+((i=+n[(A|=0)>>3]-+n[e>>3])*i+(t=+n[A+8>>3]-+n[e+8>>3])*t+(r=+n[A+16>>3]-+n[e+16>>3])*r)}function se(A,e,r){A|=0,r|=0;var t=0;(0|(e|=0))>0?(t=0|be(e,4),i[A>>2]=t,t||Q(23230,23253,40,23267)):i[A>>2]=0,i[A+4>>2]=e,i[A+8>>2]=0,i[A+12>>2]=r}function ue(A){var e,r,t,o=0,a=0,s=0,l=0;e=(A|=0)+4|0,r=A+12|0,t=A+8|0;A:for(;;){for(a=0|i[e>>2],o=0;;){if((0|o)>=(0|a))break A;if(s=0|i[A>>2],l=0|i[s+(o<<2)>>2])break;o=o+1|0}o=s+(~~(+f(+ +u(10,+ +(15-(0|i[r>>2])|0))*(+n[l>>3]+ +n[l+8>>3]))%+(0|a))>>>0<<2)|0,a=0|i[o>>2];e:do{if(0|a){if(s=l+32|0,(0|a)==(0|l))i[o>>2]=i[s>>2];else{if(!(o=0|i[(a=a+32|0)>>2]))break;for(;(0|o)!=(0|l);)if(!(o=0|i[(a=o+32|0)>>2]))break e;i[a>>2]=i[s>>2]}Be(l),i[t>>2]=(0|i[t>>2])-1}}while(0)}Be(0|i[A>>2])}function le(A){var e,r=0,t=0;for(e=0|i[(A|=0)+4>>2],t=0;;){if((0|t)>=(0|e)){r=0,t=4;break}if(r=0|i[(0|i[A>>2])+(t<<2)>>2]){t=4;break}t=t+1|0}return 4==(0|t)?0|r:0}function he(A,e){e|=0;var r=0,t=0,o=0,a=0;if(r=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,r=(0|i[A>>2])+(r<<2)|0,!(t=0|i[r>>2]))return 0|(a=1);a=e+32|0;do{if((0|t)!=(0|e)){if(!(r=0|i[t+32>>2]))return 0|(a=1);for(o=r;;){if((0|o)==(0|e)){o=8;break}if(!(r=0|i[o+32>>2])){r=1,o=10;break}t=o,o=r}if(8==(0|o)){i[t+32>>2]=i[a>>2];break}if(10==(0|o))return 0|r}else i[r>>2]=i[a>>2]}while(0);return Be(e),i[(a=A+8|0)>>2]=(0|i[a>>2])-1,0|(a=0)}function ce(A,e,r){A|=0,e|=0,r|=0;var t,o=0,a=0,s=0;(t=0|pe(40))||Q(23283,23253,98,23296),i[t>>2]=i[e>>2],i[t+4>>2]=i[e+4>>2],i[t+8>>2]=i[e+8>>2],i[t+12>>2]=i[e+12>>2],i[(a=t+16|0)>>2]=i[r>>2],i[a+4>>2]=i[r+4>>2],i[a+8>>2]=i[r+8>>2],i[a+12>>2]=i[r+12>>2],i[t+32>>2]=0,a=~~(+f(+ +u(10,+ +(15-(0|i[A+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,a=(0|i[A>>2])+(a<<2)|0,o=0|i[a>>2];do{if(o){for(;!(0|xA(o,e)&&0|xA(o+16|0,r));)if(a=0|i[o+32>>2],!(0|i[(o=0==(0|a)?o:a)+32>>2])){s=10;break}if(10==(0|s)){i[o+32>>2]=t;break}return Be(t),0|(s=o)}i[a>>2]=t}while(0);return i[(s=A+8|0)>>2]=1+(0|i[s>>2]),0|(s=t)}function de(A,e,r){e|=0,r|=0;var t=0,o=0;if(o=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,!(o=0|i[(0|i[A>>2])+(o<<2)>>2]))return 0|(r=0);if(!r){for(A=o;;){if(0|xA(A,e)){t=10;break}if(!(A=0|i[A+32>>2])){A=0,t=10;break}}if(10==(0|t))return 0|A}for(A=o;;){if(0|xA(A,e)&&0|xA(A+16|0,r)){t=10;break}if(!(A=0|i[A+32>>2])){A=0,t=10;break}}return 10==(0|t)?0|A:0}function ge(A,e){e|=0;var r=0;if(r=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,!(A=0|i[(0|i[A>>2])+(r<<2)>>2]))return 0|(r=0);for(;;){if(0|xA(A,e)){e=5;break}if(!(A=0|i[A+32>>2])){A=0,e=5;break}}return 5==(0|e)?0|A:0}function we(A){return 0|~~+function(A){return+ +Ie(+(A=+A))}(A=+A)}function pe(A){A|=0;var e,r=0,t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0;e=I,I=I+16|0,d=e;do{if(A>>>0<245){if(A=(l=A>>>0<11?16:A+11&-8)>>>3,3&(t=(c=0|i[5829])>>>A)|0)return n=0|i[(t=(A=23356+((r=(1&t^1)+A|0)<<1<<2)|0)+8|0)>>2],(0|(a=0|i[(o=n+8|0)>>2]))==(0|A)?i[5829]=c&~(1<>2]=A,i[t>>2]=a),k=r<<3,i[n+4>>2]=3|k,i[(k=n+k+4|0)>>2]=1|i[k>>2],I=e,0|(k=o);if(l>>>0>(h=0|i[5831])>>>0){if(0|t)return r=((r=t<>>=s=r>>>12&16)>>>5&8)|s|(a=(r>>>=t)>>>2&4)|(A=(r>>>=a)>>>1&2)|(n=(r>>>=A)>>>1&1))+(r>>>n)|0)<<1<<2)|0)+8|0)>>2],(0|(t=0|i[(s=a+8|0)>>2]))==(0|r)?(A=c&~(1<>2]=r,i[A>>2]=t,A=c),f=(k=n<<3)-l|0,i[a+4>>2]=3|l,i[(o=a+l|0)+4>>2]=1|f,i[a+k>>2]=f,0|h&&(n=0|i[5834],t=23356+((r=h>>>3)<<1<<2)|0,A&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=n,i[r+12>>2]=n,i[n+8>>2]=r,i[n+12>>2]=t),i[5831]=f,i[5834]=o,I=e,0|(k=s);if(a=0|i[5830]){for(t=(a&0-a)-1|0,t=u=0|i[23620+(((n=(t>>>=o=t>>>12&16)>>>5&8)|o|(f=(t>>>=n)>>>2&4)|(s=(t>>>=f)>>>1&2)|(u=(t>>>=s)>>>1&1))+(t>>>u)<<2)>>2],s=u,u=(-8&i[u+4>>2])-l|0;(A=0|i[t+16>>2])||(A=0|i[t+20>>2]);)t=A,s=(o=(f=(-8&i[A+4>>2])-l|0)>>>0>>0)?A:s,u=o?f:u;if((f=s+l|0)>>>0>s>>>0){o=0|i[s+24>>2],r=0|i[s+12>>2];do{if((0|r)==(0|s)){if(!(r=0|i[(A=s+20|0)>>2])&&!(r=0|i[(A=s+16|0)>>2])){t=0;break}for(;;)if(t=0|i[(n=r+20|0)>>2])r=t,A=n;else{if(!(t=0|i[(n=r+16|0)>>2]))break;r=t,A=n}i[A>>2]=0,t=r}else t=0|i[s+8>>2],i[t+12>>2]=r,i[r+8>>2]=t,t=r}while(0);do{if(0|o){if(r=0|i[s+28>>2],(0|s)==(0|i[(A=23620+(r<<2)|0)>>2])){if(i[A>>2]=t,!t){i[5830]=a&~(1<>2])==(0|s)?k:o+20|0)>>2]=t,!t)break;i[t+24>>2]=o,0|(r=0|i[s+16>>2])&&(i[t+16>>2]=r,i[r+24>>2]=t),0|(r=0|i[s+20>>2])&&(i[t+20>>2]=r,i[r+24>>2]=t)}}while(0);return u>>>0<16?(k=u+l|0,i[s+4>>2]=3|k,i[(k=s+k+4|0)>>2]=1|i[k>>2]):(i[s+4>>2]=3|l,i[f+4>>2]=1|u,i[f+u>>2]=u,0|h&&(n=0|i[5834],t=23356+((r=h>>>3)<<1<<2)|0,(r=1<>2]:(i[5829]=r|c,r=t,A=t+8|0),i[A>>2]=n,i[r+12>>2]=n,i[n+8>>2]=r,i[n+12>>2]=t),i[5831]=u,i[5834]=f),I=e,0|(k=s+8|0)}c=l}else c=l}else c=l}else if(A>>>0<=4294967231)if(l=-8&(A=A+11|0),n=0|i[5830]){o=0-l|0,u=(A>>>=8)?l>>>0>16777215?31:l>>>((u=14-((s=((p=A<<(c=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|c|(u=((p<<=s)+245760|0)>>>16&2))+(p<>>15)|0)+7|0)&1|u<<1:0,t=0|i[23620+(u<<2)>>2];A:do{if(t)for(A=0,s=l<<(31==(0|u)?0:25-(u>>>1)|0),a=0;;){if((f=(-8&i[t+4>>2])-l|0)>>>0>>0){if(!f){A=t,o=0,p=65;break A}A=t,o=f}if(a=0==(0|(p=0|i[t+20>>2]))|(0|p)==(0|(t=0|i[t+16+(s>>>31<<2)>>2]))?a:p,!t){t=a,p=61;break}s<<=1}else t=0,A=0,p=61}while(0);if(61==(0|p)){if(0==(0|t)&0==(0|A)){if(!(A=((A=2<>>=f=c>>>12&16)>>>5&8)|f|(s=(c>>>=a)>>>2&4)|(u=(c>>>=s)>>>1&2)|(t=(c>>>=u)>>>1&1))+(c>>>t)<<2)>>2]}t?p=65:(s=A,f=o)}if(65==(0|p))for(a=t;;){if(o=(t=(c=(-8&i[a+4>>2])-l|0)>>>0>>0)?c:o,A=t?a:A,(t=0|i[a+16>>2])||(t=0|i[a+20>>2]),!t){s=A,f=o;break}a=t}if(0!=(0|s)&&f>>>0<((0|i[5831])-l|0)>>>0&&(h=s+l|0)>>>0>s>>>0){a=0|i[s+24>>2],r=0|i[s+12>>2];do{if((0|r)==(0|s)){if(!(r=0|i[(A=s+20|0)>>2])&&!(r=0|i[(A=s+16|0)>>2])){r=0;break}for(;;)if(t=0|i[(o=r+20|0)>>2])r=t,A=o;else{if(!(t=0|i[(o=r+16|0)>>2]))break;r=t,A=o}i[A>>2]=0}else k=0|i[s+8>>2],i[k+12>>2]=r,i[r+8>>2]=k}while(0);do{if(a){if(A=0|i[s+28>>2],(0|s)==(0|i[(t=23620+(A<<2)|0)>>2])){if(i[t>>2]=r,!r){n&=~(1<>2])==(0|s)?k:a+20|0)>>2]=r,!r)break;i[r+24>>2]=a,0|(A=0|i[s+16>>2])&&(i[r+16>>2]=A,i[A+24>>2]=r),(A=0|i[s+20>>2])&&(i[r+20>>2]=A,i[A+24>>2]=r)}}while(0);A:do{if(f>>>0<16)k=f+l|0,i[s+4>>2]=3|k,i[(k=s+k+4|0)>>2]=1|i[k>>2];else{if(i[s+4>>2]=3|l,i[h+4>>2]=1|f,i[h+f>>2]=f,r=f>>>3,f>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=h,i[r+12>>2]=h,i[h+8>>2]=r,i[h+12>>2]=t;break}if(r=23620+((t=(r=f>>>8)?f>>>0>16777215?31:f>>>((t=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(t=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|t<<1:0)<<2)|0,i[h+28>>2]=t,i[(A=h+16|0)+4>>2]=0,i[A>>2]=0,!(n&(A=1<>2]=h,i[h+24>>2]=r,i[h+12>>2]=h,i[h+8>>2]=h;break}r=0|i[r>>2];e:do{if((-8&i[r+4>>2]|0)!=(0|f)){for(n=f<<(31==(0|t)?0:25-(t>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|f)){r=A;break e}n<<=1,r=A}i[t>>2]=h,i[h+24>>2]=r,i[h+12>>2]=h,i[h+8>>2]=h;break A}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=h,i[m>>2]=h,i[h+8>>2]=k,i[h+12>>2]=r,i[h+24>>2]=0}}while(0);return I=e,0|(k=s+8|0)}c=l}else c=l;else c=-1}while(0);if((t=0|i[5831])>>>0>=c>>>0)return r=t-c|0,A=0|i[5834],r>>>0>15?(k=A+c|0,i[5834]=k,i[5831]=r,i[k+4>>2]=1|r,i[A+t>>2]=r,i[A+4>>2]=3|c):(i[5831]=0,i[5834]=0,i[A+4>>2]=3|t,i[(k=A+t+4|0)>>2]=1|i[k>>2]),I=e,0|(k=A+8|0);if((f=0|i[5832])>>>0>c>>>0)return v=f-c|0,i[5832]=v,m=(k=0|i[5835])+c|0,i[5835]=m,i[m+4>>2]=1|v,i[k+4>>2]=3|c,I=e,0|(k=k+8|0);if(0|i[5947]?A=0|i[5949]:(i[5949]=4096,i[5948]=4096,i[5950]=-1,i[5951]=-1,i[5952]=0,i[5940]=0,i[5947]=-16&d^1431655768,A=4096),s=c+48|0,(l=(a=A+(u=c+47|0)|0)&(o=0-A|0))>>>0<=c>>>0)return I=e,0|(k=0);if(0|(A=0|i[5939])&&(d=(h=0|i[5937])+l|0)>>>0<=h>>>0|d>>>0>A>>>0)return I=e,0|(k=0);A:do{if(4&i[5940])r=0,p=143;else{t=0|i[5835];e:do{if(t){for(n=23764;!((d=0|i[n>>2])>>>0<=t>>>0&&(d+(0|i[n+4>>2])|0)>>>0>t>>>0);){if(!(A=0|i[n+8>>2])){p=128;break e}n=A}if((r=a-f&o)>>>0<2147483647)if((0|(A=0|Fe(0|r)))==((0|i[n>>2])+(0|i[n+4>>2])|0)){if(-1!=(0|A)){f=r,a=A,p=145;break A}}else n=A,p=136;else r=0}else p=128}while(0);do{if(128==(0|p))if(-1!=(0|(t=0|Fe(0)))&&(r=t,w=(r=(0==((w=(g=0|i[5948])+-1|0)&r|0)?0:(w+r&0-g)-r|0)+l|0)+(g=0|i[5937])|0,r>>>0>c>>>0&r>>>0<2147483647)){if(0|(d=0|i[5939])&&w>>>0<=g>>>0|w>>>0>d>>>0){r=0;break}if((0|(A=0|Fe(0|r)))==(0|t)){f=r,a=t,p=145;break A}n=A,p=136}else r=0}while(0);do{if(136==(0|p)){if(t=0-r|0,!(s>>>0>r>>>0&r>>>0<2147483647&-1!=(0|n))){if(-1==(0|n)){r=0;break}f=r,a=n,p=145;break A}if((A=u-r+(A=0|i[5949])&0-A)>>>0>=2147483647){f=r,a=n,p=145;break A}if(-1==(0|Fe(0|A))){Fe(0|t),r=0;break}f=A+r|0,a=n,p=145;break A}}while(0);i[5940]=4|i[5940],p=143}}while(0);if(143==(0|p)&&l>>>0<2147483647&&!(-1==(0|(v=0|Fe(0|l)))|1^(b=(B=(w=0|Fe(0))-v|0)>>>0>(c+40|0)>>>0)|v>>>0>>0&-1!=(0|v)&-1!=(0|w)^1)&&(f=b?B:r,a=v,p=145),145==(0|p)){r=(0|i[5937])+f|0,i[5937]=r,r>>>0>(0|i[5938])>>>0&&(i[5938]=r),u=0|i[5835];A:do{if(u){for(r=23764;;){if((0|a)==((A=0|i[r>>2])+(t=0|i[r+4>>2])|0)){p=154;break}if(!(n=0|i[r+8>>2]))break;r=n}if(154==(0|p)&&(m=r+4|0,0==(8&i[r+12>>2]|0))&&a>>>0>u>>>0&A>>>0<=u>>>0){i[m>>2]=t+f,m=u+(v=0==(7&(v=u+8|0)|0)?0:0-v&7)|0,v=(k=(0|i[5832])+f|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[u+k+4>>2]=40,i[5836]=i[5951];break}for(a>>>0<(0|i[5833])>>>0&&(i[5833]=a),t=a+f|0,r=23764;;){if((0|i[r>>2])==(0|t)){p=162;break}if(!(A=0|i[r+8>>2]))break;r=A}if(162==(0|p)&&0==(8&i[r+12>>2]|0)){i[r>>2]=a,i[(h=r+4|0)>>2]=(0|i[h>>2])+f,l=(h=a+(0==(7&(h=a+8|0)|0)?0:0-h&7)|0)+c|0,s=(r=t+(0==(7&(r=t+8|0)|0)?0:0-r&7)|0)-h-c|0,i[h+4>>2]=3|c;e:do{if((0|u)==(0|r))k=(0|i[5832])+s|0,i[5832]=k,i[5835]=l,i[l+4>>2]=1|k;else{if((0|i[5834])==(0|r)){k=(0|i[5831])+s|0,i[5831]=k,i[5834]=l,i[l+4>>2]=1|k,i[l+k>>2]=k;break}if(1==(3&(A=0|i[r+4>>2])|0)){f=-8&A,n=A>>>3;r:do{if(A>>>0<256){if(A=0|i[r+8>>2],(0|(t=0|i[r+12>>2]))==(0|A)){i[5829]=i[5829]&~(1<>2]=t,i[t+8>>2]=A;break}a=0|i[r+24>>2],A=0|i[r+12>>2];do{if((0|A)==(0|r)){if(A=0|i[(n=(t=r+16|0)+4|0)>>2])t=n;else if(!(A=0|i[t>>2])){A=0;break}for(;;)if(n=0|i[(o=A+20|0)>>2])A=n,t=o;else{if(!(n=0|i[(o=A+16|0)>>2]))break;A=n,t=o}i[t>>2]=0}else k=0|i[r+8>>2],i[k+12>>2]=A,i[A+8>>2]=k}while(0);if(!a)break;n=23620+((t=0|i[r+28>>2])<<2)|0;do{if((0|i[n>>2])==(0|r)){if(i[n>>2]=A,0|A)break;i[5830]=i[5830]&~(1<>2])==(0|r)?k:a+20|0)>>2]=A,!A)break r}while(0);if(i[A+24>>2]=a,0|(n=0|i[(t=r+16|0)>>2])&&(i[A+16>>2]=n,i[n+24>>2]=A),!(t=0|i[t+4>>2]))break;i[A+20>>2]=t,i[t+24>>2]=A}while(0);r=r+f|0,o=f+s|0}else o=s;if(i[(r=r+4|0)>>2]=-2&i[r>>2],i[l+4>>2]=1|o,i[l+o>>2]=o,r=o>>>3,o>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=l,i[r+12>>2]=l,i[l+8>>2]=r,i[l+12>>2]=t;break}r=o>>>8;do{if(r){if(o>>>0>16777215){n=31;break}n=o>>>((n=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(n=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|n<<1}else n=0}while(0);if(r=23620+(n<<2)|0,i[l+28>>2]=n,i[(A=l+16|0)+4>>2]=0,i[A>>2]=0,!((A=0|i[5830])&(t=1<>2]=l,i[l+24>>2]=r,i[l+12>>2]=l,i[l+8>>2]=l;break}r=0|i[r>>2];r:do{if((-8&i[r+4>>2]|0)!=(0|o)){for(n=o<<(31==(0|n)?0:25-(n>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|o)){r=A;break r}n<<=1,r=A}i[t>>2]=l,i[l+24>>2]=r,i[l+12>>2]=l,i[l+8>>2]=l;break e}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=l,i[m>>2]=l,i[l+8>>2]=k,i[l+12>>2]=r,i[l+24>>2]=0}}while(0);return I=e,0|(k=h+8|0)}for(r=23764;!((A=0|i[r>>2])>>>0<=u>>>0&&(k=A+(0|i[r+4>>2])|0)>>>0>u>>>0);)r=0|i[r+8>>2];r=(A=(A=(o=k+-47|0)+(0==(7&(A=o+8|0)|0)?0:0-A&7)|0)>>>0<(o=u+16|0)>>>0?u:A)+8|0,m=a+(v=0==(7&(v=a+8|0)|0)?0:0-v&7)|0,v=(t=f+-40|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[a+t+4>>2]=40,i[5836]=i[5951],i[(t=A+4|0)>>2]=27,i[r>>2]=i[5941],i[r+4>>2]=i[5942],i[r+8>>2]=i[5943],i[r+12>>2]=i[5944],i[5941]=a,i[5942]=f,i[5944]=0,i[5943]=r,r=A+24|0;do{m=r,i[(r=r+4|0)>>2]=7}while((m+8|0)>>>0>>0);if((0|A)!=(0|u)){if(a=A-u|0,i[t>>2]=-2&i[t>>2],i[u+4>>2]=1|a,i[A>>2]=a,r=a>>>3,a>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=u,i[r+12>>2]=u,i[u+8>>2]=r,i[u+12>>2]=t;break}if(t=23620+((n=(r=a>>>8)?a>>>0>16777215?31:a>>>((n=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(n=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|n<<1:0)<<2)|0,i[u+28>>2]=n,i[u+20>>2]=0,i[o>>2]=0,!((r=0|i[5830])&(A=1<>2]=u,i[u+24>>2]=t,i[u+12>>2]=u,i[u+8>>2]=u;break}r=0|i[t>>2];e:do{if((-8&i[r+4>>2]|0)!=(0|a)){for(n=a<<(31==(0|n)?0:25-(n>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|a)){r=A;break e}n<<=1,r=A}i[t>>2]=u,i[u+24>>2]=r,i[u+12>>2]=u,i[u+8>>2]=u;break A}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=u,i[m>>2]=u,i[u+8>>2]=k,i[u+12>>2]=r,i[u+24>>2]=0}}else 0==(0|(k=0|i[5833]))|a>>>0>>0&&(i[5833]=a),i[5941]=a,i[5942]=f,i[5944]=0,i[5838]=i[5947],i[5837]=-1,i[5842]=23356,i[5841]=23356,i[5844]=23364,i[5843]=23364,i[5846]=23372,i[5845]=23372,i[5848]=23380,i[5847]=23380,i[5850]=23388,i[5849]=23388,i[5852]=23396,i[5851]=23396,i[5854]=23404,i[5853]=23404,i[5856]=23412,i[5855]=23412,i[5858]=23420,i[5857]=23420,i[5860]=23428,i[5859]=23428,i[5862]=23436,i[5861]=23436,i[5864]=23444,i[5863]=23444,i[5866]=23452,i[5865]=23452,i[5868]=23460,i[5867]=23460,i[5870]=23468,i[5869]=23468,i[5872]=23476,i[5871]=23476,i[5874]=23484,i[5873]=23484,i[5876]=23492,i[5875]=23492,i[5878]=23500,i[5877]=23500,i[5880]=23508,i[5879]=23508,i[5882]=23516,i[5881]=23516,i[5884]=23524,i[5883]=23524,i[5886]=23532,i[5885]=23532,i[5888]=23540,i[5887]=23540,i[5890]=23548,i[5889]=23548,i[5892]=23556,i[5891]=23556,i[5894]=23564,i[5893]=23564,i[5896]=23572,i[5895]=23572,i[5898]=23580,i[5897]=23580,i[5900]=23588,i[5899]=23588,i[5902]=23596,i[5901]=23596,i[5904]=23604,i[5903]=23604,m=a+(v=0==(7&(v=a+8|0)|0)?0:0-v&7)|0,v=(k=f+-40|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[a+k+4>>2]=40,i[5836]=i[5951]}while(0);if((r=0|i[5832])>>>0>c>>>0)return v=r-c|0,i[5832]=v,m=(k=0|i[5835])+c|0,i[5835]=m,i[m+4>>2]=1|v,i[k+4>>2]=3|c,I=e,0|(k=k+8|0)}return i[(k=23312)>>2]=12,I=e,0|(k=0)}function Be(A){var e=0,r=0,t=0,n=0,o=0,a=0,f=0,s=0;if(A|=0){r=A+-8|0,n=0|i[5833],s=r+(e=-8&(A=0|i[A+-4>>2]))|0;do{if(1&A)f=r,a=r;else{if(t=0|i[r>>2],!(3&A))return;if(o=t+e|0,(a=r+(0-t)|0)>>>0>>0)return;if((0|i[5834])==(0|a)){if(3!=(3&(e=0|i[(A=s+4|0)>>2])|0)){f=a,e=o;break}return i[5831]=o,i[A>>2]=-2&e,i[a+4>>2]=1|o,void(i[a+o>>2]=o)}if(r=t>>>3,t>>>0<256){if(A=0|i[a+8>>2],(0|(e=0|i[a+12>>2]))==(0|A)){i[5829]=i[5829]&~(1<>2]=e,i[e+8>>2]=A,f=a,e=o;break}n=0|i[a+24>>2],A=0|i[a+12>>2];do{if((0|A)==(0|a)){if(A=0|i[(r=(e=a+16|0)+4|0)>>2])e=r;else if(!(A=0|i[e>>2])){A=0;break}for(;;)if(r=0|i[(t=A+20|0)>>2])A=r,e=t;else{if(!(r=0|i[(t=A+16|0)>>2]))break;A=r,e=t}i[e>>2]=0}else f=0|i[a+8>>2],i[f+12>>2]=A,i[A+8>>2]=f}while(0);if(n){if(e=0|i[a+28>>2],(0|i[(r=23620+(e<<2)|0)>>2])==(0|a)){if(i[r>>2]=A,!A){i[5830]=i[5830]&~(1<>2])==(0|a)?f:n+20|0)>>2]=A,!A){f=a,e=o;break}i[A+24>>2]=n,0|(r=0|i[(e=a+16|0)>>2])&&(i[A+16>>2]=r,i[r+24>>2]=A),(e=0|i[e+4>>2])?(i[A+20>>2]=e,i[e+24>>2]=A,f=a,e=o):(f=a,e=o)}else f=a,e=o}}while(0);if(!(a>>>0>=s>>>0)&&1&(t=0|i[(A=s+4|0)>>2])){if(2&t)i[A>>2]=-2&t,i[f+4>>2]=1|e,i[a+e>>2]=e,n=e;else{if((0|i[5835])==(0|s)){if(s=(0|i[5832])+e|0,i[5832]=s,i[5835]=f,i[f+4>>2]=1|s,(0|f)!=(0|i[5834]))return;return i[5834]=0,void(i[5831]=0)}if((0|i[5834])==(0|s))return s=(0|i[5831])+e|0,i[5831]=s,i[5834]=a,i[f+4>>2]=1|s,void(i[a+s>>2]=s);n=(-8&t)+e|0,r=t>>>3;do{if(t>>>0<256){if(e=0|i[s+8>>2],(0|(A=0|i[s+12>>2]))==(0|e)){i[5829]=i[5829]&~(1<>2]=A,i[A+8>>2]=e;break}o=0|i[s+24>>2],A=0|i[s+12>>2];do{if((0|A)==(0|s)){if(A=0|i[(r=(e=s+16|0)+4|0)>>2])e=r;else if(!(A=0|i[e>>2])){r=0;break}for(;;)if(r=0|i[(t=A+20|0)>>2])A=r,e=t;else{if(!(r=0|i[(t=A+16|0)>>2]))break;A=r,e=t}i[e>>2]=0,r=A}else r=0|i[s+8>>2],i[r+12>>2]=A,i[A+8>>2]=r,r=A}while(0);if(0|o){if(A=0|i[s+28>>2],(0|i[(e=23620+(A<<2)|0)>>2])==(0|s)){if(i[e>>2]=r,!r){i[5830]=i[5830]&~(1<>2])==(0|s)?t:o+20|0)>>2]=r,!r)break;i[r+24>>2]=o,0|(e=0|i[(A=s+16|0)>>2])&&(i[r+16>>2]=e,i[e+24>>2]=r),0|(A=0|i[A+4>>2])&&(i[r+20>>2]=A,i[A+24>>2]=r)}}while(0);if(i[f+4>>2]=1|n,i[a+n>>2]=n,(0|f)==(0|i[5834]))return void(i[5831]=n)}if(A=n>>>3,n>>>0<256)return r=23356+(A<<1<<2)|0,(e=0|i[5829])&(A=1<>2]:(i[5829]=e|A,A=r,e=r+8|0),i[e>>2]=f,i[A+12>>2]=f,i[f+8>>2]=A,void(i[f+12>>2]=r);A=23620+((t=(A=n>>>8)?n>>>0>16777215?31:n>>>((t=14-((o=((s=A<<(a=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|a|(t=((s<<=o)+245760|0)>>>16&2))+(s<>>15)|0)+7|0)&1|t<<1:0)<<2)|0,i[f+28>>2]=t,i[f+20>>2]=0,i[f+16>>2]=0,e=0|i[5830],r=1<>2];e:do{if((-8&i[A+4>>2]|0)!=(0|n)){for(t=n<<(31==(0|t)?0:25-(t>>>1)|0);e=0|i[(r=A+16+(t>>>31<<2)|0)>>2];){if((-8&i[e+4>>2]|0)==(0|n)){A=e;break e}t<<=1,A=e}i[r>>2]=f,i[f+24>>2]=A,i[f+12>>2]=f,i[f+8>>2]=f;break A}}while(0);s=0|i[(a=A+8|0)>>2],i[s+12>>2]=f,i[a>>2]=f,i[f+8>>2]=s,i[f+12>>2]=A,i[f+24>>2]=0}else i[5830]=e|r,i[A>>2]=f,i[f+24>>2]=A,i[f+12>>2]=f,i[f+8>>2]=f}while(0);if(s=(0|i[5837])-1|0,i[5837]=s,!(0|s)){for(A=23772;A=0|i[A>>2];)A=A+8|0;i[5837]=-1}}}}function be(A,e){e|=0;var r=0;return(A|=0)?(r=0|b(e,A),(e|A)>>>0>65535&&(r=(0|(r>>>0)/(A>>>0))==(0|e)?r:-1)):r=0,(A=0|pe(r))&&3&i[A+-4>>2]?(_e(0|A,0,0|r),0|A):0|A}function ve(A,e,r,t){return 0|(k(0|(t=(e|=0)-(t|=0)-((r|=0)>>>0>(A|=0)>>>0|0)>>>0)),A-r>>>0|0)}function me(A){return 0|((A|=0)?31-(0|m(A^A-1))|0:32)}function ke(A,e,r,t,n){n|=0;var o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0;if(l=A|=0,a=r|=0,f=c=t|=0,!(u=s=e|=0))return o=0!=(0|n),f?o?(i[n>>2]=0|A,i[n+4>>2]=0&e,n=0,0|(k(0|(c=0)),n)):(n=0,0|(k(0|(c=0)),n)):(o&&(i[n>>2]=(l>>>0)%(a>>>0),i[n+4>>2]=0),n=(l>>>0)/(a>>>0)>>>0,0|(k(0|(c=0)),n));o=0==(0|f);do{if(a){if(!o){if((o=(0|m(0|f))-(0|m(0|u))|0)>>>0<=31){a=h=o+1|0,A=l>>>(h>>>0)&(e=o-31>>31)|u<<(f=31-o|0),e&=u>>>(h>>>0),o=0,f=l<>2]=0|A,i[n+4>>2]=s|0&e,n=0,0|(k(0|(c=0)),n)):(n=0,0|(k(0|(c=0)),n))}if((o=a-1|0)&a|0){a=f=33+(0|m(0|a))-(0|m(0|u))|0,A=(h=32-f|0)-1>>31&u>>>((d=f-32|0)>>>0)|(u<>>(f>>>0))&(e=d>>31),e&=u>>>(f>>>0),o=l<<(g=64-f|0)&(s=h>>31),f=(u<>>(d>>>0))&s|l<>31;break}return 0|n&&(i[n>>2]=o&l,i[n+4>>2]=0),1==(0|a)?(g=0|A,0|(k(0|(d=s|0&e)),g)):(d=u>>>((g=0|me(0|a))>>>0)|0,g=u<<32-g|l>>>(g>>>0)|0,0|(k(0|d),g))}if(o)return 0|n&&(i[n>>2]=(u>>>0)%(a>>>0),i[n+4>>2]=0),g=(u>>>0)/(a>>>0)>>>0,0|(k(0|(d=0)),g);if(!l)return 0|n&&(i[n>>2]=0,i[n+4>>2]=(u>>>0)%(f>>>0)),g=(u>>>0)/(f>>>0)>>>0,0|(k(0|(d=0)),g);if(!((o=f-1|0)&f))return 0|n&&(i[n>>2]=0|A,i[n+4>>2]=o&u|0&e),d=0,g=u>>>((0|me(0|f))>>>0),0|(k(0|d),g);if((o=(0|m(0|f))-(0|m(0|u))|0)>>>0<=30){a=e=o+1|0,A=u<<(f=31-o|0)|l>>>(e>>>0),e=u>>>(e>>>0),o=0,f=l<>2]=0|A,i[n+4>>2]=s|0&e,g=0,0|(k(0|(d=0)),g)):(g=0,0|(k(0|(d=0)),g))}while(0);if(a){u=0|function(A,e,r,t){return 0|(k((e|=0)+(t|=0)+((r=(A|=0)+(r|=0)>>>0)>>>0>>0|0)>>>0|0),0|r)}(0|(h=0|r),0|(l=c|0&t),-1,-1),r=0|M(),s=f,f=0;do{t=s,s=o>>>31|s<<1,o=f|o<<1,ve(0|u,0|r,0|(t=A<<1|t>>>31|0),0|(c=A>>>31|e<<1|0)),f=1&(d=(g=0|M())>>31|((0|g)<0?-1:0)<<1),A=0|ve(0|t,0|c,d&h|0,(((0|g)<0?-1:0)>>31|((0|g)<0?-1:0)<<1)&l|0),e=0|M(),a=a-1|0}while(0!=(0|a));u=s,s=0}else u=f,s=0,f=0;return a=0,0|n&&(i[n>>2]=A,i[n+4>>2]=e),g=-2&(o<<1|0)|f,0|(k(0|(d=(0|o)>>>31|(u|a)<<1|0&(a<<1|o>>>31)|s)),g)}function Me(A,e,r,t){var n,o;return o=I,I=I+16|0,ke(A|=0,e|=0,r|=0,t|=0,n=0|o),I=o,0|(k(0|i[n+4>>2]),0|i[n>>2])}function Qe(A,e,r){return A|=0,e|=0,(0|(r|=0))<32?(k(e>>>r|0),A>>>r|(e&(1<>>r-32|0)}function ye(A,e,r){return A|=0,e|=0,(0|(r|=0))<32?(k(e<>>32-r|0),A<=0?+a(A+.5):+B(A-.5)}function De(A,e,r){A|=0,e|=0;var n,o,a=0;if((0|(r|=0))>=8192)return x(0|A,0|e,0|r),0|A;if(o=0|A,n=A+r|0,(3&A)==(3&e)){for(;3&A;){if(!r)return 0|o;t[A>>0]=0|t[e>>0],A=A+1|0,e=e+1|0,r=r-1|0}for(a=(r=-4&n|0)-64|0;(0|A)<=(0|a);)i[A>>2]=i[e>>2],i[A+4>>2]=i[e+4>>2],i[A+8>>2]=i[e+8>>2],i[A+12>>2]=i[e+12>>2],i[A+16>>2]=i[e+16>>2],i[A+20>>2]=i[e+20>>2],i[A+24>>2]=i[e+24>>2],i[A+28>>2]=i[e+28>>2],i[A+32>>2]=i[e+32>>2],i[A+36>>2]=i[e+36>>2],i[A+40>>2]=i[e+40>>2],i[A+44>>2]=i[e+44>>2],i[A+48>>2]=i[e+48>>2],i[A+52>>2]=i[e+52>>2],i[A+56>>2]=i[e+56>>2],i[A+60>>2]=i[e+60>>2],A=A+64|0,e=e+64|0;for(;(0|A)<(0|r);)i[A>>2]=i[e>>2],A=A+4|0,e=e+4|0}else for(r=n-4|0;(0|A)<(0|r);)t[A>>0]=0|t[e>>0],t[A+1>>0]=0|t[e+1>>0],t[A+2>>0]=0|t[e+2>>0],t[A+3>>0]=0|t[e+3>>0],A=A+4|0,e=e+4|0;for(;(0|A)<(0|n);)t[A>>0]=0|t[e>>0],A=A+1|0,e=e+1|0;return 0|o}function _e(A,e,r){e|=0;var n,o=0,a=0,f=0;if(n=(A|=0)+(r|=0)|0,e&=255,(0|r)>=67){for(;3&A;)t[A>>0]=e,A=A+1|0;for(f=e|e<<8|e<<16|e<<24,a=(o=-4&n|0)-64|0;(0|A)<=(0|a);)i[A>>2]=f,i[A+4>>2]=f,i[A+8>>2]=f,i[A+12>>2]=f,i[A+16>>2]=f,i[A+20>>2]=f,i[A+24>>2]=f,i[A+28>>2]=f,i[A+32>>2]=f,i[A+36>>2]=f,i[A+40>>2]=f,i[A+44>>2]=f,i[A+48>>2]=f,i[A+52>>2]=f,i[A+56>>2]=f,i[A+60>>2]=f,A=A+64|0;for(;(0|A)<(0|o);)i[A>>2]=f,A=A+4|0}for(;(0|A)<(0|n);)t[A>>0]=e,A=A+1|0;return n-r|0}function Ie(A){return(A=+A)>=0?+a(A+.5):+B(A-.5)}function Fe(A){A|=0;var e,r,t;return t=0|E(),(0|A)>0&(0|(e=(r=0|i[o>>2])+A|0))<(0|r)|(0|e)<0?(_(0|e),y(12),-1):(0|e)>(0|t)&&!(0|D(0|e))?(y(12),-1):(i[o>>2]=e,0|r)}return{___uremdi3:Me,_bitshift64Lshr:Qe,_bitshift64Shl:ye,_calloc:be,_cellAreaKm2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))>0){if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1!=(0|e)){A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e))}}else o=0;return I=n,6371.007180918475*o*6371.007180918475},_cellAreaM2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))>0){if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1!=(0|e)){A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e))}}else o=0;return I=n,6371.007180918475*o*6371.007180918475*1e3*1e3},_cellAreaRads2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))<=0)return I=n,+(o=0);if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1==(0|e))return I=n,+o;A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e));return I=n,+o},_compact:function(A,e,r){e|=0;var t,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,Q=0,y=0,E=0;if(!(r|=0))return 0|(y=0);if(n=0|i[(o=A|=0)>>2],!0&0==(15728640&(o=0|i[o+4>>2])|0)){if((0|r)<=0)return 0|(y=0);if(i[(y=e)>>2]=n,i[y+4>>2]=o,1==(0|r))return 0|(y=0);n=1;do{Q=0|i[(k=A+(n<<3)|0)+4>>2],i[(y=e+(n<<3)|0)>>2]=i[k>>2],i[y+4>>2]=Q,n=n+1|0}while((0|n)!=(0|r));return 0|(n=0)}if(!(Q=0|pe(k=r<<3)))return 0|(y=-3);if(De(0|Q,0|A,0|k),!(t=0|be(r,8)))return Be(Q),0|(y=-3);n=r;A:for(;;){v=0|Qe(0|(h=0|i[(f=Q)>>2]),0|(f=0|i[f+4>>2]),52),M(),m=(v&=15)+-1|0,b=(0|n)>0;e:do{if(b){if(B=((0|n)<0)<<31>>31,w=0|ye(0|m,0,52),p=0|M(),m>>>0>15)for(o=0,A=h,r=f;;){if(!(0==(0|A)&0==(0|r))){if(a=0|Qe(0|A,0|r,52),M(),s=(0|(a&=15))<(0|m),a=(0|a)==(0|m),r=0|Me(0|(l=s?0:a?A:0),0|(A=s?0:a?r:0),0|n,0|B),M(),0==(0|(u=0|i[(s=a=t+(r<<3)|0)>>2]))&0==(0|(s=0|i[s+4>>2])))r=l;else for(w=0,g=r,d=s,r=l;;){if((0|w)>(0|n)){y=41;break A}if((0|u)==(0|r)&(-117440513&d|0)==(0|A)){l=0|Qe(0|u,0|d,56),M(),c=(l&=7)+1|0,p=0|Qe(0|u,0|d,45),M();r:do{if(0|S(127&p)){if(u=0|Qe(0|u,0|d,52),M(),!(u&=15)){s=6;break}for(s=1;;){if(!(0==((p=0|ye(7,0,3*(15-s|0)|0))&r|0)&0==((0|M())&A|0))){s=7;break r}if(!(s>>>0>>0)){s=6;break}s=s+1|0}}else s=7}while(0);if((l+2|0)>>>0>s>>>0){y=51;break A}p=0|ye(0|c,0,56),A=0|M()|-117440513&A,i[(s=a)>>2]=0,i[s+4>>2]=0,s=g,r|=p}else s=(g+1|0)%(0|n)|0;if(0==(0|(u=0|i[(d=a=t+(s<<3)|0)>>2]))&0==(0|(d=0|i[d+4>>2])))break;w=w+1|0,g=s}i[(p=a)>>2]=r,i[p+4>>2]=A}if((0|(o=o+1|0))>=(0|n))break e;A=0|i[(r=Q+(o<<3)|0)>>2],r=0|i[r+4>>2]}for(o=0,A=h,r=f;;){if(!(0==(0|A)&0==(0|r))){if(s=0|Qe(0|A,0|r,52),M(),(0|(s&=15))>=(0|m)){if((0|s)!=(0|m)&&(A|=w,r=-15728641&r|p,s>>>0>=v>>>0)){a=m;do{g=0|ye(7,0,3*(14-a|0)|0),a=a+1|0,A|=g,r=0|M()|r}while(a>>>0>>0)}}else A=0,r=0;if(s=0|Me(0|A,0|r,0|n,0|B),M(),!(0==(0|(l=0|i[(u=a=t+(s<<3)|0)>>2]))&0==(0|(u=0|i[u+4>>2]))))for(g=0;;){if((0|g)>(0|n)){y=41;break A}if((0|l)==(0|A)&(-117440513&u|0)==(0|r)){c=0|Qe(0|l,0|u,56),M(),d=(c&=7)+1|0,E=0|Qe(0|l,0|u,45),M();r:do{if(0|S(127&E)){if(l=0|Qe(0|l,0|u,52),M(),!(l&=15)){u=6;break}for(u=1;;){if(!(0==((E=0|ye(7,0,3*(15-u|0)|0))&A|0)&0==((0|M())&r|0))){u=7;break r}if(!(u>>>0>>0)){u=6;break}u=u+1|0}}else u=7}while(0);if((c+2|0)>>>0>u>>>0){y=51;break A}E=0|ye(0|d,0,56),r=0|M()|-117440513&r,i[(d=a)>>2]=0,i[d+4>>2]=0,A|=E}else s=(s+1|0)%(0|n)|0;if(0==(0|(l=0|i[(u=a=t+(s<<3)|0)>>2]))&0==(0|(u=0|i[u+4>>2])))break;g=g+1|0}i[(E=a)>>2]=A,i[E+4>>2]=r}if((0|(o=o+1|0))>=(0|n))break e;A=0|i[(r=Q+(o<<3)|0)>>2],r=0|i[r+4>>2]}}}while(0);if((n+5|0)>>>0<11){y=99;break}if(!(p=0|be((0|n)/6|0,8))){y=58;break}e:do{if(b){g=0,d=0;do{if(!(0==(0|(o=0|i[(A=s=t+(g<<3)|0)>>2]))&0==(0|(A=0|i[A+4>>2])))){u=0|Qe(0|o,0|A,56),M(),r=(u&=7)+1|0,l=-117440513&A,E=0|Qe(0|o,0|A,45),M();r:do{if(0|S(127&E)){if(c=0|Qe(0|o,0|A,52),M(),0|(c&=15))for(a=1;;){if(!(0==(o&(E=0|ye(7,0,3*(15-a|0)|0))|0)&0==(l&(0|M())|0)))break r;if(!(a>>>0>>0))break;a=a+1|0}o|=A=0|ye(0|r,0,56),A=0|M()|l,i[(r=s)>>2]=o,i[r+4>>2]=A,r=u+2|0}}while(0);7==(0|r)&&(i[(E=p+(d<<3)|0)>>2]=o,i[E+4>>2]=-117440513&A,d=d+1|0)}g=g+1|0}while((0|g)!=(0|n));if(b){if(w=((0|n)<0)<<31>>31,c=0|ye(0|m,0,52),g=0|M(),m>>>0>15)for(A=0,o=0;;){do{if(!(0==(0|h)&0==(0|f))){for(u=0|Qe(0|h,0|f,52),M(),a=(0|(u&=15))<(0|m),u=(0|u)==(0|m),a=0|Me(0|(s=a?0:u?h:0),0|(u=a?0:u?f:0),0|n,0|w),M(),r=0;;){if((0|r)>(0|n)){y=98;break A}if((-117440513&(l=0|i[(E=t+(a<<3)|0)+4>>2])|0)==(0|u)&&(0|i[E>>2])==(0|s)){y=70;break}if((0|i[(E=t+((a=(a+1|0)%(0|n)|0)<<3)|0)>>2])==(0|s)&&(0|i[E+4>>2])==(0|u))break;r=r+1|0}if(70==(0|y)&&(y=0,!0&100663296==(117440512&l|0)))break;i[(E=e+(o<<3)|0)>>2]=h,i[E+4>>2]=f,o=o+1|0}}while(0);if((0|(A=A+1|0))>=(0|n)){n=d;break e}h=0|i[(f=Q+(A<<3)|0)>>2],f=0|i[f+4>>2]}for(A=0,o=0;;){do{if(!(0==(0|h)&0==(0|f))){if(u=0|Qe(0|h,0|f,52),M(),(0|(u&=15))>=(0|m))if((0|u)!=(0|m))if(r=h|c,a=-15728641&f|g,u>>>0>>0)u=a;else{s=m;do{E=0|ye(7,0,3*(14-s|0)|0),s=s+1|0,r|=E,a=0|M()|a}while(s>>>0>>0);u=a}else r=h,u=f;else r=0,u=0;for(s=0|Me(0|r,0|u,0|n,0|w),M(),a=0;;){if((0|a)>(0|n)){y=98;break A}if((-117440513&(l=0|i[(E=t+(s<<3)|0)+4>>2])|0)==(0|u)&&(0|i[E>>2])==(0|r)){y=93;break}if((0|i[(E=t+((s=(s+1|0)%(0|n)|0)<<3)|0)>>2])==(0|r)&&(0|i[E+4>>2])==(0|u))break;a=a+1|0}if(93==(0|y)&&(y=0,!0&100663296==(117440512&l|0)))break;i[(E=e+(o<<3)|0)>>2]=h,i[E+4>>2]=f,o=o+1|0}}while(0);if((0|(A=A+1|0))>=(0|n)){n=d;break e}h=0|i[(f=Q+(A<<3)|0)>>2],f=0|i[f+4>>2]}}else o=0,n=d}else o=0,n=0}while(0);if(_e(0|t,0,0|k),De(0|Q,0|p,n<<3|0),Be(p),!n)break;e=e+(o<<3)|0}return 41==(0|y)?(Be(Q),Be(t),0|(E=-1)):51==(0|y)?(Be(Q),Be(t),0|(E=-2)):58==(0|y)?(Be(Q),Be(t),0|(E=-3)):98==(0|y)?(Be(p),Be(Q),Be(t),0|(E=-1)):(99==(0|y)&&De(0|e,0|Q,n<<3|0),Be(Q),Be(t),0|(E=0))},_destroyLinkedPolygon:function(A){var e=0,r=0,t=0,n=0;if(A|=0)for(t=1;;){if(0|(e=0|i[A>>2]))do{if(0|(r=0|i[e>>2]))do{n=r,r=0|i[r+16>>2],Be(n)}while(0!=(0|r));n=e,e=0|i[e+8>>2],Be(n)}while(0!=(0|e));if(e=A,A=0|i[A+8>>2],t||Be(e),!A)break;t=0}},_edgeLengthKm:function(A){return+ +n[20752+((A|=0)<<3)>>3]},_edgeLengthM:function(A){return+ +n[20880+((A|=0)<<3)>>3]},_emscripten_replace_memory:function(A){return t=new Int8Array(A),new Uint8Array(A),i=new Int32Array(A),new Float32Array(A),n=new Float64Array(A),r=A,!0},_exactEdgeLengthKm:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+c)*+l(+a)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)!=(0|e));return I=t,+(d=6371.007180918475*o)},_exactEdgeLengthM:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+c)*+l(+a)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)!=(0|e));return I=t,+(d=6371.007180918475*o*1e3)},_exactEdgeLengthRads:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+a)*+l(+c)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)<(0|e));return I=t,+o},_experimentalH3ToLocalIj:function(A,e,r,t,i){var n,o;return i|=0,o=I,I=I+16|0,(A=0|$A(A|=0,e|=0,r|=0,t|=0,n=o))||(cA(n,i),A=0),I=o,0|A},_experimentalLocalIjToH3:function(A,e,r,t){var i,n;return A|=0,e|=0,t|=0,i=I,I=I+16|0,dA(r|=0,n=i),t=0|Ae(A,e,n,t),I=i,0|t},_free:Be,_geoToH3:LA,_getDestinationH3IndexFromUnidirectionalEdge:function(A,e){A|=0;var r,t,n=0;return r=I,I=I+16|0,n=r,!0&268435456==(2013265920&(e|=0)|0)?(t=0|Qe(0|A,0|e,56),M(),i[n>>2]=0,n=0|U(A,-2130706433&e|134217728,7&t,n),e=0|M(),k(0|e),I=r,0|n):(n=0,k(0|(e=0)),I=r,0|n)},_getH3IndexesFromUnidirectionalEdge:function(A,e,r){A|=0;var t,n,o,a,f=0;o=I,I=I+16|0,t=o,a=!0&268435456==(2013265920&(e|=0)|0),n=-2130706433&e|134217728,i[(f=r|=0)>>2]=a?A:0,i[f+4>>2]=a?n:0,a?(e=0|Qe(0|A,0|e,56),M(),i[t>>2]=0,A=0|U(A,n,7&e,t),e=0|M()):(A=0,e=0),i[(f=r+8|0)>>2]=A,i[f+4>>2]=e,I=o},_getH3UnidirectionalEdge:function(A,e,r,t){var n,o,a=0,f=0,s=0,u=0,l=0;if(o=I,I=I+16|0,n=o,!(0|ZA(A|=0,e|=0,r|=0,t|=0)))return u=0,k(0|(s=0)),I=o,0|u;for(s=-2130706433&e,a=(a=0==(0|UA(A,e)))?1:2;i[n>>2]=0,f=a+1|0,!((0|(l=0|U(A,e,a,n)))==(0|r)&(0|M())==(0|t));){if(!(f>>>0<7)){a=0,A=0,u=6;break}a=f}return 6==(0|u)?(k(0|a),I=o,0|A):(l=0|ye(0|a,0,56),u=0|s|M()|268435456,l|=A,k(0|u),I=o,0|l)},_getH3UnidirectionalEdgeBoundary:WA,_getH3UnidirectionalEdgesFromHexagon:function(A,e,r){r|=0;var t,n=0;t=0==(0|UA(A|=0,e|=0)),e&=-2130706433,i[(n=r)>>2]=t?A:0,i[n+4>>2]=t?285212672|e:0,i[(n=r+8|0)>>2]=A,i[n+4>>2]=301989888|e,i[(n=r+16|0)>>2]=A,i[n+4>>2]=318767104|e,i[(n=r+24|0)>>2]=A,i[n+4>>2]=335544320|e,i[(n=r+32|0)>>2]=A,i[n+4>>2]=352321536|e,i[(r=r+40|0)>>2]=A,i[r+4>>2]=369098752|e},_getOriginH3IndexFromUnidirectionalEdge:function(A,e){var r;return A|=0,k(0|((r=!0&268435456==(2013265920&(e|=0)|0))?-2130706433&e|134217728:0)),0|(r?A:0)},_getPentagonIndexes:NA,_getRes0Indexes:function(A){A|=0;var e=0,r=0,t=0;e=0;do{ye(0|e,0,45),t=134225919|M(),i[(r=A+(e<<3)|0)>>2]=-1,i[r+4>>2]=t,e=e+1|0}while(122!=(0|e))},_h3Distance:function(A,e,r,t){var i,n,o;return r|=0,t|=0,o=I,I=I+32|0,n=o,A=0==(0|$A(A|=0,e|=0,A,e,i=o+12|0))&&0==(0|$A(A,e,r,t,n))?0|hA(i,n):-1,I=o,0|A},_h3GetBaseCell:IA,_h3GetFaces:function A(e,r,t){t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0;n=I,I=I+128|0,h=n+112|0,f=n+96|0,c=n,a=0|Qe(0|(e|=0),0|(r|=0),52),M(),u=15&a,i[h>>2]=u,s=0|Qe(0|e,0|r,45),M(),s&=127;A:do{if(0|S(s)){if(0|u)for(o=1;;){if(!(0==((l=0|ye(7,0,3*(15-o|0)|0))&e|0)&0==((0|M())&r|0))){a=0;break A}if(!(o>>>0>>0))break;o=o+1|0}if(!(1&a))return l=0|ye(u+1|0,0,52),c=0|M()|-15728641&r,A((l|e)&~(h=0|ye(7,0,3*(14-u|0)|0)),c&~(0|M()),t),void(I=n);a=1}else a=0}while(0);YA(e,r,f),a?(mA(f,h,c),l=5):(yA(f,h,c),l=6);A:do{if(0|S(s))if(u)for(o=1;;){if(!(0==((s=0|ye(7,0,3*(15-o|0)|0))&e|0)&0==((0|M())&r|0))){o=8;break A}if(!(o>>>0>>0)){o=20;break}o=o+1|0}else o=20;else o=8}while(0);if(_e(0|t,-1,0|o),a){a=0;do{for(MA(f=c+(a<<4)|0,0|i[h>>2]),f=0|i[f>>2],o=0;!(-1==(0|(u=0|i[(s=t+(o<<2)|0)>>2]))|(0|u)==(0|f));)o=o+1|0;i[s>>2]=f,a=a+1|0}while((0|a)!=(0|l))}else{a=0;do{for(kA(f=c+(a<<4)|0,0|i[h>>2],0,1),f=0|i[f>>2],o=0;!(-1==(0|(u=0|i[(s=t+(o<<2)|0)>>2]))|(0|u)==(0|f));)o=o+1|0;i[s>>2]=f,a=a+1|0}while((0|a)!=(0|l))}I=n},_h3GetResolution:function(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),52),M(),15&e|0},_h3IndexesAreNeighbors:ZA,_h3IsPentagon:UA,_h3IsResClassIII:function(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),52),M(),1&e|0},_h3IsValid:FA,_h3Line:function(A,e,r,t,n){r|=0,t|=0,n|=0;var o,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,Q=0;if(o=I,I=I+48|0,s=o+12|0,M=o,0==(0|$A(A|=0,e|=0,A,e,a=o+24|0))&&0==(0|$A(A,e,r,t,s))){if((0|(k=0|hA(a,s)))<0)return I=o,0|(M=k);for(i[a>>2]=0,i[a+4>>2]=0,i[a+8>>2]=0,i[s>>2]=0,i[s+4>>2]=0,i[s+8>>2]=0,$A(A,e,A,e,a),$A(A,e,r,t,s),gA(a),gA(s),k?(w=+(0|k),m=a,r=c=0|i[a>>2],t=d=0|i[(b=a+4|0)>>2],a=g=0|i[(v=a+8|0)>>2],p=+((0|i[s>>2])-c|0)/w,B=+((0|i[s+4>>2])-d|0)/w,w=+((0|i[s+8>>2])-g|0)/w):(b=t=a+4|0,v=g=a+8|0,m=a,r=0|i[a>>2],t=0|i[t>>2],a=0|i[g>>2],p=0,B=0,w=0),i[M>>2]=r,i[(g=M+4|0)>>2]=t,i[(d=M+8|0)>>2]=a,c=0;;){Q=p*(l=+(0|c))+ +(0|r),u=B*l+ +(0|i[b>>2]),l=w*l+ +(0|i[v>>2]),t=~~+xe(+Q),s=~~+xe(+u),r=~~+xe(+l),Q=+f(+(+(0|t)-Q)),u=+f(+(+(0|s)-u)),l=+f(+(+(0|r)-l));do{if(!(Q>u&Q>l)){if(h=0-t|0,u>l){a=h-r|0;break}a=s,r=h-s|0;break}t=0-(s+r)|0,a=s}while(0);if(i[M>>2]=t,i[g>>2]=a,i[d>>2]=r,wA(M),Ae(A,e,M,n+(c<<3)|0),(0|c)==(0|k))break;c=c+1|0,r=0|i[m>>2]}return I=o,0|(M=0)}return I=o,0|(M=-1)},_h3LineSize:function(A,e,r,t){var i,n,o;return r|=0,t|=0,o=I,I=I+32|0,n=o,A=0==(0|$A(A|=0,e|=0,A,e,i=o+12|0))&&0==(0|$A(A,e,r,t,n))?0|hA(i,n):-1,I=o,(A>>>31^1)+A|0},_h3SetToLinkedGeo:function(A,e,r){r|=0;var t,n,o,a=0;if(o=I,I=I+32|0,t=o,function(A,e,r){A|=0,r|=0;var t,n,o=0,a=0,f=0,s=0,u=0;if(n=I,I=I+176|0,t=n,(0|(e|=0))<1)return se(r,0,0),void(I=n);s=0|Qe(0|i[(s=A)>>2],0|i[s+4>>2],52),M(),se(r,(0|e)>6?e:6,15&s),s=0;do{if(jA(0|i[(o=A+(s<<3)|0)>>2],0|i[o+4>>2],t),(0|(o=0|i[t>>2]))>0){u=0;do{f=t+8+(u<<4)|0,(a=0|de(r,o=t+8+(((0|(u=u+1|0))%(0|o)|0)<<4)|0,f))?he(r,a):ce(r,f,o),o=0|i[t>>2]}while((0|u)<(0|o))}s=s+1|0}while((0|s)!=(0|e));I=n}(A|=0,e|=0,n=o+16|0),i[r>>2]=0,i[r+4>>2]=0,i[r+8>>2]=0,!(A=0|le(n)))return XA(r),ue(n),void(I=o);do{e=0|JA(r);do{KA(e,A),a=A+16|0,i[t>>2]=i[a>>2],i[t+4>>2]=i[a+4>>2],i[t+8>>2]=i[a+8>>2],i[t+12>>2]=i[a+12>>2],he(n,A),A=0|ge(n,t)}while(0!=(0|A));A=0|le(n)}while(0!=(0|A));XA(r),ue(n),I=o},_h3ToCenterChild:function(A,e,r){r|=0;var t=0,i=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(t&=15))<=(0|r)){if((0|t)!=(0|r)&&(A|=i=0|ye(0|r,0,52),e=0|M()|-15728641&e,(0|t)<(0|r)))do{i=0|ye(7,0,3*(14-t|0)|0),t=t+1|0,A&=~i,e&=~(0|M())}while((0|t)<(0|r))}else e=0,A=0;return k(0|e),0|A},_h3ToChildren:PA,_h3ToGeo:OA,_h3ToGeoBoundary:jA,_h3ToParent:CA,_h3UnidirectionalEdgeIsValid:function(A,e){var r=0;if(!(!0&268435456==(2013265920&(e|=0)|0)))return 0|(r=0);switch(r=0|Qe(0|(A|=0),0|e,56),M(),7&r){case 0:case 7:return 0|(r=0)}return!0&16777216==(117440512&e|0)&0!=(0|UA(A,r=-2130706433&e|134217728))?0|(r=0):0|(r=0|FA(A,r))},_hexAreaKm2:function(A){return+ +n[20496+((A|=0)<<3)>>3]},_hexAreaM2:function(A){return+ +n[20624+((A|=0)<<3)>>3]},_hexRing:function(A,e,r,t){A|=0,e|=0,t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0,h=0;if(n=I,I=I+16|0,h=n,!(r|=0))return i[(h=t)>>2]=A,i[h+4>>2]=e,I=n,0|(h=0);i[h>>2]=0;A:do{if(0|UA(A,e))A=1;else{if(a=(0|r)>0){o=0,l=A;do{if(0==(0|(l=0|U(l,e,4,h)))&0==(0|(e=0|M()))){A=2;break A}if(o=o+1|0,0|UA(l,e)){A=1;break A}}while((0|o)<(0|r));if(i[(u=t)>>2]=l,i[u+4>>2]=e,u=r+-1|0,a){a=0,f=1,o=l,A=e;do{if(0==(0|(o=0|U(o,A,2,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(f<<3)|0)>>2]=o,i[s+4>>2]=A,f=f+1|0,0|UA(o,A)){A=1;break A}a=a+1|0}while((0|a)<(0|r));s=0,a=f;do{if(0==(0|(o=0|U(o,A,3,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(f=t+(a<<3)|0)>>2]=o,i[f+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}s=s+1|0}while((0|s)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,1,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,5,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,4,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));for(f=0;;){if(0==(0|(o=0|U(o,A,6,h)))&0==(0|(A=0|M()))){A=2;break A}if((0|f)!=(0|u)){if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,0|UA(o,A)){A=1;break A}a=a+1|0}if((0|(f=f+1|0))>=(0|r)){f=l,a=e;break}}}else f=l,o=l,a=e,A=e}else i[(f=t)>>2]=A,i[f+4>>2]=e,f=A,o=A,a=e,A=e;A=1&((0|f)!=(0|o)|(0|a)!=(0|A))}}while(0);return I=n,0|(h=A)},_i64Subtract:ve,_kRing:F,_kRingDistances:function(A,e,r,t,i){var n;if(0|C(A|=0,e|=0,r|=0,t|=0,i|=0)){if(_e(0|t,0,(n=1+(0|b(3*r|0,r+1|0))|0)<<3|0),0|i)return _e(0|i,0,n<<2|0),void P(A,e,r,t,i,n,0);(i=0|be(n,4))&&(P(A,e,r,t,i,n,0),Be(i))}},_llvm_minnum_f64:Ee,_llvm_round_f64:xe,_malloc:pe,_maxFaceCount:function(A,e){var r=0,t=0;if(t=0|Qe(0|(A|=0),0|(e|=0),45),M(),!(0|S(127&t)))return 0|(t=2);if(t=0|Qe(0|A,0|e,52),M(),!(t&=15))return 0|(t=5);for(r=1;;){if(!(0==((0|ye(7,0,3*(15-r|0)|0))&A|0)&0==((0|M())&e|0))){r=2,A=6;break}if(!(r>>>0>>0)){r=5,A=6;break}r=r+1|0}return 6==(0|A)?0|r:0},_maxH3ToChildrenSize:function(A,e,r){return r|=0,A=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(A&=15))<=(0|r)?0|(r=0|ee(7,r-A|0)):0|(r=0)},_maxKringSize:function(A){return 1+(0|b(3*(A|=0)|0,A+1|0))|0},_maxPolyfillSize:function(A,e){e|=0;var r,t=0,n=0,o=0,a=0,f=0;if(r=I,I=I+48|0,o=r+8|0,n=r,a=0|i[(f=A|=0)+4>>2],i[(t=n)>>2]=i[f>>2],i[t+4>>2]=a,te(n,o),o=0|j(o,e),e=0|i[n>>2],(0|(n=0|i[A+8>>2]))<=0)return I=r,0|(f=(f=(a=(0|o)<(0|(f=e)))?f:o)+12|0);t=0|i[A+12>>2],A=0;do{e=(0|i[t+(A<<3)>>2])+e|0,A=A+1|0}while((0|A)<(0|n));return I=r,0|(f=(f=(f=(0|o)<(0|e))?e:o)+12|0)},_maxUncompactSize:function(A,e,r){A|=0,r|=0;var t=0,n=0,o=0,a=0;if((0|(e|=0))<=0)return 0|(r=0);if((0|r)>=16){for(t=0;;){if(!(0==(0|i[(a=A+(t<<3)|0)>>2])&0==(0|i[a+4>>2]))){t=-1,n=13;break}if((0|(t=t+1|0))>=(0|e)){t=0,n=13;break}}if(13==(0|n))return 0|t}t=0,a=0;A:for(;;){o=0|i[(n=A+(a<<3)|0)>>2],n=0|i[n+4>>2];do{if(!(0==(0|o)&0==(0|n))){if(n=0|Qe(0|o,0|n,52),M(),(0|(n&=15))>(0|r)){t=-1,n=13;break A}if((0|n)==(0|r)){t=t+1|0;break}t=(0|ee(7,r-n|0))+t|0;break}}while(0);if((0|(a=a+1|0))>=(0|e)){n=13;break}}return 13==(0|n)?0|t:0},_memcpy:De,_memset:_e,_numHexagons:function(A){var e;return A=0|i[(e=21008+((A|=0)<<3)|0)>>2],k(0|i[e+4>>2]),0|A},_pentagonIndexCount:function(){return 12},_pointDistKm:DA,_pointDistM:function(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))*6371.007180918475*1e3},_pointDistRads:function(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))},_polyfill:function(A,e,r){var t,n=0,o=0,a=0,f=0,s=0;if(t=I,I=I+48|0,n=t+8|0,o=t,0|function(A,e,r){e|=0,r|=0;var t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,y=0,E=0,x=0,D=0,_=0,F=0,U=0,S=0,T=0,V=0,H=0;H=I,I=I+112|0,U=H+80|0,s=H+72|0,S=H,T=H+56|0,(V=0|pe(32+(i[(u=(A=A|0)+8|0)>>2]<<5)|0))||Q(22848,22448,800,22456);if(ie(A,V),t=0|i[(o=A)+4>>2],i[(f=s)>>2]=i[o>>2],i[f+4>>2]=t,te(s,U),f=0|j(U,e),t=0|i[s>>2],(0|(o=0|i[u>>2]))>0){a=0|i[A+12>>2],n=0;do{t=(0|i[a+(n<<3)>>2])+t|0,n=n+1|0}while((0|n)!=(0|o))}if(n=0|be(F=(f=(0|f)<(0|t)?t:f)+12|0,8),l=0|be(F,8),i[U>>2]=0,_=0|i[(D=A)+4>>2],i[(t=s)>>2]=i[D>>2],i[t+4>>2]=_,0|(t=0|G(s,F,e,U,n,l)))return Be(n),Be(l),Be(V),I=H,0|(V=t);A:do{if((0|i[u>>2])>0){for(o=A+12|0,t=0;a=0|G((0|i[o>>2])+(t<<3)|0,F,e,U,n,l),t=t+1|0,!(0|a);)if((0|t)>=(0|i[u>>2]))break A;return Be(n),Be(l),Be(V),I=H,0|(V=a)}}while(0);(0|f)>-12&&_e(0|l,0,((0|F)>1?F:1)<<3|0);A:do{if((0|i[U>>2])>0){_=((0|F)<0)<<31>>31,m=n,k=l,y=n,E=n,x=l,D=n,t=n,p=n,B=l,b=l,v=l,n=l;e:for(;;){for(w=0|i[U>>2],d=0,g=0,o=0;;){f=(a=S)+56|0;do{i[a>>2]=0,a=a+4|0}while((0|a)<(0|f));if(0|C(s=0|i[(e=m+(d<<3)|0)>>2],e=0|i[e+4>>2],1,S,0)){f=(a=S)+56|0;do{i[a>>2]=0,a=a+4|0}while((0|a)<(0|f));0|(a=0|be(7,4))&&(P(s,e,1,S,a,7,0),Be(a))}c=0;do{l=0|i[(h=S+(c<<3)|0)>>2],h=0|i[h+4>>2];r:do{if(!(0==(0|l)&0==(0|h))){if(s=0|Me(0|l,0|h,0|F,0|_),M(),!(0==(0|(e=0|i[(f=a=r+(s<<3)|0)>>2]))&0==(0|(f=0|i[f+4>>2]))))for(u=0;;){if((0|u)>(0|F))break e;if((0|e)==(0|l)&(0|f)==(0|h))break r;if(0==(0|(e=0|i[(f=a=r+((s=(s+1|0)%(0|F)|0)<<3)|0)>>2]))&0==(0|(f=0|i[f+4>>2])))break;u=u+1|0}0==(0|l)&0==(0|h)||(OA(l,h,T),0|ne(A,V,T)&&(i[(u=a)>>2]=l,i[u+4>>2]=h,i[(u=k+(o<<3)|0)>>2]=l,i[u+4>>2]=h,o=o+1|0))}}while(0);c=c+1|0}while(c>>>0<7);if((0|(g=g+1|0))>=(0|w))break;d=d+1|0}if((0|w)>0&&_e(0|y,0,w<<3|0),i[U>>2]=o,!((0|o)>0))break A;l=n,h=v,c=D,d=b,g=B,w=k,n=p,v=t,b=E,B=y,p=l,t=h,D=x,x=c,E=d,y=g,k=m,m=w}return Be(E),Be(x),Be(V),I=H,0|(V=-1)}t=l}while(0);return Be(V),Be(n),Be(t),I=H,0|(V=0)}(A|=0,e|=0,r|=0)){if(a=0|i[(s=A)+4>>2],i[(f=o)>>2]=i[s>>2],i[f+4>>2]=a,te(o,n),f=0|j(n,e),e=0|i[o>>2],(0|(a=0|i[A+8>>2]))>0){o=0|i[A+12>>2],n=0;do{e=(0|i[o+(n<<3)>>2])+e|0,n=n+1|0}while((0|n)!=(0|a))}(0|(e=(0|f)<(0|e)?e:f))<=-12||_e(0|r,0,8+(((0|(s=e+11|0))>0?s:0)<<3)|0),I=t}else I=t},_res0IndexCount:function(){return 122},_round:Ie,_sbrk:Fe,_sizeOfCoordIJ:function(){return 8},_sizeOfGeoBoundary:function(){return 168},_sizeOfGeoCoord:function(){return 16},_sizeOfGeoPolygon:function(){return 16},_sizeOfGeofence:function(){return 8},_sizeOfH3Index:function(){return 8},_sizeOfLinkedGeoPolygon:function(){return 12},_uncompact:function(A,e,r,t,n){A|=0,r|=0,t|=0,n|=0;var o=0,a=0,f=0,s=0,u=0,l=0;if((0|(e|=0))<=0)return 0|(n=0);if((0|n)>=16){for(o=0;;){if(!(0==(0|i[(l=A+(o<<3)|0)>>2])&0==(0|i[l+4>>2]))){o=14;break}if((0|(o=o+1|0))>=(0|e)){a=0,o=16;break}}if(14==(0|o))return 0|((0|t)>0?-2:-1);if(16==(0|o))return 0|a}o=0,l=0;A:for(;;){a=0|i[(f=u=A+(l<<3)|0)>>2],f=0|i[f+4>>2];do{if(!(0==(0|a)&0==(0|f))){if((0|o)>=(0|t)){a=-1,o=16;break A}if(s=0|Qe(0|a,0|f,52),M(),(0|(s&=15))>(0|n)){a=-2,o=16;break A}if((0|s)==(0|n)){i[(u=r+(o<<3)|0)>>2]=a,i[u+4>>2]=f,o=o+1|0;break}if((0|(a=(0|ee(7,n-s|0))+o|0))>(0|t)){a=-1,o=16;break A}PA(0|i[u>>2],0|i[u+4>>2],n,r+(o<<3)|0),o=a}}while(0);if((0|(l=l+1|0))>=(0|e)){a=0,o=16;break}}return 16==(0|o)?0|a:0},establishStackSpace:function(A,e){I=A|=0},stackAlloc:function(A){var e;return e=I,I=(I=I+(A|=0)|0)+15&-16,0|e},stackRestore:function(A){I=A|=0},stackSave:function(){return 0|I}}}({Math:Math,Int8Array:Int8Array,Int32Array:Int32Array,Uint8Array:Uint8Array,Float32Array:Float32Array,Float64Array:Float64Array},{a:fA,b:function(A){s=A},c:u,d:function(A,e,r,t){fA("Assertion failed: "+g(A)+", at: "+[e?g(e):"unknown filename",r,t?g(t):"unknown function"])},e:function(A){return r.___errno_location&&(v[r.___errno_location()>>2]=A),A},f:N,g:function(A,e,r){B.set(B.subarray(e,e+r),A)},h:function(A){var e=N(),r=16777216,t=2130706432;if(A>t)return!1;for(var i=Math.max(e,16777216);i>0]=e;break;case"i16":b[A>>1]=e;break;case"i32":v[A>>2]=e;break;case"i64":H=[e>>>0,(V=e,+F(V)>=1?V>0?(0|U(+P(V/4294967296),4294967295))>>>0:~~+C((V-+(~~V>>>0))/4294967296)>>>0:0)],v[A>>2]=H[0],v[A+4>>2]=H[1];break;case"float":m[A>>2]=e;break;case"double":k[A>>3]=e;break;default:fA("invalid type for setValue: "+r)}},r.getValue=function(A,e,r){switch("*"===(e=e||"i8").charAt(e.length-1)&&(e="i32"),e){case"i1":case"i8":return p[A>>0];case"i16":return b[A>>1];case"i32":case"i64":return v[A>>2];case"float":return m[A>>2];case"double":return k[A>>3];default:fA("invalid type for getValue: "+e)}return null},r.getTempRet0=u,R){z(R)||(K=R,R=r.locateFile?r.locateFile(K,o):o+K),G++,r.monitorRunDependencies&&r.monitorRunDependencies(G);var tA=function(A){A.byteLength&&(A=new Uint8Array(A)),B.set(A,8),r.memoryInitializerRequest&&delete r.memoryInitializerRequest.response,function(A){if(G--,r.monitorRunDependencies&&r.monitorRunDependencies(G),0==G&&(null!==S&&(clearInterval(S),S=null),T)){var e=T;T=null,e()}}()},iA=function(){i(R,tA,(function(){throw"could not load memory initializer "+R}))},nA=J(R);if(nA)tA(nA.buffer);else if(r.memoryInitializerRequest){var oA=function(){var A=r.memoryInitializerRequest,e=A.response;if(200!==A.status&&0!==A.status){var t=J(r.memoryInitializerRequestURL);if(!t)return console.warn("a problem seems to have happened with Module.memoryInitializerRequest, status: "+A.status+", retrying "+R),void iA();e=t.buffer}tA(e)};r.memoryInitializerRequest.response?setTimeout(oA,0):r.memoryInitializerRequest.addEventListener("load",oA)}else iA()}function aA(A){function e(){X||(X=!0,l||(E(D),E(_),r.onRuntimeInitialized&&r.onRuntimeInitialized(),function(){if(r.postRun)for("function"==typeof r.postRun&&(r.postRun=[r.postRun]);r.postRun.length;)A=r.postRun.shift(),I.unshift(A);var A;E(I)}()))}A=A||n,G>0||(!function(){if(r.preRun)for("function"==typeof r.preRun&&(r.preRun=[r.preRun]);r.preRun.length;)A=r.preRun.shift(),x.unshift(A);var A;E(x)}(),G>0||(r.setStatus?(r.setStatus("Running..."),setTimeout((function(){setTimeout((function(){r.setStatus("")}),1),e()}),1)):e()))}function fA(A){throw r.onAbort&&r.onAbort(A),a(A+=""),f(A),l=!0,"abort("+A+"). Build with -s ASSERTIONS=1 for more info."}if(T=function A(){X||aA(),X||(T=A)},r.run=aA,r.abort=fA,r.preInit)for("function"==typeof r.preInit&&(r.preInit=[r.preInit]);r.preInit.length>0;)r.preInit.pop()();return aA(),A}("object"==typeof t?t:{}),i="number",n={};[["sizeOfH3Index",i],["sizeOfGeoCoord",i],["sizeOfGeoBoundary",i],["sizeOfGeoPolygon",i],["sizeOfGeofence",i],["sizeOfLinkedGeoPolygon",i],["sizeOfCoordIJ",i],["h3IsValid",i,[i,i]],["geoToH3",i,[i,i,i]],["h3ToGeo",null,[i,i,i]],["h3ToGeoBoundary",null,[i,i,i]],["maxKringSize",i,[i]],["kRing",null,[i,i,i,i]],["kRingDistances",null,[i,i,i,i,i]],["hexRing",null,[i,i,i,i]],["maxPolyfillSize",i,[i,i]],["polyfill",null,[i,i,i]],["h3SetToLinkedGeo",null,[i,i,i]],["destroyLinkedPolygon",null,[i]],["compact",i,[i,i,i]],["uncompact",i,[i,i,i,i,i]],["maxUncompactSize",i,[i,i,i]],["h3IsPentagon",i,[i,i]],["h3IsResClassIII",i,[i,i]],["h3GetBaseCell",i,[i,i]],["h3GetResolution",i,[i,i]],["maxFaceCount",i,[i,i]],["h3GetFaces",null,[i,i,i]],["h3ToParent",i,[i,i,i]],["h3ToChildren",null,[i,i,i,i]],["h3ToCenterChild",i,[i,i,i]],["maxH3ToChildrenSize",i,[i,i,i]],["h3IndexesAreNeighbors",i,[i,i,i,i]],["getH3UnidirectionalEdge",i,[i,i,i,i]],["getOriginH3IndexFromUnidirectionalEdge",i,[i,i]],["getDestinationH3IndexFromUnidirectionalEdge",i,[i,i]],["h3UnidirectionalEdgeIsValid",i,[i,i]],["getH3IndexesFromUnidirectionalEdge",null,[i,i,i]],["getH3UnidirectionalEdgesFromHexagon",null,[i,i,i]],["getH3UnidirectionalEdgeBoundary",null,[i,i,i]],["h3Distance",i,[i,i,i,i]],["h3Line",i,[i,i,i,i,i]],["h3LineSize",i,[i,i,i,i]],["experimentalH3ToLocalIj",i,[i,i,i,i,i]],["experimentalLocalIjToH3",i,[i,i,i,i]],["hexAreaM2",i,[i]],["hexAreaKm2",i,[i]],["edgeLengthM",i,[i]],["edgeLengthKm",i,[i]],["pointDistM",i,[i,i]],["pointDistKm",i,[i,i]],["pointDistRads",i,[i,i]],["cellAreaM2",i,[i,i]],["cellAreaKm2",i,[i,i]],["cellAreaRads2",i,[i,i]],["exactEdgeLengthM",i,[i,i]],["exactEdgeLengthKm",i,[i,i]],["exactEdgeLengthRads",i,[i,i]],["numHexagons",i,[i]],["getRes0Indexes",null,[i]],["res0IndexCount",i],["getPentagonIndexes",null,[i,i]],["pentagonIndexCount",i]].forEach((function(A){n[A[0]]=t.cwrap.apply(t,A)}));var o=16,a=n.sizeOfH3Index(),f=n.sizeOfGeoCoord(),s=n.sizeOfGeoBoundary(),u=n.sizeOfGeoPolygon(),l=n.sizeOfGeofence(),h=n.sizeOfLinkedGeoPolygon(),c=n.sizeOfCoordIJ(),d={m:"m",m2:"m2",km:"km",km2:"km2",rads:"rads",rads2:"rads2"};function g(A){if("number"!=typeof A||A<0||A>15||Math.floor(A)!==A)throw new Error("Invalid resolution: "+A)}var w=/[^0-9a-fA-F]/;function p(A){if(Array.isArray(A)&&2===A.length&&Number.isInteger(A[0])&&Number.isInteger(A[1]))return A;if("string"!=typeof A||w.test(A))return[0,0];var e=parseInt(A.substring(0,A.length-8),o);return[parseInt(A.substring(A.length-8),o),e]}function B(A){if(A>=0)return A.toString(o);var e=v(8,(A&=2147483647).toString(o));return e=(parseInt(e[0],o)+8).toString(o)+e.substring(1)}function b(A,e){return B(e)+v(8,B(A))}function v(A,e){for(var r=A-e.length,t="",i=0;i=0&&r.push(n)}return r}(a,o);return t._free(a),f},r.h3GetResolution=function(A){var e=p(A),r=e[0],t=e[1];return n.h3IsValid(r,t)?n.h3GetResolution(r,t):-1},r.geoToH3=function(A,e,r){var i=t._malloc(f);t.HEAPF64.set([A,e].map(U),i/8);var o=M(n.geoToH3(i,r));return t._free(i),o},r.h3ToGeo=function(A){var e=t._malloc(f),r=p(A),i=r[0],o=r[1];n.h3ToGeo(i,o,e);var a=I(e);return t._free(e),a},r.h3ToGeoBoundary=function(A,e){var r=t._malloc(s),i=p(A),o=i[0],a=i[1];n.h3ToGeoBoundary(o,a,r);var f=C(r,e,e);return t._free(r),f},r.h3ToParent=function(A,e){var r=p(A),t=r[0],i=r[1];return M(n.h3ToParent(t,i,e))},r.h3ToChildren=function(A,e){if(!P(A))return[];var r=p(A),i=r[0],o=r[1],f=n.maxH3ToChildrenSize(i,o,e),s=t._calloc(f,a);n.h3ToChildren(i,o,e,s);var u=E(s,f);return t._free(s),u},r.h3ToCenterChild=function(A,e){var r=p(A),t=r[0],i=r[1];return M(n.h3ToCenterChild(t,i,e))},r.kRing=function(A,e){var r=p(A),i=r[0],o=r[1],f=n.maxKringSize(e),s=t._calloc(f,a);n.kRing(i,o,e,s);var u=E(s,f);return t._free(s),u},r.kRingDistances=function(A,e){var r=p(A),i=r[0],o=r[1],f=n.maxKringSize(e),s=t._calloc(f,a),u=t._calloc(f,4);n.kRingDistances(i,o,e,s,u);for(var l=[],h=0;h0){r=t._calloc(i,l);for(var f=0;f0){for(var n=t.getValue(A+r,"i32"),o=0;o */ +r.read=function(A,e,r,t,i){var n,o,a=8*i-t-1,f=(1<>1,u=-7,l=r?i-1:0,h=r?-1:1,c=A[e+l];for(l+=h,n=c&(1<<-u)-1,c>>=-u,u+=a;u>0;n=256*n+A[e+l],l+=h,u-=8);for(o=n&(1<<-u)-1,n>>=-u,u+=t;u>0;o=256*o+A[e+l],l+=h,u-=8);if(0===n)n=1-s;else{if(n===f)return o?NaN:1/0*(c?-1:1);o+=Math.pow(2,t),n-=s}return(c?-1:1)*o*Math.pow(2,n-t)},r.write=function(A,e,r,t,i,n){var o,a,f,s=8*n-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,c=t?0:n-1,d=t?1:-1,g=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=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(f=Math.pow(2,-o))<1&&(o--,f*=2),(e+=o+l>=1?h/f:h*Math.pow(2,1-l))*f>=2&&(o++,f/=2),o+l>=u?(a=0,o=u):o+l>=1?(a=(e*f-1)*Math.pow(2,i),o+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),o=0));i>=8;A[r+c]=255&a,c+=d,a/=256,i-=8);for(o=o<0;A[r+c]=255&o,c+=d,o/=256,s-=8);A[r+c-d]|=128*g}},{}],9:[function(A,e,r){"use strict";e.exports=i;var t=A("ieee754");function i(A){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(A)?A:new Uint8Array(A||0),this.pos=0,this.type=0,this.length=this.buf.length}i.Varint=0,i.Fixed64=1,i.Bytes=2,i.Fixed32=5;var n=4294967296,o=1/n,a="undefined"==typeof TextDecoder?null:new TextDecoder("utf8");function f(A){return A.type===i.Bytes?A.readVarint()+A.pos:A.pos+1}function s(A,e,r){return r?4294967296*e+(A>>>0):4294967296*(e>>>0)+(A>>>0)}function u(A,e,r){var t=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(t);for(var i=r.pos-1;i>=A;i--)r.buf[i+t]=r.buf[i]}function l(A,e){for(var r=0;r>>8,A[r+2]=e>>>16,A[r+3]=e>>>24}function k(A,e){return(A[e]|A[e+1]<<8|A[e+2]<<16)+(A[e+3]<<24)}i.prototype={destroy:function(){this.buf=null},readFields:function(A,e,r){for(r=r||this.length;this.pos>3,n=this.pos;this.type=7&t,A(i,e,this),this.pos===n&&this.skip(t)}return e},readMessage:function(A,e){return this.readFields(A,e,this.readVarint()+this.pos)},readFixed32:function(){var A=v(this.buf,this.pos);return this.pos+=4,A},readSFixed32:function(){var A=k(this.buf,this.pos);return this.pos+=4,A},readFixed64:function(){var A=v(this.buf,this.pos)+v(this.buf,this.pos+4)*n;return this.pos+=8,A},readSFixed64:function(){var A=v(this.buf,this.pos)+k(this.buf,this.pos+4)*n;return this.pos+=8,A},readFloat:function(){var A=t.read(this.buf,this.pos,!0,23,4);return this.pos+=4,A},readDouble:function(){var A=t.read(this.buf,this.pos,!0,52,8);return this.pos+=8,A},readVarint:function(A){var e,r,t=this.buf;return e=127&(r=t[this.pos++]),r<128?e:(e|=(127&(r=t[this.pos++]))<<7,r<128?e:(e|=(127&(r=t[this.pos++]))<<14,r<128?e:(e|=(127&(r=t[this.pos++]))<<21,r<128?e:function(A,e,r){var t,i,n=r.buf;if(i=n[r.pos++],t=(112&i)>>4,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<3,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<10,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<17,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<24,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(1&i)<<31,i<128)return s(A,t,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=t[this.pos]))<<28,A,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var A=this.readVarint();return A%2==1?(A+1)/-2:A/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var A=this.readVarint()+this.pos,e=this.pos;return this.pos=A,A-e>=12&&a?function(A,e,r){return a.decode(A.subarray(e,r))}(this.buf,e,A):function(A,e,r){var t="",i=e;for(;i239?4:f>223?3:f>191?2:1;if(i+u>r)break;1===u?f<128&&(s=f):2===u?128==(192&(n=A[i+1]))&&(s=(31&f)<<6|63&n)<=127&&(s=null):3===u?(n=A[i+1],o=A[i+2],128==(192&n)&&128==(192&o)&&((s=(15&f)<<12|(63&n)<<6|63&o)<=2047||s>=55296&&s<=57343)&&(s=null)):4===u&&(n=A[i+1],o=A[i+2],a=A[i+3],128==(192&n)&&128==(192&o)&&128==(192&a)&&((s=(15&f)<<18|(63&n)<<12|(63&o)<<6|63&a)<=65535||s>=1114112)&&(s=null)),null===s?(s=65533,u=1):s>65535&&(s-=65536,t+=String.fromCharCode(s>>>10&1023|55296),s=56320|1023&s),t+=String.fromCharCode(s),i+=u}return t}(this.buf,e,A)},readBytes:function(){var A=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,A);return this.pos=A,e},readPackedVarint:function(A,e){if(this.type!==i.Bytes)return A.push(this.readVarint(e));var r=f(this);for(A=A||[];this.pos127;);else if(e===i.Bytes)this.pos=this.readVarint()+this.pos;else if(e===i.Fixed32)this.pos+=4;else{if(e!==i.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(A,e){this.writeVarint(A<<3|e)},realloc:function(A){for(var e=this.length||16;e268435455||A<0?function(A,e){var r,t;A>=0?(r=A%4294967296|0,t=A/4294967296|0):(t=~(-A/4294967296),4294967295^(r=~(-A%4294967296))?r=r+1|0:(r=0,t=t+1|0));if(A>=0x10000000000000000||A<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(A,e,r){r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos]=127&A}(r,0,e),function(A,e){var r=(7&A)<<4;if(e.buf[e.pos++]|=r|((A>>>=3)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;e.buf[e.pos++]=127&A}(t,e)}(A,this):(this.realloc(4),this.buf[this.pos++]=127&A|(A>127?128:0),A<=127||(this.buf[this.pos++]=127&(A>>>=7)|(A>127?128:0),A<=127||(this.buf[this.pos++]=127&(A>>>=7)|(A>127?128:0),A<=127||(this.buf[this.pos++]=A>>>7&127))))},writeSVarint:function(A){this.writeVarint(A<0?2*-A-1:2*A)},writeBoolean:function(A){this.writeVarint(Boolean(A))},writeString:function(A){A=String(A),this.realloc(4*A.length),this.pos++;var e=this.pos;this.pos=function(A,e,r){for(var t,i,n=0;n55295&&t<57344){if(!i){t>56319||n+1===e.length?(A[r++]=239,A[r++]=191,A[r++]=189):i=t;continue}if(t<56320){A[r++]=239,A[r++]=191,A[r++]=189,i=t;continue}t=i-55296<<10|t-56320|65536,i=null}else i&&(A[r++]=239,A[r++]=191,A[r++]=189,i=null);t<128?A[r++]=t:(t<2048?A[r++]=t>>6|192:(t<65536?A[r++]=t>>12|224:(A[r++]=t>>18|240,A[r++]=t>>12&63|128),A[r++]=t>>6&63|128),A[r++]=63&t|128)}return r}(this.buf,A,this.pos);var r=this.pos-e;r>=128&&u(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r},writeFloat:function(A){this.realloc(4),t.write(this.buf,A,this.pos,!0,23,4),this.pos+=4},writeDouble:function(A){this.realloc(8),t.write(this.buf,A,this.pos,!0,52,8),this.pos+=8},writeBytes:function(A){var e=A.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&u(r,t,this),this.pos=r-1,this.writeVarint(t),this.pos+=t},writeMessage:function(A,e,r){this.writeTag(A,i.Bytes),this.writeRawMessage(e,r)},writePackedVarint:function(A,e){e.length&&this.writeMessage(A,l,e)},writePackedSVarint:function(A,e){e.length&&this.writeMessage(A,h,e)},writePackedBoolean:function(A,e){e.length&&this.writeMessage(A,g,e)},writePackedFloat:function(A,e){e.length&&this.writeMessage(A,c,e)},writePackedDouble:function(A,e){e.length&&this.writeMessage(A,d,e)},writePackedFixed32:function(A,e){e.length&&this.writeMessage(A,w,e)},writePackedSFixed32:function(A,e){e.length&&this.writeMessage(A,p,e)},writePackedFixed64:function(A,e){e.length&&this.writeMessage(A,B,e)},writePackedSFixed64:function(A,e){e.length&&this.writeMessage(A,b,e)},writeBytesField:function(A,e){this.writeTag(A,i.Bytes),this.writeBytes(e)},writeFixed32Field:function(A,e){this.writeTag(A,i.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(A,e){this.writeTag(A,i.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(A,e){this.writeTag(A,i.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(A,e){this.writeTag(A,i.Fixed64),this.writeSFixed64(e)},writeVarintField:function(A,e){this.writeTag(A,i.Varint),this.writeVarint(e)},writeSVarintField:function(A,e){this.writeTag(A,i.Varint),this.writeSVarint(e)},writeStringField:function(A,e){this.writeTag(A,i.Bytes),this.writeString(e)},writeFloatField:function(A,e){this.writeTag(A,i.Fixed32),this.writeFloat(e)},writeDoubleField:function(A,e){this.writeTag(A,i.Fixed64),this.writeDouble(e)},writeBooleanField:function(A,e){this.writeVarintField(A,Boolean(e))}}},{ieee754:8}],10:[function(A,e,r){var t=A("pbf"),i=A("./lib/geojson_wrapper");function n(A){var e=new t;return function(A,e){for(var r in A.layers)e.writeMessage(3,o,A.layers[r])}(A,e),e.finish()}function o(A,e){var r;e.writeVarintField(15,A.version||1),e.writeStringField(1,A.name||""),e.writeVarintField(5,A.extent||4096);var t={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r>31}function l(A,e){for(var r=A.loadGeometry(),t=A.type,i=0,n=0,o=r.length,a=0;anew Promise(((r,t)=>{var i;r((i=e,{type:"FeatureCollection",features:A.cells.map((A=>{const e={properties:A,geometry:{type:i.geometry_type,coordinates:i.generate(A.h3id)}};return i.promoteID||(e.id=parseInt(A.h3id,16)),e}))}))})),a=A=>{const e=["type","data","maxzoom","attribution","buffer","filter","tolerance","cluster","clusterRadius","clusterMaxZoom","clusterMinPoints","clusterProperties","lineMetrics","generateId","promoteId"];return f(A,((A,r)=>e.includes(A)))},f=(A,e)=>Object.fromEntries(Object.entries(A).filter((([A,r])=>e(A,r))));t.Map.prototype.addH3TSource=function(A,e){const r=Object.assign({},n,e,{type:"vector",format:"pbf"});r.generate=A=>"Polygon"===r.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),r.promoteId&&(r.promoteId="h3id"),t.addProtocol("h3tiles",((A,e)=>{const t=`http${!1===r.https?"":"s"}://${A.url.split("://")[1]}`,n=A.url.split(/\/|\./i),a=n.length,f=n.slice(a-4,a-1).map((A=>1*A)),s=new AbortController,u=s.signal;let l;r.timeout>0&&setTimeout((()=>s.abort()),r.timeout),fetch(t,{signal:u}).then((A=>{if(A.ok)return l=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,r))).then((A=>{const t=i.tovt(A).getTile(...f),n={};n[r.sourcelayer]=t;const o=i.topbf.fromGeojsonVt(n,{version:2});r.debug&&console.log(`${f}: ${A.features.length} features, ${(performance.now()-l).toFixed(0)} ms`),e(null,o,null,null)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Tile .../${f.join("/")}.h3t is taking too long to fetch`),e(new Error(A))}))})),this.addSource(A,(A=>{const e=["type","url","tiles","bounds","scheme","minzoom","maxzoom","attribution","promoteId","volatile"];return f(A,((A,r)=>e.includes(A)))})(r))};t.Map.prototype.addH3JSource=function(A,e){const r=new AbortController,t=r.signal,f=Object.assign({},n,e,{type:"geojson"});let s;if(f.generate=A=>"Polygon"===f.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),f.promoteId&&(f.promoteId="h3id"),f.timeout>0&&setTimeout((()=>r.abort()),f.timeout),"string"==typeof f.data)return f.timeout>0&&setTimeout((()=>r.abort()),f.timeout),new Promise(((e,r)=>{fetch(f.data,{signal:t}).then((A=>{if(A.ok)return s=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,f))).then((r=>{f.data=r,this.addSource(A,a(f)),f.debug&&console.log(`${r.features.length} features, ${(performance.now()-s).toFixed(0)} ms`),e(this)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Source file ${f.data} is taking too long to fetch`),console.error(A.message)}))}));o(f.data,f).then((e=>(f.data=e,this.addSource(A,a(f)),new Promise(((A,e)=>A(this))))))};t.Map.prototype.setH3JData=function(A,e,r){const t=Object.assign({},n,r);t.generate=A=>"Polygon"===t.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),t.promoteId&&(t.promoteId="h3id");const a=new AbortController,f=a.signal,s=this.getSource(A);let u;"string"==typeof e?(t.timeout>0&&setTimeout((()=>a.abort()),t.timeout),fetch(e,{signal:f}).then((A=>{if(A.ok)return u=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,t))).then((A=>{s.setData(A),t.debug&&console.log(`${A.features.length} features, ${(performance.now()-u).toFixed(0)} ms`)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Data file ${e} is taking too long to fetch`),console.error(A.message)}))):o(e,t).then((A=>s.setData(A)))}},{"geojson-vt":6,"h3-js":7,"vt-pbf":10}]},{},[12])(12)})); \ No newline at end of file diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css new file mode 100644 index 0000000..0347a27 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css @@ -0,0 +1,88 @@ + +/* Override default control style */ +.mapbox-gl-draw_ctrl-bottom-left, +.mapbox-gl-draw_ctrl-top-left { + margin-left:0; + border-radius:0 4px 4px 0; +} +.mapbox-gl-draw_ctrl-top-right, +.mapbox-gl-draw_ctrl-bottom-right { + margin-right:0; + border-radius:4px 0 0 4px; +} + +.mapbox-gl-draw_ctrl-draw-btn { + border-color:rgba(0,0,0,0.9); + color:rgba(255,255,255,0.5); + width:30px; + height:30px; +} + +.mapbox-gl-draw_ctrl-draw-btn.active, +.mapbox-gl-draw_ctrl-draw-btn.active:hover { + background-color:rgb(0 0 0/5%); +} +.mapbox-gl-draw_ctrl-draw-btn { + background-repeat: no-repeat; + background-position: center; +} + +.mapbox-gl-draw_point { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m10 2c-3.3 0-6 2.7-6 6s6 9 6 9 6-5.7 6-9-2.7-6-6-6zm0 2c2.1 0 3.8 1.7 3.8 3.8 0 1.5-1.8 3.9-2.9 5.2h-1.7c-1.1-1.4-2.9-3.8-2.9-5.2-.1-2.1 1.6-3.8 3.7-3.8z"/>%3C/svg>'); +} +.mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m15 12.3v-4.6c.6-.3 1-1 1-1.7 0-1.1-.9-2-2-2-.7 0-1.4.4-1.7 1h-4.6c-.3-.6-1-1-1.7-1-1.1 0-2 .9-2 2 0 .7.4 1.4 1 1.7v4.6c-.6.3-1 1-1 1.7 0 1.1.9 2 2 2 .7 0 1.4-.4 1.7-1h4.6c.3.6 1 1 1.7 1 1.1 0 2-.9 2-2 0-.7-.4-1.4-1-1.7zm-8-.3v-4l1-1h4l1 1v4l-1 1h-4z"/>%3C/svg>'); +} +.mapbox-gl-draw_line { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m13.5 3.5c-1.4 0-2.5 1.1-2.5 2.5 0 .3 0 .6.2.9l-3.8 3.8c-.3-.1-.6-.2-.9-.2-1.4 0-2.5 1.1-2.5 2.5s1.1 2.5 2.5 2.5 2.5-1.1 2.5-2.5c0-.3 0-.6-.2-.9l3.8-3.8c.3.1.6.2.9.2 1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5z"/>%3C/svg>'); +} +.mapbox-gl-draw_trash { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="M10,3.4 c-0.8,0-1.5,0.5-1.8,1.2H5l-1,1v1h12v-1l-1-1h-3.2C11.5,3.9,10.8,3.4,10,3.4z M5,8v7c0,1,1,2,2,2h6c1,0,2-1,2-2V8h-2v5.5h-1.5V8h-3 v5.5H7V8H5z"/>%3C/svg>'); +} +.mapbox-gl-draw_uncombine { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m12 2c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l1 1c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-1-1c-.2-.2-.4-.3-.7-.3zm4 4c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l1 1c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-1-1c-.2-.2-.4-.3-.7-.3zm-7 1c-1 0-1 1-.5 1.5.3.3 1 1 1 1l-1 1s-.5.5 0 1 1 0 1 0l1-1 1 1c.5.5 1.5.5 1.5-.5v-4zm-5 3c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l4.9 4.9c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-4.9-4.9c-.1-.2-.4-.3-.7-.3z"/>%3C/svg>'); +} +.mapbox-gl-draw_combine { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="M12.1,2c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l4.9,4.9c0.4,0.4,1,0.4,1.4,0l1-1 c0.4-0.4,0.4-1,0-1.4l-4.9-4.9C12.6,2.1,12.3,2,12.1,2z M8,8C7,8,7,9,7.5,9.5c0.3,0.3,1,1,1,1l-1,1c0,0-0.5,0.5,0,1s1,0,1,0l1-1l1,1 C11,13,12,13,12,12V8H8z M4,10c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l1,1c0.4,0.4,1,0.4,1.4,0l1-1c0.4-0.4,0.4-1,0-1.4 l-1-1C4.5,10.1,4.3,10,4,10z M8,14c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l1,1c0.4,0.4,1,0.4,1.4,0l1-1 c0.4-0.4,0.4-1,0-1.4l-1-1C8.5,14.1,8.3,14,8,14z"/>%3C/svg>'); +} + +.mapboxgl-map.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: pointer; +} +.mapboxgl-map.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mouse-add .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: crosshair; +} +.mapboxgl-map.mouse-move.mode-direct_select .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: grab; + cursor: -moz-grab; + cursor: -webkit-grab; +} +.mapboxgl-map.mode-direct_select.feature-vertex.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mode-direct_select.feature-midpoint.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: cell; +} +.mapboxgl-map.mode-direct_select.feature-feature.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mode-static.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: grab; + cursor: -moz-grab; + cursor: -webkit-grab; +} + +.mapbox-gl-draw_boxselect { + pointer-events: none; + position: absolute; + top: 0; + left: 0; + width: 0; + height: 0; + background: rgba(0,0,0,.1); + border: 2px dotted #fff; + opacity: 0.5; +} diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js new file mode 100644 index 0000000..271f1f7 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js @@ -0,0 +1,2 @@ +var e,t;e=this,t=function(){const e=function(e,t){const o={drag:[],click:[],mousemove:[],mousedown:[],mouseup:[],mouseout:[],keydown:[],keyup:[],touchstart:[],touchmove:[],touchend:[],tap:[]},n={on(e,t,n){if(void 0===o[e])throw new Error(`Invalid event type: ${e}`);o[e].push({selector:t,fn:n})},render(e){t.store.featureChanged(e)}},r=function(e,r){const i=o[e];let s=i.length;for(;s--;){const e=i[s];if(e.selector(r)){e.fn.call(n,r)||t.store.render(),t.ui.updateMapClasses();break}}};return e.start.call(n),{render:e.render,stop(){e.stop&&e.stop()},trash(){e.trash&&(e.trash(),t.store.render())},combineFeatures(){e.combineFeatures&&e.combineFeatures()},uncombineFeatures(){e.uncombineFeatures&&e.uncombineFeatures()},drag(e){r("drag",e)},click(e){r("click",e)},mousemove(e){r("mousemove",e)},mousedown(e){r("mousedown",e)},mouseup(e){r("mouseup",e)},mouseout(e){r("mouseout",e)},keydown(e){r("keydown",e)},keyup(e){r("keyup",e)},touchstart(e){r("touchstart",e)},touchmove(e){r("touchmove",e)},touchend(e){r("touchend",e)},tap(e){r("tap",e)}}};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var o,n,r={},i={};function s(){return o||(o=1,i.RADIUS=6378137,i.FLATTENING=1/298.257223563,i.POLAR_RADIUS=6356752.3142),i}var a=function(){if(n)return r;n=1;var e=s();function t(e){var t=0;if(e&&e.length>0){t+=Math.abs(o(e[0]));for(var n=1;n2){for(c=0;c(e.geometry.type===h.POLYGON&&(e.area=c.geometry({type:h.FEATURE,property:{},geometry:e.geometry})),e))).sort(S).map((e=>(delete e.area,e)))}function L(e,t=0){return[[e.point.x-t,e.point.y-t],[e.point.x+t,e.point.y+t]]}function M(e){if(this._items={},this._nums={},this._length=e?e.length:0,e)for(let t=0,o=e.length;t{e.push({k:t,v:this._items[t]})})),Object.keys(this._nums).forEach((t=>{e.push({k:JSON.parse(t),v:this._nums[t]})})),e.sort(((e,t)=>e.v-t.v)).map((e=>e.k))},M.prototype.clear=function(){return this._length=0,this._items={},this._nums={},this};const N=[y.FEATURE,y.MIDPOINT,y.VERTEX];var b={click:function(e,t,o){return x(e,t,o,o.options.clickBuffer)},touch:function(e,t,o){return x(e,t,o,o.options.touchBuffer)}};function x(e,t,o,n){if(null===o.map)return[];const r=e?L(e,n):t,i={};o.options.styles&&(i.layers=o.options.styles.map((e=>e.id)).filter((e=>null!=o.map.getLayer(e))));const s=o.map.queryRenderedFeatures(r,i).filter((e=>-1!==N.indexOf(e.properties.meta))),a=new M,c=[];return s.forEach((e=>{const t=e.properties.id;a.has(t)||(a.add(t),c.push(e))})),O(c)}function A(e,t){const o=b.click(e,null,t),n={mouse:d.NONE};return o[0]&&(n.mouse=o[0].properties.active===E.ACTIVE?d.MOVE:d.POINTER,n.feature=o[0].properties.meta),-1!==t.events.currentModeName().indexOf("draw")&&(n.mouse=d.ADD),t.ui.queueMapClasses(n),t.ui.updateMapClasses(),o[0]}function P(e,t){const o=e.x-t.x,n=e.y-t.y;return Math.sqrt(o*o+n*n)}const F=4,R=12,w=500;function D(e,t,o={}){const n=null!=o.fineTolerance?o.fineTolerance:F,r=null!=o.grossTolerance?o.grossTolerance:R,i=null!=o.interval?o.interval:w;e.point=e.point||t.point,e.time=e.time||t.time;const s=P(e.point,t.point);return s(o=t)=>{let n="",r=0|o;for(;r--;)n+=e[Math.random()*e.length|0];return n})("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",32);function B(){return G()}const j=function(e,t){this.ctx=e,this.properties=t.properties||{},this.coordinates=t.geometry.coordinates,this.id=t.id||B(),this.type=t.geometry.type};j.prototype.changed=function(){this.ctx.store.featureChanged(this.id)},j.prototype.incomingCoords=function(e){this.setCoordinates(e)},j.prototype.setCoordinates=function(e){this.coordinates=e,this.changed()},j.prototype.getCoordinates=function(){return JSON.parse(JSON.stringify(this.coordinates))},j.prototype.setProperty=function(e,t){this.properties[e]=t},j.prototype.toGeoJSON=function(){return JSON.parse(JSON.stringify({id:this.id,type:h.FEATURE,properties:this.properties,geometry:{coordinates:this.getCoordinates(),type:this.type}}))},j.prototype.internal=function(e){const t={id:this.id,meta:y.FEATURE,"meta:type":this.type,active:E.INACTIVE,mode:e};if(this.ctx.options.userProperties)for(const e in this.properties)t[`user_${e}`]=this.properties[e];return{type:h.FEATURE,properties:t,geometry:{coordinates:this.getCoordinates(),type:this.type}}};const J=function(e,t){j.call(this,e,t)};(J.prototype=Object.create(j.prototype)).isValid=function(){return"number"==typeof this.coordinates[0]&&"number"==typeof this.coordinates[1]},J.prototype.updateCoordinate=function(e,t,o){this.coordinates=3===arguments.length?[t,o]:[e,t],this.changed()},J.prototype.getCoordinate=function(){return this.getCoordinates()};const $=function(e,t){j.call(this,e,t)};($.prototype=Object.create(j.prototype)).isValid=function(){return this.coordinates.length>1},$.prototype.addCoordinate=function(e,t,o){this.changed();const n=parseInt(e,10);this.coordinates.splice(n,0,[t,o])},$.prototype.getCoordinate=function(e){const t=parseInt(e,10);return JSON.parse(JSON.stringify(this.coordinates[t]))},$.prototype.removeCoordinate=function(e){this.changed(),this.coordinates.splice(parseInt(e,10),1)},$.prototype.updateCoordinate=function(e,t,o){const n=parseInt(e,10);this.coordinates[n]=[t,o],this.changed()};const Y=function(e,t){j.call(this,e,t),this.coordinates=this.coordinates.map((e=>e.slice(0,-1)))};(Y.prototype=Object.create(j.prototype)).isValid=function(){return 0!==this.coordinates.length&&this.coordinates.every((e=>e.length>2))},Y.prototype.incomingCoords=function(e){this.coordinates=e.map((e=>e.slice(0,-1))),this.changed()},Y.prototype.setCoordinates=function(e){this.coordinates=e,this.changed()},Y.prototype.addCoordinate=function(e,t,o){this.changed();const n=e.split(".").map((e=>parseInt(e,10)));this.coordinates[n[0]].splice(n[1],0,[t,o])},Y.prototype.removeCoordinate=function(e){this.changed();const t=e.split(".").map((e=>parseInt(e,10))),o=this.coordinates[t[0]];o&&(o.splice(t[1],1),o.length<3&&this.coordinates.splice(t[0],1))},Y.prototype.getCoordinate=function(e){const t=e.split(".").map((e=>parseInt(e,10))),o=this.coordinates[t[0]];return JSON.parse(JSON.stringify(o[t[1]]))},Y.prototype.getCoordinates=function(){return this.coordinates.map((e=>e.concat([e[0]])))},Y.prototype.updateCoordinate=function(e,t,o){this.changed();const n=e.split("."),r=parseInt(n[0],10),i=parseInt(n[1],10);void 0===this.coordinates[r]&&(this.coordinates[r]=[]),this.coordinates[r][i]=[t,o]};const H={MultiPoint:J,MultiLineString:$,MultiPolygon:Y},X=(e,t,o,n,r)=>{const i=o.split("."),s=parseInt(i[0],10),a=i[1]?i.slice(1).join("."):null;return e[s][t](a,n,r)},q=function(e,t){if(j.call(this,e,t),delete this.coordinates,this.model=H[t.geometry.type],void 0===this.model)throw new TypeError(`${t.geometry.type} is not a valid type`);this.features=this._coordinatesToFeatures(t.geometry.coordinates)};function Z(e){this.map=e.map,this.drawConfig=JSON.parse(JSON.stringify(e.options||{})),this._ctx=e}(q.prototype=Object.create(j.prototype))._coordinatesToFeatures=function(e){const t=this.model.bind(this);return e.map((e=>new t(this.ctx,{id:B(),type:h.FEATURE,properties:{},geometry:{coordinates:e,type:this.type.replace("Multi","")}})))},q.prototype.isValid=function(){return this.features.every((e=>e.isValid()))},q.prototype.setCoordinates=function(e){this.features=this._coordinatesToFeatures(e),this.changed()},q.prototype.getCoordinate=function(e){return X(this.features,"getCoordinate",e)},q.prototype.getCoordinates=function(){return JSON.parse(JSON.stringify(this.features.map((e=>e.type===h.POLYGON?e.getCoordinates():e.coordinates))))},q.prototype.updateCoordinate=function(e,t,o){X(this.features,"updateCoordinate",e,t,o),this.changed()},q.prototype.addCoordinate=function(e,t,o){X(this.features,"addCoordinate",e,t,o),this.changed()},q.prototype.removeCoordinate=function(e){X(this.features,"removeCoordinate",e),this.changed()},q.prototype.getFeatures=function(){return this.features},Z.prototype.setSelected=function(e){return this._ctx.store.setSelected(e)},Z.prototype.setSelectedCoordinates=function(e){this._ctx.store.setSelectedCoordinates(e),e.reduce(((e,t)=>(void 0===e[t.feature_id]&&(e[t.feature_id]=!0,this._ctx.store.get(t.feature_id).changed()),e)),{})},Z.prototype.getSelected=function(){return this._ctx.store.getSelected()},Z.prototype.getSelectedIds=function(){return this._ctx.store.getSelectedIds()},Z.prototype.isSelected=function(e){return this._ctx.store.isSelected(e)},Z.prototype.getFeature=function(e){return this._ctx.store.get(e)},Z.prototype.select=function(e){return this._ctx.store.select(e)},Z.prototype.deselect=function(e){return this._ctx.store.deselect(e)},Z.prototype.deleteFeature=function(e,t={}){return this._ctx.store.delete(e,t)},Z.prototype.addFeature=function(e,t={}){return this._ctx.store.add(e,t)},Z.prototype.clearSelectedFeatures=function(){return this._ctx.store.clearSelected()},Z.prototype.clearSelectedCoordinates=function(){return this._ctx.store.clearSelectedCoordinates()},Z.prototype.setActionableState=function(e={}){const t={trash:e.trash||!1,combineFeatures:e.combineFeatures||!1,uncombineFeatures:e.uncombineFeatures||!1};return this._ctx.events.actionable(t)},Z.prototype.changeMode=function(e,t={},o={}){return this._ctx.events.changeMode(e,t,o)},Z.prototype.fire=function(e,t){return this._ctx.events.fire(e,t)},Z.prototype.updateUIClasses=function(e){return this._ctx.ui.queueMapClasses(e)},Z.prototype.activateUIButton=function(e){return this._ctx.ui.setActiveButton(e)},Z.prototype.featuresAt=function(e,t,o="click"){if("click"!==o&&"touch"!==o)throw new Error("invalid buffer type");return b[o](e,t,this._ctx)},Z.prototype.newFeature=function(e){const t=e.geometry.type;return t===h.POINT?new J(this._ctx,e):t===h.LINE_STRING?new $(this._ctx,e):t===h.POLYGON?new Y(this._ctx,e):new q(this._ctx,e)},Z.prototype.isInstanceOf=function(e,t){if(e===h.POINT)return t instanceof J;if(e===h.LINE_STRING)return t instanceof $;if(e===h.POLYGON)return t instanceof Y;if("MultiFeature"===e)return t instanceof q;throw new Error(`Unknown feature class: ${e}`)},Z.prototype.doRender=function(e){return this._ctx.store.featureChanged(e)},Z.prototype.onSetup=function(){},Z.prototype.onDrag=function(){},Z.prototype.onClick=function(){},Z.prototype.onMouseMove=function(){},Z.prototype.onMouseDown=function(){},Z.prototype.onMouseUp=function(){},Z.prototype.onMouseOut=function(){},Z.prototype.onKeyUp=function(){},Z.prototype.onKeyDown=function(){},Z.prototype.onTouchStart=function(){},Z.prototype.onTouchMove=function(){},Z.prototype.onTouchEnd=function(){},Z.prototype.onTap=function(){},Z.prototype.onStop=function(){},Z.prototype.onTrash=function(){},Z.prototype.onCombineFeature=function(){},Z.prototype.onUncombineFeature=function(){},Z.prototype.toDisplayFeatures=function(){throw new Error("You must overwrite toDisplayFeatures")};const W={drag:"onDrag",click:"onClick",mousemove:"onMouseMove",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseout:"onMouseOut",keyup:"onKeyUp",keydown:"onKeyDown",touchstart:"onTouchStart",touchmove:"onTouchMove",touchend:"onTouchEnd",tap:"onTap"},K=Object.keys(W);function z(e){const t=Object.keys(e);return function(o,n={}){let r={};const i=t.reduce(((t,o)=>(t[o]=e[o],t)),new Z(o));return{start(){r=i.onSetup(n),K.forEach((t=>{const o=W[t];let n=()=>!1;var s;e[o]&&(n=()=>!0),this.on(t,n,(s=o,e=>i[s](r,e)))}))},stop(){i.onStop(r)},trash(){i.onTrash(r)},combineFeatures(){i.onCombineFeatures(r)},uncombineFeatures(){i.onUncombineFeatures(r)},render(e,t){i.toDisplayFeatures(r,e,t)}}}}function Q(e){return[].concat(e).filter((e=>void 0!==e))}function ee(){const e=this;if(!e.ctx.map||void 0===e.ctx.map.getSource(l.HOT))return a();const t=e.ctx.events.currentModeName();e.ctx.ui.queueMapClasses({mode:t});let o=[],n=[];e.isDirty?n=e.getAllIds():(o=e.getChangedIds().filter((t=>void 0!==e.get(t))),n=e.sources.hot.filter((t=>t.properties.id&&-1===o.indexOf(t.properties.id)&&void 0!==e.get(t.properties.id))).map((e=>e.properties.id))),e.sources.hot=[];const r=e.sources.cold.length;e.sources.cold=e.isDirty?[]:e.sources.cold.filter((e=>{const t=e.properties.id||e.properties.parent;return-1===o.indexOf(t)}));const i=r!==e.sources.cold.length||n.length>0;function s(o,n){const r=e.get(o).internal(t);e.ctx.events.currentModeRender(r,(o=>{o.properties.mode=t,e.sources[n].push(o)}))}function a(){e.isDirty=!1,e.clearChangedIds()}o.forEach((e=>s(e,"hot"))),n.forEach((e=>s(e,"cold"))),i&&e.ctx.map.getSource(l.COLD).setData({type:h.FEATURE_COLLECTION,features:e.sources.cold}),e.ctx.map.getSource(l.HOT).setData({type:h.FEATURE_COLLECTION,features:e.sources.hot}),a()}function te(e){let t;this._features={},this._featureIds=new M,this._selectedFeatureIds=new M,this._selectedCoordinates=[],this._changedFeatureIds=new M,this._emitSelectionChange=!1,this._mapInitialConfig={},this.ctx=e,this.sources={hot:[],cold:[]},this.render=()=>{t||(t=requestAnimationFrame((()=>{t=null,ee.call(this),this._emitSelectionChange&&(this.ctx.events.fire(g.SELECTION_CHANGE,{features:this.getSelected().map((e=>e.toGeoJSON())),points:this.getSelectedCoordinates().map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e.coordinates}})))}),this._emitSelectionChange=!1),this.ctx.events.fire(g.RENDER,{})})))},this.isDirty=!1}function oe(e,t={}){const o=e._selectedCoordinates.filter((t=>e._selectedFeatureIds.has(t.feature_id)));e._selectedCoordinates.length===o.length||t.silent||(e._emitSelectionChange=!0),e._selectedCoordinates=o}te.prototype.createRenderBatch=function(){const e=this.render;let t=0;return this.render=function(){t++},()=>{this.render=e,t>0&&this.render()}},te.prototype.setDirty=function(){return this.isDirty=!0,this},te.prototype.featureCreated=function(e,t={}){if(this._changedFeatureIds.add(e),!0!==(null!=t.silent?t.silent:this.ctx.options.suppressAPIEvents)){const t=this.get(e);this.ctx.events.fire(g.CREATE,{features:[t.toGeoJSON()]})}return this},te.prototype.featureChanged=function(e,t={}){return this._changedFeatureIds.add(e),!0!==(null!=t.silent?t.silent:this.ctx.options.suppressAPIEvents)&&this.ctx.events.fire(g.UPDATE,{action:t.action?t.action:m.CHANGE_COORDINATES,features:[this.get(e).toGeoJSON()]}),this},te.prototype.getChangedIds=function(){return this._changedFeatureIds.values()},te.prototype.clearChangedIds=function(){return this._changedFeatureIds.clear(),this},te.prototype.getAllIds=function(){return this._featureIds.values()},te.prototype.add=function(e,t={}){return this._features[e.id]=e,this._featureIds.add(e.id),this.featureCreated(e.id,{silent:t.silent}),this},te.prototype.delete=function(e,t={}){const o=[];return Q(e).forEach((e=>{this._featureIds.has(e)&&(this._featureIds.delete(e),this._selectedFeatureIds.delete(e),t.silent||-1===o.indexOf(this._features[e])&&o.push(this._features[e].toGeoJSON()),delete this._features[e],this.isDirty=!0)})),o.length&&this.ctx.events.fire(g.DELETE,{features:o}),oe(this,t),this},te.prototype.get=function(e){return this._features[e]},te.prototype.getAll=function(){return Object.keys(this._features).map((e=>this._features[e]))},te.prototype.select=function(e,t={}){return Q(e).forEach((e=>{this._selectedFeatureIds.has(e)||(this._selectedFeatureIds.add(e),this._changedFeatureIds.add(e),t.silent||(this._emitSelectionChange=!0))})),this},te.prototype.deselect=function(e,t={}){return Q(e).forEach((e=>{this._selectedFeatureIds.has(e)&&(this._selectedFeatureIds.delete(e),this._changedFeatureIds.add(e),t.silent||(this._emitSelectionChange=!0))})),oe(this,t),this},te.prototype.clearSelected=function(e={}){return this.deselect(this._selectedFeatureIds.values(),{silent:e.silent}),this},te.prototype.setSelected=function(e,t={}){return e=Q(e),this.deselect(this._selectedFeatureIds.values().filter((t=>-1===e.indexOf(t))),{silent:t.silent}),this.select(e.filter((e=>!this._selectedFeatureIds.has(e))),{silent:t.silent}),this},te.prototype.setSelectedCoordinates=function(e){return this._selectedCoordinates=e,this._emitSelectionChange=!0,this},te.prototype.clearSelectedCoordinates=function(){return this._selectedCoordinates=[],this._emitSelectionChange=!0,this},te.prototype.getSelectedIds=function(){return this._selectedFeatureIds.values()},te.prototype.getSelected=function(){return this.getSelectedIds().map((e=>this.get(e)))},te.prototype.getSelectedCoordinates=function(){return this._selectedCoordinates.map((e=>({coordinates:this.get(e.feature_id).getCoordinate(e.coord_path)})))},te.prototype.isSelected=function(e){return this._selectedFeatureIds.has(e)},te.prototype.setFeatureProperty=function(e,t,o,n={}){this.get(e).setProperty(t,o),this.featureChanged(e,{silent:n.silent,action:m.CHANGE_PROPERTIES})},te.prototype.storeMapConfig=function(){T.forEach((e=>{this.ctx.map[e]&&(this._mapInitialConfig[e]=this.ctx.map[e].isEnabled())}))},te.prototype.restoreMapConfig=function(){Object.keys(this._mapInitialConfig).forEach((e=>{this._mapInitialConfig[e]?this.ctx.map[e].enable():this.ctx.map[e].disable()}))},te.prototype.getInitialConfigValue=function(e){return void 0===this._mapInitialConfig[e]||this._mapInitialConfig[e]};const ne=["mode","feature","mouse"];function re(t){let o=null,n=null;const r={onRemove(){return t.map.off("load",r.connect),clearInterval(n),r.removeLayers(),t.store.restoreMapConfig(),t.ui.removeButtons(),t.events.removeEventListeners(),t.ui.clearMapClasses(),t.boxZoomInitial&&t.map.boxZoom.enable(),t.map=null,t.container=null,t.store=null,o&&o.parentNode&&o.parentNode.removeChild(o),o=null,this},connect(){t.map.off("load",r.connect),clearInterval(n),r.addLayers(),t.store.storeMapConfig(),t.events.addEventListeners()},onAdd(i){if(t.map=i,t.events=function(t){const o=Object.keys(t.options.modes).reduce(((e,o)=>(e[o]=z(t.options.modes[o]),e)),{});let n={},r={};const i={};let s=null,a=null;i.drag=function(e,o){o({point:e.point,time:(new Date).getTime()})?(t.ui.queueMapClasses({mouse:d.DRAG}),a.drag(e)):e.originalEvent.stopPropagation()},i.mousedrag=function(e){i.drag(e,(e=>!D(n,e)))},i.touchdrag=function(e){i.drag(e,(e=>!V(r,e)))},i.mousemove=function(e){if(1===(void 0!==e.originalEvent.buttons?e.originalEvent.buttons:e.originalEvent.which))return i.mousedrag(e);const o=A(e,t);e.featureTarget=o,a.mousemove(e)},i.mousedown=function(e){n={time:(new Date).getTime(),point:e.point};const o=A(e,t);e.featureTarget=o,a.mousedown(e)},i.mouseup=function(e){const o=A(e,t);e.featureTarget=o,D(n,{point:e.point,time:(new Date).getTime()})?a.click(e):a.mouseup(e)},i.mouseout=function(e){a.mouseout(e)},i.touchstart=function(e){if(!t.options.touchEnabled)return;r={time:(new Date).getTime(),point:e.point};const o=b.touch(e,null,t)[0];e.featureTarget=o,a.touchstart(e)},i.touchmove=function(e){if(t.options.touchEnabled)return a.touchmove(e),i.touchdrag(e)},i.touchend=function(e){if(e.originalEvent.preventDefault(),!t.options.touchEnabled)return;const o=b.touch(e,null,t)[0];e.featureTarget=o,V(r,{time:(new Date).getTime(),point:e.point})?a.tap(e):a.touchend(e)};const c=e=>!(8===e||46===e||e>=48&&e<=57);function l(n,r,i={}){a.stop();const c=o[n];if(void 0===c)throw new Error(`${n} is not valid`);s=n;const u=c(t,r);a=e(u,t),i.silent||t.map.fire(g.MODE_CHANGE,{mode:n}),t.store.setDirty(),t.store.render()}i.keydown=function(e){(e.srcElement||e.target).classList.contains(u.CANVAS)&&(8!==e.keyCode&&46!==e.keyCode||!t.options.controls.trash?c(e.keyCode)?a.keydown(e):49===e.keyCode&&t.options.controls.point?l(f.DRAW_POINT):50===e.keyCode&&t.options.controls.line_string?l(f.DRAW_LINE_STRING):51===e.keyCode&&t.options.controls.polygon&&l(f.DRAW_POLYGON):(e.preventDefault(),a.trash()))},i.keyup=function(e){c(e.keyCode)&&a.keyup(e)},i.zoomend=function(){t.store.changeZoom()},i.data=function(e){if("style"===e.dataType){const{setup:e,map:o,options:n,store:r}=t;n.styles.some((e=>o.getLayer(e.id)))||(e.addLayers(),r.setDirty(),r.render())}};const p={trash:!1,combineFeatures:!1,uncombineFeatures:!1};return{start(){s=t.options.defaultMode,a=e(o[s](t),t)},changeMode:l,actionable:function(e){let o=!1;Object.keys(e).forEach((t=>{if(void 0===p[t])throw new Error("Invalid action type");p[t]!==e[t]&&(o=!0),p[t]=e[t]})),o&&t.map.fire(g.ACTIONABLE,{actions:p})},currentModeName:()=>s,currentModeRender:(e,t)=>a.render(e,t),fire(e,o){t.map&&t.map.fire(e,o)},addEventListeners(){t.map.on("mousemove",i.mousemove),t.map.on("mousedown",i.mousedown),t.map.on("mouseup",i.mouseup),t.map.on("data",i.data),t.map.on("touchmove",i.touchmove),t.map.on("touchstart",i.touchstart),t.map.on("touchend",i.touchend),t.container.addEventListener("mouseout",i.mouseout),t.options.keybindings&&(t.container.addEventListener("keydown",i.keydown),t.container.addEventListener("keyup",i.keyup))},removeEventListeners(){t.map.off("mousemove",i.mousemove),t.map.off("mousedown",i.mousedown),t.map.off("mouseup",i.mouseup),t.map.off("data",i.data),t.map.off("touchmove",i.touchmove),t.map.off("touchstart",i.touchstart),t.map.off("touchend",i.touchend),t.container.removeEventListener("mouseout",i.mouseout),t.options.keybindings&&(t.container.removeEventListener("keydown",i.keydown),t.container.removeEventListener("keyup",i.keyup))},trash(e){a.trash(e)},combineFeatures(){a.combineFeatures()},uncombineFeatures(){a.uncombineFeatures()},getMode:()=>s}}(t),t.ui=function(e){const t={};let o=null,n={mode:null,feature:null,mouse:null},r={mode:null,feature:null,mouse:null};function i(e){r=Object.assign(r,e)}function s(){if(!e.container)return;const t=[],o=[];ne.forEach((e=>{r[e]!==n[e]&&(t.push(`${e}-${n[e]}`),null!==r[e]&&o.push(`${e}-${r[e]}`))})),t.length>0&&e.container.classList.remove(...t),o.length>0&&e.container.classList.add(...o),n=Object.assign(n,r)}function a(e,t={}){const n=document.createElement("button");return n.className=`${u.CONTROL_BUTTON} ${t.className}`,n.setAttribute("title",t.title),t.container.appendChild(n),n.addEventListener("click",(n=>{if(n.preventDefault(),n.stopPropagation(),n.target===o)return c(),void t.onDeactivate();l(e),t.onActivate()}),!0),n}function c(){o&&(o.classList.remove(u.ACTIVE_BUTTON),o=null)}function l(e){c();const n=t[e];n&&n&&"trash"!==e&&(n.classList.add(u.ACTIVE_BUTTON),o=n)}return{setActiveButton:l,queueMapClasses:i,updateMapClasses:s,clearMapClasses:function(){i({mode:null,feature:null,mouse:null}),s()},addButtons:function(){const o=e.options.controls,n=document.createElement("div");return n.className=`${u.CONTROL_GROUP} ${u.CONTROL_BASE}`,o?(o[p.LINE]&&(t[p.LINE]=a(p.LINE,{container:n,className:u.CONTROL_BUTTON_LINE,title:"LineString tool "+(e.options.keybindings?"(l)":""),onActivate:()=>e.events.changeMode(f.DRAW_LINE_STRING),onDeactivate:()=>e.events.trash()})),o[p.POLYGON]&&(t[p.POLYGON]=a(p.POLYGON,{container:n,className:u.CONTROL_BUTTON_POLYGON,title:"Polygon tool "+(e.options.keybindings?"(p)":""),onActivate:()=>e.events.changeMode(f.DRAW_POLYGON),onDeactivate:()=>e.events.trash()})),o[p.POINT]&&(t[p.POINT]=a(p.POINT,{container:n,className:u.CONTROL_BUTTON_POINT,title:"Marker tool "+(e.options.keybindings?"(m)":""),onActivate:()=>e.events.changeMode(f.DRAW_POINT),onDeactivate:()=>e.events.trash()})),o.trash&&(t.trash=a("trash",{container:n,className:u.CONTROL_BUTTON_TRASH,title:"Delete",onActivate:()=>{e.events.trash()}})),o.combine_features&&(t.combine_features=a("combineFeatures",{container:n,className:u.CONTROL_BUTTON_COMBINE_FEATURES,title:"Combine",onActivate:()=>{e.events.combineFeatures()}})),o.uncombine_features&&(t.uncombine_features=a("uncombineFeatures",{container:n,className:u.CONTROL_BUTTON_UNCOMBINE_FEATURES,title:"Uncombine",onActivate:()=>{e.events.uncombineFeatures()}})),n):n},removeButtons:function(){Object.keys(t).forEach((e=>{const o=t[e];o.parentNode&&o.parentNode.removeChild(o),delete t[e]}))}}}(t),t.container=i.getContainer(),t.store=new te(t),o=t.ui.addButtons(),t.options.boxSelect){t.boxZoomInitial=i.boxZoom.isEnabled(),i.boxZoom.disable();const e=i.dragPan.isEnabled();i.dragPan.disable(),i.dragPan.enable(),e||i.dragPan.disable()}return i.loaded()?r.connect():(i.on("load",r.connect),n=setInterval((()=>{i.loaded()&&r.connect()}),16)),t.events.start(),o},addLayers(){t.map.addSource(l.COLD,{data:{type:h.FEATURE_COLLECTION,features:[]},type:"geojson"}),t.map.addSource(l.HOT,{data:{type:h.FEATURE_COLLECTION,features:[]},type:"geojson"}),t.options.styles.forEach((e=>{t.map.addLayer(e)})),t.store.setDirty(!0),t.store.render()},removeLayers(){t.options.styles.forEach((e=>{t.map.getLayer(e.id)&&t.map.removeLayer(e.id)})),t.map.getSource(l.COLD)&&t.map.removeSource(l.COLD),t.map.getSource(l.HOT)&&t.map.removeSource(l.HOT)}};return t.setup=r,r}const ie="#3bb2d0",se="#fbb03b",ae="#fff";var ce=[{id:"gl-draw-polygon-fill",type:"fill",filter:["all",["==","$type","Polygon"]],paint:{"fill-color":["case",["==",["get","active"],"true"],se,ie],"fill-opacity":.1}},{id:"gl-draw-lines",type:"line",filter:["any",["==","$type","LineString"],["==","$type","Polygon"]],layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":["case",["==",["get","active"],"true"],se,ie],"line-dasharray":["case",["==",["get","active"],"true"],[.2,2],[2,0]],"line-width":2}},{id:"gl-draw-point-outer",type:"circle",filter:["all",["==","$type","Point"],["==","meta","feature"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],7,5],"circle-color":ae}},{id:"gl-draw-point-inner",type:"circle",filter:["all",["==","$type","Point"],["==","meta","feature"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],5,3],"circle-color":["case",["==",["get","active"],"true"],se,ie]}},{id:"gl-draw-vertex-outer",type:"circle",filter:["all",["==","$type","Point"],["==","meta","vertex"],["!=","mode","simple_select"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],7,5],"circle-color":ae}},{id:"gl-draw-vertex-inner",type:"circle",filter:["all",["==","$type","Point"],["==","meta","vertex"],["!=","mode","simple_select"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],5,3],"circle-color":se}},{id:"gl-draw-midpoint",type:"circle",filter:["all",["==","meta","midpoint"]],paint:{"circle-radius":3,"circle-color":se}}];function ue(e){return function(t){const o=t.featureTarget;return!!o&&!!o.properties&&o.properties.meta===e}}function le(e){return!!e.originalEvent&&!!e.originalEvent.shiftKey&&0===e.originalEvent.button}function de(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.active===E.ACTIVE&&e.featureTarget.properties.meta===y.FEATURE}function pe(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.active===E.INACTIVE&&e.featureTarget.properties.meta===y.FEATURE}function he(e){return void 0===e.featureTarget}function fe(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.meta===y.FEATURE}function ge(e){const t=e.featureTarget;return!!t&&!!t.properties&&t.properties.meta===y.VERTEX}function me(e){return!!e.originalEvent&&!0===e.originalEvent.shiftKey}function ye(e){return 27===e.keyCode}function Ee(e){return 13===e.keyCode}var Te=Object.freeze({__proto__:null,isActiveFeature:de,isEnterKey:Ee,isEscapeKey:ye,isFeature:fe,isInactiveFeature:pe,isOfMetaType:ue,isShiftDown:me,isShiftMousedown:le,isTrue:function(){return!0},isVertex:ge,noTarget:he});function Ce(e,t){this.x=e,this.y=t}function _e(e,t){const o=t.getBoundingClientRect();return new Ce(e.clientX-o.left-(t.clientLeft||0),e.clientY-o.top-(t.clientTop||0))}function ve(e,t,o,n){return{type:h.FEATURE,properties:{meta:y.VERTEX,parent:e,coord_path:o,active:n?E.ACTIVE:E.INACTIVE},geometry:{type:h.POINT,coordinates:t}}}function Ie(e,t,o){const n=t.geometry.coordinates,r=o.geometry.coordinates;if(n[1]>_||n[1]_||r[1]{const u=null!=o?`${o}.${a}`:String(a),l=ve(i,e,u,c(u));if(t.midpoints&&r){const e=Ie(i,r,l);e&&s.push(e)}r=l;const d=JSON.stringify(e);n!==d&&s.push(l),0===a&&(n=d)}))}function c(e){return!!t.selectedPaths&&-1!==t.selectedPaths.indexOf(e)}return n===h.POINT?s.push(ve(i,r,o,c(o))):n===h.POLYGON?r.forEach(((e,t)=>{a(e,null!==o?`${o}.${t}`:String(t))})):n===h.LINE_STRING?a(r,o):0===n.indexOf(h.MULTI_PREFIX)&&function(){const o=n.replace(h.MULTI_PREFIX,"");r.forEach(((n,r)=>{const i={type:h.FEATURE,properties:e.properties,geometry:{type:o,coordinates:n}};s=s.concat(Se(i,t,r))}))}(),s}Ce.prototype={clone(){return new Ce(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){const t=e.x-this.x,o=e.y-this.y;return t*t+o*o},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){const t=e[0]*this.x+e[1]*this.y,o=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=o,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){const e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){const t=Math.cos(e),o=Math.sin(e),n=t*this.x-o*this.y,r=o*this.x+t*this.y;return this.x=n,this.y=r,this},_rotateAround(e,t){const o=Math.cos(e),n=Math.sin(e),r=t.x+o*(this.x-t.x)-n*(this.y-t.y),i=t.y+n*(this.x-t.x)+o*(this.y-t.y);return this.x=r,this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:Ce},Ce.convert=function(e){if(e instanceof Ce)return e;if(Array.isArray(e))return new Ce(+e[0],+e[1]);if(void 0!==e.x&&void 0!==e.y)return new Ce(+e.x,+e.y);throw new Error("Expected [x, y] or {x, y} point format")};var Oe={enable(e){setTimeout((()=>{e.map&&e.map.doubleClickZoom&&e._ctx&&e._ctx.store&&e._ctx.store.getInitialConfigValue&&e._ctx.store.getInitialConfigValue("doubleClickZoom")&&e.map.doubleClickZoom.enable()}),0)},disable(e){setTimeout((()=>{e.map&&e.map.doubleClickZoom&&e.map.doubleClickZoom.disable()}),0)}};const{LAT_MIN:Le,LAT_MAX:Me,LAT_RENDERED_MIN:Ne,LAT_RENDERED_MAX:be,LNG_MIN:xe,LNG_MAX:Ae}=v;function Pe(e,t){let o=Le,n=Me,r=Le,i=Me,s=Ae,a=xe;e.forEach((e=>{const t=function(e){const t={Point:0,LineString:1,Polygon:2,MultiPoint:1,MultiLineString:2,MultiPolygon:3}[e.geometry.type],o=[e.geometry.coordinates].flat(t),n=o.map((e=>e[0])),r=o.map((e=>e[1])),i=e=>Math.min.apply(null,e),s=e=>Math.max.apply(null,e);return[i(n),i(r),s(n),s(r)]}(e),c=t[1],u=t[3],l=t[0],d=t[2];c>o&&(o=c),ur&&(r=u),ca&&(a=d)}));const c=t;return o+c.lat>be&&(c.lat=be-o),r+c.lat>Me&&(c.lat=Me-r),n+c.lat=Ae&&(c.lng-=360*Math.ceil(Math.abs(c.lng)/360)),c}function Fe(e,t){const o=Pe(e.map((e=>e.toGeoJSON())),t);e.forEach((e=>{const t=e.getCoordinates(),n=e=>{const t={lng:e[0]+o.lng,lat:e[1]+o.lat};return[t.lng,t.lat]},r=e=>e.map((e=>n(e))),i=e=>e.map((e=>r(e)));let s;e.type===h.POINT?s=n(t):e.type===h.LINE_STRING||e.type===h.MULTI_POINT?s=t.map(n):e.type===h.POLYGON||e.type===h.MULTI_LINE_STRING?s=t.map(r):e.type===h.MULTI_POLYGON&&(s=t.map(i)),e.incomingCoords(s)}))}const Re={onSetup:function(e){const t={dragMoveLocation:null,boxSelectStartLocation:null,boxSelectElement:void 0,boxSelecting:!1,canBoxSelect:!1,dragMoving:!1,canDragMove:!1,initialDragPanState:this.map.dragPan.isEnabled(),initiallySelectedFeatureIds:e.featureIds||[]};return this.setSelected(t.initiallySelectedFeatureIds.filter((e=>void 0!==this.getFeature(e)))),this.fireActionable(),this.setActionableState({combineFeatures:!0,uncombineFeatures:!0,trash:!0}),t},fireUpdate:function(){this.fire(g.UPDATE,{action:m.MOVE,features:this.getSelected().map((e=>e.toGeoJSON()))})},fireActionable:function(){const e=this.getSelected(),t=e.filter((e=>this.isInstanceOf("MultiFeature",e)));let o=!1;if(e.length>1){o=!0;const t=e[0].type.replace("Multi","");e.forEach((e=>{e.type.replace("Multi","")!==t&&(o=!1)}))}const n=t.length>0,r=e.length>0;this.setActionableState({combineFeatures:o,uncombineFeatures:n,trash:r})},getUniqueIds:function(e){return e.length?e.map((e=>e.properties.id)).filter((e=>void 0!==e)).reduce(((e,t)=>(e.add(t),e)),new M).values():[]},stopExtendedInteractions:function(e){e.boxSelectElement&&(e.boxSelectElement.parentNode&&e.boxSelectElement.parentNode.removeChild(e.boxSelectElement),e.boxSelectElement=null),(e.canDragMove||e.canBoxSelect)&&!0===e.initialDragPanState&&this.map.dragPan.enable(),e.boxSelecting=!1,e.canBoxSelect=!1,e.dragMoving=!1,e.canDragMove=!1},onStop:function(){Oe.enable(this)},onMouseMove:function(e,t){return fe(t)&&e.dragMoving&&this.fireUpdate(),this.stopExtendedInteractions(e),!0},onMouseOut:function(e){return!e.dragMoving||this.fireUpdate()}};Re.onTap=Re.onClick=function(e,t){return he(t)?this.clickAnywhere(e,t):ue(y.VERTEX)(t)?this.clickOnVertex(e,t):fe(t)?this.clickOnFeature(e,t):void 0},Re.clickAnywhere=function(e){const t=this.getSelectedIds();t.length&&(this.clearSelectedFeatures(),t.forEach((e=>this.doRender(e)))),Oe.enable(this),this.stopExtendedInteractions(e)},Re.clickOnVertex=function(e,t){this.changeMode(f.DIRECT_SELECT,{featureId:t.featureTarget.properties.parent,coordPath:t.featureTarget.properties.coord_path,startPos:t.lngLat}),this.updateUIClasses({mouse:d.MOVE})},Re.startOnActiveFeature=function(e,t){this.stopExtendedInteractions(e),this.map.dragPan.disable(),this.doRender(t.featureTarget.properties.id),e.canDragMove=!0,e.dragMoveLocation=t.lngLat},Re.clickOnFeature=function(e,t){Oe.disable(this),this.stopExtendedInteractions(e);const o=me(t),n=this.getSelectedIds(),r=t.featureTarget.properties.id,i=this.isSelected(r);if(!o&&i&&this.getFeature(r).type!==h.POINT)return this.changeMode(f.DIRECT_SELECT,{featureId:r});i&&o?(this.deselect(r),this.updateUIClasses({mouse:d.POINTER}),1===n.length&&Oe.enable(this)):!i&&o?(this.select(r),this.updateUIClasses({mouse:d.MOVE})):i||o||(n.forEach((e=>this.doRender(e))),this.setSelected(r),this.updateUIClasses({mouse:d.MOVE})),this.doRender(r)},Re.onMouseDown=function(e,t){return e.initialDragPanState=this.map.dragPan.isEnabled(),de(t)?this.startOnActiveFeature(e,t):this.drawConfig.boxSelect&&le(t)?this.startBoxSelect(e,t):void 0},Re.startBoxSelect=function(e,t){this.stopExtendedInteractions(e),this.map.dragPan.disable(),e.boxSelectStartLocation=_e(t.originalEvent,this.map.getContainer()),e.canBoxSelect=!0},Re.onTouchStart=function(e,t){if(de(t))return this.startOnActiveFeature(e,t)},Re.onDrag=function(e,t){return e.canDragMove?this.dragMove(e,t):this.drawConfig.boxSelect&&e.canBoxSelect?this.whileBoxSelect(e,t):void 0},Re.whileBoxSelect=function(e,t){e.boxSelecting=!0,this.updateUIClasses({mouse:d.ADD}),e.boxSelectElement||(e.boxSelectElement=document.createElement("div"),e.boxSelectElement.classList.add(u.BOX_SELECT),this.map.getContainer().appendChild(e.boxSelectElement));const o=_e(t.originalEvent,this.map.getContainer()),n=Math.min(e.boxSelectStartLocation.x,o.x),r=Math.max(e.boxSelectStartLocation.x,o.x),i=Math.min(e.boxSelectStartLocation.y,o.y),s=Math.max(e.boxSelectStartLocation.y,o.y),a=`translate(${n}px, ${i}px)`;e.boxSelectElement.style.transform=a,e.boxSelectElement.style.WebkitTransform=a,e.boxSelectElement.style.width=r-n+"px",e.boxSelectElement.style.height=s-i+"px"},Re.dragMove=function(e,t){e.dragMoving=!0,t.originalEvent.stopPropagation();const o={lng:t.lngLat.lng-e.dragMoveLocation.lng,lat:t.lngLat.lat-e.dragMoveLocation.lat};Fe(this.getSelected(),o),e.dragMoveLocation=t.lngLat},Re.onTouchEnd=Re.onMouseUp=function(e,t){if(e.dragMoving)this.fireUpdate();else if(e.boxSelecting){const o=[e.boxSelectStartLocation,_e(t.originalEvent,this.map.getContainer())],n=this.featuresAt(null,o,"click"),r=this.getUniqueIds(n).filter((e=>!this.isSelected(e)));r.length&&(this.select(r),r.forEach((e=>this.doRender(e))),this.updateUIClasses({mouse:d.MOVE}))}this.stopExtendedInteractions(e)},Re.toDisplayFeatures=function(e,t,o){t.properties.active=this.isSelected(t.properties.id)?E.ACTIVE:E.INACTIVE,o(t),this.fireActionable(),t.properties.active===E.ACTIVE&&t.geometry.type!==h.POINT&&Se(t).forEach(o)},Re.onTrash=function(){this.deleteFeature(this.getSelectedIds()),this.fireActionable()},Re.onCombineFeatures=function(){const e=this.getSelected();if(0===e.length||e.length<2)return;const t=[],o=[],n=e[0].type.replace("Multi","");for(let r=0;r{t.push(e)})):t.push(i.getCoordinates()),o.push(i.toGeoJSON())}if(o.length>1){const e=this.newFeature({type:h.FEATURE,properties:o[0].properties,geometry:{type:`Multi${n}`,coordinates:t}});this.addFeature(e),this.deleteFeature(this.getSelectedIds(),{silent:!0}),this.setSelected([e.id]),this.fire(g.COMBINE_FEATURES,{createdFeatures:[e.toGeoJSON()],deletedFeatures:o})}this.fireActionable()},Re.onUncombineFeatures=function(){const e=this.getSelected();if(0===e.length)return;const t=[],o=[];for(let n=0;n{this.addFeature(e),e.properties=r.properties,t.push(e.toGeoJSON()),this.select([e.id])})),this.deleteFeature(r.id,{silent:!0}),o.push(r.toGeoJSON()))}t.length>1&&this.fire(g.UNCOMBINE_FEATURES,{createdFeatures:t,deletedFeatures:o}),this.fireActionable()};const we=ue(y.VERTEX),De=ue(y.MIDPOINT),Ue={fireUpdate:function(){this.fire(g.UPDATE,{action:m.CHANGE_COORDINATES,features:this.getSelected().map((e=>e.toGeoJSON()))})},fireActionable:function(e){this.setActionableState({combineFeatures:!1,uncombineFeatures:!1,trash:e.selectedCoordPaths.length>0})},startDragging:function(e,t){e.initialDragPanState=this.map.dragPan.isEnabled(),this.map.dragPan.disable(),e.canDragMove=!0,e.dragMoveLocation=t.lngLat},stopDragging:function(e){e.canDragMove&&!0===e.initialDragPanState&&this.map.dragPan.enable(),e.dragMoving=!1,e.canDragMove=!1,e.dragMoveLocation=null},onVertex:function(e,t){this.startDragging(e,t);const o=t.featureTarget.properties,n=e.selectedCoordPaths.indexOf(o.coord_path);me(t)||-1!==n?me(t)&&-1===n&&e.selectedCoordPaths.push(o.coord_path):e.selectedCoordPaths=[o.coord_path];const r=this.pathsToCoordinates(e.featureId,e.selectedCoordPaths);this.setSelectedCoordinates(r)},onMidpoint:function(e,t){this.startDragging(e,t);const o=t.featureTarget.properties;e.feature.addCoordinate(o.coord_path,o.lng,o.lat),this.fireUpdate(),e.selectedCoordPaths=[o.coord_path]},pathsToCoordinates:function(e,t){return t.map((t=>({feature_id:e,coord_path:t})))},onFeature:function(e,t){0===e.selectedCoordPaths.length?this.startDragging(e,t):this.stopDragging(e)},dragFeature:function(e,t,o){Fe(this.getSelected(),o),e.dragMoveLocation=t.lngLat},dragVertex:function(e,t,o){const n=e.selectedCoordPaths.map((t=>e.feature.getCoordinate(t))),r=Pe(n.map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e}}))),o);for(let t=0;tt.localeCompare(e,"en",{numeric:!0}))).forEach((t=>e.feature.removeCoordinate(t))),this.fireUpdate(),e.selectedCoordPaths=[],this.clearSelectedCoordinates(),this.fireActionable(e),!1===e.feature.isValid()&&(this.deleteFeature([e.featureId]),this.changeMode(f.SIMPLE_SELECT,{}))},onMouseMove:function(e,t){const o=de(t),n=we(t),r=De(t),i=0===e.selectedCoordPaths.length;return o&&i||n&&!i?this.updateUIClasses({mouse:d.MOVE}):this.updateUIClasses({mouse:d.NONE}),(n||o||r)&&e.dragMoving&&this.fireUpdate(),this.stopDragging(e),!0},onMouseOut:function(e){return e.dragMoving&&this.fireUpdate(),!0}};Ue.onTouchStart=Ue.onMouseDown=function(e,t){return we(t)?this.onVertex(e,t):de(t)?this.onFeature(e,t):De(t)?this.onMidpoint(e,t):void 0},Ue.onDrag=function(e,t){if(!0!==e.canDragMove)return;e.dragMoving=!0,t.originalEvent.stopPropagation();const o={lng:t.lngLat.lng-e.dragMoveLocation.lng,lat:t.lngLat.lat-e.dragMoveLocation.lat};e.selectedCoordPaths.length>0?this.dragVertex(e,t,o):this.dragFeature(e,t,o),e.dragMoveLocation=t.lngLat},Ue.onClick=function(e,t){return he(t)?this.clickNoTarget(e,t):de(t)?this.clickActiveFeature(e,t):pe(t)?this.clickInactive(e,t):void this.stopDragging(e)},Ue.onTap=function(e,t){return he(t)?this.clickNoTarget(e,t):de(t)?this.clickActiveFeature(e,t):pe(t)?this.clickInactive(e,t):void 0},Ue.onTouchEnd=Ue.onMouseUp=function(e){e.dragMoving&&this.fireUpdate(),this.stopDragging(e)};const ke={};function Ve(e,t){return!!e.lngLat&&e.lngLat.lng===t[0]&&e.lngLat.lat===t[1]}ke.onSetup=function(){const e=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:[]}});return this.addFeature(e),this.clearSelectedFeatures(),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.POINT),this.setActionableState({trash:!0}),{point:e}},ke.stopDrawingAndRemove=function(e){this.deleteFeature([e.point.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)},ke.onTap=ke.onClick=function(e,t){this.updateUIClasses({mouse:d.MOVE}),e.point.updateCoordinate("",t.lngLat.lng,t.lngLat.lat),this.fire(g.CREATE,{features:[e.point.toGeoJSON()]}),this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.point.id]})},ke.onStop=function(e){this.activateUIButton(),e.point.getCoordinate().length||this.deleteFeature([e.point.id],{silent:!0})},ke.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.point.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t)},ke.onTrash=ke.stopDrawingAndRemove,ke.onKeyUp=function(e,t){if(ye(t)||Ee(t))return this.stopDrawingAndRemove(e,t)};const Ge={onSetup:function(){const e=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.POLYGON,coordinates:[[]]}});return this.addFeature(e),this.clearSelectedFeatures(),Oe.disable(this),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.POLYGON),this.setActionableState({trash:!0}),{polygon:e,currentVertexPosition:0}},clickAnywhere:function(e,t){if(e.currentVertexPosition>0&&Ve(t,e.polygon.coordinates[0][e.currentVertexPosition-1]))return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]});this.updateUIClasses({mouse:d.ADD}),e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat),e.currentVertexPosition++,e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat)},clickOnVertex:function(e){return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]})},onMouseMove:function(e,t){e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat),ge(t)&&this.updateUIClasses({mouse:d.POINTER})}};Ge.onTap=Ge.onClick=function(e,t){return ge(t)?this.clickOnVertex(e,t):this.clickAnywhere(e,t)},Ge.onKeyUp=function(e,t){ye(t)?(this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)):Ee(t)&&this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]})},Ge.onStop=function(e){this.updateUIClasses({mouse:d.NONE}),Oe.enable(this),this.activateUIButton(),void 0!==this.getFeature(e.polygon.id)&&(e.polygon.removeCoordinate(`0.${e.currentVertexPosition}`),e.polygon.isValid()?this.fire(g.CREATE,{features:[e.polygon.toGeoJSON()]}):(this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT,{},{silent:!0})))},Ge.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.polygon.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t);if(0===t.geometry.coordinates.length)return;const r=t.geometry.coordinates[0].length;if(!(r<3)){if(t.properties.meta=y.FEATURE,o(ve(e.polygon.id,t.geometry.coordinates[0][0],"0.0",!1)),r>3){const n=t.geometry.coordinates[0].length-3;o(ve(e.polygon.id,t.geometry.coordinates[0][n],`0.${n}`,!1))}if(r<=4){const e=[[t.geometry.coordinates[0][0][0],t.geometry.coordinates[0][0][1]],[t.geometry.coordinates[0][1][0],t.geometry.coordinates[0][1][1]]];if(o({type:h.FEATURE,properties:t.properties,geometry:{coordinates:e,type:h.LINE_STRING}}),3===r)return}return o(t)}},Ge.onTrash=function(e){this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)};const Be={onSetup:function(e){const t=(e=e||{}).featureId;let o,n,r="forward";if(t){if(o=this.getFeature(t),!o)throw new Error("Could not find a feature with the provided featureId");let i=e.from;if(i&&"Feature"===i.type&&i.geometry&&"Point"===i.geometry.type&&(i=i.geometry),i&&"Point"===i.type&&i.coordinates&&2===i.coordinates.length&&(i=i.coordinates),!i||!Array.isArray(i))throw new Error("Please use the `from` property to indicate which point to continue the line from");const s=o.coordinates.length-1;if(o.coordinates[s][0]===i[0]&&o.coordinates[s][1]===i[1])n=s+1,o.addCoordinate(n,...o.coordinates[s]);else{if(o.coordinates[0][0]!==i[0]||o.coordinates[0][1]!==i[1])throw new Error("`from` should match the point at either the start or the end of the provided LineString");r="backwards",n=0,o.addCoordinate(n,...o.coordinates[0])}}else o=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.LINE_STRING,coordinates:[]}}),n=0,this.addFeature(o);return this.clearSelectedFeatures(),Oe.disable(this),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.LINE),this.setActionableState({trash:!0}),{line:o,currentVertexPosition:n,direction:r}},clickAnywhere:function(e,t){if(e.currentVertexPosition>0&&Ve(t,e.line.coordinates[e.currentVertexPosition-1])||"backwards"===e.direction&&Ve(t,e.line.coordinates[e.currentVertexPosition+1]))return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]});this.updateUIClasses({mouse:d.ADD}),e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat),"forward"===e.direction?(e.currentVertexPosition++,e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat)):e.line.addCoordinate(0,t.lngLat.lng,t.lngLat.lat)},clickOnVertex:function(e){return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]})},onMouseMove:function(e,t){e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat),ge(t)&&this.updateUIClasses({mouse:d.POINTER})}};Be.onTap=Be.onClick=function(e,t){if(ge(t))return this.clickOnVertex(e,t);this.clickAnywhere(e,t)},Be.onKeyUp=function(e,t){Ee(t)?this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]}):ye(t)&&(this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT))},Be.onStop=function(e){Oe.enable(this),this.activateUIButton(),void 0!==this.getFeature(e.line.id)&&(e.line.removeCoordinate(`${e.currentVertexPosition}`),e.line.isValid()?this.fire(g.CREATE,{features:[e.line.toGeoJSON()]}):(this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT,{},{silent:!0})))},Be.onTrash=function(e){this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)},Be.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.line.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t);t.geometry.coordinates.length<2||(t.properties.meta=y.FEATURE,o(ve(e.line.id,t.geometry.coordinates["forward"===e.direction?t.geometry.coordinates.length-2:1],""+("forward"===e.direction?t.geometry.coordinates.length-2:1),!1)),o(t))};var je={simple_select:Re,direct_select:Ue,draw_point:ke,draw_polygon:Ge,draw_line_string:Be};const Je={defaultMode:f.SIMPLE_SELECT,keybindings:!0,touchEnabled:!0,clickBuffer:2,touchBuffer:25,boxSelect:!0,displayControlsDefault:!0,styles:ce,modes:je,controls:{},userProperties:!1,suppressAPIEvents:!0},$e={point:!0,line_string:!0,polygon:!0,trash:!0,combine_features:!0,uncombine_features:!0},Ye={point:!1,line_string:!1,polygon:!1,trash:!1,combine_features:!1,uncombine_features:!1};function He(e,t){return e.map((e=>e.source?e:Object.assign({},e,{id:`${e.id}.${t}`,source:"hot"===t?l.HOT:l.COLD})))}var Xe,qe,Ze,We,Ke=t(qe?Xe:(qe=1,Xe=function e(t,o){if(t===o)return!0;if(t&&o&&"object"==typeof t&&"object"==typeof o){if(t.constructor!==o.constructor)return!1;var n,r,i;if(Array.isArray(t)){if((n=t.length)!=o.length)return!1;for(r=n;0!=r--;)if(!e(t[r],o[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===o.source&&t.flags===o.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===o.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===o.toString();if((n=(i=Object.keys(t)).length)!==Object.keys(o).length)return!1;for(r=n;0!=r--;)if(!Object.prototype.hasOwnProperty.call(o,i[r]))return!1;for(r=n;0!=r--;){var s=i[r];if(!e(t[s],o[s]))return!1}return!0}return t!=t&&o!=o})),ze=function(){if(We)return Ze;We=1,Ze=function(t){if(!t||!t.type)return null;var o=e[t.type];return o?"geometry"===o?{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:t}]}:"feature"===o?{type:"FeatureCollection",features:[t]}:"featurecollection"===o?t:void 0:null};var e={Point:"geometry",MultiPoint:"geometry",LineString:"geometry",MultiLineString:"geometry",Polygon:"geometry",MultiPolygon:"geometry",GeometryCollection:"geometry",Feature:"feature",FeatureCollection:"featurecollection"};return Ze}(),Qe=t(ze);function et(e,t){return e.length===t.length&&JSON.stringify(e.map((e=>e)).sort())===JSON.stringify(t.map((e=>e)).sort())}const tt={Polygon:Y,LineString:$,Point:J,MultiPolygon:q,MultiLineString:q,MultiPoint:q};var ot=Object.freeze({__proto__:null,CommonSelectors:Te,ModeHandler:e,StringSet:M,constrainFeatureMovement:Pe,createMidPoint:Ie,createSupplementaryPoints:Se,createVertex:ve,doubleClickZoom:Oe,euclideanDistance:P,featuresAt:b,getFeatureAtAndSetCursors:A,isClick:D,isEventAtCoordinates:Ve,isTap:V,mapEventToBoundingBox:L,moveFeatures:Fe,sortFeatures:O,stringSetsAreEqual:et,theme:ce,toDenseArray:Q});const nt=function(e,t){const o={options:e=function(e={}){let t=Object.assign({},e);return e.controls||(t.controls={}),!1===e.displayControlsDefault?t.controls=Object.assign({},Ye,e.controls):t.controls=Object.assign({},$e,e.controls),t=Object.assign({},Je,t),t.styles=He(t.styles,"cold").concat(He(t.styles,"hot")),t}(e)};t=function(e,t){t.modes=f;const o=void 0===e.options.suppressAPIEvents||!!e.options.suppressAPIEvents;return t.getFeatureIdsAt=function(t){return b.click({point:t},null,e).map((e=>e.properties.id))},t.getSelectedIds=function(){return e.store.getSelectedIds()},t.getSelected=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getSelectedIds().map((t=>e.store.get(t))).map((e=>e.toGeoJSON()))}},t.getSelectedPoints=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getSelectedCoordinates().map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e.coordinates}})))}},t.set=function(o){if(void 0===o.type||o.type!==h.FEATURE_COLLECTION||!Array.isArray(o.features))throw new Error("Invalid FeatureCollection");const n=e.store.createRenderBatch();let r=e.store.getAllIds().slice();const i=t.add(o),s=new M(i);return r=r.filter((e=>!s.has(e))),r.length&&t.delete(r),n(),i},t.add=function(t){const n=JSON.parse(JSON.stringify(Qe(t))).features.map((t=>{if(t.id=t.id||B(),null===t.geometry)throw new Error("Invalid geometry: null");if(void 0===e.store.get(t.id)||e.store.get(t.id).type!==t.geometry.type){const n=tt[t.geometry.type];if(void 0===n)throw new Error(`Invalid geometry type: ${t.geometry.type}.`);const r=new n(e,t);e.store.add(r,{silent:o})}else{const n=e.store.get(t.id),r=n.properties;n.properties=t.properties,Ke(r,t.properties)||e.store.featureChanged(n.id,{silent:o}),Ke(n.getCoordinates(),t.geometry.coordinates)||n.incomingCoords(t.geometry.coordinates)}return t.id}));return e.store.render(),n},t.get=function(t){const o=e.store.get(t);if(o)return o.toGeoJSON()},t.getAll=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getAll().map((e=>e.toGeoJSON()))}},t.delete=function(n){return e.store.delete(n,{silent:o}),t.getMode()!==f.DIRECT_SELECT||e.store.getSelectedIds().length?e.store.render():e.events.changeMode(f.SIMPLE_SELECT,void 0,{silent:o}),t},t.deleteAll=function(){return e.store.delete(e.store.getAllIds(),{silent:o}),t.getMode()===f.DIRECT_SELECT?e.events.changeMode(f.SIMPLE_SELECT,void 0,{silent:o}):e.store.render(),t},t.changeMode=function(n,r={}){return n===f.SIMPLE_SELECT&&t.getMode()===f.SIMPLE_SELECT?(et(r.featureIds||[],e.store.getSelectedIds())||(e.store.setSelected(r.featureIds,{silent:o}),e.store.render()),t):(n===f.DIRECT_SELECT&&t.getMode()===f.DIRECT_SELECT&&r.featureId===e.store.getSelectedIds()[0]||e.events.changeMode(n,r,{silent:o}),t)},t.getMode=function(){return e.events.getMode()},t.trash=function(){return e.events.trash({silent:o}),t},t.combineFeatures=function(){return e.events.combineFeatures({silent:o}),t},t.uncombineFeatures=function(){return e.events.uncombineFeatures({silent:o}),t},t.setFeatureProperty=function(n,r,i){return e.store.setFeatureProperty(n,r,i,{silent:o}),t},t}(o,t),o.api=t;const n=re(o);return t.onAdd=n.onAdd,t.onRemove=n.onRemove,t.types=p,t.options=e,t};function rt(e){nt(e,this)}return rt.modes=je,rt.constants=v,rt.lib=ot,rt},"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).MapboxDraw=t(); +//# sourceMappingURL=mapbox-gl-draw.js.map diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js new file mode 100644 index 0000000..e2b91ff --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js @@ -0,0 +1 @@ +var MapboxGLGlobeMinimap=function(){"use strict";class t{constructor(){this._partials=new Float64Array(32),this._n=0}add(t){const n=this._partials;let e=0;for(let r=0;r0){for(o=t[--i];i>0&&(n=o,e=t[--i],o=n+e,r=e-(o-n),!r););i>0&&(r<0&&t[i-1]<0||r>0&&t[i-1]>0)&&(e=2*r,n=o+e,e==n-o&&(o=n))}return o}}function n(t){return Array.from(function*(t){for(const n of t)yield*n}(t))}var e={value:()=>{}};function r(){for(var t,n=0,e=arguments.length,r={};n=0&&(n=t.slice(e+1),t=t.slice(0,e)),t&&!r.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))),l=-1,s=a.length;if(!(arguments.length<2)){if(null!=n&&"function"!=typeof n)throw new Error("invalid callback: "+n);for(;++l0)for(var e,r,i=new Array(e),o=0;o=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),l.hasOwnProperty(n)?{space:l[n],local:t}:t}function c(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===a&&n.documentElement.namespaceURI===a?n.createElement(t):n.createElementNS(e,t)}}function f(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function h(t){var n=s(t);return(n.local?f:c)(n)}function p(){}function d(t){return null==t?p:function(){return this.querySelector(t)}}function v(){return[]}function g(t){return null==t?v:function(){return this.querySelectorAll(t)}}function y(t){return function(){return null==(n=t.apply(this,arguments))?[]:Array.isArray(n)?n:Array.from(n);var n}}function _(t){return function(){return this.matches(t)}}function m(t){return function(n){return n.matches(t)}}var w=Array.prototype.find;function b(){return this.firstElementChild}var x=Array.prototype.filter;function E(){return Array.from(this.children)}function S(t){return new Array(t.length)}function N(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}function k(t,n,e,r,i,o){for(var u,a=0,l=n.length,s=o.length;an?1:t>=n?0:NaN}function P(t){return function(){this.removeAttribute(t)}}function j(t){return function(){this.removeAttributeNS(t.space,t.local)}}function R(t,n){return function(){this.setAttribute(t,n)}}function T(t,n){return function(){this.setAttributeNS(t.space,t.local,n)}}function q(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttribute(t):this.setAttribute(t,e)}}function O(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}}function L(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function X(t){return function(){this.style.removeProperty(t)}}function z(t,n,e){return function(){this.style.setProperty(t,n,e)}}function D(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}function H(t,n){return t.style.getPropertyValue(n)||L(t).getComputedStyle(t,null).getPropertyValue(n)}function I(t){return function(){delete this[t]}}function Y(t,n){return function(){this[t]=n}}function B(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}function F(t){return t.trim().split(/^|\s+/)}function V(t){return t.classList||new G(t)}function G(t){this._node=t,this._names=F(t.getAttribute("class")||"")}function U(t,n){for(var e=V(t),r=-1,i=n.length;++r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var gt=[null];function yt(t,n){this._groups=t,this._parents=n}function _t(){return new yt([[document.documentElement]],gt)}function mt(t){return"string"==typeof t?new yt([[document.querySelector(t)]],[document.documentElement]):new yt([[t]],gt)}function wt(t,n,e){t.prototype=n.prototype=e,e.constructor=t}function bt(t,n){var e=Object.create(t.prototype);for(var r in n)e[r]=n[r];return e}function xt(){}yt.prototype=_t.prototype={constructor:yt,select:function(t){"function"!=typeof t&&(t=d(t));for(var n=this._groups,e=n.length,r=new Array(e),i=0;i=b&&(b=w+1);!(m=y[b])&&++b=0;)(r=i[o])&&(u&&4^r.compareDocumentPosition(u)&&u.parentNode.insertBefore(r,u),u=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=C);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?X:"function"==typeof n?D:z)(t,n,null==e?"":e)):H(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?I:"function"==typeof n?B:Y)(t,n)):this.node()[t]},classed:function(t,n){var e=F(t+"");if(arguments.length<2){for(var r=V(this.node()),i=-1,o=e.length;++i=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}}))}(t+""),u=o.length;if(!(arguments.length<2)){for(a=n?ht:ft,r=0;r>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):8===e?Dt(n>>24&255,n>>16&255,n>>8&255,(255&n)/255):4===e?Dt(n>>12&15|n>>8&240,n>>8&15|n>>4&240,n>>4&15|240&n,((15&n)<<4|15&n)/255):null):(n=$t.exec(t))?new It(n[1],n[2],n[3],1):(n=Ct.exec(t))?new It(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=Pt.exec(t))?Dt(n[1],n[2],n[3],n[4]):(n=jt.exec(t))?Dt(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=Rt.exec(t))?Ut(n[1],n[2]/100,n[3]/100,1):(n=Tt.exec(t))?Ut(n[1],n[2]/100,n[3]/100,n[4]):qt.hasOwnProperty(t)?zt(qt[t]):"transparent"===t?new It(NaN,NaN,NaN,0):null}function zt(t){return new It(t>>16&255,t>>8&255,255&t,1)}function Dt(t,n,e,r){return r<=0&&(t=n=e=NaN),new It(t,n,e,r)}function Ht(t,n,e,r){return 1===arguments.length?((i=t)instanceof xt||(i=Xt(i)),i?new It((i=i.rgb()).r,i.g,i.b,i.opacity):new It):new It(t,n,e,null==r?1:r);var i}function It(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function Yt(){return`#${Gt(this.r)}${Gt(this.g)}${Gt(this.b)}`}function Bt(){const t=Ft(this.opacity);return`${1===t?"rgb(":"rgba("}${Vt(this.r)}, ${Vt(this.g)}, ${Vt(this.b)}${1===t?")":`, ${t})`}`}function Ft(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Vt(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Gt(t){return((t=Vt(t))<16?"0":"")+t.toString(16)}function Ut(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new Wt(t,n,e,r)}function Zt(t){if(t instanceof Wt)return new Wt(t.h,t.s,t.l,t.opacity);if(t instanceof xt||(t=Xt(t)),!t)return new Wt;if(t instanceof Wt)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),u=NaN,a=o-i,l=(o+i)/2;return a?(u=n===o?(e-r)/a+6*(e0&&l<1?0:u,new Wt(u,a,l,t.opacity)}function Wt(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function Kt(t){return(t=(t||0)%360)<0?t+360:t}function Jt(t){return Math.max(0,Math.min(1,t||0))}function Qt(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}wt(xt,Xt,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:Ot,formatHex:Ot,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return Zt(this).formatHsl()},formatRgb:Lt,toString:Lt}),wt(It,Ht,bt(xt,{brighter(t){return t=null==t?St:Math.pow(St,t),new It(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?Et:Math.pow(Et,t),new It(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new It(Vt(this.r),Vt(this.g),Vt(this.b),Ft(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Yt,formatHex:Yt,formatHex8:function(){return`#${Gt(this.r)}${Gt(this.g)}${Gt(this.b)}${Gt(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:Bt,toString:Bt})),wt(Wt,(function(t,n,e,r){return 1===arguments.length?Zt(t):new Wt(t,n,e,null==r?1:r)}),bt(xt,{brighter(t){return t=null==t?St:Math.pow(St,t),new Wt(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?Et:Math.pow(Et,t),new Wt(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new It(Qt(t>=240?t-240:t+120,i,r),Qt(t,i,r),Qt(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new Wt(Kt(this.h),Jt(this.s),Jt(this.l),Ft(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=Ft(this.opacity);return`${1===t?"hsl(":"hsla("}${Kt(this.h)}, ${100*Jt(this.s)}%, ${100*Jt(this.l)}%${1===t?")":`, ${t})`}`}}));var tn=t=>()=>t;function nn(t){return 1==(t=+t)?en:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):tn(isNaN(n)?e:n)}}function en(t,n){var e=n-t;return e?function(t,n){return function(e){return t+e*n}}(t,e):tn(isNaN(t)?n:t)}var rn=function t(n){var e=nn(n);function r(t,n){var r=e((t=Ht(t)).r,(n=Ht(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),u=en(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=u(n),t+""}}return r.gamma=t,r}(1);function on(t,n){n||(n=[]);var e,r=t?Math.min(n.length,t.length):0,i=n.slice();return function(o){for(e=0;eo&&(i=n.slice(o,i),a[u]?a[u]+=i:a[++u]=i),(e=e[0])===(r=r[0])?a[u]?a[u]+=r:a[++u]=r:(a[++u]=null,l.push({i:u,x:ln(e,r)})),o=fn.lastIndex;return o180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:ln(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,u.rotate,a,l),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:ln(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,u.skewX,a,l),function(t,n,e,r,o,u){if(t!==e||n!==r){var a=o.push(i(o)+"scale(",null,",",null,")");u.push({i:a-4,x:ln(t,e)},{i:a-2,x:ln(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,u.scaleX,u.scaleY,a,l),o=u=null,function(t){for(var n,e=-1,r=l.length;++e=0&&n._call.call(void 0,t),n=n._next;--En}()}finally{En=0,function(){var t,n,e=mn,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:mn=n);wn=t,Xn(r)}(),An=0}}function Ln(){var t=Cn.now(),n=t-Mn;n>kn&&($n-=n,Mn=t)}function Xn(t){En||(Sn&&(Sn=clearTimeout(Sn)),t-An>24?(t<1/0&&(Sn=setTimeout(On,t-Cn.now()-$n)),Nn&&(Nn=clearInterval(Nn))):(Nn||(Mn=Cn.now(),Nn=setInterval(Ln,kn)),En=1,Pn(On)))}function zn(t,n,e){var r=new Tn;return n=null==n?0:+n,r.restart((e=>{r.stop(),t(e+n)}),n,e),r}Tn.prototype=qn.prototype={constructor:Tn,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?jn():+e)+(null==n?0:+n),this._next||wn===this||(wn?wn._next=this:mn=this,wn=this),this._call=t,this._time=e,Xn()},stop:function(){this._call&&(this._call=null,this._time=1/0,Xn())}};var Dn=r("start","end","cancel","interrupt"),Hn=[],In=0,Yn=1,Bn=2,Fn=3,Vn=4,Gn=5,Un=6;function Zn(t,n,e,r,i,o){var u=t.__transition;if(u){if(e in u)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(t){e.state=Yn,e.timer.restart(u,e.delay,e.time),e.delay<=t&&u(t-e.delay)}function u(o){var s,c,f,h;if(e.state!==Yn)return l();for(s in i)if((h=i[s]).name===e.name){if(h.state===Fn)return zn(u);h.state===Vn?(h.state=Un,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[s]):+sIn)throw new Error("too late; already scheduled");return e}function Kn(t,n){var e=Jn(t,n);if(e.state>Fn)throw new Error("too late; already running");return e}function Jn(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function Qn(t,n){var e,r;return function(){var i=Kn(this,t),o=i.tween;if(o!==e)for(var u=0,a=(r=e=o).length;u=0&&(t=t.slice(0,n)),!t||"start"===t}))}(n)?Wn:Kn;return function(){var u=o(this,t),a=u.on;a!==r&&(i=(r=a).copy()).on(n,e),u.on=i}}(e,t,n))},attr:function(t,n){var e=s(t),r="transform"===e?xn:ee;return this.attrTween(t,"function"==typeof n?(e.local?le:ae)(e,r,ne(this,"attr."+t,n)):null==n?(e.local?ie:re)(e):(e.local?ue:oe)(e,r,n))},attrTween:function(t,n){var e="attr."+t;if(arguments.length<2)return(e=this.tween(e))&&e._value;if(null==n)return this.tween(e,null);if("function"!=typeof n)throw new Error;var r=s(t);return this.tween(e,(r.local?se:ce)(r,n))},style:function(t,n,e){var r="transform"==(t+="")?bn:ee;return null==n?this.styleTween(t,function(t,n){var e,r,i;return function(){var o=H(this,t),u=(this.style.removeProperty(t),H(this,t));return o===u?null:o===e&&u===r?i:i=n(e=o,r=u)}}(t,r)).on("end.style."+t,ge(t)):"function"==typeof n?this.styleTween(t,function(t,n,e){var r,i,o;return function(){var u=H(this,t),a=e(this),l=a+"";return null==a&&(this.style.removeProperty(t),l=a=H(this,t)),u===l?null:u===r&&l===i?o:(i=l,o=n(r=u,a))}}(t,r,ne(this,"style."+t,n))).each(function(t,n){var e,r,i,o,u="style."+n,a="end."+u;return function(){var l=Kn(this,t),s=l.on,c=null==l.value[u]?o||(o=ge(n)):void 0;s===e&&i===c||(r=(e=s).copy()).on(a,i=c),l.on=r}}(this._id,t)):this.styleTween(t,function(t,n,e){var r,i,o=e+"";return function(){var u=H(this,t);return u===o?null:u===r?i:i=n(r=u,e)}}(t,r,n),e).on("end.style."+t,null)},styleTween:function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,function(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&function(t,n,e){return function(r){this.style.setProperty(t,n.call(this,r),e)}}(t,o,e)),r}return o._value=n,o}(t,n,null==e?"":e))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var n=t(this);this.textContent=null==n?"":n}}(ne(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},textTween:function(t){var n="text";if(arguments.length<1)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;return this.tween(n,function(t){var n,e;function r(){var r=t.apply(this,arguments);return r!==e&&(n=(e=r)&&function(t){return function(n){this.textContent=t.call(this,n)}}(r)),n}return r._value=t,r}(t))},remove:function(){return this.on("end.remove",function(t){return function(){var n=this.parentNode;for(var e in this.__transition)if(+e!==t)return;n&&n.removeChild(this)}}(this._id))},tween:function(t,n){var e=this._id;if(t+="",arguments.length<2){for(var r,i=Jn(this.node(),e).tween,o=0,u=i.length;oBn&&e.state0?1:t<0?-1:0},Xe=Math.sqrt;function ze(t){return t>1?Me:t<-1?-Me:Math.asin(t)}function De(){}function He(t,n){t&&Ye.hasOwnProperty(t.type)&&Ye[t.type](t,n)}var Ie={Feature:function(t,n){He(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++rke&&(t-=Math.round(t/$e)*$e),[t,n]}function er(t){return function(n,e){return je(n+=t)>ke&&(n-=Math.round(n/$e)*$e),[n,e]}}function rr(t){var n=er(t);return n.invert=er(-t),n}function ir(t,n){var e=qe(t),r=Oe(t),i=qe(n),o=Oe(n);function u(t,n){var u=qe(n),a=qe(t)*u,l=Oe(t)*u,s=Oe(n),c=s*e+a*r;return[Te(l*i-c*o,a*e-s*r),ze(c*i+l*o)]}return u.invert=function(t,n){var u=qe(n),a=qe(t)*u,l=Oe(t)*u,s=Oe(n),c=s*i-l*o;return[Te(l*i+s*o,a*e+c*r),ze(c*e-a*r)]},u}function or(t,n){(n=Ue(n))[0]-=t,Qe(n);var e,r=(e=-n[1])>1?0:e<-1?ke:Math.acos(e);return((-n[2]<0?-r:r)+$e-Se)%$e}function ur(){var t,n=[];return{point:function(n,e,r){t.push([n,e,r])},lineStart:function(){n.push(t=[])},lineEnd:De,rejoin:function(){n.length>1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function ar(t,n){return je(t[0]-n[0])=0;--o)i.point((c=s[o])[0],c[1]);else r(h.x,h.p.x,-1,i);h=h.p}s=(h=h.o).z,p=!p}while(!h.v);i.lineEnd()}}}function cr(t){if(n=t.length){for(var n,e,r=0,i=t[0];++r=0?1:-1,M=k*N,A=M>ke,$=y*E;if(s.add(Te($*k*Oe(M),_*S+$*qe(M))),a+=A?N+k*$e:N,A^v>=r^b>=r){var C=We(Ue(d),Ue(w));Qe(C);var P=We(u,C);Qe(P);var j=(A^N>=0?-1:1)*ze(P[2]);(i>j||i===j&&(C[0]||C[1]))&&(l+=A^N>=0?1:-1)}}return(a<-Se||a0){for(p||(u.polygonStart(),p=!0),u.lineStart(),t=0;t1&&2&i&&o.push(o.pop().concat(o.shift())),l.push(o.filter(pr))}return d}}function pr(t){return t.length>1}function dr(t,n){return((t=t.x)[0]<0?t[1]-Me-Se:Me-t[1])-((n=n.x)[0]<0?n[1]-Me-Se:Me-n[1])}nr.invert=nr;var vr=hr((function(){return!0}),(function(t){var n,e=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),n=1},point:function(o,u){var a=o>0?ke:-ke,l=je(o-e);je(l-ke)0?Me:-Me),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),n=0):i!==a&&l>=ke&&(je(e-i)Se?Re((Oe(n)*(o=qe(r))*Oe(e)-Oe(r)*(i=qe(n))*Oe(t))/(i*o*u)):(n+r)/2}(e,r,o,u),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),n=0),t.point(e=o,r=u),i=a},lineEnd:function(){t.lineEnd(),e=r=NaN},clean:function(){return 2-n}}}),(function(t,n,e,r){var i;if(null==t)i=e*Me,r.point(-ke,i),r.point(0,i),r.point(ke,i),r.point(ke,0),r.point(ke,-i),r.point(0,-i),r.point(-ke,-i),r.point(-ke,0),r.point(-ke,i);else if(je(t[0]-n[0])>Se){var o=t[0]0,i=je(n)>Se;function o(t,e){return qe(t)*qe(e)>n}function u(t,e,r){var i=[1,0,0],o=We(Ue(t),Ue(e)),u=Ze(o,o),a=o[0],l=u-a*a;if(!l)return!r&&t;var s=n*u/l,c=-n*a/l,f=We(i,o),h=Je(i,s);Ke(h,Je(o,c));var p=f,d=Ze(h,p),v=Ze(p,p),g=d*d-v*(Ze(h,h)-1);if(!(g<0)){var y=Xe(g),_=Je(p,(-d-y)/v);if(Ke(_,h),_=Ge(_),!r)return _;var m,w=t[0],b=e[0],x=t[1],E=e[1];b0^_[1]<(je(_[0]-w)ke^(w<=_[0]&&_[0]<=b)){var k=Je(p,(-d+y)/v);return Ke(k,h),[_,Ge(k)]}}}function a(n,e){var i=r?t:ke-t,o=0;return n<-i?o|=1:n>i&&(o|=2),e<-i?o|=4:e>i&&(o|=8),o}return hr(o,(function(t){var n,e,l,s,c;return{lineStart:function(){s=l=!1,c=1},point:function(f,h){var p,d=[f,h],v=o(f,h),g=r?v?0:a(f,h):v?a(f+(f<0?ke:-ke),h):0;if(!n&&(s=l=v)&&t.lineStart(),v!==l&&(!(p=u(n,d))||ar(n,p)||ar(d,p))&&(d[2]=1),v!==l)c=0,v?(t.lineStart(),p=u(d,n),t.point(p[0],p[1])):(p=u(n,d),t.point(p[0],p[1],2),t.lineEnd()),n=p;else if(i&&n&&r^v){var y;g&e||!(y=u(d,n,!0))||(c=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1],3)))}!v||n&&ar(n,d)||t.point(d[0],d[1]),n=d,l=v,e=g},lineEnd:function(){l&&t.lineEnd(),n=null},clean:function(){return c|(s&&l)<<1}}}),(function(n,r,i,o){!function(t,n,e,r,i,o){if(e){var u=qe(n),a=Oe(n),l=r*e;null==i?(i=n+r*$e,o=n-l/2):(i=or(u,i),o=or(u,o),(r>0?io)&&(i+=r*$e));for(var s,c=i;r>0?c>o:c0)do{l.point(0===c||3===c?t:r,c>1?i:e)}while((c=(c+u+4)%4)!==f);else l.point(o[0],o[1])}function a(n,i){return je(n[0]-t)0?0:3:je(n[0]-r)0?2:1:je(n[1]-e)0?1:0:i>0?3:2}function l(t,n){return s(t.x,n.x)}function s(t,n){var e=a(t,1),r=a(n,1);return e!==r?e-r:0===e?n[1]-t[1]:1===e?t[0]-n[0]:2===e?t[1]-n[1]:n[0]-t[0]}return function(a){var s,c,f,h,p,d,v,g,y,_,m,w=a,b=ur(),x={point:E,lineStart:function(){x.point=S,c&&c.push(f=[]);_=!0,y=!1,v=g=NaN},lineEnd:function(){s&&(S(h,p),d&&y&&b.rejoin(),s.push(b.result()));x.point=E,y&&w.lineEnd()},polygonStart:function(){w=b,s=[],c=[],m=!0},polygonEnd:function(){var e=function(){for(var n=0,e=0,r=c.length;ei&&(h-o)*(i-u)>(p-u)*(t-o)&&++n:p<=i&&(h-o)*(i-u)<(p-u)*(t-o)&&--n;return n}(),r=m&&e,o=(s=n(s)).length;(r||o)&&(a.polygonStart(),r&&(a.lineStart(),u(null,null,1,a),a.lineEnd()),o&&sr(s,l,e,u,a),a.polygonEnd());w=a,s=c=f=null}};function E(t,n){o(t,n)&&w.point(t,n)}function S(n,u){var a=o(n,u);if(c&&f.push([n,u]),_)h=n,p=u,d=a,_=!1,a&&(w.lineStart(),w.point(n,u));else if(a&&y)w.point(n,u);else{var l=[v=Math.max(_r,Math.min(yr,v)),g=Math.max(_r,Math.min(yr,g))],s=[n=Math.max(_r,Math.min(yr,n)),u=Math.max(_r,Math.min(yr,u))];!function(t,n,e,r,i,o){var u,a=t[0],l=t[1],s=0,c=1,f=n[0]-a,h=n[1]-l;if(u=e-a,f||!(u>0)){if(u/=f,f<0){if(u0){if(u>c)return;u>s&&(s=u)}if(u=i-a,f||!(u<0)){if(u/=f,f<0){if(u>c)return;u>s&&(s=u)}else if(f>0){if(u0)){if(u/=h,h<0){if(u0){if(u>c)return;u>s&&(s=u)}if(u=o-l,h||!(u<0)){if(u/=h,h<0){if(u>c)return;u>s&&(s=u)}else if(h>0){if(u0&&(t[0]=a+s*f,t[1]=l+s*h),c<1&&(n[0]=a+c*f,n[1]=l+c*h),!0}}}}}(l,s,t,e,r,i)?a&&(w.lineStart(),w.point(n,u),m=!1):(y||(w.lineStart(),w.point(l[0],l[1])),w.point(s[0],s[1]),a||w.lineEnd(),m=!1)}v=n,g=u,y=a}return x}}var wr,br,xr,Er,Sr=t=>t,Nr=new t,kr=new t,Mr={point:De,lineStart:De,lineEnd:De,polygonStart:function(){Mr.lineStart=Ar,Mr.lineEnd=Pr},polygonEnd:function(){Mr.lineStart=Mr.lineEnd=Mr.point=De,Nr.add(je(kr)),kr=new t},result:function(){var n=Nr/2;return Nr=new t,n}};function Ar(){Mr.point=$r}function $r(t,n){Mr.point=Cr,wr=xr=t,br=Er=n}function Cr(t,n){kr.add(Er*t-xr*n),xr=t,Er=n}function Pr(){Cr(wr,br)}var jr=1/0,Rr=jr,Tr=-jr,qr=Tr,Or={point:function(t,n){tTr&&(Tr=t);nqr&&(qr=n)},lineStart:De,lineEnd:De,polygonStart:De,polygonEnd:De,result:function(){var t=[[jr,Rr],[Tr,qr]];return Tr=qr=-(Rr=jr=1/0),t}};var Lr,Xr,zr,Dr,Hr=0,Ir=0,Yr=0,Br=0,Fr=0,Vr=0,Gr=0,Ur=0,Zr=0,Wr={point:Kr,lineStart:Jr,lineEnd:ni,polygonStart:function(){Wr.lineStart=ei,Wr.lineEnd=ri},polygonEnd:function(){Wr.point=Kr,Wr.lineStart=Jr,Wr.lineEnd=ni},result:function(){var t=Zr?[Gr/Zr,Ur/Zr]:Vr?[Br/Vr,Fr/Vr]:Yr?[Hr/Yr,Ir/Yr]:[NaN,NaN];return Hr=Ir=Yr=Br=Fr=Vr=Gr=Ur=Zr=0,t}};function Kr(t,n){Hr+=t,Ir+=n,++Yr}function Jr(){Wr.point=Qr}function Qr(t,n){Wr.point=ti,Kr(zr=t,Dr=n)}function ti(t,n){var e=t-zr,r=n-Dr,i=Xe(e*e+r*r);Br+=i*(zr+t)/2,Fr+=i*(Dr+n)/2,Vr+=i,Kr(zr=t,Dr=n)}function ni(){Wr.point=Kr}function ei(){Wr.point=ii}function ri(){oi(Lr,Xr)}function ii(t,n){Wr.point=oi,Kr(Lr=zr=t,Xr=Dr=n)}function oi(t,n){var e=t-zr,r=n-Dr,i=Xe(e*e+r*r);Br+=i*(zr+t)/2,Fr+=i*(Dr+n)/2,Vr+=i,Gr+=(i=Dr*t-zr*n)*(zr+t),Ur+=i*(Dr+n),Zr+=3*i,Kr(zr=t,Dr=n)}function ui(t){this._context=t}ui.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._context.moveTo(t,n),this._point=1;break;case 1:this._context.lineTo(t,n);break;default:this._context.moveTo(t+this._radius,n),this._context.arc(t,n,this._radius,0,$e)}},result:De};var ai,li,si,ci,fi,hi=new t,pi={point:De,lineStart:function(){pi.point=di},lineEnd:function(){ai&&vi(li,si),pi.point=De},polygonStart:function(){ai=!0},polygonEnd:function(){ai=null},result:function(){var n=+hi;return hi=new t,n}};function di(t,n){pi.point=vi,li=ci=t,si=fi=n}function vi(t,n){ci-=t,fi-=n,hi.add(Xe(ci*ci+fi*fi)),ci=t,fi=n}let gi,yi,_i,mi;class wi{constructor(t){this._append=null==t?bi:function(t){const n=Math.floor(t);if(!(n>=0))throw new RangeError(`invalid digits: ${t}`);if(n>15)return bi;if(n!==gi){const t=10**n;gi=n,yi=function(n){let e=1;this._+=n[0];for(const r=n.length;e4*n&&v--){var w=u+h,b=a+p,x=l+d,E=Xe(w*w+b*b+x*x),S=ze(x/=E),N=je(je(x)-1)n||je((y*$+_*C)/m-.5)>.3||u*h+a*p+l*d2?t[2]%360*Pe:0,$()):[g*Ce,y*Ce,_*Ce]},M.angle=function(t){return arguments.length?(m=t%360*Pe,$()):m*Ce},M.reflectX=function(t){return arguments.length?(w=t?-1:1,$()):w<0},M.reflectY=function(t){return arguments.length?(b=t?-1:1,$()):b<0},M.precision=function(t){return arguments.length?(u=Ai(a,k=t*t),C()):Xe(k)},M.fitExtent=function(t,n){return Ni(M,t,n)},M.fitSize=function(t,n){return function(t,n,e){return Ni(t,[[0,0],n],e)}(M,t,n)},M.fitWidth=function(t,n){return function(t,n,e){return Si(t,(function(e){var r=+n,i=r/(e[1][0]-e[0][0]),o=(r-i*(e[1][0]+e[0][0]))/2,u=-i*e[0][1];t.scale(150*i).translate([o,u])}),e)}(M,t,n)},M.fitHeight=function(t,n){return function(t,n,e){return Si(t,(function(e){var r=+n,i=r/(e[1][1]-e[0][1]),o=-i*e[0][0],u=(r-i*(e[1][1]+e[0][1]))/2;t.scale(150*i).translate([o,u])}),e)}(M,t,n)},function(){return n=t.apply(this,arguments),M.invert=n.invert&&A,$()}}((function(){return t}))()}function Ri(t,n){return[qe(n)*Oe(t),Oe(n)]}function Ti(t,n,e){this.k=t,this.x=n,this.y=e}function qi(t){return t}function Oi(t,n){var e=n.id,r=n.bbox,i=null==n.properties?{}:n.properties,o=function(t,n){var e=function(t){if(null==t)return qi;var n,e,r=t.scale[0],i=t.scale[1],o=t.translate[0],u=t.translate[1];return function(t,a){a||(n=e=0);var l=2,s=t.length,c=new Array(s);for(c[0]=(n+=t[0])*r+o,c[1]=(e+=t[1])*i+u;l=0))throw new RangeError(`invalid digits: ${t}`);i=n}return null===n&&(r=new wi(i)),u},u.projection(t).digits(i).context(n)}(this.projection,r),this.globe={type:"Sphere"},this.land=(o=Li,"GeometryCollection"===(u=Li.objects.land).type?{type:"FeatureCollection",features:u.geometries.map((function(t){return Oi(o,t)}))}:Oi(o,u)),this._update(),n.on("move",this._update.bind(this))},_draw_marker:function(){const{globeSize:t,markerSize:n,markerColor:e}=this.options;mt(Xi).append("svg").attr("width",t).attr("height",t).attr("style","position: absolute; left: 0; top: 0;").append("path").attr("opacity",0).attr("d","M5.36018 5.33333C5.36018 4.59722 5.61972 3.96875 6.13881 3.44792C6.65789 2.92708 7.28426 2.66667 8.0179 2.66667C8.75154 2.66667 9.3779 2.92708 9.89699 3.44792C10.4161 3.96875 10.6756 4.59722 10.6756 5.33333C10.6756 6.06944 10.4161 6.69792 9.89699 7.21875C9.3779 7.73958 8.75154 8 8.0179 8C7.28426 8 6.65789 7.73958 6.13881 7.21875C5.61972 6.69792 5.36018 6.06944 5.36018 5.33333ZM2.70246 5.33333C2.70246 6.09028 2.81666 6.7118 3.04506 7.19792L6.824 15.2604C6.93474 15.4896 7.09911 15.6701 7.31713 15.8021C7.53515 15.934 7.76874 16 8.0179 16C8.26706 16 8.50065 15.934 8.71866 15.8021C8.93668 15.6701 9.09759 15.4896 9.20141 15.2604L12.9907 7.19792C13.2191 6.71181 13.3333 6.09028 13.3333 5.33333C13.3333 3.86111 12.8142 2.60417 11.7761 1.5625C10.7379 0.520833 9.48518 -8.13254e-07 8.0179 -9.41527e-07C6.55062 -1.0698e-06 5.29789 0.520832 4.25972 1.5625C3.22155 2.60417 2.70246 3.86111 2.70246 5.33333Z").attr("transform",`scale(${n}, ${n}), translate(${t*(1/n)/2-8}, ${t*(1/n)/2-16})`).attr("style","fill:"+e).transition().duration(100).attr("opacity",1)},_update:function(){const t=this,n=this._parentMap.getCenter();me().duration(this.initialTween?1e3:1).tween("rotate",(function(){const e=pn(t.projection.rotate(),[-n.lng,-n.lat]);return function(n){t.projection.rotate(e(n)),t.context.clearRect(0,0,t.canvas.width,t.canvas.height),t.context.fillStyle=t.options.waterColor,t.context.beginPath(),t.path(t.globe),t.context.fill(),t.context.fillStyle=t.options.landColor,t.context.beginPath(),t.path(t.land),t.context.fill()}})).on("end",(()=>{t.initialTween&&(t._draw_marker(),t.initialTween=!1)}))},_createContainer:function(t){const{globeSize:n,id:e}=this.options,r=document.createElement("div");return r.className="mapboxgl-ctrl-globe-minimap mapboxgl-ctrl",r.setAttribute("style","width: "+n+"; height: "+n+";"),r.addEventListener("contextmenu",this._preventDefault),t.getContainer().appendChild(r),""!==e&&(r.id=e),r},_preventDefault:function(t){t.preventDefault()}},window.GlobeMinimap=zi,zi}(); diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js new file mode 100644 index 0000000..207d876 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js @@ -0,0 +1,1102 @@ +/** + * mapbox-pmtiles v1.1.0 - Optimized Version with Lifecycle Management + * Original source: https://github.com/am2222/mapbox-pmtiles by Majid Hojati + * License: MIT + * + * This is an optimized version of the mapbox-pmtiles library that provides + * better performance for large datasets through: + * - Configurable resource management + * - Instance-scoped worker pools and caches + * - Proper lifecycle management and cleanup + * - Reference counting for shared resources + * - Enhanced error handling and timeouts + * - Memory optimization with size-based LRU caches + * + * Last updated: 2025 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + // Global shared resources with reference counting + const GLOBAL_SHARED_RESOURCES = { + // Protocol cache - expensive to duplicate, shared with reference counting + protocolCache: new Map(), // url -> { protocol, instance, refCount } + + // Metadata cache - small and shareable + metadataCache: new Map(), // cacheKey -> data + + // Pre-calculated world sizes for common zoom levels (static, no cleanup needed) + worldSizeCache: new Array(25).fill(null).map((_, z) => Math.pow(2, z)), + + // Global cleanup registry + activeManagers: new Set(), + + // Debug/development features + debug: false, + performanceMetrics: new Map(), + }; + + /** + * Default configuration options + */ + const DEFAULT_OPTIONS = { + workerPoolSize: 4, + tileCacheSize: 1000, + tileCacheMaxMemoryMB: 100, + metadataCacheSize: 100, + enableSharedProtocols: true, + requestTimeoutMs: 30000, + enableDebugLogging: false, + enablePerformanceMetrics: false, + }; + + /** + * LRU Cache implementation with size-based eviction + */ + class LRUCache { + constructor(maxSize, maxMemoryBytes = Infinity) { + this.maxSize = maxSize; + this.maxMemoryBytes = maxMemoryBytes; + this.cache = new Map(); + this.currentMemoryBytes = 0; + } + + get(key) { + if (this.cache.has(key)) { + // Move to end (most recently used) + const value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return value.data; + } + return undefined; + } + + set(key, data, estimatedSize = 0) { + // Remove if exists + if (this.cache.has(key)) { + const existing = this.cache.get(key); + this.currentMemoryBytes -= existing.size; + this.cache.delete(key); + } + + // Evict old entries if necessary + while ( + this.cache.size >= this.maxSize || + this.currentMemoryBytes + estimatedSize > this.maxMemoryBytes + ) { + const firstKey = this.cache.keys().next().value; + if (!firstKey) break; + + const firstValue = this.cache.get(firstKey); + this.currentMemoryBytes -= firstValue.size; + this.cache.delete(firstKey); + } + + // Add new entry + this.cache.set(key, { data, size: estimatedSize }); + this.currentMemoryBytes += estimatedSize; + } + + has(key) { + return this.cache.has(key); + } + + delete(key) { + if (this.cache.has(key)) { + const value = this.cache.get(key); + this.currentMemoryBytes -= value.size; + this.cache.delete(key); + return true; + } + return false; + } + + clear() { + this.cache.clear(); + this.currentMemoryBytes = 0; + } + + get size() { + return this.cache.size; + } + + getMemoryUsage() { + return { + entries: this.cache.size, + memoryBytes: this.currentMemoryBytes, + memoryMB: this.currentMemoryBytes / (1024 * 1024), + }; + } + } + + /** + * Resource Manager - handles per-instance resources and lifecycle + */ + class PMTilesResourceManager { + constructor(options = {}) { + this.config = { ...DEFAULT_OPTIONS, ...options }; + this.destroyed = false; + this.paused = false; + this.dispatcher = null; + + // Instance-scoped resources + this.workerPool = []; + this.workerPoolIndex = 0; + this.tileCache = new LRUCache( + this.config.tileCacheSize, + this.config.tileCacheMaxMemoryMB * 1024 * 1024, + ); + this.pendingRequests = new Map(); + this.activeRequests = new Set(); + + // Performance tracking + this.metrics = { + tilesLoaded: 0, + cacheHits: 0, + cacheMisses: 0, + memoryPeakMB: 0, + averageLoadTimeMs: 0, + }; + + // Register for global cleanup + GLOBAL_SHARED_RESOURCES.activeManagers.add(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager created", this.config); + } + } + + /** + * Initialize worker pool + */ + initializeWorkerPool(dispatcher) { + if (this.destroyed) return; + + // Store dispatcher reference + if (dispatcher) { + this.dispatcher = dispatcher; + } + + if (this.workerPool.length === 0 && this.dispatcher) { + for (let i = 0; i < this.config.workerPoolSize; i++) { + try { + this.workerPool.push(this.dispatcher.getActor()); + } catch (error) { + console.warn("[PMTiles] Failed to create worker:", error); + } + } + + if (this.config.enableDebugLogging) { + console.log( + `[PMTiles] Initialized worker pool with ${this.workerPool.length} workers`, + ); + } + } + } + + /** + * Get next worker from pool (round-robin) + */ + getWorkerFromPool() { + if (this.destroyed) { + return null; + } + + // Try to initialize workers if not done yet + if (this.workerPool.length === 0 && this.dispatcher) { + this.initializeWorkerPool(this.dispatcher); + } + + if (this.workerPool.length === 0) { + if (this.config.enableDebugLogging) { + console.warn( + "[PMTiles] Worker pool is empty, dispatcher available:", + !!this.dispatcher, + ); + } + return null; + } + + const worker = this.workerPool[this.workerPoolIndex]; + this.workerPoolIndex = + (this.workerPoolIndex + 1) % this.workerPool.length; + return worker; + } + + /** + * Get or create protocol instance with reference counting + */ + getProtocol(url) { + if (this.destroyed) return null; + + if (!this.config.enableSharedProtocols) { + // Create instance-specific protocol + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + return { protocol, instance }; + } + + // Use shared protocol with reference counting + if (!GLOBAL_SHARED_RESOURCES.protocolCache.has(url)) { + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + GLOBAL_SHARED_RESOURCES.protocolCache.set(url, { + protocol, + instance, + refCount: 0, + }); + } + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + cached.refCount++; + return cached; + } + + /** + * Release protocol reference + */ + releaseProtocol(url) { + if (!this.config.enableSharedProtocols) return; + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + if (cached) { + cached.refCount--; + if (cached.refCount <= 0) { + GLOBAL_SHARED_RESOURCES.protocolCache.delete(url); + + if (this.config.enableDebugLogging) { + console.log(`[PMTiles] Released protocol for ${url}`); + } + } + } + } + + /** + * Cache key for tiles + */ + getTileCacheKey(url, z, x, y) { + return `${url}:${z}:${x}:${y}`; + } + + /** + * Add tile to cache with size estimation + */ + addToTileCache(key, data) { + if (this.destroyed) return; + + let estimatedSize = 0; + if (data instanceof ImageBitmap) { + // Rough estimation: width * height * 4 bytes per pixel + estimatedSize = data.width * data.height * 4; + } else if (data && data.byteLength) { + estimatedSize = data.byteLength; + } else { + estimatedSize = 10000; // Default estimate + } + + this.tileCache.set(key, data, estimatedSize); + + // Update peak memory usage + const memoryUsage = this.tileCache.getMemoryUsage(); + this.metrics.memoryPeakMB = Math.max( + this.metrics.memoryPeakMB, + memoryUsage.memoryMB, + ); + } + + /** + * Get cached metadata + */ + getCachedMetadata(cacheKey) { + return GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + } + + /** + * Set cached metadata + */ + setCachedMetadata(cacheKey, data) { + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, data); + } + + /** + * Pause all operations + */ + pause() { + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager paused"); + } + } + + /** + * Resume operations + */ + resume() { + this.paused = false; + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager resumed"); + } + } + + /** + * Get performance metrics + */ + getMetrics() { + return { + ...this.metrics, + tileCache: this.tileCache.getMemoryUsage(), + workerPoolSize: this.workerPool.length, + pendingRequests: this.pendingRequests.size, + isPaused: this.paused, + isDestroyed: this.destroyed, + }; + } + + /** + * Destroy and cleanup all resources + */ + destroy() { + if (this.destroyed) return; + + this.destroyed = true; + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + // Clear caches + this.tileCache.clear(); + + // Clear worker pool references + this.workerPool.length = 0; + + // Remove from global registry + GLOBAL_SHARED_RESOURCES.activeManagers.delete(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager destroyed", this.getMetrics()); + } + } + } + + /** + * Global cleanup function + */ + const cleanup = () => { + for (const manager of GLOBAL_SHARED_RESOURCES.activeManagers) { + manager.destroy(); + } + GLOBAL_SHARED_RESOURCES.protocolCache.clear(); + GLOBAL_SHARED_RESOURCES.metadataCache.clear(); + }; + + // Register global cleanup + if (typeof window !== "undefined") { + window.addEventListener("beforeunload", cleanup); + } + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + + // Pre-calculate mercator bounds + this._mercatorBounds = { + west: mercatorXFromLng(this.bounds.getWest()), + north: mercatorYFromLat(this.bounds.getNorth()), + east: mercatorXFromLng(this.bounds.getEast()), + south: mercatorYFromLat(this.bounds.getSouth()), + }; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + // Use pre-calculated world size + const worldSize = + GLOBAL_SHARED_RESOURCES.worldSizeCache[tileID.z] || + Math.pow(2, tileID.z); + + // Use pre-calculated mercator bounds + const level = { + minX: Math.floor(this._mercatorBounds.west * worldSize), + minY: Math.floor(this._mercatorBounds.north * worldSize), + maxX: Math.ceil(this._mercatorBounds.east * worldSize), + maxY: Math.ceil(this._mercatorBounds.south * worldSize), + }; + + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + /** + * Enhanced PMTiles Source with lifecycle management + */ + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + + // Extract PMTiles-specific options + const pmtilesOptions = { + workerPoolSize: options.workerPoolSize, + tileCacheSize: options.tileCacheSize, + tileCacheMaxMemoryMB: options.tileCacheMaxMemoryMB, + metadataCacheSize: options.metadataCacheSize, + enableSharedProtocols: options.enableSharedProtocols, + requestTimeoutMs: options.requestTimeoutMs, + enableDebugLogging: options.enableDebugLogging, + enablePerformanceMetrics: options.enablePerformanceMetrics, + }; + + // Initialize resource manager + this.resourceManager = new PMTilesResourceManager(pmtilesOptions); + + // Standard source properties + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = _dispatcher; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._implementation = options; + + // Initialize worker pool + this.resourceManager.initializeWorkerPool(_dispatcher); + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + return; + } + + const { url } = options; + this.url = url; + this.tileSize = 512; + + // Get protocol instance + this.protocolInfo = this.resourceManager.getProtocol(url); + if (!this.protocolInfo) { + this.fire( + new ErrorEvent(new Error(`Failed to create protocol for ${url}`)), + ); + return; + } + + this._protocol = this.protocolInfo.protocol; + this._instance = this.protocolInfo.instance; + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + } + + static async getMetadata(url) { + // Check cache first + const cacheKey = `${url}:metadata`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const metadata = await instance.getMetadata(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, metadata); + return metadata; + } + + static async getHeader(url) { + // Check cache first + const cacheKey = `${url}:header`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const header = await instance.getHeader(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, header); + return header; + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (this.resourceManager.destroyed) return; + + if (!tile.destroy) { + tile.destroy = () => {}; + } + if (!tile.abort) { + tile.abort = () => { + tile.aborted = true; + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + }; + } + } + + /** + * Pause tile loading + */ + pause() { + this.resourceManager.pause(); + } + + /** + * Resume tile loading + */ + resume() { + this.resourceManager.resume(); + } + + /** + * Get performance metrics + */ + getMetrics() { + return this.resourceManager.getMetrics(); + } + + /** + * Destroy source and cleanup resources + */ + destroy() { + if (this.protocolInfo && this.url) { + this.resourceManager.releaseProtocol(this.url); + } + + this.resourceManager.destroy(); + this._loaded = false; + } + + async load(callback) { + if (this.resourceManager.destroyed) { + const error = new Error("Source has been destroyed"); + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + // Check metadata cache first + const headerKey = `${this.url}:header`; + const metadataKey = `${this.url}:metadata`; + + let header, tileJSON; + + const cachedHeader = this.resourceManager.getCachedMetadata(headerKey); + const cachedMetadata = + this.resourceManager.getCachedMetadata(metadataKey); + + if (cachedHeader && cachedMetadata) { + header = cachedHeader; + tileJSON = cachedMetadata; + } else { + try { + // Load and cache + [header, tileJSON] = await Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]); + this.resourceManager.setCachedMetadata(headerKey, header); + this.resourceManager.setCachedMetadata(metadataKey, tileJSON); + } catch (error) { + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + } + + try { + extend(this, tileJSON); + this.header = header; + const { tileType, minZoom, maxZoom, minLon, minLat, maxLon, maxLat } = + header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes(this.tileType) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { dataType: "source", sourceDataType: "metadata" }), + ); + this.fire( + new Event("data", { dataType: "source", sourceDataType: "content" }), + ); + } catch (err2) { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + } + } + + loaded() { + return this._loaded && !this.resourceManager.destroyed; + } + + loadVectorTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + const startTime = Date.now(); + var _a2, _b2, _c; + + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + + // Update metrics + this.resourceManager.metrics.tilesLoaded++; + const loadTime = Date.now() - startTime; + this.resourceManager.metrics.averageLoadTimeMs = + (this.resourceManager.metrics.averageLoadTimeMs + loadTime) / 2; + + if (tile.aborted) return callback(null); + + // Handle abort errors gracefully + if (err2 && err2.name === "AbortError") { + return callback(null); + } + + if (err2 && err2.status !== 404) { + return callback(err2); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + // Handle abort errors gracefully + if (error && (error.name === "AbortError" || error.code === 20)) { + return done.call(this, null); + } + done.call(this, error); + return; + } + + params.data = { + cacheControl, + expires, + rawData: data, + }; + + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + // Use shared worker pool + tile.actor = this.resourceManager.getWorkerFromPool(); + + // Fallback to dispatcher if worker pool failed + if (!tile.actor && this.dispatcher) { + try { + tile.actor = this.dispatcher.getActor(); + } catch (error) { + console.warn("[PMTiles] Failed to get fallback worker:", error); + return callback(new Error("No workers available")); + } + } + + if (!tile.actor) { + return callback(new Error("No workers available")); + } + + // Create request with timeout + const requestPromise = this._protocol.tile({ ...request }, afterLoad); + + // Add timeout if configured + if (this.resourceManager.config.requestTimeoutMs > 0) { + const timeoutId = setTimeout(() => { + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + done.call(this, new Error("Request timeout")); + }, this.resourceManager.config.requestTimeoutMs); + + const originalCancel = requestPromise.cancel; + requestPromise.cancel = () => { + clearTimeout(timeoutId); + if (originalCancel) originalCancel(); + }; + } + + tile.request = requestPromise; + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + if (this.resourceManager.destroyed) return; + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + var _a2, _b2; + + // Check tile cache first + const cacheKey = this.resourceManager.getTileCacheKey( + this.url, + tile.tileID.canonical.z, + tile.tileID.canonical.x, + tile.tileID.canonical.y, + ); + + if (this.resourceManager.tileCache.has(cacheKey)) { + this.resourceManager.metrics.cacheHits++; + const cachedData = this.resourceManager.tileCache.get(cacheKey); + this.loadRasterTileData(tile, cachedData); + tile.state = "loaded"; + return callback(null); + } + + this.resourceManager.metrics.cacheMisses++; + + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + + // Optimized raster tile loading - try direct ArrayBuffer first + const arrayBuffer = data.buffer || data; + window + .createImageBitmap(arrayBuffer) + .then((imageBitmap) => { + // Cache the decoded image + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + // Fallback to blob method + const blob = new window.Blob([new Uint8Array(data)], { + type: this.contentType, + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error(`Can't decode image for ${this.id}: ${error}`), + ); + }); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + this.fixTile(tile); + const controller = new AbortController(); + + // Add timeout if configured + let timeoutId; + if (this.resourceManager.config.requestTimeoutMs > 0) { + timeoutId = setTimeout(() => { + controller.abort(); + }, this.resourceManager.config.requestTimeoutMs); + } + + tile.request = { + cancel: () => { + if (timeoutId) clearTimeout(timeoutId); + controller.abort(); + }, + }; + + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (timeoutId) clearTimeout(timeoutId); + + // Handle abort errors gracefully + if (error.name === "AbortError" || error.code === 20) { + delete tile.request; + return callback(null); + } + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Expose cleanup function + PmTilesSource.cleanup = cleanup; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; + global.PMTilesResourceManager = PMTilesResourceManager; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js new file mode 100644 index 0000000..2130749 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js @@ -0,0 +1,459 @@ +/** + * mapbox-pmtiles v1.0.53 + * Original source: https://github.com/am2222/mapbox-pmtiles + * License: MIT + * + * This is a vendored copy of the mapbox-pmtiles library that provides + * PMTiles support for Mapbox GL JS by implementing a custom source type. + * + * Last updated: 2024 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + const worldSize = Math.pow(2, tileID.z); + const level = { + minX: Math.floor(mercatorXFromLng(this.bounds.getWest()) * worldSize), + minY: Math.floor(mercatorYFromLat(this.bounds.getNorth()) * worldSize), + maxX: Math.ceil(mercatorXFromLng(this.bounds.getEast()) * worldSize), + maxY: Math.ceil(mercatorYFromLat(this.bounds.getSouth()) * worldSize), + }; + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = void 0; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._dataType = "vector"; + this.dispatcher = _dispatcher; + this._implementation = options; + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + } + + const { url } = options; + this.reparseOverscaled = true; + this.scheme = "xyz"; + this.tileSize = 512; + this._loaded = false; + this.type = "vector"; + this._protocol = new pmtiles.Protocol(); + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + const pmtilesInstance = new pmtiles.PMTiles(url); + this._protocol.add(pmtilesInstance); + this._instance = pmtilesInstance; + } + + static async getMetadata(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getMetadata(); + } + + static async getHeader(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getHeader(); + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (!tile.destroy) { + tile.destroy = () => {}; + } + } + + async load(callback) { + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + return Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]) + .then(([header, tileJSON]) => { + extend(this, tileJSON); + this.header = header; + const { + specVersion, + clustered, + tileType, + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + centerZoom, + centerLon, + centerLat, + } = header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes( + this.tileType, + ) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "metadata", + }), + ); + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "content", + }), + ); + }) + .catch((err2) => { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + }); + } + + loaded() { + return this._loaded; + } + + loadVectorTile(tile, callback) { + var _a2, _b2, _c; + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + if (tile.aborted) return callback(null); + if (err2 && err2.status !== 404) { + return callback(err2); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + done.call(this, error); + return; + } + params.data = { + cacheControl, + expires, + rawData: data, + }; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + tile.actor = this._tileWorkers[url] = + this._tileWorkers[url] || this.dispatcher.getActor(); + tile.request = this._protocol.tile({ ...request }, afterLoad); + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + var _a2, _b2; + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + const blob = new window.Blob([new Uint8Array(data)], { + type: "image/png", + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error( + `Can't infer data type for ${this.id}, only raster data supported at the moment. ${error}`, + ), + ); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + this.fixTile(tile); + const controller = new AbortController(); + tile.request = { cancel: () => controller.abort() }; + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (error.code === 20) return; + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css new file mode 100644 index 0000000..16b2196 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css @@ -0,0 +1,44 @@ +.maplibregl-compare { + background-color: #fff; + position: absolute; + width: 2px; + height: 100%; + z-index: 1; +} +.maplibregl-compare .compare-swiper-vertical { + background-color: #3887be; + box-shadow: inset 0 0 0 2px #fff; + display: inline-block; + border-radius: 50%; + position: absolute; + width: 60px; + height: 60px; + top: 50%; + left: -30px; + margin: -30px 1px 0; + color: #fff; + cursor: ew-resize; + background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgd2lkdGg9IjYwIiAgIGhlaWdodD0iNjAiICAgdmVyc2lvbj0iMS4xIiAgIHZpZXdCb3g9IjAgMCA2MCA2MCIgICBpZD0ic3ZnNTQzNCIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxK2RldmVsK29zeG1lbnUgcjEyOTExIiAgIHNvZGlwb2RpOmRvY25hbWU9Imwtci5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE1NDQ0Ij4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgICAgPGRjOnRpdGxlPjwvZGM6dGl0bGU+ICAgICAgPC9jYzpXb3JrPiAgICA8L3JkZjpSREY+ICA8L21ldGFkYXRhPiAgPGRlZnMgICAgIGlkPSJkZWZzNTQ0MiIgLz4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTI4NiIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9Ijc1MSIgICAgIGlkPSJuYW1lZHZpZXc1NDQwIiAgICAgc2hvd2dyaWQ9InRydWUiICAgICBpbmtzY2FwZTp6b29tPSI0IiAgICAgaW5rc2NhcGU6Y3g9IjI1Ljg4OTgzMSIgICAgIGlua3NjYXBlOmN5PSIzNC4zODE4MzMiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyMyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjAiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJzdmc1NDM0IiAgICAgaW5rc2NhcGU6b2JqZWN0LW5vZGVzPSJ0cnVlIiAgICAgaW5rc2NhcGU6c25hcC1zbW9vdGgtbm9kZXM9InRydWUiPiAgICA8aW5rc2NhcGU6Z3JpZCAgICAgICB0eXBlPSJ4eWdyaWQiICAgICAgIGlkPSJncmlkNTk4OSIgLz4gIDwvc29kaXBvZGk6bmFtZWR2aWV3PiAgPHBhdGggICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjFweDtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIiAgICAgZD0iTSAyNSAyNCBMIDE2IDMwIEwgMjUgMzYgTCAyNSAyNCB6IE0gMzUgMjQgTCAzNSAzNiBMIDQ0IDMwIEwgMzUgMjQgeiAiICAgICBpZD0icGF0aDU5OTUiIC8+PC9zdmc+); +} + +.maplibregl-compare-horizontal { + position: relative; + width: 100%; + height: 2px; +} +.maplibregl-compare .compare-swiper-horizontal { + background-color: #3887be; + box-shadow: inset 0 0 0 2px #fff; + display: inline-block; + border-radius: 50%; + position: absolute; + width: 60px; + height: 60px; + top: 50%; + left: 50%; + margin: -30px 1px 0; + color: #fff; + cursor: ns-resize; + background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgd2lkdGg9IjYwIiAgIGhlaWdodD0iNjAiICAgdmVyc2lvbj0iMS4xIiAgIHZpZXdCb3g9IjAgMCA2MCA2MCIgICBpZD0ic3ZnNTQzNCIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxK2RldmVsK29zeG1lbnUgcjEyOTExIiAgIHNvZGlwb2RpOmRvY25hbWU9Imwtci5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE1NDQ0Ij4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgICAgPGRjOnRpdGxlPjwvZGM6dGl0bGU+ICAgICAgPC9jYzpXb3JrPiAgICA8L3JkZjpSREY+ICA8L21ldGFkYXRhPiAgPGRlZnMgICAgIGlkPSJkZWZzNTQ0MiIgLz4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTI4NiIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9Ijc1MSIgICAgIGlkPSJuYW1lZHZpZXc1NDQwIiAgICAgc2hvd2dyaWQ9InRydWUiICAgICBpbmtzY2FwZTp6b29tPSI0IiAgICAgaW5rc2NhcGU6Y3g9IjI1Ljg4OTgzMSIgICAgIGlua3NjYXBlOmN5PSIzNC4zODE4MzMiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyMyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjAiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJzdmc1NDM0IiAgICAgaW5rc2NhcGU6b2JqZWN0LW5vZGVzPSJ0cnVlIiAgICAgaW5rc2NhcGU6c25hcC1zbW9vdGgtbm9kZXM9InRydWUiPiAgICA8aW5rc2NhcGU6Z3JpZCAgICAgICB0eXBlPSJ4eWdyaWQiICAgICAgIGlkPSJncmlkNTk4OSIgLz4gIDwvc29kaXBvZGk6bmFtZWR2aWV3PiAgPHBhdGggICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjFweDtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIiAgICAgZD0iTSAyNSAyNCBMIDE2IDMwIEwgMjUgMzYgTCAyNSAyNCB6IE0gMzUgMjQgTCAzNSAzNiBMIDQ0IDMwIEwgMzUgMjQgeiAiICAgICBpZD0icGF0aDU5OTUiIC8+PC9zdmc+); + transform: rotate(90deg); +} diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js new file mode 100644 index 0000000..71e47d5 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js @@ -0,0 +1 @@ +!function o(i,r,s){function h(t,e){if(!r[t]){if(!i[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(u)return u(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=r[t]={exports:{}},i[t][0].call(n.exports,function(e){return h(i[t][1][e]||e)},n,n.exports,o,i,r,s)}return r[t].exports}for(var u="function"==typeof require&&require,e=0;ethis._bounds.width?this._bounds.width:e},_getY:function(e){e=(e=e.touches?e.touches[0]:e).clientY-this._bounds.top;return e=(e=e<0?0:e)>this._bounds.height?this._bounds.height:e},setSlider:function(e){this._setPosition(e)},on:function(e,t){return this._ev.on(e,t),this},fire:function(e,t){return this._ev.emit(e,t),this},off:function(e,t){return this._ev.removeListener(e,t),this},remove:function(){this._clearSync(),this._mapB.off("resize",this._onResize);var e=this._mapA.getContainer();e&&(e.style.clip=null,e.removeEventListener("mousemove",this._onMove));e=this._mapB.getContainer();e&&(e.style.clip=null,e.removeEventListener("mousemove",this._onMove)),this._swiper.removeEventListener("mousedown",this._onDown),this._swiper.removeEventListener("touchstart",this._onDown),this._controlContainer.remove()}},window.maplibregl?maplibregl.Compare=o:void 0!==t&&(t.exports=o)},{"@mapbox/mapbox-gl-sync-move":2,events:3}],2:[function(e,t,n){t.exports=function(){var e=arguments.length;if(1===e)t=arguments[0];else for(var t=[],n=0;nn&&!r.warned&&(r.warned=!0,(n=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit")).name="MaxListenersExceededWarning",n.emitter=e,n.type=t,n.count=r.length,n=n,console&&console.warn&&console.warn(n))),e}function l(e,t,n){e={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},t=function(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}.bind(e);return t.listener=n,e.wrapFn=t}function p(e,t,n){e=e._events;if(void 0===e)return[];t=e[t];return void 0===t?[]:"function"==typeof t?n?[t.listener||t]:[t]:n?function(e){for(var t=new Array(e.length),n=0;n * { + z-index: 2; + position: absolute; + right: 8px; + top: 7px; + display: none; +} + +.maplibregl-ctrl-geocoder, +.maplibregl-ctrl-geocoder .suggestions { + box-shadow: 0 0 10px 2px rgba(0, 0, 0, 0.1); +} + +/* Collapsed */ +.maplibregl-ctrl-geocoder.maplibregl-ctrl-geocoder--collapsed { + width: 50px; + min-width: 50px; + transition: width 0.25s, min-width 0.25s; +} + +/* Suggestions */ +.maplibregl-ctrl-geocoder .suggestions { + background-color: #fff; + border-radius: 4px; + left: 0; + list-style: none; + margin: 0; + padding: 0; + position: absolute; + width: 100%; + top: 110%; /* fallback */ + top: calc(100% + 6px); + z-index: 1000; + overflow: hidden; + font-size: 15px; +} + +.maplibregl-ctrl-bottom-left .suggestions, +.maplibregl-ctrl-bottom-right .suggestions { + top: auto; + bottom: 100%; +} + +.maplibregl-ctrl-geocoder .suggestions > li > a { + cursor: default; + display: block; + padding: 6px 12px; + color: #404040; +} + +.maplibregl-ctrl-geocoder .suggestions > .active > a, +.maplibregl-ctrl-geocoder .suggestions > li > a:hover { + color: #404040; + background-color: #f3f3f3; + text-decoration: none; + cursor: pointer; +} + +.maplibregl-ctrl-geocoder--suggestion { + display: flex; + flex-direction: row; + align-items: center; +} + +.maplibre-ctrl-geocoder--suggestion-icon { + min-width: 30px; + min-height: 24px; + max-width: 30px; + max-height: 24px; + padding-right: 12px; +} + +.maplibregl-ctrl-geocoder--suggestion-info { + display: flex; + flex-direction: column; +} + +.maplibregl-ctrl-geocoder--suggestion-match { + font-weight: bold; +} + +.maplibregl-ctrl-geocoder--suggestion-title, +.maplibregl-ctrl-geocoder--suggestion-address { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +.maplibregl-ctrl-geocoder--result { + display: flex; + flex-direction: row; + align-items: center; +} + +.maplibre-ctrl-geocoder--result-icon { + min-width: 30px; + min-height: 24px; + max-width: 30px; + max-height: 24px; + padding-right: 12px; +} + +.maplibregl-ctrl-geocoder--result-title { + font-weight: bold; +} + +.maplibregl-ctrl-geocoder--result-title, +.maplibregl-ctrl-geocoder--result-address { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +/* Icons */ +.maplibregl-ctrl-geocoder--icon { + display: inline-block; + vertical-align: middle; + speak: none; + fill: #757575; + top: 15px; +} + +.maplibregl-ctrl-geocoder--icon-search { + position: absolute; + top: 13px; + left: 12px; + width: 23px; + height: 23px; +} + +.maplibregl-ctrl-geocoder--button { + padding: 0; + margin: 0; + border: none; + cursor: pointer; + background: #fff; + line-height: 1; +} + +.maplibregl-ctrl-geocoder--icon-close { + width: 20px; + height: 20px; + margin-top: 8px; + margin-right: 3px; +} + +.maplibregl-ctrl-geocoder--button:hover .maplibregl-ctrl-geocoder--icon-close { + fill: #909090; +} + +.maplibregl-ctrl-geocoder--icon-loading { + width: 26px; + height: 26px; + margin-top: 5px; + margin-right: 0px; + -moz-animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); + -webkit-animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); + animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); +} + +/* Animation */ +@-webkit-keyframes rotate { + from { + -webkit-transform: rotate(0); + transform: rotate(0); + } + to { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +@keyframes rotate { + from { + -webkit-transform: rotate(0); + transform: rotate(0); + } + to { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +/* Media queries*/ +@media screen and (min-width: 640px) { + .maplibregl-ctrl-geocoder.maplibregl-ctrl-geocoder--collapsed { + width: 36px; + min-width: 36px; + } + + .maplibregl-ctrl-geocoder { + width: 33.3333%; + font-size: 15px; + line-height: 20px; + max-width: 360px; + } + .maplibregl-ctrl-geocoder .suggestions { + font-size: 13px; + } + + .maplibregl-ctrl-geocoder--icon { + top: 8px; + } + + .maplibregl-ctrl-geocoder--icon-close { + width: 16px; + height: 16px; + margin-top: 3px; + margin-right: 0; + } + + .maplibregl-ctrl-geocoder--icon-search { + left: 7px; + width: 20px; + height: 20px; + } + + .maplibregl-ctrl-geocoder--input { + height: 36px; + padding: 6px 35px; + } + + .maplibregl-ctrl-geocoder--icon-loading { + width: 26px; + height: 26px; + margin-top: -2px; + margin-right: -5px; + } + + .maplibre-gl-geocoder--error { + color: #909090; + padding: 6px 12px; + font-size: 16px; + text-align: center; + } +} diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js new file mode 100644 index 0000000..e285a1a --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js @@ -0,0 +1,2 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.MaplibreGeocoder=t()}}(function(){return function(){function t(e,i,n){function s(o,l){if(!i[o]){if(!e[o]){var a="function"==typeof require&&require;if(!l&&a)return a(o,!0);if(r)return r(o,!0);var h=new Error("Cannot find module '"+o+"'");throw h.code="MODULE_NOT_FOUND",h}var u=i[o]={exports:{}};e[o][0].call(u.exports,function(t){return s(e[o][1][t]||t)},u,u.exports,t,e,i,n)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o
'+e[0]+'
'+e.splice(1,e.length).join(",")+"
"}var i=t.text,n=i.toLowerCase().indexOf(this.query.toLowerCase()),s=this.query.length;return'
'+i.substring(0,n)+''+i.substring(n,n+s)+""+i.substring(n+s)+"
"},popupRender:function(t){var e=t.place_name.split(",");return'"},showResultMarkers:!0,debounceSearch:200},addTo:function(t){function e(t,e){if(!document.body.contains(e))throw new Error("Element provided to #addTo() exists, but is not in the DOM");var i=t.onAdd();e.appendChild(i)}if(t._controlContainer)t.addControl(this);else if(t instanceof HTMLElement)e(this,t);else{if("string"!=typeof t)throw new Error("Error: addTo must be a maplibre-gl-js map, an html element, or a CSS selector query for a single html element");var i=document.querySelectorAll(t);if(0===i.length)throw new Error("Element ",t,"not found.");if(i.length>1)throw new Error("Geocoder can only be added to a single html element");e(this,i[0])}},onAdd:function(t){if(t&&"string"!=typeof t&&(this._map=t),this.setLanguage(),this.options.localGeocoderOnly&&!this.options.localGeocoder)throw new Error("A localGeocoder function must be specified to use localGeocoderOnly mode");this._onChange=this._onChange.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPaste=this._onPaste.bind(this),this._onBlur=this._onBlur.bind(this),this._showButton=this._showButton.bind(this),this._hideButton=this._hideButton.bind(this),this._onQueryResult=this._onQueryResult.bind(this),this.clear=this.clear.bind(this),this._updateProximity=this._updateProximity.bind(this),this._collapse=this._collapse.bind(this),this._unCollapse=this._unCollapse.bind(this),this._clear=this._clear.bind(this),this._clearOnBlur=this._clearOnBlur.bind(this);var e=this.container=document.createElement("div");e.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl";var i=this.createIcon("search",'');this._inputEl=document.createElement("input"),this._inputEl.type="text",this._inputEl.className="mapboxgl-ctrl-geocoder--input maplibregl-ctrl-geocoder--input",this.setPlaceholder(),this.options.collapsed&&(this._collapse(),this.container.addEventListener("mouseenter",this._unCollapse),this.container.addEventListener("mouseleave",this._collapse),this._inputEl.addEventListener("focus",this._unCollapse)),(this.options.collapsed||this.options.clearOnBlur)&&this._inputEl.addEventListener("blur",this._onBlur),this._inputEl.addEventListener("keydown",r(this._onKeyDown,this.options.debounceSearch)),this._inputEl.addEventListener("paste",this._onPaste),this._inputEl.addEventListener("change",this._onChange),this.container.addEventListener("mouseenter",this._showButton),this.container.addEventListener("mouseleave",this._hideButton);var n=document.createElement("div");n.classList.add("mapboxgl-ctrl-geocoder--pin-right","maplibregl-ctrl-geocoder--pin-right"),this._clearEl=document.createElement("button"),this._clearEl.setAttribute("aria-label","Clear"),this._clearEl.addEventListener("click",this.clear),this._clearEl.className="mapboxgl-ctrl-geocoder--button maplibregl-ctrl-geocoder--button";var o=this.createIcon("close",'');return this._clearEl.appendChild(o),this._loadingEl=this.createIcon("loading",''),n.appendChild(this._clearEl),n.appendChild(this._loadingEl),e.appendChild(i),e.appendChild(this._inputEl),e.appendChild(n),this._typeahead=new s(this._inputEl,[],{filter:!1,minLength:this.options.minLength,limit:this.options.limit,noInitialSelection:!0}),this.setRenderFunction(this.options.render),this._typeahead.getItemValue=this.options.getItemValue,this.mapMarker=null,this.resultMarkers=[],this._handleMarker=this._handleMarker.bind(this),this._handleResultMarkers=this._handleResultMarkers.bind(this),this._map&&(this.options.trackProximity&&(this._updateProximity(),this._map.on("moveend",this._updateProximity)),this._maplibregl=this.options.maplibregl,!this._maplibregl&&this.options.marker&&(console.error("No maplibregl detected in options. Map markers are disabled. Please set options.maplibregl."),this.options.marker=!1)),e},createIcon:function(t,e){var i=document.createElementNS("http://www.w3.org/2000/svg","svg");if(i.setAttribute("class","mapboxgl-ctrl-geocoder--icon mapboxgl-ctrl-geocoder--icon-"+t+" maplibregl-ctrl-geocoder--icon maplibregl-ctrl-geocoder--icon-"+t),i.setAttribute("viewBox","0 0 18 18"),i.setAttribute("xml:space","preserve"),i.setAttribute("width",18),i.setAttribute("height",18),"innerHTML"in i)i.innerHTML=e;else{var n=document.createElement("div");n.innerHTML=""+e.valueOf().toString()+"";var s=n.firstChild,r=s.firstChild;i.appendChild(r)}return i},onRemove:function(){return this.container.parentNode.removeChild(this.container),this.options.trackProximity&&this._map&&this._map.off("moveend",this._updateProximity),this._removeMarker(),this._map=null,this},_onPaste:function(t){var e=(t.clipboardData||window.clipboardData).getData("text");e.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(e)},_onKeyDown:function(t){if(27===t.keyCode&&this.options.clearAndBlurOnEsc)return this._clear(t),this._inputEl.blur();var e=t.target&&t.target.shadowRoot?t.target.shadowRoot.activeElement:t.target;if(!(e?e.value:""))return this.fresh=!0,9!==t.keyCode&&this.clear(t),this._clearEl.style.display="none";if(!t.metaKey&&-1===[9,27,37,39,38,40].indexOf(t.keyCode)){if(13===t.keyCode){if(this.options.showResultsWhileTyping)return void(null==this._typeahead.selected&&this.geocoderApi.getSuggestions?this._geocode(e.value,!0):null==this._typeahead.selected&&this.options.showResultMarkers&&this._fitBoundsForMarkers());this._typeahead.selected||this._geocode(e.value)}e.value.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(e.value)}},_showButton:function(){this._inputEl.value.length>0&&(this._clearEl.style.display="block")},_hideButton:function(){this._typeahead.selected&&(this._clearEl.style.display="none")},_onBlur:function(t){this.options.clearOnBlur&&this._clearOnBlur(t),this.options.collapsed&&this._collapse()},_onChange:function(){var t=this._typeahead.selected;if(t&&!t.geometry)t.placeId?this._geocode(t.placeId,!0,!0):this._geocode(t.text,!0);else if(t&&JSON.stringify(t)!==this.lastSelected){if(this._clearEl.style.display="none",this.options.flyTo){var e;if(this._removeResultMarkers(),t.properties&&a[t.properties.short_code])e=o({},this.options.flyTo),this._map&&this._map.fitBounds(a[t.properties.short_code].bbox,e);else if(t.bbox){var i=t.bbox;e=o({},this.options.flyTo),this._map&&this._map.fitBounds([[i[0],i[1]],[i[2],i[3]]],e)}else{var n={zoom:this.options.zoom};e=o({},n,this.options.flyTo),t.center?e.center=t.center:t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(e.center=t.geometry.coordinates),this._map&&this._map.flyTo(e)}}this.options.marker&&this._maplibregl&&this._handleMarker(t),this._inputEl.focus(),this._inputEl.scrollLeft=0,this._inputEl.setSelectionRange(0,0),this.lastSelected=JSON.stringify(t),this._typeahead.selected=null,this._eventEmitter.emit("result",{result:t})}},_getConfigForRequest:function(){var t=["bbox","limit","proximity","countries","types","language","reverseMode"],e=this;return t.reduce(function(t,i){return e.options[i]&&(["countries","types","language"].indexOf(i)>-1?t[i]=e.options[i].split(/[\s,]+/):t[i]=e.options[i],"proximity"===i&&e.options[i]&&"number"==typeof e.options[i].longitude&&"number"==typeof e.options[i].latitude&&(t[i]=[e.options[i].longitude,e.options[i].latitude])),t},{})},_geocode:function(t,e,i){this._loadingEl.style.display="block",this._eventEmitter.emit("loading",{query:t}),this.inputString=t;var n,s=null,r=this._getConfigForRequest();if(this.options.localGeocoderOnly)n=Promise.resolve();else if(this.options.reverseGeocode&&/(-?\d+\.?\d*)[, ]+(-?\d+\.?\d*)[ ]*$/.test(t)){var l=t.split(/[\s(,)?]+/).map(function(t){return parseFloat(t,10)}).reverse();r.types&&r.types[0],r=o(r,{query:l,limit:1}),"proximity"in r&&delete r.proximity,n=this.geocoderApi.reverseGeocode(r)}else r=o(r,{query:t}),n=this.geocoderApi.getSuggestions?e?this.geocoderApi.searchByPlaceId&&i?this.geocoderApi.searchByPlaceId(r):this.geocoderApi.forwardGeocode(r):this.geocoderApi.getSuggestions(r):this.geocoderApi.forwardGeocode(r);var a=[];this.options.localGeocoder&&((a=this.options.localGeocoder(t))||(a=[]));var h=[];return n.catch(function(t){s=t}.bind(this)).then(function(e){this._loadingEl.style.display="none";var i={};return i=e||{type:"FeatureCollection",features:[]},i.config=r,this.fresh&&(this.fresh=!1),i.features=i.features?a.concat(i.features):a,this.options.externalGeocoder?(h=this.options.externalGeocoder(t,i.features,r)||[],h.then(function(t){return i.features=i.features?t.concat(i.features):t,i},function(){return i})):i}.bind(this)).then(function(t){if(s)throw s;this.options.filter&&t.features.length&&(t.features=t.features.filter(this.options.filter));var i=[];i=t.suggestions?t.suggestions:t.place?[t.place]:t.features,i.length?(this._clearEl.style.display="block",this._typeahead.update(i),(!this.options.showResultsWhileTyping||e)&&this.options.showResultMarkers&&(t.features.length>0||t.place)&&this._fitBoundsForMarkers(),this._eventEmitter.emit("results",t)):(this._clearEl.style.display="none",this._typeahead.selected=null,this._renderNoResults(),this._eventEmitter.emit("results",t))}.bind(this)).catch(function(t){this._loadingEl.style.display="none",a.length&&this.options.localGeocoder||h.length&&this.options.externalGeocoder?(this._clearEl.style.display="block",this._typeahead.update(a)):(this._clearEl.style.display="none",this._typeahead.selected=null,this._renderError()),this._eventEmitter.emit("results",{features:a}),this._eventEmitter.emit("error",{error:t})}.bind(this)),n},_clear:function(t){t&&t.preventDefault(),this._inputEl.value="",this._typeahead.selected=null,this._typeahead.clear(),this._onChange(),this._clearEl.style.display="none",this._removeMarker(),this._removeResultMarkers(),this.lastSelected=null,this._eventEmitter.emit("clear"),this.fresh=!0},clear:function(t){this._clear(t),this._inputEl.focus()},_clearOnBlur:function(t){var e=this;t.relatedTarget&&e._clear(t)},_onQueryResult:function(t){var e=t;if(e.features.length){var i=e.features[0];this._typeahead.selected=i,this._inputEl.value=i.place_name,this._onChange()}},_updateProximity:function(){if(this._map)if(this._map.getZoom()>9){var t=this._map.getCenter().wrap();this.setProximity({longitude:t.lng,latitude:t.lat})}else this.setProximity(null)},_collapse:function(){this._inputEl.value||this._inputEl===document.activeElement||this.container.classList.add("mapboxgl-ctrl-geocoder--collapsed","maplibregl-ctrl-geocoder--collapsed")},_unCollapse:function(){this.container.classList.remove("mapboxgl-ctrl-geocoder--collapsed","maplibregl-ctrl-geocoder--collapsed")},query:function(t){return this._geocode(t).then(this._onQueryResult),this},_renderError:function(){this._renderMessage("
There was an error reaching the server
")},_renderNoResults:function(){this._renderMessage("
No results found
")},_renderMessage:function(t){this._typeahead.update([]),this._typeahead.selected=null,this._typeahead.clear(),this._typeahead.renderError(t)},_getPlaceholderText:function(){if(this.options.placeholder)return this.options.placeholder;if(this.options.language){var t=this.options.language.split(",")[0],e=u.language(t),i=h.placeholder[e];if(i)return i}return"Search"},_fitBoundsForMarkers:function(){if(!(this._typeahead.data.length<1)){var t=this._typeahead.data.filter(function(t){return"string"!=typeof t}).slice(0,this.options.limit);if(this._clearEl.style.display="none",this.options.flyTo&&this._maplibregl&&this._map){var e={padding:100},i=o({},e,this.options.flyTo),n=new this._maplibregl.LngLatBounds;t.forEach(function(t){n.extend(t.geometry.coordinates)}),this._map.fitBounds(n.toArray(),i)}return t.length>0&&this._maplibregl&&this._handleResultMarkers(t),this}},setInput:function(t){return this._inputEl.value=t,this._typeahead.selected=null,this._typeahead.clear(),t.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(t),this},setProximity:function(t){return this.options.proximity=t,this},getProximity:function(){return this.options.proximity},setRenderFunction:function(t){return t&&"function"==typeof t&&(this._typeahead.render=t),this},getRenderFunction:function(){return this._typeahead.render},setLanguage:function(t){var e=navigator.language||navigator.userLanguage||navigator.browserLanguage;return this.options.language=t||this.options.language||e,this},getLanguage:function(){return this.options.language},getZoom:function(){return this.options.zoom},setZoom:function(t){return this.options.zoom=t,this},getFlyTo:function(){return this.options.flyTo},setFlyTo:function(t){return this.options.flyTo=t,this},getPlaceholder:function(){return this.options.placeholder},setPlaceholder:function(t){return this.placeholder=t||this._getPlaceholderText(),this._inputEl.placeholder=this.placeholder,this._inputEl.setAttribute("aria-label",this.placeholder),this},getBbox:function(){return this.options.bbox},setBbox:function(t){return this.options.bbox=t,this},getCountries:function(){return this.options.countries},setCountries:function(t){return this.options.countries=t,this},getTypes:function(){return this.options.types},setTypes:function(t){return this.options.types=t,this},getMinLength:function(){return this.options.minLength},setMinLength:function(t){return this.options.minLength=t,this._typeahead&&(this._typeahead.options.minLength=t),this},getLimit:function(){return this.options.limit},setLimit:function(t){return this.options.limit=t,this._typeahead&&(this._typeahead.options.limit=t),this},getFilter:function(){return this.options.filter},setFilter:function(t){return this.options.filter=t,this},setGeocoderApi:function(t){return this.geocoderApi=t,this},getGeocoderApi:function(){return this.geocoderApi},_handleMarker:function(t){if(this._map){this._removeMarker();var e={color:"#4668F2"},i=o({},e,this.options.marker);this.mapMarker=new this._maplibregl.Marker(i);var n;if(this.options.popup){var s={},r=o({},s,this.options.popup);n=new this._maplibregl.Popup(r).setHTML(this.options.popupRender(t))}return t.center?(this.mapMarker.setLngLat(t.center).addTo(this._map),this.options.popup&&this.mapMarker.setPopup(n)):t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(this.mapMarker.setLngLat(t.geometry.coordinates).addTo(this._map),this.options.popup&&this.mapMarker.setPopup(n)),this}},_removeMarker:function(){this.mapMarker&&(this.mapMarker.remove(),this.mapMarker=null)},_handleResultMarkers:function(t){if(this._map){this._removeResultMarkers();var e={color:"#4668F2"},i=o({},e,this.options.showResultMarkers);return t.forEach(function(t){if(this.options.showResultMarkers&&this.options.showResultMarkers.element){var e=this.options.showResultMarkers.element.cloneNode(!0);i=o(i,{element:e})}var n,s=new this._maplibregl.Marker(o({},i,{element:e}));if(this.options.popup){var r={},l=o({},r,this.options.popup);n=new this._maplibregl.Popup(l).setHTML(this.options.popupRender(t))}t.center?(s.setLngLat(t.center).addTo(this._map),this.options.popup&&s.setPopup(n)):t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(s.setLngLat(t.geometry.coordinates).addTo(this._map),this.options.popup&&s.setPopup(n)),this.resultMarkers.push(s)}.bind(this)),this}},_removeResultMarkers:function(){this.resultMarkers&&this.resultMarkers.length>0&&(this.resultMarkers.forEach(function(t){t.remove()}),this.resultMarkers=[])},on:function(t,e){return this._eventEmitter.on(t,e),this},off:function(t,e){return this._eventEmitter.removeListener(t,e),this}},e.exports=n},{"./exceptions":1,"./localization":3,events:4,"lodash.debounce":6,subtag:7,"suggestions-list":8,xtend:11}],3:[function(t,e,i){"use strict";var n={de:"Suche",it:"Ricerca",en:"Search",nl:"Zoeken",fr:"Chercher",ca:"Cerca",he:"לחפש",ja:"サーチ",lv:"Meklēt",pt:"Procurar",sr:"Претрага",zh:"搜索",cs:"Vyhledávání",hu:"Keresés",ka:"ძიება",nb:"Søke",sk:"Vyhľadávanie",th:"ค้นหา",fi:"Hae",is:"Leita",ko:"수색",pl:"Szukaj",sl:"Iskanje",fa:"جستجو",ru:"Поиск"};e.exports={placeholder:n}},{}],4:[function(t,e,i){function n(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=w(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}function s(t){return void 0===t._maxListeners?n.defaultMaxListeners:t._maxListeners}function r(t,e,i){if(e)t.call(i);else for(var n=t.length,s=m(t,n),r=0;r0&&l.length>r){l.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+l.length+' "'+String(e)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=l.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",a.name,a.message)}}else l=o[e]=i,++t._eventsCount;return t}function c(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var t=new Array(arguments.length),e=0;e1&&(e=arguments[1]),e instanceof Error)throw e;var d=new Error('Unhandled "error" event. ('+e+")");throw d.context=e,d}if(!(i=c[t]))return!1;var f="function"==typeof i;switch(n=arguments.length){case 1:r(i,f,this);break;case 2:o(i,f,this,arguments[1]);break;case 3:l(i,f,this,arguments[1],arguments[2]);break;case 4:a(i,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(n-1),u=1;u=0;r--)if(i[r]===e||i[r].listener===e){o=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():g(i,s),1===i.length&&(n[t]=i[0]),n.removeListener&&this.emit("removeListener",t,o||e)}return this},n.prototype.removeAllListeners=function(t){var e,i,n;if(!(i=this._events))return this;if(!i.removeListener)return 0===arguments.length?(this._events=w(null),this._eventsCount=0):i[t]&&(0==--this._eventsCount?this._events=w(null):delete i[t]),this;if(0===arguments.length){var s,r=x(i);for(n=0;n=0;n--)this.removeListener(t,e[n]);return this},n.prototype.listeners=function(t){return d(this,t,!0)},n.prototype.rawListeners=function(t){return d(this,t,!1)},n.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):f.call(t,e)},n.prototype.listenerCount=f,n.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],5:[function(t,e,i){!function(){var t=this,n={};void 0!==i?e.exports=n:t.fuzzy=n,n.simpleFilter=function(t,e){return e.filter(function(e){return n.test(t,e)})},n.test=function(t,e){return null!==n.match(t,e)},n.match=function(t,e,i){i=i||{};var n,s=0,r=[],o=e.length,l=0,a=0,h=i.pre||"",u=i.post||"",c=i.caseSensitive&&e||e.toLowerCase();t=i.caseSensitive&&t||t.toLowerCase();for(var p=0;p=e||i<0||C&&n>=v}function u(){var t=x();if(h(t))return c(t);_=setTimeout(u,a(t))}function c(t){return _=void 0,M&&g?s(t):(g=m=void 0,y)}function p(){void 0!==_&&clearTimeout(_),L=0,g=E=m=_=void 0}function d(){return void 0===_?y:c(x())}function f(){var t=x(),i=h(t);if(g=arguments,m=this,E=t,i){if(void 0===_)return r(E);if(C)return _=setTimeout(u,e),s(E)}return void 0===_&&(_=setTimeout(u,e)),y}var g,m,v,y,_,E,L=0,k=!1,C=!1,M=!0;if("function"!=typeof t)throw new TypeError(l);return e=o(e)||0,n(i)&&(k=!!i.leading,C="maxWait"in i,v=C?b(o(i.maxWait)||0,e):v,M="trailing"in i?!!i.trailing:M),f.cancel=p,f.flush=d,f}function n(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function s(t){return!!t&&"object"==typeof t}function r(t){return"symbol"==typeof t||s(t)&&_.call(t)==h}function o(t){if("number"==typeof t)return t;if(r(t))return a;if(n(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=n(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(u,"");var i=p.test(t);return i||d.test(t)?f(t.slice(2),i?2:8):c.test(t)?a:+t}var l="Expected a function",a=NaN,h="[object Symbol]",u=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,d=/^0o[0-7]+$/i,f=parseInt,g="object"==typeof t&&t&&t.Object===Object&&t,m="object"==typeof self&&self&&self.Object===Object&&self,v=g||m||Function("return this")(),y=Object.prototype,_=y.toString,b=Math.max,w=Math.min,x=function(){return v.Date.now()};e.exports=i}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],7:[function(t,e,i){!function(t,i,n){void 0!==e&&e.exports?e.exports=n():t.subtag=n()}(this,0,function(){function t(t){return t.match(o)||[]}function e(e){return t(e).filter(function(t,e){return t&&e})}function i(e){return e=t(e),{language:e[1]||r,extlang:e[2]||r,script:e[3]||r,region:e[4]||r}}function n(t,e,i){Object.defineProperty(t,e,{value:i,enumerable:!0})}function s(e,s,o){function l(i){return t(i)[e]||r}n(l,"pattern",s),n(i,o,l)}var r="",o=/^([a-zA-Z]{2,3})(?:[_-]+([a-zA-Z]{3})(?=$|[_-]+))?(?:[_-]+([a-zA-Z]{4})(?=$|[_-]+))?(?:[_-]+([a-zA-Z]{2}|[0-9]{3})(?=$|[_-]+))?/;return s(1,/^[a-zA-Z]{2,3}$/,"language"),s(2,/^[a-zA-Z]{3}$/,"extlang"),s(3,/^[a-zA-Z]{4}$/,"script"),s(4,/^[a-zA-Z]{2}$|^[0-9]{3}$/,"region"),n(i,"split",e),i})},{}],8:[function(t,e,i){"use strict";var n=t("./src/suggestions");e.exports=n,"undefined"!=typeof window&&(window.Suggestions=n)},{"./src/suggestions":10}],9:[function(t,e,i){"use strict";var n=function(t){return this.component=t,this.items=[],this.active=t.options.noInitialSelection?-1:0,this.wrapper=document.createElement("div"),this.wrapper.className="suggestions-wrapper",this.element=document.createElement("ul"),this.element.className="suggestions",this.wrapper.appendChild(this.element),this.selectingListItem=!1,t.el.parentNode.insertBefore(this.wrapper,t.el.nextSibling),this};n.prototype.show=function(){this.element.style.display="block"},n.prototype.hide=function(){this.element.style.display="none"},n.prototype.add=function(t){this.items.push(t)},n.prototype.clear=function(){this.items=[],this.active=this.component.options.noInitialSelection?-1:0},n.prototype.isEmpty=function(){return!this.items.length},n.prototype.isVisible=function(){return"block"===this.element.style.display},n.prototype.draw=function(){if(this.element.innerHTML="", +0===this.items.length)return void this.hide();for(var t=0;t=this.items.length-1?0:this.active+1)},n.prototype.drawError=function(t){var e=document.createElement("li");e.innerHTML=t,this.element.appendChild(e),this.show()},e.exports=n},{}],10:[function(t,e,i){"use strict";var n=t("xtend"),s=t("fuzzy"),r=t("./list"),o=function(t,e,i){return i=i||{},this.options=n({minLength:2,limit:5,filter:!0,hideOnBlur:!0,noInitialSelection:!0},i),this.el=t,this.data=e||[],this.list=new r(this),this.query="",this.selected=null,this.list.draw(),this.el.addEventListener("keyup",function(t){this.handleKeyUp(t.keyCode,t)}.bind(this),!1),this.el.addEventListener("keydown",function(t){this.handleKeyDown(t)}.bind(this)),this.el.addEventListener("focus",function(){this.handleFocus()}.bind(this)),this.el.addEventListener("blur",function(){this.handleBlur()}.bind(this)),this.el.addEventListener("paste",function(t){this.handlePaste(t)}.bind(this)),this.render=this.options.render?this.options.render.bind(this):this.render.bind(this),this.getItemValue=this.options.getItemValue?this.options.getItemValue.bind(this):this.getItemValue.bind(this),this};o.prototype.handleKeyUp=function(t,e){if(40!==t&&38!==t&&27!==t&&9!==t)return 13===t?void(this.list.items[this.list.active]&&(this.list.handleMouseUp(this.list.items[this.list.active]),e.stopPropagation())):void this.handleInputChange(this.el.value)},o.prototype.handleKeyDown=function(t){switch(t.keyCode){case 13:this.list.active>=0&&(this.list.selectingListItem=!0);break;case 9:this.list.isEmpty()||(this.list.isVisible()&&t.preventDefault(),this.value(this.list.active>=0?this.list.items[this.list.active].original:null),this.list.hide());break;case 27:this.list.isEmpty()||this.list.hide();break;case 38:this.list.previous();break;case 40:this.list.next()}},o.prototype.handleBlur=function(){!this.list.selectingListItem&&this.options.hideOnBlur&&this.list.hide()},o.prototype.handlePaste=function(t){if(t.clipboardData)this.handleInputChange(t.clipboardData.getData("Text"));else{var e=this;setTimeout(function(){e.handleInputChange(t.target.value)},100)}},o.prototype.handleInputChange=function(t){if(this.query=this.normalize(t),this.list.clear(),this.query.length-1},o.prototype.value=function(t){if(this.selected=t,this.el.value=this.getItemValue(t||{place_name:this.query}),document.createEvent){var e=document.createEvent("HTMLEvents");e.initEvent("change",!0,!1),this.el.dispatchEvent(e)}else this.el.fireEvent("onchange")},o.prototype.getCandidates=function(t){var e,i={pre:"",post:"",extract:function(t){return this.getItemValue(t)}.bind(this)};this.options.filter?(e=s.filter(this.query,this.data,i),e=e.map(function(t){return{original:t.original,string:this.render(t.original,t.string)}}.bind(this))):e=this.data.map(function(t){return{original:t,string:this.render(t)}}.bind(this)),t(e)},o.prototype.getItemValue=function(t){return t},o.prototype.render=function(t,e){if(e)return e;for(var i=t.original?this.getItemValue(t.original):this.getItemValue(t),n=this.normalize(i),s=n.lastIndexOf(this.query);s>-1;){var r=s+this.query.length;i=i.slice(0,s)+""+i.slice(s,r)+""+i.slice(r),s=n.slice(0,s).lastIndexOf(this.query)}return i},o.prototype.renderError=function(t){this.list.drawError(t)},e.exports=o},{"./list":9,fuzzy:5,xtend:11}],11:[function(t,e,i){function n(){for(var t={},e=0;e.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:hsla(0,0%,100%,.5);background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:rgba(0,0,0,.05)}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:hsla(0,0%,100%,.75);border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:rgba(0,0,0,.05)}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px rgba(0,0,0,.35);box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:rgba(0,0,0,.4);color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media (hover:none),(pointer:coarse){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999} \ No newline at end of file diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js new file mode 100644 index 0000000..53dd1e0 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js @@ -0,0 +1,59 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v5.7.2/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory()); +})(this, (function () { 'use strict'; + +/* eslint-disable */ + +var maplibregl = {}; +var modules = {}; +function define(moduleName, _dependencies, moduleFactory) { + modules[moduleName] = moduleFactory; + + // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) + if (moduleName !== 'index') { + return; + } + + // we assume that when an index module is initializing then other modules are loaded already + var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);' + + var sharedModule = {}; + // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) + // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) + // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following + modules.shared(sharedModule); + modules.index(maplibregl, sharedModule); + + if (typeof window !== 'undefined') { + maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); + } + + return maplibregl; +}; + + + +define("shared",["exports"],(function(t){"use strict";function e(t,e,r,n){return new(r||(r=Promise))((function(i,s){function a(t){try{l(n.next(t));}catch(t){s(t);}}function o(t){try{l(n.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(a,o);}l((n=n.apply(t,e||[])).next());}))}function r(t,e){this.x=t,this.y=e;}function n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,s;"function"==typeof SuppressedError&&SuppressedError,r.prototype={clone(){return new r(this.x,this.y)},add(t){return this.clone()._add(t)},sub(t){return this.clone()._sub(t)},multByPoint(t){return this.clone()._multByPoint(t)},divByPoint(t){return this.clone()._divByPoint(t)},mult(t){return this.clone()._mult(t)},div(t){return this.clone()._div(t)},rotate(t){return this.clone()._rotate(t)},rotateAround(t,e){return this.clone()._rotateAround(t,e)},matMult(t){return this.clone()._matMult(t)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(t){return this.x===t.x&&this.y===t.y},dist(t){return Math.sqrt(this.distSqr(t))},distSqr(t){const e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle(){return Math.atan2(this.y,this.x)},angleTo(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith(t){return this.angleWithSep(t.x,t.y)},angleWithSep(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult(t){const e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add(t){return this.x+=t.x,this.y+=t.y,this},_sub(t){return this.x-=t.x,this.y-=t.y,this},_mult(t){return this.x*=t,this.y*=t,this},_div(t){return this.x/=t,this.y/=t,this},_multByPoint(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint(t){return this.x/=t.x,this.y/=t.y,this},_unit(){return this._div(this.mag()),this},_perp(){const t=this.y;return this.y=this.x,this.x=-t,this},_rotate(t){const e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround(t,e){const r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:r},r.convert=function(t){if(t instanceof r)return t;if(Array.isArray(t))return new r(+t[0],+t[1]);if(void 0!==t.x&&void 0!==t.y)return new r(+t.x,+t.y);throw new Error("Expected [x, y] or {x, y} point format")};var a=function(){if(s)return i;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return s=1,i=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},i}(),o=n(a);let l,u;function c(){return null==l&&(l="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),l}function h(){if(null==u&&(u=!1,c())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:!0});if(e){for(let r=0;r4&&void 0!==arguments[4]?arguments[4]:"zyx",s=Math.PI/360;e*=s,n*=s,r*=s;var a=Math.sin(e),o=Math.cos(e),l=Math.sin(r),u=Math.cos(r),c=Math.sin(n),h=Math.cos(n);switch(i){case "xyz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "xzy":t[0]=a*u*h-o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h+a*l*c;break;case "yxz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;case "yzx":t[0]=a*u*h+o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h-a*l*c;break;case "zxy":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "zyx":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;default:throw new Error("Unknown angle order "+i)}return t}function I(){var t=new f(2);return f!=Float32Array&&(t[0]=0,t[1]=0),t}function z(t,e){var r=new f(2);return r[0]=t,r[1]=e,r}m(),_=new f(4),f!=Float32Array&&(_[0]=0,_[1]=0,_[2]=0,_[3]=0),m(),x(1,0,0),x(0,1,0),k(),k(),d(),I();const P=8192;function C(t,e,r){return e*(P/(t.tileSize*Math.pow(2,r-t.tileID.overscaledZ)))}function E(t,e){return (t%e+e)%e}function T(t,e,r){return t*(1-r)+e*r}function B(t){if(t<=0)return 0;if(t>=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function V(t,e,r,n){const i=new o(t,e,r,n);return t=>i.solve(t)}const F=V(.25,.1,.25,1);function $(t,e,r){return Math.min(r,Math.max(e,t))}function D(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function L(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let O=1;function R(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function U(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}function j(t){return Array.isArray(t)?t.map(j):"object"==typeof t&&t?R(t,j):t}const N={};function q(t){N[t]||("undefined"!=typeof console&&console.warn(t),N[t]=!0);}function G(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function X(t){return "undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}let Z=null;function Y(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const H="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function K(t,r,n,i,s){return e(this,void 0,void 0,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const e=new VideoFrame(t,{timestamp:0});try{const a=null==e?void 0:e.format;if(!a||!a.startsWith("BGR")&&!a.startsWith("RGB"))throw new Error(`Unrecognized format ${a}`);const o=a.startsWith("BGR"),l=new Uint8ClampedArray(i*s*4);if(yield e.copyTo(l,function(t,e,r,n,i){const s=4*Math.max(-e,0),a=(Math.max(0,r)-r)*n*4+s,o=4*n,l=Math.max(0,e),u=Math.max(0,r);return {rect:{x:l,y:u,width:Math.min(t.width,e+n)-l,height:Math.min(t.height,r+i)-u},layout:[{offset:a,stride:o}]}}(t,r,n,i,s)),o)for(let t=0;t{t.removeEventListener(e,r,n);}}}function tt(t){return t*Math.PI/180}function et(t){return t/Math.PI*180}const rt={touchstart:!0,touchmove:!0,touchmoveWindow:!0,touchend:!0,touchcancel:!0},nt={dblclick:!0,click:!0,mouseover:!0,mouseout:!0,mousedown:!0,mousemove:!0,mousemoveWindow:!0,mouseup:!0,mouseupWindow:!0,contextmenu:!0,wheel:!0},it="AbortError";function st(){return new Error(it)}const at={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function ot(t){return at.REGISTERED_PROTOCOLS[t.substring(0,t.indexOf("://"))]}const lt="global-dispatcher";class ut extends Error{constructor(t,e,r,n){super(`AJAXError: ${e} (${t}): ${r}`),this.status=t,this.statusText=e,this.url=r,this.body=n;}}const ct=()=>X(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,ht=function(t,r){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const e=ot(t.url);if(e)return e(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:lt},r)}if(!(/^file:/.test(n=t.url)||/^file:/.test(ct())&&!/^\w+:/.test(n))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,r){return e(this,void 0,void 0,(function*(){const e=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:ct(),signal:r.signal});let n,i;"json"!==t.type||e.headers.has("Accept")||e.headers.set("Accept","application/json");try{n=yield fetch(e);}catch(e){throw new ut(0,e.message,t.url,new Blob)}if(!n.ok){const e=yield n.blob();throw new ut(n.status,n.statusText,t.url,e)}i="arrayBuffer"===t.type||"image"===t.type?n.arrayBuffer():"json"===t.type?n.json():n.text();const s=yield i;if(r.signal.aborted)throw st();return {data:s,cacheControl:n.headers.get("Cache-Control"),expires:n.headers.get("Expires")}}))}(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:!0,targetMapId:lt},r)}var n;return function(t,e){return new Promise(((r,n)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,!0),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||void 0===i?void 0:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{n(new Error(s.statusText));},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response);}catch(t){return void n(t)}r({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires")});}else {const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});n(new ut(s.status,s.statusText,t.url,e));}},e.signal.addEventListener("abort",(()=>{s.abort(),n(st());})),s.send(t.body);}))}(t,r)};function pt(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return !0;const e=new URL(t),r=window.location;return e.protocol===r.protocol&&e.host===r.host}function ft(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function dt(t,e,r){if(r&&r[t]){const n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}class yt{constructor(t,e={}){L(this,e),this.type=t;}}class mt extends yt{constructor(t,e={}){super("error",L({error:t},e));}}class gt{on(t,e){return this._listeners=this._listeners||{},ft(t,e,this._listeners),{unsubscribe:()=>{this.off(t,e);}}}off(t,e){return dt(t,e,this._listeners),dt(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},ft(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new yt(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)dt(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(L(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof mt&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var xt={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},state:{type:"state",default:{}},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},"font-faces":{type:"array",value:"fontFaces"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},"color-relief":{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_color-relief","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const vt=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function bt(t,e){const r={};for(const e in t)"ref"!==e&&(r[e]=t[e]);return vt.forEach((t=>{t in e&&(r[t]=e[t]);})),r}function wt(t,e){if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return !1;for(let r=0;r`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const Jt=[Vt,Ft,$t,Dt,Lt,Ot,Nt,Rt,Ht(Ut),qt,Xt,Gt,Zt,Yt];function Wt(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Wt(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of Jt)if(!Wt(t,e))return null}return `Expected ${Kt(t)} but found ${Kt(e)} instead.`}function Qt(t,e){return e.some((e=>e.kind===t.kind))}function te(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function ee(t,e){return "array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const re=.96422,ne=.82521,ie=4/29,se=6/29,ae=3*se*se,oe=se*se*se,le=Math.PI/180,ue=180/Math.PI;function ce(t){return (t%=360)<0&&(t+=360),t}function he([t,e,r,n]){let i,s;const a=fe((.2225045*(t=pe(t))+.7168786*(e=pe(e))+.0606169*(r=pe(r)))/1);t===e&&e===r?i=s=a:(i=fe((.4360747*t+.3850649*e+.1430804*r)/re),s=fe((.0139322*t+.0971045*e+.7141733*r)/ne));const o=116*a-16;return [o<0?0:o,500*(i-a),200*(a-s),n]}function pe(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function fe(t){return t>oe?Math.pow(t,1/3):t/ae+ie}function de([t,e,r,n]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,a=isNaN(r)?i:i-r/200;return i=1*me(i),s=re*me(s),a=ne*me(a),[ye(3.1338561*s-1.6168667*i-.4906146*a),ye(-.9787684*s+1.9161415*i+.033454*a),ye(.0719453*s-.2289914*i+1.4052427*a),n]}function ye(t){return (t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function me(t){return t>se?t*t*t:ae*(t-ie)}const ge=Object.hasOwn||function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};function xe(t,e){return ge(t,e)?t[e]:void 0}function ve(t){return parseInt(t.padEnd(2,t),16)/255}function be(t,e){return we(e?t/100:t,0,1)}function we(t,e,r){return Math.min(Math.max(e,t),r)}function _e(t){return !t.some(Number.isNaN)}const Se={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function Ae(t,e,r){return t+r*(e-t)}function ke(t,e,r){return t.map(((t,n)=>Ae(t,e[n],r)))}class Me{constructor(t,e,r,n=1,i=!0){this.r=t,this.g=e,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[t,e,r,n]));}static parse(t){if(t instanceof Me)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return [0,0,0,0];const e=xe(Se,t);if(e){const[t,r,n]=e;return [t/255,r/255,n/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let r=1;return [ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,r,n,i,s,a,o,l,u,c,h,p]=e,f=[i||" ",o||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[n,a,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[we(+r/e,0,1),we(+s/e,0,1),we(+l/e,0,1),h?be(+h,p):1];if(_e(t))return t}}return}}const r=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[t,e,n,i,s,a,o,l,u]=r,c=[n||" ",s||" ",o].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,we(+i,0,100),we(+a,0,100),l?be(+l,u):1];if(_e(t))return function([t,e,r,n]){function i(n){const i=(n+t/30)%12,s=e*Math.min(r,1-r);return r-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=ce(t),e/=100,r/=100,[i(0),i(8),i(4),n]}(t)}}}(t);return e?new Me(...e,!1):void 0}get rgb(){const{r:t,g:e,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[t/i,e/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,r,n,i]=he(t),s=Math.sqrt(r*r+n*n);return [Math.round(1e4*s)?ce(Math.atan2(n,r)*ue):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",he(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,r,n]=this.rgb;return `rgba(${[t,e,r].map((t=>Math.round(255*t))).join(",")},${n})`}static interpolate(t,e,r,n="rgb"){switch(n){case "rgb":{const[n,i,s,a]=ke(t.rgb,e.rgb,r);return new Me(n,i,s,a,!1)}case "hcl":{const[n,i,s,a]=t.hcl,[o,l,u,c]=e.hcl;let h,p;if(isNaN(n)||isNaN(o))isNaN(n)?isNaN(o)?h=NaN:(h=o,1!==s&&0!==s||(p=l)):(h=n,1!==u&&0!==u||(p=i));else {let t=o-n;o>n&&t>180?t-=360:o180&&(t+=360),h=n+r*t;}const[f,d,y,m]=function([t,e,r,n]){return t=isNaN(t)?0:t*le,de([r,Math.cos(t)*e,Math.sin(t)*e,n])}([h,null!=p?p:Ae(i,l,r),Ae(s,u,r),Ae(a,c,r)]);return new Me(f,d,y,m,!1)}case "lab":{const[n,i,s,a]=de(ke(t.lab,e.lab,r));return new Me(n,i,s,a,!1)}}}}Me.black=new Me(0,0,0,1),Me.white=new Me(1,1,1,1),Me.transparent=new Me(0,0,0,0),Me.red=new Me(1,0,0,1);class Ie{constructor(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const ze=["bottom","center","top"];class Pe{constructor(t,e,r,n,i,s){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i,this.verticalAlign=s;}}class Ce{constructor(t){this.sections=t;}static fromString(t){return new Ce([new Pe(t,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof Ce?t:Ce.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class Ee{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Ee)return t;if("number"==typeof t)return new Ee([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]];}return new Ee(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Ee(ke(t.values,e.values,r))}}class Te{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Te)return t;if("number"==typeof t)return new Te([t]);if(Array.isArray(t)){for(const e of t)if("number"!=typeof e)return;return new Te(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Te(ke(t.values,e.values,r))}}class Be{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Be)return t;if("string"==typeof t){const e=Me.parse(t);if(!e)return;return new Be([e])}if(!Array.isArray(t))return;const e=[];for(const r of t){if("string"!=typeof r)return;const t=Me.parse(r);if(!t)return;e.push(t);}return new Be(e)}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r,n="rgb"){const i=[];if(t.values.length!=e.values.length)throw new Error(`colorArray: Arrays have mismatched length (${t.values.length} vs. ${e.values.length}), cannot interpolate.`);for(let s=0;s=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Re(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof Le||t instanceof Me||t instanceof Ie||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De)return !0;if(Array.isArray(t)){for(const e of t)if(!Re(e))return !1;return !0}if("object"==typeof t){for(const e in t)if(!Re(t[e]))return !1;return !0}return !1}function Ue(t){if(null===t)return Vt;if("string"==typeof t)return $t;if("boolean"==typeof t)return Dt;if("number"==typeof t)return Ft;if(t instanceof Me)return Lt;if(t instanceof Le)return Ot;if(t instanceof Ie)return jt;if(t instanceof Ce)return Nt;if(t instanceof Ee)return qt;if(t instanceof Te)return Xt;if(t instanceof Be)return Gt;if(t instanceof $e)return Yt;if(t instanceof De)return Zt;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=Ue(e);if(r){if(r===t)continue;r=Ut;break}r=t;}return Ht(r||Ut,e)}return Rt}function je(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof Me||t instanceof Le||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De?t.toString():JSON.stringify(t)}class Ne{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Re(t[1]))return e.error("invalid value");const r=t[1];let n=Ue(r);const i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new Ne(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return !0}}const qe={string:$t,number:Ft,boolean:Dt,object:Rt};class Ge{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r,n=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const r=t[1];if("string"!=typeof r||!(r in qe)||"object"===r)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=qe[r],n++;}else i=Ut;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],n++;}r=Ht(i,s);}else {if(!qe[i])throw new Error(`Types doesn't contain name = ${i}`);r=qe[i];}const s=[];for(;nt.outputDefined()))}}const Xe={"to-boolean":Dt,"to-color":Lt,"to-number":Ft,"to-string":$t};class Ze{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[0];if(!Xe[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");const n=Xe[r],i=[];for(let r=1;r4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:Oe(e[0],e[1],e[2],e[3]),!r))return new Me(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new Ve(r||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "padding":{let e;for(const r of this.args){e=r.evaluate(t);const n=Ee.parse(e);if(n)return n}throw new Ve(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "numberArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Te.parse(e);if(n)return n}throw new Ve(`Could not parse numberArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "colorArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Be.parse(e);if(n)return n}throw new Ve(`Could not parse colorArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "variableAnchorOffsetCollection":{let e;for(const r of this.args){e=r.evaluate(t);const n=$e.parse(e);if(n)return n}throw new Ve(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "number":{let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new Ve(`Could not convert ${JSON.stringify(e)} to number.`)}case "formatted":return Ce.fromString(je(this.args[0].evaluate(t)));case "resolvedImage":return De.fromString(je(this.args[0].evaluate(t)));case "projectionDefinition":return this.args[0].evaluate(t);default:return je(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}const Ye=["Unknown","Point","LineString","Polygon"];class He{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null;}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?Ye[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache.get(t);return e||(e=Me.parse(t),this._parseColorCache.set(t,e)),e}}class Ke{constructor(t,e,r=[],n,i=new Bt,s=[]){this.registry=t,this.path=r,this.key=r.map((t=>`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=n,this._isConstant=e;}parse(t,e,r,n,i={}){return e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return "assert"===r?new Ge(e,[t]):"coerce"===r?new Ze(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const n=t[0];if("string"!=typeof n)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[n];if(i){let n=i.parse(t,this);if(!n)return null;if(this.expectedType){const t=this.expectedType,i=n.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind){if("projectionDefinition"===t.kind&&["string","array"].includes(i.kind)||["color","formatted","resolvedImage"].includes(t.kind)&&["value","string"].includes(i.kind)||["padding","numberArray"].includes(t.kind)&&["value","number","array"].includes(i.kind)||"colorArray"===t.kind&&["value","string","array"].includes(i.kind)||"variableAnchorOffsetCollection"===t.kind&&["value","array"].includes(i.kind))n=r(n,t,e.typeAnnotation||"coerce");else if(this.checkSubtype(t,i))return null}else n=r(n,t,e.typeAnnotation||"assert");}if(!(n instanceof Ne)&&"resolvedImage"!==n.type.kind&&this._isConstant(n)){const t=new He;try{n=new Ne(n.type,n.evaluate(t));}catch(t){return this.error(t.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Ke(this.registry,this._isConstant,n,e||null,i,this.errors)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new Tt(r,t));}checkSubtype(t,e){const r=Wt(t,e);return r&&this.error(r),r}}class Je{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new Ve(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new Ve(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return !1}}class tr{constructor(t,e){this.type=Dt,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);return r&&n?Qt(r.type,[Dt,$t,Ft,Vt,Ut])?new tr(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);if(!te(r,["string","array"]))throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return !0}}class er{constructor(t,e,r){this.type=Ft,this.needle=t,this.haystack=e,this.fromIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);if(!r||!n)return null;if(!Qt(r.type,[Dt,$t,Ft,Vt,Ut]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new er(r,n,i):null}return new er(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(t)),te(r,["string"])){const t=r.indexOf(e,n);return -1===t?-1:[...r.slice(0,t)].length}if(te(r,["array"]))return r.indexOf(e,n);throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return !1}}class rr{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(r){if(u.checkSubtype(r,Ue(t)))return null}else r=Ue(t);if(void 0!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length;}const c=e.parse(l,a,n);if(!c)return null;n=n||c.type,s.push(c);}const a=e.parse(t[1],1,Ut);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,n);return o?"value"!==a.type.kind&&e.concat(1).checkSubtype(r,a.type)?null:new rr(r,n,a,i,s,o):null}evaluate(t){const e=this.input.evaluate(t);return (Ue(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class nr{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class ir{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ft);if(!r||!n)return null;if(!Qt(r.type,[Ht(Ut),$t,Ut]))return e.error(`Expected first argument to be of type array or string, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new ir(r.type,r,n,i):null}return new ir(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);let n;if(this.endIndex&&(n=this.endIndex.evaluate(t)),te(e,["string"]))return [...e].slice(r,n).join("");if(te(e,["array"]))return e.slice(r,n);throw new Ve(`Expected first argument to be of type array or string, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return !1}}function sr(t,e){const r=t.length-1;let n,i,s=0,a=r,o=0;for(;s<=a;)if(o=Math.floor((s+a)/2),n=t[o],i=t[o+1],n<=e){if(o===r||ee))throw new Ve("Input is not a number.");a=o-1;}return 0}class ar{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',o);const u=e.parse(a,l,i);if(!u)return null;i=i||u.type,n.push([s,u]);}return new ar(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[sr(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function or(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var lr,ur,cr=function(){if(ur)return lr;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return ur=1,lr=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},lr}(),hr=or(cr);class pr{constructor(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e);}static interpolationFactor(t,e,r,n){let i=0;if("exponential"===t.name)i=fr(e,t.base,r,n);else if("linear"===t.name)i=fr(e,1,r,n);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new hr(s[0],s[1],s[2],s[3]).solve(fr(e,1,r,n));}return i}static parse(t,e){let[r,n,i,...s]=t;if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){const t=n[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:t};}else {if("cubic-bezier"!==n[0])return e.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const t=n.slice(1);if(4!==t.length||t.some((t=>"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,Ft),!i)return null;const a=[];let o=null;"interpolate-hcl"!==r&&"interpolate-lab"!==r||e.expectedType==Gt?e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType):o=Lt;for(let t=0;t=r)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,o);if(!u)return null;o=o||u.type,a.push([r,u]);}return ee(o,Ft)||ee(o,Ot)||ee(o,Lt)||ee(o,qt)||ee(o,Xt)||ee(o,Gt)||ee(o,Yt)||ee(o,Ht(Ft))?new pr(o,r,n,i,a):e.error(`Type ${Kt(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=sr(e,n),a=pr.interpolationFactor(this.interpolation,n,e[s],e[s+1]),o=r[s].evaluate(t),l=r[s+1].evaluate(t);switch(this.operator){case "interpolate":switch(this.type.kind){case "number":return Ae(o,l,a);case "color":return Me.interpolate(o,l,a);case "padding":return Ee.interpolate(o,l,a);case "colorArray":return Be.interpolate(o,l,a);case "numberArray":return Te.interpolate(o,l,a);case "variableAnchorOffsetCollection":return $e.interpolate(o,l,a);case "array":return ke(o,l,a);case "projectionDefinition":return Le.interpolate(o,l,a)}case "interpolate-hcl":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"hcl");case "colorArray":return Be.interpolate(o,l,a,"hcl")}case "interpolate-lab":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"lab");case "colorArray":return Be.interpolate(o,l,a,"lab")}}}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function fr(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}const dr={color:Me.interpolate,number:Ae,padding:Ee.interpolate,numberArray:Te.interpolate,colorArray:Be.interpolate,variableAnchorOffsetCollection:$e.interpolate,array:ke};class yr{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r=null;const n=e.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const n of t.slice(1)){const t=e.parse(n,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!t)return null;r=r||t.type,i.push(t);}if(!r)throw new Error("No output type");const s=n&&i.some((t=>Wt(n,t.type)));return new yr(s?Ut:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(t),r&&r instanceof De&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break;return r}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function mr(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function gr(t,e,r,n){return 0===n.compare(e,r)}function xr(t,e,r){const n="=="!==t&&"!="!==t;return class i{constructor(t,e,r){this.type=Dt,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const r=t[0];let s=e.parse(t[1],1,Ut);if(!s)return null;if(!mr(r,s.type))return e.concat(1).error(`"${r}" comparisons are not supported for type '${Kt(s.type)}'.`);let a=e.parse(t[2],2,Ut);if(!a)return null;if(!mr(r,a.type))return e.concat(2).error(`"${r}" comparisons are not supported for type '${Kt(a.type)}'.`);if(s.type.kind!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error(`Cannot compare types '${Kt(s.type)}' and '${Kt(a.type)}'.`);n&&("value"===s.type.kind&&"value"!==a.type.kind?s=new Ge(a.type,[s]):"value"!==s.type.kind&&"value"===a.type.kind&&(a=new Ge(s.type,[a])));let o=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error("Cannot use collator to compare non-string types.");if(o=e.parse(t[3],3,jt),!o)return null}return new i(s,a,o)}evaluate(i){const s=this.lhs.evaluate(i),a=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=Ue(s),r=Ue(a);if(e.kind!==r.kind||"string"!==e.kind&&"number"!==e.kind)throw new Ve(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=Ue(s),r=Ue(a);if("string"!==t.kind||"string"!==r.kind)return e(i,s,a)}return this.collator?r(i,s,a,this.collator.evaluate(i)):e(i,s,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return !0}}}const vr=xr("==",(function(t,e,r){return e===r}),gr),br=xr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !gr(0,e,r,n)})),wr=xr("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),Sr=xr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),Ar=xr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class kr{constructor(t,e,r){this.type=jt,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");const n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,Dt);if(!n)return null;const i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Dt);if(!i)return null;let s=null;return r.locale&&(s=e.parse(r.locale,1,$t),!s)?null:new kr(n,i,s)}evaluate(t){return new Ie(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);}outputDefined(){return !1}}class Mr{constructor(t,e,r,n,i){this.type=$t,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=e.parse(n.locale,1,$t),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,$t),!s))return null;let a=null;if(n["min-fraction-digits"]&&(a=e.parse(n["min-fraction-digits"],1,Ft),!a))return null;let o=null;return n["max-fraction-digits"]&&(o=e.parse(n["max-fraction-digits"],1,Ft),!o)?null:new Mr(r,i,s,a,o)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return !1}}class Ir{constructor(t){this.type=Nt,this.sections=t;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");const n=[];let i=!1;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&"object"==typeof s&&!Array.isArray(s)){i=!1;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,Ft),!t))return null;let r=null;if(s["text-font"]&&(r=e.parse(s["text-font"],1,Ht($t)),!r))return null;let a=null;if(s["text-color"]&&(a=e.parse(s["text-color"],1,Lt),!a))return null;let o=null;if(s["vertical-align"]){if("string"==typeof s["vertical-align"]&&!ze.includes(s["vertical-align"]))return e.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${s["vertical-align"]}' instead.`);if(o=e.parse(s["vertical-align"],1,$t),!o)return null}const l=n[n.length-1];l.scale=t,l.font=r,l.textColor=a,l.verticalAlign=o;}else {const s=e.parse(t[r],1,Ut);if(!s)return null;const a=s.type.kind;if("string"!==a&&"value"!==a&&"null"!==a&&"resolvedImage"!==a)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:s,scale:null,font:null,textColor:null,verticalAlign:null});}}return new Ir(n)}evaluate(t){return new Ce(this.sections.map((e=>{const r=e.content.evaluate(t);return Ue(r)===Zt?new Pe("",r,null,null,null,e.verticalAlign?e.verticalAlign.evaluate(t):null):new Pe(je(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null,e.verticalAlign?e.verticalAlign.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor),e.verticalAlign&&t(e.verticalAlign);}outputDefined(){return !1}}class zr{constructor(t){this.type=Zt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,$t);return r?new zr(r):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),r=De.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r}eachChild(t){t(this.input);}outputDefined(){return !1}}class Pr{constructor(t){this.type=Ft,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${Kt(r.type)} instead.`):new Pr(r):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return [...e].length;if(Array.isArray(e))return e.length;throw new Ve(`Expected value to be of type string or array, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return !1}}const Cr=8192;function Er(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*Cr),Math.round(n*i*Cr)]}function Tr(t,e){const r=Math.pow(2,e.z);return [(i=(t[0]/Cr+e.x)/r,360*i-180),(n=(t[1]/Cr+e.y)/r,360/Math.PI*Math.atan(Math.exp((180-360*n)*Math.PI/180))-90)];var n,i;}function Br(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function Vr(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function Fr(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],a=t[1]-r[1];return n*a-s*i==0&&n*s<=0&&i*a<=0}function $r(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!jr(t,e,r,n)||!jr(r,n,t,e));var i,s;}function Dr(t,e,r){for(const n of r)for(let r=0;r(i=t)[1]!=(a=o[e+1])[1]>i[1]&&i[0]<(a[0]-s[0])*(i[1]-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}var i,s,a;return n}function Or(t,e){for(const r of e)if(Lr(t,r))return !0;return !1}function Rr(t,e){for(const r of t)if(!Lr(r,e))return !1;for(let r=0;r0&&o<0||a<0&&o>0}function Nr(t,e,r){const n=[];for(let i=0;ir[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i;}Br(e,t);}function Xr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];Gr(n,e,r,i),a.push(n);}return a}function Zr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];Br(e,r),t.push(r);}a.push(t);}if(e[2]-e[0]<=i/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const n of t)Gr(n,e,r,i);}var o;return a}class Yr{constructor(t,e){this.type=Dt,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const r of e.features){const{type:e,coordinates:n}=r.geometry;"Polygon"===e&&t.push(n),"MultiPolygon"===e&&t.push(...n);}if(t.length)return new Yr(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new Yr(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new Yr(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Lr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Or(t,s))return !1}return !0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Rr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Ur(t,s))return !1}return !0}(t,this.geometries)}return !1}eachChild(){}outputDefined(){return !0}}let Hr=class{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}};function Kr(t,e,r=0,n=t.length-1,i=Wr){for(;n>r;){if(n-r>600){const s=n-r+1,a=e-r+1,o=Math.log(s),l=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*l*(s-l)/s)*(a-s/2<0?-1:1);Kr(t,e,Math.max(r,Math.floor(e-a*l/s+u)),Math.min(n,Math.floor(e+(s-a)*l/s+u)),i);}const s=t[e];let a=r,o=n;for(Jr(t,r,e),i(t[n],s)>0&&Jr(t,r,n);a0;)o--;}0===i(t[r],s)?Jr(t,r,o):(o++,Jr(t,o,n)),o<=e&&(r=o+1),e<=o&&(n=o-1);}}function Jr(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function Wr(t,e){return te?1:0}function Qr(t,e){if(t.length<=1)return [t];const r=[];let n,i;for(const e of t){const t=en(e);0!==t&&(e.area=Math.abs(t),void 0===i&&(i=t<0),i===t<0?(n&&r.push(n),n=[e]):n.push(e));}if(n&&r.push(n),e>1)for(let t=0;t1?(l=t[o+1][0],u=t[o+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function on(t,e){return e[0]-t[0]}function ln(t){return t[1]-t[0]+1}function un(t,e){return t[1]>=t[0]&&t[1]t[1])return [null,null];const r=ln(t);if(e){if(2===r)return [t,null];const e=Math.floor(r/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===r)return [t,null];const n=Math.floor(r/2)-1;return [[t[0],t[0]+n],[t[0]+n+1,t[1]]]}function hn(t,e){if(!un(e,t.length))return [1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=e[0];n<=e[1];++n)Br(r,t[n]);return r}function pn(t){const e=[1/0,1/0,-1/0,-1/0];for(const r of t)for(const t of r)Br(e,t);return e}function fn(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function dn(t,e,r){if(!fn(t)||!fn(e))return NaN;let n=0,i=0;return t[2]e[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if(Vr(i,s)){if(wn(t,e))return 0}else if(wn(e,t))return 0;let a=1/0;for(const n of t)for(let t=0,i=n.length,s=i-1;t0;){const i=a.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(ln(l)<=u){if(!un(l,t.length))return NaN;if(e){const e=bn(t,l,r,n);if(isNaN(e)||0===e)return e;s=Math.min(s,e);}else for(let e=l[0];e<=l[1];++e){const i=vn(t[e],r,n);if(s=Math.min(s,i),0===s)return 0}}else {const r=cn(l,e);Sn(a,s,n,t,o,r[0]),Sn(a,s,n,t,o,r[1]);}}return s}function Mn(t,e,r,n,i,s=1/0){let a=Math.min(s,i.distance(t[0],r[0]));if(0===a)return a;const o=new Hr([[0,[0,t.length-1],[0,r.length-1]]],on);for(;o.length>0;){const s=o.pop();if(s[0]>=a)continue;const l=s[1],u=s[2],c=e?50:100,h=n?50:100;if(ln(l)<=c&&ln(u)<=h){if(!un(l,t.length)&&un(u,r.length))return NaN;let s;if(e&&n)s=gn(t,l,r,u,i),a=Math.min(a,s);else if(e&&!n){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=yn(r[t],e,i),a=Math.min(a,s),0===a)return a}else if(!e&&n){const e=r.slice(u[0],u[1]+1);for(let r=l[0];r<=l[1];++r)if(s=yn(t[r],e,i),a=Math.min(a,s),0===a)return a}else s=xn(t,l,r,u,i),a=Math.min(a,s);}else {const s=cn(l,e),c=cn(u,n);An(o,a,i,t,r,s[0],c[0]),An(o,a,i,t,r,s[0],c[1]),An(o,a,i,t,r,s[1],c[0]),An(o,a,i,t,r,s[1],c[1]);}}return a}function In(t){return "MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class zn{constructor(t,e){this.type=Ft,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new zn(e,e.features.map((t=>In(t.geometry))).flat());if("Feature"===e.type)return new zn(e,In(e.geometry));if("type"in e&&"coordinates"in e)return new zn(e,In(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!1,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!1,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!1,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!0,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!0,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!0,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const r=t.geometry();if(0===r.length||0===r[0].length)return NaN;const n=Qr(r,0).map((e=>e.map((e=>e.map((e=>Tr([e.x,e.y],t.canonical))))))),i=new an(n[0][0][0][1]);let s=1/0;for(const t of e)for(const e of n){switch(t.type){case "Point":s=Math.min(s,kn([t.coordinates],!1,e,i,s));break;case "LineString":s=Math.min(s,kn(t.coordinates,!0,e,i,s));break;case "Polygon":s=Math.min(s,_n(e,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return !0}}class Pn{constructor(t){this.type=Ut,this.key=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=t[1];return null==r?e.error("Global state property must be defined."):"string"!=typeof r?e.error(`Global state property must be string, but found ${typeof t[1]} instead.`):new Pn(r)}evaluate(t){var e;const r=null===(e=t.globals)||void 0===e?void 0:e.globalState;return r&&0!==Object.keys(r).length?xe(r,this.key):null}eachChild(){}outputDefined(){return !1}}const Cn={"==":vr,"!=":br,">":_r,"<":wr,">=":Ar,"<=":Sr,array:Ge,at:Qe,boolean:Ge,case:nr,coalesce:yr,collator:kr,format:Ir,image:zr,in:tr,"index-of":er,interpolate:pr,"interpolate-hcl":pr,"interpolate-lab":pr,length:Pr,let:Je,literal:Ne,match:rr,number:Ge,"number-format":Mr,object:Ge,slice:ir,step:ar,string:Ge,"to-boolean":Ze,"to-color":Ze,"to-number":Ze,"to-string":Ze,var:We,within:Yr,distance:zn,"global-state":Pn};class En{constructor(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return !1}static parse(t,e){const r=t[0],n=En.definitions[r];if(!n)return e.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let o=null;for(const[n,s]of a){o=new Ke(e.registry,$n,e.path,null,e.scope);const a=[];let l=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(Kt).join(", ")})`:`(${Kt(e.type)}...)`;var e;})).join(" | "),n=[];for(let r=1;r{r=e?r&&$n(t):r&&t instanceof Ne;})),!!r&&Dn(t)&&On(t,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function Dn(t){if(t instanceof En){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}if(t instanceof Yr)return !1;if(t instanceof zn)return !1;let e=!0;return t.eachChild((t=>{e&&!Dn(t)&&(e=!1);})),e}function Ln(t){if(t instanceof En&&"feature-state"===t.name)return !1;let e=!0;return t.eachChild((t=>{e&&!Ln(t)&&(e=!1);})),e}function On(t,e){if(t instanceof En&&e.indexOf(t.name)>=0)return !1;let r=!0;return t.eachChild((t=>{r&&!On(t,e)&&(r=!1);})),r}function Rn(t){return {result:"success",value:t}}function Un(t){return {result:"error",value:t}}function jn(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Nn(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function qn(t){return !!t.expression&&t.expression.interpolated}function Gn(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Xn(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)&&Ue(t)===Rt}function Zn(t){return t}function Yn(t,e){const r=t.stops&&"object"==typeof t.stops[0][0],n=r||!(r||void 0!==t.property),i=t.type||(qn(e)?"exponential":"interval"),s=function(t){switch(t.type){case "color":return Me.parse;case "padding":return Ee.parse;case "numberArray":return Te.parse;case "colorArray":return Be.parse;default:return null}}(e);if(s&&((t=Et({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],s(t[1])]))),t.default=s(t.default?t.default:e.default)),t.colorSpace&&"rgb"!==(a=t.colorSpace)&&"hcl"!==a&&"lab"!==a)throw new Error(`Unknown color space: "${t.colorSpace}"`);var a;const o=function(t){switch(t){case "exponential":return Wn;case "interval":return Jn;case "categorical":return Kn;case "identity":return Qn;default:throw new Error(`Unknown function type "${t}"`)}}(i);let l,u;if("categorical"===i){l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0];}if(r){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>Wn({stops:i,base:t.base},e,r).evaluate(r,n)}}if(n){const r="exponential"===i?{name:"exponential",base:void 0!==t.base?t.base:1}:null;return {kind:"camera",interpolationType:r,interpolationFactor:pr.interpolationFactor.bind(void 0,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>o(t,e,r,l,u)}}return {kind:"source",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:void 0;return void 0===i?Hn(t.default,e.default):o(t,e,i,l,u)}}}function Hn(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Kn(t,e,r,n,i){return Hn(typeof r===i?n[r]:void 0,t.default,e.default)}function Jn(t,e,r){if("number"!==Gn(r))return Hn(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=sr(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function Wn(t,e,r){const n=void 0!==t.base?t.base:1;if("number"!==Gn(r))return Hn(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=sr(t.stops.map((t=>t[0])),r),a=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),o=t.stops[s][1],l=t.stops[s+1][1],u=dr[e.type]||Zn;return "function"==typeof o.evaluate?{evaluate(...e){const r=o.evaluate.apply(void 0,e),n=l.evaluate.apply(void 0,e);if(void 0!==r&&void 0!==n)return u(r,n,a,t.colorSpace)}}:u(o,l,a,t.colorSpace)}function Qn(t,e,r){switch(e.type){case "color":r=Me.parse(r);break;case "formatted":r=Ce.fromString(r.toString());break;case "resolvedImage":r=De.fromString(r.toString());break;case "padding":r=Ee.parse(r);break;case "colorArray":r=Be.parse(r);break;case "numberArray":r=Te.parse(r);break;default:Gn(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0);}return Hn(r,t.default,e.default)}En.register(Cn,{error:[{kind:"error"},[$t],(t,[e])=>{throw new Ve(e.evaluate(t))}],typeof:[$t,[Ut],(t,[e])=>Kt(Ue(e.evaluate(t)))],"to-rgba":[Ht(Ft,4),[Lt],(t,[e])=>{const[r,n,i,s]=e.evaluate(t).rgb;return [255*r,255*n,255*i,s]}],rgb:[Lt,[Ft,Ft,Ft],Tn],rgba:[Lt,[Ft,Ft,Ft,Ft],Tn],has:{type:Dt,overloads:[[[$t],(t,[e])=>Bn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Bn(e.evaluate(t),r.evaluate(t))]]},get:{type:Ut,overloads:[[[$t],(t,[e])=>Vn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Vn(e.evaluate(t),r.evaluate(t))]]},"feature-state":[Ut,[$t],(t,[e])=>Vn(e.evaluate(t),t.featureState||{})],properties:[Rt,[],t=>t.properties()],"geometry-type":[$t,[],t=>t.geometryType()],id:[Ut,[],t=>t.id()],zoom:[Ft,[],t=>t.globals.zoom],"heatmap-density":[Ft,[],t=>t.globals.heatmapDensity||0],elevation:[Ft,[],t=>t.globals.elevation||0],"line-progress":[Ft,[],t=>t.globals.lineProgress||0],accumulated:[Ut,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[Ft,Fn(Ft),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],"*":[Ft,Fn(Ft),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],"-":{type:Ft,overloads:[[[Ft,Ft],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[Ft],(t,[e])=>-e.evaluate(t)]]},"/":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],"%":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[Ft,[],()=>Math.LN2],pi:[Ft,[],()=>Math.PI],e:[Ft,[],()=>Math.E],"^":[Ft,[Ft,Ft],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[Ft,[Ft],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))],log2:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[Ft,[Ft],(t,[e])=>Math.sin(e.evaluate(t))],cos:[Ft,[Ft],(t,[e])=>Math.cos(e.evaluate(t))],tan:[Ft,[Ft],(t,[e])=>Math.tan(e.evaluate(t))],asin:[Ft,[Ft],(t,[e])=>Math.asin(e.evaluate(t))],acos:[Ft,[Ft],(t,[e])=>Math.acos(e.evaluate(t))],atan:[Ft,[Ft],(t,[e])=>Math.atan(e.evaluate(t))],min:[Ft,Fn(Ft),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[Ft,Fn(Ft),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[Ft,[Ft],(t,[e])=>Math.abs(e.evaluate(t))],round:[Ft,[Ft],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[Ft,[Ft],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[Ft,[Ft],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[Dt,[$t,Ut],(t,[e,r])=>t.properties()[e.value]===r.value],"filter-id-==":[Dt,[Ut],(t,[e])=>t.id()===e.value],"filter-type-==":[Dt,[$t],(t,[e])=>t.geometryType()===e.value],"filter-<":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],"filter-<=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],"filter->=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],"filter-has":[Dt,[Ut],(t,[e])=>e.value in t.properties()],"filter-has-id":[Dt,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[Dt,[Ht($t)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[Dt,[Ht(Ut)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[Dt,[$t,Ht(Ut)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[Dt,[$t,Ht(Ut)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(!r.evaluate(t))return !1;return !0}]]},any:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(r.evaluate(t))return !0;return !1}]]},"!":[Dt,[Dt],(t,[e])=>!e.evaluate(t)],"is-supported-script":[Dt,[$t],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return !r||r(e.evaluate(t))}],upcase:[$t,[$t],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[$t,[$t],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[$t,Fn(Ut),(t,e)=>e.map((e=>je(e.evaluate(t)))).join("")],"resolved-locale":[$t,[jt],(t,[e])=>e.evaluate(t).resolvedLocale()]});class ti{constructor(t,e,r){this.expression=t,this._warningHistory={},this._evaluator=new He,this._defaultValue=e?function(t){if("color"===t.type&&Xn(t.default))return new Me(0,0,0,0);switch(t.type){case "color":return Me.parse(t.default)||null;case "padding":return Ee.parse(t.default)||null;case "numberArray":return Te.parse(t.default)||null;case "colorArray":return Be.parse(t.default)||null;case "variableAnchorOffsetCollection":return $e.parse(t.default)||null;case "projectionDefinition":return Le.parse(t.default)||null;default:return void 0===t.default?null:t.default}}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null,this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s){this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new Ve(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function ei(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Cn}function ri(t,e,r){const n=new Ke(Cn,$n,[],e?function(t){const e={color:Lt,string:$t,number:Ft,enum:$t,boolean:Dt,formatted:Nt,padding:qt,numberArray:Xt,colorArray:Gt,projectionDefinition:Ot,resolvedImage:Zt,variableAnchorOffsetCollection:Yt};return "array"===t.type?Ht(e[t.value]||Ut,t.length):e[t.type]}(e):void 0),i=n.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return i?Rn(new ti(i,e,r)):Un(n.errors)}class ni{constructor(t,e,r){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}}class ii{constructor(t,e,r,n,i){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this.interpolationType=n,this._globalState=i;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?pr.interpolationFactor(this.interpolationType,t,e,r):0}}function si(t,e,r){const n=ri(t,e,r);if("error"===n.result)return n;const i=n.value.expression,s=Dn(i);if(!s&&!jn(e))return Un([new Tt("","data expressions not supported")]);const a=On(i,["zoom"]);if(!a&&!Nn(e))return Un([new Tt("","zoom expressions not supported")]);const o=oi(i);return o||a?o instanceof Tt?Un([o]):o instanceof pr&&!qn(e)?Un([new Tt("",'"interpolate" expressions cannot be used with this property')]):Rn(o?new ii(s?"camera":"composite",n.value,o.labels,o instanceof pr?o.interpolation:void 0,r):new ni(s?"constant":"source",n.value,r)):Un([new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class ai{constructor(t,e){this._parameters=t,this._specification=e,Et(this,Yn(this._parameters,this._specification));}static deserialize(t){return new ai(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function oi(t){let e=null;if(t instanceof Je)e=oi(t.result);else if(t instanceof yr){for(const r of t.args)if(e=oi(r),e)break}else (t instanceof ar||t instanceof pr)&&t.input instanceof En&&"zoom"===t.input.name&&(e=t);return e instanceof Tt||t.eachChild((t=>{const r=oi(t);r instanceof Tt?e=r:!e&&r?e=new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&r&&e!==r&&(e=new Tt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),e}function li(t,e=new Set){return t instanceof Pn&&e.add(t.key),t.eachChild((t=>{li(t,e);})),e}function ui(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case "has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case "in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case "!in":case "!has":case "none":return !1;case "==":case "!=":case ">":case ">=":case "<":case "<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case "any":case "all":for(const e of t.slice(1))if(!ui(e)&&"boolean"!=typeof e)return !1;return !0;default:return !0}}const ci={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function hi(t,e){if(null==t)return {filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};ui(t)||(t=di(t));const r=ri(t,ci,e);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return {filter:(t,e,n)=>r.value.evaluate(t,e,{},n),needGeometry:fi(t),getGlobalStateRefs:()=>li(r.value.expression)}}function pi(t,e){return te?1:0}function fi(t){if(!Array.isArray(t))return !1;if("within"===t[0]||"distance"===t[0])return !0;for(let e=1;e"===e||"<="===e||">="===e?yi(t[1],t[2],e):"any"===e?(r=t.slice(1),["any"].concat(r.map(di))):"all"===e?["all"].concat(t.slice(1).map(di)):"none"===e?["all"].concat(t.slice(1).map(di).map(xi)):"in"===e?mi(t[1],t.slice(2)):"!in"===e?xi(mi(t[1],t.slice(2))):"has"===e?gi(t[1]):"!has"!==e||xi(gi(t[1]));var r;}function yi(t,e,r){switch(t){case "$type":return [`filter-type-${r}`,e];case "$id":return [`filter-id-${r}`,e];default:return [`filter-${r}`,t,e]}}function mi(t,e){if(0===e.length)return !1;switch(t){case "$type":return ["filter-type-in",["literal",e]];case "$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(pi)]]:["filter-in-small",t,["literal",e]]}}function gi(t){switch(t){case "$type":return !0;case "$id":return ["filter-has-id"];default:return ["filter-has",t]}}function xi(t){return ["!",t]}function vi(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const r of t)e+=`${vi(r)},`;return `${e}]`}const r=Object.keys(t).sort();let n="{";for(let e=0;en.maximum?[new Ct(e,r,`${r} is greater than the maximum value ${n.maximum}`)]:[]}function Ii(t){const e=t.valueSpec,r=_i(t.value.type);let n,i,s,a={};const o="categorical"!==r&&void 0===t.value.property,l=!o,u="array"===Gn(t.value.stops)&&"array"===Gn(t.value.stops[0])&&"object"===Gn(t.value.stops[0][0]),c=Ai({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===r)return [new Ct(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const n=t.value;return e=e.concat(ki({key:t.key,value:n,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===Gn(n)&&0===n.length&&e.push(new Ct(t.key,n,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===r&&o&&c.push(new Ct(t.key,t.value,'missing required property "property"')),"identity"===r||t.value.stops||c.push(new Ct(t.key,t.value,'missing required property "stops"')),"exponential"===r&&t.valueSpec.expression&&!qn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!jn(t.valueSpec)?c.push(new Ct(t.key,t.value,"property functions not supported")):o&&!Nn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"zoom functions not supported"))),"categorical"!==r&&!u||void 0!==t.value.property||c.push(new Ct(t.key,t.value,'"property" property is required')),c;function h(t){let r=[];const n=t.value,o=t.key;if("array"!==Gn(n))return [new Ct(o,n,`array expected, ${Gn(n)} found`)];if(2!==n.length)return [new Ct(o,n,`array length 2 expected, length ${n.length} found`)];if(u){if("object"!==Gn(n[0]))return [new Ct(o,n,`object expected, ${Gn(n[0])} found`)];if(void 0===n[0].zoom)return [new Ct(o,n,"object stop key must have zoom")];if(void 0===n[0].value)return [new Ct(o,n,"object stop key must have value")];if(s&&s>_i(n[0].zoom))return [new Ct(o,n[0].zoom,"stop zoom values must appear in ascending order")];_i(n[0].zoom)!==s&&(s=_i(n[0].zoom),i=void 0,a={}),r=r.concat(Ai({key:`${o}[0]`,value:n[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Mi,value:p}}));}else r=r.concat(p({key:`${o}[0]`,value:n[0],validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},n));return ei(Si(n[1]))?r.concat([new Ct(`${o}[1]`,n[1],"expressions are not allowed in function stops.")]):r.concat(t.validateSpec({key:`${o}[1]`,value:n[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const o=Gn(t.value),l=_i(t.value),u=null!==t.value?t.value:s;if(n){if(o!==n)return [new Ct(t.key,u,`${o} stop domain type must match previous stop domain type ${n}`)]}else n=o;if("number"!==o&&"string"!==o&&"boolean"!==o)return [new Ct(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==o&&"categorical"!==r){let n=`number expected, ${o} found`;return jn(e)&&void 0===r&&(n+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new Ct(t.key,u,n)]}return "categorical"!==r||"number"!==o||isFinite(l)&&Math.floor(l)===l?"categorical"!==r&&"number"===o&&void 0!==i&&lnew Ct(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new Ct(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!On(r,["zoom","feature-state"]))return [new Ct(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!Dn(r))return [new Ct(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function Pi(t){const e=t.key,r=t.value,n=Gn(r);return "string"!==n?[new Ct(e,r,`color expected, ${n} found`)]:Me.parse(String(r))?[]:[new Ct(e,r,`color expected, "${r}" found`)]}function Ci(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${n.values.join(", ")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${Object.keys(n.values).join(", ")}], ${JSON.stringify(r)} found`)),i}function Ei(t){return ui(Si(t.value))?zi(Et({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):Ti(t)}function Ti(t){const e=t.value,r=t.key;if("array"!==Gn(e))return [new Ct(r,e,`array expected, ${Gn(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return [new Ct(r,e,"filter array must have at least 1 element")];switch(s=s.concat(Ci({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),_i(e[0])){case "<":case "<=":case ">":case ">=":e.length>=2&&"$type"===_i(e[1])&&s.push(new Ct(r,e,`"$type" cannot be use with operator "${e[0]}"`));case "==":case "!=":3!==e.length&&s.push(new Ct(r,e,`filter array for operator "${e[0]}" must have 3 elements`));case "in":case "!in":e.length>=2&&(i=Gn(e[1]),"string"!==i&&s.push(new Ct(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let a=2;a{t in r&&e.push(new Ct(n,r[t],`"${t}" is prohibited for ref layers`));})),i.layers.forEach((e=>{_i(e.id)===o&&(t=e);})),t?t.ref?e.push(new Ct(n,r.ref,"ref cannot reference another ref layer")):a=_i(t.type):e.push(new Ct(n,r.ref,`ref layer "${o}" not found`));}else if("background"!==a)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&_i(t.type);t?"vector"===s&&"raster"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster source`)):"raster-dem"!==s&&"hillshade"===a||"raster-dem"!==s&&"color-relief"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster-dem source`)):"raster"===s&&"raster"!==a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a vector source`)):"vector"!==s||r["source-layer"]?"raster-dem"===s&&"hillshade"!==a&&"color-relief"!==a?e.push(new Ct(n,r.source,"raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.")):"line"!==a||!r.paint||!r.paint["line-gradient"]||"geojson"===s&&t.lineMetrics||e.push(new Ct(n,r,`layer "${r.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new Ct(n,r,`layer "${r.id}" must specify a "source-layer"`)):e.push(new Ct(n,r.source,`source "${r.source}" not found`));}else e.push(new Ct(n,r,'missing required property "source"'));return e=e.concat(Ai({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:r,objectKey:"type"}),filter:Ei,layout:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Fi(Et({layerType:a},t))}}),paint:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Vi(Et({layerType:a},t))}})}})),e}function Di(t){const e=t.value,r=t.key,n=Gn(e);return "string"!==n?[new Ct(r,e,`string expected, ${n} found`)]:[]}const Li={promoteId:function({key:t,value:e}){if("string"===Gn(e))return Di({key:t,value:e});{const r=[];for(const n in e)r.push(...Di({key:`${t}.${n}`,value:e[n]}));return r}}};function Oi(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return [new Ct(r,e,'"type" is required')];const a=_i(e.type);let o;switch(a){case "vector":case "raster":return o=Ai({key:r,value:e,valueSpec:n[`source_${a.replace("-","_")}`],style:t.style,styleSpec:n,objectElementValidators:Li,validateSpec:s}),o;case "raster-dem":return o=function(t){var e;const r=null!==(e=t.sourceName)&&void 0!==e?e:"",n=t.value,i=t.styleSpec,s=i.source_raster_dem,a=t.style;let o=[];const l=Gn(n);if(void 0===n)return o;if("object"!==l)return o.push(new Ct("source_raster_dem",n,`object expected, ${l} found`)),o;const u="custom"===_i(n.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in n)!u&&c.includes(e)?o.push(new Ct(e,n[e],`In "${r}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?o=o.concat(t.validateSpec({key:e,value:n[e],valueSpec:s[e],validateSpec:t.validateSpec,style:a,styleSpec:i})):o.push(new Ct(e,n[e],`unknown property "${e}"`));return o}({sourceName:r,value:e,style:t.style,styleSpec:n,validateSpec:s}),o;case "geojson":if(o=Ai({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,validateSpec:s,objectElementValidators:Li}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],s="string"==typeof n?[n,["accumulated"],["get",t]]:n;o.push(...zi({key:`${r}.${t}.map`,value:i,expressionContext:"cluster-map"})),o.push(...zi({key:`${r}.${t}.reduce`,value:s,expressionContext:"cluster-reduce"}));}return o;case "video":return Ai({key:r,value:e,valueSpec:n.source_video,style:i,validateSpec:s,styleSpec:n});case "image":return Ai({key:r,value:e,valueSpec:n.source_image,style:i,validateSpec:s,styleSpec:n});case "canvas":return [new Ct(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Ci({key:`${r}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]}})}}function Ri(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("light",e,`object expected, ${a} found`)]),s;for(const a in e){const o=a.match(/^(.*)-transition$/);s=s.concat(o&&n[o[1]]&&n[o[1]].transition?t.validateSpec({key:a,value:e[a],valueSpec:r.transition,validateSpec:t.validateSpec,style:i,styleSpec:r}):n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);}return s}function Ui(t){const e=t.value,r=t.styleSpec,n=r.sky,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("sky",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a}function ji(t){const e=t.value,r=t.styleSpec,n=r.terrain,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("terrain",e,`object expected, ${a} found`)]),s;for(const a in e)s=s.concat(n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);return s}function Ni(t){let e=[];const r=t.value,n=t.key;if(Array.isArray(r)){const i=[],s=[];for(const a in r)r[a].id&&i.includes(r[a].id)&&e.push(new Ct(n,r,`all the sprites' ids must be unique, but ${r[a].id} is duplicated`)),i.push(r[a].id),r[a].url&&s.includes(r[a].url)&&e.push(new Ct(n,r,`all the sprites' URLs must be unique, but ${r[a].url} is duplicated`)),s.push(r[a].url),e=e.concat(Ai({key:`${n}[${a}]`,value:r[a],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:t.validateSpec}));return e}return Di({key:n,value:r})}function qi(t){return e=t.value,Boolean(e)&&e.constructor===Object?[]:[new Ct(t.key,t.value,`object expected, ${Gn(t.value)} found`)];var e;}const Gi={"*":()=>[],array:ki,boolean:function(t){const e=t.value,r=t.key,n=Gn(e);return "boolean"!==n?[new Ct(r,e,`boolean expected, ${n} found`)]:[]},number:Mi,color:Pi,constants:wi,enum:Ci,filter:Ei,function:Ii,layer:$i,object:Ai,source:Oi,light:Ri,sky:Ui,terrain:ji,projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("projection",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a},projectionDefinition:function(t){const e=t.key;let r=t.value;r=r instanceof String?r.valueOf():r;const n=Gn(r);return "array"!==n||function(t){return Array.isArray(t)&&3===t.length&&"string"==typeof t[0]&&"string"==typeof t[1]&&"number"==typeof t[2]}(r)||function(t){return !!["interpolate","step","literal"].includes(t[0])}(r)?["array","string"].includes(n)?[]:[new Ct(e,r,`projection expected, invalid type "${n}" found`)]:[new Ct(e,r,`projection expected, invalid array ${JSON.stringify(r)} found`)]},string:Di,formatted:function(t){return 0===Di(t).length?[]:zi(t)},resolvedImage:function(t){return 0===Di(t).length?[]:zi(t)},padding:function(t){const e=t.key,r=t.value;if("array"===Gn(r)){if(r.length<1||r.length>4)return [new Ct(e,r,`padding requires 1 to 4 values; ${r.length} values found`)];const n={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(r=r.concat(wi({key:"constants",value:t.constants}))),Ki(r)}function Hi(t){return function(e){return t({...e,validateSpec:Xi})}}function Ki(t){return [].concat(t).sort(((t,e)=>t.line-e.line))}function Ji(t){return function(...e){return Ki(t.apply(this,e))}}Yi.source=Ji(Hi(Oi)),Yi.sprite=Ji(Hi(Ni)),Yi.glyphs=Ji(Hi(Zi)),Yi.light=Ji(Hi(Ri)),Yi.sky=Ji(Hi(Ui)),Yi.terrain=Ji(Hi(ji)),Yi.state=Ji(Hi(qi)),Yi.layer=Ji(Hi($i)),Yi.filter=Ji(Hi(Ei)),Yi.paintProperty=Ji(Hi(Vi)),Yi.layoutProperty=Ji(Hi(Fi));const Wi=Yi,Qi=Wi.light,ts=Wi.sky,es=Wi.paintProperty,rs=Wi.layoutProperty;function ns(t,e){let r=!1;if(e&&e.length)for(const n of e)t.fire(new mt(new Error(n.message))),r=!0;return r}class is{constructor(t,e,r){const n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(let t=0;t=u[l+0]&&n>=u[l+1])?(a[h]=!0,s.push(i[h])):a[h]=!1;}}}}_forEachCell(t,e,r,n,i,s,a,o){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!o||o(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,r,n,u,s,a,o))return}}_convertFromCellCoord(t){return (t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let r=0;for(let t=0;t=0)continue;const s=t[n];i[n]=ss[r].shallow.indexOf(n)>=0?s:cs(s,e);}t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==r&&(i.$name=r),i}function hs(t){if(us(t))return t;if(Array.isArray(t))return t.map(hs);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=ls(t)||"Object";if(!ss[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:r}=ss[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const r of Object.keys(t)){if("$name"===r)continue;const i=t[r];n[r]=ss[e].shallow.indexOf(r)>=0?i:hs(i);}return n}class ps{constructor(){this.first=!0;}update(t,e){const r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Hiragana:t=>t>=12352&&t<=12447,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"CJK Unified Ideographs":t=>t>=19968&&t<=40959,"Hangul Syllables":t=>t>=44032&&t<=55215,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function ds(t){for(const e of t)if(bs(e.charCodeAt(0)))return !0;return !1}function ys(t){for(const e of t)if(!xs(e.charCodeAt(0)))return !1;return !0}function ms(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const gs=ms(["Arab","Dupl","Mong","Ougr","Syrc"]);function xs(t){return !gs.test(String.fromCodePoint(t))}const vs=ms(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function bs(t){return !(746!==t&&747!==t&&(t<4352||!(fs["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||fs["CJK Compatibility"](t)||fs["CJK Strokes"](t)||!(!fs["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||fs["Enclosed CJK Letters and Months"](t)||fs["Ideographic Description Characters"](t)||fs.Kanbun(t)||fs.Katakana(t)&&12540!==t||!(!fs["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!fs["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||fs["Vertical Forms"](t)||fs["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||vs.test(String.fromCodePoint(t)))))}function ws(t){return !(bs(t)||function(t){return !!(fs["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||fs["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||fs["Letterlike Symbols"](t)||fs["Number Forms"](t)||fs["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||fs["Control Pictures"](t)&&9251!==t||fs["Optical Character Recognition"](t)||fs["Enclosed Alphanumerics"](t)||fs["Geometric Shapes"](t)||fs["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||fs["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||fs["CJK Symbols and Punctuation"](t)||fs.Katakana(t)||fs["Private Use Area"](t)||fs["CJK Compatibility Forms"](t)||fs["Small Form Variants"](t)||fs["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}const _s=ms(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Ss(t){return _s.test(String.fromCodePoint(t))}function As(t,e){return !(!e&&Ss(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||fs.Khmer(t))}function ks(t){for(const e of t)if(Ss(e.charCodeAt(0)))return !0;return !1}const Ms=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{};}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL;}getState(){return {pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){if(Ms.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText,this.loadScriptResolve();}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(t,r){return e(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if("loading"!==t.pluginStatus)return this.setState(t),t;const e=t.pluginURL,n=new Promise((t=>{this.loadScriptResolve=t;}));r(e);const i=new Promise((t=>setTimeout((()=>t()),this.TIMEOUT)));if(yield Promise.race([n,i]),this.isParsed()){const t={pluginStatus:"loaded",pluginURL:e};return this.setState(t),t}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${e}`)}))}};class Is{constructor(t,e){this.isSupportedScript=zs,this.zoom=t,e?(this.now=e.now||0,this.fadeDuration=e.fadeDuration||0,this.zoomHistory=e.zoomHistory||new ps,this.transition=e.transition||{}):(this.now=0,this.fadeDuration=0,this.zoomHistory=new ps,this.transition={});}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}}}function zs(t){return function(t,e){for(const r of t)if(!As(r.charCodeAt(0),e))return !1;return !0}(t,"loaded"===Ms.getRTLTextPluginStatus())}class Ps{constructor(t,e,r){this.property=t,this.value=e,this.expression=function(t,e,r){if(Xn(t))return new ai(t,e);if(ei(t)){const n=si(t,e,r);if("error"===n.result)throw new Error(n.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return n.value}{let r=t;return "color"===e.type&&"string"==typeof t?r=Me.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"numberArray"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"colorArray"!==e.type||"string"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)?r=$e.parse(t):"projectionDefinition"===e.type&&"string"==typeof t&&(r=Le.parse(t)):r=Be.parse(t):r=Te.parse(t):r=Ee.parse(t),{globalStateRefs:new Set,_globalState:null,kind:"constant",evaluate:()=>r}}}(void 0===e?t.specification.default:e,t.specification,r);}isDataDriven(){return "source"===this.expression.kind||"composite"===this.expression.kind}getGlobalStateRefs(){return this.expression.globalStateRefs||new Set}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class Cs{constructor(t,e){this.property=t,this.value=new Ps(t,void 0,e);}transitioned(t,e){return new Ts(this.property,this.value,e,L({},t.transition,this.transition),t.now)}untransitioned(){return new Ts(this.property,this.value,null,{},0)}}class Es{constructor(t,e){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues),this._globalState=e;}getValue(t){return j(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].value=new Ps(this._values[t].property,null===e?void 0:j(e),this._globalState);}getTransition(t){return j(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].transition=j(e)||void 0;}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r);const n=this.getTransition(e);void 0!==n&&(t[`${e}-transition`]=n);}return t}transitioned(t,e){const r=new Bs(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new Bs(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class Ts{constructor(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(nn.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Rs{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new Is(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Is(Math.floor(e.zoom),e)),t.expression.evaluate(new Is(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Us{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)}interpolate(){return !1}}class js{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const r=t[e];r.specification.overridable&&this.overridableProperties.push(e);const n=this.defaultPropertyValues[e]=new Ps(r,void 0,void 0),i=this.defaultTransitionablePropertyValues[e]=new Cs(r,void 0);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}}}as("DataDrivenProperty",Ls),as("DataConstantProperty",Ds),as("CrossFadedDataDrivenProperty",Os),as("CrossFadedProperty",Rs),as("ColorRampProperty",Us);const Ns="-transition";class qs extends gt{constructor(t,e,r){if(super(),this.id=t.id,this.type=t.type,this._globalState=r,this._featureFilter={filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter,this._featureFilter=hi(t.filter,r)),e.layout&&(this._unevaluatedLayout=new Vs(e.layout,r)),e.paint)){this._transitionablePaint=new Es(e.paint,r);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new $s(e.paint);}}setFilter(t){this.filter=t,this._featureFilter=hi(t,this._globalState);}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}getLayoutAffectingGlobalStateRefs(){const t=new Set;if(this._unevaluatedLayout)for(const e in this._unevaluatedLayout._values){const r=this._unevaluatedLayout._values[e];for(const e of r.getGlobalStateRefs())t.add(e);}for(const e of this._featureFilter.getGlobalStateRefs())t.add(e);return t}getPaintAffectingGlobalStateRefs(){var t;const e=new globalThis.Map;if(this._transitionablePaint)for(const r in this._transitionablePaint._values){const n=this._transitionablePaint._values[r].value;for(const i of n.getGlobalStateRefs()){const s=null!==(t=e.get(i))&&void 0!==t?t:[];s.push({name:r,value:n.value}),e.set(i,s);}}return e}setLayoutProperty(t,e,r={}){null!=e&&this._validate(rs,`layers.${this.id}.layout.${t}`,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);}getPaintProperty(t){return t.endsWith(Ns)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(es,`layers.${this.id}.paint.${t}`,t,e,r))return !1;if(t.endsWith(Ns))return this._transitionablePaint.setTransition(t.slice(0,-11),e||void 0),!1;{const r=this._transitionablePaint._values[t],n="cross-faded-data-driven"===r.property.specification["property-type"],i=r.value.isDataDriven(),s=r.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const a=this._transitionablePaint._values[t].value;return a.isDataDriven()||i||n||this._handleOverridablePaintPropertyUpdate(t,s,a)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,r){return !1}isHidden(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),U(t,((t,e)=>!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return (!i||!1!==i.validate)&&ns(this,t.call(Wi,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:xt,style:{glyphs:!0,sprite:!0}}))}is3D(){return !1}isTileClipped(){return !1}hasOffscreenPass(){return !1}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof Fs&&jn(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1}}const Gs={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Xs{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class Zs{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Ys(t,e=1){let r=0,n=0;return {members:t.map((t=>{const i=Gs[t.type].BYTES_PER_ELEMENT,s=r=Hs(r,Math.max(e,i)),a=t.components||1;return n=Math.max(n,i),r+=i*a,{name:t.name,type:t.type,components:a,offset:s}})),size:Hs(r,Math.max(n,e)),alignment:e}}function Hs(t,e){return Math.ceil(t/e)*e}class Ks extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}Ks.prototype.bytesPerElement=4,as("StructArrayLayout2i4",Ks);class Js extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}Js.prototype.bytesPerElement=6,as("StructArrayLayout3i6",Js);class Ws extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}Ws.prototype.bytesPerElement=8,as("StructArrayLayout4i8",Ws);class Qs extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}Qs.prototype.bytesPerElement=12,as("StructArrayLayout2i4i12",Qs);class ta extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=4*t,l=8*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.uint8[l+4]=n,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=a,t}}ta.prototype.bytesPerElement=8,as("StructArrayLayout2i4ub8",ta);class ea extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}ea.prototype.bytesPerElement=8,as("StructArrayLayout2f8",ea);class ra extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,s,a,o,l,u)}emplace(t,e,r,n,i,s,a,o,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=r,this.uint16[h+2]=n,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=a,this.uint16[h+6]=o,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}ra.prototype.bytesPerElement=20,as("StructArrayLayout10ui20",ra);class na extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,a,o,l,u,c,h)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=a,this.uint16[f+6]=o,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}na.prototype.bytesPerElement=24,as("StructArrayLayout4i4ui4i24",na);class ia extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}ia.prototype.bytesPerElement=12,as("StructArrayLayout3f12",ia);class sa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}sa.prototype.bytesPerElement=4,as("StructArrayLayout1ul4",sa);class aa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,s,a,o,l)}emplace(t,e,r,n,i,s,a,o,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=r,this.int16[c+2]=n,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=a,this.uint32[h+3]=o,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}aa.prototype.bytesPerElement=20,as("StructArrayLayout6i1ul2ui20",aa);class oa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}oa.prototype.bytesPerElement=12,as("StructArrayLayout2i2i2i12",oa);class la extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.int16[o+6]=i,this.int16[o+7]=s,t}}la.prototype.bytesPerElement=16,as("StructArrayLayout2f1f2i16",la);class ua extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=16*t,l=4*t,u=8*t;return this.uint8[o+0]=e,this.uint8[o+1]=r,this.float32[l+1]=n,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=a,t}}ua.prototype.bytesPerElement=16,as("StructArrayLayout2ub2f2i16",ua);class ca extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}ca.prototype.bytesPerElement=6,as("StructArrayLayout3ui6",ca);class ha extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=r,this.uint16[x+2]=n,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=a,this.uint32[v+4]=o,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}ha.prototype.bytesPerElement=48,as("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",ha);class pa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I){const z=this.length;return this.resize(z+1),this.emplace(z,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I,z){const P=32*t,C=16*t;return this.int16[P+0]=e,this.int16[P+1]=r,this.int16[P+2]=n,this.int16[P+3]=i,this.int16[P+4]=s,this.int16[P+5]=a,this.int16[P+6]=o,this.int16[P+7]=l,this.uint16[P+8]=u,this.uint16[P+9]=c,this.uint16[P+10]=h,this.uint16[P+11]=p,this.uint16[P+12]=f,this.uint16[P+13]=d,this.uint16[P+14]=y,this.uint16[P+15]=m,this.uint16[P+16]=g,this.uint16[P+17]=x,this.uint16[P+18]=v,this.uint16[P+19]=b,this.uint16[P+20]=w,this.uint16[P+21]=_,this.uint16[P+22]=S,this.uint32[C+12]=A,this.float32[C+13]=k,this.float32[C+14]=M,this.uint16[P+30]=I,this.uint16[P+31]=z,t}}pa.prototype.bytesPerElement=64,as("StructArrayLayout8i15ui1ul2f2ui64",pa);class fa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}fa.prototype.bytesPerElement=4,as("StructArrayLayout1f4",fa);class da extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}da.prototype.bytesPerElement=12,as("StructArrayLayout1ui2f12",da);class ya extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t}}ya.prototype.bytesPerElement=8,as("StructArrayLayout1ul2ui8",ya);class ma extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}ma.prototype.bytesPerElement=4,as("StructArrayLayout2ui4",ma);class ga extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}ga.prototype.bytesPerElement=2,as("StructArrayLayout1ui2",ga);class xa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}xa.prototype.bytesPerElement=16,as("StructArrayLayout4f16",xa);class va extends Xs{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new r(this.anchorPointX,this.anchorPointY)}}va.prototype.size=20;class ba extends aa{get(t){return new va(this,t)}}as("CollisionBoxArray",ba);class wa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t;}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}wa.prototype.size=48;class _a extends ha{get(t){return new wa(this,t)}}as("PlacedSymbolArray",_a);class Sa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t;}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}Sa.prototype.size=64;class Aa extends pa{get(t){return new Sa(this,t)}}as("SymbolInstanceArray",Aa);class ka extends fa{getoffsetX(t){return this.float32[1*t+0]}}as("GlyphOffsetArray",ka);class Ma extends Js{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}as("SymbolLineVertexArray",Ma);class Ia extends Xs{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}Ia.prototype.size=12;class za extends da{get(t){return new Ia(this,t)}}as("TextAnchorOffsetArray",za);class Pa extends Xs{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}Pa.prototype.size=8;class Ca extends ya{get(t){return new Pa(this,t)}}as("FeatureIndexArray",Ca);class Ea extends Ks{}class Ta extends Ks{}class Ba extends Ks{}class Va extends Qs{}class Fa extends ta{}class $a extends ea{}class Da extends ra{}class La extends na{}class Oa extends ia{}class Ra extends sa{}class Ua extends oa{}class ja extends ua{}class Na extends ca{}class qa extends ma{}const Ga=Ys([{name:"a_pos",components:2,type:"Int16"}],4),{members:Xa}=Ga;class Za{constructor(t=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=t;}prepareSegment(t,e,r,n){const i=this.segments[this.segments.length-1];return t>Za.MAX_VERTEX_ARRAY_LENGTH&&q(`Max vertices per segment is ${Za.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${Za.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!i||i.vertexLength+t>Za.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n?this.createNewSegment(e,r,n):i}createNewSegment(t,e,r){const n={vertexOffset:t.length,primitiveOffset:e.length,vertexLength:0,primitiveLength:0,vaos:{}};return void 0!==r&&(n.sortKey=r),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(n),n}getOrCreateLatestSegment(t,e,r){return this.prepareSegment(0,t,e,r)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0;}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,r,n){return new Za([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function Ya(t,e){return 256*(t=$(Math.floor(t),0,255))+$(Math.floor(e),0,255)}Za.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,as("SegmentVector",Za);const Ha=Ys([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var Ka,Ja,Wa,Qa={exports:{}},to={exports:{}},eo={exports:{}},ro=function(){if(Wa)return Qa.exports;Wa=1;var t=(Ka||(Ka=1,to.exports=function(t,e){var r,n,i,s,a,o,l,u;for(n=t.length-(r=3&t.length),i=e,a=3432918353,o=461845907,u=0;u>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0}),to.exports),e=(Ja||(Ja=1,eo.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0}),eo.exports);return Qa.exports=t,Qa.exports.murmur3=t,Qa.exports.murmur2=e,Qa.exports}(),no=n(ro);class io{constructor(){this.ids=[],this.positions=[],this.indexed=!1;}add(t,e,r,n){this.ids.push(so(t)),this.positions.push(e,r,n);}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=so(t);let r=0,n=this.ids.length-1;for(;r>1;this.ids[t]>=e?n=t:r=t+1;}const i=[];for(;this.ids[r]===e;)i.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return i}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return ao(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}}static deserialize(t){const e=new io;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e}}function so(t){const e=+t;return !isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:no(String(t))}function ao(t,e,r,n){for(;r>1];let s=r-1,a=n+1;for(;;){do{s++;}while(t[s]i);if(s>=a)break;oo(t,s,a),oo(e,3*s,3*a),oo(e,3*s+1,3*a+1),oo(e,3*s+2,3*a+2);}a-r`u_${t}`)),this.type=r;}setUniform(t,e,r){t.set(r.constantOr(this.value));}getBinding(t,e,r){return "color"===this.type?new ho(t,e):new uo(t,e)}}class mo{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;}setUniform(t,e,r,n){const i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);}getBinding(t,e,r){return "u_pattern"===r.substr(0,9)?new co(t,e):new uo(t,e)}}class go{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?2:1,offset:0}))),this.paintVertexArray=new n;}populatePaintArray(t,e,r){const n=this.paintVertexArray.length,i=this.expression.evaluate(new Is(0,r),e,{},r.canonical,[],r.formattedSection);this.paintVertexArray.resize(t),this._setPaintValue(n,t,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(0,i),r,n);this._setPaintValue(t,e,s);}_setPaintValue(t,e,r){if("color"===this.type){const n=fo(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,r){const n=this.expression.evaluate(new Is(this.zoom,r),e,{},r.canonical,[],r.formattedSection),i=this.expression.evaluate(new Is(this.zoom+1,r),e,{},r.canonical,[],r.formattedSection),s=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(s,t,n,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(this.zoom,i),r,n),a=this.expression.evaluate(new Is(this.zoom+1,i),r,n);this._setPaintValue(t,e,s,a);}_setPaintValue(t,e,r,n){if("color"===this.type){const i=fo(r),s=fo(n);for(let r=t;r`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof go||r instanceof xo)for(let e=0;e!0){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new bo(n,e,r);this.needsUpload=!1,this._featureMap=new io,this._bufferOffset=0;}populatePaintArrays(t,e,r,n){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;}updatePaintArrays(t,e,r,n){for(const i of r)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,n)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}function _o(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function So(t,e,r){const n={color:{source:ea,composite:xa},number:{source:fa,composite:ea}},i=function(t){return {"line-pattern":{source:Da,composite:Da},"fill-pattern":{source:Da,composite:Da},"fill-extrusion-pattern":{source:Da,composite:Da}}[t]}(t);return i&&i[r]||n[e][r]}as("ConstantBinder",yo),as("CrossFadedConstantBinder",mo),as("SourceExpressionBinder",go),as("CrossFadedCompositeBinder",vo),as("CompositeExpressionBinder",xo),as("ProgramConfiguration",bo,{omit:["_buffers"]}),as("ProgramConfigurationSet",wo);const Ao=Math.pow(2,14)-1,ko=-Ao-1;function Mo(t){const e=P/t.extent,r=t.loadGeometry();for(let t=0;tr.x+1||sr.y+1)&&q("Geometry exceeds allowed extent, reduce your vector tile buffer size");}}return r}function Io(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?Mo(t):[]}}const zo=-32768;function Po(t,e,r,n,i){t.emplaceBack(zo+8*e+n,zo+8*r+i);}class Co{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Ta,this.indexArray=new Na,this.segments=new Za,this.programConfigurations=new wo(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){const n=this.layers[0],i=[];let s=null,a=!1,o="heatmap"===n.type;if("circle"===n.type){const t=n;s=t.layout.get("circle-sort-key"),a=!s.isConstant(),o=o||"map"===t.paint.get("circle-pitch-alignment");}const l=o?e.subdivisionGranularity.circle:1;for(const{feature:e,id:n,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=a?s.evaluate(u,{},r):void 0,h={id:n,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};i.push(h);}a&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of i){const{geometry:i,index:s,sourceLayerIndex:a}=n,o=t[s].feature;this.addFeature(n,i,s,r,l),e.featureIndex.insert(o,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Xa),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,r,n,i=1){let s;switch(i){case 1:s=[0,7];break;case 3:s=[0,2,5,7];break;case 5:s=[0,1,3,4,6,7];break;case 7:s=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${i}; valid values are 1, 3, 5, 7.`)}const a=s.length;for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=P||n<0||n>=P)continue;const i=this.segments.prepareSegment(a*a,this.layoutVertexArray,this.indexArray,t.sortKey),o=i.vertexLength;for(let t=0;t1){if(Fo(t,e))return !0;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function Oo(t,e){let r,n,i,s=!1;for(let a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s);}return s}function Ro(t,e){let r=!1;for(let n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-s.x)*(e.y-s.y)/(a.y-s.y)+s.x&&(r=!r);}return r}function Uo(t,e,r){const n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;const s=G(t,e,r[0]);return s!==G(t,e,r[1])||s!==G(t,e,r[2])||s!==G(t,e,r[3])}function jo(t,e,r){const n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function No(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function qo(t,e,n,i,s){if(!e[0]&&!e[1])return t;const a=r.convert(e)._mult(s);"viewport"===n&&a._rotate(-i);const o=[];for(let e=0;eKo(t,e,r,n)))}(l,i,a,o),f=u),Ho({queryGeometry:p,size:f,transform:i,unwrappedTileID:a,getElevation:o,pitchAlignment:h,pitchScale:c},n)}}class el extends Co{}let rl;as("HeatmapBucket",el,{omit:["layers"]});var nl={get paint(){return rl=rl||new js({"heatmap-radius":new Ls(xt.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Ls(xt.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Ds(xt.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Us(xt.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Ds(xt.paint_heatmap["heatmap-opacity"])})}};function il(t,{width:e,height:r},n,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*r*n)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*r*n}`)}else i=new Uint8Array(e*r*n);return t.width=e,t.height=r,t.data=i,t}function sl(t,{width:e,height:r},n){if(e===t.width&&r===t.height)return;const i=il({},{width:e,height:r},n);al(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,r)},n),t.width=e,t.height=r,t.data=i.data;}function al(t,e,r,n,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const a=t.data,o=e.data;if(a===o)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=a;const o=t.expression.evaluate(e);i.setPixel(n/4/r,s/4,o);};if(t.clips)for(let e=0,i=0;ethis.max&&(this.max=r),r=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)}unpack(t,e,r){return t*this.redFactor+e*this.greenFactor+r*this.blueFactor-this.baseShift}pack(t){return vl(t,this.getUnpackVector())}getPixels(){return new ll({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,a=r*this.dim+this.dim;switch(e){case -1:n=i-1;break;case 1:i=n+1;}switch(r){case -1:s=a-1;break;case 1:a=s+1;}const o=-e*this.dim,l=-r*this.dim;for(let e=s;e0)for(let i=e;i=e;i-=n)s=Zl(i/n|0,t[i],t[i+1],s);return s&&Ul(s,s.next)&&(Yl(s),s=s.next),s}function Ml(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!Ul(n,n.next)&&0!==Rl(n.prev,n,n.next))n=n.next;else {if(Yl(n),n=e=n.prev,n===n.next)break;r=!0;}}while(r||n!==e);return e}function Il(t,e,r,n,i,s,a){if(!t)return;!a&&s&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=Fl(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let s=null;for(e=0;i;){e++;let a=i,o=0;for(let t=0;t0||l>0&&a;)0!==o&&(0===l||!a||i.z<=a.z)?(n=i,i=i.nextZ,o--):(n=a,a=a.nextZ,l--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;i=a;}s.nextZ=null,r*=2;}while(e>1)}(i);}(t,n,i,s);let o=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?Pl(t,n,i,s):zl(t))e.push(l.i,t.i,u.i),Yl(t),t=u.next,o=u.next;else if((t=u)===o){a?1===a?Il(t=Cl(Ml(t),e),e,r,n,i,s,2):2===a&&El(t,e,r,n,i,s):Il(Ml(t),e,r,n,i,s,1);break}}}function zl(t){const e=t.prev,r=t,n=t.next;if(Rl(e,r,n)>=0)return !1;const i=e.x,s=r.x,a=n.x,o=e.y,l=r.y,u=n.y,c=Math.min(i,s,a),h=Math.min(o,l,u),p=Math.max(i,s,a),f=Math.max(o,l,u);let d=n.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&Ll(i,o,s,l,a,u,d.x,d.y)&&Rl(d.prev,d,d.next)>=0)return !1;d=d.next;}return !0}function Pl(t,e,r,n){const i=t.prev,s=t,a=t.next;if(Rl(i,s,a)>=0)return !1;const o=i.x,l=s.x,u=a.x,c=i.y,h=s.y,p=a.y,f=Math.min(o,l,u),d=Math.min(c,h,p),y=Math.max(o,l,u),m=Math.max(c,h,p),g=Fl(f,d,e,r,n),x=Fl(y,m,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}return !0}function Cl(t,e){let r=t;do{const n=r.prev,i=r.next.next;!Ul(n,i)&&jl(n,r,r.next,i)&&Gl(n,i)&&Gl(i,n)&&(e.push(n.i,r.i,i.i),Yl(r),Yl(r.next),r=t=i),r=r.next;}while(r!==t);return Ml(r)}function El(t,e,r,n,i,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Ol(a,t)){let o=Xl(a,t);return a=Ml(a,a.next),o=Ml(o,o.next),Il(a,e,r,n,i,s,0),void Il(o,e,r,n,i,s,0)}t=t.next;}a=a.next;}while(a!==t)}function Tl(t,e){let r=t.x-e.x;return 0===r&&(r=t.y-e.y,0===r)&&(r=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)),r}function Bl(t,e){const r=function(t,e){let r=e;const n=t.x,i=t.y;let s,a=-1/0;if(Ul(t,r))return r;do{if(Ul(t,r.next))return r.next;if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){const t=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(t<=n&&t>a&&(a=t,s=r.x=r.x&&r.x>=l&&n!==r.x&&Dl(is.x||r.x===s.x&&Vl(s,r)))&&(s=r,c=e);}r=r.next;}while(r!==o);return s}(t,e);if(!r)return e;const n=Xl(r,t);return Ml(n,n.next),Ml(r,r.next)}function Vl(t,e){return Rl(t.prev,t,e.prev)<0&&Rl(e.next,t,t.next)<0}function Fl(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function $l(t){let e=t,r=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(r-a)*(e-o)&&(r-a)*(s-o)>=(i-a)*(n-o)}function Ll(t,e,r,n,i,s,a,o){return !(t===a&&e===o)&&Dl(t,e,r,n,i,s,a,o)}function Ol(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&jl(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(Gl(t,e)&&Gl(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Rl(t.prev,t,e.prev)||Rl(t,e.prev,e))||Ul(t,e)&&Rl(t.prev,t,t.next)>0&&Rl(e.prev,e,e.next)>0)}function Rl(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Ul(t,e){return t.x===e.x&&t.y===e.y}function jl(t,e,r,n){const i=ql(Rl(t,e,r)),s=ql(Rl(t,e,n)),a=ql(Rl(r,n,t)),o=ql(Rl(r,n,e));return i!==s&&a!==o||!(0!==i||!Nl(t,r,e))||!(0!==s||!Nl(t,n,e))||!(0!==a||!Nl(r,t,n))||!(0!==o||!Nl(r,e,n))}function Nl(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function ql(t){return t>0?1:t<0?-1:0}function Gl(t,e){return Rl(t.prev,t,t.next)<0?Rl(t,e,t.next)>=0&&Rl(t,t.prev,e)>=0:Rl(t,e,t.prev)<0||Rl(t,t.next,e)<0}function Xl(t,e){const r=Hl(t.i,t.x,t.y),n=Hl(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function Zl(t,e,r,n){const i=Hl(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Yl(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 Hl(t,e,r){return {i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class Kl{constructor(t,e){if(e>t)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=t,this._minGranularity=e;}getGranularityForZoomLevel(t){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||e>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const r=0|Math.round(t),n=0|Math.round(e),i=this._getKey(r,n);if(this._vertexDictionary.has(i))return this._vertexDictionary.get(i);const s=this._vertexBuffer.length/2;return this._vertexDictionary.set(i,s),this._vertexBuffer.push(r,n),s}_subdivideTrianglesScanline(t){if(this._granularity<2)return function(t,e){const r=[];for(let n=0;n0?(r.push(i),r.push(a),r.push(s)):(r.push(i),r.push(s),r.push(a));}return r}(this._vertexBuffer,t);const e=[],r=t.length;for(let n=0;n=1||v<=0)||y&&(oi)){u>=n&&u<=i&&s.push(r[(t+1)%3]);continue}!y&&x>0&&s.push(this._vertexToIndex(a+p*x,o+f*x));const b=a+p*Math.max(x,0),w=a+p*Math.min(v,1);d||this._generateIntraEdgeVertices(s,a,o,l,u,b,w),!y&&v<1&&s.push(this._vertexToIndex(a+p*v,o+f*v)),(y||u>=n&&u<=i)&&s.push(r[(t+1)%3]),!y&&(u<=n||u>=i)&&this._generateInterEdgeVertices(s,a,o,l,u,c,h,w,n,i);}return s}_generateIntraEdgeVertices(t,e,r,n,i,s,a){const o=n-e,l=i-r,u=0===l,c=u?Math.min(e,n):Math.min(s,a),h=u?Math.max(e,n):Math.max(s,a),p=Math.floor(c/this._granularityCellSize)+1,f=Math.ceil(h/this._granularityCellSize)-1;if(u?e=p;n--){const i=n*this._granularityCellSize;t.push(this._vertexToIndex(i,r+l*(i-e)/o));}}_generateInterEdgeVertices(t,e,r,n,i,s,a,o,l,u){const c=i-r,h=s-n,p=a-i,f=(l-i)/p,d=(u-i)/p,y=Math.min(f,d),m=Math.max(f,d),g=n+h*y;let x=Math.floor(Math.min(g,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(g,o)/this._granularityCellSize)-1,b=o=1||m<=0){const t=r-a,n=s+(e-s)*Math.min((l-a)/t,(u-a)/t);x=Math.floor(Math.min(n,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(n,o)/this._granularityCellSize)-1,b=o0?u:l;if(b)for(let e=x;e<=v;e++)t.push(this._vertexToIndex(e*this._granularityCellSize,_));else for(let e=v;e>=x;e--)t.push(this._vertexToIndex(e*this._granularityCellSize,_));}_generateOutline(t){const e=[];for(const r of t){const t=ru(r,this._granularity,!0),n=this._pointArrayToIndices(t),i=[];for(let t=1;ti!=(s===Wl)?(t.push(e),t.push(r),t.push(this._vertexToIndex(n,s)),t.push(r),t.push(this._vertexToIndex(i,s)),t.push(this._vertexToIndex(n,s))):(t.push(r),t.push(e),t.push(this._vertexToIndex(n,s)),t.push(this._vertexToIndex(i,s)),t.push(r),t.push(this._vertexToIndex(n,s)));}_fillPoles(t,e,r){const n=this._vertexBuffer,i=P,s=t.length;for(let a=2;a80*r){o=t[0],l=t[1];let e=o,n=l;for(let s=r;se&&(e=r),i>n&&(n=i);}u=Math.max(e-o,n-l),u=0!==u?32767/u:0;}return Il(s,a,r,o,l,u,0),a}(r,n),e=this._convertIndices(r,t);i=this._subdivideTrianglesScanline(e);}catch(t){console.error(t);}let s=[];return e&&(s=this._generateOutline(t)),this._ensureNoPoleVertices(),this._handlePoles(i),{verticesFlattened:this._vertexBuffer,indicesTriangles:i,indicesLineList:s}}_convertIndices(t,e){const r=[];for(let n=0;n0?(Math.floor(x/o)+1)*o:(Math.ceil(x/o)-1)*o,e=y>0?(Math.floor(v/o)+1)*o:(Math.ceil(v/o)-1)*o,n=Math.abs(x-t),i=Math.abs(v-e),s=Math.abs(x-c),a=Math.abs(v-h),u=p?n/m:Number.POSITIVE_INFINITY,b=f?i/g:Number.POSITIVE_INFINITY;if((s<=n||!p)&&(a<=i||!f))break;if(u=0?a-1:s-1,i=(o+1)%s,l=t[2*e[n]],u=t[2*e[i]],c=t[2*e[a]],h=t[2*e[a]+1],p=t[2*e[o]+1];let f=!1;if(lu)f=!1;else {const r=p-h,s=-(t[2*e[o]]-c),a=h((u-c)*r+(t[2*e[i]+1]-h)*s)*a&&(f=!0);}if(f){const t=e[n],i=e[a],l=e[o];t!==i&&t!==l&&i!==l&&r.push(l,i,t),a--,a<0&&(a=s-1);}else {const t=e[i],n=e[a],l=e[o];t!==n&&t!==l&&n!==l&&r.push(l,n,t),o++,o>=s&&(o=0);}if(n===i)break}}function iu(t,e,r,n,i,s,a,o,l){const u=i.length/2,c=a&&o&&l;if(uZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,y=!0,m=!0,g=!0,c=0);const x=su(a,n,s,o,p,y,u),v=su(a,n,s,o,f,m,u),b=su(a,n,s,o,d,g,u);r.emplaceBack(c+x-l,c+v-l,c+b-l),u.primitiveLength++;}}(e,r,n,i,s,t),c&&function(t,e,r,n,i,s){const a=[];for(let t=0;tZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,d=!0,y=!0,c=0);const m=su(a,n,s,o,i,d,u),g=su(a,n,s,o,h,y,u);r.emplaceBack(c+m-l,c+g-l),u.primitiveLength++;}}}(a,r,o,i,l,t),e.forceNewSegmentOnNextPrepare(),null==a||a.forceNewSegmentOnNextPrepare();}function su(t,e,r,n,i,s,a){if(s){const s=n.count;return r(e[2*i],e[2*i+1]),t[i]=n.count,n.count++,a.vertexLength++,s}return t[i]}class au{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Ba,this.indexArray=new Na,this.indexArray2=new qa,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.segments2=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("fill",this.layers,e);const n=this.layers[0].layout.get("fill-sort-key"),i=!n.isConstant(),s=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=Io(a,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),c,r))continue;const h=i?n.evaluate(c,{},r,e.availableImages):void 0,p={id:o,properties:a.properties,type:a.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:Mo(a),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("fill",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,_l),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,r,n,i,s){for(const t of Qr(e,500)){const e=eu(t,n,s.fill.getGranularityForZoomLevel(n.z)),r=this.layoutVertexArray;iu(((t,e)=>{r.emplaceBack(t,e);}),this.segments,this.layoutVertexArray,this.indexArray,e.verticesFlattened,e.indicesTriangles,this.segments2,this.indexArray2,e.indicesLineList);}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}}let ou,lu;as("FillBucket",au,{omit:["layers","patternFeatures"]});var uu={get paint(){return lu=lu||new js({"fill-antialias":new Ds(xt.paint_fill["fill-antialias"]),"fill-opacity":new Ls(xt.paint_fill["fill-opacity"]),"fill-color":new Ls(xt.paint_fill["fill-color"]),"fill-outline-color":new Ls(xt.paint_fill["fill-outline-color"]),"fill-translate":new Ds(xt.paint_fill["fill-translate"]),"fill-translate-anchor":new Ds(xt.paint_fill["fill-translate-anchor"]),"fill-pattern":new Os(xt.paint_fill["fill-pattern"])})},get layout(){return ou=ou||new js({"fill-sort-key":new Ls(xt.layout_fill["fill-sort-key"])})}};class cu extends qs{constructor(t,e){super(t,uu,e);}recalculate(t,e){super.recalculate(t,e);const r=this.paint._values["fill-outline-color"];"constant"===r.value.kind&&void 0===r.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);}createBucket(t){return new au(t)}queryRadius(){return No(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:t,geometry:e,transform:r,pixelsToTileUnits:n}){return Bo(qo(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-r.bearingInRadians,n),e)}isTileClipped(){return !0}}const hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),pu=Ys([{name:"a_centroid",components:2,type:"Int16"}],4),{members:fu}=hu;class du{constructor(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this.id=void 0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(yu,this,e);}loadGeometry(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos,n=[];let i,s=1,a=0,o=0,l=0;for(;t.pos>3;}if(a--,1===s||2===s)o+=t.readSVarint(),l+=t.readSVarint(),1===s&&(i&&n.push(i),i=[]),i&&i.push(new r(o,l));else {if(7!==s)throw new Error(`unknown command ${s}`);i&&i.push(i[0].clone());}}return i&&n.push(i),n}bbox(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos;let r=1,n=0,i=0,s=0,a=1/0,o=-1/0,l=1/0,u=-1/0;for(;t.pos>3;}if(n--,1===r||2===r)i+=t.readSVarint(),s+=t.readSVarint(),io&&(o=i),su&&(u=s);else if(7!==r)throw new Error(`unknown command ${r}`)}return [a,l,o,u]}toGeoJSON(t,e,r){const n=this.extent*Math.pow(2,r),i=this.extent*t,s=this.extent*e,a=this.loadGeometry();function o(t){return [360*(t.x+i)/n-180,360/Math.PI*Math.atan(Math.exp((1-2*(t.y+s)/n)*Math.PI))-90]}function l(t){return t.map(o)}let u;if(1===this.type){const t=[];for(const e of a)t.push(e[0]);const e=l(t);u=1===t.length?{type:"Point",coordinates:e[0]}:{type:"MultiPoint",coordinates:e};}else if(2===this.type){const t=a.map(l);u=1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t};}else {if(3!==this.type)throw new Error("unknown feature type");{const t=function(t){const e=t.length;if(e<=1)return [t];const r=[];let n,i;for(let s=0;s=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];const e=this._pbf.readVarint()+this._pbf.pos;return new du(this._pbf,e,this.extent,this._keys,this._values)}}function xu(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){let e=null;const r=t.readVarint()+t.pos;for(;t.pos>3;e=1===r?t.readString():2===r?t.readFloat():3===r?t.readDouble():4===r?t.readVarint64():5===r?t.readVarint():6===r?t.readSVarint():7===r?t.readBoolean():null;}if(null==e)throw new Error("unknown feature value");return e}(r));}class vu{constructor(t,e){this.layers=t.readFields(bu,{},e);}}function bu(t,e,r){if(3===t){const t=new gu(r,r.readVarint()+r.pos);t.length&&(e[t.name]=t);}}const wu=Math.pow(2,13);function _u(t,e,r,n,i,s,a,o){t.emplaceBack(e,r,2*Math.floor(n*wu)+a,i*wu*2,s*wu*2,Math.round(o));}class Su{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Va,this.centroidVertexArray=new Ea,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.features=[],this.hasPattern=Sl("fill-extrusion",this.layers,e);for(const{feature:n,id:i,index:s,sourceLayerIndex:a}of t){const t=this.layers[0]._featureFilter.needGeometry,o=Io(n,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),o,r))continue;const l={id:i,sourceLayerIndex:a,index:s,geometry:t?o.geometry:Mo(n),properties:n.properties,type:n.type,patterns:{}};this.hasPattern?this.features.push(Al("fill-extrusion",this.layers,l,{zoom:this.zoom},e)):this.addFeature(l,l.geometry,s,r,{},e.subdivisionGranularity),e.featureIndex.insert(n,l.geometry,s,a,this.index,!0);}}addFeatures(t,e,r){for(const n of this.features){const{geometry:i}=n;this.addFeature(n,i,n.index,e,r,t.subdivisionGranularity);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,fu),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,pu.members,!0),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy());}addFeature(t,e,r,n,i,s){for(const r of Qr(e,500)){const e={x:0,y:0,sampleCount:0},i=this.layoutVertexArray.length;this.processPolygon(e,n,t,r,s);const a=this.layoutVertexArray.length-i,o=Math.floor(e.x/e.sampleCount),l=Math.floor(e.y/e.sampleCount);for(let t=0;t{_u(u,t,e,0,0,1,1,0);}),this.segments,this.layoutVertexArray,this.indexArray,l.verticesFlattened,l.indicesTriangles);}_generateSideFaces(t,e){let r=0;for(let n=1;nZa.MAX_VERTEX_ARRAY_LENGTH&&(e.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const a=i.sub(s)._perp()._unit(),o=s.dist(i);r+o>32768&&(r=0),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,1,r),r+=o,_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,1,r);const l=e.segment.vertexLength;this.indexArray.emplaceBack(l,l+2,l+1),this.indexArray.emplaceBack(l+1,l+2,l+3),e.segment.vertexLength+=4,e.segment.primitiveLength+=2;}}}function Au(t,e){for(let r=0;rP)||t.y===e.y&&(t.y<0||t.y>P)}function Mu(t){return t.every((t=>t.x<0))||t.every((t=>t.x>P))||t.every((t=>t.y<0))||t.every((t=>t.y>P))}let Iu;as("FillExtrusionBucket",Su,{omit:["layers","features"]});var zu={get paint(){return Iu=Iu||new js({"fill-extrusion-opacity":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Os(xt["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class Pu extends qs{constructor(t,e){super(t,zu,e);}createBucket(t){return new Su(t)}queryRadius(){return No(this.paint.get("fill-extrusion-translate"))}is3D(){return !0}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a,pixelPosMatrix:o}){const l=qo(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-s.bearingInRadians,a),u=this.paint.get("fill-extrusion-height").evaluate(e,n),c=this.paint.get("fill-extrusion-base").evaluate(e,n),h=function(t,e){const n=[];for(const i of t){const t=[i.x,i.y,0,1];A(t,t,e),n.push(new r(t[0]/t[3],t[1]/t[3]));}return n}(l,o),p=function(t,e,n,i){const s=[],a=[],o=i[8]*e,l=i[9]*e,u=i[10]*e,c=i[11]*e,h=i[8]*n,p=i[9]*n,f=i[10]*n,d=i[11]*n;for(const e of t){const t=[],n=[];for(const s of e){const e=s.x,a=s.y,y=i[0]*e+i[4]*a+i[12],m=i[1]*e+i[5]*a+i[13],g=i[2]*e+i[6]*a+i[14],x=i[3]*e+i[7]*a+i[15],v=g+u,b=x+c,w=y+h,_=m+p,S=g+f,A=x+d,k=new r((y+o)/b,(m+l)/b);k.z=v/b,t.push(k);const M=new r(w/A,_/A);M.z=S/A,n.push(M);}s.push(t),a.push(n);}return [s,a]}(i,c,u,o);return function(t,e,r){let n=1/0;Bo(r,e)&&(n=Eu(r,e[0]));for(let i=0;it.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new Fa,this.layoutVertexArray2=new $a,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("line",this.layers,e);const n=this.layers[0].layout.get("line-sort-key"),i=!n.isConstant(),s=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=i?n.evaluate(u,{},r):void 0,h={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("line",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,Fu)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Bu),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return {start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i,s){const a=this.layers[0].layout,o=a.get("line-join").evaluate(t,{}),l=a.get("line-cap"),u=a.get("line-miter-limit"),c=a.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,o,l,u,c,n,s);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}addLine(t,e,r,n,i,s,a,o){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,t=ru(t,a?o.line.getGranularityForZoomLevel(a.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[u-1].equals(t[u-2]);)u--;let c=0;for(;c0;if(w&&e>c){const t=f.dist(d);if(t>2*h){const e=f.sub(f.sub(d)._mult(h/t)._round());this.updateDistance(d,e),this.addCurrentVertex(e,m,0,0,p),d=e;}}const S=d&&y;let A=S?r:l?"butt":n;if(S&&"round"===A&&(vi&&(A="bevel"),"bevel"===A&&(v>2&&(A="flipbevel"),v100)a=g.mult(-1);else {const t=v*m.add(g).mag()/m.sub(g).mag();a._perp()._mult(t*(_?-1:1));}this.addCurrentVertex(f,a,0,0,p),this.addCurrentVertex(f,a.mult(-1),0,0,p);}else if("bevel"===A||"fakeround"===A){const t=-Math.sqrt(v*v-1),e=_?t:0,r=_?0:t;if(d&&this.addCurrentVertex(f,m,e,r,p),"fakeround"===A){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*h){const e=f.add(y.sub(f)._mult(h/t)._round());this.updateDistance(f,e),this.addCurrentVertex(e,g,0,0,p),f=e;}}}}addCurrentVertex(t,e,r,n,i,s=!1){const a=e.y*n-e.x,o=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,!1,r,i),this.addHalfVertex(t,a,o,s,!0,-n,i),this.distance>Du/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,r,n,i,s));}addHalfVertex({x:t,y:e},r,n,i,s,a,o){const l=.5*(this.lineClips?this.scaledDistance*(Du-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,u,this.e2),o.primitiveLength++),s?this.e2=u:this.e1=u;}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}}let Ou,Ru;as("LineBucket",Lu,{omit:["layers","patternFeatures"]});var Uu={get paint(){return Ru=Ru||new js({"line-opacity":new Ls(xt.paint_line["line-opacity"]),"line-color":new Ls(xt.paint_line["line-color"]),"line-translate":new Ds(xt.paint_line["line-translate"]),"line-translate-anchor":new Ds(xt.paint_line["line-translate-anchor"]),"line-width":new Ls(xt.paint_line["line-width"]),"line-gap-width":new Ls(xt.paint_line["line-gap-width"]),"line-offset":new Ls(xt.paint_line["line-offset"]),"line-blur":new Ls(xt.paint_line["line-blur"]),"line-dasharray":new Rs(xt.paint_line["line-dasharray"]),"line-pattern":new Os(xt.paint_line["line-pattern"]),"line-gradient":new Us(xt.paint_line["line-gradient"])})},get layout(){return Ou=Ou||new js({"line-cap":new Ds(xt.layout_line["line-cap"]),"line-join":new Ls(xt.layout_line["line-join"]),"line-miter-limit":new Ds(xt.layout_line["line-miter-limit"]),"line-round-limit":new Ds(xt.layout_line["line-round-limit"]),"line-sort-key":new Ls(xt.layout_line["line-sort-key"])})}};class ju extends Ls{possiblyEvaluate(t,e){return e=new Is(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=L({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}let Nu;class qu extends qs{constructor(t,e){super(t,Uu,e),this.gradientVersion=0,Nu||(Nu=new ju(Uu.paint.properties["line-width"].specification),Nu.useIntegerZoom=!0);}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return void 0!==t._styleExpression}(t)&&t._styleExpression.expression instanceof ar,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=Nu.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t);}createBucket(t){return new Lu(t)}queryRadius(t){const e=t,r=Gu(jo("line-width",this,e),jo("line-gap-width",this,e)),n=jo("line-offset",this,e);return r/2+Math.abs(n)+No(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a}){const o=qo(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-s.bearingInRadians,a),l=a/2*Gu(this.paint.get("line-width").evaluate(e,n),this.paint.get("line-gap-width").evaluate(e,n)),u=this.paint.get("line-offset").evaluate(e,n);return u&&(i=function(t,e){const n=[];for(let i=0;i=3)for(let e=0;e0?e+2*t:t}const Xu=Ys([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Zu=Ys([{name:"a_projected_pos",components:3,type:"Float32"}],4);Ys([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Yu=Ys([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Ys([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const Hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Ku=Ys([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Ju(t,e,r){return t.sections.forEach((t=>{t.text=function(t,e,r){const n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Ms.applyArabicShaping&&(t=Ms.applyArabicShaping(t)),t}(t.text,e,r);})),t}Ys([{name:"triangle",components:3,type:"Uint16"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Ys([{type:"Float32",name:"offsetX"}]),Ys([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Ys([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const Wu={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Qu=24;const tc=4294967296,ec=1/tc,rc="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class nc{constructor(t=new Uint8Array(16)){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length;}readFields(t,e,r=this.length){for(;this.pos>3,i=this.pos;this.type=7&r,t(n,e,this),this.pos===i&&this.skip(r);}return e}readMessage(t,e){return this.readFields(t,e,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*tc;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*tc;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const e=this.buf;let r,n;return n=e[this.pos++],r=127&n,n<128?r:(n=e[this.pos++],r|=(127&n)<<7,n<128?r:(n=e[this.pos++],r|=(127&n)<<14,n<128?r:(n=e[this.pos++],r|=(127&n)<<21,n<128?r:(n=e[this.pos],r|=(15&n)<<28,function(t,e,r){const n=r.buf;let i,s;if(s=n[r.pos++],i=(112&s)>>4,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<3,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<10,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<17,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<24,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(1&s)<<31,s<128)return ic(t,i,e);throw new Error("Expected varint not more than 10 bytes")}(r,t,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2==1?(t+1)/-2:t/2}readBoolean(){return Boolean(this.readVarint())}readString(){const t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&rc?rc.decode(this.buf.subarray(e,t)):function(t,e,r){let n="",i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+u>r)break;1===u?e<128&&(l=e):2===u?(s=t[i+1],128==(192&s)&&(l=(31&e)<<6|63&s,l<=127&&(l=null))):3===u?(s=t[i+1],a=t[i+2],128==(192&s)&&128==(192&a)&&(l=(15&e)<<12|(63&s)<<6|63&a,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===u&&(s=t[i+1],a=t[i+2],o=t[i+3],128==(192&s)&&128==(192&a)&&128==(192&o)&&(l=(15&e)<<18|(63&s)<<12|(63&a)<<6|63&o,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,u=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=u;}return n}(this.buf,e,t)}readBytes(){const t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e}readPackedVarint(t=[],e){const r=this.readPackedEnd();for(;this.pos127;);else if(2===e)this.pos=this.readVarint()+this.pos;else if(5===e)this.pos+=4;else {if(1!==e)throw new Error(`Unimplemented type: ${e}`);this.pos+=8;}}writeTag(t,e){this.writeVarint(t<<3|e);}realloc(t){let e=this.length||16;for(;e268435455||t<0?function(t,e){let r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(r=~(-t%4294967296),n=~(-t/4294967296),4294967295^r?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){const r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(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(t){this.writeVarint(t<0?2*-t-1:2*t);}writeBoolean(t){this.writeVarint(+t);}writeString(t){t=String(t),this.realloc(4*t.length),this.pos++;const e=this.pos;this.pos=function(t,e,r){for(let n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);const r=this.pos-e;r>=128&&sc(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4;}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8;}writeBytes(t){const e=t.length;this.writeVarint(e),this.realloc(e);for(let r=0;r=128&&sc(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;}writeMessage(t,e,r){this.writeTag(t,2),this.writeRawMessage(e,r);}writePackedVarint(t,e){e.length&&this.writeMessage(t,ac,e);}writePackedSVarint(t,e){e.length&&this.writeMessage(t,oc,e);}writePackedBoolean(t,e){e.length&&this.writeMessage(t,cc,e);}writePackedFloat(t,e){e.length&&this.writeMessage(t,lc,e);}writePackedDouble(t,e){e.length&&this.writeMessage(t,uc,e);}writePackedFixed32(t,e){e.length&&this.writeMessage(t,hc,e);}writePackedSFixed32(t,e){e.length&&this.writeMessage(t,pc,e);}writePackedFixed64(t,e){e.length&&this.writeMessage(t,fc,e);}writePackedSFixed64(t,e){e.length&&this.writeMessage(t,dc,e);}writeBytesField(t,e){this.writeTag(t,2),this.writeBytes(e);}writeFixed32Field(t,e){this.writeTag(t,5),this.writeFixed32(e);}writeSFixed32Field(t,e){this.writeTag(t,5),this.writeSFixed32(e);}writeFixed64Field(t,e){this.writeTag(t,1),this.writeFixed64(e);}writeSFixed64Field(t,e){this.writeTag(t,1),this.writeSFixed64(e);}writeVarintField(t,e){this.writeTag(t,0),this.writeVarint(e);}writeSVarintField(t,e){this.writeTag(t,0),this.writeSVarint(e);}writeStringField(t,e){this.writeTag(t,2),this.writeString(e);}writeFloatField(t,e){this.writeTag(t,5),this.writeFloat(e);}writeDoubleField(t,e){this.writeTag(t,1),this.writeDouble(e);}writeBooleanField(t,e){this.writeVarintField(t,+e);}}function ic(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function sc(t,e,r){const n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(let e=r.pos-1;e>=t;e--)r.buf[e+n]=r.buf[e];}function ac(t,e){for(let r=0;re.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();e&&t=0&&r>=t&&kc[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e);}substring(t,e){const r=new Sc;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}getMaxImageSize(t){let e=0,r=0;for(let n=0;n=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Ac(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=Sc.fromFeature(e,s);let g;p===t.ao.vertical&&m.verticalizePunctuation();const{processBidirectionalText:x,processStyledBidirectionalText:v}=Ms;if(x&&1===m.sections.length){g=[];const t=x(m.toString(),Bc(m,c,a,r,i,d));for(const e of t){const t=new Sc;t.text=e,t.sections=m.sections;for(let r=0;r=0;let u=0;for(let r=0;ru){const t=Math.ceil(s/u);i*=t/a,a=t;}return {x1:n,y1:i,x2:n+s,y2:i+a}}function Nc(t,e,r,n,i,s){const a=t.image;let o;if(a.content){const t=a.content,e=a.pixelRatio||1;o=[t[0]/e,t[1]/e,a.displaySize[0]-t[2]/e,a.displaySize[1]-t[3]/e];}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===r||"both"===r?(f=i[0]+l-n[3],h=i[0]+u+n[1]):(f=i[0]+(l+u-a.displaySize[0])/2,h=f+a.displaySize[0]);const d=e.top*s,y=e.bottom*s;return "height"===r||"both"===r?(c=i[1]+d-n[0],p=i[1]+y+n[2]):(c=i[1]+(d+y-a.displaySize[1])/2,p=c+a.displaySize[1]),{image:a,top:c,right:h,bottom:p,left:f,collisionPadding:o}}const qc=128,Gc=32640;function Xc(t,e){const{expression:r}=e;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new Is(t+1))};if("source"===r.kind)return {kind:"source"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;it.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];const r=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Xc(this.zoom,r["text-size"]),this.iconSizeData=Xc(this.zoom,r["icon-size"]);const n=this.layers[0].layout,i=n.get("symbol-sort-key"),s=n.get("symbol-z-order");this.canOverlap="never"!==Zc(n,"text-overlap","text-allow-overlap")||"never"!==Zc(n,"icon-overlap","icon-allow-overlap")||n.get("text-ignore-placement")||n.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!i.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===n.get("symbol-placement")&&(this.writingModes=n.get("text-writing-mode").map((e=>t.ao[e]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID;}createArrays(){this.text=new Wc(new wo(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new Wc(new wo(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new ka,this.lineVertexArray=new Ma,this.symbolInstances=new Aa,this.textAnchorOffsets=new za;}calculateGlyphDependencies(t,e,r,n,i){for(let s=0;s0)&&("constant"!==a.value.kind||a.value.value.length>0),c="constant"!==l.value.kind||!!l.value.value||Object.keys(l.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!u&&!c)return;const p=r.iconDependencies,f=r.glyphDependencies,d=r.availableImages,y=new Is(this.zoom);for(const{feature:r,id:o,index:l,sourceLayerIndex:m}of e){const e=i._featureFilter.needGeometry,g=Io(r,e);if(!i._featureFilter.filter(y,g,n))continue;let x,v;if(e||(g.geometry=Mo(r)),u){const t=i.getValueAndResolveTokens("text-field",g,n,d),e=Ce.factory(t),r=this.hasRTLText=this.hasRTLText||Jc(e);(!r||"unavailable"===Ms.getRTLTextPluginStatus()||r&&Ms.isParsed())&&(x=Ju(e,i,g));}if(c){const t=i.getValueAndResolveTokens("icon-image",g,n,d);v=t instanceof De?t:De.fromString(t);}if(!x&&!v)continue;const b=this.sortFeaturesByKey?h.evaluate(g,{},n):void 0;if(this.features.push({id:o,text:x,icon:v,index:l,sourceLayerIndex:m,geometry:g.geometry,properties:r.properties,type:du.types[r.type],sortKey:b}),v&&(p[v.name]=!0),x){const e=a.evaluate(g,{},n).join(","),r="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(t.ao.vertical)>=0;for(const t of x.sections)if(t.image)p[t.image.name]=!0;else {const n=ds(x.toString()),i=t.fontStack||e,s=f[i]=f[i]||{};this.calculateGlyphDependencies(t.text,s,r,this.allowVerticalPlacement,n);}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++;}function a(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function o(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return `${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}));}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(void 0!==t.segment){let r=t.dist(e[t.segment+1]),n=t.dist(e[t.segment]);const i={};for(let n=t.segment+1;n=0;r--)i[r]={x:e[r].x,y:e[r].y,tileUnitDistanceFromAnchor:n},r>0&&(n+=e[r-1].dist(e[r]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,r)=>{t>=0&&r.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t);})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}let eh,rh;as("SymbolBucket",th,{omit:["layers","collisionBoxArray","features","compareText"]}),th.MAX_GLYPHS=65535,th.addDynamicAttributes=Kc;var nh={get paint(){return rh=rh||new js({"icon-opacity":new Ls(xt.paint_symbol["icon-opacity"]),"icon-color":new Ls(xt.paint_symbol["icon-color"]),"icon-halo-color":new Ls(xt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Ls(xt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Ls(xt.paint_symbol["icon-halo-blur"]),"icon-translate":new Ds(xt.paint_symbol["icon-translate"]),"icon-translate-anchor":new Ds(xt.paint_symbol["icon-translate-anchor"]),"text-opacity":new Ls(xt.paint_symbol["text-opacity"]),"text-color":new Ls(xt.paint_symbol["text-color"],{runtimeType:Lt,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new Ls(xt.paint_symbol["text-halo-color"]),"text-halo-width":new Ls(xt.paint_symbol["text-halo-width"]),"text-halo-blur":new Ls(xt.paint_symbol["text-halo-blur"]),"text-translate":new Ds(xt.paint_symbol["text-translate"]),"text-translate-anchor":new Ds(xt.paint_symbol["text-translate-anchor"])})},get layout(){return eh=eh||new js({"symbol-placement":new Ds(xt.layout_symbol["symbol-placement"]),"symbol-spacing":new Ds(xt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Ds(xt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Ls(xt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Ds(xt.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new Ds(xt.layout_symbol["icon-allow-overlap"]),"icon-overlap":new Ds(xt.layout_symbol["icon-overlap"]),"icon-ignore-placement":new Ds(xt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Ds(xt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Ds(xt.layout_symbol["icon-rotation-alignment"]),"icon-size":new Ls(xt.layout_symbol["icon-size"]),"icon-text-fit":new Ds(xt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Ds(xt.layout_symbol["icon-text-fit-padding"]),"icon-image":new Ls(xt.layout_symbol["icon-image"]),"icon-rotate":new Ls(xt.layout_symbol["icon-rotate"]),"icon-padding":new Ls(xt.layout_symbol["icon-padding"]),"icon-keep-upright":new Ds(xt.layout_symbol["icon-keep-upright"]),"icon-offset":new Ls(xt.layout_symbol["icon-offset"]),"icon-anchor":new Ls(xt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Ds(xt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Ds(xt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Ds(xt.layout_symbol["text-rotation-alignment"]),"text-field":new Ls(xt.layout_symbol["text-field"]),"text-font":new Ls(xt.layout_symbol["text-font"]),"text-size":new Ls(xt.layout_symbol["text-size"]),"text-max-width":new Ls(xt.layout_symbol["text-max-width"]),"text-line-height":new Ds(xt.layout_symbol["text-line-height"]),"text-letter-spacing":new Ls(xt.layout_symbol["text-letter-spacing"]),"text-justify":new Ls(xt.layout_symbol["text-justify"]),"text-radial-offset":new Ls(xt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Ds(xt.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Ls(xt.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Ls(xt.layout_symbol["text-anchor"]),"text-max-angle":new Ds(xt.layout_symbol["text-max-angle"]),"text-writing-mode":new Ds(xt.layout_symbol["text-writing-mode"]),"text-rotate":new Ls(xt.layout_symbol["text-rotate"]),"text-padding":new Ds(xt.layout_symbol["text-padding"]),"text-keep-upright":new Ds(xt.layout_symbol["text-keep-upright"]),"text-transform":new Ls(xt.layout_symbol["text-transform"]),"text-offset":new Ls(xt.layout_symbol["text-offset"]),"text-allow-overlap":new Ds(xt.layout_symbol["text-allow-overlap"]),"text-overlap":new Ds(xt.layout_symbol["text-overlap"]),"text-ignore-placement":new Ds(xt.layout_symbol["text-ignore-placement"]),"text-optional":new Ds(xt.layout_symbol["text-optional"])})}};class ih{constructor(t){if(void 0===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:Vt,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return !1}serialize(){return null}}as("FormatSectionOverride",ih,{omit:["defaultValue"]});class sh extends qs{constructor(t,e){super(t,nh,e);}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const r of t)e.indexOf(r)<0&&e.push(r);this.layout._values["text-writing-mode"]=e;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||ei(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>t&&r in t?String(t[r]):""))}(e.properties,i)}createBucket(t){return new th(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of nh.paint.overridableProperties){if(!sh.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new ih(e),n=new ti(r,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new ni("source",n):new ii("composite",n,e.value.zoomStops),this.paint._values[t]=new Fs(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,r){return !(!this.layout||e.isDataDriven()||r.isDataDriven())&&sh.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get("text-field"),n=nh.paint.properties[e];let i=!1;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=!0)};if("constant"===r.value.kind&&r.value.value instanceof Ce)s(r.value.value.sections);else if("source"===r.value.kind||"composite"===r.value.kind){const t=e=>{i||(e instanceof Ne&&Ue(e.value)===Nt?s(e.value.sections):e instanceof Ir?s(e.sections):e.eachChild(t));},e=r.value;e._styleExpression&&t(e._styleExpression.expression);}return i}}let ah;var oh={get paint(){return ah=ah||new js({"background-color":new Ds(xt.paint_background["background-color"]),"background-pattern":new Rs(xt.paint_background["background-pattern"]),"background-opacity":new Ds(xt.paint_background["background-opacity"])})}};class lh extends qs{constructor(t,e){super(t,oh,e);}}let uh;var ch={get paint(){return uh=uh||new js({"raster-opacity":new Ds(xt.paint_raster["raster-opacity"]),"raster-hue-rotate":new Ds(xt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Ds(xt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Ds(xt.paint_raster["raster-brightness-max"]),"raster-saturation":new Ds(xt.paint_raster["raster-saturation"]),"raster-contrast":new Ds(xt.paint_raster["raster-contrast"]),"raster-resampling":new Ds(xt.paint_raster["raster-resampling"]),"raster-fade-duration":new Ds(xt.paint_raster["raster-fade-duration"])})}};class hh extends qs{constructor(t,e){super(t,ch,e);}}class ph extends qs{constructor(t,e){super(t,{},e),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},this.implementation=t;}is3D(){return "3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return !1}serialize(){throw new Error("Custom layers cannot be serialized")}}class fh{constructor(t){this._methodToThrottle=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle();});}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle();}),0));}remove(){delete this._channel,this._methodToThrottle=()=>{};}}const dh={once:!0},yh=6371008.8;class mh{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new mh(D(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return yh*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof mh)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new mh(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new mh(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const gh=2*Math.PI*yh;function xh(t){return gh*Math.cos(t*Math.PI/180)}function vh(t){return (180+t)/360}function bh(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function wh(t,e){return t/xh(e)}function _h(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}function Sh(t,e){return t*xh(_h(e))}class Ah{constructor(t,e,r=0){this.x=+t,this.y=+e,this.z=+r;}static fromLngLat(t,e=0){const r=mh.convert(t);return new Ah(vh(r.lng),bh(r.lat),wh(e,r.lat))}toLngLat(){return new mh(360*this.x-180,_h(this.y))}toAltitude(){return Sh(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/gh*(t=_h(this.y),1/Math.cos(t*Math.PI/180));var t;}}function kh(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}class Mh{constructor(t,e,r){if(!function(t,e,r){return !(t<0||t>25||r<0||r>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,r))throw new Error(`x=${e}, y=${r}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=r,this.key=Ph(0,t,t,e,r);}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,r){const n=(s=this.y,a=this.z,o=kh(256*(i=this.x),256*(s=Math.pow(2,a)-s-1),a),l=kh(256*(i+1),256*(s+1),a),o[0]+","+o[1]+","+l[0]+","+l[1]);var i,s,a,o,l;const u=function(t,e,r){let n,i="";for(let s=t;s>0;s--)n=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,n)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new r((t.x*e-this.x)*P,(t.y*e-this.y)*P)}toString(){return `${this.z}/${this.x}/${this.y}`}}class Ih{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Ph(t,e.z,e.z,e.x,e.y);}}class zh{constructor(t,e,r,n,i){if(this.terrainRttPosMatrix32f=null,t= z; overscaledZ = ${t}; z = ${r}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Mh(r,+n,+i),this.key=Ph(e,t,r,n,i);}clone(){return new zh(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new zh(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new zh(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const r=this.canonical.z-t;return t>this.canonical.z?Ph(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Ph(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}isChildOf(t){if(t.wrap!==this.wrap)return !1;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new zh(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new zh(e,this.wrap,e,r,n),new zh(e,this.wrap,e,r+1,n),new zh(e,this.wrap,e,r,n+1),new zh(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.ythis.maxX||this.minY>this.maxY)&&(this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0),this}shrinkBy(t){return this.expandBy(-t)}map(t){const e=new Eh;return e.extend(t(new r(this.minX,this.minY))),e.extend(t(new r(this.maxX,this.minY))),e.extend(t(new r(this.minX,this.maxY))),e.extend(t(new r(this.maxX,this.maxY))),e}static fromPoints(t){const e=new Eh;for(const r of t)e.extend(r);return e}contains(t){return t.x>=this.minX&&t.x<=this.maxX&&t.y>=this.minY&&t.y<=this.maxY}empty(){return this.minX>this.maxX}width(){return this.maxX-this.minX}height(){return this.maxY-this.minY}covers(t){return !this.empty()&&!t.empty()&&t.minX>=this.minX&&t.maxX<=this.maxX&&t.minY>=this.minY&&t.maxY<=this.maxY}intersects(t){return !this.empty()&&!t.empty()&&t.minX<=this.maxX&&t.maxX>=this.minX&&t.minY<=this.maxY&&t.maxY>=this.minY}}class Th{constructor(t){this._stringToNumber={},this._numberToString=[];for(let e=0;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class Bh{constructor(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}class Vh{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new is(P,16,0),this.grid3D=new is(P,16,0),this.featureIndexArray=new Ca,this.promoteId=e;}insert(t,e,r,n,i,s){const a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);const o=s?this.grid3D:this.grid;for(let t=0;t=0&&n[3]>=0&&o.insert(a,n[0],n[1],n[2],n[3]);}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new vu(new nc(this.rawTileData)).layers,this.sourceLayerCoder=new Th(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,n,i){this.loadVTLayers();const s=t.params,a=P/t.tileSize/t.scale,o=hi(s.filter,s.globalState),l=t.queryGeometry,u=t.queryPadding*a,c=Eh.fromPoints(l),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=Eh.fromPoints(t.cameraQueryGeometry).expandBy(u),f=this.grid3D.query(p.minX,p.minY,p.maxX,p.maxY,((e,n,i,s)=>function(t,e,n,i,s){for(const r of t)if(e<=r.x&&n<=r.y&&i>=r.x&&s>=r.y)return !0;const a=[new r(e,n),new r(e,s),new r(i,s),new r(i,n)];if(t.length>2)for(const e of a)if(Ro(t,e))return !0;for(let e=0;e(p||(p=Mo(e)),r.queryIntersectsFeature({queryGeometry:l,feature:e,featureState:n,geometry:p,zoom:this.z,transform:t.transform,pixelsToTileUnits:a,pixelPosMatrix:t.pixelPosMatrix,unwrappedTileID:this.tileID.toUnwrapped(),getElevation:t.getElevation}))));}return d}loadMatchingFeature(t,e,r,n,i,s,a,o,l,u,c){const h=this.bucketLayerIDs[e];if(s&&!h.some((t=>s.has(t))))return;const p=this.sourceLayerCoder.decode(r),f=this.vtLayers[p].feature(n);if(i.needGeometry){const t=Io(f,!0);if(!i.filter(new Is(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new Is(this.tileID.overscaledZ),f))return;const d=this.getId(f,p);for(let e=0;e{const a=e instanceof $s?e.get(s):null;return a&&a.evaluate?a.evaluate(r,n,i):a}))}function $h(t,e){return e-t}function Dh(t,e,n,i,s){const a=[];for(let o=0;o=i&&c.x>=i||(o.x>=i?o=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round():c.x>=i&&(c=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round()),o.y>=s&&c.y>=s||(o.y>=s?o=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round():c.y>=s&&(c=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round()),u&&o.equals(u[u.length-1])||(u=[o],a.push(u)),u.push(c)))));}}return a}as("FeatureIndex",Vh,{omit:["rawTileData","sourceLayerCoder"]});class Lh extends r{constructor(t,e,r,n){super(t,e),this.angle=r,void 0!==n&&(this.segment=n);}clone(){return new Lh(this.x,this.y,this.angle,this.segment)}}function Oh(t,e,r,n,i){if(void 0===e.segment||0===r)return !0;let s=e,a=e.segment+1,o=0;for(;o>-r/2;){if(a--,a<0)return !1;o-=t[a].dist(s),s=t[a];}o+=t[a].dist(t[a+1]),a++;const l=[];let u=0;for(;on;)u-=l.shift().angleDelta;if(u>i)return !1;a++,o+=e.dist(r);}return !0}function Rh(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=dr.number(n.x,i.x,c),p=dr.number(n.y,i.y,c),f=new Lh(h,p,i.angleTo(n),r);return f._round(),!a||Oh(t,f,o,a,e)?f:void 0}l+=s;}}function qh(t,e,r,n,i,s,a,o,l){const u=Uh(n,s,a),c=jh(n,i),h=c*a,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new Lh(g,x,y,e);r._round(),n&&!Oh(t,r,s,n,i)||f.push(r);}}h+=d;}return o||f.length||a||(f=Gh(t,h/2,r,n,i,s,a,!0,l)),f}function Xh(t,e,n,i){const s=[],a=t.image,o=a.pixelRatio,l=a.paddedRect.w-2,u=a.paddedRect.h-2;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=a.stretchX||[[0,l]],p=a.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=l-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,S=m,A=0,k=g;if(a.content&&i){const e=a.content,r=e[2]-e[0],n=e[3]-e[1];(a.textFitWidth||a.textFitHeight)&&(c=jc(t)),x=Zh(h,0,e[0]),b=Zh(p,0,e[1]),v=Zh(h,e[0],e[2]),w=Zh(p,e[1],e[3]),_=e[0]-x,A=e[1]-b,S=r-v,k=n-w;}const M=c.x1,I=c.y1,z=c.x2-M,P=c.y2-I,C=(t,i,s,l)=>{const u=Hh(t.stretch-x,v,z,M),c=Kh(t.fixed-_,S,t.stretch,d),h=Hh(i.stretch-b,w,P,I),p=Kh(i.fixed-A,k,i.stretch,y),f=Hh(s.stretch-x,v,z,M),m=Kh(s.fixed-_,S,s.stretch,d),g=Hh(l.stretch-b,w,P,I),C=Kh(l.fixed-A,k,l.stretch,y),E=new r(u,h),T=new r(f,h),B=new r(f,g),V=new r(u,g),F=new r(c/o,p/o),$=new r(m/o,C/o),D=e*Math.PI/180;if(D){const t=Math.sin(D),e=Math.cos(D),r=[e,-t,t,e];E._matMult(r),T._matMult(r),V._matMult(r),B._matMult(r);}const L=t.stretch+t.fixed,O=i.stretch+i.fixed;return {tl:E,tr:T,bl:V,br:B,tex:{x:a.paddedRect.x+1+L,y:a.paddedRect.y+1+O,w:s.stretch+s.fixed-L,h:l.stretch+l.fixed-O},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:F,pixelOffsetBR:$,minFontScaleX:S/o/z,minFontScaleY:k/o/P,isSDF:n}};if(i&&(a.stretchX||a.stretchY)){const t=Yh(h,m,d),e=Yh(p,g,y);for(let r=0;r0&&(n=Math.max(10,n),this.circleDiameter=n);}else {const u=(null===(h=a.image)||void 0===h?void 0:h.content)&&(a.image.textFitWidth||a.image.textFitHeight)?jc(a):{x1:a.left,y1:a.top,x2:a.right,y2:a.bottom};u.y1=u.y1*o-l[0],u.y2=u.y2*o+l[2],u.x1=u.x1*o-l[3],u.x2=u.x2*o+l[1];const p=a.collisionPadding;if(p&&(u.x1-=p[0]*o,u.y1-=p[1]*o,u.x2+=p[2]*o,u.y2+=p[3]*o),c){const t=new r(u.x1,u.y1),e=new r(u.x2,u.y1),n=new r(u.x1,u.y2),i=new r(u.x2,u.y2),s=c*Math.PI/180;t._rotate(s),e._rotate(s),n._rotate(s),i._rotate(s),u.x1=Math.min(t.x,e.x,n.x,i.x),u.x2=Math.max(t.x,e.x,n.x,i.x),u.y1=Math.min(t.y,e.y,n.y,i.y),u.y2=Math.max(t.y,e.y,n.y,i.y);}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,n,i,s);}this.boxEndIndex=t.length;}}class Wh{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}}function Qh(t,e=1,n=!1){const i=Eh.fromPoints(t[0]),s=Math.min(i.width(),i.height());let a=s/2;const o=new Wh([],tp),{minX:l,minY:u,maxX:c,maxY:h}=i;if(0===s)return new r(l,u);for(let e=l;ep.d||!p.d)&&(p=r,n&&console.log("found best %d after %d probes",Math.round(1e4*r.d)/1e4,f)),r.max-p.d<=e||(a=r.h/2,o.push(new ep(r.p.x-a,r.p.y-a,a,t)),o.push(new ep(r.p.x+a,r.p.y-a,a,t)),o.push(new ep(r.p.x-a,r.p.y+a,a,t)),o.push(new ep(r.p.x+a,r.p.y+a,a,t)),f+=4);}return n&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function tp(t,e){return e.max-t.max}function ep(t,e,n,i){this.p=new r(t,e),this.h=n,this.d=function(t,e){let r=!1,n=1/0;for(let i=0;it.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(r=!r),n=Math.min(n,Lo(t,i,o));}}return (r?1:-1)*Math.sqrt(n)}(this.p,i),this.max=this.d+this.h*Math.SQRT2;}var rp;t.aE=void 0,(rp=t.aE||(t.aE={}))[rp.center=1]="center",rp[rp.left=2]="left",rp[rp.right=3]="right",rp[rp.top=4]="top",rp[rp.bottom=5]="bottom",rp[rp["top-left"]=6]="top-left",rp[rp["top-right"]=7]="top-right",rp[rp["bottom-left"]=8]="bottom-left",rp[rp["bottom-right"]=9]="bottom-right";const np=Number.POSITIVE_INFINITY;function ip(t,e){return e[1]!==np?function(t,e,r){let n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case "top-right":case "top-left":case "top":i=r-7;break;case "bottom-right":case "bottom-left":case "bottom":i=7-r;}switch(t){case "top-right":case "bottom-right":case "right":n=-e;break;case "top-left":case "bottom-left":case "left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){let r=0,n=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case "top-right":case "top-left":n=i-7;break;case "bottom-right":case "bottom-left":n=7-i;break;case "bottom":n=7-e;break;case "top":n=e-7;}switch(t){case "top-right":case "bottom-right":r=-i;break;case "top-left":case "bottom-left":r=i;break;case "left":r=e;break;case "right":r=-e;}return [r,n]}(t,e[0])}function sp(t,e,r){var n;const i=t.layout,s=null===(n=i.get("text-variable-anchor-offset"))||void 0===n?void 0:n.evaluate(e,{},r);if(s){const t=s.values,e=[];for(let r=0;rt*Qu));n.startsWith("top")?i[1]-=7:n.startsWith("bottom")&&(i[1]+=7),e[r+1]=i;}return new $e(e)}const a=i.get("text-variable-anchor");if(a){let n;n=void 0!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},r)*Qu,np]:i.get("text-offset").evaluate(e,{},r).map((t=>t*Qu));const s=[];for(const t of a)s.push(t,ip(t,n));return new $e(s)}return null}function ap(t){switch(t){case "right":case "top-right":case "bottom-right":return "right";case "left":case "top-left":case "bottom-left":return "left"}return "center"}function op(e,r,n,i,s,a,o,l,u,c,h,p){let f=a.textMaxSize.evaluate(r,{});void 0===f&&(f=o);const d=e.layers[0].layout,y=d.get("icon-offset").evaluate(r,{},h),m=up(n.horizontal),g=o/24,x=e.tilePixelRatio*g,v=e.tilePixelRatio*f/24,b=e.tilePixelRatio*l,w=e.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*e.tilePixelRatio,S=function(t,e,r,n=1){const i=t.get("icon-padding").evaluate(e,{},r),s=i&&i.values;return [s[0]*n,s[1]*n,s[2]*n,s[3]*n]}(d,r,h,e.tilePixelRatio),A=d.get("text-max-angle")/180*Math.PI,k="viewport"!==d.get("text-rotation-alignment")&&"point"!==d.get("symbol-placement"),M="map"===d.get("icon-rotation-alignment")&&"point"!==d.get("symbol-placement"),I=d.get("symbol-placement"),z=w/2,C=d.get("icon-text-fit");let E;i&&"none"!==C&&(e.allowVerticalPlacement&&n.vertical&&(E=Nc(i,n.vertical,C,d.get("icon-text-fit-padding"),y,g)),m&&(i=Nc(i,m,C,d.get("icon-text-fit-padding"),y,g)));const T=h?p.line.getGranularityForZoomLevel(h.z):1,B=(l,p)=>{p.x<0||p.x>=P||p.y<0||p.y>=P||function(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k){const M=e.addToLineVertexArray(r,n);let I,z,P,C,E=0,T=0,B=0,V=0,F=-1,$=-1;const D={};let L=no("");if(e.allowVerticalPlacement&&i.vertical){const t=l.layout.get("text-rotate").evaluate(w,{},A)+90;P=new Jh(u,r,c,h,p,i.vertical,f,d,y,t),o&&(C=new Jh(u,r,c,h,p,o,g,x,y,t));}if(s){const n=l.layout.get("icon-rotate").evaluate(w,{}),i="none"!==l.layout.get("icon-text-fit"),a=Xh(s,n,S,i),f=o?Xh(o,n,S,i):void 0;z=new Jh(u,r,c,h,p,s,g,x,!1,n),E=4*a.length;const d=e.iconSizeData;let y=null;"source"===d.kind?(y=[qc*l.layout.get("icon-size").evaluate(w,{})],y[0]>Gc&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)):"composite"===d.kind&&(y=[qc*_.compositeIconSizes[0].evaluate(w,{},A),qc*_.compositeIconSizes[1].evaluate(w,{},A)],(y[0]>Gc||y[1]>Gc)&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)),e.addSymbols(e.icon,a,y,b,v,w,t.ao.none,r,M.lineStartIndex,M.lineLength,-1,A),F=e.icon.placedSymbolArray.length-1,f&&(T=4*f.length,e.addSymbols(e.icon,f,y,b,v,w,t.ao.vertical,r,M.lineStartIndex,M.lineLength,-1,A),$=e.icon.placedSymbolArray.length-1);}const O=Object.keys(i.horizontal);for(const n of O){const s=i.horizontal[n];if(!I){L=no(s.text);const t=l.layout.get("text-rotate").evaluate(w,{},A);I=new Jh(u,r,c,h,p,s,f,d,y,t);}const o=1===s.positionedLines.length;if(B+=lp(e,r,s,a,l,y,w,m,M,i.vertical?t.ao.horizontal:t.ao.horizontalOnly,o?O:[n],D,F,_,A),o)break}i.vertical&&(V+=lp(e,r,i.vertical,a,l,y,w,m,M,t.ao.vertical,["vertical"],D,$,_,A));const R=I?I.boxStartIndex:e.collisionBoxArray.length,U=I?I.boxEndIndex:e.collisionBoxArray.length,j=P?P.boxStartIndex:e.collisionBoxArray.length,N=P?P.boxEndIndex:e.collisionBoxArray.length,G=z?z.boxStartIndex:e.collisionBoxArray.length,X=z?z.boxEndIndex:e.collisionBoxArray.length,Z=C?C.boxStartIndex:e.collisionBoxArray.length,Y=C?C.boxEndIndex:e.collisionBoxArray.length;let H=-1;const K=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=K(I,H),H=K(P,H),H=K(z,H),H=K(C,H);const J=H>-1?1:0;J&&(H*=k/Qu),e.glyphOffsetArray.length>=th.MAX_GLYPHS&&q("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==w.sortKey&&e.addToSortKeyRanges(e.symbolInstances.length,w.sortKey);const W=sp(l,w,A),[Q,tt]=function(e,r){const n=e.length,i=null==r?void 0:r.values;if((null==i?void 0:i.length)>0)for(let r=0;r=0?D.right:-1,D.center>=0?D.center:-1,D.left>=0?D.left:-1,D.vertical||-1,F,$,L,R,U,j,N,G,X,Z,Y,c,B,V,E,T,J,0,f,H,Q,tt);}(e,p,l,n,i,s,E,e.layers[0],e.collisionBoxArray,r.index,r.sourceLayerIndex,e.index,x,[_,_,_,_],k,u,b,S,M,y,r,a,c,h,o);};if("line"===I)for(const t of Dh(r.geometry,0,0,P,P)){const r=ru(t,T),s=qh(r,w,A,n.vertical||m,i,24,v,e.overscaling,P);for(const t of s)m&&cp(e,m.text,z,t)||B(r,t);}else if("line-center"===I){for(const t of r.geometry)if(t.length>1){const e=ru(t,T),r=Nh(e,A,n.vertical||m,i,24,v);r&&B(e,r);}}else if("Polygon"===r.type)for(const t of Qr(r.geometry,0)){const e=Qh(t,16);B(ru(t[0],T,!0),new Lh(e.x,e.y,0));}else if("LineString"===r.type)for(const t of r.geometry){const e=ru(t,T);B(e,new Lh(e[0].x,e[0].y,0));}else if("Point"===r.type)for(const t of r.geometry)for(const e of t)B([e],new Lh(e.x,e.y,0));}function lp(t,e,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=function(t,e,n,i,s,a,o,l){const u=i.layout.get("text-rotate").evaluate(a,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const i of t.positionedGlyphs){if(!i.rect)continue;const a=i.rect||{};let h=4,p=!0,f=1,d=0;const y=(s||l)&&i.vertical,m=i.metrics.advance*i.scale/2;if(l&&e.verticalizable&&(d=t.lineOffset/2-(i.imageName?-(Qu-i.metrics.width*i.scale)/2:(i.scale-1)*Qu)),i.imageName){const t=o[i.imageName];p=t.sdf,f=t.pixelRatio,h=1/f;}const g=s?[i.x+m,i.y]:[0,0];let x=s?[0,0]:[i.x+m+n[0],i.y+n[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=i.metrics.isDoubleResolution?2:1,w=(i.metrics.left-h)*i.scale-m+x[0],_=(-i.metrics.top-h)*i.scale+x[1],S=w+a.w/b*i.scale/f,A=_+a.h/b*i.scale/f,k=new r(w,_),M=new r(S,_),I=new r(w,A),z=new r(S,A);if(y){const t=new r(-m,m- -17),e=-Math.PI/2,n=12-m,s=new r(22-n,-(i.imageName?n:0)),a=new r(...v);k._rotateAround(e,t)._add(s)._add(a),M._rotateAround(e,t)._add(s)._add(a),I._rotateAround(e,t)._add(s)._add(a),z._rotateAround(e,t)._add(s)._add(a);}if(u){const t=Math.sin(u),e=Math.cos(u),r=[e,-t,t,e];k._matMult(r),M._matMult(r),I._matMult(r),z._matMult(r);}const P=new r(0,0),C=new r(0,0);c.push({tl:k,tr:M,bl:I,br:z,tex:a,writingMode:e.writingMode,glyphOffset:g,sectionIndex:i.sectionIndex,isSDF:p,pixelOffsetTL:P,pixelOffsetBR:C,minFontScaleX:0,minFontScaleY:0});}return c}(0,n,l,s,a,o,i,t.allowVerticalPlacement),g=t.textSizeData;let x=null;"source"===g.kind?(x=[qc*s.layout.get("text-size").evaluate(o,{})],x[0]>Gc&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)):"composite"===g.kind&&(x=[qc*d.compositeTextSizes[0].evaluate(o,{},y),qc*d.compositeTextSizes[1].evaluate(o,{},y)],(x[0]>Gc||x[1]>Gc)&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)),t.addSymbols(t.text,m,x,l,a,o,c,e,u.lineStartIndex,u.lineLength,f,y);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*m.length}function up(t){for(const e in t)return t[e];return null}function cp(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=hp[15&r];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new pp(a,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=hp.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+s+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return fp(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,r,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:a}=this,o=[0,i.length-1,0],l=[];for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=a){for(let a=h;a<=c;a++){const o=s[2*a],u=s[2*a+1];o>=t&&o<=r&&u>=e&&u<=n&&l.push(i[a]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?r>=f:n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return l}within(t,e,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:n,coords:i,nodeSize:s}=this,a=[0,n.length-1,0],o=[],l=r*r;for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)gp(i[2*r],i[2*r+1],t,e)<=l&&o.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];gp(f,d,t,e)<=l&&o.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return o}}function fp(t,e,r,n,i,s){if(i-n<=r)return;const a=n+i>>1;dp(t,e,a,n,i,s),fp(t,e,r,n,a-1,1-s),fp(t,e,r,a+1,i,1-s);}function dp(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const a=i-n+1,o=r-n+1,l=Math.log(a),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(a-u)/a)*(o-a/2<0?-1:1);dp(t,e,r,Math.max(n,Math.floor(r-o*u/a+c)),Math.min(i,Math.floor(r+(a-o)*u/a+c)),s);}const a=e[2*r+s];let o=n,l=i;for(yp(t,e,n,r),e[2*i+s]>a&&yp(t,e,n,i);oa;)l--;}e[2*n+s]===a?yp(t,e,n,l):(l++,yp(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1);}}function yp(t,e,r,n){mp(t,r,n),mp(e,2*r,2*n),mp(e,2*r+1,2*n+1);}function mp(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function gp(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}var xp;t.cx=void 0,(xp=t.cx||(t.cx={})).create="create",xp.load="load",xp.fullLoad="fullLoad";let vp=null,bp=[];const wp=1e3/60,_p="loadTime",Sp="fullLoadTime",Ap={mark(t){performance.mark(t);},frame(t){const e=t;null!=vp&&bp.push(e-vp),vp=e;},clearMetrics(){vp=null,bp=[],performance.clearMeasures(_p),performance.clearMeasures(Sp);for(const e in t.cx)performance.clearMarks(t.cx[e]);},getPerformanceMetrics(){performance.measure(_p,t.cx.create,t.cx.load),performance.measure(Sp,t.cx.create,t.cx.fullLoad);const e=performance.getEntriesByName(_p)[0].duration,r=performance.getEntriesByName(Sp)[0].duration,n=bp.length,i=1/(bp.reduce(((t,e)=>t+e),0)/n/1e3),s=bp.filter((t=>t>wp)).reduce(((t,e)=>t+(e-wp)/wp),0);return {loadTime:e,fullLoadTime:r,fps:i,percentDroppedFrames:s/(n+s)*100,totalFrames:n}}};t.$=P,t.A=f,t.B=function([t,e,r]){return e+=90,e*=Math.PI/180,r*=Math.PI/180,{x:t*Math.cos(e)*Math.sin(r),y:t*Math.sin(e)*Math.sin(r),z:t*Math.cos(r)}},t.C=dr,t.D=Ds,t.E=gt,t.F=Is,t.G=ts,t.H=function(t){if(null==Z){const e=t.navigator?t.navigator.userAgent:null;Z=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return Z},t.I=vc,t.J=class{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new fh((()=>this.process())),this.subscription=Q(this.target,"message",(t=>this.receive(t)),!1),this.globalScope=X(self)?t:window;}registerMessageHandler(t,e){this.messageHandlers[t]=e;}sendAsync(t,e){return new Promise(((r,n)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10),s=e?Q(e.signal,"abort",(()=>{null==s||s.unsubscribe(),delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e);}),dh):null;this.resolveRejects[i]={resolve:t=>{null==s||s.unsubscribe(),r(t);},reject:t=>{null==s||s.unsubscribe(),n(t);}};const a=[],o=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:cs(t.data,a)});this.target.postMessage(o,{transfer:a});}))}receive(t){const e=t.data,r=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[r];const t=this.abortControllers[r];return delete this.abortControllers[r],void(t&&t.abort())}if(X(self)||e.mustQueue)return this.tasks[r]=e,this.taskQueue.push(r),void this.invoker.trigger();this.processTask(r,e);}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e);}processTask(t,r){return e(this,void 0,void 0,(function*(){if(""===r.type){const e=this.resolveRejects[t];if(delete this.resolveRejects[t],!e)return;return void(r.error?e.reject(hs(r.error)):e.resolve(hs(r.data)))}if(!this.messageHandlers[r.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${r.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const e=hs(r.data),n=new AbortController;this.abortControllers[t]=n;try{const i=yield this.messageHandlers[r.type](r.sourceMapId,e,n);this.completeTask(t,null,i);}catch(e){this.completeTask(t,e);}}))}completeTask(t,e,r){const n=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?cs(e):null,data:cs(r,n)};this.target.postMessage(i,{transfer:n});}remove(){this.invoker.remove(),this.subscription.unsubscribe();}},t.K=lt,t.L=function(){var t=new f(16);return f!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.M=function(t,e,r){var n,i,s,a,o,l,u,c,h,p,f,d,y=r[0],m=r[1],g=r[2];return e===t?(t[12]=e[0]*y+e[4]*m+e[8]*g+e[12],t[13]=e[1]*y+e[5]*m+e[9]*g+e[13],t[14]=e[2]*y+e[6]*m+e[10]*g+e[14],t[15]=e[3]*y+e[7]*m+e[11]*g+e[15]):(i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=n=e[0],t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=n*y+o*m+h*g+e[12],t[13]=i*y+l*m+p*g+e[13],t[14]=s*y+u*m+f*g+e[14],t[15]=a*y+c*m+d*g+e[15]),t},t.N=function(t,e,r){var n=r[0],i=r[1],s=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.O=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],y=e[12],m=e[13],g=e[14],x=e[15],v=r[0],b=r[1],w=r[2],_=r[3];return t[0]=v*n+b*o+w*h+_*y,t[1]=v*i+b*l+w*p+_*m,t[2]=v*s+b*u+w*f+_*g,t[3]=v*a+b*c+w*d+_*x,t[4]=(v=r[4])*n+(b=r[5])*o+(w=r[6])*h+(_=r[7])*y,t[5]=v*i+b*l+w*p+_*m,t[6]=v*s+b*u+w*f+_*g,t[7]=v*a+b*c+w*d+_*x,t[8]=(v=r[8])*n+(b=r[9])*o+(w=r[10])*h+(_=r[11])*y,t[9]=v*i+b*l+w*p+_*m,t[10]=v*s+b*u+w*f+_*g,t[11]=v*a+b*c+w*d+_*x,t[12]=(v=r[12])*n+(b=r[13])*o+(w=r[14])*h+(_=r[15])*y,t[13]=v*i+b*l+w*p+_*m,t[14]=v*s+b*u+w*f+_*g,t[15]=v*a+b*c+w*d+_*x,t},t.P=r,t.Q=function(t,e){const r={};for(let n=0;n!n.has(t.id)))),o.update&&(o.update=o.update.filter((t=>!n.has(t.id))));const i=new Set((null!==(r=t.add)&&void 0!==r?r:[]).map((t=>t.id)));e.remove=e.remove.filter((t=>!i.has(t)));}if(e.remove){const t=new Set(o.remove?o.remove.concat(e.remove):e.remove);o.remove=Array.from(t.values());}if(e.add){const t=o.add?o.add.concat(e.add):e.add,r=new Map(t.map((t=>[t.id,t])));o.add=Array.from(r.values());}if(e.update){const t=new Map(null===(n=o.update)||void 0===n?void 0:n.map((t=>[t.id,t])));for(const r of e.update){const e=null!==(i=t.get(r.id))&&void 0!==i?i:{id:r.id};r.newGeometry&&(e.newGeometry=r.newGeometry),r.addOrUpdateProperties&&(e.addOrUpdateProperties=(null!==(s=e.addOrUpdateProperties)&&void 0!==s?s:[]).concat(r.addOrUpdateProperties)),r.removeProperties&&(e.removeProperties=(null!==(a=e.removeProperties)&&void 0!==a?a:[]).concat(r.removeProperties)),r.removeAllProperties&&(e.removeAllProperties=!0),t.set(r.id,e);}o.update=Array.from(t.values());}return o.remove&&o.add&&(o.remove=o.remove.filter((t=>-1===o.add.findIndex((e=>e.id===t))))),o},t.a1=Ah,t.a2=Eh,t.a3=25,t.a4=Mh,t.a5=t=>{const e=window.document.createElement("video");return e.muted=!0,new Promise((r=>{e.onloadstart=()=>{r(e);};for(const r of t){const t=window.document.createElement("source");pt(r)||(e.crossOrigin="Anonymous"),t.src=r,e.appendChild(t);}}))},t.a6=Ct,t.a7=function(){return O++},t.a8=ba,t.a9=th,t.aA=function(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return [e,r,n,i]},t.aB=Qu,t.aC=C,t.aD=function(t,e,r,n,i=!1){if(!r[0]&&!r[1])return [0,0];const s=i?"map"===n?-t.bearingInRadians:0:"viewport"===n?t.bearingInRadians:0;if(s){const t=Math.sin(s),e=Math.cos(s);r=[r[0]*e-r[1]*t,r[0]*t+r[1]*e];}return [i?r[0]:C(e,r[0],t.zoom),i?r[1]:C(e,r[1],t.zoom)]},t.aF=Zc,t.aG=ap,t.aH=Vc,t.aI=pp,t.aJ=Ys,t.aK=Jl,t.aL=Ea,t.aM=Za,t.aN=Na,t.aO=D,t.aP=et,t.aQ=Sh,t.aR=b,t.aS=v,t.aT=function(t){var e=new f(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.aU=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t},t.aV=function(t,e){var r=e[0],n=e[1],i=e[2],s=r*r+n*n+i*i;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t},t.aW=w,t.aX=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.aY=function(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t},t.aZ=g,t.a_=function(t,e,r){const n=e[0]*r[0]+e[1]*r[1]+e[2]*r[2];return 0===n?null:(-(t[0]*r[0]+t[1]*r[1]+t[2]*r[2])-r[3])/n},t.aa=hi,t.ab=Io,t.ac=Bh,t.ad=function(t){const e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,r,n,i)=>{const s=n||i;return e[r]=!s||s.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t;}return e},t.ae=tt,t.af=function(t){return Math.pow(2,t)},t.ag=y,t.ah=$,t.ai=85.051129,t.aj=wh,t.ak=function(t){return Math.log(t)/Math.LN2},t.al=function(t){var e=t[0],r=t[1];return e*e+r*r},t.am=function(t,e){const r=[];for(const n in t)n in e||r.push(n);return r},t.an=function(t,e){let r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){const{interpolationType:i,minZoom:s,maxZoom:a}=t,o=i?$(pr.interpolationFactor(i,e,s,a),0,1):0;"camera"===t.kind?n=dr.number(t.minSize,t.maxSize,o):r=o;}return {uSizeT:r,uSize:n}},t.ap=function(t,{uSize:e,uSizeT:r},{lowerSize:n,upperSize:i}){return "source"===t.kind?n/qc:"composite"===t.kind?dr.number(n/qc,i/qc,r):e},t.aq=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],y=e[13],m=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,w=n*l-i*o,_=n*u-s*o,S=i*u-s*l,A=c*y-h*d,k=c*m-p*d,M=c*g-f*d,I=h*m-p*y,z=h*g-f*y,P=p*g-f*m,C=x*P-v*z+b*I+w*M-_*k+S*A;return C?(t[0]=(o*P-l*z+u*I)*(C=1/C),t[1]=(i*z-n*P-s*I)*C,t[2]=(y*S-m*_+g*w)*C,t[3]=(p*_-h*S-f*w)*C,t[4]=(l*M-a*P-u*k)*C,t[5]=(r*P-i*M+s*k)*C,t[6]=(m*b-d*S-g*v)*C,t[7]=(c*S-p*b+f*v)*C,t[8]=(a*z-o*M+u*A)*C,t[9]=(n*M-r*z-s*A)*C,t[10]=(d*_-y*b+g*x)*C,t[11]=(h*b-c*_-f*x)*C,t[12]=(o*k-a*I-l*A)*C,t[13]=(r*I-n*k+i*A)*C,t[14]=(y*v-d*w-m*x)*C,t[15]=(c*w-h*v+p*x)*C,t):null},t.ar=I,t.as=function(t){var e=t[0],r=t[1];return Math.sqrt(e*e+r*r)},t.at=function(t){return t[0]=0,t[1]=0,t},t.au=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t},t.av=Kc,t.aw=A,t.ax=function(t,e,n,i){const s=e.y-t.y,a=e.x-t.x,o=i.y-n.y,l=i.x-n.x,u=o*a-l*s;if(0===u)return null;const c=(l*(t.y-n.y)-o*(t.x-n.x))/u;return new r(t.x+c*a,t.y+c*s)},t.ay=Dh,t.az=Eo,t.b=Y,t.b$=class extends la{},t.b0=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t},t.b1=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]},t.b2=Ih,t.b3=Ph,t.b4=function(t,e,r,n,i){var s=1/Math.tan(e/2);if(t[0]=s/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=s,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0){var a=1/(n-i);t[10]=(i+n)*a,t[14]=2*i*n*a;}else t[10]=-1,t[14]=-2*n;return t},t.b5=function(t){var e=new f(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.b6=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[4],c=e[5],h=e[6],p=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i+u*n,t[1]=a*i+c*n,t[2]=o*i+h*n,t[3]=l*i+p*n,t[4]=u*i-s*n,t[5]=c*i-a*n,t[6]=h*i-o*n,t[7]=p*i-l*n,t},t.b7=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=s*i+u*n,t[5]=a*i+c*n,t[6]=o*i+h*n,t[7]=l*i+p*n,t[8]=u*i-s*n,t[9]=c*i-a*n,t[10]=h*i-o*n,t[11]=p*i-l*n,t},t.b8=function(){const t=new Float32Array(16);return y(t),t},t.b9=function(){const t=new Float64Array(16);return y(t),t},t.bA=function(t,e){const r=E(t,360),n=E(e,360),i=n-r,s=n>r?i-360:i+360;return Math.abs(i)0?a:-a},t.bD=function(t,e){const r=E(t,2*Math.PI),n=E(e,2*Math.PI);return Math.min(Math.abs(r-n),Math.abs(r-n+2*Math.PI),Math.abs(r-n-2*Math.PI))},t.bE=function(){const t={},e=xt.$version;for(const r in xt.$root){const n=xt.$root[r];if(n.required){let i=null;i="version"===r?e:"array"===n.type?[]:{},null!=i&&(t[r]=i);}}return t},t.bF=ps,t.bG=ct,t.bH=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(let n=0;n{"source"in t&&n[t.source]?r.push({command:"removeLayer",args:[t.id]}):s.push(t);})),r=r.concat(i),function(t,e,r){e=e||[];const n=(t=t||[]).map(zt),i=e.map(zt),s=t.reduce(Pt,{}),a=e.reduce(Pt,{}),o=n.slice(),l=Object.create(null);let u,c,h,p,f;for(let t=0,e=0;tp?(i=Math.acos(s),a=Math.sin(i),o=Math.sin((1-n)*i)/a,l=Math.sin(n*i)/a):(o=1-n,l=n),t[0]=o*u+l*d,t[1]=o*c+l*y,t[2]=o*h+l*m,t[3]=o*f+l*g,t},t.bd=function(t){const e=new Float64Array(9);var r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v;h=(i=(n=t)[0])*(l=i+i),p=(s=n[1])*l,d=(a=n[2])*l,y=a*(u=s+s),g=(o=n[3])*l,x=o*u,v=o*(c=a+a),(r=e)[0]=1-(f=s*u)-(m=a*c),r[3]=p-v,r[6]=d+x,r[1]=p+v,r[4]=1-h-m,r[7]=y-g,r[2]=d-x,r[5]=y+g,r[8]=1-h-f;const b=et(-Math.asin($(e[2],-1,1)));let w,_;return Math.hypot(e[5],e[8])<.001?(w=0,_=-et(Math.atan2(e[3],e[4]))):(w=et(0===e[5]&&0===e[8]?0:Math.atan2(e[5],e[8])),_=et(0===e[1]&&0===e[0]?0:Math.atan2(e[1],e[0]))),{roll:w,pitch:b+90,bearing:_}},t.be=function(t,e){return t.roll==e.roll&&t.pitch==e.pitch&&t.bearing==e.bearing},t.bf=Me,t.bg=uo,t.bh=Wl,t.bi=Ql,t.bj=Kl,t.bk=T,t.bl=B,t.bm=Le,t.bn=function(t,e,r,n,i){return T(n,i,$((t-e)/(r-e),0,1))},t.bo=E,t.bp=function(){return new Float64Array(3)},t.bq=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t},t.br=M,t.bs=function(t,e,r){var n=r[0],i=r[1],s=r[2],a=r[3],o=e[0],l=e[1],u=e[2],c=i*u-s*l,h=s*o-n*u,p=n*l-i*o;return t[0]=o+a*(c+=c)+i*(p+=p)-s*(h+=h),t[1]=l+a*h+s*c-n*p,t[2]=u+a*p+n*h-i*c,t},t.bt=function(t,e,r){const n=(i=[t[0],t[1],t[2],e[0],e[1],e[2],r[0],r[1],r[2]])[0]*((c=i[8])*(a=i[4])-(o=i[5])*(u=i[7]))+i[1]*(-c*(s=i[3])+o*(l=i[6]))+i[2]*(u*s-a*l);var i,s,a,o,l,u,c;if(0===n)return null;const h=w([],[e[0],e[1],e[2]],[r[0],r[1],r[2]]),p=w([],[r[0],r[1],r[2]],[t[0],t[1],t[2]]),f=w([],[t[0],t[1],t[2]],[e[0],e[1],e[2]]),d=b([],h,-t[3]);return v(d,d,b([],p,-e[3])),v(d,d,b([],f,-r[3])),b(d,d,1/n),d},t.bu=yh,t.bv=function(){return new Float64Array(4)},t.bw=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),s[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),s[2]=i[2],t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bx=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0],s[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),s[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.by=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),s[1]=i[1],s[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bz=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i-u*n,t[1]=a*i-c*n,t[2]=o*i-h*n,t[3]=l*i-p*n,t[8]=s*n+u*i,t[9]=a*n+c*i,t[10]=o*n+h*i,t[11]=l*n+p*i,t},t.c=st,t.c0=Ku,t.c1=class extends ca{},t.c2=cl,t.c3=function(t){return t<=1?1:Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},t.c4=ul,t.c5=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[3]*n+r[7]*i+r[11]*s+r[15];return t[0]=(r[0]*n+r[4]*i+r[8]*s+r[12])/(a=a||1),t[1]=(r[1]*n+r[5]*i+r[9]*s+r[13])/a,t[2]=(r[2]*n+r[6]*i+r[10]*s+r[14])/a,t},t.c6=class extends Ws{},t.c7=class extends ga{},t.c8=function(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[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]},t.c9=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=t[9],f=t[10],d=t[11],y=t[12],m=t[13],g=t[14],x=t[15],v=e[0],b=e[1],w=e[2],_=e[3],S=e[4],A=e[5],k=e[6],M=e[7],I=e[8],z=e[9],P=e[10],C=e[11],E=e[12],T=e[13],B=e[14],V=e[15];return Math.abs(r-v)<=p*Math.max(1,Math.abs(r),Math.abs(v))&&Math.abs(n-b)<=p*Math.max(1,Math.abs(n),Math.abs(b))&&Math.abs(i-w)<=p*Math.max(1,Math.abs(i),Math.abs(w))&&Math.abs(s-_)<=p*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(a-S)<=p*Math.max(1,Math.abs(a),Math.abs(S))&&Math.abs(o-A)<=p*Math.max(1,Math.abs(o),Math.abs(A))&&Math.abs(l-k)<=p*Math.max(1,Math.abs(l),Math.abs(k))&&Math.abs(u-M)<=p*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(c-I)<=p*Math.max(1,Math.abs(c),Math.abs(I))&&Math.abs(h-z)<=p*Math.max(1,Math.abs(h),Math.abs(z))&&Math.abs(f-P)<=p*Math.max(1,Math.abs(f),Math.abs(P))&&Math.abs(d-C)<=p*Math.max(1,Math.abs(d),Math.abs(C))&&Math.abs(y-E)<=p*Math.max(1,Math.abs(y),Math.abs(E))&&Math.abs(m-T)<=p*Math.max(1,Math.abs(m),Math.abs(T))&&Math.abs(g-B)<=p*Math.max(1,Math.abs(g),Math.abs(B))&&Math.abs(x-V)<=p*Math.max(1,Math.abs(x),Math.abs(V))},t.cA=function(t,e){at.REGISTERED_PROTOCOLS[t]=e;},t.cB=function(t){delete at.REGISTERED_PROTOCOLS[t];},t.cC=function(t,e){const r={};for(let n=0;nt*Qu));}let v=o?"center":n.get("text-justify").evaluate(i,{},e.canonical);const b="point"===n.get("symbol-placement")?n.get("text-max-width").evaluate(i,{},e.canonical)*Qu:1/0,w=()=>{e.bucket.allowVerticalPlacement&&ds(s)&&(d.vertical=Ac(y,e.glyphMap,e.glyphPositions,e.imagePositions,c,b,a,m,"left",f,g,t.ao.vertical,!0,p,h));};if(!o&&x){const r=new Set;if("auto"===v)for(let t=0;t0||(null===(i=r.addOrUpdateProperties)||void 0===i?void 0:i.length)>0);if((r.newGeometry||r.removeAllProperties||o)&&(e=Object.assign({},e),t.set(r.id,e),o&&(e.properties=Object.assign({},e.properties))),r.newGeometry&&(e.geometry=r.newGeometry),r.removeAllProperties)e.properties={};else if((null===(s=r.removeProperties)||void 0===s?void 0:s.length)>0)for(const t of r.removeProperties)Object.prototype.hasOwnProperty.call(e.properties,t)&&delete e.properties[t];if((null===(a=r.addOrUpdateProperties)||void 0===a?void 0:a.length)>0)for(const{key:t,value:n}of r.addOrUpdateProperties)e.properties[t]=n;}},t.cX=Ms,t.ca=function(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[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.cb=t=>"symbol"===t.type,t.cc=t=>"circle"===t.type,t.cd=t=>"heatmap"===t.type,t.ce=t=>"line"===t.type,t.cf=t=>"fill"===t.type,t.cg=t=>"fill-extrusion"===t.type,t.ch=t=>"hillshade"===t.type,t.ci=t=>"color-relief"===t.type,t.cj=t=>"raster"===t.type,t.ck=t=>"background"===t.type,t.cl=t=>"custom"===t.type,t.cm=V,t.cn=function(t,e,r){const n=z(e.x-r.x,e.y-r.y),i=z(t.x-r.x,t.y-r.y);var s,a;return et(Math.atan2(n[0]*i[1]-n[1]*i[0],(s=n)[0]*(a=i)[0]+s[1]*a[1]))},t.co=F,t.cp=function(t,e){return nt[e]&&(t instanceof MouseEvent||t instanceof WheelEvent)},t.cq=function(t,e){return rt[e]&&"touches"in t},t.cr=function(t){return rt[t]||nt[t]},t.cs=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t},t.ct=function(t,e){const{x:r,y:n}=Ah.fromLngLat(e);return !(t<0||t>25||n<0||n>=1||r<0||r>=1)},t.cu=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.cv=class extends Js{},t.cw=Ap,t.cy=function(t){return t.message===it},t.cz=ut,t.d=pt,t.e=L,t.f=t=>e(void 0,void 0,void 0,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),t.g=ot,t.h=t=>new Promise(((e,r)=>{const n=new Image;n.onload=()=>{e(n),URL.revokeObjectURL(n.src),n.onload=null,window.requestAnimationFrame((()=>{n.src=H;}));},n.onerror=()=>r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const i=new Blob([new Uint8Array(t)],{type:"image/png"});n.src=t.byteLength?URL.createObjectURL(i):H;})),t.i=X,t.j=(t,e)=>ht(L(t,{type:"json"}),e),t.k=mt,t.l=yt,t.m=ht,t.n=(t,e)=>ht(L(t,{type:"arrayBuffer"}),e),t.o=function(t){return new nc(t).readFields(yc,[])},t.p=xc,t.q=ol,t.r=js,t.s=Q,t.t=Es,t.u=fs,t.v=xt,t.w=q,t.x=Qi,t.y=ns,t.z=Wi;})); + +define("worker",["./shared"],(function(e){"use strict";class t{constructor(e,t){this.keyCache={},e&&this.replace(e,t);}replace(e,t){this._layerConfigs={},this._layers={},this.update(e,[],t);}update(t,i,o){for(const i of t){this._layerConfigs[i.id]=i;const t=this._layers[i.id]=e.bJ(i,o);t._featureFilter=e.aa(t.filter,o),this.keyCache[i.id]&&delete this.keyCache[i.id];}for(const e of i)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const s=e.cC(Object.values(this._layerConfigs),this.keyCache);for(const e of s){const t=e.map((e=>this._layers[e.id])),i=t[0];if("none"===i.visibility)continue;const o=i.source||"";let s=this.familiesBySource[o];s||(s=this.familiesBySource[o]={});const n=i.sourceLayer||"_geojsonTileLayer";let r=s[n];r||(r=s[n]=[]),r.push(t);}}}class i{constructor(t){const i={},o=[];for(const e in t){const s=t[e],n=i[e]={};for(const e in s){const t=s[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const i={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};o.push(i),n[e]={rect:i,metrics:t.metrics};}}const{w:s,h:n}=e.p(o),r=new e.q({width:s||1,height:n||1});for(const o in t){const s=t[o];for(const t in s){const n=s[+t];if(!n||0===n.bitmap.width||0===n.bitmap.height)continue;const a=i[o][t].rect;e.q.copy(n.bitmap,r,{x:0,y:0},{x:a.x+1,y:a.y+1},n.bitmap);}}this.image=r,this.positions=i;}}e.cD("GlyphAtlas",i);class o{constructor(t){this.tileID=new e.Z(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[];}parse(t,o,n,r,a){return e._(this,void 0,void 0,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.a8;const l=new e.cE(Object.keys(t.layers).sort()),c=new e.cF(this.tileID,this.promoteId);c.bucketLayerIDs=[];const u={},h={featureIndex:c,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:n,subdivisionGranularity:a},d=o.familiesBySource[this.source];for(const i in d){const o=t.layers[i];if(!o)continue;1===o.version&&e.w(`Vector tile source "${this.source}" layer "${i}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const r=l.encode(i),a=[];for(let e=0;e=i.maxzoom||"none"!==i.visibility&&(s(t,this.zoom,n),(u[i.id]=i.createBucket({index:c.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:r,sourceID:this.source})).populate(a,h,this.tileID.canonical),c.bucketLayerIDs.push(t.map((e=>e.id))));}}const f=e.bN(h.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?void 0:e.abort())),this.inFlightDependencies=[];let g=Promise.resolve({});if(Object.keys(f).length){const e=new AbortController;this.inFlightDependencies.push(e),g=r.sendAsync({type:"GG",data:{stacks:f,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const p=Object.keys(h.iconDependencies);let m=Promise.resolve({});if(p.length){const e=new AbortController;this.inFlightDependencies.push(e),m=r.sendAsync({type:"GI",data:{icons:p,source:this.source,tileID:this.tileID,type:"icons"}},e);}const y=Object.keys(h.patternDependencies);let v=Promise.resolve({});if(y.length){const e=new AbortController;this.inFlightDependencies.push(e),v=r.sendAsync({type:"GI",data:{icons:y,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const[w,x,b]=yield Promise.all([g,m,v]),S=new i(w),_=new e.cG(x,b);for(const t in u){const i=u[t];i instanceof e.a9?(s(i.layers,this.zoom,n),e.cH({bucket:i,glyphMap:w,glyphPositions:S.positions,imageMap:x,imagePositions:_.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:h.subdivisionGranularity})):i.hasPattern&&(i instanceof e.cI||i instanceof e.cJ||i instanceof e.cK)&&(s(i.layers,this.zoom,n),i.addFeatures(h,this.tileID.canonical,_.patternPositions));}return this.status="done",{buckets:Object.values(u).filter((e=>!e.isEmpty())),featureIndex:c,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:S.image,imageAtlas:_,glyphMap:this.returnDependencies?w:null,iconMap:this.returnDependencies?x:null,glyphPositions:this.returnDependencies?S.positions:null}}))}}function s(t,i,o){const s=new e.F(i);for(const e of t)e.recalculate(s,o);}class n{constructor(e,t,i){this.actor=e,this.layerIndex=t,this.availableImages=i,this.fetching={},this.loading={},this.loaded={};}loadVectorTile(t,i){return e._(this,void 0,void 0,(function*(){const o=yield e.n(t.request,i);try{return {vectorTile:new e.cL(new e.cM(o.data)),rawData:o.data,cacheControl:o.cacheControl,expires:o.expires}}catch(e){const i=new Uint8Array(o.data);let s=`Unable to parse the tile at ${t.request.url}, `;throw s+=31===i[0]&&139===i[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${e.message}`,new Error(s)}}))}loadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid,s=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.cN(t.request),n=new o(t);this.loading[i]=n;const r=new AbortController;n.abort=r;try{const o=yield this.loadVectorTile(t,r);if(delete this.loading[i],!o)return null;const a=o.rawData,l={};o.expires&&(l.expires=o.expires),o.cacheControl&&(l.cacheControl=o.cacheControl);const c={};if(s){const e=s.finish();e&&(c.resourceTiming=JSON.parse(JSON.stringify(e)));}n.vectorTile=o.vectorTile;const u=n.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);this.loaded[i]=n,this.fetching[i]={rawTileData:a,cacheControl:l,resourceTiming:c};try{const t=yield u;return e.e({rawTileData:a.slice(0)},t,l,c)}finally{delete this.fetching[i];}}catch(e){throw delete this.loading[i],n.status="done",this.loaded[i]=n,e}}))}reloadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid;if(!this.loaded||!this.loaded[i])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const o=this.loaded[i];if(o.showCollisionBoxes=t.showCollisionBoxes,"parsing"===o.status){const s=yield o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);let n;if(this.fetching[i]){const{rawTileData:t,cacheControl:o,resourceTiming:r}=this.fetching[i];delete this.fetching[i],n=e.e({rawTileData:t.slice(0)},s,o,r);}else n=s;return n}if("done"===o.status&&o.vectorTile)return o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity)}))}abortTile(t){return e._(this,void 0,void 0,(function*(){const e=this.loading,i=t.uid;e&&e[i]&&e[i].abort&&(e[i].abort.abort(),delete e[i]);}))}removeTile(t){return e._(this,void 0,void 0,(function*(){this.loaded&&this.loaded[t.uid]&&delete this.loaded[t.uid];}))}}class r{constructor(){this.loaded={};}loadTile(t){return e._(this,void 0,void 0,(function*(){const{uid:i,encoding:o,rawImageData:s,redFactor:n,greenFactor:r,blueFactor:a,baseShift:l}=t,c=s.width+2,u=s.height+2,h=e.b(s)?new e.R({width:c,height:u},yield e.cO(s,-1,-1,c,u)):s,d=new e.cP(i,h,o,n,r,a,l);return this.loaded=this.loaded||{},this.loaded[i]=d,d}))}removeTile(e){const t=this.loaded,i=e.uid;t&&t[i]&&delete t[i];}}var a,l,c=function(){if(l)return a;function e(e,i){if(0!==e.length){t(e[0],i);for(var o=1;o=Math.abs(a)?i-l+a:a-l+i,i=l;}i+o>=0!=!!t&&e.reverse();}return l=1,a=function t(i,o){var s,n=i&&i.type;if("FeatureCollection"===n)for(s=0;s>31}function v(e,t){const i=e.loadGeometry(),o=e.type;let s=0,n=0;for(const r of i){let i=1;1===o&&(i=r.length),t.writeVarint(m(1,i));const a=3===o?r.length-1:r.length;for(let e=0;ee},b=Math.fround||(S=new Float32Array(1),e=>(S[0]=+e,S[0]));var S;class _{constructor(e){this.options=Object.assign(Object.create(x),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:i,maxZoom:o}=this.options;t&&console.time("total time");const s=`prepare ${e.length} points`;t&&console.time(s),this.points=e;const n=[];for(let t=0;t=i;e--){const i=+Date.now();r=this.trees[e]=this._createTree(this._cluster(r,e)),t&&console.log("z%d: %d clusters in %dms",e,r.numItems,+Date.now()-i);}return t&&console.timeEnd("total time"),this}getClusters(e,t){let i=((e[0]+180)%360+360)%360-180;const o=Math.max(-90,Math.min(90,e[1]));let s=180===e[2]?180:((e[2]+180)%360+360)%360-180;const n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)i=-180,s=180;else if(i>s){const e=this.getClusters([i,o,180,n],t),r=this.getClusters([-180,o,s,n],t);return e.concat(r)}const r=this.trees[this._limitZoom(t)],a=r.range(k(i),P(n),k(s),P(o)),l=r.data,c=[];for(const e of a){const t=this.stride*e;c.push(l[t+5]>1?M(l,t,this.clusterProps):this.points[l[t+3]]);}return c}getChildren(e){const t=this._getOriginId(e),i=this._getOriginZoom(e),o="No cluster with the specified id.",s=this.trees[i];if(!s)throw new Error(o);const n=s.data;if(t*this.stride>=n.length)throw new Error(o);const r=this.options.radius/(this.options.extent*Math.pow(2,i-1)),a=s.within(n[t*this.stride],n[t*this.stride+1],r),l=[];for(const t of a){const i=t*this.stride;n[i+4]===e&&l.push(n[i+5]>1?M(n,i,this.clusterProps):this.points[n[i+3]]);}if(0===l.length)throw new Error(o);return l}getLeaves(e,t,i){const o=[];return this._appendLeaves(o,e,t=t||10,i=i||0,0),o}getTile(e,t,i){const o=this.trees[this._limitZoom(e)],s=Math.pow(2,e),{extent:n,radius:r}=this.options,a=r/n,l=(i-a)/s,c=(i+1+a)/s,u={features:[]};return this._addTileFeatures(o.range((t-a)/s,l,(t+1+a)/s,c),o.data,t,i,s,u),0===t&&this._addTileFeatures(o.range(1-a/s,l,1,c),o.data,s,i,s,u),t===s-1&&this._addTileFeatures(o.range(0,l,a/s,c),o.data,-1,i,s,u),u.features.length?u:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const i=this.getChildren(e);if(t++,1!==i.length)break;e=i[0].properties.cluster_id;}return t}_appendLeaves(e,t,i,o,s){const n=this.getChildren(t);for(const t of n){const n=t.properties;if(n&&n.cluster?s+n.point_count<=o?s+=n.point_count:s=this._appendLeaves(e,n.cluster_id,i,o,s):s1;let l,c,u;if(a)l=I(t,e,this.clusterProps),c=t[e],u=t[e+1];else {const i=this.points[t[e+3]];l=i.properties;const[o,s]=i.geometry.coordinates;c=k(o),u=P(s);}const h={type:1,geometry:[[Math.round(this.options.extent*(c*s-i)),Math.round(this.options.extent*(u*s-o))]],tags:l};let d;d=a||this.options.generateId?t[e+3]:this.points[t[e+3]].id,void 0!==d&&(h.id=d),n.features.push(h);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:i,extent:o,reduce:s,minPoints:n}=this.options,r=i/(o*Math.pow(2,t)),a=e.data,l=[],c=this.stride;for(let i=0;it&&(f+=a[i+5]);}if(f>d&&f>=n){let e,n=o*d,r=u*d,g=-1;const p=(i/c<<5)+(t+1)+this.points.length;for(const o of h){const l=o*c;if(a[l+2]<=t)continue;a[l+2]=t;const u=a[l+5];n+=a[l]*u,r+=a[l+1]*u,a[l+4]=p,s&&(e||(e=this._map(a,i,!0),g=this.clusterProps.length,this.clusterProps.push(e)),s(e,this._map(a,l)));}a[i+4]=p,l.push(n/f,r/f,1/0,p,-1,f),s&&l.push(g);}else {for(let e=0;e1)for(const e of h){const i=e*c;if(!(a[i+2]<=t)){a[i+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,i){if(e[t+5]>1){const o=this.clusterProps[e[t+6]];return i?Object.assign({},o):o}const o=this.points[e[t+3]].properties,s=this.options.map(o);return i&&s===o?Object.assign({},s):s}}function M(e,t,i){return {type:"Feature",id:e[t+3],properties:I(e,t,i),geometry:{type:"Point",coordinates:[(o=e[t],360*(o-.5)),T(e[t+1])]}};var o;}function I(e,t,i){const o=e[t+5],s=o>=1e4?`${Math.round(o/1e3)}k`:o>=1e3?Math.round(o/100)/10+"k":o,n=e[t+6],r=-1===n?{}:Object.assign({},i[n]);return Object.assign(r,{cluster:!0,cluster_id:e[t+3],point_count:o,point_count_abbreviated:s})}function k(e){return e/360+.5}function P(e){const t=Math.sin(e*Math.PI/180),i=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return i<0?0:i>1?1:i}function T(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function D(e,t,i,o){let s=o;const n=t+(i-t>>1);let r,a=i-t;const l=e[t],c=e[t+1],u=e[i],h=e[i+1];for(let o=t+3;os)r=o,s=t;else if(t===s){const e=Math.abs(o-n);eo&&(r-t>3&&D(e,t,r,o),e[r+2]=s,i-r>3&&D(e,r,i,o));}function C(e,t,i,o,s,n){let r=s-i,a=n-o;if(0!==r||0!==a){const l=((e-i)*r+(t-o)*a)/(r*r+a*a);l>1?(i=s,o=n):l>0&&(i+=r*l,o+=a*l);}return r=e-i,a=t-o,r*r+a*a}function L(e,t,i,o){const s={id:null==e?null:e,type:t,geometry:i,tags:o,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===t||"MultiPoint"===t||"LineString"===t)O(s,i);else if("Polygon"===t)O(s,i[0]);else if("MultiLineString"===t)for(const e of i)O(s,e);else if("MultiPolygon"===t)for(const e of i)O(s,e[0]);return s}function O(e,t){for(let i=0;i0&&(r+=o?(s*l-a*n)/2:Math.sqrt(Math.pow(a-s,2)+Math.pow(l-n,2))),s=a,n=l;}const a=t.length-3;t[2]=1,D(t,0,a,i),t[a+2]=1,t.size=Math.abs(r),t.start=0,t.end=t.size;}function G(e,t,i,o){for(let s=0;s1?1:i}function j(e,t,i,o,s,n,r,a){if(o/=t,n>=(i/=t)&&r=o)return null;const l=[];for(const t of e){const e=t.geometry;let n=t.type;const r=0===s?t.minX:t.minY,c=0===s?t.maxX:t.maxY;if(r>=i&&c=o)continue;let u=[];if("Point"===n||"MultiPoint"===n)N(e,u,i,o,s);else if("LineString"===n)R(e,u,i,o,s,!1,a.lineMetrics);else if("MultiLineString"===n)J(e,u,i,o,s,!1);else if("Polygon"===n)J(e,u,i,o,s,!0);else if("MultiPolygon"===n)for(const t of e){const e=[];J(t,e,i,o,s,!0),e.length&&u.push(e);}if(u.length){if(a.lineMetrics&&"LineString"===n){for(const e of u)l.push(L(t.id,n,e,t.tags));continue}"LineString"!==n&&"MultiLineString"!==n||(1===u.length?(n="LineString",u=u[0]):n="MultiLineString"),"Point"!==n&&"MultiPoint"!==n||(n=3===u.length?"Point":"MultiPoint"),l.push(L(t.id,n,u,t.tags));}}return l.length?l:null}function N(e,t,i,o,s){for(let n=0;n=i&&r<=o&&Y(t,e[n],e[n+1],e[n+2]);}}function R(e,t,i,o,s,n,r){let a=W(e);const l=0===s?q:X;let c,u,h=e.start;for(let d=0;di&&(u=l(a,f,g,m,y,i),r&&(a.start=h+c*u)):v>o?w=i&&(u=l(a,f,g,m,y,i),x=!0),w>o&&v<=o&&(u=l(a,f,g,m,y,o),x=!0),!n&&x&&(r&&(a.end=h+c*u),t.push(a),a=W(e)),r&&(h+=c);}let d=e.length-3;const f=e[d],g=e[d+1],p=0===s?f:g;p>=i&&p<=o&&Y(a,f,g,e[d+2]),d=a.length-3,n&&d>=3&&(a[d]!==a[0]||a[d+1]!==a[1])&&Y(a,a[0],a[1],a[2]),a.length&&t.push(a);}function W(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function J(e,t,i,o,s,n){for(const r of e)R(r,t,i,o,s,n,!1);}function Y(e,t,i,o){e.push(t,i,o);}function q(e,t,i,o,s,n){const r=(n-t)/(o-t);return Y(e,n,i+(s-i)*r,1),r}function X(e,t,i,o,s,n){const r=(n-i)/(s-i);return Y(e,t+(o-t)*r,n,1),r}function H(e,t){const i=[];for(let o=0;o0&&t.size<(s?r:o))return void(i.numPoints+=t.length/3);const a=[];for(let e=0;er)&&(i.numSimplified++,a.push(t[e],t[e+1])),i.numPoints++;s&&function(e,t){let i=0;for(let t=0,o=e.length,s=o-2;t0===t)for(let t=0,i=e.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");let o=function(e,t){const i=[];if("FeatureCollection"===e.type)for(let o=0;o1&&console.time("creation"),d=this.tiles[h]=U(e,t,i,o,l),this.tileCoords.push({z:t,x:i,y:o}),c)){c>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,i,o,d.numFeatures,d.numPoints,d.numSimplified),console.timeEnd("creation"));const e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++;}if(d.source=e,null==s){if(t===l.indexMaxZoom||d.numPoints<=l.indexMaxPoints)continue}else {if(t===l.maxZoom||t===s)continue;if(null!=s){const e=s-t;if(i!==n>>e||o!==r>>e)continue}}if(d.source=null,0===e.length)continue;c>1&&console.time("clipping");const f=.5*l.buffer/l.extent,g=.5-f,p=.5+f,m=1+f;let y=null,v=null,w=null,x=null,b=j(e,u,i-f,i+p,0,d.minX,d.maxX,l),S=j(e,u,i+g,i+m,0,d.minX,d.maxX,l);e=null,b&&(y=j(b,u,o-f,o+p,1,d.minY,d.maxY,l),v=j(b,u,o+g,o+m,1,d.minY,d.maxY,l),b=null),S&&(w=j(S,u,o-f,o+p,1,d.minY,d.maxY,l),x=j(S,u,o+g,o+m,1,d.minY,d.maxY,l),S=null),c>1&&console.timeEnd("clipping"),a.push(y||[],t+1,2*i,2*o),a.push(v||[],t+1,2*i,2*o+1),a.push(w||[],t+1,2*i+1,2*o),a.push(x||[],t+1,2*i+1,2*o+1);}}getTile(e,t,i){e=+e,t=+t,i=+i;const o=this.options,{extent:s,debug:n}=o;if(e<0||e>24)return null;const r=1<1&&console.log("drilling down to z%d-%d-%d",e,t,i);let l,c=e,u=t,h=i;for(;!l&&c>0;)c--,u>>=1,h>>=1,l=this.tiles[ie(c,u,h)];return l&&l.source?(n>1&&(console.log("found parent tile z%d-%d-%d",c,u,h),console.time("drilling down")),this.splitTile(l.source,c,u,h,e,t,i),n>1&&console.timeEnd("drilling down"),this.tiles[a]?B(this.tiles[a],s):null):null}}function ie(e,t,i){return 32*((1<{r.properties=e;const t={};for(const e of a)t[e]=o[e].evaluate(n,r);return t},t.reduce=(e,t)=>{r.properties=t;for(const t of a)n.accumulated=e[t],e[t]=s[t].evaluate(n,r);},t}(t)).load(i.features):function(e,t){return new te(e,t)}(i,t.geojsonVtOptions),this.loaded={};const s={data:i};if(o){const e=o.finish();e&&(s.resourceTiming={},s.resourceTiming[t.source]=JSON.parse(JSON.stringify(e)));}return s}catch(t){if(delete this._pendingRequest,e.cy(t))return {abandoned:!0};throw t}}))}getData(){return e._(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(e){const t=this.loaded;return t&&t[e.uid]?super.reloadTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){let o=yield this.loadGeoJSON(t,i);if(delete this._pendingRequest,"object"!=typeof o)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(u(o,!0),t.filter){const i=e.cT(t.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===i.result)throw new Error(i.value.map((e=>`${e.key}: ${e.message}`)).join(", "));const s=o.features.filter((e=>i.value.evaluate({zoom:0},e)));o={type:"FeatureCollection",features:s};}return o}))}loadGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){const{promoteId:o}=t;if(t.request){const s=yield e.j(t.request,i);return this._dataUpdateable=e.cV(s.data,o)?e.cU(s.data,o):void 0,s.data}if("string"==typeof t.data)try{const i=JSON.parse(t.data);return this._dataUpdateable=e.cV(i,o)?e.cU(i,o):void 0,i}catch(e){throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}if(!t.dataDiff)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${t.source}`);return e.cW(this._dataUpdateable,t.dataDiff,o),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(t){return e._(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset)}}class se{constructor(t){this.self=t,this.actor=new e.J(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=new Map,this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.cA,this.self.removeProtocol=e.cB,this.self.registerRTLTextPlugin=t=>{e.cX.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,i)=>e._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(t,i.source).removeTile(i);})))),this.actor.registerMessageHandler("GCEZ",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterExpansionZoom(i)})))),this.actor.registerMessageHandler("GCC",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterChildren(i)})))),this.actor.registerMessageHandler("GCL",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterLeaves(i)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("GD",((e,t)=>this._getWorkerSource(e,t.type,t.source).getData())),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,i)=>e._(this,void 0,void 0,(function*(){if(!this.workerSources[t]||!this.workerSources[t][i.type]||!this.workerSources[t][i.type][i.source])return;const e=this.workerSources[t][i.type][i.source];delete this.workerSources[t][i.type][i.source],void 0!==e.removeSource&&e.removeSource(i);})))),this.actor.registerMessageHandler("RM",(t=>e._(this,void 0,void 0,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t],this.globalStates.delete(t);})))),this.actor.registerMessageHandler("SR",((t,i)=>e._(this,void 0,void 0,(function*(){this.referrer=i;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,i)=>e._(this,void 0,void 0,(function*(){this.self.importScripts(i);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).update(i.layers,i.removedIds,this._getGlobalState(t));})))),this.actor.registerMessageHandler("UGS",((t,i)=>e._(this,void 0,void 0,(function*(){const e=this._getGlobalState(t);for(const t in i)e[t]=i[t];})))),this.actor.registerMessageHandler("SL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).replace(i,this._getGlobalState(t));}))));}_getGlobalState(e){let t=this.globalStates.get(e);return t||(t={},this.globalStates.set(e,t)),t}_setImages(t,i){return e._(this,void 0,void 0,(function*(){this.availableImages[t]=i;for(const e in this.workerSources[t]){const o=this.workerSources[t][e];for(const e in o)o[e].availableImages=i;}}))}_syncRTLPluginState(t,i){return e._(this,void 0,void 0,(function*(){return yield e.cX.syncState(i,this.self.importScripts)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(e){let i=this.layerIndexes[e];return i||(i=this.layerIndexes[e]=new t),i}_getWorkerSource(e,t,i){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][i]){const o={sendAsync:(t,i)=>(t.targetMapId=e,this.actor.sendAsync(t,i))};switch(t){case "vector":this.workerSources[e][t][i]=new n(o,this._getLayerIndex(e),this._getAvailableImages(e));break;case "geojson":this.workerSources[e][t][i]=new oe(o,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][i]=new this.externalWorkerSourceTypes[t](o,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][t][i]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new r),this.demWorkerSources[e][t]}}return e.i(self)&&(self.worker=new se(self)),se})); + +define("index",["exports","./shared"],(function(e,t){"use strict";var i="5.7.2";function o(){var e=new t.A(4);return t.A!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}let r,a;const s={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frame(e,i,o){const r=requestAnimationFrame((e=>{a(),i(e);})),{unsubscribe:a}=t.s(e.signal,"abort",(()=>{a(),cancelAnimationFrame(r),o(t.c());}),!1);},frameAsync(e){return new Promise(((t,i)=>{this.frame(e,t,i);}))},getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(r||(r=document.createElement("a")),r.href=e,r.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==a&&(a=matchMedia("(prefers-reduced-motion: reduce)")),a.matches)}};class n{static testProp(e){if(!n.docStyle)return e[0];for(let t=0;t{window.removeEventListener("click",n.suppressClickInternal,!0);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,o){const r=i.boundingClientRect;return new t.P((o.clientX-r.left)/i.x-e.clientLeft,(o.clientY-r.top)/i.y-e.clientTop)}static mousePos(e,t){const i=n.getScale(e);return n.getPoint(e,i,t)}static touchPos(e,t){const i=[],o=n.getScale(e);for(let r=0;r{c&&_(c),c=null,d=!0;},h.onerror=()=>{u=!0,c=null;},h.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(e){let i,o,r,a;e.resetRequestQueue=()=>{i=[],o=0,r=0,a={};},e.addThrottleControl=e=>{const t=r++;return a[t]=e,t},e.removeThrottleControl=e=>{delete a[e],n();},e.getImage=(e,o,r=!0)=>new Promise(((a,s)=>{l.supported&&(e.headers||(e.headers={}),e.headers.accept="image/webp,*/*"),t.e(e,{type:"image"}),i.push({abortController:o,requestParameters:e,supportImageRefresh:r,state:"queued",onError:e=>{s(e);},onSuccess:e=>{a(e);}}),n();}));const s=e=>t._(this,void 0,void 0,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:r,onError:a,onSuccess:s,abortController:l}=e,h=!1===r&&!t.i(self)&&!t.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),!0));o++;const u=h?c(i,l):t.m(i,l);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.b(i.data)?s(i):i.data&&s({data:yield(d=i.data,"function"==typeof createImageBitmap?t.f(d):t.h(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,a(t);}finally{o--,n();}var d;})),n=()=>{const e=(()=>{for(const e of Object.keys(a))if(a[e]())return !0;return !1})()?t.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=o;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:s(e);}},c=(e,i)=>new Promise(((o,r)=>{const a=new Image,s=e.url,n=e.credentials;n&&"include"===n?a.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.d(s))&&(a.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{a.src="",r(t.c());})),a.fetchPriority="high",a.onload=()=>{a.onerror=a.onload=null,o({data:a});},a.onerror=()=>{a.onerror=a.onload=null,i.signal.aborted||r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));},a.src=s;}));}(p||(p={})),p.resetRequestQueue();class m{constructor(e){this._transformRequestFn=null!=e?e:null;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}function f(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:o,url:r}of e){const e=`${o}${r}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:o,url:r}));}}return t}function g(e,t,i){try{const o=new URL(e);return o.pathname+=`${t}${i}`,o.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}function v(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class b extends t.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.R({width:1,height:1}),this.dirty=!0;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.R({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let o=!0;const r=i.data||i.spriteData;return this._validateStretch(i.stretchX,r&&r.width)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchX" value`))),o=!1),this._validateStretch(i.stretchY,r&&r.height)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchY" value`))),o=!1),this._validateContent(i.content,i)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "content" value`))),o=!1),o}_validateStretch(e,t){if(!e)return !0;let i=0;for(const o of e){if(o[0]{let o=!0;if(!this.isLoaded())for(const t of e)this.images[t]||(o=!1);this.isLoaded()||o?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const o of e){let e=this.getImage(o);e||(this.fire(new t.l("styleimagemissing",{id:o})),e=this.getImage(o)),e?i[o]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.w(`Image "${o}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);}return i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],o=this.getImage(e);if(!o)return null;if(i&&i.position.version===o.version)return i.position;if(i)i.position.version=o.version;else {const i={w:o.data.width+2,h:o.data.height+2,x:0,y:0},r=new t.I(i,o);this.patterns[e]={bin:i,position:r};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const i=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new t.T(e,this.atlasImage,i.RGBA),this.atlasTexture.bind(i.LINEAR,i.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:o}=t.p(e),r=this.atlasImage;r.resize({width:i||1,height:o||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],o=i.x+1,a=i.y+1,s=this.getImage(e).data,n=s.width,l=s.height;t.R.copy(s,r,{x:0,y:0},{x:o,y:a},{width:n,height:l}),t.R.copy(s,r,{x:0,y:l-1},{x:o,y:a-1},{width:n,height:1}),t.R.copy(s,r,{x:0,y:0},{x:o,y:a+l},{width:n,height:1}),t.R.copy(s,r,{x:n-1,y:0},{x:o-1,y:a},{width:1,height:l}),t.R.copy(s,r,{x:0,y:0},{x:o+n,y:a},{width:1,height:l});}this.dirty=!0;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=!0;const e=this.getImage(i);e||t.w(`Image with ID: "${i}" was not found`),v(e)&&this.updateImage(i,e);}}}const x=1e20;function y(e,t,i,o,r,a,s,n,l){for(let c=t;c-1);l++,a[l]=n,s[l]=c,s[l+1]=x;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(t.ranges[r])return {stack:e,id:i,glyph:o};if(!this.url)throw new Error("glyphsUrl is not set");if(!t.requests[r]){const i=T.loadGlyphRange(e,r,this.url,this.requestManager);t.requests[r]=i;}const a=yield t.requests[r];for(const e in a)this._doesCharSupportLocalGlyph(+e)||(t.glyphs[+e]=a[+e]);return t.ranges[r]=!0,{stack:e,id:i,glyph:a[i]||null}}))}_doesCharSupportLocalGlyph(e){return !!this.localIdeographFontFamily&&(/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(e))||t.u["CJK Unified Ideographs"](e)||t.u["Hangul Syllables"](e)||t.u.Hiragana(e)||t.u.Katakana(e)||t.u["CJK Symbols and Punctuation"](e)||t.u["Halfwidth and Fullwidth Forms"](e))}_tinySDF(e,i,o){const r=this.localIdeographFontFamily;if(!r)return;if(!this._doesCharSupportLocalGlyph(o))return;let a=e.tinySDF;if(!a){let t="400";/bold/i.test(i)?t="900":/medium/i.test(i)?t="500":/light/i.test(i)&&(t="200"),a=e.tinySDF=new T.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,lang:this.lang,fontFamily:r,fontWeight:t});}const s=a.draw(String.fromCharCode(o));return {id:o,bitmap:new t.q({width:s.width||60,height:s.height||60},s.data),metrics:{width:s.glyphWidth/2||24,height:s.glyphHeight/2||24,left:s.glyphLeft/2+.5||0,top:s.glyphTop/2-27.5||-8,advance:s.glyphAdvance/2||24,isDoubleResolution:!0}}}}T.loadGlyphRange=function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=256*i,s=a+255,n=r.transformRequest(o.replace("{fontstack}",e).replace("{range}",`${a}-${s}`),"Glyphs"),l=yield t.n(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${a}-${s}`);const c={};for(const e of t.o(l.data))c[e.id]=e;return c}))},T.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:o=.25,fontFamily:r="sans-serif",fontWeight:a="normal",fontStyle:s="normal",lang:n=null}={}){this.buffer=t,this.cutoff=o,this.radius=i,this.lang=n;const l=this.size=e+4*t,c=this._createCanvas(l),h=this.ctx=c.getContext("2d",{willReadFrequently:!0});h.font=`${s} ${a} ${e}px ${r}`,h.textBaseline="alphabetic",h.textAlign="left",h.fillStyle="black",this.gridOuter=new Float64Array(l*l),this.gridInner=new Float64Array(l*l),this.f=new Float64Array(l),this.z=new Float64Array(l+1),this.v=new Uint16Array(l);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:o,actualBoundingBoxLeft:r,actualBoundingBoxRight:a}=this.ctx.measureText(e),s=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(a-r))),l=Math.min(this.size-this.buffer,s+Math.ceil(o)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:s,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;this.lang&&(p.lang=this.lang),p.clearRect(m,m,n,l),p.fillText(e,m,m+s);const v=p.getImageData(m,m,n,l);g.fill(x,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[o]=e<0?e*e:0;}}y(g,0,0,c,h,c,this.f,this.v,this.z),y(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(s=e[++a]);const l=Math.abs(n-s.left),c=Math.abs(n-s.right),h=Math.min(l,c);let u;const d=t/i*(o+1);if(s.isDash){const e=o-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=o-Math.sqrt(h*h+d*d);this.data[r+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],o=e[t+1];i.zeroLength?e.splice(t,1):o&&o.isDash===i.isDash&&(o.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const o=this.width*this.nextRow;let r=0,a=e[r];for(let t=0;t1&&(a=e[++r]);const i=Math.abs(t-a.left),s=Math.abs(t-a.right),n=Math.min(i,s);this.data[o+t]=Math.max(0,Math.min(255,(a.isDash?n:-n)+128));}}addDash(e,i){const o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.w("LineAtlas out of space"),null;let a=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[R]}numActive(){return Object.keys(this.active).length}}const D=Math.floor(s.hardwareConcurrency/2);let A,L;function k(){return A||(A=new z),A}z.workerCount=t.H(globalThis)?Math.max(Math.min(D,3),1):1;class F{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const o=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}}function B(){return L||(L=new F(k(),t.K),L.registerMessageHandler("GR",((e,i,o)=>t.m(i,o)))),L}function O(e,i){const o=t.L();return t.M(o,o,[1,1,0]),t.N(o,o,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.O(o,o,e.calculatePosMatrix(i.toUnwrapped())):o}function j(e,t,i,o,r,a,s){var n;const l=function(e,t,i){if(e)for(const o of e){const e=t[o];if(e&&e.source===i&&"fill-extrusion"===e.type)return !0}else for(const e in t){const o=t[e];if(o.source===i&&"fill-extrusion"===o.type)return !0}return !1}(null!==(n=null==r?void 0:r.layers)&&void 0!==n?n:null,t,e.id),c=a.maxPitchScaleFactor(),h=e.tilesIn(o,c,l);h.sort(N);const u=[];for(const o of h)u.push({wrappedTileID:o.tileID.wrapped().key,queryResults:o.tile.queryRenderedFeatures(t,i,e._state,o.queryGeometry,o.cameraQueryGeometry,o.scale,r,a,c,O(e.transform,o.tileID),s?(e,t)=>s(o.tileID,e,t):void 0)});return function(e,t){for(const i in e)for(const o of e[i])U(o,t);return e}(function(e){const t={},i={};for(const o of e){const e=o.queryResults,r=o.wrappedTileID,a=i[r]=i[r]||{};for(const i in e){const o=e[i],r=a[i]=a[i]||{},s=t[i]=t[i]||[];for(const e of o)r[e.featureIndex]||(r[e.featureIndex]=!0,s.push(e));}}return t}(u),e)}function N(e,t){const i=e.tileID,o=t.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}function U(e,t){const i=e.feature,o=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=o;}function Z(e,i,o){return t._(this,void 0,void 0,(function*(){let r=e;if(e.url?r=(yield t.j(i.transformRequest(e.url,"Source"),o)).data:yield s.frameAsync(o),!r)return null;const a=t.Q(t.e(r,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in r&&r.vector_layers&&(a.vectorLayerIds=r.vector_layers.map((e=>e.id))),a}))}class G{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}extend(e){const i=this._sw,o=this._ne;let r,a;if(e instanceof t.S)r=e,a=e;else {if(!(e instanceof G))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(G.convert(e)):this.extend(t.S.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.S.convert(e)):this;if(r=e._sw,a=e._ne,!r||!a)return this}return i||o?(i.lng=Math.min(r.lng,i.lng),i.lat=Math.min(r.lat,i.lat),o.lng=Math.max(a.lng,o.lng),o.lat=Math.max(a.lat,o.lat)):(this._sw=new t.S(r.lng,r.lat),this._ne=new t.S(a.lng,a.lat)),this}getCenter(){return new t.S((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new t.S(this.getWest(),this.getNorth())}getSouthEast(){return new t.S(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(e){const{lng:i,lat:o}=t.S.convert(e);let r=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(r=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=o&&o<=this._ne.lat&&r}static convert(e){return e instanceof G?e:e?new G(e):e}static fromLngLat(e,i=0){const o=360*i/40075017,r=o/Math.cos(Math.PI/180*e.lat);return new G(new t.S(e.lng-r,e.lat-o),new t.S(e.lng+r,e.lat+o))}adjustAntiMeridian(){const e=new t.S(this._sw.lng,this._sw.lat),i=new t.S(this._ne.lng,this._ne.lat);return new G(e,e.lng>i.lng?new t.S(i.lng+360,i.lat):i)}}class V{constructor(e,t,i){this.bounds=G.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),o=Math.floor(t.V(this.bounds.getWest())*i),r=Math.floor(t.U(this.bounds.getNorth())*i),a=Math.ceil(t.V(this.bounds.getEast())*i),s=Math.ceil(t.U(this.bounds.getSouth())*i);return e.x>=o&&e.x=r&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.e({},this._options)}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};i.request.collectResourceTiming=this._collectResourceTiming;let o="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),o="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:o,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_afterTileLoadWorkerResponse(e,t){if(t&&t.resourceTiming&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return !1}}class q extends t.E{constructor(e,i,o,r){super(),this.id=e,this.dispatcher=o,this.setEventedParent(r),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.e({type:"raster"},i),t.e(this,t.Q(i,["url","scheme","tileSize"]));}load(){return t._(this,arguments,void 0,(function*(e=!1){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield Z(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,i&&(t.e(this,i),i.bounds&&(this.tileBounds=new V(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.l("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(!0);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.e({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const o=yield p.getImage(this.map._requestManager.transformRequest(i,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(o&&o.data){this.map._refreshExpiredTiles&&(o.cacheControl||o.expires)&&e.setExpiryData({cacheControl:o.cacheControl,expires:o.expires});const i=this.map.painter.context,r=i.gl,a=o.data;e.texture=this.map.painter.getTileTexture(a.width),e.texture?e.texture.update(a,{useMipmap:!0}):(e.texture=new t.T(i,a,r.RGBA,{useMipmap:!0}),e.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return !1}}class W extends q{constructor(e,i,o,r){super(e,i,o,r),this.type="raster-dem",this.maxzoom=22,this._options=t.e({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),o=this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield p.getImage(o,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const o=i.data;this.map._refreshExpiredTiles&&(i.cacheControl||i.expires)&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const r=t.b(o)&&t.W()?o:yield this.readImageNow(o),a={type:this.type,uid:e.uid,source:this.id,rawImageData:r,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!e.actor||"expired"===e.state){e.actor=this.dispatcher.getActor();const t=yield e.actor.sendAsync({type:"LDT",data:a});e.dem=t,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t._(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&t.X()){const i=e.width+2,o=e.height+2;try{return new t.R({width:i,height:o},yield t.Y(e,-1,-1,i,o))}catch(e){}}return s.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,o=Math.pow(2,i.z),r=(i.x-1+o)%o,a=0===i.x?e.wrap-1:e.wrap,s=(i.x+1+o)%o,n=i.x+1===o?e.wrap+1:e.wrap,l={};return l[new t.Z(e.overscaledZ,a,i.z,r,i.y).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y).key]={backfilled:!1},i.y>0&&(l[new t.Z(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y-1).key]={backfilled:!1}),i.y+1e.coordinates)).flat(1/0):e.coordinates.flat(1/0)}getBounds(){return t._(this,void 0,void 0,(function*(){const e=new G,t=yield this.getData();let i;switch(t.type){case "FeatureCollection":i=t.features.map((e=>this.getCoordinatesFromGeometry(e.geometry))).flat(1/0);break;case "Feature":i=this.getCoordinatesFromGeometry(t.geometry);break;default:i=this.getCoordinatesFromGeometry(t);}if(0==i.length)return e;for(let t=0;t0&&t.e(r,{resourceTiming:i}),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"metadata"}))),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"content"})));}catch(e){if(this._isUpdatingWorker=!1,this._removed)return void this.fire(new t.l("dataabort",{dataType:"source"}));this.fire(new t.k(e));}finally{(this._pendingWorkerUpdate.data||this._pendingWorkerUpdate.diff)&&this._updateWorkerData();}}))}loaded(){return !this._isUpdatingWorker&&void 0===this._pendingWorkerUpdate.data&&void 0===this._pendingWorkerUpdate.diff}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};e.abortController=new AbortController;const o=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(o,this.map.painter,"RT"===t);}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=!0;}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return !1}}class X extends t.E{constructor(e,t,i,o){super(),this.flippedWindingOrder=!1,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(o),this.options=t;}load(e){return t._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield p.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.a1.fromLngLat);var o;return this.tileID=function(e){const i=t.a2.fromPoints(e),o=i.width(),r=i.height(),a=Math.max(o,r),s=Math.max(0,Math.floor(-Math.log(a)/Math.LN2)),n=Math.pow(2,s);return new t.a4(s,Math.floor((i.minX+i.maxX)/2*n),Math.floor((i.minY+i.maxY)/2*n))}(i),this.terrainTileRanges=this._getOverlappingTileRanges(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((o=this.tileCoords)[1].x-o[0].x)*(o[2].y-o[0].y)-(o[1].y-o[0].y)*(o[2].x-o[0].x)<0,this.fire(new t.l("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new t.T(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t._(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return !1}_getOverlappingTileRanges(e){const{minX:i,minY:o,maxX:r,maxY:a}=t.a2.fromPoints(e),s={};for(let e=0;e<=t.a3;e++){const t=Math.pow(2,e),n=Math.floor(i*t),l=Math.floor(o*t),c=Math.floor(r*t),h=Math.floor(a*t);s[e]={minTileX:n,minTileY:l,maxTileX:c,maxTileY:h};}return s}}class K extends X{constructor(e,t,i,o){super(e,t,i,o),this.roundZoom=!0,this.type="video",this.options=t;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!1;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,"Source").url);try{const e=yield t.a5(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.k(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.k(new t.a6(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.T(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class Y extends X{constructor(e,i,o,r){super(e,i,o,r),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.k(new t.a6(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.k(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,o=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.T(i,this.canvas,o.RGBA,{premultiply:!0});let r=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=!0);}r&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return !0;return !1}}const Q={},J=e=>{switch(e){case "geojson":return H;case "image":return X;case "raster":return q;case "raster-dem":return W;case "vector":return $;case "video":return K;case "canvas":return Y}return Q[e]},ee="RTLPluginLoaded";class te extends t.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=B();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t._(this,arguments,void 0,(function*(e,t=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=s.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.l(ee));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let ie=null;function oe(){return ie||(ie=new te),ie}class re{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=e,this.uid=t.a7(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(e){const t=e+this.timeAdded;tt.getLayer(e))).filter(Boolean);if(0!==e.length){o.layers=e,o.stateDependentLayerIds&&(o.stateDependentLayers=o.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=o;}}return i}(e.buckets,null==i?void 0:i.style),this.hasSymbolBuckets=!1;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9){if(this.hasSymbolBuckets=!0,!o)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9&&i.hasRTLText){this.hasRTLText=!0,oe().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.a8;}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const i=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new t.T(e,this.imageAtlas.image,i.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new t.T(e,this.glyphAtlasImage,i.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,o,r,a,s,n,l,c,h){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:o,cameraQueryGeometry:r,scale:a,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:s,queryPadding:this.queryPadding*l,getElevation:h},e,t,i):{}}querySourceFeatures(e,i){const o=this.latestFeatureIndex;if(!o||!o.rawTileData)return;const r=o.loadVTLayers(),a=i&&i.sourceLayer?i.sourceLayer:"",s=r._geojsonTileLayer||r[a];if(!s)return;const n=t.aa(null==i?void 0:i.filter,null==i?void 0:i.globalState),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=!1;else if(i)if(this.expirationTime{this.remove(e,r);}),i)),this.data[o].push(r),this.order.push(o),this.order.length>this.max){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}has(e){return e.wrapped().key in this.data}getAndRemove(e){return this.has(e)?this._getAndRemoveByKey(e.wrapped().key):null}_getAndRemoveByKey(e){const t=this.data[e].shift();return t.timeout&&clearTimeout(t.timeout),0===this.data[e].length&&delete this.data[e],this.order.splice(this.order.indexOf(e),1),t.value}getByKey(e){const t=this.data[e];return t?t[0].value:null}get(e){return this.has(e)?this.data[e.wrapped().key][0].value:null}remove(e,t){if(!this.has(e))return this;const i=e.wrapped().key,o=void 0===t?0:this.data[i].indexOf(t),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(e){for(this.max=e;this.order.length>this.max;){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}filter(e){const t=[];for(const i in this.data)for(const o of this.data[i])e(o.value)||t.push(o);for(const e of t)this.remove(e.value.tileID,e);}}class se{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(e,i,o){const r=String(i);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][r]=this.stateChanges[e][r]||{},t.e(this.stateChanges[e][r],o),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==r&&(this.deletedStates[e][t]=null);}else if(this.deletedStates[e]&&null===this.deletedStates[e][r]){this.deletedStates[e][r]={};for(const t in this.state[e][r])o[t]||(this.deletedStates[e][r][t]=null);}else for(const t in o)this.deletedStates[e]&&this.deletedStates[e][r]&&null===this.deletedStates[e][r][t]&&delete this.deletedStates[e][r][t];}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const o=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&void 0!==t)null!==this.deletedStates[e][o]&&(this.deletedStates[e][o]=this.deletedStates[e][o]||{},this.deletedStates[e][o][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][o])for(i in this.deletedStates[e][o]={},this.stateChanges[e][o])this.deletedStates[e][o][i]=null;else this.deletedStates[e][o]=null;else this.deletedStates[e]=null;}getState(e,i){const o=String(i),r=t.e({},(this.state[e]||{})[o],(this.stateChanges[e]||{})[o]);if(null===this.deletedStates[e])return {};if(this.deletedStates[e]){const t=this.deletedStates[e][i];if(null===t)return {};for(const e in t)delete r[e];}return r}initializeTileState(e,t){e.setFeatureState(this.state,t);}coalesceChanges(e,i){const o={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const i={};for(const o in this.stateChanges[e])this.state[e][o]||(this.state[e][o]={}),t.e(this.state[e][o],this.stateChanges[e][o]),i[o]=this.state[e][o];o[e]=i;}for(const e in this.deletedStates){this.state[e]=this.state[e]||{};const i={};if(null===this.deletedStates[e])for(const t in this.state[e])i[t]={},this.state[e][t]={};else for(const t in this.deletedStates[e]){if(null===this.deletedStates[e][t])this.state[e][t]={};else for(const i of Object.keys(this.deletedStates[e][t]))delete this.state[e][t][i];i[t]=this.state[e][t];}o[e]=o[e]||{},t.e(o[e],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(o).length)for(const t in e)e[t].setFeatureState(o,i);}}const ne=89.25;function le(e,i){const o=t.ah(i.lat,-t.ai,t.ai);return new t.P(t.V(i.lng)*e,t.U(o)*e)}function ce(e,i){return new t.a1(i.x/e,i.y/e).toLngLat()}function he(e){return e.cameraToCenterDistance*Math.min(.85*Math.tan(t.ae(90-e.pitch)),Math.tan(t.ae(ne-e.pitch)))}function ue(e,i){const o=e.canonical,r=i/t.af(o.z),a=o.x+Math.pow(2,o.z)*e.wrap,s=t.ag(new Float64Array(16));return t.M(s,s,[a*r,o.y*r,0]),t.N(s,s,[r/t.$,r/t.$,1]),s}function de(e,i,o,r,a){const s=t.a1.fromLngLat(e,i),n=a*t.aj(1,e.lat),l=n*Math.cos(t.ae(o)),c=Math.sqrt(n*n-l*l),h=c*Math.sin(t.ae(-r)),u=c*Math.cos(t.ae(-r));return new t.a1(s.x+h,s.y+u,s.z+l)}function _e(e,t,i){const o=t.intersectsFrustum(e);if(!i||0===o)return o;const r=t.intersectsPlane(i);return 0===r?0:2===o&&2===r?2:1}function pe(e,t,i){let o=0;const r=(i-t)/10;for(let a=0;a<10;a++)o+=r*Math.pow(Math.cos(t+(a+.5)/10*(i-t)),e);return o}function me(e,i){return function(o,r,a,s,n){const l=2*((e-1)/t.ak(Math.cos(t.ae(ne-n))/Math.cos(t.ae(ne)))-1),c=Math.acos(a/s),h=2*pe(l-1,0,t.ae(n/2)),u=Math.min(t.ae(ne),c+t.ae(n/2)),d=pe(l-1,Math.min(u,c-t.ae(n/2)),u),_=Math.atan(r/a),p=Math.hypot(r,a);let m=o;return m+=t.ak(s/p/Math.max(.5,Math.cos(t.ae(n/2)))),m+=l*t.ak(Math.cos(_))/2,m-=t.ak(Math.max(1,d/h/i))/2,m}}const fe=me(9.314,3);function ge(e,i){const o=(i.roundZoom?Math.round:Math.floor)(e.zoom+t.ak(e.tileSize/i.tileSize));return Math.max(0,o)}function ve(e,i){const o=e.getCameraFrustum(),r=e.getClippingPlane(),a=e.screenPointToMercatorCoordinate(e.getCameraPoint()),s=t.a1.fromLngLat(e.center,e.elevation);a.z=s.z+Math.cos(e.pitchInRadians)*e.cameraToCenterDistance/e.worldSize;const n=e.getCoveringTilesDetailsProvider(),l=n.allowVariableZoom(e,i),c=ge(e,i),h=i.minzoom||0,u=void 0!==i.maxzoom?i.maxzoom:e.maxZoom,d=Math.min(Math.max(0,c),u),_=Math.pow(2,d),p=[_*a.x,_*a.y,0],m=[_*s.x,_*s.y,0],f=Math.hypot(s.x-a.x,s.y-a.y),g=Math.abs(s.z-a.z),v=Math.hypot(f,g),b=e=>({zoom:0,x:0,y:0,wrap:e,fullyVisible:!1}),x=[],y=[];if(e.renderWorldCopies&&n.allowWorldCopies())for(let e=1;e<=3;e++)x.push(b(-e)),x.push(b(e));for(x.push(b(0));x.length>0;){const _=x.pop(),f=_.x,b=_.y;let w=_.fullyVisible;const T={x:f,y:b,z:_.zoom},P=n.getTileBoundingVolume(T,_.wrap,e.elevation,i);if(!w){const e=_e(o,P,r);if(0===e)continue;w=2===e;}const C=n.distanceToTile2d(a.x,a.y,T,P);let I=c;l&&(I=(i.calculateTileZoom||fe)(e.zoom+t.ak(e.tileSize/i.tileSize),C,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const M=Math.min(I,u);if(_.wrap=n.getWrap(s,T,_.wrap),_.zoom>=M){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return y.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}const be=t.a2.fromPoints([new t.P(0,0),new t.P(t.$,t.$)]);class xe extends t.E{constructor(e,t,i){super(),this.id=e,this.dispatcher=i,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=!1;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,o)=>{const r=new(J(t.type))(e,t,i,o);if(r.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${r.id}`);return r})(e,t,i,this),this._tiles={},this._cache=new ae(0,(e=>this._unloadTile(e))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new se,this._didEmitContent=!1,this._updated=!1;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e);}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return !0;if(!this._updated)return !1;for(const e in this._tiles){const t=this._tiles[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}return !0}getSource(){return this._source}pause(){this._paused=!0;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,o){return t._(this,void 0,void 0,(function*(){try{yield this._source.loadTile(e),this._tileLoaded(e,i,o);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.k(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.l("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const t in this._tiles){const i=this._tiles[t];i.upload(e),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(ye).map((e=>e.key))}getRenderableIds(e){const i=[];for(const t in this._tiles)this._isIdRenderable(t,e)&&i.push(this._tiles[t]);return e?i.sort(((e,i)=>{const o=e.tileID,r=i.tileID,a=new t.P(o.canonical.x,o.canonical.y)._rotate(-this.transform.bearingInRadians),s=new t.P(r.canonical.x,r.canonical.y)._rotate(-this.transform.bearingInRadians);return o.overscaledZ-r.overscaledZ||s.y-a.y||s.x-a.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(ye).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return !!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())}reload(e){if(this._paused)this._shouldReloadOnResume=!0;else {this._cache.reset();for(const t in this._tiles)e?this._reloadTile(t,"expired"):"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading");}}_reloadTile(e,i){return t._(this,void 0,void 0,(function*(){const t=this._tiles[e];t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,o){e.timeAdded=s.now(),"expired"===o&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.l("data",{dataType:"source",tile:e,coord:e.tileID}));}_backfillDEM(e){const t=this.getRenderableIds();for(let o=0;o1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,o),e.neighboringTiles&&e.neighboringTiles[a]&&(e.neighboringTiles[a].backfilled=!0)));}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,o){for(const r in this._tiles){let a=this._tiles[r];if(o[r]||!a.hasData()||a.tileID.overscaledZ<=t||a.tileID.overscaledZ>i)continue;let s=a.tileID;for(;a&&a.tileID.overscaledZ>t+1;){const e=a.tileID.scaledTo(a.tileID.overscaledZ-1);a=this._tiles[e.key],a&&a.hasData()&&(s=e);}let n=s;for(;n.overscaledZ>t;)if(n=n.scaledTo(n.overscaledZ-1),e[n.key]||e[n.canonical.key]){o[s.key]=s;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),o=this._getLoadedTile(t);if(o)return o}}findLoadedSibling(e){return this._getLoadedTile(e)}_getLoadedTile(e){const t=this._tiles[e.key];return t&&t.hasData()?t:this._cache.getByKey(e.wrapped().key)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,o=Math.ceil(e.height/this._source.tileSize)+1,r=Math.floor(i*o*(null===this._maxTileCacheZoomLevels?t.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),a="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(a);}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e={};for(const i in this._tiles){const o=this._tiles[i];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),e[o.tileID.key]=o;}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(e,this._tiles[e]);}}_updateCoveredAndRetainedTiles(e,t,i,o,r,a){const n={},l={},c=Object.keys(e),h=s.now();for(const i of c){const o=e[i],r=this._tiles[i];if(!r||0!==r.fadeEndTime&&r.fadeEndTime<=h)continue;const a=this.findLoadedParent(o,t),s=this.findLoadedSibling(o),c=a||s||null;c&&(this._addTile(c.tileID),n[c.tileID.key]=c.tileID),l[i]=o;}this._retainLoadedChildren(l,o,i,e);for(const t in n)e[t]||(this._coveredTiles[t]=!0,e[t]=n[t]);if(a){const t={},i={};for(const e of r)this._tiles[e.key].hasData()?t[e.key]=e:i[e.key]=e;for(const o in i){const r=i[o].children(this._source.maxzoom);this._tiles[r[0].key]&&this._tiles[r[1].key]&&this._tiles[r[2].key]&&this._tiles[r[3].key]&&(t[r[0].key]=e[r[0].key]=r[0],t[r[1].key]=e[r[1].key]=r[1],t[r[2].key]=e[r[2].key]=r[2],t[r[3].key]=e[r[3].key]=r[3],delete i[o]);}for(const o in i){const r=i[o],a=this.findLoadedParent(r,this._source.minzoom),s=this.findLoadedSibling(r),n=a||s||null;if(n){t[n.tileID.key]=e[n.tileID.key]=n.tileID;for(const e in t)t[e].isChildOf(n.tileID)&&delete t[e];}}for(const e in this._tiles)t[e]||(this._coveredTiles[e]=!0);}}update(e,i){if(!this._sourceLoaded||this._paused)return;let o;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?o=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.Z(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(o=ve(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(o=o.filter((e=>this._source.hasTile(e))))):o=[];const r=ge(e,this._source),a=Math.max(r-xe.maxOverzooming,this._source.minzoom),s=Math.max(r+xe.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const e={};for(const t of o)if(t.canonical.z>this._source.minzoom){const i=t.scaledTo(t.canonical.z-1);e[i.key]=i;const o=t.scaledTo(Math.max(this._source.minzoom,Math.min(t.canonical.z,5)));e[o.key]=o;}o=o.concat(Object.values(e));}const n=0===o.length&&!this._updated&&this._didEmitContent;this._updated=!0,n&&this.fire(new t.l("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(o,r);we(this._source.type)&&this._updateCoveredAndRetainedTiles(l,a,s,r,o,i);for(const e in l)this._tiles[e].clearFadeHold();const c=t.am(this._tiles,l);for(const e of c){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const o={},r={},a=Math.max(t-xe.maxOverzooming,this._source.minzoom),s=Math.max(t+xe.maxUnderzooming,this._source.minzoom),n={};for(const i of e){const e=this._addTile(i);o[i.key]=i,e.hasData()||tthis._source.maxzoom){const e=s.children(this._source.maxzoom)[0],t=this.getTile(e);if(t&&t.hasData()){o[e.key]=e;continue}}else {const e=s.children(this._source.maxzoom);if(4===e.length&&o[e[0].key]&&o[e[1].key]&&o[e[2].key]&&o[e[3].key])continue;if(1===e.length&&o[e[0].key])continue}let n=e.wasRequested();for(let t=s.overscaledZ-1;t>=a;--t){const a=s.scaledTo(t);if(r[a.key])break;if(r[a.key]=!0,e=this.getTile(a),!e&&n&&(e=this._addTile(a)),e){const t=e.hasData();if((t||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||n)&&(o[a.key]=a),n=e.wasRequested(),t)break}}}return o}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,o=this._tiles[e].tileID;for(;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}t.push(o.key);const e=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;o=e;}for(const e of t)this._loadedParentTiles[e]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const e in this._tiles){const t=this._tiles[e].tileID,i=this._getLoadedTile(t);this._loadedSiblingTiles[t.key]=i;}}_addTile(e){let i=this._tiles[e.key];if(i)return i;i=this._cache.getAndRemove(e),i&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));const o=i;return i||(i=new re(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._tiles[e.key]=i,o||this._source.fire(new t.l("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}refreshTiles(e){for(const t in this._tiles)(this._isIdRenderable(t)||"errored"==this._tiles[t].state)&&e.some((e=>e.equals(this._tiles[t].tileID.canonical)))&&this._reloadTile(t,"expired");}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=!0,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){const t=e.sourceDataType;"source"===e.dataType&&"metadata"===t&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===t&&(this.reload(e.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0);}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e in this._tiles)this._removeTile(e);this._cache.reset();}tilesIn(e,i,o){const r=[],a=this.transform;if(!a)return r;const s=a.getCoveringTilesDetailsProvider().allowWorldCopies(),n=o?a.getCameraQueryGeometry(e):e,l=e=>a.screenPointToMercatorCoordinate(e,this.terrain),c=this.transformBbox(e,l,!s),h=this.transformBbox(n,l,!s),u=this.getIds(),d=t.a2.fromPoints(h);for(let e=0;ee.getTilePoint(new t.a1(i.x,i.y))));if(i.expandBy(_),i.intersects(be)){const t=c.map((t=>e.getTilePoint(t))),i=h.map((t=>e.getTilePoint(t)));r.push({tile:o,tileID:s?e:e.unwrapTo(0),queryGeometry:t,cameraQueryGeometry:i,scale:l});}}}return r}transformBbox(e,i,o){let r=e.map(i);if(o){const o=t.a2.fromPoints(e);o.shrinkBy(.001*Math.min(o.width(),o.height()));const a=o.map(i);t.a2.fromPoints(r).covers(a)||(r=r.map((e=>e.x>.5?new t.a1(e.x-1,e.y,e.z):e)));}return r}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._tiles[e].tileID));return this.transform&&this.transform.populateCache(t),t}hasTransition(){if(this._source.hasTransition())return !0;if(we(this._source.type)){const e=s.now();for(const t in this._tiles)if(this._tiles[t].fadeEndTime>=e)return !0}return !1}setFeatureState(e,t,i){this._state.updateState(e=e||"_geojsonTileLayer",t,i);}removeFeatureState(e,t,i){this._state.removeFeatureState(e=e||"_geojsonTileLayer",t,i);}getFeatureState(e,t){return this._state.getState(e=e||"_geojsonTileLayer",t)}setDependencies(e,t,i){const o=this._tiles[e];o&&o.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)));}}function ye(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),o=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||o-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function we(e){return "raster"===e||"image"===e||"video"===e}xe.maxOverzooming=10,xe.maxUnderzooming=3;class Te{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(r-s)/n:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))}}function Pe(e,t){let i=!0;return "always"===e||"never"!==e&&"never"!==t||(i=!1),i}class Ce{constructor(e,t,i){const o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||o<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=o){if(r)return [{key:null,x1:e,y1:t,x2:i,y2:o}];for(let e=0;e0}hitTestCircle(e,t,i,o,r){const a=e-i,s=e+i,n=t-i,l=t+i;if(s<0||a>this.width||l<0||n>this.height)return !1;const c=[];return this._forEachCell(a,n,s,l,this._queryCellCircle,c,{hitTest:!0,overlapMode:o,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},r),c.length>0}_queryCell(e,t,i,o,r,a,s,n){const{seenUids:l,hitTest:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const r=this.bboxes;for(const s of u)if(!l.box[s]){l.box[s]=!0;const u=4*s,d=this.boxKeys[s];if(e<=r[u+2]&&t<=r[u+3]&&i>=r[u+0]&&o>=r[u+1]&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))&&(a.push({key:d,x1:r[u],y1:r[u+1],x2:r[u+2],y2:r[u+3]}),c))return !0}}const d=this.circleCells[r];if(null!==d){const r=this.circles;for(const s of d)if(!l.circle[s]){l.circle[s]=!0;const u=3*s,d=this.circleKeys[s];if(this._circleAndRectCollide(r[u],r[u+1],r[u+2],e,t,i,o)&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))){const e=r[u],t=r[u+1],i=r[u+2];if(a.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return !0}}}return !1}_queryCellCircle(e,t,i,o,r,a,s,n){const{circle:l,seenUids:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=!0;const i=4*t,o=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}const d=this.circleCells[r];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=!0;const i=3*t,o=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}}_forEachCell(e,t,i,o,r,a,s,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(o);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(r.call(this,e,t,i,o,this.xCellCount*l+d,a,s,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,o,r,a){const s=o-e,n=r-t,l=i+a;return l*l>s*s+n*n}_circleAndRectCollide(e,t,i,o,r,a,s){const n=(a-o)/2,l=Math.abs(e-(o+n));if(l>n+i)return !1;const c=(s-r)/2,h=Math.abs(t-(r+c));if(h>c+i)return !1;if(l<=n||h<=c)return !0;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function Ie(e,i,r){const a=t.L();if(!e){const{vecSouth:e,vecEast:t}=Se(i),r=o();r[0]=t[0],r[1]=t[1],r[2]=e[0],r[3]=e[1],s=r,(d=(l=(n=r)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(s[0]=u*(d=1/d),s[1]=-c*d,s[2]=-h*d,s[3]=l*d),a[0]=r[0],a[1]=r[1],a[4]=r[2],a[5]=r[3];}var s,n,l,c,h,u,d;return t.N(a,a,[1/r,1/r,1]),a}function Me(e,i,o,r){if(e){const e=t.L();if(!i){const{vecSouth:t,vecEast:i}=Se(o);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.N(e,e,[r,r,1]),e}return o.pixelsToClipSpaceMatrix}function Se(e){const i=Math.cos(e.rollInRadians),o=Math.sin(e.rollInRadians),r=Math.cos(e.pitchInRadians),a=Math.cos(e.bearingInRadians),s=Math.sin(e.bearingInRadians),n=t.ar();n[0]=-a*r*o-s*i,n[1]=-s*r*o+a*i;const l=t.as(n);l<1e-9?t.at(n):t.au(n,n,1/l);const c=t.ar();c[0]=a*r*i-s*o,c[1]=s*r*i+a*o;const h=t.as(c);return h<1e-9?t.at(c):t.au(c,c,1/h),{vecEast:c,vecSouth:n}}function Ee(e,i,o,r){let a;r?(a=[e,i,r(e,i),1],t.aw(a,a,o)):(a=[e,i,0,1],qe(a,a,o));const s=a[3];return {point:new t.P(a[0]/s,a[1]/s),signedDistanceFromCamera:s,isOccluded:!1}}function Re(e,t){return .5+e/t*.5}function ze(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function De(e,i,o,r,a,s,n,l,c,h,u,d,_){const p=o?e.textSizeData:e.iconSizeData,m=t.an(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=o?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,b=o?e.text.placedSymbolArray:e.icon.placedSymbolArray,x=i.transform.width/i.transform.height;let y=!1;for(let o=0;oMath.abs(o.x-i.x)*r?{useVertical:!0}:(e===t.ao.vertical?i.yo.x)?{needsFlipping:!0}:null}function ke(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:o,symbol:r,fontSize:a,flip:s,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=a/24,_=r.lineOffsetX*d,p=r.lineOffsetY*d;let m;if(r.numGlyphs>1){const e=r.glyphStartIndex+r.numGlyphs,t=r.lineStartIndex,a=r.lineStartIndex+r.lineLength,c=Ae(d,l,_,p,s,r,u,i);if(!c)return {notEnoughRoom:!0};const f=je(c.first.point.x,c.first.point.y,i,o),g=je(c.last.point.x,c.last.point.y,i,o);if(n&&!s){const e=Le(r.writingMode,f,g,h);if(e)return e}m=[c.first];for(let o=r.glyphStartIndex+1;o0?n.point:Fe(i.tileAnchorPoint,s,e,1,i),c=je(e.x,e.y,i,o),u=je(l.x,l.y,i,o),d=Le(r.writingMode,c,u,h);if(d)return d}const e=Ge(d*l.getoffsetX(r.glyphStartIndex),_,p,s,r.segment,r.lineStartIndex,r.lineStartIndex+r.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:!0};m=[e];}for(const e of m)t.av(c,e.point,e.angle);return {}}function Fe(e,t,i,o,r){const a=e.add(e.sub(t)._unit()),s=Oe(a.x,a.y,r).point,n=i.sub(s);return i.add(n._mult(o/n.mag()))}function Be(e,i,o){const r=i.projectionCache;if(r.projections[e])return r.projections[e];const a=new t.P(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),s=Oe(a.x,a.y,i);if(s.signedDistanceFromCamera>0)return r.projections[e]=s.point,r.anyProjectionOccluded=r.anyProjectionOccluded||s.isOccluded,s.point;const n=e-o.direction;return Fe(0===o.distanceFromAnchor?i.tileAnchorPoint:new t.P(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),a,o.previousVertex,o.absOffsetX-o.distanceFromAnchor+1,i)}function Oe(e,t,i){const o=e+i.translation[0],r=t+i.translation[1];let a;return i.pitchWithMap?(a=Ee(o,r,i.pitchedLabelPlaneMatrix,i.getElevation),a.isOccluded=!1):(a=i.transform.projectTileCoordinates(o,r,i.unwrappedTileID,i.getElevation),a.point.x=(.5*a.point.x+.5)*i.width,a.point.y=(.5*-a.point.y+.5)*i.height),a}function je(e,i,o,r){if(o.pitchWithMap){const a=[e,i,0,1];return t.aw(a,a,r),o.transform.projectTileCoordinates(a[0]/a[3],a[1]/a[3],o.unwrappedTileID,o.getElevation).point}return {x:e/o.width*2-1,y:1-i/o.height*2}}function Ne(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function Ue(e,t,i){return e._unit()._perp()._mult(t*i)}function Ze(e,i,o,r,a,s,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=o.add(i);if(e+c.direction=a)return l.projectionCache.offsets[e]=h,h;const u=Be(e+c.direction,l,c),d=Ue(u.sub(o),n,c.direction),_=o.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.ax(s,h,_,p)||h,l.projectionCache.offsets[e]}function Ge(e,t,i,o,r,a,s,n,l){const c=o?e-t:e+t;let h=c>0?1:-1,u=0;o&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?a+r:a+r+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Oe(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,b=0;const x=Math.abs(c),y=[];let w;for(;v+b<=x;){if(_+=h,_=s)return null;v+=b,g=f,m=p;const e={absOffsetX:x,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=Be(_,n,e),0===i)y.push(g),w=f.sub(g);else {let t;const o=f.sub(g);t=0===o.mag()?Ue(Be(_+h,n,e).sub(f),i,h):Ue(o,i,h),m||(m=g.add(t)),p=Ze(_,t,f,a,s,m,i,n,e),y.push(m),w=p.sub(m);}b=w.mag();}const T=w._mult((x-v)/b)._add(m||g),P=u+Math.atan2(f.y-g.y,f.x-g.x);return y.push(T),{point:T,angle:l?P:0,path:y}}const Ve=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function $e(e,t){for(let i=0;i=1;e--)_.push(s.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=o.x&&i.x<=r.x&&e.y>=o.y&&i.y<=r.y?[_]:i.xr.x||i.yr.y?[]:t.ay([_],o.x,o.y,r.x,r.y);}for(const t of f){a.reset(t,.25*i);let o=0;o=a.length<=.5*i?1:Math.ceil(a.paddedLength/p)+1;for(let t=0;t{const t=Ee(e.x,e.y,o,i.getElevation),r=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return r.point.x=(.5*r.point.x+.5)*i.width,r.point.y=(.5*-r.point.y+.5)*i.height,r}))}(e,i);return function(e){let t=0,i=0,o=0,r=0;for(let a=0;ai&&(i=r,t=o));return e.slice(t,t+i)}(o)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[],o=new t.a2;for(const r of e){const e=new t.P(r.x+We,r.y+We);o.extend(e),i.push(e);}const{minX:r,minY:a,maxX:s,maxY:n}=o,l=this.grid.query(r,a,s,n).concat(this.ignoredGrid.query(r,a,s,n)),c={},h={};for(const e of l){const o=e.key;if(void 0===c[o.bucketInstanceId]&&(c[o.bucketInstanceId]={}),c[o.bucketInstanceId][o.featureIndex])continue;const r=[new t.P(e.x1,e.y1),new t.P(e.x2,e.y1),new t.P(e.x2,e.y2),new t.P(e.x1,e.y2)];t.az(i,r)&&(c[o.bucketInstanceId][o.featureIndex]=!0,void 0===h[o.bucketInstanceId]&&(h[o.bucketInstanceId]=[]),h[o.bucketInstanceId].push(o.featureIndex));}return h}insertCollisionBox(e,t,i,o,r,a){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,o,r,a){const s=i?this.ignoredGrid:this.grid,n={bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t};for(let t=0;t=this.screenRightBoundary||othis.screenBottomBoundary}isInsideGrid(e,t,i,o){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,r,c,u)));E=e.some((e=>!e.isOccluded)),S=e.map((e=>new t.P(e.x,e.y)));}else E=!0;return {box:t.aA(S),allPointsOccluded:!E}}}class Xe{constructor(e,t,i,o){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):o&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class Ke{constructor(e,t,i,o,r){this.text=new Xe(e?e.text:null,t,i,r),this.icon=new Xe(e?e.icon:null,t,o,r);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ye{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class Qe{constructor(e,t,i,o,r){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=r;}}class Je{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function et(e,i,o,r,a){const{horizontalAlign:s,verticalAlign:n}=t.aH(e);return new t.P(-(s-.5)*i+r[0]*a,-(n-.5)*o+r[1]*a)}class tt{constructor(e,t,i,o,r){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new He(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new Je(o),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=r,r&&(r.prevPlacement=void 0),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,o)=>t.getElevation(e,i,o):null}getBucketParts(e,i,o,r){const a=o.getBucket(i),s=o.latestFeatureIndex;if(!a||!s||i.id!==a.layerIds[0])return;const n=o.collisionBoxArray,l=a.layers[0].layout,c=a.layers[0].paint,h=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),u=o.tileSize/t.$,d=o.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.aC(o,1,this.transform.zoom),m=t.aD(this.collisionIndex.transform,o,c.get("text-translate"),c.get("text-translate-anchor")),f=t.aD(this.collisionIndex.transform,o,c.get("icon-translate"),c.get("icon-translate-anchor")),g=Ie(_,this.transform,p);this.retainedQueryData[a.bucketInstanceId]=new Qe(a.bucketInstanceId,s,a.sourceLayerIndex,a.index,o.tileID);const v={bucket:a,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:o.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.an(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(r)for(const t of a.sortKeyRanges){const{sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r}=t;e.push({sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v,b,x){const y=t.aE[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=et(y,o,r,w,a),P=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,s,f,u.predicate,b,T,x);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,s,g,u.predicate,b,T,x).placeable)&&P.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:o,height:r,anchor:y,textBoxScale:a,prevAnchor:e},this.markUsedJustification(p,y,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:P}}}placeLayerBucketPart(e,i,o){const{bucket:r,layout:a,translationText:s,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=a.get("text-optional"),f=a.get("icon-optional"),g=t.aF(a,"text-overlap","text-allow-overlap"),v="always"===g,b=t.aF(a,"icon-overlap","icon-allow-overlap"),x="always"===b,y="map"===a.get("text-rotation-alignment"),w="map"===a.get("text-pitch-alignment"),T="none"!==a.get("icon-text-fit"),P="viewport-y"===a.get("symbol-z-order"),C=v&&(x||!r.hasIconData()||f),I=x&&(v||!r.hasTextData()||m);!r.collisionArrays&&d&&r.deserializeCollisionBoxes(d);const M=this.retainedQueryData[r.bucketInstanceId].tileID,S=this._getTerrainElevationFunc(M),E=this.transform.getFastPathSimpleProjectionMatrix(M),R=(e,d,x)=>{var P,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new Ye(!1,!1,!1));let z=!1,D=!1,A=!0,L=null,k={box:null,placeable:!1,offscreen:null,occluded:!1},F={placeable:!1},B=null,O=null,j=null,N=0,U=0,Z=0;d.textFeatureIndex?N=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(N=e.featureIndex),d.verticalTextFeatureIndex&&(U=d.verticalTextFeatureIndex);const G=d.textBox;if(G){const i=i=>{let o=t.ao.horizontal;if(r.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,o=t,this.markUsedOrientation(r,o,e));}return o},a=(i,o)=>{if(r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of r.writingModes)if(e===t.ao.vertical?(k=o(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const o=(t,i)=>{const o=this.collisionIndex.placeCollisionBox(t,g,h,M,l,w,y,s,p.predicate,S,void 0,E);return o&&o.placeable&&(this.markUsedOrientation(r,i,e),this.placedOrientations[e.crossTileID]=i),o};a((()=>o(G,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?o(i,t.ao.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.aE[null===(R=null===(P=this.prevPlacement)||void 0===P?void 0:P.variableOffsets[e.crossTileID])||void 0===R?void 0:R.anchor];const m=(t,i,a)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===b?i:null;let x=null,P="never"===g?1:2,C="never";_&&P++;for(let i=0;im(G,d.iconBox,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.ao.vertical):{box:null,occluded:!0,offscreen:null}})),k&&(z=k.placeable,A=k.offscreen);const f=i(k&&k.placeable);if(!z&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(r,t.anchor,e,f));}}}if(B=k,z=B&&B.placeable,A=B&&B.offscreen,e.useRuntimeCollisionCircles){const i=r.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.ap(r.textSizeData,_,i),h=a.get("text-padding");O=this.collisionIndex.placeCollisionCircles(g,i,r.lineVertexArray,r.glyphOffsetArray,n,l,c,o,w,p.predicate,e.collisionCircleDiameter,h,s,S),O.circles.length&&O.collisionDetected&&!o&&t.w("Collisions detected, but collision boxes are not shown"),z=v||O.circles.length>0&&!O.collisionDetected,A=A&&O.offscreen;}if(d.iconFeatureIndex&&(Z=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,b,h,M,l,w,y,n,p.predicate,S,T&&L?L:void 0,E);F&&F.placeable&&d.verticalIconBox?(j=e(d.verticalIconBox),D=j.placeable):(j=e(d.iconBox),D=j.placeable),A=A&&j.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,$=f||0===e.numIconVertices;V||$?$?V||(D=D&&z):z=D&&z:D=z=D&&z;const q=D&&j.placeable;if(z&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,a.get("text-ignore-placement"),r.bucketInstanceId,F&&F.placeable&&U?U:N,p.ID),q&&this.collisionIndex.insertCollisionBox(j.box,b,a.get("icon-ignore-placement"),r.bucketInstanceId,Z,p.ID),O&&z&&this.collisionIndex.insertCollisionCircles(O.circles,g,a.get("text-ignore-placement"),r.bucketInstanceId,N,p.ID),o&&this.storeCollisionData(r.bucketInstanceId,x,d,B,j,O),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===r.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new Ye((z||C)&&!(null==B?void 0:B.occluded),(D||I)&&!(null==j?void 0:j.occluded),A||r.justReloaded),i[e.crossTileID]=!0;};if(P){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=r.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(r.symbolInstances.get(i),r.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=a>=0&&t!==a?0:o.crossTileID);}markUsedOrientation(e,i,o){const r=i===t.ao.horizontal||i===t.ao.horizontalOnly?i:0,a=i===t.ao.vertical?i:0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];for(const t of s)e.text.placedSymbolArray.get(t).placedOrientation=r;o.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).placedOrientation=a);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=!1;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const o=t?t.symbolFadeChange(e):1,r=t?t.opacities:{},a=t?t.variableOffsets:{},s=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],a=r[e];a?(this.opacities[e]=new Ke(a,o,t.text,t.icon),i=i||t.text!==a.text.placed||t.icon!==a.icon.placed):(this.opacities[e]=new Ke(null,o,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in r){const t=r[e];if(!this.opacities[e]){const r=new Ke(t,o,!1,!1);r.isHidden()||(this.opacities[e]=r,i=i||t.text.placed||t.icon.placed);}}for(const e in a)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=a[e]);for(const e in s)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=s[e]);if(t&&void 0===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const o of t){const t=o.getBucket(e);t&&o.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,o.tileID,i,o.collisionBoxArray);}}updateBucketOpacities(e,i,o,r){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=!1),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=!1),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const a=e.layers[0],s=a.layout,n=new Ke(null,0,!1,!1,!0),l=s.get("text-allow-overlap"),c=s.get("icon-allow-overlap"),h=a._unevaluatedLayout.hasValue("text-variable-anchor")||a._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===s.get("text-rotation-alignment"),d="map"===s.get("text-pitch-alignment"),_="none"!==s.get("icon-text-fit"),p=new Ke(null,0,l&&(c||!e.hasIconData()||s.get("icon-optional")),c&&(l||!e.hasTextData()||s.get("text-optional")),!0);!e.collisionArrays&&r&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(r);const m=(e,t,i)=>{for(let o=0;o0,v=this.placedOrientations[r.crossTileID],b=v===t.ao.vertical,x=v===t.ao.horizontal||v===t.ao.horizontalOnly;if(a>0||s>0){const t=ht(c.text);m(e.text,a,b?ut:t),m(e.text,s,x?ut:t);const i=c.text.isHidden();[r.rightJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||b?1:0);})),r.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).hidden=i||x?1:0);const o=this.variableOffsets[r.crossTileID];o&&this.markUsedJustification(e,o.anchor,r,v);const n=this.placedOrientations[r.crossTileID];n&&(this.markUsedJustification(e,"left",r,n),this.markUsedOrientation(e,n,r));}if(g){const t=ht(c.icon),i=!(_&&r.verticalPlacedIconSymbolIndex&&b);r.placedIconSymbolIndex>=0&&(m(e.icon,r.numIconVertices,i?t:ut),e.icon.placedSymbolArray.get(r.placedIconSymbolIndex).hidden=c.icon.isHidden()),r.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,r.numVerticalIconVertices,i?ut:t),e.icon.placedSymbolArray.get(r.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const y=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const o=e.collisionArrays[i];if(o){let i=new t.P(0,0);if(o.textBox||o.verticalTextBox){let t=!0;if(h){const e=this.variableOffsets[l];e?(i=et(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=!1;}if(o.textBox||o.verticalTextBox){let r;o.textBox&&(r=b),o.verticalTextBox&&(r=x),it(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||r,y.text,i.x,i.y);}}if(o.iconBox||o.verticalIconBox){const t=Boolean(!x&&o.verticalIconBox);let r;o.iconBox&&(r=t),o.verticalIconBox&&(r=!t),it(e.iconCollisionBox.collisionVertexArray,c.icon.placed,r,y.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=!0;}}function it(e,t,i,o,r,a){o&&0!==o.length||(o=[0,0,0,0]);const s=o[0]-We,n=o[1]-We,l=o[2]-We,c=o[3]-We;e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,c),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,c);}const ot=Math.pow(2,25),rt=Math.pow(2,24),at=Math.pow(2,17),st=Math.pow(2,16),nt=Math.pow(2,9),lt=Math.pow(2,8),ct=Math.pow(2,1);function ht(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*ot+t*rt+i*at+t*st+i*nt+t*lt+i*ct+t}const ut=0;class dt{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,o,r){const a=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&s.now()-o>2;for(;this._currentPlacementIndex>=0;){const o=t[e[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if("symbol"===o.type&&(!o.minzoom||o.minzoom<=a)&&(!o.maxzoom||o.maxzoom>a)){if(this._inProgressLayer||(this._inProgressLayer=new dt(o)),this._inProgressLayer.continuePlacement(i[o.source],this.placement,this._showCollisionBoxes,o,r))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(e){return this.placement.commit(e),this.placement}}const pt=512/t.$/2;class mt{constructor(e,i,o){this.tileID=e,this.bucketInstanceId=o,this._symbolsByKey={};const r=new Map;for(let e=0;e({x:Math.floor(e.anchorX*pt),y:Math.floor(e.anchorY*pt)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(o.positions.length>128){const e=new t.aI(o.positions.length,16,Uint16Array);for(const{x:t,y:i}of o.positions)e.add(t,i);e.finish(),delete o.positions,o.index=e;}this._symbolsByKey[e]=o;}}getScaledCoordinates(e,i){const{x:o,y:r,z:a}=this.tileID.canonical,{x:s,y:n,z:l}=i.canonical,c=pt/Math.pow(2,l-a),h=(n*t.$+e.anchorY)*c,u=r*t.$*pt;return {x:Math.floor((s*t.$+e.anchorX)*c-o*t.$*pt),y:Math.floor(h-u)}}findMatches(e,t,i){const o=this.tileID.canonical.ze))}}class ft{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class gt{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],o={};for(const e in i){const r=i[e];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+t),o[r.tileID.key]=r;}this.indexes[e]=o;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in r){const a=r[i];a.tileID.isChildOf(e)&&a.findMatches(t.symbolInstances,e,o);}else {const a=r[e.scaledTo(Number(i)).key];a&&a.findMatches(t.symbolInstances,e,o);}}for(let e=0;e{t[e]=!0;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var bt="void main() {fragColor=vec4(1.0);}";const xt={prelude:yt("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:yt("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:yt("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:yt("uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:yt("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:yt("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:yt(bt,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:yt("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:yt("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:yt("in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:yt("in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),colorRelief:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform int u_color_ramp_size;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {float x=(float(stop)+0.5)/float(u_color_ramp_size);vec4 data=texture(u_elevation_stops,vec2(x,0))*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int r=(u_color_ramp_size-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else\n{l=m;el_l=el_m;}}float x=(float(l)+(el-el_l)/(el_r-el_l)+0.5)/float(u_color_ramp_size);fragColor=u_opacity*texture(u_color_stops,vec2(x,0));\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_dimension;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),debug:yt("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}","in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:yt(bt,"in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:yt("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:yt("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:yt("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:yt("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:yt("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {vec2 epsilon=1.0/u_dimension;float tileSize=u_dimension.x-2.0;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))*tileSize/pow(2.0,exaggeration+(28.2562-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+0.5,deriv.y/8.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:yt("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];\n#define PI 3.141592653589793\n#define STANDARD 0\n#define COMBINED 1\n#define IGOR 2\n#define MULTIDIRECTIONAL 3\n#define BASIC 4\nfloat get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);}void igor_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float aspect=get_aspect(deriv);float azimuth=u_azimuths[0]+PI;float slope_stength=atan(length(deriv))*2.0/PI;float aspect_strength=1.0-abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);float shadow_strength=slope_stength*aspect_strength;float highlight_strength=slope_stength*(1.0-aspect_strength);fragColor=u_shadows[0]*shadow_strength+u_highlights[0]*highlight_strength;}void standard_hillshade(vec2 deriv){float azimuth=u_azimuths[0]+PI;float slope=atan(0.625*length(deriv));float aspect=get_aspect(deriv);float intensity=u_exaggeration;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadows[0],u_highlights[0],shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;}void basic_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor=u_highlights[0]*(2.0*shade-1.0);}else\n{fragColor=u_shadows[0]*(1.0-2.0*shade);}}void multidirectional_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;fragColor=vec4(0,0,0,0);for(int i=0; i < NUM_ILLUMINATION_SOURCES; i++){float cos_alt=cos(u_altitudes[i]);float sin_alt=sin(u_altitudes[i]);float cos_az=-cos(u_azimuths[i]);float sin_az=-sin(u_azimuths[i]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor+=u_highlights[i]*(2.0*shade-1.0)/float(NUM_ILLUMINATION_SOURCES);}else\n{fragColor+=u_shadows[i]*(1.0-2.0*shade)/float(NUM_ILLUMINATION_SOURCES);}}}void combined_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=acos((sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv)));cang=clamp(cang,0.0,PI/2.0);float shade=cang*atan(length(deriv))*4.0/PI/PI;float highlight=(PI/2.0-cang)*atan(length(deriv))*4.0/PI/PI;fragColor=u_shadows[0]*shade+u_highlights[0]*highlight;}void main() {vec4 pixel=texture(u_image,v_pos);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));vec2 deriv=((pixel.rg*8.0)-4.0)/scaleFactor;if (u_method==BASIC) {basic_hillshade(deriv);} else if (u_method==COMBINED) {combined_hillshade(deriv);} else if (u_method==IGOR) {igor_hillshade(deriv);} else if (u_method==MULTIDIRECTIONAL) {multidirectional_hillshade(deriv);} else if (u_method==STANDARD) {standard_hillshade(deriv);} else {standard_hillshade(deriv);}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:yt("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:yt("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0);vec4 color1=texture(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:yt("uniform sampler2D u_texture;in vec2 v_tex;in float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;fragColor=texture(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_tex;out float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:yt("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:yt("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;fragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:yt("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}","in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:yt("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}","in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:yt("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:yt("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:yt("in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}","in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:yt("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function yt(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o=t.match(/in ([\w]+) ([\w]+)/g),r=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=a?a.concat(r):r,n={};return {fragmentSource:e=e.replace(i,((e,t,i,o,r)=>(n[r]=!0,"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nin ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = u_${r};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,o,r)=>{const a="float"===o?"vec2":"vec4",s=r.match(/color/)?"color":a;return n[r]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\nout ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`})),staticAttributes:o,staticUniforms:s}}class wt{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var Tt=t.aJ([{name:"a_pos",type:"Int16",components:2}]);const Pt="#define PROJECTION_MERCATOR",Ct="mercator";class It{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return !1}get shaderVariantName(){return Ct}get shaderDefine(){return Pt}get shaderPreludeCode(){return xt.projectionMercator}get vertexShaderPreludeCode(){return xt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.aK.noSubdivision}get useGlobeControls(){return !1}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(e){}getMeshFromTileID(e,i,o,r,a){if(this._cachedMesh)return this._cachedMesh;const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(t.$,0),s.emplaceBack(0,t.$),s.emplaceBack(t.$,t.$);const n=e.createVertexBuffer(s,Tt.members),l=t.aM.simpleSegment(0,0,4,2),c=new t.aN;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new wt(n,h,l),this._cachedMesh}recalculate(){}hasTransition(){return !1}setErrorQueryLatitudeDegrees(e){}}class Mt{constructor(e=0,t=0,i=0,o=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=o;}interpolate(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.C.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.C.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.C.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.C.number(e.right,i.right,o)),this}getCenter(e,i){const o=t.ah((this.left+e-this.right)/2,0,e),r=t.ah((this.top+i-this.bottom)/2,0,i);return new t.P(o,r)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new Mt(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function St(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function Et(e){return Math.max(0,Math.floor(e))}class Rt{constructor(e,i,o,r,a,s){this._callbacks=e,this._tileSize=512,this._renderWorldCopies=void 0===s||!!s,this._minZoom=i||0,this._maxZoom=o||22,this._minPitch=null==r?0:r,this._maxPitch=null==a?60:a,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.S(0,0),this._elevation=0,this._zoom=0,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new Mt,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=!0;}apply(e,i,o){this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new Mt(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,this._cameraToCenterDistance=e.cameraToCenterDistance,this._nearZ=e.nearZ,this._farZ=e.farZ,this._autoCalculateNearFarZ=!o&&e.autoCalculateNearFarZ,i&&this._constrain(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e;}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const i=t.aO(e,-180,180)*Math.PI/180;var r,a,s,n,l,c,h,u,d;this._bearingInRadians!==i&&(this._unmodified=!1,this._bearingInRadians=i,this._calcMatrices(),this._rotationMatrix=o(),r=this._rotationMatrix,s=-this._bearingInRadians,n=(a=this._rotationMatrix)[0],l=a[1],c=a[2],h=a[3],u=Math.sin(s),d=Math.cos(s),r[0]=n*d+c*u,r[1]=l*d+h*u,r[2]=n*-u+c*d,r[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.ah(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=!1,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=!1,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.aP(this._fovInRadians)}setFov(e){e=t.ah(e,.1,150),this.fov!==e&&(this._unmodified=!1,this._fovInRadians=t.ae(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const i=this.getConstrained(this._center,e).zoom;this._zoom!==i&&(this._unmodified=!1,this._zoom=i,this._tileZoom=Math.max(0,Math.floor(i)),this._scale=t.af(i),this._constrain(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(e,t){this._autoCalculateNearFarZ=!1,this._nearZ=e,this._farZ=t,this._calcMatrices();}clearNearFarZOverride(){this._autoCalculateNearFarZ=!0,this._calcMatrices();}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices();}resize(e,t,i=!0){this._width=e,this._height=t,i&&this._constrain(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new G([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-t.ai,t.ai]);}getConstrained(e,t){return this._callbacks.getConstrained(e,t)}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{const{minX:o,minY:r,maxX:a,maxY:s}=t.a2.fromPoints(i).extend(e);return [new t.P(o,r),new t.P(a,r),new t.P(a,s),new t.P(o,s),new t.P(o,r)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const e=this._unmodified,{center:t,zoom:i}=this.getConstrained(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=!1;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.ag(new Float64Array(16));t.N(e,e,[this._width/2,-this._height/2,1]),t.M(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.ag(new Float64Array(16)),t.N(e,e,[1,-1,1]),t.M(e,e,[-1,-1,0]),t.N(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height;}this._callbacks.calcMatrices();}calculateCenterFromCameraLngLatAlt(e,i,o,r){const a=void 0!==o?o:this.bearing,s=r=void 0!==r?r:this.pitch,n=t.a1.fromLngLat(e,i),l=-Math.cos(t.ae(s)),c=Math.sin(t.ae(s)),h=c*Math.sin(t.ae(a)),u=-c*Math.cos(t.ae(a));let d=this.elevation;const _=i-d;let p;l*_>=0||Math.abs(l)<.1?(p=1e4,d=i+p*l):p=-_/l;let m,f,g=t.aQ(1,n.y),v=0;do{if(v+=1,v>10)break;f=p/g,m=new t.a1(n.x+h*f,n.y+u*f),g=1/m.meterInMercatorCoordinateUnits();}while(Math.abs(p-f*g)>1e-12);return {center:m.toLngLat(),elevation:d,zoom:t.ak(this.height/2/Math.tan(this.fovInRadians/2)/f/this.tileSize)}}recalculateZoomAndCenter(e){if(this.elevation-e==0)return;const i=t.aj(1,this.center.lat)*this.worldSize,o=this.cameraToCenterDistance/i,r=t.a1.fromLngLat(this.center,this.elevation),a=de(this.center,this.elevation,this.pitch,this.bearing,o);this._elevation=e;const s=this.calculateCenterFromCameraLngLatAlt(a.toLngLat(),t.aQ(a.z,r.y),this.bearing,this.pitch);this._elevation=s.elevation,this._center=s.center,this.setZoom(s.zoom);}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.P(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/e).toLngLat()}getMercatorTileCoordinates(e){if(!e)return [0,0,1,1];const i=e.canonical.z>=0?1<this.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[o]*this.min[o],i+=e[o]*this.max[o]):(i+=e[o]*this.min[o],t+=e[o]*this.max[o]);return t>=0?2:i<0?0:1}}class Dt{distanceToTile2d(e,t,i,o){const r=o.distanceX([e,t]),a=o.distanceY([e,t]);return Math.hypot(r,a)}getWrap(e,t,i){return i}getTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}const c=1<r}allowWorldCopies(){return !0}prepareNextFrame(){}}class At{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,o=0,r,a){const s=a?[[6,5,4],[0,1,2],[0,3,7],[2,1,5],[3,2,6],[0,4,5]]:[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]],n=Math.pow(2,o),l=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((o=>function(e,i,o,r){const a=t.aw([],e,i),s=1/a[3]/o*r;return t.aY(a,a,[s,s,1/a[3],s])}(o,e,i,n)));r&&function(e,i,o,r){const a=r?4:0,s=r?0:4;let n=0;const l=[],c=[];for(let i=0;i<4;i++){const o=t.aU([],e[i+s],e[i+a]),r=t.aZ(o);t.aR(o,o,1/r),l.push(r),c.push(o);}for(let i=0;i<4;i++){const r=t.a_(e[i+a],c[i],o);n=null!==r&&r>=0?Math.max(n,r):Math.max(n,l[i]);}const h=function(e,i){const o=t.aU([],e[i[0]],e[i[1]]),r=t.aU([],e[i[2]],e[i[1]]),a=[0,0,0,0];return t.aV(a,t.aW([],o,r)),a[3]=-t.aX(a,e[i[0]]),a}(e,i),u=function(e,i){const o=t.a$(e),r=t.b0([],e,1/o),a=t.aU([],i,t.aR([],r,t.aX(i,r))),s=t.a$(a);if(s>0){const e=Math.sqrt(1-r[3]*r[3]),o=t.aR([],r,-r[3]),n=t.aS([],o,t.aR([],a,e/s));return t.b1(i,n)}return null}(o,h);if(null!==u){const e=u/t.aX(c[0],h);n=Math.min(n,e);}for(let t=0;t<4;t++){const i=Math.min(n,l[t]);e[t+s]=[e[t+a][0]+c[t][0]*i,e[t+a][1]+c[t][1]*i,e[t+a][2]+c[t][2]*i,1];}}(l,s[0],r,a);const c=s.map((e=>{const i=t.aU([],l[e[0]],l[e[1]]),o=t.aU([],l[e[2]],l[e[1]]),r=t.aV([],t.aW([],i,o)),a=-t.aX(r,l[e[1]]);return r.concat(a)})),h=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of l)for(let t=0;t<3;t++)h[t]=Math.min(h[t],e[t]),u[t]=Math.max(u[t],e[t]);return new At(l,c,new zt(h,u))}}class Lt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e,t){}constructor(e,t,i,o,r){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)},e,t,i,o,r),this._coveringTilesDetailsProvider=new Dt;}clone(){const e=new Lt;return e.apply(this),e}apply(e,t,i){this._helper.apply(e,t,i);}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.b2(0,e)];if(this._helper._renderWorldCopies){const o=this.screenPointToMercatorCoordinate(new t.P(0,0)),r=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,0)),a=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,this._helper._height)),s=this.screenPointToMercatorCoordinate(new t.P(0,this._helper._height)),n=Math.floor(Math.min(o.x,r.x,a.x,s.x)),l=Math.floor(Math.max(o.x,r.x,a.x,s.x)),c=1;for(let o=n-c;o<=l+c;o++)0!==o&&i.push(new t.b2(o,e));}return i}getCameraFrustum(){return At.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const t=this.screenPointToLocation(this.centerPoint,e),i=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(i);}setLocationAtPoint(e,i){const o=t.aj(this.elevation,this.center.lat),r=this.screenPointToMercatorCoordinateAtZ(i,o),a=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,o),s=t.a1.fromLngLat(e),n=new t.a1(s.x-(r.x-a.x),s.y-(r.y-a.y));this.setCenter(null==n?void 0:n.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,i){return i?this.coordinatePoint(t.a1.fromLngLat(e),i.getElevationForLngLatZoom(e,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(t.a1.fromLngLat(e))}screenPointToLocation(e,t){var i;return null===(i=this.screenPointToMercatorCoordinate(e,t))||void 0===i?void 0:i.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const o=i||0,r=[e.x,e.y,0,1],a=[e.x,e.y,1,1];t.aw(r,r,this._pixelMatrixInverse),t.aw(a,a,this._pixelMatrixInverse);const s=r[3],n=a[3],l=r[1]/s,c=a[1]/n,h=r[2]/s,u=a[2]/n,d=h===u?0:(o-h)/(u-h);return new t.a1(t.C.number(r[0]/s,a[0]/n,d)/this.worldSize,t.C.number(l,c,d)/this.worldSize,o)}coordinatePoint(e,i=0,o=this._pixelMatrix){const r=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.aw(r,r,o),new t.P(r[0]/r[3],r[1]/r[3])}getBounds(){const e=Math.max(0,this._helper._height/2-he(this));return (new G).extend(this.screenPointToLocation(new t.P(0,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.P(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-he(this)}calculatePosMatrix(e,i=!1,o){var r;const a=null!==(r=e.key)&&void 0!==r?r:t.b3(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),s=i?this._alignedPosMatrixCache:this._posMatrixCache;if(s.has(a)){const e=s.get(a);return o?e.f32:e.f64}const n=ue(e,this.worldSize);t.O(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return s.set(a,l),o?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,o=this._fogMatrixCacheF32;if(o.has(i))return o.get(i);const r=ue(e,this.worldSize);return t.O(r,this._fogMatrix,r),o.set(i,new Float32Array(r)),o.get(i)}getConstrained(e,i){i=t.ah(+i,this.minZoom,this.maxZoom);const o={center:new t.S(e.lng,e.lat),zoom:i};let r=this._helper._lngRange;if(!this._helper._renderWorldCopies&&null===r){const e=180-1e-10;r=[-e,e];}const a=this.tileSize*t.af(o.zoom);let s=0,n=a,l=0,c=a,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;s=t.U(e[1])*a,n=t.U(e[0])*a,n-s<_&&(h=_/(n-s));}r&&(l=t.aO(t.V(r[0])*a,0,a),c=t.aO(t.V(r[1])*a,0,a),cn&&(g=n-e);}if(r){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.aO(p,e-a/2,e+a/2));const o=d/2;i-oc&&(f=c-o);}if(void 0!==f||void 0!==g){const e=new t.P(null!=f?f:p,null!=g?g:m);o.center=ce(a,e).wrap();}return o}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}_calculateNearFarZIfNeeded(e,i,o){if(!this._helper.autoCalculateNearFarZ)return;const r=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),a=e-r*this._helper._pixelPerMeter/Math.cos(i),s=r<0?a:e,n=Math.PI/2+this.pitchInRadians,l=t.ae(this.fov)*(Math.abs(Math.cos(t.ae(this.roll)))*this.height+Math.abs(Math.sin(t.ae(this.roll)))*this.width)/this.height*(.5+o.y/this.height),c=Math.sin(l)*s/Math.sin(t.ah(Math.PI-n-l,.01,Math.PI-.01)),h=he(this),u=Math.atan(h/this._helper.cameraToCenterDistance),d=t.ae(.75),_=u>d?2*u*(.5+o.y/(2*h)):d,p=Math.sin(_)*s/Math.sin(t.ah(Math.PI-n-_,.01,Math.PI-.01)),m=Math.min(c,p);this._helper._farZ=1.01*(Math.cos(Math.PI/2-i)*m+s),this._helper._nearZ=this._helper._height/50;}_calcMatrices(){if(!this._helper._height)return;const e=this.centerOffset,i=le(this.worldSize,this.center),o=i.x,r=i.y;this._helper._pixelPerMeter=t.aj(1,this.center.lat)*this.worldSize;const a=t.ae(Math.min(this.pitch,ne)),s=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(a));let n;this._calculateNearFarZIfNeeded(s,a,e),n=new Float64Array(16),t.b4(n,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),t.aq(this._invProjMatrix,n),n[8]=2*-e.x/this._helper._width,n[9]=2*e.y/this._helper._height,this._projectionMatrix=t.b5(n),t.N(n,n,[1,-1,1]),t.M(n,n,[0,0,-this._helper.cameraToCenterDistance]),t.b6(n,n,-this.rollInRadians),t.b7(n,n,this.pitchInRadians),t.b6(n,n,-this.bearingInRadians),t.M(n,n,[-o,-r,0]),this._mercatorMatrix=t.N([],n,[this.worldSize,this.worldSize,this.worldSize]),t.N(n,n,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n),t.M(n,n,[0,0,-this.elevation]),this._viewProjMatrix=n,this._invViewProjMatrix=t.aq([],n);const l=[0,0,-1,1];t.aw(l,l,this._invViewProjMatrix),this._cameraPosition=[l[0]/l[3],l[1]/l[3],l[2]/l[3]],this._fogMatrix=new Float64Array(16),t.b4(this._fogMatrix,this.fovInRadians,this.width/this.height,s,this._helper._farZ),this._fogMatrix[8]=2*-e.x/this.width,this._fogMatrix[9]=2*e.y/this.height,t.N(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.b6(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.b7(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.b6(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.M(this._fogMatrix,this._fogMatrix,[-o,-r,0]),t.N(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n);const c=this._helper._width%2/2,h=this._helper._height%2/2,u=Math.cos(this.bearingInRadians),d=Math.sin(-this.bearingInRadians),_=o-Math.round(o)+u*c+d*h,p=r-Math.round(r)+u*h+d*c,m=new Float64Array(n);if(t.M(m,m,[_>.5?_-1:_,p>.5?p-1:p,0]),this._alignedProjMatrix=m,n=t.aq(new Float64Array(16),this._pixelMatrix),!n)throw new Error("failed to invert matrix");this._pixelMatrixInverse=n,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.P(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.aw(i,i,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/e).toLngLat()}lngLatToCameraDepth(e,i){const o=t.a1.fromLngLat(e),r=[o.x*this.worldSize,o.y*this.worldSize,i,1];return t.aw(r,r,this._viewProjMatrix),r[2]/r[3]}getProjectionData(e){const{overscaledTileID:i,aligned:o,applyTerrainMatrix:r}=e,a=this._helper.getMercatorTileCoordinates(i),s=i?this.calculatePosMatrix(i,o,!0):null;let n;return n=i&&i.terrainRttPosMatrix32f&&r?i.terrainRttPosMatrix32f:s||t.b8(),{mainMatrix:n,tileMercatorCoords:a,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:n}}isLocationOccluded(e){return !1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,i){return 1}transformLightDirection(e){return t.aT(e)}getRayDirectionFromPixel(e){throw new Error("Not implemented.")}projectTileCoordinates(e,i,o,r){const a=this.calculatePosMatrix(o);let s;r?(s=[e,i,r(e,i),1],t.aw(s,s,a)):(s=[e,i,0,1],qe(s,s,a));const n=s[3];return {point:new t.P(s[0]/n,s[1]/n),signedDistanceFromCamera:n,isOccluded:!1}}populateCache(e){for(const t of e)this.calculatePosMatrix(t);}getMatrixForModel(e,i){const o=t.a1.fromLngLat(e,i),r=o.meterInMercatorCoordinateUnits(),a=t.b9();return t.M(a,a,[o.x,o.y,o.z]),t.b6(a,a,Math.PI),t.b7(a,a,Math.PI/2),t.N(a,a,[-r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=new t.Z(0,0,0,0,0),o=this.getProjectionData({overscaledTileID:i,applyGlobeMatrix:e}),r=ue(i,this.worldSize);t.O(r,this._viewProjMatrix,r),o.tileMercatorCoords=[0,0,1,1];const a=[t.$,t.$,this.worldSize/this._helper.pixelsPerMeter],s=t.ba();return t.N(s,r,a),o.fallbackMatrix=s,o.mainMatrix=s,o}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}}function kt(){t.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");}function Ft(e){if(e.useSlerp)if(e.k<1){const i=t.bb(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),o=t.bb(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),r=new Float64Array(4);t.bc(r,i,o,e.k);const a=t.bd(r);e.tr.setRoll(a.roll),e.tr.setPitch(a.pitch),e.tr.setBearing(a.bearing);}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(t.C.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(t.C.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(t.C.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k));}function Bt(e,i,o,r,a){const s=a.padding,n=le(a.worldSize,o.getNorthWest()),l=le(a.worldSize,o.getNorthEast()),c=le(a.worldSize,o.getSouthEast()),h=le(a.worldSize,o.getSouthWest()),u=t.ae(-r),d=n.rotate(u),_=l.rotate(u),p=c.rotate(u),m=h.rotate(u),f=new t.P(Math.max(d.x,_.x,m.x,p.x),Math.max(d.y,_.y,m.y,p.y)),g=new t.P(Math.min(d.x,_.x,m.x,p.x),Math.min(d.y,_.y,m.y,p.y)),v=f.sub(g),b=(a.width-(s.left+s.right+i.left+i.right))/v.x,x=(a.height-(s.top+s.bottom+i.top+i.bottom))/v.y;if(x<0||b<0)return void kt();const y=Math.min(t.ak(a.scale*Math.min(b,x)),e.maxZoom),w=t.P.convert(e.offset),T=new t.P((i.left-i.right)/2,(i.top-i.bottom)/2).rotate(t.ae(r)),P=w.add(T).mult(a.scale/t.af(y));return {center:ce(a.worldSize,n.add(c).div(2).sub(P)),zoom:y,bearing:r}}class Ot{get useGlobeControls(){return !1}handlePanInertia(e,t){const i=e.mag(),o=Math.abs(he(t));return {easingOffset:e.mult(Math.min(.75*o/i,1)),easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta);}handleMapControlsPan(e,t,i){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(i,e.around);}cameraForBoxAndBearing(e,t,i,o,r){return Bt(e,t,i,o,r)}handleJumpToCenterZoom(e,i){e.zoom!==(void 0!==i.zoom?+i.zoom:e.zoom)&&e.setZoom(+i.zoom),void 0!==i.center&&e.setCenter(t.S.convert(i.center));}handleEaseTo(e,i){const o=e.zoom,r=e.padding,a={roll:e.roll,pitch:e.pitch,bearing:e.bearing},s={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},n=void 0!==i.zoom,l=!e.isPaddingEqual(i.padding);let c=!1;const h=n?+i.zoom:e.zoom;let u=e.centerPoint.add(i.offsetAsPoint);const d=e.screenPointToLocation(u),{center:_,zoom:p}=e.getConstrained(t.S.convert(i.center||d),null!=h?h:o);St(e,_);const m=le(e.worldSize,d),f=le(e.worldSize,_).sub(m),g=t.af(p-o);return c=p!==o,{easeFunc:n=>{if(c&&e.setZoom(t.C.number(o,p,n)),t.be(a,s)||Ft({startEulerAngles:a,endEulerAngles:s,tr:e,k:n,useSlerp:a.roll!=s.roll}),l&&(e.interpolatePadding(r,i.padding,n),u=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const i=t.af(e.zoom-o),r=p>o?Math.min(2,g):Math.max(.5,g),a=Math.pow(r,1-n),s=ce(e.worldSize,m.add(f.mult(n*a)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?s.wrap():s,u);}},isZooming:c,elevationCenter:_}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.zoom,a=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),o?+i.zoom:r),s=a.center,n=a.zoom;St(e,s);const l=le(e.worldSize,i.locationAtOffset),c=le(e.worldSize,s).sub(l),h=c.mag(),u=t.af(n-r);let d;if(void 0!==i.minZoom){const o=Math.min(+i.minZoom,r,n),a=e.getConstrained(s,o).zoom;d=t.af(a-r);}return {easeFunc:(i,o,a,h)=>{e.setZoom(1===i?n:r+t.ak(o));const u=1===i?s:ce(e.worldSize,l.add(c.mult(a)).mult(o));e.setLocationAtPoint(e.renderWorldCopies?u.wrap():u,h);},scaleOfZoom:u,targetCenter:s,scaleOfMinZoom:d,pixelPathLength:h}}}class jt{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}jt.Replace=[1,0],jt.disabled=new jt(jt.Replace,t.bf.transparent,[!1,!1,!1,!1]),jt.unblended=new jt(jt.Replace,t.bf.transparent,[!0,!0,!0,!0]),jt.alphaBlended=new jt([1,771],t.bf.transparent,[!0,!0,!0,!0]);const Nt=2305;class Ut{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}Ut.disabled=new Ut(!1,1029,Nt),Ut.backCCW=new Ut(!0,1029,Nt),Ut.frontCCW=new Ut(!0,1028,Nt);class Zt{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Zt.ReadOnly=!1,Zt.ReadWrite=!0,Zt.disabled=new Zt(519,Zt.ReadOnly,[0,1]);const Gt=7680;class Vt{constructor(e,t,i,o,r,a){this.test=e,this.ref=t,this.mask=i,this.fail=o,this.depthFail=r,this.pass=a;}}Vt.disabled=new Vt({func:519,mask:0},0,0,Gt,Gt,Gt);const $t=new WeakMap;function qt(e){var t;if($t.has(e))return $t.get(e);{const i=null===(t=e.getParameter(e.VERSION))||void 0===t?void 0:t.startsWith("WebGL 2.0");return $t.set(e,i),i}}class Wt{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,o=i.gl;this._texFormat=o.RGBA,this._texType=o.UNSIGNED_BYTE;const r=new t.aL;r.emplaceBack(-1,-1),r.emplaceBack(2,-1),r.emplaceBack(-1,2);const a=new t.aN;a.emplaceBack(0,1,2),this._fullscreenTriangle=new wt(i.createVertexBuffer(r,Tt.members),i.createIndexBuffer(a),t.aM.simpleSegment(0,0,r.length,a.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(o.TEXTURE1);const s=o.createTexture();o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texImage2D(o.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(s),qt(o)&&(this._pbo=o.createBuffer(),o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.bufferData(o.PIXEL_PACK_BUFFER,4,o.STREAM_READ),o.bindBuffer(o.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const o=this._cachedRenderContext.context,r=o.gl;if(this._bindFramebuffer(),o.viewport.set([0,0,this._texWidth,this._texHeight]),o.clear({color:t.bf.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(o,r.TRIANGLES,Zt.disabled,Vt.disabled,jt.unblended,Ut.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&qt(r)){r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.readBuffer(r.COLOR_ATTACHMENT0),r.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),r.bindBuffer(r.PIXEL_PACK_BUFFER,null);const e=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);r.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&qt(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=Wt._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const Ht=t.$/128;function Xt(e,i){const o=void 0!==e.granularity?Math.max(e.granularity,1):1,r=o+(e.generateBorders?2:0),a=o+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),s=r+1,n=a+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=o+(e.generateBorders?1:0),u=o+(e.generateBorders||e.extendToSouthPole?1:0),d=s*n,_=r*a*6,p=s*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g=0;for(let i=c;i<=u;i++)for(let r=l;r<=h;r++){let a=r/o*t.$;-1===r&&(a=-Ht),r===o+1&&(a=t.$+Ht);let s=i/o*t.$;-1===i&&(s=e.extendToNorthPole?t.bh:-Ht),i===o+1&&(s=e.extendToSouthPole?t.bi:t.$+Ht),f[g++]=a,f[g++]=s;}const v=m?new Uint32Array(_):new Uint16Array(_);let b=0;for(let e=0;e0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return "globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy();}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e);}getMeshFromTileID(e,t,i,o,r){return this.currentProjection.getMeshFromTileID(e,t,i,o,r)}setProjection(e){this._transitionable.setValue("type",(null==e?void 0:e.type)||"mercator");}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e);}}function ei(e){const t=oi(e.worldSize,e.center.lat);return 2*Math.PI*t}function ti(e,i,o,r,a){const s=1/(1<1e-6){const r=e[0]/o,a=Math.acos(e[2]/o),s=(r>0?a:-a)/Math.PI*180;return new t.S(t.aO(s,-180,180),i)}return new t.S(0,i)}function ai(e){return Math.cos(e*Math.PI/180)}function si(e,i){const o=ai(e),r=ai(i);return t.ak(r/o)}function ni(e,i){const o=e.rotate(i.bearingInRadians),r=i.zoom+si(i.center.lat,0),a=t.bk(1/ai(i.center.lat),1/ai(Math.min(Math.abs(i.center.lat),60)),t.bn(r,7,3,0,1)),s=360/ei({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.S(i.center.lng-o.x*s*a,t.ah(i.center.lat+o.y*s,-t.ai,t.ai))}function li(e){const t=.5*e,i=Math.sin(t),o=Math.cos(t);return Math.log(i+o)-Math.log(o-i)}function ci(e,i,o,r){const a=e.lat+o*r;if(Math.abs(o)>1){const s=(Math.sign(e.lat+o)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+o)*Math.PI/180,l=li(s+r*(n-s)),c=li(s),h=li(n);return new t.S(e.lng+i*((l-c)/(h-c)),a)}return new t.S(e.lng+i*r,a)}class hi{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._boundingVolumeFactory=e;}swapBuffers(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1;}getTileBoundingVolume(e,t,i,o){const r=`${e.z}_${e.x}_${e.y}_${(null==o?void 0:o.terrain)?"t":""}`,a=this._cache.get(r);if(a)return a;const s=this._cachePrevious.get(r);if(s)return this._cache.set(r,s),s;const n=this._boundingVolumeFactory(e,t,i,o);return this._cache.set(r,n),this._hadAnyChanges=!0,n}}class ui{constructor(e,t,i,o){this.min=i,this.max=o,this.points=e,this.planes=t;}static fromAabb(e,t){const i=[];for(let o=0;o<8;o++)i.push([1&~o?e[0]:t[0],1==(o>>1&1)?t[1]:e[1],1==(o>>2&1)?t[2]:e[2]]);return new ui(i,[[-1,0,0,t[0]],[1,0,0,-e[0]],[0,-1,0,t[1]],[0,1,0,-e[1]],[0,0,-1,t[2]],[0,0,1,-e[2]]],e,t)}static fromCenterSizeAngles(e,i,o){const r=t.br([],o[0],o[1],o[2]),a=t.bs([],[i[0],0,0],r),s=t.bs([],[0,i[1],0],r),n=t.bs([],[0,0,i[2]],r),l=[...e],c=[...e];for(let t=0;t<8;t++)for(let i=0;i<3;i++){const o=e[i]+a[i]*(1&~t?-1:1)+s[i]*(1==(t>>1&1)?1:-1)+n[i]*(1==(t>>2&1)?1:-1);l[i]=Math.min(l[i],o),c[i]=Math.max(c[i],o);}const h=[];for(let i=0;i<8;i++){const o=[...e];t.aS(o,o,t.aR([],a,1&~i?-1:1)),t.aS(o,o,t.aR([],s,1==(i>>1&1)?1:-1)),t.aS(o,o,t.aR([],n,1==(i>>2&1)?1:-1)),h.push(o);}return new ui(h,[[...a,-t.aX(a,h[0])],[...s,-t.aX(s,h[0])],[...n,-t.aX(n,h[0])],[-a[0],-a[1],-a[2],-t.aX(a,h[7])],[-s[0],-s[1],-s[2],-t.aX(s,h[7])],[-n[0],-n[1],-n[2],-t.aX(n,h[7])]],l,c)}intersectsFrustum(e){let t=!0;const i=this.points.length,o=this.planes.length,r=e.planes.length,a=e.points.length;for(let o=0;o=0&&a++;}if(0===a)return 0;a=0&&o++;}if(0===o)return 0}return 1}intersectsPlane(e){const t=this.points.length;let i=0;for(let o=0;o=0&&i++;}return i===t?2:0===i?0:1}}function di(e,t,i){const o=e-t;return o<0?-o:Math.max(0,o-i)}function _i(e,t,i,o,r){const a=e-i;let s;return s=a<0?Math.min(-a,1+a-r):a>1?Math.min(Math.max(a-r,0),1-a):0,Math.max(s,di(t,o,r))}class pi{constructor(){this._boundingVolumeCache=new hi(this._computeTileBoundingVolume);}prepareNextFrame(){this._boundingVolumeCache.swapBuffers();}distanceToTile2d(e,t,i,o){const r=1<4}allowWorldCopies(){return !1}getTileBoundingVolume(e,t,i,o){return this._boundingVolumeCache.getTileBoundingVolume(e,t,i,o)}_computeTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}if(n/=t.bu,l/=t.bu,n+=1,l+=1,e.z<=0)return ui.fromAabb([-l,-l,-l],[l,l,l]);if(1===e.z)return ui.fromAabb([0===e.x?-l:0,0===e.y?0:-l,-l],[0===e.x?0:l,0===e.y?l:0,l]);{const i=[ti(0,0,e.x,e.y,e.z),ti(t.$,0,e.x,e.y,e.z),ti(t.$,t.$,e.x,e.y,e.z),ti(0,t.$,e.x,e.y,e.z)],o=[];for(const e of i)o.push(t.aR([],e,l));if(l!==n)for(const e of i)o.push(t.aR([],e,n));0===e.y&&o.push([0,1,0]),e.y===(1<=(1<{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._coveringTilesDetailsProvider=new pi;}clone(){const e=new fi;return e.apply(this),e}apply(e,t){this._globeLatitudeErrorCorrectionRadians=t||0,this._helper.apply(e);}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const e=t.bp();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(e){const{overscaledTileID:t,applyGlobeMatrix:i}=e,o=this._helper.getMercatorTileCoordinates(t);return {mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:o,clippingPlane:this._cachedClippingPlane,projectionTransition:i?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(e){const i=this.pitchInRadians,o=this.cameraToCenterDistance/e,r=Math.sin(i)*o,a=Math.cos(i)*o+1,s=1/Math.sqrt(r*r+a*a)*1;let n=-r,l=a;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];t.bw(h,h,[0,0,0],-this.bearingInRadians),t.bx(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.by(h,h,[0,0,0],this.center.lng*Math.PI/180);const u=1/t.aZ(h);return t.aR(h,h,u),[...h,-s*u]}isLocationOccluded(e){return !this.isSurfacePointVisible(ii(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,o=this._helper._center.lat*Math.PI/180,r=Math.cos(o),a=[Math.sin(i)*r,Math.sin(o),Math.cos(i)*r],s=[a[2],0,-a[0]],n=[0,0,0];t.aW(n,s,a),t.aV(s,s),t.aV(n,n);const l=[0,0,0];return t.aV(l,[s[0]*e[0]+n[0]*e[1]+a[0]*e[2],s[1]*e[0]+n[1]*e[1]+a[1]*e[2],s[2]*e[0]+n[2]*e[1]+a[2]*e[2]]),l}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(e,i,o){const r=function(e,i,o){const r=1/(1<a&&(a=i),on&&(n=o);}const h=[c.lng+s,c.lat+l,c.lng+a,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new G(h)}getConstrained(e,i){const o=t.ah(e.lat,-t.ai,t.ai),r=t.ah(+i,this.minZoom+si(0,o),this.maxZoom);return {center:new t.S(e.lng,o),zoom:r}}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,i){const o=ii(this.unprojectScreenPoint(i)),r=ii(e),a=t.bp();t.bB(a);const s=t.bp();t.by(s,o,a,-this.center.lng*Math.PI/180),t.bx(s,s,a,this.center.lat*Math.PI/180);const n=r[0]*r[0]+r[2]*r[2],l=s[0]*s[0];if(n=-g&&p<=g,b=f>=-g&&f<=g;let x,y;if(v&&b){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.bD(u,e)+t.bD(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return !1;const i=t.bv();return t.aw(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const o=t.aX(e,i),r=t.bp(),a=t.bp();t.aR(a,i,o),t.aU(r,e,a);const s=1-t.aX(r,r);if(s<0)return null;const n=t.aX(e,e)-1,l=-o+(o<0?1:-1)*Math.sqrt(s),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,o=this.getRayDirectionFromPixel(e),r=this.rayPlanetIntersection(i,o);if(r){const e=t.bp();t.aS(e,i,[o[0]*r.tMin,o[1]*r.tMin,o[2]*r.tMin]);const a=t.bp();return t.aV(a,e),ri(a)}const a=this._cachedClippingPlane,s=a[0]*o[0]+a[1]*o[1]+a[2]*o[2],n=-t.b1(a,i)/s,l=t.bp();if(n>0)t.aS(l,i,[o[0]*n,o[1]*n,o[2]*n]);else {const e=t.bp();t.aS(e,i,[2*o[0],2*o[1],2*o[2]]);const r=t.b1(this._cachedClippingPlane,e);t.aU(l,e,[this._cachedClippingPlane[0]*r,this._cachedClippingPlane[1]*r,this._cachedClippingPlane[2]*r]);}const c=function(e){const i=t.bp();return i[0]=e[0]*-e[3],i[1]=e[1]*-e[3],i[2]=e[2]*-e[3],{center:i,radius:Math.sqrt(1-e[3]*e[3])}}(a);return ri(function(e,i,o){const r=t.bp();t.aU(r,o,e);const a=t.bp();return t.bq(a,e,r,i/t.a$(r)),a}(c.center,c.radius,l))}getMatrixForModel(e,i){const o=t.S.convert(e),r=1/t.bu,a=t.b9();return t.bz(a,a,o.lng/180*Math.PI),t.b7(a,a,-o.lat/180*Math.PI),t.M(a,a,[0,0,1+i/t.bu]),t.b7(a,a,.5*Math.PI),t.N(a,a,[r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=this.getProjectionData({overscaledTileID:new t.Z(0,0,0,0,0),applyGlobeMatrix:e});return i.tileMercatorCoords=[0,0,1,1],i}getFastPathSimpleProjectionMatrix(e){}}class gi{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame(),this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame();}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._globeness=1,this._mercatorTransform=new Lt,this._verticalPerspectiveTransform=new fi;}clone(){const e=new gi;return e._globeness=this._globeness,e._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,e.apply(this),e}apply(e){this._helper.apply(e),this._mercatorTransform.apply(this),this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians);}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){const t=this._mercatorTransform.getProjectionData(e),i=this._verticalPerspectiveTransform.getProjectionData(e);return {mainMatrix:this.isGlobeRendering?i.mainMatrix:t.mainMatrix,clippingPlane:i.clippingPlane,tileMercatorCoords:i.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return t.bk(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return t.bk(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,i,o){const r=this._mercatorTransform.getPitchedTextCorrection(e,i,o),a=this._verticalPerspectiveTransform.getPitchedTextCorrection(e,i,o);return t.bk(r,a,this._globeness)}projectTileCoordinates(e,t,i,o){return this.currentTransform.projectTileCoordinates(e,t,i,o)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ);}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this._mercatorTransform.recalculateZoomAndCenter(e),this._verticalPerspectiveTransform.recalculateZoomAndCenter(e);}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e);}getBounds(){return this.currentTransform.getBounds()}getConstrained(e,t){return this.currentTransform.getConstrained(e,t)}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,t){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,t),void this.apply(this._mercatorTransform);this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform);}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getMatrixForModel(e,t){return this.currentTransform.getMatrixForModel(e,t)}getProjectionDataForCustomLayer(e=!0){const t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;const i=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return i.fallbackMatrix=t.mainMatrix,i}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}}class vi{get useGlobeControls(){return !0}handlePanInertia(e,i){const o=ni(e,i);return Math.abs(o.lng-i.center.lng)>180&&(o.lng=i.center.lng+179.5*Math.sign(o.lng-i.center.lng)),{easingCenter:o,easingOffset:new t.P(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){const o=e.around,r=i.screenPointToLocation(o);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const a=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const s=i.zoom-a;if(0===s)return;const n=t.bA(i.center.lng,r.lng),l=n/(Math.abs(n/180)+1),c=t.bA(i.center.lat,r.lat),h=i.getRayDirectionFromPixel(o),u=i.cameraPosition,d=-1*t.aX(u,h),_=t.bp();t.aS(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.aZ(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=oi(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.bn(f,.9,.5,1,.25),v=(1-t.af(-s))*Math.min(m,g),b=i.center.lat,x=i.zoom,y=new t.S(i.center.lng+l*v,t.ah(i.center.lat+c*v,-t.ai,t.ai));i.setLocationAtPoint(r,o);const w=i.center,T=t.bn(Math.abs(n),45,85,0,1),P=t.bn(f,.75,.35,0,1),C=Math.pow(Math.max(T,P),.25),I=t.bA(w.lng,y.lng),M=t.bA(w.lat,y.lat);i.setCenter(new t.S(w.lng+I*C,w.lat+M*C).wrap()),i.setZoom(x+si(b,i.center.lat));}handleMapControlsPan(e,t,i){if(!e.panDelta)return;const o=t.center.lat,r=t.zoom;t.setCenter(ni(e.panDelta,t).wrap()),t.setZoom(r+si(o,t.center.lat));}cameraForBoxAndBearing(e,i,o,r,a){const s=Bt(e,i,o,r,a),n=i.left/a.width*2-1,l=(a.width-i.right)/a.width*2-1,c=i.top/a.height*-2+1,h=(a.height-i.bottom)/a.height*-2+1,u=t.bA(o.getWest(),o.getEast())<0,d=u?o.getEast():o.getWest(),_=u?o.getWest():o.getEast(),p=Math.max(o.getNorth(),o.getSouth()),m=Math.min(o.getNorth(),o.getSouth()),f=d+.5*t.bA(d,_),g=p+.5*t.bA(p,m),v=a.clone();v.setCenter(s.center),v.setBearing(s.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(s.zoom);const b=v.modelViewProjectionMatrix,x=[ii(o.getNorthWest()),ii(o.getNorthEast()),ii(o.getSouthWest()),ii(o.getSouthEast()),ii(new t.S(_,g)),ii(new t.S(d,g)),ii(new t.S(f,p)),ii(new t.S(f,m))],y=ii(s.center);let w=Number.POSITIVE_INFINITY;for(const e of x)n<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",n))),l>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",l))),c>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",c))),h<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",h)));if(Number.isFinite(w)&&0!==w)return s.zoom=v.zoom+t.ak(w),s;kt();}handleJumpToCenterZoom(e,i){const o=e.center.lat,r=e.getConstrained(i.center?t.S.convert(i.center):e.center,e.zoom).center;e.setCenter(r.wrap());const a=void 0!==i.zoom?+i.zoom:e.zoom+si(o,r.lat);e.zoom!==a&&e.setZoom(a);}handleEaseTo(e,i){const o=e.zoom,r=e.center,a=e.padding,s={roll:e.roll,pitch:e.pitch,bearing:e.bearing},n={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},l=void 0!==i.zoom,c=!e.isPaddingEqual(i.padding);let h=!1;const u=i.center?t.S.convert(i.center):r,d=e.getConstrained(u,o).center;St(e,d);const _=e.clone();_.setCenter(d),_.setZoom(l?+i.zoom:o+si(r.lat,u.lat)),_.setBearing(i.bearing);const p=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));_.setLocationAtPoint(d,p);const m=(i.offset&&i.offsetAsPoint.mag())>0?_.center:d,f=l?+i.zoom:o+si(r.lat,m.lat),g=o+si(r.lat,0),v=f+si(m.lat,0),b=t.bA(r.lng,m.lng),x=t.bA(r.lat,m.lat),y=t.af(v-g);return h=f!==o,{easeFunc:o=>{if(t.be(s,n)||Ft({startEulerAngles:s,endEulerAngles:n,tr:e,k:o,useSlerp:s.roll!=n.roll}),c&&e.interpolatePadding(a,i.padding,o),i.around)t.w("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=v>g?Math.min(2,y):Math.max(.5,y),i=Math.pow(t,1-o),a=ci(r,b,x,o*i);e.setCenter(a.wrap());}if(h){const i=t.C.number(g,v,o)+si(0,e.center.lat);e.setZoom(i);}},isZooming:h,elevationCenter:m}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.center,a=e.zoom,s=e.padding,n=!e.isPaddingEqual(i.padding),l=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),a).center,c=o?+i.zoom:e.zoom+si(e.center.lat,l.lat),h=e.clone();h.setCenter(l),h.setZoom(c),h.setBearing(i.bearing);const u=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));h.setLocationAtPoint(l,u);const d=h.center;St(e,d);const _=function(e,i,o){const r=ii(i),a=ii(o),s=t.aX(r,a),n=Math.acos(s),l=ei(e);return n/(2*Math.PI)*l}(e,r,d),p=a+si(r.lat,0),m=c+si(d.lat,0),f=t.af(m-p);let g;if("number"==typeof i.minZoom){const o=+i.minZoom+si(d.lat,0),r=Math.min(o,p,m)+si(0,d.lat),a=e.getConstrained(d,r).zoom+si(d.lat,0);g=t.af(a-p);}const v=t.bA(r.lng,d.lng),b=t.bA(r.lat,d.lat);return {easeFunc:(o,a,l,h)=>{const u=ci(r,v,b,l);n&&e.interpolatePadding(s,i.padding,o);const _=1===o?d:u;e.setCenter(_.wrap());const m=p+t.ak(a);e.setZoom(1===o?c:m+si(0,_.lat));},scaleOfZoom:f,targetCenter:d,scaleOfMinZoom:g,pixelPathLength:_}}static solveVectorScale(e,t,i,o,r){const a="x"===o?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],s=[i[3],i[7],i[11],i[15]],n=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],l=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],c=t[0]*a[0]+t[1]*a[1]+t[2]*a[2],h=t[0]*s[0]+t[1]*s[1]+t[2]*s[2];return c+r*l===n+r*h||s[3]*(n-c)+a[3]*(h-l)+n*h==c*l?null:(c+a[3]-r*h-r*s[3])/(c-n-r*h+r*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.y(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),yi=t.bE();class wi extends t.E{constructor(e,i={}){var o,r;super(),this._rtlPluginLoaded=()=>{for(const e in this.sourceCaches){const t=this.sourceCaches[e].getSource().type;"vector"!==t&&"geojson"!==t||this.sourceCaches[e].reload();}},this.map=e,this.dispatcher=new F(k(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.imageManager=new b,this.imageManager.setEventedParent(this);const a=(null===(o=e._container)||void 0===o?void 0:o.lang)||"undefined"!=typeof document&&(null===(r=document.documentElement)||void 0===r?void 0:r.lang)||void 0;this.glyphManager=new T(e._requestManager,i.localIdeographFontFamily,a),this.lineAtlas=new E(256,512),this.crossTileSymbolIndex=new vt,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.bF,this._loaded=!1,this._availableImages=[],this._globalState={},this._resetUpdates(),this.dispatcher.broadcast("SR",t.bG()),oe().on(ee,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.sourceCaches[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}setGlobalStateProperty(e,i){var o,r,a;this._checkLoaded();const s=null===i?null!==(a=null===(r=null===(o=this.stylesheet.state)||void 0===o?void 0:o[e])||void 0===r?void 0:r.default)&&void 0!==a?a:null:i;if(t.bH(s,this._globalState[e]))return this;this._globalState[e]=s,this._applyGlobalStateChanges([e]);}getGlobalState(){return this._globalState}setGlobalState(e){this._checkLoaded();const i=[];for(const o in e)!t.bH(this._globalState[o],e[o].default)&&(i.push(o),this._globalState[o]=e[o].default);this._applyGlobalStateChanges(i);}_applyGlobalStateChanges(e){if(0===e.length)return;const t=new Set,i={};for(const o of e){i[o]=this._globalState[o];for(const e in this._layers){const i=this._layers[e],r=i.getLayoutAffectingGlobalStateRefs(),a=i.getPaintAffectingGlobalStateRefs();if(r.has(o)&&t.add(i.source),a.has(o))for(const{name:e,value:t}of a.get(o))this._updatePaintProperty(i,e,t);}}this.dispatcher.broadcast("UGS",i);for(const e in this.sourceCaches)t.has(e)&&(this._reloadSource(e),this._changed=!0);}loadURL(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const r=this.map._requestManager.transformRequest(e,"Style");this._loadStyleRequest=new AbortController;const a=this._loadStyleRequest;t.j(r,this._loadStyleRequest).then((e=>{this._loadStyleRequest=null,this._load(e.data,i,o);})).catch((e=>{this._loadStyleRequest=null,e&&!a.signal.aborted&&this.fire(new t.k(e));}));}loadJSON(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,s.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=!1!==i.validate,this._load(e,i,o);})).catch((()=>{}));}loadEmpty(){this.fire(new t.l("dataloading",{dataType:"style"})),this._load(yi,{validate:!1});}_load(e,i,o){var r,a;let s=i.transformStyle?i.transformStyle(o,e):e;if(!i.validate||!xi(this,t.z(s))){s=Object.assign({},s),this._loaded=!0,this.stylesheet=s;for(const e in s.sources)this.addSource(e,s.sources[e],{validate:!1});s.sprite?this._loadSprite(s.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(s.glyphs),this._createLayers(),this.light=new I(this.stylesheet.light),this._setProjectionInternal((null===(r=this.stylesheet.projection)||void 0===r?void 0:r.type)||"mercator"),this.sky=new S(this.stylesheet.sky),this.map.setTerrain(null!==(a=this.stylesheet.terrain)&&void 0!==a?a:null),this.fire(new t.l("data",{dataType:"style"})),this.fire(new t.l("style.load"));}}_createLayers(){var e;const i=t.bI(this.stylesheet.layers);this.setGlobalState(null!==(e=this.stylesheet.state)&&void 0!==e?e:null),this.dispatcher.broadcast("SL",i),this._order=i.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const e of i){const i=t.bJ(e,this._globalState);i.setEventedParent(this,{layer:{id:e.id}}),this._layers[e.id]=i;}}_loadSprite(e,i=!1,o=void 0){let r;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=f(e),n=o>1?"@2x":"",l={},c={};for(const{id:e,url:o}of a){const a=i.transformRequest(g(o,n,".json"),"SpriteJSON");l[e]=t.j(a,r);const s=i.transformRequest(g(o,n,".png"),"SpriteImage");c[e]=p.getImage(s,r);}return yield Promise.all([...Object.values(l),...Object.values(c)]),function(e,i){return t._(this,void 0,void 0,(function*(){const t={};for(const o in e){t[o]={};const r=s.getImageCanvasContext((yield i[o]).data),a=(yield e[o]).data;for(const e in a){const{width:i,height:s,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=a[e];t[o][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:s,x:n,y:l,context:r}};}}return t}))}(l,c)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const o=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of o)this.imageManager.removeImage(e),this._changedImages[e]=!0;for(const o in e[t]){const r="default"===t?o:`${t}:${o}`;this._spritesImagesIds[t].push(r),r in this.imageManager.images?this.imageManager.updateImage(r,e[t][o],!1):this.imageManager.addImage(r,e[t][o]),i&&(this._changedImages[r]=!0);}}})).catch((e=>{this._spriteRequest=null,r=e,this.fire(new t.k(r));})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),i&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"})),o&&o(r);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}_validateLayer(e){const i=this.sourceCaches[e.source];if(!i)return;const o=e.sourceLayer;if(!o)return;const r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.k(new Error(`Source layer "${o}" does not exist on source "${r.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(const e in this.sourceCaches)if(!this.sourceCaches[e].loaded())return !1;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=!1){const o=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.bK(o):o);const r=[];for(const a of e)if(o[a]){const e=i?t.bK(o[a]):o[a];r.push(e);}return r}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){var e,t,i;if(null===(e=this.light)||void 0===e?void 0:e.hasTransition())return !0;if(null===(t=this.sky)||void 0===t?void 0:t.hasTransition())return !0;if(null===(i=this.projection)||void 0===i?void 0:i.hasTransition())return !0;for(const e in this.sourceCaches)if(this.sourceCaches[e].hasTransition())return !0;for(const e in this._layers)if(this._layers[e].hasTransition())return !0;return !1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const o={};for(const e in this.sourceCaches){const t=this.sourceCaches[e];o[e]=t.used,t.used=!1;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.sourceCaches[i.source].used=!0);}for(const e in o){const i=this.sourceCaches[e];!!o[e]!=!!i.used&&i.fire(new t.l("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.projection.recalculate(e),this.z=e.zoom,i&&this.fire(new t.l("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,!1),removedIds:t});}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1;}setState(e,i={}){var o;this._checkLoaded();const r=this.serialize();if(e=i.transformStyle?i.transformStyle(r,e):e,(null===(o=i.validate)||void 0===o||o)&&xi(this,t.z(e)))return !1;(e=t.bK(e)).layers=t.bI(e.layers);const a=t.bL(r,e),s=this._getOperationsToPerform(a);if(s.unimplemented.length>0)throw new Error(`Unimplemented: ${s.unimplemented.join(", ")}.`);if(0===s.operations.length)return !1;for(const e of s.operations)e();return this.stylesheet=e,this._serializedLayers=null,!0}_getOperationsToPerform(e){const t=[],i=[];for(const o of e)switch(o.command){case "setCenter":case "setZoom":case "setBearing":case "setPitch":case "setRoll":continue;case "addLayer":t.push((()=>this.addLayer.apply(this,o.args)));break;case "removeLayer":t.push((()=>this.removeLayer.apply(this,o.args)));break;case "setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,o.args)));break;case "setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,o.args)));break;case "setFilter":t.push((()=>this.setFilter.apply(this,o.args)));break;case "addSource":t.push((()=>this.addSource.apply(this,o.args)));break;case "removeSource":t.push((()=>this.removeSource.apply(this,o.args)));break;case "setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,o.args)));break;case "setLight":t.push((()=>this.setLight.apply(this,o.args)));break;case "setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,o.args)));break;case "setGlyphs":t.push((()=>this.setGlyphs.apply(this,o.args)));break;case "setSprite":t.push((()=>this.setSprite.apply(this,o.args)));break;case "setTerrain":t.push((()=>this.map.setTerrain.apply(this,o.args)));break;case "setSky":t.push((()=>this.setSky.apply(this,o.args)));break;case "setProjection":this.setProjection.apply(this,o.args);break;case "setGlobalState":t.push((()=>this.setGlobalState.apply(this,o.args)));break;case "setTransition":t.push((()=>{}));break;default:i.push(o.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,o={}){if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.z.source,`sources.${e}`,i,null,o))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const r=this.sourceCaches[e]=new xe(e,i,this.dispatcher);r.style=this,r.setEventedParent(this,(()=>({isSourceLoaded:r.loaded(),source:r.serialize(),sourceId:e}))),r.onAdd(this.map),this._changed=!0;}removeSource(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.k(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],i.fire(new t.l("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=!0;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error(`There is no source with this ID=${e}`);const i=this.sourceCaches[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=!0;}getSource(e){return this.sourceCaches[e]&&this.sourceCaches[e].getSource()}addLayer(e,i,o={}){this._checkLoaded();const r=e.id;if(this.getLayer(r))return void this.fire(new t.k(new Error(`Layer "${r}" already exists on this map.`)));let a;if("custom"===e.type){if(xi(this,t.bM(e)))return;a=t.bJ(e,this._globalState);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(r,e.source),e=t.bK(e),e=t.e(e,{source:r})),this._validate(t.z.layer,`layers.${r}`,e,{arrayIndex:-1},o))return;a=t.bJ(e,this._globalState),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}});}const s=i?this._order.indexOf(i):this._order.length;if(i&&-1===s)this.fire(new t.k(new Error(`Cannot add layer "${r}" before non-existing layer "${i}".`)));else {if(this._order.splice(s,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){const e=this._removedLayers[r];delete this._removedLayers[r],e.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=!0,!this._layers[e])return void this.fire(new t.k(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const o=this._order.indexOf(e);this._order.splice(o,1);const r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.k(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.k(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,o){this._checkLoaded();const r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.k(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,o={}){this._checkLoaded();const r=this.getLayer(e);if(r){if(!t.bH(r.filter,i))return null==i?(r.setFilter(void 0),void this._updateLayer(r)):void(this._validate(t.z.filter,`layers.${r.id}.filter`,i,null,o)||(r.setFilter(t.bK(i)),this._updateLayer(r)))}else this.fire(new t.k(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.bK(this.getLayer(e).filter)}setLayoutProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.k(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getPaintProperty(i),o)||this._updatePaintProperty(a,i,o,r):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}_updatePaintProperty(e,t,i,o={}){e.setPaintProperty(t,i,o)&&this._updateLayer(e),this._changed=!0,this._updatedPaintProps[e.id]=!0,this._serializedLayers=null;}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0===a)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const s=a.getSource().type;"geojson"===s&&r?this.fire(new t.k(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==s||r?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const o=e.source,r=this.sourceCaches[o];if(void 0===r)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const a=r.getSource().type,s="vector"===a?e.sourceLayer:void 0;"vector"!==a||s?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.k(new Error("A feature id is required to remove its specific state property."))):r.removeFeatureState(s,e.id,i):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r)return "vector"!==r.getSource().type||o?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id)):void this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.k(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.bN(this.sourceCaches,(e=>e.serialize())),i=this._serializeByIds(this._order,!0),o=this.map.getTerrain()||void 0,r=this.stylesheet;return t.bO({version:r.version,name:r.name,metadata:r.metadata,light:r.light,sky:r.sky,center:r.center,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,sprite:r.sprite,glyphs:r.glyphs,transition:r.transition,projection:r.projection,sources:e,layers:i,terrain:o},(e=>void 0!==e))}_updateLayer(e){this._updatedLayers[e.id]=!0,e.source&&!this._updatedSources[e.source]&&"raster"!==this.sourceCaches[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.sourceCaches[e.source].pause()),this._serializedLayers=null,this._changed=!0;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},o=[];for(let r=this._order.length-1;r>=0;r--){const a=this._order[r];if(t(a)){i[a]=r;for(const t of e){const e=t[a];if(e)for(const t of e)o.push(t);}}}o.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const r=[];for(let a=this._order.length-1;a>=0;a--){const s=this._order[a];if(t(s))for(let e=o.length-1;e>=0;e--){const t=o[e].feature;if(i[t.layer.id]this.map.terrain.getElevation(e,t,i):void 0));return this.placement&&a.push(function(e,t,i,o,r,a,s){const n={},l=a.queryRenderedSymbols(o),c=[];for(const e of Object.keys(l).map(Number))c.push(s[e]);c.sort(N);for(const i of c){const o=i.featureIndex.lookupSymbolFeatures(l[i.bucketInstanceId],t,i.bucketIndex,i.sourceLayerIndex,{filterSpec:r.filter,globalState:r.globalState},r.layers,r.availableImages,e);for(const e in o){const t=n[e]=n[e]||[],r=o[e];r.sort(((e,t)=>{const o=i.featureSortOrder;if(o){const i=o.indexOf(e.featureIndex);return o.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of r)t.push(e);}}return function(e,t,i){for(const o in e)for(const r of e[o])U(r,i[t[o].source]);return e}(n,e,i)}(this._layers,s,this.sourceCaches,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(a)}querySourceFeatures(e,i){(null==i?void 0:i.filter)&&this._validate(t.z.filter,"querySourceFeatures.filter",i.filter,null,i);const o=this.sourceCaches[e];return o?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),o=[],r={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const o=this.crossTileSymbolIndex.addLayer(i,l[i.source],e.center.lng);a=a||o;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((r=r||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(s.now(),e.zoom))&&(this.pauseablePlacement=new _t(e,this.map.terrain,this._order,r,t,i,o,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(s.now()),n=!0),a&&this.pauseablePlacement.placement.setStale()),n||a)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,l[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(s.now())}_releaseSymbolFadeTiles(){for(const e in this.sourceCaches)this.sourceCaches[e].releaseSymbolFadeTiles();}getImages(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.z.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}addSprite(e,i,o={},r){this._checkLoaded();const a=[{id:e,url:i}],s=[...f(this.stylesheet.sprite),...a];this._validate(t.z.sprite,"sprite",s,null,o)||(this.stylesheet.sprite=s,this._loadSprite(a,!0,r));}removeSprite(e){this._checkLoaded();const i=f(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=!0;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:void 0,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}else this.fire(new t.k(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return f(this.stylesheet.sprite)}setSprite(e,i={},o){this._checkLoaded(),e&&this._validate(t.z.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,!0,o):(this._unloadSprite(),o&&o(null)));}}var Ti=t.aJ([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class Pi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;}bind(e,t,i,o,r,a,s,n,l){this.context=e;let c=this.boundPaintVertexBuffers.length!==o.length;for(let e=0;!c&&e({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:o?o.properties.get("fog-color"):t.bf.white,u_fog_ground_blend:o?o.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:a?0:o?o.calculateFogBlendOpacity(r):0,u_horizon_color:o?o.properties.get("horizon-color"):t.bf.white,u_horizon_fog_blend:o?o.properties.get("horizon-fog-blend"):1,u_is_globe_mode:a?1:0}),Ii={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function Mi(e){const t=[];for(let i=0;i({u_depth:new t.bP(e,i.u_depth),u_terrain:new t.bP(e,i.u_terrain),u_terrain_dim:new t.bg(e,i.u_terrain_dim),u_terrain_matrix:new t.bR(e,i.u_terrain_matrix),u_terrain_unpack:new t.bS(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.bg(e,i.u_terrain_exaggeration)}))(e,C),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.bR(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.bS(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.bS(e,i.u_projection_clipping_plane),u_projection_transition:new t.bg(e,i.u_projection_transition),u_projection_fallback_matrix:new t.bR(e,i.u_projection_fallback_matrix)}))(e,C),this.binderUniforms=o?o.getUniforms(e,C):[];}draw(e,t,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v){const b=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(o),e.setColorMode(r),e.setCullFace(a),n){e.activeTexture.set(b.TEXTURE2),b.bindTexture(b.TEXTURE_2D,n.depthTexture),e.activeTexture.set(b.TEXTURE3),b.bindTexture(b.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[Ii[e]].set(l[e]);if(s)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(s[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let x=0;switch(t){case b.LINES:x=2;break;case b.TRIANGLES:x=3;break;case b.LINE_STRIP:x=1;}for(const i of d.get()){const o=i.vaos||(i.vaos={});(o[c]||(o[c]=new Pi)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),b.drawElements(t,i.primitiveLength*x,b.UNSIGNED_SHORT,i.primitiveOffset*x*2);}}}function Ei(e,i,o){const r=1/t.aC(o,1,i.transform.tileZoom),a=Math.pow(2,o.tileID.overscaledZ),s=o.tileSize*Math.pow(2,i.transform.tileZoom)/a,n=s*(o.tileID.canonical.x+o.tileID.wrap*a),l=s*o.tileID.canonical.y;return {u_image:0,u_texsize:o.imageAtlasTexture.size,u_scale:[r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Ri=(e,i,o,r)=>{const a=e.style.light,s=a.properties.get("position"),n=[s.x,s.y,s.z],l=t.bV();"viewport"===a.properties.get("anchor")&&t.bW(l,e.transform.bearingInRadians),t.bX(n,n,l);const c=e.transform.transformLightDirection(n),h=a.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:o,u_fill_translate:r}},zi=(e,i,o,r,a,s,n)=>t.e(Ri(e,i,o,r),Ei(s,e,n),{u_height_factor:-Math.pow(2,a.overscaledZ)/n.tileSize/8}),Di=(e,i,o,r)=>t.e(Ei(i,e,o),{u_fill_translate:r}),Ai=(e,t)=>({u_world:e,u_fill_translate:t}),Li=(e,i,o,r,a)=>t.e(Di(e,i,o,a),{u_world:r}),ki=(e,i,o,r,a)=>{const s=e.transform;let n,l,c=0;if("map"===o.paint.get("circle-pitch-alignment")){const e=t.aC(i,1,s.zoom);n=!0,l=[e,e],c=e/(t.$*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*a;}else n=!1,l=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===o.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:r}},Fi=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),Bi=e=>({u_viewport_size:[e.width,e.height]}),Oi=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),ji=(e,i,o,r)=>{const a=t.aC(e,1,i)/(t.$*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*r;return {u_extrude_scale:t.aC(e,1,i),u_intensity:o,u_globe_extrude_scale:a}},Ni=(e,i,o,r)=>{const a=t.L();t.bY(a,0,e.width,e.height,0,0,1);const s=e.context.gl;return {u_matrix:a,u_world:[s.drawingBufferWidth,s.drawingBufferHeight],u_image:o,u_color_ramp:r,u_opacity:i.paint.get("heatmap-opacity")}},Ui=(e,t,i)=>{const o=i.paint.get("hillshade-accent-color");let r;switch(i.paint.get("hillshade-method")){case "basic":r=4;break;case "combined":r=1;break;case "igor":r=2;break;case "multidirectional":r=3;break;default:r=0;}const a=i.getIlluminationProperties();for(let t=0;t{const o=i.stride,r=t.L();return t.bY(r,0,t.$,-t.$,0,0,1),t.M(r,r,[0,-t.$,0]),{u_matrix:r,u_image:1,u_dimension:[o,o],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function Gi(e,i){const o=Math.pow(2,i.canonical.z),r=i.canonical.y;return [new t.a1(0,r/o).toLngLat().lat,new t.a1(0,(r+1)/o).toLngLat().lat]}const Vi=(e,t,i=0)=>({u_image:0,u_unpack:t.getUnpackVector(),u_dimension:[t.stride,t.stride],u_elevation_stops:1,u_color_stops:4,u_color_ramp_size:i,u_opacity:e.paint.get("color-relief-opacity")}),$i=(e,i,o,r)=>{const a=e.transform;return {u_translation:Ki(e,i,o),u_ratio:r/t.aC(i,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},qi=(e,i,o,r,a)=>t.e($i(e,i,o,r),{u_image:0,u_image_height:a}),Wi=(e,i,o,r,a)=>{const s=e.transform,n=Xi(i,s);return {u_translation:Ki(e,i,o),u_texsize:i.imageAtlasTexture.size,u_ratio:r/t.aC(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},Hi=(e,i,o,r,a,s)=>{const n=e.lineAtlas,l=Xi(i,e.transform),c="round"===o.layout.get("line-cap"),h=n.getDash(a.from,c),u=n.getDash(a.to,c),d=h.width*s.fromScale,_=u.width*s.toScale;return t.e($i(e,i,o,r),{u_patternscale_a:[l/d,-h.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*e.pixelRatio)/2,u_image:0,u_tex_y_a:h.y,u_tex_y_b:u.y,u_mix:s.t})};function Xi(e,i){return 1/t.aC(e,1,i.tileZoom)}function Ki(e,i,o){return t.aD(e.transform,i,o.paint.get("line-translate"),o.paint.get("line-translate-anchor"))}const Yi=(e,t,i,o,r)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*o.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:o.paint.get("raster-brightness-min"),u_brightness_high:o.paint.get("raster-brightness-max"),u_saturation_factor:(s=o.paint.get("raster-saturation"),s>0?1-1/(1.001-s):-s),u_contrast_factor:(a=o.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Qi(o.paint.get("raster-hue-rotate")),u_coords_top:[r[0].x,r[0].y,r[1].x,r[1].y],u_coords_bottom:[r[3].x,r[3].y,r[2].x,r[2].y]};var a,s;};function Qi(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const Ji=(e,t,i,o,r,a,s,n,l,c,h,u,d)=>{const _=s.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+o,u_is_along_line:r,u_is_variable_anchor:a,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},eo=(e,i,o,r,a,s,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.e(Ji(e,i,o,r,a,s,n,l,c,h,u,d,p),{u_gamma_scale:r?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:1})},to=(e,i,o,r,a,s,n,l,c,h,u,d,_)=>t.e(eo(e,i,o,r,a,s,n,l,c,h,!0,u,0,_),{u_texsize_icon:d,u_texture_icon:1}),io=(e,t)=>({u_opacity:e,u_color:t}),oo=(e,i,o,r,a)=>t.e(function(e,i,o,r){const a=o.imageManager.getPattern(e.from.toString()),s=o.imageManager.getPattern(e.to.toString()),{width:n,height:l}=o.imageManager.getPixelSize(),c=Math.pow(2,r.tileID.overscaledZ),h=r.tileSize*Math.pow(2,o.transform.tileZoom)/c,u=h*(r.tileID.canonical.x+r.tileID.wrap*c),d=h*r.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:s.tl,u_pattern_br_b:s.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:s.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.aC(r,1,o.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(o,a,i,r),{u_opacity:e}),ro=(e,t)=>{},ao={fillExtrusion:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_height_factor:new t.bg(e,i.u_height_factor),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.bU(e,i.u_world),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_scale_with_map:new t.bP(e,i.u_scale_with_map),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_extrude_scale:new t.bU(e,i.u_extrude_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale),u_translate:new t.bU(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.bU(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.bU(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.bQ(e,i.u_color),u_overlay:new t.bP(e,i.u_overlay),u_overlay_scale:new t.bg(e,i.u_overlay_scale)}),depth:ro,clippingMask:ro,heatmap:(e,i)=>({u_extrude_scale:new t.bg(e,i.u_extrude_scale),u_intensity:new t.bg(e,i.u_intensity),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_color_ramp:new t.bP(e,i.u_color_ramp),u_opacity:new t.bg(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.bP(e,i.u_image),u_latrange:new t.bU(e,i.u_latrange),u_exaggeration:new t.bg(e,i.u_exaggeration),u_altitudes:new t.b_(e,i.u_altitudes),u_azimuths:new t.b_(e,i.u_azimuths),u_accent:new t.bQ(e,i.u_accent),u_method:new t.bP(e,i.u_method),u_shadows:new t.bZ(e,i.u_shadows),u_highlights:new t.bZ(e,i.u_highlights)}),hillshadePrepare:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_image:new t.bP(e,i.u_image),u_dimension:new t.bU(e,i.u_dimension),u_zoom:new t.bg(e,i.u_zoom),u_unpack:new t.bS(e,i.u_unpack)}),colorRelief:(e,i)=>({u_image:new t.bP(e,i.u_image),u_unpack:new t.bS(e,i.u_unpack),u_dimension:new t.bU(e,i.u_dimension),u_elevation_stops:new t.bP(e,i.u_elevation_stops),u_color_stops:new t.bP(e,i.u_color_stops),u_color_ramp_size:new t.bP(e,i.u_color_ramp_size),u_opacity:new t.bg(e,i.u_opacity)}),line:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_image:new t.bP(e,i.u_image),u_image_height:new t.bg(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_texsize:new t.bU(e,i.u_texsize),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_image:new t.bP(e,i.u_image),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_patternscale_a:new t.bU(e,i.u_patternscale_a),u_patternscale_b:new t.bU(e,i.u_patternscale_b),u_sdfgamma:new t.bg(e,i.u_sdfgamma),u_image:new t.bP(e,i.u_image),u_tex_y_a:new t.bg(e,i.u_tex_y_a),u_tex_y_b:new t.bg(e,i.u_tex_y_b),u_mix:new t.bg(e,i.u_mix)}),raster:(e,i)=>({u_tl_parent:new t.bU(e,i.u_tl_parent),u_scale_parent:new t.bg(e,i.u_scale_parent),u_buffer_scale:new t.bg(e,i.u_buffer_scale),u_fade_t:new t.bg(e,i.u_fade_t),u_opacity:new t.bg(e,i.u_opacity),u_image0:new t.bP(e,i.u_image0),u_image1:new t.bP(e,i.u_image1),u_brightness_low:new t.bg(e,i.u_brightness_low),u_brightness_high:new t.bg(e,i.u_brightness_high),u_saturation_factor:new t.bg(e,i.u_saturation_factor),u_contrast_factor:new t.bg(e,i.u_contrast_factor),u_spin_weights:new t.bT(e,i.u_spin_weights),u_coords_top:new t.bS(e,i.u_coords_top),u_coords_bottom:new t.bS(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texsize_icon:new t.bU(e,i.u_texsize_icon),u_texture:new t.bP(e,i.u_texture),u_texture_icon:new t.bP(e,i.u_texture_icon),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_color:new t.bQ(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_image:new t.bP(e,i.u_image),u_pattern_tl_a:new t.bU(e,i.u_pattern_tl_a),u_pattern_br_a:new t.bU(e,i.u_pattern_br_a),u_pattern_tl_b:new t.bU(e,i.u_pattern_tl_b),u_pattern_br_b:new t.bU(e,i.u_pattern_br_b),u_texsize:new t.bU(e,i.u_texsize),u_mix:new t.bg(e,i.u_mix),u_pattern_size_a:new t.bU(e,i.u_pattern_size_a),u_pattern_size_b:new t.bU(e,i.u_pattern_size_b),u_scale_a:new t.bg(e,i.u_scale_a),u_scale_b:new t.bg(e,i.u_scale_b),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.bg(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_ele_delta:new t.bg(e,i.u_ele_delta),u_fog_matrix:new t.bR(e,i.u_fog_matrix),u_fog_color:new t.bQ(e,i.u_fog_color),u_fog_ground_blend:new t.bg(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.bg(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon_fog_blend:new t.bg(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.bg(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.bg(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_terrain_coords_id:new t.bg(e,i.u_terrain_coords_id),u_ele_delta:new t.bg(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.bg(e,i.u_input),u_output_expected:new t.bg(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.bT(e,i.u_sun_pos),u_atmosphere_blend:new t.bg(e,i.u_atmosphere_blend),u_globe_position:new t.bT(e,i.u_globe_position),u_globe_radius:new t.bg(e,i.u_globe_radius),u_inv_proj_matrix:new t.bR(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.bQ(e,i.u_sky_color),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon:new t.bU(e,i.u_horizon),u_horizon_normal:new t.bU(e,i.u_horizon_normal),u_sky_horizon_blend:new t.bg(e,i.u_sky_horizon_blend),u_sky_blend:new t.bg(e,i.u_sky_blend)})};class so{constructor(e,t,i){this.context=e;const o=e.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const no={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class lo{constructor(e,t,i,o){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=o,this.context=e;const r=e.gl;this.buffer=r.createBuffer(),e.bindVertexBuffer.set(this.buffer),r.bufferData(r.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(s,l.LINES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Fi(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),o.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!a||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.b$;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:S,angle:E});}else $e(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===o.layout.get("text-rotation-alignment");De(c,e,a,O,j,v,h,i,l.toUnwrapped(),f.width,f.height,U,t);}const $=a&&P||V,q=b||$?Yo:v?O:e.transform.clipSpaceToPixelsMatrix,W=p&&0!==o.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1);let H;H=p?c.iconsInText?to(T.kind,E,x,v,b,$,e,q,N,U,z,k,I):eo(T.kind,E,x,v,b,$,e,q,N,U,a,z,0,I):Ji(T.kind,E,x,v,b,$,e,q,N,U,a,z,I);const X={program:S,buffers:u,uniformValues:H,projectionData:Z,atlasTexture:D,atlasTextureIcon:F,atlasInterpolation:A,atlasInterpolationIcon:L,isSDF:p,hasHalo:W};if(y&&c.canOverlap){w=!0;const e=u.segments.get();for(const i of e)C.push({segments:new t.aM([i]),sortKey:i.sortKey,state:X,terrainData:R});}else C.push({segments:u.segments,sortKey:0,state:X,terrainData:R});}w&&C.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of C){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const r=i.uniformValues;i.hasHalo&&(r.u_is_halo=1,or(i.buffers,t.segments,o,e,i.program,T,u,d,r,i.projectionData,t.terrainData)),r.u_is_halo=0;}or(i.buffers,t.segments,o,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function or(e,t,i,o,r,a,s,n,l,c,h){const u=o.context;r.draw(u,u.gl.TRIANGLES,a,s,n,Ut.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,o.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function rr(e,i,o,r,a){const s=e.context,n=s.gl,l=Vt.disabled,c=new jt([n.ONE,n.ONE],t.bf.transparent,[!0,!0,!0,!0]),h=i.getBucket(o);if(!h)return;const u=r.key;let d=o.heatmapFbos.get(u);d||(d=sr(s,i.tileSize,i.tileSize),o.heatmapFbos.set(u,d)),s.bindFramebuffer.set(d.framebuffer),s.viewport.set([0,0,i.tileSize,i.tileSize]),s.clear({color:t.bf.transparent});const _=h.programConfigurations.get(o.id),p=e.useProgram("heatmap",_,!a),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),f=e.style.map.terrain.getTerrainData(r);p.draw(s,n.TRIANGLES,Zt.disabled,l,c,Ut.disabled,ji(i,e.transform.zoom,o.paint.get("heatmap-intensity"),1),f,m,o.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,o.paint,e.transform.zoom,_);}function ar(e,t,i,o,r){const a=e.context,s=a.gl,n=e.transform;a.setColorMode(e.colorModeForRenderPass());const l=nr(a,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,h.colorAttachment.get()),a.activeTexture.set(s.TEXTURE1),l.bind(s.LINEAR,s.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:r,applyGlobeMatrix:!o});e.useProgram("heatmapTexture").draw(a,s.TRIANGLES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Ni(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function sr(e,t,i){var o,r;const a=e.gl,s=a.createTexture();a.bindTexture(a.TEXTURE_2D,s),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR);const n=null!==(o=e.HALF_FLOAT)&&void 0!==o?o:a.UNSIGNED_BYTE,l=null!==(r=e.RGBA16F)&&void 0!==r?r:a.RGBA;a.texImage2D(a.TEXTURE_2D,0,l,t,i,0,a.RGBA,n,null);const c=e.createFramebuffer(t,i,!1,!1);return c.colorAttachment.set(s),c}function nr(e,i){return i.colorRampTexture||(i.colorRampTexture=new t.T(e,i.colorRamp,e.gl.RGBA)),i.colorRampTexture}function lr(e,t,i,o,r){if(!i||!o||!o.imageAtlas)return;const a=o.imageAtlas.patternPositions;let s=a[i.to.toString()],n=a[i.from.toString()];if(!s&&n&&(s=n),!n&&s&&(n=s),!s||!n){const e=r.getPaintProperty(t);s=a[e],n=a[e];}s&&n&&e.setConstantPatternPositions(s,n);}function cr(e,i,o,r,a,s,n,l){const c=e.context.gl,h="fill-pattern",u=o.paint.get(h),d=u&&u.constantOr(1),_=o.getCrossfadeParameters();let p,m,f,g,v;const b=e.transform,x=o.paint.get("fill-translate"),y=o.paint.get("fill-translate-anchor");n?(m=d&&!o.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",p=c.LINES):(m=d?"fillPattern":"fill",p=c.TRIANGLES);const w=u.constantOr(null);for(const u of r){const r=i.getTile(u);if(d&&!r.patternsLoaded())continue;const T=r.getBucket(o);if(!T)continue;const P=T.programConfigurations.get(o.id),C=e.useProgram(m,P),I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(u);d&&(e.context.activeTexture.set(c.TEXTURE0),r.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),P.updatePaintBuffers(_)),lr(P,h,w,r,o);const M=b.getProjectionData({overscaledTileID:u,applyGlobeMatrix:!l,applyTerrainMatrix:!0}),S=t.aD(b,r,x,y);if(n){g=T.indexBuffer2,v=T.segments2;const t=[c.drawingBufferWidth,c.drawingBufferHeight];f="fillOutlinePattern"===m&&d?Li(e,_,r,t,S):Ai(t,S);}else g=T.indexBuffer,v=T.segments,f=d?Di(e,_,r,S):{u_fill_translate:S};const E=e.stencilModeForClipping(u);C.draw(e.context,p,a,E,s,Ut.backCCW,f,I,M,o.id,T.layoutVertexBuffer,g,v,o.paint,e.transform.zoom,P);}}function hr(e,i,o,r,a,s,n,l){const c=e.context,h=c.gl,u="fill-extrusion-pattern",d=o.paint.get(u),_=d.constantOr(1),p=o.getCrossfadeParameters(),m=o.paint.get("fill-extrusion-opacity"),f=d.constantOr(null),g=e.transform;for(const d of r){const r=i.getTile(d),v=r.getBucket(o);if(!v)continue;const b=e.style.map.terrain&&e.style.map.terrain.getTerrainData(d),x=v.programConfigurations.get(o.id),y=e.useProgram(_?"fillExtrusionPattern":"fillExtrusion",x);_&&(e.context.activeTexture.set(h.TEXTURE0),r.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),x.updatePaintBuffers(p));const w=g.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!l,applyTerrainMatrix:!0});lr(x,u,f,r,o);const T=t.aD(g,r,o.paint.get("fill-extrusion-translate"),o.paint.get("fill-extrusion-translate-anchor")),P=o.paint.get("fill-extrusion-vertical-gradient"),C=_?zi(e,P,m,T,d,p,r):Ri(e,P,m,T);y.draw(c,c.gl.TRIANGLES,a,s,n,Ut.backCCW,C,b,w,o.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,o.paint,e.transform.zoom,x,e.style.map.terrain&&v.centroidVertexBuffer);}}function ur(e,t,i,o,r,a,s,n,l){var c;const h=e.style.projection,u=e.context,d=e.transform,_=u.gl,p=[`#define NUM_ILLUMINATION_SOURCES ${i.paint.get("hillshade-highlight-color").values.length}`],m=e.useProgram("hillshade",null,!1,p),f=!e.options.moving;for(const p of o){const o=t.getTile(p),g=o.fbo;if(!g)continue;const v=h.getMeshFromTileID(u,p.canonical,n,!0,"raster"),b=null===(c=e.style.map.terrain)||void 0===c?void 0:c.getTerrainData(p);u.activeTexture.set(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g.colorAttachment.get());const x=d.getProjectionData({overscaledTileID:p,aligned:f,applyGlobeMatrix:!l,applyTerrainMatrix:!0});m.draw(u,_.TRIANGLES,a,r[p.overscaledZ],s,Ut.backCCW,Ui(e,o,i),b,x,i.id,v.vertexBuffer,v.indexBuffer,v.segments);}}function dr(e,i,o,r,a,s,n,l,c){var h;const u=e.style.projection,d=e.context,_=e.transform,p=d.gl,m=e.useProgram("colorRelief"),f=!e.options.moving;let g=!0,v=0;for(const b of r){const r=i.getTile(b),x=r.dem;if(g){const e=p.getParameter(p.MAX_TEXTURE_SIZE),{elevationTexture:t,colorTexture:i}=o.getColorRampTextures(d,e,x.getUnpackVector());d.activeTexture.set(p.TEXTURE1),t.bind(p.NEAREST,p.CLAMP_TO_EDGE),d.activeTexture.set(p.TEXTURE4),i.bind(p.LINEAR,p.CLAMP_TO_EDGE),g=!1,v=t.size[0];}if(!x||!x.data)continue;const y=x.stride,w=x.getPixels();if(d.activeTexture.set(p.TEXTURE0),d.pixelStoreUnpackPremultiplyAlpha.set(!1),r.demTexture=r.demTexture||e.getTileTexture(y),r.demTexture){const e=r.demTexture;e.update(w,{premultiply:!1}),e.bind(p.LINEAR,p.CLAMP_TO_EDGE);}else r.demTexture=new t.T(d,w,p.RGBA,{premultiply:!1}),r.demTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE);const T=u.getMeshFromTileID(d,b.canonical,l,!0,"raster"),P=null===(h=e.style.map.terrain)||void 0===h?void 0:h.getTerrainData(b),C=_.getProjectionData({overscaledTileID:b,aligned:f,applyGlobeMatrix:!c,applyTerrainMatrix:!0});m.draw(d,p.TRIANGLES,s,a[b.overscaledZ],n,Ut.backCCW,Vi(o,r.dem,v),P,C,o.id,T.vertexBuffer,T.indexBuffer,T.segments);}}const _r=[new t.P(0,0),new t.P(t.$,0),new t.P(t.$,t.$),new t.P(0,t.$)];function pr(e,t,i,o,r,a,s,n,l=!1,c=!1){const h=o[o.length-1].overscaledZ,u=e.context,d=u.gl,_=e.useProgram("raster"),p=e.transform,m=e.style.projection,f=e.colorModeForRenderPass(),g=!e.options.moving;for(const v of o){const o=e.getDepthModeForSublayer(v.overscaledZ-h,1===i.paint.get("raster-opacity")?Zt.ReadWrite:Zt.ReadOnly,d.LESS),b=t.getTile(v);b.registerFadeDuration(i.paint.get("raster-fade-duration"));const x=t.findLoadedParent(v,0),y=t.findLoadedSibling(v),w=mr(b,x||y||null,t,i,e.transform,e.style.map.terrain);let T,P;const C="nearest"===i.paint.get("raster-resampling")?d.NEAREST:d.LINEAR;u.activeTexture.set(d.TEXTURE0),b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),u.activeTexture.set(d.TEXTURE1),x?(x.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),T=Math.pow(2,x.tileID.overscaledZ-b.tileID.overscaledZ),P=[b.tileID.canonical.x*T%1,b.tileID.canonical.y*T%1]):b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),b.texture.useMipmap&&u.extTextureFilterAnisotropic&&e.transform.pitch>20&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(v),M=p.getProjectionData({overscaledTileID:v,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),S=Yi(P||[0,0],T||1,w,i,n),E=m.getMeshFromTileID(u,v.canonical,a,s,"raster");_.draw(u,d.TRIANGLES,o,r?r[v.overscaledZ]:Vt.disabled,f,l?Ut.frontCCW:Ut.backCCW,S,I,M,i.id,E.vertexBuffer,E.indexBuffer,E.segments);}}function mr(e,i,o,r,a,n){const l=r.paint.get("raster-fade-duration");if(!n&&l>0){const r=s.now(),n=(r-e.timeAdded)/l,c=i?(r-i.timeAdded)/l:-1,h=o.getSource(),u=ge(a,{tileSize:h.tileSize,roundZoom:h.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-u)>Math.abs(e.tileID.overscaledZ-u),_=d&&e.refreshedUponExpiration?1:t.ah(d?n:1-c,0,1);return e.refreshedUponExpiration&&n>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-_}:{opacity:_,mix:0}}return {opacity:1,mix:0}}const fr=new t.bf(1,0,0,1),gr=new t.bf(0,1,0,1),vr=new t.bf(0,0,1,1),br=new t.bf(1,0,1,1),xr=new t.bf(0,1,1,1);function yr(e,t,i,o){Tr(e,0,t+i/2,e.transform.width,i,o);}function wr(e,t,i,o){Tr(e,t-i/2,0,i,e.transform.height,o);}function Tr(e,t,i,o,r,a){const s=e.context,n=s.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,o*e.pixelRatio,r*e.pixelRatio),s.clear({color:a}),n.disable(n.SCISSOR_TEST);}function Pr(e,i,o){const r=e.context,a=r.gl,s=e.useProgram("debug"),n=Zt.disabled,l=Vt.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(o);r.activeTexture.set(a.TEXTURE0);const d=i.getTileByID(o.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(o).tileSize,m=512/Math.min(p,512)*(o.overscaledZ/e.transform.zoom)*.5;let f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=` => ${o.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,o=e.context.gl,r=e.debugOverlayCanvas.getContext("2d");r.clearRect(0,0,i.width,i.height),r.shadowColor="white",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle="white",r.textBaseline="top",r.font="bold 36px Open Sans, sans-serif",r.fillText(t,5,5),r.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:o,applyGlobeMatrix:!0,applyTerrainMatrix:!0});s.draw(r,a.TRIANGLES,n,l,jt.alphaBlended,Ut.disabled,Oi(t.bf.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),s.draw(r,a.LINE_STRIP,n,l,c,Ut.disabled,Oi(t.bf.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function Cr(e,t,i,o){const{isRenderingGlobe:r}=o,a=e.context,s=a.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain");a.bindFramebuffer.set(null),a.viewport.set([0,0,e.width,e.height]);for(const o of i){const i=t.getTerrainMesh(o.tileID),u=e.renderToTexture.getTexture(o),d=t.getTerrainData(o.tileID);a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,u.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(o.tileID.toUnwrapped()),m=Ci(_,p,e.style.sky,n.pitch,r),f=n.getProjectionData({overscaledTileID:o.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});h.draw(a,s.TRIANGLES,c,Vt.disabled,l,Ut.backCCW,m,d,f,"terrain",i.vertexBuffer,i.indexBuffer,i.segments);}}function Ir(e,i){if(!i.mesh){const o=new t.aL;o.emplaceBack(-1,-1),o.emplaceBack(1,-1),o.emplaceBack(1,1),o.emplaceBack(-1,1);const r=new t.aN;r.emplaceBack(0,1,2),r.emplaceBack(0,2,3),i.mesh=new wt(e.createVertexBuffer(o,Tt.members),e.createIndexBuffer(r),t.aM.simpleSegment(0,0,o.length,r.length));}return i.mesh}class Mr{constructor(e,i){this.context=new Ho(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:t.ag(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=xe.maxUnderzooming+xe.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new vt;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.aL;i.emplaceBack(0,0),i.emplaceBack(t.$,0),i.emplaceBack(0,t.$),i.emplaceBack(t.$,t.$),this.tileExtentBuffer=e.createVertexBuffer(i,Tt.members),this.tileExtentSegments=t.aM.simpleSegment(0,0,4,2);const o=new t.aL;o.emplaceBack(0,0),o.emplaceBack(t.$,0),o.emplaceBack(0,t.$),o.emplaceBack(t.$,t.$),this.debugBuffer=e.createVertexBuffer(o,Tt.members),this.debugSegments=t.aM.simpleSegment(0,0,4,5);const r=new t.c6;r.emplaceBack(0,0,0,0),r.emplaceBack(t.$,0,t.$,0),r.emplaceBack(0,t.$,0,t.$),r.emplaceBack(t.$,t.$,t.$,t.$),this.rasterBoundsBuffer=e.createVertexBuffer(r,Ti.members),this.rasterBoundsSegments=t.aM.simpleSegment(0,0,4,2);const a=new t.aL;a.emplaceBack(0,0),a.emplaceBack(t.$,0),a.emplaceBack(0,t.$),a.emplaceBack(t.$,t.$),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(a,Tt.members),this.rasterBoundsSegmentsPosOnly=t.aM.simpleSegment(0,0,4,5);const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(1,0),s.emplaceBack(0,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,Tt.members),this.viewportSegments=t.aM.simpleSegment(0,0,4,2);const n=new t.c7;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.aN;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new Vt({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new wt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const o=t.L();t.bY(o,0,this.width,this.height,0,0,1),t.N(o,o,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const r={mainMatrix:o,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:o};this.useProgram("clippingMask",null,!0).draw(e,i.TRIANGLES,Zt.disabled,this.stencilClearMode,jt.disabled,Ut.disabled,null,null,r,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const o=this.context;o.setColorMode(jt.disabled),o.setDepthMode(Zt.disabled);const r={};for(const e of t)r[e.key]=this.nextStencilID++;this._renderTileMasks(r,t,i,!0),this._renderTileMasks(r,t,i,!1),this._tileClippingMaskIDs=r;}_renderTileMasks(e,t,i,o){const r=this.context,a=r.gl,s=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=s.getMeshFromTileID(this.context,c.canonical,o,!0,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!i,applyTerrainMatrix:!0});l.draw(r,a.TRIANGLES,Zt.disabled,new Vt({func:a.ALWAYS,mask:0},t,255,a.KEEP,a.KEEP,a.REPLACE),jt.disabled,i?Ut.disabled:Ut.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,o=this.transform,r=this.useProgram("depth"),a=this.getDepthModeFor3D(),s=ve(o,{tileSize:o.tileSize});for(const n of s){const s=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,!0,!0,"raster"),c=o.getProjectionData({overscaledTileID:n,applyGlobeMatrix:!0,applyTerrainMatrix:!0});r.draw(e,t.TRIANGLES,a,Vt.disabled,jt.disabled,Ut.backCCW,null,s,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new Vt({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new Vt({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(r>1){this.currentStencilSource=void 0,this.nextStencilID+r>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(this.clearStencil(),r>1){const e={},a={};for(let i=0;i0};for(const e in n){const t=n[e];t.used&&t.prepare(this.context),l[e]=t.getVisibleCoordinates(!1),c[e]=l[e].slice().reverse(),h[e]=t.getVisibleCoordinates(!0).reverse();}this.opaquePassCutoff=1/0;for(let e=0;ethis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.bf.black:t.bf.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,o=i.gl,r=((e,t,i)=>{const o=Math.cos(t.rollInRadians),r=Math.sin(t.rollInRadians),a=he(t),s=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-a*r)*i,(t.height/2+a*o)*i],u_horizon_normal:[-r,o],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:s}})(t,e.style.map.transform,e.pixelRatio),a=new Zt(o.LEQUAL,Zt.ReadWrite,[0,1]),s=Vt.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=Ir(i,t);l.draw(i,o.TRIANGLES,a,s,n,Ut.disabled,r,null,void 0,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=a.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[a[this.currentLayer]],t=n[e.source],i=l[e.source];this._renderTileClippingMasks(e,i,!1),this.renderLayer(this,t,e,i,u);}this.renderPass="translucent";let d=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:o,u_inv_proj_matrix:r}))(c,u,[p[0],p[1],p[2]],d,_),f=Ir(r,i);s.draw(r,a.TRIANGLES,n,Vt.disabled,jt.alphaBlended,Ut.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const o=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.sourceCaches[i.source]]:[])),r=o.filter((e=>"vector"===e.getSource().type)),a=o.filter((e=>"vector"!==e.getSource().type)),s=e=>{(!i||i.getSource().maxzooms(e))),i||a.forEach((e=>s(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let o=0;ou.getElevation(a,e,t):null;er(s,d,_,c,h,f,i,p,g,t.aD(h,e,n,l),a.toUnwrapped(),o);}}}(r,e,o,i,o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),a),0!==o.paint.get("icon-opacity").constantOr(1)&&ir(e,i,o,r,!1,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),o.layout.get("icon-rotation-alignment"),o.layout.get("icon-pitch-alignment"),o.layout.get("icon-keep-upright"),l,c,n),0!==o.paint.get("text-opacity").constantOr(1)&&ir(e,i,o,r,!0,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&(Ko(e,i,o,r,!0),Ko(e,i,o,r,!1));}(e,i,o,r,this.style.placement.variableOffsets,a):t.cc(o)?function(e,i,o,r,a){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:s}=a,n=o.paint.get("circle-opacity"),l=o.paint.get("circle-stroke-width"),c=o.paint.get("circle-stroke-opacity"),h=!o.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Zt.ReadOnly),m=Vt.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let a=0;ae.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:r,layoutVertexBuffer:a,indexBuffer:s,uniformValues:n,terrainData:l,projectionData:c}=t.state;r.draw(u,d.TRIANGLES,p,m,f,Ut.backCCW,n,l,c,o.id,a,s,t.segments,o.paint,e.transform.zoom,i);}}(e,i,o,r,a):t.cd(o)?function(e,i,o,r,a){if(0===o.paint.get("heatmap-opacity"))return;const s=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=a;if(e.style.map.terrain){for(const t of r){const r=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?rr(e,r,o,t,l):"translucent"===e.renderPass&&ar(e,o,t,n,l));}s.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,o,r){const a=e.context,s=a.gl,n=e.transform,l=Vt.disabled,c=new jt([s.ONE,s.ONE],t.bf.transparent,[!0,!0,!0,!0]);((function(e,i,o){const r=e.gl;e.activeTexture.set(r.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let a=o.heatmapFbos.get(t.c2);a?(r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer)):(a=sr(e,i.width/4,i.height/4),o.heatmapFbos.set(t.c2,a));}))(a,e,o),a.clear({color:t.bf.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return !1;if(!e.from||!e.to)return !0;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=!1,o=[]){this.cache=this.cache||{};const r=!!this.style.map.terrain,a=this.style.projection,s=i?xt.projectionMercator:a.shaderPreludeCode,n=i?Pt:a.shaderDefine,l=e+(t?t.cacheKey:"")+`/${i?Ct:a.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(r?"/terrain":"")+(o?`/${o.join("/")}`:"");return this.cache[l]||(this.cache[l]=new Si(this.context,xt[e],t,ao[e],this._showOverdrawInspector,r,s,n,o)),this.cache[l]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Sr(e,t){let i,o=!1,r=null,a=null;const s=()=>{r=null,o&&(e.apply(a,i),r=setTimeout(s,t),o=!1);};return (...e)=>(o=!0,a=this,i=e,r||s(),r)}class Er{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(!this._isValidHash(e))return !1;const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let o=window.location.hash.replace(i,"");o.startsWith("#&")?o=o.slice(0,1)+o.slice(2):"#"===o&&(o="");let r=window.location.href.replace(/(#.+)?$/,o);r=r.replace("&&","&"),window.history.replaceState(window.history.state,null,r);},this._updateHash=Sr(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,o=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),r=Math.pow(10,o),a=Math.round(t.lng*r)/r,s=Math.round(t.lat*r)/r,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${a}/${s}/${i}`:`${i}/${s}/${a}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const o=i.split("=")[0];return o===e?(t=!0,`${o}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return !1;try{new t.S(+e[2],+e[1]);}catch(e){return !1}const i=+e[0],o=+(e[3]||0),r=+(e[4]||0);return i>=this._map.getMinZoom()&&i<=this._map.getMaxZoom()&&o>=-180&&o<=180&&r>=this._map.getMinPitch()&&r<=this._map.getMaxPitch()}}const Rr={linearity:.3,easing:t.cm(0,0,.3,1)},zr=t.e({deceleration:2500,maxSpeed:1400},Rr),Dr=t.e({deceleration:20,maxSpeed:1400},Rr),Ar=t.e({deceleration:1e3,maxSpeed:360},Rr),Lr=t.e({deceleration:1e3,maxSpeed:90},Rr),kr=t.e({deceleration:1e3,maxSpeed:360},Rr);class Fr{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:s.now(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=s.now();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const o=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,r={};if(i.pan.mag()){const a=Or(i.pan.mag(),o,t.e({},zr,e||{})),s=i.pan.mult(a.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(s,this._map.transform);r.center=n.easingCenter,r.offset=n.easingOffset,Br(r,a);}if(i.zoom){const e=Or(i.zoom,o,Dr);r.zoom=this._map.transform.zoom+e.amount,Br(r,e);}if(i.bearing){const e=Or(i.bearing,o,Ar);r.bearing=this._map.transform.bearing+t.ah(e.amount,-179,179),Br(r,e);}if(i.pitch){const e=Or(i.pitch,o,Lr);r.pitch=this._map.transform.pitch+e.amount,Br(r,e);}if(i.roll){const e=Or(i.roll,o,kr);r.roll=this._map.transform.roll+t.ah(e.amount,-179,179),Br(r,e);}if(r.zoom||r.bearing){const e=void 0===i.pinchAround?i.around:i.pinchAround;r.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.e(r,{noMoveStart:!0})}}function Br(e,t){(!e.duration||e.durationi.unproject(e))),l=a.reduce(((e,t,i,o)=>e.add(t.div(o.length))),new t.P(0,0));super(e,{points:a,point:l,lngLats:s,lngLat:i.unproject(l),originalEvent:o}),this._defaultPrevented=!1;}}class Ur extends t.l{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=!1;}}class Zr{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new Ur(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new jr(e.type,this._map,e))}mouseup(e){this._map.fire(new jr(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new jr(e.type,this._map,e));}dblclick(e){return this._firePreventable(new jr(e.type,this._map,e))}mouseover(e){this._map.fire(new jr(e.type,this._map,e));}mouseout(e){this._map.fire(new jr(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Nr(e.type,this._map,e))}touchmove(e){this._map.fire(new Nr(e.type,this._map,e));}touchend(e){this._map.fire(new Nr(e.type,this._map,e));}touchcancel(e){this._map.fire(new Nr(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Gr{constructor(e){this._map=e;}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new jr(e.type,this._map,e));}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new jr("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new jr(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Vr{constructor(e){this._map=e;}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return {lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class $r{constructor(e,t){this._map=e,this._tr=new Vr(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(n.disableDrag(),this._startPos=this._lastPos=t,this._active=!0);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(o,r,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.l(e,{originalEvent:i}))}}function qr(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let o=0;othis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){const i=new t.P(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=qr(o,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const o=qr(i,t);for(const e in this.touches){const t=o[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Hr{constructor(e){this.singleTap=new Wr(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const o=this.singleTap.touchend(e,t,i);if(o){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(o)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}}}class Xr{constructor(e){this._tr=new Vr(e),this._zoomIn=new Hr({numTouches:1,numTaps:2}),this._zoomOut=new Hr({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const o=this._zoomIn.touchend(e,t,i),r=this._zoomOut.touchend(e,t,i),a=this._tr;return o?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom+1,around:a.unproject(o)},{originalEvent:e})}):r?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom-1,around:a.unproject(r)},{originalEvent:e})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class Kr{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0));}dragMove(e,t){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const o=Array.isArray(t)?t[0]:t;return !this._moved&&o.dist(i)!0}),t=new ta){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t;}_executeRelevantHandler(e,t,i){return e instanceof MouseEvent?t(e):"undefined"!=typeof TouchEvent&&e instanceof TouchEvent?i(e):void 0}startMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.startMove(e)),(e=>this.oneFingerTouchMoveStateManager.startMove(e)));}endMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.endMove(e)),(e=>this.oneFingerTouchMoveStateManager.endMove(e)));}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}const oa=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};class ra{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=!1,this._touches={},this._sum=new t.P(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,o){o.length>0&&(this._active=!0);const r=qr(o,i),a=new t.P(0,0),s=new t.P(0,0);let n=0;for(const e in r){const t=r[e],i=this._touches[e];i&&(a._add(t),s._add(t.sub(i)),n++,r[e]=t);}if(this._touches=r,this._shouldBePrevented(n)||!s.mag())return;const l=s.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class da extends aa{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,ua(e[0].sub(e[1]))&&(this._valid=!1);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const o=e[0].sub(this._lastPoints[0]),r=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const o=e.mag()>=2,r=t.mag()>=2;if(!o&&!r)return;if(!o||!r)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const a=e.y>0==t.y>0;return ua(e)&&ua(t)&&a}}const _a={panStep:100,bearingStep:15,pitchStep:10};class pa{constructor(e){this._tr=new Vr(e);const t=_a;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1;}reset(){this._active=!1;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,o=0,r=0,a=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),r=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),r=1);break;case 38:e.shiftKey?o=1:(e.preventDefault(),a=-1);break;case 40:e.shiftKey?o=-1:(e.preventDefault(),a=1);break;default:return}return this._rotationDisabled&&(i=0,o=0),{cameraAnimation:s=>{const n=this._tr;s.easeTo({duration:300,easeId:"keyboardHandler",easing:ma,zoom:t?Math.round(n.zoom)+t*(e.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+o*this._pitchStep,offset:[-r*this._panStep,-a*this._panStep],center:n.center},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function ma(e){return e*(2-e)}const fa=4.000244140625,ga=1/450;class va{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new Vr(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=ga;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=!1);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=s.now(),o=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%fa==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":o>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(o*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=n.mousePos(this._map.getCanvas(),e),o=this._tr;this._aroundPoint=this._aroundCenter?o.transform.locationToScreenPoint(t.S.convert(o.center)):i,this._frameId||(this._frameId=!0,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>fa?this._wheelZoomRate:this._defaultZoomRate;let o=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==o&&(o=1/o);const r="number"!=typeof this._targetZoom?e.scale:t.af(this._targetZoom);this._targetZoom=e.getConstrained(e.getCameraLngLat(),t.ak(r*o)).zoom,"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,o=this._startZoom,r=this._easing;let a,n=!1;if("wheel"===this._type&&o&&r){const e=s.now()-this._lastWheelEventTime,l=Math.min((e+5)/200,1),c=r(l);a=t.C.number(o,i,c),l<1?this._frameId||(this._frameId=!0):n=!0;}else a=i,n=!0;return this._active=!0,n&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=a,{noInertia:!0,needsRenderFrame:!n,zoomDelta:a-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.co;if(this._prevEase){const e=this._prevEase,o=(s.now()-e.start)/e.duration,r=e.easing(o+.01)-e.easing(o),a=.27/Math.sqrt(r*r+1e-4)*.01,n=Math.sqrt(.0729-a*a);i=t.cm(a,n,.25,1);}return this._prevEase={start:s.now(),duration:e,easing:i},i}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class ba{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class xa{constructor(e){this._tr=new Vr(e),this.reset();}reset(){this._active=!1;}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ya{constructor(){this._tap=new Hr({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const o=t[0],r=e.timeStamp-this._tapTime<500,a=this._tapPoint.dist(o)<30;r&&a?i.length>0&&(this._swipePoint=o,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const o=t[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,e.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const o=this._tap.touchend(e,t,i);o&&(this._tapTime=e.timeStamp,this._tapPoint=o);}}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class wa{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Ta{constructor(e,t,i,o){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=o;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Pa{constructor(e,t,i,o){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class Ca{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=!1;}isActive(){return !1}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=n.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),o=document.createElement("div");o.className="maplibregl-desktop-message",o.textContent=t,this._container.appendChild(o);const r=document.createElement("div");r.className="maplibregl-mobile-message",r.textContent=i,this._container.appendChild(r),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(n.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=!0;}disable(){this._enabled=!1,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.l("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const Ia=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Ma extends t.l{}function Sa(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class Ea{constructor(e,i){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,i)=>{if("blur"===e.type)return void this.stop(!0);this._updatingCamera=!0;const o="renderFrame"===e.type?void 0:e,r={needsRenderFrame:!1},a={},s={};for(const{handlerName:l,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let u;if(this._blockedByActive(s,h,l))c.reset();else if(c[i||e.type]){if(t.cp(e,i||e.type)){const t=n.mousePos(this._map.getCanvas(),e);u=c[i||e.type](e,t);}else if(t.cq(e,i||e.type)){const t=this._getMapTouches(e.touches),o=n.touchPos(this._map.getCanvas(),t);u=c[i||e.type](e,o,t);}else t.cr(i||e.type)||(u=c[i||e.type](e));this.mergeHandlerResult(r,a,u,l,o),u&&u.needsRenderFrame&&this._triggerRenderFrame();}(u||c.isActive())&&(s[l]=c);}const l={};for(const e in this._previousActiveHandlers)s[e]||(l[e]=o);this._previousActiveHandlers=s,(Object.keys(l).length||Sa(r))&&(this._changes.push([r,a,l]),this._triggerRenderFrame()),(Object.keys(s).length||Sa(r))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:c}=r;c&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],c(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Fr(e),this._bearingSnap=i.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(i);const o=this._el;this._listeners=[[o,"touchstart",{passive:!0}],[o,"touchmove",{passive:!1}],[o,"touchend",void 0],[o,"touchcancel",void 0],[o,"mousedown",void 0],[o,"mousemove",void 0],[o,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[o,"mouseover",void 0],[o,"mouseout",void 0],[o,"dblclick",void 0],[o,"click",void 0],[o,"keydown",{capture:!1}],[o,"keyup",void 0],[o,"wheel",{passive:!1}],[o,"contextmenu",void 0],[window,"blur",void 0]];for(const[e,t,i]of this._listeners)n.addEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)n.removeEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const i=this._map,o=i.getCanvasContainer();this._add("mapEvent",new Zr(i,e));const r=i.boxZoom=new $r(i,e);this._add("boxZoom",r),e.interactive&&e.boxZoom&&r.enable();const a=i.cooperativeGestures=new Ca(i,e.cooperativeGestures);this._add("cooperativeGestures",a),e.cooperativeGestures&&a.enable();const s=new Xr(i),l=new xa(i);i.doubleClickZoom=new ba(l,s),this._add("tapZoom",s),this._add("clickZoom",l),e.interactive&&e.doubleClickZoom&&i.doubleClickZoom.enable();const c=new ya;this._add("tapDragZoom",c);const h=i.touchPitch=new da(i);this._add("touchPitch",h),e.interactive&&e.touchPitch&&i.touchPitch.enable(e.touchPitch);const u=()=>i.project(i.getCenter()),d=function({enable:e,clickTolerance:i,aroundCenter:o=!0,minPixelCenterThreshold:r=100,rotateDegreesPerPixelMoved:a=.8},s){const l=new ea({checkCorrectEvent:e=>0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:i,move:(e,i)=>{const n=s();if(o&&Math.abs(n.y-e.y)>r)return {bearingDelta:t.cn(new t.P(e.x,i.y),i,n)};let l=(i.x-e.x)*a;return o&&i.y0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)});return new Kr({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:o,enable:e,assignEvents:oa})}(e),p=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3},o){const r=new ea({checkCorrectEvent:e=>2===n.mouseButton(e)&&e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>{const r=o();let a=(t.x-e.x)*i;return t.y0===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:i,enable:e,assignEvents:oa})}(e),f=new ra(e,i);i.dragPan=new wa(o,m,f),this._add("mousePan",m),this._add("touchPan",f,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&i.dragPan.enable(e.dragPan);const g=new ha,v=new la;i.touchZoomRotate=new Pa(o,v,g,c),this._add("touchRotate",g,["touchPan","touchZoom"]),this._add("touchZoom",v,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&i.touchZoomRotate.enable(e.touchZoomRotate);const b=i.scrollZoom=new va(i,(()=>this._triggerRenderFrame()));this._add("scrollZoom",b,["mousePan"]),e.interactive&&e.scrollZoom&&i.scrollZoom.enable(e.scrollZoom);const x=i.keyboard=new pa(i);this._add("keyboard",x),e.interactive&&e.keyboard&&i.keyboard.enable(),this._add("blockableMapEvent",new Gr(i));}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(Ia(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const o in e)if(o!==i&&(!t||t.indexOf(o)<0))return !0;return !1}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,o,r,a){if(!o)return;t.e(e,o);const s={handlerName:r,originalEvent:o.originalEvent||a};void 0!==o.zoomDelta&&(i.zoom=s),void 0!==o.panDelta&&(i.drag=s),void 0!==o.rollDelta&&(i.roll=s),void 0!==o.pitchDelta&&(i.pitch=s),void 0!==o.bearingDelta&&(i.rotate=s);}_applyChanges(){const e={},i={},o={};for(const[r,a,s]of this._changes)r.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(r.panDelta)),r.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+r.zoomDelta),r.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+r.bearingDelta),r.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+r.pitchDelta),r.rollDelta&&(e.rollDelta=(e.rollDelta||0)+r.rollDelta),void 0!==r.around&&(e.around=r.around),void 0!==r.pinchAround&&(e.pinchAround=r.pinchAround),r.noInertia&&(e.noInertia=r.noInertia),t.e(i,a),t.e(o,s);this._updateMapTransform(e,i,o),this._changes=[];}_updateMapTransform(e,t,i){const o=this._map,r=o._getTransformForUpdate(),a=o.terrain;if(!(Sa(e)||a&&this._terrainMovement))return this._fireEvents(t,i,!0);o._stop(!0);let{panDelta:s,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;void 0!==d&&(u=d),u=u||o.transform.centerPoint,a&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const _={panDelta:s,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const p=u.distSqr(r.centerPoint)<.01?r.center:r.screenPointToLocation(s?u.sub(s):u);a?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._terrainMovement||!t.drag&&!t.zoom?t.drag&&this._terrainMovement?r.setCenter(r.screenPointToLocation(r.centerPoint.sub(s))):this._map.cameraHelper.handleMapControlsPan(_,r,p):(this._terrainMovement=!0,this._map._elevationFreeze=!0,this._map.cameraHelper.handleMapControlsPan(_,r,p))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._map.cameraHelper.handleMapControlsPan(_,r,p)),o._applyUpdatedTransform(r),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0);}_fireEvents(e,i,o){const r=Ia(this._eventsInProgress),a=Ia(e),n={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(n[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!r&&a&&this._fireEvent("movestart",a.originalEvent);for(const e in n)this._fireEvent(e,n[e]);a&&this._fireEvent("move",a.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const l={};let c;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:o}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],c=i[t]||o,l[`${e}end`]=c);}for(const e in l)this._fireEvent(e,l[e]);const h=Ia(this._eventsInProgress),u=(r||a)&&!h;if(u&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(o&&u){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new Ma("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}class Ra extends t.E{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((s.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=i.bearingSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.S(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,o){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},i),o)}panTo(e,i,o){return this.easeTo(t.e({center:e},i),o)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,o){return this.easeTo(t.e({zoom:e},i),o)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.l("movestart",i)).fire(new t.l("move",i)).fire(new t.l("moveend",i))),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,o){return this.easeTo(t.e({bearing:e},i),o)}resetNorth(e,i){return this.rotateTo(0,t.e({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){f.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,o={}){this._moving=!0,i||o.moving||this.fire(new t.l("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.l("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.l("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.l("pitchstart",e)),this._rolling&&!o.rolling&&this.fire(new t.l("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0;}_updateElevation(e){void 0!==this._elevationStart&&void 0!==this._elevationCenter||this._prepareElevation(this.transform.center),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.C.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),o=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:o,zoom:r,roll:a,pitch:s,bearing:n,elevation:l}=e(t);o&&t.setCenter(o),void 0!==l&&t.setElevation(l),void 0!==r&&t.setZoom(r),void 0!==a&&t.setRoll(a),void 0!==s&&t.setPitch(s),void 0!==n&&t.setBearing(n),i.apply(t);}this.transform.apply(i);}_fireMoveEvents(e){this.fire(new t.l("move",e)),this._zooming&&this.fire(new t.l("zoom",e)),this._rotating&&this.fire(new t.l("rotate",e)),this._pitching&&this.fire(new t.l("pitch",e)),this._rolling&&this.fire(new t.l("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const o=this._zooming,r=this._rotating,a=this._pitching,s=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,o&&this.fire(new t.l("zoomend",e)),r&&this.fire(new t.l("rotateend",e)),a&&this.fire(new t.l("pitchend",e)),s&&this.fire(new t.l("rollend",e)),this.fire(new t.l("moveend",e));}flyTo(e,i){if(!e.essential&&s.prefersReducedMotion){const o=t.Q(e,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(o,i)}this.stop(),e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.co},e);const o=this._getTransformForUpdate(),r=o.bearing,a=o.pitch,n=o.roll,l=o.padding,c="bearing"in e?this._normalizeBearing(e.bearing,r):r,h="pitch"in e?+e.pitch:a,u="roll"in e?this._normalizeBearing(e.roll,n):n,d="padding"in e?e.padding:o.padding,_=t.P.convert(e.offset);let p=o.centerPoint.add(_);const m=o.screenPointToLocation(p),f=this.cameraHelper.handleFlyTo(o,{bearing:c,pitch:h,roll:u,padding:d,locationAtOffset:m,offsetAsPoint:_,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(o.width,o.height),b=v/f.scaleOfZoom,x=f.pixelPathLength;"number"==typeof f.scaleOfMinZoom&&(g=Math.sqrt(v/f.scaleOfMinZoom/x*2));const y=g*g;function w(e){const t=(b*b-v*v+(e?-1:1)*y*y*x*x)/(2*(e?b:v)*y*x);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function P(e){return (Math.exp(e)+Math.exp(-e))/2}const C=w(!1);let I=function(e){return P(C)/P(C+g*e)},M=function(e){return v*((P(C)*(T(t=C+g*e)/P(t))-T(C))/y)/x;var t;},S=(w(!0)-C)/g;if(Math.abs(x)<2e-6||!isFinite(S)){if(Math.abs(v-b)<1e-6)return this.easeTo(e,i);const t=b0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*S/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=r!==c,this._pitching=h!==a,this._rolling=u!==n,this._padding=!o.isPaddingEqual(d),this._prepareEase(i,!1),this.terrain&&this._prepareElevation(f.targetCenter),this._ease((s=>{const m=s*S,g=1/I(m),v=M(m);this._rotating&&o.setBearing(t.C.number(r,c,s)),this._pitching&&o.setPitch(t.C.number(a,h,s)),this._rolling&&o.setRoll(t.C.number(n,u,s)),this._padding&&(o.interpolatePadding(l,d,s),p=o.centerPoint.add(_)),f.easeFunc(s,g,v,p),this.terrain&&!e.freezeElevation&&this._updateElevation(s),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=s.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.aO(e,-180,180);const o=Math.abs(e-i);return Math.abs(e-360-i)MapLibre
'};class Da{constructor(e=za){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=n.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=n.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=n.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.sourceCaches;for(const i in t){const o=t[i];if(o.used||o.usedForTerrain){const t=o.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let o=i+1;o=0)return !1;return !0}));const i=e.join(" | ");i!==this._attribHTML&&(this._attribHTML=i,e.length?(this._innerContainer.innerHTML=n.sanitize(i),this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Aa{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=n.create("div","maplibregl-ctrl");const t=n.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){n.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0;}}class La{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}var ka=t.aJ([{name:"a_pos3d",type:"Int16",components:3}]);class Fa extends t.E{constructor(e){super(),this._lastTilesetChange=s.now(),this.sourceCache=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize;}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null;}update(e,i){this.sourceCache.update(e,i),this._renderableTilesKeys=[];const o={};for(const r of ve(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:i,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))o[r.key]=!0,this._renderableTilesKeys.push(r.key),this._tiles[r.key]||(r.terrainRttPosMatrix32f=new Float64Array(16),t.bY(r.terrainRttPosMatrix32f,0,t.$,t.$,0,0,1),this._tiles[r.key]=new re(r,this.tileSize),this._lastTilesetChange=s.now());for(const e in this._tiles)o[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e,t){return t?this._getTerrainCoordsForTileRanges(e,t):this._getTerrainCoordsForRegularTile(e)}_getTerrainCoordsForRegularTile(e){const i={};for(const o of this._renderableTilesKeys){const r=this._tiles[o].tileID,a=e.clone(),s=t.ba();if(r.canonical.equals(e.canonical))t.bY(s,0,t.$,t.$,0,0,1);else if(r.canonical.isChildOf(e.canonical)){const i=r.canonical.z-e.canonical.z,o=r.canonical.x-(r.canonical.x>>i<>i<>i;t.bY(s,0,n,n,0,0,1),t.M(s,s,[-o*n,-a*n,0]);}else {if(!e.canonical.isChildOf(r.canonical))continue;{const i=e.canonical.z-r.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i;t.bY(s,0,t.$,t.$,0,0,1),t.M(s,s,[o*n,a*n,0]),t.N(s,s,[1/2**i,1/2**i,0]);}}a.terrainRttPosMatrix32f=new Float32Array(s),i[o]=a;}return i}_getTerrainCoordsForTileRanges(e,i){const o={};for(const r of this._renderableTilesKeys){const a=this._tiles[r].tileID;if(!this._isWithinTileRanges(a,i))continue;const s=e.clone(),n=t.ba();if(a.canonical.z===e.canonical.z){const i=e.canonical.x-a.canonical.x,o=e.canonical.y-a.canonical.y;t.bY(n,0,t.$,t.$,0,0,1),t.M(n,n,[i*t.$,o*t.$,0]);}else if(a.canonical.z>e.canonical.z){const i=a.canonical.z-e.canonical.z,o=a.canonical.x-(a.canonical.x>>i<>i<>i),l=e.canonical.y-(a.canonical.y>>i),c=t.$>>i;t.bY(n,0,c,c,0,0,1),t.M(n,n,[-o*c+s*t.$,-r*c+l*t.$,0]);}else {const i=e.canonical.z-a.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i)-a.canonical.x,l=(e.canonical.y>>i)-a.canonical.y,c=t.$<i.maxzoom&&(o=i.maxzoom),o=i.minzoom&&(!r||!r.dem);)r=this.sourceCache.getTileByID(e.scaledTo(o--).key);return r}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}_isWithinTileRanges(e,t){return t[e.canonical.z]&&e.canonical.x>=t[e.canonical.z].minTileX&&e.canonical.x<=t[e.canonical.z].maxTileX&&e.canonical.y>=t[e.canonical.z].minTileY&&e.canonical.y<=t[e.canonical.z].maxTileY}}class Ba{constructor(e,t,i){this._meshCache={},this.painter=e,this.sourceCache=new Fa(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(e,i,o,r=t.$){var a;if(!(i>=0&&i=0&&oe.canonical.z&&(e.canonical.z>=o?r=e.canonical.z-o:t.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const a=e.canonical.x-(e.canonical.x>>r<>r<>8<<4|e>>8,i[t+3]=0;const o=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),r=new t.T(e,o,e.gl.RGBA,{premultiply:!1});return r.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=r,r}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(!0);const i=new Uint8Array(4),o=this.painter.context,r=o.gl,a=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),s=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);o.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),r.readPixels(a,n-s-1,1,1,r.RGBA,r.UNSIGNED_BYTE,i),o.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.sourceCache.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<0,r=o&&0===e.canonical.y,a=o&&e.canonical.y===(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const ja={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class Na{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new Oa(e.context,30,t.sourceCache.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.sourceCaches){this._coordsAscending[t]={};const i=e.sourceCaches[t].getVisibleCoordinates(),o=e.sourceCaches[t].getSource(),r=o instanceof X?o.terrainTileRanges:null;for(const e of i){const i=this.terrain.sourceCache.getTerrainCoords(e,r);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._coordsAscendingStr={};for(const t of e._order){const i=e._layers[t],o=i.source;if(ja[i.type]&&!this._coordsAscendingStr[o]){this._coordsAscendingStr[o]={};for(const e in this._coordsAscending[o])this._coordsAscendingStr[o][e]=this._coordsAscending[o][e].map((e=>e.key)).sort().join();}}for(const e of this._renderableTiles)for(const t in this._coordsAscendingStr){const i=this._coordsAscendingStr[t][e.tileID.key];i&&i!==e.rttCoords[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return !1;const o=Object.assign(Object.assign({},i),{isRenderingToTexture:!0}),r=e.type,a=this.painter,s=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(ja[r]&&(this._prevType&&ja[this._prevType]||this._stacks.push([]),this._prevType=r,this._stacks[this._stacks.length-1].push(e.id),!s))return !0;if(ja[this._prevType]||ja[r]&&s){this._prevType=r;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const r of this._renderableTiles){if(this.pool.isFull()&&(Cr(this.painter,this.terrain,this._rttTiles,o),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(r),r.rtt[e]){const t=this.pool.getObjectForId(r.rtt[e].id);if(t.stamp===r.rtt[e].stamp){this.pool.useObject(t);continue}}const s=this.pool.getOrCreateFreeObject();this.pool.useObject(s),this.pool.stampObject(s),r.rtt[e]={id:s.id,stamp:s.stamp},a.context.bindFramebuffer.set(s.fbo.framebuffer),a.context.clear({color:t.bf.transparent,stencil:0}),a.currentStencilSource=void 0;for(let e=0;e{this.startMove(e,n.mousePos(this.element,e)),n.addEventListener(window,"mousemove",this.mousemove),n.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=e=>{this.move(e,n.mousePos(this.element,e));},this.mouseup=e=>{this._rotatePitchHandler.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),n.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.addEventListener(window,"touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHandler.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10,this.element=i;const r=new ia;this._rotatePitchHandler=new Kr({clickTolerance:3,move:(e,r)=>{const a=i.getBoundingClientRect(),s=new t.P((a.bottom-a.top)/2,(a.right-a.left)/2);return {bearingDelta:t.cn(new t.P(e.x,r.y),r,s),pitchDelta:o?-.5*(r.y-e.y):void 0}},moveStateManager:r,enable:!0,assignEvents:()=>{}}),this.map=e,n.addEventListener(i,"mousedown",this.mousedown),n.addEventListener(i,"touchstart",this.touchstart,{passive:!1}),n.addEventListener(i,"touchcancel",this.reset);}startMove(e,t){this._rotatePitchHandler.dragStart(e,t),n.disableDrag();}move(e,t){const i=this.map,{bearingDelta:o,pitchDelta:r}=this._rotatePitchHandler.dragMove(e,t)||{};o&&i.setBearing(i.getBearing()+o),r&&i.setPitch(i.getPitch()+r);}off(){const e=this.element;n.removeEventListener(e,"mousedown",this.mousedown),n.removeEventListener(e,"touchstart",this.touchstart,{passive:!1}),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend),n.removeEventListener(e,"touchcancel",this.reset),this.offTemp();}offTemp(){n.enableDrag(),n.removeEventListener(window,"mousemove",this.mousemove),n.removeEventListener(window,"mouseup",this.mouseup),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend);}}let qa;function Wa(e,i,o,r=!1){if(r||!o.getCoveringTilesDetailsProvider().allowWorldCopies())return null==e?void 0:e.wrap();const a=new t.S(e.lng,e.lat);if(e=new t.S(e.lng,e.lat),i){const r=new t.S(e.lng-360,e.lat),a=new t.S(e.lng+360,e.lat),s=o.locationToScreenPoint(e).distSqr(i);o.locationToScreenPoint(r).distSqr(i)180;){const t=o.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=o.width&&t.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==a.lng&&o.isPointOnMapSurface(o.locationToScreenPoint(e))?e:a}const Ha={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Xa(e,t,i){const o=e.classList;for(const e in Ha)o.remove(`maplibregl-${i}-anchor-${e}`);o.add(`maplibregl-${i}-anchor-${t}`);}class Ka extends t.E{constructor(e){if(super(),this._onKeyPress=e=>{const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{if(!this._map)return;const t=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?void 0:e.type)||"render"===(null==e?void 0:e.type)&&!t)&&this._map.once("render",this._update),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let i="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?i=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(i=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),n.setTransform(this._element,`${Ha[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${i}`),s.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.l("dragstart"))),this.fire(new t.l("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.l("dragend")),this._state="inactive";},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||!1,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(null==e?void 0:e.opacity,null==e?void 0:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.P.convert(e&&e.offset||[0,0]);else {this._defaultMarker=!0,this._element=n.create("div");const i=n.createNS("http://www.w3.org/2000/svg","svg"),o=41,r=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${o}px`),i.setAttributeNS(null,"width",`${r}px`),i.setAttributeNS(null,"viewBox",`0 0 ${r} ${o}`);const a=n.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"stroke","none"),a.setAttributeNS(null,"stroke-width","1"),a.setAttributeNS(null,"fill","none"),a.setAttributeNS(null,"fill-rule","evenodd");const s=n.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"fill-rule","nonzero");const l=n.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"transform","translate(3.0, 29.0)"),l.setAttributeNS(null,"fill","#000000");const c=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const e of c){const t=n.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),l.appendChild(t);}const h=n.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);const u=n.createNS("http://www.w3.org/2000/svg","path");u.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(u);const d=n.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");const _=n.createNS("http://www.w3.org/2000/svg","path");_.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(_);const p=n.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const m=n.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(8.0, 8.0)");const f=n.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#000000"),f.setAttributeNS(null,"opacity","0.25"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962");const g=n.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#FFFFFF"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962"),m.appendChild(f),m.appendChild(g),s.appendChild(l),s.appendChild(h),s.appendChild(d),s.appendChild(p),s.appendChild(m),i.appendChild(s),i.setAttributeNS(null,"height",o*this._scale+"px"),i.setAttributeNS(null,"width",r*this._scale+"px"),this._element.appendChild(i),this._offset=t.P.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),Xa(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),n.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,o=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-t],"bottom-left":[o,-1*(t-i+o)],"bottom-right":[-o,-1*(t-i+o)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=!1){var i,o;const r=null===(i=this._map)||void 0===i?void 0:i.terrain,a=this._map.transform.isLocationOccluded(this._lngLat);if(!r||a){const e=a?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const s=this._map,n=s.terrain.depthAtPoint(this._pos),l=s.terrain.getElevationForLngLatZoom(this._lngLat,s.transform.tileZoom);if(s.transform.lngLatToCameraDepth(this._lngLat,l)-n<.006)return void(this._element.style.opacity=this._opacity);const c=-this._offset.y/s.transform.pixelsPerMeter,h=Math.sin(s.getPitch()*Math.PI/180)*c,u=s.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),d=s.transform.lngLatToCameraDepth(this._lngLat,l+h)-u>.006;(null===(o=this._popup)||void 0===o?void 0:o.isOpen())&&d&&this._popup.remove(),this._element.style.opacity=d?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return (void 0===this._opacity||void 0===e&&void 0===t)&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==e&&(this._opacity=e),void 0!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(!0),this}}const Ya={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let Qa=0,Ja=!1;const es={maxWidth:100,unit:"metric"};function ts(e,t,i){const o=i&&i.maxWidth||100,r=e._container.clientHeight/2,a=e._container.clientWidth/2,s=e.unproject([a-o/2,r]),n=e.unproject([a+o/2,r]),l=Math.round(e.project(n).x-e.project(s).x),c=Math.min(o,l,e._container.clientWidth),h=s.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?is(t,c,i/5280,e._getUIString("ScaleControl.Miles")):is(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?is(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?is(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):is(t,c,h,e._getUIString("ScaleControl.Meters"));}function is(e,t,i,o){const r=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(r/i)+"px",e.innerHTML=`${r} ${o}`;}const os={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1,locationOccludedOpacity:void 0},rs=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function as(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(i,i),"top-right":new t.P(-i,i),bottom:new t.P(0,-e),"bottom-left":new t.P(i,-i),"bottom-right":new t.P(-i,-i),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){const i=t.P.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e["top-left"]||[0,0]),"top-right":t.P.convert(e["top-right"]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e["bottom-left"]||[0,0]),"bottom-right":t.P.convert(e["bottom-right"]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return as(new t.P(0,0))}const ss=i;e.AJAXError=t.cz,e.Event=t.l,e.Evented=t.E,e.LngLat=t.S,e.MercatorCoordinate=t.a1,e.Point=t.P,e.addProtocol=t.cA,e.config=t.a,e.removeProtocol=t.cB,e.AttributionControl=Da,e.BoxZoomHandler=$r,e.CanvasSource=Y,e.CooperativeGesturesHandler=Ca,e.DoubleClickZoomHandler=ba,e.DragPanHandler=wa,e.DragRotateHandler=Ta,e.EdgeInsets=Mt,e.FullscreenControl=class extends t.E{constructor(e={}){super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(e=null==t?void 0:t.shadowRoot)||void 0===e?void 0:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){n.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=n.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);n.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new t.l("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.l("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=H,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.l("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "BACKGROUND":case "BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.l("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.S(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.e({bearing:r},this.options.fitBoundsOptions),s=G.fromLngLat(i,o);this._map.fitBounds(s,a,{geolocateSource:!0});},this._updateMarker=e=>{if(e){const i=new t.S(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this._updateCircleRadiusIfNeeded();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded();},this._onError=e=>{if(this._map){if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Ja)return;this.options.trackUserLocation&&this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.l("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=n.create("button","maplibregl-ctrl-geolocate",this._container),n.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0);},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.w("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=n.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new Ka({element:this._dotElement}),this._circleElement=n.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ka({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onUpdate),this._map.on("move",this._onUpdate),this._map.on("rotate",this._onUpdate),this._map.on("pitch",this._onUpdate)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(e=>{const i=(null==e?void 0:e[0])instanceof ResizeObserverEntry;e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||i||this._map.isZooming()||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.l("trackuserlocationend")),this.fire(new t.l("userlocationlostfocus")));}));}},this.options=t.e({},Ya,e);}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t._(this,arguments,void 0,(function*(e=!1){if(void 0!==qa&&!e)return qa;if(void 0===window.navigator.permissions)return qa=!!window.navigator.geolocation,qa;try{const e=yield window.navigator.permissions.query({name:"geolocation"});qa="denied"!==e.state;}catch(e){qa=!!window.navigator.geolocation;}return qa}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),n.remove(this._container),this._map.off("zoom",this._onUpdate),this._map.off("move",this._onUpdate),this._map.off("rotate",this._onUpdate),this._map.off("pitch",this._onUpdate),this._map=void 0,Qa=0,Ja=!1;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case "WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case "ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadiusIfNeeded(){const e=this._userLocationDotMarker.getLngLat();if(!(this.options.showUserLocation&&this.options.showAccuracyCircle&&this._accuracy&&e))return;const t=this._map.project(e),i=this._map.unproject([t.x+100,t.y]),o=e.distanceTo(i)/100,r=2*this._accuracy/o;this._circleElement.style.width=`${r.toFixed(2)}px`,this._circleElement.style.height=`${r.toFixed(2)}px`;}trigger(){if(!this._setup)return t.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case "OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.l("trackuserlocationstart"));break;case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":case "BACKGROUND_ERROR":Qa--,Ja=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new t.l("trackuserlocationend"));break;case "BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.l("trackuserlocationstart")),this.fire(new t.l("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case "WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),Qa++,Qa>1?(e={maximumAge:6e5,timeout:0},Ja=!0):(e=this.options.positionOptions,Ja=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||void 0===e?void 0:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||void 0===e?void 0:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=n.create("button","maplibregl-ctrl-globe",this._container),n.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0;}},e.Hash=Er,e.ImageSource=X,e.KeyboardHandler=pa,e.LngLatBounds=G,e.LogoControl=Aa,e.Map=class extends Ra{constructor(e){var i,o;t.cw.mark(t.cx.create);const r=Object.assign(Object.assign(Object.assign({},Ga),e),{canvasContextAttributes:Object.assign(Object.assign({},Ga.canvasContextAttributes),e.canvasContextAttributes)});if(null!=r.minZoom&&null!=r.maxZoom&&r.minZoom>r.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=r.minPitch&&null!=r.maxPitch&&r.minPitch>r.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=r.minPitch&&r.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=r.maxPitch&&r.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const a=new Lt,s=new Ot;if(void 0!==r.minZoom&&a.setMinZoom(r.minZoom),void 0!==r.maxZoom&&a.setMaxZoom(r.maxZoom),void 0!==r.minPitch&&a.setMinPitch(r.minPitch),void 0!==r.maxPitch&&a.setMaxPitch(r.maxPitch),void 0!==r.renderWorldCopies&&a.setRenderWorldCopies(r.renderWorldCopies),super(a,s,{bearingSnap:r.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new La,this._controls=[],this._mapId=t.a7(),this._contextLost=e=>{e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new t.l("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._setupPainter(),this.resize(),this._update(),this.fire(new t.l("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update();},this._interactive=r.interactive,this._maxTileCacheSize=r.maxTileCacheSize,this._maxTileCacheZoomLevels=r.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},r.canvasContextAttributes),this._trackResize=!0===r.trackResize,this._bearingSnap=r.bearingSnap,this._centerClampedToGround=r.centerClampedToGround,this._refreshExpiredTiles=!0===r.refreshExpiredTiles,this._fadeDuration=r.fadeDuration,this._crossSourceCollisions=!0===r.crossSourceCollisions,this._collectResourceTiming=!0===r.collectResourceTiming,this._locale=Object.assign(Object.assign({},Ua),r.locale),this._clickTolerance=r.clickTolerance,this._overridePixelRatio=r.pixelRatio,this._maxCanvasSize=r.maxCanvasSize,this.transformCameraUpdate=r.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===r.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=p.addThrottleControl((()=>this.isMoving())),this._requestManager=new m(r.transformRequest),"string"==typeof r.container){if(this._container=document.getElementById(r.container),!this._container)throw new Error(`Container '${r.container}' not found.`)}else {if(!(r.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=r.container;}if(r.maxBounds&&this.setMaxBounds(r.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0);})),this.once("idle",(()=>{this._idleTriggered=!0;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let e=!1;const t=Sr((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{e?t(i):e=!0;})),this._resizeObserver.observe(this._container);}this.handlers=new Ea(this,r),this._hash=r.hash&&new Er("string"==typeof r.hash&&r.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:r.center,elevation:r.elevation,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,roll:r.roll}),r.bounds&&(this.resize(),this.fitBounds(r.bounds,t.e({},r.fitBoundsOptions,{duration:0}))));const n="string"==typeof r.style||!("globe"===(null===(o=null===(i=r.style)||void 0===i?void 0:i.projection)||void 0===o?void 0:o.type));this.resize(null,n),this._localIdeographFontFamily=r.localIdeographFontFamily,this._validateStyle=r.validateStyle,r.style&&this.setStyle(r.style,{localIdeographFontFamily:r.localIdeographFontFamily}),r.attributionControl&&this.addControl(new Da("boolean"==typeof r.attributionControl?void 0:r.attributionControl)),r.maplibreLogo&&this.addControl(new Aa,r.logoPosition),this.on("style.load",(()=>{if(n||this._resizeTransform(),this.transform.unmodified){const e=t.Q(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.l(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.l(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.l("sourcedataabort",e));}));}_getMapId(){return this._mapId}setGlobalStateProperty(e,t){return this.style.setGlobalStateProperty(e,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(e,i){if(void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.k(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const o=e.onAdd(this);this._controls.push(e);const r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.k(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}coveringTiles(e){return ve(this.transform,e)}calculateCameraOptionsFromTo(e,t,i,o){return null==o&&this.terrain&&(o=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(e,t,i,o)}resize(e,i=!0){const[o,r]=this._containerDimensions(),a=this._getClampedPixelRatio(o,r);if(this._resizeCanvas(o,r,a),this.painter.resize(o,r,a),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const t=this._getClampedPixelRatio(o,r);this._resizeCanvas(o,r,t),this.painter.resize(o,r,t);}this._resizeTransform(i);const s=!this._moving;return s&&(this.stop(),this.fire(new t.l("movestart",e)).fire(new t.l("move",e))),this.fire(new t.l("resize",e)),s&&this.fire(new t.l("moveend",e)),this}_resizeTransform(e=!0){var t;const[i,o]=this._containerDimensions();this.transform.resize(i,o,e),null===(t=this._requestedCameraState)||void 0===t||t.resize(i,o,e);}_getClampedPixelRatio(e,t){const{0:i,1:o}=this._maxCanvasSize,r=this.getPixelRatio(),a=e*r,s=t*r;return Math.min(a>i?i/a:1,s>o?o/s:1)*r}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&void 0!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(G.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom)return this.transform.setMinZoom(e),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(e),this._update(),this.getZoom()>e&&this.setZoom(e),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.setMinPitch(e),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch)return this.transform.setMaxPitch(e),this._update(),this.getPitch()>e&&this.setPitch(e),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.S.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||void 0===e?void 0:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||void 0===e?void 0:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||void 0===e?void 0:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e))),s=0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[];s.length?o||(o=!0,i.call(this,new jr(e,this,r.originalEvent,{features:s}))):o=!1;};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:()=>{o=!1;}}}}if("mouseleave"===e||"mouseout"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e)));(0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[]).length?o=!0:o&&(o=!1,i.call(this,new jr(e,this,r.originalEvent)));},a=t=>{o&&(o=!1,i.call(this,new jr(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:a}}}{const o=e=>{const o=t.filter((e=>this.getLayer(e))),r=0!==o.length?this.queryRenderedFeatures(e.point,{layers:o}):[];r.length&&(e.features=r,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:o}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const o=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in r.delegates)this.off(e,r.delegates[e]);return void o.splice(e,1)}}}on(e,t,i){if(void 0===i)return super.on(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);this._saveDelegatedListener(e,r);for(const e in r.delegates)this.on(e,r.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,o,i);}}}once(e,t,i){if(void 0===i)return super.once(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);for(const t in r.delegates){const a=r.delegates[t];r.delegates[t]=(...t)=>{this._removeDelegatedListener(e,o,i),a(...t);};}this._saveDelegatedListener(e,r);for(const e in r.delegates)this.once(e,r.delegates[e]);return this}off(e,t,i){return void 0===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let o;const r=e instanceof t.P||Array.isArray(e),a=r?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(r?{}:e)||{},a instanceof t.P||"number"==typeof a[0])o=[t.P.convert(a)];else {const e=t.P.convert(a[0]),i=t.P.convert(a[1]);o=[e,new t.P(i.x,e.y),i,new t.P(e.x,i.y),e];}return this.style.queryRenderedFeatures(o,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return !1!==(i=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,o;if(t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const r=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new wi(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,r):this.style.loadJSON(e,t,r),this):(null===(o=null===(i=this.style)||void 0===i?void 0:i.projection)||void 0===o||o.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new wi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){if("string"==typeof e){const o=this._requestManager.transformRequest(e,"Style");t.j(o,new AbortController).then((e=>{this._updateDiff(e.data,i);})).catch((e=>{e&&this.fire(new t.k(e));}));}else "object"==typeof e&&this._updateDiff(e,i);}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(o){t.w(`Unable to perform style diff: ${o.message||o.error||o}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():t.w("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){const i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.k(new Error(`There is no source with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.sourceCaches[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const o=this.style._layers[i];"hillshade"===o.type&&o.source===e.source&&t.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality."),"color-relief"===o.type&&o.source===e.source&&t.w("You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");}this.terrain=new Ba(this.painter,i,e),this.painter.renderToTexture=new Na(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{var i;"style"===t.dataType?this.terrain.sourceCache.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),"image"===(null===(i=t.source)||void 0===i?void 0:i.type)?this.terrain.sourceCache.freeRtt():this.terrain.sourceCache.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.l("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||void 0===e?void 0:e.options)&&void 0!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.sourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}}return !0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}setSourceTileLodParams(e,t,i){if(i){const o=this.getSource(i);if(!o)throw new Error(`There is no source with ID "${i}", cannot set LOD parameters`);o.calculateTileZoom=me(Math.max(1,e),Math.max(1,t));}else for(const i in this.style.sourceCaches)this.style.sourceCaches[i].getSource().calculateTileZoom=me(Math.max(1,e),Math.max(1,t));return this._update(!0),this}refreshTiles(e,i){const o=this.style.sourceCaches[e];if(!o)throw new Error(`There is no source cache with ID "${e}", cannot refresh tile`);void 0===i?o.reload(!0):o.refreshTiles(i.map((e=>new t.a4(e.z,e.x,e.y))));}addImage(e,i,o={}){const{pixelRatio:r=1,sdf:a=!1,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u}=o;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.b(i))){if(void 0===i.width||void 0===i.height)return this.fire(new t.k(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:o,height:s,data:d}=i,_=i;return this.style.addImage(e,{data:new t.R({width:o,height:s},new Uint8Array(d)),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:o,height:d,data:_}=s.getImageData(i);this.style.addImage(e,{data:new t.R({width:o,height:d},_),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0});}}updateImage(e,i){const o=this.style.getImage(e);if(!o)return this.fire(new t.k(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const r=i instanceof HTMLImageElement||t.b(i)?s.getImageData(i):i,{width:a,height:n,data:l}=r;if(void 0===a||void 0===n)return this.fire(new t.k(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(a!==o.data.width||n!==o.data.height)return this.fire(new t.k(new Error("The width and height of the updated image must be that same as the previous version of the image")));const c=!(i instanceof HTMLImageElement||t.b(i));return o.data.replace(l,c),this.style.updateImage(e,o),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.k(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(e);}loadImage(e){return p.getImage(this._requestManager.transformRequest(e,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(!0)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,o={}){return this.style.setPaintProperty(e,t,i,o),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,o={}){return this.style.setLayoutProperty(e,t,i,o),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(!0);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=n.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=n.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),o=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],o);const r=this._controlContainer=n.create("div","maplibregl-control-container",e),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{a[e]=n.create("div",`maplibregl-ctrl-${e} `,r);})),this._container.addEventListener("scroll",this._onMapScroll,!1);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0});let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:!0});let i=null;if(i=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e),!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new Mr(i,this.transform),l.testSupport(i);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.l("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){var i,o,r,a,n;const l=this._idleTriggered?this._fadeDuration:0,c=(null===(i=this.style.projection)||void 0===i?void 0:i.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let h=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,i=s.now();this.style.zoomHistory.update(e,i);const o=new t.F(e,{now:i,fadeDuration:l,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),r=o.crossFadingFactor();1===r&&r===this._crossFadingFactor||(h=!0,this._crossFadingFactor=r),this.style.update(o);}const u=(null===(o=this.style.projection)||void 0===o?void 0:o.transitionState)>0!==c;null===(r=this.style.projection)||void 0===r||r.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(a=this.style.projection)||void 0===a?void 0:a.transitionState,null===(n=this.style.projection)||void 0===n?void 0:n.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||u)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,l,this._crossSourceCollisions,u),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:l,showPadding:this.showPadding}),this.fire(new t.l("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,t.cw.mark(t.cx.load),this.fire(new t.l("load"))),this.style&&(this.style.hasTransitions()||h)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const d=this._sourcesDirty||this._styleDirty||this._placementDirty;return d||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.l("idle")),!this._loaded||this._fullyLoaded||d||(this._fullyLoaded=!0,t.cw.mark(t.cx.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),p.removeThrottleControl(this._imageQueueHandle),null===(e=this._resizeObserver)||void 0===e||e.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?void 0:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),n.remove(this._canvasContainer),n.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),t.cw.clearMetrics(),this._removed=!0,this.fire(new t.l("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,s.frame(this._frameRequest,(e=>{t.cw.frame(e),this._frameRequest=null;try{this._render(e);}catch(e){if(!t.cy(e)&&!function(e){return e.message===qo}(e))throw e}}),(()=>{})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return Za}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}},e.MapMouseEvent=jr,e.MapTouchEvent=Nr,e.MapWheelEvent=Ur,e.Marker=Ka,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.e({},Va,e),this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=n.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new $a(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){n.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=n.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.E{constructor(e){super(),this._updateOpacity=()=>{void 0!==this.options.locationOccludedOpacity&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:"");},this.remove=()=>(this._content&&n.remove(this._content),this._container&&(n.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new t.l("close"))),this),this._onMouseUp=e=>{this._update(e.point);},this._onMouseMove=e=>{this._update(e.point);},this._onDrag=e=>{this._update(e.point);},this._update=e=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=n.create("div","maplibregl-popup",this._map.getContainer()),this._tip=n.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer");}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),this._trackPointer&&!e)return;const t=this._flatPos=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&e?e:this._map.transform.locationToScreenPoint(this._lngLat));let i=this.options.anchor;const o=as(this.options.offset);if(!i){const e=this._container.offsetWidth,r=this._container.offsetHeight;let a;a=t.y+o.bottom.ythis._map.transform.height-r?["bottom"]:[],t.xthis._map.transform.width-e/2&&a.push("right"),i=0===a.length?"bottom":a.join("-");}let r=t.add(o[i]);this.options.subpixelPositioning||(r=r.round()),n.setTransform(this._container,`${Ha[i]} translate(${r.x}px,${r.y}px)`),Xa(this._container,i,"popup"),this._updateOpacity();},this._onClose=()=>{this.remove();},this.options=t.e(Object.create(os),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.l("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let o;for(i.innerHTML=e;o=i.firstChild,o;)t.appendChild(o);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||void 0===e?void 0:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=n.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}_createCloseButton(){this.options.closeButton&&(this._closeButton=n.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(rs);e&&e.focus();}},e.RasterDEMTileSource=W,e.RasterTileSource=q,e.ScaleControl=class{constructor(e){this._onMove=()=>{ts(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,ts(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},es),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){n.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;}},e.ScrollZoomHandler=va,e.Style=wi,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=n.create("button","maplibregl-ctrl-terrain",this._container),n.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){n.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0;}},e.TwoFingersTouchPitchHandler=da,e.TwoFingersTouchRotateHandler=ha,e.TwoFingersTouchZoomHandler=la,e.TwoFingersTouchZoomRotateHandler=Pa,e.VectorTileSource=$,e.VideoSource=K,e.addSourceType=(e,i)=>t._(void 0,void 0,void 0,(function*(){if(J(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{Q[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=A;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(R),A=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},e.createTileMesh=Xt,e.getMaxParallelImageRequests=function(){return t.a.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},e.getVersion=function(){return ss},e.getWorkerCount=function(){return z.workerCount},e.getWorkerUrl=function(){return t.a.WORKER_URL},e.importScriptInWorkers=function(e){return B().broadcast("IS",e)},e.prewarm=function(){k().acquire(R);},e.setMaxParallelImageRequests=function(e){t.a.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setRTLTextPlugin=function(e,t){return oe().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){z.workerCount=e;},e.setWorkerUrl=function(e){t.a.WORKER_URL=e;};})); + +// +// Our custom intro provides a specialized "define()" function, called by the +// AMD modules below, that sets up the worker blob URL and then executes the +// main module, storing its exported value as 'maplibregl' + + +var maplibregl$1 = maplibregl; + +return maplibregl$1; + +})); +//# sourceMappingURL=maplibre-gl.js.map diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt new file mode 100644 index 0000000..624d1f1 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2023, MapTiler +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js new file mode 100644 index 0000000..0fe7116 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js @@ -0,0 +1,14 @@ +(function(j,ee){typeof exports=="object"&&typeof module<"u"?ee(exports,require("maplibre-gl")):typeof define=="function"&&define.amd?define(["exports","maplibre-gl"],ee):(j=typeof globalThis<"u"?globalThis:j||self,ee(j.maplibreglMaptilerGeocoder={},j.maplibregl))})(this,function(j,ee){"use strict";var Ws=Object.defineProperty;var bn=j=>{throw TypeError(j)};var Gs=(j,ee,me)=>ee in j?Ws(j,ee,{enumerable:!0,configurable:!0,writable:!0,value:me}):j[ee]=me;var A=(j,ee,me)=>Gs(j,typeof ee!="symbol"?ee+"":ee,me),wn=(j,ee,me)=>ee.has(j)||bn("Cannot "+me);var ue=(j,ee,me)=>(wn(j,ee,"read from private field"),me?me.call(j):ee.get(j)),Vt=(j,ee,me)=>ee.has(j)?bn("Cannot add the same private member more than once"):ee instanceof WeakSet?ee.add(j):ee.set(j,me),kt=(j,ee,me,dt)=>(wn(j,ee,"write to private field"),dt?dt.call(j,me):ee.set(j,me),me);var fn,cn;function me(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const dt=me(ee);function ne(){}function Ln(i,e){for(const t in e)i[t]=e[t];return i}function yi(i){return i()}function vi(){return Object.create(null)}function Ue(i){i.forEach(yi)}function bi(i){return typeof i=="function"}function Ke(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}let Rt;function ye(i,e){return i===e?!0:(Rt||(Rt=document.createElement("a")),Rt.href=e,i===Rt.href)}function _n(i){return Object.keys(i).length===0}function Sn(i,e,t,n){if(i){const r=wi(i,e,t,n);return i[0](r)}}function wi(i,e,t,n){return i[1]&&n?Ln(t.ctx.slice(),i[1](n(e))):t.ctx}function xn(i,e,t,n){return i[2],e.dirty}function Tn(i,e,t,n,r,u){if(r){const a=wi(e,t,n,u);i.p(a,r)}}function Mn(i){if(i.ctx.length>32){const e=[],t=i.ctx.length/32;for(let n=0;ni.removeEventListener(e,t,n)}function Nn(i){return function(e){return e.preventDefault(),i.call(this,e)}}function S(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function kn(i){return Array.from(i.childNodes)}function gt(i,e){e=""+e,i.data!==e&&(i.data=e)}function Ei(i,e){i.value=e??""}function Ie(i,e,t){i.classList.toggle(e,!!t)}function On(i,e,{bubbles:t=!1,cancelable:n=!1}={}){return new CustomEvent(i,{detail:e,bubbles:t,cancelable:n})}let mt;function pt(i){mt=i}function Li(){if(!mt)throw new Error("Function called outside component initialization");return mt}function Rn(i){Li().$$.on_destroy.push(i)}function _i(){const i=Li();return(e,t,{cancelable:n=!1}={})=>{const r=i.$$.callbacks[e];if(r){const u=On(e,t,{cancelable:n});return r.slice().forEach(a=>{a.call(i,u)}),!u.defaultPrevented}return!0}}function Pn(i,e){const t=i.$$.callbacks[e.type];t&&t.slice().forEach(n=>n.call(this,e))}const ut=[],Yt=[];let at=[];const Si=[],In=Promise.resolve();let Qt=!1;function An(){Qt||(Qt=!0,In.then(xi))}function Xt(i){at.push(i)}const Jt=new Set;let ft=0;function xi(){if(ft!==0)return;const i=mt;do{try{for(;fti.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),at=e}const It=new Set;let nt;function yt(){nt={r:0,c:[],p:nt}}function vt(){nt.r||Ue(nt.c),nt=nt.p}function re(i,e){i&&i.i&&(It.delete(i),i.i(e))}function fe(i,e,t,n){if(i&&i.o){if(It.has(i))return;It.add(i),nt.c.push(()=>{It.delete(i),n&&(t&&i.d(1),n())}),i.o(e)}else n&&n()}function Ti(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function Gn(i,e){fe(i,1,1,()=>{e.delete(i.key)})}function Dn(i,e,t,n,r,u,a,o,g,c,E,_){let M=i.length,R=u.length,k=M;const I={};for(;k--;)I[i[k].key]=k;const C=[],O=new Map,x=new Map,N=[];for(k=R;k--;){const W=_(r,u,k),s=t(W);let l=a.get(s);l?N.push(()=>l.p(W,e)):(l=c(s,W),l.c()),O.set(s,C[k]=l),s in I&&x.set(s,Math.abs(k-I[s]))}const P=new Set,B=new Set;function z(W){re(W,1),W.m(o,E),a.set(W.key,W),E=W.first,R--}for(;M&&R;){const W=C[R-1],s=i[M-1],l=W.key,f=s.key;W===s?(E=W.first,M--,R--):O.has(f)?!a.has(l)||P.has(l)?z(W):B.has(f)?M--:x.get(l)>x.get(f)?(B.add(l),z(W)):(P.add(f),M--):(g(s,a),M--)}for(;M--;){const W=i[M];O.has(W.key)||g(W,a)}for(;R;)z(C[R-1]);return Ue(N),C}function Qe(i){i&&i.c()}function qe(i,e,t){const{fragment:n,after_update:r}=i.$$;n&&n.m(e,t),Xt(()=>{const u=i.$$.on_mount.map(yi).filter(bi);i.$$.on_destroy?i.$$.on_destroy.push(...u):Ue(u),i.$$.on_mount=[]}),r.forEach(Xt)}function Fe(i,e){const t=i.$$;t.fragment!==null&&(Wn(t.after_update),Ue(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function zn(i,e){i.$$.dirty[0]===-1&&(ut.push(i),An(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<{const k=R.length?R[0]:M;return c.ctx&&r(c.ctx[_],c.ctx[_]=k)&&(!c.skip_bound&&c.bound[_]&&c.bound[_](k),E&&zn(i,_)),M}):[],c.update(),E=!0,Ue(c.before_update),c.fragment=n?n(c.ctx):!1,e.target){if(e.hydrate){const _=kn(e.target);c.fragment&&c.fragment.l(_),_.forEach($)}else c.fragment&&c.fragment.c();e.intro&&re(i.$$.fragment),qe(i,e.target,e.anchor),xi()}pt(g)}class Je{constructor(){A(this,"$$");A(this,"$$set")}$destroy(){Fe(this,1),this.$destroy=ne}$on(e,t){if(!bi(t))return ne;const n=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return n.push(t),()=>{const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}$set(e){this.$$set&&!_n(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Un="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Un);function qn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M13.12.706a.982.982 0 0 0-1.391 0L6.907 5.517 2.087.696a.982.982 0 1 0-1.391 1.39l4.821 4.821L.696 11.73a.982.982 0 1 0 1.39 1.39l4.821-4.821 4.822 4.821a.982.982 0 1 0 1.39-1.39L8.298 6.908l4.821-4.822a.988.988 0 0 0 0-1.38Z"),S(e,"viewBox","0 0 14 14"),S(e,"width","13"),S(e,"height","13"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Mi extends Je{constructor(e){super(),Xe(this,e,null,qn,Ke,{})}}function Fn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M15 0C6.705 0 0 6.705 0 15C0 23.295 6.705 30 15 30C23.295 30 30 23.295 30 15C30 6.705 23.295 0 15 0ZM22.5 20.385L20.385 22.5L15 17.115L9.615 22.5L7.5 20.385L12.885 15L7.5 9.615L9.615 7.5L15 12.885L20.385 7.5L22.5 9.615L17.115 15L22.5 20.385Z"),S(e,"viewBox","0 0 30 30"),S(e,"fill","none"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"class","svelte-d2loi5")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Ci extends Je{constructor(e){super(),Xe(this,e,null,Fn,Ke,{})}}function jn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"area.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"area.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Zn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"reverse.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"reverse.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Hn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"poi.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"poi.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Vn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"postal_code.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"postal_code.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Kn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"street.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"street.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Yn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"road.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"road.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Qn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"housenumber.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"housenumber.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Xn(i){let e,t,n,r;return{c(){e=Y("img"),ye(e.src,t=i[5])||S(e,"src",t),S(e,"alt",i[4]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(u,a){te(u,e,a),n||(r=he(e,"error",i[14]),n=!0)},p(u,a){a&32&&!ye(e.src,t=u[5])&&S(e,"src",t),a&16&&S(e,"alt",u[4]),a&128&&S(e,"title",u[7])},d(u){u&&$(e),n=!1,r()}}}function Jn(i){let e,t;return{c(){e=Y("div"),S(e,"class","sprite-icon svelte-w9y5n9"),S(e,"style",t=` + width: ${i[6].width/xe}px; + height: ${i[6].height/xe}px; + background-image: url(${i[3]}sprite${$t}.png); + background-position: -${i[6].x/xe}px -${i[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `),S(e,"title",i[7])},m(n,r){te(n,e,r)},p(n,r){r&72&&t!==(t=` + width: ${n[6].width/xe}px; + height: ${n[6].height/xe}px; + background-image: url(${n[3]}sprite${$t}.png); + background-position: -${n[6].x/xe}px -${n[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `)&&S(e,"style",t),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Ni(i){let e,t;return{c(){e=Y("span"),t=Ye(i[7]),S(e,"class","secondary svelte-w9y5n9")},m(n,r){te(n,e,r),V(e,t)},p(n,r){r&128&>(t,n[7])},d(n){n&&$(e)}}}function $n(i){let e,t,n,r,u,a,o,g,c,E=(i[8]?i[0].place_name:i[0].place_name.replace(/,.*/,""))+"",_,M,R=i[2]==="always"||i[2]!=="never"&&!i[0].address&&!i[0].id.startsWith("road.")&&!i[0].id.startsWith("address.")&&!i[0].id.startsWith("postal_code.")&&(!i[0].id.startsWith("poi.")||!i[5])&&!i[8],k,I,C=(i[8]?"":i[0].place_name.replace(/[^,]*,?\s*/,""))+"",O,x,N,P,B,z;function W(m,h){return h&1&&(t=null),h&1&&(n=null),h&1&&(r=null),h&1&&(u=null),Oe&&m[6]?Jn:m[5]?Xn:m[0].address?Qn:(t==null&&(t=!!m[0].id.startsWith("road.")),t?Yn:(n==null&&(n=!!m[0].id.startsWith("address.")),n?Kn:(r==null&&(r=!!m[0].id.startsWith("postal_code.")),r?Vn:(u==null&&(u=!!m[0].id.startsWith("poi.")),u?Hn:m[8]?Zn:jn))))}let s=W(i,-1),l=s(i),f=R&&Ni(i);return{c(){e=Y("li"),l.c(),a=we(),o=Y("span"),g=Y("span"),c=Y("span"),_=Ye(E),M=we(),f&&f.c(),k=we(),I=Y("span"),O=Ye(C),S(c,"class","primary svelte-w9y5n9"),S(g,"class","svelte-w9y5n9"),S(I,"class","line2 svelte-w9y5n9"),S(o,"class","texts svelte-w9y5n9"),S(e,"tabindex","-1"),S(e,"role","option"),S(e,"aria-selected",x=i[1]==="selected"),S(e,"aria-checked",N=i[1]==="picked"),S(e,"class",P=Pt(i[1])+" svelte-w9y5n9")},m(m,h){te(m,e,h),l.m(e,null),V(e,a),V(e,o),V(o,g),V(g,c),V(c,_),V(g,M),f&&f.m(g,null),V(o,k),V(o,I),V(I,O),B||(z=[he(e,"mouseenter",i[13]),he(e,"focus",i[15]),he(e,"click",i[16])],B=!0)},p(m,[h]){s===(s=W(m,h))&&l?l.p(m,h):(l.d(1),l=s(m),l&&(l.c(),l.m(e,a))),h&257&&E!==(E=(m[8]?m[0].place_name:m[0].place_name.replace(/,.*/,""))+"")&>(_,E),h&293&&(R=m[2]==="always"||m[2]!=="never"&&!m[0].address&&!m[0].id.startsWith("road.")&&!m[0].id.startsWith("address.")&&!m[0].id.startsWith("postal_code.")&&(!m[0].id.startsWith("poi.")||!m[5])&&!m[8]),R?f?f.p(m,h):(f=Ni(m),f.c(),f.m(g,null)):f&&(f.d(1),f=null),h&257&&C!==(C=(m[8]?"":m[0].place_name.replace(/[^,]*,?\s*/,""))+"")&>(O,C),h&2&&x!==(x=m[1]==="selected")&&S(e,"aria-selected",x),h&2&&N!==(N=m[1]==="picked")&&S(e,"aria-checked",N),h&2&&P!==(P=Pt(m[1])+" svelte-w9y5n9")&&S(e,"class",P)},i:ne,o:ne,d(m){m&&$(e),l.d(),f&&f.d(),B=!1,Ue(z)}}}const ki=typeof devicePixelRatio>"u"?1:devicePixelRatio>1.25,$t=ki?"@2x":"",xe=ki?2:1;let Oe,At;function er(i,e,t){let n,r,u,{feature:a}=e,{style:o="default"}=e,{showPlaceType:g}=e,{missingIconsCache:c}=e,{iconsBaseUrl:E}=e;const _=_i();let M,R,k,I;function C(){At??(At=fetch(`${E}sprite${$t}.json`).then(s=>s.json()).then(s=>{Oe=s}).catch(()=>{Oe=null}))}function O(){R&&c.add(R),x()}function x(){Oe!==void 0?N():(C(),At==null||At.then(N))}function N(){do{if(I--,t(4,M=n==null?void 0:n[I]),t(6,k=M?Oe==null?void 0:Oe.icons[M]:void 0),k)break;t(5,R=M?E+M.replace(/ /g,"_")+".svg":void 0)}while(I>-1&&(!R||c.has(R)))}function P(s){Pn.call(this,i,s)}const B=()=>O(),z=()=>_("select",void 0),W=s=>{document.activeElement!==s.target&&_("select",void 0)};return i.$$set=s=>{"feature"in s&&t(0,a=s.feature),"style"in s&&t(1,o=s.style),"showPlaceType"in s&&t(2,g=s.showPlaceType),"missingIconsCache"in s&&t(11,c=s.missingIconsCache),"iconsBaseUrl"in s&&t(3,E=s.iconsBaseUrl)},i.$$.update=()=>{var s,l,f,m,h;i.$$.dirty&1&&t(12,n=(s=a.properties)==null?void 0:s.categories),i.$$.dirty&1&&t(8,r=a.place_type[0]==="reverse"),i.$$.dirty&1&&t(7,u=((f=(l=a.properties)==null?void 0:l.categories)==null?void 0:f.join(", "))??((h=(m=a.properties)==null?void 0:m.place_type_name)==null?void 0:h[0])??a.place_type[0]),i.$$.dirty&4096&&(I=(n==null?void 0:n.length)??0,x())},[a,o,g,E,M,R,k,u,r,_,O,c,n,P,B,z,W]}class tr extends Je{constructor(e){super(),Xe(this,e,er,$n,Ke,{feature:0,style:1,showPlaceType:2,missingIconsCache:11,iconsBaseUrl:3})}}function ir(i){let e;return{c(){e=Y("div"),e.innerHTML='',S(e,"class","svelte-1ocfouu")},m(t,n){te(t,e,n)},p:ne,i:ne,o:ne,d(t){t&&$(e)}}}class nr extends Je{constructor(e){super(),Xe(this,e,null,ir,Ke,{})}}function rr(i){let e,t,n;return{c(){e=ke("svg"),t=ke("path"),S(t,"stroke-width","4"),S(t,"d","M 5,33.103579 C 5,17.607779 18.457,5 35,5 C 51.543,5 65,17.607779 65,33.103579 C 65,56.388679 40.4668,76.048179 36.6112,79.137779 C 36.3714,79.329879 36.2116,79.457979 36.1427,79.518879 C 35.8203,79.800879 35.4102,79.942779 35,79.942779 C 34.5899,79.942779 34.1797,79.800879 33.8575,79.518879 C 33.7886,79.457979 33.6289,79.330079 33.3893,79.138079 C 29.5346,76.049279 5,56.389379 5,33.103579 Z M 35.0001,49.386379 C 43.1917,49.386379 49.8323,42.646079 49.8323,34.331379 C 49.8323,26.016779 43.1917,19.276479 35.0001,19.276479 C 26.8085,19.276479 20.1679,26.016779 20.1679,34.331379 C 20.1679,42.646079 26.8085,49.386379 35.0001,49.386379 Z"),S(t,"class","svelte-gzo3ar"),S(e,"width",n=i[0]==="list"?20:void 0),S(e,"viewBox","0 0 70 85"),S(e,"fill","none"),S(e,"class","svelte-gzo3ar"),Ie(e,"in-map",i[0]!=="list"),Ie(e,"list-icon",i[0]==="list")},m(r,u){te(r,e,u),V(e,t)},p(r,[u]){u&1&&n!==(n=r[0]==="list"?20:void 0)&&S(e,"width",n),u&1&&Ie(e,"in-map",r[0]!=="list"),u&1&&Ie(e,"list-icon",r[0]==="list")},i:ne,o:ne,d(r){r&&$(e)}}}function sr(i,e,t){let{displayIn:n}=e;return i.$$set=r=>{"displayIn"in r&&t(0,n=r.displayIn)},[n]}class or extends Je{constructor(e){super(),Xe(this,e,sr,rr,Ke,{displayIn:0})}}function lr(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M30.003-26.765C13.46-26.765 0-14.158 0 1.337c0 23.286 24.535 42.952 28.39 46.04.24.192.402.316.471.376.323.282.732.424 1.142.424.41 0 .82-.142 1.142-.424.068-.06.231-.183.471-.376 3.856-3.09 28.39-22.754 28.39-46.04 0-15.495-13.46-28.102-30.003-28.102Zm1.757 12.469c4.38 0 7.858 1.052 10.431 3.158 2.595 2.105 3.89 4.913 3.89 8.422 0 2.34-.53 4.362-1.593 6.063-1.063 1.702-3.086 3.616-6.063 5.742-2.042 1.51-3.337 2.659-3.89 3.446-.532.787-.8 1.82-.8 3.096v1.914h-8.449V15.18c0-2.041.434-3.815 1.306-5.325.872-1.51 2.467-3.118 4.785-4.82 2.233-1.594 3.7-2.89 4.402-3.889a5.582 5.582 0 0 0 1.087-3.35c0-1.382-.51-2.435-1.531-3.158-1.02-.723-2.45-1.087-4.28-1.087-3.19 0-6.826 1.047-10.91 3.131l-3.472-6.986c4.742-2.659 9.77-3.992 15.087-3.992Zm-1.88 37.324c1.765 0 3.124.472 4.08 1.408.98.936 1.47 2.276 1.47 4.02 0 1.68-.49 3.007-1.47 3.985-.977.957-2.336 1.435-4.08 1.435-1.787 0-3.171-.465-4.15-1.4-.978-.958-1.47-2.298-1.47-4.02 0-1.787.48-3.14 1.436-4.054.957-.915 2.355-1.374 4.184-1.374Z"),S(e,"viewBox","0 0 60.006 21.412"),S(e,"width","14"),S(e,"height","20"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class ur extends Je{constructor(e){super(),Xe(this,e,null,lr,Ke,{})}}function ar(i){let e,t,n;return{c(){e=ke("svg"),t=ke("circle"),n=ke("path"),S(t,"cx","4.789"),S(t,"cy","4.787"),S(t,"r","3.85"),S(t,"class","svelte-1aq105l"),S(n,"d","M12.063 12.063 7.635 7.635"),S(n,"class","svelte-1aq105l"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"width","13"),S(e,"height","13"),S(e,"viewBox","0 0 13 13"),S(e,"class","svelte-1aq105l")},m(r,u){te(r,e,u),V(e,t),V(e,n)},p:ne,i:ne,o:ne,d(r){r&&$(e)}}}class fr extends Je{constructor(e){super(),Xe(this,e,null,ar,Ke,{})}}function cr(i,e,t){const n=e[1],r=e[0],u=n-r;return i===n&&t?i:((i-r)%u+u)%u+r}function Bt(i){const e=[...i];return e[2]Math.abs((e[0]-360+e[2])/2)?e[0]-=360:e[2]+=360),e}let bt;async function hr(i,e,t){const n=i==null?void 0:i.getCenterAndZoom();for(const r of e??[])if(!(n&&(r.minZoom!=null&&r.minZoom>n[0]||r.maxZoom!=null&&r.maxZoomDate.now()){if(!bt.coords)break e;return bt.coords}let u;try{return u=await new Promise((a,o)=>{t.signal.addEventListener("abort",()=>{o(Error("aborted"))}),navigator.geolocation.getCurrentPosition(g=>{a([g.coords.longitude,g.coords.latitude].map(c=>c.toFixed(6)).join(","))},g=>{o(g)},r)}),u}catch{}finally{r.cachedLocationExpiry&&(bt={time:Date.now(),coords:u})}if(t.signal.aborted)return}if(r.type==="server-geolocation")return"ip";if(n&&r.type==="map-center")return n[1].toFixed(6)+","+n[2].toFixed(6)}}const dr=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(EAST|WEST|[EW])?$/i,Oi=/^([+-]?[0-8]?[0-9])\s+([0-5]?[0-9]\.\d{3,})[\s,]{1,}([+-]?[0-1]?[0-9]?[0-9])\s+([0-5]?[0-9]\.\d{3,})$/,Ri=/^(NORTH|SOUTH|[NS])?[\s]*([+-]?[0-8]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(NORTH|SOUTH|[NS])?[\s]*[,/;]?[\s]*(EAST|WEST|[EW])?[\s]*([+-]?[0-1]?[0-9]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(EAST|WEST|[EW])?$/i,Pi=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(EAST|WEST|[EW])?$/i,Ii=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)\s*(EAST|WEST|[EW])?$/i,Ai=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|’’|´´|["″”\.])?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|´´|’’|["″”\.])?\s*(EAST|WEST|[EW])?$/i;function gr(i){if(!["DMS","DM","DD"].includes(i))throw new Error("invalid format specified");if(this.decimalCoordinates&&this.decimalCoordinates.trim()){const e=this.decimalCoordinates.split(",").map(R=>Number(R.trim())),t=Number(e[0]),n=Number(e[1]),r=Math.abs(t),u=Math.abs(n),a=t>0?"N":"S",o=n>0?"E":"W";let g;i=="DD"&&(g=`${r}° ${a}, ${u}° ${o}`);const c=Math.floor(r),E=Math.floor(u),_=(r-c)*60,M=(u-E)*60;if(i=="DM"){let R=Bi(_,3).toFixed(3).padStart(6,"0"),k=Bi(M,3).toFixed(3).padStart(6,"0");R.endsWith(".000")&&k.endsWith(".000")&&(R=R.replace(/\.000$/,""),k=k.replace(/\.000$/,"")),g=`${c}° ${R}' ${a}, ${E}° ${k}' ${o}`}if(i=="DMS"){const R=Math.floor(_),k=Math.floor(M);let I=((_-R)*60).toFixed(1).padStart(4,"0"),C=((M-k)*60).toFixed(1).padStart(4,"0");const O=R.toString().padStart(2,"0"),x=k.toString().padStart(2,"0");I.endsWith(".0")&&C.endsWith(".0")&&(I=I.replace(/\.0$/,""),C=C.replace(/\.0$/,"")),g=`${c}° ${O}' ${I}" ${a}, ${E}° ${x}' ${C}" ${o}`}return g}else throw new Error("no decimal coordinates to convert")}function Bi(i,e){const t=Math.pow(10,e);return Math.round((i+Number.EPSILON)*t)/t}function ei(i,e){e||(e=5),i=i.replace(/\s+/g," ").trim();let t=null,n=null,r="",u="",a=null,o=[],g=!1;if(dr.test(i))throw new Error("invalid coordinate value");if(Oi.test(i))if(o=Oi.exec(i),g=wt(o),g)t=Math.abs(o[1])+o[2]/60,Number(o[1])<0&&(t*=-1),n=Math.abs(o[3])+o[4]/60,Number(o[3])<0&&(n*=-1),a="DM";else throw new Error("invalid coordinate format");else if(Ri.test(i))if(o=Ri.exec(i),g=wt(o),g){if(t=o[2],n=o[6],t.includes(",")&&(t=t.replace(",",".")),n.includes(",")&&(n=n.replace(",",".")),a="DD",Number(Math.round(t))==Number(t))throw new Error("integer only coordinate provided");if(Number(Math.round(n))==Number(n))throw new Error("integer only coordinate provided");o[1]?(r=o[1],u=o[5]):o[4]&&(r=o[4],u=o[8])}else throw new Error("invalid decimal coordinate format");else if(Pi.test(i))if(o=Pi.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[9])),o[11]&&(n+=o[11]/60),o[13]&&(n+=o[13].replace(",",".")/3600),parseInt(o[9])<0&&(n=-1*n),o[1]?(r=o[1],u=o[8]):o[7]&&(r=o[7],u=o[14]);else throw new Error("invalid DMS coordinates format");else if(Ii.test(i))if(o=Ii.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6]/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12]/60),o[14]&&(n+=o[14]/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid DMS coordinates format");else if(Ai.test(i)){if(o=Ai.exec(i),g=wt(o),o.filter(c=>c).length<=5)throw new Error("invalid coordinates format");if(g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4].replace(",",".")/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12].replace(",",".")/60),o[14]&&(n+=o[14].replace(",",".")/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid coordinates format")}if(g){if(Math.abs(n)>=180)throw new Error("invalid longitude value");if(Math.abs(t)>=90)throw new Error("invalid latitude value");if(r&&!u||!r&&u)throw new Error("invalid coordinates value");if(r&&r==u)throw new Error("invalid coordinates format");t.toString().includes(",")&&(t=t.replace(",",".")),n.toString().includes(",")&&(n=n.replace(",","."));let c=/S|SOUTH/i;c.test(r)&&t>0&&(t=-1*t),c=/W|WEST/i,c.test(u)&&n>0&&(n=-1*n);const E=o[0].trim();let _,M;const R=/[,/;\u0020]/g,k=E.match(R);if(k==null){const O=Math.floor(i.length/2);_=E.substring(0,O).trim(),M=E.substring(O).trim()}else{let O;k.length%2==1?O=Math.floor(k.length/2):O=k.length/2-1;let x=0;if(O==0)x=E.indexOf(k[0]),_=E.substring(0,x).trim(),M=E.substring(x+1).trim();else{let N=0,P=0;for(;N<=O;)x=E.indexOf(k[N],P),P=x+1,N++;_=E.substring(0,x).trim(),M=E.substring(x+1).trim()}}const I=_.split(".");if(I.length==2&&I[1]==0&&I[1].length!=2)throw new Error("invalid coordinates format");const C=M.split(".");if(C.length==2&&C[1]==0&&C[1].length!=2)throw new Error("invalid coordinates format");if(/^\d+$/.test(_)||/^\d+$/.test(M))throw new Error("degree only coordinate/s provided");return t=Number(Number(t).toFixed(e)),n=Number(Number(n).toFixed(e)),Object.freeze({verbatimCoordinates:E,verbatimLatitude:_,verbatimLongitude:M,decimalLatitude:t,decimalLongitude:n,decimalCoordinates:`${t},${n}`,originalFormat:a,closeEnough:mr,toCoordinateFormat:gr})}else throw new Error("coordinates pattern match failed")}function wt(i){if(!isNaN(i[0]))return!1;const e=[...i];if(e.shift(),e.length%2>0)return!1;const t=/^[-+]?\d+([\.,]\d+)?$/,n=/[eastsouthnorthwest]+/i,r=e.length/2;for(let u=0;u{e.decimalLatitude?i.push(e):i.push({...e,...vr})}),[...i,...br,...wr]}const Lr=Er();ei.formats=Lr.map(i=>i.verbatimCoordinates);const _r=ei;function Gi(i,e,t){const n=i.slice();return n[97]=e[t],n[99]=t,n}function Di(i){let e,t,n,r,u;return t=new Mi({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[3]),S(e,"class","svelte-bz0zu3")},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[78]),r=!0)},p(a,o){(!n||o[0]&8)&&S(e,"title",a[3])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function zi(i){let e,t;return e=new nr({}),{c(){Qe(e.$$.fragment)},m(n,r){qe(e,n,r),t=!0},i(n){t||(re(e.$$.fragment,n),t=!0)},o(n){fe(e.$$.fragment,n),t=!1},d(n){Fe(e,n)}}}function Ui(i){let e,t,n,r,u;return t=new ur({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[10]),S(e,"class","svelte-bz0zu3"),Ie(e,"active",i[0])},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[79]),r=!0)},p(a,o){(!n||o[0]&1024)&&S(e,"title",a[10]),(!n||o[0]&1)&&Ie(e,"active",a[0])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function Sr(i){let e,t=[],n=new Map,r,u,a,o=Ti(i[13]);const g=c=>c[97].id+(c[97].address?","+c[97].address:"");for(let c=0;c{B=null}),vt()):B?(B.p(d,v),v[0]&1048576&&re(B,1)):(B=Di(d),B.c(),re(B,1),B.m(c,E)),d[20]?z?v[0]&1048576&&re(z,1):(z=zi(),z.c(),re(z,1),z.m(c,null)):z&&(yt(),fe(z,1,1,()=>{z=null}),vt()),(!O||v[0]&2)&&Ie(c,"displayable",d[1]!==""),d[6]==="button"?W?(W.p(d,v),v[0]&64&&re(W,1)):(W=Ui(d),W.c(),re(W,1),W.m(n,M)):W&&(yt(),fe(W,1,1,()=>{W=null}),vt()),l&&l.p&&(!O||v[2]&128)&&Tn(l,s,d,d[69],O?xn(s,d[69],v,null):Mn(d[69]),null);let p=k;k=h(d),k===p?~k&&m[k].p(d,v):(I&&(yt(),fe(m[p],1,1,()=>{m[p]=null}),vt()),~k?(I=m[k],I?I.p(d,v):(I=m[k]=f[k](d),I.c()),re(I,1),I.m(t,null)):I=null),(!O||v[0]&4&&C!==(C=Pt(d[2])+" svelte-bz0zu3"))&&S(t,"class",C),(!O||v[0]&38)&&Ie(t,"can-collapse",d[5]&&d[1]==="")},i(d){O||(re(P),re(u.$$.fragment,d),re(B),re(z),re(W),re(l,d),re(I),O=!0)},o(d){fe(P),fe(u.$$.fragment,d),fe(B),fe(z),fe(W),fe(l,d),fe(I),O=!1},d(d){d&&($(e),$(t)),Fe(u),i[72](null),B&&B.d(),z&&z.d(),W&&W.d(),l&&l.d(d),~k&&m[k].d(),x=!1,Ue(N)}}}function Nr(i,e,t){let n,r,u,{$$slots:a={},$$scope:o}=e;const g={continental_marine:4,country:4,major_landform:8,region:5,subregion:6,county:7,joint_municipality:8,joint_submunicipality:9,municipality:10,municipal_district:11,locality:12,neighbourhood:13,place:14,postal_code:14,road:16,poi:17,address:18,"poi.peak":15,"poi.shop":18,"poi.cafe":18,"poi.restaurant":18,"poi.aerodrome":13};let{class:c=void 0}=e,{apiKey:E=void 0}=e,{bbox:_=void 0}=e,{clearButtonTitle:M="clear"}=e,{clearOnBlur:R=!1}=e,{clearListOnPick:k=!1}=e,{keepListOpen:I=!1}=e,{collapsed:C=!1}=e,{country:O=void 0}=e,{debounceSearch:x=200}=e,{enableReverse:N="never"}=e,{errorMessage:P="Something went wrong…"}=e,{filter:B=()=>!0}=e,{flyTo:z=!0}=e,{fuzzyMatch:W=!0}=e,{language:s=void 0}=e,{limit:l=void 0}=e;const f=41415112612;let{reverseGeocodingLimit:m=f}=e,{mapController:h=void 0}=e,{minLength:d=2}=e,{noResultsMessage:v="Oops! Looks like you're trying to predict something that's not quite right. We can't seem to find what you're looking for. Maybe try double-checking your spelling or try a different search term. Keep on typing - we'll do our best to get you where you need to go!"}=e,{placeholder:p="Search"}=e,{proximity:y=[{type:"server-geolocation"}]}=e,{reverseActive:b=N==="always"}=e,{reverseButtonTitle:w="toggle reverse geocoding"}=e,{searchValue:T=""}=e,{pickedResultStyle:G="full-geometry"}=e,{showPlaceType:D="if-needed"}=e,{showResultsWhileTyping:H=!0}=e,{selectFirst:Q=!0}=e,{flyToSelected:se=!1}=e,{markerOnSelected:Z=!0}=e,{types:K=void 0}=e;const de=[];let{reverseGeocodingTypes:He=de}=e,{exhaustiveReverseGeocoding:st=!1}=e,{excludeTypes:ot=!1}=e;const Le=void 0;let{reverseGeocodingExcludeTypes:We=Le}=e,{zoom:pe=g}=e,{apiUrl:ge="https://api.maptiler.com/geocoding"}=e,{fetchParameters:ie={}}=e,{iconsBaseUrl:hn="https://cdn.maptiler.com/maptiler-geocoding-control/v2.1.7/icons/"}=e,{adjustUrlQuery:ui=()=>{}}=e,{adjustUrl:ai=()=>{}}=e;function gs(L){Pe.focus(L)}function ms(){Pe.blur()}function dn(L,le=!0,ae=!1){t(1,T=L),le?(t(15,X=-1),mn()):(pn(void 0,!ae,ae),setTimeout(()=>{Pe.focus(),Pe.select()}))}function ps(){t(13,F=void 0),t(14,U=void 0),t(15,X=-1)}function ys(){t(64,ce=[]),t(14,U=void 0)}let F,ce,U,gn="",Pe,X=-1,Ge,Zt=[],lt,ct,ht,fi,Ve=!1;const vs=new Set,tt=_i();Rn(()=>{h&&(h.setEventHandler(void 0),h.indicateReverse(!1),h.setSelectedMarker(-1),h.setFeatures(void 0,void 0,!1))});function mn(L){if(t(17,Ve=!1),ct&&(clearTimeout(ct),ct=void 0),X>-1&&F)t(14,U=F[X]),t(1,T=U.place_type[0]==="reverse"?U.place_name:U.place_name.replace(/,.*/,"")),t(19,Ge=void 0),t(64,ce=void 0),t(15,X=-1);else if(T){const le=L||!ci(T);hi(T,{exact:!0}).then(()=>{t(64,ce=F),t(14,U=void 0),le&&bs()}).catch(ae=>t(19,Ge=ae))}}function ci(L){try{return _r(L,6)}catch{return!1}}async function hi(L,{byId:le=!1,exact:ae=!1}={}){var Se,De,it;t(19,Ge=void 0),lt==null||lt.abort();const _e=new AbortController;t(20,lt=_e);try{const J=ci(L),Mt=new URL(ge+"/"+encodeURIComponent(J?J.decimalLongitude+","+J.decimalLatitude:L)+".json"),Ne=Mt.searchParams;s!==void 0&&Ne.set("language",Array.isArray(s)?s.join(","):s??"");const[mi]=(h==null?void 0:h.getCenterAndZoom())??[];let ze=(Se=!J||He===de?K:He)==null?void 0:Se.map(ve=>typeof ve=="string"?ve:mi===void 0||(ve[0]??0)<=mi&&mi<(ve[1]??1/0)?ve[2]:void 0).filter(ve=>ve!==void 0);ze&&(ze=[...new Set(ze)],Ne.set("types",ze.join(",")));const vn=!J||We===Le?ot:We;if(vn&&Ne.set("excludeTypes",String(vn)),_&&Ne.set("bbox",_.map(ve=>ve.toFixed(6)).join(",")),O&&Ne.set("country",Array.isArray(O)?O.join(","):O),!le&&!J){const ve=await hr(h,y,_e);ve&&Ne.set("proximity",ve),(ae||!H)&&Ne.set("autocomplete","false"),Ne.set("fuzzyMatch",String(W))}const Ct=m===f?l:m;Ct!==void 0&&Ct>1&&(ze==null?void 0:ze.length)!==1&&console.warn("For reverse geocoding when limit > 1 then types must contain single value."),J?(Ct===1||Ct!==void 0&&(st||(ze==null?void 0:ze.length)===1))&&Ne.set("limit",String(Ct)):l!==void 0&&Ne.set("limit",String(l)),E&&Ne.set("key",E),ui(Ne),ai(Mt);const Bs=Mt.searchParams.get("types")===""&&Mt.searchParams.get("excludeTypes")!=="true",Ht=Mt.toString();if(Ht===gn){le?(k&&t(13,F=void 0),t(14,U=Zt[0])):(t(13,F=Zt),((De=F[X])==null?void 0:De.id)!==(r==null?void 0:r.id)&&t(15,X=-1));return}gn=Ht;let Nt;if(Bs)Nt={type:"FeatureCollection",features:[]};else{const ve=await fetch(Ht,{signal:_e.signal,...ie});if(!ve.ok)throw new Error(await ve.text());Nt=await ve.json()}tt("response",{url:Ht,featureCollection:Nt}),le?(k&&t(13,F=void 0),t(14,U=Nt.features[0]),Zt=[U]):(t(13,F=Nt.features.filter(B)),J&&F.unshift({type:"Feature",properties:{},id:"reverse_"+J.decimalLongitude+"_"+J.decimalLatitude,text:J.decimalLatitude+", "+J.decimalLongitude,place_name:J.decimalLatitude+", "+J.decimalLongitude,place_type:["reverse"],center:[J.decimalLongitude,J.decimalLatitude],bbox:[J.decimalLongitude,J.decimalLatitude,J.decimalLongitude,J.decimalLatitude],geometry:{type:"Point",coordinates:[J.decimalLongitude,J.decimalLatitude]}}),Zt=F,((it=F[X])==null?void 0:it.id)!==(r==null?void 0:r.id)&&t(15,X=-1),J&&Pe.focus())}catch(J){if(J&&typeof J=="object"&&"name"in J&&J.name==="AbortError")return;throw J}finally{_e===lt&&t(20,lt=void 0)}}function bs(){var _e;if(!(ce!=null&&ce.length)||!z)return;const L=[180,90,-180,-90],le=!ce.some(Se=>!Se.matching_text);let ae;for(const Se of ce){const De=Tt(Se);if(ae=ae===void 0?De:De===void 0?ae:Math.max(ae,De),le||!Se.matching_text)for(const it of[0,1,2,3])L[it]=Math[it<2?"min":"max"](L[it],((_e=Se.bbox)==null?void 0:_e[it])??Se.center[it%2])}h&&ce.length>0&&(U&&L[0]===L[2]&&L[1]===L[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(L),50,ae))}function di(){!U||!h||(!U.bbox||U.bbox[0]===U.bbox[2]&&U.bbox[1]===U.bbox[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(U.bbox),50,Tt(U)))}function Tt(L){var ae;if(!L.bbox||L.bbox[0]!==L.bbox[2]&&L.bbox[1]!==L.bbox[3])return;const le=L.id.replace(/\..*/,"");return(Array.isArray((ae=L.properties)==null?void 0:ae.categories)?L.properties.categories.reduce((_e,Se)=>{const De=pe[le+"."+Se];return _e===void 0?De:De===void 0?_e:Math.max(_e,De)},void 0):void 0)??pe[le]}function ws(L){t(0,b=N==="always"),t(13,F=void 0),t(14,U=void 0),t(15,X=-1),dn(L[1].toFixed(6)+", "+cr(L[0],[-180,180],!0).toFixed(6),!1,!0)}function Es(L){if(!F)return;let le=L.key==="ArrowDown"?1:L.key==="ArrowUp"?-1:0;le&&(Pe.focus(),t(17,Ve=!0),L.preventDefault(),U&&X===-1&&t(15,X=F.findIndex(ae=>ae.id===(U==null?void 0:U.id))),X===(U||Q?0:-1)&&le===-1&&t(15,X=F.length),t(15,X+=le),X>=F.length&&t(15,X=-1),X<0&&(U||Q)&&t(15,X=0))}function pn(L,le=!0,ae=!1){if(t(19,Ge=void 0),t(14,U=void 0),t(17,Ve=!0),H||ae){if(ct&&clearTimeout(ct),T.length{hi(_e).catch(Se=>t(19,Ge=Se))},le?x:0)}else t(13,F=void 0),t(19,Ge=void 0)}function gi(L){U&&(U==null?void 0:U.id)===(L==null?void 0:L.id)?di():(t(14,U=L),t(1,T=L.place_name))}function yn(L){t(15,X=L)}function Ls(){(!Q||U)&&t(15,X=-1),se&&di()}const _s=()=>Pe.focus();function Ss(L){Yt[L?"unshift":"push"](()=>{Pe=L,t(18,Pe)})}function xs(){T=this.value,t(1,T),t(17,Ve),t(31,R),t(16,ht)}const Ts=()=>t(17,Ve=!0),Ms=()=>t(17,Ve=!1),Cs=()=>t(17,Ve=!0),Ns=()=>t(14,U=void 0),ks=()=>{t(1,T=""),t(14,U=void 0),Pe.focus()},Os=()=>t(0,b=!b),Rs=()=>t(19,Ge=void 0),Ps=L=>yn(L),Is=L=>gi(L),As=()=>{};return i.$$set=L=>{"class"in L&&t(2,c=L.class),"apiKey"in L&&t(29,E=L.apiKey),"bbox"in L&&t(30,_=L.bbox),"clearButtonTitle"in L&&t(3,M=L.clearButtonTitle),"clearOnBlur"in L&&t(31,R=L.clearOnBlur),"clearListOnPick"in L&&t(32,k=L.clearListOnPick),"keepListOpen"in L&&t(4,I=L.keepListOpen),"collapsed"in L&&t(5,C=L.collapsed),"country"in L&&t(33,O=L.country),"debounceSearch"in L&&t(34,x=L.debounceSearch),"enableReverse"in L&&t(6,N=L.enableReverse),"errorMessage"in L&&t(7,P=L.errorMessage),"filter"in L&&t(35,B=L.filter),"flyTo"in L&&t(36,z=L.flyTo),"fuzzyMatch"in L&&t(37,W=L.fuzzyMatch),"language"in L&&t(38,s=L.language),"limit"in L&&t(39,l=L.limit),"reverseGeocodingLimit"in L&&t(40,m=L.reverseGeocodingLimit),"mapController"in L&&t(41,h=L.mapController),"minLength"in L&&t(42,d=L.minLength),"noResultsMessage"in L&&t(8,v=L.noResultsMessage),"placeholder"in L&&t(9,p=L.placeholder),"proximity"in L&&t(43,y=L.proximity),"reverseActive"in L&&t(0,b=L.reverseActive),"reverseButtonTitle"in L&&t(10,w=L.reverseButtonTitle),"searchValue"in L&&t(1,T=L.searchValue),"pickedResultStyle"in L&&t(44,G=L.pickedResultStyle),"showPlaceType"in L&&t(11,D=L.showPlaceType),"showResultsWhileTyping"in L&&t(45,H=L.showResultsWhileTyping),"selectFirst"in L&&t(46,Q=L.selectFirst),"flyToSelected"in L&&t(47,se=L.flyToSelected),"markerOnSelected"in L&&t(48,Z=L.markerOnSelected),"types"in L&&t(49,K=L.types),"reverseGeocodingTypes"in L&&t(50,He=L.reverseGeocodingTypes),"exhaustiveReverseGeocoding"in L&&t(51,st=L.exhaustiveReverseGeocoding),"excludeTypes"in L&&t(52,ot=L.excludeTypes),"reverseGeocodingExcludeTypes"in L&&t(53,We=L.reverseGeocodingExcludeTypes),"zoom"in L&&t(54,pe=L.zoom),"apiUrl"in L&&t(55,ge=L.apiUrl),"fetchParameters"in L&&t(56,ie=L.fetchParameters),"iconsBaseUrl"in L&&t(12,hn=L.iconsBaseUrl),"adjustUrlQuery"in L&&t(57,ui=L.adjustUrlQuery),"adjustUrl"in L&&t(58,ai=L.adjustUrl),"$$scope"in L&&t(69,o=L.$$scope)},i.$$.update=()=>{if(i.$$.dirty[0]&64&&t(0,b=N==="always"),i.$$.dirty[0]&16384|i.$$.dirty[1]&8192&&G!=="marker-only"&&U&&!U.address&&U.geometry.type==="Point"&&U.place_type[0]!=="reverse"&&hi(U.id,{byId:!0}).catch(L=>t(19,Ge=L)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1058|i.$$.dirty[2]&8&&(h&&U&&U.id!==fi&&z&&(di(),k&&t(13,F=void 0),t(64,ce=void 0),t(15,X=-1)),t(65,fi=U==null?void 0:U.id)),i.$$.dirty[0]&196608|i.$$.dirty[1]&1&&setTimeout(()=>{t(16,ht=Ve),R&&!ht&&t(1,T="")}),i.$$.dirty[0]&8194|i.$$.dirty[1]&2048&&T.length{switch(L.type){case"mapClick":b&&ws(L.coordinates);break;case"markerClick":{const le=F==null?void 0:F.find(ae=>ae.id===L.id);le&&gi(le)}break;case"markerMouseEnter":ce&&t(15,X=ht?(F==null?void 0:F.findIndex(le=>le.id===L.id))??-1:-1);break;case"markerMouseLeave":ce&&t(15,X=-1);break}}),i.$$.dirty[0]&40960&&t(66,r=F==null?void 0:F[X]),i.$$.dirty[1]&66592|i.$$.dirty[2]&16&&h&&r&&z&&se&&h.flyTo(r.center,Tt(r)),i.$$.dirty[1]&8192&&t(68,n=G==="full-geometry-including-polygon-center-marker"),i.$$.dirty[1]&132096|i.$$.dirty[2]&64&&(Z||h==null||h.setFeatures(void 0,void 0,n)),i.$$.dirty[0]&16384|i.$$.dirty[1]&132096|i.$$.dirty[2]&84&&h&&Z&&!ce&&(h.setFeatures(r?[r]:void 0,U,n),h.setSelectedMarker(r?0:-1)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1024|i.$$.dirty[2]&68&&h&&h.setFeatures(ce,U,n),i.$$.dirty[0]&32768|i.$$.dirty[1]&1024|i.$$.dirty[2]&4&&ce&&h&&h.setSelectedMarker(X),i.$$.dirty[0]&2|i.$$.dirty[1]&1024&&h){const L=ci(T);h.setReverseMarker(L?[L.decimalLongitude,L.decimalLatitude]:void 0)}i.$$.dirty[2]&16&&tt("select",{feature:r}),i.$$.dirty[0]&16384&&tt("pick",{feature:U}),i.$$.dirty[0]&73744&&t(67,u=!!(F!=null&&F.length)&&(ht||I)),i.$$.dirty[2]&32&&tt("optionsvisibilitychange",{optionsVisible:u}),i.$$.dirty[0]&8192&&tt("featureslisted",{features:F}),i.$$.dirty[2]&4&&tt("featuresmarked",{features:ce}),i.$$.dirty[0]&1&&tt("reversetoggle",{reverse:b}),i.$$.dirty[0]&2&&tt("querychange",{query:T}),i.$$.dirty[0]&1|i.$$.dirty[1]&1024&&h&&h.indicateReverse(b)},[b,T,c,M,I,C,N,P,v,p,w,D,hn,F,U,X,ht,Ve,Pe,Ge,lt,vs,mn,Es,pn,gi,yn,Ls,g,E,_,R,k,O,x,B,z,W,s,l,m,h,d,y,G,H,Q,se,Z,K,He,st,ot,We,pe,ge,ie,ui,ai,gs,ms,dn,ps,ys,ce,fi,r,u,n,o,a,_s,Ss,xs,Ts,Ms,Cs,Ns,ks,Os,Rs,Ps,Is,As]}let kr=class extends Je{constructor(e){super(),Xe(this,e,Nr,Cr,Ke,{ZOOM_DEFAULTS:28,class:2,apiKey:29,bbox:30,clearButtonTitle:3,clearOnBlur:31,clearListOnPick:32,keepListOpen:4,collapsed:5,country:33,debounceSearch:34,enableReverse:6,errorMessage:7,filter:35,flyTo:36,fuzzyMatch:37,language:38,limit:39,reverseGeocodingLimit:40,mapController:41,minLength:42,noResultsMessage:8,placeholder:9,proximity:43,reverseActive:0,reverseButtonTitle:10,searchValue:1,pickedResultStyle:44,showPlaceType:11,showResultsWhileTyping:45,selectFirst:46,flyToSelected:47,markerOnSelected:48,types:49,reverseGeocodingTypes:50,exhaustiveReverseGeocoding:51,excludeTypes:52,reverseGeocodingExcludeTypes:53,zoom:54,apiUrl:55,fetchParameters:56,iconsBaseUrl:12,adjustUrlQuery:57,adjustUrl:58,focus:59,blur:60,setQuery:61,clearList:62,clearMap:63},null,[-1,-1,-1,-1])}get ZOOM_DEFAULTS(){return this.$$.ctx[28]}get focus(){return this.$$.ctx[59]}get blur(){return this.$$.ctx[60]}get setQuery(){return this.$$.ctx[61]}get clearList(){return this.$$.ctx[62]}get clearMap(){return this.$$.ctx[63]}};function Et(i,e,t={}){const n={type:"Feature"};return(t.id===0||t.id)&&(n.id=t.id),t.bbox&&(n.bbox=t.bbox),n.properties=e||{},n.geometry=i,n}function ti(i,e,t={}){for(const r of i){if(r.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(r[r.length-1].length!==r[0].length)throw new Error("First and last Position are not equivalent.");for(let u=0;u_?w.c=w.e=null:s.e=10;v/=10,d++);d>_?w.c=w.e=null:(w.e=d,w.c=[s]);return}b=String(s)}else{if(!Or.test(b=String(s)))return n(w,b,p);w.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(v=b.search(/e/i))>0?(d<0&&(d=v),d+=+b.slice(v+1),b=b.substring(0,v)):d<0&&(d=b.length)}else{if(oe(l,2,C.length,"Base"),l==10&&O)return w=new x(s),z(w,a+w.e+1,o);if(b=String(s),p=typeof s=="number"){if(s*0!=0)return n(w,b,p,l);if(w.s=1/s<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(ji+s)}else w.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(f=C.slice(0,l),d=v=0,y=b.length;vd){d=y;continue}}else if(!h&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){h=!0,v=-1,d=0;continue}return n(w,String(s),p,l)}p=!1,b=t(b,l,10,w.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(v=0;b.charCodeAt(v)===48;v++);for(y=b.length;b.charCodeAt(--y)===48;);if(b=b.slice(v,++y)){if(y-=v,p&&x.DEBUG&&y>15&&(s>Zi||s!==Te(s)))throw Error(ji+w.s*s);if((d=d-v-1)>_)w.c=w.e=null;else if(d=-1e9&&h<=Ee&&h===Te(h)){if(m[0]===0){if(h===0&&m.length===1)return!0;break e}if(l=(h+1)%q,l<1&&(l+=q),String(m[0]).length==l){for(l=0;l=Re||f!==Te(f))break e;if(f!==0)return!0}}}else if(m===null&&h===null&&(d===null||d===1||d===-1))return!0;throw Error(be+"Invalid BigNumber: "+s)},x.maximum=x.max=function(){return P(arguments,-1)},x.minimum=x.min=function(){return P(arguments,1)},x.random=function(){var s=9007199254740992,l=Math.random()*s&2097151?function(){return Te(Math.random()*s)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(f){var m,h,d,v,p,y=0,b=[],w=new x(u);if(f==null?f=a:oe(f,0,Ee),v=ii(f/q),M)if(crypto.getRandomValues){for(m=crypto.getRandomValues(new Uint32Array(v*=2));y>>11),p>=9e15?(h=crypto.getRandomValues(new Uint32Array(2)),m[y]=h[0],m[y+1]=h[1]):(b.push(p%1e14),y+=2);y=v/2}else if(crypto.randomBytes){for(m=crypto.randomBytes(v*=7);y=9e15?crypto.randomBytes(7).copy(m,y):(b.push(p%1e14),y+=7);y=v/7}else throw M=!1,Error(be+"crypto unavailable");if(!M)for(;y=10;p/=10,y++);yh-1&&(p[v+1]==null&&(p[v+1]=0),p[v+1]+=p[v]/h|0,p[v]%=h)}return p.reverse()}return function(f,m,h,d,v){var p,y,b,w,T,G,D,H,Q=f.indexOf("."),se=a,Z=o;for(Q>=0&&(w=k,k=0,f=f.replace(".",""),H=new x(m),G=H.pow(f.length-Q),k=w,H.c=l(je(Ce(G.c),G.e,"0"),10,h,s),H.e=H.c.length),D=l(f,m,h,v?(p=C,s):(p=s,C)),b=w=D.length;D[--w]==0;D.pop());if(!D[0])return p.charAt(0);if(Q<0?--b:(G.c=D,G.e=b,G.s=d,G=e(G,H,se,Z,h),D=G.c,T=G.r,b=G.e),y=b+se+1,Q=D[y],w=h/2,T=T||y<0||D[y+1]!=null,T=Z<4?(Q!=null||T)&&(Z==0||Z==(G.s<0?3:2)):Q>w||Q==w&&(Z==4||T||Z==6&&D[y-1]&1||Z==(G.s<0?8:7)),y<1||!D[0])f=T?je(p.charAt(1),-se,p.charAt(0)):p.charAt(0);else{if(D.length=y,T)for(--h;++D[--y]>h;)D[y]=0,y||(++b,D=[1].concat(D));for(w=D.length;!D[--w];);for(Q=0,f="";Q<=w;f+=p.charAt(D[Q++]));f=je(f,b,p.charAt(0))}return f}}(),e=function(){function s(m,h,d){var v,p,y,b,w=0,T=m.length,G=h%$e,D=h/$e|0;for(m=m.slice();T--;)y=m[T]%$e,b=m[T]/$e|0,v=D*y+b*G,p=G*y+v%$e*$e+w,w=(p/d|0)+(v/$e|0)+D*b,m[T]=p%d;return w&&(m=[w].concat(m)),m}function l(m,h,d,v){var p,y;if(d!=v)y=d>v?1:-1;else for(p=y=0;ph[p]?1:-1;break}return y}function f(m,h,d,v){for(var p=0;d--;)m[d]-=p,p=m[d]1;m.splice(0,1));}return function(m,h,d,v,p){var y,b,w,T,G,D,H,Q,se,Z,K,de,He,st,ot,Le,We,pe=m.s==h.s?1:-1,ge=m.c,ie=h.c;if(!ge||!ge[0]||!ie||!ie[0])return new x(!m.s||!h.s||(ge?ie&&ge[0]==ie[0]:!ie)?NaN:ge&&ge[0]==0||!ie?pe*0:pe/0);for(Q=new x(pe),se=Q.c=[],b=m.e-h.e,pe=d+b+1,p||(p=Re,b=Me(m.e/q)-Me(h.e/q),pe=pe/q|0),w=0;ie[w]==(ge[w]||0);w++);if(ie[w]>(ge[w]||0)&&b--,pe<0)se.push(1),T=!0;else{for(st=ge.length,Le=ie.length,w=0,pe+=2,G=Te(p/(ie[0]+1)),G>1&&(ie=s(ie,G,p),ge=s(ge,G,p),Le=ie.length,st=ge.length),He=Le,Z=ge.slice(0,Le),K=Z.length;K=p/2&&ot++;do{if(G=0,y=l(ie,Z,Le,K),y<0){if(de=Z[0],Le!=K&&(de=de*p+(Z[1]||0)),G=Te(de/ot),G>1)for(G>=p&&(G=p-1),D=s(ie,G,p),H=D.length,K=Z.length;l(D,Z,H,K)==1;)G--,f(D,Le=10;pe/=10,w++);z(Q,d+(Q.e=w+b*q-1)+1,v,T)}else Q.e=b,Q.r=+T;return Q}}();function N(s,l,f,m){var h,d,v,p,y;if(f==null?f=o:oe(f,0,8),!s.c)return s.toString();if(h=s.c[0],v=s.e,l==null)y=Ce(s.c),y=m==1||m==2&&(v<=g||v>=c)?Gt(y,v):je(y,v,"0");else if(s=z(new x(s),l,f),d=s.e,y=Ce(s.c),p=y.length,m==1||m==2&&(l<=d||d<=g)){for(;pp){if(--l>0)for(y+=".";l--;y+="0");}else if(l+=d-p,l>0)for(d+1==p&&(y+=".");l--;y+="0");return s.s<0&&h?"-"+y:y}function P(s,l){for(var f,m,h=1,d=new x(s[0]);h=10;h/=10,m++);return(f=m+f*q-1)>_?s.c=s.e=null:f=10;p/=10,h++);if(d=l-h,d<0)d+=q,v=l,y=T[b=0],w=Te(y/G[h-v-1]%10);else if(b=ii((d+1)/q),b>=T.length)if(m){for(;T.length<=b;T.push(0));y=w=0,h=1,d%=q,v=d-q+1}else break e;else{for(y=p=T[b],h=1;p>=10;p/=10,h++);d%=q,v=d-q+h,w=v<0?0:Te(y/G[h-v-1]%10)}if(m=m||l<0||T[b+1]!=null||(v<0?y:y%G[h-v-1]),m=f<4?(w||m)&&(f==0||f==(s.s<0?3:2)):w>5||w==5&&(f==4||m||f==6&&(d>0?v>0?y/G[h-v]:0:T[b-1])%10&1||f==(s.s<0?8:7)),l<1||!T[0])return T.length=0,m?(l-=s.e+1,T[0]=G[(q-l%q)%q],s.e=-l||0):T[0]=s.e=0,s;if(d==0?(T.length=b,p=1,b--):(T.length=b+1,p=G[q-d],T[b]=v>0?Te(y/G[h-v]%G[v])*p:0),m)for(;;)if(b==0){for(d=1,v=T[0];v>=10;v/=10,d++);for(v=T[0]+=p,p=1;v>=10;v/=10,p++);d!=p&&(s.e++,T[0]==Re&&(T[0]=1));break}else{if(T[b]+=p,T[b]!=Re)break;T[b--]=0,p=1}for(d=T.length;T[--d]===0;T.pop());}s.e>_?s.c=s.e=null:s.e=c?Gt(l,f):je(l,f,"0"),s.s<0?"-"+l:l)}return r.absoluteValue=r.abs=function(){var s=new x(this);return s.s<0&&(s.s=1),s},r.comparedTo=function(s,l){return rt(this,new x(s,l))},r.decimalPlaces=r.dp=function(s,l){var f,m,h,d=this;if(s!=null)return oe(s,0,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s+d.e+1,l);if(!(f=d.c))return null;if(m=((h=f.length-1)-Me(this.e/q))*q,h=f[h])for(;h%10==0;h/=10,m--);return m<0&&(m=0),m},r.dividedBy=r.div=function(s,l){return e(this,new x(s,l),a,o)},r.dividedToIntegerBy=r.idiv=function(s,l){return e(this,new x(s,l),0,1)},r.exponentiatedBy=r.pow=function(s,l){var f,m,h,d,v,p,y,b,w,T=this;if(s=new x(s),s.c&&!s.isInteger())throw Error(be+"Exponent not an integer: "+W(s));if(l!=null&&(l=new x(l)),p=s.e>14,!T.c||!T.c[0]||T.c[0]==1&&!T.e&&T.c.length==1||!s.c||!s.c[0])return w=new x(Math.pow(+W(T),p?s.s*(2-Wt(s)):+W(s))),l?w.mod(l):w;if(y=s.s<0,l){if(l.c?!l.c[0]:!l.s)return new x(NaN);m=!y&&T.isInteger()&&l.isInteger(),m&&(T=T.mod(l))}else{if(s.e>9&&(T.e>0||T.e<-1||(T.e==0?T.c[0]>1||p&&T.c[1]>=24e7:T.c[0]<8e13||p&&T.c[0]<=9999975e7)))return d=T.s<0&&Wt(s)?-0:0,T.e>-1&&(d=1/d),new x(y?1/d:d);k&&(d=ii(k/q+2))}for(p?(f=new x(.5),y&&(s.s=1),b=Wt(s)):(h=Math.abs(+W(s)),b=h%2),w=new x(u);;){if(b){if(w=w.times(T),!w.c)break;d?w.c.length>d&&(w.c.length=d):m&&(w=w.mod(l))}if(h){if(h=Te(h/2),h===0)break;b=h%2}else if(s=s.times(f),z(s,s.e+1,1),s.e>14)b=Wt(s);else{if(h=+W(s),h===0)break;b=h%2}T=T.times(T),d?T.c&&T.c.length>d&&(T.c.length=d):m&&(T=T.mod(l))}return m?w:(y&&(w=u.div(w)),l?w.mod(l):d?z(w,k,o,v):w)},r.integerValue=function(s){var l=new x(this);return s==null?s=o:oe(s,0,8),z(l,l.e+1,s)},r.isEqualTo=r.eq=function(s,l){return rt(this,new x(s,l))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(s,l){return rt(this,new x(s,l))>0},r.isGreaterThanOrEqualTo=r.gte=function(s,l){return(l=rt(this,new x(s,l)))===1||l===0},r.isInteger=function(){return!!this.c&&Me(this.e/q)>this.c.length-2},r.isLessThan=r.lt=function(s,l){return rt(this,new x(s,l))<0},r.isLessThanOrEqualTo=r.lte=function(s,l){return(l=rt(this,new x(s,l)))===-1||l===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(s,l){var f,m,h,d,v=this,p=v.s;if(s=new x(s,l),l=s.s,!p||!l)return new x(NaN);if(p!=l)return s.s=-l,v.plus(s);var y=v.e/q,b=s.e/q,w=v.c,T=s.c;if(!y||!b){if(!w||!T)return w?(s.s=-l,s):new x(T?v:NaN);if(!w[0]||!T[0])return T[0]?(s.s=-l,s):new x(w[0]?v:o==3?-0:0)}if(y=Me(y),b=Me(b),w=w.slice(),p=y-b){for((d=p<0)?(p=-p,h=w):(b=y,h=T),h.reverse(),l=p;l--;h.push(0));h.reverse()}else for(m=(d=(p=w.length)<(l=T.length))?p:l,p=l=0;l0)for(;l--;w[f++]=0);for(l=Re-1;m>p;){if(w[--m]=0;){for(f=0,G=de[h]%se,D=de[h]/se|0,v=y,d=h+v;d>h;)b=K[--v]%se,w=K[v]/se|0,p=D*b+w*G,b=G*b+p%se*se+H[d]+f,f=(b/Q|0)+(p/se|0)+D*w,H[d--]=b%Q;H[d]=f}return f?++m:H.splice(0,1),B(s,H,m)},r.negated=function(){var s=new x(this);return s.s=-s.s||null,s},r.plus=function(s,l){var f,m=this,h=m.s;if(s=new x(s,l),l=s.s,!h||!l)return new x(NaN);if(h!=l)return s.s=-l,m.minus(s);var d=m.e/q,v=s.e/q,p=m.c,y=s.c;if(!d||!v){if(!p||!y)return new x(h/0);if(!p[0]||!y[0])return y[0]?s:new x(p[0]?m:h*0)}if(d=Me(d),v=Me(v),p=p.slice(),h=d-v){for(h>0?(v=d,f=y):(h=-h,f=p),f.reverse();h--;f.push(0));f.reverse()}for(h=p.length,l=y.length,h-l<0&&(f=y,y=p,p=f,l=h),h=0;l;)h=(p[--l]=p[l]+y[l]+h)/Re|0,p[l]=Re===p[l]?0:p[l]%Re;return h&&(p=[h].concat(p),++v),B(s,p,v)},r.precision=r.sd=function(s,l){var f,m,h,d=this;if(s!=null&&s!==!!s)return oe(s,1,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s,l);if(!(f=d.c))return null;if(h=f.length-1,m=h*q+1,h=f[h]){for(;h%10==0;h/=10,m--);for(h=f[0];h>=10;h/=10,m++);}return s&&d.e+1>m&&(m=d.e+1),m},r.shiftedBy=function(s){return oe(s,-9007199254740991,Zi),this.times("1e"+s)},r.squareRoot=r.sqrt=function(){var s,l,f,m,h,d=this,v=d.c,p=d.s,y=d.e,b=a+4,w=new x("0.5");if(p!==1||!v||!v[0])return new x(!p||p<0&&(!v||v[0])?NaN:v?d:1/0);if(p=Math.sqrt(+W(d)),p==0||p==1/0?(l=Ce(v),(l.length+y)%2==0&&(l+="0"),p=Math.sqrt(+l),y=Me((y+1)/2)-(y<0||y%2),p==1/0?l="5e"+y:(l=p.toExponential(),l=l.slice(0,l.indexOf("e")+1)+y),f=new x(l)):f=new x(p+""),f.c[0]){for(y=f.e,p=y+b,p<3&&(p=0);;)if(h=f,f=w.times(h.plus(e(d,h,b,1))),Ce(h.c).slice(0,p)===(l=Ce(f.c)).slice(0,p))if(f.e0&&H>0){for(d=H%p||p,w=D.substr(0,d);d0&&(w+=b+D.slice(d)),G&&(w="-"+w)}m=T?w+(f.decimalSeparator||"")+((y=+f.fractionGroupSize)?T.replace(new RegExp("\\d{"+y+"}\\B","g"),"$&"+(f.fractionGroupSeparator||"")):T):w}return(f.prefix||"")+m+(f.suffix||"")},r.toFraction=function(s){var l,f,m,h,d,v,p,y,b,w,T,G,D=this,H=D.c;if(s!=null&&(p=new x(s),!p.isInteger()&&(p.c||p.s!==1)||p.lt(u)))throw Error(be+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+W(p));if(!H)return new x(D);for(l=new x(u),b=f=new x(u),m=y=new x(u),G=Ce(H),d=l.e=G.length-D.e-1,l.c[0]=ni[(v=d%q)<0?q+v:v],s=!s||p.comparedTo(l)>0?d>0?l:b:p,v=_,_=1/0,p=new x(G),y.c[0]=0;w=e(p,l,0,1),h=f.plus(w.times(m)),h.comparedTo(s)!=1;)f=m,m=h,b=y.plus(w.times(h=b)),y=h,l=p.minus(w.times(h=l)),p=h;return h=e(s.minus(f),m,0,1),y=y.plus(h.times(b)),f=f.plus(h.times(m)),y.s=b.s=D.s,d=d*2,T=e(b,m,d,o).minus(D).abs().comparedTo(e(y,f,d,o).minus(D).abs())<1?[b,m]:[y,f],_=v,T},r.toNumber=function(){return+W(this)},r.toPrecision=function(s,l){return s!=null&&oe(s,1,Ee),N(this,s,l,2)},r.toString=function(s){var l,f=this,m=f.s,h=f.e;return h===null?m?(l="Infinity",m<0&&(l="-"+l)):l="NaN":(s==null?l=h<=g||h>=c?Gt(Ce(f.c),h):je(Ce(f.c),h,"0"):s===10&&O?(f=z(new x(f),a+h+1,o),l=je(Ce(f.c),f.e,"0")):(oe(s,2,C.length,"Base"),l=t(je(Ce(f.c),h,"0"),10,s,m,!0)),m<0&&f.c[0]&&(l="-"+l)),l},r.valueOf=r.toJSON=function(){return W(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,i!=null&&x.set(i),x}function Me(i){var e=i|0;return i>0||i===e?e:e-1}function Ce(i){for(var e,t,n=1,r=i.length,u=i[0]+"";nc^t?1:-1;for(o=(g=r.length)<(c=u.length)?g:c,a=0;au[a]^t?1:-1;return g==c?0:g>c^t?1:-1}function oe(i,e,t,n){if(it||i!==Te(i))throw Error(be+(n||"Argument")+(typeof i=="number"?it?" out of range: ":" not an integer: ":" not a primitive number: ")+String(i))}function Wt(i){var e=i.c.length-1;return Me(i.e/q)==e&&i.c[e]%2!=0}function Gt(i,e){return(i.length>1?i.charAt(0)+"."+i.slice(1):i)+(e<0?"e":"e+")+e}function je(i,e,t){var n,r;if(e<0){for(r=t+".";++e;r+=t);i=r+i}else if(n=i.length,++e>n){for(r=t,e-=n;--e;r+=t);i+=r}else e0){let c=a.left;if(c==null||(g=o(c.key,i),g>0&&(a.left=c.right,c.right=a,a=c,c=a.left,c==null)))break;t==null?n=a:t.left=a,t=a,a=c}else if(g<0){let c=a.right;if(c==null||(g=o(c.key,i),g<0&&(a.right=c.left,c.left=a,a=c,c=a.right,c==null)))break;r==null?u=a:r.right=a,r=a,a=c}else break;return r!=null&&(r.right=a.left,a.left=u),t!=null&&(t.left=a.right,a.right=n),this.root!==a&&(this.root=a,this.splayCount++),g}splayMin(i){let e=i,t=e.left;for(;t!=null;){const n=t;e.left=n.right,n.right=e,e=n,t=e.left}return e}splayMax(i){let e=i,t=e.right;for(;t!=null;){const n=t;e.right=n.left,n.left=e,e=n,t=e.right}return e}_delete(i){if(this.root==null||this.splay(i)!=0)return null;let t=this.root;const n=t,r=t.left;if(this.size--,r==null)this.root=t.right;else{const u=t.right;t=this.splayMax(r),t.right=u,this.root=t}return this.modificationCount++,n}addNewRoot(i,e){this.size++,this.modificationCount++;const t=this.root;if(t==null){this.root=i;return}e<0?(i.left=t,i.right=t.right,t.right=null):(i.right=t,i.left=t.left,t.left=null),this.root=i}_first(){const i=this.root;return i==null?null:(this.root=this.splayMin(i),this.root)}_last(){const i=this.root;return i==null?null:(this.root=this.splayMax(i),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(i){return this.validKey(i)&&this.splay(i)==0}defaultCompare(){return(i,e)=>ie?1:0}wrap(){return{getRoot:()=>this.root,setRoot:i=>{this.root=i},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:i=>{this.splayCount=i},splay:i=>this.splay(i),has:i=>this.has(i)}}},Dt=class Ot extends Pr{constructor(t,n){super();A(this,"root",null);A(this,"compare");A(this,"validKey");A(this,fn,"[object Set]");this.compare=t??this.defaultCompare(),this.validKey=n??(r=>r!=null&&r!=null)}delete(t){return this.validKey(t)?this._delete(t)!=null:!1}deleteAll(t){for(const n of t)this.delete(n)}forEach(t){const n=this[Symbol.iterator]();let r;for(;r=n.next(),!r.done;)t(r.value,r.value,this)}add(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this}addAndReturn(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this.root.key}addAll(t){for(const n of t)this.add(n)}isEmpty(){return this.root==null}isNotEmpty(){return this.root!=null}single(){if(this.size==0)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(this.size==0)throw"Bad state: No element";return this._first().key}last(){if(this.size==0)throw"Bad state: No element";return this._last().key}lastBefore(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)<0)return this.root.key;let r=this.root.left;if(r==null)return null;let u=r.right;for(;u!=null;)r=u,u=r.right;return r.key}firstAfter(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)>0)return this.root.key;let r=this.root.right;if(r==null)return null;let u=r.left;for(;u!=null;)r=u,u=r.left;return r.key}retainAll(t){const n=new Ot(this.compare,this.validKey),r=this.modificationCount;for(const u of t){if(r!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(u)&&this.splay(u)==0&&n.add(this.root.key)}n.size!=this.size&&(this.root=n.root,this.size=n.size,this.modificationCount++)}lookup(t){return!this.validKey(t)||this.splay(t)!=0?null:this.root.key}intersection(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)&&n.add(r);return n}difference(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)||n.add(r);return n}union(t){const n=this.clone();return n.addAll(t),n}clone(){const t=new Ot(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(t){if(t==null)return null;function n(u,a){let o,g;do{if(o=u.left,g=u.right,o!=null){const c=new _t(o.key);a.left=c,n(o,c)}if(g!=null){const c=new _t(g.key);a.right=c,u=g,a=c}}while(g!=null)}const r=new _t(t.key);return n(t,r),r}toSet(){return this.clone()}entries(){return new Ar(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[(cn=Symbol.iterator,fn=Symbol.toStringTag,cn)](){return new Ir(this.wrap())}},Vi=class{constructor(i){A(this,"tree");A(this,"path",new Array);A(this,"modificationCount",null);A(this,"splayCount");this.tree=i,this.splayCount=i.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const i=this.path[this.path.length-1];return this.getValue(i)}rebuildPath(i){this.path.splice(0,this.path.length),this.tree.splay(i),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(i){for(;i!=null;)this.path.push(i),i=i.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(this.modificationCount==null){this.modificationCount=this.tree.getModificationCount();let t=this.tree.getRoot();for(;t!=null;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let i=this.path[this.path.length-1],e=i.right;if(e!=null){for(;e!=null;)this.path.push(e),e=e.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===i;)i=this.path.pop();return this.path.length>0}},Ir=class extends Vi{getValue(i){return i.key}},Ar=class extends Vi{getValue(i){return[i.key,i.key]}},Ki=i=>()=>i,ri=i=>{const e=i?(t,n)=>n.minus(t).abs().isLessThanOrEqualTo(i):Ki(!1);return(t,n)=>e(t,n)?0:t.comparedTo(n)};function Br(i){const e=i?(t,n,r,u,a)=>t.exponentiatedBy(2).isLessThanOrEqualTo(u.minus(n).exponentiatedBy(2).plus(a.minus(r).exponentiatedBy(2)).times(i)):Ki(!1);return(t,n,r)=>{const u=t.x,a=t.y,o=r.x,g=r.y,c=a.minus(g).times(n.x.minus(o)).minus(u.minus(o).times(n.y.minus(g)));return e(c,u,a,o,g)?0:c.comparedTo(0)}}var Wr=i=>i,Gr=i=>{if(i){const e=new Dt(ri(i)),t=new Dt(ri(i)),n=(u,a)=>a.addAndReturn(u),r=u=>({x:n(u.x,e),y:n(u.y,t)});return r({x:new Ae(0),y:new Ae(0)}),r}return Wr},si=i=>({set:e=>{Ze=si(e)},reset:()=>si(i),compare:ri(i),snap:Gr(i),orient:Br(i)}),Ze=si(),St=(i,e)=>i.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(i.ur.x)&&i.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(i.ur.y),oi=(i,e)=>{if(e.ur.x.isLessThan(i.ll.x)||i.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(i.ll.y)||i.ur.y.isLessThan(e.ll.y))return null;const t=i.ll.x.isLessThan(e.ll.x)?e.ll.x:i.ll.x,n=i.ur.x.isLessThan(e.ur.x)?i.ur.x:e.ur.x,r=i.ll.y.isLessThan(e.ll.y)?e.ll.y:i.ll.y,u=i.ur.y.isLessThan(e.ur.y)?i.ur.y:e.ur.y;return{ll:{x:t,y:r},ur:{x:n,y:u}}},zt=(i,e)=>i.x.times(e.y).minus(i.y.times(e.x)),Yi=(i,e)=>i.x.times(e.x).plus(i.y.times(e.y)),Ut=i=>Yi(i,i).sqrt(),Dr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return zt(r,n).div(Ut(r)).div(Ut(n))},zr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return Yi(r,n).div(Ut(r)).div(Ut(n))},Qi=(i,e,t)=>e.y.isZero()?null:{x:i.x.plus(e.x.div(e.y).times(t.minus(i.y))),y:t},Xi=(i,e,t)=>e.x.isZero()?null:{x:t,y:i.y.plus(e.y.div(e.x).times(t.minus(i.x)))},Ur=(i,e,t,n)=>{if(e.x.isZero())return Xi(t,n,i.x);if(n.x.isZero())return Xi(i,e,t.x);if(e.y.isZero())return Qi(t,n,i.y);if(n.y.isZero())return Qi(i,e,t.y);const r=zt(e,n);if(r.isZero())return null;const u={x:t.x.minus(i.x),y:t.y.minus(i.y)},a=zt(u,e).div(r),o=zt(u,n).div(r),g=i.x.plus(o.times(e.x)),c=t.x.plus(a.times(n.x)),E=i.y.plus(o.times(e.y)),_=t.y.plus(a.times(n.y)),M=g.plus(c).div(2),R=E.plus(_).div(2);return{x:M,y:R}},Be=class En{constructor(e,t){A(this,"point");A(this,"isLeft");A(this,"segment");A(this,"otherSE");A(this,"consumedBy");e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}static compare(e,t){const n=En.comparePoints(e.point,t.point);return n!==0?n:(e.point!==t.point&&e.link(t),e.isLeft!==t.isLeft?e.isLeft?1:-1:Ft.compare(e.segment,t.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let n=0,r=t.length;n{const u=r.otherSE;t.set(r,{sine:Dr(this.point,e.point,u.point),cosine:zr(this.point,e.point,u.point)})};return(r,u)=>{t.has(r)||n(r),t.has(u)||n(u);const{sine:a,cosine:o}=t.get(r),{sine:g,cosine:c}=t.get(u);return a.isGreaterThanOrEqualTo(0)&&g.isGreaterThanOrEqualTo(0)?o.isLessThan(c)?1:o.isGreaterThan(c)?-1:0:a.isLessThan(0)&&g.isLessThan(0)?o.isLessThan(c)?-1:o.isGreaterThan(c)?1:0:g.isLessThan(a)?-1:g.isGreaterThan(a)?1:0}}},qr=class pi{constructor(e){A(this,"events");A(this,"poly");A(this,"_isExteriorRing");A(this,"_enclosingRing");this.events=e;for(let t=0,n=e.length;t0&&(e=g)}let t=e.segment.prevInResult(),n=t?t.prevInResult():null;for(;;){if(!t)return null;if(!n)return t.ringOut;if(n.ringOut!==t.ringOut)return((r=n.ringOut)==null?void 0:r.enclosingRing())!==t.ringOut?t.ringOut:(u=t.ringOut)==null?void 0:u.enclosingRing();t=n.prevInResult(),n=t?t.prevInResult():null}}},Ji=class{constructor(i){A(this,"exteriorRing");A(this,"interiorRings");this.exteriorRing=i,i.poly=this,this.interiorRings=[]}addInterior(i){this.interiorRings.push(i),i.poly=this}getGeom(){const i=this.exteriorRing.getGeom();if(i===null)return null;const e=[i];for(let t=0,n=this.interiorRings.length;t0?(this.tree.delete(e),t.push(i)):(this.segments.push(e),e.prev=n)}else{if(n&&r){const u=n.getIntersection(r);if(u!==null){if(!n.isAnEndpoint(u)){const a=this._splitSafely(n,u);for(let o=0,g=a.length;o0)return-1;const M=t.comparePoint(e.rightSE.point);return M!==0?M:-1}if(n.isGreaterThan(r)){if(o.isLessThan(g)&&o.isLessThan(E))return-1;if(o.isGreaterThan(g)&&o.isGreaterThan(E))return 1;const _=t.comparePoint(e.leftSE.point);if(_!==0)return _;const M=e.comparePoint(t.rightSE.point);return M<0?1:M>0?-1:1}if(o.isLessThan(g))return-1;if(o.isGreaterThan(g))return 1;if(u.isLessThan(a)){const _=t.comparePoint(e.rightSE.point);if(_!==0)return _}if(u.isGreaterThan(a)){const _=e.comparePoint(t.rightSE.point);if(_<0)return 1;if(_>0)return-1}if(!u.eq(a)){const _=c.minus(o),M=u.minus(n),R=E.minus(g),k=a.minus(r);if(_.isGreaterThan(M)&&R.isLessThan(k))return 1;if(_.isLessThan(M)&&R.isGreaterThan(k))return-1}return u.isGreaterThan(a)?1:u.isLessThan(a)||c.isLessThan(E)?-1:c.isGreaterThan(E)?1:e.idt.id?1:0}static fromRing(e,t,n){let r,u,a;const o=Be.comparePoints(e,t);if(o<0)r=e,u=t,a=1;else if(o>0)r=t,u=e,a=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const g=new Be(r,!0),c=new Be(u,!1);return new Kt(g,c,[n],[a])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return Ze.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),n=e.bbox(),r=oi(t,n);if(r===null)return null;const u=this.leftSE.point,a=this.rightSE.point,o=e.leftSE.point,g=e.rightSE.point,c=St(t,o)&&this.comparePoint(o)===0,E=St(n,u)&&e.comparePoint(u)===0,_=St(t,g)&&this.comparePoint(g)===0,M=St(n,a)&&e.comparePoint(a)===0;if(E&&c)return M&&!_?a:!M&&_?g:null;if(E)return _&&u.x.eq(g.x)&&u.y.eq(g.y)?null:u;if(c)return M&&a.x.eq(o.x)&&a.y.eq(o.y)?null:o;if(M&&_)return null;if(M)return a;if(_)return g;const R=Ur(u,this.vector(),o,e.vector());return R===null||!St(r,R)?null:Ze.snap(R)}split(e){const t=[],n=e.events!==void 0,r=new Be(e,!0),u=new Be(e,!1),a=this.rightSE;this.replaceRightSE(u),t.push(u),t.push(r);const o=new Kt(r,a,this.rings.slice(),this.windings.slice());return Be.comparePoints(o.leftSE.point,o.rightSE.point)>0&&o.swapEvents(),Be.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(r.checkForConsuming(),u.checkForConsuming()),t}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,n=this.windings.length;t0){const u=t;t=n,n=u}if(t.prev===n){const u=t;t=n,n=u}for(let u=0,a=n.rings.length;ur.length===1&&r[0].isSubject;this._isInResult=n(e)!==n(t);break}}return this._isInResult}},$i=class{constructor(i,e,t){A(this,"poly");A(this,"isExterior");A(this,"segments");A(this,"bbox");if(!Array.isArray(i)||i.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=e,this.isExterior=t,this.segments=[],typeof i[0][0]!="number"||typeof i[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const n=Ze.snap({x:new Ae(i[0][0]),y:new Ae(i[0][1])});this.bbox={ll:{x:n.x,y:n.y},ur:{x:n.x,y:n.y}};let r=n;for(let u=1,a=i.length;uqt.run("union",i,e),Yr=(i,...e)=>qt.run("difference",i,e);Ze.set;function tn(i,e,t){if(i!==null)for(var n,r,u,a,o,g,c,E=0,_=0,M,R=i.type,k=R==="FeatureCollection",I=R==="Feature",C=k?i.features.length:1,O=0;O{t.push(r.coordinates)}),t.length<2)throw new Error("Must have at least 2 geometries");const n=Kr(t[0],...t.slice(1));return n.length===0?null:n.length===1?ti(n[0],e.properties):Fi(n,e.properties)}var nn=Xr;function Jr(i,e={}){if(i.bbox!=null&&e.recompute!==!0)return i.bbox;const t=[1/0,1/0,-1/0,-1/0];return tn(i,n=>{t[0]>n[0]&&(t[0]=n[0]),t[1]>n[1]&&(t[1]=n[1]),t[2]{e.push(r.coordinates)}),e.length<2)throw new Error("Must have at least two features");const t=i.features[0].properties||{},n=Yr(e[0],...e.slice(1));return n.length===0?null:n.length===1?ti(n[0],t):Fi(n,t)}var es=$r;function ts(i){if(!i)throw new Error("geojson is required");var e=[];return Qr(i,function(t){e.push(t)}),Lt(e)}var is=ts;function sn(i,e){const t=es(Lt([ti([[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]]),i]));if(!t)return;t.properties={isMask:!0};const n=Bt(rn(i)),r=(n[2]-n[0])/360/1e3,u=n[0]<-180,a=n[2]>180,o=is(i);if(o.features.length>1&&(u||a))for(const g of o.features){const c=Bt(rn(g));if(a&&c[0]<-180+r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]+=360-r;if(u&&c[2]>180-r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]-=360-r}e(Lt([o.features.length<2?i:nn(o)??i,t]))}const on={fill:{paint:{"fill-color":"#000","fill-opacity":.1},filter:["all",["==",["geometry-type"],"Polygon"],["has","isMask"]]},line:{layout:{"line-cap":"square"},paint:{"line-width":["case",["==",["geometry-type"],"Polygon"],2,3],"line-dasharray":[1,1],"line-color":"#3170fe"},filter:["!",["has","isMask"]]}},jt="mtlr-gc-full-geom",ln="mtlr-gc-full-geom-fill",un="mtlr-gc-full-geom-line";function an(i,e,t=!0,n=!0,r={},u={},a=on){let o;const g=[];let c,E,_;function M(){if(!i.loaded){i.once("load",M);return}const C=a?a===!0?on:a:void 0;if(!(C!=null&&C.fill)&&!(C!=null&&C.line))return;const O=i.getSource(jt);if(O)O.setData(_??Lt([]));else if(_)i.addSource(jt,{type:"geojson",data:_});else return;!i.getLayer(ln)&&(C!=null&&C.fill)&&i.addLayer({...C==null?void 0:C.fill,id:ln,type:"fill",source:jt}),!i.getLayer(un)&&(C!=null&&C.line)&&i.addLayer({...C==null?void 0:C.line,id:un,type:"line",source:jt})}function R(C){_=C,M()}i.on("styledata",()=>{setTimeout(()=>{_&&M()})});const k=C=>{o==null||o({type:"mapClick",coordinates:[C.lngLat.lng,C.lngLat.lat]})};function I(C=!1){if(!e)throw new Error;const O=document.createElement("div");return C&&O.classList.add("marker-interactive"),new or({props:{displayIn:"maplibre"},target:O}),new e.Marker({element:O,offset:[1,-13]})}return{setEventHandler(C){C?(o=C,i.on("click",k)):(o=void 0,i.off("click",k))},flyTo(C,O){i.flyTo({center:C,...O?{zoom:O}:{},...r})},fitBounds(C,O,x){i.fitBounds([[C[0],C[1]],[C[2],C[3]]],{padding:O,...x?{maxZoom:x}:{},...u})},indicateReverse(C){i.getCanvasContainer().style.cursor=C?"crosshair":""},setReverseMarker(C){!e||!t||(E?C?E.setLngLat(C):(E.remove(),E=void 0):C&&(t instanceof Function?E=t(i)??void 0:(E=(typeof t=="object"?new e.Marker(t):I()).setLngLat(C).addTo(i),E.getElement().classList.add("marker-reverse"))))},setFeatures(C,O,x){for(const N of g)N.remove();if(g.length=0,R(void 0),!!e){e:if(O){let N=!1;if(O.geometry.type==="GeometryCollection"){const P=O.geometry.geometries.filter(B=>B.type==="Polygon"||B.type==="MultiPolygon");t:if(P.length>0){const B=nn(Lt(P.map(z=>Et(z))));if(!B)break t;sn({...O,geometry:B.geometry},R),N=!0}else{const B=O.geometry.geometries.filter(z=>z.type==="LineString"||z.type==="MultiLineString");B.length>0&&(R({...O,geometry:{type:"GeometryCollection",geometries:B}}),N=!0)}}if(!N){if(O.geometry.type==="Polygon"||O.geometry.type==="MultiPolygon")sn(O,R);else if(O.geometry.type==="LineString"||O.geometry.type==="MultiLineString"){R(O);break e}}if(!x&&!O.geometry.type.endsWith("Point"))break e;if(t instanceof Function){const P=t(i,O);P&&g.push(P)}else t&&g.push(typeof t=="object"?new e.Marker(t):I().setLngLat(O.center).addTo(i))}if(n)for(const N of C??[]){if(N===O)continue;let P;if(n instanceof Function){if(P=n(i,N),!P)continue}else P=(typeof n=="object"?new e.Marker(n):I(!0)).setLngLat(N.center).setPopup(new e.Popup({offset:[1,-27],closeButton:!1,closeOnMove:!0,className:"maptiler-gc-popup"}).setText(N.place_type[0]==="reverse"?N.place_name:N.place_name.replace(/,.*/,""))).addTo(i);const B=P.getElement();B.addEventListener("click",z=>{z.stopPropagation(),o==null||o({type:"markerClick",id:N.id})}),B.addEventListener("mouseenter",()=>{o==null||o({type:"markerMouseEnter",id:N.id}),P.togglePopup()}),B.addEventListener("mouseleave",()=>{o==null||o({type:"markerMouseLeave",id:N.id}),P.togglePopup()}),g.push(P)}}},setSelectedMarker(C){c&&c.getElement().classList.toggle("marker-selected",!1),c=C>-1?g[C]:void 0,c==null||c.getElement().classList.toggle("marker-selected",!0)},getCenterAndZoom(){const C=i.getCenter();return[i.getZoom(),C.lng,C.lat]}}}function ns(i,e,t){var k,I,C;class n{constructor(x,N){A(this,"type");A(this,"target");this.type=N,this.target=x}}class r extends n{constructor(N,P){super(N,"select");A(this,"feature");Object.assign(this,P)}}class u extends n{constructor(N,P){super(N,"featureslisted");A(this,"features");this.features=P}}class a extends n{constructor(N,P){super(N,"featuresmarked");A(this,"features");this.features=P}}class o extends n{constructor(N,P){super(N,"optionsvisibilitychange");A(this,"optionsVisible");this.optionsVisible=P}}class g extends n{constructor(N,P){super(N,"pick");A(this,"feature");this.feature=P}}class c extends n{constructor(N,P){super(N,"querychange");A(this,"query");this.query=P}}class E extends n{constructor(N,P,B){super(N,"response");A(this,"url");A(this,"featureCollection");this.url=P,this.featureCollection=B}}class _ extends n{constructor(N,P){super(N,"reversetoggle");A(this,"reverse");this.reverse=P}}class M extends i{constructor(N={}){super();Vt(this,k);Vt(this,I);Vt(this,C);kt(this,I,N)}onAddInt(N){const P=document.createElement("div");P.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl mapboxgl-ctrl-group";const{marker:B,showResultMarkers:z,flyTo:W,fullGeometryStyle:s,...l}=ue(this,I),f=typeof W=="boolean"?{}:W,h={mapController:an(N,e,B,z,f,f,s),flyTo:W===void 0?!0:!!W,apiKey:"",...t==null?void 0:t(N,P),...l};return h.apiKey||console.warn("No MapTiler Cloud API key was provided, some or all geocoding requests may fail"),kt(this,k,new kr({target:P,props:h})),ue(this,k).$on("select",d=>{this.fire(new r(this,d.detail))}),ue(this,k).$on("pick",d=>{this.fire(new g(this,d.detail.feature))}),ue(this,k).$on("featureslisted",d=>{this.fire(new u(this,d.detail.features))}),ue(this,k).$on("featuresmarked",d=>{this.fire(new a(this,d.detail.features))}),ue(this,k).$on("response",d=>{this.fire(new E(this,d.detail.url,d.detail.featureCollection))}),ue(this,k).$on("optionsvisibilitychange",d=>{this.fire(new o(this,d.detail.optionsVisible))}),ue(this,k).$on("reversetoggle",d=>{this.fire(new _(this,d.detail.reverse))}),ue(this,k).$on("querychange",d=>{this.fire(new c(this,d.detail.query))}),kt(this,C,P),P}on(N,P){return super.on(N,P)}once(N,P){return super.once(N,P)}off(N,P){return super.off(N,P)}listens(N){return super.listens(N)}setOptions(N){var l;Object.assign(ue(this,I),N);const{marker:P,showResultMarkers:B,flyTo:z,fullGeometryStyle:W,...s}=ue(this,I);(l=ue(this,k))==null||l.$set(s)}setQuery(N,P=!0){var B;(B=ue(this,k))==null||B.setQuery(N,P)}clearMap(){var N;(N=ue(this,k))==null||N.clearMap()}clearList(){var N;(N=ue(this,k))==null||N.clearList()}setReverseMode(N){var P;(P=ue(this,k))==null||P.$set({reverseActive:N})}focus(N){var P;(P=ue(this,k))==null||P.focus(N)}blur(){var N;(N=ue(this,k))==null||N.blur()}onRemove(){var N,P,B;(N=ue(this,k))==null||N.$destroy(),kt(this,k,void 0),(B=(P=ue(this,C))==null?void 0:P.parentNode)==null||B.removeChild(ue(this,C))}}return k=new WeakMap,I=new WeakMap,C=new WeakMap,{MapLibreBasedGeocodingControl:M,events:{SelectEvent:r,FeaturesListedEvent:u,FeaturesMarkedEvent:a,OptionsVisibilityChangeEvent:o,PickEvent:g,QueryChangeEvent:c,ResponseEvent:E,ReverseToggleEvent:_}}}const{MapLibreBasedGeocodingControl:rs,events:et}=ns(dt.Evented,dt);class ss extends rs{onAdd(e){return super.onAddInt(e)}}const os=et.SelectEvent,ls=et.FeaturesListedEvent,us=et.FeaturesMarkedEvent,as=et.OptionsVisibilityChangeEvent,fs=et.PickEvent,cs=et.QueryChangeEvent,hs=et.ResponseEvent,ds=et.ReverseToggleEvent;j.FeaturesListedEvent=ls,j.FeaturesMarkedEvent=us,j.GeocodingControl=ss,j.OptionsVisibilityChangeEvent=as,j.PickEvent=fs,j.QueryChangeEvent=cs,j.ResponseEvent=hs,j.ReverseToggleEvent=ds,j.SelectEvent=os,j.createMapLibreGlMapController=an,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"})}); +//# sourceMappingURL=maplibregl.umd.js.map diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css new file mode 100644 index 0000000..c865c17 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css @@ -0,0 +1 @@ +svg.svelte-d2loi5{display:block;fill:#e15042}.sprite-icon.svelte-w9y5n9.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75;background-repeat:no-repeat}li.svelte-w9y5n9.svelte-w9y5n9{text-align:left;cursor:default;display:grid;grid-template-columns:40px 1fr;color:var(--color-text);padding:8px 0;font-size:14px;line-height:18px;min-width:fit-content;outline:0}li.svelte-w9y5n9.svelte-w9y5n9:first-child{padding-top:10px}li.svelte-w9y5n9.svelte-w9y5n9:last-child{padding-bottom:10px}li.picked.svelte-w9y5n9.svelte-w9y5n9{background-color:#e7edff}li.picked.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#96a4c7;padding-left:4px}li.picked.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#96a4c7}li.selected.svelte-w9y5n9.svelte-w9y5n9{background-color:#f3f6ff}li.selected.svelte-w9y5n9.svelte-w9y5n9{animation:svelte-w9y5n9-backAndForth 5s linear infinite}li.selected.svelte-w9y5n9 .primary.svelte-w9y5n9{color:#2b8bfb}li.selected.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#a2adc7;padding-left:4px}li.selected.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#a2adc7}li.svelte-w9y5n9>img.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75}.texts.svelte-w9y5n9.svelte-w9y5n9{padding:0 17px 0 0}.texts.svelte-w9y5n9>.svelte-w9y5n9{white-space:nowrap;display:block;min-width:fit-content}.primary.svelte-w9y5n9.svelte-w9y5n9{font-weight:600}.secondary.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7;padding-left:4px}.line2.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7}@keyframes svelte-w9y5n9-backAndForth{0%{transform:translate(0)}10%{transform:translate(0)}45%{transform:translate(calc(-100% + 270px))}55%{transform:translate(calc(-100% + 270px))}90%{transform:translate(0)}to{transform:translate(0)}}div.svelte-1ocfouu{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);pointer-events:none;display:flex;align-items:center}.loading-icon.svelte-1ocfouu{animation:svelte-1ocfouu-rotate .8s infinite cubic-bezier(.45,.05,.55,.95)}@keyframes svelte-1ocfouu-rotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}svg.svelte-gzo3ar.svelte-gzo3ar{display:block;fill:#6b7c93;stroke:#6b7c93}.list-icon.svelte-gzo3ar.svelte-gzo3ar{grid-row:1/3;align-self:center;margin:8px}.in-map.svelte-gzo3ar.svelte-gzo3ar{height:30px}.maplibregl-canvas-container .marker-selected{z-index:1}.maplibregl-canvas-container svg.svelte-gzo3ar path.svelte-gzo3ar,.leaflet-map-pane svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#3170fe;stroke:#3170fe}.marker-selected svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#98b7ff;stroke:#3170fe}.marker-reverse svg.svelte-gzo3ar path.svelte-gzo3ar{fill:silver;stroke:gray}.marker-interactive{cursor:pointer!important}.maptiler-gc-popup>.maplibregl-popup-content{padding:2px 8px}svg.svelte-en2qvf{display:block;fill:var(--color-icon-button)}circle.svelte-1aq105l{stroke-width:1.875;fill:none}path.svelte-1aq105l{stroke-width:1.875;stroke-linecap:round}svg.svelte-1aq105l{display:block;stroke:var(--color-icon-button)}form.svelte-bz0zu3.svelte-bz0zu3{font-family:Open Sans,Ubuntu,Helvetica Neue,Arial,Helvetica,sans-serif;position:relative;background-color:#fff;z-index:10;border-radius:4px;margin:0;transition:max-width .25s;box-shadow:0 2px 5px #33335926;--color-text:#444952;--color-icon-button:#444952}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3:after,form.svelte-bz0zu3 .svelte-bz0zu3:before{box-sizing:border-box}form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:29px}form.can-collapse.svelte-bz0zu3 input.svelte-bz0zu3::placeholder{transition:opacity .25s;opacity:0}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3.svelte-bz0zu3:focus-within,form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px}form.svelte-bz0zu3 input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:focus-within input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:hover input.svelte-bz0zu3::placeholder{opacity:1}input.svelte-bz0zu3.svelte-bz0zu3{font:inherit;font-size:14px;flex-grow:1;min-height:29px;background-color:transparent;color:#444952;white-space:nowrap;overflow:hidden;border:0;margin:0;padding:0}input.svelte-bz0zu3.svelte-bz0zu3:focus{color:#444952;outline:0;outline:none;box-shadow:none}ul.svelte-bz0zu3.svelte-bz0zu3,div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{background-color:#fff;border-radius:4px;left:0;list-style:none;margin:0;padding:0;position:absolute;width:100%;top:calc(100% + 6px);overflow:hidden}ul.svelte-bz0zu3.svelte-bz0zu3{font-size:14px;line-height:16px;box-shadow:0 5px 10px #33335926}div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{font:inherit;line-height:18px;font-size:12px;display:flex;gap:16px}div.error.svelte-bz0zu3.svelte-bz0zu3{padding:16px;font-weight:600;color:#e25041;background-color:#fbeae8}div.error.svelte-bz0zu3 div.svelte-bz0zu3{flex-grow:1}div.error.svelte-bz0zu3 svg{flex-shrink:0;width:20px;height:20px}div.error.svelte-bz0zu3 button.svelte-bz0zu3{flex-shrink:0}div.error.svelte-bz0zu3 button.svelte-bz0zu3>svg{width:13px;fill:#e25041}div.error.svelte-bz0zu3 button.svelte-bz0zu3:hover svg,div.error.svelte-bz0zu3 button.svelte-bz0zu3:active svg{fill:#444952}div.no-results.svelte-bz0zu3.svelte-bz0zu3{padding:14px 24px 14px 16px;font-weight:400;color:#6b7c93;box-shadow:0 5px 10px #33335926}div.no-results.svelte-bz0zu3 svg{margin-top:4px;flex-shrink:0;width:20px;height:20px;width:30px;height:30px}.leaflet-bottom ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-left ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-right ul.options.svelte-bz0zu3.svelte-bz0zu3{top:auto;bottom:calc(100% + 6px)}button.svelte-bz0zu3.svelte-bz0zu3{padding:0;margin:0;border:0;background-color:transparent;height:auto;width:auto}button.svelte-bz0zu3.svelte-bz0zu3:hover{background-color:transparent}button.svelte-bz0zu3:hover svg,button.svelte-bz0zu3:active svg{fill:#2b8bfb}.input-group.svelte-bz0zu3.svelte-bz0zu3{display:flex;align-items:stretch;gap:7px;padding-inline:8px;border-radius:4px;overflow:hidden}.input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{outline:#2b8bfb solid 2px}.search-button.svelte-bz0zu3.svelte-bz0zu3{flex-shrink:0}.maplibregl-ctrl-geocoder:not(.maptiler-ctrl) .search-button svg{width:12px!important;transform:translate(.5px)}.clear-button-container.svelte-bz0zu3.svelte-bz0zu3{display:flex;display:none;position:relative;align-items:stretch}.clear-button-container.displayable.svelte-bz0zu3.svelte-bz0zu3{display:flex;flex-shrink:0}.maplibregl-ctrl-geocoder{position:relative;z-index:3}.maptiler-ctrl:not(:empty){box-shadow:none}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3{padding-inline:8px;border:white solid 2px}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{border:#2b8bfb solid 2px;outline:0;outline:none}.maptiler-ctrl form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:33px}.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:focus-within,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px} diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js new file mode 100644 index 0000000..1a901ee --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js @@ -0,0 +1,2 @@ +"use strict";var pmtiles=(()=>{var k=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var U=Math.pow;var f=(r,e)=>k(r,"name",{value:e,configurable:!0});var Xe=(r,e)=>{for(var t in e)k(r,t,{get:e[t],enumerable:!0})},_e=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ye(e))!Qe.call(r,i)&&i!==t&&k(r,i,{get:()=>e[i],enumerable:!(n=Je(e,i))||n.enumerable});return r};var et=r=>_e(k({},"__esModule",{value:!0}),r);var m=(r,e,t)=>new Promise((n,i)=>{var a=h=>{try{u(t.next(h))}catch(l){i(l)}},s=h=>{try{u(t.throw(h))}catch(l){i(l)}},u=h=>h.done?n(h.value):Promise.resolve(h.value).then(a,s);u((t=t.apply(r,e)).next())});var Dt={};Xe(Dt,{Compression:()=>Oe,EtagMismatch:()=>B,FetchSource:()=>K,FileSource:()=>oe,PMTiles:()=>P,Protocol:()=>ie,ResolvedValueCache:()=>ue,SharedPromiseCache:()=>G,TileType:()=>se,bytesToHeader:()=>$e,findTile:()=>Fe,getUint64:()=>b,leafletRasterLayer:()=>wt,readVarint:()=>R,tileIdToZxy:()=>Tt,tileTypeExt:()=>Ze,zxyToTileId:()=>Ie});var w=Uint8Array,E=Uint16Array,tt=Int32Array,Me=new w([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ue=new w([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),rt=new w([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ee=f(function(r,e){for(var t=new E(31),n=0;n<31;++n)t[n]=e+=1<>1|(g&21845)<<1,T=(T&52428)>>2|(T&13107)<<2,T=(T&61680)>>4|(T&3855)<<4,re[g]=((T&65280)>>8|(T&255)<<8)>>1;var T,g,F=f(function(r,e,t){for(var n=r.length,i=0,a=new E(e);i>h]=l}else for(u=new E(n),i=0;i>15-r[i]);return u},"hMap"),$=new w(288);for(g=0;g<144;++g)$[g]=8;var g;for(g=144;g<256;++g)$[g]=9;var g;for(g=256;g<280;++g)$[g]=7;var g;for(g=280;g<288;++g)$[g]=8;var g,Re=new w(32);for(g=0;g<32;++g)Re[g]=5;var g;var at=F($,9,1);var st=F(Re,5,1),ee=f(function(r){for(var e=r[0],t=1;te&&(e=r[t]);return e},"max"),z=f(function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},"bits"),te=f(function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},"bits16"),ot=f(function(r){return(r+7)/8|0},"shft"),ut=f(function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new w(r.subarray(e,t))},"slc");var ft=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],y=f(function(r,e,t){var n=new Error(e||ft[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,y),!t)throw n;return n},"err"),ne=f(function(r,e,t,n){var i=r.length,a=n?n.length:0;if(!i||e.f&&!e.l)return t||new w(0);var s=!t,u=s||e.i!=2,h=e.i;s&&(t=new w(i*3));var l=f(function(Te){var Ce=t.length;if(Te>Ce){var De=new w(Math.max(Ce*2,Te));De.set(t),t=De}},"cbuf"),c=e.f||0,o=e.p||0,v=e.b||0,d=e.l,p=e.d,H=e.m,I=e.n,q=i*8;do{if(!d){c=z(r,o,1);var j=z(r,o+1,3);if(o+=3,j)if(j==1)d=at,p=st,H=9,I=5;else if(j==2){var J=z(r,o,31)+257,me=z(r,o+10,15)+4,de=J+z(r,o+5,31)+1;o+=14;for(var O=new w(de),Y=new w(19),x=0;x>4;if(A<16)O[x++]=A;else{var D=0,V=0;for(A==16?(V=3+z(r,o,3),o+=2,D=O[x-1]):A==17?(V=3+z(r,o,7),o+=3):A==18&&(V=11+z(r,o,127),o+=7);V--;)O[x++]=D}}var xe=O.subarray(0,J),C=O.subarray(J);H=ee(xe),I=ee(C),d=F(xe,H,1),p=F(C,I,1)}else y(1);else{var A=ot(o)+4,W=r[A-4]|r[A-3]<<8,N=A+W;if(N>i){h&&y(0);break}u&&l(v+W),t.set(r.subarray(A,N),v),e.b=v+=W,e.p=o=N*8,e.f=c;continue}if(o>q){h&&y(0);break}}u&&l(v+131072);for(var je=(1<>4;if(o+=D&15,o>q){h&&y(0);break}if(D||y(2),M<256)t[v++]=M;else if(M==256){Q=o,d=null;break}else{var be=M-254;if(M>264){var x=M-257,Z=Me[x];be=z(r,o,(1<>4;X||y(3),o+=X&15;var C=it[_];if(_>3){var Z=Ue[_];C+=te(r,o)&(1<q){h&&y(0);break}u&&l(v+131072);var ze=v+be;if(v>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},"gzs"),ct=f(function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0},"gzl");var vt=f(function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&y(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&y(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2},"zls");function gt(r,e){return ne(r,{i:2},e&&e.out,e&&e.dictionary)}f(gt,"inflateSync");function pt(r,e){var t=ht(r);return t+8>r.length&&y(6,"invalid gzip data"),ne(r.subarray(t,-8),{i:2},e&&e.out||new w(ct(r)),e&&e.dictionary)}f(pt,"gunzipSync");function mt(r,e){return ne(r.subarray(vt(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}f(mt,"unzlibSync");function Be(r,e){return r[0]==31&&r[1]==139&&r[2]==8?pt(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?gt(r,e):mt(r,e)}f(Be,"decompressSync");var dt=typeof TextDecoder!="undefined"&&new TextDecoder,yt=0;try{dt.decode(lt,{stream:!0}),yt=1}catch(r){}var wt=f((r,e)=>{let t=!1,n="",i=L.GridLayer.extend({createTile:f((a,s)=>{let u=document.createElement("img"),h=new AbortController,l=h.signal;return u.cancel=()=>{h.abort()},t||(r.getHeader().then(c=>{c.tileType===1?console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):c.tileType===2?n="image/png":c.tileType===3?n="image/jpeg":c.tileType===4?n="image/webp":c.tileType===5&&(n="image/avif")}),t=!0),r.getZxy(a.z,a.x,a.y,l).then(c=>{if(c){let o=new Blob([c.data],{type:n}),v=window.URL.createObjectURL(o);u.src=v,u.cancel=void 0,s(void 0,u)}}).catch(c=>{if(c.name!=="AbortError")throw c}),u},"createTile"),_removeTile:f(function(a){let s=this._tiles[a];s&&(s.el.cancel&&s.el.cancel(),s.el.width=0,s.el.height=0,s.el.deleted=!0,L.DomUtil.remove(s.el),delete this._tiles[a],this.fire("tileunload",{tile:s.el,coords:this._keyToTileCoords(a)}))},"_removeTile")});return new i(e)},"leafletRasterLayer"),xt=f(r=>(e,t)=>{if(t instanceof AbortController)return r(e,t);let n=new AbortController;return r(e,n).then(i=>t(void 0,i.data,i.cacheControl||"",i.expires||""),i=>t(i)).catch(i=>t(i)),{cancel:f(()=>n.abort(),"cancel")}},"v3compat"),ae=class ae{constructor(e){this.tilev4=f((e,t)=>m(this,null,function*(){if(e.type==="json"){let v=e.url.substr(10),d=this.tiles.get(v);if(d||(d=new P(v),this.tiles.set(v,d)),this.metadata)return{data:yield d.getTileJson(e.url)};let p=yield d.getHeader();return(p.minLon>=p.maxLon||p.minLat>=p.maxLat)&&console.error(`Bounds of PMTiles archive ${p.minLon},${p.minLat},${p.maxLon},${p.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:p.minZoom,maxzoom:p.maxZoom,bounds:[p.minLon,p.minLat,p.maxLon,p.maxLat]}}}let n=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),i=e.url.match(n);if(!i)throw new Error("Invalid PMTiles protocol URL");let a=i[1],s=this.tiles.get(a);s||(s=new P(a),this.tiles.set(a,s));let u=i[2],h=i[3],l=i[4],c=yield s.getHeader(),o=yield s==null?void 0:s.getZxy(+u,+h,+l,t.signal);if(o)return{data:new Uint8Array(o.data),cacheControl:o.cacheControl,expires:o.expires};if(c.tileType===1){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4");this.tile=xt(this.tilev4);this.tiles=new Map,this.metadata=(e==null?void 0:e.metadata)||!1,this.errorOnMissingTile=(e==null?void 0:e.errorOnMissingTile)||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};f(ae,"Protocol");var ie=ae;function S(r,e){return(e>>>0)*4294967296+(r>>>0)}f(S,"toNum");function bt(r,e){let t=e.buf,n=t[e.pos++],i=(n&112)>>4;if(n<128||(n=t[e.pos++],i|=(n&127)<<3,n<128)||(n=t[e.pos++],i|=(n&127)<<10,n<128)||(n=t[e.pos++],i|=(n&127)<<17,n<128)||(n=t[e.pos++],i|=(n&127)<<24,n<128)||(n=t[e.pos++],i|=(n&1)<<31,n<128))return S(r,i);throw new Error("Expected varint not more than 10 bytes")}f(bt,"readVarintRemainder");function R(r){let e=r.buf,t=e[r.pos++],n=t&127;return t<128||(t=e[r.pos++],n|=(t&127)<<7,t<128)||(t=e[r.pos++],n|=(t&127)<<14,t<128)||(t=e[r.pos++],n|=(t&127)<<21,t<128)?n:(t=e[r.pos],n|=(t&15)<<28,bt(n,r))}f(R,"readVarint");function He(r,e,t,n){if(n===0){t===1&&(e[0]=r-1-e[0],e[1]=r-1-e[1]);let i=e[0];e[0]=e[1],e[1]=i}}f(He,"rotate");function zt(r,e){let t=U(2,r),n=e,i=e,a=e,s=[0,0],u=1;for(;u26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>U(2,r)-1||t>U(2,r)-1)throw new Error("tile x/y outside zoom level bounds");let n=At[r],i=U(2,r),a=0,s=0,u=0,h=[e,t],l=i/2;for(;l>0;)a=(h[0]&l)>0?1:0,s=(h[1]&l)>0?1:0,u+=l*l*(3*a^s),He(l,h,a,s),l=l/2;return n+u}f(Ie,"zxyToTileId");function Tt(r){let e=0,t=0;for(let n=0;n<27;n++){let i=(1<r)return zt(n,r-e);e+=i}throw new Error("Tile zoom level exceeds max safe number limit (26)")}f(Tt,"tileIdToZxy");var Oe=(a=>(a[a.Unknown=0]="Unknown",a[a.None=1]="None",a[a.Gzip=2]="Gzip",a[a.Brotli=3]="Brotli",a[a.Zstd=4]="Zstd",a))(Oe||{});function fe(r,e){return m(this,null,function*(){if(e===1||e===0)return r;if(e===2){if(typeof globalThis.DecompressionStream=="undefined")return Be(new Uint8Array(r));let t=new Response(r).body;if(!t)throw new Error("Failed to read response stream");let n=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(n).arrayBuffer()}throw new Error("Compression method not supported")})}f(fe,"defaultDecompress");var se=(s=>(s[s.Unknown=0]="Unknown",s[s.Mvt=1]="Mvt",s[s.Png=2]="Png",s[s.Jpeg=3]="Jpeg",s[s.Webp=4]="Webp",s[s.Avif=5]="Avif",s))(se||{});function Ze(r){return r===1?".mvt":r===2?".png":r===3?".jpg":r===4?".webp":r===5?".avif":""}f(Ze,"tileTypeExt");var Ct=127;function Fe(r,e){let t=0,n=r.length-1;for(;t<=n;){let i=n+t>>1,a=e-r[i].tileId;if(a>0)t=i+1;else if(a<0)n=i-1;else return r[i]}return n>=0&&(r[n].runLength===0||e-r[n].tileId-1,a=/Chrome|Chromium|Edg|OPR|Brave/.test(n);this.chromeWindowsNoCache=!1,i&&a&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,n,i){return m(this,null,function*(){let a,s;n?s=n:(a=new AbortController,s=a.signal);let u=new Headers(this.customHeaders);u.set("range",`bytes=${e}-${e+t-1}`);let h;this.mustReload?h="reload":this.chromeWindowsNoCache&&(h="no-store");let l=yield fetch(this.url,{signal:s,cache:h,headers:u});if(e===0&&l.status===416){let d=l.headers.get("Content-Range");if(!d||!d.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let p=+d.substr(8);l=yield fetch(this.url,{signal:s,cache:"reload",headers:{range:`bytes=0-${p-1}`}})}let c=l.headers.get("Etag");if(c!=null&&c.startsWith("W/")&&(c=null),l.status===416||i&&c&&c!==i)throw this.mustReload=!0,new B(`Server returned non-matching ETag ${i} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(l.status>=300)throw new Error(`Bad response code: ${l.status}`);let o=l.headers.get("Content-Length");if(l.status===200&&(!o||+o>t))throw a&&a.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield l.arrayBuffer(),etag:c||void 0,cacheControl:l.headers.get("Cache-Control")||void 0,expires:l.headers.get("Expires")||void 0}})}};f(he,"FetchSource");var K=he;function b(r,e){let t=r.getUint32(e+4,!0),n=r.getUint32(e+0,!0);return t*U(2,32)+n}f(b,"getUint64");function $e(r,e){let t=new DataView(r),n=t.getUint8(7);if(n>3)throw new Error(`Archive is spec version ${n} but this library supports up to spec version 3`);return{specVersion:n,rootDirectoryOffset:b(t,8),rootDirectoryLength:b(t,16),jsonMetadataOffset:b(t,24),jsonMetadataLength:b(t,32),leafDirectoryOffset:b(t,40),leafDirectoryLength:b(t,48),tileDataOffset:b(t,56),tileDataLength:b(t,64),numAddressedTiles:b(t,72),numTileEntries:b(t,80),numTileContents:b(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}f($e,"bytesToHeader");function Ve(r){let e={buf:new Uint8Array(r),pos:0},t=R(e),n=[],i=0;for(let a=0;a0?n[a].offset=n[a-1].offset+n[a-1].length:n[a].offset=s-1}return n}f(Ve,"deserializeIndex");var ce=class ce extends Error{};f(ce,"EtagMismatch");var B=ce;function ke(r,e){return m(this,null,function*(){let t=yield r.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let i=t.data.slice(0,Ct),a=$e(i,t.etag),s=t.data.slice(a.rootDirectoryOffset,a.rootDirectoryOffset+a.rootDirectoryLength),u=`${r.getKey()}|${a.etag||""}|${a.rootDirectoryOffset}|${a.rootDirectoryLength}`,h=Ve(yield e(s,a.internalCompression));return[a,[u,h.length,h]]})}f(ke,"getHeaderAndRoot");function Ke(r,e,t,n,i){return m(this,null,function*(){let a=yield r.getBytes(t,n,void 0,i.etag),s=yield e(a.data,i.internalCompression),u=Ve(s);if(u.length===0)throw new Error("Empty directory is invalid");return u})}f(Ke,"getDirectory");var ve=class ve{constructor(e=100,t=!0,n=fe){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return m(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,n.data;let i=yield ke(e,this.decompress);return i[1]&&this.cache.set(i[1][0],{lastUsed:this.counter++,data:i[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:i[0]}),this.prune(),i[0]})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,s.data;let u=yield Ke(e,this.decompress,t,n,i);return this.cache.set(a,{lastUsed:this.counter++,data:u}),this.prune(),u})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{ke(e,this.decompress).then(u=>{u[1]&&this.cache.set(u[1][0],{lastUsed:this.counter++,data:Promise.resolve(u[1][2])}),a(u[0]),this.prune()}).catch(u=>{s(u)})});return this.cache.set(t,{lastUsed:this.counter++,data:i}),i})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,yield s.data;let u=new Promise((h,l)=>{Ke(e,this.decompress,t,n,i).then(c=>{h(c),this.prune()}).catch(c=>{l(c)})});return this.cache.set(a,{lastUsed:this.counter++,data:u}),u})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{this.getHeader(e).then(s=>{i(),this.invalidations.delete(t)}).catch(s=>{a(s)})});this.invalidations.set(t,n)})}};f(ge,"SharedPromiseCache");var G=ge,pe=class pe{constructor(e,t,n){typeof e=="string"?this.source=new K(e):this.source=e,n?this.decompress=n:this.decompress=fe,t?this.cache=t:this.cache=new G}getHeader(){return m(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,n,i){return m(this,null,function*(){let a=Ie(e,t,n),s=yield this.cache.getHeader(this.source);if(es.maxZoom)return;let u=s.rootDirectoryOffset,h=s.rootDirectoryLength;for(let l=0;l<=3;l++){let c=yield this.cache.getDirectory(this.source,u,h,s),o=Fe(c,a);if(o){if(o.runLength>0){let v=yield this.source.getBytes(s.tileDataOffset+o.offset,o.length,i,s.etag);return{data:yield this.decompress(v.data,s.tileCompression),cacheControl:v.cacheControl,expires:v.expires}}u=s.leafDirectoryOffset+o.offset,h=o.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,n,i){return m(this,null,function*(){try{return yield this.getZxyAttempt(e,t,n,i)}catch(a){if(a instanceof B)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,n,i);throw a}})}getMetadataAttempt(){return m(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),n=yield this.decompress(t.data,e.internalCompression),i=new TextDecoder("utf-8");return JSON.parse(i.decode(n))})}getMetadata(){return m(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof B)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return m(this,null,function*(){let t=yield this.getHeader(),n=yield this.getMetadata(),i=Ze(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${i}`],vector_layers:n.vector_layers,attribution:n.attribution,description:n.description,name:n.name,version:n.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};f(pe,"PMTiles");var P=pe;return et(Dt);})(); +//# sourceMappingURL=pmtiles.js.map \ No newline at end of file diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js new file mode 100644 index 0000000..2b7b5bf --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js @@ -0,0 +1,311 @@ +// Radius/Circle drawing mode for Mapbox GL Draw +// Creates a circle by drawing from center to edge +(function (MapboxDraw) { + const DrawLine = MapboxDraw.modes.draw_line_string; + + // Utility function to create a vertex feature + const createVertex = function (parentId, coordinates, path, selected) { + return { + type: "Feature", + properties: { + meta: "vertex", + parent: parentId, + coord_path: path, + active: selected ? "true" : "false" + }, + geometry: { + type: "Point", + coordinates: coordinates + } + }; + }; + + // Utility function to calculate distance between two points in kilometers + const calculateDistance = function (coord1, coord2) { + const lat1 = coord1[1]; + const lon1 = coord1[0]; + const lat2 = coord2[1]; + const lon2 = coord2[0]; + + const R = 6371; // Radius of the Earth in kilometers + const dLat = (lat2 - lat1) * Math.PI / 180; + const dLon = (lon2 - lon1) * Math.PI / 180; + const a = + Math.sin(dLat/2) * Math.sin(dLat/2) + + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * + Math.sin(dLon/2) * Math.sin(dLon/2); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + const distance = R * c; + + return distance; + }; + + // Utility function to create a GeoJSON circle + const createGeoJSONCircle = function (center, radiusInKm, parentId, points) { + points = points || 64; + + const coords = { + latitude: center[1], + longitude: center[0] + }; + + const km = radiusInKm; + const ret = []; + const distanceX = km / (111.32 * Math.cos((coords.latitude * Math.PI) / 180)); + const distanceY = km / 110.574; + + let theta, x, y; + for (let i = 0; i < points; i++) { + theta = (i / points) * (2 * Math.PI); + x = distanceX * Math.cos(theta); + y = distanceY * Math.sin(theta); + + ret.push([coords.longitude + x, coords.latitude + y]); + } + ret.push(ret[0]); + + return { + type: "Feature", + geometry: { + type: "Polygon", + coordinates: [ret] + }, + properties: { + parent: parentId, + meta: "radius" + } + }; + }; + + // Utility function to format distance for display + const getDisplayMeasurements = function (distanceKm) { + let metricUnits = "m"; + let metricFormat = "0,0"; + let metricMeasurement; + + let standardUnits = "feet"; + let standardFormat = "0,0"; + let standardMeasurement; + + metricMeasurement = distanceKm * 1000; // Convert to meters + if (metricMeasurement >= 1000) { + metricMeasurement = metricMeasurement / 1000; + metricUnits = "km"; + metricFormat = "0.00"; + } + + standardMeasurement = distanceKm * 1000 * 3.28084; // Convert to feet + if (standardMeasurement >= 5280) { + standardMeasurement = standardMeasurement / 5280; + standardUnits = "mi"; + standardFormat = "0.00"; + } + + // Simple number formatting (without numeral.js dependency) + const formatNumber = function(num, format) { + if (format === "0,0") { + return Math.round(num).toLocaleString(); + } else if (format === "0.00") { + return num.toFixed(2); + } + return num.toString(); + }; + + return { + metric: formatNumber(metricMeasurement, metricFormat) + " " + metricUnits, + standard: formatNumber(standardMeasurement, standardFormat) + " " + standardUnits + }; + }; + + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RadiusMode = Object.assign({}, DrawLine); + + RadiusMode.onSetup = function (opts) { + const line = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "LineString", + coordinates: [] + } + }); + + this.addFeature(line); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.activateUIButton("line"); + this.setActionableState({ trash: true }); + + return { + line: line, + currentVertexPosition: 0, + direction: "forward" + }; + }; + + RadiusMode.onClick = function (state, e) { + // This ends the drawing after the user creates a second point + if (state.currentVertexPosition === 1) { + // Update the second coordinate in place, don't add at position 0 + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + return this.changeMode("simple_select", { featureIds: [state.line.id] }); + } + + this.updateUIClasses({ mouse: "add" }); + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + + if (state.direction === "forward") { + state.currentVertexPosition += 1; + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + } else { + state.line.addCoordinate(0, e.lngLat.lng, e.lngLat.lat); + } + + return null; + }; + + RadiusMode.onMouseMove = function (state, e) { + if (state.currentVertexPosition === 1) { + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + } + }; + + // Creates the final geojson circle polygon + RadiusMode.onStop = function (state) { + doubleClickZoom.enable(this); + this.activateUIButton(); + + // Check to see if we've deleted this feature + if (this.getFeature(state.line.id) === undefined) return; + + if (state.line.isValid()) { + const lineGeoJson = state.line.toGeoJSON(); + const coords = lineGeoJson.geometry.coordinates; + + if (coords.length >= 2) { + // Calculate radius in kilometers + const radiusKm = calculateDistance(coords[0], coords[1]); + + // Create the circle polygon + const circleFeature = createGeoJSONCircle(coords[0], radiusKm, state.line.id); + + // Add radius property for reference + circleFeature.properties.radius = (radiusKm * 1000).toFixed(1); + + // Remove the meta property that was interfering + delete circleFeature.properties.meta; + delete circleFeature.properties.parent; + + // Delete the temporary line first + this.deleteFeature([state.line.id], { silent: true }); + + // Add the circle feature to the draw instance + const circleDrawFeature = this.newFeature(circleFeature); + this.addFeature(circleDrawFeature); + + this.map.fire("draw.create", { + features: [circleDrawFeature.toGeoJSON()] + }); + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + + this.changeMode("simple_select", {}, { silent: true }); + }; + + RadiusMode.toDisplayFeatures = function (state, geojson, display) { + const isActiveLine = geojson.properties.id === state.line.id; + geojson.properties.active = isActiveLine ? "true" : "false"; + + if (!isActiveLine) return display(geojson); + + // Only render the line if it has at least one real coordinate + if (geojson.geometry.coordinates.length < 2) return null; + + geojson.properties.meta = "feature"; + + // Display center vertex as a point feature + display(createVertex( + state.line.id, + geojson.geometry.coordinates[ + state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1 + ], + "" + (state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1), + false + )); + + // Display the line as it is drawn + display(geojson); + + const coords = geojson.geometry.coordinates; + if (coords.length >= 2) { + const distanceKm = calculateDistance(coords[0], coords[1]); + const displayMeasurements = getDisplayMeasurements(distanceKm); + + // Create custom feature for the current pointer position + const currentVertex = { + type: "Feature", + properties: { + meta: "currentPosition", + radiusMetric: displayMeasurements.metric, + radiusStandard: displayMeasurements.standard, + parent: state.line.id + }, + geometry: { + type: "Point", + coordinates: coords[1] + } + }; + display(currentVertex); + + // Create custom feature for radius circle + const center = coords[0]; + const circleFeature = createGeoJSONCircle(center, distanceKm, state.line.id); + display(circleFeature); + } + + return null; + }; + + RadiusMode.onTrash = function (state) { + this.deleteFeature([state.line.id], { silent: true }); + this.changeMode("simple_select"); + }; + + MapboxDraw.modes.draw_radius = RadiusMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js new file mode 100644 index 0000000..73af6d6 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js @@ -0,0 +1,124 @@ +// Rectangle drawing mode for Mapbox GL Draw +// Adapted from https://github.com/edgespatial/mapbox-gl-draw-rectangle-mode +(function (MapboxDraw) { + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RectangleMode = { + onSetup: function (opts) { + const rectangle = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "Polygon", + coordinates: [[]] + } + }); + + this.addFeature(rectangle); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.setActionableState({ trash: true }); + + return { + rectangle: rectangle + }; + }, + + onClick: function (state, e) { + // If we have a start point and click on a different point, complete the rectangle + if (state.startPoint && + (state.startPoint[0] !== e.lngLat.lng || state.startPoint[1] !== e.lngLat.lat)) { + this.updateUIClasses({ mouse: "pointer" }); + state.endPoint = [e.lngLat.lng, e.lngLat.lat]; + this.changeMode("simple_select", { featuresId: state.rectangle.id }); + return; + } + + // Set the start point + const startPoint = [e.lngLat.lng, e.lngLat.lat]; + state.startPoint = startPoint; + }, + + onMouseMove: function (state, e) { + // Update rectangle coordinates as the mouse moves + if (state.startPoint) { + const startX = state.startPoint[0]; + const startY = state.startPoint[1]; + const endX = e.lngLat.lng; + const endY = e.lngLat.lat; + + state.rectangle.updateCoordinate("0.0", startX, startY); + state.rectangle.updateCoordinate("0.1", endX, startY); + state.rectangle.updateCoordinate("0.2", endX, endY); + state.rectangle.updateCoordinate("0.3", startX, endY); + state.rectangle.updateCoordinate("0.4", startX, startY); + } + }, + + onKeyUp: function (state, e) { + if (e.keyCode === 27) { // Escape key + return this.changeMode("simple_select"); + } + }, + + onStop: function (state) { + doubleClickZoom.enable(this); + this.updateUIClasses({ mouse: "none" }); + this.activateUIButton(); + + if (this.getFeature(state.rectangle.id) !== undefined) { + // Remove the closing coordinate (duplicate of first) + state.rectangle.removeCoordinate("0.4"); + + if (state.rectangle.isValid()) { + this.map.fire("draw.create", { + features: [state.rectangle.toGeoJSON()] + }); + } else { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select", {}, { silent: true }); + } + } + }, + + toDisplayFeatures: function (state, geojson, display) { + const isActiveRectangle = geojson.properties.id === state.rectangle.id; + geojson.properties.active = isActiveRectangle ? "true" : "false"; + + if (!isActiveRectangle) { + return display(geojson); + } + + // Only display the rectangle if we have started drawing + if (state.startPoint) { + return display(geojson); + } + }, + + onTrash: function (state) { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select"); + } + }; + + MapboxDraw.modes.draw_rectangle = RectangleMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/turf/turf.min.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/turf/turf.min.js new file mode 100644 index 0000000..635896d --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/lib/turf/turf.min.js @@ -0,0 +1,37 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).turf={})}(this,(function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}function u(t,e,n){return(e=y(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function l(t){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},l(t)}function h(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&p(t,e)}function c(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(c=function(){return!!t})()}function f(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}function g(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function p(t,e){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},p(t,e)}function v(t,e){return n(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,o,s,a=[],u=!0,l=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);u=!0);}catch(t){l=!0,i=t}finally{try{if(!u&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw i}}return a}}(t,e)||_(t,e)||g()}function d(t){return function(t){if(Array.isArray(t))return e(t)}(t)||f(t)||_(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function m(t){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},m(t)}function _(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var x=6371008.8,E={centimeters:100*x,centimetres:100*x,degrees:360/(2*Math.PI),feet:3.28084*x,inches:39.37*x,kilometers:x/1e3,kilometres:x/1e3,meters:x,metres:x,miles:x/1609.344,millimeters:1e3*x,millimetres:1e3*x,nauticalmiles:x/1852,radians:1,yards:1.0936*x},k={acres:247105e-9,centimeters:1e4,centimetres:1e4,feet:10.763910417,hectares:1e-4,inches:1550.003100006,kilometers:1e-6,kilometres:1e-6,meters:1,metres:1,miles:386e-9,nauticalmiles:2.9155334959812285e-7,millimeters:1e6,millimetres:1e6,yards:1.195990046};function b(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={type:"Feature"};return(0===n.id||n.id)&&(r.id=n.id),n.bbox&&(r.bbox=n.bbox),r.properties=e||{},r.geometry=t,r}function w(t,e){switch(t){case"Point":return I(e).geometry;case"LineString":return L(e).geometry;case"Polygon":return S(e).geometry;case"MultiPoint":return O(e).geometry;case"MultiLineString":return T(e).geometry;case"MultiPolygon":return R(e).geometry;default:throw new Error(t+" is invalid")}}function I(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("coordinates is required");if(!Array.isArray(t))throw new Error("coordinates must be an Array");if(t.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!U(t[0])||!U(t[1]))throw new Error("coordinates must contain numbers");return b({type:"Point",coordinates:t},e,n)}function N(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return I(t,e)})),n)}function S(t,e){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=a(t);try{for(i.s();!(n=i.n()).done;){var o=n.value;if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(var s=0;s2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return S(t,e)})),n)}function L(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(t.length<2)throw new Error("coordinates must be an array of two or more positions");return b({type:"LineString",coordinates:t},e,n)}function P(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return L(t,e)})),n)}function C(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={type:"FeatureCollection"};return e.id&&(n.id=e.id),e.bbox&&(n.bbox=e.bbox),n.features=t,n}function T(t,e){return b({type:"MultiLineString",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function O(t,e){return b({type:"MultiPoint",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function R(t,e){return b({type:"MultiPolygon",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function A(t,e){return b({type:"GeometryCollection",geometries:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function D(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e&&!(e>=0))throw new Error("precision must be a positive number");var n=Math.pow(10,e||0);return Math.round(t*n)/n}function F(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t*n}function q(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t/n}function V(t,e){return Y(q(t,e))}function G(t){var e=t%360;return e<0&&(e+=360),e}function B(t){return(t%=360)>180?t-360:t<-180?t+360:t}function Y(t){return 180*(t%(2*Math.PI))/Math.PI}function z(t){return t%360*Math.PI/180}function j(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("length must be a positive number");return F(q(t,e),n)}function X(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"meters",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("area must be a positive number");var r=k[e];if(!r)throw new Error("invalid original units");var i=k[n];if(!i)throw new Error("invalid final units");return t/r*i}function U(t){return!isNaN(t)&&null!==t&&!Array.isArray(t)}function Z(t){return null!==t&&"object"===m(t)&&!Array.isArray(t)}function H(t){if(!t)throw new Error("bbox is required");if(!Array.isArray(t))throw new Error("bbox must be an Array");if(4!==t.length&&6!==t.length)throw new Error("bbox must be an Array of 4 or 6 numbers");t.forEach((function(t){if(!U(t))throw new Error("bbox must only contain numbers")}))}function W(t){if(!t)throw new Error("id is required");if(-1===["string","number"].indexOf(m(t)))throw new Error("id must be a number or a string")}var J=Object.freeze({__proto__:null,areaFactors:k,azimuthToBearing:B,bearingToAzimuth:G,convertArea:X,convertLength:j,degreesToRadians:z,earthRadius:x,factors:E,feature:b,featureCollection:C,geometry:w,geometryCollection:A,isNumber:U,isObject:Z,lengthToDegrees:V,lengthToRadians:q,lineString:L,lineStrings:P,multiLineString:T,multiPoint:O,multiPolygon:R,point:I,points:N,polygon:S,polygons:M,radiansToDegrees:Y,radiansToLength:F,round:D,validateBBox:H,validateId:W});function K(t){if(!t)throw new Error("coord is required");if(!Array.isArray(t)){if("Feature"===t.type&&null!==t.geometry&&"Point"===t.geometry.type)return d(t.geometry.coordinates);if("Point"===t.type)return d(t.coordinates)}if(Array.isArray(t)&&t.length>=2&&!Array.isArray(t[0])&&!Array.isArray(t[1]))return d(t);throw new Error("coord must be GeoJSON Point or an Array of numbers")}function Q(t){if(Array.isArray(t))return t;if("Feature"===t.type){if(null!==t.geometry)return t.geometry.coordinates}else if(t.coordinates)return t.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function $(t){if(t.length>1&&U(t[0])&&U(t[1]))return!0;if(Array.isArray(t[0])&&t[0].length)return $(t[0]);throw new Error("coordinates must only contain numbers")}function tt(t,e,n){if(!e||!n)throw new Error("type and name required");if(!t||t.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.type)}function et(t,e,n){if(!t)throw new Error("No feature passed");if(!n)throw new Error(".featureOf() requires a name");if(!t||"Feature"!==t.type||!t.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!t.geometry||t.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.geometry.type)}function nt(t,e,n){if(!t)throw new Error("No featureCollection passed");if(!n)throw new Error(".collectionOf() requires a name");if(!t||"FeatureCollection"!==t.type)throw new Error("Invalid input to "+n+", FeatureCollection required");var r,i=a(t.features);try{for(i.s();!(r=i.n()).done;){var o=r.value;if(!o||"Feature"!==o.type||!o.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!o.geometry||o.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+o.geometry.type)}}catch(t){i.e(t)}finally{i.f()}}function rt(t){return"Feature"===t.type?t.geometry:t}function it(t,e){return"FeatureCollection"===t.type?"FeatureCollection":"GeometryCollection"===t.type?"GeometryCollection":"Feature"===t.type&&null!==t.geometry?t.geometry.type:t.type}var ot=Object.freeze({__proto__:null,collectionOf:nt,containsNumber:$,featureOf:et,geojsonType:tt,getCoord:K,getCoords:Q,getGeom:rt,getType:it});function st(t,e){if(!0===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final)return function(t,e){var n=st(e,t);return n=(n+180)%360}(t,e);var n=K(t),r=K(e),i=z(n[0]),o=z(r[0]),s=z(n[1]),a=z(r[1]),u=Math.sin(o-i)*Math.cos(a),l=Math.cos(s)*Math.sin(a)-Math.sin(s)*Math.cos(a)*Math.cos(o-i);return Y(Math.atan2(u,l))}function at(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=K(t),o=z(i[0]),s=z(i[1]),a=z(n),u=q(e,r.units),l=Math.asin(Math.sin(s)*Math.cos(u)+Math.cos(s)*Math.sin(u)*Math.cos(a));return I([Y(o+Math.atan2(Math.sin(a)*Math.sin(u)*Math.cos(s),Math.cos(u)-Math.sin(s)*Math.sin(l))),Y(l)],r.properties)}function ut(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e),o=z(i[1]-r[1]),s=z(i[0]-r[0]),a=z(r[1]),u=z(i[1]),l=Math.pow(Math.sin(o/2),2)+Math.pow(Math.sin(s/2),2)*Math.cos(a)*Math.cos(u);return F(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)),n.units)}function lt(t,e){var n;return(n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final?ht(K(e),K(t)):ht(K(t),K(e)))>180?-(360-n):n}function ht(t,e){var n=z(t[1]),r=z(e[1]),i=z(e[0]-t[0]);i>Math.PI&&(i-=2*Math.PI),i<-Math.PI&&(i+=2*Math.PI);var o=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(n/2+Math.PI/4));return(Y(Math.atan2(i,o))+360)%360}function ct(t,e,n){if(null!==t)for(var r,i,o,s,a,u,l,h,c=0,f=0,g=t.type,p="FeatureCollection"===g,v="Feature"===g,d=p?t.features.length:1,y=0;ya||f>u||g>l)return s=o,a=n,u=f,l=g,void(i=0);var p=L([s,o],t.properties);if(!1===e(p,n,r,g,i))return!1;i++,s=o}))&&void 0}}}))}function bt(t,e,n){var r=n,i=!1;return kt(t,(function(t,o,s,a,u){r=!1===i&&void 0===n?t:e(r,t,o,s,a,u),i=!0})),r}function wt(t,e){if(!t)throw new Error("geojson is required");xt(t,(function(t,n,r){if(null!==t.geometry){var i=t.geometry.type,o=t.geometry.coordinates;switch(i){case"LineString":if(!1===e(t,n,r,0,0))return!1;break;case"Polygon":for(var s=0;s0){e+=Math.abs(Ot(t[0]));for(var n=1;n=e?(r+2)%e:r+2],a=i[0]*Tt,u=o[1]*Tt;n+=(s[0]*Tt-a)*Math.sin(u),r++}return n*Ct}function Rt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=t.bbox&&!0!==e.recompute)return t.bbox;var n=[1/0,1/0,-1/0,-1/0];return ct(t,(function(t){n[0]>t[0]&&(n[0]=t[0]),n[1]>t[1]&&(n[1]=t[1]),n[2]e[2]&&(n|=2),t[1]e[3]&&(n|=8),n}function qt(t,e){var n,r=[],i=a(t);try{for(i.s();!(n=i.n()).done;){var o=At(n.value,e);o.length>0&&(o[0][0]===o[o.length-1][0]&&o[0][1]===o[o.length-1][1]||o.push(o[0]),o.length>=4&&r.push(o))}}catch(t){i.e(t)}finally{i.f()}return r}function Vt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Number(t[0]),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]);if(6===t.length)throw new Error("@turf/bbox-polygon does not support BBox with 6 positions");var s=[n,r];return S([[s,[i,r],[i,o],[n,o],s]],e.properties,{bbox:t,id:e.id})}var Gt=function(){return s((function t(e){i(this,t),this.points=e.points||[],this.duration=e.duration||1e4,this.sharpness=e.sharpness||.85,this.centers=[],this.controls=[],this.stepLength=e.stepLength||60,this.length=this.points.length,this.delay=0;for(var n=0;nt&&(e.push(r),n=i)}return e}},{key:"vector",value:function(t){var e=this.pos(t+10),n=this.pos(t-10);return{angle:180*Math.atan2(e.y-n.y,e.x-n.x)/3.14,speed:Math.sqrt((n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y)+(n.z-e.z)*(n.z-e.z))}}},{key:"pos",value:function(t){var e=t-this.delay;e<0&&(e=0),e>this.duration&&(e=this.duration-1);var n=e/this.duration;if(n>=1)return this.points[this.length-1];var r=Math.floor((this.points.length-1)*n);return function(t,e,n,r,i){var o=function(t){var e=t*t,n=e*t;return[n,3*e*(1-t),3*t*(1-t)*(1-t),(1-t)*(1-t)*(1-t)]}(t),s={x:i.x*o[0]+r.x*o[1]+n.x*o[2]+e.x*o[3],y:i.y*o[0]+r.y*o[1]+n.y*o[2]+e.y*o[3],z:i.z*o[0]+r.z*o[1]+n.z*o[2]+e.z*o[3]};return s}((this.length-1)*n-r,this.points[r],this.controls[r][1],this.controls[r+1][0],this.points[r+1])}}])}();function Bt(t){for(var e,n,r=Q(t),i=0,o=1;o0}function Yt(t,e){for(var n=0,r=0,i=0,o=0,s=0,a=0,u=0,l=0,h=null,c=null,f=t[0],g=t[1],p=e.length;n0&&l>0)a=l,s=(h=c)[0]-f;else{if(u=c[0]-t[0],l>0&&a<=0){if((o=s*l-u*a)>0)i+=1;else if(0===o)return 0}else if(a>0&&l<=0){if((o=s*l-u*a)<0)i+=1;else if(0===o)return 0}else if(0===l&&a<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&l<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&0===l){if(u<=0&&s>=0)return 0;if(s<=0&&u>=0)return 0}h=c,a=l,s=u}}return i%2!=0}function zt(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("point is required");if(!e)throw new Error("polygon is required");var r=K(t),i=rt(e),o=i.type,s=e.bbox,a=i.coordinates;if(s&&!1===function(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}(r,s))return!1;"Polygon"===o&&(a=[a]);for(var u=!1,l=0;l2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=Q(e),o=0;oi)return!1}else if(0!==g)return!1;return Math.abs(c)===Math.abs(f)&&0===Math.abs(c)?!r&&(n[0]===t[0]&&n[1]===t[1]):r?"start"===r?Math.abs(c)>=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o0?u<=s&&s=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o<=l:l<=o&&o<=a:f>0?u<=s&&s<=h:h<=s&&s<=u}function Ut(t,e){if("Feature"===t.type&&null===t.geometry)return!1;if("Feature"===e.type&&null===e.geometry)return!1;if(!Zt(Rt(t),Rt(e)))return!1;var n,r=a(rt(e).coordinates);try{for(r.s();!(n=r.n()).done;){var i,o=a(n.value);try{for(o.s();!(i=o.n()).done;){if(!zt(i.value,t))return!1}}catch(t){o.e(t)}finally{o.f()}}}catch(t){r.e(t)}finally{r.f()}return!0}function Zt(t,e){return!(t[0]>e[0])&&(!(t[2]e[1])&&!(t[3]0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Kt;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function Kt(t,e){return te?1:0}function Qt(t,e){return t.p.x>e.p.x?1:t.p.xe.p.y?1:-1:1}function $t(t,e){return t.rightSweepEvent.p.x>e.rightSweepEvent.p.x?1:t.rightSweepEvent.p.x0?(h.isLeftEndpoint=!0,l.isLeftEndpoint=!1):(l.isLeftEndpoint=!0,h.isLeftEndpoint=!1),e.push(l),e.push(h),s=a,re+=1}}ee+=1}var oe=s((function t(e){i(this,t),this.leftSweepEvent=e,this.rightSweepEvent=e.otherEvent}));function se(t,e){if(null===t||null===e)return!1;if(t.leftSweepEvent.ringId===e.leftSweepEvent.ringId&&(t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.rightSweepEvent)||t.leftSweepEvent.isSamePoint(e.leftSweepEvent)||t.leftSweepEvent.isSamePoint(e.rightSweepEvent)))return!1;var n=t.leftSweepEvent.p.x,r=t.leftSweepEvent.p.y,i=t.rightSweepEvent.p.x,o=t.rightSweepEvent.p.y,s=e.leftSweepEvent.p.x,a=e.leftSweepEvent.p.y,u=e.rightSweepEvent.p.x,l=e.rightSweepEvent.p.y,h=(l-a)*(i-n)-(u-s)*(o-r),c=(u-s)*(r-a)-(l-a)*(n-s),f=(i-n)*(r-a)-(o-r)*(n-s);if(0===h)return!1;var g=c/h,p=f/h;return g>=0&&g<=1&&p>=0&&p<=1&&[n+g*(i-n),r+g*(o-r)]}var ae=function(t,e){var n=new Jt([],Qt);return function(t,e){if("FeatureCollection"===t.type)for(var n=t.features,r=0;r2&&void 0!==arguments[2]?arguments[2]:{},r=n.removeDuplicates,i=void 0===r||r,o=n.ignoreSelfIntersections,s=void 0===o||o,a=[];"FeatureCollection"===t.type?a=a.concat(t.features):"Feature"===t.type?a.push(t):"LineString"!==t.type&&"Polygon"!==t.type&&"MultiLineString"!==t.type&&"MultiPolygon"!==t.type||a.push(b(t)),"FeatureCollection"===e.type?a=a.concat(e.features):"Feature"===e.type?a.push(e):"LineString"!==e.type&&"Polygon"!==e.type&&"MultiLineString"!==e.type&&"MultiPolygon"!==e.type||a.push(b(e));var u=ae(C(a),s),l=[];if(i){var h={};u.forEach((function(t){var e=t.join(",");h[e]||(h[e]=!0,l.push(t))}))}else l=u;return C(l.map((function(t){return I(t)})))}function le(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t);switch(e.properties||"Feature"!==t.type||(e.properties=t.properties),n.type){case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{};return he(r,i)}(n,e);case"MultiPolygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{},o=[];return r.forEach((function(t){o.push(he(t,i))})),C(o)}(n,e);default:throw new Error("invalid poly")}}function he(t,e){return t.length>1?T(t,e):L(t[0],e)}function ce(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;switch(i){case"MultiPoint":switch(o){case"LineString":return fe(n,r);case"Polygon":return pe(n,r);default:throw new Error("feature2 "+o+" geometry not supported")}case"LineString":switch(o){case"MultiPoint":return fe(r,n);case"LineString":return function(t,e){if(ue(t,e).features.length>0)for(var n=0;n0}function pe(t,e){for(var n=!1,r=!1,i=t.coordinates.length,o=0;o=Math.abs(a)?s>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:a>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1]:Math.abs(s)>=Math.abs(a)?s>0?t[0]0?t[1]2&&void 0!==arguments[2]?arguments[2]:{ignoreSelfIntersections:!0}).ignoreSelfIntersections,r=void 0===n||n,i=!0;return xt(t,(function(t){xt(e,(function(e){if(!1===i)return!1;i=function(t,e,n){switch(t.type){case"Point":switch(e.type){case"Point":return r=t.coordinates,i=e.coordinates,!(r[0]===i[0]&&r[1]===i[1]);case"LineString":return!ye(e,t);case"Polygon":return!zt(t,e)}break;case"LineString":switch(e.type){case"Point":return!ye(t,e);case"LineString":return!function(t,e,n){var r=ue(t,e,{ignoreSelfIntersections:n});if(r.features.length>0)return!0;return!1}(t,e,n);case"Polygon":return!me(e,t,n)}break;case"Polygon":switch(e.type){case"Point":return!zt(e,t);case"LineString":return!me(t,e,n);case"Polygon":return!function(t,e,n){var r,i=a(t.coordinates[0]);try{for(i.s();!(r=i.n()).done;){if(zt(r.value,e))return!0}}catch(t){i.e(t)}finally{i.f()}var o,s=a(e.coordinates[0]);try{for(s.s();!(o=s.n()).done;){if(zt(o.value,t))return!0}}catch(t){s.e(t)}finally{s.f()}var u=ue(le(t),le(e),{ignoreSelfIntersections:n});if(u.features.length>0)return!0;return!1}(e,t,n)}}var r,i;return!1}(t.geometry,e.geometry,r)}))})),i}function ye(t,e){for(var n=0;n0}function _e(t,e,n){var r=n[0]-t[0],i=n[1]-t[1],o=e[0]-t[0],s=e[1]-t[1];return 0==r*s-i*o&&(Math.abs(o)>=Math.abs(s)?o>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:s>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1])}var xe=Object.defineProperty,Ee=function(t,e){return xe(t,"name",{value:e,configurable:!0})},ke=function(){return s((function t(e){var n,r,o;i(this,t),this.direction=!1,this.compareProperties=!0,this.precision=Math.pow(10,-(null!=(n=null==e?void 0:e.precision)?n:17)),this.direction=null!=(r=null==e?void 0:e.direction)&&r,this.compareProperties=null==(o=null==e?void 0:e.compareProperties)||o}),[{key:"compare",value:function(t,e){var n=this;if(t.type!==e.type)return!1;if(!we(t,e))return!1;switch(t.type){case"Point":return this.compareCoord(t.coordinates,e.coordinates);case"LineString":return this.compareLine(t.coordinates,e.coordinates);case"Polygon":return this.comparePolygon(t,e);case"GeometryCollection":return this.compareGeometryCollection(t,e);case"Feature":return this.compareFeature(t,e);case"FeatureCollection":return this.compareFeatureCollection(t,e);default:if(t.type.startsWith("Multi")){var r=Ie(t),i=Ie(e);return r.every((function(t){return i.some((function(e){return n.compare(t,e)}))}))}}return!1}},{key:"compareCoord",value:function(t,e){var n=this;return t.length===e.length&&t.every((function(t,r){return Math.abs(t-e[r])2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!we(t,e))return!1;var i=t,o=e;if(r&&!this.compareCoord(i[0],o[0])){var s=this.fixStartIndex(o,i);if(!s)return!1;o=s}var a=this.compareCoord(i[n],o[n]);return this.direction||a?this.comparePath(i,o):!!this.compareCoord(i[n],o[o.length-(1+n)])&&this.comparePath(i.slice().reverse(),o)}},{key:"fixStartIndex",value:function(t,e){for(var n,r=-1,i=0;i=0&&(n=[].concat(t.slice(r,t.length),t.slice(1,r+1))),n}},{key:"comparePath",value:function(t,e){var n=this;return t.every((function(t,r){return n.compareCoord(t,e[r])}))}},{key:"comparePolygon",value:function(t,e){var n=this;if(this.compareLine(t.coordinates[0],e.coordinates[0],1,!0)){var r=t.coordinates.slice(1,t.coordinates.length),i=e.coordinates.slice(1,e.coordinates.length);return r.every((function(t){return i.some((function(e){return n.compareLine(t,e,1,!0)}))}))}return!1}},{key:"compareGeometryCollection",value:function(t,e){var n=this;return we(t.geometries,e.geometries)&&this.compareBBox(t,e)&&t.geometries.every((function(t,r){return n.compare(t,e.geometries[r])}))}},{key:"compareFeature",value:function(t,e){return t.id===e.id&&(!this.compareProperties||Se(t.properties,e.properties))&&this.compareBBox(t,e)&&this.compare(t.geometry,e.geometry)}},{key:"compareFeatureCollection",value:function(t,e){var n=this;return we(t.features,e.features)&&this.compareBBox(t,e)&&t.features.every((function(t,r){return n.compare(t,e.features[r])}))}},{key:"compareBBox",value:function(t,e){return Boolean(!t.bbox&&!e.bbox)||!(!t.bbox||!e.bbox)&&this.compareCoord(t.bbox,e.bbox)}}])}();Ee(ke,"GeojsonEquality");var be=ke;function we(t,e){return t.coordinates?t.coordinates.length===e.coordinates.length:t.length===e.length}function Ie(t){return t.coordinates.map((function(e){return{type:t.type.replace("Multi",""),coordinates:e}}))}function Ne(t,e,n){return new be(n).compare(t,e)}function Se(t,e){if(null===t&&null===e)return!0;if(null===t||null===e)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(var i=0,o=n;i1&&void 0!==arguments[1]?arguments[1]:{},n="object"===m(e)?e.mutate:e;if(!t)throw new Error("geojson is required");var r=it(t),i=[];switch(r){case"LineString":i=Pe(t,r);break;case"MultiLineString":case"Polygon":Q(t).forEach((function(t){i.push(Pe(t,r))}));break;case"MultiPolygon":Q(t).forEach((function(t){var e=[];t.forEach((function(t){e.push(Pe(t,r))})),i.push(e)}));break;case"Point":return t;case"MultiPoint":var o={};Q(t).forEach((function(t){var e=t.join("-");Object.prototype.hasOwnProperty.call(o,e)||(i.push(t),o[e]=!0)}));break;default:throw new Error(r+" geometry not supported")}return t.coordinates?!0===n?(t.coordinates=i,t):{type:r,coordinates:i}:!0===n?(t.geometry.coordinates=i,t):b({type:r,coordinates:i},t.properties,{bbox:t.bbox,id:t.id})}function Pe(t,e){var n=Q(t);if(2===n.length&&!Ce(n[0],n[1]))return n;var r=[],i=n.length-1,o=r.length;r.push(n[0]);for(var s=1;s2&&Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1))}if(r.push(n[n.length-1]),o=r.length,("Polygon"===e||"MultiPolygon"===e)&&Ce(n[0],n[n.length-1])&&o<4)throw new Error("invalid polygon");return"LineString"===e&&o<3||Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1),r}function Ce(t,e){return t[0]===e[0]&&t[1]===e[1]}function Te(t,e,n){var r=n[0],i=n[1],o=t[0],s=t[1],a=e[0],u=e[1],l=a-o,h=u-s;return 0===(r-o)*h-(i-s)*l&&(Math.abs(l)>=Math.abs(h)?l>0?o<=r&&r<=a:a<=r&&r<=o:h>0?s<=i&&i<=u:u<=i&&i<=s)}function Oe(t,e){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).ignoreSelfIntersections,r=void 0===n||n,i=!1;return xt(t,(function(t){xt(e,(function(e){if(!0===i)return!0;i=!de(t.geometry,e.geometry,{ignoreSelfIntersections:r})}))})),i}function Re(t,e,n,r,i){Ae(t,e,n||0,r||t.length-1,i||Fe)}function Ae(t,e,n,r,i){for(;r>n;){if(r-n>600){var o=r-n+1,s=e-n+1,a=Math.log(o),u=.5*Math.exp(2*a/3),l=.5*Math.sqrt(a*u*(o-u)/o)*(s-o/2<0?-1:1);Ae(t,e,Math.max(n,Math.floor(e-s*u/o+l)),Math.min(r,Math.floor(e+(o-s)*u/o+l)),i)}var h=t[e],c=n,f=r;for(De(t,n,e),i(t[r],h)>0&&De(t,n,r);c0;)f--}0===i(t[n],h)?De(t,n,f):De(t,++f,r),f<=e&&(n=f+1),e<=f&&(r=f-1)}}function De(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function Fe(t,e){return te?1:0}var qe=function(){return s((function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:9;i(this,t),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}),[{key:"all",value:function(){return this._all(this.data,[])}},{key:"search",value:function(t){var e=this.data,n=[];if(!He(t,e))return n;for(var r=this.toBBox,i=[];e;){for(var o=0;o=0&&i[e].children.length>this._maxEntries;)this._split(i,e),e--;this._adjustParentBBoxes(r,i,e)}},{key:"_split",value:function(t,e){var n=t[e],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=We(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,Ge(n,this.toBBox),Ge(s,this.toBBox),e?t[e-1].children.push(s):this._splitRoot(n,s)}},{key:"_splitRoot",value:function(t,e){this.data=We([t,e]),this.data.height=t.height+1,this.data.leaf=!1,Ge(this.data,this.toBBox)}},{key:"_chooseSplitIndex",value:function(t,e,n){for(var r,i,o,s,a,u,l,h=1/0,c=1/0,f=e;f<=n-e;f++){var g=Be(t,0,f,this.toBBox),p=Be(t,f,n,this.toBBox),v=(i=g,o=p,s=void 0,a=void 0,u=void 0,l=void 0,s=Math.max(i.minX,o.minX),a=Math.max(i.minY,o.minY),u=Math.min(i.maxX,o.maxX),l=Math.min(i.maxY,o.maxY),Math.max(0,u-s)*Math.max(0,l-a)),d=Xe(g)+Xe(p);v=e;h--){var c=t.children[h];Ye(s,t.leaf?i(c):c),a+=Ue(s)}return a}},{key:"_adjustParentBBoxes",value:function(t,e,n){for(var r=n;r>=0;r--)Ye(e[r],t)}},{key:"_condense",value:function(t){for(var e,n=t.length-1;n>=0;n--)0===t[n].children.length?n>0?(e=t[n-1].children).splice(e.indexOf(t[n]),1):this.clear():Ge(t[n],this.toBBox)}}])}();function Ve(t,e,n){if(!n)return e.indexOf(t);for(var r=0;r=t.minX&&e.maxY>=t.minY}function We(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Je(t,e,n,r,i){for(var o=[e,n];o.length;)if(!((n=o.pop())-(e=o.pop())<=r)){var s=e+Math.ceil((n-e)/r/2)*r;Re(t,s,e,n,i),o.push(e,s,s,n)}}var Ke=Object.freeze({__proto__:null,default:qe});function Qe(t){var e=new qe(t);return e.insert=function(t){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.insert.call(this,t)},e.load=function(t){var e=[];return Array.isArray(t)?t.forEach((function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})):vt(t,(function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})),qe.prototype.load.call(this,e)},e.remove=function(t,e){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.remove.call(this,t,e)},e.clear=function(){return qe.prototype.clear.call(this)},e.search=function(t){return C(qe.prototype.search.call(this,this.toBBox(t)))},e.collides=function(t){return qe.prototype.collides.call(this,this.toBBox(t))},e.all=function(){return C(qe.prototype.all.call(this))},e.toJSON=function(){return qe.prototype.toJSON.call(this)},e.fromJSON=function(t){return qe.prototype.fromJSON.call(this,t)},e.toBBox=function(t){var e;if(t.bbox)e=t.bbox;else if(Array.isArray(t)&&4===t.length)e=t;else if(Array.isArray(t)&&6===t.length)e=[t[0],t[1],t[3],t[4]];else if("Feature"===t.type)e=Rt(t);else{if("FeatureCollection"!==t.type)throw new Error("invalid geojson");e=Rt(t)}return{minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}},e}function $e(t){if(!t)throw new Error("geojson is required");var e=[];return xt(t,(function(t){!function(t,e){var n=[],r=t.geometry;if(null!==r){switch(r.type){case"Polygon":n=Q(r);break;case"LineString":n=[Q(r)]}n.forEach((function(n){var r=function(t,e){var n=[];return t.reduce((function(t,r){var i=L([t,r],e);return i.bbox=function(t,e){var n=t[0],r=t[1],i=e[0],o=e[1],s=ni?n:i,l=r>o?r:o;return[s,a,u,l]}(t,r),n.push(i),r})),n}(n,t.properties);r.forEach((function(t){t.id=e.length,e.push(t)}))}))}}(t,e)})),C(e)}var tn,en,nn=Object.defineProperty,rn=Object.defineProperties,on=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertySymbols,an=Object.prototype.hasOwnProperty,un=Object.prototype.propertyIsEnumerable,ln=function(t,e,n){return e in t?nn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},hn=function(t,e){for(var n in e||(e={}))an.call(e,n)&&ln(t,n,e[n]);if(sn){var r,i=a(sn(e));try{for(i.s();!(r=i.n()).done;){n=r.value;un.call(e,n)&&ln(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},cn=function(t,e){return rn(t,on(e))};function fn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t||!e)throw new Error("lines and pt are required arguments");var r=K(e),i=I([1/0,1/0],{dist:1/0,index:-1,multiFeatureIndex:-1,location:-1}),o=0;return xt(t,(function(t,s,a){for(var u=Q(t),l=0;lR||pn(p,f)>R?ut(dn(f),dn(g))<=ut(dn(f),dn(p))?[dn(g),!0,!1]:[dn(p),!1,!0]:[dn(f),!1,!1]}function mn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function _n(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var n=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,r.get?r:{enumerable:!0,get:function(){return t[e]}})})),n}var xn=(en||(en=1,tn=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==m(e)&&"object"==m(n)){if(e.constructor!==n.constructor)return!1;var r,i,o;if(Array.isArray(e)){if((r=e.length)!=n.length)return!1;for(i=r;0!=i--;)if(!t(e[i],n[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((r=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(i=r;0!=i--;)if(!Object.prototype.hasOwnProperty.call(n,o[i]))return!1;for(i=r;0!=i--;){var s=o[i];if(!t(e[s],n[s]))return!1}return!0}return e!=e&&n!=n}),tn),En=mn(xn);function kn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r,i=n.tolerance||0,o=[],s=Qe(),a=$e(t);s.load(a);var u=[];return kt(e,(function(t){var e=!1;t&&(vt(s.search(t),(function(n){if(!1===e){var o=Q(t).sort(),s=Q(n).sort();if(En(o,s))e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(o[0],n)&&jt(o[1],n):fn(n,o[0]).properties.dist<=i&&fn(n,o[1]).properties.dist<=i)e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(s[0],t)&&jt(s[1],t):fn(t,s[0]).properties.dist<=i&&fn(t,s[1]).properties.dist<=i)if(r){var a=bn(r,n);a?r=a:u.push(n)}else r=n}})),!1===e&&r&&(o.push(r),u.length&&(o=o.concat(u),u=[]),r=void 0))})),r&&o.push(r),C(o)}function bn(t,e){var n=Q(e),r=Q(t),i=r[0],o=r[r.length-1],s=t.geometry.coordinates;if(En(n[0],i))s.unshift(n[1]);else if(En(n[0],o))s.push(n[1]);else if(En(n[1],i))s.unshift(n[0]);else{if(!En(n[1],o))return;s.push(n[0])}return t}function wn(t,e){var n=G(lt(t[0],t[1])),r=G(lt(e[0],e[1]));return n===r||(r-n)%180==0}function In(t,e){if(t.geometry&&t.geometry.type)return t.geometry.type;if(t.type)return t.type;throw new Error("Invalid GeoJSON object for "+e)}function Nn(t,e){return!!Sn(e.coordinates[0],t.coordinates)||!!Sn(e.coordinates[e.coordinates.length-1],t.coordinates)}function Sn(t,e){return t[0]===e[0]&&t[1]===e[1]}function Mn(t){return t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]}function Ln(t){for(var e=0;ee[0])&&(!(t[2]e[1])&&!(t[3]1&&void 0!==arguments[1]?arguments[1]:{},n=Rt(t);return I([(n[0]+n[2])/2,(n[1]+n[3])/2],e.properties,e)}var Dn,Fn={exports:{}};var qn=(Dn||(Dn=1,function(t,e){t.exports=function(){function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}var y=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getEndCapStyle",value:function(){return this._endCapStyle}},{key:"isSingleSided",value:function(){return this._isSingleSided}},{key:"setQuadrantSegments",value:function(t){this._quadrantSegments=t,0===this._quadrantSegments&&(this._joinStyle=e.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=e.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),t<=0&&(this._quadrantSegments=1),this._joinStyle!==e.JOIN_ROUND&&(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS)}},{key:"getJoinStyle",value:function(){return this._joinStyle}},{key:"setJoinStyle",value:function(t){this._joinStyle=t}},{key:"setSimplifyFactor",value:function(t){this._simplifyFactor=t<0?0:t}},{key:"getSimplifyFactor",value:function(){return this._simplifyFactor}},{key:"getQuadrantSegments",value:function(){return this._quadrantSegments}},{key:"setEndCapStyle",value:function(t){this._endCapStyle=t}},{key:"getMitreLimit",value:function(){return this._mitreLimit}},{key:"setMitreLimit",value:function(t){this._mitreLimit=t}},{key:"setSingleSided",value:function(t){this._isSingleSided=t}}],[{key:"constructor_",value:function(){if(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=e.CAP_ROUND,this._joinStyle=e.JOIN_ROUND,this._mitreLimit=e.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=e.DEFAULT_SIMPLIFY_FACTOR,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.setQuadrantSegments(t)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.setQuadrantSegments(n),this.setEndCapStyle(r)}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];this.setQuadrantSegments(i),this.setEndCapStyle(o),this.setJoinStyle(s),this.setMitreLimit(a)}}},{key:"bufferDistanceError",value:function(t){var e=Math.PI/2/t;return 1-Math.cos(e/2)}}]),e}();y.CAP_ROUND=1,y.CAP_FLAT=2,y.CAP_SQUARE=3,y.JOIN_ROUND=1,y.JOIN_MITRE=2,y.JOIN_BEVEL=3,y.DEFAULT_QUADRANT_SEGMENTS=8,y.DEFAULT_MITRE_LIMIT=5,y.DEFAULT_SIMPLIFY_FACTOR=.01;var _=function(e){r(o,e);var i=c(o);function o(e){var n;return t(this,o),(n=i.call(this,e)).name=Object.keys({Exception:o})[0],n}return n(o,[{key:"toString",value:function(){return this.message}}]),o}(u(Error)),x=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({IllegalArgumentException:i})[0],r}return i}(_),E=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}();function k(){}function b(){}function w(){}var I,N,S,M,L,P,C,T,O=function(){function e(){t(this,e)}return n(e,null,[{key:"equalsWithTolerance",value:function(t,e,n){return Math.abs(t-e)<=n}}]),e}(),R=function(){function e(n,r){t(this,e),this.low=r||0,this.high=n||0}return n(e,null,[{key:"toBinaryString",value:function(t){var e,n="";for(e=2147483648;e>0;e>>>=1)n+=(t.high&e)===e?"1":"0";for(e=2147483648;e>0;e>>>=1)n+=(t.low&e)===e?"1":"0";return n}}]),e}();function A(){}function D(){}A.NaN=NaN,A.isNaN=function(t){return Number.isNaN(t)},A.isInfinite=function(t){return!Number.isFinite(t)},A.MAX_VALUE=Number.MAX_VALUE,A.POSITIVE_INFINITY=Number.POSITIVE_INFINITY,A.NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,"function"==typeof Float64Array&&"function"==typeof Int32Array?(P=2146435072,C=new Float64Array(1),T=new Int32Array(C.buffer),A.doubleToLongBits=function(t){C[0]=t;var e=0|T[0],n=0|T[1];return(n&P)===P&&0!=(1048575&n)&&0!==e&&(e=0,n=2146959360),new R(n,e)},A.longBitsToDouble=function(t){return T[0]=t.low,T[1]=t.high,C[0]}):(I=1023,N=Math.log2,S=Math.floor,M=Math.pow,L=function(){for(var t=53;t>0;t--){var e=M(2,t)-1;if(S(N(e))+1===t)return e}return 0}(),A.doubleToLongBits=function(t){var e,n,r,i,o,s,a,u,l;if(t<0||1/t===Number.NEGATIVE_INFINITY?(s=1<<31,t=-t):s=0,0===t)return new R(u=s,l=0);if(t===1/0)return new R(u=2146435072|s,l=0);if(t!=t)return new R(u=2146959360,l=0);if(i=0,l=0,(e=S(t))>1)if(e<=L)(i=S(N(e)))<=20?(l=0,u=e<<20-i&1048575):(l=e%(n=M(2,r=i-20))<<32-r,u=e/n&1048575);else for(r=e,l=0;0!==(r=S(n=r/2));)i++,l>>>=1,l|=(1&u)<<31,u>>>=1,n!==r&&(u|=524288);if(a=i+I,o=0===e,e=t-e,i<52&&0!==e)for(r=0;;){if((n=2*e)>=1?(e=n-1,o?(a--,o=!1):(r<<=1,r|=1,i++)):(e=n,o?0==--a&&(i++,o=!1):(r<<=1,i++)),20===i)u|=r,r=0;else if(52===i){l|=r;break}if(1===n){i<20?u|=r<<20-i:i<52&&(l|=r<<52-i);break}}return u|=a<<20,new R(u|=s,l)},A.longBitsToDouble=function(t){var e,n,r,i,o=t.high,s=t.low,a=o&1<<31?-1:1;for(r=((2146435072&o)>>20)-I,i=0,n=1<<19,e=1;e<=20;e++)o&n&&(i+=M(2,-e)),n>>>=1;for(n=1<<31,e=21;e<=52;e++)s&n&&(i+=M(2,-e)),n>>>=1;if(-1023===r){if(0===i)return 0*a;r=-1022}else{if(1024===r)return 0===i?a/0:NaN;i+=1}return a*i*M(2,r)});var F=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({RuntimeException:i})[0],r}return i}(_),q=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){if(0===arguments.length)F.constructor_.call(this);else if(1===arguments.length){var t=arguments[0];F.constructor_.call(this,t)}}}]),o}(F),V=function(){function e(){t(this,e)}return n(e,null,[{key:"shouldNeverReachHere",value:function(){if(0===arguments.length)e.shouldNeverReachHere(null);else if(1===arguments.length){var t=arguments[0];throw new q("Should never reach here"+(null!==t?": "+t:""))}}},{key:"isTrue",value:function(){if(1===arguments.length){var t=arguments[0];e.isTrue(t,null)}else if(2===arguments.length){var n=arguments[1];if(!arguments[0])throw null===n?new q:new q(n)}}},{key:"equals",value:function(){if(2===arguments.length){var t=arguments[0],n=arguments[1];e.equals(t,n,null)}else if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2];if(!i.equals(r))throw new q("Expected "+r+" but encountered "+i+(null!==o?": "+o:""))}}}]),e}(),G=new ArrayBuffer(8),B=new Float64Array(G),Y=new Int32Array(G),z=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getM",value:function(){return A.NaN}},{key:"setOrdinate",value:function(t,n){switch(t){case e.X:this.x=n;break;case e.Y:this.y=n;break;case e.Z:this.setZ(n);break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"equals2D",value:function(){if(1===arguments.length){var t=arguments[0];return this.x===t.x&&this.y===t.y}if(2===arguments.length){var e=arguments[0],n=arguments[1];return!!O.equalsWithTolerance(this.x,e.x,n)&&!!O.equalsWithTolerance(this.y,e.y,n)}}},{key:"setM",value:function(t){throw new x("Invalid ordinate index: "+e.M)}},{key:"getZ",value:function(){return this.z}},{key:"getOrdinate",value:function(t){switch(t){case e.X:return this.x;case e.Y:return this.y;case e.Z:return this.getZ()}throw new x("Invalid ordinate index: "+t)}},{key:"equals3D",value:function(t){return this.x===t.x&&this.y===t.y&&(this.getZ()===t.getZ()||A.isNaN(this.getZ())&&A.isNaN(t.getZ()))}},{key:"equals",value:function(t){return t instanceof e&&this.equals2D(t)}},{key:"equalInZ",value:function(t,e){return O.equalsWithTolerance(this.getZ(),t.getZ(),e)}},{key:"setX",value:function(t){this.x=t}},{key:"compareTo",value:function(t){var e=t;return this.xe.x?1:this.ye.y?1:0}},{key:"getX",value:function(){return this.x}},{key:"setZ",value:function(t){this.z=t}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return V.shouldNeverReachHere("this shouldn't happen because this class is Cloneable"),null;throw t}}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+")"}},{key:"distance3D",value:function(t){var e=this.x-t.x,n=this.y-t.y,r=this.getZ()-t.getZ();return Math.sqrt(e*e+n*n+r*r)}},{key:"getY",value:function(){return this.y}},{key:"setY",value:function(t){this.y=t}},{key:"distance",value:function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*t+e.hashCode(this.x))+e.hashCode(this.y)}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}},{key:"interfaces_",get:function(){return[k,b,w]}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.z=null,0===arguments.length)e.constructor_.call(this,0,0);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.x,t.y,t.getZ())}else if(2===arguments.length){var n=arguments[0],r=arguments[1];e.constructor_.call(this,n,r,e.NULL_ORDINATE)}else if(3===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2];this.x=i,this.y=o,this.z=s}}},{key:"hashCode",value:function(t){return B[0]=t,Y[0]^Y[1]}}]),e}(),j=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compare",value:function(t,n){var r=e.compare(t.x,n.x);if(0!==r)return r;var i=e.compare(t.y,n.y);return 0!==i?i:this._dimensionsToTest<=2?0:e.compare(t.getZ(),n.getZ())}},{key:"interfaces_",get:function(){return[D]}}],[{key:"constructor_",value:function(){if(this._dimensionsToTest=2,0===arguments.length)e.constructor_.call(this,2);else if(1===arguments.length){var t=arguments[0];if(2!==t&&3!==t)throw new x("only 2 or 3 dimensions may be specified");this._dimensionsToTest=t}}},{key:"compare",value:function(t,e){return te?1:A.isNaN(t)?A.isNaN(e)?0:-1:A.isNaN(e)?1:0}}]),e}();z.DimensionalComparator=j,z.NULL_ORDINATE=A.NaN,z.X=0,z.Y=1,z.Z=2,z.M=3;var X=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getArea",value:function(){return this.getWidth()*this.getHeight()}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.isNull()?n.isNull():this._maxx===n.getMaxX()&&this._maxy===n.getMaxY()&&this._minx===n.getMinX()&&this._miny===n.getMinY()}},{key:"intersection",value:function(t){if(this.isNull()||t.isNull()||!this.intersects(t))return new e;var n=this._minx>t._minx?this._minx:t._minx,r=this._miny>t._miny?this._miny:t._miny;return new e(n,this._maxx=this._minx&&n.getMaxX()<=this._maxx&&n.getMinY()>=this._miny&&n.getMaxY()<=this._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return!this.isNull()&&r>=this._minx&&r<=this._maxx&&i>=this._miny&&i<=this._maxy}}},{key:"intersects",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return!this.isNull()&&!t.isNull()&&!(t._minx>this._maxx||t._maxxthis._maxy||t._maxythis._maxx||(r.x>i.x?r.x:i.x)this._maxy||(r.y>i.y?r.y:i.y)this._maxx||othis._maxy||sthis._maxx&&(this._maxx=n._maxx),n._minythis._maxy&&(this._maxy=n._maxy))}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.isNull()?(this._minx=r,this._maxx=r,this._miny=i,this._maxy=i):(rthis._maxx&&(this._maxx=r),ithis._maxy&&(this._maxy=i))}}},{key:"minExtent",value:function(){if(this.isNull())return 0;var t=this.getWidth(),e=this.getHeight();return te._minx?1:this._minye._miny?1:this._maxxe._maxx?1:this._maxye._maxy?1:0}},{key:"translate",value:function(t,e){if(this.isNull())return null;this.init(this.getMinX()+t,this.getMaxX()+t,this.getMinY()+e,this.getMaxY()+e)}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"Env["+this._minx+" : "+this._maxx+", "+this._miny+" : "+this._maxy+"]"}},{key:"setToNull",value:function(){this._minx=0,this._maxx=-1,this._miny=0,this._maxy=-1}},{key:"disjoint",value:function(t){return!(!this.isNull()&&!t.isNull())||t._minx>this._maxx||t._maxxthis._maxy||t._maxye?t:e}},{key:"expandBy",value:function(){if(1===arguments.length){var t=arguments[0];this.expandBy(t,t)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];if(this.isNull())return null;this._minx-=e,this._maxx+=e,this._miny-=n,this._maxy+=n,(this._minx>this._maxx||this._miny>this._maxy)&&this.setToNull()}}},{key:"contains",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.covers(t)}if(arguments[0]instanceof z){var n=arguments[0];return this.covers(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return this.covers(r,i)}}},{key:"centre",value:function(){return this.isNull()?null:new z((this.getMinX()+this.getMaxX())/2,(this.getMinY()+this.getMaxY())/2)}},{key:"init",value:function(){if(0===arguments.length)this.setToNull();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this._minx=n._minx,this._maxx=n._maxx,this._miny=n._miny,this._maxy=n._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];ot._maxx&&(e=this._minx-t._maxx);var n=0;return this._maxyt._maxy&&(n=this._miny-t._maxy),0===e?n:0===n?e:Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*(t=37*(t=37*t+z.hashCode(this._minx))+z.hashCode(this._maxx))+z.hashCode(this._miny))+z.hashCode(this._maxy)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,0===arguments.length)this.init();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];this.init(o,s,a,u)}}},{key:"intersects",value:function(){if(3===arguments.length){var t=arguments[0],e=arguments[1],n=arguments[2];return n.x>=(t.xe.x?t.x:e.x)&&n.y>=(t.ye.y?t.y:e.y)}if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=arguments[3],a=Math.min(o.x,s.x),u=Math.max(o.x,s.x),l=Math.min(r.x,i.x),h=Math.max(r.x,i.x);return!(l>u||hu||h=this.size())throw new nt;return this.array[t]}},{key:"push",value:function(t){return this.array.push(t),t}},{key:"pop",value:function(){if(0===this.array.length)throw new et;return this.array.pop()}},{key:"peek",value:function(){if(0===this.array.length)throw new et;return this.array[this.array.length-1]}},{key:"empty",value:function(){return 0===this.array.length}},{key:"isEmpty",value:function(){return this.empty()}},{key:"search",value:function(t){return this.array.indexOf(t)}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}}]),o}(rt);function ot(t,e){return t.interfaces_&&t.interfaces_.indexOf(e)>-1}var st=function(){function e(n){t(this,e),this.str=n}return n(e,[{key:"append",value:function(t){this.str+=t}},{key:"setCharAt",value:function(t,e){this.str=this.str.substr(0,t)+e+this.str.substr(t+1)}},{key:"toString",value:function(){return this.str}}]),e}(),at=function(){function e(n){t(this,e),this.value=n}return n(e,[{key:"intValue",value:function(){return this.value}},{key:"compareTo",value:function(t){return this.valuet?1:0}}],[{key:"compare",value:function(t,e){return te?1:0}},{key:"isNan",value:function(t){return Number.isNaN(t)}},{key:"valueOf",value:function(t){return new e(t)}}]),e}(),ut=function(){function e(){t(this,e)}return n(e,null,[{key:"isWhitespace",value:function(t){return t<=32&&t>=0||127===t}},{key:"toUpperCase",value:function(t){return t.toUpperCase()}}]),e}(),lt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"le",value:function(t){return this._hi9?(c=!0,f="9"):f="0"+h,a.append(f),r=r.subtract(e.valueOf(h)).multiply(e.TEN),c&&r.selfAdd(e.TEN);var g=!0,p=e.magnitude(r._hi);if(p<0&&Math.abs(p)>=u-l&&(g=!1),!g)break}return n[0]=i,a.toString()}},{key:"sqr",value:function(){return this.multiply(this)}},{key:"doubleValue",value:function(){return this._hi+this._lo}},{key:"subtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.add(t.negate())}if("number"==typeof arguments[0]){var n=arguments[0];return this.add(-n)}}},{key:"equals",value:function(){if(1===arguments.length&&arguments[0]instanceof e){var t=arguments[0];return this._hi===t._hi&&this._lo===t._lo}}},{key:"isZero",value:function(){return 0===this._hi&&0===this._lo}},{key:"selfSubtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.isNaN()?this:this.selfAdd(-t._hi,-t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.isNaN()?this:this.selfAdd(-n,0)}}},{key:"getSpecialNumberString",value:function(){return this.isZero()?"0.0":this.isNaN()?"NaN ":null}},{key:"min",value:function(t){return this.le(t)?this:t}},{key:"selfDivide",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfDivide(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfDivide(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null,c=null,f=null;return l=this._hi/r,f=(o=(h=e.SPLIT*l)-(o=h-l))*(a=(f=e.SPLIT*r)-(a=f-r))-(c=l*r)+o*(u=r-a)+(s=l-o)*a+s*u,f=l+(h=(this._hi-c-f+this._lo-l*i)/r),this._hi=f,this._lo=l-f+h,this}}},{key:"dump",value:function(){return"DD<"+this._hi+", "+this._lo+">"}},{key:"divide",value:function(){if(arguments[0]instanceof e){var t=arguments[0],n=null,r=null,i=null,o=null,s=null,a=null,u=null,l=null;return r=(s=this._hi/t._hi)-(n=(a=e.SPLIT*s)-(n=a-s)),l=n*(i=(l=e.SPLIT*t._hi)-(i=l-t._hi))-(u=s*t._hi)+n*(o=t._hi-i)+r*i+r*o,new e(l=s+(a=(this._hi-u-l+this._lo-s*t._lo)/t._hi),s-l+a)}if("number"==typeof arguments[0]){var h=arguments[0];return A.isNaN(h)?e.createNaN():e.copy(this).selfDivide(h,0)}}},{key:"ge",value:function(t){return this._hi>t._hi||this._hi===t._hi&&this._lo>=t._lo}},{key:"pow",value:function(t){if(0===t)return e.valueOf(1);var n=new e(this),r=e.valueOf(1),i=Math.abs(t);if(i>1)for(;i>0;)i%2==1&&r.selfMultiply(n),(i/=2)>0&&(n=n.sqr());else r=n;return t<0?r.reciprocal():r}},{key:"ceil",value:function(){if(this.isNaN())return e.NaN;var t=Math.ceil(this._hi),n=0;return t===this._hi&&(n=Math.ceil(this._lo)),new e(t,n)}},{key:"compareTo",value:function(t){var e=t;return this._hie._hi?1:this._loe._lo?1:0}},{key:"rint",value:function(){return this.isNaN()?this:this.add(.5).floor()}},{key:"setValue",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.init(t),this}if("number"==typeof arguments[0]){var n=arguments[0];return this.init(n),this}}},{key:"max",value:function(t){return this.ge(t)?this:t}},{key:"sqrt",value:function(){if(this.isZero())return e.valueOf(0);if(this.isNegative())return e.NaN;var t=1/Math.sqrt(this._hi),n=this._hi*t,r=e.valueOf(n),i=this.subtract(r.sqr())._hi*(.5*t);return r.add(i)}},{key:"selfAdd",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfAdd(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0],r=null,i=null,o=null,s=null,a=null,u=null;return s=(o=this._hi+n)-(a=o-this._hi),i=(u=(s=n-a+(this._hi-s))+this._lo)+(o-(r=o+u)),this._hi=r+i,this._lo=i+(r-this._hi),this}}else if(2===arguments.length){var l=arguments[0],h=arguments[1],c=null,f=null,g=null,p=null,v=null,d=null,y=null;p=this._hi+l,f=this._lo+h,v=p-(d=p-this._hi),g=f-(y=f-this._lo);var m=(c=p+(d=(v=l-d+(this._hi-v))+f))+(d=(g=h-y+(this._lo-g))+(d+(p-c))),_=d+(c-m);return this._hi=m,this._lo=_,this}}},{key:"selfMultiply",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfMultiply(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfMultiply(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null;o=(l=e.SPLIT*this._hi)-this._hi,h=e.SPLIT*r,o=l-o,s=this._hi-o,a=h-r;var c=(l=this._hi*r)+(h=o*(a=h-a)-l+o*(u=r-a)+s*a+s*u+(this._hi*i+this._lo*r)),f=h+(o=l-c);return this._hi=c,this._lo=f,this}}},{key:"selfSqr",value:function(){return this.selfMultiply(this)}},{key:"floor",value:function(){if(this.isNaN())return e.NaN;var t=Math.floor(this._hi),n=0;return t===this._hi&&(n=Math.floor(this._lo)),new e(t,n)}},{key:"negate",value:function(){return this.isNaN()?this:new e(-this._hi,-this._lo)}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return null;throw t}}},{key:"multiply",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return t.isNaN()?e.createNaN():e.copy(this).selfMultiply(t)}if("number"==typeof arguments[0]){var n=arguments[0];return A.isNaN(n)?e.createNaN():e.copy(this).selfMultiply(n,0)}}},{key:"isNaN",value:function(){return A.isNaN(this._hi)}},{key:"intValue",value:function(){return Math.trunc(this._hi)}},{key:"toString",value:function(){var t=e.magnitude(this._hi);return t>=-3&&t<=20?this.toStandardNotation():this.toSciNotation()}},{key:"toStandardNotation",value:function(){var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!0,n),i=n[0]+1,o=r;if("."===r.charAt(0))o="0"+r;else if(i<0)o="0."+e.stringOfChar("0",-i)+r;else if(-1===r.indexOf(".")){var s=i-r.length;o=r+e.stringOfChar("0",s)+".0"}return this.isNegative()?"-"+o:o}},{key:"reciprocal",value:function(){var t,n,r,i,o=null,s=null,a=null,u=null;t=(r=1/this._hi)-(o=(a=e.SPLIT*r)-(o=a-r)),s=(u=e.SPLIT*this._hi)-this._hi;var l=r+(a=(1-(i=r*this._hi)-(u=o*(s=u-s)-i+o*(n=this._hi-s)+t*s+t*n)-r*this._lo)/this._hi);return new e(l,r-l+a)}},{key:"toSciNotation",value:function(){if(this.isZero())return e.SCI_NOT_ZERO;var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!1,n),i=e.SCI_NOT_EXPONENT_CHAR+n[0];if("0"===r.charAt(0))throw new IllegalStateException("Found leading zero: "+r);var o="";r.length>1&&(o=r.substring(1));var s=r.charAt(0)+"."+o;return this.isNegative()?"-"+s+i:s+i}},{key:"abs",value:function(){return this.isNaN()?e.NaN:this.isNegative()?this.negate():new e(this)}},{key:"isPositive",value:function(){return this._hi>0||0===this._hi&&this._lo>0}},{key:"lt",value:function(t){return this._hit._hi||this._hi===t._hi&&this._lo>t._lo}},{key:"isNegative",value:function(){return this._hi<0||0===this._hi&&this._lo<0}},{key:"trunc",value:function(){return this.isNaN()?e.NaN:this.isPositive()?this.floor():this.ceil()}},{key:"signum",value:function(){return this._hi>0?1:this._hi<0?-1:this._lo>0?1:this._lo<0?-1:0}},{key:"interfaces_",get:function(){return[w,k,b]}}],[{key:"constructor_",value:function(){if(this._hi=0,this._lo=0,0===arguments.length)this.init(0);else if(1===arguments.length){if("number"==typeof arguments[0]){var t=arguments[0];this.init(t)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}else if("string"==typeof arguments[0]){var r=arguments[0];e.constructor_.call(this,e.parse(r))}}else if(2===arguments.length){var i=arguments[0],o=arguments[1];this.init(i,o)}}},{key:"determinant",value:function(){if("number"==typeof arguments[3]&&"number"==typeof arguments[2]&&"number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1],r=arguments[2],i=arguments[3];return e.determinant(e.valueOf(t),e.valueOf(n),e.valueOf(r),e.valueOf(i))}if(arguments[3]instanceof e&&arguments[2]instanceof e&&arguments[0]instanceof e&&arguments[1]instanceof e){var o=arguments[1],s=arguments[2],a=arguments[3];return arguments[0].multiply(a).selfSubtract(o.multiply(s))}}},{key:"sqr",value:function(t){return e.valueOf(t).selfMultiply(t)}},{key:"valueOf",value:function(){if("string"==typeof arguments[0]){var t=arguments[0];return e.parse(t)}if("number"==typeof arguments[0])return new e(arguments[0])}},{key:"sqrt",value:function(t){return e.valueOf(t).sqrt()}},{key:"parse",value:function(t){for(var n=0,r=t.length;ut.isWhitespace(t.charAt(n));)n++;var i=!1;if(n=r);){var c=t.charAt(n);if(n++,ut.isDigit(c)){var f=c-"0";s.selfMultiply(e.TEN),s.selfAdd(f),a++}else{if("."!==c){if("e"===c||"E"===c){var g=t.substring(n);try{l=at.parseInt(g)}catch(e){throw e instanceof NumberFormatException?new NumberFormatException("Invalid exponent "+g+" in string "+t):e}break}throw new NumberFormatException("Unexpected character '"+c+"' at position "+n+" in string "+t)}u=a,h=!0}}var p=s;h||(u=a);var v=a-u-l;if(0===v)p=s;else if(v>0){var d=e.TEN.pow(v);p=s.divide(d)}else if(v<0){var y=e.TEN.pow(-v);p=s.multiply(y)}return i?p.negate():p}},{key:"createNaN",value:function(){return new e(A.NaN,A.NaN)}},{key:"copy",value:function(t){return new e(t)}},{key:"magnitude",value:function(t){var e=Math.abs(t),n=Math.log(e)/Math.log(10),r=Math.trunc(Math.floor(n));return 10*Math.pow(10,r)<=e&&(r+=1),r}},{key:"stringOfChar",value:function(t,e){for(var n=new st,r=0;r0){if(s<=0)return e.signum(a);i=o+s}else{if(!(o<0))return e.signum(a);if(s>=0)return e.signum(a);i=-o-s}var u=e.DP_SAFE_EPSILON*i;return a>=u||-a>=u?e.signum(a):2}},{key:"signum",value:function(t){return t>0?1:t<0?-1:0}}]),e}();ht.DP_SAFE_EPSILON=1e-15;var ct=function(){function e(){t(this,e)}return n(e,[{key:"getM",value:function(t){if(this.hasM()){var e=this.getDimension()-this.getMeasures();return this.getOrdinate(t,e)}return A.NaN}},{key:"setOrdinate",value:function(t,e,n){}},{key:"getZ",value:function(t){return this.hasZ()?this.getOrdinate(t,2):A.NaN}},{key:"size",value:function(){}},{key:"getOrdinate",value:function(t,e){}},{key:"getCoordinate",value:function(){}},{key:"getCoordinateCopy",value:function(t){}},{key:"createCoordinate",value:function(){}},{key:"getDimension",value:function(){}},{key:"hasM",value:function(){return this.getMeasures()>0}},{key:"getX",value:function(t){}},{key:"hasZ",value:function(){return this.getDimension()-this.getMeasures()>2}},{key:"getMeasures",value:function(){return 0}},{key:"expandEnvelope",value:function(t){}},{key:"copy",value:function(){}},{key:"getY",value:function(t){}},{key:"toCoordinateArray",value:function(){}},{key:"interfaces_",get:function(){return[b]}}]),e}();ct.X=0,ct.Y=1,ct.Z=2,ct.M=3;var ft=function(){function e(){t(this,e)}return n(e,null,[{key:"index",value:function(t,e,n){return ht.orientationIndex(t,e,n)}},{key:"isCCW",value:function(){if(arguments[0]instanceof Array){var t=arguments[0],n=t.length-1;if(n<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var r=t[0],i=0,o=1;o<=n;o++){var s=t[o];s.y>r.y&&(r=s,i=o)}var a=i;do{(a-=1)<0&&(a=n)}while(t[a].equals2D(r)&&a!==i);var u=i;do{u=(u+1)%n}while(t[u].equals2D(r)&&u!==i);var l=t[a],h=t[u];if(l.equals2D(r)||h.equals2D(r)||l.equals2D(h))return!1;var c=e.index(l,r,h);return 0===c?l.x>h.x:c>0}if(ot(arguments[0],ct)){var f=arguments[0],g=f.size()-1;if(g<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var p=f.getCoordinate(0),v=0,d=1;d<=g;d++){var y=f.getCoordinate(d);y.y>p.y&&(p=y,v=d)}var m=null,_=v;do{(_-=1)<0&&(_=g),m=f.getCoordinate(_)}while(m.equals2D(p)&&_!==v);var E=null,k=v;do{k=(k+1)%g,E=f.getCoordinate(k)}while(E.equals2D(p)&&k!==v);if(m.equals2D(p)||E.equals2D(p)||m.equals2D(E))return!1;var b=e.index(m,p,E);return 0===b?m.x>E.x:b>0}}}]),e}();ft.CLOCKWISE=-1,ft.RIGHT=ft.CLOCKWISE,ft.COUNTERCLOCKWISE=1,ft.LEFT=ft.COUNTERCLOCKWISE,ft.COLLINEAR=0,ft.STRAIGHT=ft.COLLINEAR;var gt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this._minCoord}},{key:"getRightmostSide",value:function(t,e){var n=this.getRightmostSideOfSegment(t,e);return n<0&&(n=this.getRightmostSideOfSegment(t,e-1)),n<0&&(this._minCoord=null,this.checkForRightmostCoordinate(t)),n}},{key:"findRightmostEdgeAtVertex",value:function(){var t=this._minDe.getEdge().getCoordinates();V.isTrue(this._minIndex>0&&this._minIndexthis._minCoord.y&&n.y>this._minCoord.y&&r===ft.CLOCKWISE)&&(i=!0),i&&(this._minIndex=this._minIndex-1)}},{key:"getRightmostSideOfSegment",value:function(t,e){var n=t.getEdge().getCoordinates();if(e<0||e+1>=n.length)return-1;if(n[e].y===n[e+1].y)return-1;var r=tt.LEFT;return n[e].ythis._minCoord.x)&&(this._minDe=t,this._minIndex=n,this._minCoord=e[n])}},{key:"findRightmostEdgeAtNode",value:function(){var t=this._minDe.getNode().getEdges();this._minDe=t.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)}},{key:"findEdge",value:function(t){for(var e=t.iterator();e.hasNext();){var n=e.next();n.isForward()&&this.checkForRightmostCoordinate(n)}V.isTrue(0!==this._minIndex||this._minCoord.equals(this._minDe.getCoordinate()),"inconsistency in rightmost processing"),0===this._minIndex?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe,this.getRightmostSide(this._minDe,this._minIndex)===tt.LEFT&&(this._orientedDe=this._minDe.getSym())}}],[{key:"constructor_",value:function(){this._minIndex=-1,this._minCoord=null,this._minDe=null,this._orientedDe=null}}]),e}(),pt=function(e){r(o,e);var i=c(o);function o(e,n){var r;return t(this,o),(r=i.call(this,n?e+" [ "+n+" ]":e)).pt=n?new z(n):void 0,r.name=Object.keys({TopologyException:o})[0],r}return n(o,[{key:"getCoordinate",value:function(){return this.pt}}]),o}(F),vt=function(){function e(){t(this,e),this.array=[]}return n(e,[{key:"addLast",value:function(t){this.array.push(t)}},{key:"removeFirst",value:function(){return this.array.shift()}},{key:"isEmpty",value:function(){return 0===this.array.length}}]),e}(),dt=function(e,i){r(s,e);var o=c(s);function s(e){var n;return t(this,s),(n=o.call(this)).array=[],e instanceof H&&n.addAll(e),n}return n(s,[{key:"interfaces_",get:function(){return[rt,H]}},{key:"ensureCapacity",value:function(){}},{key:"add",value:function(t){return 1===arguments.length?this.array.push(t):this.array.splice(arguments[0],0,arguments[1]),!0}},{key:"clear",value:function(){this.array=[]}},{key:"addAll",value:function(t){var e,n=d(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.array.push(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"set",value:function(t,e){var n=this.array[t];return this.array[t]=e,n}},{key:"iterator",value:function(){return new yt(this)}},{key:"get",value:function(t){if(t<0||t>=this.size())throw new nt;return this.array[t]}},{key:"isEmpty",value:function(){return 0===this.array.length}},{key:"sort",value:function(t){t?this.array.sort((function(e,n){return t.compare(e,n)})):this.array.sort()}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}},{key:"remove",value:function(t){for(var e=0,n=this.array.length;e=1&&e.getDepth(tt.LEFT)<=0&&!e.isInteriorAreaEdge()&&e.setInResult(!0)}}},{key:"computeDepths",value:function(t){var e=new Q,n=new vt,r=t.getNode();for(n.addLast(r),e.add(r),t.setVisited(!0);!n.isEmpty();){var i=n.removeFirst();e.add(i),this.computeNodeDepth(i);for(var o=i.getEdges().iterator();o.hasNext();){var s=o.next().getSym();if(!s.isVisited()){var a=s.getNode();e.contains(a)||(n.addLast(a),e.add(a))}}}}},{key:"compareTo",value:function(t){var e=t;return this._rightMostCoord.xe._rightMostCoord.x?1:0}},{key:"getEnvelope",value:function(){if(null===this._env){for(var t=new X,e=this._dirEdgeList.iterator();e.hasNext();)for(var n=e.next().getEdge().getCoordinates(),r=0;re.x?t.x:e.x,a=t.y>e.y?t.y:e.y,u=n.xr.x?n.x:r.x,c=n.y>r.y?n.y:r.y,f=((i>u?i:u)+(sl?o:l)+(an?n:t}if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var r=arguments[0],i=arguments[1],o=arguments[2];return ro?o:r}}},{key:"wrap",value:function(t,e){return t<0?e- -t%e:t%e}},{key:"max",value:function(){if(3===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[0];return t>n&&(n=t),e>n&&(n=e),n}if(4===arguments.length){var r=arguments[1],i=arguments[2],o=arguments[3],s=arguments[0];return r>s&&(s=r),i>s&&(s=i),o>s&&(s=o),s}}},{key:"average",value:function(t,e){return(t+e)/2}}]),e}();Et.LOG_10=Math.log(10);var kt=function(){function e(){t(this,e)}return n(e,null,[{key:"segmentToSegment",value:function(t,n,r,i){if(t.equals(n))return e.pointToSegment(t,r,i);if(r.equals(i))return e.pointToSegment(i,t,n);var o=!1;if(X.intersects(t,n,r,i)){var s=(n.x-t.x)*(i.y-r.y)-(n.y-t.y)*(i.x-r.x);if(0===s)o=!0;else{var a=(t.y-r.y)*(i.x-r.x)-(t.x-r.x)*(i.y-r.y),u=((t.y-r.y)*(n.x-t.x)-(t.x-r.x)*(n.y-t.y))/s,l=a/s;(l<0||l>1||u<0||u>1)&&(o=!0)}}else o=!0;return o?Et.min(e.pointToSegment(t,r,i),e.pointToSegment(n,r,i),e.pointToSegment(r,t,n),e.pointToSegment(i,t,n)):0}},{key:"pointToSegment",value:function(t,e,n){if(e.x===n.x&&e.y===n.y)return t.distance(e);var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/r;if(i<=0)return t.distance(e);if(i>=1)return t.distance(n);var o=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(o)*Math.sqrt(r)}},{key:"pointToLinePerpendicular",value:function(t,e,n){var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(i)*Math.sqrt(r)}},{key:"pointToSegmentString",value:function(t,n){if(0===n.length)throw new x("Line array must contain at least one vertex");for(var r=t.distance(n[0]),i=0;i0)&&(o=a,i=s)}return i}}},{key:"extend",value:function(t,n,r){var i=t.create(r,n.getDimension()),o=n.size();if(e.copy(n,0,i,0,o),o>0)for(var s=o;s0)&&(e=r)}return e}}]),e}(),Mt=function(){function e(){t(this,e)}return n(e,null,[{key:"toDimensionSymbol",value:function(t){switch(t){case e.FALSE:return e.SYM_FALSE;case e.TRUE:return e.SYM_TRUE;case e.DONTCARE:return e.SYM_DONTCARE;case e.P:return e.SYM_P;case e.L:return e.SYM_L;case e.A:return e.SYM_A}throw new x("Unknown dimension value: "+t)}},{key:"toDimensionValue",value:function(t){switch(ut.toUpperCase(t)){case e.SYM_FALSE:return e.FALSE;case e.SYM_TRUE:return e.TRUE;case e.SYM_DONTCARE:return e.DONTCARE;case e.SYM_P:return e.P;case e.SYM_L:return e.L;case e.SYM_A:return e.A}throw new x("Unknown dimension symbol: "+t)}}]),e}();Mt.P=0,Mt.L=1,Mt.A=2,Mt.FALSE=-1,Mt.TRUE=-2,Mt.DONTCARE=-3,Mt.SYM_FALSE="F",Mt.SYM_TRUE="T",Mt.SYM_DONTCARE="*",Mt.SYM_P="0",Mt.SYM_L="1",Mt.SYM_A="2";var Lt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}(),Pt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t,e){}},{key:"isDone",value:function(){}},{key:"isGeometryChanged",value:function(){}}]),e}(),Ct=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"computeEnvelopeInternal",value:function(){return this.isEmpty()?new X:this._points.expandEnvelope(new X)}},{key:"isRing",value:function(){return this.isClosed()&&this.isSimple()}},{key:"getCoordinates",value:function(){return this._points.toCoordinateArray()}},{key:"copyInternal",value:function(){return new s(this._points.copy(),this._factory)}},{key:"equalsExact",value:function(){if(2===arguments.length&&"number"==typeof arguments[1]&&arguments[0]instanceof U){var t=arguments[0],e=arguments[1];if(!this.isEquivalentClass(t))return!1;var n=t;if(this._points.size()!==n._points.size())return!1;for(var r=0;r0){var n=this._points.copy();St.reverse(n),this._points=n}return null}}}},{key:"getCoordinate",value:function(){return this.isEmpty()?null:this._points.getCoordinate(0)}},{key:"getBoundaryDimension",value:function(){return this.isClosed()?Mt.FALSE:0}},{key:"isClosed",value:function(){return!this.isEmpty()&&this.getCoordinateN(0).equals2D(this.getCoordinateN(this.getNumPoints()-1))}},{key:"reverseInternal",value:function(){var t=this._points.copy();return St.reverse(t),this.getFactory().createLineString(t)}},{key:"getEndPoint",value:function(){return this.isEmpty()?null:this.getPointN(this.getNumPoints()-1)}},{key:"getTypeCode",value:function(){return U.TYPECODE_LINESTRING}},{key:"getDimension",value:function(){return 1}},{key:"getLength",value:function(){return It.ofLine(this._points)}},{key:"getNumPoints",value:function(){return this._points.size()}},{key:"compareToSameClass",value:function(){if(1===arguments.length){for(var t=arguments[0],e=0,n=0;e= 2)");this._points=t}},{key:"isCoordinate",value:function(t){for(var e=0;e=1&&this.getCoordinateSequence().size()= 4)")}},{key:"getGeometryType",value:function(){return U.TYPENAME_LINEARRING}}],[{key:"constructor_",value:function(){var t=arguments[0],e=arguments[1];Ct.constructor_.call(this,t,e),this.validateConstruction()}}]),s}(Ct);zt.MINIMUM_VALID_SIZE=4;var jt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}}],[{key:"constructor_",value:function(){if(0===arguments.length)z.constructor_.call(this);else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y)}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y)}}else if(2===arguments.length){var n=arguments[0],r=arguments[1];z.constructor_.call(this,n,r,z.NULL_ORDINATE)}}}]),o}(z);jt.X=0,jt.Y=1,jt.Z=-1,jt.M=-1;var Xt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;case o.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y;case o.M:return this._m}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y),this._m=this.getM()}}else if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2];z.constructor_.call(this,n,r,z.NULL_ORDINATE),this._m=i}}}]),o}(z);Xt.X=0,Xt.Y=1,Xt.Z=-1,Xt.M=2;var Ut=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case z.X:this.x=e;break;case z.Y:this.y=e;break;case z.Z:this.z=e;break;case z.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getOrdinate",value:function(t){switch(t){case z.X:return this.x;case z.Y:return this.y;case z.Z:return this.getZ();case z.M:return this.getM()}throw new x("Invalid ordinate index: "+t)}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e),this._m=this.getM()}}else if(4===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],s=arguments[3];z.constructor_.call(this,n,r,i),this._m=s}}}]),o}(z),Zt=function(){function e(){t(this,e)}return n(e,null,[{key:"measures",value:function(t){return t instanceof jt?0:t instanceof Xt||t instanceof Ut?1:0}},{key:"dimension",value:function(t){return t instanceof jt?2:t instanceof Xt?3:t instanceof Ut?4:3}},{key:"create",value:function(){if(1===arguments.length){var t=arguments[0];return e.create(t,0)}if(2===arguments.length){var n=arguments[0],r=arguments[1];return 2===n?new jt:3===n&&0===r?new z:3===n&&1===r?new Xt:4===n&&1===r?new Ut:new z}}}]),e}(),Ht=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getCoordinate",value:function(t){return this.get(t)}},{key:"addAll",value:function(){if(2===arguments.length&&"boolean"==typeof arguments[1]&&ot(arguments[0],H)){for(var t=arguments[1],e=!1,n=arguments[0].iterator();n.hasNext();)this.add(n.next(),t),e=!0;return e}return f(i(s.prototype),"addAll",this).apply(this,arguments)}},{key:"clone",value:function(){for(var t=f(i(s.prototype),"clone",this).call(this),e=0;e=1&&this.get(this.size()-1).equals2D(r))return null;f(i(s.prototype),"add",this).call(this,r)}else if(arguments[0]instanceof Object&&"boolean"==typeof arguments[1]){var o=arguments[0],a=arguments[1];return this.add(o,a),!0}}else if(3===arguments.length){if("boolean"==typeof arguments[2]&&arguments[0]instanceof Array&&"boolean"==typeof arguments[1]){var u=arguments[0],l=arguments[1];if(arguments[2])for(var h=0;h=0;c--)this.add(u[c],l);return!0}if("boolean"==typeof arguments[2]&&Number.isInteger(arguments[0])&&arguments[1]instanceof z){var g=arguments[0],p=arguments[1];if(!arguments[2]){var v=this.size();if(v>0){if(g>0&&this.get(g-1).equals2D(p))return null;if(g_&&(x=-1);for(var E=m;E!==_;E+=x)this.add(d[E],y);return!0}}},{key:"closeRing",value:function(){if(this.size()>0){var t=this.get(0).copy();this.add(t,!1)}}}],[{key:"constructor_",value:function(){if(0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.ensureCapacity(t.length),this.add(t,!0)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this.ensureCapacity(e.length),this.add(e,n)}}}]),s}(dt);Ht.coordArrayType=new Array(0).fill(null);var Wt=function(){function e(){t(this,e)}return n(e,null,[{key:"isRing",value:function(t){return!(t.length<4||!t[0].equals2D(t[t.length-1]))}},{key:"ptNotInList",value:function(t,n){for(var r=0;r=t?e:[]}},{key:"indexOf",value:function(t,e){for(var n=0;n0)&&(e=t[n]);return e}},{key:"extract",value:function(t,e,n){e=Et.clamp(e,0,t.length);var r=(n=Et.clamp(n,-1,t.length))-e+1;n<0&&(r=0),e>=t.length&&(r=0),nr.length)return 1;if(0===n.length)return 0;var i=Wt.compare(n,r);return Wt.isEqualReversed(n,r)?0:i}},{key:"OLDcompare",value:function(t,e){var n=t,r=e;if(n.lengthr.length)return 1;if(0===n.length)return 0;for(var i=Wt.increasingDirection(n),o=Wt.increasingDirection(r),s=i>0?0:n.length-1,a=o>0?0:n.length-1,u=0;u0){var t=new Qt(17*this._coordinates.length);t.append("("),t.append(this._coordinates[0]);for(var e=1;e3&&(t=3),t<2&&(t=2),new $t(arguments[0],t)}if(3===arguments.length){var e=arguments[2],n=arguments[1]-e;return e>1&&(e=1),n>3&&(n=3),n<2&&(n=2),new $t(arguments[0],n+e,e)}}}},{key:"interfaces_",get:function(){return[bt,w]}}],[{key:"instance",value:function(){return e.instanceObject}}]),e}();te.instanceObject=new te;var ee=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e=0?t:e}}]),e}(),oe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"readResolve",value:function(){return e.nameToTypeMap.get(this._name)}},{key:"toString",value:function(){return this._name}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){this._name=null;var t=arguments[0];this._name=t,e.nameToTypeMap.put(t,this)}}]),e}();oe.nameToTypeMap=new re,ie.Type=oe,ie.FIXED=new oe("FIXED"),ie.FLOATING=new oe("FLOATING"),ie.FLOATING_SINGLE=new oe("FLOATING SINGLE"),ie.maximumPreciseValue=9007199254740992;var se=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e1){if(u instanceof Ft)return this.createMultiPolygon(e.toPolygonArray(t));if(u instanceof Ct)return this.createMultiLineString(e.toLineStringArray(t));if(u instanceof Ot)return this.createMultiPoint(e.toPointArray(t));V.shouldNeverReachHere("Unhandled geometry type: "+u.getGeometryType())}return u}},{key:"createMultiPointFromCoords",value:function(t){return this.createMultiPoint(null!==t?this.getCoordinateSequenceFactory().create(t):null)}},{key:"createPoint",value:function(){if(0===arguments.length)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];return this.createPoint(null!==t?this.getCoordinateSequenceFactory().create([t]):null)}if(ot(arguments[0],ct))return new Ot(arguments[0],this)}}},{key:"getCoordinateSequenceFactory",value:function(){return this._coordinateSequenceFactory}},{key:"createPolygon",value:function(){if(0===arguments.length)return this.createPolygon(null,null);if(1===arguments.length){if(ot(arguments[0],ct)){var t=arguments[0];return this.createPolygon(this.createLinearRing(t))}if(arguments[0]instanceof Array){var e=arguments[0];return this.createPolygon(this.createLinearRing(e))}if(arguments[0]instanceof zt){var n=arguments[0];return this.createPolygon(n,null)}}else if(2===arguments.length)return new Ft(arguments[0],arguments[1],this)}},{key:"getSRID",value:function(){return this._SRID}},{key:"createGeometryCollection",value:function(){return 0===arguments.length?new Bt(null,this):1===arguments.length?new Bt(arguments[0],this):void 0}},{key:"getPrecisionModel",value:function(){return this._precisionModel}},{key:"createLinearRing",value:function(){if(0===arguments.length)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof Array){var t=arguments[0];return this.createLinearRing(null!==t?this.getCoordinateSequenceFactory().create(t):null)}if(ot(arguments[0],ct))return new zt(arguments[0],this)}}},{key:"createMultiPolygon",value:function(){return 0===arguments.length?new ee(null,this):1===arguments.length?new ee(arguments[0],this):void 0}},{key:"createMultiPoint",value:function(){if(0===arguments.length)return new Yt(null,this);if(1===arguments.length){if(arguments[0]instanceof Array)return new Yt(arguments[0],this);if(ot(arguments[0],ct)){var t=arguments[0];if(null===t)return this.createMultiPoint(new Array(0).fill(null));for(var e=new Array(t.size()).fill(null),n=0;n="a"&&t<="z"||t>="A"&&t<="Z"}},{key:"isNumeric_",value:function(t,e){return t>="0"&&t<="9"||"."==t&&!(void 0!==e&&e)}},{key:"isWhiteSpace_",value:function(t){return" "==t||"\t"==t||"\r"==t||"\n"==t}},{key:"nextChar_",value:function(){return this.wkt.charAt(++this.index_)}},{key:"nextToken",value:function(){var t,e=this.nextChar_(),n=this.index_,r=e;if("("==e)t=ve;else if(","==e)t=me;else if(")"==e)t=de;else if(this.isNumeric_(e)||"-"==e)t=ye,r=this.readNumber_();else if(this.isAlpha_(e))t=pe,r=this.readText_();else{if(this.isWhiteSpace_(e))return this.nextToken();if(""!==e)throw new Error("Unexpected character: "+e);t=_e}return{position:n,value:r,type:t}}},{key:"readNumber_",value:function(){var t,e=this.index_,n=!1,r=!1;do{"."==t?n=!0:"e"!=t&&"E"!=t||(r=!0),t=this.nextChar_()}while(this.isNumeric_(t,n)||!r&&("e"==t||"E"==t)||r&&("-"==t||"+"==t));return parseFloat(this.wkt.substring(e,this.index_--))}},{key:"readText_",value:function(){var t,e=this.index_;do{t=this.nextChar_()}while(this.isAlpha_(t));return this.wkt.substring(e,this.index_--).toUpperCase()}}]),e}(),ke=function(){function e(n,r){t(this,e),this.lexer_=n,this.token_,this.layout_=ue,this.factory=r}return n(e,[{key:"consume_",value:function(){this.token_=this.lexer_.nextToken()}},{key:"isTokenType",value:function(t){return this.token_.type==t}},{key:"match",value:function(t){var e=this.isTokenType(t);return e&&this.consume_(),e}},{key:"parse",value:function(){return this.consume_(),this.parseGeometry_()}},{key:"parseGeometryLayout_",value:function(){var t=ue,e=this.token_;if(this.isTokenType(pe)){var n=e.value;"Z"===n?t=le:"M"===n?t=he:"ZM"===n&&(t=ce),t!==ue&&this.consume_()}return t}},{key:"parseGeometryCollectionText_",value:function(){if(this.match(ve)){var t=[];do{t.push(this.parseGeometry_())}while(this.match(me));if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePointText_",value:function(){if(this.match(ve)){var t=this.parsePoint_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return null;throw new Error(this.formatErrorMessage_())}},{key:"parseLineStringText_",value:function(){if(this.match(ve)){var t=this.parsePointList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePolygonText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPointText_",value:function(){var t;if(this.match(ve)){if(t=this.token_.type==ve?this.parsePointTextList_():this.parsePointList_(),this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiLineStringText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPolygonText_",value:function(){if(this.match(ve)){var t=this.parsePolygonTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePoint_",value:function(){for(var t=[],e=this.layout_.length,n=0;n1?t.createPolygon(r[0],r.slice(1)):t.createPolygon(r[0])},r=this.token_;if(this.match(pe)){var i=r.value;if(this.layout_=this.parseGeometryLayout_(),"GEOMETRYCOLLECTION"==i){var o=this.parseGeometryCollectionText_();return t.createGeometryCollection(o)}switch(i){case"POINT":var s=this.parsePointText_();return s?t.createPoint(a(z,g(s))):t.createPoint();case"LINESTRING":var u=this.parseLineStringText_().map(e);return t.createLineString(u);case"LINEARRING":var l=this.parseLineStringText_().map(e);return t.createLinearRing(l);case"POLYGON":var h=this.parsePolygonText_();return h&&0!==h.length?n(h):t.createPolygon();case"MULTIPOINT":var c=this.parseMultiPointText_();if(!c||0===c.length)return t.createMultiPoint();var f=c.map(e).map((function(e){return t.createPoint(e)}));return t.createMultiPoint(f);case"MULTILINESTRING":var p=this.parseMultiLineStringText_().map((function(n){return t.createLineString(n.map(e))}));return t.createMultiLineString(p);case"MULTIPOLYGON":var v=this.parseMultiPolygonText_();if(!v||0===v.length)return t.createMultiPolygon();var d=v.map(n);return t.createMultiPolygon(d);default:throw new Error("Invalid geometry type: "+i)}}throw new Error(this.formatErrorMessage_())}}]),e}();function be(t){if(t.isEmpty())return"";var e=t.getCoordinate(),n=[e.x,e.y];return void 0===e.z||Number.isNaN(e.z)||n.push(e.z),void 0===e.m||Number.isNaN(e.m)||n.push(e.m),n.join(" ")}function we(t){for(var e=t.getCoordinates().map((function(t){var e=[t.x,t.y];return void 0===t.z||Number.isNaN(t.z)||e.push(t.z),void 0===t.m||Number.isNaN(t.m)||e.push(t.m),e})),n=[],r=0,i=e.length;r0&&(e+=" "+r),t.isEmpty()?e+" "+ge:e+" ("+n(t)+")"}var Me=function(){function e(n){t(this,e),this.geometryFactory=n||new ae,this.precisionModel=this.geometryFactory.getPrecisionModel()}return n(e,[{key:"read",value:function(t){var e=new Ee(t);return new ke(e,this.geometryFactory).parse()}},{key:"write",value:function(t){return Se(t)}}]),e}(),Le=function(){function e(n){t(this,e),this.parser=new Me(n)}return n(e,[{key:"write",value:function(t){return this.parser.write(t)}}],[{key:"toLineString",value:function(t,e){if(2!==arguments.length)throw new Error("Not implemented");return"LINESTRING ( "+t.x+" "+t.y+", "+e.x+" "+e.y+" )"}}]),e}(),Pe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getIndexAlongSegment",value:function(t,e){return this.computeIntLineIndex(),this._intLineIndex[t][e]}},{key:"getTopologySummary",value:function(){var t=new Qt;return this.isEndPoint()&&t.append(" endpoint"),this._isProper&&t.append(" proper"),this.isCollinear()&&t.append(" collinear"),t.toString()}},{key:"computeIntersection",value:function(t,e,n,r){this._inputLines[0][0]=t,this._inputLines[0][1]=e,this._inputLines[1][0]=n,this._inputLines[1][1]=r,this._result=this.computeIntersect(t,e,n,r)}},{key:"getIntersectionNum",value:function(){return this._result}},{key:"computeIntLineIndex",value:function(){if(0===arguments.length)null===this._intLineIndex&&(this._intLineIndex=Array(2).fill().map((function(){return Array(2)})),this.computeIntLineIndex(0),this.computeIntLineIndex(1));else if(1===arguments.length){var t=arguments[0];this.getEdgeDistance(t,0)>this.getEdgeDistance(t,1)?(this._intLineIndex[t][0]=0,this._intLineIndex[t][1]=1):(this._intLineIndex[t][0]=1,this._intLineIndex[t][1]=0)}}},{key:"isProper",value:function(){return this.hasIntersection()&&this._isProper}},{key:"setPrecisionModel",value:function(t){this._precisionModel=t}},{key:"isInteriorIntersection",value:function(){if(0===arguments.length)return!!this.isInteriorIntersection(0)||!!this.isInteriorIntersection(1);if(1===arguments.length){for(var t=arguments[0],e=0;ei?r:i;else{var s=Math.abs(t.x-e.x),a=Math.abs(t.y-e.y);0!==(o=r>i?s:a)||t.equals(e)||(o=Math.max(s,a))}return V.isTrue(!(0===o&&!t.equals(e)),"Bad distance calculation"),o}},{key:"nonRobustComputeEdgeDistance",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y,o=Math.sqrt(r*r+i*i);return V.isTrue(!(0===o&&!t.equals(e)),"Invalid distance calculation"),o}}]),e}();Pe.DONT_INTERSECT=0,Pe.DO_INTERSECT=1,Pe.COLLINEAR=2,Pe.NO_INTERSECTION=0,Pe.POINT_INTERSECTION=1,Pe.COLLINEAR_INTERSECTION=2;var Ce=function(e){r(s,e);var o=c(s);function s(){return t(this,s),o.call(this)}return n(s,[{key:"isInSegmentEnvelopes",value:function(t){var e=new X(this._inputLines[0][0],this._inputLines[0][1]),n=new X(this._inputLines[1][0],this._inputLines[1][1]);return e.contains(t)&&n.contains(t)}},{key:"computeIntersection",value:function(){if(3!==arguments.length)return f(i(s.prototype),"computeIntersection",this).apply(this,arguments);var t=arguments[0],e=arguments[1],n=arguments[2];if(this._isProper=!1,X.intersects(e,n,t)&&0===ft.index(e,n,t)&&0===ft.index(n,e,t))return this._isProper=!0,(t.equals(e)||t.equals(n))&&(this._isProper=!1),this._result=Pe.POINT_INTERSECTION,null;this._result=Pe.NO_INTERSECTION}},{key:"intersection",value:function(t,e,n,r){var i=this.intersectionSafe(t,e,n,r);return this.isInSegmentEnvelopes(i)||(i=new z(s.nearestEndpoint(t,e,n,r))),null!==this._precisionModel&&this._precisionModel.makePrecise(i),i}},{key:"checkDD",value:function(t,e,n,r,i){var o=ht.intersection(t,e,n,r),s=this.isInSegmentEnvelopes(o);xt.out.println("DD in env = "+s+" --------------------- "+o),i.distance(o)>1e-4&&xt.out.println("Distance = "+i.distance(o))}},{key:"intersectionSafe",value:function(t,e,n,r){var i=_t.intersection(t,e,n,r);return null===i&&(i=s.nearestEndpoint(t,e,n,r)),i}},{key:"computeCollinearIntersection",value:function(t,e,n,r){var i=X.intersects(t,e,n),o=X.intersects(t,e,r),s=X.intersects(n,r,t),a=X.intersects(n,r,e);return i&&o?(this._intPt[0]=n,this._intPt[1]=r,Pe.COLLINEAR_INTERSECTION):s&&a?(this._intPt[0]=t,this._intPt[1]=e,Pe.COLLINEAR_INTERSECTION):i&&s?(this._intPt[0]=n,this._intPt[1]=t,!n.equals(t)||o||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):i&&a?(this._intPt[0]=n,this._intPt[1]=e,!n.equals(e)||o||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&s?(this._intPt[0]=r,this._intPt[1]=t,!r.equals(t)||i||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&a?(this._intPt[0]=r,this._intPt[1]=e,!r.equals(e)||i||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):Pe.NO_INTERSECTION}},{key:"computeIntersect",value:function(t,e,n,r){if(this._isProper=!1,!X.intersects(t,e,n,r))return Pe.NO_INTERSECTION;var i=ft.index(t,e,n),o=ft.index(t,e,r);if(i>0&&o>0||i<0&&o<0)return Pe.NO_INTERSECTION;var s=ft.index(n,r,t),a=ft.index(n,r,e);return s>0&&a>0||s<0&&a<0?Pe.NO_INTERSECTION:0===i&&0===o&&0===s&&0===a?this.computeCollinearIntersection(t,e,n,r):(0===i||0===o||0===s||0===a?(this._isProper=!1,t.equals2D(n)||t.equals2D(r)?this._intPt[0]=t:e.equals2D(n)||e.equals2D(r)?this._intPt[0]=e:0===i?this._intPt[0]=new z(n):0===o?this._intPt[0]=new z(r):0===s?this._intPt[0]=new z(t):0===a&&(this._intPt[0]=new z(e))):(this._isProper=!0,this._intPt[0]=this.intersection(t,e,n,r)),Pe.POINT_INTERSECTION)}}],[{key:"nearestEndpoint",value:function(t,e,n,r){var i=t,o=kt.pointToSegment(t,n,r),s=kt.pointToSegment(e,n,r);return sr&&(n=e.x,r=t.x),this._p.x>=n&&this._p.x<=r&&(this._isPointOnSegment=!0),null}if(t.y>this._p.y&&e.y<=this._p.y||e.y>this._p.y&&t.y<=this._p.y){var i=ft.index(t,e,this._p);if(i===ft.COLLINEAR)return this._isPointOnSegment=!0,null;e.ythis.location.length){var e=new Array(3).fill(null);e[tt.ON]=this.location[tt.ON],e[tt.LEFT]=Z.NONE,e[tt.RIGHT]=Z.NONE,this.location=e}for(var n=0;n1&&t.append(Z.toLocationSymbol(this.location[tt.LEFT])),t.append(Z.toLocationSymbol(this.location[tt.ON])),this.location.length>1&&t.append(Z.toLocationSymbol(this.location[tt.RIGHT])),t.toString()}},{key:"setLocations",value:function(t,e,n){this.location[tt.ON]=t,this.location[tt.LEFT]=e,this.location[tt.RIGHT]=n}},{key:"get",value:function(t){return t1}},{key:"isAnyNull",value:function(){for(var t=0;tthis._maxNodeDegree&&(this._maxNodeDegree=e),t=this.getNext(t)}while(t!==this._startDe);this._maxNodeDegree*=2}},{key:"addPoints",value:function(t,e,n){var r=t.getCoordinates();if(e){var i=1;n&&(i=0);for(var o=i;o=0;a--)this._pts.add(r[a])}}},{key:"isHole",value:function(){return this._isHole}},{key:"setInResult",value:function(){var t=this._startDe;do{t.getEdge().setInResult(!0),t=t.getNext()}while(t!==this._startDe)}},{key:"containsPoint",value:function(t){var e=this.getLinearRing();if(!e.getEnvelopeInternal().contains(t))return!1;if(!Oe.isInRing(t,e.getCoordinates()))return!1;for(var n=this._holes.iterator();n.hasNext();)if(n.next().containsPoint(t))return!1;return!0}},{key:"addHole",value:function(t){this._holes.add(t)}},{key:"isShell",value:function(){return null===this._shell}},{key:"getLabel",value:function(){return this._label}},{key:"getEdges",value:function(){return this._edges}},{key:"getMaxNodeDegree",value:function(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree}},{key:"getShell",value:function(){return this._shell}},{key:"mergeLabel",value:function(){if(1===arguments.length){var t=arguments[0];this.mergeLabel(t,0),this.mergeLabel(t,1)}else if(2===arguments.length){var e=arguments[1],n=arguments[0].getLocation(e,tt.RIGHT);if(n===Z.NONE)return null;if(this._label.getLocation(e)===Z.NONE)return this._label.setLocation(e,n),null}}},{key:"setShell",value:function(t){this._shell=t,null!==t&&t.addHole(this)}},{key:"toPolygon",value:function(t){for(var e=new Array(this._holes.size()).fill(null),n=0;n=2,"found partial label"),this.computeIM(t)}},{key:"isInResult",value:function(){return this._isInResult}},{key:"isVisited",value:function(){return this._isVisited}}],[{key:"constructor_",value:function(){if(this._label=null,this._isInResult=!1,this._isCovered=!1,this._isCoveredSet=!1,this._isVisited=!1,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._label=t}}}]),e}(),Ge=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isIncidentEdgeInResult",value:function(){for(var t=this.getEdges().getEdges().iterator();t.hasNext();)if(t.next().getEdge().isInResult())return!0;return!1}},{key:"isIsolated",value:function(){return 1===this._label.getGeometryCount()}},{key:"getCoordinate",value:function(){return this._coord}},{key:"print",value:function(t){t.println("node "+this._coord+" lbl: "+this._label)}},{key:"computeIM",value:function(t){}},{key:"computeMergedLocation",value:function(t,e){var n=Z.NONE;if(n=this._label.getLocation(e),!t.isNull(e)){var r=t.getLocation(e);n!==Z.BOUNDARY&&(n=r)}return n}},{key:"setLabel",value:function(){if(2!==arguments.length||!Number.isInteger(arguments[1])||!Number.isInteger(arguments[0]))return f(i(s.prototype),"setLabel",this).apply(this,arguments);var t=arguments[0],e=arguments[1];null===this._label?this._label=new Ae(t,e):this._label.setLocation(t,e)}},{key:"getEdges",value:function(){return this._edges}},{key:"mergeLabel",value:function(){if(arguments[0]instanceof s){var t=arguments[0];this.mergeLabel(t._label)}else if(arguments[0]instanceof Ae)for(var e=arguments[0],n=0;n<2;n++){var r=this.computeMergedLocation(e,n);this._label.getLocation(n)===Z.NONE&&this._label.setLocation(n,r)}}},{key:"add",value:function(t){this._edges.insert(t),t.setNode(this)}},{key:"setLabelBoundary",value:function(t){if(null===this._label)return null;var e=Z.NONE;null!==this._label&&(e=this._label.getLocation(t));var n=null;switch(e){case Z.BOUNDARY:n=Z.INTERIOR;break;case Z.INTERIOR:default:n=Z.BOUNDARY}this._label.setLocation(t,n)}}],[{key:"constructor_",value:function(){this._coord=null,this._edges=null;var t=arguments[0],e=arguments[1];this._coord=t,this._edges=e,this._label=new Ae(0,Z.NONE)}}]),s}(Ve),Be=function(e){r(i,e);var n=c(i);function i(){return t(this,i),n.apply(this,arguments)}return i}(ne);function Ye(t){return null==t?0:t.color}function ze(t){return null==t?null:t.parent}function je(t,e){null!==t&&(t.color=e)}function Xe(t){return null==t?null:t.left}function Ue(t){return null==t?null:t.right}var Ze=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),(e=i.call(this)).root_=null,e.size_=0,e}return n(o,[{key:"get",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return e.value;e=e.right}}return null}},{key:"put",value:function(t,e){if(null===this.root_)return this.root_={key:t,value:e,left:null,right:null,parent:null,color:0,getValue:function(){return this.value},getKey:function(){return this.key}},this.size_=1,null;var n,r,i=this.root_;do{if(n=i,(r=t.compareTo(i.key))<0)i=i.left;else{if(!(r>0)){var o=i.value;return i.value=e,o}i=i.right}}while(null!==i);var s={key:t,left:null,right:null,value:e,parent:n,color:0,getValue:function(){return this.value},getKey:function(){return this.key}};return r<0?n.left=s:n.right=s,this.fixAfterInsertion(s),this.size_++,null}},{key:"fixAfterInsertion",value:function(t){var e;for(t.color=1;null!=t&&t!==this.root_&&1===t.parent.color;)ze(t)===Xe(ze(ze(t)))?1===Ye(e=Ue(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Ue(ze(t))&&(t=ze(t),this.rotateLeft(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateRight(ze(ze(t)))):1===Ye(e=Xe(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Xe(ze(t))&&(t=ze(t),this.rotateRight(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateLeft(ze(ze(t))));this.root_.color=0}},{key:"values",value:function(){var t=new dt,e=this.getFirstEntry();if(null!==e)for(t.add(e.value);null!==(e=o.successor(e));)t.add(e.value);return t}},{key:"entrySet",value:function(){var t=new Q,e=this.getFirstEntry();if(null!==e)for(t.add(e);null!==(e=o.successor(e));)t.add(e);return t}},{key:"rotateLeft",value:function(t){if(null!=t){var e=t.right;t.right=e.left,null!=e.left&&(e.left.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.left===t?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}}},{key:"rotateRight",value:function(t){if(null!=t){var e=t.left;t.left=e.right,null!=e.right&&(e.right.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.right===t?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}}},{key:"getFirstEntry",value:function(){var t=this.root_;if(null!=t)for(;null!=t.left;)t=t.left;return t}},{key:"size",value:function(){return this.size_}},{key:"containsKey",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return!0;e=e.right}}return!1}}],[{key:"successor",value:function(t){var e;if(null===t)return null;if(null!==t.right){for(e=t.right;null!==e.left;)e=e.left;return e}e=t.parent;for(var n=t;null!==e&&n===e.right;)n=e,e=e.parent;return e}}]),o}(Be),He=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"find",value:function(t){return this.nodeMap.get(t)}},{key:"addNode",value:function(){if(arguments[0]instanceof z){var t=arguments[0],e=this.nodeMap.get(t);return null===e&&(e=this.nodeFact.createNode(t),this.nodeMap.put(t,e)),e}if(arguments[0]instanceof Ge){var n=arguments[0],r=this.nodeMap.get(n.getCoordinate());return null===r?(this.nodeMap.put(n.getCoordinate(),n),n):(r.mergeLabel(n),r)}}},{key:"print",value:function(t){for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this.nodeMap.values().iterator()}},{key:"values",value:function(){return this.nodeMap.values()}},{key:"getBoundaryNodes",value:function(t){for(var e=new dt,n=this.iterator();n.hasNext();){var r=n.next();r.getLabel().getLocation(t)===Z.BOUNDARY&&e.add(r)}return e}},{key:"add",value:function(t){var e=t.getCoordinate();this.addNode(e).add(t)}}],[{key:"constructor_",value:function(){this.nodeMap=new Ze,this.nodeFact=null;var t=arguments[0];this.nodeFact=t}}]),e}(),We=function(){function e(){t(this,e)}return n(e,null,[{key:"isNorthern",value:function(t){return t===e.NE||t===e.NW}},{key:"isOpposite",value:function(t,e){return t!==e&&2==(t-e+4)%4}},{key:"commonHalfPlane",value:function(t,e){if(t===e)return t;if(2==(t-e+4)%4)return-1;var n=te?t:e)?3:n}},{key:"isInHalfPlane",value:function(t,n){return n===e.SE?t===e.SE||t===e.SW:t===n||t===n+1}},{key:"quadrant",value:function(){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1];if(0===t&&0===n)throw new x("Cannot compute the quadrant for point ( "+t+", "+n+" )");return t>=0?n>=0?e.NE:e.SE:n>=0?e.NW:e.SW}if(arguments[0]instanceof z&&arguments[1]instanceof z){var r=arguments[0],i=arguments[1];if(i.x===r.x&&i.y===r.y)throw new x("Cannot compute the quadrant for two identical points "+r);return i.x>=r.x?i.y>=r.y?e.NE:e.SE:i.y>=r.y?e.NW:e.SW}}}]),e}();We.NE=0,We.NW=1,We.SW=2,We.SE=3;var Je=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareDirection",value:function(t){return this._dx===t._dx&&this._dy===t._dy?0:this._quadrant>t._quadrant?1:this._quadrant2){o.linkDirectedEdgesForMinimalEdgeRings();var s=o.buildMinimalRings(),a=this.findShell(s);null!==a?(this.placePolygonHoles(a,s),e.add(a)):n.addAll(s)}else r.add(o)}return r}},{key:"buildMaximalEdgeRings",value:function(t){for(var e=new dt,n=t.iterator();n.hasNext();){var r=n.next();if(r.isInResult()&&r.getLabel().isArea()&&null===r.getEdgeRing()){var i=new qe(r,this._geometryFactory);e.add(i),i.setInResult()}}return e}},{key:"placePolygonHoles",value:function(t,e){for(var n=e.iterator();n.hasNext();){var r=n.next();r.isHole()&&r.setShell(t)}}},{key:"getPolygons",value:function(){return this.computePolygons(this._shellList)}},{key:"findShell",value:function(t){for(var e=0,n=null,r=t.iterator();r.hasNext();){var i=r.next();i.isHole()||(n=i,e++)}return V.isTrue(e<=1,"found two shells in MinimalEdgeRing list"),n}},{key:"add",value:function(){if(1===arguments.length){var t=arguments[0];this.add(t.getEdgeEnds(),t.getNodes())}else if(2===arguments.length){var e=arguments[0],n=arguments[1];$e.linkResultDirectedEdges(n);var r=this.buildMaximalEdgeRings(e),i=new dt,o=this.buildMinimalEdgeRings(r,this._shellList,i);this.sortShellsAndHoles(o,this._shellList,i),this.placeFreeHoles(this._shellList,i)}}}],[{key:"constructor_",value:function(){this._geometryFactory=null,this._shellList=new dt;var t=arguments[0];this._geometryFactory=t}},{key:"findEdgeRingContaining",value:function(t,e){for(var n=t.getLinearRing(),r=n.getEnvelopeInternal(),i=n.getCoordinateN(0),o=null,s=null,a=e.iterator();a.hasNext();){var u=a.next(),l=u.getLinearRing(),h=l.getEnvelopeInternal();if(!h.equals(r)&&h.contains(r)){i=Wt.ptNotInList(n.getCoordinates(),l.getCoordinates());var c=!1;Oe.isInRing(i,l.getCoordinates())&&(c=!0),c&&(null===o||s.contains(h))&&(s=(o=u).getLinearRing().getEnvelopeInternal())}}return o}}]),e}(),en=function(){function e(){t(this,e)}return n(e,[{key:"getBounds",value:function(){}}]),e}(),nn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getItem",value:function(){return this._item}},{key:"getBounds",value:function(){return this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){this._bounds=null,this._item=null;var t=arguments[0],e=arguments[1];this._bounds=t,this._item=e}}]),e}(),rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"poll",value:function(){if(this.isEmpty())return null;var t=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),t}},{key:"size",value:function(){return this._size}},{key:"reorder",value:function(t){for(var e=null,n=this._items.get(t);2*t<=this._size&&((e=2*t)!==this._size&&this._items.get(e+1).compareTo(this._items.get(e))<0&&e++,this._items.get(e).compareTo(n)<0);t=e)this._items.set(t,this._items.get(e));this._items.set(t,n)}},{key:"clear",value:function(){this._size=0,this._items.clear()}},{key:"peek",value:function(){return this.isEmpty()?null:this._items.get(1)}},{key:"isEmpty",value:function(){return 0===this._size}},{key:"add",value:function(t){this._items.add(null),this._size+=1;var e=this._size;for(this._items.set(0,t);t.compareTo(this._items.get(Math.trunc(e/2)))<0;e/=2)this._items.set(e,this._items.get(Math.trunc(e/2)));this._items.set(e,t)}}],[{key:"constructor_",value:function(){this._size=null,this._items=null,this._size=0,this._items=new dt,this._items.add(null)}}]),e}(),on=function(){function e(){t(this,e)}return n(e,[{key:"insert",value:function(t,e){}},{key:"remove",value:function(t,e){}},{key:"query",value:function(){}}]),e}(),sn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLevel",value:function(){return this._level}},{key:"size",value:function(){return this._childBoundables.size()}},{key:"getChildBoundables",value:function(){return this._childBoundables}},{key:"addChildBoundable",value:function(t){V.isTrue(null===this._bounds),this._childBoundables.add(t)}},{key:"isEmpty",value:function(){return this._childBoundables.isEmpty()}},{key:"getBounds",value:function(){return null===this._bounds&&(this._bounds=this.computeBounds()),this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){if(this._childBoundables=new dt,this._bounds=null,this._level=null,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._level=t}}}]),e}(),an={reverseOrder:function(){return{compare:function(t,e){return e.compareTo(t)}}},min:function(t){return an.sort(t),t.get(0)},sort:function(t,e){var n=t.toArray();e?At.sort(n,e):At.sort(n);for(var r=t.iterator(),i=0,o=n.length;ie.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,!1,t,n),null):(this.expand(this._boundable2,this._boundable1,!0,t,n),null);if(r)return this.expand(this._boundable1,this._boundable2,!1,t,n),null;if(i)return this.expand(this._boundable2,this._boundable1,!0,t,n),null;throw new x("neither boundable is composite")}},{key:"isLeaves",value:function(){return!(e.isComposite(this._boundable1)||e.isComposite(this._boundable2))}},{key:"compareTo",value:function(t){var e=t;return this._distancee._distance?1:0}},{key:"expand",value:function(t,n,r,i,o){for(var s=t.getChildBoundables().iterator();s.hasNext();){var a=s.next(),u=null;(u=r?new e(n,a,this._itemDistance):new e(a,n,this._itemDistance)).getDistance()-2),r.getLevel()===n)return i.add(r),null;for(var o=r.getChildBoundables().iterator();o.hasNext();){var s=o.next();s instanceof sn?this.boundablesAtLevel(n,s,i):(V.isTrue(s instanceof nn),-1===n&&i.add(s))}return null}}},{key:"query",value:function(){if(1===arguments.length){var t=arguments[0];this.build();var e=new dt;return this.isEmpty()||this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.queryInternal(t,this._root,e),e}if(2===arguments.length){var n=arguments[0],r=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),n)&&this.queryInternal(n,this._root,r)}}},{key:"build",value:function(){if(this._built)return null;this._root=this._itemBoundables.isEmpty()?this.createNode(0):this.createHigherLevels(this._itemBoundables,-1),this._itemBoundables=null,this._built=!0}},{key:"getRoot",value:function(){return this.build(),this._root}},{key:"remove",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];return this.build(),!!this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.remove(t,this._root,e)}if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],o=this.removeItem(r,i);if(o)return!0;for(var s=null,a=r.getChildBoundables().iterator();a.hasNext();){var u=a.next();if(this.getIntersectsOp().intersects(u.getBounds(),n)&&u instanceof sn&&(o=this.remove(n,u,i))){s=u;break}}return null!==s&&s.getChildBoundables().isEmpty()&&r.getChildBoundables().remove(s),o}}},{key:"createHigherLevels",value:function(t,e){V.isTrue(!t.isEmpty());var n=this.createParentBoundables(t,e+1);return 1===n.size()?n.get(0):this.createHigherLevels(n,e+1)}},{key:"depth",value:function(){if(0===arguments.length)return this.isEmpty()?0:(this.build(),this.depth(this._root));if(1===arguments.length){for(var t=0,e=arguments[0].getChildBoundables().iterator();e.hasNext();){var n=e.next();if(n instanceof sn){var r=this.depth(n);r>t&&(t=r)}}return t+1}}},{key:"createParentBoundables",value:function(t,e){V.isTrue(!t.isEmpty());var n=new dt;n.add(this.createNode(e));var r=new dt(t);an.sort(r,this.getComparator());for(var i=r.iterator();i.hasNext();){var o=i.next();this.lastNode(n).getChildBoundables().size()===this.getNodeCapacity()&&n.add(this.createNode(e)),this.lastNode(n).addChildBoundable(o)}return n}},{key:"isEmpty",value:function(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){if(this._root=null,this._built=!1,this._itemBoundables=new dt,this._nodeCapacity=null,0===arguments.length)e.constructor_.call(this,e.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];V.isTrue(t>1,"Node capacity must be greater than 1"),this._nodeCapacity=t}}},{key:"compareDoubles",value:function(t,e){return t>e?1:t0);for(var n=new dt,r=0;r=0;){var u=o.poll(),l=u.getDistance();if(l>=i)break;u.isLeaves()?a.size()l&&(a.poll(),a.add(u)),i=a.peek().getDistance()):u.expandToQueue(o,i)}return s.getItems(a)}}},{key:"createNode",value:function(t){return new pn(t)}},{key:"size",value:function(){return 0===arguments.length?f(i(s.prototype),"size",this).call(this):f(i(s.prototype),"size",this).apply(this,arguments)}},{key:"insert",value:function(){if(!(2===arguments.length&&arguments[1]instanceof Object&&arguments[0]instanceof X))return f(i(s.prototype),"insert",this).apply(this,arguments);var t=arguments[0],e=arguments[1];if(t.isNull())return null;f(i(s.prototype),"insert",this).call(this,t,e)}},{key:"getIntersectsOp",value:function(){return s.intersectsOp}},{key:"verticalSlices",value:function(t,e){for(var n=Math.trunc(Math.ceil(t.size()/e)),r=new Array(e).fill(null),i=t.iterator(),o=0;o0;){var s=o.poll(),a=s.getDistance();if(a>=r)break;s.isLeaves()?(r=a,i=s):s.expandToQueue(o,r)}return null===i?null:[i.getBoundable(0).getItem(),i.getBoundable(1).getItem()]}}else{if(2===arguments.length){var u=arguments[0],l=arguments[1];if(this.isEmpty()||u.isEmpty())return null;var h=new ln(this.getRoot(),u.getRoot(),l);return this.nearestNeighbour(h)}if(3===arguments.length){var c=arguments[2],f=new nn(arguments[0],arguments[1]),g=new ln(this.getRoot(),f,c);return this.nearestNeighbour(g)[0]}if(4===arguments.length){var p=arguments[2],v=arguments[3],d=new nn(arguments[0],arguments[1]),y=new ln(this.getRoot(),d,p);return this.nearestNeighbourK(y,v)}}}},{key:"isWithinDistance",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1],n=A.POSITIVE_INFINITY,r=new rn;for(r.add(t);!r.isEmpty();){var i=r.poll(),o=i.getDistance();if(o>e)return!1;if(i.maximumDistance()<=e)return!0;if(i.isLeaves()){if((n=o)<=e)return!0}else i.expandToQueue(r,n)}return!1}if(3===arguments.length){var s=arguments[0],a=arguments[1],u=arguments[2],l=new ln(this.getRoot(),s.getRoot(),a);return this.isWithinDistance(l,u)}}},{key:"interfaces_",get:function(){return[on,w]}}],[{key:"constructor_",value:function(){if(0===arguments.length)s.constructor_.call(this,s.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];cn.constructor_.call(this,t)}}},{key:"centreX",value:function(t){return s.avg(t.getMinX(),t.getMaxX())}},{key:"avg",value:function(t,e){return(t+e)/2}},{key:"getItems",value:function(t){for(var e=new Array(t.size()).fill(null),n=0;!t.isEmpty();){var r=t.poll();e[n]=r.getBoundable(0).getItem(),n++}return e}},{key:"centreY",value:function(t){return s.avg(t.getMinY(),t.getMaxY())}}]),s}(cn),pn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"computeBounds",value:function(){for(var t=null,e=this.getChildBoundables().iterator();e.hasNext();){var n=e.next();null===t?t=new X(n.getBounds()):t.expandToInclude(n.getBounds())}return t}}],[{key:"constructor_",value:function(){var t=arguments[0];sn.constructor_.call(this,t)}}]),o}(sn);gn.STRtreeNode=pn,gn.xComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreX(t.getBounds()),gn.centreX(e.getBounds()))}}]),e}()),gn.yComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreY(t.getBounds()),gn.centreY(e.getBounds()))}}]),e}()),gn.intersectsOp=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[IntersectsOp]}},{key:"intersects",value:function(t,e){return t.intersects(e)}}]),e}()),gn.DEFAULT_NODE_CAPACITY=10;var vn=function(){function e(){t(this,e)}return n(e,null,[{key:"relativeSign",value:function(t,e){return te?1:0}},{key:"compare",value:function(t,n,r){if(n.equals2D(r))return 0;var i=e.relativeSign(n.x,r.x),o=e.relativeSign(n.y,r.y);switch(t){case 0:return e.compareValue(i,o);case 1:return e.compareValue(o,i);case 2:return e.compareValue(o,-i);case 3:return e.compareValue(-i,o);case 4:return e.compareValue(-i,-o);case 5:return e.compareValue(-o,-i);case 6:return e.compareValue(-o,i);case 7:return e.compareValue(i,-o)}return V.shouldNeverReachHere("invalid octant value"),0}},{key:"compareValue",value:function(t,e){return t<0?-1:t>0?1:e<0?-1:e>0?1:0}}]),e}(),dn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this.coord}},{key:"print",value:function(t){t.print(this.coord),t.print(" seg # = "+this.segmentIndex)}},{key:"compareTo",value:function(t){var e=t;return this.segmentIndexe.segmentIndex?1:this.coord.equals2D(e.coord)?0:this._isInterior?e._isInterior?vn.compare(this._segmentOctant,this.coord,e.coord):1:-1}},{key:"isEndPoint",value:function(t){return 0===this.segmentIndex&&!this._isInterior||this.segmentIndex===t}},{key:"toString",value:function(){return this.segmentIndex+":"+this.coord.toString()}},{key:"isInterior",value:function(){return this._isInterior}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;var t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this._segString=t,this.coord=new z(e),this.segmentIndex=n,this._segmentOctant=r,this._isInterior=!e.equals2D(t.getCoordinate(n))}}]),e}(),yn=function(){function e(){t(this,e)}return n(e,[{key:"hasNext",value:function(){}},{key:"next",value:function(){}},{key:"remove",value:function(){}}]),e}(),mn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getSplitCoordinates",value:function(){var t=new Ht;this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next();this.addEdgeCoordinates(n,r,t),n=r}return t.toCoordinateArray()}},{key:"addCollapsedNodes",value:function(){var t=new dt;this.findCollapsesFromInsertedNodes(t),this.findCollapsesFromExistingVertices(t);for(var e=t.iterator();e.hasNext();){var n=e.next().intValue();this.add(this._edge.getCoordinate(n),n)}}},{key:"createSplitEdgePts",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2;if(2===n)return[new z(t.coord),new z(e.coord)];var r=this._edge.getCoordinate(e.segmentIndex),i=e.isInterior()||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this._edge.getCoordinate(a);return i&&(o[s]=new z(e.coord)),o}},{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"findCollapsesFromExistingVertices",value:function(t){for(var e=0;e=0?n>=0?r>=i?0:1:r>=i?7:6:n>=0?r>=i?3:2:r>=i?4:5}if(arguments[0]instanceof z&&arguments[1]instanceof z){var o=arguments[0],s=arguments[1],a=s.x-o.x,u=s.y-o.y;if(0===a&&0===u)throw new x("Cannot compute the octant for two identical points "+o);return e.octant(a,u)}}}]),e}(),xn=function(){function e(){t(this,e)}return n(e,[{key:"getCoordinates",value:function(){}},{key:"size",value:function(){}},{key:"getCoordinate",value:function(t){}},{key:"isClosed",value:function(){}},{key:"setData",value:function(t){}},{key:"getData",value:function(){}}]),e}(),En=function(){function e(){t(this,e)}return n(e,[{key:"addIntersection",value:function(t,e){}},{key:"interfaces_",get:function(){return[xn]}}]),e}(),kn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinates",value:function(){return this._pts}},{key:"size",value:function(){return this._pts.length}},{key:"getCoordinate",value:function(t){return this._pts[t]}},{key:"isClosed",value:function(){return this._pts[0].equals(this._pts[this._pts.length-1])}},{key:"getSegmentOctant",value:function(t){return t===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(t),this.getCoordinate(t+1))}},{key:"setData",value:function(t){this._data=t}},{key:"safeOctant",value:function(t,e){return t.equals2D(e)?0:_n.octant(t,e)}},{key:"getData",value:function(){return this._data}},{key:"addIntersection",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];this.addIntersectionNode(t,e)}else if(4===arguments.length){var n=arguments[1],r=arguments[3],i=new z(arguments[0].getIntersection(r));this.addIntersection(i,n)}}},{key:"toString",value:function(){return Le.toLineString(new $t(this._pts))}},{key:"getNodeList",value:function(){return this._nodeList}},{key:"addIntersectionNode",value:function(t,e){var n=e,r=n+1;if(r=0&&r>=0||n<=0&&r<=0?Math.max(n,r):0}if(arguments[0]instanceof z){var i=arguments[0];return ft.index(this.p0,this.p1,i)}}},{key:"toGeometry",value:function(t){return t.createLineString([this.p0,this.p1])}},{key:"isVertical",value:function(){return this.p0.x===this.p1.x}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.p0.equals(n.p0)&&this.p1.equals(n.p1)}},{key:"intersection",value:function(t){var e=new Ce;return e.computeIntersection(this.p0,this.p1,t.p0,t.p1),e.hasIntersection()?e.getIntersection(0):null}},{key:"project",value:function(){if(arguments[0]instanceof z){var t=arguments[0];if(t.equals(this.p0)||t.equals(this.p1))return new z(t);var n=this.projectionFactor(t),r=new z;return r.x=this.p0.x+n*(this.p1.x-this.p0.x),r.y=this.p0.y+n*(this.p1.y-this.p0.y),r}if(arguments[0]instanceof e){var i=arguments[0],o=this.projectionFactor(i.p0),s=this.projectionFactor(i.p1);if(o>=1&&s>=1)return null;if(o<=0&&s<=0)return null;var a=this.project(i.p0);o<0&&(a=this.p0),o>1&&(a=this.p1);var u=this.project(i.p1);return s<0&&(u=this.p0),s>1&&(u=this.p1),new e(a,u)}}},{key:"normalize",value:function(){this.p1.compareTo(this.p0)<0&&this.reverse()}},{key:"angle",value:function(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)}},{key:"getCoordinate",value:function(t){return 0===t?this.p0:this.p1}},{key:"distancePerpendicular",value:function(t){return kt.pointToLinePerpendicular(t,this.p0,this.p1)}},{key:"minY",value:function(){return Math.min(this.p0.y,this.p1.y)}},{key:"midPoint",value:function(){return e.midPoint(this.p0,this.p1)}},{key:"projectionFactor",value:function(t){if(t.equals(this.p0))return 0;if(t.equals(this.p1))return 1;var e=this.p1.x-this.p0.x,n=this.p1.y-this.p0.y,r=e*e+n*n;return r<=0?A.NaN:((t.x-this.p0.x)*e+(t.y-this.p0.y)*n)/r}},{key:"closestPoints",value:function(t){var e=this.intersection(t);if(null!==e)return[e,e];var n=new Array(2).fill(null),r=A.MAX_VALUE,i=null,o=this.closestPoint(t.p0);r=o.distance(t.p0),n[0]=o,n[1]=t.p0;var s=this.closestPoint(t.p1);(i=s.distance(t.p1))0&&e<1?this.project(t):this.p0.distance(t)1||A.isNaN(e))&&(e=1),e}},{key:"toString",value:function(){return"LINESTRING( "+this.p0.x+" "+this.p0.y+", "+this.p1.x+" "+this.p1.y+")"}},{key:"isHorizontal",value:function(){return this.p0.y===this.p1.y}},{key:"reflect",value:function(t){var e=this.p1.getY()-this.p0.getY(),n=this.p0.getX()-this.p1.getX(),r=this.p0.getY()*(this.p1.getX()-this.p0.getX())-this.p0.getX()*(this.p1.getY()-this.p0.getY()),i=e*e+n*n,o=e*e-n*n,s=t.getX(),a=t.getY();return new z((-o*s-2*e*n*a-2*e*r)/i,(o*a-2*e*n*s-2*n*r)/i)}},{key:"distance",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return kt.segmentToSegment(this.p0,this.p1,t.p0,t.p1)}if(arguments[0]instanceof z){var n=arguments[0];return kt.pointToSegment(n,this.p0,this.p1)}}},{key:"pointAlong",value:function(t){var e=new z;return e.x=this.p0.x+t*(this.p1.x-this.p0.x),e.y=this.p0.y+t*(this.p1.y-this.p0.y),e}},{key:"hashCode",value:function(){var t=A.doubleToLongBits(this.p0.x);t^=31*A.doubleToLongBits(this.p0.y);var e=Math.trunc(t)^Math.trunc(t>>32),n=A.doubleToLongBits(this.p1.x);return n^=31*A.doubleToLongBits(this.p1.y),e^Math.trunc(n)^Math.trunc(n>>32)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this.p0=null,this.p1=null,0===arguments.length)e.constructor_.call(this,new z,new z);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.p0,t.p1)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.p0=n,this.p1=r}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];e.constructor_.call(this,new z(i,o),new z(s,a))}}},{key:"midPoint",value:function(t,e){return new z((t.x+e.x)/2,(t.y+e.y)/2)}}]),e}(),wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"overlap",value:function(){if(2===arguments.length);else if(4===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[3];arguments[0].getLineSegment(t,this._overlapSeg1),e.getLineSegment(n,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}}}],[{key:"constructor_",value:function(){this._overlapSeg1=new bn,this._overlapSeg2=new bn}}]),e}(),In=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLineSegment",value:function(t,e){e.p0=this._pts[t],e.p1=this._pts[t+1]}},{key:"computeSelect",value:function(t,e,n,r){var i=this._pts[e],o=this._pts[n];if(n-e==1)return r.select(this,e),null;if(!t.intersects(i,o))return null;var s=Math.trunc((e+n)/2);e=t.length-1)return t.length-1;for(var r=We.quadrant(t[n],t[n+1]),i=e+1;in.getId()&&(n.computeOverlaps(i,t),this._nOverlaps++),this._segInt.isDone())return null}}}],[{key:"constructor_",value:function(){if(this._monoChains=new dt,this._index=new gn,this._idCounter=0,this._nodedSegStrings=null,this._nOverlaps=0,0===arguments.length);else if(1===arguments.length){var t=arguments[0];Mn.constructor_.call(this,t)}}}]),o}(Mn),Pn=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"overlap",value:function(){if(4!==arguments.length)return f(i(s.prototype),"overlap",this).apply(this,arguments);var t=arguments[1],e=arguments[2],n=arguments[3],r=arguments[0].getContext(),o=e.getContext();this._si.processIntersections(r,t,o,n)}}],[{key:"constructor_",value:function(){this._si=null;var t=arguments[0];this._si=t}}]),s}(wn);Ln.SegmentOverlapAction=Pn;var Cn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isDeletable",value:function(t,e,n,r){var i=this._inputLine[t],o=this._inputLine[e],s=this._inputLine[n];return!!this.isConcave(i,o,s)&&!!this.isShallow(i,o,s,r)&&this.isShallowSampled(i,o,t,n,r)}},{key:"deleteShallowConcavities",value:function(){for(var t=1,n=this.findNextNonDeletedIndex(t),r=this.findNextNonDeletedIndex(n),i=!1;r=0;r--)this.addPt(t[r])}},{key:"isRedundant",value:function(t){if(this._ptList.size()<1)return!1;var e=this._ptList.get(this._ptList.size()-1);return t.distance(e)Math.PI;)t-=e.PI_TIMES_2;for(;t<=-Math.PI;)t+=e.PI_TIMES_2;return t}},{key:"angle",value:function(){if(1===arguments.length){var t=arguments[0];return Math.atan2(t.y,t.x)}if(2===arguments.length){var e=arguments[0],n=arguments[1],r=n.x-e.x,i=n.y-e.y;return Math.atan2(i,r)}}},{key:"isAcute",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)>0}},{key:"isObtuse",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)<0}},{key:"interiorAngle",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return Math.abs(o-i)}},{key:"normalizePositive",value:function(t){if(t<0){for(;t<0;)t+=e.PI_TIMES_2;t>=e.PI_TIMES_2&&(t=0)}else{for(;t>=e.PI_TIMES_2;)t-=e.PI_TIMES_2;t<0&&(t=0)}return t}},{key:"angleBetween",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return e.diff(i,o)}},{key:"diff",value:function(t,e){var n=null;return(n=tMath.PI&&(n=2*Math.PI-n),n}},{key:"toRadians",value:function(t){return t*Math.PI/180}},{key:"getTurn",value:function(t,n){var r=Math.sin(n-t);return r>0?e.COUNTERCLOCKWISE:r<0?e.CLOCKWISE:e.NONE}},{key:"angleBetweenOriented",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r)-i;return o<=-Math.PI?o+e.PI_TIMES_2:o>Math.PI?o-e.PI_TIMES_2:o}}]),e}();On.PI_TIMES_2=2*Math.PI,On.PI_OVER_2=Math.PI/2,On.PI_OVER_4=Math.PI/4,On.COUNTERCLOCKWISE=ft.COUNTERCLOCKWISE,On.CLOCKWISE=ft.CLOCKWISE,On.NONE=ft.COLLINEAR;var Rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addNextSegment",value:function(t,e){if(this._s0=this._s1,this._s1=this._s2,this._s2=t,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;var n=ft.index(this._s0,this._s1,this._s2),r=n===ft.CLOCKWISE&&this._side===tt.LEFT||n===ft.COUNTERCLOCKWISE&&this._side===tt.RIGHT;0===n?this.addCollinear(e):r?this.addOutsideTurn(n,e):this.addInsideTurn(n,e)}},{key:"addLineEndCap",value:function(t,e){var n=new bn(t,e),r=new bn;this.computeOffsetSegment(n,tt.LEFT,this._distance,r);var i=new bn;this.computeOffsetSegment(n,tt.RIGHT,this._distance,i);var o=e.x-t.x,s=e.y-t.y,a=Math.atan2(s,o);switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:this._segList.addPt(r.p1),this.addDirectedFillet(e,a+Math.PI/2,a-Math.PI/2,ft.CLOCKWISE,this._distance),this._segList.addPt(i.p1);break;case y.CAP_FLAT:this._segList.addPt(r.p1),this._segList.addPt(i.p1);break;case y.CAP_SQUARE:var u=new z;u.x=Math.abs(this._distance)*Math.cos(a),u.y=Math.abs(this._distance)*Math.sin(a);var l=new z(r.p1.x+u.x,r.p1.y+u.y),h=new z(i.p1.x+u.x,i.p1.y+u.y);this._segList.addPt(l),this._segList.addPt(h)}}},{key:"getCoordinates",value:function(){return this._segList.getCoordinates()}},{key:"addMitreJoin",value:function(t,e,n,r){var i=_t.intersection(e.p0,e.p1,n.p0,n.p1);if(null!==i&&(r<=0?1:i.distance(t)/Math.abs(r))<=this._bufParams.getMitreLimit())return this._segList.addPt(i),null;this.addLimitedMitreJoin(e,n,r,this._bufParams.getMitreLimit())}},{key:"addOutsideTurn",value:function(t,n){if(this._offset0.p1.distance(this._offset1.p0)=h&&(a-=2*Math.PI),this._segList.addPt(e),this.addDirectedFillet(t,a,h,r,i),this._segList.addPt(n)}},{key:"addLastSegment",value:function(){this._segList.addPt(this._offset1.p1)}},{key:"initSideSegments",value:function(t,e,n){this._s1=t,this._s2=e,this._side=n,this._seg1.setCoordinates(t,e),this.computeOffsetSegment(this._seg1,n,this._distance,this._offset1)}},{key:"addLimitedMitreJoin",value:function(t,e,n,r){var i=this._seg0.p1,o=On.angle(i,this._seg0.p0),s=On.angleBetweenOriented(this._seg0.p0,i,this._seg1.p1)/2,a=On.normalize(o+s),u=On.normalize(a+Math.PI),l=r*n,h=n-l*Math.abs(Math.sin(s)),c=i.x+l*Math.cos(u),f=i.y+l*Math.sin(u),g=new z(c,f),p=new bn(i,g),v=p.pointAlongOffset(1,h),d=p.pointAlongOffset(1,-h);this._side===tt.LEFT?(this._segList.addPt(v),this._segList.addPt(d)):(this._segList.addPt(d),this._segList.addPt(v))}},{key:"addDirectedFillet",value:function(t,e,n,r,i){var o=r===ft.CLOCKWISE?-1:1,s=Math.abs(e-n),a=Math.trunc(s/this._filletAngleQuantum+.5);if(a<1)return null;for(var u=s/a,l=new z,h=0;h0){var r=new z((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(r);var i=new z((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(i)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}}},{key:"createCircle",value:function(t){var e=new z(t.x+this._distance,t.y);this._segList.addPt(e),this.addDirectedFillet(t,0,2*Math.PI,-1,this._distance),this._segList.closeRing()}},{key:"addBevelJoin",value:function(t,e){this._segList.addPt(t.p1),this._segList.addPt(e.p0)}},{key:"init",value:function(t){this._distance=t,this._maxCurveSegmentError=t*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new Tn,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(t*e.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)}},{key:"addCollinear",value:function(t){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2),this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===y.JOIN_BEVEL||this._bufParams.getJoinStyle()===y.JOIN_MITRE?(t&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,ft.CLOCKWISE,this._distance))}},{key:"closeRing",value:function(){this._segList.closeRing()}},{key:"hasNarrowConcaveAngle",value:function(){return this._hasNarrowConcaveAngle}}],[{key:"constructor_",value:function(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new bn,this._seg1=new bn,this._offset0=new bn,this._offset1=new bn,this._side=0,this._hasNarrowConcaveAngle=!1;var t=arguments[0],n=arguments[1],r=arguments[2];this._precisionModel=t,this._bufParams=n,this._li=new Ce,this._filletAngleQuantum=Math.PI/2/n.getQuadrantSegments(),n.getQuadrantSegments()>=8&&n.getJoinStyle()===y.JOIN_ROUND&&(this._closingSegLengthFactor=e.MAX_CLOSING_SEG_LEN_FACTOR),this.init(r)}}]),e}();Rn.OFFSET_SEGMENT_SEPARATION_FACTOR=.001,Rn.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR=.001,Rn.CURVE_VERTEX_SNAP_DISTANCE_FACTOR=1e-6,Rn.MAX_CLOSING_SEG_LEN_FACTOR=80;var An=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getOffsetCurve",value:function(t,e){if(this._distance=e,0===e)return null;var n=e<0,r=Math.abs(e),i=this.getSegGen(r);t.length<=1?this.computePointCurve(t[0],i):this.computeOffsetCurve(t,n,i);var o=i.getCoordinates();return n&&Wt.reverse(o),o}},{key:"computeSingleSidedBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){n.addSegments(t,!0);var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{n.addSegments(t,!1);var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment(),n.closeRing()}},{key:"computeRingBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);e===tt.RIGHT&&(r=-r);var i=Cn.simplify(t,r),o=i.length-1;n.initSideSegments(i[o-1],i[0],e);for(var s=1;s<=o;s++){var a=1!==s;n.addNextSegment(i[s],a)}n.closeRing()}},{key:"computeLineBufferCurve",value:function(t,e){var n=this.simplifyTolerance(this._distance),r=Cn.simplify(t,n),i=r.length-1;e.initSideSegments(r[0],r[1],tt.LEFT);for(var o=2;o<=i;o++)e.addNextSegment(r[o],!0);e.addLastSegment(),e.addLineEndCap(r[i-1],r[i]);var s=Cn.simplify(t,-n),a=s.length-1;e.initSideSegments(s[a],s[a-1],tt.LEFT);for(var u=a-2;u>=0;u--)e.addNextSegment(s[u],!0);e.addLastSegment(),e.addLineEndCap(s[1],s[0]),e.closeRing()}},{key:"computePointCurve",value:function(t,e){switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:e.createCircle(t);break;case y.CAP_SQUARE:e.createSquare(t)}}},{key:"getLineCurve",value:function(t,e){if(this._distance=e,this.isLineOffsetEmpty(e))return null;var n=Math.abs(e),r=this.getSegGen(n);if(t.length<=1)this.computePointCurve(t[0],r);else if(this._bufParams.isSingleSided()){var i=e<0;this.computeSingleSidedBufferCurve(t,i,r)}else this.computeLineBufferCurve(t,r);return r.getCoordinates()}},{key:"getBufferParameters",value:function(){return this._bufParams}},{key:"simplifyTolerance",value:function(t){return t*this._bufParams.getSimplifyFactor()}},{key:"getRingCurve",value:function(t,n,r){if(this._distance=r,t.length<=2)return this.getLineCurve(t,r);if(0===r)return e.copyCoordinates(t);var i=this.getSegGen(r);return this.computeRingBufferCurve(t,n,i),i.getCoordinates()}},{key:"computeOffsetCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment()}},{key:"isLineOffsetEmpty",value:function(t){return 0===t||t<0&&!this._bufParams.isSingleSided()}},{key:"getSegGen",value:function(t){return new Rn(this._precisionModel,this._bufParams,t)}}],[{key:"constructor_",value:function(){this._distance=0,this._precisionModel=null,this._bufParams=null;var t=arguments[0],e=arguments[1];this._precisionModel=t,this._bufParams=e}},{key:"copyCoordinates",value:function(t){for(var e=new Array(t.length).fill(null),n=0;ni.getMaxY()||this.findStabbedSegments(t,r.getDirectedEdges(),e)}return e}if(3===arguments.length)if(ot(arguments[2],rt)&&arguments[0]instanceof z&&arguments[1]instanceof Ke){for(var o=arguments[0],s=arguments[1],a=arguments[2],u=s.getEdge().getCoordinates(),l=0;lthis._seg.p1.y&&this._seg.reverse(),!(Math.max(this._seg.p0.x,this._seg.p1.x)this._seg.p1.y||ft.index(this._seg.p0,this._seg.p1,o)===ft.RIGHT)){var h=s.getDepth(tt.LEFT);this._seg.p0.equals(u[l])||(h=s.getDepth(tt.RIGHT));var c=new Fn(this._seg,h);a.add(c)}}else if(ot(arguments[2],rt)&&arguments[0]instanceof z&&ot(arguments[1],rt))for(var f=arguments[0],g=arguments[2],p=arguments[1].iterator();p.hasNext();){var v=p.next();v.isForward()&&this.findStabbedSegments(f,v,g)}}},{key:"getDepth",value:function(t){var e=this.findStabbedSegments(t);return 0===e.size()?0:an.min(e)._leftDepth}}],[{key:"constructor_",value:function(){this._subgraphs=null,this._seg=new bn;var t=arguments[0];this._subgraphs=t}}]),e}(),Fn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var e=t;if(this._upwardSeg.minX()>=e._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=e._upwardSeg.minX())return-1;var n=this._upwardSeg.orientationIndex(e._upwardSeg);return 0!==n||0!=(n=-1*e._upwardSeg.orientationIndex(this._upwardSeg))?n:this._upwardSeg.compareTo(e._upwardSeg)}},{key:"compareX",value:function(t,e){var n=t.p0.compareTo(e.p0);return 0!==n?n:t.p1.compareTo(e.p1)}},{key:"toString",value:function(){return this._upwardSeg.toString()}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._upwardSeg=null,this._leftDepth=null;var t=arguments[0],e=arguments[1];this._upwardSeg=new bn(t),this._leftDepth=e}}]),e}();Dn.DepthSegment=Fn;var qn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){_.constructor_.call(this,"Projective point not representable on the Cartesian plane.")}}]),o}(_),Vn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getY",value:function(){var t=this.y/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getX",value:function(){var t=this.x/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getCoordinate",value:function(){var t=new z;return t.x=this.getX(),t.y=this.getY(),t}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.w=null,0===arguments.length)this.x=0,this.y=0,this.w=1;else if(1===arguments.length){var t=arguments[0];this.x=t.x,this.y=t.y,this.w=1}else if(2===arguments.length){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var n=arguments[0],r=arguments[1];this.x=n,this.y=r,this.w=1}else if(arguments[0]instanceof e&&arguments[1]instanceof e){var i=arguments[0],o=arguments[1];this.x=i.y*o.w-o.y*i.w,this.y=o.x*i.w-i.x*o.w,this.w=i.x*o.y-o.x*i.y}else if(arguments[0]instanceof z&&arguments[1]instanceof z){var s=arguments[0],a=arguments[1];this.x=s.y-a.y,this.y=a.x-s.x,this.w=s.x*a.y-a.x*s.y}}else if(3===arguments.length){var u=arguments[0],l=arguments[1],h=arguments[2];this.x=u,this.y=l,this.w=h}else if(4===arguments.length){var c=arguments[0],f=arguments[1],g=arguments[2],p=arguments[3],v=c.y-f.y,d=f.x-c.x,y=c.x*f.y-f.x*c.y,m=g.y-p.y,_=p.x-g.x,x=g.x*p.y-p.x*g.y;this.x=d*x-_*y,this.y=m*y-v*x,this.w=v*_-m*d}}}]),e}(),Gn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"area",value:function(){return e.area(this.p0,this.p1,this.p2)}},{key:"signedArea",value:function(){return e.signedArea(this.p0,this.p1,this.p2)}},{key:"interpolateZ",value:function(t){if(null===t)throw new x("Supplied point is null.");return e.interpolateZ(t,this.p0,this.p1,this.p2)}},{key:"longestSideLength",value:function(){return e.longestSideLength(this.p0,this.p1,this.p2)}},{key:"isAcute",value:function(){return e.isAcute(this.p0,this.p1,this.p2)}},{key:"circumcentre",value:function(){return e.circumcentre(this.p0,this.p1,this.p2)}},{key:"area3D",value:function(){return e.area3D(this.p0,this.p1,this.p2)}},{key:"centroid",value:function(){return e.centroid(this.p0,this.p1,this.p2)}},{key:"inCentre",value:function(){return e.inCentre(this.p0,this.p1,this.p2)}}],[{key:"constructor_",value:function(){this.p0=null,this.p1=null,this.p2=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.p0=t,this.p1=e,this.p2=n}},{key:"area",value:function(t,e,n){return Math.abs(((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2)}},{key:"signedArea",value:function(t,e,n){return((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2}},{key:"det",value:function(t,e,n,r){return t*r-e*n}},{key:"interpolateZ",value:function(t,e,n,r){var i=e.x,o=e.y,s=n.x-i,a=r.x-i,u=n.y-o,l=r.y-o,h=s*l-a*u,c=t.x-i,f=t.y-o,g=(l*c-a*f)/h,p=(-u*c+s*f)/h;return e.getZ()+g*(n.getZ()-e.getZ())+p*(r.getZ()-e.getZ())}},{key:"longestSideLength",value:function(t,e,n){var r=t.distance(e),i=e.distance(n),o=n.distance(t),s=r;return i>s&&(s=i),o>s&&(s=o),s}},{key:"circumcentreDD",value:function(t,e,n){var r=lt.valueOf(t.x).subtract(n.x),i=lt.valueOf(t.y).subtract(n.y),o=lt.valueOf(e.x).subtract(n.x),s=lt.valueOf(e.y).subtract(n.y),a=lt.determinant(r,i,o,s).multiply(2),u=r.sqr().add(i.sqr()),l=o.sqr().add(s.sqr()),h=lt.determinant(i,u,s,l),c=lt.determinant(r,u,o,l),f=lt.valueOf(n.x).subtract(h.divide(a)).doubleValue(),g=lt.valueOf(n.y).add(c.divide(a)).doubleValue();return new z(f,g)}},{key:"isAcute",value:function(t,e,n){return!!On.isAcute(t,e,n)&&!!On.isAcute(e,n,t)&&!!On.isAcute(n,t,e)}},{key:"circumcentre",value:function(t,n,r){var i=r.x,o=r.y,s=t.x-i,a=t.y-o,u=n.x-i,l=n.y-o,h=2*e.det(s,a,u,l),c=e.det(a,s*s+a*a,l,u*u+l*l),f=e.det(s,s*s+a*a,u,u*u+l*l);return new z(i-c/h,o+f/h)}},{key:"perpendicularBisector",value:function(t,e){var n=e.x-t.x,r=e.y-t.y,i=new Vn(t.x+n/2,t.y+r/2,1),o=new Vn(t.x-r+n/2,t.y+n+r/2,1);return new Vn(i,o)}},{key:"angleBisector",value:function(t,e,n){var r=e.distance(t),i=r/(r+e.distance(n)),o=n.x-t.x,s=n.y-t.y;return new z(t.x+i*o,t.y+i*s)}},{key:"area3D",value:function(t,e,n){var r=e.x-t.x,i=e.y-t.y,o=e.getZ()-t.getZ(),s=n.x-t.x,a=n.y-t.y,u=n.getZ()-t.getZ(),l=i*u-o*a,h=o*s-r*u,c=r*a-i*s,f=l*l+h*h+c*c;return Math.sqrt(f)/2}},{key:"centroid",value:function(t,e,n){var r=(t.x+e.x+n.x)/3,i=(t.y+e.y+n.y)/3;return new z(r,i)}},{key:"inCentre",value:function(t,e,n){var r=e.distance(n),i=t.distance(n),o=t.distance(e),s=r+i+o,a=(r*t.x+i*e.x+o*n.x)/s,u=(r*t.y+i*e.y+o*n.y)/s;return new z(a,u)}}]),e}(),Bn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addRingSide",value:function(t,e,n,r,i){if(0===e&&t.length=zt.MINIMUM_VALID_SIZE&&ft.isCCW(t)&&(o=i,s=r,n=tt.opposite(n));var a=this._curveBuilder.getRingCurve(t,n,e);this.addCurve(a,o,s)}},{key:"addRingBothSides",value:function(t,e){this.addRingSide(t,e,tt.LEFT,Z.EXTERIOR,Z.INTERIOR),this.addRingSide(t,e,tt.RIGHT,Z.INTERIOR,Z.EXTERIOR)}},{key:"addPoint",value:function(t){if(this._distance<=0)return null;var e=t.getCoordinates(),n=this._curveBuilder.getLineCurve(e,this._distance);this.addCurve(n,Z.EXTERIOR,Z.INTERIOR)}},{key:"addPolygon",value:function(t){var e=this._distance,n=tt.LEFT;this._distance<0&&(e=-this._distance,n=tt.RIGHT);var r=t.getExteriorRing(),i=Wt.removeRepeatedPoints(r.getCoordinates());if(this._distance<0&&this.isErodedCompletely(r,this._distance))return null;if(this._distance<=0&&i.length<3)return null;this.addRingSide(i,e,n,Z.EXTERIOR,Z.INTERIOR);for(var o=0;o0&&this.isErodedCompletely(s,-this._distance)||this.addRingSide(a,e,tt.opposite(n),Z.INTERIOR,Z.EXTERIOR)}}},{key:"isTriangleErodedCompletely",value:function(t,e){var n=new Gn(t[0],t[1],t[2]),r=n.inCentre();return kt.pointToSegment(r,n.p0,n.p1)i}},{key:"addCollection",value:function(t){for(var e=0;e=this._max)throw new W;var t=this._parent.getGeometryN(this._index++);return t instanceof Bt?(this._subcollectionIterator=new e(t),this._subcollectionIterator.next()):t}},{key:"remove",value:function(){throw new J(this.getClass().getName())}},{key:"hasNext",value:function(){if(this._atStart)return!0;if(null!==this._subcollectionIterator){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)}},{key:"interfaces_",get:function(){return[yn]}}],[{key:"constructor_",value:function(){this._parent=null,this._atStart=null,this._max=null,this._index=null,this._subcollectionIterator=null;var t=arguments[0];this._parent=t,this._atStart=!0,this._index=0,this._max=t.getNumGeometries()}},{key:"isAtomic",value:function(t){return!(t instanceof Bt)}}]),e}(),jn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"locate",value:function(t){return e.locate(t,this._geom)}},{key:"interfaces_",get:function(){return[Yn]}}],[{key:"constructor_",value:function(){this._geom=null;var t=arguments[0];this._geom=t}},{key:"locatePointInPolygon",value:function(t,n){if(n.isEmpty())return Z.EXTERIOR;var r=n.getExteriorRing(),i=e.locatePointInRing(t,r);if(i!==Z.INTERIOR)return i;for(var o=0;o=0;n--){var r=this._edgeList.get(n),i=r.getSym();null===e&&(e=i),null!==t&&i.setNext(t),t=r}e.setNext(t)}},{key:"computeDepths",value:function(){if(1===arguments.length){var t=arguments[0],e=this.findIndex(t),n=t.getDepth(tt.LEFT),r=t.getDepth(tt.RIGHT),i=this.computeDepths(e+1,this._edgeList.size(),n);if(this.computeDepths(0,e,i)!==r)throw new pt("depth mismatch at "+t.getCoordinate())}else if(3===arguments.length){for(var o=arguments[1],s=arguments[2],a=arguments[0];a=0;i--){var o=this._resultAreaEdgeList.get(i),s=o.getSym();switch(null===e&&o.getEdgeRing()===t&&(e=o),r){case this._SCANNING_FOR_INCOMING:if(s.getEdgeRing()!==t)continue;n=s,r=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(o.getEdgeRing()!==t)continue;n.setNextMin(o),r=this._SCANNING_FOR_INCOMING}}r===this._LINKING_TO_OUTGOING&&(V.isTrue(null!==e,"found null for first outgoing dirEdge"),V.isTrue(e.getEdgeRing()===t,"unable to link last incoming dirEdge"),n.setNextMin(e))}},{key:"getOutgoingDegree",value:function(){if(0===arguments.length){for(var t=0,e=this.iterator();e.hasNext();)e.next().isInResult()&&t++;return t}if(1===arguments.length){for(var n=arguments[0],r=0,i=this.iterator();i.hasNext();)i.next().getEdgeRing()===n&&r++;return r}}},{key:"getLabel",value:function(){return this._label}},{key:"findCoveredLineEdges",value:function(){for(var t=Z.NONE,e=this.iterator();e.hasNext();){var n=e.next(),r=n.getSym();if(!n.isLineEdge()){if(n.isInResult()){t=Z.INTERIOR;break}if(r.isInResult()){t=Z.EXTERIOR;break}}}if(t===Z.NONE)return null;for(var i=t,o=this.iterator();o.hasNext();){var s=o.next(),a=s.getSym();s.isLineEdge()?s.getEdge().setCovered(i===Z.INTERIOR):(s.isInResult()&&(i=Z.EXTERIOR),a.isInResult()&&(i=Z.INTERIOR))}}},{key:"computeLabelling",value:function(t){f(i(s.prototype),"computeLabelling",this).call(this,t),this._label=new Ae(Z.NONE);for(var e=this.iterator();e.hasNext();)for(var n=e.next().getEdge().getLabel(),r=0;r<2;r++){var o=n.getLocation(r);o!==Z.INTERIOR&&o!==Z.BOUNDARY||this._label.setLocation(r,Z.INTERIOR)}}}],[{key:"constructor_",value:function(){this._resultAreaEdgeList=null,this._label=null,this._SCANNING_FOR_INCOMING=1,this._LINKING_TO_OUTGOING=2}}]),s}(Xn),Zn=function(e){r(o,e);var i=c(o);function o(){return t(this,o),i.call(this)}return n(o,[{key:"createNode",value:function(t){return new Ge(t,new Un)}}]),o}(Qe),Hn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var n=t;return e.compareOriented(this._pts,this._orientation,n._pts,n._orientation)}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._pts=null,this._orientation=null;var t=arguments[0];this._pts=t,this._orientation=e.orientation(t)}},{key:"orientation",value:function(t){return 1===Wt.increasingDirection(t)}},{key:"compareOriented",value:function(t,e,n,r){for(var i=e?1:-1,o=r?1:-1,s=e?t.length:-1,a=r?n.length:-1,u=e?0:t.length-1,l=r?0:n.length-1;;){var h=t[u].compareTo(n[l]);if(0!==h)return h;var c=(u+=i)===s,f=(l+=o)===a;if(c&&!f)return-1;if(!c&&f)return 1;if(c&&f)return 0}}}]),e}(),Wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.print("MULTILINESTRING ( ");for(var e=0;e0&&t.print(","),t.print("(");for(var r=n.getCoordinates(),i=0;i0&&t.print(","),t.print(r[i].x+" "+r[i].y);t.println(")")}t.print(") ")}},{key:"addAll",value:function(t){for(var e=t.iterator();e.hasNext();)this.add(e.next())}},{key:"findEdgeIndex",value:function(t){for(var e=0;et?1:this.diste?1:0}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this.coord=null,this.segmentIndex=null,this.dist=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.coord=new z(t),this.segmentIndex=e,this.dist=n}}]),e}(),$n=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this._nodeMap.values().iterator()}},{key:"addSplitEdges",value:function(t){this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next(),i=this.createSplitEdge(n,r);t.add(i),n=r}}},{key:"addEndpoints",value:function(){var t=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[t],t,0)}},{key:"createSplitEdge",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2,r=this.edge.pts[e.segmentIndex],i=e.dist>0||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this.edge.pts[a];return i&&(o[s]=e.coord),new or(o,new Ae(this.edge._label))}},{key:"add",value:function(t,e,n){var r=new Qn(t,e,n),i=this._nodeMap.get(r);return null!==i?i:(this._nodeMap.put(r,r),r)}},{key:"isIntersection",value:function(t){for(var e=this.iterator();e.hasNext();)if(e.next().coord.equals(t))return!0;return!1}}],[{key:"constructor_",value:function(){this._nodeMap=new Ze,this.edge=null;var t=arguments[0];this.edge=t}}]),e}(),tr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isIntersects",value:function(){return!this.isDisjoint()}},{key:"isCovers",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"isCoveredBy",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"set",value:function(){if(1===arguments.length)for(var t=arguments[0],e=0;e=0&&e>=0&&this.setAtLeast(t,e,n)}},{key:"isWithin",value:function(){return e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"isTouches",value:function(t,n){return t>n?this.isTouches(n,t):(t===Mt.A&&n===Mt.A||t===Mt.L&&n===Mt.L||t===Mt.L&&n===Mt.A||t===Mt.P&&n===Mt.A||t===Mt.P&&n===Mt.L)&&this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&(e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))}},{key:"isOverlaps",value:function(t,n){return t===Mt.P&&n===Mt.P||t===Mt.A&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&1===this._matrix[Z.INTERIOR][Z.INTERIOR]&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR])}},{key:"isEquals",value:function(t,n){return t===n&&e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"toString",value:function(){for(var t=new Qt("123456789"),e=0;e<3;e++)for(var n=0;n<3;n++)t.setCharAt(3*e+n,Mt.toDimensionSymbol(this._matrix[e][n]));return t.toString()}},{key:"setAll",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this._matrix[e][n]=t}},{key:"get",value:function(t,e){return this._matrix[t][e]}},{key:"transpose",value:function(){var t=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=t,t=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=t,t=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=t,this}},{key:"matches",value:function(t){if(9!==t.length)throw new x("Should be length 9: "+t);for(var n=0;n<3;n++)for(var r=0;r<3;r++)if(!e.matches(this._matrix[n][r],t.charAt(3*n+r)))return!1;return!0}},{key:"add",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this.setAtLeast(e,n,t.get(e,n))}},{key:"isDisjoint",value:function(){return this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.INTERIOR][Z.BOUNDARY]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.BOUNDARY]===Mt.FALSE}},{key:"isCrosses",value:function(t,n){return t===Mt.P&&n===Mt.L||t===Mt.P&&n===Mt.A||t===Mt.L&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR]):t===Mt.L&&n===Mt.P||t===Mt.A&&n===Mt.P||t===Mt.A&&n===Mt.L?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&0===this._matrix[Z.INTERIOR][Z.INTERIOR]}},{key:"interfaces_",get:function(){return[b]}}],[{key:"constructor_",value:function(){if(this._matrix=null,0===arguments.length)this._matrix=Array(3).fill().map((function(){return Array(3)})),this.setAll(Mt.FALSE);else if(1===arguments.length)if("string"==typeof arguments[0]){var t=arguments[0];e.constructor_.call(this),this.set(t)}else if(arguments[0]instanceof e){var n=arguments[0];e.constructor_.call(this),this._matrix[Z.INTERIOR][Z.INTERIOR]=n._matrix[Z.INTERIOR][Z.INTERIOR],this._matrix[Z.INTERIOR][Z.BOUNDARY]=n._matrix[Z.INTERIOR][Z.BOUNDARY],this._matrix[Z.INTERIOR][Z.EXTERIOR]=n._matrix[Z.INTERIOR][Z.EXTERIOR],this._matrix[Z.BOUNDARY][Z.INTERIOR]=n._matrix[Z.BOUNDARY][Z.INTERIOR],this._matrix[Z.BOUNDARY][Z.BOUNDARY]=n._matrix[Z.BOUNDARY][Z.BOUNDARY],this._matrix[Z.BOUNDARY][Z.EXTERIOR]=n._matrix[Z.BOUNDARY][Z.EXTERIOR],this._matrix[Z.EXTERIOR][Z.INTERIOR]=n._matrix[Z.EXTERIOR][Z.INTERIOR],this._matrix[Z.EXTERIOR][Z.BOUNDARY]=n._matrix[Z.EXTERIOR][Z.BOUNDARY],this._matrix[Z.EXTERIOR][Z.EXTERIOR]=n._matrix[Z.EXTERIOR][Z.EXTERIOR]}}},{key:"matches",value:function(){if(Number.isInteger(arguments[0])&&"string"==typeof arguments[1]){var t=arguments[0],n=arguments[1];return n===Mt.SYM_DONTCARE||n===Mt.SYM_TRUE&&(t>=0||t===Mt.TRUE)||n===Mt.SYM_FALSE&&t===Mt.FALSE||n===Mt.SYM_P&&t===Mt.P||n===Mt.SYM_L&&t===Mt.L||n===Mt.SYM_A&&t===Mt.A}if("string"==typeof arguments[0]&&"string"==typeof arguments[1]){var r=arguments[1];return new e(arguments[0]).matches(r)}}},{key:"isTrue",value:function(t){return t>=0||t===Mt.TRUE}}]),e}(),er=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"size",value:function(){return this._size}},{key:"addAll",value:function(t){return null===t||0===t.length?null:(this.ensureCapacity(this._size+t.length),xt.arraycopy(t,0,this._data,this._size,t.length),void(this._size+=t.length))}},{key:"ensureCapacity",value:function(t){if(t<=this._data.length)return null;var e=Math.max(t,2*this._data.length);this._data=At.copyOf(this._data,e)}},{key:"toArray",value:function(){var t=new Array(this._size).fill(null);return xt.arraycopy(this._data,0,t,0,this._size),t}},{key:"add",value:function(t){this.ensureCapacity(this._size+1),this._data[this._size]=t,++this._size}}],[{key:"constructor_",value:function(){if(this._data=null,this._size=0,0===arguments.length)e.constructor_.call(this,10);else if(1===arguments.length){var t=arguments[0];this._data=new Array(t).fill(null)}}}]),e}(),nr=function(){function e(){t(this,e)}return n(e,[{key:"getChainStartIndices",value:function(t){var e=0,n=new er(Math.trunc(t.length/2));n.add(e);do{var r=this.findChainEnd(t,e);n.add(r),e=r}while(en?e:n}},{key:"getMinX",value:function(t){var e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return ee&&(r=1),this._depth[t][n]=r}}}},{key:"getDelta",value:function(t){return this._depth[t][tt.RIGHT]-this._depth[t][tt.LEFT]}},{key:"getLocation",value:function(t,e){return this._depth[t][e]<=0?Z.EXTERIOR:Z.INTERIOR}},{key:"toString",value:function(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}},{key:"add",value:function(){if(1===arguments.length)for(var t=arguments[0],n=0;n<2;n++)for(var r=1;r<3;r++){var i=t.getLocation(n,r);i!==Z.EXTERIOR&&i!==Z.INTERIOR||(this.isNull(n,r)?this._depth[n][r]=e.depthAtLocation(i):this._depth[n][r]+=e.depthAtLocation(i))}else if(3===arguments.length){var o=arguments[0],s=arguments[1];arguments[2]===Z.INTERIOR&&this._depth[o][s]++}}}],[{key:"constructor_",value:function(){this._depth=Array(2).fill().map((function(){return Array(3)}));for(var t=0;t<2;t++)for(var n=0;n<3;n++)this._depth[t][n]=e.NULL_VALUE}},{key:"depthAtLocation",value:function(t){return t===Z.EXTERIOR?0:t===Z.INTERIOR?1:e.NULL_VALUE}}]),e}();ir.NULL_VALUE=-1;var or=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getDepth",value:function(){return this._depth}},{key:"getCollapsedEdge",value:function(){var t=new Array(2).fill(null);return t[0]=this.pts[0],t[1]=this.pts[1],new s(t,Ae.toLineLabel(this._label))}},{key:"isIsolated",value:function(){return this._isIsolated}},{key:"getCoordinates",value:function(){return this.pts}},{key:"setIsolated",value:function(t){this._isIsolated=t}},{key:"setName",value:function(t){this._name=t}},{key:"equals",value:function(t){if(!(t instanceof s))return!1;var e=t;if(this.pts.length!==e.pts.length)return!1;for(var n=!0,r=!0,i=this.pts.length,o=0;o0?this.pts[0]:null;if(1===arguments.length){var t=arguments[0];return this.pts[t]}}},{key:"print",value:function(t){t.print("edge "+this._name+": "),t.print("LINESTRING (");for(var e=0;e0&&t.print(","),t.print(this.pts[e].x+" "+this.pts[e].y);t.print(") "+this._label+" "+this._depthDelta)}},{key:"computeIM",value:function(t){s.updateIM(this._label,t)}},{key:"isCollapsed",value:function(){return!!this._label.isArea()&&3===this.pts.length&&!!this.pts[0].equals(this.pts[2])}},{key:"isClosed",value:function(){return this.pts[0].equals(this.pts[this.pts.length-1])}},{key:"getMaximumSegmentIndex",value:function(){return this.pts.length-1}},{key:"getDepthDelta",value:function(){return this._depthDelta}},{key:"getNumPoints",value:function(){return this.pts.length}},{key:"printReverse",value:function(t){t.print("edge "+this._name+": ");for(var e=this.pts.length-1;e>=0;e--)t.print(this.pts[e]+" ");t.println("")}},{key:"getMonotoneChainEdge",value:function(){return null===this._mce&&(this._mce=new rr(this)),this._mce}},{key:"getEnvelope",value:function(){if(null===this._env){this._env=new X;for(var t=0;t0&&t.append(","),t.append(this.pts[e].x+" "+this.pts[e].y);return t.append(") "+this._label+" "+this._depthDelta),t.toString()}},{key:"isPointwiseEqual",value:function(t){if(this.pts.length!==t.pts.length)return!1;for(var e=0;er||this._maxyo;if(s)return!1;var a=this.intersectsToleranceSquare(t,e);return V.isTrue(!(s&&a),"Found bad envelope test"),a}},{key:"initCorners",value:function(t){var e=.5;this._minx=t.x-e,this._maxx=t.x+e,this._miny=t.y-e,this._maxy=t.y+e,this._corner[0]=new z(this._maxx,this._maxy),this._corner[1]=new z(this._minx,this._maxy),this._corner[2]=new z(this._minx,this._miny),this._corner[3]=new z(this._maxx,this._miny)}},{key:"intersects",value:function(t,e){return 1===this._scaleFactor?this.intersectsScaled(t,e):(this.copyScaled(t,this._p0Scaled),this.copyScaled(e,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}},{key:"scale",value:function(t){return Math.round(t*this._scaleFactor)}},{key:"getCoordinate",value:function(){return this._originalPt}},{key:"copyScaled",value:function(t,e){e.x=this.scale(t.x),e.y=this.scale(t.y)}},{key:"getSafeEnvelope",value:function(){if(null===this._safeEnv){var t=e.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new X(this._originalPt.x-t,this._originalPt.x+t,this._originalPt.y-t,this._originalPt.y+t)}return this._safeEnv}},{key:"intersectsPixelClosure",value:function(t,e){return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.hasIntersection()))))}},{key:"intersectsToleranceSquare",value:function(t,e){var n=!1,r=!1;return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.isProper()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.isProper()||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.isProper()||(this._li.hasIntersection()&&(r=!0),this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.isProper()||n&&r||t.equals(this._pt)||e.equals(this._pt)))))}},{key:"addSnappedNode",value:function(t,e){var n=t.getCoordinate(e),r=t.getCoordinate(e+1);return!!this.intersects(n,r)&&(t.addIntersection(this.getCoordinate(),e),!0)}}],[{key:"constructor_",value:function(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;var t=arguments[0],e=arguments[1],n=arguments[2];if(this._originalPt=t,this._pt=t,this._scaleFactor=e,this._li=n,e<=0)throw new x("Scale factor must be non-zero");1!==e&&(this._pt=new z(this.scale(t.x),this.scale(t.y)),this._p0Scaled=new z,this._p1Scaled=new z),this.initCorners(this._pt)}}]),e}();lr.SAFE_ENV_EXPANSION_FACTOR=.75;var hr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"select",value:function(){if(1===arguments.length);else if(2===arguments.length){var t=arguments[1];arguments[0].getLineSegment(t,this.selectedSegment),this.select(this.selectedSegment)}}}],[{key:"constructor_",value:function(){this.selectedSegment=new bn}}]),e}(),cr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"snap",value:function(){if(1===arguments.length){var e=arguments[0];return this.snap(e,null,-1)}if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=r.getSafeEnvelope(),a=new fr(r,i,o);return this._index.query(s,new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[hn]}},{key:"visitItem",value:function(t){t.select(s,a)}}]),e}())),a.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var t=arguments[0];this._index=t}}]),e}(),fr=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isNodeAdded",value:function(){return this._isNodeAdded}},{key:"select",value:function(){if(!(2===arguments.length&&Number.isInteger(arguments[1])&&arguments[0]instanceof In))return f(i(s.prototype),"select",this).apply(this,arguments);var t=arguments[1],e=arguments[0].getContext();if(this._parentEdge===e&&(t===this._hotPixelVertexIndex||t+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(e,t)}}],[{key:"constructor_",value:function(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var t=arguments[0],e=arguments[1],n=arguments[2];this._hotPixel=t,this._parentEdge=e,this._hotPixelVertexIndex=n}}]),s}(hr);cr.HotPixelSnapAction=fr;var gr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"processIntersections",value:function(t,e,n,r){if(t===n&&e===r)return null;var i=t.getCoordinates()[e],o=t.getCoordinates()[e+1],s=n.getCoordinates()[r],a=n.getCoordinates()[r+1];if(this._li.computeIntersection(i,o,s,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var u=0;u=0;t--){try{this.bufferReducedPrecision(t)}catch(t){if(!(t instanceof pt))throw t;this._saveException=t}if(null!==this._resultGeometry)return null}throw this._saveException}if(1===arguments.length){var n=arguments[0],r=e.precisionScaleFactor(this._argGeom,this._distance,n),i=new ie(r);this.bufferFixedPrecision(i)}}},{key:"computeGeometry",value:function(){if(this.bufferOriginalPrecision(),null!==this._resultGeometry)return null;var t=this._argGeom.getFactory().getPrecisionModel();t.getType()===ie.FIXED?this.bufferFixedPrecision(t):this.bufferReducedPrecision()}},{key:"setQuadrantSegments",value:function(t){this._bufParams.setQuadrantSegments(t)}},{key:"bufferOriginalPrecision",value:function(){try{var t=new sr(this._bufParams);this._resultGeometry=t.buffer(this._argGeom,this._distance)}catch(t){if(!(t instanceof F))throw t;this._saveException=t}}},{key:"getResultGeometry",value:function(t){return this._distance=t,this.computeGeometry(),this._resultGeometry}},{key:"setEndCapStyle",value:function(t){this._bufParams.setEndCapStyle(t)}}],[{key:"constructor_",value:function(){if(this._argGeom=null,this._distance=null,this._bufParams=new y,this._resultGeometry=null,this._saveException=null,1===arguments.length){var t=arguments[0];this._argGeom=t}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this._argGeom=e,this._bufParams=n}}},{key:"bufferOp",value:function(){if(2===arguments.length){var t=arguments[1];return new e(arguments[0]).getResultGeometry(t)}if(3===arguments.length){if(Number.isInteger(arguments[2])&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var n=arguments[1],r=arguments[2],i=new e(arguments[0]);return i.setQuadrantSegments(r),i.getResultGeometry(n)}if(arguments[2]instanceof y&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var o=arguments[1];return new e(arguments[0],arguments[2]).getResultGeometry(o)}}else if(4===arguments.length){var s=arguments[1],a=arguments[2],u=arguments[3],l=new e(arguments[0]);return l.setQuadrantSegments(a),l.setEndCapStyle(u),l.getResultGeometry(s)}}},{key:"precisionScaleFactor",value:function(t,e,n){var r=t.getEnvelopeInternal(),i=Et.max(Math.abs(r.getMaxX()),Math.abs(r.getMaxY()),Math.abs(r.getMinX()),Math.abs(r.getMinY()))+2*(e>0?e:0),o=n-Math.trunc(Math.log(i)/Math.log(10)+1);return Math.pow(10,o)}}]),e}();vr.CAP_ROUND=y.CAP_ROUND,vr.CAP_BUTT=y.CAP_FLAT,vr.CAP_FLAT=y.CAP_FLAT,vr.CAP_SQUARE=y.CAP_SQUARE,vr.MAX_PRECISION_DIGITS=12;var dr=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],yr=function(){function e(n){t(this,e),this.geometryFactory=n||new ae}return n(e,[{key:"read",value:function(t){var e,n=(e="string"==typeof t?JSON.parse(t):t).type;if(!mr[n])throw new Error("Unknown GeoJSON type: "+e.type);return-1!==dr.indexOf(n)?mr[n].call(this,e.coordinates):"GeometryCollection"===n?mr[n].call(this,e.geometries):mr[n].call(this,e)}},{key:"write",value:function(t){var e=t.getGeometryType();if(!_r[e])throw new Error("Geometry is not supported");return _r[e].call(this,t)}}]),e}(),mr={Feature:function(t){var e={};for(var n in t)e[n]=t[n];if(t.geometry){var r=t.geometry.type;if(!mr[r])throw new Error("Unknown GeoJSON type: "+t.type);e.geometry=this.read(t.geometry)}return t.bbox&&(e.bbox=mr.bbox.call(this,t.bbox)),e},FeatureCollection:function(t){var e={};if(t.features){e.features=[];for(var n=0;n1?0:t<-1?Xn:Math.acos(t)}function ir(t){return t>1?Un:t<-1?-Un:Math.asin(t)}function or(){}function sr(t,e){t&&ur.hasOwnProperty(t.type)&&ur[t.type](t,e)}var ar={Feature:function(t,e){sr(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++rXn?t-Hn:t<-Xn?t+Hn:t,e]}function xr(t){return function(e,n){return[(e+=t)>Xn?e-Hn:e<-Xn?e+Hn:e,n]}}function Er(t){var e=xr(t);return e.invert=xr(-t),e}function kr(t,e){var n=tr(t),r=er(t),i=tr(e),o=er(e);function s(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*n+a*r;return[$n(u*i-h*o,a*n-l*r),ir(h*i+u*o)]}return s.invert=function(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*i-u*o;return[$n(u*i+l*o,a*n+h*r),ir(h*n-a*r)]},s}function br(t,e){(e=fr(e))[0]-=t,yr(e);var n=rr(-e[1]);return((-e[2]<0?-n:n)+Hn-jn)%Hn}function wr(){var t,e=[];return{point:function(e,n){t.push([e,n])},lineStart:function(){e.push(t=[])},lineEnd:or,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function Ir(t,e){return Kn(t[0]-e[0])=0;--o)i.point((h=l[o])[0],h[1]);else r(f.x,f.p.x,-1,i);f=f.p}l=(f=f.o).z,g=!g}while(!f.v);i.lineEnd()}}}function Mr(t){if(e=t.length){for(var e,n,r=0,i=t[0];++re?1:t>=e?0:NaN}function Pr(t){for(var e,n,r,i=t.length,o=-1,s=0;++o=0;)for(e=(r=t[i]).length;--e>=0;)n[--s]=r[e];return n}Gn(),Gn(),Gn(),_r.invert=_r,function(t){var e;1===t.length&&(e=t,t=function(t,n){return Lr(e(t),n)})}(Lr);var Cr=1e9,Tr=-Cr;function Or(t,e,n,r){function i(i,o){return t<=i&&i<=n&&e<=o&&o<=r}function o(i,o,a,l){var h=0,c=0;if(null==i||(h=s(i,a))!==(c=s(o,a))||u(i,o)<0^a>0)do{l.point(0===h||3===h?t:n,h>1?r:e)}while((h=(h+a+4)%4)!==c);else l.point(o[0],o[1])}function s(r,i){return Kn(r[0]-t)0?0:3:Kn(r[0]-n)0?2:1:Kn(r[1]-e)0?1:0:i>0?3:2}function a(t,e){return u(t.x,e.x)}function u(t,e){var n=s(t,1),r=s(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){var u,l,h,c,f,g,p,v,d,y,m,_=s,x=wr(),E={point:k,lineStart:function(){E.point=b,l&&l.push(h=[]);y=!0,d=!1,p=v=NaN},lineEnd:function(){u&&(b(c,f),g&&d&&x.rejoin(),u.push(x.result()));E.point=k,d&&_.lineEnd()},polygonStart:function(){_=x,u=[],l=[],m=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,i=l.length;nr&&(f-o)*(r-s)>(g-s)*(t-o)&&++e:g<=r&&(f-o)*(r-s)<(g-s)*(t-o)&&--e;return e}(),n=m&&e,i=(u=Pr(u)).length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),o(null,null,1,s),s.lineEnd()),i&&Sr(u,a,e,o,s),s.polygonEnd());_=s,u=l=h=null}};function k(t,e){i(t,e)&&_.point(t,e)}function b(o,s){var a=i(o,s);if(l&&h.push([o,s]),y)c=o,f=s,g=a,y=!1,a&&(_.lineStart(),_.point(o,s));else if(a&&d)_.point(o,s);else{var u=[p=Math.max(Tr,Math.min(Cr,p)),v=Math.max(Tr,Math.min(Cr,v))],x=[o=Math.max(Tr,Math.min(Cr,o)),s=Math.max(Tr,Math.min(Cr,s))];!function(t,e,n,r,i,o){var s,a=t[0],u=t[1],l=0,h=1,c=e[0]-a,f=e[1]-u;if(s=n-a,c||!(s>0)){if(s/=c,c<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=i-a,c||!(s<0)){if(s/=c,c<0){if(s>h)return;s>l&&(l=s)}else if(c>0){if(s0)){if(s/=f,f<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=o-u,f||!(s<0)){if(s/=f,f<0){if(s>h)return;s>l&&(l=s)}else if(f>0){if(s0&&(t[0]=a+l*c,t[1]=u+l*f),h<1&&(e[0]=a+h*c,e[1]=u+h*f),!0}}}}}(u,x,t,e,n,r)?a&&(_.lineStart(),_.point(o,s),m=!1):(d||(_.lineStart(),_.point(u[0],u[1])),_.point(x[0],x[1]),a||_.lineEnd(),m=!1)}p=o,v=s,d=a}return E}}var Rr=Gn();function Ar(t){return t}Gn(),Gn(),Gn();var Dr=1/0,Fr=Dr,qr=-Dr,Vr=qr,Gr={point:function(t,e){tqr&&(qr=t);eVr&&(Vr=e)},lineStart:or,lineEnd:or,polygonStart:or,polygonEnd:or,result:function(){var t=[[Dr,Fr],[qr,Vr]];return qr=Vr=-(Fr=Dr=1/0),t}};function Br(t,e,n,r){return function(i,o){var s,a,u,l=e(o),h=i.invert(r[0],r[1]),c=wr(),f=e(c),g=!1,p={point:v,lineStart:y,lineEnd:m,polygonStart:function(){p.point=_,p.lineStart=x,p.lineEnd=E,a=[],s=[]},polygonEnd:function(){p.point=v,p.lineStart=y,p.lineEnd=m,a=Pr(a);var t=function(t,e){var n=e[0],r=e[1],i=[er(n),-tr(n),0],o=0,s=0;Rr.reset();for(var a=0,u=t.length;a=0?1:-1,w=b*k,I=w>Xn,N=p*x;if(Rr.add($n(N*b*er(w),v*E+N*tr(w))),o+=I?k+b*Hn:k,I^f>=n^m>=n){var S=pr(fr(c),fr(y));yr(S);var M=pr(i,S);yr(M);var L=(I^k>=0?-1:1)*ir(M[2]);(r>L||r===L&&(S[0]||S[1]))&&(s+=I^k>=0?1:-1)}}return(o<-jn||o0){for(g||(o.polygonStart(),g=!0),o.lineStart(),t=0;t1&&2&i&&l.push(l.pop().concat(l.shift())),a.push(l.filter(Yr))}return p}}function Yr(t){return t.length>1}function zr(t,e){return((t=t.x)[0]<0?t[1]-Un-jn:Un-t[1])-((e=e.x)[0]<0?e[1]-Un-jn:Un-e[1])}Gn();var jr=Br((function(){return!0}),(function(t){var e,n=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,s){var a=o>0?Xn:-Xn,u=Kn(o-n);Kn(u-Xn)0?Un:-Un),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),e=0):i!==a&&u>=Xn&&(Kn(n-i)jn?Qn((er(e)*(o=tr(r))*er(n)-er(r)*(i=tr(e))*er(t))/(i*o*s)):(e+r)/2}(n,r,o,s),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),e=0),t.point(n=o,r=s),i=a},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var i;if(null==t)i=n*Un,r.point(-Xn,i),r.point(0,i),r.point(Xn,i),r.point(Xn,0),r.point(Xn,-i),r.point(0,-i),r.point(-Xn,-i),r.point(-Xn,0),r.point(-Xn,i);else if(Kn(t[0]-e[0])>jn){var o=t[0]0,i=Kn(n)>jn;function o(t,e){return tr(t)*tr(e)>n}function s(t,e,r){var i=[1,0,0],o=pr(fr(t),fr(e)),s=gr(o,o),a=o[0],u=s-a*a;if(!u)return!r&&t;var l=n*s/u,h=-n*a/u,c=pr(i,o),f=dr(i,l);vr(f,dr(o,h));var g=c,p=gr(f,g),v=gr(g,g),d=p*p-v*(gr(f,f)-1);if(!(d<0)){var y=nr(d),m=dr(g,(-p-y)/v);if(vr(m,f),m=cr(m),!r)return m;var _,x=t[0],E=e[0],k=t[1],b=e[1];E0^m[1]<(Kn(m[0]-x)Xn^(x<=m[0]&&m[0]<=E)){var N=dr(g,(-p+y)/v);return vr(N,f),[m,cr(N)]}}}function a(e,n){var i=r?t:Xn-t,o=0;return e<-i?o|=1:e>i&&(o|=2),n<-i?o|=4:n>i&&(o|=8),o}return Br(o,(function(t){var e,n,u,l,h;return{lineStart:function(){l=u=!1,h=1},point:function(c,f){var g,p=[c,f],v=o(c,f),d=r?v?0:a(c,f):v?a(c+(c<0?Xn:-Xn),f):0;if(!e&&(l=u=v)&&t.lineStart(),v!==u&&(!(g=s(e,p))||Ir(e,g)||Ir(p,g))&&(p[0]+=jn,p[1]+=jn,v=o(p[0],p[1])),v!==u)h=0,v?(t.lineStart(),g=s(p,e),t.point(g[0],g[1])):(g=s(e,p),t.point(g[0],g[1]),t.lineEnd()),e=g;else if(i&&e&&r^v){var y;d&n||!(y=s(p,e,!0))||(h=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1])))}!v||e&&Ir(e,p)||t.point(p[0],p[1]),e=p,u=v,n=d},lineEnd:function(){u&&t.lineEnd(),e=null},clean:function(){return h|(l&&u)<<1}}}),(function(n,r,i,o){!function(t,e,n,r,i,o){if(n){var s=tr(e),a=er(e),u=r*n;null==i?(i=e+r*Hn,o=e-u/2):(i=br(s,i),o=br(s,o),(r>0?io)&&(i+=r*Hn));for(var l,h=i;r>0?h>o:h4*e&&v--){var x=s+f,E=a+g,k=u+p,b=nr(x*x+E*E+k*k),w=ir(k/=b),I=Kn(Kn(k)-1)e||Kn((y*L+m*P)/_-.5)>.3||s*f+a*g+u*p2?t[2]%360*Jn:0,M()):[d*Wn,y*Wn,m*Wn]},I.precision=function(t){return arguments.length?(w=Kr(S,b=t*t),L()):nr(b)},I.fitExtent=function(t,e){return Hr(I,t,e)},I.fitSize=function(t,e){return function(t,e,n){return Hr(t,[[0,0],e],n)}(I,t,e)},function(){return e=t.apply(this,arguments),I.invert=e.invert&&N,M()}}((function(){return t}))()}function ti(t){return function(e,n){var r=tr(e),i=tr(n),o=t(r*i);return[o*i*er(e),o*er(n)]}}function ei(t){return function(e,n){var r=nr(e*e+n*n),i=t(r),o=er(i),s=tr(i);return[$n(e*o,r*s),ir(r&&n*o/r)]}}ti((function(t){return nr(2/(1+t))})).invert=ei((function(t){return 2*ir(t/2)}));var ni=ti((function(t){return(t=rr(t))&&t/er(t)}));function ri(){return $r(ni).scale(79.4188).clipAngle(179.999)}function ii(t,e){return[t,e]}ni.invert=ei((function(t){return t})),ii.invert=ii;var oi=Vn.BufferOp,si=Vn.GeoJSONReader,ai=Vn.GeoJSONWriter;function ui(t,e,n,r){var i=t.properties||{},o="Feature"===t.type?t.geometry:t;if("GeometryCollection"===o.type){var s=[];return mt(t,(function(t){var i=ui(t,e,n,r);i&&s.push(i)})),C(s)}var a=function(t){var e=An(t).geometry.coordinates,n=[-e[0],-e[1]];return ri().rotate(n).scale(x)}(o),u={type:o.type,coordinates:hi(o.coordinates,a)},l=(new si).read(u),h=F(q(e,n),"meters"),c=oi.bufferOp(l,h,r);if(!li((c=(new ai).write(c)).coordinates))return b({type:c.type,coordinates:ci(c.coordinates,a)},i)}function li(t){return Array.isArray(t[0])?li(t[0]):isNaN(t[0])}function hi(t,e){return"object"!==m(t[0])?e(t):t.map((function(t){return hi(t,e)}))}function ci(t,e){return"object"!==m(t[0])?e.invert(t):t.map((function(t){return ci(t,e)}))}function fi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return mt(t,(function(t,o,s){var a=e.weight?null==s?void 0:s[e.weight]:void 0;if(!U(a=null==a?1:a))throw new Error("weight value must be a number for feature index "+o);(a=Number(a))>0&&ct(t,(function(t){n+=t[0]*a,r+=t[1]*a,i+=a}))})),I([n/i,r/i],e.properties,e)}function gi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return ct(t,(function(t){n+=t[0],r+=t[1],i++}),!0),I([n/i,r/i],e.properties)}function pi(t,e,n,r,i){var o=r.tolerance||.001,s=0,a=0,u=0,l=0;if(vt(n,(function(e){var n,r=null==(n=e.properties)?void 0:n.weight,i=null==r?1:r;if(!U(i=Number(i)))throw new Error("weight value must be a number");if(i>0){l+=1;var o=i*ut(e,t);0===o&&(o=1);var h=i/o;s+=e.geometry.coordinates[0]*h,a+=e.geometry.coordinates[1]*h,u+=h}})),l<1)throw new Error("no features to measure");var h=s/u,c=a/u;return 1===l||0===i||Math.abs(h-e[0])0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mi;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function mi(t,e){return te?1:0}var _i,xi,Ei,ki,bi,wi=_n(Object.freeze({__proto__:null,default:yi})),Ii={exports:{}};function Ni(){if(bi)return Ii.exports;bi=1;var t=(xi||(xi=1,_i=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=(r-n)/2,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),_i),e=(ki||(ki=1,Ei=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=r-n,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),Ei);return Ii.exports=function(n,r,i,o){return r.length>0&&Array.isArray(r[0])?e(n,r,i,o):t(n,r,i,o)},Ii.exports.nested=e,Ii.exports.flat=t,Ii.exports}var Si,Mi,Li={exports:{}};Li.exports;function Pi(){return Si||(Si=1,function(t,e){!function(t){var e=134217729,n=33306690738754706e-32;function r(t,e,n,r,i){var o,s,a,u,l=e[0],h=r[0],c=0,f=0;h>l==h>-l?(o=l,l=e[++c]):(o=h,h=r[++f]);var g=0;if(cl==h>-l?(a=o-((s=l+o)-l),l=e[++c]):(a=o-((s=h+o)-h),h=r[++f]),o=s,0!==a&&(i[g++]=a);cl==h>-l?(a=o-((s=o+l)-(u=s-o))+(l-u),l=e[++c]):(a=o-((s=o+h)-(u=s-o))+(h-u),h=r[++f]),o=s,0!==a&&(i[g++]=a);for(;c0!=m>0)return _;var x=Math.abs(y+m);return Math.abs(_)>=o*x?_:-function(t,i,o,g,p,v,d){var y,m,_,x,E,k,b,w,I,N,S,M,L,P,C,T,O,R,A=t-p,D=o-p,F=i-v,q=g-v;E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=q-(I=(k=e*q)-(k-q)))-((P=A*q)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=D-(I=(k=e*D)-(k-D)))-((T=F*D)-b*I-w*I-b*N))),u[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),u[1]=L-(S+E)+(E-T),E=(R=M+S)-M,u[2]=M-(R-E)+(S-E),u[3]=R;var V=function(t,e){for(var n=e[0],r=1;r=G||-V>=G)return V;if(y=t-(A+(E=t-A))+(E-p),_=o-(D+(E=o-D))+(E-p),m=i-(F+(E=i-F))+(E-v),x=g-(q+(E=g-q))+(E-v),0===y&&0===m&&0===_&&0===x)return V;if(G=a*d+n*Math.abs(V),(V+=A*x+q*y-(F*_+D*m))>=G||-V>=G)return V;E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=q-(I=(k=e*q)-(k-q)))-((P=y*q)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=D-(I=(k=e*D)-(k-D)))-((T=m*D)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var B=r(4,u,4,f,l);E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=x-(I=(k=e*x)-(k-x)))-((P=A*x)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=_-(I=(k=e*_)-(k-_)))-((T=F*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var Y=r(B,l,4,f,h);E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=x-(I=(k=e*x)-(k-x)))-((P=y*x)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=_-(I=(k=e*_)-(k-_)))-((T=m*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var z=r(Y,h,4,f,c);return c[z-1]}(t,i,g,p,v,d,x)},t.orient2dfast=function(t,e,n,r,i,o){return(e-o)*(n-i)-(t-i)*(r-o)},Object.defineProperty(t,"__esModule",{value:!0})}(e)}(0,Li.exports)),Li.exports}var Ci=function(){if(Mi)return vi.exports;Mi=1;var t=di,e=wi,n=Ni(),r=Pi().orient2d;function i(e,r,i){r=Math.max(0,void 0===r?2:r),i=i||0;var s=function(t){for(var e=t[0],r=t[0],i=t[0],o=t[0],s=0;si[0]&&(i=a),a[1]o[1]&&(o=a)}var u=[e,r,i,o],l=u.slice();for(s=0;s=2&&h(e[e.length-2],e[e.length-1],t[n])<=0;)e.pop();e.push(t[n])}for(var r=[],i=t.length-1;i>=0;i--){for(;r.length>=2&&h(r[r.length-2],r[r.length-1],t[i])<=0;)r.pop();r.push(t[i])}return r.pop(),e.pop(),e.concat(r)}(l)}(e),a=new t(16);a.toBBox=function(t){return{minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]}},a.compareMinX=function(t,e){return t[0]-e[0]},a.compareMinY=function(t,e){return t[1]-e[1]},a.load(e);for(var u,l=[],p=0;pu||c.push({node:v,dist:d})}for(;c.length&&!c.peek().node.children;){var y=c.pop(),m=y.node,_=p(m,n,r),x=p(m,i,o);if(y.dist<_&&y.dist=e.minX&&t[0]<=e.maxX&&t[1]>=e.minY&&t[1]<=e.maxY}function l(t,e,n){for(var r,i,o,s,a=Math.min(t[0],e[0]),u=Math.min(t[1],e[1]),l=Math.max(t[0],e[0]),c=Math.max(t[1],e[1]),f=n.search({minX:a,minY:u,maxX:l,maxY:c}),g=0;g0!=h(r,i,s)>0&&h(o,s,r)>0!=h(o,s,i)>0)return!1;return!0}function h(t,e,n){return r(t[0],t[1],e[0],e[1],n[0],n[1])}function c(t){var e=t.p,n=t.next.p;return t.minX=Math.min(e[0],n[0]),t.minY=Math.min(e[1],n[1]),t.maxX=Math.max(e[0],n[0]),t.maxY=Math.max(e[1],n[1]),t}function f(t,e){var n={p:t,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return e?(n.next=e.next,n.prev=e,e.next.prev=n,e.next=n):(n.prev=n,n.next=n),n}function g(t,e){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function p(t,e,n){var r=e[0],i=e[1],o=n[0]-r,s=n[1]-i;if(0!==o||0!==s){var a=((t[0]-r)*o+(t[1]-i)*s)/(o*o+s*s);a>1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function v(t,e,n,r,i,o,s,a){var u,l,h,c,f=n-t,g=r-e,p=s-i,v=a-o,d=t-i,y=e-o,m=f*f+g*g,_=f*p+g*v,x=p*p+v*v,E=f*d+g*y,k=p*d+v*y,b=m*x-_*_,w=b,I=b;0===b?(l=0,w=1,c=k,I=x):(c=m*k-_*E,(l=_*k-x*E)<0?(l=0,c=k,I=x):l>w&&(l=w,c=k+_,I=x)),c<0?(c=0,-E<0?l=0:-E>m?l=w:(l=-E,w=m)):c>I&&(c=I,-E+_<0?l=0:-E+_>m?l=w:(l=-E+_,w=m));var N=(1-(h=0===c?0:c/I))*i+h*s-((1-(u=0===l?0:l/w))*t+u*n),S=(1-h)*o+h*a-((1-u)*e+u*r);return N*N+S*S}function d(t,e){return t[0]===e[0]?t[1]-e[1]:t[0]-e[0]}return e.default&&(e=e.default),vi.exports=i,vi.exports.default=i,vi.exports}(),Ti=mn(Ci);function Oi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e.concavity=e.concavity||1/0;var n=[];if(ct(t,(function(t){n.push([t[0],t[1]])})),!n.length)return null;var r=Ti(n,e.concavity);return r.length>3?S([r]):null}function Ri(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.steps||64,i=n.properties?n.properties:!Array.isArray(t)&&"Feature"===t.type&&t.properties?t.properties:{},o=[],s=0;s0;r.length0;){var a=t[Math.floor(Math.random()*o)],u=s?a.join("_"):""+a;n[u]||(n[u]=!0,r.push(a))}if(r.length0,u=t[Math.floor(Math.random()*s)];for(a&&u.join("_"),o.push(u);o.length0,y=[];if(s)u="kmrand"==s?r(t,e):"kmpp"==s?i(t,e):s;else for(var m={};u.lengthc&&(c=t[a].y);var g,p=l-u,v=c-h,d=p>v?p:v,y=.5*(l+u),m=.5*(c+h),_=[new so({__sentinel:!0,x:y-20*d,y:m-d},{__sentinel:!0,x:y,y:m+20*d},{__sentinel:!0,x:y+20*d,y:m-d})],x=[],E=[];a=t.length;for(;a--;){for(E.length=0,g=_.length;g--;)(p=t[a].x-_[g].x)>0&&p*p>_[g].r?(x.push(_[g]),_.splice(g,1)):p*p+(v=t[a].y-_[g].y)*v>_[g].r||(E.push(_[g].a,_[g].b,_[g].b,_[g].c,_[g].c,_[g].a),_.splice(g,1));for(uo(E),g=E.length;g;)n=E[--g],e=E[--g],r=t[a],i=n.x-e.x,o=n.y-e.y,s=2*(i*(r.y-n.y)-o*(r.x-n.x)),Math.abs(s)>f&&_.push(new so(e,n,r))}Array.prototype.push.apply(x,_),a=x.length;for(;a--;)(x[a].a.__sentinel||x[a].b.__sentinel||x[a].c.__sentinel)&&x.splice(a,1);return x}(t.features.map((function(t){var r={x:t.geometry.coordinates[0],y:t.geometry.coordinates[1]};return e?r.z=t.properties[e]:3===t.geometry.coordinates.length&&(n=!0,r.z=t.geometry.coordinates[2]),r}))).map((function(t){var e=[t.a.x,t.a.y],r=[t.b.x,t.b.y],i=[t.c.x,t.c.y],o={};return n?(e.push(t.a.z),r.push(t.b.z),i.push(t.c.z)):o={a:t.a.z,b:t.b.z,c:t.c.z},S([[e,r,i,e]],o)})))}var so=s((function t(e,n,r){i(this,t),this.a=e,this.b=n,this.c=r;var o,s,a=n.x-e.x,u=n.y-e.y,l=r.x-e.x,h=r.y-e.y,c=a*(e.x+n.x)+u*(e.y+n.y),f=l*(e.x+r.x)+h*(e.y+r.y),g=2*(a*(r.y-n.y)-u*(r.x-n.x));this.x=(h*c-u*f)/g,this.y=(a*f-l*c)/g,o=this.x-e.x,s=this.y-e.y,this.r=o*o+s*s}));function ao(t,e){return e.x-t.x}function uo(t){var e,n,r,i,o,s=t.length;t:for(;s;)for(n=t[--s],e=t[--s],r=s;r;)if(o=t[--r],e===(i=t[--r])&&n===o||e===o&&n===i){t.splice(s,2),t.splice(r,2),s-=2;continue t}}function lo(t){return t}function ho(t,e){var n=function(t){if(null==t)return lo;var e,n,r=t.scale[0],i=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,a){a||(e=n=0);var u=2,l=t.length,h=new Array(l);for(h[0]=(e+=t[0])*r+o,h[1]=(n+=t[1])*i+s;u1)for(var o,a,u=1,l=s(i[0]);ul&&(a=i[0],i[0]=i[u],i[u]=a,l=o);return i})).filter((function(t){return t.length>0}))}}var po=Object.prototype.hasOwnProperty;function vo(t,e,n,r,i,o){3===arguments.length&&(r=o=Array,i=null);for(var s=new r(t=1<=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},maybeSet:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},get:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)break;h=s[l=l+1&u]}return o},keys:function(){for(var t=[],e=0,n=s.length;e>7^xo[2]^xo[3])}function ko(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=function(){for(var t=vo(1.4*o.length,E,k,Int32Array,-1,Int32Array),e=new Int32Array(o.length),n=0,r=o.length;n=0){var o=c[n];i===e&&o===r||i===r&&o===e||(++g,f[n]=1)}else h[n]=e,c[n]=r}}function E(t){return Eo(o[t])}function k(t,e){return yo(o[t],o[e])}l=h=c=null;var b,w=function(t,e,n,r,i){3===arguments.length&&(r=Array,i=null);for(var o=new r(t=1<=t)throw new Error("full hashset");u=o[a=a+1&s]}return o[a]=r,!0},has:function(r){for(var a=e(r)&s,u=o[a],l=0;u!=i;){if(n(u,r))return!0;if(++l>=t)break;u=o[a=a+1&s]}return!1},values:function(){for(var t=[],e=0,n=o.length;e>1);er&&(r=o),si&&(i=s)}function u(t){t.forEach(a)}function l(t){t.forEach(u)}for(var h in t)o(t[h]);return r>=e&&i>=n?[e,n,r,i]:void 0}(t=Io(t)),r=function(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=s.length+a.length;for(delete t.lines,delete t.rings,r=0,i=s.length;r1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=[],i=It(t,(function(t,e){var n=function(t,e){var n,r=t.geometry.coordinates,i=e.geometry.coordinates,o=Oo(r[0]),s=Oo(r[r.length-1]),a=Oo(i[0]),u=Oo(i[i.length-1]);if(o===u)n=i.concat(r.slice(1));else if(a===s)n=r.concat(i.slice(1));else if(o===a)n=r.slice(1).reverse().concat(i);else{if(s!==u)return null;n=r.concat(i.reverse().slice(1))}return L(n)}(t,e);return n||(r.push(t),e)}));return i&&r.push(i),r.length?1===r.length?r[0]:T(r.map((function(t){return t.coordinates}))):null}function Oo(t){return t[0].toString()+","+t[1].toString()}function Ro(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=function(t){var e={};xt(t,(function(t){e[t.geometry.type]=!0}));var n=Object.keys(e);if(1===n.length)return n[0];return null}(t);if(!r)throw new Error("geojson must be homogenous");var i=t;switch(r){case"LineString":return To(i,e);case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==e.mutate&&void 0!==e.mutate||(t=Ai(t));var n=[];xt(t,(function(t){n.push(t.geometry)}));var r=Lo({geoms:A(n).geometry});return fo(r,r.objects.geoms.geometries)}(i,e);default:throw new Error(r+" is not supported")}}var Ao=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Do=Math.ceil,Fo=Math.floor,qo="[BigNumber Error] ",Vo=qo+"Number primitive has more than 15 significant digits: ",Go=1e14,Bo=14,Yo=9007199254740991,zo=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Xo=1e9;function Uo(t){var e=0|t;return t>0||t===e?e:e-1}function Zo(t){for(var e,n,r=1,i=t.length,o=t[0]+"";rl^n?1:-1;for(a=(u=i.length)<(l=o.length)?u:l,s=0;so[s]^n?1:-1;return u==l?0:u>l^n?1:-1}function Wo(t,e,n,r){if(tn||t!==Fo(t))throw Error(qo+(r||"Argument")+("number"==typeof t?tn?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Jo(t){var e=t.c.length-1;return Uo(t.e/Bo)==e&&t.c[e]%2!=0}function Ko(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Qo(t,e,n){var r,i;if(e<0){for(i=n+".";++e;i+=n);t=i+t}else if(++e>(r=t.length)){for(i=n,e-=r;--e;i+=n);t+=i}else ex?f.c=f.e=null:t.e<_?f.c=[f.e=0]:(f.e=t.e,f.c=t.c.slice()));if((l="number"==typeof t)&&0*t==0){if(f.s=1/t<0?(t=-t,-1):1,t===~~t){for(a=0,u=t;u>=10;u/=10,a++);return void(a>x?f.c=f.e=null:(f.e=a,f.c=[t]))}c=String(t)}else{if(!Ao.test(c=String(t)))return i(f,c,l);f.s=45==c.charCodeAt(0)?(c=c.slice(1),-1):1}(a=c.indexOf("."))>-1&&(c=c.replace(".","")),(u=c.search(/e/i))>0?(a<0&&(a=u),a+=+c.slice(u+1),c=c.substring(0,u)):a<0&&(a=c.length)}else{if(Wo(e,2,I.length,"Base"),10==e&&N)return C(f=new S(t),p+f.e+1,v);if(c=String(t),l="number"==typeof t){if(0*t!=0)return i(f,c,l,e);if(f.s=1/t<0?(c=c.slice(1),-1):1,S.DEBUG&&c.replace(/^0\.0*|\./,"").length>15)throw Error(Vo+t)}else f.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1;for(n=I.slice(0,e),a=u=0,h=c.length;ua){a=h;continue}}else if(!s&&(c==c.toUpperCase()&&(c=c.toLowerCase())||c==c.toLowerCase()&&(c=c.toUpperCase()))){s=!0,u=-1,a=0;continue}return i(f,String(t),l,e)}l=!1,(a=(c=r(c,e,10,f.s)).indexOf("."))>-1?c=c.replace(".",""):a=c.length}for(u=0;48===c.charCodeAt(u);u++);for(h=c.length;48===c.charCodeAt(--h););if(c=c.slice(u,++h)){if(h-=u,l&&S.DEBUG&&h>15&&(t>Yo||t!==Fo(t)))throw Error(Vo+f.s*t);if((a=a-u-1)>x)f.c=f.e=null;else if(a<_)f.c=[f.e=0];else{if(f.e=a,f.c=[],u=(a+1)%Bo,a<0&&(u+=Bo),u=y)?Ko(u,s):Qo(u,s,"0");else if(o=(t=C(new S(t),e,n)).e,a=(u=Zo(t.c)).length,1==r||2==r&&(e<=o||o<=d)){for(;aa){if(--e>0)for(u+=".";e--;u+="0");}else if((e+=o-a)>0)for(o+1==a&&(u+=".");e--;u+="0");return t.s<0&&i?"-"+u:u}function L(t,e){for(var n,r,i=1,o=new S(t[0]);i=10;i/=10,r++);return(n=r+n*Bo-1)>x?t.c=t.e=null:n<_?t.c=[t.e=0]:(t.e=n,t.c=e),t}function C(t,e,n,r){var i,o,s,a,u,l,h,c=t.c,f=zo;if(c){t:{for(i=1,a=c[0];a>=10;a/=10,i++);if((o=e-i)<0)o+=Bo,s=e,u=c[l=0],h=Fo(u/f[i-s-1]%10);else if((l=Do((o+1)/Bo))>=c.length){if(!r)break t;for(;c.length<=l;c.push(0));u=h=0,i=1,s=(o%=Bo)-Bo+1}else{for(u=a=c[l],i=1;a>=10;a/=10,i++);h=(s=(o%=Bo)-Bo+i)<0?0:Fo(u/f[i-s-1]%10)}if(r=r||e<0||null!=c[l+1]||(s<0?u:u%f[i-s-1]),r=n<4?(h||r)&&(0==n||n==(t.s<0?3:2)):h>5||5==h&&(4==n||r||6==n&&(o>0?s>0?u/f[i-s]:0:c[l-1])%10&1||n==(t.s<0?8:7)),e<1||!c[0])return c.length=0,r?(e-=t.e+1,c[0]=f[(Bo-e%Bo)%Bo],t.e=-e||0):c[0]=t.e=0,t;if(0==o?(c.length=l,a=1,l--):(c.length=l+1,a=f[Bo-o],c[l]=s>0?Fo(u/f[i-s]%f[s])*a:0),r)for(;;){if(0==l){for(o=1,s=c[0];s>=10;s/=10,o++);for(s=c[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(t.e++,c[0]==Go&&(c[0]=1));break}if(c[l]+=a,c[l]!=Go)break;c[l--]=0,a=1}for(o=c.length;0===c[--o];c.pop());}t.e>x?t.c=t.e=null:t.e<_&&(t.c=[t.e=0])}return t}function T(t){var e,n=t.e;return null===n?t.toString():(e=Zo(t.c),e=n<=d||n>=y?Ko(e,n):Qo(e,n,"0"),t.s<0?"-"+e:e)}return S.clone=t,S.ROUND_UP=0,S.ROUND_DOWN=1,S.ROUND_CEIL=2,S.ROUND_FLOOR=3,S.ROUND_HALF_UP=4,S.ROUND_HALF_DOWN=5,S.ROUND_HALF_EVEN=6,S.ROUND_HALF_CEIL=7,S.ROUND_HALF_FLOOR=8,S.EUCLID=9,S.config=S.set=function(t){var e,n;if(null!=t){if("object"!=m(t))throw Error(qo+"Object expected: "+t);if(t.hasOwnProperty(e="DECIMAL_PLACES")&&(Wo(n=t[e],0,Xo,e),p=n),t.hasOwnProperty(e="ROUNDING_MODE")&&(Wo(n=t[e],0,8,e),v=n),t.hasOwnProperty(e="EXPONENTIAL_AT")&&((n=t[e])&&n.pop?(Wo(n[0],-Xo,0,e),Wo(n[1],0,Xo,e),d=n[0],y=n[1]):(Wo(n,-Xo,Xo,e),d=-(y=n<0?-n:n))),t.hasOwnProperty(e="RANGE"))if((n=t[e])&&n.pop)Wo(n[0],-Xo,-1,e),Wo(n[1],1,Xo,e),_=n[0],x=n[1];else{if(Wo(n,-Xo,Xo,e),!n)throw Error(qo+e+" cannot be zero: "+n);_=-(x=n<0?-n:n)}if(t.hasOwnProperty(e="CRYPTO")){if((n=t[e])!==!!n)throw Error(qo+e+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw E=!n,Error(qo+"crypto unavailable");E=n}else E=n}if(t.hasOwnProperty(e="MODULO_MODE")&&(Wo(n=t[e],0,9,e),k=n),t.hasOwnProperty(e="POW_PRECISION")&&(Wo(n=t[e],0,Xo,e),b=n),t.hasOwnProperty(e="FORMAT")){if("object"!=m(n=t[e]))throw Error(qo+e+" not an object: "+n);w=n}if(t.hasOwnProperty(e="ALPHABET")){if("string"!=typeof(n=t[e])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(qo+e+" invalid: "+n);N="0123456789"==n.slice(0,10),I=n}}return{DECIMAL_PLACES:p,ROUNDING_MODE:v,EXPONENTIAL_AT:[d,y],RANGE:[_,x],CRYPTO:E,MODULO_MODE:k,POW_PRECISION:b,FORMAT:w,ALPHABET:I}},S.isBigNumber=function(t){if(!t||!0!==t._isBigNumber)return!1;if(!S.DEBUG)return!0;var e,n,r=t.c,i=t.e,o=t.s;t:if("[object Array]"=={}.toString.call(r)){if((1===o||-1===o)&&i>=-Xo&&i<=Xo&&i===Fo(i)){if(0===r[0]){if(0===i&&1===r.length)return!0;break t}if((e=(i+1)%Bo)<1&&(e+=Bo),String(r[0]).length==e){for(e=0;e=Go||n!==Fo(n))break t;if(0!==n)return!0}}}else if(null===r&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(qo+"Invalid BigNumber: "+t)},S.maximum=S.max=function(){return L(arguments,-1)},S.minimum=S.min=function(){return L(arguments,1)},S.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Fo(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(t){var e,n,r,i,o,a=0,u=[],l=new S(g);if(null==t?t=p:Wo(t,0,Xo),i=Do(t/Bo),E)if(crypto.getRandomValues){for(e=crypto.getRandomValues(new Uint32Array(i*=2));a>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),e[a]=n[0],e[a+1]=n[1]):(u.push(o%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw E=!1,Error(qo+"crypto unavailable");for(e=crypto.randomBytes(i*=7);a=9e15?crypto.randomBytes(7).copy(e,a):(u.push(o%1e14),a+=7);a=i/7}if(!E)for(;a=10;o/=10,a++);an-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(r,i,o,s,a){var u,l,h,c,f,g,d,y,m=r.indexOf("."),_=p,x=v;for(m>=0&&(c=b,b=0,r=r.replace(".",""),g=(y=new S(i)).pow(r.length-m),b=c,y.c=e(Qo(Zo(g.c),g.e,"0"),10,o,t),y.e=y.c.length),h=c=(d=e(r,i,o,a?(u=I,t):(u=t,I))).length;0==d[--c];d.pop());if(!d[0])return u.charAt(0);if(m<0?--h:(g.c=d,g.e=h,g.s=s,d=(g=n(g,y,_,x,o)).c,f=g.r,h=g.e),m=d[l=h+_+1],c=o/2,f=f||l<0||null!=d[l+1],f=x<4?(null!=m||f)&&(0==x||x==(g.s<0?3:2)):m>c||m==c&&(4==x||f||6==x&&1&d[l-1]||x==(g.s<0?8:7)),l<1||!d[0])r=f?Qo(u.charAt(1),-_,u.charAt(0)):u.charAt(0);else{if(d.length=l,f)for(--o;++d[--l]>o;)d[l]=0,l||(++h,d=[1].concat(d));for(c=d.length;!d[--c];);for(m=0,r="";m<=c;r+=u.charAt(d[m++]));r=Qo(r,h,u.charAt(0))}return r}}(),n=function(){function t(t,e,n){var r,i,o,s,a=0,u=t.length,l=e%jo,h=e/jo|0;for(t=t.slice();u--;)a=((i=l*(o=t[u]%jo)+(r=h*o+(s=t[u]/jo|0)*l)%jo*jo+a)/n|0)+(r/jo|0)+h*s,t[u]=i%n;return a&&(t=[a].concat(t)),t}function e(t,e,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;ie[i]?1:-1;break}return o}function n(t,e,n,r){for(var i=0;n--;)t[n]-=i,i=t[n]1;t.splice(0,1));}return function(r,i,o,s,a){var u,l,h,c,f,g,p,v,d,y,m,_,x,E,k,b,w,I=r.s==i.s?1:-1,N=r.c,M=i.c;if(!(N&&N[0]&&M&&M[0]))return new S(r.s&&i.s&&(N?!M||N[0]!=M[0]:M)?N&&0==N[0]||!M?0*I:I/0:NaN);for(d=(v=new S(I)).c=[],I=o+(l=r.e-i.e)+1,a||(a=Go,l=Uo(r.e/Bo)-Uo(i.e/Bo),I=I/Bo|0),h=0;M[h]==(N[h]||0);h++);if(M[h]>(N[h]||0)&&l--,I<0)d.push(1),c=!0;else{for(E=N.length,b=M.length,h=0,I+=2,(f=Fo(a/(M[0]+1)))>1&&(M=t(M,f,a),N=t(N,f,a),b=M.length,E=N.length),x=b,m=(y=N.slice(0,b)).length;m=a/2&&k++;do{if(f=0,(u=e(M,y,b,m))<0){if(_=y[0],b!=m&&(_=_*a+(y[1]||0)),(f=Fo(_/k))>1)for(f>=a&&(f=a-1),p=(g=t(M,f,a)).length,m=y.length;1==e(g,y,p,m);)f--,n(g,b=10;I/=10,h++);C(v,o+(v.e=h+l*Bo-1)+1,s,c)}else v.e=l,v.r=+c;return v}}(),a=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,l=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,c=/^\s*\+(?=[\w.])|^\s+|\s+$/g,i=function(t,e,n,r){var i,o=n?e:e.replace(c,"");if(h.test(o))t.s=isNaN(o)?null:o<0?-1:1;else{if(!n&&(o=o.replace(a,(function(t,e,n){return i="x"==(n=n.toLowerCase())?16:"b"==n?2:8,r&&r!=i?t:e})),r&&(i=r,o=o.replace(u,"$1").replace(l,"0.$1")),e!=o))return new S(o,i);if(S.DEBUG)throw Error(qo+"Not a"+(r?" base "+r:"")+" number: "+e);t.s=null}t.c=t.e=null},f.absoluteValue=f.abs=function(){var t=new S(this);return t.s<0&&(t.s=1),t},f.comparedTo=function(t,e){return Ho(this,new S(t,e))},f.decimalPlaces=f.dp=function(t,e){var n,r,i,o=this;if(null!=t)return Wo(t,0,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t+o.e+1,e);if(!(n=o.c))return null;if(r=((i=n.length-1)-Uo(this.e/Bo))*Bo,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},f.dividedBy=f.div=function(t,e){return n(this,new S(t,e),p,v)},f.dividedToIntegerBy=f.idiv=function(t,e){return n(this,new S(t,e),0,1)},f.exponentiatedBy=f.pow=function(t,e){var n,r,i,o,s,a,u,l,h=this;if((t=new S(t)).c&&!t.isInteger())throw Error(qo+"Exponent not an integer: "+T(t));if(null!=e&&(e=new S(e)),s=t.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!t.c||!t.c[0])return l=new S(Math.pow(+T(h),s?t.s*(2-Jo(t)):+T(t))),e?l.mod(e):l;if(a=t.s<0,e){if(e.c?!e.c[0]:!e.s)return new S(NaN);(r=!a&&h.isInteger()&&e.isInteger())&&(h=h.mod(e))}else{if(t.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return o=h.s<0&&Jo(t)?-0:0,h.e>-1&&(o=1/o),new S(a?1/o:o);b&&(o=Do(b/Bo+2))}for(s?(n=new S(.5),a&&(t.s=1),u=Jo(t)):u=(i=Math.abs(+T(t)))%2,l=new S(g);;){if(u){if(!(l=l.times(h)).c)break;o?l.c.length>o&&(l.c.length=o):r&&(l=l.mod(e))}if(i){if(0===(i=Fo(i/2)))break;u=i%2}else if(C(t=t.times(n),t.e+1,1),t.e>14)u=Jo(t);else{if(0===(i=+T(t)))break;u=i%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):r&&(h=h.mod(e))}return r?l:(a&&(l=g.div(l)),e?l.mod(e):o?C(l,b,v,undefined):l)},f.integerValue=function(t){var e=new S(this);return null==t?t=v:Wo(t,0,8),C(e,e.e+1,t)},f.isEqualTo=f.eq=function(t,e){return 0===Ho(this,new S(t,e))},f.isFinite=function(){return!!this.c},f.isGreaterThan=f.gt=function(t,e){return Ho(this,new S(t,e))>0},f.isGreaterThanOrEqualTo=f.gte=function(t,e){return 1===(e=Ho(this,new S(t,e)))||0===e},f.isInteger=function(){return!!this.c&&Uo(this.e/Bo)>this.c.length-2},f.isLessThan=f.lt=function(t,e){return Ho(this,new S(t,e))<0},f.isLessThanOrEqualTo=f.lte=function(t,e){return-1===(e=Ho(this,new S(t,e)))||0===e},f.isNaN=function(){return!this.s},f.isNegative=function(){return this.s<0},f.isPositive=function(){return this.s>0},f.isZero=function(){return!!this.c&&0==this.c[0]},f.minus=function(t,e){var n,r,i,o,s=this,a=s.s;if(e=(t=new S(t,e)).s,!a||!e)return new S(NaN);if(a!=e)return t.s=-e,s.plus(t);var u=s.e/Bo,l=t.e/Bo,h=s.c,c=t.c;if(!u||!l){if(!h||!c)return h?(t.s=-e,t):new S(c?s:NaN);if(!h[0]||!c[0])return c[0]?(t.s=-e,t):new S(h[0]?s:3==v?-0:0)}if(u=Uo(u),l=Uo(l),h=h.slice(),a=u-l){for((o=a<0)?(a=-a,i=h):(l=u,i=c),i.reverse(),e=a;e--;i.push(0));i.reverse()}else for(r=(o=(a=h.length)<(e=c.length))?a:e,a=e=0;e0)for(;e--;h[n++]=0);for(e=Go-1;r>a;){if(h[--r]=0;){for(n=0,f=_[i]%d,g=_[i]/d|0,o=i+(s=u);o>i;)n=((l=f*(l=m[--s]%d)+(a=g*l+(h=m[s]/d|0)*f)%d*d+p[o]+n)/v|0)+(a/d|0)+g*h,p[o--]=l%v;p[o]=n}return n?++r:p.splice(0,1),P(t,p,r)},f.negated=function(){var t=new S(this);return t.s=-t.s||null,t},f.plus=function(t,e){var n,r=this,i=r.s;if(e=(t=new S(t,e)).s,!i||!e)return new S(NaN);if(i!=e)return t.s=-e,r.minus(t);var o=r.e/Bo,s=t.e/Bo,a=r.c,u=t.c;if(!o||!s){if(!a||!u)return new S(i/0);if(!a[0]||!u[0])return u[0]?t:new S(a[0]?r:0*i)}if(o=Uo(o),s=Uo(s),a=a.slice(),i=o-s){for(i>0?(s=o,n=u):(i=-i,n=a),n.reverse();i--;n.push(0));n.reverse()}for((i=a.length)-(e=u.length)<0&&(n=u,u=a,a=n,e=i),i=0;e;)i=(a[--e]=a[e]+u[e]+i)/Go|0,a[e]=Go===a[e]?0:a[e]%Go;return i&&(a=[i].concat(a),++s),P(t,a,s)},f.precision=f.sd=function(t,e){var n,r,i,o=this;if(null!=t&&t!==!!t)return Wo(t,1,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t,e);if(!(n=o.c))return null;if(r=(i=n.length-1)*Bo+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return t&&o.e+1>r&&(r=o.e+1),r},f.shiftedBy=function(t){return Wo(t,-9007199254740991,Yo),this.times("1e"+t)},f.squareRoot=f.sqrt=function(){var t,e,r,i,o,s=this,a=s.c,u=s.s,l=s.e,h=p+4,c=new S("0.5");if(1!==u||!a||!a[0])return new S(!u||u<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(u=Math.sqrt(+T(s)))||u==1/0?(((e=Zo(a)).length+l)%2==0&&(e+="0"),u=Math.sqrt(+e),l=Uo((l+1)/2)-(l<0||l%2),r=new S(e=u==1/0?"5e"+l:(e=u.toExponential()).slice(0,e.indexOf("e")+1)+l)):r=new S(u+""),r.c[0])for((u=(l=r.e)+h)<3&&(u=0);;)if(o=r,r=c.times(o.plus(n(s,o,h,1))),Zo(o.c).slice(0,u)===(e=Zo(r.c)).slice(0,u)){if(r.e0&&p>0){for(o=p%a||a,h=g.substr(0,o);o0&&(h+=l+g.slice(o)),f&&(h="-"+h)}r=c?h+(n.decimalSeparator||"")+((u=+n.fractionGroupSize)?c.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):c):h}return(n.prefix||"")+r+(n.suffix||"")},f.toFraction=function(t){var e,r,i,o,s,a,u,l,h,c,f,p,d=this,y=d.c;if(null!=t&&(!(u=new S(t)).isInteger()&&(u.c||1!==u.s)||u.lt(g)))throw Error(qo+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+T(u));if(!y)return new S(d);for(e=new S(g),h=r=new S(g),i=l=new S(g),p=Zo(y),s=e.e=p.length-d.e-1,e.c[0]=zo[(a=s%Bo)<0?Bo+a:a],t=!t||u.comparedTo(e)>0?s>0?e:h:u,a=x,x=1/0,u=new S(p),l.c[0]=0;c=n(u,e,0,1),1!=(o=r.plus(c.times(i))).comparedTo(t);)r=i,i=o,h=l.plus(c.times(o=h)),l=o,e=u.minus(c.times(o=e)),u=o;return o=n(t.minus(r),i,0,1),l=l.plus(o.times(h)),r=r.plus(o.times(i)),l.s=h.s=d.s,f=n(h,i,s*=2,v).minus(d).abs().comparedTo(n(l,r,s,v).minus(d).abs())<1?[h,i]:[l,r],x=a,f},f.toNumber=function(){return+T(this)},f.toPrecision=function(t,e){return null!=t&&Wo(t,1,Xo),M(this,t,e,2)},f.toString=function(t){var e,n=this,i=n.s,o=n.e;return null===o?i?(e="Infinity",i<0&&(e="-"+e)):e="NaN":(null==t?e=o<=d||o>=y?Ko(Zo(n.c),o):Qo(Zo(n.c),o,"0"):10===t&&N?e=Qo(Zo((n=C(new S(n),p+o+1,v)).c),n.e,"0"):(Wo(t,2,I.length,"Base"),e=r(Qo(Zo(n.c),o,"0"),10,t,i,!0)),i<0&&n.c[0]&&(e="-"+e)),e},f.valueOf=f.toJSON=function(){return T(this)},f._isBigNumber=!0,f[Symbol.toStringTag]="BigNumber",f[Symbol.for("nodejs.util.inspect.custom")]=f.valueOf,null!=e&&S.set(e),S}(),ts=function(t){function e(t){return i(this,e),r(this,e,[t])}return h(e,t),s(e)}(s((function t(e){i(this,t),u(this,"key",void 0),u(this,"left",null),u(this,"right",null),this.key=e}))),es=function(){return s((function t(){i(this,t),u(this,"size",0),u(this,"modificationCount",0),u(this,"splayCount",0)}),[{key:"splay",value:function(t){var e=this.root;if(null==e)return this.compare(t,t),-1;for(var n,r=null,i=null,o=null,s=null,a=e,u=this.compare;;)if((n=u(a.key,t))>0){var l=a.left;if(null==l)break;if((n=u(l.key,t))>0&&(a.left=l.right,l.right=a,null==(l=(a=l).left)))break;null==r?i=a:r.left=a,r=a,a=l}else{if(!(n<0))break;var h=a.right;if(null==h)break;if((n=u(h.key,t))<0&&(a.right=h.left,h.left=a,null==(h=(a=h).right)))break;null==o?s=a:o.right=a,o=a,a=h}return null!=o&&(o.right=a.left,a.left=s),null!=r&&(r.left=a.right,a.right=i),this.root!==a&&(this.root=a,this.splayCount++),n}},{key:"splayMin",value:function(t){for(var e=t,n=e.left;null!=n;){var r=n;e.left=r.right,r.right=e,n=(e=r).left}return e}},{key:"splayMax",value:function(t){for(var e=t,n=e.right;null!=n;){var r=n;e.right=r.left,r.left=e,n=(e=r).right}return e}},{key:"_delete",value:function(t){if(null==this.root)return null;if(0!=this.splay(t))return null;var e=this.root,n=e,r=e.left;if(this.size--,null==r)this.root=e.right;else{var i=e.right;(e=this.splayMax(r)).right=i,this.root=e}return this.modificationCount++,n}},{key:"addNewRoot",value:function(t,e){this.size++,this.modificationCount++;var n=this.root;null!=n?(e<0?(t.left=n,t.right=n.right,n.right=null):(t.right=n,t.left=n.left,n.left=null),this.root=t):this.root=t}},{key:"_first",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMin(t),this.root)}},{key:"_last",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMax(t),this.root)}},{key:"clear",value:function(){this.root=null,this.size=0,this.modificationCount++}},{key:"has",value:function(t){return this.validKey(t)&&0==this.splay(t)}},{key:"defaultCompare",value:function(){return function(t,e){return te?1:0}}},{key:"wrap",value:function(){var t=this;return{getRoot:function(){return t.root},setRoot:function(e){t.root=e},getSize:function(){return t.size},getModificationCount:function(){return t.modificationCount},getSplayCount:function(){return t.splayCount},setSplayCount:function(e){t.splayCount=e},splay:function(e){return t.splay(e)},has:function(e){return t.has(e)}}}}])}(),ns=function(t){function e(t,n){var o;return i(this,e),u(o=r(this,e),"root",null),u(o,"compare",void 0),u(o,"validKey",void 0),u(o,Symbol.toStringTag,"[object Set]"),o.compare=null!=t?t:o.defaultCompare(),o.validKey=null!=n?n:function(t){return null!=t&&null!=t},o}return h(e,t),s(e,[{key:"delete",value:function(t){return!!this.validKey(t)&&null!=this._delete(t)}},{key:"deleteAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.delete(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"forEach",value:function(t){for(var e,n=this[Symbol.iterator]();!(e=n.next()).done;)t(e.value,e.value,this)}},{key:"add",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this}},{key:"addAndReturn",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this.root.key}},{key:"addAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.add(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"isEmpty",value:function(){return null==this.root}},{key:"isNotEmpty",value:function(){return null!=this.root}},{key:"single",value:function(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}},{key:"first",value:function(){if(0==this.size)throw"Bad state: No element";return this._first().key}},{key:"last",value:function(){if(0==this.size)throw"Bad state: No element";return this._last().key}},{key:"lastBefore",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)<0)return this.root.key;var e=this.root.left;if(null==e)return null;for(var n=e.right;null!=n;)n=(e=n).right;return e.key}},{key:"firstAfter",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)>0)return this.root.key;var e=this.root.right;if(null==e)return null;for(var n=e.left;null!=n;)n=(e=n).left;return e.key}},{key:"retainAll",value:function(t){var n,r=new e(this.compare,this.validKey),i=this.modificationCount,o=a(t);try{for(o.s();!(n=o.n()).done;){var s=n.value;if(i!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(s)&&0==this.splay(s)&&r.add(this.root.key)}}catch(t){o.e(t)}finally{o.f()}r.size!=this.size&&(this.root=r.root,this.size=r.size,this.modificationCount++)}},{key:"lookup",value:function(t){return this.validKey(t)?0!=this.splay(t)?null:this.root.key:null}},{key:"intersection",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)&&r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"difference",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)||r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"union",value:function(t){var e=this.clone();return e.addAll(t),e}},{key:"clone",value:function(){var t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}},{key:"copyNode",value:function(t){if(null==t)return null;var e=new ts(t.key);return function t(e,n){var r,i;do{if(r=e.left,i=e.right,null!=r){var o=new ts(r.key);n.left=o,t(r,o)}if(null!=i){var s=new ts(i.key);n.right=s,e=i,n=s}}while(null!=i)}(t,e),e}},{key:"toSet",value:function(){return this.clone()}},{key:"entries",value:function(){return new os(this.wrap())}},{key:"keys",value:function(){return this[Symbol.iterator]()}},{key:"values",value:function(){return this[Symbol.iterator]()}},{key:Symbol.iterator,value:function(){return new is(this.wrap())}}])}(es),rs=function(){return s((function t(e){i(this,t),u(this,"tree",void 0),u(this,"path",new Array),u(this,"modificationCount",null),u(this,"splayCount",void 0),this.tree=e,this.splayCount=e.getSplayCount()}),[{key:Symbol.iterator,value:function(){return this}},{key:"next",value:function(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}},{key:"current",value:function(){if(!this.path.length)return null;var t=this.path[this.path.length-1];return this.getValue(t)}},{key:"rebuildPath",value:function(t){this.path.splice(0,this.path.length),this.tree.splay(t),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}},{key:"findLeftMostDescendent",value:function(t){for(;null!=t;)this.path.push(t),t=t.left}},{key:"moveNext",value:function(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();for(var t=this.tree.getRoot();null!=t;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);var e=this.path[this.path.length-1],n=e.right;if(null!=n){for(;null!=n;)this.path.push(n),n=n.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}}])}(),is=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return t.key}}])}(rs),os=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return[t.key,t.key]}}])}(rs),ss=function(t){return function(){return t}},as=function(t){var e=t?function(e,n){return n.minus(e).abs().isLessThanOrEqualTo(t)}:ss(!1);return function(t,n){return e(t,n)?0:t.comparedTo(n)}};function us(t){var e=t?function(e,n,r,i,o){return e.exponentiatedBy(2).isLessThanOrEqualTo(i.minus(n).exponentiatedBy(2).plus(o.minus(r).exponentiatedBy(2)).times(t))}:ss(!1);return function(t,n,r){var i=t.x,o=t.y,s=r.x,a=r.y,u=o.minus(a).times(n.x.minus(s)).minus(i.minus(s).times(n.y.minus(a)));return e(u,i,o,s,a)?0:u.comparedTo(0)}}var ls=function(t){return t},hs=function(t){if(t){var e=new ns(as(t)),n=new ns(as(t)),r=function(t,e){return e.addAndReturn(t)},i=function(t){return{x:r(t.x,e),y:r(t.y,n)}};return i({x:new $o(0),y:new $o(0)}),i}return ls},cs=function(t){return{set:function(t){fs=cs(t)},reset:function(){return cs(t)},compare:as(t),snap:hs(t),orient:us(t)}},fs=cs(),gs=function(t,e){return t.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(t.ur.x)&&t.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(t.ur.y)},ps=function(t,e){if(e.ur.x.isLessThan(t.ll.x)||t.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(t.ll.y)||t.ur.y.isLessThan(e.ll.y))return null;var n=t.ll.x.isLessThan(e.ll.x)?e.ll.x:t.ll.x,r=t.ur.x.isLessThan(e.ur.x)?t.ur.x:e.ur.x;return{ll:{x:n,y:t.ll.y.isLessThan(e.ll.y)?e.ll.y:t.ll.y},ur:{x:r,y:t.ur.y.isLessThan(e.ur.y)?t.ur.y:e.ur.y}}},vs=function(t,e){return t.x.times(e.y).minus(t.y.times(e.x))},ds=function(t,e){return t.x.times(e.x).plus(t.y.times(e.y))},ys=function(t){return ds(t,t).sqrt()},ms=function(t,e,n){var r={x:e.x.minus(t.x),y:e.y.minus(t.y)},i={x:n.x.minus(t.x),y:n.y.minus(t.y)};return ds(i,r).div(ys(i)).div(ys(r))},_s=function(t,e,n){return e.y.isZero()?null:{x:t.x.plus(e.x.div(e.y).times(n.minus(t.y))),y:n}},xs=function(t,e,n){return e.x.isZero()?null:{x:n,y:t.y.plus(e.y.div(e.x).times(n.minus(t.x)))}},Es=function(){function t(e,n){i(this,t),u(this,"point",void 0),u(this,"isLeft",void 0),u(this,"segment",void 0),u(this,"otherSE",void 0),u(this,"consumedBy",void 0),void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}return s(t,[{key:"link",value:function(t){if(t.point===this.point)throw new Error("Tried to link already linked events");for(var e=t.point.events,n=0,r=e.length;n0&&(t=r)}for(var i=t.segment.prevInResult(),o=i?i.prevInResult():null;;){if(!i)return null;if(!o)return i.ringOut;var s,a;if(o.ringOut!==i.ringOut)return(null===(s=o.ringOut)||void 0===s?void 0:s.enclosingRing())!==i.ringOut?i.ringOut:null===(a=i.ringOut)||void 0===a?void 0:a.enclosingRing();i=o.prevInResult(),o=i?i.prevInResult():null}}}],[{key:"factory",value:function(e){for(var n=[],r=0,i=e.length;r1&&void 0!==arguments[1]?arguments[1]:Ls.compare;i(this,t),u(this,"queue",void 0),u(this,"tree",void 0),u(this,"segments",void 0),this.queue=e,this.tree=new ns(n),this.segments=[]}),[{key:"process",value:function(t){var e=t.segment,n=[];if(t.consumedBy)return t.isLeft?this.queue.delete(t.otherSE):this.tree.delete(e),n;t.isLeft&&this.tree.add(e);var r=e,i=e;do{r=this.tree.lastBefore(r)}while(null!=r&&null!=r.consumedBy);do{i=this.tree.firstAfter(i)}while(null!=i&&null!=i.consumedBy);if(t.isLeft){var o=null;if(r){var s=r.getIntersection(e);if(null!==s&&(e.isAnEndpoint(s)||(o=s),!r.isAnEndpoint(s)))for(var a=this._splitSafely(r,s),u=0,l=a.length;u0?(this.tree.delete(e),n.push(t)):(this.segments.push(e),e.prev=r)}else{if(r&&i){var _=r.getIntersection(i);if(null!==_){if(!r.isAnEndpoint(_))for(var x=this._splitSafely(r,_),E=0,k=x.length;E0&&a.swapEvents(),Es.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}},{key:"swapEvents",value:function(){var t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(var e=0,n=this.windings.length;e0){var o=n;n=r,r=o}if(n.prev===r){var s=n;n=r,r=s}for(var a=0,u=r.rings.length;a0)return-1;var c=e.comparePoint(t.rightSE.point);return 0!==c?c:-1}if(n.isGreaterThan(r)){if(s.isLessThan(a)&&s.isLessThan(l))return-1;if(s.isGreaterThan(a)&&s.isGreaterThan(l))return 1;var f=e.comparePoint(t.leftSE.point);if(0!==f)return f;var g=t.comparePoint(e.rightSE.point);return g<0?1:g>0?-1:1}if(s.isLessThan(a))return-1;if(s.isGreaterThan(a))return 1;if(i.isLessThan(o)){var p=e.comparePoint(t.rightSE.point);if(0!==p)return p}if(i.isGreaterThan(o)){var v=t.comparePoint(e.rightSE.point);if(v<0)return 1;if(v>0)return-1}if(!i.eq(o)){var d=u.minus(s),y=i.minus(n),m=l.minus(a),_=o.minus(r);if(d.isGreaterThan(y)&&m.isLessThan(_))return 1;if(d.isLessThan(y)&&m.isGreaterThan(_))return-1}return i.isGreaterThan(o)?1:i.isLessThan(o)||u.isLessThan(l)?-1:u.isGreaterThan(l)?1:t.ide.id?1:0}},{key:"fromRing",value:function(e,n,r){var i,o,s,a=Es.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else{if(!(a>0))throw new Error("Tried to create degenerate segment at [".concat(e.x,", ").concat(e.y,"]"));i=n,o=e,s=-1}return new t(new Es(i,!0),new Es(o,!1),[r],[s])}}])}(),Ps=function(){return s((function t(e,n,r){if(i(this,t),u(this,"poly",void 0),u(this,"isExterior",void 0),u(this,"segments",void 0),u(this,"bbox",void 0),!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");var o=fs.snap({x:new $o(e[0][0]),y:new $o(e[0][1])});this.bbox={ll:{x:o.x,y:o.y},ur:{x:o.x,y:o.y}};for(var s=o,a=1,l=e.length;a1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r2&&void 0!==arguments[2]?arguments[2]:2,r=K(t),i=K(e),o=r[0]-i[0],s=r[1]-i[1];return 1===n?Math.abs(o)+Math.abs(s):Math.pow(Math.pow(o,n)+Math.pow(s,n),1/n)}function Gs(t,e){var n,r,i=(e=e||{}).threshold||1e4,o=e.p||2,s=null!=(n=e.binary)&&n,a=e.alpha||-1,u=null!=(r=e.standardization)&&r,l=[];vt(t,(function(t){l.push(gi(t))}));for(var h=[],c=0;c3&&void 0!==arguments[3]?arguments[3]:{},i=e<0,o=j(Math.abs(e),r.units,"meters");i&&(o=-Math.abs(o));var s=K(t),a=function(t,e,n,r){r=void 0===r?x:Number(r);var i=e/r,o=t[0]*Math.PI/180,s=z(t[1]),a=z(n),u=i*Math.cos(a),l=s+u;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);var h=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),c=Math.abs(h)>1e-11?u/h:Math.cos(s),f=i*Math.sin(a)/c;return[(180*(o+f)/Math.PI+540)%360-180,180*l/Math.PI]}(s,o,n);return a[0]+=a[0]-s[0]>180?-360:s[0]-a[0]>180?360:0,I(a,r.properties)}function Ys(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e);i[0]+=i[0]-r[0]>180?-360:r[0]-i[0]>180?360:0;var o=function(t,e,n){var r=n=void 0===n?x:Number(n),i=t[1]*Math.PI/180,o=e[1]*Math.PI/180,s=o-i,a=Math.abs(e[0]-t[0])*Math.PI/180;a>Math.PI&&(a-=2*Math.PI);var u=Math.log(Math.tan(o/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),l=Math.abs(u)>1e-11?s/u:Math.cos(i);return Math.sqrt(s*s+l*l*a*a)*r}(r,i);return j(o,"meters",n.units)}function zs(t,e,n){if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.pivot,i=n.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("angle is required");if(0===e)return t;var o=null!=r?r:gi(t);return!1!==i&&void 0!==i||(t=Ai(t)),ct(t,(function(t){var n=lt(o,t)+e,r=Ys(o,t),i=Q(Bs(o,r,n));t[0]=i[0],t[1]=i[1]})),t}function js(t,e,n,r){var i=(r=r||{}).steps||64,o=r.units||"kilometers",s=r.angle||0,a=r.pivot||t,u=r.properties||{};if(!t)throw new Error("center is required");if(!e)throw new Error("xSemiAxis is required");if(!n)throw new Error("ySemiAxis is required");if(!Z(r))throw new Error("options must be an object");if(!U(i))throw new Error("steps must be a number");if(!U(s))throw new Error("angle must be a number");var l=K(t);if("degrees"!==o){var h=Bs(t,e,90,{units:o}),c=Bs(t,n,0,{units:o});e=K(h)[0]-l[0],n=K(c)[1]-l[1]}for(var f=[],g=0;g=-270&&(v=-v),p<-180&&p>=-360&&(d=-d),"degrees"===o){var y=z(s),m=v*Math.cos(y)+d*Math.sin(y),_=d*Math.cos(y)-v*Math.sin(y);v=m,d=_}f.push([v+l[0],d+l[1]])}return f.push(f[0]),"degrees"===o?S([f],u):zs(S([f],u),s,{pivot:a})}function Xs(t){var e=t*Math.PI/180;return Math.tan(e)}function Us(t){return Vt(Rt(t))}function Zs(t){var e=[];return"FeatureCollection"===t.type?vt(t,(function(t){ct(t,(function(n){e.push(I(n,t.properties))}))})):"Feature"===t.type?ct(t,(function(n){e.push(I(n,t.properties))})):ct(t,(function(t){e.push(I(t))})),C(e)}var Hs=Math.PI/180,Ws=180/Math.PI,Js=function(t,e){this.lon=t,this.lat=e,this.x=Hs*t,this.y=Hs*e};Js.prototype.view=function(){return String(this.lon).slice(0,4)+","+String(this.lat).slice(0,4)},Js.prototype.antipode=function(){var t=-1*this.lat,e=this.lon<0?180+this.lon:-1*(180-this.lon);return new Js(e,t)};var Ks=function(){this.coords=[],this.length=0};Ks.prototype.move_to=function(t){this.length++,this.coords.push(t)};var Qs=function(t){this.properties=t||{},this.geometries=[]};Qs.prototype.json=function(){if(this.geometries.length<=0)return{geometry:{type:"LineString",coordinates:null},type:"Feature",properties:this.properties};if(1===this.geometries.length)return{geometry:{type:"LineString",coordinates:this.geometries[0].coords},type:"Feature",properties:this.properties};for(var t=[],e=0;e1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must specify at least 2 geometries");var r=Rs.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)}function ea(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.stringify(n.properties||{}),i=v(t,4),o=i[0],s=i[1],a=i[2],u=i[3],l=(s+u)/2,h=(o+a)/2,c=2*e/ut([o,l],[a,l],n)*(a-o),f=2*e/ut([h,s],[h,u],n)*(u-s),g=c/2,p=2*g,d=Math.sqrt(3)/2*f,y=a-o,m=u-s,_=3/4*p,x=d,E=(y-p)/(p-g/2),k=Math.floor(E),b=(k*_-g/2-y)/2-g/2+_/2,w=Math.floor((m-d)/d),I=(m-w*d)/2,N=w*d-m>d/2;N&&(I-=d/4);for(var S=[],M=[],L=0;L<6;L++){var P=2*Math.PI/6*L;S.push(Math.cos(P)),M.push(Math.sin(P))}for(var T=[],O=0;O<=k;O++)for(var R=0;R<=w;R++){var A=O%2==1;if((0!==R||!A)&&(0!==R||!N)){var D=O*_+o-b,F=R*x+s+I;if(A&&(F-=d/2),!0===n.triangles)ra([D,F],c/2,f/2,JSON.parse(r),S,M).forEach((function(t){n.mask?ta(C([n.mask,t]))&&T.push(t):T.push(t)}));else{var q=na([D,F],c/2,f/2,JSON.parse(r),S,M);n.mask?ta(C([n.mask,q]))&&T.push(q):T.push(q)}}}return C(T)}function na(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=t[0]+e*i[a],l=t[1]+n*o[a];s.push([u,l])}return s.push(s[0].slice()),S([s],r)}function ra(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=[];u.push(t),u.push([t[0]+e*i[a],t[1]+n*o[a]]),u.push([t[0]+e*i[(a+1)%6],t[1]+n*o[(a+1)%6]]),u.push(t),s.push(S([u],r))}return s}function ia(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.mask&&!n.units&&(n.units="kilometers");for(var r=[],i=t[0],o=t[1],s=t[2],a=t[3],u=e/ut([i,o],[s,o],n)*(s-i),l=e/ut([i,o],[i,a],n)*(a-o),h=s-i,c=a-o,f=Math.floor(h/u),g=(c-Math.floor(c/l)*l)/2,p=i+(h-f*u)/2;p<=s;){for(var v=o+g;v<=a;){var d=I([p,v],n.properties);n.mask?Cn(d,n.mask)&&r.push(d):r.push(d),v+=l}p+=u}return C(r)}function oa(t,e,n){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=[],o=t[0],s=t[1],a=t[2],u=t[3],l=a-o,h=j(e,r.units,"degrees"),c=u-s,f=j(n,r.units,"degrees"),g=Math.floor(Math.abs(l)/h),p=Math.floor(Math.abs(c)/f),v=(c-p*f)/2,d=o+(l-g*h)/2,y=0;y2&&void 0!==arguments[2]?arguments[2]:{})}function aa(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=[],i=e/ut([t[0],t[1]],[t[2],t[1]],n)*(t[2]-t[0]),o=e/ut([t[0],t[1]],[t[0],t[3]],n)*(t[3]-t[1]),s=0,a=t[0];a<=t[2];){for(var u=0,l=t[1];l<=t[3];){var h=null,c=null;s%2==0&&u%2==0?(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)):s%2==0&&u%2==1?(h=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties)):u%2==0&&s%2==1?(h=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties),c=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties)):u%2==1&&s%2==1&&(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)),n.mask?(ta(C([n.mask,h]))&&r.push(h),ta(C([n.mask,c]))&&r.push(c)):(r.push(h),r.push(c)),l+=o,u++}s++,a+=i}return C(r)} +/*! + * MarchingSquaresJS + * version 1.3.3 + * https://github.com/RaumZeit/MarchingSquares.js + * + * @license GNU Affero General Public License. + * Copyright (c) 2015-2019 Ronny Lorenz + */ +function ua(t,e,n){return tr&&(i=n,n=r,r=i),tr?(t-r)/(t-e):(t-n)/(t-e)}function ha(t,e,n,r){return t1){for(;0!==o;)o>>=1,a++;r===1<1){for(;0!==s;)s>>=1,u++;i===1<0&&(this.childB=new da(t,e+o,n,r-o,s),this.lowerBound=Math.min(this.lowerBound,this.childB.lowerBound),this.upperBound=Math.max(this.upperBound,this.childB.upperBound),i-s>0&&(this.childC=new da(t,e+o,n+s,r-o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childC.lowerBound),this.upperBound=Math.max(this.upperBound,this.childC.upperBound))),i-s>0&&(this.childD=new da(t,e,n+s,o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childD.lowerBound),this.upperBound=Math.max(this.upperBound,this.childD.upperBound))}}function ya(t){var e,n;if(!t)throw new Error("data is required");if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Error("data must be scalar field, i.e. array of arrays");if(t.length<2)throw new Error("data must contain at least two rows");if((n=t[0].length)<2)throw new Error("data must contain at least two columns");for(e=1;e=e||t[s][r-1]>=e){n=!1;break}if(n&&(t[i-1][0]>=e||t[i-1][r-1]>=e)&&(n=!1),n)for(o=0;o=e||t[i-1][o]>e){n=!1;break}return n}(t,n.threshold)&&(n.linearRing?_.push([[0,0],[0,x],[E,x],[E,0],[0,0]]):_.push([[0,0],[0,x],[E,x],[E,0]])),e.forEach((function(t,N){t.forEach((function(t,S){for(r=null,i=0;i<4;i++)if(r=k[i],"object"===m(t.edges[r])){for(a=[],o=t.edges[r],u=r,l=N,h=S,c=!1,f=[N+o.path[0][0],S+o.path[0][1]],a.push(f);!c&&"object"===m((s=e[l][h]).edges[u]);)if(o=s.edges[u],delete s.edges[u],(g=o.path[1])[0]+=l,g[1]+=h,a.push(g),u=o.move.enter,l+=o.move.x,h+=o.move.y,void 0===e[l]||void 0===e[l][h]){if(!n.linearRing)break;if(p=0,v=0,l===E?(l--,p=0):l<0?(l++,p=2):h===x?(h--,p=3):h<0&&(h++,p=1),l===N&&h===S&&p===I[r]){c=!0,u=r;break}for(;;){if(d=!1,v>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[l]&&void 0!==e[l][h]&&(s=e[l][h],y=k[p],"object"===m(s.edges[y]))){o=s.edges[y],a.push(pa(l,h,p,o.path)),u=y,d=!0;break}if(d)break;if(a.push(va(l,h,p)),h+=w[p],void 0!==e[l+=b[p]]&&void 0!==e[l][h]||(0===p&&h<0||1===p&&l<0||2===p&&h===x||3===p&&l===E)&&(l-=b[p],h-=w[p],p=(p+1)%4,v++),l===N&&h===S&&p===I[r]){c=!0,u=r;break}}}!n.linearRing||a[a.length-1][0]===f[0]&&a[a.length-1][1]===f[1]||a.push(f),_.push(a)}}))})),_}(h,c,r)}a?g.push(f):g=f,"function"==typeof r.successCallback&&r.successCallback(g,t)})),g}function _a(t,e,n,r){var i,o,s,a,u,l,h=0,c=t[n+1][e],f=t[n+1][e+1],g=t[n][e+1],p=t[n][e],v=r.threshold;if(!(isNaN(p)||isNaN(g)||isNaN(f)||isNaN(c))){switch(h|=c>=v?8:0,h|=f>=v?4:0,h|=g>=v?2:0,l={cval:h=+(h|=p>=v?1:0),polygons:[],edges:{},x0:p,x1:g,x2:f,x3:c},h){case 0:r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,0]]);break;case 15:break;case 14:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.left={path:[[0,i],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[a,0]]);break;case 13:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[a,0],[1,o],[1,0]]);break;case 11:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[1,o],[s,1],[1,1]]);break;case 7:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[s,1],[0,i],[0,1]]);break;case 1:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[a,0],[0,i],[0,1],[1,1],[1,0]]);break;case 2:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,o],[a,0]]);break;case 4:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[1,o],[1,0]]);break;case 8:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[s,1],[1,1],[1,0]]);break;case 12:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[1,o],[1,0]]);break;case 9:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[a,0],[s,1],[1,1],[1,0]]);break;case 3:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[0,i],[0,1],[1,1],[1,o]]);break;case 6:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[a,0]]);break;case 10:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),u=(p+g+f+c)/4,r.polygons_full&&(uf&&(v>h&&ph&&vu&&(u=d)}var y=[];if(a&&u0&&Math.abs(x-n[_-1][0])>f){var E=parseFloat(n[_-1][0]),k=parseFloat(n[_-1][1]),b=parseFloat(n[_][0]),w=parseFloat(n[_][1]);if(E>-180&&E-180&&n[_-1][0]h&&E<180&&-180===b&&_+1h&&n[_-1][0]<180){m.push([180,n[_][1]]),_++,m.push([n[_][0],n[_][1]]);continue}if(Eh){var I=E;E=b,b=I;var N=k;k=w,w=N}if(E>h&&b=180&&Eh?180:-180,M]),(m=[]).push([n[_-1][0]>h?-180:180,M]),y.push(m)}else m=[],y.push(m);m.push([x,n[_][1]])}else m.push([n[_][0],n[_][1]])}}else{var L=[];y.push(L);for(var P=0;Pe||this.upperBound=e)&&r.push({x:this.x,y:this.y})),r},da.prototype.cellsBelowThreshold=function(t,e){var n=[];return e=void 0===e||e,this.lowerBound>t||(this.childA||this.childB||this.childC||this.childD?(this.childA&&(n=n.concat(this.childA.cellsBelowThreshold(t,e))),this.childB&&(n=n.concat(this.childB.cellsBelowThreshold(t,e))),this.childD&&(n=n.concat(this.childD.cellsBelowThreshold(t,e))),this.childC&&(n=n.concat(this.childC.cellsBelowThreshold(t,e)))):(e||this.upperBound>=t)&&n.push({x:this.x,y:this.y})),n};var xa={square:function(t,e,n,r,i,o){o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,0]])},triangle_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,a],[s,0],[0,0]])},triangle_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[1,a],[1,0]])},triangle_tr:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[1,s],[a,1],[1,1]])},triangle_tl:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[s,1]])},tetragon_t:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[1,1],[1,s]])},tetragon_r:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[a,1],[1,1],[1,0]])},tetragon_b:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,0]])},tetragon_l:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[a,0]])},tetragon_bl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[a,0]])},tetragon_br:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate_b(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[1,l]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[1,l],[1,u],[a,0]])},tetragon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rb={path:[[1,l],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}}),o.polygons&&t.polygons.push([[1,l],[s,1],[a,1],[1,u]])},tetragon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[0,l]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[a,1],[0,l],[0,u],[s,1]])},tetragon_lr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[1,u],[1,l]])},tetragon_tb:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[l,0],[s,1],[a,1],[u,0]])},pentagon_tr:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[1,a],[1,0]])},pentagon_tl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,0]])},pentagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,a],[s,0]])},pentagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[a,0],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[1,1],[1,0],[a,0]])},pentagon_tr_rl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[1,u],[1,l]])},pentagon_rb_bt:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,n,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[u,0],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[l,1],[1,1],[1,s],[a,0],[u,0]])},pentagon_bl_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[1,l],[1,0]])},pentagon_lt_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[l,0]])},pentagon_bl_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[l,0],[0,s]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[u,0],[l,0]])},pentagon_lt_rl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[u,1],[1,1],[1,l]])},pentagon_tr_bt:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,1],[a,1],[1,u],[1,0],[l,0]])},pentagon_rb_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_b(n,r,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,u],[l,0]])},hexagon_lt_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[1,l],[1,0]])},hexagon_bl_lt:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[1,1],[1,0]])},hexagon_bl_rb:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.rt={path:[[1,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[1,1],[1,l],[a,0]])},hexagon_tr_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[a,1],[1,u],[1,l],[s,0]])},hexagon_lt_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,u],[l,0]])},hexagon_bl_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,1],[u,1],[1,l],[1,0]])},heptagon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[1,1],[1,c],[a,0]])},heptagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate_a(i,r,o.minV,o.maxV),l=o.interpolate_b(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,a],[u,1],[l,1],[1,h],[1,c],[s,0]])},heptagon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[l,1],[1,h],[1,c],[a,0]])},heptagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(i,r,o.minV,o.maxV),h=o.interpolate_b(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[h,1],[1,c]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[h,1],[1,c],[1,0]])},octagon:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate_a(i,r,o.minV,o.maxV),c=o.interpolate_b(i,r,o.minV,o.maxV),f=o.interpolate_b(n,r,o.minV,o.maxV),g=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[c,1],[1,f]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,g],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[c,1],[1,f],[1,g],[a,0]])}};function Ea(t,e,n,r){var i,o,s,a=!1,u=null,l=null,h=null,c=null,f=!1,g=[],p=[],v=[];if(!t)throw new Error("data is required");if(null==e)throw new Error("lowerBound is required");if(null==n)throw new Error("bandWidth is required");if(s=function(t){var e,n,r,i,o;for(i=new fa,t=t||{},o=Object.keys(i),e=0;en||t[a][i-1]n){r=!1;break}if(r&&(t[o-1][0]n||t[o-1][i-1]n)&&(r=!1),r)for(s=0;sn||t[o-1][s]n){r=!1;break}return r}(t,n.minV,n.maxV)&&(n.linearRing?x.push([[0,0],[0,E],[k,E],[k,0],[0,0]]):x.push([[0,0],[0,E],[k,E],[k,0]])),e.forEach((function(t,M){t.forEach((function(t,L){for(r=null,o=0;o<8;o++)if(r=N[o],"object"===m(t.edges[r])){for(i=[],s=t.edges[r],l=r,h=M,c=L,f=!1,g=[M+s.path[0][0],L+s.path[0][1]],i.push(g);!f&&"object"===m((p=e[h][c]).edges[l]);)if(s=p.edges[l],delete p.edges[l],(y=s.path[1])[0]+=h,y[1]+=c,i.push(y),l=s.move.enter,h+=s.move.x,c+=s.move.y,void 0===e[h]||void 0===e[h][c]){if(v=0,d=0,h===k)h--,v=0;else if(h<0)h++,v=2;else if(c===E)c--,v=3;else{if(!(c<0))throw new Error("Left the grid somewhere in the interior!");c++,v=1}if(h===M&&c===L&&v===S[r]){f=!0,l=r;break}for(;;){if(_=!1,d>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[h]&&void 0!==e[h][c])for(p=e[h][c],a=0;ao?2:sf?128:64,s|=uf?32:16,s|=lf?8:4,o=0,i={cval:s=+(s|=hf?2:1),polygons:[],edges:{},x0:h,x1:l,x2:u,x3:a,x:e,y:n},s){case 85:xa.square(i,h,l,u,a,r);case 0:case 170:break;case 169:xa.triangle_bl(i,h,l,u,a,r);break;case 166:xa.triangle_br(i,h,l,u,a,r);break;case 154:xa.triangle_tr(i,h,l,u,a,r);break;case 106:xa.triangle_tl(i,h,l,u,a,r);break;case 1:xa.triangle_bl(i,h,l,u,a,r);break;case 4:xa.triangle_br(i,h,l,u,a,r);break;case 16:xa.triangle_tr(i,h,l,u,a,r);break;case 64:xa.triangle_tl(i,h,l,u,a,r);break;case 168:xa.tetragon_bl(i,h,l,u,a,r);break;case 162:xa.tetragon_br(i,h,l,u,a,r);break;case 138:xa.tetragon_tr(i,h,l,u,a,r);break;case 42:xa.tetragon_tl(i,h,l,u,a,r);break;case 2:xa.tetragon_bl(i,h,l,u,a,r);break;case 8:xa.tetragon_br(i,h,l,u,a,r);break;case 32:xa.tetragon_tr(i,h,l,u,a,r);break;case 128:xa.tetragon_tl(i,h,l,u,a,r);break;case 5:xa.tetragon_b(i,h,l,u,a,r);break;case 20:xa.tetragon_r(i,h,l,u,a,r);break;case 80:xa.tetragon_t(i,h,l,u,a,r);break;case 65:xa.tetragon_l(i,h,l,u,a,r);break;case 165:xa.tetragon_b(i,h,l,u,a,r);break;case 150:xa.tetragon_r(i,h,l,u,a,r);break;case 90:xa.tetragon_t(i,h,l,u,a,r);break;case 105:xa.tetragon_l(i,h,l,u,a,r);break;case 160:xa.tetragon_lr(i,h,l,u,a,r);break;case 130:xa.tetragon_tb(i,h,l,u,a,r);break;case 10:xa.tetragon_lr(i,h,l,u,a,r);break;case 40:xa.tetragon_tb(i,h,l,u,a,r);break;case 101:xa.pentagon_tr(i,h,l,u,a,r);break;case 149:xa.pentagon_tl(i,h,l,u,a,r);break;case 86:xa.pentagon_bl(i,h,l,u,a,r);break;case 89:xa.pentagon_br(i,h,l,u,a,r);break;case 69:xa.pentagon_tr(i,h,l,u,a,r);break;case 21:xa.pentagon_tl(i,h,l,u,a,r);break;case 84:xa.pentagon_bl(i,h,l,u,a,r);break;case 81:xa.pentagon_br(i,h,l,u,a,r);break;case 96:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 24:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 6:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 129:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 74:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 146:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 164:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 41:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 66:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 144:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 36:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 9:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 104:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 26:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 134:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 161:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 37:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 148:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 82:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 73:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 133:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 22:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 88:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 97:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 145:case 25:xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 70:case 100:xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 17:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 68:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 153:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 102:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 152:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 137:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 98:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 38:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 18:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 33:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 72:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 132:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 136:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r));break;case 34:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r))}return i}}var wa=Object.defineProperty,Ia=Object.getOwnPropertySymbols,Na=Object.prototype.hasOwnProperty,Sa=Object.prototype.propertyIsEnumerable,Ma=function(t,e,n){return e in t?wa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},La=function(t,e){for(var n in e||(e={}))Na.call(e,n)&&Ma(t,n,e[n]);if(Ia){var r,i=a(Ia(e));try{for(i.s();!(r=i.n()).done;){n=r.value;Sa.call(e,n)&&Ma(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t};function Pa(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.zProperty||"elevation",r=e.flip,i=e.flags;nt(t,"Point","input must contain Points");for(var o=function(t,e){var n={};vt(t,(function(t){var e=Q(t)[1];n[e]||(n[e]=[]),n[e].push(t)}));var r=Object.keys(n).map((function(t){return n[t].sort((function(t,e){return Q(t)[0]-Q(e)[0]}))})),i=r.sort((function(t,n){return e?Q(t[0])[1]-Q(n[0])[1]:Q(n[0])[1]-Q(t[0])[1]}));return i}(t,r),s=[],a=0;a=0&&l<=1&&(f.onLine1=!0),h>=0&&h<=1&&(f.onLine2=!0),!(!f.onLine1||!f.onLine2)&&[f.x,f.y])}function za(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return bt(t,(function(t,n){var r=n.geometry.coordinates;return t+ut(r[0],r[1],e)}),0)}function ja(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=i.steps||64,s=Xa(n),a=Xa(r),u=Array.isArray(t)||"Feature"!==t.type?{}:t.properties;if(s===a)return L(Ri(t,e,i).geometry.coordinates[0],u);for(var l=s,h=s=h&&c===i.length-1);c++){if(h>e&&0===o.length){if(!(s=e-h))return o.push(i[c]),L(o);a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates)}if(h>=n)return(s=n-h)?(a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates),L(o)):(o.push(i[c]),L(o));if(h>=e&&o.push(i[c]),c===i.length-1)return L(o);h+=ut(i[c],i[c+1],r)}if(h0){var a=r[e-1],u=Wa(n,a);!1!==u&&(a[1]=u,n[0]=u),s.push(a[0]),e===o.length-2&&(s.push(n[0]),s.push(n[1]))}2===o.length&&(s.push(n[0]),s.push(n[1]))}var l,h,c,f,g,p,v,d})),L(s,t.properties)}function Ka(t){var e=t[0],n=t[1],r=t[2],i=t[3];if(ut(t.slice(0,2),[r,n])>=ut(t.slice(0,2),[e,i])){var o=(n+i)/2;return[e,o-(r-e)/2,r,o+(r-e)/2]}var s=(e+r)/2;return[s-(i-n)/2,n,s+(i-n)/2,i]}function Qa(t,e){if(!Z(e=null!=e?e:{}))throw new Error("options is invalid");var n=e.precision,r=e.coordinates,i=e.mutate;if(n=null==n||isNaN(n)?6:n,r=null==r||isNaN(r)?3:r,!t)throw new Error(" is required");if("number"!=typeof n)throw new Error(" must be a number");if("number"!=typeof r)throw new Error(" must be a number");!1!==i&&void 0!==i||(t=JSON.parse(JSON.stringify(t)));var o=Math.pow(10,n);return ct(t,(function(t){!function(t,e,n){t.length>n&&t.splice(n,t.length);for(var r=0;r1&&n.push(L(l)),C(n)}function eu(t,e){if(!e.features.length)throw new Error("lines must contain features");if(1===e.features.length)return e.features[0];var n,r=1/0;return vt(e,(function(e){var i=fn(e,t).properties.dist;iu?(a.unshift(t),u=e):a.push(t)}else a.push(t)})),S(a,e);default:throw new Error("geometry type "+s+" is not supported")}}function iu(t){var e=t[0],n=e[0],r=e[1],i=t[t.length-1],o=i[0],s=i[1];return n===o&&r===s||t.push(e),t}function ou(t){return R(t)}function su(t){var e=[[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]];return t&&(e="Feature"===t.type?t.geometry.coordinates:t.coordinates),S(e)}function au(t){var e,n=0,r=a(t);try{for(r.s();!(e=r.n()).done;){n+=e.value}}catch(t){r.e(t)}finally{r.f()}return n/t.length}var uu=Object.defineProperty,lu=Object.defineProperties,hu=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,fu=Object.prototype.hasOwnProperty,gu=Object.prototype.propertyIsEnumerable,pu=function(t,e,n){return e in t?uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},vu=function(t,e){for(var n in e||(e={}))fu.call(e,n)&&pu(t,n,e[n]);if(cu){var r,i=a(cu(e));try{for(i.s();!(r=i.n()).done;){n=r.value;gu.call(e,n)&&pu(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},du=function(t,e){return lu(t,hu(e))};function yu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("targetPoint is required");if(!e)throw new Error("points is required");var r=1/0,i=0;vt(e,(function(e,o){var s=ut(t,e,n);s2&&void 0!==arguments[2]?arguments[2]:{},o=null!=(n=i.method)?n:"geodesic",s=null!=(r=i.units)?r:"kilometers";if(!t)throw new Error("pt is required");if(Array.isArray(t)?t=I(t):"Point"===t.type?t=b(t):et(t,"Point","point"),!e)throw new Error("line is required");Array.isArray(e)?e=L(e):"LineString"===e.type?e=b(e):et(e,"LineString","line");var a=1/0,u=t.geometry.coordinates;return kt(e,(function(t){if(t){var e=t.geometry.coordinates[0],n=t.geometry.coordinates[1],r=function(t,e,n,r){if("geodesic"===r.method){return fn(L([e,n]).geometry,t,{units:"degrees"}).properties.dist}var i=[n[0]-e[0],n[1]-e[1]],o=[t[0]-e[0],t[1]-e[1]],s=_u(o,i);if(s<=0)return Ys(t,e,{units:"degrees"});var a=_u(i,i);if(a<=s)return Ys(t,n,{units:"degrees"});var u=s/a,l=[e[0]+u*i[0],e[1]+u*i[1]];return Ys(t,l,{units:"degrees"})}(u,e,n,{method:o});r0)-(t<0)||+t}(r*(n[1]-e[1])-o*i)}function Lu(t,e){return e.geometry.coordinates[0].every((function(e){return zt(I(e),t)}))}var Pu=function(){return s((function t(e){i(this,t),this.id=t.buildId(e),this.coordinates=e,this.innerEdges=[],this.outerEdges=[],this.outerEdgesSorted=!1}),[{key:"removeInnerEdge",value:function(t){this.innerEdges=this.innerEdges.filter((function(e){return e.from.id!==t.from.id}))}},{key:"removeOuterEdge",value:function(t){this.outerEdges=this.outerEdges.filter((function(e){return e.to.id!==t.to.id}))}},{key:"addOuterEdge",value:function(t){this.outerEdges.push(t),this.outerEdgesSorted=!1}},{key:"sortOuterEdges",value:function(){var t=this;this.outerEdgesSorted||(this.outerEdges.sort((function(e,n){var r=e.to,i=n.to;if(r.coordinates[0]-t.coordinates[0]>=0&&i.coordinates[0]-t.coordinates[0]<0)return 1;if(r.coordinates[0]-t.coordinates[0]<0&&i.coordinates[0]-t.coordinates[0]>=0)return-1;if(r.coordinates[0]-t.coordinates[0]==0&&i.coordinates[0]-t.coordinates[0]==0)return r.coordinates[1]-t.coordinates[1]>=0||i.coordinates[1]-t.coordinates[1]>=0?r.coordinates[1]-i.coordinates[1]:i.coordinates[1]-r.coordinates[1];var o=Mu(t.coordinates,r.coordinates,i.coordinates);return o<0?1:o>0?-1:Math.pow(r.coordinates[0]-t.coordinates[0],2)+Math.pow(r.coordinates[1]-t.coordinates[1],2)-(Math.pow(i.coordinates[0]-t.coordinates[0],2)+Math.pow(i.coordinates[1]-t.coordinates[1],2))})),this.outerEdgesSorted=!0)}},{key:"getOuterEdges",value:function(){return this.sortOuterEdges(),this.outerEdges}},{key:"getOuterEdge",value:function(t){return this.sortOuterEdges(),this.outerEdges[t]}},{key:"addInnerEdge",value:function(t){this.innerEdges.push(t)}}],[{key:"buildId",value:function(t){return t.join(",")}}])}(),Cu=function(){function t(e,n){i(this,t),this.from=e,this.to=n,this.next=void 0,this.label=void 0,this.symetric=void 0,this.ring=void 0,this.from.addOuterEdge(this),this.to.addInnerEdge(this)}return s(t,[{key:"getSymetric",value:function(){return this.symetric||(this.symetric=new t(this.to,this.from),this.symetric.symetric=this),this.symetric}},{key:"deleteEdge",value:function(){this.from.removeOuterEdge(this),this.to.removeInnerEdge(this)}},{key:"isEqual",value:function(t){return this.from.id===t.from.id&&this.to.id===t.to.id}},{key:"toString",value:function(){return"Edge { ".concat(this.from.id," -> ").concat(this.to.id," }")}},{key:"toLineString",value:function(){return L([this.from.coordinates,this.to.coordinates])}},{key:"compareTo",value:function(t){return Mu(t.from.coordinates,t.to.coordinates,this.to.coordinates)}}])}(),Tu=function(){return s((function t(){i(this,t),this.edges=[],this.polygon=void 0,this.envelope=void 0}),[{key:"push",value:function(t){this.edges.push(t),this.polygon=this.envelope=void 0}},{key:"get",value:function(t){return this.edges[t]}},{key:"length",get:function(){return this.edges.length}},{key:"forEach",value:function(t){this.edges.forEach(t)}},{key:"map",value:function(t){return this.edges.map(t)}},{key:"some",value:function(t){return this.edges.some(t)}},{key:"isValid",value:function(){return!0}},{key:"isHole",value:function(){var t=this,e=this.edges.reduce((function(e,n,r){return n.from.coordinates[1]>t.edges[e].from.coordinates[1]&&(e=r),e}),0),n=(0===e?this.length:e)-1,r=(e+1)%this.length,i=Mu(this.edges[n].from.coordinates,this.edges[e].from.coordinates,this.edges[r].from.coordinates);return 0===i?this.edges[n].from.coordinates[0]>this.edges[r].from.coordinates[0]:i>0}},{key:"toMultiPoint",value:function(){return O(this.edges.map((function(t){return t.from.coordinates})))}},{key:"toPolygon",value:function(){if(this.polygon)return this.polygon;var t=this.edges.map((function(t){return t.from.coordinates}));return t.push(this.edges[0].from.coordinates),this.polygon=S([t])}},{key:"getEnvelope",value:function(){return this.envelope?this.envelope:this.envelope=Us(this.toPolygon())}},{key:"inside",value:function(t){return zt(t,this.toPolygon())}}],[{key:"findEdgeRingContaining",value:function(t,e){var n,r,i=t.getEnvelope();return e.forEach((function(e){var o,s,u,l,h,c,f=e.getEnvelope();if((r&&(n=r.getEnvelope()),s=i,u=(o=f).geometry.coordinates[0].map((function(t){return t[0]})),l=o.geometry.coordinates[0].map((function(t){return t[1]})),h=s.geometry.coordinates[0].map((function(t){return t[0]})),c=s.geometry.coordinates[0].map((function(t){return t[1]})),Math.max.apply(null,u)!==Math.max.apply(null,h)||Math.max.apply(null,l)!==Math.max.apply(null,c)||Math.min.apply(null,u)!==Math.min.apply(null,h)||Math.min.apply(null,l)!==Math.min.apply(null,c))&&Lu(f,i)){var g,p,v=a(t.map((function(t){return t.from.coordinates})));try{var d=function(){var t=p.value;e.some((function(e){return n=t,r=e.from.coordinates,n[0]===r[0]&&n[1]===r[1];var n,r}))||(g=t)};for(v.s();!(p=v.n()).done;)d()}catch(t){v.e(t)}finally{v.f()}g&&e.inside(I(g))&&(r&&!Lu(n,f)||(r=e))}})),r}}])}();var Ou=function(){function t(){i(this,t),this.edges=[],this.nodes={}}return s(t,[{key:"getNode",value:function(t){var e=Pu.buildId(t),n=this.nodes[e];return n||(n=this.nodes[e]=new Pu(t)),n}},{key:"addEdge",value:function(t,e){var n=new Cu(t,e),r=n.getSymetric();this.edges.push(n),this.edges.push(r)}},{key:"deleteDangles",value:function(){var t=this;Object.keys(this.nodes).map((function(e){return t.nodes[e]})).forEach((function(e){return t._removeIfDangle(e)}))}},{key:"_removeIfDangle",value:function(t){var e=this;if(t.innerEdges.length<=1){var n=t.getOuterEdges().map((function(t){return t.to}));this.removeNode(t),n.forEach((function(t){return e._removeIfDangle(t)}))}}},{key:"deleteCutEdges",value:function(){var t=this;this._computeNextCWEdges(),this._findLabeledEdgeRings(),this.edges.forEach((function(e){e.label===e.symetric.label&&(t.removeEdge(e.symetric),t.removeEdge(e))}))}},{key:"_computeNextCWEdges",value:function(t){var e=this;void 0===t?Object.keys(this.nodes).forEach((function(t){return e._computeNextCWEdges(e.nodes[t])})):t.getOuterEdges().forEach((function(e,n){t.getOuterEdge((0===n?t.getOuterEdges().length:n)-1).symetric.next=e}))}},{key:"_computeNextCCWEdges",value:function(t,e){for(var n,r,i=t.getOuterEdges(),o=i.length-1;o>=0;--o){var s=i[o],a=s.symetric,u=void 0,l=void 0;s.label===e&&(u=s),a.label===e&&(l=a),u&&l&&(l&&(r=l),u&&(r&&(r.next=u,r=void 0),n||(n=u)))}r&&(r.next=n)}},{key:"_findLabeledEdgeRings",value:function(){var t=[],e=0;return this.edges.forEach((function(n){if(!(n.label>=0)){t.push(n);var r=n;do{r.label=e,r=r.next}while(!n.isEqual(r));e++}})),t}},{key:"getEdgeRings",value:function(){var t=this;this._computeNextCWEdges(),this.edges.forEach((function(t){t.label=void 0})),this._findLabeledEdgeRings().forEach((function(e){t._findIntersectionNodes(e).forEach((function(n){t._computeNextCCWEdges(n,e.label)}))}));var e=[];return this.edges.forEach((function(n){n.ring||e.push(t._findEdgeRing(n))})),e}},{key:"_findIntersectionNodes",value:function(t){var e=[],n=t,r=function(){var r=0;n.from.getOuterEdges().forEach((function(e){e.label===t.label&&++r})),r>1&&e.push(n.from),n=n.next};do{r()}while(!t.isEqual(n));return e}},{key:"_findEdgeRing",value:function(t){var e=t,n=new Tu;do{n.push(e),e.ring=n,e=e.next}while(!t.isEqual(e));return n}},{key:"removeNode",value:function(t){var e=this;t.getOuterEdges().forEach((function(t){return e.removeEdge(t)})),t.innerEdges.forEach((function(t){return e.removeEdge(t)})),delete this.nodes[t.id]}},{key:"removeEdge",value:function(t){this.edges=this.edges.filter((function(e){return!e.isEqual(t)})),t.deleteEdge()}}],[{key:"fromGeoJson",value:function(e){!function(t){if(!t)throw new Error("No geojson passed");if("FeatureCollection"!==t.type&&"GeometryCollection"!==t.type&&"MultiLineString"!==t.type&&"LineString"!==t.type&&"Feature"!==t.type)throw new Error("Invalid input type '".concat(t.type,"'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature"))}(e);var n=new t;return xt(e,(function(t){et(t,"LineString","Graph::fromGeoJson"),ft(t,(function(t,e){if(t){var r=n.getNode(t),i=n.getNode(e);n.addEdge(r,i)}return e}))})),n}}])}();function Ru(t,e){var n,r;ct(t,(function(t,i,o,s,a){if(r!==a)e.push([]);else{var u=n[0],l=n[1],h=t[0],c=t[1];e[a].push([.75*u+.25*h,.75*l+.25*c]),e[a].push([.25*u+.75*h,.25*l+.75*c])}n=t,r=a}),!1),e.forEach((function(t){t.push(t[0])}))}function Au(t,e){var n,r,i;ct(t,(function(t,o,s,a,u){if(r!==a)e.push([[]]);else if(i!==u)e[a].push([]);else{var l=n[0],h=n[1],c=t[0],f=t[1];e[a][u].push([.75*l+.25*c,.75*h+.25*f]),e[a][u].push([.25*l+.75*c,.25*h+.75*f])}n=t,r=a,i=u}),!1),e.forEach((function(t){t.forEach((function(t){t.push(t[0])}))}))}function Du(t,e,n,r,i){for(var o=0;o0?qu(e,s,r)<0||(r=s):n>0&&u<=0&&(Fu(e,s,i)||(i=s)),n=u}return[r,i]}function Fu(t,e,n){return qu(t,e,n)>0}function qu(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(n[0]-t[0])*(e[1]-t[1])}function Vu(t){return Bu(t,"mercator",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Gu(t){return Bu(t,"wgs84",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Bu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=(n=n||{}).mutate;if(!t)throw new Error("geojson is required");return Array.isArray(t)&&U(t[0])?t="mercator"===e?Yu(t):zu(t):(!0!==r&&(t=Ai(t)),ct(t,(function(t){var n="mercator"===e?Yu(t):zu(t);t[0]=n[0],t[1]=n[1]}))),t}function Yu(t){var e=Math.PI/180,n=6378137,r=20037508.342789244,i=Math.abs(t[0])<=180?t[0]:t[0]-360*function(t){return t<0?-1:t>0?1:0}(t[0]),o=[n*i*e,n*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return o[0]>r&&(o[0]=r),o[0]<-r&&(o[0]=-r),o[1]>r&&(o[1]=r),o[1]<-r&&(o[1]=-r),o}function zu(t){var e=180/Math.PI,n=6378137;return[t[0]*e/n,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/n)))*e]}var ju=Object.freeze({__proto__:null,toMercator:Vu,toWgs84:Gu});var Xu={20:1.07275,15:1.13795,10:1.22385,5:1.3581,2:1.51743,1:1.62762};function Uu(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}function Zu(t){var e=[];return function t(n){return 0===n||1===n?1:e[n]>0?e[n]:e[n]=t(n-1)*n}(t)}function Hu(t){return Ju(t),Wu(t)}function Wu(t){return Array.isArray(t)?el(t):t&&t.bbox?el(t.bbox):[360*tl(),180*tl()]}function Ju(t){null!=t&&(Array.isArray(t)?H(t):null!=t.bbox&&H(t.bbox))}function Ku(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1);for(var n=[],r=0;r1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1),void 0!==e.bbox&&null!==e.bbox||(e.bbox=[-180,-90,180,90]),U(e.num_vertices)&&void 0!==e.num_vertices||(e.num_vertices=10),U(e.max_radial_length)&&void 0!==e.max_radial_length||(e.max_radial_length=10);var n=Math.abs(e.bbox[0]-e.bbox[2]),r=Math.abs(e.bbox[1]-e.bbox[3]),i=Math.min(n/2,r/2);if(e.max_radial_length>i)throw new Error("max_radial_length is greater than the radius of the bbox");for(var o=[e.bbox[0]+e.max_radial_length,e.bbox[1]+e.max_radial_length,e.bbox[2]-e.max_radial_length,e.bbox[3]-e.max_radial_length],s=[],a=function(){var t,n=[],r=d(Array(e.num_vertices+1)).map(Math.random);r.forEach((function(t,e,n){n[e]=e>0?t+n[e-1]:t})),r.forEach((function(t){t=2*t*Math.PI/r[r.length-1];var i=Math.random();n.push([i*(e.max_radial_length||10)*Math.sin(t),i*(e.max_radial_length||10)*Math.cos(t)])})),n[n.length-1]=n[0],n=n.reverse().map((t=Wu(o),function(e){return[e[0]+t[0],e[1]+t[1]]})),s.push(S([n]))},u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox;Ju(n);var r=e.num_vertices,i=e.max_length,o=e.max_rotation;null==t&&(t=1),(!U(r)||void 0===r||r<2)&&(r=10),U(i)&&void 0!==i||(i=1e-4),U(o)&&void 0!==o||(o=Math.PI/8);for(var s=[],a=0;a0;){var l=a.pop();if(l===n)return ll(l);l.closed=!0;for(var h=t.neighbors(l),c=0,f=h.length;c1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function dl(t,e,n,r,i){for(var o,s=r,a=e+1;as&&(o=a,s=u)}s>r&&(o-e>1&&dl(t,e,o,r,i),i.push(t[o]),n-o>1&&dl(t,o,n,r,i))}function yl(t,e){var n=t.length-1,r=[t[0]];return dl(t,0,n,e,r),r.push(t[n]),r}function ml(t,e,n){if(t.length<=2)return t;var r=void 0!==e?e*e:1;return t=n?t:function(t,e){for(var n,r,i,o,s,a=t[0],u=[a],l=1,h=t.length;le&&(u.push(n),a=n);return a!==n&&u.push(n),u}(t,r),t=yl(t,r)}function _l(t,e,n){return t.map((function(t){if(t.length<4)throw new Error("invalid polygon");for(var r=e,i=ml(t,r,n);!xl(i);)i=ml(t,r-=.01*r,n);return i[i.length-1][0]===i[0][0]&&i[i.length-1][1]===i[0][1]||i.push(i[0]),i}))}function xl(t){return!(t.length<3)&&!(3===t.length&&t[2][0]===t[0][0]&&t[2][1]===t[0][1])}function El(t,e){return{x:t[0]-e[0],y:t[1]-e[1]}}cl.prototype.init=function(){this.dirtyNodes=[];for(var t=0;t0&&(this.content[0]=e,this.bubbleUp(0)),t},remove:function(t){var e=this.content.indexOf(t),n=this.content.pop();e!==this.content.length-1&&(this.content[e]=n,this.scoreFunction(n)0;){var n=(t+1>>1)-1,r=this.content[n];if(!(this.scoreFunction(e)80*i){o=a=t[0],s=h=t[1];for(var _=i;_a&&(a=c),g>h&&(h=g);p=0!==(p=Math.max(a-o,h-s))?32767/p:0}return r(y,m,i,o,s,p,0),m}function e(t,e,n,r,i){var o,s;if(i===I(t,e,n,r)>0)for(o=e;o=e;o-=r)s=k(o,t[o],t[o+1],s);return s&&d(s,s.next)&&(b(s),s=s.next),s}function n(t,e){if(!t)return t;e||(e=t);var n,r=t;do{if(n=!1,r.steiner||!d(r,r.next)&&0!==v(r.prev,r,r.next))r=r.next;else{if(b(r),(r=e=r.prev)===r.next)break;n=!0}}while(n||r!==e);return e}function r(t,e,u,l,h,f,g){if(t){!g&&f&&function(t,e,n,r){var i=t;do{0===i.z&&(i.z=c(i.x,i.y,e,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,n,r,i,o,s,a,u,l=1;do{for(n=t,t=null,o=null,s=0;n;){for(s++,r=n,a=0,e=0;e0||u>0&&r;)0!==a&&(0===u||!r||n.z<=r.z)?(i=n,n=n.nextZ,a--):(i=r,r=r.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;n=r}o.nextZ=null,l*=2}while(s>1)}(i)}(t,l,h,f);for(var p,v,d=t;t.prev!==t.next;)if(p=t.prev,v=t.next,f?o(t,l,h,f):i(t))e.push(p.i/u|0),e.push(t.i/u|0),e.push(v.i/u|0),b(t),t=v.next,d=v.next;else if((t=v)===d){g?1===g?r(t=s(n(t),e,u),e,u,l,h,f,2):2===g&&a(t,e,u,l,h,f):r(n(t),e,u,l,h,f,1);break}}}function i(t){var e=t.prev,n=t,r=t.next;if(v(e,n,r)>=0)return!1;for(var i=e.x,o=n.x,s=r.x,a=e.y,u=n.y,l=r.y,h=io?i>s?i:s:o>s?o:s,p=a>u?a>l?a:l:u>l?u:l,d=r.next;d!==e;){if(d.x>=h&&d.x<=f&&d.y>=c&&d.y<=p&&g(i,a,o,u,s,l,d.x,d.y)&&v(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function o(t,e,n,r){var i=t.prev,o=t,s=t.next;if(v(i,o,s)>=0)return!1;for(var a=i.x,u=o.x,l=s.x,h=i.y,f=o.y,p=s.y,d=au?a>l?a:l:u>l?u:l,_=h>f?h>p?h:p:f>p?f:p,x=c(d,y,e,n,r),E=c(m,_,e,n,r),k=t.prevZ,b=t.nextZ;k&&k.z>=x&&b&&b.z<=E;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;if(k=k.prevZ,b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;k&&k.z>=x;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;k=k.prevZ}for(;b&&b.z<=E;){if(b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function s(t,e,r){var i=t;do{var o=i.prev,s=i.next.next;!d(o,s)&&y(o,i,i.next,s)&&x(o,s)&&x(s,o)&&(e.push(o.i/r|0),e.push(i.i/r|0),e.push(s.i/r|0),b(i),b(i.next),i=t=s),i=i.next}while(i!==t);return n(i)}function a(t,e,i,o,s,a){var u=t;do{for(var l=u.next.next;l!==u.prev;){if(u.i!==l.i&&p(u,l)){var h=E(u,l);return u=n(u,u.next),h=n(h,h.next),r(u,e,i,o,s,a,0),void r(h,e,i,o,s,a,0)}l=l.next}u=u.next}while(u!==t)}function u(t,e){return t.x-e.x}function l(t,e){var r=function(t,e){var n,r=e,i=t.x,o=t.y,s=-1/0;do{if(o<=r.y&&o>=r.next.y&&r.next.y!==r.y){var a=r.x+(o-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=i&&a>s&&(s=a,n=r.x=r.x&&r.x>=c&&i!==r.x&&g(on.x||r.x===n.x&&h(n,r)))&&(n=r,p=u)),r=r.next}while(r!==l);return n}(t,e);if(!r)return e;var i=E(r,t);return n(i,i.next),n(r,r.next)}function h(t,e){return v(t.prev,t,e.prev)<0&&v(e.next,t,t.next)<0}function c(t,e,n,r,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function f(t){var e=t,n=t;do{(e.x=(t-s)*(o-a)&&(t-s)*(r-a)>=(n-s)*(e-a)&&(n-s)*(o-a)>=(i-s)*(r-a)}function p(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&y(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(x(t,e)&&x(e,t)&&function(t,e){var n=t,r=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{n.y>o!=n.next.y>o&&n.next.y!==n.y&&i<(n.next.x-n.x)*(o-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==t);return r}(t,e)&&(v(t.prev,t,e.prev)||v(t,e.prev,e))||d(t,e)&&v(t.prev,t,t.next)>0&&v(e.prev,e,e.next)>0)}function v(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function d(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,n,r){var i=_(v(t,e,n)),o=_(v(t,e,r)),s=_(v(n,r,t)),a=_(v(n,r,e));return i!==o&&s!==a||(!(0!==i||!m(t,n,e))||(!(0!==o||!m(t,r,e))||(!(0!==s||!m(n,t,r))||!(0!==a||!m(n,e,r)))))}function m(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function _(t){return t>0?1:t<0?-1:0}function x(t,e){return v(t.prev,t,t.next)<0?v(t,e,t.next)>=0&&v(t,t.prev,e)>=0:v(t,e,t.prev)<0||v(t,t.next,e)<0}function E(t,e){var n=new w(t.i,t.x,t.y),r=new w(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,n.next=i,i.prev=n,r.next=n,n.prev=r,o.next=r,r.prev=o,r}function k(t,e,n,r){var i=new w(t,e,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function b(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 w(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function I(t,e,n,r){for(var i=0,o=e,s=n-r;o0&&(r+=t[i-1].length,n.holes.push(r))}return n},bl.exports}(),Il=mn(wl);function Nl(t){var e=function(t){for(var e=t[0][0].length,n={vertices:[],holes:[],dimensions:e},r=0,i=0;i0&&(r+=t[i-1].length,n.holes.push(r))}return n}(t),n=Il(e.vertices,e.holes,2),r=[],i=[];n.forEach((function(t,r){var o=n[r];i.push([e.vertices[2*o],e.vertices[2*o+1]])}));for(var o=0;o=1||u<=0||l>=1||l<=0))){var v=p,d=!o[v];d&&(o[v]=!0),e?i.push(e(p,t,n,h,c,u,s,a,f,g,l,d)):i.push(p)}}function v(t,e){var n,i,o,s,a=r[t][e],u=r[t][e+1];return a[0]f[e.isect].coord?-1:1}));for(l=[];x.length>0;){var I=x.pop(),N=I.isect,M=I.parent,L=I.winding,P=l.length,T=[f[N].coord],O=N;if(f[N].ringAndEdge1Walkable)var R=f[N].ringAndEdge1,A=f[N].nxtIsectAlongRingAndEdge1;else R=f[N].ringAndEdge2,A=f[N].nxtIsectAlongRingAndEdge2;for(;!Rl(f[N].coord,f[A].coord);){T.push(f[A].coord);var D=void 0;for(r=0;r1)for(e=0;e=0==e}function Ol(t){for(var e=0,n=0;n0)){if(o/=f,f<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=r-u,f||!(o<0)){if(o/=f,f<0){if(o>c)return;o>h&&(h=o)}else if(f>0){if(o0)){if(o/=g,g<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=i-l,g||!(o<0)){if(o/=g,g<0){if(o>c)return;o>h&&(h=o)}else if(g>0){if(o0||c<1)||(h>0&&(t[0]=[u+h*f,l+h*g]),c<1&&(t[1]=[u+c*f,l+c*g]),!0)}}}}}function Hl(t,e,n,r,i){var o=t[1];if(o)return!0;var s,a,u=t[0],l=t.left,h=t.right,c=l[0],f=l[1],g=h[0],p=h[1],v=(c+g)/2,d=(f+p)/2;if(p===f){if(v=r)return;if(c>g){if(u){if(u[1]>=i)return}else u=[v,n];o=[v,i]}else{if(u){if(u[1]1)if(c>g){if(u){if(u[1]>=i)return}else u=[(n-a)/s,n];o=[(i-a)/s,i]}else{if(u){if(u[1]=r)return}else u=[e,s*e+a];o=[r,s*r+a]}else{if(u){if(u[0]=-dh)){var g=u*u+l*l,p=h*h+c*c,v=(c*g-l*p)/f,d=(u*p-h*g)/f,y=$l.pop()||new th;y.arc=t,y.site=i,y.x=v+s,y.y=(y.cy=d+a)+Math.sqrt(v*v+d*d),t.circle=y;for(var m=null,_=gh._;_;)if(y.y<_.y||y.y===_.y&&y.x<=_.x){if(!_.L){m=_.P;break}_=_.L}else{if(!_.R){m=_;break}_=_.R}gh.insert(m,y),m||(Ql=y)}}}}function nh(t){var e=t.circle;e&&(e.P||(Ql=e.N),gh.remove(e),$l.push(e),Gl(e),t.circle=null)}var rh=[];function ih(){Gl(this),this.edge=this.site=this.circle=null}function oh(t){var e=rh.pop()||new ih;return e.site=t,e}function sh(t){nh(t),ch.remove(t),rh.push(t),Gl(t)}function ah(t){var e=t.circle,n=e.x,r=e.cy,i=[n,r],o=t.P,s=t.N,a=[t];sh(t);for(var u=o;u.circle&&Math.abs(n-u.circle.x)vh)a=a.L;else{if(!((i=o-hh(a,s))>vh)){r>-vh?(e=a.P,n=a):i>-vh?(e=a,n=a.N):e=n=a;break}if(!a.R){e=a;break}a=a.R}!function(t){fh[t.index]={site:t,halfedges:[]}}(t);var u=oh(t);if(ch.insert(e,u),e||n){if(e===n)return nh(e),n=oh(e.site),ch.insert(u,n),u.edge=n.edge=jl(e.site,u.site),eh(e),void eh(n);if(n){nh(e),nh(n);var l=e.site,h=l[0],c=l[1],f=t[0]-h,g=t[1]-c,p=n.site,v=p[0]-h,d=p[1]-c,y=2*(f*d-g*v),m=f*f+g*g,_=v*v+d*d,x=[(d*m-g*_)/y+h,(f*_-v*m)/y+c];Ul(n.edge,l,p,x),u.edge=jl(l,t,null,x),n.edge=jl(t,p,null,x),eh(e),eh(n)}else u.edge=jl(e.site,u.site)}}function lh(t,e){var n=t.site,r=n[0],i=n[1],o=i-e;if(!o)return r;var s=t.P;if(!s)return-1/0;var a=(n=s.site)[0],u=n[1],l=u-e;if(!l)return a;var h=a-r,c=1/o-1/l,f=h/l;return c?(-f+Math.sqrt(f*f-2*c*(h*h/(-2*l)-u+l/2+i-o/2)))/c+r:(r+a)/2}function hh(t,e){var n=t.N;if(n)return lh(n,e);var r=t.site;return r[1]===e?r[0]:1/0}var ch,fh,gh,ph,vh=1e-6,dh=1e-12;function yh(t,e){return e[1]-t[1]||e[0]-t[0]}function mh(t,e){var n,r,i,o=t.sort(yh).pop();for(ph=[],fh=new Array(t.length),ch=new Vl,gh=new Vl;;)if(i=Ql,o&&(!i||o[1]vh||Math.abs(i[0][1]-i[1][1])>vh)||delete ph[o]}(s,a,u,l),function(t,e,n,r){var i,o,s,a,u,l,h,c,f,g,p,v,d=fh.length,y=!0;for(i=0;ivh||Math.abs(v-f)>vh)&&(u.splice(a,0,ph.push(Xl(s,g,Math.abs(p-t)vh?[t,Math.abs(c-t)vh?[Math.abs(f-r)vh?[n,Math.abs(c-n)vh?[Math.abs(f-e)=a)return null;var u=t-i.site[0],l=e-i.site[1],h=u*u+l*l;do{i=o.cells[r=s],s=null,i.halfedges.forEach((function(n){var r=o.edges[n],a=r.left;if(a!==i.site&&a||(a=r.right)){var u=t-a[0],l=e-a[1],c=u*u+l*l;c2&&void 0!==arguments[2]?arguments[2]:{},r=rt(t).coordinates,i=0,o=0;o=i&&o===r.length-1);o++){if(i>=e){var s=e-i;if(s){var a=st(r[o],r[o-1])-180;return at(r[o],s,a,n)}return I(r[o])}i+=ut(r[o],r[o+1],n)}return I(r[r.length-1])},t.angle=function(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!Z(r))throw new Error("options is invalid");if(!t)throw new Error("startPoint is required");if(!e)throw new Error("midPoint is required");if(!n)throw new Error("endPoint is required");var i=t,o=e,s=n,a=G(!0!==r.mercator?st(o,i):lt(o,i)),u=G(!0!==r.mercator?st(o,s):lt(o,s));u1&&void 0!==arguments[1]?arguments[1]:{},n=e.resolution||1e4,r=e.sharpness||.85,i=[],o=rt(t).coordinates.map((function(t){return{x:t[0],y:t[1]}})),s=new Gt({duration:n,points:o,sharpness:r}),a=function(t){var e=s.pos(t);Math.floor(t/100)%2==0&&i.push([e.x,e.y])},u=0;u0;else if(n!==u>0)return!0}return!1},t.booleanContains=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type,s=n.coordinates,u=r.coordinates;switch(i){case"Point":if("Point"===o)return Ht(s,u);throw new Error("feature2 "+o+" geometry not supported");case"MultiPoint":switch(o){case"Point":return function(t,e){var n,r=!1;for(n=0;n2&&void 0!==arguments[2]?arguments[2]:{}).precision;if("number"!=typeof(n=null==n||isNaN(n)?6:n)||!(n>=0))throw new Error("precision must be a positive number");return rt(t).type===rt(e).type&&Ne(Le(t),Le(e),{precision:n})},t.booleanIntersects=Oe,t.booleanOverlap=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;if("MultiPoint"===i&&"MultiPoint"!==o||("LineString"===i||"MultiLineString"===i)&&"LineString"!==o&&"MultiLineString"!==o||("Polygon"===i||"MultiPolygon"===i)&&"Polygon"!==o&&"MultiPolygon"!==o)throw new Error("features must be of the same type");if("Point"===i)throw new Error("Point geometry not supported");if(Ne(t,e,{precision:6}))return!1;var s=0;switch(i){case"MultiPoint":for(var a=0;a0},t.booleanParallel=function(t,e){if(!t)throw new Error("line1 is required");if(!e)throw new Error("line2 is required");if("LineString"!==In(t,"line1"))throw new Error("line1 must be a LineString");if("LineString"!==In(e,"line2"))throw new Error("line2 must be a LineString");for(var n=$e(Le(t)).features,r=$e(Le(e)).features,i=0;i1;case"MultiPoint":for(var i=0;i0&&ue(S([r[0]]),S([r[i]])).features.length>1)return!1}return!0;case"MultiPolygon":for(i=0;i0&&ue(S([o[0]]),S([o[s]])).features.length>1)return!1}return!0;default:return!1}},t.booleanWithin=Cn,t.buffer=function(t,e,n){var r=(n=n||{}).units||"kilometers",i=n.steps||8;if(!t)throw new Error("geojson is required");if("object"!==m(n))throw new Error("options must be an object");if("number"!=typeof i)throw new Error("steps must be an number");if(void 0===e)throw new Error("radius is required");if(i<=0)throw new Error("steps must be greater than 0");var o=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){var n=ui(t,e,r,i);n&&o.push(n)})),C(o);case"FeatureCollection":return vt(t,(function(t){var n=ui(t,e,r,i);n&&vt(n,(function(t){t&&o.push(t)}))})),C(o)}return ui(t,e,r,i)},t.center=An,t.centerMean=fi,t.centerMedian=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.counter||10;if(!U(n))throw new Error("counter must be a number");var r=e.weight,i=fi(t,{weight:e.weight}),o=C([]);vt(t,(function(t){var e;o.features.push(gi(t,{properties:{weight:null==(e=t.properties)?void 0:e[r]}}))}));var s={tolerance:e.tolerance,medianCandidates:[]};return pi(i.geometry.coordinates,[0,0],o,s,n)},t.centerOfMass=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(it(e)){case"Point":return I(K(e),n.properties);case"Polygon":var r=[];ct(e,(function(t){r.push(t)}));var i,o,s,a,u,l,h,c,f=gi(e,{properties:n.properties}),g=f.geometry.coordinates,p=0,v=0,d=0,y=r.map((function(t){return[t[0]-g[0],t[1]-g[1]]}));for(i=0;i2&&void 0!==arguments[2]?arguments[2]:{};!0!==n.mutate&&(t=Ai(t));var r=n.minPoints||3,i=V(e,n.units),o=new to(t.features.length),s=t.features.map((function(t){return!1})),a=t.features.map((function(t){return!1})),u=t.features.map((function(t){return!1})),l=t.features.map((function(t){return-1}));o.load(t.features.map((function(t,e){var n=v(t.geometry.coordinates,2),r=n[0],i=n[1];return{minX:r,minY:i,maxX:r,maxY:i,index:e}})));var h=function(n){var r=t.features[n],s=v(r.geometry.coordinates,2),a=s[0],u=s[1],l=Math.max(u-i,-90),h=Math.min(u+i,90),c=l<0&&h>0?i:Math.abs(l)=r){var i=c;c++,s[e]=!0,function(t,e){for(var n=0;n=r&&e.push.apply(e,d(o))}a[i]||(a[i]=!0,l[i]=t)}}(i,n)}else u[e]=!0}})),t.features.forEach((function(e,n){var r=t.features[n];r.properties||(r.properties={}),l[n]>=0?(r.properties.dbscan=u[n]?"edge":"core",r.properties.cluster=l[n]):r.properties.dbscan="noise"})),t},t.clustersKmeans=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.features.length;e.numberOfClusters=e.numberOfClusters||Math.round(Math.sqrt(n/2)),e.numberOfClusters>n&&(e.numberOfClusters=n),!0!==e.mutate&&(t=Ai(t));var r=yt(t),i=r.slice(0,e.numberOfClusters),o=ro(r,e.numberOfClusters,i),s={};return o.centroids.forEach((function(t,e){s[e]=t})),vt(t,(function(t,e){var n=o.idxs[e];t.properties.cluster=n,t.properties.centroid=s[n]})),t},t.collect=function(t,e,n,r){var i=new io(6),o=e.features.map((function(t){var e;return{minX:t.geometry.coordinates[0],minY:t.geometry.coordinates[1],maxX:t.geometry.coordinates[0],maxY:t.geometry.coordinates[1],property:null==(e=t.properties)?void 0:e[n]}}));return i.load(o),t.features.forEach((function(t){t.properties||(t.properties={});var e=Rt(t),n=i.search({minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}),o=[];n.forEach((function(e){zt([e.minX,e.minY],t)&&o.push(e.property)})),t.properties[r]=o})),t},t.collectionOf=nt,t.combine=function(t){var e={MultiPoint:{coordinates:[],properties:[]},MultiLineString:{coordinates:[],properties:[]},MultiPolygon:{coordinates:[],properties:[]}};return vt(t,(function(t){var n,r,i,o;switch(null==(o=t.geometry)?void 0:o.type){case"Point":e.MultiPoint.coordinates.push(t.geometry.coordinates),e.MultiPoint.properties.push(t.properties);break;case"MultiPoint":(n=e.MultiPoint.coordinates).push.apply(n,d(t.geometry.coordinates)),e.MultiPoint.properties.push(t.properties);break;case"LineString":e.MultiLineString.coordinates.push(t.geometry.coordinates),e.MultiLineString.properties.push(t.properties);break;case"MultiLineString":(r=e.MultiLineString.coordinates).push.apply(r,d(t.geometry.coordinates)),e.MultiLineString.properties.push(t.properties);break;case"Polygon":e.MultiPolygon.coordinates.push(t.geometry.coordinates),e.MultiPolygon.properties.push(t.properties);break;case"MultiPolygon":(i=e.MultiPolygon.coordinates).push.apply(i,d(t.geometry.coordinates)),e.MultiPolygon.properties.push(t.properties)}})),C(Object.keys(e).filter((function(t){return e[t].coordinates.length})).sort().map((function(t){return b({type:t,coordinates:e[t].coordinates},{collectedProperties:e[t].properties})})))},t.concave=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.maxEdge||1/0,r=function(t){var e=[],n={};return vt(t,(function(t){if(t.geometry){var r=t.geometry.coordinates.join("-");Object.prototype.hasOwnProperty.call(n,r)||(e.push(t),n[r]=!0)}})),C(e)}(t),i=oo(r);if(i.features=i.features.filter((function(t){var r=t.geometry.coordinates[0][0],i=t.geometry.coordinates[0][1],o=t.geometry.coordinates[0][2],s=ut(r,i,e),a=ut(i,o,e),u=ut(r,o,e);return s<=n&&a<=n&&u<=n})),i.features.length<1)return null;var o=Ro(i);return 1===o.coordinates.length&&(o.coordinates=o.coordinates[0],o.type="Polygon"),b(o)},t.containsNumber=$,t.convertArea=X,t.convertLength=j,t.convex=Oi,t.coordAll=yt,t.coordEach=ct,t.coordReduce=ft,t.createBins=zi,t.degreesToRadians=z,t.destination=at,t.difference=function(t){var e=[];if(mt(t,(function(t){e.push(t.coordinates)})),e.length<2)throw new Error("Must have at least two features");var n=t.features[0].properties||{},r=As.apply(Fs,[e[0]].concat(d(e.slice(1))));return 0===r.length?null:1===r.length?S(r[0],n):R(r,n)},t.dissolve=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.propertyName;nt(t,"Polygon","dissolve");var r=[];if(!n)return qs(R(Os.apply(null,t.features.map((function(t){return t.geometry.coordinates})))));var i={};vt(t,(function(t){t.properties&&(Object.prototype.hasOwnProperty.call(i,t.properties[n])||(i[t.properties[n]]=[]),i[t.properties[n]].push(t))}));for(var o=Object.keys(i),s=0;s1&&void 0!==arguments[1]?arguments[1]:{},o=i.properties,s=null==(e=i.autoComplete)||e,a=null==(n=i.orderCoords)||n;if(null!=(r=i.mutate)&&r||(t=Ai(t)),"FeatureCollection"===t.type){var u=[];return t.features.forEach((function(t){u.push(Q(ru(t,{},s,a)))})),R(u,o)}return ru(t,o,s,a)},t.mask=function(t,e,n){var r,i=null!=(r=null==n?void 0:n.mutate)&&r,o=e;e&&!1===i&&(o=Ai(e));var s,a=su(o);return("FeatureCollection"===t.type?ou(2===(s=t).features.length?Os(s.features[0].geometry.coordinates,s.features[1].geometry.coordinates):Os.apply(Fs,s.features.map((function(t){return t.geometry.coordinates})))):"Feature"===t.type?ou(Os(t.geometry.coordinates)):ou(Os(t.coordinates))).geometry.coordinates.forEach((function(t){a.geometry.coordinates.push(t[0])})),a},t.meta=Mt,t.midpoint=function(t,e){return at(t,ut(t,e)/2,st(t,e))},t.moranIndex=function(t,e){var n,r,i=e.inputField,o=e.threshold||1e5,s=e.p||2,u=null!=(n=e.binary)&&n,l=Gs(t,{alpha:e.alpha||-1,binary:u,p:s,standardization:null==(r=e.standardization)||r,threshold:o}),h=[];vt(t,(function(t){var e=t.properties||{};h.push(e[i])}));for(var c=au(h),f=function(t){var e,n=au(t),r=0,i=a(t);try{for(i.s();!(e=i.n()).done;){var o=e.value;r+=Math.pow(o-n,2)}}catch(t){i.e(t)}finally{i.f()}return r/t.length}(h),g=0,p=0,v=0,d=0,y=l.length,m=0;m2&&void 0!==arguments[2]?arguments[2]:{},r=n.units,i=n.properties||{},o=function(t){var e=[];switch(t.geometry?t.geometry.type:t.type){case"GeometryCollection":return mt(t,(function(t){"Point"===t.type&&e.push({type:"Feature",properties:{},geometry:t})})),{type:"FeatureCollection",features:e};case"FeatureCollection":return t.features=t.features.filter((function(t){return"Point"===t.geometry.type})),t;default:throw new Error("points must be a Point Collection")}}(t);if(!o.features.length)throw new Error("points must contain features");if(!e)throw new Error("line is required");if("LineString"!==it(e))throw new Error("line must be a LineString");var s=1/0,a=null;return vt(o,(function(t){var n=mu(t,e,{units:r});n2&&void 0!==arguments[2]?arguments[2]:{},a=null!=(i=s.method)?i:"geodesic",u=null!=(o=s.units)?o:"kilometers";if(!e)throw new Error("point is required");if(!r)throw new Error("polygon or multi-polygon is required");var l,h=rt(r);if("MultiPolygon"===h.type){var c=h.coordinates.map((function(n){return t(e,S(n),{method:a,units:u})}));return Math.min.apply(Math,d(c.map(Math.abs)))*(zt(e,r)?-1:1)}if(h.coordinates.length>1){var p=h.coordinates.map((function(n){return t(e,S([n]),{method:a,units:u})})),v=n(l=p)||f(l)||_(l)||g(),y=v[0],m=v.slice(1);if(y>=0)return y;var x=Math.min.apply(Math,d(m));return x<0?Math.abs(x):Math.min(x,Math.abs(y))}var E=le(h),k=1/0;return xt(E,(function(t){k=Math.min(k,mu(e,t,{method:a,units:u}))})),zt(e,h)?-k:k},t.points=N,t.pointsWithinPolygon=Su,t.polygon=S,t.polygonSmooth=function(t,e){(e=e||{}).iterations=e.iterations||1;var n=e.iterations,r=[];if(!t)throw new Error("inputPolys is required");return mt(t,(function(t,e,i){if("Polygon"===t.type){for(var o=[[]],s=0;s0&&(u=S(o).geometry),Ru(u,a),o=a.slice(0)}r.push(S(o,i))}else{if("MultiPolygon"!==t.type)throw new Error("geometry is invalid, must be Polygon or MultiPolygon");for(var l=[[[]]],h=0;h0&&(f=R(l).geometry),Au(f,c),l=c.slice(0)}r.push(R(l,i))}})),C(r)},t.polygonTangents=function(t,e){var n,r=Q(t),i=Q(e),o=[],s=[],a=Rt(e),u=0,l=null;switch(r[0]>a[0]&&r[0]a[1]&&r[1]_&&(_=k)}for(var b=[],w=Object.keys(l).length,I=f/w,N=0,S=0;S<_+1;S++)N+=Math.exp(-I)*Math.pow(I,S)/Zu(S),b.push(N);for(var M=[],L=0,P=0;P<_+1;P++){for(var C=0,T=Object.keys(l);CR&&(R=D)}var F=Xu[r]/Math.sqrt(w),q={criticalValue:F,isRandom:!0,maxAbsoluteDifference:R,observedDistribution:M};return R>F&&(q.isRandom=!1),q},t.radiansToDegrees=Y,t.radiansToLength=F,t.random=nl,t.randomLineString=$u,t.randomPoint=Ku,t.randomPolygon=Qu,t.randomPosition=Hu,t.rectangleGrid=oa,t.rewind=function(t){var e,n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(r=r||{}))throw new Error("options is invalid");var i=null!=(e=r.mutate)&&e,o=null!=(n=r.reverse)&&n;if(!t)throw new Error(" is required");if("boolean"!=typeof o)throw new Error(" must be a boolean");if("boolean"!=typeof i)throw new Error(" must be a boolean");i||"Point"===t.type||"MultiPoint"===t.type||(t=Ai(t));var s=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){rl(t,o)})),t;case"FeatureCollection":return vt(t,(function(t){vt(rl(t,o),(function(t){s.push(t)}))})),C(s)}return rl(t,o)},t.rhumbBearing=lt,t.rhumbDestination=Bs,t.rhumbDistance=Ys,t.round=D,t.sample=function(t,e){if(!t)throw new Error("fc is required");if(null==e)throw new Error("num is required");if("number"!=typeof e)throw new Error("num must be a number");var n=C(function(t,e){var n,r,i=t.slice(0),o=t.length,s=o-e;for(;o-- >s;)n=i[r=Math.floor((o+1)*Math.random())],i[r]=i[o],i[o]=n;return i.slice(s)}(t.features,e));return n},t.sector=function(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!Z(i=i||{}))throw new Error("options is invalid");var o=i.properties;if(!t)throw new Error("center is required");if(null==n)throw new Error("bearing1 is required");if(null==r)throw new Error("bearing2 is required");if(!e)throw new Error("radius is required");if("object"!==m(i))throw new Error("options must be an object");if(sl(n)===sl(r))return Ri(t,e,i);var s=Q(t),a=ja(t,e,n,r,i),u=[[s]];return ct(a,(function(t){u[0].push(t)})),u[0].push(s),S(u,o)},t.segmentEach=kt,t.segmentReduce=bt,t.shortestPath=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.obstacles||C([]),i=n.resolution||100;if(!t)throw new Error("start is required");if(!e)throw new Error("end is required");if(i&&(!U(i)||i<=0))throw new Error("options.resolution must be a number, greater than 0");var o=K(t),s=K(e);if(t=I(o),e=I(s),"FeatureCollection"===r.type){if(0===r.features.length)return L([o,s])}else{if("Polygon"!==r.type)throw new Error("invalid obstacles");r=C([b(rt(r))])}var a=r;a.features.push(t),a.features.push(e);var u=v(Rt(al(Vt(Rt(a)),1.15)),4),l=u[0],h=u[1],c=u[2],f=u[3],g=ut([l,h],[c,h],n)/i;a.features.pop(),a.features.pop();for(var p,d,y=g/ut([l,h],[c,h],n)*(c-l),m=g/ut([l,h],[l,f],n)*(f-h),_=c-l,x=f-h,E=Math.floor(_/y),k=Math.floor(x/m),w=(_-E*y)/2,N=[],S=[],M=1/0,P=1/0,T=f-(x-k*m)/2,O=0;T>=h;){for(var R=[],A=[],D=l+w,F=0;D<=c;){var q=I([D,T]),V=pl(q,r);R.push(V?0:1),A.push(D+"|"+T);var G=ut(q,t);!V&&G1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(i=null!=i?i:{}))throw new Error("options is invalid");var o=null!=(e=i.tolerance)?e:1,s=null!=(n=i.highQuality)&&n,a=null!=(r=i.mutate)&&r;if(!t)throw new Error("geojson is required");if(o&&o<0)throw new Error("invalid tolerance");return!0!==a&&(t=Ai(t)),mt(t,(function(t){!function(t,e,n){var r=t.type;if("Point"===r||"MultiPoint"===r)return t;if(Le(t,{mutate:!0}),"GeometryCollection"!==r)switch(r){case"LineString":t.coordinates=ml(t.coordinates,e,n);break;case"MultiLineString":t.coordinates=t.coordinates.map((function(t){return ml(t,e,n)}));break;case"Polygon":t.coordinates=_l(t.coordinates,e,n);break;case"MultiPolygon":t.coordinates=t.coordinates.map((function(t){return _l(t,e,n)}))}}(t,o,s)})),t},t.square=Ka,t.squareGrid=sa,t.standardDeviationalEllipse=function(t,e){var n;if(!Z(e=e||{}))throw new Error("options is invalid");var r=e.steps||64,i=e.weight,o=e.properties||{};if(!U(r))throw new Error("steps must be a number");if(!Z(o))throw new Error("properties must be a number");var s=yt(t).length,a=fi(t,{weight:i}),u=0,l=0,h=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));u+=Math.pow(r.x,2)*n,l+=Math.pow(r.y,2)*n,h+=r.x*r.y*n}));var c=u-l,f=Math.sqrt(Math.pow(c,2)+4*Math.pow(h,2)),g=2*h,p=Math.atan((c+f)/g),v=180*p/Math.PI,d=0,y=0,m=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));d+=Math.pow(r.x*Math.cos(p)-r.y*Math.sin(p),2)*n,y+=Math.pow(r.x*Math.sin(p)+r.y*Math.cos(p),2)*n,m+=n}));var _=Math.sqrt(2*d/m),x=Math.sqrt(2*y/m),E=js(a,_,x,{units:"degrees",angle:v,steps:r,properties:o}),k=Su(t,C([E])),b={meanCenterCoordinates:Q(a),semiMajorAxis:_,semiMinorAxis:x,numberOfFeatures:s,angle:v,percentageWithinEllipse:100*yt(k).length/s};return E.properties=null!=(n=E.properties)?n:{},E.properties.standardDeviationalEllipse=b,E},t.tag=function(t,e,n,r){return t=Ai(t),e=Ai(e),vt(t,(function(t){t.properties||(t.properties={}),vt(e,(function(e){t.properties&&e.properties&&void 0===t.properties[r]&&zt(t,e)&&(t.properties[r]=e.properties[n])}))})),t},t.tesselate=function(t){if(!t.geometry||"Polygon"!==t.geometry.type&&"MultiPolygon"!==t.geometry.type)throw new Error("input must be a Polygon or MultiPolygon");var e={type:"FeatureCollection",features:[]};return"Polygon"===t.geometry.type?e.features=Nl(t.geometry.coordinates):t.geometry.coordinates.forEach((function(t){e.features=e.features.concat(Nl(t))})),e},t.tin=oo,t.toMercator=Vu,t.toWgs84=Gu,t.transformRotate=zs,t.transformScale=al,t.transformTranslate=function(t,e,n,r){if(!Z(r=r||{}))throw new Error("options is invalid");var i=r.units,o=r.zTranslation,s=r.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("distance is required");if(o&&"number"!=typeof o&&isNaN(o))throw new Error("zTranslation is not a number");if(o=void 0!==o?o:0,0===e&&0===o)return t;if(null==n||isNaN(n))throw new Error("direction is required");return e<0&&(e=-e,n+=180),!1!==s&&void 0!==s||(t=Ai(t)),ct(t,(function(t){var r=Q(Bs(t,e,n,{units:i}));t[0]=r[0],t[1]=r[1],o&&3===t.length&&(t[2]+=o)})),t},t.triangleGrid=aa,t.truncate=Qa,t.union=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must have at least 2 geometries");var r=Os.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)},t.unkinkPolygon=function(t){var e=[];return xt(t,(function(t){"Polygon"===t.geometry.type&&vt(Ll(t),(function(n){e.push(S(n.geometry.coordinates,t.properties))}))})),C(e)},t.validateBBox=H,t.validateId=W,t.voronoi=function(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox||[-180,-85,180,85];if(!t)throw new Error("points is required");if(!Array.isArray(n))throw new Error("bbox is invalid");return nt(t,"Point","points"),C(function(){var t=Fl,e=ql,n=null;function r(r){return new mh(r.map((function(n,i){var o=[Math.round(t(n,i,r)/vh)*vh,Math.round(e(n,i,r)/vh)*vh];return o.index=i,o.data=n,o})),n)}return r.polygons=function(t){return r(t).polygons()},r.links=function(t){return r(t).links()},r.triangles=function(t){return r(t).triangles()},r.x=function(e){return arguments.length?(t="function"==typeof e?e:Dl(+e),r):t},r.y=function(t){return arguments.length?(e="function"==typeof t?t:Dl(+t),r):e},r.extent=function(t){return arguments.length?(n=null==t?null:[[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]],r):n&&[[n[0][0],n[0][1]],[n[1][0],n[1][1]]]},r.size=function(t){return arguments.length?(n=null==t?null:[[0,0],[+t[0],+t[1]]],r):n&&[n[1][0]-n[0][0],n[1][1]-n[0][1]]},r}().x((function(t){return t.geometry.coordinates[0]})).y((function(t){return t.geometry.coordinates[1]})).extent([[n[0],n[1]],[n[2],n[3]]]).polygons(t.features).map((function(e,n){return Object.assign(function(t){return(t=t.slice()).push(t[0]),S([t])}(e),{properties:Fi(t.features[n].properties)})})))}})); diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl.js new file mode 100644 index 0000000..c0d6d59 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl.js @@ -0,0 +1,3910 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl.yaml b/docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl.yaml new file mode 100644 index 0000000..6a5c2f7 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl.yaml @@ -0,0 +1,65 @@ +dependencies: + - name: mapbox-gl-js + version: "3.15.0" + src: + href: "https://api.mapbox.com/mapbox-gl-js/v3.15.0/" + script: + - "mapbox-gl.js" + stylesheet: + - "mapbox-gl.css" + - name: mapbox-gl-draw + version: "1.5.0" + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.5.0/" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: mapbox-gl-geocoder + version: 5.0.0 + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/" + script: + - "mapbox-gl-geocoder.min.js" + stylesheet: + - "mapbox-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: mapbox-pmtiles + version: 1.1.0 + src: "htmlwidgets/lib/mapbox-pmtiles" + script: + - "pmtiles-source-optimized-v2.js" + - name: turf + version: "7.2.0" + src: "htmlwidgets/lib/turf" + script: + - "turf.min.js" + - name: turf-operations + version: "1.0.0" + src: "htmlwidgets" + script: + - "turf-operations.js" diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl_compare.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl_compare.js new file mode 100644 index 0000000..780fbd6 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl_compare.js @@ -0,0 +1,3192 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +HTMLWidgets.widget({ + name: "mapboxgl_compare", + + type: "output", + + factory: function (el, width, height) { + // Store maps and compare object to allow access during Shiny updates + let beforeMap, afterMap, compareControl, draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + if (typeof mapboxgl.Compare === "undefined") { + console.error("Mapbox GL Compare plugin is not loaded."); + return; + } + + // Register PMTiles source type if available + if (typeof MapboxPmTilesSource !== "undefined" && typeof pmtiles !== "undefined") { + try { + mapboxgl.Style.setSourceType(PMTILES_SOURCE_TYPE, MapboxPmTilesSource); + console.log("PMTiles support enabled for Mapbox GL JS Compare"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + // Create container divs for the maps + const beforeContainerId = `${el.id}-before`; + const afterContainerId = `${el.id}-after`; + + // Different HTML structure based on mode + if (x.mode === "sync") { + // Side-by-side sync mode + const containerStyle = + x.orientation === "horizontal" + ? `display: flex; flex-direction: column; width: 100%; height: 100%;` + : `display: flex; flex-direction: row; width: 100%; height: 100%;`; + + const mapStyle = + x.orientation === "horizontal" + ? `width: 100%; height: 50%; position: relative;` + : `width: 50%; height: 100%; position: relative;`; + + el.innerHTML = ` +
+
+
+
+ `; + } else { + // Default swipe mode + el.innerHTML = ` +
+
+ `; + } + + beforeMap = new mapboxgl.Map({ + container: beforeContainerId, + style: x.map1.style, + center: x.map1.center, + zoom: x.map1.zoom, + bearing: x.map1.bearing, + pitch: x.map1.pitch, + projection: x.map1.projection, + accessToken: x.map1.access_token, + ...x.map1.additional_params, + }); + + afterMap = new mapboxgl.Map({ + container: afterContainerId, + style: x.map2.style, + center: x.map2.center, + zoom: x.map2.zoom, + bearing: x.map2.bearing, + pitch: x.map2.pitch, + projection: x.map2.projection, + accessToken: x.map2.access_token, + ...x.map2.additional_params, + }); + + // Set the global access token + mapboxgl.accessToken = x.map1.access_token; + + if (x.mode === "swipe") { + // Only create the swiper in swipe mode + compareControl = new mapboxgl.Compare( + beforeMap, + afterMap, + `#${el.id}`, + { + mousemove: x.mousemove, + orientation: x.orientation, + }, + ); + + // Apply custom swiper color if provided + if (x.swiper_color) { + const swiperSelector = + x.orientation === "vertical" + ? ".mapboxgl-compare .compare-swiper-vertical" + : ".mapboxgl-compare .compare-swiper-horizontal"; + + const styleEl = document.createElement("style"); + styleEl.innerHTML = `${swiperSelector} { background-color: ${x.swiper_color}; }`; + document.head.appendChild(styleEl); + } + } else { + // For sync mode, we directly leverage the sync-move module's approach + + // Function to synchronize maps as seen in the mapbox-gl-sync-move module + const syncMaps = () => { + // Array of maps to sync + const maps = [beforeMap, afterMap]; + // Array of move event handlers + const moveHandlers = []; + + // Setup the sync between maps + maps.forEach((map, index) => { + // Create a handler for each map that syncs all other maps + moveHandlers[index] = (e) => { + // Disable all move events temporarily + maps.forEach((m, i) => { + m.off("move", moveHandlers[i]); + }); + + // Get the state from the map that triggered the event + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Apply this state to all other maps + maps + .filter((m, i) => i !== index) + .forEach((m) => { + m.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + }); + + // Re-enable move events + maps.forEach((m, i) => { + m.on("move", moveHandlers[i]); + }); + }; + + // Add the move handler to each map + map.on("move", moveHandlers[index]); + }); + }; + + // Initialize the sync + syncMaps(); + } + + // Ensure both maps resize correctly + beforeMap.on("load", function () { + beforeMap.resize(); + applyMapModifications(beforeMap, x.map1); + + // Setup Shiny event handlers for the before map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(beforeMap, el.id, "before"); + } + }); + + afterMap.on("load", function () { + afterMap.resize(); + applyMapModifications(afterMap, x.map2); + + // Setup Shiny event handlers for the after map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(afterMap, el.id, "after"); + } + + // Add compare-level legends after both maps are loaded + if (x.compare_legends && Array.isArray(x.compare_legends)) { + x.compare_legends.forEach(function(legendInfo) { + // Add CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendInfo.css; + legendCss.setAttribute("data-mapgl-legend-css", el.id); + document.head.appendChild(legendCss); + + // Create legend element + const legend = document.createElement("div"); + legend.innerHTML = legendInfo.html; + legend.classList.add("mapboxgl-legend"); + + // Append to the appropriate container based on target + if (legendInfo.target === "compare") { + // Append to the main compare container + el.appendChild(legend); + } else if (legendInfo.target === "before") { + // Append to the before map container + beforeMap.getContainer().appendChild(legend); + } else if (legendInfo.target === "after") { + // Append to the after map container + afterMap.getContainer().appendChild(legend); + } + }); + } + }); + + // Handle Shiny messages + if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler( + "mapboxgl-compare-proxy", + function (data) { + if (data.id !== el.id) return; + + // Get the message and determine which map to target + var message = data.message; + var map = message.map === "before" ? beforeMap : afterMap; + + if (!map) return; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Process the message based on type + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup( + e, + map, + message.layer.popup, + message.layer.id, + ); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = + clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + message.layer.tooltip, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error( + "Failed to add layer via proxy: ", + message.layer, + e, + ); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if ( + window._mapboxPopups && + window._mapboxPopups[message.layer_id] + ) { + window._mapboxPopups[message.layer_id].remove(); + delete window._mapboxPopups[message.layer_id]; + } + + if (map.getLayer(message.layer_id)) { + // Remove tooltip handlers + if ( + window._mapboxHandlers && + window._mapboxHandlers[message.layer_id] + ) { + const handlers = window._mapboxHandlers[message.layer_id]; + if (handlers.mousemove) { + map.off( + "mousemove", + message.layer_id, + handlers.mousemove, + ); + } + if (handlers.mouseleave) { + map.off( + "mouseleave", + message.layer_id, + handlers.mouseleave, + ); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer_id]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer_id] + ) { + map.off( + "click", + message.layer_id, + window._mapboxClickHandlers[message.layer_id], + ); + delete window._mapboxClickHandlers[message.layer_id]; + } + + // Remove the layer + map.removeLayer(message.layer_id); + } + if (map.getSource(message.layer_id)) { + map.removeSource(message.layer_id); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer_id]; + delete layerState.paintProperties[message.layer_id]; + delete layerState.layoutProperties[message.layer_id]; + delete layerState.tooltips[message.layer_id]; + delete layerState.popups[message.layer_id]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty( + message.layer, + message.name, + message.value, + ); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "add_legend") { + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + + // Append legend to the correct map container + const targetContainer = map.getContainer(); + targetContainer.appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Save the current view state + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Apply the new style + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + map.off("mousemove", layerId); + map.off("mouseleave", layerId); + + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on("mousemove", layerId, function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }); + + map.on("mouseleave", layerId, function () { + onMouseLeaveTooltip(map, tooltip); + }); + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + delete window._mapboxClickHandlers[layerId]; + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + + // Restore the view state after the style has loaded + map.once("style.load", function () { + map.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + + // Re-apply map modifications + if (map === beforeMap) { + applyMapModifications(map, x.map1); + } else { + applyMapModifications(map, x.map2); + } + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "navigation", control: nav }); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + customControlContainer.innerHTML = controlOptions.html; + customControlContainer.className = "mapboxgl-ctrl"; + if (controlOptions.className) { + customControlContainer.className += " " + controlOptions.className; + } + + // Create the custom control object + const customControl = { + onAdd: function(map) { + return customControlContainer; + }, + onRemove: function() { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild(customControlContainer); + } + } + }; + + map.addControl(customControl, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + + // Store control with proper type + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = + "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + const resetControlObj = { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }; + + map.addControl(resetControlObj, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "reset", control: resetControlObj }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(draw, message.source, map); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + if (map._mapgl_draw) { + const features = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + if (draw) { + if (map._mapgl_draw) map._mapgl_draw.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + if (draw) { + if (message.data.clear_existing) { + if (map._mapgl_draw) map._mapgl_draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "fullscreen", control: fullscreen }); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "scale", control: scaleControl }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(data.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(data.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(data.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(data.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "geolocate", control: geolocate }); + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "geocoder", control: geocoder }); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + + // Handle use_icon parameter + let className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + + if (message.use_icon) { + className += " icon-only"; + } + + layersControl.className = className; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `.layers-control { background-color: ${colors.background} !important; }`; + } + if (colors.text) { + css += `.layers-control a { color: ${colors.text} !important; }`; + } + if (colors.activeBackground) { + css += `.layers-control a.active { background-color: ${colors.activeBackground} !important; }`; + } + if (colors.activeText) { + css += `.layers-control a.active { color: ${colors.activeText} !important; }`; + } + if (colors.hoverBackground) { + css += `.layers-control a:hover { background-color: ${colors.hoverBackground} !important; }`; + } + if (colors.hoverText) { + css += `.layers-control a:hover { color: ${colors.hoverText} !important; }`; + } + if (colors.toggleButtonBackground) { + css += `.layers-control .toggle-button { background-color: ${colors.toggleButtonBackground} + !important; }`; + } + if (colors.toggleButtonText) { + css += `.layers-control .toggle-button { color: ${colors.toggleButtonText} !important; }`; + } + + styleEl.innerHTML = css; + document.head.appendChild(styleEl); + } + + document.getElementById(data.id).appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + message.layers || + map.getStyle().layers.map((layer) => layer.id); + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + toggleButton.textContent = "Layers"; + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "layers", control: layersControl }); + } else if (message.type === "add_globe_minimap") { + // Add the globe minimap control + const minimap = new MapboxGlobeMinimap({ + center: map.getCenter(), + zoom: map.getZoom(), + bearing: map.getBearing(), + pitch: map.getPitch(), + globeSize: message.globe_size, + landColor: message.land_color, + waterColor: message.water_color, + markerColor: message.marker_color, + markerSize: message.marker_size, + }); + + map.addControl(minimap, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "globe_minimap", control: minimap }); + } else if (message.type === "set_rain") { + if (message.rain) { + map.setRain(message.rain); + } else { + map.setRain(null); + } + } else if (message.type === "set_snow") { + if (message.snow) { + map.setSnow(message.snow); + } else { + map.setSnow(null); + } + } else if (message.type === "set_projection") { + map.setProjection(message.projection); + } else if (message.type === "set_source") { + if (map.getLayer(message.layer)) { + const sourceId = map.getLayer(message.layer).source; + map.getSource(sourceId).setData(JSON.parse(message.source)); + } + } else if (message.type === "set_tooltip") { + // Track tooltip state + layerState.tooltips[message.layer] = message.tooltip; + + if (map.getLayer(message.layer)) { + // Remove any existing tooltip handlers + map.off("mousemove", message.layer); + map.off("mouseleave", message.layer); + + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on("mousemove", message.layer, function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[message.tooltip]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }); + + map.on("mouseleave", message.layer, function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }); + } + } else if (message.type === "set_popup") { + // Track popup state + layerState.popups[message.layer] = message.popup; + + if (map.getLayer(message.layer)) { + // Remove any existing popup click handlers for this layer + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove any existing popup for this layer + if ( + window._mapboxPopups && + window._mapboxPopups[message.layer] + ) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Create new click handler for popup + const clickHandler = function (e) { + onClickPopup(e, map, message.popup, message.layer); + }; + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer] = clickHandler; + + // Add click handler + map.on("click", message.layer, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer, function () { + map.getCanvas().style.cursor = ""; + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } + } else if (message.type === "set_opacity") { + // Set opacity for all fill layers + const style = map.getStyle(); + if (style && style.layers) { + style.layers.forEach(function (layer) { + if (layer.type === "fill" && map.getLayer(layer.id)) { + map.setPaintProperty( + layer.id, + "fill-opacity", + message.opacity, + ); + } + }); + } + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection) + ); + } else if (message.type === "clear_controls") { + // Handle clear_controls for compare widgets + if (!message.controls || message.controls.length === 0) { + // Clear all controls + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + } + } + }, + ); + } + + function setupShinyEvents(map, parentId, mapType) { + // Set view state on move end + map.on("moveend", function () { + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_view", { + center: [center.lng, center.lat], + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + } + }); + + // Send clicked point coordinates to Shiny + map.on("click", function (e) { + // Check if this map's draw control is active and in a drawing mode + let isDrawing = false; + if (map._mapgl_draw && map._mapgl_draw.getMode) { + const mode = map._mapgl_draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + // Filter out draw layers + const nonDrawFeatures = features.filter(feature => + !feature.layer.id.includes('gl-draw') && + !feature.source.includes('gl-draw') + ); + + if (nonDrawFeatures.length > 0) { + const feature = nonDrawFeatures[0]; + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }); + } + } else { + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_feature_click", null); + } + } + } + + // Always send regular click event + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }); + } + }); + + // Add hover events if enabled for this map + const mapConfig = (mapType === "before") ? x.map1 : x.map2; + if (mapConfig.hover_events && mapConfig.hover_events.enabled) { + map.on("mousemove", function (e) { + if (window.Shiny) { + // Feature hover events + if (mapConfig.hover_events.features) { + const options = mapConfig.hover_events.layer_id + ? { layers: Array.isArray(mapConfig.hover_events.layer_id) + ? mapConfig.hover_events.layer_id + : mapConfig.hover_events.layer_id.split(',').map(id => id.trim()) } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if(features.length > 0) { + const feature = features[0]; + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } else { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + null + ); + } + } + + // Coordinate hover events + if (mapConfig.hover_events.coordinates) { + Shiny.setInputValue( + parentId + "_" + mapType + "_hover", + { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } + } + }); + } + } + + function applyMapModifications(map, mapData) { + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + // Note: tooltip handlers are already defined at the top of the file + + // Set config properties if provided + if (mapData.config_properties) { + mapData.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + // Process H3J sources if provided + if (mapData.h3j_sources) { + mapData.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + }); + } + + if (mapData.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + mapData.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setText(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + } + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + } + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (mapData.sources) { + mapData.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceConfig = { + type: "vector", + url: source.url, + }; + if (source.promoteId) { + sourceConfig.promoteId = source.promoteId; + } + map.addSource(source.id, sourceConfig); + } else if (source.type === "geojson") { + const geojsonData = source.data; + map.addSource(source.id, { + type: "geojson", + data: geojsonData, + generateId: true, + }); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + // Add layers if provided + if (mapData.layers) { + mapData.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + map.on("click", layer.id, function (e) { + const description = e.features[0].properties[layer.popup]; + + new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = e.features[0].id; + map.setFeatureState( + { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: true }, + ); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Set terrain if provided + if (mapData.terrain) { + map.setTerrain({ + source: mapData.terrain.source, + exaggeration: mapData.terrain.exaggeration, + }); + } + + // Set fog + if (mapData.fog) { + map.setFog(mapData.fog); + } + + // Set rain effect if provided + if (mapData.rain) { + map.setRain(mapData.rain); + } + + // Set snow effect if provided + if (mapData.snow) { + map.setSnow(mapData.snow); + } + + if (mapData.fitBounds) { + map.fitBounds(mapData.fitBounds.bounds, mapData.fitBounds.options); + } + if (mapData.flyTo) { + map.flyTo(mapData.flyTo); + } + if (mapData.easeTo) { + map.easeTo(mapData.easeTo); + } + if (mapData.setCenter) { + map.setCenter(mapData.setCenter); + } + if (mapData.setZoom) { + map.setZoom(mapData.setZoom); + } + + // Apply moveLayer operations if provided + if (mapData.moveLayer) { + mapData.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + if (mapData.jumpTo) { + map.jumpTo(mapData.jumpTo); + } + + // Add custom images if provided + if (mapData.images && Array.isArray(mapData.images)) { + mapData.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (mapData.images) { + console.error("mapData.images is not an array:", mapData.images); + } + + // Remove existing legends only from this specific map container + const mapContainer = map.getContainer(); + const existingLegends = mapContainer.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + + // Don't remove all legend styles globally - they might belong to other maps + // Only remove styles when the entire widget is being recreated + + if (mapData.legend_html && mapData.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = mapData.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", el.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = mapData.legend_html; + legend.classList.add("mapboxgl-legend"); + + // Append legend to the correct map container instead of main container + const mapContainer = map.getContainer(); + mapContainer.appendChild(legend); + } + + // Add fullscreen control if enabled + if ( + mapData.fullscreen_control && + mapData.fullscreen_control.enabled + ) { + const position = mapData.fullscreen_control.position || "top-right"; + map.addControl(new mapboxgl.FullscreenControl(), position); + } + + // Add navigation control if enabled + if (mapData.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: mapData.navigation_control.show_compass, + showZoom: mapData.navigation_control.show_zoom, + visualizePitch: mapData.navigation_control.visualize_pitch, + }); + map.addControl(nav, mapData.navigation_control.position); + } + + // Add scale control if enabled + if (mapData.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: mapData.scale_control.maxWidth, + unit: mapData.scale_control.unit, + }); + map.addControl(scaleControl, mapData.scale_control.position); + map.controls.push(scaleControl); + } + + // Add geolocate control if enabled + if (mapData.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: mapData.geolocate_control.positionOptions, + trackUserLocation: mapData.geolocate_control.trackUserLocation, + showAccuracyCircle: mapData.geolocate_control.showAccuracyCircle, + showUserLocation: mapData.geolocate_control.showUserLocation, + showUserHeading: mapData.geolocate_control.showUserHeading, + fitBoundsOptions: mapData.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, mapData.geolocate_control.position); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Helper function to generate draw styles based on parameters + function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "midpoint"], + ], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: [ + "all", + ["==", "meta", "vertex"], + ["==", "$type", "Point"], + ], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: [ + "all", + ["==", "meta", "vertex"], + ["==", "$type", "Point"], + ], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } + } + + // Add geocoder control if enabled + if (mapData.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...mapData.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + mapData.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + + // Add draw control if enabled + if (mapData.draw_control) { + if (mapData.draw_control && mapData.draw_control.enabled) { + let drawOptions = mapData.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (mapData.draw_control.styling) { + const generatedStyles = generateDrawStyles( + mapData.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (mapData.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + mapData.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (mapData.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (mapData.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, mapData.draw_control.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add custom mode buttons and styling + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + + // Add rectangle styling and button + if (mapData.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + drawControl.changeMode('draw_rectangle'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + } + + // Add radius styling and button + if (mapData.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + drawControl.changeMode('draw_radius'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + } + }, 100); + + // Add initial features if provided + if (mapData.draw_control.source) { + addSourceFeaturesToDraw(drawControl, mapData.draw_control.source, map); + } + + // Process any queued features + if (mapData.draw_features_queue) { + mapData.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + if (map._mapgl_draw) map._mapgl_draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (mapData.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (mapData.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${mapData.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + // Helper function for updating drawn features + function updateDrawnFeatures() { + if (HTMLWidgets.shinyMode && map._mapgl_draw) { + const features = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(features), + ); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + } + + // Add reset control if enabled + if (mapData.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: mapData.reset_control.animate, + }; + + if (mapData.reset_control.duration) { + initialView.duration = mapData.reset_control.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + mapData.reset_control.position, + ); + } + + // Add the layers control if provided + if (mapData.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = mapData.layers_control.control_id; + + // Handle use_icon parameter + let className = mapData.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + + layersControl.className = className; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = mapData.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + mapData.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = mapData.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (mapData.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + if (mapData.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + } + }, + + resize: function (width, height) { + // Code to handle resizing if necessary + }, + }; + }, +}); diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl_compare.yaml b/docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl_compare.yaml new file mode 100644 index 0000000..55f1563 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/mapboxgl_compare.yaml @@ -0,0 +1,57 @@ +dependencies: + - name: mapbox-gl-js + version: "3.15.0" + src: + href: "https://api.mapbox.com/mapbox-gl-js/" + script: + - "v3.15.0/mapbox-gl.js" + - "plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.js" + stylesheet: + - "v3.15.0/mapbox-gl.css" + - "plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.css" + - name: mapbox-gl-draw + version: "1.4.3" + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: mapbox-gl-geocoder + version: 5.0.0 + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/" + script: + - "mapbox-gl-geocoder.min.js" + stylesheet: + - "mapbox-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: mapbox-pmtiles + version: 1.1.0 + src: "htmlwidgets/lib/mapbox-pmtiles" + script: + - "pmtiles-source-optimized-v2.js" diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl.js new file mode 100644 index 0000000..5937d02 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl.js @@ -0,0 +1,5048 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + const result = originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + return result; + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse( + this.getAttribute("data-layer-ids"), + ); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } + } + }); +} diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl.yaml b/docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl.yaml new file mode 100644 index 0000000..f6679e5 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl.yaml @@ -0,0 +1,69 @@ +dependencies: + - name: maplibre-gl + version: "5.7.2" + src: "htmlwidgets/lib/maplibre-gl" + script: + - "maplibre-gl.js" + stylesheet: + - "maplibre-gl.css" + - name: mapbox-gl-draw + version: "1.5.0" + src: "htmlwidgets/lib/mapbox-gl-draw" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: maplibre-gl-geocoder + version: 1.5.0 + src: "htmlwidgets/lib/maplibre-gl-geocoder" + script: + - "maplibre-gl-geocoder.min.js" + stylesheet: + - "maplibre-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: h3j-h3t + version: 0.9.2 + src: "htmlwidgets/lib/h3j-h3t" + script: + - "h3j_h3t.js" + - name: maptiler-geocoding-control + version: 2.1.7 + src: "htmlwidgets/lib/maptiler-geocoding-control" + script: + - "maplibregl.umd.js" + stylesheet: + - "style.css" + - name: turf + version: "7.2.0" + src: "htmlwidgets/lib/turf" + script: + - "turf.min.js" + - name: turf-operations + version: "1.0.0" + src: "htmlwidgets" + script: + - "turf-operations.js" diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl_compare.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl_compare.js new file mode 100644 index 0000000..a0e0caf --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl_compare.js @@ -0,0 +1,4138 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case 'get': + return properties[expression[1]]; + case 'concat': + return expression.slice(1).map(item => evaluateExpression(item, properties)).join(''); + case 'to-string': + return String(evaluateExpression(expression[1], properties)); + case 'to-number': + return Number(evaluateExpression(expression[1], properties)); + case 'number-format': + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || 'en-US'; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty('min-fraction-digits')) { + formatOptions.minimumFractionDigits = options['min-fraction-digits']; + } + if (options.hasOwnProperty('max-fraction-digits')) { + formatOptions.maximumFractionDigits = options['max-fraction-digits']; + } + if (options.hasOwnProperty('min-integer-digits')) { + formatOptions.minimumIntegerDigits = options['min-integer-digits']; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty('useGrouping')) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(tooltipProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._maplibrePopups && window._maplibrePopups[layerId]) { + window._maplibrePopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._maplibrePopups) { + window._maplibrePopups = {}; + } + window._maplibrePopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on('close', function() { + if (window._maplibrePopups[layerId] === popup) { + delete window._maplibrePopups[layerId]; + } + }); +} + +HTMLWidgets.widget({ + name: "maplibregl_compare", + + type: "output", + + factory: function (el, width, height) { + // Store maps and compare object to allow access during Shiny updates + let beforeMap, afterMap, compareControl, draw; + + return { + renderValue: function (x) { + + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + if (typeof maplibregl.Compare === "undefined") { + console.error("Maplibre GL Compare plugin is not loaded."); + return; + } + + // Add PMTiles support + if (typeof pmtiles !== "undefined") { + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + } + + // Create container divs for the maps + const beforeContainerId = `${el.id}-before`; + const afterContainerId = `${el.id}-after`; + + // Different HTML structure based on mode + if (x.mode === "sync") { + // Side-by-side sync mode + const containerStyle = + x.orientation === "horizontal" + ? `display: flex; flex-direction: column; width: 100%; height: 100%;` + : `display: flex; flex-direction: row; width: 100%; height: 100%;`; + + const mapStyle = + x.orientation === "horizontal" + ? `width: 100%; height: 50%; position: relative;` + : `width: 50%; height: 100%; position: relative;`; + + el.innerHTML = ` +
+
+
+
+ `; + } else { + // Default swipe mode + el.innerHTML = ` +
+
+ `; + } + + beforeMap = new maplibregl.Map({ + container: beforeContainerId, + style: x.map1.style, + center: x.map1.center, + zoom: x.map1.zoom, + bearing: x.map1.bearing, + pitch: x.map1.pitch, + accessToken: x.map1.access_token, + ...x.map1.additional_params, + }); + + // Initialize controls array + beforeMap.controls = []; + + afterMap = new maplibregl.Map({ + container: afterContainerId, + style: x.map2.style, + center: x.map2.center, + zoom: x.map2.zoom, + bearing: x.map2.bearing, + pitch: x.map2.pitch, + accessToken: x.map2.access_token, + ...x.map2.additional_params, + }); + + // Initialize controls array + afterMap.controls = []; + + if (x.mode === "swipe") { + // Only create the swiper in swipe mode + compareControl = new maplibregl.Compare( + beforeMap, + afterMap, + `#${el.id}`, + { + mousemove: x.mousemove, + orientation: x.orientation, + }, + ); + + // Apply custom swiper color if provided + if (x.swiper_color) { + const swiperSelector = x.orientation === "vertical" ? + ".maplibregl-compare .compare-swiper-vertical" : + ".maplibregl-compare .compare-swiper-horizontal"; + + const styleEl = document.createElement('style'); + styleEl.innerHTML = `${swiperSelector} { background-color: ${x.swiper_color}; }`; + document.head.appendChild(styleEl); + } + } else { + // For sync mode, we directly leverage the sync-move module's approach + + // Function to synchronize maps as seen in the mapbox-gl-sync-move module + const syncMaps = () => { + // Array of maps to sync + const maps = [beforeMap, afterMap]; + // Array of move event handlers + const moveHandlers = []; + + // Setup the sync between maps + maps.forEach((map, index) => { + // Create a handler for each map that syncs all other maps + moveHandlers[index] = (e) => { + // Disable all move events temporarily + maps.forEach((m, i) => { + m.off("move", moveHandlers[i]); + }); + + // Get the state from the map that triggered the event + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Apply this state to all other maps + maps.filter((m, i) => i !== index).forEach( + (m) => { + m.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + }, + ); + + // Re-enable move events + maps.forEach((m, i) => { + m.on("move", moveHandlers[i]); + }); + }; + + // Add the move handler to each map + map.on("move", moveHandlers[index]); + }); + }; + + // Initialize the sync + syncMaps(); + } + + // Ensure both maps resize correctly + beforeMap.on("load", function () { + beforeMap.resize(); + applyMapModifications(beforeMap, x.map1); + + // Setup Shiny event handlers for the before map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(beforeMap, el.id, "before"); + } + }); + + afterMap.on("load", function () { + afterMap.resize(); + applyMapModifications(afterMap, x.map2); + + // Setup Shiny event handlers for the after map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(afterMap, el.id, "after"); + } + + // Add compare-level legends after both maps are loaded + if (x.compare_legends && Array.isArray(x.compare_legends)) { + x.compare_legends.forEach(function(legendInfo) { + // Add CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendInfo.css; + legendCss.setAttribute("data-mapgl-legend-css", el.id); + document.head.appendChild(legendCss); + + // Create legend element + const legend = document.createElement("div"); + legend.innerHTML = legendInfo.html; + legend.classList.add("mapboxgl-legend"); + + // Append to the appropriate container based on target + if (legendInfo.target === "compare") { + // Append to the main compare container + el.appendChild(legend); + } else if (legendInfo.target === "before") { + // Append to the before map container + beforeMap.getContainer().appendChild(legend); + } else if (legendInfo.target === "after") { + // Append to the after map container + afterMap.getContainer().appendChild(legend); + } + }); + } + }); + + // Define updateDrawnFeatures function for the draw tool + window.updateDrawnFeatures = function () { + if (draw) { + const features = draw.getAll(); + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(features), + ); + } + }; + + // Handle Shiny messages + if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler( + "maplibre-compare-proxy", + function (data) { + if (data.id !== el.id) return; + + // Get the message and determine which map to target + var message = data.message; + var map = + message.map === "before" ? beforeMap : afterMap; + + if (!map) return; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {} // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Process the message based on type + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "promoteId") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "data" && key !== "generateId") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "tiles" && key !== "tileSize" && key !== "maxzoom") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if ( + message.source.type === "raster-dem" + ) { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "tileSize" && key !== "maxzoom") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "coordinates") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "urls" && key !== "coordinates") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function(key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer( + message.layer, + message.layer.before_id, + ); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on( + "click", + message.layer.id, + clickHandler + ); + + // Change cursor to pointer when hovering over the layer + map.on( + "mouseenter", + message.layer.id, + function () { + map.getCanvas().style.cursor = + "pointer"; + }, + ); + + // Change cursor back to default when leaving the layer + map.on( + "mouseleave", + message.layer.id, + function () { + map.getCanvas().style.cursor = + ""; + }, + ); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + message.layer.tooltip, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on( + "mousemove", + message.layer.id, + mouseMoveHandler, + ); + map.on( + "mouseleave", + message.layer.id, + mouseLeaveHandler, + ); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[ + message.layer.id + ] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [ + key, + value, + ] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace( + /_/g, + "-", + ); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on( + "mousemove", + message.layer.id, + function (e) { + if (e.features.length > 0) { + if ( + hoveredFeatureId !== + null + ) { + const featureState = { + source: + typeof message + .layer + .source === + "string" + ? message + .layer + .source + : message + .layer + .id, + id: hoveredFeatureId, + }; + if ( + message.layer + .source_layer + ) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState( + featureState, + { + hover: false, + }, + ); + } + hoveredFeatureId = + e.features[0].id; + const featureState = { + source: + typeof message.layer + .source === + "string" + ? message.layer + .source + : message.layer + .id, + id: hoveredFeatureId, + }; + if ( + message.layer + .source_layer + ) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState( + featureState, + { + hover: true, + }, + ); + } + }, + ); + + map.on( + "mouseleave", + message.layer.id, + function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer + .source === + "string" + ? message.layer + .source + : message.layer + .id, + id: hoveredFeatureId, + }; + if ( + message.layer + .source_layer + ) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState( + featureState, + { + hover: false, + }, + ); + } + hoveredFeatureId = null; + }, + ); + + Object.keys(jsHoverOptions).forEach( + function (key) { + const originalPaint = + map.getPaintProperty( + message.layer.id, + key, + ) || + message.layer.paint[key]; + map.setPaintProperty( + message.layer.id, + key, + [ + "case", + [ + "boolean", + [ + "feature-state", + "hover", + ], + false, + ], + jsHoverOptions[key], + originalPaint, + ], + ); + }, + ); + } + } catch (e) { + console.error( + "Failed to add layer via proxy: ", + message.layer, + e, + ); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer_id and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer_id key + if (window._mapboxPopups[message.layer_id]) { + window._mapboxPopups[message.layer_id].remove(); + delete window._mapboxPopups[message.layer_id]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if (message.layer && message.layer.id && window._mapboxPopups[message.layer.id]) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer_id)) { + // Remove tooltip handlers + if ( + window._mapboxHandlers && + window._mapboxHandlers[message.layer_id] + ) { + const handlers = + window._mapboxHandlers[ + message.layer_id + ]; + if (handlers.mousemove) { + map.off( + "mousemove", + message.layer_id, + handlers.mousemove, + ); + } + if (handlers.mouseleave) { + map.off( + "mouseleave", + message.layer_id, + handlers.mouseleave, + ); + } + // Clean up the reference + delete window._mapboxHandlers[ + message.layer_id + ]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer_id key + if (window._mapboxClickHandlers[message.layer_id]) { + map.off( + "click", + message.layer_id, + window._mapboxClickHandlers[message.layer_id] + ); + delete window._mapboxClickHandlers[message.layer_id]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if (message.layer && message.layer.id && window._mapboxClickHandlers[message.layer.id]) { + map.off( + "click", + message.layer_id, + window._mapboxClickHandlers[message.layer.id] + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer_id); + } + if (map.getSource(message.layer_id)) { + map.removeSource(message.layer_id); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer_id]; + delete layerState.paintProperties[message.layer_id]; + delete layerState.layoutProperties[message.layer_id]; + delete layerState.tooltips[message.layer_id]; + delete layerState.popups[message.layer_id]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty( + message.layer, + message.name, + message.value, + ); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find( + (layer) => layer.id === layerId, + ); + const currentPaintProperty = + map.getPaintProperty(layerId, propertyName); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + [ + "boolean", + ["feature-state", "hover"], + false, + ], + hoverValue, + newValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + // No hover options, just set the new value directly + map.setPaintProperty( + layerId, + propertyName, + newValue, + ); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "add_legend") { + if (!message.add) { + const existingLegends = + document.querySelectorAll( + `#${data.id} .maplibregl-legend`, + ); + existingLegends.forEach((legend) => + legend.remove(), + ); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll(`style[data-mapgl-legend-css="${data.id}"]`); + legendStyles.forEach((style) => style.remove()); + } + + const legendCss = + document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute('data-mapgl-legend-css', data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("maplibregl-legend"); + + // Append legend to the correct map container + const targetContainer = map.getContainer(); + targetContainer.appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Save the current view state + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log("[MapGL Debug] Current style sources:", Object.keys(currentStyle.sources)); + console.log("[MapGL Debug] Current style layers:", currentStyle.layers.map(l => l.id)); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function(layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log("[MapGL Debug] Found source from test layer:", layer.source); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + + // If the paint property has a hover case, it's user-added + (layer.paint && Object.values(layer.paint).some(value => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover")) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = layerSource && layerSource.type === "vector" && ( + layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler") + ); + + if (!isBaseMapSource) { + console.log("[MapGL Debug] Found user source from layer:", layer.source); + userSourceIds.push(layer.source); + } else { + console.log("[MapGL Debug] Not adding base map source from layer:", layer.source); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if (source.url && typeof source.url === 'string' && + (source.url.includes("data:application/json") || + source.url.includes("blob:"))) { + console.log("[MapGL Debug] Found user source with data URL:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !(sourceId.startsWith("maptiler") && !sourceId.includes("user")) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) // Filter basemap sources but keep user ones + ) { + console.log("[MapGL Debug] Found user source via filtering:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find(l => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function(layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = layerSource && layerSource.type === "vector" && ( + layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler") + ); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log("[MapGL Debug] Including user layer:", layer.id, "source:", layer.source); + } else if (isBaseMapSource) { + console.log("[MapGL Debug] Excluding base map layer:", layer.id, "source:", layer.source); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function() { + // Re-add user sources + userSourceIds.forEach(function(sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function(layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log("[MapGL Debug] Re-adding mousemove handler for:", layer.id); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log("[MapGL Debug] Re-adding mouseleave handler for:", layer.id); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log("[MapGL Debug] Restoring tooltip for:", layerId); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function(e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = e.features[0].properties[tooltipProperty]; + tooltip.setLngLat(e.lngLat).setHTML(description).addTo(map); + } + }; + + const mouseLeaveHandler = function() { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if (Array.isArray(value) && value[0] === "case" && + Array.isArray(value[1]) && value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && value[1][1][1] === "hover") { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log("[MapGL Debug] Restoring tracked layer modifications"); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log("[MapGL Debug] Restoring filter for layer:", layerId); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log("[MapGL Debug] Restoring paint property:", layerId, propertyName, savedValue); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty(layerId, propertyName); + if (currentValue && Array.isArray(currentValue) && currentValue[0] === "case") { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log("[MapGL Debug] Restoring layout property:", layerId, propertyName, properties[propertyName]); + map.setLayoutProperty(layerId, propertyName, properties[propertyName]); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log("[MapGL Debug] Restoring tooltip:", layerId, tooltipProperty); + + // Remove existing tooltip handlers first + map.off("mousemove", layerId); + map.off("mouseleave", layerId); + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on("mousemove", layerId, function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }); + + map.on("mouseleave", layerId, function () { + onMouseLeaveTooltip(map, tooltip); + }); + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log("[MapGL Debug] Restoring popup:", layerId, popupProperty); + + // Remove existing popup handlers first + if (window._maplibreClickHandlers && window._maplibreClickHandlers[layerId]) { + map.off("click", layerId, window._maplibreClickHandlers[layerId]); + delete window._maplibreClickHandlers[layerId]; + } + + const clickHandler = function(e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + if (!window._maplibreClickHandlers) { + window._maplibreClickHandlers = {}; + } + window._maplibreClickHandlers[layerId] = clickHandler; + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off('style.load', onStyleLoad); + }; + + map.on('style.load', onStyleLoad); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map(id => ({id, source: currentStyle.sources[id]})), + layers: userLayers + }; + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function() { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = window._mapglPreservedData && window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log("[MapGL Debug] Backup restoration needed for layers"); + + // Re-add sources first + preserved.sources.forEach(function(src) { + try { + if (!map.getSource(src.id)) { + console.log("[MapGL Debug] Backup: adding source", src.id); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error("[MapGL Debug] Backup: error adding source", src.id, err); + } + }); + + // Then re-add layers + preserved.layers.forEach(function(layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Backup: adding layer", layer.id); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log("[MapGL Debug] Backup: restoring tooltip for", layer.id); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function(e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = e.features[0].properties[tooltipProperty]; + tooltip.setLngLat(e.lngLat).setHTML(description).addTo(map); + } + }; + + const mouseLeaveHandler = function() { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if (Array.isArray(value) && value[0] === "case" && + Array.isArray(value[1]) && value[1][0] === "boolean" && + value[1][1] && Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && value[1][1][1] === "hover") { + // This is a hover-enabled paint property + console.log("[MapGL Debug] Backup: restoring hover style for", layer.id, key); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Backup: error adding layer", layer.id, err); + } + }); + } else { + console.log("[MapGL Debug] Backup check: layers already restored properly"); + } + } + } catch (err) { + console.error("[MapGL Debug] Error in backup restoration:", err); + } + }, 500); // 500ms delay - faster recovery + } + } + + // Apply the new style + map.setStyle(message.style, { + diff: message.diff, + }); + + if (message.config) { + Object.keys(message.config).forEach( + function (key) { + map.setConfigProperty( + "basemap", + key, + message.config[key], + ); + }, + ); + } + + // Restore the view state after the style has loaded + map.once("style.load", function () { + map.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + + // Re-apply map modifications + if (map === beforeMap) { + applyMapModifications(map, x.map1); + } else { + applyMapModifications(map, x.map2); + } + }); + } else if ( + message.type === "add_navigation_control" + ) { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: + message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl.maplibregl-ctrl-group:not(.maplibre-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + map.controls.push({ type: "navigation", control: nav }); + } else if (message.type === "add_reset_control") { + const resetControl = + document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute( + "aria-label", + "Reset", + ); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = + "background-color 0.2s"; + resetControl.addEventListener( + "mouseover", + function () { + this.style.backgroundColor = "#f0f0f0"; + }, + ); + resetControl.addEventListener( + "mouseout", + function () { + this.style.backgroundColor = "white"; + }, + ); + + const resetContainer = + document.createElement("div"); + resetContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild( + resetContainer, + ); + }, + }, + message.position, + ); + // Add to controls array + map.controls.push(resetControl); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + if (message.freehand) { + drawOptions = Object.assign( + {}, + drawOptions, + { + modes: Object.assign( + {}, + MapboxDraw.modes, + { + draw_polygon: + MapboxDraw.modes + .draw_freehand, + }, + ), + }, + ); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on( + "draw.create", + window.updateDrawnFeatures, + ); + map.on( + "draw.delete", + window.updateDrawnFeatures, + ); + map.on( + "draw.update", + window.updateDrawnFeatures, + ); + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group", + ); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + } else if (message.type === "get_drawn_features") { + if (draw) { + const features = draw + ? draw.getAll() + : null; + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if ( + message.type === "clear_drawn_features" + ) { + if (draw) { + draw.deleteAll(); + // Update the drawn features + window.updateDrawnFeatures(); + } + } else if (message.type === "add_markers") { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: + marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker( + markerOptions, + ) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue( + data.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + + mapMarker.on("dragend", function () { + const lngLat = + mapMarker.getLngLat(); + Shiny.setInputValue( + data.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + }); + } + + window.maplibreglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreglMarkers) { + window.maplibreglMarkers.forEach( + function (marker) { + marker.remove(); + }, + ); + window.maplibreglMarkers = []; + } + } else if ( + message.type === "add_fullscreen_control" + ) { + const position = + message.position || "top-right"; + const fullscreen = + new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = + new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl( + scaleControl, + message.options.position, + ); + map.controls.push(scaleControl); + } else if ( + message.type === "add_geolocate_control" + ) { + const geolocate = + new maplibregl.GeolocateControl({ + positionOptions: + message.options.positionOptions, + trackUserLocation: + message.options.trackUserLocation, + showAccuracyCircle: + message.options.showAccuracyCircle, + showUserLocation: + message.options.showUserLocation, + showUserHeading: + message.options.showUserHeading, + fitBoundsOptions: + message.options.fitBoundsOptions, + }); + map.addControl( + geolocate, + message.options.position, + ); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue( + data.id + "_geolocate", + { + coords: event.coords, + time: new Date(), + }, + ); + }); + + geolocate.on( + "trackuserlocationstart", + function () { + Shiny.setInputValue( + data.id + "_geolocate_tracking", + { + status: "start", + time: new Date(), + }, + ); + }, + ); + + geolocate.on( + "trackuserlocationend", + function () { + Shiny.setInputValue( + data.id + "_geolocate_tracking", + { + status: "end", + time: new Date(), + }, + ); + }, + ); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue( + data.id + "_geolocate_error", + { + message: + "Location permission denied", + time: new Date(), + }, + ); + } + }); + } + } else if ( + message.type === "add_geocoder_control" + ) { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = + await fetch(request); + const geojson = + await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - + feature.bbox[0]) / + 2, + feature.bbox[1] + + (feature.bbox[3] - + feature.bbox[1]) / + 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: + feature.properties + .display_name, + properties: + feature.properties, + text: feature.properties + .display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error( + `Failed to forwardGeocode with error: ${e}`, + ); + } + + return { + features, + }; + }, + }; + + const geocoderOptions = { + maplibregl: maplibregl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if ( + typeof geocoderOptions.collapsed === + "undefined" + ) + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder( + geocoderApi, + geocoderOptions, + ); + } + + map.addControl( + geocoder, + message.options.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } else if (message.type === "add_layers_control") { + const layersControl = + document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = + document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `.layers-control { background-color: ${colors.background} !important; }`; + } + if (colors.text) { + css += `.layers-control a { color: ${colors.text} !important; }`; + } + if (colors.activeBackground) { + css += `.layers-control a.active { background-color: ${colors.activeBackground} !important; }`; + } + if (colors.activeText) { + css += `.layers-control a.active { color: ${colors.activeText} !important; }`; + } + if (colors.hoverBackground) { + css += `.layers-control a:hover { background-color: ${colors.hoverBackground} !important; }`; + } + if (colors.hoverText) { + css += `.layers-control a:hover { color: ${colors.hoverText} !important; }`; + } + if (colors.toggleButtonBackground) { + css += `.layers-control .toggle-button { background-color: ${colors.toggleButtonBackground} + !important; }`; + } + if (colors.toggleButtonText) { + css += `.layers-control .toggle-button { color: ${colors.toggleButtonText} !important; }`; + } + + styleEl.innerHTML = css; + document.head.appendChild(styleEl); + } + + document + .getElementById(data.id) + .appendChild(layersControl); + + const layersList = + document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + message.layers || + map + .getStyle() + .layers.map((layer) => layer.id); + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = + map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty( + clickedLayer, + "visibility", + "none", + ); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (message.collapsible) { + const toggleButton = + document.createElement("div"); + toggleButton.className = "toggle-button"; + toggleButton.textContent = "Layers"; + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore( + toggleButton, + layersList, + ); + } + } else if (message.type === "add_globe_minimap") { + // Add the globe minimap control if supported + if (typeof MapboxGlobeMinimap !== "undefined") { + const minimap = new MapboxGlobeMinimap({ + center: map.getCenter(), + zoom: map.getZoom(), + bearing: map.getBearing(), + pitch: map.getPitch(), + globeSize: message.globe_size, + landColor: message.land_color, + waterColor: message.water_color, + markerColor: message.marker_color, + markerSize: message.marker_size, + }); + + map.addControl(minimap, message.position); + } else { + console.warn( + "MapboxGlobeMinimap is not defined", + ); + } + } else if (message.type === "add_globe_control") { + // Add the globe control + const globeControl = + new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign( + {}, + drawOptions, + { + modes: Object.assign( + {}, + MapboxDraw.modes, + { + draw_polygon: + MapboxDraw.modes + .draw_freehand, + }, + ), + // defaultMode: 'draw_polygon' # Don't set the default yet + }, + ); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: '#fbb03b', + point_color: '#3bb2d0', + line_color: '#3bb2d0', + fill_color: '#3bb2d0', + fill_opacity: 0.1, + line_width: 2 + }); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(draw, message.source, map); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + if (draw) { + const features = draw + ? draw.getAll() + : null; + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if ( + message.type === "clear_drawn_features" + ) { + if (draw) { + draw.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + if (draw) { + if (message.data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn('Draw control not initialized'); + } + } else if (message.type === "set_projection") { + // Only if maplibre supports projection + if (typeof map.setProjection === "function") { + map.setProjection(message.projection); + } + } else if (message.type === "set_source") { + if (map.getLayer(message.layer)) { + const sourceId = map.getLayer( + message.layer, + ).source; + map.getSource(sourceId).setData( + JSON.parse(message.source), + ); + } + } else if (message.type === "set_tooltip") { + // Track tooltip state + layerState.tooltips[message.layer] = message.tooltip; + + if (map.getLayer(message.layer)) { + // Remove any existing tooltip handlers + map.off("mousemove", message.layer); + map.off("mouseleave", message.layer); + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on( + "mousemove", + message.layer, + function (e) { + map.getCanvas().style.cursor = + "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[ + message.tooltip + ]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }, + ); + + map.on( + "mouseleave", + message.layer, + function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }, + ); + } + } else if (message.type === "set_popup") { + // Track popup state + layerState.popups[message.layer] = message.popup; + + if (map.getLayer(message.layer)) { + // Remove any existing popup click handlers for this layer + if (window._maplibreClickHandlers && window._maplibreClickHandlers[message.layer]) { + map.off("click", message.layer, window._maplibreClickHandlers[message.layer]); + delete window._maplibreClickHandlers[message.layer]; + } + + // Remove any existing popup for this layer + if (window._maplibrePopups && window._maplibrePopups[message.layer]) { + window._maplibrePopups[message.layer].remove(); + delete window._maplibrePopups[message.layer]; + } + + // Create new click handler for popup + const clickHandler = function (e) { + onClickPopup(e, map, message.popup, message.layer); + }; + + // Store handler reference + if (!window._maplibreClickHandlers) { + window._maplibreClickHandlers = {}; + } + window._maplibreClickHandlers[message.layer] = clickHandler; + + // Add click handler + map.on("click", message.layer, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer, function () { + map.getCanvas().style.cursor = ""; + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer( + message.layer, + message.before, + ); + } else { + map.moveLayer(message.layer); + } + } + } else if (message.type === "set_opacity") { + // Set opacity for all fill layers + const style = map.getStyle(); + if (style && style.layers) { + style.layers.forEach(function (layer) { + if ( + layer.type === "fill" && + map.getLayer(layer.id) + ) { + map.setPaintProperty( + layer.id, + "fill-opacity", + message.opacity, + ); + } + }); + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection) + ); + } else if (message.type === "clear_controls") { + // Handle clear_controls for compare widgets + if (!message.controls || message.controls.length === 0) { + // Clear all controls + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + } + } + }, + ); + } + + function setupShinyEvents(map, parentId, mapType) { + // Set view state on move end + map.on("moveend", function () { + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_view", + { + center: [center.lng, center.lat], + zoom: zoom, + bearing: bearing, + pitch: pitch, + }, + ); + } + }); + + // Send clicked point coordinates to Shiny + map.on("click", function (e) { + // Check if this map's draw control is active and in a drawing mode + let isDrawing = false; + if (map._mapgl_draw && map._mapgl_draw.getMode) { + const mode = map._mapgl_draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + console.log(`[${mapType}] Draw mode: ${mode}, isDrawing: ${isDrawing}`); + } else { + console.log(`[${mapType}] No draw control found`); + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + // Filter out draw layers + const nonDrawFeatures = features.filter(feature => + !feature.layer.id.includes('gl-draw') && + !feature.source.includes('gl-draw') + ); + console.log(`[${mapType}] Features found: ${features.length}, non-draw: ${nonDrawFeatures.length}`); + + if (nonDrawFeatures.length > 0) { + const feature = nonDrawFeatures[0]; + console.log(`[${mapType}] Feature click detected, layer: ${feature.layer.id}`); + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_click", + { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }, + ); + } + } else { + console.log(`[${mapType}] No non-draw features found at click point`); + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_click", + null + ); + } + } + } else { + console.log(`[${mapType}] Feature click suppressed - currently drawing`); + } + + // Always send regular click event + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_click", + { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }, + ); + } + }); + + // Add hover events if enabled for this map + const mapConfig = (mapType === "before") ? x.map1 : x.map2; + if (mapConfig.hover_events && mapConfig.hover_events.enabled) { + map.on("mousemove", function (e) { + if (window.Shiny) { + // Feature hover events + if (mapConfig.hover_events.features) { + const options = mapConfig.hover_events.layer_id + ? { layers: Array.isArray(mapConfig.hover_events.layer_id) + ? mapConfig.hover_events.layer_id + : mapConfig.hover_events.layer_id.split(',').map(id => id.trim()) } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if(features.length > 0) { + const feature = features[0]; + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } else { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + null + ); + } + } + + // Coordinate hover events + if (mapConfig.hover_events.coordinates) { + Shiny.setInputValue( + parentId + "_" + mapType + "_hover", + { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } + } + }); + } + } + + function applyMapModifications(map, mapData) { + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + // Define the tooltip handler functions to match the ones in maplibregl.js + function onMouseMoveTooltip( + e, + map, + tooltipPopup, + tooltipProperty, + ) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(tooltipProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } + } + + function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } + + function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case 'get': + return properties[expression[1]]; + case 'concat': + return expression.slice(1).map(item => evaluateExpression(item, properties)).join(''); + case 'to-string': + return String(evaluateExpression(expression[1], properties)); + case 'to-number': + return Number(evaluateExpression(expression[1], properties)); + default: + // For literals and other simple values + return expression; + } + } + + function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._maplibrePopups && window._maplibrePopups[layerId]) { + window._maplibrePopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._maplibrePopups) { + window._maplibrePopups = {}; + } + window._maplibrePopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on('close', function() { + if (window._maplibrePopups[layerId] === popup) { + delete window._maplibrePopups[layerId]; + } + }); + } + + // Set config properties if provided + if (mapData.config_properties) { + mapData.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + // Process H3J sources if provided + if (mapData.h3j_sources) { + mapData.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + }); + } + + if (mapData.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + mapData.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker( + markerOptions, + ) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setText(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + } + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + } + }); + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (mapData.sources) { + mapData.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceConfig = { + type: "vector", + url: source.url, + }; + if (source.promoteId) { + sourceConfig.promoteId = source.promoteId; + } + map.addSource(source.id, sourceConfig); + } else if (source.type === "geojson") { + map.addSource(source.id, { + type: "geojson", + data: source.data, + generateId: source.generateId !== false, + }); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + // Add layers if provided + if (mapData.layers) { + mapData.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = + layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + map.on("click", layer.id, function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = + "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + layer.tooltip, + ); + }; + + // Create a reference to the mouseleave handler function + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references + map.on( + "mousemove", + layer.id, + mouseMoveHandler, + ); + map.on( + "mouseleave", + layer.id, + mouseLeaveHandler, + ); + + // Store these handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === + "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = e.features[0].id; + map.setFeatureState( + { + source: + typeof layer.source === + "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: true }, + ); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === + "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach( + function (key) { + const originalPaint = + map.getPaintProperty( + layer.id, + key, + ) || layer.paint[key]; + map.setPaintProperty( + layer.id, + key, + [ + "case", + [ + "boolean", + [ + "feature-state", + "hover", + ], + false, + ], + jsHoverOptions[key], + originalPaint, + ], + ); + }, + ); + } + } catch (e) { + console.error( + "Failed to add layer: ", + layer, + e, + ); + } + }); + } + + // Set terrain if provided + if (mapData.terrain) { + map.setTerrain({ + source: mapData.terrain.source, + exaggeration: mapData.terrain.exaggeration, + }); + } + + // Set fog + if (mapData.fog) { + map.setFog(mapData.fog); + } + + if (mapData.fitBounds) { + map.fitBounds( + mapData.fitBounds.bounds, + mapData.fitBounds.options, + ); + } + if (mapData.flyTo) { + map.flyTo(mapData.flyTo); + } + if (mapData.easeTo) { + map.easeTo(mapData.easeTo); + } + if (mapData.setCenter) { + map.setCenter(mapData.setCenter); + } + if (mapData.setZoom) { + map.setZoom(mapData.setZoom); + } + + // Apply moveLayer operations if provided + if (mapData.moveLayer) { + mapData.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + if (mapData.jumpTo) { + map.jumpTo(mapData.jumpTo); + } + + // Add custom images if provided + if (mapData.images && Array.isArray(mapData.images)) { + mapData.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage( + imageInfo.url, + ); + if (!map.hasImage(imageInfo.id)) { + map.addImage( + imageInfo.id, + image.data, + imageInfo.options, + ); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (mapData.images) { + console.error( + "mapData.images is not an array:", + mapData.images, + ); + } + + // Remove existing legends only from this specific map container + const mapContainer = map.getContainer(); + const existingLegends = mapContainer.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + + if (mapData.legend_html && mapData.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = mapData.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = mapData.legend_html; + legend.classList.add("mapboxgl-legend"); + + // Append legend to the correct map container instead of main container + mapContainer.appendChild(legend); + } + + // Add fullscreen control if enabled + if ( + mapData.fullscreen_control && + mapData.fullscreen_control.enabled + ) { + const position = + mapData.fullscreen_control.position || "top-right"; + map.addControl( + new maplibregl.FullscreenControl(), + position, + ); + } + + // Helper function to generate draw styles based on parameters + function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + 'id': 'gl-draw-point-active', + 'type': 'circle', + 'filter': ['all', + ['==', '$type', 'Point'], + ['==', 'meta', 'feature'], + ['==', 'active', 'true']], + 'paint': { + 'circle-radius': styling.vertex_radius + 2, + 'circle-color': styling.active_color + } + }, + { + 'id': 'gl-draw-point', + 'type': 'circle', + 'filter': ['all', + ['==', '$type', 'Point'], + ['==', 'meta', 'feature'], + ['==', 'active', 'false']], + 'paint': { + 'circle-radius': styling.vertex_radius, + 'circle-color': styling.point_color + } + }, + // Line styles + { + 'id': 'gl-draw-line', + 'type': 'line', + 'filter': ['all', ['==', '$type', 'LineString']], + 'layout': { + 'line-cap': 'round', + 'line-join': 'round' + }, + 'paint': { + 'line-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.line_color + ], + 'line-width': styling.line_width + } + }, + // Polygon fill + { + 'id': 'gl-draw-polygon-fill', + 'type': 'fill', + 'filter': ['all', ['==', '$type', 'Polygon']], + 'paint': { + 'fill-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.fill_color + ], + 'fill-outline-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.fill_color + ], + 'fill-opacity': styling.fill_opacity + } + }, + // Polygon outline + { + 'id': 'gl-draw-polygon-stroke', + 'type': 'line', + 'filter': ['all', ['==', '$type', 'Polygon']], + 'layout': { + 'line-cap': 'round', + 'line-join': 'round' + }, + 'paint': { + 'line-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.line_color + ], + 'line-width': styling.line_width + } + }, + // Midpoints + { + 'id': 'gl-draw-polygon-midpoint', + 'type': 'circle', + 'filter': ['all', + ['==', '$type', 'Point'], + ['==', 'meta', 'midpoint']], + 'paint': { + 'circle-radius': 3, + 'circle-color': styling.active_color + } + }, + // Vertex point halos + { + 'id': 'gl-draw-vertex-halo-active', + 'type': 'circle', + 'filter': ['all', + ['==', 'meta', 'vertex'], + ['==', '$type', 'Point']], + 'paint': { + 'circle-radius': ['case', + ['==', ['get', 'active'], 'true'], styling.vertex_radius + 4, + styling.vertex_radius + 2 + ], + 'circle-color': '#FFF' + } + }, + // Vertex points + { + 'id': 'gl-draw-vertex-active', + 'type': 'circle', + 'filter': ['all', + ['==', 'meta', 'vertex'], + ['==', '$type', 'Point']], + 'paint': { + 'circle-radius': ['case', + ['==', ['get', 'active'], 'true'], styling.vertex_radius + 2, + styling.vertex_radius + ], + 'circle-color': styling.active_color + } + } + ]; + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn('Source not found or has no data:', sourceId); + } + } + + if (mapData.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: mapData.scale_control.maxWidth, + unit: mapData.scale_control.unit, + }); + map.addControl( + scaleControl, + mapData.scale_control.position, + ); + map.controls.push(scaleControl); + } + + // Add navigation control if enabled + if (mapData.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: + mapData.navigation_control.show_compass, + showZoom: mapData.navigation_control.show_zoom, + visualizePitch: + mapData.navigation_control.visualize_pitch, + }); + map.addControl( + nav, + mapData.navigation_control.position, + ); + map.controls.push({ type: "navigation", control: nav }); + } + + // Add geolocate control if enabled + if (mapData.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: + mapData.geolocate_control.positionOptions, + trackUserLocation: + mapData.geolocate_control.trackUserLocation, + showAccuracyCircle: + mapData.geolocate_control.showAccuracyCircle, + showUserLocation: + mapData.geolocate_control.showUserLocation, + showUserHeading: + mapData.geolocate_control.showUserHeading, + fitBoundsOptions: + mapData.geolocate_control.fitBoundsOptions, + }); + map.addControl( + geolocate, + mapData.geolocate_control.position, + ); + + map.controls.push(geolocate); + } + + // Add globe control if enabled + if (mapData.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl( + globeControl, + mapData.globe_control.position, + ); + map.controls.push(globeControl); + } + + // Add draw control if enabled + if (mapData.draw_control && mapData.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = mapData.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (mapData.draw_control.styling) { + const generatedStyles = generateDrawStyles(mapData.draw_control.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (mapData.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + mapData.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (mapData.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (mapData.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: '#fbb03b', + point_color: '#3bb2d0', + line_color: '#3bb2d0', + fill_color: '#3bb2d0', + fill_opacity: 0.1, + line_width: 2 + }); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, mapData.draw_control.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add custom mode buttons and styling + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + + // Add rectangle styling and button + if (mapData.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + drawControl.changeMode('draw_rectangle'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + } + + // Add radius styling and button + if (mapData.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + drawControl.changeMode('draw_radius'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + } + }, 100); + + // Add initial features if provided + if (mapData.draw_control.source) { + addSourceFeaturesToDraw(drawControl, mapData.draw_control.source, map); + } + + // Process any queued features + if (mapData.draw_features_queue) { + mapData.draw_features_queue.forEach(function(data) { + if (data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, data.source, map); + }); + } + + // Apply orientation styling + if (mapData.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (mapData.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${mapData.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + + // Helper function for updating drawn features + function updateDrawnFeatures() { + if (HTMLWidgets.shinyMode && draw) { + const features = draw.getAll(); + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(features), + ); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + } + + if (mapData.geolocate_control && HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue( + el.id + "_geolocate_error", + { + message: "Location permission denied", + time: new Date(), + }, + ); + } + }); + } + + // Add geocoder control if enabled + if (mapData.geocoder_control) { + const provider = mapData.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: mapData.geocoder_control.api_key, + maplibregl: maplibregl, + ...mapData.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - + feature.bbox[0]) / + 2, + feature.bbox[1] + + (feature.bbox[3] - + feature.bbox[1]) / + 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: + feature.properties.display_name, + properties: feature.properties, + text: feature.properties + .display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error( + `Failed to forwardGeocode with error: ${e}`, + ); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...mapData.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder( + geocoderApi, + geocoderOptions, + ); + } + + map.addControl( + geocoder, + mapData.geocoder_control.position || "top-right", + ); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + // Add reset control if enabled + if (mapData.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: mapData.reset_control.animate, + }; + + if (mapData.reset_control.duration) { + initialView.duration = + mapData.reset_control.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild( + resetContainer, + ); + }, + }, + mapData.reset_control.position, + ); + } + + + function updateDrawnFeatures() { + if (map._mapgl_draw) { + var drawnFeatures = map._mapgl_draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + // Add the layers control if provided + if (mapData.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = mapData.layers_control.control_id; + + // Handle use_icon parameter + let className = mapData.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + + layersControl.className = className; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = + mapData.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + mapData.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = mapData.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty( + clickedLayer, + "visibility", + "none", + ); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (mapData.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + if (mapData.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore( + toggleButton, + layersList, + ); + } + } + + // Set projection if provided (after all other setup is complete) + if (mapData.setProjection && mapData.setProjection.length > 0) { + mapData.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection in compare view:", e); + } + } + }); + } + } + }, + + resize: function (width, height) { + // Code to handle resizing if necessary + }, + }; + }, +}); diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl_compare.yaml b/docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl_compare.yaml new file mode 100644 index 0000000..a72887c --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/maplibregl_compare.yaml @@ -0,0 +1,67 @@ +dependencies: + - name: maplibre-gl + version: "5.7.2" + src: "htmlwidgets/lib/maplibre-gl" + script: + - "maplibre-gl.js" + stylesheet: + - "maplibre-gl.css" + - name: maplibre-gl-compare + version: "0.5" + src: "htmlwidgets/lib/maplibre-gl-compare" + script: + - "maplibre-gl-compare.js" + stylesheet: + - "maplibre-gl-compare.css" + - name: mapbox-gl-draw + version: "1.5.0" + src: "htmlwidgets/lib/mapbox-gl-draw" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: maplibre-gl-geocoder + version: 1.5.0 + src: "htmlwidgets/lib/maplibre-gl-geocoder" + script: + - "maplibre-gl-geocoder.min.js" + stylesheet: + - "maplibre-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: h3j-h3t + version: 0.9.2 + src: "htmlwidgets/lib/h3j-h3t" + script: + - "h3j_h3t.js" + - name: maptiler-geocoding-control + version: 2.1.7 + src: + href: "https://cdn.maptiler.com/maptiler-geocoding-control/v2.1.7/" + script: + - "maplibregl.umd.js" + stylesheet: + - "style.css" diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/styles/filter-control.css b/docs/articles/layers-overview_files/turf-operations-1.0.0/styles/filter-control.css new file mode 100644 index 0000000..e6096c3 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/styles/filter-control.css @@ -0,0 +1,65 @@ +.filter-control { + background: #fff; + position: absolute; + z-index: 1; + border-radius: 3px; + width: 200px; + border: 1px solid rgba(0, 0, 0, 0.4); + font-family: 'Open Sans', sans-serif; + margin: 10px; + padding: 10px; +} + +.filter-control .filter-title { + font-weight: bold; + margin-bottom: 10px; + text-align: center; +} + +.filter-control input[type="range"] { + width: 100%; + margin: 10px 0; +} + +.filter-control .range-value { + text-align: center; + margin-top: 5px; +} + +.filter-control .checkbox-group { + display: flex; + flex-direction: column; + gap: 5px; +} + +.filter-control .checkbox-group label { + display: flex; + align-items: center; + gap: 5px; +} + +.filter-control .toggle-button { + background: darkgrey; + color: #ffffff; + text-align: center; + cursor: pointer; + padding: 5px 0; + border-radius: 3px 3px 0 0; + margin: -10px -10px 10px -10px; +} + +.filter-control .toggle-button:hover { + background: grey; +} + +.filter-control .filter-content { + display: block; +} + +.filter-control.collapsible .filter-content { + display: none; +} + +.filter-control.collapsible.open .filter-content { + display: block; +} \ No newline at end of file diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/styles/layers-control.css b/docs/articles/layers-overview_files/turf-operations-1.0.0/styles/layers-control.css new file mode 100644 index 0000000..8551228 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/styles/layers-control.css @@ -0,0 +1,123 @@ +.layers-control { + background: #fff; + position: absolute; + z-index: 1; + border-radius: 4px; + width: 120px; + border: 1px solid rgba(0, 0, 0, 0.15); + font-family: "Open Sans", sans-serif; + margin: 0px; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15); + overflow: hidden; + transition: all 0.2s ease-in-out; +} + +.layers-control a { + font-size: 13px; + color: #404040; + display: block; + margin: 0; + padding: 10px; + text-decoration: none; + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + text-align: center; + transition: all 0.15s ease-in-out; + font-weight: normal; +} + +.layers-control a:last-child { + border: none; +} + +.layers-control a:hover { + background-color: #f8f8f8; + color: #1a1a1a; +} + +.layers-control a.active { + background-color: #4a90e2; + color: #ffffff; + font-weight: 500; +} + +.layers-control a.active:hover { + background: #3b7ed2; +} + +.layers-control .toggle-button { + display: none; + background: #4a90e2; + color: #ffffff; + text-align: center; + cursor: pointer; + padding: 8px 0; + border-radius: 4px 4px 0 0; + font-weight: 500; + letter-spacing: 0.3px; + box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.05) inset; + transition: all 0.15s ease-in-out; +} + +.layers-control .toggle-button:hover { + background: #3b7ed2; +} + +.layers-control .layers-list { + display: block; +} + +.layers-control.collapsible .toggle-button { + display: block; + border-bottom: 1px solid rgba(0, 0, 0, 0.25); +} + +.layers-control.collapsible .layers-list { + display: none; + opacity: 0; + max-height: 0; + transition: + opacity 0.25s ease, + max-height 0.25s ease; +} + +.layers-control.collapsible.open .layers-list { + display: block; + opacity: 1; + max-height: 500px; /* Large enough value to accommodate all content */ +} + +/* Compact icon styling */ +.layers-control.collapsible.icon-only { + width: auto; + min-width: 36px; + border-radius: 4px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); + transform: translateZ( + 0 + ); /* Force hardware acceleration for smoother animations */ +} + +.layers-control.collapsible.icon-only .toggle-button { + border-radius: 4px; + padding: 8px; + width: 36px; + height: 36px; + box-sizing: border-box; + margin: 0; + border-bottom: none; + display: flex; + align-items: center; + justify-content: center; + box-shadow: none; +} + +.layers-control.collapsible.icon-only.open { + width: 120px; + box-shadow: 0 3px 10px rgba(0, 0, 0, 0.25); +} + +.layers-control.collapsible.icon-only.open .toggle-button { + border-radius: 4px 4px 0 0; + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + width: 100%; +} diff --git a/docs/articles/layers-overview_files/turf-operations-1.0.0/turf-operations.js b/docs/articles/layers-overview_files/turf-operations-1.0.0/turf-operations.js new file mode 100644 index 0000000..2b4e514 --- /dev/null +++ b/docs/articles/layers-overview_files/turf-operations-1.0.0/turf-operations.js @@ -0,0 +1,967 @@ +// Turf.js operations module for mapgl +// Shared operations that work with both mapboxgl and maplibre maps + +// Process turf operations on map initialization (for static maps) +function processTurfOperationsOnLoad(map, turfOperations, widgetId) { + if (!turfOperations || turfOperations.length === 0) return; + + // Wait for map to be fully loaded, then execute operations + map.on('load', function() { + // Add a small delay to ensure all layers are loaded + setTimeout(function() { + turfOperations.forEach(function(operation) { + try { + handleTurfOperation(map, operation, widgetId); + } catch (error) { + console.error(`Error processing turf operation ${operation.type}:`, error); + } + }); + }, 100); + }); +} + +// Main handler for all turf operations +function handleTurfOperation(map, message, widgetId) { + try { + switch (message.type) { + case "turf_buffer": + executeTurfBuffer(map, message, widgetId); + break; + case "turf_union": + executeTurfUnion(map, message, widgetId); + break; + case "turf_intersect": + executeTurfIntersect(map, message, widgetId); + break; + case "turf_difference": + executeTurfDifference(map, message, widgetId); + break; + case "turf_convex_hull": + executeTurfConvexHull(map, message, widgetId); + break; + case "turf_concave_hull": + executeTurfConcaveHull(map, message, widgetId); + break; + case "turf_voronoi": + executeTurfVoronoi(map, message, widgetId); + break; + case "turf_distance": + executeTurfDistance(map, message, widgetId); + break; + case "turf_area": + executeTurfArea(map, message, widgetId); + break; + case "turf_centroid": + executeTurfCentroid(map, message, widgetId); + break; + case "turf_center_of_mass": + executeTurfCenterOfMass(map, message, widgetId); + break; + case "turf_filter": + executeTurfFilter(map, message, widgetId); + break; + default: + console.warn(`Unknown turf operation: ${message.type}`); + } + } catch (error) { + console.error(`Error executing turf operation ${message.type}:`, error); + if (HTMLWidgets.shinyMode && message.send_to_r) { + Shiny.setInputValue(widgetId + "_turf_error", { + operation: message.type, + error: error.message, + timestamp: Date.now() + }); + } + } +} + +// Helper function to get input data for turf operations +function getInputData(map, message) { + // If coordinates provided, create point or points client-side + if (message.coordinates) { + // Handle single coordinate pair + if (typeof message.coordinates[0] === 'number') { + return turf.point(message.coordinates); + } + // Handle multiple coordinate pairs + if (Array.isArray(message.coordinates[0])) { + const points = message.coordinates.map(coord => turf.point(coord)); + return { + type: "FeatureCollection", + features: points + }; + } + } + + // If GeoJSON data provided directly + if (message.data) { + // Check if data is already an object (shouldn't happen) or string + if (typeof message.data === 'string') { + return JSON.parse(message.data); + } else { + // If it's already an object, return as-is + return message.data; + } + } + + // If layer_id provided, get from existing layer + if (message.layer_id) { + return getSourceData(map, message.layer_id); + } + + throw new Error("No valid input data provided (coordinates, data, or layer_id)"); +} + +// Helper function to get source data from a layer +function getSourceData(map, layerId) { + // First try to get from existing source + const source = map.getSource(layerId); + if (source) { + // Check for _data property (GeoJSON sources) + if (source._data) { + return source._data; + } + // Check for data property + if (source.data) { + return source.data; + } + } + + // Try with _source suffix (common pattern in mapgl) + const sourceWithSuffix = map.getSource(layerId + "_source"); + if (sourceWithSuffix) { + if (sourceWithSuffix._data) { + return sourceWithSuffix._data; + } + if (sourceWithSuffix.data) { + return sourceWithSuffix.data; + } + } + + // Query rendered features as fallback + try { + const features = map.queryRenderedFeatures({ layers: [layerId] }); + if (features.length > 0) { + return { + type: "FeatureCollection", + features: features + }; + } + } catch (e) { + // Layer might not exist, continue to error + } + + throw new Error(`Could not find source data for layer: ${layerId}`); +} + +// Helper function to add result source to map +function addResultSource(map, result, sourceId) { + if (!sourceId) return; + + // Ensure result is valid GeoJSON + if (!result) { + result = { + type: "FeatureCollection", + features: [] + }; + } + + // Check if source exists, update data or create new + const existingSource = map.getSource(sourceId); + if (existingSource) { + // Update existing source data + existingSource.setData(result); + } else { + // Add new source with result data + map.addSource(sourceId, { + type: "geojson", + data: result, + generateId: true + }); + } +} + +// Helper function to send result to R via Shiny input +function sendResultToR(widgetId, operation, result, metadata = {}, inputId = null) { + if (HTMLWidgets.shinyMode && inputId) { + Shiny.setInputValue(widgetId + "_turf_" + inputId, { + operation: operation, + result: result, + metadata: metadata, + timestamp: Date.now() + }); + } +} + +// Buffer operation +function executeTurfBuffer(map, message, widgetId) { + const inputData = getInputData(map, message); + + const buffered = turf.buffer(inputData, message.radius, { + units: message.units || "meters" + }); + + if (message.source_id) { + addResultSource(map, buffered, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "buffer", buffered, { + radius: message.radius, + units: message.units || "meters" + }, message.input_id); + } +} + +// Union operation +function executeTurfUnion(map, message, widgetId) { + const inputData = getInputData(map, message); + + let result; + if (inputData.type === "FeatureCollection" && inputData.features.length > 1) { + // Use turf.union with properly formatted FeatureCollection + const union = turf.union(turf.featureCollection(inputData.features)); + + result = union ? { + type: "FeatureCollection", + features: [union] + } : { + type: "FeatureCollection", + features: [] + }; + } else if (inputData.type === "FeatureCollection" && inputData.features.length === 1) { + // Single feature, return as-is + result = { + type: "FeatureCollection", + features: [inputData.features[0]] + }; + } else { + // Single feature, return as-is in FeatureCollection + result = { + type: "FeatureCollection", + features: [inputData] + }; + } + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "union", result, {}, message.input_id); + } +} + +// Intersect operation +function executeTurfIntersect(map, message, widgetId) { + const sourceData1 = getInputData(map, message); + + // Get second geometry data + let sourceData2; + if (message.data_2) { + // Handle data_2 directly + if (typeof message.data_2 === 'string') { + sourceData2 = JSON.parse(message.data_2); + } else { + sourceData2 = message.data_2; + } + } else if (message.layer_id_2) { + // Handle layer_id_2 as before + sourceData2 = getSourceData(map, message.layer_id_2); + } else { + throw new Error("Either data_2 or layer_id_2 must be provided for intersect operation"); + } + + // Extract features arrays + const features1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features : [sourceData1]; + const features2 = sourceData2.type === "FeatureCollection" ? + sourceData2.features : [sourceData2]; + + // Collect all intersection results + const resultFeatures = []; + + features1.forEach((feature1, index1) => { + if (!feature1 || !feature1.geometry) { + console.warn(`Skipping invalid feature at index ${index1}`); + return; + } + + features2.forEach((feature2, index2) => { + if (!feature2 || !feature2.geometry) { + return; + } + + // Use booleanIntersects for efficient filtering + if (turf.booleanIntersects(feature1, feature2)) { + try { + // Use turf.intersect with options to preserve properties + const intersection = turf.intersect( + turf.featureCollection([feature1, feature2]), + { properties: feature1.properties } + ); + + if (intersection) { + // Ensure properties are preserved (fallback if options didn't work) + if (!intersection.properties || Object.keys(intersection.properties).length === 0) { + intersection.properties = { ...feature1.properties }; + } + resultFeatures.push(intersection); + } + } catch (error) { + console.error(`Error intersecting features ${index1} and ${index2}:`, error); + } + } + }); + }); + + const result = { + type: "FeatureCollection", + features: resultFeatures + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "intersect", result, {}, message.input_id); + } +} + +// Difference operation +function executeTurfDifference(map, message, widgetId) { + const sourceData1 = getInputData(map, message); + + // Get second geometry data + let sourceData2; + if (message.data_2) { + // Handle data_2 directly + if (typeof message.data_2 === 'string') { + sourceData2 = JSON.parse(message.data_2); + } else { + sourceData2 = message.data_2; + } + } else if (message.layer_id_2) { + // Handle layer_id_2 as before + sourceData2 = getSourceData(map, message.layer_id_2); + } else { + throw new Error("Either data_2 or layer_id_2 must be provided for difference operation"); + } + + // Extract features arrays + const features1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features : [sourceData1]; + const features2 = sourceData2.type === "FeatureCollection" ? + sourceData2.features : [sourceData2]; + + // Process each feature in features1 + const resultFeatures = []; + + features1.forEach((feature1, index) => { + if (!feature1 || !feature1.geometry) { + console.warn(`Skipping invalid feature at index ${index}`); + return; + } + + // Start with the original feature + let currentFeature = feature1; + + // Apply difference with each feature from features2 + for (const feature2 of features2) { + if (!feature2 || !feature2.geometry || !currentFeature) { + continue; + } + + // Use booleanIntersects for efficient filtering + if (turf.booleanIntersects(currentFeature, feature2)) { + try { + const diff = turf.difference(turf.featureCollection([currentFeature, feature2])); + + if (diff) { + // Preserve properties from the original feature + diff.properties = { ...feature1.properties }; + currentFeature = diff; + } else { + // Feature was completely erased + currentFeature = null; + break; + } + } catch (error) { + console.error("Error in difference operation:", error); + // Keep the current feature unchanged on error + } + } + // If no intersection, currentFeature remains unchanged + } + + // Add the result if it still exists + if (currentFeature) { + resultFeatures.push(currentFeature); + } + }); + + const result = { + type: "FeatureCollection", + features: resultFeatures + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "difference", result, {}, message.input_id); + } +} + +// Convex hull operation +function executeTurfConvexHull(map, message, widgetId) { + const inputData = getInputData(map, message); + + // Ensure we have valid input data + if (!inputData) { + console.warn("No input data for convex hull"); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + // Check for minimum points if it's a FeatureCollection + if (inputData.type === "FeatureCollection" && inputData.features.length < 3) { + console.warn("Convex hull requires at least 3 points, got:", inputData.features.length); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + const hull = turf.convex(inputData); + + const result = hull ? { + type: "FeatureCollection", + features: [hull] + } : { + type: "FeatureCollection", + features: [] + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "convex_hull", result, {}, message.input_id); + } +} + +// Concave hull operation +function executeTurfConcaveHull(map, message, widgetId) { + const inputData = getInputData(map, message); + + // Ensure we have a FeatureCollection of Points for turf.concave + let pointCollection; + if (inputData.type === "FeatureCollection") { + // Filter to only Point geometries and ensure it's a proper FeatureCollection + const pointFeatures = inputData.features.filter(feature => + feature.geometry && feature.geometry.type === "Point" + ); + pointCollection = turf.featureCollection(pointFeatures); + } else if (inputData.type === "Feature" && inputData.geometry.type === "Point") { + // Single point - wrap in FeatureCollection + pointCollection = turf.featureCollection([inputData]); + } else { + console.warn("Concave hull requires Point geometries, received:", inputData); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + // Check if we have enough points (need at least 3 for a hull) + if (!pointCollection.features || pointCollection.features.length < 3) { + console.warn("Concave hull requires at least 3 points, got:", pointCollection.features?.length || 0); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + // Smart max_edge calculation with fallback + let hull = null; + let actualMaxEdge = message.max_edge; + + if (message.max_edge) { + // User specified max_edge, try it first + hull = turf.concave(pointCollection, { + maxEdge: message.max_edge, + units: message.units || "kilometers" + }); + } + + // If no hull or user didn't specify max_edge, try to find optimal value + if (!hull) { + // Calculate distances between all points to find reasonable max_edge + const distances = []; + const features = pointCollection.features; + + for (let i = 0; i < features.length; i++) { + for (let j = i + 1; j < features.length; j++) { + const dist = turf.distance(features[i], features[j], { + units: message.units || "kilometers" + }); + distances.push(dist); + } + } + + // Sort distances and try different percentiles as max_edge + distances.sort((a, b) => a - b); + const percentiles = [0.6, 0.7, 0.8, 0.9]; // Try 60th, 70th, 80th, 90th percentiles + + for (const percentile of percentiles) { + const index = Math.floor(distances.length * percentile); + const testMaxEdge = distances[index]; + + hull = turf.concave(pointCollection, { + maxEdge: testMaxEdge, + units: message.units || "kilometers" + }); + + if (hull) { + actualMaxEdge = testMaxEdge; + console.log(`Auto-calculated max_edge: ${testMaxEdge.toFixed(2)} ${message.units || "kilometers"}`); + break; + } + } + + // Final fallback - use convex hull if concave fails + if (!hull) { + console.warn("Concave hull failed, falling back to convex hull"); + hull = turf.convex(pointCollection); + actualMaxEdge = "convex_fallback"; + } + } + + const result = hull ? { + type: "FeatureCollection", + features: [hull] + } : { + type: "FeatureCollection", + features: [] + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "concave_hull", result, { + max_edge: message.max_edge, + units: message.units || "kilometers" + }, message.input_id); + } +} + +// Voronoi operation +function executeTurfVoronoi(map, message, widgetId) { + const inputData = getInputData(map, message); + + const options = {}; + let finalBbox = null; + let clippingData = null; + + // Handle bbox parameter + if (message.bbox) { + // Direct bbox array [minX, minY, maxX, maxY] + options.bbox = message.bbox; + finalBbox = message.bbox; + } else if (message.bbox_layer_id) { + // Extract bbox from layer + try { + const bboxSourceData = getSourceData(map, message.bbox_layer_id); + if (bboxSourceData) { + // Calculate bbox from layer data + const bbox = turf.bbox(bboxSourceData); + options.bbox = bbox; + finalBbox = bbox; + // Keep the layer data for potential intersection clipping + clippingData = bboxSourceData; + } + } catch (error) { + console.warn(`Could not extract bbox from layer ${message.bbox_layer_id}:`, error); + } + } + + let voronoi = turf.voronoi(inputData, options); + + // If we have clipping data (from bbox_layer_id), intersect each Voronoi polygon + if (voronoi && clippingData && clippingData.type === "FeatureCollection") { + const clippedFeatures = []; + + for (const voronoiFeature of voronoi.features) { + try { + // Try to intersect with each feature in the clipping layer + for (const clipFeature of clippingData.features) { + const intersection = turf.intersect(turf.featureCollection([voronoiFeature, clipFeature])); + if (intersection) { + clippedFeatures.push(intersection); + } + } + } catch (error) { + // If intersection fails, keep original feature + clippedFeatures.push(voronoiFeature); + } + } + + voronoi = { + type: "FeatureCollection", + features: clippedFeatures + }; + } + + // If property parameter is provided, use turf.collect to transfer attributes from points to polygons + if (voronoi && message.property && inputData.type === "FeatureCollection") { + try { + // Use turf.collect to gather point properties within each Voronoi polygon + const collected = turf.collect(voronoi, inputData, message.property, `${message.property}_collected`); + + // Since each Voronoi polygon should contain exactly one point, extract the single value from the array + for (const feature of collected.features) { + const collectedValues = feature.properties[`${message.property}_collected`]; + if (collectedValues && collectedValues.length > 0) { + // Take the first (and should be only) value and assign it directly to the property name + feature.properties[message.property] = collectedValues[0]; + // Remove the temporary array property + delete feature.properties[`${message.property}_collected`]; + } + } + + voronoi = collected; + } catch (error) { + console.warn(`Failed to collect property '${message.property}' from points to Voronoi polygons:`, error); + // Continue with uncollected voronoi if collection fails + } + } + + if (message.source_id && voronoi) { + addResultSource(map, voronoi, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "voronoi", voronoi, { + bbox: finalBbox, + bbox_layer_id: message.bbox_layer_id + }, message.input_id); + } +} + +// Distance operation +function executeTurfDistance(map, message, widgetId) { + let feature1, feature2; + + // Get first feature + if (message.coordinates) { + feature1 = turf.point(message.coordinates); + } else if (message.data) { + const sourceData1 = JSON.parse(message.data); + feature1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features[0] : sourceData1; + } else if (message.layer_id) { + const sourceData1 = getSourceData(map, message.layer_id); + feature1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features[0] : sourceData1; + } + + // Get second feature + if (message.coordinates_2) { + feature2 = turf.point(message.coordinates_2); + } else if (message.layer_id_2) { + const sourceData2 = getSourceData(map, message.layer_id_2); + feature2 = sourceData2.type === "FeatureCollection" ? + sourceData2.features[0] : sourceData2; + } + + const distance = turf.distance(feature1, feature2, { + units: message.units || "kilometers" + }); + + if (message.input_id) { + sendResultToR(widgetId, "distance", distance, { + units: message.units || "kilometers" + }, message.input_id); + } +} + +// Area operation +function executeTurfArea(map, message, widgetId) { + const inputData = getInputData(map, message); + + const area = turf.area(inputData); + + if (message.input_id) { + sendResultToR(widgetId, "area", area, { + units: "square_meters" + }, message.input_id); + } +} + +// Centroid operation (using turf.centroid - vertex average method) +function executeTurfCentroid(map, message, widgetId) { + const inputData = getInputData(map, message); + + const centroids = []; + + // Handle both single features and FeatureCollections + const features = inputData.type === "FeatureCollection" ? inputData.features : [inputData]; + + // Calculate centroid for each individual feature using turf.centroid + for (const feature of features) { + const centroid = turf.centroid(feature); + + // Preserve all properties from the source feature + if (feature.properties) { + centroid.properties = { ...feature.properties }; + } + + centroids.push(centroid); + } + + const result = { + type: "FeatureCollection", + features: centroids + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "centroid", result, {}, message.input_id); + } +} + +// Center of Mass operation (replaces centroid for better accuracy) +function executeTurfCenterOfMass(map, message, widgetId) { + const inputData = getInputData(map, message); + + const centers = []; + + // Handle both single features and FeatureCollections + const features = inputData.type === "FeatureCollection" ? inputData.features : [inputData]; + + // Calculate center of mass for each individual feature + for (const feature of features) { + const centerOfMass = turf.centerOfMass(feature, {}); + + // Preserve all properties from the source feature + if (feature.properties) { + centerOfMass.properties = { ...feature.properties }; + } + + centers.push(centerOfMass); + } + + const result = { + type: "FeatureCollection", + features: centers + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "center_of_mass", result, {}, message.input_id); + } +} + +// Filter operation +function executeTurfFilter(map, message, widgetId) { + const sourceData = getInputData(map, message); + + // Get filter geometry data + let filterData; + if (message.filter_data) { + // Handle filter_data directly + if (typeof message.filter_data === 'string') { + filterData = JSON.parse(message.filter_data); + } else { + filterData = message.filter_data; + } + } else if (message.filter_layer_id) { + // Handle filter_layer_id as before + filterData = getSourceData(map, message.filter_layer_id); + } else { + throw new Error("Either filter_data or filter_layer_id must be provided for filter operation"); + } + + // Extract features arrays + const features = sourceData.type === "FeatureCollection" ? + sourceData.features : [sourceData]; + const filterFeatures = filterData.type === "FeatureCollection" ? + filterData.features : [filterData]; + + // Collect filtered results + const resultFeatures = []; + + features.forEach((feature, index) => { + if (!feature || !feature.geometry) { + console.warn(`Skipping invalid feature at index ${index}`); + return; + } + + // Check if this feature matches the predicate against any filter feature + let matches = false; + + for (const filterFeature of filterFeatures) { + if (!filterFeature || !filterFeature.geometry) { + continue; + } + + try { + // Handle MultiPolygon geometries for within/contains predicates + if ((feature.geometry.type === 'MultiPolygon' || filterFeature.geometry.type === 'MultiPolygon') && + (message.predicate === 'within' || message.predicate === 'contains')) { + + // MultiPolygon handling for 'within' + if (message.predicate === 'within') { + if (feature.geometry.type === 'MultiPolygon') { + // All parts of the MultiPolygon must be within the filter + const polygons = feature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: feature.properties + })); + matches = polygons.every(poly => { + try { + return turf.booleanWithin(poly, filterFeature); + } catch (e) { + return false; + } + }); + } else if (filterFeature.geometry.type === 'MultiPolygon') { + // Feature must be within at least one part of the MultiPolygon + const polygons = filterFeature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: filterFeature.properties + })); + matches = polygons.some(poly => { + try { + return turf.booleanWithin(feature, poly); + } catch (e) { + return false; + } + }); + } + } + // MultiPolygon handling for 'contains' + else if (message.predicate === 'contains') { + if (feature.geometry.type === 'MultiPolygon') { + // At least one part of the MultiPolygon must contain the filter + const polygons = feature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: feature.properties + })); + matches = polygons.some(poly => { + try { + return turf.booleanContains(poly, filterFeature); + } catch (e) { + return false; + } + }); + } else if (filterFeature.geometry.type === 'MultiPolygon') { + // Feature must be contained by at least one part of the MultiPolygon + const polygons = filterFeature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: filterFeature.properties + })); + matches = polygons.some(poly => { + try { + return turf.booleanContains(poly, feature); + } catch (e) { + return false; + } + }); + } + } + } else { + // Use the appropriate boolean function based on predicate + switch (message.predicate) { + case "intersects": + matches = turf.booleanIntersects(feature, filterFeature); + break; + case "within": + matches = turf.booleanWithin(feature, filterFeature); + break; + case "contains": + matches = turf.booleanContains(feature, filterFeature); + break; + case "crosses": + matches = turf.booleanCrosses(feature, filterFeature); + break; + case "disjoint": + matches = turf.booleanDisjoint(feature, filterFeature); + break; + default: + console.warn(`Unknown predicate: ${message.predicate}`); + continue; + } + } + + if (matches) { + break; // Found a match, no need to check other filter features + } + } catch (error) { + console.error(`Error testing predicate ${message.predicate}:`, error); + continue; + } + } + + // If this feature matches the predicate, add it to results + if (matches) { + // Preserve all properties from the original feature + const resultFeature = { + ...feature, + properties: { ...feature.properties } + }; + resultFeatures.push(resultFeature); + } + }); + + const result = { + type: "FeatureCollection", + features: resultFeatures + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "filter", result, { + predicate: message.predicate, + filtered_count: resultFeatures.length, + total_count: features.length + }, message.input_id); + } +} \ No newline at end of file diff --git a/docs/articles/map-design_files/mapbox-pmtiles-1.1.0/pmtiles-source-optimized-v2.js b/docs/articles/map-design_files/mapbox-pmtiles-1.1.0/pmtiles-source-optimized-v2.js new file mode 100644 index 0000000..207d876 --- /dev/null +++ b/docs/articles/map-design_files/mapbox-pmtiles-1.1.0/pmtiles-source-optimized-v2.js @@ -0,0 +1,1102 @@ +/** + * mapbox-pmtiles v1.1.0 - Optimized Version with Lifecycle Management + * Original source: https://github.com/am2222/mapbox-pmtiles by Majid Hojati + * License: MIT + * + * This is an optimized version of the mapbox-pmtiles library that provides + * better performance for large datasets through: + * - Configurable resource management + * - Instance-scoped worker pools and caches + * - Proper lifecycle management and cleanup + * - Reference counting for shared resources + * - Enhanced error handling and timeouts + * - Memory optimization with size-based LRU caches + * + * Last updated: 2025 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + // Global shared resources with reference counting + const GLOBAL_SHARED_RESOURCES = { + // Protocol cache - expensive to duplicate, shared with reference counting + protocolCache: new Map(), // url -> { protocol, instance, refCount } + + // Metadata cache - small and shareable + metadataCache: new Map(), // cacheKey -> data + + // Pre-calculated world sizes for common zoom levels (static, no cleanup needed) + worldSizeCache: new Array(25).fill(null).map((_, z) => Math.pow(2, z)), + + // Global cleanup registry + activeManagers: new Set(), + + // Debug/development features + debug: false, + performanceMetrics: new Map(), + }; + + /** + * Default configuration options + */ + const DEFAULT_OPTIONS = { + workerPoolSize: 4, + tileCacheSize: 1000, + tileCacheMaxMemoryMB: 100, + metadataCacheSize: 100, + enableSharedProtocols: true, + requestTimeoutMs: 30000, + enableDebugLogging: false, + enablePerformanceMetrics: false, + }; + + /** + * LRU Cache implementation with size-based eviction + */ + class LRUCache { + constructor(maxSize, maxMemoryBytes = Infinity) { + this.maxSize = maxSize; + this.maxMemoryBytes = maxMemoryBytes; + this.cache = new Map(); + this.currentMemoryBytes = 0; + } + + get(key) { + if (this.cache.has(key)) { + // Move to end (most recently used) + const value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return value.data; + } + return undefined; + } + + set(key, data, estimatedSize = 0) { + // Remove if exists + if (this.cache.has(key)) { + const existing = this.cache.get(key); + this.currentMemoryBytes -= existing.size; + this.cache.delete(key); + } + + // Evict old entries if necessary + while ( + this.cache.size >= this.maxSize || + this.currentMemoryBytes + estimatedSize > this.maxMemoryBytes + ) { + const firstKey = this.cache.keys().next().value; + if (!firstKey) break; + + const firstValue = this.cache.get(firstKey); + this.currentMemoryBytes -= firstValue.size; + this.cache.delete(firstKey); + } + + // Add new entry + this.cache.set(key, { data, size: estimatedSize }); + this.currentMemoryBytes += estimatedSize; + } + + has(key) { + return this.cache.has(key); + } + + delete(key) { + if (this.cache.has(key)) { + const value = this.cache.get(key); + this.currentMemoryBytes -= value.size; + this.cache.delete(key); + return true; + } + return false; + } + + clear() { + this.cache.clear(); + this.currentMemoryBytes = 0; + } + + get size() { + return this.cache.size; + } + + getMemoryUsage() { + return { + entries: this.cache.size, + memoryBytes: this.currentMemoryBytes, + memoryMB: this.currentMemoryBytes / (1024 * 1024), + }; + } + } + + /** + * Resource Manager - handles per-instance resources and lifecycle + */ + class PMTilesResourceManager { + constructor(options = {}) { + this.config = { ...DEFAULT_OPTIONS, ...options }; + this.destroyed = false; + this.paused = false; + this.dispatcher = null; + + // Instance-scoped resources + this.workerPool = []; + this.workerPoolIndex = 0; + this.tileCache = new LRUCache( + this.config.tileCacheSize, + this.config.tileCacheMaxMemoryMB * 1024 * 1024, + ); + this.pendingRequests = new Map(); + this.activeRequests = new Set(); + + // Performance tracking + this.metrics = { + tilesLoaded: 0, + cacheHits: 0, + cacheMisses: 0, + memoryPeakMB: 0, + averageLoadTimeMs: 0, + }; + + // Register for global cleanup + GLOBAL_SHARED_RESOURCES.activeManagers.add(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager created", this.config); + } + } + + /** + * Initialize worker pool + */ + initializeWorkerPool(dispatcher) { + if (this.destroyed) return; + + // Store dispatcher reference + if (dispatcher) { + this.dispatcher = dispatcher; + } + + if (this.workerPool.length === 0 && this.dispatcher) { + for (let i = 0; i < this.config.workerPoolSize; i++) { + try { + this.workerPool.push(this.dispatcher.getActor()); + } catch (error) { + console.warn("[PMTiles] Failed to create worker:", error); + } + } + + if (this.config.enableDebugLogging) { + console.log( + `[PMTiles] Initialized worker pool with ${this.workerPool.length} workers`, + ); + } + } + } + + /** + * Get next worker from pool (round-robin) + */ + getWorkerFromPool() { + if (this.destroyed) { + return null; + } + + // Try to initialize workers if not done yet + if (this.workerPool.length === 0 && this.dispatcher) { + this.initializeWorkerPool(this.dispatcher); + } + + if (this.workerPool.length === 0) { + if (this.config.enableDebugLogging) { + console.warn( + "[PMTiles] Worker pool is empty, dispatcher available:", + !!this.dispatcher, + ); + } + return null; + } + + const worker = this.workerPool[this.workerPoolIndex]; + this.workerPoolIndex = + (this.workerPoolIndex + 1) % this.workerPool.length; + return worker; + } + + /** + * Get or create protocol instance with reference counting + */ + getProtocol(url) { + if (this.destroyed) return null; + + if (!this.config.enableSharedProtocols) { + // Create instance-specific protocol + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + return { protocol, instance }; + } + + // Use shared protocol with reference counting + if (!GLOBAL_SHARED_RESOURCES.protocolCache.has(url)) { + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + GLOBAL_SHARED_RESOURCES.protocolCache.set(url, { + protocol, + instance, + refCount: 0, + }); + } + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + cached.refCount++; + return cached; + } + + /** + * Release protocol reference + */ + releaseProtocol(url) { + if (!this.config.enableSharedProtocols) return; + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + if (cached) { + cached.refCount--; + if (cached.refCount <= 0) { + GLOBAL_SHARED_RESOURCES.protocolCache.delete(url); + + if (this.config.enableDebugLogging) { + console.log(`[PMTiles] Released protocol for ${url}`); + } + } + } + } + + /** + * Cache key for tiles + */ + getTileCacheKey(url, z, x, y) { + return `${url}:${z}:${x}:${y}`; + } + + /** + * Add tile to cache with size estimation + */ + addToTileCache(key, data) { + if (this.destroyed) return; + + let estimatedSize = 0; + if (data instanceof ImageBitmap) { + // Rough estimation: width * height * 4 bytes per pixel + estimatedSize = data.width * data.height * 4; + } else if (data && data.byteLength) { + estimatedSize = data.byteLength; + } else { + estimatedSize = 10000; // Default estimate + } + + this.tileCache.set(key, data, estimatedSize); + + // Update peak memory usage + const memoryUsage = this.tileCache.getMemoryUsage(); + this.metrics.memoryPeakMB = Math.max( + this.metrics.memoryPeakMB, + memoryUsage.memoryMB, + ); + } + + /** + * Get cached metadata + */ + getCachedMetadata(cacheKey) { + return GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + } + + /** + * Set cached metadata + */ + setCachedMetadata(cacheKey, data) { + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, data); + } + + /** + * Pause all operations + */ + pause() { + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager paused"); + } + } + + /** + * Resume operations + */ + resume() { + this.paused = false; + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager resumed"); + } + } + + /** + * Get performance metrics + */ + getMetrics() { + return { + ...this.metrics, + tileCache: this.tileCache.getMemoryUsage(), + workerPoolSize: this.workerPool.length, + pendingRequests: this.pendingRequests.size, + isPaused: this.paused, + isDestroyed: this.destroyed, + }; + } + + /** + * Destroy and cleanup all resources + */ + destroy() { + if (this.destroyed) return; + + this.destroyed = true; + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + // Clear caches + this.tileCache.clear(); + + // Clear worker pool references + this.workerPool.length = 0; + + // Remove from global registry + GLOBAL_SHARED_RESOURCES.activeManagers.delete(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager destroyed", this.getMetrics()); + } + } + } + + /** + * Global cleanup function + */ + const cleanup = () => { + for (const manager of GLOBAL_SHARED_RESOURCES.activeManagers) { + manager.destroy(); + } + GLOBAL_SHARED_RESOURCES.protocolCache.clear(); + GLOBAL_SHARED_RESOURCES.metadataCache.clear(); + }; + + // Register global cleanup + if (typeof window !== "undefined") { + window.addEventListener("beforeunload", cleanup); + } + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + + // Pre-calculate mercator bounds + this._mercatorBounds = { + west: mercatorXFromLng(this.bounds.getWest()), + north: mercatorYFromLat(this.bounds.getNorth()), + east: mercatorXFromLng(this.bounds.getEast()), + south: mercatorYFromLat(this.bounds.getSouth()), + }; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + // Use pre-calculated world size + const worldSize = + GLOBAL_SHARED_RESOURCES.worldSizeCache[tileID.z] || + Math.pow(2, tileID.z); + + // Use pre-calculated mercator bounds + const level = { + minX: Math.floor(this._mercatorBounds.west * worldSize), + minY: Math.floor(this._mercatorBounds.north * worldSize), + maxX: Math.ceil(this._mercatorBounds.east * worldSize), + maxY: Math.ceil(this._mercatorBounds.south * worldSize), + }; + + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + /** + * Enhanced PMTiles Source with lifecycle management + */ + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + + // Extract PMTiles-specific options + const pmtilesOptions = { + workerPoolSize: options.workerPoolSize, + tileCacheSize: options.tileCacheSize, + tileCacheMaxMemoryMB: options.tileCacheMaxMemoryMB, + metadataCacheSize: options.metadataCacheSize, + enableSharedProtocols: options.enableSharedProtocols, + requestTimeoutMs: options.requestTimeoutMs, + enableDebugLogging: options.enableDebugLogging, + enablePerformanceMetrics: options.enablePerformanceMetrics, + }; + + // Initialize resource manager + this.resourceManager = new PMTilesResourceManager(pmtilesOptions); + + // Standard source properties + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = _dispatcher; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._implementation = options; + + // Initialize worker pool + this.resourceManager.initializeWorkerPool(_dispatcher); + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + return; + } + + const { url } = options; + this.url = url; + this.tileSize = 512; + + // Get protocol instance + this.protocolInfo = this.resourceManager.getProtocol(url); + if (!this.protocolInfo) { + this.fire( + new ErrorEvent(new Error(`Failed to create protocol for ${url}`)), + ); + return; + } + + this._protocol = this.protocolInfo.protocol; + this._instance = this.protocolInfo.instance; + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + } + + static async getMetadata(url) { + // Check cache first + const cacheKey = `${url}:metadata`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const metadata = await instance.getMetadata(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, metadata); + return metadata; + } + + static async getHeader(url) { + // Check cache first + const cacheKey = `${url}:header`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const header = await instance.getHeader(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, header); + return header; + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (this.resourceManager.destroyed) return; + + if (!tile.destroy) { + tile.destroy = () => {}; + } + if (!tile.abort) { + tile.abort = () => { + tile.aborted = true; + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + }; + } + } + + /** + * Pause tile loading + */ + pause() { + this.resourceManager.pause(); + } + + /** + * Resume tile loading + */ + resume() { + this.resourceManager.resume(); + } + + /** + * Get performance metrics + */ + getMetrics() { + return this.resourceManager.getMetrics(); + } + + /** + * Destroy source and cleanup resources + */ + destroy() { + if (this.protocolInfo && this.url) { + this.resourceManager.releaseProtocol(this.url); + } + + this.resourceManager.destroy(); + this._loaded = false; + } + + async load(callback) { + if (this.resourceManager.destroyed) { + const error = new Error("Source has been destroyed"); + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + // Check metadata cache first + const headerKey = `${this.url}:header`; + const metadataKey = `${this.url}:metadata`; + + let header, tileJSON; + + const cachedHeader = this.resourceManager.getCachedMetadata(headerKey); + const cachedMetadata = + this.resourceManager.getCachedMetadata(metadataKey); + + if (cachedHeader && cachedMetadata) { + header = cachedHeader; + tileJSON = cachedMetadata; + } else { + try { + // Load and cache + [header, tileJSON] = await Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]); + this.resourceManager.setCachedMetadata(headerKey, header); + this.resourceManager.setCachedMetadata(metadataKey, tileJSON); + } catch (error) { + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + } + + try { + extend(this, tileJSON); + this.header = header; + const { tileType, minZoom, maxZoom, minLon, minLat, maxLon, maxLat } = + header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes(this.tileType) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { dataType: "source", sourceDataType: "metadata" }), + ); + this.fire( + new Event("data", { dataType: "source", sourceDataType: "content" }), + ); + } catch (err2) { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + } + } + + loaded() { + return this._loaded && !this.resourceManager.destroyed; + } + + loadVectorTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + const startTime = Date.now(); + var _a2, _b2, _c; + + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + + // Update metrics + this.resourceManager.metrics.tilesLoaded++; + const loadTime = Date.now() - startTime; + this.resourceManager.metrics.averageLoadTimeMs = + (this.resourceManager.metrics.averageLoadTimeMs + loadTime) / 2; + + if (tile.aborted) return callback(null); + + // Handle abort errors gracefully + if (err2 && err2.name === "AbortError") { + return callback(null); + } + + if (err2 && err2.status !== 404) { + return callback(err2); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + // Handle abort errors gracefully + if (error && (error.name === "AbortError" || error.code === 20)) { + return done.call(this, null); + } + done.call(this, error); + return; + } + + params.data = { + cacheControl, + expires, + rawData: data, + }; + + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + // Use shared worker pool + tile.actor = this.resourceManager.getWorkerFromPool(); + + // Fallback to dispatcher if worker pool failed + if (!tile.actor && this.dispatcher) { + try { + tile.actor = this.dispatcher.getActor(); + } catch (error) { + console.warn("[PMTiles] Failed to get fallback worker:", error); + return callback(new Error("No workers available")); + } + } + + if (!tile.actor) { + return callback(new Error("No workers available")); + } + + // Create request with timeout + const requestPromise = this._protocol.tile({ ...request }, afterLoad); + + // Add timeout if configured + if (this.resourceManager.config.requestTimeoutMs > 0) { + const timeoutId = setTimeout(() => { + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + done.call(this, new Error("Request timeout")); + }, this.resourceManager.config.requestTimeoutMs); + + const originalCancel = requestPromise.cancel; + requestPromise.cancel = () => { + clearTimeout(timeoutId); + if (originalCancel) originalCancel(); + }; + } + + tile.request = requestPromise; + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + if (this.resourceManager.destroyed) return; + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + var _a2, _b2; + + // Check tile cache first + const cacheKey = this.resourceManager.getTileCacheKey( + this.url, + tile.tileID.canonical.z, + tile.tileID.canonical.x, + tile.tileID.canonical.y, + ); + + if (this.resourceManager.tileCache.has(cacheKey)) { + this.resourceManager.metrics.cacheHits++; + const cachedData = this.resourceManager.tileCache.get(cacheKey); + this.loadRasterTileData(tile, cachedData); + tile.state = "loaded"; + return callback(null); + } + + this.resourceManager.metrics.cacheMisses++; + + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + + // Optimized raster tile loading - try direct ArrayBuffer first + const arrayBuffer = data.buffer || data; + window + .createImageBitmap(arrayBuffer) + .then((imageBitmap) => { + // Cache the decoded image + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + // Fallback to blob method + const blob = new window.Blob([new Uint8Array(data)], { + type: this.contentType, + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error(`Can't decode image for ${this.id}: ${error}`), + ); + }); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + this.fixTile(tile); + const controller = new AbortController(); + + // Add timeout if configured + let timeoutId; + if (this.resourceManager.config.requestTimeoutMs > 0) { + timeoutId = setTimeout(() => { + controller.abort(); + }, this.resourceManager.config.requestTimeoutMs); + } + + tile.request = { + cancel: () => { + if (timeoutId) clearTimeout(timeoutId); + controller.abort(); + }, + }; + + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (timeoutId) clearTimeout(timeoutId); + + // Handle abort errors gracefully + if (error.name === "AbortError" || error.code === 20) { + delete tile.request; + return callback(null); + } + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Expose cleanup function + PmTilesSource.cleanup = cleanup; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; + global.PMTilesResourceManager = PMTilesResourceManager; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/map-design_files/mapbox-pmtiles-1.1.0/pmtiles-source.js b/docs/articles/map-design_files/mapbox-pmtiles-1.1.0/pmtiles-source.js new file mode 100644 index 0000000..2130749 --- /dev/null +++ b/docs/articles/map-design_files/mapbox-pmtiles-1.1.0/pmtiles-source.js @@ -0,0 +1,459 @@ +/** + * mapbox-pmtiles v1.0.53 + * Original source: https://github.com/am2222/mapbox-pmtiles + * License: MIT + * + * This is a vendored copy of the mapbox-pmtiles library that provides + * PMTiles support for Mapbox GL JS by implementing a custom source type. + * + * Last updated: 2024 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + const worldSize = Math.pow(2, tileID.z); + const level = { + minX: Math.floor(mercatorXFromLng(this.bounds.getWest()) * worldSize), + minY: Math.floor(mercatorYFromLat(this.bounds.getNorth()) * worldSize), + maxX: Math.ceil(mercatorXFromLng(this.bounds.getEast()) * worldSize), + maxY: Math.ceil(mercatorYFromLat(this.bounds.getSouth()) * worldSize), + }; + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = void 0; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._dataType = "vector"; + this.dispatcher = _dispatcher; + this._implementation = options; + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + } + + const { url } = options; + this.reparseOverscaled = true; + this.scheme = "xyz"; + this.tileSize = 512; + this._loaded = false; + this.type = "vector"; + this._protocol = new pmtiles.Protocol(); + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + const pmtilesInstance = new pmtiles.PMTiles(url); + this._protocol.add(pmtilesInstance); + this._instance = pmtilesInstance; + } + + static async getMetadata(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getMetadata(); + } + + static async getHeader(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getHeader(); + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (!tile.destroy) { + tile.destroy = () => {}; + } + } + + async load(callback) { + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + return Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]) + .then(([header, tileJSON]) => { + extend(this, tileJSON); + this.header = header; + const { + specVersion, + clustered, + tileType, + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + centerZoom, + centerLon, + centerLat, + } = header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes( + this.tileType, + ) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "metadata", + }), + ); + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "content", + }), + ); + }) + .catch((err2) => { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + }); + } + + loaded() { + return this._loaded; + } + + loadVectorTile(tile, callback) { + var _a2, _b2, _c; + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + if (tile.aborted) return callback(null); + if (err2 && err2.status !== 404) { + return callback(err2); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + done.call(this, error); + return; + } + params.data = { + cacheControl, + expires, + rawData: data, + }; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + tile.actor = this._tileWorkers[url] = + this._tileWorkers[url] || this.dispatcher.getActor(); + tile.request = this._protocol.tile({ ...request }, afterLoad); + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + var _a2, _b2; + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + const blob = new window.Blob([new Uint8Array(data)], { + type: "image/png", + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error( + `Can't infer data type for ${this.id}, only raster data supported at the moment. ${error}`, + ), + ); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + this.fixTile(tile); + const controller = new AbortController(); + tile.request = { cancel: () => controller.abort() }; + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (error.code === 20) return; + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/layers-overview_files/mapboxgl-binding-0.2.9.9000/mapboxgl.js b/docs/articles/map-design_files/mapboxgl-binding-0.3.1.9000/mapboxgl.js similarity index 89% rename from docs/articles/layers-overview_files/mapboxgl-binding-0.2.9.9000/mapboxgl.js rename to docs/articles/map-design_files/mapboxgl-binding-0.3.1.9000/mapboxgl.js index b9f2563..700670b 100644 --- a/docs/articles/layers-overview_files/mapboxgl-binding-0.2.9.9000/mapboxgl.js +++ b/docs/articles/map-design_files/mapboxgl-binding-0.3.1.9000/mapboxgl.js @@ -292,6 +292,22 @@ HTMLWidgets.widget({ return; } + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + mapboxgl.accessToken = x.access_token; map = new mapboxgl.Map({ @@ -477,6 +493,18 @@ HTMLWidgets.widget({ urls: source.urls, coordinates: source.coordinates, }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); } }); } @@ -887,6 +915,85 @@ HTMLWidgets.widget({ drawBar.style.flexDirection = "row"; } } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } } // Helper function to add features from a source to draw @@ -1128,17 +1235,17 @@ HTMLWidgets.widget({ // Set the position correctly - fix position bug by using correct CSS positioning const position = x.layers_control.position || "top-left"; if (position === "top-left") { - layersControl.style.top = "10px"; - layersControl.style.left = "10px"; + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; } else if (position === "top-right") { - layersControl.style.top = "10px"; - layersControl.style.right = "10px"; + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; } else if (position === "bottom-left") { - layersControl.style.bottom = "30px"; - layersControl.style.left = "10px"; + layersControl.style.bottom = (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; } else if (position === "bottom-right") { - layersControl.style.bottom = "40px"; - layersControl.style.right = "10px"; + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; } // Apply custom colors if provided @@ -1343,38 +1450,44 @@ HTMLWidgets.widget({ // add hover listener for shinyMode if enabled if (x.hover_events && x.hover_events.enabled) { - map.on("mousemove", function (e) { - // Feature hover events - if (x.hover_events.features) { - const features = map.queryRenderedFeatures(e.point); - - if(features.length > 0) { - const feature = features[0]; - Shiny.onInputChange(el.id + "_feature_hover", { - id: feature.id, - properties: feature.properties, - layer: feature.layer.id, - lng: e.lngLat.lng, - lat: e.lngLat.lat, - time: new Date(), - }); - } else { - Shiny.onInputChange( - el.id + "_feature_hover", - null, - ); - } + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); } + } - // Coordinate hover events - if (x.hover_events.coordinates) { - Shiny.onInputChange(el.id + "_hover", { - lng: e.lngLat.lng, - lat: e.lngLat.lat, - time: new Date(), - }); - } - }); + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); } } @@ -1580,6 +1693,18 @@ if (HTMLWidgets.shinyMode) { sourceConfig[key] = message.source[key]; } }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); } } else if (message.type === "add_layer") { @@ -1846,6 +1971,52 @@ if (HTMLWidgets.shinyMode) { layerState.paintProperties[layerId] = {}; } layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); } else if (message.type === "add_legend") { // Extract legend ID from HTML to track it const legendIdMatch = message.html.match(/id="([^"]+)"/); @@ -2321,6 +2492,85 @@ if (HTMLWidgets.shinyMode) { drawBar.style.flexDirection = "row"; } } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } } else if (message.type === "get_drawn_features") { var drawControl = widget.drawControl || widget.getDraw(); if (drawControl) { @@ -2494,17 +2744,17 @@ if (HTMLWidgets.shinyMode) { // Set the position correctly const position = message.position || "top-left"; if (position === "top-left") { - layersControl.style.top = "10px"; - layersControl.style.left = "10px"; + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; } else if (position === "top-right") { - layersControl.style.top = "10px"; - layersControl.style.right = "10px"; + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; } else if (position === "bottom-left") { - layersControl.style.bottom = "30px"; - layersControl.style.left = "10px"; + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; } else if (position === "bottom-right") { - layersControl.style.bottom = "40px"; - layersControl.style.right = "10px"; + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; } // Apply custom colors if provided diff --git a/docs/articles/map-design_files/mapboxgl-binding-0.3.2/mapboxgl.js b/docs/articles/map-design_files/mapboxgl-binding-0.3.2/mapboxgl.js new file mode 100644 index 0000000..42e4216 --- /dev/null +++ b/docs/articles/map-design_files/mapboxgl-binding-0.3.2/mapboxgl.js @@ -0,0 +1,3197 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/map-design_files/mapboxgl-binding-0.3.9.9000/mapboxgl.js b/docs/articles/map-design_files/mapboxgl-binding-0.3.9.9000/mapboxgl.js new file mode 100644 index 0000000..182e834 --- /dev/null +++ b/docs/articles/map-design_files/mapboxgl-binding-0.3.9.9000/mapboxgl.js @@ -0,0 +1,3249 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/map-design_files/mapboxgl-binding-0.4.0.9000/mapboxgl.js b/docs/articles/map-design_files/mapboxgl-binding-0.4.0.9000/mapboxgl.js new file mode 100644 index 0000000..3fee4ba --- /dev/null +++ b/docs/articles/map-design_files/mapboxgl-binding-0.4.0.9000/mapboxgl.js @@ -0,0 +1,3418 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/map-design_files/mapboxgl-binding-0.4.0/mapboxgl.js b/docs/articles/map-design_files/mapboxgl-binding-0.4.0/mapboxgl.js new file mode 100644 index 0000000..182e834 --- /dev/null +++ b/docs/articles/map-design_files/mapboxgl-binding-0.4.0/mapboxgl.js @@ -0,0 +1,3249 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/map-design_files/mapboxgl-binding-0.4.1/mapboxgl.js b/docs/articles/map-design_files/mapboxgl-binding-0.4.1/mapboxgl.js new file mode 100644 index 0000000..c0d6d59 --- /dev/null +++ b/docs/articles/map-design_files/mapboxgl-binding-0.4.1/mapboxgl.js @@ -0,0 +1,3910 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/map-design_files/pmtiles-4.3.0/pmtiles.js b/docs/articles/map-design_files/pmtiles-4.3.0/pmtiles.js new file mode 100644 index 0000000..1a901ee --- /dev/null +++ b/docs/articles/map-design_files/pmtiles-4.3.0/pmtiles.js @@ -0,0 +1,2 @@ +"use strict";var pmtiles=(()=>{var k=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var U=Math.pow;var f=(r,e)=>k(r,"name",{value:e,configurable:!0});var Xe=(r,e)=>{for(var t in e)k(r,t,{get:e[t],enumerable:!0})},_e=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ye(e))!Qe.call(r,i)&&i!==t&&k(r,i,{get:()=>e[i],enumerable:!(n=Je(e,i))||n.enumerable});return r};var et=r=>_e(k({},"__esModule",{value:!0}),r);var m=(r,e,t)=>new Promise((n,i)=>{var a=h=>{try{u(t.next(h))}catch(l){i(l)}},s=h=>{try{u(t.throw(h))}catch(l){i(l)}},u=h=>h.done?n(h.value):Promise.resolve(h.value).then(a,s);u((t=t.apply(r,e)).next())});var Dt={};Xe(Dt,{Compression:()=>Oe,EtagMismatch:()=>B,FetchSource:()=>K,FileSource:()=>oe,PMTiles:()=>P,Protocol:()=>ie,ResolvedValueCache:()=>ue,SharedPromiseCache:()=>G,TileType:()=>se,bytesToHeader:()=>$e,findTile:()=>Fe,getUint64:()=>b,leafletRasterLayer:()=>wt,readVarint:()=>R,tileIdToZxy:()=>Tt,tileTypeExt:()=>Ze,zxyToTileId:()=>Ie});var w=Uint8Array,E=Uint16Array,tt=Int32Array,Me=new w([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ue=new w([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),rt=new w([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ee=f(function(r,e){for(var t=new E(31),n=0;n<31;++n)t[n]=e+=1<>1|(g&21845)<<1,T=(T&52428)>>2|(T&13107)<<2,T=(T&61680)>>4|(T&3855)<<4,re[g]=((T&65280)>>8|(T&255)<<8)>>1;var T,g,F=f(function(r,e,t){for(var n=r.length,i=0,a=new E(e);i>h]=l}else for(u=new E(n),i=0;i>15-r[i]);return u},"hMap"),$=new w(288);for(g=0;g<144;++g)$[g]=8;var g;for(g=144;g<256;++g)$[g]=9;var g;for(g=256;g<280;++g)$[g]=7;var g;for(g=280;g<288;++g)$[g]=8;var g,Re=new w(32);for(g=0;g<32;++g)Re[g]=5;var g;var at=F($,9,1);var st=F(Re,5,1),ee=f(function(r){for(var e=r[0],t=1;te&&(e=r[t]);return e},"max"),z=f(function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},"bits"),te=f(function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},"bits16"),ot=f(function(r){return(r+7)/8|0},"shft"),ut=f(function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new w(r.subarray(e,t))},"slc");var ft=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],y=f(function(r,e,t){var n=new Error(e||ft[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,y),!t)throw n;return n},"err"),ne=f(function(r,e,t,n){var i=r.length,a=n?n.length:0;if(!i||e.f&&!e.l)return t||new w(0);var s=!t,u=s||e.i!=2,h=e.i;s&&(t=new w(i*3));var l=f(function(Te){var Ce=t.length;if(Te>Ce){var De=new w(Math.max(Ce*2,Te));De.set(t),t=De}},"cbuf"),c=e.f||0,o=e.p||0,v=e.b||0,d=e.l,p=e.d,H=e.m,I=e.n,q=i*8;do{if(!d){c=z(r,o,1);var j=z(r,o+1,3);if(o+=3,j)if(j==1)d=at,p=st,H=9,I=5;else if(j==2){var J=z(r,o,31)+257,me=z(r,o+10,15)+4,de=J+z(r,o+5,31)+1;o+=14;for(var O=new w(de),Y=new w(19),x=0;x>4;if(A<16)O[x++]=A;else{var D=0,V=0;for(A==16?(V=3+z(r,o,3),o+=2,D=O[x-1]):A==17?(V=3+z(r,o,7),o+=3):A==18&&(V=11+z(r,o,127),o+=7);V--;)O[x++]=D}}var xe=O.subarray(0,J),C=O.subarray(J);H=ee(xe),I=ee(C),d=F(xe,H,1),p=F(C,I,1)}else y(1);else{var A=ot(o)+4,W=r[A-4]|r[A-3]<<8,N=A+W;if(N>i){h&&y(0);break}u&&l(v+W),t.set(r.subarray(A,N),v),e.b=v+=W,e.p=o=N*8,e.f=c;continue}if(o>q){h&&y(0);break}}u&&l(v+131072);for(var je=(1<>4;if(o+=D&15,o>q){h&&y(0);break}if(D||y(2),M<256)t[v++]=M;else if(M==256){Q=o,d=null;break}else{var be=M-254;if(M>264){var x=M-257,Z=Me[x];be=z(r,o,(1<>4;X||y(3),o+=X&15;var C=it[_];if(_>3){var Z=Ue[_];C+=te(r,o)&(1<q){h&&y(0);break}u&&l(v+131072);var ze=v+be;if(v>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},"gzs"),ct=f(function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0},"gzl");var vt=f(function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&y(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&y(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2},"zls");function gt(r,e){return ne(r,{i:2},e&&e.out,e&&e.dictionary)}f(gt,"inflateSync");function pt(r,e){var t=ht(r);return t+8>r.length&&y(6,"invalid gzip data"),ne(r.subarray(t,-8),{i:2},e&&e.out||new w(ct(r)),e&&e.dictionary)}f(pt,"gunzipSync");function mt(r,e){return ne(r.subarray(vt(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}f(mt,"unzlibSync");function Be(r,e){return r[0]==31&&r[1]==139&&r[2]==8?pt(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?gt(r,e):mt(r,e)}f(Be,"decompressSync");var dt=typeof TextDecoder!="undefined"&&new TextDecoder,yt=0;try{dt.decode(lt,{stream:!0}),yt=1}catch(r){}var wt=f((r,e)=>{let t=!1,n="",i=L.GridLayer.extend({createTile:f((a,s)=>{let u=document.createElement("img"),h=new AbortController,l=h.signal;return u.cancel=()=>{h.abort()},t||(r.getHeader().then(c=>{c.tileType===1?console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):c.tileType===2?n="image/png":c.tileType===3?n="image/jpeg":c.tileType===4?n="image/webp":c.tileType===5&&(n="image/avif")}),t=!0),r.getZxy(a.z,a.x,a.y,l).then(c=>{if(c){let o=new Blob([c.data],{type:n}),v=window.URL.createObjectURL(o);u.src=v,u.cancel=void 0,s(void 0,u)}}).catch(c=>{if(c.name!=="AbortError")throw c}),u},"createTile"),_removeTile:f(function(a){let s=this._tiles[a];s&&(s.el.cancel&&s.el.cancel(),s.el.width=0,s.el.height=0,s.el.deleted=!0,L.DomUtil.remove(s.el),delete this._tiles[a],this.fire("tileunload",{tile:s.el,coords:this._keyToTileCoords(a)}))},"_removeTile")});return new i(e)},"leafletRasterLayer"),xt=f(r=>(e,t)=>{if(t instanceof AbortController)return r(e,t);let n=new AbortController;return r(e,n).then(i=>t(void 0,i.data,i.cacheControl||"",i.expires||""),i=>t(i)).catch(i=>t(i)),{cancel:f(()=>n.abort(),"cancel")}},"v3compat"),ae=class ae{constructor(e){this.tilev4=f((e,t)=>m(this,null,function*(){if(e.type==="json"){let v=e.url.substr(10),d=this.tiles.get(v);if(d||(d=new P(v),this.tiles.set(v,d)),this.metadata)return{data:yield d.getTileJson(e.url)};let p=yield d.getHeader();return(p.minLon>=p.maxLon||p.minLat>=p.maxLat)&&console.error(`Bounds of PMTiles archive ${p.minLon},${p.minLat},${p.maxLon},${p.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:p.minZoom,maxzoom:p.maxZoom,bounds:[p.minLon,p.minLat,p.maxLon,p.maxLat]}}}let n=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),i=e.url.match(n);if(!i)throw new Error("Invalid PMTiles protocol URL");let a=i[1],s=this.tiles.get(a);s||(s=new P(a),this.tiles.set(a,s));let u=i[2],h=i[3],l=i[4],c=yield s.getHeader(),o=yield s==null?void 0:s.getZxy(+u,+h,+l,t.signal);if(o)return{data:new Uint8Array(o.data),cacheControl:o.cacheControl,expires:o.expires};if(c.tileType===1){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4");this.tile=xt(this.tilev4);this.tiles=new Map,this.metadata=(e==null?void 0:e.metadata)||!1,this.errorOnMissingTile=(e==null?void 0:e.errorOnMissingTile)||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};f(ae,"Protocol");var ie=ae;function S(r,e){return(e>>>0)*4294967296+(r>>>0)}f(S,"toNum");function bt(r,e){let t=e.buf,n=t[e.pos++],i=(n&112)>>4;if(n<128||(n=t[e.pos++],i|=(n&127)<<3,n<128)||(n=t[e.pos++],i|=(n&127)<<10,n<128)||(n=t[e.pos++],i|=(n&127)<<17,n<128)||(n=t[e.pos++],i|=(n&127)<<24,n<128)||(n=t[e.pos++],i|=(n&1)<<31,n<128))return S(r,i);throw new Error("Expected varint not more than 10 bytes")}f(bt,"readVarintRemainder");function R(r){let e=r.buf,t=e[r.pos++],n=t&127;return t<128||(t=e[r.pos++],n|=(t&127)<<7,t<128)||(t=e[r.pos++],n|=(t&127)<<14,t<128)||(t=e[r.pos++],n|=(t&127)<<21,t<128)?n:(t=e[r.pos],n|=(t&15)<<28,bt(n,r))}f(R,"readVarint");function He(r,e,t,n){if(n===0){t===1&&(e[0]=r-1-e[0],e[1]=r-1-e[1]);let i=e[0];e[0]=e[1],e[1]=i}}f(He,"rotate");function zt(r,e){let t=U(2,r),n=e,i=e,a=e,s=[0,0],u=1;for(;u26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>U(2,r)-1||t>U(2,r)-1)throw new Error("tile x/y outside zoom level bounds");let n=At[r],i=U(2,r),a=0,s=0,u=0,h=[e,t],l=i/2;for(;l>0;)a=(h[0]&l)>0?1:0,s=(h[1]&l)>0?1:0,u+=l*l*(3*a^s),He(l,h,a,s),l=l/2;return n+u}f(Ie,"zxyToTileId");function Tt(r){let e=0,t=0;for(let n=0;n<27;n++){let i=(1<r)return zt(n,r-e);e+=i}throw new Error("Tile zoom level exceeds max safe number limit (26)")}f(Tt,"tileIdToZxy");var Oe=(a=>(a[a.Unknown=0]="Unknown",a[a.None=1]="None",a[a.Gzip=2]="Gzip",a[a.Brotli=3]="Brotli",a[a.Zstd=4]="Zstd",a))(Oe||{});function fe(r,e){return m(this,null,function*(){if(e===1||e===0)return r;if(e===2){if(typeof globalThis.DecompressionStream=="undefined")return Be(new Uint8Array(r));let t=new Response(r).body;if(!t)throw new Error("Failed to read response stream");let n=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(n).arrayBuffer()}throw new Error("Compression method not supported")})}f(fe,"defaultDecompress");var se=(s=>(s[s.Unknown=0]="Unknown",s[s.Mvt=1]="Mvt",s[s.Png=2]="Png",s[s.Jpeg=3]="Jpeg",s[s.Webp=4]="Webp",s[s.Avif=5]="Avif",s))(se||{});function Ze(r){return r===1?".mvt":r===2?".png":r===3?".jpg":r===4?".webp":r===5?".avif":""}f(Ze,"tileTypeExt");var Ct=127;function Fe(r,e){let t=0,n=r.length-1;for(;t<=n;){let i=n+t>>1,a=e-r[i].tileId;if(a>0)t=i+1;else if(a<0)n=i-1;else return r[i]}return n>=0&&(r[n].runLength===0||e-r[n].tileId-1,a=/Chrome|Chromium|Edg|OPR|Brave/.test(n);this.chromeWindowsNoCache=!1,i&&a&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,n,i){return m(this,null,function*(){let a,s;n?s=n:(a=new AbortController,s=a.signal);let u=new Headers(this.customHeaders);u.set("range",`bytes=${e}-${e+t-1}`);let h;this.mustReload?h="reload":this.chromeWindowsNoCache&&(h="no-store");let l=yield fetch(this.url,{signal:s,cache:h,headers:u});if(e===0&&l.status===416){let d=l.headers.get("Content-Range");if(!d||!d.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let p=+d.substr(8);l=yield fetch(this.url,{signal:s,cache:"reload",headers:{range:`bytes=0-${p-1}`}})}let c=l.headers.get("Etag");if(c!=null&&c.startsWith("W/")&&(c=null),l.status===416||i&&c&&c!==i)throw this.mustReload=!0,new B(`Server returned non-matching ETag ${i} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(l.status>=300)throw new Error(`Bad response code: ${l.status}`);let o=l.headers.get("Content-Length");if(l.status===200&&(!o||+o>t))throw a&&a.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield l.arrayBuffer(),etag:c||void 0,cacheControl:l.headers.get("Cache-Control")||void 0,expires:l.headers.get("Expires")||void 0}})}};f(he,"FetchSource");var K=he;function b(r,e){let t=r.getUint32(e+4,!0),n=r.getUint32(e+0,!0);return t*U(2,32)+n}f(b,"getUint64");function $e(r,e){let t=new DataView(r),n=t.getUint8(7);if(n>3)throw new Error(`Archive is spec version ${n} but this library supports up to spec version 3`);return{specVersion:n,rootDirectoryOffset:b(t,8),rootDirectoryLength:b(t,16),jsonMetadataOffset:b(t,24),jsonMetadataLength:b(t,32),leafDirectoryOffset:b(t,40),leafDirectoryLength:b(t,48),tileDataOffset:b(t,56),tileDataLength:b(t,64),numAddressedTiles:b(t,72),numTileEntries:b(t,80),numTileContents:b(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}f($e,"bytesToHeader");function Ve(r){let e={buf:new Uint8Array(r),pos:0},t=R(e),n=[],i=0;for(let a=0;a0?n[a].offset=n[a-1].offset+n[a-1].length:n[a].offset=s-1}return n}f(Ve,"deserializeIndex");var ce=class ce extends Error{};f(ce,"EtagMismatch");var B=ce;function ke(r,e){return m(this,null,function*(){let t=yield r.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let i=t.data.slice(0,Ct),a=$e(i,t.etag),s=t.data.slice(a.rootDirectoryOffset,a.rootDirectoryOffset+a.rootDirectoryLength),u=`${r.getKey()}|${a.etag||""}|${a.rootDirectoryOffset}|${a.rootDirectoryLength}`,h=Ve(yield e(s,a.internalCompression));return[a,[u,h.length,h]]})}f(ke,"getHeaderAndRoot");function Ke(r,e,t,n,i){return m(this,null,function*(){let a=yield r.getBytes(t,n,void 0,i.etag),s=yield e(a.data,i.internalCompression),u=Ve(s);if(u.length===0)throw new Error("Empty directory is invalid");return u})}f(Ke,"getDirectory");var ve=class ve{constructor(e=100,t=!0,n=fe){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return m(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,n.data;let i=yield ke(e,this.decompress);return i[1]&&this.cache.set(i[1][0],{lastUsed:this.counter++,data:i[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:i[0]}),this.prune(),i[0]})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,s.data;let u=yield Ke(e,this.decompress,t,n,i);return this.cache.set(a,{lastUsed:this.counter++,data:u}),this.prune(),u})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{ke(e,this.decompress).then(u=>{u[1]&&this.cache.set(u[1][0],{lastUsed:this.counter++,data:Promise.resolve(u[1][2])}),a(u[0]),this.prune()}).catch(u=>{s(u)})});return this.cache.set(t,{lastUsed:this.counter++,data:i}),i})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,yield s.data;let u=new Promise((h,l)=>{Ke(e,this.decompress,t,n,i).then(c=>{h(c),this.prune()}).catch(c=>{l(c)})});return this.cache.set(a,{lastUsed:this.counter++,data:u}),u})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{this.getHeader(e).then(s=>{i(),this.invalidations.delete(t)}).catch(s=>{a(s)})});this.invalidations.set(t,n)})}};f(ge,"SharedPromiseCache");var G=ge,pe=class pe{constructor(e,t,n){typeof e=="string"?this.source=new K(e):this.source=e,n?this.decompress=n:this.decompress=fe,t?this.cache=t:this.cache=new G}getHeader(){return m(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,n,i){return m(this,null,function*(){let a=Ie(e,t,n),s=yield this.cache.getHeader(this.source);if(es.maxZoom)return;let u=s.rootDirectoryOffset,h=s.rootDirectoryLength;for(let l=0;l<=3;l++){let c=yield this.cache.getDirectory(this.source,u,h,s),o=Fe(c,a);if(o){if(o.runLength>0){let v=yield this.source.getBytes(s.tileDataOffset+o.offset,o.length,i,s.etag);return{data:yield this.decompress(v.data,s.tileCompression),cacheControl:v.cacheControl,expires:v.expires}}u=s.leafDirectoryOffset+o.offset,h=o.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,n,i){return m(this,null,function*(){try{return yield this.getZxyAttempt(e,t,n,i)}catch(a){if(a instanceof B)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,n,i);throw a}})}getMetadataAttempt(){return m(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),n=yield this.decompress(t.data,e.internalCompression),i=new TextDecoder("utf-8");return JSON.parse(i.decode(n))})}getMetadata(){return m(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof B)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return m(this,null,function*(){let t=yield this.getHeader(),n=yield this.getMetadata(),i=Ze(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${i}`],vector_layers:n.vector_layers,attribution:n.attribution,description:n.description,name:n.name,version:n.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};f(pe,"PMTiles");var P=pe;return et(Dt);})(); +//# sourceMappingURL=pmtiles.js.map \ No newline at end of file diff --git a/docs/articles/map-design_files/radius-mode-1.0.0/radius-mode.js b/docs/articles/map-design_files/radius-mode-1.0.0/radius-mode.js new file mode 100644 index 0000000..2b7b5bf --- /dev/null +++ b/docs/articles/map-design_files/radius-mode-1.0.0/radius-mode.js @@ -0,0 +1,311 @@ +// Radius/Circle drawing mode for Mapbox GL Draw +// Creates a circle by drawing from center to edge +(function (MapboxDraw) { + const DrawLine = MapboxDraw.modes.draw_line_string; + + // Utility function to create a vertex feature + const createVertex = function (parentId, coordinates, path, selected) { + return { + type: "Feature", + properties: { + meta: "vertex", + parent: parentId, + coord_path: path, + active: selected ? "true" : "false" + }, + geometry: { + type: "Point", + coordinates: coordinates + } + }; + }; + + // Utility function to calculate distance between two points in kilometers + const calculateDistance = function (coord1, coord2) { + const lat1 = coord1[1]; + const lon1 = coord1[0]; + const lat2 = coord2[1]; + const lon2 = coord2[0]; + + const R = 6371; // Radius of the Earth in kilometers + const dLat = (lat2 - lat1) * Math.PI / 180; + const dLon = (lon2 - lon1) * Math.PI / 180; + const a = + Math.sin(dLat/2) * Math.sin(dLat/2) + + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * + Math.sin(dLon/2) * Math.sin(dLon/2); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + const distance = R * c; + + return distance; + }; + + // Utility function to create a GeoJSON circle + const createGeoJSONCircle = function (center, radiusInKm, parentId, points) { + points = points || 64; + + const coords = { + latitude: center[1], + longitude: center[0] + }; + + const km = radiusInKm; + const ret = []; + const distanceX = km / (111.32 * Math.cos((coords.latitude * Math.PI) / 180)); + const distanceY = km / 110.574; + + let theta, x, y; + for (let i = 0; i < points; i++) { + theta = (i / points) * (2 * Math.PI); + x = distanceX * Math.cos(theta); + y = distanceY * Math.sin(theta); + + ret.push([coords.longitude + x, coords.latitude + y]); + } + ret.push(ret[0]); + + return { + type: "Feature", + geometry: { + type: "Polygon", + coordinates: [ret] + }, + properties: { + parent: parentId, + meta: "radius" + } + }; + }; + + // Utility function to format distance for display + const getDisplayMeasurements = function (distanceKm) { + let metricUnits = "m"; + let metricFormat = "0,0"; + let metricMeasurement; + + let standardUnits = "feet"; + let standardFormat = "0,0"; + let standardMeasurement; + + metricMeasurement = distanceKm * 1000; // Convert to meters + if (metricMeasurement >= 1000) { + metricMeasurement = metricMeasurement / 1000; + metricUnits = "km"; + metricFormat = "0.00"; + } + + standardMeasurement = distanceKm * 1000 * 3.28084; // Convert to feet + if (standardMeasurement >= 5280) { + standardMeasurement = standardMeasurement / 5280; + standardUnits = "mi"; + standardFormat = "0.00"; + } + + // Simple number formatting (without numeral.js dependency) + const formatNumber = function(num, format) { + if (format === "0,0") { + return Math.round(num).toLocaleString(); + } else if (format === "0.00") { + return num.toFixed(2); + } + return num.toString(); + }; + + return { + metric: formatNumber(metricMeasurement, metricFormat) + " " + metricUnits, + standard: formatNumber(standardMeasurement, standardFormat) + " " + standardUnits + }; + }; + + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RadiusMode = Object.assign({}, DrawLine); + + RadiusMode.onSetup = function (opts) { + const line = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "LineString", + coordinates: [] + } + }); + + this.addFeature(line); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.activateUIButton("line"); + this.setActionableState({ trash: true }); + + return { + line: line, + currentVertexPosition: 0, + direction: "forward" + }; + }; + + RadiusMode.onClick = function (state, e) { + // This ends the drawing after the user creates a second point + if (state.currentVertexPosition === 1) { + // Update the second coordinate in place, don't add at position 0 + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + return this.changeMode("simple_select", { featureIds: [state.line.id] }); + } + + this.updateUIClasses({ mouse: "add" }); + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + + if (state.direction === "forward") { + state.currentVertexPosition += 1; + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + } else { + state.line.addCoordinate(0, e.lngLat.lng, e.lngLat.lat); + } + + return null; + }; + + RadiusMode.onMouseMove = function (state, e) { + if (state.currentVertexPosition === 1) { + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + } + }; + + // Creates the final geojson circle polygon + RadiusMode.onStop = function (state) { + doubleClickZoom.enable(this); + this.activateUIButton(); + + // Check to see if we've deleted this feature + if (this.getFeature(state.line.id) === undefined) return; + + if (state.line.isValid()) { + const lineGeoJson = state.line.toGeoJSON(); + const coords = lineGeoJson.geometry.coordinates; + + if (coords.length >= 2) { + // Calculate radius in kilometers + const radiusKm = calculateDistance(coords[0], coords[1]); + + // Create the circle polygon + const circleFeature = createGeoJSONCircle(coords[0], radiusKm, state.line.id); + + // Add radius property for reference + circleFeature.properties.radius = (radiusKm * 1000).toFixed(1); + + // Remove the meta property that was interfering + delete circleFeature.properties.meta; + delete circleFeature.properties.parent; + + // Delete the temporary line first + this.deleteFeature([state.line.id], { silent: true }); + + // Add the circle feature to the draw instance + const circleDrawFeature = this.newFeature(circleFeature); + this.addFeature(circleDrawFeature); + + this.map.fire("draw.create", { + features: [circleDrawFeature.toGeoJSON()] + }); + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + + this.changeMode("simple_select", {}, { silent: true }); + }; + + RadiusMode.toDisplayFeatures = function (state, geojson, display) { + const isActiveLine = geojson.properties.id === state.line.id; + geojson.properties.active = isActiveLine ? "true" : "false"; + + if (!isActiveLine) return display(geojson); + + // Only render the line if it has at least one real coordinate + if (geojson.geometry.coordinates.length < 2) return null; + + geojson.properties.meta = "feature"; + + // Display center vertex as a point feature + display(createVertex( + state.line.id, + geojson.geometry.coordinates[ + state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1 + ], + "" + (state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1), + false + )); + + // Display the line as it is drawn + display(geojson); + + const coords = geojson.geometry.coordinates; + if (coords.length >= 2) { + const distanceKm = calculateDistance(coords[0], coords[1]); + const displayMeasurements = getDisplayMeasurements(distanceKm); + + // Create custom feature for the current pointer position + const currentVertex = { + type: "Feature", + properties: { + meta: "currentPosition", + radiusMetric: displayMeasurements.metric, + radiusStandard: displayMeasurements.standard, + parent: state.line.id + }, + geometry: { + type: "Point", + coordinates: coords[1] + } + }; + display(currentVertex); + + // Create custom feature for radius circle + const center = coords[0]; + const circleFeature = createGeoJSONCircle(center, distanceKm, state.line.id); + display(circleFeature); + } + + return null; + }; + + RadiusMode.onTrash = function (state) { + this.deleteFeature([state.line.id], { silent: true }); + this.changeMode("simple_select"); + }; + + MapboxDraw.modes.draw_radius = RadiusMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/map-design_files/rectangle-mode-1.0.0/rectangle-mode.js b/docs/articles/map-design_files/rectangle-mode-1.0.0/rectangle-mode.js new file mode 100644 index 0000000..73af6d6 --- /dev/null +++ b/docs/articles/map-design_files/rectangle-mode-1.0.0/rectangle-mode.js @@ -0,0 +1,124 @@ +// Rectangle drawing mode for Mapbox GL Draw +// Adapted from https://github.com/edgespatial/mapbox-gl-draw-rectangle-mode +(function (MapboxDraw) { + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RectangleMode = { + onSetup: function (opts) { + const rectangle = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "Polygon", + coordinates: [[]] + } + }); + + this.addFeature(rectangle); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.setActionableState({ trash: true }); + + return { + rectangle: rectangle + }; + }, + + onClick: function (state, e) { + // If we have a start point and click on a different point, complete the rectangle + if (state.startPoint && + (state.startPoint[0] !== e.lngLat.lng || state.startPoint[1] !== e.lngLat.lat)) { + this.updateUIClasses({ mouse: "pointer" }); + state.endPoint = [e.lngLat.lng, e.lngLat.lat]; + this.changeMode("simple_select", { featuresId: state.rectangle.id }); + return; + } + + // Set the start point + const startPoint = [e.lngLat.lng, e.lngLat.lat]; + state.startPoint = startPoint; + }, + + onMouseMove: function (state, e) { + // Update rectangle coordinates as the mouse moves + if (state.startPoint) { + const startX = state.startPoint[0]; + const startY = state.startPoint[1]; + const endX = e.lngLat.lng; + const endY = e.lngLat.lat; + + state.rectangle.updateCoordinate("0.0", startX, startY); + state.rectangle.updateCoordinate("0.1", endX, startY); + state.rectangle.updateCoordinate("0.2", endX, endY); + state.rectangle.updateCoordinate("0.3", startX, endY); + state.rectangle.updateCoordinate("0.4", startX, startY); + } + }, + + onKeyUp: function (state, e) { + if (e.keyCode === 27) { // Escape key + return this.changeMode("simple_select"); + } + }, + + onStop: function (state) { + doubleClickZoom.enable(this); + this.updateUIClasses({ mouse: "none" }); + this.activateUIButton(); + + if (this.getFeature(state.rectangle.id) !== undefined) { + // Remove the closing coordinate (duplicate of first) + state.rectangle.removeCoordinate("0.4"); + + if (state.rectangle.isValid()) { + this.map.fire("draw.create", { + features: [state.rectangle.toGeoJSON()] + }); + } else { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select", {}, { silent: true }); + } + } + }, + + toDisplayFeatures: function (state, geojson, display) { + const isActiveRectangle = geojson.properties.id === state.rectangle.id; + geojson.properties.active = isActiveRectangle ? "true" : "false"; + + if (!isActiveRectangle) { + return display(geojson); + } + + // Only display the rectangle if we have started drawing + if (state.startPoint) { + return display(geojson); + } + }, + + onTrash: function (state) { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select"); + } + }; + + MapboxDraw.modes.draw_rectangle = RectangleMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/map-design_files/turf-7.2.0/turf.min.js b/docs/articles/map-design_files/turf-7.2.0/turf.min.js new file mode 100644 index 0000000..635896d --- /dev/null +++ b/docs/articles/map-design_files/turf-7.2.0/turf.min.js @@ -0,0 +1,37 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).turf={})}(this,(function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}function u(t,e,n){return(e=y(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function l(t){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},l(t)}function h(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&p(t,e)}function c(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(c=function(){return!!t})()}function f(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}function g(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function p(t,e){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},p(t,e)}function v(t,e){return n(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,o,s,a=[],u=!0,l=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);u=!0);}catch(t){l=!0,i=t}finally{try{if(!u&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw i}}return a}}(t,e)||_(t,e)||g()}function d(t){return function(t){if(Array.isArray(t))return e(t)}(t)||f(t)||_(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function m(t){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},m(t)}function _(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var x=6371008.8,E={centimeters:100*x,centimetres:100*x,degrees:360/(2*Math.PI),feet:3.28084*x,inches:39.37*x,kilometers:x/1e3,kilometres:x/1e3,meters:x,metres:x,miles:x/1609.344,millimeters:1e3*x,millimetres:1e3*x,nauticalmiles:x/1852,radians:1,yards:1.0936*x},k={acres:247105e-9,centimeters:1e4,centimetres:1e4,feet:10.763910417,hectares:1e-4,inches:1550.003100006,kilometers:1e-6,kilometres:1e-6,meters:1,metres:1,miles:386e-9,nauticalmiles:2.9155334959812285e-7,millimeters:1e6,millimetres:1e6,yards:1.195990046};function b(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={type:"Feature"};return(0===n.id||n.id)&&(r.id=n.id),n.bbox&&(r.bbox=n.bbox),r.properties=e||{},r.geometry=t,r}function w(t,e){switch(t){case"Point":return I(e).geometry;case"LineString":return L(e).geometry;case"Polygon":return S(e).geometry;case"MultiPoint":return O(e).geometry;case"MultiLineString":return T(e).geometry;case"MultiPolygon":return R(e).geometry;default:throw new Error(t+" is invalid")}}function I(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("coordinates is required");if(!Array.isArray(t))throw new Error("coordinates must be an Array");if(t.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!U(t[0])||!U(t[1]))throw new Error("coordinates must contain numbers");return b({type:"Point",coordinates:t},e,n)}function N(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return I(t,e)})),n)}function S(t,e){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=a(t);try{for(i.s();!(n=i.n()).done;){var o=n.value;if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(var s=0;s2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return S(t,e)})),n)}function L(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(t.length<2)throw new Error("coordinates must be an array of two or more positions");return b({type:"LineString",coordinates:t},e,n)}function P(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return L(t,e)})),n)}function C(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={type:"FeatureCollection"};return e.id&&(n.id=e.id),e.bbox&&(n.bbox=e.bbox),n.features=t,n}function T(t,e){return b({type:"MultiLineString",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function O(t,e){return b({type:"MultiPoint",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function R(t,e){return b({type:"MultiPolygon",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function A(t,e){return b({type:"GeometryCollection",geometries:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function D(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e&&!(e>=0))throw new Error("precision must be a positive number");var n=Math.pow(10,e||0);return Math.round(t*n)/n}function F(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t*n}function q(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t/n}function V(t,e){return Y(q(t,e))}function G(t){var e=t%360;return e<0&&(e+=360),e}function B(t){return(t%=360)>180?t-360:t<-180?t+360:t}function Y(t){return 180*(t%(2*Math.PI))/Math.PI}function z(t){return t%360*Math.PI/180}function j(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("length must be a positive number");return F(q(t,e),n)}function X(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"meters",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("area must be a positive number");var r=k[e];if(!r)throw new Error("invalid original units");var i=k[n];if(!i)throw new Error("invalid final units");return t/r*i}function U(t){return!isNaN(t)&&null!==t&&!Array.isArray(t)}function Z(t){return null!==t&&"object"===m(t)&&!Array.isArray(t)}function H(t){if(!t)throw new Error("bbox is required");if(!Array.isArray(t))throw new Error("bbox must be an Array");if(4!==t.length&&6!==t.length)throw new Error("bbox must be an Array of 4 or 6 numbers");t.forEach((function(t){if(!U(t))throw new Error("bbox must only contain numbers")}))}function W(t){if(!t)throw new Error("id is required");if(-1===["string","number"].indexOf(m(t)))throw new Error("id must be a number or a string")}var J=Object.freeze({__proto__:null,areaFactors:k,azimuthToBearing:B,bearingToAzimuth:G,convertArea:X,convertLength:j,degreesToRadians:z,earthRadius:x,factors:E,feature:b,featureCollection:C,geometry:w,geometryCollection:A,isNumber:U,isObject:Z,lengthToDegrees:V,lengthToRadians:q,lineString:L,lineStrings:P,multiLineString:T,multiPoint:O,multiPolygon:R,point:I,points:N,polygon:S,polygons:M,radiansToDegrees:Y,radiansToLength:F,round:D,validateBBox:H,validateId:W});function K(t){if(!t)throw new Error("coord is required");if(!Array.isArray(t)){if("Feature"===t.type&&null!==t.geometry&&"Point"===t.geometry.type)return d(t.geometry.coordinates);if("Point"===t.type)return d(t.coordinates)}if(Array.isArray(t)&&t.length>=2&&!Array.isArray(t[0])&&!Array.isArray(t[1]))return d(t);throw new Error("coord must be GeoJSON Point or an Array of numbers")}function Q(t){if(Array.isArray(t))return t;if("Feature"===t.type){if(null!==t.geometry)return t.geometry.coordinates}else if(t.coordinates)return t.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function $(t){if(t.length>1&&U(t[0])&&U(t[1]))return!0;if(Array.isArray(t[0])&&t[0].length)return $(t[0]);throw new Error("coordinates must only contain numbers")}function tt(t,e,n){if(!e||!n)throw new Error("type and name required");if(!t||t.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.type)}function et(t,e,n){if(!t)throw new Error("No feature passed");if(!n)throw new Error(".featureOf() requires a name");if(!t||"Feature"!==t.type||!t.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!t.geometry||t.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.geometry.type)}function nt(t,e,n){if(!t)throw new Error("No featureCollection passed");if(!n)throw new Error(".collectionOf() requires a name");if(!t||"FeatureCollection"!==t.type)throw new Error("Invalid input to "+n+", FeatureCollection required");var r,i=a(t.features);try{for(i.s();!(r=i.n()).done;){var o=r.value;if(!o||"Feature"!==o.type||!o.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!o.geometry||o.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+o.geometry.type)}}catch(t){i.e(t)}finally{i.f()}}function rt(t){return"Feature"===t.type?t.geometry:t}function it(t,e){return"FeatureCollection"===t.type?"FeatureCollection":"GeometryCollection"===t.type?"GeometryCollection":"Feature"===t.type&&null!==t.geometry?t.geometry.type:t.type}var ot=Object.freeze({__proto__:null,collectionOf:nt,containsNumber:$,featureOf:et,geojsonType:tt,getCoord:K,getCoords:Q,getGeom:rt,getType:it});function st(t,e){if(!0===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final)return function(t,e){var n=st(e,t);return n=(n+180)%360}(t,e);var n=K(t),r=K(e),i=z(n[0]),o=z(r[0]),s=z(n[1]),a=z(r[1]),u=Math.sin(o-i)*Math.cos(a),l=Math.cos(s)*Math.sin(a)-Math.sin(s)*Math.cos(a)*Math.cos(o-i);return Y(Math.atan2(u,l))}function at(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=K(t),o=z(i[0]),s=z(i[1]),a=z(n),u=q(e,r.units),l=Math.asin(Math.sin(s)*Math.cos(u)+Math.cos(s)*Math.sin(u)*Math.cos(a));return I([Y(o+Math.atan2(Math.sin(a)*Math.sin(u)*Math.cos(s),Math.cos(u)-Math.sin(s)*Math.sin(l))),Y(l)],r.properties)}function ut(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e),o=z(i[1]-r[1]),s=z(i[0]-r[0]),a=z(r[1]),u=z(i[1]),l=Math.pow(Math.sin(o/2),2)+Math.pow(Math.sin(s/2),2)*Math.cos(a)*Math.cos(u);return F(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)),n.units)}function lt(t,e){var n;return(n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final?ht(K(e),K(t)):ht(K(t),K(e)))>180?-(360-n):n}function ht(t,e){var n=z(t[1]),r=z(e[1]),i=z(e[0]-t[0]);i>Math.PI&&(i-=2*Math.PI),i<-Math.PI&&(i+=2*Math.PI);var o=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(n/2+Math.PI/4));return(Y(Math.atan2(i,o))+360)%360}function ct(t,e,n){if(null!==t)for(var r,i,o,s,a,u,l,h,c=0,f=0,g=t.type,p="FeatureCollection"===g,v="Feature"===g,d=p?t.features.length:1,y=0;ya||f>u||g>l)return s=o,a=n,u=f,l=g,void(i=0);var p=L([s,o],t.properties);if(!1===e(p,n,r,g,i))return!1;i++,s=o}))&&void 0}}}))}function bt(t,e,n){var r=n,i=!1;return kt(t,(function(t,o,s,a,u){r=!1===i&&void 0===n?t:e(r,t,o,s,a,u),i=!0})),r}function wt(t,e){if(!t)throw new Error("geojson is required");xt(t,(function(t,n,r){if(null!==t.geometry){var i=t.geometry.type,o=t.geometry.coordinates;switch(i){case"LineString":if(!1===e(t,n,r,0,0))return!1;break;case"Polygon":for(var s=0;s0){e+=Math.abs(Ot(t[0]));for(var n=1;n=e?(r+2)%e:r+2],a=i[0]*Tt,u=o[1]*Tt;n+=(s[0]*Tt-a)*Math.sin(u),r++}return n*Ct}function Rt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=t.bbox&&!0!==e.recompute)return t.bbox;var n=[1/0,1/0,-1/0,-1/0];return ct(t,(function(t){n[0]>t[0]&&(n[0]=t[0]),n[1]>t[1]&&(n[1]=t[1]),n[2]e[2]&&(n|=2),t[1]e[3]&&(n|=8),n}function qt(t,e){var n,r=[],i=a(t);try{for(i.s();!(n=i.n()).done;){var o=At(n.value,e);o.length>0&&(o[0][0]===o[o.length-1][0]&&o[0][1]===o[o.length-1][1]||o.push(o[0]),o.length>=4&&r.push(o))}}catch(t){i.e(t)}finally{i.f()}return r}function Vt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Number(t[0]),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]);if(6===t.length)throw new Error("@turf/bbox-polygon does not support BBox with 6 positions");var s=[n,r];return S([[s,[i,r],[i,o],[n,o],s]],e.properties,{bbox:t,id:e.id})}var Gt=function(){return s((function t(e){i(this,t),this.points=e.points||[],this.duration=e.duration||1e4,this.sharpness=e.sharpness||.85,this.centers=[],this.controls=[],this.stepLength=e.stepLength||60,this.length=this.points.length,this.delay=0;for(var n=0;nt&&(e.push(r),n=i)}return e}},{key:"vector",value:function(t){var e=this.pos(t+10),n=this.pos(t-10);return{angle:180*Math.atan2(e.y-n.y,e.x-n.x)/3.14,speed:Math.sqrt((n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y)+(n.z-e.z)*(n.z-e.z))}}},{key:"pos",value:function(t){var e=t-this.delay;e<0&&(e=0),e>this.duration&&(e=this.duration-1);var n=e/this.duration;if(n>=1)return this.points[this.length-1];var r=Math.floor((this.points.length-1)*n);return function(t,e,n,r,i){var o=function(t){var e=t*t,n=e*t;return[n,3*e*(1-t),3*t*(1-t)*(1-t),(1-t)*(1-t)*(1-t)]}(t),s={x:i.x*o[0]+r.x*o[1]+n.x*o[2]+e.x*o[3],y:i.y*o[0]+r.y*o[1]+n.y*o[2]+e.y*o[3],z:i.z*o[0]+r.z*o[1]+n.z*o[2]+e.z*o[3]};return s}((this.length-1)*n-r,this.points[r],this.controls[r][1],this.controls[r+1][0],this.points[r+1])}}])}();function Bt(t){for(var e,n,r=Q(t),i=0,o=1;o0}function Yt(t,e){for(var n=0,r=0,i=0,o=0,s=0,a=0,u=0,l=0,h=null,c=null,f=t[0],g=t[1],p=e.length;n0&&l>0)a=l,s=(h=c)[0]-f;else{if(u=c[0]-t[0],l>0&&a<=0){if((o=s*l-u*a)>0)i+=1;else if(0===o)return 0}else if(a>0&&l<=0){if((o=s*l-u*a)<0)i+=1;else if(0===o)return 0}else if(0===l&&a<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&l<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&0===l){if(u<=0&&s>=0)return 0;if(s<=0&&u>=0)return 0}h=c,a=l,s=u}}return i%2!=0}function zt(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("point is required");if(!e)throw new Error("polygon is required");var r=K(t),i=rt(e),o=i.type,s=e.bbox,a=i.coordinates;if(s&&!1===function(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}(r,s))return!1;"Polygon"===o&&(a=[a]);for(var u=!1,l=0;l2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=Q(e),o=0;oi)return!1}else if(0!==g)return!1;return Math.abs(c)===Math.abs(f)&&0===Math.abs(c)?!r&&(n[0]===t[0]&&n[1]===t[1]):r?"start"===r?Math.abs(c)>=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o0?u<=s&&s=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o<=l:l<=o&&o<=a:f>0?u<=s&&s<=h:h<=s&&s<=u}function Ut(t,e){if("Feature"===t.type&&null===t.geometry)return!1;if("Feature"===e.type&&null===e.geometry)return!1;if(!Zt(Rt(t),Rt(e)))return!1;var n,r=a(rt(e).coordinates);try{for(r.s();!(n=r.n()).done;){var i,o=a(n.value);try{for(o.s();!(i=o.n()).done;){if(!zt(i.value,t))return!1}}catch(t){o.e(t)}finally{o.f()}}}catch(t){r.e(t)}finally{r.f()}return!0}function Zt(t,e){return!(t[0]>e[0])&&(!(t[2]e[1])&&!(t[3]0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Kt;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function Kt(t,e){return te?1:0}function Qt(t,e){return t.p.x>e.p.x?1:t.p.xe.p.y?1:-1:1}function $t(t,e){return t.rightSweepEvent.p.x>e.rightSweepEvent.p.x?1:t.rightSweepEvent.p.x0?(h.isLeftEndpoint=!0,l.isLeftEndpoint=!1):(l.isLeftEndpoint=!0,h.isLeftEndpoint=!1),e.push(l),e.push(h),s=a,re+=1}}ee+=1}var oe=s((function t(e){i(this,t),this.leftSweepEvent=e,this.rightSweepEvent=e.otherEvent}));function se(t,e){if(null===t||null===e)return!1;if(t.leftSweepEvent.ringId===e.leftSweepEvent.ringId&&(t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.rightSweepEvent)||t.leftSweepEvent.isSamePoint(e.leftSweepEvent)||t.leftSweepEvent.isSamePoint(e.rightSweepEvent)))return!1;var n=t.leftSweepEvent.p.x,r=t.leftSweepEvent.p.y,i=t.rightSweepEvent.p.x,o=t.rightSweepEvent.p.y,s=e.leftSweepEvent.p.x,a=e.leftSweepEvent.p.y,u=e.rightSweepEvent.p.x,l=e.rightSweepEvent.p.y,h=(l-a)*(i-n)-(u-s)*(o-r),c=(u-s)*(r-a)-(l-a)*(n-s),f=(i-n)*(r-a)-(o-r)*(n-s);if(0===h)return!1;var g=c/h,p=f/h;return g>=0&&g<=1&&p>=0&&p<=1&&[n+g*(i-n),r+g*(o-r)]}var ae=function(t,e){var n=new Jt([],Qt);return function(t,e){if("FeatureCollection"===t.type)for(var n=t.features,r=0;r2&&void 0!==arguments[2]?arguments[2]:{},r=n.removeDuplicates,i=void 0===r||r,o=n.ignoreSelfIntersections,s=void 0===o||o,a=[];"FeatureCollection"===t.type?a=a.concat(t.features):"Feature"===t.type?a.push(t):"LineString"!==t.type&&"Polygon"!==t.type&&"MultiLineString"!==t.type&&"MultiPolygon"!==t.type||a.push(b(t)),"FeatureCollection"===e.type?a=a.concat(e.features):"Feature"===e.type?a.push(e):"LineString"!==e.type&&"Polygon"!==e.type&&"MultiLineString"!==e.type&&"MultiPolygon"!==e.type||a.push(b(e));var u=ae(C(a),s),l=[];if(i){var h={};u.forEach((function(t){var e=t.join(",");h[e]||(h[e]=!0,l.push(t))}))}else l=u;return C(l.map((function(t){return I(t)})))}function le(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t);switch(e.properties||"Feature"!==t.type||(e.properties=t.properties),n.type){case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{};return he(r,i)}(n,e);case"MultiPolygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{},o=[];return r.forEach((function(t){o.push(he(t,i))})),C(o)}(n,e);default:throw new Error("invalid poly")}}function he(t,e){return t.length>1?T(t,e):L(t[0],e)}function ce(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;switch(i){case"MultiPoint":switch(o){case"LineString":return fe(n,r);case"Polygon":return pe(n,r);default:throw new Error("feature2 "+o+" geometry not supported")}case"LineString":switch(o){case"MultiPoint":return fe(r,n);case"LineString":return function(t,e){if(ue(t,e).features.length>0)for(var n=0;n0}function pe(t,e){for(var n=!1,r=!1,i=t.coordinates.length,o=0;o=Math.abs(a)?s>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:a>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1]:Math.abs(s)>=Math.abs(a)?s>0?t[0]0?t[1]2&&void 0!==arguments[2]?arguments[2]:{ignoreSelfIntersections:!0}).ignoreSelfIntersections,r=void 0===n||n,i=!0;return xt(t,(function(t){xt(e,(function(e){if(!1===i)return!1;i=function(t,e,n){switch(t.type){case"Point":switch(e.type){case"Point":return r=t.coordinates,i=e.coordinates,!(r[0]===i[0]&&r[1]===i[1]);case"LineString":return!ye(e,t);case"Polygon":return!zt(t,e)}break;case"LineString":switch(e.type){case"Point":return!ye(t,e);case"LineString":return!function(t,e,n){var r=ue(t,e,{ignoreSelfIntersections:n});if(r.features.length>0)return!0;return!1}(t,e,n);case"Polygon":return!me(e,t,n)}break;case"Polygon":switch(e.type){case"Point":return!zt(e,t);case"LineString":return!me(t,e,n);case"Polygon":return!function(t,e,n){var r,i=a(t.coordinates[0]);try{for(i.s();!(r=i.n()).done;){if(zt(r.value,e))return!0}}catch(t){i.e(t)}finally{i.f()}var o,s=a(e.coordinates[0]);try{for(s.s();!(o=s.n()).done;){if(zt(o.value,t))return!0}}catch(t){s.e(t)}finally{s.f()}var u=ue(le(t),le(e),{ignoreSelfIntersections:n});if(u.features.length>0)return!0;return!1}(e,t,n)}}var r,i;return!1}(t.geometry,e.geometry,r)}))})),i}function ye(t,e){for(var n=0;n0}function _e(t,e,n){var r=n[0]-t[0],i=n[1]-t[1],o=e[0]-t[0],s=e[1]-t[1];return 0==r*s-i*o&&(Math.abs(o)>=Math.abs(s)?o>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:s>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1])}var xe=Object.defineProperty,Ee=function(t,e){return xe(t,"name",{value:e,configurable:!0})},ke=function(){return s((function t(e){var n,r,o;i(this,t),this.direction=!1,this.compareProperties=!0,this.precision=Math.pow(10,-(null!=(n=null==e?void 0:e.precision)?n:17)),this.direction=null!=(r=null==e?void 0:e.direction)&&r,this.compareProperties=null==(o=null==e?void 0:e.compareProperties)||o}),[{key:"compare",value:function(t,e){var n=this;if(t.type!==e.type)return!1;if(!we(t,e))return!1;switch(t.type){case"Point":return this.compareCoord(t.coordinates,e.coordinates);case"LineString":return this.compareLine(t.coordinates,e.coordinates);case"Polygon":return this.comparePolygon(t,e);case"GeometryCollection":return this.compareGeometryCollection(t,e);case"Feature":return this.compareFeature(t,e);case"FeatureCollection":return this.compareFeatureCollection(t,e);default:if(t.type.startsWith("Multi")){var r=Ie(t),i=Ie(e);return r.every((function(t){return i.some((function(e){return n.compare(t,e)}))}))}}return!1}},{key:"compareCoord",value:function(t,e){var n=this;return t.length===e.length&&t.every((function(t,r){return Math.abs(t-e[r])2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!we(t,e))return!1;var i=t,o=e;if(r&&!this.compareCoord(i[0],o[0])){var s=this.fixStartIndex(o,i);if(!s)return!1;o=s}var a=this.compareCoord(i[n],o[n]);return this.direction||a?this.comparePath(i,o):!!this.compareCoord(i[n],o[o.length-(1+n)])&&this.comparePath(i.slice().reverse(),o)}},{key:"fixStartIndex",value:function(t,e){for(var n,r=-1,i=0;i=0&&(n=[].concat(t.slice(r,t.length),t.slice(1,r+1))),n}},{key:"comparePath",value:function(t,e){var n=this;return t.every((function(t,r){return n.compareCoord(t,e[r])}))}},{key:"comparePolygon",value:function(t,e){var n=this;if(this.compareLine(t.coordinates[0],e.coordinates[0],1,!0)){var r=t.coordinates.slice(1,t.coordinates.length),i=e.coordinates.slice(1,e.coordinates.length);return r.every((function(t){return i.some((function(e){return n.compareLine(t,e,1,!0)}))}))}return!1}},{key:"compareGeometryCollection",value:function(t,e){var n=this;return we(t.geometries,e.geometries)&&this.compareBBox(t,e)&&t.geometries.every((function(t,r){return n.compare(t,e.geometries[r])}))}},{key:"compareFeature",value:function(t,e){return t.id===e.id&&(!this.compareProperties||Se(t.properties,e.properties))&&this.compareBBox(t,e)&&this.compare(t.geometry,e.geometry)}},{key:"compareFeatureCollection",value:function(t,e){var n=this;return we(t.features,e.features)&&this.compareBBox(t,e)&&t.features.every((function(t,r){return n.compare(t,e.features[r])}))}},{key:"compareBBox",value:function(t,e){return Boolean(!t.bbox&&!e.bbox)||!(!t.bbox||!e.bbox)&&this.compareCoord(t.bbox,e.bbox)}}])}();Ee(ke,"GeojsonEquality");var be=ke;function we(t,e){return t.coordinates?t.coordinates.length===e.coordinates.length:t.length===e.length}function Ie(t){return t.coordinates.map((function(e){return{type:t.type.replace("Multi",""),coordinates:e}}))}function Ne(t,e,n){return new be(n).compare(t,e)}function Se(t,e){if(null===t&&null===e)return!0;if(null===t||null===e)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(var i=0,o=n;i1&&void 0!==arguments[1]?arguments[1]:{},n="object"===m(e)?e.mutate:e;if(!t)throw new Error("geojson is required");var r=it(t),i=[];switch(r){case"LineString":i=Pe(t,r);break;case"MultiLineString":case"Polygon":Q(t).forEach((function(t){i.push(Pe(t,r))}));break;case"MultiPolygon":Q(t).forEach((function(t){var e=[];t.forEach((function(t){e.push(Pe(t,r))})),i.push(e)}));break;case"Point":return t;case"MultiPoint":var o={};Q(t).forEach((function(t){var e=t.join("-");Object.prototype.hasOwnProperty.call(o,e)||(i.push(t),o[e]=!0)}));break;default:throw new Error(r+" geometry not supported")}return t.coordinates?!0===n?(t.coordinates=i,t):{type:r,coordinates:i}:!0===n?(t.geometry.coordinates=i,t):b({type:r,coordinates:i},t.properties,{bbox:t.bbox,id:t.id})}function Pe(t,e){var n=Q(t);if(2===n.length&&!Ce(n[0],n[1]))return n;var r=[],i=n.length-1,o=r.length;r.push(n[0]);for(var s=1;s2&&Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1))}if(r.push(n[n.length-1]),o=r.length,("Polygon"===e||"MultiPolygon"===e)&&Ce(n[0],n[n.length-1])&&o<4)throw new Error("invalid polygon");return"LineString"===e&&o<3||Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1),r}function Ce(t,e){return t[0]===e[0]&&t[1]===e[1]}function Te(t,e,n){var r=n[0],i=n[1],o=t[0],s=t[1],a=e[0],u=e[1],l=a-o,h=u-s;return 0===(r-o)*h-(i-s)*l&&(Math.abs(l)>=Math.abs(h)?l>0?o<=r&&r<=a:a<=r&&r<=o:h>0?s<=i&&i<=u:u<=i&&i<=s)}function Oe(t,e){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).ignoreSelfIntersections,r=void 0===n||n,i=!1;return xt(t,(function(t){xt(e,(function(e){if(!0===i)return!0;i=!de(t.geometry,e.geometry,{ignoreSelfIntersections:r})}))})),i}function Re(t,e,n,r,i){Ae(t,e,n||0,r||t.length-1,i||Fe)}function Ae(t,e,n,r,i){for(;r>n;){if(r-n>600){var o=r-n+1,s=e-n+1,a=Math.log(o),u=.5*Math.exp(2*a/3),l=.5*Math.sqrt(a*u*(o-u)/o)*(s-o/2<0?-1:1);Ae(t,e,Math.max(n,Math.floor(e-s*u/o+l)),Math.min(r,Math.floor(e+(o-s)*u/o+l)),i)}var h=t[e],c=n,f=r;for(De(t,n,e),i(t[r],h)>0&&De(t,n,r);c0;)f--}0===i(t[n],h)?De(t,n,f):De(t,++f,r),f<=e&&(n=f+1),e<=f&&(r=f-1)}}function De(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function Fe(t,e){return te?1:0}var qe=function(){return s((function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:9;i(this,t),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}),[{key:"all",value:function(){return this._all(this.data,[])}},{key:"search",value:function(t){var e=this.data,n=[];if(!He(t,e))return n;for(var r=this.toBBox,i=[];e;){for(var o=0;o=0&&i[e].children.length>this._maxEntries;)this._split(i,e),e--;this._adjustParentBBoxes(r,i,e)}},{key:"_split",value:function(t,e){var n=t[e],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=We(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,Ge(n,this.toBBox),Ge(s,this.toBBox),e?t[e-1].children.push(s):this._splitRoot(n,s)}},{key:"_splitRoot",value:function(t,e){this.data=We([t,e]),this.data.height=t.height+1,this.data.leaf=!1,Ge(this.data,this.toBBox)}},{key:"_chooseSplitIndex",value:function(t,e,n){for(var r,i,o,s,a,u,l,h=1/0,c=1/0,f=e;f<=n-e;f++){var g=Be(t,0,f,this.toBBox),p=Be(t,f,n,this.toBBox),v=(i=g,o=p,s=void 0,a=void 0,u=void 0,l=void 0,s=Math.max(i.minX,o.minX),a=Math.max(i.minY,o.minY),u=Math.min(i.maxX,o.maxX),l=Math.min(i.maxY,o.maxY),Math.max(0,u-s)*Math.max(0,l-a)),d=Xe(g)+Xe(p);v=e;h--){var c=t.children[h];Ye(s,t.leaf?i(c):c),a+=Ue(s)}return a}},{key:"_adjustParentBBoxes",value:function(t,e,n){for(var r=n;r>=0;r--)Ye(e[r],t)}},{key:"_condense",value:function(t){for(var e,n=t.length-1;n>=0;n--)0===t[n].children.length?n>0?(e=t[n-1].children).splice(e.indexOf(t[n]),1):this.clear():Ge(t[n],this.toBBox)}}])}();function Ve(t,e,n){if(!n)return e.indexOf(t);for(var r=0;r=t.minX&&e.maxY>=t.minY}function We(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Je(t,e,n,r,i){for(var o=[e,n];o.length;)if(!((n=o.pop())-(e=o.pop())<=r)){var s=e+Math.ceil((n-e)/r/2)*r;Re(t,s,e,n,i),o.push(e,s,s,n)}}var Ke=Object.freeze({__proto__:null,default:qe});function Qe(t){var e=new qe(t);return e.insert=function(t){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.insert.call(this,t)},e.load=function(t){var e=[];return Array.isArray(t)?t.forEach((function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})):vt(t,(function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})),qe.prototype.load.call(this,e)},e.remove=function(t,e){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.remove.call(this,t,e)},e.clear=function(){return qe.prototype.clear.call(this)},e.search=function(t){return C(qe.prototype.search.call(this,this.toBBox(t)))},e.collides=function(t){return qe.prototype.collides.call(this,this.toBBox(t))},e.all=function(){return C(qe.prototype.all.call(this))},e.toJSON=function(){return qe.prototype.toJSON.call(this)},e.fromJSON=function(t){return qe.prototype.fromJSON.call(this,t)},e.toBBox=function(t){var e;if(t.bbox)e=t.bbox;else if(Array.isArray(t)&&4===t.length)e=t;else if(Array.isArray(t)&&6===t.length)e=[t[0],t[1],t[3],t[4]];else if("Feature"===t.type)e=Rt(t);else{if("FeatureCollection"!==t.type)throw new Error("invalid geojson");e=Rt(t)}return{minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}},e}function $e(t){if(!t)throw new Error("geojson is required");var e=[];return xt(t,(function(t){!function(t,e){var n=[],r=t.geometry;if(null!==r){switch(r.type){case"Polygon":n=Q(r);break;case"LineString":n=[Q(r)]}n.forEach((function(n){var r=function(t,e){var n=[];return t.reduce((function(t,r){var i=L([t,r],e);return i.bbox=function(t,e){var n=t[0],r=t[1],i=e[0],o=e[1],s=ni?n:i,l=r>o?r:o;return[s,a,u,l]}(t,r),n.push(i),r})),n}(n,t.properties);r.forEach((function(t){t.id=e.length,e.push(t)}))}))}}(t,e)})),C(e)}var tn,en,nn=Object.defineProperty,rn=Object.defineProperties,on=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertySymbols,an=Object.prototype.hasOwnProperty,un=Object.prototype.propertyIsEnumerable,ln=function(t,e,n){return e in t?nn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},hn=function(t,e){for(var n in e||(e={}))an.call(e,n)&&ln(t,n,e[n]);if(sn){var r,i=a(sn(e));try{for(i.s();!(r=i.n()).done;){n=r.value;un.call(e,n)&&ln(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},cn=function(t,e){return rn(t,on(e))};function fn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t||!e)throw new Error("lines and pt are required arguments");var r=K(e),i=I([1/0,1/0],{dist:1/0,index:-1,multiFeatureIndex:-1,location:-1}),o=0;return xt(t,(function(t,s,a){for(var u=Q(t),l=0;lR||pn(p,f)>R?ut(dn(f),dn(g))<=ut(dn(f),dn(p))?[dn(g),!0,!1]:[dn(p),!1,!0]:[dn(f),!1,!1]}function mn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function _n(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var n=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,r.get?r:{enumerable:!0,get:function(){return t[e]}})})),n}var xn=(en||(en=1,tn=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==m(e)&&"object"==m(n)){if(e.constructor!==n.constructor)return!1;var r,i,o;if(Array.isArray(e)){if((r=e.length)!=n.length)return!1;for(i=r;0!=i--;)if(!t(e[i],n[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((r=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(i=r;0!=i--;)if(!Object.prototype.hasOwnProperty.call(n,o[i]))return!1;for(i=r;0!=i--;){var s=o[i];if(!t(e[s],n[s]))return!1}return!0}return e!=e&&n!=n}),tn),En=mn(xn);function kn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r,i=n.tolerance||0,o=[],s=Qe(),a=$e(t);s.load(a);var u=[];return kt(e,(function(t){var e=!1;t&&(vt(s.search(t),(function(n){if(!1===e){var o=Q(t).sort(),s=Q(n).sort();if(En(o,s))e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(o[0],n)&&jt(o[1],n):fn(n,o[0]).properties.dist<=i&&fn(n,o[1]).properties.dist<=i)e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(s[0],t)&&jt(s[1],t):fn(t,s[0]).properties.dist<=i&&fn(t,s[1]).properties.dist<=i)if(r){var a=bn(r,n);a?r=a:u.push(n)}else r=n}})),!1===e&&r&&(o.push(r),u.length&&(o=o.concat(u),u=[]),r=void 0))})),r&&o.push(r),C(o)}function bn(t,e){var n=Q(e),r=Q(t),i=r[0],o=r[r.length-1],s=t.geometry.coordinates;if(En(n[0],i))s.unshift(n[1]);else if(En(n[0],o))s.push(n[1]);else if(En(n[1],i))s.unshift(n[0]);else{if(!En(n[1],o))return;s.push(n[0])}return t}function wn(t,e){var n=G(lt(t[0],t[1])),r=G(lt(e[0],e[1]));return n===r||(r-n)%180==0}function In(t,e){if(t.geometry&&t.geometry.type)return t.geometry.type;if(t.type)return t.type;throw new Error("Invalid GeoJSON object for "+e)}function Nn(t,e){return!!Sn(e.coordinates[0],t.coordinates)||!!Sn(e.coordinates[e.coordinates.length-1],t.coordinates)}function Sn(t,e){return t[0]===e[0]&&t[1]===e[1]}function Mn(t){return t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]}function Ln(t){for(var e=0;ee[0])&&(!(t[2]e[1])&&!(t[3]1&&void 0!==arguments[1]?arguments[1]:{},n=Rt(t);return I([(n[0]+n[2])/2,(n[1]+n[3])/2],e.properties,e)}var Dn,Fn={exports:{}};var qn=(Dn||(Dn=1,function(t,e){t.exports=function(){function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}var y=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getEndCapStyle",value:function(){return this._endCapStyle}},{key:"isSingleSided",value:function(){return this._isSingleSided}},{key:"setQuadrantSegments",value:function(t){this._quadrantSegments=t,0===this._quadrantSegments&&(this._joinStyle=e.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=e.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),t<=0&&(this._quadrantSegments=1),this._joinStyle!==e.JOIN_ROUND&&(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS)}},{key:"getJoinStyle",value:function(){return this._joinStyle}},{key:"setJoinStyle",value:function(t){this._joinStyle=t}},{key:"setSimplifyFactor",value:function(t){this._simplifyFactor=t<0?0:t}},{key:"getSimplifyFactor",value:function(){return this._simplifyFactor}},{key:"getQuadrantSegments",value:function(){return this._quadrantSegments}},{key:"setEndCapStyle",value:function(t){this._endCapStyle=t}},{key:"getMitreLimit",value:function(){return this._mitreLimit}},{key:"setMitreLimit",value:function(t){this._mitreLimit=t}},{key:"setSingleSided",value:function(t){this._isSingleSided=t}}],[{key:"constructor_",value:function(){if(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=e.CAP_ROUND,this._joinStyle=e.JOIN_ROUND,this._mitreLimit=e.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=e.DEFAULT_SIMPLIFY_FACTOR,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.setQuadrantSegments(t)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.setQuadrantSegments(n),this.setEndCapStyle(r)}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];this.setQuadrantSegments(i),this.setEndCapStyle(o),this.setJoinStyle(s),this.setMitreLimit(a)}}},{key:"bufferDistanceError",value:function(t){var e=Math.PI/2/t;return 1-Math.cos(e/2)}}]),e}();y.CAP_ROUND=1,y.CAP_FLAT=2,y.CAP_SQUARE=3,y.JOIN_ROUND=1,y.JOIN_MITRE=2,y.JOIN_BEVEL=3,y.DEFAULT_QUADRANT_SEGMENTS=8,y.DEFAULT_MITRE_LIMIT=5,y.DEFAULT_SIMPLIFY_FACTOR=.01;var _=function(e){r(o,e);var i=c(o);function o(e){var n;return t(this,o),(n=i.call(this,e)).name=Object.keys({Exception:o})[0],n}return n(o,[{key:"toString",value:function(){return this.message}}]),o}(u(Error)),x=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({IllegalArgumentException:i})[0],r}return i}(_),E=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}();function k(){}function b(){}function w(){}var I,N,S,M,L,P,C,T,O=function(){function e(){t(this,e)}return n(e,null,[{key:"equalsWithTolerance",value:function(t,e,n){return Math.abs(t-e)<=n}}]),e}(),R=function(){function e(n,r){t(this,e),this.low=r||0,this.high=n||0}return n(e,null,[{key:"toBinaryString",value:function(t){var e,n="";for(e=2147483648;e>0;e>>>=1)n+=(t.high&e)===e?"1":"0";for(e=2147483648;e>0;e>>>=1)n+=(t.low&e)===e?"1":"0";return n}}]),e}();function A(){}function D(){}A.NaN=NaN,A.isNaN=function(t){return Number.isNaN(t)},A.isInfinite=function(t){return!Number.isFinite(t)},A.MAX_VALUE=Number.MAX_VALUE,A.POSITIVE_INFINITY=Number.POSITIVE_INFINITY,A.NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,"function"==typeof Float64Array&&"function"==typeof Int32Array?(P=2146435072,C=new Float64Array(1),T=new Int32Array(C.buffer),A.doubleToLongBits=function(t){C[0]=t;var e=0|T[0],n=0|T[1];return(n&P)===P&&0!=(1048575&n)&&0!==e&&(e=0,n=2146959360),new R(n,e)},A.longBitsToDouble=function(t){return T[0]=t.low,T[1]=t.high,C[0]}):(I=1023,N=Math.log2,S=Math.floor,M=Math.pow,L=function(){for(var t=53;t>0;t--){var e=M(2,t)-1;if(S(N(e))+1===t)return e}return 0}(),A.doubleToLongBits=function(t){var e,n,r,i,o,s,a,u,l;if(t<0||1/t===Number.NEGATIVE_INFINITY?(s=1<<31,t=-t):s=0,0===t)return new R(u=s,l=0);if(t===1/0)return new R(u=2146435072|s,l=0);if(t!=t)return new R(u=2146959360,l=0);if(i=0,l=0,(e=S(t))>1)if(e<=L)(i=S(N(e)))<=20?(l=0,u=e<<20-i&1048575):(l=e%(n=M(2,r=i-20))<<32-r,u=e/n&1048575);else for(r=e,l=0;0!==(r=S(n=r/2));)i++,l>>>=1,l|=(1&u)<<31,u>>>=1,n!==r&&(u|=524288);if(a=i+I,o=0===e,e=t-e,i<52&&0!==e)for(r=0;;){if((n=2*e)>=1?(e=n-1,o?(a--,o=!1):(r<<=1,r|=1,i++)):(e=n,o?0==--a&&(i++,o=!1):(r<<=1,i++)),20===i)u|=r,r=0;else if(52===i){l|=r;break}if(1===n){i<20?u|=r<<20-i:i<52&&(l|=r<<52-i);break}}return u|=a<<20,new R(u|=s,l)},A.longBitsToDouble=function(t){var e,n,r,i,o=t.high,s=t.low,a=o&1<<31?-1:1;for(r=((2146435072&o)>>20)-I,i=0,n=1<<19,e=1;e<=20;e++)o&n&&(i+=M(2,-e)),n>>>=1;for(n=1<<31,e=21;e<=52;e++)s&n&&(i+=M(2,-e)),n>>>=1;if(-1023===r){if(0===i)return 0*a;r=-1022}else{if(1024===r)return 0===i?a/0:NaN;i+=1}return a*i*M(2,r)});var F=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({RuntimeException:i})[0],r}return i}(_),q=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){if(0===arguments.length)F.constructor_.call(this);else if(1===arguments.length){var t=arguments[0];F.constructor_.call(this,t)}}}]),o}(F),V=function(){function e(){t(this,e)}return n(e,null,[{key:"shouldNeverReachHere",value:function(){if(0===arguments.length)e.shouldNeverReachHere(null);else if(1===arguments.length){var t=arguments[0];throw new q("Should never reach here"+(null!==t?": "+t:""))}}},{key:"isTrue",value:function(){if(1===arguments.length){var t=arguments[0];e.isTrue(t,null)}else if(2===arguments.length){var n=arguments[1];if(!arguments[0])throw null===n?new q:new q(n)}}},{key:"equals",value:function(){if(2===arguments.length){var t=arguments[0],n=arguments[1];e.equals(t,n,null)}else if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2];if(!i.equals(r))throw new q("Expected "+r+" but encountered "+i+(null!==o?": "+o:""))}}}]),e}(),G=new ArrayBuffer(8),B=new Float64Array(G),Y=new Int32Array(G),z=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getM",value:function(){return A.NaN}},{key:"setOrdinate",value:function(t,n){switch(t){case e.X:this.x=n;break;case e.Y:this.y=n;break;case e.Z:this.setZ(n);break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"equals2D",value:function(){if(1===arguments.length){var t=arguments[0];return this.x===t.x&&this.y===t.y}if(2===arguments.length){var e=arguments[0],n=arguments[1];return!!O.equalsWithTolerance(this.x,e.x,n)&&!!O.equalsWithTolerance(this.y,e.y,n)}}},{key:"setM",value:function(t){throw new x("Invalid ordinate index: "+e.M)}},{key:"getZ",value:function(){return this.z}},{key:"getOrdinate",value:function(t){switch(t){case e.X:return this.x;case e.Y:return this.y;case e.Z:return this.getZ()}throw new x("Invalid ordinate index: "+t)}},{key:"equals3D",value:function(t){return this.x===t.x&&this.y===t.y&&(this.getZ()===t.getZ()||A.isNaN(this.getZ())&&A.isNaN(t.getZ()))}},{key:"equals",value:function(t){return t instanceof e&&this.equals2D(t)}},{key:"equalInZ",value:function(t,e){return O.equalsWithTolerance(this.getZ(),t.getZ(),e)}},{key:"setX",value:function(t){this.x=t}},{key:"compareTo",value:function(t){var e=t;return this.xe.x?1:this.ye.y?1:0}},{key:"getX",value:function(){return this.x}},{key:"setZ",value:function(t){this.z=t}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return V.shouldNeverReachHere("this shouldn't happen because this class is Cloneable"),null;throw t}}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+")"}},{key:"distance3D",value:function(t){var e=this.x-t.x,n=this.y-t.y,r=this.getZ()-t.getZ();return Math.sqrt(e*e+n*n+r*r)}},{key:"getY",value:function(){return this.y}},{key:"setY",value:function(t){this.y=t}},{key:"distance",value:function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*t+e.hashCode(this.x))+e.hashCode(this.y)}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}},{key:"interfaces_",get:function(){return[k,b,w]}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.z=null,0===arguments.length)e.constructor_.call(this,0,0);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.x,t.y,t.getZ())}else if(2===arguments.length){var n=arguments[0],r=arguments[1];e.constructor_.call(this,n,r,e.NULL_ORDINATE)}else if(3===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2];this.x=i,this.y=o,this.z=s}}},{key:"hashCode",value:function(t){return B[0]=t,Y[0]^Y[1]}}]),e}(),j=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compare",value:function(t,n){var r=e.compare(t.x,n.x);if(0!==r)return r;var i=e.compare(t.y,n.y);return 0!==i?i:this._dimensionsToTest<=2?0:e.compare(t.getZ(),n.getZ())}},{key:"interfaces_",get:function(){return[D]}}],[{key:"constructor_",value:function(){if(this._dimensionsToTest=2,0===arguments.length)e.constructor_.call(this,2);else if(1===arguments.length){var t=arguments[0];if(2!==t&&3!==t)throw new x("only 2 or 3 dimensions may be specified");this._dimensionsToTest=t}}},{key:"compare",value:function(t,e){return te?1:A.isNaN(t)?A.isNaN(e)?0:-1:A.isNaN(e)?1:0}}]),e}();z.DimensionalComparator=j,z.NULL_ORDINATE=A.NaN,z.X=0,z.Y=1,z.Z=2,z.M=3;var X=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getArea",value:function(){return this.getWidth()*this.getHeight()}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.isNull()?n.isNull():this._maxx===n.getMaxX()&&this._maxy===n.getMaxY()&&this._minx===n.getMinX()&&this._miny===n.getMinY()}},{key:"intersection",value:function(t){if(this.isNull()||t.isNull()||!this.intersects(t))return new e;var n=this._minx>t._minx?this._minx:t._minx,r=this._miny>t._miny?this._miny:t._miny;return new e(n,this._maxx=this._minx&&n.getMaxX()<=this._maxx&&n.getMinY()>=this._miny&&n.getMaxY()<=this._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return!this.isNull()&&r>=this._minx&&r<=this._maxx&&i>=this._miny&&i<=this._maxy}}},{key:"intersects",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return!this.isNull()&&!t.isNull()&&!(t._minx>this._maxx||t._maxxthis._maxy||t._maxythis._maxx||(r.x>i.x?r.x:i.x)this._maxy||(r.y>i.y?r.y:i.y)this._maxx||othis._maxy||sthis._maxx&&(this._maxx=n._maxx),n._minythis._maxy&&(this._maxy=n._maxy))}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.isNull()?(this._minx=r,this._maxx=r,this._miny=i,this._maxy=i):(rthis._maxx&&(this._maxx=r),ithis._maxy&&(this._maxy=i))}}},{key:"minExtent",value:function(){if(this.isNull())return 0;var t=this.getWidth(),e=this.getHeight();return te._minx?1:this._minye._miny?1:this._maxxe._maxx?1:this._maxye._maxy?1:0}},{key:"translate",value:function(t,e){if(this.isNull())return null;this.init(this.getMinX()+t,this.getMaxX()+t,this.getMinY()+e,this.getMaxY()+e)}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"Env["+this._minx+" : "+this._maxx+", "+this._miny+" : "+this._maxy+"]"}},{key:"setToNull",value:function(){this._minx=0,this._maxx=-1,this._miny=0,this._maxy=-1}},{key:"disjoint",value:function(t){return!(!this.isNull()&&!t.isNull())||t._minx>this._maxx||t._maxxthis._maxy||t._maxye?t:e}},{key:"expandBy",value:function(){if(1===arguments.length){var t=arguments[0];this.expandBy(t,t)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];if(this.isNull())return null;this._minx-=e,this._maxx+=e,this._miny-=n,this._maxy+=n,(this._minx>this._maxx||this._miny>this._maxy)&&this.setToNull()}}},{key:"contains",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.covers(t)}if(arguments[0]instanceof z){var n=arguments[0];return this.covers(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return this.covers(r,i)}}},{key:"centre",value:function(){return this.isNull()?null:new z((this.getMinX()+this.getMaxX())/2,(this.getMinY()+this.getMaxY())/2)}},{key:"init",value:function(){if(0===arguments.length)this.setToNull();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this._minx=n._minx,this._maxx=n._maxx,this._miny=n._miny,this._maxy=n._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];ot._maxx&&(e=this._minx-t._maxx);var n=0;return this._maxyt._maxy&&(n=this._miny-t._maxy),0===e?n:0===n?e:Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*(t=37*(t=37*t+z.hashCode(this._minx))+z.hashCode(this._maxx))+z.hashCode(this._miny))+z.hashCode(this._maxy)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,0===arguments.length)this.init();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];this.init(o,s,a,u)}}},{key:"intersects",value:function(){if(3===arguments.length){var t=arguments[0],e=arguments[1],n=arguments[2];return n.x>=(t.xe.x?t.x:e.x)&&n.y>=(t.ye.y?t.y:e.y)}if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=arguments[3],a=Math.min(o.x,s.x),u=Math.max(o.x,s.x),l=Math.min(r.x,i.x),h=Math.max(r.x,i.x);return!(l>u||hu||h=this.size())throw new nt;return this.array[t]}},{key:"push",value:function(t){return this.array.push(t),t}},{key:"pop",value:function(){if(0===this.array.length)throw new et;return this.array.pop()}},{key:"peek",value:function(){if(0===this.array.length)throw new et;return this.array[this.array.length-1]}},{key:"empty",value:function(){return 0===this.array.length}},{key:"isEmpty",value:function(){return this.empty()}},{key:"search",value:function(t){return this.array.indexOf(t)}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}}]),o}(rt);function ot(t,e){return t.interfaces_&&t.interfaces_.indexOf(e)>-1}var st=function(){function e(n){t(this,e),this.str=n}return n(e,[{key:"append",value:function(t){this.str+=t}},{key:"setCharAt",value:function(t,e){this.str=this.str.substr(0,t)+e+this.str.substr(t+1)}},{key:"toString",value:function(){return this.str}}]),e}(),at=function(){function e(n){t(this,e),this.value=n}return n(e,[{key:"intValue",value:function(){return this.value}},{key:"compareTo",value:function(t){return this.valuet?1:0}}],[{key:"compare",value:function(t,e){return te?1:0}},{key:"isNan",value:function(t){return Number.isNaN(t)}},{key:"valueOf",value:function(t){return new e(t)}}]),e}(),ut=function(){function e(){t(this,e)}return n(e,null,[{key:"isWhitespace",value:function(t){return t<=32&&t>=0||127===t}},{key:"toUpperCase",value:function(t){return t.toUpperCase()}}]),e}(),lt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"le",value:function(t){return this._hi9?(c=!0,f="9"):f="0"+h,a.append(f),r=r.subtract(e.valueOf(h)).multiply(e.TEN),c&&r.selfAdd(e.TEN);var g=!0,p=e.magnitude(r._hi);if(p<0&&Math.abs(p)>=u-l&&(g=!1),!g)break}return n[0]=i,a.toString()}},{key:"sqr",value:function(){return this.multiply(this)}},{key:"doubleValue",value:function(){return this._hi+this._lo}},{key:"subtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.add(t.negate())}if("number"==typeof arguments[0]){var n=arguments[0];return this.add(-n)}}},{key:"equals",value:function(){if(1===arguments.length&&arguments[0]instanceof e){var t=arguments[0];return this._hi===t._hi&&this._lo===t._lo}}},{key:"isZero",value:function(){return 0===this._hi&&0===this._lo}},{key:"selfSubtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.isNaN()?this:this.selfAdd(-t._hi,-t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.isNaN()?this:this.selfAdd(-n,0)}}},{key:"getSpecialNumberString",value:function(){return this.isZero()?"0.0":this.isNaN()?"NaN ":null}},{key:"min",value:function(t){return this.le(t)?this:t}},{key:"selfDivide",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfDivide(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfDivide(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null,c=null,f=null;return l=this._hi/r,f=(o=(h=e.SPLIT*l)-(o=h-l))*(a=(f=e.SPLIT*r)-(a=f-r))-(c=l*r)+o*(u=r-a)+(s=l-o)*a+s*u,f=l+(h=(this._hi-c-f+this._lo-l*i)/r),this._hi=f,this._lo=l-f+h,this}}},{key:"dump",value:function(){return"DD<"+this._hi+", "+this._lo+">"}},{key:"divide",value:function(){if(arguments[0]instanceof e){var t=arguments[0],n=null,r=null,i=null,o=null,s=null,a=null,u=null,l=null;return r=(s=this._hi/t._hi)-(n=(a=e.SPLIT*s)-(n=a-s)),l=n*(i=(l=e.SPLIT*t._hi)-(i=l-t._hi))-(u=s*t._hi)+n*(o=t._hi-i)+r*i+r*o,new e(l=s+(a=(this._hi-u-l+this._lo-s*t._lo)/t._hi),s-l+a)}if("number"==typeof arguments[0]){var h=arguments[0];return A.isNaN(h)?e.createNaN():e.copy(this).selfDivide(h,0)}}},{key:"ge",value:function(t){return this._hi>t._hi||this._hi===t._hi&&this._lo>=t._lo}},{key:"pow",value:function(t){if(0===t)return e.valueOf(1);var n=new e(this),r=e.valueOf(1),i=Math.abs(t);if(i>1)for(;i>0;)i%2==1&&r.selfMultiply(n),(i/=2)>0&&(n=n.sqr());else r=n;return t<0?r.reciprocal():r}},{key:"ceil",value:function(){if(this.isNaN())return e.NaN;var t=Math.ceil(this._hi),n=0;return t===this._hi&&(n=Math.ceil(this._lo)),new e(t,n)}},{key:"compareTo",value:function(t){var e=t;return this._hie._hi?1:this._loe._lo?1:0}},{key:"rint",value:function(){return this.isNaN()?this:this.add(.5).floor()}},{key:"setValue",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.init(t),this}if("number"==typeof arguments[0]){var n=arguments[0];return this.init(n),this}}},{key:"max",value:function(t){return this.ge(t)?this:t}},{key:"sqrt",value:function(){if(this.isZero())return e.valueOf(0);if(this.isNegative())return e.NaN;var t=1/Math.sqrt(this._hi),n=this._hi*t,r=e.valueOf(n),i=this.subtract(r.sqr())._hi*(.5*t);return r.add(i)}},{key:"selfAdd",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfAdd(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0],r=null,i=null,o=null,s=null,a=null,u=null;return s=(o=this._hi+n)-(a=o-this._hi),i=(u=(s=n-a+(this._hi-s))+this._lo)+(o-(r=o+u)),this._hi=r+i,this._lo=i+(r-this._hi),this}}else if(2===arguments.length){var l=arguments[0],h=arguments[1],c=null,f=null,g=null,p=null,v=null,d=null,y=null;p=this._hi+l,f=this._lo+h,v=p-(d=p-this._hi),g=f-(y=f-this._lo);var m=(c=p+(d=(v=l-d+(this._hi-v))+f))+(d=(g=h-y+(this._lo-g))+(d+(p-c))),_=d+(c-m);return this._hi=m,this._lo=_,this}}},{key:"selfMultiply",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfMultiply(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfMultiply(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null;o=(l=e.SPLIT*this._hi)-this._hi,h=e.SPLIT*r,o=l-o,s=this._hi-o,a=h-r;var c=(l=this._hi*r)+(h=o*(a=h-a)-l+o*(u=r-a)+s*a+s*u+(this._hi*i+this._lo*r)),f=h+(o=l-c);return this._hi=c,this._lo=f,this}}},{key:"selfSqr",value:function(){return this.selfMultiply(this)}},{key:"floor",value:function(){if(this.isNaN())return e.NaN;var t=Math.floor(this._hi),n=0;return t===this._hi&&(n=Math.floor(this._lo)),new e(t,n)}},{key:"negate",value:function(){return this.isNaN()?this:new e(-this._hi,-this._lo)}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return null;throw t}}},{key:"multiply",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return t.isNaN()?e.createNaN():e.copy(this).selfMultiply(t)}if("number"==typeof arguments[0]){var n=arguments[0];return A.isNaN(n)?e.createNaN():e.copy(this).selfMultiply(n,0)}}},{key:"isNaN",value:function(){return A.isNaN(this._hi)}},{key:"intValue",value:function(){return Math.trunc(this._hi)}},{key:"toString",value:function(){var t=e.magnitude(this._hi);return t>=-3&&t<=20?this.toStandardNotation():this.toSciNotation()}},{key:"toStandardNotation",value:function(){var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!0,n),i=n[0]+1,o=r;if("."===r.charAt(0))o="0"+r;else if(i<0)o="0."+e.stringOfChar("0",-i)+r;else if(-1===r.indexOf(".")){var s=i-r.length;o=r+e.stringOfChar("0",s)+".0"}return this.isNegative()?"-"+o:o}},{key:"reciprocal",value:function(){var t,n,r,i,o=null,s=null,a=null,u=null;t=(r=1/this._hi)-(o=(a=e.SPLIT*r)-(o=a-r)),s=(u=e.SPLIT*this._hi)-this._hi;var l=r+(a=(1-(i=r*this._hi)-(u=o*(s=u-s)-i+o*(n=this._hi-s)+t*s+t*n)-r*this._lo)/this._hi);return new e(l,r-l+a)}},{key:"toSciNotation",value:function(){if(this.isZero())return e.SCI_NOT_ZERO;var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!1,n),i=e.SCI_NOT_EXPONENT_CHAR+n[0];if("0"===r.charAt(0))throw new IllegalStateException("Found leading zero: "+r);var o="";r.length>1&&(o=r.substring(1));var s=r.charAt(0)+"."+o;return this.isNegative()?"-"+s+i:s+i}},{key:"abs",value:function(){return this.isNaN()?e.NaN:this.isNegative()?this.negate():new e(this)}},{key:"isPositive",value:function(){return this._hi>0||0===this._hi&&this._lo>0}},{key:"lt",value:function(t){return this._hit._hi||this._hi===t._hi&&this._lo>t._lo}},{key:"isNegative",value:function(){return this._hi<0||0===this._hi&&this._lo<0}},{key:"trunc",value:function(){return this.isNaN()?e.NaN:this.isPositive()?this.floor():this.ceil()}},{key:"signum",value:function(){return this._hi>0?1:this._hi<0?-1:this._lo>0?1:this._lo<0?-1:0}},{key:"interfaces_",get:function(){return[w,k,b]}}],[{key:"constructor_",value:function(){if(this._hi=0,this._lo=0,0===arguments.length)this.init(0);else if(1===arguments.length){if("number"==typeof arguments[0]){var t=arguments[0];this.init(t)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}else if("string"==typeof arguments[0]){var r=arguments[0];e.constructor_.call(this,e.parse(r))}}else if(2===arguments.length){var i=arguments[0],o=arguments[1];this.init(i,o)}}},{key:"determinant",value:function(){if("number"==typeof arguments[3]&&"number"==typeof arguments[2]&&"number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1],r=arguments[2],i=arguments[3];return e.determinant(e.valueOf(t),e.valueOf(n),e.valueOf(r),e.valueOf(i))}if(arguments[3]instanceof e&&arguments[2]instanceof e&&arguments[0]instanceof e&&arguments[1]instanceof e){var o=arguments[1],s=arguments[2],a=arguments[3];return arguments[0].multiply(a).selfSubtract(o.multiply(s))}}},{key:"sqr",value:function(t){return e.valueOf(t).selfMultiply(t)}},{key:"valueOf",value:function(){if("string"==typeof arguments[0]){var t=arguments[0];return e.parse(t)}if("number"==typeof arguments[0])return new e(arguments[0])}},{key:"sqrt",value:function(t){return e.valueOf(t).sqrt()}},{key:"parse",value:function(t){for(var n=0,r=t.length;ut.isWhitespace(t.charAt(n));)n++;var i=!1;if(n=r);){var c=t.charAt(n);if(n++,ut.isDigit(c)){var f=c-"0";s.selfMultiply(e.TEN),s.selfAdd(f),a++}else{if("."!==c){if("e"===c||"E"===c){var g=t.substring(n);try{l=at.parseInt(g)}catch(e){throw e instanceof NumberFormatException?new NumberFormatException("Invalid exponent "+g+" in string "+t):e}break}throw new NumberFormatException("Unexpected character '"+c+"' at position "+n+" in string "+t)}u=a,h=!0}}var p=s;h||(u=a);var v=a-u-l;if(0===v)p=s;else if(v>0){var d=e.TEN.pow(v);p=s.divide(d)}else if(v<0){var y=e.TEN.pow(-v);p=s.multiply(y)}return i?p.negate():p}},{key:"createNaN",value:function(){return new e(A.NaN,A.NaN)}},{key:"copy",value:function(t){return new e(t)}},{key:"magnitude",value:function(t){var e=Math.abs(t),n=Math.log(e)/Math.log(10),r=Math.trunc(Math.floor(n));return 10*Math.pow(10,r)<=e&&(r+=1),r}},{key:"stringOfChar",value:function(t,e){for(var n=new st,r=0;r0){if(s<=0)return e.signum(a);i=o+s}else{if(!(o<0))return e.signum(a);if(s>=0)return e.signum(a);i=-o-s}var u=e.DP_SAFE_EPSILON*i;return a>=u||-a>=u?e.signum(a):2}},{key:"signum",value:function(t){return t>0?1:t<0?-1:0}}]),e}();ht.DP_SAFE_EPSILON=1e-15;var ct=function(){function e(){t(this,e)}return n(e,[{key:"getM",value:function(t){if(this.hasM()){var e=this.getDimension()-this.getMeasures();return this.getOrdinate(t,e)}return A.NaN}},{key:"setOrdinate",value:function(t,e,n){}},{key:"getZ",value:function(t){return this.hasZ()?this.getOrdinate(t,2):A.NaN}},{key:"size",value:function(){}},{key:"getOrdinate",value:function(t,e){}},{key:"getCoordinate",value:function(){}},{key:"getCoordinateCopy",value:function(t){}},{key:"createCoordinate",value:function(){}},{key:"getDimension",value:function(){}},{key:"hasM",value:function(){return this.getMeasures()>0}},{key:"getX",value:function(t){}},{key:"hasZ",value:function(){return this.getDimension()-this.getMeasures()>2}},{key:"getMeasures",value:function(){return 0}},{key:"expandEnvelope",value:function(t){}},{key:"copy",value:function(){}},{key:"getY",value:function(t){}},{key:"toCoordinateArray",value:function(){}},{key:"interfaces_",get:function(){return[b]}}]),e}();ct.X=0,ct.Y=1,ct.Z=2,ct.M=3;var ft=function(){function e(){t(this,e)}return n(e,null,[{key:"index",value:function(t,e,n){return ht.orientationIndex(t,e,n)}},{key:"isCCW",value:function(){if(arguments[0]instanceof Array){var t=arguments[0],n=t.length-1;if(n<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var r=t[0],i=0,o=1;o<=n;o++){var s=t[o];s.y>r.y&&(r=s,i=o)}var a=i;do{(a-=1)<0&&(a=n)}while(t[a].equals2D(r)&&a!==i);var u=i;do{u=(u+1)%n}while(t[u].equals2D(r)&&u!==i);var l=t[a],h=t[u];if(l.equals2D(r)||h.equals2D(r)||l.equals2D(h))return!1;var c=e.index(l,r,h);return 0===c?l.x>h.x:c>0}if(ot(arguments[0],ct)){var f=arguments[0],g=f.size()-1;if(g<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var p=f.getCoordinate(0),v=0,d=1;d<=g;d++){var y=f.getCoordinate(d);y.y>p.y&&(p=y,v=d)}var m=null,_=v;do{(_-=1)<0&&(_=g),m=f.getCoordinate(_)}while(m.equals2D(p)&&_!==v);var E=null,k=v;do{k=(k+1)%g,E=f.getCoordinate(k)}while(E.equals2D(p)&&k!==v);if(m.equals2D(p)||E.equals2D(p)||m.equals2D(E))return!1;var b=e.index(m,p,E);return 0===b?m.x>E.x:b>0}}}]),e}();ft.CLOCKWISE=-1,ft.RIGHT=ft.CLOCKWISE,ft.COUNTERCLOCKWISE=1,ft.LEFT=ft.COUNTERCLOCKWISE,ft.COLLINEAR=0,ft.STRAIGHT=ft.COLLINEAR;var gt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this._minCoord}},{key:"getRightmostSide",value:function(t,e){var n=this.getRightmostSideOfSegment(t,e);return n<0&&(n=this.getRightmostSideOfSegment(t,e-1)),n<0&&(this._minCoord=null,this.checkForRightmostCoordinate(t)),n}},{key:"findRightmostEdgeAtVertex",value:function(){var t=this._minDe.getEdge().getCoordinates();V.isTrue(this._minIndex>0&&this._minIndexthis._minCoord.y&&n.y>this._minCoord.y&&r===ft.CLOCKWISE)&&(i=!0),i&&(this._minIndex=this._minIndex-1)}},{key:"getRightmostSideOfSegment",value:function(t,e){var n=t.getEdge().getCoordinates();if(e<0||e+1>=n.length)return-1;if(n[e].y===n[e+1].y)return-1;var r=tt.LEFT;return n[e].ythis._minCoord.x)&&(this._minDe=t,this._minIndex=n,this._minCoord=e[n])}},{key:"findRightmostEdgeAtNode",value:function(){var t=this._minDe.getNode().getEdges();this._minDe=t.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)}},{key:"findEdge",value:function(t){for(var e=t.iterator();e.hasNext();){var n=e.next();n.isForward()&&this.checkForRightmostCoordinate(n)}V.isTrue(0!==this._minIndex||this._minCoord.equals(this._minDe.getCoordinate()),"inconsistency in rightmost processing"),0===this._minIndex?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe,this.getRightmostSide(this._minDe,this._minIndex)===tt.LEFT&&(this._orientedDe=this._minDe.getSym())}}],[{key:"constructor_",value:function(){this._minIndex=-1,this._minCoord=null,this._minDe=null,this._orientedDe=null}}]),e}(),pt=function(e){r(o,e);var i=c(o);function o(e,n){var r;return t(this,o),(r=i.call(this,n?e+" [ "+n+" ]":e)).pt=n?new z(n):void 0,r.name=Object.keys({TopologyException:o})[0],r}return n(o,[{key:"getCoordinate",value:function(){return this.pt}}]),o}(F),vt=function(){function e(){t(this,e),this.array=[]}return n(e,[{key:"addLast",value:function(t){this.array.push(t)}},{key:"removeFirst",value:function(){return this.array.shift()}},{key:"isEmpty",value:function(){return 0===this.array.length}}]),e}(),dt=function(e,i){r(s,e);var o=c(s);function s(e){var n;return t(this,s),(n=o.call(this)).array=[],e instanceof H&&n.addAll(e),n}return n(s,[{key:"interfaces_",get:function(){return[rt,H]}},{key:"ensureCapacity",value:function(){}},{key:"add",value:function(t){return 1===arguments.length?this.array.push(t):this.array.splice(arguments[0],0,arguments[1]),!0}},{key:"clear",value:function(){this.array=[]}},{key:"addAll",value:function(t){var e,n=d(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.array.push(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"set",value:function(t,e){var n=this.array[t];return this.array[t]=e,n}},{key:"iterator",value:function(){return new yt(this)}},{key:"get",value:function(t){if(t<0||t>=this.size())throw new nt;return this.array[t]}},{key:"isEmpty",value:function(){return 0===this.array.length}},{key:"sort",value:function(t){t?this.array.sort((function(e,n){return t.compare(e,n)})):this.array.sort()}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}},{key:"remove",value:function(t){for(var e=0,n=this.array.length;e=1&&e.getDepth(tt.LEFT)<=0&&!e.isInteriorAreaEdge()&&e.setInResult(!0)}}},{key:"computeDepths",value:function(t){var e=new Q,n=new vt,r=t.getNode();for(n.addLast(r),e.add(r),t.setVisited(!0);!n.isEmpty();){var i=n.removeFirst();e.add(i),this.computeNodeDepth(i);for(var o=i.getEdges().iterator();o.hasNext();){var s=o.next().getSym();if(!s.isVisited()){var a=s.getNode();e.contains(a)||(n.addLast(a),e.add(a))}}}}},{key:"compareTo",value:function(t){var e=t;return this._rightMostCoord.xe._rightMostCoord.x?1:0}},{key:"getEnvelope",value:function(){if(null===this._env){for(var t=new X,e=this._dirEdgeList.iterator();e.hasNext();)for(var n=e.next().getEdge().getCoordinates(),r=0;re.x?t.x:e.x,a=t.y>e.y?t.y:e.y,u=n.xr.x?n.x:r.x,c=n.y>r.y?n.y:r.y,f=((i>u?i:u)+(sl?o:l)+(an?n:t}if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var r=arguments[0],i=arguments[1],o=arguments[2];return ro?o:r}}},{key:"wrap",value:function(t,e){return t<0?e- -t%e:t%e}},{key:"max",value:function(){if(3===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[0];return t>n&&(n=t),e>n&&(n=e),n}if(4===arguments.length){var r=arguments[1],i=arguments[2],o=arguments[3],s=arguments[0];return r>s&&(s=r),i>s&&(s=i),o>s&&(s=o),s}}},{key:"average",value:function(t,e){return(t+e)/2}}]),e}();Et.LOG_10=Math.log(10);var kt=function(){function e(){t(this,e)}return n(e,null,[{key:"segmentToSegment",value:function(t,n,r,i){if(t.equals(n))return e.pointToSegment(t,r,i);if(r.equals(i))return e.pointToSegment(i,t,n);var o=!1;if(X.intersects(t,n,r,i)){var s=(n.x-t.x)*(i.y-r.y)-(n.y-t.y)*(i.x-r.x);if(0===s)o=!0;else{var a=(t.y-r.y)*(i.x-r.x)-(t.x-r.x)*(i.y-r.y),u=((t.y-r.y)*(n.x-t.x)-(t.x-r.x)*(n.y-t.y))/s,l=a/s;(l<0||l>1||u<0||u>1)&&(o=!0)}}else o=!0;return o?Et.min(e.pointToSegment(t,r,i),e.pointToSegment(n,r,i),e.pointToSegment(r,t,n),e.pointToSegment(i,t,n)):0}},{key:"pointToSegment",value:function(t,e,n){if(e.x===n.x&&e.y===n.y)return t.distance(e);var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/r;if(i<=0)return t.distance(e);if(i>=1)return t.distance(n);var o=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(o)*Math.sqrt(r)}},{key:"pointToLinePerpendicular",value:function(t,e,n){var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(i)*Math.sqrt(r)}},{key:"pointToSegmentString",value:function(t,n){if(0===n.length)throw new x("Line array must contain at least one vertex");for(var r=t.distance(n[0]),i=0;i0)&&(o=a,i=s)}return i}}},{key:"extend",value:function(t,n,r){var i=t.create(r,n.getDimension()),o=n.size();if(e.copy(n,0,i,0,o),o>0)for(var s=o;s0)&&(e=r)}return e}}]),e}(),Mt=function(){function e(){t(this,e)}return n(e,null,[{key:"toDimensionSymbol",value:function(t){switch(t){case e.FALSE:return e.SYM_FALSE;case e.TRUE:return e.SYM_TRUE;case e.DONTCARE:return e.SYM_DONTCARE;case e.P:return e.SYM_P;case e.L:return e.SYM_L;case e.A:return e.SYM_A}throw new x("Unknown dimension value: "+t)}},{key:"toDimensionValue",value:function(t){switch(ut.toUpperCase(t)){case e.SYM_FALSE:return e.FALSE;case e.SYM_TRUE:return e.TRUE;case e.SYM_DONTCARE:return e.DONTCARE;case e.SYM_P:return e.P;case e.SYM_L:return e.L;case e.SYM_A:return e.A}throw new x("Unknown dimension symbol: "+t)}}]),e}();Mt.P=0,Mt.L=1,Mt.A=2,Mt.FALSE=-1,Mt.TRUE=-2,Mt.DONTCARE=-3,Mt.SYM_FALSE="F",Mt.SYM_TRUE="T",Mt.SYM_DONTCARE="*",Mt.SYM_P="0",Mt.SYM_L="1",Mt.SYM_A="2";var Lt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}(),Pt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t,e){}},{key:"isDone",value:function(){}},{key:"isGeometryChanged",value:function(){}}]),e}(),Ct=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"computeEnvelopeInternal",value:function(){return this.isEmpty()?new X:this._points.expandEnvelope(new X)}},{key:"isRing",value:function(){return this.isClosed()&&this.isSimple()}},{key:"getCoordinates",value:function(){return this._points.toCoordinateArray()}},{key:"copyInternal",value:function(){return new s(this._points.copy(),this._factory)}},{key:"equalsExact",value:function(){if(2===arguments.length&&"number"==typeof arguments[1]&&arguments[0]instanceof U){var t=arguments[0],e=arguments[1];if(!this.isEquivalentClass(t))return!1;var n=t;if(this._points.size()!==n._points.size())return!1;for(var r=0;r0){var n=this._points.copy();St.reverse(n),this._points=n}return null}}}},{key:"getCoordinate",value:function(){return this.isEmpty()?null:this._points.getCoordinate(0)}},{key:"getBoundaryDimension",value:function(){return this.isClosed()?Mt.FALSE:0}},{key:"isClosed",value:function(){return!this.isEmpty()&&this.getCoordinateN(0).equals2D(this.getCoordinateN(this.getNumPoints()-1))}},{key:"reverseInternal",value:function(){var t=this._points.copy();return St.reverse(t),this.getFactory().createLineString(t)}},{key:"getEndPoint",value:function(){return this.isEmpty()?null:this.getPointN(this.getNumPoints()-1)}},{key:"getTypeCode",value:function(){return U.TYPECODE_LINESTRING}},{key:"getDimension",value:function(){return 1}},{key:"getLength",value:function(){return It.ofLine(this._points)}},{key:"getNumPoints",value:function(){return this._points.size()}},{key:"compareToSameClass",value:function(){if(1===arguments.length){for(var t=arguments[0],e=0,n=0;e= 2)");this._points=t}},{key:"isCoordinate",value:function(t){for(var e=0;e=1&&this.getCoordinateSequence().size()= 4)")}},{key:"getGeometryType",value:function(){return U.TYPENAME_LINEARRING}}],[{key:"constructor_",value:function(){var t=arguments[0],e=arguments[1];Ct.constructor_.call(this,t,e),this.validateConstruction()}}]),s}(Ct);zt.MINIMUM_VALID_SIZE=4;var jt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}}],[{key:"constructor_",value:function(){if(0===arguments.length)z.constructor_.call(this);else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y)}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y)}}else if(2===arguments.length){var n=arguments[0],r=arguments[1];z.constructor_.call(this,n,r,z.NULL_ORDINATE)}}}]),o}(z);jt.X=0,jt.Y=1,jt.Z=-1,jt.M=-1;var Xt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;case o.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y;case o.M:return this._m}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y),this._m=this.getM()}}else if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2];z.constructor_.call(this,n,r,z.NULL_ORDINATE),this._m=i}}}]),o}(z);Xt.X=0,Xt.Y=1,Xt.Z=-1,Xt.M=2;var Ut=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case z.X:this.x=e;break;case z.Y:this.y=e;break;case z.Z:this.z=e;break;case z.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getOrdinate",value:function(t){switch(t){case z.X:return this.x;case z.Y:return this.y;case z.Z:return this.getZ();case z.M:return this.getM()}throw new x("Invalid ordinate index: "+t)}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e),this._m=this.getM()}}else if(4===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],s=arguments[3];z.constructor_.call(this,n,r,i),this._m=s}}}]),o}(z),Zt=function(){function e(){t(this,e)}return n(e,null,[{key:"measures",value:function(t){return t instanceof jt?0:t instanceof Xt||t instanceof Ut?1:0}},{key:"dimension",value:function(t){return t instanceof jt?2:t instanceof Xt?3:t instanceof Ut?4:3}},{key:"create",value:function(){if(1===arguments.length){var t=arguments[0];return e.create(t,0)}if(2===arguments.length){var n=arguments[0],r=arguments[1];return 2===n?new jt:3===n&&0===r?new z:3===n&&1===r?new Xt:4===n&&1===r?new Ut:new z}}}]),e}(),Ht=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getCoordinate",value:function(t){return this.get(t)}},{key:"addAll",value:function(){if(2===arguments.length&&"boolean"==typeof arguments[1]&&ot(arguments[0],H)){for(var t=arguments[1],e=!1,n=arguments[0].iterator();n.hasNext();)this.add(n.next(),t),e=!0;return e}return f(i(s.prototype),"addAll",this).apply(this,arguments)}},{key:"clone",value:function(){for(var t=f(i(s.prototype),"clone",this).call(this),e=0;e=1&&this.get(this.size()-1).equals2D(r))return null;f(i(s.prototype),"add",this).call(this,r)}else if(arguments[0]instanceof Object&&"boolean"==typeof arguments[1]){var o=arguments[0],a=arguments[1];return this.add(o,a),!0}}else if(3===arguments.length){if("boolean"==typeof arguments[2]&&arguments[0]instanceof Array&&"boolean"==typeof arguments[1]){var u=arguments[0],l=arguments[1];if(arguments[2])for(var h=0;h=0;c--)this.add(u[c],l);return!0}if("boolean"==typeof arguments[2]&&Number.isInteger(arguments[0])&&arguments[1]instanceof z){var g=arguments[0],p=arguments[1];if(!arguments[2]){var v=this.size();if(v>0){if(g>0&&this.get(g-1).equals2D(p))return null;if(g_&&(x=-1);for(var E=m;E!==_;E+=x)this.add(d[E],y);return!0}}},{key:"closeRing",value:function(){if(this.size()>0){var t=this.get(0).copy();this.add(t,!1)}}}],[{key:"constructor_",value:function(){if(0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.ensureCapacity(t.length),this.add(t,!0)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this.ensureCapacity(e.length),this.add(e,n)}}}]),s}(dt);Ht.coordArrayType=new Array(0).fill(null);var Wt=function(){function e(){t(this,e)}return n(e,null,[{key:"isRing",value:function(t){return!(t.length<4||!t[0].equals2D(t[t.length-1]))}},{key:"ptNotInList",value:function(t,n){for(var r=0;r=t?e:[]}},{key:"indexOf",value:function(t,e){for(var n=0;n0)&&(e=t[n]);return e}},{key:"extract",value:function(t,e,n){e=Et.clamp(e,0,t.length);var r=(n=Et.clamp(n,-1,t.length))-e+1;n<0&&(r=0),e>=t.length&&(r=0),nr.length)return 1;if(0===n.length)return 0;var i=Wt.compare(n,r);return Wt.isEqualReversed(n,r)?0:i}},{key:"OLDcompare",value:function(t,e){var n=t,r=e;if(n.lengthr.length)return 1;if(0===n.length)return 0;for(var i=Wt.increasingDirection(n),o=Wt.increasingDirection(r),s=i>0?0:n.length-1,a=o>0?0:n.length-1,u=0;u0){var t=new Qt(17*this._coordinates.length);t.append("("),t.append(this._coordinates[0]);for(var e=1;e3&&(t=3),t<2&&(t=2),new $t(arguments[0],t)}if(3===arguments.length){var e=arguments[2],n=arguments[1]-e;return e>1&&(e=1),n>3&&(n=3),n<2&&(n=2),new $t(arguments[0],n+e,e)}}}},{key:"interfaces_",get:function(){return[bt,w]}}],[{key:"instance",value:function(){return e.instanceObject}}]),e}();te.instanceObject=new te;var ee=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e=0?t:e}}]),e}(),oe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"readResolve",value:function(){return e.nameToTypeMap.get(this._name)}},{key:"toString",value:function(){return this._name}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){this._name=null;var t=arguments[0];this._name=t,e.nameToTypeMap.put(t,this)}}]),e}();oe.nameToTypeMap=new re,ie.Type=oe,ie.FIXED=new oe("FIXED"),ie.FLOATING=new oe("FLOATING"),ie.FLOATING_SINGLE=new oe("FLOATING SINGLE"),ie.maximumPreciseValue=9007199254740992;var se=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e1){if(u instanceof Ft)return this.createMultiPolygon(e.toPolygonArray(t));if(u instanceof Ct)return this.createMultiLineString(e.toLineStringArray(t));if(u instanceof Ot)return this.createMultiPoint(e.toPointArray(t));V.shouldNeverReachHere("Unhandled geometry type: "+u.getGeometryType())}return u}},{key:"createMultiPointFromCoords",value:function(t){return this.createMultiPoint(null!==t?this.getCoordinateSequenceFactory().create(t):null)}},{key:"createPoint",value:function(){if(0===arguments.length)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];return this.createPoint(null!==t?this.getCoordinateSequenceFactory().create([t]):null)}if(ot(arguments[0],ct))return new Ot(arguments[0],this)}}},{key:"getCoordinateSequenceFactory",value:function(){return this._coordinateSequenceFactory}},{key:"createPolygon",value:function(){if(0===arguments.length)return this.createPolygon(null,null);if(1===arguments.length){if(ot(arguments[0],ct)){var t=arguments[0];return this.createPolygon(this.createLinearRing(t))}if(arguments[0]instanceof Array){var e=arguments[0];return this.createPolygon(this.createLinearRing(e))}if(arguments[0]instanceof zt){var n=arguments[0];return this.createPolygon(n,null)}}else if(2===arguments.length)return new Ft(arguments[0],arguments[1],this)}},{key:"getSRID",value:function(){return this._SRID}},{key:"createGeometryCollection",value:function(){return 0===arguments.length?new Bt(null,this):1===arguments.length?new Bt(arguments[0],this):void 0}},{key:"getPrecisionModel",value:function(){return this._precisionModel}},{key:"createLinearRing",value:function(){if(0===arguments.length)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof Array){var t=arguments[0];return this.createLinearRing(null!==t?this.getCoordinateSequenceFactory().create(t):null)}if(ot(arguments[0],ct))return new zt(arguments[0],this)}}},{key:"createMultiPolygon",value:function(){return 0===arguments.length?new ee(null,this):1===arguments.length?new ee(arguments[0],this):void 0}},{key:"createMultiPoint",value:function(){if(0===arguments.length)return new Yt(null,this);if(1===arguments.length){if(arguments[0]instanceof Array)return new Yt(arguments[0],this);if(ot(arguments[0],ct)){var t=arguments[0];if(null===t)return this.createMultiPoint(new Array(0).fill(null));for(var e=new Array(t.size()).fill(null),n=0;n="a"&&t<="z"||t>="A"&&t<="Z"}},{key:"isNumeric_",value:function(t,e){return t>="0"&&t<="9"||"."==t&&!(void 0!==e&&e)}},{key:"isWhiteSpace_",value:function(t){return" "==t||"\t"==t||"\r"==t||"\n"==t}},{key:"nextChar_",value:function(){return this.wkt.charAt(++this.index_)}},{key:"nextToken",value:function(){var t,e=this.nextChar_(),n=this.index_,r=e;if("("==e)t=ve;else if(","==e)t=me;else if(")"==e)t=de;else if(this.isNumeric_(e)||"-"==e)t=ye,r=this.readNumber_();else if(this.isAlpha_(e))t=pe,r=this.readText_();else{if(this.isWhiteSpace_(e))return this.nextToken();if(""!==e)throw new Error("Unexpected character: "+e);t=_e}return{position:n,value:r,type:t}}},{key:"readNumber_",value:function(){var t,e=this.index_,n=!1,r=!1;do{"."==t?n=!0:"e"!=t&&"E"!=t||(r=!0),t=this.nextChar_()}while(this.isNumeric_(t,n)||!r&&("e"==t||"E"==t)||r&&("-"==t||"+"==t));return parseFloat(this.wkt.substring(e,this.index_--))}},{key:"readText_",value:function(){var t,e=this.index_;do{t=this.nextChar_()}while(this.isAlpha_(t));return this.wkt.substring(e,this.index_--).toUpperCase()}}]),e}(),ke=function(){function e(n,r){t(this,e),this.lexer_=n,this.token_,this.layout_=ue,this.factory=r}return n(e,[{key:"consume_",value:function(){this.token_=this.lexer_.nextToken()}},{key:"isTokenType",value:function(t){return this.token_.type==t}},{key:"match",value:function(t){var e=this.isTokenType(t);return e&&this.consume_(),e}},{key:"parse",value:function(){return this.consume_(),this.parseGeometry_()}},{key:"parseGeometryLayout_",value:function(){var t=ue,e=this.token_;if(this.isTokenType(pe)){var n=e.value;"Z"===n?t=le:"M"===n?t=he:"ZM"===n&&(t=ce),t!==ue&&this.consume_()}return t}},{key:"parseGeometryCollectionText_",value:function(){if(this.match(ve)){var t=[];do{t.push(this.parseGeometry_())}while(this.match(me));if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePointText_",value:function(){if(this.match(ve)){var t=this.parsePoint_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return null;throw new Error(this.formatErrorMessage_())}},{key:"parseLineStringText_",value:function(){if(this.match(ve)){var t=this.parsePointList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePolygonText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPointText_",value:function(){var t;if(this.match(ve)){if(t=this.token_.type==ve?this.parsePointTextList_():this.parsePointList_(),this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiLineStringText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPolygonText_",value:function(){if(this.match(ve)){var t=this.parsePolygonTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePoint_",value:function(){for(var t=[],e=this.layout_.length,n=0;n1?t.createPolygon(r[0],r.slice(1)):t.createPolygon(r[0])},r=this.token_;if(this.match(pe)){var i=r.value;if(this.layout_=this.parseGeometryLayout_(),"GEOMETRYCOLLECTION"==i){var o=this.parseGeometryCollectionText_();return t.createGeometryCollection(o)}switch(i){case"POINT":var s=this.parsePointText_();return s?t.createPoint(a(z,g(s))):t.createPoint();case"LINESTRING":var u=this.parseLineStringText_().map(e);return t.createLineString(u);case"LINEARRING":var l=this.parseLineStringText_().map(e);return t.createLinearRing(l);case"POLYGON":var h=this.parsePolygonText_();return h&&0!==h.length?n(h):t.createPolygon();case"MULTIPOINT":var c=this.parseMultiPointText_();if(!c||0===c.length)return t.createMultiPoint();var f=c.map(e).map((function(e){return t.createPoint(e)}));return t.createMultiPoint(f);case"MULTILINESTRING":var p=this.parseMultiLineStringText_().map((function(n){return t.createLineString(n.map(e))}));return t.createMultiLineString(p);case"MULTIPOLYGON":var v=this.parseMultiPolygonText_();if(!v||0===v.length)return t.createMultiPolygon();var d=v.map(n);return t.createMultiPolygon(d);default:throw new Error("Invalid geometry type: "+i)}}throw new Error(this.formatErrorMessage_())}}]),e}();function be(t){if(t.isEmpty())return"";var e=t.getCoordinate(),n=[e.x,e.y];return void 0===e.z||Number.isNaN(e.z)||n.push(e.z),void 0===e.m||Number.isNaN(e.m)||n.push(e.m),n.join(" ")}function we(t){for(var e=t.getCoordinates().map((function(t){var e=[t.x,t.y];return void 0===t.z||Number.isNaN(t.z)||e.push(t.z),void 0===t.m||Number.isNaN(t.m)||e.push(t.m),e})),n=[],r=0,i=e.length;r0&&(e+=" "+r),t.isEmpty()?e+" "+ge:e+" ("+n(t)+")"}var Me=function(){function e(n){t(this,e),this.geometryFactory=n||new ae,this.precisionModel=this.geometryFactory.getPrecisionModel()}return n(e,[{key:"read",value:function(t){var e=new Ee(t);return new ke(e,this.geometryFactory).parse()}},{key:"write",value:function(t){return Se(t)}}]),e}(),Le=function(){function e(n){t(this,e),this.parser=new Me(n)}return n(e,[{key:"write",value:function(t){return this.parser.write(t)}}],[{key:"toLineString",value:function(t,e){if(2!==arguments.length)throw new Error("Not implemented");return"LINESTRING ( "+t.x+" "+t.y+", "+e.x+" "+e.y+" )"}}]),e}(),Pe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getIndexAlongSegment",value:function(t,e){return this.computeIntLineIndex(),this._intLineIndex[t][e]}},{key:"getTopologySummary",value:function(){var t=new Qt;return this.isEndPoint()&&t.append(" endpoint"),this._isProper&&t.append(" proper"),this.isCollinear()&&t.append(" collinear"),t.toString()}},{key:"computeIntersection",value:function(t,e,n,r){this._inputLines[0][0]=t,this._inputLines[0][1]=e,this._inputLines[1][0]=n,this._inputLines[1][1]=r,this._result=this.computeIntersect(t,e,n,r)}},{key:"getIntersectionNum",value:function(){return this._result}},{key:"computeIntLineIndex",value:function(){if(0===arguments.length)null===this._intLineIndex&&(this._intLineIndex=Array(2).fill().map((function(){return Array(2)})),this.computeIntLineIndex(0),this.computeIntLineIndex(1));else if(1===arguments.length){var t=arguments[0];this.getEdgeDistance(t,0)>this.getEdgeDistance(t,1)?(this._intLineIndex[t][0]=0,this._intLineIndex[t][1]=1):(this._intLineIndex[t][0]=1,this._intLineIndex[t][1]=0)}}},{key:"isProper",value:function(){return this.hasIntersection()&&this._isProper}},{key:"setPrecisionModel",value:function(t){this._precisionModel=t}},{key:"isInteriorIntersection",value:function(){if(0===arguments.length)return!!this.isInteriorIntersection(0)||!!this.isInteriorIntersection(1);if(1===arguments.length){for(var t=arguments[0],e=0;ei?r:i;else{var s=Math.abs(t.x-e.x),a=Math.abs(t.y-e.y);0!==(o=r>i?s:a)||t.equals(e)||(o=Math.max(s,a))}return V.isTrue(!(0===o&&!t.equals(e)),"Bad distance calculation"),o}},{key:"nonRobustComputeEdgeDistance",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y,o=Math.sqrt(r*r+i*i);return V.isTrue(!(0===o&&!t.equals(e)),"Invalid distance calculation"),o}}]),e}();Pe.DONT_INTERSECT=0,Pe.DO_INTERSECT=1,Pe.COLLINEAR=2,Pe.NO_INTERSECTION=0,Pe.POINT_INTERSECTION=1,Pe.COLLINEAR_INTERSECTION=2;var Ce=function(e){r(s,e);var o=c(s);function s(){return t(this,s),o.call(this)}return n(s,[{key:"isInSegmentEnvelopes",value:function(t){var e=new X(this._inputLines[0][0],this._inputLines[0][1]),n=new X(this._inputLines[1][0],this._inputLines[1][1]);return e.contains(t)&&n.contains(t)}},{key:"computeIntersection",value:function(){if(3!==arguments.length)return f(i(s.prototype),"computeIntersection",this).apply(this,arguments);var t=arguments[0],e=arguments[1],n=arguments[2];if(this._isProper=!1,X.intersects(e,n,t)&&0===ft.index(e,n,t)&&0===ft.index(n,e,t))return this._isProper=!0,(t.equals(e)||t.equals(n))&&(this._isProper=!1),this._result=Pe.POINT_INTERSECTION,null;this._result=Pe.NO_INTERSECTION}},{key:"intersection",value:function(t,e,n,r){var i=this.intersectionSafe(t,e,n,r);return this.isInSegmentEnvelopes(i)||(i=new z(s.nearestEndpoint(t,e,n,r))),null!==this._precisionModel&&this._precisionModel.makePrecise(i),i}},{key:"checkDD",value:function(t,e,n,r,i){var o=ht.intersection(t,e,n,r),s=this.isInSegmentEnvelopes(o);xt.out.println("DD in env = "+s+" --------------------- "+o),i.distance(o)>1e-4&&xt.out.println("Distance = "+i.distance(o))}},{key:"intersectionSafe",value:function(t,e,n,r){var i=_t.intersection(t,e,n,r);return null===i&&(i=s.nearestEndpoint(t,e,n,r)),i}},{key:"computeCollinearIntersection",value:function(t,e,n,r){var i=X.intersects(t,e,n),o=X.intersects(t,e,r),s=X.intersects(n,r,t),a=X.intersects(n,r,e);return i&&o?(this._intPt[0]=n,this._intPt[1]=r,Pe.COLLINEAR_INTERSECTION):s&&a?(this._intPt[0]=t,this._intPt[1]=e,Pe.COLLINEAR_INTERSECTION):i&&s?(this._intPt[0]=n,this._intPt[1]=t,!n.equals(t)||o||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):i&&a?(this._intPt[0]=n,this._intPt[1]=e,!n.equals(e)||o||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&s?(this._intPt[0]=r,this._intPt[1]=t,!r.equals(t)||i||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&a?(this._intPt[0]=r,this._intPt[1]=e,!r.equals(e)||i||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):Pe.NO_INTERSECTION}},{key:"computeIntersect",value:function(t,e,n,r){if(this._isProper=!1,!X.intersects(t,e,n,r))return Pe.NO_INTERSECTION;var i=ft.index(t,e,n),o=ft.index(t,e,r);if(i>0&&o>0||i<0&&o<0)return Pe.NO_INTERSECTION;var s=ft.index(n,r,t),a=ft.index(n,r,e);return s>0&&a>0||s<0&&a<0?Pe.NO_INTERSECTION:0===i&&0===o&&0===s&&0===a?this.computeCollinearIntersection(t,e,n,r):(0===i||0===o||0===s||0===a?(this._isProper=!1,t.equals2D(n)||t.equals2D(r)?this._intPt[0]=t:e.equals2D(n)||e.equals2D(r)?this._intPt[0]=e:0===i?this._intPt[0]=new z(n):0===o?this._intPt[0]=new z(r):0===s?this._intPt[0]=new z(t):0===a&&(this._intPt[0]=new z(e))):(this._isProper=!0,this._intPt[0]=this.intersection(t,e,n,r)),Pe.POINT_INTERSECTION)}}],[{key:"nearestEndpoint",value:function(t,e,n,r){var i=t,o=kt.pointToSegment(t,n,r),s=kt.pointToSegment(e,n,r);return sr&&(n=e.x,r=t.x),this._p.x>=n&&this._p.x<=r&&(this._isPointOnSegment=!0),null}if(t.y>this._p.y&&e.y<=this._p.y||e.y>this._p.y&&t.y<=this._p.y){var i=ft.index(t,e,this._p);if(i===ft.COLLINEAR)return this._isPointOnSegment=!0,null;e.ythis.location.length){var e=new Array(3).fill(null);e[tt.ON]=this.location[tt.ON],e[tt.LEFT]=Z.NONE,e[tt.RIGHT]=Z.NONE,this.location=e}for(var n=0;n1&&t.append(Z.toLocationSymbol(this.location[tt.LEFT])),t.append(Z.toLocationSymbol(this.location[tt.ON])),this.location.length>1&&t.append(Z.toLocationSymbol(this.location[tt.RIGHT])),t.toString()}},{key:"setLocations",value:function(t,e,n){this.location[tt.ON]=t,this.location[tt.LEFT]=e,this.location[tt.RIGHT]=n}},{key:"get",value:function(t){return t1}},{key:"isAnyNull",value:function(){for(var t=0;tthis._maxNodeDegree&&(this._maxNodeDegree=e),t=this.getNext(t)}while(t!==this._startDe);this._maxNodeDegree*=2}},{key:"addPoints",value:function(t,e,n){var r=t.getCoordinates();if(e){var i=1;n&&(i=0);for(var o=i;o=0;a--)this._pts.add(r[a])}}},{key:"isHole",value:function(){return this._isHole}},{key:"setInResult",value:function(){var t=this._startDe;do{t.getEdge().setInResult(!0),t=t.getNext()}while(t!==this._startDe)}},{key:"containsPoint",value:function(t){var e=this.getLinearRing();if(!e.getEnvelopeInternal().contains(t))return!1;if(!Oe.isInRing(t,e.getCoordinates()))return!1;for(var n=this._holes.iterator();n.hasNext();)if(n.next().containsPoint(t))return!1;return!0}},{key:"addHole",value:function(t){this._holes.add(t)}},{key:"isShell",value:function(){return null===this._shell}},{key:"getLabel",value:function(){return this._label}},{key:"getEdges",value:function(){return this._edges}},{key:"getMaxNodeDegree",value:function(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree}},{key:"getShell",value:function(){return this._shell}},{key:"mergeLabel",value:function(){if(1===arguments.length){var t=arguments[0];this.mergeLabel(t,0),this.mergeLabel(t,1)}else if(2===arguments.length){var e=arguments[1],n=arguments[0].getLocation(e,tt.RIGHT);if(n===Z.NONE)return null;if(this._label.getLocation(e)===Z.NONE)return this._label.setLocation(e,n),null}}},{key:"setShell",value:function(t){this._shell=t,null!==t&&t.addHole(this)}},{key:"toPolygon",value:function(t){for(var e=new Array(this._holes.size()).fill(null),n=0;n=2,"found partial label"),this.computeIM(t)}},{key:"isInResult",value:function(){return this._isInResult}},{key:"isVisited",value:function(){return this._isVisited}}],[{key:"constructor_",value:function(){if(this._label=null,this._isInResult=!1,this._isCovered=!1,this._isCoveredSet=!1,this._isVisited=!1,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._label=t}}}]),e}(),Ge=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isIncidentEdgeInResult",value:function(){for(var t=this.getEdges().getEdges().iterator();t.hasNext();)if(t.next().getEdge().isInResult())return!0;return!1}},{key:"isIsolated",value:function(){return 1===this._label.getGeometryCount()}},{key:"getCoordinate",value:function(){return this._coord}},{key:"print",value:function(t){t.println("node "+this._coord+" lbl: "+this._label)}},{key:"computeIM",value:function(t){}},{key:"computeMergedLocation",value:function(t,e){var n=Z.NONE;if(n=this._label.getLocation(e),!t.isNull(e)){var r=t.getLocation(e);n!==Z.BOUNDARY&&(n=r)}return n}},{key:"setLabel",value:function(){if(2!==arguments.length||!Number.isInteger(arguments[1])||!Number.isInteger(arguments[0]))return f(i(s.prototype),"setLabel",this).apply(this,arguments);var t=arguments[0],e=arguments[1];null===this._label?this._label=new Ae(t,e):this._label.setLocation(t,e)}},{key:"getEdges",value:function(){return this._edges}},{key:"mergeLabel",value:function(){if(arguments[0]instanceof s){var t=arguments[0];this.mergeLabel(t._label)}else if(arguments[0]instanceof Ae)for(var e=arguments[0],n=0;n<2;n++){var r=this.computeMergedLocation(e,n);this._label.getLocation(n)===Z.NONE&&this._label.setLocation(n,r)}}},{key:"add",value:function(t){this._edges.insert(t),t.setNode(this)}},{key:"setLabelBoundary",value:function(t){if(null===this._label)return null;var e=Z.NONE;null!==this._label&&(e=this._label.getLocation(t));var n=null;switch(e){case Z.BOUNDARY:n=Z.INTERIOR;break;case Z.INTERIOR:default:n=Z.BOUNDARY}this._label.setLocation(t,n)}}],[{key:"constructor_",value:function(){this._coord=null,this._edges=null;var t=arguments[0],e=arguments[1];this._coord=t,this._edges=e,this._label=new Ae(0,Z.NONE)}}]),s}(Ve),Be=function(e){r(i,e);var n=c(i);function i(){return t(this,i),n.apply(this,arguments)}return i}(ne);function Ye(t){return null==t?0:t.color}function ze(t){return null==t?null:t.parent}function je(t,e){null!==t&&(t.color=e)}function Xe(t){return null==t?null:t.left}function Ue(t){return null==t?null:t.right}var Ze=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),(e=i.call(this)).root_=null,e.size_=0,e}return n(o,[{key:"get",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return e.value;e=e.right}}return null}},{key:"put",value:function(t,e){if(null===this.root_)return this.root_={key:t,value:e,left:null,right:null,parent:null,color:0,getValue:function(){return this.value},getKey:function(){return this.key}},this.size_=1,null;var n,r,i=this.root_;do{if(n=i,(r=t.compareTo(i.key))<0)i=i.left;else{if(!(r>0)){var o=i.value;return i.value=e,o}i=i.right}}while(null!==i);var s={key:t,left:null,right:null,value:e,parent:n,color:0,getValue:function(){return this.value},getKey:function(){return this.key}};return r<0?n.left=s:n.right=s,this.fixAfterInsertion(s),this.size_++,null}},{key:"fixAfterInsertion",value:function(t){var e;for(t.color=1;null!=t&&t!==this.root_&&1===t.parent.color;)ze(t)===Xe(ze(ze(t)))?1===Ye(e=Ue(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Ue(ze(t))&&(t=ze(t),this.rotateLeft(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateRight(ze(ze(t)))):1===Ye(e=Xe(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Xe(ze(t))&&(t=ze(t),this.rotateRight(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateLeft(ze(ze(t))));this.root_.color=0}},{key:"values",value:function(){var t=new dt,e=this.getFirstEntry();if(null!==e)for(t.add(e.value);null!==(e=o.successor(e));)t.add(e.value);return t}},{key:"entrySet",value:function(){var t=new Q,e=this.getFirstEntry();if(null!==e)for(t.add(e);null!==(e=o.successor(e));)t.add(e);return t}},{key:"rotateLeft",value:function(t){if(null!=t){var e=t.right;t.right=e.left,null!=e.left&&(e.left.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.left===t?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}}},{key:"rotateRight",value:function(t){if(null!=t){var e=t.left;t.left=e.right,null!=e.right&&(e.right.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.right===t?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}}},{key:"getFirstEntry",value:function(){var t=this.root_;if(null!=t)for(;null!=t.left;)t=t.left;return t}},{key:"size",value:function(){return this.size_}},{key:"containsKey",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return!0;e=e.right}}return!1}}],[{key:"successor",value:function(t){var e;if(null===t)return null;if(null!==t.right){for(e=t.right;null!==e.left;)e=e.left;return e}e=t.parent;for(var n=t;null!==e&&n===e.right;)n=e,e=e.parent;return e}}]),o}(Be),He=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"find",value:function(t){return this.nodeMap.get(t)}},{key:"addNode",value:function(){if(arguments[0]instanceof z){var t=arguments[0],e=this.nodeMap.get(t);return null===e&&(e=this.nodeFact.createNode(t),this.nodeMap.put(t,e)),e}if(arguments[0]instanceof Ge){var n=arguments[0],r=this.nodeMap.get(n.getCoordinate());return null===r?(this.nodeMap.put(n.getCoordinate(),n),n):(r.mergeLabel(n),r)}}},{key:"print",value:function(t){for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this.nodeMap.values().iterator()}},{key:"values",value:function(){return this.nodeMap.values()}},{key:"getBoundaryNodes",value:function(t){for(var e=new dt,n=this.iterator();n.hasNext();){var r=n.next();r.getLabel().getLocation(t)===Z.BOUNDARY&&e.add(r)}return e}},{key:"add",value:function(t){var e=t.getCoordinate();this.addNode(e).add(t)}}],[{key:"constructor_",value:function(){this.nodeMap=new Ze,this.nodeFact=null;var t=arguments[0];this.nodeFact=t}}]),e}(),We=function(){function e(){t(this,e)}return n(e,null,[{key:"isNorthern",value:function(t){return t===e.NE||t===e.NW}},{key:"isOpposite",value:function(t,e){return t!==e&&2==(t-e+4)%4}},{key:"commonHalfPlane",value:function(t,e){if(t===e)return t;if(2==(t-e+4)%4)return-1;var n=te?t:e)?3:n}},{key:"isInHalfPlane",value:function(t,n){return n===e.SE?t===e.SE||t===e.SW:t===n||t===n+1}},{key:"quadrant",value:function(){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1];if(0===t&&0===n)throw new x("Cannot compute the quadrant for point ( "+t+", "+n+" )");return t>=0?n>=0?e.NE:e.SE:n>=0?e.NW:e.SW}if(arguments[0]instanceof z&&arguments[1]instanceof z){var r=arguments[0],i=arguments[1];if(i.x===r.x&&i.y===r.y)throw new x("Cannot compute the quadrant for two identical points "+r);return i.x>=r.x?i.y>=r.y?e.NE:e.SE:i.y>=r.y?e.NW:e.SW}}}]),e}();We.NE=0,We.NW=1,We.SW=2,We.SE=3;var Je=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareDirection",value:function(t){return this._dx===t._dx&&this._dy===t._dy?0:this._quadrant>t._quadrant?1:this._quadrant2){o.linkDirectedEdgesForMinimalEdgeRings();var s=o.buildMinimalRings(),a=this.findShell(s);null!==a?(this.placePolygonHoles(a,s),e.add(a)):n.addAll(s)}else r.add(o)}return r}},{key:"buildMaximalEdgeRings",value:function(t){for(var e=new dt,n=t.iterator();n.hasNext();){var r=n.next();if(r.isInResult()&&r.getLabel().isArea()&&null===r.getEdgeRing()){var i=new qe(r,this._geometryFactory);e.add(i),i.setInResult()}}return e}},{key:"placePolygonHoles",value:function(t,e){for(var n=e.iterator();n.hasNext();){var r=n.next();r.isHole()&&r.setShell(t)}}},{key:"getPolygons",value:function(){return this.computePolygons(this._shellList)}},{key:"findShell",value:function(t){for(var e=0,n=null,r=t.iterator();r.hasNext();){var i=r.next();i.isHole()||(n=i,e++)}return V.isTrue(e<=1,"found two shells in MinimalEdgeRing list"),n}},{key:"add",value:function(){if(1===arguments.length){var t=arguments[0];this.add(t.getEdgeEnds(),t.getNodes())}else if(2===arguments.length){var e=arguments[0],n=arguments[1];$e.linkResultDirectedEdges(n);var r=this.buildMaximalEdgeRings(e),i=new dt,o=this.buildMinimalEdgeRings(r,this._shellList,i);this.sortShellsAndHoles(o,this._shellList,i),this.placeFreeHoles(this._shellList,i)}}}],[{key:"constructor_",value:function(){this._geometryFactory=null,this._shellList=new dt;var t=arguments[0];this._geometryFactory=t}},{key:"findEdgeRingContaining",value:function(t,e){for(var n=t.getLinearRing(),r=n.getEnvelopeInternal(),i=n.getCoordinateN(0),o=null,s=null,a=e.iterator();a.hasNext();){var u=a.next(),l=u.getLinearRing(),h=l.getEnvelopeInternal();if(!h.equals(r)&&h.contains(r)){i=Wt.ptNotInList(n.getCoordinates(),l.getCoordinates());var c=!1;Oe.isInRing(i,l.getCoordinates())&&(c=!0),c&&(null===o||s.contains(h))&&(s=(o=u).getLinearRing().getEnvelopeInternal())}}return o}}]),e}(),en=function(){function e(){t(this,e)}return n(e,[{key:"getBounds",value:function(){}}]),e}(),nn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getItem",value:function(){return this._item}},{key:"getBounds",value:function(){return this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){this._bounds=null,this._item=null;var t=arguments[0],e=arguments[1];this._bounds=t,this._item=e}}]),e}(),rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"poll",value:function(){if(this.isEmpty())return null;var t=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),t}},{key:"size",value:function(){return this._size}},{key:"reorder",value:function(t){for(var e=null,n=this._items.get(t);2*t<=this._size&&((e=2*t)!==this._size&&this._items.get(e+1).compareTo(this._items.get(e))<0&&e++,this._items.get(e).compareTo(n)<0);t=e)this._items.set(t,this._items.get(e));this._items.set(t,n)}},{key:"clear",value:function(){this._size=0,this._items.clear()}},{key:"peek",value:function(){return this.isEmpty()?null:this._items.get(1)}},{key:"isEmpty",value:function(){return 0===this._size}},{key:"add",value:function(t){this._items.add(null),this._size+=1;var e=this._size;for(this._items.set(0,t);t.compareTo(this._items.get(Math.trunc(e/2)))<0;e/=2)this._items.set(e,this._items.get(Math.trunc(e/2)));this._items.set(e,t)}}],[{key:"constructor_",value:function(){this._size=null,this._items=null,this._size=0,this._items=new dt,this._items.add(null)}}]),e}(),on=function(){function e(){t(this,e)}return n(e,[{key:"insert",value:function(t,e){}},{key:"remove",value:function(t,e){}},{key:"query",value:function(){}}]),e}(),sn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLevel",value:function(){return this._level}},{key:"size",value:function(){return this._childBoundables.size()}},{key:"getChildBoundables",value:function(){return this._childBoundables}},{key:"addChildBoundable",value:function(t){V.isTrue(null===this._bounds),this._childBoundables.add(t)}},{key:"isEmpty",value:function(){return this._childBoundables.isEmpty()}},{key:"getBounds",value:function(){return null===this._bounds&&(this._bounds=this.computeBounds()),this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){if(this._childBoundables=new dt,this._bounds=null,this._level=null,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._level=t}}}]),e}(),an={reverseOrder:function(){return{compare:function(t,e){return e.compareTo(t)}}},min:function(t){return an.sort(t),t.get(0)},sort:function(t,e){var n=t.toArray();e?At.sort(n,e):At.sort(n);for(var r=t.iterator(),i=0,o=n.length;ie.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,!1,t,n),null):(this.expand(this._boundable2,this._boundable1,!0,t,n),null);if(r)return this.expand(this._boundable1,this._boundable2,!1,t,n),null;if(i)return this.expand(this._boundable2,this._boundable1,!0,t,n),null;throw new x("neither boundable is composite")}},{key:"isLeaves",value:function(){return!(e.isComposite(this._boundable1)||e.isComposite(this._boundable2))}},{key:"compareTo",value:function(t){var e=t;return this._distancee._distance?1:0}},{key:"expand",value:function(t,n,r,i,o){for(var s=t.getChildBoundables().iterator();s.hasNext();){var a=s.next(),u=null;(u=r?new e(n,a,this._itemDistance):new e(a,n,this._itemDistance)).getDistance()-2),r.getLevel()===n)return i.add(r),null;for(var o=r.getChildBoundables().iterator();o.hasNext();){var s=o.next();s instanceof sn?this.boundablesAtLevel(n,s,i):(V.isTrue(s instanceof nn),-1===n&&i.add(s))}return null}}},{key:"query",value:function(){if(1===arguments.length){var t=arguments[0];this.build();var e=new dt;return this.isEmpty()||this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.queryInternal(t,this._root,e),e}if(2===arguments.length){var n=arguments[0],r=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),n)&&this.queryInternal(n,this._root,r)}}},{key:"build",value:function(){if(this._built)return null;this._root=this._itemBoundables.isEmpty()?this.createNode(0):this.createHigherLevels(this._itemBoundables,-1),this._itemBoundables=null,this._built=!0}},{key:"getRoot",value:function(){return this.build(),this._root}},{key:"remove",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];return this.build(),!!this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.remove(t,this._root,e)}if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],o=this.removeItem(r,i);if(o)return!0;for(var s=null,a=r.getChildBoundables().iterator();a.hasNext();){var u=a.next();if(this.getIntersectsOp().intersects(u.getBounds(),n)&&u instanceof sn&&(o=this.remove(n,u,i))){s=u;break}}return null!==s&&s.getChildBoundables().isEmpty()&&r.getChildBoundables().remove(s),o}}},{key:"createHigherLevels",value:function(t,e){V.isTrue(!t.isEmpty());var n=this.createParentBoundables(t,e+1);return 1===n.size()?n.get(0):this.createHigherLevels(n,e+1)}},{key:"depth",value:function(){if(0===arguments.length)return this.isEmpty()?0:(this.build(),this.depth(this._root));if(1===arguments.length){for(var t=0,e=arguments[0].getChildBoundables().iterator();e.hasNext();){var n=e.next();if(n instanceof sn){var r=this.depth(n);r>t&&(t=r)}}return t+1}}},{key:"createParentBoundables",value:function(t,e){V.isTrue(!t.isEmpty());var n=new dt;n.add(this.createNode(e));var r=new dt(t);an.sort(r,this.getComparator());for(var i=r.iterator();i.hasNext();){var o=i.next();this.lastNode(n).getChildBoundables().size()===this.getNodeCapacity()&&n.add(this.createNode(e)),this.lastNode(n).addChildBoundable(o)}return n}},{key:"isEmpty",value:function(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){if(this._root=null,this._built=!1,this._itemBoundables=new dt,this._nodeCapacity=null,0===arguments.length)e.constructor_.call(this,e.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];V.isTrue(t>1,"Node capacity must be greater than 1"),this._nodeCapacity=t}}},{key:"compareDoubles",value:function(t,e){return t>e?1:t0);for(var n=new dt,r=0;r=0;){var u=o.poll(),l=u.getDistance();if(l>=i)break;u.isLeaves()?a.size()l&&(a.poll(),a.add(u)),i=a.peek().getDistance()):u.expandToQueue(o,i)}return s.getItems(a)}}},{key:"createNode",value:function(t){return new pn(t)}},{key:"size",value:function(){return 0===arguments.length?f(i(s.prototype),"size",this).call(this):f(i(s.prototype),"size",this).apply(this,arguments)}},{key:"insert",value:function(){if(!(2===arguments.length&&arguments[1]instanceof Object&&arguments[0]instanceof X))return f(i(s.prototype),"insert",this).apply(this,arguments);var t=arguments[0],e=arguments[1];if(t.isNull())return null;f(i(s.prototype),"insert",this).call(this,t,e)}},{key:"getIntersectsOp",value:function(){return s.intersectsOp}},{key:"verticalSlices",value:function(t,e){for(var n=Math.trunc(Math.ceil(t.size()/e)),r=new Array(e).fill(null),i=t.iterator(),o=0;o0;){var s=o.poll(),a=s.getDistance();if(a>=r)break;s.isLeaves()?(r=a,i=s):s.expandToQueue(o,r)}return null===i?null:[i.getBoundable(0).getItem(),i.getBoundable(1).getItem()]}}else{if(2===arguments.length){var u=arguments[0],l=arguments[1];if(this.isEmpty()||u.isEmpty())return null;var h=new ln(this.getRoot(),u.getRoot(),l);return this.nearestNeighbour(h)}if(3===arguments.length){var c=arguments[2],f=new nn(arguments[0],arguments[1]),g=new ln(this.getRoot(),f,c);return this.nearestNeighbour(g)[0]}if(4===arguments.length){var p=arguments[2],v=arguments[3],d=new nn(arguments[0],arguments[1]),y=new ln(this.getRoot(),d,p);return this.nearestNeighbourK(y,v)}}}},{key:"isWithinDistance",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1],n=A.POSITIVE_INFINITY,r=new rn;for(r.add(t);!r.isEmpty();){var i=r.poll(),o=i.getDistance();if(o>e)return!1;if(i.maximumDistance()<=e)return!0;if(i.isLeaves()){if((n=o)<=e)return!0}else i.expandToQueue(r,n)}return!1}if(3===arguments.length){var s=arguments[0],a=arguments[1],u=arguments[2],l=new ln(this.getRoot(),s.getRoot(),a);return this.isWithinDistance(l,u)}}},{key:"interfaces_",get:function(){return[on,w]}}],[{key:"constructor_",value:function(){if(0===arguments.length)s.constructor_.call(this,s.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];cn.constructor_.call(this,t)}}},{key:"centreX",value:function(t){return s.avg(t.getMinX(),t.getMaxX())}},{key:"avg",value:function(t,e){return(t+e)/2}},{key:"getItems",value:function(t){for(var e=new Array(t.size()).fill(null),n=0;!t.isEmpty();){var r=t.poll();e[n]=r.getBoundable(0).getItem(),n++}return e}},{key:"centreY",value:function(t){return s.avg(t.getMinY(),t.getMaxY())}}]),s}(cn),pn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"computeBounds",value:function(){for(var t=null,e=this.getChildBoundables().iterator();e.hasNext();){var n=e.next();null===t?t=new X(n.getBounds()):t.expandToInclude(n.getBounds())}return t}}],[{key:"constructor_",value:function(){var t=arguments[0];sn.constructor_.call(this,t)}}]),o}(sn);gn.STRtreeNode=pn,gn.xComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreX(t.getBounds()),gn.centreX(e.getBounds()))}}]),e}()),gn.yComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreY(t.getBounds()),gn.centreY(e.getBounds()))}}]),e}()),gn.intersectsOp=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[IntersectsOp]}},{key:"intersects",value:function(t,e){return t.intersects(e)}}]),e}()),gn.DEFAULT_NODE_CAPACITY=10;var vn=function(){function e(){t(this,e)}return n(e,null,[{key:"relativeSign",value:function(t,e){return te?1:0}},{key:"compare",value:function(t,n,r){if(n.equals2D(r))return 0;var i=e.relativeSign(n.x,r.x),o=e.relativeSign(n.y,r.y);switch(t){case 0:return e.compareValue(i,o);case 1:return e.compareValue(o,i);case 2:return e.compareValue(o,-i);case 3:return e.compareValue(-i,o);case 4:return e.compareValue(-i,-o);case 5:return e.compareValue(-o,-i);case 6:return e.compareValue(-o,i);case 7:return e.compareValue(i,-o)}return V.shouldNeverReachHere("invalid octant value"),0}},{key:"compareValue",value:function(t,e){return t<0?-1:t>0?1:e<0?-1:e>0?1:0}}]),e}(),dn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this.coord}},{key:"print",value:function(t){t.print(this.coord),t.print(" seg # = "+this.segmentIndex)}},{key:"compareTo",value:function(t){var e=t;return this.segmentIndexe.segmentIndex?1:this.coord.equals2D(e.coord)?0:this._isInterior?e._isInterior?vn.compare(this._segmentOctant,this.coord,e.coord):1:-1}},{key:"isEndPoint",value:function(t){return 0===this.segmentIndex&&!this._isInterior||this.segmentIndex===t}},{key:"toString",value:function(){return this.segmentIndex+":"+this.coord.toString()}},{key:"isInterior",value:function(){return this._isInterior}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;var t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this._segString=t,this.coord=new z(e),this.segmentIndex=n,this._segmentOctant=r,this._isInterior=!e.equals2D(t.getCoordinate(n))}}]),e}(),yn=function(){function e(){t(this,e)}return n(e,[{key:"hasNext",value:function(){}},{key:"next",value:function(){}},{key:"remove",value:function(){}}]),e}(),mn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getSplitCoordinates",value:function(){var t=new Ht;this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next();this.addEdgeCoordinates(n,r,t),n=r}return t.toCoordinateArray()}},{key:"addCollapsedNodes",value:function(){var t=new dt;this.findCollapsesFromInsertedNodes(t),this.findCollapsesFromExistingVertices(t);for(var e=t.iterator();e.hasNext();){var n=e.next().intValue();this.add(this._edge.getCoordinate(n),n)}}},{key:"createSplitEdgePts",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2;if(2===n)return[new z(t.coord),new z(e.coord)];var r=this._edge.getCoordinate(e.segmentIndex),i=e.isInterior()||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this._edge.getCoordinate(a);return i&&(o[s]=new z(e.coord)),o}},{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"findCollapsesFromExistingVertices",value:function(t){for(var e=0;e=0?n>=0?r>=i?0:1:r>=i?7:6:n>=0?r>=i?3:2:r>=i?4:5}if(arguments[0]instanceof z&&arguments[1]instanceof z){var o=arguments[0],s=arguments[1],a=s.x-o.x,u=s.y-o.y;if(0===a&&0===u)throw new x("Cannot compute the octant for two identical points "+o);return e.octant(a,u)}}}]),e}(),xn=function(){function e(){t(this,e)}return n(e,[{key:"getCoordinates",value:function(){}},{key:"size",value:function(){}},{key:"getCoordinate",value:function(t){}},{key:"isClosed",value:function(){}},{key:"setData",value:function(t){}},{key:"getData",value:function(){}}]),e}(),En=function(){function e(){t(this,e)}return n(e,[{key:"addIntersection",value:function(t,e){}},{key:"interfaces_",get:function(){return[xn]}}]),e}(),kn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinates",value:function(){return this._pts}},{key:"size",value:function(){return this._pts.length}},{key:"getCoordinate",value:function(t){return this._pts[t]}},{key:"isClosed",value:function(){return this._pts[0].equals(this._pts[this._pts.length-1])}},{key:"getSegmentOctant",value:function(t){return t===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(t),this.getCoordinate(t+1))}},{key:"setData",value:function(t){this._data=t}},{key:"safeOctant",value:function(t,e){return t.equals2D(e)?0:_n.octant(t,e)}},{key:"getData",value:function(){return this._data}},{key:"addIntersection",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];this.addIntersectionNode(t,e)}else if(4===arguments.length){var n=arguments[1],r=arguments[3],i=new z(arguments[0].getIntersection(r));this.addIntersection(i,n)}}},{key:"toString",value:function(){return Le.toLineString(new $t(this._pts))}},{key:"getNodeList",value:function(){return this._nodeList}},{key:"addIntersectionNode",value:function(t,e){var n=e,r=n+1;if(r=0&&r>=0||n<=0&&r<=0?Math.max(n,r):0}if(arguments[0]instanceof z){var i=arguments[0];return ft.index(this.p0,this.p1,i)}}},{key:"toGeometry",value:function(t){return t.createLineString([this.p0,this.p1])}},{key:"isVertical",value:function(){return this.p0.x===this.p1.x}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.p0.equals(n.p0)&&this.p1.equals(n.p1)}},{key:"intersection",value:function(t){var e=new Ce;return e.computeIntersection(this.p0,this.p1,t.p0,t.p1),e.hasIntersection()?e.getIntersection(0):null}},{key:"project",value:function(){if(arguments[0]instanceof z){var t=arguments[0];if(t.equals(this.p0)||t.equals(this.p1))return new z(t);var n=this.projectionFactor(t),r=new z;return r.x=this.p0.x+n*(this.p1.x-this.p0.x),r.y=this.p0.y+n*(this.p1.y-this.p0.y),r}if(arguments[0]instanceof e){var i=arguments[0],o=this.projectionFactor(i.p0),s=this.projectionFactor(i.p1);if(o>=1&&s>=1)return null;if(o<=0&&s<=0)return null;var a=this.project(i.p0);o<0&&(a=this.p0),o>1&&(a=this.p1);var u=this.project(i.p1);return s<0&&(u=this.p0),s>1&&(u=this.p1),new e(a,u)}}},{key:"normalize",value:function(){this.p1.compareTo(this.p0)<0&&this.reverse()}},{key:"angle",value:function(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)}},{key:"getCoordinate",value:function(t){return 0===t?this.p0:this.p1}},{key:"distancePerpendicular",value:function(t){return kt.pointToLinePerpendicular(t,this.p0,this.p1)}},{key:"minY",value:function(){return Math.min(this.p0.y,this.p1.y)}},{key:"midPoint",value:function(){return e.midPoint(this.p0,this.p1)}},{key:"projectionFactor",value:function(t){if(t.equals(this.p0))return 0;if(t.equals(this.p1))return 1;var e=this.p1.x-this.p0.x,n=this.p1.y-this.p0.y,r=e*e+n*n;return r<=0?A.NaN:((t.x-this.p0.x)*e+(t.y-this.p0.y)*n)/r}},{key:"closestPoints",value:function(t){var e=this.intersection(t);if(null!==e)return[e,e];var n=new Array(2).fill(null),r=A.MAX_VALUE,i=null,o=this.closestPoint(t.p0);r=o.distance(t.p0),n[0]=o,n[1]=t.p0;var s=this.closestPoint(t.p1);(i=s.distance(t.p1))0&&e<1?this.project(t):this.p0.distance(t)1||A.isNaN(e))&&(e=1),e}},{key:"toString",value:function(){return"LINESTRING( "+this.p0.x+" "+this.p0.y+", "+this.p1.x+" "+this.p1.y+")"}},{key:"isHorizontal",value:function(){return this.p0.y===this.p1.y}},{key:"reflect",value:function(t){var e=this.p1.getY()-this.p0.getY(),n=this.p0.getX()-this.p1.getX(),r=this.p0.getY()*(this.p1.getX()-this.p0.getX())-this.p0.getX()*(this.p1.getY()-this.p0.getY()),i=e*e+n*n,o=e*e-n*n,s=t.getX(),a=t.getY();return new z((-o*s-2*e*n*a-2*e*r)/i,(o*a-2*e*n*s-2*n*r)/i)}},{key:"distance",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return kt.segmentToSegment(this.p0,this.p1,t.p0,t.p1)}if(arguments[0]instanceof z){var n=arguments[0];return kt.pointToSegment(n,this.p0,this.p1)}}},{key:"pointAlong",value:function(t){var e=new z;return e.x=this.p0.x+t*(this.p1.x-this.p0.x),e.y=this.p0.y+t*(this.p1.y-this.p0.y),e}},{key:"hashCode",value:function(){var t=A.doubleToLongBits(this.p0.x);t^=31*A.doubleToLongBits(this.p0.y);var e=Math.trunc(t)^Math.trunc(t>>32),n=A.doubleToLongBits(this.p1.x);return n^=31*A.doubleToLongBits(this.p1.y),e^Math.trunc(n)^Math.trunc(n>>32)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this.p0=null,this.p1=null,0===arguments.length)e.constructor_.call(this,new z,new z);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.p0,t.p1)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.p0=n,this.p1=r}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];e.constructor_.call(this,new z(i,o),new z(s,a))}}},{key:"midPoint",value:function(t,e){return new z((t.x+e.x)/2,(t.y+e.y)/2)}}]),e}(),wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"overlap",value:function(){if(2===arguments.length);else if(4===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[3];arguments[0].getLineSegment(t,this._overlapSeg1),e.getLineSegment(n,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}}}],[{key:"constructor_",value:function(){this._overlapSeg1=new bn,this._overlapSeg2=new bn}}]),e}(),In=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLineSegment",value:function(t,e){e.p0=this._pts[t],e.p1=this._pts[t+1]}},{key:"computeSelect",value:function(t,e,n,r){var i=this._pts[e],o=this._pts[n];if(n-e==1)return r.select(this,e),null;if(!t.intersects(i,o))return null;var s=Math.trunc((e+n)/2);e=t.length-1)return t.length-1;for(var r=We.quadrant(t[n],t[n+1]),i=e+1;in.getId()&&(n.computeOverlaps(i,t),this._nOverlaps++),this._segInt.isDone())return null}}}],[{key:"constructor_",value:function(){if(this._monoChains=new dt,this._index=new gn,this._idCounter=0,this._nodedSegStrings=null,this._nOverlaps=0,0===arguments.length);else if(1===arguments.length){var t=arguments[0];Mn.constructor_.call(this,t)}}}]),o}(Mn),Pn=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"overlap",value:function(){if(4!==arguments.length)return f(i(s.prototype),"overlap",this).apply(this,arguments);var t=arguments[1],e=arguments[2],n=arguments[3],r=arguments[0].getContext(),o=e.getContext();this._si.processIntersections(r,t,o,n)}}],[{key:"constructor_",value:function(){this._si=null;var t=arguments[0];this._si=t}}]),s}(wn);Ln.SegmentOverlapAction=Pn;var Cn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isDeletable",value:function(t,e,n,r){var i=this._inputLine[t],o=this._inputLine[e],s=this._inputLine[n];return!!this.isConcave(i,o,s)&&!!this.isShallow(i,o,s,r)&&this.isShallowSampled(i,o,t,n,r)}},{key:"deleteShallowConcavities",value:function(){for(var t=1,n=this.findNextNonDeletedIndex(t),r=this.findNextNonDeletedIndex(n),i=!1;r=0;r--)this.addPt(t[r])}},{key:"isRedundant",value:function(t){if(this._ptList.size()<1)return!1;var e=this._ptList.get(this._ptList.size()-1);return t.distance(e)Math.PI;)t-=e.PI_TIMES_2;for(;t<=-Math.PI;)t+=e.PI_TIMES_2;return t}},{key:"angle",value:function(){if(1===arguments.length){var t=arguments[0];return Math.atan2(t.y,t.x)}if(2===arguments.length){var e=arguments[0],n=arguments[1],r=n.x-e.x,i=n.y-e.y;return Math.atan2(i,r)}}},{key:"isAcute",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)>0}},{key:"isObtuse",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)<0}},{key:"interiorAngle",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return Math.abs(o-i)}},{key:"normalizePositive",value:function(t){if(t<0){for(;t<0;)t+=e.PI_TIMES_2;t>=e.PI_TIMES_2&&(t=0)}else{for(;t>=e.PI_TIMES_2;)t-=e.PI_TIMES_2;t<0&&(t=0)}return t}},{key:"angleBetween",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return e.diff(i,o)}},{key:"diff",value:function(t,e){var n=null;return(n=tMath.PI&&(n=2*Math.PI-n),n}},{key:"toRadians",value:function(t){return t*Math.PI/180}},{key:"getTurn",value:function(t,n){var r=Math.sin(n-t);return r>0?e.COUNTERCLOCKWISE:r<0?e.CLOCKWISE:e.NONE}},{key:"angleBetweenOriented",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r)-i;return o<=-Math.PI?o+e.PI_TIMES_2:o>Math.PI?o-e.PI_TIMES_2:o}}]),e}();On.PI_TIMES_2=2*Math.PI,On.PI_OVER_2=Math.PI/2,On.PI_OVER_4=Math.PI/4,On.COUNTERCLOCKWISE=ft.COUNTERCLOCKWISE,On.CLOCKWISE=ft.CLOCKWISE,On.NONE=ft.COLLINEAR;var Rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addNextSegment",value:function(t,e){if(this._s0=this._s1,this._s1=this._s2,this._s2=t,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;var n=ft.index(this._s0,this._s1,this._s2),r=n===ft.CLOCKWISE&&this._side===tt.LEFT||n===ft.COUNTERCLOCKWISE&&this._side===tt.RIGHT;0===n?this.addCollinear(e):r?this.addOutsideTurn(n,e):this.addInsideTurn(n,e)}},{key:"addLineEndCap",value:function(t,e){var n=new bn(t,e),r=new bn;this.computeOffsetSegment(n,tt.LEFT,this._distance,r);var i=new bn;this.computeOffsetSegment(n,tt.RIGHT,this._distance,i);var o=e.x-t.x,s=e.y-t.y,a=Math.atan2(s,o);switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:this._segList.addPt(r.p1),this.addDirectedFillet(e,a+Math.PI/2,a-Math.PI/2,ft.CLOCKWISE,this._distance),this._segList.addPt(i.p1);break;case y.CAP_FLAT:this._segList.addPt(r.p1),this._segList.addPt(i.p1);break;case y.CAP_SQUARE:var u=new z;u.x=Math.abs(this._distance)*Math.cos(a),u.y=Math.abs(this._distance)*Math.sin(a);var l=new z(r.p1.x+u.x,r.p1.y+u.y),h=new z(i.p1.x+u.x,i.p1.y+u.y);this._segList.addPt(l),this._segList.addPt(h)}}},{key:"getCoordinates",value:function(){return this._segList.getCoordinates()}},{key:"addMitreJoin",value:function(t,e,n,r){var i=_t.intersection(e.p0,e.p1,n.p0,n.p1);if(null!==i&&(r<=0?1:i.distance(t)/Math.abs(r))<=this._bufParams.getMitreLimit())return this._segList.addPt(i),null;this.addLimitedMitreJoin(e,n,r,this._bufParams.getMitreLimit())}},{key:"addOutsideTurn",value:function(t,n){if(this._offset0.p1.distance(this._offset1.p0)=h&&(a-=2*Math.PI),this._segList.addPt(e),this.addDirectedFillet(t,a,h,r,i),this._segList.addPt(n)}},{key:"addLastSegment",value:function(){this._segList.addPt(this._offset1.p1)}},{key:"initSideSegments",value:function(t,e,n){this._s1=t,this._s2=e,this._side=n,this._seg1.setCoordinates(t,e),this.computeOffsetSegment(this._seg1,n,this._distance,this._offset1)}},{key:"addLimitedMitreJoin",value:function(t,e,n,r){var i=this._seg0.p1,o=On.angle(i,this._seg0.p0),s=On.angleBetweenOriented(this._seg0.p0,i,this._seg1.p1)/2,a=On.normalize(o+s),u=On.normalize(a+Math.PI),l=r*n,h=n-l*Math.abs(Math.sin(s)),c=i.x+l*Math.cos(u),f=i.y+l*Math.sin(u),g=new z(c,f),p=new bn(i,g),v=p.pointAlongOffset(1,h),d=p.pointAlongOffset(1,-h);this._side===tt.LEFT?(this._segList.addPt(v),this._segList.addPt(d)):(this._segList.addPt(d),this._segList.addPt(v))}},{key:"addDirectedFillet",value:function(t,e,n,r,i){var o=r===ft.CLOCKWISE?-1:1,s=Math.abs(e-n),a=Math.trunc(s/this._filletAngleQuantum+.5);if(a<1)return null;for(var u=s/a,l=new z,h=0;h0){var r=new z((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(r);var i=new z((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(i)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}}},{key:"createCircle",value:function(t){var e=new z(t.x+this._distance,t.y);this._segList.addPt(e),this.addDirectedFillet(t,0,2*Math.PI,-1,this._distance),this._segList.closeRing()}},{key:"addBevelJoin",value:function(t,e){this._segList.addPt(t.p1),this._segList.addPt(e.p0)}},{key:"init",value:function(t){this._distance=t,this._maxCurveSegmentError=t*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new Tn,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(t*e.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)}},{key:"addCollinear",value:function(t){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2),this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===y.JOIN_BEVEL||this._bufParams.getJoinStyle()===y.JOIN_MITRE?(t&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,ft.CLOCKWISE,this._distance))}},{key:"closeRing",value:function(){this._segList.closeRing()}},{key:"hasNarrowConcaveAngle",value:function(){return this._hasNarrowConcaveAngle}}],[{key:"constructor_",value:function(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new bn,this._seg1=new bn,this._offset0=new bn,this._offset1=new bn,this._side=0,this._hasNarrowConcaveAngle=!1;var t=arguments[0],n=arguments[1],r=arguments[2];this._precisionModel=t,this._bufParams=n,this._li=new Ce,this._filletAngleQuantum=Math.PI/2/n.getQuadrantSegments(),n.getQuadrantSegments()>=8&&n.getJoinStyle()===y.JOIN_ROUND&&(this._closingSegLengthFactor=e.MAX_CLOSING_SEG_LEN_FACTOR),this.init(r)}}]),e}();Rn.OFFSET_SEGMENT_SEPARATION_FACTOR=.001,Rn.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR=.001,Rn.CURVE_VERTEX_SNAP_DISTANCE_FACTOR=1e-6,Rn.MAX_CLOSING_SEG_LEN_FACTOR=80;var An=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getOffsetCurve",value:function(t,e){if(this._distance=e,0===e)return null;var n=e<0,r=Math.abs(e),i=this.getSegGen(r);t.length<=1?this.computePointCurve(t[0],i):this.computeOffsetCurve(t,n,i);var o=i.getCoordinates();return n&&Wt.reverse(o),o}},{key:"computeSingleSidedBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){n.addSegments(t,!0);var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{n.addSegments(t,!1);var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment(),n.closeRing()}},{key:"computeRingBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);e===tt.RIGHT&&(r=-r);var i=Cn.simplify(t,r),o=i.length-1;n.initSideSegments(i[o-1],i[0],e);for(var s=1;s<=o;s++){var a=1!==s;n.addNextSegment(i[s],a)}n.closeRing()}},{key:"computeLineBufferCurve",value:function(t,e){var n=this.simplifyTolerance(this._distance),r=Cn.simplify(t,n),i=r.length-1;e.initSideSegments(r[0],r[1],tt.LEFT);for(var o=2;o<=i;o++)e.addNextSegment(r[o],!0);e.addLastSegment(),e.addLineEndCap(r[i-1],r[i]);var s=Cn.simplify(t,-n),a=s.length-1;e.initSideSegments(s[a],s[a-1],tt.LEFT);for(var u=a-2;u>=0;u--)e.addNextSegment(s[u],!0);e.addLastSegment(),e.addLineEndCap(s[1],s[0]),e.closeRing()}},{key:"computePointCurve",value:function(t,e){switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:e.createCircle(t);break;case y.CAP_SQUARE:e.createSquare(t)}}},{key:"getLineCurve",value:function(t,e){if(this._distance=e,this.isLineOffsetEmpty(e))return null;var n=Math.abs(e),r=this.getSegGen(n);if(t.length<=1)this.computePointCurve(t[0],r);else if(this._bufParams.isSingleSided()){var i=e<0;this.computeSingleSidedBufferCurve(t,i,r)}else this.computeLineBufferCurve(t,r);return r.getCoordinates()}},{key:"getBufferParameters",value:function(){return this._bufParams}},{key:"simplifyTolerance",value:function(t){return t*this._bufParams.getSimplifyFactor()}},{key:"getRingCurve",value:function(t,n,r){if(this._distance=r,t.length<=2)return this.getLineCurve(t,r);if(0===r)return e.copyCoordinates(t);var i=this.getSegGen(r);return this.computeRingBufferCurve(t,n,i),i.getCoordinates()}},{key:"computeOffsetCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment()}},{key:"isLineOffsetEmpty",value:function(t){return 0===t||t<0&&!this._bufParams.isSingleSided()}},{key:"getSegGen",value:function(t){return new Rn(this._precisionModel,this._bufParams,t)}}],[{key:"constructor_",value:function(){this._distance=0,this._precisionModel=null,this._bufParams=null;var t=arguments[0],e=arguments[1];this._precisionModel=t,this._bufParams=e}},{key:"copyCoordinates",value:function(t){for(var e=new Array(t.length).fill(null),n=0;ni.getMaxY()||this.findStabbedSegments(t,r.getDirectedEdges(),e)}return e}if(3===arguments.length)if(ot(arguments[2],rt)&&arguments[0]instanceof z&&arguments[1]instanceof Ke){for(var o=arguments[0],s=arguments[1],a=arguments[2],u=s.getEdge().getCoordinates(),l=0;lthis._seg.p1.y&&this._seg.reverse(),!(Math.max(this._seg.p0.x,this._seg.p1.x)this._seg.p1.y||ft.index(this._seg.p0,this._seg.p1,o)===ft.RIGHT)){var h=s.getDepth(tt.LEFT);this._seg.p0.equals(u[l])||(h=s.getDepth(tt.RIGHT));var c=new Fn(this._seg,h);a.add(c)}}else if(ot(arguments[2],rt)&&arguments[0]instanceof z&&ot(arguments[1],rt))for(var f=arguments[0],g=arguments[2],p=arguments[1].iterator();p.hasNext();){var v=p.next();v.isForward()&&this.findStabbedSegments(f,v,g)}}},{key:"getDepth",value:function(t){var e=this.findStabbedSegments(t);return 0===e.size()?0:an.min(e)._leftDepth}}],[{key:"constructor_",value:function(){this._subgraphs=null,this._seg=new bn;var t=arguments[0];this._subgraphs=t}}]),e}(),Fn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var e=t;if(this._upwardSeg.minX()>=e._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=e._upwardSeg.minX())return-1;var n=this._upwardSeg.orientationIndex(e._upwardSeg);return 0!==n||0!=(n=-1*e._upwardSeg.orientationIndex(this._upwardSeg))?n:this._upwardSeg.compareTo(e._upwardSeg)}},{key:"compareX",value:function(t,e){var n=t.p0.compareTo(e.p0);return 0!==n?n:t.p1.compareTo(e.p1)}},{key:"toString",value:function(){return this._upwardSeg.toString()}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._upwardSeg=null,this._leftDepth=null;var t=arguments[0],e=arguments[1];this._upwardSeg=new bn(t),this._leftDepth=e}}]),e}();Dn.DepthSegment=Fn;var qn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){_.constructor_.call(this,"Projective point not representable on the Cartesian plane.")}}]),o}(_),Vn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getY",value:function(){var t=this.y/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getX",value:function(){var t=this.x/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getCoordinate",value:function(){var t=new z;return t.x=this.getX(),t.y=this.getY(),t}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.w=null,0===arguments.length)this.x=0,this.y=0,this.w=1;else if(1===arguments.length){var t=arguments[0];this.x=t.x,this.y=t.y,this.w=1}else if(2===arguments.length){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var n=arguments[0],r=arguments[1];this.x=n,this.y=r,this.w=1}else if(arguments[0]instanceof e&&arguments[1]instanceof e){var i=arguments[0],o=arguments[1];this.x=i.y*o.w-o.y*i.w,this.y=o.x*i.w-i.x*o.w,this.w=i.x*o.y-o.x*i.y}else if(arguments[0]instanceof z&&arguments[1]instanceof z){var s=arguments[0],a=arguments[1];this.x=s.y-a.y,this.y=a.x-s.x,this.w=s.x*a.y-a.x*s.y}}else if(3===arguments.length){var u=arguments[0],l=arguments[1],h=arguments[2];this.x=u,this.y=l,this.w=h}else if(4===arguments.length){var c=arguments[0],f=arguments[1],g=arguments[2],p=arguments[3],v=c.y-f.y,d=f.x-c.x,y=c.x*f.y-f.x*c.y,m=g.y-p.y,_=p.x-g.x,x=g.x*p.y-p.x*g.y;this.x=d*x-_*y,this.y=m*y-v*x,this.w=v*_-m*d}}}]),e}(),Gn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"area",value:function(){return e.area(this.p0,this.p1,this.p2)}},{key:"signedArea",value:function(){return e.signedArea(this.p0,this.p1,this.p2)}},{key:"interpolateZ",value:function(t){if(null===t)throw new x("Supplied point is null.");return e.interpolateZ(t,this.p0,this.p1,this.p2)}},{key:"longestSideLength",value:function(){return e.longestSideLength(this.p0,this.p1,this.p2)}},{key:"isAcute",value:function(){return e.isAcute(this.p0,this.p1,this.p2)}},{key:"circumcentre",value:function(){return e.circumcentre(this.p0,this.p1,this.p2)}},{key:"area3D",value:function(){return e.area3D(this.p0,this.p1,this.p2)}},{key:"centroid",value:function(){return e.centroid(this.p0,this.p1,this.p2)}},{key:"inCentre",value:function(){return e.inCentre(this.p0,this.p1,this.p2)}}],[{key:"constructor_",value:function(){this.p0=null,this.p1=null,this.p2=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.p0=t,this.p1=e,this.p2=n}},{key:"area",value:function(t,e,n){return Math.abs(((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2)}},{key:"signedArea",value:function(t,e,n){return((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2}},{key:"det",value:function(t,e,n,r){return t*r-e*n}},{key:"interpolateZ",value:function(t,e,n,r){var i=e.x,o=e.y,s=n.x-i,a=r.x-i,u=n.y-o,l=r.y-o,h=s*l-a*u,c=t.x-i,f=t.y-o,g=(l*c-a*f)/h,p=(-u*c+s*f)/h;return e.getZ()+g*(n.getZ()-e.getZ())+p*(r.getZ()-e.getZ())}},{key:"longestSideLength",value:function(t,e,n){var r=t.distance(e),i=e.distance(n),o=n.distance(t),s=r;return i>s&&(s=i),o>s&&(s=o),s}},{key:"circumcentreDD",value:function(t,e,n){var r=lt.valueOf(t.x).subtract(n.x),i=lt.valueOf(t.y).subtract(n.y),o=lt.valueOf(e.x).subtract(n.x),s=lt.valueOf(e.y).subtract(n.y),a=lt.determinant(r,i,o,s).multiply(2),u=r.sqr().add(i.sqr()),l=o.sqr().add(s.sqr()),h=lt.determinant(i,u,s,l),c=lt.determinant(r,u,o,l),f=lt.valueOf(n.x).subtract(h.divide(a)).doubleValue(),g=lt.valueOf(n.y).add(c.divide(a)).doubleValue();return new z(f,g)}},{key:"isAcute",value:function(t,e,n){return!!On.isAcute(t,e,n)&&!!On.isAcute(e,n,t)&&!!On.isAcute(n,t,e)}},{key:"circumcentre",value:function(t,n,r){var i=r.x,o=r.y,s=t.x-i,a=t.y-o,u=n.x-i,l=n.y-o,h=2*e.det(s,a,u,l),c=e.det(a,s*s+a*a,l,u*u+l*l),f=e.det(s,s*s+a*a,u,u*u+l*l);return new z(i-c/h,o+f/h)}},{key:"perpendicularBisector",value:function(t,e){var n=e.x-t.x,r=e.y-t.y,i=new Vn(t.x+n/2,t.y+r/2,1),o=new Vn(t.x-r+n/2,t.y+n+r/2,1);return new Vn(i,o)}},{key:"angleBisector",value:function(t,e,n){var r=e.distance(t),i=r/(r+e.distance(n)),o=n.x-t.x,s=n.y-t.y;return new z(t.x+i*o,t.y+i*s)}},{key:"area3D",value:function(t,e,n){var r=e.x-t.x,i=e.y-t.y,o=e.getZ()-t.getZ(),s=n.x-t.x,a=n.y-t.y,u=n.getZ()-t.getZ(),l=i*u-o*a,h=o*s-r*u,c=r*a-i*s,f=l*l+h*h+c*c;return Math.sqrt(f)/2}},{key:"centroid",value:function(t,e,n){var r=(t.x+e.x+n.x)/3,i=(t.y+e.y+n.y)/3;return new z(r,i)}},{key:"inCentre",value:function(t,e,n){var r=e.distance(n),i=t.distance(n),o=t.distance(e),s=r+i+o,a=(r*t.x+i*e.x+o*n.x)/s,u=(r*t.y+i*e.y+o*n.y)/s;return new z(a,u)}}]),e}(),Bn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addRingSide",value:function(t,e,n,r,i){if(0===e&&t.length=zt.MINIMUM_VALID_SIZE&&ft.isCCW(t)&&(o=i,s=r,n=tt.opposite(n));var a=this._curveBuilder.getRingCurve(t,n,e);this.addCurve(a,o,s)}},{key:"addRingBothSides",value:function(t,e){this.addRingSide(t,e,tt.LEFT,Z.EXTERIOR,Z.INTERIOR),this.addRingSide(t,e,tt.RIGHT,Z.INTERIOR,Z.EXTERIOR)}},{key:"addPoint",value:function(t){if(this._distance<=0)return null;var e=t.getCoordinates(),n=this._curveBuilder.getLineCurve(e,this._distance);this.addCurve(n,Z.EXTERIOR,Z.INTERIOR)}},{key:"addPolygon",value:function(t){var e=this._distance,n=tt.LEFT;this._distance<0&&(e=-this._distance,n=tt.RIGHT);var r=t.getExteriorRing(),i=Wt.removeRepeatedPoints(r.getCoordinates());if(this._distance<0&&this.isErodedCompletely(r,this._distance))return null;if(this._distance<=0&&i.length<3)return null;this.addRingSide(i,e,n,Z.EXTERIOR,Z.INTERIOR);for(var o=0;o0&&this.isErodedCompletely(s,-this._distance)||this.addRingSide(a,e,tt.opposite(n),Z.INTERIOR,Z.EXTERIOR)}}},{key:"isTriangleErodedCompletely",value:function(t,e){var n=new Gn(t[0],t[1],t[2]),r=n.inCentre();return kt.pointToSegment(r,n.p0,n.p1)i}},{key:"addCollection",value:function(t){for(var e=0;e=this._max)throw new W;var t=this._parent.getGeometryN(this._index++);return t instanceof Bt?(this._subcollectionIterator=new e(t),this._subcollectionIterator.next()):t}},{key:"remove",value:function(){throw new J(this.getClass().getName())}},{key:"hasNext",value:function(){if(this._atStart)return!0;if(null!==this._subcollectionIterator){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)}},{key:"interfaces_",get:function(){return[yn]}}],[{key:"constructor_",value:function(){this._parent=null,this._atStart=null,this._max=null,this._index=null,this._subcollectionIterator=null;var t=arguments[0];this._parent=t,this._atStart=!0,this._index=0,this._max=t.getNumGeometries()}},{key:"isAtomic",value:function(t){return!(t instanceof Bt)}}]),e}(),jn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"locate",value:function(t){return e.locate(t,this._geom)}},{key:"interfaces_",get:function(){return[Yn]}}],[{key:"constructor_",value:function(){this._geom=null;var t=arguments[0];this._geom=t}},{key:"locatePointInPolygon",value:function(t,n){if(n.isEmpty())return Z.EXTERIOR;var r=n.getExteriorRing(),i=e.locatePointInRing(t,r);if(i!==Z.INTERIOR)return i;for(var o=0;o=0;n--){var r=this._edgeList.get(n),i=r.getSym();null===e&&(e=i),null!==t&&i.setNext(t),t=r}e.setNext(t)}},{key:"computeDepths",value:function(){if(1===arguments.length){var t=arguments[0],e=this.findIndex(t),n=t.getDepth(tt.LEFT),r=t.getDepth(tt.RIGHT),i=this.computeDepths(e+1,this._edgeList.size(),n);if(this.computeDepths(0,e,i)!==r)throw new pt("depth mismatch at "+t.getCoordinate())}else if(3===arguments.length){for(var o=arguments[1],s=arguments[2],a=arguments[0];a=0;i--){var o=this._resultAreaEdgeList.get(i),s=o.getSym();switch(null===e&&o.getEdgeRing()===t&&(e=o),r){case this._SCANNING_FOR_INCOMING:if(s.getEdgeRing()!==t)continue;n=s,r=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(o.getEdgeRing()!==t)continue;n.setNextMin(o),r=this._SCANNING_FOR_INCOMING}}r===this._LINKING_TO_OUTGOING&&(V.isTrue(null!==e,"found null for first outgoing dirEdge"),V.isTrue(e.getEdgeRing()===t,"unable to link last incoming dirEdge"),n.setNextMin(e))}},{key:"getOutgoingDegree",value:function(){if(0===arguments.length){for(var t=0,e=this.iterator();e.hasNext();)e.next().isInResult()&&t++;return t}if(1===arguments.length){for(var n=arguments[0],r=0,i=this.iterator();i.hasNext();)i.next().getEdgeRing()===n&&r++;return r}}},{key:"getLabel",value:function(){return this._label}},{key:"findCoveredLineEdges",value:function(){for(var t=Z.NONE,e=this.iterator();e.hasNext();){var n=e.next(),r=n.getSym();if(!n.isLineEdge()){if(n.isInResult()){t=Z.INTERIOR;break}if(r.isInResult()){t=Z.EXTERIOR;break}}}if(t===Z.NONE)return null;for(var i=t,o=this.iterator();o.hasNext();){var s=o.next(),a=s.getSym();s.isLineEdge()?s.getEdge().setCovered(i===Z.INTERIOR):(s.isInResult()&&(i=Z.EXTERIOR),a.isInResult()&&(i=Z.INTERIOR))}}},{key:"computeLabelling",value:function(t){f(i(s.prototype),"computeLabelling",this).call(this,t),this._label=new Ae(Z.NONE);for(var e=this.iterator();e.hasNext();)for(var n=e.next().getEdge().getLabel(),r=0;r<2;r++){var o=n.getLocation(r);o!==Z.INTERIOR&&o!==Z.BOUNDARY||this._label.setLocation(r,Z.INTERIOR)}}}],[{key:"constructor_",value:function(){this._resultAreaEdgeList=null,this._label=null,this._SCANNING_FOR_INCOMING=1,this._LINKING_TO_OUTGOING=2}}]),s}(Xn),Zn=function(e){r(o,e);var i=c(o);function o(){return t(this,o),i.call(this)}return n(o,[{key:"createNode",value:function(t){return new Ge(t,new Un)}}]),o}(Qe),Hn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var n=t;return e.compareOriented(this._pts,this._orientation,n._pts,n._orientation)}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._pts=null,this._orientation=null;var t=arguments[0];this._pts=t,this._orientation=e.orientation(t)}},{key:"orientation",value:function(t){return 1===Wt.increasingDirection(t)}},{key:"compareOriented",value:function(t,e,n,r){for(var i=e?1:-1,o=r?1:-1,s=e?t.length:-1,a=r?n.length:-1,u=e?0:t.length-1,l=r?0:n.length-1;;){var h=t[u].compareTo(n[l]);if(0!==h)return h;var c=(u+=i)===s,f=(l+=o)===a;if(c&&!f)return-1;if(!c&&f)return 1;if(c&&f)return 0}}}]),e}(),Wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.print("MULTILINESTRING ( ");for(var e=0;e0&&t.print(","),t.print("(");for(var r=n.getCoordinates(),i=0;i0&&t.print(","),t.print(r[i].x+" "+r[i].y);t.println(")")}t.print(") ")}},{key:"addAll",value:function(t){for(var e=t.iterator();e.hasNext();)this.add(e.next())}},{key:"findEdgeIndex",value:function(t){for(var e=0;et?1:this.diste?1:0}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this.coord=null,this.segmentIndex=null,this.dist=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.coord=new z(t),this.segmentIndex=e,this.dist=n}}]),e}(),$n=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this._nodeMap.values().iterator()}},{key:"addSplitEdges",value:function(t){this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next(),i=this.createSplitEdge(n,r);t.add(i),n=r}}},{key:"addEndpoints",value:function(){var t=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[t],t,0)}},{key:"createSplitEdge",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2,r=this.edge.pts[e.segmentIndex],i=e.dist>0||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this.edge.pts[a];return i&&(o[s]=e.coord),new or(o,new Ae(this.edge._label))}},{key:"add",value:function(t,e,n){var r=new Qn(t,e,n),i=this._nodeMap.get(r);return null!==i?i:(this._nodeMap.put(r,r),r)}},{key:"isIntersection",value:function(t){for(var e=this.iterator();e.hasNext();)if(e.next().coord.equals(t))return!0;return!1}}],[{key:"constructor_",value:function(){this._nodeMap=new Ze,this.edge=null;var t=arguments[0];this.edge=t}}]),e}(),tr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isIntersects",value:function(){return!this.isDisjoint()}},{key:"isCovers",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"isCoveredBy",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"set",value:function(){if(1===arguments.length)for(var t=arguments[0],e=0;e=0&&e>=0&&this.setAtLeast(t,e,n)}},{key:"isWithin",value:function(){return e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"isTouches",value:function(t,n){return t>n?this.isTouches(n,t):(t===Mt.A&&n===Mt.A||t===Mt.L&&n===Mt.L||t===Mt.L&&n===Mt.A||t===Mt.P&&n===Mt.A||t===Mt.P&&n===Mt.L)&&this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&(e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))}},{key:"isOverlaps",value:function(t,n){return t===Mt.P&&n===Mt.P||t===Mt.A&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&1===this._matrix[Z.INTERIOR][Z.INTERIOR]&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR])}},{key:"isEquals",value:function(t,n){return t===n&&e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"toString",value:function(){for(var t=new Qt("123456789"),e=0;e<3;e++)for(var n=0;n<3;n++)t.setCharAt(3*e+n,Mt.toDimensionSymbol(this._matrix[e][n]));return t.toString()}},{key:"setAll",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this._matrix[e][n]=t}},{key:"get",value:function(t,e){return this._matrix[t][e]}},{key:"transpose",value:function(){var t=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=t,t=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=t,t=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=t,this}},{key:"matches",value:function(t){if(9!==t.length)throw new x("Should be length 9: "+t);for(var n=0;n<3;n++)for(var r=0;r<3;r++)if(!e.matches(this._matrix[n][r],t.charAt(3*n+r)))return!1;return!0}},{key:"add",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this.setAtLeast(e,n,t.get(e,n))}},{key:"isDisjoint",value:function(){return this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.INTERIOR][Z.BOUNDARY]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.BOUNDARY]===Mt.FALSE}},{key:"isCrosses",value:function(t,n){return t===Mt.P&&n===Mt.L||t===Mt.P&&n===Mt.A||t===Mt.L&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR]):t===Mt.L&&n===Mt.P||t===Mt.A&&n===Mt.P||t===Mt.A&&n===Mt.L?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&0===this._matrix[Z.INTERIOR][Z.INTERIOR]}},{key:"interfaces_",get:function(){return[b]}}],[{key:"constructor_",value:function(){if(this._matrix=null,0===arguments.length)this._matrix=Array(3).fill().map((function(){return Array(3)})),this.setAll(Mt.FALSE);else if(1===arguments.length)if("string"==typeof arguments[0]){var t=arguments[0];e.constructor_.call(this),this.set(t)}else if(arguments[0]instanceof e){var n=arguments[0];e.constructor_.call(this),this._matrix[Z.INTERIOR][Z.INTERIOR]=n._matrix[Z.INTERIOR][Z.INTERIOR],this._matrix[Z.INTERIOR][Z.BOUNDARY]=n._matrix[Z.INTERIOR][Z.BOUNDARY],this._matrix[Z.INTERIOR][Z.EXTERIOR]=n._matrix[Z.INTERIOR][Z.EXTERIOR],this._matrix[Z.BOUNDARY][Z.INTERIOR]=n._matrix[Z.BOUNDARY][Z.INTERIOR],this._matrix[Z.BOUNDARY][Z.BOUNDARY]=n._matrix[Z.BOUNDARY][Z.BOUNDARY],this._matrix[Z.BOUNDARY][Z.EXTERIOR]=n._matrix[Z.BOUNDARY][Z.EXTERIOR],this._matrix[Z.EXTERIOR][Z.INTERIOR]=n._matrix[Z.EXTERIOR][Z.INTERIOR],this._matrix[Z.EXTERIOR][Z.BOUNDARY]=n._matrix[Z.EXTERIOR][Z.BOUNDARY],this._matrix[Z.EXTERIOR][Z.EXTERIOR]=n._matrix[Z.EXTERIOR][Z.EXTERIOR]}}},{key:"matches",value:function(){if(Number.isInteger(arguments[0])&&"string"==typeof arguments[1]){var t=arguments[0],n=arguments[1];return n===Mt.SYM_DONTCARE||n===Mt.SYM_TRUE&&(t>=0||t===Mt.TRUE)||n===Mt.SYM_FALSE&&t===Mt.FALSE||n===Mt.SYM_P&&t===Mt.P||n===Mt.SYM_L&&t===Mt.L||n===Mt.SYM_A&&t===Mt.A}if("string"==typeof arguments[0]&&"string"==typeof arguments[1]){var r=arguments[1];return new e(arguments[0]).matches(r)}}},{key:"isTrue",value:function(t){return t>=0||t===Mt.TRUE}}]),e}(),er=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"size",value:function(){return this._size}},{key:"addAll",value:function(t){return null===t||0===t.length?null:(this.ensureCapacity(this._size+t.length),xt.arraycopy(t,0,this._data,this._size,t.length),void(this._size+=t.length))}},{key:"ensureCapacity",value:function(t){if(t<=this._data.length)return null;var e=Math.max(t,2*this._data.length);this._data=At.copyOf(this._data,e)}},{key:"toArray",value:function(){var t=new Array(this._size).fill(null);return xt.arraycopy(this._data,0,t,0,this._size),t}},{key:"add",value:function(t){this.ensureCapacity(this._size+1),this._data[this._size]=t,++this._size}}],[{key:"constructor_",value:function(){if(this._data=null,this._size=0,0===arguments.length)e.constructor_.call(this,10);else if(1===arguments.length){var t=arguments[0];this._data=new Array(t).fill(null)}}}]),e}(),nr=function(){function e(){t(this,e)}return n(e,[{key:"getChainStartIndices",value:function(t){var e=0,n=new er(Math.trunc(t.length/2));n.add(e);do{var r=this.findChainEnd(t,e);n.add(r),e=r}while(en?e:n}},{key:"getMinX",value:function(t){var e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return ee&&(r=1),this._depth[t][n]=r}}}},{key:"getDelta",value:function(t){return this._depth[t][tt.RIGHT]-this._depth[t][tt.LEFT]}},{key:"getLocation",value:function(t,e){return this._depth[t][e]<=0?Z.EXTERIOR:Z.INTERIOR}},{key:"toString",value:function(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}},{key:"add",value:function(){if(1===arguments.length)for(var t=arguments[0],n=0;n<2;n++)for(var r=1;r<3;r++){var i=t.getLocation(n,r);i!==Z.EXTERIOR&&i!==Z.INTERIOR||(this.isNull(n,r)?this._depth[n][r]=e.depthAtLocation(i):this._depth[n][r]+=e.depthAtLocation(i))}else if(3===arguments.length){var o=arguments[0],s=arguments[1];arguments[2]===Z.INTERIOR&&this._depth[o][s]++}}}],[{key:"constructor_",value:function(){this._depth=Array(2).fill().map((function(){return Array(3)}));for(var t=0;t<2;t++)for(var n=0;n<3;n++)this._depth[t][n]=e.NULL_VALUE}},{key:"depthAtLocation",value:function(t){return t===Z.EXTERIOR?0:t===Z.INTERIOR?1:e.NULL_VALUE}}]),e}();ir.NULL_VALUE=-1;var or=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getDepth",value:function(){return this._depth}},{key:"getCollapsedEdge",value:function(){var t=new Array(2).fill(null);return t[0]=this.pts[0],t[1]=this.pts[1],new s(t,Ae.toLineLabel(this._label))}},{key:"isIsolated",value:function(){return this._isIsolated}},{key:"getCoordinates",value:function(){return this.pts}},{key:"setIsolated",value:function(t){this._isIsolated=t}},{key:"setName",value:function(t){this._name=t}},{key:"equals",value:function(t){if(!(t instanceof s))return!1;var e=t;if(this.pts.length!==e.pts.length)return!1;for(var n=!0,r=!0,i=this.pts.length,o=0;o0?this.pts[0]:null;if(1===arguments.length){var t=arguments[0];return this.pts[t]}}},{key:"print",value:function(t){t.print("edge "+this._name+": "),t.print("LINESTRING (");for(var e=0;e0&&t.print(","),t.print(this.pts[e].x+" "+this.pts[e].y);t.print(") "+this._label+" "+this._depthDelta)}},{key:"computeIM",value:function(t){s.updateIM(this._label,t)}},{key:"isCollapsed",value:function(){return!!this._label.isArea()&&3===this.pts.length&&!!this.pts[0].equals(this.pts[2])}},{key:"isClosed",value:function(){return this.pts[0].equals(this.pts[this.pts.length-1])}},{key:"getMaximumSegmentIndex",value:function(){return this.pts.length-1}},{key:"getDepthDelta",value:function(){return this._depthDelta}},{key:"getNumPoints",value:function(){return this.pts.length}},{key:"printReverse",value:function(t){t.print("edge "+this._name+": ");for(var e=this.pts.length-1;e>=0;e--)t.print(this.pts[e]+" ");t.println("")}},{key:"getMonotoneChainEdge",value:function(){return null===this._mce&&(this._mce=new rr(this)),this._mce}},{key:"getEnvelope",value:function(){if(null===this._env){this._env=new X;for(var t=0;t0&&t.append(","),t.append(this.pts[e].x+" "+this.pts[e].y);return t.append(") "+this._label+" "+this._depthDelta),t.toString()}},{key:"isPointwiseEqual",value:function(t){if(this.pts.length!==t.pts.length)return!1;for(var e=0;er||this._maxyo;if(s)return!1;var a=this.intersectsToleranceSquare(t,e);return V.isTrue(!(s&&a),"Found bad envelope test"),a}},{key:"initCorners",value:function(t){var e=.5;this._minx=t.x-e,this._maxx=t.x+e,this._miny=t.y-e,this._maxy=t.y+e,this._corner[0]=new z(this._maxx,this._maxy),this._corner[1]=new z(this._minx,this._maxy),this._corner[2]=new z(this._minx,this._miny),this._corner[3]=new z(this._maxx,this._miny)}},{key:"intersects",value:function(t,e){return 1===this._scaleFactor?this.intersectsScaled(t,e):(this.copyScaled(t,this._p0Scaled),this.copyScaled(e,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}},{key:"scale",value:function(t){return Math.round(t*this._scaleFactor)}},{key:"getCoordinate",value:function(){return this._originalPt}},{key:"copyScaled",value:function(t,e){e.x=this.scale(t.x),e.y=this.scale(t.y)}},{key:"getSafeEnvelope",value:function(){if(null===this._safeEnv){var t=e.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new X(this._originalPt.x-t,this._originalPt.x+t,this._originalPt.y-t,this._originalPt.y+t)}return this._safeEnv}},{key:"intersectsPixelClosure",value:function(t,e){return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.hasIntersection()))))}},{key:"intersectsToleranceSquare",value:function(t,e){var n=!1,r=!1;return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.isProper()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.isProper()||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.isProper()||(this._li.hasIntersection()&&(r=!0),this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.isProper()||n&&r||t.equals(this._pt)||e.equals(this._pt)))))}},{key:"addSnappedNode",value:function(t,e){var n=t.getCoordinate(e),r=t.getCoordinate(e+1);return!!this.intersects(n,r)&&(t.addIntersection(this.getCoordinate(),e),!0)}}],[{key:"constructor_",value:function(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;var t=arguments[0],e=arguments[1],n=arguments[2];if(this._originalPt=t,this._pt=t,this._scaleFactor=e,this._li=n,e<=0)throw new x("Scale factor must be non-zero");1!==e&&(this._pt=new z(this.scale(t.x),this.scale(t.y)),this._p0Scaled=new z,this._p1Scaled=new z),this.initCorners(this._pt)}}]),e}();lr.SAFE_ENV_EXPANSION_FACTOR=.75;var hr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"select",value:function(){if(1===arguments.length);else if(2===arguments.length){var t=arguments[1];arguments[0].getLineSegment(t,this.selectedSegment),this.select(this.selectedSegment)}}}],[{key:"constructor_",value:function(){this.selectedSegment=new bn}}]),e}(),cr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"snap",value:function(){if(1===arguments.length){var e=arguments[0];return this.snap(e,null,-1)}if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=r.getSafeEnvelope(),a=new fr(r,i,o);return this._index.query(s,new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[hn]}},{key:"visitItem",value:function(t){t.select(s,a)}}]),e}())),a.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var t=arguments[0];this._index=t}}]),e}(),fr=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isNodeAdded",value:function(){return this._isNodeAdded}},{key:"select",value:function(){if(!(2===arguments.length&&Number.isInteger(arguments[1])&&arguments[0]instanceof In))return f(i(s.prototype),"select",this).apply(this,arguments);var t=arguments[1],e=arguments[0].getContext();if(this._parentEdge===e&&(t===this._hotPixelVertexIndex||t+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(e,t)}}],[{key:"constructor_",value:function(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var t=arguments[0],e=arguments[1],n=arguments[2];this._hotPixel=t,this._parentEdge=e,this._hotPixelVertexIndex=n}}]),s}(hr);cr.HotPixelSnapAction=fr;var gr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"processIntersections",value:function(t,e,n,r){if(t===n&&e===r)return null;var i=t.getCoordinates()[e],o=t.getCoordinates()[e+1],s=n.getCoordinates()[r],a=n.getCoordinates()[r+1];if(this._li.computeIntersection(i,o,s,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var u=0;u=0;t--){try{this.bufferReducedPrecision(t)}catch(t){if(!(t instanceof pt))throw t;this._saveException=t}if(null!==this._resultGeometry)return null}throw this._saveException}if(1===arguments.length){var n=arguments[0],r=e.precisionScaleFactor(this._argGeom,this._distance,n),i=new ie(r);this.bufferFixedPrecision(i)}}},{key:"computeGeometry",value:function(){if(this.bufferOriginalPrecision(),null!==this._resultGeometry)return null;var t=this._argGeom.getFactory().getPrecisionModel();t.getType()===ie.FIXED?this.bufferFixedPrecision(t):this.bufferReducedPrecision()}},{key:"setQuadrantSegments",value:function(t){this._bufParams.setQuadrantSegments(t)}},{key:"bufferOriginalPrecision",value:function(){try{var t=new sr(this._bufParams);this._resultGeometry=t.buffer(this._argGeom,this._distance)}catch(t){if(!(t instanceof F))throw t;this._saveException=t}}},{key:"getResultGeometry",value:function(t){return this._distance=t,this.computeGeometry(),this._resultGeometry}},{key:"setEndCapStyle",value:function(t){this._bufParams.setEndCapStyle(t)}}],[{key:"constructor_",value:function(){if(this._argGeom=null,this._distance=null,this._bufParams=new y,this._resultGeometry=null,this._saveException=null,1===arguments.length){var t=arguments[0];this._argGeom=t}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this._argGeom=e,this._bufParams=n}}},{key:"bufferOp",value:function(){if(2===arguments.length){var t=arguments[1];return new e(arguments[0]).getResultGeometry(t)}if(3===arguments.length){if(Number.isInteger(arguments[2])&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var n=arguments[1],r=arguments[2],i=new e(arguments[0]);return i.setQuadrantSegments(r),i.getResultGeometry(n)}if(arguments[2]instanceof y&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var o=arguments[1];return new e(arguments[0],arguments[2]).getResultGeometry(o)}}else if(4===arguments.length){var s=arguments[1],a=arguments[2],u=arguments[3],l=new e(arguments[0]);return l.setQuadrantSegments(a),l.setEndCapStyle(u),l.getResultGeometry(s)}}},{key:"precisionScaleFactor",value:function(t,e,n){var r=t.getEnvelopeInternal(),i=Et.max(Math.abs(r.getMaxX()),Math.abs(r.getMaxY()),Math.abs(r.getMinX()),Math.abs(r.getMinY()))+2*(e>0?e:0),o=n-Math.trunc(Math.log(i)/Math.log(10)+1);return Math.pow(10,o)}}]),e}();vr.CAP_ROUND=y.CAP_ROUND,vr.CAP_BUTT=y.CAP_FLAT,vr.CAP_FLAT=y.CAP_FLAT,vr.CAP_SQUARE=y.CAP_SQUARE,vr.MAX_PRECISION_DIGITS=12;var dr=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],yr=function(){function e(n){t(this,e),this.geometryFactory=n||new ae}return n(e,[{key:"read",value:function(t){var e,n=(e="string"==typeof t?JSON.parse(t):t).type;if(!mr[n])throw new Error("Unknown GeoJSON type: "+e.type);return-1!==dr.indexOf(n)?mr[n].call(this,e.coordinates):"GeometryCollection"===n?mr[n].call(this,e.geometries):mr[n].call(this,e)}},{key:"write",value:function(t){var e=t.getGeometryType();if(!_r[e])throw new Error("Geometry is not supported");return _r[e].call(this,t)}}]),e}(),mr={Feature:function(t){var e={};for(var n in t)e[n]=t[n];if(t.geometry){var r=t.geometry.type;if(!mr[r])throw new Error("Unknown GeoJSON type: "+t.type);e.geometry=this.read(t.geometry)}return t.bbox&&(e.bbox=mr.bbox.call(this,t.bbox)),e},FeatureCollection:function(t){var e={};if(t.features){e.features=[];for(var n=0;n1?0:t<-1?Xn:Math.acos(t)}function ir(t){return t>1?Un:t<-1?-Un:Math.asin(t)}function or(){}function sr(t,e){t&&ur.hasOwnProperty(t.type)&&ur[t.type](t,e)}var ar={Feature:function(t,e){sr(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++rXn?t-Hn:t<-Xn?t+Hn:t,e]}function xr(t){return function(e,n){return[(e+=t)>Xn?e-Hn:e<-Xn?e+Hn:e,n]}}function Er(t){var e=xr(t);return e.invert=xr(-t),e}function kr(t,e){var n=tr(t),r=er(t),i=tr(e),o=er(e);function s(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*n+a*r;return[$n(u*i-h*o,a*n-l*r),ir(h*i+u*o)]}return s.invert=function(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*i-u*o;return[$n(u*i+l*o,a*n+h*r),ir(h*n-a*r)]},s}function br(t,e){(e=fr(e))[0]-=t,yr(e);var n=rr(-e[1]);return((-e[2]<0?-n:n)+Hn-jn)%Hn}function wr(){var t,e=[];return{point:function(e,n){t.push([e,n])},lineStart:function(){e.push(t=[])},lineEnd:or,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function Ir(t,e){return Kn(t[0]-e[0])=0;--o)i.point((h=l[o])[0],h[1]);else r(f.x,f.p.x,-1,i);f=f.p}l=(f=f.o).z,g=!g}while(!f.v);i.lineEnd()}}}function Mr(t){if(e=t.length){for(var e,n,r=0,i=t[0];++re?1:t>=e?0:NaN}function Pr(t){for(var e,n,r,i=t.length,o=-1,s=0;++o=0;)for(e=(r=t[i]).length;--e>=0;)n[--s]=r[e];return n}Gn(),Gn(),Gn(),_r.invert=_r,function(t){var e;1===t.length&&(e=t,t=function(t,n){return Lr(e(t),n)})}(Lr);var Cr=1e9,Tr=-Cr;function Or(t,e,n,r){function i(i,o){return t<=i&&i<=n&&e<=o&&o<=r}function o(i,o,a,l){var h=0,c=0;if(null==i||(h=s(i,a))!==(c=s(o,a))||u(i,o)<0^a>0)do{l.point(0===h||3===h?t:n,h>1?r:e)}while((h=(h+a+4)%4)!==c);else l.point(o[0],o[1])}function s(r,i){return Kn(r[0]-t)0?0:3:Kn(r[0]-n)0?2:1:Kn(r[1]-e)0?1:0:i>0?3:2}function a(t,e){return u(t.x,e.x)}function u(t,e){var n=s(t,1),r=s(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){var u,l,h,c,f,g,p,v,d,y,m,_=s,x=wr(),E={point:k,lineStart:function(){E.point=b,l&&l.push(h=[]);y=!0,d=!1,p=v=NaN},lineEnd:function(){u&&(b(c,f),g&&d&&x.rejoin(),u.push(x.result()));E.point=k,d&&_.lineEnd()},polygonStart:function(){_=x,u=[],l=[],m=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,i=l.length;nr&&(f-o)*(r-s)>(g-s)*(t-o)&&++e:g<=r&&(f-o)*(r-s)<(g-s)*(t-o)&&--e;return e}(),n=m&&e,i=(u=Pr(u)).length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),o(null,null,1,s),s.lineEnd()),i&&Sr(u,a,e,o,s),s.polygonEnd());_=s,u=l=h=null}};function k(t,e){i(t,e)&&_.point(t,e)}function b(o,s){var a=i(o,s);if(l&&h.push([o,s]),y)c=o,f=s,g=a,y=!1,a&&(_.lineStart(),_.point(o,s));else if(a&&d)_.point(o,s);else{var u=[p=Math.max(Tr,Math.min(Cr,p)),v=Math.max(Tr,Math.min(Cr,v))],x=[o=Math.max(Tr,Math.min(Cr,o)),s=Math.max(Tr,Math.min(Cr,s))];!function(t,e,n,r,i,o){var s,a=t[0],u=t[1],l=0,h=1,c=e[0]-a,f=e[1]-u;if(s=n-a,c||!(s>0)){if(s/=c,c<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=i-a,c||!(s<0)){if(s/=c,c<0){if(s>h)return;s>l&&(l=s)}else if(c>0){if(s0)){if(s/=f,f<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=o-u,f||!(s<0)){if(s/=f,f<0){if(s>h)return;s>l&&(l=s)}else if(f>0){if(s0&&(t[0]=a+l*c,t[1]=u+l*f),h<1&&(e[0]=a+h*c,e[1]=u+h*f),!0}}}}}(u,x,t,e,n,r)?a&&(_.lineStart(),_.point(o,s),m=!1):(d||(_.lineStart(),_.point(u[0],u[1])),_.point(x[0],x[1]),a||_.lineEnd(),m=!1)}p=o,v=s,d=a}return E}}var Rr=Gn();function Ar(t){return t}Gn(),Gn(),Gn();var Dr=1/0,Fr=Dr,qr=-Dr,Vr=qr,Gr={point:function(t,e){tqr&&(qr=t);eVr&&(Vr=e)},lineStart:or,lineEnd:or,polygonStart:or,polygonEnd:or,result:function(){var t=[[Dr,Fr],[qr,Vr]];return qr=Vr=-(Fr=Dr=1/0),t}};function Br(t,e,n,r){return function(i,o){var s,a,u,l=e(o),h=i.invert(r[0],r[1]),c=wr(),f=e(c),g=!1,p={point:v,lineStart:y,lineEnd:m,polygonStart:function(){p.point=_,p.lineStart=x,p.lineEnd=E,a=[],s=[]},polygonEnd:function(){p.point=v,p.lineStart=y,p.lineEnd=m,a=Pr(a);var t=function(t,e){var n=e[0],r=e[1],i=[er(n),-tr(n),0],o=0,s=0;Rr.reset();for(var a=0,u=t.length;a=0?1:-1,w=b*k,I=w>Xn,N=p*x;if(Rr.add($n(N*b*er(w),v*E+N*tr(w))),o+=I?k+b*Hn:k,I^f>=n^m>=n){var S=pr(fr(c),fr(y));yr(S);var M=pr(i,S);yr(M);var L=(I^k>=0?-1:1)*ir(M[2]);(r>L||r===L&&(S[0]||S[1]))&&(s+=I^k>=0?1:-1)}}return(o<-jn||o0){for(g||(o.polygonStart(),g=!0),o.lineStart(),t=0;t1&&2&i&&l.push(l.pop().concat(l.shift())),a.push(l.filter(Yr))}return p}}function Yr(t){return t.length>1}function zr(t,e){return((t=t.x)[0]<0?t[1]-Un-jn:Un-t[1])-((e=e.x)[0]<0?e[1]-Un-jn:Un-e[1])}Gn();var jr=Br((function(){return!0}),(function(t){var e,n=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,s){var a=o>0?Xn:-Xn,u=Kn(o-n);Kn(u-Xn)0?Un:-Un),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),e=0):i!==a&&u>=Xn&&(Kn(n-i)jn?Qn((er(e)*(o=tr(r))*er(n)-er(r)*(i=tr(e))*er(t))/(i*o*s)):(e+r)/2}(n,r,o,s),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),e=0),t.point(n=o,r=s),i=a},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var i;if(null==t)i=n*Un,r.point(-Xn,i),r.point(0,i),r.point(Xn,i),r.point(Xn,0),r.point(Xn,-i),r.point(0,-i),r.point(-Xn,-i),r.point(-Xn,0),r.point(-Xn,i);else if(Kn(t[0]-e[0])>jn){var o=t[0]0,i=Kn(n)>jn;function o(t,e){return tr(t)*tr(e)>n}function s(t,e,r){var i=[1,0,0],o=pr(fr(t),fr(e)),s=gr(o,o),a=o[0],u=s-a*a;if(!u)return!r&&t;var l=n*s/u,h=-n*a/u,c=pr(i,o),f=dr(i,l);vr(f,dr(o,h));var g=c,p=gr(f,g),v=gr(g,g),d=p*p-v*(gr(f,f)-1);if(!(d<0)){var y=nr(d),m=dr(g,(-p-y)/v);if(vr(m,f),m=cr(m),!r)return m;var _,x=t[0],E=e[0],k=t[1],b=e[1];E0^m[1]<(Kn(m[0]-x)Xn^(x<=m[0]&&m[0]<=E)){var N=dr(g,(-p+y)/v);return vr(N,f),[m,cr(N)]}}}function a(e,n){var i=r?t:Xn-t,o=0;return e<-i?o|=1:e>i&&(o|=2),n<-i?o|=4:n>i&&(o|=8),o}return Br(o,(function(t){var e,n,u,l,h;return{lineStart:function(){l=u=!1,h=1},point:function(c,f){var g,p=[c,f],v=o(c,f),d=r?v?0:a(c,f):v?a(c+(c<0?Xn:-Xn),f):0;if(!e&&(l=u=v)&&t.lineStart(),v!==u&&(!(g=s(e,p))||Ir(e,g)||Ir(p,g))&&(p[0]+=jn,p[1]+=jn,v=o(p[0],p[1])),v!==u)h=0,v?(t.lineStart(),g=s(p,e),t.point(g[0],g[1])):(g=s(e,p),t.point(g[0],g[1]),t.lineEnd()),e=g;else if(i&&e&&r^v){var y;d&n||!(y=s(p,e,!0))||(h=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1])))}!v||e&&Ir(e,p)||t.point(p[0],p[1]),e=p,u=v,n=d},lineEnd:function(){u&&t.lineEnd(),e=null},clean:function(){return h|(l&&u)<<1}}}),(function(n,r,i,o){!function(t,e,n,r,i,o){if(n){var s=tr(e),a=er(e),u=r*n;null==i?(i=e+r*Hn,o=e-u/2):(i=br(s,i),o=br(s,o),(r>0?io)&&(i+=r*Hn));for(var l,h=i;r>0?h>o:h4*e&&v--){var x=s+f,E=a+g,k=u+p,b=nr(x*x+E*E+k*k),w=ir(k/=b),I=Kn(Kn(k)-1)e||Kn((y*L+m*P)/_-.5)>.3||s*f+a*g+u*p2?t[2]%360*Jn:0,M()):[d*Wn,y*Wn,m*Wn]},I.precision=function(t){return arguments.length?(w=Kr(S,b=t*t),L()):nr(b)},I.fitExtent=function(t,e){return Hr(I,t,e)},I.fitSize=function(t,e){return function(t,e,n){return Hr(t,[[0,0],e],n)}(I,t,e)},function(){return e=t.apply(this,arguments),I.invert=e.invert&&N,M()}}((function(){return t}))()}function ti(t){return function(e,n){var r=tr(e),i=tr(n),o=t(r*i);return[o*i*er(e),o*er(n)]}}function ei(t){return function(e,n){var r=nr(e*e+n*n),i=t(r),o=er(i),s=tr(i);return[$n(e*o,r*s),ir(r&&n*o/r)]}}ti((function(t){return nr(2/(1+t))})).invert=ei((function(t){return 2*ir(t/2)}));var ni=ti((function(t){return(t=rr(t))&&t/er(t)}));function ri(){return $r(ni).scale(79.4188).clipAngle(179.999)}function ii(t,e){return[t,e]}ni.invert=ei((function(t){return t})),ii.invert=ii;var oi=Vn.BufferOp,si=Vn.GeoJSONReader,ai=Vn.GeoJSONWriter;function ui(t,e,n,r){var i=t.properties||{},o="Feature"===t.type?t.geometry:t;if("GeometryCollection"===o.type){var s=[];return mt(t,(function(t){var i=ui(t,e,n,r);i&&s.push(i)})),C(s)}var a=function(t){var e=An(t).geometry.coordinates,n=[-e[0],-e[1]];return ri().rotate(n).scale(x)}(o),u={type:o.type,coordinates:hi(o.coordinates,a)},l=(new si).read(u),h=F(q(e,n),"meters"),c=oi.bufferOp(l,h,r);if(!li((c=(new ai).write(c)).coordinates))return b({type:c.type,coordinates:ci(c.coordinates,a)},i)}function li(t){return Array.isArray(t[0])?li(t[0]):isNaN(t[0])}function hi(t,e){return"object"!==m(t[0])?e(t):t.map((function(t){return hi(t,e)}))}function ci(t,e){return"object"!==m(t[0])?e.invert(t):t.map((function(t){return ci(t,e)}))}function fi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return mt(t,(function(t,o,s){var a=e.weight?null==s?void 0:s[e.weight]:void 0;if(!U(a=null==a?1:a))throw new Error("weight value must be a number for feature index "+o);(a=Number(a))>0&&ct(t,(function(t){n+=t[0]*a,r+=t[1]*a,i+=a}))})),I([n/i,r/i],e.properties,e)}function gi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return ct(t,(function(t){n+=t[0],r+=t[1],i++}),!0),I([n/i,r/i],e.properties)}function pi(t,e,n,r,i){var o=r.tolerance||.001,s=0,a=0,u=0,l=0;if(vt(n,(function(e){var n,r=null==(n=e.properties)?void 0:n.weight,i=null==r?1:r;if(!U(i=Number(i)))throw new Error("weight value must be a number");if(i>0){l+=1;var o=i*ut(e,t);0===o&&(o=1);var h=i/o;s+=e.geometry.coordinates[0]*h,a+=e.geometry.coordinates[1]*h,u+=h}})),l<1)throw new Error("no features to measure");var h=s/u,c=a/u;return 1===l||0===i||Math.abs(h-e[0])0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mi;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function mi(t,e){return te?1:0}var _i,xi,Ei,ki,bi,wi=_n(Object.freeze({__proto__:null,default:yi})),Ii={exports:{}};function Ni(){if(bi)return Ii.exports;bi=1;var t=(xi||(xi=1,_i=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=(r-n)/2,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),_i),e=(ki||(ki=1,Ei=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=r-n,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),Ei);return Ii.exports=function(n,r,i,o){return r.length>0&&Array.isArray(r[0])?e(n,r,i,o):t(n,r,i,o)},Ii.exports.nested=e,Ii.exports.flat=t,Ii.exports}var Si,Mi,Li={exports:{}};Li.exports;function Pi(){return Si||(Si=1,function(t,e){!function(t){var e=134217729,n=33306690738754706e-32;function r(t,e,n,r,i){var o,s,a,u,l=e[0],h=r[0],c=0,f=0;h>l==h>-l?(o=l,l=e[++c]):(o=h,h=r[++f]);var g=0;if(cl==h>-l?(a=o-((s=l+o)-l),l=e[++c]):(a=o-((s=h+o)-h),h=r[++f]),o=s,0!==a&&(i[g++]=a);cl==h>-l?(a=o-((s=o+l)-(u=s-o))+(l-u),l=e[++c]):(a=o-((s=o+h)-(u=s-o))+(h-u),h=r[++f]),o=s,0!==a&&(i[g++]=a);for(;c0!=m>0)return _;var x=Math.abs(y+m);return Math.abs(_)>=o*x?_:-function(t,i,o,g,p,v,d){var y,m,_,x,E,k,b,w,I,N,S,M,L,P,C,T,O,R,A=t-p,D=o-p,F=i-v,q=g-v;E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=q-(I=(k=e*q)-(k-q)))-((P=A*q)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=D-(I=(k=e*D)-(k-D)))-((T=F*D)-b*I-w*I-b*N))),u[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),u[1]=L-(S+E)+(E-T),E=(R=M+S)-M,u[2]=M-(R-E)+(S-E),u[3]=R;var V=function(t,e){for(var n=e[0],r=1;r=G||-V>=G)return V;if(y=t-(A+(E=t-A))+(E-p),_=o-(D+(E=o-D))+(E-p),m=i-(F+(E=i-F))+(E-v),x=g-(q+(E=g-q))+(E-v),0===y&&0===m&&0===_&&0===x)return V;if(G=a*d+n*Math.abs(V),(V+=A*x+q*y-(F*_+D*m))>=G||-V>=G)return V;E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=q-(I=(k=e*q)-(k-q)))-((P=y*q)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=D-(I=(k=e*D)-(k-D)))-((T=m*D)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var B=r(4,u,4,f,l);E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=x-(I=(k=e*x)-(k-x)))-((P=A*x)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=_-(I=(k=e*_)-(k-_)))-((T=F*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var Y=r(B,l,4,f,h);E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=x-(I=(k=e*x)-(k-x)))-((P=y*x)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=_-(I=(k=e*_)-(k-_)))-((T=m*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var z=r(Y,h,4,f,c);return c[z-1]}(t,i,g,p,v,d,x)},t.orient2dfast=function(t,e,n,r,i,o){return(e-o)*(n-i)-(t-i)*(r-o)},Object.defineProperty(t,"__esModule",{value:!0})}(e)}(0,Li.exports)),Li.exports}var Ci=function(){if(Mi)return vi.exports;Mi=1;var t=di,e=wi,n=Ni(),r=Pi().orient2d;function i(e,r,i){r=Math.max(0,void 0===r?2:r),i=i||0;var s=function(t){for(var e=t[0],r=t[0],i=t[0],o=t[0],s=0;si[0]&&(i=a),a[1]o[1]&&(o=a)}var u=[e,r,i,o],l=u.slice();for(s=0;s=2&&h(e[e.length-2],e[e.length-1],t[n])<=0;)e.pop();e.push(t[n])}for(var r=[],i=t.length-1;i>=0;i--){for(;r.length>=2&&h(r[r.length-2],r[r.length-1],t[i])<=0;)r.pop();r.push(t[i])}return r.pop(),e.pop(),e.concat(r)}(l)}(e),a=new t(16);a.toBBox=function(t){return{minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]}},a.compareMinX=function(t,e){return t[0]-e[0]},a.compareMinY=function(t,e){return t[1]-e[1]},a.load(e);for(var u,l=[],p=0;pu||c.push({node:v,dist:d})}for(;c.length&&!c.peek().node.children;){var y=c.pop(),m=y.node,_=p(m,n,r),x=p(m,i,o);if(y.dist<_&&y.dist=e.minX&&t[0]<=e.maxX&&t[1]>=e.minY&&t[1]<=e.maxY}function l(t,e,n){for(var r,i,o,s,a=Math.min(t[0],e[0]),u=Math.min(t[1],e[1]),l=Math.max(t[0],e[0]),c=Math.max(t[1],e[1]),f=n.search({minX:a,minY:u,maxX:l,maxY:c}),g=0;g0!=h(r,i,s)>0&&h(o,s,r)>0!=h(o,s,i)>0)return!1;return!0}function h(t,e,n){return r(t[0],t[1],e[0],e[1],n[0],n[1])}function c(t){var e=t.p,n=t.next.p;return t.minX=Math.min(e[0],n[0]),t.minY=Math.min(e[1],n[1]),t.maxX=Math.max(e[0],n[0]),t.maxY=Math.max(e[1],n[1]),t}function f(t,e){var n={p:t,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return e?(n.next=e.next,n.prev=e,e.next.prev=n,e.next=n):(n.prev=n,n.next=n),n}function g(t,e){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function p(t,e,n){var r=e[0],i=e[1],o=n[0]-r,s=n[1]-i;if(0!==o||0!==s){var a=((t[0]-r)*o+(t[1]-i)*s)/(o*o+s*s);a>1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function v(t,e,n,r,i,o,s,a){var u,l,h,c,f=n-t,g=r-e,p=s-i,v=a-o,d=t-i,y=e-o,m=f*f+g*g,_=f*p+g*v,x=p*p+v*v,E=f*d+g*y,k=p*d+v*y,b=m*x-_*_,w=b,I=b;0===b?(l=0,w=1,c=k,I=x):(c=m*k-_*E,(l=_*k-x*E)<0?(l=0,c=k,I=x):l>w&&(l=w,c=k+_,I=x)),c<0?(c=0,-E<0?l=0:-E>m?l=w:(l=-E,w=m)):c>I&&(c=I,-E+_<0?l=0:-E+_>m?l=w:(l=-E+_,w=m));var N=(1-(h=0===c?0:c/I))*i+h*s-((1-(u=0===l?0:l/w))*t+u*n),S=(1-h)*o+h*a-((1-u)*e+u*r);return N*N+S*S}function d(t,e){return t[0]===e[0]?t[1]-e[1]:t[0]-e[0]}return e.default&&(e=e.default),vi.exports=i,vi.exports.default=i,vi.exports}(),Ti=mn(Ci);function Oi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e.concavity=e.concavity||1/0;var n=[];if(ct(t,(function(t){n.push([t[0],t[1]])})),!n.length)return null;var r=Ti(n,e.concavity);return r.length>3?S([r]):null}function Ri(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.steps||64,i=n.properties?n.properties:!Array.isArray(t)&&"Feature"===t.type&&t.properties?t.properties:{},o=[],s=0;s0;r.length0;){var a=t[Math.floor(Math.random()*o)],u=s?a.join("_"):""+a;n[u]||(n[u]=!0,r.push(a))}if(r.length0,u=t[Math.floor(Math.random()*s)];for(a&&u.join("_"),o.push(u);o.length0,y=[];if(s)u="kmrand"==s?r(t,e):"kmpp"==s?i(t,e):s;else for(var m={};u.lengthc&&(c=t[a].y);var g,p=l-u,v=c-h,d=p>v?p:v,y=.5*(l+u),m=.5*(c+h),_=[new so({__sentinel:!0,x:y-20*d,y:m-d},{__sentinel:!0,x:y,y:m+20*d},{__sentinel:!0,x:y+20*d,y:m-d})],x=[],E=[];a=t.length;for(;a--;){for(E.length=0,g=_.length;g--;)(p=t[a].x-_[g].x)>0&&p*p>_[g].r?(x.push(_[g]),_.splice(g,1)):p*p+(v=t[a].y-_[g].y)*v>_[g].r||(E.push(_[g].a,_[g].b,_[g].b,_[g].c,_[g].c,_[g].a),_.splice(g,1));for(uo(E),g=E.length;g;)n=E[--g],e=E[--g],r=t[a],i=n.x-e.x,o=n.y-e.y,s=2*(i*(r.y-n.y)-o*(r.x-n.x)),Math.abs(s)>f&&_.push(new so(e,n,r))}Array.prototype.push.apply(x,_),a=x.length;for(;a--;)(x[a].a.__sentinel||x[a].b.__sentinel||x[a].c.__sentinel)&&x.splice(a,1);return x}(t.features.map((function(t){var r={x:t.geometry.coordinates[0],y:t.geometry.coordinates[1]};return e?r.z=t.properties[e]:3===t.geometry.coordinates.length&&(n=!0,r.z=t.geometry.coordinates[2]),r}))).map((function(t){var e=[t.a.x,t.a.y],r=[t.b.x,t.b.y],i=[t.c.x,t.c.y],o={};return n?(e.push(t.a.z),r.push(t.b.z),i.push(t.c.z)):o={a:t.a.z,b:t.b.z,c:t.c.z},S([[e,r,i,e]],o)})))}var so=s((function t(e,n,r){i(this,t),this.a=e,this.b=n,this.c=r;var o,s,a=n.x-e.x,u=n.y-e.y,l=r.x-e.x,h=r.y-e.y,c=a*(e.x+n.x)+u*(e.y+n.y),f=l*(e.x+r.x)+h*(e.y+r.y),g=2*(a*(r.y-n.y)-u*(r.x-n.x));this.x=(h*c-u*f)/g,this.y=(a*f-l*c)/g,o=this.x-e.x,s=this.y-e.y,this.r=o*o+s*s}));function ao(t,e){return e.x-t.x}function uo(t){var e,n,r,i,o,s=t.length;t:for(;s;)for(n=t[--s],e=t[--s],r=s;r;)if(o=t[--r],e===(i=t[--r])&&n===o||e===o&&n===i){t.splice(s,2),t.splice(r,2),s-=2;continue t}}function lo(t){return t}function ho(t,e){var n=function(t){if(null==t)return lo;var e,n,r=t.scale[0],i=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,a){a||(e=n=0);var u=2,l=t.length,h=new Array(l);for(h[0]=(e+=t[0])*r+o,h[1]=(n+=t[1])*i+s;u1)for(var o,a,u=1,l=s(i[0]);ul&&(a=i[0],i[0]=i[u],i[u]=a,l=o);return i})).filter((function(t){return t.length>0}))}}var po=Object.prototype.hasOwnProperty;function vo(t,e,n,r,i,o){3===arguments.length&&(r=o=Array,i=null);for(var s=new r(t=1<=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},maybeSet:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},get:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)break;h=s[l=l+1&u]}return o},keys:function(){for(var t=[],e=0,n=s.length;e>7^xo[2]^xo[3])}function ko(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=function(){for(var t=vo(1.4*o.length,E,k,Int32Array,-1,Int32Array),e=new Int32Array(o.length),n=0,r=o.length;n=0){var o=c[n];i===e&&o===r||i===r&&o===e||(++g,f[n]=1)}else h[n]=e,c[n]=r}}function E(t){return Eo(o[t])}function k(t,e){return yo(o[t],o[e])}l=h=c=null;var b,w=function(t,e,n,r,i){3===arguments.length&&(r=Array,i=null);for(var o=new r(t=1<=t)throw new Error("full hashset");u=o[a=a+1&s]}return o[a]=r,!0},has:function(r){for(var a=e(r)&s,u=o[a],l=0;u!=i;){if(n(u,r))return!0;if(++l>=t)break;u=o[a=a+1&s]}return!1},values:function(){for(var t=[],e=0,n=o.length;e>1);er&&(r=o),si&&(i=s)}function u(t){t.forEach(a)}function l(t){t.forEach(u)}for(var h in t)o(t[h]);return r>=e&&i>=n?[e,n,r,i]:void 0}(t=Io(t)),r=function(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=s.length+a.length;for(delete t.lines,delete t.rings,r=0,i=s.length;r1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=[],i=It(t,(function(t,e){var n=function(t,e){var n,r=t.geometry.coordinates,i=e.geometry.coordinates,o=Oo(r[0]),s=Oo(r[r.length-1]),a=Oo(i[0]),u=Oo(i[i.length-1]);if(o===u)n=i.concat(r.slice(1));else if(a===s)n=r.concat(i.slice(1));else if(o===a)n=r.slice(1).reverse().concat(i);else{if(s!==u)return null;n=r.concat(i.reverse().slice(1))}return L(n)}(t,e);return n||(r.push(t),e)}));return i&&r.push(i),r.length?1===r.length?r[0]:T(r.map((function(t){return t.coordinates}))):null}function Oo(t){return t[0].toString()+","+t[1].toString()}function Ro(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=function(t){var e={};xt(t,(function(t){e[t.geometry.type]=!0}));var n=Object.keys(e);if(1===n.length)return n[0];return null}(t);if(!r)throw new Error("geojson must be homogenous");var i=t;switch(r){case"LineString":return To(i,e);case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==e.mutate&&void 0!==e.mutate||(t=Ai(t));var n=[];xt(t,(function(t){n.push(t.geometry)}));var r=Lo({geoms:A(n).geometry});return fo(r,r.objects.geoms.geometries)}(i,e);default:throw new Error(r+" is not supported")}}var Ao=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Do=Math.ceil,Fo=Math.floor,qo="[BigNumber Error] ",Vo=qo+"Number primitive has more than 15 significant digits: ",Go=1e14,Bo=14,Yo=9007199254740991,zo=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Xo=1e9;function Uo(t){var e=0|t;return t>0||t===e?e:e-1}function Zo(t){for(var e,n,r=1,i=t.length,o=t[0]+"";rl^n?1:-1;for(a=(u=i.length)<(l=o.length)?u:l,s=0;so[s]^n?1:-1;return u==l?0:u>l^n?1:-1}function Wo(t,e,n,r){if(tn||t!==Fo(t))throw Error(qo+(r||"Argument")+("number"==typeof t?tn?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Jo(t){var e=t.c.length-1;return Uo(t.e/Bo)==e&&t.c[e]%2!=0}function Ko(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Qo(t,e,n){var r,i;if(e<0){for(i=n+".";++e;i+=n);t=i+t}else if(++e>(r=t.length)){for(i=n,e-=r;--e;i+=n);t+=i}else ex?f.c=f.e=null:t.e<_?f.c=[f.e=0]:(f.e=t.e,f.c=t.c.slice()));if((l="number"==typeof t)&&0*t==0){if(f.s=1/t<0?(t=-t,-1):1,t===~~t){for(a=0,u=t;u>=10;u/=10,a++);return void(a>x?f.c=f.e=null:(f.e=a,f.c=[t]))}c=String(t)}else{if(!Ao.test(c=String(t)))return i(f,c,l);f.s=45==c.charCodeAt(0)?(c=c.slice(1),-1):1}(a=c.indexOf("."))>-1&&(c=c.replace(".","")),(u=c.search(/e/i))>0?(a<0&&(a=u),a+=+c.slice(u+1),c=c.substring(0,u)):a<0&&(a=c.length)}else{if(Wo(e,2,I.length,"Base"),10==e&&N)return C(f=new S(t),p+f.e+1,v);if(c=String(t),l="number"==typeof t){if(0*t!=0)return i(f,c,l,e);if(f.s=1/t<0?(c=c.slice(1),-1):1,S.DEBUG&&c.replace(/^0\.0*|\./,"").length>15)throw Error(Vo+t)}else f.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1;for(n=I.slice(0,e),a=u=0,h=c.length;ua){a=h;continue}}else if(!s&&(c==c.toUpperCase()&&(c=c.toLowerCase())||c==c.toLowerCase()&&(c=c.toUpperCase()))){s=!0,u=-1,a=0;continue}return i(f,String(t),l,e)}l=!1,(a=(c=r(c,e,10,f.s)).indexOf("."))>-1?c=c.replace(".",""):a=c.length}for(u=0;48===c.charCodeAt(u);u++);for(h=c.length;48===c.charCodeAt(--h););if(c=c.slice(u,++h)){if(h-=u,l&&S.DEBUG&&h>15&&(t>Yo||t!==Fo(t)))throw Error(Vo+f.s*t);if((a=a-u-1)>x)f.c=f.e=null;else if(a<_)f.c=[f.e=0];else{if(f.e=a,f.c=[],u=(a+1)%Bo,a<0&&(u+=Bo),u=y)?Ko(u,s):Qo(u,s,"0");else if(o=(t=C(new S(t),e,n)).e,a=(u=Zo(t.c)).length,1==r||2==r&&(e<=o||o<=d)){for(;aa){if(--e>0)for(u+=".";e--;u+="0");}else if((e+=o-a)>0)for(o+1==a&&(u+=".");e--;u+="0");return t.s<0&&i?"-"+u:u}function L(t,e){for(var n,r,i=1,o=new S(t[0]);i=10;i/=10,r++);return(n=r+n*Bo-1)>x?t.c=t.e=null:n<_?t.c=[t.e=0]:(t.e=n,t.c=e),t}function C(t,e,n,r){var i,o,s,a,u,l,h,c=t.c,f=zo;if(c){t:{for(i=1,a=c[0];a>=10;a/=10,i++);if((o=e-i)<0)o+=Bo,s=e,u=c[l=0],h=Fo(u/f[i-s-1]%10);else if((l=Do((o+1)/Bo))>=c.length){if(!r)break t;for(;c.length<=l;c.push(0));u=h=0,i=1,s=(o%=Bo)-Bo+1}else{for(u=a=c[l],i=1;a>=10;a/=10,i++);h=(s=(o%=Bo)-Bo+i)<0?0:Fo(u/f[i-s-1]%10)}if(r=r||e<0||null!=c[l+1]||(s<0?u:u%f[i-s-1]),r=n<4?(h||r)&&(0==n||n==(t.s<0?3:2)):h>5||5==h&&(4==n||r||6==n&&(o>0?s>0?u/f[i-s]:0:c[l-1])%10&1||n==(t.s<0?8:7)),e<1||!c[0])return c.length=0,r?(e-=t.e+1,c[0]=f[(Bo-e%Bo)%Bo],t.e=-e||0):c[0]=t.e=0,t;if(0==o?(c.length=l,a=1,l--):(c.length=l+1,a=f[Bo-o],c[l]=s>0?Fo(u/f[i-s]%f[s])*a:0),r)for(;;){if(0==l){for(o=1,s=c[0];s>=10;s/=10,o++);for(s=c[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(t.e++,c[0]==Go&&(c[0]=1));break}if(c[l]+=a,c[l]!=Go)break;c[l--]=0,a=1}for(o=c.length;0===c[--o];c.pop());}t.e>x?t.c=t.e=null:t.e<_&&(t.c=[t.e=0])}return t}function T(t){var e,n=t.e;return null===n?t.toString():(e=Zo(t.c),e=n<=d||n>=y?Ko(e,n):Qo(e,n,"0"),t.s<0?"-"+e:e)}return S.clone=t,S.ROUND_UP=0,S.ROUND_DOWN=1,S.ROUND_CEIL=2,S.ROUND_FLOOR=3,S.ROUND_HALF_UP=4,S.ROUND_HALF_DOWN=5,S.ROUND_HALF_EVEN=6,S.ROUND_HALF_CEIL=7,S.ROUND_HALF_FLOOR=8,S.EUCLID=9,S.config=S.set=function(t){var e,n;if(null!=t){if("object"!=m(t))throw Error(qo+"Object expected: "+t);if(t.hasOwnProperty(e="DECIMAL_PLACES")&&(Wo(n=t[e],0,Xo,e),p=n),t.hasOwnProperty(e="ROUNDING_MODE")&&(Wo(n=t[e],0,8,e),v=n),t.hasOwnProperty(e="EXPONENTIAL_AT")&&((n=t[e])&&n.pop?(Wo(n[0],-Xo,0,e),Wo(n[1],0,Xo,e),d=n[0],y=n[1]):(Wo(n,-Xo,Xo,e),d=-(y=n<0?-n:n))),t.hasOwnProperty(e="RANGE"))if((n=t[e])&&n.pop)Wo(n[0],-Xo,-1,e),Wo(n[1],1,Xo,e),_=n[0],x=n[1];else{if(Wo(n,-Xo,Xo,e),!n)throw Error(qo+e+" cannot be zero: "+n);_=-(x=n<0?-n:n)}if(t.hasOwnProperty(e="CRYPTO")){if((n=t[e])!==!!n)throw Error(qo+e+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw E=!n,Error(qo+"crypto unavailable");E=n}else E=n}if(t.hasOwnProperty(e="MODULO_MODE")&&(Wo(n=t[e],0,9,e),k=n),t.hasOwnProperty(e="POW_PRECISION")&&(Wo(n=t[e],0,Xo,e),b=n),t.hasOwnProperty(e="FORMAT")){if("object"!=m(n=t[e]))throw Error(qo+e+" not an object: "+n);w=n}if(t.hasOwnProperty(e="ALPHABET")){if("string"!=typeof(n=t[e])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(qo+e+" invalid: "+n);N="0123456789"==n.slice(0,10),I=n}}return{DECIMAL_PLACES:p,ROUNDING_MODE:v,EXPONENTIAL_AT:[d,y],RANGE:[_,x],CRYPTO:E,MODULO_MODE:k,POW_PRECISION:b,FORMAT:w,ALPHABET:I}},S.isBigNumber=function(t){if(!t||!0!==t._isBigNumber)return!1;if(!S.DEBUG)return!0;var e,n,r=t.c,i=t.e,o=t.s;t:if("[object Array]"=={}.toString.call(r)){if((1===o||-1===o)&&i>=-Xo&&i<=Xo&&i===Fo(i)){if(0===r[0]){if(0===i&&1===r.length)return!0;break t}if((e=(i+1)%Bo)<1&&(e+=Bo),String(r[0]).length==e){for(e=0;e=Go||n!==Fo(n))break t;if(0!==n)return!0}}}else if(null===r&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(qo+"Invalid BigNumber: "+t)},S.maximum=S.max=function(){return L(arguments,-1)},S.minimum=S.min=function(){return L(arguments,1)},S.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Fo(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(t){var e,n,r,i,o,a=0,u=[],l=new S(g);if(null==t?t=p:Wo(t,0,Xo),i=Do(t/Bo),E)if(crypto.getRandomValues){for(e=crypto.getRandomValues(new Uint32Array(i*=2));a>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),e[a]=n[0],e[a+1]=n[1]):(u.push(o%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw E=!1,Error(qo+"crypto unavailable");for(e=crypto.randomBytes(i*=7);a=9e15?crypto.randomBytes(7).copy(e,a):(u.push(o%1e14),a+=7);a=i/7}if(!E)for(;a=10;o/=10,a++);an-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(r,i,o,s,a){var u,l,h,c,f,g,d,y,m=r.indexOf("."),_=p,x=v;for(m>=0&&(c=b,b=0,r=r.replace(".",""),g=(y=new S(i)).pow(r.length-m),b=c,y.c=e(Qo(Zo(g.c),g.e,"0"),10,o,t),y.e=y.c.length),h=c=(d=e(r,i,o,a?(u=I,t):(u=t,I))).length;0==d[--c];d.pop());if(!d[0])return u.charAt(0);if(m<0?--h:(g.c=d,g.e=h,g.s=s,d=(g=n(g,y,_,x,o)).c,f=g.r,h=g.e),m=d[l=h+_+1],c=o/2,f=f||l<0||null!=d[l+1],f=x<4?(null!=m||f)&&(0==x||x==(g.s<0?3:2)):m>c||m==c&&(4==x||f||6==x&&1&d[l-1]||x==(g.s<0?8:7)),l<1||!d[0])r=f?Qo(u.charAt(1),-_,u.charAt(0)):u.charAt(0);else{if(d.length=l,f)for(--o;++d[--l]>o;)d[l]=0,l||(++h,d=[1].concat(d));for(c=d.length;!d[--c];);for(m=0,r="";m<=c;r+=u.charAt(d[m++]));r=Qo(r,h,u.charAt(0))}return r}}(),n=function(){function t(t,e,n){var r,i,o,s,a=0,u=t.length,l=e%jo,h=e/jo|0;for(t=t.slice();u--;)a=((i=l*(o=t[u]%jo)+(r=h*o+(s=t[u]/jo|0)*l)%jo*jo+a)/n|0)+(r/jo|0)+h*s,t[u]=i%n;return a&&(t=[a].concat(t)),t}function e(t,e,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;ie[i]?1:-1;break}return o}function n(t,e,n,r){for(var i=0;n--;)t[n]-=i,i=t[n]1;t.splice(0,1));}return function(r,i,o,s,a){var u,l,h,c,f,g,p,v,d,y,m,_,x,E,k,b,w,I=r.s==i.s?1:-1,N=r.c,M=i.c;if(!(N&&N[0]&&M&&M[0]))return new S(r.s&&i.s&&(N?!M||N[0]!=M[0]:M)?N&&0==N[0]||!M?0*I:I/0:NaN);for(d=(v=new S(I)).c=[],I=o+(l=r.e-i.e)+1,a||(a=Go,l=Uo(r.e/Bo)-Uo(i.e/Bo),I=I/Bo|0),h=0;M[h]==(N[h]||0);h++);if(M[h]>(N[h]||0)&&l--,I<0)d.push(1),c=!0;else{for(E=N.length,b=M.length,h=0,I+=2,(f=Fo(a/(M[0]+1)))>1&&(M=t(M,f,a),N=t(N,f,a),b=M.length,E=N.length),x=b,m=(y=N.slice(0,b)).length;m=a/2&&k++;do{if(f=0,(u=e(M,y,b,m))<0){if(_=y[0],b!=m&&(_=_*a+(y[1]||0)),(f=Fo(_/k))>1)for(f>=a&&(f=a-1),p=(g=t(M,f,a)).length,m=y.length;1==e(g,y,p,m);)f--,n(g,b=10;I/=10,h++);C(v,o+(v.e=h+l*Bo-1)+1,s,c)}else v.e=l,v.r=+c;return v}}(),a=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,l=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,c=/^\s*\+(?=[\w.])|^\s+|\s+$/g,i=function(t,e,n,r){var i,o=n?e:e.replace(c,"");if(h.test(o))t.s=isNaN(o)?null:o<0?-1:1;else{if(!n&&(o=o.replace(a,(function(t,e,n){return i="x"==(n=n.toLowerCase())?16:"b"==n?2:8,r&&r!=i?t:e})),r&&(i=r,o=o.replace(u,"$1").replace(l,"0.$1")),e!=o))return new S(o,i);if(S.DEBUG)throw Error(qo+"Not a"+(r?" base "+r:"")+" number: "+e);t.s=null}t.c=t.e=null},f.absoluteValue=f.abs=function(){var t=new S(this);return t.s<0&&(t.s=1),t},f.comparedTo=function(t,e){return Ho(this,new S(t,e))},f.decimalPlaces=f.dp=function(t,e){var n,r,i,o=this;if(null!=t)return Wo(t,0,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t+o.e+1,e);if(!(n=o.c))return null;if(r=((i=n.length-1)-Uo(this.e/Bo))*Bo,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},f.dividedBy=f.div=function(t,e){return n(this,new S(t,e),p,v)},f.dividedToIntegerBy=f.idiv=function(t,e){return n(this,new S(t,e),0,1)},f.exponentiatedBy=f.pow=function(t,e){var n,r,i,o,s,a,u,l,h=this;if((t=new S(t)).c&&!t.isInteger())throw Error(qo+"Exponent not an integer: "+T(t));if(null!=e&&(e=new S(e)),s=t.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!t.c||!t.c[0])return l=new S(Math.pow(+T(h),s?t.s*(2-Jo(t)):+T(t))),e?l.mod(e):l;if(a=t.s<0,e){if(e.c?!e.c[0]:!e.s)return new S(NaN);(r=!a&&h.isInteger()&&e.isInteger())&&(h=h.mod(e))}else{if(t.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return o=h.s<0&&Jo(t)?-0:0,h.e>-1&&(o=1/o),new S(a?1/o:o);b&&(o=Do(b/Bo+2))}for(s?(n=new S(.5),a&&(t.s=1),u=Jo(t)):u=(i=Math.abs(+T(t)))%2,l=new S(g);;){if(u){if(!(l=l.times(h)).c)break;o?l.c.length>o&&(l.c.length=o):r&&(l=l.mod(e))}if(i){if(0===(i=Fo(i/2)))break;u=i%2}else if(C(t=t.times(n),t.e+1,1),t.e>14)u=Jo(t);else{if(0===(i=+T(t)))break;u=i%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):r&&(h=h.mod(e))}return r?l:(a&&(l=g.div(l)),e?l.mod(e):o?C(l,b,v,undefined):l)},f.integerValue=function(t){var e=new S(this);return null==t?t=v:Wo(t,0,8),C(e,e.e+1,t)},f.isEqualTo=f.eq=function(t,e){return 0===Ho(this,new S(t,e))},f.isFinite=function(){return!!this.c},f.isGreaterThan=f.gt=function(t,e){return Ho(this,new S(t,e))>0},f.isGreaterThanOrEqualTo=f.gte=function(t,e){return 1===(e=Ho(this,new S(t,e)))||0===e},f.isInteger=function(){return!!this.c&&Uo(this.e/Bo)>this.c.length-2},f.isLessThan=f.lt=function(t,e){return Ho(this,new S(t,e))<0},f.isLessThanOrEqualTo=f.lte=function(t,e){return-1===(e=Ho(this,new S(t,e)))||0===e},f.isNaN=function(){return!this.s},f.isNegative=function(){return this.s<0},f.isPositive=function(){return this.s>0},f.isZero=function(){return!!this.c&&0==this.c[0]},f.minus=function(t,e){var n,r,i,o,s=this,a=s.s;if(e=(t=new S(t,e)).s,!a||!e)return new S(NaN);if(a!=e)return t.s=-e,s.plus(t);var u=s.e/Bo,l=t.e/Bo,h=s.c,c=t.c;if(!u||!l){if(!h||!c)return h?(t.s=-e,t):new S(c?s:NaN);if(!h[0]||!c[0])return c[0]?(t.s=-e,t):new S(h[0]?s:3==v?-0:0)}if(u=Uo(u),l=Uo(l),h=h.slice(),a=u-l){for((o=a<0)?(a=-a,i=h):(l=u,i=c),i.reverse(),e=a;e--;i.push(0));i.reverse()}else for(r=(o=(a=h.length)<(e=c.length))?a:e,a=e=0;e0)for(;e--;h[n++]=0);for(e=Go-1;r>a;){if(h[--r]=0;){for(n=0,f=_[i]%d,g=_[i]/d|0,o=i+(s=u);o>i;)n=((l=f*(l=m[--s]%d)+(a=g*l+(h=m[s]/d|0)*f)%d*d+p[o]+n)/v|0)+(a/d|0)+g*h,p[o--]=l%v;p[o]=n}return n?++r:p.splice(0,1),P(t,p,r)},f.negated=function(){var t=new S(this);return t.s=-t.s||null,t},f.plus=function(t,e){var n,r=this,i=r.s;if(e=(t=new S(t,e)).s,!i||!e)return new S(NaN);if(i!=e)return t.s=-e,r.minus(t);var o=r.e/Bo,s=t.e/Bo,a=r.c,u=t.c;if(!o||!s){if(!a||!u)return new S(i/0);if(!a[0]||!u[0])return u[0]?t:new S(a[0]?r:0*i)}if(o=Uo(o),s=Uo(s),a=a.slice(),i=o-s){for(i>0?(s=o,n=u):(i=-i,n=a),n.reverse();i--;n.push(0));n.reverse()}for((i=a.length)-(e=u.length)<0&&(n=u,u=a,a=n,e=i),i=0;e;)i=(a[--e]=a[e]+u[e]+i)/Go|0,a[e]=Go===a[e]?0:a[e]%Go;return i&&(a=[i].concat(a),++s),P(t,a,s)},f.precision=f.sd=function(t,e){var n,r,i,o=this;if(null!=t&&t!==!!t)return Wo(t,1,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t,e);if(!(n=o.c))return null;if(r=(i=n.length-1)*Bo+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return t&&o.e+1>r&&(r=o.e+1),r},f.shiftedBy=function(t){return Wo(t,-9007199254740991,Yo),this.times("1e"+t)},f.squareRoot=f.sqrt=function(){var t,e,r,i,o,s=this,a=s.c,u=s.s,l=s.e,h=p+4,c=new S("0.5");if(1!==u||!a||!a[0])return new S(!u||u<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(u=Math.sqrt(+T(s)))||u==1/0?(((e=Zo(a)).length+l)%2==0&&(e+="0"),u=Math.sqrt(+e),l=Uo((l+1)/2)-(l<0||l%2),r=new S(e=u==1/0?"5e"+l:(e=u.toExponential()).slice(0,e.indexOf("e")+1)+l)):r=new S(u+""),r.c[0])for((u=(l=r.e)+h)<3&&(u=0);;)if(o=r,r=c.times(o.plus(n(s,o,h,1))),Zo(o.c).slice(0,u)===(e=Zo(r.c)).slice(0,u)){if(r.e0&&p>0){for(o=p%a||a,h=g.substr(0,o);o0&&(h+=l+g.slice(o)),f&&(h="-"+h)}r=c?h+(n.decimalSeparator||"")+((u=+n.fractionGroupSize)?c.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):c):h}return(n.prefix||"")+r+(n.suffix||"")},f.toFraction=function(t){var e,r,i,o,s,a,u,l,h,c,f,p,d=this,y=d.c;if(null!=t&&(!(u=new S(t)).isInteger()&&(u.c||1!==u.s)||u.lt(g)))throw Error(qo+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+T(u));if(!y)return new S(d);for(e=new S(g),h=r=new S(g),i=l=new S(g),p=Zo(y),s=e.e=p.length-d.e-1,e.c[0]=zo[(a=s%Bo)<0?Bo+a:a],t=!t||u.comparedTo(e)>0?s>0?e:h:u,a=x,x=1/0,u=new S(p),l.c[0]=0;c=n(u,e,0,1),1!=(o=r.plus(c.times(i))).comparedTo(t);)r=i,i=o,h=l.plus(c.times(o=h)),l=o,e=u.minus(c.times(o=e)),u=o;return o=n(t.minus(r),i,0,1),l=l.plus(o.times(h)),r=r.plus(o.times(i)),l.s=h.s=d.s,f=n(h,i,s*=2,v).minus(d).abs().comparedTo(n(l,r,s,v).minus(d).abs())<1?[h,i]:[l,r],x=a,f},f.toNumber=function(){return+T(this)},f.toPrecision=function(t,e){return null!=t&&Wo(t,1,Xo),M(this,t,e,2)},f.toString=function(t){var e,n=this,i=n.s,o=n.e;return null===o?i?(e="Infinity",i<0&&(e="-"+e)):e="NaN":(null==t?e=o<=d||o>=y?Ko(Zo(n.c),o):Qo(Zo(n.c),o,"0"):10===t&&N?e=Qo(Zo((n=C(new S(n),p+o+1,v)).c),n.e,"0"):(Wo(t,2,I.length,"Base"),e=r(Qo(Zo(n.c),o,"0"),10,t,i,!0)),i<0&&n.c[0]&&(e="-"+e)),e},f.valueOf=f.toJSON=function(){return T(this)},f._isBigNumber=!0,f[Symbol.toStringTag]="BigNumber",f[Symbol.for("nodejs.util.inspect.custom")]=f.valueOf,null!=e&&S.set(e),S}(),ts=function(t){function e(t){return i(this,e),r(this,e,[t])}return h(e,t),s(e)}(s((function t(e){i(this,t),u(this,"key",void 0),u(this,"left",null),u(this,"right",null),this.key=e}))),es=function(){return s((function t(){i(this,t),u(this,"size",0),u(this,"modificationCount",0),u(this,"splayCount",0)}),[{key:"splay",value:function(t){var e=this.root;if(null==e)return this.compare(t,t),-1;for(var n,r=null,i=null,o=null,s=null,a=e,u=this.compare;;)if((n=u(a.key,t))>0){var l=a.left;if(null==l)break;if((n=u(l.key,t))>0&&(a.left=l.right,l.right=a,null==(l=(a=l).left)))break;null==r?i=a:r.left=a,r=a,a=l}else{if(!(n<0))break;var h=a.right;if(null==h)break;if((n=u(h.key,t))<0&&(a.right=h.left,h.left=a,null==(h=(a=h).right)))break;null==o?s=a:o.right=a,o=a,a=h}return null!=o&&(o.right=a.left,a.left=s),null!=r&&(r.left=a.right,a.right=i),this.root!==a&&(this.root=a,this.splayCount++),n}},{key:"splayMin",value:function(t){for(var e=t,n=e.left;null!=n;){var r=n;e.left=r.right,r.right=e,n=(e=r).left}return e}},{key:"splayMax",value:function(t){for(var e=t,n=e.right;null!=n;){var r=n;e.right=r.left,r.left=e,n=(e=r).right}return e}},{key:"_delete",value:function(t){if(null==this.root)return null;if(0!=this.splay(t))return null;var e=this.root,n=e,r=e.left;if(this.size--,null==r)this.root=e.right;else{var i=e.right;(e=this.splayMax(r)).right=i,this.root=e}return this.modificationCount++,n}},{key:"addNewRoot",value:function(t,e){this.size++,this.modificationCount++;var n=this.root;null!=n?(e<0?(t.left=n,t.right=n.right,n.right=null):(t.right=n,t.left=n.left,n.left=null),this.root=t):this.root=t}},{key:"_first",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMin(t),this.root)}},{key:"_last",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMax(t),this.root)}},{key:"clear",value:function(){this.root=null,this.size=0,this.modificationCount++}},{key:"has",value:function(t){return this.validKey(t)&&0==this.splay(t)}},{key:"defaultCompare",value:function(){return function(t,e){return te?1:0}}},{key:"wrap",value:function(){var t=this;return{getRoot:function(){return t.root},setRoot:function(e){t.root=e},getSize:function(){return t.size},getModificationCount:function(){return t.modificationCount},getSplayCount:function(){return t.splayCount},setSplayCount:function(e){t.splayCount=e},splay:function(e){return t.splay(e)},has:function(e){return t.has(e)}}}}])}(),ns=function(t){function e(t,n){var o;return i(this,e),u(o=r(this,e),"root",null),u(o,"compare",void 0),u(o,"validKey",void 0),u(o,Symbol.toStringTag,"[object Set]"),o.compare=null!=t?t:o.defaultCompare(),o.validKey=null!=n?n:function(t){return null!=t&&null!=t},o}return h(e,t),s(e,[{key:"delete",value:function(t){return!!this.validKey(t)&&null!=this._delete(t)}},{key:"deleteAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.delete(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"forEach",value:function(t){for(var e,n=this[Symbol.iterator]();!(e=n.next()).done;)t(e.value,e.value,this)}},{key:"add",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this}},{key:"addAndReturn",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this.root.key}},{key:"addAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.add(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"isEmpty",value:function(){return null==this.root}},{key:"isNotEmpty",value:function(){return null!=this.root}},{key:"single",value:function(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}},{key:"first",value:function(){if(0==this.size)throw"Bad state: No element";return this._first().key}},{key:"last",value:function(){if(0==this.size)throw"Bad state: No element";return this._last().key}},{key:"lastBefore",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)<0)return this.root.key;var e=this.root.left;if(null==e)return null;for(var n=e.right;null!=n;)n=(e=n).right;return e.key}},{key:"firstAfter",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)>0)return this.root.key;var e=this.root.right;if(null==e)return null;for(var n=e.left;null!=n;)n=(e=n).left;return e.key}},{key:"retainAll",value:function(t){var n,r=new e(this.compare,this.validKey),i=this.modificationCount,o=a(t);try{for(o.s();!(n=o.n()).done;){var s=n.value;if(i!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(s)&&0==this.splay(s)&&r.add(this.root.key)}}catch(t){o.e(t)}finally{o.f()}r.size!=this.size&&(this.root=r.root,this.size=r.size,this.modificationCount++)}},{key:"lookup",value:function(t){return this.validKey(t)?0!=this.splay(t)?null:this.root.key:null}},{key:"intersection",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)&&r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"difference",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)||r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"union",value:function(t){var e=this.clone();return e.addAll(t),e}},{key:"clone",value:function(){var t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}},{key:"copyNode",value:function(t){if(null==t)return null;var e=new ts(t.key);return function t(e,n){var r,i;do{if(r=e.left,i=e.right,null!=r){var o=new ts(r.key);n.left=o,t(r,o)}if(null!=i){var s=new ts(i.key);n.right=s,e=i,n=s}}while(null!=i)}(t,e),e}},{key:"toSet",value:function(){return this.clone()}},{key:"entries",value:function(){return new os(this.wrap())}},{key:"keys",value:function(){return this[Symbol.iterator]()}},{key:"values",value:function(){return this[Symbol.iterator]()}},{key:Symbol.iterator,value:function(){return new is(this.wrap())}}])}(es),rs=function(){return s((function t(e){i(this,t),u(this,"tree",void 0),u(this,"path",new Array),u(this,"modificationCount",null),u(this,"splayCount",void 0),this.tree=e,this.splayCount=e.getSplayCount()}),[{key:Symbol.iterator,value:function(){return this}},{key:"next",value:function(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}},{key:"current",value:function(){if(!this.path.length)return null;var t=this.path[this.path.length-1];return this.getValue(t)}},{key:"rebuildPath",value:function(t){this.path.splice(0,this.path.length),this.tree.splay(t),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}},{key:"findLeftMostDescendent",value:function(t){for(;null!=t;)this.path.push(t),t=t.left}},{key:"moveNext",value:function(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();for(var t=this.tree.getRoot();null!=t;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);var e=this.path[this.path.length-1],n=e.right;if(null!=n){for(;null!=n;)this.path.push(n),n=n.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}}])}(),is=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return t.key}}])}(rs),os=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return[t.key,t.key]}}])}(rs),ss=function(t){return function(){return t}},as=function(t){var e=t?function(e,n){return n.minus(e).abs().isLessThanOrEqualTo(t)}:ss(!1);return function(t,n){return e(t,n)?0:t.comparedTo(n)}};function us(t){var e=t?function(e,n,r,i,o){return e.exponentiatedBy(2).isLessThanOrEqualTo(i.minus(n).exponentiatedBy(2).plus(o.minus(r).exponentiatedBy(2)).times(t))}:ss(!1);return function(t,n,r){var i=t.x,o=t.y,s=r.x,a=r.y,u=o.minus(a).times(n.x.minus(s)).minus(i.minus(s).times(n.y.minus(a)));return e(u,i,o,s,a)?0:u.comparedTo(0)}}var ls=function(t){return t},hs=function(t){if(t){var e=new ns(as(t)),n=new ns(as(t)),r=function(t,e){return e.addAndReturn(t)},i=function(t){return{x:r(t.x,e),y:r(t.y,n)}};return i({x:new $o(0),y:new $o(0)}),i}return ls},cs=function(t){return{set:function(t){fs=cs(t)},reset:function(){return cs(t)},compare:as(t),snap:hs(t),orient:us(t)}},fs=cs(),gs=function(t,e){return t.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(t.ur.x)&&t.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(t.ur.y)},ps=function(t,e){if(e.ur.x.isLessThan(t.ll.x)||t.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(t.ll.y)||t.ur.y.isLessThan(e.ll.y))return null;var n=t.ll.x.isLessThan(e.ll.x)?e.ll.x:t.ll.x,r=t.ur.x.isLessThan(e.ur.x)?t.ur.x:e.ur.x;return{ll:{x:n,y:t.ll.y.isLessThan(e.ll.y)?e.ll.y:t.ll.y},ur:{x:r,y:t.ur.y.isLessThan(e.ur.y)?t.ur.y:e.ur.y}}},vs=function(t,e){return t.x.times(e.y).minus(t.y.times(e.x))},ds=function(t,e){return t.x.times(e.x).plus(t.y.times(e.y))},ys=function(t){return ds(t,t).sqrt()},ms=function(t,e,n){var r={x:e.x.minus(t.x),y:e.y.minus(t.y)},i={x:n.x.minus(t.x),y:n.y.minus(t.y)};return ds(i,r).div(ys(i)).div(ys(r))},_s=function(t,e,n){return e.y.isZero()?null:{x:t.x.plus(e.x.div(e.y).times(n.minus(t.y))),y:n}},xs=function(t,e,n){return e.x.isZero()?null:{x:n,y:t.y.plus(e.y.div(e.x).times(n.minus(t.x)))}},Es=function(){function t(e,n){i(this,t),u(this,"point",void 0),u(this,"isLeft",void 0),u(this,"segment",void 0),u(this,"otherSE",void 0),u(this,"consumedBy",void 0),void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}return s(t,[{key:"link",value:function(t){if(t.point===this.point)throw new Error("Tried to link already linked events");for(var e=t.point.events,n=0,r=e.length;n0&&(t=r)}for(var i=t.segment.prevInResult(),o=i?i.prevInResult():null;;){if(!i)return null;if(!o)return i.ringOut;var s,a;if(o.ringOut!==i.ringOut)return(null===(s=o.ringOut)||void 0===s?void 0:s.enclosingRing())!==i.ringOut?i.ringOut:null===(a=i.ringOut)||void 0===a?void 0:a.enclosingRing();i=o.prevInResult(),o=i?i.prevInResult():null}}}],[{key:"factory",value:function(e){for(var n=[],r=0,i=e.length;r1&&void 0!==arguments[1]?arguments[1]:Ls.compare;i(this,t),u(this,"queue",void 0),u(this,"tree",void 0),u(this,"segments",void 0),this.queue=e,this.tree=new ns(n),this.segments=[]}),[{key:"process",value:function(t){var e=t.segment,n=[];if(t.consumedBy)return t.isLeft?this.queue.delete(t.otherSE):this.tree.delete(e),n;t.isLeft&&this.tree.add(e);var r=e,i=e;do{r=this.tree.lastBefore(r)}while(null!=r&&null!=r.consumedBy);do{i=this.tree.firstAfter(i)}while(null!=i&&null!=i.consumedBy);if(t.isLeft){var o=null;if(r){var s=r.getIntersection(e);if(null!==s&&(e.isAnEndpoint(s)||(o=s),!r.isAnEndpoint(s)))for(var a=this._splitSafely(r,s),u=0,l=a.length;u0?(this.tree.delete(e),n.push(t)):(this.segments.push(e),e.prev=r)}else{if(r&&i){var _=r.getIntersection(i);if(null!==_){if(!r.isAnEndpoint(_))for(var x=this._splitSafely(r,_),E=0,k=x.length;E0&&a.swapEvents(),Es.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}},{key:"swapEvents",value:function(){var t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(var e=0,n=this.windings.length;e0){var o=n;n=r,r=o}if(n.prev===r){var s=n;n=r,r=s}for(var a=0,u=r.rings.length;a0)return-1;var c=e.comparePoint(t.rightSE.point);return 0!==c?c:-1}if(n.isGreaterThan(r)){if(s.isLessThan(a)&&s.isLessThan(l))return-1;if(s.isGreaterThan(a)&&s.isGreaterThan(l))return 1;var f=e.comparePoint(t.leftSE.point);if(0!==f)return f;var g=t.comparePoint(e.rightSE.point);return g<0?1:g>0?-1:1}if(s.isLessThan(a))return-1;if(s.isGreaterThan(a))return 1;if(i.isLessThan(o)){var p=e.comparePoint(t.rightSE.point);if(0!==p)return p}if(i.isGreaterThan(o)){var v=t.comparePoint(e.rightSE.point);if(v<0)return 1;if(v>0)return-1}if(!i.eq(o)){var d=u.minus(s),y=i.minus(n),m=l.minus(a),_=o.minus(r);if(d.isGreaterThan(y)&&m.isLessThan(_))return 1;if(d.isLessThan(y)&&m.isGreaterThan(_))return-1}return i.isGreaterThan(o)?1:i.isLessThan(o)||u.isLessThan(l)?-1:u.isGreaterThan(l)?1:t.ide.id?1:0}},{key:"fromRing",value:function(e,n,r){var i,o,s,a=Es.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else{if(!(a>0))throw new Error("Tried to create degenerate segment at [".concat(e.x,", ").concat(e.y,"]"));i=n,o=e,s=-1}return new t(new Es(i,!0),new Es(o,!1),[r],[s])}}])}(),Ps=function(){return s((function t(e,n,r){if(i(this,t),u(this,"poly",void 0),u(this,"isExterior",void 0),u(this,"segments",void 0),u(this,"bbox",void 0),!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");var o=fs.snap({x:new $o(e[0][0]),y:new $o(e[0][1])});this.bbox={ll:{x:o.x,y:o.y},ur:{x:o.x,y:o.y}};for(var s=o,a=1,l=e.length;a1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r2&&void 0!==arguments[2]?arguments[2]:2,r=K(t),i=K(e),o=r[0]-i[0],s=r[1]-i[1];return 1===n?Math.abs(o)+Math.abs(s):Math.pow(Math.pow(o,n)+Math.pow(s,n),1/n)}function Gs(t,e){var n,r,i=(e=e||{}).threshold||1e4,o=e.p||2,s=null!=(n=e.binary)&&n,a=e.alpha||-1,u=null!=(r=e.standardization)&&r,l=[];vt(t,(function(t){l.push(gi(t))}));for(var h=[],c=0;c3&&void 0!==arguments[3]?arguments[3]:{},i=e<0,o=j(Math.abs(e),r.units,"meters");i&&(o=-Math.abs(o));var s=K(t),a=function(t,e,n,r){r=void 0===r?x:Number(r);var i=e/r,o=t[0]*Math.PI/180,s=z(t[1]),a=z(n),u=i*Math.cos(a),l=s+u;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);var h=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),c=Math.abs(h)>1e-11?u/h:Math.cos(s),f=i*Math.sin(a)/c;return[(180*(o+f)/Math.PI+540)%360-180,180*l/Math.PI]}(s,o,n);return a[0]+=a[0]-s[0]>180?-360:s[0]-a[0]>180?360:0,I(a,r.properties)}function Ys(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e);i[0]+=i[0]-r[0]>180?-360:r[0]-i[0]>180?360:0;var o=function(t,e,n){var r=n=void 0===n?x:Number(n),i=t[1]*Math.PI/180,o=e[1]*Math.PI/180,s=o-i,a=Math.abs(e[0]-t[0])*Math.PI/180;a>Math.PI&&(a-=2*Math.PI);var u=Math.log(Math.tan(o/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),l=Math.abs(u)>1e-11?s/u:Math.cos(i);return Math.sqrt(s*s+l*l*a*a)*r}(r,i);return j(o,"meters",n.units)}function zs(t,e,n){if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.pivot,i=n.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("angle is required");if(0===e)return t;var o=null!=r?r:gi(t);return!1!==i&&void 0!==i||(t=Ai(t)),ct(t,(function(t){var n=lt(o,t)+e,r=Ys(o,t),i=Q(Bs(o,r,n));t[0]=i[0],t[1]=i[1]})),t}function js(t,e,n,r){var i=(r=r||{}).steps||64,o=r.units||"kilometers",s=r.angle||0,a=r.pivot||t,u=r.properties||{};if(!t)throw new Error("center is required");if(!e)throw new Error("xSemiAxis is required");if(!n)throw new Error("ySemiAxis is required");if(!Z(r))throw new Error("options must be an object");if(!U(i))throw new Error("steps must be a number");if(!U(s))throw new Error("angle must be a number");var l=K(t);if("degrees"!==o){var h=Bs(t,e,90,{units:o}),c=Bs(t,n,0,{units:o});e=K(h)[0]-l[0],n=K(c)[1]-l[1]}for(var f=[],g=0;g=-270&&(v=-v),p<-180&&p>=-360&&(d=-d),"degrees"===o){var y=z(s),m=v*Math.cos(y)+d*Math.sin(y),_=d*Math.cos(y)-v*Math.sin(y);v=m,d=_}f.push([v+l[0],d+l[1]])}return f.push(f[0]),"degrees"===o?S([f],u):zs(S([f],u),s,{pivot:a})}function Xs(t){var e=t*Math.PI/180;return Math.tan(e)}function Us(t){return Vt(Rt(t))}function Zs(t){var e=[];return"FeatureCollection"===t.type?vt(t,(function(t){ct(t,(function(n){e.push(I(n,t.properties))}))})):"Feature"===t.type?ct(t,(function(n){e.push(I(n,t.properties))})):ct(t,(function(t){e.push(I(t))})),C(e)}var Hs=Math.PI/180,Ws=180/Math.PI,Js=function(t,e){this.lon=t,this.lat=e,this.x=Hs*t,this.y=Hs*e};Js.prototype.view=function(){return String(this.lon).slice(0,4)+","+String(this.lat).slice(0,4)},Js.prototype.antipode=function(){var t=-1*this.lat,e=this.lon<0?180+this.lon:-1*(180-this.lon);return new Js(e,t)};var Ks=function(){this.coords=[],this.length=0};Ks.prototype.move_to=function(t){this.length++,this.coords.push(t)};var Qs=function(t){this.properties=t||{},this.geometries=[]};Qs.prototype.json=function(){if(this.geometries.length<=0)return{geometry:{type:"LineString",coordinates:null},type:"Feature",properties:this.properties};if(1===this.geometries.length)return{geometry:{type:"LineString",coordinates:this.geometries[0].coords},type:"Feature",properties:this.properties};for(var t=[],e=0;e1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must specify at least 2 geometries");var r=Rs.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)}function ea(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.stringify(n.properties||{}),i=v(t,4),o=i[0],s=i[1],a=i[2],u=i[3],l=(s+u)/2,h=(o+a)/2,c=2*e/ut([o,l],[a,l],n)*(a-o),f=2*e/ut([h,s],[h,u],n)*(u-s),g=c/2,p=2*g,d=Math.sqrt(3)/2*f,y=a-o,m=u-s,_=3/4*p,x=d,E=(y-p)/(p-g/2),k=Math.floor(E),b=(k*_-g/2-y)/2-g/2+_/2,w=Math.floor((m-d)/d),I=(m-w*d)/2,N=w*d-m>d/2;N&&(I-=d/4);for(var S=[],M=[],L=0;L<6;L++){var P=2*Math.PI/6*L;S.push(Math.cos(P)),M.push(Math.sin(P))}for(var T=[],O=0;O<=k;O++)for(var R=0;R<=w;R++){var A=O%2==1;if((0!==R||!A)&&(0!==R||!N)){var D=O*_+o-b,F=R*x+s+I;if(A&&(F-=d/2),!0===n.triangles)ra([D,F],c/2,f/2,JSON.parse(r),S,M).forEach((function(t){n.mask?ta(C([n.mask,t]))&&T.push(t):T.push(t)}));else{var q=na([D,F],c/2,f/2,JSON.parse(r),S,M);n.mask?ta(C([n.mask,q]))&&T.push(q):T.push(q)}}}return C(T)}function na(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=t[0]+e*i[a],l=t[1]+n*o[a];s.push([u,l])}return s.push(s[0].slice()),S([s],r)}function ra(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=[];u.push(t),u.push([t[0]+e*i[a],t[1]+n*o[a]]),u.push([t[0]+e*i[(a+1)%6],t[1]+n*o[(a+1)%6]]),u.push(t),s.push(S([u],r))}return s}function ia(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.mask&&!n.units&&(n.units="kilometers");for(var r=[],i=t[0],o=t[1],s=t[2],a=t[3],u=e/ut([i,o],[s,o],n)*(s-i),l=e/ut([i,o],[i,a],n)*(a-o),h=s-i,c=a-o,f=Math.floor(h/u),g=(c-Math.floor(c/l)*l)/2,p=i+(h-f*u)/2;p<=s;){for(var v=o+g;v<=a;){var d=I([p,v],n.properties);n.mask?Cn(d,n.mask)&&r.push(d):r.push(d),v+=l}p+=u}return C(r)}function oa(t,e,n){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=[],o=t[0],s=t[1],a=t[2],u=t[3],l=a-o,h=j(e,r.units,"degrees"),c=u-s,f=j(n,r.units,"degrees"),g=Math.floor(Math.abs(l)/h),p=Math.floor(Math.abs(c)/f),v=(c-p*f)/2,d=o+(l-g*h)/2,y=0;y2&&void 0!==arguments[2]?arguments[2]:{})}function aa(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=[],i=e/ut([t[0],t[1]],[t[2],t[1]],n)*(t[2]-t[0]),o=e/ut([t[0],t[1]],[t[0],t[3]],n)*(t[3]-t[1]),s=0,a=t[0];a<=t[2];){for(var u=0,l=t[1];l<=t[3];){var h=null,c=null;s%2==0&&u%2==0?(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)):s%2==0&&u%2==1?(h=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties)):u%2==0&&s%2==1?(h=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties),c=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties)):u%2==1&&s%2==1&&(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)),n.mask?(ta(C([n.mask,h]))&&r.push(h),ta(C([n.mask,c]))&&r.push(c)):(r.push(h),r.push(c)),l+=o,u++}s++,a+=i}return C(r)} +/*! + * MarchingSquaresJS + * version 1.3.3 + * https://github.com/RaumZeit/MarchingSquares.js + * + * @license GNU Affero General Public License. + * Copyright (c) 2015-2019 Ronny Lorenz + */ +function ua(t,e,n){return tr&&(i=n,n=r,r=i),tr?(t-r)/(t-e):(t-n)/(t-e)}function ha(t,e,n,r){return t1){for(;0!==o;)o>>=1,a++;r===1<1){for(;0!==s;)s>>=1,u++;i===1<0&&(this.childB=new da(t,e+o,n,r-o,s),this.lowerBound=Math.min(this.lowerBound,this.childB.lowerBound),this.upperBound=Math.max(this.upperBound,this.childB.upperBound),i-s>0&&(this.childC=new da(t,e+o,n+s,r-o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childC.lowerBound),this.upperBound=Math.max(this.upperBound,this.childC.upperBound))),i-s>0&&(this.childD=new da(t,e,n+s,o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childD.lowerBound),this.upperBound=Math.max(this.upperBound,this.childD.upperBound))}}function ya(t){var e,n;if(!t)throw new Error("data is required");if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Error("data must be scalar field, i.e. array of arrays");if(t.length<2)throw new Error("data must contain at least two rows");if((n=t[0].length)<2)throw new Error("data must contain at least two columns");for(e=1;e=e||t[s][r-1]>=e){n=!1;break}if(n&&(t[i-1][0]>=e||t[i-1][r-1]>=e)&&(n=!1),n)for(o=0;o=e||t[i-1][o]>e){n=!1;break}return n}(t,n.threshold)&&(n.linearRing?_.push([[0,0],[0,x],[E,x],[E,0],[0,0]]):_.push([[0,0],[0,x],[E,x],[E,0]])),e.forEach((function(t,N){t.forEach((function(t,S){for(r=null,i=0;i<4;i++)if(r=k[i],"object"===m(t.edges[r])){for(a=[],o=t.edges[r],u=r,l=N,h=S,c=!1,f=[N+o.path[0][0],S+o.path[0][1]],a.push(f);!c&&"object"===m((s=e[l][h]).edges[u]);)if(o=s.edges[u],delete s.edges[u],(g=o.path[1])[0]+=l,g[1]+=h,a.push(g),u=o.move.enter,l+=o.move.x,h+=o.move.y,void 0===e[l]||void 0===e[l][h]){if(!n.linearRing)break;if(p=0,v=0,l===E?(l--,p=0):l<0?(l++,p=2):h===x?(h--,p=3):h<0&&(h++,p=1),l===N&&h===S&&p===I[r]){c=!0,u=r;break}for(;;){if(d=!1,v>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[l]&&void 0!==e[l][h]&&(s=e[l][h],y=k[p],"object"===m(s.edges[y]))){o=s.edges[y],a.push(pa(l,h,p,o.path)),u=y,d=!0;break}if(d)break;if(a.push(va(l,h,p)),h+=w[p],void 0!==e[l+=b[p]]&&void 0!==e[l][h]||(0===p&&h<0||1===p&&l<0||2===p&&h===x||3===p&&l===E)&&(l-=b[p],h-=w[p],p=(p+1)%4,v++),l===N&&h===S&&p===I[r]){c=!0,u=r;break}}}!n.linearRing||a[a.length-1][0]===f[0]&&a[a.length-1][1]===f[1]||a.push(f),_.push(a)}}))})),_}(h,c,r)}a?g.push(f):g=f,"function"==typeof r.successCallback&&r.successCallback(g,t)})),g}function _a(t,e,n,r){var i,o,s,a,u,l,h=0,c=t[n+1][e],f=t[n+1][e+1],g=t[n][e+1],p=t[n][e],v=r.threshold;if(!(isNaN(p)||isNaN(g)||isNaN(f)||isNaN(c))){switch(h|=c>=v?8:0,h|=f>=v?4:0,h|=g>=v?2:0,l={cval:h=+(h|=p>=v?1:0),polygons:[],edges:{},x0:p,x1:g,x2:f,x3:c},h){case 0:r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,0]]);break;case 15:break;case 14:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.left={path:[[0,i],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[a,0]]);break;case 13:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[a,0],[1,o],[1,0]]);break;case 11:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[1,o],[s,1],[1,1]]);break;case 7:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[s,1],[0,i],[0,1]]);break;case 1:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[a,0],[0,i],[0,1],[1,1],[1,0]]);break;case 2:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,o],[a,0]]);break;case 4:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[1,o],[1,0]]);break;case 8:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[s,1],[1,1],[1,0]]);break;case 12:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[1,o],[1,0]]);break;case 9:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[a,0],[s,1],[1,1],[1,0]]);break;case 3:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[0,i],[0,1],[1,1],[1,o]]);break;case 6:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[a,0]]);break;case 10:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),u=(p+g+f+c)/4,r.polygons_full&&(uf&&(v>h&&ph&&vu&&(u=d)}var y=[];if(a&&u0&&Math.abs(x-n[_-1][0])>f){var E=parseFloat(n[_-1][0]),k=parseFloat(n[_-1][1]),b=parseFloat(n[_][0]),w=parseFloat(n[_][1]);if(E>-180&&E-180&&n[_-1][0]h&&E<180&&-180===b&&_+1h&&n[_-1][0]<180){m.push([180,n[_][1]]),_++,m.push([n[_][0],n[_][1]]);continue}if(Eh){var I=E;E=b,b=I;var N=k;k=w,w=N}if(E>h&&b=180&&Eh?180:-180,M]),(m=[]).push([n[_-1][0]>h?-180:180,M]),y.push(m)}else m=[],y.push(m);m.push([x,n[_][1]])}else m.push([n[_][0],n[_][1]])}}else{var L=[];y.push(L);for(var P=0;Pe||this.upperBound=e)&&r.push({x:this.x,y:this.y})),r},da.prototype.cellsBelowThreshold=function(t,e){var n=[];return e=void 0===e||e,this.lowerBound>t||(this.childA||this.childB||this.childC||this.childD?(this.childA&&(n=n.concat(this.childA.cellsBelowThreshold(t,e))),this.childB&&(n=n.concat(this.childB.cellsBelowThreshold(t,e))),this.childD&&(n=n.concat(this.childD.cellsBelowThreshold(t,e))),this.childC&&(n=n.concat(this.childC.cellsBelowThreshold(t,e)))):(e||this.upperBound>=t)&&n.push({x:this.x,y:this.y})),n};var xa={square:function(t,e,n,r,i,o){o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,0]])},triangle_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,a],[s,0],[0,0]])},triangle_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[1,a],[1,0]])},triangle_tr:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[1,s],[a,1],[1,1]])},triangle_tl:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[s,1]])},tetragon_t:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[1,1],[1,s]])},tetragon_r:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[a,1],[1,1],[1,0]])},tetragon_b:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,0]])},tetragon_l:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[a,0]])},tetragon_bl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[a,0]])},tetragon_br:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate_b(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[1,l]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[1,l],[1,u],[a,0]])},tetragon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rb={path:[[1,l],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}}),o.polygons&&t.polygons.push([[1,l],[s,1],[a,1],[1,u]])},tetragon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[0,l]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[a,1],[0,l],[0,u],[s,1]])},tetragon_lr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[1,u],[1,l]])},tetragon_tb:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[l,0],[s,1],[a,1],[u,0]])},pentagon_tr:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[1,a],[1,0]])},pentagon_tl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,0]])},pentagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,a],[s,0]])},pentagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[a,0],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[1,1],[1,0],[a,0]])},pentagon_tr_rl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[1,u],[1,l]])},pentagon_rb_bt:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,n,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[u,0],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[l,1],[1,1],[1,s],[a,0],[u,0]])},pentagon_bl_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[1,l],[1,0]])},pentagon_lt_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[l,0]])},pentagon_bl_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[l,0],[0,s]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[u,0],[l,0]])},pentagon_lt_rl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[u,1],[1,1],[1,l]])},pentagon_tr_bt:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,1],[a,1],[1,u],[1,0],[l,0]])},pentagon_rb_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_b(n,r,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,u],[l,0]])},hexagon_lt_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[1,l],[1,0]])},hexagon_bl_lt:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[1,1],[1,0]])},hexagon_bl_rb:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.rt={path:[[1,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[1,1],[1,l],[a,0]])},hexagon_tr_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[a,1],[1,u],[1,l],[s,0]])},hexagon_lt_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,u],[l,0]])},hexagon_bl_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,1],[u,1],[1,l],[1,0]])},heptagon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[1,1],[1,c],[a,0]])},heptagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate_a(i,r,o.minV,o.maxV),l=o.interpolate_b(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,a],[u,1],[l,1],[1,h],[1,c],[s,0]])},heptagon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[l,1],[1,h],[1,c],[a,0]])},heptagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(i,r,o.minV,o.maxV),h=o.interpolate_b(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[h,1],[1,c]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[h,1],[1,c],[1,0]])},octagon:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate_a(i,r,o.minV,o.maxV),c=o.interpolate_b(i,r,o.minV,o.maxV),f=o.interpolate_b(n,r,o.minV,o.maxV),g=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[c,1],[1,f]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,g],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[c,1],[1,f],[1,g],[a,0]])}};function Ea(t,e,n,r){var i,o,s,a=!1,u=null,l=null,h=null,c=null,f=!1,g=[],p=[],v=[];if(!t)throw new Error("data is required");if(null==e)throw new Error("lowerBound is required");if(null==n)throw new Error("bandWidth is required");if(s=function(t){var e,n,r,i,o;for(i=new fa,t=t||{},o=Object.keys(i),e=0;en||t[a][i-1]n){r=!1;break}if(r&&(t[o-1][0]n||t[o-1][i-1]n)&&(r=!1),r)for(s=0;sn||t[o-1][s]n){r=!1;break}return r}(t,n.minV,n.maxV)&&(n.linearRing?x.push([[0,0],[0,E],[k,E],[k,0],[0,0]]):x.push([[0,0],[0,E],[k,E],[k,0]])),e.forEach((function(t,M){t.forEach((function(t,L){for(r=null,o=0;o<8;o++)if(r=N[o],"object"===m(t.edges[r])){for(i=[],s=t.edges[r],l=r,h=M,c=L,f=!1,g=[M+s.path[0][0],L+s.path[0][1]],i.push(g);!f&&"object"===m((p=e[h][c]).edges[l]);)if(s=p.edges[l],delete p.edges[l],(y=s.path[1])[0]+=h,y[1]+=c,i.push(y),l=s.move.enter,h+=s.move.x,c+=s.move.y,void 0===e[h]||void 0===e[h][c]){if(v=0,d=0,h===k)h--,v=0;else if(h<0)h++,v=2;else if(c===E)c--,v=3;else{if(!(c<0))throw new Error("Left the grid somewhere in the interior!");c++,v=1}if(h===M&&c===L&&v===S[r]){f=!0,l=r;break}for(;;){if(_=!1,d>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[h]&&void 0!==e[h][c])for(p=e[h][c],a=0;ao?2:sf?128:64,s|=uf?32:16,s|=lf?8:4,o=0,i={cval:s=+(s|=hf?2:1),polygons:[],edges:{},x0:h,x1:l,x2:u,x3:a,x:e,y:n},s){case 85:xa.square(i,h,l,u,a,r);case 0:case 170:break;case 169:xa.triangle_bl(i,h,l,u,a,r);break;case 166:xa.triangle_br(i,h,l,u,a,r);break;case 154:xa.triangle_tr(i,h,l,u,a,r);break;case 106:xa.triangle_tl(i,h,l,u,a,r);break;case 1:xa.triangle_bl(i,h,l,u,a,r);break;case 4:xa.triangle_br(i,h,l,u,a,r);break;case 16:xa.triangle_tr(i,h,l,u,a,r);break;case 64:xa.triangle_tl(i,h,l,u,a,r);break;case 168:xa.tetragon_bl(i,h,l,u,a,r);break;case 162:xa.tetragon_br(i,h,l,u,a,r);break;case 138:xa.tetragon_tr(i,h,l,u,a,r);break;case 42:xa.tetragon_tl(i,h,l,u,a,r);break;case 2:xa.tetragon_bl(i,h,l,u,a,r);break;case 8:xa.tetragon_br(i,h,l,u,a,r);break;case 32:xa.tetragon_tr(i,h,l,u,a,r);break;case 128:xa.tetragon_tl(i,h,l,u,a,r);break;case 5:xa.tetragon_b(i,h,l,u,a,r);break;case 20:xa.tetragon_r(i,h,l,u,a,r);break;case 80:xa.tetragon_t(i,h,l,u,a,r);break;case 65:xa.tetragon_l(i,h,l,u,a,r);break;case 165:xa.tetragon_b(i,h,l,u,a,r);break;case 150:xa.tetragon_r(i,h,l,u,a,r);break;case 90:xa.tetragon_t(i,h,l,u,a,r);break;case 105:xa.tetragon_l(i,h,l,u,a,r);break;case 160:xa.tetragon_lr(i,h,l,u,a,r);break;case 130:xa.tetragon_tb(i,h,l,u,a,r);break;case 10:xa.tetragon_lr(i,h,l,u,a,r);break;case 40:xa.tetragon_tb(i,h,l,u,a,r);break;case 101:xa.pentagon_tr(i,h,l,u,a,r);break;case 149:xa.pentagon_tl(i,h,l,u,a,r);break;case 86:xa.pentagon_bl(i,h,l,u,a,r);break;case 89:xa.pentagon_br(i,h,l,u,a,r);break;case 69:xa.pentagon_tr(i,h,l,u,a,r);break;case 21:xa.pentagon_tl(i,h,l,u,a,r);break;case 84:xa.pentagon_bl(i,h,l,u,a,r);break;case 81:xa.pentagon_br(i,h,l,u,a,r);break;case 96:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 24:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 6:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 129:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 74:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 146:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 164:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 41:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 66:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 144:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 36:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 9:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 104:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 26:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 134:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 161:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 37:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 148:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 82:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 73:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 133:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 22:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 88:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 97:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 145:case 25:xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 70:case 100:xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 17:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 68:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 153:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 102:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 152:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 137:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 98:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 38:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 18:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 33:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 72:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 132:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 136:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r));break;case 34:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r))}return i}}var wa=Object.defineProperty,Ia=Object.getOwnPropertySymbols,Na=Object.prototype.hasOwnProperty,Sa=Object.prototype.propertyIsEnumerable,Ma=function(t,e,n){return e in t?wa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},La=function(t,e){for(var n in e||(e={}))Na.call(e,n)&&Ma(t,n,e[n]);if(Ia){var r,i=a(Ia(e));try{for(i.s();!(r=i.n()).done;){n=r.value;Sa.call(e,n)&&Ma(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t};function Pa(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.zProperty||"elevation",r=e.flip,i=e.flags;nt(t,"Point","input must contain Points");for(var o=function(t,e){var n={};vt(t,(function(t){var e=Q(t)[1];n[e]||(n[e]=[]),n[e].push(t)}));var r=Object.keys(n).map((function(t){return n[t].sort((function(t,e){return Q(t)[0]-Q(e)[0]}))})),i=r.sort((function(t,n){return e?Q(t[0])[1]-Q(n[0])[1]:Q(n[0])[1]-Q(t[0])[1]}));return i}(t,r),s=[],a=0;a=0&&l<=1&&(f.onLine1=!0),h>=0&&h<=1&&(f.onLine2=!0),!(!f.onLine1||!f.onLine2)&&[f.x,f.y])}function za(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return bt(t,(function(t,n){var r=n.geometry.coordinates;return t+ut(r[0],r[1],e)}),0)}function ja(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=i.steps||64,s=Xa(n),a=Xa(r),u=Array.isArray(t)||"Feature"!==t.type?{}:t.properties;if(s===a)return L(Ri(t,e,i).geometry.coordinates[0],u);for(var l=s,h=s=h&&c===i.length-1);c++){if(h>e&&0===o.length){if(!(s=e-h))return o.push(i[c]),L(o);a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates)}if(h>=n)return(s=n-h)?(a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates),L(o)):(o.push(i[c]),L(o));if(h>=e&&o.push(i[c]),c===i.length-1)return L(o);h+=ut(i[c],i[c+1],r)}if(h0){var a=r[e-1],u=Wa(n,a);!1!==u&&(a[1]=u,n[0]=u),s.push(a[0]),e===o.length-2&&(s.push(n[0]),s.push(n[1]))}2===o.length&&(s.push(n[0]),s.push(n[1]))}var l,h,c,f,g,p,v,d})),L(s,t.properties)}function Ka(t){var e=t[0],n=t[1],r=t[2],i=t[3];if(ut(t.slice(0,2),[r,n])>=ut(t.slice(0,2),[e,i])){var o=(n+i)/2;return[e,o-(r-e)/2,r,o+(r-e)/2]}var s=(e+r)/2;return[s-(i-n)/2,n,s+(i-n)/2,i]}function Qa(t,e){if(!Z(e=null!=e?e:{}))throw new Error("options is invalid");var n=e.precision,r=e.coordinates,i=e.mutate;if(n=null==n||isNaN(n)?6:n,r=null==r||isNaN(r)?3:r,!t)throw new Error(" is required");if("number"!=typeof n)throw new Error(" must be a number");if("number"!=typeof r)throw new Error(" must be a number");!1!==i&&void 0!==i||(t=JSON.parse(JSON.stringify(t)));var o=Math.pow(10,n);return ct(t,(function(t){!function(t,e,n){t.length>n&&t.splice(n,t.length);for(var r=0;r1&&n.push(L(l)),C(n)}function eu(t,e){if(!e.features.length)throw new Error("lines must contain features");if(1===e.features.length)return e.features[0];var n,r=1/0;return vt(e,(function(e){var i=fn(e,t).properties.dist;iu?(a.unshift(t),u=e):a.push(t)}else a.push(t)})),S(a,e);default:throw new Error("geometry type "+s+" is not supported")}}function iu(t){var e=t[0],n=e[0],r=e[1],i=t[t.length-1],o=i[0],s=i[1];return n===o&&r===s||t.push(e),t}function ou(t){return R(t)}function su(t){var e=[[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]];return t&&(e="Feature"===t.type?t.geometry.coordinates:t.coordinates),S(e)}function au(t){var e,n=0,r=a(t);try{for(r.s();!(e=r.n()).done;){n+=e.value}}catch(t){r.e(t)}finally{r.f()}return n/t.length}var uu=Object.defineProperty,lu=Object.defineProperties,hu=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,fu=Object.prototype.hasOwnProperty,gu=Object.prototype.propertyIsEnumerable,pu=function(t,e,n){return e in t?uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},vu=function(t,e){for(var n in e||(e={}))fu.call(e,n)&&pu(t,n,e[n]);if(cu){var r,i=a(cu(e));try{for(i.s();!(r=i.n()).done;){n=r.value;gu.call(e,n)&&pu(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},du=function(t,e){return lu(t,hu(e))};function yu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("targetPoint is required");if(!e)throw new Error("points is required");var r=1/0,i=0;vt(e,(function(e,o){var s=ut(t,e,n);s2&&void 0!==arguments[2]?arguments[2]:{},o=null!=(n=i.method)?n:"geodesic",s=null!=(r=i.units)?r:"kilometers";if(!t)throw new Error("pt is required");if(Array.isArray(t)?t=I(t):"Point"===t.type?t=b(t):et(t,"Point","point"),!e)throw new Error("line is required");Array.isArray(e)?e=L(e):"LineString"===e.type?e=b(e):et(e,"LineString","line");var a=1/0,u=t.geometry.coordinates;return kt(e,(function(t){if(t){var e=t.geometry.coordinates[0],n=t.geometry.coordinates[1],r=function(t,e,n,r){if("geodesic"===r.method){return fn(L([e,n]).geometry,t,{units:"degrees"}).properties.dist}var i=[n[0]-e[0],n[1]-e[1]],o=[t[0]-e[0],t[1]-e[1]],s=_u(o,i);if(s<=0)return Ys(t,e,{units:"degrees"});var a=_u(i,i);if(a<=s)return Ys(t,n,{units:"degrees"});var u=s/a,l=[e[0]+u*i[0],e[1]+u*i[1]];return Ys(t,l,{units:"degrees"})}(u,e,n,{method:o});r0)-(t<0)||+t}(r*(n[1]-e[1])-o*i)}function Lu(t,e){return e.geometry.coordinates[0].every((function(e){return zt(I(e),t)}))}var Pu=function(){return s((function t(e){i(this,t),this.id=t.buildId(e),this.coordinates=e,this.innerEdges=[],this.outerEdges=[],this.outerEdgesSorted=!1}),[{key:"removeInnerEdge",value:function(t){this.innerEdges=this.innerEdges.filter((function(e){return e.from.id!==t.from.id}))}},{key:"removeOuterEdge",value:function(t){this.outerEdges=this.outerEdges.filter((function(e){return e.to.id!==t.to.id}))}},{key:"addOuterEdge",value:function(t){this.outerEdges.push(t),this.outerEdgesSorted=!1}},{key:"sortOuterEdges",value:function(){var t=this;this.outerEdgesSorted||(this.outerEdges.sort((function(e,n){var r=e.to,i=n.to;if(r.coordinates[0]-t.coordinates[0]>=0&&i.coordinates[0]-t.coordinates[0]<0)return 1;if(r.coordinates[0]-t.coordinates[0]<0&&i.coordinates[0]-t.coordinates[0]>=0)return-1;if(r.coordinates[0]-t.coordinates[0]==0&&i.coordinates[0]-t.coordinates[0]==0)return r.coordinates[1]-t.coordinates[1]>=0||i.coordinates[1]-t.coordinates[1]>=0?r.coordinates[1]-i.coordinates[1]:i.coordinates[1]-r.coordinates[1];var o=Mu(t.coordinates,r.coordinates,i.coordinates);return o<0?1:o>0?-1:Math.pow(r.coordinates[0]-t.coordinates[0],2)+Math.pow(r.coordinates[1]-t.coordinates[1],2)-(Math.pow(i.coordinates[0]-t.coordinates[0],2)+Math.pow(i.coordinates[1]-t.coordinates[1],2))})),this.outerEdgesSorted=!0)}},{key:"getOuterEdges",value:function(){return this.sortOuterEdges(),this.outerEdges}},{key:"getOuterEdge",value:function(t){return this.sortOuterEdges(),this.outerEdges[t]}},{key:"addInnerEdge",value:function(t){this.innerEdges.push(t)}}],[{key:"buildId",value:function(t){return t.join(",")}}])}(),Cu=function(){function t(e,n){i(this,t),this.from=e,this.to=n,this.next=void 0,this.label=void 0,this.symetric=void 0,this.ring=void 0,this.from.addOuterEdge(this),this.to.addInnerEdge(this)}return s(t,[{key:"getSymetric",value:function(){return this.symetric||(this.symetric=new t(this.to,this.from),this.symetric.symetric=this),this.symetric}},{key:"deleteEdge",value:function(){this.from.removeOuterEdge(this),this.to.removeInnerEdge(this)}},{key:"isEqual",value:function(t){return this.from.id===t.from.id&&this.to.id===t.to.id}},{key:"toString",value:function(){return"Edge { ".concat(this.from.id," -> ").concat(this.to.id," }")}},{key:"toLineString",value:function(){return L([this.from.coordinates,this.to.coordinates])}},{key:"compareTo",value:function(t){return Mu(t.from.coordinates,t.to.coordinates,this.to.coordinates)}}])}(),Tu=function(){return s((function t(){i(this,t),this.edges=[],this.polygon=void 0,this.envelope=void 0}),[{key:"push",value:function(t){this.edges.push(t),this.polygon=this.envelope=void 0}},{key:"get",value:function(t){return this.edges[t]}},{key:"length",get:function(){return this.edges.length}},{key:"forEach",value:function(t){this.edges.forEach(t)}},{key:"map",value:function(t){return this.edges.map(t)}},{key:"some",value:function(t){return this.edges.some(t)}},{key:"isValid",value:function(){return!0}},{key:"isHole",value:function(){var t=this,e=this.edges.reduce((function(e,n,r){return n.from.coordinates[1]>t.edges[e].from.coordinates[1]&&(e=r),e}),0),n=(0===e?this.length:e)-1,r=(e+1)%this.length,i=Mu(this.edges[n].from.coordinates,this.edges[e].from.coordinates,this.edges[r].from.coordinates);return 0===i?this.edges[n].from.coordinates[0]>this.edges[r].from.coordinates[0]:i>0}},{key:"toMultiPoint",value:function(){return O(this.edges.map((function(t){return t.from.coordinates})))}},{key:"toPolygon",value:function(){if(this.polygon)return this.polygon;var t=this.edges.map((function(t){return t.from.coordinates}));return t.push(this.edges[0].from.coordinates),this.polygon=S([t])}},{key:"getEnvelope",value:function(){return this.envelope?this.envelope:this.envelope=Us(this.toPolygon())}},{key:"inside",value:function(t){return zt(t,this.toPolygon())}}],[{key:"findEdgeRingContaining",value:function(t,e){var n,r,i=t.getEnvelope();return e.forEach((function(e){var o,s,u,l,h,c,f=e.getEnvelope();if((r&&(n=r.getEnvelope()),s=i,u=(o=f).geometry.coordinates[0].map((function(t){return t[0]})),l=o.geometry.coordinates[0].map((function(t){return t[1]})),h=s.geometry.coordinates[0].map((function(t){return t[0]})),c=s.geometry.coordinates[0].map((function(t){return t[1]})),Math.max.apply(null,u)!==Math.max.apply(null,h)||Math.max.apply(null,l)!==Math.max.apply(null,c)||Math.min.apply(null,u)!==Math.min.apply(null,h)||Math.min.apply(null,l)!==Math.min.apply(null,c))&&Lu(f,i)){var g,p,v=a(t.map((function(t){return t.from.coordinates})));try{var d=function(){var t=p.value;e.some((function(e){return n=t,r=e.from.coordinates,n[0]===r[0]&&n[1]===r[1];var n,r}))||(g=t)};for(v.s();!(p=v.n()).done;)d()}catch(t){v.e(t)}finally{v.f()}g&&e.inside(I(g))&&(r&&!Lu(n,f)||(r=e))}})),r}}])}();var Ou=function(){function t(){i(this,t),this.edges=[],this.nodes={}}return s(t,[{key:"getNode",value:function(t){var e=Pu.buildId(t),n=this.nodes[e];return n||(n=this.nodes[e]=new Pu(t)),n}},{key:"addEdge",value:function(t,e){var n=new Cu(t,e),r=n.getSymetric();this.edges.push(n),this.edges.push(r)}},{key:"deleteDangles",value:function(){var t=this;Object.keys(this.nodes).map((function(e){return t.nodes[e]})).forEach((function(e){return t._removeIfDangle(e)}))}},{key:"_removeIfDangle",value:function(t){var e=this;if(t.innerEdges.length<=1){var n=t.getOuterEdges().map((function(t){return t.to}));this.removeNode(t),n.forEach((function(t){return e._removeIfDangle(t)}))}}},{key:"deleteCutEdges",value:function(){var t=this;this._computeNextCWEdges(),this._findLabeledEdgeRings(),this.edges.forEach((function(e){e.label===e.symetric.label&&(t.removeEdge(e.symetric),t.removeEdge(e))}))}},{key:"_computeNextCWEdges",value:function(t){var e=this;void 0===t?Object.keys(this.nodes).forEach((function(t){return e._computeNextCWEdges(e.nodes[t])})):t.getOuterEdges().forEach((function(e,n){t.getOuterEdge((0===n?t.getOuterEdges().length:n)-1).symetric.next=e}))}},{key:"_computeNextCCWEdges",value:function(t,e){for(var n,r,i=t.getOuterEdges(),o=i.length-1;o>=0;--o){var s=i[o],a=s.symetric,u=void 0,l=void 0;s.label===e&&(u=s),a.label===e&&(l=a),u&&l&&(l&&(r=l),u&&(r&&(r.next=u,r=void 0),n||(n=u)))}r&&(r.next=n)}},{key:"_findLabeledEdgeRings",value:function(){var t=[],e=0;return this.edges.forEach((function(n){if(!(n.label>=0)){t.push(n);var r=n;do{r.label=e,r=r.next}while(!n.isEqual(r));e++}})),t}},{key:"getEdgeRings",value:function(){var t=this;this._computeNextCWEdges(),this.edges.forEach((function(t){t.label=void 0})),this._findLabeledEdgeRings().forEach((function(e){t._findIntersectionNodes(e).forEach((function(n){t._computeNextCCWEdges(n,e.label)}))}));var e=[];return this.edges.forEach((function(n){n.ring||e.push(t._findEdgeRing(n))})),e}},{key:"_findIntersectionNodes",value:function(t){var e=[],n=t,r=function(){var r=0;n.from.getOuterEdges().forEach((function(e){e.label===t.label&&++r})),r>1&&e.push(n.from),n=n.next};do{r()}while(!t.isEqual(n));return e}},{key:"_findEdgeRing",value:function(t){var e=t,n=new Tu;do{n.push(e),e.ring=n,e=e.next}while(!t.isEqual(e));return n}},{key:"removeNode",value:function(t){var e=this;t.getOuterEdges().forEach((function(t){return e.removeEdge(t)})),t.innerEdges.forEach((function(t){return e.removeEdge(t)})),delete this.nodes[t.id]}},{key:"removeEdge",value:function(t){this.edges=this.edges.filter((function(e){return!e.isEqual(t)})),t.deleteEdge()}}],[{key:"fromGeoJson",value:function(e){!function(t){if(!t)throw new Error("No geojson passed");if("FeatureCollection"!==t.type&&"GeometryCollection"!==t.type&&"MultiLineString"!==t.type&&"LineString"!==t.type&&"Feature"!==t.type)throw new Error("Invalid input type '".concat(t.type,"'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature"))}(e);var n=new t;return xt(e,(function(t){et(t,"LineString","Graph::fromGeoJson"),ft(t,(function(t,e){if(t){var r=n.getNode(t),i=n.getNode(e);n.addEdge(r,i)}return e}))})),n}}])}();function Ru(t,e){var n,r;ct(t,(function(t,i,o,s,a){if(r!==a)e.push([]);else{var u=n[0],l=n[1],h=t[0],c=t[1];e[a].push([.75*u+.25*h,.75*l+.25*c]),e[a].push([.25*u+.75*h,.25*l+.75*c])}n=t,r=a}),!1),e.forEach((function(t){t.push(t[0])}))}function Au(t,e){var n,r,i;ct(t,(function(t,o,s,a,u){if(r!==a)e.push([[]]);else if(i!==u)e[a].push([]);else{var l=n[0],h=n[1],c=t[0],f=t[1];e[a][u].push([.75*l+.25*c,.75*h+.25*f]),e[a][u].push([.25*l+.75*c,.25*h+.75*f])}n=t,r=a,i=u}),!1),e.forEach((function(t){t.forEach((function(t){t.push(t[0])}))}))}function Du(t,e,n,r,i){for(var o=0;o0?qu(e,s,r)<0||(r=s):n>0&&u<=0&&(Fu(e,s,i)||(i=s)),n=u}return[r,i]}function Fu(t,e,n){return qu(t,e,n)>0}function qu(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(n[0]-t[0])*(e[1]-t[1])}function Vu(t){return Bu(t,"mercator",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Gu(t){return Bu(t,"wgs84",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Bu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=(n=n||{}).mutate;if(!t)throw new Error("geojson is required");return Array.isArray(t)&&U(t[0])?t="mercator"===e?Yu(t):zu(t):(!0!==r&&(t=Ai(t)),ct(t,(function(t){var n="mercator"===e?Yu(t):zu(t);t[0]=n[0],t[1]=n[1]}))),t}function Yu(t){var e=Math.PI/180,n=6378137,r=20037508.342789244,i=Math.abs(t[0])<=180?t[0]:t[0]-360*function(t){return t<0?-1:t>0?1:0}(t[0]),o=[n*i*e,n*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return o[0]>r&&(o[0]=r),o[0]<-r&&(o[0]=-r),o[1]>r&&(o[1]=r),o[1]<-r&&(o[1]=-r),o}function zu(t){var e=180/Math.PI,n=6378137;return[t[0]*e/n,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/n)))*e]}var ju=Object.freeze({__proto__:null,toMercator:Vu,toWgs84:Gu});var Xu={20:1.07275,15:1.13795,10:1.22385,5:1.3581,2:1.51743,1:1.62762};function Uu(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}function Zu(t){var e=[];return function t(n){return 0===n||1===n?1:e[n]>0?e[n]:e[n]=t(n-1)*n}(t)}function Hu(t){return Ju(t),Wu(t)}function Wu(t){return Array.isArray(t)?el(t):t&&t.bbox?el(t.bbox):[360*tl(),180*tl()]}function Ju(t){null!=t&&(Array.isArray(t)?H(t):null!=t.bbox&&H(t.bbox))}function Ku(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1);for(var n=[],r=0;r1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1),void 0!==e.bbox&&null!==e.bbox||(e.bbox=[-180,-90,180,90]),U(e.num_vertices)&&void 0!==e.num_vertices||(e.num_vertices=10),U(e.max_radial_length)&&void 0!==e.max_radial_length||(e.max_radial_length=10);var n=Math.abs(e.bbox[0]-e.bbox[2]),r=Math.abs(e.bbox[1]-e.bbox[3]),i=Math.min(n/2,r/2);if(e.max_radial_length>i)throw new Error("max_radial_length is greater than the radius of the bbox");for(var o=[e.bbox[0]+e.max_radial_length,e.bbox[1]+e.max_radial_length,e.bbox[2]-e.max_radial_length,e.bbox[3]-e.max_radial_length],s=[],a=function(){var t,n=[],r=d(Array(e.num_vertices+1)).map(Math.random);r.forEach((function(t,e,n){n[e]=e>0?t+n[e-1]:t})),r.forEach((function(t){t=2*t*Math.PI/r[r.length-1];var i=Math.random();n.push([i*(e.max_radial_length||10)*Math.sin(t),i*(e.max_radial_length||10)*Math.cos(t)])})),n[n.length-1]=n[0],n=n.reverse().map((t=Wu(o),function(e){return[e[0]+t[0],e[1]+t[1]]})),s.push(S([n]))},u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox;Ju(n);var r=e.num_vertices,i=e.max_length,o=e.max_rotation;null==t&&(t=1),(!U(r)||void 0===r||r<2)&&(r=10),U(i)&&void 0!==i||(i=1e-4),U(o)&&void 0!==o||(o=Math.PI/8);for(var s=[],a=0;a0;){var l=a.pop();if(l===n)return ll(l);l.closed=!0;for(var h=t.neighbors(l),c=0,f=h.length;c1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function dl(t,e,n,r,i){for(var o,s=r,a=e+1;as&&(o=a,s=u)}s>r&&(o-e>1&&dl(t,e,o,r,i),i.push(t[o]),n-o>1&&dl(t,o,n,r,i))}function yl(t,e){var n=t.length-1,r=[t[0]];return dl(t,0,n,e,r),r.push(t[n]),r}function ml(t,e,n){if(t.length<=2)return t;var r=void 0!==e?e*e:1;return t=n?t:function(t,e){for(var n,r,i,o,s,a=t[0],u=[a],l=1,h=t.length;le&&(u.push(n),a=n);return a!==n&&u.push(n),u}(t,r),t=yl(t,r)}function _l(t,e,n){return t.map((function(t){if(t.length<4)throw new Error("invalid polygon");for(var r=e,i=ml(t,r,n);!xl(i);)i=ml(t,r-=.01*r,n);return i[i.length-1][0]===i[0][0]&&i[i.length-1][1]===i[0][1]||i.push(i[0]),i}))}function xl(t){return!(t.length<3)&&!(3===t.length&&t[2][0]===t[0][0]&&t[2][1]===t[0][1])}function El(t,e){return{x:t[0]-e[0],y:t[1]-e[1]}}cl.prototype.init=function(){this.dirtyNodes=[];for(var t=0;t0&&(this.content[0]=e,this.bubbleUp(0)),t},remove:function(t){var e=this.content.indexOf(t),n=this.content.pop();e!==this.content.length-1&&(this.content[e]=n,this.scoreFunction(n)0;){var n=(t+1>>1)-1,r=this.content[n];if(!(this.scoreFunction(e)80*i){o=a=t[0],s=h=t[1];for(var _=i;_a&&(a=c),g>h&&(h=g);p=0!==(p=Math.max(a-o,h-s))?32767/p:0}return r(y,m,i,o,s,p,0),m}function e(t,e,n,r,i){var o,s;if(i===I(t,e,n,r)>0)for(o=e;o=e;o-=r)s=k(o,t[o],t[o+1],s);return s&&d(s,s.next)&&(b(s),s=s.next),s}function n(t,e){if(!t)return t;e||(e=t);var n,r=t;do{if(n=!1,r.steiner||!d(r,r.next)&&0!==v(r.prev,r,r.next))r=r.next;else{if(b(r),(r=e=r.prev)===r.next)break;n=!0}}while(n||r!==e);return e}function r(t,e,u,l,h,f,g){if(t){!g&&f&&function(t,e,n,r){var i=t;do{0===i.z&&(i.z=c(i.x,i.y,e,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,n,r,i,o,s,a,u,l=1;do{for(n=t,t=null,o=null,s=0;n;){for(s++,r=n,a=0,e=0;e0||u>0&&r;)0!==a&&(0===u||!r||n.z<=r.z)?(i=n,n=n.nextZ,a--):(i=r,r=r.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;n=r}o.nextZ=null,l*=2}while(s>1)}(i)}(t,l,h,f);for(var p,v,d=t;t.prev!==t.next;)if(p=t.prev,v=t.next,f?o(t,l,h,f):i(t))e.push(p.i/u|0),e.push(t.i/u|0),e.push(v.i/u|0),b(t),t=v.next,d=v.next;else if((t=v)===d){g?1===g?r(t=s(n(t),e,u),e,u,l,h,f,2):2===g&&a(t,e,u,l,h,f):r(n(t),e,u,l,h,f,1);break}}}function i(t){var e=t.prev,n=t,r=t.next;if(v(e,n,r)>=0)return!1;for(var i=e.x,o=n.x,s=r.x,a=e.y,u=n.y,l=r.y,h=io?i>s?i:s:o>s?o:s,p=a>u?a>l?a:l:u>l?u:l,d=r.next;d!==e;){if(d.x>=h&&d.x<=f&&d.y>=c&&d.y<=p&&g(i,a,o,u,s,l,d.x,d.y)&&v(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function o(t,e,n,r){var i=t.prev,o=t,s=t.next;if(v(i,o,s)>=0)return!1;for(var a=i.x,u=o.x,l=s.x,h=i.y,f=o.y,p=s.y,d=au?a>l?a:l:u>l?u:l,_=h>f?h>p?h:p:f>p?f:p,x=c(d,y,e,n,r),E=c(m,_,e,n,r),k=t.prevZ,b=t.nextZ;k&&k.z>=x&&b&&b.z<=E;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;if(k=k.prevZ,b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;k&&k.z>=x;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;k=k.prevZ}for(;b&&b.z<=E;){if(b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function s(t,e,r){var i=t;do{var o=i.prev,s=i.next.next;!d(o,s)&&y(o,i,i.next,s)&&x(o,s)&&x(s,o)&&(e.push(o.i/r|0),e.push(i.i/r|0),e.push(s.i/r|0),b(i),b(i.next),i=t=s),i=i.next}while(i!==t);return n(i)}function a(t,e,i,o,s,a){var u=t;do{for(var l=u.next.next;l!==u.prev;){if(u.i!==l.i&&p(u,l)){var h=E(u,l);return u=n(u,u.next),h=n(h,h.next),r(u,e,i,o,s,a,0),void r(h,e,i,o,s,a,0)}l=l.next}u=u.next}while(u!==t)}function u(t,e){return t.x-e.x}function l(t,e){var r=function(t,e){var n,r=e,i=t.x,o=t.y,s=-1/0;do{if(o<=r.y&&o>=r.next.y&&r.next.y!==r.y){var a=r.x+(o-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=i&&a>s&&(s=a,n=r.x=r.x&&r.x>=c&&i!==r.x&&g(on.x||r.x===n.x&&h(n,r)))&&(n=r,p=u)),r=r.next}while(r!==l);return n}(t,e);if(!r)return e;var i=E(r,t);return n(i,i.next),n(r,r.next)}function h(t,e){return v(t.prev,t,e.prev)<0&&v(e.next,t,t.next)<0}function c(t,e,n,r,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function f(t){var e=t,n=t;do{(e.x=(t-s)*(o-a)&&(t-s)*(r-a)>=(n-s)*(e-a)&&(n-s)*(o-a)>=(i-s)*(r-a)}function p(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&y(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(x(t,e)&&x(e,t)&&function(t,e){var n=t,r=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{n.y>o!=n.next.y>o&&n.next.y!==n.y&&i<(n.next.x-n.x)*(o-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==t);return r}(t,e)&&(v(t.prev,t,e.prev)||v(t,e.prev,e))||d(t,e)&&v(t.prev,t,t.next)>0&&v(e.prev,e,e.next)>0)}function v(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function d(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,n,r){var i=_(v(t,e,n)),o=_(v(t,e,r)),s=_(v(n,r,t)),a=_(v(n,r,e));return i!==o&&s!==a||(!(0!==i||!m(t,n,e))||(!(0!==o||!m(t,r,e))||(!(0!==s||!m(n,t,r))||!(0!==a||!m(n,e,r)))))}function m(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function _(t){return t>0?1:t<0?-1:0}function x(t,e){return v(t.prev,t,t.next)<0?v(t,e,t.next)>=0&&v(t,t.prev,e)>=0:v(t,e,t.prev)<0||v(t,t.next,e)<0}function E(t,e){var n=new w(t.i,t.x,t.y),r=new w(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,n.next=i,i.prev=n,r.next=n,n.prev=r,o.next=r,r.prev=o,r}function k(t,e,n,r){var i=new w(t,e,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function b(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 w(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function I(t,e,n,r){for(var i=0,o=e,s=n-r;o0&&(r+=t[i-1].length,n.holes.push(r))}return n},bl.exports}(),Il=mn(wl);function Nl(t){var e=function(t){for(var e=t[0][0].length,n={vertices:[],holes:[],dimensions:e},r=0,i=0;i0&&(r+=t[i-1].length,n.holes.push(r))}return n}(t),n=Il(e.vertices,e.holes,2),r=[],i=[];n.forEach((function(t,r){var o=n[r];i.push([e.vertices[2*o],e.vertices[2*o+1]])}));for(var o=0;o=1||u<=0||l>=1||l<=0))){var v=p,d=!o[v];d&&(o[v]=!0),e?i.push(e(p,t,n,h,c,u,s,a,f,g,l,d)):i.push(p)}}function v(t,e){var n,i,o,s,a=r[t][e],u=r[t][e+1];return a[0]f[e.isect].coord?-1:1}));for(l=[];x.length>0;){var I=x.pop(),N=I.isect,M=I.parent,L=I.winding,P=l.length,T=[f[N].coord],O=N;if(f[N].ringAndEdge1Walkable)var R=f[N].ringAndEdge1,A=f[N].nxtIsectAlongRingAndEdge1;else R=f[N].ringAndEdge2,A=f[N].nxtIsectAlongRingAndEdge2;for(;!Rl(f[N].coord,f[A].coord);){T.push(f[A].coord);var D=void 0;for(r=0;r1)for(e=0;e=0==e}function Ol(t){for(var e=0,n=0;n0)){if(o/=f,f<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=r-u,f||!(o<0)){if(o/=f,f<0){if(o>c)return;o>h&&(h=o)}else if(f>0){if(o0)){if(o/=g,g<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=i-l,g||!(o<0)){if(o/=g,g<0){if(o>c)return;o>h&&(h=o)}else if(g>0){if(o0||c<1)||(h>0&&(t[0]=[u+h*f,l+h*g]),c<1&&(t[1]=[u+c*f,l+c*g]),!0)}}}}}function Hl(t,e,n,r,i){var o=t[1];if(o)return!0;var s,a,u=t[0],l=t.left,h=t.right,c=l[0],f=l[1],g=h[0],p=h[1],v=(c+g)/2,d=(f+p)/2;if(p===f){if(v=r)return;if(c>g){if(u){if(u[1]>=i)return}else u=[v,n];o=[v,i]}else{if(u){if(u[1]1)if(c>g){if(u){if(u[1]>=i)return}else u=[(n-a)/s,n];o=[(i-a)/s,i]}else{if(u){if(u[1]=r)return}else u=[e,s*e+a];o=[r,s*r+a]}else{if(u){if(u[0]=-dh)){var g=u*u+l*l,p=h*h+c*c,v=(c*g-l*p)/f,d=(u*p-h*g)/f,y=$l.pop()||new th;y.arc=t,y.site=i,y.x=v+s,y.y=(y.cy=d+a)+Math.sqrt(v*v+d*d),t.circle=y;for(var m=null,_=gh._;_;)if(y.y<_.y||y.y===_.y&&y.x<=_.x){if(!_.L){m=_.P;break}_=_.L}else{if(!_.R){m=_;break}_=_.R}gh.insert(m,y),m||(Ql=y)}}}}function nh(t){var e=t.circle;e&&(e.P||(Ql=e.N),gh.remove(e),$l.push(e),Gl(e),t.circle=null)}var rh=[];function ih(){Gl(this),this.edge=this.site=this.circle=null}function oh(t){var e=rh.pop()||new ih;return e.site=t,e}function sh(t){nh(t),ch.remove(t),rh.push(t),Gl(t)}function ah(t){var e=t.circle,n=e.x,r=e.cy,i=[n,r],o=t.P,s=t.N,a=[t];sh(t);for(var u=o;u.circle&&Math.abs(n-u.circle.x)vh)a=a.L;else{if(!((i=o-hh(a,s))>vh)){r>-vh?(e=a.P,n=a):i>-vh?(e=a,n=a.N):e=n=a;break}if(!a.R){e=a;break}a=a.R}!function(t){fh[t.index]={site:t,halfedges:[]}}(t);var u=oh(t);if(ch.insert(e,u),e||n){if(e===n)return nh(e),n=oh(e.site),ch.insert(u,n),u.edge=n.edge=jl(e.site,u.site),eh(e),void eh(n);if(n){nh(e),nh(n);var l=e.site,h=l[0],c=l[1],f=t[0]-h,g=t[1]-c,p=n.site,v=p[0]-h,d=p[1]-c,y=2*(f*d-g*v),m=f*f+g*g,_=v*v+d*d,x=[(d*m-g*_)/y+h,(f*_-v*m)/y+c];Ul(n.edge,l,p,x),u.edge=jl(l,t,null,x),n.edge=jl(t,p,null,x),eh(e),eh(n)}else u.edge=jl(e.site,u.site)}}function lh(t,e){var n=t.site,r=n[0],i=n[1],o=i-e;if(!o)return r;var s=t.P;if(!s)return-1/0;var a=(n=s.site)[0],u=n[1],l=u-e;if(!l)return a;var h=a-r,c=1/o-1/l,f=h/l;return c?(-f+Math.sqrt(f*f-2*c*(h*h/(-2*l)-u+l/2+i-o/2)))/c+r:(r+a)/2}function hh(t,e){var n=t.N;if(n)return lh(n,e);var r=t.site;return r[1]===e?r[0]:1/0}var ch,fh,gh,ph,vh=1e-6,dh=1e-12;function yh(t,e){return e[1]-t[1]||e[0]-t[0]}function mh(t,e){var n,r,i,o=t.sort(yh).pop();for(ph=[],fh=new Array(t.length),ch=new Vl,gh=new Vl;;)if(i=Ql,o&&(!i||o[1]vh||Math.abs(i[0][1]-i[1][1])>vh)||delete ph[o]}(s,a,u,l),function(t,e,n,r){var i,o,s,a,u,l,h,c,f,g,p,v,d=fh.length,y=!0;for(i=0;ivh||Math.abs(v-f)>vh)&&(u.splice(a,0,ph.push(Xl(s,g,Math.abs(p-t)vh?[t,Math.abs(c-t)vh?[Math.abs(f-r)vh?[n,Math.abs(c-n)vh?[Math.abs(f-e)=a)return null;var u=t-i.site[0],l=e-i.site[1],h=u*u+l*l;do{i=o.cells[r=s],s=null,i.halfedges.forEach((function(n){var r=o.edges[n],a=r.left;if(a!==i.site&&a||(a=r.right)){var u=t-a[0],l=e-a[1],c=u*u+l*l;c2&&void 0!==arguments[2]?arguments[2]:{},r=rt(t).coordinates,i=0,o=0;o=i&&o===r.length-1);o++){if(i>=e){var s=e-i;if(s){var a=st(r[o],r[o-1])-180;return at(r[o],s,a,n)}return I(r[o])}i+=ut(r[o],r[o+1],n)}return I(r[r.length-1])},t.angle=function(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!Z(r))throw new Error("options is invalid");if(!t)throw new Error("startPoint is required");if(!e)throw new Error("midPoint is required");if(!n)throw new Error("endPoint is required");var i=t,o=e,s=n,a=G(!0!==r.mercator?st(o,i):lt(o,i)),u=G(!0!==r.mercator?st(o,s):lt(o,s));u1&&void 0!==arguments[1]?arguments[1]:{},n=e.resolution||1e4,r=e.sharpness||.85,i=[],o=rt(t).coordinates.map((function(t){return{x:t[0],y:t[1]}})),s=new Gt({duration:n,points:o,sharpness:r}),a=function(t){var e=s.pos(t);Math.floor(t/100)%2==0&&i.push([e.x,e.y])},u=0;u0;else if(n!==u>0)return!0}return!1},t.booleanContains=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type,s=n.coordinates,u=r.coordinates;switch(i){case"Point":if("Point"===o)return Ht(s,u);throw new Error("feature2 "+o+" geometry not supported");case"MultiPoint":switch(o){case"Point":return function(t,e){var n,r=!1;for(n=0;n2&&void 0!==arguments[2]?arguments[2]:{}).precision;if("number"!=typeof(n=null==n||isNaN(n)?6:n)||!(n>=0))throw new Error("precision must be a positive number");return rt(t).type===rt(e).type&&Ne(Le(t),Le(e),{precision:n})},t.booleanIntersects=Oe,t.booleanOverlap=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;if("MultiPoint"===i&&"MultiPoint"!==o||("LineString"===i||"MultiLineString"===i)&&"LineString"!==o&&"MultiLineString"!==o||("Polygon"===i||"MultiPolygon"===i)&&"Polygon"!==o&&"MultiPolygon"!==o)throw new Error("features must be of the same type");if("Point"===i)throw new Error("Point geometry not supported");if(Ne(t,e,{precision:6}))return!1;var s=0;switch(i){case"MultiPoint":for(var a=0;a0},t.booleanParallel=function(t,e){if(!t)throw new Error("line1 is required");if(!e)throw new Error("line2 is required");if("LineString"!==In(t,"line1"))throw new Error("line1 must be a LineString");if("LineString"!==In(e,"line2"))throw new Error("line2 must be a LineString");for(var n=$e(Le(t)).features,r=$e(Le(e)).features,i=0;i1;case"MultiPoint":for(var i=0;i0&&ue(S([r[0]]),S([r[i]])).features.length>1)return!1}return!0;case"MultiPolygon":for(i=0;i0&&ue(S([o[0]]),S([o[s]])).features.length>1)return!1}return!0;default:return!1}},t.booleanWithin=Cn,t.buffer=function(t,e,n){var r=(n=n||{}).units||"kilometers",i=n.steps||8;if(!t)throw new Error("geojson is required");if("object"!==m(n))throw new Error("options must be an object");if("number"!=typeof i)throw new Error("steps must be an number");if(void 0===e)throw new Error("radius is required");if(i<=0)throw new Error("steps must be greater than 0");var o=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){var n=ui(t,e,r,i);n&&o.push(n)})),C(o);case"FeatureCollection":return vt(t,(function(t){var n=ui(t,e,r,i);n&&vt(n,(function(t){t&&o.push(t)}))})),C(o)}return ui(t,e,r,i)},t.center=An,t.centerMean=fi,t.centerMedian=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.counter||10;if(!U(n))throw new Error("counter must be a number");var r=e.weight,i=fi(t,{weight:e.weight}),o=C([]);vt(t,(function(t){var e;o.features.push(gi(t,{properties:{weight:null==(e=t.properties)?void 0:e[r]}}))}));var s={tolerance:e.tolerance,medianCandidates:[]};return pi(i.geometry.coordinates,[0,0],o,s,n)},t.centerOfMass=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(it(e)){case"Point":return I(K(e),n.properties);case"Polygon":var r=[];ct(e,(function(t){r.push(t)}));var i,o,s,a,u,l,h,c,f=gi(e,{properties:n.properties}),g=f.geometry.coordinates,p=0,v=0,d=0,y=r.map((function(t){return[t[0]-g[0],t[1]-g[1]]}));for(i=0;i2&&void 0!==arguments[2]?arguments[2]:{};!0!==n.mutate&&(t=Ai(t));var r=n.minPoints||3,i=V(e,n.units),o=new to(t.features.length),s=t.features.map((function(t){return!1})),a=t.features.map((function(t){return!1})),u=t.features.map((function(t){return!1})),l=t.features.map((function(t){return-1}));o.load(t.features.map((function(t,e){var n=v(t.geometry.coordinates,2),r=n[0],i=n[1];return{minX:r,minY:i,maxX:r,maxY:i,index:e}})));var h=function(n){var r=t.features[n],s=v(r.geometry.coordinates,2),a=s[0],u=s[1],l=Math.max(u-i,-90),h=Math.min(u+i,90),c=l<0&&h>0?i:Math.abs(l)=r){var i=c;c++,s[e]=!0,function(t,e){for(var n=0;n=r&&e.push.apply(e,d(o))}a[i]||(a[i]=!0,l[i]=t)}}(i,n)}else u[e]=!0}})),t.features.forEach((function(e,n){var r=t.features[n];r.properties||(r.properties={}),l[n]>=0?(r.properties.dbscan=u[n]?"edge":"core",r.properties.cluster=l[n]):r.properties.dbscan="noise"})),t},t.clustersKmeans=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.features.length;e.numberOfClusters=e.numberOfClusters||Math.round(Math.sqrt(n/2)),e.numberOfClusters>n&&(e.numberOfClusters=n),!0!==e.mutate&&(t=Ai(t));var r=yt(t),i=r.slice(0,e.numberOfClusters),o=ro(r,e.numberOfClusters,i),s={};return o.centroids.forEach((function(t,e){s[e]=t})),vt(t,(function(t,e){var n=o.idxs[e];t.properties.cluster=n,t.properties.centroid=s[n]})),t},t.collect=function(t,e,n,r){var i=new io(6),o=e.features.map((function(t){var e;return{minX:t.geometry.coordinates[0],minY:t.geometry.coordinates[1],maxX:t.geometry.coordinates[0],maxY:t.geometry.coordinates[1],property:null==(e=t.properties)?void 0:e[n]}}));return i.load(o),t.features.forEach((function(t){t.properties||(t.properties={});var e=Rt(t),n=i.search({minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}),o=[];n.forEach((function(e){zt([e.minX,e.minY],t)&&o.push(e.property)})),t.properties[r]=o})),t},t.collectionOf=nt,t.combine=function(t){var e={MultiPoint:{coordinates:[],properties:[]},MultiLineString:{coordinates:[],properties:[]},MultiPolygon:{coordinates:[],properties:[]}};return vt(t,(function(t){var n,r,i,o;switch(null==(o=t.geometry)?void 0:o.type){case"Point":e.MultiPoint.coordinates.push(t.geometry.coordinates),e.MultiPoint.properties.push(t.properties);break;case"MultiPoint":(n=e.MultiPoint.coordinates).push.apply(n,d(t.geometry.coordinates)),e.MultiPoint.properties.push(t.properties);break;case"LineString":e.MultiLineString.coordinates.push(t.geometry.coordinates),e.MultiLineString.properties.push(t.properties);break;case"MultiLineString":(r=e.MultiLineString.coordinates).push.apply(r,d(t.geometry.coordinates)),e.MultiLineString.properties.push(t.properties);break;case"Polygon":e.MultiPolygon.coordinates.push(t.geometry.coordinates),e.MultiPolygon.properties.push(t.properties);break;case"MultiPolygon":(i=e.MultiPolygon.coordinates).push.apply(i,d(t.geometry.coordinates)),e.MultiPolygon.properties.push(t.properties)}})),C(Object.keys(e).filter((function(t){return e[t].coordinates.length})).sort().map((function(t){return b({type:t,coordinates:e[t].coordinates},{collectedProperties:e[t].properties})})))},t.concave=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.maxEdge||1/0,r=function(t){var e=[],n={};return vt(t,(function(t){if(t.geometry){var r=t.geometry.coordinates.join("-");Object.prototype.hasOwnProperty.call(n,r)||(e.push(t),n[r]=!0)}})),C(e)}(t),i=oo(r);if(i.features=i.features.filter((function(t){var r=t.geometry.coordinates[0][0],i=t.geometry.coordinates[0][1],o=t.geometry.coordinates[0][2],s=ut(r,i,e),a=ut(i,o,e),u=ut(r,o,e);return s<=n&&a<=n&&u<=n})),i.features.length<1)return null;var o=Ro(i);return 1===o.coordinates.length&&(o.coordinates=o.coordinates[0],o.type="Polygon"),b(o)},t.containsNumber=$,t.convertArea=X,t.convertLength=j,t.convex=Oi,t.coordAll=yt,t.coordEach=ct,t.coordReduce=ft,t.createBins=zi,t.degreesToRadians=z,t.destination=at,t.difference=function(t){var e=[];if(mt(t,(function(t){e.push(t.coordinates)})),e.length<2)throw new Error("Must have at least two features");var n=t.features[0].properties||{},r=As.apply(Fs,[e[0]].concat(d(e.slice(1))));return 0===r.length?null:1===r.length?S(r[0],n):R(r,n)},t.dissolve=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.propertyName;nt(t,"Polygon","dissolve");var r=[];if(!n)return qs(R(Os.apply(null,t.features.map((function(t){return t.geometry.coordinates})))));var i={};vt(t,(function(t){t.properties&&(Object.prototype.hasOwnProperty.call(i,t.properties[n])||(i[t.properties[n]]=[]),i[t.properties[n]].push(t))}));for(var o=Object.keys(i),s=0;s1&&void 0!==arguments[1]?arguments[1]:{},o=i.properties,s=null==(e=i.autoComplete)||e,a=null==(n=i.orderCoords)||n;if(null!=(r=i.mutate)&&r||(t=Ai(t)),"FeatureCollection"===t.type){var u=[];return t.features.forEach((function(t){u.push(Q(ru(t,{},s,a)))})),R(u,o)}return ru(t,o,s,a)},t.mask=function(t,e,n){var r,i=null!=(r=null==n?void 0:n.mutate)&&r,o=e;e&&!1===i&&(o=Ai(e));var s,a=su(o);return("FeatureCollection"===t.type?ou(2===(s=t).features.length?Os(s.features[0].geometry.coordinates,s.features[1].geometry.coordinates):Os.apply(Fs,s.features.map((function(t){return t.geometry.coordinates})))):"Feature"===t.type?ou(Os(t.geometry.coordinates)):ou(Os(t.coordinates))).geometry.coordinates.forEach((function(t){a.geometry.coordinates.push(t[0])})),a},t.meta=Mt,t.midpoint=function(t,e){return at(t,ut(t,e)/2,st(t,e))},t.moranIndex=function(t,e){var n,r,i=e.inputField,o=e.threshold||1e5,s=e.p||2,u=null!=(n=e.binary)&&n,l=Gs(t,{alpha:e.alpha||-1,binary:u,p:s,standardization:null==(r=e.standardization)||r,threshold:o}),h=[];vt(t,(function(t){var e=t.properties||{};h.push(e[i])}));for(var c=au(h),f=function(t){var e,n=au(t),r=0,i=a(t);try{for(i.s();!(e=i.n()).done;){var o=e.value;r+=Math.pow(o-n,2)}}catch(t){i.e(t)}finally{i.f()}return r/t.length}(h),g=0,p=0,v=0,d=0,y=l.length,m=0;m2&&void 0!==arguments[2]?arguments[2]:{},r=n.units,i=n.properties||{},o=function(t){var e=[];switch(t.geometry?t.geometry.type:t.type){case"GeometryCollection":return mt(t,(function(t){"Point"===t.type&&e.push({type:"Feature",properties:{},geometry:t})})),{type:"FeatureCollection",features:e};case"FeatureCollection":return t.features=t.features.filter((function(t){return"Point"===t.geometry.type})),t;default:throw new Error("points must be a Point Collection")}}(t);if(!o.features.length)throw new Error("points must contain features");if(!e)throw new Error("line is required");if("LineString"!==it(e))throw new Error("line must be a LineString");var s=1/0,a=null;return vt(o,(function(t){var n=mu(t,e,{units:r});n2&&void 0!==arguments[2]?arguments[2]:{},a=null!=(i=s.method)?i:"geodesic",u=null!=(o=s.units)?o:"kilometers";if(!e)throw new Error("point is required");if(!r)throw new Error("polygon or multi-polygon is required");var l,h=rt(r);if("MultiPolygon"===h.type){var c=h.coordinates.map((function(n){return t(e,S(n),{method:a,units:u})}));return Math.min.apply(Math,d(c.map(Math.abs)))*(zt(e,r)?-1:1)}if(h.coordinates.length>1){var p=h.coordinates.map((function(n){return t(e,S([n]),{method:a,units:u})})),v=n(l=p)||f(l)||_(l)||g(),y=v[0],m=v.slice(1);if(y>=0)return y;var x=Math.min.apply(Math,d(m));return x<0?Math.abs(x):Math.min(x,Math.abs(y))}var E=le(h),k=1/0;return xt(E,(function(t){k=Math.min(k,mu(e,t,{method:a,units:u}))})),zt(e,h)?-k:k},t.points=N,t.pointsWithinPolygon=Su,t.polygon=S,t.polygonSmooth=function(t,e){(e=e||{}).iterations=e.iterations||1;var n=e.iterations,r=[];if(!t)throw new Error("inputPolys is required");return mt(t,(function(t,e,i){if("Polygon"===t.type){for(var o=[[]],s=0;s0&&(u=S(o).geometry),Ru(u,a),o=a.slice(0)}r.push(S(o,i))}else{if("MultiPolygon"!==t.type)throw new Error("geometry is invalid, must be Polygon or MultiPolygon");for(var l=[[[]]],h=0;h0&&(f=R(l).geometry),Au(f,c),l=c.slice(0)}r.push(R(l,i))}})),C(r)},t.polygonTangents=function(t,e){var n,r=Q(t),i=Q(e),o=[],s=[],a=Rt(e),u=0,l=null;switch(r[0]>a[0]&&r[0]a[1]&&r[1]_&&(_=k)}for(var b=[],w=Object.keys(l).length,I=f/w,N=0,S=0;S<_+1;S++)N+=Math.exp(-I)*Math.pow(I,S)/Zu(S),b.push(N);for(var M=[],L=0,P=0;P<_+1;P++){for(var C=0,T=Object.keys(l);CR&&(R=D)}var F=Xu[r]/Math.sqrt(w),q={criticalValue:F,isRandom:!0,maxAbsoluteDifference:R,observedDistribution:M};return R>F&&(q.isRandom=!1),q},t.radiansToDegrees=Y,t.radiansToLength=F,t.random=nl,t.randomLineString=$u,t.randomPoint=Ku,t.randomPolygon=Qu,t.randomPosition=Hu,t.rectangleGrid=oa,t.rewind=function(t){var e,n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(r=r||{}))throw new Error("options is invalid");var i=null!=(e=r.mutate)&&e,o=null!=(n=r.reverse)&&n;if(!t)throw new Error(" is required");if("boolean"!=typeof o)throw new Error(" must be a boolean");if("boolean"!=typeof i)throw new Error(" must be a boolean");i||"Point"===t.type||"MultiPoint"===t.type||(t=Ai(t));var s=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){rl(t,o)})),t;case"FeatureCollection":return vt(t,(function(t){vt(rl(t,o),(function(t){s.push(t)}))})),C(s)}return rl(t,o)},t.rhumbBearing=lt,t.rhumbDestination=Bs,t.rhumbDistance=Ys,t.round=D,t.sample=function(t,e){if(!t)throw new Error("fc is required");if(null==e)throw new Error("num is required");if("number"!=typeof e)throw new Error("num must be a number");var n=C(function(t,e){var n,r,i=t.slice(0),o=t.length,s=o-e;for(;o-- >s;)n=i[r=Math.floor((o+1)*Math.random())],i[r]=i[o],i[o]=n;return i.slice(s)}(t.features,e));return n},t.sector=function(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!Z(i=i||{}))throw new Error("options is invalid");var o=i.properties;if(!t)throw new Error("center is required");if(null==n)throw new Error("bearing1 is required");if(null==r)throw new Error("bearing2 is required");if(!e)throw new Error("radius is required");if("object"!==m(i))throw new Error("options must be an object");if(sl(n)===sl(r))return Ri(t,e,i);var s=Q(t),a=ja(t,e,n,r,i),u=[[s]];return ct(a,(function(t){u[0].push(t)})),u[0].push(s),S(u,o)},t.segmentEach=kt,t.segmentReduce=bt,t.shortestPath=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.obstacles||C([]),i=n.resolution||100;if(!t)throw new Error("start is required");if(!e)throw new Error("end is required");if(i&&(!U(i)||i<=0))throw new Error("options.resolution must be a number, greater than 0");var o=K(t),s=K(e);if(t=I(o),e=I(s),"FeatureCollection"===r.type){if(0===r.features.length)return L([o,s])}else{if("Polygon"!==r.type)throw new Error("invalid obstacles");r=C([b(rt(r))])}var a=r;a.features.push(t),a.features.push(e);var u=v(Rt(al(Vt(Rt(a)),1.15)),4),l=u[0],h=u[1],c=u[2],f=u[3],g=ut([l,h],[c,h],n)/i;a.features.pop(),a.features.pop();for(var p,d,y=g/ut([l,h],[c,h],n)*(c-l),m=g/ut([l,h],[l,f],n)*(f-h),_=c-l,x=f-h,E=Math.floor(_/y),k=Math.floor(x/m),w=(_-E*y)/2,N=[],S=[],M=1/0,P=1/0,T=f-(x-k*m)/2,O=0;T>=h;){for(var R=[],A=[],D=l+w,F=0;D<=c;){var q=I([D,T]),V=pl(q,r);R.push(V?0:1),A.push(D+"|"+T);var G=ut(q,t);!V&&G1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(i=null!=i?i:{}))throw new Error("options is invalid");var o=null!=(e=i.tolerance)?e:1,s=null!=(n=i.highQuality)&&n,a=null!=(r=i.mutate)&&r;if(!t)throw new Error("geojson is required");if(o&&o<0)throw new Error("invalid tolerance");return!0!==a&&(t=Ai(t)),mt(t,(function(t){!function(t,e,n){var r=t.type;if("Point"===r||"MultiPoint"===r)return t;if(Le(t,{mutate:!0}),"GeometryCollection"!==r)switch(r){case"LineString":t.coordinates=ml(t.coordinates,e,n);break;case"MultiLineString":t.coordinates=t.coordinates.map((function(t){return ml(t,e,n)}));break;case"Polygon":t.coordinates=_l(t.coordinates,e,n);break;case"MultiPolygon":t.coordinates=t.coordinates.map((function(t){return _l(t,e,n)}))}}(t,o,s)})),t},t.square=Ka,t.squareGrid=sa,t.standardDeviationalEllipse=function(t,e){var n;if(!Z(e=e||{}))throw new Error("options is invalid");var r=e.steps||64,i=e.weight,o=e.properties||{};if(!U(r))throw new Error("steps must be a number");if(!Z(o))throw new Error("properties must be a number");var s=yt(t).length,a=fi(t,{weight:i}),u=0,l=0,h=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));u+=Math.pow(r.x,2)*n,l+=Math.pow(r.y,2)*n,h+=r.x*r.y*n}));var c=u-l,f=Math.sqrt(Math.pow(c,2)+4*Math.pow(h,2)),g=2*h,p=Math.atan((c+f)/g),v=180*p/Math.PI,d=0,y=0,m=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));d+=Math.pow(r.x*Math.cos(p)-r.y*Math.sin(p),2)*n,y+=Math.pow(r.x*Math.sin(p)+r.y*Math.cos(p),2)*n,m+=n}));var _=Math.sqrt(2*d/m),x=Math.sqrt(2*y/m),E=js(a,_,x,{units:"degrees",angle:v,steps:r,properties:o}),k=Su(t,C([E])),b={meanCenterCoordinates:Q(a),semiMajorAxis:_,semiMinorAxis:x,numberOfFeatures:s,angle:v,percentageWithinEllipse:100*yt(k).length/s};return E.properties=null!=(n=E.properties)?n:{},E.properties.standardDeviationalEllipse=b,E},t.tag=function(t,e,n,r){return t=Ai(t),e=Ai(e),vt(t,(function(t){t.properties||(t.properties={}),vt(e,(function(e){t.properties&&e.properties&&void 0===t.properties[r]&&zt(t,e)&&(t.properties[r]=e.properties[n])}))})),t},t.tesselate=function(t){if(!t.geometry||"Polygon"!==t.geometry.type&&"MultiPolygon"!==t.geometry.type)throw new Error("input must be a Polygon or MultiPolygon");var e={type:"FeatureCollection",features:[]};return"Polygon"===t.geometry.type?e.features=Nl(t.geometry.coordinates):t.geometry.coordinates.forEach((function(t){e.features=e.features.concat(Nl(t))})),e},t.tin=oo,t.toMercator=Vu,t.toWgs84=Gu,t.transformRotate=zs,t.transformScale=al,t.transformTranslate=function(t,e,n,r){if(!Z(r=r||{}))throw new Error("options is invalid");var i=r.units,o=r.zTranslation,s=r.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("distance is required");if(o&&"number"!=typeof o&&isNaN(o))throw new Error("zTranslation is not a number");if(o=void 0!==o?o:0,0===e&&0===o)return t;if(null==n||isNaN(n))throw new Error("direction is required");return e<0&&(e=-e,n+=180),!1!==s&&void 0!==s||(t=Ai(t)),ct(t,(function(t){var r=Q(Bs(t,e,n,{units:i}));t[0]=r[0],t[1]=r[1],o&&3===t.length&&(t[2]+=o)})),t},t.triangleGrid=aa,t.truncate=Qa,t.union=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must have at least 2 geometries");var r=Os.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)},t.unkinkPolygon=function(t){var e=[];return xt(t,(function(t){"Polygon"===t.geometry.type&&vt(Ll(t),(function(n){e.push(S(n.geometry.coordinates,t.properties))}))})),C(e)},t.validateBBox=H,t.validateId=W,t.voronoi=function(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox||[-180,-85,180,85];if(!t)throw new Error("points is required");if(!Array.isArray(n))throw new Error("bbox is invalid");return nt(t,"Point","points"),C(function(){var t=Fl,e=ql,n=null;function r(r){return new mh(r.map((function(n,i){var o=[Math.round(t(n,i,r)/vh)*vh,Math.round(e(n,i,r)/vh)*vh];return o.index=i,o.data=n,o})),n)}return r.polygons=function(t){return r(t).polygons()},r.links=function(t){return r(t).links()},r.triangles=function(t){return r(t).triangles()},r.x=function(e){return arguments.length?(t="function"==typeof e?e:Dl(+e),r):t},r.y=function(t){return arguments.length?(e="function"==typeof t?t:Dl(+t),r):e},r.extent=function(t){return arguments.length?(n=null==t?null:[[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]],r):n&&[[n[0][0],n[0][1]],[n[1][0],n[1][1]]]},r.size=function(t){return arguments.length?(n=null==t?null:[[0,0],[+t[0],+t[1]]],r):n&&[n[1][0]-n[0][0],n[1][1]-n[0][1]]},r}().x((function(t){return t.geometry.coordinates[0]})).y((function(t){return t.geometry.coordinates[1]})).extent([[n[0],n[1]],[n[2],n[3]]]).polygons(t.features).map((function(e,n){return Object.assign(function(t){return(t=t.slice()).push(t[0]),S([t])}(e),{properties:Fi(t.features[n].properties)})})))}})); diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js new file mode 100644 index 0000000..6b2b9e8 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js @@ -0,0 +1,207 @@ +// This code is derived from the ISC-licensed "mapbox-gl-draw-freehand-mode" plugin +// by Ben Ehmke, Eric Dong, and Joe Woodhouse. +// Source: https://github.com/bemky/mapbox-gl-draw-freehand-mode +(function (MapboxDraw) { + const { geojsonTypes, cursors, types, updateActions, modes, events } = + MapboxDraw.constants; + + const FreehandMode = {}; + + FreehandMode.onSetup = function () { + const polygon = this.newFeature({ + type: geojsonTypes.FEATURE, + properties: {}, + geometry: { + type: geojsonTypes.POLYGON, + coordinates: [[]], + }, + }); + + this.addFeature(polygon); + this.clearSelectedFeatures(); + + // Disable map dragging + setTimeout(() => { + if (!this.map || !this.map.dragPan) return; + this.map.dragPan.disable(); + }, 0); + + this.updateUIClasses({ mouse: cursors.ADD }); + this.activateUIButton(types.POLYGON); + this.setActionableState({ + trash: true, + }); + + return { + polygon, + currentVertexPosition: 0, + dragMoving: false, + isDrawing: false, + }; + }; + + FreehandMode.onDrag = FreehandMode.onTouchMove = function (state, e) { + state.dragMoving = true; + state.isDrawing = true; + this.updateUIClasses({ mouse: cursors.ADD }); + state.polygon.updateCoordinate( + `0.${state.currentVertexPosition}`, + e.lngLat.lng, + e.lngLat.lat, + ); + state.currentVertexPosition++; + state.polygon.updateCoordinate( + `0.${state.currentVertexPosition}`, + e.lngLat.lng, + e.lngLat.lat, + ); + }; + + FreehandMode.onMouseUp = function (state) { + if (state.dragMoving) { + this.simplify(state.polygon); + this.updateUIClasses({ mouse: cursors.MOVE }); + this.fireUpdate(); + this.changeMode(modes.SIMPLE_SELECT, { + featureIds: [state.polygon.id], + }); + } + }; + + FreehandMode.fireCreate = function (polygon) { + this.map.fire(events.CREATE, { + features: [polygon.toGeoJSON()], + }); + }; + + FreehandMode.fireUpdate = function () { + this.map.fire(events.UPDATE, { + action: updateActions.MOVE, + features: this.getSelected().map((f) => f.toGeoJSON()), + }); + }; + + FreehandMode.simplify = function (polygon) { + if (!this.map.simplify_freehand) return; + + const tolerance = 1 / Math.pow(1.05, 10 * this.map.getZoom()); + const simplifiedCoords = simplifyGeometry( + polygon.coordinates[0], + tolerance, + ); + polygon.setCoordinates([simplifiedCoords]); + }; + + function simplifyGeometry(points, tolerance) { + if (points.length <= 2) return points; + + const sqTolerance = tolerance * tolerance; + const last = points.length - 1; + const simplified = [points[0]]; + simplifyDPStep(points, 0, last, sqTolerance, simplified); + simplified.push(points[last]); + + return simplified; + } + + function simplifyDPStep(points, first, last, sqTolerance, simplified) { + let maxSqDist = sqTolerance; + let index; + + for (let i = first + 1; i < last; i++) { + const sqDist = getSquareSegmentDistance( + points[i], + points[first], + points[last], + ); + if (sqDist > maxSqDist) { + index = i; + maxSqDist = sqDist; + } + } + + if (maxSqDist > sqTolerance) { + if (index - first > 1) + simplifyDPStep(points, first, index, sqTolerance, simplified); + simplified.push(points[index]); + if (last - index > 1) + simplifyDPStep(points, index, last, sqTolerance, simplified); + } + } + + function getSquareSegmentDistance(p, p1, p2) { + let x = p1[0], + y = p1[1]; + let dx = p2[0] - x, + dy = p2[1] - y; + + if (dx !== 0 || dy !== 0) { + const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy); + if (t > 1) { + x = p2[0]; + y = p2[1]; + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } + + dx = p[0] - x; + dy = p[1] - y; + + return dx * dx + dy * dy; + } + + FreehandMode.onStop = function (state) { + this.updateUIClasses({ mouse: cursors.NONE }); + this.activateUIButton(); + + // Enable map dragging + setTimeout(() => { + if (!this.map || !this.map.dragPan) return; + this.map.dragPan.enable(); + }, 0); + }; + + FreehandMode.toDisplayFeatures = function (state, geojson, display) { + const isActivePolygon = geojson.properties.id === state.polygon.id; + geojson.properties.active = isActivePolygon ? "true" : "false"; + if (!isActivePolygon) return display(geojson); + + // Only render the polygon if it has at least three points + if (geojson.geometry.coordinates[0].length < 3) return; + + const coordinateCount = geojson.geometry.coordinates[0].length; + + // If we have fewer than three coordinates, we need to create a LineString instead of a Polygon + if (coordinateCount < 3) { + const lineCoordinates = [ + [ + geojson.geometry.coordinates[0][0][0], + geojson.geometry.coordinates[0][0][1], + ], + [ + geojson.geometry.coordinates[0][1][0], + geojson.geometry.coordinates[0][1][1], + ], + ]; + return display({ + type: geojsonTypes.FEATURE, + properties: geojson.properties, + geometry: { + coordinates: lineCoordinates, + type: geojsonTypes.LINE_STRING, + }, + }); + } + + return display(geojson); + }; + + FreehandMode.onTrash = function (state) { + this.deleteFeature([state.polygon.id], { silent: true }); + this.changeMode(modes.SIMPLE_SELECT); + }; + + MapboxDraw.modes.draw_freehand = FreehandMode; +})(MapboxDraw); diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js new file mode 100644 index 0000000..16631aa --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js @@ -0,0 +1,3 @@ +!function(A){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=A();else if("function"==typeof define&&define.amd)define([],A);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).h3j_h3t=A()}}((function(){return function A(e,r,t){function i(o,a){if(!r[o]){if(!e[o]){var f="function"==typeof require&&require;if(!a&&f)return f(o,!0);if(n)return n(o,!0);var s=new Error("Cannot find module '"+o+"'");throw s.code="MODULE_NOT_FOUND",s}var u=r[o]={exports:{}};e[o][0].call(u.exports,(function(A){return i(e[o][1][A]||A)}),u,u.exports,A,e,r,t)}return r[o].exports}for(var n="function"==typeof require&&require,o=0;o>3}if(n--,1===i||2===i)o+=A.readSVarint(),a+=A.readSVarint(),1===i&&(e&&f.push(e),e=[]),e.push(new t(o,a));else{if(7!==i)throw new Error("unknown command "+i);e&&e.push(e[0].clone())}}return e&&f.push(e),f},i.prototype.bbox=function(){var A=this._pbf;A.pos=this._geometry;for(var e=A.readVarint()+A.pos,r=1,t=0,i=0,n=0,o=1/0,a=-1/0,f=1/0,s=-1/0;A.pos>3}if(t--,1===r||2===r)(i+=A.readSVarint())a&&(a=i),(n+=A.readSVarint())s&&(s=n);else if(7!==r)throw new Error("unknown command "+r)}return[o,f,a,s]},i.prototype.toGeoJSON=function(A,e,r){var t,n,a=this.extent*Math.pow(2,r),f=this.extent*A,s=this.extent*e,u=this.loadGeometry(),l=i.types[this.type];function h(A){for(var e=0;e>3;e=1===t?A.readString():2===t?A.readFloat():3===t?A.readDouble():4===t?A.readVarint64():5===t?A.readVarint():6===t?A.readSVarint():7===t?A.readBoolean():null}return e}(r))}e.exports=i,i.prototype.feature=function(A){if(A<0||A>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[A];var e=this._pbf.readVarint()+this._pbf.pos;return new t(this._pbf,e,this.extent,this._keys,this._values)}},{"./vectortilefeature.js":4}],6:[function(A,e,r){!function(A,t){"object"==typeof r&&void 0!==e?e.exports=t():A.geojsonvt=t()}(this,(function(){"use strict";function A(r,t,i,n){for(var o,a=n,f=i-t>>1,s=i-t,u=r[t],l=r[t+1],h=r[i],c=r[i+1],d=t+3;da)o=d,a=g;else if(g===a){var w=Math.abs(d-f);wn&&(o-t>3&&A(r,t,o,n),r[o+2]=a,i-o>3&&A(r,o,i,n))}function e(A,e,r,t,i,n){var o=i-r,a=n-t;if(0!==o||0!==a){var f=((A-r)*o+(e-t)*a)/(o*o+a*a);f>1?(r=i,t=n):f>0&&(r+=o*f,t+=a*f)}return(o=A-r)*o+(a=e-t)*a}function r(A,e,r,i){var n={id:void 0===A?null:A,type:e,geometry:r,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(A){var e=A.geometry,r=A.type;if("Point"===r||"MultiPoint"===r||"LineString"===r)t(A,e);else if("Polygon"===r||"MultiLineString"===r)for(var i=0;i0&&(a+=i?(n*h-l*o)/2:Math.sqrt(Math.pow(l-n,2)+Math.pow(h-o,2))),n=l,o=h}var c=r.length-3;r[2]=1,A(r,0,c,t),r[c+2]=1,r.size=Math.abs(a),r.start=0,r.end=r.size}function a(A,e,r,t){for(var i=0;i1?1:r}function u(A,e,t,i,n,o,a,f){if(i/=e,o>=(t/=e)&&a=i)return null;for(var s=[],u=0;u=t&&B=i)){var b=[];if("Point"===w||"MultiPoint"===w)l(g,b,t,i,n);else if("LineString"===w)h(g,b,t,i,n,!1,f.lineMetrics);else if("MultiLineString"===w)d(g,b,t,i,n,!1);else if("Polygon"===w)d(g,b,t,i,n,!0);else if("MultiPolygon"===w)for(var v=0;v=r&&o<=t&&(e.push(A[n]),e.push(A[n+1]),e.push(A[n+2]))}}function h(A,e,r,t,i,n,o){for(var a,f,s=c(A),u=0===i?w:p,l=A.start,h=0;hr&&(f=u(s,d,B,v,m,r),o&&(s.start=l+a*f)):k>t?M=r&&(f=u(s,d,B,v,m,r),Q=!0),M>t&&k<=t&&(f=u(s,d,B,v,m,t),Q=!0),!n&&Q&&(o&&(s.end=l+a*f),e.push(s),s=c(A)),o&&(l+=a)}var y=A.length-3;d=A[y],B=A[y+1],b=A[y+2],(k=0===i?d:B)>=r&&k<=t&&g(s,d,B,b),y=s.length-3,n&&y>=3&&(s[y]!==s[0]||s[y+1]!==s[1])&&g(s,s[0],s[1],s[2]),s.length&&e.push(s)}function c(A){var e=[];return e.size=A.size,e.start=A.start,e.end=A.end,e}function d(A,e,r,t,i,n){for(var o=0;oo.maxX&&(o.maxX=u),l>o.maxY&&(o.maxY=l)}return o}function M(A,e,r,t){var i=e.geometry,n=e.type,o=[];if("Point"===n||"MultiPoint"===n)for(var a=0;a0&&e.size<(i?o:t))r.numPoints+=e.length/3;else{for(var a=[],f=0;fo)&&(r.numSimplified++,a.push(e[f]),a.push(e[f+1])),r.numPoints++;i&&function(A,e){for(var r=0,t=0,i=A.length,n=i-2;t0===e)for(t=0,i=A.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(e.promoteId&&e.generateId)throw new Error("promoteId and generateId cannot be used together.");var t=function(A,e){var r=[];if("FeatureCollection"===A.type)for(var t=0;t1&&console.time("creation"),c=this.tiles[h]=k(A,e,r,t,f),this.tileCoords.push({z:e,x:r,y:t}),s)){s>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,r,t,c.numFeatures,c.numPoints,c.numSimplified),console.timeEnd("creation"));var d="z"+e;this.stats[d]=(this.stats[d]||0)+1,this.total++}if(c.source=A,i){if(e===f.maxZoom||e===i)continue;var g=1<1&&console.time("clipping");var w,p,B,b,v,m,M=.5*f.buffer/f.extent,Q=.5-M,y=.5+M,x=1+M;w=p=B=b=null,v=u(A,l,r-M,r+y,0,c.minX,c.maxX,f),m=u(A,l,r+Q,r+x,0,c.minX,c.maxX,f),A=null,v&&(w=u(v,l,t-M,t+y,1,c.minY,c.maxY,f),p=u(v,l,t+Q,t+x,1,c.minY,c.maxY,f),v=null),m&&(B=u(m,l,t-M,t+y,1,c.minY,c.maxY,f),b=u(m,l,t+Q,t+x,1,c.minY,c.maxY,f),m=null),s>1&&console.timeEnd("clipping"),a.push(w||[],e+1,2*r,2*t),a.push(p||[],e+1,2*r,2*t+1),a.push(B||[],e+1,2*r+1,2*t),a.push(b||[],e+1,2*r+1,2*t+1)}}},y.prototype.getTile=function(A,e,r){var t=this.options,i=t.extent,n=t.debug;if(A<0||A>24)return null;var o=1<1&&console.log("drilling down to z%d-%d-%d",A,e,r);for(var f,s=A,u=e,l=r;!f&&s>0;)s--,u=Math.floor(u/2),l=Math.floor(l/2),f=this.tiles[E(s,u,l)];return f&&f.source?(n>1&&console.log("found parent tile z%d-%d-%d",s,u,l),n>1&&console.time("drilling down"),this.splitTile(f.source,s,u,l,A,e,r),n>1&&console.timeEnd("drilling down"),this.tiles[a]?v(this.tiles[a],i):null):null},function(A,e){return new y(A,e)}}))},{}],7:[function(A,e,r){var t=function(A){var e,r=void 0!==(A=A||{})?A:{},t={};for(e in r)r.hasOwnProperty(e)&&(t[e]=r[e]);var i,n=[],o="";document.currentScript&&(o=document.currentScript.src),o=0!==o.indexOf("blob:")?o.substr(0,o.lastIndexOf("/")+1):"",i=function(A,e,r){var t=new XMLHttpRequest;t.open("GET",A,!0),t.responseType="arraybuffer",t.onload=function(){if(200==t.status||0==t.status&&t.response)e(t.response);else{var i=J(A);i?e(i.buffer):r()}},t.onerror=r,t.send(null)};var a=r.print||console.log.bind(console),f=r.printErr||console.warn.bind(console);for(e in t)t.hasOwnProperty(e)&&(r[e]=t[e]);t=null,r.arguments&&(n=r.arguments);var s=0,u=function(){return s};var l=!1;function h(A){var e,t=r["_"+A];return e="Cannot call unknown function "+A+", make sure it is exported",t||fA("Assertion failed: "+e),t}function c(A,e,r,t,i){var n={string:function(A){var e=0;if(null!=A&&0!==A){var r=1+(A.length<<2);(function(A,e,r){(function(A,e,r,t){if(!(t>0))return 0;for(var i=r,n=r+t-1,o=0;o=55296&&a<=57343)a=65536+((1023&a)<<10)|1023&A.charCodeAt(++o);if(a<=127){if(r>=n)break;e[r++]=a}else if(a<=2047){if(r+1>=n)break;e[r++]=192|a>>6,e[r++]=128|63&a}else if(a<=65535){if(r+2>=n)break;e[r++]=224|a>>12,e[r++]=128|a>>6&63,e[r++]=128|63&a}else{if(r+3>=n)break;e[r++]=240|a>>18,e[r++]=128|a>>12&63,e[r++]=128|a>>6&63,e[r++]=128|63&a}}e[r]=0})(A,B,e,r)})(A,e=AA(r),r)}return e},array:function(A){var e=AA(A.length);return function(A,e){p.set(A,e)}(A,e),e}};var o=h(A),a=[],f=0;if(t)for(var s=0;s=t);)++i;if(i-e>16&&A.subarray&&d)return d.decode(A.subarray(e,i));for(var n="";e>10,56320|1023&s)}}else n+=String.fromCharCode((31&o)<<6|a)}else n+=String.fromCharCode(o)}return n}(B,A,e):""}var w,p,B,b,v,m,k;"undefined"!=typeof TextDecoder&&new TextDecoder("utf-16le");function M(A,e){return A%e>0&&(A+=e-A%e),A}function Q(A){w=A,r.HEAP8=p=new Int8Array(A),r.HEAP16=b=new Int16Array(A),r.HEAP32=v=new Int32Array(A),r.HEAPU8=B=new Uint8Array(A),r.HEAPU16=new Uint16Array(A),r.HEAPU32=new Uint32Array(A),r.HEAPF32=m=new Float32Array(A),r.HEAPF64=k=new Float64Array(A)}var y=r.TOTAL_MEMORY||33554432;function E(A){for(;A.length>0;){var e=A.shift();if("function"!=typeof e){var t=e.func;"number"==typeof t?void 0===e.arg?r.dynCall_v(t):r.dynCall_vi(t,e.arg):t(void 0===e.arg?null:e.arg)}else e()}}y=(w=r.buffer?r.buffer:new ArrayBuffer(y)).byteLength,Q(w),v[6004]=5266928;var x=[],D=[],_=[],I=[];var F=Math.abs,C=Math.ceil,P=Math.floor,U=Math.min,G=0,S=null,T=null;r.preloadedImages={},r.preloadedAudios={};var V,H,R=null,L="data:application/octet-stream;base64,";function z(A){return String.prototype.startsWith?A.startsWith(L):0===A.indexOf(L)}R="data:application/octet-stream;base64,AAAAAAAAAAACAAAAAwAAAAEAAAAFAAAABAAAAAYAAAAAAAAAAAAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAYAAAABAAAABAAAAAMAAAAGAAAABQAAAAIAAAAAAAAAAgAAAAMAAAABAAAABAAAAAYAAAAAAAAABQAAAAMAAAAGAAAABAAAAAUAAAAAAAAAAQAAAAIAAAAEAAAABQAAAAYAAAAAAAAAAgAAAAMAAAABAAAABQAAAAIAAAAAAAAAAQAAAAMAAAAGAAAABAAAAAYAAAAAAAAABQAAAAIAAAABAAAABAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAgAAAAMAAAAAAAAAAAAAAAIAAAAAAAAAAQAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAABgAAAAAAAAAFAAAAAAAAAAAAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAIAAAAAAAAABgAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAgAAAAAAAAAAAAAABgAAAAAAAAADAAAAAgAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAUAAAAEAAAAAAAAAAEAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAEAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAUAAAACAAAABAAAAAMAAAAIAAAAAQAAAAcAAAAGAAAACQAAAAAAAAADAAAAAgAAAAIAAAAGAAAACgAAAAsAAAAAAAAAAQAAAAUAAAADAAAADQAAAAEAAAAHAAAABAAAAAwAAAAAAAAABAAAAH8AAAAPAAAACAAAAAMAAAAAAAAADAAAAAUAAAACAAAAEgAAAAoAAAAIAAAAAAAAABAAAAAGAAAADgAAAAsAAAARAAAAAQAAAAkAAAACAAAABwAAABUAAAAJAAAAEwAAAAMAAAANAAAAAQAAAAgAAAAFAAAAFgAAABAAAAAEAAAAAAAAAA8AAAAJAAAAEwAAAA4AAAAUAAAAAQAAAAcAAAAGAAAACgAAAAsAAAAYAAAAFwAAAAUAAAACAAAAEgAAAAsAAAARAAAAFwAAABkAAAACAAAABgAAAAoAAAAMAAAAHAAAAA0AAAAaAAAABAAAAA8AAAADAAAADQAAABoAAAAVAAAAHQAAAAMAAAAMAAAABwAAAA4AAAB/AAAAEQAAABsAAAAJAAAAFAAAAAYAAAAPAAAAFgAAABwAAAAfAAAABAAAAAgAAAAMAAAAEAAAABIAAAAhAAAAHgAAAAgAAAAFAAAAFgAAABEAAAALAAAADgAAAAYAAAAjAAAAGQAAABsAAAASAAAAGAAAAB4AAAAgAAAABQAAAAoAAAAQAAAAEwAAACIAAAAUAAAAJAAAAAcAAAAVAAAACQAAABQAAAAOAAAAEwAAAAkAAAAoAAAAGwAAACQAAAAVAAAAJgAAABMAAAAiAAAADQAAAB0AAAAHAAAAFgAAABAAAAApAAAAIQAAAA8AAAAIAAAAHwAAABcAAAAYAAAACwAAAAoAAAAnAAAAJQAAABkAAAAYAAAAfwAAACAAAAAlAAAACgAAABcAAAASAAAAGQAAABcAAAARAAAACwAAAC0AAAAnAAAAIwAAABoAAAAqAAAAHQAAACsAAAAMAAAAHAAAAA0AAAAbAAAAKAAAACMAAAAuAAAADgAAABQAAAARAAAAHAAAAB8AAAAqAAAALAAAAAwAAAAPAAAAGgAAAB0AAAArAAAAJgAAAC8AAAANAAAAGgAAABUAAAAeAAAAIAAAADAAAAAyAAAAEAAAABIAAAAhAAAAHwAAACkAAAAsAAAANQAAAA8AAAAWAAAAHAAAACAAAAAeAAAAGAAAABIAAAA0AAAAMgAAACUAAAAhAAAAHgAAADEAAAAwAAAAFgAAABAAAAApAAAAIgAAABMAAAAmAAAAFQAAADYAAAAkAAAAMwAAACMAAAAuAAAALQAAADgAAAARAAAAGwAAABkAAAAkAAAAFAAAACIAAAATAAAANwAAACgAAAA2AAAAJQAAACcAAAA0AAAAOQAAABgAAAAXAAAAIAAAACYAAAB/AAAAIgAAADMAAAAdAAAALwAAABUAAAAnAAAAJQAAABkAAAAXAAAAOwAAADkAAAAtAAAAKAAAABsAAAAkAAAAFAAAADwAAAAuAAAANwAAACkAAAAxAAAANQAAAD0AAAAWAAAAIQAAAB8AAAAqAAAAOgAAACsAAAA+AAAAHAAAACwAAAAaAAAAKwAAAD4AAAAvAAAAQAAAABoAAAAqAAAAHQAAACwAAAA1AAAAOgAAAEEAAAAcAAAAHwAAACoAAAAtAAAAJwAAACMAAAAZAAAAPwAAADsAAAA4AAAALgAAADwAAAA4AAAARAAAABsAAAAoAAAAIwAAAC8AAAAmAAAAKwAAAB0AAABFAAAAMwAAAEAAAAAwAAAAMQAAAB4AAAAhAAAAQwAAAEIAAAAyAAAAMQAAAH8AAAA9AAAAQgAAACEAAAAwAAAAKQAAADIAAAAwAAAAIAAAAB4AAABGAAAAQwAAADQAAAAzAAAARQAAADYAAABHAAAAJgAAAC8AAAAiAAAANAAAADkAAABGAAAASgAAACAAAAAlAAAAMgAAADUAAAA9AAAAQQAAAEsAAAAfAAAAKQAAACwAAAA2AAAARwAAADcAAABJAAAAIgAAADMAAAAkAAAANwAAACgAAAA2AAAAJAAAAEgAAAA8AAAASQAAADgAAABEAAAAPwAAAE0AAAAjAAAALgAAAC0AAAA5AAAAOwAAAEoAAABOAAAAJQAAACcAAAA0AAAAOgAAAH8AAAA+AAAATAAAACwAAABBAAAAKgAAADsAAAA/AAAATgAAAE8AAAAnAAAALQAAADkAAAA8AAAASAAAAEQAAABQAAAAKAAAADcAAAAuAAAAPQAAADUAAAAxAAAAKQAAAFEAAABLAAAAQgAAAD4AAAArAAAAOgAAACoAAABSAAAAQAAAAEwAAAA/AAAAfwAAADgAAAAtAAAATwAAADsAAABNAAAAQAAAAC8AAAA+AAAAKwAAAFQAAABFAAAAUgAAAEEAAAA6AAAANQAAACwAAABWAAAATAAAAEsAAABCAAAAQwAAAFEAAABVAAAAMQAAADAAAAA9AAAAQwAAAEIAAAAyAAAAMAAAAFcAAABVAAAARgAAAEQAAAA4AAAAPAAAAC4AAABaAAAATQAAAFAAAABFAAAAMwAAAEAAAAAvAAAAWQAAAEcAAABUAAAARgAAAEMAAAA0AAAAMgAAAFMAAABXAAAASgAAAEcAAABZAAAASQAAAFsAAAAzAAAARQAAADYAAABIAAAAfwAAAEkAAAA3AAAAUAAAADwAAABYAAAASQAAAFsAAABIAAAAWAAAADYAAABHAAAANwAAAEoAAABOAAAAUwAAAFwAAAA0AAAAOQAAAEYAAABLAAAAQQAAAD0AAAA1AAAAXgAAAFYAAABRAAAATAAAAFYAAABSAAAAYAAAADoAAABBAAAAPgAAAE0AAAA/AAAARAAAADgAAABdAAAATwAAAFoAAABOAAAASgAAADsAAAA5AAAAXwAAAFwAAABPAAAATwAAAE4AAAA/AAAAOwAAAF0AAABfAAAATQAAAFAAAABEAAAASAAAADwAAABjAAAAWgAAAFgAAABRAAAAVQAAAF4AAABlAAAAPQAAAEIAAABLAAAAUgAAAGAAAABUAAAAYgAAAD4AAABMAAAAQAAAAFMAAAB/AAAASgAAAEYAAABkAAAAVwAAAFwAAABUAAAARQAAAFIAAABAAAAAYQAAAFkAAABiAAAAVQAAAFcAAABlAAAAZgAAAEIAAABDAAAAUQAAAFYAAABMAAAASwAAAEEAAABoAAAAYAAAAF4AAABXAAAAUwAAAGYAAABkAAAAQwAAAEYAAABVAAAAWAAAAEgAAABbAAAASQAAAGMAAABQAAAAaQAAAFkAAABhAAAAWwAAAGcAAABFAAAAVAAAAEcAAABaAAAATQAAAFAAAABEAAAAagAAAF0AAABjAAAAWwAAAEkAAABZAAAARwAAAGkAAABYAAAAZwAAAFwAAABTAAAATgAAAEoAAABsAAAAZAAAAF8AAABdAAAATwAAAFoAAABNAAAAbQAAAF8AAABqAAAAXgAAAFYAAABRAAAASwAAAGsAAABoAAAAZQAAAF8AAABcAAAATwAAAE4AAABtAAAAbAAAAF0AAABgAAAAaAAAAGIAAABuAAAATAAAAFYAAABSAAAAYQAAAH8AAABiAAAAVAAAAGcAAABZAAAAbwAAAGIAAABuAAAAYQAAAG8AAABSAAAAYAAAAFQAAABjAAAAUAAAAGkAAABYAAAAagAAAFoAAABxAAAAZAAAAGYAAABTAAAAVwAAAGwAAAByAAAAXAAAAGUAAABmAAAAawAAAHAAAABRAAAAVQAAAF4AAABmAAAAZQAAAFcAAABVAAAAcgAAAHAAAABkAAAAZwAAAFsAAABhAAAAWQAAAHQAAABpAAAAbwAAAGgAAABrAAAAbgAAAHMAAABWAAAAXgAAAGAAAABpAAAAWAAAAGcAAABbAAAAcQAAAGMAAAB0AAAAagAAAF0AAABjAAAAWgAAAHUAAABtAAAAcQAAAGsAAAB/AAAAZQAAAF4AAABzAAAAaAAAAHAAAABsAAAAZAAAAF8AAABcAAAAdgAAAHIAAABtAAAAbQAAAGwAAABdAAAAXwAAAHUAAAB2AAAAagAAAG4AAABiAAAAaAAAAGAAAAB3AAAAbwAAAHMAAABvAAAAYQAAAG4AAABiAAAAdAAAAGcAAAB3AAAAcAAAAGsAAABmAAAAZQAAAHgAAABzAAAAcgAAAHEAAABjAAAAdAAAAGkAAAB1AAAAagAAAHkAAAByAAAAcAAAAGQAAABmAAAAdgAAAHgAAABsAAAAcwAAAG4AAABrAAAAaAAAAHgAAAB3AAAAcAAAAHQAAABnAAAAdwAAAG8AAABxAAAAaQAAAHkAAAB1AAAAfwAAAG0AAAB2AAAAcQAAAHkAAABqAAAAdgAAAHgAAABsAAAAcgAAAHUAAAB5AAAAbQAAAHcAAABvAAAAcwAAAG4AAAB5AAAAdAAAAHgAAAB4AAAAcwAAAHIAAABwAAAAeQAAAHcAAAB2AAAAeQAAAHQAAAB4AAAAdwAAAHUAAABxAAAAdgAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAEAAAAFAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAIAAAAFAAAAAQAAAAAAAAD/////AQAAAAAAAAADAAAABAAAAAIAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAUAAAABAAAAAAAAAAAAAAABAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAAFAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAQAAAAFAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAADAAAAAAAAAAAAAAABAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAABAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAADAAAABQAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAADAAAAAAAAAAAAAAABAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAADAAAAAQAAAAAAAAABAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAMAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAADAAAABQAAAAEAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAEAAAABQAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAgAAAAUAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAABQAAAAAAAAAAAAAABQAAAAUAAAAAAAAAAAAAAP////8BAAAAAAAAAAMAAAAEAAAAAgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAABQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAABQAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAQAAAP//////////AQAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAIAAAAAAAAAAAAAAAEAAAACAAAABgAAAAQAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAABwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAoAAAACAAAAAAAAAAAAAAABAAAAAQAAAAUAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAsAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAIAAAAAAAAAAAAAAAEAAAADAAAABwAAAAYAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAHAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAABAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAOAAAAAgAAAAAAAAAAAAAAAQAAAAAAAAAJAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAwAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAgAAAAAAAAAAAAAAAQAAAAQAAAAIAAAACgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAsAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAACAAAAAAAAAAAAAAABAAAACwAAAA8AAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA4AAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAgAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAFAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAACAAAAAAAAAAAAAAABAAAADAAAABAAAAAMAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAEAAAAKAAAAEwAAAAgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAADwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAJAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAgAAAAAAAAAAAAAAAQAAAA0AAAARAAAADQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAABEAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAADQAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAIAAAAAAAAAAAAAAAEAAAAOAAAAEgAAAA8AAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAPAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAABIAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAEQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABMAAAACAAAAAAAAAAAAAAABAAAA//////////8TAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAASAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABIAAAAAAAAAGAAAAAAAAAAhAAAAAAAAAB4AAAAAAAAAIAAAAAMAAAAxAAAAAQAAADAAAAADAAAAMgAAAAMAAAAIAAAAAAAAAAUAAAAFAAAACgAAAAUAAAAWAAAAAAAAABAAAAAAAAAAEgAAAAAAAAApAAAAAQAAACEAAAAAAAAAHgAAAAAAAAAEAAAAAAAAAAAAAAAFAAAAAgAAAAUAAAAPAAAAAQAAAAgAAAAAAAAABQAAAAUAAAAfAAAAAQAAABYAAAAAAAAAEAAAAAAAAAACAAAAAAAAAAYAAAAAAAAADgAAAAAAAAAKAAAAAAAAAAsAAAAAAAAAEQAAAAMAAAAYAAAAAQAAABcAAAADAAAAGQAAAAMAAAAAAAAAAAAAAAEAAAAFAAAACQAAAAUAAAAFAAAAAAAAAAIAAAAAAAAABgAAAAAAAAASAAAAAQAAAAoAAAAAAAAACwAAAAAAAAAEAAAAAQAAAAMAAAAFAAAABwAAAAUAAAAIAAAAAQAAAAAAAAAAAAAAAQAAAAUAAAAQAAAAAQAAAAUAAAAAAAAAAgAAAAAAAAAHAAAAAAAAABUAAAAAAAAAJgAAAAAAAAAJAAAAAAAAABMAAAAAAAAAIgAAAAMAAAAOAAAAAQAAABQAAAADAAAAJAAAAAMAAAADAAAAAAAAAA0AAAAFAAAAHQAAAAUAAAABAAAAAAAAAAcAAAAAAAAAFQAAAAAAAAAGAAAAAQAAAAkAAAAAAAAAEwAAAAAAAAAEAAAAAgAAAAwAAAAFAAAAGgAAAAUAAAAAAAAAAQAAAAMAAAAAAAAADQAAAAUAAAACAAAAAQAAAAEAAAAAAAAABwAAAAAAAAAaAAAAAAAAACoAAAAAAAAAOgAAAAAAAAAdAAAAAAAAACsAAAAAAAAAPgAAAAMAAAAmAAAAAQAAAC8AAAADAAAAQAAAAAMAAAAMAAAAAAAAABwAAAAFAAAALAAAAAUAAAANAAAAAAAAABoAAAAAAAAAKgAAAAAAAAAVAAAAAQAAAB0AAAAAAAAAKwAAAAAAAAAEAAAAAwAAAA8AAAAFAAAAHwAAAAUAAAADAAAAAQAAAAwAAAAAAAAAHAAAAAUAAAAHAAAAAQAAAA0AAAAAAAAAGgAAAAAAAAAfAAAAAAAAACkAAAAAAAAAMQAAAAAAAAAsAAAAAAAAADUAAAAAAAAAPQAAAAMAAAA6AAAAAQAAAEEAAAADAAAASwAAAAMAAAAPAAAAAAAAABYAAAAFAAAAIQAAAAUAAAAcAAAAAAAAAB8AAAAAAAAAKQAAAAAAAAAqAAAAAQAAACwAAAAAAAAANQAAAAAAAAAEAAAABAAAAAgAAAAFAAAAEAAAAAUAAAAMAAAAAQAAAA8AAAAAAAAAFgAAAAUAAAAaAAAAAQAAABwAAAAAAAAAHwAAAAAAAAAyAAAAAAAAADAAAAAAAAAAMQAAAAMAAAAgAAAAAAAAAB4AAAADAAAAIQAAAAMAAAAYAAAAAwAAABIAAAADAAAAEAAAAAMAAABGAAAAAAAAAEMAAAAAAAAAQgAAAAMAAAA0AAAAAwAAADIAAAAAAAAAMAAAAAAAAAAlAAAAAwAAACAAAAAAAAAAHgAAAAMAAABTAAAAAAAAAFcAAAADAAAAVQAAAAMAAABKAAAAAwAAAEYAAAAAAAAAQwAAAAAAAAA5AAAAAQAAADQAAAADAAAAMgAAAAAAAAAZAAAAAAAAABcAAAAAAAAAGAAAAAMAAAARAAAAAAAAAAsAAAADAAAACgAAAAMAAAAOAAAAAwAAAAYAAAADAAAAAgAAAAMAAAAtAAAAAAAAACcAAAAAAAAAJQAAAAMAAAAjAAAAAwAAABkAAAAAAAAAFwAAAAAAAAAbAAAAAwAAABEAAAAAAAAACwAAAAMAAAA/AAAAAAAAADsAAAADAAAAOQAAAAMAAAA4AAAAAwAAAC0AAAAAAAAAJwAAAAAAAAAuAAAAAwAAACMAAAADAAAAGQAAAAAAAAAkAAAAAAAAABQAAAAAAAAADgAAAAMAAAAiAAAAAAAAABMAAAADAAAACQAAAAMAAAAmAAAAAwAAABUAAAADAAAABwAAAAMAAAA3AAAAAAAAACgAAAAAAAAAGwAAAAMAAAA2AAAAAwAAACQAAAAAAAAAFAAAAAAAAAAzAAAAAwAAACIAAAAAAAAAEwAAAAMAAABIAAAAAAAAADwAAAADAAAALgAAAAMAAABJAAAAAwAAADcAAAAAAAAAKAAAAAAAAABHAAAAAwAAADYAAAADAAAAJAAAAAAAAABAAAAAAAAAAC8AAAAAAAAAJgAAAAMAAAA+AAAAAAAAACsAAAADAAAAHQAAAAMAAAA6AAAAAwAAACoAAAADAAAAGgAAAAMAAABUAAAAAAAAAEUAAAAAAAAAMwAAAAMAAABSAAAAAwAAAEAAAAAAAAAALwAAAAAAAABMAAAAAwAAAD4AAAAAAAAAKwAAAAMAAABhAAAAAAAAAFkAAAADAAAARwAAAAMAAABiAAAAAwAAAFQAAAAAAAAARQAAAAAAAABgAAAAAwAAAFIAAAADAAAAQAAAAAAAAABLAAAAAAAAAEEAAAAAAAAAOgAAAAMAAAA9AAAAAAAAADUAAAADAAAALAAAAAMAAAAxAAAAAwAAACkAAAADAAAAHwAAAAMAAABeAAAAAAAAAFYAAAAAAAAATAAAAAMAAABRAAAAAwAAAEsAAAAAAAAAQQAAAAAAAABCAAAAAwAAAD0AAAAAAAAANQAAAAMAAABrAAAAAAAAAGgAAAADAAAAYAAAAAMAAABlAAAAAwAAAF4AAAAAAAAAVgAAAAAAAABVAAAAAwAAAFEAAAADAAAASwAAAAAAAAA5AAAAAAAAADsAAAAAAAAAPwAAAAMAAABKAAAAAAAAAE4AAAADAAAATwAAAAMAAABTAAAAAwAAAFwAAAADAAAAXwAAAAMAAAAlAAAAAAAAACcAAAADAAAALQAAAAMAAAA0AAAAAAAAADkAAAAAAAAAOwAAAAAAAABGAAAAAwAAAEoAAAAAAAAATgAAAAMAAAAYAAAAAAAAABcAAAADAAAAGQAAAAMAAAAgAAAAAwAAACUAAAAAAAAAJwAAAAMAAAAyAAAAAwAAADQAAAAAAAAAOQAAAAAAAAAuAAAAAAAAADwAAAAAAAAASAAAAAMAAAA4AAAAAAAAAEQAAAADAAAAUAAAAAMAAAA/AAAAAwAAAE0AAAADAAAAWgAAAAMAAAAbAAAAAAAAACgAAAADAAAANwAAAAMAAAAjAAAAAAAAAC4AAAAAAAAAPAAAAAAAAAAtAAAAAwAAADgAAAAAAAAARAAAAAMAAAAOAAAAAAAAABQAAAADAAAAJAAAAAMAAAARAAAAAwAAABsAAAAAAAAAKAAAAAMAAAAZAAAAAwAAACMAAAAAAAAALgAAAAAAAABHAAAAAAAAAFkAAAAAAAAAYQAAAAMAAABJAAAAAAAAAFsAAAADAAAAZwAAAAMAAABIAAAAAwAAAFgAAAADAAAAaQAAAAMAAAAzAAAAAAAAAEUAAAADAAAAVAAAAAMAAAA2AAAAAAAAAEcAAAAAAAAAWQAAAAAAAAA3AAAAAwAAAEkAAAAAAAAAWwAAAAMAAAAmAAAAAAAAAC8AAAADAAAAQAAAAAMAAAAiAAAAAwAAADMAAAAAAAAARQAAAAMAAAAkAAAAAwAAADYAAAAAAAAARwAAAAAAAABgAAAAAAAAAGgAAAAAAAAAawAAAAMAAABiAAAAAAAAAG4AAAADAAAAcwAAAAMAAABhAAAAAwAAAG8AAAADAAAAdwAAAAMAAABMAAAAAAAAAFYAAAADAAAAXgAAAAMAAABSAAAAAAAAAGAAAAAAAAAAaAAAAAAAAABUAAAAAwAAAGIAAAAAAAAAbgAAAAMAAAA6AAAAAAAAAEEAAAADAAAASwAAAAMAAAA+AAAAAwAAAEwAAAAAAAAAVgAAAAMAAABAAAAAAwAAAFIAAAAAAAAAYAAAAAAAAABVAAAAAAAAAFcAAAAAAAAAUwAAAAMAAABlAAAAAAAAAGYAAAADAAAAZAAAAAMAAABrAAAAAwAAAHAAAAADAAAAcgAAAAMAAABCAAAAAAAAAEMAAAADAAAARgAAAAMAAABRAAAAAAAAAFUAAAAAAAAAVwAAAAAAAABeAAAAAwAAAGUAAAAAAAAAZgAAAAMAAAAxAAAAAAAAADAAAAADAAAAMgAAAAMAAAA9AAAAAwAAAEIAAAAAAAAAQwAAAAMAAABLAAAAAwAAAFEAAAAAAAAAVQAAAAAAAABfAAAAAAAAAFwAAAAAAAAAUwAAAAAAAABPAAAAAAAAAE4AAAAAAAAASgAAAAMAAAA/AAAAAQAAADsAAAADAAAAOQAAAAMAAABtAAAAAAAAAGwAAAAAAAAAZAAAAAUAAABdAAAAAQAAAF8AAAAAAAAAXAAAAAAAAABNAAAAAQAAAE8AAAAAAAAATgAAAAAAAAB1AAAABAAAAHYAAAAFAAAAcgAAAAUAAABqAAAAAQAAAG0AAAAAAAAAbAAAAAAAAABaAAAAAQAAAF0AAAABAAAAXwAAAAAAAABaAAAAAAAAAE0AAAAAAAAAPwAAAAAAAABQAAAAAAAAAEQAAAAAAAAAOAAAAAMAAABIAAAAAQAAADwAAAADAAAALgAAAAMAAABqAAAAAAAAAF0AAAAAAAAATwAAAAUAAABjAAAAAQAAAFoAAAAAAAAATQAAAAAAAABYAAAAAQAAAFAAAAAAAAAARAAAAAAAAAB1AAAAAwAAAG0AAAAFAAAAXwAAAAUAAABxAAAAAQAAAGoAAAAAAAAAXQAAAAAAAABpAAAAAQAAAGMAAAABAAAAWgAAAAAAAABpAAAAAAAAAFgAAAAAAAAASAAAAAAAAABnAAAAAAAAAFsAAAAAAAAASQAAAAMAAABhAAAAAQAAAFkAAAADAAAARwAAAAMAAABxAAAAAAAAAGMAAAAAAAAAUAAAAAUAAAB0AAAAAQAAAGkAAAAAAAAAWAAAAAAAAABvAAAAAQAAAGcAAAAAAAAAWwAAAAAAAAB1AAAAAgAAAGoAAAAFAAAAWgAAAAUAAAB5AAAAAQAAAHEAAAAAAAAAYwAAAAAAAAB3AAAAAQAAAHQAAAABAAAAaQAAAAAAAAB3AAAAAAAAAG8AAAAAAAAAYQAAAAAAAABzAAAAAAAAAG4AAAAAAAAAYgAAAAMAAABrAAAAAQAAAGgAAAADAAAAYAAAAAMAAAB5AAAAAAAAAHQAAAAAAAAAZwAAAAUAAAB4AAAAAQAAAHcAAAAAAAAAbwAAAAAAAABwAAAAAQAAAHMAAAAAAAAAbgAAAAAAAAB1AAAAAQAAAHEAAAAFAAAAaQAAAAUAAAB2AAAAAQAAAHkAAAAAAAAAdAAAAAAAAAByAAAAAQAAAHgAAAABAAAAdwAAAAAAAAByAAAAAAAAAHAAAAAAAAAAawAAAAAAAABkAAAAAAAAAGYAAAAAAAAAZQAAAAMAAABTAAAAAQAAAFcAAAADAAAAVQAAAAMAAAB2AAAAAAAAAHgAAAAAAAAAcwAAAAUAAABsAAAAAQAAAHIAAAAAAAAAcAAAAAAAAABcAAAAAQAAAGQAAAAAAAAAZgAAAAAAAAB1AAAAAAAAAHkAAAAFAAAAdwAAAAUAAABtAAAAAQAAAHYAAAAAAAAAeAAAAAAAAABfAAAAAQAAAGwAAAABAAAAcgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAEAAAABAAAAAAAAAAAAAAABAAAAAAAAAAEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAB+ogX28rbpPxqumpJv+fM/165tC4ns9D+XaEnTqUsEQFrOtNlC4PA/3U+0XG6P9b9TdUUBxTTjP4PUp8ex1ty/B1rD/EN43z+lcDi6LLrZP/a45NWEHMY/oJ5ijLDZ+j/xw3rjxWPjP2B8A46ioQdAotff3wla2z+FMSpA1jj+v6b5Y1mtPbS/cIu8K0F457/2esiyJpDNv98k5Ts2NeA/pvljWa09tD88ClUJ60MDQPZ6yLImkM0/4ONKxa0UBcD2uOTVhBzGv5G7JRxGave/8cN648Vj47+HCwtkjAXIv6LX398JWtu/qyheaCAL9D9TdUUBxTTjv4gyTxslhwVAB1rD/EN4378EH/28teoFwH6iBfbytum/F6ztFYdK/r/Xrm0Liez0vwcS6wNGWeO/Ws602ULg8L9TCtRLiLT8P8pi5RexJsw/BlIKPVwR5T95Wyu0/QjnP5PjoT7YYcu/mBhKZ6zrwj8wRYS7NebuP3qW6geh+Ls/SLrixebL3r+pcyymN9XrPwmkNHp7xec/GWNMZVAA17+82s+x2BLiPwn2ytbJ9ek/LgEH1sMS1j8yp/2LhTfeP+SnWwtQBbu/d38gkp5X7z8ytsuHaADGPzUYObdf1+m/7IauECWhwz+cjSACjzniP76Z+wUhN9K/1+GEKzup67+/GYr/04baPw6idWOvsuc/ZedTWsRa5b/EJQOuRzi0v/OncYhHPes/h49PixY53j+i8wWfC03Nvw2idWOvsue/ZedTWsRa5T/EJQOuRzi0P/KncYhHPeu/iY9PixY53r+i8wWfC03NP9anWwtQBbs/d38gkp5X778ytsuHaADGvzUYObdf1+k/74auECWhw7+cjSACjzniv8CZ+wUhN9I/1uGEKzup6z+/GYr/04bavwmkNHp7xee/F2NMZVAA1z+82s+x2BLivwr2ytbJ9em/KwEH1sMS1r8yp/2LhTfev81i5RexJsy/BlIKPVwR5b95Wyu0/Qjnv5DjoT7YYcs/nBhKZ6zrwr8wRYS7Nebuv3OW6geh+Lu/SLrixebL3j+pcyymN9Xrv8rHIFfWehZAMBwUdlo0DECTUc17EOb2PxpVB1SWChdAzjbhb9pTDUDQhmdvECX5P9FlMKCC9+g/IIAzjELgE0DajDngMv8GQFhWDmDPjNs/y1guLh96EkAxPi8k7DIEQJCc4URlhRhA3eLKKLwkEECqpNAyTBD/P6xpjXcDiwVAFtl//cQm4z+Ibt3XKiYTQM7mCLUb3QdAoM1t8yVv7D8aLZv2Nk8UQEAJPV5nQwxAtSsfTCoE9z9TPjXLXIIWQBVanC5W9AtAYM3d7Adm9j++5mQz1FoWQBUThyaVBghAwH5muQsV7T89Q1qv82MUQJoWGOfNuBdAzrkClkmwDkDQjKq77t37Py+g0dtitsE/ZwAMTwVPEUBojepluNwBQGYbtuW+t9w/HNWIJs6MEkDTNuQUSlgEQKxktPP5TcQ/ixbLB8JjEUCwuWjXMQYCQAS/R09FkRdAowpiZjhhDkB7LmlczD/7P01iQmhhsAVAnrtTwDy84z/Z6jfQ2TgTQChOCXMnWwpAhrW3daoz8z/HYJvVPI4VQLT3ik5FcA5Angi7LOZd+z+NNVzDy5gXQBXdvVTFUA1AYNMgOeYe+T8+qHXGCwkXQKQTOKwa5AJA8gFVoEMW0T+FwzJyttIRQAEAAAD/////BwAAAP////8xAAAA/////1cBAAD/////YQkAAP////+nQQAA/////5HLAQD/////95AMAP/////B9lcAAAAAAAAAAAAAAAAAAgAAAP////8OAAAA/////2IAAAD/////rgIAAP/////CEgAA/////06DAAD/////IpcDAP/////uIRkA/////4LtrwAAAAAAAAAAAAAAAAAAAAAAAgAAAP//////////AQAAAAMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////wIAAAD//////////wEAAAAAAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA/////////////////////wEAAAD///////////////8CAAAA////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD///////////////////////////////8CAAAA////////////////AQAAAP////////////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAAAQAAAP//////////AgAAAP//////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAAEAAAD//////////wIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAgAAAAAAAAACAAAAAQAAAAEAAAACAAAAAgAAAAAAAAAFAAAABQAAAAAAAAACAAAAAgAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAABAAAAAgAAAAIAAAACAAAAAAAAAAUAAAAGAAAAAAAAAAIAAAACAAAAAwAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAIAAAAAAAAAAgAAAAEAAAADAAAAAgAAAAIAAAAAAAAABQAAAAcAAAAAAAAAAgAAAAIAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAgAAAAAAAAACAAAAAQAAAAQAAAACAAAAAgAAAAAAAAAFAAAACAAAAAAAAAACAAAAAgAAAAMAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAACAAAAAAAAAAIAAAABAAAAAAAAAAIAAAACAAAAAAAAAAUAAAAJAAAAAAAAAAIAAAACAAAAAwAAAAUAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAIAAAACAAAAAAAAAAMAAAAOAAAAAgAAAAAAAAACAAAAAwAAAAAAAAAAAAAAAgAAAAIAAAADAAAABgAAAAAAAAAAAAAAAAAAAAAAAAALAAAAAgAAAAIAAAAAAAAAAwAAAAoAAAACAAAAAAAAAAIAAAADAAAAAQAAAAAAAAACAAAAAgAAAAMAAAAHAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAACAAAAAgAAAAAAAAADAAAACwAAAAIAAAAAAAAAAgAAAAMAAAACAAAAAAAAAAIAAAACAAAAAwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADQAAAAIAAAACAAAAAAAAAAMAAAAMAAAAAgAAAAAAAAACAAAAAwAAAAMAAAAAAAAAAgAAAAIAAAADAAAACQAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAgAAAAIAAAAAAAAAAwAAAA0AAAACAAAAAAAAAAIAAAADAAAABAAAAAAAAAACAAAAAgAAAAMAAAAKAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAACAAAAAgAAAAAAAAADAAAABgAAAAIAAAAAAAAAAgAAAAMAAAAPAAAAAAAAAAIAAAACAAAAAwAAAAsAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAIAAAACAAAAAAAAAAMAAAAHAAAAAgAAAAAAAAACAAAAAwAAABAAAAAAAAAAAgAAAAIAAAADAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAgAAAAIAAAAAAAAAAwAAAAgAAAACAAAAAAAAAAIAAAADAAAAEQAAAAAAAAACAAAAAgAAAAMAAAANAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAACAAAAAgAAAAAAAAADAAAACQAAAAIAAAAAAAAAAgAAAAMAAAASAAAAAAAAAAIAAAACAAAAAwAAAA4AAAAAAAAAAAAAAAAAAAAAAAAACQAAAAIAAAACAAAAAAAAAAMAAAAFAAAAAgAAAAAAAAACAAAAAwAAABMAAAAAAAAAAgAAAAIAAAADAAAADwAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAgAAAAAAAAACAAAAAQAAABMAAAACAAAAAgAAAAAAAAAFAAAACgAAAAAAAAACAAAAAgAAAAMAAAAQAAAAAAAAAAAAAAAAAAAAAAAAABEAAAACAAAAAAAAAAIAAAABAAAADwAAAAIAAAACAAAAAAAAAAUAAAALAAAAAAAAAAIAAAACAAAAAwAAABEAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAIAAAAAAAAAAgAAAAEAAAAQAAAAAgAAAAIAAAAAAAAABQAAAAwAAAAAAAAAAgAAAAIAAAADAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAATAAAAAgAAAAAAAAACAAAAAQAAABEAAAACAAAAAgAAAAAAAAAFAAAADQAAAAAAAAACAAAAAgAAAAMAAAATAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAACAAAAAAAAAAIAAAABAAAAEgAAAAIAAAACAAAAAAAAAAUAAAAOAAAAAAAAAAIAAAACAAAAAwAAAAIAAAABAAAAAAAAAAEAAAACAAAAAAAAAAAAAAACAAAAAQAAAAAAAAABAAAAAgAAAAEAAAAAAAAAAgAAAAAAAAAFAAAABAAAAAAAAAABAAAABQAAAAAAAAAAAAAABQAAAAQAAAAAAAAAAQAAAAUAAAAEAAAAAAAAAAUAAAAAAAAAAgAAAAEAAAAAAAAAAQAAAAIAAAAAAAAAAAAAAAIAAAABAAAAAAAAAAEAAAACAAAAAQAAAAAAAAACAAAAAgAAAAAAAAABAAAAAAAAAAAAAAAFAAAABAAAAAAAAAABAAAABQAAAAAAAAAAAAAABQAAAAQAAAAAAAAAAQAAAAUAAAAEAAAAAAAAAAUAAAAFAAAAAAAAAAEAAAAAAAAAAAAAAMuhRbbsNlBBYqHW9OmHIkF9XBuqnS31QAK37uYhNMhAOSo3UUupm0DC+6pc6JxvQHV9eseEEEJAzURsCyqlFEB8BQ4NMJjnPyy3tBoS97o/xawXQznRjj89J2K2CZxhP6vX43RIIDQ/S8isgygEBz+LvFHQkmzaPjFFFO7wMq4+AADMLkTtjkIAAOgkJqxhQgAAU7B0MjRCAADwpBcVB0IAAACYP2HaQQAAAIn/Ja5BzczM4Eg6gUHNzMxMU7BTQTMzMzNfgCZBAAAAAEi3+UAAAAAAwGPNQDMzMzMzy6BAmpmZmZkxc0AzMzMzM/NFQDMzMzMzMxlAzczMzMzM7D+ygXSx2U6RQKimJOvQKnpA23hmONTHY0A/AGcxyudNQNb3K647mzZA+S56rrwWIUAm4kUQ+9UJQKre9hGzh/M/BLvoy9WG3T+LmqMf8VHGP2m3nYNV37A/gbFHcyeCmT+cBPWBckiDP61tZACjKW0/q2RbYVUYVj8uDypVyLNAP6jGS5cA5zBBwcqhBdCNGUEGEhQ/JVEDQT6WPnRbNO1AB/AWSJgT1kDfUWNCNLDAQNk+5C33OqlAchWL34QSk0DKvtDIrNV8QNF0G3kFzGVASSeWhBl6UED+/0mNGuk4QGjA/dm/1CJALPLPMql6DEDSHoDrwpP1P2jouzWST+A/egAAAAAAAABKAwAAAAAAAPoWAAAAAAAAyqAAAAAAAAB6ZQQAAAAAAErGHgAAAAAA+mvXAAAAAADK8+MFAAAAAHqqOykAAAAASqmhIAEAAAD6oGvkBwAAAMpm8T43AAAAes+ZuIIBAABKrDQMkwoAAPq1cFUFSgAAyvkUViUGAgAAAAAAAwAAAAYAAAACAAAABQAAAAEAAAAEAAAAAAAAAAAAAAAFAAAAAwAAAAEAAAAGAAAABAAAAAIAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAP////////////////////////////////////8AAAAA/////wAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAP////8AAAAAAAAAAAEAAAABAAAAAAAAAAAAAAD/////AAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAA/////wUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////AAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////////////////////////////wAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAUAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////////////////////////////8AAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAABAAAAAAAAAAAAAAABAAAAAQAAAAEAAAAAAAAAAQAAAAAAAAAFAAAAAQAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAAAAAABAAEAAAEBAAAAAAABAAAAAQAAAAEAAQAAAAAAAAAAAAAAAAAAAAAEAAAABAAAAAAAAAACAAAAAQAAAAMAAAAOAAAABgAAAAsAAAACAAAABwAAAAEAAAAYAAAABQAAAAoAAAABAAAABgAAAAAAAAAmAAAABwAAAAwAAAADAAAACAAAAAIAAAAxAAAACQAAAA4AAAAAAAAABQAAAAQAAAA6AAAACAAAAA0AAAAEAAAACQAAAAMAAAA/AAAACwAAAAYAAAAPAAAACgAAABAAAABIAAAADAAAAAcAAAAQAAAACwAAABEAAABTAAAACgAAAAUAAAATAAAADgAAAA8AAABhAAAADQAAAAgAAAARAAAADAAAABIAAABrAAAADgAAAAkAAAASAAAADQAAABMAAAB1AAAADwAAABMAAAARAAAAEgAAABAAAAAHAAAABwAAAAEAAAACAAAABAAAAAMAAAAAAAAAAAAAAAcAAAADAAAAAQAAAAIAAAAFAAAABAAAAAAAAAAAAAAAYWxnb3MuYwBfcG9seWZpbGxJbnRlcm5hbABhZGphY2VudEZhY2VEaXJbdG1wRmlqay5mYWNlXVtmaWprLmZhY2VdID09IEtJAGZhY2VpamsuYwBfZmFjZUlqa1BlbnRUb0dlb0JvdW5kYXJ5AGFkamFjZW50RmFjZURpcltjZW50ZXJJSksuZmFjZV1bZmFjZTJdID09IEtJAF9mYWNlSWprVG9HZW9Cb3VuZGFyeQBwb2x5Z29uLT5uZXh0ID09IE5VTEwAbGlua2VkR2VvLmMAYWRkTmV3TGlua2VkUG9seWdvbgBuZXh0ICE9IE5VTEwAbG9vcCAhPSBOVUxMAGFkZE5ld0xpbmtlZExvb3AAcG9seWdvbi0+Zmlyc3QgPT0gTlVMTABhZGRMaW5rZWRMb29wAGNvb3JkICE9IE5VTEwAYWRkTGlua2VkQ29vcmQAbG9vcC0+Zmlyc3QgPT0gTlVMTABpbm5lckxvb3BzICE9IE5VTEwAbm9ybWFsaXplTXVsdGlQb2x5Z29uAGJib3hlcyAhPSBOVUxMAGNhbmRpZGF0ZXMgIT0gTlVMTABmaW5kUG9seWdvbkZvckhvbGUAY2FuZGlkYXRlQkJveGVzICE9IE5VTEwAcmV2RGlyICE9IElOVkFMSURfRElHSVQAbG9jYWxpai5jAGgzVG9Mb2NhbElqawBiYXNlQ2VsbCAhPSBvcmlnaW5CYXNlQ2VsbAAhKG9yaWdpbk9uUGVudCAmJiBpbmRleE9uUGVudCkAcGVudGFnb25Sb3RhdGlvbnMgPj0gMABkaXJlY3Rpb25Sb3RhdGlvbnMgPj0gMABiYXNlQ2VsbCA9PSBvcmlnaW5CYXNlQ2VsbABiYXNlQ2VsbCAhPSBJTlZBTElEX0JBU0VfQ0VMTABsb2NhbElqa1RvSDMAIV9pc0Jhc2VDZWxsUGVudGFnb24oYmFzZUNlbGwpAGJhc2VDZWxsUm90YXRpb25zID49IDAAd2l0aGluUGVudGFnb25Sb3RhdGlvbnMgPj0gMABncmFwaC0+YnVja2V0cyAhPSBOVUxMAHZlcnRleEdyYXBoLmMAaW5pdFZlcnRleEdyYXBoAG5vZGUgIT0gTlVMTABhZGRWZXJ0ZXhOb2Rl";function Y(A){return A}function O(A){return A.replace(/\b__Z[\w\d_]+/g,(function(A){return A===A?A:A+" ["+A+"]"}))}function j(){var A=new Error;if(!A.stack){try{throw new Error(0)}catch(e){A=e}if(!A.stack)return"(no stack trace available)"}return A.stack.toString()}function N(){return p.length}function Z(A){try{var e=new ArrayBuffer(A);if(e.byteLength!=A)return;return new Int8Array(e).set(p),$(e),Q(e),1}catch(A){}}var W="function"==typeof atob?atob:function(A){var e,r,t,i,n,o,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f="",s=0;A=A.replace(/[^A-Za-z0-9\+\/\=]/g,"");do{e=a.indexOf(A.charAt(s++))<<2|(i=a.indexOf(A.charAt(s++)))>>4,r=(15&i)<<4|(n=a.indexOf(A.charAt(s++)))>>2,t=(3&n)<<6|(o=a.indexOf(A.charAt(s++))),f+=String.fromCharCode(e),64!==n&&(f+=String.fromCharCode(r)),64!==o&&(f+=String.fromCharCode(t))}while(s>2]=A,i[a+4>>2]=e,(a=0!=(0|n))&&(i[n>>2]=0),0|UA(A,e))return I=o,0|(d=1);i[d>>2]=0;A:do{if((0|r)>=1)if(a)for(l=0,h=1,c=1,f=0,a=A;;){if(!(f|l)){if(0==(0|(a=0|U(a,e,4,d)))&0==(0|(e=0|M()))){a=2;break A}if(0|UA(a,e)){a=1;break A}}if(0==(0|(a=0|U(a,e,0|i[16+(l<<2)>>2],d)))&0==(0|(e=0|M()))){a=2;break A}if(i[(A=t+(c<<3)|0)>>2]=a,i[A+4>>2]=e,i[n+(c<<2)>>2]=h,A=(0|(f=f+1|0))==(0|h),u=6==(0|(s=l+1|0)),0|UA(a,e)){a=1;break A}if((0|(h=h+(u&A&1)|0))>(0|r)){a=0;break}l=A?u?0:s:l,c=c+1|0,f=A?0:f}else for(l=0,h=1,c=1,f=0,a=A;;){if(!(f|l)){if(0==(0|(a=0|U(a,e,4,d)))&0==(0|(e=0|M()))){a=2;break A}if(0|UA(a,e)){a=1;break A}}if(0==(0|(a=0|U(a,e,0|i[16+(l<<2)>>2],d)))&0==(0|(e=0|M()))){a=2;break A}if(i[(A=t+(c<<3)|0)>>2]=a,i[A+4>>2]=e,A=(0|(f=f+1|0))==(0|h),u=6==(0|(s=l+1|0)),0|UA(a,e)){a=1;break A}if((0|(h=h+(u&A&1)|0))>(0|r)){a=0;break}l=A?u?0:s:l,c=c+1|0,f=A?0:f}else a=0}while(0);return I=o,0|(d=a)}function P(A,e,r,t,n,o,a){r|=0,t|=0,n|=0,o|=0,a|=0;var f,s,u=0,l=0,h=0,c=0,d=0;if(s=I,I=I+16|0,f=s,0==(0|(A|=0))&0==(0|(e|=0)))I=s;else{if(u=0|Me(0|A,0|e,0|o,((0|o)<0)<<31>>31|0),M(),!(0==(0|(d=0|i[(c=l=t+(u<<3)|0)>>2]))&0==(0|(c=0|i[c+4>>2]))|(h=(0|d)==(0|A)&(0|c)==(0|e))))do{h=(0|(c=0|i[(d=l=t+((u=(u+1|0)%(0|o)|0)<<3)|0)>>2]))==(0|A)&(0|(d=0|i[d+4>>2]))==(0|e)}while(!(0==(0|c)&0==(0|d)|h));u=n+(u<<2)|0,h&&(0|i[u>>2])<=(0|a)||(i[(d=l)>>2]=A,i[d+4>>2]=e,i[u>>2]=a,(0|a)>=(0|r)||(d=a+1|0,i[f>>2]=0,P(c=0|U(A,e,2,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,3,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,1,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,5,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,4,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,6,f),0|M(),r,t,n,o,d))),I=s}}function U(A,e,r,t){A|=0,e|=0,r|=0;var n,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0;if((0|i[(t|=0)>>2])>0){a=0;do{r=0|fA(r),a=a+1|0}while((0|a)<(0|i[t>>2]))}n=0|Qe(0|A,0|e,45),M(),o=127&n,f=0|GA(A,e),a=0|Qe(0|A,0|e,52),M(),a&=15;A:do{if(a)for(;;){if(h=0|Qe(0|A,0|e,0|(l=3*(15-a|0)|0)),M(),h&=7,c=0==(0|RA(a)),a=a+-1|0,u=0|ye(7,0,0|l),e&=~(0|M()),A=(l=0|ye(0|i[(c?464:48)+(28*h|0)+(r<<2)>>2],0,0|l))|A&~u,e|=0|M(),!(r=0|i[(c?672:256)+(28*h|0)+(r<<2)>>2])){r=0;break A}if(!a){s=6;break}}else s=6}while(0);6==(0|s)&&(A|=h=0|ye(0|(c=0|i[880+(28*o|0)+(r<<2)>>2]),0,45),e=0|M()|-1040385&e,r=0|i[4304+(28*o|0)+(r<<2)>>2],127==(127&c|0)&&(c=0|ye(0|i[880+(28*o|0)+20>>2],0,45),e=0|M()|-1040385&e,r=0|i[4304+(28*o|0)+20>>2],A=0|TA(c|A,e),e=0|M(),i[t>>2]=1+(0|i[t>>2]))),s=0|Qe(0|A,0|e,45),M(),s&=127;A:do{if(0|S(s)){e:do{if(1==(0|GA(A,e))){if((0|o)!=(0|s)){if(0|R(s,0|i[7728+(28*o|0)>>2])){A=0|HA(A,e),f=1,e=0|M();break}A=0|TA(A,e),f=1,e=0|M();break}switch(0|f){case 5:A=0|HA(A,e),e=0|M(),i[t>>2]=5+(0|i[t>>2]),f=0;break e;case 3:A=0|TA(A,e),e=0|M(),i[t>>2]=1+(0|i[t>>2]),f=0;break e;default:return c=0,k(0|(h=0)),0|c}}else f=0}while(0);if((0|r)>0){a=0;do{A=0|SA(A,e),e=0|M(),a=a+1|0}while((0|a)!=(0|r))}if((0|o)!=(0|s)){if(!(0|T(s))){if(0!=(0|f)|5!=(0|GA(A,e)))break;i[t>>2]=1+(0|i[t>>2]);break}switch(127&n){case 8:case 118:break A}3!=(0|GA(A,e))&&(i[t>>2]=1+(0|i[t>>2]))}}else if((0|r)>0){a=0;do{A=0|TA(A,e),e=0|M(),a=a+1|0}while((0|a)!=(0|r))}}while(0);return i[t>>2]=((0|i[t>>2])+r|0)%6|0,c=A,k(0|(h=e)),0|c}function G(A,e,r,t,o,a){e|=0,r|=0,t|=0,o|=0,a|=0;var f,s,u,l,h,c,d,g,w,p=0,B=0,b=0,v=0,m=0,k=0,Q=0,y=0,E=0,x=0,D=0,_=0,F=0,C=0;if(w=I,I=I+48|0,c=w+32|0,d=w+16|0,g=w,(0|(p=0|i[(A|=0)>>2]))<=0)return I=w,0|(_=0);f=A+4|0,s=c+8|0,u=d+8|0,l=g+8|0,h=((0|e)<0)<<31>>31,D=0;A:for(;;){E=(B=0|i[f>>2])+(D<<4)|0,i[c>>2]=i[E>>2],i[c+4>>2]=i[E+4>>2],i[c+8>>2]=i[E+8>>2],i[c+12>>2]=i[E+12>>2],(0|D)==(p+-1|0)?(i[d>>2]=i[B>>2],i[d+4>>2]=i[B+4>>2],i[d+8>>2]=i[B+8>>2],i[d+12>>2]=i[B+12>>2]):(E=B+(D+1<<4)|0,i[d>>2]=i[E>>2],i[d+4>>2]=i[E+4>>2],i[d+8>>2]=i[E+8>>2],i[d+12>>2]=i[E+12>>2]),E=0|N(c,d,r);e:do{if((0|E)>0){x=+(0|E),y=0;r:for(;;){C=+(E-y|0),F=+(0|y),n[g>>3]=+n[c>>3]*C/x+ +n[d>>3]*F/x,n[l>>3]=+n[s>>3]*C/x+ +n[u>>3]*F/x,B=0|Me(0|(k=0|LA(g,r)),0|(Q=0|M()),0|e,0|h),M(),v=0|i[(b=p=a+(B<<3)|0)>>2],b=0|i[b+4>>2];t:do{if(0==(0|v)&0==(0|b))_=14;else for(m=0;;){if((0|m)>(0|e)){p=1;break t}if((0|v)==(0|k)&(0|b)==(0|Q)){p=7;break t}if(0==(0|(v=0|i[(b=p=a+((B=(B+1|0)%(0|e)|0)<<3)|0)>>2]))&0==(0|(b=0|i[b+4>>2]))){_=14;break}m=m+1|0}}while(0);switch(14==(0|_)&&(_=0,0==(0|k)&0==(0|Q)?p=7:(i[p>>2]=k,i[p+4>>2]=Q,p=0|i[t>>2],i[(m=o+(p<<3)|0)>>2]=k,i[m+4>>2]=Q,i[t>>2]=p+1,p=0)),7&p){case 7:case 0:break;default:break r}if((0|E)<=(0|(y=y+1|0))){_=8;break e}}if(0|p){p=-1,_=20;break A}}else _=8}while(0);if(8==(0|_)&&(_=0),(0|(D=D+1|0))>=(0|(p=0|i[A>>2]))){p=0,_=20;break}}return 20==(0|_)?(I=w,0|p):0}function S(A){return 0|i[7728+(28*(A|=0)|0)+16>>2]}function T(A){return 4==(0|(A|=0))|117==(0|A)|0}function V(A){return 0|i[11152+(216*(0|i[(A|=0)>>2])|0)+(72*(0|i[A+4>>2])|0)+(24*(0|i[A+8>>2])|0)+(i[A+12>>2]<<3)>>2]}function H(A){return 0|i[11152+(216*(0|i[(A|=0)>>2])|0)+(72*(0|i[A+4>>2])|0)+(24*(0|i[A+8>>2])|0)+(i[A+12>>2]<<3)+4>>2]}function R(A,e){return e|=0,(0|i[7728+(28*(A|=0)|0)+20>>2])==(0|e)?0|(e=1):0|(e=(0|i[7728+(28*A|0)+24>>2])==(0|e))}function L(A,e){return 0|i[880+(28*(A|=0)|0)+((e|=0)<<2)>>2]}function z(A,e){return e|=0,(0|i[880+(28*(A|=0)|0)>>2])==(0|e)?0|(e=0):(0|i[880+(28*A|0)+4>>2])==(0|e)?0|(e=1):(0|i[880+(28*A|0)+8>>2])==(0|e)?0|(e=2):(0|i[880+(28*A|0)+12>>2])==(0|e)?0|(e=3):(0|i[880+(28*A|0)+16>>2])==(0|e)?0|(e=4):(0|i[880+(28*A|0)+20>>2])==(0|e)?0|(e=5):0|((0|i[880+(28*A|0)+24>>2])==(0|e)?6:7)}function Y(A){return+n[(A|=0)+16>>3]<+n[A+24>>3]|0}function O(A,e){A|=0;var r,t,i=0;return(i=+n[(e|=0)>>3])>=+n[A+8>>3]&&i<=+n[A>>3]?(r=+n[A+16>>3],i=+n[A+24>>3],e=(t=+n[e+8>>3])>=i,A=t<=r&1,r>2]=0,l=l+4|0}while((0|l)<(0|h));return NA(e,o),OA(h=0|i[(l=o)>>2],l=0|i[l+4>>2],r),jA(h,l,t),s=+DA(r,t+8|0),n[r>>3]=+n[A>>3],n[(l=r+8|0)>>3]=+n[A+16>>3],n[t>>3]=+n[A+8>>3],n[(h=t+8|0)>>3]=+n[A+24>>3],u=+DA(r,t),h=~~+B(+u*u/+Ee(+ +f(+(+n[l>>3]-+n[h>>3])/(+n[r>>3]-+n[t>>3])),3)/(s*(2.59807621135*s)*.8)),I=a,0|(0==(0|h)?1:h)}function N(A,e,r){A|=0,e|=0,r|=0;var t,n,o,a,f,s=0,u=0;a=I,I=I+288|0,t=a+264|0,n=a+96|0,u=(s=o=a)+96|0;do{i[s>>2]=0,s=s+4|0}while((0|s)<(0|u));return NA(r,o),OA(s=0|i[(u=o)>>2],u=0|i[u+4>>2],t),jA(s,u,n),f=+DA(t,n+8|0),u=~~+B(+ +DA(A,e)/(2*f)),I=a,0|(0==(0|u)?1:u)}function Z(A,e,r,t){e|=0,r|=0,t|=0,i[(A|=0)>>2]=e,i[A+4>>2]=r,i[A+8>>2]=t}function W(A,e){A|=0;var r,t,o,a,s=0,u=0,l=0,h=0,c=0,d=0,g=0;i[(a=(e|=0)+8|0)>>2]=0,t=+n[A>>3],h=+f(+t),o=+n[A+8>>3],h+=.5*(c=+f(+o)/.8660254037844386),h-=+(0|(s=~~h)),c-=+(0|(A=~~c));do{if(h<.5){if(h<.3333333333333333){if(i[e>>2]=s,c<.5*(h+1)){i[e+4>>2]=A;break}A=A+1|0,i[e+4>>2]=A;break}if(A=(1&!(c<(g=1-h)))+A|0,i[e+4>>2]=A,g<=c&c<2*h){s=s+1|0,i[e>>2]=s;break}i[e>>2]=s;break}if(!(h<.6666666666666666)){if(s=s+1|0,i[e>>2]=s,c<.5*h){i[e+4>>2]=A;break}A=A+1|0,i[e+4>>2]=A;break}if(c<1-h){if(i[e+4>>2]=A,2*h-1>2]=s;break}}else A=A+1|0,i[e+4>>2]=A;s=s+1|0,i[e>>2]=s}while(0);do{if(t<0){if(1&A){s=~~(+(0|s)-(2*(+((d=0|ve(0|s,((0|s)<0)<<31>>31|0,0|(d=(A+1|0)/2|0),((0|d)<0)<<31>>31|0))>>>0)+4294967296*+(0|M()))+1)),i[e>>2]=s;break}s=~~(+(0|s)-2*(+((d=0|ve(0|s,((0|s)<0)<<31>>31|0,0|(d=(0|A)/2|0),((0|d)<0)<<31>>31|0))>>>0)+4294967296*+(0|M()))),i[e>>2]=s;break}}while(0);d=e+4|0,o<0&&(s=s-((1|A<<1)/2|0)|0,i[e>>2]=s,A=0-A|0,i[d>>2]=A),u=A-s|0,(0|s)<0?(l=0-s|0,i[d>>2]=u,i[a>>2]=l,i[e>>2]=0,A=u,s=0):l=0,(0|A)<0&&(s=s-A|0,i[e>>2]=s,l=l-A|0,i[a>>2]=l,i[d>>2]=0,A=0),r=s-l|0,u=A-l|0,(0|l)<0&&(i[e>>2]=r,i[d>>2]=u,i[a>>2]=0,A=u,s=r,l=0),(0|(u=(0|l)<(0|(u=(0|A)<(0|s)?A:s))?l:u))<=0||(i[e>>2]=s-u,i[d>>2]=A-u,i[a>>2]=l-u)}function J(A){var e,r=0,t=0,n=0,o=0,a=0;r=0|i[(A|=0)>>2],t=0|i[(e=A+4|0)>>2],(0|r)<0&&(t=t-r|0,i[e>>2]=t,i[(a=A+8|0)>>2]=(0|i[a>>2])-r,i[A>>2]=0,r=0),(0|t)<0?(r=r-t|0,i[A>>2]=r,o=(0|i[(a=A+8|0)>>2])-t|0,i[a>>2]=o,i[e>>2]=0,t=0):(a=o=A+8|0,o=0|i[o>>2]),(0|o)<0&&(r=r-o|0,i[A>>2]=r,t=t-o|0,i[e>>2]=t,i[a>>2]=0,o=0),(0|(n=(0|o)<(0|(n=(0|t)<(0|r)?t:r))?o:n))<=0||(i[A>>2]=r-n,i[e>>2]=t-n,i[a>>2]=o-n)}function K(A,e){e|=0;var r,t;t=0|i[(A|=0)+8>>2],r=+((0|i[A+4>>2])-t|0),n[e>>3]=+((0|i[A>>2])-t|0)-.5*r,n[e+8>>3]=.8660254037844386*r}function X(A,e,r){A|=0,e|=0,i[(r|=0)>>2]=(0|i[e>>2])+(0|i[A>>2]),i[r+4>>2]=(0|i[e+4>>2])+(0|i[A+4>>2]),i[r+8>>2]=(0|i[e+8>>2])+(0|i[A+8>>2])}function q(A,e,r){A|=0,e|=0,i[(r|=0)>>2]=(0|i[A>>2])-(0|i[e>>2]),i[r+4>>2]=(0|i[A+4>>2])-(0|i[e+4>>2]),i[r+8>>2]=(0|i[A+8>>2])-(0|i[e+8>>2])}function $(A,e){e|=0;var r,t=0;t=0|b(0|i[(A|=0)>>2],e),i[A>>2]=t,r=0|b(0|i[(t=A+4|0)>>2],e),i[t>>2]=r,e=0|b(0|i[(A=A+8|0)>>2],e),i[A>>2]=e}function AA(A){var e,r,t=0,n=0,o=0,a=0,f=0;f=(0|(r=0|i[(A|=0)>>2]))<0,A=(A=(n=(0|(a=((e=(0|(o=(0|i[A+4>>2])-(f?r:0)|0))<0)?0-o|0:0)+((0|i[A+8>>2])-(f?r:0))|0))<0)?0:a)-((o=(0|(n=(0|A)<(0|(n=(0|(t=(e?0:o)-(n?a:0)|0))<(0|(a=(f?0:r)-(e?o:0)-(n?a:0)|0))?t:a))?A:n))>0)?n:0)|0,t=t-(o?n:0)|0;A:do{switch(a-(o?n:0)|0){case 0:switch(0|t){case 0:return 0|(f=0==(0|A)?0:1==(0|A)?1:7);case 1:return 0|(f=0==(0|A)?2:1==(0|A)?3:7);default:break A}case 1:switch(0|t){case 0:return 0|(f=0==(0|A)?4:1==(0|A)?5:7);case 1:if(A)break A;return 0|(A=6);default:break A}}}while(0);return 0|(f=7)}function eA(A){var e,r,t=0,n=0,o=0,a=0,f=0;n=0|i[(e=(A|=0)+8|0)>>2],o=0|we(+((3*(t=(0|i[A>>2])-n|0)|0)-(n=(0|i[(r=A+4|0)>>2])-n|0)|0)/7),i[A>>2]=o,t=0|we(+((n<<1)+t|0)/7),i[r>>2]=t,i[e>>2]=0,n=t-o|0,(0|o)<0?(f=0-o|0,i[r>>2]=n,i[e>>2]=f,i[A>>2]=0,t=n,o=0,n=f):n=0,(0|t)<0&&(o=o-t|0,i[A>>2]=o,n=n-t|0,i[e>>2]=n,i[r>>2]=0,t=0),f=o-n|0,a=t-n|0,(0|n)<0?(i[A>>2]=f,i[r>>2]=a,i[e>>2]=0,t=a,a=f,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|t)<(0|a)?t:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=t-o,i[e>>2]=n-o)}function rA(A){var e,r,t=0,n=0,o=0,a=0,f=0;n=0|i[(e=(A|=0)+8|0)>>2],o=0|we(+(((t=(0|i[A>>2])-n|0)<<1)+(n=(0|i[(r=A+4|0)>>2])-n|0)|0)/7),i[A>>2]=o,t=0|we(+((3*n|0)-t|0)/7),i[r>>2]=t,i[e>>2]=0,n=t-o|0,(0|o)<0?(f=0-o|0,i[r>>2]=n,i[e>>2]=f,i[A>>2]=0,t=n,o=0,n=f):n=0,(0|t)<0&&(o=o-t|0,i[A>>2]=o,n=n-t|0,i[e>>2]=n,i[r>>2]=0,t=0),f=o-n|0,a=t-n|0,(0|n)<0?(i[A>>2]=f,i[r>>2]=a,i[e>>2]=0,t=a,a=f,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|t)<(0|a)?t:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=t-o,i[e>>2]=n-o)}function tA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],o=0|i[(r=A+4|0)>>2],a=0|i[(t=A+8|0)>>2],f=o+(3*n|0)|0,i[A>>2]=f,o=a+(3*o|0)|0,i[r>>2]=o,n=(3*a|0)+n|0,i[t>>2]=n,a=o-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=a,i[t>>2]=n,i[A>>2]=0,o=a,a=0):a=f,(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function iA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=(3*(n=0|i[(r=A+4|0)>>2])|0)+f|0,f=(o=0|i[(t=A+8|0)>>2])+(3*f|0)|0,i[A>>2]=f,i[r>>2]=a,n=(3*o|0)+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,f=0):o=a,(0|o)<0&&(f=f-o|0,i[A>>2]=f,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=f-n|0,a=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=a,i[t>>2]=0,f=e,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|a)<(0|f)?a:f))?n:o))<=0||(i[A>>2]=f-o,i[r>>2]=a-o,i[t>>2]=n-o)}function nA(A,e){A|=0;var r,t,n,o=0,a=0,f=0;((e|=0)+-1|0)>>>0>=6||(f=(0|i[15472+(12*e|0)>>2])+(0|i[A>>2])|0,i[A>>2]=f,n=A+4|0,a=(0|i[15472+(12*e|0)+4>>2])+(0|i[n>>2])|0,i[n>>2]=a,t=A+8|0,e=(0|i[15472+(12*e|0)+8>>2])+(0|i[t>>2])|0,i[t>>2]=e,o=a-f|0,(0|f)<0?(e=e-f|0,i[n>>2]=o,i[t>>2]=e,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,e=e-o|0,i[t>>2]=e,i[n>>2]=0,o=0),r=a-e|0,f=o-e|0,(0|e)<0?(i[A>>2]=r,i[n>>2]=f,i[t>>2]=0,a=r,e=0):f=o,(0|(o=(0|e)<(0|(o=(0|f)<(0|a)?f:a))?e:o))<=0||(i[A>>2]=a-o,i[n>>2]=f-o,i[t>>2]=e-o))}function oA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=(n=0|i[(r=A+4|0)>>2])+f|0,f=(o=0|i[(t=A+8|0)>>2])+f|0,i[A>>2]=f,i[r>>2]=a,n=o+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function aA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],a=0|i[(r=A+4|0)>>2],o=0|i[(t=A+8|0)>>2],f=a+n|0,i[A>>2]=f,a=o+a|0,i[r>>2]=a,n=o+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function fA(A){switch(0|(A|=0)){case 1:A=5;break;case 5:A=4;break;case 4:A=6;break;case 6:A=2;break;case 2:A=3;break;case 3:A=1}return 0|A}function sA(A){switch(0|(A|=0)){case 1:A=3;break;case 3:A=2;break;case 2:A=6;break;case 6:A=4;break;case 4:A=5;break;case 5:A=1}return 0|A}function uA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],o=0|i[(r=A+4|0)>>2],a=0|i[(t=A+8|0)>>2],f=o+(n<<1)|0,i[A>>2]=f,o=a+(o<<1)|0,i[r>>2]=o,n=(a<<1)+n|0,i[t>>2]=n,a=o-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=a,i[t>>2]=n,i[A>>2]=0,o=a,a=0):a=f,(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function lA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=((n=0|i[(r=A+4|0)>>2])<<1)+f|0,f=(o=0|i[(t=A+8|0)>>2])+(f<<1)|0,i[A>>2]=f,i[r>>2]=a,n=(o<<1)+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,f=0):o=a,(0|o)<0&&(f=f-o|0,i[A>>2]=f,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=f-n|0,a=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=a,i[t>>2]=0,f=e,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|a)<(0|f)?a:f))?n:o))<=0||(i[A>>2]=f-o,i[r>>2]=a-o,i[t>>2]=n-o)}function hA(A,e){e|=0;var r,t,n,o=0,a=0,f=0;return n=(0|(t=(0|i[(A|=0)>>2])-(0|i[e>>2])|0))<0,r=(0|(a=(0|i[A+4>>2])-(0|i[e+4>>2])-(n?t:0)|0))<0,e=(e=(A=(0|(f=(n?0-t|0:0)+(0|i[A+8>>2])-(0|i[e+8>>2])+(r?0-a|0:0)|0))<0)?0:f)-((a=(0|(A=(0|e)<(0|(A=(0|(o=(r?0:a)-(A?f:0)|0))<(0|(f=(n?0:t)-(r?a:0)-(A?f:0)|0))?o:f))?e:A))>0)?A:0)|0,o=o-(a?A:0)|0,0|((0|(A=(0|(A=f-(a?A:0)|0))>-1?A:0-A|0))>(0|(e=(0|(o=(0|o)>-1?o:0-o|0))>(0|(e=(0|e)>-1?e:0-e|0))?o:e))?A:e)}function cA(A,e){e|=0;var r;r=0|i[(A|=0)+8>>2],i[e>>2]=(0|i[A>>2])-r,i[e+4>>2]=(0|i[A+4>>2])-r}function dA(A,e){e|=0;var r,t,n,o=0,a=0,f=0;a=0|i[(A|=0)>>2],i[e>>2]=a,A=0|i[A+4>>2],i[(t=e+4|0)>>2]=A,i[(n=e+8|0)>>2]=0,o=A-a|0,(0|a)<0?(A=0-a|0,i[t>>2]=o,i[n>>2]=A,i[e>>2]=0,a=0):(o=A,A=0),(0|o)<0&&(a=a-o|0,i[e>>2]=a,A=A-o|0,i[n>>2]=A,i[t>>2]=0,o=0),r=a-A|0,f=o-A|0,(0|A)<0?(i[e>>2]=r,i[t>>2]=f,i[n>>2]=0,o=f,f=r,A=0):f=a,(0|(a=(0|A)<(0|(a=(0|o)<(0|f)?o:f))?A:a))<=0||(i[e>>2]=f-a,i[t>>2]=o-a,i[n>>2]=A-a)}function gA(A){var e,r,t,n;r=(n=0|i[(e=(A|=0)+8|0)>>2])-(0|i[A>>2])|0,i[A>>2]=r,A=(0|i[(t=A+4|0)>>2])-n|0,i[t>>2]=A,i[e>>2]=0-(A+r)}function wA(A){var e,r,t=0,n=0,o=0,a=0,f=0;t=0-(n=0|i[(A|=0)>>2])|0,i[A>>2]=t,i[(e=A+8|0)>>2]=0,a=(o=0|i[(r=A+4|0)>>2])+n|0,(0|n)>0?(i[r>>2]=a,i[e>>2]=n,i[A>>2]=0,t=0,o=a):n=0,(0|o)<0?(f=t-o|0,i[A>>2]=f,n=n-o|0,i[e>>2]=n,i[r>>2]=0,a=f-n|0,t=0-n|0,(0|n)<0?(i[A>>2]=a,i[r>>2]=t,i[e>>2]=0,o=t,n=0):(o=0,a=f)):a=t,(0|(t=(0|n)<(0|(t=(0|o)<(0|a)?o:a))?n:t))<=0||(i[A>>2]=a-t,i[r>>2]=o-t,i[e>>2]=n-t)}function pA(A,e,r,t){e|=0,r|=0,t|=0;var o,a=0,f=0,s=0,u=0;if(o=I,I=I+32|0,function(A,e){e|=0;var r=0,t=0,i=0;r=+n[(A=A|0)>>3],t=+l(+r),r=+h(+r),n[e+16>>3]=r,r=+n[A+8>>3],i=t*+l(+r),n[e>>3]=i,r=t*+h(+r),n[e+8>>3]=r}(A|=0,f=o),i[r>>2]=0,a=+fe(15888,f),(s=+fe(15912,f))>2]=1,a=s),(s=+fe(15936,f))>2]=2,a=s),(s=+fe(15960,f))>2]=3,a=s),(s=+fe(15984,f))>2]=4,a=s),(s=+fe(16008,f))>2]=5,a=s),(s=+fe(16032,f))>2]=6,a=s),(s=+fe(16056,f))>2]=7,a=s),(s=+fe(16080,f))>2]=8,a=s),(s=+fe(16104,f))>2]=9,a=s),(s=+fe(16128,f))>2]=10,a=s),(s=+fe(16152,f))>2]=11,a=s),(s=+fe(16176,f))>2]=12,a=s),(s=+fe(16200,f))>2]=13,a=s),(s=+fe(16224,f))>2]=14,a=s),(s=+fe(16248,f))>2]=15,a=s),(s=+fe(16272,f))>2]=16,a=s),(s=+fe(16296,f))>2]=17,a=s),(s=+fe(16320,f))>2]=18,a=s),(s=+fe(16344,f))>2]=19,a=s),(s=+d(+(1-.5*a)))<1e-16)return i[t>>2]=0,i[t+4>>2]=0,i[t+8>>2]=0,i[t+12>>2]=0,void(I=o);if(r=0|i[r>>2],a=+EA((a=+n[16368+(24*r|0)>>3])-+EA(+function(A,e){A|=0;var r=0,t=0,i=0,o=0,a=0;return o=+n[(e=e|0)>>3],t=+l(+o),i=+n[e+8>>3]-+n[A+8>>3],a=t*+h(+i),r=+n[A>>3],+ +p(+a,+(+h(+o)*+l(+r)-+l(+i)*(t*+h(+r))))}(15568+(r<<4)|0,A))),u=0|RA(e)?+EA(a+-.3334731722518321):a,a=+c(+s)/.381966011250105,(0|e)>0){f=0;do{a*=2.6457513110645907,f=f+1|0}while((0|f)!=(0|e))}s=+l(+u)*a,n[t>>3]=s,u=+h(+u)*a,n[t+8>>3]=u,I=o}function BA(A,e,r,t,o){e|=0,r|=0,t|=0,o|=0;var a=0,u=0;if((a=+function(A){var e=0,r=0;return r=+n[(A=A|0)>>3],e=+n[A+8>>3],+ +s(+(r*r+e*e))}(A|=0))<1e-16)return e=15568+(e<<4)|0,i[o>>2]=i[e>>2],i[o+4>>2]=i[e+4>>2],i[o+8>>2]=i[e+8>>2],void(i[o+12>>2]=i[e+12>>2]);if(u=+p(+ +n[A+8>>3],+ +n[A>>3]),(0|r)>0){A=0;do{a/=2.6457513110645907,A=A+1|0}while((0|A)!=(0|r))}t?(a/=3,r=0==(0|RA(r)),a=+w(.381966011250105*(r?a:a/2.6457513110645907))):(a=+w(.381966011250105*a),0|RA(r)&&(u=+EA(u+.3334731722518321))),function(A,e,r,t){A|=0,e=+e,t|=0;var o=0,a=0,s=0,u=0;if((r=+r)<1e-16)return i[t>>2]=i[A>>2],i[t+4>>2]=i[A+4>>2],i[t+8>>2]=i[A+8>>2],void(i[t+12>>2]=i[A+12>>2]);a=e<0?e+6.283185307179586:e,a=e>=6.283185307179586?a+-6.283185307179586:a;do{if(!(a<1e-16)){if(o=+f(+(a+-3.141592653589793))<1e-16,e=+n[A>>3],o){e-=r,n[t>>3]=e,o=t;break}if(s=+l(+r),r=+h(+r),e=s*+h(+e)+ +l(+a)*(r*+l(+e)),e=+g(+((e=e>1?1:e)<-1?-1:e)),n[t>>3]=e,+f(+(e+-1.5707963267948966))<1e-16)return n[t>>3]=1.5707963267948966,void(n[t+8>>3]=0);if(+f(+(e+1.5707963267948966))<1e-16)return n[t>>3]=-1.5707963267948966,void(n[t+8>>3]=0);if(u=+l(+e),a=r*+h(+a)/u,r=+n[A>>3],e=(s-+h(+e)*+h(+r))/+l(+r)/u,s=a>1?1:a,e=e>1?1:e,(e=+n[A+8>>3]+ +p(+(s<-1?-1:s),+(e<-1?-1:e)))>3.141592653589793)do{e+=-6.283185307179586}while(e>3.141592653589793);if(e<-3.141592653589793)do{e+=6.283185307179586}while(e<-3.141592653589793);return void(n[t+8>>3]=e)}e=+n[A>>3]+r,n[t>>3]=e,o=t}while(0);if(+f(+(e+-1.5707963267948966))<1e-16)return n[o>>3]=1.5707963267948966,void(n[t+8>>3]=0);if(+f(+(e+1.5707963267948966))<1e-16)return n[o>>3]=-1.5707963267948966,void(n[t+8>>3]=0);if((e=+n[A+8>>3])>3.141592653589793)do{e+=-6.283185307179586}while(e>3.141592653589793);if(e<-3.141592653589793)do{e+=6.283185307179586}while(e<-3.141592653589793);n[t+8>>3]=e}(15568+(e<<4)|0,+EA(+n[16368+(24*e|0)>>3]-u),a,o)}function bA(A,e,r){e|=0,r|=0;var t,n;t=I,I=I+16|0,K((A|=0)+4|0,n=t),BA(n,0|i[A>>2],e,0,r),I=t}function vA(A,e,r,t,o){A|=0,e|=0,r|=0,t|=0,o|=0;var a,f,s,u,l,h,c,d,g,w,p,B,b,v,m,k,M,y,E,x,D,_,F=0,C=0,P=0,U=0,G=0,S=0;if(_=I,I=I+272|0,U=_+240|0,E=_,x=_+224|0,D=_+208|0,p=_+176|0,B=_+160|0,b=_+192|0,v=_+144|0,m=_+128|0,k=_+112|0,M=_+96|0,y=_+80|0,i[(F=_+256|0)>>2]=e,i[U>>2]=i[A>>2],i[U+4>>2]=i[A+4>>2],i[U+8>>2]=i[A+8>>2],i[U+12>>2]=i[A+12>>2],mA(U,F,E),i[o>>2]=0,(0|(U=t+r+(5==(0|t)&1)|0))<=(0|r))I=_;else{f=x+4|0,s=p+4|0,u=r+5|0,l=16848+((a=0|i[F>>2])<<2)|0,h=16928+(a<<2)|0,c=m+8|0,d=k+8|0,g=M+8|0,w=D+4|0,P=r;A:for(;;){C=E+(((0|P)%5|0)<<4)|0,i[D>>2]=i[C>>2],i[D+4>>2]=i[C+4>>2],i[D+8>>2]=i[C+8>>2],i[D+12>>2]=i[C+12>>2];do{}while(2==(0|kA(D,a,0,1)));if((0|P)>(0|r)&0!=(0|RA(e))){if(i[p>>2]=i[D>>2],i[p+4>>2]=i[D+4>>2],i[p+8>>2]=i[D+8>>2],i[p+12>>2]=i[D+12>>2],K(f,B),t=0|i[p>>2],F=0|i[17008+(80*t|0)+(i[x>>2]<<2)>>2],i[p>>2]=i[18608+(80*t|0)+(20*F|0)>>2],(0|(C=0|i[18608+(80*t|0)+(20*F|0)+16>>2]))>0){A=0;do{oA(s),A=A+1|0}while((0|A)<(0|C))}switch(C=18608+(80*t|0)+(20*F|0)+4|0,i[b>>2]=i[C>>2],i[b+4>>2]=i[C+4>>2],i[b+8>>2]=i[C+8>>2],$(b,3*(0|i[l>>2])|0),X(s,b,s),J(s),K(s,v),G=+(0|i[h>>2]),n[m>>3]=3*G,n[c>>3]=0,S=-1.5*G,n[k>>3]=S,n[d>>3]=2.598076211353316*G,n[M>>3]=S,n[g>>3]=-2.598076211353316*G,0|i[17008+(80*(0|i[p>>2])|0)+(i[D>>2]<<2)>>2]){case 1:A=k,t=m;break;case 3:A=M,t=k;break;case 2:A=m,t=M;break;default:A=12;break A}oe(B,v,t,A,y),BA(y,0|i[p>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])}if((0|P)<(0|u)&&(K(w,p),BA(p,0|i[D>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])),i[x>>2]=i[D>>2],i[x+4>>2]=i[D+4>>2],i[x+8>>2]=i[D+8>>2],i[x+12>>2]=i[D+12>>2],(0|(P=P+1|0))>=(0|U)){A=3;break}}3!=(0|A)?12==(0|A)&&Q(22474,22521,581,22531):I=_}}function mA(A,e,r){A|=0,e|=0,r|=0;var t,n=0,o=0,a=0,f=0,s=0;t=I,I=I+128|0,o=t,f=20208,s=(a=n=t+64|0)+60|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));f=20272,s=(a=o)+60|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));n=(s=0==(0|RA(0|i[e>>2])))?n:o,uA(o=A+4|0),lA(o),0|RA(0|i[e>>2])&&(iA(o),i[e>>2]=1+(0|i[e>>2])),i[r>>2]=i[A>>2],X(o,n,e=r+4|0),J(e),i[r+16>>2]=i[A>>2],X(o,n+12|0,e=r+20|0),J(e),i[r+32>>2]=i[A>>2],X(o,n+24|0,e=r+36|0),J(e),i[r+48>>2]=i[A>>2],X(o,n+36|0,e=r+52|0),J(e),i[r+64>>2]=i[A>>2],X(o,n+48|0,r=r+68|0),J(r),I=t}function kA(A,e,r,t){r|=0,t|=0;var n,o,a,f,s,u,l=0,h=0,c=0,d=0,g=0;if(u=I,I=I+32|0,s=u+12|0,o=u,g=(A|=0)+4|0,d=0|i[16928+((e|=0)<<2)>>2],d=(f=0!=(0|t))?3*d|0:d,l=0|i[g>>2],n=0|i[(a=A+8|0)>>2],f){if((0|(l=n+l+(t=0|i[(h=A+12|0)>>2])|0))==(0|d))return I=u,0|(g=1);c=h}else l=n+l+(t=0|i[(c=A+12|0)>>2])|0;if((0|l)<=(0|d))return I=u,0|(g=0);do{if((0|t)>0){if(t=0|i[A>>2],(0|n)>0){h=18608+(80*t|0)+60|0,t=A;break}t=18608+(80*t|0)+40|0,r?(Z(s,d,0,0),q(g,s,o),aA(o),X(o,s,g),h=t,t=A):(h=t,t=A)}else h=18608+(80*(0|i[A>>2])|0)+20|0,t=A}while(0);if(i[t>>2]=i[h>>2],(0|i[(l=h+16|0)>>2])>0){t=0;do{oA(g),t=t+1|0}while((0|t)<(0|i[l>>2]))}return A=h+4|0,i[s>>2]=i[A>>2],i[s+4>>2]=i[A+4>>2],i[s+8>>2]=i[A+8>>2],e=0|i[16848+(e<<2)>>2],$(s,f?3*e|0:e),X(g,s,g),J(g),t=f&&((0|i[a>>2])+(0|i[g>>2])+(0|i[c>>2])|0)==(0|d)?1:2,I=u,0|(g=t)}function MA(A,e){A|=0,e|=0;var r=0;do{r=0|kA(A,e,0,1)}while(2==(0|r));return 0|r}function QA(A,e,r,t,o){A|=0,e|=0,r|=0,t|=0,o|=0;var a,f,s,u,l,h,c,d,g,w,p,B,b,v,m,k,M,y,E=0,x=0,D=0,_=0,F=0;if(y=I,I=I+240|0,v=y+208|0,m=y,k=y+192|0,M=y+176|0,g=y+160|0,w=y+144|0,p=y+128|0,B=y+112|0,b=y+96|0,i[(E=y+224|0)>>2]=e,i[v>>2]=i[A>>2],i[v+4>>2]=i[A+4>>2],i[v+8>>2]=i[A+8>>2],i[v+12>>2]=i[A+12>>2],yA(v,E,m),i[o>>2]=0,(0|(d=t+r+(6==(0|t)&1)|0))<=(0|r))I=y;else{f=r+6|0,s=16928+((a=0|i[E>>2])<<2)|0,u=w+8|0,l=p+8|0,h=B+8|0,c=k+4|0,x=0,D=r,t=-1;A:for(;;){if(A=m+((E=(0|D)%6|0)<<4)|0,i[k>>2]=i[A>>2],i[k+4>>2]=i[A+4>>2],i[k+8>>2]=i[A+8>>2],i[k+12>>2]=i[A+12>>2],A=x,x=0|kA(k,a,0,1),(0|D)>(0|r)&0!=(0|RA(e))&&(1!=(0|A)&&(0|i[k>>2])!=(0|t))){switch(K(m+(((E+5|0)%6|0)<<4)+4|0,M),K(m+(E<<4)+4|0,g),_=+(0|i[s>>2]),n[w>>3]=3*_,n[u>>3]=0,F=-1.5*_,n[p>>3]=F,n[l>>3]=2.598076211353316*_,n[B>>3]=F,n[h>>3]=-2.598076211353316*_,E=0|i[v>>2],0|i[17008+(80*E|0)+(((0|t)==(0|E)?0|i[k>>2]:t)<<2)>>2]){case 1:A=p,t=w;break;case 3:A=B,t=p;break;case 2:A=w,t=B;break;default:A=8;break A}oe(M,g,t,A,b),0|ae(M,b)||0|ae(g,b)||(BA(b,0|i[v>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2]))}if((0|D)<(0|f)&&(K(c,M),BA(M,0|i[k>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])),(0|(D=D+1|0))>=(0|d)){A=3;break}t=0|i[k>>2]}3!=(0|A)?8==(0|A)&&Q(22557,22521,746,22602):I=y}}function yA(A,e,r){A|=0,e|=0,r|=0;var t,n=0,o=0,a=0,f=0,s=0;t=I,I=I+160|0,o=t,f=20336,s=(a=n=t+80|0)+72|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));f=20416,s=(a=o)+72|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));n=(s=0==(0|RA(0|i[e>>2])))?n:o,uA(o=A+4|0),lA(o),0|RA(0|i[e>>2])&&(iA(o),i[e>>2]=1+(0|i[e>>2])),i[r>>2]=i[A>>2],X(o,n,e=r+4|0),J(e),i[r+16>>2]=i[A>>2],X(o,n+12|0,e=r+20|0),J(e),i[r+32>>2]=i[A>>2],X(o,n+24|0,e=r+36|0),J(e),i[r+48>>2]=i[A>>2],X(o,n+36|0,e=r+52|0),J(e),i[r+64>>2]=i[A>>2],X(o,n+48|0,e=r+68|0),J(e),i[r+80>>2]=i[A>>2],X(o,n+60|0,r=r+84|0),J(r),I=t}function EA(A){var e;return e=(A=+A)<0?A+6.283185307179586:A,+(A>=6.283185307179586?e+-6.283185307179586:e)}function xA(A,e){return e|=0,+f(+(+n[(A|=0)>>3]-+n[e>>3]))<17453292519943298e-27?0|(e=+f(+(+n[A+8>>3]-+n[e+8>>3]))<17453292519943298e-27):0|(e=0)}function DA(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))*6371.007180918475}function _A(A,e,r){A|=0,r|=0;var t,i,o,a,f=0,u=0,d=0,g=0,B=0,b=0;return b=+n[(e|=0)>>3],o=+n[A>>3],B=+h(.5*(b-o)),d=+n[e+8>>3],i=+n[A+8>>3],g=+h(.5*(d-i)),t=+l(+o),a=+l(+b),g=2*+p(+ +s(+(g=B*B+g*(a*t*g))),+ +s(+(1-g))),B=+n[r>>3],b=+h(.5*(B-b)),f=+n[r+8>>3],d=+h(.5*(f-d)),u=+l(+B),d=2*+p(+ +s(+(d=b*b+d*(a*u*d))),+ +s(+(1-d))),B=+h(.5*(o-B)),f=+h(.5*(i-f)),f=2*+p(+ +s(+(f=B*B+f*(t*u*f))),+ +s(+(1-f))),4*+w(+ +s(+ +c(.5*(u=.5*(g+d+f)))*+c(.5*(u-g))*+c(.5*(u-d))*+c(.5*(u-f))))}function IA(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),45),M(),127&e|0}function FA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0;if(!(!0&134217728==(-16777216&(e|=0)|0)))return 0|(e=0);if(o=0|Qe(0|(A|=0),0|e,45),M(),(o&=127)>>>0>121)return 0|(e=0);r=0|Qe(0|A,0|e,52),M(),r&=15;do{if(0|r){for(i=1,t=0;;){if(n=0|Qe(0|A,0|e,3*(15-i|0)|0),M(),0!=(0|(n&=7))&(1^t)){if(1==(0|n)&0!=(0|S(o))){a=0,t=13;break}t=1}if(7==(0|n)){a=0,t=13;break}if(!(i>>>0>>0)){t=9;break}i=i+1|0}if(9==(0|t)){if(15!=(0|r))break;return 0|(a=1)}if(13==(0|t))return 0|a}}while(0);for(;;){if(a=0|Qe(0|A,0|e,3*(14-r|0)|0),M(),!(7==(7&a|0)&!0)){a=0,t=13;break}if(!(r>>>0<14)){a=1,t=13;break}r=r+1|0}return 13==(0|t)?0|a:0}function CA(A,e,r){r|=0;var t=0,i=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|(t&=15))>=(0|r)){if((0|t)!=(0|r))if(r>>>0<=15){if(A|=i=0|ye(0|r,0,52),e=0|M()|-15728641&e,(0|t)>(0|r))do{i=0|ye(7,0,3*(14-r|0)|0),r=r+1|0,A|=i,e=0|M()|e}while((0|r)<(0|t))}else e=0,A=0}else e=0,A=0;return k(0|e),0|A}function PA(A,e,r,t){r|=0,t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(f&=15))<=(0|r)){if((0|f)==(0|r))return i[(r=t)>>2]=A,void(i[r+4>>2]=e);if(n=(0|(u=0|ee(7,r-f|0)))/7|0,s=0|Qe(0|A,0|e,45),M(),0|S(127&s)){A:do{if(f)for(a=1;;){if(o=0|Qe(0|A,0|e,3*(15-a|0)|0),M(),0|(o&=7))break A;if(!(a>>>0>>0)){o=0;break}a=a+1|0}else o=0}while(0);a=0==(0|o)}else a=0;if(l=0|ye(f+1|0,0,52),o=0|M()|-15728641&e,PA(e=(l|A)&~(e=0|ye(7,0,0|(s=3*(14-f|0)|0))),f=o&~(0|M()),r,t),o=t+(n<<3)|0,!a)return PA((l=0|ye(1,0,0|s))|e,0|M()|f,r,o),l=o+(n<<3)|0,PA((u=0|ye(2,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(3,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(4,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(5,0,0|s))|e,0|M()|f,r,l),void PA((u=0|ye(6,0,0|s))|e,0|M()|f,r,l+(n<<3)|0);a=o+(n<<3)|0,(0|u)>6&&(_e(0|o,0,(l=(a>>>0>(u=o+8|0)>>>0?a:u)+-1+(0-o)|0)+8&-8|0),o=u+(l>>>3<<3)|0),PA((l=0|ye(2,0,0|s))|e,0|M()|f,r,o),l=o+(n<<3)|0,PA((u=0|ye(3,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(4,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(5,0,0|s))|e,0|M()|f,r,l),PA((u=0|ye(6,0,0|s))|e,0|M()|f,r,l+(n<<3)|0)}}function UA(A,e){var r=0,t=0,i=0;if(i=0|Qe(0|(A|=0),0|(e|=0),45),M(),!(0|S(127&i)))return 0|(i=0);i=0|Qe(0|A,0|e,52),M(),i&=15;A:do{if(i)for(t=1;;){if(r=0|Qe(0|A,0|e,3*(15-t|0)|0),M(),0|(r&=7))break A;if(!(t>>>0>>0)){r=0;break}t=t+1|0}else r=0}while(0);return 0|(i=0==(0|r)&1)}function GA(A,e){var r=0,t=0,i=0;if(i=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(i&=15))return 0|(i=0);for(t=1;;){if(r=0|Qe(0|A,0|e,3*(15-t|0)|0),M(),0|(r&=7)){t=5;break}if(!(t>>>0>>0)){r=0,t=5;break}t=t+1|0}return 5==(0|t)?0|r:0}function SA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0,f=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(f&=15))return f=A,k(0|(a=e)),0|f;for(a=1,r=0;;){t=0|ye(7,0,0|(n=3*(15-a|0)|0)),i=0|M(),o=0|Qe(0|A,0|e,0|n),M(),A=(n=0|ye(0|fA(7&o),0,0|n))|A&~t,e=(o=0|M())|e&~i;A:do{if(!r)if(0==(n&t|0)&0==(o&i|0))r=0;else if(t=0|Qe(0|A,0|e,52),M(),t&=15){r=1;e:for(;;){switch(o=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),7&o){case 1:break e;case 0:break;default:r=1;break A}if(!(r>>>0>>0)){r=1;break A}r=r+1|0}for(r=1;;){if(i=0|Qe(0|A,0|e,0|(o=3*(15-r|0)|0)),M(),n=0|ye(7,0,0|o),e&=~(0|M()),A=A&~n|(o=0|ye(0|fA(7&i),0,0|o)),e=0|e|M(),!(r>>>0>>0)){r=1;break}r=r+1|0}}else r=1}while(0);if(!(a>>>0>>0))break;a=a+1|0}return k(0|e),0|A}function TA(A,e){var r=0,t=0,i=0,n=0,o=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(t&=15))return t=A,k(0|(r=e)),0|t;for(r=1;o=0|Qe(0|A,0|e,0|(n=3*(15-r|0)|0)),M(),i=0|ye(7,0,0|n),e&=~(0|M()),A=(n=0|ye(0|fA(7&o),0,0|n))|A&~i,e=0|M()|e,r>>>0>>0;)r=r+1|0;return k(0|e),0|A}function VA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0,f=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(f&=15))return f=A,k(0|(a=e)),0|f;for(a=1,r=0;;){t=0|ye(7,0,0|(n=3*(15-a|0)|0)),i=0|M(),o=0|Qe(0|A,0|e,0|n),M(),A=(n=0|ye(0|sA(7&o),0,0|n))|A&~t,e=(o=0|M())|e&~i;A:do{if(!r)if(0==(n&t|0)&0==(o&i|0))r=0;else if(t=0|Qe(0|A,0|e,52),M(),t&=15){r=1;e:for(;;){switch(o=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),7&o){case 1:break e;case 0:break;default:r=1;break A}if(!(r>>>0>>0)){r=1;break A}r=r+1|0}for(r=1;;){if(n=0|ye(7,0,0|(i=3*(15-r|0)|0)),o=e&~(0|M()),e=0|Qe(0|A,0|e,0|i),M(),A=A&~n|(e=0|ye(0|sA(7&e),0,0|i)),e=0|o|M(),!(r>>>0>>0)){r=1;break}r=r+1|0}}else r=1}while(0);if(!(a>>>0>>0))break;a=a+1|0}return k(0|e),0|A}function HA(A,e){var r=0,t=0,i=0,n=0,o=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(t&=15))return t=A,k(0|(r=e)),0|t;for(r=1;n=0|ye(7,0,0|(o=3*(15-r|0)|0)),i=e&~(0|M()),e=0|Qe(0|A,0|e,0|o),M(),A=(e=0|ye(0|sA(7&e),0,0|o))|A&~n,e=0|M()|i,r>>>0>>0;)r=r+1|0;return k(0|e),0|A}function RA(A){return 0|(0|(A|=0))%2}function LA(A,e){A|=0;var r,t;return t=I,I=I+16|0,r=t,(e|=0)>>>0<=15&&2146435072!=(2146435072&i[A+4>>2]|0)&&2146435072!=(2146435072&i[A+8+4>>2]|0)?(!function(A,e,r){var t,i;t=I,I=I+16|0,pA(A|=0,e|=0,r|=0,i=t),W(i,r+4|0),I=t}(A,e,r),e=0|function(A,e){A|=0;var r,t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0;if(r=I,I=I+64|0,s=r+40|0,n=r+24|0,o=r+12|0,a=r,ye(0|(e|=0),0,52),t=134225919|M(),!e)return(0|i[A+4>>2])>2||(0|i[A+8>>2])>2||(0|i[A+12>>2])>2?(s=0,k(0|(f=0)),I=r,0|s):(ye(0|V(A),0,45),f=0|M()|t,s=-1,k(0|f),I=r,0|s);if(i[s>>2]=i[A>>2],i[s+4>>2]=i[A+4>>2],i[s+8>>2]=i[A+8>>2],i[s+12>>2]=i[A+12>>2],f=s+4|0,(0|e)>0)for(A=-1;i[n>>2]=i[f>>2],i[n+4>>2]=i[f+4>>2],i[n+8>>2]=i[f+8>>2],1&e?(eA(f),i[o>>2]=i[f>>2],i[o+4>>2]=i[f+4>>2],i[o+8>>2]=i[f+8>>2],tA(o)):(rA(f),i[o>>2]=i[f>>2],i[o+4>>2]=i[f+4>>2],i[o+8>>2]=i[f+8>>2],iA(o)),q(n,o,a),J(a),u=0|ye(7,0,0|(l=3*(15-e|0)|0)),t&=~(0|M()),A=(l=0|ye(0|AA(a),0,0|l))|A&~u,t=0|M()|t,(0|e)>1;)e=e+-1|0;else A=-1;A:do{if((0|i[f>>2])<=2&&(0|i[s+8>>2])<=2&&(0|i[s+12>>2])<=2){if(e=0|ye(0|(n=0|V(s)),0,45),e|=A,A=0|M()|-1040385&t,a=0|H(s),!(0|S(n))){if((0|a)<=0)break;for(o=0;;){if(n=0|Qe(0|e,0|A,52),M(),n&=15)for(t=1;s=0|Qe(0|e,0|A,0|(l=3*(15-t|0)|0)),M(),u=0|ye(7,0,0|l),A&=~(0|M()),e=e&~u|(l=0|ye(0|fA(7&s),0,0|l)),A=0|A|M(),t>>>0>>0;)t=t+1|0;if((0|(o=o+1|0))==(0|a))break A}}o=0|Qe(0|e,0|A,52),M(),o&=15;e:do{if(o){t=1;r:for(;;){switch(l=0|Qe(0|e,0|A,3*(15-t|0)|0),M(),7&l){case 1:break r;case 0:break;default:break e}if(!(t>>>0>>0))break e;t=t+1|0}if(0|R(n,0|i[s>>2]))for(t=1;u=0|ye(7,0,0|(s=3*(15-t|0)|0)),l=A&~(0|M()),A=0|Qe(0|e,0|A,0|s),M(),e=e&~u|(A=0|ye(0|sA(7&A),0,0|s)),A=0|l|M(),t>>>0>>0;)t=t+1|0;else for(t=1;s=0|Qe(0|e,0|A,0|(l=3*(15-t|0)|0)),M(),u=0|ye(7,0,0|l),A&=~(0|M()),e=e&~u|(l=0|ye(0|fA(7&s),0,0|l)),A=0|A|M(),t>>>0>>0;)t=t+1|0}}while(0);if((0|a)>0){t=0;do{e=0|SA(e,A),A=0|M(),t=t+1|0}while((0|t)!=(0|a))}}else e=0,A=0}while(0);return l=e,k(0|(u=A)),I=r,0|l}(r,e),A=0|M()):(A=0,e=0),k(0|A),I=t,0|e}function zA(A,e,r){var t,n=0,o=0,a=0;if(t=(r|=0)+4|0,o=0|Qe(0|(A|=0),0|(e|=0),52),M(),o&=15,a=0|Qe(0|A,0|e,45),M(),n=0==(0|o),0|S(127&a)){if(n)return 0|(a=1);n=1}else{if(n)return 0|(a=0);n=0==(0|i[t>>2])&&0==(0|i[r+8>>2])?0!=(0|i[r+12>>2])&1:1}for(r=1;1&r?tA(t):iA(t),a=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),nA(t,7&a),r>>>0>>0;)r=r+1|0;return 0|n}function YA(A,e,r){r|=0;var t,n,o=0,a=0,f=0,s=0,u=0,l=0;n=I,I=I+16|0,t=n,l=0|Qe(0|(A|=0),0|(e|=0),45),M(),l&=127;A:do{if(0!=(0|S(l))&&(f=0|Qe(0|A,0|e,52),M(),0!=(0|(f&=15)))){o=1;e:for(;;){switch(u=0|Qe(0|A,0|e,3*(15-o|0)|0),M(),7&u){case 5:break e;case 0:break;default:o=e;break A}if(!(o>>>0>>0)){o=e;break A}o=o+1|0}for(a=1,o=e;s=0|ye(7,0,0|(e=3*(15-a|0)|0)),u=o&~(0|M()),o=0|Qe(0|A,0|o,0|e),M(),A=A&~s|(o=0|ye(0|sA(7&o),0,0|e)),o=0|u|M(),a>>>0>>0;)a=a+1|0}else o=e}while(0);if(u=7728+(28*l|0)|0,i[r>>2]=i[u>>2],i[r+4>>2]=i[u+4>>2],i[r+8>>2]=i[u+8>>2],i[r+12>>2]=i[u+12>>2],0|zA(A,o,r)){if(s=r+4|0,i[t>>2]=i[s>>2],i[t+4>>2]=i[s+4>>2],i[t+8>>2]=i[s+8>>2],f=0|Qe(0|A,0|o,52),M(),u=15&f,1&f?(iA(s),f=u+1|0):f=u,0|S(l)){A:do{if(u)for(e=1;;){if(a=0|Qe(0|A,0|o,3*(15-e|0)|0),M(),0|(a&=7)){o=a;break A}if(!(e>>>0>>0)){o=0;break}e=e+1|0}else o=0}while(0);o=4==(0|o)&1}else o=0;if(0|kA(r,f,o,0)){if(0|S(l))do{}while(0!=(0|kA(r,f,0,0)));(0|f)!=(0|u)&&rA(s)}else(0|f)!=(0|u)&&(i[s>>2]=i[t>>2],i[s+4>>2]=i[t+4>>2],i[s+8>>2]=i[t+8>>2]);I=n}else I=n}function OA(A,e,r){r|=0;var t,i;t=I,I=I+16|0,YA(A|=0,e|=0,i=t),e=0|Qe(0|A,0|e,52),M(),bA(i,15&e,r),I=t}function jA(A,e,r){r|=0;var t,i,n=0,o=0;i=I,I=I+16|0,YA(A|=0,e|=0,t=i),n=0|Qe(0|A,0|e,45),M(),n=0==(0|S(127&n)),o=0|Qe(0|A,0|e,52),M(),o&=15;A:do{if(!n){if(0|o)for(n=1;;){if(!(0==((0|ye(7,0,3*(15-n|0)|0))&A|0)&0==((0|M())&e|0)))break A;if(!(n>>>0>>0))break;n=n+1|0}return vA(t,o,0,5,r),void(I=i)}}while(0);QA(t,o,0,6,r),I=i}function NA(A,e){e|=0;var r,t=0,n=0,o=0,a=0,f=0,s=0;if(ye(0|(A|=0),0,52),r=134225919|M(),(0|A)<1){n=0,t=0;do{0|S(n)&&(ye(0|n,0,45),f=0|r|M(),i[(A=e+(t<<3)|0)>>2]=-1,i[A+4>>2]=f,t=t+1|0),n=n+1|0}while(122!=(0|n))}else{f=0,t=0;do{if(0|S(f)){for(ye(0|f,0,45),n=1,o=-1,a=0|r|M();o&=~(s=0|ye(7,0,3*(15-n|0)|0)),a&=~(0|M()),(0|n)!=(0|A);)n=n+1|0;i[(s=e+(t<<3)|0)>>2]=o,i[s+4>>2]=a,t=t+1|0}f=f+1|0}while(122!=(0|f))}}function ZA(A,e,r,t){var n,o=0,a=0,f=0,s=0,u=0;if(n=I,I=I+64|0,f=n,(0|(A|=0))==(0|(r|=0))&(0|(e|=0))==(0|(t|=0))|!1|134217728!=(2013265920&e|0)|!1|134217728!=(2013265920&t|0))return I=n,0|(f=0);if(o=0|Qe(0|A,0|e,52),M(),o&=15,a=0|Qe(0|r,0|t,52),M(),(0|o)!=(15&a|0))return I=n,0|(f=0);if(a=o+-1|0,o>>>0>1&&(u=0|CA(A,e,a),s=0|M(),(0|u)==(0|(a=0|CA(r,t,a)))&(0|s)==(0|M()))){if(o=0|Qe(0|A,0|e,0|(a=3*(15^o)|0)),M(),o&=7,a=0|Qe(0|r,0|t,0|a),M(),0==(0|o)|0==(0|(a&=7)))return I=n,0|(u=1);if((0|i[21136+(o<<2)>>2])==(0|a))return I=n,0|(u=1);if((0|i[21168+(o<<2)>>2])==(0|a))return I=n,0|(u=1)}a=(o=f)+56|0;do{i[o>>2]=0,o=o+4|0}while((0|o)<(0|a));return F(A,e,1,f),o=(0|i[(u=f)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+8|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+16|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+24|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+32|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+40|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)?1:1&((0|i[(o=f+48|0)>>2])==(0|r)?(0|i[o+4>>2])==(0|t):0),I=n,0|(u=o)}function WA(A,e,r){r|=0;var t,n,o,a,f=0;if(o=I,I=I+16|0,n=o,f=0|Qe(0|(A|=0),0|(e|=0),56),M(),-1==(0|(e=0|function(A,e,r){r|=0;var t=0,n=0;if(t=0|UA(A=A|0,e=e|0),(r+-1|0)>>>0>5)return 0|(r=-1);if(1==(0|r)&(n=0!=(0|t)))return 0|(r=-1);return t=0|function(A,e){var r=0,t=0,n=0,o=0,a=0,f=0,s=0,u=0;if(u=I,I=I+32|0,o=u,YA(A=A|0,e=e|0,n=u+16|0),a=0|IA(A,e),s=0|GA(A,e),function(A,e){A=7728+(28*(A|=0)|0)|0,i[(e|=0)>>2]=i[A>>2],i[e+4>>2]=i[A+4>>2],i[e+8>>2]=i[A+8>>2],i[e+12>>2]=i[A+12>>2]}(a,o),e=0|function(A,e){A|=0;var r=0,t=0;if((e|=0)>>>0>20)return-1;do{if((0|i[11152+(216*e|0)>>2])!=(0|A))if((0|i[11152+(216*e|0)+8>>2])!=(0|A))if((0|i[11152+(216*e|0)+16>>2])!=(0|A))if((0|i[11152+(216*e|0)+24>>2])!=(0|A))if((0|i[11152+(216*e|0)+32>>2])!=(0|A))if((0|i[11152+(216*e|0)+40>>2])!=(0|A))if((0|i[11152+(216*e|0)+48>>2])!=(0|A))if((0|i[11152+(216*e|0)+56>>2])!=(0|A))if((0|i[11152+(216*e|0)+64>>2])!=(0|A))if((0|i[11152+(216*e|0)+72>>2])!=(0|A))if((0|i[11152+(216*e|0)+80>>2])!=(0|A))if((0|i[11152+(216*e|0)+88>>2])!=(0|A))if((0|i[11152+(216*e|0)+96>>2])!=(0|A))if((0|i[11152+(216*e|0)+104>>2])!=(0|A))if((0|i[11152+(216*e|0)+112>>2])!=(0|A))if((0|i[11152+(216*e|0)+120>>2])!=(0|A))if((0|i[11152+(216*e|0)+128>>2])!=(0|A)){if((0|i[11152+(216*e|0)+136>>2])!=(0|A)){if((0|i[11152+(216*e|0)+144>>2])==(0|A)){A=0,r=2,t=0;break}if((0|i[11152+(216*e|0)+152>>2])==(0|A)){A=0,r=2,t=1;break}if((0|i[11152+(216*e|0)+160>>2])==(0|A)){A=0,r=2,t=2;break}if((0|i[11152+(216*e|0)+168>>2])==(0|A)){A=1,r=2,t=0;break}if((0|i[11152+(216*e|0)+176>>2])==(0|A)){A=1,r=2,t=1;break}if((0|i[11152+(216*e|0)+184>>2])==(0|A)){A=1,r=2,t=2;break}if((0|i[11152+(216*e|0)+192>>2])==(0|A)){A=2,r=2,t=0;break}if((0|i[11152+(216*e|0)+200>>2])==(0|A)){A=2,r=2,t=1;break}if((0|i[11152+(216*e|0)+208>>2])==(0|A)){A=2,r=2,t=2;break}return-1}A=2,r=1,t=2}else A=2,r=1,t=1;else A=2,r=1,t=0;else A=1,r=1,t=2;else A=1,r=1,t=1;else A=1,r=1,t=0;else A=0,r=1,t=2;else A=0,r=1,t=1;else A=0,r=1,t=0;else A=2,r=0,t=2;else A=2,r=0,t=1;else A=2,r=0,t=0;else A=1,r=0,t=2;else A=1,r=0,t=1;else A=1,r=0,t=0;else A=0,r=0,t=2;else A=0,r=0,t=1;else A=0,r=0,t=0}while(0);return 0|i[11152+(216*e|0)+(72*r|0)+(24*A|0)+(t<<3)+4>>2]}(a,0|i[n>>2]),!(0|S(a)))return I=u,0|(s=e);switch(0|a){case 4:A=0,r=14;break;case 14:A=1,r=14;break;case 24:A=2,r=14;break;case 38:A=3,r=14;break;case 49:A=4,r=14;break;case 58:A=5,r=14;break;case 63:A=6,r=14;break;case 72:A=7,r=14;break;case 83:A=8,r=14;break;case 97:A=9,r=14;break;case 107:A=10,r=14;break;case 117:A=11,r=14;break;default:f=0,t=0}14==(0|r)&&(f=0|i[22096+(24*A|0)+8>>2],t=0|i[22096+(24*A|0)+16>>2]);(0|(A=0|i[n>>2]))!=(0|i[o>>2])&&(a=0|T(a))|(0|(A=0|i[n>>2]))==(0|t)&&(e=(e+1|0)%6|0);if(3==(0|s)&(0|A)==(0|t))return I=u,0|(s=(e+5|0)%6|0);if(!(5==(0|s)&(0|A)==(0|f)))return I=u,0|(s=e);return I=u,0|(s=(e+1|0)%6|0)}(A,e),n?0|(r=(5-t+(0|i[22384+(r<<2)>>2])|0)%5|0):0|(r=(6-t+(0|i[22416+(r<<2)>>2])|0)%6|0)}(t=(a=!0&268435456==(2013265920&e|0))?A:0,A=a?-2130706433&e|134217728:0,7&f))))return i[r>>2]=0,void(I=o);YA(t,A,n),f=0|Qe(0|t,0|A,52),M(),f&=15,0|UA(t,A)?vA(n,f,e,2,r):QA(n,f,e,2,r),I=o}function JA(A){A|=0;var e,r,t=0;return(e=0|be(1,12))||Q(22691,22646,49,22704),0|(t=0|i[(r=A+4|0)>>2])?(i[(t=t+8|0)>>2]=e,i[r>>2]=e,0|e):(0|i[A>>2]&&Q(22721,22646,61,22744),i[(t=A)>>2]=e,i[r>>2]=e,0|e)}function KA(A,e){A|=0,e|=0;var r,t;return(t=0|pe(24))||Q(22758,22646,78,22772),i[t>>2]=i[e>>2],i[t+4>>2]=i[e+4>>2],i[t+8>>2]=i[e+8>>2],i[t+12>>2]=i[e+12>>2],i[t+16>>2]=0,0|(r=0|i[(e=A+4|0)>>2])?(i[r+16>>2]=t,i[e>>2]=t,0|t):(0|i[A>>2]&&Q(22787,22646,82,22772),i[A>>2]=t,i[e>>2]=t,0|t)}function XA(A){var e,r,t=0,o=0,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,y=0,E=0,x=0,D=0,_=0,I=0,F=0,C=0,P=0,U=0,G=0,S=0;if(0|i[(s=(A|=0)+8|0)>>2])return 0|(S=1);if(!(a=0|i[A>>2]))return 0|(S=0);t=a,o=0;do{o=o+1|0,t=0|i[t+8>>2]}while(0!=(0|t));if(o>>>0<2)return 0|(S=0);(r=0|pe(o<<2))||Q(22807,22646,317,22826),(e=0|pe(o<<5))||Q(22848,22646,321,22826),i[A>>2]=0,i[(D=A+4|0)>>2]=0,i[s>>2]=0,o=0,U=0,x=0,w=0;A:for(;;){if(g=0|i[a>>2]){u=0,l=g;do{if(c=+n[l+8>>3],t=l,l=0|i[l+16>>2],h=+n[(s=(d=0==(0|l))?g:l)+8>>3],+f(+(c-h))>3.141592653589793){S=14;break}u+=(h-c)*(+n[t>>3]+ +n[s>>3])}while(!d);if(14==(0|S)){S=0,u=0,t=g;do{E=+n[t+8>>3],C=0|i[(P=t+16|0)>>2],y=+n[(C=0==(0|C)?g:C)+8>>3],u+=(+n[t>>3]+ +n[C>>3])*((y<0?y+6.283185307179586:y)-(E<0?E+6.283185307179586:E)),t=0|i[(0==(0|t)?a:P)>>2]}while(0!=(0|t))}u>0?(i[r+(U<<2)>>2]=a,U=U+1|0,s=x,t=w):S=19}else S=19;if(19==(0|S)){S=0;do{if(!o){if(w){s=D,l=w+8|0,t=a,o=A;break}if(0|i[A>>2]){S=27;break A}s=D,l=A,t=a,o=A;break}if(0|i[(t=o+8|0)>>2]){S=21;break A}if(!(o=0|be(1,12))){S=23;break A}i[t>>2]=o,s=o+4|0,l=o,t=w}while(0);if(i[l>>2]=a,i[s>>2]=a,l=e+(x<<5)|0,d=0|i[a>>2]){for(n[(g=e+(x<<5)+8|0)>>3]=17976931348623157e292,n[(w=e+(x<<5)+24|0)>>3]=17976931348623157e292,n[l>>3]=-17976931348623157e292,n[(p=e+(x<<5)+16|0)>>3]=-17976931348623157e292,k=17976931348623157e292,M=-17976931348623157e292,s=0,B=d,c=17976931348623157e292,v=17976931348623157e292,m=-17976931348623157e292,h=-17976931348623157e292;u=+n[B>>3],E=+n[B+8>>3],B=0|i[B+16>>2],y=+n[((b=0==(0|B))?d:B)+8>>3],u>3]=u,c=u),E>3]=E,v=E),u>m?n[l>>3]=u:u=m,E>h&&(n[p>>3]=E,h=E),k=E>0&EM?E:M,s|=+f(+(E-y))>3.141592653589793,!b;)m=u;s&&(n[p>>3]=M,n[w>>3]=k)}else i[l>>2]=0,i[l+4>>2]=0,i[l+8>>2]=0,i[l+12>>2]=0,i[l+16>>2]=0,i[l+20>>2]=0,i[l+24>>2]=0,i[l+28>>2]=0;s=x+1|0}if(a=0|i[(P=a+8|0)>>2],i[P>>2]=0,!a){S=45;break}x=s,w=t}if(21==(0|S))Q(22624,22646,35,22658);else if(23==(0|S))Q(22678,22646,37,22658);else if(27==(0|S))Q(22721,22646,61,22744);else if(45==(0|S)){A:do{if((0|U)>0){for(P=0==(0|s),F=s<<2,C=0==(0|A),I=0,t=0;;){if(_=0|i[r+(I<<2)>>2],P)S=73;else{if(!(x=0|pe(F))){S=50;break}if(!(D=0|pe(F))){S=52;break}e:do{if(C)o=0;else{for(s=0,o=0,l=A;a=e+(s<<5)|0,0|qA(0|i[l>>2],a,0|i[_>>2])?(i[x+(o<<2)>>2]=l,i[D+(o<<2)>>2]=a,b=o+1|0):b=o,l=0|i[l+8>>2];)s=s+1|0,o=b;if((0|b)>0)if(a=0|i[x>>2],1==(0|b))o=a;else for(p=0,B=-1,o=a,w=a;;){for(d=0|i[w>>2],a=0,l=0;g=(0|(s=0|i[i[x+(l<<2)>>2]>>2]))==(0|d)?a:a+(1&(0|qA(s,0|i[D+(l<<2)>>2],0|i[d>>2])))|0,(0|(l=l+1|0))!=(0|b);)a=g;if(o=(s=(0|g)>(0|B))?w:o,(0|(a=p+1|0))==(0|b))break e;p=a,B=s?g:B,w=0|i[x+(a<<2)>>2]}else o=0}}while(0);if(Be(x),Be(D),o){if(a=0|i[(s=o+4|0)>>2])o=a+8|0;else if(0|i[o>>2]){S=70;break}i[o>>2]=_,i[s>>2]=_}else S=73}if(73==(0|S)){if(S=0,0|(t=0|i[_>>2]))do{D=t,t=0|i[t+16>>2],Be(D)}while(0!=(0|t));Be(_),t=2}if((0|(I=I+1|0))>=(0|U)){G=t;break A}}50==(0|S)?Q(22863,22646,249,22882):52==(0|S)?Q(22901,22646,252,22882):70==(0|S)&&Q(22721,22646,61,22744)}else G=0}while(0);return Be(r),Be(e),0|(S=G)}return 0}function qA(A,e,r){A|=0;var t,o=0,a=0,f=0,s=0,u=0,l=0,h=0;if(!(0|O(e|=0,r|=0)))return 0|(A=0);if(e=0|Y(e),t=+n[r>>3],o=e&(o=+n[r+8>>3])<0?o+6.283185307179586:o,!(A=0|i[A>>2]))return 0|(A=0);if(e){e=0,r=A;A:for(;;){for(;s=+n[r>>3],l=+n[r+8>>3],h=0|i[(r=r+16|0)>>2],f=+n[(h=0==(0|h)?A:h)>>3],a=+n[h+8>>3],s>f?(u=s,s=l):(u=f,f=s,s=a,a=l),tu;)if(!(r=0|i[r>>2])){r=22;break A}if(o=(s=s<0?s+6.283185307179586:s)==o|(l=a<0?a+6.283185307179586:a)==o?o+-2220446049250313e-31:o,((l+=(t-f)/(u-f)*(s-l))<0?l+6.283185307179586:l)>o&&(e^=1),!(r=0|i[r>>2])){r=22;break}}if(22==(0|r))return 0|e}else{e=0,r=A;A:for(;;){for(;s=+n[r>>3],l=+n[r+8>>3],h=0|i[(r=r+16|0)>>2],f=+n[(h=0==(0|h)?A:h)>>3],a=+n[h+8>>3],s>f?(u=s,s=l):(u=f,f=s,s=a,a=l),tu;)if(!(r=0|i[r>>2])){r=22;break A}if(a+(t-f)/(u-f)*(s-a)>(o=s==o|a==o?o+-2220446049250313e-31:o)&&(e^=1),!(r=0|i[r>>2])){r=22;break}}if(22==(0|r))return 0|e}return 0}function $A(A,e,r,n,o){r|=0,n|=0,o|=0;var a,f,s,u,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0;if(u=I,I=I+32|0,v=u+16|0,s=u,l=0|Qe(0|(A|=0),0|(e|=0),52),M(),l&=15,p=0|Qe(0|r,0|n,52),M(),(0|l)!=(15&p|0))return I=u,0|(v=1);if(g=0|Qe(0|A,0|e,45),M(),g&=127,w=0|Qe(0|r,0|n,45),M(),p=(0|g)!=(0|(w&=127))){if(7==(0|(c=0|z(g,w))))return I=u,0|(v=2);7==(0|(d=0|z(w,g)))?Q(22925,22949,151,22959):(B=c,h=d)}else B=0,h=0;a=0|S(g),f=0|S(w),i[v>>2]=0,i[v+4>>2]=0,i[v+8>>2]=0,i[v+12>>2]=0;do{if(B){if(c=(0|(w=0|i[4304+(28*g|0)+(B<<2)>>2]))>0,f)if(c){g=0,d=r,c=n;do{d=0|VA(d,c),c=0|M(),1==(0|(h=0|sA(h)))&&(h=0|sA(1)),g=g+1|0}while((0|g)!=(0|w));w=h,g=d,d=c}else w=h,g=r,d=n;else if(c){g=0,d=r,c=n;do{d=0|HA(d,c),c=0|M(),h=0|sA(h),g=g+1|0}while((0|g)!=(0|w));w=h,g=d,d=c}else w=h,g=r,d=n;if(zA(g,d,v),p||Q(22972,22949,181,22959),(c=0!=(0|a))&(h=0!=(0|f))&&Q(22999,22949,182,22959),c){if(h=0|GA(A,e),0|t[22032+(7*h|0)+B>>0]){l=3;break}g=d=0|i[21200+(28*h|0)+(B<<2)>>2],b=26}else if(h){if(h=0|GA(g,d),0|t[22032+(7*h|0)+w>>0]){l=4;break}g=0,d=0|i[21200+(28*w|0)+(h<<2)>>2],b=26}else h=0;if(26==(0|b))if((0|d)<=-1&&Q(23030,22949,212,22959),(0|g)<=-1&&Q(23053,22949,213,22959),(0|d)>0){c=v+4|0,h=0;do{aA(c),h=h+1|0}while((0|h)!=(0|d));h=g}else h=g;if(i[s>>2]=0,i[s+4>>2]=0,i[s+8>>2]=0,nA(s,B),0|l)for(;0|RA(l)?tA(s):iA(s),(0|l)>1;)l=l+-1|0;if((0|h)>0){l=0;do{aA(s),l=l+1|0}while((0|l)!=(0|h))}X(b=v+4|0,s,b),J(b),b=50}else if(zA(r,n,v),0!=(0|a)&0!=(0|f))if((0|w)!=(0|g)&&Q(23077,22949,243,22959),h=0|GA(A,e),l=0|GA(r,n),0|t[22032+(7*h|0)+l>>0])l=5;else if((0|(h=0|i[21200+(28*h|0)+(l<<2)>>2]))>0){c=v+4|0,l=0;do{aA(c),l=l+1|0}while((0|l)!=(0|h));b=50}else b=50;else b=50}while(0);return 50==(0|b)&&(l=v+4|0,i[o>>2]=i[l>>2],i[o+4>>2]=i[l+4>>2],i[o+8>>2]=i[l+8>>2],l=0),I=u,0|(v=l)}function Ae(A,e,r,t){r|=0,t|=0;var n,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0;if(o=I,I=I+48|0,s=o+36|0,u=o+24|0,l=o+12|0,h=o,f=0|Qe(0|(A|=0),0|(e|=0),52),M(),f&=15,d=0|Qe(0|A,0|e,45),M(),n=0|S(d&=127),ye(0|f,0,52),p=134225919|M(),i[(w=t)>>2]=-1,i[w+4>>2]=p,!f)return(0|i[r>>2])>1||(0|i[r+4>>2])>1||(0|i[r+8>>2])>1||127==(0|(a=0|L(d,0|AA(r))))?(I=o,0|(p=1)):(g=0|ye(0|a,0,45),w=0|M(),w=-1040385&i[(d=t)+4>>2]|w,i[(p=t)>>2]=i[d>>2]|g,i[p+4>>2]=w,I=o,0|(p=0));for(i[s>>2]=i[r>>2],i[s+4>>2]=i[r+4>>2],i[s+8>>2]=i[r+8>>2];i[u>>2]=i[s>>2],i[u+4>>2]=i[s+4>>2],i[u+8>>2]=i[s+8>>2],0|RA(f)?(eA(s),i[l>>2]=i[s>>2],i[l+4>>2]=i[s+4>>2],i[l+8>>2]=i[s+8>>2],tA(l)):(rA(s),i[l>>2]=i[s>>2],i[l+4>>2]=i[s+4>>2],i[l+8>>2]=i[s+8>>2],iA(l)),q(u,l,h),J(h),B=0|i[(w=t)>>2],w=0|i[w+4>>2],r=0|ye(7,0,0|(b=3*(15-f|0)|0)),w&=~(0|M()),b=0|ye(0|AA(h),0,0|b),w=0|M()|w,i[(p=t)>>2]=b|B&~r,i[p+4>>2]=w,(0|f)>1;)f=f+-1|0;A:do{if((0|i[s>>2])<=1&&(0|i[s+4>>2])<=1&&(0|i[s+8>>2])<=1){h=127==(0|(u=0|L(d,f=0|AA(s))))?0:0|S(u);e:do{if(f){if(n){if(s=21408+(28*(0|GA(A,e))|0)+(f<<2)|0,(0|(s=0|i[s>>2]))>0){r=0;do{f=0|fA(f),r=r+1|0}while((0|r)!=(0|s))}if(1==(0|f)){a=3;break A}127==(0|(r=0|L(d,f)))&&Q(23104,22949,376,23134),0|S(r)?Q(23147,22949,377,23134):(g=s,c=f,a=r)}else g=0,c=f,a=u;if((0|(l=0|i[4304+(28*d|0)+(c<<2)>>2]))<=-1&&Q(23178,22949,384,23134),!h){if((0|g)<=-1&&Q(23030,22949,417,23134),0|g){f=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];do{r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,f=f+1|0}while((0|f)<(0|g))}if((0|l)<=0){f=54;break}for(f=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];;)if(r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,(0|(f=f+1|0))==(0|l)){f=54;break e}}if(7==(0|(u=0|z(a,d)))&&Q(22925,22949,393,23134),r=0|i[(f=t)>>2],f=0|i[f+4>>2],(0|l)>0){s=0;do{r=0|TA(r,f),f=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=f,s=s+1|0}while((0|s)!=(0|l))}if(r=0|GA(r,f),b=0|T(a),(0|(r=0|i[(b?21824:21616)+(28*u|0)+(r<<2)>>2]))<=-1&&Q(23030,22949,412,23134),r){f=0,s=0|i[(u=t)>>2],u=0|i[u+4>>2];do{s=0|SA(s,u),u=0|M(),i[(b=t)>>2]=s,i[b+4>>2]=u,f=f+1|0}while((0|f)<(0|r));f=54}else f=54}else if(0!=(0|n)&0!=(0|h))if(f=21408+(28*(b=0|GA(A,e))|0)+((0|GA(0|i[(f=t)>>2],0|i[f+4>>2]))<<2)|0,(0|(f=0|i[f>>2]))<=-1&&Q(23201,22949,433,23134),f){a=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];do{r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,a=a+1|0}while((0|a)<(0|f));a=u,f=54}else a=u,f=55;else a=u,f=54}while(0);if(54==(0|f)&&h&&(f=55),55==(0|f)&&1==(0|GA(0|i[(b=t)>>2],0|i[b+4>>2]))){a=4;break}p=0|i[(b=t)>>2],b=-1040385&i[b+4>>2],B=0|ye(0|a,0,45),b=0|b|M(),i[(a=t)>>2]=p|B,i[a+4>>2]=b,a=0}else a=2}while(0);return I=o,0|(b=a)}function ee(A,e){var r=0;if(!(e|=0))return 0|(r=1);r=A|=0,A=1;do{A=0|b(0==(1&e|0)?1:r,A),e>>=1,r=0|b(r,r)}while(0!=(0|e));return 0|A}function re(A,e,r){A|=0;var t,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0;if(!(0|O(e|=0,r|=0)))return 0|(d=0);if(e=0|Y(e),o=+n[r>>3],a=e&(a=+n[r+8>>3])<0?a+6.283185307179586:a,(0|(d=0|i[A>>2]))<=0)return 0|(d=0);if(t=0|i[A+4>>2],e){e=0,r=-1,A=0;A:for(;;){for(c=A;u=+n[t+(c<<4)>>3],h=+n[t+(c<<4)+8>>3],s=+n[t+((A=(r+2|0)%(0|d)|0)<<4)>>3],f=+n[t+(A<<4)+8>>3],u>s?(l=u,u=h):(l=s,s=u,u=f,f=h),ol;){if(!((0|(r=c+1|0))<(0|d))){r=22;break A}A=c,c=r,r=A}if(a=(u=u<0?u+6.283185307179586:u)==a|(h=f<0?f+6.283185307179586:f)==a?a+-2220446049250313e-31:a,((h+=(o-s)/(l-s)*(u-h))<0?h+6.283185307179586:h)>a&&(e^=1),(0|(A=c+1|0))>=(0|d)){r=22;break}r=c}if(22==(0|r))return 0|e}else{e=0,r=-1,A=0;A:for(;;){for(c=A;u=+n[t+(c<<4)>>3],h=+n[t+(c<<4)+8>>3],s=+n[t+((A=(r+2|0)%(0|d)|0)<<4)>>3],f=+n[t+(A<<4)+8>>3],u>s?(l=u,u=h):(l=s,s=u,u=f,f=h),ol;){if(!((0|(r=c+1|0))<(0|d))){r=22;break A}A=c,c=r,r=A}if(f+(o-s)/(l-s)*(u-f)>(a=u==a|f==a?a+-2220446049250313e-31:a)&&(e^=1),(0|(A=c+1|0))>=(0|d)){r=22;break}r=c}if(22==(0|r))return 0|e}return 0}function te(A,e){e|=0;var r,t,o,a,s,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0;if(!(t=0|i[(A|=0)>>2]))return i[e>>2]=0,i[e+4>>2]=0,i[e+8>>2]=0,i[e+12>>2]=0,i[e+16>>2]=0,i[e+20>>2]=0,i[e+24>>2]=0,void(i[e+28>>2]=0);if(n[(o=e+8|0)>>3]=17976931348623157e292,n[(a=e+24|0)>>3]=17976931348623157e292,n[e>>3]=-17976931348623157e292,n[(s=e+16|0)>>3]=-17976931348623157e292,!((0|t)<=0)){for(r=0|i[A+4>>2],p=17976931348623157e292,B=-17976931348623157e292,b=0,A=-1,c=17976931348623157e292,d=17976931348623157e292,w=-17976931348623157e292,l=-17976931348623157e292,v=0;u=+n[r+(v<<4)>>3],g=+n[r+(v<<4)+8>>3],h=+n[r+(((0|(A=A+2|0))==(0|t)?0:A)<<4)+8>>3],u>3]=u,c=u),g>3]=g,d=g),u>w?n[e>>3]=u:u=w,g>l&&(n[s>>3]=g,l=g),p=g>0&gB?g:B,b|=+f(+(g-h))>3.141592653589793,(0|(A=v+1|0))!=(0|t);)m=v,w=u,v=A,A=m;b&&(n[s>>3]=B,n[a>>3]=p)}}function ie(A,e){e|=0;var r,t=0,o=0,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,Q=0,y=0,E=0;if(B=0|i[(A|=0)>>2]){if(n[(b=e+8|0)>>3]=17976931348623157e292,n[(v=e+24|0)>>3]=17976931348623157e292,n[e>>3]=-17976931348623157e292,n[(m=e+16|0)>>3]=-17976931348623157e292,(0|B)>0){for(a=0|i[A+4>>2],w=17976931348623157e292,p=-17976931348623157e292,o=0,t=-1,h=17976931348623157e292,c=17976931348623157e292,g=-17976931348623157e292,u=-17976931348623157e292,k=0;s=+n[a+(k<<4)>>3],d=+n[a+(k<<4)+8>>3],l=+n[a+(((0|(y=t+2|0))==(0|B)?0:y)<<4)+8>>3],s>3]=s,h=s),d>3]=d,c=d),s>g?n[e>>3]=s:s=g,d>u&&(n[m>>3]=d,u=d),w=d>0&dp?d:p,o|=+f(+(d-l))>3.141592653589793,(0|(t=k+1|0))!=(0|B);)y=k,g=s,k=t,t=y;o&&(n[m>>3]=p,n[v>>3]=w)}}else i[e>>2]=0,i[e+4>>2]=0,i[e+8>>2]=0,i[e+12>>2]=0,i[e+16>>2]=0,i[e+20>>2]=0,i[e+24>>2]=0,i[e+28>>2]=0;if(!((0|(t=0|i[(y=A+8|0)>>2]))<=0)){r=A+12|0,Q=0;do{if(a=0|i[r>>2],o=Q,v=e+((Q=Q+1|0)<<5)|0,m=0|i[a+(o<<3)>>2]){if(n[(k=e+(Q<<5)+8|0)>>3]=17976931348623157e292,n[(A=e+(Q<<5)+24|0)>>3]=17976931348623157e292,n[v>>3]=-17976931348623157e292,n[(M=e+(Q<<5)+16|0)>>3]=-17976931348623157e292,(0|m)>0){for(B=0|i[a+(o<<3)+4>>2],w=17976931348623157e292,p=-17976931348623157e292,a=0,o=-1,b=0,h=17976931348623157e292,c=17976931348623157e292,d=-17976931348623157e292,u=-17976931348623157e292;s=+n[B+(b<<4)>>3],g=+n[B+(b<<4)+8>>3],l=+n[B+(((0|(o=o+2|0))==(0|m)?0:o)<<4)+8>>3],s>3]=s,h=s),g>3]=g,c=g),s>d?n[v>>3]=s:s=d,g>u&&(n[M>>3]=g,u=g),w=g>0&gp?g:p,a|=+f(+(g-l))>3.141592653589793,(0|(o=b+1|0))!=(0|m);)E=b,b=o,d=s,o=E;a&&(n[M>>3]=p,n[A>>3]=w)}}else i[v>>2]=0,i[v+4>>2]=0,i[v+8>>2]=0,i[v+12>>2]=0,i[v+16>>2]=0,i[v+20>>2]=0,i[v+24>>2]=0,i[v+28>>2]=0,t=0|i[y>>2]}while((0|Q)<(0|t))}}function ne(A,e,r){var t=0,n=0,o=0;if(!(0|re(A|=0,e|=0,r|=0)))return 0|(n=0);if((0|i[(n=A+8|0)>>2])<=0)return 0|(n=1);for(t=A+12|0,A=0;;){if(o=A,A=A+1|0,0|re((0|i[t>>2])+(o<<3)|0,e+(A<<5)|0,r)){A=0,t=6;break}if((0|A)>=(0|i[n>>2])){A=1,t=6;break}}return 6==(0|t)?0|A:0}function oe(A,e,r,t,i){e|=0,r|=0,t|=0,i|=0;var o,a,f,s,u,l,h,c=0;s=+n[(A|=0)>>3],f=+n[e>>3]-s,a=+n[A+8>>3],o=+n[e+8>>3]-a,l=+n[r>>3],c=((c=+n[t>>3]-l)*(a-(h=+n[r+8>>3]))-(s-l)*(u=+n[t+8>>3]-h))/(f*u-o*c),n[i>>3]=s+f*c,n[i+8>>3]=a+o*c}function ae(A,e){return e|=0,+n[(A|=0)>>3]!=+n[e>>3]?0|(e=0):0|(e=+n[A+8>>3]==+n[e+8>>3])}function fe(A,e){e|=0;var r,t,i;return+((i=+n[(A|=0)>>3]-+n[e>>3])*i+(t=+n[A+8>>3]-+n[e+8>>3])*t+(r=+n[A+16>>3]-+n[e+16>>3])*r)}function se(A,e,r){A|=0,r|=0;var t=0;(0|(e|=0))>0?(t=0|be(e,4),i[A>>2]=t,t||Q(23230,23253,40,23267)):i[A>>2]=0,i[A+4>>2]=e,i[A+8>>2]=0,i[A+12>>2]=r}function ue(A){var e,r,t,o=0,a=0,s=0,l=0;e=(A|=0)+4|0,r=A+12|0,t=A+8|0;A:for(;;){for(a=0|i[e>>2],o=0;;){if((0|o)>=(0|a))break A;if(s=0|i[A>>2],l=0|i[s+(o<<2)>>2])break;o=o+1|0}o=s+(~~(+f(+ +u(10,+ +(15-(0|i[r>>2])|0))*(+n[l>>3]+ +n[l+8>>3]))%+(0|a))>>>0<<2)|0,a=0|i[o>>2];e:do{if(0|a){if(s=l+32|0,(0|a)==(0|l))i[o>>2]=i[s>>2];else{if(!(o=0|i[(a=a+32|0)>>2]))break;for(;(0|o)!=(0|l);)if(!(o=0|i[(a=o+32|0)>>2]))break e;i[a>>2]=i[s>>2]}Be(l),i[t>>2]=(0|i[t>>2])-1}}while(0)}Be(0|i[A>>2])}function le(A){var e,r=0,t=0;for(e=0|i[(A|=0)+4>>2],t=0;;){if((0|t)>=(0|e)){r=0,t=4;break}if(r=0|i[(0|i[A>>2])+(t<<2)>>2]){t=4;break}t=t+1|0}return 4==(0|t)?0|r:0}function he(A,e){e|=0;var r=0,t=0,o=0,a=0;if(r=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,r=(0|i[A>>2])+(r<<2)|0,!(t=0|i[r>>2]))return 0|(a=1);a=e+32|0;do{if((0|t)!=(0|e)){if(!(r=0|i[t+32>>2]))return 0|(a=1);for(o=r;;){if((0|o)==(0|e)){o=8;break}if(!(r=0|i[o+32>>2])){r=1,o=10;break}t=o,o=r}if(8==(0|o)){i[t+32>>2]=i[a>>2];break}if(10==(0|o))return 0|r}else i[r>>2]=i[a>>2]}while(0);return Be(e),i[(a=A+8|0)>>2]=(0|i[a>>2])-1,0|(a=0)}function ce(A,e,r){A|=0,e|=0,r|=0;var t,o=0,a=0,s=0;(t=0|pe(40))||Q(23283,23253,98,23296),i[t>>2]=i[e>>2],i[t+4>>2]=i[e+4>>2],i[t+8>>2]=i[e+8>>2],i[t+12>>2]=i[e+12>>2],i[(a=t+16|0)>>2]=i[r>>2],i[a+4>>2]=i[r+4>>2],i[a+8>>2]=i[r+8>>2],i[a+12>>2]=i[r+12>>2],i[t+32>>2]=0,a=~~(+f(+ +u(10,+ +(15-(0|i[A+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,a=(0|i[A>>2])+(a<<2)|0,o=0|i[a>>2];do{if(o){for(;!(0|xA(o,e)&&0|xA(o+16|0,r));)if(a=0|i[o+32>>2],!(0|i[(o=0==(0|a)?o:a)+32>>2])){s=10;break}if(10==(0|s)){i[o+32>>2]=t;break}return Be(t),0|(s=o)}i[a>>2]=t}while(0);return i[(s=A+8|0)>>2]=1+(0|i[s>>2]),0|(s=t)}function de(A,e,r){e|=0,r|=0;var t=0,o=0;if(o=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,!(o=0|i[(0|i[A>>2])+(o<<2)>>2]))return 0|(r=0);if(!r){for(A=o;;){if(0|xA(A,e)){t=10;break}if(!(A=0|i[A+32>>2])){A=0,t=10;break}}if(10==(0|t))return 0|A}for(A=o;;){if(0|xA(A,e)&&0|xA(A+16|0,r)){t=10;break}if(!(A=0|i[A+32>>2])){A=0,t=10;break}}return 10==(0|t)?0|A:0}function ge(A,e){e|=0;var r=0;if(r=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,!(A=0|i[(0|i[A>>2])+(r<<2)>>2]))return 0|(r=0);for(;;){if(0|xA(A,e)){e=5;break}if(!(A=0|i[A+32>>2])){A=0,e=5;break}}return 5==(0|e)?0|A:0}function we(A){return 0|~~+function(A){return+ +Ie(+(A=+A))}(A=+A)}function pe(A){A|=0;var e,r=0,t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0;e=I,I=I+16|0,d=e;do{if(A>>>0<245){if(A=(l=A>>>0<11?16:A+11&-8)>>>3,3&(t=(c=0|i[5829])>>>A)|0)return n=0|i[(t=(A=23356+((r=(1&t^1)+A|0)<<1<<2)|0)+8|0)>>2],(0|(a=0|i[(o=n+8|0)>>2]))==(0|A)?i[5829]=c&~(1<>2]=A,i[t>>2]=a),k=r<<3,i[n+4>>2]=3|k,i[(k=n+k+4|0)>>2]=1|i[k>>2],I=e,0|(k=o);if(l>>>0>(h=0|i[5831])>>>0){if(0|t)return r=((r=t<>>=s=r>>>12&16)>>>5&8)|s|(a=(r>>>=t)>>>2&4)|(A=(r>>>=a)>>>1&2)|(n=(r>>>=A)>>>1&1))+(r>>>n)|0)<<1<<2)|0)+8|0)>>2],(0|(t=0|i[(s=a+8|0)>>2]))==(0|r)?(A=c&~(1<>2]=r,i[A>>2]=t,A=c),f=(k=n<<3)-l|0,i[a+4>>2]=3|l,i[(o=a+l|0)+4>>2]=1|f,i[a+k>>2]=f,0|h&&(n=0|i[5834],t=23356+((r=h>>>3)<<1<<2)|0,A&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=n,i[r+12>>2]=n,i[n+8>>2]=r,i[n+12>>2]=t),i[5831]=f,i[5834]=o,I=e,0|(k=s);if(a=0|i[5830]){for(t=(a&0-a)-1|0,t=u=0|i[23620+(((n=(t>>>=o=t>>>12&16)>>>5&8)|o|(f=(t>>>=n)>>>2&4)|(s=(t>>>=f)>>>1&2)|(u=(t>>>=s)>>>1&1))+(t>>>u)<<2)>>2],s=u,u=(-8&i[u+4>>2])-l|0;(A=0|i[t+16>>2])||(A=0|i[t+20>>2]);)t=A,s=(o=(f=(-8&i[A+4>>2])-l|0)>>>0>>0)?A:s,u=o?f:u;if((f=s+l|0)>>>0>s>>>0){o=0|i[s+24>>2],r=0|i[s+12>>2];do{if((0|r)==(0|s)){if(!(r=0|i[(A=s+20|0)>>2])&&!(r=0|i[(A=s+16|0)>>2])){t=0;break}for(;;)if(t=0|i[(n=r+20|0)>>2])r=t,A=n;else{if(!(t=0|i[(n=r+16|0)>>2]))break;r=t,A=n}i[A>>2]=0,t=r}else t=0|i[s+8>>2],i[t+12>>2]=r,i[r+8>>2]=t,t=r}while(0);do{if(0|o){if(r=0|i[s+28>>2],(0|s)==(0|i[(A=23620+(r<<2)|0)>>2])){if(i[A>>2]=t,!t){i[5830]=a&~(1<>2])==(0|s)?k:o+20|0)>>2]=t,!t)break;i[t+24>>2]=o,0|(r=0|i[s+16>>2])&&(i[t+16>>2]=r,i[r+24>>2]=t),0|(r=0|i[s+20>>2])&&(i[t+20>>2]=r,i[r+24>>2]=t)}}while(0);return u>>>0<16?(k=u+l|0,i[s+4>>2]=3|k,i[(k=s+k+4|0)>>2]=1|i[k>>2]):(i[s+4>>2]=3|l,i[f+4>>2]=1|u,i[f+u>>2]=u,0|h&&(n=0|i[5834],t=23356+((r=h>>>3)<<1<<2)|0,(r=1<>2]:(i[5829]=r|c,r=t,A=t+8|0),i[A>>2]=n,i[r+12>>2]=n,i[n+8>>2]=r,i[n+12>>2]=t),i[5831]=u,i[5834]=f),I=e,0|(k=s+8|0)}c=l}else c=l}else c=l}else if(A>>>0<=4294967231)if(l=-8&(A=A+11|0),n=0|i[5830]){o=0-l|0,u=(A>>>=8)?l>>>0>16777215?31:l>>>((u=14-((s=((p=A<<(c=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|c|(u=((p<<=s)+245760|0)>>>16&2))+(p<>>15)|0)+7|0)&1|u<<1:0,t=0|i[23620+(u<<2)>>2];A:do{if(t)for(A=0,s=l<<(31==(0|u)?0:25-(u>>>1)|0),a=0;;){if((f=(-8&i[t+4>>2])-l|0)>>>0>>0){if(!f){A=t,o=0,p=65;break A}A=t,o=f}if(a=0==(0|(p=0|i[t+20>>2]))|(0|p)==(0|(t=0|i[t+16+(s>>>31<<2)>>2]))?a:p,!t){t=a,p=61;break}s<<=1}else t=0,A=0,p=61}while(0);if(61==(0|p)){if(0==(0|t)&0==(0|A)){if(!(A=((A=2<>>=f=c>>>12&16)>>>5&8)|f|(s=(c>>>=a)>>>2&4)|(u=(c>>>=s)>>>1&2)|(t=(c>>>=u)>>>1&1))+(c>>>t)<<2)>>2]}t?p=65:(s=A,f=o)}if(65==(0|p))for(a=t;;){if(o=(t=(c=(-8&i[a+4>>2])-l|0)>>>0>>0)?c:o,A=t?a:A,(t=0|i[a+16>>2])||(t=0|i[a+20>>2]),!t){s=A,f=o;break}a=t}if(0!=(0|s)&&f>>>0<((0|i[5831])-l|0)>>>0&&(h=s+l|0)>>>0>s>>>0){a=0|i[s+24>>2],r=0|i[s+12>>2];do{if((0|r)==(0|s)){if(!(r=0|i[(A=s+20|0)>>2])&&!(r=0|i[(A=s+16|0)>>2])){r=0;break}for(;;)if(t=0|i[(o=r+20|0)>>2])r=t,A=o;else{if(!(t=0|i[(o=r+16|0)>>2]))break;r=t,A=o}i[A>>2]=0}else k=0|i[s+8>>2],i[k+12>>2]=r,i[r+8>>2]=k}while(0);do{if(a){if(A=0|i[s+28>>2],(0|s)==(0|i[(t=23620+(A<<2)|0)>>2])){if(i[t>>2]=r,!r){n&=~(1<>2])==(0|s)?k:a+20|0)>>2]=r,!r)break;i[r+24>>2]=a,0|(A=0|i[s+16>>2])&&(i[r+16>>2]=A,i[A+24>>2]=r),(A=0|i[s+20>>2])&&(i[r+20>>2]=A,i[A+24>>2]=r)}}while(0);A:do{if(f>>>0<16)k=f+l|0,i[s+4>>2]=3|k,i[(k=s+k+4|0)>>2]=1|i[k>>2];else{if(i[s+4>>2]=3|l,i[h+4>>2]=1|f,i[h+f>>2]=f,r=f>>>3,f>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=h,i[r+12>>2]=h,i[h+8>>2]=r,i[h+12>>2]=t;break}if(r=23620+((t=(r=f>>>8)?f>>>0>16777215?31:f>>>((t=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(t=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|t<<1:0)<<2)|0,i[h+28>>2]=t,i[(A=h+16|0)+4>>2]=0,i[A>>2]=0,!(n&(A=1<>2]=h,i[h+24>>2]=r,i[h+12>>2]=h,i[h+8>>2]=h;break}r=0|i[r>>2];e:do{if((-8&i[r+4>>2]|0)!=(0|f)){for(n=f<<(31==(0|t)?0:25-(t>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|f)){r=A;break e}n<<=1,r=A}i[t>>2]=h,i[h+24>>2]=r,i[h+12>>2]=h,i[h+8>>2]=h;break A}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=h,i[m>>2]=h,i[h+8>>2]=k,i[h+12>>2]=r,i[h+24>>2]=0}}while(0);return I=e,0|(k=s+8|0)}c=l}else c=l;else c=-1}while(0);if((t=0|i[5831])>>>0>=c>>>0)return r=t-c|0,A=0|i[5834],r>>>0>15?(k=A+c|0,i[5834]=k,i[5831]=r,i[k+4>>2]=1|r,i[A+t>>2]=r,i[A+4>>2]=3|c):(i[5831]=0,i[5834]=0,i[A+4>>2]=3|t,i[(k=A+t+4|0)>>2]=1|i[k>>2]),I=e,0|(k=A+8|0);if((f=0|i[5832])>>>0>c>>>0)return v=f-c|0,i[5832]=v,m=(k=0|i[5835])+c|0,i[5835]=m,i[m+4>>2]=1|v,i[k+4>>2]=3|c,I=e,0|(k=k+8|0);if(0|i[5947]?A=0|i[5949]:(i[5949]=4096,i[5948]=4096,i[5950]=-1,i[5951]=-1,i[5952]=0,i[5940]=0,i[5947]=-16&d^1431655768,A=4096),s=c+48|0,(l=(a=A+(u=c+47|0)|0)&(o=0-A|0))>>>0<=c>>>0)return I=e,0|(k=0);if(0|(A=0|i[5939])&&(d=(h=0|i[5937])+l|0)>>>0<=h>>>0|d>>>0>A>>>0)return I=e,0|(k=0);A:do{if(4&i[5940])r=0,p=143;else{t=0|i[5835];e:do{if(t){for(n=23764;!((d=0|i[n>>2])>>>0<=t>>>0&&(d+(0|i[n+4>>2])|0)>>>0>t>>>0);){if(!(A=0|i[n+8>>2])){p=128;break e}n=A}if((r=a-f&o)>>>0<2147483647)if((0|(A=0|Fe(0|r)))==((0|i[n>>2])+(0|i[n+4>>2])|0)){if(-1!=(0|A)){f=r,a=A,p=145;break A}}else n=A,p=136;else r=0}else p=128}while(0);do{if(128==(0|p))if(-1!=(0|(t=0|Fe(0)))&&(r=t,w=(r=(0==((w=(g=0|i[5948])+-1|0)&r|0)?0:(w+r&0-g)-r|0)+l|0)+(g=0|i[5937])|0,r>>>0>c>>>0&r>>>0<2147483647)){if(0|(d=0|i[5939])&&w>>>0<=g>>>0|w>>>0>d>>>0){r=0;break}if((0|(A=0|Fe(0|r)))==(0|t)){f=r,a=t,p=145;break A}n=A,p=136}else r=0}while(0);do{if(136==(0|p)){if(t=0-r|0,!(s>>>0>r>>>0&r>>>0<2147483647&-1!=(0|n))){if(-1==(0|n)){r=0;break}f=r,a=n,p=145;break A}if((A=u-r+(A=0|i[5949])&0-A)>>>0>=2147483647){f=r,a=n,p=145;break A}if(-1==(0|Fe(0|A))){Fe(0|t),r=0;break}f=A+r|0,a=n,p=145;break A}}while(0);i[5940]=4|i[5940],p=143}}while(0);if(143==(0|p)&&l>>>0<2147483647&&!(-1==(0|(v=0|Fe(0|l)))|1^(b=(B=(w=0|Fe(0))-v|0)>>>0>(c+40|0)>>>0)|v>>>0>>0&-1!=(0|v)&-1!=(0|w)^1)&&(f=b?B:r,a=v,p=145),145==(0|p)){r=(0|i[5937])+f|0,i[5937]=r,r>>>0>(0|i[5938])>>>0&&(i[5938]=r),u=0|i[5835];A:do{if(u){for(r=23764;;){if((0|a)==((A=0|i[r>>2])+(t=0|i[r+4>>2])|0)){p=154;break}if(!(n=0|i[r+8>>2]))break;r=n}if(154==(0|p)&&(m=r+4|0,0==(8&i[r+12>>2]|0))&&a>>>0>u>>>0&A>>>0<=u>>>0){i[m>>2]=t+f,m=u+(v=0==(7&(v=u+8|0)|0)?0:0-v&7)|0,v=(k=(0|i[5832])+f|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[u+k+4>>2]=40,i[5836]=i[5951];break}for(a>>>0<(0|i[5833])>>>0&&(i[5833]=a),t=a+f|0,r=23764;;){if((0|i[r>>2])==(0|t)){p=162;break}if(!(A=0|i[r+8>>2]))break;r=A}if(162==(0|p)&&0==(8&i[r+12>>2]|0)){i[r>>2]=a,i[(h=r+4|0)>>2]=(0|i[h>>2])+f,l=(h=a+(0==(7&(h=a+8|0)|0)?0:0-h&7)|0)+c|0,s=(r=t+(0==(7&(r=t+8|0)|0)?0:0-r&7)|0)-h-c|0,i[h+4>>2]=3|c;e:do{if((0|u)==(0|r))k=(0|i[5832])+s|0,i[5832]=k,i[5835]=l,i[l+4>>2]=1|k;else{if((0|i[5834])==(0|r)){k=(0|i[5831])+s|0,i[5831]=k,i[5834]=l,i[l+4>>2]=1|k,i[l+k>>2]=k;break}if(1==(3&(A=0|i[r+4>>2])|0)){f=-8&A,n=A>>>3;r:do{if(A>>>0<256){if(A=0|i[r+8>>2],(0|(t=0|i[r+12>>2]))==(0|A)){i[5829]=i[5829]&~(1<>2]=t,i[t+8>>2]=A;break}a=0|i[r+24>>2],A=0|i[r+12>>2];do{if((0|A)==(0|r)){if(A=0|i[(n=(t=r+16|0)+4|0)>>2])t=n;else if(!(A=0|i[t>>2])){A=0;break}for(;;)if(n=0|i[(o=A+20|0)>>2])A=n,t=o;else{if(!(n=0|i[(o=A+16|0)>>2]))break;A=n,t=o}i[t>>2]=0}else k=0|i[r+8>>2],i[k+12>>2]=A,i[A+8>>2]=k}while(0);if(!a)break;n=23620+((t=0|i[r+28>>2])<<2)|0;do{if((0|i[n>>2])==(0|r)){if(i[n>>2]=A,0|A)break;i[5830]=i[5830]&~(1<>2])==(0|r)?k:a+20|0)>>2]=A,!A)break r}while(0);if(i[A+24>>2]=a,0|(n=0|i[(t=r+16|0)>>2])&&(i[A+16>>2]=n,i[n+24>>2]=A),!(t=0|i[t+4>>2]))break;i[A+20>>2]=t,i[t+24>>2]=A}while(0);r=r+f|0,o=f+s|0}else o=s;if(i[(r=r+4|0)>>2]=-2&i[r>>2],i[l+4>>2]=1|o,i[l+o>>2]=o,r=o>>>3,o>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=l,i[r+12>>2]=l,i[l+8>>2]=r,i[l+12>>2]=t;break}r=o>>>8;do{if(r){if(o>>>0>16777215){n=31;break}n=o>>>((n=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(n=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|n<<1}else n=0}while(0);if(r=23620+(n<<2)|0,i[l+28>>2]=n,i[(A=l+16|0)+4>>2]=0,i[A>>2]=0,!((A=0|i[5830])&(t=1<>2]=l,i[l+24>>2]=r,i[l+12>>2]=l,i[l+8>>2]=l;break}r=0|i[r>>2];r:do{if((-8&i[r+4>>2]|0)!=(0|o)){for(n=o<<(31==(0|n)?0:25-(n>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|o)){r=A;break r}n<<=1,r=A}i[t>>2]=l,i[l+24>>2]=r,i[l+12>>2]=l,i[l+8>>2]=l;break e}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=l,i[m>>2]=l,i[l+8>>2]=k,i[l+12>>2]=r,i[l+24>>2]=0}}while(0);return I=e,0|(k=h+8|0)}for(r=23764;!((A=0|i[r>>2])>>>0<=u>>>0&&(k=A+(0|i[r+4>>2])|0)>>>0>u>>>0);)r=0|i[r+8>>2];r=(A=(A=(o=k+-47|0)+(0==(7&(A=o+8|0)|0)?0:0-A&7)|0)>>>0<(o=u+16|0)>>>0?u:A)+8|0,m=a+(v=0==(7&(v=a+8|0)|0)?0:0-v&7)|0,v=(t=f+-40|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[a+t+4>>2]=40,i[5836]=i[5951],i[(t=A+4|0)>>2]=27,i[r>>2]=i[5941],i[r+4>>2]=i[5942],i[r+8>>2]=i[5943],i[r+12>>2]=i[5944],i[5941]=a,i[5942]=f,i[5944]=0,i[5943]=r,r=A+24|0;do{m=r,i[(r=r+4|0)>>2]=7}while((m+8|0)>>>0>>0);if((0|A)!=(0|u)){if(a=A-u|0,i[t>>2]=-2&i[t>>2],i[u+4>>2]=1|a,i[A>>2]=a,r=a>>>3,a>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=u,i[r+12>>2]=u,i[u+8>>2]=r,i[u+12>>2]=t;break}if(t=23620+((n=(r=a>>>8)?a>>>0>16777215?31:a>>>((n=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(n=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|n<<1:0)<<2)|0,i[u+28>>2]=n,i[u+20>>2]=0,i[o>>2]=0,!((r=0|i[5830])&(A=1<>2]=u,i[u+24>>2]=t,i[u+12>>2]=u,i[u+8>>2]=u;break}r=0|i[t>>2];e:do{if((-8&i[r+4>>2]|0)!=(0|a)){for(n=a<<(31==(0|n)?0:25-(n>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|a)){r=A;break e}n<<=1,r=A}i[t>>2]=u,i[u+24>>2]=r,i[u+12>>2]=u,i[u+8>>2]=u;break A}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=u,i[m>>2]=u,i[u+8>>2]=k,i[u+12>>2]=r,i[u+24>>2]=0}}else 0==(0|(k=0|i[5833]))|a>>>0>>0&&(i[5833]=a),i[5941]=a,i[5942]=f,i[5944]=0,i[5838]=i[5947],i[5837]=-1,i[5842]=23356,i[5841]=23356,i[5844]=23364,i[5843]=23364,i[5846]=23372,i[5845]=23372,i[5848]=23380,i[5847]=23380,i[5850]=23388,i[5849]=23388,i[5852]=23396,i[5851]=23396,i[5854]=23404,i[5853]=23404,i[5856]=23412,i[5855]=23412,i[5858]=23420,i[5857]=23420,i[5860]=23428,i[5859]=23428,i[5862]=23436,i[5861]=23436,i[5864]=23444,i[5863]=23444,i[5866]=23452,i[5865]=23452,i[5868]=23460,i[5867]=23460,i[5870]=23468,i[5869]=23468,i[5872]=23476,i[5871]=23476,i[5874]=23484,i[5873]=23484,i[5876]=23492,i[5875]=23492,i[5878]=23500,i[5877]=23500,i[5880]=23508,i[5879]=23508,i[5882]=23516,i[5881]=23516,i[5884]=23524,i[5883]=23524,i[5886]=23532,i[5885]=23532,i[5888]=23540,i[5887]=23540,i[5890]=23548,i[5889]=23548,i[5892]=23556,i[5891]=23556,i[5894]=23564,i[5893]=23564,i[5896]=23572,i[5895]=23572,i[5898]=23580,i[5897]=23580,i[5900]=23588,i[5899]=23588,i[5902]=23596,i[5901]=23596,i[5904]=23604,i[5903]=23604,m=a+(v=0==(7&(v=a+8|0)|0)?0:0-v&7)|0,v=(k=f+-40|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[a+k+4>>2]=40,i[5836]=i[5951]}while(0);if((r=0|i[5832])>>>0>c>>>0)return v=r-c|0,i[5832]=v,m=(k=0|i[5835])+c|0,i[5835]=m,i[m+4>>2]=1|v,i[k+4>>2]=3|c,I=e,0|(k=k+8|0)}return i[(k=23312)>>2]=12,I=e,0|(k=0)}function Be(A){var e=0,r=0,t=0,n=0,o=0,a=0,f=0,s=0;if(A|=0){r=A+-8|0,n=0|i[5833],s=r+(e=-8&(A=0|i[A+-4>>2]))|0;do{if(1&A)f=r,a=r;else{if(t=0|i[r>>2],!(3&A))return;if(o=t+e|0,(a=r+(0-t)|0)>>>0>>0)return;if((0|i[5834])==(0|a)){if(3!=(3&(e=0|i[(A=s+4|0)>>2])|0)){f=a,e=o;break}return i[5831]=o,i[A>>2]=-2&e,i[a+4>>2]=1|o,void(i[a+o>>2]=o)}if(r=t>>>3,t>>>0<256){if(A=0|i[a+8>>2],(0|(e=0|i[a+12>>2]))==(0|A)){i[5829]=i[5829]&~(1<>2]=e,i[e+8>>2]=A,f=a,e=o;break}n=0|i[a+24>>2],A=0|i[a+12>>2];do{if((0|A)==(0|a)){if(A=0|i[(r=(e=a+16|0)+4|0)>>2])e=r;else if(!(A=0|i[e>>2])){A=0;break}for(;;)if(r=0|i[(t=A+20|0)>>2])A=r,e=t;else{if(!(r=0|i[(t=A+16|0)>>2]))break;A=r,e=t}i[e>>2]=0}else f=0|i[a+8>>2],i[f+12>>2]=A,i[A+8>>2]=f}while(0);if(n){if(e=0|i[a+28>>2],(0|i[(r=23620+(e<<2)|0)>>2])==(0|a)){if(i[r>>2]=A,!A){i[5830]=i[5830]&~(1<>2])==(0|a)?f:n+20|0)>>2]=A,!A){f=a,e=o;break}i[A+24>>2]=n,0|(r=0|i[(e=a+16|0)>>2])&&(i[A+16>>2]=r,i[r+24>>2]=A),(e=0|i[e+4>>2])?(i[A+20>>2]=e,i[e+24>>2]=A,f=a,e=o):(f=a,e=o)}else f=a,e=o}}while(0);if(!(a>>>0>=s>>>0)&&1&(t=0|i[(A=s+4|0)>>2])){if(2&t)i[A>>2]=-2&t,i[f+4>>2]=1|e,i[a+e>>2]=e,n=e;else{if((0|i[5835])==(0|s)){if(s=(0|i[5832])+e|0,i[5832]=s,i[5835]=f,i[f+4>>2]=1|s,(0|f)!=(0|i[5834]))return;return i[5834]=0,void(i[5831]=0)}if((0|i[5834])==(0|s))return s=(0|i[5831])+e|0,i[5831]=s,i[5834]=a,i[f+4>>2]=1|s,void(i[a+s>>2]=s);n=(-8&t)+e|0,r=t>>>3;do{if(t>>>0<256){if(e=0|i[s+8>>2],(0|(A=0|i[s+12>>2]))==(0|e)){i[5829]=i[5829]&~(1<>2]=A,i[A+8>>2]=e;break}o=0|i[s+24>>2],A=0|i[s+12>>2];do{if((0|A)==(0|s)){if(A=0|i[(r=(e=s+16|0)+4|0)>>2])e=r;else if(!(A=0|i[e>>2])){r=0;break}for(;;)if(r=0|i[(t=A+20|0)>>2])A=r,e=t;else{if(!(r=0|i[(t=A+16|0)>>2]))break;A=r,e=t}i[e>>2]=0,r=A}else r=0|i[s+8>>2],i[r+12>>2]=A,i[A+8>>2]=r,r=A}while(0);if(0|o){if(A=0|i[s+28>>2],(0|i[(e=23620+(A<<2)|0)>>2])==(0|s)){if(i[e>>2]=r,!r){i[5830]=i[5830]&~(1<>2])==(0|s)?t:o+20|0)>>2]=r,!r)break;i[r+24>>2]=o,0|(e=0|i[(A=s+16|0)>>2])&&(i[r+16>>2]=e,i[e+24>>2]=r),0|(A=0|i[A+4>>2])&&(i[r+20>>2]=A,i[A+24>>2]=r)}}while(0);if(i[f+4>>2]=1|n,i[a+n>>2]=n,(0|f)==(0|i[5834]))return void(i[5831]=n)}if(A=n>>>3,n>>>0<256)return r=23356+(A<<1<<2)|0,(e=0|i[5829])&(A=1<>2]:(i[5829]=e|A,A=r,e=r+8|0),i[e>>2]=f,i[A+12>>2]=f,i[f+8>>2]=A,void(i[f+12>>2]=r);A=23620+((t=(A=n>>>8)?n>>>0>16777215?31:n>>>((t=14-((o=((s=A<<(a=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|a|(t=((s<<=o)+245760|0)>>>16&2))+(s<>>15)|0)+7|0)&1|t<<1:0)<<2)|0,i[f+28>>2]=t,i[f+20>>2]=0,i[f+16>>2]=0,e=0|i[5830],r=1<>2];e:do{if((-8&i[A+4>>2]|0)!=(0|n)){for(t=n<<(31==(0|t)?0:25-(t>>>1)|0);e=0|i[(r=A+16+(t>>>31<<2)|0)>>2];){if((-8&i[e+4>>2]|0)==(0|n)){A=e;break e}t<<=1,A=e}i[r>>2]=f,i[f+24>>2]=A,i[f+12>>2]=f,i[f+8>>2]=f;break A}}while(0);s=0|i[(a=A+8|0)>>2],i[s+12>>2]=f,i[a>>2]=f,i[f+8>>2]=s,i[f+12>>2]=A,i[f+24>>2]=0}else i[5830]=e|r,i[A>>2]=f,i[f+24>>2]=A,i[f+12>>2]=f,i[f+8>>2]=f}while(0);if(s=(0|i[5837])-1|0,i[5837]=s,!(0|s)){for(A=23772;A=0|i[A>>2];)A=A+8|0;i[5837]=-1}}}}function be(A,e){e|=0;var r=0;return(A|=0)?(r=0|b(e,A),(e|A)>>>0>65535&&(r=(0|(r>>>0)/(A>>>0))==(0|e)?r:-1)):r=0,(A=0|pe(r))&&3&i[A+-4>>2]?(_e(0|A,0,0|r),0|A):0|A}function ve(A,e,r,t){return 0|(k(0|(t=(e|=0)-(t|=0)-((r|=0)>>>0>(A|=0)>>>0|0)>>>0)),A-r>>>0|0)}function me(A){return 0|((A|=0)?31-(0|m(A^A-1))|0:32)}function ke(A,e,r,t,n){n|=0;var o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0;if(l=A|=0,a=r|=0,f=c=t|=0,!(u=s=e|=0))return o=0!=(0|n),f?o?(i[n>>2]=0|A,i[n+4>>2]=0&e,n=0,0|(k(0|(c=0)),n)):(n=0,0|(k(0|(c=0)),n)):(o&&(i[n>>2]=(l>>>0)%(a>>>0),i[n+4>>2]=0),n=(l>>>0)/(a>>>0)>>>0,0|(k(0|(c=0)),n));o=0==(0|f);do{if(a){if(!o){if((o=(0|m(0|f))-(0|m(0|u))|0)>>>0<=31){a=h=o+1|0,A=l>>>(h>>>0)&(e=o-31>>31)|u<<(f=31-o|0),e&=u>>>(h>>>0),o=0,f=l<>2]=0|A,i[n+4>>2]=s|0&e,n=0,0|(k(0|(c=0)),n)):(n=0,0|(k(0|(c=0)),n))}if((o=a-1|0)&a|0){a=f=33+(0|m(0|a))-(0|m(0|u))|0,A=(h=32-f|0)-1>>31&u>>>((d=f-32|0)>>>0)|(u<>>(f>>>0))&(e=d>>31),e&=u>>>(f>>>0),o=l<<(g=64-f|0)&(s=h>>31),f=(u<>>(d>>>0))&s|l<>31;break}return 0|n&&(i[n>>2]=o&l,i[n+4>>2]=0),1==(0|a)?(g=0|A,0|(k(0|(d=s|0&e)),g)):(d=u>>>((g=0|me(0|a))>>>0)|0,g=u<<32-g|l>>>(g>>>0)|0,0|(k(0|d),g))}if(o)return 0|n&&(i[n>>2]=(u>>>0)%(a>>>0),i[n+4>>2]=0),g=(u>>>0)/(a>>>0)>>>0,0|(k(0|(d=0)),g);if(!l)return 0|n&&(i[n>>2]=0,i[n+4>>2]=(u>>>0)%(f>>>0)),g=(u>>>0)/(f>>>0)>>>0,0|(k(0|(d=0)),g);if(!((o=f-1|0)&f))return 0|n&&(i[n>>2]=0|A,i[n+4>>2]=o&u|0&e),d=0,g=u>>>((0|me(0|f))>>>0),0|(k(0|d),g);if((o=(0|m(0|f))-(0|m(0|u))|0)>>>0<=30){a=e=o+1|0,A=u<<(f=31-o|0)|l>>>(e>>>0),e=u>>>(e>>>0),o=0,f=l<>2]=0|A,i[n+4>>2]=s|0&e,g=0,0|(k(0|(d=0)),g)):(g=0,0|(k(0|(d=0)),g))}while(0);if(a){u=0|function(A,e,r,t){return 0|(k((e|=0)+(t|=0)+((r=(A|=0)+(r|=0)>>>0)>>>0>>0|0)>>>0|0),0|r)}(0|(h=0|r),0|(l=c|0&t),-1,-1),r=0|M(),s=f,f=0;do{t=s,s=o>>>31|s<<1,o=f|o<<1,ve(0|u,0|r,0|(t=A<<1|t>>>31|0),0|(c=A>>>31|e<<1|0)),f=1&(d=(g=0|M())>>31|((0|g)<0?-1:0)<<1),A=0|ve(0|t,0|c,d&h|0,(((0|g)<0?-1:0)>>31|((0|g)<0?-1:0)<<1)&l|0),e=0|M(),a=a-1|0}while(0!=(0|a));u=s,s=0}else u=f,s=0,f=0;return a=0,0|n&&(i[n>>2]=A,i[n+4>>2]=e),g=-2&(o<<1|0)|f,0|(k(0|(d=(0|o)>>>31|(u|a)<<1|0&(a<<1|o>>>31)|s)),g)}function Me(A,e,r,t){var n,o;return o=I,I=I+16|0,ke(A|=0,e|=0,r|=0,t|=0,n=0|o),I=o,0|(k(0|i[n+4>>2]),0|i[n>>2])}function Qe(A,e,r){return A|=0,e|=0,(0|(r|=0))<32?(k(e>>>r|0),A>>>r|(e&(1<>>r-32|0)}function ye(A,e,r){return A|=0,e|=0,(0|(r|=0))<32?(k(e<>>32-r|0),A<=0?+a(A+.5):+B(A-.5)}function De(A,e,r){A|=0,e|=0;var n,o,a=0;if((0|(r|=0))>=8192)return x(0|A,0|e,0|r),0|A;if(o=0|A,n=A+r|0,(3&A)==(3&e)){for(;3&A;){if(!r)return 0|o;t[A>>0]=0|t[e>>0],A=A+1|0,e=e+1|0,r=r-1|0}for(a=(r=-4&n|0)-64|0;(0|A)<=(0|a);)i[A>>2]=i[e>>2],i[A+4>>2]=i[e+4>>2],i[A+8>>2]=i[e+8>>2],i[A+12>>2]=i[e+12>>2],i[A+16>>2]=i[e+16>>2],i[A+20>>2]=i[e+20>>2],i[A+24>>2]=i[e+24>>2],i[A+28>>2]=i[e+28>>2],i[A+32>>2]=i[e+32>>2],i[A+36>>2]=i[e+36>>2],i[A+40>>2]=i[e+40>>2],i[A+44>>2]=i[e+44>>2],i[A+48>>2]=i[e+48>>2],i[A+52>>2]=i[e+52>>2],i[A+56>>2]=i[e+56>>2],i[A+60>>2]=i[e+60>>2],A=A+64|0,e=e+64|0;for(;(0|A)<(0|r);)i[A>>2]=i[e>>2],A=A+4|0,e=e+4|0}else for(r=n-4|0;(0|A)<(0|r);)t[A>>0]=0|t[e>>0],t[A+1>>0]=0|t[e+1>>0],t[A+2>>0]=0|t[e+2>>0],t[A+3>>0]=0|t[e+3>>0],A=A+4|0,e=e+4|0;for(;(0|A)<(0|n);)t[A>>0]=0|t[e>>0],A=A+1|0,e=e+1|0;return 0|o}function _e(A,e,r){e|=0;var n,o=0,a=0,f=0;if(n=(A|=0)+(r|=0)|0,e&=255,(0|r)>=67){for(;3&A;)t[A>>0]=e,A=A+1|0;for(f=e|e<<8|e<<16|e<<24,a=(o=-4&n|0)-64|0;(0|A)<=(0|a);)i[A>>2]=f,i[A+4>>2]=f,i[A+8>>2]=f,i[A+12>>2]=f,i[A+16>>2]=f,i[A+20>>2]=f,i[A+24>>2]=f,i[A+28>>2]=f,i[A+32>>2]=f,i[A+36>>2]=f,i[A+40>>2]=f,i[A+44>>2]=f,i[A+48>>2]=f,i[A+52>>2]=f,i[A+56>>2]=f,i[A+60>>2]=f,A=A+64|0;for(;(0|A)<(0|o);)i[A>>2]=f,A=A+4|0}for(;(0|A)<(0|n);)t[A>>0]=e,A=A+1|0;return n-r|0}function Ie(A){return(A=+A)>=0?+a(A+.5):+B(A-.5)}function Fe(A){A|=0;var e,r,t;return t=0|E(),(0|A)>0&(0|(e=(r=0|i[o>>2])+A|0))<(0|r)|(0|e)<0?(_(0|e),y(12),-1):(0|e)>(0|t)&&!(0|D(0|e))?(y(12),-1):(i[o>>2]=e,0|r)}return{___uremdi3:Me,_bitshift64Lshr:Qe,_bitshift64Shl:ye,_calloc:be,_cellAreaKm2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))>0){if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1!=(0|e)){A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e))}}else o=0;return I=n,6371.007180918475*o*6371.007180918475},_cellAreaM2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))>0){if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1!=(0|e)){A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e))}}else o=0;return I=n,6371.007180918475*o*6371.007180918475*1e3*1e3},_cellAreaRads2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))<=0)return I=n,+(o=0);if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1==(0|e))return I=n,+o;A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e));return I=n,+o},_compact:function(A,e,r){e|=0;var t,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,Q=0,y=0,E=0;if(!(r|=0))return 0|(y=0);if(n=0|i[(o=A|=0)>>2],!0&0==(15728640&(o=0|i[o+4>>2])|0)){if((0|r)<=0)return 0|(y=0);if(i[(y=e)>>2]=n,i[y+4>>2]=o,1==(0|r))return 0|(y=0);n=1;do{Q=0|i[(k=A+(n<<3)|0)+4>>2],i[(y=e+(n<<3)|0)>>2]=i[k>>2],i[y+4>>2]=Q,n=n+1|0}while((0|n)!=(0|r));return 0|(n=0)}if(!(Q=0|pe(k=r<<3)))return 0|(y=-3);if(De(0|Q,0|A,0|k),!(t=0|be(r,8)))return Be(Q),0|(y=-3);n=r;A:for(;;){v=0|Qe(0|(h=0|i[(f=Q)>>2]),0|(f=0|i[f+4>>2]),52),M(),m=(v&=15)+-1|0,b=(0|n)>0;e:do{if(b){if(B=((0|n)<0)<<31>>31,w=0|ye(0|m,0,52),p=0|M(),m>>>0>15)for(o=0,A=h,r=f;;){if(!(0==(0|A)&0==(0|r))){if(a=0|Qe(0|A,0|r,52),M(),s=(0|(a&=15))<(0|m),a=(0|a)==(0|m),r=0|Me(0|(l=s?0:a?A:0),0|(A=s?0:a?r:0),0|n,0|B),M(),0==(0|(u=0|i[(s=a=t+(r<<3)|0)>>2]))&0==(0|(s=0|i[s+4>>2])))r=l;else for(w=0,g=r,d=s,r=l;;){if((0|w)>(0|n)){y=41;break A}if((0|u)==(0|r)&(-117440513&d|0)==(0|A)){l=0|Qe(0|u,0|d,56),M(),c=(l&=7)+1|0,p=0|Qe(0|u,0|d,45),M();r:do{if(0|S(127&p)){if(u=0|Qe(0|u,0|d,52),M(),!(u&=15)){s=6;break}for(s=1;;){if(!(0==((p=0|ye(7,0,3*(15-s|0)|0))&r|0)&0==((0|M())&A|0))){s=7;break r}if(!(s>>>0>>0)){s=6;break}s=s+1|0}}else s=7}while(0);if((l+2|0)>>>0>s>>>0){y=51;break A}p=0|ye(0|c,0,56),A=0|M()|-117440513&A,i[(s=a)>>2]=0,i[s+4>>2]=0,s=g,r|=p}else s=(g+1|0)%(0|n)|0;if(0==(0|(u=0|i[(d=a=t+(s<<3)|0)>>2]))&0==(0|(d=0|i[d+4>>2])))break;w=w+1|0,g=s}i[(p=a)>>2]=r,i[p+4>>2]=A}if((0|(o=o+1|0))>=(0|n))break e;A=0|i[(r=Q+(o<<3)|0)>>2],r=0|i[r+4>>2]}for(o=0,A=h,r=f;;){if(!(0==(0|A)&0==(0|r))){if(s=0|Qe(0|A,0|r,52),M(),(0|(s&=15))>=(0|m)){if((0|s)!=(0|m)&&(A|=w,r=-15728641&r|p,s>>>0>=v>>>0)){a=m;do{g=0|ye(7,0,3*(14-a|0)|0),a=a+1|0,A|=g,r=0|M()|r}while(a>>>0>>0)}}else A=0,r=0;if(s=0|Me(0|A,0|r,0|n,0|B),M(),!(0==(0|(l=0|i[(u=a=t+(s<<3)|0)>>2]))&0==(0|(u=0|i[u+4>>2]))))for(g=0;;){if((0|g)>(0|n)){y=41;break A}if((0|l)==(0|A)&(-117440513&u|0)==(0|r)){c=0|Qe(0|l,0|u,56),M(),d=(c&=7)+1|0,E=0|Qe(0|l,0|u,45),M();r:do{if(0|S(127&E)){if(l=0|Qe(0|l,0|u,52),M(),!(l&=15)){u=6;break}for(u=1;;){if(!(0==((E=0|ye(7,0,3*(15-u|0)|0))&A|0)&0==((0|M())&r|0))){u=7;break r}if(!(u>>>0>>0)){u=6;break}u=u+1|0}}else u=7}while(0);if((c+2|0)>>>0>u>>>0){y=51;break A}E=0|ye(0|d,0,56),r=0|M()|-117440513&r,i[(d=a)>>2]=0,i[d+4>>2]=0,A|=E}else s=(s+1|0)%(0|n)|0;if(0==(0|(l=0|i[(u=a=t+(s<<3)|0)>>2]))&0==(0|(u=0|i[u+4>>2])))break;g=g+1|0}i[(E=a)>>2]=A,i[E+4>>2]=r}if((0|(o=o+1|0))>=(0|n))break e;A=0|i[(r=Q+(o<<3)|0)>>2],r=0|i[r+4>>2]}}}while(0);if((n+5|0)>>>0<11){y=99;break}if(!(p=0|be((0|n)/6|0,8))){y=58;break}e:do{if(b){g=0,d=0;do{if(!(0==(0|(o=0|i[(A=s=t+(g<<3)|0)>>2]))&0==(0|(A=0|i[A+4>>2])))){u=0|Qe(0|o,0|A,56),M(),r=(u&=7)+1|0,l=-117440513&A,E=0|Qe(0|o,0|A,45),M();r:do{if(0|S(127&E)){if(c=0|Qe(0|o,0|A,52),M(),0|(c&=15))for(a=1;;){if(!(0==(o&(E=0|ye(7,0,3*(15-a|0)|0))|0)&0==(l&(0|M())|0)))break r;if(!(a>>>0>>0))break;a=a+1|0}o|=A=0|ye(0|r,0,56),A=0|M()|l,i[(r=s)>>2]=o,i[r+4>>2]=A,r=u+2|0}}while(0);7==(0|r)&&(i[(E=p+(d<<3)|0)>>2]=o,i[E+4>>2]=-117440513&A,d=d+1|0)}g=g+1|0}while((0|g)!=(0|n));if(b){if(w=((0|n)<0)<<31>>31,c=0|ye(0|m,0,52),g=0|M(),m>>>0>15)for(A=0,o=0;;){do{if(!(0==(0|h)&0==(0|f))){for(u=0|Qe(0|h,0|f,52),M(),a=(0|(u&=15))<(0|m),u=(0|u)==(0|m),a=0|Me(0|(s=a?0:u?h:0),0|(u=a?0:u?f:0),0|n,0|w),M(),r=0;;){if((0|r)>(0|n)){y=98;break A}if((-117440513&(l=0|i[(E=t+(a<<3)|0)+4>>2])|0)==(0|u)&&(0|i[E>>2])==(0|s)){y=70;break}if((0|i[(E=t+((a=(a+1|0)%(0|n)|0)<<3)|0)>>2])==(0|s)&&(0|i[E+4>>2])==(0|u))break;r=r+1|0}if(70==(0|y)&&(y=0,!0&100663296==(117440512&l|0)))break;i[(E=e+(o<<3)|0)>>2]=h,i[E+4>>2]=f,o=o+1|0}}while(0);if((0|(A=A+1|0))>=(0|n)){n=d;break e}h=0|i[(f=Q+(A<<3)|0)>>2],f=0|i[f+4>>2]}for(A=0,o=0;;){do{if(!(0==(0|h)&0==(0|f))){if(u=0|Qe(0|h,0|f,52),M(),(0|(u&=15))>=(0|m))if((0|u)!=(0|m))if(r=h|c,a=-15728641&f|g,u>>>0>>0)u=a;else{s=m;do{E=0|ye(7,0,3*(14-s|0)|0),s=s+1|0,r|=E,a=0|M()|a}while(s>>>0>>0);u=a}else r=h,u=f;else r=0,u=0;for(s=0|Me(0|r,0|u,0|n,0|w),M(),a=0;;){if((0|a)>(0|n)){y=98;break A}if((-117440513&(l=0|i[(E=t+(s<<3)|0)+4>>2])|0)==(0|u)&&(0|i[E>>2])==(0|r)){y=93;break}if((0|i[(E=t+((s=(s+1|0)%(0|n)|0)<<3)|0)>>2])==(0|r)&&(0|i[E+4>>2])==(0|u))break;a=a+1|0}if(93==(0|y)&&(y=0,!0&100663296==(117440512&l|0)))break;i[(E=e+(o<<3)|0)>>2]=h,i[E+4>>2]=f,o=o+1|0}}while(0);if((0|(A=A+1|0))>=(0|n)){n=d;break e}h=0|i[(f=Q+(A<<3)|0)>>2],f=0|i[f+4>>2]}}else o=0,n=d}else o=0,n=0}while(0);if(_e(0|t,0,0|k),De(0|Q,0|p,n<<3|0),Be(p),!n)break;e=e+(o<<3)|0}return 41==(0|y)?(Be(Q),Be(t),0|(E=-1)):51==(0|y)?(Be(Q),Be(t),0|(E=-2)):58==(0|y)?(Be(Q),Be(t),0|(E=-3)):98==(0|y)?(Be(p),Be(Q),Be(t),0|(E=-1)):(99==(0|y)&&De(0|e,0|Q,n<<3|0),Be(Q),Be(t),0|(E=0))},_destroyLinkedPolygon:function(A){var e=0,r=0,t=0,n=0;if(A|=0)for(t=1;;){if(0|(e=0|i[A>>2]))do{if(0|(r=0|i[e>>2]))do{n=r,r=0|i[r+16>>2],Be(n)}while(0!=(0|r));n=e,e=0|i[e+8>>2],Be(n)}while(0!=(0|e));if(e=A,A=0|i[A+8>>2],t||Be(e),!A)break;t=0}},_edgeLengthKm:function(A){return+ +n[20752+((A|=0)<<3)>>3]},_edgeLengthM:function(A){return+ +n[20880+((A|=0)<<3)>>3]},_emscripten_replace_memory:function(A){return t=new Int8Array(A),new Uint8Array(A),i=new Int32Array(A),new Float32Array(A),n=new Float64Array(A),r=A,!0},_exactEdgeLengthKm:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+c)*+l(+a)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)!=(0|e));return I=t,+(d=6371.007180918475*o)},_exactEdgeLengthM:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+c)*+l(+a)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)!=(0|e));return I=t,+(d=6371.007180918475*o*1e3)},_exactEdgeLengthRads:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+a)*+l(+c)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)<(0|e));return I=t,+o},_experimentalH3ToLocalIj:function(A,e,r,t,i){var n,o;return i|=0,o=I,I=I+16|0,(A=0|$A(A|=0,e|=0,r|=0,t|=0,n=o))||(cA(n,i),A=0),I=o,0|A},_experimentalLocalIjToH3:function(A,e,r,t){var i,n;return A|=0,e|=0,t|=0,i=I,I=I+16|0,dA(r|=0,n=i),t=0|Ae(A,e,n,t),I=i,0|t},_free:Be,_geoToH3:LA,_getDestinationH3IndexFromUnidirectionalEdge:function(A,e){A|=0;var r,t,n=0;return r=I,I=I+16|0,n=r,!0&268435456==(2013265920&(e|=0)|0)?(t=0|Qe(0|A,0|e,56),M(),i[n>>2]=0,n=0|U(A,-2130706433&e|134217728,7&t,n),e=0|M(),k(0|e),I=r,0|n):(n=0,k(0|(e=0)),I=r,0|n)},_getH3IndexesFromUnidirectionalEdge:function(A,e,r){A|=0;var t,n,o,a,f=0;o=I,I=I+16|0,t=o,a=!0&268435456==(2013265920&(e|=0)|0),n=-2130706433&e|134217728,i[(f=r|=0)>>2]=a?A:0,i[f+4>>2]=a?n:0,a?(e=0|Qe(0|A,0|e,56),M(),i[t>>2]=0,A=0|U(A,n,7&e,t),e=0|M()):(A=0,e=0),i[(f=r+8|0)>>2]=A,i[f+4>>2]=e,I=o},_getH3UnidirectionalEdge:function(A,e,r,t){var n,o,a=0,f=0,s=0,u=0,l=0;if(o=I,I=I+16|0,n=o,!(0|ZA(A|=0,e|=0,r|=0,t|=0)))return u=0,k(0|(s=0)),I=o,0|u;for(s=-2130706433&e,a=(a=0==(0|UA(A,e)))?1:2;i[n>>2]=0,f=a+1|0,!((0|(l=0|U(A,e,a,n)))==(0|r)&(0|M())==(0|t));){if(!(f>>>0<7)){a=0,A=0,u=6;break}a=f}return 6==(0|u)?(k(0|a),I=o,0|A):(l=0|ye(0|a,0,56),u=0|s|M()|268435456,l|=A,k(0|u),I=o,0|l)},_getH3UnidirectionalEdgeBoundary:WA,_getH3UnidirectionalEdgesFromHexagon:function(A,e,r){r|=0;var t,n=0;t=0==(0|UA(A|=0,e|=0)),e&=-2130706433,i[(n=r)>>2]=t?A:0,i[n+4>>2]=t?285212672|e:0,i[(n=r+8|0)>>2]=A,i[n+4>>2]=301989888|e,i[(n=r+16|0)>>2]=A,i[n+4>>2]=318767104|e,i[(n=r+24|0)>>2]=A,i[n+4>>2]=335544320|e,i[(n=r+32|0)>>2]=A,i[n+4>>2]=352321536|e,i[(r=r+40|0)>>2]=A,i[r+4>>2]=369098752|e},_getOriginH3IndexFromUnidirectionalEdge:function(A,e){var r;return A|=0,k(0|((r=!0&268435456==(2013265920&(e|=0)|0))?-2130706433&e|134217728:0)),0|(r?A:0)},_getPentagonIndexes:NA,_getRes0Indexes:function(A){A|=0;var e=0,r=0,t=0;e=0;do{ye(0|e,0,45),t=134225919|M(),i[(r=A+(e<<3)|0)>>2]=-1,i[r+4>>2]=t,e=e+1|0}while(122!=(0|e))},_h3Distance:function(A,e,r,t){var i,n,o;return r|=0,t|=0,o=I,I=I+32|0,n=o,A=0==(0|$A(A|=0,e|=0,A,e,i=o+12|0))&&0==(0|$A(A,e,r,t,n))?0|hA(i,n):-1,I=o,0|A},_h3GetBaseCell:IA,_h3GetFaces:function A(e,r,t){t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0;n=I,I=I+128|0,h=n+112|0,f=n+96|0,c=n,a=0|Qe(0|(e|=0),0|(r|=0),52),M(),u=15&a,i[h>>2]=u,s=0|Qe(0|e,0|r,45),M(),s&=127;A:do{if(0|S(s)){if(0|u)for(o=1;;){if(!(0==((l=0|ye(7,0,3*(15-o|0)|0))&e|0)&0==((0|M())&r|0))){a=0;break A}if(!(o>>>0>>0))break;o=o+1|0}if(!(1&a))return l=0|ye(u+1|0,0,52),c=0|M()|-15728641&r,A((l|e)&~(h=0|ye(7,0,3*(14-u|0)|0)),c&~(0|M()),t),void(I=n);a=1}else a=0}while(0);YA(e,r,f),a?(mA(f,h,c),l=5):(yA(f,h,c),l=6);A:do{if(0|S(s))if(u)for(o=1;;){if(!(0==((s=0|ye(7,0,3*(15-o|0)|0))&e|0)&0==((0|M())&r|0))){o=8;break A}if(!(o>>>0>>0)){o=20;break}o=o+1|0}else o=20;else o=8}while(0);if(_e(0|t,-1,0|o),a){a=0;do{for(MA(f=c+(a<<4)|0,0|i[h>>2]),f=0|i[f>>2],o=0;!(-1==(0|(u=0|i[(s=t+(o<<2)|0)>>2]))|(0|u)==(0|f));)o=o+1|0;i[s>>2]=f,a=a+1|0}while((0|a)!=(0|l))}else{a=0;do{for(kA(f=c+(a<<4)|0,0|i[h>>2],0,1),f=0|i[f>>2],o=0;!(-1==(0|(u=0|i[(s=t+(o<<2)|0)>>2]))|(0|u)==(0|f));)o=o+1|0;i[s>>2]=f,a=a+1|0}while((0|a)!=(0|l))}I=n},_h3GetResolution:function(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),52),M(),15&e|0},_h3IndexesAreNeighbors:ZA,_h3IsPentagon:UA,_h3IsResClassIII:function(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),52),M(),1&e|0},_h3IsValid:FA,_h3Line:function(A,e,r,t,n){r|=0,t|=0,n|=0;var o,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,Q=0;if(o=I,I=I+48|0,s=o+12|0,M=o,0==(0|$A(A|=0,e|=0,A,e,a=o+24|0))&&0==(0|$A(A,e,r,t,s))){if((0|(k=0|hA(a,s)))<0)return I=o,0|(M=k);for(i[a>>2]=0,i[a+4>>2]=0,i[a+8>>2]=0,i[s>>2]=0,i[s+4>>2]=0,i[s+8>>2]=0,$A(A,e,A,e,a),$A(A,e,r,t,s),gA(a),gA(s),k?(w=+(0|k),m=a,r=c=0|i[a>>2],t=d=0|i[(b=a+4|0)>>2],a=g=0|i[(v=a+8|0)>>2],p=+((0|i[s>>2])-c|0)/w,B=+((0|i[s+4>>2])-d|0)/w,w=+((0|i[s+8>>2])-g|0)/w):(b=t=a+4|0,v=g=a+8|0,m=a,r=0|i[a>>2],t=0|i[t>>2],a=0|i[g>>2],p=0,B=0,w=0),i[M>>2]=r,i[(g=M+4|0)>>2]=t,i[(d=M+8|0)>>2]=a,c=0;;){Q=p*(l=+(0|c))+ +(0|r),u=B*l+ +(0|i[b>>2]),l=w*l+ +(0|i[v>>2]),t=~~+xe(+Q),s=~~+xe(+u),r=~~+xe(+l),Q=+f(+(+(0|t)-Q)),u=+f(+(+(0|s)-u)),l=+f(+(+(0|r)-l));do{if(!(Q>u&Q>l)){if(h=0-t|0,u>l){a=h-r|0;break}a=s,r=h-s|0;break}t=0-(s+r)|0,a=s}while(0);if(i[M>>2]=t,i[g>>2]=a,i[d>>2]=r,wA(M),Ae(A,e,M,n+(c<<3)|0),(0|c)==(0|k))break;c=c+1|0,r=0|i[m>>2]}return I=o,0|(M=0)}return I=o,0|(M=-1)},_h3LineSize:function(A,e,r,t){var i,n,o;return r|=0,t|=0,o=I,I=I+32|0,n=o,A=0==(0|$A(A|=0,e|=0,A,e,i=o+12|0))&&0==(0|$A(A,e,r,t,n))?0|hA(i,n):-1,I=o,(A>>>31^1)+A|0},_h3SetToLinkedGeo:function(A,e,r){r|=0;var t,n,o,a=0;if(o=I,I=I+32|0,t=o,function(A,e,r){A|=0,r|=0;var t,n,o=0,a=0,f=0,s=0,u=0;if(n=I,I=I+176|0,t=n,(0|(e|=0))<1)return se(r,0,0),void(I=n);s=0|Qe(0|i[(s=A)>>2],0|i[s+4>>2],52),M(),se(r,(0|e)>6?e:6,15&s),s=0;do{if(jA(0|i[(o=A+(s<<3)|0)>>2],0|i[o+4>>2],t),(0|(o=0|i[t>>2]))>0){u=0;do{f=t+8+(u<<4)|0,(a=0|de(r,o=t+8+(((0|(u=u+1|0))%(0|o)|0)<<4)|0,f))?he(r,a):ce(r,f,o),o=0|i[t>>2]}while((0|u)<(0|o))}s=s+1|0}while((0|s)!=(0|e));I=n}(A|=0,e|=0,n=o+16|0),i[r>>2]=0,i[r+4>>2]=0,i[r+8>>2]=0,!(A=0|le(n)))return XA(r),ue(n),void(I=o);do{e=0|JA(r);do{KA(e,A),a=A+16|0,i[t>>2]=i[a>>2],i[t+4>>2]=i[a+4>>2],i[t+8>>2]=i[a+8>>2],i[t+12>>2]=i[a+12>>2],he(n,A),A=0|ge(n,t)}while(0!=(0|A));A=0|le(n)}while(0!=(0|A));XA(r),ue(n),I=o},_h3ToCenterChild:function(A,e,r){r|=0;var t=0,i=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(t&=15))<=(0|r)){if((0|t)!=(0|r)&&(A|=i=0|ye(0|r,0,52),e=0|M()|-15728641&e,(0|t)<(0|r)))do{i=0|ye(7,0,3*(14-t|0)|0),t=t+1|0,A&=~i,e&=~(0|M())}while((0|t)<(0|r))}else e=0,A=0;return k(0|e),0|A},_h3ToChildren:PA,_h3ToGeo:OA,_h3ToGeoBoundary:jA,_h3ToParent:CA,_h3UnidirectionalEdgeIsValid:function(A,e){var r=0;if(!(!0&268435456==(2013265920&(e|=0)|0)))return 0|(r=0);switch(r=0|Qe(0|(A|=0),0|e,56),M(),7&r){case 0:case 7:return 0|(r=0)}return!0&16777216==(117440512&e|0)&0!=(0|UA(A,r=-2130706433&e|134217728))?0|(r=0):0|(r=0|FA(A,r))},_hexAreaKm2:function(A){return+ +n[20496+((A|=0)<<3)>>3]},_hexAreaM2:function(A){return+ +n[20624+((A|=0)<<3)>>3]},_hexRing:function(A,e,r,t){A|=0,e|=0,t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0,h=0;if(n=I,I=I+16|0,h=n,!(r|=0))return i[(h=t)>>2]=A,i[h+4>>2]=e,I=n,0|(h=0);i[h>>2]=0;A:do{if(0|UA(A,e))A=1;else{if(a=(0|r)>0){o=0,l=A;do{if(0==(0|(l=0|U(l,e,4,h)))&0==(0|(e=0|M()))){A=2;break A}if(o=o+1|0,0|UA(l,e)){A=1;break A}}while((0|o)<(0|r));if(i[(u=t)>>2]=l,i[u+4>>2]=e,u=r+-1|0,a){a=0,f=1,o=l,A=e;do{if(0==(0|(o=0|U(o,A,2,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(f<<3)|0)>>2]=o,i[s+4>>2]=A,f=f+1|0,0|UA(o,A)){A=1;break A}a=a+1|0}while((0|a)<(0|r));s=0,a=f;do{if(0==(0|(o=0|U(o,A,3,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(f=t+(a<<3)|0)>>2]=o,i[f+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}s=s+1|0}while((0|s)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,1,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,5,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,4,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));for(f=0;;){if(0==(0|(o=0|U(o,A,6,h)))&0==(0|(A=0|M()))){A=2;break A}if((0|f)!=(0|u)){if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,0|UA(o,A)){A=1;break A}a=a+1|0}if((0|(f=f+1|0))>=(0|r)){f=l,a=e;break}}}else f=l,o=l,a=e,A=e}else i[(f=t)>>2]=A,i[f+4>>2]=e,f=A,o=A,a=e,A=e;A=1&((0|f)!=(0|o)|(0|a)!=(0|A))}}while(0);return I=n,0|(h=A)},_i64Subtract:ve,_kRing:F,_kRingDistances:function(A,e,r,t,i){var n;if(0|C(A|=0,e|=0,r|=0,t|=0,i|=0)){if(_e(0|t,0,(n=1+(0|b(3*r|0,r+1|0))|0)<<3|0),0|i)return _e(0|i,0,n<<2|0),void P(A,e,r,t,i,n,0);(i=0|be(n,4))&&(P(A,e,r,t,i,n,0),Be(i))}},_llvm_minnum_f64:Ee,_llvm_round_f64:xe,_malloc:pe,_maxFaceCount:function(A,e){var r=0,t=0;if(t=0|Qe(0|(A|=0),0|(e|=0),45),M(),!(0|S(127&t)))return 0|(t=2);if(t=0|Qe(0|A,0|e,52),M(),!(t&=15))return 0|(t=5);for(r=1;;){if(!(0==((0|ye(7,0,3*(15-r|0)|0))&A|0)&0==((0|M())&e|0))){r=2,A=6;break}if(!(r>>>0>>0)){r=5,A=6;break}r=r+1|0}return 6==(0|A)?0|r:0},_maxH3ToChildrenSize:function(A,e,r){return r|=0,A=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(A&=15))<=(0|r)?0|(r=0|ee(7,r-A|0)):0|(r=0)},_maxKringSize:function(A){return 1+(0|b(3*(A|=0)|0,A+1|0))|0},_maxPolyfillSize:function(A,e){e|=0;var r,t=0,n=0,o=0,a=0,f=0;if(r=I,I=I+48|0,o=r+8|0,n=r,a=0|i[(f=A|=0)+4>>2],i[(t=n)>>2]=i[f>>2],i[t+4>>2]=a,te(n,o),o=0|j(o,e),e=0|i[n>>2],(0|(n=0|i[A+8>>2]))<=0)return I=r,0|(f=(f=(a=(0|o)<(0|(f=e)))?f:o)+12|0);t=0|i[A+12>>2],A=0;do{e=(0|i[t+(A<<3)>>2])+e|0,A=A+1|0}while((0|A)<(0|n));return I=r,0|(f=(f=(f=(0|o)<(0|e))?e:o)+12|0)},_maxUncompactSize:function(A,e,r){A|=0,r|=0;var t=0,n=0,o=0,a=0;if((0|(e|=0))<=0)return 0|(r=0);if((0|r)>=16){for(t=0;;){if(!(0==(0|i[(a=A+(t<<3)|0)>>2])&0==(0|i[a+4>>2]))){t=-1,n=13;break}if((0|(t=t+1|0))>=(0|e)){t=0,n=13;break}}if(13==(0|n))return 0|t}t=0,a=0;A:for(;;){o=0|i[(n=A+(a<<3)|0)>>2],n=0|i[n+4>>2];do{if(!(0==(0|o)&0==(0|n))){if(n=0|Qe(0|o,0|n,52),M(),(0|(n&=15))>(0|r)){t=-1,n=13;break A}if((0|n)==(0|r)){t=t+1|0;break}t=(0|ee(7,r-n|0))+t|0;break}}while(0);if((0|(a=a+1|0))>=(0|e)){n=13;break}}return 13==(0|n)?0|t:0},_memcpy:De,_memset:_e,_numHexagons:function(A){var e;return A=0|i[(e=21008+((A|=0)<<3)|0)>>2],k(0|i[e+4>>2]),0|A},_pentagonIndexCount:function(){return 12},_pointDistKm:DA,_pointDistM:function(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))*6371.007180918475*1e3},_pointDistRads:function(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))},_polyfill:function(A,e,r){var t,n=0,o=0,a=0,f=0,s=0;if(t=I,I=I+48|0,n=t+8|0,o=t,0|function(A,e,r){e|=0,r|=0;var t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,y=0,E=0,x=0,D=0,_=0,F=0,U=0,S=0,T=0,V=0,H=0;H=I,I=I+112|0,U=H+80|0,s=H+72|0,S=H,T=H+56|0,(V=0|pe(32+(i[(u=(A=A|0)+8|0)>>2]<<5)|0))||Q(22848,22448,800,22456);if(ie(A,V),t=0|i[(o=A)+4>>2],i[(f=s)>>2]=i[o>>2],i[f+4>>2]=t,te(s,U),f=0|j(U,e),t=0|i[s>>2],(0|(o=0|i[u>>2]))>0){a=0|i[A+12>>2],n=0;do{t=(0|i[a+(n<<3)>>2])+t|0,n=n+1|0}while((0|n)!=(0|o))}if(n=0|be(F=(f=(0|f)<(0|t)?t:f)+12|0,8),l=0|be(F,8),i[U>>2]=0,_=0|i[(D=A)+4>>2],i[(t=s)>>2]=i[D>>2],i[t+4>>2]=_,0|(t=0|G(s,F,e,U,n,l)))return Be(n),Be(l),Be(V),I=H,0|(V=t);A:do{if((0|i[u>>2])>0){for(o=A+12|0,t=0;a=0|G((0|i[o>>2])+(t<<3)|0,F,e,U,n,l),t=t+1|0,!(0|a);)if((0|t)>=(0|i[u>>2]))break A;return Be(n),Be(l),Be(V),I=H,0|(V=a)}}while(0);(0|f)>-12&&_e(0|l,0,((0|F)>1?F:1)<<3|0);A:do{if((0|i[U>>2])>0){_=((0|F)<0)<<31>>31,m=n,k=l,y=n,E=n,x=l,D=n,t=n,p=n,B=l,b=l,v=l,n=l;e:for(;;){for(w=0|i[U>>2],d=0,g=0,o=0;;){f=(a=S)+56|0;do{i[a>>2]=0,a=a+4|0}while((0|a)<(0|f));if(0|C(s=0|i[(e=m+(d<<3)|0)>>2],e=0|i[e+4>>2],1,S,0)){f=(a=S)+56|0;do{i[a>>2]=0,a=a+4|0}while((0|a)<(0|f));0|(a=0|be(7,4))&&(P(s,e,1,S,a,7,0),Be(a))}c=0;do{l=0|i[(h=S+(c<<3)|0)>>2],h=0|i[h+4>>2];r:do{if(!(0==(0|l)&0==(0|h))){if(s=0|Me(0|l,0|h,0|F,0|_),M(),!(0==(0|(e=0|i[(f=a=r+(s<<3)|0)>>2]))&0==(0|(f=0|i[f+4>>2]))))for(u=0;;){if((0|u)>(0|F))break e;if((0|e)==(0|l)&(0|f)==(0|h))break r;if(0==(0|(e=0|i[(f=a=r+((s=(s+1|0)%(0|F)|0)<<3)|0)>>2]))&0==(0|(f=0|i[f+4>>2])))break;u=u+1|0}0==(0|l)&0==(0|h)||(OA(l,h,T),0|ne(A,V,T)&&(i[(u=a)>>2]=l,i[u+4>>2]=h,i[(u=k+(o<<3)|0)>>2]=l,i[u+4>>2]=h,o=o+1|0))}}while(0);c=c+1|0}while(c>>>0<7);if((0|(g=g+1|0))>=(0|w))break;d=d+1|0}if((0|w)>0&&_e(0|y,0,w<<3|0),i[U>>2]=o,!((0|o)>0))break A;l=n,h=v,c=D,d=b,g=B,w=k,n=p,v=t,b=E,B=y,p=l,t=h,D=x,x=c,E=d,y=g,k=m,m=w}return Be(E),Be(x),Be(V),I=H,0|(V=-1)}t=l}while(0);return Be(V),Be(n),Be(t),I=H,0|(V=0)}(A|=0,e|=0,r|=0)){if(a=0|i[(s=A)+4>>2],i[(f=o)>>2]=i[s>>2],i[f+4>>2]=a,te(o,n),f=0|j(n,e),e=0|i[o>>2],(0|(a=0|i[A+8>>2]))>0){o=0|i[A+12>>2],n=0;do{e=(0|i[o+(n<<3)>>2])+e|0,n=n+1|0}while((0|n)!=(0|a))}(0|(e=(0|f)<(0|e)?e:f))<=-12||_e(0|r,0,8+(((0|(s=e+11|0))>0?s:0)<<3)|0),I=t}else I=t},_res0IndexCount:function(){return 122},_round:Ie,_sbrk:Fe,_sizeOfCoordIJ:function(){return 8},_sizeOfGeoBoundary:function(){return 168},_sizeOfGeoCoord:function(){return 16},_sizeOfGeoPolygon:function(){return 16},_sizeOfGeofence:function(){return 8},_sizeOfH3Index:function(){return 8},_sizeOfLinkedGeoPolygon:function(){return 12},_uncompact:function(A,e,r,t,n){A|=0,r|=0,t|=0,n|=0;var o=0,a=0,f=0,s=0,u=0,l=0;if((0|(e|=0))<=0)return 0|(n=0);if((0|n)>=16){for(o=0;;){if(!(0==(0|i[(l=A+(o<<3)|0)>>2])&0==(0|i[l+4>>2]))){o=14;break}if((0|(o=o+1|0))>=(0|e)){a=0,o=16;break}}if(14==(0|o))return 0|((0|t)>0?-2:-1);if(16==(0|o))return 0|a}o=0,l=0;A:for(;;){a=0|i[(f=u=A+(l<<3)|0)>>2],f=0|i[f+4>>2];do{if(!(0==(0|a)&0==(0|f))){if((0|o)>=(0|t)){a=-1,o=16;break A}if(s=0|Qe(0|a,0|f,52),M(),(0|(s&=15))>(0|n)){a=-2,o=16;break A}if((0|s)==(0|n)){i[(u=r+(o<<3)|0)>>2]=a,i[u+4>>2]=f,o=o+1|0;break}if((0|(a=(0|ee(7,n-s|0))+o|0))>(0|t)){a=-1,o=16;break A}PA(0|i[u>>2],0|i[u+4>>2],n,r+(o<<3)|0),o=a}}while(0);if((0|(l=l+1|0))>=(0|e)){a=0,o=16;break}}return 16==(0|o)?0|a:0},establishStackSpace:function(A,e){I=A|=0},stackAlloc:function(A){var e;return e=I,I=(I=I+(A|=0)|0)+15&-16,0|e},stackRestore:function(A){I=A|=0},stackSave:function(){return 0|I}}}({Math:Math,Int8Array:Int8Array,Int32Array:Int32Array,Uint8Array:Uint8Array,Float32Array:Float32Array,Float64Array:Float64Array},{a:fA,b:function(A){s=A},c:u,d:function(A,e,r,t){fA("Assertion failed: "+g(A)+", at: "+[e?g(e):"unknown filename",r,t?g(t):"unknown function"])},e:function(A){return r.___errno_location&&(v[r.___errno_location()>>2]=A),A},f:N,g:function(A,e,r){B.set(B.subarray(e,e+r),A)},h:function(A){var e=N(),r=16777216,t=2130706432;if(A>t)return!1;for(var i=Math.max(e,16777216);i>0]=e;break;case"i16":b[A>>1]=e;break;case"i32":v[A>>2]=e;break;case"i64":H=[e>>>0,(V=e,+F(V)>=1?V>0?(0|U(+P(V/4294967296),4294967295))>>>0:~~+C((V-+(~~V>>>0))/4294967296)>>>0:0)],v[A>>2]=H[0],v[A+4>>2]=H[1];break;case"float":m[A>>2]=e;break;case"double":k[A>>3]=e;break;default:fA("invalid type for setValue: "+r)}},r.getValue=function(A,e,r){switch("*"===(e=e||"i8").charAt(e.length-1)&&(e="i32"),e){case"i1":case"i8":return p[A>>0];case"i16":return b[A>>1];case"i32":case"i64":return v[A>>2];case"float":return m[A>>2];case"double":return k[A>>3];default:fA("invalid type for getValue: "+e)}return null},r.getTempRet0=u,R){z(R)||(K=R,R=r.locateFile?r.locateFile(K,o):o+K),G++,r.monitorRunDependencies&&r.monitorRunDependencies(G);var tA=function(A){A.byteLength&&(A=new Uint8Array(A)),B.set(A,8),r.memoryInitializerRequest&&delete r.memoryInitializerRequest.response,function(A){if(G--,r.monitorRunDependencies&&r.monitorRunDependencies(G),0==G&&(null!==S&&(clearInterval(S),S=null),T)){var e=T;T=null,e()}}()},iA=function(){i(R,tA,(function(){throw"could not load memory initializer "+R}))},nA=J(R);if(nA)tA(nA.buffer);else if(r.memoryInitializerRequest){var oA=function(){var A=r.memoryInitializerRequest,e=A.response;if(200!==A.status&&0!==A.status){var t=J(r.memoryInitializerRequestURL);if(!t)return console.warn("a problem seems to have happened with Module.memoryInitializerRequest, status: "+A.status+", retrying "+R),void iA();e=t.buffer}tA(e)};r.memoryInitializerRequest.response?setTimeout(oA,0):r.memoryInitializerRequest.addEventListener("load",oA)}else iA()}function aA(A){function e(){X||(X=!0,l||(E(D),E(_),r.onRuntimeInitialized&&r.onRuntimeInitialized(),function(){if(r.postRun)for("function"==typeof r.postRun&&(r.postRun=[r.postRun]);r.postRun.length;)A=r.postRun.shift(),I.unshift(A);var A;E(I)}()))}A=A||n,G>0||(!function(){if(r.preRun)for("function"==typeof r.preRun&&(r.preRun=[r.preRun]);r.preRun.length;)A=r.preRun.shift(),x.unshift(A);var A;E(x)}(),G>0||(r.setStatus?(r.setStatus("Running..."),setTimeout((function(){setTimeout((function(){r.setStatus("")}),1),e()}),1)):e()))}function fA(A){throw r.onAbort&&r.onAbort(A),a(A+=""),f(A),l=!0,"abort("+A+"). Build with -s ASSERTIONS=1 for more info."}if(T=function A(){X||aA(),X||(T=A)},r.run=aA,r.abort=fA,r.preInit)for("function"==typeof r.preInit&&(r.preInit=[r.preInit]);r.preInit.length>0;)r.preInit.pop()();return aA(),A}("object"==typeof t?t:{}),i="number",n={};[["sizeOfH3Index",i],["sizeOfGeoCoord",i],["sizeOfGeoBoundary",i],["sizeOfGeoPolygon",i],["sizeOfGeofence",i],["sizeOfLinkedGeoPolygon",i],["sizeOfCoordIJ",i],["h3IsValid",i,[i,i]],["geoToH3",i,[i,i,i]],["h3ToGeo",null,[i,i,i]],["h3ToGeoBoundary",null,[i,i,i]],["maxKringSize",i,[i]],["kRing",null,[i,i,i,i]],["kRingDistances",null,[i,i,i,i,i]],["hexRing",null,[i,i,i,i]],["maxPolyfillSize",i,[i,i]],["polyfill",null,[i,i,i]],["h3SetToLinkedGeo",null,[i,i,i]],["destroyLinkedPolygon",null,[i]],["compact",i,[i,i,i]],["uncompact",i,[i,i,i,i,i]],["maxUncompactSize",i,[i,i,i]],["h3IsPentagon",i,[i,i]],["h3IsResClassIII",i,[i,i]],["h3GetBaseCell",i,[i,i]],["h3GetResolution",i,[i,i]],["maxFaceCount",i,[i,i]],["h3GetFaces",null,[i,i,i]],["h3ToParent",i,[i,i,i]],["h3ToChildren",null,[i,i,i,i]],["h3ToCenterChild",i,[i,i,i]],["maxH3ToChildrenSize",i,[i,i,i]],["h3IndexesAreNeighbors",i,[i,i,i,i]],["getH3UnidirectionalEdge",i,[i,i,i,i]],["getOriginH3IndexFromUnidirectionalEdge",i,[i,i]],["getDestinationH3IndexFromUnidirectionalEdge",i,[i,i]],["h3UnidirectionalEdgeIsValid",i,[i,i]],["getH3IndexesFromUnidirectionalEdge",null,[i,i,i]],["getH3UnidirectionalEdgesFromHexagon",null,[i,i,i]],["getH3UnidirectionalEdgeBoundary",null,[i,i,i]],["h3Distance",i,[i,i,i,i]],["h3Line",i,[i,i,i,i,i]],["h3LineSize",i,[i,i,i,i]],["experimentalH3ToLocalIj",i,[i,i,i,i,i]],["experimentalLocalIjToH3",i,[i,i,i,i]],["hexAreaM2",i,[i]],["hexAreaKm2",i,[i]],["edgeLengthM",i,[i]],["edgeLengthKm",i,[i]],["pointDistM",i,[i,i]],["pointDistKm",i,[i,i]],["pointDistRads",i,[i,i]],["cellAreaM2",i,[i,i]],["cellAreaKm2",i,[i,i]],["cellAreaRads2",i,[i,i]],["exactEdgeLengthM",i,[i,i]],["exactEdgeLengthKm",i,[i,i]],["exactEdgeLengthRads",i,[i,i]],["numHexagons",i,[i]],["getRes0Indexes",null,[i]],["res0IndexCount",i],["getPentagonIndexes",null,[i,i]],["pentagonIndexCount",i]].forEach((function(A){n[A[0]]=t.cwrap.apply(t,A)}));var o=16,a=n.sizeOfH3Index(),f=n.sizeOfGeoCoord(),s=n.sizeOfGeoBoundary(),u=n.sizeOfGeoPolygon(),l=n.sizeOfGeofence(),h=n.sizeOfLinkedGeoPolygon(),c=n.sizeOfCoordIJ(),d={m:"m",m2:"m2",km:"km",km2:"km2",rads:"rads",rads2:"rads2"};function g(A){if("number"!=typeof A||A<0||A>15||Math.floor(A)!==A)throw new Error("Invalid resolution: "+A)}var w=/[^0-9a-fA-F]/;function p(A){if(Array.isArray(A)&&2===A.length&&Number.isInteger(A[0])&&Number.isInteger(A[1]))return A;if("string"!=typeof A||w.test(A))return[0,0];var e=parseInt(A.substring(0,A.length-8),o);return[parseInt(A.substring(A.length-8),o),e]}function B(A){if(A>=0)return A.toString(o);var e=v(8,(A&=2147483647).toString(o));return e=(parseInt(e[0],o)+8).toString(o)+e.substring(1)}function b(A,e){return B(e)+v(8,B(A))}function v(A,e){for(var r=A-e.length,t="",i=0;i=0&&r.push(n)}return r}(a,o);return t._free(a),f},r.h3GetResolution=function(A){var e=p(A),r=e[0],t=e[1];return n.h3IsValid(r,t)?n.h3GetResolution(r,t):-1},r.geoToH3=function(A,e,r){var i=t._malloc(f);t.HEAPF64.set([A,e].map(U),i/8);var o=M(n.geoToH3(i,r));return t._free(i),o},r.h3ToGeo=function(A){var e=t._malloc(f),r=p(A),i=r[0],o=r[1];n.h3ToGeo(i,o,e);var a=I(e);return t._free(e),a},r.h3ToGeoBoundary=function(A,e){var r=t._malloc(s),i=p(A),o=i[0],a=i[1];n.h3ToGeoBoundary(o,a,r);var f=C(r,e,e);return t._free(r),f},r.h3ToParent=function(A,e){var r=p(A),t=r[0],i=r[1];return M(n.h3ToParent(t,i,e))},r.h3ToChildren=function(A,e){if(!P(A))return[];var r=p(A),i=r[0],o=r[1],f=n.maxH3ToChildrenSize(i,o,e),s=t._calloc(f,a);n.h3ToChildren(i,o,e,s);var u=E(s,f);return t._free(s),u},r.h3ToCenterChild=function(A,e){var r=p(A),t=r[0],i=r[1];return M(n.h3ToCenterChild(t,i,e))},r.kRing=function(A,e){var r=p(A),i=r[0],o=r[1],f=n.maxKringSize(e),s=t._calloc(f,a);n.kRing(i,o,e,s);var u=E(s,f);return t._free(s),u},r.kRingDistances=function(A,e){var r=p(A),i=r[0],o=r[1],f=n.maxKringSize(e),s=t._calloc(f,a),u=t._calloc(f,4);n.kRingDistances(i,o,e,s,u);for(var l=[],h=0;h0){r=t._calloc(i,l);for(var f=0;f0){for(var n=t.getValue(A+r,"i32"),o=0;o */ +r.read=function(A,e,r,t,i){var n,o,a=8*i-t-1,f=(1<>1,u=-7,l=r?i-1:0,h=r?-1:1,c=A[e+l];for(l+=h,n=c&(1<<-u)-1,c>>=-u,u+=a;u>0;n=256*n+A[e+l],l+=h,u-=8);for(o=n&(1<<-u)-1,n>>=-u,u+=t;u>0;o=256*o+A[e+l],l+=h,u-=8);if(0===n)n=1-s;else{if(n===f)return o?NaN:1/0*(c?-1:1);o+=Math.pow(2,t),n-=s}return(c?-1:1)*o*Math.pow(2,n-t)},r.write=function(A,e,r,t,i,n){var o,a,f,s=8*n-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,c=t?0:n-1,d=t?1:-1,g=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=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(f=Math.pow(2,-o))<1&&(o--,f*=2),(e+=o+l>=1?h/f:h*Math.pow(2,1-l))*f>=2&&(o++,f/=2),o+l>=u?(a=0,o=u):o+l>=1?(a=(e*f-1)*Math.pow(2,i),o+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),o=0));i>=8;A[r+c]=255&a,c+=d,a/=256,i-=8);for(o=o<0;A[r+c]=255&o,c+=d,o/=256,s-=8);A[r+c-d]|=128*g}},{}],9:[function(A,e,r){"use strict";e.exports=i;var t=A("ieee754");function i(A){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(A)?A:new Uint8Array(A||0),this.pos=0,this.type=0,this.length=this.buf.length}i.Varint=0,i.Fixed64=1,i.Bytes=2,i.Fixed32=5;var n=4294967296,o=1/n,a="undefined"==typeof TextDecoder?null:new TextDecoder("utf8");function f(A){return A.type===i.Bytes?A.readVarint()+A.pos:A.pos+1}function s(A,e,r){return r?4294967296*e+(A>>>0):4294967296*(e>>>0)+(A>>>0)}function u(A,e,r){var t=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(t);for(var i=r.pos-1;i>=A;i--)r.buf[i+t]=r.buf[i]}function l(A,e){for(var r=0;r>>8,A[r+2]=e>>>16,A[r+3]=e>>>24}function k(A,e){return(A[e]|A[e+1]<<8|A[e+2]<<16)+(A[e+3]<<24)}i.prototype={destroy:function(){this.buf=null},readFields:function(A,e,r){for(r=r||this.length;this.pos>3,n=this.pos;this.type=7&t,A(i,e,this),this.pos===n&&this.skip(t)}return e},readMessage:function(A,e){return this.readFields(A,e,this.readVarint()+this.pos)},readFixed32:function(){var A=v(this.buf,this.pos);return this.pos+=4,A},readSFixed32:function(){var A=k(this.buf,this.pos);return this.pos+=4,A},readFixed64:function(){var A=v(this.buf,this.pos)+v(this.buf,this.pos+4)*n;return this.pos+=8,A},readSFixed64:function(){var A=v(this.buf,this.pos)+k(this.buf,this.pos+4)*n;return this.pos+=8,A},readFloat:function(){var A=t.read(this.buf,this.pos,!0,23,4);return this.pos+=4,A},readDouble:function(){var A=t.read(this.buf,this.pos,!0,52,8);return this.pos+=8,A},readVarint:function(A){var e,r,t=this.buf;return e=127&(r=t[this.pos++]),r<128?e:(e|=(127&(r=t[this.pos++]))<<7,r<128?e:(e|=(127&(r=t[this.pos++]))<<14,r<128?e:(e|=(127&(r=t[this.pos++]))<<21,r<128?e:function(A,e,r){var t,i,n=r.buf;if(i=n[r.pos++],t=(112&i)>>4,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<3,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<10,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<17,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<24,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(1&i)<<31,i<128)return s(A,t,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=t[this.pos]))<<28,A,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var A=this.readVarint();return A%2==1?(A+1)/-2:A/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var A=this.readVarint()+this.pos,e=this.pos;return this.pos=A,A-e>=12&&a?function(A,e,r){return a.decode(A.subarray(e,r))}(this.buf,e,A):function(A,e,r){var t="",i=e;for(;i239?4:f>223?3:f>191?2:1;if(i+u>r)break;1===u?f<128&&(s=f):2===u?128==(192&(n=A[i+1]))&&(s=(31&f)<<6|63&n)<=127&&(s=null):3===u?(n=A[i+1],o=A[i+2],128==(192&n)&&128==(192&o)&&((s=(15&f)<<12|(63&n)<<6|63&o)<=2047||s>=55296&&s<=57343)&&(s=null)):4===u&&(n=A[i+1],o=A[i+2],a=A[i+3],128==(192&n)&&128==(192&o)&&128==(192&a)&&((s=(15&f)<<18|(63&n)<<12|(63&o)<<6|63&a)<=65535||s>=1114112)&&(s=null)),null===s?(s=65533,u=1):s>65535&&(s-=65536,t+=String.fromCharCode(s>>>10&1023|55296),s=56320|1023&s),t+=String.fromCharCode(s),i+=u}return t}(this.buf,e,A)},readBytes:function(){var A=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,A);return this.pos=A,e},readPackedVarint:function(A,e){if(this.type!==i.Bytes)return A.push(this.readVarint(e));var r=f(this);for(A=A||[];this.pos127;);else if(e===i.Bytes)this.pos=this.readVarint()+this.pos;else if(e===i.Fixed32)this.pos+=4;else{if(e!==i.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(A,e){this.writeVarint(A<<3|e)},realloc:function(A){for(var e=this.length||16;e268435455||A<0?function(A,e){var r,t;A>=0?(r=A%4294967296|0,t=A/4294967296|0):(t=~(-A/4294967296),4294967295^(r=~(-A%4294967296))?r=r+1|0:(r=0,t=t+1|0));if(A>=0x10000000000000000||A<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(A,e,r){r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos]=127&A}(r,0,e),function(A,e){var r=(7&A)<<4;if(e.buf[e.pos++]|=r|((A>>>=3)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;e.buf[e.pos++]=127&A}(t,e)}(A,this):(this.realloc(4),this.buf[this.pos++]=127&A|(A>127?128:0),A<=127||(this.buf[this.pos++]=127&(A>>>=7)|(A>127?128:0),A<=127||(this.buf[this.pos++]=127&(A>>>=7)|(A>127?128:0),A<=127||(this.buf[this.pos++]=A>>>7&127))))},writeSVarint:function(A){this.writeVarint(A<0?2*-A-1:2*A)},writeBoolean:function(A){this.writeVarint(Boolean(A))},writeString:function(A){A=String(A),this.realloc(4*A.length),this.pos++;var e=this.pos;this.pos=function(A,e,r){for(var t,i,n=0;n55295&&t<57344){if(!i){t>56319||n+1===e.length?(A[r++]=239,A[r++]=191,A[r++]=189):i=t;continue}if(t<56320){A[r++]=239,A[r++]=191,A[r++]=189,i=t;continue}t=i-55296<<10|t-56320|65536,i=null}else i&&(A[r++]=239,A[r++]=191,A[r++]=189,i=null);t<128?A[r++]=t:(t<2048?A[r++]=t>>6|192:(t<65536?A[r++]=t>>12|224:(A[r++]=t>>18|240,A[r++]=t>>12&63|128),A[r++]=t>>6&63|128),A[r++]=63&t|128)}return r}(this.buf,A,this.pos);var r=this.pos-e;r>=128&&u(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r},writeFloat:function(A){this.realloc(4),t.write(this.buf,A,this.pos,!0,23,4),this.pos+=4},writeDouble:function(A){this.realloc(8),t.write(this.buf,A,this.pos,!0,52,8),this.pos+=8},writeBytes:function(A){var e=A.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&u(r,t,this),this.pos=r-1,this.writeVarint(t),this.pos+=t},writeMessage:function(A,e,r){this.writeTag(A,i.Bytes),this.writeRawMessage(e,r)},writePackedVarint:function(A,e){e.length&&this.writeMessage(A,l,e)},writePackedSVarint:function(A,e){e.length&&this.writeMessage(A,h,e)},writePackedBoolean:function(A,e){e.length&&this.writeMessage(A,g,e)},writePackedFloat:function(A,e){e.length&&this.writeMessage(A,c,e)},writePackedDouble:function(A,e){e.length&&this.writeMessage(A,d,e)},writePackedFixed32:function(A,e){e.length&&this.writeMessage(A,w,e)},writePackedSFixed32:function(A,e){e.length&&this.writeMessage(A,p,e)},writePackedFixed64:function(A,e){e.length&&this.writeMessage(A,B,e)},writePackedSFixed64:function(A,e){e.length&&this.writeMessage(A,b,e)},writeBytesField:function(A,e){this.writeTag(A,i.Bytes),this.writeBytes(e)},writeFixed32Field:function(A,e){this.writeTag(A,i.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(A,e){this.writeTag(A,i.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(A,e){this.writeTag(A,i.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(A,e){this.writeTag(A,i.Fixed64),this.writeSFixed64(e)},writeVarintField:function(A,e){this.writeTag(A,i.Varint),this.writeVarint(e)},writeSVarintField:function(A,e){this.writeTag(A,i.Varint),this.writeSVarint(e)},writeStringField:function(A,e){this.writeTag(A,i.Bytes),this.writeString(e)},writeFloatField:function(A,e){this.writeTag(A,i.Fixed32),this.writeFloat(e)},writeDoubleField:function(A,e){this.writeTag(A,i.Fixed64),this.writeDouble(e)},writeBooleanField:function(A,e){this.writeVarintField(A,Boolean(e))}}},{ieee754:8}],10:[function(A,e,r){var t=A("pbf"),i=A("./lib/geojson_wrapper");function n(A){var e=new t;return function(A,e){for(var r in A.layers)e.writeMessage(3,o,A.layers[r])}(A,e),e.finish()}function o(A,e){var r;e.writeVarintField(15,A.version||1),e.writeStringField(1,A.name||""),e.writeVarintField(5,A.extent||4096);var t={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r>31}function l(A,e){for(var r=A.loadGeometry(),t=A.type,i=0,n=0,o=r.length,a=0;anew Promise(((r,t)=>{var i;r((i=e,{type:"FeatureCollection",features:A.cells.map((A=>{const e={properties:A,geometry:{type:i.geometry_type,coordinates:i.generate(A.h3id)}};return i.promoteID||(e.id=parseInt(A.h3id,16)),e}))}))})),a=A=>{const e=["type","data","maxzoom","attribution","buffer","filter","tolerance","cluster","clusterRadius","clusterMaxZoom","clusterMinPoints","clusterProperties","lineMetrics","generateId","promoteId"];return f(A,((A,r)=>e.includes(A)))},f=(A,e)=>Object.fromEntries(Object.entries(A).filter((([A,r])=>e(A,r))));t.Map.prototype.addH3TSource=function(A,e){const r=Object.assign({},n,e,{type:"vector",format:"pbf"});r.generate=A=>"Polygon"===r.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),r.promoteId&&(r.promoteId="h3id"),t.addProtocol("h3tiles",((A,e)=>{const t=`http${!1===r.https?"":"s"}://${A.url.split("://")[1]}`,n=A.url.split(/\/|\./i),a=n.length,f=n.slice(a-4,a-1).map((A=>1*A)),s=new AbortController,u=s.signal;let l;r.timeout>0&&setTimeout((()=>s.abort()),r.timeout),fetch(t,{signal:u}).then((A=>{if(A.ok)return l=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,r))).then((A=>{const t=i.tovt(A).getTile(...f),n={};n[r.sourcelayer]=t;const o=i.topbf.fromGeojsonVt(n,{version:2});r.debug&&console.log(`${f}: ${A.features.length} features, ${(performance.now()-l).toFixed(0)} ms`),e(null,o,null,null)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Tile .../${f.join("/")}.h3t is taking too long to fetch`),e(new Error(A))}))})),this.addSource(A,(A=>{const e=["type","url","tiles","bounds","scheme","minzoom","maxzoom","attribution","promoteId","volatile"];return f(A,((A,r)=>e.includes(A)))})(r))};t.Map.prototype.addH3JSource=function(A,e){const r=new AbortController,t=r.signal,f=Object.assign({},n,e,{type:"geojson"});let s;if(f.generate=A=>"Polygon"===f.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),f.promoteId&&(f.promoteId="h3id"),f.timeout>0&&setTimeout((()=>r.abort()),f.timeout),"string"==typeof f.data)return f.timeout>0&&setTimeout((()=>r.abort()),f.timeout),new Promise(((e,r)=>{fetch(f.data,{signal:t}).then((A=>{if(A.ok)return s=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,f))).then((r=>{f.data=r,this.addSource(A,a(f)),f.debug&&console.log(`${r.features.length} features, ${(performance.now()-s).toFixed(0)} ms`),e(this)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Source file ${f.data} is taking too long to fetch`),console.error(A.message)}))}));o(f.data,f).then((e=>(f.data=e,this.addSource(A,a(f)),new Promise(((A,e)=>A(this))))))};t.Map.prototype.setH3JData=function(A,e,r){const t=Object.assign({},n,r);t.generate=A=>"Polygon"===t.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),t.promoteId&&(t.promoteId="h3id");const a=new AbortController,f=a.signal,s=this.getSource(A);let u;"string"==typeof e?(t.timeout>0&&setTimeout((()=>a.abort()),t.timeout),fetch(e,{signal:f}).then((A=>{if(A.ok)return u=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,t))).then((A=>{s.setData(A),t.debug&&console.log(`${A.features.length} features, ${(performance.now()-u).toFixed(0)} ms`)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Data file ${e} is taking too long to fetch`),console.error(A.message)}))):o(e,t).then((A=>s.setData(A)))}},{"geojson-vt":6,"h3-js":7,"vt-pbf":10}]},{},[12])(12)})); \ No newline at end of file diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css b/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css new file mode 100644 index 0000000..0347a27 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css @@ -0,0 +1,88 @@ + +/* Override default control style */ +.mapbox-gl-draw_ctrl-bottom-left, +.mapbox-gl-draw_ctrl-top-left { + margin-left:0; + border-radius:0 4px 4px 0; +} +.mapbox-gl-draw_ctrl-top-right, +.mapbox-gl-draw_ctrl-bottom-right { + margin-right:0; + border-radius:4px 0 0 4px; +} + +.mapbox-gl-draw_ctrl-draw-btn { + border-color:rgba(0,0,0,0.9); + color:rgba(255,255,255,0.5); + width:30px; + height:30px; +} + +.mapbox-gl-draw_ctrl-draw-btn.active, +.mapbox-gl-draw_ctrl-draw-btn.active:hover { + background-color:rgb(0 0 0/5%); +} +.mapbox-gl-draw_ctrl-draw-btn { + background-repeat: no-repeat; + background-position: center; +} + +.mapbox-gl-draw_point { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m10 2c-3.3 0-6 2.7-6 6s6 9 6 9 6-5.7 6-9-2.7-6-6-6zm0 2c2.1 0 3.8 1.7 3.8 3.8 0 1.5-1.8 3.9-2.9 5.2h-1.7c-1.1-1.4-2.9-3.8-2.9-5.2-.1-2.1 1.6-3.8 3.7-3.8z"/>%3C/svg>'); +} +.mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m15 12.3v-4.6c.6-.3 1-1 1-1.7 0-1.1-.9-2-2-2-.7 0-1.4.4-1.7 1h-4.6c-.3-.6-1-1-1.7-1-1.1 0-2 .9-2 2 0 .7.4 1.4 1 1.7v4.6c-.6.3-1 1-1 1.7 0 1.1.9 2 2 2 .7 0 1.4-.4 1.7-1h4.6c.3.6 1 1 1.7 1 1.1 0 2-.9 2-2 0-.7-.4-1.4-1-1.7zm-8-.3v-4l1-1h4l1 1v4l-1 1h-4z"/>%3C/svg>'); +} +.mapbox-gl-draw_line { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m13.5 3.5c-1.4 0-2.5 1.1-2.5 2.5 0 .3 0 .6.2.9l-3.8 3.8c-.3-.1-.6-.2-.9-.2-1.4 0-2.5 1.1-2.5 2.5s1.1 2.5 2.5 2.5 2.5-1.1 2.5-2.5c0-.3 0-.6-.2-.9l3.8-3.8c.3.1.6.2.9.2 1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5z"/>%3C/svg>'); +} +.mapbox-gl-draw_trash { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="M10,3.4 c-0.8,0-1.5,0.5-1.8,1.2H5l-1,1v1h12v-1l-1-1h-3.2C11.5,3.9,10.8,3.4,10,3.4z M5,8v7c0,1,1,2,2,2h6c1,0,2-1,2-2V8h-2v5.5h-1.5V8h-3 v5.5H7V8H5z"/>%3C/svg>'); +} +.mapbox-gl-draw_uncombine { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m12 2c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l1 1c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-1-1c-.2-.2-.4-.3-.7-.3zm4 4c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l1 1c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-1-1c-.2-.2-.4-.3-.7-.3zm-7 1c-1 0-1 1-.5 1.5.3.3 1 1 1 1l-1 1s-.5.5 0 1 1 0 1 0l1-1 1 1c.5.5 1.5.5 1.5-.5v-4zm-5 3c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l4.9 4.9c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-4.9-4.9c-.1-.2-.4-.3-.7-.3z"/>%3C/svg>'); +} +.mapbox-gl-draw_combine { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="M12.1,2c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l4.9,4.9c0.4,0.4,1,0.4,1.4,0l1-1 c0.4-0.4,0.4-1,0-1.4l-4.9-4.9C12.6,2.1,12.3,2,12.1,2z M8,8C7,8,7,9,7.5,9.5c0.3,0.3,1,1,1,1l-1,1c0,0-0.5,0.5,0,1s1,0,1,0l1-1l1,1 C11,13,12,13,12,12V8H8z M4,10c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l1,1c0.4,0.4,1,0.4,1.4,0l1-1c0.4-0.4,0.4-1,0-1.4 l-1-1C4.5,10.1,4.3,10,4,10z M8,14c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l1,1c0.4,0.4,1,0.4,1.4,0l1-1 c0.4-0.4,0.4-1,0-1.4l-1-1C8.5,14.1,8.3,14,8,14z"/>%3C/svg>'); +} + +.mapboxgl-map.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: pointer; +} +.mapboxgl-map.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mouse-add .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: crosshair; +} +.mapboxgl-map.mouse-move.mode-direct_select .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: grab; + cursor: -moz-grab; + cursor: -webkit-grab; +} +.mapboxgl-map.mode-direct_select.feature-vertex.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mode-direct_select.feature-midpoint.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: cell; +} +.mapboxgl-map.mode-direct_select.feature-feature.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mode-static.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: grab; + cursor: -moz-grab; + cursor: -webkit-grab; +} + +.mapbox-gl-draw_boxselect { + pointer-events: none; + position: absolute; + top: 0; + left: 0; + width: 0; + height: 0; + background: rgba(0,0,0,.1); + border: 2px dotted #fff; + opacity: 0.5; +} diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js new file mode 100644 index 0000000..271f1f7 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js @@ -0,0 +1,2 @@ +var e,t;e=this,t=function(){const e=function(e,t){const o={drag:[],click:[],mousemove:[],mousedown:[],mouseup:[],mouseout:[],keydown:[],keyup:[],touchstart:[],touchmove:[],touchend:[],tap:[]},n={on(e,t,n){if(void 0===o[e])throw new Error(`Invalid event type: ${e}`);o[e].push({selector:t,fn:n})},render(e){t.store.featureChanged(e)}},r=function(e,r){const i=o[e];let s=i.length;for(;s--;){const e=i[s];if(e.selector(r)){e.fn.call(n,r)||t.store.render(),t.ui.updateMapClasses();break}}};return e.start.call(n),{render:e.render,stop(){e.stop&&e.stop()},trash(){e.trash&&(e.trash(),t.store.render())},combineFeatures(){e.combineFeatures&&e.combineFeatures()},uncombineFeatures(){e.uncombineFeatures&&e.uncombineFeatures()},drag(e){r("drag",e)},click(e){r("click",e)},mousemove(e){r("mousemove",e)},mousedown(e){r("mousedown",e)},mouseup(e){r("mouseup",e)},mouseout(e){r("mouseout",e)},keydown(e){r("keydown",e)},keyup(e){r("keyup",e)},touchstart(e){r("touchstart",e)},touchmove(e){r("touchmove",e)},touchend(e){r("touchend",e)},tap(e){r("tap",e)}}};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var o,n,r={},i={};function s(){return o||(o=1,i.RADIUS=6378137,i.FLATTENING=1/298.257223563,i.POLAR_RADIUS=6356752.3142),i}var a=function(){if(n)return r;n=1;var e=s();function t(e){var t=0;if(e&&e.length>0){t+=Math.abs(o(e[0]));for(var n=1;n2){for(c=0;c(e.geometry.type===h.POLYGON&&(e.area=c.geometry({type:h.FEATURE,property:{},geometry:e.geometry})),e))).sort(S).map((e=>(delete e.area,e)))}function L(e,t=0){return[[e.point.x-t,e.point.y-t],[e.point.x+t,e.point.y+t]]}function M(e){if(this._items={},this._nums={},this._length=e?e.length:0,e)for(let t=0,o=e.length;t{e.push({k:t,v:this._items[t]})})),Object.keys(this._nums).forEach((t=>{e.push({k:JSON.parse(t),v:this._nums[t]})})),e.sort(((e,t)=>e.v-t.v)).map((e=>e.k))},M.prototype.clear=function(){return this._length=0,this._items={},this._nums={},this};const N=[y.FEATURE,y.MIDPOINT,y.VERTEX];var b={click:function(e,t,o){return x(e,t,o,o.options.clickBuffer)},touch:function(e,t,o){return x(e,t,o,o.options.touchBuffer)}};function x(e,t,o,n){if(null===o.map)return[];const r=e?L(e,n):t,i={};o.options.styles&&(i.layers=o.options.styles.map((e=>e.id)).filter((e=>null!=o.map.getLayer(e))));const s=o.map.queryRenderedFeatures(r,i).filter((e=>-1!==N.indexOf(e.properties.meta))),a=new M,c=[];return s.forEach((e=>{const t=e.properties.id;a.has(t)||(a.add(t),c.push(e))})),O(c)}function A(e,t){const o=b.click(e,null,t),n={mouse:d.NONE};return o[0]&&(n.mouse=o[0].properties.active===E.ACTIVE?d.MOVE:d.POINTER,n.feature=o[0].properties.meta),-1!==t.events.currentModeName().indexOf("draw")&&(n.mouse=d.ADD),t.ui.queueMapClasses(n),t.ui.updateMapClasses(),o[0]}function P(e,t){const o=e.x-t.x,n=e.y-t.y;return Math.sqrt(o*o+n*n)}const F=4,R=12,w=500;function D(e,t,o={}){const n=null!=o.fineTolerance?o.fineTolerance:F,r=null!=o.grossTolerance?o.grossTolerance:R,i=null!=o.interval?o.interval:w;e.point=e.point||t.point,e.time=e.time||t.time;const s=P(e.point,t.point);return s(o=t)=>{let n="",r=0|o;for(;r--;)n+=e[Math.random()*e.length|0];return n})("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",32);function B(){return G()}const j=function(e,t){this.ctx=e,this.properties=t.properties||{},this.coordinates=t.geometry.coordinates,this.id=t.id||B(),this.type=t.geometry.type};j.prototype.changed=function(){this.ctx.store.featureChanged(this.id)},j.prototype.incomingCoords=function(e){this.setCoordinates(e)},j.prototype.setCoordinates=function(e){this.coordinates=e,this.changed()},j.prototype.getCoordinates=function(){return JSON.parse(JSON.stringify(this.coordinates))},j.prototype.setProperty=function(e,t){this.properties[e]=t},j.prototype.toGeoJSON=function(){return JSON.parse(JSON.stringify({id:this.id,type:h.FEATURE,properties:this.properties,geometry:{coordinates:this.getCoordinates(),type:this.type}}))},j.prototype.internal=function(e){const t={id:this.id,meta:y.FEATURE,"meta:type":this.type,active:E.INACTIVE,mode:e};if(this.ctx.options.userProperties)for(const e in this.properties)t[`user_${e}`]=this.properties[e];return{type:h.FEATURE,properties:t,geometry:{coordinates:this.getCoordinates(),type:this.type}}};const J=function(e,t){j.call(this,e,t)};(J.prototype=Object.create(j.prototype)).isValid=function(){return"number"==typeof this.coordinates[0]&&"number"==typeof this.coordinates[1]},J.prototype.updateCoordinate=function(e,t,o){this.coordinates=3===arguments.length?[t,o]:[e,t],this.changed()},J.prototype.getCoordinate=function(){return this.getCoordinates()};const $=function(e,t){j.call(this,e,t)};($.prototype=Object.create(j.prototype)).isValid=function(){return this.coordinates.length>1},$.prototype.addCoordinate=function(e,t,o){this.changed();const n=parseInt(e,10);this.coordinates.splice(n,0,[t,o])},$.prototype.getCoordinate=function(e){const t=parseInt(e,10);return JSON.parse(JSON.stringify(this.coordinates[t]))},$.prototype.removeCoordinate=function(e){this.changed(),this.coordinates.splice(parseInt(e,10),1)},$.prototype.updateCoordinate=function(e,t,o){const n=parseInt(e,10);this.coordinates[n]=[t,o],this.changed()};const Y=function(e,t){j.call(this,e,t),this.coordinates=this.coordinates.map((e=>e.slice(0,-1)))};(Y.prototype=Object.create(j.prototype)).isValid=function(){return 0!==this.coordinates.length&&this.coordinates.every((e=>e.length>2))},Y.prototype.incomingCoords=function(e){this.coordinates=e.map((e=>e.slice(0,-1))),this.changed()},Y.prototype.setCoordinates=function(e){this.coordinates=e,this.changed()},Y.prototype.addCoordinate=function(e,t,o){this.changed();const n=e.split(".").map((e=>parseInt(e,10)));this.coordinates[n[0]].splice(n[1],0,[t,o])},Y.prototype.removeCoordinate=function(e){this.changed();const t=e.split(".").map((e=>parseInt(e,10))),o=this.coordinates[t[0]];o&&(o.splice(t[1],1),o.length<3&&this.coordinates.splice(t[0],1))},Y.prototype.getCoordinate=function(e){const t=e.split(".").map((e=>parseInt(e,10))),o=this.coordinates[t[0]];return JSON.parse(JSON.stringify(o[t[1]]))},Y.prototype.getCoordinates=function(){return this.coordinates.map((e=>e.concat([e[0]])))},Y.prototype.updateCoordinate=function(e,t,o){this.changed();const n=e.split("."),r=parseInt(n[0],10),i=parseInt(n[1],10);void 0===this.coordinates[r]&&(this.coordinates[r]=[]),this.coordinates[r][i]=[t,o]};const H={MultiPoint:J,MultiLineString:$,MultiPolygon:Y},X=(e,t,o,n,r)=>{const i=o.split("."),s=parseInt(i[0],10),a=i[1]?i.slice(1).join("."):null;return e[s][t](a,n,r)},q=function(e,t){if(j.call(this,e,t),delete this.coordinates,this.model=H[t.geometry.type],void 0===this.model)throw new TypeError(`${t.geometry.type} is not a valid type`);this.features=this._coordinatesToFeatures(t.geometry.coordinates)};function Z(e){this.map=e.map,this.drawConfig=JSON.parse(JSON.stringify(e.options||{})),this._ctx=e}(q.prototype=Object.create(j.prototype))._coordinatesToFeatures=function(e){const t=this.model.bind(this);return e.map((e=>new t(this.ctx,{id:B(),type:h.FEATURE,properties:{},geometry:{coordinates:e,type:this.type.replace("Multi","")}})))},q.prototype.isValid=function(){return this.features.every((e=>e.isValid()))},q.prototype.setCoordinates=function(e){this.features=this._coordinatesToFeatures(e),this.changed()},q.prototype.getCoordinate=function(e){return X(this.features,"getCoordinate",e)},q.prototype.getCoordinates=function(){return JSON.parse(JSON.stringify(this.features.map((e=>e.type===h.POLYGON?e.getCoordinates():e.coordinates))))},q.prototype.updateCoordinate=function(e,t,o){X(this.features,"updateCoordinate",e,t,o),this.changed()},q.prototype.addCoordinate=function(e,t,o){X(this.features,"addCoordinate",e,t,o),this.changed()},q.prototype.removeCoordinate=function(e){X(this.features,"removeCoordinate",e),this.changed()},q.prototype.getFeatures=function(){return this.features},Z.prototype.setSelected=function(e){return this._ctx.store.setSelected(e)},Z.prototype.setSelectedCoordinates=function(e){this._ctx.store.setSelectedCoordinates(e),e.reduce(((e,t)=>(void 0===e[t.feature_id]&&(e[t.feature_id]=!0,this._ctx.store.get(t.feature_id).changed()),e)),{})},Z.prototype.getSelected=function(){return this._ctx.store.getSelected()},Z.prototype.getSelectedIds=function(){return this._ctx.store.getSelectedIds()},Z.prototype.isSelected=function(e){return this._ctx.store.isSelected(e)},Z.prototype.getFeature=function(e){return this._ctx.store.get(e)},Z.prototype.select=function(e){return this._ctx.store.select(e)},Z.prototype.deselect=function(e){return this._ctx.store.deselect(e)},Z.prototype.deleteFeature=function(e,t={}){return this._ctx.store.delete(e,t)},Z.prototype.addFeature=function(e,t={}){return this._ctx.store.add(e,t)},Z.prototype.clearSelectedFeatures=function(){return this._ctx.store.clearSelected()},Z.prototype.clearSelectedCoordinates=function(){return this._ctx.store.clearSelectedCoordinates()},Z.prototype.setActionableState=function(e={}){const t={trash:e.trash||!1,combineFeatures:e.combineFeatures||!1,uncombineFeatures:e.uncombineFeatures||!1};return this._ctx.events.actionable(t)},Z.prototype.changeMode=function(e,t={},o={}){return this._ctx.events.changeMode(e,t,o)},Z.prototype.fire=function(e,t){return this._ctx.events.fire(e,t)},Z.prototype.updateUIClasses=function(e){return this._ctx.ui.queueMapClasses(e)},Z.prototype.activateUIButton=function(e){return this._ctx.ui.setActiveButton(e)},Z.prototype.featuresAt=function(e,t,o="click"){if("click"!==o&&"touch"!==o)throw new Error("invalid buffer type");return b[o](e,t,this._ctx)},Z.prototype.newFeature=function(e){const t=e.geometry.type;return t===h.POINT?new J(this._ctx,e):t===h.LINE_STRING?new $(this._ctx,e):t===h.POLYGON?new Y(this._ctx,e):new q(this._ctx,e)},Z.prototype.isInstanceOf=function(e,t){if(e===h.POINT)return t instanceof J;if(e===h.LINE_STRING)return t instanceof $;if(e===h.POLYGON)return t instanceof Y;if("MultiFeature"===e)return t instanceof q;throw new Error(`Unknown feature class: ${e}`)},Z.prototype.doRender=function(e){return this._ctx.store.featureChanged(e)},Z.prototype.onSetup=function(){},Z.prototype.onDrag=function(){},Z.prototype.onClick=function(){},Z.prototype.onMouseMove=function(){},Z.prototype.onMouseDown=function(){},Z.prototype.onMouseUp=function(){},Z.prototype.onMouseOut=function(){},Z.prototype.onKeyUp=function(){},Z.prototype.onKeyDown=function(){},Z.prototype.onTouchStart=function(){},Z.prototype.onTouchMove=function(){},Z.prototype.onTouchEnd=function(){},Z.prototype.onTap=function(){},Z.prototype.onStop=function(){},Z.prototype.onTrash=function(){},Z.prototype.onCombineFeature=function(){},Z.prototype.onUncombineFeature=function(){},Z.prototype.toDisplayFeatures=function(){throw new Error("You must overwrite toDisplayFeatures")};const W={drag:"onDrag",click:"onClick",mousemove:"onMouseMove",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseout:"onMouseOut",keyup:"onKeyUp",keydown:"onKeyDown",touchstart:"onTouchStart",touchmove:"onTouchMove",touchend:"onTouchEnd",tap:"onTap"},K=Object.keys(W);function z(e){const t=Object.keys(e);return function(o,n={}){let r={};const i=t.reduce(((t,o)=>(t[o]=e[o],t)),new Z(o));return{start(){r=i.onSetup(n),K.forEach((t=>{const o=W[t];let n=()=>!1;var s;e[o]&&(n=()=>!0),this.on(t,n,(s=o,e=>i[s](r,e)))}))},stop(){i.onStop(r)},trash(){i.onTrash(r)},combineFeatures(){i.onCombineFeatures(r)},uncombineFeatures(){i.onUncombineFeatures(r)},render(e,t){i.toDisplayFeatures(r,e,t)}}}}function Q(e){return[].concat(e).filter((e=>void 0!==e))}function ee(){const e=this;if(!e.ctx.map||void 0===e.ctx.map.getSource(l.HOT))return a();const t=e.ctx.events.currentModeName();e.ctx.ui.queueMapClasses({mode:t});let o=[],n=[];e.isDirty?n=e.getAllIds():(o=e.getChangedIds().filter((t=>void 0!==e.get(t))),n=e.sources.hot.filter((t=>t.properties.id&&-1===o.indexOf(t.properties.id)&&void 0!==e.get(t.properties.id))).map((e=>e.properties.id))),e.sources.hot=[];const r=e.sources.cold.length;e.sources.cold=e.isDirty?[]:e.sources.cold.filter((e=>{const t=e.properties.id||e.properties.parent;return-1===o.indexOf(t)}));const i=r!==e.sources.cold.length||n.length>0;function s(o,n){const r=e.get(o).internal(t);e.ctx.events.currentModeRender(r,(o=>{o.properties.mode=t,e.sources[n].push(o)}))}function a(){e.isDirty=!1,e.clearChangedIds()}o.forEach((e=>s(e,"hot"))),n.forEach((e=>s(e,"cold"))),i&&e.ctx.map.getSource(l.COLD).setData({type:h.FEATURE_COLLECTION,features:e.sources.cold}),e.ctx.map.getSource(l.HOT).setData({type:h.FEATURE_COLLECTION,features:e.sources.hot}),a()}function te(e){let t;this._features={},this._featureIds=new M,this._selectedFeatureIds=new M,this._selectedCoordinates=[],this._changedFeatureIds=new M,this._emitSelectionChange=!1,this._mapInitialConfig={},this.ctx=e,this.sources={hot:[],cold:[]},this.render=()=>{t||(t=requestAnimationFrame((()=>{t=null,ee.call(this),this._emitSelectionChange&&(this.ctx.events.fire(g.SELECTION_CHANGE,{features:this.getSelected().map((e=>e.toGeoJSON())),points:this.getSelectedCoordinates().map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e.coordinates}})))}),this._emitSelectionChange=!1),this.ctx.events.fire(g.RENDER,{})})))},this.isDirty=!1}function oe(e,t={}){const o=e._selectedCoordinates.filter((t=>e._selectedFeatureIds.has(t.feature_id)));e._selectedCoordinates.length===o.length||t.silent||(e._emitSelectionChange=!0),e._selectedCoordinates=o}te.prototype.createRenderBatch=function(){const e=this.render;let t=0;return this.render=function(){t++},()=>{this.render=e,t>0&&this.render()}},te.prototype.setDirty=function(){return this.isDirty=!0,this},te.prototype.featureCreated=function(e,t={}){if(this._changedFeatureIds.add(e),!0!==(null!=t.silent?t.silent:this.ctx.options.suppressAPIEvents)){const t=this.get(e);this.ctx.events.fire(g.CREATE,{features:[t.toGeoJSON()]})}return this},te.prototype.featureChanged=function(e,t={}){return this._changedFeatureIds.add(e),!0!==(null!=t.silent?t.silent:this.ctx.options.suppressAPIEvents)&&this.ctx.events.fire(g.UPDATE,{action:t.action?t.action:m.CHANGE_COORDINATES,features:[this.get(e).toGeoJSON()]}),this},te.prototype.getChangedIds=function(){return this._changedFeatureIds.values()},te.prototype.clearChangedIds=function(){return this._changedFeatureIds.clear(),this},te.prototype.getAllIds=function(){return this._featureIds.values()},te.prototype.add=function(e,t={}){return this._features[e.id]=e,this._featureIds.add(e.id),this.featureCreated(e.id,{silent:t.silent}),this},te.prototype.delete=function(e,t={}){const o=[];return Q(e).forEach((e=>{this._featureIds.has(e)&&(this._featureIds.delete(e),this._selectedFeatureIds.delete(e),t.silent||-1===o.indexOf(this._features[e])&&o.push(this._features[e].toGeoJSON()),delete this._features[e],this.isDirty=!0)})),o.length&&this.ctx.events.fire(g.DELETE,{features:o}),oe(this,t),this},te.prototype.get=function(e){return this._features[e]},te.prototype.getAll=function(){return Object.keys(this._features).map((e=>this._features[e]))},te.prototype.select=function(e,t={}){return Q(e).forEach((e=>{this._selectedFeatureIds.has(e)||(this._selectedFeatureIds.add(e),this._changedFeatureIds.add(e),t.silent||(this._emitSelectionChange=!0))})),this},te.prototype.deselect=function(e,t={}){return Q(e).forEach((e=>{this._selectedFeatureIds.has(e)&&(this._selectedFeatureIds.delete(e),this._changedFeatureIds.add(e),t.silent||(this._emitSelectionChange=!0))})),oe(this,t),this},te.prototype.clearSelected=function(e={}){return this.deselect(this._selectedFeatureIds.values(),{silent:e.silent}),this},te.prototype.setSelected=function(e,t={}){return e=Q(e),this.deselect(this._selectedFeatureIds.values().filter((t=>-1===e.indexOf(t))),{silent:t.silent}),this.select(e.filter((e=>!this._selectedFeatureIds.has(e))),{silent:t.silent}),this},te.prototype.setSelectedCoordinates=function(e){return this._selectedCoordinates=e,this._emitSelectionChange=!0,this},te.prototype.clearSelectedCoordinates=function(){return this._selectedCoordinates=[],this._emitSelectionChange=!0,this},te.prototype.getSelectedIds=function(){return this._selectedFeatureIds.values()},te.prototype.getSelected=function(){return this.getSelectedIds().map((e=>this.get(e)))},te.prototype.getSelectedCoordinates=function(){return this._selectedCoordinates.map((e=>({coordinates:this.get(e.feature_id).getCoordinate(e.coord_path)})))},te.prototype.isSelected=function(e){return this._selectedFeatureIds.has(e)},te.prototype.setFeatureProperty=function(e,t,o,n={}){this.get(e).setProperty(t,o),this.featureChanged(e,{silent:n.silent,action:m.CHANGE_PROPERTIES})},te.prototype.storeMapConfig=function(){T.forEach((e=>{this.ctx.map[e]&&(this._mapInitialConfig[e]=this.ctx.map[e].isEnabled())}))},te.prototype.restoreMapConfig=function(){Object.keys(this._mapInitialConfig).forEach((e=>{this._mapInitialConfig[e]?this.ctx.map[e].enable():this.ctx.map[e].disable()}))},te.prototype.getInitialConfigValue=function(e){return void 0===this._mapInitialConfig[e]||this._mapInitialConfig[e]};const ne=["mode","feature","mouse"];function re(t){let o=null,n=null;const r={onRemove(){return t.map.off("load",r.connect),clearInterval(n),r.removeLayers(),t.store.restoreMapConfig(),t.ui.removeButtons(),t.events.removeEventListeners(),t.ui.clearMapClasses(),t.boxZoomInitial&&t.map.boxZoom.enable(),t.map=null,t.container=null,t.store=null,o&&o.parentNode&&o.parentNode.removeChild(o),o=null,this},connect(){t.map.off("load",r.connect),clearInterval(n),r.addLayers(),t.store.storeMapConfig(),t.events.addEventListeners()},onAdd(i){if(t.map=i,t.events=function(t){const o=Object.keys(t.options.modes).reduce(((e,o)=>(e[o]=z(t.options.modes[o]),e)),{});let n={},r={};const i={};let s=null,a=null;i.drag=function(e,o){o({point:e.point,time:(new Date).getTime()})?(t.ui.queueMapClasses({mouse:d.DRAG}),a.drag(e)):e.originalEvent.stopPropagation()},i.mousedrag=function(e){i.drag(e,(e=>!D(n,e)))},i.touchdrag=function(e){i.drag(e,(e=>!V(r,e)))},i.mousemove=function(e){if(1===(void 0!==e.originalEvent.buttons?e.originalEvent.buttons:e.originalEvent.which))return i.mousedrag(e);const o=A(e,t);e.featureTarget=o,a.mousemove(e)},i.mousedown=function(e){n={time:(new Date).getTime(),point:e.point};const o=A(e,t);e.featureTarget=o,a.mousedown(e)},i.mouseup=function(e){const o=A(e,t);e.featureTarget=o,D(n,{point:e.point,time:(new Date).getTime()})?a.click(e):a.mouseup(e)},i.mouseout=function(e){a.mouseout(e)},i.touchstart=function(e){if(!t.options.touchEnabled)return;r={time:(new Date).getTime(),point:e.point};const o=b.touch(e,null,t)[0];e.featureTarget=o,a.touchstart(e)},i.touchmove=function(e){if(t.options.touchEnabled)return a.touchmove(e),i.touchdrag(e)},i.touchend=function(e){if(e.originalEvent.preventDefault(),!t.options.touchEnabled)return;const o=b.touch(e,null,t)[0];e.featureTarget=o,V(r,{time:(new Date).getTime(),point:e.point})?a.tap(e):a.touchend(e)};const c=e=>!(8===e||46===e||e>=48&&e<=57);function l(n,r,i={}){a.stop();const c=o[n];if(void 0===c)throw new Error(`${n} is not valid`);s=n;const u=c(t,r);a=e(u,t),i.silent||t.map.fire(g.MODE_CHANGE,{mode:n}),t.store.setDirty(),t.store.render()}i.keydown=function(e){(e.srcElement||e.target).classList.contains(u.CANVAS)&&(8!==e.keyCode&&46!==e.keyCode||!t.options.controls.trash?c(e.keyCode)?a.keydown(e):49===e.keyCode&&t.options.controls.point?l(f.DRAW_POINT):50===e.keyCode&&t.options.controls.line_string?l(f.DRAW_LINE_STRING):51===e.keyCode&&t.options.controls.polygon&&l(f.DRAW_POLYGON):(e.preventDefault(),a.trash()))},i.keyup=function(e){c(e.keyCode)&&a.keyup(e)},i.zoomend=function(){t.store.changeZoom()},i.data=function(e){if("style"===e.dataType){const{setup:e,map:o,options:n,store:r}=t;n.styles.some((e=>o.getLayer(e.id)))||(e.addLayers(),r.setDirty(),r.render())}};const p={trash:!1,combineFeatures:!1,uncombineFeatures:!1};return{start(){s=t.options.defaultMode,a=e(o[s](t),t)},changeMode:l,actionable:function(e){let o=!1;Object.keys(e).forEach((t=>{if(void 0===p[t])throw new Error("Invalid action type");p[t]!==e[t]&&(o=!0),p[t]=e[t]})),o&&t.map.fire(g.ACTIONABLE,{actions:p})},currentModeName:()=>s,currentModeRender:(e,t)=>a.render(e,t),fire(e,o){t.map&&t.map.fire(e,o)},addEventListeners(){t.map.on("mousemove",i.mousemove),t.map.on("mousedown",i.mousedown),t.map.on("mouseup",i.mouseup),t.map.on("data",i.data),t.map.on("touchmove",i.touchmove),t.map.on("touchstart",i.touchstart),t.map.on("touchend",i.touchend),t.container.addEventListener("mouseout",i.mouseout),t.options.keybindings&&(t.container.addEventListener("keydown",i.keydown),t.container.addEventListener("keyup",i.keyup))},removeEventListeners(){t.map.off("mousemove",i.mousemove),t.map.off("mousedown",i.mousedown),t.map.off("mouseup",i.mouseup),t.map.off("data",i.data),t.map.off("touchmove",i.touchmove),t.map.off("touchstart",i.touchstart),t.map.off("touchend",i.touchend),t.container.removeEventListener("mouseout",i.mouseout),t.options.keybindings&&(t.container.removeEventListener("keydown",i.keydown),t.container.removeEventListener("keyup",i.keyup))},trash(e){a.trash(e)},combineFeatures(){a.combineFeatures()},uncombineFeatures(){a.uncombineFeatures()},getMode:()=>s}}(t),t.ui=function(e){const t={};let o=null,n={mode:null,feature:null,mouse:null},r={mode:null,feature:null,mouse:null};function i(e){r=Object.assign(r,e)}function s(){if(!e.container)return;const t=[],o=[];ne.forEach((e=>{r[e]!==n[e]&&(t.push(`${e}-${n[e]}`),null!==r[e]&&o.push(`${e}-${r[e]}`))})),t.length>0&&e.container.classList.remove(...t),o.length>0&&e.container.classList.add(...o),n=Object.assign(n,r)}function a(e,t={}){const n=document.createElement("button");return n.className=`${u.CONTROL_BUTTON} ${t.className}`,n.setAttribute("title",t.title),t.container.appendChild(n),n.addEventListener("click",(n=>{if(n.preventDefault(),n.stopPropagation(),n.target===o)return c(),void t.onDeactivate();l(e),t.onActivate()}),!0),n}function c(){o&&(o.classList.remove(u.ACTIVE_BUTTON),o=null)}function l(e){c();const n=t[e];n&&n&&"trash"!==e&&(n.classList.add(u.ACTIVE_BUTTON),o=n)}return{setActiveButton:l,queueMapClasses:i,updateMapClasses:s,clearMapClasses:function(){i({mode:null,feature:null,mouse:null}),s()},addButtons:function(){const o=e.options.controls,n=document.createElement("div");return n.className=`${u.CONTROL_GROUP} ${u.CONTROL_BASE}`,o?(o[p.LINE]&&(t[p.LINE]=a(p.LINE,{container:n,className:u.CONTROL_BUTTON_LINE,title:"LineString tool "+(e.options.keybindings?"(l)":""),onActivate:()=>e.events.changeMode(f.DRAW_LINE_STRING),onDeactivate:()=>e.events.trash()})),o[p.POLYGON]&&(t[p.POLYGON]=a(p.POLYGON,{container:n,className:u.CONTROL_BUTTON_POLYGON,title:"Polygon tool "+(e.options.keybindings?"(p)":""),onActivate:()=>e.events.changeMode(f.DRAW_POLYGON),onDeactivate:()=>e.events.trash()})),o[p.POINT]&&(t[p.POINT]=a(p.POINT,{container:n,className:u.CONTROL_BUTTON_POINT,title:"Marker tool "+(e.options.keybindings?"(m)":""),onActivate:()=>e.events.changeMode(f.DRAW_POINT),onDeactivate:()=>e.events.trash()})),o.trash&&(t.trash=a("trash",{container:n,className:u.CONTROL_BUTTON_TRASH,title:"Delete",onActivate:()=>{e.events.trash()}})),o.combine_features&&(t.combine_features=a("combineFeatures",{container:n,className:u.CONTROL_BUTTON_COMBINE_FEATURES,title:"Combine",onActivate:()=>{e.events.combineFeatures()}})),o.uncombine_features&&(t.uncombine_features=a("uncombineFeatures",{container:n,className:u.CONTROL_BUTTON_UNCOMBINE_FEATURES,title:"Uncombine",onActivate:()=>{e.events.uncombineFeatures()}})),n):n},removeButtons:function(){Object.keys(t).forEach((e=>{const o=t[e];o.parentNode&&o.parentNode.removeChild(o),delete t[e]}))}}}(t),t.container=i.getContainer(),t.store=new te(t),o=t.ui.addButtons(),t.options.boxSelect){t.boxZoomInitial=i.boxZoom.isEnabled(),i.boxZoom.disable();const e=i.dragPan.isEnabled();i.dragPan.disable(),i.dragPan.enable(),e||i.dragPan.disable()}return i.loaded()?r.connect():(i.on("load",r.connect),n=setInterval((()=>{i.loaded()&&r.connect()}),16)),t.events.start(),o},addLayers(){t.map.addSource(l.COLD,{data:{type:h.FEATURE_COLLECTION,features:[]},type:"geojson"}),t.map.addSource(l.HOT,{data:{type:h.FEATURE_COLLECTION,features:[]},type:"geojson"}),t.options.styles.forEach((e=>{t.map.addLayer(e)})),t.store.setDirty(!0),t.store.render()},removeLayers(){t.options.styles.forEach((e=>{t.map.getLayer(e.id)&&t.map.removeLayer(e.id)})),t.map.getSource(l.COLD)&&t.map.removeSource(l.COLD),t.map.getSource(l.HOT)&&t.map.removeSource(l.HOT)}};return t.setup=r,r}const ie="#3bb2d0",se="#fbb03b",ae="#fff";var ce=[{id:"gl-draw-polygon-fill",type:"fill",filter:["all",["==","$type","Polygon"]],paint:{"fill-color":["case",["==",["get","active"],"true"],se,ie],"fill-opacity":.1}},{id:"gl-draw-lines",type:"line",filter:["any",["==","$type","LineString"],["==","$type","Polygon"]],layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":["case",["==",["get","active"],"true"],se,ie],"line-dasharray":["case",["==",["get","active"],"true"],[.2,2],[2,0]],"line-width":2}},{id:"gl-draw-point-outer",type:"circle",filter:["all",["==","$type","Point"],["==","meta","feature"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],7,5],"circle-color":ae}},{id:"gl-draw-point-inner",type:"circle",filter:["all",["==","$type","Point"],["==","meta","feature"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],5,3],"circle-color":["case",["==",["get","active"],"true"],se,ie]}},{id:"gl-draw-vertex-outer",type:"circle",filter:["all",["==","$type","Point"],["==","meta","vertex"],["!=","mode","simple_select"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],7,5],"circle-color":ae}},{id:"gl-draw-vertex-inner",type:"circle",filter:["all",["==","$type","Point"],["==","meta","vertex"],["!=","mode","simple_select"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],5,3],"circle-color":se}},{id:"gl-draw-midpoint",type:"circle",filter:["all",["==","meta","midpoint"]],paint:{"circle-radius":3,"circle-color":se}}];function ue(e){return function(t){const o=t.featureTarget;return!!o&&!!o.properties&&o.properties.meta===e}}function le(e){return!!e.originalEvent&&!!e.originalEvent.shiftKey&&0===e.originalEvent.button}function de(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.active===E.ACTIVE&&e.featureTarget.properties.meta===y.FEATURE}function pe(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.active===E.INACTIVE&&e.featureTarget.properties.meta===y.FEATURE}function he(e){return void 0===e.featureTarget}function fe(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.meta===y.FEATURE}function ge(e){const t=e.featureTarget;return!!t&&!!t.properties&&t.properties.meta===y.VERTEX}function me(e){return!!e.originalEvent&&!0===e.originalEvent.shiftKey}function ye(e){return 27===e.keyCode}function Ee(e){return 13===e.keyCode}var Te=Object.freeze({__proto__:null,isActiveFeature:de,isEnterKey:Ee,isEscapeKey:ye,isFeature:fe,isInactiveFeature:pe,isOfMetaType:ue,isShiftDown:me,isShiftMousedown:le,isTrue:function(){return!0},isVertex:ge,noTarget:he});function Ce(e,t){this.x=e,this.y=t}function _e(e,t){const o=t.getBoundingClientRect();return new Ce(e.clientX-o.left-(t.clientLeft||0),e.clientY-o.top-(t.clientTop||0))}function ve(e,t,o,n){return{type:h.FEATURE,properties:{meta:y.VERTEX,parent:e,coord_path:o,active:n?E.ACTIVE:E.INACTIVE},geometry:{type:h.POINT,coordinates:t}}}function Ie(e,t,o){const n=t.geometry.coordinates,r=o.geometry.coordinates;if(n[1]>_||n[1]_||r[1]{const u=null!=o?`${o}.${a}`:String(a),l=ve(i,e,u,c(u));if(t.midpoints&&r){const e=Ie(i,r,l);e&&s.push(e)}r=l;const d=JSON.stringify(e);n!==d&&s.push(l),0===a&&(n=d)}))}function c(e){return!!t.selectedPaths&&-1!==t.selectedPaths.indexOf(e)}return n===h.POINT?s.push(ve(i,r,o,c(o))):n===h.POLYGON?r.forEach(((e,t)=>{a(e,null!==o?`${o}.${t}`:String(t))})):n===h.LINE_STRING?a(r,o):0===n.indexOf(h.MULTI_PREFIX)&&function(){const o=n.replace(h.MULTI_PREFIX,"");r.forEach(((n,r)=>{const i={type:h.FEATURE,properties:e.properties,geometry:{type:o,coordinates:n}};s=s.concat(Se(i,t,r))}))}(),s}Ce.prototype={clone(){return new Ce(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){const t=e.x-this.x,o=e.y-this.y;return t*t+o*o},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){const t=e[0]*this.x+e[1]*this.y,o=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=o,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){const e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){const t=Math.cos(e),o=Math.sin(e),n=t*this.x-o*this.y,r=o*this.x+t*this.y;return this.x=n,this.y=r,this},_rotateAround(e,t){const o=Math.cos(e),n=Math.sin(e),r=t.x+o*(this.x-t.x)-n*(this.y-t.y),i=t.y+n*(this.x-t.x)+o*(this.y-t.y);return this.x=r,this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:Ce},Ce.convert=function(e){if(e instanceof Ce)return e;if(Array.isArray(e))return new Ce(+e[0],+e[1]);if(void 0!==e.x&&void 0!==e.y)return new Ce(+e.x,+e.y);throw new Error("Expected [x, y] or {x, y} point format")};var Oe={enable(e){setTimeout((()=>{e.map&&e.map.doubleClickZoom&&e._ctx&&e._ctx.store&&e._ctx.store.getInitialConfigValue&&e._ctx.store.getInitialConfigValue("doubleClickZoom")&&e.map.doubleClickZoom.enable()}),0)},disable(e){setTimeout((()=>{e.map&&e.map.doubleClickZoom&&e.map.doubleClickZoom.disable()}),0)}};const{LAT_MIN:Le,LAT_MAX:Me,LAT_RENDERED_MIN:Ne,LAT_RENDERED_MAX:be,LNG_MIN:xe,LNG_MAX:Ae}=v;function Pe(e,t){let o=Le,n=Me,r=Le,i=Me,s=Ae,a=xe;e.forEach((e=>{const t=function(e){const t={Point:0,LineString:1,Polygon:2,MultiPoint:1,MultiLineString:2,MultiPolygon:3}[e.geometry.type],o=[e.geometry.coordinates].flat(t),n=o.map((e=>e[0])),r=o.map((e=>e[1])),i=e=>Math.min.apply(null,e),s=e=>Math.max.apply(null,e);return[i(n),i(r),s(n),s(r)]}(e),c=t[1],u=t[3],l=t[0],d=t[2];c>o&&(o=c),ur&&(r=u),ca&&(a=d)}));const c=t;return o+c.lat>be&&(c.lat=be-o),r+c.lat>Me&&(c.lat=Me-r),n+c.lat=Ae&&(c.lng-=360*Math.ceil(Math.abs(c.lng)/360)),c}function Fe(e,t){const o=Pe(e.map((e=>e.toGeoJSON())),t);e.forEach((e=>{const t=e.getCoordinates(),n=e=>{const t={lng:e[0]+o.lng,lat:e[1]+o.lat};return[t.lng,t.lat]},r=e=>e.map((e=>n(e))),i=e=>e.map((e=>r(e)));let s;e.type===h.POINT?s=n(t):e.type===h.LINE_STRING||e.type===h.MULTI_POINT?s=t.map(n):e.type===h.POLYGON||e.type===h.MULTI_LINE_STRING?s=t.map(r):e.type===h.MULTI_POLYGON&&(s=t.map(i)),e.incomingCoords(s)}))}const Re={onSetup:function(e){const t={dragMoveLocation:null,boxSelectStartLocation:null,boxSelectElement:void 0,boxSelecting:!1,canBoxSelect:!1,dragMoving:!1,canDragMove:!1,initialDragPanState:this.map.dragPan.isEnabled(),initiallySelectedFeatureIds:e.featureIds||[]};return this.setSelected(t.initiallySelectedFeatureIds.filter((e=>void 0!==this.getFeature(e)))),this.fireActionable(),this.setActionableState({combineFeatures:!0,uncombineFeatures:!0,trash:!0}),t},fireUpdate:function(){this.fire(g.UPDATE,{action:m.MOVE,features:this.getSelected().map((e=>e.toGeoJSON()))})},fireActionable:function(){const e=this.getSelected(),t=e.filter((e=>this.isInstanceOf("MultiFeature",e)));let o=!1;if(e.length>1){o=!0;const t=e[0].type.replace("Multi","");e.forEach((e=>{e.type.replace("Multi","")!==t&&(o=!1)}))}const n=t.length>0,r=e.length>0;this.setActionableState({combineFeatures:o,uncombineFeatures:n,trash:r})},getUniqueIds:function(e){return e.length?e.map((e=>e.properties.id)).filter((e=>void 0!==e)).reduce(((e,t)=>(e.add(t),e)),new M).values():[]},stopExtendedInteractions:function(e){e.boxSelectElement&&(e.boxSelectElement.parentNode&&e.boxSelectElement.parentNode.removeChild(e.boxSelectElement),e.boxSelectElement=null),(e.canDragMove||e.canBoxSelect)&&!0===e.initialDragPanState&&this.map.dragPan.enable(),e.boxSelecting=!1,e.canBoxSelect=!1,e.dragMoving=!1,e.canDragMove=!1},onStop:function(){Oe.enable(this)},onMouseMove:function(e,t){return fe(t)&&e.dragMoving&&this.fireUpdate(),this.stopExtendedInteractions(e),!0},onMouseOut:function(e){return!e.dragMoving||this.fireUpdate()}};Re.onTap=Re.onClick=function(e,t){return he(t)?this.clickAnywhere(e,t):ue(y.VERTEX)(t)?this.clickOnVertex(e,t):fe(t)?this.clickOnFeature(e,t):void 0},Re.clickAnywhere=function(e){const t=this.getSelectedIds();t.length&&(this.clearSelectedFeatures(),t.forEach((e=>this.doRender(e)))),Oe.enable(this),this.stopExtendedInteractions(e)},Re.clickOnVertex=function(e,t){this.changeMode(f.DIRECT_SELECT,{featureId:t.featureTarget.properties.parent,coordPath:t.featureTarget.properties.coord_path,startPos:t.lngLat}),this.updateUIClasses({mouse:d.MOVE})},Re.startOnActiveFeature=function(e,t){this.stopExtendedInteractions(e),this.map.dragPan.disable(),this.doRender(t.featureTarget.properties.id),e.canDragMove=!0,e.dragMoveLocation=t.lngLat},Re.clickOnFeature=function(e,t){Oe.disable(this),this.stopExtendedInteractions(e);const o=me(t),n=this.getSelectedIds(),r=t.featureTarget.properties.id,i=this.isSelected(r);if(!o&&i&&this.getFeature(r).type!==h.POINT)return this.changeMode(f.DIRECT_SELECT,{featureId:r});i&&o?(this.deselect(r),this.updateUIClasses({mouse:d.POINTER}),1===n.length&&Oe.enable(this)):!i&&o?(this.select(r),this.updateUIClasses({mouse:d.MOVE})):i||o||(n.forEach((e=>this.doRender(e))),this.setSelected(r),this.updateUIClasses({mouse:d.MOVE})),this.doRender(r)},Re.onMouseDown=function(e,t){return e.initialDragPanState=this.map.dragPan.isEnabled(),de(t)?this.startOnActiveFeature(e,t):this.drawConfig.boxSelect&&le(t)?this.startBoxSelect(e,t):void 0},Re.startBoxSelect=function(e,t){this.stopExtendedInteractions(e),this.map.dragPan.disable(),e.boxSelectStartLocation=_e(t.originalEvent,this.map.getContainer()),e.canBoxSelect=!0},Re.onTouchStart=function(e,t){if(de(t))return this.startOnActiveFeature(e,t)},Re.onDrag=function(e,t){return e.canDragMove?this.dragMove(e,t):this.drawConfig.boxSelect&&e.canBoxSelect?this.whileBoxSelect(e,t):void 0},Re.whileBoxSelect=function(e,t){e.boxSelecting=!0,this.updateUIClasses({mouse:d.ADD}),e.boxSelectElement||(e.boxSelectElement=document.createElement("div"),e.boxSelectElement.classList.add(u.BOX_SELECT),this.map.getContainer().appendChild(e.boxSelectElement));const o=_e(t.originalEvent,this.map.getContainer()),n=Math.min(e.boxSelectStartLocation.x,o.x),r=Math.max(e.boxSelectStartLocation.x,o.x),i=Math.min(e.boxSelectStartLocation.y,o.y),s=Math.max(e.boxSelectStartLocation.y,o.y),a=`translate(${n}px, ${i}px)`;e.boxSelectElement.style.transform=a,e.boxSelectElement.style.WebkitTransform=a,e.boxSelectElement.style.width=r-n+"px",e.boxSelectElement.style.height=s-i+"px"},Re.dragMove=function(e,t){e.dragMoving=!0,t.originalEvent.stopPropagation();const o={lng:t.lngLat.lng-e.dragMoveLocation.lng,lat:t.lngLat.lat-e.dragMoveLocation.lat};Fe(this.getSelected(),o),e.dragMoveLocation=t.lngLat},Re.onTouchEnd=Re.onMouseUp=function(e,t){if(e.dragMoving)this.fireUpdate();else if(e.boxSelecting){const o=[e.boxSelectStartLocation,_e(t.originalEvent,this.map.getContainer())],n=this.featuresAt(null,o,"click"),r=this.getUniqueIds(n).filter((e=>!this.isSelected(e)));r.length&&(this.select(r),r.forEach((e=>this.doRender(e))),this.updateUIClasses({mouse:d.MOVE}))}this.stopExtendedInteractions(e)},Re.toDisplayFeatures=function(e,t,o){t.properties.active=this.isSelected(t.properties.id)?E.ACTIVE:E.INACTIVE,o(t),this.fireActionable(),t.properties.active===E.ACTIVE&&t.geometry.type!==h.POINT&&Se(t).forEach(o)},Re.onTrash=function(){this.deleteFeature(this.getSelectedIds()),this.fireActionable()},Re.onCombineFeatures=function(){const e=this.getSelected();if(0===e.length||e.length<2)return;const t=[],o=[],n=e[0].type.replace("Multi","");for(let r=0;r{t.push(e)})):t.push(i.getCoordinates()),o.push(i.toGeoJSON())}if(o.length>1){const e=this.newFeature({type:h.FEATURE,properties:o[0].properties,geometry:{type:`Multi${n}`,coordinates:t}});this.addFeature(e),this.deleteFeature(this.getSelectedIds(),{silent:!0}),this.setSelected([e.id]),this.fire(g.COMBINE_FEATURES,{createdFeatures:[e.toGeoJSON()],deletedFeatures:o})}this.fireActionable()},Re.onUncombineFeatures=function(){const e=this.getSelected();if(0===e.length)return;const t=[],o=[];for(let n=0;n{this.addFeature(e),e.properties=r.properties,t.push(e.toGeoJSON()),this.select([e.id])})),this.deleteFeature(r.id,{silent:!0}),o.push(r.toGeoJSON()))}t.length>1&&this.fire(g.UNCOMBINE_FEATURES,{createdFeatures:t,deletedFeatures:o}),this.fireActionable()};const we=ue(y.VERTEX),De=ue(y.MIDPOINT),Ue={fireUpdate:function(){this.fire(g.UPDATE,{action:m.CHANGE_COORDINATES,features:this.getSelected().map((e=>e.toGeoJSON()))})},fireActionable:function(e){this.setActionableState({combineFeatures:!1,uncombineFeatures:!1,trash:e.selectedCoordPaths.length>0})},startDragging:function(e,t){e.initialDragPanState=this.map.dragPan.isEnabled(),this.map.dragPan.disable(),e.canDragMove=!0,e.dragMoveLocation=t.lngLat},stopDragging:function(e){e.canDragMove&&!0===e.initialDragPanState&&this.map.dragPan.enable(),e.dragMoving=!1,e.canDragMove=!1,e.dragMoveLocation=null},onVertex:function(e,t){this.startDragging(e,t);const o=t.featureTarget.properties,n=e.selectedCoordPaths.indexOf(o.coord_path);me(t)||-1!==n?me(t)&&-1===n&&e.selectedCoordPaths.push(o.coord_path):e.selectedCoordPaths=[o.coord_path];const r=this.pathsToCoordinates(e.featureId,e.selectedCoordPaths);this.setSelectedCoordinates(r)},onMidpoint:function(e,t){this.startDragging(e,t);const o=t.featureTarget.properties;e.feature.addCoordinate(o.coord_path,o.lng,o.lat),this.fireUpdate(),e.selectedCoordPaths=[o.coord_path]},pathsToCoordinates:function(e,t){return t.map((t=>({feature_id:e,coord_path:t})))},onFeature:function(e,t){0===e.selectedCoordPaths.length?this.startDragging(e,t):this.stopDragging(e)},dragFeature:function(e,t,o){Fe(this.getSelected(),o),e.dragMoveLocation=t.lngLat},dragVertex:function(e,t,o){const n=e.selectedCoordPaths.map((t=>e.feature.getCoordinate(t))),r=Pe(n.map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e}}))),o);for(let t=0;tt.localeCompare(e,"en",{numeric:!0}))).forEach((t=>e.feature.removeCoordinate(t))),this.fireUpdate(),e.selectedCoordPaths=[],this.clearSelectedCoordinates(),this.fireActionable(e),!1===e.feature.isValid()&&(this.deleteFeature([e.featureId]),this.changeMode(f.SIMPLE_SELECT,{}))},onMouseMove:function(e,t){const o=de(t),n=we(t),r=De(t),i=0===e.selectedCoordPaths.length;return o&&i||n&&!i?this.updateUIClasses({mouse:d.MOVE}):this.updateUIClasses({mouse:d.NONE}),(n||o||r)&&e.dragMoving&&this.fireUpdate(),this.stopDragging(e),!0},onMouseOut:function(e){return e.dragMoving&&this.fireUpdate(),!0}};Ue.onTouchStart=Ue.onMouseDown=function(e,t){return we(t)?this.onVertex(e,t):de(t)?this.onFeature(e,t):De(t)?this.onMidpoint(e,t):void 0},Ue.onDrag=function(e,t){if(!0!==e.canDragMove)return;e.dragMoving=!0,t.originalEvent.stopPropagation();const o={lng:t.lngLat.lng-e.dragMoveLocation.lng,lat:t.lngLat.lat-e.dragMoveLocation.lat};e.selectedCoordPaths.length>0?this.dragVertex(e,t,o):this.dragFeature(e,t,o),e.dragMoveLocation=t.lngLat},Ue.onClick=function(e,t){return he(t)?this.clickNoTarget(e,t):de(t)?this.clickActiveFeature(e,t):pe(t)?this.clickInactive(e,t):void this.stopDragging(e)},Ue.onTap=function(e,t){return he(t)?this.clickNoTarget(e,t):de(t)?this.clickActiveFeature(e,t):pe(t)?this.clickInactive(e,t):void 0},Ue.onTouchEnd=Ue.onMouseUp=function(e){e.dragMoving&&this.fireUpdate(),this.stopDragging(e)};const ke={};function Ve(e,t){return!!e.lngLat&&e.lngLat.lng===t[0]&&e.lngLat.lat===t[1]}ke.onSetup=function(){const e=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:[]}});return this.addFeature(e),this.clearSelectedFeatures(),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.POINT),this.setActionableState({trash:!0}),{point:e}},ke.stopDrawingAndRemove=function(e){this.deleteFeature([e.point.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)},ke.onTap=ke.onClick=function(e,t){this.updateUIClasses({mouse:d.MOVE}),e.point.updateCoordinate("",t.lngLat.lng,t.lngLat.lat),this.fire(g.CREATE,{features:[e.point.toGeoJSON()]}),this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.point.id]})},ke.onStop=function(e){this.activateUIButton(),e.point.getCoordinate().length||this.deleteFeature([e.point.id],{silent:!0})},ke.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.point.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t)},ke.onTrash=ke.stopDrawingAndRemove,ke.onKeyUp=function(e,t){if(ye(t)||Ee(t))return this.stopDrawingAndRemove(e,t)};const Ge={onSetup:function(){const e=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.POLYGON,coordinates:[[]]}});return this.addFeature(e),this.clearSelectedFeatures(),Oe.disable(this),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.POLYGON),this.setActionableState({trash:!0}),{polygon:e,currentVertexPosition:0}},clickAnywhere:function(e,t){if(e.currentVertexPosition>0&&Ve(t,e.polygon.coordinates[0][e.currentVertexPosition-1]))return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]});this.updateUIClasses({mouse:d.ADD}),e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat),e.currentVertexPosition++,e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat)},clickOnVertex:function(e){return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]})},onMouseMove:function(e,t){e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat),ge(t)&&this.updateUIClasses({mouse:d.POINTER})}};Ge.onTap=Ge.onClick=function(e,t){return ge(t)?this.clickOnVertex(e,t):this.clickAnywhere(e,t)},Ge.onKeyUp=function(e,t){ye(t)?(this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)):Ee(t)&&this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]})},Ge.onStop=function(e){this.updateUIClasses({mouse:d.NONE}),Oe.enable(this),this.activateUIButton(),void 0!==this.getFeature(e.polygon.id)&&(e.polygon.removeCoordinate(`0.${e.currentVertexPosition}`),e.polygon.isValid()?this.fire(g.CREATE,{features:[e.polygon.toGeoJSON()]}):(this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT,{},{silent:!0})))},Ge.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.polygon.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t);if(0===t.geometry.coordinates.length)return;const r=t.geometry.coordinates[0].length;if(!(r<3)){if(t.properties.meta=y.FEATURE,o(ve(e.polygon.id,t.geometry.coordinates[0][0],"0.0",!1)),r>3){const n=t.geometry.coordinates[0].length-3;o(ve(e.polygon.id,t.geometry.coordinates[0][n],`0.${n}`,!1))}if(r<=4){const e=[[t.geometry.coordinates[0][0][0],t.geometry.coordinates[0][0][1]],[t.geometry.coordinates[0][1][0],t.geometry.coordinates[0][1][1]]];if(o({type:h.FEATURE,properties:t.properties,geometry:{coordinates:e,type:h.LINE_STRING}}),3===r)return}return o(t)}},Ge.onTrash=function(e){this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)};const Be={onSetup:function(e){const t=(e=e||{}).featureId;let o,n,r="forward";if(t){if(o=this.getFeature(t),!o)throw new Error("Could not find a feature with the provided featureId");let i=e.from;if(i&&"Feature"===i.type&&i.geometry&&"Point"===i.geometry.type&&(i=i.geometry),i&&"Point"===i.type&&i.coordinates&&2===i.coordinates.length&&(i=i.coordinates),!i||!Array.isArray(i))throw new Error("Please use the `from` property to indicate which point to continue the line from");const s=o.coordinates.length-1;if(o.coordinates[s][0]===i[0]&&o.coordinates[s][1]===i[1])n=s+1,o.addCoordinate(n,...o.coordinates[s]);else{if(o.coordinates[0][0]!==i[0]||o.coordinates[0][1]!==i[1])throw new Error("`from` should match the point at either the start or the end of the provided LineString");r="backwards",n=0,o.addCoordinate(n,...o.coordinates[0])}}else o=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.LINE_STRING,coordinates:[]}}),n=0,this.addFeature(o);return this.clearSelectedFeatures(),Oe.disable(this),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.LINE),this.setActionableState({trash:!0}),{line:o,currentVertexPosition:n,direction:r}},clickAnywhere:function(e,t){if(e.currentVertexPosition>0&&Ve(t,e.line.coordinates[e.currentVertexPosition-1])||"backwards"===e.direction&&Ve(t,e.line.coordinates[e.currentVertexPosition+1]))return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]});this.updateUIClasses({mouse:d.ADD}),e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat),"forward"===e.direction?(e.currentVertexPosition++,e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat)):e.line.addCoordinate(0,t.lngLat.lng,t.lngLat.lat)},clickOnVertex:function(e){return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]})},onMouseMove:function(e,t){e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat),ge(t)&&this.updateUIClasses({mouse:d.POINTER})}};Be.onTap=Be.onClick=function(e,t){if(ge(t))return this.clickOnVertex(e,t);this.clickAnywhere(e,t)},Be.onKeyUp=function(e,t){Ee(t)?this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]}):ye(t)&&(this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT))},Be.onStop=function(e){Oe.enable(this),this.activateUIButton(),void 0!==this.getFeature(e.line.id)&&(e.line.removeCoordinate(`${e.currentVertexPosition}`),e.line.isValid()?this.fire(g.CREATE,{features:[e.line.toGeoJSON()]}):(this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT,{},{silent:!0})))},Be.onTrash=function(e){this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)},Be.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.line.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t);t.geometry.coordinates.length<2||(t.properties.meta=y.FEATURE,o(ve(e.line.id,t.geometry.coordinates["forward"===e.direction?t.geometry.coordinates.length-2:1],""+("forward"===e.direction?t.geometry.coordinates.length-2:1),!1)),o(t))};var je={simple_select:Re,direct_select:Ue,draw_point:ke,draw_polygon:Ge,draw_line_string:Be};const Je={defaultMode:f.SIMPLE_SELECT,keybindings:!0,touchEnabled:!0,clickBuffer:2,touchBuffer:25,boxSelect:!0,displayControlsDefault:!0,styles:ce,modes:je,controls:{},userProperties:!1,suppressAPIEvents:!0},$e={point:!0,line_string:!0,polygon:!0,trash:!0,combine_features:!0,uncombine_features:!0},Ye={point:!1,line_string:!1,polygon:!1,trash:!1,combine_features:!1,uncombine_features:!1};function He(e,t){return e.map((e=>e.source?e:Object.assign({},e,{id:`${e.id}.${t}`,source:"hot"===t?l.HOT:l.COLD})))}var Xe,qe,Ze,We,Ke=t(qe?Xe:(qe=1,Xe=function e(t,o){if(t===o)return!0;if(t&&o&&"object"==typeof t&&"object"==typeof o){if(t.constructor!==o.constructor)return!1;var n,r,i;if(Array.isArray(t)){if((n=t.length)!=o.length)return!1;for(r=n;0!=r--;)if(!e(t[r],o[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===o.source&&t.flags===o.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===o.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===o.toString();if((n=(i=Object.keys(t)).length)!==Object.keys(o).length)return!1;for(r=n;0!=r--;)if(!Object.prototype.hasOwnProperty.call(o,i[r]))return!1;for(r=n;0!=r--;){var s=i[r];if(!e(t[s],o[s]))return!1}return!0}return t!=t&&o!=o})),ze=function(){if(We)return Ze;We=1,Ze=function(t){if(!t||!t.type)return null;var o=e[t.type];return o?"geometry"===o?{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:t}]}:"feature"===o?{type:"FeatureCollection",features:[t]}:"featurecollection"===o?t:void 0:null};var e={Point:"geometry",MultiPoint:"geometry",LineString:"geometry",MultiLineString:"geometry",Polygon:"geometry",MultiPolygon:"geometry",GeometryCollection:"geometry",Feature:"feature",FeatureCollection:"featurecollection"};return Ze}(),Qe=t(ze);function et(e,t){return e.length===t.length&&JSON.stringify(e.map((e=>e)).sort())===JSON.stringify(t.map((e=>e)).sort())}const tt={Polygon:Y,LineString:$,Point:J,MultiPolygon:q,MultiLineString:q,MultiPoint:q};var ot=Object.freeze({__proto__:null,CommonSelectors:Te,ModeHandler:e,StringSet:M,constrainFeatureMovement:Pe,createMidPoint:Ie,createSupplementaryPoints:Se,createVertex:ve,doubleClickZoom:Oe,euclideanDistance:P,featuresAt:b,getFeatureAtAndSetCursors:A,isClick:D,isEventAtCoordinates:Ve,isTap:V,mapEventToBoundingBox:L,moveFeatures:Fe,sortFeatures:O,stringSetsAreEqual:et,theme:ce,toDenseArray:Q});const nt=function(e,t){const o={options:e=function(e={}){let t=Object.assign({},e);return e.controls||(t.controls={}),!1===e.displayControlsDefault?t.controls=Object.assign({},Ye,e.controls):t.controls=Object.assign({},$e,e.controls),t=Object.assign({},Je,t),t.styles=He(t.styles,"cold").concat(He(t.styles,"hot")),t}(e)};t=function(e,t){t.modes=f;const o=void 0===e.options.suppressAPIEvents||!!e.options.suppressAPIEvents;return t.getFeatureIdsAt=function(t){return b.click({point:t},null,e).map((e=>e.properties.id))},t.getSelectedIds=function(){return e.store.getSelectedIds()},t.getSelected=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getSelectedIds().map((t=>e.store.get(t))).map((e=>e.toGeoJSON()))}},t.getSelectedPoints=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getSelectedCoordinates().map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e.coordinates}})))}},t.set=function(o){if(void 0===o.type||o.type!==h.FEATURE_COLLECTION||!Array.isArray(o.features))throw new Error("Invalid FeatureCollection");const n=e.store.createRenderBatch();let r=e.store.getAllIds().slice();const i=t.add(o),s=new M(i);return r=r.filter((e=>!s.has(e))),r.length&&t.delete(r),n(),i},t.add=function(t){const n=JSON.parse(JSON.stringify(Qe(t))).features.map((t=>{if(t.id=t.id||B(),null===t.geometry)throw new Error("Invalid geometry: null");if(void 0===e.store.get(t.id)||e.store.get(t.id).type!==t.geometry.type){const n=tt[t.geometry.type];if(void 0===n)throw new Error(`Invalid geometry type: ${t.geometry.type}.`);const r=new n(e,t);e.store.add(r,{silent:o})}else{const n=e.store.get(t.id),r=n.properties;n.properties=t.properties,Ke(r,t.properties)||e.store.featureChanged(n.id,{silent:o}),Ke(n.getCoordinates(),t.geometry.coordinates)||n.incomingCoords(t.geometry.coordinates)}return t.id}));return e.store.render(),n},t.get=function(t){const o=e.store.get(t);if(o)return o.toGeoJSON()},t.getAll=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getAll().map((e=>e.toGeoJSON()))}},t.delete=function(n){return e.store.delete(n,{silent:o}),t.getMode()!==f.DIRECT_SELECT||e.store.getSelectedIds().length?e.store.render():e.events.changeMode(f.SIMPLE_SELECT,void 0,{silent:o}),t},t.deleteAll=function(){return e.store.delete(e.store.getAllIds(),{silent:o}),t.getMode()===f.DIRECT_SELECT?e.events.changeMode(f.SIMPLE_SELECT,void 0,{silent:o}):e.store.render(),t},t.changeMode=function(n,r={}){return n===f.SIMPLE_SELECT&&t.getMode()===f.SIMPLE_SELECT?(et(r.featureIds||[],e.store.getSelectedIds())||(e.store.setSelected(r.featureIds,{silent:o}),e.store.render()),t):(n===f.DIRECT_SELECT&&t.getMode()===f.DIRECT_SELECT&&r.featureId===e.store.getSelectedIds()[0]||e.events.changeMode(n,r,{silent:o}),t)},t.getMode=function(){return e.events.getMode()},t.trash=function(){return e.events.trash({silent:o}),t},t.combineFeatures=function(){return e.events.combineFeatures({silent:o}),t},t.uncombineFeatures=function(){return e.events.uncombineFeatures({silent:o}),t},t.setFeatureProperty=function(n,r,i){return e.store.setFeatureProperty(n,r,i,{silent:o}),t},t}(o,t),o.api=t;const n=re(o);return t.onAdd=n.onAdd,t.onRemove=n.onRemove,t.types=p,t.options=e,t};function rt(e){nt(e,this)}return rt.modes=je,rt.constants=v,rt.lib=ot,rt},"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).MapboxDraw=t(); +//# sourceMappingURL=mapbox-gl-draw.js.map diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js new file mode 100644 index 0000000..e2b91ff --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js @@ -0,0 +1 @@ +var MapboxGLGlobeMinimap=function(){"use strict";class t{constructor(){this._partials=new Float64Array(32),this._n=0}add(t){const n=this._partials;let e=0;for(let r=0;r0){for(o=t[--i];i>0&&(n=o,e=t[--i],o=n+e,r=e-(o-n),!r););i>0&&(r<0&&t[i-1]<0||r>0&&t[i-1]>0)&&(e=2*r,n=o+e,e==n-o&&(o=n))}return o}}function n(t){return Array.from(function*(t){for(const n of t)yield*n}(t))}var e={value:()=>{}};function r(){for(var t,n=0,e=arguments.length,r={};n=0&&(n=t.slice(e+1),t=t.slice(0,e)),t&&!r.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))),l=-1,s=a.length;if(!(arguments.length<2)){if(null!=n&&"function"!=typeof n)throw new Error("invalid callback: "+n);for(;++l0)for(var e,r,i=new Array(e),o=0;o=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),l.hasOwnProperty(n)?{space:l[n],local:t}:t}function c(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===a&&n.documentElement.namespaceURI===a?n.createElement(t):n.createElementNS(e,t)}}function f(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function h(t){var n=s(t);return(n.local?f:c)(n)}function p(){}function d(t){return null==t?p:function(){return this.querySelector(t)}}function v(){return[]}function g(t){return null==t?v:function(){return this.querySelectorAll(t)}}function y(t){return function(){return null==(n=t.apply(this,arguments))?[]:Array.isArray(n)?n:Array.from(n);var n}}function _(t){return function(){return this.matches(t)}}function m(t){return function(n){return n.matches(t)}}var w=Array.prototype.find;function b(){return this.firstElementChild}var x=Array.prototype.filter;function E(){return Array.from(this.children)}function S(t){return new Array(t.length)}function N(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}function k(t,n,e,r,i,o){for(var u,a=0,l=n.length,s=o.length;an?1:t>=n?0:NaN}function P(t){return function(){this.removeAttribute(t)}}function j(t){return function(){this.removeAttributeNS(t.space,t.local)}}function R(t,n){return function(){this.setAttribute(t,n)}}function T(t,n){return function(){this.setAttributeNS(t.space,t.local,n)}}function q(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttribute(t):this.setAttribute(t,e)}}function O(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}}function L(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function X(t){return function(){this.style.removeProperty(t)}}function z(t,n,e){return function(){this.style.setProperty(t,n,e)}}function D(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}function H(t,n){return t.style.getPropertyValue(n)||L(t).getComputedStyle(t,null).getPropertyValue(n)}function I(t){return function(){delete this[t]}}function Y(t,n){return function(){this[t]=n}}function B(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}function F(t){return t.trim().split(/^|\s+/)}function V(t){return t.classList||new G(t)}function G(t){this._node=t,this._names=F(t.getAttribute("class")||"")}function U(t,n){for(var e=V(t),r=-1,i=n.length;++r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var gt=[null];function yt(t,n){this._groups=t,this._parents=n}function _t(){return new yt([[document.documentElement]],gt)}function mt(t){return"string"==typeof t?new yt([[document.querySelector(t)]],[document.documentElement]):new yt([[t]],gt)}function wt(t,n,e){t.prototype=n.prototype=e,e.constructor=t}function bt(t,n){var e=Object.create(t.prototype);for(var r in n)e[r]=n[r];return e}function xt(){}yt.prototype=_t.prototype={constructor:yt,select:function(t){"function"!=typeof t&&(t=d(t));for(var n=this._groups,e=n.length,r=new Array(e),i=0;i=b&&(b=w+1);!(m=y[b])&&++b=0;)(r=i[o])&&(u&&4^r.compareDocumentPosition(u)&&u.parentNode.insertBefore(r,u),u=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=C);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?X:"function"==typeof n?D:z)(t,n,null==e?"":e)):H(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?I:"function"==typeof n?B:Y)(t,n)):this.node()[t]},classed:function(t,n){var e=F(t+"");if(arguments.length<2){for(var r=V(this.node()),i=-1,o=e.length;++i=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}}))}(t+""),u=o.length;if(!(arguments.length<2)){for(a=n?ht:ft,r=0;r>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):8===e?Dt(n>>24&255,n>>16&255,n>>8&255,(255&n)/255):4===e?Dt(n>>12&15|n>>8&240,n>>8&15|n>>4&240,n>>4&15|240&n,((15&n)<<4|15&n)/255):null):(n=$t.exec(t))?new It(n[1],n[2],n[3],1):(n=Ct.exec(t))?new It(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=Pt.exec(t))?Dt(n[1],n[2],n[3],n[4]):(n=jt.exec(t))?Dt(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=Rt.exec(t))?Ut(n[1],n[2]/100,n[3]/100,1):(n=Tt.exec(t))?Ut(n[1],n[2]/100,n[3]/100,n[4]):qt.hasOwnProperty(t)?zt(qt[t]):"transparent"===t?new It(NaN,NaN,NaN,0):null}function zt(t){return new It(t>>16&255,t>>8&255,255&t,1)}function Dt(t,n,e,r){return r<=0&&(t=n=e=NaN),new It(t,n,e,r)}function Ht(t,n,e,r){return 1===arguments.length?((i=t)instanceof xt||(i=Xt(i)),i?new It((i=i.rgb()).r,i.g,i.b,i.opacity):new It):new It(t,n,e,null==r?1:r);var i}function It(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function Yt(){return`#${Gt(this.r)}${Gt(this.g)}${Gt(this.b)}`}function Bt(){const t=Ft(this.opacity);return`${1===t?"rgb(":"rgba("}${Vt(this.r)}, ${Vt(this.g)}, ${Vt(this.b)}${1===t?")":`, ${t})`}`}function Ft(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Vt(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Gt(t){return((t=Vt(t))<16?"0":"")+t.toString(16)}function Ut(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new Wt(t,n,e,r)}function Zt(t){if(t instanceof Wt)return new Wt(t.h,t.s,t.l,t.opacity);if(t instanceof xt||(t=Xt(t)),!t)return new Wt;if(t instanceof Wt)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),u=NaN,a=o-i,l=(o+i)/2;return a?(u=n===o?(e-r)/a+6*(e0&&l<1?0:u,new Wt(u,a,l,t.opacity)}function Wt(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function Kt(t){return(t=(t||0)%360)<0?t+360:t}function Jt(t){return Math.max(0,Math.min(1,t||0))}function Qt(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}wt(xt,Xt,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:Ot,formatHex:Ot,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return Zt(this).formatHsl()},formatRgb:Lt,toString:Lt}),wt(It,Ht,bt(xt,{brighter(t){return t=null==t?St:Math.pow(St,t),new It(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?Et:Math.pow(Et,t),new It(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new It(Vt(this.r),Vt(this.g),Vt(this.b),Ft(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Yt,formatHex:Yt,formatHex8:function(){return`#${Gt(this.r)}${Gt(this.g)}${Gt(this.b)}${Gt(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:Bt,toString:Bt})),wt(Wt,(function(t,n,e,r){return 1===arguments.length?Zt(t):new Wt(t,n,e,null==r?1:r)}),bt(xt,{brighter(t){return t=null==t?St:Math.pow(St,t),new Wt(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?Et:Math.pow(Et,t),new Wt(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new It(Qt(t>=240?t-240:t+120,i,r),Qt(t,i,r),Qt(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new Wt(Kt(this.h),Jt(this.s),Jt(this.l),Ft(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=Ft(this.opacity);return`${1===t?"hsl(":"hsla("}${Kt(this.h)}, ${100*Jt(this.s)}%, ${100*Jt(this.l)}%${1===t?")":`, ${t})`}`}}));var tn=t=>()=>t;function nn(t){return 1==(t=+t)?en:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):tn(isNaN(n)?e:n)}}function en(t,n){var e=n-t;return e?function(t,n){return function(e){return t+e*n}}(t,e):tn(isNaN(t)?n:t)}var rn=function t(n){var e=nn(n);function r(t,n){var r=e((t=Ht(t)).r,(n=Ht(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),u=en(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=u(n),t+""}}return r.gamma=t,r}(1);function on(t,n){n||(n=[]);var e,r=t?Math.min(n.length,t.length):0,i=n.slice();return function(o){for(e=0;eo&&(i=n.slice(o,i),a[u]?a[u]+=i:a[++u]=i),(e=e[0])===(r=r[0])?a[u]?a[u]+=r:a[++u]=r:(a[++u]=null,l.push({i:u,x:ln(e,r)})),o=fn.lastIndex;return o180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:ln(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,u.rotate,a,l),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:ln(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,u.skewX,a,l),function(t,n,e,r,o,u){if(t!==e||n!==r){var a=o.push(i(o)+"scale(",null,",",null,")");u.push({i:a-4,x:ln(t,e)},{i:a-2,x:ln(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,u.scaleX,u.scaleY,a,l),o=u=null,function(t){for(var n,e=-1,r=l.length;++e=0&&n._call.call(void 0,t),n=n._next;--En}()}finally{En=0,function(){var t,n,e=mn,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:mn=n);wn=t,Xn(r)}(),An=0}}function Ln(){var t=Cn.now(),n=t-Mn;n>kn&&($n-=n,Mn=t)}function Xn(t){En||(Sn&&(Sn=clearTimeout(Sn)),t-An>24?(t<1/0&&(Sn=setTimeout(On,t-Cn.now()-$n)),Nn&&(Nn=clearInterval(Nn))):(Nn||(Mn=Cn.now(),Nn=setInterval(Ln,kn)),En=1,Pn(On)))}function zn(t,n,e){var r=new Tn;return n=null==n?0:+n,r.restart((e=>{r.stop(),t(e+n)}),n,e),r}Tn.prototype=qn.prototype={constructor:Tn,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?jn():+e)+(null==n?0:+n),this._next||wn===this||(wn?wn._next=this:mn=this,wn=this),this._call=t,this._time=e,Xn()},stop:function(){this._call&&(this._call=null,this._time=1/0,Xn())}};var Dn=r("start","end","cancel","interrupt"),Hn=[],In=0,Yn=1,Bn=2,Fn=3,Vn=4,Gn=5,Un=6;function Zn(t,n,e,r,i,o){var u=t.__transition;if(u){if(e in u)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(t){e.state=Yn,e.timer.restart(u,e.delay,e.time),e.delay<=t&&u(t-e.delay)}function u(o){var s,c,f,h;if(e.state!==Yn)return l();for(s in i)if((h=i[s]).name===e.name){if(h.state===Fn)return zn(u);h.state===Vn?(h.state=Un,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[s]):+sIn)throw new Error("too late; already scheduled");return e}function Kn(t,n){var e=Jn(t,n);if(e.state>Fn)throw new Error("too late; already running");return e}function Jn(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function Qn(t,n){var e,r;return function(){var i=Kn(this,t),o=i.tween;if(o!==e)for(var u=0,a=(r=e=o).length;u=0&&(t=t.slice(0,n)),!t||"start"===t}))}(n)?Wn:Kn;return function(){var u=o(this,t),a=u.on;a!==r&&(i=(r=a).copy()).on(n,e),u.on=i}}(e,t,n))},attr:function(t,n){var e=s(t),r="transform"===e?xn:ee;return this.attrTween(t,"function"==typeof n?(e.local?le:ae)(e,r,ne(this,"attr."+t,n)):null==n?(e.local?ie:re)(e):(e.local?ue:oe)(e,r,n))},attrTween:function(t,n){var e="attr."+t;if(arguments.length<2)return(e=this.tween(e))&&e._value;if(null==n)return this.tween(e,null);if("function"!=typeof n)throw new Error;var r=s(t);return this.tween(e,(r.local?se:ce)(r,n))},style:function(t,n,e){var r="transform"==(t+="")?bn:ee;return null==n?this.styleTween(t,function(t,n){var e,r,i;return function(){var o=H(this,t),u=(this.style.removeProperty(t),H(this,t));return o===u?null:o===e&&u===r?i:i=n(e=o,r=u)}}(t,r)).on("end.style."+t,ge(t)):"function"==typeof n?this.styleTween(t,function(t,n,e){var r,i,o;return function(){var u=H(this,t),a=e(this),l=a+"";return null==a&&(this.style.removeProperty(t),l=a=H(this,t)),u===l?null:u===r&&l===i?o:(i=l,o=n(r=u,a))}}(t,r,ne(this,"style."+t,n))).each(function(t,n){var e,r,i,o,u="style."+n,a="end."+u;return function(){var l=Kn(this,t),s=l.on,c=null==l.value[u]?o||(o=ge(n)):void 0;s===e&&i===c||(r=(e=s).copy()).on(a,i=c),l.on=r}}(this._id,t)):this.styleTween(t,function(t,n,e){var r,i,o=e+"";return function(){var u=H(this,t);return u===o?null:u===r?i:i=n(r=u,e)}}(t,r,n),e).on("end.style."+t,null)},styleTween:function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,function(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&function(t,n,e){return function(r){this.style.setProperty(t,n.call(this,r),e)}}(t,o,e)),r}return o._value=n,o}(t,n,null==e?"":e))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var n=t(this);this.textContent=null==n?"":n}}(ne(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},textTween:function(t){var n="text";if(arguments.length<1)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;return this.tween(n,function(t){var n,e;function r(){var r=t.apply(this,arguments);return r!==e&&(n=(e=r)&&function(t){return function(n){this.textContent=t.call(this,n)}}(r)),n}return r._value=t,r}(t))},remove:function(){return this.on("end.remove",function(t){return function(){var n=this.parentNode;for(var e in this.__transition)if(+e!==t)return;n&&n.removeChild(this)}}(this._id))},tween:function(t,n){var e=this._id;if(t+="",arguments.length<2){for(var r,i=Jn(this.node(),e).tween,o=0,u=i.length;oBn&&e.state0?1:t<0?-1:0},Xe=Math.sqrt;function ze(t){return t>1?Me:t<-1?-Me:Math.asin(t)}function De(){}function He(t,n){t&&Ye.hasOwnProperty(t.type)&&Ye[t.type](t,n)}var Ie={Feature:function(t,n){He(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++rke&&(t-=Math.round(t/$e)*$e),[t,n]}function er(t){return function(n,e){return je(n+=t)>ke&&(n-=Math.round(n/$e)*$e),[n,e]}}function rr(t){var n=er(t);return n.invert=er(-t),n}function ir(t,n){var e=qe(t),r=Oe(t),i=qe(n),o=Oe(n);function u(t,n){var u=qe(n),a=qe(t)*u,l=Oe(t)*u,s=Oe(n),c=s*e+a*r;return[Te(l*i-c*o,a*e-s*r),ze(c*i+l*o)]}return u.invert=function(t,n){var u=qe(n),a=qe(t)*u,l=Oe(t)*u,s=Oe(n),c=s*i-l*o;return[Te(l*i+s*o,a*e+c*r),ze(c*e-a*r)]},u}function or(t,n){(n=Ue(n))[0]-=t,Qe(n);var e,r=(e=-n[1])>1?0:e<-1?ke:Math.acos(e);return((-n[2]<0?-r:r)+$e-Se)%$e}function ur(){var t,n=[];return{point:function(n,e,r){t.push([n,e,r])},lineStart:function(){n.push(t=[])},lineEnd:De,rejoin:function(){n.length>1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function ar(t,n){return je(t[0]-n[0])=0;--o)i.point((c=s[o])[0],c[1]);else r(h.x,h.p.x,-1,i);h=h.p}s=(h=h.o).z,p=!p}while(!h.v);i.lineEnd()}}}function cr(t){if(n=t.length){for(var n,e,r=0,i=t[0];++r=0?1:-1,M=k*N,A=M>ke,$=y*E;if(s.add(Te($*k*Oe(M),_*S+$*qe(M))),a+=A?N+k*$e:N,A^v>=r^b>=r){var C=We(Ue(d),Ue(w));Qe(C);var P=We(u,C);Qe(P);var j=(A^N>=0?-1:1)*ze(P[2]);(i>j||i===j&&(C[0]||C[1]))&&(l+=A^N>=0?1:-1)}}return(a<-Se||a0){for(p||(u.polygonStart(),p=!0),u.lineStart(),t=0;t1&&2&i&&o.push(o.pop().concat(o.shift())),l.push(o.filter(pr))}return d}}function pr(t){return t.length>1}function dr(t,n){return((t=t.x)[0]<0?t[1]-Me-Se:Me-t[1])-((n=n.x)[0]<0?n[1]-Me-Se:Me-n[1])}nr.invert=nr;var vr=hr((function(){return!0}),(function(t){var n,e=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),n=1},point:function(o,u){var a=o>0?ke:-ke,l=je(o-e);je(l-ke)0?Me:-Me),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),n=0):i!==a&&l>=ke&&(je(e-i)Se?Re((Oe(n)*(o=qe(r))*Oe(e)-Oe(r)*(i=qe(n))*Oe(t))/(i*o*u)):(n+r)/2}(e,r,o,u),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),n=0),t.point(e=o,r=u),i=a},lineEnd:function(){t.lineEnd(),e=r=NaN},clean:function(){return 2-n}}}),(function(t,n,e,r){var i;if(null==t)i=e*Me,r.point(-ke,i),r.point(0,i),r.point(ke,i),r.point(ke,0),r.point(ke,-i),r.point(0,-i),r.point(-ke,-i),r.point(-ke,0),r.point(-ke,i);else if(je(t[0]-n[0])>Se){var o=t[0]0,i=je(n)>Se;function o(t,e){return qe(t)*qe(e)>n}function u(t,e,r){var i=[1,0,0],o=We(Ue(t),Ue(e)),u=Ze(o,o),a=o[0],l=u-a*a;if(!l)return!r&&t;var s=n*u/l,c=-n*a/l,f=We(i,o),h=Je(i,s);Ke(h,Je(o,c));var p=f,d=Ze(h,p),v=Ze(p,p),g=d*d-v*(Ze(h,h)-1);if(!(g<0)){var y=Xe(g),_=Je(p,(-d-y)/v);if(Ke(_,h),_=Ge(_),!r)return _;var m,w=t[0],b=e[0],x=t[1],E=e[1];b0^_[1]<(je(_[0]-w)ke^(w<=_[0]&&_[0]<=b)){var k=Je(p,(-d+y)/v);return Ke(k,h),[_,Ge(k)]}}}function a(n,e){var i=r?t:ke-t,o=0;return n<-i?o|=1:n>i&&(o|=2),e<-i?o|=4:e>i&&(o|=8),o}return hr(o,(function(t){var n,e,l,s,c;return{lineStart:function(){s=l=!1,c=1},point:function(f,h){var p,d=[f,h],v=o(f,h),g=r?v?0:a(f,h):v?a(f+(f<0?ke:-ke),h):0;if(!n&&(s=l=v)&&t.lineStart(),v!==l&&(!(p=u(n,d))||ar(n,p)||ar(d,p))&&(d[2]=1),v!==l)c=0,v?(t.lineStart(),p=u(d,n),t.point(p[0],p[1])):(p=u(n,d),t.point(p[0],p[1],2),t.lineEnd()),n=p;else if(i&&n&&r^v){var y;g&e||!(y=u(d,n,!0))||(c=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1],3)))}!v||n&&ar(n,d)||t.point(d[0],d[1]),n=d,l=v,e=g},lineEnd:function(){l&&t.lineEnd(),n=null},clean:function(){return c|(s&&l)<<1}}}),(function(n,r,i,o){!function(t,n,e,r,i,o){if(e){var u=qe(n),a=Oe(n),l=r*e;null==i?(i=n+r*$e,o=n-l/2):(i=or(u,i),o=or(u,o),(r>0?io)&&(i+=r*$e));for(var s,c=i;r>0?c>o:c0)do{l.point(0===c||3===c?t:r,c>1?i:e)}while((c=(c+u+4)%4)!==f);else l.point(o[0],o[1])}function a(n,i){return je(n[0]-t)0?0:3:je(n[0]-r)0?2:1:je(n[1]-e)0?1:0:i>0?3:2}function l(t,n){return s(t.x,n.x)}function s(t,n){var e=a(t,1),r=a(n,1);return e!==r?e-r:0===e?n[1]-t[1]:1===e?t[0]-n[0]:2===e?t[1]-n[1]:n[0]-t[0]}return function(a){var s,c,f,h,p,d,v,g,y,_,m,w=a,b=ur(),x={point:E,lineStart:function(){x.point=S,c&&c.push(f=[]);_=!0,y=!1,v=g=NaN},lineEnd:function(){s&&(S(h,p),d&&y&&b.rejoin(),s.push(b.result()));x.point=E,y&&w.lineEnd()},polygonStart:function(){w=b,s=[],c=[],m=!0},polygonEnd:function(){var e=function(){for(var n=0,e=0,r=c.length;ei&&(h-o)*(i-u)>(p-u)*(t-o)&&++n:p<=i&&(h-o)*(i-u)<(p-u)*(t-o)&&--n;return n}(),r=m&&e,o=(s=n(s)).length;(r||o)&&(a.polygonStart(),r&&(a.lineStart(),u(null,null,1,a),a.lineEnd()),o&&sr(s,l,e,u,a),a.polygonEnd());w=a,s=c=f=null}};function E(t,n){o(t,n)&&w.point(t,n)}function S(n,u){var a=o(n,u);if(c&&f.push([n,u]),_)h=n,p=u,d=a,_=!1,a&&(w.lineStart(),w.point(n,u));else if(a&&y)w.point(n,u);else{var l=[v=Math.max(_r,Math.min(yr,v)),g=Math.max(_r,Math.min(yr,g))],s=[n=Math.max(_r,Math.min(yr,n)),u=Math.max(_r,Math.min(yr,u))];!function(t,n,e,r,i,o){var u,a=t[0],l=t[1],s=0,c=1,f=n[0]-a,h=n[1]-l;if(u=e-a,f||!(u>0)){if(u/=f,f<0){if(u0){if(u>c)return;u>s&&(s=u)}if(u=i-a,f||!(u<0)){if(u/=f,f<0){if(u>c)return;u>s&&(s=u)}else if(f>0){if(u0)){if(u/=h,h<0){if(u0){if(u>c)return;u>s&&(s=u)}if(u=o-l,h||!(u<0)){if(u/=h,h<0){if(u>c)return;u>s&&(s=u)}else if(h>0){if(u0&&(t[0]=a+s*f,t[1]=l+s*h),c<1&&(n[0]=a+c*f,n[1]=l+c*h),!0}}}}}(l,s,t,e,r,i)?a&&(w.lineStart(),w.point(n,u),m=!1):(y||(w.lineStart(),w.point(l[0],l[1])),w.point(s[0],s[1]),a||w.lineEnd(),m=!1)}v=n,g=u,y=a}return x}}var wr,br,xr,Er,Sr=t=>t,Nr=new t,kr=new t,Mr={point:De,lineStart:De,lineEnd:De,polygonStart:function(){Mr.lineStart=Ar,Mr.lineEnd=Pr},polygonEnd:function(){Mr.lineStart=Mr.lineEnd=Mr.point=De,Nr.add(je(kr)),kr=new t},result:function(){var n=Nr/2;return Nr=new t,n}};function Ar(){Mr.point=$r}function $r(t,n){Mr.point=Cr,wr=xr=t,br=Er=n}function Cr(t,n){kr.add(Er*t-xr*n),xr=t,Er=n}function Pr(){Cr(wr,br)}var jr=1/0,Rr=jr,Tr=-jr,qr=Tr,Or={point:function(t,n){tTr&&(Tr=t);nqr&&(qr=n)},lineStart:De,lineEnd:De,polygonStart:De,polygonEnd:De,result:function(){var t=[[jr,Rr],[Tr,qr]];return Tr=qr=-(Rr=jr=1/0),t}};var Lr,Xr,zr,Dr,Hr=0,Ir=0,Yr=0,Br=0,Fr=0,Vr=0,Gr=0,Ur=0,Zr=0,Wr={point:Kr,lineStart:Jr,lineEnd:ni,polygonStart:function(){Wr.lineStart=ei,Wr.lineEnd=ri},polygonEnd:function(){Wr.point=Kr,Wr.lineStart=Jr,Wr.lineEnd=ni},result:function(){var t=Zr?[Gr/Zr,Ur/Zr]:Vr?[Br/Vr,Fr/Vr]:Yr?[Hr/Yr,Ir/Yr]:[NaN,NaN];return Hr=Ir=Yr=Br=Fr=Vr=Gr=Ur=Zr=0,t}};function Kr(t,n){Hr+=t,Ir+=n,++Yr}function Jr(){Wr.point=Qr}function Qr(t,n){Wr.point=ti,Kr(zr=t,Dr=n)}function ti(t,n){var e=t-zr,r=n-Dr,i=Xe(e*e+r*r);Br+=i*(zr+t)/2,Fr+=i*(Dr+n)/2,Vr+=i,Kr(zr=t,Dr=n)}function ni(){Wr.point=Kr}function ei(){Wr.point=ii}function ri(){oi(Lr,Xr)}function ii(t,n){Wr.point=oi,Kr(Lr=zr=t,Xr=Dr=n)}function oi(t,n){var e=t-zr,r=n-Dr,i=Xe(e*e+r*r);Br+=i*(zr+t)/2,Fr+=i*(Dr+n)/2,Vr+=i,Gr+=(i=Dr*t-zr*n)*(zr+t),Ur+=i*(Dr+n),Zr+=3*i,Kr(zr=t,Dr=n)}function ui(t){this._context=t}ui.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._context.moveTo(t,n),this._point=1;break;case 1:this._context.lineTo(t,n);break;default:this._context.moveTo(t+this._radius,n),this._context.arc(t,n,this._radius,0,$e)}},result:De};var ai,li,si,ci,fi,hi=new t,pi={point:De,lineStart:function(){pi.point=di},lineEnd:function(){ai&&vi(li,si),pi.point=De},polygonStart:function(){ai=!0},polygonEnd:function(){ai=null},result:function(){var n=+hi;return hi=new t,n}};function di(t,n){pi.point=vi,li=ci=t,si=fi=n}function vi(t,n){ci-=t,fi-=n,hi.add(Xe(ci*ci+fi*fi)),ci=t,fi=n}let gi,yi,_i,mi;class wi{constructor(t){this._append=null==t?bi:function(t){const n=Math.floor(t);if(!(n>=0))throw new RangeError(`invalid digits: ${t}`);if(n>15)return bi;if(n!==gi){const t=10**n;gi=n,yi=function(n){let e=1;this._+=n[0];for(const r=n.length;e4*n&&v--){var w=u+h,b=a+p,x=l+d,E=Xe(w*w+b*b+x*x),S=ze(x/=E),N=je(je(x)-1)n||je((y*$+_*C)/m-.5)>.3||u*h+a*p+l*d2?t[2]%360*Pe:0,$()):[g*Ce,y*Ce,_*Ce]},M.angle=function(t){return arguments.length?(m=t%360*Pe,$()):m*Ce},M.reflectX=function(t){return arguments.length?(w=t?-1:1,$()):w<0},M.reflectY=function(t){return arguments.length?(b=t?-1:1,$()):b<0},M.precision=function(t){return arguments.length?(u=Ai(a,k=t*t),C()):Xe(k)},M.fitExtent=function(t,n){return Ni(M,t,n)},M.fitSize=function(t,n){return function(t,n,e){return Ni(t,[[0,0],n],e)}(M,t,n)},M.fitWidth=function(t,n){return function(t,n,e){return Si(t,(function(e){var r=+n,i=r/(e[1][0]-e[0][0]),o=(r-i*(e[1][0]+e[0][0]))/2,u=-i*e[0][1];t.scale(150*i).translate([o,u])}),e)}(M,t,n)},M.fitHeight=function(t,n){return function(t,n,e){return Si(t,(function(e){var r=+n,i=r/(e[1][1]-e[0][1]),o=-i*e[0][0],u=(r-i*(e[1][1]+e[0][1]))/2;t.scale(150*i).translate([o,u])}),e)}(M,t,n)},function(){return n=t.apply(this,arguments),M.invert=n.invert&&A,$()}}((function(){return t}))()}function Ri(t,n){return[qe(n)*Oe(t),Oe(n)]}function Ti(t,n,e){this.k=t,this.x=n,this.y=e}function qi(t){return t}function Oi(t,n){var e=n.id,r=n.bbox,i=null==n.properties?{}:n.properties,o=function(t,n){var e=function(t){if(null==t)return qi;var n,e,r=t.scale[0],i=t.scale[1],o=t.translate[0],u=t.translate[1];return function(t,a){a||(n=e=0);var l=2,s=t.length,c=new Array(s);for(c[0]=(n+=t[0])*r+o,c[1]=(e+=t[1])*i+u;l=0))throw new RangeError(`invalid digits: ${t}`);i=n}return null===n&&(r=new wi(i)),u},u.projection(t).digits(i).context(n)}(this.projection,r),this.globe={type:"Sphere"},this.land=(o=Li,"GeometryCollection"===(u=Li.objects.land).type?{type:"FeatureCollection",features:u.geometries.map((function(t){return Oi(o,t)}))}:Oi(o,u)),this._update(),n.on("move",this._update.bind(this))},_draw_marker:function(){const{globeSize:t,markerSize:n,markerColor:e}=this.options;mt(Xi).append("svg").attr("width",t).attr("height",t).attr("style","position: absolute; left: 0; top: 0;").append("path").attr("opacity",0).attr("d","M5.36018 5.33333C5.36018 4.59722 5.61972 3.96875 6.13881 3.44792C6.65789 2.92708 7.28426 2.66667 8.0179 2.66667C8.75154 2.66667 9.3779 2.92708 9.89699 3.44792C10.4161 3.96875 10.6756 4.59722 10.6756 5.33333C10.6756 6.06944 10.4161 6.69792 9.89699 7.21875C9.3779 7.73958 8.75154 8 8.0179 8C7.28426 8 6.65789 7.73958 6.13881 7.21875C5.61972 6.69792 5.36018 6.06944 5.36018 5.33333ZM2.70246 5.33333C2.70246 6.09028 2.81666 6.7118 3.04506 7.19792L6.824 15.2604C6.93474 15.4896 7.09911 15.6701 7.31713 15.8021C7.53515 15.934 7.76874 16 8.0179 16C8.26706 16 8.50065 15.934 8.71866 15.8021C8.93668 15.6701 9.09759 15.4896 9.20141 15.2604L12.9907 7.19792C13.2191 6.71181 13.3333 6.09028 13.3333 5.33333C13.3333 3.86111 12.8142 2.60417 11.7761 1.5625C10.7379 0.520833 9.48518 -8.13254e-07 8.0179 -9.41527e-07C6.55062 -1.0698e-06 5.29789 0.520832 4.25972 1.5625C3.22155 2.60417 2.70246 3.86111 2.70246 5.33333Z").attr("transform",`scale(${n}, ${n}), translate(${t*(1/n)/2-8}, ${t*(1/n)/2-16})`).attr("style","fill:"+e).transition().duration(100).attr("opacity",1)},_update:function(){const t=this,n=this._parentMap.getCenter();me().duration(this.initialTween?1e3:1).tween("rotate",(function(){const e=pn(t.projection.rotate(),[-n.lng,-n.lat]);return function(n){t.projection.rotate(e(n)),t.context.clearRect(0,0,t.canvas.width,t.canvas.height),t.context.fillStyle=t.options.waterColor,t.context.beginPath(),t.path(t.globe),t.context.fill(),t.context.fillStyle=t.options.landColor,t.context.beginPath(),t.path(t.land),t.context.fill()}})).on("end",(()=>{t.initialTween&&(t._draw_marker(),t.initialTween=!1)}))},_createContainer:function(t){const{globeSize:n,id:e}=this.options,r=document.createElement("div");return r.className="mapboxgl-ctrl-globe-minimap mapboxgl-ctrl",r.setAttribute("style","width: "+n+"; height: "+n+";"),r.addEventListener("contextmenu",this._preventDefault),t.getContainer().appendChild(r),""!==e&&(r.id=e),r},_preventDefault:function(t){t.preventDefault()}},window.GlobeMinimap=zi,zi}(); diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js new file mode 100644 index 0000000..207d876 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js @@ -0,0 +1,1102 @@ +/** + * mapbox-pmtiles v1.1.0 - Optimized Version with Lifecycle Management + * Original source: https://github.com/am2222/mapbox-pmtiles by Majid Hojati + * License: MIT + * + * This is an optimized version of the mapbox-pmtiles library that provides + * better performance for large datasets through: + * - Configurable resource management + * - Instance-scoped worker pools and caches + * - Proper lifecycle management and cleanup + * - Reference counting for shared resources + * - Enhanced error handling and timeouts + * - Memory optimization with size-based LRU caches + * + * Last updated: 2025 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + // Global shared resources with reference counting + const GLOBAL_SHARED_RESOURCES = { + // Protocol cache - expensive to duplicate, shared with reference counting + protocolCache: new Map(), // url -> { protocol, instance, refCount } + + // Metadata cache - small and shareable + metadataCache: new Map(), // cacheKey -> data + + // Pre-calculated world sizes for common zoom levels (static, no cleanup needed) + worldSizeCache: new Array(25).fill(null).map((_, z) => Math.pow(2, z)), + + // Global cleanup registry + activeManagers: new Set(), + + // Debug/development features + debug: false, + performanceMetrics: new Map(), + }; + + /** + * Default configuration options + */ + const DEFAULT_OPTIONS = { + workerPoolSize: 4, + tileCacheSize: 1000, + tileCacheMaxMemoryMB: 100, + metadataCacheSize: 100, + enableSharedProtocols: true, + requestTimeoutMs: 30000, + enableDebugLogging: false, + enablePerformanceMetrics: false, + }; + + /** + * LRU Cache implementation with size-based eviction + */ + class LRUCache { + constructor(maxSize, maxMemoryBytes = Infinity) { + this.maxSize = maxSize; + this.maxMemoryBytes = maxMemoryBytes; + this.cache = new Map(); + this.currentMemoryBytes = 0; + } + + get(key) { + if (this.cache.has(key)) { + // Move to end (most recently used) + const value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return value.data; + } + return undefined; + } + + set(key, data, estimatedSize = 0) { + // Remove if exists + if (this.cache.has(key)) { + const existing = this.cache.get(key); + this.currentMemoryBytes -= existing.size; + this.cache.delete(key); + } + + // Evict old entries if necessary + while ( + this.cache.size >= this.maxSize || + this.currentMemoryBytes + estimatedSize > this.maxMemoryBytes + ) { + const firstKey = this.cache.keys().next().value; + if (!firstKey) break; + + const firstValue = this.cache.get(firstKey); + this.currentMemoryBytes -= firstValue.size; + this.cache.delete(firstKey); + } + + // Add new entry + this.cache.set(key, { data, size: estimatedSize }); + this.currentMemoryBytes += estimatedSize; + } + + has(key) { + return this.cache.has(key); + } + + delete(key) { + if (this.cache.has(key)) { + const value = this.cache.get(key); + this.currentMemoryBytes -= value.size; + this.cache.delete(key); + return true; + } + return false; + } + + clear() { + this.cache.clear(); + this.currentMemoryBytes = 0; + } + + get size() { + return this.cache.size; + } + + getMemoryUsage() { + return { + entries: this.cache.size, + memoryBytes: this.currentMemoryBytes, + memoryMB: this.currentMemoryBytes / (1024 * 1024), + }; + } + } + + /** + * Resource Manager - handles per-instance resources and lifecycle + */ + class PMTilesResourceManager { + constructor(options = {}) { + this.config = { ...DEFAULT_OPTIONS, ...options }; + this.destroyed = false; + this.paused = false; + this.dispatcher = null; + + // Instance-scoped resources + this.workerPool = []; + this.workerPoolIndex = 0; + this.tileCache = new LRUCache( + this.config.tileCacheSize, + this.config.tileCacheMaxMemoryMB * 1024 * 1024, + ); + this.pendingRequests = new Map(); + this.activeRequests = new Set(); + + // Performance tracking + this.metrics = { + tilesLoaded: 0, + cacheHits: 0, + cacheMisses: 0, + memoryPeakMB: 0, + averageLoadTimeMs: 0, + }; + + // Register for global cleanup + GLOBAL_SHARED_RESOURCES.activeManagers.add(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager created", this.config); + } + } + + /** + * Initialize worker pool + */ + initializeWorkerPool(dispatcher) { + if (this.destroyed) return; + + // Store dispatcher reference + if (dispatcher) { + this.dispatcher = dispatcher; + } + + if (this.workerPool.length === 0 && this.dispatcher) { + for (let i = 0; i < this.config.workerPoolSize; i++) { + try { + this.workerPool.push(this.dispatcher.getActor()); + } catch (error) { + console.warn("[PMTiles] Failed to create worker:", error); + } + } + + if (this.config.enableDebugLogging) { + console.log( + `[PMTiles] Initialized worker pool with ${this.workerPool.length} workers`, + ); + } + } + } + + /** + * Get next worker from pool (round-robin) + */ + getWorkerFromPool() { + if (this.destroyed) { + return null; + } + + // Try to initialize workers if not done yet + if (this.workerPool.length === 0 && this.dispatcher) { + this.initializeWorkerPool(this.dispatcher); + } + + if (this.workerPool.length === 0) { + if (this.config.enableDebugLogging) { + console.warn( + "[PMTiles] Worker pool is empty, dispatcher available:", + !!this.dispatcher, + ); + } + return null; + } + + const worker = this.workerPool[this.workerPoolIndex]; + this.workerPoolIndex = + (this.workerPoolIndex + 1) % this.workerPool.length; + return worker; + } + + /** + * Get or create protocol instance with reference counting + */ + getProtocol(url) { + if (this.destroyed) return null; + + if (!this.config.enableSharedProtocols) { + // Create instance-specific protocol + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + return { protocol, instance }; + } + + // Use shared protocol with reference counting + if (!GLOBAL_SHARED_RESOURCES.protocolCache.has(url)) { + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + GLOBAL_SHARED_RESOURCES.protocolCache.set(url, { + protocol, + instance, + refCount: 0, + }); + } + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + cached.refCount++; + return cached; + } + + /** + * Release protocol reference + */ + releaseProtocol(url) { + if (!this.config.enableSharedProtocols) return; + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + if (cached) { + cached.refCount--; + if (cached.refCount <= 0) { + GLOBAL_SHARED_RESOURCES.protocolCache.delete(url); + + if (this.config.enableDebugLogging) { + console.log(`[PMTiles] Released protocol for ${url}`); + } + } + } + } + + /** + * Cache key for tiles + */ + getTileCacheKey(url, z, x, y) { + return `${url}:${z}:${x}:${y}`; + } + + /** + * Add tile to cache with size estimation + */ + addToTileCache(key, data) { + if (this.destroyed) return; + + let estimatedSize = 0; + if (data instanceof ImageBitmap) { + // Rough estimation: width * height * 4 bytes per pixel + estimatedSize = data.width * data.height * 4; + } else if (data && data.byteLength) { + estimatedSize = data.byteLength; + } else { + estimatedSize = 10000; // Default estimate + } + + this.tileCache.set(key, data, estimatedSize); + + // Update peak memory usage + const memoryUsage = this.tileCache.getMemoryUsage(); + this.metrics.memoryPeakMB = Math.max( + this.metrics.memoryPeakMB, + memoryUsage.memoryMB, + ); + } + + /** + * Get cached metadata + */ + getCachedMetadata(cacheKey) { + return GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + } + + /** + * Set cached metadata + */ + setCachedMetadata(cacheKey, data) { + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, data); + } + + /** + * Pause all operations + */ + pause() { + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager paused"); + } + } + + /** + * Resume operations + */ + resume() { + this.paused = false; + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager resumed"); + } + } + + /** + * Get performance metrics + */ + getMetrics() { + return { + ...this.metrics, + tileCache: this.tileCache.getMemoryUsage(), + workerPoolSize: this.workerPool.length, + pendingRequests: this.pendingRequests.size, + isPaused: this.paused, + isDestroyed: this.destroyed, + }; + } + + /** + * Destroy and cleanup all resources + */ + destroy() { + if (this.destroyed) return; + + this.destroyed = true; + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + // Clear caches + this.tileCache.clear(); + + // Clear worker pool references + this.workerPool.length = 0; + + // Remove from global registry + GLOBAL_SHARED_RESOURCES.activeManagers.delete(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager destroyed", this.getMetrics()); + } + } + } + + /** + * Global cleanup function + */ + const cleanup = () => { + for (const manager of GLOBAL_SHARED_RESOURCES.activeManagers) { + manager.destroy(); + } + GLOBAL_SHARED_RESOURCES.protocolCache.clear(); + GLOBAL_SHARED_RESOURCES.metadataCache.clear(); + }; + + // Register global cleanup + if (typeof window !== "undefined") { + window.addEventListener("beforeunload", cleanup); + } + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + + // Pre-calculate mercator bounds + this._mercatorBounds = { + west: mercatorXFromLng(this.bounds.getWest()), + north: mercatorYFromLat(this.bounds.getNorth()), + east: mercatorXFromLng(this.bounds.getEast()), + south: mercatorYFromLat(this.bounds.getSouth()), + }; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + // Use pre-calculated world size + const worldSize = + GLOBAL_SHARED_RESOURCES.worldSizeCache[tileID.z] || + Math.pow(2, tileID.z); + + // Use pre-calculated mercator bounds + const level = { + minX: Math.floor(this._mercatorBounds.west * worldSize), + minY: Math.floor(this._mercatorBounds.north * worldSize), + maxX: Math.ceil(this._mercatorBounds.east * worldSize), + maxY: Math.ceil(this._mercatorBounds.south * worldSize), + }; + + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + /** + * Enhanced PMTiles Source with lifecycle management + */ + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + + // Extract PMTiles-specific options + const pmtilesOptions = { + workerPoolSize: options.workerPoolSize, + tileCacheSize: options.tileCacheSize, + tileCacheMaxMemoryMB: options.tileCacheMaxMemoryMB, + metadataCacheSize: options.metadataCacheSize, + enableSharedProtocols: options.enableSharedProtocols, + requestTimeoutMs: options.requestTimeoutMs, + enableDebugLogging: options.enableDebugLogging, + enablePerformanceMetrics: options.enablePerformanceMetrics, + }; + + // Initialize resource manager + this.resourceManager = new PMTilesResourceManager(pmtilesOptions); + + // Standard source properties + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = _dispatcher; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._implementation = options; + + // Initialize worker pool + this.resourceManager.initializeWorkerPool(_dispatcher); + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + return; + } + + const { url } = options; + this.url = url; + this.tileSize = 512; + + // Get protocol instance + this.protocolInfo = this.resourceManager.getProtocol(url); + if (!this.protocolInfo) { + this.fire( + new ErrorEvent(new Error(`Failed to create protocol for ${url}`)), + ); + return; + } + + this._protocol = this.protocolInfo.protocol; + this._instance = this.protocolInfo.instance; + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + } + + static async getMetadata(url) { + // Check cache first + const cacheKey = `${url}:metadata`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const metadata = await instance.getMetadata(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, metadata); + return metadata; + } + + static async getHeader(url) { + // Check cache first + const cacheKey = `${url}:header`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const header = await instance.getHeader(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, header); + return header; + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (this.resourceManager.destroyed) return; + + if (!tile.destroy) { + tile.destroy = () => {}; + } + if (!tile.abort) { + tile.abort = () => { + tile.aborted = true; + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + }; + } + } + + /** + * Pause tile loading + */ + pause() { + this.resourceManager.pause(); + } + + /** + * Resume tile loading + */ + resume() { + this.resourceManager.resume(); + } + + /** + * Get performance metrics + */ + getMetrics() { + return this.resourceManager.getMetrics(); + } + + /** + * Destroy source and cleanup resources + */ + destroy() { + if (this.protocolInfo && this.url) { + this.resourceManager.releaseProtocol(this.url); + } + + this.resourceManager.destroy(); + this._loaded = false; + } + + async load(callback) { + if (this.resourceManager.destroyed) { + const error = new Error("Source has been destroyed"); + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + // Check metadata cache first + const headerKey = `${this.url}:header`; + const metadataKey = `${this.url}:metadata`; + + let header, tileJSON; + + const cachedHeader = this.resourceManager.getCachedMetadata(headerKey); + const cachedMetadata = + this.resourceManager.getCachedMetadata(metadataKey); + + if (cachedHeader && cachedMetadata) { + header = cachedHeader; + tileJSON = cachedMetadata; + } else { + try { + // Load and cache + [header, tileJSON] = await Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]); + this.resourceManager.setCachedMetadata(headerKey, header); + this.resourceManager.setCachedMetadata(metadataKey, tileJSON); + } catch (error) { + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + } + + try { + extend(this, tileJSON); + this.header = header; + const { tileType, minZoom, maxZoom, minLon, minLat, maxLon, maxLat } = + header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes(this.tileType) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { dataType: "source", sourceDataType: "metadata" }), + ); + this.fire( + new Event("data", { dataType: "source", sourceDataType: "content" }), + ); + } catch (err2) { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + } + } + + loaded() { + return this._loaded && !this.resourceManager.destroyed; + } + + loadVectorTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + const startTime = Date.now(); + var _a2, _b2, _c; + + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + + // Update metrics + this.resourceManager.metrics.tilesLoaded++; + const loadTime = Date.now() - startTime; + this.resourceManager.metrics.averageLoadTimeMs = + (this.resourceManager.metrics.averageLoadTimeMs + loadTime) / 2; + + if (tile.aborted) return callback(null); + + // Handle abort errors gracefully + if (err2 && err2.name === "AbortError") { + return callback(null); + } + + if (err2 && err2.status !== 404) { + return callback(err2); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + // Handle abort errors gracefully + if (error && (error.name === "AbortError" || error.code === 20)) { + return done.call(this, null); + } + done.call(this, error); + return; + } + + params.data = { + cacheControl, + expires, + rawData: data, + }; + + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + // Use shared worker pool + tile.actor = this.resourceManager.getWorkerFromPool(); + + // Fallback to dispatcher if worker pool failed + if (!tile.actor && this.dispatcher) { + try { + tile.actor = this.dispatcher.getActor(); + } catch (error) { + console.warn("[PMTiles] Failed to get fallback worker:", error); + return callback(new Error("No workers available")); + } + } + + if (!tile.actor) { + return callback(new Error("No workers available")); + } + + // Create request with timeout + const requestPromise = this._protocol.tile({ ...request }, afterLoad); + + // Add timeout if configured + if (this.resourceManager.config.requestTimeoutMs > 0) { + const timeoutId = setTimeout(() => { + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + done.call(this, new Error("Request timeout")); + }, this.resourceManager.config.requestTimeoutMs); + + const originalCancel = requestPromise.cancel; + requestPromise.cancel = () => { + clearTimeout(timeoutId); + if (originalCancel) originalCancel(); + }; + } + + tile.request = requestPromise; + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + if (this.resourceManager.destroyed) return; + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + var _a2, _b2; + + // Check tile cache first + const cacheKey = this.resourceManager.getTileCacheKey( + this.url, + tile.tileID.canonical.z, + tile.tileID.canonical.x, + tile.tileID.canonical.y, + ); + + if (this.resourceManager.tileCache.has(cacheKey)) { + this.resourceManager.metrics.cacheHits++; + const cachedData = this.resourceManager.tileCache.get(cacheKey); + this.loadRasterTileData(tile, cachedData); + tile.state = "loaded"; + return callback(null); + } + + this.resourceManager.metrics.cacheMisses++; + + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + + // Optimized raster tile loading - try direct ArrayBuffer first + const arrayBuffer = data.buffer || data; + window + .createImageBitmap(arrayBuffer) + .then((imageBitmap) => { + // Cache the decoded image + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + // Fallback to blob method + const blob = new window.Blob([new Uint8Array(data)], { + type: this.contentType, + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error(`Can't decode image for ${this.id}: ${error}`), + ); + }); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + this.fixTile(tile); + const controller = new AbortController(); + + // Add timeout if configured + let timeoutId; + if (this.resourceManager.config.requestTimeoutMs > 0) { + timeoutId = setTimeout(() => { + controller.abort(); + }, this.resourceManager.config.requestTimeoutMs); + } + + tile.request = { + cancel: () => { + if (timeoutId) clearTimeout(timeoutId); + controller.abort(); + }, + }; + + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (timeoutId) clearTimeout(timeoutId); + + // Handle abort errors gracefully + if (error.name === "AbortError" || error.code === 20) { + delete tile.request; + return callback(null); + } + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Expose cleanup function + PmTilesSource.cleanup = cleanup; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; + global.PMTilesResourceManager = PMTilesResourceManager; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js new file mode 100644 index 0000000..2130749 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js @@ -0,0 +1,459 @@ +/** + * mapbox-pmtiles v1.0.53 + * Original source: https://github.com/am2222/mapbox-pmtiles + * License: MIT + * + * This is a vendored copy of the mapbox-pmtiles library that provides + * PMTiles support for Mapbox GL JS by implementing a custom source type. + * + * Last updated: 2024 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + const worldSize = Math.pow(2, tileID.z); + const level = { + minX: Math.floor(mercatorXFromLng(this.bounds.getWest()) * worldSize), + minY: Math.floor(mercatorYFromLat(this.bounds.getNorth()) * worldSize), + maxX: Math.ceil(mercatorXFromLng(this.bounds.getEast()) * worldSize), + maxY: Math.ceil(mercatorYFromLat(this.bounds.getSouth()) * worldSize), + }; + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = void 0; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._dataType = "vector"; + this.dispatcher = _dispatcher; + this._implementation = options; + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + } + + const { url } = options; + this.reparseOverscaled = true; + this.scheme = "xyz"; + this.tileSize = 512; + this._loaded = false; + this.type = "vector"; + this._protocol = new pmtiles.Protocol(); + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + const pmtilesInstance = new pmtiles.PMTiles(url); + this._protocol.add(pmtilesInstance); + this._instance = pmtilesInstance; + } + + static async getMetadata(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getMetadata(); + } + + static async getHeader(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getHeader(); + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (!tile.destroy) { + tile.destroy = () => {}; + } + } + + async load(callback) { + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + return Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]) + .then(([header, tileJSON]) => { + extend(this, tileJSON); + this.header = header; + const { + specVersion, + clustered, + tileType, + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + centerZoom, + centerLon, + centerLat, + } = header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes( + this.tileType, + ) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "metadata", + }), + ); + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "content", + }), + ); + }) + .catch((err2) => { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + }); + } + + loaded() { + return this._loaded; + } + + loadVectorTile(tile, callback) { + var _a2, _b2, _c; + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + if (tile.aborted) return callback(null); + if (err2 && err2.status !== 404) { + return callback(err2); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + done.call(this, error); + return; + } + params.data = { + cacheControl, + expires, + rawData: data, + }; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + tile.actor = this._tileWorkers[url] = + this._tileWorkers[url] || this.dispatcher.getActor(); + tile.request = this._protocol.tile({ ...request }, afterLoad); + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + var _a2, _b2; + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + const blob = new window.Blob([new Uint8Array(data)], { + type: "image/png", + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error( + `Can't infer data type for ${this.id}, only raster data supported at the moment. ${error}`, + ), + ); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + this.fixTile(tile); + const controller = new AbortController(); + tile.request = { cancel: () => controller.abort() }; + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (error.code === 20) return; + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css new file mode 100644 index 0000000..16b2196 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css @@ -0,0 +1,44 @@ +.maplibregl-compare { + background-color: #fff; + position: absolute; + width: 2px; + height: 100%; + z-index: 1; +} +.maplibregl-compare .compare-swiper-vertical { + background-color: #3887be; + box-shadow: inset 0 0 0 2px #fff; + display: inline-block; + border-radius: 50%; + position: absolute; + width: 60px; + height: 60px; + top: 50%; + left: -30px; + margin: -30px 1px 0; + color: #fff; + cursor: ew-resize; + background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgd2lkdGg9IjYwIiAgIGhlaWdodD0iNjAiICAgdmVyc2lvbj0iMS4xIiAgIHZpZXdCb3g9IjAgMCA2MCA2MCIgICBpZD0ic3ZnNTQzNCIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxK2RldmVsK29zeG1lbnUgcjEyOTExIiAgIHNvZGlwb2RpOmRvY25hbWU9Imwtci5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE1NDQ0Ij4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgICAgPGRjOnRpdGxlPjwvZGM6dGl0bGU+ICAgICAgPC9jYzpXb3JrPiAgICA8L3JkZjpSREY+ICA8L21ldGFkYXRhPiAgPGRlZnMgICAgIGlkPSJkZWZzNTQ0MiIgLz4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTI4NiIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9Ijc1MSIgICAgIGlkPSJuYW1lZHZpZXc1NDQwIiAgICAgc2hvd2dyaWQ9InRydWUiICAgICBpbmtzY2FwZTp6b29tPSI0IiAgICAgaW5rc2NhcGU6Y3g9IjI1Ljg4OTgzMSIgICAgIGlua3NjYXBlOmN5PSIzNC4zODE4MzMiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyMyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjAiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJzdmc1NDM0IiAgICAgaW5rc2NhcGU6b2JqZWN0LW5vZGVzPSJ0cnVlIiAgICAgaW5rc2NhcGU6c25hcC1zbW9vdGgtbm9kZXM9InRydWUiPiAgICA8aW5rc2NhcGU6Z3JpZCAgICAgICB0eXBlPSJ4eWdyaWQiICAgICAgIGlkPSJncmlkNTk4OSIgLz4gIDwvc29kaXBvZGk6bmFtZWR2aWV3PiAgPHBhdGggICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjFweDtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIiAgICAgZD0iTSAyNSAyNCBMIDE2IDMwIEwgMjUgMzYgTCAyNSAyNCB6IE0gMzUgMjQgTCAzNSAzNiBMIDQ0IDMwIEwgMzUgMjQgeiAiICAgICBpZD0icGF0aDU5OTUiIC8+PC9zdmc+); +} + +.maplibregl-compare-horizontal { + position: relative; + width: 100%; + height: 2px; +} +.maplibregl-compare .compare-swiper-horizontal { + background-color: #3887be; + box-shadow: inset 0 0 0 2px #fff; + display: inline-block; + border-radius: 50%; + position: absolute; + width: 60px; + height: 60px; + top: 50%; + left: 50%; + margin: -30px 1px 0; + color: #fff; + cursor: ns-resize; + background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgd2lkdGg9IjYwIiAgIGhlaWdodD0iNjAiICAgdmVyc2lvbj0iMS4xIiAgIHZpZXdCb3g9IjAgMCA2MCA2MCIgICBpZD0ic3ZnNTQzNCIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxK2RldmVsK29zeG1lbnUgcjEyOTExIiAgIHNvZGlwb2RpOmRvY25hbWU9Imwtci5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE1NDQ0Ij4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgICAgPGRjOnRpdGxlPjwvZGM6dGl0bGU+ICAgICAgPC9jYzpXb3JrPiAgICA8L3JkZjpSREY+ICA8L21ldGFkYXRhPiAgPGRlZnMgICAgIGlkPSJkZWZzNTQ0MiIgLz4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTI4NiIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9Ijc1MSIgICAgIGlkPSJuYW1lZHZpZXc1NDQwIiAgICAgc2hvd2dyaWQ9InRydWUiICAgICBpbmtzY2FwZTp6b29tPSI0IiAgICAgaW5rc2NhcGU6Y3g9IjI1Ljg4OTgzMSIgICAgIGlua3NjYXBlOmN5PSIzNC4zODE4MzMiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyMyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjAiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJzdmc1NDM0IiAgICAgaW5rc2NhcGU6b2JqZWN0LW5vZGVzPSJ0cnVlIiAgICAgaW5rc2NhcGU6c25hcC1zbW9vdGgtbm9kZXM9InRydWUiPiAgICA8aW5rc2NhcGU6Z3JpZCAgICAgICB0eXBlPSJ4eWdyaWQiICAgICAgIGlkPSJncmlkNTk4OSIgLz4gIDwvc29kaXBvZGk6bmFtZWR2aWV3PiAgPHBhdGggICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjFweDtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIiAgICAgZD0iTSAyNSAyNCBMIDE2IDMwIEwgMjUgMzYgTCAyNSAyNCB6IE0gMzUgMjQgTCAzNSAzNiBMIDQ0IDMwIEwgMzUgMjQgeiAiICAgICBpZD0icGF0aDU5OTUiIC8+PC9zdmc+); + transform: rotate(90deg); +} diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js new file mode 100644 index 0000000..71e47d5 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js @@ -0,0 +1 @@ +!function o(i,r,s){function h(t,e){if(!r[t]){if(!i[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(u)return u(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=r[t]={exports:{}},i[t][0].call(n.exports,function(e){return h(i[t][1][e]||e)},n,n.exports,o,i,r,s)}return r[t].exports}for(var u="function"==typeof require&&require,e=0;ethis._bounds.width?this._bounds.width:e},_getY:function(e){e=(e=e.touches?e.touches[0]:e).clientY-this._bounds.top;return e=(e=e<0?0:e)>this._bounds.height?this._bounds.height:e},setSlider:function(e){this._setPosition(e)},on:function(e,t){return this._ev.on(e,t),this},fire:function(e,t){return this._ev.emit(e,t),this},off:function(e,t){return this._ev.removeListener(e,t),this},remove:function(){this._clearSync(),this._mapB.off("resize",this._onResize);var e=this._mapA.getContainer();e&&(e.style.clip=null,e.removeEventListener("mousemove",this._onMove));e=this._mapB.getContainer();e&&(e.style.clip=null,e.removeEventListener("mousemove",this._onMove)),this._swiper.removeEventListener("mousedown",this._onDown),this._swiper.removeEventListener("touchstart",this._onDown),this._controlContainer.remove()}},window.maplibregl?maplibregl.Compare=o:void 0!==t&&(t.exports=o)},{"@mapbox/mapbox-gl-sync-move":2,events:3}],2:[function(e,t,n){t.exports=function(){var e=arguments.length;if(1===e)t=arguments[0];else for(var t=[],n=0;nn&&!r.warned&&(r.warned=!0,(n=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit")).name="MaxListenersExceededWarning",n.emitter=e,n.type=t,n.count=r.length,n=n,console&&console.warn&&console.warn(n))),e}function l(e,t,n){e={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},t=function(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}.bind(e);return t.listener=n,e.wrapFn=t}function p(e,t,n){e=e._events;if(void 0===e)return[];t=e[t];return void 0===t?[]:"function"==typeof t?n?[t.listener||t]:[t]:n?function(e){for(var t=new Array(e.length),n=0;n * { + z-index: 2; + position: absolute; + right: 8px; + top: 7px; + display: none; +} + +.maplibregl-ctrl-geocoder, +.maplibregl-ctrl-geocoder .suggestions { + box-shadow: 0 0 10px 2px rgba(0, 0, 0, 0.1); +} + +/* Collapsed */ +.maplibregl-ctrl-geocoder.maplibregl-ctrl-geocoder--collapsed { + width: 50px; + min-width: 50px; + transition: width 0.25s, min-width 0.25s; +} + +/* Suggestions */ +.maplibregl-ctrl-geocoder .suggestions { + background-color: #fff; + border-radius: 4px; + left: 0; + list-style: none; + margin: 0; + padding: 0; + position: absolute; + width: 100%; + top: 110%; /* fallback */ + top: calc(100% + 6px); + z-index: 1000; + overflow: hidden; + font-size: 15px; +} + +.maplibregl-ctrl-bottom-left .suggestions, +.maplibregl-ctrl-bottom-right .suggestions { + top: auto; + bottom: 100%; +} + +.maplibregl-ctrl-geocoder .suggestions > li > a { + cursor: default; + display: block; + padding: 6px 12px; + color: #404040; +} + +.maplibregl-ctrl-geocoder .suggestions > .active > a, +.maplibregl-ctrl-geocoder .suggestions > li > a:hover { + color: #404040; + background-color: #f3f3f3; + text-decoration: none; + cursor: pointer; +} + +.maplibregl-ctrl-geocoder--suggestion { + display: flex; + flex-direction: row; + align-items: center; +} + +.maplibre-ctrl-geocoder--suggestion-icon { + min-width: 30px; + min-height: 24px; + max-width: 30px; + max-height: 24px; + padding-right: 12px; +} + +.maplibregl-ctrl-geocoder--suggestion-info { + display: flex; + flex-direction: column; +} + +.maplibregl-ctrl-geocoder--suggestion-match { + font-weight: bold; +} + +.maplibregl-ctrl-geocoder--suggestion-title, +.maplibregl-ctrl-geocoder--suggestion-address { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +.maplibregl-ctrl-geocoder--result { + display: flex; + flex-direction: row; + align-items: center; +} + +.maplibre-ctrl-geocoder--result-icon { + min-width: 30px; + min-height: 24px; + max-width: 30px; + max-height: 24px; + padding-right: 12px; +} + +.maplibregl-ctrl-geocoder--result-title { + font-weight: bold; +} + +.maplibregl-ctrl-geocoder--result-title, +.maplibregl-ctrl-geocoder--result-address { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +/* Icons */ +.maplibregl-ctrl-geocoder--icon { + display: inline-block; + vertical-align: middle; + speak: none; + fill: #757575; + top: 15px; +} + +.maplibregl-ctrl-geocoder--icon-search { + position: absolute; + top: 13px; + left: 12px; + width: 23px; + height: 23px; +} + +.maplibregl-ctrl-geocoder--button { + padding: 0; + margin: 0; + border: none; + cursor: pointer; + background: #fff; + line-height: 1; +} + +.maplibregl-ctrl-geocoder--icon-close { + width: 20px; + height: 20px; + margin-top: 8px; + margin-right: 3px; +} + +.maplibregl-ctrl-geocoder--button:hover .maplibregl-ctrl-geocoder--icon-close { + fill: #909090; +} + +.maplibregl-ctrl-geocoder--icon-loading { + width: 26px; + height: 26px; + margin-top: 5px; + margin-right: 0px; + -moz-animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); + -webkit-animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); + animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); +} + +/* Animation */ +@-webkit-keyframes rotate { + from { + -webkit-transform: rotate(0); + transform: rotate(0); + } + to { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +@keyframes rotate { + from { + -webkit-transform: rotate(0); + transform: rotate(0); + } + to { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +/* Media queries*/ +@media screen and (min-width: 640px) { + .maplibregl-ctrl-geocoder.maplibregl-ctrl-geocoder--collapsed { + width: 36px; + min-width: 36px; + } + + .maplibregl-ctrl-geocoder { + width: 33.3333%; + font-size: 15px; + line-height: 20px; + max-width: 360px; + } + .maplibregl-ctrl-geocoder .suggestions { + font-size: 13px; + } + + .maplibregl-ctrl-geocoder--icon { + top: 8px; + } + + .maplibregl-ctrl-geocoder--icon-close { + width: 16px; + height: 16px; + margin-top: 3px; + margin-right: 0; + } + + .maplibregl-ctrl-geocoder--icon-search { + left: 7px; + width: 20px; + height: 20px; + } + + .maplibregl-ctrl-geocoder--input { + height: 36px; + padding: 6px 35px; + } + + .maplibregl-ctrl-geocoder--icon-loading { + width: 26px; + height: 26px; + margin-top: -2px; + margin-right: -5px; + } + + .maplibre-gl-geocoder--error { + color: #909090; + padding: 6px 12px; + font-size: 16px; + text-align: center; + } +} diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js new file mode 100644 index 0000000..e285a1a --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js @@ -0,0 +1,2 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.MaplibreGeocoder=t()}}(function(){return function(){function t(e,i,n){function s(o,l){if(!i[o]){if(!e[o]){var a="function"==typeof require&&require;if(!l&&a)return a(o,!0);if(r)return r(o,!0);var h=new Error("Cannot find module '"+o+"'");throw h.code="MODULE_NOT_FOUND",h}var u=i[o]={exports:{}};e[o][0].call(u.exports,function(t){return s(e[o][1][t]||t)},u,u.exports,t,e,i,n)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o
'+e[0]+'
'+e.splice(1,e.length).join(",")+"
"}var i=t.text,n=i.toLowerCase().indexOf(this.query.toLowerCase()),s=this.query.length;return'
'+i.substring(0,n)+''+i.substring(n,n+s)+""+i.substring(n+s)+"
"},popupRender:function(t){var e=t.place_name.split(",");return'"},showResultMarkers:!0,debounceSearch:200},addTo:function(t){function e(t,e){if(!document.body.contains(e))throw new Error("Element provided to #addTo() exists, but is not in the DOM");var i=t.onAdd();e.appendChild(i)}if(t._controlContainer)t.addControl(this);else if(t instanceof HTMLElement)e(this,t);else{if("string"!=typeof t)throw new Error("Error: addTo must be a maplibre-gl-js map, an html element, or a CSS selector query for a single html element");var i=document.querySelectorAll(t);if(0===i.length)throw new Error("Element ",t,"not found.");if(i.length>1)throw new Error("Geocoder can only be added to a single html element");e(this,i[0])}},onAdd:function(t){if(t&&"string"!=typeof t&&(this._map=t),this.setLanguage(),this.options.localGeocoderOnly&&!this.options.localGeocoder)throw new Error("A localGeocoder function must be specified to use localGeocoderOnly mode");this._onChange=this._onChange.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPaste=this._onPaste.bind(this),this._onBlur=this._onBlur.bind(this),this._showButton=this._showButton.bind(this),this._hideButton=this._hideButton.bind(this),this._onQueryResult=this._onQueryResult.bind(this),this.clear=this.clear.bind(this),this._updateProximity=this._updateProximity.bind(this),this._collapse=this._collapse.bind(this),this._unCollapse=this._unCollapse.bind(this),this._clear=this._clear.bind(this),this._clearOnBlur=this._clearOnBlur.bind(this);var e=this.container=document.createElement("div");e.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl";var i=this.createIcon("search",'');this._inputEl=document.createElement("input"),this._inputEl.type="text",this._inputEl.className="mapboxgl-ctrl-geocoder--input maplibregl-ctrl-geocoder--input",this.setPlaceholder(),this.options.collapsed&&(this._collapse(),this.container.addEventListener("mouseenter",this._unCollapse),this.container.addEventListener("mouseleave",this._collapse),this._inputEl.addEventListener("focus",this._unCollapse)),(this.options.collapsed||this.options.clearOnBlur)&&this._inputEl.addEventListener("blur",this._onBlur),this._inputEl.addEventListener("keydown",r(this._onKeyDown,this.options.debounceSearch)),this._inputEl.addEventListener("paste",this._onPaste),this._inputEl.addEventListener("change",this._onChange),this.container.addEventListener("mouseenter",this._showButton),this.container.addEventListener("mouseleave",this._hideButton);var n=document.createElement("div");n.classList.add("mapboxgl-ctrl-geocoder--pin-right","maplibregl-ctrl-geocoder--pin-right"),this._clearEl=document.createElement("button"),this._clearEl.setAttribute("aria-label","Clear"),this._clearEl.addEventListener("click",this.clear),this._clearEl.className="mapboxgl-ctrl-geocoder--button maplibregl-ctrl-geocoder--button";var o=this.createIcon("close",'');return this._clearEl.appendChild(o),this._loadingEl=this.createIcon("loading",''),n.appendChild(this._clearEl),n.appendChild(this._loadingEl),e.appendChild(i),e.appendChild(this._inputEl),e.appendChild(n),this._typeahead=new s(this._inputEl,[],{filter:!1,minLength:this.options.minLength,limit:this.options.limit,noInitialSelection:!0}),this.setRenderFunction(this.options.render),this._typeahead.getItemValue=this.options.getItemValue,this.mapMarker=null,this.resultMarkers=[],this._handleMarker=this._handleMarker.bind(this),this._handleResultMarkers=this._handleResultMarkers.bind(this),this._map&&(this.options.trackProximity&&(this._updateProximity(),this._map.on("moveend",this._updateProximity)),this._maplibregl=this.options.maplibregl,!this._maplibregl&&this.options.marker&&(console.error("No maplibregl detected in options. Map markers are disabled. Please set options.maplibregl."),this.options.marker=!1)),e},createIcon:function(t,e){var i=document.createElementNS("http://www.w3.org/2000/svg","svg");if(i.setAttribute("class","mapboxgl-ctrl-geocoder--icon mapboxgl-ctrl-geocoder--icon-"+t+" maplibregl-ctrl-geocoder--icon maplibregl-ctrl-geocoder--icon-"+t),i.setAttribute("viewBox","0 0 18 18"),i.setAttribute("xml:space","preserve"),i.setAttribute("width",18),i.setAttribute("height",18),"innerHTML"in i)i.innerHTML=e;else{var n=document.createElement("div");n.innerHTML=""+e.valueOf().toString()+"";var s=n.firstChild,r=s.firstChild;i.appendChild(r)}return i},onRemove:function(){return this.container.parentNode.removeChild(this.container),this.options.trackProximity&&this._map&&this._map.off("moveend",this._updateProximity),this._removeMarker(),this._map=null,this},_onPaste:function(t){var e=(t.clipboardData||window.clipboardData).getData("text");e.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(e)},_onKeyDown:function(t){if(27===t.keyCode&&this.options.clearAndBlurOnEsc)return this._clear(t),this._inputEl.blur();var e=t.target&&t.target.shadowRoot?t.target.shadowRoot.activeElement:t.target;if(!(e?e.value:""))return this.fresh=!0,9!==t.keyCode&&this.clear(t),this._clearEl.style.display="none";if(!t.metaKey&&-1===[9,27,37,39,38,40].indexOf(t.keyCode)){if(13===t.keyCode){if(this.options.showResultsWhileTyping)return void(null==this._typeahead.selected&&this.geocoderApi.getSuggestions?this._geocode(e.value,!0):null==this._typeahead.selected&&this.options.showResultMarkers&&this._fitBoundsForMarkers());this._typeahead.selected||this._geocode(e.value)}e.value.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(e.value)}},_showButton:function(){this._inputEl.value.length>0&&(this._clearEl.style.display="block")},_hideButton:function(){this._typeahead.selected&&(this._clearEl.style.display="none")},_onBlur:function(t){this.options.clearOnBlur&&this._clearOnBlur(t),this.options.collapsed&&this._collapse()},_onChange:function(){var t=this._typeahead.selected;if(t&&!t.geometry)t.placeId?this._geocode(t.placeId,!0,!0):this._geocode(t.text,!0);else if(t&&JSON.stringify(t)!==this.lastSelected){if(this._clearEl.style.display="none",this.options.flyTo){var e;if(this._removeResultMarkers(),t.properties&&a[t.properties.short_code])e=o({},this.options.flyTo),this._map&&this._map.fitBounds(a[t.properties.short_code].bbox,e);else if(t.bbox){var i=t.bbox;e=o({},this.options.flyTo),this._map&&this._map.fitBounds([[i[0],i[1]],[i[2],i[3]]],e)}else{var n={zoom:this.options.zoom};e=o({},n,this.options.flyTo),t.center?e.center=t.center:t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(e.center=t.geometry.coordinates),this._map&&this._map.flyTo(e)}}this.options.marker&&this._maplibregl&&this._handleMarker(t),this._inputEl.focus(),this._inputEl.scrollLeft=0,this._inputEl.setSelectionRange(0,0),this.lastSelected=JSON.stringify(t),this._typeahead.selected=null,this._eventEmitter.emit("result",{result:t})}},_getConfigForRequest:function(){var t=["bbox","limit","proximity","countries","types","language","reverseMode"],e=this;return t.reduce(function(t,i){return e.options[i]&&(["countries","types","language"].indexOf(i)>-1?t[i]=e.options[i].split(/[\s,]+/):t[i]=e.options[i],"proximity"===i&&e.options[i]&&"number"==typeof e.options[i].longitude&&"number"==typeof e.options[i].latitude&&(t[i]=[e.options[i].longitude,e.options[i].latitude])),t},{})},_geocode:function(t,e,i){this._loadingEl.style.display="block",this._eventEmitter.emit("loading",{query:t}),this.inputString=t;var n,s=null,r=this._getConfigForRequest();if(this.options.localGeocoderOnly)n=Promise.resolve();else if(this.options.reverseGeocode&&/(-?\d+\.?\d*)[, ]+(-?\d+\.?\d*)[ ]*$/.test(t)){var l=t.split(/[\s(,)?]+/).map(function(t){return parseFloat(t,10)}).reverse();r.types&&r.types[0],r=o(r,{query:l,limit:1}),"proximity"in r&&delete r.proximity,n=this.geocoderApi.reverseGeocode(r)}else r=o(r,{query:t}),n=this.geocoderApi.getSuggestions?e?this.geocoderApi.searchByPlaceId&&i?this.geocoderApi.searchByPlaceId(r):this.geocoderApi.forwardGeocode(r):this.geocoderApi.getSuggestions(r):this.geocoderApi.forwardGeocode(r);var a=[];this.options.localGeocoder&&((a=this.options.localGeocoder(t))||(a=[]));var h=[];return n.catch(function(t){s=t}.bind(this)).then(function(e){this._loadingEl.style.display="none";var i={};return i=e||{type:"FeatureCollection",features:[]},i.config=r,this.fresh&&(this.fresh=!1),i.features=i.features?a.concat(i.features):a,this.options.externalGeocoder?(h=this.options.externalGeocoder(t,i.features,r)||[],h.then(function(t){return i.features=i.features?t.concat(i.features):t,i},function(){return i})):i}.bind(this)).then(function(t){if(s)throw s;this.options.filter&&t.features.length&&(t.features=t.features.filter(this.options.filter));var i=[];i=t.suggestions?t.suggestions:t.place?[t.place]:t.features,i.length?(this._clearEl.style.display="block",this._typeahead.update(i),(!this.options.showResultsWhileTyping||e)&&this.options.showResultMarkers&&(t.features.length>0||t.place)&&this._fitBoundsForMarkers(),this._eventEmitter.emit("results",t)):(this._clearEl.style.display="none",this._typeahead.selected=null,this._renderNoResults(),this._eventEmitter.emit("results",t))}.bind(this)).catch(function(t){this._loadingEl.style.display="none",a.length&&this.options.localGeocoder||h.length&&this.options.externalGeocoder?(this._clearEl.style.display="block",this._typeahead.update(a)):(this._clearEl.style.display="none",this._typeahead.selected=null,this._renderError()),this._eventEmitter.emit("results",{features:a}),this._eventEmitter.emit("error",{error:t})}.bind(this)),n},_clear:function(t){t&&t.preventDefault(),this._inputEl.value="",this._typeahead.selected=null,this._typeahead.clear(),this._onChange(),this._clearEl.style.display="none",this._removeMarker(),this._removeResultMarkers(),this.lastSelected=null,this._eventEmitter.emit("clear"),this.fresh=!0},clear:function(t){this._clear(t),this._inputEl.focus()},_clearOnBlur:function(t){var e=this;t.relatedTarget&&e._clear(t)},_onQueryResult:function(t){var e=t;if(e.features.length){var i=e.features[0];this._typeahead.selected=i,this._inputEl.value=i.place_name,this._onChange()}},_updateProximity:function(){if(this._map)if(this._map.getZoom()>9){var t=this._map.getCenter().wrap();this.setProximity({longitude:t.lng,latitude:t.lat})}else this.setProximity(null)},_collapse:function(){this._inputEl.value||this._inputEl===document.activeElement||this.container.classList.add("mapboxgl-ctrl-geocoder--collapsed","maplibregl-ctrl-geocoder--collapsed")},_unCollapse:function(){this.container.classList.remove("mapboxgl-ctrl-geocoder--collapsed","maplibregl-ctrl-geocoder--collapsed")},query:function(t){return this._geocode(t).then(this._onQueryResult),this},_renderError:function(){this._renderMessage("
There was an error reaching the server
")},_renderNoResults:function(){this._renderMessage("
No results found
")},_renderMessage:function(t){this._typeahead.update([]),this._typeahead.selected=null,this._typeahead.clear(),this._typeahead.renderError(t)},_getPlaceholderText:function(){if(this.options.placeholder)return this.options.placeholder;if(this.options.language){var t=this.options.language.split(",")[0],e=u.language(t),i=h.placeholder[e];if(i)return i}return"Search"},_fitBoundsForMarkers:function(){if(!(this._typeahead.data.length<1)){var t=this._typeahead.data.filter(function(t){return"string"!=typeof t}).slice(0,this.options.limit);if(this._clearEl.style.display="none",this.options.flyTo&&this._maplibregl&&this._map){var e={padding:100},i=o({},e,this.options.flyTo),n=new this._maplibregl.LngLatBounds;t.forEach(function(t){n.extend(t.geometry.coordinates)}),this._map.fitBounds(n.toArray(),i)}return t.length>0&&this._maplibregl&&this._handleResultMarkers(t),this}},setInput:function(t){return this._inputEl.value=t,this._typeahead.selected=null,this._typeahead.clear(),t.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(t),this},setProximity:function(t){return this.options.proximity=t,this},getProximity:function(){return this.options.proximity},setRenderFunction:function(t){return t&&"function"==typeof t&&(this._typeahead.render=t),this},getRenderFunction:function(){return this._typeahead.render},setLanguage:function(t){var e=navigator.language||navigator.userLanguage||navigator.browserLanguage;return this.options.language=t||this.options.language||e,this},getLanguage:function(){return this.options.language},getZoom:function(){return this.options.zoom},setZoom:function(t){return this.options.zoom=t,this},getFlyTo:function(){return this.options.flyTo},setFlyTo:function(t){return this.options.flyTo=t,this},getPlaceholder:function(){return this.options.placeholder},setPlaceholder:function(t){return this.placeholder=t||this._getPlaceholderText(),this._inputEl.placeholder=this.placeholder,this._inputEl.setAttribute("aria-label",this.placeholder),this},getBbox:function(){return this.options.bbox},setBbox:function(t){return this.options.bbox=t,this},getCountries:function(){return this.options.countries},setCountries:function(t){return this.options.countries=t,this},getTypes:function(){return this.options.types},setTypes:function(t){return this.options.types=t,this},getMinLength:function(){return this.options.minLength},setMinLength:function(t){return this.options.minLength=t,this._typeahead&&(this._typeahead.options.minLength=t),this},getLimit:function(){return this.options.limit},setLimit:function(t){return this.options.limit=t,this._typeahead&&(this._typeahead.options.limit=t),this},getFilter:function(){return this.options.filter},setFilter:function(t){return this.options.filter=t,this},setGeocoderApi:function(t){return this.geocoderApi=t,this},getGeocoderApi:function(){return this.geocoderApi},_handleMarker:function(t){if(this._map){this._removeMarker();var e={color:"#4668F2"},i=o({},e,this.options.marker);this.mapMarker=new this._maplibregl.Marker(i);var n;if(this.options.popup){var s={},r=o({},s,this.options.popup);n=new this._maplibregl.Popup(r).setHTML(this.options.popupRender(t))}return t.center?(this.mapMarker.setLngLat(t.center).addTo(this._map),this.options.popup&&this.mapMarker.setPopup(n)):t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(this.mapMarker.setLngLat(t.geometry.coordinates).addTo(this._map),this.options.popup&&this.mapMarker.setPopup(n)),this}},_removeMarker:function(){this.mapMarker&&(this.mapMarker.remove(),this.mapMarker=null)},_handleResultMarkers:function(t){if(this._map){this._removeResultMarkers();var e={color:"#4668F2"},i=o({},e,this.options.showResultMarkers);return t.forEach(function(t){if(this.options.showResultMarkers&&this.options.showResultMarkers.element){var e=this.options.showResultMarkers.element.cloneNode(!0);i=o(i,{element:e})}var n,s=new this._maplibregl.Marker(o({},i,{element:e}));if(this.options.popup){var r={},l=o({},r,this.options.popup);n=new this._maplibregl.Popup(l).setHTML(this.options.popupRender(t))}t.center?(s.setLngLat(t.center).addTo(this._map),this.options.popup&&s.setPopup(n)):t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(s.setLngLat(t.geometry.coordinates).addTo(this._map),this.options.popup&&s.setPopup(n)),this.resultMarkers.push(s)}.bind(this)),this}},_removeResultMarkers:function(){this.resultMarkers&&this.resultMarkers.length>0&&(this.resultMarkers.forEach(function(t){t.remove()}),this.resultMarkers=[])},on:function(t,e){return this._eventEmitter.on(t,e),this},off:function(t,e){return this._eventEmitter.removeListener(t,e),this}},e.exports=n},{"./exceptions":1,"./localization":3,events:4,"lodash.debounce":6,subtag:7,"suggestions-list":8,xtend:11}],3:[function(t,e,i){"use strict";var n={de:"Suche",it:"Ricerca",en:"Search",nl:"Zoeken",fr:"Chercher",ca:"Cerca",he:"לחפש",ja:"サーチ",lv:"Meklēt",pt:"Procurar",sr:"Претрага",zh:"搜索",cs:"Vyhledávání",hu:"Keresés",ka:"ძიება",nb:"Søke",sk:"Vyhľadávanie",th:"ค้นหา",fi:"Hae",is:"Leita",ko:"수색",pl:"Szukaj",sl:"Iskanje",fa:"جستجو",ru:"Поиск"};e.exports={placeholder:n}},{}],4:[function(t,e,i){function n(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=w(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}function s(t){return void 0===t._maxListeners?n.defaultMaxListeners:t._maxListeners}function r(t,e,i){if(e)t.call(i);else for(var n=t.length,s=m(t,n),r=0;r0&&l.length>r){l.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+l.length+' "'+String(e)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=l.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",a.name,a.message)}}else l=o[e]=i,++t._eventsCount;return t}function c(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var t=new Array(arguments.length),e=0;e1&&(e=arguments[1]),e instanceof Error)throw e;var d=new Error('Unhandled "error" event. ('+e+")");throw d.context=e,d}if(!(i=c[t]))return!1;var f="function"==typeof i;switch(n=arguments.length){case 1:r(i,f,this);break;case 2:o(i,f,this,arguments[1]);break;case 3:l(i,f,this,arguments[1],arguments[2]);break;case 4:a(i,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(n-1),u=1;u=0;r--)if(i[r]===e||i[r].listener===e){o=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():g(i,s),1===i.length&&(n[t]=i[0]),n.removeListener&&this.emit("removeListener",t,o||e)}return this},n.prototype.removeAllListeners=function(t){var e,i,n;if(!(i=this._events))return this;if(!i.removeListener)return 0===arguments.length?(this._events=w(null),this._eventsCount=0):i[t]&&(0==--this._eventsCount?this._events=w(null):delete i[t]),this;if(0===arguments.length){var s,r=x(i);for(n=0;n=0;n--)this.removeListener(t,e[n]);return this},n.prototype.listeners=function(t){return d(this,t,!0)},n.prototype.rawListeners=function(t){return d(this,t,!1)},n.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):f.call(t,e)},n.prototype.listenerCount=f,n.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],5:[function(t,e,i){!function(){var t=this,n={};void 0!==i?e.exports=n:t.fuzzy=n,n.simpleFilter=function(t,e){return e.filter(function(e){return n.test(t,e)})},n.test=function(t,e){return null!==n.match(t,e)},n.match=function(t,e,i){i=i||{};var n,s=0,r=[],o=e.length,l=0,a=0,h=i.pre||"",u=i.post||"",c=i.caseSensitive&&e||e.toLowerCase();t=i.caseSensitive&&t||t.toLowerCase();for(var p=0;p=e||i<0||C&&n>=v}function u(){var t=x();if(h(t))return c(t);_=setTimeout(u,a(t))}function c(t){return _=void 0,M&&g?s(t):(g=m=void 0,y)}function p(){void 0!==_&&clearTimeout(_),L=0,g=E=m=_=void 0}function d(){return void 0===_?y:c(x())}function f(){var t=x(),i=h(t);if(g=arguments,m=this,E=t,i){if(void 0===_)return r(E);if(C)return _=setTimeout(u,e),s(E)}return void 0===_&&(_=setTimeout(u,e)),y}var g,m,v,y,_,E,L=0,k=!1,C=!1,M=!0;if("function"!=typeof t)throw new TypeError(l);return e=o(e)||0,n(i)&&(k=!!i.leading,C="maxWait"in i,v=C?b(o(i.maxWait)||0,e):v,M="trailing"in i?!!i.trailing:M),f.cancel=p,f.flush=d,f}function n(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function s(t){return!!t&&"object"==typeof t}function r(t){return"symbol"==typeof t||s(t)&&_.call(t)==h}function o(t){if("number"==typeof t)return t;if(r(t))return a;if(n(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=n(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(u,"");var i=p.test(t);return i||d.test(t)?f(t.slice(2),i?2:8):c.test(t)?a:+t}var l="Expected a function",a=NaN,h="[object Symbol]",u=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,d=/^0o[0-7]+$/i,f=parseInt,g="object"==typeof t&&t&&t.Object===Object&&t,m="object"==typeof self&&self&&self.Object===Object&&self,v=g||m||Function("return this")(),y=Object.prototype,_=y.toString,b=Math.max,w=Math.min,x=function(){return v.Date.now()};e.exports=i}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],7:[function(t,e,i){!function(t,i,n){void 0!==e&&e.exports?e.exports=n():t.subtag=n()}(this,0,function(){function t(t){return t.match(o)||[]}function e(e){return t(e).filter(function(t,e){return t&&e})}function i(e){return e=t(e),{language:e[1]||r,extlang:e[2]||r,script:e[3]||r,region:e[4]||r}}function n(t,e,i){Object.defineProperty(t,e,{value:i,enumerable:!0})}function s(e,s,o){function l(i){return t(i)[e]||r}n(l,"pattern",s),n(i,o,l)}var r="",o=/^([a-zA-Z]{2,3})(?:[_-]+([a-zA-Z]{3})(?=$|[_-]+))?(?:[_-]+([a-zA-Z]{4})(?=$|[_-]+))?(?:[_-]+([a-zA-Z]{2}|[0-9]{3})(?=$|[_-]+))?/;return s(1,/^[a-zA-Z]{2,3}$/,"language"),s(2,/^[a-zA-Z]{3}$/,"extlang"),s(3,/^[a-zA-Z]{4}$/,"script"),s(4,/^[a-zA-Z]{2}$|^[0-9]{3}$/,"region"),n(i,"split",e),i})},{}],8:[function(t,e,i){"use strict";var n=t("./src/suggestions");e.exports=n,"undefined"!=typeof window&&(window.Suggestions=n)},{"./src/suggestions":10}],9:[function(t,e,i){"use strict";var n=function(t){return this.component=t,this.items=[],this.active=t.options.noInitialSelection?-1:0,this.wrapper=document.createElement("div"),this.wrapper.className="suggestions-wrapper",this.element=document.createElement("ul"),this.element.className="suggestions",this.wrapper.appendChild(this.element),this.selectingListItem=!1,t.el.parentNode.insertBefore(this.wrapper,t.el.nextSibling),this};n.prototype.show=function(){this.element.style.display="block"},n.prototype.hide=function(){this.element.style.display="none"},n.prototype.add=function(t){this.items.push(t)},n.prototype.clear=function(){this.items=[],this.active=this.component.options.noInitialSelection?-1:0},n.prototype.isEmpty=function(){return!this.items.length},n.prototype.isVisible=function(){return"block"===this.element.style.display},n.prototype.draw=function(){if(this.element.innerHTML="", +0===this.items.length)return void this.hide();for(var t=0;t=this.items.length-1?0:this.active+1)},n.prototype.drawError=function(t){var e=document.createElement("li");e.innerHTML=t,this.element.appendChild(e),this.show()},e.exports=n},{}],10:[function(t,e,i){"use strict";var n=t("xtend"),s=t("fuzzy"),r=t("./list"),o=function(t,e,i){return i=i||{},this.options=n({minLength:2,limit:5,filter:!0,hideOnBlur:!0,noInitialSelection:!0},i),this.el=t,this.data=e||[],this.list=new r(this),this.query="",this.selected=null,this.list.draw(),this.el.addEventListener("keyup",function(t){this.handleKeyUp(t.keyCode,t)}.bind(this),!1),this.el.addEventListener("keydown",function(t){this.handleKeyDown(t)}.bind(this)),this.el.addEventListener("focus",function(){this.handleFocus()}.bind(this)),this.el.addEventListener("blur",function(){this.handleBlur()}.bind(this)),this.el.addEventListener("paste",function(t){this.handlePaste(t)}.bind(this)),this.render=this.options.render?this.options.render.bind(this):this.render.bind(this),this.getItemValue=this.options.getItemValue?this.options.getItemValue.bind(this):this.getItemValue.bind(this),this};o.prototype.handleKeyUp=function(t,e){if(40!==t&&38!==t&&27!==t&&9!==t)return 13===t?void(this.list.items[this.list.active]&&(this.list.handleMouseUp(this.list.items[this.list.active]),e.stopPropagation())):void this.handleInputChange(this.el.value)},o.prototype.handleKeyDown=function(t){switch(t.keyCode){case 13:this.list.active>=0&&(this.list.selectingListItem=!0);break;case 9:this.list.isEmpty()||(this.list.isVisible()&&t.preventDefault(),this.value(this.list.active>=0?this.list.items[this.list.active].original:null),this.list.hide());break;case 27:this.list.isEmpty()||this.list.hide();break;case 38:this.list.previous();break;case 40:this.list.next()}},o.prototype.handleBlur=function(){!this.list.selectingListItem&&this.options.hideOnBlur&&this.list.hide()},o.prototype.handlePaste=function(t){if(t.clipboardData)this.handleInputChange(t.clipboardData.getData("Text"));else{var e=this;setTimeout(function(){e.handleInputChange(t.target.value)},100)}},o.prototype.handleInputChange=function(t){if(this.query=this.normalize(t),this.list.clear(),this.query.length-1},o.prototype.value=function(t){if(this.selected=t,this.el.value=this.getItemValue(t||{place_name:this.query}),document.createEvent){var e=document.createEvent("HTMLEvents");e.initEvent("change",!0,!1),this.el.dispatchEvent(e)}else this.el.fireEvent("onchange")},o.prototype.getCandidates=function(t){var e,i={pre:"",post:"",extract:function(t){return this.getItemValue(t)}.bind(this)};this.options.filter?(e=s.filter(this.query,this.data,i),e=e.map(function(t){return{original:t.original,string:this.render(t.original,t.string)}}.bind(this))):e=this.data.map(function(t){return{original:t,string:this.render(t)}}.bind(this)),t(e)},o.prototype.getItemValue=function(t){return t},o.prototype.render=function(t,e){if(e)return e;for(var i=t.original?this.getItemValue(t.original):this.getItemValue(t),n=this.normalize(i),s=n.lastIndexOf(this.query);s>-1;){var r=s+this.query.length;i=i.slice(0,s)+""+i.slice(s,r)+""+i.slice(r),s=n.slice(0,s).lastIndexOf(this.query)}return i},o.prototype.renderError=function(t){this.list.drawError(t)},e.exports=o},{"./list":9,fuzzy:5,xtend:11}],11:[function(t,e,i){function n(){for(var t={},e=0;e.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:hsla(0,0%,100%,.5);background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:rgba(0,0,0,.05)}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:hsla(0,0%,100%,.75);border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:rgba(0,0,0,.05)}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px rgba(0,0,0,.35);box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:rgba(0,0,0,.4);color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media (hover:none),(pointer:coarse){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999} \ No newline at end of file diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js new file mode 100644 index 0000000..53dd1e0 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js @@ -0,0 +1,59 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v5.7.2/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory()); +})(this, (function () { 'use strict'; + +/* eslint-disable */ + +var maplibregl = {}; +var modules = {}; +function define(moduleName, _dependencies, moduleFactory) { + modules[moduleName] = moduleFactory; + + // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) + if (moduleName !== 'index') { + return; + } + + // we assume that when an index module is initializing then other modules are loaded already + var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);' + + var sharedModule = {}; + // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) + // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) + // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following + modules.shared(sharedModule); + modules.index(maplibregl, sharedModule); + + if (typeof window !== 'undefined') { + maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); + } + + return maplibregl; +}; + + + +define("shared",["exports"],(function(t){"use strict";function e(t,e,r,n){return new(r||(r=Promise))((function(i,s){function a(t){try{l(n.next(t));}catch(t){s(t);}}function o(t){try{l(n.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(a,o);}l((n=n.apply(t,e||[])).next());}))}function r(t,e){this.x=t,this.y=e;}function n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,s;"function"==typeof SuppressedError&&SuppressedError,r.prototype={clone(){return new r(this.x,this.y)},add(t){return this.clone()._add(t)},sub(t){return this.clone()._sub(t)},multByPoint(t){return this.clone()._multByPoint(t)},divByPoint(t){return this.clone()._divByPoint(t)},mult(t){return this.clone()._mult(t)},div(t){return this.clone()._div(t)},rotate(t){return this.clone()._rotate(t)},rotateAround(t,e){return this.clone()._rotateAround(t,e)},matMult(t){return this.clone()._matMult(t)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(t){return this.x===t.x&&this.y===t.y},dist(t){return Math.sqrt(this.distSqr(t))},distSqr(t){const e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle(){return Math.atan2(this.y,this.x)},angleTo(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith(t){return this.angleWithSep(t.x,t.y)},angleWithSep(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult(t){const e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add(t){return this.x+=t.x,this.y+=t.y,this},_sub(t){return this.x-=t.x,this.y-=t.y,this},_mult(t){return this.x*=t,this.y*=t,this},_div(t){return this.x/=t,this.y/=t,this},_multByPoint(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint(t){return this.x/=t.x,this.y/=t.y,this},_unit(){return this._div(this.mag()),this},_perp(){const t=this.y;return this.y=this.x,this.x=-t,this},_rotate(t){const e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround(t,e){const r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:r},r.convert=function(t){if(t instanceof r)return t;if(Array.isArray(t))return new r(+t[0],+t[1]);if(void 0!==t.x&&void 0!==t.y)return new r(+t.x,+t.y);throw new Error("Expected [x, y] or {x, y} point format")};var a=function(){if(s)return i;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return s=1,i=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},i}(),o=n(a);let l,u;function c(){return null==l&&(l="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),l}function h(){if(null==u&&(u=!1,c())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:!0});if(e){for(let r=0;r4&&void 0!==arguments[4]?arguments[4]:"zyx",s=Math.PI/360;e*=s,n*=s,r*=s;var a=Math.sin(e),o=Math.cos(e),l=Math.sin(r),u=Math.cos(r),c=Math.sin(n),h=Math.cos(n);switch(i){case "xyz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "xzy":t[0]=a*u*h-o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h+a*l*c;break;case "yxz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;case "yzx":t[0]=a*u*h+o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h-a*l*c;break;case "zxy":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "zyx":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;default:throw new Error("Unknown angle order "+i)}return t}function I(){var t=new f(2);return f!=Float32Array&&(t[0]=0,t[1]=0),t}function z(t,e){var r=new f(2);return r[0]=t,r[1]=e,r}m(),_=new f(4),f!=Float32Array&&(_[0]=0,_[1]=0,_[2]=0,_[3]=0),m(),x(1,0,0),x(0,1,0),k(),k(),d(),I();const P=8192;function C(t,e,r){return e*(P/(t.tileSize*Math.pow(2,r-t.tileID.overscaledZ)))}function E(t,e){return (t%e+e)%e}function T(t,e,r){return t*(1-r)+e*r}function B(t){if(t<=0)return 0;if(t>=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function V(t,e,r,n){const i=new o(t,e,r,n);return t=>i.solve(t)}const F=V(.25,.1,.25,1);function $(t,e,r){return Math.min(r,Math.max(e,t))}function D(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function L(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let O=1;function R(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function U(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}function j(t){return Array.isArray(t)?t.map(j):"object"==typeof t&&t?R(t,j):t}const N={};function q(t){N[t]||("undefined"!=typeof console&&console.warn(t),N[t]=!0);}function G(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function X(t){return "undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}let Z=null;function Y(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const H="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function K(t,r,n,i,s){return e(this,void 0,void 0,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const e=new VideoFrame(t,{timestamp:0});try{const a=null==e?void 0:e.format;if(!a||!a.startsWith("BGR")&&!a.startsWith("RGB"))throw new Error(`Unrecognized format ${a}`);const o=a.startsWith("BGR"),l=new Uint8ClampedArray(i*s*4);if(yield e.copyTo(l,function(t,e,r,n,i){const s=4*Math.max(-e,0),a=(Math.max(0,r)-r)*n*4+s,o=4*n,l=Math.max(0,e),u=Math.max(0,r);return {rect:{x:l,y:u,width:Math.min(t.width,e+n)-l,height:Math.min(t.height,r+i)-u},layout:[{offset:a,stride:o}]}}(t,r,n,i,s)),o)for(let t=0;t{t.removeEventListener(e,r,n);}}}function tt(t){return t*Math.PI/180}function et(t){return t/Math.PI*180}const rt={touchstart:!0,touchmove:!0,touchmoveWindow:!0,touchend:!0,touchcancel:!0},nt={dblclick:!0,click:!0,mouseover:!0,mouseout:!0,mousedown:!0,mousemove:!0,mousemoveWindow:!0,mouseup:!0,mouseupWindow:!0,contextmenu:!0,wheel:!0},it="AbortError";function st(){return new Error(it)}const at={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function ot(t){return at.REGISTERED_PROTOCOLS[t.substring(0,t.indexOf("://"))]}const lt="global-dispatcher";class ut extends Error{constructor(t,e,r,n){super(`AJAXError: ${e} (${t}): ${r}`),this.status=t,this.statusText=e,this.url=r,this.body=n;}}const ct=()=>X(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,ht=function(t,r){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const e=ot(t.url);if(e)return e(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:lt},r)}if(!(/^file:/.test(n=t.url)||/^file:/.test(ct())&&!/^\w+:/.test(n))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,r){return e(this,void 0,void 0,(function*(){const e=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:ct(),signal:r.signal});let n,i;"json"!==t.type||e.headers.has("Accept")||e.headers.set("Accept","application/json");try{n=yield fetch(e);}catch(e){throw new ut(0,e.message,t.url,new Blob)}if(!n.ok){const e=yield n.blob();throw new ut(n.status,n.statusText,t.url,e)}i="arrayBuffer"===t.type||"image"===t.type?n.arrayBuffer():"json"===t.type?n.json():n.text();const s=yield i;if(r.signal.aborted)throw st();return {data:s,cacheControl:n.headers.get("Cache-Control"),expires:n.headers.get("Expires")}}))}(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:!0,targetMapId:lt},r)}var n;return function(t,e){return new Promise(((r,n)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,!0),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||void 0===i?void 0:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{n(new Error(s.statusText));},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response);}catch(t){return void n(t)}r({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires")});}else {const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});n(new ut(s.status,s.statusText,t.url,e));}},e.signal.addEventListener("abort",(()=>{s.abort(),n(st());})),s.send(t.body);}))}(t,r)};function pt(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return !0;const e=new URL(t),r=window.location;return e.protocol===r.protocol&&e.host===r.host}function ft(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function dt(t,e,r){if(r&&r[t]){const n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}class yt{constructor(t,e={}){L(this,e),this.type=t;}}class mt extends yt{constructor(t,e={}){super("error",L({error:t},e));}}class gt{on(t,e){return this._listeners=this._listeners||{},ft(t,e,this._listeners),{unsubscribe:()=>{this.off(t,e);}}}off(t,e){return dt(t,e,this._listeners),dt(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},ft(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new yt(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)dt(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(L(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof mt&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var xt={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},state:{type:"state",default:{}},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},"font-faces":{type:"array",value:"fontFaces"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},"color-relief":{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_color-relief","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const vt=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function bt(t,e){const r={};for(const e in t)"ref"!==e&&(r[e]=t[e]);return vt.forEach((t=>{t in e&&(r[t]=e[t]);})),r}function wt(t,e){if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return !1;for(let r=0;r`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const Jt=[Vt,Ft,$t,Dt,Lt,Ot,Nt,Rt,Ht(Ut),qt,Xt,Gt,Zt,Yt];function Wt(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Wt(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of Jt)if(!Wt(t,e))return null}return `Expected ${Kt(t)} but found ${Kt(e)} instead.`}function Qt(t,e){return e.some((e=>e.kind===t.kind))}function te(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function ee(t,e){return "array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const re=.96422,ne=.82521,ie=4/29,se=6/29,ae=3*se*se,oe=se*se*se,le=Math.PI/180,ue=180/Math.PI;function ce(t){return (t%=360)<0&&(t+=360),t}function he([t,e,r,n]){let i,s;const a=fe((.2225045*(t=pe(t))+.7168786*(e=pe(e))+.0606169*(r=pe(r)))/1);t===e&&e===r?i=s=a:(i=fe((.4360747*t+.3850649*e+.1430804*r)/re),s=fe((.0139322*t+.0971045*e+.7141733*r)/ne));const o=116*a-16;return [o<0?0:o,500*(i-a),200*(a-s),n]}function pe(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function fe(t){return t>oe?Math.pow(t,1/3):t/ae+ie}function de([t,e,r,n]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,a=isNaN(r)?i:i-r/200;return i=1*me(i),s=re*me(s),a=ne*me(a),[ye(3.1338561*s-1.6168667*i-.4906146*a),ye(-.9787684*s+1.9161415*i+.033454*a),ye(.0719453*s-.2289914*i+1.4052427*a),n]}function ye(t){return (t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function me(t){return t>se?t*t*t:ae*(t-ie)}const ge=Object.hasOwn||function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};function xe(t,e){return ge(t,e)?t[e]:void 0}function ve(t){return parseInt(t.padEnd(2,t),16)/255}function be(t,e){return we(e?t/100:t,0,1)}function we(t,e,r){return Math.min(Math.max(e,t),r)}function _e(t){return !t.some(Number.isNaN)}const Se={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function Ae(t,e,r){return t+r*(e-t)}function ke(t,e,r){return t.map(((t,n)=>Ae(t,e[n],r)))}class Me{constructor(t,e,r,n=1,i=!0){this.r=t,this.g=e,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[t,e,r,n]));}static parse(t){if(t instanceof Me)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return [0,0,0,0];const e=xe(Se,t);if(e){const[t,r,n]=e;return [t/255,r/255,n/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let r=1;return [ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,r,n,i,s,a,o,l,u,c,h,p]=e,f=[i||" ",o||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[n,a,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[we(+r/e,0,1),we(+s/e,0,1),we(+l/e,0,1),h?be(+h,p):1];if(_e(t))return t}}return}}const r=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[t,e,n,i,s,a,o,l,u]=r,c=[n||" ",s||" ",o].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,we(+i,0,100),we(+a,0,100),l?be(+l,u):1];if(_e(t))return function([t,e,r,n]){function i(n){const i=(n+t/30)%12,s=e*Math.min(r,1-r);return r-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=ce(t),e/=100,r/=100,[i(0),i(8),i(4),n]}(t)}}}(t);return e?new Me(...e,!1):void 0}get rgb(){const{r:t,g:e,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[t/i,e/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,r,n,i]=he(t),s=Math.sqrt(r*r+n*n);return [Math.round(1e4*s)?ce(Math.atan2(n,r)*ue):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",he(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,r,n]=this.rgb;return `rgba(${[t,e,r].map((t=>Math.round(255*t))).join(",")},${n})`}static interpolate(t,e,r,n="rgb"){switch(n){case "rgb":{const[n,i,s,a]=ke(t.rgb,e.rgb,r);return new Me(n,i,s,a,!1)}case "hcl":{const[n,i,s,a]=t.hcl,[o,l,u,c]=e.hcl;let h,p;if(isNaN(n)||isNaN(o))isNaN(n)?isNaN(o)?h=NaN:(h=o,1!==s&&0!==s||(p=l)):(h=n,1!==u&&0!==u||(p=i));else {let t=o-n;o>n&&t>180?t-=360:o180&&(t+=360),h=n+r*t;}const[f,d,y,m]=function([t,e,r,n]){return t=isNaN(t)?0:t*le,de([r,Math.cos(t)*e,Math.sin(t)*e,n])}([h,null!=p?p:Ae(i,l,r),Ae(s,u,r),Ae(a,c,r)]);return new Me(f,d,y,m,!1)}case "lab":{const[n,i,s,a]=de(ke(t.lab,e.lab,r));return new Me(n,i,s,a,!1)}}}}Me.black=new Me(0,0,0,1),Me.white=new Me(1,1,1,1),Me.transparent=new Me(0,0,0,0),Me.red=new Me(1,0,0,1);class Ie{constructor(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const ze=["bottom","center","top"];class Pe{constructor(t,e,r,n,i,s){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i,this.verticalAlign=s;}}class Ce{constructor(t){this.sections=t;}static fromString(t){return new Ce([new Pe(t,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof Ce?t:Ce.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class Ee{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Ee)return t;if("number"==typeof t)return new Ee([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]];}return new Ee(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Ee(ke(t.values,e.values,r))}}class Te{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Te)return t;if("number"==typeof t)return new Te([t]);if(Array.isArray(t)){for(const e of t)if("number"!=typeof e)return;return new Te(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Te(ke(t.values,e.values,r))}}class Be{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Be)return t;if("string"==typeof t){const e=Me.parse(t);if(!e)return;return new Be([e])}if(!Array.isArray(t))return;const e=[];for(const r of t){if("string"!=typeof r)return;const t=Me.parse(r);if(!t)return;e.push(t);}return new Be(e)}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r,n="rgb"){const i=[];if(t.values.length!=e.values.length)throw new Error(`colorArray: Arrays have mismatched length (${t.values.length} vs. ${e.values.length}), cannot interpolate.`);for(let s=0;s=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Re(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof Le||t instanceof Me||t instanceof Ie||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De)return !0;if(Array.isArray(t)){for(const e of t)if(!Re(e))return !1;return !0}if("object"==typeof t){for(const e in t)if(!Re(t[e]))return !1;return !0}return !1}function Ue(t){if(null===t)return Vt;if("string"==typeof t)return $t;if("boolean"==typeof t)return Dt;if("number"==typeof t)return Ft;if(t instanceof Me)return Lt;if(t instanceof Le)return Ot;if(t instanceof Ie)return jt;if(t instanceof Ce)return Nt;if(t instanceof Ee)return qt;if(t instanceof Te)return Xt;if(t instanceof Be)return Gt;if(t instanceof $e)return Yt;if(t instanceof De)return Zt;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=Ue(e);if(r){if(r===t)continue;r=Ut;break}r=t;}return Ht(r||Ut,e)}return Rt}function je(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof Me||t instanceof Le||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De?t.toString():JSON.stringify(t)}class Ne{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Re(t[1]))return e.error("invalid value");const r=t[1];let n=Ue(r);const i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new Ne(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return !0}}const qe={string:$t,number:Ft,boolean:Dt,object:Rt};class Ge{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r,n=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const r=t[1];if("string"!=typeof r||!(r in qe)||"object"===r)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=qe[r],n++;}else i=Ut;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],n++;}r=Ht(i,s);}else {if(!qe[i])throw new Error(`Types doesn't contain name = ${i}`);r=qe[i];}const s=[];for(;nt.outputDefined()))}}const Xe={"to-boolean":Dt,"to-color":Lt,"to-number":Ft,"to-string":$t};class Ze{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[0];if(!Xe[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");const n=Xe[r],i=[];for(let r=1;r4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:Oe(e[0],e[1],e[2],e[3]),!r))return new Me(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new Ve(r||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "padding":{let e;for(const r of this.args){e=r.evaluate(t);const n=Ee.parse(e);if(n)return n}throw new Ve(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "numberArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Te.parse(e);if(n)return n}throw new Ve(`Could not parse numberArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "colorArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Be.parse(e);if(n)return n}throw new Ve(`Could not parse colorArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "variableAnchorOffsetCollection":{let e;for(const r of this.args){e=r.evaluate(t);const n=$e.parse(e);if(n)return n}throw new Ve(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "number":{let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new Ve(`Could not convert ${JSON.stringify(e)} to number.`)}case "formatted":return Ce.fromString(je(this.args[0].evaluate(t)));case "resolvedImage":return De.fromString(je(this.args[0].evaluate(t)));case "projectionDefinition":return this.args[0].evaluate(t);default:return je(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}const Ye=["Unknown","Point","LineString","Polygon"];class He{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null;}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?Ye[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache.get(t);return e||(e=Me.parse(t),this._parseColorCache.set(t,e)),e}}class Ke{constructor(t,e,r=[],n,i=new Bt,s=[]){this.registry=t,this.path=r,this.key=r.map((t=>`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=n,this._isConstant=e;}parse(t,e,r,n,i={}){return e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return "assert"===r?new Ge(e,[t]):"coerce"===r?new Ze(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const n=t[0];if("string"!=typeof n)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[n];if(i){let n=i.parse(t,this);if(!n)return null;if(this.expectedType){const t=this.expectedType,i=n.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind){if("projectionDefinition"===t.kind&&["string","array"].includes(i.kind)||["color","formatted","resolvedImage"].includes(t.kind)&&["value","string"].includes(i.kind)||["padding","numberArray"].includes(t.kind)&&["value","number","array"].includes(i.kind)||"colorArray"===t.kind&&["value","string","array"].includes(i.kind)||"variableAnchorOffsetCollection"===t.kind&&["value","array"].includes(i.kind))n=r(n,t,e.typeAnnotation||"coerce");else if(this.checkSubtype(t,i))return null}else n=r(n,t,e.typeAnnotation||"assert");}if(!(n instanceof Ne)&&"resolvedImage"!==n.type.kind&&this._isConstant(n)){const t=new He;try{n=new Ne(n.type,n.evaluate(t));}catch(t){return this.error(t.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Ke(this.registry,this._isConstant,n,e||null,i,this.errors)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new Tt(r,t));}checkSubtype(t,e){const r=Wt(t,e);return r&&this.error(r),r}}class Je{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new Ve(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new Ve(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return !1}}class tr{constructor(t,e){this.type=Dt,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);return r&&n?Qt(r.type,[Dt,$t,Ft,Vt,Ut])?new tr(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);if(!te(r,["string","array"]))throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return !0}}class er{constructor(t,e,r){this.type=Ft,this.needle=t,this.haystack=e,this.fromIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);if(!r||!n)return null;if(!Qt(r.type,[Dt,$t,Ft,Vt,Ut]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new er(r,n,i):null}return new er(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(t)),te(r,["string"])){const t=r.indexOf(e,n);return -1===t?-1:[...r.slice(0,t)].length}if(te(r,["array"]))return r.indexOf(e,n);throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return !1}}class rr{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(r){if(u.checkSubtype(r,Ue(t)))return null}else r=Ue(t);if(void 0!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length;}const c=e.parse(l,a,n);if(!c)return null;n=n||c.type,s.push(c);}const a=e.parse(t[1],1,Ut);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,n);return o?"value"!==a.type.kind&&e.concat(1).checkSubtype(r,a.type)?null:new rr(r,n,a,i,s,o):null}evaluate(t){const e=this.input.evaluate(t);return (Ue(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class nr{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class ir{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ft);if(!r||!n)return null;if(!Qt(r.type,[Ht(Ut),$t,Ut]))return e.error(`Expected first argument to be of type array or string, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new ir(r.type,r,n,i):null}return new ir(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);let n;if(this.endIndex&&(n=this.endIndex.evaluate(t)),te(e,["string"]))return [...e].slice(r,n).join("");if(te(e,["array"]))return e.slice(r,n);throw new Ve(`Expected first argument to be of type array or string, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return !1}}function sr(t,e){const r=t.length-1;let n,i,s=0,a=r,o=0;for(;s<=a;)if(o=Math.floor((s+a)/2),n=t[o],i=t[o+1],n<=e){if(o===r||ee))throw new Ve("Input is not a number.");a=o-1;}return 0}class ar{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',o);const u=e.parse(a,l,i);if(!u)return null;i=i||u.type,n.push([s,u]);}return new ar(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[sr(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function or(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var lr,ur,cr=function(){if(ur)return lr;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return ur=1,lr=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},lr}(),hr=or(cr);class pr{constructor(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e);}static interpolationFactor(t,e,r,n){let i=0;if("exponential"===t.name)i=fr(e,t.base,r,n);else if("linear"===t.name)i=fr(e,1,r,n);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new hr(s[0],s[1],s[2],s[3]).solve(fr(e,1,r,n));}return i}static parse(t,e){let[r,n,i,...s]=t;if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){const t=n[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:t};}else {if("cubic-bezier"!==n[0])return e.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const t=n.slice(1);if(4!==t.length||t.some((t=>"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,Ft),!i)return null;const a=[];let o=null;"interpolate-hcl"!==r&&"interpolate-lab"!==r||e.expectedType==Gt?e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType):o=Lt;for(let t=0;t=r)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,o);if(!u)return null;o=o||u.type,a.push([r,u]);}return ee(o,Ft)||ee(o,Ot)||ee(o,Lt)||ee(o,qt)||ee(o,Xt)||ee(o,Gt)||ee(o,Yt)||ee(o,Ht(Ft))?new pr(o,r,n,i,a):e.error(`Type ${Kt(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=sr(e,n),a=pr.interpolationFactor(this.interpolation,n,e[s],e[s+1]),o=r[s].evaluate(t),l=r[s+1].evaluate(t);switch(this.operator){case "interpolate":switch(this.type.kind){case "number":return Ae(o,l,a);case "color":return Me.interpolate(o,l,a);case "padding":return Ee.interpolate(o,l,a);case "colorArray":return Be.interpolate(o,l,a);case "numberArray":return Te.interpolate(o,l,a);case "variableAnchorOffsetCollection":return $e.interpolate(o,l,a);case "array":return ke(o,l,a);case "projectionDefinition":return Le.interpolate(o,l,a)}case "interpolate-hcl":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"hcl");case "colorArray":return Be.interpolate(o,l,a,"hcl")}case "interpolate-lab":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"lab");case "colorArray":return Be.interpolate(o,l,a,"lab")}}}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function fr(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}const dr={color:Me.interpolate,number:Ae,padding:Ee.interpolate,numberArray:Te.interpolate,colorArray:Be.interpolate,variableAnchorOffsetCollection:$e.interpolate,array:ke};class yr{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r=null;const n=e.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const n of t.slice(1)){const t=e.parse(n,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!t)return null;r=r||t.type,i.push(t);}if(!r)throw new Error("No output type");const s=n&&i.some((t=>Wt(n,t.type)));return new yr(s?Ut:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(t),r&&r instanceof De&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break;return r}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function mr(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function gr(t,e,r,n){return 0===n.compare(e,r)}function xr(t,e,r){const n="=="!==t&&"!="!==t;return class i{constructor(t,e,r){this.type=Dt,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const r=t[0];let s=e.parse(t[1],1,Ut);if(!s)return null;if(!mr(r,s.type))return e.concat(1).error(`"${r}" comparisons are not supported for type '${Kt(s.type)}'.`);let a=e.parse(t[2],2,Ut);if(!a)return null;if(!mr(r,a.type))return e.concat(2).error(`"${r}" comparisons are not supported for type '${Kt(a.type)}'.`);if(s.type.kind!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error(`Cannot compare types '${Kt(s.type)}' and '${Kt(a.type)}'.`);n&&("value"===s.type.kind&&"value"!==a.type.kind?s=new Ge(a.type,[s]):"value"!==s.type.kind&&"value"===a.type.kind&&(a=new Ge(s.type,[a])));let o=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error("Cannot use collator to compare non-string types.");if(o=e.parse(t[3],3,jt),!o)return null}return new i(s,a,o)}evaluate(i){const s=this.lhs.evaluate(i),a=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=Ue(s),r=Ue(a);if(e.kind!==r.kind||"string"!==e.kind&&"number"!==e.kind)throw new Ve(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=Ue(s),r=Ue(a);if("string"!==t.kind||"string"!==r.kind)return e(i,s,a)}return this.collator?r(i,s,a,this.collator.evaluate(i)):e(i,s,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return !0}}}const vr=xr("==",(function(t,e,r){return e===r}),gr),br=xr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !gr(0,e,r,n)})),wr=xr("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),Sr=xr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),Ar=xr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class kr{constructor(t,e,r){this.type=jt,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");const n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,Dt);if(!n)return null;const i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Dt);if(!i)return null;let s=null;return r.locale&&(s=e.parse(r.locale,1,$t),!s)?null:new kr(n,i,s)}evaluate(t){return new Ie(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);}outputDefined(){return !1}}class Mr{constructor(t,e,r,n,i){this.type=$t,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=e.parse(n.locale,1,$t),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,$t),!s))return null;let a=null;if(n["min-fraction-digits"]&&(a=e.parse(n["min-fraction-digits"],1,Ft),!a))return null;let o=null;return n["max-fraction-digits"]&&(o=e.parse(n["max-fraction-digits"],1,Ft),!o)?null:new Mr(r,i,s,a,o)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return !1}}class Ir{constructor(t){this.type=Nt,this.sections=t;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");const n=[];let i=!1;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&"object"==typeof s&&!Array.isArray(s)){i=!1;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,Ft),!t))return null;let r=null;if(s["text-font"]&&(r=e.parse(s["text-font"],1,Ht($t)),!r))return null;let a=null;if(s["text-color"]&&(a=e.parse(s["text-color"],1,Lt),!a))return null;let o=null;if(s["vertical-align"]){if("string"==typeof s["vertical-align"]&&!ze.includes(s["vertical-align"]))return e.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${s["vertical-align"]}' instead.`);if(o=e.parse(s["vertical-align"],1,$t),!o)return null}const l=n[n.length-1];l.scale=t,l.font=r,l.textColor=a,l.verticalAlign=o;}else {const s=e.parse(t[r],1,Ut);if(!s)return null;const a=s.type.kind;if("string"!==a&&"value"!==a&&"null"!==a&&"resolvedImage"!==a)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:s,scale:null,font:null,textColor:null,verticalAlign:null});}}return new Ir(n)}evaluate(t){return new Ce(this.sections.map((e=>{const r=e.content.evaluate(t);return Ue(r)===Zt?new Pe("",r,null,null,null,e.verticalAlign?e.verticalAlign.evaluate(t):null):new Pe(je(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null,e.verticalAlign?e.verticalAlign.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor),e.verticalAlign&&t(e.verticalAlign);}outputDefined(){return !1}}class zr{constructor(t){this.type=Zt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,$t);return r?new zr(r):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),r=De.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r}eachChild(t){t(this.input);}outputDefined(){return !1}}class Pr{constructor(t){this.type=Ft,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${Kt(r.type)} instead.`):new Pr(r):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return [...e].length;if(Array.isArray(e))return e.length;throw new Ve(`Expected value to be of type string or array, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return !1}}const Cr=8192;function Er(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*Cr),Math.round(n*i*Cr)]}function Tr(t,e){const r=Math.pow(2,e.z);return [(i=(t[0]/Cr+e.x)/r,360*i-180),(n=(t[1]/Cr+e.y)/r,360/Math.PI*Math.atan(Math.exp((180-360*n)*Math.PI/180))-90)];var n,i;}function Br(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function Vr(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function Fr(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],a=t[1]-r[1];return n*a-s*i==0&&n*s<=0&&i*a<=0}function $r(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!jr(t,e,r,n)||!jr(r,n,t,e));var i,s;}function Dr(t,e,r){for(const n of r)for(let r=0;r(i=t)[1]!=(a=o[e+1])[1]>i[1]&&i[0]<(a[0]-s[0])*(i[1]-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}var i,s,a;return n}function Or(t,e){for(const r of e)if(Lr(t,r))return !0;return !1}function Rr(t,e){for(const r of t)if(!Lr(r,e))return !1;for(let r=0;r0&&o<0||a<0&&o>0}function Nr(t,e,r){const n=[];for(let i=0;ir[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i;}Br(e,t);}function Xr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];Gr(n,e,r,i),a.push(n);}return a}function Zr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];Br(e,r),t.push(r);}a.push(t);}if(e[2]-e[0]<=i/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const n of t)Gr(n,e,r,i);}var o;return a}class Yr{constructor(t,e){this.type=Dt,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const r of e.features){const{type:e,coordinates:n}=r.geometry;"Polygon"===e&&t.push(n),"MultiPolygon"===e&&t.push(...n);}if(t.length)return new Yr(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new Yr(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new Yr(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Lr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Or(t,s))return !1}return !0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Rr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Ur(t,s))return !1}return !0}(t,this.geometries)}return !1}eachChild(){}outputDefined(){return !0}}let Hr=class{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}};function Kr(t,e,r=0,n=t.length-1,i=Wr){for(;n>r;){if(n-r>600){const s=n-r+1,a=e-r+1,o=Math.log(s),l=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*l*(s-l)/s)*(a-s/2<0?-1:1);Kr(t,e,Math.max(r,Math.floor(e-a*l/s+u)),Math.min(n,Math.floor(e+(s-a)*l/s+u)),i);}const s=t[e];let a=r,o=n;for(Jr(t,r,e),i(t[n],s)>0&&Jr(t,r,n);a0;)o--;}0===i(t[r],s)?Jr(t,r,o):(o++,Jr(t,o,n)),o<=e&&(r=o+1),e<=o&&(n=o-1);}}function Jr(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function Wr(t,e){return te?1:0}function Qr(t,e){if(t.length<=1)return [t];const r=[];let n,i;for(const e of t){const t=en(e);0!==t&&(e.area=Math.abs(t),void 0===i&&(i=t<0),i===t<0?(n&&r.push(n),n=[e]):n.push(e));}if(n&&r.push(n),e>1)for(let t=0;t1?(l=t[o+1][0],u=t[o+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function on(t,e){return e[0]-t[0]}function ln(t){return t[1]-t[0]+1}function un(t,e){return t[1]>=t[0]&&t[1]t[1])return [null,null];const r=ln(t);if(e){if(2===r)return [t,null];const e=Math.floor(r/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===r)return [t,null];const n=Math.floor(r/2)-1;return [[t[0],t[0]+n],[t[0]+n+1,t[1]]]}function hn(t,e){if(!un(e,t.length))return [1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=e[0];n<=e[1];++n)Br(r,t[n]);return r}function pn(t){const e=[1/0,1/0,-1/0,-1/0];for(const r of t)for(const t of r)Br(e,t);return e}function fn(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function dn(t,e,r){if(!fn(t)||!fn(e))return NaN;let n=0,i=0;return t[2]e[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if(Vr(i,s)){if(wn(t,e))return 0}else if(wn(e,t))return 0;let a=1/0;for(const n of t)for(let t=0,i=n.length,s=i-1;t0;){const i=a.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(ln(l)<=u){if(!un(l,t.length))return NaN;if(e){const e=bn(t,l,r,n);if(isNaN(e)||0===e)return e;s=Math.min(s,e);}else for(let e=l[0];e<=l[1];++e){const i=vn(t[e],r,n);if(s=Math.min(s,i),0===s)return 0}}else {const r=cn(l,e);Sn(a,s,n,t,o,r[0]),Sn(a,s,n,t,o,r[1]);}}return s}function Mn(t,e,r,n,i,s=1/0){let a=Math.min(s,i.distance(t[0],r[0]));if(0===a)return a;const o=new Hr([[0,[0,t.length-1],[0,r.length-1]]],on);for(;o.length>0;){const s=o.pop();if(s[0]>=a)continue;const l=s[1],u=s[2],c=e?50:100,h=n?50:100;if(ln(l)<=c&&ln(u)<=h){if(!un(l,t.length)&&un(u,r.length))return NaN;let s;if(e&&n)s=gn(t,l,r,u,i),a=Math.min(a,s);else if(e&&!n){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=yn(r[t],e,i),a=Math.min(a,s),0===a)return a}else if(!e&&n){const e=r.slice(u[0],u[1]+1);for(let r=l[0];r<=l[1];++r)if(s=yn(t[r],e,i),a=Math.min(a,s),0===a)return a}else s=xn(t,l,r,u,i),a=Math.min(a,s);}else {const s=cn(l,e),c=cn(u,n);An(o,a,i,t,r,s[0],c[0]),An(o,a,i,t,r,s[0],c[1]),An(o,a,i,t,r,s[1],c[0]),An(o,a,i,t,r,s[1],c[1]);}}return a}function In(t){return "MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class zn{constructor(t,e){this.type=Ft,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new zn(e,e.features.map((t=>In(t.geometry))).flat());if("Feature"===e.type)return new zn(e,In(e.geometry));if("type"in e&&"coordinates"in e)return new zn(e,In(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!1,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!1,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!1,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!0,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!0,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!0,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const r=t.geometry();if(0===r.length||0===r[0].length)return NaN;const n=Qr(r,0).map((e=>e.map((e=>e.map((e=>Tr([e.x,e.y],t.canonical))))))),i=new an(n[0][0][0][1]);let s=1/0;for(const t of e)for(const e of n){switch(t.type){case "Point":s=Math.min(s,kn([t.coordinates],!1,e,i,s));break;case "LineString":s=Math.min(s,kn(t.coordinates,!0,e,i,s));break;case "Polygon":s=Math.min(s,_n(e,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return !0}}class Pn{constructor(t){this.type=Ut,this.key=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=t[1];return null==r?e.error("Global state property must be defined."):"string"!=typeof r?e.error(`Global state property must be string, but found ${typeof t[1]} instead.`):new Pn(r)}evaluate(t){var e;const r=null===(e=t.globals)||void 0===e?void 0:e.globalState;return r&&0!==Object.keys(r).length?xe(r,this.key):null}eachChild(){}outputDefined(){return !1}}const Cn={"==":vr,"!=":br,">":_r,"<":wr,">=":Ar,"<=":Sr,array:Ge,at:Qe,boolean:Ge,case:nr,coalesce:yr,collator:kr,format:Ir,image:zr,in:tr,"index-of":er,interpolate:pr,"interpolate-hcl":pr,"interpolate-lab":pr,length:Pr,let:Je,literal:Ne,match:rr,number:Ge,"number-format":Mr,object:Ge,slice:ir,step:ar,string:Ge,"to-boolean":Ze,"to-color":Ze,"to-number":Ze,"to-string":Ze,var:We,within:Yr,distance:zn,"global-state":Pn};class En{constructor(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return !1}static parse(t,e){const r=t[0],n=En.definitions[r];if(!n)return e.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let o=null;for(const[n,s]of a){o=new Ke(e.registry,$n,e.path,null,e.scope);const a=[];let l=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(Kt).join(", ")})`:`(${Kt(e.type)}...)`;var e;})).join(" | "),n=[];for(let r=1;r{r=e?r&&$n(t):r&&t instanceof Ne;})),!!r&&Dn(t)&&On(t,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function Dn(t){if(t instanceof En){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}if(t instanceof Yr)return !1;if(t instanceof zn)return !1;let e=!0;return t.eachChild((t=>{e&&!Dn(t)&&(e=!1);})),e}function Ln(t){if(t instanceof En&&"feature-state"===t.name)return !1;let e=!0;return t.eachChild((t=>{e&&!Ln(t)&&(e=!1);})),e}function On(t,e){if(t instanceof En&&e.indexOf(t.name)>=0)return !1;let r=!0;return t.eachChild((t=>{r&&!On(t,e)&&(r=!1);})),r}function Rn(t){return {result:"success",value:t}}function Un(t){return {result:"error",value:t}}function jn(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Nn(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function qn(t){return !!t.expression&&t.expression.interpolated}function Gn(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Xn(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)&&Ue(t)===Rt}function Zn(t){return t}function Yn(t,e){const r=t.stops&&"object"==typeof t.stops[0][0],n=r||!(r||void 0!==t.property),i=t.type||(qn(e)?"exponential":"interval"),s=function(t){switch(t.type){case "color":return Me.parse;case "padding":return Ee.parse;case "numberArray":return Te.parse;case "colorArray":return Be.parse;default:return null}}(e);if(s&&((t=Et({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],s(t[1])]))),t.default=s(t.default?t.default:e.default)),t.colorSpace&&"rgb"!==(a=t.colorSpace)&&"hcl"!==a&&"lab"!==a)throw new Error(`Unknown color space: "${t.colorSpace}"`);var a;const o=function(t){switch(t){case "exponential":return Wn;case "interval":return Jn;case "categorical":return Kn;case "identity":return Qn;default:throw new Error(`Unknown function type "${t}"`)}}(i);let l,u;if("categorical"===i){l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0];}if(r){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>Wn({stops:i,base:t.base},e,r).evaluate(r,n)}}if(n){const r="exponential"===i?{name:"exponential",base:void 0!==t.base?t.base:1}:null;return {kind:"camera",interpolationType:r,interpolationFactor:pr.interpolationFactor.bind(void 0,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>o(t,e,r,l,u)}}return {kind:"source",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:void 0;return void 0===i?Hn(t.default,e.default):o(t,e,i,l,u)}}}function Hn(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Kn(t,e,r,n,i){return Hn(typeof r===i?n[r]:void 0,t.default,e.default)}function Jn(t,e,r){if("number"!==Gn(r))return Hn(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=sr(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function Wn(t,e,r){const n=void 0!==t.base?t.base:1;if("number"!==Gn(r))return Hn(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=sr(t.stops.map((t=>t[0])),r),a=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),o=t.stops[s][1],l=t.stops[s+1][1],u=dr[e.type]||Zn;return "function"==typeof o.evaluate?{evaluate(...e){const r=o.evaluate.apply(void 0,e),n=l.evaluate.apply(void 0,e);if(void 0!==r&&void 0!==n)return u(r,n,a,t.colorSpace)}}:u(o,l,a,t.colorSpace)}function Qn(t,e,r){switch(e.type){case "color":r=Me.parse(r);break;case "formatted":r=Ce.fromString(r.toString());break;case "resolvedImage":r=De.fromString(r.toString());break;case "padding":r=Ee.parse(r);break;case "colorArray":r=Be.parse(r);break;case "numberArray":r=Te.parse(r);break;default:Gn(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0);}return Hn(r,t.default,e.default)}En.register(Cn,{error:[{kind:"error"},[$t],(t,[e])=>{throw new Ve(e.evaluate(t))}],typeof:[$t,[Ut],(t,[e])=>Kt(Ue(e.evaluate(t)))],"to-rgba":[Ht(Ft,4),[Lt],(t,[e])=>{const[r,n,i,s]=e.evaluate(t).rgb;return [255*r,255*n,255*i,s]}],rgb:[Lt,[Ft,Ft,Ft],Tn],rgba:[Lt,[Ft,Ft,Ft,Ft],Tn],has:{type:Dt,overloads:[[[$t],(t,[e])=>Bn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Bn(e.evaluate(t),r.evaluate(t))]]},get:{type:Ut,overloads:[[[$t],(t,[e])=>Vn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Vn(e.evaluate(t),r.evaluate(t))]]},"feature-state":[Ut,[$t],(t,[e])=>Vn(e.evaluate(t),t.featureState||{})],properties:[Rt,[],t=>t.properties()],"geometry-type":[$t,[],t=>t.geometryType()],id:[Ut,[],t=>t.id()],zoom:[Ft,[],t=>t.globals.zoom],"heatmap-density":[Ft,[],t=>t.globals.heatmapDensity||0],elevation:[Ft,[],t=>t.globals.elevation||0],"line-progress":[Ft,[],t=>t.globals.lineProgress||0],accumulated:[Ut,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[Ft,Fn(Ft),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],"*":[Ft,Fn(Ft),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],"-":{type:Ft,overloads:[[[Ft,Ft],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[Ft],(t,[e])=>-e.evaluate(t)]]},"/":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],"%":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[Ft,[],()=>Math.LN2],pi:[Ft,[],()=>Math.PI],e:[Ft,[],()=>Math.E],"^":[Ft,[Ft,Ft],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[Ft,[Ft],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))],log2:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[Ft,[Ft],(t,[e])=>Math.sin(e.evaluate(t))],cos:[Ft,[Ft],(t,[e])=>Math.cos(e.evaluate(t))],tan:[Ft,[Ft],(t,[e])=>Math.tan(e.evaluate(t))],asin:[Ft,[Ft],(t,[e])=>Math.asin(e.evaluate(t))],acos:[Ft,[Ft],(t,[e])=>Math.acos(e.evaluate(t))],atan:[Ft,[Ft],(t,[e])=>Math.atan(e.evaluate(t))],min:[Ft,Fn(Ft),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[Ft,Fn(Ft),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[Ft,[Ft],(t,[e])=>Math.abs(e.evaluate(t))],round:[Ft,[Ft],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[Ft,[Ft],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[Ft,[Ft],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[Dt,[$t,Ut],(t,[e,r])=>t.properties()[e.value]===r.value],"filter-id-==":[Dt,[Ut],(t,[e])=>t.id()===e.value],"filter-type-==":[Dt,[$t],(t,[e])=>t.geometryType()===e.value],"filter-<":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],"filter-<=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],"filter->=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],"filter-has":[Dt,[Ut],(t,[e])=>e.value in t.properties()],"filter-has-id":[Dt,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[Dt,[Ht($t)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[Dt,[Ht(Ut)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[Dt,[$t,Ht(Ut)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[Dt,[$t,Ht(Ut)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(!r.evaluate(t))return !1;return !0}]]},any:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(r.evaluate(t))return !0;return !1}]]},"!":[Dt,[Dt],(t,[e])=>!e.evaluate(t)],"is-supported-script":[Dt,[$t],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return !r||r(e.evaluate(t))}],upcase:[$t,[$t],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[$t,[$t],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[$t,Fn(Ut),(t,e)=>e.map((e=>je(e.evaluate(t)))).join("")],"resolved-locale":[$t,[jt],(t,[e])=>e.evaluate(t).resolvedLocale()]});class ti{constructor(t,e,r){this.expression=t,this._warningHistory={},this._evaluator=new He,this._defaultValue=e?function(t){if("color"===t.type&&Xn(t.default))return new Me(0,0,0,0);switch(t.type){case "color":return Me.parse(t.default)||null;case "padding":return Ee.parse(t.default)||null;case "numberArray":return Te.parse(t.default)||null;case "colorArray":return Be.parse(t.default)||null;case "variableAnchorOffsetCollection":return $e.parse(t.default)||null;case "projectionDefinition":return Le.parse(t.default)||null;default:return void 0===t.default?null:t.default}}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null,this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s){this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new Ve(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function ei(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Cn}function ri(t,e,r){const n=new Ke(Cn,$n,[],e?function(t){const e={color:Lt,string:$t,number:Ft,enum:$t,boolean:Dt,formatted:Nt,padding:qt,numberArray:Xt,colorArray:Gt,projectionDefinition:Ot,resolvedImage:Zt,variableAnchorOffsetCollection:Yt};return "array"===t.type?Ht(e[t.value]||Ut,t.length):e[t.type]}(e):void 0),i=n.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return i?Rn(new ti(i,e,r)):Un(n.errors)}class ni{constructor(t,e,r){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}}class ii{constructor(t,e,r,n,i){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this.interpolationType=n,this._globalState=i;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?pr.interpolationFactor(this.interpolationType,t,e,r):0}}function si(t,e,r){const n=ri(t,e,r);if("error"===n.result)return n;const i=n.value.expression,s=Dn(i);if(!s&&!jn(e))return Un([new Tt("","data expressions not supported")]);const a=On(i,["zoom"]);if(!a&&!Nn(e))return Un([new Tt("","zoom expressions not supported")]);const o=oi(i);return o||a?o instanceof Tt?Un([o]):o instanceof pr&&!qn(e)?Un([new Tt("",'"interpolate" expressions cannot be used with this property')]):Rn(o?new ii(s?"camera":"composite",n.value,o.labels,o instanceof pr?o.interpolation:void 0,r):new ni(s?"constant":"source",n.value,r)):Un([new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class ai{constructor(t,e){this._parameters=t,this._specification=e,Et(this,Yn(this._parameters,this._specification));}static deserialize(t){return new ai(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function oi(t){let e=null;if(t instanceof Je)e=oi(t.result);else if(t instanceof yr){for(const r of t.args)if(e=oi(r),e)break}else (t instanceof ar||t instanceof pr)&&t.input instanceof En&&"zoom"===t.input.name&&(e=t);return e instanceof Tt||t.eachChild((t=>{const r=oi(t);r instanceof Tt?e=r:!e&&r?e=new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&r&&e!==r&&(e=new Tt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),e}function li(t,e=new Set){return t instanceof Pn&&e.add(t.key),t.eachChild((t=>{li(t,e);})),e}function ui(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case "has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case "in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case "!in":case "!has":case "none":return !1;case "==":case "!=":case ">":case ">=":case "<":case "<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case "any":case "all":for(const e of t.slice(1))if(!ui(e)&&"boolean"!=typeof e)return !1;return !0;default:return !0}}const ci={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function hi(t,e){if(null==t)return {filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};ui(t)||(t=di(t));const r=ri(t,ci,e);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return {filter:(t,e,n)=>r.value.evaluate(t,e,{},n),needGeometry:fi(t),getGlobalStateRefs:()=>li(r.value.expression)}}function pi(t,e){return te?1:0}function fi(t){if(!Array.isArray(t))return !1;if("within"===t[0]||"distance"===t[0])return !0;for(let e=1;e"===e||"<="===e||">="===e?yi(t[1],t[2],e):"any"===e?(r=t.slice(1),["any"].concat(r.map(di))):"all"===e?["all"].concat(t.slice(1).map(di)):"none"===e?["all"].concat(t.slice(1).map(di).map(xi)):"in"===e?mi(t[1],t.slice(2)):"!in"===e?xi(mi(t[1],t.slice(2))):"has"===e?gi(t[1]):"!has"!==e||xi(gi(t[1]));var r;}function yi(t,e,r){switch(t){case "$type":return [`filter-type-${r}`,e];case "$id":return [`filter-id-${r}`,e];default:return [`filter-${r}`,t,e]}}function mi(t,e){if(0===e.length)return !1;switch(t){case "$type":return ["filter-type-in",["literal",e]];case "$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(pi)]]:["filter-in-small",t,["literal",e]]}}function gi(t){switch(t){case "$type":return !0;case "$id":return ["filter-has-id"];default:return ["filter-has",t]}}function xi(t){return ["!",t]}function vi(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const r of t)e+=`${vi(r)},`;return `${e}]`}const r=Object.keys(t).sort();let n="{";for(let e=0;en.maximum?[new Ct(e,r,`${r} is greater than the maximum value ${n.maximum}`)]:[]}function Ii(t){const e=t.valueSpec,r=_i(t.value.type);let n,i,s,a={};const o="categorical"!==r&&void 0===t.value.property,l=!o,u="array"===Gn(t.value.stops)&&"array"===Gn(t.value.stops[0])&&"object"===Gn(t.value.stops[0][0]),c=Ai({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===r)return [new Ct(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const n=t.value;return e=e.concat(ki({key:t.key,value:n,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===Gn(n)&&0===n.length&&e.push(new Ct(t.key,n,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===r&&o&&c.push(new Ct(t.key,t.value,'missing required property "property"')),"identity"===r||t.value.stops||c.push(new Ct(t.key,t.value,'missing required property "stops"')),"exponential"===r&&t.valueSpec.expression&&!qn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!jn(t.valueSpec)?c.push(new Ct(t.key,t.value,"property functions not supported")):o&&!Nn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"zoom functions not supported"))),"categorical"!==r&&!u||void 0!==t.value.property||c.push(new Ct(t.key,t.value,'"property" property is required')),c;function h(t){let r=[];const n=t.value,o=t.key;if("array"!==Gn(n))return [new Ct(o,n,`array expected, ${Gn(n)} found`)];if(2!==n.length)return [new Ct(o,n,`array length 2 expected, length ${n.length} found`)];if(u){if("object"!==Gn(n[0]))return [new Ct(o,n,`object expected, ${Gn(n[0])} found`)];if(void 0===n[0].zoom)return [new Ct(o,n,"object stop key must have zoom")];if(void 0===n[0].value)return [new Ct(o,n,"object stop key must have value")];if(s&&s>_i(n[0].zoom))return [new Ct(o,n[0].zoom,"stop zoom values must appear in ascending order")];_i(n[0].zoom)!==s&&(s=_i(n[0].zoom),i=void 0,a={}),r=r.concat(Ai({key:`${o}[0]`,value:n[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Mi,value:p}}));}else r=r.concat(p({key:`${o}[0]`,value:n[0],validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},n));return ei(Si(n[1]))?r.concat([new Ct(`${o}[1]`,n[1],"expressions are not allowed in function stops.")]):r.concat(t.validateSpec({key:`${o}[1]`,value:n[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const o=Gn(t.value),l=_i(t.value),u=null!==t.value?t.value:s;if(n){if(o!==n)return [new Ct(t.key,u,`${o} stop domain type must match previous stop domain type ${n}`)]}else n=o;if("number"!==o&&"string"!==o&&"boolean"!==o)return [new Ct(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==o&&"categorical"!==r){let n=`number expected, ${o} found`;return jn(e)&&void 0===r&&(n+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new Ct(t.key,u,n)]}return "categorical"!==r||"number"!==o||isFinite(l)&&Math.floor(l)===l?"categorical"!==r&&"number"===o&&void 0!==i&&lnew Ct(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new Ct(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!On(r,["zoom","feature-state"]))return [new Ct(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!Dn(r))return [new Ct(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function Pi(t){const e=t.key,r=t.value,n=Gn(r);return "string"!==n?[new Ct(e,r,`color expected, ${n} found`)]:Me.parse(String(r))?[]:[new Ct(e,r,`color expected, "${r}" found`)]}function Ci(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${n.values.join(", ")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${Object.keys(n.values).join(", ")}], ${JSON.stringify(r)} found`)),i}function Ei(t){return ui(Si(t.value))?zi(Et({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):Ti(t)}function Ti(t){const e=t.value,r=t.key;if("array"!==Gn(e))return [new Ct(r,e,`array expected, ${Gn(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return [new Ct(r,e,"filter array must have at least 1 element")];switch(s=s.concat(Ci({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),_i(e[0])){case "<":case "<=":case ">":case ">=":e.length>=2&&"$type"===_i(e[1])&&s.push(new Ct(r,e,`"$type" cannot be use with operator "${e[0]}"`));case "==":case "!=":3!==e.length&&s.push(new Ct(r,e,`filter array for operator "${e[0]}" must have 3 elements`));case "in":case "!in":e.length>=2&&(i=Gn(e[1]),"string"!==i&&s.push(new Ct(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let a=2;a{t in r&&e.push(new Ct(n,r[t],`"${t}" is prohibited for ref layers`));})),i.layers.forEach((e=>{_i(e.id)===o&&(t=e);})),t?t.ref?e.push(new Ct(n,r.ref,"ref cannot reference another ref layer")):a=_i(t.type):e.push(new Ct(n,r.ref,`ref layer "${o}" not found`));}else if("background"!==a)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&_i(t.type);t?"vector"===s&&"raster"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster source`)):"raster-dem"!==s&&"hillshade"===a||"raster-dem"!==s&&"color-relief"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster-dem source`)):"raster"===s&&"raster"!==a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a vector source`)):"vector"!==s||r["source-layer"]?"raster-dem"===s&&"hillshade"!==a&&"color-relief"!==a?e.push(new Ct(n,r.source,"raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.")):"line"!==a||!r.paint||!r.paint["line-gradient"]||"geojson"===s&&t.lineMetrics||e.push(new Ct(n,r,`layer "${r.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new Ct(n,r,`layer "${r.id}" must specify a "source-layer"`)):e.push(new Ct(n,r.source,`source "${r.source}" not found`));}else e.push(new Ct(n,r,'missing required property "source"'));return e=e.concat(Ai({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:r,objectKey:"type"}),filter:Ei,layout:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Fi(Et({layerType:a},t))}}),paint:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Vi(Et({layerType:a},t))}})}})),e}function Di(t){const e=t.value,r=t.key,n=Gn(e);return "string"!==n?[new Ct(r,e,`string expected, ${n} found`)]:[]}const Li={promoteId:function({key:t,value:e}){if("string"===Gn(e))return Di({key:t,value:e});{const r=[];for(const n in e)r.push(...Di({key:`${t}.${n}`,value:e[n]}));return r}}};function Oi(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return [new Ct(r,e,'"type" is required')];const a=_i(e.type);let o;switch(a){case "vector":case "raster":return o=Ai({key:r,value:e,valueSpec:n[`source_${a.replace("-","_")}`],style:t.style,styleSpec:n,objectElementValidators:Li,validateSpec:s}),o;case "raster-dem":return o=function(t){var e;const r=null!==(e=t.sourceName)&&void 0!==e?e:"",n=t.value,i=t.styleSpec,s=i.source_raster_dem,a=t.style;let o=[];const l=Gn(n);if(void 0===n)return o;if("object"!==l)return o.push(new Ct("source_raster_dem",n,`object expected, ${l} found`)),o;const u="custom"===_i(n.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in n)!u&&c.includes(e)?o.push(new Ct(e,n[e],`In "${r}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?o=o.concat(t.validateSpec({key:e,value:n[e],valueSpec:s[e],validateSpec:t.validateSpec,style:a,styleSpec:i})):o.push(new Ct(e,n[e],`unknown property "${e}"`));return o}({sourceName:r,value:e,style:t.style,styleSpec:n,validateSpec:s}),o;case "geojson":if(o=Ai({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,validateSpec:s,objectElementValidators:Li}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],s="string"==typeof n?[n,["accumulated"],["get",t]]:n;o.push(...zi({key:`${r}.${t}.map`,value:i,expressionContext:"cluster-map"})),o.push(...zi({key:`${r}.${t}.reduce`,value:s,expressionContext:"cluster-reduce"}));}return o;case "video":return Ai({key:r,value:e,valueSpec:n.source_video,style:i,validateSpec:s,styleSpec:n});case "image":return Ai({key:r,value:e,valueSpec:n.source_image,style:i,validateSpec:s,styleSpec:n});case "canvas":return [new Ct(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Ci({key:`${r}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]}})}}function Ri(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("light",e,`object expected, ${a} found`)]),s;for(const a in e){const o=a.match(/^(.*)-transition$/);s=s.concat(o&&n[o[1]]&&n[o[1]].transition?t.validateSpec({key:a,value:e[a],valueSpec:r.transition,validateSpec:t.validateSpec,style:i,styleSpec:r}):n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);}return s}function Ui(t){const e=t.value,r=t.styleSpec,n=r.sky,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("sky",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a}function ji(t){const e=t.value,r=t.styleSpec,n=r.terrain,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("terrain",e,`object expected, ${a} found`)]),s;for(const a in e)s=s.concat(n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);return s}function Ni(t){let e=[];const r=t.value,n=t.key;if(Array.isArray(r)){const i=[],s=[];for(const a in r)r[a].id&&i.includes(r[a].id)&&e.push(new Ct(n,r,`all the sprites' ids must be unique, but ${r[a].id} is duplicated`)),i.push(r[a].id),r[a].url&&s.includes(r[a].url)&&e.push(new Ct(n,r,`all the sprites' URLs must be unique, but ${r[a].url} is duplicated`)),s.push(r[a].url),e=e.concat(Ai({key:`${n}[${a}]`,value:r[a],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:t.validateSpec}));return e}return Di({key:n,value:r})}function qi(t){return e=t.value,Boolean(e)&&e.constructor===Object?[]:[new Ct(t.key,t.value,`object expected, ${Gn(t.value)} found`)];var e;}const Gi={"*":()=>[],array:ki,boolean:function(t){const e=t.value,r=t.key,n=Gn(e);return "boolean"!==n?[new Ct(r,e,`boolean expected, ${n} found`)]:[]},number:Mi,color:Pi,constants:wi,enum:Ci,filter:Ei,function:Ii,layer:$i,object:Ai,source:Oi,light:Ri,sky:Ui,terrain:ji,projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("projection",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a},projectionDefinition:function(t){const e=t.key;let r=t.value;r=r instanceof String?r.valueOf():r;const n=Gn(r);return "array"!==n||function(t){return Array.isArray(t)&&3===t.length&&"string"==typeof t[0]&&"string"==typeof t[1]&&"number"==typeof t[2]}(r)||function(t){return !!["interpolate","step","literal"].includes(t[0])}(r)?["array","string"].includes(n)?[]:[new Ct(e,r,`projection expected, invalid type "${n}" found`)]:[new Ct(e,r,`projection expected, invalid array ${JSON.stringify(r)} found`)]},string:Di,formatted:function(t){return 0===Di(t).length?[]:zi(t)},resolvedImage:function(t){return 0===Di(t).length?[]:zi(t)},padding:function(t){const e=t.key,r=t.value;if("array"===Gn(r)){if(r.length<1||r.length>4)return [new Ct(e,r,`padding requires 1 to 4 values; ${r.length} values found`)];const n={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(r=r.concat(wi({key:"constants",value:t.constants}))),Ki(r)}function Hi(t){return function(e){return t({...e,validateSpec:Xi})}}function Ki(t){return [].concat(t).sort(((t,e)=>t.line-e.line))}function Ji(t){return function(...e){return Ki(t.apply(this,e))}}Yi.source=Ji(Hi(Oi)),Yi.sprite=Ji(Hi(Ni)),Yi.glyphs=Ji(Hi(Zi)),Yi.light=Ji(Hi(Ri)),Yi.sky=Ji(Hi(Ui)),Yi.terrain=Ji(Hi(ji)),Yi.state=Ji(Hi(qi)),Yi.layer=Ji(Hi($i)),Yi.filter=Ji(Hi(Ei)),Yi.paintProperty=Ji(Hi(Vi)),Yi.layoutProperty=Ji(Hi(Fi));const Wi=Yi,Qi=Wi.light,ts=Wi.sky,es=Wi.paintProperty,rs=Wi.layoutProperty;function ns(t,e){let r=!1;if(e&&e.length)for(const n of e)t.fire(new mt(new Error(n.message))),r=!0;return r}class is{constructor(t,e,r){const n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(let t=0;t=u[l+0]&&n>=u[l+1])?(a[h]=!0,s.push(i[h])):a[h]=!1;}}}}_forEachCell(t,e,r,n,i,s,a,o){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!o||o(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,r,n,u,s,a,o))return}}_convertFromCellCoord(t){return (t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let r=0;for(let t=0;t=0)continue;const s=t[n];i[n]=ss[r].shallow.indexOf(n)>=0?s:cs(s,e);}t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==r&&(i.$name=r),i}function hs(t){if(us(t))return t;if(Array.isArray(t))return t.map(hs);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=ls(t)||"Object";if(!ss[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:r}=ss[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const r of Object.keys(t)){if("$name"===r)continue;const i=t[r];n[r]=ss[e].shallow.indexOf(r)>=0?i:hs(i);}return n}class ps{constructor(){this.first=!0;}update(t,e){const r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Hiragana:t=>t>=12352&&t<=12447,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"CJK Unified Ideographs":t=>t>=19968&&t<=40959,"Hangul Syllables":t=>t>=44032&&t<=55215,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function ds(t){for(const e of t)if(bs(e.charCodeAt(0)))return !0;return !1}function ys(t){for(const e of t)if(!xs(e.charCodeAt(0)))return !1;return !0}function ms(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const gs=ms(["Arab","Dupl","Mong","Ougr","Syrc"]);function xs(t){return !gs.test(String.fromCodePoint(t))}const vs=ms(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function bs(t){return !(746!==t&&747!==t&&(t<4352||!(fs["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||fs["CJK Compatibility"](t)||fs["CJK Strokes"](t)||!(!fs["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||fs["Enclosed CJK Letters and Months"](t)||fs["Ideographic Description Characters"](t)||fs.Kanbun(t)||fs.Katakana(t)&&12540!==t||!(!fs["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!fs["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||fs["Vertical Forms"](t)||fs["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||vs.test(String.fromCodePoint(t)))))}function ws(t){return !(bs(t)||function(t){return !!(fs["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||fs["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||fs["Letterlike Symbols"](t)||fs["Number Forms"](t)||fs["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||fs["Control Pictures"](t)&&9251!==t||fs["Optical Character Recognition"](t)||fs["Enclosed Alphanumerics"](t)||fs["Geometric Shapes"](t)||fs["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||fs["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||fs["CJK Symbols and Punctuation"](t)||fs.Katakana(t)||fs["Private Use Area"](t)||fs["CJK Compatibility Forms"](t)||fs["Small Form Variants"](t)||fs["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}const _s=ms(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Ss(t){return _s.test(String.fromCodePoint(t))}function As(t,e){return !(!e&&Ss(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||fs.Khmer(t))}function ks(t){for(const e of t)if(Ss(e.charCodeAt(0)))return !0;return !1}const Ms=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{};}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL;}getState(){return {pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){if(Ms.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText,this.loadScriptResolve();}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(t,r){return e(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if("loading"!==t.pluginStatus)return this.setState(t),t;const e=t.pluginURL,n=new Promise((t=>{this.loadScriptResolve=t;}));r(e);const i=new Promise((t=>setTimeout((()=>t()),this.TIMEOUT)));if(yield Promise.race([n,i]),this.isParsed()){const t={pluginStatus:"loaded",pluginURL:e};return this.setState(t),t}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${e}`)}))}};class Is{constructor(t,e){this.isSupportedScript=zs,this.zoom=t,e?(this.now=e.now||0,this.fadeDuration=e.fadeDuration||0,this.zoomHistory=e.zoomHistory||new ps,this.transition=e.transition||{}):(this.now=0,this.fadeDuration=0,this.zoomHistory=new ps,this.transition={});}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}}}function zs(t){return function(t,e){for(const r of t)if(!As(r.charCodeAt(0),e))return !1;return !0}(t,"loaded"===Ms.getRTLTextPluginStatus())}class Ps{constructor(t,e,r){this.property=t,this.value=e,this.expression=function(t,e,r){if(Xn(t))return new ai(t,e);if(ei(t)){const n=si(t,e,r);if("error"===n.result)throw new Error(n.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return n.value}{let r=t;return "color"===e.type&&"string"==typeof t?r=Me.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"numberArray"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"colorArray"!==e.type||"string"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)?r=$e.parse(t):"projectionDefinition"===e.type&&"string"==typeof t&&(r=Le.parse(t)):r=Be.parse(t):r=Te.parse(t):r=Ee.parse(t),{globalStateRefs:new Set,_globalState:null,kind:"constant",evaluate:()=>r}}}(void 0===e?t.specification.default:e,t.specification,r);}isDataDriven(){return "source"===this.expression.kind||"composite"===this.expression.kind}getGlobalStateRefs(){return this.expression.globalStateRefs||new Set}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class Cs{constructor(t,e){this.property=t,this.value=new Ps(t,void 0,e);}transitioned(t,e){return new Ts(this.property,this.value,e,L({},t.transition,this.transition),t.now)}untransitioned(){return new Ts(this.property,this.value,null,{},0)}}class Es{constructor(t,e){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues),this._globalState=e;}getValue(t){return j(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].value=new Ps(this._values[t].property,null===e?void 0:j(e),this._globalState);}getTransition(t){return j(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].transition=j(e)||void 0;}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r);const n=this.getTransition(e);void 0!==n&&(t[`${e}-transition`]=n);}return t}transitioned(t,e){const r=new Bs(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new Bs(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class Ts{constructor(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(nn.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Rs{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new Is(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Is(Math.floor(e.zoom),e)),t.expression.evaluate(new Is(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Us{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)}interpolate(){return !1}}class js{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const r=t[e];r.specification.overridable&&this.overridableProperties.push(e);const n=this.defaultPropertyValues[e]=new Ps(r,void 0,void 0),i=this.defaultTransitionablePropertyValues[e]=new Cs(r,void 0);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}}}as("DataDrivenProperty",Ls),as("DataConstantProperty",Ds),as("CrossFadedDataDrivenProperty",Os),as("CrossFadedProperty",Rs),as("ColorRampProperty",Us);const Ns="-transition";class qs extends gt{constructor(t,e,r){if(super(),this.id=t.id,this.type=t.type,this._globalState=r,this._featureFilter={filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter,this._featureFilter=hi(t.filter,r)),e.layout&&(this._unevaluatedLayout=new Vs(e.layout,r)),e.paint)){this._transitionablePaint=new Es(e.paint,r);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new $s(e.paint);}}setFilter(t){this.filter=t,this._featureFilter=hi(t,this._globalState);}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}getLayoutAffectingGlobalStateRefs(){const t=new Set;if(this._unevaluatedLayout)for(const e in this._unevaluatedLayout._values){const r=this._unevaluatedLayout._values[e];for(const e of r.getGlobalStateRefs())t.add(e);}for(const e of this._featureFilter.getGlobalStateRefs())t.add(e);return t}getPaintAffectingGlobalStateRefs(){var t;const e=new globalThis.Map;if(this._transitionablePaint)for(const r in this._transitionablePaint._values){const n=this._transitionablePaint._values[r].value;for(const i of n.getGlobalStateRefs()){const s=null!==(t=e.get(i))&&void 0!==t?t:[];s.push({name:r,value:n.value}),e.set(i,s);}}return e}setLayoutProperty(t,e,r={}){null!=e&&this._validate(rs,`layers.${this.id}.layout.${t}`,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);}getPaintProperty(t){return t.endsWith(Ns)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(es,`layers.${this.id}.paint.${t}`,t,e,r))return !1;if(t.endsWith(Ns))return this._transitionablePaint.setTransition(t.slice(0,-11),e||void 0),!1;{const r=this._transitionablePaint._values[t],n="cross-faded-data-driven"===r.property.specification["property-type"],i=r.value.isDataDriven(),s=r.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const a=this._transitionablePaint._values[t].value;return a.isDataDriven()||i||n||this._handleOverridablePaintPropertyUpdate(t,s,a)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,r){return !1}isHidden(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),U(t,((t,e)=>!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return (!i||!1!==i.validate)&&ns(this,t.call(Wi,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:xt,style:{glyphs:!0,sprite:!0}}))}is3D(){return !1}isTileClipped(){return !1}hasOffscreenPass(){return !1}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof Fs&&jn(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1}}const Gs={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Xs{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class Zs{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Ys(t,e=1){let r=0,n=0;return {members:t.map((t=>{const i=Gs[t.type].BYTES_PER_ELEMENT,s=r=Hs(r,Math.max(e,i)),a=t.components||1;return n=Math.max(n,i),r+=i*a,{name:t.name,type:t.type,components:a,offset:s}})),size:Hs(r,Math.max(n,e)),alignment:e}}function Hs(t,e){return Math.ceil(t/e)*e}class Ks extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}Ks.prototype.bytesPerElement=4,as("StructArrayLayout2i4",Ks);class Js extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}Js.prototype.bytesPerElement=6,as("StructArrayLayout3i6",Js);class Ws extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}Ws.prototype.bytesPerElement=8,as("StructArrayLayout4i8",Ws);class Qs extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}Qs.prototype.bytesPerElement=12,as("StructArrayLayout2i4i12",Qs);class ta extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=4*t,l=8*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.uint8[l+4]=n,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=a,t}}ta.prototype.bytesPerElement=8,as("StructArrayLayout2i4ub8",ta);class ea extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}ea.prototype.bytesPerElement=8,as("StructArrayLayout2f8",ea);class ra extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,s,a,o,l,u)}emplace(t,e,r,n,i,s,a,o,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=r,this.uint16[h+2]=n,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=a,this.uint16[h+6]=o,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}ra.prototype.bytesPerElement=20,as("StructArrayLayout10ui20",ra);class na extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,a,o,l,u,c,h)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=a,this.uint16[f+6]=o,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}na.prototype.bytesPerElement=24,as("StructArrayLayout4i4ui4i24",na);class ia extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}ia.prototype.bytesPerElement=12,as("StructArrayLayout3f12",ia);class sa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}sa.prototype.bytesPerElement=4,as("StructArrayLayout1ul4",sa);class aa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,s,a,o,l)}emplace(t,e,r,n,i,s,a,o,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=r,this.int16[c+2]=n,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=a,this.uint32[h+3]=o,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}aa.prototype.bytesPerElement=20,as("StructArrayLayout6i1ul2ui20",aa);class oa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}oa.prototype.bytesPerElement=12,as("StructArrayLayout2i2i2i12",oa);class la extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.int16[o+6]=i,this.int16[o+7]=s,t}}la.prototype.bytesPerElement=16,as("StructArrayLayout2f1f2i16",la);class ua extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=16*t,l=4*t,u=8*t;return this.uint8[o+0]=e,this.uint8[o+1]=r,this.float32[l+1]=n,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=a,t}}ua.prototype.bytesPerElement=16,as("StructArrayLayout2ub2f2i16",ua);class ca extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}ca.prototype.bytesPerElement=6,as("StructArrayLayout3ui6",ca);class ha extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=r,this.uint16[x+2]=n,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=a,this.uint32[v+4]=o,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}ha.prototype.bytesPerElement=48,as("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",ha);class pa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I){const z=this.length;return this.resize(z+1),this.emplace(z,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I,z){const P=32*t,C=16*t;return this.int16[P+0]=e,this.int16[P+1]=r,this.int16[P+2]=n,this.int16[P+3]=i,this.int16[P+4]=s,this.int16[P+5]=a,this.int16[P+6]=o,this.int16[P+7]=l,this.uint16[P+8]=u,this.uint16[P+9]=c,this.uint16[P+10]=h,this.uint16[P+11]=p,this.uint16[P+12]=f,this.uint16[P+13]=d,this.uint16[P+14]=y,this.uint16[P+15]=m,this.uint16[P+16]=g,this.uint16[P+17]=x,this.uint16[P+18]=v,this.uint16[P+19]=b,this.uint16[P+20]=w,this.uint16[P+21]=_,this.uint16[P+22]=S,this.uint32[C+12]=A,this.float32[C+13]=k,this.float32[C+14]=M,this.uint16[P+30]=I,this.uint16[P+31]=z,t}}pa.prototype.bytesPerElement=64,as("StructArrayLayout8i15ui1ul2f2ui64",pa);class fa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}fa.prototype.bytesPerElement=4,as("StructArrayLayout1f4",fa);class da extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}da.prototype.bytesPerElement=12,as("StructArrayLayout1ui2f12",da);class ya extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t}}ya.prototype.bytesPerElement=8,as("StructArrayLayout1ul2ui8",ya);class ma extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}ma.prototype.bytesPerElement=4,as("StructArrayLayout2ui4",ma);class ga extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}ga.prototype.bytesPerElement=2,as("StructArrayLayout1ui2",ga);class xa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}xa.prototype.bytesPerElement=16,as("StructArrayLayout4f16",xa);class va extends Xs{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new r(this.anchorPointX,this.anchorPointY)}}va.prototype.size=20;class ba extends aa{get(t){return new va(this,t)}}as("CollisionBoxArray",ba);class wa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t;}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}wa.prototype.size=48;class _a extends ha{get(t){return new wa(this,t)}}as("PlacedSymbolArray",_a);class Sa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t;}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}Sa.prototype.size=64;class Aa extends pa{get(t){return new Sa(this,t)}}as("SymbolInstanceArray",Aa);class ka extends fa{getoffsetX(t){return this.float32[1*t+0]}}as("GlyphOffsetArray",ka);class Ma extends Js{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}as("SymbolLineVertexArray",Ma);class Ia extends Xs{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}Ia.prototype.size=12;class za extends da{get(t){return new Ia(this,t)}}as("TextAnchorOffsetArray",za);class Pa extends Xs{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}Pa.prototype.size=8;class Ca extends ya{get(t){return new Pa(this,t)}}as("FeatureIndexArray",Ca);class Ea extends Ks{}class Ta extends Ks{}class Ba extends Ks{}class Va extends Qs{}class Fa extends ta{}class $a extends ea{}class Da extends ra{}class La extends na{}class Oa extends ia{}class Ra extends sa{}class Ua extends oa{}class ja extends ua{}class Na extends ca{}class qa extends ma{}const Ga=Ys([{name:"a_pos",components:2,type:"Int16"}],4),{members:Xa}=Ga;class Za{constructor(t=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=t;}prepareSegment(t,e,r,n){const i=this.segments[this.segments.length-1];return t>Za.MAX_VERTEX_ARRAY_LENGTH&&q(`Max vertices per segment is ${Za.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${Za.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!i||i.vertexLength+t>Za.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n?this.createNewSegment(e,r,n):i}createNewSegment(t,e,r){const n={vertexOffset:t.length,primitiveOffset:e.length,vertexLength:0,primitiveLength:0,vaos:{}};return void 0!==r&&(n.sortKey=r),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(n),n}getOrCreateLatestSegment(t,e,r){return this.prepareSegment(0,t,e,r)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0;}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,r,n){return new Za([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function Ya(t,e){return 256*(t=$(Math.floor(t),0,255))+$(Math.floor(e),0,255)}Za.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,as("SegmentVector",Za);const Ha=Ys([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var Ka,Ja,Wa,Qa={exports:{}},to={exports:{}},eo={exports:{}},ro=function(){if(Wa)return Qa.exports;Wa=1;var t=(Ka||(Ka=1,to.exports=function(t,e){var r,n,i,s,a,o,l,u;for(n=t.length-(r=3&t.length),i=e,a=3432918353,o=461845907,u=0;u>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0}),to.exports),e=(Ja||(Ja=1,eo.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0}),eo.exports);return Qa.exports=t,Qa.exports.murmur3=t,Qa.exports.murmur2=e,Qa.exports}(),no=n(ro);class io{constructor(){this.ids=[],this.positions=[],this.indexed=!1;}add(t,e,r,n){this.ids.push(so(t)),this.positions.push(e,r,n);}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=so(t);let r=0,n=this.ids.length-1;for(;r>1;this.ids[t]>=e?n=t:r=t+1;}const i=[];for(;this.ids[r]===e;)i.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return i}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return ao(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}}static deserialize(t){const e=new io;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e}}function so(t){const e=+t;return !isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:no(String(t))}function ao(t,e,r,n){for(;r>1];let s=r-1,a=n+1;for(;;){do{s++;}while(t[s]i);if(s>=a)break;oo(t,s,a),oo(e,3*s,3*a),oo(e,3*s+1,3*a+1),oo(e,3*s+2,3*a+2);}a-r`u_${t}`)),this.type=r;}setUniform(t,e,r){t.set(r.constantOr(this.value));}getBinding(t,e,r){return "color"===this.type?new ho(t,e):new uo(t,e)}}class mo{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;}setUniform(t,e,r,n){const i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);}getBinding(t,e,r){return "u_pattern"===r.substr(0,9)?new co(t,e):new uo(t,e)}}class go{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?2:1,offset:0}))),this.paintVertexArray=new n;}populatePaintArray(t,e,r){const n=this.paintVertexArray.length,i=this.expression.evaluate(new Is(0,r),e,{},r.canonical,[],r.formattedSection);this.paintVertexArray.resize(t),this._setPaintValue(n,t,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(0,i),r,n);this._setPaintValue(t,e,s);}_setPaintValue(t,e,r){if("color"===this.type){const n=fo(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,r){const n=this.expression.evaluate(new Is(this.zoom,r),e,{},r.canonical,[],r.formattedSection),i=this.expression.evaluate(new Is(this.zoom+1,r),e,{},r.canonical,[],r.formattedSection),s=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(s,t,n,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(this.zoom,i),r,n),a=this.expression.evaluate(new Is(this.zoom+1,i),r,n);this._setPaintValue(t,e,s,a);}_setPaintValue(t,e,r,n){if("color"===this.type){const i=fo(r),s=fo(n);for(let r=t;r`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof go||r instanceof xo)for(let e=0;e!0){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new bo(n,e,r);this.needsUpload=!1,this._featureMap=new io,this._bufferOffset=0;}populatePaintArrays(t,e,r,n){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;}updatePaintArrays(t,e,r,n){for(const i of r)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,n)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}function _o(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function So(t,e,r){const n={color:{source:ea,composite:xa},number:{source:fa,composite:ea}},i=function(t){return {"line-pattern":{source:Da,composite:Da},"fill-pattern":{source:Da,composite:Da},"fill-extrusion-pattern":{source:Da,composite:Da}}[t]}(t);return i&&i[r]||n[e][r]}as("ConstantBinder",yo),as("CrossFadedConstantBinder",mo),as("SourceExpressionBinder",go),as("CrossFadedCompositeBinder",vo),as("CompositeExpressionBinder",xo),as("ProgramConfiguration",bo,{omit:["_buffers"]}),as("ProgramConfigurationSet",wo);const Ao=Math.pow(2,14)-1,ko=-Ao-1;function Mo(t){const e=P/t.extent,r=t.loadGeometry();for(let t=0;tr.x+1||sr.y+1)&&q("Geometry exceeds allowed extent, reduce your vector tile buffer size");}}return r}function Io(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?Mo(t):[]}}const zo=-32768;function Po(t,e,r,n,i){t.emplaceBack(zo+8*e+n,zo+8*r+i);}class Co{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Ta,this.indexArray=new Na,this.segments=new Za,this.programConfigurations=new wo(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){const n=this.layers[0],i=[];let s=null,a=!1,o="heatmap"===n.type;if("circle"===n.type){const t=n;s=t.layout.get("circle-sort-key"),a=!s.isConstant(),o=o||"map"===t.paint.get("circle-pitch-alignment");}const l=o?e.subdivisionGranularity.circle:1;for(const{feature:e,id:n,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=a?s.evaluate(u,{},r):void 0,h={id:n,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};i.push(h);}a&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of i){const{geometry:i,index:s,sourceLayerIndex:a}=n,o=t[s].feature;this.addFeature(n,i,s,r,l),e.featureIndex.insert(o,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Xa),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,r,n,i=1){let s;switch(i){case 1:s=[0,7];break;case 3:s=[0,2,5,7];break;case 5:s=[0,1,3,4,6,7];break;case 7:s=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${i}; valid values are 1, 3, 5, 7.`)}const a=s.length;for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=P||n<0||n>=P)continue;const i=this.segments.prepareSegment(a*a,this.layoutVertexArray,this.indexArray,t.sortKey),o=i.vertexLength;for(let t=0;t1){if(Fo(t,e))return !0;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function Oo(t,e){let r,n,i,s=!1;for(let a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s);}return s}function Ro(t,e){let r=!1;for(let n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-s.x)*(e.y-s.y)/(a.y-s.y)+s.x&&(r=!r);}return r}function Uo(t,e,r){const n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;const s=G(t,e,r[0]);return s!==G(t,e,r[1])||s!==G(t,e,r[2])||s!==G(t,e,r[3])}function jo(t,e,r){const n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function No(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function qo(t,e,n,i,s){if(!e[0]&&!e[1])return t;const a=r.convert(e)._mult(s);"viewport"===n&&a._rotate(-i);const o=[];for(let e=0;eKo(t,e,r,n)))}(l,i,a,o),f=u),Ho({queryGeometry:p,size:f,transform:i,unwrappedTileID:a,getElevation:o,pitchAlignment:h,pitchScale:c},n)}}class el extends Co{}let rl;as("HeatmapBucket",el,{omit:["layers"]});var nl={get paint(){return rl=rl||new js({"heatmap-radius":new Ls(xt.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Ls(xt.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Ds(xt.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Us(xt.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Ds(xt.paint_heatmap["heatmap-opacity"])})}};function il(t,{width:e,height:r},n,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*r*n)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*r*n}`)}else i=new Uint8Array(e*r*n);return t.width=e,t.height=r,t.data=i,t}function sl(t,{width:e,height:r},n){if(e===t.width&&r===t.height)return;const i=il({},{width:e,height:r},n);al(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,r)},n),t.width=e,t.height=r,t.data=i.data;}function al(t,e,r,n,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const a=t.data,o=e.data;if(a===o)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=a;const o=t.expression.evaluate(e);i.setPixel(n/4/r,s/4,o);};if(t.clips)for(let e=0,i=0;ethis.max&&(this.max=r),r=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)}unpack(t,e,r){return t*this.redFactor+e*this.greenFactor+r*this.blueFactor-this.baseShift}pack(t){return vl(t,this.getUnpackVector())}getPixels(){return new ll({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,a=r*this.dim+this.dim;switch(e){case -1:n=i-1;break;case 1:i=n+1;}switch(r){case -1:s=a-1;break;case 1:a=s+1;}const o=-e*this.dim,l=-r*this.dim;for(let e=s;e0)for(let i=e;i=e;i-=n)s=Zl(i/n|0,t[i],t[i+1],s);return s&&Ul(s,s.next)&&(Yl(s),s=s.next),s}function Ml(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!Ul(n,n.next)&&0!==Rl(n.prev,n,n.next))n=n.next;else {if(Yl(n),n=e=n.prev,n===n.next)break;r=!0;}}while(r||n!==e);return e}function Il(t,e,r,n,i,s,a){if(!t)return;!a&&s&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=Fl(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let s=null;for(e=0;i;){e++;let a=i,o=0;for(let t=0;t0||l>0&&a;)0!==o&&(0===l||!a||i.z<=a.z)?(n=i,i=i.nextZ,o--):(n=a,a=a.nextZ,l--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;i=a;}s.nextZ=null,r*=2;}while(e>1)}(i);}(t,n,i,s);let o=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?Pl(t,n,i,s):zl(t))e.push(l.i,t.i,u.i),Yl(t),t=u.next,o=u.next;else if((t=u)===o){a?1===a?Il(t=Cl(Ml(t),e),e,r,n,i,s,2):2===a&&El(t,e,r,n,i,s):Il(Ml(t),e,r,n,i,s,1);break}}}function zl(t){const e=t.prev,r=t,n=t.next;if(Rl(e,r,n)>=0)return !1;const i=e.x,s=r.x,a=n.x,o=e.y,l=r.y,u=n.y,c=Math.min(i,s,a),h=Math.min(o,l,u),p=Math.max(i,s,a),f=Math.max(o,l,u);let d=n.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&Ll(i,o,s,l,a,u,d.x,d.y)&&Rl(d.prev,d,d.next)>=0)return !1;d=d.next;}return !0}function Pl(t,e,r,n){const i=t.prev,s=t,a=t.next;if(Rl(i,s,a)>=0)return !1;const o=i.x,l=s.x,u=a.x,c=i.y,h=s.y,p=a.y,f=Math.min(o,l,u),d=Math.min(c,h,p),y=Math.max(o,l,u),m=Math.max(c,h,p),g=Fl(f,d,e,r,n),x=Fl(y,m,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}return !0}function Cl(t,e){let r=t;do{const n=r.prev,i=r.next.next;!Ul(n,i)&&jl(n,r,r.next,i)&&Gl(n,i)&&Gl(i,n)&&(e.push(n.i,r.i,i.i),Yl(r),Yl(r.next),r=t=i),r=r.next;}while(r!==t);return Ml(r)}function El(t,e,r,n,i,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Ol(a,t)){let o=Xl(a,t);return a=Ml(a,a.next),o=Ml(o,o.next),Il(a,e,r,n,i,s,0),void Il(o,e,r,n,i,s,0)}t=t.next;}a=a.next;}while(a!==t)}function Tl(t,e){let r=t.x-e.x;return 0===r&&(r=t.y-e.y,0===r)&&(r=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)),r}function Bl(t,e){const r=function(t,e){let r=e;const n=t.x,i=t.y;let s,a=-1/0;if(Ul(t,r))return r;do{if(Ul(t,r.next))return r.next;if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){const t=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(t<=n&&t>a&&(a=t,s=r.x=r.x&&r.x>=l&&n!==r.x&&Dl(is.x||r.x===s.x&&Vl(s,r)))&&(s=r,c=e);}r=r.next;}while(r!==o);return s}(t,e);if(!r)return e;const n=Xl(r,t);return Ml(n,n.next),Ml(r,r.next)}function Vl(t,e){return Rl(t.prev,t,e.prev)<0&&Rl(e.next,t,t.next)<0}function Fl(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function $l(t){let e=t,r=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(r-a)*(e-o)&&(r-a)*(s-o)>=(i-a)*(n-o)}function Ll(t,e,r,n,i,s,a,o){return !(t===a&&e===o)&&Dl(t,e,r,n,i,s,a,o)}function Ol(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&jl(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(Gl(t,e)&&Gl(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Rl(t.prev,t,e.prev)||Rl(t,e.prev,e))||Ul(t,e)&&Rl(t.prev,t,t.next)>0&&Rl(e.prev,e,e.next)>0)}function Rl(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Ul(t,e){return t.x===e.x&&t.y===e.y}function jl(t,e,r,n){const i=ql(Rl(t,e,r)),s=ql(Rl(t,e,n)),a=ql(Rl(r,n,t)),o=ql(Rl(r,n,e));return i!==s&&a!==o||!(0!==i||!Nl(t,r,e))||!(0!==s||!Nl(t,n,e))||!(0!==a||!Nl(r,t,n))||!(0!==o||!Nl(r,e,n))}function Nl(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function ql(t){return t>0?1:t<0?-1:0}function Gl(t,e){return Rl(t.prev,t,t.next)<0?Rl(t,e,t.next)>=0&&Rl(t,t.prev,e)>=0:Rl(t,e,t.prev)<0||Rl(t,t.next,e)<0}function Xl(t,e){const r=Hl(t.i,t.x,t.y),n=Hl(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function Zl(t,e,r,n){const i=Hl(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Yl(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 Hl(t,e,r){return {i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class Kl{constructor(t,e){if(e>t)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=t,this._minGranularity=e;}getGranularityForZoomLevel(t){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||e>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const r=0|Math.round(t),n=0|Math.round(e),i=this._getKey(r,n);if(this._vertexDictionary.has(i))return this._vertexDictionary.get(i);const s=this._vertexBuffer.length/2;return this._vertexDictionary.set(i,s),this._vertexBuffer.push(r,n),s}_subdivideTrianglesScanline(t){if(this._granularity<2)return function(t,e){const r=[];for(let n=0;n0?(r.push(i),r.push(a),r.push(s)):(r.push(i),r.push(s),r.push(a));}return r}(this._vertexBuffer,t);const e=[],r=t.length;for(let n=0;n=1||v<=0)||y&&(oi)){u>=n&&u<=i&&s.push(r[(t+1)%3]);continue}!y&&x>0&&s.push(this._vertexToIndex(a+p*x,o+f*x));const b=a+p*Math.max(x,0),w=a+p*Math.min(v,1);d||this._generateIntraEdgeVertices(s,a,o,l,u,b,w),!y&&v<1&&s.push(this._vertexToIndex(a+p*v,o+f*v)),(y||u>=n&&u<=i)&&s.push(r[(t+1)%3]),!y&&(u<=n||u>=i)&&this._generateInterEdgeVertices(s,a,o,l,u,c,h,w,n,i);}return s}_generateIntraEdgeVertices(t,e,r,n,i,s,a){const o=n-e,l=i-r,u=0===l,c=u?Math.min(e,n):Math.min(s,a),h=u?Math.max(e,n):Math.max(s,a),p=Math.floor(c/this._granularityCellSize)+1,f=Math.ceil(h/this._granularityCellSize)-1;if(u?e=p;n--){const i=n*this._granularityCellSize;t.push(this._vertexToIndex(i,r+l*(i-e)/o));}}_generateInterEdgeVertices(t,e,r,n,i,s,a,o,l,u){const c=i-r,h=s-n,p=a-i,f=(l-i)/p,d=(u-i)/p,y=Math.min(f,d),m=Math.max(f,d),g=n+h*y;let x=Math.floor(Math.min(g,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(g,o)/this._granularityCellSize)-1,b=o=1||m<=0){const t=r-a,n=s+(e-s)*Math.min((l-a)/t,(u-a)/t);x=Math.floor(Math.min(n,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(n,o)/this._granularityCellSize)-1,b=o0?u:l;if(b)for(let e=x;e<=v;e++)t.push(this._vertexToIndex(e*this._granularityCellSize,_));else for(let e=v;e>=x;e--)t.push(this._vertexToIndex(e*this._granularityCellSize,_));}_generateOutline(t){const e=[];for(const r of t){const t=ru(r,this._granularity,!0),n=this._pointArrayToIndices(t),i=[];for(let t=1;ti!=(s===Wl)?(t.push(e),t.push(r),t.push(this._vertexToIndex(n,s)),t.push(r),t.push(this._vertexToIndex(i,s)),t.push(this._vertexToIndex(n,s))):(t.push(r),t.push(e),t.push(this._vertexToIndex(n,s)),t.push(this._vertexToIndex(i,s)),t.push(r),t.push(this._vertexToIndex(n,s)));}_fillPoles(t,e,r){const n=this._vertexBuffer,i=P,s=t.length;for(let a=2;a80*r){o=t[0],l=t[1];let e=o,n=l;for(let s=r;se&&(e=r),i>n&&(n=i);}u=Math.max(e-o,n-l),u=0!==u?32767/u:0;}return Il(s,a,r,o,l,u,0),a}(r,n),e=this._convertIndices(r,t);i=this._subdivideTrianglesScanline(e);}catch(t){console.error(t);}let s=[];return e&&(s=this._generateOutline(t)),this._ensureNoPoleVertices(),this._handlePoles(i),{verticesFlattened:this._vertexBuffer,indicesTriangles:i,indicesLineList:s}}_convertIndices(t,e){const r=[];for(let n=0;n0?(Math.floor(x/o)+1)*o:(Math.ceil(x/o)-1)*o,e=y>0?(Math.floor(v/o)+1)*o:(Math.ceil(v/o)-1)*o,n=Math.abs(x-t),i=Math.abs(v-e),s=Math.abs(x-c),a=Math.abs(v-h),u=p?n/m:Number.POSITIVE_INFINITY,b=f?i/g:Number.POSITIVE_INFINITY;if((s<=n||!p)&&(a<=i||!f))break;if(u=0?a-1:s-1,i=(o+1)%s,l=t[2*e[n]],u=t[2*e[i]],c=t[2*e[a]],h=t[2*e[a]+1],p=t[2*e[o]+1];let f=!1;if(lu)f=!1;else {const r=p-h,s=-(t[2*e[o]]-c),a=h((u-c)*r+(t[2*e[i]+1]-h)*s)*a&&(f=!0);}if(f){const t=e[n],i=e[a],l=e[o];t!==i&&t!==l&&i!==l&&r.push(l,i,t),a--,a<0&&(a=s-1);}else {const t=e[i],n=e[a],l=e[o];t!==n&&t!==l&&n!==l&&r.push(l,n,t),o++,o>=s&&(o=0);}if(n===i)break}}function iu(t,e,r,n,i,s,a,o,l){const u=i.length/2,c=a&&o&&l;if(uZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,y=!0,m=!0,g=!0,c=0);const x=su(a,n,s,o,p,y,u),v=su(a,n,s,o,f,m,u),b=su(a,n,s,o,d,g,u);r.emplaceBack(c+x-l,c+v-l,c+b-l),u.primitiveLength++;}}(e,r,n,i,s,t),c&&function(t,e,r,n,i,s){const a=[];for(let t=0;tZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,d=!0,y=!0,c=0);const m=su(a,n,s,o,i,d,u),g=su(a,n,s,o,h,y,u);r.emplaceBack(c+m-l,c+g-l),u.primitiveLength++;}}}(a,r,o,i,l,t),e.forceNewSegmentOnNextPrepare(),null==a||a.forceNewSegmentOnNextPrepare();}function su(t,e,r,n,i,s,a){if(s){const s=n.count;return r(e[2*i],e[2*i+1]),t[i]=n.count,n.count++,a.vertexLength++,s}return t[i]}class au{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Ba,this.indexArray=new Na,this.indexArray2=new qa,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.segments2=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("fill",this.layers,e);const n=this.layers[0].layout.get("fill-sort-key"),i=!n.isConstant(),s=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=Io(a,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),c,r))continue;const h=i?n.evaluate(c,{},r,e.availableImages):void 0,p={id:o,properties:a.properties,type:a.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:Mo(a),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("fill",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,_l),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,r,n,i,s){for(const t of Qr(e,500)){const e=eu(t,n,s.fill.getGranularityForZoomLevel(n.z)),r=this.layoutVertexArray;iu(((t,e)=>{r.emplaceBack(t,e);}),this.segments,this.layoutVertexArray,this.indexArray,e.verticesFlattened,e.indicesTriangles,this.segments2,this.indexArray2,e.indicesLineList);}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}}let ou,lu;as("FillBucket",au,{omit:["layers","patternFeatures"]});var uu={get paint(){return lu=lu||new js({"fill-antialias":new Ds(xt.paint_fill["fill-antialias"]),"fill-opacity":new Ls(xt.paint_fill["fill-opacity"]),"fill-color":new Ls(xt.paint_fill["fill-color"]),"fill-outline-color":new Ls(xt.paint_fill["fill-outline-color"]),"fill-translate":new Ds(xt.paint_fill["fill-translate"]),"fill-translate-anchor":new Ds(xt.paint_fill["fill-translate-anchor"]),"fill-pattern":new Os(xt.paint_fill["fill-pattern"])})},get layout(){return ou=ou||new js({"fill-sort-key":new Ls(xt.layout_fill["fill-sort-key"])})}};class cu extends qs{constructor(t,e){super(t,uu,e);}recalculate(t,e){super.recalculate(t,e);const r=this.paint._values["fill-outline-color"];"constant"===r.value.kind&&void 0===r.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);}createBucket(t){return new au(t)}queryRadius(){return No(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:t,geometry:e,transform:r,pixelsToTileUnits:n}){return Bo(qo(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-r.bearingInRadians,n),e)}isTileClipped(){return !0}}const hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),pu=Ys([{name:"a_centroid",components:2,type:"Int16"}],4),{members:fu}=hu;class du{constructor(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this.id=void 0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(yu,this,e);}loadGeometry(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos,n=[];let i,s=1,a=0,o=0,l=0;for(;t.pos>3;}if(a--,1===s||2===s)o+=t.readSVarint(),l+=t.readSVarint(),1===s&&(i&&n.push(i),i=[]),i&&i.push(new r(o,l));else {if(7!==s)throw new Error(`unknown command ${s}`);i&&i.push(i[0].clone());}}return i&&n.push(i),n}bbox(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos;let r=1,n=0,i=0,s=0,a=1/0,o=-1/0,l=1/0,u=-1/0;for(;t.pos>3;}if(n--,1===r||2===r)i+=t.readSVarint(),s+=t.readSVarint(),io&&(o=i),su&&(u=s);else if(7!==r)throw new Error(`unknown command ${r}`)}return [a,l,o,u]}toGeoJSON(t,e,r){const n=this.extent*Math.pow(2,r),i=this.extent*t,s=this.extent*e,a=this.loadGeometry();function o(t){return [360*(t.x+i)/n-180,360/Math.PI*Math.atan(Math.exp((1-2*(t.y+s)/n)*Math.PI))-90]}function l(t){return t.map(o)}let u;if(1===this.type){const t=[];for(const e of a)t.push(e[0]);const e=l(t);u=1===t.length?{type:"Point",coordinates:e[0]}:{type:"MultiPoint",coordinates:e};}else if(2===this.type){const t=a.map(l);u=1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t};}else {if(3!==this.type)throw new Error("unknown feature type");{const t=function(t){const e=t.length;if(e<=1)return [t];const r=[];let n,i;for(let s=0;s=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];const e=this._pbf.readVarint()+this._pbf.pos;return new du(this._pbf,e,this.extent,this._keys,this._values)}}function xu(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){let e=null;const r=t.readVarint()+t.pos;for(;t.pos>3;e=1===r?t.readString():2===r?t.readFloat():3===r?t.readDouble():4===r?t.readVarint64():5===r?t.readVarint():6===r?t.readSVarint():7===r?t.readBoolean():null;}if(null==e)throw new Error("unknown feature value");return e}(r));}class vu{constructor(t,e){this.layers=t.readFields(bu,{},e);}}function bu(t,e,r){if(3===t){const t=new gu(r,r.readVarint()+r.pos);t.length&&(e[t.name]=t);}}const wu=Math.pow(2,13);function _u(t,e,r,n,i,s,a,o){t.emplaceBack(e,r,2*Math.floor(n*wu)+a,i*wu*2,s*wu*2,Math.round(o));}class Su{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Va,this.centroidVertexArray=new Ea,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.features=[],this.hasPattern=Sl("fill-extrusion",this.layers,e);for(const{feature:n,id:i,index:s,sourceLayerIndex:a}of t){const t=this.layers[0]._featureFilter.needGeometry,o=Io(n,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),o,r))continue;const l={id:i,sourceLayerIndex:a,index:s,geometry:t?o.geometry:Mo(n),properties:n.properties,type:n.type,patterns:{}};this.hasPattern?this.features.push(Al("fill-extrusion",this.layers,l,{zoom:this.zoom},e)):this.addFeature(l,l.geometry,s,r,{},e.subdivisionGranularity),e.featureIndex.insert(n,l.geometry,s,a,this.index,!0);}}addFeatures(t,e,r){for(const n of this.features){const{geometry:i}=n;this.addFeature(n,i,n.index,e,r,t.subdivisionGranularity);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,fu),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,pu.members,!0),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy());}addFeature(t,e,r,n,i,s){for(const r of Qr(e,500)){const e={x:0,y:0,sampleCount:0},i=this.layoutVertexArray.length;this.processPolygon(e,n,t,r,s);const a=this.layoutVertexArray.length-i,o=Math.floor(e.x/e.sampleCount),l=Math.floor(e.y/e.sampleCount);for(let t=0;t{_u(u,t,e,0,0,1,1,0);}),this.segments,this.layoutVertexArray,this.indexArray,l.verticesFlattened,l.indicesTriangles);}_generateSideFaces(t,e){let r=0;for(let n=1;nZa.MAX_VERTEX_ARRAY_LENGTH&&(e.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const a=i.sub(s)._perp()._unit(),o=s.dist(i);r+o>32768&&(r=0),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,1,r),r+=o,_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,1,r);const l=e.segment.vertexLength;this.indexArray.emplaceBack(l,l+2,l+1),this.indexArray.emplaceBack(l+1,l+2,l+3),e.segment.vertexLength+=4,e.segment.primitiveLength+=2;}}}function Au(t,e){for(let r=0;rP)||t.y===e.y&&(t.y<0||t.y>P)}function Mu(t){return t.every((t=>t.x<0))||t.every((t=>t.x>P))||t.every((t=>t.y<0))||t.every((t=>t.y>P))}let Iu;as("FillExtrusionBucket",Su,{omit:["layers","features"]});var zu={get paint(){return Iu=Iu||new js({"fill-extrusion-opacity":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Os(xt["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class Pu extends qs{constructor(t,e){super(t,zu,e);}createBucket(t){return new Su(t)}queryRadius(){return No(this.paint.get("fill-extrusion-translate"))}is3D(){return !0}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a,pixelPosMatrix:o}){const l=qo(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-s.bearingInRadians,a),u=this.paint.get("fill-extrusion-height").evaluate(e,n),c=this.paint.get("fill-extrusion-base").evaluate(e,n),h=function(t,e){const n=[];for(const i of t){const t=[i.x,i.y,0,1];A(t,t,e),n.push(new r(t[0]/t[3],t[1]/t[3]));}return n}(l,o),p=function(t,e,n,i){const s=[],a=[],o=i[8]*e,l=i[9]*e,u=i[10]*e,c=i[11]*e,h=i[8]*n,p=i[9]*n,f=i[10]*n,d=i[11]*n;for(const e of t){const t=[],n=[];for(const s of e){const e=s.x,a=s.y,y=i[0]*e+i[4]*a+i[12],m=i[1]*e+i[5]*a+i[13],g=i[2]*e+i[6]*a+i[14],x=i[3]*e+i[7]*a+i[15],v=g+u,b=x+c,w=y+h,_=m+p,S=g+f,A=x+d,k=new r((y+o)/b,(m+l)/b);k.z=v/b,t.push(k);const M=new r(w/A,_/A);M.z=S/A,n.push(M);}s.push(t),a.push(n);}return [s,a]}(i,c,u,o);return function(t,e,r){let n=1/0;Bo(r,e)&&(n=Eu(r,e[0]));for(let i=0;it.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new Fa,this.layoutVertexArray2=new $a,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("line",this.layers,e);const n=this.layers[0].layout.get("line-sort-key"),i=!n.isConstant(),s=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=i?n.evaluate(u,{},r):void 0,h={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("line",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,Fu)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Bu),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return {start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i,s){const a=this.layers[0].layout,o=a.get("line-join").evaluate(t,{}),l=a.get("line-cap"),u=a.get("line-miter-limit"),c=a.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,o,l,u,c,n,s);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}addLine(t,e,r,n,i,s,a,o){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,t=ru(t,a?o.line.getGranularityForZoomLevel(a.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[u-1].equals(t[u-2]);)u--;let c=0;for(;c0;if(w&&e>c){const t=f.dist(d);if(t>2*h){const e=f.sub(f.sub(d)._mult(h/t)._round());this.updateDistance(d,e),this.addCurrentVertex(e,m,0,0,p),d=e;}}const S=d&&y;let A=S?r:l?"butt":n;if(S&&"round"===A&&(vi&&(A="bevel"),"bevel"===A&&(v>2&&(A="flipbevel"),v100)a=g.mult(-1);else {const t=v*m.add(g).mag()/m.sub(g).mag();a._perp()._mult(t*(_?-1:1));}this.addCurrentVertex(f,a,0,0,p),this.addCurrentVertex(f,a.mult(-1),0,0,p);}else if("bevel"===A||"fakeround"===A){const t=-Math.sqrt(v*v-1),e=_?t:0,r=_?0:t;if(d&&this.addCurrentVertex(f,m,e,r,p),"fakeround"===A){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*h){const e=f.add(y.sub(f)._mult(h/t)._round());this.updateDistance(f,e),this.addCurrentVertex(e,g,0,0,p),f=e;}}}}addCurrentVertex(t,e,r,n,i,s=!1){const a=e.y*n-e.x,o=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,!1,r,i),this.addHalfVertex(t,a,o,s,!0,-n,i),this.distance>Du/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,r,n,i,s));}addHalfVertex({x:t,y:e},r,n,i,s,a,o){const l=.5*(this.lineClips?this.scaledDistance*(Du-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,u,this.e2),o.primitiveLength++),s?this.e2=u:this.e1=u;}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}}let Ou,Ru;as("LineBucket",Lu,{omit:["layers","patternFeatures"]});var Uu={get paint(){return Ru=Ru||new js({"line-opacity":new Ls(xt.paint_line["line-opacity"]),"line-color":new Ls(xt.paint_line["line-color"]),"line-translate":new Ds(xt.paint_line["line-translate"]),"line-translate-anchor":new Ds(xt.paint_line["line-translate-anchor"]),"line-width":new Ls(xt.paint_line["line-width"]),"line-gap-width":new Ls(xt.paint_line["line-gap-width"]),"line-offset":new Ls(xt.paint_line["line-offset"]),"line-blur":new Ls(xt.paint_line["line-blur"]),"line-dasharray":new Rs(xt.paint_line["line-dasharray"]),"line-pattern":new Os(xt.paint_line["line-pattern"]),"line-gradient":new Us(xt.paint_line["line-gradient"])})},get layout(){return Ou=Ou||new js({"line-cap":new Ds(xt.layout_line["line-cap"]),"line-join":new Ls(xt.layout_line["line-join"]),"line-miter-limit":new Ds(xt.layout_line["line-miter-limit"]),"line-round-limit":new Ds(xt.layout_line["line-round-limit"]),"line-sort-key":new Ls(xt.layout_line["line-sort-key"])})}};class ju extends Ls{possiblyEvaluate(t,e){return e=new Is(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=L({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}let Nu;class qu extends qs{constructor(t,e){super(t,Uu,e),this.gradientVersion=0,Nu||(Nu=new ju(Uu.paint.properties["line-width"].specification),Nu.useIntegerZoom=!0);}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return void 0!==t._styleExpression}(t)&&t._styleExpression.expression instanceof ar,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=Nu.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t);}createBucket(t){return new Lu(t)}queryRadius(t){const e=t,r=Gu(jo("line-width",this,e),jo("line-gap-width",this,e)),n=jo("line-offset",this,e);return r/2+Math.abs(n)+No(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a}){const o=qo(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-s.bearingInRadians,a),l=a/2*Gu(this.paint.get("line-width").evaluate(e,n),this.paint.get("line-gap-width").evaluate(e,n)),u=this.paint.get("line-offset").evaluate(e,n);return u&&(i=function(t,e){const n=[];for(let i=0;i=3)for(let e=0;e0?e+2*t:t}const Xu=Ys([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Zu=Ys([{name:"a_projected_pos",components:3,type:"Float32"}],4);Ys([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Yu=Ys([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Ys([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const Hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Ku=Ys([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Ju(t,e,r){return t.sections.forEach((t=>{t.text=function(t,e,r){const n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Ms.applyArabicShaping&&(t=Ms.applyArabicShaping(t)),t}(t.text,e,r);})),t}Ys([{name:"triangle",components:3,type:"Uint16"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Ys([{type:"Float32",name:"offsetX"}]),Ys([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Ys([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const Wu={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Qu=24;const tc=4294967296,ec=1/tc,rc="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class nc{constructor(t=new Uint8Array(16)){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length;}readFields(t,e,r=this.length){for(;this.pos>3,i=this.pos;this.type=7&r,t(n,e,this),this.pos===i&&this.skip(r);}return e}readMessage(t,e){return this.readFields(t,e,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*tc;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*tc;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const e=this.buf;let r,n;return n=e[this.pos++],r=127&n,n<128?r:(n=e[this.pos++],r|=(127&n)<<7,n<128?r:(n=e[this.pos++],r|=(127&n)<<14,n<128?r:(n=e[this.pos++],r|=(127&n)<<21,n<128?r:(n=e[this.pos],r|=(15&n)<<28,function(t,e,r){const n=r.buf;let i,s;if(s=n[r.pos++],i=(112&s)>>4,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<3,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<10,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<17,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<24,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(1&s)<<31,s<128)return ic(t,i,e);throw new Error("Expected varint not more than 10 bytes")}(r,t,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2==1?(t+1)/-2:t/2}readBoolean(){return Boolean(this.readVarint())}readString(){const t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&rc?rc.decode(this.buf.subarray(e,t)):function(t,e,r){let n="",i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+u>r)break;1===u?e<128&&(l=e):2===u?(s=t[i+1],128==(192&s)&&(l=(31&e)<<6|63&s,l<=127&&(l=null))):3===u?(s=t[i+1],a=t[i+2],128==(192&s)&&128==(192&a)&&(l=(15&e)<<12|(63&s)<<6|63&a,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===u&&(s=t[i+1],a=t[i+2],o=t[i+3],128==(192&s)&&128==(192&a)&&128==(192&o)&&(l=(15&e)<<18|(63&s)<<12|(63&a)<<6|63&o,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,u=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=u;}return n}(this.buf,e,t)}readBytes(){const t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e}readPackedVarint(t=[],e){const r=this.readPackedEnd();for(;this.pos127;);else if(2===e)this.pos=this.readVarint()+this.pos;else if(5===e)this.pos+=4;else {if(1!==e)throw new Error(`Unimplemented type: ${e}`);this.pos+=8;}}writeTag(t,e){this.writeVarint(t<<3|e);}realloc(t){let e=this.length||16;for(;e268435455||t<0?function(t,e){let r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(r=~(-t%4294967296),n=~(-t/4294967296),4294967295^r?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){const r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(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(t){this.writeVarint(t<0?2*-t-1:2*t);}writeBoolean(t){this.writeVarint(+t);}writeString(t){t=String(t),this.realloc(4*t.length),this.pos++;const e=this.pos;this.pos=function(t,e,r){for(let n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);const r=this.pos-e;r>=128&&sc(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4;}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8;}writeBytes(t){const e=t.length;this.writeVarint(e),this.realloc(e);for(let r=0;r=128&&sc(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;}writeMessage(t,e,r){this.writeTag(t,2),this.writeRawMessage(e,r);}writePackedVarint(t,e){e.length&&this.writeMessage(t,ac,e);}writePackedSVarint(t,e){e.length&&this.writeMessage(t,oc,e);}writePackedBoolean(t,e){e.length&&this.writeMessage(t,cc,e);}writePackedFloat(t,e){e.length&&this.writeMessage(t,lc,e);}writePackedDouble(t,e){e.length&&this.writeMessage(t,uc,e);}writePackedFixed32(t,e){e.length&&this.writeMessage(t,hc,e);}writePackedSFixed32(t,e){e.length&&this.writeMessage(t,pc,e);}writePackedFixed64(t,e){e.length&&this.writeMessage(t,fc,e);}writePackedSFixed64(t,e){e.length&&this.writeMessage(t,dc,e);}writeBytesField(t,e){this.writeTag(t,2),this.writeBytes(e);}writeFixed32Field(t,e){this.writeTag(t,5),this.writeFixed32(e);}writeSFixed32Field(t,e){this.writeTag(t,5),this.writeSFixed32(e);}writeFixed64Field(t,e){this.writeTag(t,1),this.writeFixed64(e);}writeSFixed64Field(t,e){this.writeTag(t,1),this.writeSFixed64(e);}writeVarintField(t,e){this.writeTag(t,0),this.writeVarint(e);}writeSVarintField(t,e){this.writeTag(t,0),this.writeSVarint(e);}writeStringField(t,e){this.writeTag(t,2),this.writeString(e);}writeFloatField(t,e){this.writeTag(t,5),this.writeFloat(e);}writeDoubleField(t,e){this.writeTag(t,1),this.writeDouble(e);}writeBooleanField(t,e){this.writeVarintField(t,+e);}}function ic(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function sc(t,e,r){const n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(let e=r.pos-1;e>=t;e--)r.buf[e+n]=r.buf[e];}function ac(t,e){for(let r=0;re.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();e&&t=0&&r>=t&&kc[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e);}substring(t,e){const r=new Sc;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}getMaxImageSize(t){let e=0,r=0;for(let n=0;n=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Ac(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=Sc.fromFeature(e,s);let g;p===t.ao.vertical&&m.verticalizePunctuation();const{processBidirectionalText:x,processStyledBidirectionalText:v}=Ms;if(x&&1===m.sections.length){g=[];const t=x(m.toString(),Bc(m,c,a,r,i,d));for(const e of t){const t=new Sc;t.text=e,t.sections=m.sections;for(let r=0;r=0;let u=0;for(let r=0;ru){const t=Math.ceil(s/u);i*=t/a,a=t;}return {x1:n,y1:i,x2:n+s,y2:i+a}}function Nc(t,e,r,n,i,s){const a=t.image;let o;if(a.content){const t=a.content,e=a.pixelRatio||1;o=[t[0]/e,t[1]/e,a.displaySize[0]-t[2]/e,a.displaySize[1]-t[3]/e];}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===r||"both"===r?(f=i[0]+l-n[3],h=i[0]+u+n[1]):(f=i[0]+(l+u-a.displaySize[0])/2,h=f+a.displaySize[0]);const d=e.top*s,y=e.bottom*s;return "height"===r||"both"===r?(c=i[1]+d-n[0],p=i[1]+y+n[2]):(c=i[1]+(d+y-a.displaySize[1])/2,p=c+a.displaySize[1]),{image:a,top:c,right:h,bottom:p,left:f,collisionPadding:o}}const qc=128,Gc=32640;function Xc(t,e){const{expression:r}=e;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new Is(t+1))};if("source"===r.kind)return {kind:"source"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;it.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];const r=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Xc(this.zoom,r["text-size"]),this.iconSizeData=Xc(this.zoom,r["icon-size"]);const n=this.layers[0].layout,i=n.get("symbol-sort-key"),s=n.get("symbol-z-order");this.canOverlap="never"!==Zc(n,"text-overlap","text-allow-overlap")||"never"!==Zc(n,"icon-overlap","icon-allow-overlap")||n.get("text-ignore-placement")||n.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!i.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===n.get("symbol-placement")&&(this.writingModes=n.get("text-writing-mode").map((e=>t.ao[e]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID;}createArrays(){this.text=new Wc(new wo(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new Wc(new wo(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new ka,this.lineVertexArray=new Ma,this.symbolInstances=new Aa,this.textAnchorOffsets=new za;}calculateGlyphDependencies(t,e,r,n,i){for(let s=0;s0)&&("constant"!==a.value.kind||a.value.value.length>0),c="constant"!==l.value.kind||!!l.value.value||Object.keys(l.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!u&&!c)return;const p=r.iconDependencies,f=r.glyphDependencies,d=r.availableImages,y=new Is(this.zoom);for(const{feature:r,id:o,index:l,sourceLayerIndex:m}of e){const e=i._featureFilter.needGeometry,g=Io(r,e);if(!i._featureFilter.filter(y,g,n))continue;let x,v;if(e||(g.geometry=Mo(r)),u){const t=i.getValueAndResolveTokens("text-field",g,n,d),e=Ce.factory(t),r=this.hasRTLText=this.hasRTLText||Jc(e);(!r||"unavailable"===Ms.getRTLTextPluginStatus()||r&&Ms.isParsed())&&(x=Ju(e,i,g));}if(c){const t=i.getValueAndResolveTokens("icon-image",g,n,d);v=t instanceof De?t:De.fromString(t);}if(!x&&!v)continue;const b=this.sortFeaturesByKey?h.evaluate(g,{},n):void 0;if(this.features.push({id:o,text:x,icon:v,index:l,sourceLayerIndex:m,geometry:g.geometry,properties:r.properties,type:du.types[r.type],sortKey:b}),v&&(p[v.name]=!0),x){const e=a.evaluate(g,{},n).join(","),r="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(t.ao.vertical)>=0;for(const t of x.sections)if(t.image)p[t.image.name]=!0;else {const n=ds(x.toString()),i=t.fontStack||e,s=f[i]=f[i]||{};this.calculateGlyphDependencies(t.text,s,r,this.allowVerticalPlacement,n);}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++;}function a(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function o(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return `${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}));}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(void 0!==t.segment){let r=t.dist(e[t.segment+1]),n=t.dist(e[t.segment]);const i={};for(let n=t.segment+1;n=0;r--)i[r]={x:e[r].x,y:e[r].y,tileUnitDistanceFromAnchor:n},r>0&&(n+=e[r-1].dist(e[r]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,r)=>{t>=0&&r.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t);})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}let eh,rh;as("SymbolBucket",th,{omit:["layers","collisionBoxArray","features","compareText"]}),th.MAX_GLYPHS=65535,th.addDynamicAttributes=Kc;var nh={get paint(){return rh=rh||new js({"icon-opacity":new Ls(xt.paint_symbol["icon-opacity"]),"icon-color":new Ls(xt.paint_symbol["icon-color"]),"icon-halo-color":new Ls(xt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Ls(xt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Ls(xt.paint_symbol["icon-halo-blur"]),"icon-translate":new Ds(xt.paint_symbol["icon-translate"]),"icon-translate-anchor":new Ds(xt.paint_symbol["icon-translate-anchor"]),"text-opacity":new Ls(xt.paint_symbol["text-opacity"]),"text-color":new Ls(xt.paint_symbol["text-color"],{runtimeType:Lt,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new Ls(xt.paint_symbol["text-halo-color"]),"text-halo-width":new Ls(xt.paint_symbol["text-halo-width"]),"text-halo-blur":new Ls(xt.paint_symbol["text-halo-blur"]),"text-translate":new Ds(xt.paint_symbol["text-translate"]),"text-translate-anchor":new Ds(xt.paint_symbol["text-translate-anchor"])})},get layout(){return eh=eh||new js({"symbol-placement":new Ds(xt.layout_symbol["symbol-placement"]),"symbol-spacing":new Ds(xt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Ds(xt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Ls(xt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Ds(xt.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new Ds(xt.layout_symbol["icon-allow-overlap"]),"icon-overlap":new Ds(xt.layout_symbol["icon-overlap"]),"icon-ignore-placement":new Ds(xt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Ds(xt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Ds(xt.layout_symbol["icon-rotation-alignment"]),"icon-size":new Ls(xt.layout_symbol["icon-size"]),"icon-text-fit":new Ds(xt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Ds(xt.layout_symbol["icon-text-fit-padding"]),"icon-image":new Ls(xt.layout_symbol["icon-image"]),"icon-rotate":new Ls(xt.layout_symbol["icon-rotate"]),"icon-padding":new Ls(xt.layout_symbol["icon-padding"]),"icon-keep-upright":new Ds(xt.layout_symbol["icon-keep-upright"]),"icon-offset":new Ls(xt.layout_symbol["icon-offset"]),"icon-anchor":new Ls(xt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Ds(xt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Ds(xt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Ds(xt.layout_symbol["text-rotation-alignment"]),"text-field":new Ls(xt.layout_symbol["text-field"]),"text-font":new Ls(xt.layout_symbol["text-font"]),"text-size":new Ls(xt.layout_symbol["text-size"]),"text-max-width":new Ls(xt.layout_symbol["text-max-width"]),"text-line-height":new Ds(xt.layout_symbol["text-line-height"]),"text-letter-spacing":new Ls(xt.layout_symbol["text-letter-spacing"]),"text-justify":new Ls(xt.layout_symbol["text-justify"]),"text-radial-offset":new Ls(xt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Ds(xt.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Ls(xt.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Ls(xt.layout_symbol["text-anchor"]),"text-max-angle":new Ds(xt.layout_symbol["text-max-angle"]),"text-writing-mode":new Ds(xt.layout_symbol["text-writing-mode"]),"text-rotate":new Ls(xt.layout_symbol["text-rotate"]),"text-padding":new Ds(xt.layout_symbol["text-padding"]),"text-keep-upright":new Ds(xt.layout_symbol["text-keep-upright"]),"text-transform":new Ls(xt.layout_symbol["text-transform"]),"text-offset":new Ls(xt.layout_symbol["text-offset"]),"text-allow-overlap":new Ds(xt.layout_symbol["text-allow-overlap"]),"text-overlap":new Ds(xt.layout_symbol["text-overlap"]),"text-ignore-placement":new Ds(xt.layout_symbol["text-ignore-placement"]),"text-optional":new Ds(xt.layout_symbol["text-optional"])})}};class ih{constructor(t){if(void 0===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:Vt,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return !1}serialize(){return null}}as("FormatSectionOverride",ih,{omit:["defaultValue"]});class sh extends qs{constructor(t,e){super(t,nh,e);}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const r of t)e.indexOf(r)<0&&e.push(r);this.layout._values["text-writing-mode"]=e;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||ei(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>t&&r in t?String(t[r]):""))}(e.properties,i)}createBucket(t){return new th(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of nh.paint.overridableProperties){if(!sh.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new ih(e),n=new ti(r,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new ni("source",n):new ii("composite",n,e.value.zoomStops),this.paint._values[t]=new Fs(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,r){return !(!this.layout||e.isDataDriven()||r.isDataDriven())&&sh.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get("text-field"),n=nh.paint.properties[e];let i=!1;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=!0)};if("constant"===r.value.kind&&r.value.value instanceof Ce)s(r.value.value.sections);else if("source"===r.value.kind||"composite"===r.value.kind){const t=e=>{i||(e instanceof Ne&&Ue(e.value)===Nt?s(e.value.sections):e instanceof Ir?s(e.sections):e.eachChild(t));},e=r.value;e._styleExpression&&t(e._styleExpression.expression);}return i}}let ah;var oh={get paint(){return ah=ah||new js({"background-color":new Ds(xt.paint_background["background-color"]),"background-pattern":new Rs(xt.paint_background["background-pattern"]),"background-opacity":new Ds(xt.paint_background["background-opacity"])})}};class lh extends qs{constructor(t,e){super(t,oh,e);}}let uh;var ch={get paint(){return uh=uh||new js({"raster-opacity":new Ds(xt.paint_raster["raster-opacity"]),"raster-hue-rotate":new Ds(xt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Ds(xt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Ds(xt.paint_raster["raster-brightness-max"]),"raster-saturation":new Ds(xt.paint_raster["raster-saturation"]),"raster-contrast":new Ds(xt.paint_raster["raster-contrast"]),"raster-resampling":new Ds(xt.paint_raster["raster-resampling"]),"raster-fade-duration":new Ds(xt.paint_raster["raster-fade-duration"])})}};class hh extends qs{constructor(t,e){super(t,ch,e);}}class ph extends qs{constructor(t,e){super(t,{},e),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},this.implementation=t;}is3D(){return "3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return !1}serialize(){throw new Error("Custom layers cannot be serialized")}}class fh{constructor(t){this._methodToThrottle=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle();});}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle();}),0));}remove(){delete this._channel,this._methodToThrottle=()=>{};}}const dh={once:!0},yh=6371008.8;class mh{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new mh(D(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return yh*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof mh)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new mh(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new mh(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const gh=2*Math.PI*yh;function xh(t){return gh*Math.cos(t*Math.PI/180)}function vh(t){return (180+t)/360}function bh(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function wh(t,e){return t/xh(e)}function _h(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}function Sh(t,e){return t*xh(_h(e))}class Ah{constructor(t,e,r=0){this.x=+t,this.y=+e,this.z=+r;}static fromLngLat(t,e=0){const r=mh.convert(t);return new Ah(vh(r.lng),bh(r.lat),wh(e,r.lat))}toLngLat(){return new mh(360*this.x-180,_h(this.y))}toAltitude(){return Sh(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/gh*(t=_h(this.y),1/Math.cos(t*Math.PI/180));var t;}}function kh(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}class Mh{constructor(t,e,r){if(!function(t,e,r){return !(t<0||t>25||r<0||r>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,r))throw new Error(`x=${e}, y=${r}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=r,this.key=Ph(0,t,t,e,r);}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,r){const n=(s=this.y,a=this.z,o=kh(256*(i=this.x),256*(s=Math.pow(2,a)-s-1),a),l=kh(256*(i+1),256*(s+1),a),o[0]+","+o[1]+","+l[0]+","+l[1]);var i,s,a,o,l;const u=function(t,e,r){let n,i="";for(let s=t;s>0;s--)n=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,n)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new r((t.x*e-this.x)*P,(t.y*e-this.y)*P)}toString(){return `${this.z}/${this.x}/${this.y}`}}class Ih{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Ph(t,e.z,e.z,e.x,e.y);}}class zh{constructor(t,e,r,n,i){if(this.terrainRttPosMatrix32f=null,t= z; overscaledZ = ${t}; z = ${r}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Mh(r,+n,+i),this.key=Ph(e,t,r,n,i);}clone(){return new zh(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new zh(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new zh(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const r=this.canonical.z-t;return t>this.canonical.z?Ph(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Ph(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}isChildOf(t){if(t.wrap!==this.wrap)return !1;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new zh(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new zh(e,this.wrap,e,r,n),new zh(e,this.wrap,e,r+1,n),new zh(e,this.wrap,e,r,n+1),new zh(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.ythis.maxX||this.minY>this.maxY)&&(this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0),this}shrinkBy(t){return this.expandBy(-t)}map(t){const e=new Eh;return e.extend(t(new r(this.minX,this.minY))),e.extend(t(new r(this.maxX,this.minY))),e.extend(t(new r(this.minX,this.maxY))),e.extend(t(new r(this.maxX,this.maxY))),e}static fromPoints(t){const e=new Eh;for(const r of t)e.extend(r);return e}contains(t){return t.x>=this.minX&&t.x<=this.maxX&&t.y>=this.minY&&t.y<=this.maxY}empty(){return this.minX>this.maxX}width(){return this.maxX-this.minX}height(){return this.maxY-this.minY}covers(t){return !this.empty()&&!t.empty()&&t.minX>=this.minX&&t.maxX<=this.maxX&&t.minY>=this.minY&&t.maxY<=this.maxY}intersects(t){return !this.empty()&&!t.empty()&&t.minX<=this.maxX&&t.maxX>=this.minX&&t.minY<=this.maxY&&t.maxY>=this.minY}}class Th{constructor(t){this._stringToNumber={},this._numberToString=[];for(let e=0;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class Bh{constructor(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}class Vh{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new is(P,16,0),this.grid3D=new is(P,16,0),this.featureIndexArray=new Ca,this.promoteId=e;}insert(t,e,r,n,i,s){const a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);const o=s?this.grid3D:this.grid;for(let t=0;t=0&&n[3]>=0&&o.insert(a,n[0],n[1],n[2],n[3]);}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new vu(new nc(this.rawTileData)).layers,this.sourceLayerCoder=new Th(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,n,i){this.loadVTLayers();const s=t.params,a=P/t.tileSize/t.scale,o=hi(s.filter,s.globalState),l=t.queryGeometry,u=t.queryPadding*a,c=Eh.fromPoints(l),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=Eh.fromPoints(t.cameraQueryGeometry).expandBy(u),f=this.grid3D.query(p.minX,p.minY,p.maxX,p.maxY,((e,n,i,s)=>function(t,e,n,i,s){for(const r of t)if(e<=r.x&&n<=r.y&&i>=r.x&&s>=r.y)return !0;const a=[new r(e,n),new r(e,s),new r(i,s),new r(i,n)];if(t.length>2)for(const e of a)if(Ro(t,e))return !0;for(let e=0;e(p||(p=Mo(e)),r.queryIntersectsFeature({queryGeometry:l,feature:e,featureState:n,geometry:p,zoom:this.z,transform:t.transform,pixelsToTileUnits:a,pixelPosMatrix:t.pixelPosMatrix,unwrappedTileID:this.tileID.toUnwrapped(),getElevation:t.getElevation}))));}return d}loadMatchingFeature(t,e,r,n,i,s,a,o,l,u,c){const h=this.bucketLayerIDs[e];if(s&&!h.some((t=>s.has(t))))return;const p=this.sourceLayerCoder.decode(r),f=this.vtLayers[p].feature(n);if(i.needGeometry){const t=Io(f,!0);if(!i.filter(new Is(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new Is(this.tileID.overscaledZ),f))return;const d=this.getId(f,p);for(let e=0;e{const a=e instanceof $s?e.get(s):null;return a&&a.evaluate?a.evaluate(r,n,i):a}))}function $h(t,e){return e-t}function Dh(t,e,n,i,s){const a=[];for(let o=0;o=i&&c.x>=i||(o.x>=i?o=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round():c.x>=i&&(c=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round()),o.y>=s&&c.y>=s||(o.y>=s?o=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round():c.y>=s&&(c=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round()),u&&o.equals(u[u.length-1])||(u=[o],a.push(u)),u.push(c)))));}}return a}as("FeatureIndex",Vh,{omit:["rawTileData","sourceLayerCoder"]});class Lh extends r{constructor(t,e,r,n){super(t,e),this.angle=r,void 0!==n&&(this.segment=n);}clone(){return new Lh(this.x,this.y,this.angle,this.segment)}}function Oh(t,e,r,n,i){if(void 0===e.segment||0===r)return !0;let s=e,a=e.segment+1,o=0;for(;o>-r/2;){if(a--,a<0)return !1;o-=t[a].dist(s),s=t[a];}o+=t[a].dist(t[a+1]),a++;const l=[];let u=0;for(;on;)u-=l.shift().angleDelta;if(u>i)return !1;a++,o+=e.dist(r);}return !0}function Rh(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=dr.number(n.x,i.x,c),p=dr.number(n.y,i.y,c),f=new Lh(h,p,i.angleTo(n),r);return f._round(),!a||Oh(t,f,o,a,e)?f:void 0}l+=s;}}function qh(t,e,r,n,i,s,a,o,l){const u=Uh(n,s,a),c=jh(n,i),h=c*a,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new Lh(g,x,y,e);r._round(),n&&!Oh(t,r,s,n,i)||f.push(r);}}h+=d;}return o||f.length||a||(f=Gh(t,h/2,r,n,i,s,a,!0,l)),f}function Xh(t,e,n,i){const s=[],a=t.image,o=a.pixelRatio,l=a.paddedRect.w-2,u=a.paddedRect.h-2;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=a.stretchX||[[0,l]],p=a.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=l-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,S=m,A=0,k=g;if(a.content&&i){const e=a.content,r=e[2]-e[0],n=e[3]-e[1];(a.textFitWidth||a.textFitHeight)&&(c=jc(t)),x=Zh(h,0,e[0]),b=Zh(p,0,e[1]),v=Zh(h,e[0],e[2]),w=Zh(p,e[1],e[3]),_=e[0]-x,A=e[1]-b,S=r-v,k=n-w;}const M=c.x1,I=c.y1,z=c.x2-M,P=c.y2-I,C=(t,i,s,l)=>{const u=Hh(t.stretch-x,v,z,M),c=Kh(t.fixed-_,S,t.stretch,d),h=Hh(i.stretch-b,w,P,I),p=Kh(i.fixed-A,k,i.stretch,y),f=Hh(s.stretch-x,v,z,M),m=Kh(s.fixed-_,S,s.stretch,d),g=Hh(l.stretch-b,w,P,I),C=Kh(l.fixed-A,k,l.stretch,y),E=new r(u,h),T=new r(f,h),B=new r(f,g),V=new r(u,g),F=new r(c/o,p/o),$=new r(m/o,C/o),D=e*Math.PI/180;if(D){const t=Math.sin(D),e=Math.cos(D),r=[e,-t,t,e];E._matMult(r),T._matMult(r),V._matMult(r),B._matMult(r);}const L=t.stretch+t.fixed,O=i.stretch+i.fixed;return {tl:E,tr:T,bl:V,br:B,tex:{x:a.paddedRect.x+1+L,y:a.paddedRect.y+1+O,w:s.stretch+s.fixed-L,h:l.stretch+l.fixed-O},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:F,pixelOffsetBR:$,minFontScaleX:S/o/z,minFontScaleY:k/o/P,isSDF:n}};if(i&&(a.stretchX||a.stretchY)){const t=Yh(h,m,d),e=Yh(p,g,y);for(let r=0;r0&&(n=Math.max(10,n),this.circleDiameter=n);}else {const u=(null===(h=a.image)||void 0===h?void 0:h.content)&&(a.image.textFitWidth||a.image.textFitHeight)?jc(a):{x1:a.left,y1:a.top,x2:a.right,y2:a.bottom};u.y1=u.y1*o-l[0],u.y2=u.y2*o+l[2],u.x1=u.x1*o-l[3],u.x2=u.x2*o+l[1];const p=a.collisionPadding;if(p&&(u.x1-=p[0]*o,u.y1-=p[1]*o,u.x2+=p[2]*o,u.y2+=p[3]*o),c){const t=new r(u.x1,u.y1),e=new r(u.x2,u.y1),n=new r(u.x1,u.y2),i=new r(u.x2,u.y2),s=c*Math.PI/180;t._rotate(s),e._rotate(s),n._rotate(s),i._rotate(s),u.x1=Math.min(t.x,e.x,n.x,i.x),u.x2=Math.max(t.x,e.x,n.x,i.x),u.y1=Math.min(t.y,e.y,n.y,i.y),u.y2=Math.max(t.y,e.y,n.y,i.y);}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,n,i,s);}this.boxEndIndex=t.length;}}class Wh{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}}function Qh(t,e=1,n=!1){const i=Eh.fromPoints(t[0]),s=Math.min(i.width(),i.height());let a=s/2;const o=new Wh([],tp),{minX:l,minY:u,maxX:c,maxY:h}=i;if(0===s)return new r(l,u);for(let e=l;ep.d||!p.d)&&(p=r,n&&console.log("found best %d after %d probes",Math.round(1e4*r.d)/1e4,f)),r.max-p.d<=e||(a=r.h/2,o.push(new ep(r.p.x-a,r.p.y-a,a,t)),o.push(new ep(r.p.x+a,r.p.y-a,a,t)),o.push(new ep(r.p.x-a,r.p.y+a,a,t)),o.push(new ep(r.p.x+a,r.p.y+a,a,t)),f+=4);}return n&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function tp(t,e){return e.max-t.max}function ep(t,e,n,i){this.p=new r(t,e),this.h=n,this.d=function(t,e){let r=!1,n=1/0;for(let i=0;it.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(r=!r),n=Math.min(n,Lo(t,i,o));}}return (r?1:-1)*Math.sqrt(n)}(this.p,i),this.max=this.d+this.h*Math.SQRT2;}var rp;t.aE=void 0,(rp=t.aE||(t.aE={}))[rp.center=1]="center",rp[rp.left=2]="left",rp[rp.right=3]="right",rp[rp.top=4]="top",rp[rp.bottom=5]="bottom",rp[rp["top-left"]=6]="top-left",rp[rp["top-right"]=7]="top-right",rp[rp["bottom-left"]=8]="bottom-left",rp[rp["bottom-right"]=9]="bottom-right";const np=Number.POSITIVE_INFINITY;function ip(t,e){return e[1]!==np?function(t,e,r){let n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case "top-right":case "top-left":case "top":i=r-7;break;case "bottom-right":case "bottom-left":case "bottom":i=7-r;}switch(t){case "top-right":case "bottom-right":case "right":n=-e;break;case "top-left":case "bottom-left":case "left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){let r=0,n=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case "top-right":case "top-left":n=i-7;break;case "bottom-right":case "bottom-left":n=7-i;break;case "bottom":n=7-e;break;case "top":n=e-7;}switch(t){case "top-right":case "bottom-right":r=-i;break;case "top-left":case "bottom-left":r=i;break;case "left":r=e;break;case "right":r=-e;}return [r,n]}(t,e[0])}function sp(t,e,r){var n;const i=t.layout,s=null===(n=i.get("text-variable-anchor-offset"))||void 0===n?void 0:n.evaluate(e,{},r);if(s){const t=s.values,e=[];for(let r=0;rt*Qu));n.startsWith("top")?i[1]-=7:n.startsWith("bottom")&&(i[1]+=7),e[r+1]=i;}return new $e(e)}const a=i.get("text-variable-anchor");if(a){let n;n=void 0!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},r)*Qu,np]:i.get("text-offset").evaluate(e,{},r).map((t=>t*Qu));const s=[];for(const t of a)s.push(t,ip(t,n));return new $e(s)}return null}function ap(t){switch(t){case "right":case "top-right":case "bottom-right":return "right";case "left":case "top-left":case "bottom-left":return "left"}return "center"}function op(e,r,n,i,s,a,o,l,u,c,h,p){let f=a.textMaxSize.evaluate(r,{});void 0===f&&(f=o);const d=e.layers[0].layout,y=d.get("icon-offset").evaluate(r,{},h),m=up(n.horizontal),g=o/24,x=e.tilePixelRatio*g,v=e.tilePixelRatio*f/24,b=e.tilePixelRatio*l,w=e.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*e.tilePixelRatio,S=function(t,e,r,n=1){const i=t.get("icon-padding").evaluate(e,{},r),s=i&&i.values;return [s[0]*n,s[1]*n,s[2]*n,s[3]*n]}(d,r,h,e.tilePixelRatio),A=d.get("text-max-angle")/180*Math.PI,k="viewport"!==d.get("text-rotation-alignment")&&"point"!==d.get("symbol-placement"),M="map"===d.get("icon-rotation-alignment")&&"point"!==d.get("symbol-placement"),I=d.get("symbol-placement"),z=w/2,C=d.get("icon-text-fit");let E;i&&"none"!==C&&(e.allowVerticalPlacement&&n.vertical&&(E=Nc(i,n.vertical,C,d.get("icon-text-fit-padding"),y,g)),m&&(i=Nc(i,m,C,d.get("icon-text-fit-padding"),y,g)));const T=h?p.line.getGranularityForZoomLevel(h.z):1,B=(l,p)=>{p.x<0||p.x>=P||p.y<0||p.y>=P||function(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k){const M=e.addToLineVertexArray(r,n);let I,z,P,C,E=0,T=0,B=0,V=0,F=-1,$=-1;const D={};let L=no("");if(e.allowVerticalPlacement&&i.vertical){const t=l.layout.get("text-rotate").evaluate(w,{},A)+90;P=new Jh(u,r,c,h,p,i.vertical,f,d,y,t),o&&(C=new Jh(u,r,c,h,p,o,g,x,y,t));}if(s){const n=l.layout.get("icon-rotate").evaluate(w,{}),i="none"!==l.layout.get("icon-text-fit"),a=Xh(s,n,S,i),f=o?Xh(o,n,S,i):void 0;z=new Jh(u,r,c,h,p,s,g,x,!1,n),E=4*a.length;const d=e.iconSizeData;let y=null;"source"===d.kind?(y=[qc*l.layout.get("icon-size").evaluate(w,{})],y[0]>Gc&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)):"composite"===d.kind&&(y=[qc*_.compositeIconSizes[0].evaluate(w,{},A),qc*_.compositeIconSizes[1].evaluate(w,{},A)],(y[0]>Gc||y[1]>Gc)&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)),e.addSymbols(e.icon,a,y,b,v,w,t.ao.none,r,M.lineStartIndex,M.lineLength,-1,A),F=e.icon.placedSymbolArray.length-1,f&&(T=4*f.length,e.addSymbols(e.icon,f,y,b,v,w,t.ao.vertical,r,M.lineStartIndex,M.lineLength,-1,A),$=e.icon.placedSymbolArray.length-1);}const O=Object.keys(i.horizontal);for(const n of O){const s=i.horizontal[n];if(!I){L=no(s.text);const t=l.layout.get("text-rotate").evaluate(w,{},A);I=new Jh(u,r,c,h,p,s,f,d,y,t);}const o=1===s.positionedLines.length;if(B+=lp(e,r,s,a,l,y,w,m,M,i.vertical?t.ao.horizontal:t.ao.horizontalOnly,o?O:[n],D,F,_,A),o)break}i.vertical&&(V+=lp(e,r,i.vertical,a,l,y,w,m,M,t.ao.vertical,["vertical"],D,$,_,A));const R=I?I.boxStartIndex:e.collisionBoxArray.length,U=I?I.boxEndIndex:e.collisionBoxArray.length,j=P?P.boxStartIndex:e.collisionBoxArray.length,N=P?P.boxEndIndex:e.collisionBoxArray.length,G=z?z.boxStartIndex:e.collisionBoxArray.length,X=z?z.boxEndIndex:e.collisionBoxArray.length,Z=C?C.boxStartIndex:e.collisionBoxArray.length,Y=C?C.boxEndIndex:e.collisionBoxArray.length;let H=-1;const K=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=K(I,H),H=K(P,H),H=K(z,H),H=K(C,H);const J=H>-1?1:0;J&&(H*=k/Qu),e.glyphOffsetArray.length>=th.MAX_GLYPHS&&q("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==w.sortKey&&e.addToSortKeyRanges(e.symbolInstances.length,w.sortKey);const W=sp(l,w,A),[Q,tt]=function(e,r){const n=e.length,i=null==r?void 0:r.values;if((null==i?void 0:i.length)>0)for(let r=0;r=0?D.right:-1,D.center>=0?D.center:-1,D.left>=0?D.left:-1,D.vertical||-1,F,$,L,R,U,j,N,G,X,Z,Y,c,B,V,E,T,J,0,f,H,Q,tt);}(e,p,l,n,i,s,E,e.layers[0],e.collisionBoxArray,r.index,r.sourceLayerIndex,e.index,x,[_,_,_,_],k,u,b,S,M,y,r,a,c,h,o);};if("line"===I)for(const t of Dh(r.geometry,0,0,P,P)){const r=ru(t,T),s=qh(r,w,A,n.vertical||m,i,24,v,e.overscaling,P);for(const t of s)m&&cp(e,m.text,z,t)||B(r,t);}else if("line-center"===I){for(const t of r.geometry)if(t.length>1){const e=ru(t,T),r=Nh(e,A,n.vertical||m,i,24,v);r&&B(e,r);}}else if("Polygon"===r.type)for(const t of Qr(r.geometry,0)){const e=Qh(t,16);B(ru(t[0],T,!0),new Lh(e.x,e.y,0));}else if("LineString"===r.type)for(const t of r.geometry){const e=ru(t,T);B(e,new Lh(e[0].x,e[0].y,0));}else if("Point"===r.type)for(const t of r.geometry)for(const e of t)B([e],new Lh(e.x,e.y,0));}function lp(t,e,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=function(t,e,n,i,s,a,o,l){const u=i.layout.get("text-rotate").evaluate(a,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const i of t.positionedGlyphs){if(!i.rect)continue;const a=i.rect||{};let h=4,p=!0,f=1,d=0;const y=(s||l)&&i.vertical,m=i.metrics.advance*i.scale/2;if(l&&e.verticalizable&&(d=t.lineOffset/2-(i.imageName?-(Qu-i.metrics.width*i.scale)/2:(i.scale-1)*Qu)),i.imageName){const t=o[i.imageName];p=t.sdf,f=t.pixelRatio,h=1/f;}const g=s?[i.x+m,i.y]:[0,0];let x=s?[0,0]:[i.x+m+n[0],i.y+n[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=i.metrics.isDoubleResolution?2:1,w=(i.metrics.left-h)*i.scale-m+x[0],_=(-i.metrics.top-h)*i.scale+x[1],S=w+a.w/b*i.scale/f,A=_+a.h/b*i.scale/f,k=new r(w,_),M=new r(S,_),I=new r(w,A),z=new r(S,A);if(y){const t=new r(-m,m- -17),e=-Math.PI/2,n=12-m,s=new r(22-n,-(i.imageName?n:0)),a=new r(...v);k._rotateAround(e,t)._add(s)._add(a),M._rotateAround(e,t)._add(s)._add(a),I._rotateAround(e,t)._add(s)._add(a),z._rotateAround(e,t)._add(s)._add(a);}if(u){const t=Math.sin(u),e=Math.cos(u),r=[e,-t,t,e];k._matMult(r),M._matMult(r),I._matMult(r),z._matMult(r);}const P=new r(0,0),C=new r(0,0);c.push({tl:k,tr:M,bl:I,br:z,tex:a,writingMode:e.writingMode,glyphOffset:g,sectionIndex:i.sectionIndex,isSDF:p,pixelOffsetTL:P,pixelOffsetBR:C,minFontScaleX:0,minFontScaleY:0});}return c}(0,n,l,s,a,o,i,t.allowVerticalPlacement),g=t.textSizeData;let x=null;"source"===g.kind?(x=[qc*s.layout.get("text-size").evaluate(o,{})],x[0]>Gc&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)):"composite"===g.kind&&(x=[qc*d.compositeTextSizes[0].evaluate(o,{},y),qc*d.compositeTextSizes[1].evaluate(o,{},y)],(x[0]>Gc||x[1]>Gc)&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)),t.addSymbols(t.text,m,x,l,a,o,c,e,u.lineStartIndex,u.lineLength,f,y);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*m.length}function up(t){for(const e in t)return t[e];return null}function cp(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=hp[15&r];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new pp(a,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=hp.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+s+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return fp(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,r,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:a}=this,o=[0,i.length-1,0],l=[];for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=a){for(let a=h;a<=c;a++){const o=s[2*a],u=s[2*a+1];o>=t&&o<=r&&u>=e&&u<=n&&l.push(i[a]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?r>=f:n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return l}within(t,e,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:n,coords:i,nodeSize:s}=this,a=[0,n.length-1,0],o=[],l=r*r;for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)gp(i[2*r],i[2*r+1],t,e)<=l&&o.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];gp(f,d,t,e)<=l&&o.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return o}}function fp(t,e,r,n,i,s){if(i-n<=r)return;const a=n+i>>1;dp(t,e,a,n,i,s),fp(t,e,r,n,a-1,1-s),fp(t,e,r,a+1,i,1-s);}function dp(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const a=i-n+1,o=r-n+1,l=Math.log(a),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(a-u)/a)*(o-a/2<0?-1:1);dp(t,e,r,Math.max(n,Math.floor(r-o*u/a+c)),Math.min(i,Math.floor(r+(a-o)*u/a+c)),s);}const a=e[2*r+s];let o=n,l=i;for(yp(t,e,n,r),e[2*i+s]>a&&yp(t,e,n,i);oa;)l--;}e[2*n+s]===a?yp(t,e,n,l):(l++,yp(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1);}}function yp(t,e,r,n){mp(t,r,n),mp(e,2*r,2*n),mp(e,2*r+1,2*n+1);}function mp(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function gp(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}var xp;t.cx=void 0,(xp=t.cx||(t.cx={})).create="create",xp.load="load",xp.fullLoad="fullLoad";let vp=null,bp=[];const wp=1e3/60,_p="loadTime",Sp="fullLoadTime",Ap={mark(t){performance.mark(t);},frame(t){const e=t;null!=vp&&bp.push(e-vp),vp=e;},clearMetrics(){vp=null,bp=[],performance.clearMeasures(_p),performance.clearMeasures(Sp);for(const e in t.cx)performance.clearMarks(t.cx[e]);},getPerformanceMetrics(){performance.measure(_p,t.cx.create,t.cx.load),performance.measure(Sp,t.cx.create,t.cx.fullLoad);const e=performance.getEntriesByName(_p)[0].duration,r=performance.getEntriesByName(Sp)[0].duration,n=bp.length,i=1/(bp.reduce(((t,e)=>t+e),0)/n/1e3),s=bp.filter((t=>t>wp)).reduce(((t,e)=>t+(e-wp)/wp),0);return {loadTime:e,fullLoadTime:r,fps:i,percentDroppedFrames:s/(n+s)*100,totalFrames:n}}};t.$=P,t.A=f,t.B=function([t,e,r]){return e+=90,e*=Math.PI/180,r*=Math.PI/180,{x:t*Math.cos(e)*Math.sin(r),y:t*Math.sin(e)*Math.sin(r),z:t*Math.cos(r)}},t.C=dr,t.D=Ds,t.E=gt,t.F=Is,t.G=ts,t.H=function(t){if(null==Z){const e=t.navigator?t.navigator.userAgent:null;Z=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return Z},t.I=vc,t.J=class{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new fh((()=>this.process())),this.subscription=Q(this.target,"message",(t=>this.receive(t)),!1),this.globalScope=X(self)?t:window;}registerMessageHandler(t,e){this.messageHandlers[t]=e;}sendAsync(t,e){return new Promise(((r,n)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10),s=e?Q(e.signal,"abort",(()=>{null==s||s.unsubscribe(),delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e);}),dh):null;this.resolveRejects[i]={resolve:t=>{null==s||s.unsubscribe(),r(t);},reject:t=>{null==s||s.unsubscribe(),n(t);}};const a=[],o=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:cs(t.data,a)});this.target.postMessage(o,{transfer:a});}))}receive(t){const e=t.data,r=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[r];const t=this.abortControllers[r];return delete this.abortControllers[r],void(t&&t.abort())}if(X(self)||e.mustQueue)return this.tasks[r]=e,this.taskQueue.push(r),void this.invoker.trigger();this.processTask(r,e);}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e);}processTask(t,r){return e(this,void 0,void 0,(function*(){if(""===r.type){const e=this.resolveRejects[t];if(delete this.resolveRejects[t],!e)return;return void(r.error?e.reject(hs(r.error)):e.resolve(hs(r.data)))}if(!this.messageHandlers[r.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${r.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const e=hs(r.data),n=new AbortController;this.abortControllers[t]=n;try{const i=yield this.messageHandlers[r.type](r.sourceMapId,e,n);this.completeTask(t,null,i);}catch(e){this.completeTask(t,e);}}))}completeTask(t,e,r){const n=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?cs(e):null,data:cs(r,n)};this.target.postMessage(i,{transfer:n});}remove(){this.invoker.remove(),this.subscription.unsubscribe();}},t.K=lt,t.L=function(){var t=new f(16);return f!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.M=function(t,e,r){var n,i,s,a,o,l,u,c,h,p,f,d,y=r[0],m=r[1],g=r[2];return e===t?(t[12]=e[0]*y+e[4]*m+e[8]*g+e[12],t[13]=e[1]*y+e[5]*m+e[9]*g+e[13],t[14]=e[2]*y+e[6]*m+e[10]*g+e[14],t[15]=e[3]*y+e[7]*m+e[11]*g+e[15]):(i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=n=e[0],t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=n*y+o*m+h*g+e[12],t[13]=i*y+l*m+p*g+e[13],t[14]=s*y+u*m+f*g+e[14],t[15]=a*y+c*m+d*g+e[15]),t},t.N=function(t,e,r){var n=r[0],i=r[1],s=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.O=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],y=e[12],m=e[13],g=e[14],x=e[15],v=r[0],b=r[1],w=r[2],_=r[3];return t[0]=v*n+b*o+w*h+_*y,t[1]=v*i+b*l+w*p+_*m,t[2]=v*s+b*u+w*f+_*g,t[3]=v*a+b*c+w*d+_*x,t[4]=(v=r[4])*n+(b=r[5])*o+(w=r[6])*h+(_=r[7])*y,t[5]=v*i+b*l+w*p+_*m,t[6]=v*s+b*u+w*f+_*g,t[7]=v*a+b*c+w*d+_*x,t[8]=(v=r[8])*n+(b=r[9])*o+(w=r[10])*h+(_=r[11])*y,t[9]=v*i+b*l+w*p+_*m,t[10]=v*s+b*u+w*f+_*g,t[11]=v*a+b*c+w*d+_*x,t[12]=(v=r[12])*n+(b=r[13])*o+(w=r[14])*h+(_=r[15])*y,t[13]=v*i+b*l+w*p+_*m,t[14]=v*s+b*u+w*f+_*g,t[15]=v*a+b*c+w*d+_*x,t},t.P=r,t.Q=function(t,e){const r={};for(let n=0;n!n.has(t.id)))),o.update&&(o.update=o.update.filter((t=>!n.has(t.id))));const i=new Set((null!==(r=t.add)&&void 0!==r?r:[]).map((t=>t.id)));e.remove=e.remove.filter((t=>!i.has(t)));}if(e.remove){const t=new Set(o.remove?o.remove.concat(e.remove):e.remove);o.remove=Array.from(t.values());}if(e.add){const t=o.add?o.add.concat(e.add):e.add,r=new Map(t.map((t=>[t.id,t])));o.add=Array.from(r.values());}if(e.update){const t=new Map(null===(n=o.update)||void 0===n?void 0:n.map((t=>[t.id,t])));for(const r of e.update){const e=null!==(i=t.get(r.id))&&void 0!==i?i:{id:r.id};r.newGeometry&&(e.newGeometry=r.newGeometry),r.addOrUpdateProperties&&(e.addOrUpdateProperties=(null!==(s=e.addOrUpdateProperties)&&void 0!==s?s:[]).concat(r.addOrUpdateProperties)),r.removeProperties&&(e.removeProperties=(null!==(a=e.removeProperties)&&void 0!==a?a:[]).concat(r.removeProperties)),r.removeAllProperties&&(e.removeAllProperties=!0),t.set(r.id,e);}o.update=Array.from(t.values());}return o.remove&&o.add&&(o.remove=o.remove.filter((t=>-1===o.add.findIndex((e=>e.id===t))))),o},t.a1=Ah,t.a2=Eh,t.a3=25,t.a4=Mh,t.a5=t=>{const e=window.document.createElement("video");return e.muted=!0,new Promise((r=>{e.onloadstart=()=>{r(e);};for(const r of t){const t=window.document.createElement("source");pt(r)||(e.crossOrigin="Anonymous"),t.src=r,e.appendChild(t);}}))},t.a6=Ct,t.a7=function(){return O++},t.a8=ba,t.a9=th,t.aA=function(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return [e,r,n,i]},t.aB=Qu,t.aC=C,t.aD=function(t,e,r,n,i=!1){if(!r[0]&&!r[1])return [0,0];const s=i?"map"===n?-t.bearingInRadians:0:"viewport"===n?t.bearingInRadians:0;if(s){const t=Math.sin(s),e=Math.cos(s);r=[r[0]*e-r[1]*t,r[0]*t+r[1]*e];}return [i?r[0]:C(e,r[0],t.zoom),i?r[1]:C(e,r[1],t.zoom)]},t.aF=Zc,t.aG=ap,t.aH=Vc,t.aI=pp,t.aJ=Ys,t.aK=Jl,t.aL=Ea,t.aM=Za,t.aN=Na,t.aO=D,t.aP=et,t.aQ=Sh,t.aR=b,t.aS=v,t.aT=function(t){var e=new f(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.aU=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t},t.aV=function(t,e){var r=e[0],n=e[1],i=e[2],s=r*r+n*n+i*i;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t},t.aW=w,t.aX=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.aY=function(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t},t.aZ=g,t.a_=function(t,e,r){const n=e[0]*r[0]+e[1]*r[1]+e[2]*r[2];return 0===n?null:(-(t[0]*r[0]+t[1]*r[1]+t[2]*r[2])-r[3])/n},t.aa=hi,t.ab=Io,t.ac=Bh,t.ad=function(t){const e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,r,n,i)=>{const s=n||i;return e[r]=!s||s.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t;}return e},t.ae=tt,t.af=function(t){return Math.pow(2,t)},t.ag=y,t.ah=$,t.ai=85.051129,t.aj=wh,t.ak=function(t){return Math.log(t)/Math.LN2},t.al=function(t){var e=t[0],r=t[1];return e*e+r*r},t.am=function(t,e){const r=[];for(const n in t)n in e||r.push(n);return r},t.an=function(t,e){let r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){const{interpolationType:i,minZoom:s,maxZoom:a}=t,o=i?$(pr.interpolationFactor(i,e,s,a),0,1):0;"camera"===t.kind?n=dr.number(t.minSize,t.maxSize,o):r=o;}return {uSizeT:r,uSize:n}},t.ap=function(t,{uSize:e,uSizeT:r},{lowerSize:n,upperSize:i}){return "source"===t.kind?n/qc:"composite"===t.kind?dr.number(n/qc,i/qc,r):e},t.aq=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],y=e[13],m=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,w=n*l-i*o,_=n*u-s*o,S=i*u-s*l,A=c*y-h*d,k=c*m-p*d,M=c*g-f*d,I=h*m-p*y,z=h*g-f*y,P=p*g-f*m,C=x*P-v*z+b*I+w*M-_*k+S*A;return C?(t[0]=(o*P-l*z+u*I)*(C=1/C),t[1]=(i*z-n*P-s*I)*C,t[2]=(y*S-m*_+g*w)*C,t[3]=(p*_-h*S-f*w)*C,t[4]=(l*M-a*P-u*k)*C,t[5]=(r*P-i*M+s*k)*C,t[6]=(m*b-d*S-g*v)*C,t[7]=(c*S-p*b+f*v)*C,t[8]=(a*z-o*M+u*A)*C,t[9]=(n*M-r*z-s*A)*C,t[10]=(d*_-y*b+g*x)*C,t[11]=(h*b-c*_-f*x)*C,t[12]=(o*k-a*I-l*A)*C,t[13]=(r*I-n*k+i*A)*C,t[14]=(y*v-d*w-m*x)*C,t[15]=(c*w-h*v+p*x)*C,t):null},t.ar=I,t.as=function(t){var e=t[0],r=t[1];return Math.sqrt(e*e+r*r)},t.at=function(t){return t[0]=0,t[1]=0,t},t.au=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t},t.av=Kc,t.aw=A,t.ax=function(t,e,n,i){const s=e.y-t.y,a=e.x-t.x,o=i.y-n.y,l=i.x-n.x,u=o*a-l*s;if(0===u)return null;const c=(l*(t.y-n.y)-o*(t.x-n.x))/u;return new r(t.x+c*a,t.y+c*s)},t.ay=Dh,t.az=Eo,t.b=Y,t.b$=class extends la{},t.b0=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t},t.b1=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]},t.b2=Ih,t.b3=Ph,t.b4=function(t,e,r,n,i){var s=1/Math.tan(e/2);if(t[0]=s/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=s,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0){var a=1/(n-i);t[10]=(i+n)*a,t[14]=2*i*n*a;}else t[10]=-1,t[14]=-2*n;return t},t.b5=function(t){var e=new f(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.b6=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[4],c=e[5],h=e[6],p=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i+u*n,t[1]=a*i+c*n,t[2]=o*i+h*n,t[3]=l*i+p*n,t[4]=u*i-s*n,t[5]=c*i-a*n,t[6]=h*i-o*n,t[7]=p*i-l*n,t},t.b7=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=s*i+u*n,t[5]=a*i+c*n,t[6]=o*i+h*n,t[7]=l*i+p*n,t[8]=u*i-s*n,t[9]=c*i-a*n,t[10]=h*i-o*n,t[11]=p*i-l*n,t},t.b8=function(){const t=new Float32Array(16);return y(t),t},t.b9=function(){const t=new Float64Array(16);return y(t),t},t.bA=function(t,e){const r=E(t,360),n=E(e,360),i=n-r,s=n>r?i-360:i+360;return Math.abs(i)0?a:-a},t.bD=function(t,e){const r=E(t,2*Math.PI),n=E(e,2*Math.PI);return Math.min(Math.abs(r-n),Math.abs(r-n+2*Math.PI),Math.abs(r-n-2*Math.PI))},t.bE=function(){const t={},e=xt.$version;for(const r in xt.$root){const n=xt.$root[r];if(n.required){let i=null;i="version"===r?e:"array"===n.type?[]:{},null!=i&&(t[r]=i);}}return t},t.bF=ps,t.bG=ct,t.bH=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(let n=0;n{"source"in t&&n[t.source]?r.push({command:"removeLayer",args:[t.id]}):s.push(t);})),r=r.concat(i),function(t,e,r){e=e||[];const n=(t=t||[]).map(zt),i=e.map(zt),s=t.reduce(Pt,{}),a=e.reduce(Pt,{}),o=n.slice(),l=Object.create(null);let u,c,h,p,f;for(let t=0,e=0;tp?(i=Math.acos(s),a=Math.sin(i),o=Math.sin((1-n)*i)/a,l=Math.sin(n*i)/a):(o=1-n,l=n),t[0]=o*u+l*d,t[1]=o*c+l*y,t[2]=o*h+l*m,t[3]=o*f+l*g,t},t.bd=function(t){const e=new Float64Array(9);var r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v;h=(i=(n=t)[0])*(l=i+i),p=(s=n[1])*l,d=(a=n[2])*l,y=a*(u=s+s),g=(o=n[3])*l,x=o*u,v=o*(c=a+a),(r=e)[0]=1-(f=s*u)-(m=a*c),r[3]=p-v,r[6]=d+x,r[1]=p+v,r[4]=1-h-m,r[7]=y-g,r[2]=d-x,r[5]=y+g,r[8]=1-h-f;const b=et(-Math.asin($(e[2],-1,1)));let w,_;return Math.hypot(e[5],e[8])<.001?(w=0,_=-et(Math.atan2(e[3],e[4]))):(w=et(0===e[5]&&0===e[8]?0:Math.atan2(e[5],e[8])),_=et(0===e[1]&&0===e[0]?0:Math.atan2(e[1],e[0]))),{roll:w,pitch:b+90,bearing:_}},t.be=function(t,e){return t.roll==e.roll&&t.pitch==e.pitch&&t.bearing==e.bearing},t.bf=Me,t.bg=uo,t.bh=Wl,t.bi=Ql,t.bj=Kl,t.bk=T,t.bl=B,t.bm=Le,t.bn=function(t,e,r,n,i){return T(n,i,$((t-e)/(r-e),0,1))},t.bo=E,t.bp=function(){return new Float64Array(3)},t.bq=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t},t.br=M,t.bs=function(t,e,r){var n=r[0],i=r[1],s=r[2],a=r[3],o=e[0],l=e[1],u=e[2],c=i*u-s*l,h=s*o-n*u,p=n*l-i*o;return t[0]=o+a*(c+=c)+i*(p+=p)-s*(h+=h),t[1]=l+a*h+s*c-n*p,t[2]=u+a*p+n*h-i*c,t},t.bt=function(t,e,r){const n=(i=[t[0],t[1],t[2],e[0],e[1],e[2],r[0],r[1],r[2]])[0]*((c=i[8])*(a=i[4])-(o=i[5])*(u=i[7]))+i[1]*(-c*(s=i[3])+o*(l=i[6]))+i[2]*(u*s-a*l);var i,s,a,o,l,u,c;if(0===n)return null;const h=w([],[e[0],e[1],e[2]],[r[0],r[1],r[2]]),p=w([],[r[0],r[1],r[2]],[t[0],t[1],t[2]]),f=w([],[t[0],t[1],t[2]],[e[0],e[1],e[2]]),d=b([],h,-t[3]);return v(d,d,b([],p,-e[3])),v(d,d,b([],f,-r[3])),b(d,d,1/n),d},t.bu=yh,t.bv=function(){return new Float64Array(4)},t.bw=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),s[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),s[2]=i[2],t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bx=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0],s[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),s[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.by=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),s[1]=i[1],s[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bz=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i-u*n,t[1]=a*i-c*n,t[2]=o*i-h*n,t[3]=l*i-p*n,t[8]=s*n+u*i,t[9]=a*n+c*i,t[10]=o*n+h*i,t[11]=l*n+p*i,t},t.c=st,t.c0=Ku,t.c1=class extends ca{},t.c2=cl,t.c3=function(t){return t<=1?1:Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},t.c4=ul,t.c5=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[3]*n+r[7]*i+r[11]*s+r[15];return t[0]=(r[0]*n+r[4]*i+r[8]*s+r[12])/(a=a||1),t[1]=(r[1]*n+r[5]*i+r[9]*s+r[13])/a,t[2]=(r[2]*n+r[6]*i+r[10]*s+r[14])/a,t},t.c6=class extends Ws{},t.c7=class extends ga{},t.c8=function(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[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]},t.c9=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=t[9],f=t[10],d=t[11],y=t[12],m=t[13],g=t[14],x=t[15],v=e[0],b=e[1],w=e[2],_=e[3],S=e[4],A=e[5],k=e[6],M=e[7],I=e[8],z=e[9],P=e[10],C=e[11],E=e[12],T=e[13],B=e[14],V=e[15];return Math.abs(r-v)<=p*Math.max(1,Math.abs(r),Math.abs(v))&&Math.abs(n-b)<=p*Math.max(1,Math.abs(n),Math.abs(b))&&Math.abs(i-w)<=p*Math.max(1,Math.abs(i),Math.abs(w))&&Math.abs(s-_)<=p*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(a-S)<=p*Math.max(1,Math.abs(a),Math.abs(S))&&Math.abs(o-A)<=p*Math.max(1,Math.abs(o),Math.abs(A))&&Math.abs(l-k)<=p*Math.max(1,Math.abs(l),Math.abs(k))&&Math.abs(u-M)<=p*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(c-I)<=p*Math.max(1,Math.abs(c),Math.abs(I))&&Math.abs(h-z)<=p*Math.max(1,Math.abs(h),Math.abs(z))&&Math.abs(f-P)<=p*Math.max(1,Math.abs(f),Math.abs(P))&&Math.abs(d-C)<=p*Math.max(1,Math.abs(d),Math.abs(C))&&Math.abs(y-E)<=p*Math.max(1,Math.abs(y),Math.abs(E))&&Math.abs(m-T)<=p*Math.max(1,Math.abs(m),Math.abs(T))&&Math.abs(g-B)<=p*Math.max(1,Math.abs(g),Math.abs(B))&&Math.abs(x-V)<=p*Math.max(1,Math.abs(x),Math.abs(V))},t.cA=function(t,e){at.REGISTERED_PROTOCOLS[t]=e;},t.cB=function(t){delete at.REGISTERED_PROTOCOLS[t];},t.cC=function(t,e){const r={};for(let n=0;nt*Qu));}let v=o?"center":n.get("text-justify").evaluate(i,{},e.canonical);const b="point"===n.get("symbol-placement")?n.get("text-max-width").evaluate(i,{},e.canonical)*Qu:1/0,w=()=>{e.bucket.allowVerticalPlacement&&ds(s)&&(d.vertical=Ac(y,e.glyphMap,e.glyphPositions,e.imagePositions,c,b,a,m,"left",f,g,t.ao.vertical,!0,p,h));};if(!o&&x){const r=new Set;if("auto"===v)for(let t=0;t0||(null===(i=r.addOrUpdateProperties)||void 0===i?void 0:i.length)>0);if((r.newGeometry||r.removeAllProperties||o)&&(e=Object.assign({},e),t.set(r.id,e),o&&(e.properties=Object.assign({},e.properties))),r.newGeometry&&(e.geometry=r.newGeometry),r.removeAllProperties)e.properties={};else if((null===(s=r.removeProperties)||void 0===s?void 0:s.length)>0)for(const t of r.removeProperties)Object.prototype.hasOwnProperty.call(e.properties,t)&&delete e.properties[t];if((null===(a=r.addOrUpdateProperties)||void 0===a?void 0:a.length)>0)for(const{key:t,value:n}of r.addOrUpdateProperties)e.properties[t]=n;}},t.cX=Ms,t.ca=function(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[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.cb=t=>"symbol"===t.type,t.cc=t=>"circle"===t.type,t.cd=t=>"heatmap"===t.type,t.ce=t=>"line"===t.type,t.cf=t=>"fill"===t.type,t.cg=t=>"fill-extrusion"===t.type,t.ch=t=>"hillshade"===t.type,t.ci=t=>"color-relief"===t.type,t.cj=t=>"raster"===t.type,t.ck=t=>"background"===t.type,t.cl=t=>"custom"===t.type,t.cm=V,t.cn=function(t,e,r){const n=z(e.x-r.x,e.y-r.y),i=z(t.x-r.x,t.y-r.y);var s,a;return et(Math.atan2(n[0]*i[1]-n[1]*i[0],(s=n)[0]*(a=i)[0]+s[1]*a[1]))},t.co=F,t.cp=function(t,e){return nt[e]&&(t instanceof MouseEvent||t instanceof WheelEvent)},t.cq=function(t,e){return rt[e]&&"touches"in t},t.cr=function(t){return rt[t]||nt[t]},t.cs=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t},t.ct=function(t,e){const{x:r,y:n}=Ah.fromLngLat(e);return !(t<0||t>25||n<0||n>=1||r<0||r>=1)},t.cu=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.cv=class extends Js{},t.cw=Ap,t.cy=function(t){return t.message===it},t.cz=ut,t.d=pt,t.e=L,t.f=t=>e(void 0,void 0,void 0,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),t.g=ot,t.h=t=>new Promise(((e,r)=>{const n=new Image;n.onload=()=>{e(n),URL.revokeObjectURL(n.src),n.onload=null,window.requestAnimationFrame((()=>{n.src=H;}));},n.onerror=()=>r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const i=new Blob([new Uint8Array(t)],{type:"image/png"});n.src=t.byteLength?URL.createObjectURL(i):H;})),t.i=X,t.j=(t,e)=>ht(L(t,{type:"json"}),e),t.k=mt,t.l=yt,t.m=ht,t.n=(t,e)=>ht(L(t,{type:"arrayBuffer"}),e),t.o=function(t){return new nc(t).readFields(yc,[])},t.p=xc,t.q=ol,t.r=js,t.s=Q,t.t=Es,t.u=fs,t.v=xt,t.w=q,t.x=Qi,t.y=ns,t.z=Wi;})); + +define("worker",["./shared"],(function(e){"use strict";class t{constructor(e,t){this.keyCache={},e&&this.replace(e,t);}replace(e,t){this._layerConfigs={},this._layers={},this.update(e,[],t);}update(t,i,o){for(const i of t){this._layerConfigs[i.id]=i;const t=this._layers[i.id]=e.bJ(i,o);t._featureFilter=e.aa(t.filter,o),this.keyCache[i.id]&&delete this.keyCache[i.id];}for(const e of i)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const s=e.cC(Object.values(this._layerConfigs),this.keyCache);for(const e of s){const t=e.map((e=>this._layers[e.id])),i=t[0];if("none"===i.visibility)continue;const o=i.source||"";let s=this.familiesBySource[o];s||(s=this.familiesBySource[o]={});const n=i.sourceLayer||"_geojsonTileLayer";let r=s[n];r||(r=s[n]=[]),r.push(t);}}}class i{constructor(t){const i={},o=[];for(const e in t){const s=t[e],n=i[e]={};for(const e in s){const t=s[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const i={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};o.push(i),n[e]={rect:i,metrics:t.metrics};}}const{w:s,h:n}=e.p(o),r=new e.q({width:s||1,height:n||1});for(const o in t){const s=t[o];for(const t in s){const n=s[+t];if(!n||0===n.bitmap.width||0===n.bitmap.height)continue;const a=i[o][t].rect;e.q.copy(n.bitmap,r,{x:0,y:0},{x:a.x+1,y:a.y+1},n.bitmap);}}this.image=r,this.positions=i;}}e.cD("GlyphAtlas",i);class o{constructor(t){this.tileID=new e.Z(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[];}parse(t,o,n,r,a){return e._(this,void 0,void 0,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.a8;const l=new e.cE(Object.keys(t.layers).sort()),c=new e.cF(this.tileID,this.promoteId);c.bucketLayerIDs=[];const u={},h={featureIndex:c,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:n,subdivisionGranularity:a},d=o.familiesBySource[this.source];for(const i in d){const o=t.layers[i];if(!o)continue;1===o.version&&e.w(`Vector tile source "${this.source}" layer "${i}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const r=l.encode(i),a=[];for(let e=0;e=i.maxzoom||"none"!==i.visibility&&(s(t,this.zoom,n),(u[i.id]=i.createBucket({index:c.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:r,sourceID:this.source})).populate(a,h,this.tileID.canonical),c.bucketLayerIDs.push(t.map((e=>e.id))));}}const f=e.bN(h.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?void 0:e.abort())),this.inFlightDependencies=[];let g=Promise.resolve({});if(Object.keys(f).length){const e=new AbortController;this.inFlightDependencies.push(e),g=r.sendAsync({type:"GG",data:{stacks:f,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const p=Object.keys(h.iconDependencies);let m=Promise.resolve({});if(p.length){const e=new AbortController;this.inFlightDependencies.push(e),m=r.sendAsync({type:"GI",data:{icons:p,source:this.source,tileID:this.tileID,type:"icons"}},e);}const y=Object.keys(h.patternDependencies);let v=Promise.resolve({});if(y.length){const e=new AbortController;this.inFlightDependencies.push(e),v=r.sendAsync({type:"GI",data:{icons:y,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const[w,x,b]=yield Promise.all([g,m,v]),S=new i(w),_=new e.cG(x,b);for(const t in u){const i=u[t];i instanceof e.a9?(s(i.layers,this.zoom,n),e.cH({bucket:i,glyphMap:w,glyphPositions:S.positions,imageMap:x,imagePositions:_.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:h.subdivisionGranularity})):i.hasPattern&&(i instanceof e.cI||i instanceof e.cJ||i instanceof e.cK)&&(s(i.layers,this.zoom,n),i.addFeatures(h,this.tileID.canonical,_.patternPositions));}return this.status="done",{buckets:Object.values(u).filter((e=>!e.isEmpty())),featureIndex:c,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:S.image,imageAtlas:_,glyphMap:this.returnDependencies?w:null,iconMap:this.returnDependencies?x:null,glyphPositions:this.returnDependencies?S.positions:null}}))}}function s(t,i,o){const s=new e.F(i);for(const e of t)e.recalculate(s,o);}class n{constructor(e,t,i){this.actor=e,this.layerIndex=t,this.availableImages=i,this.fetching={},this.loading={},this.loaded={};}loadVectorTile(t,i){return e._(this,void 0,void 0,(function*(){const o=yield e.n(t.request,i);try{return {vectorTile:new e.cL(new e.cM(o.data)),rawData:o.data,cacheControl:o.cacheControl,expires:o.expires}}catch(e){const i=new Uint8Array(o.data);let s=`Unable to parse the tile at ${t.request.url}, `;throw s+=31===i[0]&&139===i[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${e.message}`,new Error(s)}}))}loadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid,s=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.cN(t.request),n=new o(t);this.loading[i]=n;const r=new AbortController;n.abort=r;try{const o=yield this.loadVectorTile(t,r);if(delete this.loading[i],!o)return null;const a=o.rawData,l={};o.expires&&(l.expires=o.expires),o.cacheControl&&(l.cacheControl=o.cacheControl);const c={};if(s){const e=s.finish();e&&(c.resourceTiming=JSON.parse(JSON.stringify(e)));}n.vectorTile=o.vectorTile;const u=n.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);this.loaded[i]=n,this.fetching[i]={rawTileData:a,cacheControl:l,resourceTiming:c};try{const t=yield u;return e.e({rawTileData:a.slice(0)},t,l,c)}finally{delete this.fetching[i];}}catch(e){throw delete this.loading[i],n.status="done",this.loaded[i]=n,e}}))}reloadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid;if(!this.loaded||!this.loaded[i])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const o=this.loaded[i];if(o.showCollisionBoxes=t.showCollisionBoxes,"parsing"===o.status){const s=yield o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);let n;if(this.fetching[i]){const{rawTileData:t,cacheControl:o,resourceTiming:r}=this.fetching[i];delete this.fetching[i],n=e.e({rawTileData:t.slice(0)},s,o,r);}else n=s;return n}if("done"===o.status&&o.vectorTile)return o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity)}))}abortTile(t){return e._(this,void 0,void 0,(function*(){const e=this.loading,i=t.uid;e&&e[i]&&e[i].abort&&(e[i].abort.abort(),delete e[i]);}))}removeTile(t){return e._(this,void 0,void 0,(function*(){this.loaded&&this.loaded[t.uid]&&delete this.loaded[t.uid];}))}}class r{constructor(){this.loaded={};}loadTile(t){return e._(this,void 0,void 0,(function*(){const{uid:i,encoding:o,rawImageData:s,redFactor:n,greenFactor:r,blueFactor:a,baseShift:l}=t,c=s.width+2,u=s.height+2,h=e.b(s)?new e.R({width:c,height:u},yield e.cO(s,-1,-1,c,u)):s,d=new e.cP(i,h,o,n,r,a,l);return this.loaded=this.loaded||{},this.loaded[i]=d,d}))}removeTile(e){const t=this.loaded,i=e.uid;t&&t[i]&&delete t[i];}}var a,l,c=function(){if(l)return a;function e(e,i){if(0!==e.length){t(e[0],i);for(var o=1;o=Math.abs(a)?i-l+a:a-l+i,i=l;}i+o>=0!=!!t&&e.reverse();}return l=1,a=function t(i,o){var s,n=i&&i.type;if("FeatureCollection"===n)for(s=0;s>31}function v(e,t){const i=e.loadGeometry(),o=e.type;let s=0,n=0;for(const r of i){let i=1;1===o&&(i=r.length),t.writeVarint(m(1,i));const a=3===o?r.length-1:r.length;for(let e=0;ee},b=Math.fround||(S=new Float32Array(1),e=>(S[0]=+e,S[0]));var S;class _{constructor(e){this.options=Object.assign(Object.create(x),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:i,maxZoom:o}=this.options;t&&console.time("total time");const s=`prepare ${e.length} points`;t&&console.time(s),this.points=e;const n=[];for(let t=0;t=i;e--){const i=+Date.now();r=this.trees[e]=this._createTree(this._cluster(r,e)),t&&console.log("z%d: %d clusters in %dms",e,r.numItems,+Date.now()-i);}return t&&console.timeEnd("total time"),this}getClusters(e,t){let i=((e[0]+180)%360+360)%360-180;const o=Math.max(-90,Math.min(90,e[1]));let s=180===e[2]?180:((e[2]+180)%360+360)%360-180;const n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)i=-180,s=180;else if(i>s){const e=this.getClusters([i,o,180,n],t),r=this.getClusters([-180,o,s,n],t);return e.concat(r)}const r=this.trees[this._limitZoom(t)],a=r.range(k(i),P(n),k(s),P(o)),l=r.data,c=[];for(const e of a){const t=this.stride*e;c.push(l[t+5]>1?M(l,t,this.clusterProps):this.points[l[t+3]]);}return c}getChildren(e){const t=this._getOriginId(e),i=this._getOriginZoom(e),o="No cluster with the specified id.",s=this.trees[i];if(!s)throw new Error(o);const n=s.data;if(t*this.stride>=n.length)throw new Error(o);const r=this.options.radius/(this.options.extent*Math.pow(2,i-1)),a=s.within(n[t*this.stride],n[t*this.stride+1],r),l=[];for(const t of a){const i=t*this.stride;n[i+4]===e&&l.push(n[i+5]>1?M(n,i,this.clusterProps):this.points[n[i+3]]);}if(0===l.length)throw new Error(o);return l}getLeaves(e,t,i){const o=[];return this._appendLeaves(o,e,t=t||10,i=i||0,0),o}getTile(e,t,i){const o=this.trees[this._limitZoom(e)],s=Math.pow(2,e),{extent:n,radius:r}=this.options,a=r/n,l=(i-a)/s,c=(i+1+a)/s,u={features:[]};return this._addTileFeatures(o.range((t-a)/s,l,(t+1+a)/s,c),o.data,t,i,s,u),0===t&&this._addTileFeatures(o.range(1-a/s,l,1,c),o.data,s,i,s,u),t===s-1&&this._addTileFeatures(o.range(0,l,a/s,c),o.data,-1,i,s,u),u.features.length?u:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const i=this.getChildren(e);if(t++,1!==i.length)break;e=i[0].properties.cluster_id;}return t}_appendLeaves(e,t,i,o,s){const n=this.getChildren(t);for(const t of n){const n=t.properties;if(n&&n.cluster?s+n.point_count<=o?s+=n.point_count:s=this._appendLeaves(e,n.cluster_id,i,o,s):s1;let l,c,u;if(a)l=I(t,e,this.clusterProps),c=t[e],u=t[e+1];else {const i=this.points[t[e+3]];l=i.properties;const[o,s]=i.geometry.coordinates;c=k(o),u=P(s);}const h={type:1,geometry:[[Math.round(this.options.extent*(c*s-i)),Math.round(this.options.extent*(u*s-o))]],tags:l};let d;d=a||this.options.generateId?t[e+3]:this.points[t[e+3]].id,void 0!==d&&(h.id=d),n.features.push(h);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:i,extent:o,reduce:s,minPoints:n}=this.options,r=i/(o*Math.pow(2,t)),a=e.data,l=[],c=this.stride;for(let i=0;it&&(f+=a[i+5]);}if(f>d&&f>=n){let e,n=o*d,r=u*d,g=-1;const p=(i/c<<5)+(t+1)+this.points.length;for(const o of h){const l=o*c;if(a[l+2]<=t)continue;a[l+2]=t;const u=a[l+5];n+=a[l]*u,r+=a[l+1]*u,a[l+4]=p,s&&(e||(e=this._map(a,i,!0),g=this.clusterProps.length,this.clusterProps.push(e)),s(e,this._map(a,l)));}a[i+4]=p,l.push(n/f,r/f,1/0,p,-1,f),s&&l.push(g);}else {for(let e=0;e1)for(const e of h){const i=e*c;if(!(a[i+2]<=t)){a[i+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,i){if(e[t+5]>1){const o=this.clusterProps[e[t+6]];return i?Object.assign({},o):o}const o=this.points[e[t+3]].properties,s=this.options.map(o);return i&&s===o?Object.assign({},s):s}}function M(e,t,i){return {type:"Feature",id:e[t+3],properties:I(e,t,i),geometry:{type:"Point",coordinates:[(o=e[t],360*(o-.5)),T(e[t+1])]}};var o;}function I(e,t,i){const o=e[t+5],s=o>=1e4?`${Math.round(o/1e3)}k`:o>=1e3?Math.round(o/100)/10+"k":o,n=e[t+6],r=-1===n?{}:Object.assign({},i[n]);return Object.assign(r,{cluster:!0,cluster_id:e[t+3],point_count:o,point_count_abbreviated:s})}function k(e){return e/360+.5}function P(e){const t=Math.sin(e*Math.PI/180),i=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return i<0?0:i>1?1:i}function T(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function D(e,t,i,o){let s=o;const n=t+(i-t>>1);let r,a=i-t;const l=e[t],c=e[t+1],u=e[i],h=e[i+1];for(let o=t+3;os)r=o,s=t;else if(t===s){const e=Math.abs(o-n);eo&&(r-t>3&&D(e,t,r,o),e[r+2]=s,i-r>3&&D(e,r,i,o));}function C(e,t,i,o,s,n){let r=s-i,a=n-o;if(0!==r||0!==a){const l=((e-i)*r+(t-o)*a)/(r*r+a*a);l>1?(i=s,o=n):l>0&&(i+=r*l,o+=a*l);}return r=e-i,a=t-o,r*r+a*a}function L(e,t,i,o){const s={id:null==e?null:e,type:t,geometry:i,tags:o,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===t||"MultiPoint"===t||"LineString"===t)O(s,i);else if("Polygon"===t)O(s,i[0]);else if("MultiLineString"===t)for(const e of i)O(s,e);else if("MultiPolygon"===t)for(const e of i)O(s,e[0]);return s}function O(e,t){for(let i=0;i0&&(r+=o?(s*l-a*n)/2:Math.sqrt(Math.pow(a-s,2)+Math.pow(l-n,2))),s=a,n=l;}const a=t.length-3;t[2]=1,D(t,0,a,i),t[a+2]=1,t.size=Math.abs(r),t.start=0,t.end=t.size;}function G(e,t,i,o){for(let s=0;s1?1:i}function j(e,t,i,o,s,n,r,a){if(o/=t,n>=(i/=t)&&r=o)return null;const l=[];for(const t of e){const e=t.geometry;let n=t.type;const r=0===s?t.minX:t.minY,c=0===s?t.maxX:t.maxY;if(r>=i&&c=o)continue;let u=[];if("Point"===n||"MultiPoint"===n)N(e,u,i,o,s);else if("LineString"===n)R(e,u,i,o,s,!1,a.lineMetrics);else if("MultiLineString"===n)J(e,u,i,o,s,!1);else if("Polygon"===n)J(e,u,i,o,s,!0);else if("MultiPolygon"===n)for(const t of e){const e=[];J(t,e,i,o,s,!0),e.length&&u.push(e);}if(u.length){if(a.lineMetrics&&"LineString"===n){for(const e of u)l.push(L(t.id,n,e,t.tags));continue}"LineString"!==n&&"MultiLineString"!==n||(1===u.length?(n="LineString",u=u[0]):n="MultiLineString"),"Point"!==n&&"MultiPoint"!==n||(n=3===u.length?"Point":"MultiPoint"),l.push(L(t.id,n,u,t.tags));}}return l.length?l:null}function N(e,t,i,o,s){for(let n=0;n=i&&r<=o&&Y(t,e[n],e[n+1],e[n+2]);}}function R(e,t,i,o,s,n,r){let a=W(e);const l=0===s?q:X;let c,u,h=e.start;for(let d=0;di&&(u=l(a,f,g,m,y,i),r&&(a.start=h+c*u)):v>o?w=i&&(u=l(a,f,g,m,y,i),x=!0),w>o&&v<=o&&(u=l(a,f,g,m,y,o),x=!0),!n&&x&&(r&&(a.end=h+c*u),t.push(a),a=W(e)),r&&(h+=c);}let d=e.length-3;const f=e[d],g=e[d+1],p=0===s?f:g;p>=i&&p<=o&&Y(a,f,g,e[d+2]),d=a.length-3,n&&d>=3&&(a[d]!==a[0]||a[d+1]!==a[1])&&Y(a,a[0],a[1],a[2]),a.length&&t.push(a);}function W(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function J(e,t,i,o,s,n){for(const r of e)R(r,t,i,o,s,n,!1);}function Y(e,t,i,o){e.push(t,i,o);}function q(e,t,i,o,s,n){const r=(n-t)/(o-t);return Y(e,n,i+(s-i)*r,1),r}function X(e,t,i,o,s,n){const r=(n-i)/(s-i);return Y(e,t+(o-t)*r,n,1),r}function H(e,t){const i=[];for(let o=0;o0&&t.size<(s?r:o))return void(i.numPoints+=t.length/3);const a=[];for(let e=0;er)&&(i.numSimplified++,a.push(t[e],t[e+1])),i.numPoints++;s&&function(e,t){let i=0;for(let t=0,o=e.length,s=o-2;t0===t)for(let t=0,i=e.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");let o=function(e,t){const i=[];if("FeatureCollection"===e.type)for(let o=0;o1&&console.time("creation"),d=this.tiles[h]=U(e,t,i,o,l),this.tileCoords.push({z:t,x:i,y:o}),c)){c>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,i,o,d.numFeatures,d.numPoints,d.numSimplified),console.timeEnd("creation"));const e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++;}if(d.source=e,null==s){if(t===l.indexMaxZoom||d.numPoints<=l.indexMaxPoints)continue}else {if(t===l.maxZoom||t===s)continue;if(null!=s){const e=s-t;if(i!==n>>e||o!==r>>e)continue}}if(d.source=null,0===e.length)continue;c>1&&console.time("clipping");const f=.5*l.buffer/l.extent,g=.5-f,p=.5+f,m=1+f;let y=null,v=null,w=null,x=null,b=j(e,u,i-f,i+p,0,d.minX,d.maxX,l),S=j(e,u,i+g,i+m,0,d.minX,d.maxX,l);e=null,b&&(y=j(b,u,o-f,o+p,1,d.minY,d.maxY,l),v=j(b,u,o+g,o+m,1,d.minY,d.maxY,l),b=null),S&&(w=j(S,u,o-f,o+p,1,d.minY,d.maxY,l),x=j(S,u,o+g,o+m,1,d.minY,d.maxY,l),S=null),c>1&&console.timeEnd("clipping"),a.push(y||[],t+1,2*i,2*o),a.push(v||[],t+1,2*i,2*o+1),a.push(w||[],t+1,2*i+1,2*o),a.push(x||[],t+1,2*i+1,2*o+1);}}getTile(e,t,i){e=+e,t=+t,i=+i;const o=this.options,{extent:s,debug:n}=o;if(e<0||e>24)return null;const r=1<1&&console.log("drilling down to z%d-%d-%d",e,t,i);let l,c=e,u=t,h=i;for(;!l&&c>0;)c--,u>>=1,h>>=1,l=this.tiles[ie(c,u,h)];return l&&l.source?(n>1&&(console.log("found parent tile z%d-%d-%d",c,u,h),console.time("drilling down")),this.splitTile(l.source,c,u,h,e,t,i),n>1&&console.timeEnd("drilling down"),this.tiles[a]?B(this.tiles[a],s):null):null}}function ie(e,t,i){return 32*((1<{r.properties=e;const t={};for(const e of a)t[e]=o[e].evaluate(n,r);return t},t.reduce=(e,t)=>{r.properties=t;for(const t of a)n.accumulated=e[t],e[t]=s[t].evaluate(n,r);},t}(t)).load(i.features):function(e,t){return new te(e,t)}(i,t.geojsonVtOptions),this.loaded={};const s={data:i};if(o){const e=o.finish();e&&(s.resourceTiming={},s.resourceTiming[t.source]=JSON.parse(JSON.stringify(e)));}return s}catch(t){if(delete this._pendingRequest,e.cy(t))return {abandoned:!0};throw t}}))}getData(){return e._(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(e){const t=this.loaded;return t&&t[e.uid]?super.reloadTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){let o=yield this.loadGeoJSON(t,i);if(delete this._pendingRequest,"object"!=typeof o)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(u(o,!0),t.filter){const i=e.cT(t.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===i.result)throw new Error(i.value.map((e=>`${e.key}: ${e.message}`)).join(", "));const s=o.features.filter((e=>i.value.evaluate({zoom:0},e)));o={type:"FeatureCollection",features:s};}return o}))}loadGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){const{promoteId:o}=t;if(t.request){const s=yield e.j(t.request,i);return this._dataUpdateable=e.cV(s.data,o)?e.cU(s.data,o):void 0,s.data}if("string"==typeof t.data)try{const i=JSON.parse(t.data);return this._dataUpdateable=e.cV(i,o)?e.cU(i,o):void 0,i}catch(e){throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}if(!t.dataDiff)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${t.source}`);return e.cW(this._dataUpdateable,t.dataDiff,o),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(t){return e._(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset)}}class se{constructor(t){this.self=t,this.actor=new e.J(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=new Map,this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.cA,this.self.removeProtocol=e.cB,this.self.registerRTLTextPlugin=t=>{e.cX.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,i)=>e._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(t,i.source).removeTile(i);})))),this.actor.registerMessageHandler("GCEZ",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterExpansionZoom(i)})))),this.actor.registerMessageHandler("GCC",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterChildren(i)})))),this.actor.registerMessageHandler("GCL",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterLeaves(i)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("GD",((e,t)=>this._getWorkerSource(e,t.type,t.source).getData())),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,i)=>e._(this,void 0,void 0,(function*(){if(!this.workerSources[t]||!this.workerSources[t][i.type]||!this.workerSources[t][i.type][i.source])return;const e=this.workerSources[t][i.type][i.source];delete this.workerSources[t][i.type][i.source],void 0!==e.removeSource&&e.removeSource(i);})))),this.actor.registerMessageHandler("RM",(t=>e._(this,void 0,void 0,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t],this.globalStates.delete(t);})))),this.actor.registerMessageHandler("SR",((t,i)=>e._(this,void 0,void 0,(function*(){this.referrer=i;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,i)=>e._(this,void 0,void 0,(function*(){this.self.importScripts(i);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).update(i.layers,i.removedIds,this._getGlobalState(t));})))),this.actor.registerMessageHandler("UGS",((t,i)=>e._(this,void 0,void 0,(function*(){const e=this._getGlobalState(t);for(const t in i)e[t]=i[t];})))),this.actor.registerMessageHandler("SL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).replace(i,this._getGlobalState(t));}))));}_getGlobalState(e){let t=this.globalStates.get(e);return t||(t={},this.globalStates.set(e,t)),t}_setImages(t,i){return e._(this,void 0,void 0,(function*(){this.availableImages[t]=i;for(const e in this.workerSources[t]){const o=this.workerSources[t][e];for(const e in o)o[e].availableImages=i;}}))}_syncRTLPluginState(t,i){return e._(this,void 0,void 0,(function*(){return yield e.cX.syncState(i,this.self.importScripts)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(e){let i=this.layerIndexes[e];return i||(i=this.layerIndexes[e]=new t),i}_getWorkerSource(e,t,i){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][i]){const o={sendAsync:(t,i)=>(t.targetMapId=e,this.actor.sendAsync(t,i))};switch(t){case "vector":this.workerSources[e][t][i]=new n(o,this._getLayerIndex(e),this._getAvailableImages(e));break;case "geojson":this.workerSources[e][t][i]=new oe(o,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][i]=new this.externalWorkerSourceTypes[t](o,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][t][i]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new r),this.demWorkerSources[e][t]}}return e.i(self)&&(self.worker=new se(self)),se})); + +define("index",["exports","./shared"],(function(e,t){"use strict";var i="5.7.2";function o(){var e=new t.A(4);return t.A!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}let r,a;const s={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frame(e,i,o){const r=requestAnimationFrame((e=>{a(),i(e);})),{unsubscribe:a}=t.s(e.signal,"abort",(()=>{a(),cancelAnimationFrame(r),o(t.c());}),!1);},frameAsync(e){return new Promise(((t,i)=>{this.frame(e,t,i);}))},getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(r||(r=document.createElement("a")),r.href=e,r.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==a&&(a=matchMedia("(prefers-reduced-motion: reduce)")),a.matches)}};class n{static testProp(e){if(!n.docStyle)return e[0];for(let t=0;t{window.removeEventListener("click",n.suppressClickInternal,!0);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,o){const r=i.boundingClientRect;return new t.P((o.clientX-r.left)/i.x-e.clientLeft,(o.clientY-r.top)/i.y-e.clientTop)}static mousePos(e,t){const i=n.getScale(e);return n.getPoint(e,i,t)}static touchPos(e,t){const i=[],o=n.getScale(e);for(let r=0;r{c&&_(c),c=null,d=!0;},h.onerror=()=>{u=!0,c=null;},h.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(e){let i,o,r,a;e.resetRequestQueue=()=>{i=[],o=0,r=0,a={};},e.addThrottleControl=e=>{const t=r++;return a[t]=e,t},e.removeThrottleControl=e=>{delete a[e],n();},e.getImage=(e,o,r=!0)=>new Promise(((a,s)=>{l.supported&&(e.headers||(e.headers={}),e.headers.accept="image/webp,*/*"),t.e(e,{type:"image"}),i.push({abortController:o,requestParameters:e,supportImageRefresh:r,state:"queued",onError:e=>{s(e);},onSuccess:e=>{a(e);}}),n();}));const s=e=>t._(this,void 0,void 0,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:r,onError:a,onSuccess:s,abortController:l}=e,h=!1===r&&!t.i(self)&&!t.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),!0));o++;const u=h?c(i,l):t.m(i,l);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.b(i.data)?s(i):i.data&&s({data:yield(d=i.data,"function"==typeof createImageBitmap?t.f(d):t.h(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,a(t);}finally{o--,n();}var d;})),n=()=>{const e=(()=>{for(const e of Object.keys(a))if(a[e]())return !0;return !1})()?t.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=o;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:s(e);}},c=(e,i)=>new Promise(((o,r)=>{const a=new Image,s=e.url,n=e.credentials;n&&"include"===n?a.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.d(s))&&(a.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{a.src="",r(t.c());})),a.fetchPriority="high",a.onload=()=>{a.onerror=a.onload=null,o({data:a});},a.onerror=()=>{a.onerror=a.onload=null,i.signal.aborted||r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));},a.src=s;}));}(p||(p={})),p.resetRequestQueue();class m{constructor(e){this._transformRequestFn=null!=e?e:null;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}function f(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:o,url:r}of e){const e=`${o}${r}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:o,url:r}));}}return t}function g(e,t,i){try{const o=new URL(e);return o.pathname+=`${t}${i}`,o.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}function v(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class b extends t.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.R({width:1,height:1}),this.dirty=!0;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.R({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let o=!0;const r=i.data||i.spriteData;return this._validateStretch(i.stretchX,r&&r.width)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchX" value`))),o=!1),this._validateStretch(i.stretchY,r&&r.height)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchY" value`))),o=!1),this._validateContent(i.content,i)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "content" value`))),o=!1),o}_validateStretch(e,t){if(!e)return !0;let i=0;for(const o of e){if(o[0]{let o=!0;if(!this.isLoaded())for(const t of e)this.images[t]||(o=!1);this.isLoaded()||o?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const o of e){let e=this.getImage(o);e||(this.fire(new t.l("styleimagemissing",{id:o})),e=this.getImage(o)),e?i[o]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.w(`Image "${o}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);}return i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],o=this.getImage(e);if(!o)return null;if(i&&i.position.version===o.version)return i.position;if(i)i.position.version=o.version;else {const i={w:o.data.width+2,h:o.data.height+2,x:0,y:0},r=new t.I(i,o);this.patterns[e]={bin:i,position:r};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const i=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new t.T(e,this.atlasImage,i.RGBA),this.atlasTexture.bind(i.LINEAR,i.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:o}=t.p(e),r=this.atlasImage;r.resize({width:i||1,height:o||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],o=i.x+1,a=i.y+1,s=this.getImage(e).data,n=s.width,l=s.height;t.R.copy(s,r,{x:0,y:0},{x:o,y:a},{width:n,height:l}),t.R.copy(s,r,{x:0,y:l-1},{x:o,y:a-1},{width:n,height:1}),t.R.copy(s,r,{x:0,y:0},{x:o,y:a+l},{width:n,height:1}),t.R.copy(s,r,{x:n-1,y:0},{x:o-1,y:a},{width:1,height:l}),t.R.copy(s,r,{x:0,y:0},{x:o+n,y:a},{width:1,height:l});}this.dirty=!0;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=!0;const e=this.getImage(i);e||t.w(`Image with ID: "${i}" was not found`),v(e)&&this.updateImage(i,e);}}}const x=1e20;function y(e,t,i,o,r,a,s,n,l){for(let c=t;c-1);l++,a[l]=n,s[l]=c,s[l+1]=x;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(t.ranges[r])return {stack:e,id:i,glyph:o};if(!this.url)throw new Error("glyphsUrl is not set");if(!t.requests[r]){const i=T.loadGlyphRange(e,r,this.url,this.requestManager);t.requests[r]=i;}const a=yield t.requests[r];for(const e in a)this._doesCharSupportLocalGlyph(+e)||(t.glyphs[+e]=a[+e]);return t.ranges[r]=!0,{stack:e,id:i,glyph:a[i]||null}}))}_doesCharSupportLocalGlyph(e){return !!this.localIdeographFontFamily&&(/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(e))||t.u["CJK Unified Ideographs"](e)||t.u["Hangul Syllables"](e)||t.u.Hiragana(e)||t.u.Katakana(e)||t.u["CJK Symbols and Punctuation"](e)||t.u["Halfwidth and Fullwidth Forms"](e))}_tinySDF(e,i,o){const r=this.localIdeographFontFamily;if(!r)return;if(!this._doesCharSupportLocalGlyph(o))return;let a=e.tinySDF;if(!a){let t="400";/bold/i.test(i)?t="900":/medium/i.test(i)?t="500":/light/i.test(i)&&(t="200"),a=e.tinySDF=new T.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,lang:this.lang,fontFamily:r,fontWeight:t});}const s=a.draw(String.fromCharCode(o));return {id:o,bitmap:new t.q({width:s.width||60,height:s.height||60},s.data),metrics:{width:s.glyphWidth/2||24,height:s.glyphHeight/2||24,left:s.glyphLeft/2+.5||0,top:s.glyphTop/2-27.5||-8,advance:s.glyphAdvance/2||24,isDoubleResolution:!0}}}}T.loadGlyphRange=function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=256*i,s=a+255,n=r.transformRequest(o.replace("{fontstack}",e).replace("{range}",`${a}-${s}`),"Glyphs"),l=yield t.n(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${a}-${s}`);const c={};for(const e of t.o(l.data))c[e.id]=e;return c}))},T.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:o=.25,fontFamily:r="sans-serif",fontWeight:a="normal",fontStyle:s="normal",lang:n=null}={}){this.buffer=t,this.cutoff=o,this.radius=i,this.lang=n;const l=this.size=e+4*t,c=this._createCanvas(l),h=this.ctx=c.getContext("2d",{willReadFrequently:!0});h.font=`${s} ${a} ${e}px ${r}`,h.textBaseline="alphabetic",h.textAlign="left",h.fillStyle="black",this.gridOuter=new Float64Array(l*l),this.gridInner=new Float64Array(l*l),this.f=new Float64Array(l),this.z=new Float64Array(l+1),this.v=new Uint16Array(l);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:o,actualBoundingBoxLeft:r,actualBoundingBoxRight:a}=this.ctx.measureText(e),s=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(a-r))),l=Math.min(this.size-this.buffer,s+Math.ceil(o)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:s,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;this.lang&&(p.lang=this.lang),p.clearRect(m,m,n,l),p.fillText(e,m,m+s);const v=p.getImageData(m,m,n,l);g.fill(x,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[o]=e<0?e*e:0;}}y(g,0,0,c,h,c,this.f,this.v,this.z),y(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(s=e[++a]);const l=Math.abs(n-s.left),c=Math.abs(n-s.right),h=Math.min(l,c);let u;const d=t/i*(o+1);if(s.isDash){const e=o-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=o-Math.sqrt(h*h+d*d);this.data[r+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],o=e[t+1];i.zeroLength?e.splice(t,1):o&&o.isDash===i.isDash&&(o.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const o=this.width*this.nextRow;let r=0,a=e[r];for(let t=0;t1&&(a=e[++r]);const i=Math.abs(t-a.left),s=Math.abs(t-a.right),n=Math.min(i,s);this.data[o+t]=Math.max(0,Math.min(255,(a.isDash?n:-n)+128));}}addDash(e,i){const o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.w("LineAtlas out of space"),null;let a=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[R]}numActive(){return Object.keys(this.active).length}}const D=Math.floor(s.hardwareConcurrency/2);let A,L;function k(){return A||(A=new z),A}z.workerCount=t.H(globalThis)?Math.max(Math.min(D,3),1):1;class F{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const o=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}}function B(){return L||(L=new F(k(),t.K),L.registerMessageHandler("GR",((e,i,o)=>t.m(i,o)))),L}function O(e,i){const o=t.L();return t.M(o,o,[1,1,0]),t.N(o,o,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.O(o,o,e.calculatePosMatrix(i.toUnwrapped())):o}function j(e,t,i,o,r,a,s){var n;const l=function(e,t,i){if(e)for(const o of e){const e=t[o];if(e&&e.source===i&&"fill-extrusion"===e.type)return !0}else for(const e in t){const o=t[e];if(o.source===i&&"fill-extrusion"===o.type)return !0}return !1}(null!==(n=null==r?void 0:r.layers)&&void 0!==n?n:null,t,e.id),c=a.maxPitchScaleFactor(),h=e.tilesIn(o,c,l);h.sort(N);const u=[];for(const o of h)u.push({wrappedTileID:o.tileID.wrapped().key,queryResults:o.tile.queryRenderedFeatures(t,i,e._state,o.queryGeometry,o.cameraQueryGeometry,o.scale,r,a,c,O(e.transform,o.tileID),s?(e,t)=>s(o.tileID,e,t):void 0)});return function(e,t){for(const i in e)for(const o of e[i])U(o,t);return e}(function(e){const t={},i={};for(const o of e){const e=o.queryResults,r=o.wrappedTileID,a=i[r]=i[r]||{};for(const i in e){const o=e[i],r=a[i]=a[i]||{},s=t[i]=t[i]||[];for(const e of o)r[e.featureIndex]||(r[e.featureIndex]=!0,s.push(e));}}return t}(u),e)}function N(e,t){const i=e.tileID,o=t.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}function U(e,t){const i=e.feature,o=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=o;}function Z(e,i,o){return t._(this,void 0,void 0,(function*(){let r=e;if(e.url?r=(yield t.j(i.transformRequest(e.url,"Source"),o)).data:yield s.frameAsync(o),!r)return null;const a=t.Q(t.e(r,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in r&&r.vector_layers&&(a.vectorLayerIds=r.vector_layers.map((e=>e.id))),a}))}class G{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}extend(e){const i=this._sw,o=this._ne;let r,a;if(e instanceof t.S)r=e,a=e;else {if(!(e instanceof G))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(G.convert(e)):this.extend(t.S.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.S.convert(e)):this;if(r=e._sw,a=e._ne,!r||!a)return this}return i||o?(i.lng=Math.min(r.lng,i.lng),i.lat=Math.min(r.lat,i.lat),o.lng=Math.max(a.lng,o.lng),o.lat=Math.max(a.lat,o.lat)):(this._sw=new t.S(r.lng,r.lat),this._ne=new t.S(a.lng,a.lat)),this}getCenter(){return new t.S((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new t.S(this.getWest(),this.getNorth())}getSouthEast(){return new t.S(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(e){const{lng:i,lat:o}=t.S.convert(e);let r=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(r=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=o&&o<=this._ne.lat&&r}static convert(e){return e instanceof G?e:e?new G(e):e}static fromLngLat(e,i=0){const o=360*i/40075017,r=o/Math.cos(Math.PI/180*e.lat);return new G(new t.S(e.lng-r,e.lat-o),new t.S(e.lng+r,e.lat+o))}adjustAntiMeridian(){const e=new t.S(this._sw.lng,this._sw.lat),i=new t.S(this._ne.lng,this._ne.lat);return new G(e,e.lng>i.lng?new t.S(i.lng+360,i.lat):i)}}class V{constructor(e,t,i){this.bounds=G.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),o=Math.floor(t.V(this.bounds.getWest())*i),r=Math.floor(t.U(this.bounds.getNorth())*i),a=Math.ceil(t.V(this.bounds.getEast())*i),s=Math.ceil(t.U(this.bounds.getSouth())*i);return e.x>=o&&e.x=r&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.e({},this._options)}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};i.request.collectResourceTiming=this._collectResourceTiming;let o="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),o="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:o,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_afterTileLoadWorkerResponse(e,t){if(t&&t.resourceTiming&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return !1}}class q extends t.E{constructor(e,i,o,r){super(),this.id=e,this.dispatcher=o,this.setEventedParent(r),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.e({type:"raster"},i),t.e(this,t.Q(i,["url","scheme","tileSize"]));}load(){return t._(this,arguments,void 0,(function*(e=!1){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield Z(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,i&&(t.e(this,i),i.bounds&&(this.tileBounds=new V(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.l("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(!0);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.e({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const o=yield p.getImage(this.map._requestManager.transformRequest(i,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(o&&o.data){this.map._refreshExpiredTiles&&(o.cacheControl||o.expires)&&e.setExpiryData({cacheControl:o.cacheControl,expires:o.expires});const i=this.map.painter.context,r=i.gl,a=o.data;e.texture=this.map.painter.getTileTexture(a.width),e.texture?e.texture.update(a,{useMipmap:!0}):(e.texture=new t.T(i,a,r.RGBA,{useMipmap:!0}),e.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return !1}}class W extends q{constructor(e,i,o,r){super(e,i,o,r),this.type="raster-dem",this.maxzoom=22,this._options=t.e({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),o=this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield p.getImage(o,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const o=i.data;this.map._refreshExpiredTiles&&(i.cacheControl||i.expires)&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const r=t.b(o)&&t.W()?o:yield this.readImageNow(o),a={type:this.type,uid:e.uid,source:this.id,rawImageData:r,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!e.actor||"expired"===e.state){e.actor=this.dispatcher.getActor();const t=yield e.actor.sendAsync({type:"LDT",data:a});e.dem=t,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t._(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&t.X()){const i=e.width+2,o=e.height+2;try{return new t.R({width:i,height:o},yield t.Y(e,-1,-1,i,o))}catch(e){}}return s.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,o=Math.pow(2,i.z),r=(i.x-1+o)%o,a=0===i.x?e.wrap-1:e.wrap,s=(i.x+1+o)%o,n=i.x+1===o?e.wrap+1:e.wrap,l={};return l[new t.Z(e.overscaledZ,a,i.z,r,i.y).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y).key]={backfilled:!1},i.y>0&&(l[new t.Z(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y-1).key]={backfilled:!1}),i.y+1e.coordinates)).flat(1/0):e.coordinates.flat(1/0)}getBounds(){return t._(this,void 0,void 0,(function*(){const e=new G,t=yield this.getData();let i;switch(t.type){case "FeatureCollection":i=t.features.map((e=>this.getCoordinatesFromGeometry(e.geometry))).flat(1/0);break;case "Feature":i=this.getCoordinatesFromGeometry(t.geometry);break;default:i=this.getCoordinatesFromGeometry(t);}if(0==i.length)return e;for(let t=0;t0&&t.e(r,{resourceTiming:i}),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"metadata"}))),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"content"})));}catch(e){if(this._isUpdatingWorker=!1,this._removed)return void this.fire(new t.l("dataabort",{dataType:"source"}));this.fire(new t.k(e));}finally{(this._pendingWorkerUpdate.data||this._pendingWorkerUpdate.diff)&&this._updateWorkerData();}}))}loaded(){return !this._isUpdatingWorker&&void 0===this._pendingWorkerUpdate.data&&void 0===this._pendingWorkerUpdate.diff}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};e.abortController=new AbortController;const o=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(o,this.map.painter,"RT"===t);}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=!0;}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return !1}}class X extends t.E{constructor(e,t,i,o){super(),this.flippedWindingOrder=!1,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(o),this.options=t;}load(e){return t._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield p.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.a1.fromLngLat);var o;return this.tileID=function(e){const i=t.a2.fromPoints(e),o=i.width(),r=i.height(),a=Math.max(o,r),s=Math.max(0,Math.floor(-Math.log(a)/Math.LN2)),n=Math.pow(2,s);return new t.a4(s,Math.floor((i.minX+i.maxX)/2*n),Math.floor((i.minY+i.maxY)/2*n))}(i),this.terrainTileRanges=this._getOverlappingTileRanges(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((o=this.tileCoords)[1].x-o[0].x)*(o[2].y-o[0].y)-(o[1].y-o[0].y)*(o[2].x-o[0].x)<0,this.fire(new t.l("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new t.T(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t._(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return !1}_getOverlappingTileRanges(e){const{minX:i,minY:o,maxX:r,maxY:a}=t.a2.fromPoints(e),s={};for(let e=0;e<=t.a3;e++){const t=Math.pow(2,e),n=Math.floor(i*t),l=Math.floor(o*t),c=Math.floor(r*t),h=Math.floor(a*t);s[e]={minTileX:n,minTileY:l,maxTileX:c,maxTileY:h};}return s}}class K extends X{constructor(e,t,i,o){super(e,t,i,o),this.roundZoom=!0,this.type="video",this.options=t;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!1;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,"Source").url);try{const e=yield t.a5(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.k(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.k(new t.a6(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.T(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class Y extends X{constructor(e,i,o,r){super(e,i,o,r),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.k(new t.a6(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.k(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,o=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.T(i,this.canvas,o.RGBA,{premultiply:!0});let r=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=!0);}r&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return !0;return !1}}const Q={},J=e=>{switch(e){case "geojson":return H;case "image":return X;case "raster":return q;case "raster-dem":return W;case "vector":return $;case "video":return K;case "canvas":return Y}return Q[e]},ee="RTLPluginLoaded";class te extends t.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=B();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t._(this,arguments,void 0,(function*(e,t=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=s.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.l(ee));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let ie=null;function oe(){return ie||(ie=new te),ie}class re{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=e,this.uid=t.a7(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(e){const t=e+this.timeAdded;tt.getLayer(e))).filter(Boolean);if(0!==e.length){o.layers=e,o.stateDependentLayerIds&&(o.stateDependentLayers=o.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=o;}}return i}(e.buckets,null==i?void 0:i.style),this.hasSymbolBuckets=!1;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9){if(this.hasSymbolBuckets=!0,!o)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9&&i.hasRTLText){this.hasRTLText=!0,oe().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.a8;}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const i=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new t.T(e,this.imageAtlas.image,i.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new t.T(e,this.glyphAtlasImage,i.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,o,r,a,s,n,l,c,h){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:o,cameraQueryGeometry:r,scale:a,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:s,queryPadding:this.queryPadding*l,getElevation:h},e,t,i):{}}querySourceFeatures(e,i){const o=this.latestFeatureIndex;if(!o||!o.rawTileData)return;const r=o.loadVTLayers(),a=i&&i.sourceLayer?i.sourceLayer:"",s=r._geojsonTileLayer||r[a];if(!s)return;const n=t.aa(null==i?void 0:i.filter,null==i?void 0:i.globalState),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=!1;else if(i)if(this.expirationTime{this.remove(e,r);}),i)),this.data[o].push(r),this.order.push(o),this.order.length>this.max){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}has(e){return e.wrapped().key in this.data}getAndRemove(e){return this.has(e)?this._getAndRemoveByKey(e.wrapped().key):null}_getAndRemoveByKey(e){const t=this.data[e].shift();return t.timeout&&clearTimeout(t.timeout),0===this.data[e].length&&delete this.data[e],this.order.splice(this.order.indexOf(e),1),t.value}getByKey(e){const t=this.data[e];return t?t[0].value:null}get(e){return this.has(e)?this.data[e.wrapped().key][0].value:null}remove(e,t){if(!this.has(e))return this;const i=e.wrapped().key,o=void 0===t?0:this.data[i].indexOf(t),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(e){for(this.max=e;this.order.length>this.max;){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}filter(e){const t=[];for(const i in this.data)for(const o of this.data[i])e(o.value)||t.push(o);for(const e of t)this.remove(e.value.tileID,e);}}class se{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(e,i,o){const r=String(i);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][r]=this.stateChanges[e][r]||{},t.e(this.stateChanges[e][r],o),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==r&&(this.deletedStates[e][t]=null);}else if(this.deletedStates[e]&&null===this.deletedStates[e][r]){this.deletedStates[e][r]={};for(const t in this.state[e][r])o[t]||(this.deletedStates[e][r][t]=null);}else for(const t in o)this.deletedStates[e]&&this.deletedStates[e][r]&&null===this.deletedStates[e][r][t]&&delete this.deletedStates[e][r][t];}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const o=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&void 0!==t)null!==this.deletedStates[e][o]&&(this.deletedStates[e][o]=this.deletedStates[e][o]||{},this.deletedStates[e][o][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][o])for(i in this.deletedStates[e][o]={},this.stateChanges[e][o])this.deletedStates[e][o][i]=null;else this.deletedStates[e][o]=null;else this.deletedStates[e]=null;}getState(e,i){const o=String(i),r=t.e({},(this.state[e]||{})[o],(this.stateChanges[e]||{})[o]);if(null===this.deletedStates[e])return {};if(this.deletedStates[e]){const t=this.deletedStates[e][i];if(null===t)return {};for(const e in t)delete r[e];}return r}initializeTileState(e,t){e.setFeatureState(this.state,t);}coalesceChanges(e,i){const o={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const i={};for(const o in this.stateChanges[e])this.state[e][o]||(this.state[e][o]={}),t.e(this.state[e][o],this.stateChanges[e][o]),i[o]=this.state[e][o];o[e]=i;}for(const e in this.deletedStates){this.state[e]=this.state[e]||{};const i={};if(null===this.deletedStates[e])for(const t in this.state[e])i[t]={},this.state[e][t]={};else for(const t in this.deletedStates[e]){if(null===this.deletedStates[e][t])this.state[e][t]={};else for(const i of Object.keys(this.deletedStates[e][t]))delete this.state[e][t][i];i[t]=this.state[e][t];}o[e]=o[e]||{},t.e(o[e],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(o).length)for(const t in e)e[t].setFeatureState(o,i);}}const ne=89.25;function le(e,i){const o=t.ah(i.lat,-t.ai,t.ai);return new t.P(t.V(i.lng)*e,t.U(o)*e)}function ce(e,i){return new t.a1(i.x/e,i.y/e).toLngLat()}function he(e){return e.cameraToCenterDistance*Math.min(.85*Math.tan(t.ae(90-e.pitch)),Math.tan(t.ae(ne-e.pitch)))}function ue(e,i){const o=e.canonical,r=i/t.af(o.z),a=o.x+Math.pow(2,o.z)*e.wrap,s=t.ag(new Float64Array(16));return t.M(s,s,[a*r,o.y*r,0]),t.N(s,s,[r/t.$,r/t.$,1]),s}function de(e,i,o,r,a){const s=t.a1.fromLngLat(e,i),n=a*t.aj(1,e.lat),l=n*Math.cos(t.ae(o)),c=Math.sqrt(n*n-l*l),h=c*Math.sin(t.ae(-r)),u=c*Math.cos(t.ae(-r));return new t.a1(s.x+h,s.y+u,s.z+l)}function _e(e,t,i){const o=t.intersectsFrustum(e);if(!i||0===o)return o;const r=t.intersectsPlane(i);return 0===r?0:2===o&&2===r?2:1}function pe(e,t,i){let o=0;const r=(i-t)/10;for(let a=0;a<10;a++)o+=r*Math.pow(Math.cos(t+(a+.5)/10*(i-t)),e);return o}function me(e,i){return function(o,r,a,s,n){const l=2*((e-1)/t.ak(Math.cos(t.ae(ne-n))/Math.cos(t.ae(ne)))-1),c=Math.acos(a/s),h=2*pe(l-1,0,t.ae(n/2)),u=Math.min(t.ae(ne),c+t.ae(n/2)),d=pe(l-1,Math.min(u,c-t.ae(n/2)),u),_=Math.atan(r/a),p=Math.hypot(r,a);let m=o;return m+=t.ak(s/p/Math.max(.5,Math.cos(t.ae(n/2)))),m+=l*t.ak(Math.cos(_))/2,m-=t.ak(Math.max(1,d/h/i))/2,m}}const fe=me(9.314,3);function ge(e,i){const o=(i.roundZoom?Math.round:Math.floor)(e.zoom+t.ak(e.tileSize/i.tileSize));return Math.max(0,o)}function ve(e,i){const o=e.getCameraFrustum(),r=e.getClippingPlane(),a=e.screenPointToMercatorCoordinate(e.getCameraPoint()),s=t.a1.fromLngLat(e.center,e.elevation);a.z=s.z+Math.cos(e.pitchInRadians)*e.cameraToCenterDistance/e.worldSize;const n=e.getCoveringTilesDetailsProvider(),l=n.allowVariableZoom(e,i),c=ge(e,i),h=i.minzoom||0,u=void 0!==i.maxzoom?i.maxzoom:e.maxZoom,d=Math.min(Math.max(0,c),u),_=Math.pow(2,d),p=[_*a.x,_*a.y,0],m=[_*s.x,_*s.y,0],f=Math.hypot(s.x-a.x,s.y-a.y),g=Math.abs(s.z-a.z),v=Math.hypot(f,g),b=e=>({zoom:0,x:0,y:0,wrap:e,fullyVisible:!1}),x=[],y=[];if(e.renderWorldCopies&&n.allowWorldCopies())for(let e=1;e<=3;e++)x.push(b(-e)),x.push(b(e));for(x.push(b(0));x.length>0;){const _=x.pop(),f=_.x,b=_.y;let w=_.fullyVisible;const T={x:f,y:b,z:_.zoom},P=n.getTileBoundingVolume(T,_.wrap,e.elevation,i);if(!w){const e=_e(o,P,r);if(0===e)continue;w=2===e;}const C=n.distanceToTile2d(a.x,a.y,T,P);let I=c;l&&(I=(i.calculateTileZoom||fe)(e.zoom+t.ak(e.tileSize/i.tileSize),C,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const M=Math.min(I,u);if(_.wrap=n.getWrap(s,T,_.wrap),_.zoom>=M){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return y.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}const be=t.a2.fromPoints([new t.P(0,0),new t.P(t.$,t.$)]);class xe extends t.E{constructor(e,t,i){super(),this.id=e,this.dispatcher=i,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=!1;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,o)=>{const r=new(J(t.type))(e,t,i,o);if(r.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${r.id}`);return r})(e,t,i,this),this._tiles={},this._cache=new ae(0,(e=>this._unloadTile(e))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new se,this._didEmitContent=!1,this._updated=!1;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e);}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return !0;if(!this._updated)return !1;for(const e in this._tiles){const t=this._tiles[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}return !0}getSource(){return this._source}pause(){this._paused=!0;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,o){return t._(this,void 0,void 0,(function*(){try{yield this._source.loadTile(e),this._tileLoaded(e,i,o);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.k(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.l("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const t in this._tiles){const i=this._tiles[t];i.upload(e),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(ye).map((e=>e.key))}getRenderableIds(e){const i=[];for(const t in this._tiles)this._isIdRenderable(t,e)&&i.push(this._tiles[t]);return e?i.sort(((e,i)=>{const o=e.tileID,r=i.tileID,a=new t.P(o.canonical.x,o.canonical.y)._rotate(-this.transform.bearingInRadians),s=new t.P(r.canonical.x,r.canonical.y)._rotate(-this.transform.bearingInRadians);return o.overscaledZ-r.overscaledZ||s.y-a.y||s.x-a.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(ye).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return !!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())}reload(e){if(this._paused)this._shouldReloadOnResume=!0;else {this._cache.reset();for(const t in this._tiles)e?this._reloadTile(t,"expired"):"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading");}}_reloadTile(e,i){return t._(this,void 0,void 0,(function*(){const t=this._tiles[e];t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,o){e.timeAdded=s.now(),"expired"===o&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.l("data",{dataType:"source",tile:e,coord:e.tileID}));}_backfillDEM(e){const t=this.getRenderableIds();for(let o=0;o1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,o),e.neighboringTiles&&e.neighboringTiles[a]&&(e.neighboringTiles[a].backfilled=!0)));}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,o){for(const r in this._tiles){let a=this._tiles[r];if(o[r]||!a.hasData()||a.tileID.overscaledZ<=t||a.tileID.overscaledZ>i)continue;let s=a.tileID;for(;a&&a.tileID.overscaledZ>t+1;){const e=a.tileID.scaledTo(a.tileID.overscaledZ-1);a=this._tiles[e.key],a&&a.hasData()&&(s=e);}let n=s;for(;n.overscaledZ>t;)if(n=n.scaledTo(n.overscaledZ-1),e[n.key]||e[n.canonical.key]){o[s.key]=s;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),o=this._getLoadedTile(t);if(o)return o}}findLoadedSibling(e){return this._getLoadedTile(e)}_getLoadedTile(e){const t=this._tiles[e.key];return t&&t.hasData()?t:this._cache.getByKey(e.wrapped().key)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,o=Math.ceil(e.height/this._source.tileSize)+1,r=Math.floor(i*o*(null===this._maxTileCacheZoomLevels?t.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),a="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(a);}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e={};for(const i in this._tiles){const o=this._tiles[i];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),e[o.tileID.key]=o;}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(e,this._tiles[e]);}}_updateCoveredAndRetainedTiles(e,t,i,o,r,a){const n={},l={},c=Object.keys(e),h=s.now();for(const i of c){const o=e[i],r=this._tiles[i];if(!r||0!==r.fadeEndTime&&r.fadeEndTime<=h)continue;const a=this.findLoadedParent(o,t),s=this.findLoadedSibling(o),c=a||s||null;c&&(this._addTile(c.tileID),n[c.tileID.key]=c.tileID),l[i]=o;}this._retainLoadedChildren(l,o,i,e);for(const t in n)e[t]||(this._coveredTiles[t]=!0,e[t]=n[t]);if(a){const t={},i={};for(const e of r)this._tiles[e.key].hasData()?t[e.key]=e:i[e.key]=e;for(const o in i){const r=i[o].children(this._source.maxzoom);this._tiles[r[0].key]&&this._tiles[r[1].key]&&this._tiles[r[2].key]&&this._tiles[r[3].key]&&(t[r[0].key]=e[r[0].key]=r[0],t[r[1].key]=e[r[1].key]=r[1],t[r[2].key]=e[r[2].key]=r[2],t[r[3].key]=e[r[3].key]=r[3],delete i[o]);}for(const o in i){const r=i[o],a=this.findLoadedParent(r,this._source.minzoom),s=this.findLoadedSibling(r),n=a||s||null;if(n){t[n.tileID.key]=e[n.tileID.key]=n.tileID;for(const e in t)t[e].isChildOf(n.tileID)&&delete t[e];}}for(const e in this._tiles)t[e]||(this._coveredTiles[e]=!0);}}update(e,i){if(!this._sourceLoaded||this._paused)return;let o;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?o=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.Z(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(o=ve(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(o=o.filter((e=>this._source.hasTile(e))))):o=[];const r=ge(e,this._source),a=Math.max(r-xe.maxOverzooming,this._source.minzoom),s=Math.max(r+xe.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const e={};for(const t of o)if(t.canonical.z>this._source.minzoom){const i=t.scaledTo(t.canonical.z-1);e[i.key]=i;const o=t.scaledTo(Math.max(this._source.minzoom,Math.min(t.canonical.z,5)));e[o.key]=o;}o=o.concat(Object.values(e));}const n=0===o.length&&!this._updated&&this._didEmitContent;this._updated=!0,n&&this.fire(new t.l("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(o,r);we(this._source.type)&&this._updateCoveredAndRetainedTiles(l,a,s,r,o,i);for(const e in l)this._tiles[e].clearFadeHold();const c=t.am(this._tiles,l);for(const e of c){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const o={},r={},a=Math.max(t-xe.maxOverzooming,this._source.minzoom),s=Math.max(t+xe.maxUnderzooming,this._source.minzoom),n={};for(const i of e){const e=this._addTile(i);o[i.key]=i,e.hasData()||tthis._source.maxzoom){const e=s.children(this._source.maxzoom)[0],t=this.getTile(e);if(t&&t.hasData()){o[e.key]=e;continue}}else {const e=s.children(this._source.maxzoom);if(4===e.length&&o[e[0].key]&&o[e[1].key]&&o[e[2].key]&&o[e[3].key])continue;if(1===e.length&&o[e[0].key])continue}let n=e.wasRequested();for(let t=s.overscaledZ-1;t>=a;--t){const a=s.scaledTo(t);if(r[a.key])break;if(r[a.key]=!0,e=this.getTile(a),!e&&n&&(e=this._addTile(a)),e){const t=e.hasData();if((t||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||n)&&(o[a.key]=a),n=e.wasRequested(),t)break}}}return o}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,o=this._tiles[e].tileID;for(;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}t.push(o.key);const e=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;o=e;}for(const e of t)this._loadedParentTiles[e]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const e in this._tiles){const t=this._tiles[e].tileID,i=this._getLoadedTile(t);this._loadedSiblingTiles[t.key]=i;}}_addTile(e){let i=this._tiles[e.key];if(i)return i;i=this._cache.getAndRemove(e),i&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));const o=i;return i||(i=new re(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._tiles[e.key]=i,o||this._source.fire(new t.l("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}refreshTiles(e){for(const t in this._tiles)(this._isIdRenderable(t)||"errored"==this._tiles[t].state)&&e.some((e=>e.equals(this._tiles[t].tileID.canonical)))&&this._reloadTile(t,"expired");}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=!0,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){const t=e.sourceDataType;"source"===e.dataType&&"metadata"===t&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===t&&(this.reload(e.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0);}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e in this._tiles)this._removeTile(e);this._cache.reset();}tilesIn(e,i,o){const r=[],a=this.transform;if(!a)return r;const s=a.getCoveringTilesDetailsProvider().allowWorldCopies(),n=o?a.getCameraQueryGeometry(e):e,l=e=>a.screenPointToMercatorCoordinate(e,this.terrain),c=this.transformBbox(e,l,!s),h=this.transformBbox(n,l,!s),u=this.getIds(),d=t.a2.fromPoints(h);for(let e=0;ee.getTilePoint(new t.a1(i.x,i.y))));if(i.expandBy(_),i.intersects(be)){const t=c.map((t=>e.getTilePoint(t))),i=h.map((t=>e.getTilePoint(t)));r.push({tile:o,tileID:s?e:e.unwrapTo(0),queryGeometry:t,cameraQueryGeometry:i,scale:l});}}}return r}transformBbox(e,i,o){let r=e.map(i);if(o){const o=t.a2.fromPoints(e);o.shrinkBy(.001*Math.min(o.width(),o.height()));const a=o.map(i);t.a2.fromPoints(r).covers(a)||(r=r.map((e=>e.x>.5?new t.a1(e.x-1,e.y,e.z):e)));}return r}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._tiles[e].tileID));return this.transform&&this.transform.populateCache(t),t}hasTransition(){if(this._source.hasTransition())return !0;if(we(this._source.type)){const e=s.now();for(const t in this._tiles)if(this._tiles[t].fadeEndTime>=e)return !0}return !1}setFeatureState(e,t,i){this._state.updateState(e=e||"_geojsonTileLayer",t,i);}removeFeatureState(e,t,i){this._state.removeFeatureState(e=e||"_geojsonTileLayer",t,i);}getFeatureState(e,t){return this._state.getState(e=e||"_geojsonTileLayer",t)}setDependencies(e,t,i){const o=this._tiles[e];o&&o.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)));}}function ye(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),o=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||o-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function we(e){return "raster"===e||"image"===e||"video"===e}xe.maxOverzooming=10,xe.maxUnderzooming=3;class Te{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(r-s)/n:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))}}function Pe(e,t){let i=!0;return "always"===e||"never"!==e&&"never"!==t||(i=!1),i}class Ce{constructor(e,t,i){const o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||o<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=o){if(r)return [{key:null,x1:e,y1:t,x2:i,y2:o}];for(let e=0;e0}hitTestCircle(e,t,i,o,r){const a=e-i,s=e+i,n=t-i,l=t+i;if(s<0||a>this.width||l<0||n>this.height)return !1;const c=[];return this._forEachCell(a,n,s,l,this._queryCellCircle,c,{hitTest:!0,overlapMode:o,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},r),c.length>0}_queryCell(e,t,i,o,r,a,s,n){const{seenUids:l,hitTest:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const r=this.bboxes;for(const s of u)if(!l.box[s]){l.box[s]=!0;const u=4*s,d=this.boxKeys[s];if(e<=r[u+2]&&t<=r[u+3]&&i>=r[u+0]&&o>=r[u+1]&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))&&(a.push({key:d,x1:r[u],y1:r[u+1],x2:r[u+2],y2:r[u+3]}),c))return !0}}const d=this.circleCells[r];if(null!==d){const r=this.circles;for(const s of d)if(!l.circle[s]){l.circle[s]=!0;const u=3*s,d=this.circleKeys[s];if(this._circleAndRectCollide(r[u],r[u+1],r[u+2],e,t,i,o)&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))){const e=r[u],t=r[u+1],i=r[u+2];if(a.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return !0}}}return !1}_queryCellCircle(e,t,i,o,r,a,s,n){const{circle:l,seenUids:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=!0;const i=4*t,o=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}const d=this.circleCells[r];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=!0;const i=3*t,o=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}}_forEachCell(e,t,i,o,r,a,s,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(o);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(r.call(this,e,t,i,o,this.xCellCount*l+d,a,s,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,o,r,a){const s=o-e,n=r-t,l=i+a;return l*l>s*s+n*n}_circleAndRectCollide(e,t,i,o,r,a,s){const n=(a-o)/2,l=Math.abs(e-(o+n));if(l>n+i)return !1;const c=(s-r)/2,h=Math.abs(t-(r+c));if(h>c+i)return !1;if(l<=n||h<=c)return !0;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function Ie(e,i,r){const a=t.L();if(!e){const{vecSouth:e,vecEast:t}=Se(i),r=o();r[0]=t[0],r[1]=t[1],r[2]=e[0],r[3]=e[1],s=r,(d=(l=(n=r)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(s[0]=u*(d=1/d),s[1]=-c*d,s[2]=-h*d,s[3]=l*d),a[0]=r[0],a[1]=r[1],a[4]=r[2],a[5]=r[3];}var s,n,l,c,h,u,d;return t.N(a,a,[1/r,1/r,1]),a}function Me(e,i,o,r){if(e){const e=t.L();if(!i){const{vecSouth:t,vecEast:i}=Se(o);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.N(e,e,[r,r,1]),e}return o.pixelsToClipSpaceMatrix}function Se(e){const i=Math.cos(e.rollInRadians),o=Math.sin(e.rollInRadians),r=Math.cos(e.pitchInRadians),a=Math.cos(e.bearingInRadians),s=Math.sin(e.bearingInRadians),n=t.ar();n[0]=-a*r*o-s*i,n[1]=-s*r*o+a*i;const l=t.as(n);l<1e-9?t.at(n):t.au(n,n,1/l);const c=t.ar();c[0]=a*r*i-s*o,c[1]=s*r*i+a*o;const h=t.as(c);return h<1e-9?t.at(c):t.au(c,c,1/h),{vecEast:c,vecSouth:n}}function Ee(e,i,o,r){let a;r?(a=[e,i,r(e,i),1],t.aw(a,a,o)):(a=[e,i,0,1],qe(a,a,o));const s=a[3];return {point:new t.P(a[0]/s,a[1]/s),signedDistanceFromCamera:s,isOccluded:!1}}function Re(e,t){return .5+e/t*.5}function ze(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function De(e,i,o,r,a,s,n,l,c,h,u,d,_){const p=o?e.textSizeData:e.iconSizeData,m=t.an(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=o?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,b=o?e.text.placedSymbolArray:e.icon.placedSymbolArray,x=i.transform.width/i.transform.height;let y=!1;for(let o=0;oMath.abs(o.x-i.x)*r?{useVertical:!0}:(e===t.ao.vertical?i.yo.x)?{needsFlipping:!0}:null}function ke(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:o,symbol:r,fontSize:a,flip:s,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=a/24,_=r.lineOffsetX*d,p=r.lineOffsetY*d;let m;if(r.numGlyphs>1){const e=r.glyphStartIndex+r.numGlyphs,t=r.lineStartIndex,a=r.lineStartIndex+r.lineLength,c=Ae(d,l,_,p,s,r,u,i);if(!c)return {notEnoughRoom:!0};const f=je(c.first.point.x,c.first.point.y,i,o),g=je(c.last.point.x,c.last.point.y,i,o);if(n&&!s){const e=Le(r.writingMode,f,g,h);if(e)return e}m=[c.first];for(let o=r.glyphStartIndex+1;o0?n.point:Fe(i.tileAnchorPoint,s,e,1,i),c=je(e.x,e.y,i,o),u=je(l.x,l.y,i,o),d=Le(r.writingMode,c,u,h);if(d)return d}const e=Ge(d*l.getoffsetX(r.glyphStartIndex),_,p,s,r.segment,r.lineStartIndex,r.lineStartIndex+r.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:!0};m=[e];}for(const e of m)t.av(c,e.point,e.angle);return {}}function Fe(e,t,i,o,r){const a=e.add(e.sub(t)._unit()),s=Oe(a.x,a.y,r).point,n=i.sub(s);return i.add(n._mult(o/n.mag()))}function Be(e,i,o){const r=i.projectionCache;if(r.projections[e])return r.projections[e];const a=new t.P(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),s=Oe(a.x,a.y,i);if(s.signedDistanceFromCamera>0)return r.projections[e]=s.point,r.anyProjectionOccluded=r.anyProjectionOccluded||s.isOccluded,s.point;const n=e-o.direction;return Fe(0===o.distanceFromAnchor?i.tileAnchorPoint:new t.P(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),a,o.previousVertex,o.absOffsetX-o.distanceFromAnchor+1,i)}function Oe(e,t,i){const o=e+i.translation[0],r=t+i.translation[1];let a;return i.pitchWithMap?(a=Ee(o,r,i.pitchedLabelPlaneMatrix,i.getElevation),a.isOccluded=!1):(a=i.transform.projectTileCoordinates(o,r,i.unwrappedTileID,i.getElevation),a.point.x=(.5*a.point.x+.5)*i.width,a.point.y=(.5*-a.point.y+.5)*i.height),a}function je(e,i,o,r){if(o.pitchWithMap){const a=[e,i,0,1];return t.aw(a,a,r),o.transform.projectTileCoordinates(a[0]/a[3],a[1]/a[3],o.unwrappedTileID,o.getElevation).point}return {x:e/o.width*2-1,y:1-i/o.height*2}}function Ne(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function Ue(e,t,i){return e._unit()._perp()._mult(t*i)}function Ze(e,i,o,r,a,s,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=o.add(i);if(e+c.direction=a)return l.projectionCache.offsets[e]=h,h;const u=Be(e+c.direction,l,c),d=Ue(u.sub(o),n,c.direction),_=o.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.ax(s,h,_,p)||h,l.projectionCache.offsets[e]}function Ge(e,t,i,o,r,a,s,n,l){const c=o?e-t:e+t;let h=c>0?1:-1,u=0;o&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?a+r:a+r+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Oe(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,b=0;const x=Math.abs(c),y=[];let w;for(;v+b<=x;){if(_+=h,_=s)return null;v+=b,g=f,m=p;const e={absOffsetX:x,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=Be(_,n,e),0===i)y.push(g),w=f.sub(g);else {let t;const o=f.sub(g);t=0===o.mag()?Ue(Be(_+h,n,e).sub(f),i,h):Ue(o,i,h),m||(m=g.add(t)),p=Ze(_,t,f,a,s,m,i,n,e),y.push(m),w=p.sub(m);}b=w.mag();}const T=w._mult((x-v)/b)._add(m||g),P=u+Math.atan2(f.y-g.y,f.x-g.x);return y.push(T),{point:T,angle:l?P:0,path:y}}const Ve=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function $e(e,t){for(let i=0;i=1;e--)_.push(s.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=o.x&&i.x<=r.x&&e.y>=o.y&&i.y<=r.y?[_]:i.xr.x||i.yr.y?[]:t.ay([_],o.x,o.y,r.x,r.y);}for(const t of f){a.reset(t,.25*i);let o=0;o=a.length<=.5*i?1:Math.ceil(a.paddedLength/p)+1;for(let t=0;t{const t=Ee(e.x,e.y,o,i.getElevation),r=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return r.point.x=(.5*r.point.x+.5)*i.width,r.point.y=(.5*-r.point.y+.5)*i.height,r}))}(e,i);return function(e){let t=0,i=0,o=0,r=0;for(let a=0;ai&&(i=r,t=o));return e.slice(t,t+i)}(o)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[],o=new t.a2;for(const r of e){const e=new t.P(r.x+We,r.y+We);o.extend(e),i.push(e);}const{minX:r,minY:a,maxX:s,maxY:n}=o,l=this.grid.query(r,a,s,n).concat(this.ignoredGrid.query(r,a,s,n)),c={},h={};for(const e of l){const o=e.key;if(void 0===c[o.bucketInstanceId]&&(c[o.bucketInstanceId]={}),c[o.bucketInstanceId][o.featureIndex])continue;const r=[new t.P(e.x1,e.y1),new t.P(e.x2,e.y1),new t.P(e.x2,e.y2),new t.P(e.x1,e.y2)];t.az(i,r)&&(c[o.bucketInstanceId][o.featureIndex]=!0,void 0===h[o.bucketInstanceId]&&(h[o.bucketInstanceId]=[]),h[o.bucketInstanceId].push(o.featureIndex));}return h}insertCollisionBox(e,t,i,o,r,a){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,o,r,a){const s=i?this.ignoredGrid:this.grid,n={bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t};for(let t=0;t=this.screenRightBoundary||othis.screenBottomBoundary}isInsideGrid(e,t,i,o){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,r,c,u)));E=e.some((e=>!e.isOccluded)),S=e.map((e=>new t.P(e.x,e.y)));}else E=!0;return {box:t.aA(S),allPointsOccluded:!E}}}class Xe{constructor(e,t,i,o){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):o&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class Ke{constructor(e,t,i,o,r){this.text=new Xe(e?e.text:null,t,i,r),this.icon=new Xe(e?e.icon:null,t,o,r);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ye{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class Qe{constructor(e,t,i,o,r){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=r;}}class Je{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function et(e,i,o,r,a){const{horizontalAlign:s,verticalAlign:n}=t.aH(e);return new t.P(-(s-.5)*i+r[0]*a,-(n-.5)*o+r[1]*a)}class tt{constructor(e,t,i,o,r){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new He(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new Je(o),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=r,r&&(r.prevPlacement=void 0),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,o)=>t.getElevation(e,i,o):null}getBucketParts(e,i,o,r){const a=o.getBucket(i),s=o.latestFeatureIndex;if(!a||!s||i.id!==a.layerIds[0])return;const n=o.collisionBoxArray,l=a.layers[0].layout,c=a.layers[0].paint,h=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),u=o.tileSize/t.$,d=o.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.aC(o,1,this.transform.zoom),m=t.aD(this.collisionIndex.transform,o,c.get("text-translate"),c.get("text-translate-anchor")),f=t.aD(this.collisionIndex.transform,o,c.get("icon-translate"),c.get("icon-translate-anchor")),g=Ie(_,this.transform,p);this.retainedQueryData[a.bucketInstanceId]=new Qe(a.bucketInstanceId,s,a.sourceLayerIndex,a.index,o.tileID);const v={bucket:a,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:o.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.an(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(r)for(const t of a.sortKeyRanges){const{sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r}=t;e.push({sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v,b,x){const y=t.aE[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=et(y,o,r,w,a),P=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,s,f,u.predicate,b,T,x);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,s,g,u.predicate,b,T,x).placeable)&&P.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:o,height:r,anchor:y,textBoxScale:a,prevAnchor:e},this.markUsedJustification(p,y,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:P}}}placeLayerBucketPart(e,i,o){const{bucket:r,layout:a,translationText:s,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=a.get("text-optional"),f=a.get("icon-optional"),g=t.aF(a,"text-overlap","text-allow-overlap"),v="always"===g,b=t.aF(a,"icon-overlap","icon-allow-overlap"),x="always"===b,y="map"===a.get("text-rotation-alignment"),w="map"===a.get("text-pitch-alignment"),T="none"!==a.get("icon-text-fit"),P="viewport-y"===a.get("symbol-z-order"),C=v&&(x||!r.hasIconData()||f),I=x&&(v||!r.hasTextData()||m);!r.collisionArrays&&d&&r.deserializeCollisionBoxes(d);const M=this.retainedQueryData[r.bucketInstanceId].tileID,S=this._getTerrainElevationFunc(M),E=this.transform.getFastPathSimpleProjectionMatrix(M),R=(e,d,x)=>{var P,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new Ye(!1,!1,!1));let z=!1,D=!1,A=!0,L=null,k={box:null,placeable:!1,offscreen:null,occluded:!1},F={placeable:!1},B=null,O=null,j=null,N=0,U=0,Z=0;d.textFeatureIndex?N=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(N=e.featureIndex),d.verticalTextFeatureIndex&&(U=d.verticalTextFeatureIndex);const G=d.textBox;if(G){const i=i=>{let o=t.ao.horizontal;if(r.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,o=t,this.markUsedOrientation(r,o,e));}return o},a=(i,o)=>{if(r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of r.writingModes)if(e===t.ao.vertical?(k=o(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const o=(t,i)=>{const o=this.collisionIndex.placeCollisionBox(t,g,h,M,l,w,y,s,p.predicate,S,void 0,E);return o&&o.placeable&&(this.markUsedOrientation(r,i,e),this.placedOrientations[e.crossTileID]=i),o};a((()=>o(G,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?o(i,t.ao.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.aE[null===(R=null===(P=this.prevPlacement)||void 0===P?void 0:P.variableOffsets[e.crossTileID])||void 0===R?void 0:R.anchor];const m=(t,i,a)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===b?i:null;let x=null,P="never"===g?1:2,C="never";_&&P++;for(let i=0;im(G,d.iconBox,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.ao.vertical):{box:null,occluded:!0,offscreen:null}})),k&&(z=k.placeable,A=k.offscreen);const f=i(k&&k.placeable);if(!z&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(r,t.anchor,e,f));}}}if(B=k,z=B&&B.placeable,A=B&&B.offscreen,e.useRuntimeCollisionCircles){const i=r.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.ap(r.textSizeData,_,i),h=a.get("text-padding");O=this.collisionIndex.placeCollisionCircles(g,i,r.lineVertexArray,r.glyphOffsetArray,n,l,c,o,w,p.predicate,e.collisionCircleDiameter,h,s,S),O.circles.length&&O.collisionDetected&&!o&&t.w("Collisions detected, but collision boxes are not shown"),z=v||O.circles.length>0&&!O.collisionDetected,A=A&&O.offscreen;}if(d.iconFeatureIndex&&(Z=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,b,h,M,l,w,y,n,p.predicate,S,T&&L?L:void 0,E);F&&F.placeable&&d.verticalIconBox?(j=e(d.verticalIconBox),D=j.placeable):(j=e(d.iconBox),D=j.placeable),A=A&&j.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,$=f||0===e.numIconVertices;V||$?$?V||(D=D&&z):z=D&&z:D=z=D&&z;const q=D&&j.placeable;if(z&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,a.get("text-ignore-placement"),r.bucketInstanceId,F&&F.placeable&&U?U:N,p.ID),q&&this.collisionIndex.insertCollisionBox(j.box,b,a.get("icon-ignore-placement"),r.bucketInstanceId,Z,p.ID),O&&z&&this.collisionIndex.insertCollisionCircles(O.circles,g,a.get("text-ignore-placement"),r.bucketInstanceId,N,p.ID),o&&this.storeCollisionData(r.bucketInstanceId,x,d,B,j,O),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===r.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new Ye((z||C)&&!(null==B?void 0:B.occluded),(D||I)&&!(null==j?void 0:j.occluded),A||r.justReloaded),i[e.crossTileID]=!0;};if(P){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=r.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(r.symbolInstances.get(i),r.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=a>=0&&t!==a?0:o.crossTileID);}markUsedOrientation(e,i,o){const r=i===t.ao.horizontal||i===t.ao.horizontalOnly?i:0,a=i===t.ao.vertical?i:0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];for(const t of s)e.text.placedSymbolArray.get(t).placedOrientation=r;o.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).placedOrientation=a);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=!1;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const o=t?t.symbolFadeChange(e):1,r=t?t.opacities:{},a=t?t.variableOffsets:{},s=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],a=r[e];a?(this.opacities[e]=new Ke(a,o,t.text,t.icon),i=i||t.text!==a.text.placed||t.icon!==a.icon.placed):(this.opacities[e]=new Ke(null,o,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in r){const t=r[e];if(!this.opacities[e]){const r=new Ke(t,o,!1,!1);r.isHidden()||(this.opacities[e]=r,i=i||t.text.placed||t.icon.placed);}}for(const e in a)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=a[e]);for(const e in s)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=s[e]);if(t&&void 0===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const o of t){const t=o.getBucket(e);t&&o.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,o.tileID,i,o.collisionBoxArray);}}updateBucketOpacities(e,i,o,r){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=!1),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=!1),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const a=e.layers[0],s=a.layout,n=new Ke(null,0,!1,!1,!0),l=s.get("text-allow-overlap"),c=s.get("icon-allow-overlap"),h=a._unevaluatedLayout.hasValue("text-variable-anchor")||a._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===s.get("text-rotation-alignment"),d="map"===s.get("text-pitch-alignment"),_="none"!==s.get("icon-text-fit"),p=new Ke(null,0,l&&(c||!e.hasIconData()||s.get("icon-optional")),c&&(l||!e.hasTextData()||s.get("text-optional")),!0);!e.collisionArrays&&r&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(r);const m=(e,t,i)=>{for(let o=0;o0,v=this.placedOrientations[r.crossTileID],b=v===t.ao.vertical,x=v===t.ao.horizontal||v===t.ao.horizontalOnly;if(a>0||s>0){const t=ht(c.text);m(e.text,a,b?ut:t),m(e.text,s,x?ut:t);const i=c.text.isHidden();[r.rightJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||b?1:0);})),r.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).hidden=i||x?1:0);const o=this.variableOffsets[r.crossTileID];o&&this.markUsedJustification(e,o.anchor,r,v);const n=this.placedOrientations[r.crossTileID];n&&(this.markUsedJustification(e,"left",r,n),this.markUsedOrientation(e,n,r));}if(g){const t=ht(c.icon),i=!(_&&r.verticalPlacedIconSymbolIndex&&b);r.placedIconSymbolIndex>=0&&(m(e.icon,r.numIconVertices,i?t:ut),e.icon.placedSymbolArray.get(r.placedIconSymbolIndex).hidden=c.icon.isHidden()),r.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,r.numVerticalIconVertices,i?ut:t),e.icon.placedSymbolArray.get(r.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const y=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const o=e.collisionArrays[i];if(o){let i=new t.P(0,0);if(o.textBox||o.verticalTextBox){let t=!0;if(h){const e=this.variableOffsets[l];e?(i=et(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=!1;}if(o.textBox||o.verticalTextBox){let r;o.textBox&&(r=b),o.verticalTextBox&&(r=x),it(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||r,y.text,i.x,i.y);}}if(o.iconBox||o.verticalIconBox){const t=Boolean(!x&&o.verticalIconBox);let r;o.iconBox&&(r=t),o.verticalIconBox&&(r=!t),it(e.iconCollisionBox.collisionVertexArray,c.icon.placed,r,y.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=!0;}}function it(e,t,i,o,r,a){o&&0!==o.length||(o=[0,0,0,0]);const s=o[0]-We,n=o[1]-We,l=o[2]-We,c=o[3]-We;e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,c),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,c);}const ot=Math.pow(2,25),rt=Math.pow(2,24),at=Math.pow(2,17),st=Math.pow(2,16),nt=Math.pow(2,9),lt=Math.pow(2,8),ct=Math.pow(2,1);function ht(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*ot+t*rt+i*at+t*st+i*nt+t*lt+i*ct+t}const ut=0;class dt{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,o,r){const a=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&s.now()-o>2;for(;this._currentPlacementIndex>=0;){const o=t[e[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if("symbol"===o.type&&(!o.minzoom||o.minzoom<=a)&&(!o.maxzoom||o.maxzoom>a)){if(this._inProgressLayer||(this._inProgressLayer=new dt(o)),this._inProgressLayer.continuePlacement(i[o.source],this.placement,this._showCollisionBoxes,o,r))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(e){return this.placement.commit(e),this.placement}}const pt=512/t.$/2;class mt{constructor(e,i,o){this.tileID=e,this.bucketInstanceId=o,this._symbolsByKey={};const r=new Map;for(let e=0;e({x:Math.floor(e.anchorX*pt),y:Math.floor(e.anchorY*pt)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(o.positions.length>128){const e=new t.aI(o.positions.length,16,Uint16Array);for(const{x:t,y:i}of o.positions)e.add(t,i);e.finish(),delete o.positions,o.index=e;}this._symbolsByKey[e]=o;}}getScaledCoordinates(e,i){const{x:o,y:r,z:a}=this.tileID.canonical,{x:s,y:n,z:l}=i.canonical,c=pt/Math.pow(2,l-a),h=(n*t.$+e.anchorY)*c,u=r*t.$*pt;return {x:Math.floor((s*t.$+e.anchorX)*c-o*t.$*pt),y:Math.floor(h-u)}}findMatches(e,t,i){const o=this.tileID.canonical.ze))}}class ft{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class gt{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],o={};for(const e in i){const r=i[e];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+t),o[r.tileID.key]=r;}this.indexes[e]=o;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in r){const a=r[i];a.tileID.isChildOf(e)&&a.findMatches(t.symbolInstances,e,o);}else {const a=r[e.scaledTo(Number(i)).key];a&&a.findMatches(t.symbolInstances,e,o);}}for(let e=0;e{t[e]=!0;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var bt="void main() {fragColor=vec4(1.0);}";const xt={prelude:yt("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:yt("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:yt("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:yt("uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:yt("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:yt("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:yt(bt,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:yt("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:yt("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:yt("in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:yt("in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),colorRelief:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform int u_color_ramp_size;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {float x=(float(stop)+0.5)/float(u_color_ramp_size);vec4 data=texture(u_elevation_stops,vec2(x,0))*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int r=(u_color_ramp_size-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else\n{l=m;el_l=el_m;}}float x=(float(l)+(el-el_l)/(el_r-el_l)+0.5)/float(u_color_ramp_size);fragColor=u_opacity*texture(u_color_stops,vec2(x,0));\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_dimension;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),debug:yt("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}","in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:yt(bt,"in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:yt("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:yt("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:yt("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:yt("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:yt("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {vec2 epsilon=1.0/u_dimension;float tileSize=u_dimension.x-2.0;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))*tileSize/pow(2.0,exaggeration+(28.2562-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+0.5,deriv.y/8.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:yt("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];\n#define PI 3.141592653589793\n#define STANDARD 0\n#define COMBINED 1\n#define IGOR 2\n#define MULTIDIRECTIONAL 3\n#define BASIC 4\nfloat get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);}void igor_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float aspect=get_aspect(deriv);float azimuth=u_azimuths[0]+PI;float slope_stength=atan(length(deriv))*2.0/PI;float aspect_strength=1.0-abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);float shadow_strength=slope_stength*aspect_strength;float highlight_strength=slope_stength*(1.0-aspect_strength);fragColor=u_shadows[0]*shadow_strength+u_highlights[0]*highlight_strength;}void standard_hillshade(vec2 deriv){float azimuth=u_azimuths[0]+PI;float slope=atan(0.625*length(deriv));float aspect=get_aspect(deriv);float intensity=u_exaggeration;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadows[0],u_highlights[0],shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;}void basic_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor=u_highlights[0]*(2.0*shade-1.0);}else\n{fragColor=u_shadows[0]*(1.0-2.0*shade);}}void multidirectional_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;fragColor=vec4(0,0,0,0);for(int i=0; i < NUM_ILLUMINATION_SOURCES; i++){float cos_alt=cos(u_altitudes[i]);float sin_alt=sin(u_altitudes[i]);float cos_az=-cos(u_azimuths[i]);float sin_az=-sin(u_azimuths[i]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor+=u_highlights[i]*(2.0*shade-1.0)/float(NUM_ILLUMINATION_SOURCES);}else\n{fragColor+=u_shadows[i]*(1.0-2.0*shade)/float(NUM_ILLUMINATION_SOURCES);}}}void combined_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=acos((sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv)));cang=clamp(cang,0.0,PI/2.0);float shade=cang*atan(length(deriv))*4.0/PI/PI;float highlight=(PI/2.0-cang)*atan(length(deriv))*4.0/PI/PI;fragColor=u_shadows[0]*shade+u_highlights[0]*highlight;}void main() {vec4 pixel=texture(u_image,v_pos);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));vec2 deriv=((pixel.rg*8.0)-4.0)/scaleFactor;if (u_method==BASIC) {basic_hillshade(deriv);} else if (u_method==COMBINED) {combined_hillshade(deriv);} else if (u_method==IGOR) {igor_hillshade(deriv);} else if (u_method==MULTIDIRECTIONAL) {multidirectional_hillshade(deriv);} else if (u_method==STANDARD) {standard_hillshade(deriv);} else {standard_hillshade(deriv);}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:yt("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:yt("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0);vec4 color1=texture(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:yt("uniform sampler2D u_texture;in vec2 v_tex;in float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;fragColor=texture(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_tex;out float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:yt("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:yt("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;fragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:yt("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}","in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:yt("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}","in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:yt("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:yt("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:yt("in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}","in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:yt("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function yt(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o=t.match(/in ([\w]+) ([\w]+)/g),r=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=a?a.concat(r):r,n={};return {fragmentSource:e=e.replace(i,((e,t,i,o,r)=>(n[r]=!0,"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nin ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = u_${r};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,o,r)=>{const a="float"===o?"vec2":"vec4",s=r.match(/color/)?"color":a;return n[r]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\nout ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`})),staticAttributes:o,staticUniforms:s}}class wt{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var Tt=t.aJ([{name:"a_pos",type:"Int16",components:2}]);const Pt="#define PROJECTION_MERCATOR",Ct="mercator";class It{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return !1}get shaderVariantName(){return Ct}get shaderDefine(){return Pt}get shaderPreludeCode(){return xt.projectionMercator}get vertexShaderPreludeCode(){return xt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.aK.noSubdivision}get useGlobeControls(){return !1}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(e){}getMeshFromTileID(e,i,o,r,a){if(this._cachedMesh)return this._cachedMesh;const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(t.$,0),s.emplaceBack(0,t.$),s.emplaceBack(t.$,t.$);const n=e.createVertexBuffer(s,Tt.members),l=t.aM.simpleSegment(0,0,4,2),c=new t.aN;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new wt(n,h,l),this._cachedMesh}recalculate(){}hasTransition(){return !1}setErrorQueryLatitudeDegrees(e){}}class Mt{constructor(e=0,t=0,i=0,o=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=o;}interpolate(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.C.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.C.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.C.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.C.number(e.right,i.right,o)),this}getCenter(e,i){const o=t.ah((this.left+e-this.right)/2,0,e),r=t.ah((this.top+i-this.bottom)/2,0,i);return new t.P(o,r)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new Mt(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function St(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function Et(e){return Math.max(0,Math.floor(e))}class Rt{constructor(e,i,o,r,a,s){this._callbacks=e,this._tileSize=512,this._renderWorldCopies=void 0===s||!!s,this._minZoom=i||0,this._maxZoom=o||22,this._minPitch=null==r?0:r,this._maxPitch=null==a?60:a,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.S(0,0),this._elevation=0,this._zoom=0,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new Mt,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=!0;}apply(e,i,o){this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new Mt(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,this._cameraToCenterDistance=e.cameraToCenterDistance,this._nearZ=e.nearZ,this._farZ=e.farZ,this._autoCalculateNearFarZ=!o&&e.autoCalculateNearFarZ,i&&this._constrain(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e;}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const i=t.aO(e,-180,180)*Math.PI/180;var r,a,s,n,l,c,h,u,d;this._bearingInRadians!==i&&(this._unmodified=!1,this._bearingInRadians=i,this._calcMatrices(),this._rotationMatrix=o(),r=this._rotationMatrix,s=-this._bearingInRadians,n=(a=this._rotationMatrix)[0],l=a[1],c=a[2],h=a[3],u=Math.sin(s),d=Math.cos(s),r[0]=n*d+c*u,r[1]=l*d+h*u,r[2]=n*-u+c*d,r[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.ah(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=!1,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=!1,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.aP(this._fovInRadians)}setFov(e){e=t.ah(e,.1,150),this.fov!==e&&(this._unmodified=!1,this._fovInRadians=t.ae(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const i=this.getConstrained(this._center,e).zoom;this._zoom!==i&&(this._unmodified=!1,this._zoom=i,this._tileZoom=Math.max(0,Math.floor(i)),this._scale=t.af(i),this._constrain(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(e,t){this._autoCalculateNearFarZ=!1,this._nearZ=e,this._farZ=t,this._calcMatrices();}clearNearFarZOverride(){this._autoCalculateNearFarZ=!0,this._calcMatrices();}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices();}resize(e,t,i=!0){this._width=e,this._height=t,i&&this._constrain(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new G([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-t.ai,t.ai]);}getConstrained(e,t){return this._callbacks.getConstrained(e,t)}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{const{minX:o,minY:r,maxX:a,maxY:s}=t.a2.fromPoints(i).extend(e);return [new t.P(o,r),new t.P(a,r),new t.P(a,s),new t.P(o,s),new t.P(o,r)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const e=this._unmodified,{center:t,zoom:i}=this.getConstrained(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=!1;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.ag(new Float64Array(16));t.N(e,e,[this._width/2,-this._height/2,1]),t.M(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.ag(new Float64Array(16)),t.N(e,e,[1,-1,1]),t.M(e,e,[-1,-1,0]),t.N(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height;}this._callbacks.calcMatrices();}calculateCenterFromCameraLngLatAlt(e,i,o,r){const a=void 0!==o?o:this.bearing,s=r=void 0!==r?r:this.pitch,n=t.a1.fromLngLat(e,i),l=-Math.cos(t.ae(s)),c=Math.sin(t.ae(s)),h=c*Math.sin(t.ae(a)),u=-c*Math.cos(t.ae(a));let d=this.elevation;const _=i-d;let p;l*_>=0||Math.abs(l)<.1?(p=1e4,d=i+p*l):p=-_/l;let m,f,g=t.aQ(1,n.y),v=0;do{if(v+=1,v>10)break;f=p/g,m=new t.a1(n.x+h*f,n.y+u*f),g=1/m.meterInMercatorCoordinateUnits();}while(Math.abs(p-f*g)>1e-12);return {center:m.toLngLat(),elevation:d,zoom:t.ak(this.height/2/Math.tan(this.fovInRadians/2)/f/this.tileSize)}}recalculateZoomAndCenter(e){if(this.elevation-e==0)return;const i=t.aj(1,this.center.lat)*this.worldSize,o=this.cameraToCenterDistance/i,r=t.a1.fromLngLat(this.center,this.elevation),a=de(this.center,this.elevation,this.pitch,this.bearing,o);this._elevation=e;const s=this.calculateCenterFromCameraLngLatAlt(a.toLngLat(),t.aQ(a.z,r.y),this.bearing,this.pitch);this._elevation=s.elevation,this._center=s.center,this.setZoom(s.zoom);}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.P(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/e).toLngLat()}getMercatorTileCoordinates(e){if(!e)return [0,0,1,1];const i=e.canonical.z>=0?1<this.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[o]*this.min[o],i+=e[o]*this.max[o]):(i+=e[o]*this.min[o],t+=e[o]*this.max[o]);return t>=0?2:i<0?0:1}}class Dt{distanceToTile2d(e,t,i,o){const r=o.distanceX([e,t]),a=o.distanceY([e,t]);return Math.hypot(r,a)}getWrap(e,t,i){return i}getTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}const c=1<r}allowWorldCopies(){return !0}prepareNextFrame(){}}class At{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,o=0,r,a){const s=a?[[6,5,4],[0,1,2],[0,3,7],[2,1,5],[3,2,6],[0,4,5]]:[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]],n=Math.pow(2,o),l=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((o=>function(e,i,o,r){const a=t.aw([],e,i),s=1/a[3]/o*r;return t.aY(a,a,[s,s,1/a[3],s])}(o,e,i,n)));r&&function(e,i,o,r){const a=r?4:0,s=r?0:4;let n=0;const l=[],c=[];for(let i=0;i<4;i++){const o=t.aU([],e[i+s],e[i+a]),r=t.aZ(o);t.aR(o,o,1/r),l.push(r),c.push(o);}for(let i=0;i<4;i++){const r=t.a_(e[i+a],c[i],o);n=null!==r&&r>=0?Math.max(n,r):Math.max(n,l[i]);}const h=function(e,i){const o=t.aU([],e[i[0]],e[i[1]]),r=t.aU([],e[i[2]],e[i[1]]),a=[0,0,0,0];return t.aV(a,t.aW([],o,r)),a[3]=-t.aX(a,e[i[0]]),a}(e,i),u=function(e,i){const o=t.a$(e),r=t.b0([],e,1/o),a=t.aU([],i,t.aR([],r,t.aX(i,r))),s=t.a$(a);if(s>0){const e=Math.sqrt(1-r[3]*r[3]),o=t.aR([],r,-r[3]),n=t.aS([],o,t.aR([],a,e/s));return t.b1(i,n)}return null}(o,h);if(null!==u){const e=u/t.aX(c[0],h);n=Math.min(n,e);}for(let t=0;t<4;t++){const i=Math.min(n,l[t]);e[t+s]=[e[t+a][0]+c[t][0]*i,e[t+a][1]+c[t][1]*i,e[t+a][2]+c[t][2]*i,1];}}(l,s[0],r,a);const c=s.map((e=>{const i=t.aU([],l[e[0]],l[e[1]]),o=t.aU([],l[e[2]],l[e[1]]),r=t.aV([],t.aW([],i,o)),a=-t.aX(r,l[e[1]]);return r.concat(a)})),h=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of l)for(let t=0;t<3;t++)h[t]=Math.min(h[t],e[t]),u[t]=Math.max(u[t],e[t]);return new At(l,c,new zt(h,u))}}class Lt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e,t){}constructor(e,t,i,o,r){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)},e,t,i,o,r),this._coveringTilesDetailsProvider=new Dt;}clone(){const e=new Lt;return e.apply(this),e}apply(e,t,i){this._helper.apply(e,t,i);}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.b2(0,e)];if(this._helper._renderWorldCopies){const o=this.screenPointToMercatorCoordinate(new t.P(0,0)),r=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,0)),a=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,this._helper._height)),s=this.screenPointToMercatorCoordinate(new t.P(0,this._helper._height)),n=Math.floor(Math.min(o.x,r.x,a.x,s.x)),l=Math.floor(Math.max(o.x,r.x,a.x,s.x)),c=1;for(let o=n-c;o<=l+c;o++)0!==o&&i.push(new t.b2(o,e));}return i}getCameraFrustum(){return At.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const t=this.screenPointToLocation(this.centerPoint,e),i=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(i);}setLocationAtPoint(e,i){const o=t.aj(this.elevation,this.center.lat),r=this.screenPointToMercatorCoordinateAtZ(i,o),a=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,o),s=t.a1.fromLngLat(e),n=new t.a1(s.x-(r.x-a.x),s.y-(r.y-a.y));this.setCenter(null==n?void 0:n.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,i){return i?this.coordinatePoint(t.a1.fromLngLat(e),i.getElevationForLngLatZoom(e,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(t.a1.fromLngLat(e))}screenPointToLocation(e,t){var i;return null===(i=this.screenPointToMercatorCoordinate(e,t))||void 0===i?void 0:i.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const o=i||0,r=[e.x,e.y,0,1],a=[e.x,e.y,1,1];t.aw(r,r,this._pixelMatrixInverse),t.aw(a,a,this._pixelMatrixInverse);const s=r[3],n=a[3],l=r[1]/s,c=a[1]/n,h=r[2]/s,u=a[2]/n,d=h===u?0:(o-h)/(u-h);return new t.a1(t.C.number(r[0]/s,a[0]/n,d)/this.worldSize,t.C.number(l,c,d)/this.worldSize,o)}coordinatePoint(e,i=0,o=this._pixelMatrix){const r=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.aw(r,r,o),new t.P(r[0]/r[3],r[1]/r[3])}getBounds(){const e=Math.max(0,this._helper._height/2-he(this));return (new G).extend(this.screenPointToLocation(new t.P(0,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.P(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-he(this)}calculatePosMatrix(e,i=!1,o){var r;const a=null!==(r=e.key)&&void 0!==r?r:t.b3(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),s=i?this._alignedPosMatrixCache:this._posMatrixCache;if(s.has(a)){const e=s.get(a);return o?e.f32:e.f64}const n=ue(e,this.worldSize);t.O(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return s.set(a,l),o?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,o=this._fogMatrixCacheF32;if(o.has(i))return o.get(i);const r=ue(e,this.worldSize);return t.O(r,this._fogMatrix,r),o.set(i,new Float32Array(r)),o.get(i)}getConstrained(e,i){i=t.ah(+i,this.minZoom,this.maxZoom);const o={center:new t.S(e.lng,e.lat),zoom:i};let r=this._helper._lngRange;if(!this._helper._renderWorldCopies&&null===r){const e=180-1e-10;r=[-e,e];}const a=this.tileSize*t.af(o.zoom);let s=0,n=a,l=0,c=a,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;s=t.U(e[1])*a,n=t.U(e[0])*a,n-s<_&&(h=_/(n-s));}r&&(l=t.aO(t.V(r[0])*a,0,a),c=t.aO(t.V(r[1])*a,0,a),cn&&(g=n-e);}if(r){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.aO(p,e-a/2,e+a/2));const o=d/2;i-oc&&(f=c-o);}if(void 0!==f||void 0!==g){const e=new t.P(null!=f?f:p,null!=g?g:m);o.center=ce(a,e).wrap();}return o}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}_calculateNearFarZIfNeeded(e,i,o){if(!this._helper.autoCalculateNearFarZ)return;const r=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),a=e-r*this._helper._pixelPerMeter/Math.cos(i),s=r<0?a:e,n=Math.PI/2+this.pitchInRadians,l=t.ae(this.fov)*(Math.abs(Math.cos(t.ae(this.roll)))*this.height+Math.abs(Math.sin(t.ae(this.roll)))*this.width)/this.height*(.5+o.y/this.height),c=Math.sin(l)*s/Math.sin(t.ah(Math.PI-n-l,.01,Math.PI-.01)),h=he(this),u=Math.atan(h/this._helper.cameraToCenterDistance),d=t.ae(.75),_=u>d?2*u*(.5+o.y/(2*h)):d,p=Math.sin(_)*s/Math.sin(t.ah(Math.PI-n-_,.01,Math.PI-.01)),m=Math.min(c,p);this._helper._farZ=1.01*(Math.cos(Math.PI/2-i)*m+s),this._helper._nearZ=this._helper._height/50;}_calcMatrices(){if(!this._helper._height)return;const e=this.centerOffset,i=le(this.worldSize,this.center),o=i.x,r=i.y;this._helper._pixelPerMeter=t.aj(1,this.center.lat)*this.worldSize;const a=t.ae(Math.min(this.pitch,ne)),s=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(a));let n;this._calculateNearFarZIfNeeded(s,a,e),n=new Float64Array(16),t.b4(n,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),t.aq(this._invProjMatrix,n),n[8]=2*-e.x/this._helper._width,n[9]=2*e.y/this._helper._height,this._projectionMatrix=t.b5(n),t.N(n,n,[1,-1,1]),t.M(n,n,[0,0,-this._helper.cameraToCenterDistance]),t.b6(n,n,-this.rollInRadians),t.b7(n,n,this.pitchInRadians),t.b6(n,n,-this.bearingInRadians),t.M(n,n,[-o,-r,0]),this._mercatorMatrix=t.N([],n,[this.worldSize,this.worldSize,this.worldSize]),t.N(n,n,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n),t.M(n,n,[0,0,-this.elevation]),this._viewProjMatrix=n,this._invViewProjMatrix=t.aq([],n);const l=[0,0,-1,1];t.aw(l,l,this._invViewProjMatrix),this._cameraPosition=[l[0]/l[3],l[1]/l[3],l[2]/l[3]],this._fogMatrix=new Float64Array(16),t.b4(this._fogMatrix,this.fovInRadians,this.width/this.height,s,this._helper._farZ),this._fogMatrix[8]=2*-e.x/this.width,this._fogMatrix[9]=2*e.y/this.height,t.N(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.b6(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.b7(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.b6(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.M(this._fogMatrix,this._fogMatrix,[-o,-r,0]),t.N(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n);const c=this._helper._width%2/2,h=this._helper._height%2/2,u=Math.cos(this.bearingInRadians),d=Math.sin(-this.bearingInRadians),_=o-Math.round(o)+u*c+d*h,p=r-Math.round(r)+u*h+d*c,m=new Float64Array(n);if(t.M(m,m,[_>.5?_-1:_,p>.5?p-1:p,0]),this._alignedProjMatrix=m,n=t.aq(new Float64Array(16),this._pixelMatrix),!n)throw new Error("failed to invert matrix");this._pixelMatrixInverse=n,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.P(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.aw(i,i,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/e).toLngLat()}lngLatToCameraDepth(e,i){const o=t.a1.fromLngLat(e),r=[o.x*this.worldSize,o.y*this.worldSize,i,1];return t.aw(r,r,this._viewProjMatrix),r[2]/r[3]}getProjectionData(e){const{overscaledTileID:i,aligned:o,applyTerrainMatrix:r}=e,a=this._helper.getMercatorTileCoordinates(i),s=i?this.calculatePosMatrix(i,o,!0):null;let n;return n=i&&i.terrainRttPosMatrix32f&&r?i.terrainRttPosMatrix32f:s||t.b8(),{mainMatrix:n,tileMercatorCoords:a,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:n}}isLocationOccluded(e){return !1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,i){return 1}transformLightDirection(e){return t.aT(e)}getRayDirectionFromPixel(e){throw new Error("Not implemented.")}projectTileCoordinates(e,i,o,r){const a=this.calculatePosMatrix(o);let s;r?(s=[e,i,r(e,i),1],t.aw(s,s,a)):(s=[e,i,0,1],qe(s,s,a));const n=s[3];return {point:new t.P(s[0]/n,s[1]/n),signedDistanceFromCamera:n,isOccluded:!1}}populateCache(e){for(const t of e)this.calculatePosMatrix(t);}getMatrixForModel(e,i){const o=t.a1.fromLngLat(e,i),r=o.meterInMercatorCoordinateUnits(),a=t.b9();return t.M(a,a,[o.x,o.y,o.z]),t.b6(a,a,Math.PI),t.b7(a,a,Math.PI/2),t.N(a,a,[-r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=new t.Z(0,0,0,0,0),o=this.getProjectionData({overscaledTileID:i,applyGlobeMatrix:e}),r=ue(i,this.worldSize);t.O(r,this._viewProjMatrix,r),o.tileMercatorCoords=[0,0,1,1];const a=[t.$,t.$,this.worldSize/this._helper.pixelsPerMeter],s=t.ba();return t.N(s,r,a),o.fallbackMatrix=s,o.mainMatrix=s,o}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}}function kt(){t.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");}function Ft(e){if(e.useSlerp)if(e.k<1){const i=t.bb(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),o=t.bb(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),r=new Float64Array(4);t.bc(r,i,o,e.k);const a=t.bd(r);e.tr.setRoll(a.roll),e.tr.setPitch(a.pitch),e.tr.setBearing(a.bearing);}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(t.C.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(t.C.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(t.C.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k));}function Bt(e,i,o,r,a){const s=a.padding,n=le(a.worldSize,o.getNorthWest()),l=le(a.worldSize,o.getNorthEast()),c=le(a.worldSize,o.getSouthEast()),h=le(a.worldSize,o.getSouthWest()),u=t.ae(-r),d=n.rotate(u),_=l.rotate(u),p=c.rotate(u),m=h.rotate(u),f=new t.P(Math.max(d.x,_.x,m.x,p.x),Math.max(d.y,_.y,m.y,p.y)),g=new t.P(Math.min(d.x,_.x,m.x,p.x),Math.min(d.y,_.y,m.y,p.y)),v=f.sub(g),b=(a.width-(s.left+s.right+i.left+i.right))/v.x,x=(a.height-(s.top+s.bottom+i.top+i.bottom))/v.y;if(x<0||b<0)return void kt();const y=Math.min(t.ak(a.scale*Math.min(b,x)),e.maxZoom),w=t.P.convert(e.offset),T=new t.P((i.left-i.right)/2,(i.top-i.bottom)/2).rotate(t.ae(r)),P=w.add(T).mult(a.scale/t.af(y));return {center:ce(a.worldSize,n.add(c).div(2).sub(P)),zoom:y,bearing:r}}class Ot{get useGlobeControls(){return !1}handlePanInertia(e,t){const i=e.mag(),o=Math.abs(he(t));return {easingOffset:e.mult(Math.min(.75*o/i,1)),easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta);}handleMapControlsPan(e,t,i){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(i,e.around);}cameraForBoxAndBearing(e,t,i,o,r){return Bt(e,t,i,o,r)}handleJumpToCenterZoom(e,i){e.zoom!==(void 0!==i.zoom?+i.zoom:e.zoom)&&e.setZoom(+i.zoom),void 0!==i.center&&e.setCenter(t.S.convert(i.center));}handleEaseTo(e,i){const o=e.zoom,r=e.padding,a={roll:e.roll,pitch:e.pitch,bearing:e.bearing},s={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},n=void 0!==i.zoom,l=!e.isPaddingEqual(i.padding);let c=!1;const h=n?+i.zoom:e.zoom;let u=e.centerPoint.add(i.offsetAsPoint);const d=e.screenPointToLocation(u),{center:_,zoom:p}=e.getConstrained(t.S.convert(i.center||d),null!=h?h:o);St(e,_);const m=le(e.worldSize,d),f=le(e.worldSize,_).sub(m),g=t.af(p-o);return c=p!==o,{easeFunc:n=>{if(c&&e.setZoom(t.C.number(o,p,n)),t.be(a,s)||Ft({startEulerAngles:a,endEulerAngles:s,tr:e,k:n,useSlerp:a.roll!=s.roll}),l&&(e.interpolatePadding(r,i.padding,n),u=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const i=t.af(e.zoom-o),r=p>o?Math.min(2,g):Math.max(.5,g),a=Math.pow(r,1-n),s=ce(e.worldSize,m.add(f.mult(n*a)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?s.wrap():s,u);}},isZooming:c,elevationCenter:_}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.zoom,a=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),o?+i.zoom:r),s=a.center,n=a.zoom;St(e,s);const l=le(e.worldSize,i.locationAtOffset),c=le(e.worldSize,s).sub(l),h=c.mag(),u=t.af(n-r);let d;if(void 0!==i.minZoom){const o=Math.min(+i.minZoom,r,n),a=e.getConstrained(s,o).zoom;d=t.af(a-r);}return {easeFunc:(i,o,a,h)=>{e.setZoom(1===i?n:r+t.ak(o));const u=1===i?s:ce(e.worldSize,l.add(c.mult(a)).mult(o));e.setLocationAtPoint(e.renderWorldCopies?u.wrap():u,h);},scaleOfZoom:u,targetCenter:s,scaleOfMinZoom:d,pixelPathLength:h}}}class jt{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}jt.Replace=[1,0],jt.disabled=new jt(jt.Replace,t.bf.transparent,[!1,!1,!1,!1]),jt.unblended=new jt(jt.Replace,t.bf.transparent,[!0,!0,!0,!0]),jt.alphaBlended=new jt([1,771],t.bf.transparent,[!0,!0,!0,!0]);const Nt=2305;class Ut{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}Ut.disabled=new Ut(!1,1029,Nt),Ut.backCCW=new Ut(!0,1029,Nt),Ut.frontCCW=new Ut(!0,1028,Nt);class Zt{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Zt.ReadOnly=!1,Zt.ReadWrite=!0,Zt.disabled=new Zt(519,Zt.ReadOnly,[0,1]);const Gt=7680;class Vt{constructor(e,t,i,o,r,a){this.test=e,this.ref=t,this.mask=i,this.fail=o,this.depthFail=r,this.pass=a;}}Vt.disabled=new Vt({func:519,mask:0},0,0,Gt,Gt,Gt);const $t=new WeakMap;function qt(e){var t;if($t.has(e))return $t.get(e);{const i=null===(t=e.getParameter(e.VERSION))||void 0===t?void 0:t.startsWith("WebGL 2.0");return $t.set(e,i),i}}class Wt{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,o=i.gl;this._texFormat=o.RGBA,this._texType=o.UNSIGNED_BYTE;const r=new t.aL;r.emplaceBack(-1,-1),r.emplaceBack(2,-1),r.emplaceBack(-1,2);const a=new t.aN;a.emplaceBack(0,1,2),this._fullscreenTriangle=new wt(i.createVertexBuffer(r,Tt.members),i.createIndexBuffer(a),t.aM.simpleSegment(0,0,r.length,a.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(o.TEXTURE1);const s=o.createTexture();o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texImage2D(o.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(s),qt(o)&&(this._pbo=o.createBuffer(),o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.bufferData(o.PIXEL_PACK_BUFFER,4,o.STREAM_READ),o.bindBuffer(o.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const o=this._cachedRenderContext.context,r=o.gl;if(this._bindFramebuffer(),o.viewport.set([0,0,this._texWidth,this._texHeight]),o.clear({color:t.bf.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(o,r.TRIANGLES,Zt.disabled,Vt.disabled,jt.unblended,Ut.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&qt(r)){r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.readBuffer(r.COLOR_ATTACHMENT0),r.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),r.bindBuffer(r.PIXEL_PACK_BUFFER,null);const e=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);r.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&qt(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=Wt._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const Ht=t.$/128;function Xt(e,i){const o=void 0!==e.granularity?Math.max(e.granularity,1):1,r=o+(e.generateBorders?2:0),a=o+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),s=r+1,n=a+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=o+(e.generateBorders?1:0),u=o+(e.generateBorders||e.extendToSouthPole?1:0),d=s*n,_=r*a*6,p=s*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g=0;for(let i=c;i<=u;i++)for(let r=l;r<=h;r++){let a=r/o*t.$;-1===r&&(a=-Ht),r===o+1&&(a=t.$+Ht);let s=i/o*t.$;-1===i&&(s=e.extendToNorthPole?t.bh:-Ht),i===o+1&&(s=e.extendToSouthPole?t.bi:t.$+Ht),f[g++]=a,f[g++]=s;}const v=m?new Uint32Array(_):new Uint16Array(_);let b=0;for(let e=0;e0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return "globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy();}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e);}getMeshFromTileID(e,t,i,o,r){return this.currentProjection.getMeshFromTileID(e,t,i,o,r)}setProjection(e){this._transitionable.setValue("type",(null==e?void 0:e.type)||"mercator");}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e);}}function ei(e){const t=oi(e.worldSize,e.center.lat);return 2*Math.PI*t}function ti(e,i,o,r,a){const s=1/(1<1e-6){const r=e[0]/o,a=Math.acos(e[2]/o),s=(r>0?a:-a)/Math.PI*180;return new t.S(t.aO(s,-180,180),i)}return new t.S(0,i)}function ai(e){return Math.cos(e*Math.PI/180)}function si(e,i){const o=ai(e),r=ai(i);return t.ak(r/o)}function ni(e,i){const o=e.rotate(i.bearingInRadians),r=i.zoom+si(i.center.lat,0),a=t.bk(1/ai(i.center.lat),1/ai(Math.min(Math.abs(i.center.lat),60)),t.bn(r,7,3,0,1)),s=360/ei({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.S(i.center.lng-o.x*s*a,t.ah(i.center.lat+o.y*s,-t.ai,t.ai))}function li(e){const t=.5*e,i=Math.sin(t),o=Math.cos(t);return Math.log(i+o)-Math.log(o-i)}function ci(e,i,o,r){const a=e.lat+o*r;if(Math.abs(o)>1){const s=(Math.sign(e.lat+o)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+o)*Math.PI/180,l=li(s+r*(n-s)),c=li(s),h=li(n);return new t.S(e.lng+i*((l-c)/(h-c)),a)}return new t.S(e.lng+i*r,a)}class hi{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._boundingVolumeFactory=e;}swapBuffers(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1;}getTileBoundingVolume(e,t,i,o){const r=`${e.z}_${e.x}_${e.y}_${(null==o?void 0:o.terrain)?"t":""}`,a=this._cache.get(r);if(a)return a;const s=this._cachePrevious.get(r);if(s)return this._cache.set(r,s),s;const n=this._boundingVolumeFactory(e,t,i,o);return this._cache.set(r,n),this._hadAnyChanges=!0,n}}class ui{constructor(e,t,i,o){this.min=i,this.max=o,this.points=e,this.planes=t;}static fromAabb(e,t){const i=[];for(let o=0;o<8;o++)i.push([1&~o?e[0]:t[0],1==(o>>1&1)?t[1]:e[1],1==(o>>2&1)?t[2]:e[2]]);return new ui(i,[[-1,0,0,t[0]],[1,0,0,-e[0]],[0,-1,0,t[1]],[0,1,0,-e[1]],[0,0,-1,t[2]],[0,0,1,-e[2]]],e,t)}static fromCenterSizeAngles(e,i,o){const r=t.br([],o[0],o[1],o[2]),a=t.bs([],[i[0],0,0],r),s=t.bs([],[0,i[1],0],r),n=t.bs([],[0,0,i[2]],r),l=[...e],c=[...e];for(let t=0;t<8;t++)for(let i=0;i<3;i++){const o=e[i]+a[i]*(1&~t?-1:1)+s[i]*(1==(t>>1&1)?1:-1)+n[i]*(1==(t>>2&1)?1:-1);l[i]=Math.min(l[i],o),c[i]=Math.max(c[i],o);}const h=[];for(let i=0;i<8;i++){const o=[...e];t.aS(o,o,t.aR([],a,1&~i?-1:1)),t.aS(o,o,t.aR([],s,1==(i>>1&1)?1:-1)),t.aS(o,o,t.aR([],n,1==(i>>2&1)?1:-1)),h.push(o);}return new ui(h,[[...a,-t.aX(a,h[0])],[...s,-t.aX(s,h[0])],[...n,-t.aX(n,h[0])],[-a[0],-a[1],-a[2],-t.aX(a,h[7])],[-s[0],-s[1],-s[2],-t.aX(s,h[7])],[-n[0],-n[1],-n[2],-t.aX(n,h[7])]],l,c)}intersectsFrustum(e){let t=!0;const i=this.points.length,o=this.planes.length,r=e.planes.length,a=e.points.length;for(let o=0;o=0&&a++;}if(0===a)return 0;a=0&&o++;}if(0===o)return 0}return 1}intersectsPlane(e){const t=this.points.length;let i=0;for(let o=0;o=0&&i++;}return i===t?2:0===i?0:1}}function di(e,t,i){const o=e-t;return o<0?-o:Math.max(0,o-i)}function _i(e,t,i,o,r){const a=e-i;let s;return s=a<0?Math.min(-a,1+a-r):a>1?Math.min(Math.max(a-r,0),1-a):0,Math.max(s,di(t,o,r))}class pi{constructor(){this._boundingVolumeCache=new hi(this._computeTileBoundingVolume);}prepareNextFrame(){this._boundingVolumeCache.swapBuffers();}distanceToTile2d(e,t,i,o){const r=1<4}allowWorldCopies(){return !1}getTileBoundingVolume(e,t,i,o){return this._boundingVolumeCache.getTileBoundingVolume(e,t,i,o)}_computeTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}if(n/=t.bu,l/=t.bu,n+=1,l+=1,e.z<=0)return ui.fromAabb([-l,-l,-l],[l,l,l]);if(1===e.z)return ui.fromAabb([0===e.x?-l:0,0===e.y?0:-l,-l],[0===e.x?0:l,0===e.y?l:0,l]);{const i=[ti(0,0,e.x,e.y,e.z),ti(t.$,0,e.x,e.y,e.z),ti(t.$,t.$,e.x,e.y,e.z),ti(0,t.$,e.x,e.y,e.z)],o=[];for(const e of i)o.push(t.aR([],e,l));if(l!==n)for(const e of i)o.push(t.aR([],e,n));0===e.y&&o.push([0,1,0]),e.y===(1<=(1<{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._coveringTilesDetailsProvider=new pi;}clone(){const e=new fi;return e.apply(this),e}apply(e,t){this._globeLatitudeErrorCorrectionRadians=t||0,this._helper.apply(e);}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const e=t.bp();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(e){const{overscaledTileID:t,applyGlobeMatrix:i}=e,o=this._helper.getMercatorTileCoordinates(t);return {mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:o,clippingPlane:this._cachedClippingPlane,projectionTransition:i?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(e){const i=this.pitchInRadians,o=this.cameraToCenterDistance/e,r=Math.sin(i)*o,a=Math.cos(i)*o+1,s=1/Math.sqrt(r*r+a*a)*1;let n=-r,l=a;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];t.bw(h,h,[0,0,0],-this.bearingInRadians),t.bx(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.by(h,h,[0,0,0],this.center.lng*Math.PI/180);const u=1/t.aZ(h);return t.aR(h,h,u),[...h,-s*u]}isLocationOccluded(e){return !this.isSurfacePointVisible(ii(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,o=this._helper._center.lat*Math.PI/180,r=Math.cos(o),a=[Math.sin(i)*r,Math.sin(o),Math.cos(i)*r],s=[a[2],0,-a[0]],n=[0,0,0];t.aW(n,s,a),t.aV(s,s),t.aV(n,n);const l=[0,0,0];return t.aV(l,[s[0]*e[0]+n[0]*e[1]+a[0]*e[2],s[1]*e[0]+n[1]*e[1]+a[1]*e[2],s[2]*e[0]+n[2]*e[1]+a[2]*e[2]]),l}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(e,i,o){const r=function(e,i,o){const r=1/(1<a&&(a=i),on&&(n=o);}const h=[c.lng+s,c.lat+l,c.lng+a,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new G(h)}getConstrained(e,i){const o=t.ah(e.lat,-t.ai,t.ai),r=t.ah(+i,this.minZoom+si(0,o),this.maxZoom);return {center:new t.S(e.lng,o),zoom:r}}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,i){const o=ii(this.unprojectScreenPoint(i)),r=ii(e),a=t.bp();t.bB(a);const s=t.bp();t.by(s,o,a,-this.center.lng*Math.PI/180),t.bx(s,s,a,this.center.lat*Math.PI/180);const n=r[0]*r[0]+r[2]*r[2],l=s[0]*s[0];if(n=-g&&p<=g,b=f>=-g&&f<=g;let x,y;if(v&&b){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.bD(u,e)+t.bD(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return !1;const i=t.bv();return t.aw(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const o=t.aX(e,i),r=t.bp(),a=t.bp();t.aR(a,i,o),t.aU(r,e,a);const s=1-t.aX(r,r);if(s<0)return null;const n=t.aX(e,e)-1,l=-o+(o<0?1:-1)*Math.sqrt(s),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,o=this.getRayDirectionFromPixel(e),r=this.rayPlanetIntersection(i,o);if(r){const e=t.bp();t.aS(e,i,[o[0]*r.tMin,o[1]*r.tMin,o[2]*r.tMin]);const a=t.bp();return t.aV(a,e),ri(a)}const a=this._cachedClippingPlane,s=a[0]*o[0]+a[1]*o[1]+a[2]*o[2],n=-t.b1(a,i)/s,l=t.bp();if(n>0)t.aS(l,i,[o[0]*n,o[1]*n,o[2]*n]);else {const e=t.bp();t.aS(e,i,[2*o[0],2*o[1],2*o[2]]);const r=t.b1(this._cachedClippingPlane,e);t.aU(l,e,[this._cachedClippingPlane[0]*r,this._cachedClippingPlane[1]*r,this._cachedClippingPlane[2]*r]);}const c=function(e){const i=t.bp();return i[0]=e[0]*-e[3],i[1]=e[1]*-e[3],i[2]=e[2]*-e[3],{center:i,radius:Math.sqrt(1-e[3]*e[3])}}(a);return ri(function(e,i,o){const r=t.bp();t.aU(r,o,e);const a=t.bp();return t.bq(a,e,r,i/t.a$(r)),a}(c.center,c.radius,l))}getMatrixForModel(e,i){const o=t.S.convert(e),r=1/t.bu,a=t.b9();return t.bz(a,a,o.lng/180*Math.PI),t.b7(a,a,-o.lat/180*Math.PI),t.M(a,a,[0,0,1+i/t.bu]),t.b7(a,a,.5*Math.PI),t.N(a,a,[r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=this.getProjectionData({overscaledTileID:new t.Z(0,0,0,0,0),applyGlobeMatrix:e});return i.tileMercatorCoords=[0,0,1,1],i}getFastPathSimpleProjectionMatrix(e){}}class gi{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame(),this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame();}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._globeness=1,this._mercatorTransform=new Lt,this._verticalPerspectiveTransform=new fi;}clone(){const e=new gi;return e._globeness=this._globeness,e._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,e.apply(this),e}apply(e){this._helper.apply(e),this._mercatorTransform.apply(this),this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians);}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){const t=this._mercatorTransform.getProjectionData(e),i=this._verticalPerspectiveTransform.getProjectionData(e);return {mainMatrix:this.isGlobeRendering?i.mainMatrix:t.mainMatrix,clippingPlane:i.clippingPlane,tileMercatorCoords:i.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return t.bk(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return t.bk(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,i,o){const r=this._mercatorTransform.getPitchedTextCorrection(e,i,o),a=this._verticalPerspectiveTransform.getPitchedTextCorrection(e,i,o);return t.bk(r,a,this._globeness)}projectTileCoordinates(e,t,i,o){return this.currentTransform.projectTileCoordinates(e,t,i,o)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ);}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this._mercatorTransform.recalculateZoomAndCenter(e),this._verticalPerspectiveTransform.recalculateZoomAndCenter(e);}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e);}getBounds(){return this.currentTransform.getBounds()}getConstrained(e,t){return this.currentTransform.getConstrained(e,t)}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,t){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,t),void this.apply(this._mercatorTransform);this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform);}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getMatrixForModel(e,t){return this.currentTransform.getMatrixForModel(e,t)}getProjectionDataForCustomLayer(e=!0){const t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;const i=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return i.fallbackMatrix=t.mainMatrix,i}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}}class vi{get useGlobeControls(){return !0}handlePanInertia(e,i){const o=ni(e,i);return Math.abs(o.lng-i.center.lng)>180&&(o.lng=i.center.lng+179.5*Math.sign(o.lng-i.center.lng)),{easingCenter:o,easingOffset:new t.P(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){const o=e.around,r=i.screenPointToLocation(o);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const a=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const s=i.zoom-a;if(0===s)return;const n=t.bA(i.center.lng,r.lng),l=n/(Math.abs(n/180)+1),c=t.bA(i.center.lat,r.lat),h=i.getRayDirectionFromPixel(o),u=i.cameraPosition,d=-1*t.aX(u,h),_=t.bp();t.aS(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.aZ(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=oi(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.bn(f,.9,.5,1,.25),v=(1-t.af(-s))*Math.min(m,g),b=i.center.lat,x=i.zoom,y=new t.S(i.center.lng+l*v,t.ah(i.center.lat+c*v,-t.ai,t.ai));i.setLocationAtPoint(r,o);const w=i.center,T=t.bn(Math.abs(n),45,85,0,1),P=t.bn(f,.75,.35,0,1),C=Math.pow(Math.max(T,P),.25),I=t.bA(w.lng,y.lng),M=t.bA(w.lat,y.lat);i.setCenter(new t.S(w.lng+I*C,w.lat+M*C).wrap()),i.setZoom(x+si(b,i.center.lat));}handleMapControlsPan(e,t,i){if(!e.panDelta)return;const o=t.center.lat,r=t.zoom;t.setCenter(ni(e.panDelta,t).wrap()),t.setZoom(r+si(o,t.center.lat));}cameraForBoxAndBearing(e,i,o,r,a){const s=Bt(e,i,o,r,a),n=i.left/a.width*2-1,l=(a.width-i.right)/a.width*2-1,c=i.top/a.height*-2+1,h=(a.height-i.bottom)/a.height*-2+1,u=t.bA(o.getWest(),o.getEast())<0,d=u?o.getEast():o.getWest(),_=u?o.getWest():o.getEast(),p=Math.max(o.getNorth(),o.getSouth()),m=Math.min(o.getNorth(),o.getSouth()),f=d+.5*t.bA(d,_),g=p+.5*t.bA(p,m),v=a.clone();v.setCenter(s.center),v.setBearing(s.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(s.zoom);const b=v.modelViewProjectionMatrix,x=[ii(o.getNorthWest()),ii(o.getNorthEast()),ii(o.getSouthWest()),ii(o.getSouthEast()),ii(new t.S(_,g)),ii(new t.S(d,g)),ii(new t.S(f,p)),ii(new t.S(f,m))],y=ii(s.center);let w=Number.POSITIVE_INFINITY;for(const e of x)n<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",n))),l>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",l))),c>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",c))),h<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",h)));if(Number.isFinite(w)&&0!==w)return s.zoom=v.zoom+t.ak(w),s;kt();}handleJumpToCenterZoom(e,i){const o=e.center.lat,r=e.getConstrained(i.center?t.S.convert(i.center):e.center,e.zoom).center;e.setCenter(r.wrap());const a=void 0!==i.zoom?+i.zoom:e.zoom+si(o,r.lat);e.zoom!==a&&e.setZoom(a);}handleEaseTo(e,i){const o=e.zoom,r=e.center,a=e.padding,s={roll:e.roll,pitch:e.pitch,bearing:e.bearing},n={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},l=void 0!==i.zoom,c=!e.isPaddingEqual(i.padding);let h=!1;const u=i.center?t.S.convert(i.center):r,d=e.getConstrained(u,o).center;St(e,d);const _=e.clone();_.setCenter(d),_.setZoom(l?+i.zoom:o+si(r.lat,u.lat)),_.setBearing(i.bearing);const p=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));_.setLocationAtPoint(d,p);const m=(i.offset&&i.offsetAsPoint.mag())>0?_.center:d,f=l?+i.zoom:o+si(r.lat,m.lat),g=o+si(r.lat,0),v=f+si(m.lat,0),b=t.bA(r.lng,m.lng),x=t.bA(r.lat,m.lat),y=t.af(v-g);return h=f!==o,{easeFunc:o=>{if(t.be(s,n)||Ft({startEulerAngles:s,endEulerAngles:n,tr:e,k:o,useSlerp:s.roll!=n.roll}),c&&e.interpolatePadding(a,i.padding,o),i.around)t.w("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=v>g?Math.min(2,y):Math.max(.5,y),i=Math.pow(t,1-o),a=ci(r,b,x,o*i);e.setCenter(a.wrap());}if(h){const i=t.C.number(g,v,o)+si(0,e.center.lat);e.setZoom(i);}},isZooming:h,elevationCenter:m}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.center,a=e.zoom,s=e.padding,n=!e.isPaddingEqual(i.padding),l=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),a).center,c=o?+i.zoom:e.zoom+si(e.center.lat,l.lat),h=e.clone();h.setCenter(l),h.setZoom(c),h.setBearing(i.bearing);const u=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));h.setLocationAtPoint(l,u);const d=h.center;St(e,d);const _=function(e,i,o){const r=ii(i),a=ii(o),s=t.aX(r,a),n=Math.acos(s),l=ei(e);return n/(2*Math.PI)*l}(e,r,d),p=a+si(r.lat,0),m=c+si(d.lat,0),f=t.af(m-p);let g;if("number"==typeof i.minZoom){const o=+i.minZoom+si(d.lat,0),r=Math.min(o,p,m)+si(0,d.lat),a=e.getConstrained(d,r).zoom+si(d.lat,0);g=t.af(a-p);}const v=t.bA(r.lng,d.lng),b=t.bA(r.lat,d.lat);return {easeFunc:(o,a,l,h)=>{const u=ci(r,v,b,l);n&&e.interpolatePadding(s,i.padding,o);const _=1===o?d:u;e.setCenter(_.wrap());const m=p+t.ak(a);e.setZoom(1===o?c:m+si(0,_.lat));},scaleOfZoom:f,targetCenter:d,scaleOfMinZoom:g,pixelPathLength:_}}static solveVectorScale(e,t,i,o,r){const a="x"===o?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],s=[i[3],i[7],i[11],i[15]],n=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],l=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],c=t[0]*a[0]+t[1]*a[1]+t[2]*a[2],h=t[0]*s[0]+t[1]*s[1]+t[2]*s[2];return c+r*l===n+r*h||s[3]*(n-c)+a[3]*(h-l)+n*h==c*l?null:(c+a[3]-r*h-r*s[3])/(c-n-r*h+r*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.y(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),yi=t.bE();class wi extends t.E{constructor(e,i={}){var o,r;super(),this._rtlPluginLoaded=()=>{for(const e in this.sourceCaches){const t=this.sourceCaches[e].getSource().type;"vector"!==t&&"geojson"!==t||this.sourceCaches[e].reload();}},this.map=e,this.dispatcher=new F(k(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.imageManager=new b,this.imageManager.setEventedParent(this);const a=(null===(o=e._container)||void 0===o?void 0:o.lang)||"undefined"!=typeof document&&(null===(r=document.documentElement)||void 0===r?void 0:r.lang)||void 0;this.glyphManager=new T(e._requestManager,i.localIdeographFontFamily,a),this.lineAtlas=new E(256,512),this.crossTileSymbolIndex=new vt,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.bF,this._loaded=!1,this._availableImages=[],this._globalState={},this._resetUpdates(),this.dispatcher.broadcast("SR",t.bG()),oe().on(ee,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.sourceCaches[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}setGlobalStateProperty(e,i){var o,r,a;this._checkLoaded();const s=null===i?null!==(a=null===(r=null===(o=this.stylesheet.state)||void 0===o?void 0:o[e])||void 0===r?void 0:r.default)&&void 0!==a?a:null:i;if(t.bH(s,this._globalState[e]))return this;this._globalState[e]=s,this._applyGlobalStateChanges([e]);}getGlobalState(){return this._globalState}setGlobalState(e){this._checkLoaded();const i=[];for(const o in e)!t.bH(this._globalState[o],e[o].default)&&(i.push(o),this._globalState[o]=e[o].default);this._applyGlobalStateChanges(i);}_applyGlobalStateChanges(e){if(0===e.length)return;const t=new Set,i={};for(const o of e){i[o]=this._globalState[o];for(const e in this._layers){const i=this._layers[e],r=i.getLayoutAffectingGlobalStateRefs(),a=i.getPaintAffectingGlobalStateRefs();if(r.has(o)&&t.add(i.source),a.has(o))for(const{name:e,value:t}of a.get(o))this._updatePaintProperty(i,e,t);}}this.dispatcher.broadcast("UGS",i);for(const e in this.sourceCaches)t.has(e)&&(this._reloadSource(e),this._changed=!0);}loadURL(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const r=this.map._requestManager.transformRequest(e,"Style");this._loadStyleRequest=new AbortController;const a=this._loadStyleRequest;t.j(r,this._loadStyleRequest).then((e=>{this._loadStyleRequest=null,this._load(e.data,i,o);})).catch((e=>{this._loadStyleRequest=null,e&&!a.signal.aborted&&this.fire(new t.k(e));}));}loadJSON(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,s.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=!1!==i.validate,this._load(e,i,o);})).catch((()=>{}));}loadEmpty(){this.fire(new t.l("dataloading",{dataType:"style"})),this._load(yi,{validate:!1});}_load(e,i,o){var r,a;let s=i.transformStyle?i.transformStyle(o,e):e;if(!i.validate||!xi(this,t.z(s))){s=Object.assign({},s),this._loaded=!0,this.stylesheet=s;for(const e in s.sources)this.addSource(e,s.sources[e],{validate:!1});s.sprite?this._loadSprite(s.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(s.glyphs),this._createLayers(),this.light=new I(this.stylesheet.light),this._setProjectionInternal((null===(r=this.stylesheet.projection)||void 0===r?void 0:r.type)||"mercator"),this.sky=new S(this.stylesheet.sky),this.map.setTerrain(null!==(a=this.stylesheet.terrain)&&void 0!==a?a:null),this.fire(new t.l("data",{dataType:"style"})),this.fire(new t.l("style.load"));}}_createLayers(){var e;const i=t.bI(this.stylesheet.layers);this.setGlobalState(null!==(e=this.stylesheet.state)&&void 0!==e?e:null),this.dispatcher.broadcast("SL",i),this._order=i.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const e of i){const i=t.bJ(e,this._globalState);i.setEventedParent(this,{layer:{id:e.id}}),this._layers[e.id]=i;}}_loadSprite(e,i=!1,o=void 0){let r;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=f(e),n=o>1?"@2x":"",l={},c={};for(const{id:e,url:o}of a){const a=i.transformRequest(g(o,n,".json"),"SpriteJSON");l[e]=t.j(a,r);const s=i.transformRequest(g(o,n,".png"),"SpriteImage");c[e]=p.getImage(s,r);}return yield Promise.all([...Object.values(l),...Object.values(c)]),function(e,i){return t._(this,void 0,void 0,(function*(){const t={};for(const o in e){t[o]={};const r=s.getImageCanvasContext((yield i[o]).data),a=(yield e[o]).data;for(const e in a){const{width:i,height:s,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=a[e];t[o][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:s,x:n,y:l,context:r}};}}return t}))}(l,c)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const o=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of o)this.imageManager.removeImage(e),this._changedImages[e]=!0;for(const o in e[t]){const r="default"===t?o:`${t}:${o}`;this._spritesImagesIds[t].push(r),r in this.imageManager.images?this.imageManager.updateImage(r,e[t][o],!1):this.imageManager.addImage(r,e[t][o]),i&&(this._changedImages[r]=!0);}}})).catch((e=>{this._spriteRequest=null,r=e,this.fire(new t.k(r));})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),i&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"})),o&&o(r);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}_validateLayer(e){const i=this.sourceCaches[e.source];if(!i)return;const o=e.sourceLayer;if(!o)return;const r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.k(new Error(`Source layer "${o}" does not exist on source "${r.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(const e in this.sourceCaches)if(!this.sourceCaches[e].loaded())return !1;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=!1){const o=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.bK(o):o);const r=[];for(const a of e)if(o[a]){const e=i?t.bK(o[a]):o[a];r.push(e);}return r}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){var e,t,i;if(null===(e=this.light)||void 0===e?void 0:e.hasTransition())return !0;if(null===(t=this.sky)||void 0===t?void 0:t.hasTransition())return !0;if(null===(i=this.projection)||void 0===i?void 0:i.hasTransition())return !0;for(const e in this.sourceCaches)if(this.sourceCaches[e].hasTransition())return !0;for(const e in this._layers)if(this._layers[e].hasTransition())return !0;return !1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const o={};for(const e in this.sourceCaches){const t=this.sourceCaches[e];o[e]=t.used,t.used=!1;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.sourceCaches[i.source].used=!0);}for(const e in o){const i=this.sourceCaches[e];!!o[e]!=!!i.used&&i.fire(new t.l("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.projection.recalculate(e),this.z=e.zoom,i&&this.fire(new t.l("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,!1),removedIds:t});}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1;}setState(e,i={}){var o;this._checkLoaded();const r=this.serialize();if(e=i.transformStyle?i.transformStyle(r,e):e,(null===(o=i.validate)||void 0===o||o)&&xi(this,t.z(e)))return !1;(e=t.bK(e)).layers=t.bI(e.layers);const a=t.bL(r,e),s=this._getOperationsToPerform(a);if(s.unimplemented.length>0)throw new Error(`Unimplemented: ${s.unimplemented.join(", ")}.`);if(0===s.operations.length)return !1;for(const e of s.operations)e();return this.stylesheet=e,this._serializedLayers=null,!0}_getOperationsToPerform(e){const t=[],i=[];for(const o of e)switch(o.command){case "setCenter":case "setZoom":case "setBearing":case "setPitch":case "setRoll":continue;case "addLayer":t.push((()=>this.addLayer.apply(this,o.args)));break;case "removeLayer":t.push((()=>this.removeLayer.apply(this,o.args)));break;case "setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,o.args)));break;case "setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,o.args)));break;case "setFilter":t.push((()=>this.setFilter.apply(this,o.args)));break;case "addSource":t.push((()=>this.addSource.apply(this,o.args)));break;case "removeSource":t.push((()=>this.removeSource.apply(this,o.args)));break;case "setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,o.args)));break;case "setLight":t.push((()=>this.setLight.apply(this,o.args)));break;case "setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,o.args)));break;case "setGlyphs":t.push((()=>this.setGlyphs.apply(this,o.args)));break;case "setSprite":t.push((()=>this.setSprite.apply(this,o.args)));break;case "setTerrain":t.push((()=>this.map.setTerrain.apply(this,o.args)));break;case "setSky":t.push((()=>this.setSky.apply(this,o.args)));break;case "setProjection":this.setProjection.apply(this,o.args);break;case "setGlobalState":t.push((()=>this.setGlobalState.apply(this,o.args)));break;case "setTransition":t.push((()=>{}));break;default:i.push(o.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,o={}){if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.z.source,`sources.${e}`,i,null,o))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const r=this.sourceCaches[e]=new xe(e,i,this.dispatcher);r.style=this,r.setEventedParent(this,(()=>({isSourceLoaded:r.loaded(),source:r.serialize(),sourceId:e}))),r.onAdd(this.map),this._changed=!0;}removeSource(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.k(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],i.fire(new t.l("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=!0;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error(`There is no source with this ID=${e}`);const i=this.sourceCaches[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=!0;}getSource(e){return this.sourceCaches[e]&&this.sourceCaches[e].getSource()}addLayer(e,i,o={}){this._checkLoaded();const r=e.id;if(this.getLayer(r))return void this.fire(new t.k(new Error(`Layer "${r}" already exists on this map.`)));let a;if("custom"===e.type){if(xi(this,t.bM(e)))return;a=t.bJ(e,this._globalState);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(r,e.source),e=t.bK(e),e=t.e(e,{source:r})),this._validate(t.z.layer,`layers.${r}`,e,{arrayIndex:-1},o))return;a=t.bJ(e,this._globalState),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}});}const s=i?this._order.indexOf(i):this._order.length;if(i&&-1===s)this.fire(new t.k(new Error(`Cannot add layer "${r}" before non-existing layer "${i}".`)));else {if(this._order.splice(s,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){const e=this._removedLayers[r];delete this._removedLayers[r],e.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=!0,!this._layers[e])return void this.fire(new t.k(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const o=this._order.indexOf(e);this._order.splice(o,1);const r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.k(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.k(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,o){this._checkLoaded();const r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.k(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,o={}){this._checkLoaded();const r=this.getLayer(e);if(r){if(!t.bH(r.filter,i))return null==i?(r.setFilter(void 0),void this._updateLayer(r)):void(this._validate(t.z.filter,`layers.${r.id}.filter`,i,null,o)||(r.setFilter(t.bK(i)),this._updateLayer(r)))}else this.fire(new t.k(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.bK(this.getLayer(e).filter)}setLayoutProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.k(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getPaintProperty(i),o)||this._updatePaintProperty(a,i,o,r):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}_updatePaintProperty(e,t,i,o={}){e.setPaintProperty(t,i,o)&&this._updateLayer(e),this._changed=!0,this._updatedPaintProps[e.id]=!0,this._serializedLayers=null;}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0===a)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const s=a.getSource().type;"geojson"===s&&r?this.fire(new t.k(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==s||r?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const o=e.source,r=this.sourceCaches[o];if(void 0===r)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const a=r.getSource().type,s="vector"===a?e.sourceLayer:void 0;"vector"!==a||s?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.k(new Error("A feature id is required to remove its specific state property."))):r.removeFeatureState(s,e.id,i):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r)return "vector"!==r.getSource().type||o?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id)):void this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.k(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.bN(this.sourceCaches,(e=>e.serialize())),i=this._serializeByIds(this._order,!0),o=this.map.getTerrain()||void 0,r=this.stylesheet;return t.bO({version:r.version,name:r.name,metadata:r.metadata,light:r.light,sky:r.sky,center:r.center,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,sprite:r.sprite,glyphs:r.glyphs,transition:r.transition,projection:r.projection,sources:e,layers:i,terrain:o},(e=>void 0!==e))}_updateLayer(e){this._updatedLayers[e.id]=!0,e.source&&!this._updatedSources[e.source]&&"raster"!==this.sourceCaches[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.sourceCaches[e.source].pause()),this._serializedLayers=null,this._changed=!0;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},o=[];for(let r=this._order.length-1;r>=0;r--){const a=this._order[r];if(t(a)){i[a]=r;for(const t of e){const e=t[a];if(e)for(const t of e)o.push(t);}}}o.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const r=[];for(let a=this._order.length-1;a>=0;a--){const s=this._order[a];if(t(s))for(let e=o.length-1;e>=0;e--){const t=o[e].feature;if(i[t.layer.id]this.map.terrain.getElevation(e,t,i):void 0));return this.placement&&a.push(function(e,t,i,o,r,a,s){const n={},l=a.queryRenderedSymbols(o),c=[];for(const e of Object.keys(l).map(Number))c.push(s[e]);c.sort(N);for(const i of c){const o=i.featureIndex.lookupSymbolFeatures(l[i.bucketInstanceId],t,i.bucketIndex,i.sourceLayerIndex,{filterSpec:r.filter,globalState:r.globalState},r.layers,r.availableImages,e);for(const e in o){const t=n[e]=n[e]||[],r=o[e];r.sort(((e,t)=>{const o=i.featureSortOrder;if(o){const i=o.indexOf(e.featureIndex);return o.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of r)t.push(e);}}return function(e,t,i){for(const o in e)for(const r of e[o])U(r,i[t[o].source]);return e}(n,e,i)}(this._layers,s,this.sourceCaches,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(a)}querySourceFeatures(e,i){(null==i?void 0:i.filter)&&this._validate(t.z.filter,"querySourceFeatures.filter",i.filter,null,i);const o=this.sourceCaches[e];return o?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),o=[],r={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const o=this.crossTileSymbolIndex.addLayer(i,l[i.source],e.center.lng);a=a||o;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((r=r||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(s.now(),e.zoom))&&(this.pauseablePlacement=new _t(e,this.map.terrain,this._order,r,t,i,o,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(s.now()),n=!0),a&&this.pauseablePlacement.placement.setStale()),n||a)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,l[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(s.now())}_releaseSymbolFadeTiles(){for(const e in this.sourceCaches)this.sourceCaches[e].releaseSymbolFadeTiles();}getImages(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.z.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}addSprite(e,i,o={},r){this._checkLoaded();const a=[{id:e,url:i}],s=[...f(this.stylesheet.sprite),...a];this._validate(t.z.sprite,"sprite",s,null,o)||(this.stylesheet.sprite=s,this._loadSprite(a,!0,r));}removeSprite(e){this._checkLoaded();const i=f(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=!0;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:void 0,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}else this.fire(new t.k(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return f(this.stylesheet.sprite)}setSprite(e,i={},o){this._checkLoaded(),e&&this._validate(t.z.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,!0,o):(this._unloadSprite(),o&&o(null)));}}var Ti=t.aJ([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class Pi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;}bind(e,t,i,o,r,a,s,n,l){this.context=e;let c=this.boundPaintVertexBuffers.length!==o.length;for(let e=0;!c&&e({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:o?o.properties.get("fog-color"):t.bf.white,u_fog_ground_blend:o?o.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:a?0:o?o.calculateFogBlendOpacity(r):0,u_horizon_color:o?o.properties.get("horizon-color"):t.bf.white,u_horizon_fog_blend:o?o.properties.get("horizon-fog-blend"):1,u_is_globe_mode:a?1:0}),Ii={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function Mi(e){const t=[];for(let i=0;i({u_depth:new t.bP(e,i.u_depth),u_terrain:new t.bP(e,i.u_terrain),u_terrain_dim:new t.bg(e,i.u_terrain_dim),u_terrain_matrix:new t.bR(e,i.u_terrain_matrix),u_terrain_unpack:new t.bS(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.bg(e,i.u_terrain_exaggeration)}))(e,C),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.bR(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.bS(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.bS(e,i.u_projection_clipping_plane),u_projection_transition:new t.bg(e,i.u_projection_transition),u_projection_fallback_matrix:new t.bR(e,i.u_projection_fallback_matrix)}))(e,C),this.binderUniforms=o?o.getUniforms(e,C):[];}draw(e,t,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v){const b=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(o),e.setColorMode(r),e.setCullFace(a),n){e.activeTexture.set(b.TEXTURE2),b.bindTexture(b.TEXTURE_2D,n.depthTexture),e.activeTexture.set(b.TEXTURE3),b.bindTexture(b.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[Ii[e]].set(l[e]);if(s)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(s[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let x=0;switch(t){case b.LINES:x=2;break;case b.TRIANGLES:x=3;break;case b.LINE_STRIP:x=1;}for(const i of d.get()){const o=i.vaos||(i.vaos={});(o[c]||(o[c]=new Pi)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),b.drawElements(t,i.primitiveLength*x,b.UNSIGNED_SHORT,i.primitiveOffset*x*2);}}}function Ei(e,i,o){const r=1/t.aC(o,1,i.transform.tileZoom),a=Math.pow(2,o.tileID.overscaledZ),s=o.tileSize*Math.pow(2,i.transform.tileZoom)/a,n=s*(o.tileID.canonical.x+o.tileID.wrap*a),l=s*o.tileID.canonical.y;return {u_image:0,u_texsize:o.imageAtlasTexture.size,u_scale:[r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Ri=(e,i,o,r)=>{const a=e.style.light,s=a.properties.get("position"),n=[s.x,s.y,s.z],l=t.bV();"viewport"===a.properties.get("anchor")&&t.bW(l,e.transform.bearingInRadians),t.bX(n,n,l);const c=e.transform.transformLightDirection(n),h=a.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:o,u_fill_translate:r}},zi=(e,i,o,r,a,s,n)=>t.e(Ri(e,i,o,r),Ei(s,e,n),{u_height_factor:-Math.pow(2,a.overscaledZ)/n.tileSize/8}),Di=(e,i,o,r)=>t.e(Ei(i,e,o),{u_fill_translate:r}),Ai=(e,t)=>({u_world:e,u_fill_translate:t}),Li=(e,i,o,r,a)=>t.e(Di(e,i,o,a),{u_world:r}),ki=(e,i,o,r,a)=>{const s=e.transform;let n,l,c=0;if("map"===o.paint.get("circle-pitch-alignment")){const e=t.aC(i,1,s.zoom);n=!0,l=[e,e],c=e/(t.$*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*a;}else n=!1,l=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===o.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:r}},Fi=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),Bi=e=>({u_viewport_size:[e.width,e.height]}),Oi=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),ji=(e,i,o,r)=>{const a=t.aC(e,1,i)/(t.$*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*r;return {u_extrude_scale:t.aC(e,1,i),u_intensity:o,u_globe_extrude_scale:a}},Ni=(e,i,o,r)=>{const a=t.L();t.bY(a,0,e.width,e.height,0,0,1);const s=e.context.gl;return {u_matrix:a,u_world:[s.drawingBufferWidth,s.drawingBufferHeight],u_image:o,u_color_ramp:r,u_opacity:i.paint.get("heatmap-opacity")}},Ui=(e,t,i)=>{const o=i.paint.get("hillshade-accent-color");let r;switch(i.paint.get("hillshade-method")){case "basic":r=4;break;case "combined":r=1;break;case "igor":r=2;break;case "multidirectional":r=3;break;default:r=0;}const a=i.getIlluminationProperties();for(let t=0;t{const o=i.stride,r=t.L();return t.bY(r,0,t.$,-t.$,0,0,1),t.M(r,r,[0,-t.$,0]),{u_matrix:r,u_image:1,u_dimension:[o,o],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function Gi(e,i){const o=Math.pow(2,i.canonical.z),r=i.canonical.y;return [new t.a1(0,r/o).toLngLat().lat,new t.a1(0,(r+1)/o).toLngLat().lat]}const Vi=(e,t,i=0)=>({u_image:0,u_unpack:t.getUnpackVector(),u_dimension:[t.stride,t.stride],u_elevation_stops:1,u_color_stops:4,u_color_ramp_size:i,u_opacity:e.paint.get("color-relief-opacity")}),$i=(e,i,o,r)=>{const a=e.transform;return {u_translation:Ki(e,i,o),u_ratio:r/t.aC(i,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},qi=(e,i,o,r,a)=>t.e($i(e,i,o,r),{u_image:0,u_image_height:a}),Wi=(e,i,o,r,a)=>{const s=e.transform,n=Xi(i,s);return {u_translation:Ki(e,i,o),u_texsize:i.imageAtlasTexture.size,u_ratio:r/t.aC(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},Hi=(e,i,o,r,a,s)=>{const n=e.lineAtlas,l=Xi(i,e.transform),c="round"===o.layout.get("line-cap"),h=n.getDash(a.from,c),u=n.getDash(a.to,c),d=h.width*s.fromScale,_=u.width*s.toScale;return t.e($i(e,i,o,r),{u_patternscale_a:[l/d,-h.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*e.pixelRatio)/2,u_image:0,u_tex_y_a:h.y,u_tex_y_b:u.y,u_mix:s.t})};function Xi(e,i){return 1/t.aC(e,1,i.tileZoom)}function Ki(e,i,o){return t.aD(e.transform,i,o.paint.get("line-translate"),o.paint.get("line-translate-anchor"))}const Yi=(e,t,i,o,r)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*o.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:o.paint.get("raster-brightness-min"),u_brightness_high:o.paint.get("raster-brightness-max"),u_saturation_factor:(s=o.paint.get("raster-saturation"),s>0?1-1/(1.001-s):-s),u_contrast_factor:(a=o.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Qi(o.paint.get("raster-hue-rotate")),u_coords_top:[r[0].x,r[0].y,r[1].x,r[1].y],u_coords_bottom:[r[3].x,r[3].y,r[2].x,r[2].y]};var a,s;};function Qi(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const Ji=(e,t,i,o,r,a,s,n,l,c,h,u,d)=>{const _=s.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+o,u_is_along_line:r,u_is_variable_anchor:a,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},eo=(e,i,o,r,a,s,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.e(Ji(e,i,o,r,a,s,n,l,c,h,u,d,p),{u_gamma_scale:r?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:1})},to=(e,i,o,r,a,s,n,l,c,h,u,d,_)=>t.e(eo(e,i,o,r,a,s,n,l,c,h,!0,u,0,_),{u_texsize_icon:d,u_texture_icon:1}),io=(e,t)=>({u_opacity:e,u_color:t}),oo=(e,i,o,r,a)=>t.e(function(e,i,o,r){const a=o.imageManager.getPattern(e.from.toString()),s=o.imageManager.getPattern(e.to.toString()),{width:n,height:l}=o.imageManager.getPixelSize(),c=Math.pow(2,r.tileID.overscaledZ),h=r.tileSize*Math.pow(2,o.transform.tileZoom)/c,u=h*(r.tileID.canonical.x+r.tileID.wrap*c),d=h*r.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:s.tl,u_pattern_br_b:s.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:s.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.aC(r,1,o.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(o,a,i,r),{u_opacity:e}),ro=(e,t)=>{},ao={fillExtrusion:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_height_factor:new t.bg(e,i.u_height_factor),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.bU(e,i.u_world),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_scale_with_map:new t.bP(e,i.u_scale_with_map),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_extrude_scale:new t.bU(e,i.u_extrude_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale),u_translate:new t.bU(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.bU(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.bU(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.bQ(e,i.u_color),u_overlay:new t.bP(e,i.u_overlay),u_overlay_scale:new t.bg(e,i.u_overlay_scale)}),depth:ro,clippingMask:ro,heatmap:(e,i)=>({u_extrude_scale:new t.bg(e,i.u_extrude_scale),u_intensity:new t.bg(e,i.u_intensity),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_color_ramp:new t.bP(e,i.u_color_ramp),u_opacity:new t.bg(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.bP(e,i.u_image),u_latrange:new t.bU(e,i.u_latrange),u_exaggeration:new t.bg(e,i.u_exaggeration),u_altitudes:new t.b_(e,i.u_altitudes),u_azimuths:new t.b_(e,i.u_azimuths),u_accent:new t.bQ(e,i.u_accent),u_method:new t.bP(e,i.u_method),u_shadows:new t.bZ(e,i.u_shadows),u_highlights:new t.bZ(e,i.u_highlights)}),hillshadePrepare:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_image:new t.bP(e,i.u_image),u_dimension:new t.bU(e,i.u_dimension),u_zoom:new t.bg(e,i.u_zoom),u_unpack:new t.bS(e,i.u_unpack)}),colorRelief:(e,i)=>({u_image:new t.bP(e,i.u_image),u_unpack:new t.bS(e,i.u_unpack),u_dimension:new t.bU(e,i.u_dimension),u_elevation_stops:new t.bP(e,i.u_elevation_stops),u_color_stops:new t.bP(e,i.u_color_stops),u_color_ramp_size:new t.bP(e,i.u_color_ramp_size),u_opacity:new t.bg(e,i.u_opacity)}),line:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_image:new t.bP(e,i.u_image),u_image_height:new t.bg(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_texsize:new t.bU(e,i.u_texsize),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_image:new t.bP(e,i.u_image),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_patternscale_a:new t.bU(e,i.u_patternscale_a),u_patternscale_b:new t.bU(e,i.u_patternscale_b),u_sdfgamma:new t.bg(e,i.u_sdfgamma),u_image:new t.bP(e,i.u_image),u_tex_y_a:new t.bg(e,i.u_tex_y_a),u_tex_y_b:new t.bg(e,i.u_tex_y_b),u_mix:new t.bg(e,i.u_mix)}),raster:(e,i)=>({u_tl_parent:new t.bU(e,i.u_tl_parent),u_scale_parent:new t.bg(e,i.u_scale_parent),u_buffer_scale:new t.bg(e,i.u_buffer_scale),u_fade_t:new t.bg(e,i.u_fade_t),u_opacity:new t.bg(e,i.u_opacity),u_image0:new t.bP(e,i.u_image0),u_image1:new t.bP(e,i.u_image1),u_brightness_low:new t.bg(e,i.u_brightness_low),u_brightness_high:new t.bg(e,i.u_brightness_high),u_saturation_factor:new t.bg(e,i.u_saturation_factor),u_contrast_factor:new t.bg(e,i.u_contrast_factor),u_spin_weights:new t.bT(e,i.u_spin_weights),u_coords_top:new t.bS(e,i.u_coords_top),u_coords_bottom:new t.bS(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texsize_icon:new t.bU(e,i.u_texsize_icon),u_texture:new t.bP(e,i.u_texture),u_texture_icon:new t.bP(e,i.u_texture_icon),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_color:new t.bQ(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_image:new t.bP(e,i.u_image),u_pattern_tl_a:new t.bU(e,i.u_pattern_tl_a),u_pattern_br_a:new t.bU(e,i.u_pattern_br_a),u_pattern_tl_b:new t.bU(e,i.u_pattern_tl_b),u_pattern_br_b:new t.bU(e,i.u_pattern_br_b),u_texsize:new t.bU(e,i.u_texsize),u_mix:new t.bg(e,i.u_mix),u_pattern_size_a:new t.bU(e,i.u_pattern_size_a),u_pattern_size_b:new t.bU(e,i.u_pattern_size_b),u_scale_a:new t.bg(e,i.u_scale_a),u_scale_b:new t.bg(e,i.u_scale_b),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.bg(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_ele_delta:new t.bg(e,i.u_ele_delta),u_fog_matrix:new t.bR(e,i.u_fog_matrix),u_fog_color:new t.bQ(e,i.u_fog_color),u_fog_ground_blend:new t.bg(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.bg(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon_fog_blend:new t.bg(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.bg(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.bg(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_terrain_coords_id:new t.bg(e,i.u_terrain_coords_id),u_ele_delta:new t.bg(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.bg(e,i.u_input),u_output_expected:new t.bg(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.bT(e,i.u_sun_pos),u_atmosphere_blend:new t.bg(e,i.u_atmosphere_blend),u_globe_position:new t.bT(e,i.u_globe_position),u_globe_radius:new t.bg(e,i.u_globe_radius),u_inv_proj_matrix:new t.bR(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.bQ(e,i.u_sky_color),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon:new t.bU(e,i.u_horizon),u_horizon_normal:new t.bU(e,i.u_horizon_normal),u_sky_horizon_blend:new t.bg(e,i.u_sky_horizon_blend),u_sky_blend:new t.bg(e,i.u_sky_blend)})};class so{constructor(e,t,i){this.context=e;const o=e.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const no={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class lo{constructor(e,t,i,o){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=o,this.context=e;const r=e.gl;this.buffer=r.createBuffer(),e.bindVertexBuffer.set(this.buffer),r.bufferData(r.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(s,l.LINES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Fi(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),o.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!a||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.b$;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:S,angle:E});}else $e(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===o.layout.get("text-rotation-alignment");De(c,e,a,O,j,v,h,i,l.toUnwrapped(),f.width,f.height,U,t);}const $=a&&P||V,q=b||$?Yo:v?O:e.transform.clipSpaceToPixelsMatrix,W=p&&0!==o.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1);let H;H=p?c.iconsInText?to(T.kind,E,x,v,b,$,e,q,N,U,z,k,I):eo(T.kind,E,x,v,b,$,e,q,N,U,a,z,0,I):Ji(T.kind,E,x,v,b,$,e,q,N,U,a,z,I);const X={program:S,buffers:u,uniformValues:H,projectionData:Z,atlasTexture:D,atlasTextureIcon:F,atlasInterpolation:A,atlasInterpolationIcon:L,isSDF:p,hasHalo:W};if(y&&c.canOverlap){w=!0;const e=u.segments.get();for(const i of e)C.push({segments:new t.aM([i]),sortKey:i.sortKey,state:X,terrainData:R});}else C.push({segments:u.segments,sortKey:0,state:X,terrainData:R});}w&&C.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of C){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const r=i.uniformValues;i.hasHalo&&(r.u_is_halo=1,or(i.buffers,t.segments,o,e,i.program,T,u,d,r,i.projectionData,t.terrainData)),r.u_is_halo=0;}or(i.buffers,t.segments,o,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function or(e,t,i,o,r,a,s,n,l,c,h){const u=o.context;r.draw(u,u.gl.TRIANGLES,a,s,n,Ut.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,o.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function rr(e,i,o,r,a){const s=e.context,n=s.gl,l=Vt.disabled,c=new jt([n.ONE,n.ONE],t.bf.transparent,[!0,!0,!0,!0]),h=i.getBucket(o);if(!h)return;const u=r.key;let d=o.heatmapFbos.get(u);d||(d=sr(s,i.tileSize,i.tileSize),o.heatmapFbos.set(u,d)),s.bindFramebuffer.set(d.framebuffer),s.viewport.set([0,0,i.tileSize,i.tileSize]),s.clear({color:t.bf.transparent});const _=h.programConfigurations.get(o.id),p=e.useProgram("heatmap",_,!a),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),f=e.style.map.terrain.getTerrainData(r);p.draw(s,n.TRIANGLES,Zt.disabled,l,c,Ut.disabled,ji(i,e.transform.zoom,o.paint.get("heatmap-intensity"),1),f,m,o.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,o.paint,e.transform.zoom,_);}function ar(e,t,i,o,r){const a=e.context,s=a.gl,n=e.transform;a.setColorMode(e.colorModeForRenderPass());const l=nr(a,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,h.colorAttachment.get()),a.activeTexture.set(s.TEXTURE1),l.bind(s.LINEAR,s.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:r,applyGlobeMatrix:!o});e.useProgram("heatmapTexture").draw(a,s.TRIANGLES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Ni(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function sr(e,t,i){var o,r;const a=e.gl,s=a.createTexture();a.bindTexture(a.TEXTURE_2D,s),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR);const n=null!==(o=e.HALF_FLOAT)&&void 0!==o?o:a.UNSIGNED_BYTE,l=null!==(r=e.RGBA16F)&&void 0!==r?r:a.RGBA;a.texImage2D(a.TEXTURE_2D,0,l,t,i,0,a.RGBA,n,null);const c=e.createFramebuffer(t,i,!1,!1);return c.colorAttachment.set(s),c}function nr(e,i){return i.colorRampTexture||(i.colorRampTexture=new t.T(e,i.colorRamp,e.gl.RGBA)),i.colorRampTexture}function lr(e,t,i,o,r){if(!i||!o||!o.imageAtlas)return;const a=o.imageAtlas.patternPositions;let s=a[i.to.toString()],n=a[i.from.toString()];if(!s&&n&&(s=n),!n&&s&&(n=s),!s||!n){const e=r.getPaintProperty(t);s=a[e],n=a[e];}s&&n&&e.setConstantPatternPositions(s,n);}function cr(e,i,o,r,a,s,n,l){const c=e.context.gl,h="fill-pattern",u=o.paint.get(h),d=u&&u.constantOr(1),_=o.getCrossfadeParameters();let p,m,f,g,v;const b=e.transform,x=o.paint.get("fill-translate"),y=o.paint.get("fill-translate-anchor");n?(m=d&&!o.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",p=c.LINES):(m=d?"fillPattern":"fill",p=c.TRIANGLES);const w=u.constantOr(null);for(const u of r){const r=i.getTile(u);if(d&&!r.patternsLoaded())continue;const T=r.getBucket(o);if(!T)continue;const P=T.programConfigurations.get(o.id),C=e.useProgram(m,P),I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(u);d&&(e.context.activeTexture.set(c.TEXTURE0),r.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),P.updatePaintBuffers(_)),lr(P,h,w,r,o);const M=b.getProjectionData({overscaledTileID:u,applyGlobeMatrix:!l,applyTerrainMatrix:!0}),S=t.aD(b,r,x,y);if(n){g=T.indexBuffer2,v=T.segments2;const t=[c.drawingBufferWidth,c.drawingBufferHeight];f="fillOutlinePattern"===m&&d?Li(e,_,r,t,S):Ai(t,S);}else g=T.indexBuffer,v=T.segments,f=d?Di(e,_,r,S):{u_fill_translate:S};const E=e.stencilModeForClipping(u);C.draw(e.context,p,a,E,s,Ut.backCCW,f,I,M,o.id,T.layoutVertexBuffer,g,v,o.paint,e.transform.zoom,P);}}function hr(e,i,o,r,a,s,n,l){const c=e.context,h=c.gl,u="fill-extrusion-pattern",d=o.paint.get(u),_=d.constantOr(1),p=o.getCrossfadeParameters(),m=o.paint.get("fill-extrusion-opacity"),f=d.constantOr(null),g=e.transform;for(const d of r){const r=i.getTile(d),v=r.getBucket(o);if(!v)continue;const b=e.style.map.terrain&&e.style.map.terrain.getTerrainData(d),x=v.programConfigurations.get(o.id),y=e.useProgram(_?"fillExtrusionPattern":"fillExtrusion",x);_&&(e.context.activeTexture.set(h.TEXTURE0),r.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),x.updatePaintBuffers(p));const w=g.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!l,applyTerrainMatrix:!0});lr(x,u,f,r,o);const T=t.aD(g,r,o.paint.get("fill-extrusion-translate"),o.paint.get("fill-extrusion-translate-anchor")),P=o.paint.get("fill-extrusion-vertical-gradient"),C=_?zi(e,P,m,T,d,p,r):Ri(e,P,m,T);y.draw(c,c.gl.TRIANGLES,a,s,n,Ut.backCCW,C,b,w,o.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,o.paint,e.transform.zoom,x,e.style.map.terrain&&v.centroidVertexBuffer);}}function ur(e,t,i,o,r,a,s,n,l){var c;const h=e.style.projection,u=e.context,d=e.transform,_=u.gl,p=[`#define NUM_ILLUMINATION_SOURCES ${i.paint.get("hillshade-highlight-color").values.length}`],m=e.useProgram("hillshade",null,!1,p),f=!e.options.moving;for(const p of o){const o=t.getTile(p),g=o.fbo;if(!g)continue;const v=h.getMeshFromTileID(u,p.canonical,n,!0,"raster"),b=null===(c=e.style.map.terrain)||void 0===c?void 0:c.getTerrainData(p);u.activeTexture.set(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g.colorAttachment.get());const x=d.getProjectionData({overscaledTileID:p,aligned:f,applyGlobeMatrix:!l,applyTerrainMatrix:!0});m.draw(u,_.TRIANGLES,a,r[p.overscaledZ],s,Ut.backCCW,Ui(e,o,i),b,x,i.id,v.vertexBuffer,v.indexBuffer,v.segments);}}function dr(e,i,o,r,a,s,n,l,c){var h;const u=e.style.projection,d=e.context,_=e.transform,p=d.gl,m=e.useProgram("colorRelief"),f=!e.options.moving;let g=!0,v=0;for(const b of r){const r=i.getTile(b),x=r.dem;if(g){const e=p.getParameter(p.MAX_TEXTURE_SIZE),{elevationTexture:t,colorTexture:i}=o.getColorRampTextures(d,e,x.getUnpackVector());d.activeTexture.set(p.TEXTURE1),t.bind(p.NEAREST,p.CLAMP_TO_EDGE),d.activeTexture.set(p.TEXTURE4),i.bind(p.LINEAR,p.CLAMP_TO_EDGE),g=!1,v=t.size[0];}if(!x||!x.data)continue;const y=x.stride,w=x.getPixels();if(d.activeTexture.set(p.TEXTURE0),d.pixelStoreUnpackPremultiplyAlpha.set(!1),r.demTexture=r.demTexture||e.getTileTexture(y),r.demTexture){const e=r.demTexture;e.update(w,{premultiply:!1}),e.bind(p.LINEAR,p.CLAMP_TO_EDGE);}else r.demTexture=new t.T(d,w,p.RGBA,{premultiply:!1}),r.demTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE);const T=u.getMeshFromTileID(d,b.canonical,l,!0,"raster"),P=null===(h=e.style.map.terrain)||void 0===h?void 0:h.getTerrainData(b),C=_.getProjectionData({overscaledTileID:b,aligned:f,applyGlobeMatrix:!c,applyTerrainMatrix:!0});m.draw(d,p.TRIANGLES,s,a[b.overscaledZ],n,Ut.backCCW,Vi(o,r.dem,v),P,C,o.id,T.vertexBuffer,T.indexBuffer,T.segments);}}const _r=[new t.P(0,0),new t.P(t.$,0),new t.P(t.$,t.$),new t.P(0,t.$)];function pr(e,t,i,o,r,a,s,n,l=!1,c=!1){const h=o[o.length-1].overscaledZ,u=e.context,d=u.gl,_=e.useProgram("raster"),p=e.transform,m=e.style.projection,f=e.colorModeForRenderPass(),g=!e.options.moving;for(const v of o){const o=e.getDepthModeForSublayer(v.overscaledZ-h,1===i.paint.get("raster-opacity")?Zt.ReadWrite:Zt.ReadOnly,d.LESS),b=t.getTile(v);b.registerFadeDuration(i.paint.get("raster-fade-duration"));const x=t.findLoadedParent(v,0),y=t.findLoadedSibling(v),w=mr(b,x||y||null,t,i,e.transform,e.style.map.terrain);let T,P;const C="nearest"===i.paint.get("raster-resampling")?d.NEAREST:d.LINEAR;u.activeTexture.set(d.TEXTURE0),b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),u.activeTexture.set(d.TEXTURE1),x?(x.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),T=Math.pow(2,x.tileID.overscaledZ-b.tileID.overscaledZ),P=[b.tileID.canonical.x*T%1,b.tileID.canonical.y*T%1]):b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),b.texture.useMipmap&&u.extTextureFilterAnisotropic&&e.transform.pitch>20&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(v),M=p.getProjectionData({overscaledTileID:v,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),S=Yi(P||[0,0],T||1,w,i,n),E=m.getMeshFromTileID(u,v.canonical,a,s,"raster");_.draw(u,d.TRIANGLES,o,r?r[v.overscaledZ]:Vt.disabled,f,l?Ut.frontCCW:Ut.backCCW,S,I,M,i.id,E.vertexBuffer,E.indexBuffer,E.segments);}}function mr(e,i,o,r,a,n){const l=r.paint.get("raster-fade-duration");if(!n&&l>0){const r=s.now(),n=(r-e.timeAdded)/l,c=i?(r-i.timeAdded)/l:-1,h=o.getSource(),u=ge(a,{tileSize:h.tileSize,roundZoom:h.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-u)>Math.abs(e.tileID.overscaledZ-u),_=d&&e.refreshedUponExpiration?1:t.ah(d?n:1-c,0,1);return e.refreshedUponExpiration&&n>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-_}:{opacity:_,mix:0}}return {opacity:1,mix:0}}const fr=new t.bf(1,0,0,1),gr=new t.bf(0,1,0,1),vr=new t.bf(0,0,1,1),br=new t.bf(1,0,1,1),xr=new t.bf(0,1,1,1);function yr(e,t,i,o){Tr(e,0,t+i/2,e.transform.width,i,o);}function wr(e,t,i,o){Tr(e,t-i/2,0,i,e.transform.height,o);}function Tr(e,t,i,o,r,a){const s=e.context,n=s.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,o*e.pixelRatio,r*e.pixelRatio),s.clear({color:a}),n.disable(n.SCISSOR_TEST);}function Pr(e,i,o){const r=e.context,a=r.gl,s=e.useProgram("debug"),n=Zt.disabled,l=Vt.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(o);r.activeTexture.set(a.TEXTURE0);const d=i.getTileByID(o.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(o).tileSize,m=512/Math.min(p,512)*(o.overscaledZ/e.transform.zoom)*.5;let f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=` => ${o.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,o=e.context.gl,r=e.debugOverlayCanvas.getContext("2d");r.clearRect(0,0,i.width,i.height),r.shadowColor="white",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle="white",r.textBaseline="top",r.font="bold 36px Open Sans, sans-serif",r.fillText(t,5,5),r.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:o,applyGlobeMatrix:!0,applyTerrainMatrix:!0});s.draw(r,a.TRIANGLES,n,l,jt.alphaBlended,Ut.disabled,Oi(t.bf.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),s.draw(r,a.LINE_STRIP,n,l,c,Ut.disabled,Oi(t.bf.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function Cr(e,t,i,o){const{isRenderingGlobe:r}=o,a=e.context,s=a.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain");a.bindFramebuffer.set(null),a.viewport.set([0,0,e.width,e.height]);for(const o of i){const i=t.getTerrainMesh(o.tileID),u=e.renderToTexture.getTexture(o),d=t.getTerrainData(o.tileID);a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,u.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(o.tileID.toUnwrapped()),m=Ci(_,p,e.style.sky,n.pitch,r),f=n.getProjectionData({overscaledTileID:o.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});h.draw(a,s.TRIANGLES,c,Vt.disabled,l,Ut.backCCW,m,d,f,"terrain",i.vertexBuffer,i.indexBuffer,i.segments);}}function Ir(e,i){if(!i.mesh){const o=new t.aL;o.emplaceBack(-1,-1),o.emplaceBack(1,-1),o.emplaceBack(1,1),o.emplaceBack(-1,1);const r=new t.aN;r.emplaceBack(0,1,2),r.emplaceBack(0,2,3),i.mesh=new wt(e.createVertexBuffer(o,Tt.members),e.createIndexBuffer(r),t.aM.simpleSegment(0,0,o.length,r.length));}return i.mesh}class Mr{constructor(e,i){this.context=new Ho(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:t.ag(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=xe.maxUnderzooming+xe.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new vt;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.aL;i.emplaceBack(0,0),i.emplaceBack(t.$,0),i.emplaceBack(0,t.$),i.emplaceBack(t.$,t.$),this.tileExtentBuffer=e.createVertexBuffer(i,Tt.members),this.tileExtentSegments=t.aM.simpleSegment(0,0,4,2);const o=new t.aL;o.emplaceBack(0,0),o.emplaceBack(t.$,0),o.emplaceBack(0,t.$),o.emplaceBack(t.$,t.$),this.debugBuffer=e.createVertexBuffer(o,Tt.members),this.debugSegments=t.aM.simpleSegment(0,0,4,5);const r=new t.c6;r.emplaceBack(0,0,0,0),r.emplaceBack(t.$,0,t.$,0),r.emplaceBack(0,t.$,0,t.$),r.emplaceBack(t.$,t.$,t.$,t.$),this.rasterBoundsBuffer=e.createVertexBuffer(r,Ti.members),this.rasterBoundsSegments=t.aM.simpleSegment(0,0,4,2);const a=new t.aL;a.emplaceBack(0,0),a.emplaceBack(t.$,0),a.emplaceBack(0,t.$),a.emplaceBack(t.$,t.$),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(a,Tt.members),this.rasterBoundsSegmentsPosOnly=t.aM.simpleSegment(0,0,4,5);const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(1,0),s.emplaceBack(0,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,Tt.members),this.viewportSegments=t.aM.simpleSegment(0,0,4,2);const n=new t.c7;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.aN;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new Vt({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new wt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const o=t.L();t.bY(o,0,this.width,this.height,0,0,1),t.N(o,o,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const r={mainMatrix:o,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:o};this.useProgram("clippingMask",null,!0).draw(e,i.TRIANGLES,Zt.disabled,this.stencilClearMode,jt.disabled,Ut.disabled,null,null,r,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const o=this.context;o.setColorMode(jt.disabled),o.setDepthMode(Zt.disabled);const r={};for(const e of t)r[e.key]=this.nextStencilID++;this._renderTileMasks(r,t,i,!0),this._renderTileMasks(r,t,i,!1),this._tileClippingMaskIDs=r;}_renderTileMasks(e,t,i,o){const r=this.context,a=r.gl,s=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=s.getMeshFromTileID(this.context,c.canonical,o,!0,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!i,applyTerrainMatrix:!0});l.draw(r,a.TRIANGLES,Zt.disabled,new Vt({func:a.ALWAYS,mask:0},t,255,a.KEEP,a.KEEP,a.REPLACE),jt.disabled,i?Ut.disabled:Ut.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,o=this.transform,r=this.useProgram("depth"),a=this.getDepthModeFor3D(),s=ve(o,{tileSize:o.tileSize});for(const n of s){const s=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,!0,!0,"raster"),c=o.getProjectionData({overscaledTileID:n,applyGlobeMatrix:!0,applyTerrainMatrix:!0});r.draw(e,t.TRIANGLES,a,Vt.disabled,jt.disabled,Ut.backCCW,null,s,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new Vt({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new Vt({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(r>1){this.currentStencilSource=void 0,this.nextStencilID+r>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(this.clearStencil(),r>1){const e={},a={};for(let i=0;i0};for(const e in n){const t=n[e];t.used&&t.prepare(this.context),l[e]=t.getVisibleCoordinates(!1),c[e]=l[e].slice().reverse(),h[e]=t.getVisibleCoordinates(!0).reverse();}this.opaquePassCutoff=1/0;for(let e=0;ethis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.bf.black:t.bf.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,o=i.gl,r=((e,t,i)=>{const o=Math.cos(t.rollInRadians),r=Math.sin(t.rollInRadians),a=he(t),s=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-a*r)*i,(t.height/2+a*o)*i],u_horizon_normal:[-r,o],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:s}})(t,e.style.map.transform,e.pixelRatio),a=new Zt(o.LEQUAL,Zt.ReadWrite,[0,1]),s=Vt.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=Ir(i,t);l.draw(i,o.TRIANGLES,a,s,n,Ut.disabled,r,null,void 0,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=a.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[a[this.currentLayer]],t=n[e.source],i=l[e.source];this._renderTileClippingMasks(e,i,!1),this.renderLayer(this,t,e,i,u);}this.renderPass="translucent";let d=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:o,u_inv_proj_matrix:r}))(c,u,[p[0],p[1],p[2]],d,_),f=Ir(r,i);s.draw(r,a.TRIANGLES,n,Vt.disabled,jt.alphaBlended,Ut.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const o=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.sourceCaches[i.source]]:[])),r=o.filter((e=>"vector"===e.getSource().type)),a=o.filter((e=>"vector"!==e.getSource().type)),s=e=>{(!i||i.getSource().maxzooms(e))),i||a.forEach((e=>s(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let o=0;ou.getElevation(a,e,t):null;er(s,d,_,c,h,f,i,p,g,t.aD(h,e,n,l),a.toUnwrapped(),o);}}}(r,e,o,i,o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),a),0!==o.paint.get("icon-opacity").constantOr(1)&&ir(e,i,o,r,!1,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),o.layout.get("icon-rotation-alignment"),o.layout.get("icon-pitch-alignment"),o.layout.get("icon-keep-upright"),l,c,n),0!==o.paint.get("text-opacity").constantOr(1)&&ir(e,i,o,r,!0,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&(Ko(e,i,o,r,!0),Ko(e,i,o,r,!1));}(e,i,o,r,this.style.placement.variableOffsets,a):t.cc(o)?function(e,i,o,r,a){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:s}=a,n=o.paint.get("circle-opacity"),l=o.paint.get("circle-stroke-width"),c=o.paint.get("circle-stroke-opacity"),h=!o.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Zt.ReadOnly),m=Vt.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let a=0;ae.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:r,layoutVertexBuffer:a,indexBuffer:s,uniformValues:n,terrainData:l,projectionData:c}=t.state;r.draw(u,d.TRIANGLES,p,m,f,Ut.backCCW,n,l,c,o.id,a,s,t.segments,o.paint,e.transform.zoom,i);}}(e,i,o,r,a):t.cd(o)?function(e,i,o,r,a){if(0===o.paint.get("heatmap-opacity"))return;const s=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=a;if(e.style.map.terrain){for(const t of r){const r=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?rr(e,r,o,t,l):"translucent"===e.renderPass&&ar(e,o,t,n,l));}s.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,o,r){const a=e.context,s=a.gl,n=e.transform,l=Vt.disabled,c=new jt([s.ONE,s.ONE],t.bf.transparent,[!0,!0,!0,!0]);((function(e,i,o){const r=e.gl;e.activeTexture.set(r.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let a=o.heatmapFbos.get(t.c2);a?(r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer)):(a=sr(e,i.width/4,i.height/4),o.heatmapFbos.set(t.c2,a));}))(a,e,o),a.clear({color:t.bf.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return !1;if(!e.from||!e.to)return !0;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=!1,o=[]){this.cache=this.cache||{};const r=!!this.style.map.terrain,a=this.style.projection,s=i?xt.projectionMercator:a.shaderPreludeCode,n=i?Pt:a.shaderDefine,l=e+(t?t.cacheKey:"")+`/${i?Ct:a.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(r?"/terrain":"")+(o?`/${o.join("/")}`:"");return this.cache[l]||(this.cache[l]=new Si(this.context,xt[e],t,ao[e],this._showOverdrawInspector,r,s,n,o)),this.cache[l]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Sr(e,t){let i,o=!1,r=null,a=null;const s=()=>{r=null,o&&(e.apply(a,i),r=setTimeout(s,t),o=!1);};return (...e)=>(o=!0,a=this,i=e,r||s(),r)}class Er{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(!this._isValidHash(e))return !1;const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let o=window.location.hash.replace(i,"");o.startsWith("#&")?o=o.slice(0,1)+o.slice(2):"#"===o&&(o="");let r=window.location.href.replace(/(#.+)?$/,o);r=r.replace("&&","&"),window.history.replaceState(window.history.state,null,r);},this._updateHash=Sr(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,o=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),r=Math.pow(10,o),a=Math.round(t.lng*r)/r,s=Math.round(t.lat*r)/r,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${a}/${s}/${i}`:`${i}/${s}/${a}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const o=i.split("=")[0];return o===e?(t=!0,`${o}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return !1;try{new t.S(+e[2],+e[1]);}catch(e){return !1}const i=+e[0],o=+(e[3]||0),r=+(e[4]||0);return i>=this._map.getMinZoom()&&i<=this._map.getMaxZoom()&&o>=-180&&o<=180&&r>=this._map.getMinPitch()&&r<=this._map.getMaxPitch()}}const Rr={linearity:.3,easing:t.cm(0,0,.3,1)},zr=t.e({deceleration:2500,maxSpeed:1400},Rr),Dr=t.e({deceleration:20,maxSpeed:1400},Rr),Ar=t.e({deceleration:1e3,maxSpeed:360},Rr),Lr=t.e({deceleration:1e3,maxSpeed:90},Rr),kr=t.e({deceleration:1e3,maxSpeed:360},Rr);class Fr{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:s.now(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=s.now();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const o=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,r={};if(i.pan.mag()){const a=Or(i.pan.mag(),o,t.e({},zr,e||{})),s=i.pan.mult(a.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(s,this._map.transform);r.center=n.easingCenter,r.offset=n.easingOffset,Br(r,a);}if(i.zoom){const e=Or(i.zoom,o,Dr);r.zoom=this._map.transform.zoom+e.amount,Br(r,e);}if(i.bearing){const e=Or(i.bearing,o,Ar);r.bearing=this._map.transform.bearing+t.ah(e.amount,-179,179),Br(r,e);}if(i.pitch){const e=Or(i.pitch,o,Lr);r.pitch=this._map.transform.pitch+e.amount,Br(r,e);}if(i.roll){const e=Or(i.roll,o,kr);r.roll=this._map.transform.roll+t.ah(e.amount,-179,179),Br(r,e);}if(r.zoom||r.bearing){const e=void 0===i.pinchAround?i.around:i.pinchAround;r.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.e(r,{noMoveStart:!0})}}function Br(e,t){(!e.duration||e.durationi.unproject(e))),l=a.reduce(((e,t,i,o)=>e.add(t.div(o.length))),new t.P(0,0));super(e,{points:a,point:l,lngLats:s,lngLat:i.unproject(l),originalEvent:o}),this._defaultPrevented=!1;}}class Ur extends t.l{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=!1;}}class Zr{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new Ur(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new jr(e.type,this._map,e))}mouseup(e){this._map.fire(new jr(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new jr(e.type,this._map,e));}dblclick(e){return this._firePreventable(new jr(e.type,this._map,e))}mouseover(e){this._map.fire(new jr(e.type,this._map,e));}mouseout(e){this._map.fire(new jr(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Nr(e.type,this._map,e))}touchmove(e){this._map.fire(new Nr(e.type,this._map,e));}touchend(e){this._map.fire(new Nr(e.type,this._map,e));}touchcancel(e){this._map.fire(new Nr(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Gr{constructor(e){this._map=e;}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new jr(e.type,this._map,e));}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new jr("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new jr(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Vr{constructor(e){this._map=e;}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return {lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class $r{constructor(e,t){this._map=e,this._tr=new Vr(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(n.disableDrag(),this._startPos=this._lastPos=t,this._active=!0);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(o,r,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.l(e,{originalEvent:i}))}}function qr(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let o=0;othis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){const i=new t.P(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=qr(o,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const o=qr(i,t);for(const e in this.touches){const t=o[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Hr{constructor(e){this.singleTap=new Wr(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const o=this.singleTap.touchend(e,t,i);if(o){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(o)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}}}class Xr{constructor(e){this._tr=new Vr(e),this._zoomIn=new Hr({numTouches:1,numTaps:2}),this._zoomOut=new Hr({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const o=this._zoomIn.touchend(e,t,i),r=this._zoomOut.touchend(e,t,i),a=this._tr;return o?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom+1,around:a.unproject(o)},{originalEvent:e})}):r?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom-1,around:a.unproject(r)},{originalEvent:e})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class Kr{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0));}dragMove(e,t){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const o=Array.isArray(t)?t[0]:t;return !this._moved&&o.dist(i)!0}),t=new ta){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t;}_executeRelevantHandler(e,t,i){return e instanceof MouseEvent?t(e):"undefined"!=typeof TouchEvent&&e instanceof TouchEvent?i(e):void 0}startMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.startMove(e)),(e=>this.oneFingerTouchMoveStateManager.startMove(e)));}endMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.endMove(e)),(e=>this.oneFingerTouchMoveStateManager.endMove(e)));}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}const oa=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};class ra{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=!1,this._touches={},this._sum=new t.P(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,o){o.length>0&&(this._active=!0);const r=qr(o,i),a=new t.P(0,0),s=new t.P(0,0);let n=0;for(const e in r){const t=r[e],i=this._touches[e];i&&(a._add(t),s._add(t.sub(i)),n++,r[e]=t);}if(this._touches=r,this._shouldBePrevented(n)||!s.mag())return;const l=s.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class da extends aa{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,ua(e[0].sub(e[1]))&&(this._valid=!1);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const o=e[0].sub(this._lastPoints[0]),r=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const o=e.mag()>=2,r=t.mag()>=2;if(!o&&!r)return;if(!o||!r)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const a=e.y>0==t.y>0;return ua(e)&&ua(t)&&a}}const _a={panStep:100,bearingStep:15,pitchStep:10};class pa{constructor(e){this._tr=new Vr(e);const t=_a;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1;}reset(){this._active=!1;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,o=0,r=0,a=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),r=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),r=1);break;case 38:e.shiftKey?o=1:(e.preventDefault(),a=-1);break;case 40:e.shiftKey?o=-1:(e.preventDefault(),a=1);break;default:return}return this._rotationDisabled&&(i=0,o=0),{cameraAnimation:s=>{const n=this._tr;s.easeTo({duration:300,easeId:"keyboardHandler",easing:ma,zoom:t?Math.round(n.zoom)+t*(e.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+o*this._pitchStep,offset:[-r*this._panStep,-a*this._panStep],center:n.center},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function ma(e){return e*(2-e)}const fa=4.000244140625,ga=1/450;class va{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new Vr(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=ga;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=!1);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=s.now(),o=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%fa==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":o>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(o*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=n.mousePos(this._map.getCanvas(),e),o=this._tr;this._aroundPoint=this._aroundCenter?o.transform.locationToScreenPoint(t.S.convert(o.center)):i,this._frameId||(this._frameId=!0,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>fa?this._wheelZoomRate:this._defaultZoomRate;let o=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==o&&(o=1/o);const r="number"!=typeof this._targetZoom?e.scale:t.af(this._targetZoom);this._targetZoom=e.getConstrained(e.getCameraLngLat(),t.ak(r*o)).zoom,"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,o=this._startZoom,r=this._easing;let a,n=!1;if("wheel"===this._type&&o&&r){const e=s.now()-this._lastWheelEventTime,l=Math.min((e+5)/200,1),c=r(l);a=t.C.number(o,i,c),l<1?this._frameId||(this._frameId=!0):n=!0;}else a=i,n=!0;return this._active=!0,n&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=a,{noInertia:!0,needsRenderFrame:!n,zoomDelta:a-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.co;if(this._prevEase){const e=this._prevEase,o=(s.now()-e.start)/e.duration,r=e.easing(o+.01)-e.easing(o),a=.27/Math.sqrt(r*r+1e-4)*.01,n=Math.sqrt(.0729-a*a);i=t.cm(a,n,.25,1);}return this._prevEase={start:s.now(),duration:e,easing:i},i}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class ba{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class xa{constructor(e){this._tr=new Vr(e),this.reset();}reset(){this._active=!1;}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ya{constructor(){this._tap=new Hr({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const o=t[0],r=e.timeStamp-this._tapTime<500,a=this._tapPoint.dist(o)<30;r&&a?i.length>0&&(this._swipePoint=o,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const o=t[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,e.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const o=this._tap.touchend(e,t,i);o&&(this._tapTime=e.timeStamp,this._tapPoint=o);}}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class wa{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Ta{constructor(e,t,i,o){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=o;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Pa{constructor(e,t,i,o){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class Ca{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=!1;}isActive(){return !1}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=n.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),o=document.createElement("div");o.className="maplibregl-desktop-message",o.textContent=t,this._container.appendChild(o);const r=document.createElement("div");r.className="maplibregl-mobile-message",r.textContent=i,this._container.appendChild(r),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(n.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=!0;}disable(){this._enabled=!1,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.l("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const Ia=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Ma extends t.l{}function Sa(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class Ea{constructor(e,i){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,i)=>{if("blur"===e.type)return void this.stop(!0);this._updatingCamera=!0;const o="renderFrame"===e.type?void 0:e,r={needsRenderFrame:!1},a={},s={};for(const{handlerName:l,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let u;if(this._blockedByActive(s,h,l))c.reset();else if(c[i||e.type]){if(t.cp(e,i||e.type)){const t=n.mousePos(this._map.getCanvas(),e);u=c[i||e.type](e,t);}else if(t.cq(e,i||e.type)){const t=this._getMapTouches(e.touches),o=n.touchPos(this._map.getCanvas(),t);u=c[i||e.type](e,o,t);}else t.cr(i||e.type)||(u=c[i||e.type](e));this.mergeHandlerResult(r,a,u,l,o),u&&u.needsRenderFrame&&this._triggerRenderFrame();}(u||c.isActive())&&(s[l]=c);}const l={};for(const e in this._previousActiveHandlers)s[e]||(l[e]=o);this._previousActiveHandlers=s,(Object.keys(l).length||Sa(r))&&(this._changes.push([r,a,l]),this._triggerRenderFrame()),(Object.keys(s).length||Sa(r))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:c}=r;c&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],c(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Fr(e),this._bearingSnap=i.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(i);const o=this._el;this._listeners=[[o,"touchstart",{passive:!0}],[o,"touchmove",{passive:!1}],[o,"touchend",void 0],[o,"touchcancel",void 0],[o,"mousedown",void 0],[o,"mousemove",void 0],[o,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[o,"mouseover",void 0],[o,"mouseout",void 0],[o,"dblclick",void 0],[o,"click",void 0],[o,"keydown",{capture:!1}],[o,"keyup",void 0],[o,"wheel",{passive:!1}],[o,"contextmenu",void 0],[window,"blur",void 0]];for(const[e,t,i]of this._listeners)n.addEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)n.removeEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const i=this._map,o=i.getCanvasContainer();this._add("mapEvent",new Zr(i,e));const r=i.boxZoom=new $r(i,e);this._add("boxZoom",r),e.interactive&&e.boxZoom&&r.enable();const a=i.cooperativeGestures=new Ca(i,e.cooperativeGestures);this._add("cooperativeGestures",a),e.cooperativeGestures&&a.enable();const s=new Xr(i),l=new xa(i);i.doubleClickZoom=new ba(l,s),this._add("tapZoom",s),this._add("clickZoom",l),e.interactive&&e.doubleClickZoom&&i.doubleClickZoom.enable();const c=new ya;this._add("tapDragZoom",c);const h=i.touchPitch=new da(i);this._add("touchPitch",h),e.interactive&&e.touchPitch&&i.touchPitch.enable(e.touchPitch);const u=()=>i.project(i.getCenter()),d=function({enable:e,clickTolerance:i,aroundCenter:o=!0,minPixelCenterThreshold:r=100,rotateDegreesPerPixelMoved:a=.8},s){const l=new ea({checkCorrectEvent:e=>0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:i,move:(e,i)=>{const n=s();if(o&&Math.abs(n.y-e.y)>r)return {bearingDelta:t.cn(new t.P(e.x,i.y),i,n)};let l=(i.x-e.x)*a;return o&&i.y0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)});return new Kr({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:o,enable:e,assignEvents:oa})}(e),p=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3},o){const r=new ea({checkCorrectEvent:e=>2===n.mouseButton(e)&&e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>{const r=o();let a=(t.x-e.x)*i;return t.y0===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:i,enable:e,assignEvents:oa})}(e),f=new ra(e,i);i.dragPan=new wa(o,m,f),this._add("mousePan",m),this._add("touchPan",f,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&i.dragPan.enable(e.dragPan);const g=new ha,v=new la;i.touchZoomRotate=new Pa(o,v,g,c),this._add("touchRotate",g,["touchPan","touchZoom"]),this._add("touchZoom",v,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&i.touchZoomRotate.enable(e.touchZoomRotate);const b=i.scrollZoom=new va(i,(()=>this._triggerRenderFrame()));this._add("scrollZoom",b,["mousePan"]),e.interactive&&e.scrollZoom&&i.scrollZoom.enable(e.scrollZoom);const x=i.keyboard=new pa(i);this._add("keyboard",x),e.interactive&&e.keyboard&&i.keyboard.enable(),this._add("blockableMapEvent",new Gr(i));}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(Ia(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const o in e)if(o!==i&&(!t||t.indexOf(o)<0))return !0;return !1}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,o,r,a){if(!o)return;t.e(e,o);const s={handlerName:r,originalEvent:o.originalEvent||a};void 0!==o.zoomDelta&&(i.zoom=s),void 0!==o.panDelta&&(i.drag=s),void 0!==o.rollDelta&&(i.roll=s),void 0!==o.pitchDelta&&(i.pitch=s),void 0!==o.bearingDelta&&(i.rotate=s);}_applyChanges(){const e={},i={},o={};for(const[r,a,s]of this._changes)r.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(r.panDelta)),r.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+r.zoomDelta),r.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+r.bearingDelta),r.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+r.pitchDelta),r.rollDelta&&(e.rollDelta=(e.rollDelta||0)+r.rollDelta),void 0!==r.around&&(e.around=r.around),void 0!==r.pinchAround&&(e.pinchAround=r.pinchAround),r.noInertia&&(e.noInertia=r.noInertia),t.e(i,a),t.e(o,s);this._updateMapTransform(e,i,o),this._changes=[];}_updateMapTransform(e,t,i){const o=this._map,r=o._getTransformForUpdate(),a=o.terrain;if(!(Sa(e)||a&&this._terrainMovement))return this._fireEvents(t,i,!0);o._stop(!0);let{panDelta:s,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;void 0!==d&&(u=d),u=u||o.transform.centerPoint,a&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const _={panDelta:s,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const p=u.distSqr(r.centerPoint)<.01?r.center:r.screenPointToLocation(s?u.sub(s):u);a?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._terrainMovement||!t.drag&&!t.zoom?t.drag&&this._terrainMovement?r.setCenter(r.screenPointToLocation(r.centerPoint.sub(s))):this._map.cameraHelper.handleMapControlsPan(_,r,p):(this._terrainMovement=!0,this._map._elevationFreeze=!0,this._map.cameraHelper.handleMapControlsPan(_,r,p))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._map.cameraHelper.handleMapControlsPan(_,r,p)),o._applyUpdatedTransform(r),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0);}_fireEvents(e,i,o){const r=Ia(this._eventsInProgress),a=Ia(e),n={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(n[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!r&&a&&this._fireEvent("movestart",a.originalEvent);for(const e in n)this._fireEvent(e,n[e]);a&&this._fireEvent("move",a.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const l={};let c;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:o}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],c=i[t]||o,l[`${e}end`]=c);}for(const e in l)this._fireEvent(e,l[e]);const h=Ia(this._eventsInProgress),u=(r||a)&&!h;if(u&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(o&&u){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new Ma("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}class Ra extends t.E{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((s.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=i.bearingSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.S(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,o){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},i),o)}panTo(e,i,o){return this.easeTo(t.e({center:e},i),o)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,o){return this.easeTo(t.e({zoom:e},i),o)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.l("movestart",i)).fire(new t.l("move",i)).fire(new t.l("moveend",i))),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,o){return this.easeTo(t.e({bearing:e},i),o)}resetNorth(e,i){return this.rotateTo(0,t.e({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){f.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,o={}){this._moving=!0,i||o.moving||this.fire(new t.l("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.l("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.l("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.l("pitchstart",e)),this._rolling&&!o.rolling&&this.fire(new t.l("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0;}_updateElevation(e){void 0!==this._elevationStart&&void 0!==this._elevationCenter||this._prepareElevation(this.transform.center),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.C.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),o=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:o,zoom:r,roll:a,pitch:s,bearing:n,elevation:l}=e(t);o&&t.setCenter(o),void 0!==l&&t.setElevation(l),void 0!==r&&t.setZoom(r),void 0!==a&&t.setRoll(a),void 0!==s&&t.setPitch(s),void 0!==n&&t.setBearing(n),i.apply(t);}this.transform.apply(i);}_fireMoveEvents(e){this.fire(new t.l("move",e)),this._zooming&&this.fire(new t.l("zoom",e)),this._rotating&&this.fire(new t.l("rotate",e)),this._pitching&&this.fire(new t.l("pitch",e)),this._rolling&&this.fire(new t.l("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const o=this._zooming,r=this._rotating,a=this._pitching,s=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,o&&this.fire(new t.l("zoomend",e)),r&&this.fire(new t.l("rotateend",e)),a&&this.fire(new t.l("pitchend",e)),s&&this.fire(new t.l("rollend",e)),this.fire(new t.l("moveend",e));}flyTo(e,i){if(!e.essential&&s.prefersReducedMotion){const o=t.Q(e,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(o,i)}this.stop(),e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.co},e);const o=this._getTransformForUpdate(),r=o.bearing,a=o.pitch,n=o.roll,l=o.padding,c="bearing"in e?this._normalizeBearing(e.bearing,r):r,h="pitch"in e?+e.pitch:a,u="roll"in e?this._normalizeBearing(e.roll,n):n,d="padding"in e?e.padding:o.padding,_=t.P.convert(e.offset);let p=o.centerPoint.add(_);const m=o.screenPointToLocation(p),f=this.cameraHelper.handleFlyTo(o,{bearing:c,pitch:h,roll:u,padding:d,locationAtOffset:m,offsetAsPoint:_,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(o.width,o.height),b=v/f.scaleOfZoom,x=f.pixelPathLength;"number"==typeof f.scaleOfMinZoom&&(g=Math.sqrt(v/f.scaleOfMinZoom/x*2));const y=g*g;function w(e){const t=(b*b-v*v+(e?-1:1)*y*y*x*x)/(2*(e?b:v)*y*x);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function P(e){return (Math.exp(e)+Math.exp(-e))/2}const C=w(!1);let I=function(e){return P(C)/P(C+g*e)},M=function(e){return v*((P(C)*(T(t=C+g*e)/P(t))-T(C))/y)/x;var t;},S=(w(!0)-C)/g;if(Math.abs(x)<2e-6||!isFinite(S)){if(Math.abs(v-b)<1e-6)return this.easeTo(e,i);const t=b0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*S/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=r!==c,this._pitching=h!==a,this._rolling=u!==n,this._padding=!o.isPaddingEqual(d),this._prepareEase(i,!1),this.terrain&&this._prepareElevation(f.targetCenter),this._ease((s=>{const m=s*S,g=1/I(m),v=M(m);this._rotating&&o.setBearing(t.C.number(r,c,s)),this._pitching&&o.setPitch(t.C.number(a,h,s)),this._rolling&&o.setRoll(t.C.number(n,u,s)),this._padding&&(o.interpolatePadding(l,d,s),p=o.centerPoint.add(_)),f.easeFunc(s,g,v,p),this.terrain&&!e.freezeElevation&&this._updateElevation(s),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=s.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.aO(e,-180,180);const o=Math.abs(e-i);return Math.abs(e-360-i)MapLibre
'};class Da{constructor(e=za){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=n.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=n.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=n.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.sourceCaches;for(const i in t){const o=t[i];if(o.used||o.usedForTerrain){const t=o.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let o=i+1;o=0)return !1;return !0}));const i=e.join(" | ");i!==this._attribHTML&&(this._attribHTML=i,e.length?(this._innerContainer.innerHTML=n.sanitize(i),this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Aa{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=n.create("div","maplibregl-ctrl");const t=n.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){n.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0;}}class La{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}var ka=t.aJ([{name:"a_pos3d",type:"Int16",components:3}]);class Fa extends t.E{constructor(e){super(),this._lastTilesetChange=s.now(),this.sourceCache=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize;}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null;}update(e,i){this.sourceCache.update(e,i),this._renderableTilesKeys=[];const o={};for(const r of ve(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:i,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))o[r.key]=!0,this._renderableTilesKeys.push(r.key),this._tiles[r.key]||(r.terrainRttPosMatrix32f=new Float64Array(16),t.bY(r.terrainRttPosMatrix32f,0,t.$,t.$,0,0,1),this._tiles[r.key]=new re(r,this.tileSize),this._lastTilesetChange=s.now());for(const e in this._tiles)o[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e,t){return t?this._getTerrainCoordsForTileRanges(e,t):this._getTerrainCoordsForRegularTile(e)}_getTerrainCoordsForRegularTile(e){const i={};for(const o of this._renderableTilesKeys){const r=this._tiles[o].tileID,a=e.clone(),s=t.ba();if(r.canonical.equals(e.canonical))t.bY(s,0,t.$,t.$,0,0,1);else if(r.canonical.isChildOf(e.canonical)){const i=r.canonical.z-e.canonical.z,o=r.canonical.x-(r.canonical.x>>i<>i<>i;t.bY(s,0,n,n,0,0,1),t.M(s,s,[-o*n,-a*n,0]);}else {if(!e.canonical.isChildOf(r.canonical))continue;{const i=e.canonical.z-r.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i;t.bY(s,0,t.$,t.$,0,0,1),t.M(s,s,[o*n,a*n,0]),t.N(s,s,[1/2**i,1/2**i,0]);}}a.terrainRttPosMatrix32f=new Float32Array(s),i[o]=a;}return i}_getTerrainCoordsForTileRanges(e,i){const o={};for(const r of this._renderableTilesKeys){const a=this._tiles[r].tileID;if(!this._isWithinTileRanges(a,i))continue;const s=e.clone(),n=t.ba();if(a.canonical.z===e.canonical.z){const i=e.canonical.x-a.canonical.x,o=e.canonical.y-a.canonical.y;t.bY(n,0,t.$,t.$,0,0,1),t.M(n,n,[i*t.$,o*t.$,0]);}else if(a.canonical.z>e.canonical.z){const i=a.canonical.z-e.canonical.z,o=a.canonical.x-(a.canonical.x>>i<>i<>i),l=e.canonical.y-(a.canonical.y>>i),c=t.$>>i;t.bY(n,0,c,c,0,0,1),t.M(n,n,[-o*c+s*t.$,-r*c+l*t.$,0]);}else {const i=e.canonical.z-a.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i)-a.canonical.x,l=(e.canonical.y>>i)-a.canonical.y,c=t.$<i.maxzoom&&(o=i.maxzoom),o=i.minzoom&&(!r||!r.dem);)r=this.sourceCache.getTileByID(e.scaledTo(o--).key);return r}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}_isWithinTileRanges(e,t){return t[e.canonical.z]&&e.canonical.x>=t[e.canonical.z].minTileX&&e.canonical.x<=t[e.canonical.z].maxTileX&&e.canonical.y>=t[e.canonical.z].minTileY&&e.canonical.y<=t[e.canonical.z].maxTileY}}class Ba{constructor(e,t,i){this._meshCache={},this.painter=e,this.sourceCache=new Fa(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(e,i,o,r=t.$){var a;if(!(i>=0&&i=0&&oe.canonical.z&&(e.canonical.z>=o?r=e.canonical.z-o:t.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const a=e.canonical.x-(e.canonical.x>>r<>r<>8<<4|e>>8,i[t+3]=0;const o=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),r=new t.T(e,o,e.gl.RGBA,{premultiply:!1});return r.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=r,r}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(!0);const i=new Uint8Array(4),o=this.painter.context,r=o.gl,a=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),s=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);o.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),r.readPixels(a,n-s-1,1,1,r.RGBA,r.UNSIGNED_BYTE,i),o.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.sourceCache.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<0,r=o&&0===e.canonical.y,a=o&&e.canonical.y===(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const ja={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class Na{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new Oa(e.context,30,t.sourceCache.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.sourceCaches){this._coordsAscending[t]={};const i=e.sourceCaches[t].getVisibleCoordinates(),o=e.sourceCaches[t].getSource(),r=o instanceof X?o.terrainTileRanges:null;for(const e of i){const i=this.terrain.sourceCache.getTerrainCoords(e,r);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._coordsAscendingStr={};for(const t of e._order){const i=e._layers[t],o=i.source;if(ja[i.type]&&!this._coordsAscendingStr[o]){this._coordsAscendingStr[o]={};for(const e in this._coordsAscending[o])this._coordsAscendingStr[o][e]=this._coordsAscending[o][e].map((e=>e.key)).sort().join();}}for(const e of this._renderableTiles)for(const t in this._coordsAscendingStr){const i=this._coordsAscendingStr[t][e.tileID.key];i&&i!==e.rttCoords[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return !1;const o=Object.assign(Object.assign({},i),{isRenderingToTexture:!0}),r=e.type,a=this.painter,s=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(ja[r]&&(this._prevType&&ja[this._prevType]||this._stacks.push([]),this._prevType=r,this._stacks[this._stacks.length-1].push(e.id),!s))return !0;if(ja[this._prevType]||ja[r]&&s){this._prevType=r;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const r of this._renderableTiles){if(this.pool.isFull()&&(Cr(this.painter,this.terrain,this._rttTiles,o),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(r),r.rtt[e]){const t=this.pool.getObjectForId(r.rtt[e].id);if(t.stamp===r.rtt[e].stamp){this.pool.useObject(t);continue}}const s=this.pool.getOrCreateFreeObject();this.pool.useObject(s),this.pool.stampObject(s),r.rtt[e]={id:s.id,stamp:s.stamp},a.context.bindFramebuffer.set(s.fbo.framebuffer),a.context.clear({color:t.bf.transparent,stencil:0}),a.currentStencilSource=void 0;for(let e=0;e{this.startMove(e,n.mousePos(this.element,e)),n.addEventListener(window,"mousemove",this.mousemove),n.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=e=>{this.move(e,n.mousePos(this.element,e));},this.mouseup=e=>{this._rotatePitchHandler.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),n.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.addEventListener(window,"touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHandler.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10,this.element=i;const r=new ia;this._rotatePitchHandler=new Kr({clickTolerance:3,move:(e,r)=>{const a=i.getBoundingClientRect(),s=new t.P((a.bottom-a.top)/2,(a.right-a.left)/2);return {bearingDelta:t.cn(new t.P(e.x,r.y),r,s),pitchDelta:o?-.5*(r.y-e.y):void 0}},moveStateManager:r,enable:!0,assignEvents:()=>{}}),this.map=e,n.addEventListener(i,"mousedown",this.mousedown),n.addEventListener(i,"touchstart",this.touchstart,{passive:!1}),n.addEventListener(i,"touchcancel",this.reset);}startMove(e,t){this._rotatePitchHandler.dragStart(e,t),n.disableDrag();}move(e,t){const i=this.map,{bearingDelta:o,pitchDelta:r}=this._rotatePitchHandler.dragMove(e,t)||{};o&&i.setBearing(i.getBearing()+o),r&&i.setPitch(i.getPitch()+r);}off(){const e=this.element;n.removeEventListener(e,"mousedown",this.mousedown),n.removeEventListener(e,"touchstart",this.touchstart,{passive:!1}),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend),n.removeEventListener(e,"touchcancel",this.reset),this.offTemp();}offTemp(){n.enableDrag(),n.removeEventListener(window,"mousemove",this.mousemove),n.removeEventListener(window,"mouseup",this.mouseup),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend);}}let qa;function Wa(e,i,o,r=!1){if(r||!o.getCoveringTilesDetailsProvider().allowWorldCopies())return null==e?void 0:e.wrap();const a=new t.S(e.lng,e.lat);if(e=new t.S(e.lng,e.lat),i){const r=new t.S(e.lng-360,e.lat),a=new t.S(e.lng+360,e.lat),s=o.locationToScreenPoint(e).distSqr(i);o.locationToScreenPoint(r).distSqr(i)180;){const t=o.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=o.width&&t.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==a.lng&&o.isPointOnMapSurface(o.locationToScreenPoint(e))?e:a}const Ha={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Xa(e,t,i){const o=e.classList;for(const e in Ha)o.remove(`maplibregl-${i}-anchor-${e}`);o.add(`maplibregl-${i}-anchor-${t}`);}class Ka extends t.E{constructor(e){if(super(),this._onKeyPress=e=>{const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{if(!this._map)return;const t=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?void 0:e.type)||"render"===(null==e?void 0:e.type)&&!t)&&this._map.once("render",this._update),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let i="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?i=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(i=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),n.setTransform(this._element,`${Ha[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${i}`),s.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.l("dragstart"))),this.fire(new t.l("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.l("dragend")),this._state="inactive";},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||!1,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(null==e?void 0:e.opacity,null==e?void 0:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.P.convert(e&&e.offset||[0,0]);else {this._defaultMarker=!0,this._element=n.create("div");const i=n.createNS("http://www.w3.org/2000/svg","svg"),o=41,r=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${o}px`),i.setAttributeNS(null,"width",`${r}px`),i.setAttributeNS(null,"viewBox",`0 0 ${r} ${o}`);const a=n.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"stroke","none"),a.setAttributeNS(null,"stroke-width","1"),a.setAttributeNS(null,"fill","none"),a.setAttributeNS(null,"fill-rule","evenodd");const s=n.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"fill-rule","nonzero");const l=n.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"transform","translate(3.0, 29.0)"),l.setAttributeNS(null,"fill","#000000");const c=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const e of c){const t=n.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),l.appendChild(t);}const h=n.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);const u=n.createNS("http://www.w3.org/2000/svg","path");u.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(u);const d=n.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");const _=n.createNS("http://www.w3.org/2000/svg","path");_.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(_);const p=n.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const m=n.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(8.0, 8.0)");const f=n.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#000000"),f.setAttributeNS(null,"opacity","0.25"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962");const g=n.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#FFFFFF"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962"),m.appendChild(f),m.appendChild(g),s.appendChild(l),s.appendChild(h),s.appendChild(d),s.appendChild(p),s.appendChild(m),i.appendChild(s),i.setAttributeNS(null,"height",o*this._scale+"px"),i.setAttributeNS(null,"width",r*this._scale+"px"),this._element.appendChild(i),this._offset=t.P.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),Xa(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),n.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,o=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-t],"bottom-left":[o,-1*(t-i+o)],"bottom-right":[-o,-1*(t-i+o)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=!1){var i,o;const r=null===(i=this._map)||void 0===i?void 0:i.terrain,a=this._map.transform.isLocationOccluded(this._lngLat);if(!r||a){const e=a?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const s=this._map,n=s.terrain.depthAtPoint(this._pos),l=s.terrain.getElevationForLngLatZoom(this._lngLat,s.transform.tileZoom);if(s.transform.lngLatToCameraDepth(this._lngLat,l)-n<.006)return void(this._element.style.opacity=this._opacity);const c=-this._offset.y/s.transform.pixelsPerMeter,h=Math.sin(s.getPitch()*Math.PI/180)*c,u=s.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),d=s.transform.lngLatToCameraDepth(this._lngLat,l+h)-u>.006;(null===(o=this._popup)||void 0===o?void 0:o.isOpen())&&d&&this._popup.remove(),this._element.style.opacity=d?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return (void 0===this._opacity||void 0===e&&void 0===t)&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==e&&(this._opacity=e),void 0!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(!0),this}}const Ya={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let Qa=0,Ja=!1;const es={maxWidth:100,unit:"metric"};function ts(e,t,i){const o=i&&i.maxWidth||100,r=e._container.clientHeight/2,a=e._container.clientWidth/2,s=e.unproject([a-o/2,r]),n=e.unproject([a+o/2,r]),l=Math.round(e.project(n).x-e.project(s).x),c=Math.min(o,l,e._container.clientWidth),h=s.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?is(t,c,i/5280,e._getUIString("ScaleControl.Miles")):is(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?is(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?is(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):is(t,c,h,e._getUIString("ScaleControl.Meters"));}function is(e,t,i,o){const r=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(r/i)+"px",e.innerHTML=`${r} ${o}`;}const os={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1,locationOccludedOpacity:void 0},rs=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function as(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(i,i),"top-right":new t.P(-i,i),bottom:new t.P(0,-e),"bottom-left":new t.P(i,-i),"bottom-right":new t.P(-i,-i),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){const i=t.P.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e["top-left"]||[0,0]),"top-right":t.P.convert(e["top-right"]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e["bottom-left"]||[0,0]),"bottom-right":t.P.convert(e["bottom-right"]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return as(new t.P(0,0))}const ss=i;e.AJAXError=t.cz,e.Event=t.l,e.Evented=t.E,e.LngLat=t.S,e.MercatorCoordinate=t.a1,e.Point=t.P,e.addProtocol=t.cA,e.config=t.a,e.removeProtocol=t.cB,e.AttributionControl=Da,e.BoxZoomHandler=$r,e.CanvasSource=Y,e.CooperativeGesturesHandler=Ca,e.DoubleClickZoomHandler=ba,e.DragPanHandler=wa,e.DragRotateHandler=Ta,e.EdgeInsets=Mt,e.FullscreenControl=class extends t.E{constructor(e={}){super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(e=null==t?void 0:t.shadowRoot)||void 0===e?void 0:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){n.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=n.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);n.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new t.l("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.l("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=H,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.l("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "BACKGROUND":case "BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.l("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.S(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.e({bearing:r},this.options.fitBoundsOptions),s=G.fromLngLat(i,o);this._map.fitBounds(s,a,{geolocateSource:!0});},this._updateMarker=e=>{if(e){const i=new t.S(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this._updateCircleRadiusIfNeeded();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded();},this._onError=e=>{if(this._map){if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Ja)return;this.options.trackUserLocation&&this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.l("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=n.create("button","maplibregl-ctrl-geolocate",this._container),n.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0);},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.w("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=n.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new Ka({element:this._dotElement}),this._circleElement=n.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ka({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onUpdate),this._map.on("move",this._onUpdate),this._map.on("rotate",this._onUpdate),this._map.on("pitch",this._onUpdate)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(e=>{const i=(null==e?void 0:e[0])instanceof ResizeObserverEntry;e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||i||this._map.isZooming()||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.l("trackuserlocationend")),this.fire(new t.l("userlocationlostfocus")));}));}},this.options=t.e({},Ya,e);}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t._(this,arguments,void 0,(function*(e=!1){if(void 0!==qa&&!e)return qa;if(void 0===window.navigator.permissions)return qa=!!window.navigator.geolocation,qa;try{const e=yield window.navigator.permissions.query({name:"geolocation"});qa="denied"!==e.state;}catch(e){qa=!!window.navigator.geolocation;}return qa}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),n.remove(this._container),this._map.off("zoom",this._onUpdate),this._map.off("move",this._onUpdate),this._map.off("rotate",this._onUpdate),this._map.off("pitch",this._onUpdate),this._map=void 0,Qa=0,Ja=!1;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case "WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case "ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadiusIfNeeded(){const e=this._userLocationDotMarker.getLngLat();if(!(this.options.showUserLocation&&this.options.showAccuracyCircle&&this._accuracy&&e))return;const t=this._map.project(e),i=this._map.unproject([t.x+100,t.y]),o=e.distanceTo(i)/100,r=2*this._accuracy/o;this._circleElement.style.width=`${r.toFixed(2)}px`,this._circleElement.style.height=`${r.toFixed(2)}px`;}trigger(){if(!this._setup)return t.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case "OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.l("trackuserlocationstart"));break;case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":case "BACKGROUND_ERROR":Qa--,Ja=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new t.l("trackuserlocationend"));break;case "BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.l("trackuserlocationstart")),this.fire(new t.l("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case "WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),Qa++,Qa>1?(e={maximumAge:6e5,timeout:0},Ja=!0):(e=this.options.positionOptions,Ja=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||void 0===e?void 0:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||void 0===e?void 0:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=n.create("button","maplibregl-ctrl-globe",this._container),n.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0;}},e.Hash=Er,e.ImageSource=X,e.KeyboardHandler=pa,e.LngLatBounds=G,e.LogoControl=Aa,e.Map=class extends Ra{constructor(e){var i,o;t.cw.mark(t.cx.create);const r=Object.assign(Object.assign(Object.assign({},Ga),e),{canvasContextAttributes:Object.assign(Object.assign({},Ga.canvasContextAttributes),e.canvasContextAttributes)});if(null!=r.minZoom&&null!=r.maxZoom&&r.minZoom>r.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=r.minPitch&&null!=r.maxPitch&&r.minPitch>r.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=r.minPitch&&r.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=r.maxPitch&&r.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const a=new Lt,s=new Ot;if(void 0!==r.minZoom&&a.setMinZoom(r.minZoom),void 0!==r.maxZoom&&a.setMaxZoom(r.maxZoom),void 0!==r.minPitch&&a.setMinPitch(r.minPitch),void 0!==r.maxPitch&&a.setMaxPitch(r.maxPitch),void 0!==r.renderWorldCopies&&a.setRenderWorldCopies(r.renderWorldCopies),super(a,s,{bearingSnap:r.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new La,this._controls=[],this._mapId=t.a7(),this._contextLost=e=>{e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new t.l("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._setupPainter(),this.resize(),this._update(),this.fire(new t.l("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update();},this._interactive=r.interactive,this._maxTileCacheSize=r.maxTileCacheSize,this._maxTileCacheZoomLevels=r.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},r.canvasContextAttributes),this._trackResize=!0===r.trackResize,this._bearingSnap=r.bearingSnap,this._centerClampedToGround=r.centerClampedToGround,this._refreshExpiredTiles=!0===r.refreshExpiredTiles,this._fadeDuration=r.fadeDuration,this._crossSourceCollisions=!0===r.crossSourceCollisions,this._collectResourceTiming=!0===r.collectResourceTiming,this._locale=Object.assign(Object.assign({},Ua),r.locale),this._clickTolerance=r.clickTolerance,this._overridePixelRatio=r.pixelRatio,this._maxCanvasSize=r.maxCanvasSize,this.transformCameraUpdate=r.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===r.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=p.addThrottleControl((()=>this.isMoving())),this._requestManager=new m(r.transformRequest),"string"==typeof r.container){if(this._container=document.getElementById(r.container),!this._container)throw new Error(`Container '${r.container}' not found.`)}else {if(!(r.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=r.container;}if(r.maxBounds&&this.setMaxBounds(r.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0);})),this.once("idle",(()=>{this._idleTriggered=!0;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let e=!1;const t=Sr((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{e?t(i):e=!0;})),this._resizeObserver.observe(this._container);}this.handlers=new Ea(this,r),this._hash=r.hash&&new Er("string"==typeof r.hash&&r.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:r.center,elevation:r.elevation,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,roll:r.roll}),r.bounds&&(this.resize(),this.fitBounds(r.bounds,t.e({},r.fitBoundsOptions,{duration:0}))));const n="string"==typeof r.style||!("globe"===(null===(o=null===(i=r.style)||void 0===i?void 0:i.projection)||void 0===o?void 0:o.type));this.resize(null,n),this._localIdeographFontFamily=r.localIdeographFontFamily,this._validateStyle=r.validateStyle,r.style&&this.setStyle(r.style,{localIdeographFontFamily:r.localIdeographFontFamily}),r.attributionControl&&this.addControl(new Da("boolean"==typeof r.attributionControl?void 0:r.attributionControl)),r.maplibreLogo&&this.addControl(new Aa,r.logoPosition),this.on("style.load",(()=>{if(n||this._resizeTransform(),this.transform.unmodified){const e=t.Q(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.l(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.l(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.l("sourcedataabort",e));}));}_getMapId(){return this._mapId}setGlobalStateProperty(e,t){return this.style.setGlobalStateProperty(e,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(e,i){if(void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.k(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const o=e.onAdd(this);this._controls.push(e);const r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.k(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}coveringTiles(e){return ve(this.transform,e)}calculateCameraOptionsFromTo(e,t,i,o){return null==o&&this.terrain&&(o=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(e,t,i,o)}resize(e,i=!0){const[o,r]=this._containerDimensions(),a=this._getClampedPixelRatio(o,r);if(this._resizeCanvas(o,r,a),this.painter.resize(o,r,a),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const t=this._getClampedPixelRatio(o,r);this._resizeCanvas(o,r,t),this.painter.resize(o,r,t);}this._resizeTransform(i);const s=!this._moving;return s&&(this.stop(),this.fire(new t.l("movestart",e)).fire(new t.l("move",e))),this.fire(new t.l("resize",e)),s&&this.fire(new t.l("moveend",e)),this}_resizeTransform(e=!0){var t;const[i,o]=this._containerDimensions();this.transform.resize(i,o,e),null===(t=this._requestedCameraState)||void 0===t||t.resize(i,o,e);}_getClampedPixelRatio(e,t){const{0:i,1:o}=this._maxCanvasSize,r=this.getPixelRatio(),a=e*r,s=t*r;return Math.min(a>i?i/a:1,s>o?o/s:1)*r}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&void 0!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(G.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom)return this.transform.setMinZoom(e),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(e),this._update(),this.getZoom()>e&&this.setZoom(e),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.setMinPitch(e),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch)return this.transform.setMaxPitch(e),this._update(),this.getPitch()>e&&this.setPitch(e),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.S.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||void 0===e?void 0:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||void 0===e?void 0:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||void 0===e?void 0:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e))),s=0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[];s.length?o||(o=!0,i.call(this,new jr(e,this,r.originalEvent,{features:s}))):o=!1;};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:()=>{o=!1;}}}}if("mouseleave"===e||"mouseout"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e)));(0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[]).length?o=!0:o&&(o=!1,i.call(this,new jr(e,this,r.originalEvent)));},a=t=>{o&&(o=!1,i.call(this,new jr(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:a}}}{const o=e=>{const o=t.filter((e=>this.getLayer(e))),r=0!==o.length?this.queryRenderedFeatures(e.point,{layers:o}):[];r.length&&(e.features=r,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:o}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const o=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in r.delegates)this.off(e,r.delegates[e]);return void o.splice(e,1)}}}on(e,t,i){if(void 0===i)return super.on(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);this._saveDelegatedListener(e,r);for(const e in r.delegates)this.on(e,r.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,o,i);}}}once(e,t,i){if(void 0===i)return super.once(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);for(const t in r.delegates){const a=r.delegates[t];r.delegates[t]=(...t)=>{this._removeDelegatedListener(e,o,i),a(...t);};}this._saveDelegatedListener(e,r);for(const e in r.delegates)this.once(e,r.delegates[e]);return this}off(e,t,i){return void 0===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let o;const r=e instanceof t.P||Array.isArray(e),a=r?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(r?{}:e)||{},a instanceof t.P||"number"==typeof a[0])o=[t.P.convert(a)];else {const e=t.P.convert(a[0]),i=t.P.convert(a[1]);o=[e,new t.P(i.x,e.y),i,new t.P(e.x,i.y),e];}return this.style.queryRenderedFeatures(o,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return !1!==(i=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,o;if(t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const r=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new wi(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,r):this.style.loadJSON(e,t,r),this):(null===(o=null===(i=this.style)||void 0===i?void 0:i.projection)||void 0===o||o.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new wi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){if("string"==typeof e){const o=this._requestManager.transformRequest(e,"Style");t.j(o,new AbortController).then((e=>{this._updateDiff(e.data,i);})).catch((e=>{e&&this.fire(new t.k(e));}));}else "object"==typeof e&&this._updateDiff(e,i);}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(o){t.w(`Unable to perform style diff: ${o.message||o.error||o}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():t.w("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){const i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.k(new Error(`There is no source with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.sourceCaches[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const o=this.style._layers[i];"hillshade"===o.type&&o.source===e.source&&t.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality."),"color-relief"===o.type&&o.source===e.source&&t.w("You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");}this.terrain=new Ba(this.painter,i,e),this.painter.renderToTexture=new Na(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{var i;"style"===t.dataType?this.terrain.sourceCache.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),"image"===(null===(i=t.source)||void 0===i?void 0:i.type)?this.terrain.sourceCache.freeRtt():this.terrain.sourceCache.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.l("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||void 0===e?void 0:e.options)&&void 0!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.sourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}}return !0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}setSourceTileLodParams(e,t,i){if(i){const o=this.getSource(i);if(!o)throw new Error(`There is no source with ID "${i}", cannot set LOD parameters`);o.calculateTileZoom=me(Math.max(1,e),Math.max(1,t));}else for(const i in this.style.sourceCaches)this.style.sourceCaches[i].getSource().calculateTileZoom=me(Math.max(1,e),Math.max(1,t));return this._update(!0),this}refreshTiles(e,i){const o=this.style.sourceCaches[e];if(!o)throw new Error(`There is no source cache with ID "${e}", cannot refresh tile`);void 0===i?o.reload(!0):o.refreshTiles(i.map((e=>new t.a4(e.z,e.x,e.y))));}addImage(e,i,o={}){const{pixelRatio:r=1,sdf:a=!1,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u}=o;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.b(i))){if(void 0===i.width||void 0===i.height)return this.fire(new t.k(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:o,height:s,data:d}=i,_=i;return this.style.addImage(e,{data:new t.R({width:o,height:s},new Uint8Array(d)),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:o,height:d,data:_}=s.getImageData(i);this.style.addImage(e,{data:new t.R({width:o,height:d},_),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0});}}updateImage(e,i){const o=this.style.getImage(e);if(!o)return this.fire(new t.k(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const r=i instanceof HTMLImageElement||t.b(i)?s.getImageData(i):i,{width:a,height:n,data:l}=r;if(void 0===a||void 0===n)return this.fire(new t.k(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(a!==o.data.width||n!==o.data.height)return this.fire(new t.k(new Error("The width and height of the updated image must be that same as the previous version of the image")));const c=!(i instanceof HTMLImageElement||t.b(i));return o.data.replace(l,c),this.style.updateImage(e,o),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.k(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(e);}loadImage(e){return p.getImage(this._requestManager.transformRequest(e,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(!0)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,o={}){return this.style.setPaintProperty(e,t,i,o),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,o={}){return this.style.setLayoutProperty(e,t,i,o),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(!0);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=n.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=n.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),o=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],o);const r=this._controlContainer=n.create("div","maplibregl-control-container",e),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{a[e]=n.create("div",`maplibregl-ctrl-${e} `,r);})),this._container.addEventListener("scroll",this._onMapScroll,!1);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0});let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:!0});let i=null;if(i=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e),!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new Mr(i,this.transform),l.testSupport(i);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.l("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){var i,o,r,a,n;const l=this._idleTriggered?this._fadeDuration:0,c=(null===(i=this.style.projection)||void 0===i?void 0:i.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let h=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,i=s.now();this.style.zoomHistory.update(e,i);const o=new t.F(e,{now:i,fadeDuration:l,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),r=o.crossFadingFactor();1===r&&r===this._crossFadingFactor||(h=!0,this._crossFadingFactor=r),this.style.update(o);}const u=(null===(o=this.style.projection)||void 0===o?void 0:o.transitionState)>0!==c;null===(r=this.style.projection)||void 0===r||r.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(a=this.style.projection)||void 0===a?void 0:a.transitionState,null===(n=this.style.projection)||void 0===n?void 0:n.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||u)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,l,this._crossSourceCollisions,u),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:l,showPadding:this.showPadding}),this.fire(new t.l("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,t.cw.mark(t.cx.load),this.fire(new t.l("load"))),this.style&&(this.style.hasTransitions()||h)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const d=this._sourcesDirty||this._styleDirty||this._placementDirty;return d||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.l("idle")),!this._loaded||this._fullyLoaded||d||(this._fullyLoaded=!0,t.cw.mark(t.cx.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),p.removeThrottleControl(this._imageQueueHandle),null===(e=this._resizeObserver)||void 0===e||e.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?void 0:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),n.remove(this._canvasContainer),n.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),t.cw.clearMetrics(),this._removed=!0,this.fire(new t.l("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,s.frame(this._frameRequest,(e=>{t.cw.frame(e),this._frameRequest=null;try{this._render(e);}catch(e){if(!t.cy(e)&&!function(e){return e.message===qo}(e))throw e}}),(()=>{})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return Za}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}},e.MapMouseEvent=jr,e.MapTouchEvent=Nr,e.MapWheelEvent=Ur,e.Marker=Ka,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.e({},Va,e),this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=n.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new $a(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){n.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=n.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.E{constructor(e){super(),this._updateOpacity=()=>{void 0!==this.options.locationOccludedOpacity&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:"");},this.remove=()=>(this._content&&n.remove(this._content),this._container&&(n.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new t.l("close"))),this),this._onMouseUp=e=>{this._update(e.point);},this._onMouseMove=e=>{this._update(e.point);},this._onDrag=e=>{this._update(e.point);},this._update=e=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=n.create("div","maplibregl-popup",this._map.getContainer()),this._tip=n.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer");}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),this._trackPointer&&!e)return;const t=this._flatPos=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&e?e:this._map.transform.locationToScreenPoint(this._lngLat));let i=this.options.anchor;const o=as(this.options.offset);if(!i){const e=this._container.offsetWidth,r=this._container.offsetHeight;let a;a=t.y+o.bottom.ythis._map.transform.height-r?["bottom"]:[],t.xthis._map.transform.width-e/2&&a.push("right"),i=0===a.length?"bottom":a.join("-");}let r=t.add(o[i]);this.options.subpixelPositioning||(r=r.round()),n.setTransform(this._container,`${Ha[i]} translate(${r.x}px,${r.y}px)`),Xa(this._container,i,"popup"),this._updateOpacity();},this._onClose=()=>{this.remove();},this.options=t.e(Object.create(os),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.l("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let o;for(i.innerHTML=e;o=i.firstChild,o;)t.appendChild(o);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||void 0===e?void 0:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=n.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}_createCloseButton(){this.options.closeButton&&(this._closeButton=n.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(rs);e&&e.focus();}},e.RasterDEMTileSource=W,e.RasterTileSource=q,e.ScaleControl=class{constructor(e){this._onMove=()=>{ts(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,ts(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},es),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){n.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;}},e.ScrollZoomHandler=va,e.Style=wi,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=n.create("button","maplibregl-ctrl-terrain",this._container),n.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){n.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0;}},e.TwoFingersTouchPitchHandler=da,e.TwoFingersTouchRotateHandler=ha,e.TwoFingersTouchZoomHandler=la,e.TwoFingersTouchZoomRotateHandler=Pa,e.VectorTileSource=$,e.VideoSource=K,e.addSourceType=(e,i)=>t._(void 0,void 0,void 0,(function*(){if(J(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{Q[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=A;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(R),A=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},e.createTileMesh=Xt,e.getMaxParallelImageRequests=function(){return t.a.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},e.getVersion=function(){return ss},e.getWorkerCount=function(){return z.workerCount},e.getWorkerUrl=function(){return t.a.WORKER_URL},e.importScriptInWorkers=function(e){return B().broadcast("IS",e)},e.prewarm=function(){k().acquire(R);},e.setMaxParallelImageRequests=function(e){t.a.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setRTLTextPlugin=function(e,t){return oe().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){z.workerCount=e;},e.setWorkerUrl=function(e){t.a.WORKER_URL=e;};})); + +// +// Our custom intro provides a specialized "define()" function, called by the +// AMD modules below, that sets up the worker blob URL and then executes the +// main module, storing its exported value as 'maplibregl' + + +var maplibregl$1 = maplibregl; + +return maplibregl$1; + +})); +//# sourceMappingURL=maplibre-gl.js.map diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt new file mode 100644 index 0000000..624d1f1 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2023, MapTiler +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js new file mode 100644 index 0000000..0fe7116 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js @@ -0,0 +1,14 @@ +(function(j,ee){typeof exports=="object"&&typeof module<"u"?ee(exports,require("maplibre-gl")):typeof define=="function"&&define.amd?define(["exports","maplibre-gl"],ee):(j=typeof globalThis<"u"?globalThis:j||self,ee(j.maplibreglMaptilerGeocoder={},j.maplibregl))})(this,function(j,ee){"use strict";var Ws=Object.defineProperty;var bn=j=>{throw TypeError(j)};var Gs=(j,ee,me)=>ee in j?Ws(j,ee,{enumerable:!0,configurable:!0,writable:!0,value:me}):j[ee]=me;var A=(j,ee,me)=>Gs(j,typeof ee!="symbol"?ee+"":ee,me),wn=(j,ee,me)=>ee.has(j)||bn("Cannot "+me);var ue=(j,ee,me)=>(wn(j,ee,"read from private field"),me?me.call(j):ee.get(j)),Vt=(j,ee,me)=>ee.has(j)?bn("Cannot add the same private member more than once"):ee instanceof WeakSet?ee.add(j):ee.set(j,me),kt=(j,ee,me,dt)=>(wn(j,ee,"write to private field"),dt?dt.call(j,me):ee.set(j,me),me);var fn,cn;function me(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const dt=me(ee);function ne(){}function Ln(i,e){for(const t in e)i[t]=e[t];return i}function yi(i){return i()}function vi(){return Object.create(null)}function Ue(i){i.forEach(yi)}function bi(i){return typeof i=="function"}function Ke(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}let Rt;function ye(i,e){return i===e?!0:(Rt||(Rt=document.createElement("a")),Rt.href=e,i===Rt.href)}function _n(i){return Object.keys(i).length===0}function Sn(i,e,t,n){if(i){const r=wi(i,e,t,n);return i[0](r)}}function wi(i,e,t,n){return i[1]&&n?Ln(t.ctx.slice(),i[1](n(e))):t.ctx}function xn(i,e,t,n){return i[2],e.dirty}function Tn(i,e,t,n,r,u){if(r){const a=wi(e,t,n,u);i.p(a,r)}}function Mn(i){if(i.ctx.length>32){const e=[],t=i.ctx.length/32;for(let n=0;ni.removeEventListener(e,t,n)}function Nn(i){return function(e){return e.preventDefault(),i.call(this,e)}}function S(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function kn(i){return Array.from(i.childNodes)}function gt(i,e){e=""+e,i.data!==e&&(i.data=e)}function Ei(i,e){i.value=e??""}function Ie(i,e,t){i.classList.toggle(e,!!t)}function On(i,e,{bubbles:t=!1,cancelable:n=!1}={}){return new CustomEvent(i,{detail:e,bubbles:t,cancelable:n})}let mt;function pt(i){mt=i}function Li(){if(!mt)throw new Error("Function called outside component initialization");return mt}function Rn(i){Li().$$.on_destroy.push(i)}function _i(){const i=Li();return(e,t,{cancelable:n=!1}={})=>{const r=i.$$.callbacks[e];if(r){const u=On(e,t,{cancelable:n});return r.slice().forEach(a=>{a.call(i,u)}),!u.defaultPrevented}return!0}}function Pn(i,e){const t=i.$$.callbacks[e.type];t&&t.slice().forEach(n=>n.call(this,e))}const ut=[],Yt=[];let at=[];const Si=[],In=Promise.resolve();let Qt=!1;function An(){Qt||(Qt=!0,In.then(xi))}function Xt(i){at.push(i)}const Jt=new Set;let ft=0;function xi(){if(ft!==0)return;const i=mt;do{try{for(;fti.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),at=e}const It=new Set;let nt;function yt(){nt={r:0,c:[],p:nt}}function vt(){nt.r||Ue(nt.c),nt=nt.p}function re(i,e){i&&i.i&&(It.delete(i),i.i(e))}function fe(i,e,t,n){if(i&&i.o){if(It.has(i))return;It.add(i),nt.c.push(()=>{It.delete(i),n&&(t&&i.d(1),n())}),i.o(e)}else n&&n()}function Ti(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function Gn(i,e){fe(i,1,1,()=>{e.delete(i.key)})}function Dn(i,e,t,n,r,u,a,o,g,c,E,_){let M=i.length,R=u.length,k=M;const I={};for(;k--;)I[i[k].key]=k;const C=[],O=new Map,x=new Map,N=[];for(k=R;k--;){const W=_(r,u,k),s=t(W);let l=a.get(s);l?N.push(()=>l.p(W,e)):(l=c(s,W),l.c()),O.set(s,C[k]=l),s in I&&x.set(s,Math.abs(k-I[s]))}const P=new Set,B=new Set;function z(W){re(W,1),W.m(o,E),a.set(W.key,W),E=W.first,R--}for(;M&&R;){const W=C[R-1],s=i[M-1],l=W.key,f=s.key;W===s?(E=W.first,M--,R--):O.has(f)?!a.has(l)||P.has(l)?z(W):B.has(f)?M--:x.get(l)>x.get(f)?(B.add(l),z(W)):(P.add(f),M--):(g(s,a),M--)}for(;M--;){const W=i[M];O.has(W.key)||g(W,a)}for(;R;)z(C[R-1]);return Ue(N),C}function Qe(i){i&&i.c()}function qe(i,e,t){const{fragment:n,after_update:r}=i.$$;n&&n.m(e,t),Xt(()=>{const u=i.$$.on_mount.map(yi).filter(bi);i.$$.on_destroy?i.$$.on_destroy.push(...u):Ue(u),i.$$.on_mount=[]}),r.forEach(Xt)}function Fe(i,e){const t=i.$$;t.fragment!==null&&(Wn(t.after_update),Ue(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function zn(i,e){i.$$.dirty[0]===-1&&(ut.push(i),An(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<{const k=R.length?R[0]:M;return c.ctx&&r(c.ctx[_],c.ctx[_]=k)&&(!c.skip_bound&&c.bound[_]&&c.bound[_](k),E&&zn(i,_)),M}):[],c.update(),E=!0,Ue(c.before_update),c.fragment=n?n(c.ctx):!1,e.target){if(e.hydrate){const _=kn(e.target);c.fragment&&c.fragment.l(_),_.forEach($)}else c.fragment&&c.fragment.c();e.intro&&re(i.$$.fragment),qe(i,e.target,e.anchor),xi()}pt(g)}class Je{constructor(){A(this,"$$");A(this,"$$set")}$destroy(){Fe(this,1),this.$destroy=ne}$on(e,t){if(!bi(t))return ne;const n=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return n.push(t),()=>{const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}$set(e){this.$$set&&!_n(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Un="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Un);function qn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M13.12.706a.982.982 0 0 0-1.391 0L6.907 5.517 2.087.696a.982.982 0 1 0-1.391 1.39l4.821 4.821L.696 11.73a.982.982 0 1 0 1.39 1.39l4.821-4.821 4.822 4.821a.982.982 0 1 0 1.39-1.39L8.298 6.908l4.821-4.822a.988.988 0 0 0 0-1.38Z"),S(e,"viewBox","0 0 14 14"),S(e,"width","13"),S(e,"height","13"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Mi extends Je{constructor(e){super(),Xe(this,e,null,qn,Ke,{})}}function Fn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M15 0C6.705 0 0 6.705 0 15C0 23.295 6.705 30 15 30C23.295 30 30 23.295 30 15C30 6.705 23.295 0 15 0ZM22.5 20.385L20.385 22.5L15 17.115L9.615 22.5L7.5 20.385L12.885 15L7.5 9.615L9.615 7.5L15 12.885L20.385 7.5L22.5 9.615L17.115 15L22.5 20.385Z"),S(e,"viewBox","0 0 30 30"),S(e,"fill","none"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"class","svelte-d2loi5")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Ci extends Je{constructor(e){super(),Xe(this,e,null,Fn,Ke,{})}}function jn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"area.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"area.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Zn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"reverse.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"reverse.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Hn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"poi.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"poi.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Vn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"postal_code.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"postal_code.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Kn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"street.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"street.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Yn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"road.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"road.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Qn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"housenumber.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"housenumber.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Xn(i){let e,t,n,r;return{c(){e=Y("img"),ye(e.src,t=i[5])||S(e,"src",t),S(e,"alt",i[4]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(u,a){te(u,e,a),n||(r=he(e,"error",i[14]),n=!0)},p(u,a){a&32&&!ye(e.src,t=u[5])&&S(e,"src",t),a&16&&S(e,"alt",u[4]),a&128&&S(e,"title",u[7])},d(u){u&&$(e),n=!1,r()}}}function Jn(i){let e,t;return{c(){e=Y("div"),S(e,"class","sprite-icon svelte-w9y5n9"),S(e,"style",t=` + width: ${i[6].width/xe}px; + height: ${i[6].height/xe}px; + background-image: url(${i[3]}sprite${$t}.png); + background-position: -${i[6].x/xe}px -${i[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `),S(e,"title",i[7])},m(n,r){te(n,e,r)},p(n,r){r&72&&t!==(t=` + width: ${n[6].width/xe}px; + height: ${n[6].height/xe}px; + background-image: url(${n[3]}sprite${$t}.png); + background-position: -${n[6].x/xe}px -${n[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `)&&S(e,"style",t),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Ni(i){let e,t;return{c(){e=Y("span"),t=Ye(i[7]),S(e,"class","secondary svelte-w9y5n9")},m(n,r){te(n,e,r),V(e,t)},p(n,r){r&128&>(t,n[7])},d(n){n&&$(e)}}}function $n(i){let e,t,n,r,u,a,o,g,c,E=(i[8]?i[0].place_name:i[0].place_name.replace(/,.*/,""))+"",_,M,R=i[2]==="always"||i[2]!=="never"&&!i[0].address&&!i[0].id.startsWith("road.")&&!i[0].id.startsWith("address.")&&!i[0].id.startsWith("postal_code.")&&(!i[0].id.startsWith("poi.")||!i[5])&&!i[8],k,I,C=(i[8]?"":i[0].place_name.replace(/[^,]*,?\s*/,""))+"",O,x,N,P,B,z;function W(m,h){return h&1&&(t=null),h&1&&(n=null),h&1&&(r=null),h&1&&(u=null),Oe&&m[6]?Jn:m[5]?Xn:m[0].address?Qn:(t==null&&(t=!!m[0].id.startsWith("road.")),t?Yn:(n==null&&(n=!!m[0].id.startsWith("address.")),n?Kn:(r==null&&(r=!!m[0].id.startsWith("postal_code.")),r?Vn:(u==null&&(u=!!m[0].id.startsWith("poi.")),u?Hn:m[8]?Zn:jn))))}let s=W(i,-1),l=s(i),f=R&&Ni(i);return{c(){e=Y("li"),l.c(),a=we(),o=Y("span"),g=Y("span"),c=Y("span"),_=Ye(E),M=we(),f&&f.c(),k=we(),I=Y("span"),O=Ye(C),S(c,"class","primary svelte-w9y5n9"),S(g,"class","svelte-w9y5n9"),S(I,"class","line2 svelte-w9y5n9"),S(o,"class","texts svelte-w9y5n9"),S(e,"tabindex","-1"),S(e,"role","option"),S(e,"aria-selected",x=i[1]==="selected"),S(e,"aria-checked",N=i[1]==="picked"),S(e,"class",P=Pt(i[1])+" svelte-w9y5n9")},m(m,h){te(m,e,h),l.m(e,null),V(e,a),V(e,o),V(o,g),V(g,c),V(c,_),V(g,M),f&&f.m(g,null),V(o,k),V(o,I),V(I,O),B||(z=[he(e,"mouseenter",i[13]),he(e,"focus",i[15]),he(e,"click",i[16])],B=!0)},p(m,[h]){s===(s=W(m,h))&&l?l.p(m,h):(l.d(1),l=s(m),l&&(l.c(),l.m(e,a))),h&257&&E!==(E=(m[8]?m[0].place_name:m[0].place_name.replace(/,.*/,""))+"")&>(_,E),h&293&&(R=m[2]==="always"||m[2]!=="never"&&!m[0].address&&!m[0].id.startsWith("road.")&&!m[0].id.startsWith("address.")&&!m[0].id.startsWith("postal_code.")&&(!m[0].id.startsWith("poi.")||!m[5])&&!m[8]),R?f?f.p(m,h):(f=Ni(m),f.c(),f.m(g,null)):f&&(f.d(1),f=null),h&257&&C!==(C=(m[8]?"":m[0].place_name.replace(/[^,]*,?\s*/,""))+"")&>(O,C),h&2&&x!==(x=m[1]==="selected")&&S(e,"aria-selected",x),h&2&&N!==(N=m[1]==="picked")&&S(e,"aria-checked",N),h&2&&P!==(P=Pt(m[1])+" svelte-w9y5n9")&&S(e,"class",P)},i:ne,o:ne,d(m){m&&$(e),l.d(),f&&f.d(),B=!1,Ue(z)}}}const ki=typeof devicePixelRatio>"u"?1:devicePixelRatio>1.25,$t=ki?"@2x":"",xe=ki?2:1;let Oe,At;function er(i,e,t){let n,r,u,{feature:a}=e,{style:o="default"}=e,{showPlaceType:g}=e,{missingIconsCache:c}=e,{iconsBaseUrl:E}=e;const _=_i();let M,R,k,I;function C(){At??(At=fetch(`${E}sprite${$t}.json`).then(s=>s.json()).then(s=>{Oe=s}).catch(()=>{Oe=null}))}function O(){R&&c.add(R),x()}function x(){Oe!==void 0?N():(C(),At==null||At.then(N))}function N(){do{if(I--,t(4,M=n==null?void 0:n[I]),t(6,k=M?Oe==null?void 0:Oe.icons[M]:void 0),k)break;t(5,R=M?E+M.replace(/ /g,"_")+".svg":void 0)}while(I>-1&&(!R||c.has(R)))}function P(s){Pn.call(this,i,s)}const B=()=>O(),z=()=>_("select",void 0),W=s=>{document.activeElement!==s.target&&_("select",void 0)};return i.$$set=s=>{"feature"in s&&t(0,a=s.feature),"style"in s&&t(1,o=s.style),"showPlaceType"in s&&t(2,g=s.showPlaceType),"missingIconsCache"in s&&t(11,c=s.missingIconsCache),"iconsBaseUrl"in s&&t(3,E=s.iconsBaseUrl)},i.$$.update=()=>{var s,l,f,m,h;i.$$.dirty&1&&t(12,n=(s=a.properties)==null?void 0:s.categories),i.$$.dirty&1&&t(8,r=a.place_type[0]==="reverse"),i.$$.dirty&1&&t(7,u=((f=(l=a.properties)==null?void 0:l.categories)==null?void 0:f.join(", "))??((h=(m=a.properties)==null?void 0:m.place_type_name)==null?void 0:h[0])??a.place_type[0]),i.$$.dirty&4096&&(I=(n==null?void 0:n.length)??0,x())},[a,o,g,E,M,R,k,u,r,_,O,c,n,P,B,z,W]}class tr extends Je{constructor(e){super(),Xe(this,e,er,$n,Ke,{feature:0,style:1,showPlaceType:2,missingIconsCache:11,iconsBaseUrl:3})}}function ir(i){let e;return{c(){e=Y("div"),e.innerHTML='',S(e,"class","svelte-1ocfouu")},m(t,n){te(t,e,n)},p:ne,i:ne,o:ne,d(t){t&&$(e)}}}class nr extends Je{constructor(e){super(),Xe(this,e,null,ir,Ke,{})}}function rr(i){let e,t,n;return{c(){e=ke("svg"),t=ke("path"),S(t,"stroke-width","4"),S(t,"d","M 5,33.103579 C 5,17.607779 18.457,5 35,5 C 51.543,5 65,17.607779 65,33.103579 C 65,56.388679 40.4668,76.048179 36.6112,79.137779 C 36.3714,79.329879 36.2116,79.457979 36.1427,79.518879 C 35.8203,79.800879 35.4102,79.942779 35,79.942779 C 34.5899,79.942779 34.1797,79.800879 33.8575,79.518879 C 33.7886,79.457979 33.6289,79.330079 33.3893,79.138079 C 29.5346,76.049279 5,56.389379 5,33.103579 Z M 35.0001,49.386379 C 43.1917,49.386379 49.8323,42.646079 49.8323,34.331379 C 49.8323,26.016779 43.1917,19.276479 35.0001,19.276479 C 26.8085,19.276479 20.1679,26.016779 20.1679,34.331379 C 20.1679,42.646079 26.8085,49.386379 35.0001,49.386379 Z"),S(t,"class","svelte-gzo3ar"),S(e,"width",n=i[0]==="list"?20:void 0),S(e,"viewBox","0 0 70 85"),S(e,"fill","none"),S(e,"class","svelte-gzo3ar"),Ie(e,"in-map",i[0]!=="list"),Ie(e,"list-icon",i[0]==="list")},m(r,u){te(r,e,u),V(e,t)},p(r,[u]){u&1&&n!==(n=r[0]==="list"?20:void 0)&&S(e,"width",n),u&1&&Ie(e,"in-map",r[0]!=="list"),u&1&&Ie(e,"list-icon",r[0]==="list")},i:ne,o:ne,d(r){r&&$(e)}}}function sr(i,e,t){let{displayIn:n}=e;return i.$$set=r=>{"displayIn"in r&&t(0,n=r.displayIn)},[n]}class or extends Je{constructor(e){super(),Xe(this,e,sr,rr,Ke,{displayIn:0})}}function lr(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M30.003-26.765C13.46-26.765 0-14.158 0 1.337c0 23.286 24.535 42.952 28.39 46.04.24.192.402.316.471.376.323.282.732.424 1.142.424.41 0 .82-.142 1.142-.424.068-.06.231-.183.471-.376 3.856-3.09 28.39-22.754 28.39-46.04 0-15.495-13.46-28.102-30.003-28.102Zm1.757 12.469c4.38 0 7.858 1.052 10.431 3.158 2.595 2.105 3.89 4.913 3.89 8.422 0 2.34-.53 4.362-1.593 6.063-1.063 1.702-3.086 3.616-6.063 5.742-2.042 1.51-3.337 2.659-3.89 3.446-.532.787-.8 1.82-.8 3.096v1.914h-8.449V15.18c0-2.041.434-3.815 1.306-5.325.872-1.51 2.467-3.118 4.785-4.82 2.233-1.594 3.7-2.89 4.402-3.889a5.582 5.582 0 0 0 1.087-3.35c0-1.382-.51-2.435-1.531-3.158-1.02-.723-2.45-1.087-4.28-1.087-3.19 0-6.826 1.047-10.91 3.131l-3.472-6.986c4.742-2.659 9.77-3.992 15.087-3.992Zm-1.88 37.324c1.765 0 3.124.472 4.08 1.408.98.936 1.47 2.276 1.47 4.02 0 1.68-.49 3.007-1.47 3.985-.977.957-2.336 1.435-4.08 1.435-1.787 0-3.171-.465-4.15-1.4-.978-.958-1.47-2.298-1.47-4.02 0-1.787.48-3.14 1.436-4.054.957-.915 2.355-1.374 4.184-1.374Z"),S(e,"viewBox","0 0 60.006 21.412"),S(e,"width","14"),S(e,"height","20"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class ur extends Je{constructor(e){super(),Xe(this,e,null,lr,Ke,{})}}function ar(i){let e,t,n;return{c(){e=ke("svg"),t=ke("circle"),n=ke("path"),S(t,"cx","4.789"),S(t,"cy","4.787"),S(t,"r","3.85"),S(t,"class","svelte-1aq105l"),S(n,"d","M12.063 12.063 7.635 7.635"),S(n,"class","svelte-1aq105l"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"width","13"),S(e,"height","13"),S(e,"viewBox","0 0 13 13"),S(e,"class","svelte-1aq105l")},m(r,u){te(r,e,u),V(e,t),V(e,n)},p:ne,i:ne,o:ne,d(r){r&&$(e)}}}class fr extends Je{constructor(e){super(),Xe(this,e,null,ar,Ke,{})}}function cr(i,e,t){const n=e[1],r=e[0],u=n-r;return i===n&&t?i:((i-r)%u+u)%u+r}function Bt(i){const e=[...i];return e[2]Math.abs((e[0]-360+e[2])/2)?e[0]-=360:e[2]+=360),e}let bt;async function hr(i,e,t){const n=i==null?void 0:i.getCenterAndZoom();for(const r of e??[])if(!(n&&(r.minZoom!=null&&r.minZoom>n[0]||r.maxZoom!=null&&r.maxZoomDate.now()){if(!bt.coords)break e;return bt.coords}let u;try{return u=await new Promise((a,o)=>{t.signal.addEventListener("abort",()=>{o(Error("aborted"))}),navigator.geolocation.getCurrentPosition(g=>{a([g.coords.longitude,g.coords.latitude].map(c=>c.toFixed(6)).join(","))},g=>{o(g)},r)}),u}catch{}finally{r.cachedLocationExpiry&&(bt={time:Date.now(),coords:u})}if(t.signal.aborted)return}if(r.type==="server-geolocation")return"ip";if(n&&r.type==="map-center")return n[1].toFixed(6)+","+n[2].toFixed(6)}}const dr=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(EAST|WEST|[EW])?$/i,Oi=/^([+-]?[0-8]?[0-9])\s+([0-5]?[0-9]\.\d{3,})[\s,]{1,}([+-]?[0-1]?[0-9]?[0-9])\s+([0-5]?[0-9]\.\d{3,})$/,Ri=/^(NORTH|SOUTH|[NS])?[\s]*([+-]?[0-8]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(NORTH|SOUTH|[NS])?[\s]*[,/;]?[\s]*(EAST|WEST|[EW])?[\s]*([+-]?[0-1]?[0-9]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(EAST|WEST|[EW])?$/i,Pi=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(EAST|WEST|[EW])?$/i,Ii=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)\s*(EAST|WEST|[EW])?$/i,Ai=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|’’|´´|["″”\.])?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|´´|’’|["″”\.])?\s*(EAST|WEST|[EW])?$/i;function gr(i){if(!["DMS","DM","DD"].includes(i))throw new Error("invalid format specified");if(this.decimalCoordinates&&this.decimalCoordinates.trim()){const e=this.decimalCoordinates.split(",").map(R=>Number(R.trim())),t=Number(e[0]),n=Number(e[1]),r=Math.abs(t),u=Math.abs(n),a=t>0?"N":"S",o=n>0?"E":"W";let g;i=="DD"&&(g=`${r}° ${a}, ${u}° ${o}`);const c=Math.floor(r),E=Math.floor(u),_=(r-c)*60,M=(u-E)*60;if(i=="DM"){let R=Bi(_,3).toFixed(3).padStart(6,"0"),k=Bi(M,3).toFixed(3).padStart(6,"0");R.endsWith(".000")&&k.endsWith(".000")&&(R=R.replace(/\.000$/,""),k=k.replace(/\.000$/,"")),g=`${c}° ${R}' ${a}, ${E}° ${k}' ${o}`}if(i=="DMS"){const R=Math.floor(_),k=Math.floor(M);let I=((_-R)*60).toFixed(1).padStart(4,"0"),C=((M-k)*60).toFixed(1).padStart(4,"0");const O=R.toString().padStart(2,"0"),x=k.toString().padStart(2,"0");I.endsWith(".0")&&C.endsWith(".0")&&(I=I.replace(/\.0$/,""),C=C.replace(/\.0$/,"")),g=`${c}° ${O}' ${I}" ${a}, ${E}° ${x}' ${C}" ${o}`}return g}else throw new Error("no decimal coordinates to convert")}function Bi(i,e){const t=Math.pow(10,e);return Math.round((i+Number.EPSILON)*t)/t}function ei(i,e){e||(e=5),i=i.replace(/\s+/g," ").trim();let t=null,n=null,r="",u="",a=null,o=[],g=!1;if(dr.test(i))throw new Error("invalid coordinate value");if(Oi.test(i))if(o=Oi.exec(i),g=wt(o),g)t=Math.abs(o[1])+o[2]/60,Number(o[1])<0&&(t*=-1),n=Math.abs(o[3])+o[4]/60,Number(o[3])<0&&(n*=-1),a="DM";else throw new Error("invalid coordinate format");else if(Ri.test(i))if(o=Ri.exec(i),g=wt(o),g){if(t=o[2],n=o[6],t.includes(",")&&(t=t.replace(",",".")),n.includes(",")&&(n=n.replace(",",".")),a="DD",Number(Math.round(t))==Number(t))throw new Error("integer only coordinate provided");if(Number(Math.round(n))==Number(n))throw new Error("integer only coordinate provided");o[1]?(r=o[1],u=o[5]):o[4]&&(r=o[4],u=o[8])}else throw new Error("invalid decimal coordinate format");else if(Pi.test(i))if(o=Pi.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[9])),o[11]&&(n+=o[11]/60),o[13]&&(n+=o[13].replace(",",".")/3600),parseInt(o[9])<0&&(n=-1*n),o[1]?(r=o[1],u=o[8]):o[7]&&(r=o[7],u=o[14]);else throw new Error("invalid DMS coordinates format");else if(Ii.test(i))if(o=Ii.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6]/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12]/60),o[14]&&(n+=o[14]/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid DMS coordinates format");else if(Ai.test(i)){if(o=Ai.exec(i),g=wt(o),o.filter(c=>c).length<=5)throw new Error("invalid coordinates format");if(g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4].replace(",",".")/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12].replace(",",".")/60),o[14]&&(n+=o[14].replace(",",".")/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid coordinates format")}if(g){if(Math.abs(n)>=180)throw new Error("invalid longitude value");if(Math.abs(t)>=90)throw new Error("invalid latitude value");if(r&&!u||!r&&u)throw new Error("invalid coordinates value");if(r&&r==u)throw new Error("invalid coordinates format");t.toString().includes(",")&&(t=t.replace(",",".")),n.toString().includes(",")&&(n=n.replace(",","."));let c=/S|SOUTH/i;c.test(r)&&t>0&&(t=-1*t),c=/W|WEST/i,c.test(u)&&n>0&&(n=-1*n);const E=o[0].trim();let _,M;const R=/[,/;\u0020]/g,k=E.match(R);if(k==null){const O=Math.floor(i.length/2);_=E.substring(0,O).trim(),M=E.substring(O).trim()}else{let O;k.length%2==1?O=Math.floor(k.length/2):O=k.length/2-1;let x=0;if(O==0)x=E.indexOf(k[0]),_=E.substring(0,x).trim(),M=E.substring(x+1).trim();else{let N=0,P=0;for(;N<=O;)x=E.indexOf(k[N],P),P=x+1,N++;_=E.substring(0,x).trim(),M=E.substring(x+1).trim()}}const I=_.split(".");if(I.length==2&&I[1]==0&&I[1].length!=2)throw new Error("invalid coordinates format");const C=M.split(".");if(C.length==2&&C[1]==0&&C[1].length!=2)throw new Error("invalid coordinates format");if(/^\d+$/.test(_)||/^\d+$/.test(M))throw new Error("degree only coordinate/s provided");return t=Number(Number(t).toFixed(e)),n=Number(Number(n).toFixed(e)),Object.freeze({verbatimCoordinates:E,verbatimLatitude:_,verbatimLongitude:M,decimalLatitude:t,decimalLongitude:n,decimalCoordinates:`${t},${n}`,originalFormat:a,closeEnough:mr,toCoordinateFormat:gr})}else throw new Error("coordinates pattern match failed")}function wt(i){if(!isNaN(i[0]))return!1;const e=[...i];if(e.shift(),e.length%2>0)return!1;const t=/^[-+]?\d+([\.,]\d+)?$/,n=/[eastsouthnorthwest]+/i,r=e.length/2;for(let u=0;u{e.decimalLatitude?i.push(e):i.push({...e,...vr})}),[...i,...br,...wr]}const Lr=Er();ei.formats=Lr.map(i=>i.verbatimCoordinates);const _r=ei;function Gi(i,e,t){const n=i.slice();return n[97]=e[t],n[99]=t,n}function Di(i){let e,t,n,r,u;return t=new Mi({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[3]),S(e,"class","svelte-bz0zu3")},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[78]),r=!0)},p(a,o){(!n||o[0]&8)&&S(e,"title",a[3])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function zi(i){let e,t;return e=new nr({}),{c(){Qe(e.$$.fragment)},m(n,r){qe(e,n,r),t=!0},i(n){t||(re(e.$$.fragment,n),t=!0)},o(n){fe(e.$$.fragment,n),t=!1},d(n){Fe(e,n)}}}function Ui(i){let e,t,n,r,u;return t=new ur({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[10]),S(e,"class","svelte-bz0zu3"),Ie(e,"active",i[0])},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[79]),r=!0)},p(a,o){(!n||o[0]&1024)&&S(e,"title",a[10]),(!n||o[0]&1)&&Ie(e,"active",a[0])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function Sr(i){let e,t=[],n=new Map,r,u,a,o=Ti(i[13]);const g=c=>c[97].id+(c[97].address?","+c[97].address:"");for(let c=0;c{B=null}),vt()):B?(B.p(d,v),v[0]&1048576&&re(B,1)):(B=Di(d),B.c(),re(B,1),B.m(c,E)),d[20]?z?v[0]&1048576&&re(z,1):(z=zi(),z.c(),re(z,1),z.m(c,null)):z&&(yt(),fe(z,1,1,()=>{z=null}),vt()),(!O||v[0]&2)&&Ie(c,"displayable",d[1]!==""),d[6]==="button"?W?(W.p(d,v),v[0]&64&&re(W,1)):(W=Ui(d),W.c(),re(W,1),W.m(n,M)):W&&(yt(),fe(W,1,1,()=>{W=null}),vt()),l&&l.p&&(!O||v[2]&128)&&Tn(l,s,d,d[69],O?xn(s,d[69],v,null):Mn(d[69]),null);let p=k;k=h(d),k===p?~k&&m[k].p(d,v):(I&&(yt(),fe(m[p],1,1,()=>{m[p]=null}),vt()),~k?(I=m[k],I?I.p(d,v):(I=m[k]=f[k](d),I.c()),re(I,1),I.m(t,null)):I=null),(!O||v[0]&4&&C!==(C=Pt(d[2])+" svelte-bz0zu3"))&&S(t,"class",C),(!O||v[0]&38)&&Ie(t,"can-collapse",d[5]&&d[1]==="")},i(d){O||(re(P),re(u.$$.fragment,d),re(B),re(z),re(W),re(l,d),re(I),O=!0)},o(d){fe(P),fe(u.$$.fragment,d),fe(B),fe(z),fe(W),fe(l,d),fe(I),O=!1},d(d){d&&($(e),$(t)),Fe(u),i[72](null),B&&B.d(),z&&z.d(),W&&W.d(),l&&l.d(d),~k&&m[k].d(),x=!1,Ue(N)}}}function Nr(i,e,t){let n,r,u,{$$slots:a={},$$scope:o}=e;const g={continental_marine:4,country:4,major_landform:8,region:5,subregion:6,county:7,joint_municipality:8,joint_submunicipality:9,municipality:10,municipal_district:11,locality:12,neighbourhood:13,place:14,postal_code:14,road:16,poi:17,address:18,"poi.peak":15,"poi.shop":18,"poi.cafe":18,"poi.restaurant":18,"poi.aerodrome":13};let{class:c=void 0}=e,{apiKey:E=void 0}=e,{bbox:_=void 0}=e,{clearButtonTitle:M="clear"}=e,{clearOnBlur:R=!1}=e,{clearListOnPick:k=!1}=e,{keepListOpen:I=!1}=e,{collapsed:C=!1}=e,{country:O=void 0}=e,{debounceSearch:x=200}=e,{enableReverse:N="never"}=e,{errorMessage:P="Something went wrong…"}=e,{filter:B=()=>!0}=e,{flyTo:z=!0}=e,{fuzzyMatch:W=!0}=e,{language:s=void 0}=e,{limit:l=void 0}=e;const f=41415112612;let{reverseGeocodingLimit:m=f}=e,{mapController:h=void 0}=e,{minLength:d=2}=e,{noResultsMessage:v="Oops! Looks like you're trying to predict something that's not quite right. We can't seem to find what you're looking for. Maybe try double-checking your spelling or try a different search term. Keep on typing - we'll do our best to get you where you need to go!"}=e,{placeholder:p="Search"}=e,{proximity:y=[{type:"server-geolocation"}]}=e,{reverseActive:b=N==="always"}=e,{reverseButtonTitle:w="toggle reverse geocoding"}=e,{searchValue:T=""}=e,{pickedResultStyle:G="full-geometry"}=e,{showPlaceType:D="if-needed"}=e,{showResultsWhileTyping:H=!0}=e,{selectFirst:Q=!0}=e,{flyToSelected:se=!1}=e,{markerOnSelected:Z=!0}=e,{types:K=void 0}=e;const de=[];let{reverseGeocodingTypes:He=de}=e,{exhaustiveReverseGeocoding:st=!1}=e,{excludeTypes:ot=!1}=e;const Le=void 0;let{reverseGeocodingExcludeTypes:We=Le}=e,{zoom:pe=g}=e,{apiUrl:ge="https://api.maptiler.com/geocoding"}=e,{fetchParameters:ie={}}=e,{iconsBaseUrl:hn="https://cdn.maptiler.com/maptiler-geocoding-control/v2.1.7/icons/"}=e,{adjustUrlQuery:ui=()=>{}}=e,{adjustUrl:ai=()=>{}}=e;function gs(L){Pe.focus(L)}function ms(){Pe.blur()}function dn(L,le=!0,ae=!1){t(1,T=L),le?(t(15,X=-1),mn()):(pn(void 0,!ae,ae),setTimeout(()=>{Pe.focus(),Pe.select()}))}function ps(){t(13,F=void 0),t(14,U=void 0),t(15,X=-1)}function ys(){t(64,ce=[]),t(14,U=void 0)}let F,ce,U,gn="",Pe,X=-1,Ge,Zt=[],lt,ct,ht,fi,Ve=!1;const vs=new Set,tt=_i();Rn(()=>{h&&(h.setEventHandler(void 0),h.indicateReverse(!1),h.setSelectedMarker(-1),h.setFeatures(void 0,void 0,!1))});function mn(L){if(t(17,Ve=!1),ct&&(clearTimeout(ct),ct=void 0),X>-1&&F)t(14,U=F[X]),t(1,T=U.place_type[0]==="reverse"?U.place_name:U.place_name.replace(/,.*/,"")),t(19,Ge=void 0),t(64,ce=void 0),t(15,X=-1);else if(T){const le=L||!ci(T);hi(T,{exact:!0}).then(()=>{t(64,ce=F),t(14,U=void 0),le&&bs()}).catch(ae=>t(19,Ge=ae))}}function ci(L){try{return _r(L,6)}catch{return!1}}async function hi(L,{byId:le=!1,exact:ae=!1}={}){var Se,De,it;t(19,Ge=void 0),lt==null||lt.abort();const _e=new AbortController;t(20,lt=_e);try{const J=ci(L),Mt=new URL(ge+"/"+encodeURIComponent(J?J.decimalLongitude+","+J.decimalLatitude:L)+".json"),Ne=Mt.searchParams;s!==void 0&&Ne.set("language",Array.isArray(s)?s.join(","):s??"");const[mi]=(h==null?void 0:h.getCenterAndZoom())??[];let ze=(Se=!J||He===de?K:He)==null?void 0:Se.map(ve=>typeof ve=="string"?ve:mi===void 0||(ve[0]??0)<=mi&&mi<(ve[1]??1/0)?ve[2]:void 0).filter(ve=>ve!==void 0);ze&&(ze=[...new Set(ze)],Ne.set("types",ze.join(",")));const vn=!J||We===Le?ot:We;if(vn&&Ne.set("excludeTypes",String(vn)),_&&Ne.set("bbox",_.map(ve=>ve.toFixed(6)).join(",")),O&&Ne.set("country",Array.isArray(O)?O.join(","):O),!le&&!J){const ve=await hr(h,y,_e);ve&&Ne.set("proximity",ve),(ae||!H)&&Ne.set("autocomplete","false"),Ne.set("fuzzyMatch",String(W))}const Ct=m===f?l:m;Ct!==void 0&&Ct>1&&(ze==null?void 0:ze.length)!==1&&console.warn("For reverse geocoding when limit > 1 then types must contain single value."),J?(Ct===1||Ct!==void 0&&(st||(ze==null?void 0:ze.length)===1))&&Ne.set("limit",String(Ct)):l!==void 0&&Ne.set("limit",String(l)),E&&Ne.set("key",E),ui(Ne),ai(Mt);const Bs=Mt.searchParams.get("types")===""&&Mt.searchParams.get("excludeTypes")!=="true",Ht=Mt.toString();if(Ht===gn){le?(k&&t(13,F=void 0),t(14,U=Zt[0])):(t(13,F=Zt),((De=F[X])==null?void 0:De.id)!==(r==null?void 0:r.id)&&t(15,X=-1));return}gn=Ht;let Nt;if(Bs)Nt={type:"FeatureCollection",features:[]};else{const ve=await fetch(Ht,{signal:_e.signal,...ie});if(!ve.ok)throw new Error(await ve.text());Nt=await ve.json()}tt("response",{url:Ht,featureCollection:Nt}),le?(k&&t(13,F=void 0),t(14,U=Nt.features[0]),Zt=[U]):(t(13,F=Nt.features.filter(B)),J&&F.unshift({type:"Feature",properties:{},id:"reverse_"+J.decimalLongitude+"_"+J.decimalLatitude,text:J.decimalLatitude+", "+J.decimalLongitude,place_name:J.decimalLatitude+", "+J.decimalLongitude,place_type:["reverse"],center:[J.decimalLongitude,J.decimalLatitude],bbox:[J.decimalLongitude,J.decimalLatitude,J.decimalLongitude,J.decimalLatitude],geometry:{type:"Point",coordinates:[J.decimalLongitude,J.decimalLatitude]}}),Zt=F,((it=F[X])==null?void 0:it.id)!==(r==null?void 0:r.id)&&t(15,X=-1),J&&Pe.focus())}catch(J){if(J&&typeof J=="object"&&"name"in J&&J.name==="AbortError")return;throw J}finally{_e===lt&&t(20,lt=void 0)}}function bs(){var _e;if(!(ce!=null&&ce.length)||!z)return;const L=[180,90,-180,-90],le=!ce.some(Se=>!Se.matching_text);let ae;for(const Se of ce){const De=Tt(Se);if(ae=ae===void 0?De:De===void 0?ae:Math.max(ae,De),le||!Se.matching_text)for(const it of[0,1,2,3])L[it]=Math[it<2?"min":"max"](L[it],((_e=Se.bbox)==null?void 0:_e[it])??Se.center[it%2])}h&&ce.length>0&&(U&&L[0]===L[2]&&L[1]===L[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(L),50,ae))}function di(){!U||!h||(!U.bbox||U.bbox[0]===U.bbox[2]&&U.bbox[1]===U.bbox[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(U.bbox),50,Tt(U)))}function Tt(L){var ae;if(!L.bbox||L.bbox[0]!==L.bbox[2]&&L.bbox[1]!==L.bbox[3])return;const le=L.id.replace(/\..*/,"");return(Array.isArray((ae=L.properties)==null?void 0:ae.categories)?L.properties.categories.reduce((_e,Se)=>{const De=pe[le+"."+Se];return _e===void 0?De:De===void 0?_e:Math.max(_e,De)},void 0):void 0)??pe[le]}function ws(L){t(0,b=N==="always"),t(13,F=void 0),t(14,U=void 0),t(15,X=-1),dn(L[1].toFixed(6)+", "+cr(L[0],[-180,180],!0).toFixed(6),!1,!0)}function Es(L){if(!F)return;let le=L.key==="ArrowDown"?1:L.key==="ArrowUp"?-1:0;le&&(Pe.focus(),t(17,Ve=!0),L.preventDefault(),U&&X===-1&&t(15,X=F.findIndex(ae=>ae.id===(U==null?void 0:U.id))),X===(U||Q?0:-1)&&le===-1&&t(15,X=F.length),t(15,X+=le),X>=F.length&&t(15,X=-1),X<0&&(U||Q)&&t(15,X=0))}function pn(L,le=!0,ae=!1){if(t(19,Ge=void 0),t(14,U=void 0),t(17,Ve=!0),H||ae){if(ct&&clearTimeout(ct),T.length{hi(_e).catch(Se=>t(19,Ge=Se))},le?x:0)}else t(13,F=void 0),t(19,Ge=void 0)}function gi(L){U&&(U==null?void 0:U.id)===(L==null?void 0:L.id)?di():(t(14,U=L),t(1,T=L.place_name))}function yn(L){t(15,X=L)}function Ls(){(!Q||U)&&t(15,X=-1),se&&di()}const _s=()=>Pe.focus();function Ss(L){Yt[L?"unshift":"push"](()=>{Pe=L,t(18,Pe)})}function xs(){T=this.value,t(1,T),t(17,Ve),t(31,R),t(16,ht)}const Ts=()=>t(17,Ve=!0),Ms=()=>t(17,Ve=!1),Cs=()=>t(17,Ve=!0),Ns=()=>t(14,U=void 0),ks=()=>{t(1,T=""),t(14,U=void 0),Pe.focus()},Os=()=>t(0,b=!b),Rs=()=>t(19,Ge=void 0),Ps=L=>yn(L),Is=L=>gi(L),As=()=>{};return i.$$set=L=>{"class"in L&&t(2,c=L.class),"apiKey"in L&&t(29,E=L.apiKey),"bbox"in L&&t(30,_=L.bbox),"clearButtonTitle"in L&&t(3,M=L.clearButtonTitle),"clearOnBlur"in L&&t(31,R=L.clearOnBlur),"clearListOnPick"in L&&t(32,k=L.clearListOnPick),"keepListOpen"in L&&t(4,I=L.keepListOpen),"collapsed"in L&&t(5,C=L.collapsed),"country"in L&&t(33,O=L.country),"debounceSearch"in L&&t(34,x=L.debounceSearch),"enableReverse"in L&&t(6,N=L.enableReverse),"errorMessage"in L&&t(7,P=L.errorMessage),"filter"in L&&t(35,B=L.filter),"flyTo"in L&&t(36,z=L.flyTo),"fuzzyMatch"in L&&t(37,W=L.fuzzyMatch),"language"in L&&t(38,s=L.language),"limit"in L&&t(39,l=L.limit),"reverseGeocodingLimit"in L&&t(40,m=L.reverseGeocodingLimit),"mapController"in L&&t(41,h=L.mapController),"minLength"in L&&t(42,d=L.minLength),"noResultsMessage"in L&&t(8,v=L.noResultsMessage),"placeholder"in L&&t(9,p=L.placeholder),"proximity"in L&&t(43,y=L.proximity),"reverseActive"in L&&t(0,b=L.reverseActive),"reverseButtonTitle"in L&&t(10,w=L.reverseButtonTitle),"searchValue"in L&&t(1,T=L.searchValue),"pickedResultStyle"in L&&t(44,G=L.pickedResultStyle),"showPlaceType"in L&&t(11,D=L.showPlaceType),"showResultsWhileTyping"in L&&t(45,H=L.showResultsWhileTyping),"selectFirst"in L&&t(46,Q=L.selectFirst),"flyToSelected"in L&&t(47,se=L.flyToSelected),"markerOnSelected"in L&&t(48,Z=L.markerOnSelected),"types"in L&&t(49,K=L.types),"reverseGeocodingTypes"in L&&t(50,He=L.reverseGeocodingTypes),"exhaustiveReverseGeocoding"in L&&t(51,st=L.exhaustiveReverseGeocoding),"excludeTypes"in L&&t(52,ot=L.excludeTypes),"reverseGeocodingExcludeTypes"in L&&t(53,We=L.reverseGeocodingExcludeTypes),"zoom"in L&&t(54,pe=L.zoom),"apiUrl"in L&&t(55,ge=L.apiUrl),"fetchParameters"in L&&t(56,ie=L.fetchParameters),"iconsBaseUrl"in L&&t(12,hn=L.iconsBaseUrl),"adjustUrlQuery"in L&&t(57,ui=L.adjustUrlQuery),"adjustUrl"in L&&t(58,ai=L.adjustUrl),"$$scope"in L&&t(69,o=L.$$scope)},i.$$.update=()=>{if(i.$$.dirty[0]&64&&t(0,b=N==="always"),i.$$.dirty[0]&16384|i.$$.dirty[1]&8192&&G!=="marker-only"&&U&&!U.address&&U.geometry.type==="Point"&&U.place_type[0]!=="reverse"&&hi(U.id,{byId:!0}).catch(L=>t(19,Ge=L)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1058|i.$$.dirty[2]&8&&(h&&U&&U.id!==fi&&z&&(di(),k&&t(13,F=void 0),t(64,ce=void 0),t(15,X=-1)),t(65,fi=U==null?void 0:U.id)),i.$$.dirty[0]&196608|i.$$.dirty[1]&1&&setTimeout(()=>{t(16,ht=Ve),R&&!ht&&t(1,T="")}),i.$$.dirty[0]&8194|i.$$.dirty[1]&2048&&T.length{switch(L.type){case"mapClick":b&&ws(L.coordinates);break;case"markerClick":{const le=F==null?void 0:F.find(ae=>ae.id===L.id);le&&gi(le)}break;case"markerMouseEnter":ce&&t(15,X=ht?(F==null?void 0:F.findIndex(le=>le.id===L.id))??-1:-1);break;case"markerMouseLeave":ce&&t(15,X=-1);break}}),i.$$.dirty[0]&40960&&t(66,r=F==null?void 0:F[X]),i.$$.dirty[1]&66592|i.$$.dirty[2]&16&&h&&r&&z&&se&&h.flyTo(r.center,Tt(r)),i.$$.dirty[1]&8192&&t(68,n=G==="full-geometry-including-polygon-center-marker"),i.$$.dirty[1]&132096|i.$$.dirty[2]&64&&(Z||h==null||h.setFeatures(void 0,void 0,n)),i.$$.dirty[0]&16384|i.$$.dirty[1]&132096|i.$$.dirty[2]&84&&h&&Z&&!ce&&(h.setFeatures(r?[r]:void 0,U,n),h.setSelectedMarker(r?0:-1)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1024|i.$$.dirty[2]&68&&h&&h.setFeatures(ce,U,n),i.$$.dirty[0]&32768|i.$$.dirty[1]&1024|i.$$.dirty[2]&4&&ce&&h&&h.setSelectedMarker(X),i.$$.dirty[0]&2|i.$$.dirty[1]&1024&&h){const L=ci(T);h.setReverseMarker(L?[L.decimalLongitude,L.decimalLatitude]:void 0)}i.$$.dirty[2]&16&&tt("select",{feature:r}),i.$$.dirty[0]&16384&&tt("pick",{feature:U}),i.$$.dirty[0]&73744&&t(67,u=!!(F!=null&&F.length)&&(ht||I)),i.$$.dirty[2]&32&&tt("optionsvisibilitychange",{optionsVisible:u}),i.$$.dirty[0]&8192&&tt("featureslisted",{features:F}),i.$$.dirty[2]&4&&tt("featuresmarked",{features:ce}),i.$$.dirty[0]&1&&tt("reversetoggle",{reverse:b}),i.$$.dirty[0]&2&&tt("querychange",{query:T}),i.$$.dirty[0]&1|i.$$.dirty[1]&1024&&h&&h.indicateReverse(b)},[b,T,c,M,I,C,N,P,v,p,w,D,hn,F,U,X,ht,Ve,Pe,Ge,lt,vs,mn,Es,pn,gi,yn,Ls,g,E,_,R,k,O,x,B,z,W,s,l,m,h,d,y,G,H,Q,se,Z,K,He,st,ot,We,pe,ge,ie,ui,ai,gs,ms,dn,ps,ys,ce,fi,r,u,n,o,a,_s,Ss,xs,Ts,Ms,Cs,Ns,ks,Os,Rs,Ps,Is,As]}let kr=class extends Je{constructor(e){super(),Xe(this,e,Nr,Cr,Ke,{ZOOM_DEFAULTS:28,class:2,apiKey:29,bbox:30,clearButtonTitle:3,clearOnBlur:31,clearListOnPick:32,keepListOpen:4,collapsed:5,country:33,debounceSearch:34,enableReverse:6,errorMessage:7,filter:35,flyTo:36,fuzzyMatch:37,language:38,limit:39,reverseGeocodingLimit:40,mapController:41,minLength:42,noResultsMessage:8,placeholder:9,proximity:43,reverseActive:0,reverseButtonTitle:10,searchValue:1,pickedResultStyle:44,showPlaceType:11,showResultsWhileTyping:45,selectFirst:46,flyToSelected:47,markerOnSelected:48,types:49,reverseGeocodingTypes:50,exhaustiveReverseGeocoding:51,excludeTypes:52,reverseGeocodingExcludeTypes:53,zoom:54,apiUrl:55,fetchParameters:56,iconsBaseUrl:12,adjustUrlQuery:57,adjustUrl:58,focus:59,blur:60,setQuery:61,clearList:62,clearMap:63},null,[-1,-1,-1,-1])}get ZOOM_DEFAULTS(){return this.$$.ctx[28]}get focus(){return this.$$.ctx[59]}get blur(){return this.$$.ctx[60]}get setQuery(){return this.$$.ctx[61]}get clearList(){return this.$$.ctx[62]}get clearMap(){return this.$$.ctx[63]}};function Et(i,e,t={}){const n={type:"Feature"};return(t.id===0||t.id)&&(n.id=t.id),t.bbox&&(n.bbox=t.bbox),n.properties=e||{},n.geometry=i,n}function ti(i,e,t={}){for(const r of i){if(r.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(r[r.length-1].length!==r[0].length)throw new Error("First and last Position are not equivalent.");for(let u=0;u_?w.c=w.e=null:s.e=10;v/=10,d++);d>_?w.c=w.e=null:(w.e=d,w.c=[s]);return}b=String(s)}else{if(!Or.test(b=String(s)))return n(w,b,p);w.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(v=b.search(/e/i))>0?(d<0&&(d=v),d+=+b.slice(v+1),b=b.substring(0,v)):d<0&&(d=b.length)}else{if(oe(l,2,C.length,"Base"),l==10&&O)return w=new x(s),z(w,a+w.e+1,o);if(b=String(s),p=typeof s=="number"){if(s*0!=0)return n(w,b,p,l);if(w.s=1/s<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(ji+s)}else w.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(f=C.slice(0,l),d=v=0,y=b.length;vd){d=y;continue}}else if(!h&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){h=!0,v=-1,d=0;continue}return n(w,String(s),p,l)}p=!1,b=t(b,l,10,w.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(v=0;b.charCodeAt(v)===48;v++);for(y=b.length;b.charCodeAt(--y)===48;);if(b=b.slice(v,++y)){if(y-=v,p&&x.DEBUG&&y>15&&(s>Zi||s!==Te(s)))throw Error(ji+w.s*s);if((d=d-v-1)>_)w.c=w.e=null;else if(d=-1e9&&h<=Ee&&h===Te(h)){if(m[0]===0){if(h===0&&m.length===1)return!0;break e}if(l=(h+1)%q,l<1&&(l+=q),String(m[0]).length==l){for(l=0;l=Re||f!==Te(f))break e;if(f!==0)return!0}}}else if(m===null&&h===null&&(d===null||d===1||d===-1))return!0;throw Error(be+"Invalid BigNumber: "+s)},x.maximum=x.max=function(){return P(arguments,-1)},x.minimum=x.min=function(){return P(arguments,1)},x.random=function(){var s=9007199254740992,l=Math.random()*s&2097151?function(){return Te(Math.random()*s)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(f){var m,h,d,v,p,y=0,b=[],w=new x(u);if(f==null?f=a:oe(f,0,Ee),v=ii(f/q),M)if(crypto.getRandomValues){for(m=crypto.getRandomValues(new Uint32Array(v*=2));y>>11),p>=9e15?(h=crypto.getRandomValues(new Uint32Array(2)),m[y]=h[0],m[y+1]=h[1]):(b.push(p%1e14),y+=2);y=v/2}else if(crypto.randomBytes){for(m=crypto.randomBytes(v*=7);y=9e15?crypto.randomBytes(7).copy(m,y):(b.push(p%1e14),y+=7);y=v/7}else throw M=!1,Error(be+"crypto unavailable");if(!M)for(;y=10;p/=10,y++);yh-1&&(p[v+1]==null&&(p[v+1]=0),p[v+1]+=p[v]/h|0,p[v]%=h)}return p.reverse()}return function(f,m,h,d,v){var p,y,b,w,T,G,D,H,Q=f.indexOf("."),se=a,Z=o;for(Q>=0&&(w=k,k=0,f=f.replace(".",""),H=new x(m),G=H.pow(f.length-Q),k=w,H.c=l(je(Ce(G.c),G.e,"0"),10,h,s),H.e=H.c.length),D=l(f,m,h,v?(p=C,s):(p=s,C)),b=w=D.length;D[--w]==0;D.pop());if(!D[0])return p.charAt(0);if(Q<0?--b:(G.c=D,G.e=b,G.s=d,G=e(G,H,se,Z,h),D=G.c,T=G.r,b=G.e),y=b+se+1,Q=D[y],w=h/2,T=T||y<0||D[y+1]!=null,T=Z<4?(Q!=null||T)&&(Z==0||Z==(G.s<0?3:2)):Q>w||Q==w&&(Z==4||T||Z==6&&D[y-1]&1||Z==(G.s<0?8:7)),y<1||!D[0])f=T?je(p.charAt(1),-se,p.charAt(0)):p.charAt(0);else{if(D.length=y,T)for(--h;++D[--y]>h;)D[y]=0,y||(++b,D=[1].concat(D));for(w=D.length;!D[--w];);for(Q=0,f="";Q<=w;f+=p.charAt(D[Q++]));f=je(f,b,p.charAt(0))}return f}}(),e=function(){function s(m,h,d){var v,p,y,b,w=0,T=m.length,G=h%$e,D=h/$e|0;for(m=m.slice();T--;)y=m[T]%$e,b=m[T]/$e|0,v=D*y+b*G,p=G*y+v%$e*$e+w,w=(p/d|0)+(v/$e|0)+D*b,m[T]=p%d;return w&&(m=[w].concat(m)),m}function l(m,h,d,v){var p,y;if(d!=v)y=d>v?1:-1;else for(p=y=0;ph[p]?1:-1;break}return y}function f(m,h,d,v){for(var p=0;d--;)m[d]-=p,p=m[d]1;m.splice(0,1));}return function(m,h,d,v,p){var y,b,w,T,G,D,H,Q,se,Z,K,de,He,st,ot,Le,We,pe=m.s==h.s?1:-1,ge=m.c,ie=h.c;if(!ge||!ge[0]||!ie||!ie[0])return new x(!m.s||!h.s||(ge?ie&&ge[0]==ie[0]:!ie)?NaN:ge&&ge[0]==0||!ie?pe*0:pe/0);for(Q=new x(pe),se=Q.c=[],b=m.e-h.e,pe=d+b+1,p||(p=Re,b=Me(m.e/q)-Me(h.e/q),pe=pe/q|0),w=0;ie[w]==(ge[w]||0);w++);if(ie[w]>(ge[w]||0)&&b--,pe<0)se.push(1),T=!0;else{for(st=ge.length,Le=ie.length,w=0,pe+=2,G=Te(p/(ie[0]+1)),G>1&&(ie=s(ie,G,p),ge=s(ge,G,p),Le=ie.length,st=ge.length),He=Le,Z=ge.slice(0,Le),K=Z.length;K=p/2&&ot++;do{if(G=0,y=l(ie,Z,Le,K),y<0){if(de=Z[0],Le!=K&&(de=de*p+(Z[1]||0)),G=Te(de/ot),G>1)for(G>=p&&(G=p-1),D=s(ie,G,p),H=D.length,K=Z.length;l(D,Z,H,K)==1;)G--,f(D,Le=10;pe/=10,w++);z(Q,d+(Q.e=w+b*q-1)+1,v,T)}else Q.e=b,Q.r=+T;return Q}}();function N(s,l,f,m){var h,d,v,p,y;if(f==null?f=o:oe(f,0,8),!s.c)return s.toString();if(h=s.c[0],v=s.e,l==null)y=Ce(s.c),y=m==1||m==2&&(v<=g||v>=c)?Gt(y,v):je(y,v,"0");else if(s=z(new x(s),l,f),d=s.e,y=Ce(s.c),p=y.length,m==1||m==2&&(l<=d||d<=g)){for(;pp){if(--l>0)for(y+=".";l--;y+="0");}else if(l+=d-p,l>0)for(d+1==p&&(y+=".");l--;y+="0");return s.s<0&&h?"-"+y:y}function P(s,l){for(var f,m,h=1,d=new x(s[0]);h=10;h/=10,m++);return(f=m+f*q-1)>_?s.c=s.e=null:f=10;p/=10,h++);if(d=l-h,d<0)d+=q,v=l,y=T[b=0],w=Te(y/G[h-v-1]%10);else if(b=ii((d+1)/q),b>=T.length)if(m){for(;T.length<=b;T.push(0));y=w=0,h=1,d%=q,v=d-q+1}else break e;else{for(y=p=T[b],h=1;p>=10;p/=10,h++);d%=q,v=d-q+h,w=v<0?0:Te(y/G[h-v-1]%10)}if(m=m||l<0||T[b+1]!=null||(v<0?y:y%G[h-v-1]),m=f<4?(w||m)&&(f==0||f==(s.s<0?3:2)):w>5||w==5&&(f==4||m||f==6&&(d>0?v>0?y/G[h-v]:0:T[b-1])%10&1||f==(s.s<0?8:7)),l<1||!T[0])return T.length=0,m?(l-=s.e+1,T[0]=G[(q-l%q)%q],s.e=-l||0):T[0]=s.e=0,s;if(d==0?(T.length=b,p=1,b--):(T.length=b+1,p=G[q-d],T[b]=v>0?Te(y/G[h-v]%G[v])*p:0),m)for(;;)if(b==0){for(d=1,v=T[0];v>=10;v/=10,d++);for(v=T[0]+=p,p=1;v>=10;v/=10,p++);d!=p&&(s.e++,T[0]==Re&&(T[0]=1));break}else{if(T[b]+=p,T[b]!=Re)break;T[b--]=0,p=1}for(d=T.length;T[--d]===0;T.pop());}s.e>_?s.c=s.e=null:s.e=c?Gt(l,f):je(l,f,"0"),s.s<0?"-"+l:l)}return r.absoluteValue=r.abs=function(){var s=new x(this);return s.s<0&&(s.s=1),s},r.comparedTo=function(s,l){return rt(this,new x(s,l))},r.decimalPlaces=r.dp=function(s,l){var f,m,h,d=this;if(s!=null)return oe(s,0,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s+d.e+1,l);if(!(f=d.c))return null;if(m=((h=f.length-1)-Me(this.e/q))*q,h=f[h])for(;h%10==0;h/=10,m--);return m<0&&(m=0),m},r.dividedBy=r.div=function(s,l){return e(this,new x(s,l),a,o)},r.dividedToIntegerBy=r.idiv=function(s,l){return e(this,new x(s,l),0,1)},r.exponentiatedBy=r.pow=function(s,l){var f,m,h,d,v,p,y,b,w,T=this;if(s=new x(s),s.c&&!s.isInteger())throw Error(be+"Exponent not an integer: "+W(s));if(l!=null&&(l=new x(l)),p=s.e>14,!T.c||!T.c[0]||T.c[0]==1&&!T.e&&T.c.length==1||!s.c||!s.c[0])return w=new x(Math.pow(+W(T),p?s.s*(2-Wt(s)):+W(s))),l?w.mod(l):w;if(y=s.s<0,l){if(l.c?!l.c[0]:!l.s)return new x(NaN);m=!y&&T.isInteger()&&l.isInteger(),m&&(T=T.mod(l))}else{if(s.e>9&&(T.e>0||T.e<-1||(T.e==0?T.c[0]>1||p&&T.c[1]>=24e7:T.c[0]<8e13||p&&T.c[0]<=9999975e7)))return d=T.s<0&&Wt(s)?-0:0,T.e>-1&&(d=1/d),new x(y?1/d:d);k&&(d=ii(k/q+2))}for(p?(f=new x(.5),y&&(s.s=1),b=Wt(s)):(h=Math.abs(+W(s)),b=h%2),w=new x(u);;){if(b){if(w=w.times(T),!w.c)break;d?w.c.length>d&&(w.c.length=d):m&&(w=w.mod(l))}if(h){if(h=Te(h/2),h===0)break;b=h%2}else if(s=s.times(f),z(s,s.e+1,1),s.e>14)b=Wt(s);else{if(h=+W(s),h===0)break;b=h%2}T=T.times(T),d?T.c&&T.c.length>d&&(T.c.length=d):m&&(T=T.mod(l))}return m?w:(y&&(w=u.div(w)),l?w.mod(l):d?z(w,k,o,v):w)},r.integerValue=function(s){var l=new x(this);return s==null?s=o:oe(s,0,8),z(l,l.e+1,s)},r.isEqualTo=r.eq=function(s,l){return rt(this,new x(s,l))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(s,l){return rt(this,new x(s,l))>0},r.isGreaterThanOrEqualTo=r.gte=function(s,l){return(l=rt(this,new x(s,l)))===1||l===0},r.isInteger=function(){return!!this.c&&Me(this.e/q)>this.c.length-2},r.isLessThan=r.lt=function(s,l){return rt(this,new x(s,l))<0},r.isLessThanOrEqualTo=r.lte=function(s,l){return(l=rt(this,new x(s,l)))===-1||l===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(s,l){var f,m,h,d,v=this,p=v.s;if(s=new x(s,l),l=s.s,!p||!l)return new x(NaN);if(p!=l)return s.s=-l,v.plus(s);var y=v.e/q,b=s.e/q,w=v.c,T=s.c;if(!y||!b){if(!w||!T)return w?(s.s=-l,s):new x(T?v:NaN);if(!w[0]||!T[0])return T[0]?(s.s=-l,s):new x(w[0]?v:o==3?-0:0)}if(y=Me(y),b=Me(b),w=w.slice(),p=y-b){for((d=p<0)?(p=-p,h=w):(b=y,h=T),h.reverse(),l=p;l--;h.push(0));h.reverse()}else for(m=(d=(p=w.length)<(l=T.length))?p:l,p=l=0;l0)for(;l--;w[f++]=0);for(l=Re-1;m>p;){if(w[--m]=0;){for(f=0,G=de[h]%se,D=de[h]/se|0,v=y,d=h+v;d>h;)b=K[--v]%se,w=K[v]/se|0,p=D*b+w*G,b=G*b+p%se*se+H[d]+f,f=(b/Q|0)+(p/se|0)+D*w,H[d--]=b%Q;H[d]=f}return f?++m:H.splice(0,1),B(s,H,m)},r.negated=function(){var s=new x(this);return s.s=-s.s||null,s},r.plus=function(s,l){var f,m=this,h=m.s;if(s=new x(s,l),l=s.s,!h||!l)return new x(NaN);if(h!=l)return s.s=-l,m.minus(s);var d=m.e/q,v=s.e/q,p=m.c,y=s.c;if(!d||!v){if(!p||!y)return new x(h/0);if(!p[0]||!y[0])return y[0]?s:new x(p[0]?m:h*0)}if(d=Me(d),v=Me(v),p=p.slice(),h=d-v){for(h>0?(v=d,f=y):(h=-h,f=p),f.reverse();h--;f.push(0));f.reverse()}for(h=p.length,l=y.length,h-l<0&&(f=y,y=p,p=f,l=h),h=0;l;)h=(p[--l]=p[l]+y[l]+h)/Re|0,p[l]=Re===p[l]?0:p[l]%Re;return h&&(p=[h].concat(p),++v),B(s,p,v)},r.precision=r.sd=function(s,l){var f,m,h,d=this;if(s!=null&&s!==!!s)return oe(s,1,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s,l);if(!(f=d.c))return null;if(h=f.length-1,m=h*q+1,h=f[h]){for(;h%10==0;h/=10,m--);for(h=f[0];h>=10;h/=10,m++);}return s&&d.e+1>m&&(m=d.e+1),m},r.shiftedBy=function(s){return oe(s,-9007199254740991,Zi),this.times("1e"+s)},r.squareRoot=r.sqrt=function(){var s,l,f,m,h,d=this,v=d.c,p=d.s,y=d.e,b=a+4,w=new x("0.5");if(p!==1||!v||!v[0])return new x(!p||p<0&&(!v||v[0])?NaN:v?d:1/0);if(p=Math.sqrt(+W(d)),p==0||p==1/0?(l=Ce(v),(l.length+y)%2==0&&(l+="0"),p=Math.sqrt(+l),y=Me((y+1)/2)-(y<0||y%2),p==1/0?l="5e"+y:(l=p.toExponential(),l=l.slice(0,l.indexOf("e")+1)+y),f=new x(l)):f=new x(p+""),f.c[0]){for(y=f.e,p=y+b,p<3&&(p=0);;)if(h=f,f=w.times(h.plus(e(d,h,b,1))),Ce(h.c).slice(0,p)===(l=Ce(f.c)).slice(0,p))if(f.e0&&H>0){for(d=H%p||p,w=D.substr(0,d);d0&&(w+=b+D.slice(d)),G&&(w="-"+w)}m=T?w+(f.decimalSeparator||"")+((y=+f.fractionGroupSize)?T.replace(new RegExp("\\d{"+y+"}\\B","g"),"$&"+(f.fractionGroupSeparator||"")):T):w}return(f.prefix||"")+m+(f.suffix||"")},r.toFraction=function(s){var l,f,m,h,d,v,p,y,b,w,T,G,D=this,H=D.c;if(s!=null&&(p=new x(s),!p.isInteger()&&(p.c||p.s!==1)||p.lt(u)))throw Error(be+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+W(p));if(!H)return new x(D);for(l=new x(u),b=f=new x(u),m=y=new x(u),G=Ce(H),d=l.e=G.length-D.e-1,l.c[0]=ni[(v=d%q)<0?q+v:v],s=!s||p.comparedTo(l)>0?d>0?l:b:p,v=_,_=1/0,p=new x(G),y.c[0]=0;w=e(p,l,0,1),h=f.plus(w.times(m)),h.comparedTo(s)!=1;)f=m,m=h,b=y.plus(w.times(h=b)),y=h,l=p.minus(w.times(h=l)),p=h;return h=e(s.minus(f),m,0,1),y=y.plus(h.times(b)),f=f.plus(h.times(m)),y.s=b.s=D.s,d=d*2,T=e(b,m,d,o).minus(D).abs().comparedTo(e(y,f,d,o).minus(D).abs())<1?[b,m]:[y,f],_=v,T},r.toNumber=function(){return+W(this)},r.toPrecision=function(s,l){return s!=null&&oe(s,1,Ee),N(this,s,l,2)},r.toString=function(s){var l,f=this,m=f.s,h=f.e;return h===null?m?(l="Infinity",m<0&&(l="-"+l)):l="NaN":(s==null?l=h<=g||h>=c?Gt(Ce(f.c),h):je(Ce(f.c),h,"0"):s===10&&O?(f=z(new x(f),a+h+1,o),l=je(Ce(f.c),f.e,"0")):(oe(s,2,C.length,"Base"),l=t(je(Ce(f.c),h,"0"),10,s,m,!0)),m<0&&f.c[0]&&(l="-"+l)),l},r.valueOf=r.toJSON=function(){return W(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,i!=null&&x.set(i),x}function Me(i){var e=i|0;return i>0||i===e?e:e-1}function Ce(i){for(var e,t,n=1,r=i.length,u=i[0]+"";nc^t?1:-1;for(o=(g=r.length)<(c=u.length)?g:c,a=0;au[a]^t?1:-1;return g==c?0:g>c^t?1:-1}function oe(i,e,t,n){if(it||i!==Te(i))throw Error(be+(n||"Argument")+(typeof i=="number"?it?" out of range: ":" not an integer: ":" not a primitive number: ")+String(i))}function Wt(i){var e=i.c.length-1;return Me(i.e/q)==e&&i.c[e]%2!=0}function Gt(i,e){return(i.length>1?i.charAt(0)+"."+i.slice(1):i)+(e<0?"e":"e+")+e}function je(i,e,t){var n,r;if(e<0){for(r=t+".";++e;r+=t);i=r+i}else if(n=i.length,++e>n){for(r=t,e-=n;--e;r+=t);i+=r}else e0){let c=a.left;if(c==null||(g=o(c.key,i),g>0&&(a.left=c.right,c.right=a,a=c,c=a.left,c==null)))break;t==null?n=a:t.left=a,t=a,a=c}else if(g<0){let c=a.right;if(c==null||(g=o(c.key,i),g<0&&(a.right=c.left,c.left=a,a=c,c=a.right,c==null)))break;r==null?u=a:r.right=a,r=a,a=c}else break;return r!=null&&(r.right=a.left,a.left=u),t!=null&&(t.left=a.right,a.right=n),this.root!==a&&(this.root=a,this.splayCount++),g}splayMin(i){let e=i,t=e.left;for(;t!=null;){const n=t;e.left=n.right,n.right=e,e=n,t=e.left}return e}splayMax(i){let e=i,t=e.right;for(;t!=null;){const n=t;e.right=n.left,n.left=e,e=n,t=e.right}return e}_delete(i){if(this.root==null||this.splay(i)!=0)return null;let t=this.root;const n=t,r=t.left;if(this.size--,r==null)this.root=t.right;else{const u=t.right;t=this.splayMax(r),t.right=u,this.root=t}return this.modificationCount++,n}addNewRoot(i,e){this.size++,this.modificationCount++;const t=this.root;if(t==null){this.root=i;return}e<0?(i.left=t,i.right=t.right,t.right=null):(i.right=t,i.left=t.left,t.left=null),this.root=i}_first(){const i=this.root;return i==null?null:(this.root=this.splayMin(i),this.root)}_last(){const i=this.root;return i==null?null:(this.root=this.splayMax(i),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(i){return this.validKey(i)&&this.splay(i)==0}defaultCompare(){return(i,e)=>ie?1:0}wrap(){return{getRoot:()=>this.root,setRoot:i=>{this.root=i},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:i=>{this.splayCount=i},splay:i=>this.splay(i),has:i=>this.has(i)}}},Dt=class Ot extends Pr{constructor(t,n){super();A(this,"root",null);A(this,"compare");A(this,"validKey");A(this,fn,"[object Set]");this.compare=t??this.defaultCompare(),this.validKey=n??(r=>r!=null&&r!=null)}delete(t){return this.validKey(t)?this._delete(t)!=null:!1}deleteAll(t){for(const n of t)this.delete(n)}forEach(t){const n=this[Symbol.iterator]();let r;for(;r=n.next(),!r.done;)t(r.value,r.value,this)}add(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this}addAndReturn(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this.root.key}addAll(t){for(const n of t)this.add(n)}isEmpty(){return this.root==null}isNotEmpty(){return this.root!=null}single(){if(this.size==0)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(this.size==0)throw"Bad state: No element";return this._first().key}last(){if(this.size==0)throw"Bad state: No element";return this._last().key}lastBefore(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)<0)return this.root.key;let r=this.root.left;if(r==null)return null;let u=r.right;for(;u!=null;)r=u,u=r.right;return r.key}firstAfter(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)>0)return this.root.key;let r=this.root.right;if(r==null)return null;let u=r.left;for(;u!=null;)r=u,u=r.left;return r.key}retainAll(t){const n=new Ot(this.compare,this.validKey),r=this.modificationCount;for(const u of t){if(r!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(u)&&this.splay(u)==0&&n.add(this.root.key)}n.size!=this.size&&(this.root=n.root,this.size=n.size,this.modificationCount++)}lookup(t){return!this.validKey(t)||this.splay(t)!=0?null:this.root.key}intersection(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)&&n.add(r);return n}difference(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)||n.add(r);return n}union(t){const n=this.clone();return n.addAll(t),n}clone(){const t=new Ot(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(t){if(t==null)return null;function n(u,a){let o,g;do{if(o=u.left,g=u.right,o!=null){const c=new _t(o.key);a.left=c,n(o,c)}if(g!=null){const c=new _t(g.key);a.right=c,u=g,a=c}}while(g!=null)}const r=new _t(t.key);return n(t,r),r}toSet(){return this.clone()}entries(){return new Ar(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[(cn=Symbol.iterator,fn=Symbol.toStringTag,cn)](){return new Ir(this.wrap())}},Vi=class{constructor(i){A(this,"tree");A(this,"path",new Array);A(this,"modificationCount",null);A(this,"splayCount");this.tree=i,this.splayCount=i.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const i=this.path[this.path.length-1];return this.getValue(i)}rebuildPath(i){this.path.splice(0,this.path.length),this.tree.splay(i),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(i){for(;i!=null;)this.path.push(i),i=i.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(this.modificationCount==null){this.modificationCount=this.tree.getModificationCount();let t=this.tree.getRoot();for(;t!=null;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let i=this.path[this.path.length-1],e=i.right;if(e!=null){for(;e!=null;)this.path.push(e),e=e.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===i;)i=this.path.pop();return this.path.length>0}},Ir=class extends Vi{getValue(i){return i.key}},Ar=class extends Vi{getValue(i){return[i.key,i.key]}},Ki=i=>()=>i,ri=i=>{const e=i?(t,n)=>n.minus(t).abs().isLessThanOrEqualTo(i):Ki(!1);return(t,n)=>e(t,n)?0:t.comparedTo(n)};function Br(i){const e=i?(t,n,r,u,a)=>t.exponentiatedBy(2).isLessThanOrEqualTo(u.minus(n).exponentiatedBy(2).plus(a.minus(r).exponentiatedBy(2)).times(i)):Ki(!1);return(t,n,r)=>{const u=t.x,a=t.y,o=r.x,g=r.y,c=a.minus(g).times(n.x.minus(o)).minus(u.minus(o).times(n.y.minus(g)));return e(c,u,a,o,g)?0:c.comparedTo(0)}}var Wr=i=>i,Gr=i=>{if(i){const e=new Dt(ri(i)),t=new Dt(ri(i)),n=(u,a)=>a.addAndReturn(u),r=u=>({x:n(u.x,e),y:n(u.y,t)});return r({x:new Ae(0),y:new Ae(0)}),r}return Wr},si=i=>({set:e=>{Ze=si(e)},reset:()=>si(i),compare:ri(i),snap:Gr(i),orient:Br(i)}),Ze=si(),St=(i,e)=>i.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(i.ur.x)&&i.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(i.ur.y),oi=(i,e)=>{if(e.ur.x.isLessThan(i.ll.x)||i.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(i.ll.y)||i.ur.y.isLessThan(e.ll.y))return null;const t=i.ll.x.isLessThan(e.ll.x)?e.ll.x:i.ll.x,n=i.ur.x.isLessThan(e.ur.x)?i.ur.x:e.ur.x,r=i.ll.y.isLessThan(e.ll.y)?e.ll.y:i.ll.y,u=i.ur.y.isLessThan(e.ur.y)?i.ur.y:e.ur.y;return{ll:{x:t,y:r},ur:{x:n,y:u}}},zt=(i,e)=>i.x.times(e.y).minus(i.y.times(e.x)),Yi=(i,e)=>i.x.times(e.x).plus(i.y.times(e.y)),Ut=i=>Yi(i,i).sqrt(),Dr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return zt(r,n).div(Ut(r)).div(Ut(n))},zr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return Yi(r,n).div(Ut(r)).div(Ut(n))},Qi=(i,e,t)=>e.y.isZero()?null:{x:i.x.plus(e.x.div(e.y).times(t.minus(i.y))),y:t},Xi=(i,e,t)=>e.x.isZero()?null:{x:t,y:i.y.plus(e.y.div(e.x).times(t.minus(i.x)))},Ur=(i,e,t,n)=>{if(e.x.isZero())return Xi(t,n,i.x);if(n.x.isZero())return Xi(i,e,t.x);if(e.y.isZero())return Qi(t,n,i.y);if(n.y.isZero())return Qi(i,e,t.y);const r=zt(e,n);if(r.isZero())return null;const u={x:t.x.minus(i.x),y:t.y.minus(i.y)},a=zt(u,e).div(r),o=zt(u,n).div(r),g=i.x.plus(o.times(e.x)),c=t.x.plus(a.times(n.x)),E=i.y.plus(o.times(e.y)),_=t.y.plus(a.times(n.y)),M=g.plus(c).div(2),R=E.plus(_).div(2);return{x:M,y:R}},Be=class En{constructor(e,t){A(this,"point");A(this,"isLeft");A(this,"segment");A(this,"otherSE");A(this,"consumedBy");e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}static compare(e,t){const n=En.comparePoints(e.point,t.point);return n!==0?n:(e.point!==t.point&&e.link(t),e.isLeft!==t.isLeft?e.isLeft?1:-1:Ft.compare(e.segment,t.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let n=0,r=t.length;n{const u=r.otherSE;t.set(r,{sine:Dr(this.point,e.point,u.point),cosine:zr(this.point,e.point,u.point)})};return(r,u)=>{t.has(r)||n(r),t.has(u)||n(u);const{sine:a,cosine:o}=t.get(r),{sine:g,cosine:c}=t.get(u);return a.isGreaterThanOrEqualTo(0)&&g.isGreaterThanOrEqualTo(0)?o.isLessThan(c)?1:o.isGreaterThan(c)?-1:0:a.isLessThan(0)&&g.isLessThan(0)?o.isLessThan(c)?-1:o.isGreaterThan(c)?1:0:g.isLessThan(a)?-1:g.isGreaterThan(a)?1:0}}},qr=class pi{constructor(e){A(this,"events");A(this,"poly");A(this,"_isExteriorRing");A(this,"_enclosingRing");this.events=e;for(let t=0,n=e.length;t0&&(e=g)}let t=e.segment.prevInResult(),n=t?t.prevInResult():null;for(;;){if(!t)return null;if(!n)return t.ringOut;if(n.ringOut!==t.ringOut)return((r=n.ringOut)==null?void 0:r.enclosingRing())!==t.ringOut?t.ringOut:(u=t.ringOut)==null?void 0:u.enclosingRing();t=n.prevInResult(),n=t?t.prevInResult():null}}},Ji=class{constructor(i){A(this,"exteriorRing");A(this,"interiorRings");this.exteriorRing=i,i.poly=this,this.interiorRings=[]}addInterior(i){this.interiorRings.push(i),i.poly=this}getGeom(){const i=this.exteriorRing.getGeom();if(i===null)return null;const e=[i];for(let t=0,n=this.interiorRings.length;t0?(this.tree.delete(e),t.push(i)):(this.segments.push(e),e.prev=n)}else{if(n&&r){const u=n.getIntersection(r);if(u!==null){if(!n.isAnEndpoint(u)){const a=this._splitSafely(n,u);for(let o=0,g=a.length;o0)return-1;const M=t.comparePoint(e.rightSE.point);return M!==0?M:-1}if(n.isGreaterThan(r)){if(o.isLessThan(g)&&o.isLessThan(E))return-1;if(o.isGreaterThan(g)&&o.isGreaterThan(E))return 1;const _=t.comparePoint(e.leftSE.point);if(_!==0)return _;const M=e.comparePoint(t.rightSE.point);return M<0?1:M>0?-1:1}if(o.isLessThan(g))return-1;if(o.isGreaterThan(g))return 1;if(u.isLessThan(a)){const _=t.comparePoint(e.rightSE.point);if(_!==0)return _}if(u.isGreaterThan(a)){const _=e.comparePoint(t.rightSE.point);if(_<0)return 1;if(_>0)return-1}if(!u.eq(a)){const _=c.minus(o),M=u.minus(n),R=E.minus(g),k=a.minus(r);if(_.isGreaterThan(M)&&R.isLessThan(k))return 1;if(_.isLessThan(M)&&R.isGreaterThan(k))return-1}return u.isGreaterThan(a)?1:u.isLessThan(a)||c.isLessThan(E)?-1:c.isGreaterThan(E)?1:e.idt.id?1:0}static fromRing(e,t,n){let r,u,a;const o=Be.comparePoints(e,t);if(o<0)r=e,u=t,a=1;else if(o>0)r=t,u=e,a=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const g=new Be(r,!0),c=new Be(u,!1);return new Kt(g,c,[n],[a])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return Ze.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),n=e.bbox(),r=oi(t,n);if(r===null)return null;const u=this.leftSE.point,a=this.rightSE.point,o=e.leftSE.point,g=e.rightSE.point,c=St(t,o)&&this.comparePoint(o)===0,E=St(n,u)&&e.comparePoint(u)===0,_=St(t,g)&&this.comparePoint(g)===0,M=St(n,a)&&e.comparePoint(a)===0;if(E&&c)return M&&!_?a:!M&&_?g:null;if(E)return _&&u.x.eq(g.x)&&u.y.eq(g.y)?null:u;if(c)return M&&a.x.eq(o.x)&&a.y.eq(o.y)?null:o;if(M&&_)return null;if(M)return a;if(_)return g;const R=Ur(u,this.vector(),o,e.vector());return R===null||!St(r,R)?null:Ze.snap(R)}split(e){const t=[],n=e.events!==void 0,r=new Be(e,!0),u=new Be(e,!1),a=this.rightSE;this.replaceRightSE(u),t.push(u),t.push(r);const o=new Kt(r,a,this.rings.slice(),this.windings.slice());return Be.comparePoints(o.leftSE.point,o.rightSE.point)>0&&o.swapEvents(),Be.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(r.checkForConsuming(),u.checkForConsuming()),t}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,n=this.windings.length;t0){const u=t;t=n,n=u}if(t.prev===n){const u=t;t=n,n=u}for(let u=0,a=n.rings.length;ur.length===1&&r[0].isSubject;this._isInResult=n(e)!==n(t);break}}return this._isInResult}},$i=class{constructor(i,e,t){A(this,"poly");A(this,"isExterior");A(this,"segments");A(this,"bbox");if(!Array.isArray(i)||i.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=e,this.isExterior=t,this.segments=[],typeof i[0][0]!="number"||typeof i[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const n=Ze.snap({x:new Ae(i[0][0]),y:new Ae(i[0][1])});this.bbox={ll:{x:n.x,y:n.y},ur:{x:n.x,y:n.y}};let r=n;for(let u=1,a=i.length;uqt.run("union",i,e),Yr=(i,...e)=>qt.run("difference",i,e);Ze.set;function tn(i,e,t){if(i!==null)for(var n,r,u,a,o,g,c,E=0,_=0,M,R=i.type,k=R==="FeatureCollection",I=R==="Feature",C=k?i.features.length:1,O=0;O{t.push(r.coordinates)}),t.length<2)throw new Error("Must have at least 2 geometries");const n=Kr(t[0],...t.slice(1));return n.length===0?null:n.length===1?ti(n[0],e.properties):Fi(n,e.properties)}var nn=Xr;function Jr(i,e={}){if(i.bbox!=null&&e.recompute!==!0)return i.bbox;const t=[1/0,1/0,-1/0,-1/0];return tn(i,n=>{t[0]>n[0]&&(t[0]=n[0]),t[1]>n[1]&&(t[1]=n[1]),t[2]{e.push(r.coordinates)}),e.length<2)throw new Error("Must have at least two features");const t=i.features[0].properties||{},n=Yr(e[0],...e.slice(1));return n.length===0?null:n.length===1?ti(n[0],t):Fi(n,t)}var es=$r;function ts(i){if(!i)throw new Error("geojson is required");var e=[];return Qr(i,function(t){e.push(t)}),Lt(e)}var is=ts;function sn(i,e){const t=es(Lt([ti([[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]]),i]));if(!t)return;t.properties={isMask:!0};const n=Bt(rn(i)),r=(n[2]-n[0])/360/1e3,u=n[0]<-180,a=n[2]>180,o=is(i);if(o.features.length>1&&(u||a))for(const g of o.features){const c=Bt(rn(g));if(a&&c[0]<-180+r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]+=360-r;if(u&&c[2]>180-r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]-=360-r}e(Lt([o.features.length<2?i:nn(o)??i,t]))}const on={fill:{paint:{"fill-color":"#000","fill-opacity":.1},filter:["all",["==",["geometry-type"],"Polygon"],["has","isMask"]]},line:{layout:{"line-cap":"square"},paint:{"line-width":["case",["==",["geometry-type"],"Polygon"],2,3],"line-dasharray":[1,1],"line-color":"#3170fe"},filter:["!",["has","isMask"]]}},jt="mtlr-gc-full-geom",ln="mtlr-gc-full-geom-fill",un="mtlr-gc-full-geom-line";function an(i,e,t=!0,n=!0,r={},u={},a=on){let o;const g=[];let c,E,_;function M(){if(!i.loaded){i.once("load",M);return}const C=a?a===!0?on:a:void 0;if(!(C!=null&&C.fill)&&!(C!=null&&C.line))return;const O=i.getSource(jt);if(O)O.setData(_??Lt([]));else if(_)i.addSource(jt,{type:"geojson",data:_});else return;!i.getLayer(ln)&&(C!=null&&C.fill)&&i.addLayer({...C==null?void 0:C.fill,id:ln,type:"fill",source:jt}),!i.getLayer(un)&&(C!=null&&C.line)&&i.addLayer({...C==null?void 0:C.line,id:un,type:"line",source:jt})}function R(C){_=C,M()}i.on("styledata",()=>{setTimeout(()=>{_&&M()})});const k=C=>{o==null||o({type:"mapClick",coordinates:[C.lngLat.lng,C.lngLat.lat]})};function I(C=!1){if(!e)throw new Error;const O=document.createElement("div");return C&&O.classList.add("marker-interactive"),new or({props:{displayIn:"maplibre"},target:O}),new e.Marker({element:O,offset:[1,-13]})}return{setEventHandler(C){C?(o=C,i.on("click",k)):(o=void 0,i.off("click",k))},flyTo(C,O){i.flyTo({center:C,...O?{zoom:O}:{},...r})},fitBounds(C,O,x){i.fitBounds([[C[0],C[1]],[C[2],C[3]]],{padding:O,...x?{maxZoom:x}:{},...u})},indicateReverse(C){i.getCanvasContainer().style.cursor=C?"crosshair":""},setReverseMarker(C){!e||!t||(E?C?E.setLngLat(C):(E.remove(),E=void 0):C&&(t instanceof Function?E=t(i)??void 0:(E=(typeof t=="object"?new e.Marker(t):I()).setLngLat(C).addTo(i),E.getElement().classList.add("marker-reverse"))))},setFeatures(C,O,x){for(const N of g)N.remove();if(g.length=0,R(void 0),!!e){e:if(O){let N=!1;if(O.geometry.type==="GeometryCollection"){const P=O.geometry.geometries.filter(B=>B.type==="Polygon"||B.type==="MultiPolygon");t:if(P.length>0){const B=nn(Lt(P.map(z=>Et(z))));if(!B)break t;sn({...O,geometry:B.geometry},R),N=!0}else{const B=O.geometry.geometries.filter(z=>z.type==="LineString"||z.type==="MultiLineString");B.length>0&&(R({...O,geometry:{type:"GeometryCollection",geometries:B}}),N=!0)}}if(!N){if(O.geometry.type==="Polygon"||O.geometry.type==="MultiPolygon")sn(O,R);else if(O.geometry.type==="LineString"||O.geometry.type==="MultiLineString"){R(O);break e}}if(!x&&!O.geometry.type.endsWith("Point"))break e;if(t instanceof Function){const P=t(i,O);P&&g.push(P)}else t&&g.push(typeof t=="object"?new e.Marker(t):I().setLngLat(O.center).addTo(i))}if(n)for(const N of C??[]){if(N===O)continue;let P;if(n instanceof Function){if(P=n(i,N),!P)continue}else P=(typeof n=="object"?new e.Marker(n):I(!0)).setLngLat(N.center).setPopup(new e.Popup({offset:[1,-27],closeButton:!1,closeOnMove:!0,className:"maptiler-gc-popup"}).setText(N.place_type[0]==="reverse"?N.place_name:N.place_name.replace(/,.*/,""))).addTo(i);const B=P.getElement();B.addEventListener("click",z=>{z.stopPropagation(),o==null||o({type:"markerClick",id:N.id})}),B.addEventListener("mouseenter",()=>{o==null||o({type:"markerMouseEnter",id:N.id}),P.togglePopup()}),B.addEventListener("mouseleave",()=>{o==null||o({type:"markerMouseLeave",id:N.id}),P.togglePopup()}),g.push(P)}}},setSelectedMarker(C){c&&c.getElement().classList.toggle("marker-selected",!1),c=C>-1?g[C]:void 0,c==null||c.getElement().classList.toggle("marker-selected",!0)},getCenterAndZoom(){const C=i.getCenter();return[i.getZoom(),C.lng,C.lat]}}}function ns(i,e,t){var k,I,C;class n{constructor(x,N){A(this,"type");A(this,"target");this.type=N,this.target=x}}class r extends n{constructor(N,P){super(N,"select");A(this,"feature");Object.assign(this,P)}}class u extends n{constructor(N,P){super(N,"featureslisted");A(this,"features");this.features=P}}class a extends n{constructor(N,P){super(N,"featuresmarked");A(this,"features");this.features=P}}class o extends n{constructor(N,P){super(N,"optionsvisibilitychange");A(this,"optionsVisible");this.optionsVisible=P}}class g extends n{constructor(N,P){super(N,"pick");A(this,"feature");this.feature=P}}class c extends n{constructor(N,P){super(N,"querychange");A(this,"query");this.query=P}}class E extends n{constructor(N,P,B){super(N,"response");A(this,"url");A(this,"featureCollection");this.url=P,this.featureCollection=B}}class _ extends n{constructor(N,P){super(N,"reversetoggle");A(this,"reverse");this.reverse=P}}class M extends i{constructor(N={}){super();Vt(this,k);Vt(this,I);Vt(this,C);kt(this,I,N)}onAddInt(N){const P=document.createElement("div");P.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl mapboxgl-ctrl-group";const{marker:B,showResultMarkers:z,flyTo:W,fullGeometryStyle:s,...l}=ue(this,I),f=typeof W=="boolean"?{}:W,h={mapController:an(N,e,B,z,f,f,s),flyTo:W===void 0?!0:!!W,apiKey:"",...t==null?void 0:t(N,P),...l};return h.apiKey||console.warn("No MapTiler Cloud API key was provided, some or all geocoding requests may fail"),kt(this,k,new kr({target:P,props:h})),ue(this,k).$on("select",d=>{this.fire(new r(this,d.detail))}),ue(this,k).$on("pick",d=>{this.fire(new g(this,d.detail.feature))}),ue(this,k).$on("featureslisted",d=>{this.fire(new u(this,d.detail.features))}),ue(this,k).$on("featuresmarked",d=>{this.fire(new a(this,d.detail.features))}),ue(this,k).$on("response",d=>{this.fire(new E(this,d.detail.url,d.detail.featureCollection))}),ue(this,k).$on("optionsvisibilitychange",d=>{this.fire(new o(this,d.detail.optionsVisible))}),ue(this,k).$on("reversetoggle",d=>{this.fire(new _(this,d.detail.reverse))}),ue(this,k).$on("querychange",d=>{this.fire(new c(this,d.detail.query))}),kt(this,C,P),P}on(N,P){return super.on(N,P)}once(N,P){return super.once(N,P)}off(N,P){return super.off(N,P)}listens(N){return super.listens(N)}setOptions(N){var l;Object.assign(ue(this,I),N);const{marker:P,showResultMarkers:B,flyTo:z,fullGeometryStyle:W,...s}=ue(this,I);(l=ue(this,k))==null||l.$set(s)}setQuery(N,P=!0){var B;(B=ue(this,k))==null||B.setQuery(N,P)}clearMap(){var N;(N=ue(this,k))==null||N.clearMap()}clearList(){var N;(N=ue(this,k))==null||N.clearList()}setReverseMode(N){var P;(P=ue(this,k))==null||P.$set({reverseActive:N})}focus(N){var P;(P=ue(this,k))==null||P.focus(N)}blur(){var N;(N=ue(this,k))==null||N.blur()}onRemove(){var N,P,B;(N=ue(this,k))==null||N.$destroy(),kt(this,k,void 0),(B=(P=ue(this,C))==null?void 0:P.parentNode)==null||B.removeChild(ue(this,C))}}return k=new WeakMap,I=new WeakMap,C=new WeakMap,{MapLibreBasedGeocodingControl:M,events:{SelectEvent:r,FeaturesListedEvent:u,FeaturesMarkedEvent:a,OptionsVisibilityChangeEvent:o,PickEvent:g,QueryChangeEvent:c,ResponseEvent:E,ReverseToggleEvent:_}}}const{MapLibreBasedGeocodingControl:rs,events:et}=ns(dt.Evented,dt);class ss extends rs{onAdd(e){return super.onAddInt(e)}}const os=et.SelectEvent,ls=et.FeaturesListedEvent,us=et.FeaturesMarkedEvent,as=et.OptionsVisibilityChangeEvent,fs=et.PickEvent,cs=et.QueryChangeEvent,hs=et.ResponseEvent,ds=et.ReverseToggleEvent;j.FeaturesListedEvent=ls,j.FeaturesMarkedEvent=us,j.GeocodingControl=ss,j.OptionsVisibilityChangeEvent=as,j.PickEvent=fs,j.QueryChangeEvent=cs,j.ResponseEvent=hs,j.ReverseToggleEvent=ds,j.SelectEvent=os,j.createMapLibreGlMapController=an,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"})}); +//# sourceMappingURL=maplibregl.umd.js.map diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css new file mode 100644 index 0000000..c865c17 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css @@ -0,0 +1 @@ +svg.svelte-d2loi5{display:block;fill:#e15042}.sprite-icon.svelte-w9y5n9.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75;background-repeat:no-repeat}li.svelte-w9y5n9.svelte-w9y5n9{text-align:left;cursor:default;display:grid;grid-template-columns:40px 1fr;color:var(--color-text);padding:8px 0;font-size:14px;line-height:18px;min-width:fit-content;outline:0}li.svelte-w9y5n9.svelte-w9y5n9:first-child{padding-top:10px}li.svelte-w9y5n9.svelte-w9y5n9:last-child{padding-bottom:10px}li.picked.svelte-w9y5n9.svelte-w9y5n9{background-color:#e7edff}li.picked.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#96a4c7;padding-left:4px}li.picked.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#96a4c7}li.selected.svelte-w9y5n9.svelte-w9y5n9{background-color:#f3f6ff}li.selected.svelte-w9y5n9.svelte-w9y5n9{animation:svelte-w9y5n9-backAndForth 5s linear infinite}li.selected.svelte-w9y5n9 .primary.svelte-w9y5n9{color:#2b8bfb}li.selected.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#a2adc7;padding-left:4px}li.selected.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#a2adc7}li.svelte-w9y5n9>img.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75}.texts.svelte-w9y5n9.svelte-w9y5n9{padding:0 17px 0 0}.texts.svelte-w9y5n9>.svelte-w9y5n9{white-space:nowrap;display:block;min-width:fit-content}.primary.svelte-w9y5n9.svelte-w9y5n9{font-weight:600}.secondary.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7;padding-left:4px}.line2.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7}@keyframes svelte-w9y5n9-backAndForth{0%{transform:translate(0)}10%{transform:translate(0)}45%{transform:translate(calc(-100% + 270px))}55%{transform:translate(calc(-100% + 270px))}90%{transform:translate(0)}to{transform:translate(0)}}div.svelte-1ocfouu{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);pointer-events:none;display:flex;align-items:center}.loading-icon.svelte-1ocfouu{animation:svelte-1ocfouu-rotate .8s infinite cubic-bezier(.45,.05,.55,.95)}@keyframes svelte-1ocfouu-rotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}svg.svelte-gzo3ar.svelte-gzo3ar{display:block;fill:#6b7c93;stroke:#6b7c93}.list-icon.svelte-gzo3ar.svelte-gzo3ar{grid-row:1/3;align-self:center;margin:8px}.in-map.svelte-gzo3ar.svelte-gzo3ar{height:30px}.maplibregl-canvas-container .marker-selected{z-index:1}.maplibregl-canvas-container svg.svelte-gzo3ar path.svelte-gzo3ar,.leaflet-map-pane svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#3170fe;stroke:#3170fe}.marker-selected svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#98b7ff;stroke:#3170fe}.marker-reverse svg.svelte-gzo3ar path.svelte-gzo3ar{fill:silver;stroke:gray}.marker-interactive{cursor:pointer!important}.maptiler-gc-popup>.maplibregl-popup-content{padding:2px 8px}svg.svelte-en2qvf{display:block;fill:var(--color-icon-button)}circle.svelte-1aq105l{stroke-width:1.875;fill:none}path.svelte-1aq105l{stroke-width:1.875;stroke-linecap:round}svg.svelte-1aq105l{display:block;stroke:var(--color-icon-button)}form.svelte-bz0zu3.svelte-bz0zu3{font-family:Open Sans,Ubuntu,Helvetica Neue,Arial,Helvetica,sans-serif;position:relative;background-color:#fff;z-index:10;border-radius:4px;margin:0;transition:max-width .25s;box-shadow:0 2px 5px #33335926;--color-text:#444952;--color-icon-button:#444952}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3:after,form.svelte-bz0zu3 .svelte-bz0zu3:before{box-sizing:border-box}form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:29px}form.can-collapse.svelte-bz0zu3 input.svelte-bz0zu3::placeholder{transition:opacity .25s;opacity:0}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3.svelte-bz0zu3:focus-within,form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px}form.svelte-bz0zu3 input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:focus-within input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:hover input.svelte-bz0zu3::placeholder{opacity:1}input.svelte-bz0zu3.svelte-bz0zu3{font:inherit;font-size:14px;flex-grow:1;min-height:29px;background-color:transparent;color:#444952;white-space:nowrap;overflow:hidden;border:0;margin:0;padding:0}input.svelte-bz0zu3.svelte-bz0zu3:focus{color:#444952;outline:0;outline:none;box-shadow:none}ul.svelte-bz0zu3.svelte-bz0zu3,div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{background-color:#fff;border-radius:4px;left:0;list-style:none;margin:0;padding:0;position:absolute;width:100%;top:calc(100% + 6px);overflow:hidden}ul.svelte-bz0zu3.svelte-bz0zu3{font-size:14px;line-height:16px;box-shadow:0 5px 10px #33335926}div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{font:inherit;line-height:18px;font-size:12px;display:flex;gap:16px}div.error.svelte-bz0zu3.svelte-bz0zu3{padding:16px;font-weight:600;color:#e25041;background-color:#fbeae8}div.error.svelte-bz0zu3 div.svelte-bz0zu3{flex-grow:1}div.error.svelte-bz0zu3 svg{flex-shrink:0;width:20px;height:20px}div.error.svelte-bz0zu3 button.svelte-bz0zu3{flex-shrink:0}div.error.svelte-bz0zu3 button.svelte-bz0zu3>svg{width:13px;fill:#e25041}div.error.svelte-bz0zu3 button.svelte-bz0zu3:hover svg,div.error.svelte-bz0zu3 button.svelte-bz0zu3:active svg{fill:#444952}div.no-results.svelte-bz0zu3.svelte-bz0zu3{padding:14px 24px 14px 16px;font-weight:400;color:#6b7c93;box-shadow:0 5px 10px #33335926}div.no-results.svelte-bz0zu3 svg{margin-top:4px;flex-shrink:0;width:20px;height:20px;width:30px;height:30px}.leaflet-bottom ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-left ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-right ul.options.svelte-bz0zu3.svelte-bz0zu3{top:auto;bottom:calc(100% + 6px)}button.svelte-bz0zu3.svelte-bz0zu3{padding:0;margin:0;border:0;background-color:transparent;height:auto;width:auto}button.svelte-bz0zu3.svelte-bz0zu3:hover{background-color:transparent}button.svelte-bz0zu3:hover svg,button.svelte-bz0zu3:active svg{fill:#2b8bfb}.input-group.svelte-bz0zu3.svelte-bz0zu3{display:flex;align-items:stretch;gap:7px;padding-inline:8px;border-radius:4px;overflow:hidden}.input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{outline:#2b8bfb solid 2px}.search-button.svelte-bz0zu3.svelte-bz0zu3{flex-shrink:0}.maplibregl-ctrl-geocoder:not(.maptiler-ctrl) .search-button svg{width:12px!important;transform:translate(.5px)}.clear-button-container.svelte-bz0zu3.svelte-bz0zu3{display:flex;display:none;position:relative;align-items:stretch}.clear-button-container.displayable.svelte-bz0zu3.svelte-bz0zu3{display:flex;flex-shrink:0}.maplibregl-ctrl-geocoder{position:relative;z-index:3}.maptiler-ctrl:not(:empty){box-shadow:none}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3{padding-inline:8px;border:white solid 2px}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{border:#2b8bfb solid 2px;outline:0;outline:none}.maptiler-ctrl form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:33px}.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:focus-within,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px} diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js new file mode 100644 index 0000000..1a901ee --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js @@ -0,0 +1,2 @@ +"use strict";var pmtiles=(()=>{var k=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var U=Math.pow;var f=(r,e)=>k(r,"name",{value:e,configurable:!0});var Xe=(r,e)=>{for(var t in e)k(r,t,{get:e[t],enumerable:!0})},_e=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ye(e))!Qe.call(r,i)&&i!==t&&k(r,i,{get:()=>e[i],enumerable:!(n=Je(e,i))||n.enumerable});return r};var et=r=>_e(k({},"__esModule",{value:!0}),r);var m=(r,e,t)=>new Promise((n,i)=>{var a=h=>{try{u(t.next(h))}catch(l){i(l)}},s=h=>{try{u(t.throw(h))}catch(l){i(l)}},u=h=>h.done?n(h.value):Promise.resolve(h.value).then(a,s);u((t=t.apply(r,e)).next())});var Dt={};Xe(Dt,{Compression:()=>Oe,EtagMismatch:()=>B,FetchSource:()=>K,FileSource:()=>oe,PMTiles:()=>P,Protocol:()=>ie,ResolvedValueCache:()=>ue,SharedPromiseCache:()=>G,TileType:()=>se,bytesToHeader:()=>$e,findTile:()=>Fe,getUint64:()=>b,leafletRasterLayer:()=>wt,readVarint:()=>R,tileIdToZxy:()=>Tt,tileTypeExt:()=>Ze,zxyToTileId:()=>Ie});var w=Uint8Array,E=Uint16Array,tt=Int32Array,Me=new w([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ue=new w([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),rt=new w([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ee=f(function(r,e){for(var t=new E(31),n=0;n<31;++n)t[n]=e+=1<>1|(g&21845)<<1,T=(T&52428)>>2|(T&13107)<<2,T=(T&61680)>>4|(T&3855)<<4,re[g]=((T&65280)>>8|(T&255)<<8)>>1;var T,g,F=f(function(r,e,t){for(var n=r.length,i=0,a=new E(e);i>h]=l}else for(u=new E(n),i=0;i>15-r[i]);return u},"hMap"),$=new w(288);for(g=0;g<144;++g)$[g]=8;var g;for(g=144;g<256;++g)$[g]=9;var g;for(g=256;g<280;++g)$[g]=7;var g;for(g=280;g<288;++g)$[g]=8;var g,Re=new w(32);for(g=0;g<32;++g)Re[g]=5;var g;var at=F($,9,1);var st=F(Re,5,1),ee=f(function(r){for(var e=r[0],t=1;te&&(e=r[t]);return e},"max"),z=f(function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},"bits"),te=f(function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},"bits16"),ot=f(function(r){return(r+7)/8|0},"shft"),ut=f(function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new w(r.subarray(e,t))},"slc");var ft=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],y=f(function(r,e,t){var n=new Error(e||ft[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,y),!t)throw n;return n},"err"),ne=f(function(r,e,t,n){var i=r.length,a=n?n.length:0;if(!i||e.f&&!e.l)return t||new w(0);var s=!t,u=s||e.i!=2,h=e.i;s&&(t=new w(i*3));var l=f(function(Te){var Ce=t.length;if(Te>Ce){var De=new w(Math.max(Ce*2,Te));De.set(t),t=De}},"cbuf"),c=e.f||0,o=e.p||0,v=e.b||0,d=e.l,p=e.d,H=e.m,I=e.n,q=i*8;do{if(!d){c=z(r,o,1);var j=z(r,o+1,3);if(o+=3,j)if(j==1)d=at,p=st,H=9,I=5;else if(j==2){var J=z(r,o,31)+257,me=z(r,o+10,15)+4,de=J+z(r,o+5,31)+1;o+=14;for(var O=new w(de),Y=new w(19),x=0;x>4;if(A<16)O[x++]=A;else{var D=0,V=0;for(A==16?(V=3+z(r,o,3),o+=2,D=O[x-1]):A==17?(V=3+z(r,o,7),o+=3):A==18&&(V=11+z(r,o,127),o+=7);V--;)O[x++]=D}}var xe=O.subarray(0,J),C=O.subarray(J);H=ee(xe),I=ee(C),d=F(xe,H,1),p=F(C,I,1)}else y(1);else{var A=ot(o)+4,W=r[A-4]|r[A-3]<<8,N=A+W;if(N>i){h&&y(0);break}u&&l(v+W),t.set(r.subarray(A,N),v),e.b=v+=W,e.p=o=N*8,e.f=c;continue}if(o>q){h&&y(0);break}}u&&l(v+131072);for(var je=(1<>4;if(o+=D&15,o>q){h&&y(0);break}if(D||y(2),M<256)t[v++]=M;else if(M==256){Q=o,d=null;break}else{var be=M-254;if(M>264){var x=M-257,Z=Me[x];be=z(r,o,(1<>4;X||y(3),o+=X&15;var C=it[_];if(_>3){var Z=Ue[_];C+=te(r,o)&(1<q){h&&y(0);break}u&&l(v+131072);var ze=v+be;if(v>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},"gzs"),ct=f(function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0},"gzl");var vt=f(function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&y(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&y(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2},"zls");function gt(r,e){return ne(r,{i:2},e&&e.out,e&&e.dictionary)}f(gt,"inflateSync");function pt(r,e){var t=ht(r);return t+8>r.length&&y(6,"invalid gzip data"),ne(r.subarray(t,-8),{i:2},e&&e.out||new w(ct(r)),e&&e.dictionary)}f(pt,"gunzipSync");function mt(r,e){return ne(r.subarray(vt(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}f(mt,"unzlibSync");function Be(r,e){return r[0]==31&&r[1]==139&&r[2]==8?pt(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?gt(r,e):mt(r,e)}f(Be,"decompressSync");var dt=typeof TextDecoder!="undefined"&&new TextDecoder,yt=0;try{dt.decode(lt,{stream:!0}),yt=1}catch(r){}var wt=f((r,e)=>{let t=!1,n="",i=L.GridLayer.extend({createTile:f((a,s)=>{let u=document.createElement("img"),h=new AbortController,l=h.signal;return u.cancel=()=>{h.abort()},t||(r.getHeader().then(c=>{c.tileType===1?console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):c.tileType===2?n="image/png":c.tileType===3?n="image/jpeg":c.tileType===4?n="image/webp":c.tileType===5&&(n="image/avif")}),t=!0),r.getZxy(a.z,a.x,a.y,l).then(c=>{if(c){let o=new Blob([c.data],{type:n}),v=window.URL.createObjectURL(o);u.src=v,u.cancel=void 0,s(void 0,u)}}).catch(c=>{if(c.name!=="AbortError")throw c}),u},"createTile"),_removeTile:f(function(a){let s=this._tiles[a];s&&(s.el.cancel&&s.el.cancel(),s.el.width=0,s.el.height=0,s.el.deleted=!0,L.DomUtil.remove(s.el),delete this._tiles[a],this.fire("tileunload",{tile:s.el,coords:this._keyToTileCoords(a)}))},"_removeTile")});return new i(e)},"leafletRasterLayer"),xt=f(r=>(e,t)=>{if(t instanceof AbortController)return r(e,t);let n=new AbortController;return r(e,n).then(i=>t(void 0,i.data,i.cacheControl||"",i.expires||""),i=>t(i)).catch(i=>t(i)),{cancel:f(()=>n.abort(),"cancel")}},"v3compat"),ae=class ae{constructor(e){this.tilev4=f((e,t)=>m(this,null,function*(){if(e.type==="json"){let v=e.url.substr(10),d=this.tiles.get(v);if(d||(d=new P(v),this.tiles.set(v,d)),this.metadata)return{data:yield d.getTileJson(e.url)};let p=yield d.getHeader();return(p.minLon>=p.maxLon||p.minLat>=p.maxLat)&&console.error(`Bounds of PMTiles archive ${p.minLon},${p.minLat},${p.maxLon},${p.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:p.minZoom,maxzoom:p.maxZoom,bounds:[p.minLon,p.minLat,p.maxLon,p.maxLat]}}}let n=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),i=e.url.match(n);if(!i)throw new Error("Invalid PMTiles protocol URL");let a=i[1],s=this.tiles.get(a);s||(s=new P(a),this.tiles.set(a,s));let u=i[2],h=i[3],l=i[4],c=yield s.getHeader(),o=yield s==null?void 0:s.getZxy(+u,+h,+l,t.signal);if(o)return{data:new Uint8Array(o.data),cacheControl:o.cacheControl,expires:o.expires};if(c.tileType===1){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4");this.tile=xt(this.tilev4);this.tiles=new Map,this.metadata=(e==null?void 0:e.metadata)||!1,this.errorOnMissingTile=(e==null?void 0:e.errorOnMissingTile)||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};f(ae,"Protocol");var ie=ae;function S(r,e){return(e>>>0)*4294967296+(r>>>0)}f(S,"toNum");function bt(r,e){let t=e.buf,n=t[e.pos++],i=(n&112)>>4;if(n<128||(n=t[e.pos++],i|=(n&127)<<3,n<128)||(n=t[e.pos++],i|=(n&127)<<10,n<128)||(n=t[e.pos++],i|=(n&127)<<17,n<128)||(n=t[e.pos++],i|=(n&127)<<24,n<128)||(n=t[e.pos++],i|=(n&1)<<31,n<128))return S(r,i);throw new Error("Expected varint not more than 10 bytes")}f(bt,"readVarintRemainder");function R(r){let e=r.buf,t=e[r.pos++],n=t&127;return t<128||(t=e[r.pos++],n|=(t&127)<<7,t<128)||(t=e[r.pos++],n|=(t&127)<<14,t<128)||(t=e[r.pos++],n|=(t&127)<<21,t<128)?n:(t=e[r.pos],n|=(t&15)<<28,bt(n,r))}f(R,"readVarint");function He(r,e,t,n){if(n===0){t===1&&(e[0]=r-1-e[0],e[1]=r-1-e[1]);let i=e[0];e[0]=e[1],e[1]=i}}f(He,"rotate");function zt(r,e){let t=U(2,r),n=e,i=e,a=e,s=[0,0],u=1;for(;u26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>U(2,r)-1||t>U(2,r)-1)throw new Error("tile x/y outside zoom level bounds");let n=At[r],i=U(2,r),a=0,s=0,u=0,h=[e,t],l=i/2;for(;l>0;)a=(h[0]&l)>0?1:0,s=(h[1]&l)>0?1:0,u+=l*l*(3*a^s),He(l,h,a,s),l=l/2;return n+u}f(Ie,"zxyToTileId");function Tt(r){let e=0,t=0;for(let n=0;n<27;n++){let i=(1<r)return zt(n,r-e);e+=i}throw new Error("Tile zoom level exceeds max safe number limit (26)")}f(Tt,"tileIdToZxy");var Oe=(a=>(a[a.Unknown=0]="Unknown",a[a.None=1]="None",a[a.Gzip=2]="Gzip",a[a.Brotli=3]="Brotli",a[a.Zstd=4]="Zstd",a))(Oe||{});function fe(r,e){return m(this,null,function*(){if(e===1||e===0)return r;if(e===2){if(typeof globalThis.DecompressionStream=="undefined")return Be(new Uint8Array(r));let t=new Response(r).body;if(!t)throw new Error("Failed to read response stream");let n=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(n).arrayBuffer()}throw new Error("Compression method not supported")})}f(fe,"defaultDecompress");var se=(s=>(s[s.Unknown=0]="Unknown",s[s.Mvt=1]="Mvt",s[s.Png=2]="Png",s[s.Jpeg=3]="Jpeg",s[s.Webp=4]="Webp",s[s.Avif=5]="Avif",s))(se||{});function Ze(r){return r===1?".mvt":r===2?".png":r===3?".jpg":r===4?".webp":r===5?".avif":""}f(Ze,"tileTypeExt");var Ct=127;function Fe(r,e){let t=0,n=r.length-1;for(;t<=n;){let i=n+t>>1,a=e-r[i].tileId;if(a>0)t=i+1;else if(a<0)n=i-1;else return r[i]}return n>=0&&(r[n].runLength===0||e-r[n].tileId-1,a=/Chrome|Chromium|Edg|OPR|Brave/.test(n);this.chromeWindowsNoCache=!1,i&&a&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,n,i){return m(this,null,function*(){let a,s;n?s=n:(a=new AbortController,s=a.signal);let u=new Headers(this.customHeaders);u.set("range",`bytes=${e}-${e+t-1}`);let h;this.mustReload?h="reload":this.chromeWindowsNoCache&&(h="no-store");let l=yield fetch(this.url,{signal:s,cache:h,headers:u});if(e===0&&l.status===416){let d=l.headers.get("Content-Range");if(!d||!d.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let p=+d.substr(8);l=yield fetch(this.url,{signal:s,cache:"reload",headers:{range:`bytes=0-${p-1}`}})}let c=l.headers.get("Etag");if(c!=null&&c.startsWith("W/")&&(c=null),l.status===416||i&&c&&c!==i)throw this.mustReload=!0,new B(`Server returned non-matching ETag ${i} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(l.status>=300)throw new Error(`Bad response code: ${l.status}`);let o=l.headers.get("Content-Length");if(l.status===200&&(!o||+o>t))throw a&&a.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield l.arrayBuffer(),etag:c||void 0,cacheControl:l.headers.get("Cache-Control")||void 0,expires:l.headers.get("Expires")||void 0}})}};f(he,"FetchSource");var K=he;function b(r,e){let t=r.getUint32(e+4,!0),n=r.getUint32(e+0,!0);return t*U(2,32)+n}f(b,"getUint64");function $e(r,e){let t=new DataView(r),n=t.getUint8(7);if(n>3)throw new Error(`Archive is spec version ${n} but this library supports up to spec version 3`);return{specVersion:n,rootDirectoryOffset:b(t,8),rootDirectoryLength:b(t,16),jsonMetadataOffset:b(t,24),jsonMetadataLength:b(t,32),leafDirectoryOffset:b(t,40),leafDirectoryLength:b(t,48),tileDataOffset:b(t,56),tileDataLength:b(t,64),numAddressedTiles:b(t,72),numTileEntries:b(t,80),numTileContents:b(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}f($e,"bytesToHeader");function Ve(r){let e={buf:new Uint8Array(r),pos:0},t=R(e),n=[],i=0;for(let a=0;a0?n[a].offset=n[a-1].offset+n[a-1].length:n[a].offset=s-1}return n}f(Ve,"deserializeIndex");var ce=class ce extends Error{};f(ce,"EtagMismatch");var B=ce;function ke(r,e){return m(this,null,function*(){let t=yield r.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let i=t.data.slice(0,Ct),a=$e(i,t.etag),s=t.data.slice(a.rootDirectoryOffset,a.rootDirectoryOffset+a.rootDirectoryLength),u=`${r.getKey()}|${a.etag||""}|${a.rootDirectoryOffset}|${a.rootDirectoryLength}`,h=Ve(yield e(s,a.internalCompression));return[a,[u,h.length,h]]})}f(ke,"getHeaderAndRoot");function Ke(r,e,t,n,i){return m(this,null,function*(){let a=yield r.getBytes(t,n,void 0,i.etag),s=yield e(a.data,i.internalCompression),u=Ve(s);if(u.length===0)throw new Error("Empty directory is invalid");return u})}f(Ke,"getDirectory");var ve=class ve{constructor(e=100,t=!0,n=fe){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return m(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,n.data;let i=yield ke(e,this.decompress);return i[1]&&this.cache.set(i[1][0],{lastUsed:this.counter++,data:i[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:i[0]}),this.prune(),i[0]})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,s.data;let u=yield Ke(e,this.decompress,t,n,i);return this.cache.set(a,{lastUsed:this.counter++,data:u}),this.prune(),u})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{ke(e,this.decompress).then(u=>{u[1]&&this.cache.set(u[1][0],{lastUsed:this.counter++,data:Promise.resolve(u[1][2])}),a(u[0]),this.prune()}).catch(u=>{s(u)})});return this.cache.set(t,{lastUsed:this.counter++,data:i}),i})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,yield s.data;let u=new Promise((h,l)=>{Ke(e,this.decompress,t,n,i).then(c=>{h(c),this.prune()}).catch(c=>{l(c)})});return this.cache.set(a,{lastUsed:this.counter++,data:u}),u})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{this.getHeader(e).then(s=>{i(),this.invalidations.delete(t)}).catch(s=>{a(s)})});this.invalidations.set(t,n)})}};f(ge,"SharedPromiseCache");var G=ge,pe=class pe{constructor(e,t,n){typeof e=="string"?this.source=new K(e):this.source=e,n?this.decompress=n:this.decompress=fe,t?this.cache=t:this.cache=new G}getHeader(){return m(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,n,i){return m(this,null,function*(){let a=Ie(e,t,n),s=yield this.cache.getHeader(this.source);if(es.maxZoom)return;let u=s.rootDirectoryOffset,h=s.rootDirectoryLength;for(let l=0;l<=3;l++){let c=yield this.cache.getDirectory(this.source,u,h,s),o=Fe(c,a);if(o){if(o.runLength>0){let v=yield this.source.getBytes(s.tileDataOffset+o.offset,o.length,i,s.etag);return{data:yield this.decompress(v.data,s.tileCompression),cacheControl:v.cacheControl,expires:v.expires}}u=s.leafDirectoryOffset+o.offset,h=o.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,n,i){return m(this,null,function*(){try{return yield this.getZxyAttempt(e,t,n,i)}catch(a){if(a instanceof B)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,n,i);throw a}})}getMetadataAttempt(){return m(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),n=yield this.decompress(t.data,e.internalCompression),i=new TextDecoder("utf-8");return JSON.parse(i.decode(n))})}getMetadata(){return m(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof B)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return m(this,null,function*(){let t=yield this.getHeader(),n=yield this.getMetadata(),i=Ze(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${i}`],vector_layers:n.vector_layers,attribution:n.attribution,description:n.description,name:n.name,version:n.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};f(pe,"PMTiles");var P=pe;return et(Dt);})(); +//# sourceMappingURL=pmtiles.js.map \ No newline at end of file diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js new file mode 100644 index 0000000..2b7b5bf --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js @@ -0,0 +1,311 @@ +// Radius/Circle drawing mode for Mapbox GL Draw +// Creates a circle by drawing from center to edge +(function (MapboxDraw) { + const DrawLine = MapboxDraw.modes.draw_line_string; + + // Utility function to create a vertex feature + const createVertex = function (parentId, coordinates, path, selected) { + return { + type: "Feature", + properties: { + meta: "vertex", + parent: parentId, + coord_path: path, + active: selected ? "true" : "false" + }, + geometry: { + type: "Point", + coordinates: coordinates + } + }; + }; + + // Utility function to calculate distance between two points in kilometers + const calculateDistance = function (coord1, coord2) { + const lat1 = coord1[1]; + const lon1 = coord1[0]; + const lat2 = coord2[1]; + const lon2 = coord2[0]; + + const R = 6371; // Radius of the Earth in kilometers + const dLat = (lat2 - lat1) * Math.PI / 180; + const dLon = (lon2 - lon1) * Math.PI / 180; + const a = + Math.sin(dLat/2) * Math.sin(dLat/2) + + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * + Math.sin(dLon/2) * Math.sin(dLon/2); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + const distance = R * c; + + return distance; + }; + + // Utility function to create a GeoJSON circle + const createGeoJSONCircle = function (center, radiusInKm, parentId, points) { + points = points || 64; + + const coords = { + latitude: center[1], + longitude: center[0] + }; + + const km = radiusInKm; + const ret = []; + const distanceX = km / (111.32 * Math.cos((coords.latitude * Math.PI) / 180)); + const distanceY = km / 110.574; + + let theta, x, y; + for (let i = 0; i < points; i++) { + theta = (i / points) * (2 * Math.PI); + x = distanceX * Math.cos(theta); + y = distanceY * Math.sin(theta); + + ret.push([coords.longitude + x, coords.latitude + y]); + } + ret.push(ret[0]); + + return { + type: "Feature", + geometry: { + type: "Polygon", + coordinates: [ret] + }, + properties: { + parent: parentId, + meta: "radius" + } + }; + }; + + // Utility function to format distance for display + const getDisplayMeasurements = function (distanceKm) { + let metricUnits = "m"; + let metricFormat = "0,0"; + let metricMeasurement; + + let standardUnits = "feet"; + let standardFormat = "0,0"; + let standardMeasurement; + + metricMeasurement = distanceKm * 1000; // Convert to meters + if (metricMeasurement >= 1000) { + metricMeasurement = metricMeasurement / 1000; + metricUnits = "km"; + metricFormat = "0.00"; + } + + standardMeasurement = distanceKm * 1000 * 3.28084; // Convert to feet + if (standardMeasurement >= 5280) { + standardMeasurement = standardMeasurement / 5280; + standardUnits = "mi"; + standardFormat = "0.00"; + } + + // Simple number formatting (without numeral.js dependency) + const formatNumber = function(num, format) { + if (format === "0,0") { + return Math.round(num).toLocaleString(); + } else if (format === "0.00") { + return num.toFixed(2); + } + return num.toString(); + }; + + return { + metric: formatNumber(metricMeasurement, metricFormat) + " " + metricUnits, + standard: formatNumber(standardMeasurement, standardFormat) + " " + standardUnits + }; + }; + + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RadiusMode = Object.assign({}, DrawLine); + + RadiusMode.onSetup = function (opts) { + const line = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "LineString", + coordinates: [] + } + }); + + this.addFeature(line); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.activateUIButton("line"); + this.setActionableState({ trash: true }); + + return { + line: line, + currentVertexPosition: 0, + direction: "forward" + }; + }; + + RadiusMode.onClick = function (state, e) { + // This ends the drawing after the user creates a second point + if (state.currentVertexPosition === 1) { + // Update the second coordinate in place, don't add at position 0 + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + return this.changeMode("simple_select", { featureIds: [state.line.id] }); + } + + this.updateUIClasses({ mouse: "add" }); + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + + if (state.direction === "forward") { + state.currentVertexPosition += 1; + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + } else { + state.line.addCoordinate(0, e.lngLat.lng, e.lngLat.lat); + } + + return null; + }; + + RadiusMode.onMouseMove = function (state, e) { + if (state.currentVertexPosition === 1) { + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + } + }; + + // Creates the final geojson circle polygon + RadiusMode.onStop = function (state) { + doubleClickZoom.enable(this); + this.activateUIButton(); + + // Check to see if we've deleted this feature + if (this.getFeature(state.line.id) === undefined) return; + + if (state.line.isValid()) { + const lineGeoJson = state.line.toGeoJSON(); + const coords = lineGeoJson.geometry.coordinates; + + if (coords.length >= 2) { + // Calculate radius in kilometers + const radiusKm = calculateDistance(coords[0], coords[1]); + + // Create the circle polygon + const circleFeature = createGeoJSONCircle(coords[0], radiusKm, state.line.id); + + // Add radius property for reference + circleFeature.properties.radius = (radiusKm * 1000).toFixed(1); + + // Remove the meta property that was interfering + delete circleFeature.properties.meta; + delete circleFeature.properties.parent; + + // Delete the temporary line first + this.deleteFeature([state.line.id], { silent: true }); + + // Add the circle feature to the draw instance + const circleDrawFeature = this.newFeature(circleFeature); + this.addFeature(circleDrawFeature); + + this.map.fire("draw.create", { + features: [circleDrawFeature.toGeoJSON()] + }); + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + + this.changeMode("simple_select", {}, { silent: true }); + }; + + RadiusMode.toDisplayFeatures = function (state, geojson, display) { + const isActiveLine = geojson.properties.id === state.line.id; + geojson.properties.active = isActiveLine ? "true" : "false"; + + if (!isActiveLine) return display(geojson); + + // Only render the line if it has at least one real coordinate + if (geojson.geometry.coordinates.length < 2) return null; + + geojson.properties.meta = "feature"; + + // Display center vertex as a point feature + display(createVertex( + state.line.id, + geojson.geometry.coordinates[ + state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1 + ], + "" + (state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1), + false + )); + + // Display the line as it is drawn + display(geojson); + + const coords = geojson.geometry.coordinates; + if (coords.length >= 2) { + const distanceKm = calculateDistance(coords[0], coords[1]); + const displayMeasurements = getDisplayMeasurements(distanceKm); + + // Create custom feature for the current pointer position + const currentVertex = { + type: "Feature", + properties: { + meta: "currentPosition", + radiusMetric: displayMeasurements.metric, + radiusStandard: displayMeasurements.standard, + parent: state.line.id + }, + geometry: { + type: "Point", + coordinates: coords[1] + } + }; + display(currentVertex); + + // Create custom feature for radius circle + const center = coords[0]; + const circleFeature = createGeoJSONCircle(center, distanceKm, state.line.id); + display(circleFeature); + } + + return null; + }; + + RadiusMode.onTrash = function (state) { + this.deleteFeature([state.line.id], { silent: true }); + this.changeMode("simple_select"); + }; + + MapboxDraw.modes.draw_radius = RadiusMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js new file mode 100644 index 0000000..73af6d6 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js @@ -0,0 +1,124 @@ +// Rectangle drawing mode for Mapbox GL Draw +// Adapted from https://github.com/edgespatial/mapbox-gl-draw-rectangle-mode +(function (MapboxDraw) { + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RectangleMode = { + onSetup: function (opts) { + const rectangle = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "Polygon", + coordinates: [[]] + } + }); + + this.addFeature(rectangle); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.setActionableState({ trash: true }); + + return { + rectangle: rectangle + }; + }, + + onClick: function (state, e) { + // If we have a start point and click on a different point, complete the rectangle + if (state.startPoint && + (state.startPoint[0] !== e.lngLat.lng || state.startPoint[1] !== e.lngLat.lat)) { + this.updateUIClasses({ mouse: "pointer" }); + state.endPoint = [e.lngLat.lng, e.lngLat.lat]; + this.changeMode("simple_select", { featuresId: state.rectangle.id }); + return; + } + + // Set the start point + const startPoint = [e.lngLat.lng, e.lngLat.lat]; + state.startPoint = startPoint; + }, + + onMouseMove: function (state, e) { + // Update rectangle coordinates as the mouse moves + if (state.startPoint) { + const startX = state.startPoint[0]; + const startY = state.startPoint[1]; + const endX = e.lngLat.lng; + const endY = e.lngLat.lat; + + state.rectangle.updateCoordinate("0.0", startX, startY); + state.rectangle.updateCoordinate("0.1", endX, startY); + state.rectangle.updateCoordinate("0.2", endX, endY); + state.rectangle.updateCoordinate("0.3", startX, endY); + state.rectangle.updateCoordinate("0.4", startX, startY); + } + }, + + onKeyUp: function (state, e) { + if (e.keyCode === 27) { // Escape key + return this.changeMode("simple_select"); + } + }, + + onStop: function (state) { + doubleClickZoom.enable(this); + this.updateUIClasses({ mouse: "none" }); + this.activateUIButton(); + + if (this.getFeature(state.rectangle.id) !== undefined) { + // Remove the closing coordinate (duplicate of first) + state.rectangle.removeCoordinate("0.4"); + + if (state.rectangle.isValid()) { + this.map.fire("draw.create", { + features: [state.rectangle.toGeoJSON()] + }); + } else { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select", {}, { silent: true }); + } + } + }, + + toDisplayFeatures: function (state, geojson, display) { + const isActiveRectangle = geojson.properties.id === state.rectangle.id; + geojson.properties.active = isActiveRectangle ? "true" : "false"; + + if (!isActiveRectangle) { + return display(geojson); + } + + // Only display the rectangle if we have started drawing + if (state.startPoint) { + return display(geojson); + } + }, + + onTrash: function (state) { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select"); + } + }; + + MapboxDraw.modes.draw_rectangle = RectangleMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/lib/turf/turf.min.js b/docs/articles/map-design_files/turf-operations-1.0.0/lib/turf/turf.min.js new file mode 100644 index 0000000..635896d --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/lib/turf/turf.min.js @@ -0,0 +1,37 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).turf={})}(this,(function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}function u(t,e,n){return(e=y(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function l(t){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},l(t)}function h(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&p(t,e)}function c(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(c=function(){return!!t})()}function f(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}function g(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function p(t,e){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},p(t,e)}function v(t,e){return n(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,o,s,a=[],u=!0,l=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);u=!0);}catch(t){l=!0,i=t}finally{try{if(!u&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw i}}return a}}(t,e)||_(t,e)||g()}function d(t){return function(t){if(Array.isArray(t))return e(t)}(t)||f(t)||_(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function m(t){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},m(t)}function _(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var x=6371008.8,E={centimeters:100*x,centimetres:100*x,degrees:360/(2*Math.PI),feet:3.28084*x,inches:39.37*x,kilometers:x/1e3,kilometres:x/1e3,meters:x,metres:x,miles:x/1609.344,millimeters:1e3*x,millimetres:1e3*x,nauticalmiles:x/1852,radians:1,yards:1.0936*x},k={acres:247105e-9,centimeters:1e4,centimetres:1e4,feet:10.763910417,hectares:1e-4,inches:1550.003100006,kilometers:1e-6,kilometres:1e-6,meters:1,metres:1,miles:386e-9,nauticalmiles:2.9155334959812285e-7,millimeters:1e6,millimetres:1e6,yards:1.195990046};function b(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={type:"Feature"};return(0===n.id||n.id)&&(r.id=n.id),n.bbox&&(r.bbox=n.bbox),r.properties=e||{},r.geometry=t,r}function w(t,e){switch(t){case"Point":return I(e).geometry;case"LineString":return L(e).geometry;case"Polygon":return S(e).geometry;case"MultiPoint":return O(e).geometry;case"MultiLineString":return T(e).geometry;case"MultiPolygon":return R(e).geometry;default:throw new Error(t+" is invalid")}}function I(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("coordinates is required");if(!Array.isArray(t))throw new Error("coordinates must be an Array");if(t.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!U(t[0])||!U(t[1]))throw new Error("coordinates must contain numbers");return b({type:"Point",coordinates:t},e,n)}function N(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return I(t,e)})),n)}function S(t,e){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=a(t);try{for(i.s();!(n=i.n()).done;){var o=n.value;if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(var s=0;s2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return S(t,e)})),n)}function L(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(t.length<2)throw new Error("coordinates must be an array of two or more positions");return b({type:"LineString",coordinates:t},e,n)}function P(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return L(t,e)})),n)}function C(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={type:"FeatureCollection"};return e.id&&(n.id=e.id),e.bbox&&(n.bbox=e.bbox),n.features=t,n}function T(t,e){return b({type:"MultiLineString",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function O(t,e){return b({type:"MultiPoint",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function R(t,e){return b({type:"MultiPolygon",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function A(t,e){return b({type:"GeometryCollection",geometries:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function D(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e&&!(e>=0))throw new Error("precision must be a positive number");var n=Math.pow(10,e||0);return Math.round(t*n)/n}function F(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t*n}function q(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t/n}function V(t,e){return Y(q(t,e))}function G(t){var e=t%360;return e<0&&(e+=360),e}function B(t){return(t%=360)>180?t-360:t<-180?t+360:t}function Y(t){return 180*(t%(2*Math.PI))/Math.PI}function z(t){return t%360*Math.PI/180}function j(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("length must be a positive number");return F(q(t,e),n)}function X(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"meters",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("area must be a positive number");var r=k[e];if(!r)throw new Error("invalid original units");var i=k[n];if(!i)throw new Error("invalid final units");return t/r*i}function U(t){return!isNaN(t)&&null!==t&&!Array.isArray(t)}function Z(t){return null!==t&&"object"===m(t)&&!Array.isArray(t)}function H(t){if(!t)throw new Error("bbox is required");if(!Array.isArray(t))throw new Error("bbox must be an Array");if(4!==t.length&&6!==t.length)throw new Error("bbox must be an Array of 4 or 6 numbers");t.forEach((function(t){if(!U(t))throw new Error("bbox must only contain numbers")}))}function W(t){if(!t)throw new Error("id is required");if(-1===["string","number"].indexOf(m(t)))throw new Error("id must be a number or a string")}var J=Object.freeze({__proto__:null,areaFactors:k,azimuthToBearing:B,bearingToAzimuth:G,convertArea:X,convertLength:j,degreesToRadians:z,earthRadius:x,factors:E,feature:b,featureCollection:C,geometry:w,geometryCollection:A,isNumber:U,isObject:Z,lengthToDegrees:V,lengthToRadians:q,lineString:L,lineStrings:P,multiLineString:T,multiPoint:O,multiPolygon:R,point:I,points:N,polygon:S,polygons:M,radiansToDegrees:Y,radiansToLength:F,round:D,validateBBox:H,validateId:W});function K(t){if(!t)throw new Error("coord is required");if(!Array.isArray(t)){if("Feature"===t.type&&null!==t.geometry&&"Point"===t.geometry.type)return d(t.geometry.coordinates);if("Point"===t.type)return d(t.coordinates)}if(Array.isArray(t)&&t.length>=2&&!Array.isArray(t[0])&&!Array.isArray(t[1]))return d(t);throw new Error("coord must be GeoJSON Point or an Array of numbers")}function Q(t){if(Array.isArray(t))return t;if("Feature"===t.type){if(null!==t.geometry)return t.geometry.coordinates}else if(t.coordinates)return t.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function $(t){if(t.length>1&&U(t[0])&&U(t[1]))return!0;if(Array.isArray(t[0])&&t[0].length)return $(t[0]);throw new Error("coordinates must only contain numbers")}function tt(t,e,n){if(!e||!n)throw new Error("type and name required");if(!t||t.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.type)}function et(t,e,n){if(!t)throw new Error("No feature passed");if(!n)throw new Error(".featureOf() requires a name");if(!t||"Feature"!==t.type||!t.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!t.geometry||t.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.geometry.type)}function nt(t,e,n){if(!t)throw new Error("No featureCollection passed");if(!n)throw new Error(".collectionOf() requires a name");if(!t||"FeatureCollection"!==t.type)throw new Error("Invalid input to "+n+", FeatureCollection required");var r,i=a(t.features);try{for(i.s();!(r=i.n()).done;){var o=r.value;if(!o||"Feature"!==o.type||!o.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!o.geometry||o.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+o.geometry.type)}}catch(t){i.e(t)}finally{i.f()}}function rt(t){return"Feature"===t.type?t.geometry:t}function it(t,e){return"FeatureCollection"===t.type?"FeatureCollection":"GeometryCollection"===t.type?"GeometryCollection":"Feature"===t.type&&null!==t.geometry?t.geometry.type:t.type}var ot=Object.freeze({__proto__:null,collectionOf:nt,containsNumber:$,featureOf:et,geojsonType:tt,getCoord:K,getCoords:Q,getGeom:rt,getType:it});function st(t,e){if(!0===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final)return function(t,e){var n=st(e,t);return n=(n+180)%360}(t,e);var n=K(t),r=K(e),i=z(n[0]),o=z(r[0]),s=z(n[1]),a=z(r[1]),u=Math.sin(o-i)*Math.cos(a),l=Math.cos(s)*Math.sin(a)-Math.sin(s)*Math.cos(a)*Math.cos(o-i);return Y(Math.atan2(u,l))}function at(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=K(t),o=z(i[0]),s=z(i[1]),a=z(n),u=q(e,r.units),l=Math.asin(Math.sin(s)*Math.cos(u)+Math.cos(s)*Math.sin(u)*Math.cos(a));return I([Y(o+Math.atan2(Math.sin(a)*Math.sin(u)*Math.cos(s),Math.cos(u)-Math.sin(s)*Math.sin(l))),Y(l)],r.properties)}function ut(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e),o=z(i[1]-r[1]),s=z(i[0]-r[0]),a=z(r[1]),u=z(i[1]),l=Math.pow(Math.sin(o/2),2)+Math.pow(Math.sin(s/2),2)*Math.cos(a)*Math.cos(u);return F(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)),n.units)}function lt(t,e){var n;return(n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final?ht(K(e),K(t)):ht(K(t),K(e)))>180?-(360-n):n}function ht(t,e){var n=z(t[1]),r=z(e[1]),i=z(e[0]-t[0]);i>Math.PI&&(i-=2*Math.PI),i<-Math.PI&&(i+=2*Math.PI);var o=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(n/2+Math.PI/4));return(Y(Math.atan2(i,o))+360)%360}function ct(t,e,n){if(null!==t)for(var r,i,o,s,a,u,l,h,c=0,f=0,g=t.type,p="FeatureCollection"===g,v="Feature"===g,d=p?t.features.length:1,y=0;ya||f>u||g>l)return s=o,a=n,u=f,l=g,void(i=0);var p=L([s,o],t.properties);if(!1===e(p,n,r,g,i))return!1;i++,s=o}))&&void 0}}}))}function bt(t,e,n){var r=n,i=!1;return kt(t,(function(t,o,s,a,u){r=!1===i&&void 0===n?t:e(r,t,o,s,a,u),i=!0})),r}function wt(t,e){if(!t)throw new Error("geojson is required");xt(t,(function(t,n,r){if(null!==t.geometry){var i=t.geometry.type,o=t.geometry.coordinates;switch(i){case"LineString":if(!1===e(t,n,r,0,0))return!1;break;case"Polygon":for(var s=0;s0){e+=Math.abs(Ot(t[0]));for(var n=1;n=e?(r+2)%e:r+2],a=i[0]*Tt,u=o[1]*Tt;n+=(s[0]*Tt-a)*Math.sin(u),r++}return n*Ct}function Rt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=t.bbox&&!0!==e.recompute)return t.bbox;var n=[1/0,1/0,-1/0,-1/0];return ct(t,(function(t){n[0]>t[0]&&(n[0]=t[0]),n[1]>t[1]&&(n[1]=t[1]),n[2]e[2]&&(n|=2),t[1]e[3]&&(n|=8),n}function qt(t,e){var n,r=[],i=a(t);try{for(i.s();!(n=i.n()).done;){var o=At(n.value,e);o.length>0&&(o[0][0]===o[o.length-1][0]&&o[0][1]===o[o.length-1][1]||o.push(o[0]),o.length>=4&&r.push(o))}}catch(t){i.e(t)}finally{i.f()}return r}function Vt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Number(t[0]),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]);if(6===t.length)throw new Error("@turf/bbox-polygon does not support BBox with 6 positions");var s=[n,r];return S([[s,[i,r],[i,o],[n,o],s]],e.properties,{bbox:t,id:e.id})}var Gt=function(){return s((function t(e){i(this,t),this.points=e.points||[],this.duration=e.duration||1e4,this.sharpness=e.sharpness||.85,this.centers=[],this.controls=[],this.stepLength=e.stepLength||60,this.length=this.points.length,this.delay=0;for(var n=0;nt&&(e.push(r),n=i)}return e}},{key:"vector",value:function(t){var e=this.pos(t+10),n=this.pos(t-10);return{angle:180*Math.atan2(e.y-n.y,e.x-n.x)/3.14,speed:Math.sqrt((n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y)+(n.z-e.z)*(n.z-e.z))}}},{key:"pos",value:function(t){var e=t-this.delay;e<0&&(e=0),e>this.duration&&(e=this.duration-1);var n=e/this.duration;if(n>=1)return this.points[this.length-1];var r=Math.floor((this.points.length-1)*n);return function(t,e,n,r,i){var o=function(t){var e=t*t,n=e*t;return[n,3*e*(1-t),3*t*(1-t)*(1-t),(1-t)*(1-t)*(1-t)]}(t),s={x:i.x*o[0]+r.x*o[1]+n.x*o[2]+e.x*o[3],y:i.y*o[0]+r.y*o[1]+n.y*o[2]+e.y*o[3],z:i.z*o[0]+r.z*o[1]+n.z*o[2]+e.z*o[3]};return s}((this.length-1)*n-r,this.points[r],this.controls[r][1],this.controls[r+1][0],this.points[r+1])}}])}();function Bt(t){for(var e,n,r=Q(t),i=0,o=1;o0}function Yt(t,e){for(var n=0,r=0,i=0,o=0,s=0,a=0,u=0,l=0,h=null,c=null,f=t[0],g=t[1],p=e.length;n0&&l>0)a=l,s=(h=c)[0]-f;else{if(u=c[0]-t[0],l>0&&a<=0){if((o=s*l-u*a)>0)i+=1;else if(0===o)return 0}else if(a>0&&l<=0){if((o=s*l-u*a)<0)i+=1;else if(0===o)return 0}else if(0===l&&a<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&l<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&0===l){if(u<=0&&s>=0)return 0;if(s<=0&&u>=0)return 0}h=c,a=l,s=u}}return i%2!=0}function zt(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("point is required");if(!e)throw new Error("polygon is required");var r=K(t),i=rt(e),o=i.type,s=e.bbox,a=i.coordinates;if(s&&!1===function(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}(r,s))return!1;"Polygon"===o&&(a=[a]);for(var u=!1,l=0;l2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=Q(e),o=0;oi)return!1}else if(0!==g)return!1;return Math.abs(c)===Math.abs(f)&&0===Math.abs(c)?!r&&(n[0]===t[0]&&n[1]===t[1]):r?"start"===r?Math.abs(c)>=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o0?u<=s&&s=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o<=l:l<=o&&o<=a:f>0?u<=s&&s<=h:h<=s&&s<=u}function Ut(t,e){if("Feature"===t.type&&null===t.geometry)return!1;if("Feature"===e.type&&null===e.geometry)return!1;if(!Zt(Rt(t),Rt(e)))return!1;var n,r=a(rt(e).coordinates);try{for(r.s();!(n=r.n()).done;){var i,o=a(n.value);try{for(o.s();!(i=o.n()).done;){if(!zt(i.value,t))return!1}}catch(t){o.e(t)}finally{o.f()}}}catch(t){r.e(t)}finally{r.f()}return!0}function Zt(t,e){return!(t[0]>e[0])&&(!(t[2]e[1])&&!(t[3]0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Kt;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function Kt(t,e){return te?1:0}function Qt(t,e){return t.p.x>e.p.x?1:t.p.xe.p.y?1:-1:1}function $t(t,e){return t.rightSweepEvent.p.x>e.rightSweepEvent.p.x?1:t.rightSweepEvent.p.x0?(h.isLeftEndpoint=!0,l.isLeftEndpoint=!1):(l.isLeftEndpoint=!0,h.isLeftEndpoint=!1),e.push(l),e.push(h),s=a,re+=1}}ee+=1}var oe=s((function t(e){i(this,t),this.leftSweepEvent=e,this.rightSweepEvent=e.otherEvent}));function se(t,e){if(null===t||null===e)return!1;if(t.leftSweepEvent.ringId===e.leftSweepEvent.ringId&&(t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.rightSweepEvent)||t.leftSweepEvent.isSamePoint(e.leftSweepEvent)||t.leftSweepEvent.isSamePoint(e.rightSweepEvent)))return!1;var n=t.leftSweepEvent.p.x,r=t.leftSweepEvent.p.y,i=t.rightSweepEvent.p.x,o=t.rightSweepEvent.p.y,s=e.leftSweepEvent.p.x,a=e.leftSweepEvent.p.y,u=e.rightSweepEvent.p.x,l=e.rightSweepEvent.p.y,h=(l-a)*(i-n)-(u-s)*(o-r),c=(u-s)*(r-a)-(l-a)*(n-s),f=(i-n)*(r-a)-(o-r)*(n-s);if(0===h)return!1;var g=c/h,p=f/h;return g>=0&&g<=1&&p>=0&&p<=1&&[n+g*(i-n),r+g*(o-r)]}var ae=function(t,e){var n=new Jt([],Qt);return function(t,e){if("FeatureCollection"===t.type)for(var n=t.features,r=0;r2&&void 0!==arguments[2]?arguments[2]:{},r=n.removeDuplicates,i=void 0===r||r,o=n.ignoreSelfIntersections,s=void 0===o||o,a=[];"FeatureCollection"===t.type?a=a.concat(t.features):"Feature"===t.type?a.push(t):"LineString"!==t.type&&"Polygon"!==t.type&&"MultiLineString"!==t.type&&"MultiPolygon"!==t.type||a.push(b(t)),"FeatureCollection"===e.type?a=a.concat(e.features):"Feature"===e.type?a.push(e):"LineString"!==e.type&&"Polygon"!==e.type&&"MultiLineString"!==e.type&&"MultiPolygon"!==e.type||a.push(b(e));var u=ae(C(a),s),l=[];if(i){var h={};u.forEach((function(t){var e=t.join(",");h[e]||(h[e]=!0,l.push(t))}))}else l=u;return C(l.map((function(t){return I(t)})))}function le(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t);switch(e.properties||"Feature"!==t.type||(e.properties=t.properties),n.type){case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{};return he(r,i)}(n,e);case"MultiPolygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{},o=[];return r.forEach((function(t){o.push(he(t,i))})),C(o)}(n,e);default:throw new Error("invalid poly")}}function he(t,e){return t.length>1?T(t,e):L(t[0],e)}function ce(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;switch(i){case"MultiPoint":switch(o){case"LineString":return fe(n,r);case"Polygon":return pe(n,r);default:throw new Error("feature2 "+o+" geometry not supported")}case"LineString":switch(o){case"MultiPoint":return fe(r,n);case"LineString":return function(t,e){if(ue(t,e).features.length>0)for(var n=0;n0}function pe(t,e){for(var n=!1,r=!1,i=t.coordinates.length,o=0;o=Math.abs(a)?s>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:a>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1]:Math.abs(s)>=Math.abs(a)?s>0?t[0]0?t[1]2&&void 0!==arguments[2]?arguments[2]:{ignoreSelfIntersections:!0}).ignoreSelfIntersections,r=void 0===n||n,i=!0;return xt(t,(function(t){xt(e,(function(e){if(!1===i)return!1;i=function(t,e,n){switch(t.type){case"Point":switch(e.type){case"Point":return r=t.coordinates,i=e.coordinates,!(r[0]===i[0]&&r[1]===i[1]);case"LineString":return!ye(e,t);case"Polygon":return!zt(t,e)}break;case"LineString":switch(e.type){case"Point":return!ye(t,e);case"LineString":return!function(t,e,n){var r=ue(t,e,{ignoreSelfIntersections:n});if(r.features.length>0)return!0;return!1}(t,e,n);case"Polygon":return!me(e,t,n)}break;case"Polygon":switch(e.type){case"Point":return!zt(e,t);case"LineString":return!me(t,e,n);case"Polygon":return!function(t,e,n){var r,i=a(t.coordinates[0]);try{for(i.s();!(r=i.n()).done;){if(zt(r.value,e))return!0}}catch(t){i.e(t)}finally{i.f()}var o,s=a(e.coordinates[0]);try{for(s.s();!(o=s.n()).done;){if(zt(o.value,t))return!0}}catch(t){s.e(t)}finally{s.f()}var u=ue(le(t),le(e),{ignoreSelfIntersections:n});if(u.features.length>0)return!0;return!1}(e,t,n)}}var r,i;return!1}(t.geometry,e.geometry,r)}))})),i}function ye(t,e){for(var n=0;n0}function _e(t,e,n){var r=n[0]-t[0],i=n[1]-t[1],o=e[0]-t[0],s=e[1]-t[1];return 0==r*s-i*o&&(Math.abs(o)>=Math.abs(s)?o>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:s>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1])}var xe=Object.defineProperty,Ee=function(t,e){return xe(t,"name",{value:e,configurable:!0})},ke=function(){return s((function t(e){var n,r,o;i(this,t),this.direction=!1,this.compareProperties=!0,this.precision=Math.pow(10,-(null!=(n=null==e?void 0:e.precision)?n:17)),this.direction=null!=(r=null==e?void 0:e.direction)&&r,this.compareProperties=null==(o=null==e?void 0:e.compareProperties)||o}),[{key:"compare",value:function(t,e){var n=this;if(t.type!==e.type)return!1;if(!we(t,e))return!1;switch(t.type){case"Point":return this.compareCoord(t.coordinates,e.coordinates);case"LineString":return this.compareLine(t.coordinates,e.coordinates);case"Polygon":return this.comparePolygon(t,e);case"GeometryCollection":return this.compareGeometryCollection(t,e);case"Feature":return this.compareFeature(t,e);case"FeatureCollection":return this.compareFeatureCollection(t,e);default:if(t.type.startsWith("Multi")){var r=Ie(t),i=Ie(e);return r.every((function(t){return i.some((function(e){return n.compare(t,e)}))}))}}return!1}},{key:"compareCoord",value:function(t,e){var n=this;return t.length===e.length&&t.every((function(t,r){return Math.abs(t-e[r])2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!we(t,e))return!1;var i=t,o=e;if(r&&!this.compareCoord(i[0],o[0])){var s=this.fixStartIndex(o,i);if(!s)return!1;o=s}var a=this.compareCoord(i[n],o[n]);return this.direction||a?this.comparePath(i,o):!!this.compareCoord(i[n],o[o.length-(1+n)])&&this.comparePath(i.slice().reverse(),o)}},{key:"fixStartIndex",value:function(t,e){for(var n,r=-1,i=0;i=0&&(n=[].concat(t.slice(r,t.length),t.slice(1,r+1))),n}},{key:"comparePath",value:function(t,e){var n=this;return t.every((function(t,r){return n.compareCoord(t,e[r])}))}},{key:"comparePolygon",value:function(t,e){var n=this;if(this.compareLine(t.coordinates[0],e.coordinates[0],1,!0)){var r=t.coordinates.slice(1,t.coordinates.length),i=e.coordinates.slice(1,e.coordinates.length);return r.every((function(t){return i.some((function(e){return n.compareLine(t,e,1,!0)}))}))}return!1}},{key:"compareGeometryCollection",value:function(t,e){var n=this;return we(t.geometries,e.geometries)&&this.compareBBox(t,e)&&t.geometries.every((function(t,r){return n.compare(t,e.geometries[r])}))}},{key:"compareFeature",value:function(t,e){return t.id===e.id&&(!this.compareProperties||Se(t.properties,e.properties))&&this.compareBBox(t,e)&&this.compare(t.geometry,e.geometry)}},{key:"compareFeatureCollection",value:function(t,e){var n=this;return we(t.features,e.features)&&this.compareBBox(t,e)&&t.features.every((function(t,r){return n.compare(t,e.features[r])}))}},{key:"compareBBox",value:function(t,e){return Boolean(!t.bbox&&!e.bbox)||!(!t.bbox||!e.bbox)&&this.compareCoord(t.bbox,e.bbox)}}])}();Ee(ke,"GeojsonEquality");var be=ke;function we(t,e){return t.coordinates?t.coordinates.length===e.coordinates.length:t.length===e.length}function Ie(t){return t.coordinates.map((function(e){return{type:t.type.replace("Multi",""),coordinates:e}}))}function Ne(t,e,n){return new be(n).compare(t,e)}function Se(t,e){if(null===t&&null===e)return!0;if(null===t||null===e)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(var i=0,o=n;i1&&void 0!==arguments[1]?arguments[1]:{},n="object"===m(e)?e.mutate:e;if(!t)throw new Error("geojson is required");var r=it(t),i=[];switch(r){case"LineString":i=Pe(t,r);break;case"MultiLineString":case"Polygon":Q(t).forEach((function(t){i.push(Pe(t,r))}));break;case"MultiPolygon":Q(t).forEach((function(t){var e=[];t.forEach((function(t){e.push(Pe(t,r))})),i.push(e)}));break;case"Point":return t;case"MultiPoint":var o={};Q(t).forEach((function(t){var e=t.join("-");Object.prototype.hasOwnProperty.call(o,e)||(i.push(t),o[e]=!0)}));break;default:throw new Error(r+" geometry not supported")}return t.coordinates?!0===n?(t.coordinates=i,t):{type:r,coordinates:i}:!0===n?(t.geometry.coordinates=i,t):b({type:r,coordinates:i},t.properties,{bbox:t.bbox,id:t.id})}function Pe(t,e){var n=Q(t);if(2===n.length&&!Ce(n[0],n[1]))return n;var r=[],i=n.length-1,o=r.length;r.push(n[0]);for(var s=1;s2&&Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1))}if(r.push(n[n.length-1]),o=r.length,("Polygon"===e||"MultiPolygon"===e)&&Ce(n[0],n[n.length-1])&&o<4)throw new Error("invalid polygon");return"LineString"===e&&o<3||Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1),r}function Ce(t,e){return t[0]===e[0]&&t[1]===e[1]}function Te(t,e,n){var r=n[0],i=n[1],o=t[0],s=t[1],a=e[0],u=e[1],l=a-o,h=u-s;return 0===(r-o)*h-(i-s)*l&&(Math.abs(l)>=Math.abs(h)?l>0?o<=r&&r<=a:a<=r&&r<=o:h>0?s<=i&&i<=u:u<=i&&i<=s)}function Oe(t,e){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).ignoreSelfIntersections,r=void 0===n||n,i=!1;return xt(t,(function(t){xt(e,(function(e){if(!0===i)return!0;i=!de(t.geometry,e.geometry,{ignoreSelfIntersections:r})}))})),i}function Re(t,e,n,r,i){Ae(t,e,n||0,r||t.length-1,i||Fe)}function Ae(t,e,n,r,i){for(;r>n;){if(r-n>600){var o=r-n+1,s=e-n+1,a=Math.log(o),u=.5*Math.exp(2*a/3),l=.5*Math.sqrt(a*u*(o-u)/o)*(s-o/2<0?-1:1);Ae(t,e,Math.max(n,Math.floor(e-s*u/o+l)),Math.min(r,Math.floor(e+(o-s)*u/o+l)),i)}var h=t[e],c=n,f=r;for(De(t,n,e),i(t[r],h)>0&&De(t,n,r);c0;)f--}0===i(t[n],h)?De(t,n,f):De(t,++f,r),f<=e&&(n=f+1),e<=f&&(r=f-1)}}function De(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function Fe(t,e){return te?1:0}var qe=function(){return s((function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:9;i(this,t),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}),[{key:"all",value:function(){return this._all(this.data,[])}},{key:"search",value:function(t){var e=this.data,n=[];if(!He(t,e))return n;for(var r=this.toBBox,i=[];e;){for(var o=0;o=0&&i[e].children.length>this._maxEntries;)this._split(i,e),e--;this._adjustParentBBoxes(r,i,e)}},{key:"_split",value:function(t,e){var n=t[e],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=We(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,Ge(n,this.toBBox),Ge(s,this.toBBox),e?t[e-1].children.push(s):this._splitRoot(n,s)}},{key:"_splitRoot",value:function(t,e){this.data=We([t,e]),this.data.height=t.height+1,this.data.leaf=!1,Ge(this.data,this.toBBox)}},{key:"_chooseSplitIndex",value:function(t,e,n){for(var r,i,o,s,a,u,l,h=1/0,c=1/0,f=e;f<=n-e;f++){var g=Be(t,0,f,this.toBBox),p=Be(t,f,n,this.toBBox),v=(i=g,o=p,s=void 0,a=void 0,u=void 0,l=void 0,s=Math.max(i.minX,o.minX),a=Math.max(i.minY,o.minY),u=Math.min(i.maxX,o.maxX),l=Math.min(i.maxY,o.maxY),Math.max(0,u-s)*Math.max(0,l-a)),d=Xe(g)+Xe(p);v=e;h--){var c=t.children[h];Ye(s,t.leaf?i(c):c),a+=Ue(s)}return a}},{key:"_adjustParentBBoxes",value:function(t,e,n){for(var r=n;r>=0;r--)Ye(e[r],t)}},{key:"_condense",value:function(t){for(var e,n=t.length-1;n>=0;n--)0===t[n].children.length?n>0?(e=t[n-1].children).splice(e.indexOf(t[n]),1):this.clear():Ge(t[n],this.toBBox)}}])}();function Ve(t,e,n){if(!n)return e.indexOf(t);for(var r=0;r=t.minX&&e.maxY>=t.minY}function We(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Je(t,e,n,r,i){for(var o=[e,n];o.length;)if(!((n=o.pop())-(e=o.pop())<=r)){var s=e+Math.ceil((n-e)/r/2)*r;Re(t,s,e,n,i),o.push(e,s,s,n)}}var Ke=Object.freeze({__proto__:null,default:qe});function Qe(t){var e=new qe(t);return e.insert=function(t){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.insert.call(this,t)},e.load=function(t){var e=[];return Array.isArray(t)?t.forEach((function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})):vt(t,(function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})),qe.prototype.load.call(this,e)},e.remove=function(t,e){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.remove.call(this,t,e)},e.clear=function(){return qe.prototype.clear.call(this)},e.search=function(t){return C(qe.prototype.search.call(this,this.toBBox(t)))},e.collides=function(t){return qe.prototype.collides.call(this,this.toBBox(t))},e.all=function(){return C(qe.prototype.all.call(this))},e.toJSON=function(){return qe.prototype.toJSON.call(this)},e.fromJSON=function(t){return qe.prototype.fromJSON.call(this,t)},e.toBBox=function(t){var e;if(t.bbox)e=t.bbox;else if(Array.isArray(t)&&4===t.length)e=t;else if(Array.isArray(t)&&6===t.length)e=[t[0],t[1],t[3],t[4]];else if("Feature"===t.type)e=Rt(t);else{if("FeatureCollection"!==t.type)throw new Error("invalid geojson");e=Rt(t)}return{minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}},e}function $e(t){if(!t)throw new Error("geojson is required");var e=[];return xt(t,(function(t){!function(t,e){var n=[],r=t.geometry;if(null!==r){switch(r.type){case"Polygon":n=Q(r);break;case"LineString":n=[Q(r)]}n.forEach((function(n){var r=function(t,e){var n=[];return t.reduce((function(t,r){var i=L([t,r],e);return i.bbox=function(t,e){var n=t[0],r=t[1],i=e[0],o=e[1],s=ni?n:i,l=r>o?r:o;return[s,a,u,l]}(t,r),n.push(i),r})),n}(n,t.properties);r.forEach((function(t){t.id=e.length,e.push(t)}))}))}}(t,e)})),C(e)}var tn,en,nn=Object.defineProperty,rn=Object.defineProperties,on=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertySymbols,an=Object.prototype.hasOwnProperty,un=Object.prototype.propertyIsEnumerable,ln=function(t,e,n){return e in t?nn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},hn=function(t,e){for(var n in e||(e={}))an.call(e,n)&&ln(t,n,e[n]);if(sn){var r,i=a(sn(e));try{for(i.s();!(r=i.n()).done;){n=r.value;un.call(e,n)&&ln(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},cn=function(t,e){return rn(t,on(e))};function fn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t||!e)throw new Error("lines and pt are required arguments");var r=K(e),i=I([1/0,1/0],{dist:1/0,index:-1,multiFeatureIndex:-1,location:-1}),o=0;return xt(t,(function(t,s,a){for(var u=Q(t),l=0;lR||pn(p,f)>R?ut(dn(f),dn(g))<=ut(dn(f),dn(p))?[dn(g),!0,!1]:[dn(p),!1,!0]:[dn(f),!1,!1]}function mn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function _n(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var n=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,r.get?r:{enumerable:!0,get:function(){return t[e]}})})),n}var xn=(en||(en=1,tn=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==m(e)&&"object"==m(n)){if(e.constructor!==n.constructor)return!1;var r,i,o;if(Array.isArray(e)){if((r=e.length)!=n.length)return!1;for(i=r;0!=i--;)if(!t(e[i],n[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((r=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(i=r;0!=i--;)if(!Object.prototype.hasOwnProperty.call(n,o[i]))return!1;for(i=r;0!=i--;){var s=o[i];if(!t(e[s],n[s]))return!1}return!0}return e!=e&&n!=n}),tn),En=mn(xn);function kn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r,i=n.tolerance||0,o=[],s=Qe(),a=$e(t);s.load(a);var u=[];return kt(e,(function(t){var e=!1;t&&(vt(s.search(t),(function(n){if(!1===e){var o=Q(t).sort(),s=Q(n).sort();if(En(o,s))e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(o[0],n)&&jt(o[1],n):fn(n,o[0]).properties.dist<=i&&fn(n,o[1]).properties.dist<=i)e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(s[0],t)&&jt(s[1],t):fn(t,s[0]).properties.dist<=i&&fn(t,s[1]).properties.dist<=i)if(r){var a=bn(r,n);a?r=a:u.push(n)}else r=n}})),!1===e&&r&&(o.push(r),u.length&&(o=o.concat(u),u=[]),r=void 0))})),r&&o.push(r),C(o)}function bn(t,e){var n=Q(e),r=Q(t),i=r[0],o=r[r.length-1],s=t.geometry.coordinates;if(En(n[0],i))s.unshift(n[1]);else if(En(n[0],o))s.push(n[1]);else if(En(n[1],i))s.unshift(n[0]);else{if(!En(n[1],o))return;s.push(n[0])}return t}function wn(t,e){var n=G(lt(t[0],t[1])),r=G(lt(e[0],e[1]));return n===r||(r-n)%180==0}function In(t,e){if(t.geometry&&t.geometry.type)return t.geometry.type;if(t.type)return t.type;throw new Error("Invalid GeoJSON object for "+e)}function Nn(t,e){return!!Sn(e.coordinates[0],t.coordinates)||!!Sn(e.coordinates[e.coordinates.length-1],t.coordinates)}function Sn(t,e){return t[0]===e[0]&&t[1]===e[1]}function Mn(t){return t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]}function Ln(t){for(var e=0;ee[0])&&(!(t[2]e[1])&&!(t[3]1&&void 0!==arguments[1]?arguments[1]:{},n=Rt(t);return I([(n[0]+n[2])/2,(n[1]+n[3])/2],e.properties,e)}var Dn,Fn={exports:{}};var qn=(Dn||(Dn=1,function(t,e){t.exports=function(){function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}var y=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getEndCapStyle",value:function(){return this._endCapStyle}},{key:"isSingleSided",value:function(){return this._isSingleSided}},{key:"setQuadrantSegments",value:function(t){this._quadrantSegments=t,0===this._quadrantSegments&&(this._joinStyle=e.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=e.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),t<=0&&(this._quadrantSegments=1),this._joinStyle!==e.JOIN_ROUND&&(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS)}},{key:"getJoinStyle",value:function(){return this._joinStyle}},{key:"setJoinStyle",value:function(t){this._joinStyle=t}},{key:"setSimplifyFactor",value:function(t){this._simplifyFactor=t<0?0:t}},{key:"getSimplifyFactor",value:function(){return this._simplifyFactor}},{key:"getQuadrantSegments",value:function(){return this._quadrantSegments}},{key:"setEndCapStyle",value:function(t){this._endCapStyle=t}},{key:"getMitreLimit",value:function(){return this._mitreLimit}},{key:"setMitreLimit",value:function(t){this._mitreLimit=t}},{key:"setSingleSided",value:function(t){this._isSingleSided=t}}],[{key:"constructor_",value:function(){if(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=e.CAP_ROUND,this._joinStyle=e.JOIN_ROUND,this._mitreLimit=e.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=e.DEFAULT_SIMPLIFY_FACTOR,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.setQuadrantSegments(t)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.setQuadrantSegments(n),this.setEndCapStyle(r)}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];this.setQuadrantSegments(i),this.setEndCapStyle(o),this.setJoinStyle(s),this.setMitreLimit(a)}}},{key:"bufferDistanceError",value:function(t){var e=Math.PI/2/t;return 1-Math.cos(e/2)}}]),e}();y.CAP_ROUND=1,y.CAP_FLAT=2,y.CAP_SQUARE=3,y.JOIN_ROUND=1,y.JOIN_MITRE=2,y.JOIN_BEVEL=3,y.DEFAULT_QUADRANT_SEGMENTS=8,y.DEFAULT_MITRE_LIMIT=5,y.DEFAULT_SIMPLIFY_FACTOR=.01;var _=function(e){r(o,e);var i=c(o);function o(e){var n;return t(this,o),(n=i.call(this,e)).name=Object.keys({Exception:o})[0],n}return n(o,[{key:"toString",value:function(){return this.message}}]),o}(u(Error)),x=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({IllegalArgumentException:i})[0],r}return i}(_),E=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}();function k(){}function b(){}function w(){}var I,N,S,M,L,P,C,T,O=function(){function e(){t(this,e)}return n(e,null,[{key:"equalsWithTolerance",value:function(t,e,n){return Math.abs(t-e)<=n}}]),e}(),R=function(){function e(n,r){t(this,e),this.low=r||0,this.high=n||0}return n(e,null,[{key:"toBinaryString",value:function(t){var e,n="";for(e=2147483648;e>0;e>>>=1)n+=(t.high&e)===e?"1":"0";for(e=2147483648;e>0;e>>>=1)n+=(t.low&e)===e?"1":"0";return n}}]),e}();function A(){}function D(){}A.NaN=NaN,A.isNaN=function(t){return Number.isNaN(t)},A.isInfinite=function(t){return!Number.isFinite(t)},A.MAX_VALUE=Number.MAX_VALUE,A.POSITIVE_INFINITY=Number.POSITIVE_INFINITY,A.NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,"function"==typeof Float64Array&&"function"==typeof Int32Array?(P=2146435072,C=new Float64Array(1),T=new Int32Array(C.buffer),A.doubleToLongBits=function(t){C[0]=t;var e=0|T[0],n=0|T[1];return(n&P)===P&&0!=(1048575&n)&&0!==e&&(e=0,n=2146959360),new R(n,e)},A.longBitsToDouble=function(t){return T[0]=t.low,T[1]=t.high,C[0]}):(I=1023,N=Math.log2,S=Math.floor,M=Math.pow,L=function(){for(var t=53;t>0;t--){var e=M(2,t)-1;if(S(N(e))+1===t)return e}return 0}(),A.doubleToLongBits=function(t){var e,n,r,i,o,s,a,u,l;if(t<0||1/t===Number.NEGATIVE_INFINITY?(s=1<<31,t=-t):s=0,0===t)return new R(u=s,l=0);if(t===1/0)return new R(u=2146435072|s,l=0);if(t!=t)return new R(u=2146959360,l=0);if(i=0,l=0,(e=S(t))>1)if(e<=L)(i=S(N(e)))<=20?(l=0,u=e<<20-i&1048575):(l=e%(n=M(2,r=i-20))<<32-r,u=e/n&1048575);else for(r=e,l=0;0!==(r=S(n=r/2));)i++,l>>>=1,l|=(1&u)<<31,u>>>=1,n!==r&&(u|=524288);if(a=i+I,o=0===e,e=t-e,i<52&&0!==e)for(r=0;;){if((n=2*e)>=1?(e=n-1,o?(a--,o=!1):(r<<=1,r|=1,i++)):(e=n,o?0==--a&&(i++,o=!1):(r<<=1,i++)),20===i)u|=r,r=0;else if(52===i){l|=r;break}if(1===n){i<20?u|=r<<20-i:i<52&&(l|=r<<52-i);break}}return u|=a<<20,new R(u|=s,l)},A.longBitsToDouble=function(t){var e,n,r,i,o=t.high,s=t.low,a=o&1<<31?-1:1;for(r=((2146435072&o)>>20)-I,i=0,n=1<<19,e=1;e<=20;e++)o&n&&(i+=M(2,-e)),n>>>=1;for(n=1<<31,e=21;e<=52;e++)s&n&&(i+=M(2,-e)),n>>>=1;if(-1023===r){if(0===i)return 0*a;r=-1022}else{if(1024===r)return 0===i?a/0:NaN;i+=1}return a*i*M(2,r)});var F=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({RuntimeException:i})[0],r}return i}(_),q=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){if(0===arguments.length)F.constructor_.call(this);else if(1===arguments.length){var t=arguments[0];F.constructor_.call(this,t)}}}]),o}(F),V=function(){function e(){t(this,e)}return n(e,null,[{key:"shouldNeverReachHere",value:function(){if(0===arguments.length)e.shouldNeverReachHere(null);else if(1===arguments.length){var t=arguments[0];throw new q("Should never reach here"+(null!==t?": "+t:""))}}},{key:"isTrue",value:function(){if(1===arguments.length){var t=arguments[0];e.isTrue(t,null)}else if(2===arguments.length){var n=arguments[1];if(!arguments[0])throw null===n?new q:new q(n)}}},{key:"equals",value:function(){if(2===arguments.length){var t=arguments[0],n=arguments[1];e.equals(t,n,null)}else if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2];if(!i.equals(r))throw new q("Expected "+r+" but encountered "+i+(null!==o?": "+o:""))}}}]),e}(),G=new ArrayBuffer(8),B=new Float64Array(G),Y=new Int32Array(G),z=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getM",value:function(){return A.NaN}},{key:"setOrdinate",value:function(t,n){switch(t){case e.X:this.x=n;break;case e.Y:this.y=n;break;case e.Z:this.setZ(n);break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"equals2D",value:function(){if(1===arguments.length){var t=arguments[0];return this.x===t.x&&this.y===t.y}if(2===arguments.length){var e=arguments[0],n=arguments[1];return!!O.equalsWithTolerance(this.x,e.x,n)&&!!O.equalsWithTolerance(this.y,e.y,n)}}},{key:"setM",value:function(t){throw new x("Invalid ordinate index: "+e.M)}},{key:"getZ",value:function(){return this.z}},{key:"getOrdinate",value:function(t){switch(t){case e.X:return this.x;case e.Y:return this.y;case e.Z:return this.getZ()}throw new x("Invalid ordinate index: "+t)}},{key:"equals3D",value:function(t){return this.x===t.x&&this.y===t.y&&(this.getZ()===t.getZ()||A.isNaN(this.getZ())&&A.isNaN(t.getZ()))}},{key:"equals",value:function(t){return t instanceof e&&this.equals2D(t)}},{key:"equalInZ",value:function(t,e){return O.equalsWithTolerance(this.getZ(),t.getZ(),e)}},{key:"setX",value:function(t){this.x=t}},{key:"compareTo",value:function(t){var e=t;return this.xe.x?1:this.ye.y?1:0}},{key:"getX",value:function(){return this.x}},{key:"setZ",value:function(t){this.z=t}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return V.shouldNeverReachHere("this shouldn't happen because this class is Cloneable"),null;throw t}}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+")"}},{key:"distance3D",value:function(t){var e=this.x-t.x,n=this.y-t.y,r=this.getZ()-t.getZ();return Math.sqrt(e*e+n*n+r*r)}},{key:"getY",value:function(){return this.y}},{key:"setY",value:function(t){this.y=t}},{key:"distance",value:function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*t+e.hashCode(this.x))+e.hashCode(this.y)}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}},{key:"interfaces_",get:function(){return[k,b,w]}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.z=null,0===arguments.length)e.constructor_.call(this,0,0);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.x,t.y,t.getZ())}else if(2===arguments.length){var n=arguments[0],r=arguments[1];e.constructor_.call(this,n,r,e.NULL_ORDINATE)}else if(3===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2];this.x=i,this.y=o,this.z=s}}},{key:"hashCode",value:function(t){return B[0]=t,Y[0]^Y[1]}}]),e}(),j=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compare",value:function(t,n){var r=e.compare(t.x,n.x);if(0!==r)return r;var i=e.compare(t.y,n.y);return 0!==i?i:this._dimensionsToTest<=2?0:e.compare(t.getZ(),n.getZ())}},{key:"interfaces_",get:function(){return[D]}}],[{key:"constructor_",value:function(){if(this._dimensionsToTest=2,0===arguments.length)e.constructor_.call(this,2);else if(1===arguments.length){var t=arguments[0];if(2!==t&&3!==t)throw new x("only 2 or 3 dimensions may be specified");this._dimensionsToTest=t}}},{key:"compare",value:function(t,e){return te?1:A.isNaN(t)?A.isNaN(e)?0:-1:A.isNaN(e)?1:0}}]),e}();z.DimensionalComparator=j,z.NULL_ORDINATE=A.NaN,z.X=0,z.Y=1,z.Z=2,z.M=3;var X=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getArea",value:function(){return this.getWidth()*this.getHeight()}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.isNull()?n.isNull():this._maxx===n.getMaxX()&&this._maxy===n.getMaxY()&&this._minx===n.getMinX()&&this._miny===n.getMinY()}},{key:"intersection",value:function(t){if(this.isNull()||t.isNull()||!this.intersects(t))return new e;var n=this._minx>t._minx?this._minx:t._minx,r=this._miny>t._miny?this._miny:t._miny;return new e(n,this._maxx=this._minx&&n.getMaxX()<=this._maxx&&n.getMinY()>=this._miny&&n.getMaxY()<=this._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return!this.isNull()&&r>=this._minx&&r<=this._maxx&&i>=this._miny&&i<=this._maxy}}},{key:"intersects",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return!this.isNull()&&!t.isNull()&&!(t._minx>this._maxx||t._maxxthis._maxy||t._maxythis._maxx||(r.x>i.x?r.x:i.x)this._maxy||(r.y>i.y?r.y:i.y)this._maxx||othis._maxy||sthis._maxx&&(this._maxx=n._maxx),n._minythis._maxy&&(this._maxy=n._maxy))}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.isNull()?(this._minx=r,this._maxx=r,this._miny=i,this._maxy=i):(rthis._maxx&&(this._maxx=r),ithis._maxy&&(this._maxy=i))}}},{key:"minExtent",value:function(){if(this.isNull())return 0;var t=this.getWidth(),e=this.getHeight();return te._minx?1:this._minye._miny?1:this._maxxe._maxx?1:this._maxye._maxy?1:0}},{key:"translate",value:function(t,e){if(this.isNull())return null;this.init(this.getMinX()+t,this.getMaxX()+t,this.getMinY()+e,this.getMaxY()+e)}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"Env["+this._minx+" : "+this._maxx+", "+this._miny+" : "+this._maxy+"]"}},{key:"setToNull",value:function(){this._minx=0,this._maxx=-1,this._miny=0,this._maxy=-1}},{key:"disjoint",value:function(t){return!(!this.isNull()&&!t.isNull())||t._minx>this._maxx||t._maxxthis._maxy||t._maxye?t:e}},{key:"expandBy",value:function(){if(1===arguments.length){var t=arguments[0];this.expandBy(t,t)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];if(this.isNull())return null;this._minx-=e,this._maxx+=e,this._miny-=n,this._maxy+=n,(this._minx>this._maxx||this._miny>this._maxy)&&this.setToNull()}}},{key:"contains",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.covers(t)}if(arguments[0]instanceof z){var n=arguments[0];return this.covers(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return this.covers(r,i)}}},{key:"centre",value:function(){return this.isNull()?null:new z((this.getMinX()+this.getMaxX())/2,(this.getMinY()+this.getMaxY())/2)}},{key:"init",value:function(){if(0===arguments.length)this.setToNull();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this._minx=n._minx,this._maxx=n._maxx,this._miny=n._miny,this._maxy=n._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];ot._maxx&&(e=this._minx-t._maxx);var n=0;return this._maxyt._maxy&&(n=this._miny-t._maxy),0===e?n:0===n?e:Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*(t=37*(t=37*t+z.hashCode(this._minx))+z.hashCode(this._maxx))+z.hashCode(this._miny))+z.hashCode(this._maxy)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,0===arguments.length)this.init();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];this.init(o,s,a,u)}}},{key:"intersects",value:function(){if(3===arguments.length){var t=arguments[0],e=arguments[1],n=arguments[2];return n.x>=(t.xe.x?t.x:e.x)&&n.y>=(t.ye.y?t.y:e.y)}if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=arguments[3],a=Math.min(o.x,s.x),u=Math.max(o.x,s.x),l=Math.min(r.x,i.x),h=Math.max(r.x,i.x);return!(l>u||hu||h=this.size())throw new nt;return this.array[t]}},{key:"push",value:function(t){return this.array.push(t),t}},{key:"pop",value:function(){if(0===this.array.length)throw new et;return this.array.pop()}},{key:"peek",value:function(){if(0===this.array.length)throw new et;return this.array[this.array.length-1]}},{key:"empty",value:function(){return 0===this.array.length}},{key:"isEmpty",value:function(){return this.empty()}},{key:"search",value:function(t){return this.array.indexOf(t)}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}}]),o}(rt);function ot(t,e){return t.interfaces_&&t.interfaces_.indexOf(e)>-1}var st=function(){function e(n){t(this,e),this.str=n}return n(e,[{key:"append",value:function(t){this.str+=t}},{key:"setCharAt",value:function(t,e){this.str=this.str.substr(0,t)+e+this.str.substr(t+1)}},{key:"toString",value:function(){return this.str}}]),e}(),at=function(){function e(n){t(this,e),this.value=n}return n(e,[{key:"intValue",value:function(){return this.value}},{key:"compareTo",value:function(t){return this.valuet?1:0}}],[{key:"compare",value:function(t,e){return te?1:0}},{key:"isNan",value:function(t){return Number.isNaN(t)}},{key:"valueOf",value:function(t){return new e(t)}}]),e}(),ut=function(){function e(){t(this,e)}return n(e,null,[{key:"isWhitespace",value:function(t){return t<=32&&t>=0||127===t}},{key:"toUpperCase",value:function(t){return t.toUpperCase()}}]),e}(),lt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"le",value:function(t){return this._hi9?(c=!0,f="9"):f="0"+h,a.append(f),r=r.subtract(e.valueOf(h)).multiply(e.TEN),c&&r.selfAdd(e.TEN);var g=!0,p=e.magnitude(r._hi);if(p<0&&Math.abs(p)>=u-l&&(g=!1),!g)break}return n[0]=i,a.toString()}},{key:"sqr",value:function(){return this.multiply(this)}},{key:"doubleValue",value:function(){return this._hi+this._lo}},{key:"subtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.add(t.negate())}if("number"==typeof arguments[0]){var n=arguments[0];return this.add(-n)}}},{key:"equals",value:function(){if(1===arguments.length&&arguments[0]instanceof e){var t=arguments[0];return this._hi===t._hi&&this._lo===t._lo}}},{key:"isZero",value:function(){return 0===this._hi&&0===this._lo}},{key:"selfSubtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.isNaN()?this:this.selfAdd(-t._hi,-t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.isNaN()?this:this.selfAdd(-n,0)}}},{key:"getSpecialNumberString",value:function(){return this.isZero()?"0.0":this.isNaN()?"NaN ":null}},{key:"min",value:function(t){return this.le(t)?this:t}},{key:"selfDivide",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfDivide(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfDivide(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null,c=null,f=null;return l=this._hi/r,f=(o=(h=e.SPLIT*l)-(o=h-l))*(a=(f=e.SPLIT*r)-(a=f-r))-(c=l*r)+o*(u=r-a)+(s=l-o)*a+s*u,f=l+(h=(this._hi-c-f+this._lo-l*i)/r),this._hi=f,this._lo=l-f+h,this}}},{key:"dump",value:function(){return"DD<"+this._hi+", "+this._lo+">"}},{key:"divide",value:function(){if(arguments[0]instanceof e){var t=arguments[0],n=null,r=null,i=null,o=null,s=null,a=null,u=null,l=null;return r=(s=this._hi/t._hi)-(n=(a=e.SPLIT*s)-(n=a-s)),l=n*(i=(l=e.SPLIT*t._hi)-(i=l-t._hi))-(u=s*t._hi)+n*(o=t._hi-i)+r*i+r*o,new e(l=s+(a=(this._hi-u-l+this._lo-s*t._lo)/t._hi),s-l+a)}if("number"==typeof arguments[0]){var h=arguments[0];return A.isNaN(h)?e.createNaN():e.copy(this).selfDivide(h,0)}}},{key:"ge",value:function(t){return this._hi>t._hi||this._hi===t._hi&&this._lo>=t._lo}},{key:"pow",value:function(t){if(0===t)return e.valueOf(1);var n=new e(this),r=e.valueOf(1),i=Math.abs(t);if(i>1)for(;i>0;)i%2==1&&r.selfMultiply(n),(i/=2)>0&&(n=n.sqr());else r=n;return t<0?r.reciprocal():r}},{key:"ceil",value:function(){if(this.isNaN())return e.NaN;var t=Math.ceil(this._hi),n=0;return t===this._hi&&(n=Math.ceil(this._lo)),new e(t,n)}},{key:"compareTo",value:function(t){var e=t;return this._hie._hi?1:this._loe._lo?1:0}},{key:"rint",value:function(){return this.isNaN()?this:this.add(.5).floor()}},{key:"setValue",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.init(t),this}if("number"==typeof arguments[0]){var n=arguments[0];return this.init(n),this}}},{key:"max",value:function(t){return this.ge(t)?this:t}},{key:"sqrt",value:function(){if(this.isZero())return e.valueOf(0);if(this.isNegative())return e.NaN;var t=1/Math.sqrt(this._hi),n=this._hi*t,r=e.valueOf(n),i=this.subtract(r.sqr())._hi*(.5*t);return r.add(i)}},{key:"selfAdd",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfAdd(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0],r=null,i=null,o=null,s=null,a=null,u=null;return s=(o=this._hi+n)-(a=o-this._hi),i=(u=(s=n-a+(this._hi-s))+this._lo)+(o-(r=o+u)),this._hi=r+i,this._lo=i+(r-this._hi),this}}else if(2===arguments.length){var l=arguments[0],h=arguments[1],c=null,f=null,g=null,p=null,v=null,d=null,y=null;p=this._hi+l,f=this._lo+h,v=p-(d=p-this._hi),g=f-(y=f-this._lo);var m=(c=p+(d=(v=l-d+(this._hi-v))+f))+(d=(g=h-y+(this._lo-g))+(d+(p-c))),_=d+(c-m);return this._hi=m,this._lo=_,this}}},{key:"selfMultiply",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfMultiply(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfMultiply(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null;o=(l=e.SPLIT*this._hi)-this._hi,h=e.SPLIT*r,o=l-o,s=this._hi-o,a=h-r;var c=(l=this._hi*r)+(h=o*(a=h-a)-l+o*(u=r-a)+s*a+s*u+(this._hi*i+this._lo*r)),f=h+(o=l-c);return this._hi=c,this._lo=f,this}}},{key:"selfSqr",value:function(){return this.selfMultiply(this)}},{key:"floor",value:function(){if(this.isNaN())return e.NaN;var t=Math.floor(this._hi),n=0;return t===this._hi&&(n=Math.floor(this._lo)),new e(t,n)}},{key:"negate",value:function(){return this.isNaN()?this:new e(-this._hi,-this._lo)}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return null;throw t}}},{key:"multiply",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return t.isNaN()?e.createNaN():e.copy(this).selfMultiply(t)}if("number"==typeof arguments[0]){var n=arguments[0];return A.isNaN(n)?e.createNaN():e.copy(this).selfMultiply(n,0)}}},{key:"isNaN",value:function(){return A.isNaN(this._hi)}},{key:"intValue",value:function(){return Math.trunc(this._hi)}},{key:"toString",value:function(){var t=e.magnitude(this._hi);return t>=-3&&t<=20?this.toStandardNotation():this.toSciNotation()}},{key:"toStandardNotation",value:function(){var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!0,n),i=n[0]+1,o=r;if("."===r.charAt(0))o="0"+r;else if(i<0)o="0."+e.stringOfChar("0",-i)+r;else if(-1===r.indexOf(".")){var s=i-r.length;o=r+e.stringOfChar("0",s)+".0"}return this.isNegative()?"-"+o:o}},{key:"reciprocal",value:function(){var t,n,r,i,o=null,s=null,a=null,u=null;t=(r=1/this._hi)-(o=(a=e.SPLIT*r)-(o=a-r)),s=(u=e.SPLIT*this._hi)-this._hi;var l=r+(a=(1-(i=r*this._hi)-(u=o*(s=u-s)-i+o*(n=this._hi-s)+t*s+t*n)-r*this._lo)/this._hi);return new e(l,r-l+a)}},{key:"toSciNotation",value:function(){if(this.isZero())return e.SCI_NOT_ZERO;var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!1,n),i=e.SCI_NOT_EXPONENT_CHAR+n[0];if("0"===r.charAt(0))throw new IllegalStateException("Found leading zero: "+r);var o="";r.length>1&&(o=r.substring(1));var s=r.charAt(0)+"."+o;return this.isNegative()?"-"+s+i:s+i}},{key:"abs",value:function(){return this.isNaN()?e.NaN:this.isNegative()?this.negate():new e(this)}},{key:"isPositive",value:function(){return this._hi>0||0===this._hi&&this._lo>0}},{key:"lt",value:function(t){return this._hit._hi||this._hi===t._hi&&this._lo>t._lo}},{key:"isNegative",value:function(){return this._hi<0||0===this._hi&&this._lo<0}},{key:"trunc",value:function(){return this.isNaN()?e.NaN:this.isPositive()?this.floor():this.ceil()}},{key:"signum",value:function(){return this._hi>0?1:this._hi<0?-1:this._lo>0?1:this._lo<0?-1:0}},{key:"interfaces_",get:function(){return[w,k,b]}}],[{key:"constructor_",value:function(){if(this._hi=0,this._lo=0,0===arguments.length)this.init(0);else if(1===arguments.length){if("number"==typeof arguments[0]){var t=arguments[0];this.init(t)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}else if("string"==typeof arguments[0]){var r=arguments[0];e.constructor_.call(this,e.parse(r))}}else if(2===arguments.length){var i=arguments[0],o=arguments[1];this.init(i,o)}}},{key:"determinant",value:function(){if("number"==typeof arguments[3]&&"number"==typeof arguments[2]&&"number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1],r=arguments[2],i=arguments[3];return e.determinant(e.valueOf(t),e.valueOf(n),e.valueOf(r),e.valueOf(i))}if(arguments[3]instanceof e&&arguments[2]instanceof e&&arguments[0]instanceof e&&arguments[1]instanceof e){var o=arguments[1],s=arguments[2],a=arguments[3];return arguments[0].multiply(a).selfSubtract(o.multiply(s))}}},{key:"sqr",value:function(t){return e.valueOf(t).selfMultiply(t)}},{key:"valueOf",value:function(){if("string"==typeof arguments[0]){var t=arguments[0];return e.parse(t)}if("number"==typeof arguments[0])return new e(arguments[0])}},{key:"sqrt",value:function(t){return e.valueOf(t).sqrt()}},{key:"parse",value:function(t){for(var n=0,r=t.length;ut.isWhitespace(t.charAt(n));)n++;var i=!1;if(n=r);){var c=t.charAt(n);if(n++,ut.isDigit(c)){var f=c-"0";s.selfMultiply(e.TEN),s.selfAdd(f),a++}else{if("."!==c){if("e"===c||"E"===c){var g=t.substring(n);try{l=at.parseInt(g)}catch(e){throw e instanceof NumberFormatException?new NumberFormatException("Invalid exponent "+g+" in string "+t):e}break}throw new NumberFormatException("Unexpected character '"+c+"' at position "+n+" in string "+t)}u=a,h=!0}}var p=s;h||(u=a);var v=a-u-l;if(0===v)p=s;else if(v>0){var d=e.TEN.pow(v);p=s.divide(d)}else if(v<0){var y=e.TEN.pow(-v);p=s.multiply(y)}return i?p.negate():p}},{key:"createNaN",value:function(){return new e(A.NaN,A.NaN)}},{key:"copy",value:function(t){return new e(t)}},{key:"magnitude",value:function(t){var e=Math.abs(t),n=Math.log(e)/Math.log(10),r=Math.trunc(Math.floor(n));return 10*Math.pow(10,r)<=e&&(r+=1),r}},{key:"stringOfChar",value:function(t,e){for(var n=new st,r=0;r0){if(s<=0)return e.signum(a);i=o+s}else{if(!(o<0))return e.signum(a);if(s>=0)return e.signum(a);i=-o-s}var u=e.DP_SAFE_EPSILON*i;return a>=u||-a>=u?e.signum(a):2}},{key:"signum",value:function(t){return t>0?1:t<0?-1:0}}]),e}();ht.DP_SAFE_EPSILON=1e-15;var ct=function(){function e(){t(this,e)}return n(e,[{key:"getM",value:function(t){if(this.hasM()){var e=this.getDimension()-this.getMeasures();return this.getOrdinate(t,e)}return A.NaN}},{key:"setOrdinate",value:function(t,e,n){}},{key:"getZ",value:function(t){return this.hasZ()?this.getOrdinate(t,2):A.NaN}},{key:"size",value:function(){}},{key:"getOrdinate",value:function(t,e){}},{key:"getCoordinate",value:function(){}},{key:"getCoordinateCopy",value:function(t){}},{key:"createCoordinate",value:function(){}},{key:"getDimension",value:function(){}},{key:"hasM",value:function(){return this.getMeasures()>0}},{key:"getX",value:function(t){}},{key:"hasZ",value:function(){return this.getDimension()-this.getMeasures()>2}},{key:"getMeasures",value:function(){return 0}},{key:"expandEnvelope",value:function(t){}},{key:"copy",value:function(){}},{key:"getY",value:function(t){}},{key:"toCoordinateArray",value:function(){}},{key:"interfaces_",get:function(){return[b]}}]),e}();ct.X=0,ct.Y=1,ct.Z=2,ct.M=3;var ft=function(){function e(){t(this,e)}return n(e,null,[{key:"index",value:function(t,e,n){return ht.orientationIndex(t,e,n)}},{key:"isCCW",value:function(){if(arguments[0]instanceof Array){var t=arguments[0],n=t.length-1;if(n<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var r=t[0],i=0,o=1;o<=n;o++){var s=t[o];s.y>r.y&&(r=s,i=o)}var a=i;do{(a-=1)<0&&(a=n)}while(t[a].equals2D(r)&&a!==i);var u=i;do{u=(u+1)%n}while(t[u].equals2D(r)&&u!==i);var l=t[a],h=t[u];if(l.equals2D(r)||h.equals2D(r)||l.equals2D(h))return!1;var c=e.index(l,r,h);return 0===c?l.x>h.x:c>0}if(ot(arguments[0],ct)){var f=arguments[0],g=f.size()-1;if(g<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var p=f.getCoordinate(0),v=0,d=1;d<=g;d++){var y=f.getCoordinate(d);y.y>p.y&&(p=y,v=d)}var m=null,_=v;do{(_-=1)<0&&(_=g),m=f.getCoordinate(_)}while(m.equals2D(p)&&_!==v);var E=null,k=v;do{k=(k+1)%g,E=f.getCoordinate(k)}while(E.equals2D(p)&&k!==v);if(m.equals2D(p)||E.equals2D(p)||m.equals2D(E))return!1;var b=e.index(m,p,E);return 0===b?m.x>E.x:b>0}}}]),e}();ft.CLOCKWISE=-1,ft.RIGHT=ft.CLOCKWISE,ft.COUNTERCLOCKWISE=1,ft.LEFT=ft.COUNTERCLOCKWISE,ft.COLLINEAR=0,ft.STRAIGHT=ft.COLLINEAR;var gt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this._minCoord}},{key:"getRightmostSide",value:function(t,e){var n=this.getRightmostSideOfSegment(t,e);return n<0&&(n=this.getRightmostSideOfSegment(t,e-1)),n<0&&(this._minCoord=null,this.checkForRightmostCoordinate(t)),n}},{key:"findRightmostEdgeAtVertex",value:function(){var t=this._minDe.getEdge().getCoordinates();V.isTrue(this._minIndex>0&&this._minIndexthis._minCoord.y&&n.y>this._minCoord.y&&r===ft.CLOCKWISE)&&(i=!0),i&&(this._minIndex=this._minIndex-1)}},{key:"getRightmostSideOfSegment",value:function(t,e){var n=t.getEdge().getCoordinates();if(e<0||e+1>=n.length)return-1;if(n[e].y===n[e+1].y)return-1;var r=tt.LEFT;return n[e].ythis._minCoord.x)&&(this._minDe=t,this._minIndex=n,this._minCoord=e[n])}},{key:"findRightmostEdgeAtNode",value:function(){var t=this._minDe.getNode().getEdges();this._minDe=t.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)}},{key:"findEdge",value:function(t){for(var e=t.iterator();e.hasNext();){var n=e.next();n.isForward()&&this.checkForRightmostCoordinate(n)}V.isTrue(0!==this._minIndex||this._minCoord.equals(this._minDe.getCoordinate()),"inconsistency in rightmost processing"),0===this._minIndex?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe,this.getRightmostSide(this._minDe,this._minIndex)===tt.LEFT&&(this._orientedDe=this._minDe.getSym())}}],[{key:"constructor_",value:function(){this._minIndex=-1,this._minCoord=null,this._minDe=null,this._orientedDe=null}}]),e}(),pt=function(e){r(o,e);var i=c(o);function o(e,n){var r;return t(this,o),(r=i.call(this,n?e+" [ "+n+" ]":e)).pt=n?new z(n):void 0,r.name=Object.keys({TopologyException:o})[0],r}return n(o,[{key:"getCoordinate",value:function(){return this.pt}}]),o}(F),vt=function(){function e(){t(this,e),this.array=[]}return n(e,[{key:"addLast",value:function(t){this.array.push(t)}},{key:"removeFirst",value:function(){return this.array.shift()}},{key:"isEmpty",value:function(){return 0===this.array.length}}]),e}(),dt=function(e,i){r(s,e);var o=c(s);function s(e){var n;return t(this,s),(n=o.call(this)).array=[],e instanceof H&&n.addAll(e),n}return n(s,[{key:"interfaces_",get:function(){return[rt,H]}},{key:"ensureCapacity",value:function(){}},{key:"add",value:function(t){return 1===arguments.length?this.array.push(t):this.array.splice(arguments[0],0,arguments[1]),!0}},{key:"clear",value:function(){this.array=[]}},{key:"addAll",value:function(t){var e,n=d(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.array.push(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"set",value:function(t,e){var n=this.array[t];return this.array[t]=e,n}},{key:"iterator",value:function(){return new yt(this)}},{key:"get",value:function(t){if(t<0||t>=this.size())throw new nt;return this.array[t]}},{key:"isEmpty",value:function(){return 0===this.array.length}},{key:"sort",value:function(t){t?this.array.sort((function(e,n){return t.compare(e,n)})):this.array.sort()}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}},{key:"remove",value:function(t){for(var e=0,n=this.array.length;e=1&&e.getDepth(tt.LEFT)<=0&&!e.isInteriorAreaEdge()&&e.setInResult(!0)}}},{key:"computeDepths",value:function(t){var e=new Q,n=new vt,r=t.getNode();for(n.addLast(r),e.add(r),t.setVisited(!0);!n.isEmpty();){var i=n.removeFirst();e.add(i),this.computeNodeDepth(i);for(var o=i.getEdges().iterator();o.hasNext();){var s=o.next().getSym();if(!s.isVisited()){var a=s.getNode();e.contains(a)||(n.addLast(a),e.add(a))}}}}},{key:"compareTo",value:function(t){var e=t;return this._rightMostCoord.xe._rightMostCoord.x?1:0}},{key:"getEnvelope",value:function(){if(null===this._env){for(var t=new X,e=this._dirEdgeList.iterator();e.hasNext();)for(var n=e.next().getEdge().getCoordinates(),r=0;re.x?t.x:e.x,a=t.y>e.y?t.y:e.y,u=n.xr.x?n.x:r.x,c=n.y>r.y?n.y:r.y,f=((i>u?i:u)+(sl?o:l)+(an?n:t}if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var r=arguments[0],i=arguments[1],o=arguments[2];return ro?o:r}}},{key:"wrap",value:function(t,e){return t<0?e- -t%e:t%e}},{key:"max",value:function(){if(3===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[0];return t>n&&(n=t),e>n&&(n=e),n}if(4===arguments.length){var r=arguments[1],i=arguments[2],o=arguments[3],s=arguments[0];return r>s&&(s=r),i>s&&(s=i),o>s&&(s=o),s}}},{key:"average",value:function(t,e){return(t+e)/2}}]),e}();Et.LOG_10=Math.log(10);var kt=function(){function e(){t(this,e)}return n(e,null,[{key:"segmentToSegment",value:function(t,n,r,i){if(t.equals(n))return e.pointToSegment(t,r,i);if(r.equals(i))return e.pointToSegment(i,t,n);var o=!1;if(X.intersects(t,n,r,i)){var s=(n.x-t.x)*(i.y-r.y)-(n.y-t.y)*(i.x-r.x);if(0===s)o=!0;else{var a=(t.y-r.y)*(i.x-r.x)-(t.x-r.x)*(i.y-r.y),u=((t.y-r.y)*(n.x-t.x)-(t.x-r.x)*(n.y-t.y))/s,l=a/s;(l<0||l>1||u<0||u>1)&&(o=!0)}}else o=!0;return o?Et.min(e.pointToSegment(t,r,i),e.pointToSegment(n,r,i),e.pointToSegment(r,t,n),e.pointToSegment(i,t,n)):0}},{key:"pointToSegment",value:function(t,e,n){if(e.x===n.x&&e.y===n.y)return t.distance(e);var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/r;if(i<=0)return t.distance(e);if(i>=1)return t.distance(n);var o=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(o)*Math.sqrt(r)}},{key:"pointToLinePerpendicular",value:function(t,e,n){var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(i)*Math.sqrt(r)}},{key:"pointToSegmentString",value:function(t,n){if(0===n.length)throw new x("Line array must contain at least one vertex");for(var r=t.distance(n[0]),i=0;i0)&&(o=a,i=s)}return i}}},{key:"extend",value:function(t,n,r){var i=t.create(r,n.getDimension()),o=n.size();if(e.copy(n,0,i,0,o),o>0)for(var s=o;s0)&&(e=r)}return e}}]),e}(),Mt=function(){function e(){t(this,e)}return n(e,null,[{key:"toDimensionSymbol",value:function(t){switch(t){case e.FALSE:return e.SYM_FALSE;case e.TRUE:return e.SYM_TRUE;case e.DONTCARE:return e.SYM_DONTCARE;case e.P:return e.SYM_P;case e.L:return e.SYM_L;case e.A:return e.SYM_A}throw new x("Unknown dimension value: "+t)}},{key:"toDimensionValue",value:function(t){switch(ut.toUpperCase(t)){case e.SYM_FALSE:return e.FALSE;case e.SYM_TRUE:return e.TRUE;case e.SYM_DONTCARE:return e.DONTCARE;case e.SYM_P:return e.P;case e.SYM_L:return e.L;case e.SYM_A:return e.A}throw new x("Unknown dimension symbol: "+t)}}]),e}();Mt.P=0,Mt.L=1,Mt.A=2,Mt.FALSE=-1,Mt.TRUE=-2,Mt.DONTCARE=-3,Mt.SYM_FALSE="F",Mt.SYM_TRUE="T",Mt.SYM_DONTCARE="*",Mt.SYM_P="0",Mt.SYM_L="1",Mt.SYM_A="2";var Lt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}(),Pt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t,e){}},{key:"isDone",value:function(){}},{key:"isGeometryChanged",value:function(){}}]),e}(),Ct=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"computeEnvelopeInternal",value:function(){return this.isEmpty()?new X:this._points.expandEnvelope(new X)}},{key:"isRing",value:function(){return this.isClosed()&&this.isSimple()}},{key:"getCoordinates",value:function(){return this._points.toCoordinateArray()}},{key:"copyInternal",value:function(){return new s(this._points.copy(),this._factory)}},{key:"equalsExact",value:function(){if(2===arguments.length&&"number"==typeof arguments[1]&&arguments[0]instanceof U){var t=arguments[0],e=arguments[1];if(!this.isEquivalentClass(t))return!1;var n=t;if(this._points.size()!==n._points.size())return!1;for(var r=0;r0){var n=this._points.copy();St.reverse(n),this._points=n}return null}}}},{key:"getCoordinate",value:function(){return this.isEmpty()?null:this._points.getCoordinate(0)}},{key:"getBoundaryDimension",value:function(){return this.isClosed()?Mt.FALSE:0}},{key:"isClosed",value:function(){return!this.isEmpty()&&this.getCoordinateN(0).equals2D(this.getCoordinateN(this.getNumPoints()-1))}},{key:"reverseInternal",value:function(){var t=this._points.copy();return St.reverse(t),this.getFactory().createLineString(t)}},{key:"getEndPoint",value:function(){return this.isEmpty()?null:this.getPointN(this.getNumPoints()-1)}},{key:"getTypeCode",value:function(){return U.TYPECODE_LINESTRING}},{key:"getDimension",value:function(){return 1}},{key:"getLength",value:function(){return It.ofLine(this._points)}},{key:"getNumPoints",value:function(){return this._points.size()}},{key:"compareToSameClass",value:function(){if(1===arguments.length){for(var t=arguments[0],e=0,n=0;e= 2)");this._points=t}},{key:"isCoordinate",value:function(t){for(var e=0;e=1&&this.getCoordinateSequence().size()= 4)")}},{key:"getGeometryType",value:function(){return U.TYPENAME_LINEARRING}}],[{key:"constructor_",value:function(){var t=arguments[0],e=arguments[1];Ct.constructor_.call(this,t,e),this.validateConstruction()}}]),s}(Ct);zt.MINIMUM_VALID_SIZE=4;var jt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}}],[{key:"constructor_",value:function(){if(0===arguments.length)z.constructor_.call(this);else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y)}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y)}}else if(2===arguments.length){var n=arguments[0],r=arguments[1];z.constructor_.call(this,n,r,z.NULL_ORDINATE)}}}]),o}(z);jt.X=0,jt.Y=1,jt.Z=-1,jt.M=-1;var Xt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;case o.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y;case o.M:return this._m}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y),this._m=this.getM()}}else if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2];z.constructor_.call(this,n,r,z.NULL_ORDINATE),this._m=i}}}]),o}(z);Xt.X=0,Xt.Y=1,Xt.Z=-1,Xt.M=2;var Ut=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case z.X:this.x=e;break;case z.Y:this.y=e;break;case z.Z:this.z=e;break;case z.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getOrdinate",value:function(t){switch(t){case z.X:return this.x;case z.Y:return this.y;case z.Z:return this.getZ();case z.M:return this.getM()}throw new x("Invalid ordinate index: "+t)}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e),this._m=this.getM()}}else if(4===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],s=arguments[3];z.constructor_.call(this,n,r,i),this._m=s}}}]),o}(z),Zt=function(){function e(){t(this,e)}return n(e,null,[{key:"measures",value:function(t){return t instanceof jt?0:t instanceof Xt||t instanceof Ut?1:0}},{key:"dimension",value:function(t){return t instanceof jt?2:t instanceof Xt?3:t instanceof Ut?4:3}},{key:"create",value:function(){if(1===arguments.length){var t=arguments[0];return e.create(t,0)}if(2===arguments.length){var n=arguments[0],r=arguments[1];return 2===n?new jt:3===n&&0===r?new z:3===n&&1===r?new Xt:4===n&&1===r?new Ut:new z}}}]),e}(),Ht=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getCoordinate",value:function(t){return this.get(t)}},{key:"addAll",value:function(){if(2===arguments.length&&"boolean"==typeof arguments[1]&&ot(arguments[0],H)){for(var t=arguments[1],e=!1,n=arguments[0].iterator();n.hasNext();)this.add(n.next(),t),e=!0;return e}return f(i(s.prototype),"addAll",this).apply(this,arguments)}},{key:"clone",value:function(){for(var t=f(i(s.prototype),"clone",this).call(this),e=0;e=1&&this.get(this.size()-1).equals2D(r))return null;f(i(s.prototype),"add",this).call(this,r)}else if(arguments[0]instanceof Object&&"boolean"==typeof arguments[1]){var o=arguments[0],a=arguments[1];return this.add(o,a),!0}}else if(3===arguments.length){if("boolean"==typeof arguments[2]&&arguments[0]instanceof Array&&"boolean"==typeof arguments[1]){var u=arguments[0],l=arguments[1];if(arguments[2])for(var h=0;h=0;c--)this.add(u[c],l);return!0}if("boolean"==typeof arguments[2]&&Number.isInteger(arguments[0])&&arguments[1]instanceof z){var g=arguments[0],p=arguments[1];if(!arguments[2]){var v=this.size();if(v>0){if(g>0&&this.get(g-1).equals2D(p))return null;if(g_&&(x=-1);for(var E=m;E!==_;E+=x)this.add(d[E],y);return!0}}},{key:"closeRing",value:function(){if(this.size()>0){var t=this.get(0).copy();this.add(t,!1)}}}],[{key:"constructor_",value:function(){if(0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.ensureCapacity(t.length),this.add(t,!0)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this.ensureCapacity(e.length),this.add(e,n)}}}]),s}(dt);Ht.coordArrayType=new Array(0).fill(null);var Wt=function(){function e(){t(this,e)}return n(e,null,[{key:"isRing",value:function(t){return!(t.length<4||!t[0].equals2D(t[t.length-1]))}},{key:"ptNotInList",value:function(t,n){for(var r=0;r=t?e:[]}},{key:"indexOf",value:function(t,e){for(var n=0;n0)&&(e=t[n]);return e}},{key:"extract",value:function(t,e,n){e=Et.clamp(e,0,t.length);var r=(n=Et.clamp(n,-1,t.length))-e+1;n<0&&(r=0),e>=t.length&&(r=0),nr.length)return 1;if(0===n.length)return 0;var i=Wt.compare(n,r);return Wt.isEqualReversed(n,r)?0:i}},{key:"OLDcompare",value:function(t,e){var n=t,r=e;if(n.lengthr.length)return 1;if(0===n.length)return 0;for(var i=Wt.increasingDirection(n),o=Wt.increasingDirection(r),s=i>0?0:n.length-1,a=o>0?0:n.length-1,u=0;u0){var t=new Qt(17*this._coordinates.length);t.append("("),t.append(this._coordinates[0]);for(var e=1;e3&&(t=3),t<2&&(t=2),new $t(arguments[0],t)}if(3===arguments.length){var e=arguments[2],n=arguments[1]-e;return e>1&&(e=1),n>3&&(n=3),n<2&&(n=2),new $t(arguments[0],n+e,e)}}}},{key:"interfaces_",get:function(){return[bt,w]}}],[{key:"instance",value:function(){return e.instanceObject}}]),e}();te.instanceObject=new te;var ee=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e=0?t:e}}]),e}(),oe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"readResolve",value:function(){return e.nameToTypeMap.get(this._name)}},{key:"toString",value:function(){return this._name}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){this._name=null;var t=arguments[0];this._name=t,e.nameToTypeMap.put(t,this)}}]),e}();oe.nameToTypeMap=new re,ie.Type=oe,ie.FIXED=new oe("FIXED"),ie.FLOATING=new oe("FLOATING"),ie.FLOATING_SINGLE=new oe("FLOATING SINGLE"),ie.maximumPreciseValue=9007199254740992;var se=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e1){if(u instanceof Ft)return this.createMultiPolygon(e.toPolygonArray(t));if(u instanceof Ct)return this.createMultiLineString(e.toLineStringArray(t));if(u instanceof Ot)return this.createMultiPoint(e.toPointArray(t));V.shouldNeverReachHere("Unhandled geometry type: "+u.getGeometryType())}return u}},{key:"createMultiPointFromCoords",value:function(t){return this.createMultiPoint(null!==t?this.getCoordinateSequenceFactory().create(t):null)}},{key:"createPoint",value:function(){if(0===arguments.length)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];return this.createPoint(null!==t?this.getCoordinateSequenceFactory().create([t]):null)}if(ot(arguments[0],ct))return new Ot(arguments[0],this)}}},{key:"getCoordinateSequenceFactory",value:function(){return this._coordinateSequenceFactory}},{key:"createPolygon",value:function(){if(0===arguments.length)return this.createPolygon(null,null);if(1===arguments.length){if(ot(arguments[0],ct)){var t=arguments[0];return this.createPolygon(this.createLinearRing(t))}if(arguments[0]instanceof Array){var e=arguments[0];return this.createPolygon(this.createLinearRing(e))}if(arguments[0]instanceof zt){var n=arguments[0];return this.createPolygon(n,null)}}else if(2===arguments.length)return new Ft(arguments[0],arguments[1],this)}},{key:"getSRID",value:function(){return this._SRID}},{key:"createGeometryCollection",value:function(){return 0===arguments.length?new Bt(null,this):1===arguments.length?new Bt(arguments[0],this):void 0}},{key:"getPrecisionModel",value:function(){return this._precisionModel}},{key:"createLinearRing",value:function(){if(0===arguments.length)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof Array){var t=arguments[0];return this.createLinearRing(null!==t?this.getCoordinateSequenceFactory().create(t):null)}if(ot(arguments[0],ct))return new zt(arguments[0],this)}}},{key:"createMultiPolygon",value:function(){return 0===arguments.length?new ee(null,this):1===arguments.length?new ee(arguments[0],this):void 0}},{key:"createMultiPoint",value:function(){if(0===arguments.length)return new Yt(null,this);if(1===arguments.length){if(arguments[0]instanceof Array)return new Yt(arguments[0],this);if(ot(arguments[0],ct)){var t=arguments[0];if(null===t)return this.createMultiPoint(new Array(0).fill(null));for(var e=new Array(t.size()).fill(null),n=0;n="a"&&t<="z"||t>="A"&&t<="Z"}},{key:"isNumeric_",value:function(t,e){return t>="0"&&t<="9"||"."==t&&!(void 0!==e&&e)}},{key:"isWhiteSpace_",value:function(t){return" "==t||"\t"==t||"\r"==t||"\n"==t}},{key:"nextChar_",value:function(){return this.wkt.charAt(++this.index_)}},{key:"nextToken",value:function(){var t,e=this.nextChar_(),n=this.index_,r=e;if("("==e)t=ve;else if(","==e)t=me;else if(")"==e)t=de;else if(this.isNumeric_(e)||"-"==e)t=ye,r=this.readNumber_();else if(this.isAlpha_(e))t=pe,r=this.readText_();else{if(this.isWhiteSpace_(e))return this.nextToken();if(""!==e)throw new Error("Unexpected character: "+e);t=_e}return{position:n,value:r,type:t}}},{key:"readNumber_",value:function(){var t,e=this.index_,n=!1,r=!1;do{"."==t?n=!0:"e"!=t&&"E"!=t||(r=!0),t=this.nextChar_()}while(this.isNumeric_(t,n)||!r&&("e"==t||"E"==t)||r&&("-"==t||"+"==t));return parseFloat(this.wkt.substring(e,this.index_--))}},{key:"readText_",value:function(){var t,e=this.index_;do{t=this.nextChar_()}while(this.isAlpha_(t));return this.wkt.substring(e,this.index_--).toUpperCase()}}]),e}(),ke=function(){function e(n,r){t(this,e),this.lexer_=n,this.token_,this.layout_=ue,this.factory=r}return n(e,[{key:"consume_",value:function(){this.token_=this.lexer_.nextToken()}},{key:"isTokenType",value:function(t){return this.token_.type==t}},{key:"match",value:function(t){var e=this.isTokenType(t);return e&&this.consume_(),e}},{key:"parse",value:function(){return this.consume_(),this.parseGeometry_()}},{key:"parseGeometryLayout_",value:function(){var t=ue,e=this.token_;if(this.isTokenType(pe)){var n=e.value;"Z"===n?t=le:"M"===n?t=he:"ZM"===n&&(t=ce),t!==ue&&this.consume_()}return t}},{key:"parseGeometryCollectionText_",value:function(){if(this.match(ve)){var t=[];do{t.push(this.parseGeometry_())}while(this.match(me));if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePointText_",value:function(){if(this.match(ve)){var t=this.parsePoint_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return null;throw new Error(this.formatErrorMessage_())}},{key:"parseLineStringText_",value:function(){if(this.match(ve)){var t=this.parsePointList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePolygonText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPointText_",value:function(){var t;if(this.match(ve)){if(t=this.token_.type==ve?this.parsePointTextList_():this.parsePointList_(),this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiLineStringText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPolygonText_",value:function(){if(this.match(ve)){var t=this.parsePolygonTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePoint_",value:function(){for(var t=[],e=this.layout_.length,n=0;n1?t.createPolygon(r[0],r.slice(1)):t.createPolygon(r[0])},r=this.token_;if(this.match(pe)){var i=r.value;if(this.layout_=this.parseGeometryLayout_(),"GEOMETRYCOLLECTION"==i){var o=this.parseGeometryCollectionText_();return t.createGeometryCollection(o)}switch(i){case"POINT":var s=this.parsePointText_();return s?t.createPoint(a(z,g(s))):t.createPoint();case"LINESTRING":var u=this.parseLineStringText_().map(e);return t.createLineString(u);case"LINEARRING":var l=this.parseLineStringText_().map(e);return t.createLinearRing(l);case"POLYGON":var h=this.parsePolygonText_();return h&&0!==h.length?n(h):t.createPolygon();case"MULTIPOINT":var c=this.parseMultiPointText_();if(!c||0===c.length)return t.createMultiPoint();var f=c.map(e).map((function(e){return t.createPoint(e)}));return t.createMultiPoint(f);case"MULTILINESTRING":var p=this.parseMultiLineStringText_().map((function(n){return t.createLineString(n.map(e))}));return t.createMultiLineString(p);case"MULTIPOLYGON":var v=this.parseMultiPolygonText_();if(!v||0===v.length)return t.createMultiPolygon();var d=v.map(n);return t.createMultiPolygon(d);default:throw new Error("Invalid geometry type: "+i)}}throw new Error(this.formatErrorMessage_())}}]),e}();function be(t){if(t.isEmpty())return"";var e=t.getCoordinate(),n=[e.x,e.y];return void 0===e.z||Number.isNaN(e.z)||n.push(e.z),void 0===e.m||Number.isNaN(e.m)||n.push(e.m),n.join(" ")}function we(t){for(var e=t.getCoordinates().map((function(t){var e=[t.x,t.y];return void 0===t.z||Number.isNaN(t.z)||e.push(t.z),void 0===t.m||Number.isNaN(t.m)||e.push(t.m),e})),n=[],r=0,i=e.length;r0&&(e+=" "+r),t.isEmpty()?e+" "+ge:e+" ("+n(t)+")"}var Me=function(){function e(n){t(this,e),this.geometryFactory=n||new ae,this.precisionModel=this.geometryFactory.getPrecisionModel()}return n(e,[{key:"read",value:function(t){var e=new Ee(t);return new ke(e,this.geometryFactory).parse()}},{key:"write",value:function(t){return Se(t)}}]),e}(),Le=function(){function e(n){t(this,e),this.parser=new Me(n)}return n(e,[{key:"write",value:function(t){return this.parser.write(t)}}],[{key:"toLineString",value:function(t,e){if(2!==arguments.length)throw new Error("Not implemented");return"LINESTRING ( "+t.x+" "+t.y+", "+e.x+" "+e.y+" )"}}]),e}(),Pe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getIndexAlongSegment",value:function(t,e){return this.computeIntLineIndex(),this._intLineIndex[t][e]}},{key:"getTopologySummary",value:function(){var t=new Qt;return this.isEndPoint()&&t.append(" endpoint"),this._isProper&&t.append(" proper"),this.isCollinear()&&t.append(" collinear"),t.toString()}},{key:"computeIntersection",value:function(t,e,n,r){this._inputLines[0][0]=t,this._inputLines[0][1]=e,this._inputLines[1][0]=n,this._inputLines[1][1]=r,this._result=this.computeIntersect(t,e,n,r)}},{key:"getIntersectionNum",value:function(){return this._result}},{key:"computeIntLineIndex",value:function(){if(0===arguments.length)null===this._intLineIndex&&(this._intLineIndex=Array(2).fill().map((function(){return Array(2)})),this.computeIntLineIndex(0),this.computeIntLineIndex(1));else if(1===arguments.length){var t=arguments[0];this.getEdgeDistance(t,0)>this.getEdgeDistance(t,1)?(this._intLineIndex[t][0]=0,this._intLineIndex[t][1]=1):(this._intLineIndex[t][0]=1,this._intLineIndex[t][1]=0)}}},{key:"isProper",value:function(){return this.hasIntersection()&&this._isProper}},{key:"setPrecisionModel",value:function(t){this._precisionModel=t}},{key:"isInteriorIntersection",value:function(){if(0===arguments.length)return!!this.isInteriorIntersection(0)||!!this.isInteriorIntersection(1);if(1===arguments.length){for(var t=arguments[0],e=0;ei?r:i;else{var s=Math.abs(t.x-e.x),a=Math.abs(t.y-e.y);0!==(o=r>i?s:a)||t.equals(e)||(o=Math.max(s,a))}return V.isTrue(!(0===o&&!t.equals(e)),"Bad distance calculation"),o}},{key:"nonRobustComputeEdgeDistance",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y,o=Math.sqrt(r*r+i*i);return V.isTrue(!(0===o&&!t.equals(e)),"Invalid distance calculation"),o}}]),e}();Pe.DONT_INTERSECT=0,Pe.DO_INTERSECT=1,Pe.COLLINEAR=2,Pe.NO_INTERSECTION=0,Pe.POINT_INTERSECTION=1,Pe.COLLINEAR_INTERSECTION=2;var Ce=function(e){r(s,e);var o=c(s);function s(){return t(this,s),o.call(this)}return n(s,[{key:"isInSegmentEnvelopes",value:function(t){var e=new X(this._inputLines[0][0],this._inputLines[0][1]),n=new X(this._inputLines[1][0],this._inputLines[1][1]);return e.contains(t)&&n.contains(t)}},{key:"computeIntersection",value:function(){if(3!==arguments.length)return f(i(s.prototype),"computeIntersection",this).apply(this,arguments);var t=arguments[0],e=arguments[1],n=arguments[2];if(this._isProper=!1,X.intersects(e,n,t)&&0===ft.index(e,n,t)&&0===ft.index(n,e,t))return this._isProper=!0,(t.equals(e)||t.equals(n))&&(this._isProper=!1),this._result=Pe.POINT_INTERSECTION,null;this._result=Pe.NO_INTERSECTION}},{key:"intersection",value:function(t,e,n,r){var i=this.intersectionSafe(t,e,n,r);return this.isInSegmentEnvelopes(i)||(i=new z(s.nearestEndpoint(t,e,n,r))),null!==this._precisionModel&&this._precisionModel.makePrecise(i),i}},{key:"checkDD",value:function(t,e,n,r,i){var o=ht.intersection(t,e,n,r),s=this.isInSegmentEnvelopes(o);xt.out.println("DD in env = "+s+" --------------------- "+o),i.distance(o)>1e-4&&xt.out.println("Distance = "+i.distance(o))}},{key:"intersectionSafe",value:function(t,e,n,r){var i=_t.intersection(t,e,n,r);return null===i&&(i=s.nearestEndpoint(t,e,n,r)),i}},{key:"computeCollinearIntersection",value:function(t,e,n,r){var i=X.intersects(t,e,n),o=X.intersects(t,e,r),s=X.intersects(n,r,t),a=X.intersects(n,r,e);return i&&o?(this._intPt[0]=n,this._intPt[1]=r,Pe.COLLINEAR_INTERSECTION):s&&a?(this._intPt[0]=t,this._intPt[1]=e,Pe.COLLINEAR_INTERSECTION):i&&s?(this._intPt[0]=n,this._intPt[1]=t,!n.equals(t)||o||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):i&&a?(this._intPt[0]=n,this._intPt[1]=e,!n.equals(e)||o||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&s?(this._intPt[0]=r,this._intPt[1]=t,!r.equals(t)||i||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&a?(this._intPt[0]=r,this._intPt[1]=e,!r.equals(e)||i||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):Pe.NO_INTERSECTION}},{key:"computeIntersect",value:function(t,e,n,r){if(this._isProper=!1,!X.intersects(t,e,n,r))return Pe.NO_INTERSECTION;var i=ft.index(t,e,n),o=ft.index(t,e,r);if(i>0&&o>0||i<0&&o<0)return Pe.NO_INTERSECTION;var s=ft.index(n,r,t),a=ft.index(n,r,e);return s>0&&a>0||s<0&&a<0?Pe.NO_INTERSECTION:0===i&&0===o&&0===s&&0===a?this.computeCollinearIntersection(t,e,n,r):(0===i||0===o||0===s||0===a?(this._isProper=!1,t.equals2D(n)||t.equals2D(r)?this._intPt[0]=t:e.equals2D(n)||e.equals2D(r)?this._intPt[0]=e:0===i?this._intPt[0]=new z(n):0===o?this._intPt[0]=new z(r):0===s?this._intPt[0]=new z(t):0===a&&(this._intPt[0]=new z(e))):(this._isProper=!0,this._intPt[0]=this.intersection(t,e,n,r)),Pe.POINT_INTERSECTION)}}],[{key:"nearestEndpoint",value:function(t,e,n,r){var i=t,o=kt.pointToSegment(t,n,r),s=kt.pointToSegment(e,n,r);return sr&&(n=e.x,r=t.x),this._p.x>=n&&this._p.x<=r&&(this._isPointOnSegment=!0),null}if(t.y>this._p.y&&e.y<=this._p.y||e.y>this._p.y&&t.y<=this._p.y){var i=ft.index(t,e,this._p);if(i===ft.COLLINEAR)return this._isPointOnSegment=!0,null;e.ythis.location.length){var e=new Array(3).fill(null);e[tt.ON]=this.location[tt.ON],e[tt.LEFT]=Z.NONE,e[tt.RIGHT]=Z.NONE,this.location=e}for(var n=0;n1&&t.append(Z.toLocationSymbol(this.location[tt.LEFT])),t.append(Z.toLocationSymbol(this.location[tt.ON])),this.location.length>1&&t.append(Z.toLocationSymbol(this.location[tt.RIGHT])),t.toString()}},{key:"setLocations",value:function(t,e,n){this.location[tt.ON]=t,this.location[tt.LEFT]=e,this.location[tt.RIGHT]=n}},{key:"get",value:function(t){return t1}},{key:"isAnyNull",value:function(){for(var t=0;tthis._maxNodeDegree&&(this._maxNodeDegree=e),t=this.getNext(t)}while(t!==this._startDe);this._maxNodeDegree*=2}},{key:"addPoints",value:function(t,e,n){var r=t.getCoordinates();if(e){var i=1;n&&(i=0);for(var o=i;o=0;a--)this._pts.add(r[a])}}},{key:"isHole",value:function(){return this._isHole}},{key:"setInResult",value:function(){var t=this._startDe;do{t.getEdge().setInResult(!0),t=t.getNext()}while(t!==this._startDe)}},{key:"containsPoint",value:function(t){var e=this.getLinearRing();if(!e.getEnvelopeInternal().contains(t))return!1;if(!Oe.isInRing(t,e.getCoordinates()))return!1;for(var n=this._holes.iterator();n.hasNext();)if(n.next().containsPoint(t))return!1;return!0}},{key:"addHole",value:function(t){this._holes.add(t)}},{key:"isShell",value:function(){return null===this._shell}},{key:"getLabel",value:function(){return this._label}},{key:"getEdges",value:function(){return this._edges}},{key:"getMaxNodeDegree",value:function(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree}},{key:"getShell",value:function(){return this._shell}},{key:"mergeLabel",value:function(){if(1===arguments.length){var t=arguments[0];this.mergeLabel(t,0),this.mergeLabel(t,1)}else if(2===arguments.length){var e=arguments[1],n=arguments[0].getLocation(e,tt.RIGHT);if(n===Z.NONE)return null;if(this._label.getLocation(e)===Z.NONE)return this._label.setLocation(e,n),null}}},{key:"setShell",value:function(t){this._shell=t,null!==t&&t.addHole(this)}},{key:"toPolygon",value:function(t){for(var e=new Array(this._holes.size()).fill(null),n=0;n=2,"found partial label"),this.computeIM(t)}},{key:"isInResult",value:function(){return this._isInResult}},{key:"isVisited",value:function(){return this._isVisited}}],[{key:"constructor_",value:function(){if(this._label=null,this._isInResult=!1,this._isCovered=!1,this._isCoveredSet=!1,this._isVisited=!1,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._label=t}}}]),e}(),Ge=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isIncidentEdgeInResult",value:function(){for(var t=this.getEdges().getEdges().iterator();t.hasNext();)if(t.next().getEdge().isInResult())return!0;return!1}},{key:"isIsolated",value:function(){return 1===this._label.getGeometryCount()}},{key:"getCoordinate",value:function(){return this._coord}},{key:"print",value:function(t){t.println("node "+this._coord+" lbl: "+this._label)}},{key:"computeIM",value:function(t){}},{key:"computeMergedLocation",value:function(t,e){var n=Z.NONE;if(n=this._label.getLocation(e),!t.isNull(e)){var r=t.getLocation(e);n!==Z.BOUNDARY&&(n=r)}return n}},{key:"setLabel",value:function(){if(2!==arguments.length||!Number.isInteger(arguments[1])||!Number.isInteger(arguments[0]))return f(i(s.prototype),"setLabel",this).apply(this,arguments);var t=arguments[0],e=arguments[1];null===this._label?this._label=new Ae(t,e):this._label.setLocation(t,e)}},{key:"getEdges",value:function(){return this._edges}},{key:"mergeLabel",value:function(){if(arguments[0]instanceof s){var t=arguments[0];this.mergeLabel(t._label)}else if(arguments[0]instanceof Ae)for(var e=arguments[0],n=0;n<2;n++){var r=this.computeMergedLocation(e,n);this._label.getLocation(n)===Z.NONE&&this._label.setLocation(n,r)}}},{key:"add",value:function(t){this._edges.insert(t),t.setNode(this)}},{key:"setLabelBoundary",value:function(t){if(null===this._label)return null;var e=Z.NONE;null!==this._label&&(e=this._label.getLocation(t));var n=null;switch(e){case Z.BOUNDARY:n=Z.INTERIOR;break;case Z.INTERIOR:default:n=Z.BOUNDARY}this._label.setLocation(t,n)}}],[{key:"constructor_",value:function(){this._coord=null,this._edges=null;var t=arguments[0],e=arguments[1];this._coord=t,this._edges=e,this._label=new Ae(0,Z.NONE)}}]),s}(Ve),Be=function(e){r(i,e);var n=c(i);function i(){return t(this,i),n.apply(this,arguments)}return i}(ne);function Ye(t){return null==t?0:t.color}function ze(t){return null==t?null:t.parent}function je(t,e){null!==t&&(t.color=e)}function Xe(t){return null==t?null:t.left}function Ue(t){return null==t?null:t.right}var Ze=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),(e=i.call(this)).root_=null,e.size_=0,e}return n(o,[{key:"get",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return e.value;e=e.right}}return null}},{key:"put",value:function(t,e){if(null===this.root_)return this.root_={key:t,value:e,left:null,right:null,parent:null,color:0,getValue:function(){return this.value},getKey:function(){return this.key}},this.size_=1,null;var n,r,i=this.root_;do{if(n=i,(r=t.compareTo(i.key))<0)i=i.left;else{if(!(r>0)){var o=i.value;return i.value=e,o}i=i.right}}while(null!==i);var s={key:t,left:null,right:null,value:e,parent:n,color:0,getValue:function(){return this.value},getKey:function(){return this.key}};return r<0?n.left=s:n.right=s,this.fixAfterInsertion(s),this.size_++,null}},{key:"fixAfterInsertion",value:function(t){var e;for(t.color=1;null!=t&&t!==this.root_&&1===t.parent.color;)ze(t)===Xe(ze(ze(t)))?1===Ye(e=Ue(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Ue(ze(t))&&(t=ze(t),this.rotateLeft(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateRight(ze(ze(t)))):1===Ye(e=Xe(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Xe(ze(t))&&(t=ze(t),this.rotateRight(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateLeft(ze(ze(t))));this.root_.color=0}},{key:"values",value:function(){var t=new dt,e=this.getFirstEntry();if(null!==e)for(t.add(e.value);null!==(e=o.successor(e));)t.add(e.value);return t}},{key:"entrySet",value:function(){var t=new Q,e=this.getFirstEntry();if(null!==e)for(t.add(e);null!==(e=o.successor(e));)t.add(e);return t}},{key:"rotateLeft",value:function(t){if(null!=t){var e=t.right;t.right=e.left,null!=e.left&&(e.left.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.left===t?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}}},{key:"rotateRight",value:function(t){if(null!=t){var e=t.left;t.left=e.right,null!=e.right&&(e.right.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.right===t?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}}},{key:"getFirstEntry",value:function(){var t=this.root_;if(null!=t)for(;null!=t.left;)t=t.left;return t}},{key:"size",value:function(){return this.size_}},{key:"containsKey",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return!0;e=e.right}}return!1}}],[{key:"successor",value:function(t){var e;if(null===t)return null;if(null!==t.right){for(e=t.right;null!==e.left;)e=e.left;return e}e=t.parent;for(var n=t;null!==e&&n===e.right;)n=e,e=e.parent;return e}}]),o}(Be),He=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"find",value:function(t){return this.nodeMap.get(t)}},{key:"addNode",value:function(){if(arguments[0]instanceof z){var t=arguments[0],e=this.nodeMap.get(t);return null===e&&(e=this.nodeFact.createNode(t),this.nodeMap.put(t,e)),e}if(arguments[0]instanceof Ge){var n=arguments[0],r=this.nodeMap.get(n.getCoordinate());return null===r?(this.nodeMap.put(n.getCoordinate(),n),n):(r.mergeLabel(n),r)}}},{key:"print",value:function(t){for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this.nodeMap.values().iterator()}},{key:"values",value:function(){return this.nodeMap.values()}},{key:"getBoundaryNodes",value:function(t){for(var e=new dt,n=this.iterator();n.hasNext();){var r=n.next();r.getLabel().getLocation(t)===Z.BOUNDARY&&e.add(r)}return e}},{key:"add",value:function(t){var e=t.getCoordinate();this.addNode(e).add(t)}}],[{key:"constructor_",value:function(){this.nodeMap=new Ze,this.nodeFact=null;var t=arguments[0];this.nodeFact=t}}]),e}(),We=function(){function e(){t(this,e)}return n(e,null,[{key:"isNorthern",value:function(t){return t===e.NE||t===e.NW}},{key:"isOpposite",value:function(t,e){return t!==e&&2==(t-e+4)%4}},{key:"commonHalfPlane",value:function(t,e){if(t===e)return t;if(2==(t-e+4)%4)return-1;var n=te?t:e)?3:n}},{key:"isInHalfPlane",value:function(t,n){return n===e.SE?t===e.SE||t===e.SW:t===n||t===n+1}},{key:"quadrant",value:function(){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1];if(0===t&&0===n)throw new x("Cannot compute the quadrant for point ( "+t+", "+n+" )");return t>=0?n>=0?e.NE:e.SE:n>=0?e.NW:e.SW}if(arguments[0]instanceof z&&arguments[1]instanceof z){var r=arguments[0],i=arguments[1];if(i.x===r.x&&i.y===r.y)throw new x("Cannot compute the quadrant for two identical points "+r);return i.x>=r.x?i.y>=r.y?e.NE:e.SE:i.y>=r.y?e.NW:e.SW}}}]),e}();We.NE=0,We.NW=1,We.SW=2,We.SE=3;var Je=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareDirection",value:function(t){return this._dx===t._dx&&this._dy===t._dy?0:this._quadrant>t._quadrant?1:this._quadrant2){o.linkDirectedEdgesForMinimalEdgeRings();var s=o.buildMinimalRings(),a=this.findShell(s);null!==a?(this.placePolygonHoles(a,s),e.add(a)):n.addAll(s)}else r.add(o)}return r}},{key:"buildMaximalEdgeRings",value:function(t){for(var e=new dt,n=t.iterator();n.hasNext();){var r=n.next();if(r.isInResult()&&r.getLabel().isArea()&&null===r.getEdgeRing()){var i=new qe(r,this._geometryFactory);e.add(i),i.setInResult()}}return e}},{key:"placePolygonHoles",value:function(t,e){for(var n=e.iterator();n.hasNext();){var r=n.next();r.isHole()&&r.setShell(t)}}},{key:"getPolygons",value:function(){return this.computePolygons(this._shellList)}},{key:"findShell",value:function(t){for(var e=0,n=null,r=t.iterator();r.hasNext();){var i=r.next();i.isHole()||(n=i,e++)}return V.isTrue(e<=1,"found two shells in MinimalEdgeRing list"),n}},{key:"add",value:function(){if(1===arguments.length){var t=arguments[0];this.add(t.getEdgeEnds(),t.getNodes())}else if(2===arguments.length){var e=arguments[0],n=arguments[1];$e.linkResultDirectedEdges(n);var r=this.buildMaximalEdgeRings(e),i=new dt,o=this.buildMinimalEdgeRings(r,this._shellList,i);this.sortShellsAndHoles(o,this._shellList,i),this.placeFreeHoles(this._shellList,i)}}}],[{key:"constructor_",value:function(){this._geometryFactory=null,this._shellList=new dt;var t=arguments[0];this._geometryFactory=t}},{key:"findEdgeRingContaining",value:function(t,e){for(var n=t.getLinearRing(),r=n.getEnvelopeInternal(),i=n.getCoordinateN(0),o=null,s=null,a=e.iterator();a.hasNext();){var u=a.next(),l=u.getLinearRing(),h=l.getEnvelopeInternal();if(!h.equals(r)&&h.contains(r)){i=Wt.ptNotInList(n.getCoordinates(),l.getCoordinates());var c=!1;Oe.isInRing(i,l.getCoordinates())&&(c=!0),c&&(null===o||s.contains(h))&&(s=(o=u).getLinearRing().getEnvelopeInternal())}}return o}}]),e}(),en=function(){function e(){t(this,e)}return n(e,[{key:"getBounds",value:function(){}}]),e}(),nn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getItem",value:function(){return this._item}},{key:"getBounds",value:function(){return this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){this._bounds=null,this._item=null;var t=arguments[0],e=arguments[1];this._bounds=t,this._item=e}}]),e}(),rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"poll",value:function(){if(this.isEmpty())return null;var t=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),t}},{key:"size",value:function(){return this._size}},{key:"reorder",value:function(t){for(var e=null,n=this._items.get(t);2*t<=this._size&&((e=2*t)!==this._size&&this._items.get(e+1).compareTo(this._items.get(e))<0&&e++,this._items.get(e).compareTo(n)<0);t=e)this._items.set(t,this._items.get(e));this._items.set(t,n)}},{key:"clear",value:function(){this._size=0,this._items.clear()}},{key:"peek",value:function(){return this.isEmpty()?null:this._items.get(1)}},{key:"isEmpty",value:function(){return 0===this._size}},{key:"add",value:function(t){this._items.add(null),this._size+=1;var e=this._size;for(this._items.set(0,t);t.compareTo(this._items.get(Math.trunc(e/2)))<0;e/=2)this._items.set(e,this._items.get(Math.trunc(e/2)));this._items.set(e,t)}}],[{key:"constructor_",value:function(){this._size=null,this._items=null,this._size=0,this._items=new dt,this._items.add(null)}}]),e}(),on=function(){function e(){t(this,e)}return n(e,[{key:"insert",value:function(t,e){}},{key:"remove",value:function(t,e){}},{key:"query",value:function(){}}]),e}(),sn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLevel",value:function(){return this._level}},{key:"size",value:function(){return this._childBoundables.size()}},{key:"getChildBoundables",value:function(){return this._childBoundables}},{key:"addChildBoundable",value:function(t){V.isTrue(null===this._bounds),this._childBoundables.add(t)}},{key:"isEmpty",value:function(){return this._childBoundables.isEmpty()}},{key:"getBounds",value:function(){return null===this._bounds&&(this._bounds=this.computeBounds()),this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){if(this._childBoundables=new dt,this._bounds=null,this._level=null,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._level=t}}}]),e}(),an={reverseOrder:function(){return{compare:function(t,e){return e.compareTo(t)}}},min:function(t){return an.sort(t),t.get(0)},sort:function(t,e){var n=t.toArray();e?At.sort(n,e):At.sort(n);for(var r=t.iterator(),i=0,o=n.length;ie.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,!1,t,n),null):(this.expand(this._boundable2,this._boundable1,!0,t,n),null);if(r)return this.expand(this._boundable1,this._boundable2,!1,t,n),null;if(i)return this.expand(this._boundable2,this._boundable1,!0,t,n),null;throw new x("neither boundable is composite")}},{key:"isLeaves",value:function(){return!(e.isComposite(this._boundable1)||e.isComposite(this._boundable2))}},{key:"compareTo",value:function(t){var e=t;return this._distancee._distance?1:0}},{key:"expand",value:function(t,n,r,i,o){for(var s=t.getChildBoundables().iterator();s.hasNext();){var a=s.next(),u=null;(u=r?new e(n,a,this._itemDistance):new e(a,n,this._itemDistance)).getDistance()-2),r.getLevel()===n)return i.add(r),null;for(var o=r.getChildBoundables().iterator();o.hasNext();){var s=o.next();s instanceof sn?this.boundablesAtLevel(n,s,i):(V.isTrue(s instanceof nn),-1===n&&i.add(s))}return null}}},{key:"query",value:function(){if(1===arguments.length){var t=arguments[0];this.build();var e=new dt;return this.isEmpty()||this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.queryInternal(t,this._root,e),e}if(2===arguments.length){var n=arguments[0],r=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),n)&&this.queryInternal(n,this._root,r)}}},{key:"build",value:function(){if(this._built)return null;this._root=this._itemBoundables.isEmpty()?this.createNode(0):this.createHigherLevels(this._itemBoundables,-1),this._itemBoundables=null,this._built=!0}},{key:"getRoot",value:function(){return this.build(),this._root}},{key:"remove",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];return this.build(),!!this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.remove(t,this._root,e)}if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],o=this.removeItem(r,i);if(o)return!0;for(var s=null,a=r.getChildBoundables().iterator();a.hasNext();){var u=a.next();if(this.getIntersectsOp().intersects(u.getBounds(),n)&&u instanceof sn&&(o=this.remove(n,u,i))){s=u;break}}return null!==s&&s.getChildBoundables().isEmpty()&&r.getChildBoundables().remove(s),o}}},{key:"createHigherLevels",value:function(t,e){V.isTrue(!t.isEmpty());var n=this.createParentBoundables(t,e+1);return 1===n.size()?n.get(0):this.createHigherLevels(n,e+1)}},{key:"depth",value:function(){if(0===arguments.length)return this.isEmpty()?0:(this.build(),this.depth(this._root));if(1===arguments.length){for(var t=0,e=arguments[0].getChildBoundables().iterator();e.hasNext();){var n=e.next();if(n instanceof sn){var r=this.depth(n);r>t&&(t=r)}}return t+1}}},{key:"createParentBoundables",value:function(t,e){V.isTrue(!t.isEmpty());var n=new dt;n.add(this.createNode(e));var r=new dt(t);an.sort(r,this.getComparator());for(var i=r.iterator();i.hasNext();){var o=i.next();this.lastNode(n).getChildBoundables().size()===this.getNodeCapacity()&&n.add(this.createNode(e)),this.lastNode(n).addChildBoundable(o)}return n}},{key:"isEmpty",value:function(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){if(this._root=null,this._built=!1,this._itemBoundables=new dt,this._nodeCapacity=null,0===arguments.length)e.constructor_.call(this,e.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];V.isTrue(t>1,"Node capacity must be greater than 1"),this._nodeCapacity=t}}},{key:"compareDoubles",value:function(t,e){return t>e?1:t0);for(var n=new dt,r=0;r=0;){var u=o.poll(),l=u.getDistance();if(l>=i)break;u.isLeaves()?a.size()l&&(a.poll(),a.add(u)),i=a.peek().getDistance()):u.expandToQueue(o,i)}return s.getItems(a)}}},{key:"createNode",value:function(t){return new pn(t)}},{key:"size",value:function(){return 0===arguments.length?f(i(s.prototype),"size",this).call(this):f(i(s.prototype),"size",this).apply(this,arguments)}},{key:"insert",value:function(){if(!(2===arguments.length&&arguments[1]instanceof Object&&arguments[0]instanceof X))return f(i(s.prototype),"insert",this).apply(this,arguments);var t=arguments[0],e=arguments[1];if(t.isNull())return null;f(i(s.prototype),"insert",this).call(this,t,e)}},{key:"getIntersectsOp",value:function(){return s.intersectsOp}},{key:"verticalSlices",value:function(t,e){for(var n=Math.trunc(Math.ceil(t.size()/e)),r=new Array(e).fill(null),i=t.iterator(),o=0;o0;){var s=o.poll(),a=s.getDistance();if(a>=r)break;s.isLeaves()?(r=a,i=s):s.expandToQueue(o,r)}return null===i?null:[i.getBoundable(0).getItem(),i.getBoundable(1).getItem()]}}else{if(2===arguments.length){var u=arguments[0],l=arguments[1];if(this.isEmpty()||u.isEmpty())return null;var h=new ln(this.getRoot(),u.getRoot(),l);return this.nearestNeighbour(h)}if(3===arguments.length){var c=arguments[2],f=new nn(arguments[0],arguments[1]),g=new ln(this.getRoot(),f,c);return this.nearestNeighbour(g)[0]}if(4===arguments.length){var p=arguments[2],v=arguments[3],d=new nn(arguments[0],arguments[1]),y=new ln(this.getRoot(),d,p);return this.nearestNeighbourK(y,v)}}}},{key:"isWithinDistance",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1],n=A.POSITIVE_INFINITY,r=new rn;for(r.add(t);!r.isEmpty();){var i=r.poll(),o=i.getDistance();if(o>e)return!1;if(i.maximumDistance()<=e)return!0;if(i.isLeaves()){if((n=o)<=e)return!0}else i.expandToQueue(r,n)}return!1}if(3===arguments.length){var s=arguments[0],a=arguments[1],u=arguments[2],l=new ln(this.getRoot(),s.getRoot(),a);return this.isWithinDistance(l,u)}}},{key:"interfaces_",get:function(){return[on,w]}}],[{key:"constructor_",value:function(){if(0===arguments.length)s.constructor_.call(this,s.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];cn.constructor_.call(this,t)}}},{key:"centreX",value:function(t){return s.avg(t.getMinX(),t.getMaxX())}},{key:"avg",value:function(t,e){return(t+e)/2}},{key:"getItems",value:function(t){for(var e=new Array(t.size()).fill(null),n=0;!t.isEmpty();){var r=t.poll();e[n]=r.getBoundable(0).getItem(),n++}return e}},{key:"centreY",value:function(t){return s.avg(t.getMinY(),t.getMaxY())}}]),s}(cn),pn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"computeBounds",value:function(){for(var t=null,e=this.getChildBoundables().iterator();e.hasNext();){var n=e.next();null===t?t=new X(n.getBounds()):t.expandToInclude(n.getBounds())}return t}}],[{key:"constructor_",value:function(){var t=arguments[0];sn.constructor_.call(this,t)}}]),o}(sn);gn.STRtreeNode=pn,gn.xComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreX(t.getBounds()),gn.centreX(e.getBounds()))}}]),e}()),gn.yComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreY(t.getBounds()),gn.centreY(e.getBounds()))}}]),e}()),gn.intersectsOp=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[IntersectsOp]}},{key:"intersects",value:function(t,e){return t.intersects(e)}}]),e}()),gn.DEFAULT_NODE_CAPACITY=10;var vn=function(){function e(){t(this,e)}return n(e,null,[{key:"relativeSign",value:function(t,e){return te?1:0}},{key:"compare",value:function(t,n,r){if(n.equals2D(r))return 0;var i=e.relativeSign(n.x,r.x),o=e.relativeSign(n.y,r.y);switch(t){case 0:return e.compareValue(i,o);case 1:return e.compareValue(o,i);case 2:return e.compareValue(o,-i);case 3:return e.compareValue(-i,o);case 4:return e.compareValue(-i,-o);case 5:return e.compareValue(-o,-i);case 6:return e.compareValue(-o,i);case 7:return e.compareValue(i,-o)}return V.shouldNeverReachHere("invalid octant value"),0}},{key:"compareValue",value:function(t,e){return t<0?-1:t>0?1:e<0?-1:e>0?1:0}}]),e}(),dn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this.coord}},{key:"print",value:function(t){t.print(this.coord),t.print(" seg # = "+this.segmentIndex)}},{key:"compareTo",value:function(t){var e=t;return this.segmentIndexe.segmentIndex?1:this.coord.equals2D(e.coord)?0:this._isInterior?e._isInterior?vn.compare(this._segmentOctant,this.coord,e.coord):1:-1}},{key:"isEndPoint",value:function(t){return 0===this.segmentIndex&&!this._isInterior||this.segmentIndex===t}},{key:"toString",value:function(){return this.segmentIndex+":"+this.coord.toString()}},{key:"isInterior",value:function(){return this._isInterior}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;var t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this._segString=t,this.coord=new z(e),this.segmentIndex=n,this._segmentOctant=r,this._isInterior=!e.equals2D(t.getCoordinate(n))}}]),e}(),yn=function(){function e(){t(this,e)}return n(e,[{key:"hasNext",value:function(){}},{key:"next",value:function(){}},{key:"remove",value:function(){}}]),e}(),mn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getSplitCoordinates",value:function(){var t=new Ht;this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next();this.addEdgeCoordinates(n,r,t),n=r}return t.toCoordinateArray()}},{key:"addCollapsedNodes",value:function(){var t=new dt;this.findCollapsesFromInsertedNodes(t),this.findCollapsesFromExistingVertices(t);for(var e=t.iterator();e.hasNext();){var n=e.next().intValue();this.add(this._edge.getCoordinate(n),n)}}},{key:"createSplitEdgePts",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2;if(2===n)return[new z(t.coord),new z(e.coord)];var r=this._edge.getCoordinate(e.segmentIndex),i=e.isInterior()||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this._edge.getCoordinate(a);return i&&(o[s]=new z(e.coord)),o}},{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"findCollapsesFromExistingVertices",value:function(t){for(var e=0;e=0?n>=0?r>=i?0:1:r>=i?7:6:n>=0?r>=i?3:2:r>=i?4:5}if(arguments[0]instanceof z&&arguments[1]instanceof z){var o=arguments[0],s=arguments[1],a=s.x-o.x,u=s.y-o.y;if(0===a&&0===u)throw new x("Cannot compute the octant for two identical points "+o);return e.octant(a,u)}}}]),e}(),xn=function(){function e(){t(this,e)}return n(e,[{key:"getCoordinates",value:function(){}},{key:"size",value:function(){}},{key:"getCoordinate",value:function(t){}},{key:"isClosed",value:function(){}},{key:"setData",value:function(t){}},{key:"getData",value:function(){}}]),e}(),En=function(){function e(){t(this,e)}return n(e,[{key:"addIntersection",value:function(t,e){}},{key:"interfaces_",get:function(){return[xn]}}]),e}(),kn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinates",value:function(){return this._pts}},{key:"size",value:function(){return this._pts.length}},{key:"getCoordinate",value:function(t){return this._pts[t]}},{key:"isClosed",value:function(){return this._pts[0].equals(this._pts[this._pts.length-1])}},{key:"getSegmentOctant",value:function(t){return t===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(t),this.getCoordinate(t+1))}},{key:"setData",value:function(t){this._data=t}},{key:"safeOctant",value:function(t,e){return t.equals2D(e)?0:_n.octant(t,e)}},{key:"getData",value:function(){return this._data}},{key:"addIntersection",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];this.addIntersectionNode(t,e)}else if(4===arguments.length){var n=arguments[1],r=arguments[3],i=new z(arguments[0].getIntersection(r));this.addIntersection(i,n)}}},{key:"toString",value:function(){return Le.toLineString(new $t(this._pts))}},{key:"getNodeList",value:function(){return this._nodeList}},{key:"addIntersectionNode",value:function(t,e){var n=e,r=n+1;if(r=0&&r>=0||n<=0&&r<=0?Math.max(n,r):0}if(arguments[0]instanceof z){var i=arguments[0];return ft.index(this.p0,this.p1,i)}}},{key:"toGeometry",value:function(t){return t.createLineString([this.p0,this.p1])}},{key:"isVertical",value:function(){return this.p0.x===this.p1.x}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.p0.equals(n.p0)&&this.p1.equals(n.p1)}},{key:"intersection",value:function(t){var e=new Ce;return e.computeIntersection(this.p0,this.p1,t.p0,t.p1),e.hasIntersection()?e.getIntersection(0):null}},{key:"project",value:function(){if(arguments[0]instanceof z){var t=arguments[0];if(t.equals(this.p0)||t.equals(this.p1))return new z(t);var n=this.projectionFactor(t),r=new z;return r.x=this.p0.x+n*(this.p1.x-this.p0.x),r.y=this.p0.y+n*(this.p1.y-this.p0.y),r}if(arguments[0]instanceof e){var i=arguments[0],o=this.projectionFactor(i.p0),s=this.projectionFactor(i.p1);if(o>=1&&s>=1)return null;if(o<=0&&s<=0)return null;var a=this.project(i.p0);o<0&&(a=this.p0),o>1&&(a=this.p1);var u=this.project(i.p1);return s<0&&(u=this.p0),s>1&&(u=this.p1),new e(a,u)}}},{key:"normalize",value:function(){this.p1.compareTo(this.p0)<0&&this.reverse()}},{key:"angle",value:function(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)}},{key:"getCoordinate",value:function(t){return 0===t?this.p0:this.p1}},{key:"distancePerpendicular",value:function(t){return kt.pointToLinePerpendicular(t,this.p0,this.p1)}},{key:"minY",value:function(){return Math.min(this.p0.y,this.p1.y)}},{key:"midPoint",value:function(){return e.midPoint(this.p0,this.p1)}},{key:"projectionFactor",value:function(t){if(t.equals(this.p0))return 0;if(t.equals(this.p1))return 1;var e=this.p1.x-this.p0.x,n=this.p1.y-this.p0.y,r=e*e+n*n;return r<=0?A.NaN:((t.x-this.p0.x)*e+(t.y-this.p0.y)*n)/r}},{key:"closestPoints",value:function(t){var e=this.intersection(t);if(null!==e)return[e,e];var n=new Array(2).fill(null),r=A.MAX_VALUE,i=null,o=this.closestPoint(t.p0);r=o.distance(t.p0),n[0]=o,n[1]=t.p0;var s=this.closestPoint(t.p1);(i=s.distance(t.p1))0&&e<1?this.project(t):this.p0.distance(t)1||A.isNaN(e))&&(e=1),e}},{key:"toString",value:function(){return"LINESTRING( "+this.p0.x+" "+this.p0.y+", "+this.p1.x+" "+this.p1.y+")"}},{key:"isHorizontal",value:function(){return this.p0.y===this.p1.y}},{key:"reflect",value:function(t){var e=this.p1.getY()-this.p0.getY(),n=this.p0.getX()-this.p1.getX(),r=this.p0.getY()*(this.p1.getX()-this.p0.getX())-this.p0.getX()*(this.p1.getY()-this.p0.getY()),i=e*e+n*n,o=e*e-n*n,s=t.getX(),a=t.getY();return new z((-o*s-2*e*n*a-2*e*r)/i,(o*a-2*e*n*s-2*n*r)/i)}},{key:"distance",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return kt.segmentToSegment(this.p0,this.p1,t.p0,t.p1)}if(arguments[0]instanceof z){var n=arguments[0];return kt.pointToSegment(n,this.p0,this.p1)}}},{key:"pointAlong",value:function(t){var e=new z;return e.x=this.p0.x+t*(this.p1.x-this.p0.x),e.y=this.p0.y+t*(this.p1.y-this.p0.y),e}},{key:"hashCode",value:function(){var t=A.doubleToLongBits(this.p0.x);t^=31*A.doubleToLongBits(this.p0.y);var e=Math.trunc(t)^Math.trunc(t>>32),n=A.doubleToLongBits(this.p1.x);return n^=31*A.doubleToLongBits(this.p1.y),e^Math.trunc(n)^Math.trunc(n>>32)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this.p0=null,this.p1=null,0===arguments.length)e.constructor_.call(this,new z,new z);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.p0,t.p1)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.p0=n,this.p1=r}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];e.constructor_.call(this,new z(i,o),new z(s,a))}}},{key:"midPoint",value:function(t,e){return new z((t.x+e.x)/2,(t.y+e.y)/2)}}]),e}(),wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"overlap",value:function(){if(2===arguments.length);else if(4===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[3];arguments[0].getLineSegment(t,this._overlapSeg1),e.getLineSegment(n,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}}}],[{key:"constructor_",value:function(){this._overlapSeg1=new bn,this._overlapSeg2=new bn}}]),e}(),In=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLineSegment",value:function(t,e){e.p0=this._pts[t],e.p1=this._pts[t+1]}},{key:"computeSelect",value:function(t,e,n,r){var i=this._pts[e],o=this._pts[n];if(n-e==1)return r.select(this,e),null;if(!t.intersects(i,o))return null;var s=Math.trunc((e+n)/2);e=t.length-1)return t.length-1;for(var r=We.quadrant(t[n],t[n+1]),i=e+1;in.getId()&&(n.computeOverlaps(i,t),this._nOverlaps++),this._segInt.isDone())return null}}}],[{key:"constructor_",value:function(){if(this._monoChains=new dt,this._index=new gn,this._idCounter=0,this._nodedSegStrings=null,this._nOverlaps=0,0===arguments.length);else if(1===arguments.length){var t=arguments[0];Mn.constructor_.call(this,t)}}}]),o}(Mn),Pn=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"overlap",value:function(){if(4!==arguments.length)return f(i(s.prototype),"overlap",this).apply(this,arguments);var t=arguments[1],e=arguments[2],n=arguments[3],r=arguments[0].getContext(),o=e.getContext();this._si.processIntersections(r,t,o,n)}}],[{key:"constructor_",value:function(){this._si=null;var t=arguments[0];this._si=t}}]),s}(wn);Ln.SegmentOverlapAction=Pn;var Cn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isDeletable",value:function(t,e,n,r){var i=this._inputLine[t],o=this._inputLine[e],s=this._inputLine[n];return!!this.isConcave(i,o,s)&&!!this.isShallow(i,o,s,r)&&this.isShallowSampled(i,o,t,n,r)}},{key:"deleteShallowConcavities",value:function(){for(var t=1,n=this.findNextNonDeletedIndex(t),r=this.findNextNonDeletedIndex(n),i=!1;r=0;r--)this.addPt(t[r])}},{key:"isRedundant",value:function(t){if(this._ptList.size()<1)return!1;var e=this._ptList.get(this._ptList.size()-1);return t.distance(e)Math.PI;)t-=e.PI_TIMES_2;for(;t<=-Math.PI;)t+=e.PI_TIMES_2;return t}},{key:"angle",value:function(){if(1===arguments.length){var t=arguments[0];return Math.atan2(t.y,t.x)}if(2===arguments.length){var e=arguments[0],n=arguments[1],r=n.x-e.x,i=n.y-e.y;return Math.atan2(i,r)}}},{key:"isAcute",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)>0}},{key:"isObtuse",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)<0}},{key:"interiorAngle",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return Math.abs(o-i)}},{key:"normalizePositive",value:function(t){if(t<0){for(;t<0;)t+=e.PI_TIMES_2;t>=e.PI_TIMES_2&&(t=0)}else{for(;t>=e.PI_TIMES_2;)t-=e.PI_TIMES_2;t<0&&(t=0)}return t}},{key:"angleBetween",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return e.diff(i,o)}},{key:"diff",value:function(t,e){var n=null;return(n=tMath.PI&&(n=2*Math.PI-n),n}},{key:"toRadians",value:function(t){return t*Math.PI/180}},{key:"getTurn",value:function(t,n){var r=Math.sin(n-t);return r>0?e.COUNTERCLOCKWISE:r<0?e.CLOCKWISE:e.NONE}},{key:"angleBetweenOriented",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r)-i;return o<=-Math.PI?o+e.PI_TIMES_2:o>Math.PI?o-e.PI_TIMES_2:o}}]),e}();On.PI_TIMES_2=2*Math.PI,On.PI_OVER_2=Math.PI/2,On.PI_OVER_4=Math.PI/4,On.COUNTERCLOCKWISE=ft.COUNTERCLOCKWISE,On.CLOCKWISE=ft.CLOCKWISE,On.NONE=ft.COLLINEAR;var Rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addNextSegment",value:function(t,e){if(this._s0=this._s1,this._s1=this._s2,this._s2=t,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;var n=ft.index(this._s0,this._s1,this._s2),r=n===ft.CLOCKWISE&&this._side===tt.LEFT||n===ft.COUNTERCLOCKWISE&&this._side===tt.RIGHT;0===n?this.addCollinear(e):r?this.addOutsideTurn(n,e):this.addInsideTurn(n,e)}},{key:"addLineEndCap",value:function(t,e){var n=new bn(t,e),r=new bn;this.computeOffsetSegment(n,tt.LEFT,this._distance,r);var i=new bn;this.computeOffsetSegment(n,tt.RIGHT,this._distance,i);var o=e.x-t.x,s=e.y-t.y,a=Math.atan2(s,o);switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:this._segList.addPt(r.p1),this.addDirectedFillet(e,a+Math.PI/2,a-Math.PI/2,ft.CLOCKWISE,this._distance),this._segList.addPt(i.p1);break;case y.CAP_FLAT:this._segList.addPt(r.p1),this._segList.addPt(i.p1);break;case y.CAP_SQUARE:var u=new z;u.x=Math.abs(this._distance)*Math.cos(a),u.y=Math.abs(this._distance)*Math.sin(a);var l=new z(r.p1.x+u.x,r.p1.y+u.y),h=new z(i.p1.x+u.x,i.p1.y+u.y);this._segList.addPt(l),this._segList.addPt(h)}}},{key:"getCoordinates",value:function(){return this._segList.getCoordinates()}},{key:"addMitreJoin",value:function(t,e,n,r){var i=_t.intersection(e.p0,e.p1,n.p0,n.p1);if(null!==i&&(r<=0?1:i.distance(t)/Math.abs(r))<=this._bufParams.getMitreLimit())return this._segList.addPt(i),null;this.addLimitedMitreJoin(e,n,r,this._bufParams.getMitreLimit())}},{key:"addOutsideTurn",value:function(t,n){if(this._offset0.p1.distance(this._offset1.p0)=h&&(a-=2*Math.PI),this._segList.addPt(e),this.addDirectedFillet(t,a,h,r,i),this._segList.addPt(n)}},{key:"addLastSegment",value:function(){this._segList.addPt(this._offset1.p1)}},{key:"initSideSegments",value:function(t,e,n){this._s1=t,this._s2=e,this._side=n,this._seg1.setCoordinates(t,e),this.computeOffsetSegment(this._seg1,n,this._distance,this._offset1)}},{key:"addLimitedMitreJoin",value:function(t,e,n,r){var i=this._seg0.p1,o=On.angle(i,this._seg0.p0),s=On.angleBetweenOriented(this._seg0.p0,i,this._seg1.p1)/2,a=On.normalize(o+s),u=On.normalize(a+Math.PI),l=r*n,h=n-l*Math.abs(Math.sin(s)),c=i.x+l*Math.cos(u),f=i.y+l*Math.sin(u),g=new z(c,f),p=new bn(i,g),v=p.pointAlongOffset(1,h),d=p.pointAlongOffset(1,-h);this._side===tt.LEFT?(this._segList.addPt(v),this._segList.addPt(d)):(this._segList.addPt(d),this._segList.addPt(v))}},{key:"addDirectedFillet",value:function(t,e,n,r,i){var o=r===ft.CLOCKWISE?-1:1,s=Math.abs(e-n),a=Math.trunc(s/this._filletAngleQuantum+.5);if(a<1)return null;for(var u=s/a,l=new z,h=0;h0){var r=new z((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(r);var i=new z((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(i)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}}},{key:"createCircle",value:function(t){var e=new z(t.x+this._distance,t.y);this._segList.addPt(e),this.addDirectedFillet(t,0,2*Math.PI,-1,this._distance),this._segList.closeRing()}},{key:"addBevelJoin",value:function(t,e){this._segList.addPt(t.p1),this._segList.addPt(e.p0)}},{key:"init",value:function(t){this._distance=t,this._maxCurveSegmentError=t*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new Tn,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(t*e.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)}},{key:"addCollinear",value:function(t){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2),this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===y.JOIN_BEVEL||this._bufParams.getJoinStyle()===y.JOIN_MITRE?(t&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,ft.CLOCKWISE,this._distance))}},{key:"closeRing",value:function(){this._segList.closeRing()}},{key:"hasNarrowConcaveAngle",value:function(){return this._hasNarrowConcaveAngle}}],[{key:"constructor_",value:function(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new bn,this._seg1=new bn,this._offset0=new bn,this._offset1=new bn,this._side=0,this._hasNarrowConcaveAngle=!1;var t=arguments[0],n=arguments[1],r=arguments[2];this._precisionModel=t,this._bufParams=n,this._li=new Ce,this._filletAngleQuantum=Math.PI/2/n.getQuadrantSegments(),n.getQuadrantSegments()>=8&&n.getJoinStyle()===y.JOIN_ROUND&&(this._closingSegLengthFactor=e.MAX_CLOSING_SEG_LEN_FACTOR),this.init(r)}}]),e}();Rn.OFFSET_SEGMENT_SEPARATION_FACTOR=.001,Rn.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR=.001,Rn.CURVE_VERTEX_SNAP_DISTANCE_FACTOR=1e-6,Rn.MAX_CLOSING_SEG_LEN_FACTOR=80;var An=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getOffsetCurve",value:function(t,e){if(this._distance=e,0===e)return null;var n=e<0,r=Math.abs(e),i=this.getSegGen(r);t.length<=1?this.computePointCurve(t[0],i):this.computeOffsetCurve(t,n,i);var o=i.getCoordinates();return n&&Wt.reverse(o),o}},{key:"computeSingleSidedBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){n.addSegments(t,!0);var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{n.addSegments(t,!1);var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment(),n.closeRing()}},{key:"computeRingBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);e===tt.RIGHT&&(r=-r);var i=Cn.simplify(t,r),o=i.length-1;n.initSideSegments(i[o-1],i[0],e);for(var s=1;s<=o;s++){var a=1!==s;n.addNextSegment(i[s],a)}n.closeRing()}},{key:"computeLineBufferCurve",value:function(t,e){var n=this.simplifyTolerance(this._distance),r=Cn.simplify(t,n),i=r.length-1;e.initSideSegments(r[0],r[1],tt.LEFT);for(var o=2;o<=i;o++)e.addNextSegment(r[o],!0);e.addLastSegment(),e.addLineEndCap(r[i-1],r[i]);var s=Cn.simplify(t,-n),a=s.length-1;e.initSideSegments(s[a],s[a-1],tt.LEFT);for(var u=a-2;u>=0;u--)e.addNextSegment(s[u],!0);e.addLastSegment(),e.addLineEndCap(s[1],s[0]),e.closeRing()}},{key:"computePointCurve",value:function(t,e){switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:e.createCircle(t);break;case y.CAP_SQUARE:e.createSquare(t)}}},{key:"getLineCurve",value:function(t,e){if(this._distance=e,this.isLineOffsetEmpty(e))return null;var n=Math.abs(e),r=this.getSegGen(n);if(t.length<=1)this.computePointCurve(t[0],r);else if(this._bufParams.isSingleSided()){var i=e<0;this.computeSingleSidedBufferCurve(t,i,r)}else this.computeLineBufferCurve(t,r);return r.getCoordinates()}},{key:"getBufferParameters",value:function(){return this._bufParams}},{key:"simplifyTolerance",value:function(t){return t*this._bufParams.getSimplifyFactor()}},{key:"getRingCurve",value:function(t,n,r){if(this._distance=r,t.length<=2)return this.getLineCurve(t,r);if(0===r)return e.copyCoordinates(t);var i=this.getSegGen(r);return this.computeRingBufferCurve(t,n,i),i.getCoordinates()}},{key:"computeOffsetCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment()}},{key:"isLineOffsetEmpty",value:function(t){return 0===t||t<0&&!this._bufParams.isSingleSided()}},{key:"getSegGen",value:function(t){return new Rn(this._precisionModel,this._bufParams,t)}}],[{key:"constructor_",value:function(){this._distance=0,this._precisionModel=null,this._bufParams=null;var t=arguments[0],e=arguments[1];this._precisionModel=t,this._bufParams=e}},{key:"copyCoordinates",value:function(t){for(var e=new Array(t.length).fill(null),n=0;ni.getMaxY()||this.findStabbedSegments(t,r.getDirectedEdges(),e)}return e}if(3===arguments.length)if(ot(arguments[2],rt)&&arguments[0]instanceof z&&arguments[1]instanceof Ke){for(var o=arguments[0],s=arguments[1],a=arguments[2],u=s.getEdge().getCoordinates(),l=0;lthis._seg.p1.y&&this._seg.reverse(),!(Math.max(this._seg.p0.x,this._seg.p1.x)this._seg.p1.y||ft.index(this._seg.p0,this._seg.p1,o)===ft.RIGHT)){var h=s.getDepth(tt.LEFT);this._seg.p0.equals(u[l])||(h=s.getDepth(tt.RIGHT));var c=new Fn(this._seg,h);a.add(c)}}else if(ot(arguments[2],rt)&&arguments[0]instanceof z&&ot(arguments[1],rt))for(var f=arguments[0],g=arguments[2],p=arguments[1].iterator();p.hasNext();){var v=p.next();v.isForward()&&this.findStabbedSegments(f,v,g)}}},{key:"getDepth",value:function(t){var e=this.findStabbedSegments(t);return 0===e.size()?0:an.min(e)._leftDepth}}],[{key:"constructor_",value:function(){this._subgraphs=null,this._seg=new bn;var t=arguments[0];this._subgraphs=t}}]),e}(),Fn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var e=t;if(this._upwardSeg.minX()>=e._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=e._upwardSeg.minX())return-1;var n=this._upwardSeg.orientationIndex(e._upwardSeg);return 0!==n||0!=(n=-1*e._upwardSeg.orientationIndex(this._upwardSeg))?n:this._upwardSeg.compareTo(e._upwardSeg)}},{key:"compareX",value:function(t,e){var n=t.p0.compareTo(e.p0);return 0!==n?n:t.p1.compareTo(e.p1)}},{key:"toString",value:function(){return this._upwardSeg.toString()}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._upwardSeg=null,this._leftDepth=null;var t=arguments[0],e=arguments[1];this._upwardSeg=new bn(t),this._leftDepth=e}}]),e}();Dn.DepthSegment=Fn;var qn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){_.constructor_.call(this,"Projective point not representable on the Cartesian plane.")}}]),o}(_),Vn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getY",value:function(){var t=this.y/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getX",value:function(){var t=this.x/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getCoordinate",value:function(){var t=new z;return t.x=this.getX(),t.y=this.getY(),t}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.w=null,0===arguments.length)this.x=0,this.y=0,this.w=1;else if(1===arguments.length){var t=arguments[0];this.x=t.x,this.y=t.y,this.w=1}else if(2===arguments.length){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var n=arguments[0],r=arguments[1];this.x=n,this.y=r,this.w=1}else if(arguments[0]instanceof e&&arguments[1]instanceof e){var i=arguments[0],o=arguments[1];this.x=i.y*o.w-o.y*i.w,this.y=o.x*i.w-i.x*o.w,this.w=i.x*o.y-o.x*i.y}else if(arguments[0]instanceof z&&arguments[1]instanceof z){var s=arguments[0],a=arguments[1];this.x=s.y-a.y,this.y=a.x-s.x,this.w=s.x*a.y-a.x*s.y}}else if(3===arguments.length){var u=arguments[0],l=arguments[1],h=arguments[2];this.x=u,this.y=l,this.w=h}else if(4===arguments.length){var c=arguments[0],f=arguments[1],g=arguments[2],p=arguments[3],v=c.y-f.y,d=f.x-c.x,y=c.x*f.y-f.x*c.y,m=g.y-p.y,_=p.x-g.x,x=g.x*p.y-p.x*g.y;this.x=d*x-_*y,this.y=m*y-v*x,this.w=v*_-m*d}}}]),e}(),Gn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"area",value:function(){return e.area(this.p0,this.p1,this.p2)}},{key:"signedArea",value:function(){return e.signedArea(this.p0,this.p1,this.p2)}},{key:"interpolateZ",value:function(t){if(null===t)throw new x("Supplied point is null.");return e.interpolateZ(t,this.p0,this.p1,this.p2)}},{key:"longestSideLength",value:function(){return e.longestSideLength(this.p0,this.p1,this.p2)}},{key:"isAcute",value:function(){return e.isAcute(this.p0,this.p1,this.p2)}},{key:"circumcentre",value:function(){return e.circumcentre(this.p0,this.p1,this.p2)}},{key:"area3D",value:function(){return e.area3D(this.p0,this.p1,this.p2)}},{key:"centroid",value:function(){return e.centroid(this.p0,this.p1,this.p2)}},{key:"inCentre",value:function(){return e.inCentre(this.p0,this.p1,this.p2)}}],[{key:"constructor_",value:function(){this.p0=null,this.p1=null,this.p2=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.p0=t,this.p1=e,this.p2=n}},{key:"area",value:function(t,e,n){return Math.abs(((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2)}},{key:"signedArea",value:function(t,e,n){return((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2}},{key:"det",value:function(t,e,n,r){return t*r-e*n}},{key:"interpolateZ",value:function(t,e,n,r){var i=e.x,o=e.y,s=n.x-i,a=r.x-i,u=n.y-o,l=r.y-o,h=s*l-a*u,c=t.x-i,f=t.y-o,g=(l*c-a*f)/h,p=(-u*c+s*f)/h;return e.getZ()+g*(n.getZ()-e.getZ())+p*(r.getZ()-e.getZ())}},{key:"longestSideLength",value:function(t,e,n){var r=t.distance(e),i=e.distance(n),o=n.distance(t),s=r;return i>s&&(s=i),o>s&&(s=o),s}},{key:"circumcentreDD",value:function(t,e,n){var r=lt.valueOf(t.x).subtract(n.x),i=lt.valueOf(t.y).subtract(n.y),o=lt.valueOf(e.x).subtract(n.x),s=lt.valueOf(e.y).subtract(n.y),a=lt.determinant(r,i,o,s).multiply(2),u=r.sqr().add(i.sqr()),l=o.sqr().add(s.sqr()),h=lt.determinant(i,u,s,l),c=lt.determinant(r,u,o,l),f=lt.valueOf(n.x).subtract(h.divide(a)).doubleValue(),g=lt.valueOf(n.y).add(c.divide(a)).doubleValue();return new z(f,g)}},{key:"isAcute",value:function(t,e,n){return!!On.isAcute(t,e,n)&&!!On.isAcute(e,n,t)&&!!On.isAcute(n,t,e)}},{key:"circumcentre",value:function(t,n,r){var i=r.x,o=r.y,s=t.x-i,a=t.y-o,u=n.x-i,l=n.y-o,h=2*e.det(s,a,u,l),c=e.det(a,s*s+a*a,l,u*u+l*l),f=e.det(s,s*s+a*a,u,u*u+l*l);return new z(i-c/h,o+f/h)}},{key:"perpendicularBisector",value:function(t,e){var n=e.x-t.x,r=e.y-t.y,i=new Vn(t.x+n/2,t.y+r/2,1),o=new Vn(t.x-r+n/2,t.y+n+r/2,1);return new Vn(i,o)}},{key:"angleBisector",value:function(t,e,n){var r=e.distance(t),i=r/(r+e.distance(n)),o=n.x-t.x,s=n.y-t.y;return new z(t.x+i*o,t.y+i*s)}},{key:"area3D",value:function(t,e,n){var r=e.x-t.x,i=e.y-t.y,o=e.getZ()-t.getZ(),s=n.x-t.x,a=n.y-t.y,u=n.getZ()-t.getZ(),l=i*u-o*a,h=o*s-r*u,c=r*a-i*s,f=l*l+h*h+c*c;return Math.sqrt(f)/2}},{key:"centroid",value:function(t,e,n){var r=(t.x+e.x+n.x)/3,i=(t.y+e.y+n.y)/3;return new z(r,i)}},{key:"inCentre",value:function(t,e,n){var r=e.distance(n),i=t.distance(n),o=t.distance(e),s=r+i+o,a=(r*t.x+i*e.x+o*n.x)/s,u=(r*t.y+i*e.y+o*n.y)/s;return new z(a,u)}}]),e}(),Bn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addRingSide",value:function(t,e,n,r,i){if(0===e&&t.length=zt.MINIMUM_VALID_SIZE&&ft.isCCW(t)&&(o=i,s=r,n=tt.opposite(n));var a=this._curveBuilder.getRingCurve(t,n,e);this.addCurve(a,o,s)}},{key:"addRingBothSides",value:function(t,e){this.addRingSide(t,e,tt.LEFT,Z.EXTERIOR,Z.INTERIOR),this.addRingSide(t,e,tt.RIGHT,Z.INTERIOR,Z.EXTERIOR)}},{key:"addPoint",value:function(t){if(this._distance<=0)return null;var e=t.getCoordinates(),n=this._curveBuilder.getLineCurve(e,this._distance);this.addCurve(n,Z.EXTERIOR,Z.INTERIOR)}},{key:"addPolygon",value:function(t){var e=this._distance,n=tt.LEFT;this._distance<0&&(e=-this._distance,n=tt.RIGHT);var r=t.getExteriorRing(),i=Wt.removeRepeatedPoints(r.getCoordinates());if(this._distance<0&&this.isErodedCompletely(r,this._distance))return null;if(this._distance<=0&&i.length<3)return null;this.addRingSide(i,e,n,Z.EXTERIOR,Z.INTERIOR);for(var o=0;o0&&this.isErodedCompletely(s,-this._distance)||this.addRingSide(a,e,tt.opposite(n),Z.INTERIOR,Z.EXTERIOR)}}},{key:"isTriangleErodedCompletely",value:function(t,e){var n=new Gn(t[0],t[1],t[2]),r=n.inCentre();return kt.pointToSegment(r,n.p0,n.p1)i}},{key:"addCollection",value:function(t){for(var e=0;e=this._max)throw new W;var t=this._parent.getGeometryN(this._index++);return t instanceof Bt?(this._subcollectionIterator=new e(t),this._subcollectionIterator.next()):t}},{key:"remove",value:function(){throw new J(this.getClass().getName())}},{key:"hasNext",value:function(){if(this._atStart)return!0;if(null!==this._subcollectionIterator){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)}},{key:"interfaces_",get:function(){return[yn]}}],[{key:"constructor_",value:function(){this._parent=null,this._atStart=null,this._max=null,this._index=null,this._subcollectionIterator=null;var t=arguments[0];this._parent=t,this._atStart=!0,this._index=0,this._max=t.getNumGeometries()}},{key:"isAtomic",value:function(t){return!(t instanceof Bt)}}]),e}(),jn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"locate",value:function(t){return e.locate(t,this._geom)}},{key:"interfaces_",get:function(){return[Yn]}}],[{key:"constructor_",value:function(){this._geom=null;var t=arguments[0];this._geom=t}},{key:"locatePointInPolygon",value:function(t,n){if(n.isEmpty())return Z.EXTERIOR;var r=n.getExteriorRing(),i=e.locatePointInRing(t,r);if(i!==Z.INTERIOR)return i;for(var o=0;o=0;n--){var r=this._edgeList.get(n),i=r.getSym();null===e&&(e=i),null!==t&&i.setNext(t),t=r}e.setNext(t)}},{key:"computeDepths",value:function(){if(1===arguments.length){var t=arguments[0],e=this.findIndex(t),n=t.getDepth(tt.LEFT),r=t.getDepth(tt.RIGHT),i=this.computeDepths(e+1,this._edgeList.size(),n);if(this.computeDepths(0,e,i)!==r)throw new pt("depth mismatch at "+t.getCoordinate())}else if(3===arguments.length){for(var o=arguments[1],s=arguments[2],a=arguments[0];a=0;i--){var o=this._resultAreaEdgeList.get(i),s=o.getSym();switch(null===e&&o.getEdgeRing()===t&&(e=o),r){case this._SCANNING_FOR_INCOMING:if(s.getEdgeRing()!==t)continue;n=s,r=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(o.getEdgeRing()!==t)continue;n.setNextMin(o),r=this._SCANNING_FOR_INCOMING}}r===this._LINKING_TO_OUTGOING&&(V.isTrue(null!==e,"found null for first outgoing dirEdge"),V.isTrue(e.getEdgeRing()===t,"unable to link last incoming dirEdge"),n.setNextMin(e))}},{key:"getOutgoingDegree",value:function(){if(0===arguments.length){for(var t=0,e=this.iterator();e.hasNext();)e.next().isInResult()&&t++;return t}if(1===arguments.length){for(var n=arguments[0],r=0,i=this.iterator();i.hasNext();)i.next().getEdgeRing()===n&&r++;return r}}},{key:"getLabel",value:function(){return this._label}},{key:"findCoveredLineEdges",value:function(){for(var t=Z.NONE,e=this.iterator();e.hasNext();){var n=e.next(),r=n.getSym();if(!n.isLineEdge()){if(n.isInResult()){t=Z.INTERIOR;break}if(r.isInResult()){t=Z.EXTERIOR;break}}}if(t===Z.NONE)return null;for(var i=t,o=this.iterator();o.hasNext();){var s=o.next(),a=s.getSym();s.isLineEdge()?s.getEdge().setCovered(i===Z.INTERIOR):(s.isInResult()&&(i=Z.EXTERIOR),a.isInResult()&&(i=Z.INTERIOR))}}},{key:"computeLabelling",value:function(t){f(i(s.prototype),"computeLabelling",this).call(this,t),this._label=new Ae(Z.NONE);for(var e=this.iterator();e.hasNext();)for(var n=e.next().getEdge().getLabel(),r=0;r<2;r++){var o=n.getLocation(r);o!==Z.INTERIOR&&o!==Z.BOUNDARY||this._label.setLocation(r,Z.INTERIOR)}}}],[{key:"constructor_",value:function(){this._resultAreaEdgeList=null,this._label=null,this._SCANNING_FOR_INCOMING=1,this._LINKING_TO_OUTGOING=2}}]),s}(Xn),Zn=function(e){r(o,e);var i=c(o);function o(){return t(this,o),i.call(this)}return n(o,[{key:"createNode",value:function(t){return new Ge(t,new Un)}}]),o}(Qe),Hn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var n=t;return e.compareOriented(this._pts,this._orientation,n._pts,n._orientation)}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._pts=null,this._orientation=null;var t=arguments[0];this._pts=t,this._orientation=e.orientation(t)}},{key:"orientation",value:function(t){return 1===Wt.increasingDirection(t)}},{key:"compareOriented",value:function(t,e,n,r){for(var i=e?1:-1,o=r?1:-1,s=e?t.length:-1,a=r?n.length:-1,u=e?0:t.length-1,l=r?0:n.length-1;;){var h=t[u].compareTo(n[l]);if(0!==h)return h;var c=(u+=i)===s,f=(l+=o)===a;if(c&&!f)return-1;if(!c&&f)return 1;if(c&&f)return 0}}}]),e}(),Wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.print("MULTILINESTRING ( ");for(var e=0;e0&&t.print(","),t.print("(");for(var r=n.getCoordinates(),i=0;i0&&t.print(","),t.print(r[i].x+" "+r[i].y);t.println(")")}t.print(") ")}},{key:"addAll",value:function(t){for(var e=t.iterator();e.hasNext();)this.add(e.next())}},{key:"findEdgeIndex",value:function(t){for(var e=0;et?1:this.diste?1:0}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this.coord=null,this.segmentIndex=null,this.dist=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.coord=new z(t),this.segmentIndex=e,this.dist=n}}]),e}(),$n=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this._nodeMap.values().iterator()}},{key:"addSplitEdges",value:function(t){this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next(),i=this.createSplitEdge(n,r);t.add(i),n=r}}},{key:"addEndpoints",value:function(){var t=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[t],t,0)}},{key:"createSplitEdge",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2,r=this.edge.pts[e.segmentIndex],i=e.dist>0||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this.edge.pts[a];return i&&(o[s]=e.coord),new or(o,new Ae(this.edge._label))}},{key:"add",value:function(t,e,n){var r=new Qn(t,e,n),i=this._nodeMap.get(r);return null!==i?i:(this._nodeMap.put(r,r),r)}},{key:"isIntersection",value:function(t){for(var e=this.iterator();e.hasNext();)if(e.next().coord.equals(t))return!0;return!1}}],[{key:"constructor_",value:function(){this._nodeMap=new Ze,this.edge=null;var t=arguments[0];this.edge=t}}]),e}(),tr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isIntersects",value:function(){return!this.isDisjoint()}},{key:"isCovers",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"isCoveredBy",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"set",value:function(){if(1===arguments.length)for(var t=arguments[0],e=0;e=0&&e>=0&&this.setAtLeast(t,e,n)}},{key:"isWithin",value:function(){return e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"isTouches",value:function(t,n){return t>n?this.isTouches(n,t):(t===Mt.A&&n===Mt.A||t===Mt.L&&n===Mt.L||t===Mt.L&&n===Mt.A||t===Mt.P&&n===Mt.A||t===Mt.P&&n===Mt.L)&&this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&(e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))}},{key:"isOverlaps",value:function(t,n){return t===Mt.P&&n===Mt.P||t===Mt.A&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&1===this._matrix[Z.INTERIOR][Z.INTERIOR]&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR])}},{key:"isEquals",value:function(t,n){return t===n&&e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"toString",value:function(){for(var t=new Qt("123456789"),e=0;e<3;e++)for(var n=0;n<3;n++)t.setCharAt(3*e+n,Mt.toDimensionSymbol(this._matrix[e][n]));return t.toString()}},{key:"setAll",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this._matrix[e][n]=t}},{key:"get",value:function(t,e){return this._matrix[t][e]}},{key:"transpose",value:function(){var t=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=t,t=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=t,t=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=t,this}},{key:"matches",value:function(t){if(9!==t.length)throw new x("Should be length 9: "+t);for(var n=0;n<3;n++)for(var r=0;r<3;r++)if(!e.matches(this._matrix[n][r],t.charAt(3*n+r)))return!1;return!0}},{key:"add",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this.setAtLeast(e,n,t.get(e,n))}},{key:"isDisjoint",value:function(){return this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.INTERIOR][Z.BOUNDARY]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.BOUNDARY]===Mt.FALSE}},{key:"isCrosses",value:function(t,n){return t===Mt.P&&n===Mt.L||t===Mt.P&&n===Mt.A||t===Mt.L&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR]):t===Mt.L&&n===Mt.P||t===Mt.A&&n===Mt.P||t===Mt.A&&n===Mt.L?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&0===this._matrix[Z.INTERIOR][Z.INTERIOR]}},{key:"interfaces_",get:function(){return[b]}}],[{key:"constructor_",value:function(){if(this._matrix=null,0===arguments.length)this._matrix=Array(3).fill().map((function(){return Array(3)})),this.setAll(Mt.FALSE);else if(1===arguments.length)if("string"==typeof arguments[0]){var t=arguments[0];e.constructor_.call(this),this.set(t)}else if(arguments[0]instanceof e){var n=arguments[0];e.constructor_.call(this),this._matrix[Z.INTERIOR][Z.INTERIOR]=n._matrix[Z.INTERIOR][Z.INTERIOR],this._matrix[Z.INTERIOR][Z.BOUNDARY]=n._matrix[Z.INTERIOR][Z.BOUNDARY],this._matrix[Z.INTERIOR][Z.EXTERIOR]=n._matrix[Z.INTERIOR][Z.EXTERIOR],this._matrix[Z.BOUNDARY][Z.INTERIOR]=n._matrix[Z.BOUNDARY][Z.INTERIOR],this._matrix[Z.BOUNDARY][Z.BOUNDARY]=n._matrix[Z.BOUNDARY][Z.BOUNDARY],this._matrix[Z.BOUNDARY][Z.EXTERIOR]=n._matrix[Z.BOUNDARY][Z.EXTERIOR],this._matrix[Z.EXTERIOR][Z.INTERIOR]=n._matrix[Z.EXTERIOR][Z.INTERIOR],this._matrix[Z.EXTERIOR][Z.BOUNDARY]=n._matrix[Z.EXTERIOR][Z.BOUNDARY],this._matrix[Z.EXTERIOR][Z.EXTERIOR]=n._matrix[Z.EXTERIOR][Z.EXTERIOR]}}},{key:"matches",value:function(){if(Number.isInteger(arguments[0])&&"string"==typeof arguments[1]){var t=arguments[0],n=arguments[1];return n===Mt.SYM_DONTCARE||n===Mt.SYM_TRUE&&(t>=0||t===Mt.TRUE)||n===Mt.SYM_FALSE&&t===Mt.FALSE||n===Mt.SYM_P&&t===Mt.P||n===Mt.SYM_L&&t===Mt.L||n===Mt.SYM_A&&t===Mt.A}if("string"==typeof arguments[0]&&"string"==typeof arguments[1]){var r=arguments[1];return new e(arguments[0]).matches(r)}}},{key:"isTrue",value:function(t){return t>=0||t===Mt.TRUE}}]),e}(),er=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"size",value:function(){return this._size}},{key:"addAll",value:function(t){return null===t||0===t.length?null:(this.ensureCapacity(this._size+t.length),xt.arraycopy(t,0,this._data,this._size,t.length),void(this._size+=t.length))}},{key:"ensureCapacity",value:function(t){if(t<=this._data.length)return null;var e=Math.max(t,2*this._data.length);this._data=At.copyOf(this._data,e)}},{key:"toArray",value:function(){var t=new Array(this._size).fill(null);return xt.arraycopy(this._data,0,t,0,this._size),t}},{key:"add",value:function(t){this.ensureCapacity(this._size+1),this._data[this._size]=t,++this._size}}],[{key:"constructor_",value:function(){if(this._data=null,this._size=0,0===arguments.length)e.constructor_.call(this,10);else if(1===arguments.length){var t=arguments[0];this._data=new Array(t).fill(null)}}}]),e}(),nr=function(){function e(){t(this,e)}return n(e,[{key:"getChainStartIndices",value:function(t){var e=0,n=new er(Math.trunc(t.length/2));n.add(e);do{var r=this.findChainEnd(t,e);n.add(r),e=r}while(en?e:n}},{key:"getMinX",value:function(t){var e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return ee&&(r=1),this._depth[t][n]=r}}}},{key:"getDelta",value:function(t){return this._depth[t][tt.RIGHT]-this._depth[t][tt.LEFT]}},{key:"getLocation",value:function(t,e){return this._depth[t][e]<=0?Z.EXTERIOR:Z.INTERIOR}},{key:"toString",value:function(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}},{key:"add",value:function(){if(1===arguments.length)for(var t=arguments[0],n=0;n<2;n++)for(var r=1;r<3;r++){var i=t.getLocation(n,r);i!==Z.EXTERIOR&&i!==Z.INTERIOR||(this.isNull(n,r)?this._depth[n][r]=e.depthAtLocation(i):this._depth[n][r]+=e.depthAtLocation(i))}else if(3===arguments.length){var o=arguments[0],s=arguments[1];arguments[2]===Z.INTERIOR&&this._depth[o][s]++}}}],[{key:"constructor_",value:function(){this._depth=Array(2).fill().map((function(){return Array(3)}));for(var t=0;t<2;t++)for(var n=0;n<3;n++)this._depth[t][n]=e.NULL_VALUE}},{key:"depthAtLocation",value:function(t){return t===Z.EXTERIOR?0:t===Z.INTERIOR?1:e.NULL_VALUE}}]),e}();ir.NULL_VALUE=-1;var or=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getDepth",value:function(){return this._depth}},{key:"getCollapsedEdge",value:function(){var t=new Array(2).fill(null);return t[0]=this.pts[0],t[1]=this.pts[1],new s(t,Ae.toLineLabel(this._label))}},{key:"isIsolated",value:function(){return this._isIsolated}},{key:"getCoordinates",value:function(){return this.pts}},{key:"setIsolated",value:function(t){this._isIsolated=t}},{key:"setName",value:function(t){this._name=t}},{key:"equals",value:function(t){if(!(t instanceof s))return!1;var e=t;if(this.pts.length!==e.pts.length)return!1;for(var n=!0,r=!0,i=this.pts.length,o=0;o0?this.pts[0]:null;if(1===arguments.length){var t=arguments[0];return this.pts[t]}}},{key:"print",value:function(t){t.print("edge "+this._name+": "),t.print("LINESTRING (");for(var e=0;e0&&t.print(","),t.print(this.pts[e].x+" "+this.pts[e].y);t.print(") "+this._label+" "+this._depthDelta)}},{key:"computeIM",value:function(t){s.updateIM(this._label,t)}},{key:"isCollapsed",value:function(){return!!this._label.isArea()&&3===this.pts.length&&!!this.pts[0].equals(this.pts[2])}},{key:"isClosed",value:function(){return this.pts[0].equals(this.pts[this.pts.length-1])}},{key:"getMaximumSegmentIndex",value:function(){return this.pts.length-1}},{key:"getDepthDelta",value:function(){return this._depthDelta}},{key:"getNumPoints",value:function(){return this.pts.length}},{key:"printReverse",value:function(t){t.print("edge "+this._name+": ");for(var e=this.pts.length-1;e>=0;e--)t.print(this.pts[e]+" ");t.println("")}},{key:"getMonotoneChainEdge",value:function(){return null===this._mce&&(this._mce=new rr(this)),this._mce}},{key:"getEnvelope",value:function(){if(null===this._env){this._env=new X;for(var t=0;t0&&t.append(","),t.append(this.pts[e].x+" "+this.pts[e].y);return t.append(") "+this._label+" "+this._depthDelta),t.toString()}},{key:"isPointwiseEqual",value:function(t){if(this.pts.length!==t.pts.length)return!1;for(var e=0;er||this._maxyo;if(s)return!1;var a=this.intersectsToleranceSquare(t,e);return V.isTrue(!(s&&a),"Found bad envelope test"),a}},{key:"initCorners",value:function(t){var e=.5;this._minx=t.x-e,this._maxx=t.x+e,this._miny=t.y-e,this._maxy=t.y+e,this._corner[0]=new z(this._maxx,this._maxy),this._corner[1]=new z(this._minx,this._maxy),this._corner[2]=new z(this._minx,this._miny),this._corner[3]=new z(this._maxx,this._miny)}},{key:"intersects",value:function(t,e){return 1===this._scaleFactor?this.intersectsScaled(t,e):(this.copyScaled(t,this._p0Scaled),this.copyScaled(e,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}},{key:"scale",value:function(t){return Math.round(t*this._scaleFactor)}},{key:"getCoordinate",value:function(){return this._originalPt}},{key:"copyScaled",value:function(t,e){e.x=this.scale(t.x),e.y=this.scale(t.y)}},{key:"getSafeEnvelope",value:function(){if(null===this._safeEnv){var t=e.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new X(this._originalPt.x-t,this._originalPt.x+t,this._originalPt.y-t,this._originalPt.y+t)}return this._safeEnv}},{key:"intersectsPixelClosure",value:function(t,e){return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.hasIntersection()))))}},{key:"intersectsToleranceSquare",value:function(t,e){var n=!1,r=!1;return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.isProper()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.isProper()||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.isProper()||(this._li.hasIntersection()&&(r=!0),this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.isProper()||n&&r||t.equals(this._pt)||e.equals(this._pt)))))}},{key:"addSnappedNode",value:function(t,e){var n=t.getCoordinate(e),r=t.getCoordinate(e+1);return!!this.intersects(n,r)&&(t.addIntersection(this.getCoordinate(),e),!0)}}],[{key:"constructor_",value:function(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;var t=arguments[0],e=arguments[1],n=arguments[2];if(this._originalPt=t,this._pt=t,this._scaleFactor=e,this._li=n,e<=0)throw new x("Scale factor must be non-zero");1!==e&&(this._pt=new z(this.scale(t.x),this.scale(t.y)),this._p0Scaled=new z,this._p1Scaled=new z),this.initCorners(this._pt)}}]),e}();lr.SAFE_ENV_EXPANSION_FACTOR=.75;var hr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"select",value:function(){if(1===arguments.length);else if(2===arguments.length){var t=arguments[1];arguments[0].getLineSegment(t,this.selectedSegment),this.select(this.selectedSegment)}}}],[{key:"constructor_",value:function(){this.selectedSegment=new bn}}]),e}(),cr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"snap",value:function(){if(1===arguments.length){var e=arguments[0];return this.snap(e,null,-1)}if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=r.getSafeEnvelope(),a=new fr(r,i,o);return this._index.query(s,new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[hn]}},{key:"visitItem",value:function(t){t.select(s,a)}}]),e}())),a.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var t=arguments[0];this._index=t}}]),e}(),fr=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isNodeAdded",value:function(){return this._isNodeAdded}},{key:"select",value:function(){if(!(2===arguments.length&&Number.isInteger(arguments[1])&&arguments[0]instanceof In))return f(i(s.prototype),"select",this).apply(this,arguments);var t=arguments[1],e=arguments[0].getContext();if(this._parentEdge===e&&(t===this._hotPixelVertexIndex||t+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(e,t)}}],[{key:"constructor_",value:function(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var t=arguments[0],e=arguments[1],n=arguments[2];this._hotPixel=t,this._parentEdge=e,this._hotPixelVertexIndex=n}}]),s}(hr);cr.HotPixelSnapAction=fr;var gr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"processIntersections",value:function(t,e,n,r){if(t===n&&e===r)return null;var i=t.getCoordinates()[e],o=t.getCoordinates()[e+1],s=n.getCoordinates()[r],a=n.getCoordinates()[r+1];if(this._li.computeIntersection(i,o,s,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var u=0;u=0;t--){try{this.bufferReducedPrecision(t)}catch(t){if(!(t instanceof pt))throw t;this._saveException=t}if(null!==this._resultGeometry)return null}throw this._saveException}if(1===arguments.length){var n=arguments[0],r=e.precisionScaleFactor(this._argGeom,this._distance,n),i=new ie(r);this.bufferFixedPrecision(i)}}},{key:"computeGeometry",value:function(){if(this.bufferOriginalPrecision(),null!==this._resultGeometry)return null;var t=this._argGeom.getFactory().getPrecisionModel();t.getType()===ie.FIXED?this.bufferFixedPrecision(t):this.bufferReducedPrecision()}},{key:"setQuadrantSegments",value:function(t){this._bufParams.setQuadrantSegments(t)}},{key:"bufferOriginalPrecision",value:function(){try{var t=new sr(this._bufParams);this._resultGeometry=t.buffer(this._argGeom,this._distance)}catch(t){if(!(t instanceof F))throw t;this._saveException=t}}},{key:"getResultGeometry",value:function(t){return this._distance=t,this.computeGeometry(),this._resultGeometry}},{key:"setEndCapStyle",value:function(t){this._bufParams.setEndCapStyle(t)}}],[{key:"constructor_",value:function(){if(this._argGeom=null,this._distance=null,this._bufParams=new y,this._resultGeometry=null,this._saveException=null,1===arguments.length){var t=arguments[0];this._argGeom=t}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this._argGeom=e,this._bufParams=n}}},{key:"bufferOp",value:function(){if(2===arguments.length){var t=arguments[1];return new e(arguments[0]).getResultGeometry(t)}if(3===arguments.length){if(Number.isInteger(arguments[2])&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var n=arguments[1],r=arguments[2],i=new e(arguments[0]);return i.setQuadrantSegments(r),i.getResultGeometry(n)}if(arguments[2]instanceof y&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var o=arguments[1];return new e(arguments[0],arguments[2]).getResultGeometry(o)}}else if(4===arguments.length){var s=arguments[1],a=arguments[2],u=arguments[3],l=new e(arguments[0]);return l.setQuadrantSegments(a),l.setEndCapStyle(u),l.getResultGeometry(s)}}},{key:"precisionScaleFactor",value:function(t,e,n){var r=t.getEnvelopeInternal(),i=Et.max(Math.abs(r.getMaxX()),Math.abs(r.getMaxY()),Math.abs(r.getMinX()),Math.abs(r.getMinY()))+2*(e>0?e:0),o=n-Math.trunc(Math.log(i)/Math.log(10)+1);return Math.pow(10,o)}}]),e}();vr.CAP_ROUND=y.CAP_ROUND,vr.CAP_BUTT=y.CAP_FLAT,vr.CAP_FLAT=y.CAP_FLAT,vr.CAP_SQUARE=y.CAP_SQUARE,vr.MAX_PRECISION_DIGITS=12;var dr=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],yr=function(){function e(n){t(this,e),this.geometryFactory=n||new ae}return n(e,[{key:"read",value:function(t){var e,n=(e="string"==typeof t?JSON.parse(t):t).type;if(!mr[n])throw new Error("Unknown GeoJSON type: "+e.type);return-1!==dr.indexOf(n)?mr[n].call(this,e.coordinates):"GeometryCollection"===n?mr[n].call(this,e.geometries):mr[n].call(this,e)}},{key:"write",value:function(t){var e=t.getGeometryType();if(!_r[e])throw new Error("Geometry is not supported");return _r[e].call(this,t)}}]),e}(),mr={Feature:function(t){var e={};for(var n in t)e[n]=t[n];if(t.geometry){var r=t.geometry.type;if(!mr[r])throw new Error("Unknown GeoJSON type: "+t.type);e.geometry=this.read(t.geometry)}return t.bbox&&(e.bbox=mr.bbox.call(this,t.bbox)),e},FeatureCollection:function(t){var e={};if(t.features){e.features=[];for(var n=0;n1?0:t<-1?Xn:Math.acos(t)}function ir(t){return t>1?Un:t<-1?-Un:Math.asin(t)}function or(){}function sr(t,e){t&&ur.hasOwnProperty(t.type)&&ur[t.type](t,e)}var ar={Feature:function(t,e){sr(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++rXn?t-Hn:t<-Xn?t+Hn:t,e]}function xr(t){return function(e,n){return[(e+=t)>Xn?e-Hn:e<-Xn?e+Hn:e,n]}}function Er(t){var e=xr(t);return e.invert=xr(-t),e}function kr(t,e){var n=tr(t),r=er(t),i=tr(e),o=er(e);function s(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*n+a*r;return[$n(u*i-h*o,a*n-l*r),ir(h*i+u*o)]}return s.invert=function(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*i-u*o;return[$n(u*i+l*o,a*n+h*r),ir(h*n-a*r)]},s}function br(t,e){(e=fr(e))[0]-=t,yr(e);var n=rr(-e[1]);return((-e[2]<0?-n:n)+Hn-jn)%Hn}function wr(){var t,e=[];return{point:function(e,n){t.push([e,n])},lineStart:function(){e.push(t=[])},lineEnd:or,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function Ir(t,e){return Kn(t[0]-e[0])=0;--o)i.point((h=l[o])[0],h[1]);else r(f.x,f.p.x,-1,i);f=f.p}l=(f=f.o).z,g=!g}while(!f.v);i.lineEnd()}}}function Mr(t){if(e=t.length){for(var e,n,r=0,i=t[0];++re?1:t>=e?0:NaN}function Pr(t){for(var e,n,r,i=t.length,o=-1,s=0;++o=0;)for(e=(r=t[i]).length;--e>=0;)n[--s]=r[e];return n}Gn(),Gn(),Gn(),_r.invert=_r,function(t){var e;1===t.length&&(e=t,t=function(t,n){return Lr(e(t),n)})}(Lr);var Cr=1e9,Tr=-Cr;function Or(t,e,n,r){function i(i,o){return t<=i&&i<=n&&e<=o&&o<=r}function o(i,o,a,l){var h=0,c=0;if(null==i||(h=s(i,a))!==(c=s(o,a))||u(i,o)<0^a>0)do{l.point(0===h||3===h?t:n,h>1?r:e)}while((h=(h+a+4)%4)!==c);else l.point(o[0],o[1])}function s(r,i){return Kn(r[0]-t)0?0:3:Kn(r[0]-n)0?2:1:Kn(r[1]-e)0?1:0:i>0?3:2}function a(t,e){return u(t.x,e.x)}function u(t,e){var n=s(t,1),r=s(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){var u,l,h,c,f,g,p,v,d,y,m,_=s,x=wr(),E={point:k,lineStart:function(){E.point=b,l&&l.push(h=[]);y=!0,d=!1,p=v=NaN},lineEnd:function(){u&&(b(c,f),g&&d&&x.rejoin(),u.push(x.result()));E.point=k,d&&_.lineEnd()},polygonStart:function(){_=x,u=[],l=[],m=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,i=l.length;nr&&(f-o)*(r-s)>(g-s)*(t-o)&&++e:g<=r&&(f-o)*(r-s)<(g-s)*(t-o)&&--e;return e}(),n=m&&e,i=(u=Pr(u)).length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),o(null,null,1,s),s.lineEnd()),i&&Sr(u,a,e,o,s),s.polygonEnd());_=s,u=l=h=null}};function k(t,e){i(t,e)&&_.point(t,e)}function b(o,s){var a=i(o,s);if(l&&h.push([o,s]),y)c=o,f=s,g=a,y=!1,a&&(_.lineStart(),_.point(o,s));else if(a&&d)_.point(o,s);else{var u=[p=Math.max(Tr,Math.min(Cr,p)),v=Math.max(Tr,Math.min(Cr,v))],x=[o=Math.max(Tr,Math.min(Cr,o)),s=Math.max(Tr,Math.min(Cr,s))];!function(t,e,n,r,i,o){var s,a=t[0],u=t[1],l=0,h=1,c=e[0]-a,f=e[1]-u;if(s=n-a,c||!(s>0)){if(s/=c,c<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=i-a,c||!(s<0)){if(s/=c,c<0){if(s>h)return;s>l&&(l=s)}else if(c>0){if(s0)){if(s/=f,f<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=o-u,f||!(s<0)){if(s/=f,f<0){if(s>h)return;s>l&&(l=s)}else if(f>0){if(s0&&(t[0]=a+l*c,t[1]=u+l*f),h<1&&(e[0]=a+h*c,e[1]=u+h*f),!0}}}}}(u,x,t,e,n,r)?a&&(_.lineStart(),_.point(o,s),m=!1):(d||(_.lineStart(),_.point(u[0],u[1])),_.point(x[0],x[1]),a||_.lineEnd(),m=!1)}p=o,v=s,d=a}return E}}var Rr=Gn();function Ar(t){return t}Gn(),Gn(),Gn();var Dr=1/0,Fr=Dr,qr=-Dr,Vr=qr,Gr={point:function(t,e){tqr&&(qr=t);eVr&&(Vr=e)},lineStart:or,lineEnd:or,polygonStart:or,polygonEnd:or,result:function(){var t=[[Dr,Fr],[qr,Vr]];return qr=Vr=-(Fr=Dr=1/0),t}};function Br(t,e,n,r){return function(i,o){var s,a,u,l=e(o),h=i.invert(r[0],r[1]),c=wr(),f=e(c),g=!1,p={point:v,lineStart:y,lineEnd:m,polygonStart:function(){p.point=_,p.lineStart=x,p.lineEnd=E,a=[],s=[]},polygonEnd:function(){p.point=v,p.lineStart=y,p.lineEnd=m,a=Pr(a);var t=function(t,e){var n=e[0],r=e[1],i=[er(n),-tr(n),0],o=0,s=0;Rr.reset();for(var a=0,u=t.length;a=0?1:-1,w=b*k,I=w>Xn,N=p*x;if(Rr.add($n(N*b*er(w),v*E+N*tr(w))),o+=I?k+b*Hn:k,I^f>=n^m>=n){var S=pr(fr(c),fr(y));yr(S);var M=pr(i,S);yr(M);var L=(I^k>=0?-1:1)*ir(M[2]);(r>L||r===L&&(S[0]||S[1]))&&(s+=I^k>=0?1:-1)}}return(o<-jn||o0){for(g||(o.polygonStart(),g=!0),o.lineStart(),t=0;t1&&2&i&&l.push(l.pop().concat(l.shift())),a.push(l.filter(Yr))}return p}}function Yr(t){return t.length>1}function zr(t,e){return((t=t.x)[0]<0?t[1]-Un-jn:Un-t[1])-((e=e.x)[0]<0?e[1]-Un-jn:Un-e[1])}Gn();var jr=Br((function(){return!0}),(function(t){var e,n=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,s){var a=o>0?Xn:-Xn,u=Kn(o-n);Kn(u-Xn)0?Un:-Un),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),e=0):i!==a&&u>=Xn&&(Kn(n-i)jn?Qn((er(e)*(o=tr(r))*er(n)-er(r)*(i=tr(e))*er(t))/(i*o*s)):(e+r)/2}(n,r,o,s),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),e=0),t.point(n=o,r=s),i=a},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var i;if(null==t)i=n*Un,r.point(-Xn,i),r.point(0,i),r.point(Xn,i),r.point(Xn,0),r.point(Xn,-i),r.point(0,-i),r.point(-Xn,-i),r.point(-Xn,0),r.point(-Xn,i);else if(Kn(t[0]-e[0])>jn){var o=t[0]0,i=Kn(n)>jn;function o(t,e){return tr(t)*tr(e)>n}function s(t,e,r){var i=[1,0,0],o=pr(fr(t),fr(e)),s=gr(o,o),a=o[0],u=s-a*a;if(!u)return!r&&t;var l=n*s/u,h=-n*a/u,c=pr(i,o),f=dr(i,l);vr(f,dr(o,h));var g=c,p=gr(f,g),v=gr(g,g),d=p*p-v*(gr(f,f)-1);if(!(d<0)){var y=nr(d),m=dr(g,(-p-y)/v);if(vr(m,f),m=cr(m),!r)return m;var _,x=t[0],E=e[0],k=t[1],b=e[1];E0^m[1]<(Kn(m[0]-x)Xn^(x<=m[0]&&m[0]<=E)){var N=dr(g,(-p+y)/v);return vr(N,f),[m,cr(N)]}}}function a(e,n){var i=r?t:Xn-t,o=0;return e<-i?o|=1:e>i&&(o|=2),n<-i?o|=4:n>i&&(o|=8),o}return Br(o,(function(t){var e,n,u,l,h;return{lineStart:function(){l=u=!1,h=1},point:function(c,f){var g,p=[c,f],v=o(c,f),d=r?v?0:a(c,f):v?a(c+(c<0?Xn:-Xn),f):0;if(!e&&(l=u=v)&&t.lineStart(),v!==u&&(!(g=s(e,p))||Ir(e,g)||Ir(p,g))&&(p[0]+=jn,p[1]+=jn,v=o(p[0],p[1])),v!==u)h=0,v?(t.lineStart(),g=s(p,e),t.point(g[0],g[1])):(g=s(e,p),t.point(g[0],g[1]),t.lineEnd()),e=g;else if(i&&e&&r^v){var y;d&n||!(y=s(p,e,!0))||(h=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1])))}!v||e&&Ir(e,p)||t.point(p[0],p[1]),e=p,u=v,n=d},lineEnd:function(){u&&t.lineEnd(),e=null},clean:function(){return h|(l&&u)<<1}}}),(function(n,r,i,o){!function(t,e,n,r,i,o){if(n){var s=tr(e),a=er(e),u=r*n;null==i?(i=e+r*Hn,o=e-u/2):(i=br(s,i),o=br(s,o),(r>0?io)&&(i+=r*Hn));for(var l,h=i;r>0?h>o:h4*e&&v--){var x=s+f,E=a+g,k=u+p,b=nr(x*x+E*E+k*k),w=ir(k/=b),I=Kn(Kn(k)-1)e||Kn((y*L+m*P)/_-.5)>.3||s*f+a*g+u*p2?t[2]%360*Jn:0,M()):[d*Wn,y*Wn,m*Wn]},I.precision=function(t){return arguments.length?(w=Kr(S,b=t*t),L()):nr(b)},I.fitExtent=function(t,e){return Hr(I,t,e)},I.fitSize=function(t,e){return function(t,e,n){return Hr(t,[[0,0],e],n)}(I,t,e)},function(){return e=t.apply(this,arguments),I.invert=e.invert&&N,M()}}((function(){return t}))()}function ti(t){return function(e,n){var r=tr(e),i=tr(n),o=t(r*i);return[o*i*er(e),o*er(n)]}}function ei(t){return function(e,n){var r=nr(e*e+n*n),i=t(r),o=er(i),s=tr(i);return[$n(e*o,r*s),ir(r&&n*o/r)]}}ti((function(t){return nr(2/(1+t))})).invert=ei((function(t){return 2*ir(t/2)}));var ni=ti((function(t){return(t=rr(t))&&t/er(t)}));function ri(){return $r(ni).scale(79.4188).clipAngle(179.999)}function ii(t,e){return[t,e]}ni.invert=ei((function(t){return t})),ii.invert=ii;var oi=Vn.BufferOp,si=Vn.GeoJSONReader,ai=Vn.GeoJSONWriter;function ui(t,e,n,r){var i=t.properties||{},o="Feature"===t.type?t.geometry:t;if("GeometryCollection"===o.type){var s=[];return mt(t,(function(t){var i=ui(t,e,n,r);i&&s.push(i)})),C(s)}var a=function(t){var e=An(t).geometry.coordinates,n=[-e[0],-e[1]];return ri().rotate(n).scale(x)}(o),u={type:o.type,coordinates:hi(o.coordinates,a)},l=(new si).read(u),h=F(q(e,n),"meters"),c=oi.bufferOp(l,h,r);if(!li((c=(new ai).write(c)).coordinates))return b({type:c.type,coordinates:ci(c.coordinates,a)},i)}function li(t){return Array.isArray(t[0])?li(t[0]):isNaN(t[0])}function hi(t,e){return"object"!==m(t[0])?e(t):t.map((function(t){return hi(t,e)}))}function ci(t,e){return"object"!==m(t[0])?e.invert(t):t.map((function(t){return ci(t,e)}))}function fi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return mt(t,(function(t,o,s){var a=e.weight?null==s?void 0:s[e.weight]:void 0;if(!U(a=null==a?1:a))throw new Error("weight value must be a number for feature index "+o);(a=Number(a))>0&&ct(t,(function(t){n+=t[0]*a,r+=t[1]*a,i+=a}))})),I([n/i,r/i],e.properties,e)}function gi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return ct(t,(function(t){n+=t[0],r+=t[1],i++}),!0),I([n/i,r/i],e.properties)}function pi(t,e,n,r,i){var o=r.tolerance||.001,s=0,a=0,u=0,l=0;if(vt(n,(function(e){var n,r=null==(n=e.properties)?void 0:n.weight,i=null==r?1:r;if(!U(i=Number(i)))throw new Error("weight value must be a number");if(i>0){l+=1;var o=i*ut(e,t);0===o&&(o=1);var h=i/o;s+=e.geometry.coordinates[0]*h,a+=e.geometry.coordinates[1]*h,u+=h}})),l<1)throw new Error("no features to measure");var h=s/u,c=a/u;return 1===l||0===i||Math.abs(h-e[0])0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mi;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function mi(t,e){return te?1:0}var _i,xi,Ei,ki,bi,wi=_n(Object.freeze({__proto__:null,default:yi})),Ii={exports:{}};function Ni(){if(bi)return Ii.exports;bi=1;var t=(xi||(xi=1,_i=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=(r-n)/2,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),_i),e=(ki||(ki=1,Ei=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=r-n,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),Ei);return Ii.exports=function(n,r,i,o){return r.length>0&&Array.isArray(r[0])?e(n,r,i,o):t(n,r,i,o)},Ii.exports.nested=e,Ii.exports.flat=t,Ii.exports}var Si,Mi,Li={exports:{}};Li.exports;function Pi(){return Si||(Si=1,function(t,e){!function(t){var e=134217729,n=33306690738754706e-32;function r(t,e,n,r,i){var o,s,a,u,l=e[0],h=r[0],c=0,f=0;h>l==h>-l?(o=l,l=e[++c]):(o=h,h=r[++f]);var g=0;if(cl==h>-l?(a=o-((s=l+o)-l),l=e[++c]):(a=o-((s=h+o)-h),h=r[++f]),o=s,0!==a&&(i[g++]=a);cl==h>-l?(a=o-((s=o+l)-(u=s-o))+(l-u),l=e[++c]):(a=o-((s=o+h)-(u=s-o))+(h-u),h=r[++f]),o=s,0!==a&&(i[g++]=a);for(;c0!=m>0)return _;var x=Math.abs(y+m);return Math.abs(_)>=o*x?_:-function(t,i,o,g,p,v,d){var y,m,_,x,E,k,b,w,I,N,S,M,L,P,C,T,O,R,A=t-p,D=o-p,F=i-v,q=g-v;E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=q-(I=(k=e*q)-(k-q)))-((P=A*q)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=D-(I=(k=e*D)-(k-D)))-((T=F*D)-b*I-w*I-b*N))),u[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),u[1]=L-(S+E)+(E-T),E=(R=M+S)-M,u[2]=M-(R-E)+(S-E),u[3]=R;var V=function(t,e){for(var n=e[0],r=1;r=G||-V>=G)return V;if(y=t-(A+(E=t-A))+(E-p),_=o-(D+(E=o-D))+(E-p),m=i-(F+(E=i-F))+(E-v),x=g-(q+(E=g-q))+(E-v),0===y&&0===m&&0===_&&0===x)return V;if(G=a*d+n*Math.abs(V),(V+=A*x+q*y-(F*_+D*m))>=G||-V>=G)return V;E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=q-(I=(k=e*q)-(k-q)))-((P=y*q)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=D-(I=(k=e*D)-(k-D)))-((T=m*D)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var B=r(4,u,4,f,l);E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=x-(I=(k=e*x)-(k-x)))-((P=A*x)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=_-(I=(k=e*_)-(k-_)))-((T=F*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var Y=r(B,l,4,f,h);E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=x-(I=(k=e*x)-(k-x)))-((P=y*x)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=_-(I=(k=e*_)-(k-_)))-((T=m*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var z=r(Y,h,4,f,c);return c[z-1]}(t,i,g,p,v,d,x)},t.orient2dfast=function(t,e,n,r,i,o){return(e-o)*(n-i)-(t-i)*(r-o)},Object.defineProperty(t,"__esModule",{value:!0})}(e)}(0,Li.exports)),Li.exports}var Ci=function(){if(Mi)return vi.exports;Mi=1;var t=di,e=wi,n=Ni(),r=Pi().orient2d;function i(e,r,i){r=Math.max(0,void 0===r?2:r),i=i||0;var s=function(t){for(var e=t[0],r=t[0],i=t[0],o=t[0],s=0;si[0]&&(i=a),a[1]o[1]&&(o=a)}var u=[e,r,i,o],l=u.slice();for(s=0;s=2&&h(e[e.length-2],e[e.length-1],t[n])<=0;)e.pop();e.push(t[n])}for(var r=[],i=t.length-1;i>=0;i--){for(;r.length>=2&&h(r[r.length-2],r[r.length-1],t[i])<=0;)r.pop();r.push(t[i])}return r.pop(),e.pop(),e.concat(r)}(l)}(e),a=new t(16);a.toBBox=function(t){return{minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]}},a.compareMinX=function(t,e){return t[0]-e[0]},a.compareMinY=function(t,e){return t[1]-e[1]},a.load(e);for(var u,l=[],p=0;pu||c.push({node:v,dist:d})}for(;c.length&&!c.peek().node.children;){var y=c.pop(),m=y.node,_=p(m,n,r),x=p(m,i,o);if(y.dist<_&&y.dist=e.minX&&t[0]<=e.maxX&&t[1]>=e.minY&&t[1]<=e.maxY}function l(t,e,n){for(var r,i,o,s,a=Math.min(t[0],e[0]),u=Math.min(t[1],e[1]),l=Math.max(t[0],e[0]),c=Math.max(t[1],e[1]),f=n.search({minX:a,minY:u,maxX:l,maxY:c}),g=0;g0!=h(r,i,s)>0&&h(o,s,r)>0!=h(o,s,i)>0)return!1;return!0}function h(t,e,n){return r(t[0],t[1],e[0],e[1],n[0],n[1])}function c(t){var e=t.p,n=t.next.p;return t.minX=Math.min(e[0],n[0]),t.minY=Math.min(e[1],n[1]),t.maxX=Math.max(e[0],n[0]),t.maxY=Math.max(e[1],n[1]),t}function f(t,e){var n={p:t,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return e?(n.next=e.next,n.prev=e,e.next.prev=n,e.next=n):(n.prev=n,n.next=n),n}function g(t,e){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function p(t,e,n){var r=e[0],i=e[1],o=n[0]-r,s=n[1]-i;if(0!==o||0!==s){var a=((t[0]-r)*o+(t[1]-i)*s)/(o*o+s*s);a>1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function v(t,e,n,r,i,o,s,a){var u,l,h,c,f=n-t,g=r-e,p=s-i,v=a-o,d=t-i,y=e-o,m=f*f+g*g,_=f*p+g*v,x=p*p+v*v,E=f*d+g*y,k=p*d+v*y,b=m*x-_*_,w=b,I=b;0===b?(l=0,w=1,c=k,I=x):(c=m*k-_*E,(l=_*k-x*E)<0?(l=0,c=k,I=x):l>w&&(l=w,c=k+_,I=x)),c<0?(c=0,-E<0?l=0:-E>m?l=w:(l=-E,w=m)):c>I&&(c=I,-E+_<0?l=0:-E+_>m?l=w:(l=-E+_,w=m));var N=(1-(h=0===c?0:c/I))*i+h*s-((1-(u=0===l?0:l/w))*t+u*n),S=(1-h)*o+h*a-((1-u)*e+u*r);return N*N+S*S}function d(t,e){return t[0]===e[0]?t[1]-e[1]:t[0]-e[0]}return e.default&&(e=e.default),vi.exports=i,vi.exports.default=i,vi.exports}(),Ti=mn(Ci);function Oi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e.concavity=e.concavity||1/0;var n=[];if(ct(t,(function(t){n.push([t[0],t[1]])})),!n.length)return null;var r=Ti(n,e.concavity);return r.length>3?S([r]):null}function Ri(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.steps||64,i=n.properties?n.properties:!Array.isArray(t)&&"Feature"===t.type&&t.properties?t.properties:{},o=[],s=0;s0;r.length0;){var a=t[Math.floor(Math.random()*o)],u=s?a.join("_"):""+a;n[u]||(n[u]=!0,r.push(a))}if(r.length0,u=t[Math.floor(Math.random()*s)];for(a&&u.join("_"),o.push(u);o.length0,y=[];if(s)u="kmrand"==s?r(t,e):"kmpp"==s?i(t,e):s;else for(var m={};u.lengthc&&(c=t[a].y);var g,p=l-u,v=c-h,d=p>v?p:v,y=.5*(l+u),m=.5*(c+h),_=[new so({__sentinel:!0,x:y-20*d,y:m-d},{__sentinel:!0,x:y,y:m+20*d},{__sentinel:!0,x:y+20*d,y:m-d})],x=[],E=[];a=t.length;for(;a--;){for(E.length=0,g=_.length;g--;)(p=t[a].x-_[g].x)>0&&p*p>_[g].r?(x.push(_[g]),_.splice(g,1)):p*p+(v=t[a].y-_[g].y)*v>_[g].r||(E.push(_[g].a,_[g].b,_[g].b,_[g].c,_[g].c,_[g].a),_.splice(g,1));for(uo(E),g=E.length;g;)n=E[--g],e=E[--g],r=t[a],i=n.x-e.x,o=n.y-e.y,s=2*(i*(r.y-n.y)-o*(r.x-n.x)),Math.abs(s)>f&&_.push(new so(e,n,r))}Array.prototype.push.apply(x,_),a=x.length;for(;a--;)(x[a].a.__sentinel||x[a].b.__sentinel||x[a].c.__sentinel)&&x.splice(a,1);return x}(t.features.map((function(t){var r={x:t.geometry.coordinates[0],y:t.geometry.coordinates[1]};return e?r.z=t.properties[e]:3===t.geometry.coordinates.length&&(n=!0,r.z=t.geometry.coordinates[2]),r}))).map((function(t){var e=[t.a.x,t.a.y],r=[t.b.x,t.b.y],i=[t.c.x,t.c.y],o={};return n?(e.push(t.a.z),r.push(t.b.z),i.push(t.c.z)):o={a:t.a.z,b:t.b.z,c:t.c.z},S([[e,r,i,e]],o)})))}var so=s((function t(e,n,r){i(this,t),this.a=e,this.b=n,this.c=r;var o,s,a=n.x-e.x,u=n.y-e.y,l=r.x-e.x,h=r.y-e.y,c=a*(e.x+n.x)+u*(e.y+n.y),f=l*(e.x+r.x)+h*(e.y+r.y),g=2*(a*(r.y-n.y)-u*(r.x-n.x));this.x=(h*c-u*f)/g,this.y=(a*f-l*c)/g,o=this.x-e.x,s=this.y-e.y,this.r=o*o+s*s}));function ao(t,e){return e.x-t.x}function uo(t){var e,n,r,i,o,s=t.length;t:for(;s;)for(n=t[--s],e=t[--s],r=s;r;)if(o=t[--r],e===(i=t[--r])&&n===o||e===o&&n===i){t.splice(s,2),t.splice(r,2),s-=2;continue t}}function lo(t){return t}function ho(t,e){var n=function(t){if(null==t)return lo;var e,n,r=t.scale[0],i=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,a){a||(e=n=0);var u=2,l=t.length,h=new Array(l);for(h[0]=(e+=t[0])*r+o,h[1]=(n+=t[1])*i+s;u1)for(var o,a,u=1,l=s(i[0]);ul&&(a=i[0],i[0]=i[u],i[u]=a,l=o);return i})).filter((function(t){return t.length>0}))}}var po=Object.prototype.hasOwnProperty;function vo(t,e,n,r,i,o){3===arguments.length&&(r=o=Array,i=null);for(var s=new r(t=1<=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},maybeSet:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},get:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)break;h=s[l=l+1&u]}return o},keys:function(){for(var t=[],e=0,n=s.length;e>7^xo[2]^xo[3])}function ko(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=function(){for(var t=vo(1.4*o.length,E,k,Int32Array,-1,Int32Array),e=new Int32Array(o.length),n=0,r=o.length;n=0){var o=c[n];i===e&&o===r||i===r&&o===e||(++g,f[n]=1)}else h[n]=e,c[n]=r}}function E(t){return Eo(o[t])}function k(t,e){return yo(o[t],o[e])}l=h=c=null;var b,w=function(t,e,n,r,i){3===arguments.length&&(r=Array,i=null);for(var o=new r(t=1<=t)throw new Error("full hashset");u=o[a=a+1&s]}return o[a]=r,!0},has:function(r){for(var a=e(r)&s,u=o[a],l=0;u!=i;){if(n(u,r))return!0;if(++l>=t)break;u=o[a=a+1&s]}return!1},values:function(){for(var t=[],e=0,n=o.length;e>1);er&&(r=o),si&&(i=s)}function u(t){t.forEach(a)}function l(t){t.forEach(u)}for(var h in t)o(t[h]);return r>=e&&i>=n?[e,n,r,i]:void 0}(t=Io(t)),r=function(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=s.length+a.length;for(delete t.lines,delete t.rings,r=0,i=s.length;r1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=[],i=It(t,(function(t,e){var n=function(t,e){var n,r=t.geometry.coordinates,i=e.geometry.coordinates,o=Oo(r[0]),s=Oo(r[r.length-1]),a=Oo(i[0]),u=Oo(i[i.length-1]);if(o===u)n=i.concat(r.slice(1));else if(a===s)n=r.concat(i.slice(1));else if(o===a)n=r.slice(1).reverse().concat(i);else{if(s!==u)return null;n=r.concat(i.reverse().slice(1))}return L(n)}(t,e);return n||(r.push(t),e)}));return i&&r.push(i),r.length?1===r.length?r[0]:T(r.map((function(t){return t.coordinates}))):null}function Oo(t){return t[0].toString()+","+t[1].toString()}function Ro(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=function(t){var e={};xt(t,(function(t){e[t.geometry.type]=!0}));var n=Object.keys(e);if(1===n.length)return n[0];return null}(t);if(!r)throw new Error("geojson must be homogenous");var i=t;switch(r){case"LineString":return To(i,e);case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==e.mutate&&void 0!==e.mutate||(t=Ai(t));var n=[];xt(t,(function(t){n.push(t.geometry)}));var r=Lo({geoms:A(n).geometry});return fo(r,r.objects.geoms.geometries)}(i,e);default:throw new Error(r+" is not supported")}}var Ao=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Do=Math.ceil,Fo=Math.floor,qo="[BigNumber Error] ",Vo=qo+"Number primitive has more than 15 significant digits: ",Go=1e14,Bo=14,Yo=9007199254740991,zo=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Xo=1e9;function Uo(t){var e=0|t;return t>0||t===e?e:e-1}function Zo(t){for(var e,n,r=1,i=t.length,o=t[0]+"";rl^n?1:-1;for(a=(u=i.length)<(l=o.length)?u:l,s=0;so[s]^n?1:-1;return u==l?0:u>l^n?1:-1}function Wo(t,e,n,r){if(tn||t!==Fo(t))throw Error(qo+(r||"Argument")+("number"==typeof t?tn?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Jo(t){var e=t.c.length-1;return Uo(t.e/Bo)==e&&t.c[e]%2!=0}function Ko(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Qo(t,e,n){var r,i;if(e<0){for(i=n+".";++e;i+=n);t=i+t}else if(++e>(r=t.length)){for(i=n,e-=r;--e;i+=n);t+=i}else ex?f.c=f.e=null:t.e<_?f.c=[f.e=0]:(f.e=t.e,f.c=t.c.slice()));if((l="number"==typeof t)&&0*t==0){if(f.s=1/t<0?(t=-t,-1):1,t===~~t){for(a=0,u=t;u>=10;u/=10,a++);return void(a>x?f.c=f.e=null:(f.e=a,f.c=[t]))}c=String(t)}else{if(!Ao.test(c=String(t)))return i(f,c,l);f.s=45==c.charCodeAt(0)?(c=c.slice(1),-1):1}(a=c.indexOf("."))>-1&&(c=c.replace(".","")),(u=c.search(/e/i))>0?(a<0&&(a=u),a+=+c.slice(u+1),c=c.substring(0,u)):a<0&&(a=c.length)}else{if(Wo(e,2,I.length,"Base"),10==e&&N)return C(f=new S(t),p+f.e+1,v);if(c=String(t),l="number"==typeof t){if(0*t!=0)return i(f,c,l,e);if(f.s=1/t<0?(c=c.slice(1),-1):1,S.DEBUG&&c.replace(/^0\.0*|\./,"").length>15)throw Error(Vo+t)}else f.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1;for(n=I.slice(0,e),a=u=0,h=c.length;ua){a=h;continue}}else if(!s&&(c==c.toUpperCase()&&(c=c.toLowerCase())||c==c.toLowerCase()&&(c=c.toUpperCase()))){s=!0,u=-1,a=0;continue}return i(f,String(t),l,e)}l=!1,(a=(c=r(c,e,10,f.s)).indexOf("."))>-1?c=c.replace(".",""):a=c.length}for(u=0;48===c.charCodeAt(u);u++);for(h=c.length;48===c.charCodeAt(--h););if(c=c.slice(u,++h)){if(h-=u,l&&S.DEBUG&&h>15&&(t>Yo||t!==Fo(t)))throw Error(Vo+f.s*t);if((a=a-u-1)>x)f.c=f.e=null;else if(a<_)f.c=[f.e=0];else{if(f.e=a,f.c=[],u=(a+1)%Bo,a<0&&(u+=Bo),u=y)?Ko(u,s):Qo(u,s,"0");else if(o=(t=C(new S(t),e,n)).e,a=(u=Zo(t.c)).length,1==r||2==r&&(e<=o||o<=d)){for(;aa){if(--e>0)for(u+=".";e--;u+="0");}else if((e+=o-a)>0)for(o+1==a&&(u+=".");e--;u+="0");return t.s<0&&i?"-"+u:u}function L(t,e){for(var n,r,i=1,o=new S(t[0]);i=10;i/=10,r++);return(n=r+n*Bo-1)>x?t.c=t.e=null:n<_?t.c=[t.e=0]:(t.e=n,t.c=e),t}function C(t,e,n,r){var i,o,s,a,u,l,h,c=t.c,f=zo;if(c){t:{for(i=1,a=c[0];a>=10;a/=10,i++);if((o=e-i)<0)o+=Bo,s=e,u=c[l=0],h=Fo(u/f[i-s-1]%10);else if((l=Do((o+1)/Bo))>=c.length){if(!r)break t;for(;c.length<=l;c.push(0));u=h=0,i=1,s=(o%=Bo)-Bo+1}else{for(u=a=c[l],i=1;a>=10;a/=10,i++);h=(s=(o%=Bo)-Bo+i)<0?0:Fo(u/f[i-s-1]%10)}if(r=r||e<0||null!=c[l+1]||(s<0?u:u%f[i-s-1]),r=n<4?(h||r)&&(0==n||n==(t.s<0?3:2)):h>5||5==h&&(4==n||r||6==n&&(o>0?s>0?u/f[i-s]:0:c[l-1])%10&1||n==(t.s<0?8:7)),e<1||!c[0])return c.length=0,r?(e-=t.e+1,c[0]=f[(Bo-e%Bo)%Bo],t.e=-e||0):c[0]=t.e=0,t;if(0==o?(c.length=l,a=1,l--):(c.length=l+1,a=f[Bo-o],c[l]=s>0?Fo(u/f[i-s]%f[s])*a:0),r)for(;;){if(0==l){for(o=1,s=c[0];s>=10;s/=10,o++);for(s=c[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(t.e++,c[0]==Go&&(c[0]=1));break}if(c[l]+=a,c[l]!=Go)break;c[l--]=0,a=1}for(o=c.length;0===c[--o];c.pop());}t.e>x?t.c=t.e=null:t.e<_&&(t.c=[t.e=0])}return t}function T(t){var e,n=t.e;return null===n?t.toString():(e=Zo(t.c),e=n<=d||n>=y?Ko(e,n):Qo(e,n,"0"),t.s<0?"-"+e:e)}return S.clone=t,S.ROUND_UP=0,S.ROUND_DOWN=1,S.ROUND_CEIL=2,S.ROUND_FLOOR=3,S.ROUND_HALF_UP=4,S.ROUND_HALF_DOWN=5,S.ROUND_HALF_EVEN=6,S.ROUND_HALF_CEIL=7,S.ROUND_HALF_FLOOR=8,S.EUCLID=9,S.config=S.set=function(t){var e,n;if(null!=t){if("object"!=m(t))throw Error(qo+"Object expected: "+t);if(t.hasOwnProperty(e="DECIMAL_PLACES")&&(Wo(n=t[e],0,Xo,e),p=n),t.hasOwnProperty(e="ROUNDING_MODE")&&(Wo(n=t[e],0,8,e),v=n),t.hasOwnProperty(e="EXPONENTIAL_AT")&&((n=t[e])&&n.pop?(Wo(n[0],-Xo,0,e),Wo(n[1],0,Xo,e),d=n[0],y=n[1]):(Wo(n,-Xo,Xo,e),d=-(y=n<0?-n:n))),t.hasOwnProperty(e="RANGE"))if((n=t[e])&&n.pop)Wo(n[0],-Xo,-1,e),Wo(n[1],1,Xo,e),_=n[0],x=n[1];else{if(Wo(n,-Xo,Xo,e),!n)throw Error(qo+e+" cannot be zero: "+n);_=-(x=n<0?-n:n)}if(t.hasOwnProperty(e="CRYPTO")){if((n=t[e])!==!!n)throw Error(qo+e+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw E=!n,Error(qo+"crypto unavailable");E=n}else E=n}if(t.hasOwnProperty(e="MODULO_MODE")&&(Wo(n=t[e],0,9,e),k=n),t.hasOwnProperty(e="POW_PRECISION")&&(Wo(n=t[e],0,Xo,e),b=n),t.hasOwnProperty(e="FORMAT")){if("object"!=m(n=t[e]))throw Error(qo+e+" not an object: "+n);w=n}if(t.hasOwnProperty(e="ALPHABET")){if("string"!=typeof(n=t[e])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(qo+e+" invalid: "+n);N="0123456789"==n.slice(0,10),I=n}}return{DECIMAL_PLACES:p,ROUNDING_MODE:v,EXPONENTIAL_AT:[d,y],RANGE:[_,x],CRYPTO:E,MODULO_MODE:k,POW_PRECISION:b,FORMAT:w,ALPHABET:I}},S.isBigNumber=function(t){if(!t||!0!==t._isBigNumber)return!1;if(!S.DEBUG)return!0;var e,n,r=t.c,i=t.e,o=t.s;t:if("[object Array]"=={}.toString.call(r)){if((1===o||-1===o)&&i>=-Xo&&i<=Xo&&i===Fo(i)){if(0===r[0]){if(0===i&&1===r.length)return!0;break t}if((e=(i+1)%Bo)<1&&(e+=Bo),String(r[0]).length==e){for(e=0;e=Go||n!==Fo(n))break t;if(0!==n)return!0}}}else if(null===r&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(qo+"Invalid BigNumber: "+t)},S.maximum=S.max=function(){return L(arguments,-1)},S.minimum=S.min=function(){return L(arguments,1)},S.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Fo(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(t){var e,n,r,i,o,a=0,u=[],l=new S(g);if(null==t?t=p:Wo(t,0,Xo),i=Do(t/Bo),E)if(crypto.getRandomValues){for(e=crypto.getRandomValues(new Uint32Array(i*=2));a>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),e[a]=n[0],e[a+1]=n[1]):(u.push(o%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw E=!1,Error(qo+"crypto unavailable");for(e=crypto.randomBytes(i*=7);a=9e15?crypto.randomBytes(7).copy(e,a):(u.push(o%1e14),a+=7);a=i/7}if(!E)for(;a=10;o/=10,a++);an-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(r,i,o,s,a){var u,l,h,c,f,g,d,y,m=r.indexOf("."),_=p,x=v;for(m>=0&&(c=b,b=0,r=r.replace(".",""),g=(y=new S(i)).pow(r.length-m),b=c,y.c=e(Qo(Zo(g.c),g.e,"0"),10,o,t),y.e=y.c.length),h=c=(d=e(r,i,o,a?(u=I,t):(u=t,I))).length;0==d[--c];d.pop());if(!d[0])return u.charAt(0);if(m<0?--h:(g.c=d,g.e=h,g.s=s,d=(g=n(g,y,_,x,o)).c,f=g.r,h=g.e),m=d[l=h+_+1],c=o/2,f=f||l<0||null!=d[l+1],f=x<4?(null!=m||f)&&(0==x||x==(g.s<0?3:2)):m>c||m==c&&(4==x||f||6==x&&1&d[l-1]||x==(g.s<0?8:7)),l<1||!d[0])r=f?Qo(u.charAt(1),-_,u.charAt(0)):u.charAt(0);else{if(d.length=l,f)for(--o;++d[--l]>o;)d[l]=0,l||(++h,d=[1].concat(d));for(c=d.length;!d[--c];);for(m=0,r="";m<=c;r+=u.charAt(d[m++]));r=Qo(r,h,u.charAt(0))}return r}}(),n=function(){function t(t,e,n){var r,i,o,s,a=0,u=t.length,l=e%jo,h=e/jo|0;for(t=t.slice();u--;)a=((i=l*(o=t[u]%jo)+(r=h*o+(s=t[u]/jo|0)*l)%jo*jo+a)/n|0)+(r/jo|0)+h*s,t[u]=i%n;return a&&(t=[a].concat(t)),t}function e(t,e,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;ie[i]?1:-1;break}return o}function n(t,e,n,r){for(var i=0;n--;)t[n]-=i,i=t[n]1;t.splice(0,1));}return function(r,i,o,s,a){var u,l,h,c,f,g,p,v,d,y,m,_,x,E,k,b,w,I=r.s==i.s?1:-1,N=r.c,M=i.c;if(!(N&&N[0]&&M&&M[0]))return new S(r.s&&i.s&&(N?!M||N[0]!=M[0]:M)?N&&0==N[0]||!M?0*I:I/0:NaN);for(d=(v=new S(I)).c=[],I=o+(l=r.e-i.e)+1,a||(a=Go,l=Uo(r.e/Bo)-Uo(i.e/Bo),I=I/Bo|0),h=0;M[h]==(N[h]||0);h++);if(M[h]>(N[h]||0)&&l--,I<0)d.push(1),c=!0;else{for(E=N.length,b=M.length,h=0,I+=2,(f=Fo(a/(M[0]+1)))>1&&(M=t(M,f,a),N=t(N,f,a),b=M.length,E=N.length),x=b,m=(y=N.slice(0,b)).length;m=a/2&&k++;do{if(f=0,(u=e(M,y,b,m))<0){if(_=y[0],b!=m&&(_=_*a+(y[1]||0)),(f=Fo(_/k))>1)for(f>=a&&(f=a-1),p=(g=t(M,f,a)).length,m=y.length;1==e(g,y,p,m);)f--,n(g,b=10;I/=10,h++);C(v,o+(v.e=h+l*Bo-1)+1,s,c)}else v.e=l,v.r=+c;return v}}(),a=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,l=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,c=/^\s*\+(?=[\w.])|^\s+|\s+$/g,i=function(t,e,n,r){var i,o=n?e:e.replace(c,"");if(h.test(o))t.s=isNaN(o)?null:o<0?-1:1;else{if(!n&&(o=o.replace(a,(function(t,e,n){return i="x"==(n=n.toLowerCase())?16:"b"==n?2:8,r&&r!=i?t:e})),r&&(i=r,o=o.replace(u,"$1").replace(l,"0.$1")),e!=o))return new S(o,i);if(S.DEBUG)throw Error(qo+"Not a"+(r?" base "+r:"")+" number: "+e);t.s=null}t.c=t.e=null},f.absoluteValue=f.abs=function(){var t=new S(this);return t.s<0&&(t.s=1),t},f.comparedTo=function(t,e){return Ho(this,new S(t,e))},f.decimalPlaces=f.dp=function(t,e){var n,r,i,o=this;if(null!=t)return Wo(t,0,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t+o.e+1,e);if(!(n=o.c))return null;if(r=((i=n.length-1)-Uo(this.e/Bo))*Bo,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},f.dividedBy=f.div=function(t,e){return n(this,new S(t,e),p,v)},f.dividedToIntegerBy=f.idiv=function(t,e){return n(this,new S(t,e),0,1)},f.exponentiatedBy=f.pow=function(t,e){var n,r,i,o,s,a,u,l,h=this;if((t=new S(t)).c&&!t.isInteger())throw Error(qo+"Exponent not an integer: "+T(t));if(null!=e&&(e=new S(e)),s=t.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!t.c||!t.c[0])return l=new S(Math.pow(+T(h),s?t.s*(2-Jo(t)):+T(t))),e?l.mod(e):l;if(a=t.s<0,e){if(e.c?!e.c[0]:!e.s)return new S(NaN);(r=!a&&h.isInteger()&&e.isInteger())&&(h=h.mod(e))}else{if(t.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return o=h.s<0&&Jo(t)?-0:0,h.e>-1&&(o=1/o),new S(a?1/o:o);b&&(o=Do(b/Bo+2))}for(s?(n=new S(.5),a&&(t.s=1),u=Jo(t)):u=(i=Math.abs(+T(t)))%2,l=new S(g);;){if(u){if(!(l=l.times(h)).c)break;o?l.c.length>o&&(l.c.length=o):r&&(l=l.mod(e))}if(i){if(0===(i=Fo(i/2)))break;u=i%2}else if(C(t=t.times(n),t.e+1,1),t.e>14)u=Jo(t);else{if(0===(i=+T(t)))break;u=i%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):r&&(h=h.mod(e))}return r?l:(a&&(l=g.div(l)),e?l.mod(e):o?C(l,b,v,undefined):l)},f.integerValue=function(t){var e=new S(this);return null==t?t=v:Wo(t,0,8),C(e,e.e+1,t)},f.isEqualTo=f.eq=function(t,e){return 0===Ho(this,new S(t,e))},f.isFinite=function(){return!!this.c},f.isGreaterThan=f.gt=function(t,e){return Ho(this,new S(t,e))>0},f.isGreaterThanOrEqualTo=f.gte=function(t,e){return 1===(e=Ho(this,new S(t,e)))||0===e},f.isInteger=function(){return!!this.c&&Uo(this.e/Bo)>this.c.length-2},f.isLessThan=f.lt=function(t,e){return Ho(this,new S(t,e))<0},f.isLessThanOrEqualTo=f.lte=function(t,e){return-1===(e=Ho(this,new S(t,e)))||0===e},f.isNaN=function(){return!this.s},f.isNegative=function(){return this.s<0},f.isPositive=function(){return this.s>0},f.isZero=function(){return!!this.c&&0==this.c[0]},f.minus=function(t,e){var n,r,i,o,s=this,a=s.s;if(e=(t=new S(t,e)).s,!a||!e)return new S(NaN);if(a!=e)return t.s=-e,s.plus(t);var u=s.e/Bo,l=t.e/Bo,h=s.c,c=t.c;if(!u||!l){if(!h||!c)return h?(t.s=-e,t):new S(c?s:NaN);if(!h[0]||!c[0])return c[0]?(t.s=-e,t):new S(h[0]?s:3==v?-0:0)}if(u=Uo(u),l=Uo(l),h=h.slice(),a=u-l){for((o=a<0)?(a=-a,i=h):(l=u,i=c),i.reverse(),e=a;e--;i.push(0));i.reverse()}else for(r=(o=(a=h.length)<(e=c.length))?a:e,a=e=0;e0)for(;e--;h[n++]=0);for(e=Go-1;r>a;){if(h[--r]=0;){for(n=0,f=_[i]%d,g=_[i]/d|0,o=i+(s=u);o>i;)n=((l=f*(l=m[--s]%d)+(a=g*l+(h=m[s]/d|0)*f)%d*d+p[o]+n)/v|0)+(a/d|0)+g*h,p[o--]=l%v;p[o]=n}return n?++r:p.splice(0,1),P(t,p,r)},f.negated=function(){var t=new S(this);return t.s=-t.s||null,t},f.plus=function(t,e){var n,r=this,i=r.s;if(e=(t=new S(t,e)).s,!i||!e)return new S(NaN);if(i!=e)return t.s=-e,r.minus(t);var o=r.e/Bo,s=t.e/Bo,a=r.c,u=t.c;if(!o||!s){if(!a||!u)return new S(i/0);if(!a[0]||!u[0])return u[0]?t:new S(a[0]?r:0*i)}if(o=Uo(o),s=Uo(s),a=a.slice(),i=o-s){for(i>0?(s=o,n=u):(i=-i,n=a),n.reverse();i--;n.push(0));n.reverse()}for((i=a.length)-(e=u.length)<0&&(n=u,u=a,a=n,e=i),i=0;e;)i=(a[--e]=a[e]+u[e]+i)/Go|0,a[e]=Go===a[e]?0:a[e]%Go;return i&&(a=[i].concat(a),++s),P(t,a,s)},f.precision=f.sd=function(t,e){var n,r,i,o=this;if(null!=t&&t!==!!t)return Wo(t,1,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t,e);if(!(n=o.c))return null;if(r=(i=n.length-1)*Bo+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return t&&o.e+1>r&&(r=o.e+1),r},f.shiftedBy=function(t){return Wo(t,-9007199254740991,Yo),this.times("1e"+t)},f.squareRoot=f.sqrt=function(){var t,e,r,i,o,s=this,a=s.c,u=s.s,l=s.e,h=p+4,c=new S("0.5");if(1!==u||!a||!a[0])return new S(!u||u<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(u=Math.sqrt(+T(s)))||u==1/0?(((e=Zo(a)).length+l)%2==0&&(e+="0"),u=Math.sqrt(+e),l=Uo((l+1)/2)-(l<0||l%2),r=new S(e=u==1/0?"5e"+l:(e=u.toExponential()).slice(0,e.indexOf("e")+1)+l)):r=new S(u+""),r.c[0])for((u=(l=r.e)+h)<3&&(u=0);;)if(o=r,r=c.times(o.plus(n(s,o,h,1))),Zo(o.c).slice(0,u)===(e=Zo(r.c)).slice(0,u)){if(r.e0&&p>0){for(o=p%a||a,h=g.substr(0,o);o0&&(h+=l+g.slice(o)),f&&(h="-"+h)}r=c?h+(n.decimalSeparator||"")+((u=+n.fractionGroupSize)?c.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):c):h}return(n.prefix||"")+r+(n.suffix||"")},f.toFraction=function(t){var e,r,i,o,s,a,u,l,h,c,f,p,d=this,y=d.c;if(null!=t&&(!(u=new S(t)).isInteger()&&(u.c||1!==u.s)||u.lt(g)))throw Error(qo+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+T(u));if(!y)return new S(d);for(e=new S(g),h=r=new S(g),i=l=new S(g),p=Zo(y),s=e.e=p.length-d.e-1,e.c[0]=zo[(a=s%Bo)<0?Bo+a:a],t=!t||u.comparedTo(e)>0?s>0?e:h:u,a=x,x=1/0,u=new S(p),l.c[0]=0;c=n(u,e,0,1),1!=(o=r.plus(c.times(i))).comparedTo(t);)r=i,i=o,h=l.plus(c.times(o=h)),l=o,e=u.minus(c.times(o=e)),u=o;return o=n(t.minus(r),i,0,1),l=l.plus(o.times(h)),r=r.plus(o.times(i)),l.s=h.s=d.s,f=n(h,i,s*=2,v).minus(d).abs().comparedTo(n(l,r,s,v).minus(d).abs())<1?[h,i]:[l,r],x=a,f},f.toNumber=function(){return+T(this)},f.toPrecision=function(t,e){return null!=t&&Wo(t,1,Xo),M(this,t,e,2)},f.toString=function(t){var e,n=this,i=n.s,o=n.e;return null===o?i?(e="Infinity",i<0&&(e="-"+e)):e="NaN":(null==t?e=o<=d||o>=y?Ko(Zo(n.c),o):Qo(Zo(n.c),o,"0"):10===t&&N?e=Qo(Zo((n=C(new S(n),p+o+1,v)).c),n.e,"0"):(Wo(t,2,I.length,"Base"),e=r(Qo(Zo(n.c),o,"0"),10,t,i,!0)),i<0&&n.c[0]&&(e="-"+e)),e},f.valueOf=f.toJSON=function(){return T(this)},f._isBigNumber=!0,f[Symbol.toStringTag]="BigNumber",f[Symbol.for("nodejs.util.inspect.custom")]=f.valueOf,null!=e&&S.set(e),S}(),ts=function(t){function e(t){return i(this,e),r(this,e,[t])}return h(e,t),s(e)}(s((function t(e){i(this,t),u(this,"key",void 0),u(this,"left",null),u(this,"right",null),this.key=e}))),es=function(){return s((function t(){i(this,t),u(this,"size",0),u(this,"modificationCount",0),u(this,"splayCount",0)}),[{key:"splay",value:function(t){var e=this.root;if(null==e)return this.compare(t,t),-1;for(var n,r=null,i=null,o=null,s=null,a=e,u=this.compare;;)if((n=u(a.key,t))>0){var l=a.left;if(null==l)break;if((n=u(l.key,t))>0&&(a.left=l.right,l.right=a,null==(l=(a=l).left)))break;null==r?i=a:r.left=a,r=a,a=l}else{if(!(n<0))break;var h=a.right;if(null==h)break;if((n=u(h.key,t))<0&&(a.right=h.left,h.left=a,null==(h=(a=h).right)))break;null==o?s=a:o.right=a,o=a,a=h}return null!=o&&(o.right=a.left,a.left=s),null!=r&&(r.left=a.right,a.right=i),this.root!==a&&(this.root=a,this.splayCount++),n}},{key:"splayMin",value:function(t){for(var e=t,n=e.left;null!=n;){var r=n;e.left=r.right,r.right=e,n=(e=r).left}return e}},{key:"splayMax",value:function(t){for(var e=t,n=e.right;null!=n;){var r=n;e.right=r.left,r.left=e,n=(e=r).right}return e}},{key:"_delete",value:function(t){if(null==this.root)return null;if(0!=this.splay(t))return null;var e=this.root,n=e,r=e.left;if(this.size--,null==r)this.root=e.right;else{var i=e.right;(e=this.splayMax(r)).right=i,this.root=e}return this.modificationCount++,n}},{key:"addNewRoot",value:function(t,e){this.size++,this.modificationCount++;var n=this.root;null!=n?(e<0?(t.left=n,t.right=n.right,n.right=null):(t.right=n,t.left=n.left,n.left=null),this.root=t):this.root=t}},{key:"_first",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMin(t),this.root)}},{key:"_last",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMax(t),this.root)}},{key:"clear",value:function(){this.root=null,this.size=0,this.modificationCount++}},{key:"has",value:function(t){return this.validKey(t)&&0==this.splay(t)}},{key:"defaultCompare",value:function(){return function(t,e){return te?1:0}}},{key:"wrap",value:function(){var t=this;return{getRoot:function(){return t.root},setRoot:function(e){t.root=e},getSize:function(){return t.size},getModificationCount:function(){return t.modificationCount},getSplayCount:function(){return t.splayCount},setSplayCount:function(e){t.splayCount=e},splay:function(e){return t.splay(e)},has:function(e){return t.has(e)}}}}])}(),ns=function(t){function e(t,n){var o;return i(this,e),u(o=r(this,e),"root",null),u(o,"compare",void 0),u(o,"validKey",void 0),u(o,Symbol.toStringTag,"[object Set]"),o.compare=null!=t?t:o.defaultCompare(),o.validKey=null!=n?n:function(t){return null!=t&&null!=t},o}return h(e,t),s(e,[{key:"delete",value:function(t){return!!this.validKey(t)&&null!=this._delete(t)}},{key:"deleteAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.delete(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"forEach",value:function(t){for(var e,n=this[Symbol.iterator]();!(e=n.next()).done;)t(e.value,e.value,this)}},{key:"add",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this}},{key:"addAndReturn",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this.root.key}},{key:"addAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.add(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"isEmpty",value:function(){return null==this.root}},{key:"isNotEmpty",value:function(){return null!=this.root}},{key:"single",value:function(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}},{key:"first",value:function(){if(0==this.size)throw"Bad state: No element";return this._first().key}},{key:"last",value:function(){if(0==this.size)throw"Bad state: No element";return this._last().key}},{key:"lastBefore",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)<0)return this.root.key;var e=this.root.left;if(null==e)return null;for(var n=e.right;null!=n;)n=(e=n).right;return e.key}},{key:"firstAfter",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)>0)return this.root.key;var e=this.root.right;if(null==e)return null;for(var n=e.left;null!=n;)n=(e=n).left;return e.key}},{key:"retainAll",value:function(t){var n,r=new e(this.compare,this.validKey),i=this.modificationCount,o=a(t);try{for(o.s();!(n=o.n()).done;){var s=n.value;if(i!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(s)&&0==this.splay(s)&&r.add(this.root.key)}}catch(t){o.e(t)}finally{o.f()}r.size!=this.size&&(this.root=r.root,this.size=r.size,this.modificationCount++)}},{key:"lookup",value:function(t){return this.validKey(t)?0!=this.splay(t)?null:this.root.key:null}},{key:"intersection",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)&&r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"difference",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)||r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"union",value:function(t){var e=this.clone();return e.addAll(t),e}},{key:"clone",value:function(){var t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}},{key:"copyNode",value:function(t){if(null==t)return null;var e=new ts(t.key);return function t(e,n){var r,i;do{if(r=e.left,i=e.right,null!=r){var o=new ts(r.key);n.left=o,t(r,o)}if(null!=i){var s=new ts(i.key);n.right=s,e=i,n=s}}while(null!=i)}(t,e),e}},{key:"toSet",value:function(){return this.clone()}},{key:"entries",value:function(){return new os(this.wrap())}},{key:"keys",value:function(){return this[Symbol.iterator]()}},{key:"values",value:function(){return this[Symbol.iterator]()}},{key:Symbol.iterator,value:function(){return new is(this.wrap())}}])}(es),rs=function(){return s((function t(e){i(this,t),u(this,"tree",void 0),u(this,"path",new Array),u(this,"modificationCount",null),u(this,"splayCount",void 0),this.tree=e,this.splayCount=e.getSplayCount()}),[{key:Symbol.iterator,value:function(){return this}},{key:"next",value:function(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}},{key:"current",value:function(){if(!this.path.length)return null;var t=this.path[this.path.length-1];return this.getValue(t)}},{key:"rebuildPath",value:function(t){this.path.splice(0,this.path.length),this.tree.splay(t),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}},{key:"findLeftMostDescendent",value:function(t){for(;null!=t;)this.path.push(t),t=t.left}},{key:"moveNext",value:function(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();for(var t=this.tree.getRoot();null!=t;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);var e=this.path[this.path.length-1],n=e.right;if(null!=n){for(;null!=n;)this.path.push(n),n=n.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}}])}(),is=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return t.key}}])}(rs),os=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return[t.key,t.key]}}])}(rs),ss=function(t){return function(){return t}},as=function(t){var e=t?function(e,n){return n.minus(e).abs().isLessThanOrEqualTo(t)}:ss(!1);return function(t,n){return e(t,n)?0:t.comparedTo(n)}};function us(t){var e=t?function(e,n,r,i,o){return e.exponentiatedBy(2).isLessThanOrEqualTo(i.minus(n).exponentiatedBy(2).plus(o.minus(r).exponentiatedBy(2)).times(t))}:ss(!1);return function(t,n,r){var i=t.x,o=t.y,s=r.x,a=r.y,u=o.minus(a).times(n.x.minus(s)).minus(i.minus(s).times(n.y.minus(a)));return e(u,i,o,s,a)?0:u.comparedTo(0)}}var ls=function(t){return t},hs=function(t){if(t){var e=new ns(as(t)),n=new ns(as(t)),r=function(t,e){return e.addAndReturn(t)},i=function(t){return{x:r(t.x,e),y:r(t.y,n)}};return i({x:new $o(0),y:new $o(0)}),i}return ls},cs=function(t){return{set:function(t){fs=cs(t)},reset:function(){return cs(t)},compare:as(t),snap:hs(t),orient:us(t)}},fs=cs(),gs=function(t,e){return t.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(t.ur.x)&&t.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(t.ur.y)},ps=function(t,e){if(e.ur.x.isLessThan(t.ll.x)||t.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(t.ll.y)||t.ur.y.isLessThan(e.ll.y))return null;var n=t.ll.x.isLessThan(e.ll.x)?e.ll.x:t.ll.x,r=t.ur.x.isLessThan(e.ur.x)?t.ur.x:e.ur.x;return{ll:{x:n,y:t.ll.y.isLessThan(e.ll.y)?e.ll.y:t.ll.y},ur:{x:r,y:t.ur.y.isLessThan(e.ur.y)?t.ur.y:e.ur.y}}},vs=function(t,e){return t.x.times(e.y).minus(t.y.times(e.x))},ds=function(t,e){return t.x.times(e.x).plus(t.y.times(e.y))},ys=function(t){return ds(t,t).sqrt()},ms=function(t,e,n){var r={x:e.x.minus(t.x),y:e.y.minus(t.y)},i={x:n.x.minus(t.x),y:n.y.minus(t.y)};return ds(i,r).div(ys(i)).div(ys(r))},_s=function(t,e,n){return e.y.isZero()?null:{x:t.x.plus(e.x.div(e.y).times(n.minus(t.y))),y:n}},xs=function(t,e,n){return e.x.isZero()?null:{x:n,y:t.y.plus(e.y.div(e.x).times(n.minus(t.x)))}},Es=function(){function t(e,n){i(this,t),u(this,"point",void 0),u(this,"isLeft",void 0),u(this,"segment",void 0),u(this,"otherSE",void 0),u(this,"consumedBy",void 0),void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}return s(t,[{key:"link",value:function(t){if(t.point===this.point)throw new Error("Tried to link already linked events");for(var e=t.point.events,n=0,r=e.length;n0&&(t=r)}for(var i=t.segment.prevInResult(),o=i?i.prevInResult():null;;){if(!i)return null;if(!o)return i.ringOut;var s,a;if(o.ringOut!==i.ringOut)return(null===(s=o.ringOut)||void 0===s?void 0:s.enclosingRing())!==i.ringOut?i.ringOut:null===(a=i.ringOut)||void 0===a?void 0:a.enclosingRing();i=o.prevInResult(),o=i?i.prevInResult():null}}}],[{key:"factory",value:function(e){for(var n=[],r=0,i=e.length;r1&&void 0!==arguments[1]?arguments[1]:Ls.compare;i(this,t),u(this,"queue",void 0),u(this,"tree",void 0),u(this,"segments",void 0),this.queue=e,this.tree=new ns(n),this.segments=[]}),[{key:"process",value:function(t){var e=t.segment,n=[];if(t.consumedBy)return t.isLeft?this.queue.delete(t.otherSE):this.tree.delete(e),n;t.isLeft&&this.tree.add(e);var r=e,i=e;do{r=this.tree.lastBefore(r)}while(null!=r&&null!=r.consumedBy);do{i=this.tree.firstAfter(i)}while(null!=i&&null!=i.consumedBy);if(t.isLeft){var o=null;if(r){var s=r.getIntersection(e);if(null!==s&&(e.isAnEndpoint(s)||(o=s),!r.isAnEndpoint(s)))for(var a=this._splitSafely(r,s),u=0,l=a.length;u0?(this.tree.delete(e),n.push(t)):(this.segments.push(e),e.prev=r)}else{if(r&&i){var _=r.getIntersection(i);if(null!==_){if(!r.isAnEndpoint(_))for(var x=this._splitSafely(r,_),E=0,k=x.length;E0&&a.swapEvents(),Es.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}},{key:"swapEvents",value:function(){var t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(var e=0,n=this.windings.length;e0){var o=n;n=r,r=o}if(n.prev===r){var s=n;n=r,r=s}for(var a=0,u=r.rings.length;a0)return-1;var c=e.comparePoint(t.rightSE.point);return 0!==c?c:-1}if(n.isGreaterThan(r)){if(s.isLessThan(a)&&s.isLessThan(l))return-1;if(s.isGreaterThan(a)&&s.isGreaterThan(l))return 1;var f=e.comparePoint(t.leftSE.point);if(0!==f)return f;var g=t.comparePoint(e.rightSE.point);return g<0?1:g>0?-1:1}if(s.isLessThan(a))return-1;if(s.isGreaterThan(a))return 1;if(i.isLessThan(o)){var p=e.comparePoint(t.rightSE.point);if(0!==p)return p}if(i.isGreaterThan(o)){var v=t.comparePoint(e.rightSE.point);if(v<0)return 1;if(v>0)return-1}if(!i.eq(o)){var d=u.minus(s),y=i.minus(n),m=l.minus(a),_=o.minus(r);if(d.isGreaterThan(y)&&m.isLessThan(_))return 1;if(d.isLessThan(y)&&m.isGreaterThan(_))return-1}return i.isGreaterThan(o)?1:i.isLessThan(o)||u.isLessThan(l)?-1:u.isGreaterThan(l)?1:t.ide.id?1:0}},{key:"fromRing",value:function(e,n,r){var i,o,s,a=Es.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else{if(!(a>0))throw new Error("Tried to create degenerate segment at [".concat(e.x,", ").concat(e.y,"]"));i=n,o=e,s=-1}return new t(new Es(i,!0),new Es(o,!1),[r],[s])}}])}(),Ps=function(){return s((function t(e,n,r){if(i(this,t),u(this,"poly",void 0),u(this,"isExterior",void 0),u(this,"segments",void 0),u(this,"bbox",void 0),!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");var o=fs.snap({x:new $o(e[0][0]),y:new $o(e[0][1])});this.bbox={ll:{x:o.x,y:o.y},ur:{x:o.x,y:o.y}};for(var s=o,a=1,l=e.length;a1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r2&&void 0!==arguments[2]?arguments[2]:2,r=K(t),i=K(e),o=r[0]-i[0],s=r[1]-i[1];return 1===n?Math.abs(o)+Math.abs(s):Math.pow(Math.pow(o,n)+Math.pow(s,n),1/n)}function Gs(t,e){var n,r,i=(e=e||{}).threshold||1e4,o=e.p||2,s=null!=(n=e.binary)&&n,a=e.alpha||-1,u=null!=(r=e.standardization)&&r,l=[];vt(t,(function(t){l.push(gi(t))}));for(var h=[],c=0;c3&&void 0!==arguments[3]?arguments[3]:{},i=e<0,o=j(Math.abs(e),r.units,"meters");i&&(o=-Math.abs(o));var s=K(t),a=function(t,e,n,r){r=void 0===r?x:Number(r);var i=e/r,o=t[0]*Math.PI/180,s=z(t[1]),a=z(n),u=i*Math.cos(a),l=s+u;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);var h=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),c=Math.abs(h)>1e-11?u/h:Math.cos(s),f=i*Math.sin(a)/c;return[(180*(o+f)/Math.PI+540)%360-180,180*l/Math.PI]}(s,o,n);return a[0]+=a[0]-s[0]>180?-360:s[0]-a[0]>180?360:0,I(a,r.properties)}function Ys(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e);i[0]+=i[0]-r[0]>180?-360:r[0]-i[0]>180?360:0;var o=function(t,e,n){var r=n=void 0===n?x:Number(n),i=t[1]*Math.PI/180,o=e[1]*Math.PI/180,s=o-i,a=Math.abs(e[0]-t[0])*Math.PI/180;a>Math.PI&&(a-=2*Math.PI);var u=Math.log(Math.tan(o/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),l=Math.abs(u)>1e-11?s/u:Math.cos(i);return Math.sqrt(s*s+l*l*a*a)*r}(r,i);return j(o,"meters",n.units)}function zs(t,e,n){if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.pivot,i=n.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("angle is required");if(0===e)return t;var o=null!=r?r:gi(t);return!1!==i&&void 0!==i||(t=Ai(t)),ct(t,(function(t){var n=lt(o,t)+e,r=Ys(o,t),i=Q(Bs(o,r,n));t[0]=i[0],t[1]=i[1]})),t}function js(t,e,n,r){var i=(r=r||{}).steps||64,o=r.units||"kilometers",s=r.angle||0,a=r.pivot||t,u=r.properties||{};if(!t)throw new Error("center is required");if(!e)throw new Error("xSemiAxis is required");if(!n)throw new Error("ySemiAxis is required");if(!Z(r))throw new Error("options must be an object");if(!U(i))throw new Error("steps must be a number");if(!U(s))throw new Error("angle must be a number");var l=K(t);if("degrees"!==o){var h=Bs(t,e,90,{units:o}),c=Bs(t,n,0,{units:o});e=K(h)[0]-l[0],n=K(c)[1]-l[1]}for(var f=[],g=0;g=-270&&(v=-v),p<-180&&p>=-360&&(d=-d),"degrees"===o){var y=z(s),m=v*Math.cos(y)+d*Math.sin(y),_=d*Math.cos(y)-v*Math.sin(y);v=m,d=_}f.push([v+l[0],d+l[1]])}return f.push(f[0]),"degrees"===o?S([f],u):zs(S([f],u),s,{pivot:a})}function Xs(t){var e=t*Math.PI/180;return Math.tan(e)}function Us(t){return Vt(Rt(t))}function Zs(t){var e=[];return"FeatureCollection"===t.type?vt(t,(function(t){ct(t,(function(n){e.push(I(n,t.properties))}))})):"Feature"===t.type?ct(t,(function(n){e.push(I(n,t.properties))})):ct(t,(function(t){e.push(I(t))})),C(e)}var Hs=Math.PI/180,Ws=180/Math.PI,Js=function(t,e){this.lon=t,this.lat=e,this.x=Hs*t,this.y=Hs*e};Js.prototype.view=function(){return String(this.lon).slice(0,4)+","+String(this.lat).slice(0,4)},Js.prototype.antipode=function(){var t=-1*this.lat,e=this.lon<0?180+this.lon:-1*(180-this.lon);return new Js(e,t)};var Ks=function(){this.coords=[],this.length=0};Ks.prototype.move_to=function(t){this.length++,this.coords.push(t)};var Qs=function(t){this.properties=t||{},this.geometries=[]};Qs.prototype.json=function(){if(this.geometries.length<=0)return{geometry:{type:"LineString",coordinates:null},type:"Feature",properties:this.properties};if(1===this.geometries.length)return{geometry:{type:"LineString",coordinates:this.geometries[0].coords},type:"Feature",properties:this.properties};for(var t=[],e=0;e1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must specify at least 2 geometries");var r=Rs.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)}function ea(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.stringify(n.properties||{}),i=v(t,4),o=i[0],s=i[1],a=i[2],u=i[3],l=(s+u)/2,h=(o+a)/2,c=2*e/ut([o,l],[a,l],n)*(a-o),f=2*e/ut([h,s],[h,u],n)*(u-s),g=c/2,p=2*g,d=Math.sqrt(3)/2*f,y=a-o,m=u-s,_=3/4*p,x=d,E=(y-p)/(p-g/2),k=Math.floor(E),b=(k*_-g/2-y)/2-g/2+_/2,w=Math.floor((m-d)/d),I=(m-w*d)/2,N=w*d-m>d/2;N&&(I-=d/4);for(var S=[],M=[],L=0;L<6;L++){var P=2*Math.PI/6*L;S.push(Math.cos(P)),M.push(Math.sin(P))}for(var T=[],O=0;O<=k;O++)for(var R=0;R<=w;R++){var A=O%2==1;if((0!==R||!A)&&(0!==R||!N)){var D=O*_+o-b,F=R*x+s+I;if(A&&(F-=d/2),!0===n.triangles)ra([D,F],c/2,f/2,JSON.parse(r),S,M).forEach((function(t){n.mask?ta(C([n.mask,t]))&&T.push(t):T.push(t)}));else{var q=na([D,F],c/2,f/2,JSON.parse(r),S,M);n.mask?ta(C([n.mask,q]))&&T.push(q):T.push(q)}}}return C(T)}function na(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=t[0]+e*i[a],l=t[1]+n*o[a];s.push([u,l])}return s.push(s[0].slice()),S([s],r)}function ra(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=[];u.push(t),u.push([t[0]+e*i[a],t[1]+n*o[a]]),u.push([t[0]+e*i[(a+1)%6],t[1]+n*o[(a+1)%6]]),u.push(t),s.push(S([u],r))}return s}function ia(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.mask&&!n.units&&(n.units="kilometers");for(var r=[],i=t[0],o=t[1],s=t[2],a=t[3],u=e/ut([i,o],[s,o],n)*(s-i),l=e/ut([i,o],[i,a],n)*(a-o),h=s-i,c=a-o,f=Math.floor(h/u),g=(c-Math.floor(c/l)*l)/2,p=i+(h-f*u)/2;p<=s;){for(var v=o+g;v<=a;){var d=I([p,v],n.properties);n.mask?Cn(d,n.mask)&&r.push(d):r.push(d),v+=l}p+=u}return C(r)}function oa(t,e,n){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=[],o=t[0],s=t[1],a=t[2],u=t[3],l=a-o,h=j(e,r.units,"degrees"),c=u-s,f=j(n,r.units,"degrees"),g=Math.floor(Math.abs(l)/h),p=Math.floor(Math.abs(c)/f),v=(c-p*f)/2,d=o+(l-g*h)/2,y=0;y2&&void 0!==arguments[2]?arguments[2]:{})}function aa(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=[],i=e/ut([t[0],t[1]],[t[2],t[1]],n)*(t[2]-t[0]),o=e/ut([t[0],t[1]],[t[0],t[3]],n)*(t[3]-t[1]),s=0,a=t[0];a<=t[2];){for(var u=0,l=t[1];l<=t[3];){var h=null,c=null;s%2==0&&u%2==0?(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)):s%2==0&&u%2==1?(h=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties)):u%2==0&&s%2==1?(h=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties),c=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties)):u%2==1&&s%2==1&&(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)),n.mask?(ta(C([n.mask,h]))&&r.push(h),ta(C([n.mask,c]))&&r.push(c)):(r.push(h),r.push(c)),l+=o,u++}s++,a+=i}return C(r)} +/*! + * MarchingSquaresJS + * version 1.3.3 + * https://github.com/RaumZeit/MarchingSquares.js + * + * @license GNU Affero General Public License. + * Copyright (c) 2015-2019 Ronny Lorenz + */ +function ua(t,e,n){return tr&&(i=n,n=r,r=i),tr?(t-r)/(t-e):(t-n)/(t-e)}function ha(t,e,n,r){return t1){for(;0!==o;)o>>=1,a++;r===1<1){for(;0!==s;)s>>=1,u++;i===1<0&&(this.childB=new da(t,e+o,n,r-o,s),this.lowerBound=Math.min(this.lowerBound,this.childB.lowerBound),this.upperBound=Math.max(this.upperBound,this.childB.upperBound),i-s>0&&(this.childC=new da(t,e+o,n+s,r-o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childC.lowerBound),this.upperBound=Math.max(this.upperBound,this.childC.upperBound))),i-s>0&&(this.childD=new da(t,e,n+s,o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childD.lowerBound),this.upperBound=Math.max(this.upperBound,this.childD.upperBound))}}function ya(t){var e,n;if(!t)throw new Error("data is required");if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Error("data must be scalar field, i.e. array of arrays");if(t.length<2)throw new Error("data must contain at least two rows");if((n=t[0].length)<2)throw new Error("data must contain at least two columns");for(e=1;e=e||t[s][r-1]>=e){n=!1;break}if(n&&(t[i-1][0]>=e||t[i-1][r-1]>=e)&&(n=!1),n)for(o=0;o=e||t[i-1][o]>e){n=!1;break}return n}(t,n.threshold)&&(n.linearRing?_.push([[0,0],[0,x],[E,x],[E,0],[0,0]]):_.push([[0,0],[0,x],[E,x],[E,0]])),e.forEach((function(t,N){t.forEach((function(t,S){for(r=null,i=0;i<4;i++)if(r=k[i],"object"===m(t.edges[r])){for(a=[],o=t.edges[r],u=r,l=N,h=S,c=!1,f=[N+o.path[0][0],S+o.path[0][1]],a.push(f);!c&&"object"===m((s=e[l][h]).edges[u]);)if(o=s.edges[u],delete s.edges[u],(g=o.path[1])[0]+=l,g[1]+=h,a.push(g),u=o.move.enter,l+=o.move.x,h+=o.move.y,void 0===e[l]||void 0===e[l][h]){if(!n.linearRing)break;if(p=0,v=0,l===E?(l--,p=0):l<0?(l++,p=2):h===x?(h--,p=3):h<0&&(h++,p=1),l===N&&h===S&&p===I[r]){c=!0,u=r;break}for(;;){if(d=!1,v>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[l]&&void 0!==e[l][h]&&(s=e[l][h],y=k[p],"object"===m(s.edges[y]))){o=s.edges[y],a.push(pa(l,h,p,o.path)),u=y,d=!0;break}if(d)break;if(a.push(va(l,h,p)),h+=w[p],void 0!==e[l+=b[p]]&&void 0!==e[l][h]||(0===p&&h<0||1===p&&l<0||2===p&&h===x||3===p&&l===E)&&(l-=b[p],h-=w[p],p=(p+1)%4,v++),l===N&&h===S&&p===I[r]){c=!0,u=r;break}}}!n.linearRing||a[a.length-1][0]===f[0]&&a[a.length-1][1]===f[1]||a.push(f),_.push(a)}}))})),_}(h,c,r)}a?g.push(f):g=f,"function"==typeof r.successCallback&&r.successCallback(g,t)})),g}function _a(t,e,n,r){var i,o,s,a,u,l,h=0,c=t[n+1][e],f=t[n+1][e+1],g=t[n][e+1],p=t[n][e],v=r.threshold;if(!(isNaN(p)||isNaN(g)||isNaN(f)||isNaN(c))){switch(h|=c>=v?8:0,h|=f>=v?4:0,h|=g>=v?2:0,l={cval:h=+(h|=p>=v?1:0),polygons:[],edges:{},x0:p,x1:g,x2:f,x3:c},h){case 0:r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,0]]);break;case 15:break;case 14:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.left={path:[[0,i],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[a,0]]);break;case 13:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[a,0],[1,o],[1,0]]);break;case 11:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[1,o],[s,1],[1,1]]);break;case 7:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[s,1],[0,i],[0,1]]);break;case 1:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[a,0],[0,i],[0,1],[1,1],[1,0]]);break;case 2:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,o],[a,0]]);break;case 4:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[1,o],[1,0]]);break;case 8:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[s,1],[1,1],[1,0]]);break;case 12:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[1,o],[1,0]]);break;case 9:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[a,0],[s,1],[1,1],[1,0]]);break;case 3:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[0,i],[0,1],[1,1],[1,o]]);break;case 6:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[a,0]]);break;case 10:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),u=(p+g+f+c)/4,r.polygons_full&&(uf&&(v>h&&ph&&vu&&(u=d)}var y=[];if(a&&u0&&Math.abs(x-n[_-1][0])>f){var E=parseFloat(n[_-1][0]),k=parseFloat(n[_-1][1]),b=parseFloat(n[_][0]),w=parseFloat(n[_][1]);if(E>-180&&E-180&&n[_-1][0]h&&E<180&&-180===b&&_+1h&&n[_-1][0]<180){m.push([180,n[_][1]]),_++,m.push([n[_][0],n[_][1]]);continue}if(Eh){var I=E;E=b,b=I;var N=k;k=w,w=N}if(E>h&&b=180&&Eh?180:-180,M]),(m=[]).push([n[_-1][0]>h?-180:180,M]),y.push(m)}else m=[],y.push(m);m.push([x,n[_][1]])}else m.push([n[_][0],n[_][1]])}}else{var L=[];y.push(L);for(var P=0;Pe||this.upperBound=e)&&r.push({x:this.x,y:this.y})),r},da.prototype.cellsBelowThreshold=function(t,e){var n=[];return e=void 0===e||e,this.lowerBound>t||(this.childA||this.childB||this.childC||this.childD?(this.childA&&(n=n.concat(this.childA.cellsBelowThreshold(t,e))),this.childB&&(n=n.concat(this.childB.cellsBelowThreshold(t,e))),this.childD&&(n=n.concat(this.childD.cellsBelowThreshold(t,e))),this.childC&&(n=n.concat(this.childC.cellsBelowThreshold(t,e)))):(e||this.upperBound>=t)&&n.push({x:this.x,y:this.y})),n};var xa={square:function(t,e,n,r,i,o){o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,0]])},triangle_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,a],[s,0],[0,0]])},triangle_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[1,a],[1,0]])},triangle_tr:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[1,s],[a,1],[1,1]])},triangle_tl:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[s,1]])},tetragon_t:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[1,1],[1,s]])},tetragon_r:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[a,1],[1,1],[1,0]])},tetragon_b:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,0]])},tetragon_l:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[a,0]])},tetragon_bl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[a,0]])},tetragon_br:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate_b(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[1,l]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[1,l],[1,u],[a,0]])},tetragon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rb={path:[[1,l],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}}),o.polygons&&t.polygons.push([[1,l],[s,1],[a,1],[1,u]])},tetragon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[0,l]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[a,1],[0,l],[0,u],[s,1]])},tetragon_lr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[1,u],[1,l]])},tetragon_tb:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[l,0],[s,1],[a,1],[u,0]])},pentagon_tr:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[1,a],[1,0]])},pentagon_tl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,0]])},pentagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,a],[s,0]])},pentagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[a,0],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[1,1],[1,0],[a,0]])},pentagon_tr_rl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[1,u],[1,l]])},pentagon_rb_bt:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,n,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[u,0],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[l,1],[1,1],[1,s],[a,0],[u,0]])},pentagon_bl_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[1,l],[1,0]])},pentagon_lt_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[l,0]])},pentagon_bl_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[l,0],[0,s]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[u,0],[l,0]])},pentagon_lt_rl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[u,1],[1,1],[1,l]])},pentagon_tr_bt:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,1],[a,1],[1,u],[1,0],[l,0]])},pentagon_rb_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_b(n,r,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,u],[l,0]])},hexagon_lt_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[1,l],[1,0]])},hexagon_bl_lt:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[1,1],[1,0]])},hexagon_bl_rb:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.rt={path:[[1,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[1,1],[1,l],[a,0]])},hexagon_tr_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[a,1],[1,u],[1,l],[s,0]])},hexagon_lt_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,u],[l,0]])},hexagon_bl_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,1],[u,1],[1,l],[1,0]])},heptagon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[1,1],[1,c],[a,0]])},heptagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate_a(i,r,o.minV,o.maxV),l=o.interpolate_b(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,a],[u,1],[l,1],[1,h],[1,c],[s,0]])},heptagon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[l,1],[1,h],[1,c],[a,0]])},heptagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(i,r,o.minV,o.maxV),h=o.interpolate_b(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[h,1],[1,c]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[h,1],[1,c],[1,0]])},octagon:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate_a(i,r,o.minV,o.maxV),c=o.interpolate_b(i,r,o.minV,o.maxV),f=o.interpolate_b(n,r,o.minV,o.maxV),g=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[c,1],[1,f]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,g],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[c,1],[1,f],[1,g],[a,0]])}};function Ea(t,e,n,r){var i,o,s,a=!1,u=null,l=null,h=null,c=null,f=!1,g=[],p=[],v=[];if(!t)throw new Error("data is required");if(null==e)throw new Error("lowerBound is required");if(null==n)throw new Error("bandWidth is required");if(s=function(t){var e,n,r,i,o;for(i=new fa,t=t||{},o=Object.keys(i),e=0;en||t[a][i-1]n){r=!1;break}if(r&&(t[o-1][0]n||t[o-1][i-1]n)&&(r=!1),r)for(s=0;sn||t[o-1][s]n){r=!1;break}return r}(t,n.minV,n.maxV)&&(n.linearRing?x.push([[0,0],[0,E],[k,E],[k,0],[0,0]]):x.push([[0,0],[0,E],[k,E],[k,0]])),e.forEach((function(t,M){t.forEach((function(t,L){for(r=null,o=0;o<8;o++)if(r=N[o],"object"===m(t.edges[r])){for(i=[],s=t.edges[r],l=r,h=M,c=L,f=!1,g=[M+s.path[0][0],L+s.path[0][1]],i.push(g);!f&&"object"===m((p=e[h][c]).edges[l]);)if(s=p.edges[l],delete p.edges[l],(y=s.path[1])[0]+=h,y[1]+=c,i.push(y),l=s.move.enter,h+=s.move.x,c+=s.move.y,void 0===e[h]||void 0===e[h][c]){if(v=0,d=0,h===k)h--,v=0;else if(h<0)h++,v=2;else if(c===E)c--,v=3;else{if(!(c<0))throw new Error("Left the grid somewhere in the interior!");c++,v=1}if(h===M&&c===L&&v===S[r]){f=!0,l=r;break}for(;;){if(_=!1,d>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[h]&&void 0!==e[h][c])for(p=e[h][c],a=0;ao?2:sf?128:64,s|=uf?32:16,s|=lf?8:4,o=0,i={cval:s=+(s|=hf?2:1),polygons:[],edges:{},x0:h,x1:l,x2:u,x3:a,x:e,y:n},s){case 85:xa.square(i,h,l,u,a,r);case 0:case 170:break;case 169:xa.triangle_bl(i,h,l,u,a,r);break;case 166:xa.triangle_br(i,h,l,u,a,r);break;case 154:xa.triangle_tr(i,h,l,u,a,r);break;case 106:xa.triangle_tl(i,h,l,u,a,r);break;case 1:xa.triangle_bl(i,h,l,u,a,r);break;case 4:xa.triangle_br(i,h,l,u,a,r);break;case 16:xa.triangle_tr(i,h,l,u,a,r);break;case 64:xa.triangle_tl(i,h,l,u,a,r);break;case 168:xa.tetragon_bl(i,h,l,u,a,r);break;case 162:xa.tetragon_br(i,h,l,u,a,r);break;case 138:xa.tetragon_tr(i,h,l,u,a,r);break;case 42:xa.tetragon_tl(i,h,l,u,a,r);break;case 2:xa.tetragon_bl(i,h,l,u,a,r);break;case 8:xa.tetragon_br(i,h,l,u,a,r);break;case 32:xa.tetragon_tr(i,h,l,u,a,r);break;case 128:xa.tetragon_tl(i,h,l,u,a,r);break;case 5:xa.tetragon_b(i,h,l,u,a,r);break;case 20:xa.tetragon_r(i,h,l,u,a,r);break;case 80:xa.tetragon_t(i,h,l,u,a,r);break;case 65:xa.tetragon_l(i,h,l,u,a,r);break;case 165:xa.tetragon_b(i,h,l,u,a,r);break;case 150:xa.tetragon_r(i,h,l,u,a,r);break;case 90:xa.tetragon_t(i,h,l,u,a,r);break;case 105:xa.tetragon_l(i,h,l,u,a,r);break;case 160:xa.tetragon_lr(i,h,l,u,a,r);break;case 130:xa.tetragon_tb(i,h,l,u,a,r);break;case 10:xa.tetragon_lr(i,h,l,u,a,r);break;case 40:xa.tetragon_tb(i,h,l,u,a,r);break;case 101:xa.pentagon_tr(i,h,l,u,a,r);break;case 149:xa.pentagon_tl(i,h,l,u,a,r);break;case 86:xa.pentagon_bl(i,h,l,u,a,r);break;case 89:xa.pentagon_br(i,h,l,u,a,r);break;case 69:xa.pentagon_tr(i,h,l,u,a,r);break;case 21:xa.pentagon_tl(i,h,l,u,a,r);break;case 84:xa.pentagon_bl(i,h,l,u,a,r);break;case 81:xa.pentagon_br(i,h,l,u,a,r);break;case 96:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 24:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 6:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 129:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 74:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 146:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 164:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 41:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 66:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 144:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 36:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 9:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 104:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 26:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 134:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 161:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 37:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 148:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 82:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 73:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 133:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 22:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 88:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 97:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 145:case 25:xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 70:case 100:xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 17:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 68:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 153:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 102:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 152:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 137:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 98:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 38:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 18:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 33:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 72:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 132:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 136:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r));break;case 34:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r))}return i}}var wa=Object.defineProperty,Ia=Object.getOwnPropertySymbols,Na=Object.prototype.hasOwnProperty,Sa=Object.prototype.propertyIsEnumerable,Ma=function(t,e,n){return e in t?wa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},La=function(t,e){for(var n in e||(e={}))Na.call(e,n)&&Ma(t,n,e[n]);if(Ia){var r,i=a(Ia(e));try{for(i.s();!(r=i.n()).done;){n=r.value;Sa.call(e,n)&&Ma(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t};function Pa(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.zProperty||"elevation",r=e.flip,i=e.flags;nt(t,"Point","input must contain Points");for(var o=function(t,e){var n={};vt(t,(function(t){var e=Q(t)[1];n[e]||(n[e]=[]),n[e].push(t)}));var r=Object.keys(n).map((function(t){return n[t].sort((function(t,e){return Q(t)[0]-Q(e)[0]}))})),i=r.sort((function(t,n){return e?Q(t[0])[1]-Q(n[0])[1]:Q(n[0])[1]-Q(t[0])[1]}));return i}(t,r),s=[],a=0;a=0&&l<=1&&(f.onLine1=!0),h>=0&&h<=1&&(f.onLine2=!0),!(!f.onLine1||!f.onLine2)&&[f.x,f.y])}function za(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return bt(t,(function(t,n){var r=n.geometry.coordinates;return t+ut(r[0],r[1],e)}),0)}function ja(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=i.steps||64,s=Xa(n),a=Xa(r),u=Array.isArray(t)||"Feature"!==t.type?{}:t.properties;if(s===a)return L(Ri(t,e,i).geometry.coordinates[0],u);for(var l=s,h=s=h&&c===i.length-1);c++){if(h>e&&0===o.length){if(!(s=e-h))return o.push(i[c]),L(o);a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates)}if(h>=n)return(s=n-h)?(a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates),L(o)):(o.push(i[c]),L(o));if(h>=e&&o.push(i[c]),c===i.length-1)return L(o);h+=ut(i[c],i[c+1],r)}if(h0){var a=r[e-1],u=Wa(n,a);!1!==u&&(a[1]=u,n[0]=u),s.push(a[0]),e===o.length-2&&(s.push(n[0]),s.push(n[1]))}2===o.length&&(s.push(n[0]),s.push(n[1]))}var l,h,c,f,g,p,v,d})),L(s,t.properties)}function Ka(t){var e=t[0],n=t[1],r=t[2],i=t[3];if(ut(t.slice(0,2),[r,n])>=ut(t.slice(0,2),[e,i])){var o=(n+i)/2;return[e,o-(r-e)/2,r,o+(r-e)/2]}var s=(e+r)/2;return[s-(i-n)/2,n,s+(i-n)/2,i]}function Qa(t,e){if(!Z(e=null!=e?e:{}))throw new Error("options is invalid");var n=e.precision,r=e.coordinates,i=e.mutate;if(n=null==n||isNaN(n)?6:n,r=null==r||isNaN(r)?3:r,!t)throw new Error(" is required");if("number"!=typeof n)throw new Error(" must be a number");if("number"!=typeof r)throw new Error(" must be a number");!1!==i&&void 0!==i||(t=JSON.parse(JSON.stringify(t)));var o=Math.pow(10,n);return ct(t,(function(t){!function(t,e,n){t.length>n&&t.splice(n,t.length);for(var r=0;r1&&n.push(L(l)),C(n)}function eu(t,e){if(!e.features.length)throw new Error("lines must contain features");if(1===e.features.length)return e.features[0];var n,r=1/0;return vt(e,(function(e){var i=fn(e,t).properties.dist;iu?(a.unshift(t),u=e):a.push(t)}else a.push(t)})),S(a,e);default:throw new Error("geometry type "+s+" is not supported")}}function iu(t){var e=t[0],n=e[0],r=e[1],i=t[t.length-1],o=i[0],s=i[1];return n===o&&r===s||t.push(e),t}function ou(t){return R(t)}function su(t){var e=[[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]];return t&&(e="Feature"===t.type?t.geometry.coordinates:t.coordinates),S(e)}function au(t){var e,n=0,r=a(t);try{for(r.s();!(e=r.n()).done;){n+=e.value}}catch(t){r.e(t)}finally{r.f()}return n/t.length}var uu=Object.defineProperty,lu=Object.defineProperties,hu=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,fu=Object.prototype.hasOwnProperty,gu=Object.prototype.propertyIsEnumerable,pu=function(t,e,n){return e in t?uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},vu=function(t,e){for(var n in e||(e={}))fu.call(e,n)&&pu(t,n,e[n]);if(cu){var r,i=a(cu(e));try{for(i.s();!(r=i.n()).done;){n=r.value;gu.call(e,n)&&pu(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},du=function(t,e){return lu(t,hu(e))};function yu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("targetPoint is required");if(!e)throw new Error("points is required");var r=1/0,i=0;vt(e,(function(e,o){var s=ut(t,e,n);s2&&void 0!==arguments[2]?arguments[2]:{},o=null!=(n=i.method)?n:"geodesic",s=null!=(r=i.units)?r:"kilometers";if(!t)throw new Error("pt is required");if(Array.isArray(t)?t=I(t):"Point"===t.type?t=b(t):et(t,"Point","point"),!e)throw new Error("line is required");Array.isArray(e)?e=L(e):"LineString"===e.type?e=b(e):et(e,"LineString","line");var a=1/0,u=t.geometry.coordinates;return kt(e,(function(t){if(t){var e=t.geometry.coordinates[0],n=t.geometry.coordinates[1],r=function(t,e,n,r){if("geodesic"===r.method){return fn(L([e,n]).geometry,t,{units:"degrees"}).properties.dist}var i=[n[0]-e[0],n[1]-e[1]],o=[t[0]-e[0],t[1]-e[1]],s=_u(o,i);if(s<=0)return Ys(t,e,{units:"degrees"});var a=_u(i,i);if(a<=s)return Ys(t,n,{units:"degrees"});var u=s/a,l=[e[0]+u*i[0],e[1]+u*i[1]];return Ys(t,l,{units:"degrees"})}(u,e,n,{method:o});r0)-(t<0)||+t}(r*(n[1]-e[1])-o*i)}function Lu(t,e){return e.geometry.coordinates[0].every((function(e){return zt(I(e),t)}))}var Pu=function(){return s((function t(e){i(this,t),this.id=t.buildId(e),this.coordinates=e,this.innerEdges=[],this.outerEdges=[],this.outerEdgesSorted=!1}),[{key:"removeInnerEdge",value:function(t){this.innerEdges=this.innerEdges.filter((function(e){return e.from.id!==t.from.id}))}},{key:"removeOuterEdge",value:function(t){this.outerEdges=this.outerEdges.filter((function(e){return e.to.id!==t.to.id}))}},{key:"addOuterEdge",value:function(t){this.outerEdges.push(t),this.outerEdgesSorted=!1}},{key:"sortOuterEdges",value:function(){var t=this;this.outerEdgesSorted||(this.outerEdges.sort((function(e,n){var r=e.to,i=n.to;if(r.coordinates[0]-t.coordinates[0]>=0&&i.coordinates[0]-t.coordinates[0]<0)return 1;if(r.coordinates[0]-t.coordinates[0]<0&&i.coordinates[0]-t.coordinates[0]>=0)return-1;if(r.coordinates[0]-t.coordinates[0]==0&&i.coordinates[0]-t.coordinates[0]==0)return r.coordinates[1]-t.coordinates[1]>=0||i.coordinates[1]-t.coordinates[1]>=0?r.coordinates[1]-i.coordinates[1]:i.coordinates[1]-r.coordinates[1];var o=Mu(t.coordinates,r.coordinates,i.coordinates);return o<0?1:o>0?-1:Math.pow(r.coordinates[0]-t.coordinates[0],2)+Math.pow(r.coordinates[1]-t.coordinates[1],2)-(Math.pow(i.coordinates[0]-t.coordinates[0],2)+Math.pow(i.coordinates[1]-t.coordinates[1],2))})),this.outerEdgesSorted=!0)}},{key:"getOuterEdges",value:function(){return this.sortOuterEdges(),this.outerEdges}},{key:"getOuterEdge",value:function(t){return this.sortOuterEdges(),this.outerEdges[t]}},{key:"addInnerEdge",value:function(t){this.innerEdges.push(t)}}],[{key:"buildId",value:function(t){return t.join(",")}}])}(),Cu=function(){function t(e,n){i(this,t),this.from=e,this.to=n,this.next=void 0,this.label=void 0,this.symetric=void 0,this.ring=void 0,this.from.addOuterEdge(this),this.to.addInnerEdge(this)}return s(t,[{key:"getSymetric",value:function(){return this.symetric||(this.symetric=new t(this.to,this.from),this.symetric.symetric=this),this.symetric}},{key:"deleteEdge",value:function(){this.from.removeOuterEdge(this),this.to.removeInnerEdge(this)}},{key:"isEqual",value:function(t){return this.from.id===t.from.id&&this.to.id===t.to.id}},{key:"toString",value:function(){return"Edge { ".concat(this.from.id," -> ").concat(this.to.id," }")}},{key:"toLineString",value:function(){return L([this.from.coordinates,this.to.coordinates])}},{key:"compareTo",value:function(t){return Mu(t.from.coordinates,t.to.coordinates,this.to.coordinates)}}])}(),Tu=function(){return s((function t(){i(this,t),this.edges=[],this.polygon=void 0,this.envelope=void 0}),[{key:"push",value:function(t){this.edges.push(t),this.polygon=this.envelope=void 0}},{key:"get",value:function(t){return this.edges[t]}},{key:"length",get:function(){return this.edges.length}},{key:"forEach",value:function(t){this.edges.forEach(t)}},{key:"map",value:function(t){return this.edges.map(t)}},{key:"some",value:function(t){return this.edges.some(t)}},{key:"isValid",value:function(){return!0}},{key:"isHole",value:function(){var t=this,e=this.edges.reduce((function(e,n,r){return n.from.coordinates[1]>t.edges[e].from.coordinates[1]&&(e=r),e}),0),n=(0===e?this.length:e)-1,r=(e+1)%this.length,i=Mu(this.edges[n].from.coordinates,this.edges[e].from.coordinates,this.edges[r].from.coordinates);return 0===i?this.edges[n].from.coordinates[0]>this.edges[r].from.coordinates[0]:i>0}},{key:"toMultiPoint",value:function(){return O(this.edges.map((function(t){return t.from.coordinates})))}},{key:"toPolygon",value:function(){if(this.polygon)return this.polygon;var t=this.edges.map((function(t){return t.from.coordinates}));return t.push(this.edges[0].from.coordinates),this.polygon=S([t])}},{key:"getEnvelope",value:function(){return this.envelope?this.envelope:this.envelope=Us(this.toPolygon())}},{key:"inside",value:function(t){return zt(t,this.toPolygon())}}],[{key:"findEdgeRingContaining",value:function(t,e){var n,r,i=t.getEnvelope();return e.forEach((function(e){var o,s,u,l,h,c,f=e.getEnvelope();if((r&&(n=r.getEnvelope()),s=i,u=(o=f).geometry.coordinates[0].map((function(t){return t[0]})),l=o.geometry.coordinates[0].map((function(t){return t[1]})),h=s.geometry.coordinates[0].map((function(t){return t[0]})),c=s.geometry.coordinates[0].map((function(t){return t[1]})),Math.max.apply(null,u)!==Math.max.apply(null,h)||Math.max.apply(null,l)!==Math.max.apply(null,c)||Math.min.apply(null,u)!==Math.min.apply(null,h)||Math.min.apply(null,l)!==Math.min.apply(null,c))&&Lu(f,i)){var g,p,v=a(t.map((function(t){return t.from.coordinates})));try{var d=function(){var t=p.value;e.some((function(e){return n=t,r=e.from.coordinates,n[0]===r[0]&&n[1]===r[1];var n,r}))||(g=t)};for(v.s();!(p=v.n()).done;)d()}catch(t){v.e(t)}finally{v.f()}g&&e.inside(I(g))&&(r&&!Lu(n,f)||(r=e))}})),r}}])}();var Ou=function(){function t(){i(this,t),this.edges=[],this.nodes={}}return s(t,[{key:"getNode",value:function(t){var e=Pu.buildId(t),n=this.nodes[e];return n||(n=this.nodes[e]=new Pu(t)),n}},{key:"addEdge",value:function(t,e){var n=new Cu(t,e),r=n.getSymetric();this.edges.push(n),this.edges.push(r)}},{key:"deleteDangles",value:function(){var t=this;Object.keys(this.nodes).map((function(e){return t.nodes[e]})).forEach((function(e){return t._removeIfDangle(e)}))}},{key:"_removeIfDangle",value:function(t){var e=this;if(t.innerEdges.length<=1){var n=t.getOuterEdges().map((function(t){return t.to}));this.removeNode(t),n.forEach((function(t){return e._removeIfDangle(t)}))}}},{key:"deleteCutEdges",value:function(){var t=this;this._computeNextCWEdges(),this._findLabeledEdgeRings(),this.edges.forEach((function(e){e.label===e.symetric.label&&(t.removeEdge(e.symetric),t.removeEdge(e))}))}},{key:"_computeNextCWEdges",value:function(t){var e=this;void 0===t?Object.keys(this.nodes).forEach((function(t){return e._computeNextCWEdges(e.nodes[t])})):t.getOuterEdges().forEach((function(e,n){t.getOuterEdge((0===n?t.getOuterEdges().length:n)-1).symetric.next=e}))}},{key:"_computeNextCCWEdges",value:function(t,e){for(var n,r,i=t.getOuterEdges(),o=i.length-1;o>=0;--o){var s=i[o],a=s.symetric,u=void 0,l=void 0;s.label===e&&(u=s),a.label===e&&(l=a),u&&l&&(l&&(r=l),u&&(r&&(r.next=u,r=void 0),n||(n=u)))}r&&(r.next=n)}},{key:"_findLabeledEdgeRings",value:function(){var t=[],e=0;return this.edges.forEach((function(n){if(!(n.label>=0)){t.push(n);var r=n;do{r.label=e,r=r.next}while(!n.isEqual(r));e++}})),t}},{key:"getEdgeRings",value:function(){var t=this;this._computeNextCWEdges(),this.edges.forEach((function(t){t.label=void 0})),this._findLabeledEdgeRings().forEach((function(e){t._findIntersectionNodes(e).forEach((function(n){t._computeNextCCWEdges(n,e.label)}))}));var e=[];return this.edges.forEach((function(n){n.ring||e.push(t._findEdgeRing(n))})),e}},{key:"_findIntersectionNodes",value:function(t){var e=[],n=t,r=function(){var r=0;n.from.getOuterEdges().forEach((function(e){e.label===t.label&&++r})),r>1&&e.push(n.from),n=n.next};do{r()}while(!t.isEqual(n));return e}},{key:"_findEdgeRing",value:function(t){var e=t,n=new Tu;do{n.push(e),e.ring=n,e=e.next}while(!t.isEqual(e));return n}},{key:"removeNode",value:function(t){var e=this;t.getOuterEdges().forEach((function(t){return e.removeEdge(t)})),t.innerEdges.forEach((function(t){return e.removeEdge(t)})),delete this.nodes[t.id]}},{key:"removeEdge",value:function(t){this.edges=this.edges.filter((function(e){return!e.isEqual(t)})),t.deleteEdge()}}],[{key:"fromGeoJson",value:function(e){!function(t){if(!t)throw new Error("No geojson passed");if("FeatureCollection"!==t.type&&"GeometryCollection"!==t.type&&"MultiLineString"!==t.type&&"LineString"!==t.type&&"Feature"!==t.type)throw new Error("Invalid input type '".concat(t.type,"'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature"))}(e);var n=new t;return xt(e,(function(t){et(t,"LineString","Graph::fromGeoJson"),ft(t,(function(t,e){if(t){var r=n.getNode(t),i=n.getNode(e);n.addEdge(r,i)}return e}))})),n}}])}();function Ru(t,e){var n,r;ct(t,(function(t,i,o,s,a){if(r!==a)e.push([]);else{var u=n[0],l=n[1],h=t[0],c=t[1];e[a].push([.75*u+.25*h,.75*l+.25*c]),e[a].push([.25*u+.75*h,.25*l+.75*c])}n=t,r=a}),!1),e.forEach((function(t){t.push(t[0])}))}function Au(t,e){var n,r,i;ct(t,(function(t,o,s,a,u){if(r!==a)e.push([[]]);else if(i!==u)e[a].push([]);else{var l=n[0],h=n[1],c=t[0],f=t[1];e[a][u].push([.75*l+.25*c,.75*h+.25*f]),e[a][u].push([.25*l+.75*c,.25*h+.75*f])}n=t,r=a,i=u}),!1),e.forEach((function(t){t.forEach((function(t){t.push(t[0])}))}))}function Du(t,e,n,r,i){for(var o=0;o0?qu(e,s,r)<0||(r=s):n>0&&u<=0&&(Fu(e,s,i)||(i=s)),n=u}return[r,i]}function Fu(t,e,n){return qu(t,e,n)>0}function qu(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(n[0]-t[0])*(e[1]-t[1])}function Vu(t){return Bu(t,"mercator",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Gu(t){return Bu(t,"wgs84",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Bu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=(n=n||{}).mutate;if(!t)throw new Error("geojson is required");return Array.isArray(t)&&U(t[0])?t="mercator"===e?Yu(t):zu(t):(!0!==r&&(t=Ai(t)),ct(t,(function(t){var n="mercator"===e?Yu(t):zu(t);t[0]=n[0],t[1]=n[1]}))),t}function Yu(t){var e=Math.PI/180,n=6378137,r=20037508.342789244,i=Math.abs(t[0])<=180?t[0]:t[0]-360*function(t){return t<0?-1:t>0?1:0}(t[0]),o=[n*i*e,n*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return o[0]>r&&(o[0]=r),o[0]<-r&&(o[0]=-r),o[1]>r&&(o[1]=r),o[1]<-r&&(o[1]=-r),o}function zu(t){var e=180/Math.PI,n=6378137;return[t[0]*e/n,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/n)))*e]}var ju=Object.freeze({__proto__:null,toMercator:Vu,toWgs84:Gu});var Xu={20:1.07275,15:1.13795,10:1.22385,5:1.3581,2:1.51743,1:1.62762};function Uu(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}function Zu(t){var e=[];return function t(n){return 0===n||1===n?1:e[n]>0?e[n]:e[n]=t(n-1)*n}(t)}function Hu(t){return Ju(t),Wu(t)}function Wu(t){return Array.isArray(t)?el(t):t&&t.bbox?el(t.bbox):[360*tl(),180*tl()]}function Ju(t){null!=t&&(Array.isArray(t)?H(t):null!=t.bbox&&H(t.bbox))}function Ku(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1);for(var n=[],r=0;r1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1),void 0!==e.bbox&&null!==e.bbox||(e.bbox=[-180,-90,180,90]),U(e.num_vertices)&&void 0!==e.num_vertices||(e.num_vertices=10),U(e.max_radial_length)&&void 0!==e.max_radial_length||(e.max_radial_length=10);var n=Math.abs(e.bbox[0]-e.bbox[2]),r=Math.abs(e.bbox[1]-e.bbox[3]),i=Math.min(n/2,r/2);if(e.max_radial_length>i)throw new Error("max_radial_length is greater than the radius of the bbox");for(var o=[e.bbox[0]+e.max_radial_length,e.bbox[1]+e.max_radial_length,e.bbox[2]-e.max_radial_length,e.bbox[3]-e.max_radial_length],s=[],a=function(){var t,n=[],r=d(Array(e.num_vertices+1)).map(Math.random);r.forEach((function(t,e,n){n[e]=e>0?t+n[e-1]:t})),r.forEach((function(t){t=2*t*Math.PI/r[r.length-1];var i=Math.random();n.push([i*(e.max_radial_length||10)*Math.sin(t),i*(e.max_radial_length||10)*Math.cos(t)])})),n[n.length-1]=n[0],n=n.reverse().map((t=Wu(o),function(e){return[e[0]+t[0],e[1]+t[1]]})),s.push(S([n]))},u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox;Ju(n);var r=e.num_vertices,i=e.max_length,o=e.max_rotation;null==t&&(t=1),(!U(r)||void 0===r||r<2)&&(r=10),U(i)&&void 0!==i||(i=1e-4),U(o)&&void 0!==o||(o=Math.PI/8);for(var s=[],a=0;a0;){var l=a.pop();if(l===n)return ll(l);l.closed=!0;for(var h=t.neighbors(l),c=0,f=h.length;c1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function dl(t,e,n,r,i){for(var o,s=r,a=e+1;as&&(o=a,s=u)}s>r&&(o-e>1&&dl(t,e,o,r,i),i.push(t[o]),n-o>1&&dl(t,o,n,r,i))}function yl(t,e){var n=t.length-1,r=[t[0]];return dl(t,0,n,e,r),r.push(t[n]),r}function ml(t,e,n){if(t.length<=2)return t;var r=void 0!==e?e*e:1;return t=n?t:function(t,e){for(var n,r,i,o,s,a=t[0],u=[a],l=1,h=t.length;le&&(u.push(n),a=n);return a!==n&&u.push(n),u}(t,r),t=yl(t,r)}function _l(t,e,n){return t.map((function(t){if(t.length<4)throw new Error("invalid polygon");for(var r=e,i=ml(t,r,n);!xl(i);)i=ml(t,r-=.01*r,n);return i[i.length-1][0]===i[0][0]&&i[i.length-1][1]===i[0][1]||i.push(i[0]),i}))}function xl(t){return!(t.length<3)&&!(3===t.length&&t[2][0]===t[0][0]&&t[2][1]===t[0][1])}function El(t,e){return{x:t[0]-e[0],y:t[1]-e[1]}}cl.prototype.init=function(){this.dirtyNodes=[];for(var t=0;t0&&(this.content[0]=e,this.bubbleUp(0)),t},remove:function(t){var e=this.content.indexOf(t),n=this.content.pop();e!==this.content.length-1&&(this.content[e]=n,this.scoreFunction(n)0;){var n=(t+1>>1)-1,r=this.content[n];if(!(this.scoreFunction(e)80*i){o=a=t[0],s=h=t[1];for(var _=i;_a&&(a=c),g>h&&(h=g);p=0!==(p=Math.max(a-o,h-s))?32767/p:0}return r(y,m,i,o,s,p,0),m}function e(t,e,n,r,i){var o,s;if(i===I(t,e,n,r)>0)for(o=e;o=e;o-=r)s=k(o,t[o],t[o+1],s);return s&&d(s,s.next)&&(b(s),s=s.next),s}function n(t,e){if(!t)return t;e||(e=t);var n,r=t;do{if(n=!1,r.steiner||!d(r,r.next)&&0!==v(r.prev,r,r.next))r=r.next;else{if(b(r),(r=e=r.prev)===r.next)break;n=!0}}while(n||r!==e);return e}function r(t,e,u,l,h,f,g){if(t){!g&&f&&function(t,e,n,r){var i=t;do{0===i.z&&(i.z=c(i.x,i.y,e,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,n,r,i,o,s,a,u,l=1;do{for(n=t,t=null,o=null,s=0;n;){for(s++,r=n,a=0,e=0;e0||u>0&&r;)0!==a&&(0===u||!r||n.z<=r.z)?(i=n,n=n.nextZ,a--):(i=r,r=r.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;n=r}o.nextZ=null,l*=2}while(s>1)}(i)}(t,l,h,f);for(var p,v,d=t;t.prev!==t.next;)if(p=t.prev,v=t.next,f?o(t,l,h,f):i(t))e.push(p.i/u|0),e.push(t.i/u|0),e.push(v.i/u|0),b(t),t=v.next,d=v.next;else if((t=v)===d){g?1===g?r(t=s(n(t),e,u),e,u,l,h,f,2):2===g&&a(t,e,u,l,h,f):r(n(t),e,u,l,h,f,1);break}}}function i(t){var e=t.prev,n=t,r=t.next;if(v(e,n,r)>=0)return!1;for(var i=e.x,o=n.x,s=r.x,a=e.y,u=n.y,l=r.y,h=io?i>s?i:s:o>s?o:s,p=a>u?a>l?a:l:u>l?u:l,d=r.next;d!==e;){if(d.x>=h&&d.x<=f&&d.y>=c&&d.y<=p&&g(i,a,o,u,s,l,d.x,d.y)&&v(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function o(t,e,n,r){var i=t.prev,o=t,s=t.next;if(v(i,o,s)>=0)return!1;for(var a=i.x,u=o.x,l=s.x,h=i.y,f=o.y,p=s.y,d=au?a>l?a:l:u>l?u:l,_=h>f?h>p?h:p:f>p?f:p,x=c(d,y,e,n,r),E=c(m,_,e,n,r),k=t.prevZ,b=t.nextZ;k&&k.z>=x&&b&&b.z<=E;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;if(k=k.prevZ,b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;k&&k.z>=x;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;k=k.prevZ}for(;b&&b.z<=E;){if(b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function s(t,e,r){var i=t;do{var o=i.prev,s=i.next.next;!d(o,s)&&y(o,i,i.next,s)&&x(o,s)&&x(s,o)&&(e.push(o.i/r|0),e.push(i.i/r|0),e.push(s.i/r|0),b(i),b(i.next),i=t=s),i=i.next}while(i!==t);return n(i)}function a(t,e,i,o,s,a){var u=t;do{for(var l=u.next.next;l!==u.prev;){if(u.i!==l.i&&p(u,l)){var h=E(u,l);return u=n(u,u.next),h=n(h,h.next),r(u,e,i,o,s,a,0),void r(h,e,i,o,s,a,0)}l=l.next}u=u.next}while(u!==t)}function u(t,e){return t.x-e.x}function l(t,e){var r=function(t,e){var n,r=e,i=t.x,o=t.y,s=-1/0;do{if(o<=r.y&&o>=r.next.y&&r.next.y!==r.y){var a=r.x+(o-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=i&&a>s&&(s=a,n=r.x=r.x&&r.x>=c&&i!==r.x&&g(on.x||r.x===n.x&&h(n,r)))&&(n=r,p=u)),r=r.next}while(r!==l);return n}(t,e);if(!r)return e;var i=E(r,t);return n(i,i.next),n(r,r.next)}function h(t,e){return v(t.prev,t,e.prev)<0&&v(e.next,t,t.next)<0}function c(t,e,n,r,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function f(t){var e=t,n=t;do{(e.x=(t-s)*(o-a)&&(t-s)*(r-a)>=(n-s)*(e-a)&&(n-s)*(o-a)>=(i-s)*(r-a)}function p(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&y(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(x(t,e)&&x(e,t)&&function(t,e){var n=t,r=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{n.y>o!=n.next.y>o&&n.next.y!==n.y&&i<(n.next.x-n.x)*(o-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==t);return r}(t,e)&&(v(t.prev,t,e.prev)||v(t,e.prev,e))||d(t,e)&&v(t.prev,t,t.next)>0&&v(e.prev,e,e.next)>0)}function v(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function d(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,n,r){var i=_(v(t,e,n)),o=_(v(t,e,r)),s=_(v(n,r,t)),a=_(v(n,r,e));return i!==o&&s!==a||(!(0!==i||!m(t,n,e))||(!(0!==o||!m(t,r,e))||(!(0!==s||!m(n,t,r))||!(0!==a||!m(n,e,r)))))}function m(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function _(t){return t>0?1:t<0?-1:0}function x(t,e){return v(t.prev,t,t.next)<0?v(t,e,t.next)>=0&&v(t,t.prev,e)>=0:v(t,e,t.prev)<0||v(t,t.next,e)<0}function E(t,e){var n=new w(t.i,t.x,t.y),r=new w(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,n.next=i,i.prev=n,r.next=n,n.prev=r,o.next=r,r.prev=o,r}function k(t,e,n,r){var i=new w(t,e,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function b(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 w(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function I(t,e,n,r){for(var i=0,o=e,s=n-r;o0&&(r+=t[i-1].length,n.holes.push(r))}return n},bl.exports}(),Il=mn(wl);function Nl(t){var e=function(t){for(var e=t[0][0].length,n={vertices:[],holes:[],dimensions:e},r=0,i=0;i0&&(r+=t[i-1].length,n.holes.push(r))}return n}(t),n=Il(e.vertices,e.holes,2),r=[],i=[];n.forEach((function(t,r){var o=n[r];i.push([e.vertices[2*o],e.vertices[2*o+1]])}));for(var o=0;o=1||u<=0||l>=1||l<=0))){var v=p,d=!o[v];d&&(o[v]=!0),e?i.push(e(p,t,n,h,c,u,s,a,f,g,l,d)):i.push(p)}}function v(t,e){var n,i,o,s,a=r[t][e],u=r[t][e+1];return a[0]f[e.isect].coord?-1:1}));for(l=[];x.length>0;){var I=x.pop(),N=I.isect,M=I.parent,L=I.winding,P=l.length,T=[f[N].coord],O=N;if(f[N].ringAndEdge1Walkable)var R=f[N].ringAndEdge1,A=f[N].nxtIsectAlongRingAndEdge1;else R=f[N].ringAndEdge2,A=f[N].nxtIsectAlongRingAndEdge2;for(;!Rl(f[N].coord,f[A].coord);){T.push(f[A].coord);var D=void 0;for(r=0;r1)for(e=0;e=0==e}function Ol(t){for(var e=0,n=0;n0)){if(o/=f,f<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=r-u,f||!(o<0)){if(o/=f,f<0){if(o>c)return;o>h&&(h=o)}else if(f>0){if(o0)){if(o/=g,g<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=i-l,g||!(o<0)){if(o/=g,g<0){if(o>c)return;o>h&&(h=o)}else if(g>0){if(o0||c<1)||(h>0&&(t[0]=[u+h*f,l+h*g]),c<1&&(t[1]=[u+c*f,l+c*g]),!0)}}}}}function Hl(t,e,n,r,i){var o=t[1];if(o)return!0;var s,a,u=t[0],l=t.left,h=t.right,c=l[0],f=l[1],g=h[0],p=h[1],v=(c+g)/2,d=(f+p)/2;if(p===f){if(v=r)return;if(c>g){if(u){if(u[1]>=i)return}else u=[v,n];o=[v,i]}else{if(u){if(u[1]1)if(c>g){if(u){if(u[1]>=i)return}else u=[(n-a)/s,n];o=[(i-a)/s,i]}else{if(u){if(u[1]=r)return}else u=[e,s*e+a];o=[r,s*r+a]}else{if(u){if(u[0]=-dh)){var g=u*u+l*l,p=h*h+c*c,v=(c*g-l*p)/f,d=(u*p-h*g)/f,y=$l.pop()||new th;y.arc=t,y.site=i,y.x=v+s,y.y=(y.cy=d+a)+Math.sqrt(v*v+d*d),t.circle=y;for(var m=null,_=gh._;_;)if(y.y<_.y||y.y===_.y&&y.x<=_.x){if(!_.L){m=_.P;break}_=_.L}else{if(!_.R){m=_;break}_=_.R}gh.insert(m,y),m||(Ql=y)}}}}function nh(t){var e=t.circle;e&&(e.P||(Ql=e.N),gh.remove(e),$l.push(e),Gl(e),t.circle=null)}var rh=[];function ih(){Gl(this),this.edge=this.site=this.circle=null}function oh(t){var e=rh.pop()||new ih;return e.site=t,e}function sh(t){nh(t),ch.remove(t),rh.push(t),Gl(t)}function ah(t){var e=t.circle,n=e.x,r=e.cy,i=[n,r],o=t.P,s=t.N,a=[t];sh(t);for(var u=o;u.circle&&Math.abs(n-u.circle.x)vh)a=a.L;else{if(!((i=o-hh(a,s))>vh)){r>-vh?(e=a.P,n=a):i>-vh?(e=a,n=a.N):e=n=a;break}if(!a.R){e=a;break}a=a.R}!function(t){fh[t.index]={site:t,halfedges:[]}}(t);var u=oh(t);if(ch.insert(e,u),e||n){if(e===n)return nh(e),n=oh(e.site),ch.insert(u,n),u.edge=n.edge=jl(e.site,u.site),eh(e),void eh(n);if(n){nh(e),nh(n);var l=e.site,h=l[0],c=l[1],f=t[0]-h,g=t[1]-c,p=n.site,v=p[0]-h,d=p[1]-c,y=2*(f*d-g*v),m=f*f+g*g,_=v*v+d*d,x=[(d*m-g*_)/y+h,(f*_-v*m)/y+c];Ul(n.edge,l,p,x),u.edge=jl(l,t,null,x),n.edge=jl(t,p,null,x),eh(e),eh(n)}else u.edge=jl(e.site,u.site)}}function lh(t,e){var n=t.site,r=n[0],i=n[1],o=i-e;if(!o)return r;var s=t.P;if(!s)return-1/0;var a=(n=s.site)[0],u=n[1],l=u-e;if(!l)return a;var h=a-r,c=1/o-1/l,f=h/l;return c?(-f+Math.sqrt(f*f-2*c*(h*h/(-2*l)-u+l/2+i-o/2)))/c+r:(r+a)/2}function hh(t,e){var n=t.N;if(n)return lh(n,e);var r=t.site;return r[1]===e?r[0]:1/0}var ch,fh,gh,ph,vh=1e-6,dh=1e-12;function yh(t,e){return e[1]-t[1]||e[0]-t[0]}function mh(t,e){var n,r,i,o=t.sort(yh).pop();for(ph=[],fh=new Array(t.length),ch=new Vl,gh=new Vl;;)if(i=Ql,o&&(!i||o[1]vh||Math.abs(i[0][1]-i[1][1])>vh)||delete ph[o]}(s,a,u,l),function(t,e,n,r){var i,o,s,a,u,l,h,c,f,g,p,v,d=fh.length,y=!0;for(i=0;ivh||Math.abs(v-f)>vh)&&(u.splice(a,0,ph.push(Xl(s,g,Math.abs(p-t)vh?[t,Math.abs(c-t)vh?[Math.abs(f-r)vh?[n,Math.abs(c-n)vh?[Math.abs(f-e)=a)return null;var u=t-i.site[0],l=e-i.site[1],h=u*u+l*l;do{i=o.cells[r=s],s=null,i.halfedges.forEach((function(n){var r=o.edges[n],a=r.left;if(a!==i.site&&a||(a=r.right)){var u=t-a[0],l=e-a[1],c=u*u+l*l;c2&&void 0!==arguments[2]?arguments[2]:{},r=rt(t).coordinates,i=0,o=0;o=i&&o===r.length-1);o++){if(i>=e){var s=e-i;if(s){var a=st(r[o],r[o-1])-180;return at(r[o],s,a,n)}return I(r[o])}i+=ut(r[o],r[o+1],n)}return I(r[r.length-1])},t.angle=function(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!Z(r))throw new Error("options is invalid");if(!t)throw new Error("startPoint is required");if(!e)throw new Error("midPoint is required");if(!n)throw new Error("endPoint is required");var i=t,o=e,s=n,a=G(!0!==r.mercator?st(o,i):lt(o,i)),u=G(!0!==r.mercator?st(o,s):lt(o,s));u1&&void 0!==arguments[1]?arguments[1]:{},n=e.resolution||1e4,r=e.sharpness||.85,i=[],o=rt(t).coordinates.map((function(t){return{x:t[0],y:t[1]}})),s=new Gt({duration:n,points:o,sharpness:r}),a=function(t){var e=s.pos(t);Math.floor(t/100)%2==0&&i.push([e.x,e.y])},u=0;u0;else if(n!==u>0)return!0}return!1},t.booleanContains=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type,s=n.coordinates,u=r.coordinates;switch(i){case"Point":if("Point"===o)return Ht(s,u);throw new Error("feature2 "+o+" geometry not supported");case"MultiPoint":switch(o){case"Point":return function(t,e){var n,r=!1;for(n=0;n2&&void 0!==arguments[2]?arguments[2]:{}).precision;if("number"!=typeof(n=null==n||isNaN(n)?6:n)||!(n>=0))throw new Error("precision must be a positive number");return rt(t).type===rt(e).type&&Ne(Le(t),Le(e),{precision:n})},t.booleanIntersects=Oe,t.booleanOverlap=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;if("MultiPoint"===i&&"MultiPoint"!==o||("LineString"===i||"MultiLineString"===i)&&"LineString"!==o&&"MultiLineString"!==o||("Polygon"===i||"MultiPolygon"===i)&&"Polygon"!==o&&"MultiPolygon"!==o)throw new Error("features must be of the same type");if("Point"===i)throw new Error("Point geometry not supported");if(Ne(t,e,{precision:6}))return!1;var s=0;switch(i){case"MultiPoint":for(var a=0;a0},t.booleanParallel=function(t,e){if(!t)throw new Error("line1 is required");if(!e)throw new Error("line2 is required");if("LineString"!==In(t,"line1"))throw new Error("line1 must be a LineString");if("LineString"!==In(e,"line2"))throw new Error("line2 must be a LineString");for(var n=$e(Le(t)).features,r=$e(Le(e)).features,i=0;i1;case"MultiPoint":for(var i=0;i0&&ue(S([r[0]]),S([r[i]])).features.length>1)return!1}return!0;case"MultiPolygon":for(i=0;i0&&ue(S([o[0]]),S([o[s]])).features.length>1)return!1}return!0;default:return!1}},t.booleanWithin=Cn,t.buffer=function(t,e,n){var r=(n=n||{}).units||"kilometers",i=n.steps||8;if(!t)throw new Error("geojson is required");if("object"!==m(n))throw new Error("options must be an object");if("number"!=typeof i)throw new Error("steps must be an number");if(void 0===e)throw new Error("radius is required");if(i<=0)throw new Error("steps must be greater than 0");var o=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){var n=ui(t,e,r,i);n&&o.push(n)})),C(o);case"FeatureCollection":return vt(t,(function(t){var n=ui(t,e,r,i);n&&vt(n,(function(t){t&&o.push(t)}))})),C(o)}return ui(t,e,r,i)},t.center=An,t.centerMean=fi,t.centerMedian=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.counter||10;if(!U(n))throw new Error("counter must be a number");var r=e.weight,i=fi(t,{weight:e.weight}),o=C([]);vt(t,(function(t){var e;o.features.push(gi(t,{properties:{weight:null==(e=t.properties)?void 0:e[r]}}))}));var s={tolerance:e.tolerance,medianCandidates:[]};return pi(i.geometry.coordinates,[0,0],o,s,n)},t.centerOfMass=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(it(e)){case"Point":return I(K(e),n.properties);case"Polygon":var r=[];ct(e,(function(t){r.push(t)}));var i,o,s,a,u,l,h,c,f=gi(e,{properties:n.properties}),g=f.geometry.coordinates,p=0,v=0,d=0,y=r.map((function(t){return[t[0]-g[0],t[1]-g[1]]}));for(i=0;i2&&void 0!==arguments[2]?arguments[2]:{};!0!==n.mutate&&(t=Ai(t));var r=n.minPoints||3,i=V(e,n.units),o=new to(t.features.length),s=t.features.map((function(t){return!1})),a=t.features.map((function(t){return!1})),u=t.features.map((function(t){return!1})),l=t.features.map((function(t){return-1}));o.load(t.features.map((function(t,e){var n=v(t.geometry.coordinates,2),r=n[0],i=n[1];return{minX:r,minY:i,maxX:r,maxY:i,index:e}})));var h=function(n){var r=t.features[n],s=v(r.geometry.coordinates,2),a=s[0],u=s[1],l=Math.max(u-i,-90),h=Math.min(u+i,90),c=l<0&&h>0?i:Math.abs(l)=r){var i=c;c++,s[e]=!0,function(t,e){for(var n=0;n=r&&e.push.apply(e,d(o))}a[i]||(a[i]=!0,l[i]=t)}}(i,n)}else u[e]=!0}})),t.features.forEach((function(e,n){var r=t.features[n];r.properties||(r.properties={}),l[n]>=0?(r.properties.dbscan=u[n]?"edge":"core",r.properties.cluster=l[n]):r.properties.dbscan="noise"})),t},t.clustersKmeans=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.features.length;e.numberOfClusters=e.numberOfClusters||Math.round(Math.sqrt(n/2)),e.numberOfClusters>n&&(e.numberOfClusters=n),!0!==e.mutate&&(t=Ai(t));var r=yt(t),i=r.slice(0,e.numberOfClusters),o=ro(r,e.numberOfClusters,i),s={};return o.centroids.forEach((function(t,e){s[e]=t})),vt(t,(function(t,e){var n=o.idxs[e];t.properties.cluster=n,t.properties.centroid=s[n]})),t},t.collect=function(t,e,n,r){var i=new io(6),o=e.features.map((function(t){var e;return{minX:t.geometry.coordinates[0],minY:t.geometry.coordinates[1],maxX:t.geometry.coordinates[0],maxY:t.geometry.coordinates[1],property:null==(e=t.properties)?void 0:e[n]}}));return i.load(o),t.features.forEach((function(t){t.properties||(t.properties={});var e=Rt(t),n=i.search({minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}),o=[];n.forEach((function(e){zt([e.minX,e.minY],t)&&o.push(e.property)})),t.properties[r]=o})),t},t.collectionOf=nt,t.combine=function(t){var e={MultiPoint:{coordinates:[],properties:[]},MultiLineString:{coordinates:[],properties:[]},MultiPolygon:{coordinates:[],properties:[]}};return vt(t,(function(t){var n,r,i,o;switch(null==(o=t.geometry)?void 0:o.type){case"Point":e.MultiPoint.coordinates.push(t.geometry.coordinates),e.MultiPoint.properties.push(t.properties);break;case"MultiPoint":(n=e.MultiPoint.coordinates).push.apply(n,d(t.geometry.coordinates)),e.MultiPoint.properties.push(t.properties);break;case"LineString":e.MultiLineString.coordinates.push(t.geometry.coordinates),e.MultiLineString.properties.push(t.properties);break;case"MultiLineString":(r=e.MultiLineString.coordinates).push.apply(r,d(t.geometry.coordinates)),e.MultiLineString.properties.push(t.properties);break;case"Polygon":e.MultiPolygon.coordinates.push(t.geometry.coordinates),e.MultiPolygon.properties.push(t.properties);break;case"MultiPolygon":(i=e.MultiPolygon.coordinates).push.apply(i,d(t.geometry.coordinates)),e.MultiPolygon.properties.push(t.properties)}})),C(Object.keys(e).filter((function(t){return e[t].coordinates.length})).sort().map((function(t){return b({type:t,coordinates:e[t].coordinates},{collectedProperties:e[t].properties})})))},t.concave=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.maxEdge||1/0,r=function(t){var e=[],n={};return vt(t,(function(t){if(t.geometry){var r=t.geometry.coordinates.join("-");Object.prototype.hasOwnProperty.call(n,r)||(e.push(t),n[r]=!0)}})),C(e)}(t),i=oo(r);if(i.features=i.features.filter((function(t){var r=t.geometry.coordinates[0][0],i=t.geometry.coordinates[0][1],o=t.geometry.coordinates[0][2],s=ut(r,i,e),a=ut(i,o,e),u=ut(r,o,e);return s<=n&&a<=n&&u<=n})),i.features.length<1)return null;var o=Ro(i);return 1===o.coordinates.length&&(o.coordinates=o.coordinates[0],o.type="Polygon"),b(o)},t.containsNumber=$,t.convertArea=X,t.convertLength=j,t.convex=Oi,t.coordAll=yt,t.coordEach=ct,t.coordReduce=ft,t.createBins=zi,t.degreesToRadians=z,t.destination=at,t.difference=function(t){var e=[];if(mt(t,(function(t){e.push(t.coordinates)})),e.length<2)throw new Error("Must have at least two features");var n=t.features[0].properties||{},r=As.apply(Fs,[e[0]].concat(d(e.slice(1))));return 0===r.length?null:1===r.length?S(r[0],n):R(r,n)},t.dissolve=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.propertyName;nt(t,"Polygon","dissolve");var r=[];if(!n)return qs(R(Os.apply(null,t.features.map((function(t){return t.geometry.coordinates})))));var i={};vt(t,(function(t){t.properties&&(Object.prototype.hasOwnProperty.call(i,t.properties[n])||(i[t.properties[n]]=[]),i[t.properties[n]].push(t))}));for(var o=Object.keys(i),s=0;s1&&void 0!==arguments[1]?arguments[1]:{},o=i.properties,s=null==(e=i.autoComplete)||e,a=null==(n=i.orderCoords)||n;if(null!=(r=i.mutate)&&r||(t=Ai(t)),"FeatureCollection"===t.type){var u=[];return t.features.forEach((function(t){u.push(Q(ru(t,{},s,a)))})),R(u,o)}return ru(t,o,s,a)},t.mask=function(t,e,n){var r,i=null!=(r=null==n?void 0:n.mutate)&&r,o=e;e&&!1===i&&(o=Ai(e));var s,a=su(o);return("FeatureCollection"===t.type?ou(2===(s=t).features.length?Os(s.features[0].geometry.coordinates,s.features[1].geometry.coordinates):Os.apply(Fs,s.features.map((function(t){return t.geometry.coordinates})))):"Feature"===t.type?ou(Os(t.geometry.coordinates)):ou(Os(t.coordinates))).geometry.coordinates.forEach((function(t){a.geometry.coordinates.push(t[0])})),a},t.meta=Mt,t.midpoint=function(t,e){return at(t,ut(t,e)/2,st(t,e))},t.moranIndex=function(t,e){var n,r,i=e.inputField,o=e.threshold||1e5,s=e.p||2,u=null!=(n=e.binary)&&n,l=Gs(t,{alpha:e.alpha||-1,binary:u,p:s,standardization:null==(r=e.standardization)||r,threshold:o}),h=[];vt(t,(function(t){var e=t.properties||{};h.push(e[i])}));for(var c=au(h),f=function(t){var e,n=au(t),r=0,i=a(t);try{for(i.s();!(e=i.n()).done;){var o=e.value;r+=Math.pow(o-n,2)}}catch(t){i.e(t)}finally{i.f()}return r/t.length}(h),g=0,p=0,v=0,d=0,y=l.length,m=0;m2&&void 0!==arguments[2]?arguments[2]:{},r=n.units,i=n.properties||{},o=function(t){var e=[];switch(t.geometry?t.geometry.type:t.type){case"GeometryCollection":return mt(t,(function(t){"Point"===t.type&&e.push({type:"Feature",properties:{},geometry:t})})),{type:"FeatureCollection",features:e};case"FeatureCollection":return t.features=t.features.filter((function(t){return"Point"===t.geometry.type})),t;default:throw new Error("points must be a Point Collection")}}(t);if(!o.features.length)throw new Error("points must contain features");if(!e)throw new Error("line is required");if("LineString"!==it(e))throw new Error("line must be a LineString");var s=1/0,a=null;return vt(o,(function(t){var n=mu(t,e,{units:r});n2&&void 0!==arguments[2]?arguments[2]:{},a=null!=(i=s.method)?i:"geodesic",u=null!=(o=s.units)?o:"kilometers";if(!e)throw new Error("point is required");if(!r)throw new Error("polygon or multi-polygon is required");var l,h=rt(r);if("MultiPolygon"===h.type){var c=h.coordinates.map((function(n){return t(e,S(n),{method:a,units:u})}));return Math.min.apply(Math,d(c.map(Math.abs)))*(zt(e,r)?-1:1)}if(h.coordinates.length>1){var p=h.coordinates.map((function(n){return t(e,S([n]),{method:a,units:u})})),v=n(l=p)||f(l)||_(l)||g(),y=v[0],m=v.slice(1);if(y>=0)return y;var x=Math.min.apply(Math,d(m));return x<0?Math.abs(x):Math.min(x,Math.abs(y))}var E=le(h),k=1/0;return xt(E,(function(t){k=Math.min(k,mu(e,t,{method:a,units:u}))})),zt(e,h)?-k:k},t.points=N,t.pointsWithinPolygon=Su,t.polygon=S,t.polygonSmooth=function(t,e){(e=e||{}).iterations=e.iterations||1;var n=e.iterations,r=[];if(!t)throw new Error("inputPolys is required");return mt(t,(function(t,e,i){if("Polygon"===t.type){for(var o=[[]],s=0;s0&&(u=S(o).geometry),Ru(u,a),o=a.slice(0)}r.push(S(o,i))}else{if("MultiPolygon"!==t.type)throw new Error("geometry is invalid, must be Polygon or MultiPolygon");for(var l=[[[]]],h=0;h0&&(f=R(l).geometry),Au(f,c),l=c.slice(0)}r.push(R(l,i))}})),C(r)},t.polygonTangents=function(t,e){var n,r=Q(t),i=Q(e),o=[],s=[],a=Rt(e),u=0,l=null;switch(r[0]>a[0]&&r[0]a[1]&&r[1]_&&(_=k)}for(var b=[],w=Object.keys(l).length,I=f/w,N=0,S=0;S<_+1;S++)N+=Math.exp(-I)*Math.pow(I,S)/Zu(S),b.push(N);for(var M=[],L=0,P=0;P<_+1;P++){for(var C=0,T=Object.keys(l);CR&&(R=D)}var F=Xu[r]/Math.sqrt(w),q={criticalValue:F,isRandom:!0,maxAbsoluteDifference:R,observedDistribution:M};return R>F&&(q.isRandom=!1),q},t.radiansToDegrees=Y,t.radiansToLength=F,t.random=nl,t.randomLineString=$u,t.randomPoint=Ku,t.randomPolygon=Qu,t.randomPosition=Hu,t.rectangleGrid=oa,t.rewind=function(t){var e,n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(r=r||{}))throw new Error("options is invalid");var i=null!=(e=r.mutate)&&e,o=null!=(n=r.reverse)&&n;if(!t)throw new Error(" is required");if("boolean"!=typeof o)throw new Error(" must be a boolean");if("boolean"!=typeof i)throw new Error(" must be a boolean");i||"Point"===t.type||"MultiPoint"===t.type||(t=Ai(t));var s=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){rl(t,o)})),t;case"FeatureCollection":return vt(t,(function(t){vt(rl(t,o),(function(t){s.push(t)}))})),C(s)}return rl(t,o)},t.rhumbBearing=lt,t.rhumbDestination=Bs,t.rhumbDistance=Ys,t.round=D,t.sample=function(t,e){if(!t)throw new Error("fc is required");if(null==e)throw new Error("num is required");if("number"!=typeof e)throw new Error("num must be a number");var n=C(function(t,e){var n,r,i=t.slice(0),o=t.length,s=o-e;for(;o-- >s;)n=i[r=Math.floor((o+1)*Math.random())],i[r]=i[o],i[o]=n;return i.slice(s)}(t.features,e));return n},t.sector=function(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!Z(i=i||{}))throw new Error("options is invalid");var o=i.properties;if(!t)throw new Error("center is required");if(null==n)throw new Error("bearing1 is required");if(null==r)throw new Error("bearing2 is required");if(!e)throw new Error("radius is required");if("object"!==m(i))throw new Error("options must be an object");if(sl(n)===sl(r))return Ri(t,e,i);var s=Q(t),a=ja(t,e,n,r,i),u=[[s]];return ct(a,(function(t){u[0].push(t)})),u[0].push(s),S(u,o)},t.segmentEach=kt,t.segmentReduce=bt,t.shortestPath=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.obstacles||C([]),i=n.resolution||100;if(!t)throw new Error("start is required");if(!e)throw new Error("end is required");if(i&&(!U(i)||i<=0))throw new Error("options.resolution must be a number, greater than 0");var o=K(t),s=K(e);if(t=I(o),e=I(s),"FeatureCollection"===r.type){if(0===r.features.length)return L([o,s])}else{if("Polygon"!==r.type)throw new Error("invalid obstacles");r=C([b(rt(r))])}var a=r;a.features.push(t),a.features.push(e);var u=v(Rt(al(Vt(Rt(a)),1.15)),4),l=u[0],h=u[1],c=u[2],f=u[3],g=ut([l,h],[c,h],n)/i;a.features.pop(),a.features.pop();for(var p,d,y=g/ut([l,h],[c,h],n)*(c-l),m=g/ut([l,h],[l,f],n)*(f-h),_=c-l,x=f-h,E=Math.floor(_/y),k=Math.floor(x/m),w=(_-E*y)/2,N=[],S=[],M=1/0,P=1/0,T=f-(x-k*m)/2,O=0;T>=h;){for(var R=[],A=[],D=l+w,F=0;D<=c;){var q=I([D,T]),V=pl(q,r);R.push(V?0:1),A.push(D+"|"+T);var G=ut(q,t);!V&&G1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(i=null!=i?i:{}))throw new Error("options is invalid");var o=null!=(e=i.tolerance)?e:1,s=null!=(n=i.highQuality)&&n,a=null!=(r=i.mutate)&&r;if(!t)throw new Error("geojson is required");if(o&&o<0)throw new Error("invalid tolerance");return!0!==a&&(t=Ai(t)),mt(t,(function(t){!function(t,e,n){var r=t.type;if("Point"===r||"MultiPoint"===r)return t;if(Le(t,{mutate:!0}),"GeometryCollection"!==r)switch(r){case"LineString":t.coordinates=ml(t.coordinates,e,n);break;case"MultiLineString":t.coordinates=t.coordinates.map((function(t){return ml(t,e,n)}));break;case"Polygon":t.coordinates=_l(t.coordinates,e,n);break;case"MultiPolygon":t.coordinates=t.coordinates.map((function(t){return _l(t,e,n)}))}}(t,o,s)})),t},t.square=Ka,t.squareGrid=sa,t.standardDeviationalEllipse=function(t,e){var n;if(!Z(e=e||{}))throw new Error("options is invalid");var r=e.steps||64,i=e.weight,o=e.properties||{};if(!U(r))throw new Error("steps must be a number");if(!Z(o))throw new Error("properties must be a number");var s=yt(t).length,a=fi(t,{weight:i}),u=0,l=0,h=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));u+=Math.pow(r.x,2)*n,l+=Math.pow(r.y,2)*n,h+=r.x*r.y*n}));var c=u-l,f=Math.sqrt(Math.pow(c,2)+4*Math.pow(h,2)),g=2*h,p=Math.atan((c+f)/g),v=180*p/Math.PI,d=0,y=0,m=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));d+=Math.pow(r.x*Math.cos(p)-r.y*Math.sin(p),2)*n,y+=Math.pow(r.x*Math.sin(p)+r.y*Math.cos(p),2)*n,m+=n}));var _=Math.sqrt(2*d/m),x=Math.sqrt(2*y/m),E=js(a,_,x,{units:"degrees",angle:v,steps:r,properties:o}),k=Su(t,C([E])),b={meanCenterCoordinates:Q(a),semiMajorAxis:_,semiMinorAxis:x,numberOfFeatures:s,angle:v,percentageWithinEllipse:100*yt(k).length/s};return E.properties=null!=(n=E.properties)?n:{},E.properties.standardDeviationalEllipse=b,E},t.tag=function(t,e,n,r){return t=Ai(t),e=Ai(e),vt(t,(function(t){t.properties||(t.properties={}),vt(e,(function(e){t.properties&&e.properties&&void 0===t.properties[r]&&zt(t,e)&&(t.properties[r]=e.properties[n])}))})),t},t.tesselate=function(t){if(!t.geometry||"Polygon"!==t.geometry.type&&"MultiPolygon"!==t.geometry.type)throw new Error("input must be a Polygon or MultiPolygon");var e={type:"FeatureCollection",features:[]};return"Polygon"===t.geometry.type?e.features=Nl(t.geometry.coordinates):t.geometry.coordinates.forEach((function(t){e.features=e.features.concat(Nl(t))})),e},t.tin=oo,t.toMercator=Vu,t.toWgs84=Gu,t.transformRotate=zs,t.transformScale=al,t.transformTranslate=function(t,e,n,r){if(!Z(r=r||{}))throw new Error("options is invalid");var i=r.units,o=r.zTranslation,s=r.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("distance is required");if(o&&"number"!=typeof o&&isNaN(o))throw new Error("zTranslation is not a number");if(o=void 0!==o?o:0,0===e&&0===o)return t;if(null==n||isNaN(n))throw new Error("direction is required");return e<0&&(e=-e,n+=180),!1!==s&&void 0!==s||(t=Ai(t)),ct(t,(function(t){var r=Q(Bs(t,e,n,{units:i}));t[0]=r[0],t[1]=r[1],o&&3===t.length&&(t[2]+=o)})),t},t.triangleGrid=aa,t.truncate=Qa,t.union=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must have at least 2 geometries");var r=Os.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)},t.unkinkPolygon=function(t){var e=[];return xt(t,(function(t){"Polygon"===t.geometry.type&&vt(Ll(t),(function(n){e.push(S(n.geometry.coordinates,t.properties))}))})),C(e)},t.validateBBox=H,t.validateId=W,t.voronoi=function(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox||[-180,-85,180,85];if(!t)throw new Error("points is required");if(!Array.isArray(n))throw new Error("bbox is invalid");return nt(t,"Point","points"),C(function(){var t=Fl,e=ql,n=null;function r(r){return new mh(r.map((function(n,i){var o=[Math.round(t(n,i,r)/vh)*vh,Math.round(e(n,i,r)/vh)*vh];return o.index=i,o.data=n,o})),n)}return r.polygons=function(t){return r(t).polygons()},r.links=function(t){return r(t).links()},r.triangles=function(t){return r(t).triangles()},r.x=function(e){return arguments.length?(t="function"==typeof e?e:Dl(+e),r):t},r.y=function(t){return arguments.length?(e="function"==typeof t?t:Dl(+t),r):e},r.extent=function(t){return arguments.length?(n=null==t?null:[[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]],r):n&&[[n[0][0],n[0][1]],[n[1][0],n[1][1]]]},r.size=function(t){return arguments.length?(n=null==t?null:[[0,0],[+t[0],+t[1]]],r):n&&[n[1][0]-n[0][0],n[1][1]-n[0][1]]},r}().x((function(t){return t.geometry.coordinates[0]})).y((function(t){return t.geometry.coordinates[1]})).extent([[n[0],n[1]],[n[2],n[3]]]).polygons(t.features).map((function(e,n){return Object.assign(function(t){return(t=t.slice()).push(t[0]),S([t])}(e),{properties:Fi(t.features[n].properties)})})))}})); diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl.js b/docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl.js new file mode 100644 index 0000000..c0d6d59 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl.js @@ -0,0 +1,3910 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl.yaml b/docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl.yaml new file mode 100644 index 0000000..6a5c2f7 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl.yaml @@ -0,0 +1,65 @@ +dependencies: + - name: mapbox-gl-js + version: "3.15.0" + src: + href: "https://api.mapbox.com/mapbox-gl-js/v3.15.0/" + script: + - "mapbox-gl.js" + stylesheet: + - "mapbox-gl.css" + - name: mapbox-gl-draw + version: "1.5.0" + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.5.0/" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: mapbox-gl-geocoder + version: 5.0.0 + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/" + script: + - "mapbox-gl-geocoder.min.js" + stylesheet: + - "mapbox-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: mapbox-pmtiles + version: 1.1.0 + src: "htmlwidgets/lib/mapbox-pmtiles" + script: + - "pmtiles-source-optimized-v2.js" + - name: turf + version: "7.2.0" + src: "htmlwidgets/lib/turf" + script: + - "turf.min.js" + - name: turf-operations + version: "1.0.0" + src: "htmlwidgets" + script: + - "turf-operations.js" diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl_compare.js b/docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl_compare.js new file mode 100644 index 0000000..780fbd6 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl_compare.js @@ -0,0 +1,3192 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +HTMLWidgets.widget({ + name: "mapboxgl_compare", + + type: "output", + + factory: function (el, width, height) { + // Store maps and compare object to allow access during Shiny updates + let beforeMap, afterMap, compareControl, draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + if (typeof mapboxgl.Compare === "undefined") { + console.error("Mapbox GL Compare plugin is not loaded."); + return; + } + + // Register PMTiles source type if available + if (typeof MapboxPmTilesSource !== "undefined" && typeof pmtiles !== "undefined") { + try { + mapboxgl.Style.setSourceType(PMTILES_SOURCE_TYPE, MapboxPmTilesSource); + console.log("PMTiles support enabled for Mapbox GL JS Compare"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + // Create container divs for the maps + const beforeContainerId = `${el.id}-before`; + const afterContainerId = `${el.id}-after`; + + // Different HTML structure based on mode + if (x.mode === "sync") { + // Side-by-side sync mode + const containerStyle = + x.orientation === "horizontal" + ? `display: flex; flex-direction: column; width: 100%; height: 100%;` + : `display: flex; flex-direction: row; width: 100%; height: 100%;`; + + const mapStyle = + x.orientation === "horizontal" + ? `width: 100%; height: 50%; position: relative;` + : `width: 50%; height: 100%; position: relative;`; + + el.innerHTML = ` +
+
+
+
+ `; + } else { + // Default swipe mode + el.innerHTML = ` +
+
+ `; + } + + beforeMap = new mapboxgl.Map({ + container: beforeContainerId, + style: x.map1.style, + center: x.map1.center, + zoom: x.map1.zoom, + bearing: x.map1.bearing, + pitch: x.map1.pitch, + projection: x.map1.projection, + accessToken: x.map1.access_token, + ...x.map1.additional_params, + }); + + afterMap = new mapboxgl.Map({ + container: afterContainerId, + style: x.map2.style, + center: x.map2.center, + zoom: x.map2.zoom, + bearing: x.map2.bearing, + pitch: x.map2.pitch, + projection: x.map2.projection, + accessToken: x.map2.access_token, + ...x.map2.additional_params, + }); + + // Set the global access token + mapboxgl.accessToken = x.map1.access_token; + + if (x.mode === "swipe") { + // Only create the swiper in swipe mode + compareControl = new mapboxgl.Compare( + beforeMap, + afterMap, + `#${el.id}`, + { + mousemove: x.mousemove, + orientation: x.orientation, + }, + ); + + // Apply custom swiper color if provided + if (x.swiper_color) { + const swiperSelector = + x.orientation === "vertical" + ? ".mapboxgl-compare .compare-swiper-vertical" + : ".mapboxgl-compare .compare-swiper-horizontal"; + + const styleEl = document.createElement("style"); + styleEl.innerHTML = `${swiperSelector} { background-color: ${x.swiper_color}; }`; + document.head.appendChild(styleEl); + } + } else { + // For sync mode, we directly leverage the sync-move module's approach + + // Function to synchronize maps as seen in the mapbox-gl-sync-move module + const syncMaps = () => { + // Array of maps to sync + const maps = [beforeMap, afterMap]; + // Array of move event handlers + const moveHandlers = []; + + // Setup the sync between maps + maps.forEach((map, index) => { + // Create a handler for each map that syncs all other maps + moveHandlers[index] = (e) => { + // Disable all move events temporarily + maps.forEach((m, i) => { + m.off("move", moveHandlers[i]); + }); + + // Get the state from the map that triggered the event + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Apply this state to all other maps + maps + .filter((m, i) => i !== index) + .forEach((m) => { + m.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + }); + + // Re-enable move events + maps.forEach((m, i) => { + m.on("move", moveHandlers[i]); + }); + }; + + // Add the move handler to each map + map.on("move", moveHandlers[index]); + }); + }; + + // Initialize the sync + syncMaps(); + } + + // Ensure both maps resize correctly + beforeMap.on("load", function () { + beforeMap.resize(); + applyMapModifications(beforeMap, x.map1); + + // Setup Shiny event handlers for the before map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(beforeMap, el.id, "before"); + } + }); + + afterMap.on("load", function () { + afterMap.resize(); + applyMapModifications(afterMap, x.map2); + + // Setup Shiny event handlers for the after map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(afterMap, el.id, "after"); + } + + // Add compare-level legends after both maps are loaded + if (x.compare_legends && Array.isArray(x.compare_legends)) { + x.compare_legends.forEach(function(legendInfo) { + // Add CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendInfo.css; + legendCss.setAttribute("data-mapgl-legend-css", el.id); + document.head.appendChild(legendCss); + + // Create legend element + const legend = document.createElement("div"); + legend.innerHTML = legendInfo.html; + legend.classList.add("mapboxgl-legend"); + + // Append to the appropriate container based on target + if (legendInfo.target === "compare") { + // Append to the main compare container + el.appendChild(legend); + } else if (legendInfo.target === "before") { + // Append to the before map container + beforeMap.getContainer().appendChild(legend); + } else if (legendInfo.target === "after") { + // Append to the after map container + afterMap.getContainer().appendChild(legend); + } + }); + } + }); + + // Handle Shiny messages + if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler( + "mapboxgl-compare-proxy", + function (data) { + if (data.id !== el.id) return; + + // Get the message and determine which map to target + var message = data.message; + var map = message.map === "before" ? beforeMap : afterMap; + + if (!map) return; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Process the message based on type + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup( + e, + map, + message.layer.popup, + message.layer.id, + ); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = + clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + message.layer.tooltip, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error( + "Failed to add layer via proxy: ", + message.layer, + e, + ); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if ( + window._mapboxPopups && + window._mapboxPopups[message.layer_id] + ) { + window._mapboxPopups[message.layer_id].remove(); + delete window._mapboxPopups[message.layer_id]; + } + + if (map.getLayer(message.layer_id)) { + // Remove tooltip handlers + if ( + window._mapboxHandlers && + window._mapboxHandlers[message.layer_id] + ) { + const handlers = window._mapboxHandlers[message.layer_id]; + if (handlers.mousemove) { + map.off( + "mousemove", + message.layer_id, + handlers.mousemove, + ); + } + if (handlers.mouseleave) { + map.off( + "mouseleave", + message.layer_id, + handlers.mouseleave, + ); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer_id]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer_id] + ) { + map.off( + "click", + message.layer_id, + window._mapboxClickHandlers[message.layer_id], + ); + delete window._mapboxClickHandlers[message.layer_id]; + } + + // Remove the layer + map.removeLayer(message.layer_id); + } + if (map.getSource(message.layer_id)) { + map.removeSource(message.layer_id); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer_id]; + delete layerState.paintProperties[message.layer_id]; + delete layerState.layoutProperties[message.layer_id]; + delete layerState.tooltips[message.layer_id]; + delete layerState.popups[message.layer_id]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty( + message.layer, + message.name, + message.value, + ); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "add_legend") { + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + + // Append legend to the correct map container + const targetContainer = map.getContainer(); + targetContainer.appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Save the current view state + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Apply the new style + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + map.off("mousemove", layerId); + map.off("mouseleave", layerId); + + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on("mousemove", layerId, function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }); + + map.on("mouseleave", layerId, function () { + onMouseLeaveTooltip(map, tooltip); + }); + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + delete window._mapboxClickHandlers[layerId]; + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + + // Restore the view state after the style has loaded + map.once("style.load", function () { + map.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + + // Re-apply map modifications + if (map === beforeMap) { + applyMapModifications(map, x.map1); + } else { + applyMapModifications(map, x.map2); + } + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "navigation", control: nav }); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + customControlContainer.innerHTML = controlOptions.html; + customControlContainer.className = "mapboxgl-ctrl"; + if (controlOptions.className) { + customControlContainer.className += " " + controlOptions.className; + } + + // Create the custom control object + const customControl = { + onAdd: function(map) { + return customControlContainer; + }, + onRemove: function() { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild(customControlContainer); + } + } + }; + + map.addControl(customControl, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + + // Store control with proper type + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = + "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + const resetControlObj = { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }; + + map.addControl(resetControlObj, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "reset", control: resetControlObj }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(draw, message.source, map); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + if (map._mapgl_draw) { + const features = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + if (draw) { + if (map._mapgl_draw) map._mapgl_draw.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + if (draw) { + if (message.data.clear_existing) { + if (map._mapgl_draw) map._mapgl_draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "fullscreen", control: fullscreen }); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "scale", control: scaleControl }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(data.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(data.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(data.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(data.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "geolocate", control: geolocate }); + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "geocoder", control: geocoder }); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + + // Handle use_icon parameter + let className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + + if (message.use_icon) { + className += " icon-only"; + } + + layersControl.className = className; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `.layers-control { background-color: ${colors.background} !important; }`; + } + if (colors.text) { + css += `.layers-control a { color: ${colors.text} !important; }`; + } + if (colors.activeBackground) { + css += `.layers-control a.active { background-color: ${colors.activeBackground} !important; }`; + } + if (colors.activeText) { + css += `.layers-control a.active { color: ${colors.activeText} !important; }`; + } + if (colors.hoverBackground) { + css += `.layers-control a:hover { background-color: ${colors.hoverBackground} !important; }`; + } + if (colors.hoverText) { + css += `.layers-control a:hover { color: ${colors.hoverText} !important; }`; + } + if (colors.toggleButtonBackground) { + css += `.layers-control .toggle-button { background-color: ${colors.toggleButtonBackground} + !important; }`; + } + if (colors.toggleButtonText) { + css += `.layers-control .toggle-button { color: ${colors.toggleButtonText} !important; }`; + } + + styleEl.innerHTML = css; + document.head.appendChild(styleEl); + } + + document.getElementById(data.id).appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + message.layers || + map.getStyle().layers.map((layer) => layer.id); + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + toggleButton.textContent = "Layers"; + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "layers", control: layersControl }); + } else if (message.type === "add_globe_minimap") { + // Add the globe minimap control + const minimap = new MapboxGlobeMinimap({ + center: map.getCenter(), + zoom: map.getZoom(), + bearing: map.getBearing(), + pitch: map.getPitch(), + globeSize: message.globe_size, + landColor: message.land_color, + waterColor: message.water_color, + markerColor: message.marker_color, + markerSize: message.marker_size, + }); + + map.addControl(minimap, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "globe_minimap", control: minimap }); + } else if (message.type === "set_rain") { + if (message.rain) { + map.setRain(message.rain); + } else { + map.setRain(null); + } + } else if (message.type === "set_snow") { + if (message.snow) { + map.setSnow(message.snow); + } else { + map.setSnow(null); + } + } else if (message.type === "set_projection") { + map.setProjection(message.projection); + } else if (message.type === "set_source") { + if (map.getLayer(message.layer)) { + const sourceId = map.getLayer(message.layer).source; + map.getSource(sourceId).setData(JSON.parse(message.source)); + } + } else if (message.type === "set_tooltip") { + // Track tooltip state + layerState.tooltips[message.layer] = message.tooltip; + + if (map.getLayer(message.layer)) { + // Remove any existing tooltip handlers + map.off("mousemove", message.layer); + map.off("mouseleave", message.layer); + + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on("mousemove", message.layer, function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[message.tooltip]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }); + + map.on("mouseleave", message.layer, function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }); + } + } else if (message.type === "set_popup") { + // Track popup state + layerState.popups[message.layer] = message.popup; + + if (map.getLayer(message.layer)) { + // Remove any existing popup click handlers for this layer + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove any existing popup for this layer + if ( + window._mapboxPopups && + window._mapboxPopups[message.layer] + ) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Create new click handler for popup + const clickHandler = function (e) { + onClickPopup(e, map, message.popup, message.layer); + }; + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer] = clickHandler; + + // Add click handler + map.on("click", message.layer, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer, function () { + map.getCanvas().style.cursor = ""; + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } + } else if (message.type === "set_opacity") { + // Set opacity for all fill layers + const style = map.getStyle(); + if (style && style.layers) { + style.layers.forEach(function (layer) { + if (layer.type === "fill" && map.getLayer(layer.id)) { + map.setPaintProperty( + layer.id, + "fill-opacity", + message.opacity, + ); + } + }); + } + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection) + ); + } else if (message.type === "clear_controls") { + // Handle clear_controls for compare widgets + if (!message.controls || message.controls.length === 0) { + // Clear all controls + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + } + } + }, + ); + } + + function setupShinyEvents(map, parentId, mapType) { + // Set view state on move end + map.on("moveend", function () { + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_view", { + center: [center.lng, center.lat], + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + } + }); + + // Send clicked point coordinates to Shiny + map.on("click", function (e) { + // Check if this map's draw control is active and in a drawing mode + let isDrawing = false; + if (map._mapgl_draw && map._mapgl_draw.getMode) { + const mode = map._mapgl_draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + // Filter out draw layers + const nonDrawFeatures = features.filter(feature => + !feature.layer.id.includes('gl-draw') && + !feature.source.includes('gl-draw') + ); + + if (nonDrawFeatures.length > 0) { + const feature = nonDrawFeatures[0]; + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }); + } + } else { + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_feature_click", null); + } + } + } + + // Always send regular click event + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }); + } + }); + + // Add hover events if enabled for this map + const mapConfig = (mapType === "before") ? x.map1 : x.map2; + if (mapConfig.hover_events && mapConfig.hover_events.enabled) { + map.on("mousemove", function (e) { + if (window.Shiny) { + // Feature hover events + if (mapConfig.hover_events.features) { + const options = mapConfig.hover_events.layer_id + ? { layers: Array.isArray(mapConfig.hover_events.layer_id) + ? mapConfig.hover_events.layer_id + : mapConfig.hover_events.layer_id.split(',').map(id => id.trim()) } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if(features.length > 0) { + const feature = features[0]; + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } else { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + null + ); + } + } + + // Coordinate hover events + if (mapConfig.hover_events.coordinates) { + Shiny.setInputValue( + parentId + "_" + mapType + "_hover", + { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } + } + }); + } + } + + function applyMapModifications(map, mapData) { + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + // Note: tooltip handlers are already defined at the top of the file + + // Set config properties if provided + if (mapData.config_properties) { + mapData.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + // Process H3J sources if provided + if (mapData.h3j_sources) { + mapData.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + }); + } + + if (mapData.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + mapData.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setText(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + } + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + } + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (mapData.sources) { + mapData.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceConfig = { + type: "vector", + url: source.url, + }; + if (source.promoteId) { + sourceConfig.promoteId = source.promoteId; + } + map.addSource(source.id, sourceConfig); + } else if (source.type === "geojson") { + const geojsonData = source.data; + map.addSource(source.id, { + type: "geojson", + data: geojsonData, + generateId: true, + }); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + // Add layers if provided + if (mapData.layers) { + mapData.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + map.on("click", layer.id, function (e) { + const description = e.features[0].properties[layer.popup]; + + new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = e.features[0].id; + map.setFeatureState( + { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: true }, + ); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Set terrain if provided + if (mapData.terrain) { + map.setTerrain({ + source: mapData.terrain.source, + exaggeration: mapData.terrain.exaggeration, + }); + } + + // Set fog + if (mapData.fog) { + map.setFog(mapData.fog); + } + + // Set rain effect if provided + if (mapData.rain) { + map.setRain(mapData.rain); + } + + // Set snow effect if provided + if (mapData.snow) { + map.setSnow(mapData.snow); + } + + if (mapData.fitBounds) { + map.fitBounds(mapData.fitBounds.bounds, mapData.fitBounds.options); + } + if (mapData.flyTo) { + map.flyTo(mapData.flyTo); + } + if (mapData.easeTo) { + map.easeTo(mapData.easeTo); + } + if (mapData.setCenter) { + map.setCenter(mapData.setCenter); + } + if (mapData.setZoom) { + map.setZoom(mapData.setZoom); + } + + // Apply moveLayer operations if provided + if (mapData.moveLayer) { + mapData.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + if (mapData.jumpTo) { + map.jumpTo(mapData.jumpTo); + } + + // Add custom images if provided + if (mapData.images && Array.isArray(mapData.images)) { + mapData.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (mapData.images) { + console.error("mapData.images is not an array:", mapData.images); + } + + // Remove existing legends only from this specific map container + const mapContainer = map.getContainer(); + const existingLegends = mapContainer.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + + // Don't remove all legend styles globally - they might belong to other maps + // Only remove styles when the entire widget is being recreated + + if (mapData.legend_html && mapData.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = mapData.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", el.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = mapData.legend_html; + legend.classList.add("mapboxgl-legend"); + + // Append legend to the correct map container instead of main container + const mapContainer = map.getContainer(); + mapContainer.appendChild(legend); + } + + // Add fullscreen control if enabled + if ( + mapData.fullscreen_control && + mapData.fullscreen_control.enabled + ) { + const position = mapData.fullscreen_control.position || "top-right"; + map.addControl(new mapboxgl.FullscreenControl(), position); + } + + // Add navigation control if enabled + if (mapData.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: mapData.navigation_control.show_compass, + showZoom: mapData.navigation_control.show_zoom, + visualizePitch: mapData.navigation_control.visualize_pitch, + }); + map.addControl(nav, mapData.navigation_control.position); + } + + // Add scale control if enabled + if (mapData.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: mapData.scale_control.maxWidth, + unit: mapData.scale_control.unit, + }); + map.addControl(scaleControl, mapData.scale_control.position); + map.controls.push(scaleControl); + } + + // Add geolocate control if enabled + if (mapData.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: mapData.geolocate_control.positionOptions, + trackUserLocation: mapData.geolocate_control.trackUserLocation, + showAccuracyCircle: mapData.geolocate_control.showAccuracyCircle, + showUserLocation: mapData.geolocate_control.showUserLocation, + showUserHeading: mapData.geolocate_control.showUserHeading, + fitBoundsOptions: mapData.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, mapData.geolocate_control.position); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Helper function to generate draw styles based on parameters + function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "midpoint"], + ], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: [ + "all", + ["==", "meta", "vertex"], + ["==", "$type", "Point"], + ], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: [ + "all", + ["==", "meta", "vertex"], + ["==", "$type", "Point"], + ], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } + } + + // Add geocoder control if enabled + if (mapData.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...mapData.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + mapData.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + + // Add draw control if enabled + if (mapData.draw_control) { + if (mapData.draw_control && mapData.draw_control.enabled) { + let drawOptions = mapData.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (mapData.draw_control.styling) { + const generatedStyles = generateDrawStyles( + mapData.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (mapData.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + mapData.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (mapData.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (mapData.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, mapData.draw_control.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add custom mode buttons and styling + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + + // Add rectangle styling and button + if (mapData.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + drawControl.changeMode('draw_rectangle'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + } + + // Add radius styling and button + if (mapData.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + drawControl.changeMode('draw_radius'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + } + }, 100); + + // Add initial features if provided + if (mapData.draw_control.source) { + addSourceFeaturesToDraw(drawControl, mapData.draw_control.source, map); + } + + // Process any queued features + if (mapData.draw_features_queue) { + mapData.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + if (map._mapgl_draw) map._mapgl_draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (mapData.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (mapData.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${mapData.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + // Helper function for updating drawn features + function updateDrawnFeatures() { + if (HTMLWidgets.shinyMode && map._mapgl_draw) { + const features = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(features), + ); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + } + + // Add reset control if enabled + if (mapData.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: mapData.reset_control.animate, + }; + + if (mapData.reset_control.duration) { + initialView.duration = mapData.reset_control.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + mapData.reset_control.position, + ); + } + + // Add the layers control if provided + if (mapData.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = mapData.layers_control.control_id; + + // Handle use_icon parameter + let className = mapData.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + + layersControl.className = className; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = mapData.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + mapData.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = mapData.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (mapData.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + if (mapData.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + } + }, + + resize: function (width, height) { + // Code to handle resizing if necessary + }, + }; + }, +}); diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl_compare.yaml b/docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl_compare.yaml new file mode 100644 index 0000000..55f1563 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/mapboxgl_compare.yaml @@ -0,0 +1,57 @@ +dependencies: + - name: mapbox-gl-js + version: "3.15.0" + src: + href: "https://api.mapbox.com/mapbox-gl-js/" + script: + - "v3.15.0/mapbox-gl.js" + - "plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.js" + stylesheet: + - "v3.15.0/mapbox-gl.css" + - "plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.css" + - name: mapbox-gl-draw + version: "1.4.3" + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: mapbox-gl-geocoder + version: 5.0.0 + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/" + script: + - "mapbox-gl-geocoder.min.js" + stylesheet: + - "mapbox-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: mapbox-pmtiles + version: 1.1.0 + src: "htmlwidgets/lib/mapbox-pmtiles" + script: + - "pmtiles-source-optimized-v2.js" diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/maplibregl.js b/docs/articles/map-design_files/turf-operations-1.0.0/maplibregl.js new file mode 100644 index 0000000..5937d02 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/maplibregl.js @@ -0,0 +1,5048 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + const result = originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + return result; + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse( + this.getAttribute("data-layer-ids"), + ); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } + } + }); +} diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/maplibregl.yaml b/docs/articles/map-design_files/turf-operations-1.0.0/maplibregl.yaml new file mode 100644 index 0000000..f6679e5 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/maplibregl.yaml @@ -0,0 +1,69 @@ +dependencies: + - name: maplibre-gl + version: "5.7.2" + src: "htmlwidgets/lib/maplibre-gl" + script: + - "maplibre-gl.js" + stylesheet: + - "maplibre-gl.css" + - name: mapbox-gl-draw + version: "1.5.0" + src: "htmlwidgets/lib/mapbox-gl-draw" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: maplibre-gl-geocoder + version: 1.5.0 + src: "htmlwidgets/lib/maplibre-gl-geocoder" + script: + - "maplibre-gl-geocoder.min.js" + stylesheet: + - "maplibre-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: h3j-h3t + version: 0.9.2 + src: "htmlwidgets/lib/h3j-h3t" + script: + - "h3j_h3t.js" + - name: maptiler-geocoding-control + version: 2.1.7 + src: "htmlwidgets/lib/maptiler-geocoding-control" + script: + - "maplibregl.umd.js" + stylesheet: + - "style.css" + - name: turf + version: "7.2.0" + src: "htmlwidgets/lib/turf" + script: + - "turf.min.js" + - name: turf-operations + version: "1.0.0" + src: "htmlwidgets" + script: + - "turf-operations.js" diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/maplibregl_compare.js b/docs/articles/map-design_files/turf-operations-1.0.0/maplibregl_compare.js new file mode 100644 index 0000000..a0e0caf --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/maplibregl_compare.js @@ -0,0 +1,4138 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case 'get': + return properties[expression[1]]; + case 'concat': + return expression.slice(1).map(item => evaluateExpression(item, properties)).join(''); + case 'to-string': + return String(evaluateExpression(expression[1], properties)); + case 'to-number': + return Number(evaluateExpression(expression[1], properties)); + case 'number-format': + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || 'en-US'; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty('min-fraction-digits')) { + formatOptions.minimumFractionDigits = options['min-fraction-digits']; + } + if (options.hasOwnProperty('max-fraction-digits')) { + formatOptions.maximumFractionDigits = options['max-fraction-digits']; + } + if (options.hasOwnProperty('min-integer-digits')) { + formatOptions.minimumIntegerDigits = options['min-integer-digits']; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty('useGrouping')) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(tooltipProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._maplibrePopups && window._maplibrePopups[layerId]) { + window._maplibrePopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._maplibrePopups) { + window._maplibrePopups = {}; + } + window._maplibrePopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on('close', function() { + if (window._maplibrePopups[layerId] === popup) { + delete window._maplibrePopups[layerId]; + } + }); +} + +HTMLWidgets.widget({ + name: "maplibregl_compare", + + type: "output", + + factory: function (el, width, height) { + // Store maps and compare object to allow access during Shiny updates + let beforeMap, afterMap, compareControl, draw; + + return { + renderValue: function (x) { + + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + if (typeof maplibregl.Compare === "undefined") { + console.error("Maplibre GL Compare plugin is not loaded."); + return; + } + + // Add PMTiles support + if (typeof pmtiles !== "undefined") { + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + } + + // Create container divs for the maps + const beforeContainerId = `${el.id}-before`; + const afterContainerId = `${el.id}-after`; + + // Different HTML structure based on mode + if (x.mode === "sync") { + // Side-by-side sync mode + const containerStyle = + x.orientation === "horizontal" + ? `display: flex; flex-direction: column; width: 100%; height: 100%;` + : `display: flex; flex-direction: row; width: 100%; height: 100%;`; + + const mapStyle = + x.orientation === "horizontal" + ? `width: 100%; height: 50%; position: relative;` + : `width: 50%; height: 100%; position: relative;`; + + el.innerHTML = ` +
+
+
+
+ `; + } else { + // Default swipe mode + el.innerHTML = ` +
+
+ `; + } + + beforeMap = new maplibregl.Map({ + container: beforeContainerId, + style: x.map1.style, + center: x.map1.center, + zoom: x.map1.zoom, + bearing: x.map1.bearing, + pitch: x.map1.pitch, + accessToken: x.map1.access_token, + ...x.map1.additional_params, + }); + + // Initialize controls array + beforeMap.controls = []; + + afterMap = new maplibregl.Map({ + container: afterContainerId, + style: x.map2.style, + center: x.map2.center, + zoom: x.map2.zoom, + bearing: x.map2.bearing, + pitch: x.map2.pitch, + accessToken: x.map2.access_token, + ...x.map2.additional_params, + }); + + // Initialize controls array + afterMap.controls = []; + + if (x.mode === "swipe") { + // Only create the swiper in swipe mode + compareControl = new maplibregl.Compare( + beforeMap, + afterMap, + `#${el.id}`, + { + mousemove: x.mousemove, + orientation: x.orientation, + }, + ); + + // Apply custom swiper color if provided + if (x.swiper_color) { + const swiperSelector = x.orientation === "vertical" ? + ".maplibregl-compare .compare-swiper-vertical" : + ".maplibregl-compare .compare-swiper-horizontal"; + + const styleEl = document.createElement('style'); + styleEl.innerHTML = `${swiperSelector} { background-color: ${x.swiper_color}; }`; + document.head.appendChild(styleEl); + } + } else { + // For sync mode, we directly leverage the sync-move module's approach + + // Function to synchronize maps as seen in the mapbox-gl-sync-move module + const syncMaps = () => { + // Array of maps to sync + const maps = [beforeMap, afterMap]; + // Array of move event handlers + const moveHandlers = []; + + // Setup the sync between maps + maps.forEach((map, index) => { + // Create a handler for each map that syncs all other maps + moveHandlers[index] = (e) => { + // Disable all move events temporarily + maps.forEach((m, i) => { + m.off("move", moveHandlers[i]); + }); + + // Get the state from the map that triggered the event + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Apply this state to all other maps + maps.filter((m, i) => i !== index).forEach( + (m) => { + m.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + }, + ); + + // Re-enable move events + maps.forEach((m, i) => { + m.on("move", moveHandlers[i]); + }); + }; + + // Add the move handler to each map + map.on("move", moveHandlers[index]); + }); + }; + + // Initialize the sync + syncMaps(); + } + + // Ensure both maps resize correctly + beforeMap.on("load", function () { + beforeMap.resize(); + applyMapModifications(beforeMap, x.map1); + + // Setup Shiny event handlers for the before map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(beforeMap, el.id, "before"); + } + }); + + afterMap.on("load", function () { + afterMap.resize(); + applyMapModifications(afterMap, x.map2); + + // Setup Shiny event handlers for the after map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(afterMap, el.id, "after"); + } + + // Add compare-level legends after both maps are loaded + if (x.compare_legends && Array.isArray(x.compare_legends)) { + x.compare_legends.forEach(function(legendInfo) { + // Add CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendInfo.css; + legendCss.setAttribute("data-mapgl-legend-css", el.id); + document.head.appendChild(legendCss); + + // Create legend element + const legend = document.createElement("div"); + legend.innerHTML = legendInfo.html; + legend.classList.add("mapboxgl-legend"); + + // Append to the appropriate container based on target + if (legendInfo.target === "compare") { + // Append to the main compare container + el.appendChild(legend); + } else if (legendInfo.target === "before") { + // Append to the before map container + beforeMap.getContainer().appendChild(legend); + } else if (legendInfo.target === "after") { + // Append to the after map container + afterMap.getContainer().appendChild(legend); + } + }); + } + }); + + // Define updateDrawnFeatures function for the draw tool + window.updateDrawnFeatures = function () { + if (draw) { + const features = draw.getAll(); + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(features), + ); + } + }; + + // Handle Shiny messages + if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler( + "maplibre-compare-proxy", + function (data) { + if (data.id !== el.id) return; + + // Get the message and determine which map to target + var message = data.message; + var map = + message.map === "before" ? beforeMap : afterMap; + + if (!map) return; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {} // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Process the message based on type + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "promoteId") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "data" && key !== "generateId") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "tiles" && key !== "tileSize" && key !== "maxzoom") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if ( + message.source.type === "raster-dem" + ) { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "tileSize" && key !== "maxzoom") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "coordinates") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "urls" && key !== "coordinates") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function(key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer( + message.layer, + message.layer.before_id, + ); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on( + "click", + message.layer.id, + clickHandler + ); + + // Change cursor to pointer when hovering over the layer + map.on( + "mouseenter", + message.layer.id, + function () { + map.getCanvas().style.cursor = + "pointer"; + }, + ); + + // Change cursor back to default when leaving the layer + map.on( + "mouseleave", + message.layer.id, + function () { + map.getCanvas().style.cursor = + ""; + }, + ); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + message.layer.tooltip, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on( + "mousemove", + message.layer.id, + mouseMoveHandler, + ); + map.on( + "mouseleave", + message.layer.id, + mouseLeaveHandler, + ); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[ + message.layer.id + ] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [ + key, + value, + ] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace( + /_/g, + "-", + ); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on( + "mousemove", + message.layer.id, + function (e) { + if (e.features.length > 0) { + if ( + hoveredFeatureId !== + null + ) { + const featureState = { + source: + typeof message + .layer + .source === + "string" + ? message + .layer + .source + : message + .layer + .id, + id: hoveredFeatureId, + }; + if ( + message.layer + .source_layer + ) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState( + featureState, + { + hover: false, + }, + ); + } + hoveredFeatureId = + e.features[0].id; + const featureState = { + source: + typeof message.layer + .source === + "string" + ? message.layer + .source + : message.layer + .id, + id: hoveredFeatureId, + }; + if ( + message.layer + .source_layer + ) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState( + featureState, + { + hover: true, + }, + ); + } + }, + ); + + map.on( + "mouseleave", + message.layer.id, + function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer + .source === + "string" + ? message.layer + .source + : message.layer + .id, + id: hoveredFeatureId, + }; + if ( + message.layer + .source_layer + ) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState( + featureState, + { + hover: false, + }, + ); + } + hoveredFeatureId = null; + }, + ); + + Object.keys(jsHoverOptions).forEach( + function (key) { + const originalPaint = + map.getPaintProperty( + message.layer.id, + key, + ) || + message.layer.paint[key]; + map.setPaintProperty( + message.layer.id, + key, + [ + "case", + [ + "boolean", + [ + "feature-state", + "hover", + ], + false, + ], + jsHoverOptions[key], + originalPaint, + ], + ); + }, + ); + } + } catch (e) { + console.error( + "Failed to add layer via proxy: ", + message.layer, + e, + ); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer_id and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer_id key + if (window._mapboxPopups[message.layer_id]) { + window._mapboxPopups[message.layer_id].remove(); + delete window._mapboxPopups[message.layer_id]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if (message.layer && message.layer.id && window._mapboxPopups[message.layer.id]) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer_id)) { + // Remove tooltip handlers + if ( + window._mapboxHandlers && + window._mapboxHandlers[message.layer_id] + ) { + const handlers = + window._mapboxHandlers[ + message.layer_id + ]; + if (handlers.mousemove) { + map.off( + "mousemove", + message.layer_id, + handlers.mousemove, + ); + } + if (handlers.mouseleave) { + map.off( + "mouseleave", + message.layer_id, + handlers.mouseleave, + ); + } + // Clean up the reference + delete window._mapboxHandlers[ + message.layer_id + ]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer_id key + if (window._mapboxClickHandlers[message.layer_id]) { + map.off( + "click", + message.layer_id, + window._mapboxClickHandlers[message.layer_id] + ); + delete window._mapboxClickHandlers[message.layer_id]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if (message.layer && message.layer.id && window._mapboxClickHandlers[message.layer.id]) { + map.off( + "click", + message.layer_id, + window._mapboxClickHandlers[message.layer.id] + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer_id); + } + if (map.getSource(message.layer_id)) { + map.removeSource(message.layer_id); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer_id]; + delete layerState.paintProperties[message.layer_id]; + delete layerState.layoutProperties[message.layer_id]; + delete layerState.tooltips[message.layer_id]; + delete layerState.popups[message.layer_id]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty( + message.layer, + message.name, + message.value, + ); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find( + (layer) => layer.id === layerId, + ); + const currentPaintProperty = + map.getPaintProperty(layerId, propertyName); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + [ + "boolean", + ["feature-state", "hover"], + false, + ], + hoverValue, + newValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + // No hover options, just set the new value directly + map.setPaintProperty( + layerId, + propertyName, + newValue, + ); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "add_legend") { + if (!message.add) { + const existingLegends = + document.querySelectorAll( + `#${data.id} .maplibregl-legend`, + ); + existingLegends.forEach((legend) => + legend.remove(), + ); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll(`style[data-mapgl-legend-css="${data.id}"]`); + legendStyles.forEach((style) => style.remove()); + } + + const legendCss = + document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute('data-mapgl-legend-css', data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("maplibregl-legend"); + + // Append legend to the correct map container + const targetContainer = map.getContainer(); + targetContainer.appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Save the current view state + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log("[MapGL Debug] Current style sources:", Object.keys(currentStyle.sources)); + console.log("[MapGL Debug] Current style layers:", currentStyle.layers.map(l => l.id)); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function(layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log("[MapGL Debug] Found source from test layer:", layer.source); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + + // If the paint property has a hover case, it's user-added + (layer.paint && Object.values(layer.paint).some(value => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover")) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = layerSource && layerSource.type === "vector" && ( + layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler") + ); + + if (!isBaseMapSource) { + console.log("[MapGL Debug] Found user source from layer:", layer.source); + userSourceIds.push(layer.source); + } else { + console.log("[MapGL Debug] Not adding base map source from layer:", layer.source); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if (source.url && typeof source.url === 'string' && + (source.url.includes("data:application/json") || + source.url.includes("blob:"))) { + console.log("[MapGL Debug] Found user source with data URL:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !(sourceId.startsWith("maptiler") && !sourceId.includes("user")) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) // Filter basemap sources but keep user ones + ) { + console.log("[MapGL Debug] Found user source via filtering:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find(l => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function(layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = layerSource && layerSource.type === "vector" && ( + layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler") + ); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log("[MapGL Debug] Including user layer:", layer.id, "source:", layer.source); + } else if (isBaseMapSource) { + console.log("[MapGL Debug] Excluding base map layer:", layer.id, "source:", layer.source); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function() { + // Re-add user sources + userSourceIds.forEach(function(sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function(layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log("[MapGL Debug] Re-adding mousemove handler for:", layer.id); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log("[MapGL Debug] Re-adding mouseleave handler for:", layer.id); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log("[MapGL Debug] Restoring tooltip for:", layerId); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function(e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = e.features[0].properties[tooltipProperty]; + tooltip.setLngLat(e.lngLat).setHTML(description).addTo(map); + } + }; + + const mouseLeaveHandler = function() { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if (Array.isArray(value) && value[0] === "case" && + Array.isArray(value[1]) && value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && value[1][1][1] === "hover") { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log("[MapGL Debug] Restoring tracked layer modifications"); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log("[MapGL Debug] Restoring filter for layer:", layerId); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log("[MapGL Debug] Restoring paint property:", layerId, propertyName, savedValue); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty(layerId, propertyName); + if (currentValue && Array.isArray(currentValue) && currentValue[0] === "case") { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log("[MapGL Debug] Restoring layout property:", layerId, propertyName, properties[propertyName]); + map.setLayoutProperty(layerId, propertyName, properties[propertyName]); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log("[MapGL Debug] Restoring tooltip:", layerId, tooltipProperty); + + // Remove existing tooltip handlers first + map.off("mousemove", layerId); + map.off("mouseleave", layerId); + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on("mousemove", layerId, function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }); + + map.on("mouseleave", layerId, function () { + onMouseLeaveTooltip(map, tooltip); + }); + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log("[MapGL Debug] Restoring popup:", layerId, popupProperty); + + // Remove existing popup handlers first + if (window._maplibreClickHandlers && window._maplibreClickHandlers[layerId]) { + map.off("click", layerId, window._maplibreClickHandlers[layerId]); + delete window._maplibreClickHandlers[layerId]; + } + + const clickHandler = function(e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + if (!window._maplibreClickHandlers) { + window._maplibreClickHandlers = {}; + } + window._maplibreClickHandlers[layerId] = clickHandler; + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off('style.load', onStyleLoad); + }; + + map.on('style.load', onStyleLoad); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map(id => ({id, source: currentStyle.sources[id]})), + layers: userLayers + }; + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function() { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = window._mapglPreservedData && window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log("[MapGL Debug] Backup restoration needed for layers"); + + // Re-add sources first + preserved.sources.forEach(function(src) { + try { + if (!map.getSource(src.id)) { + console.log("[MapGL Debug] Backup: adding source", src.id); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error("[MapGL Debug] Backup: error adding source", src.id, err); + } + }); + + // Then re-add layers + preserved.layers.forEach(function(layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Backup: adding layer", layer.id); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log("[MapGL Debug] Backup: restoring tooltip for", layer.id); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function(e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = e.features[0].properties[tooltipProperty]; + tooltip.setLngLat(e.lngLat).setHTML(description).addTo(map); + } + }; + + const mouseLeaveHandler = function() { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if (Array.isArray(value) && value[0] === "case" && + Array.isArray(value[1]) && value[1][0] === "boolean" && + value[1][1] && Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && value[1][1][1] === "hover") { + // This is a hover-enabled paint property + console.log("[MapGL Debug] Backup: restoring hover style for", layer.id, key); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Backup: error adding layer", layer.id, err); + } + }); + } else { + console.log("[MapGL Debug] Backup check: layers already restored properly"); + } + } + } catch (err) { + console.error("[MapGL Debug] Error in backup restoration:", err); + } + }, 500); // 500ms delay - faster recovery + } + } + + // Apply the new style + map.setStyle(message.style, { + diff: message.diff, + }); + + if (message.config) { + Object.keys(message.config).forEach( + function (key) { + map.setConfigProperty( + "basemap", + key, + message.config[key], + ); + }, + ); + } + + // Restore the view state after the style has loaded + map.once("style.load", function () { + map.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + + // Re-apply map modifications + if (map === beforeMap) { + applyMapModifications(map, x.map1); + } else { + applyMapModifications(map, x.map2); + } + }); + } else if ( + message.type === "add_navigation_control" + ) { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: + message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl.maplibregl-ctrl-group:not(.maplibre-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + map.controls.push({ type: "navigation", control: nav }); + } else if (message.type === "add_reset_control") { + const resetControl = + document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute( + "aria-label", + "Reset", + ); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = + "background-color 0.2s"; + resetControl.addEventListener( + "mouseover", + function () { + this.style.backgroundColor = "#f0f0f0"; + }, + ); + resetControl.addEventListener( + "mouseout", + function () { + this.style.backgroundColor = "white"; + }, + ); + + const resetContainer = + document.createElement("div"); + resetContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild( + resetContainer, + ); + }, + }, + message.position, + ); + // Add to controls array + map.controls.push(resetControl); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + if (message.freehand) { + drawOptions = Object.assign( + {}, + drawOptions, + { + modes: Object.assign( + {}, + MapboxDraw.modes, + { + draw_polygon: + MapboxDraw.modes + .draw_freehand, + }, + ), + }, + ); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on( + "draw.create", + window.updateDrawnFeatures, + ); + map.on( + "draw.delete", + window.updateDrawnFeatures, + ); + map.on( + "draw.update", + window.updateDrawnFeatures, + ); + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group", + ); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + } else if (message.type === "get_drawn_features") { + if (draw) { + const features = draw + ? draw.getAll() + : null; + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if ( + message.type === "clear_drawn_features" + ) { + if (draw) { + draw.deleteAll(); + // Update the drawn features + window.updateDrawnFeatures(); + } + } else if (message.type === "add_markers") { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: + marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker( + markerOptions, + ) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue( + data.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + + mapMarker.on("dragend", function () { + const lngLat = + mapMarker.getLngLat(); + Shiny.setInputValue( + data.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + }); + } + + window.maplibreglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreglMarkers) { + window.maplibreglMarkers.forEach( + function (marker) { + marker.remove(); + }, + ); + window.maplibreglMarkers = []; + } + } else if ( + message.type === "add_fullscreen_control" + ) { + const position = + message.position || "top-right"; + const fullscreen = + new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = + new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl( + scaleControl, + message.options.position, + ); + map.controls.push(scaleControl); + } else if ( + message.type === "add_geolocate_control" + ) { + const geolocate = + new maplibregl.GeolocateControl({ + positionOptions: + message.options.positionOptions, + trackUserLocation: + message.options.trackUserLocation, + showAccuracyCircle: + message.options.showAccuracyCircle, + showUserLocation: + message.options.showUserLocation, + showUserHeading: + message.options.showUserHeading, + fitBoundsOptions: + message.options.fitBoundsOptions, + }); + map.addControl( + geolocate, + message.options.position, + ); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue( + data.id + "_geolocate", + { + coords: event.coords, + time: new Date(), + }, + ); + }); + + geolocate.on( + "trackuserlocationstart", + function () { + Shiny.setInputValue( + data.id + "_geolocate_tracking", + { + status: "start", + time: new Date(), + }, + ); + }, + ); + + geolocate.on( + "trackuserlocationend", + function () { + Shiny.setInputValue( + data.id + "_geolocate_tracking", + { + status: "end", + time: new Date(), + }, + ); + }, + ); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue( + data.id + "_geolocate_error", + { + message: + "Location permission denied", + time: new Date(), + }, + ); + } + }); + } + } else if ( + message.type === "add_geocoder_control" + ) { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = + await fetch(request); + const geojson = + await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - + feature.bbox[0]) / + 2, + feature.bbox[1] + + (feature.bbox[3] - + feature.bbox[1]) / + 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: + feature.properties + .display_name, + properties: + feature.properties, + text: feature.properties + .display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error( + `Failed to forwardGeocode with error: ${e}`, + ); + } + + return { + features, + }; + }, + }; + + const geocoderOptions = { + maplibregl: maplibregl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if ( + typeof geocoderOptions.collapsed === + "undefined" + ) + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder( + geocoderApi, + geocoderOptions, + ); + } + + map.addControl( + geocoder, + message.options.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } else if (message.type === "add_layers_control") { + const layersControl = + document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = + document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `.layers-control { background-color: ${colors.background} !important; }`; + } + if (colors.text) { + css += `.layers-control a { color: ${colors.text} !important; }`; + } + if (colors.activeBackground) { + css += `.layers-control a.active { background-color: ${colors.activeBackground} !important; }`; + } + if (colors.activeText) { + css += `.layers-control a.active { color: ${colors.activeText} !important; }`; + } + if (colors.hoverBackground) { + css += `.layers-control a:hover { background-color: ${colors.hoverBackground} !important; }`; + } + if (colors.hoverText) { + css += `.layers-control a:hover { color: ${colors.hoverText} !important; }`; + } + if (colors.toggleButtonBackground) { + css += `.layers-control .toggle-button { background-color: ${colors.toggleButtonBackground} + !important; }`; + } + if (colors.toggleButtonText) { + css += `.layers-control .toggle-button { color: ${colors.toggleButtonText} !important; }`; + } + + styleEl.innerHTML = css; + document.head.appendChild(styleEl); + } + + document + .getElementById(data.id) + .appendChild(layersControl); + + const layersList = + document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + message.layers || + map + .getStyle() + .layers.map((layer) => layer.id); + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = + map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty( + clickedLayer, + "visibility", + "none", + ); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (message.collapsible) { + const toggleButton = + document.createElement("div"); + toggleButton.className = "toggle-button"; + toggleButton.textContent = "Layers"; + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore( + toggleButton, + layersList, + ); + } + } else if (message.type === "add_globe_minimap") { + // Add the globe minimap control if supported + if (typeof MapboxGlobeMinimap !== "undefined") { + const minimap = new MapboxGlobeMinimap({ + center: map.getCenter(), + zoom: map.getZoom(), + bearing: map.getBearing(), + pitch: map.getPitch(), + globeSize: message.globe_size, + landColor: message.land_color, + waterColor: message.water_color, + markerColor: message.marker_color, + markerSize: message.marker_size, + }); + + map.addControl(minimap, message.position); + } else { + console.warn( + "MapboxGlobeMinimap is not defined", + ); + } + } else if (message.type === "add_globe_control") { + // Add the globe control + const globeControl = + new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign( + {}, + drawOptions, + { + modes: Object.assign( + {}, + MapboxDraw.modes, + { + draw_polygon: + MapboxDraw.modes + .draw_freehand, + }, + ), + // defaultMode: 'draw_polygon' # Don't set the default yet + }, + ); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: '#fbb03b', + point_color: '#3bb2d0', + line_color: '#3bb2d0', + fill_color: '#3bb2d0', + fill_opacity: 0.1, + line_width: 2 + }); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(draw, message.source, map); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + if (draw) { + const features = draw + ? draw.getAll() + : null; + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if ( + message.type === "clear_drawn_features" + ) { + if (draw) { + draw.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + if (draw) { + if (message.data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn('Draw control not initialized'); + } + } else if (message.type === "set_projection") { + // Only if maplibre supports projection + if (typeof map.setProjection === "function") { + map.setProjection(message.projection); + } + } else if (message.type === "set_source") { + if (map.getLayer(message.layer)) { + const sourceId = map.getLayer( + message.layer, + ).source; + map.getSource(sourceId).setData( + JSON.parse(message.source), + ); + } + } else if (message.type === "set_tooltip") { + // Track tooltip state + layerState.tooltips[message.layer] = message.tooltip; + + if (map.getLayer(message.layer)) { + // Remove any existing tooltip handlers + map.off("mousemove", message.layer); + map.off("mouseleave", message.layer); + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on( + "mousemove", + message.layer, + function (e) { + map.getCanvas().style.cursor = + "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[ + message.tooltip + ]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }, + ); + + map.on( + "mouseleave", + message.layer, + function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }, + ); + } + } else if (message.type === "set_popup") { + // Track popup state + layerState.popups[message.layer] = message.popup; + + if (map.getLayer(message.layer)) { + // Remove any existing popup click handlers for this layer + if (window._maplibreClickHandlers && window._maplibreClickHandlers[message.layer]) { + map.off("click", message.layer, window._maplibreClickHandlers[message.layer]); + delete window._maplibreClickHandlers[message.layer]; + } + + // Remove any existing popup for this layer + if (window._maplibrePopups && window._maplibrePopups[message.layer]) { + window._maplibrePopups[message.layer].remove(); + delete window._maplibrePopups[message.layer]; + } + + // Create new click handler for popup + const clickHandler = function (e) { + onClickPopup(e, map, message.popup, message.layer); + }; + + // Store handler reference + if (!window._maplibreClickHandlers) { + window._maplibreClickHandlers = {}; + } + window._maplibreClickHandlers[message.layer] = clickHandler; + + // Add click handler + map.on("click", message.layer, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer, function () { + map.getCanvas().style.cursor = ""; + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer( + message.layer, + message.before, + ); + } else { + map.moveLayer(message.layer); + } + } + } else if (message.type === "set_opacity") { + // Set opacity for all fill layers + const style = map.getStyle(); + if (style && style.layers) { + style.layers.forEach(function (layer) { + if ( + layer.type === "fill" && + map.getLayer(layer.id) + ) { + map.setPaintProperty( + layer.id, + "fill-opacity", + message.opacity, + ); + } + }); + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection) + ); + } else if (message.type === "clear_controls") { + // Handle clear_controls for compare widgets + if (!message.controls || message.controls.length === 0) { + // Clear all controls + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + } + } + }, + ); + } + + function setupShinyEvents(map, parentId, mapType) { + // Set view state on move end + map.on("moveend", function () { + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_view", + { + center: [center.lng, center.lat], + zoom: zoom, + bearing: bearing, + pitch: pitch, + }, + ); + } + }); + + // Send clicked point coordinates to Shiny + map.on("click", function (e) { + // Check if this map's draw control is active and in a drawing mode + let isDrawing = false; + if (map._mapgl_draw && map._mapgl_draw.getMode) { + const mode = map._mapgl_draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + console.log(`[${mapType}] Draw mode: ${mode}, isDrawing: ${isDrawing}`); + } else { + console.log(`[${mapType}] No draw control found`); + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + // Filter out draw layers + const nonDrawFeatures = features.filter(feature => + !feature.layer.id.includes('gl-draw') && + !feature.source.includes('gl-draw') + ); + console.log(`[${mapType}] Features found: ${features.length}, non-draw: ${nonDrawFeatures.length}`); + + if (nonDrawFeatures.length > 0) { + const feature = nonDrawFeatures[0]; + console.log(`[${mapType}] Feature click detected, layer: ${feature.layer.id}`); + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_click", + { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }, + ); + } + } else { + console.log(`[${mapType}] No non-draw features found at click point`); + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_click", + null + ); + } + } + } else { + console.log(`[${mapType}] Feature click suppressed - currently drawing`); + } + + // Always send regular click event + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_click", + { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }, + ); + } + }); + + // Add hover events if enabled for this map + const mapConfig = (mapType === "before") ? x.map1 : x.map2; + if (mapConfig.hover_events && mapConfig.hover_events.enabled) { + map.on("mousemove", function (e) { + if (window.Shiny) { + // Feature hover events + if (mapConfig.hover_events.features) { + const options = mapConfig.hover_events.layer_id + ? { layers: Array.isArray(mapConfig.hover_events.layer_id) + ? mapConfig.hover_events.layer_id + : mapConfig.hover_events.layer_id.split(',').map(id => id.trim()) } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if(features.length > 0) { + const feature = features[0]; + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } else { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + null + ); + } + } + + // Coordinate hover events + if (mapConfig.hover_events.coordinates) { + Shiny.setInputValue( + parentId + "_" + mapType + "_hover", + { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } + } + }); + } + } + + function applyMapModifications(map, mapData) { + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + // Define the tooltip handler functions to match the ones in maplibregl.js + function onMouseMoveTooltip( + e, + map, + tooltipPopup, + tooltipProperty, + ) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(tooltipProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } + } + + function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } + + function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case 'get': + return properties[expression[1]]; + case 'concat': + return expression.slice(1).map(item => evaluateExpression(item, properties)).join(''); + case 'to-string': + return String(evaluateExpression(expression[1], properties)); + case 'to-number': + return Number(evaluateExpression(expression[1], properties)); + default: + // For literals and other simple values + return expression; + } + } + + function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._maplibrePopups && window._maplibrePopups[layerId]) { + window._maplibrePopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._maplibrePopups) { + window._maplibrePopups = {}; + } + window._maplibrePopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on('close', function() { + if (window._maplibrePopups[layerId] === popup) { + delete window._maplibrePopups[layerId]; + } + }); + } + + // Set config properties if provided + if (mapData.config_properties) { + mapData.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + // Process H3J sources if provided + if (mapData.h3j_sources) { + mapData.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + }); + } + + if (mapData.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + mapData.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker( + markerOptions, + ) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setText(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + } + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + } + }); + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (mapData.sources) { + mapData.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceConfig = { + type: "vector", + url: source.url, + }; + if (source.promoteId) { + sourceConfig.promoteId = source.promoteId; + } + map.addSource(source.id, sourceConfig); + } else if (source.type === "geojson") { + map.addSource(source.id, { + type: "geojson", + data: source.data, + generateId: source.generateId !== false, + }); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + // Add layers if provided + if (mapData.layers) { + mapData.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = + layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + map.on("click", layer.id, function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = + "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + layer.tooltip, + ); + }; + + // Create a reference to the mouseleave handler function + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references + map.on( + "mousemove", + layer.id, + mouseMoveHandler, + ); + map.on( + "mouseleave", + layer.id, + mouseLeaveHandler, + ); + + // Store these handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === + "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = e.features[0].id; + map.setFeatureState( + { + source: + typeof layer.source === + "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: true }, + ); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === + "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach( + function (key) { + const originalPaint = + map.getPaintProperty( + layer.id, + key, + ) || layer.paint[key]; + map.setPaintProperty( + layer.id, + key, + [ + "case", + [ + "boolean", + [ + "feature-state", + "hover", + ], + false, + ], + jsHoverOptions[key], + originalPaint, + ], + ); + }, + ); + } + } catch (e) { + console.error( + "Failed to add layer: ", + layer, + e, + ); + } + }); + } + + // Set terrain if provided + if (mapData.terrain) { + map.setTerrain({ + source: mapData.terrain.source, + exaggeration: mapData.terrain.exaggeration, + }); + } + + // Set fog + if (mapData.fog) { + map.setFog(mapData.fog); + } + + if (mapData.fitBounds) { + map.fitBounds( + mapData.fitBounds.bounds, + mapData.fitBounds.options, + ); + } + if (mapData.flyTo) { + map.flyTo(mapData.flyTo); + } + if (mapData.easeTo) { + map.easeTo(mapData.easeTo); + } + if (mapData.setCenter) { + map.setCenter(mapData.setCenter); + } + if (mapData.setZoom) { + map.setZoom(mapData.setZoom); + } + + // Apply moveLayer operations if provided + if (mapData.moveLayer) { + mapData.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + if (mapData.jumpTo) { + map.jumpTo(mapData.jumpTo); + } + + // Add custom images if provided + if (mapData.images && Array.isArray(mapData.images)) { + mapData.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage( + imageInfo.url, + ); + if (!map.hasImage(imageInfo.id)) { + map.addImage( + imageInfo.id, + image.data, + imageInfo.options, + ); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (mapData.images) { + console.error( + "mapData.images is not an array:", + mapData.images, + ); + } + + // Remove existing legends only from this specific map container + const mapContainer = map.getContainer(); + const existingLegends = mapContainer.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + + if (mapData.legend_html && mapData.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = mapData.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = mapData.legend_html; + legend.classList.add("mapboxgl-legend"); + + // Append legend to the correct map container instead of main container + mapContainer.appendChild(legend); + } + + // Add fullscreen control if enabled + if ( + mapData.fullscreen_control && + mapData.fullscreen_control.enabled + ) { + const position = + mapData.fullscreen_control.position || "top-right"; + map.addControl( + new maplibregl.FullscreenControl(), + position, + ); + } + + // Helper function to generate draw styles based on parameters + function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + 'id': 'gl-draw-point-active', + 'type': 'circle', + 'filter': ['all', + ['==', '$type', 'Point'], + ['==', 'meta', 'feature'], + ['==', 'active', 'true']], + 'paint': { + 'circle-radius': styling.vertex_radius + 2, + 'circle-color': styling.active_color + } + }, + { + 'id': 'gl-draw-point', + 'type': 'circle', + 'filter': ['all', + ['==', '$type', 'Point'], + ['==', 'meta', 'feature'], + ['==', 'active', 'false']], + 'paint': { + 'circle-radius': styling.vertex_radius, + 'circle-color': styling.point_color + } + }, + // Line styles + { + 'id': 'gl-draw-line', + 'type': 'line', + 'filter': ['all', ['==', '$type', 'LineString']], + 'layout': { + 'line-cap': 'round', + 'line-join': 'round' + }, + 'paint': { + 'line-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.line_color + ], + 'line-width': styling.line_width + } + }, + // Polygon fill + { + 'id': 'gl-draw-polygon-fill', + 'type': 'fill', + 'filter': ['all', ['==', '$type', 'Polygon']], + 'paint': { + 'fill-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.fill_color + ], + 'fill-outline-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.fill_color + ], + 'fill-opacity': styling.fill_opacity + } + }, + // Polygon outline + { + 'id': 'gl-draw-polygon-stroke', + 'type': 'line', + 'filter': ['all', ['==', '$type', 'Polygon']], + 'layout': { + 'line-cap': 'round', + 'line-join': 'round' + }, + 'paint': { + 'line-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.line_color + ], + 'line-width': styling.line_width + } + }, + // Midpoints + { + 'id': 'gl-draw-polygon-midpoint', + 'type': 'circle', + 'filter': ['all', + ['==', '$type', 'Point'], + ['==', 'meta', 'midpoint']], + 'paint': { + 'circle-radius': 3, + 'circle-color': styling.active_color + } + }, + // Vertex point halos + { + 'id': 'gl-draw-vertex-halo-active', + 'type': 'circle', + 'filter': ['all', + ['==', 'meta', 'vertex'], + ['==', '$type', 'Point']], + 'paint': { + 'circle-radius': ['case', + ['==', ['get', 'active'], 'true'], styling.vertex_radius + 4, + styling.vertex_radius + 2 + ], + 'circle-color': '#FFF' + } + }, + // Vertex points + { + 'id': 'gl-draw-vertex-active', + 'type': 'circle', + 'filter': ['all', + ['==', 'meta', 'vertex'], + ['==', '$type', 'Point']], + 'paint': { + 'circle-radius': ['case', + ['==', ['get', 'active'], 'true'], styling.vertex_radius + 2, + styling.vertex_radius + ], + 'circle-color': styling.active_color + } + } + ]; + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn('Source not found or has no data:', sourceId); + } + } + + if (mapData.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: mapData.scale_control.maxWidth, + unit: mapData.scale_control.unit, + }); + map.addControl( + scaleControl, + mapData.scale_control.position, + ); + map.controls.push(scaleControl); + } + + // Add navigation control if enabled + if (mapData.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: + mapData.navigation_control.show_compass, + showZoom: mapData.navigation_control.show_zoom, + visualizePitch: + mapData.navigation_control.visualize_pitch, + }); + map.addControl( + nav, + mapData.navigation_control.position, + ); + map.controls.push({ type: "navigation", control: nav }); + } + + // Add geolocate control if enabled + if (mapData.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: + mapData.geolocate_control.positionOptions, + trackUserLocation: + mapData.geolocate_control.trackUserLocation, + showAccuracyCircle: + mapData.geolocate_control.showAccuracyCircle, + showUserLocation: + mapData.geolocate_control.showUserLocation, + showUserHeading: + mapData.geolocate_control.showUserHeading, + fitBoundsOptions: + mapData.geolocate_control.fitBoundsOptions, + }); + map.addControl( + geolocate, + mapData.geolocate_control.position, + ); + + map.controls.push(geolocate); + } + + // Add globe control if enabled + if (mapData.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl( + globeControl, + mapData.globe_control.position, + ); + map.controls.push(globeControl); + } + + // Add draw control if enabled + if (mapData.draw_control && mapData.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = mapData.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (mapData.draw_control.styling) { + const generatedStyles = generateDrawStyles(mapData.draw_control.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (mapData.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + mapData.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (mapData.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (mapData.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: '#fbb03b', + point_color: '#3bb2d0', + line_color: '#3bb2d0', + fill_color: '#3bb2d0', + fill_opacity: 0.1, + line_width: 2 + }); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, mapData.draw_control.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add custom mode buttons and styling + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + + // Add rectangle styling and button + if (mapData.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + drawControl.changeMode('draw_rectangle'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + } + + // Add radius styling and button + if (mapData.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + drawControl.changeMode('draw_radius'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + } + }, 100); + + // Add initial features if provided + if (mapData.draw_control.source) { + addSourceFeaturesToDraw(drawControl, mapData.draw_control.source, map); + } + + // Process any queued features + if (mapData.draw_features_queue) { + mapData.draw_features_queue.forEach(function(data) { + if (data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, data.source, map); + }); + } + + // Apply orientation styling + if (mapData.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (mapData.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${mapData.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + + // Helper function for updating drawn features + function updateDrawnFeatures() { + if (HTMLWidgets.shinyMode && draw) { + const features = draw.getAll(); + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(features), + ); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + } + + if (mapData.geolocate_control && HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue( + el.id + "_geolocate_error", + { + message: "Location permission denied", + time: new Date(), + }, + ); + } + }); + } + + // Add geocoder control if enabled + if (mapData.geocoder_control) { + const provider = mapData.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: mapData.geocoder_control.api_key, + maplibregl: maplibregl, + ...mapData.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - + feature.bbox[0]) / + 2, + feature.bbox[1] + + (feature.bbox[3] - + feature.bbox[1]) / + 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: + feature.properties.display_name, + properties: feature.properties, + text: feature.properties + .display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error( + `Failed to forwardGeocode with error: ${e}`, + ); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...mapData.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder( + geocoderApi, + geocoderOptions, + ); + } + + map.addControl( + geocoder, + mapData.geocoder_control.position || "top-right", + ); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + // Add reset control if enabled + if (mapData.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: mapData.reset_control.animate, + }; + + if (mapData.reset_control.duration) { + initialView.duration = + mapData.reset_control.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild( + resetContainer, + ); + }, + }, + mapData.reset_control.position, + ); + } + + + function updateDrawnFeatures() { + if (map._mapgl_draw) { + var drawnFeatures = map._mapgl_draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + // Add the layers control if provided + if (mapData.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = mapData.layers_control.control_id; + + // Handle use_icon parameter + let className = mapData.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + + layersControl.className = className; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = + mapData.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + mapData.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = mapData.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty( + clickedLayer, + "visibility", + "none", + ); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (mapData.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + if (mapData.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore( + toggleButton, + layersList, + ); + } + } + + // Set projection if provided (after all other setup is complete) + if (mapData.setProjection && mapData.setProjection.length > 0) { + mapData.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection in compare view:", e); + } + } + }); + } + } + }, + + resize: function (width, height) { + // Code to handle resizing if necessary + }, + }; + }, +}); diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/maplibregl_compare.yaml b/docs/articles/map-design_files/turf-operations-1.0.0/maplibregl_compare.yaml new file mode 100644 index 0000000..a72887c --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/maplibregl_compare.yaml @@ -0,0 +1,67 @@ +dependencies: + - name: maplibre-gl + version: "5.7.2" + src: "htmlwidgets/lib/maplibre-gl" + script: + - "maplibre-gl.js" + stylesheet: + - "maplibre-gl.css" + - name: maplibre-gl-compare + version: "0.5" + src: "htmlwidgets/lib/maplibre-gl-compare" + script: + - "maplibre-gl-compare.js" + stylesheet: + - "maplibre-gl-compare.css" + - name: mapbox-gl-draw + version: "1.5.0" + src: "htmlwidgets/lib/mapbox-gl-draw" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: maplibre-gl-geocoder + version: 1.5.0 + src: "htmlwidgets/lib/maplibre-gl-geocoder" + script: + - "maplibre-gl-geocoder.min.js" + stylesheet: + - "maplibre-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: h3j-h3t + version: 0.9.2 + src: "htmlwidgets/lib/h3j-h3t" + script: + - "h3j_h3t.js" + - name: maptiler-geocoding-control + version: 2.1.7 + src: + href: "https://cdn.maptiler.com/maptiler-geocoding-control/v2.1.7/" + script: + - "maplibregl.umd.js" + stylesheet: + - "style.css" diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/styles/filter-control.css b/docs/articles/map-design_files/turf-operations-1.0.0/styles/filter-control.css new file mode 100644 index 0000000..e6096c3 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/styles/filter-control.css @@ -0,0 +1,65 @@ +.filter-control { + background: #fff; + position: absolute; + z-index: 1; + border-radius: 3px; + width: 200px; + border: 1px solid rgba(0, 0, 0, 0.4); + font-family: 'Open Sans', sans-serif; + margin: 10px; + padding: 10px; +} + +.filter-control .filter-title { + font-weight: bold; + margin-bottom: 10px; + text-align: center; +} + +.filter-control input[type="range"] { + width: 100%; + margin: 10px 0; +} + +.filter-control .range-value { + text-align: center; + margin-top: 5px; +} + +.filter-control .checkbox-group { + display: flex; + flex-direction: column; + gap: 5px; +} + +.filter-control .checkbox-group label { + display: flex; + align-items: center; + gap: 5px; +} + +.filter-control .toggle-button { + background: darkgrey; + color: #ffffff; + text-align: center; + cursor: pointer; + padding: 5px 0; + border-radius: 3px 3px 0 0; + margin: -10px -10px 10px -10px; +} + +.filter-control .toggle-button:hover { + background: grey; +} + +.filter-control .filter-content { + display: block; +} + +.filter-control.collapsible .filter-content { + display: none; +} + +.filter-control.collapsible.open .filter-content { + display: block; +} \ No newline at end of file diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/styles/layers-control.css b/docs/articles/map-design_files/turf-operations-1.0.0/styles/layers-control.css new file mode 100644 index 0000000..8551228 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/styles/layers-control.css @@ -0,0 +1,123 @@ +.layers-control { + background: #fff; + position: absolute; + z-index: 1; + border-radius: 4px; + width: 120px; + border: 1px solid rgba(0, 0, 0, 0.15); + font-family: "Open Sans", sans-serif; + margin: 0px; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15); + overflow: hidden; + transition: all 0.2s ease-in-out; +} + +.layers-control a { + font-size: 13px; + color: #404040; + display: block; + margin: 0; + padding: 10px; + text-decoration: none; + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + text-align: center; + transition: all 0.15s ease-in-out; + font-weight: normal; +} + +.layers-control a:last-child { + border: none; +} + +.layers-control a:hover { + background-color: #f8f8f8; + color: #1a1a1a; +} + +.layers-control a.active { + background-color: #4a90e2; + color: #ffffff; + font-weight: 500; +} + +.layers-control a.active:hover { + background: #3b7ed2; +} + +.layers-control .toggle-button { + display: none; + background: #4a90e2; + color: #ffffff; + text-align: center; + cursor: pointer; + padding: 8px 0; + border-radius: 4px 4px 0 0; + font-weight: 500; + letter-spacing: 0.3px; + box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.05) inset; + transition: all 0.15s ease-in-out; +} + +.layers-control .toggle-button:hover { + background: #3b7ed2; +} + +.layers-control .layers-list { + display: block; +} + +.layers-control.collapsible .toggle-button { + display: block; + border-bottom: 1px solid rgba(0, 0, 0, 0.25); +} + +.layers-control.collapsible .layers-list { + display: none; + opacity: 0; + max-height: 0; + transition: + opacity 0.25s ease, + max-height 0.25s ease; +} + +.layers-control.collapsible.open .layers-list { + display: block; + opacity: 1; + max-height: 500px; /* Large enough value to accommodate all content */ +} + +/* Compact icon styling */ +.layers-control.collapsible.icon-only { + width: auto; + min-width: 36px; + border-radius: 4px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); + transform: translateZ( + 0 + ); /* Force hardware acceleration for smoother animations */ +} + +.layers-control.collapsible.icon-only .toggle-button { + border-radius: 4px; + padding: 8px; + width: 36px; + height: 36px; + box-sizing: border-box; + margin: 0; + border-bottom: none; + display: flex; + align-items: center; + justify-content: center; + box-shadow: none; +} + +.layers-control.collapsible.icon-only.open { + width: 120px; + box-shadow: 0 3px 10px rgba(0, 0, 0, 0.25); +} + +.layers-control.collapsible.icon-only.open .toggle-button { + border-radius: 4px 4px 0 0; + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + width: 100%; +} diff --git a/docs/articles/map-design_files/turf-operations-1.0.0/turf-operations.js b/docs/articles/map-design_files/turf-operations-1.0.0/turf-operations.js new file mode 100644 index 0000000..2b4e514 --- /dev/null +++ b/docs/articles/map-design_files/turf-operations-1.0.0/turf-operations.js @@ -0,0 +1,967 @@ +// Turf.js operations module for mapgl +// Shared operations that work with both mapboxgl and maplibre maps + +// Process turf operations on map initialization (for static maps) +function processTurfOperationsOnLoad(map, turfOperations, widgetId) { + if (!turfOperations || turfOperations.length === 0) return; + + // Wait for map to be fully loaded, then execute operations + map.on('load', function() { + // Add a small delay to ensure all layers are loaded + setTimeout(function() { + turfOperations.forEach(function(operation) { + try { + handleTurfOperation(map, operation, widgetId); + } catch (error) { + console.error(`Error processing turf operation ${operation.type}:`, error); + } + }); + }, 100); + }); +} + +// Main handler for all turf operations +function handleTurfOperation(map, message, widgetId) { + try { + switch (message.type) { + case "turf_buffer": + executeTurfBuffer(map, message, widgetId); + break; + case "turf_union": + executeTurfUnion(map, message, widgetId); + break; + case "turf_intersect": + executeTurfIntersect(map, message, widgetId); + break; + case "turf_difference": + executeTurfDifference(map, message, widgetId); + break; + case "turf_convex_hull": + executeTurfConvexHull(map, message, widgetId); + break; + case "turf_concave_hull": + executeTurfConcaveHull(map, message, widgetId); + break; + case "turf_voronoi": + executeTurfVoronoi(map, message, widgetId); + break; + case "turf_distance": + executeTurfDistance(map, message, widgetId); + break; + case "turf_area": + executeTurfArea(map, message, widgetId); + break; + case "turf_centroid": + executeTurfCentroid(map, message, widgetId); + break; + case "turf_center_of_mass": + executeTurfCenterOfMass(map, message, widgetId); + break; + case "turf_filter": + executeTurfFilter(map, message, widgetId); + break; + default: + console.warn(`Unknown turf operation: ${message.type}`); + } + } catch (error) { + console.error(`Error executing turf operation ${message.type}:`, error); + if (HTMLWidgets.shinyMode && message.send_to_r) { + Shiny.setInputValue(widgetId + "_turf_error", { + operation: message.type, + error: error.message, + timestamp: Date.now() + }); + } + } +} + +// Helper function to get input data for turf operations +function getInputData(map, message) { + // If coordinates provided, create point or points client-side + if (message.coordinates) { + // Handle single coordinate pair + if (typeof message.coordinates[0] === 'number') { + return turf.point(message.coordinates); + } + // Handle multiple coordinate pairs + if (Array.isArray(message.coordinates[0])) { + const points = message.coordinates.map(coord => turf.point(coord)); + return { + type: "FeatureCollection", + features: points + }; + } + } + + // If GeoJSON data provided directly + if (message.data) { + // Check if data is already an object (shouldn't happen) or string + if (typeof message.data === 'string') { + return JSON.parse(message.data); + } else { + // If it's already an object, return as-is + return message.data; + } + } + + // If layer_id provided, get from existing layer + if (message.layer_id) { + return getSourceData(map, message.layer_id); + } + + throw new Error("No valid input data provided (coordinates, data, or layer_id)"); +} + +// Helper function to get source data from a layer +function getSourceData(map, layerId) { + // First try to get from existing source + const source = map.getSource(layerId); + if (source) { + // Check for _data property (GeoJSON sources) + if (source._data) { + return source._data; + } + // Check for data property + if (source.data) { + return source.data; + } + } + + // Try with _source suffix (common pattern in mapgl) + const sourceWithSuffix = map.getSource(layerId + "_source"); + if (sourceWithSuffix) { + if (sourceWithSuffix._data) { + return sourceWithSuffix._data; + } + if (sourceWithSuffix.data) { + return sourceWithSuffix.data; + } + } + + // Query rendered features as fallback + try { + const features = map.queryRenderedFeatures({ layers: [layerId] }); + if (features.length > 0) { + return { + type: "FeatureCollection", + features: features + }; + } + } catch (e) { + // Layer might not exist, continue to error + } + + throw new Error(`Could not find source data for layer: ${layerId}`); +} + +// Helper function to add result source to map +function addResultSource(map, result, sourceId) { + if (!sourceId) return; + + // Ensure result is valid GeoJSON + if (!result) { + result = { + type: "FeatureCollection", + features: [] + }; + } + + // Check if source exists, update data or create new + const existingSource = map.getSource(sourceId); + if (existingSource) { + // Update existing source data + existingSource.setData(result); + } else { + // Add new source with result data + map.addSource(sourceId, { + type: "geojson", + data: result, + generateId: true + }); + } +} + +// Helper function to send result to R via Shiny input +function sendResultToR(widgetId, operation, result, metadata = {}, inputId = null) { + if (HTMLWidgets.shinyMode && inputId) { + Shiny.setInputValue(widgetId + "_turf_" + inputId, { + operation: operation, + result: result, + metadata: metadata, + timestamp: Date.now() + }); + } +} + +// Buffer operation +function executeTurfBuffer(map, message, widgetId) { + const inputData = getInputData(map, message); + + const buffered = turf.buffer(inputData, message.radius, { + units: message.units || "meters" + }); + + if (message.source_id) { + addResultSource(map, buffered, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "buffer", buffered, { + radius: message.radius, + units: message.units || "meters" + }, message.input_id); + } +} + +// Union operation +function executeTurfUnion(map, message, widgetId) { + const inputData = getInputData(map, message); + + let result; + if (inputData.type === "FeatureCollection" && inputData.features.length > 1) { + // Use turf.union with properly formatted FeatureCollection + const union = turf.union(turf.featureCollection(inputData.features)); + + result = union ? { + type: "FeatureCollection", + features: [union] + } : { + type: "FeatureCollection", + features: [] + }; + } else if (inputData.type === "FeatureCollection" && inputData.features.length === 1) { + // Single feature, return as-is + result = { + type: "FeatureCollection", + features: [inputData.features[0]] + }; + } else { + // Single feature, return as-is in FeatureCollection + result = { + type: "FeatureCollection", + features: [inputData] + }; + } + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "union", result, {}, message.input_id); + } +} + +// Intersect operation +function executeTurfIntersect(map, message, widgetId) { + const sourceData1 = getInputData(map, message); + + // Get second geometry data + let sourceData2; + if (message.data_2) { + // Handle data_2 directly + if (typeof message.data_2 === 'string') { + sourceData2 = JSON.parse(message.data_2); + } else { + sourceData2 = message.data_2; + } + } else if (message.layer_id_2) { + // Handle layer_id_2 as before + sourceData2 = getSourceData(map, message.layer_id_2); + } else { + throw new Error("Either data_2 or layer_id_2 must be provided for intersect operation"); + } + + // Extract features arrays + const features1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features : [sourceData1]; + const features2 = sourceData2.type === "FeatureCollection" ? + sourceData2.features : [sourceData2]; + + // Collect all intersection results + const resultFeatures = []; + + features1.forEach((feature1, index1) => { + if (!feature1 || !feature1.geometry) { + console.warn(`Skipping invalid feature at index ${index1}`); + return; + } + + features2.forEach((feature2, index2) => { + if (!feature2 || !feature2.geometry) { + return; + } + + // Use booleanIntersects for efficient filtering + if (turf.booleanIntersects(feature1, feature2)) { + try { + // Use turf.intersect with options to preserve properties + const intersection = turf.intersect( + turf.featureCollection([feature1, feature2]), + { properties: feature1.properties } + ); + + if (intersection) { + // Ensure properties are preserved (fallback if options didn't work) + if (!intersection.properties || Object.keys(intersection.properties).length === 0) { + intersection.properties = { ...feature1.properties }; + } + resultFeatures.push(intersection); + } + } catch (error) { + console.error(`Error intersecting features ${index1} and ${index2}:`, error); + } + } + }); + }); + + const result = { + type: "FeatureCollection", + features: resultFeatures + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "intersect", result, {}, message.input_id); + } +} + +// Difference operation +function executeTurfDifference(map, message, widgetId) { + const sourceData1 = getInputData(map, message); + + // Get second geometry data + let sourceData2; + if (message.data_2) { + // Handle data_2 directly + if (typeof message.data_2 === 'string') { + sourceData2 = JSON.parse(message.data_2); + } else { + sourceData2 = message.data_2; + } + } else if (message.layer_id_2) { + // Handle layer_id_2 as before + sourceData2 = getSourceData(map, message.layer_id_2); + } else { + throw new Error("Either data_2 or layer_id_2 must be provided for difference operation"); + } + + // Extract features arrays + const features1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features : [sourceData1]; + const features2 = sourceData2.type === "FeatureCollection" ? + sourceData2.features : [sourceData2]; + + // Process each feature in features1 + const resultFeatures = []; + + features1.forEach((feature1, index) => { + if (!feature1 || !feature1.geometry) { + console.warn(`Skipping invalid feature at index ${index}`); + return; + } + + // Start with the original feature + let currentFeature = feature1; + + // Apply difference with each feature from features2 + for (const feature2 of features2) { + if (!feature2 || !feature2.geometry || !currentFeature) { + continue; + } + + // Use booleanIntersects for efficient filtering + if (turf.booleanIntersects(currentFeature, feature2)) { + try { + const diff = turf.difference(turf.featureCollection([currentFeature, feature2])); + + if (diff) { + // Preserve properties from the original feature + diff.properties = { ...feature1.properties }; + currentFeature = diff; + } else { + // Feature was completely erased + currentFeature = null; + break; + } + } catch (error) { + console.error("Error in difference operation:", error); + // Keep the current feature unchanged on error + } + } + // If no intersection, currentFeature remains unchanged + } + + // Add the result if it still exists + if (currentFeature) { + resultFeatures.push(currentFeature); + } + }); + + const result = { + type: "FeatureCollection", + features: resultFeatures + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "difference", result, {}, message.input_id); + } +} + +// Convex hull operation +function executeTurfConvexHull(map, message, widgetId) { + const inputData = getInputData(map, message); + + // Ensure we have valid input data + if (!inputData) { + console.warn("No input data for convex hull"); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + // Check for minimum points if it's a FeatureCollection + if (inputData.type === "FeatureCollection" && inputData.features.length < 3) { + console.warn("Convex hull requires at least 3 points, got:", inputData.features.length); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + const hull = turf.convex(inputData); + + const result = hull ? { + type: "FeatureCollection", + features: [hull] + } : { + type: "FeatureCollection", + features: [] + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "convex_hull", result, {}, message.input_id); + } +} + +// Concave hull operation +function executeTurfConcaveHull(map, message, widgetId) { + const inputData = getInputData(map, message); + + // Ensure we have a FeatureCollection of Points for turf.concave + let pointCollection; + if (inputData.type === "FeatureCollection") { + // Filter to only Point geometries and ensure it's a proper FeatureCollection + const pointFeatures = inputData.features.filter(feature => + feature.geometry && feature.geometry.type === "Point" + ); + pointCollection = turf.featureCollection(pointFeatures); + } else if (inputData.type === "Feature" && inputData.geometry.type === "Point") { + // Single point - wrap in FeatureCollection + pointCollection = turf.featureCollection([inputData]); + } else { + console.warn("Concave hull requires Point geometries, received:", inputData); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + // Check if we have enough points (need at least 3 for a hull) + if (!pointCollection.features || pointCollection.features.length < 3) { + console.warn("Concave hull requires at least 3 points, got:", pointCollection.features?.length || 0); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + // Smart max_edge calculation with fallback + let hull = null; + let actualMaxEdge = message.max_edge; + + if (message.max_edge) { + // User specified max_edge, try it first + hull = turf.concave(pointCollection, { + maxEdge: message.max_edge, + units: message.units || "kilometers" + }); + } + + // If no hull or user didn't specify max_edge, try to find optimal value + if (!hull) { + // Calculate distances between all points to find reasonable max_edge + const distances = []; + const features = pointCollection.features; + + for (let i = 0; i < features.length; i++) { + for (let j = i + 1; j < features.length; j++) { + const dist = turf.distance(features[i], features[j], { + units: message.units || "kilometers" + }); + distances.push(dist); + } + } + + // Sort distances and try different percentiles as max_edge + distances.sort((a, b) => a - b); + const percentiles = [0.6, 0.7, 0.8, 0.9]; // Try 60th, 70th, 80th, 90th percentiles + + for (const percentile of percentiles) { + const index = Math.floor(distances.length * percentile); + const testMaxEdge = distances[index]; + + hull = turf.concave(pointCollection, { + maxEdge: testMaxEdge, + units: message.units || "kilometers" + }); + + if (hull) { + actualMaxEdge = testMaxEdge; + console.log(`Auto-calculated max_edge: ${testMaxEdge.toFixed(2)} ${message.units || "kilometers"}`); + break; + } + } + + // Final fallback - use convex hull if concave fails + if (!hull) { + console.warn("Concave hull failed, falling back to convex hull"); + hull = turf.convex(pointCollection); + actualMaxEdge = "convex_fallback"; + } + } + + const result = hull ? { + type: "FeatureCollection", + features: [hull] + } : { + type: "FeatureCollection", + features: [] + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "concave_hull", result, { + max_edge: message.max_edge, + units: message.units || "kilometers" + }, message.input_id); + } +} + +// Voronoi operation +function executeTurfVoronoi(map, message, widgetId) { + const inputData = getInputData(map, message); + + const options = {}; + let finalBbox = null; + let clippingData = null; + + // Handle bbox parameter + if (message.bbox) { + // Direct bbox array [minX, minY, maxX, maxY] + options.bbox = message.bbox; + finalBbox = message.bbox; + } else if (message.bbox_layer_id) { + // Extract bbox from layer + try { + const bboxSourceData = getSourceData(map, message.bbox_layer_id); + if (bboxSourceData) { + // Calculate bbox from layer data + const bbox = turf.bbox(bboxSourceData); + options.bbox = bbox; + finalBbox = bbox; + // Keep the layer data for potential intersection clipping + clippingData = bboxSourceData; + } + } catch (error) { + console.warn(`Could not extract bbox from layer ${message.bbox_layer_id}:`, error); + } + } + + let voronoi = turf.voronoi(inputData, options); + + // If we have clipping data (from bbox_layer_id), intersect each Voronoi polygon + if (voronoi && clippingData && clippingData.type === "FeatureCollection") { + const clippedFeatures = []; + + for (const voronoiFeature of voronoi.features) { + try { + // Try to intersect with each feature in the clipping layer + for (const clipFeature of clippingData.features) { + const intersection = turf.intersect(turf.featureCollection([voronoiFeature, clipFeature])); + if (intersection) { + clippedFeatures.push(intersection); + } + } + } catch (error) { + // If intersection fails, keep original feature + clippedFeatures.push(voronoiFeature); + } + } + + voronoi = { + type: "FeatureCollection", + features: clippedFeatures + }; + } + + // If property parameter is provided, use turf.collect to transfer attributes from points to polygons + if (voronoi && message.property && inputData.type === "FeatureCollection") { + try { + // Use turf.collect to gather point properties within each Voronoi polygon + const collected = turf.collect(voronoi, inputData, message.property, `${message.property}_collected`); + + // Since each Voronoi polygon should contain exactly one point, extract the single value from the array + for (const feature of collected.features) { + const collectedValues = feature.properties[`${message.property}_collected`]; + if (collectedValues && collectedValues.length > 0) { + // Take the first (and should be only) value and assign it directly to the property name + feature.properties[message.property] = collectedValues[0]; + // Remove the temporary array property + delete feature.properties[`${message.property}_collected`]; + } + } + + voronoi = collected; + } catch (error) { + console.warn(`Failed to collect property '${message.property}' from points to Voronoi polygons:`, error); + // Continue with uncollected voronoi if collection fails + } + } + + if (message.source_id && voronoi) { + addResultSource(map, voronoi, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "voronoi", voronoi, { + bbox: finalBbox, + bbox_layer_id: message.bbox_layer_id + }, message.input_id); + } +} + +// Distance operation +function executeTurfDistance(map, message, widgetId) { + let feature1, feature2; + + // Get first feature + if (message.coordinates) { + feature1 = turf.point(message.coordinates); + } else if (message.data) { + const sourceData1 = JSON.parse(message.data); + feature1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features[0] : sourceData1; + } else if (message.layer_id) { + const sourceData1 = getSourceData(map, message.layer_id); + feature1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features[0] : sourceData1; + } + + // Get second feature + if (message.coordinates_2) { + feature2 = turf.point(message.coordinates_2); + } else if (message.layer_id_2) { + const sourceData2 = getSourceData(map, message.layer_id_2); + feature2 = sourceData2.type === "FeatureCollection" ? + sourceData2.features[0] : sourceData2; + } + + const distance = turf.distance(feature1, feature2, { + units: message.units || "kilometers" + }); + + if (message.input_id) { + sendResultToR(widgetId, "distance", distance, { + units: message.units || "kilometers" + }, message.input_id); + } +} + +// Area operation +function executeTurfArea(map, message, widgetId) { + const inputData = getInputData(map, message); + + const area = turf.area(inputData); + + if (message.input_id) { + sendResultToR(widgetId, "area", area, { + units: "square_meters" + }, message.input_id); + } +} + +// Centroid operation (using turf.centroid - vertex average method) +function executeTurfCentroid(map, message, widgetId) { + const inputData = getInputData(map, message); + + const centroids = []; + + // Handle both single features and FeatureCollections + const features = inputData.type === "FeatureCollection" ? inputData.features : [inputData]; + + // Calculate centroid for each individual feature using turf.centroid + for (const feature of features) { + const centroid = turf.centroid(feature); + + // Preserve all properties from the source feature + if (feature.properties) { + centroid.properties = { ...feature.properties }; + } + + centroids.push(centroid); + } + + const result = { + type: "FeatureCollection", + features: centroids + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "centroid", result, {}, message.input_id); + } +} + +// Center of Mass operation (replaces centroid for better accuracy) +function executeTurfCenterOfMass(map, message, widgetId) { + const inputData = getInputData(map, message); + + const centers = []; + + // Handle both single features and FeatureCollections + const features = inputData.type === "FeatureCollection" ? inputData.features : [inputData]; + + // Calculate center of mass for each individual feature + for (const feature of features) { + const centerOfMass = turf.centerOfMass(feature, {}); + + // Preserve all properties from the source feature + if (feature.properties) { + centerOfMass.properties = { ...feature.properties }; + } + + centers.push(centerOfMass); + } + + const result = { + type: "FeatureCollection", + features: centers + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "center_of_mass", result, {}, message.input_id); + } +} + +// Filter operation +function executeTurfFilter(map, message, widgetId) { + const sourceData = getInputData(map, message); + + // Get filter geometry data + let filterData; + if (message.filter_data) { + // Handle filter_data directly + if (typeof message.filter_data === 'string') { + filterData = JSON.parse(message.filter_data); + } else { + filterData = message.filter_data; + } + } else if (message.filter_layer_id) { + // Handle filter_layer_id as before + filterData = getSourceData(map, message.filter_layer_id); + } else { + throw new Error("Either filter_data or filter_layer_id must be provided for filter operation"); + } + + // Extract features arrays + const features = sourceData.type === "FeatureCollection" ? + sourceData.features : [sourceData]; + const filterFeatures = filterData.type === "FeatureCollection" ? + filterData.features : [filterData]; + + // Collect filtered results + const resultFeatures = []; + + features.forEach((feature, index) => { + if (!feature || !feature.geometry) { + console.warn(`Skipping invalid feature at index ${index}`); + return; + } + + // Check if this feature matches the predicate against any filter feature + let matches = false; + + for (const filterFeature of filterFeatures) { + if (!filterFeature || !filterFeature.geometry) { + continue; + } + + try { + // Handle MultiPolygon geometries for within/contains predicates + if ((feature.geometry.type === 'MultiPolygon' || filterFeature.geometry.type === 'MultiPolygon') && + (message.predicate === 'within' || message.predicate === 'contains')) { + + // MultiPolygon handling for 'within' + if (message.predicate === 'within') { + if (feature.geometry.type === 'MultiPolygon') { + // All parts of the MultiPolygon must be within the filter + const polygons = feature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: feature.properties + })); + matches = polygons.every(poly => { + try { + return turf.booleanWithin(poly, filterFeature); + } catch (e) { + return false; + } + }); + } else if (filterFeature.geometry.type === 'MultiPolygon') { + // Feature must be within at least one part of the MultiPolygon + const polygons = filterFeature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: filterFeature.properties + })); + matches = polygons.some(poly => { + try { + return turf.booleanWithin(feature, poly); + } catch (e) { + return false; + } + }); + } + } + // MultiPolygon handling for 'contains' + else if (message.predicate === 'contains') { + if (feature.geometry.type === 'MultiPolygon') { + // At least one part of the MultiPolygon must contain the filter + const polygons = feature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: feature.properties + })); + matches = polygons.some(poly => { + try { + return turf.booleanContains(poly, filterFeature); + } catch (e) { + return false; + } + }); + } else if (filterFeature.geometry.type === 'MultiPolygon') { + // Feature must be contained by at least one part of the MultiPolygon + const polygons = filterFeature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: filterFeature.properties + })); + matches = polygons.some(poly => { + try { + return turf.booleanContains(poly, feature); + } catch (e) { + return false; + } + }); + } + } + } else { + // Use the appropriate boolean function based on predicate + switch (message.predicate) { + case "intersects": + matches = turf.booleanIntersects(feature, filterFeature); + break; + case "within": + matches = turf.booleanWithin(feature, filterFeature); + break; + case "contains": + matches = turf.booleanContains(feature, filterFeature); + break; + case "crosses": + matches = turf.booleanCrosses(feature, filterFeature); + break; + case "disjoint": + matches = turf.booleanDisjoint(feature, filterFeature); + break; + default: + console.warn(`Unknown predicate: ${message.predicate}`); + continue; + } + } + + if (matches) { + break; // Found a match, no need to check other filter features + } + } catch (error) { + console.error(`Error testing predicate ${message.predicate}:`, error); + continue; + } + } + + // If this feature matches the predicate, add it to results + if (matches) { + // Preserve all properties from the original feature + const resultFeature = { + ...feature, + properties: { ...feature.properties } + }; + resultFeatures.push(resultFeature); + } + }); + + const result = { + type: "FeatureCollection", + features: resultFeatures + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "filter", result, { + predicate: message.predicate, + filtered_count: resultFeatures.length, + total_count: features.length + }, message.input_id); + } +} \ No newline at end of file diff --git a/docs/articles/turf_files/freehand-mode-1.0.0/freehand-mode.js b/docs/articles/turf_files/freehand-mode-1.0.0/freehand-mode.js new file mode 100644 index 0000000..6b2b9e8 --- /dev/null +++ b/docs/articles/turf_files/freehand-mode-1.0.0/freehand-mode.js @@ -0,0 +1,207 @@ +// This code is derived from the ISC-licensed "mapbox-gl-draw-freehand-mode" plugin +// by Ben Ehmke, Eric Dong, and Joe Woodhouse. +// Source: https://github.com/bemky/mapbox-gl-draw-freehand-mode +(function (MapboxDraw) { + const { geojsonTypes, cursors, types, updateActions, modes, events } = + MapboxDraw.constants; + + const FreehandMode = {}; + + FreehandMode.onSetup = function () { + const polygon = this.newFeature({ + type: geojsonTypes.FEATURE, + properties: {}, + geometry: { + type: geojsonTypes.POLYGON, + coordinates: [[]], + }, + }); + + this.addFeature(polygon); + this.clearSelectedFeatures(); + + // Disable map dragging + setTimeout(() => { + if (!this.map || !this.map.dragPan) return; + this.map.dragPan.disable(); + }, 0); + + this.updateUIClasses({ mouse: cursors.ADD }); + this.activateUIButton(types.POLYGON); + this.setActionableState({ + trash: true, + }); + + return { + polygon, + currentVertexPosition: 0, + dragMoving: false, + isDrawing: false, + }; + }; + + FreehandMode.onDrag = FreehandMode.onTouchMove = function (state, e) { + state.dragMoving = true; + state.isDrawing = true; + this.updateUIClasses({ mouse: cursors.ADD }); + state.polygon.updateCoordinate( + `0.${state.currentVertexPosition}`, + e.lngLat.lng, + e.lngLat.lat, + ); + state.currentVertexPosition++; + state.polygon.updateCoordinate( + `0.${state.currentVertexPosition}`, + e.lngLat.lng, + e.lngLat.lat, + ); + }; + + FreehandMode.onMouseUp = function (state) { + if (state.dragMoving) { + this.simplify(state.polygon); + this.updateUIClasses({ mouse: cursors.MOVE }); + this.fireUpdate(); + this.changeMode(modes.SIMPLE_SELECT, { + featureIds: [state.polygon.id], + }); + } + }; + + FreehandMode.fireCreate = function (polygon) { + this.map.fire(events.CREATE, { + features: [polygon.toGeoJSON()], + }); + }; + + FreehandMode.fireUpdate = function () { + this.map.fire(events.UPDATE, { + action: updateActions.MOVE, + features: this.getSelected().map((f) => f.toGeoJSON()), + }); + }; + + FreehandMode.simplify = function (polygon) { + if (!this.map.simplify_freehand) return; + + const tolerance = 1 / Math.pow(1.05, 10 * this.map.getZoom()); + const simplifiedCoords = simplifyGeometry( + polygon.coordinates[0], + tolerance, + ); + polygon.setCoordinates([simplifiedCoords]); + }; + + function simplifyGeometry(points, tolerance) { + if (points.length <= 2) return points; + + const sqTolerance = tolerance * tolerance; + const last = points.length - 1; + const simplified = [points[0]]; + simplifyDPStep(points, 0, last, sqTolerance, simplified); + simplified.push(points[last]); + + return simplified; + } + + function simplifyDPStep(points, first, last, sqTolerance, simplified) { + let maxSqDist = sqTolerance; + let index; + + for (let i = first + 1; i < last; i++) { + const sqDist = getSquareSegmentDistance( + points[i], + points[first], + points[last], + ); + if (sqDist > maxSqDist) { + index = i; + maxSqDist = sqDist; + } + } + + if (maxSqDist > sqTolerance) { + if (index - first > 1) + simplifyDPStep(points, first, index, sqTolerance, simplified); + simplified.push(points[index]); + if (last - index > 1) + simplifyDPStep(points, index, last, sqTolerance, simplified); + } + } + + function getSquareSegmentDistance(p, p1, p2) { + let x = p1[0], + y = p1[1]; + let dx = p2[0] - x, + dy = p2[1] - y; + + if (dx !== 0 || dy !== 0) { + const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy); + if (t > 1) { + x = p2[0]; + y = p2[1]; + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } + + dx = p[0] - x; + dy = p[1] - y; + + return dx * dx + dy * dy; + } + + FreehandMode.onStop = function (state) { + this.updateUIClasses({ mouse: cursors.NONE }); + this.activateUIButton(); + + // Enable map dragging + setTimeout(() => { + if (!this.map || !this.map.dragPan) return; + this.map.dragPan.enable(); + }, 0); + }; + + FreehandMode.toDisplayFeatures = function (state, geojson, display) { + const isActivePolygon = geojson.properties.id === state.polygon.id; + geojson.properties.active = isActivePolygon ? "true" : "false"; + if (!isActivePolygon) return display(geojson); + + // Only render the polygon if it has at least three points + if (geojson.geometry.coordinates[0].length < 3) return; + + const coordinateCount = geojson.geometry.coordinates[0].length; + + // If we have fewer than three coordinates, we need to create a LineString instead of a Polygon + if (coordinateCount < 3) { + const lineCoordinates = [ + [ + geojson.geometry.coordinates[0][0][0], + geojson.geometry.coordinates[0][0][1], + ], + [ + geojson.geometry.coordinates[0][1][0], + geojson.geometry.coordinates[0][1][1], + ], + ]; + return display({ + type: geojsonTypes.FEATURE, + properties: geojson.properties, + geometry: { + coordinates: lineCoordinates, + type: geojsonTypes.LINE_STRING, + }, + }); + } + + return display(geojson); + }; + + FreehandMode.onTrash = function (state) { + this.deleteFeature([state.polygon.id], { silent: true }); + this.changeMode(modes.SIMPLE_SELECT); + }; + + MapboxDraw.modes.draw_freehand = FreehandMode; +})(MapboxDraw); diff --git a/docs/articles/turf_files/h3j-h3t-0.9.2/h3j_h3t.js b/docs/articles/turf_files/h3j-h3t-0.9.2/h3j_h3t.js new file mode 100644 index 0000000..16631aa --- /dev/null +++ b/docs/articles/turf_files/h3j-h3t-0.9.2/h3j_h3t.js @@ -0,0 +1,3 @@ +!function(A){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=A();else if("function"==typeof define&&define.amd)define([],A);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).h3j_h3t=A()}}((function(){return function A(e,r,t){function i(o,a){if(!r[o]){if(!e[o]){var f="function"==typeof require&&require;if(!a&&f)return f(o,!0);if(n)return n(o,!0);var s=new Error("Cannot find module '"+o+"'");throw s.code="MODULE_NOT_FOUND",s}var u=r[o]={exports:{}};e[o][0].call(u.exports,(function(A){return i(e[o][1][A]||A)}),u,u.exports,A,e,r,t)}return r[o].exports}for(var n="function"==typeof require&&require,o=0;o>3}if(n--,1===i||2===i)o+=A.readSVarint(),a+=A.readSVarint(),1===i&&(e&&f.push(e),e=[]),e.push(new t(o,a));else{if(7!==i)throw new Error("unknown command "+i);e&&e.push(e[0].clone())}}return e&&f.push(e),f},i.prototype.bbox=function(){var A=this._pbf;A.pos=this._geometry;for(var e=A.readVarint()+A.pos,r=1,t=0,i=0,n=0,o=1/0,a=-1/0,f=1/0,s=-1/0;A.pos>3}if(t--,1===r||2===r)(i+=A.readSVarint())a&&(a=i),(n+=A.readSVarint())s&&(s=n);else if(7!==r)throw new Error("unknown command "+r)}return[o,f,a,s]},i.prototype.toGeoJSON=function(A,e,r){var t,n,a=this.extent*Math.pow(2,r),f=this.extent*A,s=this.extent*e,u=this.loadGeometry(),l=i.types[this.type];function h(A){for(var e=0;e>3;e=1===t?A.readString():2===t?A.readFloat():3===t?A.readDouble():4===t?A.readVarint64():5===t?A.readVarint():6===t?A.readSVarint():7===t?A.readBoolean():null}return e}(r))}e.exports=i,i.prototype.feature=function(A){if(A<0||A>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[A];var e=this._pbf.readVarint()+this._pbf.pos;return new t(this._pbf,e,this.extent,this._keys,this._values)}},{"./vectortilefeature.js":4}],6:[function(A,e,r){!function(A,t){"object"==typeof r&&void 0!==e?e.exports=t():A.geojsonvt=t()}(this,(function(){"use strict";function A(r,t,i,n){for(var o,a=n,f=i-t>>1,s=i-t,u=r[t],l=r[t+1],h=r[i],c=r[i+1],d=t+3;da)o=d,a=g;else if(g===a){var w=Math.abs(d-f);wn&&(o-t>3&&A(r,t,o,n),r[o+2]=a,i-o>3&&A(r,o,i,n))}function e(A,e,r,t,i,n){var o=i-r,a=n-t;if(0!==o||0!==a){var f=((A-r)*o+(e-t)*a)/(o*o+a*a);f>1?(r=i,t=n):f>0&&(r+=o*f,t+=a*f)}return(o=A-r)*o+(a=e-t)*a}function r(A,e,r,i){var n={id:void 0===A?null:A,type:e,geometry:r,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(A){var e=A.geometry,r=A.type;if("Point"===r||"MultiPoint"===r||"LineString"===r)t(A,e);else if("Polygon"===r||"MultiLineString"===r)for(var i=0;i0&&(a+=i?(n*h-l*o)/2:Math.sqrt(Math.pow(l-n,2)+Math.pow(h-o,2))),n=l,o=h}var c=r.length-3;r[2]=1,A(r,0,c,t),r[c+2]=1,r.size=Math.abs(a),r.start=0,r.end=r.size}function a(A,e,r,t){for(var i=0;i1?1:r}function u(A,e,t,i,n,o,a,f){if(i/=e,o>=(t/=e)&&a=i)return null;for(var s=[],u=0;u=t&&B=i)){var b=[];if("Point"===w||"MultiPoint"===w)l(g,b,t,i,n);else if("LineString"===w)h(g,b,t,i,n,!1,f.lineMetrics);else if("MultiLineString"===w)d(g,b,t,i,n,!1);else if("Polygon"===w)d(g,b,t,i,n,!0);else if("MultiPolygon"===w)for(var v=0;v=r&&o<=t&&(e.push(A[n]),e.push(A[n+1]),e.push(A[n+2]))}}function h(A,e,r,t,i,n,o){for(var a,f,s=c(A),u=0===i?w:p,l=A.start,h=0;hr&&(f=u(s,d,B,v,m,r),o&&(s.start=l+a*f)):k>t?M=r&&(f=u(s,d,B,v,m,r),Q=!0),M>t&&k<=t&&(f=u(s,d,B,v,m,t),Q=!0),!n&&Q&&(o&&(s.end=l+a*f),e.push(s),s=c(A)),o&&(l+=a)}var y=A.length-3;d=A[y],B=A[y+1],b=A[y+2],(k=0===i?d:B)>=r&&k<=t&&g(s,d,B,b),y=s.length-3,n&&y>=3&&(s[y]!==s[0]||s[y+1]!==s[1])&&g(s,s[0],s[1],s[2]),s.length&&e.push(s)}function c(A){var e=[];return e.size=A.size,e.start=A.start,e.end=A.end,e}function d(A,e,r,t,i,n){for(var o=0;oo.maxX&&(o.maxX=u),l>o.maxY&&(o.maxY=l)}return o}function M(A,e,r,t){var i=e.geometry,n=e.type,o=[];if("Point"===n||"MultiPoint"===n)for(var a=0;a0&&e.size<(i?o:t))r.numPoints+=e.length/3;else{for(var a=[],f=0;fo)&&(r.numSimplified++,a.push(e[f]),a.push(e[f+1])),r.numPoints++;i&&function(A,e){for(var r=0,t=0,i=A.length,n=i-2;t0===e)for(t=0,i=A.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(e.promoteId&&e.generateId)throw new Error("promoteId and generateId cannot be used together.");var t=function(A,e){var r=[];if("FeatureCollection"===A.type)for(var t=0;t1&&console.time("creation"),c=this.tiles[h]=k(A,e,r,t,f),this.tileCoords.push({z:e,x:r,y:t}),s)){s>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,r,t,c.numFeatures,c.numPoints,c.numSimplified),console.timeEnd("creation"));var d="z"+e;this.stats[d]=(this.stats[d]||0)+1,this.total++}if(c.source=A,i){if(e===f.maxZoom||e===i)continue;var g=1<1&&console.time("clipping");var w,p,B,b,v,m,M=.5*f.buffer/f.extent,Q=.5-M,y=.5+M,x=1+M;w=p=B=b=null,v=u(A,l,r-M,r+y,0,c.minX,c.maxX,f),m=u(A,l,r+Q,r+x,0,c.minX,c.maxX,f),A=null,v&&(w=u(v,l,t-M,t+y,1,c.minY,c.maxY,f),p=u(v,l,t+Q,t+x,1,c.minY,c.maxY,f),v=null),m&&(B=u(m,l,t-M,t+y,1,c.minY,c.maxY,f),b=u(m,l,t+Q,t+x,1,c.minY,c.maxY,f),m=null),s>1&&console.timeEnd("clipping"),a.push(w||[],e+1,2*r,2*t),a.push(p||[],e+1,2*r,2*t+1),a.push(B||[],e+1,2*r+1,2*t),a.push(b||[],e+1,2*r+1,2*t+1)}}},y.prototype.getTile=function(A,e,r){var t=this.options,i=t.extent,n=t.debug;if(A<0||A>24)return null;var o=1<1&&console.log("drilling down to z%d-%d-%d",A,e,r);for(var f,s=A,u=e,l=r;!f&&s>0;)s--,u=Math.floor(u/2),l=Math.floor(l/2),f=this.tiles[E(s,u,l)];return f&&f.source?(n>1&&console.log("found parent tile z%d-%d-%d",s,u,l),n>1&&console.time("drilling down"),this.splitTile(f.source,s,u,l,A,e,r),n>1&&console.timeEnd("drilling down"),this.tiles[a]?v(this.tiles[a],i):null):null},function(A,e){return new y(A,e)}}))},{}],7:[function(A,e,r){var t=function(A){var e,r=void 0!==(A=A||{})?A:{},t={};for(e in r)r.hasOwnProperty(e)&&(t[e]=r[e]);var i,n=[],o="";document.currentScript&&(o=document.currentScript.src),o=0!==o.indexOf("blob:")?o.substr(0,o.lastIndexOf("/")+1):"",i=function(A,e,r){var t=new XMLHttpRequest;t.open("GET",A,!0),t.responseType="arraybuffer",t.onload=function(){if(200==t.status||0==t.status&&t.response)e(t.response);else{var i=J(A);i?e(i.buffer):r()}},t.onerror=r,t.send(null)};var a=r.print||console.log.bind(console),f=r.printErr||console.warn.bind(console);for(e in t)t.hasOwnProperty(e)&&(r[e]=t[e]);t=null,r.arguments&&(n=r.arguments);var s=0,u=function(){return s};var l=!1;function h(A){var e,t=r["_"+A];return e="Cannot call unknown function "+A+", make sure it is exported",t||fA("Assertion failed: "+e),t}function c(A,e,r,t,i){var n={string:function(A){var e=0;if(null!=A&&0!==A){var r=1+(A.length<<2);(function(A,e,r){(function(A,e,r,t){if(!(t>0))return 0;for(var i=r,n=r+t-1,o=0;o=55296&&a<=57343)a=65536+((1023&a)<<10)|1023&A.charCodeAt(++o);if(a<=127){if(r>=n)break;e[r++]=a}else if(a<=2047){if(r+1>=n)break;e[r++]=192|a>>6,e[r++]=128|63&a}else if(a<=65535){if(r+2>=n)break;e[r++]=224|a>>12,e[r++]=128|a>>6&63,e[r++]=128|63&a}else{if(r+3>=n)break;e[r++]=240|a>>18,e[r++]=128|a>>12&63,e[r++]=128|a>>6&63,e[r++]=128|63&a}}e[r]=0})(A,B,e,r)})(A,e=AA(r),r)}return e},array:function(A){var e=AA(A.length);return function(A,e){p.set(A,e)}(A,e),e}};var o=h(A),a=[],f=0;if(t)for(var s=0;s=t);)++i;if(i-e>16&&A.subarray&&d)return d.decode(A.subarray(e,i));for(var n="";e>10,56320|1023&s)}}else n+=String.fromCharCode((31&o)<<6|a)}else n+=String.fromCharCode(o)}return n}(B,A,e):""}var w,p,B,b,v,m,k;"undefined"!=typeof TextDecoder&&new TextDecoder("utf-16le");function M(A,e){return A%e>0&&(A+=e-A%e),A}function Q(A){w=A,r.HEAP8=p=new Int8Array(A),r.HEAP16=b=new Int16Array(A),r.HEAP32=v=new Int32Array(A),r.HEAPU8=B=new Uint8Array(A),r.HEAPU16=new Uint16Array(A),r.HEAPU32=new Uint32Array(A),r.HEAPF32=m=new Float32Array(A),r.HEAPF64=k=new Float64Array(A)}var y=r.TOTAL_MEMORY||33554432;function E(A){for(;A.length>0;){var e=A.shift();if("function"!=typeof e){var t=e.func;"number"==typeof t?void 0===e.arg?r.dynCall_v(t):r.dynCall_vi(t,e.arg):t(void 0===e.arg?null:e.arg)}else e()}}y=(w=r.buffer?r.buffer:new ArrayBuffer(y)).byteLength,Q(w),v[6004]=5266928;var x=[],D=[],_=[],I=[];var F=Math.abs,C=Math.ceil,P=Math.floor,U=Math.min,G=0,S=null,T=null;r.preloadedImages={},r.preloadedAudios={};var V,H,R=null,L="data:application/octet-stream;base64,";function z(A){return String.prototype.startsWith?A.startsWith(L):0===A.indexOf(L)}R="data:application/octet-stream;base64,AAAAAAAAAAACAAAAAwAAAAEAAAAFAAAABAAAAAYAAAAAAAAAAAAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAYAAAABAAAABAAAAAMAAAAGAAAABQAAAAIAAAAAAAAAAgAAAAMAAAABAAAABAAAAAYAAAAAAAAABQAAAAMAAAAGAAAABAAAAAUAAAAAAAAAAQAAAAIAAAAEAAAABQAAAAYAAAAAAAAAAgAAAAMAAAABAAAABQAAAAIAAAAAAAAAAQAAAAMAAAAGAAAABAAAAAYAAAAAAAAABQAAAAIAAAABAAAABAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAgAAAAMAAAAAAAAAAAAAAAIAAAAAAAAAAQAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAABgAAAAAAAAAFAAAAAAAAAAAAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAIAAAAAAAAABgAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAgAAAAAAAAAAAAAABgAAAAAAAAADAAAAAgAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAUAAAAEAAAAAAAAAAEAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAEAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAUAAAACAAAABAAAAAMAAAAIAAAAAQAAAAcAAAAGAAAACQAAAAAAAAADAAAAAgAAAAIAAAAGAAAACgAAAAsAAAAAAAAAAQAAAAUAAAADAAAADQAAAAEAAAAHAAAABAAAAAwAAAAAAAAABAAAAH8AAAAPAAAACAAAAAMAAAAAAAAADAAAAAUAAAACAAAAEgAAAAoAAAAIAAAAAAAAABAAAAAGAAAADgAAAAsAAAARAAAAAQAAAAkAAAACAAAABwAAABUAAAAJAAAAEwAAAAMAAAANAAAAAQAAAAgAAAAFAAAAFgAAABAAAAAEAAAAAAAAAA8AAAAJAAAAEwAAAA4AAAAUAAAAAQAAAAcAAAAGAAAACgAAAAsAAAAYAAAAFwAAAAUAAAACAAAAEgAAAAsAAAARAAAAFwAAABkAAAACAAAABgAAAAoAAAAMAAAAHAAAAA0AAAAaAAAABAAAAA8AAAADAAAADQAAABoAAAAVAAAAHQAAAAMAAAAMAAAABwAAAA4AAAB/AAAAEQAAABsAAAAJAAAAFAAAAAYAAAAPAAAAFgAAABwAAAAfAAAABAAAAAgAAAAMAAAAEAAAABIAAAAhAAAAHgAAAAgAAAAFAAAAFgAAABEAAAALAAAADgAAAAYAAAAjAAAAGQAAABsAAAASAAAAGAAAAB4AAAAgAAAABQAAAAoAAAAQAAAAEwAAACIAAAAUAAAAJAAAAAcAAAAVAAAACQAAABQAAAAOAAAAEwAAAAkAAAAoAAAAGwAAACQAAAAVAAAAJgAAABMAAAAiAAAADQAAAB0AAAAHAAAAFgAAABAAAAApAAAAIQAAAA8AAAAIAAAAHwAAABcAAAAYAAAACwAAAAoAAAAnAAAAJQAAABkAAAAYAAAAfwAAACAAAAAlAAAACgAAABcAAAASAAAAGQAAABcAAAARAAAACwAAAC0AAAAnAAAAIwAAABoAAAAqAAAAHQAAACsAAAAMAAAAHAAAAA0AAAAbAAAAKAAAACMAAAAuAAAADgAAABQAAAARAAAAHAAAAB8AAAAqAAAALAAAAAwAAAAPAAAAGgAAAB0AAAArAAAAJgAAAC8AAAANAAAAGgAAABUAAAAeAAAAIAAAADAAAAAyAAAAEAAAABIAAAAhAAAAHwAAACkAAAAsAAAANQAAAA8AAAAWAAAAHAAAACAAAAAeAAAAGAAAABIAAAA0AAAAMgAAACUAAAAhAAAAHgAAADEAAAAwAAAAFgAAABAAAAApAAAAIgAAABMAAAAmAAAAFQAAADYAAAAkAAAAMwAAACMAAAAuAAAALQAAADgAAAARAAAAGwAAABkAAAAkAAAAFAAAACIAAAATAAAANwAAACgAAAA2AAAAJQAAACcAAAA0AAAAOQAAABgAAAAXAAAAIAAAACYAAAB/AAAAIgAAADMAAAAdAAAALwAAABUAAAAnAAAAJQAAABkAAAAXAAAAOwAAADkAAAAtAAAAKAAAABsAAAAkAAAAFAAAADwAAAAuAAAANwAAACkAAAAxAAAANQAAAD0AAAAWAAAAIQAAAB8AAAAqAAAAOgAAACsAAAA+AAAAHAAAACwAAAAaAAAAKwAAAD4AAAAvAAAAQAAAABoAAAAqAAAAHQAAACwAAAA1AAAAOgAAAEEAAAAcAAAAHwAAACoAAAAtAAAAJwAAACMAAAAZAAAAPwAAADsAAAA4AAAALgAAADwAAAA4AAAARAAAABsAAAAoAAAAIwAAAC8AAAAmAAAAKwAAAB0AAABFAAAAMwAAAEAAAAAwAAAAMQAAAB4AAAAhAAAAQwAAAEIAAAAyAAAAMQAAAH8AAAA9AAAAQgAAACEAAAAwAAAAKQAAADIAAAAwAAAAIAAAAB4AAABGAAAAQwAAADQAAAAzAAAARQAAADYAAABHAAAAJgAAAC8AAAAiAAAANAAAADkAAABGAAAASgAAACAAAAAlAAAAMgAAADUAAAA9AAAAQQAAAEsAAAAfAAAAKQAAACwAAAA2AAAARwAAADcAAABJAAAAIgAAADMAAAAkAAAANwAAACgAAAA2AAAAJAAAAEgAAAA8AAAASQAAADgAAABEAAAAPwAAAE0AAAAjAAAALgAAAC0AAAA5AAAAOwAAAEoAAABOAAAAJQAAACcAAAA0AAAAOgAAAH8AAAA+AAAATAAAACwAAABBAAAAKgAAADsAAAA/AAAATgAAAE8AAAAnAAAALQAAADkAAAA8AAAASAAAAEQAAABQAAAAKAAAADcAAAAuAAAAPQAAADUAAAAxAAAAKQAAAFEAAABLAAAAQgAAAD4AAAArAAAAOgAAACoAAABSAAAAQAAAAEwAAAA/AAAAfwAAADgAAAAtAAAATwAAADsAAABNAAAAQAAAAC8AAAA+AAAAKwAAAFQAAABFAAAAUgAAAEEAAAA6AAAANQAAACwAAABWAAAATAAAAEsAAABCAAAAQwAAAFEAAABVAAAAMQAAADAAAAA9AAAAQwAAAEIAAAAyAAAAMAAAAFcAAABVAAAARgAAAEQAAAA4AAAAPAAAAC4AAABaAAAATQAAAFAAAABFAAAAMwAAAEAAAAAvAAAAWQAAAEcAAABUAAAARgAAAEMAAAA0AAAAMgAAAFMAAABXAAAASgAAAEcAAABZAAAASQAAAFsAAAAzAAAARQAAADYAAABIAAAAfwAAAEkAAAA3AAAAUAAAADwAAABYAAAASQAAAFsAAABIAAAAWAAAADYAAABHAAAANwAAAEoAAABOAAAAUwAAAFwAAAA0AAAAOQAAAEYAAABLAAAAQQAAAD0AAAA1AAAAXgAAAFYAAABRAAAATAAAAFYAAABSAAAAYAAAADoAAABBAAAAPgAAAE0AAAA/AAAARAAAADgAAABdAAAATwAAAFoAAABOAAAASgAAADsAAAA5AAAAXwAAAFwAAABPAAAATwAAAE4AAAA/AAAAOwAAAF0AAABfAAAATQAAAFAAAABEAAAASAAAADwAAABjAAAAWgAAAFgAAABRAAAAVQAAAF4AAABlAAAAPQAAAEIAAABLAAAAUgAAAGAAAABUAAAAYgAAAD4AAABMAAAAQAAAAFMAAAB/AAAASgAAAEYAAABkAAAAVwAAAFwAAABUAAAARQAAAFIAAABAAAAAYQAAAFkAAABiAAAAVQAAAFcAAABlAAAAZgAAAEIAAABDAAAAUQAAAFYAAABMAAAASwAAAEEAAABoAAAAYAAAAF4AAABXAAAAUwAAAGYAAABkAAAAQwAAAEYAAABVAAAAWAAAAEgAAABbAAAASQAAAGMAAABQAAAAaQAAAFkAAABhAAAAWwAAAGcAAABFAAAAVAAAAEcAAABaAAAATQAAAFAAAABEAAAAagAAAF0AAABjAAAAWwAAAEkAAABZAAAARwAAAGkAAABYAAAAZwAAAFwAAABTAAAATgAAAEoAAABsAAAAZAAAAF8AAABdAAAATwAAAFoAAABNAAAAbQAAAF8AAABqAAAAXgAAAFYAAABRAAAASwAAAGsAAABoAAAAZQAAAF8AAABcAAAATwAAAE4AAABtAAAAbAAAAF0AAABgAAAAaAAAAGIAAABuAAAATAAAAFYAAABSAAAAYQAAAH8AAABiAAAAVAAAAGcAAABZAAAAbwAAAGIAAABuAAAAYQAAAG8AAABSAAAAYAAAAFQAAABjAAAAUAAAAGkAAABYAAAAagAAAFoAAABxAAAAZAAAAGYAAABTAAAAVwAAAGwAAAByAAAAXAAAAGUAAABmAAAAawAAAHAAAABRAAAAVQAAAF4AAABmAAAAZQAAAFcAAABVAAAAcgAAAHAAAABkAAAAZwAAAFsAAABhAAAAWQAAAHQAAABpAAAAbwAAAGgAAABrAAAAbgAAAHMAAABWAAAAXgAAAGAAAABpAAAAWAAAAGcAAABbAAAAcQAAAGMAAAB0AAAAagAAAF0AAABjAAAAWgAAAHUAAABtAAAAcQAAAGsAAAB/AAAAZQAAAF4AAABzAAAAaAAAAHAAAABsAAAAZAAAAF8AAABcAAAAdgAAAHIAAABtAAAAbQAAAGwAAABdAAAAXwAAAHUAAAB2AAAAagAAAG4AAABiAAAAaAAAAGAAAAB3AAAAbwAAAHMAAABvAAAAYQAAAG4AAABiAAAAdAAAAGcAAAB3AAAAcAAAAGsAAABmAAAAZQAAAHgAAABzAAAAcgAAAHEAAABjAAAAdAAAAGkAAAB1AAAAagAAAHkAAAByAAAAcAAAAGQAAABmAAAAdgAAAHgAAABsAAAAcwAAAG4AAABrAAAAaAAAAHgAAAB3AAAAcAAAAHQAAABnAAAAdwAAAG8AAABxAAAAaQAAAHkAAAB1AAAAfwAAAG0AAAB2AAAAcQAAAHkAAABqAAAAdgAAAHgAAABsAAAAcgAAAHUAAAB5AAAAbQAAAHcAAABvAAAAcwAAAG4AAAB5AAAAdAAAAHgAAAB4AAAAcwAAAHIAAABwAAAAeQAAAHcAAAB2AAAAeQAAAHQAAAB4AAAAdwAAAHUAAABxAAAAdgAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAEAAAAFAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAIAAAAFAAAAAQAAAAAAAAD/////AQAAAAAAAAADAAAABAAAAAIAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAUAAAABAAAAAAAAAAAAAAABAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAAFAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAQAAAAFAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAADAAAAAAAAAAAAAAABAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAABAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAADAAAABQAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAADAAAAAAAAAAAAAAABAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAADAAAAAQAAAAAAAAABAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAMAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAADAAAABQAAAAEAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAEAAAABQAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAgAAAAUAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAABQAAAAAAAAAAAAAABQAAAAUAAAAAAAAAAAAAAP////8BAAAAAAAAAAMAAAAEAAAAAgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAABQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAABQAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAQAAAP//////////AQAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAIAAAAAAAAAAAAAAAEAAAACAAAABgAAAAQAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAABwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAoAAAACAAAAAAAAAAAAAAABAAAAAQAAAAUAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAsAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAIAAAAAAAAAAAAAAAEAAAADAAAABwAAAAYAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAHAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAABAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAOAAAAAgAAAAAAAAAAAAAAAQAAAAAAAAAJAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAwAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAgAAAAAAAAAAAAAAAQAAAAQAAAAIAAAACgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAsAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAACAAAAAAAAAAAAAAABAAAACwAAAA8AAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA4AAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAgAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAFAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAACAAAAAAAAAAAAAAABAAAADAAAABAAAAAMAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAEAAAAKAAAAEwAAAAgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAADwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAJAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAgAAAAAAAAAAAAAAAQAAAA0AAAARAAAADQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAABEAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAADQAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAIAAAAAAAAAAAAAAAEAAAAOAAAAEgAAAA8AAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAPAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAABIAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAEQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABMAAAACAAAAAAAAAAAAAAABAAAA//////////8TAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAASAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABIAAAAAAAAAGAAAAAAAAAAhAAAAAAAAAB4AAAAAAAAAIAAAAAMAAAAxAAAAAQAAADAAAAADAAAAMgAAAAMAAAAIAAAAAAAAAAUAAAAFAAAACgAAAAUAAAAWAAAAAAAAABAAAAAAAAAAEgAAAAAAAAApAAAAAQAAACEAAAAAAAAAHgAAAAAAAAAEAAAAAAAAAAAAAAAFAAAAAgAAAAUAAAAPAAAAAQAAAAgAAAAAAAAABQAAAAUAAAAfAAAAAQAAABYAAAAAAAAAEAAAAAAAAAACAAAAAAAAAAYAAAAAAAAADgAAAAAAAAAKAAAAAAAAAAsAAAAAAAAAEQAAAAMAAAAYAAAAAQAAABcAAAADAAAAGQAAAAMAAAAAAAAAAAAAAAEAAAAFAAAACQAAAAUAAAAFAAAAAAAAAAIAAAAAAAAABgAAAAAAAAASAAAAAQAAAAoAAAAAAAAACwAAAAAAAAAEAAAAAQAAAAMAAAAFAAAABwAAAAUAAAAIAAAAAQAAAAAAAAAAAAAAAQAAAAUAAAAQAAAAAQAAAAUAAAAAAAAAAgAAAAAAAAAHAAAAAAAAABUAAAAAAAAAJgAAAAAAAAAJAAAAAAAAABMAAAAAAAAAIgAAAAMAAAAOAAAAAQAAABQAAAADAAAAJAAAAAMAAAADAAAAAAAAAA0AAAAFAAAAHQAAAAUAAAABAAAAAAAAAAcAAAAAAAAAFQAAAAAAAAAGAAAAAQAAAAkAAAAAAAAAEwAAAAAAAAAEAAAAAgAAAAwAAAAFAAAAGgAAAAUAAAAAAAAAAQAAAAMAAAAAAAAADQAAAAUAAAACAAAAAQAAAAEAAAAAAAAABwAAAAAAAAAaAAAAAAAAACoAAAAAAAAAOgAAAAAAAAAdAAAAAAAAACsAAAAAAAAAPgAAAAMAAAAmAAAAAQAAAC8AAAADAAAAQAAAAAMAAAAMAAAAAAAAABwAAAAFAAAALAAAAAUAAAANAAAAAAAAABoAAAAAAAAAKgAAAAAAAAAVAAAAAQAAAB0AAAAAAAAAKwAAAAAAAAAEAAAAAwAAAA8AAAAFAAAAHwAAAAUAAAADAAAAAQAAAAwAAAAAAAAAHAAAAAUAAAAHAAAAAQAAAA0AAAAAAAAAGgAAAAAAAAAfAAAAAAAAACkAAAAAAAAAMQAAAAAAAAAsAAAAAAAAADUAAAAAAAAAPQAAAAMAAAA6AAAAAQAAAEEAAAADAAAASwAAAAMAAAAPAAAAAAAAABYAAAAFAAAAIQAAAAUAAAAcAAAAAAAAAB8AAAAAAAAAKQAAAAAAAAAqAAAAAQAAACwAAAAAAAAANQAAAAAAAAAEAAAABAAAAAgAAAAFAAAAEAAAAAUAAAAMAAAAAQAAAA8AAAAAAAAAFgAAAAUAAAAaAAAAAQAAABwAAAAAAAAAHwAAAAAAAAAyAAAAAAAAADAAAAAAAAAAMQAAAAMAAAAgAAAAAAAAAB4AAAADAAAAIQAAAAMAAAAYAAAAAwAAABIAAAADAAAAEAAAAAMAAABGAAAAAAAAAEMAAAAAAAAAQgAAAAMAAAA0AAAAAwAAADIAAAAAAAAAMAAAAAAAAAAlAAAAAwAAACAAAAAAAAAAHgAAAAMAAABTAAAAAAAAAFcAAAADAAAAVQAAAAMAAABKAAAAAwAAAEYAAAAAAAAAQwAAAAAAAAA5AAAAAQAAADQAAAADAAAAMgAAAAAAAAAZAAAAAAAAABcAAAAAAAAAGAAAAAMAAAARAAAAAAAAAAsAAAADAAAACgAAAAMAAAAOAAAAAwAAAAYAAAADAAAAAgAAAAMAAAAtAAAAAAAAACcAAAAAAAAAJQAAAAMAAAAjAAAAAwAAABkAAAAAAAAAFwAAAAAAAAAbAAAAAwAAABEAAAAAAAAACwAAAAMAAAA/AAAAAAAAADsAAAADAAAAOQAAAAMAAAA4AAAAAwAAAC0AAAAAAAAAJwAAAAAAAAAuAAAAAwAAACMAAAADAAAAGQAAAAAAAAAkAAAAAAAAABQAAAAAAAAADgAAAAMAAAAiAAAAAAAAABMAAAADAAAACQAAAAMAAAAmAAAAAwAAABUAAAADAAAABwAAAAMAAAA3AAAAAAAAACgAAAAAAAAAGwAAAAMAAAA2AAAAAwAAACQAAAAAAAAAFAAAAAAAAAAzAAAAAwAAACIAAAAAAAAAEwAAAAMAAABIAAAAAAAAADwAAAADAAAALgAAAAMAAABJAAAAAwAAADcAAAAAAAAAKAAAAAAAAABHAAAAAwAAADYAAAADAAAAJAAAAAAAAABAAAAAAAAAAC8AAAAAAAAAJgAAAAMAAAA+AAAAAAAAACsAAAADAAAAHQAAAAMAAAA6AAAAAwAAACoAAAADAAAAGgAAAAMAAABUAAAAAAAAAEUAAAAAAAAAMwAAAAMAAABSAAAAAwAAAEAAAAAAAAAALwAAAAAAAABMAAAAAwAAAD4AAAAAAAAAKwAAAAMAAABhAAAAAAAAAFkAAAADAAAARwAAAAMAAABiAAAAAwAAAFQAAAAAAAAARQAAAAAAAABgAAAAAwAAAFIAAAADAAAAQAAAAAAAAABLAAAAAAAAAEEAAAAAAAAAOgAAAAMAAAA9AAAAAAAAADUAAAADAAAALAAAAAMAAAAxAAAAAwAAACkAAAADAAAAHwAAAAMAAABeAAAAAAAAAFYAAAAAAAAATAAAAAMAAABRAAAAAwAAAEsAAAAAAAAAQQAAAAAAAABCAAAAAwAAAD0AAAAAAAAANQAAAAMAAABrAAAAAAAAAGgAAAADAAAAYAAAAAMAAABlAAAAAwAAAF4AAAAAAAAAVgAAAAAAAABVAAAAAwAAAFEAAAADAAAASwAAAAAAAAA5AAAAAAAAADsAAAAAAAAAPwAAAAMAAABKAAAAAAAAAE4AAAADAAAATwAAAAMAAABTAAAAAwAAAFwAAAADAAAAXwAAAAMAAAAlAAAAAAAAACcAAAADAAAALQAAAAMAAAA0AAAAAAAAADkAAAAAAAAAOwAAAAAAAABGAAAAAwAAAEoAAAAAAAAATgAAAAMAAAAYAAAAAAAAABcAAAADAAAAGQAAAAMAAAAgAAAAAwAAACUAAAAAAAAAJwAAAAMAAAAyAAAAAwAAADQAAAAAAAAAOQAAAAAAAAAuAAAAAAAAADwAAAAAAAAASAAAAAMAAAA4AAAAAAAAAEQAAAADAAAAUAAAAAMAAAA/AAAAAwAAAE0AAAADAAAAWgAAAAMAAAAbAAAAAAAAACgAAAADAAAANwAAAAMAAAAjAAAAAAAAAC4AAAAAAAAAPAAAAAAAAAAtAAAAAwAAADgAAAAAAAAARAAAAAMAAAAOAAAAAAAAABQAAAADAAAAJAAAAAMAAAARAAAAAwAAABsAAAAAAAAAKAAAAAMAAAAZAAAAAwAAACMAAAAAAAAALgAAAAAAAABHAAAAAAAAAFkAAAAAAAAAYQAAAAMAAABJAAAAAAAAAFsAAAADAAAAZwAAAAMAAABIAAAAAwAAAFgAAAADAAAAaQAAAAMAAAAzAAAAAAAAAEUAAAADAAAAVAAAAAMAAAA2AAAAAAAAAEcAAAAAAAAAWQAAAAAAAAA3AAAAAwAAAEkAAAAAAAAAWwAAAAMAAAAmAAAAAAAAAC8AAAADAAAAQAAAAAMAAAAiAAAAAwAAADMAAAAAAAAARQAAAAMAAAAkAAAAAwAAADYAAAAAAAAARwAAAAAAAABgAAAAAAAAAGgAAAAAAAAAawAAAAMAAABiAAAAAAAAAG4AAAADAAAAcwAAAAMAAABhAAAAAwAAAG8AAAADAAAAdwAAAAMAAABMAAAAAAAAAFYAAAADAAAAXgAAAAMAAABSAAAAAAAAAGAAAAAAAAAAaAAAAAAAAABUAAAAAwAAAGIAAAAAAAAAbgAAAAMAAAA6AAAAAAAAAEEAAAADAAAASwAAAAMAAAA+AAAAAwAAAEwAAAAAAAAAVgAAAAMAAABAAAAAAwAAAFIAAAAAAAAAYAAAAAAAAABVAAAAAAAAAFcAAAAAAAAAUwAAAAMAAABlAAAAAAAAAGYAAAADAAAAZAAAAAMAAABrAAAAAwAAAHAAAAADAAAAcgAAAAMAAABCAAAAAAAAAEMAAAADAAAARgAAAAMAAABRAAAAAAAAAFUAAAAAAAAAVwAAAAAAAABeAAAAAwAAAGUAAAAAAAAAZgAAAAMAAAAxAAAAAAAAADAAAAADAAAAMgAAAAMAAAA9AAAAAwAAAEIAAAAAAAAAQwAAAAMAAABLAAAAAwAAAFEAAAAAAAAAVQAAAAAAAABfAAAAAAAAAFwAAAAAAAAAUwAAAAAAAABPAAAAAAAAAE4AAAAAAAAASgAAAAMAAAA/AAAAAQAAADsAAAADAAAAOQAAAAMAAABtAAAAAAAAAGwAAAAAAAAAZAAAAAUAAABdAAAAAQAAAF8AAAAAAAAAXAAAAAAAAABNAAAAAQAAAE8AAAAAAAAATgAAAAAAAAB1AAAABAAAAHYAAAAFAAAAcgAAAAUAAABqAAAAAQAAAG0AAAAAAAAAbAAAAAAAAABaAAAAAQAAAF0AAAABAAAAXwAAAAAAAABaAAAAAAAAAE0AAAAAAAAAPwAAAAAAAABQAAAAAAAAAEQAAAAAAAAAOAAAAAMAAABIAAAAAQAAADwAAAADAAAALgAAAAMAAABqAAAAAAAAAF0AAAAAAAAATwAAAAUAAABjAAAAAQAAAFoAAAAAAAAATQAAAAAAAABYAAAAAQAAAFAAAAAAAAAARAAAAAAAAAB1AAAAAwAAAG0AAAAFAAAAXwAAAAUAAABxAAAAAQAAAGoAAAAAAAAAXQAAAAAAAABpAAAAAQAAAGMAAAABAAAAWgAAAAAAAABpAAAAAAAAAFgAAAAAAAAASAAAAAAAAABnAAAAAAAAAFsAAAAAAAAASQAAAAMAAABhAAAAAQAAAFkAAAADAAAARwAAAAMAAABxAAAAAAAAAGMAAAAAAAAAUAAAAAUAAAB0AAAAAQAAAGkAAAAAAAAAWAAAAAAAAABvAAAAAQAAAGcAAAAAAAAAWwAAAAAAAAB1AAAAAgAAAGoAAAAFAAAAWgAAAAUAAAB5AAAAAQAAAHEAAAAAAAAAYwAAAAAAAAB3AAAAAQAAAHQAAAABAAAAaQAAAAAAAAB3AAAAAAAAAG8AAAAAAAAAYQAAAAAAAABzAAAAAAAAAG4AAAAAAAAAYgAAAAMAAABrAAAAAQAAAGgAAAADAAAAYAAAAAMAAAB5AAAAAAAAAHQAAAAAAAAAZwAAAAUAAAB4AAAAAQAAAHcAAAAAAAAAbwAAAAAAAABwAAAAAQAAAHMAAAAAAAAAbgAAAAAAAAB1AAAAAQAAAHEAAAAFAAAAaQAAAAUAAAB2AAAAAQAAAHkAAAAAAAAAdAAAAAAAAAByAAAAAQAAAHgAAAABAAAAdwAAAAAAAAByAAAAAAAAAHAAAAAAAAAAawAAAAAAAABkAAAAAAAAAGYAAAAAAAAAZQAAAAMAAABTAAAAAQAAAFcAAAADAAAAVQAAAAMAAAB2AAAAAAAAAHgAAAAAAAAAcwAAAAUAAABsAAAAAQAAAHIAAAAAAAAAcAAAAAAAAABcAAAAAQAAAGQAAAAAAAAAZgAAAAAAAAB1AAAAAAAAAHkAAAAFAAAAdwAAAAUAAABtAAAAAQAAAHYAAAAAAAAAeAAAAAAAAABfAAAAAQAAAGwAAAABAAAAcgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAEAAAABAAAAAAAAAAAAAAABAAAAAAAAAAEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAB+ogX28rbpPxqumpJv+fM/165tC4ns9D+XaEnTqUsEQFrOtNlC4PA/3U+0XG6P9b9TdUUBxTTjP4PUp8ex1ty/B1rD/EN43z+lcDi6LLrZP/a45NWEHMY/oJ5ijLDZ+j/xw3rjxWPjP2B8A46ioQdAotff3wla2z+FMSpA1jj+v6b5Y1mtPbS/cIu8K0F457/2esiyJpDNv98k5Ts2NeA/pvljWa09tD88ClUJ60MDQPZ6yLImkM0/4ONKxa0UBcD2uOTVhBzGv5G7JRxGave/8cN648Vj47+HCwtkjAXIv6LX398JWtu/qyheaCAL9D9TdUUBxTTjv4gyTxslhwVAB1rD/EN4378EH/28teoFwH6iBfbytum/F6ztFYdK/r/Xrm0Liez0vwcS6wNGWeO/Ws602ULg8L9TCtRLiLT8P8pi5RexJsw/BlIKPVwR5T95Wyu0/QjnP5PjoT7YYcu/mBhKZ6zrwj8wRYS7NebuP3qW6geh+Ls/SLrixebL3r+pcyymN9XrPwmkNHp7xec/GWNMZVAA17+82s+x2BLiPwn2ytbJ9ek/LgEH1sMS1j8yp/2LhTfeP+SnWwtQBbu/d38gkp5X7z8ytsuHaADGPzUYObdf1+m/7IauECWhwz+cjSACjzniP76Z+wUhN9K/1+GEKzup67+/GYr/04baPw6idWOvsuc/ZedTWsRa5b/EJQOuRzi0v/OncYhHPes/h49PixY53j+i8wWfC03Nvw2idWOvsue/ZedTWsRa5T/EJQOuRzi0P/KncYhHPeu/iY9PixY53r+i8wWfC03NP9anWwtQBbs/d38gkp5X778ytsuHaADGvzUYObdf1+k/74auECWhw7+cjSACjzniv8CZ+wUhN9I/1uGEKzup6z+/GYr/04bavwmkNHp7xee/F2NMZVAA1z+82s+x2BLivwr2ytbJ9em/KwEH1sMS1r8yp/2LhTfev81i5RexJsy/BlIKPVwR5b95Wyu0/Qjnv5DjoT7YYcs/nBhKZ6zrwr8wRYS7Nebuv3OW6geh+Lu/SLrixebL3j+pcyymN9Xrv8rHIFfWehZAMBwUdlo0DECTUc17EOb2PxpVB1SWChdAzjbhb9pTDUDQhmdvECX5P9FlMKCC9+g/IIAzjELgE0DajDngMv8GQFhWDmDPjNs/y1guLh96EkAxPi8k7DIEQJCc4URlhRhA3eLKKLwkEECqpNAyTBD/P6xpjXcDiwVAFtl//cQm4z+Ibt3XKiYTQM7mCLUb3QdAoM1t8yVv7D8aLZv2Nk8UQEAJPV5nQwxAtSsfTCoE9z9TPjXLXIIWQBVanC5W9AtAYM3d7Adm9j++5mQz1FoWQBUThyaVBghAwH5muQsV7T89Q1qv82MUQJoWGOfNuBdAzrkClkmwDkDQjKq77t37Py+g0dtitsE/ZwAMTwVPEUBojepluNwBQGYbtuW+t9w/HNWIJs6MEkDTNuQUSlgEQKxktPP5TcQ/ixbLB8JjEUCwuWjXMQYCQAS/R09FkRdAowpiZjhhDkB7LmlczD/7P01iQmhhsAVAnrtTwDy84z/Z6jfQ2TgTQChOCXMnWwpAhrW3daoz8z/HYJvVPI4VQLT3ik5FcA5Angi7LOZd+z+NNVzDy5gXQBXdvVTFUA1AYNMgOeYe+T8+qHXGCwkXQKQTOKwa5AJA8gFVoEMW0T+FwzJyttIRQAEAAAD/////BwAAAP////8xAAAA/////1cBAAD/////YQkAAP////+nQQAA/////5HLAQD/////95AMAP/////B9lcAAAAAAAAAAAAAAAAAAgAAAP////8OAAAA/////2IAAAD/////rgIAAP/////CEgAA/////06DAAD/////IpcDAP/////uIRkA/////4LtrwAAAAAAAAAAAAAAAAAAAAAAAgAAAP//////////AQAAAAMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////wIAAAD//////////wEAAAAAAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA/////////////////////wEAAAD///////////////8CAAAA////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD///////////////////////////////8CAAAA////////////////AQAAAP////////////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAAAQAAAP//////////AgAAAP//////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAAEAAAD//////////wIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAgAAAAAAAAACAAAAAQAAAAEAAAACAAAAAgAAAAAAAAAFAAAABQAAAAAAAAACAAAAAgAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAABAAAAAgAAAAIAAAACAAAAAAAAAAUAAAAGAAAAAAAAAAIAAAACAAAAAwAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAIAAAAAAAAAAgAAAAEAAAADAAAAAgAAAAIAAAAAAAAABQAAAAcAAAAAAAAAAgAAAAIAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAgAAAAAAAAACAAAAAQAAAAQAAAACAAAAAgAAAAAAAAAFAAAACAAAAAAAAAACAAAAAgAAAAMAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAACAAAAAAAAAAIAAAABAAAAAAAAAAIAAAACAAAAAAAAAAUAAAAJAAAAAAAAAAIAAAACAAAAAwAAAAUAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAIAAAACAAAAAAAAAAMAAAAOAAAAAgAAAAAAAAACAAAAAwAAAAAAAAAAAAAAAgAAAAIAAAADAAAABgAAAAAAAAAAAAAAAAAAAAAAAAALAAAAAgAAAAIAAAAAAAAAAwAAAAoAAAACAAAAAAAAAAIAAAADAAAAAQAAAAAAAAACAAAAAgAAAAMAAAAHAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAACAAAAAgAAAAAAAAADAAAACwAAAAIAAAAAAAAAAgAAAAMAAAACAAAAAAAAAAIAAAACAAAAAwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADQAAAAIAAAACAAAAAAAAAAMAAAAMAAAAAgAAAAAAAAACAAAAAwAAAAMAAAAAAAAAAgAAAAIAAAADAAAACQAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAgAAAAIAAAAAAAAAAwAAAA0AAAACAAAAAAAAAAIAAAADAAAABAAAAAAAAAACAAAAAgAAAAMAAAAKAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAACAAAAAgAAAAAAAAADAAAABgAAAAIAAAAAAAAAAgAAAAMAAAAPAAAAAAAAAAIAAAACAAAAAwAAAAsAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAIAAAACAAAAAAAAAAMAAAAHAAAAAgAAAAAAAAACAAAAAwAAABAAAAAAAAAAAgAAAAIAAAADAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAgAAAAIAAAAAAAAAAwAAAAgAAAACAAAAAAAAAAIAAAADAAAAEQAAAAAAAAACAAAAAgAAAAMAAAANAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAACAAAAAgAAAAAAAAADAAAACQAAAAIAAAAAAAAAAgAAAAMAAAASAAAAAAAAAAIAAAACAAAAAwAAAA4AAAAAAAAAAAAAAAAAAAAAAAAACQAAAAIAAAACAAAAAAAAAAMAAAAFAAAAAgAAAAAAAAACAAAAAwAAABMAAAAAAAAAAgAAAAIAAAADAAAADwAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAgAAAAAAAAACAAAAAQAAABMAAAACAAAAAgAAAAAAAAAFAAAACgAAAAAAAAACAAAAAgAAAAMAAAAQAAAAAAAAAAAAAAAAAAAAAAAAABEAAAACAAAAAAAAAAIAAAABAAAADwAAAAIAAAACAAAAAAAAAAUAAAALAAAAAAAAAAIAAAACAAAAAwAAABEAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAIAAAAAAAAAAgAAAAEAAAAQAAAAAgAAAAIAAAAAAAAABQAAAAwAAAAAAAAAAgAAAAIAAAADAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAATAAAAAgAAAAAAAAACAAAAAQAAABEAAAACAAAAAgAAAAAAAAAFAAAADQAAAAAAAAACAAAAAgAAAAMAAAATAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAACAAAAAAAAAAIAAAABAAAAEgAAAAIAAAACAAAAAAAAAAUAAAAOAAAAAAAAAAIAAAACAAAAAwAAAAIAAAABAAAAAAAAAAEAAAACAAAAAAAAAAAAAAACAAAAAQAAAAAAAAABAAAAAgAAAAEAAAAAAAAAAgAAAAAAAAAFAAAABAAAAAAAAAABAAAABQAAAAAAAAAAAAAABQAAAAQAAAAAAAAAAQAAAAUAAAAEAAAAAAAAAAUAAAAAAAAAAgAAAAEAAAAAAAAAAQAAAAIAAAAAAAAAAAAAAAIAAAABAAAAAAAAAAEAAAACAAAAAQAAAAAAAAACAAAAAgAAAAAAAAABAAAAAAAAAAAAAAAFAAAABAAAAAAAAAABAAAABQAAAAAAAAAAAAAABQAAAAQAAAAAAAAAAQAAAAUAAAAEAAAAAAAAAAUAAAAFAAAAAAAAAAEAAAAAAAAAAAAAAMuhRbbsNlBBYqHW9OmHIkF9XBuqnS31QAK37uYhNMhAOSo3UUupm0DC+6pc6JxvQHV9eseEEEJAzURsCyqlFEB8BQ4NMJjnPyy3tBoS97o/xawXQznRjj89J2K2CZxhP6vX43RIIDQ/S8isgygEBz+LvFHQkmzaPjFFFO7wMq4+AADMLkTtjkIAAOgkJqxhQgAAU7B0MjRCAADwpBcVB0IAAACYP2HaQQAAAIn/Ja5BzczM4Eg6gUHNzMxMU7BTQTMzMzNfgCZBAAAAAEi3+UAAAAAAwGPNQDMzMzMzy6BAmpmZmZkxc0AzMzMzM/NFQDMzMzMzMxlAzczMzMzM7D+ygXSx2U6RQKimJOvQKnpA23hmONTHY0A/AGcxyudNQNb3K647mzZA+S56rrwWIUAm4kUQ+9UJQKre9hGzh/M/BLvoy9WG3T+LmqMf8VHGP2m3nYNV37A/gbFHcyeCmT+cBPWBckiDP61tZACjKW0/q2RbYVUYVj8uDypVyLNAP6jGS5cA5zBBwcqhBdCNGUEGEhQ/JVEDQT6WPnRbNO1AB/AWSJgT1kDfUWNCNLDAQNk+5C33OqlAchWL34QSk0DKvtDIrNV8QNF0G3kFzGVASSeWhBl6UED+/0mNGuk4QGjA/dm/1CJALPLPMql6DEDSHoDrwpP1P2jouzWST+A/egAAAAAAAABKAwAAAAAAAPoWAAAAAAAAyqAAAAAAAAB6ZQQAAAAAAErGHgAAAAAA+mvXAAAAAADK8+MFAAAAAHqqOykAAAAASqmhIAEAAAD6oGvkBwAAAMpm8T43AAAAes+ZuIIBAABKrDQMkwoAAPq1cFUFSgAAyvkUViUGAgAAAAAAAwAAAAYAAAACAAAABQAAAAEAAAAEAAAAAAAAAAAAAAAFAAAAAwAAAAEAAAAGAAAABAAAAAIAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAP////////////////////////////////////8AAAAA/////wAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAP////8AAAAAAAAAAAEAAAABAAAAAAAAAAAAAAD/////AAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAA/////wUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////AAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////////////////////////////wAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAUAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////////////////////////////8AAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAABAAAAAAAAAAAAAAABAAAAAQAAAAEAAAAAAAAAAQAAAAAAAAAFAAAAAQAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAAAAAABAAEAAAEBAAAAAAABAAAAAQAAAAEAAQAAAAAAAAAAAAAAAAAAAAAEAAAABAAAAAAAAAACAAAAAQAAAAMAAAAOAAAABgAAAAsAAAACAAAABwAAAAEAAAAYAAAABQAAAAoAAAABAAAABgAAAAAAAAAmAAAABwAAAAwAAAADAAAACAAAAAIAAAAxAAAACQAAAA4AAAAAAAAABQAAAAQAAAA6AAAACAAAAA0AAAAEAAAACQAAAAMAAAA/AAAACwAAAAYAAAAPAAAACgAAABAAAABIAAAADAAAAAcAAAAQAAAACwAAABEAAABTAAAACgAAAAUAAAATAAAADgAAAA8AAABhAAAADQAAAAgAAAARAAAADAAAABIAAABrAAAADgAAAAkAAAASAAAADQAAABMAAAB1AAAADwAAABMAAAARAAAAEgAAABAAAAAHAAAABwAAAAEAAAACAAAABAAAAAMAAAAAAAAAAAAAAAcAAAADAAAAAQAAAAIAAAAFAAAABAAAAAAAAAAAAAAAYWxnb3MuYwBfcG9seWZpbGxJbnRlcm5hbABhZGphY2VudEZhY2VEaXJbdG1wRmlqay5mYWNlXVtmaWprLmZhY2VdID09IEtJAGZhY2VpamsuYwBfZmFjZUlqa1BlbnRUb0dlb0JvdW5kYXJ5AGFkamFjZW50RmFjZURpcltjZW50ZXJJSksuZmFjZV1bZmFjZTJdID09IEtJAF9mYWNlSWprVG9HZW9Cb3VuZGFyeQBwb2x5Z29uLT5uZXh0ID09IE5VTEwAbGlua2VkR2VvLmMAYWRkTmV3TGlua2VkUG9seWdvbgBuZXh0ICE9IE5VTEwAbG9vcCAhPSBOVUxMAGFkZE5ld0xpbmtlZExvb3AAcG9seWdvbi0+Zmlyc3QgPT0gTlVMTABhZGRMaW5rZWRMb29wAGNvb3JkICE9IE5VTEwAYWRkTGlua2VkQ29vcmQAbG9vcC0+Zmlyc3QgPT0gTlVMTABpbm5lckxvb3BzICE9IE5VTEwAbm9ybWFsaXplTXVsdGlQb2x5Z29uAGJib3hlcyAhPSBOVUxMAGNhbmRpZGF0ZXMgIT0gTlVMTABmaW5kUG9seWdvbkZvckhvbGUAY2FuZGlkYXRlQkJveGVzICE9IE5VTEwAcmV2RGlyICE9IElOVkFMSURfRElHSVQAbG9jYWxpai5jAGgzVG9Mb2NhbElqawBiYXNlQ2VsbCAhPSBvcmlnaW5CYXNlQ2VsbAAhKG9yaWdpbk9uUGVudCAmJiBpbmRleE9uUGVudCkAcGVudGFnb25Sb3RhdGlvbnMgPj0gMABkaXJlY3Rpb25Sb3RhdGlvbnMgPj0gMABiYXNlQ2VsbCA9PSBvcmlnaW5CYXNlQ2VsbABiYXNlQ2VsbCAhPSBJTlZBTElEX0JBU0VfQ0VMTABsb2NhbElqa1RvSDMAIV9pc0Jhc2VDZWxsUGVudGFnb24oYmFzZUNlbGwpAGJhc2VDZWxsUm90YXRpb25zID49IDAAd2l0aGluUGVudGFnb25Sb3RhdGlvbnMgPj0gMABncmFwaC0+YnVja2V0cyAhPSBOVUxMAHZlcnRleEdyYXBoLmMAaW5pdFZlcnRleEdyYXBoAG5vZGUgIT0gTlVMTABhZGRWZXJ0ZXhOb2Rl";function Y(A){return A}function O(A){return A.replace(/\b__Z[\w\d_]+/g,(function(A){return A===A?A:A+" ["+A+"]"}))}function j(){var A=new Error;if(!A.stack){try{throw new Error(0)}catch(e){A=e}if(!A.stack)return"(no stack trace available)"}return A.stack.toString()}function N(){return p.length}function Z(A){try{var e=new ArrayBuffer(A);if(e.byteLength!=A)return;return new Int8Array(e).set(p),$(e),Q(e),1}catch(A){}}var W="function"==typeof atob?atob:function(A){var e,r,t,i,n,o,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f="",s=0;A=A.replace(/[^A-Za-z0-9\+\/\=]/g,"");do{e=a.indexOf(A.charAt(s++))<<2|(i=a.indexOf(A.charAt(s++)))>>4,r=(15&i)<<4|(n=a.indexOf(A.charAt(s++)))>>2,t=(3&n)<<6|(o=a.indexOf(A.charAt(s++))),f+=String.fromCharCode(e),64!==n&&(f+=String.fromCharCode(r)),64!==o&&(f+=String.fromCharCode(t))}while(s>2]=A,i[a+4>>2]=e,(a=0!=(0|n))&&(i[n>>2]=0),0|UA(A,e))return I=o,0|(d=1);i[d>>2]=0;A:do{if((0|r)>=1)if(a)for(l=0,h=1,c=1,f=0,a=A;;){if(!(f|l)){if(0==(0|(a=0|U(a,e,4,d)))&0==(0|(e=0|M()))){a=2;break A}if(0|UA(a,e)){a=1;break A}}if(0==(0|(a=0|U(a,e,0|i[16+(l<<2)>>2],d)))&0==(0|(e=0|M()))){a=2;break A}if(i[(A=t+(c<<3)|0)>>2]=a,i[A+4>>2]=e,i[n+(c<<2)>>2]=h,A=(0|(f=f+1|0))==(0|h),u=6==(0|(s=l+1|0)),0|UA(a,e)){a=1;break A}if((0|(h=h+(u&A&1)|0))>(0|r)){a=0;break}l=A?u?0:s:l,c=c+1|0,f=A?0:f}else for(l=0,h=1,c=1,f=0,a=A;;){if(!(f|l)){if(0==(0|(a=0|U(a,e,4,d)))&0==(0|(e=0|M()))){a=2;break A}if(0|UA(a,e)){a=1;break A}}if(0==(0|(a=0|U(a,e,0|i[16+(l<<2)>>2],d)))&0==(0|(e=0|M()))){a=2;break A}if(i[(A=t+(c<<3)|0)>>2]=a,i[A+4>>2]=e,A=(0|(f=f+1|0))==(0|h),u=6==(0|(s=l+1|0)),0|UA(a,e)){a=1;break A}if((0|(h=h+(u&A&1)|0))>(0|r)){a=0;break}l=A?u?0:s:l,c=c+1|0,f=A?0:f}else a=0}while(0);return I=o,0|(d=a)}function P(A,e,r,t,n,o,a){r|=0,t|=0,n|=0,o|=0,a|=0;var f,s,u=0,l=0,h=0,c=0,d=0;if(s=I,I=I+16|0,f=s,0==(0|(A|=0))&0==(0|(e|=0)))I=s;else{if(u=0|Me(0|A,0|e,0|o,((0|o)<0)<<31>>31|0),M(),!(0==(0|(d=0|i[(c=l=t+(u<<3)|0)>>2]))&0==(0|(c=0|i[c+4>>2]))|(h=(0|d)==(0|A)&(0|c)==(0|e))))do{h=(0|(c=0|i[(d=l=t+((u=(u+1|0)%(0|o)|0)<<3)|0)>>2]))==(0|A)&(0|(d=0|i[d+4>>2]))==(0|e)}while(!(0==(0|c)&0==(0|d)|h));u=n+(u<<2)|0,h&&(0|i[u>>2])<=(0|a)||(i[(d=l)>>2]=A,i[d+4>>2]=e,i[u>>2]=a,(0|a)>=(0|r)||(d=a+1|0,i[f>>2]=0,P(c=0|U(A,e,2,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,3,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,1,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,5,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,4,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,6,f),0|M(),r,t,n,o,d))),I=s}}function U(A,e,r,t){A|=0,e|=0,r|=0;var n,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0;if((0|i[(t|=0)>>2])>0){a=0;do{r=0|fA(r),a=a+1|0}while((0|a)<(0|i[t>>2]))}n=0|Qe(0|A,0|e,45),M(),o=127&n,f=0|GA(A,e),a=0|Qe(0|A,0|e,52),M(),a&=15;A:do{if(a)for(;;){if(h=0|Qe(0|A,0|e,0|(l=3*(15-a|0)|0)),M(),h&=7,c=0==(0|RA(a)),a=a+-1|0,u=0|ye(7,0,0|l),e&=~(0|M()),A=(l=0|ye(0|i[(c?464:48)+(28*h|0)+(r<<2)>>2],0,0|l))|A&~u,e|=0|M(),!(r=0|i[(c?672:256)+(28*h|0)+(r<<2)>>2])){r=0;break A}if(!a){s=6;break}}else s=6}while(0);6==(0|s)&&(A|=h=0|ye(0|(c=0|i[880+(28*o|0)+(r<<2)>>2]),0,45),e=0|M()|-1040385&e,r=0|i[4304+(28*o|0)+(r<<2)>>2],127==(127&c|0)&&(c=0|ye(0|i[880+(28*o|0)+20>>2],0,45),e=0|M()|-1040385&e,r=0|i[4304+(28*o|0)+20>>2],A=0|TA(c|A,e),e=0|M(),i[t>>2]=1+(0|i[t>>2]))),s=0|Qe(0|A,0|e,45),M(),s&=127;A:do{if(0|S(s)){e:do{if(1==(0|GA(A,e))){if((0|o)!=(0|s)){if(0|R(s,0|i[7728+(28*o|0)>>2])){A=0|HA(A,e),f=1,e=0|M();break}A=0|TA(A,e),f=1,e=0|M();break}switch(0|f){case 5:A=0|HA(A,e),e=0|M(),i[t>>2]=5+(0|i[t>>2]),f=0;break e;case 3:A=0|TA(A,e),e=0|M(),i[t>>2]=1+(0|i[t>>2]),f=0;break e;default:return c=0,k(0|(h=0)),0|c}}else f=0}while(0);if((0|r)>0){a=0;do{A=0|SA(A,e),e=0|M(),a=a+1|0}while((0|a)!=(0|r))}if((0|o)!=(0|s)){if(!(0|T(s))){if(0!=(0|f)|5!=(0|GA(A,e)))break;i[t>>2]=1+(0|i[t>>2]);break}switch(127&n){case 8:case 118:break A}3!=(0|GA(A,e))&&(i[t>>2]=1+(0|i[t>>2]))}}else if((0|r)>0){a=0;do{A=0|TA(A,e),e=0|M(),a=a+1|0}while((0|a)!=(0|r))}}while(0);return i[t>>2]=((0|i[t>>2])+r|0)%6|0,c=A,k(0|(h=e)),0|c}function G(A,e,r,t,o,a){e|=0,r|=0,t|=0,o|=0,a|=0;var f,s,u,l,h,c,d,g,w,p=0,B=0,b=0,v=0,m=0,k=0,Q=0,y=0,E=0,x=0,D=0,_=0,F=0,C=0;if(w=I,I=I+48|0,c=w+32|0,d=w+16|0,g=w,(0|(p=0|i[(A|=0)>>2]))<=0)return I=w,0|(_=0);f=A+4|0,s=c+8|0,u=d+8|0,l=g+8|0,h=((0|e)<0)<<31>>31,D=0;A:for(;;){E=(B=0|i[f>>2])+(D<<4)|0,i[c>>2]=i[E>>2],i[c+4>>2]=i[E+4>>2],i[c+8>>2]=i[E+8>>2],i[c+12>>2]=i[E+12>>2],(0|D)==(p+-1|0)?(i[d>>2]=i[B>>2],i[d+4>>2]=i[B+4>>2],i[d+8>>2]=i[B+8>>2],i[d+12>>2]=i[B+12>>2]):(E=B+(D+1<<4)|0,i[d>>2]=i[E>>2],i[d+4>>2]=i[E+4>>2],i[d+8>>2]=i[E+8>>2],i[d+12>>2]=i[E+12>>2]),E=0|N(c,d,r);e:do{if((0|E)>0){x=+(0|E),y=0;r:for(;;){C=+(E-y|0),F=+(0|y),n[g>>3]=+n[c>>3]*C/x+ +n[d>>3]*F/x,n[l>>3]=+n[s>>3]*C/x+ +n[u>>3]*F/x,B=0|Me(0|(k=0|LA(g,r)),0|(Q=0|M()),0|e,0|h),M(),v=0|i[(b=p=a+(B<<3)|0)>>2],b=0|i[b+4>>2];t:do{if(0==(0|v)&0==(0|b))_=14;else for(m=0;;){if((0|m)>(0|e)){p=1;break t}if((0|v)==(0|k)&(0|b)==(0|Q)){p=7;break t}if(0==(0|(v=0|i[(b=p=a+((B=(B+1|0)%(0|e)|0)<<3)|0)>>2]))&0==(0|(b=0|i[b+4>>2]))){_=14;break}m=m+1|0}}while(0);switch(14==(0|_)&&(_=0,0==(0|k)&0==(0|Q)?p=7:(i[p>>2]=k,i[p+4>>2]=Q,p=0|i[t>>2],i[(m=o+(p<<3)|0)>>2]=k,i[m+4>>2]=Q,i[t>>2]=p+1,p=0)),7&p){case 7:case 0:break;default:break r}if((0|E)<=(0|(y=y+1|0))){_=8;break e}}if(0|p){p=-1,_=20;break A}}else _=8}while(0);if(8==(0|_)&&(_=0),(0|(D=D+1|0))>=(0|(p=0|i[A>>2]))){p=0,_=20;break}}return 20==(0|_)?(I=w,0|p):0}function S(A){return 0|i[7728+(28*(A|=0)|0)+16>>2]}function T(A){return 4==(0|(A|=0))|117==(0|A)|0}function V(A){return 0|i[11152+(216*(0|i[(A|=0)>>2])|0)+(72*(0|i[A+4>>2])|0)+(24*(0|i[A+8>>2])|0)+(i[A+12>>2]<<3)>>2]}function H(A){return 0|i[11152+(216*(0|i[(A|=0)>>2])|0)+(72*(0|i[A+4>>2])|0)+(24*(0|i[A+8>>2])|0)+(i[A+12>>2]<<3)+4>>2]}function R(A,e){return e|=0,(0|i[7728+(28*(A|=0)|0)+20>>2])==(0|e)?0|(e=1):0|(e=(0|i[7728+(28*A|0)+24>>2])==(0|e))}function L(A,e){return 0|i[880+(28*(A|=0)|0)+((e|=0)<<2)>>2]}function z(A,e){return e|=0,(0|i[880+(28*(A|=0)|0)>>2])==(0|e)?0|(e=0):(0|i[880+(28*A|0)+4>>2])==(0|e)?0|(e=1):(0|i[880+(28*A|0)+8>>2])==(0|e)?0|(e=2):(0|i[880+(28*A|0)+12>>2])==(0|e)?0|(e=3):(0|i[880+(28*A|0)+16>>2])==(0|e)?0|(e=4):(0|i[880+(28*A|0)+20>>2])==(0|e)?0|(e=5):0|((0|i[880+(28*A|0)+24>>2])==(0|e)?6:7)}function Y(A){return+n[(A|=0)+16>>3]<+n[A+24>>3]|0}function O(A,e){A|=0;var r,t,i=0;return(i=+n[(e|=0)>>3])>=+n[A+8>>3]&&i<=+n[A>>3]?(r=+n[A+16>>3],i=+n[A+24>>3],e=(t=+n[e+8>>3])>=i,A=t<=r&1,r>2]=0,l=l+4|0}while((0|l)<(0|h));return NA(e,o),OA(h=0|i[(l=o)>>2],l=0|i[l+4>>2],r),jA(h,l,t),s=+DA(r,t+8|0),n[r>>3]=+n[A>>3],n[(l=r+8|0)>>3]=+n[A+16>>3],n[t>>3]=+n[A+8>>3],n[(h=t+8|0)>>3]=+n[A+24>>3],u=+DA(r,t),h=~~+B(+u*u/+Ee(+ +f(+(+n[l>>3]-+n[h>>3])/(+n[r>>3]-+n[t>>3])),3)/(s*(2.59807621135*s)*.8)),I=a,0|(0==(0|h)?1:h)}function N(A,e,r){A|=0,e|=0,r|=0;var t,n,o,a,f,s=0,u=0;a=I,I=I+288|0,t=a+264|0,n=a+96|0,u=(s=o=a)+96|0;do{i[s>>2]=0,s=s+4|0}while((0|s)<(0|u));return NA(r,o),OA(s=0|i[(u=o)>>2],u=0|i[u+4>>2],t),jA(s,u,n),f=+DA(t,n+8|0),u=~~+B(+ +DA(A,e)/(2*f)),I=a,0|(0==(0|u)?1:u)}function Z(A,e,r,t){e|=0,r|=0,t|=0,i[(A|=0)>>2]=e,i[A+4>>2]=r,i[A+8>>2]=t}function W(A,e){A|=0;var r,t,o,a,s=0,u=0,l=0,h=0,c=0,d=0,g=0;i[(a=(e|=0)+8|0)>>2]=0,t=+n[A>>3],h=+f(+t),o=+n[A+8>>3],h+=.5*(c=+f(+o)/.8660254037844386),h-=+(0|(s=~~h)),c-=+(0|(A=~~c));do{if(h<.5){if(h<.3333333333333333){if(i[e>>2]=s,c<.5*(h+1)){i[e+4>>2]=A;break}A=A+1|0,i[e+4>>2]=A;break}if(A=(1&!(c<(g=1-h)))+A|0,i[e+4>>2]=A,g<=c&c<2*h){s=s+1|0,i[e>>2]=s;break}i[e>>2]=s;break}if(!(h<.6666666666666666)){if(s=s+1|0,i[e>>2]=s,c<.5*h){i[e+4>>2]=A;break}A=A+1|0,i[e+4>>2]=A;break}if(c<1-h){if(i[e+4>>2]=A,2*h-1>2]=s;break}}else A=A+1|0,i[e+4>>2]=A;s=s+1|0,i[e>>2]=s}while(0);do{if(t<0){if(1&A){s=~~(+(0|s)-(2*(+((d=0|ve(0|s,((0|s)<0)<<31>>31|0,0|(d=(A+1|0)/2|0),((0|d)<0)<<31>>31|0))>>>0)+4294967296*+(0|M()))+1)),i[e>>2]=s;break}s=~~(+(0|s)-2*(+((d=0|ve(0|s,((0|s)<0)<<31>>31|0,0|(d=(0|A)/2|0),((0|d)<0)<<31>>31|0))>>>0)+4294967296*+(0|M()))),i[e>>2]=s;break}}while(0);d=e+4|0,o<0&&(s=s-((1|A<<1)/2|0)|0,i[e>>2]=s,A=0-A|0,i[d>>2]=A),u=A-s|0,(0|s)<0?(l=0-s|0,i[d>>2]=u,i[a>>2]=l,i[e>>2]=0,A=u,s=0):l=0,(0|A)<0&&(s=s-A|0,i[e>>2]=s,l=l-A|0,i[a>>2]=l,i[d>>2]=0,A=0),r=s-l|0,u=A-l|0,(0|l)<0&&(i[e>>2]=r,i[d>>2]=u,i[a>>2]=0,A=u,s=r,l=0),(0|(u=(0|l)<(0|(u=(0|A)<(0|s)?A:s))?l:u))<=0||(i[e>>2]=s-u,i[d>>2]=A-u,i[a>>2]=l-u)}function J(A){var e,r=0,t=0,n=0,o=0,a=0;r=0|i[(A|=0)>>2],t=0|i[(e=A+4|0)>>2],(0|r)<0&&(t=t-r|0,i[e>>2]=t,i[(a=A+8|0)>>2]=(0|i[a>>2])-r,i[A>>2]=0,r=0),(0|t)<0?(r=r-t|0,i[A>>2]=r,o=(0|i[(a=A+8|0)>>2])-t|0,i[a>>2]=o,i[e>>2]=0,t=0):(a=o=A+8|0,o=0|i[o>>2]),(0|o)<0&&(r=r-o|0,i[A>>2]=r,t=t-o|0,i[e>>2]=t,i[a>>2]=0,o=0),(0|(n=(0|o)<(0|(n=(0|t)<(0|r)?t:r))?o:n))<=0||(i[A>>2]=r-n,i[e>>2]=t-n,i[a>>2]=o-n)}function K(A,e){e|=0;var r,t;t=0|i[(A|=0)+8>>2],r=+((0|i[A+4>>2])-t|0),n[e>>3]=+((0|i[A>>2])-t|0)-.5*r,n[e+8>>3]=.8660254037844386*r}function X(A,e,r){A|=0,e|=0,i[(r|=0)>>2]=(0|i[e>>2])+(0|i[A>>2]),i[r+4>>2]=(0|i[e+4>>2])+(0|i[A+4>>2]),i[r+8>>2]=(0|i[e+8>>2])+(0|i[A+8>>2])}function q(A,e,r){A|=0,e|=0,i[(r|=0)>>2]=(0|i[A>>2])-(0|i[e>>2]),i[r+4>>2]=(0|i[A+4>>2])-(0|i[e+4>>2]),i[r+8>>2]=(0|i[A+8>>2])-(0|i[e+8>>2])}function $(A,e){e|=0;var r,t=0;t=0|b(0|i[(A|=0)>>2],e),i[A>>2]=t,r=0|b(0|i[(t=A+4|0)>>2],e),i[t>>2]=r,e=0|b(0|i[(A=A+8|0)>>2],e),i[A>>2]=e}function AA(A){var e,r,t=0,n=0,o=0,a=0,f=0;f=(0|(r=0|i[(A|=0)>>2]))<0,A=(A=(n=(0|(a=((e=(0|(o=(0|i[A+4>>2])-(f?r:0)|0))<0)?0-o|0:0)+((0|i[A+8>>2])-(f?r:0))|0))<0)?0:a)-((o=(0|(n=(0|A)<(0|(n=(0|(t=(e?0:o)-(n?a:0)|0))<(0|(a=(f?0:r)-(e?o:0)-(n?a:0)|0))?t:a))?A:n))>0)?n:0)|0,t=t-(o?n:0)|0;A:do{switch(a-(o?n:0)|0){case 0:switch(0|t){case 0:return 0|(f=0==(0|A)?0:1==(0|A)?1:7);case 1:return 0|(f=0==(0|A)?2:1==(0|A)?3:7);default:break A}case 1:switch(0|t){case 0:return 0|(f=0==(0|A)?4:1==(0|A)?5:7);case 1:if(A)break A;return 0|(A=6);default:break A}}}while(0);return 0|(f=7)}function eA(A){var e,r,t=0,n=0,o=0,a=0,f=0;n=0|i[(e=(A|=0)+8|0)>>2],o=0|we(+((3*(t=(0|i[A>>2])-n|0)|0)-(n=(0|i[(r=A+4|0)>>2])-n|0)|0)/7),i[A>>2]=o,t=0|we(+((n<<1)+t|0)/7),i[r>>2]=t,i[e>>2]=0,n=t-o|0,(0|o)<0?(f=0-o|0,i[r>>2]=n,i[e>>2]=f,i[A>>2]=0,t=n,o=0,n=f):n=0,(0|t)<0&&(o=o-t|0,i[A>>2]=o,n=n-t|0,i[e>>2]=n,i[r>>2]=0,t=0),f=o-n|0,a=t-n|0,(0|n)<0?(i[A>>2]=f,i[r>>2]=a,i[e>>2]=0,t=a,a=f,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|t)<(0|a)?t:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=t-o,i[e>>2]=n-o)}function rA(A){var e,r,t=0,n=0,o=0,a=0,f=0;n=0|i[(e=(A|=0)+8|0)>>2],o=0|we(+(((t=(0|i[A>>2])-n|0)<<1)+(n=(0|i[(r=A+4|0)>>2])-n|0)|0)/7),i[A>>2]=o,t=0|we(+((3*n|0)-t|0)/7),i[r>>2]=t,i[e>>2]=0,n=t-o|0,(0|o)<0?(f=0-o|0,i[r>>2]=n,i[e>>2]=f,i[A>>2]=0,t=n,o=0,n=f):n=0,(0|t)<0&&(o=o-t|0,i[A>>2]=o,n=n-t|0,i[e>>2]=n,i[r>>2]=0,t=0),f=o-n|0,a=t-n|0,(0|n)<0?(i[A>>2]=f,i[r>>2]=a,i[e>>2]=0,t=a,a=f,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|t)<(0|a)?t:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=t-o,i[e>>2]=n-o)}function tA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],o=0|i[(r=A+4|0)>>2],a=0|i[(t=A+8|0)>>2],f=o+(3*n|0)|0,i[A>>2]=f,o=a+(3*o|0)|0,i[r>>2]=o,n=(3*a|0)+n|0,i[t>>2]=n,a=o-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=a,i[t>>2]=n,i[A>>2]=0,o=a,a=0):a=f,(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function iA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=(3*(n=0|i[(r=A+4|0)>>2])|0)+f|0,f=(o=0|i[(t=A+8|0)>>2])+(3*f|0)|0,i[A>>2]=f,i[r>>2]=a,n=(3*o|0)+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,f=0):o=a,(0|o)<0&&(f=f-o|0,i[A>>2]=f,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=f-n|0,a=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=a,i[t>>2]=0,f=e,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|a)<(0|f)?a:f))?n:o))<=0||(i[A>>2]=f-o,i[r>>2]=a-o,i[t>>2]=n-o)}function nA(A,e){A|=0;var r,t,n,o=0,a=0,f=0;((e|=0)+-1|0)>>>0>=6||(f=(0|i[15472+(12*e|0)>>2])+(0|i[A>>2])|0,i[A>>2]=f,n=A+4|0,a=(0|i[15472+(12*e|0)+4>>2])+(0|i[n>>2])|0,i[n>>2]=a,t=A+8|0,e=(0|i[15472+(12*e|0)+8>>2])+(0|i[t>>2])|0,i[t>>2]=e,o=a-f|0,(0|f)<0?(e=e-f|0,i[n>>2]=o,i[t>>2]=e,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,e=e-o|0,i[t>>2]=e,i[n>>2]=0,o=0),r=a-e|0,f=o-e|0,(0|e)<0?(i[A>>2]=r,i[n>>2]=f,i[t>>2]=0,a=r,e=0):f=o,(0|(o=(0|e)<(0|(o=(0|f)<(0|a)?f:a))?e:o))<=0||(i[A>>2]=a-o,i[n>>2]=f-o,i[t>>2]=e-o))}function oA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=(n=0|i[(r=A+4|0)>>2])+f|0,f=(o=0|i[(t=A+8|0)>>2])+f|0,i[A>>2]=f,i[r>>2]=a,n=o+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function aA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],a=0|i[(r=A+4|0)>>2],o=0|i[(t=A+8|0)>>2],f=a+n|0,i[A>>2]=f,a=o+a|0,i[r>>2]=a,n=o+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function fA(A){switch(0|(A|=0)){case 1:A=5;break;case 5:A=4;break;case 4:A=6;break;case 6:A=2;break;case 2:A=3;break;case 3:A=1}return 0|A}function sA(A){switch(0|(A|=0)){case 1:A=3;break;case 3:A=2;break;case 2:A=6;break;case 6:A=4;break;case 4:A=5;break;case 5:A=1}return 0|A}function uA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],o=0|i[(r=A+4|0)>>2],a=0|i[(t=A+8|0)>>2],f=o+(n<<1)|0,i[A>>2]=f,o=a+(o<<1)|0,i[r>>2]=o,n=(a<<1)+n|0,i[t>>2]=n,a=o-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=a,i[t>>2]=n,i[A>>2]=0,o=a,a=0):a=f,(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function lA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=((n=0|i[(r=A+4|0)>>2])<<1)+f|0,f=(o=0|i[(t=A+8|0)>>2])+(f<<1)|0,i[A>>2]=f,i[r>>2]=a,n=(o<<1)+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,f=0):o=a,(0|o)<0&&(f=f-o|0,i[A>>2]=f,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=f-n|0,a=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=a,i[t>>2]=0,f=e,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|a)<(0|f)?a:f))?n:o))<=0||(i[A>>2]=f-o,i[r>>2]=a-o,i[t>>2]=n-o)}function hA(A,e){e|=0;var r,t,n,o=0,a=0,f=0;return n=(0|(t=(0|i[(A|=0)>>2])-(0|i[e>>2])|0))<0,r=(0|(a=(0|i[A+4>>2])-(0|i[e+4>>2])-(n?t:0)|0))<0,e=(e=(A=(0|(f=(n?0-t|0:0)+(0|i[A+8>>2])-(0|i[e+8>>2])+(r?0-a|0:0)|0))<0)?0:f)-((a=(0|(A=(0|e)<(0|(A=(0|(o=(r?0:a)-(A?f:0)|0))<(0|(f=(n?0:t)-(r?a:0)-(A?f:0)|0))?o:f))?e:A))>0)?A:0)|0,o=o-(a?A:0)|0,0|((0|(A=(0|(A=f-(a?A:0)|0))>-1?A:0-A|0))>(0|(e=(0|(o=(0|o)>-1?o:0-o|0))>(0|(e=(0|e)>-1?e:0-e|0))?o:e))?A:e)}function cA(A,e){e|=0;var r;r=0|i[(A|=0)+8>>2],i[e>>2]=(0|i[A>>2])-r,i[e+4>>2]=(0|i[A+4>>2])-r}function dA(A,e){e|=0;var r,t,n,o=0,a=0,f=0;a=0|i[(A|=0)>>2],i[e>>2]=a,A=0|i[A+4>>2],i[(t=e+4|0)>>2]=A,i[(n=e+8|0)>>2]=0,o=A-a|0,(0|a)<0?(A=0-a|0,i[t>>2]=o,i[n>>2]=A,i[e>>2]=0,a=0):(o=A,A=0),(0|o)<0&&(a=a-o|0,i[e>>2]=a,A=A-o|0,i[n>>2]=A,i[t>>2]=0,o=0),r=a-A|0,f=o-A|0,(0|A)<0?(i[e>>2]=r,i[t>>2]=f,i[n>>2]=0,o=f,f=r,A=0):f=a,(0|(a=(0|A)<(0|(a=(0|o)<(0|f)?o:f))?A:a))<=0||(i[e>>2]=f-a,i[t>>2]=o-a,i[n>>2]=A-a)}function gA(A){var e,r,t,n;r=(n=0|i[(e=(A|=0)+8|0)>>2])-(0|i[A>>2])|0,i[A>>2]=r,A=(0|i[(t=A+4|0)>>2])-n|0,i[t>>2]=A,i[e>>2]=0-(A+r)}function wA(A){var e,r,t=0,n=0,o=0,a=0,f=0;t=0-(n=0|i[(A|=0)>>2])|0,i[A>>2]=t,i[(e=A+8|0)>>2]=0,a=(o=0|i[(r=A+4|0)>>2])+n|0,(0|n)>0?(i[r>>2]=a,i[e>>2]=n,i[A>>2]=0,t=0,o=a):n=0,(0|o)<0?(f=t-o|0,i[A>>2]=f,n=n-o|0,i[e>>2]=n,i[r>>2]=0,a=f-n|0,t=0-n|0,(0|n)<0?(i[A>>2]=a,i[r>>2]=t,i[e>>2]=0,o=t,n=0):(o=0,a=f)):a=t,(0|(t=(0|n)<(0|(t=(0|o)<(0|a)?o:a))?n:t))<=0||(i[A>>2]=a-t,i[r>>2]=o-t,i[e>>2]=n-t)}function pA(A,e,r,t){e|=0,r|=0,t|=0;var o,a=0,f=0,s=0,u=0;if(o=I,I=I+32|0,function(A,e){e|=0;var r=0,t=0,i=0;r=+n[(A=A|0)>>3],t=+l(+r),r=+h(+r),n[e+16>>3]=r,r=+n[A+8>>3],i=t*+l(+r),n[e>>3]=i,r=t*+h(+r),n[e+8>>3]=r}(A|=0,f=o),i[r>>2]=0,a=+fe(15888,f),(s=+fe(15912,f))>2]=1,a=s),(s=+fe(15936,f))>2]=2,a=s),(s=+fe(15960,f))>2]=3,a=s),(s=+fe(15984,f))>2]=4,a=s),(s=+fe(16008,f))>2]=5,a=s),(s=+fe(16032,f))>2]=6,a=s),(s=+fe(16056,f))>2]=7,a=s),(s=+fe(16080,f))>2]=8,a=s),(s=+fe(16104,f))>2]=9,a=s),(s=+fe(16128,f))>2]=10,a=s),(s=+fe(16152,f))>2]=11,a=s),(s=+fe(16176,f))>2]=12,a=s),(s=+fe(16200,f))>2]=13,a=s),(s=+fe(16224,f))>2]=14,a=s),(s=+fe(16248,f))>2]=15,a=s),(s=+fe(16272,f))>2]=16,a=s),(s=+fe(16296,f))>2]=17,a=s),(s=+fe(16320,f))>2]=18,a=s),(s=+fe(16344,f))>2]=19,a=s),(s=+d(+(1-.5*a)))<1e-16)return i[t>>2]=0,i[t+4>>2]=0,i[t+8>>2]=0,i[t+12>>2]=0,void(I=o);if(r=0|i[r>>2],a=+EA((a=+n[16368+(24*r|0)>>3])-+EA(+function(A,e){A|=0;var r=0,t=0,i=0,o=0,a=0;return o=+n[(e=e|0)>>3],t=+l(+o),i=+n[e+8>>3]-+n[A+8>>3],a=t*+h(+i),r=+n[A>>3],+ +p(+a,+(+h(+o)*+l(+r)-+l(+i)*(t*+h(+r))))}(15568+(r<<4)|0,A))),u=0|RA(e)?+EA(a+-.3334731722518321):a,a=+c(+s)/.381966011250105,(0|e)>0){f=0;do{a*=2.6457513110645907,f=f+1|0}while((0|f)!=(0|e))}s=+l(+u)*a,n[t>>3]=s,u=+h(+u)*a,n[t+8>>3]=u,I=o}function BA(A,e,r,t,o){e|=0,r|=0,t|=0,o|=0;var a=0,u=0;if((a=+function(A){var e=0,r=0;return r=+n[(A=A|0)>>3],e=+n[A+8>>3],+ +s(+(r*r+e*e))}(A|=0))<1e-16)return e=15568+(e<<4)|0,i[o>>2]=i[e>>2],i[o+4>>2]=i[e+4>>2],i[o+8>>2]=i[e+8>>2],void(i[o+12>>2]=i[e+12>>2]);if(u=+p(+ +n[A+8>>3],+ +n[A>>3]),(0|r)>0){A=0;do{a/=2.6457513110645907,A=A+1|0}while((0|A)!=(0|r))}t?(a/=3,r=0==(0|RA(r)),a=+w(.381966011250105*(r?a:a/2.6457513110645907))):(a=+w(.381966011250105*a),0|RA(r)&&(u=+EA(u+.3334731722518321))),function(A,e,r,t){A|=0,e=+e,t|=0;var o=0,a=0,s=0,u=0;if((r=+r)<1e-16)return i[t>>2]=i[A>>2],i[t+4>>2]=i[A+4>>2],i[t+8>>2]=i[A+8>>2],void(i[t+12>>2]=i[A+12>>2]);a=e<0?e+6.283185307179586:e,a=e>=6.283185307179586?a+-6.283185307179586:a;do{if(!(a<1e-16)){if(o=+f(+(a+-3.141592653589793))<1e-16,e=+n[A>>3],o){e-=r,n[t>>3]=e,o=t;break}if(s=+l(+r),r=+h(+r),e=s*+h(+e)+ +l(+a)*(r*+l(+e)),e=+g(+((e=e>1?1:e)<-1?-1:e)),n[t>>3]=e,+f(+(e+-1.5707963267948966))<1e-16)return n[t>>3]=1.5707963267948966,void(n[t+8>>3]=0);if(+f(+(e+1.5707963267948966))<1e-16)return n[t>>3]=-1.5707963267948966,void(n[t+8>>3]=0);if(u=+l(+e),a=r*+h(+a)/u,r=+n[A>>3],e=(s-+h(+e)*+h(+r))/+l(+r)/u,s=a>1?1:a,e=e>1?1:e,(e=+n[A+8>>3]+ +p(+(s<-1?-1:s),+(e<-1?-1:e)))>3.141592653589793)do{e+=-6.283185307179586}while(e>3.141592653589793);if(e<-3.141592653589793)do{e+=6.283185307179586}while(e<-3.141592653589793);return void(n[t+8>>3]=e)}e=+n[A>>3]+r,n[t>>3]=e,o=t}while(0);if(+f(+(e+-1.5707963267948966))<1e-16)return n[o>>3]=1.5707963267948966,void(n[t+8>>3]=0);if(+f(+(e+1.5707963267948966))<1e-16)return n[o>>3]=-1.5707963267948966,void(n[t+8>>3]=0);if((e=+n[A+8>>3])>3.141592653589793)do{e+=-6.283185307179586}while(e>3.141592653589793);if(e<-3.141592653589793)do{e+=6.283185307179586}while(e<-3.141592653589793);n[t+8>>3]=e}(15568+(e<<4)|0,+EA(+n[16368+(24*e|0)>>3]-u),a,o)}function bA(A,e,r){e|=0,r|=0;var t,n;t=I,I=I+16|0,K((A|=0)+4|0,n=t),BA(n,0|i[A>>2],e,0,r),I=t}function vA(A,e,r,t,o){A|=0,e|=0,r|=0,t|=0,o|=0;var a,f,s,u,l,h,c,d,g,w,p,B,b,v,m,k,M,y,E,x,D,_,F=0,C=0,P=0,U=0,G=0,S=0;if(_=I,I=I+272|0,U=_+240|0,E=_,x=_+224|0,D=_+208|0,p=_+176|0,B=_+160|0,b=_+192|0,v=_+144|0,m=_+128|0,k=_+112|0,M=_+96|0,y=_+80|0,i[(F=_+256|0)>>2]=e,i[U>>2]=i[A>>2],i[U+4>>2]=i[A+4>>2],i[U+8>>2]=i[A+8>>2],i[U+12>>2]=i[A+12>>2],mA(U,F,E),i[o>>2]=0,(0|(U=t+r+(5==(0|t)&1)|0))<=(0|r))I=_;else{f=x+4|0,s=p+4|0,u=r+5|0,l=16848+((a=0|i[F>>2])<<2)|0,h=16928+(a<<2)|0,c=m+8|0,d=k+8|0,g=M+8|0,w=D+4|0,P=r;A:for(;;){C=E+(((0|P)%5|0)<<4)|0,i[D>>2]=i[C>>2],i[D+4>>2]=i[C+4>>2],i[D+8>>2]=i[C+8>>2],i[D+12>>2]=i[C+12>>2];do{}while(2==(0|kA(D,a,0,1)));if((0|P)>(0|r)&0!=(0|RA(e))){if(i[p>>2]=i[D>>2],i[p+4>>2]=i[D+4>>2],i[p+8>>2]=i[D+8>>2],i[p+12>>2]=i[D+12>>2],K(f,B),t=0|i[p>>2],F=0|i[17008+(80*t|0)+(i[x>>2]<<2)>>2],i[p>>2]=i[18608+(80*t|0)+(20*F|0)>>2],(0|(C=0|i[18608+(80*t|0)+(20*F|0)+16>>2]))>0){A=0;do{oA(s),A=A+1|0}while((0|A)<(0|C))}switch(C=18608+(80*t|0)+(20*F|0)+4|0,i[b>>2]=i[C>>2],i[b+4>>2]=i[C+4>>2],i[b+8>>2]=i[C+8>>2],$(b,3*(0|i[l>>2])|0),X(s,b,s),J(s),K(s,v),G=+(0|i[h>>2]),n[m>>3]=3*G,n[c>>3]=0,S=-1.5*G,n[k>>3]=S,n[d>>3]=2.598076211353316*G,n[M>>3]=S,n[g>>3]=-2.598076211353316*G,0|i[17008+(80*(0|i[p>>2])|0)+(i[D>>2]<<2)>>2]){case 1:A=k,t=m;break;case 3:A=M,t=k;break;case 2:A=m,t=M;break;default:A=12;break A}oe(B,v,t,A,y),BA(y,0|i[p>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])}if((0|P)<(0|u)&&(K(w,p),BA(p,0|i[D>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])),i[x>>2]=i[D>>2],i[x+4>>2]=i[D+4>>2],i[x+8>>2]=i[D+8>>2],i[x+12>>2]=i[D+12>>2],(0|(P=P+1|0))>=(0|U)){A=3;break}}3!=(0|A)?12==(0|A)&&Q(22474,22521,581,22531):I=_}}function mA(A,e,r){A|=0,e|=0,r|=0;var t,n=0,o=0,a=0,f=0,s=0;t=I,I=I+128|0,o=t,f=20208,s=(a=n=t+64|0)+60|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));f=20272,s=(a=o)+60|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));n=(s=0==(0|RA(0|i[e>>2])))?n:o,uA(o=A+4|0),lA(o),0|RA(0|i[e>>2])&&(iA(o),i[e>>2]=1+(0|i[e>>2])),i[r>>2]=i[A>>2],X(o,n,e=r+4|0),J(e),i[r+16>>2]=i[A>>2],X(o,n+12|0,e=r+20|0),J(e),i[r+32>>2]=i[A>>2],X(o,n+24|0,e=r+36|0),J(e),i[r+48>>2]=i[A>>2],X(o,n+36|0,e=r+52|0),J(e),i[r+64>>2]=i[A>>2],X(o,n+48|0,r=r+68|0),J(r),I=t}function kA(A,e,r,t){r|=0,t|=0;var n,o,a,f,s,u,l=0,h=0,c=0,d=0,g=0;if(u=I,I=I+32|0,s=u+12|0,o=u,g=(A|=0)+4|0,d=0|i[16928+((e|=0)<<2)>>2],d=(f=0!=(0|t))?3*d|0:d,l=0|i[g>>2],n=0|i[(a=A+8|0)>>2],f){if((0|(l=n+l+(t=0|i[(h=A+12|0)>>2])|0))==(0|d))return I=u,0|(g=1);c=h}else l=n+l+(t=0|i[(c=A+12|0)>>2])|0;if((0|l)<=(0|d))return I=u,0|(g=0);do{if((0|t)>0){if(t=0|i[A>>2],(0|n)>0){h=18608+(80*t|0)+60|0,t=A;break}t=18608+(80*t|0)+40|0,r?(Z(s,d,0,0),q(g,s,o),aA(o),X(o,s,g),h=t,t=A):(h=t,t=A)}else h=18608+(80*(0|i[A>>2])|0)+20|0,t=A}while(0);if(i[t>>2]=i[h>>2],(0|i[(l=h+16|0)>>2])>0){t=0;do{oA(g),t=t+1|0}while((0|t)<(0|i[l>>2]))}return A=h+4|0,i[s>>2]=i[A>>2],i[s+4>>2]=i[A+4>>2],i[s+8>>2]=i[A+8>>2],e=0|i[16848+(e<<2)>>2],$(s,f?3*e|0:e),X(g,s,g),J(g),t=f&&((0|i[a>>2])+(0|i[g>>2])+(0|i[c>>2])|0)==(0|d)?1:2,I=u,0|(g=t)}function MA(A,e){A|=0,e|=0;var r=0;do{r=0|kA(A,e,0,1)}while(2==(0|r));return 0|r}function QA(A,e,r,t,o){A|=0,e|=0,r|=0,t|=0,o|=0;var a,f,s,u,l,h,c,d,g,w,p,B,b,v,m,k,M,y,E=0,x=0,D=0,_=0,F=0;if(y=I,I=I+240|0,v=y+208|0,m=y,k=y+192|0,M=y+176|0,g=y+160|0,w=y+144|0,p=y+128|0,B=y+112|0,b=y+96|0,i[(E=y+224|0)>>2]=e,i[v>>2]=i[A>>2],i[v+4>>2]=i[A+4>>2],i[v+8>>2]=i[A+8>>2],i[v+12>>2]=i[A+12>>2],yA(v,E,m),i[o>>2]=0,(0|(d=t+r+(6==(0|t)&1)|0))<=(0|r))I=y;else{f=r+6|0,s=16928+((a=0|i[E>>2])<<2)|0,u=w+8|0,l=p+8|0,h=B+8|0,c=k+4|0,x=0,D=r,t=-1;A:for(;;){if(A=m+((E=(0|D)%6|0)<<4)|0,i[k>>2]=i[A>>2],i[k+4>>2]=i[A+4>>2],i[k+8>>2]=i[A+8>>2],i[k+12>>2]=i[A+12>>2],A=x,x=0|kA(k,a,0,1),(0|D)>(0|r)&0!=(0|RA(e))&&(1!=(0|A)&&(0|i[k>>2])!=(0|t))){switch(K(m+(((E+5|0)%6|0)<<4)+4|0,M),K(m+(E<<4)+4|0,g),_=+(0|i[s>>2]),n[w>>3]=3*_,n[u>>3]=0,F=-1.5*_,n[p>>3]=F,n[l>>3]=2.598076211353316*_,n[B>>3]=F,n[h>>3]=-2.598076211353316*_,E=0|i[v>>2],0|i[17008+(80*E|0)+(((0|t)==(0|E)?0|i[k>>2]:t)<<2)>>2]){case 1:A=p,t=w;break;case 3:A=B,t=p;break;case 2:A=w,t=B;break;default:A=8;break A}oe(M,g,t,A,b),0|ae(M,b)||0|ae(g,b)||(BA(b,0|i[v>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2]))}if((0|D)<(0|f)&&(K(c,M),BA(M,0|i[k>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])),(0|(D=D+1|0))>=(0|d)){A=3;break}t=0|i[k>>2]}3!=(0|A)?8==(0|A)&&Q(22557,22521,746,22602):I=y}}function yA(A,e,r){A|=0,e|=0,r|=0;var t,n=0,o=0,a=0,f=0,s=0;t=I,I=I+160|0,o=t,f=20336,s=(a=n=t+80|0)+72|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));f=20416,s=(a=o)+72|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));n=(s=0==(0|RA(0|i[e>>2])))?n:o,uA(o=A+4|0),lA(o),0|RA(0|i[e>>2])&&(iA(o),i[e>>2]=1+(0|i[e>>2])),i[r>>2]=i[A>>2],X(o,n,e=r+4|0),J(e),i[r+16>>2]=i[A>>2],X(o,n+12|0,e=r+20|0),J(e),i[r+32>>2]=i[A>>2],X(o,n+24|0,e=r+36|0),J(e),i[r+48>>2]=i[A>>2],X(o,n+36|0,e=r+52|0),J(e),i[r+64>>2]=i[A>>2],X(o,n+48|0,e=r+68|0),J(e),i[r+80>>2]=i[A>>2],X(o,n+60|0,r=r+84|0),J(r),I=t}function EA(A){var e;return e=(A=+A)<0?A+6.283185307179586:A,+(A>=6.283185307179586?e+-6.283185307179586:e)}function xA(A,e){return e|=0,+f(+(+n[(A|=0)>>3]-+n[e>>3]))<17453292519943298e-27?0|(e=+f(+(+n[A+8>>3]-+n[e+8>>3]))<17453292519943298e-27):0|(e=0)}function DA(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))*6371.007180918475}function _A(A,e,r){A|=0,r|=0;var t,i,o,a,f=0,u=0,d=0,g=0,B=0,b=0;return b=+n[(e|=0)>>3],o=+n[A>>3],B=+h(.5*(b-o)),d=+n[e+8>>3],i=+n[A+8>>3],g=+h(.5*(d-i)),t=+l(+o),a=+l(+b),g=2*+p(+ +s(+(g=B*B+g*(a*t*g))),+ +s(+(1-g))),B=+n[r>>3],b=+h(.5*(B-b)),f=+n[r+8>>3],d=+h(.5*(f-d)),u=+l(+B),d=2*+p(+ +s(+(d=b*b+d*(a*u*d))),+ +s(+(1-d))),B=+h(.5*(o-B)),f=+h(.5*(i-f)),f=2*+p(+ +s(+(f=B*B+f*(t*u*f))),+ +s(+(1-f))),4*+w(+ +s(+ +c(.5*(u=.5*(g+d+f)))*+c(.5*(u-g))*+c(.5*(u-d))*+c(.5*(u-f))))}function IA(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),45),M(),127&e|0}function FA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0;if(!(!0&134217728==(-16777216&(e|=0)|0)))return 0|(e=0);if(o=0|Qe(0|(A|=0),0|e,45),M(),(o&=127)>>>0>121)return 0|(e=0);r=0|Qe(0|A,0|e,52),M(),r&=15;do{if(0|r){for(i=1,t=0;;){if(n=0|Qe(0|A,0|e,3*(15-i|0)|0),M(),0!=(0|(n&=7))&(1^t)){if(1==(0|n)&0!=(0|S(o))){a=0,t=13;break}t=1}if(7==(0|n)){a=0,t=13;break}if(!(i>>>0>>0)){t=9;break}i=i+1|0}if(9==(0|t)){if(15!=(0|r))break;return 0|(a=1)}if(13==(0|t))return 0|a}}while(0);for(;;){if(a=0|Qe(0|A,0|e,3*(14-r|0)|0),M(),!(7==(7&a|0)&!0)){a=0,t=13;break}if(!(r>>>0<14)){a=1,t=13;break}r=r+1|0}return 13==(0|t)?0|a:0}function CA(A,e,r){r|=0;var t=0,i=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|(t&=15))>=(0|r)){if((0|t)!=(0|r))if(r>>>0<=15){if(A|=i=0|ye(0|r,0,52),e=0|M()|-15728641&e,(0|t)>(0|r))do{i=0|ye(7,0,3*(14-r|0)|0),r=r+1|0,A|=i,e=0|M()|e}while((0|r)<(0|t))}else e=0,A=0}else e=0,A=0;return k(0|e),0|A}function PA(A,e,r,t){r|=0,t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(f&=15))<=(0|r)){if((0|f)==(0|r))return i[(r=t)>>2]=A,void(i[r+4>>2]=e);if(n=(0|(u=0|ee(7,r-f|0)))/7|0,s=0|Qe(0|A,0|e,45),M(),0|S(127&s)){A:do{if(f)for(a=1;;){if(o=0|Qe(0|A,0|e,3*(15-a|0)|0),M(),0|(o&=7))break A;if(!(a>>>0>>0)){o=0;break}a=a+1|0}else o=0}while(0);a=0==(0|o)}else a=0;if(l=0|ye(f+1|0,0,52),o=0|M()|-15728641&e,PA(e=(l|A)&~(e=0|ye(7,0,0|(s=3*(14-f|0)|0))),f=o&~(0|M()),r,t),o=t+(n<<3)|0,!a)return PA((l=0|ye(1,0,0|s))|e,0|M()|f,r,o),l=o+(n<<3)|0,PA((u=0|ye(2,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(3,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(4,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(5,0,0|s))|e,0|M()|f,r,l),void PA((u=0|ye(6,0,0|s))|e,0|M()|f,r,l+(n<<3)|0);a=o+(n<<3)|0,(0|u)>6&&(_e(0|o,0,(l=(a>>>0>(u=o+8|0)>>>0?a:u)+-1+(0-o)|0)+8&-8|0),o=u+(l>>>3<<3)|0),PA((l=0|ye(2,0,0|s))|e,0|M()|f,r,o),l=o+(n<<3)|0,PA((u=0|ye(3,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(4,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(5,0,0|s))|e,0|M()|f,r,l),PA((u=0|ye(6,0,0|s))|e,0|M()|f,r,l+(n<<3)|0)}}function UA(A,e){var r=0,t=0,i=0;if(i=0|Qe(0|(A|=0),0|(e|=0),45),M(),!(0|S(127&i)))return 0|(i=0);i=0|Qe(0|A,0|e,52),M(),i&=15;A:do{if(i)for(t=1;;){if(r=0|Qe(0|A,0|e,3*(15-t|0)|0),M(),0|(r&=7))break A;if(!(t>>>0>>0)){r=0;break}t=t+1|0}else r=0}while(0);return 0|(i=0==(0|r)&1)}function GA(A,e){var r=0,t=0,i=0;if(i=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(i&=15))return 0|(i=0);for(t=1;;){if(r=0|Qe(0|A,0|e,3*(15-t|0)|0),M(),0|(r&=7)){t=5;break}if(!(t>>>0>>0)){r=0,t=5;break}t=t+1|0}return 5==(0|t)?0|r:0}function SA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0,f=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(f&=15))return f=A,k(0|(a=e)),0|f;for(a=1,r=0;;){t=0|ye(7,0,0|(n=3*(15-a|0)|0)),i=0|M(),o=0|Qe(0|A,0|e,0|n),M(),A=(n=0|ye(0|fA(7&o),0,0|n))|A&~t,e=(o=0|M())|e&~i;A:do{if(!r)if(0==(n&t|0)&0==(o&i|0))r=0;else if(t=0|Qe(0|A,0|e,52),M(),t&=15){r=1;e:for(;;){switch(o=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),7&o){case 1:break e;case 0:break;default:r=1;break A}if(!(r>>>0>>0)){r=1;break A}r=r+1|0}for(r=1;;){if(i=0|Qe(0|A,0|e,0|(o=3*(15-r|0)|0)),M(),n=0|ye(7,0,0|o),e&=~(0|M()),A=A&~n|(o=0|ye(0|fA(7&i),0,0|o)),e=0|e|M(),!(r>>>0>>0)){r=1;break}r=r+1|0}}else r=1}while(0);if(!(a>>>0>>0))break;a=a+1|0}return k(0|e),0|A}function TA(A,e){var r=0,t=0,i=0,n=0,o=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(t&=15))return t=A,k(0|(r=e)),0|t;for(r=1;o=0|Qe(0|A,0|e,0|(n=3*(15-r|0)|0)),M(),i=0|ye(7,0,0|n),e&=~(0|M()),A=(n=0|ye(0|fA(7&o),0,0|n))|A&~i,e=0|M()|e,r>>>0>>0;)r=r+1|0;return k(0|e),0|A}function VA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0,f=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(f&=15))return f=A,k(0|(a=e)),0|f;for(a=1,r=0;;){t=0|ye(7,0,0|(n=3*(15-a|0)|0)),i=0|M(),o=0|Qe(0|A,0|e,0|n),M(),A=(n=0|ye(0|sA(7&o),0,0|n))|A&~t,e=(o=0|M())|e&~i;A:do{if(!r)if(0==(n&t|0)&0==(o&i|0))r=0;else if(t=0|Qe(0|A,0|e,52),M(),t&=15){r=1;e:for(;;){switch(o=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),7&o){case 1:break e;case 0:break;default:r=1;break A}if(!(r>>>0>>0)){r=1;break A}r=r+1|0}for(r=1;;){if(n=0|ye(7,0,0|(i=3*(15-r|0)|0)),o=e&~(0|M()),e=0|Qe(0|A,0|e,0|i),M(),A=A&~n|(e=0|ye(0|sA(7&e),0,0|i)),e=0|o|M(),!(r>>>0>>0)){r=1;break}r=r+1|0}}else r=1}while(0);if(!(a>>>0>>0))break;a=a+1|0}return k(0|e),0|A}function HA(A,e){var r=0,t=0,i=0,n=0,o=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(t&=15))return t=A,k(0|(r=e)),0|t;for(r=1;n=0|ye(7,0,0|(o=3*(15-r|0)|0)),i=e&~(0|M()),e=0|Qe(0|A,0|e,0|o),M(),A=(e=0|ye(0|sA(7&e),0,0|o))|A&~n,e=0|M()|i,r>>>0>>0;)r=r+1|0;return k(0|e),0|A}function RA(A){return 0|(0|(A|=0))%2}function LA(A,e){A|=0;var r,t;return t=I,I=I+16|0,r=t,(e|=0)>>>0<=15&&2146435072!=(2146435072&i[A+4>>2]|0)&&2146435072!=(2146435072&i[A+8+4>>2]|0)?(!function(A,e,r){var t,i;t=I,I=I+16|0,pA(A|=0,e|=0,r|=0,i=t),W(i,r+4|0),I=t}(A,e,r),e=0|function(A,e){A|=0;var r,t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0;if(r=I,I=I+64|0,s=r+40|0,n=r+24|0,o=r+12|0,a=r,ye(0|(e|=0),0,52),t=134225919|M(),!e)return(0|i[A+4>>2])>2||(0|i[A+8>>2])>2||(0|i[A+12>>2])>2?(s=0,k(0|(f=0)),I=r,0|s):(ye(0|V(A),0,45),f=0|M()|t,s=-1,k(0|f),I=r,0|s);if(i[s>>2]=i[A>>2],i[s+4>>2]=i[A+4>>2],i[s+8>>2]=i[A+8>>2],i[s+12>>2]=i[A+12>>2],f=s+4|0,(0|e)>0)for(A=-1;i[n>>2]=i[f>>2],i[n+4>>2]=i[f+4>>2],i[n+8>>2]=i[f+8>>2],1&e?(eA(f),i[o>>2]=i[f>>2],i[o+4>>2]=i[f+4>>2],i[o+8>>2]=i[f+8>>2],tA(o)):(rA(f),i[o>>2]=i[f>>2],i[o+4>>2]=i[f+4>>2],i[o+8>>2]=i[f+8>>2],iA(o)),q(n,o,a),J(a),u=0|ye(7,0,0|(l=3*(15-e|0)|0)),t&=~(0|M()),A=(l=0|ye(0|AA(a),0,0|l))|A&~u,t=0|M()|t,(0|e)>1;)e=e+-1|0;else A=-1;A:do{if((0|i[f>>2])<=2&&(0|i[s+8>>2])<=2&&(0|i[s+12>>2])<=2){if(e=0|ye(0|(n=0|V(s)),0,45),e|=A,A=0|M()|-1040385&t,a=0|H(s),!(0|S(n))){if((0|a)<=0)break;for(o=0;;){if(n=0|Qe(0|e,0|A,52),M(),n&=15)for(t=1;s=0|Qe(0|e,0|A,0|(l=3*(15-t|0)|0)),M(),u=0|ye(7,0,0|l),A&=~(0|M()),e=e&~u|(l=0|ye(0|fA(7&s),0,0|l)),A=0|A|M(),t>>>0>>0;)t=t+1|0;if((0|(o=o+1|0))==(0|a))break A}}o=0|Qe(0|e,0|A,52),M(),o&=15;e:do{if(o){t=1;r:for(;;){switch(l=0|Qe(0|e,0|A,3*(15-t|0)|0),M(),7&l){case 1:break r;case 0:break;default:break e}if(!(t>>>0>>0))break e;t=t+1|0}if(0|R(n,0|i[s>>2]))for(t=1;u=0|ye(7,0,0|(s=3*(15-t|0)|0)),l=A&~(0|M()),A=0|Qe(0|e,0|A,0|s),M(),e=e&~u|(A=0|ye(0|sA(7&A),0,0|s)),A=0|l|M(),t>>>0>>0;)t=t+1|0;else for(t=1;s=0|Qe(0|e,0|A,0|(l=3*(15-t|0)|0)),M(),u=0|ye(7,0,0|l),A&=~(0|M()),e=e&~u|(l=0|ye(0|fA(7&s),0,0|l)),A=0|A|M(),t>>>0>>0;)t=t+1|0}}while(0);if((0|a)>0){t=0;do{e=0|SA(e,A),A=0|M(),t=t+1|0}while((0|t)!=(0|a))}}else e=0,A=0}while(0);return l=e,k(0|(u=A)),I=r,0|l}(r,e),A=0|M()):(A=0,e=0),k(0|A),I=t,0|e}function zA(A,e,r){var t,n=0,o=0,a=0;if(t=(r|=0)+4|0,o=0|Qe(0|(A|=0),0|(e|=0),52),M(),o&=15,a=0|Qe(0|A,0|e,45),M(),n=0==(0|o),0|S(127&a)){if(n)return 0|(a=1);n=1}else{if(n)return 0|(a=0);n=0==(0|i[t>>2])&&0==(0|i[r+8>>2])?0!=(0|i[r+12>>2])&1:1}for(r=1;1&r?tA(t):iA(t),a=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),nA(t,7&a),r>>>0>>0;)r=r+1|0;return 0|n}function YA(A,e,r){r|=0;var t,n,o=0,a=0,f=0,s=0,u=0,l=0;n=I,I=I+16|0,t=n,l=0|Qe(0|(A|=0),0|(e|=0),45),M(),l&=127;A:do{if(0!=(0|S(l))&&(f=0|Qe(0|A,0|e,52),M(),0!=(0|(f&=15)))){o=1;e:for(;;){switch(u=0|Qe(0|A,0|e,3*(15-o|0)|0),M(),7&u){case 5:break e;case 0:break;default:o=e;break A}if(!(o>>>0>>0)){o=e;break A}o=o+1|0}for(a=1,o=e;s=0|ye(7,0,0|(e=3*(15-a|0)|0)),u=o&~(0|M()),o=0|Qe(0|A,0|o,0|e),M(),A=A&~s|(o=0|ye(0|sA(7&o),0,0|e)),o=0|u|M(),a>>>0>>0;)a=a+1|0}else o=e}while(0);if(u=7728+(28*l|0)|0,i[r>>2]=i[u>>2],i[r+4>>2]=i[u+4>>2],i[r+8>>2]=i[u+8>>2],i[r+12>>2]=i[u+12>>2],0|zA(A,o,r)){if(s=r+4|0,i[t>>2]=i[s>>2],i[t+4>>2]=i[s+4>>2],i[t+8>>2]=i[s+8>>2],f=0|Qe(0|A,0|o,52),M(),u=15&f,1&f?(iA(s),f=u+1|0):f=u,0|S(l)){A:do{if(u)for(e=1;;){if(a=0|Qe(0|A,0|o,3*(15-e|0)|0),M(),0|(a&=7)){o=a;break A}if(!(e>>>0>>0)){o=0;break}e=e+1|0}else o=0}while(0);o=4==(0|o)&1}else o=0;if(0|kA(r,f,o,0)){if(0|S(l))do{}while(0!=(0|kA(r,f,0,0)));(0|f)!=(0|u)&&rA(s)}else(0|f)!=(0|u)&&(i[s>>2]=i[t>>2],i[s+4>>2]=i[t+4>>2],i[s+8>>2]=i[t+8>>2]);I=n}else I=n}function OA(A,e,r){r|=0;var t,i;t=I,I=I+16|0,YA(A|=0,e|=0,i=t),e=0|Qe(0|A,0|e,52),M(),bA(i,15&e,r),I=t}function jA(A,e,r){r|=0;var t,i,n=0,o=0;i=I,I=I+16|0,YA(A|=0,e|=0,t=i),n=0|Qe(0|A,0|e,45),M(),n=0==(0|S(127&n)),o=0|Qe(0|A,0|e,52),M(),o&=15;A:do{if(!n){if(0|o)for(n=1;;){if(!(0==((0|ye(7,0,3*(15-n|0)|0))&A|0)&0==((0|M())&e|0)))break A;if(!(n>>>0>>0))break;n=n+1|0}return vA(t,o,0,5,r),void(I=i)}}while(0);QA(t,o,0,6,r),I=i}function NA(A,e){e|=0;var r,t=0,n=0,o=0,a=0,f=0,s=0;if(ye(0|(A|=0),0,52),r=134225919|M(),(0|A)<1){n=0,t=0;do{0|S(n)&&(ye(0|n,0,45),f=0|r|M(),i[(A=e+(t<<3)|0)>>2]=-1,i[A+4>>2]=f,t=t+1|0),n=n+1|0}while(122!=(0|n))}else{f=0,t=0;do{if(0|S(f)){for(ye(0|f,0,45),n=1,o=-1,a=0|r|M();o&=~(s=0|ye(7,0,3*(15-n|0)|0)),a&=~(0|M()),(0|n)!=(0|A);)n=n+1|0;i[(s=e+(t<<3)|0)>>2]=o,i[s+4>>2]=a,t=t+1|0}f=f+1|0}while(122!=(0|f))}}function ZA(A,e,r,t){var n,o=0,a=0,f=0,s=0,u=0;if(n=I,I=I+64|0,f=n,(0|(A|=0))==(0|(r|=0))&(0|(e|=0))==(0|(t|=0))|!1|134217728!=(2013265920&e|0)|!1|134217728!=(2013265920&t|0))return I=n,0|(f=0);if(o=0|Qe(0|A,0|e,52),M(),o&=15,a=0|Qe(0|r,0|t,52),M(),(0|o)!=(15&a|0))return I=n,0|(f=0);if(a=o+-1|0,o>>>0>1&&(u=0|CA(A,e,a),s=0|M(),(0|u)==(0|(a=0|CA(r,t,a)))&(0|s)==(0|M()))){if(o=0|Qe(0|A,0|e,0|(a=3*(15^o)|0)),M(),o&=7,a=0|Qe(0|r,0|t,0|a),M(),0==(0|o)|0==(0|(a&=7)))return I=n,0|(u=1);if((0|i[21136+(o<<2)>>2])==(0|a))return I=n,0|(u=1);if((0|i[21168+(o<<2)>>2])==(0|a))return I=n,0|(u=1)}a=(o=f)+56|0;do{i[o>>2]=0,o=o+4|0}while((0|o)<(0|a));return F(A,e,1,f),o=(0|i[(u=f)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+8|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+16|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+24|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+32|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+40|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)?1:1&((0|i[(o=f+48|0)>>2])==(0|r)?(0|i[o+4>>2])==(0|t):0),I=n,0|(u=o)}function WA(A,e,r){r|=0;var t,n,o,a,f=0;if(o=I,I=I+16|0,n=o,f=0|Qe(0|(A|=0),0|(e|=0),56),M(),-1==(0|(e=0|function(A,e,r){r|=0;var t=0,n=0;if(t=0|UA(A=A|0,e=e|0),(r+-1|0)>>>0>5)return 0|(r=-1);if(1==(0|r)&(n=0!=(0|t)))return 0|(r=-1);return t=0|function(A,e){var r=0,t=0,n=0,o=0,a=0,f=0,s=0,u=0;if(u=I,I=I+32|0,o=u,YA(A=A|0,e=e|0,n=u+16|0),a=0|IA(A,e),s=0|GA(A,e),function(A,e){A=7728+(28*(A|=0)|0)|0,i[(e|=0)>>2]=i[A>>2],i[e+4>>2]=i[A+4>>2],i[e+8>>2]=i[A+8>>2],i[e+12>>2]=i[A+12>>2]}(a,o),e=0|function(A,e){A|=0;var r=0,t=0;if((e|=0)>>>0>20)return-1;do{if((0|i[11152+(216*e|0)>>2])!=(0|A))if((0|i[11152+(216*e|0)+8>>2])!=(0|A))if((0|i[11152+(216*e|0)+16>>2])!=(0|A))if((0|i[11152+(216*e|0)+24>>2])!=(0|A))if((0|i[11152+(216*e|0)+32>>2])!=(0|A))if((0|i[11152+(216*e|0)+40>>2])!=(0|A))if((0|i[11152+(216*e|0)+48>>2])!=(0|A))if((0|i[11152+(216*e|0)+56>>2])!=(0|A))if((0|i[11152+(216*e|0)+64>>2])!=(0|A))if((0|i[11152+(216*e|0)+72>>2])!=(0|A))if((0|i[11152+(216*e|0)+80>>2])!=(0|A))if((0|i[11152+(216*e|0)+88>>2])!=(0|A))if((0|i[11152+(216*e|0)+96>>2])!=(0|A))if((0|i[11152+(216*e|0)+104>>2])!=(0|A))if((0|i[11152+(216*e|0)+112>>2])!=(0|A))if((0|i[11152+(216*e|0)+120>>2])!=(0|A))if((0|i[11152+(216*e|0)+128>>2])!=(0|A)){if((0|i[11152+(216*e|0)+136>>2])!=(0|A)){if((0|i[11152+(216*e|0)+144>>2])==(0|A)){A=0,r=2,t=0;break}if((0|i[11152+(216*e|0)+152>>2])==(0|A)){A=0,r=2,t=1;break}if((0|i[11152+(216*e|0)+160>>2])==(0|A)){A=0,r=2,t=2;break}if((0|i[11152+(216*e|0)+168>>2])==(0|A)){A=1,r=2,t=0;break}if((0|i[11152+(216*e|0)+176>>2])==(0|A)){A=1,r=2,t=1;break}if((0|i[11152+(216*e|0)+184>>2])==(0|A)){A=1,r=2,t=2;break}if((0|i[11152+(216*e|0)+192>>2])==(0|A)){A=2,r=2,t=0;break}if((0|i[11152+(216*e|0)+200>>2])==(0|A)){A=2,r=2,t=1;break}if((0|i[11152+(216*e|0)+208>>2])==(0|A)){A=2,r=2,t=2;break}return-1}A=2,r=1,t=2}else A=2,r=1,t=1;else A=2,r=1,t=0;else A=1,r=1,t=2;else A=1,r=1,t=1;else A=1,r=1,t=0;else A=0,r=1,t=2;else A=0,r=1,t=1;else A=0,r=1,t=0;else A=2,r=0,t=2;else A=2,r=0,t=1;else A=2,r=0,t=0;else A=1,r=0,t=2;else A=1,r=0,t=1;else A=1,r=0,t=0;else A=0,r=0,t=2;else A=0,r=0,t=1;else A=0,r=0,t=0}while(0);return 0|i[11152+(216*e|0)+(72*r|0)+(24*A|0)+(t<<3)+4>>2]}(a,0|i[n>>2]),!(0|S(a)))return I=u,0|(s=e);switch(0|a){case 4:A=0,r=14;break;case 14:A=1,r=14;break;case 24:A=2,r=14;break;case 38:A=3,r=14;break;case 49:A=4,r=14;break;case 58:A=5,r=14;break;case 63:A=6,r=14;break;case 72:A=7,r=14;break;case 83:A=8,r=14;break;case 97:A=9,r=14;break;case 107:A=10,r=14;break;case 117:A=11,r=14;break;default:f=0,t=0}14==(0|r)&&(f=0|i[22096+(24*A|0)+8>>2],t=0|i[22096+(24*A|0)+16>>2]);(0|(A=0|i[n>>2]))!=(0|i[o>>2])&&(a=0|T(a))|(0|(A=0|i[n>>2]))==(0|t)&&(e=(e+1|0)%6|0);if(3==(0|s)&(0|A)==(0|t))return I=u,0|(s=(e+5|0)%6|0);if(!(5==(0|s)&(0|A)==(0|f)))return I=u,0|(s=e);return I=u,0|(s=(e+1|0)%6|0)}(A,e),n?0|(r=(5-t+(0|i[22384+(r<<2)>>2])|0)%5|0):0|(r=(6-t+(0|i[22416+(r<<2)>>2])|0)%6|0)}(t=(a=!0&268435456==(2013265920&e|0))?A:0,A=a?-2130706433&e|134217728:0,7&f))))return i[r>>2]=0,void(I=o);YA(t,A,n),f=0|Qe(0|t,0|A,52),M(),f&=15,0|UA(t,A)?vA(n,f,e,2,r):QA(n,f,e,2,r),I=o}function JA(A){A|=0;var e,r,t=0;return(e=0|be(1,12))||Q(22691,22646,49,22704),0|(t=0|i[(r=A+4|0)>>2])?(i[(t=t+8|0)>>2]=e,i[r>>2]=e,0|e):(0|i[A>>2]&&Q(22721,22646,61,22744),i[(t=A)>>2]=e,i[r>>2]=e,0|e)}function KA(A,e){A|=0,e|=0;var r,t;return(t=0|pe(24))||Q(22758,22646,78,22772),i[t>>2]=i[e>>2],i[t+4>>2]=i[e+4>>2],i[t+8>>2]=i[e+8>>2],i[t+12>>2]=i[e+12>>2],i[t+16>>2]=0,0|(r=0|i[(e=A+4|0)>>2])?(i[r+16>>2]=t,i[e>>2]=t,0|t):(0|i[A>>2]&&Q(22787,22646,82,22772),i[A>>2]=t,i[e>>2]=t,0|t)}function XA(A){var e,r,t=0,o=0,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,y=0,E=0,x=0,D=0,_=0,I=0,F=0,C=0,P=0,U=0,G=0,S=0;if(0|i[(s=(A|=0)+8|0)>>2])return 0|(S=1);if(!(a=0|i[A>>2]))return 0|(S=0);t=a,o=0;do{o=o+1|0,t=0|i[t+8>>2]}while(0!=(0|t));if(o>>>0<2)return 0|(S=0);(r=0|pe(o<<2))||Q(22807,22646,317,22826),(e=0|pe(o<<5))||Q(22848,22646,321,22826),i[A>>2]=0,i[(D=A+4|0)>>2]=0,i[s>>2]=0,o=0,U=0,x=0,w=0;A:for(;;){if(g=0|i[a>>2]){u=0,l=g;do{if(c=+n[l+8>>3],t=l,l=0|i[l+16>>2],h=+n[(s=(d=0==(0|l))?g:l)+8>>3],+f(+(c-h))>3.141592653589793){S=14;break}u+=(h-c)*(+n[t>>3]+ +n[s>>3])}while(!d);if(14==(0|S)){S=0,u=0,t=g;do{E=+n[t+8>>3],C=0|i[(P=t+16|0)>>2],y=+n[(C=0==(0|C)?g:C)+8>>3],u+=(+n[t>>3]+ +n[C>>3])*((y<0?y+6.283185307179586:y)-(E<0?E+6.283185307179586:E)),t=0|i[(0==(0|t)?a:P)>>2]}while(0!=(0|t))}u>0?(i[r+(U<<2)>>2]=a,U=U+1|0,s=x,t=w):S=19}else S=19;if(19==(0|S)){S=0;do{if(!o){if(w){s=D,l=w+8|0,t=a,o=A;break}if(0|i[A>>2]){S=27;break A}s=D,l=A,t=a,o=A;break}if(0|i[(t=o+8|0)>>2]){S=21;break A}if(!(o=0|be(1,12))){S=23;break A}i[t>>2]=o,s=o+4|0,l=o,t=w}while(0);if(i[l>>2]=a,i[s>>2]=a,l=e+(x<<5)|0,d=0|i[a>>2]){for(n[(g=e+(x<<5)+8|0)>>3]=17976931348623157e292,n[(w=e+(x<<5)+24|0)>>3]=17976931348623157e292,n[l>>3]=-17976931348623157e292,n[(p=e+(x<<5)+16|0)>>3]=-17976931348623157e292,k=17976931348623157e292,M=-17976931348623157e292,s=0,B=d,c=17976931348623157e292,v=17976931348623157e292,m=-17976931348623157e292,h=-17976931348623157e292;u=+n[B>>3],E=+n[B+8>>3],B=0|i[B+16>>2],y=+n[((b=0==(0|B))?d:B)+8>>3],u>3]=u,c=u),E>3]=E,v=E),u>m?n[l>>3]=u:u=m,E>h&&(n[p>>3]=E,h=E),k=E>0&EM?E:M,s|=+f(+(E-y))>3.141592653589793,!b;)m=u;s&&(n[p>>3]=M,n[w>>3]=k)}else i[l>>2]=0,i[l+4>>2]=0,i[l+8>>2]=0,i[l+12>>2]=0,i[l+16>>2]=0,i[l+20>>2]=0,i[l+24>>2]=0,i[l+28>>2]=0;s=x+1|0}if(a=0|i[(P=a+8|0)>>2],i[P>>2]=0,!a){S=45;break}x=s,w=t}if(21==(0|S))Q(22624,22646,35,22658);else if(23==(0|S))Q(22678,22646,37,22658);else if(27==(0|S))Q(22721,22646,61,22744);else if(45==(0|S)){A:do{if((0|U)>0){for(P=0==(0|s),F=s<<2,C=0==(0|A),I=0,t=0;;){if(_=0|i[r+(I<<2)>>2],P)S=73;else{if(!(x=0|pe(F))){S=50;break}if(!(D=0|pe(F))){S=52;break}e:do{if(C)o=0;else{for(s=0,o=0,l=A;a=e+(s<<5)|0,0|qA(0|i[l>>2],a,0|i[_>>2])?(i[x+(o<<2)>>2]=l,i[D+(o<<2)>>2]=a,b=o+1|0):b=o,l=0|i[l+8>>2];)s=s+1|0,o=b;if((0|b)>0)if(a=0|i[x>>2],1==(0|b))o=a;else for(p=0,B=-1,o=a,w=a;;){for(d=0|i[w>>2],a=0,l=0;g=(0|(s=0|i[i[x+(l<<2)>>2]>>2]))==(0|d)?a:a+(1&(0|qA(s,0|i[D+(l<<2)>>2],0|i[d>>2])))|0,(0|(l=l+1|0))!=(0|b);)a=g;if(o=(s=(0|g)>(0|B))?w:o,(0|(a=p+1|0))==(0|b))break e;p=a,B=s?g:B,w=0|i[x+(a<<2)>>2]}else o=0}}while(0);if(Be(x),Be(D),o){if(a=0|i[(s=o+4|0)>>2])o=a+8|0;else if(0|i[o>>2]){S=70;break}i[o>>2]=_,i[s>>2]=_}else S=73}if(73==(0|S)){if(S=0,0|(t=0|i[_>>2]))do{D=t,t=0|i[t+16>>2],Be(D)}while(0!=(0|t));Be(_),t=2}if((0|(I=I+1|0))>=(0|U)){G=t;break A}}50==(0|S)?Q(22863,22646,249,22882):52==(0|S)?Q(22901,22646,252,22882):70==(0|S)&&Q(22721,22646,61,22744)}else G=0}while(0);return Be(r),Be(e),0|(S=G)}return 0}function qA(A,e,r){A|=0;var t,o=0,a=0,f=0,s=0,u=0,l=0,h=0;if(!(0|O(e|=0,r|=0)))return 0|(A=0);if(e=0|Y(e),t=+n[r>>3],o=e&(o=+n[r+8>>3])<0?o+6.283185307179586:o,!(A=0|i[A>>2]))return 0|(A=0);if(e){e=0,r=A;A:for(;;){for(;s=+n[r>>3],l=+n[r+8>>3],h=0|i[(r=r+16|0)>>2],f=+n[(h=0==(0|h)?A:h)>>3],a=+n[h+8>>3],s>f?(u=s,s=l):(u=f,f=s,s=a,a=l),tu;)if(!(r=0|i[r>>2])){r=22;break A}if(o=(s=s<0?s+6.283185307179586:s)==o|(l=a<0?a+6.283185307179586:a)==o?o+-2220446049250313e-31:o,((l+=(t-f)/(u-f)*(s-l))<0?l+6.283185307179586:l)>o&&(e^=1),!(r=0|i[r>>2])){r=22;break}}if(22==(0|r))return 0|e}else{e=0,r=A;A:for(;;){for(;s=+n[r>>3],l=+n[r+8>>3],h=0|i[(r=r+16|0)>>2],f=+n[(h=0==(0|h)?A:h)>>3],a=+n[h+8>>3],s>f?(u=s,s=l):(u=f,f=s,s=a,a=l),tu;)if(!(r=0|i[r>>2])){r=22;break A}if(a+(t-f)/(u-f)*(s-a)>(o=s==o|a==o?o+-2220446049250313e-31:o)&&(e^=1),!(r=0|i[r>>2])){r=22;break}}if(22==(0|r))return 0|e}return 0}function $A(A,e,r,n,o){r|=0,n|=0,o|=0;var a,f,s,u,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0;if(u=I,I=I+32|0,v=u+16|0,s=u,l=0|Qe(0|(A|=0),0|(e|=0),52),M(),l&=15,p=0|Qe(0|r,0|n,52),M(),(0|l)!=(15&p|0))return I=u,0|(v=1);if(g=0|Qe(0|A,0|e,45),M(),g&=127,w=0|Qe(0|r,0|n,45),M(),p=(0|g)!=(0|(w&=127))){if(7==(0|(c=0|z(g,w))))return I=u,0|(v=2);7==(0|(d=0|z(w,g)))?Q(22925,22949,151,22959):(B=c,h=d)}else B=0,h=0;a=0|S(g),f=0|S(w),i[v>>2]=0,i[v+4>>2]=0,i[v+8>>2]=0,i[v+12>>2]=0;do{if(B){if(c=(0|(w=0|i[4304+(28*g|0)+(B<<2)>>2]))>0,f)if(c){g=0,d=r,c=n;do{d=0|VA(d,c),c=0|M(),1==(0|(h=0|sA(h)))&&(h=0|sA(1)),g=g+1|0}while((0|g)!=(0|w));w=h,g=d,d=c}else w=h,g=r,d=n;else if(c){g=0,d=r,c=n;do{d=0|HA(d,c),c=0|M(),h=0|sA(h),g=g+1|0}while((0|g)!=(0|w));w=h,g=d,d=c}else w=h,g=r,d=n;if(zA(g,d,v),p||Q(22972,22949,181,22959),(c=0!=(0|a))&(h=0!=(0|f))&&Q(22999,22949,182,22959),c){if(h=0|GA(A,e),0|t[22032+(7*h|0)+B>>0]){l=3;break}g=d=0|i[21200+(28*h|0)+(B<<2)>>2],b=26}else if(h){if(h=0|GA(g,d),0|t[22032+(7*h|0)+w>>0]){l=4;break}g=0,d=0|i[21200+(28*w|0)+(h<<2)>>2],b=26}else h=0;if(26==(0|b))if((0|d)<=-1&&Q(23030,22949,212,22959),(0|g)<=-1&&Q(23053,22949,213,22959),(0|d)>0){c=v+4|0,h=0;do{aA(c),h=h+1|0}while((0|h)!=(0|d));h=g}else h=g;if(i[s>>2]=0,i[s+4>>2]=0,i[s+8>>2]=0,nA(s,B),0|l)for(;0|RA(l)?tA(s):iA(s),(0|l)>1;)l=l+-1|0;if((0|h)>0){l=0;do{aA(s),l=l+1|0}while((0|l)!=(0|h))}X(b=v+4|0,s,b),J(b),b=50}else if(zA(r,n,v),0!=(0|a)&0!=(0|f))if((0|w)!=(0|g)&&Q(23077,22949,243,22959),h=0|GA(A,e),l=0|GA(r,n),0|t[22032+(7*h|0)+l>>0])l=5;else if((0|(h=0|i[21200+(28*h|0)+(l<<2)>>2]))>0){c=v+4|0,l=0;do{aA(c),l=l+1|0}while((0|l)!=(0|h));b=50}else b=50;else b=50}while(0);return 50==(0|b)&&(l=v+4|0,i[o>>2]=i[l>>2],i[o+4>>2]=i[l+4>>2],i[o+8>>2]=i[l+8>>2],l=0),I=u,0|(v=l)}function Ae(A,e,r,t){r|=0,t|=0;var n,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0;if(o=I,I=I+48|0,s=o+36|0,u=o+24|0,l=o+12|0,h=o,f=0|Qe(0|(A|=0),0|(e|=0),52),M(),f&=15,d=0|Qe(0|A,0|e,45),M(),n=0|S(d&=127),ye(0|f,0,52),p=134225919|M(),i[(w=t)>>2]=-1,i[w+4>>2]=p,!f)return(0|i[r>>2])>1||(0|i[r+4>>2])>1||(0|i[r+8>>2])>1||127==(0|(a=0|L(d,0|AA(r))))?(I=o,0|(p=1)):(g=0|ye(0|a,0,45),w=0|M(),w=-1040385&i[(d=t)+4>>2]|w,i[(p=t)>>2]=i[d>>2]|g,i[p+4>>2]=w,I=o,0|(p=0));for(i[s>>2]=i[r>>2],i[s+4>>2]=i[r+4>>2],i[s+8>>2]=i[r+8>>2];i[u>>2]=i[s>>2],i[u+4>>2]=i[s+4>>2],i[u+8>>2]=i[s+8>>2],0|RA(f)?(eA(s),i[l>>2]=i[s>>2],i[l+4>>2]=i[s+4>>2],i[l+8>>2]=i[s+8>>2],tA(l)):(rA(s),i[l>>2]=i[s>>2],i[l+4>>2]=i[s+4>>2],i[l+8>>2]=i[s+8>>2],iA(l)),q(u,l,h),J(h),B=0|i[(w=t)>>2],w=0|i[w+4>>2],r=0|ye(7,0,0|(b=3*(15-f|0)|0)),w&=~(0|M()),b=0|ye(0|AA(h),0,0|b),w=0|M()|w,i[(p=t)>>2]=b|B&~r,i[p+4>>2]=w,(0|f)>1;)f=f+-1|0;A:do{if((0|i[s>>2])<=1&&(0|i[s+4>>2])<=1&&(0|i[s+8>>2])<=1){h=127==(0|(u=0|L(d,f=0|AA(s))))?0:0|S(u);e:do{if(f){if(n){if(s=21408+(28*(0|GA(A,e))|0)+(f<<2)|0,(0|(s=0|i[s>>2]))>0){r=0;do{f=0|fA(f),r=r+1|0}while((0|r)!=(0|s))}if(1==(0|f)){a=3;break A}127==(0|(r=0|L(d,f)))&&Q(23104,22949,376,23134),0|S(r)?Q(23147,22949,377,23134):(g=s,c=f,a=r)}else g=0,c=f,a=u;if((0|(l=0|i[4304+(28*d|0)+(c<<2)>>2]))<=-1&&Q(23178,22949,384,23134),!h){if((0|g)<=-1&&Q(23030,22949,417,23134),0|g){f=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];do{r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,f=f+1|0}while((0|f)<(0|g))}if((0|l)<=0){f=54;break}for(f=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];;)if(r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,(0|(f=f+1|0))==(0|l)){f=54;break e}}if(7==(0|(u=0|z(a,d)))&&Q(22925,22949,393,23134),r=0|i[(f=t)>>2],f=0|i[f+4>>2],(0|l)>0){s=0;do{r=0|TA(r,f),f=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=f,s=s+1|0}while((0|s)!=(0|l))}if(r=0|GA(r,f),b=0|T(a),(0|(r=0|i[(b?21824:21616)+(28*u|0)+(r<<2)>>2]))<=-1&&Q(23030,22949,412,23134),r){f=0,s=0|i[(u=t)>>2],u=0|i[u+4>>2];do{s=0|SA(s,u),u=0|M(),i[(b=t)>>2]=s,i[b+4>>2]=u,f=f+1|0}while((0|f)<(0|r));f=54}else f=54}else if(0!=(0|n)&0!=(0|h))if(f=21408+(28*(b=0|GA(A,e))|0)+((0|GA(0|i[(f=t)>>2],0|i[f+4>>2]))<<2)|0,(0|(f=0|i[f>>2]))<=-1&&Q(23201,22949,433,23134),f){a=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];do{r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,a=a+1|0}while((0|a)<(0|f));a=u,f=54}else a=u,f=55;else a=u,f=54}while(0);if(54==(0|f)&&h&&(f=55),55==(0|f)&&1==(0|GA(0|i[(b=t)>>2],0|i[b+4>>2]))){a=4;break}p=0|i[(b=t)>>2],b=-1040385&i[b+4>>2],B=0|ye(0|a,0,45),b=0|b|M(),i[(a=t)>>2]=p|B,i[a+4>>2]=b,a=0}else a=2}while(0);return I=o,0|(b=a)}function ee(A,e){var r=0;if(!(e|=0))return 0|(r=1);r=A|=0,A=1;do{A=0|b(0==(1&e|0)?1:r,A),e>>=1,r=0|b(r,r)}while(0!=(0|e));return 0|A}function re(A,e,r){A|=0;var t,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0;if(!(0|O(e|=0,r|=0)))return 0|(d=0);if(e=0|Y(e),o=+n[r>>3],a=e&(a=+n[r+8>>3])<0?a+6.283185307179586:a,(0|(d=0|i[A>>2]))<=0)return 0|(d=0);if(t=0|i[A+4>>2],e){e=0,r=-1,A=0;A:for(;;){for(c=A;u=+n[t+(c<<4)>>3],h=+n[t+(c<<4)+8>>3],s=+n[t+((A=(r+2|0)%(0|d)|0)<<4)>>3],f=+n[t+(A<<4)+8>>3],u>s?(l=u,u=h):(l=s,s=u,u=f,f=h),ol;){if(!((0|(r=c+1|0))<(0|d))){r=22;break A}A=c,c=r,r=A}if(a=(u=u<0?u+6.283185307179586:u)==a|(h=f<0?f+6.283185307179586:f)==a?a+-2220446049250313e-31:a,((h+=(o-s)/(l-s)*(u-h))<0?h+6.283185307179586:h)>a&&(e^=1),(0|(A=c+1|0))>=(0|d)){r=22;break}r=c}if(22==(0|r))return 0|e}else{e=0,r=-1,A=0;A:for(;;){for(c=A;u=+n[t+(c<<4)>>3],h=+n[t+(c<<4)+8>>3],s=+n[t+((A=(r+2|0)%(0|d)|0)<<4)>>3],f=+n[t+(A<<4)+8>>3],u>s?(l=u,u=h):(l=s,s=u,u=f,f=h),ol;){if(!((0|(r=c+1|0))<(0|d))){r=22;break A}A=c,c=r,r=A}if(f+(o-s)/(l-s)*(u-f)>(a=u==a|f==a?a+-2220446049250313e-31:a)&&(e^=1),(0|(A=c+1|0))>=(0|d)){r=22;break}r=c}if(22==(0|r))return 0|e}return 0}function te(A,e){e|=0;var r,t,o,a,s,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0;if(!(t=0|i[(A|=0)>>2]))return i[e>>2]=0,i[e+4>>2]=0,i[e+8>>2]=0,i[e+12>>2]=0,i[e+16>>2]=0,i[e+20>>2]=0,i[e+24>>2]=0,void(i[e+28>>2]=0);if(n[(o=e+8|0)>>3]=17976931348623157e292,n[(a=e+24|0)>>3]=17976931348623157e292,n[e>>3]=-17976931348623157e292,n[(s=e+16|0)>>3]=-17976931348623157e292,!((0|t)<=0)){for(r=0|i[A+4>>2],p=17976931348623157e292,B=-17976931348623157e292,b=0,A=-1,c=17976931348623157e292,d=17976931348623157e292,w=-17976931348623157e292,l=-17976931348623157e292,v=0;u=+n[r+(v<<4)>>3],g=+n[r+(v<<4)+8>>3],h=+n[r+(((0|(A=A+2|0))==(0|t)?0:A)<<4)+8>>3],u>3]=u,c=u),g>3]=g,d=g),u>w?n[e>>3]=u:u=w,g>l&&(n[s>>3]=g,l=g),p=g>0&gB?g:B,b|=+f(+(g-h))>3.141592653589793,(0|(A=v+1|0))!=(0|t);)m=v,w=u,v=A,A=m;b&&(n[s>>3]=B,n[a>>3]=p)}}function ie(A,e){e|=0;var r,t=0,o=0,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,Q=0,y=0,E=0;if(B=0|i[(A|=0)>>2]){if(n[(b=e+8|0)>>3]=17976931348623157e292,n[(v=e+24|0)>>3]=17976931348623157e292,n[e>>3]=-17976931348623157e292,n[(m=e+16|0)>>3]=-17976931348623157e292,(0|B)>0){for(a=0|i[A+4>>2],w=17976931348623157e292,p=-17976931348623157e292,o=0,t=-1,h=17976931348623157e292,c=17976931348623157e292,g=-17976931348623157e292,u=-17976931348623157e292,k=0;s=+n[a+(k<<4)>>3],d=+n[a+(k<<4)+8>>3],l=+n[a+(((0|(y=t+2|0))==(0|B)?0:y)<<4)+8>>3],s>3]=s,h=s),d>3]=d,c=d),s>g?n[e>>3]=s:s=g,d>u&&(n[m>>3]=d,u=d),w=d>0&dp?d:p,o|=+f(+(d-l))>3.141592653589793,(0|(t=k+1|0))!=(0|B);)y=k,g=s,k=t,t=y;o&&(n[m>>3]=p,n[v>>3]=w)}}else i[e>>2]=0,i[e+4>>2]=0,i[e+8>>2]=0,i[e+12>>2]=0,i[e+16>>2]=0,i[e+20>>2]=0,i[e+24>>2]=0,i[e+28>>2]=0;if(!((0|(t=0|i[(y=A+8|0)>>2]))<=0)){r=A+12|0,Q=0;do{if(a=0|i[r>>2],o=Q,v=e+((Q=Q+1|0)<<5)|0,m=0|i[a+(o<<3)>>2]){if(n[(k=e+(Q<<5)+8|0)>>3]=17976931348623157e292,n[(A=e+(Q<<5)+24|0)>>3]=17976931348623157e292,n[v>>3]=-17976931348623157e292,n[(M=e+(Q<<5)+16|0)>>3]=-17976931348623157e292,(0|m)>0){for(B=0|i[a+(o<<3)+4>>2],w=17976931348623157e292,p=-17976931348623157e292,a=0,o=-1,b=0,h=17976931348623157e292,c=17976931348623157e292,d=-17976931348623157e292,u=-17976931348623157e292;s=+n[B+(b<<4)>>3],g=+n[B+(b<<4)+8>>3],l=+n[B+(((0|(o=o+2|0))==(0|m)?0:o)<<4)+8>>3],s>3]=s,h=s),g>3]=g,c=g),s>d?n[v>>3]=s:s=d,g>u&&(n[M>>3]=g,u=g),w=g>0&gp?g:p,a|=+f(+(g-l))>3.141592653589793,(0|(o=b+1|0))!=(0|m);)E=b,b=o,d=s,o=E;a&&(n[M>>3]=p,n[A>>3]=w)}}else i[v>>2]=0,i[v+4>>2]=0,i[v+8>>2]=0,i[v+12>>2]=0,i[v+16>>2]=0,i[v+20>>2]=0,i[v+24>>2]=0,i[v+28>>2]=0,t=0|i[y>>2]}while((0|Q)<(0|t))}}function ne(A,e,r){var t=0,n=0,o=0;if(!(0|re(A|=0,e|=0,r|=0)))return 0|(n=0);if((0|i[(n=A+8|0)>>2])<=0)return 0|(n=1);for(t=A+12|0,A=0;;){if(o=A,A=A+1|0,0|re((0|i[t>>2])+(o<<3)|0,e+(A<<5)|0,r)){A=0,t=6;break}if((0|A)>=(0|i[n>>2])){A=1,t=6;break}}return 6==(0|t)?0|A:0}function oe(A,e,r,t,i){e|=0,r|=0,t|=0,i|=0;var o,a,f,s,u,l,h,c=0;s=+n[(A|=0)>>3],f=+n[e>>3]-s,a=+n[A+8>>3],o=+n[e+8>>3]-a,l=+n[r>>3],c=((c=+n[t>>3]-l)*(a-(h=+n[r+8>>3]))-(s-l)*(u=+n[t+8>>3]-h))/(f*u-o*c),n[i>>3]=s+f*c,n[i+8>>3]=a+o*c}function ae(A,e){return e|=0,+n[(A|=0)>>3]!=+n[e>>3]?0|(e=0):0|(e=+n[A+8>>3]==+n[e+8>>3])}function fe(A,e){e|=0;var r,t,i;return+((i=+n[(A|=0)>>3]-+n[e>>3])*i+(t=+n[A+8>>3]-+n[e+8>>3])*t+(r=+n[A+16>>3]-+n[e+16>>3])*r)}function se(A,e,r){A|=0,r|=0;var t=0;(0|(e|=0))>0?(t=0|be(e,4),i[A>>2]=t,t||Q(23230,23253,40,23267)):i[A>>2]=0,i[A+4>>2]=e,i[A+8>>2]=0,i[A+12>>2]=r}function ue(A){var e,r,t,o=0,a=0,s=0,l=0;e=(A|=0)+4|0,r=A+12|0,t=A+8|0;A:for(;;){for(a=0|i[e>>2],o=0;;){if((0|o)>=(0|a))break A;if(s=0|i[A>>2],l=0|i[s+(o<<2)>>2])break;o=o+1|0}o=s+(~~(+f(+ +u(10,+ +(15-(0|i[r>>2])|0))*(+n[l>>3]+ +n[l+8>>3]))%+(0|a))>>>0<<2)|0,a=0|i[o>>2];e:do{if(0|a){if(s=l+32|0,(0|a)==(0|l))i[o>>2]=i[s>>2];else{if(!(o=0|i[(a=a+32|0)>>2]))break;for(;(0|o)!=(0|l);)if(!(o=0|i[(a=o+32|0)>>2]))break e;i[a>>2]=i[s>>2]}Be(l),i[t>>2]=(0|i[t>>2])-1}}while(0)}Be(0|i[A>>2])}function le(A){var e,r=0,t=0;for(e=0|i[(A|=0)+4>>2],t=0;;){if((0|t)>=(0|e)){r=0,t=4;break}if(r=0|i[(0|i[A>>2])+(t<<2)>>2]){t=4;break}t=t+1|0}return 4==(0|t)?0|r:0}function he(A,e){e|=0;var r=0,t=0,o=0,a=0;if(r=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,r=(0|i[A>>2])+(r<<2)|0,!(t=0|i[r>>2]))return 0|(a=1);a=e+32|0;do{if((0|t)!=(0|e)){if(!(r=0|i[t+32>>2]))return 0|(a=1);for(o=r;;){if((0|o)==(0|e)){o=8;break}if(!(r=0|i[o+32>>2])){r=1,o=10;break}t=o,o=r}if(8==(0|o)){i[t+32>>2]=i[a>>2];break}if(10==(0|o))return 0|r}else i[r>>2]=i[a>>2]}while(0);return Be(e),i[(a=A+8|0)>>2]=(0|i[a>>2])-1,0|(a=0)}function ce(A,e,r){A|=0,e|=0,r|=0;var t,o=0,a=0,s=0;(t=0|pe(40))||Q(23283,23253,98,23296),i[t>>2]=i[e>>2],i[t+4>>2]=i[e+4>>2],i[t+8>>2]=i[e+8>>2],i[t+12>>2]=i[e+12>>2],i[(a=t+16|0)>>2]=i[r>>2],i[a+4>>2]=i[r+4>>2],i[a+8>>2]=i[r+8>>2],i[a+12>>2]=i[r+12>>2],i[t+32>>2]=0,a=~~(+f(+ +u(10,+ +(15-(0|i[A+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,a=(0|i[A>>2])+(a<<2)|0,o=0|i[a>>2];do{if(o){for(;!(0|xA(o,e)&&0|xA(o+16|0,r));)if(a=0|i[o+32>>2],!(0|i[(o=0==(0|a)?o:a)+32>>2])){s=10;break}if(10==(0|s)){i[o+32>>2]=t;break}return Be(t),0|(s=o)}i[a>>2]=t}while(0);return i[(s=A+8|0)>>2]=1+(0|i[s>>2]),0|(s=t)}function de(A,e,r){e|=0,r|=0;var t=0,o=0;if(o=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,!(o=0|i[(0|i[A>>2])+(o<<2)>>2]))return 0|(r=0);if(!r){for(A=o;;){if(0|xA(A,e)){t=10;break}if(!(A=0|i[A+32>>2])){A=0,t=10;break}}if(10==(0|t))return 0|A}for(A=o;;){if(0|xA(A,e)&&0|xA(A+16|0,r)){t=10;break}if(!(A=0|i[A+32>>2])){A=0,t=10;break}}return 10==(0|t)?0|A:0}function ge(A,e){e|=0;var r=0;if(r=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,!(A=0|i[(0|i[A>>2])+(r<<2)>>2]))return 0|(r=0);for(;;){if(0|xA(A,e)){e=5;break}if(!(A=0|i[A+32>>2])){A=0,e=5;break}}return 5==(0|e)?0|A:0}function we(A){return 0|~~+function(A){return+ +Ie(+(A=+A))}(A=+A)}function pe(A){A|=0;var e,r=0,t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0;e=I,I=I+16|0,d=e;do{if(A>>>0<245){if(A=(l=A>>>0<11?16:A+11&-8)>>>3,3&(t=(c=0|i[5829])>>>A)|0)return n=0|i[(t=(A=23356+((r=(1&t^1)+A|0)<<1<<2)|0)+8|0)>>2],(0|(a=0|i[(o=n+8|0)>>2]))==(0|A)?i[5829]=c&~(1<>2]=A,i[t>>2]=a),k=r<<3,i[n+4>>2]=3|k,i[(k=n+k+4|0)>>2]=1|i[k>>2],I=e,0|(k=o);if(l>>>0>(h=0|i[5831])>>>0){if(0|t)return r=((r=t<>>=s=r>>>12&16)>>>5&8)|s|(a=(r>>>=t)>>>2&4)|(A=(r>>>=a)>>>1&2)|(n=(r>>>=A)>>>1&1))+(r>>>n)|0)<<1<<2)|0)+8|0)>>2],(0|(t=0|i[(s=a+8|0)>>2]))==(0|r)?(A=c&~(1<>2]=r,i[A>>2]=t,A=c),f=(k=n<<3)-l|0,i[a+4>>2]=3|l,i[(o=a+l|0)+4>>2]=1|f,i[a+k>>2]=f,0|h&&(n=0|i[5834],t=23356+((r=h>>>3)<<1<<2)|0,A&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=n,i[r+12>>2]=n,i[n+8>>2]=r,i[n+12>>2]=t),i[5831]=f,i[5834]=o,I=e,0|(k=s);if(a=0|i[5830]){for(t=(a&0-a)-1|0,t=u=0|i[23620+(((n=(t>>>=o=t>>>12&16)>>>5&8)|o|(f=(t>>>=n)>>>2&4)|(s=(t>>>=f)>>>1&2)|(u=(t>>>=s)>>>1&1))+(t>>>u)<<2)>>2],s=u,u=(-8&i[u+4>>2])-l|0;(A=0|i[t+16>>2])||(A=0|i[t+20>>2]);)t=A,s=(o=(f=(-8&i[A+4>>2])-l|0)>>>0>>0)?A:s,u=o?f:u;if((f=s+l|0)>>>0>s>>>0){o=0|i[s+24>>2],r=0|i[s+12>>2];do{if((0|r)==(0|s)){if(!(r=0|i[(A=s+20|0)>>2])&&!(r=0|i[(A=s+16|0)>>2])){t=0;break}for(;;)if(t=0|i[(n=r+20|0)>>2])r=t,A=n;else{if(!(t=0|i[(n=r+16|0)>>2]))break;r=t,A=n}i[A>>2]=0,t=r}else t=0|i[s+8>>2],i[t+12>>2]=r,i[r+8>>2]=t,t=r}while(0);do{if(0|o){if(r=0|i[s+28>>2],(0|s)==(0|i[(A=23620+(r<<2)|0)>>2])){if(i[A>>2]=t,!t){i[5830]=a&~(1<>2])==(0|s)?k:o+20|0)>>2]=t,!t)break;i[t+24>>2]=o,0|(r=0|i[s+16>>2])&&(i[t+16>>2]=r,i[r+24>>2]=t),0|(r=0|i[s+20>>2])&&(i[t+20>>2]=r,i[r+24>>2]=t)}}while(0);return u>>>0<16?(k=u+l|0,i[s+4>>2]=3|k,i[(k=s+k+4|0)>>2]=1|i[k>>2]):(i[s+4>>2]=3|l,i[f+4>>2]=1|u,i[f+u>>2]=u,0|h&&(n=0|i[5834],t=23356+((r=h>>>3)<<1<<2)|0,(r=1<>2]:(i[5829]=r|c,r=t,A=t+8|0),i[A>>2]=n,i[r+12>>2]=n,i[n+8>>2]=r,i[n+12>>2]=t),i[5831]=u,i[5834]=f),I=e,0|(k=s+8|0)}c=l}else c=l}else c=l}else if(A>>>0<=4294967231)if(l=-8&(A=A+11|0),n=0|i[5830]){o=0-l|0,u=(A>>>=8)?l>>>0>16777215?31:l>>>((u=14-((s=((p=A<<(c=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|c|(u=((p<<=s)+245760|0)>>>16&2))+(p<>>15)|0)+7|0)&1|u<<1:0,t=0|i[23620+(u<<2)>>2];A:do{if(t)for(A=0,s=l<<(31==(0|u)?0:25-(u>>>1)|0),a=0;;){if((f=(-8&i[t+4>>2])-l|0)>>>0>>0){if(!f){A=t,o=0,p=65;break A}A=t,o=f}if(a=0==(0|(p=0|i[t+20>>2]))|(0|p)==(0|(t=0|i[t+16+(s>>>31<<2)>>2]))?a:p,!t){t=a,p=61;break}s<<=1}else t=0,A=0,p=61}while(0);if(61==(0|p)){if(0==(0|t)&0==(0|A)){if(!(A=((A=2<>>=f=c>>>12&16)>>>5&8)|f|(s=(c>>>=a)>>>2&4)|(u=(c>>>=s)>>>1&2)|(t=(c>>>=u)>>>1&1))+(c>>>t)<<2)>>2]}t?p=65:(s=A,f=o)}if(65==(0|p))for(a=t;;){if(o=(t=(c=(-8&i[a+4>>2])-l|0)>>>0>>0)?c:o,A=t?a:A,(t=0|i[a+16>>2])||(t=0|i[a+20>>2]),!t){s=A,f=o;break}a=t}if(0!=(0|s)&&f>>>0<((0|i[5831])-l|0)>>>0&&(h=s+l|0)>>>0>s>>>0){a=0|i[s+24>>2],r=0|i[s+12>>2];do{if((0|r)==(0|s)){if(!(r=0|i[(A=s+20|0)>>2])&&!(r=0|i[(A=s+16|0)>>2])){r=0;break}for(;;)if(t=0|i[(o=r+20|0)>>2])r=t,A=o;else{if(!(t=0|i[(o=r+16|0)>>2]))break;r=t,A=o}i[A>>2]=0}else k=0|i[s+8>>2],i[k+12>>2]=r,i[r+8>>2]=k}while(0);do{if(a){if(A=0|i[s+28>>2],(0|s)==(0|i[(t=23620+(A<<2)|0)>>2])){if(i[t>>2]=r,!r){n&=~(1<>2])==(0|s)?k:a+20|0)>>2]=r,!r)break;i[r+24>>2]=a,0|(A=0|i[s+16>>2])&&(i[r+16>>2]=A,i[A+24>>2]=r),(A=0|i[s+20>>2])&&(i[r+20>>2]=A,i[A+24>>2]=r)}}while(0);A:do{if(f>>>0<16)k=f+l|0,i[s+4>>2]=3|k,i[(k=s+k+4|0)>>2]=1|i[k>>2];else{if(i[s+4>>2]=3|l,i[h+4>>2]=1|f,i[h+f>>2]=f,r=f>>>3,f>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=h,i[r+12>>2]=h,i[h+8>>2]=r,i[h+12>>2]=t;break}if(r=23620+((t=(r=f>>>8)?f>>>0>16777215?31:f>>>((t=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(t=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|t<<1:0)<<2)|0,i[h+28>>2]=t,i[(A=h+16|0)+4>>2]=0,i[A>>2]=0,!(n&(A=1<>2]=h,i[h+24>>2]=r,i[h+12>>2]=h,i[h+8>>2]=h;break}r=0|i[r>>2];e:do{if((-8&i[r+4>>2]|0)!=(0|f)){for(n=f<<(31==(0|t)?0:25-(t>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|f)){r=A;break e}n<<=1,r=A}i[t>>2]=h,i[h+24>>2]=r,i[h+12>>2]=h,i[h+8>>2]=h;break A}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=h,i[m>>2]=h,i[h+8>>2]=k,i[h+12>>2]=r,i[h+24>>2]=0}}while(0);return I=e,0|(k=s+8|0)}c=l}else c=l;else c=-1}while(0);if((t=0|i[5831])>>>0>=c>>>0)return r=t-c|0,A=0|i[5834],r>>>0>15?(k=A+c|0,i[5834]=k,i[5831]=r,i[k+4>>2]=1|r,i[A+t>>2]=r,i[A+4>>2]=3|c):(i[5831]=0,i[5834]=0,i[A+4>>2]=3|t,i[(k=A+t+4|0)>>2]=1|i[k>>2]),I=e,0|(k=A+8|0);if((f=0|i[5832])>>>0>c>>>0)return v=f-c|0,i[5832]=v,m=(k=0|i[5835])+c|0,i[5835]=m,i[m+4>>2]=1|v,i[k+4>>2]=3|c,I=e,0|(k=k+8|0);if(0|i[5947]?A=0|i[5949]:(i[5949]=4096,i[5948]=4096,i[5950]=-1,i[5951]=-1,i[5952]=0,i[5940]=0,i[5947]=-16&d^1431655768,A=4096),s=c+48|0,(l=(a=A+(u=c+47|0)|0)&(o=0-A|0))>>>0<=c>>>0)return I=e,0|(k=0);if(0|(A=0|i[5939])&&(d=(h=0|i[5937])+l|0)>>>0<=h>>>0|d>>>0>A>>>0)return I=e,0|(k=0);A:do{if(4&i[5940])r=0,p=143;else{t=0|i[5835];e:do{if(t){for(n=23764;!((d=0|i[n>>2])>>>0<=t>>>0&&(d+(0|i[n+4>>2])|0)>>>0>t>>>0);){if(!(A=0|i[n+8>>2])){p=128;break e}n=A}if((r=a-f&o)>>>0<2147483647)if((0|(A=0|Fe(0|r)))==((0|i[n>>2])+(0|i[n+4>>2])|0)){if(-1!=(0|A)){f=r,a=A,p=145;break A}}else n=A,p=136;else r=0}else p=128}while(0);do{if(128==(0|p))if(-1!=(0|(t=0|Fe(0)))&&(r=t,w=(r=(0==((w=(g=0|i[5948])+-1|0)&r|0)?0:(w+r&0-g)-r|0)+l|0)+(g=0|i[5937])|0,r>>>0>c>>>0&r>>>0<2147483647)){if(0|(d=0|i[5939])&&w>>>0<=g>>>0|w>>>0>d>>>0){r=0;break}if((0|(A=0|Fe(0|r)))==(0|t)){f=r,a=t,p=145;break A}n=A,p=136}else r=0}while(0);do{if(136==(0|p)){if(t=0-r|0,!(s>>>0>r>>>0&r>>>0<2147483647&-1!=(0|n))){if(-1==(0|n)){r=0;break}f=r,a=n,p=145;break A}if((A=u-r+(A=0|i[5949])&0-A)>>>0>=2147483647){f=r,a=n,p=145;break A}if(-1==(0|Fe(0|A))){Fe(0|t),r=0;break}f=A+r|0,a=n,p=145;break A}}while(0);i[5940]=4|i[5940],p=143}}while(0);if(143==(0|p)&&l>>>0<2147483647&&!(-1==(0|(v=0|Fe(0|l)))|1^(b=(B=(w=0|Fe(0))-v|0)>>>0>(c+40|0)>>>0)|v>>>0>>0&-1!=(0|v)&-1!=(0|w)^1)&&(f=b?B:r,a=v,p=145),145==(0|p)){r=(0|i[5937])+f|0,i[5937]=r,r>>>0>(0|i[5938])>>>0&&(i[5938]=r),u=0|i[5835];A:do{if(u){for(r=23764;;){if((0|a)==((A=0|i[r>>2])+(t=0|i[r+4>>2])|0)){p=154;break}if(!(n=0|i[r+8>>2]))break;r=n}if(154==(0|p)&&(m=r+4|0,0==(8&i[r+12>>2]|0))&&a>>>0>u>>>0&A>>>0<=u>>>0){i[m>>2]=t+f,m=u+(v=0==(7&(v=u+8|0)|0)?0:0-v&7)|0,v=(k=(0|i[5832])+f|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[u+k+4>>2]=40,i[5836]=i[5951];break}for(a>>>0<(0|i[5833])>>>0&&(i[5833]=a),t=a+f|0,r=23764;;){if((0|i[r>>2])==(0|t)){p=162;break}if(!(A=0|i[r+8>>2]))break;r=A}if(162==(0|p)&&0==(8&i[r+12>>2]|0)){i[r>>2]=a,i[(h=r+4|0)>>2]=(0|i[h>>2])+f,l=(h=a+(0==(7&(h=a+8|0)|0)?0:0-h&7)|0)+c|0,s=(r=t+(0==(7&(r=t+8|0)|0)?0:0-r&7)|0)-h-c|0,i[h+4>>2]=3|c;e:do{if((0|u)==(0|r))k=(0|i[5832])+s|0,i[5832]=k,i[5835]=l,i[l+4>>2]=1|k;else{if((0|i[5834])==(0|r)){k=(0|i[5831])+s|0,i[5831]=k,i[5834]=l,i[l+4>>2]=1|k,i[l+k>>2]=k;break}if(1==(3&(A=0|i[r+4>>2])|0)){f=-8&A,n=A>>>3;r:do{if(A>>>0<256){if(A=0|i[r+8>>2],(0|(t=0|i[r+12>>2]))==(0|A)){i[5829]=i[5829]&~(1<>2]=t,i[t+8>>2]=A;break}a=0|i[r+24>>2],A=0|i[r+12>>2];do{if((0|A)==(0|r)){if(A=0|i[(n=(t=r+16|0)+4|0)>>2])t=n;else if(!(A=0|i[t>>2])){A=0;break}for(;;)if(n=0|i[(o=A+20|0)>>2])A=n,t=o;else{if(!(n=0|i[(o=A+16|0)>>2]))break;A=n,t=o}i[t>>2]=0}else k=0|i[r+8>>2],i[k+12>>2]=A,i[A+8>>2]=k}while(0);if(!a)break;n=23620+((t=0|i[r+28>>2])<<2)|0;do{if((0|i[n>>2])==(0|r)){if(i[n>>2]=A,0|A)break;i[5830]=i[5830]&~(1<>2])==(0|r)?k:a+20|0)>>2]=A,!A)break r}while(0);if(i[A+24>>2]=a,0|(n=0|i[(t=r+16|0)>>2])&&(i[A+16>>2]=n,i[n+24>>2]=A),!(t=0|i[t+4>>2]))break;i[A+20>>2]=t,i[t+24>>2]=A}while(0);r=r+f|0,o=f+s|0}else o=s;if(i[(r=r+4|0)>>2]=-2&i[r>>2],i[l+4>>2]=1|o,i[l+o>>2]=o,r=o>>>3,o>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=l,i[r+12>>2]=l,i[l+8>>2]=r,i[l+12>>2]=t;break}r=o>>>8;do{if(r){if(o>>>0>16777215){n=31;break}n=o>>>((n=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(n=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|n<<1}else n=0}while(0);if(r=23620+(n<<2)|0,i[l+28>>2]=n,i[(A=l+16|0)+4>>2]=0,i[A>>2]=0,!((A=0|i[5830])&(t=1<>2]=l,i[l+24>>2]=r,i[l+12>>2]=l,i[l+8>>2]=l;break}r=0|i[r>>2];r:do{if((-8&i[r+4>>2]|0)!=(0|o)){for(n=o<<(31==(0|n)?0:25-(n>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|o)){r=A;break r}n<<=1,r=A}i[t>>2]=l,i[l+24>>2]=r,i[l+12>>2]=l,i[l+8>>2]=l;break e}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=l,i[m>>2]=l,i[l+8>>2]=k,i[l+12>>2]=r,i[l+24>>2]=0}}while(0);return I=e,0|(k=h+8|0)}for(r=23764;!((A=0|i[r>>2])>>>0<=u>>>0&&(k=A+(0|i[r+4>>2])|0)>>>0>u>>>0);)r=0|i[r+8>>2];r=(A=(A=(o=k+-47|0)+(0==(7&(A=o+8|0)|0)?0:0-A&7)|0)>>>0<(o=u+16|0)>>>0?u:A)+8|0,m=a+(v=0==(7&(v=a+8|0)|0)?0:0-v&7)|0,v=(t=f+-40|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[a+t+4>>2]=40,i[5836]=i[5951],i[(t=A+4|0)>>2]=27,i[r>>2]=i[5941],i[r+4>>2]=i[5942],i[r+8>>2]=i[5943],i[r+12>>2]=i[5944],i[5941]=a,i[5942]=f,i[5944]=0,i[5943]=r,r=A+24|0;do{m=r,i[(r=r+4|0)>>2]=7}while((m+8|0)>>>0>>0);if((0|A)!=(0|u)){if(a=A-u|0,i[t>>2]=-2&i[t>>2],i[u+4>>2]=1|a,i[A>>2]=a,r=a>>>3,a>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=u,i[r+12>>2]=u,i[u+8>>2]=r,i[u+12>>2]=t;break}if(t=23620+((n=(r=a>>>8)?a>>>0>16777215?31:a>>>((n=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(n=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|n<<1:0)<<2)|0,i[u+28>>2]=n,i[u+20>>2]=0,i[o>>2]=0,!((r=0|i[5830])&(A=1<>2]=u,i[u+24>>2]=t,i[u+12>>2]=u,i[u+8>>2]=u;break}r=0|i[t>>2];e:do{if((-8&i[r+4>>2]|0)!=(0|a)){for(n=a<<(31==(0|n)?0:25-(n>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|a)){r=A;break e}n<<=1,r=A}i[t>>2]=u,i[u+24>>2]=r,i[u+12>>2]=u,i[u+8>>2]=u;break A}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=u,i[m>>2]=u,i[u+8>>2]=k,i[u+12>>2]=r,i[u+24>>2]=0}}else 0==(0|(k=0|i[5833]))|a>>>0>>0&&(i[5833]=a),i[5941]=a,i[5942]=f,i[5944]=0,i[5838]=i[5947],i[5837]=-1,i[5842]=23356,i[5841]=23356,i[5844]=23364,i[5843]=23364,i[5846]=23372,i[5845]=23372,i[5848]=23380,i[5847]=23380,i[5850]=23388,i[5849]=23388,i[5852]=23396,i[5851]=23396,i[5854]=23404,i[5853]=23404,i[5856]=23412,i[5855]=23412,i[5858]=23420,i[5857]=23420,i[5860]=23428,i[5859]=23428,i[5862]=23436,i[5861]=23436,i[5864]=23444,i[5863]=23444,i[5866]=23452,i[5865]=23452,i[5868]=23460,i[5867]=23460,i[5870]=23468,i[5869]=23468,i[5872]=23476,i[5871]=23476,i[5874]=23484,i[5873]=23484,i[5876]=23492,i[5875]=23492,i[5878]=23500,i[5877]=23500,i[5880]=23508,i[5879]=23508,i[5882]=23516,i[5881]=23516,i[5884]=23524,i[5883]=23524,i[5886]=23532,i[5885]=23532,i[5888]=23540,i[5887]=23540,i[5890]=23548,i[5889]=23548,i[5892]=23556,i[5891]=23556,i[5894]=23564,i[5893]=23564,i[5896]=23572,i[5895]=23572,i[5898]=23580,i[5897]=23580,i[5900]=23588,i[5899]=23588,i[5902]=23596,i[5901]=23596,i[5904]=23604,i[5903]=23604,m=a+(v=0==(7&(v=a+8|0)|0)?0:0-v&7)|0,v=(k=f+-40|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[a+k+4>>2]=40,i[5836]=i[5951]}while(0);if((r=0|i[5832])>>>0>c>>>0)return v=r-c|0,i[5832]=v,m=(k=0|i[5835])+c|0,i[5835]=m,i[m+4>>2]=1|v,i[k+4>>2]=3|c,I=e,0|(k=k+8|0)}return i[(k=23312)>>2]=12,I=e,0|(k=0)}function Be(A){var e=0,r=0,t=0,n=0,o=0,a=0,f=0,s=0;if(A|=0){r=A+-8|0,n=0|i[5833],s=r+(e=-8&(A=0|i[A+-4>>2]))|0;do{if(1&A)f=r,a=r;else{if(t=0|i[r>>2],!(3&A))return;if(o=t+e|0,(a=r+(0-t)|0)>>>0>>0)return;if((0|i[5834])==(0|a)){if(3!=(3&(e=0|i[(A=s+4|0)>>2])|0)){f=a,e=o;break}return i[5831]=o,i[A>>2]=-2&e,i[a+4>>2]=1|o,void(i[a+o>>2]=o)}if(r=t>>>3,t>>>0<256){if(A=0|i[a+8>>2],(0|(e=0|i[a+12>>2]))==(0|A)){i[5829]=i[5829]&~(1<>2]=e,i[e+8>>2]=A,f=a,e=o;break}n=0|i[a+24>>2],A=0|i[a+12>>2];do{if((0|A)==(0|a)){if(A=0|i[(r=(e=a+16|0)+4|0)>>2])e=r;else if(!(A=0|i[e>>2])){A=0;break}for(;;)if(r=0|i[(t=A+20|0)>>2])A=r,e=t;else{if(!(r=0|i[(t=A+16|0)>>2]))break;A=r,e=t}i[e>>2]=0}else f=0|i[a+8>>2],i[f+12>>2]=A,i[A+8>>2]=f}while(0);if(n){if(e=0|i[a+28>>2],(0|i[(r=23620+(e<<2)|0)>>2])==(0|a)){if(i[r>>2]=A,!A){i[5830]=i[5830]&~(1<>2])==(0|a)?f:n+20|0)>>2]=A,!A){f=a,e=o;break}i[A+24>>2]=n,0|(r=0|i[(e=a+16|0)>>2])&&(i[A+16>>2]=r,i[r+24>>2]=A),(e=0|i[e+4>>2])?(i[A+20>>2]=e,i[e+24>>2]=A,f=a,e=o):(f=a,e=o)}else f=a,e=o}}while(0);if(!(a>>>0>=s>>>0)&&1&(t=0|i[(A=s+4|0)>>2])){if(2&t)i[A>>2]=-2&t,i[f+4>>2]=1|e,i[a+e>>2]=e,n=e;else{if((0|i[5835])==(0|s)){if(s=(0|i[5832])+e|0,i[5832]=s,i[5835]=f,i[f+4>>2]=1|s,(0|f)!=(0|i[5834]))return;return i[5834]=0,void(i[5831]=0)}if((0|i[5834])==(0|s))return s=(0|i[5831])+e|0,i[5831]=s,i[5834]=a,i[f+4>>2]=1|s,void(i[a+s>>2]=s);n=(-8&t)+e|0,r=t>>>3;do{if(t>>>0<256){if(e=0|i[s+8>>2],(0|(A=0|i[s+12>>2]))==(0|e)){i[5829]=i[5829]&~(1<>2]=A,i[A+8>>2]=e;break}o=0|i[s+24>>2],A=0|i[s+12>>2];do{if((0|A)==(0|s)){if(A=0|i[(r=(e=s+16|0)+4|0)>>2])e=r;else if(!(A=0|i[e>>2])){r=0;break}for(;;)if(r=0|i[(t=A+20|0)>>2])A=r,e=t;else{if(!(r=0|i[(t=A+16|0)>>2]))break;A=r,e=t}i[e>>2]=0,r=A}else r=0|i[s+8>>2],i[r+12>>2]=A,i[A+8>>2]=r,r=A}while(0);if(0|o){if(A=0|i[s+28>>2],(0|i[(e=23620+(A<<2)|0)>>2])==(0|s)){if(i[e>>2]=r,!r){i[5830]=i[5830]&~(1<>2])==(0|s)?t:o+20|0)>>2]=r,!r)break;i[r+24>>2]=o,0|(e=0|i[(A=s+16|0)>>2])&&(i[r+16>>2]=e,i[e+24>>2]=r),0|(A=0|i[A+4>>2])&&(i[r+20>>2]=A,i[A+24>>2]=r)}}while(0);if(i[f+4>>2]=1|n,i[a+n>>2]=n,(0|f)==(0|i[5834]))return void(i[5831]=n)}if(A=n>>>3,n>>>0<256)return r=23356+(A<<1<<2)|0,(e=0|i[5829])&(A=1<>2]:(i[5829]=e|A,A=r,e=r+8|0),i[e>>2]=f,i[A+12>>2]=f,i[f+8>>2]=A,void(i[f+12>>2]=r);A=23620+((t=(A=n>>>8)?n>>>0>16777215?31:n>>>((t=14-((o=((s=A<<(a=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|a|(t=((s<<=o)+245760|0)>>>16&2))+(s<>>15)|0)+7|0)&1|t<<1:0)<<2)|0,i[f+28>>2]=t,i[f+20>>2]=0,i[f+16>>2]=0,e=0|i[5830],r=1<>2];e:do{if((-8&i[A+4>>2]|0)!=(0|n)){for(t=n<<(31==(0|t)?0:25-(t>>>1)|0);e=0|i[(r=A+16+(t>>>31<<2)|0)>>2];){if((-8&i[e+4>>2]|0)==(0|n)){A=e;break e}t<<=1,A=e}i[r>>2]=f,i[f+24>>2]=A,i[f+12>>2]=f,i[f+8>>2]=f;break A}}while(0);s=0|i[(a=A+8|0)>>2],i[s+12>>2]=f,i[a>>2]=f,i[f+8>>2]=s,i[f+12>>2]=A,i[f+24>>2]=0}else i[5830]=e|r,i[A>>2]=f,i[f+24>>2]=A,i[f+12>>2]=f,i[f+8>>2]=f}while(0);if(s=(0|i[5837])-1|0,i[5837]=s,!(0|s)){for(A=23772;A=0|i[A>>2];)A=A+8|0;i[5837]=-1}}}}function be(A,e){e|=0;var r=0;return(A|=0)?(r=0|b(e,A),(e|A)>>>0>65535&&(r=(0|(r>>>0)/(A>>>0))==(0|e)?r:-1)):r=0,(A=0|pe(r))&&3&i[A+-4>>2]?(_e(0|A,0,0|r),0|A):0|A}function ve(A,e,r,t){return 0|(k(0|(t=(e|=0)-(t|=0)-((r|=0)>>>0>(A|=0)>>>0|0)>>>0)),A-r>>>0|0)}function me(A){return 0|((A|=0)?31-(0|m(A^A-1))|0:32)}function ke(A,e,r,t,n){n|=0;var o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0;if(l=A|=0,a=r|=0,f=c=t|=0,!(u=s=e|=0))return o=0!=(0|n),f?o?(i[n>>2]=0|A,i[n+4>>2]=0&e,n=0,0|(k(0|(c=0)),n)):(n=0,0|(k(0|(c=0)),n)):(o&&(i[n>>2]=(l>>>0)%(a>>>0),i[n+4>>2]=0),n=(l>>>0)/(a>>>0)>>>0,0|(k(0|(c=0)),n));o=0==(0|f);do{if(a){if(!o){if((o=(0|m(0|f))-(0|m(0|u))|0)>>>0<=31){a=h=o+1|0,A=l>>>(h>>>0)&(e=o-31>>31)|u<<(f=31-o|0),e&=u>>>(h>>>0),o=0,f=l<>2]=0|A,i[n+4>>2]=s|0&e,n=0,0|(k(0|(c=0)),n)):(n=0,0|(k(0|(c=0)),n))}if((o=a-1|0)&a|0){a=f=33+(0|m(0|a))-(0|m(0|u))|0,A=(h=32-f|0)-1>>31&u>>>((d=f-32|0)>>>0)|(u<>>(f>>>0))&(e=d>>31),e&=u>>>(f>>>0),o=l<<(g=64-f|0)&(s=h>>31),f=(u<>>(d>>>0))&s|l<>31;break}return 0|n&&(i[n>>2]=o&l,i[n+4>>2]=0),1==(0|a)?(g=0|A,0|(k(0|(d=s|0&e)),g)):(d=u>>>((g=0|me(0|a))>>>0)|0,g=u<<32-g|l>>>(g>>>0)|0,0|(k(0|d),g))}if(o)return 0|n&&(i[n>>2]=(u>>>0)%(a>>>0),i[n+4>>2]=0),g=(u>>>0)/(a>>>0)>>>0,0|(k(0|(d=0)),g);if(!l)return 0|n&&(i[n>>2]=0,i[n+4>>2]=(u>>>0)%(f>>>0)),g=(u>>>0)/(f>>>0)>>>0,0|(k(0|(d=0)),g);if(!((o=f-1|0)&f))return 0|n&&(i[n>>2]=0|A,i[n+4>>2]=o&u|0&e),d=0,g=u>>>((0|me(0|f))>>>0),0|(k(0|d),g);if((o=(0|m(0|f))-(0|m(0|u))|0)>>>0<=30){a=e=o+1|0,A=u<<(f=31-o|0)|l>>>(e>>>0),e=u>>>(e>>>0),o=0,f=l<>2]=0|A,i[n+4>>2]=s|0&e,g=0,0|(k(0|(d=0)),g)):(g=0,0|(k(0|(d=0)),g))}while(0);if(a){u=0|function(A,e,r,t){return 0|(k((e|=0)+(t|=0)+((r=(A|=0)+(r|=0)>>>0)>>>0>>0|0)>>>0|0),0|r)}(0|(h=0|r),0|(l=c|0&t),-1,-1),r=0|M(),s=f,f=0;do{t=s,s=o>>>31|s<<1,o=f|o<<1,ve(0|u,0|r,0|(t=A<<1|t>>>31|0),0|(c=A>>>31|e<<1|0)),f=1&(d=(g=0|M())>>31|((0|g)<0?-1:0)<<1),A=0|ve(0|t,0|c,d&h|0,(((0|g)<0?-1:0)>>31|((0|g)<0?-1:0)<<1)&l|0),e=0|M(),a=a-1|0}while(0!=(0|a));u=s,s=0}else u=f,s=0,f=0;return a=0,0|n&&(i[n>>2]=A,i[n+4>>2]=e),g=-2&(o<<1|0)|f,0|(k(0|(d=(0|o)>>>31|(u|a)<<1|0&(a<<1|o>>>31)|s)),g)}function Me(A,e,r,t){var n,o;return o=I,I=I+16|0,ke(A|=0,e|=0,r|=0,t|=0,n=0|o),I=o,0|(k(0|i[n+4>>2]),0|i[n>>2])}function Qe(A,e,r){return A|=0,e|=0,(0|(r|=0))<32?(k(e>>>r|0),A>>>r|(e&(1<>>r-32|0)}function ye(A,e,r){return A|=0,e|=0,(0|(r|=0))<32?(k(e<>>32-r|0),A<=0?+a(A+.5):+B(A-.5)}function De(A,e,r){A|=0,e|=0;var n,o,a=0;if((0|(r|=0))>=8192)return x(0|A,0|e,0|r),0|A;if(o=0|A,n=A+r|0,(3&A)==(3&e)){for(;3&A;){if(!r)return 0|o;t[A>>0]=0|t[e>>0],A=A+1|0,e=e+1|0,r=r-1|0}for(a=(r=-4&n|0)-64|0;(0|A)<=(0|a);)i[A>>2]=i[e>>2],i[A+4>>2]=i[e+4>>2],i[A+8>>2]=i[e+8>>2],i[A+12>>2]=i[e+12>>2],i[A+16>>2]=i[e+16>>2],i[A+20>>2]=i[e+20>>2],i[A+24>>2]=i[e+24>>2],i[A+28>>2]=i[e+28>>2],i[A+32>>2]=i[e+32>>2],i[A+36>>2]=i[e+36>>2],i[A+40>>2]=i[e+40>>2],i[A+44>>2]=i[e+44>>2],i[A+48>>2]=i[e+48>>2],i[A+52>>2]=i[e+52>>2],i[A+56>>2]=i[e+56>>2],i[A+60>>2]=i[e+60>>2],A=A+64|0,e=e+64|0;for(;(0|A)<(0|r);)i[A>>2]=i[e>>2],A=A+4|0,e=e+4|0}else for(r=n-4|0;(0|A)<(0|r);)t[A>>0]=0|t[e>>0],t[A+1>>0]=0|t[e+1>>0],t[A+2>>0]=0|t[e+2>>0],t[A+3>>0]=0|t[e+3>>0],A=A+4|0,e=e+4|0;for(;(0|A)<(0|n);)t[A>>0]=0|t[e>>0],A=A+1|0,e=e+1|0;return 0|o}function _e(A,e,r){e|=0;var n,o=0,a=0,f=0;if(n=(A|=0)+(r|=0)|0,e&=255,(0|r)>=67){for(;3&A;)t[A>>0]=e,A=A+1|0;for(f=e|e<<8|e<<16|e<<24,a=(o=-4&n|0)-64|0;(0|A)<=(0|a);)i[A>>2]=f,i[A+4>>2]=f,i[A+8>>2]=f,i[A+12>>2]=f,i[A+16>>2]=f,i[A+20>>2]=f,i[A+24>>2]=f,i[A+28>>2]=f,i[A+32>>2]=f,i[A+36>>2]=f,i[A+40>>2]=f,i[A+44>>2]=f,i[A+48>>2]=f,i[A+52>>2]=f,i[A+56>>2]=f,i[A+60>>2]=f,A=A+64|0;for(;(0|A)<(0|o);)i[A>>2]=f,A=A+4|0}for(;(0|A)<(0|n);)t[A>>0]=e,A=A+1|0;return n-r|0}function Ie(A){return(A=+A)>=0?+a(A+.5):+B(A-.5)}function Fe(A){A|=0;var e,r,t;return t=0|E(),(0|A)>0&(0|(e=(r=0|i[o>>2])+A|0))<(0|r)|(0|e)<0?(_(0|e),y(12),-1):(0|e)>(0|t)&&!(0|D(0|e))?(y(12),-1):(i[o>>2]=e,0|r)}return{___uremdi3:Me,_bitshift64Lshr:Qe,_bitshift64Shl:ye,_calloc:be,_cellAreaKm2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))>0){if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1!=(0|e)){A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e))}}else o=0;return I=n,6371.007180918475*o*6371.007180918475},_cellAreaM2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))>0){if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1!=(0|e)){A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e))}}else o=0;return I=n,6371.007180918475*o*6371.007180918475*1e3*1e3},_cellAreaRads2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))<=0)return I=n,+(o=0);if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1==(0|e))return I=n,+o;A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e));return I=n,+o},_compact:function(A,e,r){e|=0;var t,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,Q=0,y=0,E=0;if(!(r|=0))return 0|(y=0);if(n=0|i[(o=A|=0)>>2],!0&0==(15728640&(o=0|i[o+4>>2])|0)){if((0|r)<=0)return 0|(y=0);if(i[(y=e)>>2]=n,i[y+4>>2]=o,1==(0|r))return 0|(y=0);n=1;do{Q=0|i[(k=A+(n<<3)|0)+4>>2],i[(y=e+(n<<3)|0)>>2]=i[k>>2],i[y+4>>2]=Q,n=n+1|0}while((0|n)!=(0|r));return 0|(n=0)}if(!(Q=0|pe(k=r<<3)))return 0|(y=-3);if(De(0|Q,0|A,0|k),!(t=0|be(r,8)))return Be(Q),0|(y=-3);n=r;A:for(;;){v=0|Qe(0|(h=0|i[(f=Q)>>2]),0|(f=0|i[f+4>>2]),52),M(),m=(v&=15)+-1|0,b=(0|n)>0;e:do{if(b){if(B=((0|n)<0)<<31>>31,w=0|ye(0|m,0,52),p=0|M(),m>>>0>15)for(o=0,A=h,r=f;;){if(!(0==(0|A)&0==(0|r))){if(a=0|Qe(0|A,0|r,52),M(),s=(0|(a&=15))<(0|m),a=(0|a)==(0|m),r=0|Me(0|(l=s?0:a?A:0),0|(A=s?0:a?r:0),0|n,0|B),M(),0==(0|(u=0|i[(s=a=t+(r<<3)|0)>>2]))&0==(0|(s=0|i[s+4>>2])))r=l;else for(w=0,g=r,d=s,r=l;;){if((0|w)>(0|n)){y=41;break A}if((0|u)==(0|r)&(-117440513&d|0)==(0|A)){l=0|Qe(0|u,0|d,56),M(),c=(l&=7)+1|0,p=0|Qe(0|u,0|d,45),M();r:do{if(0|S(127&p)){if(u=0|Qe(0|u,0|d,52),M(),!(u&=15)){s=6;break}for(s=1;;){if(!(0==((p=0|ye(7,0,3*(15-s|0)|0))&r|0)&0==((0|M())&A|0))){s=7;break r}if(!(s>>>0>>0)){s=6;break}s=s+1|0}}else s=7}while(0);if((l+2|0)>>>0>s>>>0){y=51;break A}p=0|ye(0|c,0,56),A=0|M()|-117440513&A,i[(s=a)>>2]=0,i[s+4>>2]=0,s=g,r|=p}else s=(g+1|0)%(0|n)|0;if(0==(0|(u=0|i[(d=a=t+(s<<3)|0)>>2]))&0==(0|(d=0|i[d+4>>2])))break;w=w+1|0,g=s}i[(p=a)>>2]=r,i[p+4>>2]=A}if((0|(o=o+1|0))>=(0|n))break e;A=0|i[(r=Q+(o<<3)|0)>>2],r=0|i[r+4>>2]}for(o=0,A=h,r=f;;){if(!(0==(0|A)&0==(0|r))){if(s=0|Qe(0|A,0|r,52),M(),(0|(s&=15))>=(0|m)){if((0|s)!=(0|m)&&(A|=w,r=-15728641&r|p,s>>>0>=v>>>0)){a=m;do{g=0|ye(7,0,3*(14-a|0)|0),a=a+1|0,A|=g,r=0|M()|r}while(a>>>0>>0)}}else A=0,r=0;if(s=0|Me(0|A,0|r,0|n,0|B),M(),!(0==(0|(l=0|i[(u=a=t+(s<<3)|0)>>2]))&0==(0|(u=0|i[u+4>>2]))))for(g=0;;){if((0|g)>(0|n)){y=41;break A}if((0|l)==(0|A)&(-117440513&u|0)==(0|r)){c=0|Qe(0|l,0|u,56),M(),d=(c&=7)+1|0,E=0|Qe(0|l,0|u,45),M();r:do{if(0|S(127&E)){if(l=0|Qe(0|l,0|u,52),M(),!(l&=15)){u=6;break}for(u=1;;){if(!(0==((E=0|ye(7,0,3*(15-u|0)|0))&A|0)&0==((0|M())&r|0))){u=7;break r}if(!(u>>>0>>0)){u=6;break}u=u+1|0}}else u=7}while(0);if((c+2|0)>>>0>u>>>0){y=51;break A}E=0|ye(0|d,0,56),r=0|M()|-117440513&r,i[(d=a)>>2]=0,i[d+4>>2]=0,A|=E}else s=(s+1|0)%(0|n)|0;if(0==(0|(l=0|i[(u=a=t+(s<<3)|0)>>2]))&0==(0|(u=0|i[u+4>>2])))break;g=g+1|0}i[(E=a)>>2]=A,i[E+4>>2]=r}if((0|(o=o+1|0))>=(0|n))break e;A=0|i[(r=Q+(o<<3)|0)>>2],r=0|i[r+4>>2]}}}while(0);if((n+5|0)>>>0<11){y=99;break}if(!(p=0|be((0|n)/6|0,8))){y=58;break}e:do{if(b){g=0,d=0;do{if(!(0==(0|(o=0|i[(A=s=t+(g<<3)|0)>>2]))&0==(0|(A=0|i[A+4>>2])))){u=0|Qe(0|o,0|A,56),M(),r=(u&=7)+1|0,l=-117440513&A,E=0|Qe(0|o,0|A,45),M();r:do{if(0|S(127&E)){if(c=0|Qe(0|o,0|A,52),M(),0|(c&=15))for(a=1;;){if(!(0==(o&(E=0|ye(7,0,3*(15-a|0)|0))|0)&0==(l&(0|M())|0)))break r;if(!(a>>>0>>0))break;a=a+1|0}o|=A=0|ye(0|r,0,56),A=0|M()|l,i[(r=s)>>2]=o,i[r+4>>2]=A,r=u+2|0}}while(0);7==(0|r)&&(i[(E=p+(d<<3)|0)>>2]=o,i[E+4>>2]=-117440513&A,d=d+1|0)}g=g+1|0}while((0|g)!=(0|n));if(b){if(w=((0|n)<0)<<31>>31,c=0|ye(0|m,0,52),g=0|M(),m>>>0>15)for(A=0,o=0;;){do{if(!(0==(0|h)&0==(0|f))){for(u=0|Qe(0|h,0|f,52),M(),a=(0|(u&=15))<(0|m),u=(0|u)==(0|m),a=0|Me(0|(s=a?0:u?h:0),0|(u=a?0:u?f:0),0|n,0|w),M(),r=0;;){if((0|r)>(0|n)){y=98;break A}if((-117440513&(l=0|i[(E=t+(a<<3)|0)+4>>2])|0)==(0|u)&&(0|i[E>>2])==(0|s)){y=70;break}if((0|i[(E=t+((a=(a+1|0)%(0|n)|0)<<3)|0)>>2])==(0|s)&&(0|i[E+4>>2])==(0|u))break;r=r+1|0}if(70==(0|y)&&(y=0,!0&100663296==(117440512&l|0)))break;i[(E=e+(o<<3)|0)>>2]=h,i[E+4>>2]=f,o=o+1|0}}while(0);if((0|(A=A+1|0))>=(0|n)){n=d;break e}h=0|i[(f=Q+(A<<3)|0)>>2],f=0|i[f+4>>2]}for(A=0,o=0;;){do{if(!(0==(0|h)&0==(0|f))){if(u=0|Qe(0|h,0|f,52),M(),(0|(u&=15))>=(0|m))if((0|u)!=(0|m))if(r=h|c,a=-15728641&f|g,u>>>0>>0)u=a;else{s=m;do{E=0|ye(7,0,3*(14-s|0)|0),s=s+1|0,r|=E,a=0|M()|a}while(s>>>0>>0);u=a}else r=h,u=f;else r=0,u=0;for(s=0|Me(0|r,0|u,0|n,0|w),M(),a=0;;){if((0|a)>(0|n)){y=98;break A}if((-117440513&(l=0|i[(E=t+(s<<3)|0)+4>>2])|0)==(0|u)&&(0|i[E>>2])==(0|r)){y=93;break}if((0|i[(E=t+((s=(s+1|0)%(0|n)|0)<<3)|0)>>2])==(0|r)&&(0|i[E+4>>2])==(0|u))break;a=a+1|0}if(93==(0|y)&&(y=0,!0&100663296==(117440512&l|0)))break;i[(E=e+(o<<3)|0)>>2]=h,i[E+4>>2]=f,o=o+1|0}}while(0);if((0|(A=A+1|0))>=(0|n)){n=d;break e}h=0|i[(f=Q+(A<<3)|0)>>2],f=0|i[f+4>>2]}}else o=0,n=d}else o=0,n=0}while(0);if(_e(0|t,0,0|k),De(0|Q,0|p,n<<3|0),Be(p),!n)break;e=e+(o<<3)|0}return 41==(0|y)?(Be(Q),Be(t),0|(E=-1)):51==(0|y)?(Be(Q),Be(t),0|(E=-2)):58==(0|y)?(Be(Q),Be(t),0|(E=-3)):98==(0|y)?(Be(p),Be(Q),Be(t),0|(E=-1)):(99==(0|y)&&De(0|e,0|Q,n<<3|0),Be(Q),Be(t),0|(E=0))},_destroyLinkedPolygon:function(A){var e=0,r=0,t=0,n=0;if(A|=0)for(t=1;;){if(0|(e=0|i[A>>2]))do{if(0|(r=0|i[e>>2]))do{n=r,r=0|i[r+16>>2],Be(n)}while(0!=(0|r));n=e,e=0|i[e+8>>2],Be(n)}while(0!=(0|e));if(e=A,A=0|i[A+8>>2],t||Be(e),!A)break;t=0}},_edgeLengthKm:function(A){return+ +n[20752+((A|=0)<<3)>>3]},_edgeLengthM:function(A){return+ +n[20880+((A|=0)<<3)>>3]},_emscripten_replace_memory:function(A){return t=new Int8Array(A),new Uint8Array(A),i=new Int32Array(A),new Float32Array(A),n=new Float64Array(A),r=A,!0},_exactEdgeLengthKm:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+c)*+l(+a)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)!=(0|e));return I=t,+(d=6371.007180918475*o)},_exactEdgeLengthM:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+c)*+l(+a)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)!=(0|e));return I=t,+(d=6371.007180918475*o*1e3)},_exactEdgeLengthRads:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+a)*+l(+c)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)<(0|e));return I=t,+o},_experimentalH3ToLocalIj:function(A,e,r,t,i){var n,o;return i|=0,o=I,I=I+16|0,(A=0|$A(A|=0,e|=0,r|=0,t|=0,n=o))||(cA(n,i),A=0),I=o,0|A},_experimentalLocalIjToH3:function(A,e,r,t){var i,n;return A|=0,e|=0,t|=0,i=I,I=I+16|0,dA(r|=0,n=i),t=0|Ae(A,e,n,t),I=i,0|t},_free:Be,_geoToH3:LA,_getDestinationH3IndexFromUnidirectionalEdge:function(A,e){A|=0;var r,t,n=0;return r=I,I=I+16|0,n=r,!0&268435456==(2013265920&(e|=0)|0)?(t=0|Qe(0|A,0|e,56),M(),i[n>>2]=0,n=0|U(A,-2130706433&e|134217728,7&t,n),e=0|M(),k(0|e),I=r,0|n):(n=0,k(0|(e=0)),I=r,0|n)},_getH3IndexesFromUnidirectionalEdge:function(A,e,r){A|=0;var t,n,o,a,f=0;o=I,I=I+16|0,t=o,a=!0&268435456==(2013265920&(e|=0)|0),n=-2130706433&e|134217728,i[(f=r|=0)>>2]=a?A:0,i[f+4>>2]=a?n:0,a?(e=0|Qe(0|A,0|e,56),M(),i[t>>2]=0,A=0|U(A,n,7&e,t),e=0|M()):(A=0,e=0),i[(f=r+8|0)>>2]=A,i[f+4>>2]=e,I=o},_getH3UnidirectionalEdge:function(A,e,r,t){var n,o,a=0,f=0,s=0,u=0,l=0;if(o=I,I=I+16|0,n=o,!(0|ZA(A|=0,e|=0,r|=0,t|=0)))return u=0,k(0|(s=0)),I=o,0|u;for(s=-2130706433&e,a=(a=0==(0|UA(A,e)))?1:2;i[n>>2]=0,f=a+1|0,!((0|(l=0|U(A,e,a,n)))==(0|r)&(0|M())==(0|t));){if(!(f>>>0<7)){a=0,A=0,u=6;break}a=f}return 6==(0|u)?(k(0|a),I=o,0|A):(l=0|ye(0|a,0,56),u=0|s|M()|268435456,l|=A,k(0|u),I=o,0|l)},_getH3UnidirectionalEdgeBoundary:WA,_getH3UnidirectionalEdgesFromHexagon:function(A,e,r){r|=0;var t,n=0;t=0==(0|UA(A|=0,e|=0)),e&=-2130706433,i[(n=r)>>2]=t?A:0,i[n+4>>2]=t?285212672|e:0,i[(n=r+8|0)>>2]=A,i[n+4>>2]=301989888|e,i[(n=r+16|0)>>2]=A,i[n+4>>2]=318767104|e,i[(n=r+24|0)>>2]=A,i[n+4>>2]=335544320|e,i[(n=r+32|0)>>2]=A,i[n+4>>2]=352321536|e,i[(r=r+40|0)>>2]=A,i[r+4>>2]=369098752|e},_getOriginH3IndexFromUnidirectionalEdge:function(A,e){var r;return A|=0,k(0|((r=!0&268435456==(2013265920&(e|=0)|0))?-2130706433&e|134217728:0)),0|(r?A:0)},_getPentagonIndexes:NA,_getRes0Indexes:function(A){A|=0;var e=0,r=0,t=0;e=0;do{ye(0|e,0,45),t=134225919|M(),i[(r=A+(e<<3)|0)>>2]=-1,i[r+4>>2]=t,e=e+1|0}while(122!=(0|e))},_h3Distance:function(A,e,r,t){var i,n,o;return r|=0,t|=0,o=I,I=I+32|0,n=o,A=0==(0|$A(A|=0,e|=0,A,e,i=o+12|0))&&0==(0|$A(A,e,r,t,n))?0|hA(i,n):-1,I=o,0|A},_h3GetBaseCell:IA,_h3GetFaces:function A(e,r,t){t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0;n=I,I=I+128|0,h=n+112|0,f=n+96|0,c=n,a=0|Qe(0|(e|=0),0|(r|=0),52),M(),u=15&a,i[h>>2]=u,s=0|Qe(0|e,0|r,45),M(),s&=127;A:do{if(0|S(s)){if(0|u)for(o=1;;){if(!(0==((l=0|ye(7,0,3*(15-o|0)|0))&e|0)&0==((0|M())&r|0))){a=0;break A}if(!(o>>>0>>0))break;o=o+1|0}if(!(1&a))return l=0|ye(u+1|0,0,52),c=0|M()|-15728641&r,A((l|e)&~(h=0|ye(7,0,3*(14-u|0)|0)),c&~(0|M()),t),void(I=n);a=1}else a=0}while(0);YA(e,r,f),a?(mA(f,h,c),l=5):(yA(f,h,c),l=6);A:do{if(0|S(s))if(u)for(o=1;;){if(!(0==((s=0|ye(7,0,3*(15-o|0)|0))&e|0)&0==((0|M())&r|0))){o=8;break A}if(!(o>>>0>>0)){o=20;break}o=o+1|0}else o=20;else o=8}while(0);if(_e(0|t,-1,0|o),a){a=0;do{for(MA(f=c+(a<<4)|0,0|i[h>>2]),f=0|i[f>>2],o=0;!(-1==(0|(u=0|i[(s=t+(o<<2)|0)>>2]))|(0|u)==(0|f));)o=o+1|0;i[s>>2]=f,a=a+1|0}while((0|a)!=(0|l))}else{a=0;do{for(kA(f=c+(a<<4)|0,0|i[h>>2],0,1),f=0|i[f>>2],o=0;!(-1==(0|(u=0|i[(s=t+(o<<2)|0)>>2]))|(0|u)==(0|f));)o=o+1|0;i[s>>2]=f,a=a+1|0}while((0|a)!=(0|l))}I=n},_h3GetResolution:function(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),52),M(),15&e|0},_h3IndexesAreNeighbors:ZA,_h3IsPentagon:UA,_h3IsResClassIII:function(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),52),M(),1&e|0},_h3IsValid:FA,_h3Line:function(A,e,r,t,n){r|=0,t|=0,n|=0;var o,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,Q=0;if(o=I,I=I+48|0,s=o+12|0,M=o,0==(0|$A(A|=0,e|=0,A,e,a=o+24|0))&&0==(0|$A(A,e,r,t,s))){if((0|(k=0|hA(a,s)))<0)return I=o,0|(M=k);for(i[a>>2]=0,i[a+4>>2]=0,i[a+8>>2]=0,i[s>>2]=0,i[s+4>>2]=0,i[s+8>>2]=0,$A(A,e,A,e,a),$A(A,e,r,t,s),gA(a),gA(s),k?(w=+(0|k),m=a,r=c=0|i[a>>2],t=d=0|i[(b=a+4|0)>>2],a=g=0|i[(v=a+8|0)>>2],p=+((0|i[s>>2])-c|0)/w,B=+((0|i[s+4>>2])-d|0)/w,w=+((0|i[s+8>>2])-g|0)/w):(b=t=a+4|0,v=g=a+8|0,m=a,r=0|i[a>>2],t=0|i[t>>2],a=0|i[g>>2],p=0,B=0,w=0),i[M>>2]=r,i[(g=M+4|0)>>2]=t,i[(d=M+8|0)>>2]=a,c=0;;){Q=p*(l=+(0|c))+ +(0|r),u=B*l+ +(0|i[b>>2]),l=w*l+ +(0|i[v>>2]),t=~~+xe(+Q),s=~~+xe(+u),r=~~+xe(+l),Q=+f(+(+(0|t)-Q)),u=+f(+(+(0|s)-u)),l=+f(+(+(0|r)-l));do{if(!(Q>u&Q>l)){if(h=0-t|0,u>l){a=h-r|0;break}a=s,r=h-s|0;break}t=0-(s+r)|0,a=s}while(0);if(i[M>>2]=t,i[g>>2]=a,i[d>>2]=r,wA(M),Ae(A,e,M,n+(c<<3)|0),(0|c)==(0|k))break;c=c+1|0,r=0|i[m>>2]}return I=o,0|(M=0)}return I=o,0|(M=-1)},_h3LineSize:function(A,e,r,t){var i,n,o;return r|=0,t|=0,o=I,I=I+32|0,n=o,A=0==(0|$A(A|=0,e|=0,A,e,i=o+12|0))&&0==(0|$A(A,e,r,t,n))?0|hA(i,n):-1,I=o,(A>>>31^1)+A|0},_h3SetToLinkedGeo:function(A,e,r){r|=0;var t,n,o,a=0;if(o=I,I=I+32|0,t=o,function(A,e,r){A|=0,r|=0;var t,n,o=0,a=0,f=0,s=0,u=0;if(n=I,I=I+176|0,t=n,(0|(e|=0))<1)return se(r,0,0),void(I=n);s=0|Qe(0|i[(s=A)>>2],0|i[s+4>>2],52),M(),se(r,(0|e)>6?e:6,15&s),s=0;do{if(jA(0|i[(o=A+(s<<3)|0)>>2],0|i[o+4>>2],t),(0|(o=0|i[t>>2]))>0){u=0;do{f=t+8+(u<<4)|0,(a=0|de(r,o=t+8+(((0|(u=u+1|0))%(0|o)|0)<<4)|0,f))?he(r,a):ce(r,f,o),o=0|i[t>>2]}while((0|u)<(0|o))}s=s+1|0}while((0|s)!=(0|e));I=n}(A|=0,e|=0,n=o+16|0),i[r>>2]=0,i[r+4>>2]=0,i[r+8>>2]=0,!(A=0|le(n)))return XA(r),ue(n),void(I=o);do{e=0|JA(r);do{KA(e,A),a=A+16|0,i[t>>2]=i[a>>2],i[t+4>>2]=i[a+4>>2],i[t+8>>2]=i[a+8>>2],i[t+12>>2]=i[a+12>>2],he(n,A),A=0|ge(n,t)}while(0!=(0|A));A=0|le(n)}while(0!=(0|A));XA(r),ue(n),I=o},_h3ToCenterChild:function(A,e,r){r|=0;var t=0,i=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(t&=15))<=(0|r)){if((0|t)!=(0|r)&&(A|=i=0|ye(0|r,0,52),e=0|M()|-15728641&e,(0|t)<(0|r)))do{i=0|ye(7,0,3*(14-t|0)|0),t=t+1|0,A&=~i,e&=~(0|M())}while((0|t)<(0|r))}else e=0,A=0;return k(0|e),0|A},_h3ToChildren:PA,_h3ToGeo:OA,_h3ToGeoBoundary:jA,_h3ToParent:CA,_h3UnidirectionalEdgeIsValid:function(A,e){var r=0;if(!(!0&268435456==(2013265920&(e|=0)|0)))return 0|(r=0);switch(r=0|Qe(0|(A|=0),0|e,56),M(),7&r){case 0:case 7:return 0|(r=0)}return!0&16777216==(117440512&e|0)&0!=(0|UA(A,r=-2130706433&e|134217728))?0|(r=0):0|(r=0|FA(A,r))},_hexAreaKm2:function(A){return+ +n[20496+((A|=0)<<3)>>3]},_hexAreaM2:function(A){return+ +n[20624+((A|=0)<<3)>>3]},_hexRing:function(A,e,r,t){A|=0,e|=0,t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0,h=0;if(n=I,I=I+16|0,h=n,!(r|=0))return i[(h=t)>>2]=A,i[h+4>>2]=e,I=n,0|(h=0);i[h>>2]=0;A:do{if(0|UA(A,e))A=1;else{if(a=(0|r)>0){o=0,l=A;do{if(0==(0|(l=0|U(l,e,4,h)))&0==(0|(e=0|M()))){A=2;break A}if(o=o+1|0,0|UA(l,e)){A=1;break A}}while((0|o)<(0|r));if(i[(u=t)>>2]=l,i[u+4>>2]=e,u=r+-1|0,a){a=0,f=1,o=l,A=e;do{if(0==(0|(o=0|U(o,A,2,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(f<<3)|0)>>2]=o,i[s+4>>2]=A,f=f+1|0,0|UA(o,A)){A=1;break A}a=a+1|0}while((0|a)<(0|r));s=0,a=f;do{if(0==(0|(o=0|U(o,A,3,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(f=t+(a<<3)|0)>>2]=o,i[f+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}s=s+1|0}while((0|s)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,1,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,5,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,4,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));for(f=0;;){if(0==(0|(o=0|U(o,A,6,h)))&0==(0|(A=0|M()))){A=2;break A}if((0|f)!=(0|u)){if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,0|UA(o,A)){A=1;break A}a=a+1|0}if((0|(f=f+1|0))>=(0|r)){f=l,a=e;break}}}else f=l,o=l,a=e,A=e}else i[(f=t)>>2]=A,i[f+4>>2]=e,f=A,o=A,a=e,A=e;A=1&((0|f)!=(0|o)|(0|a)!=(0|A))}}while(0);return I=n,0|(h=A)},_i64Subtract:ve,_kRing:F,_kRingDistances:function(A,e,r,t,i){var n;if(0|C(A|=0,e|=0,r|=0,t|=0,i|=0)){if(_e(0|t,0,(n=1+(0|b(3*r|0,r+1|0))|0)<<3|0),0|i)return _e(0|i,0,n<<2|0),void P(A,e,r,t,i,n,0);(i=0|be(n,4))&&(P(A,e,r,t,i,n,0),Be(i))}},_llvm_minnum_f64:Ee,_llvm_round_f64:xe,_malloc:pe,_maxFaceCount:function(A,e){var r=0,t=0;if(t=0|Qe(0|(A|=0),0|(e|=0),45),M(),!(0|S(127&t)))return 0|(t=2);if(t=0|Qe(0|A,0|e,52),M(),!(t&=15))return 0|(t=5);for(r=1;;){if(!(0==((0|ye(7,0,3*(15-r|0)|0))&A|0)&0==((0|M())&e|0))){r=2,A=6;break}if(!(r>>>0>>0)){r=5,A=6;break}r=r+1|0}return 6==(0|A)?0|r:0},_maxH3ToChildrenSize:function(A,e,r){return r|=0,A=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(A&=15))<=(0|r)?0|(r=0|ee(7,r-A|0)):0|(r=0)},_maxKringSize:function(A){return 1+(0|b(3*(A|=0)|0,A+1|0))|0},_maxPolyfillSize:function(A,e){e|=0;var r,t=0,n=0,o=0,a=0,f=0;if(r=I,I=I+48|0,o=r+8|0,n=r,a=0|i[(f=A|=0)+4>>2],i[(t=n)>>2]=i[f>>2],i[t+4>>2]=a,te(n,o),o=0|j(o,e),e=0|i[n>>2],(0|(n=0|i[A+8>>2]))<=0)return I=r,0|(f=(f=(a=(0|o)<(0|(f=e)))?f:o)+12|0);t=0|i[A+12>>2],A=0;do{e=(0|i[t+(A<<3)>>2])+e|0,A=A+1|0}while((0|A)<(0|n));return I=r,0|(f=(f=(f=(0|o)<(0|e))?e:o)+12|0)},_maxUncompactSize:function(A,e,r){A|=0,r|=0;var t=0,n=0,o=0,a=0;if((0|(e|=0))<=0)return 0|(r=0);if((0|r)>=16){for(t=0;;){if(!(0==(0|i[(a=A+(t<<3)|0)>>2])&0==(0|i[a+4>>2]))){t=-1,n=13;break}if((0|(t=t+1|0))>=(0|e)){t=0,n=13;break}}if(13==(0|n))return 0|t}t=0,a=0;A:for(;;){o=0|i[(n=A+(a<<3)|0)>>2],n=0|i[n+4>>2];do{if(!(0==(0|o)&0==(0|n))){if(n=0|Qe(0|o,0|n,52),M(),(0|(n&=15))>(0|r)){t=-1,n=13;break A}if((0|n)==(0|r)){t=t+1|0;break}t=(0|ee(7,r-n|0))+t|0;break}}while(0);if((0|(a=a+1|0))>=(0|e)){n=13;break}}return 13==(0|n)?0|t:0},_memcpy:De,_memset:_e,_numHexagons:function(A){var e;return A=0|i[(e=21008+((A|=0)<<3)|0)>>2],k(0|i[e+4>>2]),0|A},_pentagonIndexCount:function(){return 12},_pointDistKm:DA,_pointDistM:function(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))*6371.007180918475*1e3},_pointDistRads:function(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))},_polyfill:function(A,e,r){var t,n=0,o=0,a=0,f=0,s=0;if(t=I,I=I+48|0,n=t+8|0,o=t,0|function(A,e,r){e|=0,r|=0;var t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,y=0,E=0,x=0,D=0,_=0,F=0,U=0,S=0,T=0,V=0,H=0;H=I,I=I+112|0,U=H+80|0,s=H+72|0,S=H,T=H+56|0,(V=0|pe(32+(i[(u=(A=A|0)+8|0)>>2]<<5)|0))||Q(22848,22448,800,22456);if(ie(A,V),t=0|i[(o=A)+4>>2],i[(f=s)>>2]=i[o>>2],i[f+4>>2]=t,te(s,U),f=0|j(U,e),t=0|i[s>>2],(0|(o=0|i[u>>2]))>0){a=0|i[A+12>>2],n=0;do{t=(0|i[a+(n<<3)>>2])+t|0,n=n+1|0}while((0|n)!=(0|o))}if(n=0|be(F=(f=(0|f)<(0|t)?t:f)+12|0,8),l=0|be(F,8),i[U>>2]=0,_=0|i[(D=A)+4>>2],i[(t=s)>>2]=i[D>>2],i[t+4>>2]=_,0|(t=0|G(s,F,e,U,n,l)))return Be(n),Be(l),Be(V),I=H,0|(V=t);A:do{if((0|i[u>>2])>0){for(o=A+12|0,t=0;a=0|G((0|i[o>>2])+(t<<3)|0,F,e,U,n,l),t=t+1|0,!(0|a);)if((0|t)>=(0|i[u>>2]))break A;return Be(n),Be(l),Be(V),I=H,0|(V=a)}}while(0);(0|f)>-12&&_e(0|l,0,((0|F)>1?F:1)<<3|0);A:do{if((0|i[U>>2])>0){_=((0|F)<0)<<31>>31,m=n,k=l,y=n,E=n,x=l,D=n,t=n,p=n,B=l,b=l,v=l,n=l;e:for(;;){for(w=0|i[U>>2],d=0,g=0,o=0;;){f=(a=S)+56|0;do{i[a>>2]=0,a=a+4|0}while((0|a)<(0|f));if(0|C(s=0|i[(e=m+(d<<3)|0)>>2],e=0|i[e+4>>2],1,S,0)){f=(a=S)+56|0;do{i[a>>2]=0,a=a+4|0}while((0|a)<(0|f));0|(a=0|be(7,4))&&(P(s,e,1,S,a,7,0),Be(a))}c=0;do{l=0|i[(h=S+(c<<3)|0)>>2],h=0|i[h+4>>2];r:do{if(!(0==(0|l)&0==(0|h))){if(s=0|Me(0|l,0|h,0|F,0|_),M(),!(0==(0|(e=0|i[(f=a=r+(s<<3)|0)>>2]))&0==(0|(f=0|i[f+4>>2]))))for(u=0;;){if((0|u)>(0|F))break e;if((0|e)==(0|l)&(0|f)==(0|h))break r;if(0==(0|(e=0|i[(f=a=r+((s=(s+1|0)%(0|F)|0)<<3)|0)>>2]))&0==(0|(f=0|i[f+4>>2])))break;u=u+1|0}0==(0|l)&0==(0|h)||(OA(l,h,T),0|ne(A,V,T)&&(i[(u=a)>>2]=l,i[u+4>>2]=h,i[(u=k+(o<<3)|0)>>2]=l,i[u+4>>2]=h,o=o+1|0))}}while(0);c=c+1|0}while(c>>>0<7);if((0|(g=g+1|0))>=(0|w))break;d=d+1|0}if((0|w)>0&&_e(0|y,0,w<<3|0),i[U>>2]=o,!((0|o)>0))break A;l=n,h=v,c=D,d=b,g=B,w=k,n=p,v=t,b=E,B=y,p=l,t=h,D=x,x=c,E=d,y=g,k=m,m=w}return Be(E),Be(x),Be(V),I=H,0|(V=-1)}t=l}while(0);return Be(V),Be(n),Be(t),I=H,0|(V=0)}(A|=0,e|=0,r|=0)){if(a=0|i[(s=A)+4>>2],i[(f=o)>>2]=i[s>>2],i[f+4>>2]=a,te(o,n),f=0|j(n,e),e=0|i[o>>2],(0|(a=0|i[A+8>>2]))>0){o=0|i[A+12>>2],n=0;do{e=(0|i[o+(n<<3)>>2])+e|0,n=n+1|0}while((0|n)!=(0|a))}(0|(e=(0|f)<(0|e)?e:f))<=-12||_e(0|r,0,8+(((0|(s=e+11|0))>0?s:0)<<3)|0),I=t}else I=t},_res0IndexCount:function(){return 122},_round:Ie,_sbrk:Fe,_sizeOfCoordIJ:function(){return 8},_sizeOfGeoBoundary:function(){return 168},_sizeOfGeoCoord:function(){return 16},_sizeOfGeoPolygon:function(){return 16},_sizeOfGeofence:function(){return 8},_sizeOfH3Index:function(){return 8},_sizeOfLinkedGeoPolygon:function(){return 12},_uncompact:function(A,e,r,t,n){A|=0,r|=0,t|=0,n|=0;var o=0,a=0,f=0,s=0,u=0,l=0;if((0|(e|=0))<=0)return 0|(n=0);if((0|n)>=16){for(o=0;;){if(!(0==(0|i[(l=A+(o<<3)|0)>>2])&0==(0|i[l+4>>2]))){o=14;break}if((0|(o=o+1|0))>=(0|e)){a=0,o=16;break}}if(14==(0|o))return 0|((0|t)>0?-2:-1);if(16==(0|o))return 0|a}o=0,l=0;A:for(;;){a=0|i[(f=u=A+(l<<3)|0)>>2],f=0|i[f+4>>2];do{if(!(0==(0|a)&0==(0|f))){if((0|o)>=(0|t)){a=-1,o=16;break A}if(s=0|Qe(0|a,0|f,52),M(),(0|(s&=15))>(0|n)){a=-2,o=16;break A}if((0|s)==(0|n)){i[(u=r+(o<<3)|0)>>2]=a,i[u+4>>2]=f,o=o+1|0;break}if((0|(a=(0|ee(7,n-s|0))+o|0))>(0|t)){a=-1,o=16;break A}PA(0|i[u>>2],0|i[u+4>>2],n,r+(o<<3)|0),o=a}}while(0);if((0|(l=l+1|0))>=(0|e)){a=0,o=16;break}}return 16==(0|o)?0|a:0},establishStackSpace:function(A,e){I=A|=0},stackAlloc:function(A){var e;return e=I,I=(I=I+(A|=0)|0)+15&-16,0|e},stackRestore:function(A){I=A|=0},stackSave:function(){return 0|I}}}({Math:Math,Int8Array:Int8Array,Int32Array:Int32Array,Uint8Array:Uint8Array,Float32Array:Float32Array,Float64Array:Float64Array},{a:fA,b:function(A){s=A},c:u,d:function(A,e,r,t){fA("Assertion failed: "+g(A)+", at: "+[e?g(e):"unknown filename",r,t?g(t):"unknown function"])},e:function(A){return r.___errno_location&&(v[r.___errno_location()>>2]=A),A},f:N,g:function(A,e,r){B.set(B.subarray(e,e+r),A)},h:function(A){var e=N(),r=16777216,t=2130706432;if(A>t)return!1;for(var i=Math.max(e,16777216);i>0]=e;break;case"i16":b[A>>1]=e;break;case"i32":v[A>>2]=e;break;case"i64":H=[e>>>0,(V=e,+F(V)>=1?V>0?(0|U(+P(V/4294967296),4294967295))>>>0:~~+C((V-+(~~V>>>0))/4294967296)>>>0:0)],v[A>>2]=H[0],v[A+4>>2]=H[1];break;case"float":m[A>>2]=e;break;case"double":k[A>>3]=e;break;default:fA("invalid type for setValue: "+r)}},r.getValue=function(A,e,r){switch("*"===(e=e||"i8").charAt(e.length-1)&&(e="i32"),e){case"i1":case"i8":return p[A>>0];case"i16":return b[A>>1];case"i32":case"i64":return v[A>>2];case"float":return m[A>>2];case"double":return k[A>>3];default:fA("invalid type for getValue: "+e)}return null},r.getTempRet0=u,R){z(R)||(K=R,R=r.locateFile?r.locateFile(K,o):o+K),G++,r.monitorRunDependencies&&r.monitorRunDependencies(G);var tA=function(A){A.byteLength&&(A=new Uint8Array(A)),B.set(A,8),r.memoryInitializerRequest&&delete r.memoryInitializerRequest.response,function(A){if(G--,r.monitorRunDependencies&&r.monitorRunDependencies(G),0==G&&(null!==S&&(clearInterval(S),S=null),T)){var e=T;T=null,e()}}()},iA=function(){i(R,tA,(function(){throw"could not load memory initializer "+R}))},nA=J(R);if(nA)tA(nA.buffer);else if(r.memoryInitializerRequest){var oA=function(){var A=r.memoryInitializerRequest,e=A.response;if(200!==A.status&&0!==A.status){var t=J(r.memoryInitializerRequestURL);if(!t)return console.warn("a problem seems to have happened with Module.memoryInitializerRequest, status: "+A.status+", retrying "+R),void iA();e=t.buffer}tA(e)};r.memoryInitializerRequest.response?setTimeout(oA,0):r.memoryInitializerRequest.addEventListener("load",oA)}else iA()}function aA(A){function e(){X||(X=!0,l||(E(D),E(_),r.onRuntimeInitialized&&r.onRuntimeInitialized(),function(){if(r.postRun)for("function"==typeof r.postRun&&(r.postRun=[r.postRun]);r.postRun.length;)A=r.postRun.shift(),I.unshift(A);var A;E(I)}()))}A=A||n,G>0||(!function(){if(r.preRun)for("function"==typeof r.preRun&&(r.preRun=[r.preRun]);r.preRun.length;)A=r.preRun.shift(),x.unshift(A);var A;E(x)}(),G>0||(r.setStatus?(r.setStatus("Running..."),setTimeout((function(){setTimeout((function(){r.setStatus("")}),1),e()}),1)):e()))}function fA(A){throw r.onAbort&&r.onAbort(A),a(A+=""),f(A),l=!0,"abort("+A+"). Build with -s ASSERTIONS=1 for more info."}if(T=function A(){X||aA(),X||(T=A)},r.run=aA,r.abort=fA,r.preInit)for("function"==typeof r.preInit&&(r.preInit=[r.preInit]);r.preInit.length>0;)r.preInit.pop()();return aA(),A}("object"==typeof t?t:{}),i="number",n={};[["sizeOfH3Index",i],["sizeOfGeoCoord",i],["sizeOfGeoBoundary",i],["sizeOfGeoPolygon",i],["sizeOfGeofence",i],["sizeOfLinkedGeoPolygon",i],["sizeOfCoordIJ",i],["h3IsValid",i,[i,i]],["geoToH3",i,[i,i,i]],["h3ToGeo",null,[i,i,i]],["h3ToGeoBoundary",null,[i,i,i]],["maxKringSize",i,[i]],["kRing",null,[i,i,i,i]],["kRingDistances",null,[i,i,i,i,i]],["hexRing",null,[i,i,i,i]],["maxPolyfillSize",i,[i,i]],["polyfill",null,[i,i,i]],["h3SetToLinkedGeo",null,[i,i,i]],["destroyLinkedPolygon",null,[i]],["compact",i,[i,i,i]],["uncompact",i,[i,i,i,i,i]],["maxUncompactSize",i,[i,i,i]],["h3IsPentagon",i,[i,i]],["h3IsResClassIII",i,[i,i]],["h3GetBaseCell",i,[i,i]],["h3GetResolution",i,[i,i]],["maxFaceCount",i,[i,i]],["h3GetFaces",null,[i,i,i]],["h3ToParent",i,[i,i,i]],["h3ToChildren",null,[i,i,i,i]],["h3ToCenterChild",i,[i,i,i]],["maxH3ToChildrenSize",i,[i,i,i]],["h3IndexesAreNeighbors",i,[i,i,i,i]],["getH3UnidirectionalEdge",i,[i,i,i,i]],["getOriginH3IndexFromUnidirectionalEdge",i,[i,i]],["getDestinationH3IndexFromUnidirectionalEdge",i,[i,i]],["h3UnidirectionalEdgeIsValid",i,[i,i]],["getH3IndexesFromUnidirectionalEdge",null,[i,i,i]],["getH3UnidirectionalEdgesFromHexagon",null,[i,i,i]],["getH3UnidirectionalEdgeBoundary",null,[i,i,i]],["h3Distance",i,[i,i,i,i]],["h3Line",i,[i,i,i,i,i]],["h3LineSize",i,[i,i,i,i]],["experimentalH3ToLocalIj",i,[i,i,i,i,i]],["experimentalLocalIjToH3",i,[i,i,i,i]],["hexAreaM2",i,[i]],["hexAreaKm2",i,[i]],["edgeLengthM",i,[i]],["edgeLengthKm",i,[i]],["pointDistM",i,[i,i]],["pointDistKm",i,[i,i]],["pointDistRads",i,[i,i]],["cellAreaM2",i,[i,i]],["cellAreaKm2",i,[i,i]],["cellAreaRads2",i,[i,i]],["exactEdgeLengthM",i,[i,i]],["exactEdgeLengthKm",i,[i,i]],["exactEdgeLengthRads",i,[i,i]],["numHexagons",i,[i]],["getRes0Indexes",null,[i]],["res0IndexCount",i],["getPentagonIndexes",null,[i,i]],["pentagonIndexCount",i]].forEach((function(A){n[A[0]]=t.cwrap.apply(t,A)}));var o=16,a=n.sizeOfH3Index(),f=n.sizeOfGeoCoord(),s=n.sizeOfGeoBoundary(),u=n.sizeOfGeoPolygon(),l=n.sizeOfGeofence(),h=n.sizeOfLinkedGeoPolygon(),c=n.sizeOfCoordIJ(),d={m:"m",m2:"m2",km:"km",km2:"km2",rads:"rads",rads2:"rads2"};function g(A){if("number"!=typeof A||A<0||A>15||Math.floor(A)!==A)throw new Error("Invalid resolution: "+A)}var w=/[^0-9a-fA-F]/;function p(A){if(Array.isArray(A)&&2===A.length&&Number.isInteger(A[0])&&Number.isInteger(A[1]))return A;if("string"!=typeof A||w.test(A))return[0,0];var e=parseInt(A.substring(0,A.length-8),o);return[parseInt(A.substring(A.length-8),o),e]}function B(A){if(A>=0)return A.toString(o);var e=v(8,(A&=2147483647).toString(o));return e=(parseInt(e[0],o)+8).toString(o)+e.substring(1)}function b(A,e){return B(e)+v(8,B(A))}function v(A,e){for(var r=A-e.length,t="",i=0;i=0&&r.push(n)}return r}(a,o);return t._free(a),f},r.h3GetResolution=function(A){var e=p(A),r=e[0],t=e[1];return n.h3IsValid(r,t)?n.h3GetResolution(r,t):-1},r.geoToH3=function(A,e,r){var i=t._malloc(f);t.HEAPF64.set([A,e].map(U),i/8);var o=M(n.geoToH3(i,r));return t._free(i),o},r.h3ToGeo=function(A){var e=t._malloc(f),r=p(A),i=r[0],o=r[1];n.h3ToGeo(i,o,e);var a=I(e);return t._free(e),a},r.h3ToGeoBoundary=function(A,e){var r=t._malloc(s),i=p(A),o=i[0],a=i[1];n.h3ToGeoBoundary(o,a,r);var f=C(r,e,e);return t._free(r),f},r.h3ToParent=function(A,e){var r=p(A),t=r[0],i=r[1];return M(n.h3ToParent(t,i,e))},r.h3ToChildren=function(A,e){if(!P(A))return[];var r=p(A),i=r[0],o=r[1],f=n.maxH3ToChildrenSize(i,o,e),s=t._calloc(f,a);n.h3ToChildren(i,o,e,s);var u=E(s,f);return t._free(s),u},r.h3ToCenterChild=function(A,e){var r=p(A),t=r[0],i=r[1];return M(n.h3ToCenterChild(t,i,e))},r.kRing=function(A,e){var r=p(A),i=r[0],o=r[1],f=n.maxKringSize(e),s=t._calloc(f,a);n.kRing(i,o,e,s);var u=E(s,f);return t._free(s),u},r.kRingDistances=function(A,e){var r=p(A),i=r[0],o=r[1],f=n.maxKringSize(e),s=t._calloc(f,a),u=t._calloc(f,4);n.kRingDistances(i,o,e,s,u);for(var l=[],h=0;h0){r=t._calloc(i,l);for(var f=0;f0){for(var n=t.getValue(A+r,"i32"),o=0;o */ +r.read=function(A,e,r,t,i){var n,o,a=8*i-t-1,f=(1<>1,u=-7,l=r?i-1:0,h=r?-1:1,c=A[e+l];for(l+=h,n=c&(1<<-u)-1,c>>=-u,u+=a;u>0;n=256*n+A[e+l],l+=h,u-=8);for(o=n&(1<<-u)-1,n>>=-u,u+=t;u>0;o=256*o+A[e+l],l+=h,u-=8);if(0===n)n=1-s;else{if(n===f)return o?NaN:1/0*(c?-1:1);o+=Math.pow(2,t),n-=s}return(c?-1:1)*o*Math.pow(2,n-t)},r.write=function(A,e,r,t,i,n){var o,a,f,s=8*n-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,c=t?0:n-1,d=t?1:-1,g=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=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(f=Math.pow(2,-o))<1&&(o--,f*=2),(e+=o+l>=1?h/f:h*Math.pow(2,1-l))*f>=2&&(o++,f/=2),o+l>=u?(a=0,o=u):o+l>=1?(a=(e*f-1)*Math.pow(2,i),o+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),o=0));i>=8;A[r+c]=255&a,c+=d,a/=256,i-=8);for(o=o<0;A[r+c]=255&o,c+=d,o/=256,s-=8);A[r+c-d]|=128*g}},{}],9:[function(A,e,r){"use strict";e.exports=i;var t=A("ieee754");function i(A){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(A)?A:new Uint8Array(A||0),this.pos=0,this.type=0,this.length=this.buf.length}i.Varint=0,i.Fixed64=1,i.Bytes=2,i.Fixed32=5;var n=4294967296,o=1/n,a="undefined"==typeof TextDecoder?null:new TextDecoder("utf8");function f(A){return A.type===i.Bytes?A.readVarint()+A.pos:A.pos+1}function s(A,e,r){return r?4294967296*e+(A>>>0):4294967296*(e>>>0)+(A>>>0)}function u(A,e,r){var t=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(t);for(var i=r.pos-1;i>=A;i--)r.buf[i+t]=r.buf[i]}function l(A,e){for(var r=0;r>>8,A[r+2]=e>>>16,A[r+3]=e>>>24}function k(A,e){return(A[e]|A[e+1]<<8|A[e+2]<<16)+(A[e+3]<<24)}i.prototype={destroy:function(){this.buf=null},readFields:function(A,e,r){for(r=r||this.length;this.pos>3,n=this.pos;this.type=7&t,A(i,e,this),this.pos===n&&this.skip(t)}return e},readMessage:function(A,e){return this.readFields(A,e,this.readVarint()+this.pos)},readFixed32:function(){var A=v(this.buf,this.pos);return this.pos+=4,A},readSFixed32:function(){var A=k(this.buf,this.pos);return this.pos+=4,A},readFixed64:function(){var A=v(this.buf,this.pos)+v(this.buf,this.pos+4)*n;return this.pos+=8,A},readSFixed64:function(){var A=v(this.buf,this.pos)+k(this.buf,this.pos+4)*n;return this.pos+=8,A},readFloat:function(){var A=t.read(this.buf,this.pos,!0,23,4);return this.pos+=4,A},readDouble:function(){var A=t.read(this.buf,this.pos,!0,52,8);return this.pos+=8,A},readVarint:function(A){var e,r,t=this.buf;return e=127&(r=t[this.pos++]),r<128?e:(e|=(127&(r=t[this.pos++]))<<7,r<128?e:(e|=(127&(r=t[this.pos++]))<<14,r<128?e:(e|=(127&(r=t[this.pos++]))<<21,r<128?e:function(A,e,r){var t,i,n=r.buf;if(i=n[r.pos++],t=(112&i)>>4,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<3,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<10,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<17,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<24,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(1&i)<<31,i<128)return s(A,t,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=t[this.pos]))<<28,A,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var A=this.readVarint();return A%2==1?(A+1)/-2:A/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var A=this.readVarint()+this.pos,e=this.pos;return this.pos=A,A-e>=12&&a?function(A,e,r){return a.decode(A.subarray(e,r))}(this.buf,e,A):function(A,e,r){var t="",i=e;for(;i239?4:f>223?3:f>191?2:1;if(i+u>r)break;1===u?f<128&&(s=f):2===u?128==(192&(n=A[i+1]))&&(s=(31&f)<<6|63&n)<=127&&(s=null):3===u?(n=A[i+1],o=A[i+2],128==(192&n)&&128==(192&o)&&((s=(15&f)<<12|(63&n)<<6|63&o)<=2047||s>=55296&&s<=57343)&&(s=null)):4===u&&(n=A[i+1],o=A[i+2],a=A[i+3],128==(192&n)&&128==(192&o)&&128==(192&a)&&((s=(15&f)<<18|(63&n)<<12|(63&o)<<6|63&a)<=65535||s>=1114112)&&(s=null)),null===s?(s=65533,u=1):s>65535&&(s-=65536,t+=String.fromCharCode(s>>>10&1023|55296),s=56320|1023&s),t+=String.fromCharCode(s),i+=u}return t}(this.buf,e,A)},readBytes:function(){var A=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,A);return this.pos=A,e},readPackedVarint:function(A,e){if(this.type!==i.Bytes)return A.push(this.readVarint(e));var r=f(this);for(A=A||[];this.pos127;);else if(e===i.Bytes)this.pos=this.readVarint()+this.pos;else if(e===i.Fixed32)this.pos+=4;else{if(e!==i.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(A,e){this.writeVarint(A<<3|e)},realloc:function(A){for(var e=this.length||16;e268435455||A<0?function(A,e){var r,t;A>=0?(r=A%4294967296|0,t=A/4294967296|0):(t=~(-A/4294967296),4294967295^(r=~(-A%4294967296))?r=r+1|0:(r=0,t=t+1|0));if(A>=0x10000000000000000||A<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(A,e,r){r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos]=127&A}(r,0,e),function(A,e){var r=(7&A)<<4;if(e.buf[e.pos++]|=r|((A>>>=3)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;e.buf[e.pos++]=127&A}(t,e)}(A,this):(this.realloc(4),this.buf[this.pos++]=127&A|(A>127?128:0),A<=127||(this.buf[this.pos++]=127&(A>>>=7)|(A>127?128:0),A<=127||(this.buf[this.pos++]=127&(A>>>=7)|(A>127?128:0),A<=127||(this.buf[this.pos++]=A>>>7&127))))},writeSVarint:function(A){this.writeVarint(A<0?2*-A-1:2*A)},writeBoolean:function(A){this.writeVarint(Boolean(A))},writeString:function(A){A=String(A),this.realloc(4*A.length),this.pos++;var e=this.pos;this.pos=function(A,e,r){for(var t,i,n=0;n55295&&t<57344){if(!i){t>56319||n+1===e.length?(A[r++]=239,A[r++]=191,A[r++]=189):i=t;continue}if(t<56320){A[r++]=239,A[r++]=191,A[r++]=189,i=t;continue}t=i-55296<<10|t-56320|65536,i=null}else i&&(A[r++]=239,A[r++]=191,A[r++]=189,i=null);t<128?A[r++]=t:(t<2048?A[r++]=t>>6|192:(t<65536?A[r++]=t>>12|224:(A[r++]=t>>18|240,A[r++]=t>>12&63|128),A[r++]=t>>6&63|128),A[r++]=63&t|128)}return r}(this.buf,A,this.pos);var r=this.pos-e;r>=128&&u(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r},writeFloat:function(A){this.realloc(4),t.write(this.buf,A,this.pos,!0,23,4),this.pos+=4},writeDouble:function(A){this.realloc(8),t.write(this.buf,A,this.pos,!0,52,8),this.pos+=8},writeBytes:function(A){var e=A.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&u(r,t,this),this.pos=r-1,this.writeVarint(t),this.pos+=t},writeMessage:function(A,e,r){this.writeTag(A,i.Bytes),this.writeRawMessage(e,r)},writePackedVarint:function(A,e){e.length&&this.writeMessage(A,l,e)},writePackedSVarint:function(A,e){e.length&&this.writeMessage(A,h,e)},writePackedBoolean:function(A,e){e.length&&this.writeMessage(A,g,e)},writePackedFloat:function(A,e){e.length&&this.writeMessage(A,c,e)},writePackedDouble:function(A,e){e.length&&this.writeMessage(A,d,e)},writePackedFixed32:function(A,e){e.length&&this.writeMessage(A,w,e)},writePackedSFixed32:function(A,e){e.length&&this.writeMessage(A,p,e)},writePackedFixed64:function(A,e){e.length&&this.writeMessage(A,B,e)},writePackedSFixed64:function(A,e){e.length&&this.writeMessage(A,b,e)},writeBytesField:function(A,e){this.writeTag(A,i.Bytes),this.writeBytes(e)},writeFixed32Field:function(A,e){this.writeTag(A,i.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(A,e){this.writeTag(A,i.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(A,e){this.writeTag(A,i.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(A,e){this.writeTag(A,i.Fixed64),this.writeSFixed64(e)},writeVarintField:function(A,e){this.writeTag(A,i.Varint),this.writeVarint(e)},writeSVarintField:function(A,e){this.writeTag(A,i.Varint),this.writeSVarint(e)},writeStringField:function(A,e){this.writeTag(A,i.Bytes),this.writeString(e)},writeFloatField:function(A,e){this.writeTag(A,i.Fixed32),this.writeFloat(e)},writeDoubleField:function(A,e){this.writeTag(A,i.Fixed64),this.writeDouble(e)},writeBooleanField:function(A,e){this.writeVarintField(A,Boolean(e))}}},{ieee754:8}],10:[function(A,e,r){var t=A("pbf"),i=A("./lib/geojson_wrapper");function n(A){var e=new t;return function(A,e){for(var r in A.layers)e.writeMessage(3,o,A.layers[r])}(A,e),e.finish()}function o(A,e){var r;e.writeVarintField(15,A.version||1),e.writeStringField(1,A.name||""),e.writeVarintField(5,A.extent||4096);var t={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r>31}function l(A,e){for(var r=A.loadGeometry(),t=A.type,i=0,n=0,o=r.length,a=0;anew Promise(((r,t)=>{var i;r((i=e,{type:"FeatureCollection",features:A.cells.map((A=>{const e={properties:A,geometry:{type:i.geometry_type,coordinates:i.generate(A.h3id)}};return i.promoteID||(e.id=parseInt(A.h3id,16)),e}))}))})),a=A=>{const e=["type","data","maxzoom","attribution","buffer","filter","tolerance","cluster","clusterRadius","clusterMaxZoom","clusterMinPoints","clusterProperties","lineMetrics","generateId","promoteId"];return f(A,((A,r)=>e.includes(A)))},f=(A,e)=>Object.fromEntries(Object.entries(A).filter((([A,r])=>e(A,r))));t.Map.prototype.addH3TSource=function(A,e){const r=Object.assign({},n,e,{type:"vector",format:"pbf"});r.generate=A=>"Polygon"===r.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),r.promoteId&&(r.promoteId="h3id"),t.addProtocol("h3tiles",((A,e)=>{const t=`http${!1===r.https?"":"s"}://${A.url.split("://")[1]}`,n=A.url.split(/\/|\./i),a=n.length,f=n.slice(a-4,a-1).map((A=>1*A)),s=new AbortController,u=s.signal;let l;r.timeout>0&&setTimeout((()=>s.abort()),r.timeout),fetch(t,{signal:u}).then((A=>{if(A.ok)return l=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,r))).then((A=>{const t=i.tovt(A).getTile(...f),n={};n[r.sourcelayer]=t;const o=i.topbf.fromGeojsonVt(n,{version:2});r.debug&&console.log(`${f}: ${A.features.length} features, ${(performance.now()-l).toFixed(0)} ms`),e(null,o,null,null)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Tile .../${f.join("/")}.h3t is taking too long to fetch`),e(new Error(A))}))})),this.addSource(A,(A=>{const e=["type","url","tiles","bounds","scheme","minzoom","maxzoom","attribution","promoteId","volatile"];return f(A,((A,r)=>e.includes(A)))})(r))};t.Map.prototype.addH3JSource=function(A,e){const r=new AbortController,t=r.signal,f=Object.assign({},n,e,{type:"geojson"});let s;if(f.generate=A=>"Polygon"===f.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),f.promoteId&&(f.promoteId="h3id"),f.timeout>0&&setTimeout((()=>r.abort()),f.timeout),"string"==typeof f.data)return f.timeout>0&&setTimeout((()=>r.abort()),f.timeout),new Promise(((e,r)=>{fetch(f.data,{signal:t}).then((A=>{if(A.ok)return s=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,f))).then((r=>{f.data=r,this.addSource(A,a(f)),f.debug&&console.log(`${r.features.length} features, ${(performance.now()-s).toFixed(0)} ms`),e(this)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Source file ${f.data} is taking too long to fetch`),console.error(A.message)}))}));o(f.data,f).then((e=>(f.data=e,this.addSource(A,a(f)),new Promise(((A,e)=>A(this))))))};t.Map.prototype.setH3JData=function(A,e,r){const t=Object.assign({},n,r);t.generate=A=>"Polygon"===t.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),t.promoteId&&(t.promoteId="h3id");const a=new AbortController,f=a.signal,s=this.getSource(A);let u;"string"==typeof e?(t.timeout>0&&setTimeout((()=>a.abort()),t.timeout),fetch(e,{signal:f}).then((A=>{if(A.ok)return u=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,t))).then((A=>{s.setData(A),t.debug&&console.log(`${A.features.length} features, ${(performance.now()-u).toFixed(0)} ms`)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Data file ${e} is taking too long to fetch`),console.error(A.message)}))):o(e,t).then((A=>s.setData(A)))}},{"geojson-vt":6,"h3-js":7,"vt-pbf":10}]},{},[12])(12)})); \ No newline at end of file diff --git a/docs/articles/turf_files/htmlwidgets-1.6.4/htmlwidgets.js b/docs/articles/turf_files/htmlwidgets-1.6.4/htmlwidgets.js new file mode 100644 index 0000000..1067d02 --- /dev/null +++ b/docs/articles/turf_files/htmlwidgets-1.6.4/htmlwidgets.js @@ -0,0 +1,901 @@ +(function() { + // If window.HTMLWidgets is already defined, then use it; otherwise create a + // new object. This allows preceding code to set options that affect the + // initialization process (though none currently exist). + window.HTMLWidgets = window.HTMLWidgets || {}; + + // See if we're running in a viewer pane. If not, we're in a web browser. + var viewerMode = window.HTMLWidgets.viewerMode = + /\bviewer_pane=1\b/.test(window.location); + + // See if we're running in Shiny mode. If not, it's a static document. + // Note that static widgets can appear in both Shiny and static modes, but + // obviously, Shiny widgets can only appear in Shiny apps/documents. + var shinyMode = window.HTMLWidgets.shinyMode = + typeof(window.Shiny) !== "undefined" && !!window.Shiny.outputBindings; + + // We can't count on jQuery being available, so we implement our own + // version if necessary. + function querySelectorAll(scope, selector) { + if (typeof(jQuery) !== "undefined" && scope instanceof jQuery) { + return scope.find(selector); + } + if (scope.querySelectorAll) { + return scope.querySelectorAll(selector); + } + } + + function asArray(value) { + if (value === null) + return []; + if ($.isArray(value)) + return value; + return [value]; + } + + // Implement jQuery's extend + function extend(target /*, ... */) { + if (arguments.length == 1) { + return target; + } + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var prop in source) { + if (source.hasOwnProperty(prop)) { + target[prop] = source[prop]; + } + } + } + return target; + } + + // IE8 doesn't support Array.forEach. + function forEach(values, callback, thisArg) { + if (values.forEach) { + values.forEach(callback, thisArg); + } else { + for (var i = 0; i < values.length; i++) { + callback.call(thisArg, values[i], i, values); + } + } + } + + // Replaces the specified method with the return value of funcSource. + // + // Note that funcSource should not BE the new method, it should be a function + // that RETURNS the new method. funcSource receives a single argument that is + // the overridden method, it can be called from the new method. The overridden + // method can be called like a regular function, it has the target permanently + // bound to it so "this" will work correctly. + function overrideMethod(target, methodName, funcSource) { + var superFunc = target[methodName] || function() {}; + var superFuncBound = function() { + return superFunc.apply(target, arguments); + }; + target[methodName] = funcSource(superFuncBound); + } + + // Add a method to delegator that, when invoked, calls + // delegatee.methodName. If there is no such method on + // the delegatee, but there was one on delegator before + // delegateMethod was called, then the original version + // is invoked instead. + // For example: + // + // var a = { + // method1: function() { console.log('a1'); } + // method2: function() { console.log('a2'); } + // }; + // var b = { + // method1: function() { console.log('b1'); } + // }; + // delegateMethod(a, b, "method1"); + // delegateMethod(a, b, "method2"); + // a.method1(); + // a.method2(); + // + // The output would be "b1", "a2". + function delegateMethod(delegator, delegatee, methodName) { + var inherited = delegator[methodName]; + delegator[methodName] = function() { + var target = delegatee; + var method = delegatee[methodName]; + + // The method doesn't exist on the delegatee. Instead, + // call the method on the delegator, if it exists. + if (!method) { + target = delegator; + method = inherited; + } + + if (method) { + return method.apply(target, arguments); + } + }; + } + + // Implement a vague facsimilie of jQuery's data method + function elementData(el, name, value) { + if (arguments.length == 2) { + return el["htmlwidget_data_" + name]; + } else if (arguments.length == 3) { + el["htmlwidget_data_" + name] = value; + return el; + } else { + throw new Error("Wrong number of arguments for elementData: " + + arguments.length); + } + } + + // http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex + function escapeRegExp(str) { + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + } + + function hasClass(el, className) { + var re = new RegExp("\\b" + escapeRegExp(className) + "\\b"); + return re.test(el.className); + } + + // elements - array (or array-like object) of HTML elements + // className - class name to test for + // include - if true, only return elements with given className; + // if false, only return elements *without* given className + function filterByClass(elements, className, include) { + var results = []; + for (var i = 0; i < elements.length; i++) { + if (hasClass(elements[i], className) == include) + results.push(elements[i]); + } + return results; + } + + function on(obj, eventName, func) { + if (obj.addEventListener) { + obj.addEventListener(eventName, func, false); + } else if (obj.attachEvent) { + obj.attachEvent(eventName, func); + } + } + + function off(obj, eventName, func) { + if (obj.removeEventListener) + obj.removeEventListener(eventName, func, false); + else if (obj.detachEvent) { + obj.detachEvent(eventName, func); + } + } + + // Translate array of values to top/right/bottom/left, as usual with + // the "padding" CSS property + // https://developer.mozilla.org/en-US/docs/Web/CSS/padding + function unpackPadding(value) { + if (typeof(value) === "number") + value = [value]; + if (value.length === 1) { + return {top: value[0], right: value[0], bottom: value[0], left: value[0]}; + } + if (value.length === 2) { + return {top: value[0], right: value[1], bottom: value[0], left: value[1]}; + } + if (value.length === 3) { + return {top: value[0], right: value[1], bottom: value[2], left: value[1]}; + } + if (value.length === 4) { + return {top: value[0], right: value[1], bottom: value[2], left: value[3]}; + } + } + + // Convert an unpacked padding object to a CSS value + function paddingToCss(paddingObj) { + return paddingObj.top + "px " + paddingObj.right + "px " + paddingObj.bottom + "px " + paddingObj.left + "px"; + } + + // Makes a number suitable for CSS + function px(x) { + if (typeof(x) === "number") + return x + "px"; + else + return x; + } + + // Retrieves runtime widget sizing information for an element. + // The return value is either null, or an object with fill, padding, + // defaultWidth, defaultHeight fields. + function sizingPolicy(el) { + var sizingEl = document.querySelector("script[data-for='" + el.id + "'][type='application/htmlwidget-sizing']"); + if (!sizingEl) + return null; + var sp = JSON.parse(sizingEl.textContent || sizingEl.text || "{}"); + if (viewerMode) { + return sp.viewer; + } else { + return sp.browser; + } + } + + // @param tasks Array of strings (or falsy value, in which case no-op). + // Each element must be a valid JavaScript expression that yields a + // function. Or, can be an array of objects with "code" and "data" + // properties; in this case, the "code" property should be a string + // of JS that's an expr that yields a function, and "data" should be + // an object that will be added as an additional argument when that + // function is called. + // @param target The object that will be "this" for each function + // execution. + // @param args Array of arguments to be passed to the functions. (The + // same arguments will be passed to all functions.) + function evalAndRun(tasks, target, args) { + if (tasks) { + forEach(tasks, function(task) { + var theseArgs = args; + if (typeof(task) === "object") { + theseArgs = theseArgs.concat([task.data]); + task = task.code; + } + var taskFunc = tryEval(task); + if (typeof(taskFunc) !== "function") { + throw new Error("Task must be a function! Source:\n" + task); + } + taskFunc.apply(target, theseArgs); + }); + } + } + + // Attempt eval() both with and without enclosing in parentheses. + // Note that enclosing coerces a function declaration into + // an expression that eval() can parse + // (otherwise, a SyntaxError is thrown) + function tryEval(code) { + var result = null; + try { + result = eval("(" + code + ")"); + } catch(error) { + if (!(error instanceof SyntaxError)) { + throw error; + } + try { + result = eval(code); + } catch(e) { + if (e instanceof SyntaxError) { + throw error; + } else { + throw e; + } + } + } + return result; + } + + function initSizing(el) { + var sizing = sizingPolicy(el); + if (!sizing) + return; + + var cel = document.getElementById("htmlwidget_container"); + if (!cel) + return; + + if (typeof(sizing.padding) !== "undefined") { + document.body.style.margin = "0"; + document.body.style.padding = paddingToCss(unpackPadding(sizing.padding)); + } + + if (sizing.fill) { + document.body.style.overflow = "hidden"; + document.body.style.width = "100%"; + document.body.style.height = "100%"; + document.documentElement.style.width = "100%"; + document.documentElement.style.height = "100%"; + cel.style.position = "absolute"; + var pad = unpackPadding(sizing.padding); + cel.style.top = pad.top + "px"; + cel.style.right = pad.right + "px"; + cel.style.bottom = pad.bottom + "px"; + cel.style.left = pad.left + "px"; + el.style.width = "100%"; + el.style.height = "100%"; + + return { + getWidth: function() { return cel.getBoundingClientRect().width; }, + getHeight: function() { return cel.getBoundingClientRect().height; } + }; + + } else { + el.style.width = px(sizing.width); + el.style.height = px(sizing.height); + + return { + getWidth: function() { return cel.getBoundingClientRect().width; }, + getHeight: function() { return cel.getBoundingClientRect().height; } + }; + } + } + + // Default implementations for methods + var defaults = { + find: function(scope) { + return querySelectorAll(scope, "." + this.name); + }, + renderError: function(el, err) { + var $el = $(el); + + this.clearError(el); + + // Add all these error classes, as Shiny does + var errClass = "shiny-output-error"; + if (err.type !== null) { + // use the classes of the error condition as CSS class names + errClass = errClass + " " + $.map(asArray(err.type), function(type) { + return errClass + "-" + type; + }).join(" "); + } + errClass = errClass + " htmlwidgets-error"; + + // Is el inline or block? If inline or inline-block, just display:none it + // and add an inline error. + var display = $el.css("display"); + $el.data("restore-display-mode", display); + + if (display === "inline" || display === "inline-block") { + $el.hide(); + if (err.message !== "") { + var errorSpan = $("").addClass(errClass); + errorSpan.text(err.message); + $el.after(errorSpan); + } + } else if (display === "block") { + // If block, add an error just after the el, set visibility:none on the + // el, and position the error to be on top of the el. + // Mark it with a unique ID and CSS class so we can remove it later. + $el.css("visibility", "hidden"); + if (err.message !== "") { + var errorDiv = $(""}var i=t.text,n=i.toLowerCase().indexOf(this.query.toLowerCase()),s=this.query.length;return'
'+i.substring(0,n)+''+i.substring(n,n+s)+""+i.substring(n+s)+"
"},popupRender:function(t){var e=t.place_name.split(",");return'"},showResultMarkers:!0,debounceSearch:200},addTo:function(t){function e(t,e){if(!document.body.contains(e))throw new Error("Element provided to #addTo() exists, but is not in the DOM");var i=t.onAdd();e.appendChild(i)}if(t._controlContainer)t.addControl(this);else if(t instanceof HTMLElement)e(this,t);else{if("string"!=typeof t)throw new Error("Error: addTo must be a maplibre-gl-js map, an html element, or a CSS selector query for a single html element");var i=document.querySelectorAll(t);if(0===i.length)throw new Error("Element ",t,"not found.");if(i.length>1)throw new Error("Geocoder can only be added to a single html element");e(this,i[0])}},onAdd:function(t){if(t&&"string"!=typeof t&&(this._map=t),this.setLanguage(),this.options.localGeocoderOnly&&!this.options.localGeocoder)throw new Error("A localGeocoder function must be specified to use localGeocoderOnly mode");this._onChange=this._onChange.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPaste=this._onPaste.bind(this),this._onBlur=this._onBlur.bind(this),this._showButton=this._showButton.bind(this),this._hideButton=this._hideButton.bind(this),this._onQueryResult=this._onQueryResult.bind(this),this.clear=this.clear.bind(this),this._updateProximity=this._updateProximity.bind(this),this._collapse=this._collapse.bind(this),this._unCollapse=this._unCollapse.bind(this),this._clear=this._clear.bind(this),this._clearOnBlur=this._clearOnBlur.bind(this);var e=this.container=document.createElement("div");e.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl";var i=this.createIcon("search",'');this._inputEl=document.createElement("input"),this._inputEl.type="text",this._inputEl.className="mapboxgl-ctrl-geocoder--input maplibregl-ctrl-geocoder--input",this.setPlaceholder(),this.options.collapsed&&(this._collapse(),this.container.addEventListener("mouseenter",this._unCollapse),this.container.addEventListener("mouseleave",this._collapse),this._inputEl.addEventListener("focus",this._unCollapse)),(this.options.collapsed||this.options.clearOnBlur)&&this._inputEl.addEventListener("blur",this._onBlur),this._inputEl.addEventListener("keydown",r(this._onKeyDown,this.options.debounceSearch)),this._inputEl.addEventListener("paste",this._onPaste),this._inputEl.addEventListener("change",this._onChange),this.container.addEventListener("mouseenter",this._showButton),this.container.addEventListener("mouseleave",this._hideButton);var n=document.createElement("div");n.classList.add("mapboxgl-ctrl-geocoder--pin-right","maplibregl-ctrl-geocoder--pin-right"),this._clearEl=document.createElement("button"),this._clearEl.setAttribute("aria-label","Clear"),this._clearEl.addEventListener("click",this.clear),this._clearEl.className="mapboxgl-ctrl-geocoder--button maplibregl-ctrl-geocoder--button";var o=this.createIcon("close",'');return this._clearEl.appendChild(o),this._loadingEl=this.createIcon("loading",''),n.appendChild(this._clearEl),n.appendChild(this._loadingEl),e.appendChild(i),e.appendChild(this._inputEl),e.appendChild(n),this._typeahead=new s(this._inputEl,[],{filter:!1,minLength:this.options.minLength,limit:this.options.limit,noInitialSelection:!0}),this.setRenderFunction(this.options.render),this._typeahead.getItemValue=this.options.getItemValue,this.mapMarker=null,this.resultMarkers=[],this._handleMarker=this._handleMarker.bind(this),this._handleResultMarkers=this._handleResultMarkers.bind(this),this._map&&(this.options.trackProximity&&(this._updateProximity(),this._map.on("moveend",this._updateProximity)),this._maplibregl=this.options.maplibregl,!this._maplibregl&&this.options.marker&&(console.error("No maplibregl detected in options. Map markers are disabled. Please set options.maplibregl."),this.options.marker=!1)),e},createIcon:function(t,e){var i=document.createElementNS("http://www.w3.org/2000/svg","svg");if(i.setAttribute("class","mapboxgl-ctrl-geocoder--icon mapboxgl-ctrl-geocoder--icon-"+t+" maplibregl-ctrl-geocoder--icon maplibregl-ctrl-geocoder--icon-"+t),i.setAttribute("viewBox","0 0 18 18"),i.setAttribute("xml:space","preserve"),i.setAttribute("width",18),i.setAttribute("height",18),"innerHTML"in i)i.innerHTML=e;else{var n=document.createElement("div");n.innerHTML=""+e.valueOf().toString()+"";var s=n.firstChild,r=s.firstChild;i.appendChild(r)}return i},onRemove:function(){return this.container.parentNode.removeChild(this.container),this.options.trackProximity&&this._map&&this._map.off("moveend",this._updateProximity),this._removeMarker(),this._map=null,this},_onPaste:function(t){var e=(t.clipboardData||window.clipboardData).getData("text");e.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(e)},_onKeyDown:function(t){if(27===t.keyCode&&this.options.clearAndBlurOnEsc)return this._clear(t),this._inputEl.blur();var e=t.target&&t.target.shadowRoot?t.target.shadowRoot.activeElement:t.target;if(!(e?e.value:""))return this.fresh=!0,9!==t.keyCode&&this.clear(t),this._clearEl.style.display="none";if(!t.metaKey&&-1===[9,27,37,39,38,40].indexOf(t.keyCode)){if(13===t.keyCode){if(this.options.showResultsWhileTyping)return void(null==this._typeahead.selected&&this.geocoderApi.getSuggestions?this._geocode(e.value,!0):null==this._typeahead.selected&&this.options.showResultMarkers&&this._fitBoundsForMarkers());this._typeahead.selected||this._geocode(e.value)}e.value.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(e.value)}},_showButton:function(){this._inputEl.value.length>0&&(this._clearEl.style.display="block")},_hideButton:function(){this._typeahead.selected&&(this._clearEl.style.display="none")},_onBlur:function(t){this.options.clearOnBlur&&this._clearOnBlur(t),this.options.collapsed&&this._collapse()},_onChange:function(){var t=this._typeahead.selected;if(t&&!t.geometry)t.placeId?this._geocode(t.placeId,!0,!0):this._geocode(t.text,!0);else if(t&&JSON.stringify(t)!==this.lastSelected){if(this._clearEl.style.display="none",this.options.flyTo){var e;if(this._removeResultMarkers(),t.properties&&a[t.properties.short_code])e=o({},this.options.flyTo),this._map&&this._map.fitBounds(a[t.properties.short_code].bbox,e);else if(t.bbox){var i=t.bbox;e=o({},this.options.flyTo),this._map&&this._map.fitBounds([[i[0],i[1]],[i[2],i[3]]],e)}else{var n={zoom:this.options.zoom};e=o({},n,this.options.flyTo),t.center?e.center=t.center:t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(e.center=t.geometry.coordinates),this._map&&this._map.flyTo(e)}}this.options.marker&&this._maplibregl&&this._handleMarker(t),this._inputEl.focus(),this._inputEl.scrollLeft=0,this._inputEl.setSelectionRange(0,0),this.lastSelected=JSON.stringify(t),this._typeahead.selected=null,this._eventEmitter.emit("result",{result:t})}},_getConfigForRequest:function(){var t=["bbox","limit","proximity","countries","types","language","reverseMode"],e=this;return t.reduce(function(t,i){return e.options[i]&&(["countries","types","language"].indexOf(i)>-1?t[i]=e.options[i].split(/[\s,]+/):t[i]=e.options[i],"proximity"===i&&e.options[i]&&"number"==typeof e.options[i].longitude&&"number"==typeof e.options[i].latitude&&(t[i]=[e.options[i].longitude,e.options[i].latitude])),t},{})},_geocode:function(t,e,i){this._loadingEl.style.display="block",this._eventEmitter.emit("loading",{query:t}),this.inputString=t;var n,s=null,r=this._getConfigForRequest();if(this.options.localGeocoderOnly)n=Promise.resolve();else if(this.options.reverseGeocode&&/(-?\d+\.?\d*)[, ]+(-?\d+\.?\d*)[ ]*$/.test(t)){var l=t.split(/[\s(,)?]+/).map(function(t){return parseFloat(t,10)}).reverse();r.types&&r.types[0],r=o(r,{query:l,limit:1}),"proximity"in r&&delete r.proximity,n=this.geocoderApi.reverseGeocode(r)}else r=o(r,{query:t}),n=this.geocoderApi.getSuggestions?e?this.geocoderApi.searchByPlaceId&&i?this.geocoderApi.searchByPlaceId(r):this.geocoderApi.forwardGeocode(r):this.geocoderApi.getSuggestions(r):this.geocoderApi.forwardGeocode(r);var a=[];this.options.localGeocoder&&((a=this.options.localGeocoder(t))||(a=[]));var h=[];return n.catch(function(t){s=t}.bind(this)).then(function(e){this._loadingEl.style.display="none";var i={};return i=e||{type:"FeatureCollection",features:[]},i.config=r,this.fresh&&(this.fresh=!1),i.features=i.features?a.concat(i.features):a,this.options.externalGeocoder?(h=this.options.externalGeocoder(t,i.features,r)||[],h.then(function(t){return i.features=i.features?t.concat(i.features):t,i},function(){return i})):i}.bind(this)).then(function(t){if(s)throw s;this.options.filter&&t.features.length&&(t.features=t.features.filter(this.options.filter));var i=[];i=t.suggestions?t.suggestions:t.place?[t.place]:t.features,i.length?(this._clearEl.style.display="block",this._typeahead.update(i),(!this.options.showResultsWhileTyping||e)&&this.options.showResultMarkers&&(t.features.length>0||t.place)&&this._fitBoundsForMarkers(),this._eventEmitter.emit("results",t)):(this._clearEl.style.display="none",this._typeahead.selected=null,this._renderNoResults(),this._eventEmitter.emit("results",t))}.bind(this)).catch(function(t){this._loadingEl.style.display="none",a.length&&this.options.localGeocoder||h.length&&this.options.externalGeocoder?(this._clearEl.style.display="block",this._typeahead.update(a)):(this._clearEl.style.display="none",this._typeahead.selected=null,this._renderError()),this._eventEmitter.emit("results",{features:a}),this._eventEmitter.emit("error",{error:t})}.bind(this)),n},_clear:function(t){t&&t.preventDefault(),this._inputEl.value="",this._typeahead.selected=null,this._typeahead.clear(),this._onChange(),this._clearEl.style.display="none",this._removeMarker(),this._removeResultMarkers(),this.lastSelected=null,this._eventEmitter.emit("clear"),this.fresh=!0},clear:function(t){this._clear(t),this._inputEl.focus()},_clearOnBlur:function(t){var e=this;t.relatedTarget&&e._clear(t)},_onQueryResult:function(t){var e=t;if(e.features.length){var i=e.features[0];this._typeahead.selected=i,this._inputEl.value=i.place_name,this._onChange()}},_updateProximity:function(){if(this._map)if(this._map.getZoom()>9){var t=this._map.getCenter().wrap();this.setProximity({longitude:t.lng,latitude:t.lat})}else this.setProximity(null)},_collapse:function(){this._inputEl.value||this._inputEl===document.activeElement||this.container.classList.add("mapboxgl-ctrl-geocoder--collapsed","maplibregl-ctrl-geocoder--collapsed")},_unCollapse:function(){this.container.classList.remove("mapboxgl-ctrl-geocoder--collapsed","maplibregl-ctrl-geocoder--collapsed")},query:function(t){return this._geocode(t).then(this._onQueryResult),this},_renderError:function(){this._renderMessage("
There was an error reaching the server
")},_renderNoResults:function(){this._renderMessage("
No results found
")},_renderMessage:function(t){this._typeahead.update([]),this._typeahead.selected=null,this._typeahead.clear(),this._typeahead.renderError(t)},_getPlaceholderText:function(){if(this.options.placeholder)return this.options.placeholder;if(this.options.language){var t=this.options.language.split(",")[0],e=u.language(t),i=h.placeholder[e];if(i)return i}return"Search"},_fitBoundsForMarkers:function(){if(!(this._typeahead.data.length<1)){var t=this._typeahead.data.filter(function(t){return"string"!=typeof t}).slice(0,this.options.limit);if(this._clearEl.style.display="none",this.options.flyTo&&this._maplibregl&&this._map){var e={padding:100},i=o({},e,this.options.flyTo),n=new this._maplibregl.LngLatBounds;t.forEach(function(t){n.extend(t.geometry.coordinates)}),this._map.fitBounds(n.toArray(),i)}return t.length>0&&this._maplibregl&&this._handleResultMarkers(t),this}},setInput:function(t){return this._inputEl.value=t,this._typeahead.selected=null,this._typeahead.clear(),t.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(t),this},setProximity:function(t){return this.options.proximity=t,this},getProximity:function(){return this.options.proximity},setRenderFunction:function(t){return t&&"function"==typeof t&&(this._typeahead.render=t),this},getRenderFunction:function(){return this._typeahead.render},setLanguage:function(t){var e=navigator.language||navigator.userLanguage||navigator.browserLanguage;return this.options.language=t||this.options.language||e,this},getLanguage:function(){return this.options.language},getZoom:function(){return this.options.zoom},setZoom:function(t){return this.options.zoom=t,this},getFlyTo:function(){return this.options.flyTo},setFlyTo:function(t){return this.options.flyTo=t,this},getPlaceholder:function(){return this.options.placeholder},setPlaceholder:function(t){return this.placeholder=t||this._getPlaceholderText(),this._inputEl.placeholder=this.placeholder,this._inputEl.setAttribute("aria-label",this.placeholder),this},getBbox:function(){return this.options.bbox},setBbox:function(t){return this.options.bbox=t,this},getCountries:function(){return this.options.countries},setCountries:function(t){return this.options.countries=t,this},getTypes:function(){return this.options.types},setTypes:function(t){return this.options.types=t,this},getMinLength:function(){return this.options.minLength},setMinLength:function(t){return this.options.minLength=t,this._typeahead&&(this._typeahead.options.minLength=t),this},getLimit:function(){return this.options.limit},setLimit:function(t){return this.options.limit=t,this._typeahead&&(this._typeahead.options.limit=t),this},getFilter:function(){return this.options.filter},setFilter:function(t){return this.options.filter=t,this},setGeocoderApi:function(t){return this.geocoderApi=t,this},getGeocoderApi:function(){return this.geocoderApi},_handleMarker:function(t){if(this._map){this._removeMarker();var e={color:"#4668F2"},i=o({},e,this.options.marker);this.mapMarker=new this._maplibregl.Marker(i);var n;if(this.options.popup){var s={},r=o({},s,this.options.popup);n=new this._maplibregl.Popup(r).setHTML(this.options.popupRender(t))}return t.center?(this.mapMarker.setLngLat(t.center).addTo(this._map),this.options.popup&&this.mapMarker.setPopup(n)):t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(this.mapMarker.setLngLat(t.geometry.coordinates).addTo(this._map),this.options.popup&&this.mapMarker.setPopup(n)),this}},_removeMarker:function(){this.mapMarker&&(this.mapMarker.remove(),this.mapMarker=null)},_handleResultMarkers:function(t){if(this._map){this._removeResultMarkers();var e={color:"#4668F2"},i=o({},e,this.options.showResultMarkers);return t.forEach(function(t){if(this.options.showResultMarkers&&this.options.showResultMarkers.element){var e=this.options.showResultMarkers.element.cloneNode(!0);i=o(i,{element:e})}var n,s=new this._maplibregl.Marker(o({},i,{element:e}));if(this.options.popup){var r={},l=o({},r,this.options.popup);n=new this._maplibregl.Popup(l).setHTML(this.options.popupRender(t))}t.center?(s.setLngLat(t.center).addTo(this._map),this.options.popup&&s.setPopup(n)):t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(s.setLngLat(t.geometry.coordinates).addTo(this._map),this.options.popup&&s.setPopup(n)),this.resultMarkers.push(s)}.bind(this)),this}},_removeResultMarkers:function(){this.resultMarkers&&this.resultMarkers.length>0&&(this.resultMarkers.forEach(function(t){t.remove()}),this.resultMarkers=[])},on:function(t,e){return this._eventEmitter.on(t,e),this},off:function(t,e){return this._eventEmitter.removeListener(t,e),this}},e.exports=n},{"./exceptions":1,"./localization":3,events:4,"lodash.debounce":6,subtag:7,"suggestions-list":8,xtend:11}],3:[function(t,e,i){"use strict";var n={de:"Suche",it:"Ricerca",en:"Search",nl:"Zoeken",fr:"Chercher",ca:"Cerca",he:"לחפש",ja:"サーチ",lv:"Meklēt",pt:"Procurar",sr:"Претрага",zh:"搜索",cs:"Vyhledávání",hu:"Keresés",ka:"ძიება",nb:"Søke",sk:"Vyhľadávanie",th:"ค้นหา",fi:"Hae",is:"Leita",ko:"수색",pl:"Szukaj",sl:"Iskanje",fa:"جستجو",ru:"Поиск"};e.exports={placeholder:n}},{}],4:[function(t,e,i){function n(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=w(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}function s(t){return void 0===t._maxListeners?n.defaultMaxListeners:t._maxListeners}function r(t,e,i){if(e)t.call(i);else for(var n=t.length,s=m(t,n),r=0;r0&&l.length>r){l.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+l.length+' "'+String(e)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=l.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",a.name,a.message)}}else l=o[e]=i,++t._eventsCount;return t}function c(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var t=new Array(arguments.length),e=0;e1&&(e=arguments[1]),e instanceof Error)throw e;var d=new Error('Unhandled "error" event. ('+e+")");throw d.context=e,d}if(!(i=c[t]))return!1;var f="function"==typeof i;switch(n=arguments.length){case 1:r(i,f,this);break;case 2:o(i,f,this,arguments[1]);break;case 3:l(i,f,this,arguments[1],arguments[2]);break;case 4:a(i,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(n-1),u=1;u=0;r--)if(i[r]===e||i[r].listener===e){o=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():g(i,s),1===i.length&&(n[t]=i[0]),n.removeListener&&this.emit("removeListener",t,o||e)}return this},n.prototype.removeAllListeners=function(t){var e,i,n;if(!(i=this._events))return this;if(!i.removeListener)return 0===arguments.length?(this._events=w(null),this._eventsCount=0):i[t]&&(0==--this._eventsCount?this._events=w(null):delete i[t]),this;if(0===arguments.length){var s,r=x(i);for(n=0;n=0;n--)this.removeListener(t,e[n]);return this},n.prototype.listeners=function(t){return d(this,t,!0)},n.prototype.rawListeners=function(t){return d(this,t,!1)},n.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):f.call(t,e)},n.prototype.listenerCount=f,n.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],5:[function(t,e,i){!function(){var t=this,n={};void 0!==i?e.exports=n:t.fuzzy=n,n.simpleFilter=function(t,e){return e.filter(function(e){return n.test(t,e)})},n.test=function(t,e){return null!==n.match(t,e)},n.match=function(t,e,i){i=i||{};var n,s=0,r=[],o=e.length,l=0,a=0,h=i.pre||"",u=i.post||"",c=i.caseSensitive&&e||e.toLowerCase();t=i.caseSensitive&&t||t.toLowerCase();for(var p=0;p=e||i<0||C&&n>=v}function u(){var t=x();if(h(t))return c(t);_=setTimeout(u,a(t))}function c(t){return _=void 0,M&&g?s(t):(g=m=void 0,y)}function p(){void 0!==_&&clearTimeout(_),L=0,g=E=m=_=void 0}function d(){return void 0===_?y:c(x())}function f(){var t=x(),i=h(t);if(g=arguments,m=this,E=t,i){if(void 0===_)return r(E);if(C)return _=setTimeout(u,e),s(E)}return void 0===_&&(_=setTimeout(u,e)),y}var g,m,v,y,_,E,L=0,k=!1,C=!1,M=!0;if("function"!=typeof t)throw new TypeError(l);return e=o(e)||0,n(i)&&(k=!!i.leading,C="maxWait"in i,v=C?b(o(i.maxWait)||0,e):v,M="trailing"in i?!!i.trailing:M),f.cancel=p,f.flush=d,f}function n(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function s(t){return!!t&&"object"==typeof t}function r(t){return"symbol"==typeof t||s(t)&&_.call(t)==h}function o(t){if("number"==typeof t)return t;if(r(t))return a;if(n(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=n(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(u,"");var i=p.test(t);return i||d.test(t)?f(t.slice(2),i?2:8):c.test(t)?a:+t}var l="Expected a function",a=NaN,h="[object Symbol]",u=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,d=/^0o[0-7]+$/i,f=parseInt,g="object"==typeof t&&t&&t.Object===Object&&t,m="object"==typeof self&&self&&self.Object===Object&&self,v=g||m||Function("return this")(),y=Object.prototype,_=y.toString,b=Math.max,w=Math.min,x=function(){return v.Date.now()};e.exports=i}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],7:[function(t,e,i){!function(t,i,n){void 0!==e&&e.exports?e.exports=n():t.subtag=n()}(this,0,function(){function t(t){return t.match(o)||[]}function e(e){return t(e).filter(function(t,e){return t&&e})}function i(e){return e=t(e),{language:e[1]||r,extlang:e[2]||r,script:e[3]||r,region:e[4]||r}}function n(t,e,i){Object.defineProperty(t,e,{value:i,enumerable:!0})}function s(e,s,o){function l(i){return t(i)[e]||r}n(l,"pattern",s),n(i,o,l)}var r="",o=/^([a-zA-Z]{2,3})(?:[_-]+([a-zA-Z]{3})(?=$|[_-]+))?(?:[_-]+([a-zA-Z]{4})(?=$|[_-]+))?(?:[_-]+([a-zA-Z]{2}|[0-9]{3})(?=$|[_-]+))?/;return s(1,/^[a-zA-Z]{2,3}$/,"language"),s(2,/^[a-zA-Z]{3}$/,"extlang"),s(3,/^[a-zA-Z]{4}$/,"script"),s(4,/^[a-zA-Z]{2}$|^[0-9]{3}$/,"region"),n(i,"split",e),i})},{}],8:[function(t,e,i){"use strict";var n=t("./src/suggestions");e.exports=n,"undefined"!=typeof window&&(window.Suggestions=n)},{"./src/suggestions":10}],9:[function(t,e,i){"use strict";var n=function(t){return this.component=t,this.items=[],this.active=t.options.noInitialSelection?-1:0,this.wrapper=document.createElement("div"),this.wrapper.className="suggestions-wrapper",this.element=document.createElement("ul"),this.element.className="suggestions",this.wrapper.appendChild(this.element),this.selectingListItem=!1,t.el.parentNode.insertBefore(this.wrapper,t.el.nextSibling),this};n.prototype.show=function(){this.element.style.display="block"},n.prototype.hide=function(){this.element.style.display="none"},n.prototype.add=function(t){this.items.push(t)},n.prototype.clear=function(){this.items=[],this.active=this.component.options.noInitialSelection?-1:0},n.prototype.isEmpty=function(){return!this.items.length},n.prototype.isVisible=function(){return"block"===this.element.style.display},n.prototype.draw=function(){if(this.element.innerHTML="", +0===this.items.length)return void this.hide();for(var t=0;t=this.items.length-1?0:this.active+1)},n.prototype.drawError=function(t){var e=document.createElement("li");e.innerHTML=t,this.element.appendChild(e),this.show()},e.exports=n},{}],10:[function(t,e,i){"use strict";var n=t("xtend"),s=t("fuzzy"),r=t("./list"),o=function(t,e,i){return i=i||{},this.options=n({minLength:2,limit:5,filter:!0,hideOnBlur:!0,noInitialSelection:!0},i),this.el=t,this.data=e||[],this.list=new r(this),this.query="",this.selected=null,this.list.draw(),this.el.addEventListener("keyup",function(t){this.handleKeyUp(t.keyCode,t)}.bind(this),!1),this.el.addEventListener("keydown",function(t){this.handleKeyDown(t)}.bind(this)),this.el.addEventListener("focus",function(){this.handleFocus()}.bind(this)),this.el.addEventListener("blur",function(){this.handleBlur()}.bind(this)),this.el.addEventListener("paste",function(t){this.handlePaste(t)}.bind(this)),this.render=this.options.render?this.options.render.bind(this):this.render.bind(this),this.getItemValue=this.options.getItemValue?this.options.getItemValue.bind(this):this.getItemValue.bind(this),this};o.prototype.handleKeyUp=function(t,e){if(40!==t&&38!==t&&27!==t&&9!==t)return 13===t?void(this.list.items[this.list.active]&&(this.list.handleMouseUp(this.list.items[this.list.active]),e.stopPropagation())):void this.handleInputChange(this.el.value)},o.prototype.handleKeyDown=function(t){switch(t.keyCode){case 13:this.list.active>=0&&(this.list.selectingListItem=!0);break;case 9:this.list.isEmpty()||(this.list.isVisible()&&t.preventDefault(),this.value(this.list.active>=0?this.list.items[this.list.active].original:null),this.list.hide());break;case 27:this.list.isEmpty()||this.list.hide();break;case 38:this.list.previous();break;case 40:this.list.next()}},o.prototype.handleBlur=function(){!this.list.selectingListItem&&this.options.hideOnBlur&&this.list.hide()},o.prototype.handlePaste=function(t){if(t.clipboardData)this.handleInputChange(t.clipboardData.getData("Text"));else{var e=this;setTimeout(function(){e.handleInputChange(t.target.value)},100)}},o.prototype.handleInputChange=function(t){if(this.query=this.normalize(t),this.list.clear(),this.query.length-1},o.prototype.value=function(t){if(this.selected=t,this.el.value=this.getItemValue(t||{place_name:this.query}),document.createEvent){var e=document.createEvent("HTMLEvents");e.initEvent("change",!0,!1),this.el.dispatchEvent(e)}else this.el.fireEvent("onchange")},o.prototype.getCandidates=function(t){var e,i={pre:"",post:"",extract:function(t){return this.getItemValue(t)}.bind(this)};this.options.filter?(e=s.filter(this.query,this.data,i),e=e.map(function(t){return{original:t.original,string:this.render(t.original,t.string)}}.bind(this))):e=this.data.map(function(t){return{original:t,string:this.render(t)}}.bind(this)),t(e)},o.prototype.getItemValue=function(t){return t},o.prototype.render=function(t,e){if(e)return e;for(var i=t.original?this.getItemValue(t.original):this.getItemValue(t),n=this.normalize(i),s=n.lastIndexOf(this.query);s>-1;){var r=s+this.query.length;i=i.slice(0,s)+""+i.slice(s,r)+""+i.slice(r),s=n.slice(0,s).lastIndexOf(this.query)}return i},o.prototype.renderError=function(t){this.list.drawError(t)},e.exports=o},{"./list":9,fuzzy:5,xtend:11}],11:[function(t,e,i){function n(){for(var t={},e=0;e evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/turf_files/maplibregl-binding-0.4.0.9000/maplibregl.js b/docs/articles/turf_files/maplibregl-binding-0.4.0.9000/maplibregl.js new file mode 100644 index 0000000..8558cc4 --- /dev/null +++ b/docs/articles/turf_files/maplibregl-binding-0.4.0.9000/maplibregl.js @@ -0,0 +1,4506 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/turf_files/maplibregl-binding-0.4.0/maplibregl.js b/docs/articles/turf_files/maplibregl-binding-0.4.0/maplibregl.js new file mode 100644 index 0000000..c8312af --- /dev/null +++ b/docs/articles/turf_files/maplibregl-binding-0.4.0/maplibregl.js @@ -0,0 +1,4337 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + + // Event listener for the map + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push(nav); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + map.controls.forEach((control) => { + map.removeControl(control); + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push(customControl); + } + }); +} diff --git a/docs/articles/turf_files/maplibregl-binding-0.4.1/maplibregl.js b/docs/articles/turf_files/maplibregl-binding-0.4.1/maplibregl.js new file mode 100644 index 0000000..5937d02 --- /dev/null +++ b/docs/articles/turf_files/maplibregl-binding-0.4.1/maplibregl.js @@ -0,0 +1,5048 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + const result = originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + return result; + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse( + this.getAttribute("data-layer-ids"), + ); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } + } + }); +} diff --git a/docs/articles/turf_files/maptiler-geocoding-control-2.1.7/LICENSE.txt b/docs/articles/turf_files/maptiler-geocoding-control-2.1.7/LICENSE.txt new file mode 100644 index 0000000..624d1f1 --- /dev/null +++ b/docs/articles/turf_files/maptiler-geocoding-control-2.1.7/LICENSE.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2023, MapTiler +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/articles/turf_files/maptiler-geocoding-control-2.1.7/maplibregl.umd.js b/docs/articles/turf_files/maptiler-geocoding-control-2.1.7/maplibregl.umd.js new file mode 100644 index 0000000..0fe7116 --- /dev/null +++ b/docs/articles/turf_files/maptiler-geocoding-control-2.1.7/maplibregl.umd.js @@ -0,0 +1,14 @@ +(function(j,ee){typeof exports=="object"&&typeof module<"u"?ee(exports,require("maplibre-gl")):typeof define=="function"&&define.amd?define(["exports","maplibre-gl"],ee):(j=typeof globalThis<"u"?globalThis:j||self,ee(j.maplibreglMaptilerGeocoder={},j.maplibregl))})(this,function(j,ee){"use strict";var Ws=Object.defineProperty;var bn=j=>{throw TypeError(j)};var Gs=(j,ee,me)=>ee in j?Ws(j,ee,{enumerable:!0,configurable:!0,writable:!0,value:me}):j[ee]=me;var A=(j,ee,me)=>Gs(j,typeof ee!="symbol"?ee+"":ee,me),wn=(j,ee,me)=>ee.has(j)||bn("Cannot "+me);var ue=(j,ee,me)=>(wn(j,ee,"read from private field"),me?me.call(j):ee.get(j)),Vt=(j,ee,me)=>ee.has(j)?bn("Cannot add the same private member more than once"):ee instanceof WeakSet?ee.add(j):ee.set(j,me),kt=(j,ee,me,dt)=>(wn(j,ee,"write to private field"),dt?dt.call(j,me):ee.set(j,me),me);var fn,cn;function me(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const dt=me(ee);function ne(){}function Ln(i,e){for(const t in e)i[t]=e[t];return i}function yi(i){return i()}function vi(){return Object.create(null)}function Ue(i){i.forEach(yi)}function bi(i){return typeof i=="function"}function Ke(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}let Rt;function ye(i,e){return i===e?!0:(Rt||(Rt=document.createElement("a")),Rt.href=e,i===Rt.href)}function _n(i){return Object.keys(i).length===0}function Sn(i,e,t,n){if(i){const r=wi(i,e,t,n);return i[0](r)}}function wi(i,e,t,n){return i[1]&&n?Ln(t.ctx.slice(),i[1](n(e))):t.ctx}function xn(i,e,t,n){return i[2],e.dirty}function Tn(i,e,t,n,r,u){if(r){const a=wi(e,t,n,u);i.p(a,r)}}function Mn(i){if(i.ctx.length>32){const e=[],t=i.ctx.length/32;for(let n=0;ni.removeEventListener(e,t,n)}function Nn(i){return function(e){return e.preventDefault(),i.call(this,e)}}function S(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function kn(i){return Array.from(i.childNodes)}function gt(i,e){e=""+e,i.data!==e&&(i.data=e)}function Ei(i,e){i.value=e??""}function Ie(i,e,t){i.classList.toggle(e,!!t)}function On(i,e,{bubbles:t=!1,cancelable:n=!1}={}){return new CustomEvent(i,{detail:e,bubbles:t,cancelable:n})}let mt;function pt(i){mt=i}function Li(){if(!mt)throw new Error("Function called outside component initialization");return mt}function Rn(i){Li().$$.on_destroy.push(i)}function _i(){const i=Li();return(e,t,{cancelable:n=!1}={})=>{const r=i.$$.callbacks[e];if(r){const u=On(e,t,{cancelable:n});return r.slice().forEach(a=>{a.call(i,u)}),!u.defaultPrevented}return!0}}function Pn(i,e){const t=i.$$.callbacks[e.type];t&&t.slice().forEach(n=>n.call(this,e))}const ut=[],Yt=[];let at=[];const Si=[],In=Promise.resolve();let Qt=!1;function An(){Qt||(Qt=!0,In.then(xi))}function Xt(i){at.push(i)}const Jt=new Set;let ft=0;function xi(){if(ft!==0)return;const i=mt;do{try{for(;fti.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),at=e}const It=new Set;let nt;function yt(){nt={r:0,c:[],p:nt}}function vt(){nt.r||Ue(nt.c),nt=nt.p}function re(i,e){i&&i.i&&(It.delete(i),i.i(e))}function fe(i,e,t,n){if(i&&i.o){if(It.has(i))return;It.add(i),nt.c.push(()=>{It.delete(i),n&&(t&&i.d(1),n())}),i.o(e)}else n&&n()}function Ti(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function Gn(i,e){fe(i,1,1,()=>{e.delete(i.key)})}function Dn(i,e,t,n,r,u,a,o,g,c,E,_){let M=i.length,R=u.length,k=M;const I={};for(;k--;)I[i[k].key]=k;const C=[],O=new Map,x=new Map,N=[];for(k=R;k--;){const W=_(r,u,k),s=t(W);let l=a.get(s);l?N.push(()=>l.p(W,e)):(l=c(s,W),l.c()),O.set(s,C[k]=l),s in I&&x.set(s,Math.abs(k-I[s]))}const P=new Set,B=new Set;function z(W){re(W,1),W.m(o,E),a.set(W.key,W),E=W.first,R--}for(;M&&R;){const W=C[R-1],s=i[M-1],l=W.key,f=s.key;W===s?(E=W.first,M--,R--):O.has(f)?!a.has(l)||P.has(l)?z(W):B.has(f)?M--:x.get(l)>x.get(f)?(B.add(l),z(W)):(P.add(f),M--):(g(s,a),M--)}for(;M--;){const W=i[M];O.has(W.key)||g(W,a)}for(;R;)z(C[R-1]);return Ue(N),C}function Qe(i){i&&i.c()}function qe(i,e,t){const{fragment:n,after_update:r}=i.$$;n&&n.m(e,t),Xt(()=>{const u=i.$$.on_mount.map(yi).filter(bi);i.$$.on_destroy?i.$$.on_destroy.push(...u):Ue(u),i.$$.on_mount=[]}),r.forEach(Xt)}function Fe(i,e){const t=i.$$;t.fragment!==null&&(Wn(t.after_update),Ue(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function zn(i,e){i.$$.dirty[0]===-1&&(ut.push(i),An(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<{const k=R.length?R[0]:M;return c.ctx&&r(c.ctx[_],c.ctx[_]=k)&&(!c.skip_bound&&c.bound[_]&&c.bound[_](k),E&&zn(i,_)),M}):[],c.update(),E=!0,Ue(c.before_update),c.fragment=n?n(c.ctx):!1,e.target){if(e.hydrate){const _=kn(e.target);c.fragment&&c.fragment.l(_),_.forEach($)}else c.fragment&&c.fragment.c();e.intro&&re(i.$$.fragment),qe(i,e.target,e.anchor),xi()}pt(g)}class Je{constructor(){A(this,"$$");A(this,"$$set")}$destroy(){Fe(this,1),this.$destroy=ne}$on(e,t){if(!bi(t))return ne;const n=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return n.push(t),()=>{const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}$set(e){this.$$set&&!_n(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Un="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Un);function qn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M13.12.706a.982.982 0 0 0-1.391 0L6.907 5.517 2.087.696a.982.982 0 1 0-1.391 1.39l4.821 4.821L.696 11.73a.982.982 0 1 0 1.39 1.39l4.821-4.821 4.822 4.821a.982.982 0 1 0 1.39-1.39L8.298 6.908l4.821-4.822a.988.988 0 0 0 0-1.38Z"),S(e,"viewBox","0 0 14 14"),S(e,"width","13"),S(e,"height","13"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Mi extends Je{constructor(e){super(),Xe(this,e,null,qn,Ke,{})}}function Fn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M15 0C6.705 0 0 6.705 0 15C0 23.295 6.705 30 15 30C23.295 30 30 23.295 30 15C30 6.705 23.295 0 15 0ZM22.5 20.385L20.385 22.5L15 17.115L9.615 22.5L7.5 20.385L12.885 15L7.5 9.615L9.615 7.5L15 12.885L20.385 7.5L22.5 9.615L17.115 15L22.5 20.385Z"),S(e,"viewBox","0 0 30 30"),S(e,"fill","none"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"class","svelte-d2loi5")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Ci extends Je{constructor(e){super(),Xe(this,e,null,Fn,Ke,{})}}function jn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"area.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"area.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Zn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"reverse.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"reverse.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Hn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"poi.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"poi.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Vn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"postal_code.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"postal_code.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Kn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"street.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"street.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Yn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"road.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"road.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Qn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"housenumber.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"housenumber.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Xn(i){let e,t,n,r;return{c(){e=Y("img"),ye(e.src,t=i[5])||S(e,"src",t),S(e,"alt",i[4]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(u,a){te(u,e,a),n||(r=he(e,"error",i[14]),n=!0)},p(u,a){a&32&&!ye(e.src,t=u[5])&&S(e,"src",t),a&16&&S(e,"alt",u[4]),a&128&&S(e,"title",u[7])},d(u){u&&$(e),n=!1,r()}}}function Jn(i){let e,t;return{c(){e=Y("div"),S(e,"class","sprite-icon svelte-w9y5n9"),S(e,"style",t=` + width: ${i[6].width/xe}px; + height: ${i[6].height/xe}px; + background-image: url(${i[3]}sprite${$t}.png); + background-position: -${i[6].x/xe}px -${i[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `),S(e,"title",i[7])},m(n,r){te(n,e,r)},p(n,r){r&72&&t!==(t=` + width: ${n[6].width/xe}px; + height: ${n[6].height/xe}px; + background-image: url(${n[3]}sprite${$t}.png); + background-position: -${n[6].x/xe}px -${n[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `)&&S(e,"style",t),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Ni(i){let e,t;return{c(){e=Y("span"),t=Ye(i[7]),S(e,"class","secondary svelte-w9y5n9")},m(n,r){te(n,e,r),V(e,t)},p(n,r){r&128&>(t,n[7])},d(n){n&&$(e)}}}function $n(i){let e,t,n,r,u,a,o,g,c,E=(i[8]?i[0].place_name:i[0].place_name.replace(/,.*/,""))+"",_,M,R=i[2]==="always"||i[2]!=="never"&&!i[0].address&&!i[0].id.startsWith("road.")&&!i[0].id.startsWith("address.")&&!i[0].id.startsWith("postal_code.")&&(!i[0].id.startsWith("poi.")||!i[5])&&!i[8],k,I,C=(i[8]?"":i[0].place_name.replace(/[^,]*,?\s*/,""))+"",O,x,N,P,B,z;function W(m,h){return h&1&&(t=null),h&1&&(n=null),h&1&&(r=null),h&1&&(u=null),Oe&&m[6]?Jn:m[5]?Xn:m[0].address?Qn:(t==null&&(t=!!m[0].id.startsWith("road.")),t?Yn:(n==null&&(n=!!m[0].id.startsWith("address.")),n?Kn:(r==null&&(r=!!m[0].id.startsWith("postal_code.")),r?Vn:(u==null&&(u=!!m[0].id.startsWith("poi.")),u?Hn:m[8]?Zn:jn))))}let s=W(i,-1),l=s(i),f=R&&Ni(i);return{c(){e=Y("li"),l.c(),a=we(),o=Y("span"),g=Y("span"),c=Y("span"),_=Ye(E),M=we(),f&&f.c(),k=we(),I=Y("span"),O=Ye(C),S(c,"class","primary svelte-w9y5n9"),S(g,"class","svelte-w9y5n9"),S(I,"class","line2 svelte-w9y5n9"),S(o,"class","texts svelte-w9y5n9"),S(e,"tabindex","-1"),S(e,"role","option"),S(e,"aria-selected",x=i[1]==="selected"),S(e,"aria-checked",N=i[1]==="picked"),S(e,"class",P=Pt(i[1])+" svelte-w9y5n9")},m(m,h){te(m,e,h),l.m(e,null),V(e,a),V(e,o),V(o,g),V(g,c),V(c,_),V(g,M),f&&f.m(g,null),V(o,k),V(o,I),V(I,O),B||(z=[he(e,"mouseenter",i[13]),he(e,"focus",i[15]),he(e,"click",i[16])],B=!0)},p(m,[h]){s===(s=W(m,h))&&l?l.p(m,h):(l.d(1),l=s(m),l&&(l.c(),l.m(e,a))),h&257&&E!==(E=(m[8]?m[0].place_name:m[0].place_name.replace(/,.*/,""))+"")&>(_,E),h&293&&(R=m[2]==="always"||m[2]!=="never"&&!m[0].address&&!m[0].id.startsWith("road.")&&!m[0].id.startsWith("address.")&&!m[0].id.startsWith("postal_code.")&&(!m[0].id.startsWith("poi.")||!m[5])&&!m[8]),R?f?f.p(m,h):(f=Ni(m),f.c(),f.m(g,null)):f&&(f.d(1),f=null),h&257&&C!==(C=(m[8]?"":m[0].place_name.replace(/[^,]*,?\s*/,""))+"")&>(O,C),h&2&&x!==(x=m[1]==="selected")&&S(e,"aria-selected",x),h&2&&N!==(N=m[1]==="picked")&&S(e,"aria-checked",N),h&2&&P!==(P=Pt(m[1])+" svelte-w9y5n9")&&S(e,"class",P)},i:ne,o:ne,d(m){m&&$(e),l.d(),f&&f.d(),B=!1,Ue(z)}}}const ki=typeof devicePixelRatio>"u"?1:devicePixelRatio>1.25,$t=ki?"@2x":"",xe=ki?2:1;let Oe,At;function er(i,e,t){let n,r,u,{feature:a}=e,{style:o="default"}=e,{showPlaceType:g}=e,{missingIconsCache:c}=e,{iconsBaseUrl:E}=e;const _=_i();let M,R,k,I;function C(){At??(At=fetch(`${E}sprite${$t}.json`).then(s=>s.json()).then(s=>{Oe=s}).catch(()=>{Oe=null}))}function O(){R&&c.add(R),x()}function x(){Oe!==void 0?N():(C(),At==null||At.then(N))}function N(){do{if(I--,t(4,M=n==null?void 0:n[I]),t(6,k=M?Oe==null?void 0:Oe.icons[M]:void 0),k)break;t(5,R=M?E+M.replace(/ /g,"_")+".svg":void 0)}while(I>-1&&(!R||c.has(R)))}function P(s){Pn.call(this,i,s)}const B=()=>O(),z=()=>_("select",void 0),W=s=>{document.activeElement!==s.target&&_("select",void 0)};return i.$$set=s=>{"feature"in s&&t(0,a=s.feature),"style"in s&&t(1,o=s.style),"showPlaceType"in s&&t(2,g=s.showPlaceType),"missingIconsCache"in s&&t(11,c=s.missingIconsCache),"iconsBaseUrl"in s&&t(3,E=s.iconsBaseUrl)},i.$$.update=()=>{var s,l,f,m,h;i.$$.dirty&1&&t(12,n=(s=a.properties)==null?void 0:s.categories),i.$$.dirty&1&&t(8,r=a.place_type[0]==="reverse"),i.$$.dirty&1&&t(7,u=((f=(l=a.properties)==null?void 0:l.categories)==null?void 0:f.join(", "))??((h=(m=a.properties)==null?void 0:m.place_type_name)==null?void 0:h[0])??a.place_type[0]),i.$$.dirty&4096&&(I=(n==null?void 0:n.length)??0,x())},[a,o,g,E,M,R,k,u,r,_,O,c,n,P,B,z,W]}class tr extends Je{constructor(e){super(),Xe(this,e,er,$n,Ke,{feature:0,style:1,showPlaceType:2,missingIconsCache:11,iconsBaseUrl:3})}}function ir(i){let e;return{c(){e=Y("div"),e.innerHTML='',S(e,"class","svelte-1ocfouu")},m(t,n){te(t,e,n)},p:ne,i:ne,o:ne,d(t){t&&$(e)}}}class nr extends Je{constructor(e){super(),Xe(this,e,null,ir,Ke,{})}}function rr(i){let e,t,n;return{c(){e=ke("svg"),t=ke("path"),S(t,"stroke-width","4"),S(t,"d","M 5,33.103579 C 5,17.607779 18.457,5 35,5 C 51.543,5 65,17.607779 65,33.103579 C 65,56.388679 40.4668,76.048179 36.6112,79.137779 C 36.3714,79.329879 36.2116,79.457979 36.1427,79.518879 C 35.8203,79.800879 35.4102,79.942779 35,79.942779 C 34.5899,79.942779 34.1797,79.800879 33.8575,79.518879 C 33.7886,79.457979 33.6289,79.330079 33.3893,79.138079 C 29.5346,76.049279 5,56.389379 5,33.103579 Z M 35.0001,49.386379 C 43.1917,49.386379 49.8323,42.646079 49.8323,34.331379 C 49.8323,26.016779 43.1917,19.276479 35.0001,19.276479 C 26.8085,19.276479 20.1679,26.016779 20.1679,34.331379 C 20.1679,42.646079 26.8085,49.386379 35.0001,49.386379 Z"),S(t,"class","svelte-gzo3ar"),S(e,"width",n=i[0]==="list"?20:void 0),S(e,"viewBox","0 0 70 85"),S(e,"fill","none"),S(e,"class","svelte-gzo3ar"),Ie(e,"in-map",i[0]!=="list"),Ie(e,"list-icon",i[0]==="list")},m(r,u){te(r,e,u),V(e,t)},p(r,[u]){u&1&&n!==(n=r[0]==="list"?20:void 0)&&S(e,"width",n),u&1&&Ie(e,"in-map",r[0]!=="list"),u&1&&Ie(e,"list-icon",r[0]==="list")},i:ne,o:ne,d(r){r&&$(e)}}}function sr(i,e,t){let{displayIn:n}=e;return i.$$set=r=>{"displayIn"in r&&t(0,n=r.displayIn)},[n]}class or extends Je{constructor(e){super(),Xe(this,e,sr,rr,Ke,{displayIn:0})}}function lr(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M30.003-26.765C13.46-26.765 0-14.158 0 1.337c0 23.286 24.535 42.952 28.39 46.04.24.192.402.316.471.376.323.282.732.424 1.142.424.41 0 .82-.142 1.142-.424.068-.06.231-.183.471-.376 3.856-3.09 28.39-22.754 28.39-46.04 0-15.495-13.46-28.102-30.003-28.102Zm1.757 12.469c4.38 0 7.858 1.052 10.431 3.158 2.595 2.105 3.89 4.913 3.89 8.422 0 2.34-.53 4.362-1.593 6.063-1.063 1.702-3.086 3.616-6.063 5.742-2.042 1.51-3.337 2.659-3.89 3.446-.532.787-.8 1.82-.8 3.096v1.914h-8.449V15.18c0-2.041.434-3.815 1.306-5.325.872-1.51 2.467-3.118 4.785-4.82 2.233-1.594 3.7-2.89 4.402-3.889a5.582 5.582 0 0 0 1.087-3.35c0-1.382-.51-2.435-1.531-3.158-1.02-.723-2.45-1.087-4.28-1.087-3.19 0-6.826 1.047-10.91 3.131l-3.472-6.986c4.742-2.659 9.77-3.992 15.087-3.992Zm-1.88 37.324c1.765 0 3.124.472 4.08 1.408.98.936 1.47 2.276 1.47 4.02 0 1.68-.49 3.007-1.47 3.985-.977.957-2.336 1.435-4.08 1.435-1.787 0-3.171-.465-4.15-1.4-.978-.958-1.47-2.298-1.47-4.02 0-1.787.48-3.14 1.436-4.054.957-.915 2.355-1.374 4.184-1.374Z"),S(e,"viewBox","0 0 60.006 21.412"),S(e,"width","14"),S(e,"height","20"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class ur extends Je{constructor(e){super(),Xe(this,e,null,lr,Ke,{})}}function ar(i){let e,t,n;return{c(){e=ke("svg"),t=ke("circle"),n=ke("path"),S(t,"cx","4.789"),S(t,"cy","4.787"),S(t,"r","3.85"),S(t,"class","svelte-1aq105l"),S(n,"d","M12.063 12.063 7.635 7.635"),S(n,"class","svelte-1aq105l"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"width","13"),S(e,"height","13"),S(e,"viewBox","0 0 13 13"),S(e,"class","svelte-1aq105l")},m(r,u){te(r,e,u),V(e,t),V(e,n)},p:ne,i:ne,o:ne,d(r){r&&$(e)}}}class fr extends Je{constructor(e){super(),Xe(this,e,null,ar,Ke,{})}}function cr(i,e,t){const n=e[1],r=e[0],u=n-r;return i===n&&t?i:((i-r)%u+u)%u+r}function Bt(i){const e=[...i];return e[2]Math.abs((e[0]-360+e[2])/2)?e[0]-=360:e[2]+=360),e}let bt;async function hr(i,e,t){const n=i==null?void 0:i.getCenterAndZoom();for(const r of e??[])if(!(n&&(r.minZoom!=null&&r.minZoom>n[0]||r.maxZoom!=null&&r.maxZoomDate.now()){if(!bt.coords)break e;return bt.coords}let u;try{return u=await new Promise((a,o)=>{t.signal.addEventListener("abort",()=>{o(Error("aborted"))}),navigator.geolocation.getCurrentPosition(g=>{a([g.coords.longitude,g.coords.latitude].map(c=>c.toFixed(6)).join(","))},g=>{o(g)},r)}),u}catch{}finally{r.cachedLocationExpiry&&(bt={time:Date.now(),coords:u})}if(t.signal.aborted)return}if(r.type==="server-geolocation")return"ip";if(n&&r.type==="map-center")return n[1].toFixed(6)+","+n[2].toFixed(6)}}const dr=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(EAST|WEST|[EW])?$/i,Oi=/^([+-]?[0-8]?[0-9])\s+([0-5]?[0-9]\.\d{3,})[\s,]{1,}([+-]?[0-1]?[0-9]?[0-9])\s+([0-5]?[0-9]\.\d{3,})$/,Ri=/^(NORTH|SOUTH|[NS])?[\s]*([+-]?[0-8]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(NORTH|SOUTH|[NS])?[\s]*[,/;]?[\s]*(EAST|WEST|[EW])?[\s]*([+-]?[0-1]?[0-9]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(EAST|WEST|[EW])?$/i,Pi=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(EAST|WEST|[EW])?$/i,Ii=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)\s*(EAST|WEST|[EW])?$/i,Ai=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|’’|´´|["″”\.])?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|´´|’’|["″”\.])?\s*(EAST|WEST|[EW])?$/i;function gr(i){if(!["DMS","DM","DD"].includes(i))throw new Error("invalid format specified");if(this.decimalCoordinates&&this.decimalCoordinates.trim()){const e=this.decimalCoordinates.split(",").map(R=>Number(R.trim())),t=Number(e[0]),n=Number(e[1]),r=Math.abs(t),u=Math.abs(n),a=t>0?"N":"S",o=n>0?"E":"W";let g;i=="DD"&&(g=`${r}° ${a}, ${u}° ${o}`);const c=Math.floor(r),E=Math.floor(u),_=(r-c)*60,M=(u-E)*60;if(i=="DM"){let R=Bi(_,3).toFixed(3).padStart(6,"0"),k=Bi(M,3).toFixed(3).padStart(6,"0");R.endsWith(".000")&&k.endsWith(".000")&&(R=R.replace(/\.000$/,""),k=k.replace(/\.000$/,"")),g=`${c}° ${R}' ${a}, ${E}° ${k}' ${o}`}if(i=="DMS"){const R=Math.floor(_),k=Math.floor(M);let I=((_-R)*60).toFixed(1).padStart(4,"0"),C=((M-k)*60).toFixed(1).padStart(4,"0");const O=R.toString().padStart(2,"0"),x=k.toString().padStart(2,"0");I.endsWith(".0")&&C.endsWith(".0")&&(I=I.replace(/\.0$/,""),C=C.replace(/\.0$/,"")),g=`${c}° ${O}' ${I}" ${a}, ${E}° ${x}' ${C}" ${o}`}return g}else throw new Error("no decimal coordinates to convert")}function Bi(i,e){const t=Math.pow(10,e);return Math.round((i+Number.EPSILON)*t)/t}function ei(i,e){e||(e=5),i=i.replace(/\s+/g," ").trim();let t=null,n=null,r="",u="",a=null,o=[],g=!1;if(dr.test(i))throw new Error("invalid coordinate value");if(Oi.test(i))if(o=Oi.exec(i),g=wt(o),g)t=Math.abs(o[1])+o[2]/60,Number(o[1])<0&&(t*=-1),n=Math.abs(o[3])+o[4]/60,Number(o[3])<0&&(n*=-1),a="DM";else throw new Error("invalid coordinate format");else if(Ri.test(i))if(o=Ri.exec(i),g=wt(o),g){if(t=o[2],n=o[6],t.includes(",")&&(t=t.replace(",",".")),n.includes(",")&&(n=n.replace(",",".")),a="DD",Number(Math.round(t))==Number(t))throw new Error("integer only coordinate provided");if(Number(Math.round(n))==Number(n))throw new Error("integer only coordinate provided");o[1]?(r=o[1],u=o[5]):o[4]&&(r=o[4],u=o[8])}else throw new Error("invalid decimal coordinate format");else if(Pi.test(i))if(o=Pi.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[9])),o[11]&&(n+=o[11]/60),o[13]&&(n+=o[13].replace(",",".")/3600),parseInt(o[9])<0&&(n=-1*n),o[1]?(r=o[1],u=o[8]):o[7]&&(r=o[7],u=o[14]);else throw new Error("invalid DMS coordinates format");else if(Ii.test(i))if(o=Ii.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6]/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12]/60),o[14]&&(n+=o[14]/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid DMS coordinates format");else if(Ai.test(i)){if(o=Ai.exec(i),g=wt(o),o.filter(c=>c).length<=5)throw new Error("invalid coordinates format");if(g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4].replace(",",".")/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12].replace(",",".")/60),o[14]&&(n+=o[14].replace(",",".")/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid coordinates format")}if(g){if(Math.abs(n)>=180)throw new Error("invalid longitude value");if(Math.abs(t)>=90)throw new Error("invalid latitude value");if(r&&!u||!r&&u)throw new Error("invalid coordinates value");if(r&&r==u)throw new Error("invalid coordinates format");t.toString().includes(",")&&(t=t.replace(",",".")),n.toString().includes(",")&&(n=n.replace(",","."));let c=/S|SOUTH/i;c.test(r)&&t>0&&(t=-1*t),c=/W|WEST/i,c.test(u)&&n>0&&(n=-1*n);const E=o[0].trim();let _,M;const R=/[,/;\u0020]/g,k=E.match(R);if(k==null){const O=Math.floor(i.length/2);_=E.substring(0,O).trim(),M=E.substring(O).trim()}else{let O;k.length%2==1?O=Math.floor(k.length/2):O=k.length/2-1;let x=0;if(O==0)x=E.indexOf(k[0]),_=E.substring(0,x).trim(),M=E.substring(x+1).trim();else{let N=0,P=0;for(;N<=O;)x=E.indexOf(k[N],P),P=x+1,N++;_=E.substring(0,x).trim(),M=E.substring(x+1).trim()}}const I=_.split(".");if(I.length==2&&I[1]==0&&I[1].length!=2)throw new Error("invalid coordinates format");const C=M.split(".");if(C.length==2&&C[1]==0&&C[1].length!=2)throw new Error("invalid coordinates format");if(/^\d+$/.test(_)||/^\d+$/.test(M))throw new Error("degree only coordinate/s provided");return t=Number(Number(t).toFixed(e)),n=Number(Number(n).toFixed(e)),Object.freeze({verbatimCoordinates:E,verbatimLatitude:_,verbatimLongitude:M,decimalLatitude:t,decimalLongitude:n,decimalCoordinates:`${t},${n}`,originalFormat:a,closeEnough:mr,toCoordinateFormat:gr})}else throw new Error("coordinates pattern match failed")}function wt(i){if(!isNaN(i[0]))return!1;const e=[...i];if(e.shift(),e.length%2>0)return!1;const t=/^[-+]?\d+([\.,]\d+)?$/,n=/[eastsouthnorthwest]+/i,r=e.length/2;for(let u=0;u{e.decimalLatitude?i.push(e):i.push({...e,...vr})}),[...i,...br,...wr]}const Lr=Er();ei.formats=Lr.map(i=>i.verbatimCoordinates);const _r=ei;function Gi(i,e,t){const n=i.slice();return n[97]=e[t],n[99]=t,n}function Di(i){let e,t,n,r,u;return t=new Mi({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[3]),S(e,"class","svelte-bz0zu3")},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[78]),r=!0)},p(a,o){(!n||o[0]&8)&&S(e,"title",a[3])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function zi(i){let e,t;return e=new nr({}),{c(){Qe(e.$$.fragment)},m(n,r){qe(e,n,r),t=!0},i(n){t||(re(e.$$.fragment,n),t=!0)},o(n){fe(e.$$.fragment,n),t=!1},d(n){Fe(e,n)}}}function Ui(i){let e,t,n,r,u;return t=new ur({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[10]),S(e,"class","svelte-bz0zu3"),Ie(e,"active",i[0])},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[79]),r=!0)},p(a,o){(!n||o[0]&1024)&&S(e,"title",a[10]),(!n||o[0]&1)&&Ie(e,"active",a[0])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function Sr(i){let e,t=[],n=new Map,r,u,a,o=Ti(i[13]);const g=c=>c[97].id+(c[97].address?","+c[97].address:"");for(let c=0;c{B=null}),vt()):B?(B.p(d,v),v[0]&1048576&&re(B,1)):(B=Di(d),B.c(),re(B,1),B.m(c,E)),d[20]?z?v[0]&1048576&&re(z,1):(z=zi(),z.c(),re(z,1),z.m(c,null)):z&&(yt(),fe(z,1,1,()=>{z=null}),vt()),(!O||v[0]&2)&&Ie(c,"displayable",d[1]!==""),d[6]==="button"?W?(W.p(d,v),v[0]&64&&re(W,1)):(W=Ui(d),W.c(),re(W,1),W.m(n,M)):W&&(yt(),fe(W,1,1,()=>{W=null}),vt()),l&&l.p&&(!O||v[2]&128)&&Tn(l,s,d,d[69],O?xn(s,d[69],v,null):Mn(d[69]),null);let p=k;k=h(d),k===p?~k&&m[k].p(d,v):(I&&(yt(),fe(m[p],1,1,()=>{m[p]=null}),vt()),~k?(I=m[k],I?I.p(d,v):(I=m[k]=f[k](d),I.c()),re(I,1),I.m(t,null)):I=null),(!O||v[0]&4&&C!==(C=Pt(d[2])+" svelte-bz0zu3"))&&S(t,"class",C),(!O||v[0]&38)&&Ie(t,"can-collapse",d[5]&&d[1]==="")},i(d){O||(re(P),re(u.$$.fragment,d),re(B),re(z),re(W),re(l,d),re(I),O=!0)},o(d){fe(P),fe(u.$$.fragment,d),fe(B),fe(z),fe(W),fe(l,d),fe(I),O=!1},d(d){d&&($(e),$(t)),Fe(u),i[72](null),B&&B.d(),z&&z.d(),W&&W.d(),l&&l.d(d),~k&&m[k].d(),x=!1,Ue(N)}}}function Nr(i,e,t){let n,r,u,{$$slots:a={},$$scope:o}=e;const g={continental_marine:4,country:4,major_landform:8,region:5,subregion:6,county:7,joint_municipality:8,joint_submunicipality:9,municipality:10,municipal_district:11,locality:12,neighbourhood:13,place:14,postal_code:14,road:16,poi:17,address:18,"poi.peak":15,"poi.shop":18,"poi.cafe":18,"poi.restaurant":18,"poi.aerodrome":13};let{class:c=void 0}=e,{apiKey:E=void 0}=e,{bbox:_=void 0}=e,{clearButtonTitle:M="clear"}=e,{clearOnBlur:R=!1}=e,{clearListOnPick:k=!1}=e,{keepListOpen:I=!1}=e,{collapsed:C=!1}=e,{country:O=void 0}=e,{debounceSearch:x=200}=e,{enableReverse:N="never"}=e,{errorMessage:P="Something went wrong…"}=e,{filter:B=()=>!0}=e,{flyTo:z=!0}=e,{fuzzyMatch:W=!0}=e,{language:s=void 0}=e,{limit:l=void 0}=e;const f=41415112612;let{reverseGeocodingLimit:m=f}=e,{mapController:h=void 0}=e,{minLength:d=2}=e,{noResultsMessage:v="Oops! Looks like you're trying to predict something that's not quite right. We can't seem to find what you're looking for. Maybe try double-checking your spelling or try a different search term. Keep on typing - we'll do our best to get you where you need to go!"}=e,{placeholder:p="Search"}=e,{proximity:y=[{type:"server-geolocation"}]}=e,{reverseActive:b=N==="always"}=e,{reverseButtonTitle:w="toggle reverse geocoding"}=e,{searchValue:T=""}=e,{pickedResultStyle:G="full-geometry"}=e,{showPlaceType:D="if-needed"}=e,{showResultsWhileTyping:H=!0}=e,{selectFirst:Q=!0}=e,{flyToSelected:se=!1}=e,{markerOnSelected:Z=!0}=e,{types:K=void 0}=e;const de=[];let{reverseGeocodingTypes:He=de}=e,{exhaustiveReverseGeocoding:st=!1}=e,{excludeTypes:ot=!1}=e;const Le=void 0;let{reverseGeocodingExcludeTypes:We=Le}=e,{zoom:pe=g}=e,{apiUrl:ge="https://api.maptiler.com/geocoding"}=e,{fetchParameters:ie={}}=e,{iconsBaseUrl:hn="https://cdn.maptiler.com/maptiler-geocoding-control/v2.1.7/icons/"}=e,{adjustUrlQuery:ui=()=>{}}=e,{adjustUrl:ai=()=>{}}=e;function gs(L){Pe.focus(L)}function ms(){Pe.blur()}function dn(L,le=!0,ae=!1){t(1,T=L),le?(t(15,X=-1),mn()):(pn(void 0,!ae,ae),setTimeout(()=>{Pe.focus(),Pe.select()}))}function ps(){t(13,F=void 0),t(14,U=void 0),t(15,X=-1)}function ys(){t(64,ce=[]),t(14,U=void 0)}let F,ce,U,gn="",Pe,X=-1,Ge,Zt=[],lt,ct,ht,fi,Ve=!1;const vs=new Set,tt=_i();Rn(()=>{h&&(h.setEventHandler(void 0),h.indicateReverse(!1),h.setSelectedMarker(-1),h.setFeatures(void 0,void 0,!1))});function mn(L){if(t(17,Ve=!1),ct&&(clearTimeout(ct),ct=void 0),X>-1&&F)t(14,U=F[X]),t(1,T=U.place_type[0]==="reverse"?U.place_name:U.place_name.replace(/,.*/,"")),t(19,Ge=void 0),t(64,ce=void 0),t(15,X=-1);else if(T){const le=L||!ci(T);hi(T,{exact:!0}).then(()=>{t(64,ce=F),t(14,U=void 0),le&&bs()}).catch(ae=>t(19,Ge=ae))}}function ci(L){try{return _r(L,6)}catch{return!1}}async function hi(L,{byId:le=!1,exact:ae=!1}={}){var Se,De,it;t(19,Ge=void 0),lt==null||lt.abort();const _e=new AbortController;t(20,lt=_e);try{const J=ci(L),Mt=new URL(ge+"/"+encodeURIComponent(J?J.decimalLongitude+","+J.decimalLatitude:L)+".json"),Ne=Mt.searchParams;s!==void 0&&Ne.set("language",Array.isArray(s)?s.join(","):s??"");const[mi]=(h==null?void 0:h.getCenterAndZoom())??[];let ze=(Se=!J||He===de?K:He)==null?void 0:Se.map(ve=>typeof ve=="string"?ve:mi===void 0||(ve[0]??0)<=mi&&mi<(ve[1]??1/0)?ve[2]:void 0).filter(ve=>ve!==void 0);ze&&(ze=[...new Set(ze)],Ne.set("types",ze.join(",")));const vn=!J||We===Le?ot:We;if(vn&&Ne.set("excludeTypes",String(vn)),_&&Ne.set("bbox",_.map(ve=>ve.toFixed(6)).join(",")),O&&Ne.set("country",Array.isArray(O)?O.join(","):O),!le&&!J){const ve=await hr(h,y,_e);ve&&Ne.set("proximity",ve),(ae||!H)&&Ne.set("autocomplete","false"),Ne.set("fuzzyMatch",String(W))}const Ct=m===f?l:m;Ct!==void 0&&Ct>1&&(ze==null?void 0:ze.length)!==1&&console.warn("For reverse geocoding when limit > 1 then types must contain single value."),J?(Ct===1||Ct!==void 0&&(st||(ze==null?void 0:ze.length)===1))&&Ne.set("limit",String(Ct)):l!==void 0&&Ne.set("limit",String(l)),E&&Ne.set("key",E),ui(Ne),ai(Mt);const Bs=Mt.searchParams.get("types")===""&&Mt.searchParams.get("excludeTypes")!=="true",Ht=Mt.toString();if(Ht===gn){le?(k&&t(13,F=void 0),t(14,U=Zt[0])):(t(13,F=Zt),((De=F[X])==null?void 0:De.id)!==(r==null?void 0:r.id)&&t(15,X=-1));return}gn=Ht;let Nt;if(Bs)Nt={type:"FeatureCollection",features:[]};else{const ve=await fetch(Ht,{signal:_e.signal,...ie});if(!ve.ok)throw new Error(await ve.text());Nt=await ve.json()}tt("response",{url:Ht,featureCollection:Nt}),le?(k&&t(13,F=void 0),t(14,U=Nt.features[0]),Zt=[U]):(t(13,F=Nt.features.filter(B)),J&&F.unshift({type:"Feature",properties:{},id:"reverse_"+J.decimalLongitude+"_"+J.decimalLatitude,text:J.decimalLatitude+", "+J.decimalLongitude,place_name:J.decimalLatitude+", "+J.decimalLongitude,place_type:["reverse"],center:[J.decimalLongitude,J.decimalLatitude],bbox:[J.decimalLongitude,J.decimalLatitude,J.decimalLongitude,J.decimalLatitude],geometry:{type:"Point",coordinates:[J.decimalLongitude,J.decimalLatitude]}}),Zt=F,((it=F[X])==null?void 0:it.id)!==(r==null?void 0:r.id)&&t(15,X=-1),J&&Pe.focus())}catch(J){if(J&&typeof J=="object"&&"name"in J&&J.name==="AbortError")return;throw J}finally{_e===lt&&t(20,lt=void 0)}}function bs(){var _e;if(!(ce!=null&&ce.length)||!z)return;const L=[180,90,-180,-90],le=!ce.some(Se=>!Se.matching_text);let ae;for(const Se of ce){const De=Tt(Se);if(ae=ae===void 0?De:De===void 0?ae:Math.max(ae,De),le||!Se.matching_text)for(const it of[0,1,2,3])L[it]=Math[it<2?"min":"max"](L[it],((_e=Se.bbox)==null?void 0:_e[it])??Se.center[it%2])}h&&ce.length>0&&(U&&L[0]===L[2]&&L[1]===L[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(L),50,ae))}function di(){!U||!h||(!U.bbox||U.bbox[0]===U.bbox[2]&&U.bbox[1]===U.bbox[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(U.bbox),50,Tt(U)))}function Tt(L){var ae;if(!L.bbox||L.bbox[0]!==L.bbox[2]&&L.bbox[1]!==L.bbox[3])return;const le=L.id.replace(/\..*/,"");return(Array.isArray((ae=L.properties)==null?void 0:ae.categories)?L.properties.categories.reduce((_e,Se)=>{const De=pe[le+"."+Se];return _e===void 0?De:De===void 0?_e:Math.max(_e,De)},void 0):void 0)??pe[le]}function ws(L){t(0,b=N==="always"),t(13,F=void 0),t(14,U=void 0),t(15,X=-1),dn(L[1].toFixed(6)+", "+cr(L[0],[-180,180],!0).toFixed(6),!1,!0)}function Es(L){if(!F)return;let le=L.key==="ArrowDown"?1:L.key==="ArrowUp"?-1:0;le&&(Pe.focus(),t(17,Ve=!0),L.preventDefault(),U&&X===-1&&t(15,X=F.findIndex(ae=>ae.id===(U==null?void 0:U.id))),X===(U||Q?0:-1)&&le===-1&&t(15,X=F.length),t(15,X+=le),X>=F.length&&t(15,X=-1),X<0&&(U||Q)&&t(15,X=0))}function pn(L,le=!0,ae=!1){if(t(19,Ge=void 0),t(14,U=void 0),t(17,Ve=!0),H||ae){if(ct&&clearTimeout(ct),T.length{hi(_e).catch(Se=>t(19,Ge=Se))},le?x:0)}else t(13,F=void 0),t(19,Ge=void 0)}function gi(L){U&&(U==null?void 0:U.id)===(L==null?void 0:L.id)?di():(t(14,U=L),t(1,T=L.place_name))}function yn(L){t(15,X=L)}function Ls(){(!Q||U)&&t(15,X=-1),se&&di()}const _s=()=>Pe.focus();function Ss(L){Yt[L?"unshift":"push"](()=>{Pe=L,t(18,Pe)})}function xs(){T=this.value,t(1,T),t(17,Ve),t(31,R),t(16,ht)}const Ts=()=>t(17,Ve=!0),Ms=()=>t(17,Ve=!1),Cs=()=>t(17,Ve=!0),Ns=()=>t(14,U=void 0),ks=()=>{t(1,T=""),t(14,U=void 0),Pe.focus()},Os=()=>t(0,b=!b),Rs=()=>t(19,Ge=void 0),Ps=L=>yn(L),Is=L=>gi(L),As=()=>{};return i.$$set=L=>{"class"in L&&t(2,c=L.class),"apiKey"in L&&t(29,E=L.apiKey),"bbox"in L&&t(30,_=L.bbox),"clearButtonTitle"in L&&t(3,M=L.clearButtonTitle),"clearOnBlur"in L&&t(31,R=L.clearOnBlur),"clearListOnPick"in L&&t(32,k=L.clearListOnPick),"keepListOpen"in L&&t(4,I=L.keepListOpen),"collapsed"in L&&t(5,C=L.collapsed),"country"in L&&t(33,O=L.country),"debounceSearch"in L&&t(34,x=L.debounceSearch),"enableReverse"in L&&t(6,N=L.enableReverse),"errorMessage"in L&&t(7,P=L.errorMessage),"filter"in L&&t(35,B=L.filter),"flyTo"in L&&t(36,z=L.flyTo),"fuzzyMatch"in L&&t(37,W=L.fuzzyMatch),"language"in L&&t(38,s=L.language),"limit"in L&&t(39,l=L.limit),"reverseGeocodingLimit"in L&&t(40,m=L.reverseGeocodingLimit),"mapController"in L&&t(41,h=L.mapController),"minLength"in L&&t(42,d=L.minLength),"noResultsMessage"in L&&t(8,v=L.noResultsMessage),"placeholder"in L&&t(9,p=L.placeholder),"proximity"in L&&t(43,y=L.proximity),"reverseActive"in L&&t(0,b=L.reverseActive),"reverseButtonTitle"in L&&t(10,w=L.reverseButtonTitle),"searchValue"in L&&t(1,T=L.searchValue),"pickedResultStyle"in L&&t(44,G=L.pickedResultStyle),"showPlaceType"in L&&t(11,D=L.showPlaceType),"showResultsWhileTyping"in L&&t(45,H=L.showResultsWhileTyping),"selectFirst"in L&&t(46,Q=L.selectFirst),"flyToSelected"in L&&t(47,se=L.flyToSelected),"markerOnSelected"in L&&t(48,Z=L.markerOnSelected),"types"in L&&t(49,K=L.types),"reverseGeocodingTypes"in L&&t(50,He=L.reverseGeocodingTypes),"exhaustiveReverseGeocoding"in L&&t(51,st=L.exhaustiveReverseGeocoding),"excludeTypes"in L&&t(52,ot=L.excludeTypes),"reverseGeocodingExcludeTypes"in L&&t(53,We=L.reverseGeocodingExcludeTypes),"zoom"in L&&t(54,pe=L.zoom),"apiUrl"in L&&t(55,ge=L.apiUrl),"fetchParameters"in L&&t(56,ie=L.fetchParameters),"iconsBaseUrl"in L&&t(12,hn=L.iconsBaseUrl),"adjustUrlQuery"in L&&t(57,ui=L.adjustUrlQuery),"adjustUrl"in L&&t(58,ai=L.adjustUrl),"$$scope"in L&&t(69,o=L.$$scope)},i.$$.update=()=>{if(i.$$.dirty[0]&64&&t(0,b=N==="always"),i.$$.dirty[0]&16384|i.$$.dirty[1]&8192&&G!=="marker-only"&&U&&!U.address&&U.geometry.type==="Point"&&U.place_type[0]!=="reverse"&&hi(U.id,{byId:!0}).catch(L=>t(19,Ge=L)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1058|i.$$.dirty[2]&8&&(h&&U&&U.id!==fi&&z&&(di(),k&&t(13,F=void 0),t(64,ce=void 0),t(15,X=-1)),t(65,fi=U==null?void 0:U.id)),i.$$.dirty[0]&196608|i.$$.dirty[1]&1&&setTimeout(()=>{t(16,ht=Ve),R&&!ht&&t(1,T="")}),i.$$.dirty[0]&8194|i.$$.dirty[1]&2048&&T.length{switch(L.type){case"mapClick":b&&ws(L.coordinates);break;case"markerClick":{const le=F==null?void 0:F.find(ae=>ae.id===L.id);le&&gi(le)}break;case"markerMouseEnter":ce&&t(15,X=ht?(F==null?void 0:F.findIndex(le=>le.id===L.id))??-1:-1);break;case"markerMouseLeave":ce&&t(15,X=-1);break}}),i.$$.dirty[0]&40960&&t(66,r=F==null?void 0:F[X]),i.$$.dirty[1]&66592|i.$$.dirty[2]&16&&h&&r&&z&&se&&h.flyTo(r.center,Tt(r)),i.$$.dirty[1]&8192&&t(68,n=G==="full-geometry-including-polygon-center-marker"),i.$$.dirty[1]&132096|i.$$.dirty[2]&64&&(Z||h==null||h.setFeatures(void 0,void 0,n)),i.$$.dirty[0]&16384|i.$$.dirty[1]&132096|i.$$.dirty[2]&84&&h&&Z&&!ce&&(h.setFeatures(r?[r]:void 0,U,n),h.setSelectedMarker(r?0:-1)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1024|i.$$.dirty[2]&68&&h&&h.setFeatures(ce,U,n),i.$$.dirty[0]&32768|i.$$.dirty[1]&1024|i.$$.dirty[2]&4&&ce&&h&&h.setSelectedMarker(X),i.$$.dirty[0]&2|i.$$.dirty[1]&1024&&h){const L=ci(T);h.setReverseMarker(L?[L.decimalLongitude,L.decimalLatitude]:void 0)}i.$$.dirty[2]&16&&tt("select",{feature:r}),i.$$.dirty[0]&16384&&tt("pick",{feature:U}),i.$$.dirty[0]&73744&&t(67,u=!!(F!=null&&F.length)&&(ht||I)),i.$$.dirty[2]&32&&tt("optionsvisibilitychange",{optionsVisible:u}),i.$$.dirty[0]&8192&&tt("featureslisted",{features:F}),i.$$.dirty[2]&4&&tt("featuresmarked",{features:ce}),i.$$.dirty[0]&1&&tt("reversetoggle",{reverse:b}),i.$$.dirty[0]&2&&tt("querychange",{query:T}),i.$$.dirty[0]&1|i.$$.dirty[1]&1024&&h&&h.indicateReverse(b)},[b,T,c,M,I,C,N,P,v,p,w,D,hn,F,U,X,ht,Ve,Pe,Ge,lt,vs,mn,Es,pn,gi,yn,Ls,g,E,_,R,k,O,x,B,z,W,s,l,m,h,d,y,G,H,Q,se,Z,K,He,st,ot,We,pe,ge,ie,ui,ai,gs,ms,dn,ps,ys,ce,fi,r,u,n,o,a,_s,Ss,xs,Ts,Ms,Cs,Ns,ks,Os,Rs,Ps,Is,As]}let kr=class extends Je{constructor(e){super(),Xe(this,e,Nr,Cr,Ke,{ZOOM_DEFAULTS:28,class:2,apiKey:29,bbox:30,clearButtonTitle:3,clearOnBlur:31,clearListOnPick:32,keepListOpen:4,collapsed:5,country:33,debounceSearch:34,enableReverse:6,errorMessage:7,filter:35,flyTo:36,fuzzyMatch:37,language:38,limit:39,reverseGeocodingLimit:40,mapController:41,minLength:42,noResultsMessage:8,placeholder:9,proximity:43,reverseActive:0,reverseButtonTitle:10,searchValue:1,pickedResultStyle:44,showPlaceType:11,showResultsWhileTyping:45,selectFirst:46,flyToSelected:47,markerOnSelected:48,types:49,reverseGeocodingTypes:50,exhaustiveReverseGeocoding:51,excludeTypes:52,reverseGeocodingExcludeTypes:53,zoom:54,apiUrl:55,fetchParameters:56,iconsBaseUrl:12,adjustUrlQuery:57,adjustUrl:58,focus:59,blur:60,setQuery:61,clearList:62,clearMap:63},null,[-1,-1,-1,-1])}get ZOOM_DEFAULTS(){return this.$$.ctx[28]}get focus(){return this.$$.ctx[59]}get blur(){return this.$$.ctx[60]}get setQuery(){return this.$$.ctx[61]}get clearList(){return this.$$.ctx[62]}get clearMap(){return this.$$.ctx[63]}};function Et(i,e,t={}){const n={type:"Feature"};return(t.id===0||t.id)&&(n.id=t.id),t.bbox&&(n.bbox=t.bbox),n.properties=e||{},n.geometry=i,n}function ti(i,e,t={}){for(const r of i){if(r.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(r[r.length-1].length!==r[0].length)throw new Error("First and last Position are not equivalent.");for(let u=0;u_?w.c=w.e=null:s.e=10;v/=10,d++);d>_?w.c=w.e=null:(w.e=d,w.c=[s]);return}b=String(s)}else{if(!Or.test(b=String(s)))return n(w,b,p);w.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(v=b.search(/e/i))>0?(d<0&&(d=v),d+=+b.slice(v+1),b=b.substring(0,v)):d<0&&(d=b.length)}else{if(oe(l,2,C.length,"Base"),l==10&&O)return w=new x(s),z(w,a+w.e+1,o);if(b=String(s),p=typeof s=="number"){if(s*0!=0)return n(w,b,p,l);if(w.s=1/s<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(ji+s)}else w.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(f=C.slice(0,l),d=v=0,y=b.length;vd){d=y;continue}}else if(!h&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){h=!0,v=-1,d=0;continue}return n(w,String(s),p,l)}p=!1,b=t(b,l,10,w.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(v=0;b.charCodeAt(v)===48;v++);for(y=b.length;b.charCodeAt(--y)===48;);if(b=b.slice(v,++y)){if(y-=v,p&&x.DEBUG&&y>15&&(s>Zi||s!==Te(s)))throw Error(ji+w.s*s);if((d=d-v-1)>_)w.c=w.e=null;else if(d=-1e9&&h<=Ee&&h===Te(h)){if(m[0]===0){if(h===0&&m.length===1)return!0;break e}if(l=(h+1)%q,l<1&&(l+=q),String(m[0]).length==l){for(l=0;l=Re||f!==Te(f))break e;if(f!==0)return!0}}}else if(m===null&&h===null&&(d===null||d===1||d===-1))return!0;throw Error(be+"Invalid BigNumber: "+s)},x.maximum=x.max=function(){return P(arguments,-1)},x.minimum=x.min=function(){return P(arguments,1)},x.random=function(){var s=9007199254740992,l=Math.random()*s&2097151?function(){return Te(Math.random()*s)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(f){var m,h,d,v,p,y=0,b=[],w=new x(u);if(f==null?f=a:oe(f,0,Ee),v=ii(f/q),M)if(crypto.getRandomValues){for(m=crypto.getRandomValues(new Uint32Array(v*=2));y>>11),p>=9e15?(h=crypto.getRandomValues(new Uint32Array(2)),m[y]=h[0],m[y+1]=h[1]):(b.push(p%1e14),y+=2);y=v/2}else if(crypto.randomBytes){for(m=crypto.randomBytes(v*=7);y=9e15?crypto.randomBytes(7).copy(m,y):(b.push(p%1e14),y+=7);y=v/7}else throw M=!1,Error(be+"crypto unavailable");if(!M)for(;y=10;p/=10,y++);yh-1&&(p[v+1]==null&&(p[v+1]=0),p[v+1]+=p[v]/h|0,p[v]%=h)}return p.reverse()}return function(f,m,h,d,v){var p,y,b,w,T,G,D,H,Q=f.indexOf("."),se=a,Z=o;for(Q>=0&&(w=k,k=0,f=f.replace(".",""),H=new x(m),G=H.pow(f.length-Q),k=w,H.c=l(je(Ce(G.c),G.e,"0"),10,h,s),H.e=H.c.length),D=l(f,m,h,v?(p=C,s):(p=s,C)),b=w=D.length;D[--w]==0;D.pop());if(!D[0])return p.charAt(0);if(Q<0?--b:(G.c=D,G.e=b,G.s=d,G=e(G,H,se,Z,h),D=G.c,T=G.r,b=G.e),y=b+se+1,Q=D[y],w=h/2,T=T||y<0||D[y+1]!=null,T=Z<4?(Q!=null||T)&&(Z==0||Z==(G.s<0?3:2)):Q>w||Q==w&&(Z==4||T||Z==6&&D[y-1]&1||Z==(G.s<0?8:7)),y<1||!D[0])f=T?je(p.charAt(1),-se,p.charAt(0)):p.charAt(0);else{if(D.length=y,T)for(--h;++D[--y]>h;)D[y]=0,y||(++b,D=[1].concat(D));for(w=D.length;!D[--w];);for(Q=0,f="";Q<=w;f+=p.charAt(D[Q++]));f=je(f,b,p.charAt(0))}return f}}(),e=function(){function s(m,h,d){var v,p,y,b,w=0,T=m.length,G=h%$e,D=h/$e|0;for(m=m.slice();T--;)y=m[T]%$e,b=m[T]/$e|0,v=D*y+b*G,p=G*y+v%$e*$e+w,w=(p/d|0)+(v/$e|0)+D*b,m[T]=p%d;return w&&(m=[w].concat(m)),m}function l(m,h,d,v){var p,y;if(d!=v)y=d>v?1:-1;else for(p=y=0;ph[p]?1:-1;break}return y}function f(m,h,d,v){for(var p=0;d--;)m[d]-=p,p=m[d]1;m.splice(0,1));}return function(m,h,d,v,p){var y,b,w,T,G,D,H,Q,se,Z,K,de,He,st,ot,Le,We,pe=m.s==h.s?1:-1,ge=m.c,ie=h.c;if(!ge||!ge[0]||!ie||!ie[0])return new x(!m.s||!h.s||(ge?ie&&ge[0]==ie[0]:!ie)?NaN:ge&&ge[0]==0||!ie?pe*0:pe/0);for(Q=new x(pe),se=Q.c=[],b=m.e-h.e,pe=d+b+1,p||(p=Re,b=Me(m.e/q)-Me(h.e/q),pe=pe/q|0),w=0;ie[w]==(ge[w]||0);w++);if(ie[w]>(ge[w]||0)&&b--,pe<0)se.push(1),T=!0;else{for(st=ge.length,Le=ie.length,w=0,pe+=2,G=Te(p/(ie[0]+1)),G>1&&(ie=s(ie,G,p),ge=s(ge,G,p),Le=ie.length,st=ge.length),He=Le,Z=ge.slice(0,Le),K=Z.length;K=p/2&&ot++;do{if(G=0,y=l(ie,Z,Le,K),y<0){if(de=Z[0],Le!=K&&(de=de*p+(Z[1]||0)),G=Te(de/ot),G>1)for(G>=p&&(G=p-1),D=s(ie,G,p),H=D.length,K=Z.length;l(D,Z,H,K)==1;)G--,f(D,Le=10;pe/=10,w++);z(Q,d+(Q.e=w+b*q-1)+1,v,T)}else Q.e=b,Q.r=+T;return Q}}();function N(s,l,f,m){var h,d,v,p,y;if(f==null?f=o:oe(f,0,8),!s.c)return s.toString();if(h=s.c[0],v=s.e,l==null)y=Ce(s.c),y=m==1||m==2&&(v<=g||v>=c)?Gt(y,v):je(y,v,"0");else if(s=z(new x(s),l,f),d=s.e,y=Ce(s.c),p=y.length,m==1||m==2&&(l<=d||d<=g)){for(;pp){if(--l>0)for(y+=".";l--;y+="0");}else if(l+=d-p,l>0)for(d+1==p&&(y+=".");l--;y+="0");return s.s<0&&h?"-"+y:y}function P(s,l){for(var f,m,h=1,d=new x(s[0]);h=10;h/=10,m++);return(f=m+f*q-1)>_?s.c=s.e=null:f=10;p/=10,h++);if(d=l-h,d<0)d+=q,v=l,y=T[b=0],w=Te(y/G[h-v-1]%10);else if(b=ii((d+1)/q),b>=T.length)if(m){for(;T.length<=b;T.push(0));y=w=0,h=1,d%=q,v=d-q+1}else break e;else{for(y=p=T[b],h=1;p>=10;p/=10,h++);d%=q,v=d-q+h,w=v<0?0:Te(y/G[h-v-1]%10)}if(m=m||l<0||T[b+1]!=null||(v<0?y:y%G[h-v-1]),m=f<4?(w||m)&&(f==0||f==(s.s<0?3:2)):w>5||w==5&&(f==4||m||f==6&&(d>0?v>0?y/G[h-v]:0:T[b-1])%10&1||f==(s.s<0?8:7)),l<1||!T[0])return T.length=0,m?(l-=s.e+1,T[0]=G[(q-l%q)%q],s.e=-l||0):T[0]=s.e=0,s;if(d==0?(T.length=b,p=1,b--):(T.length=b+1,p=G[q-d],T[b]=v>0?Te(y/G[h-v]%G[v])*p:0),m)for(;;)if(b==0){for(d=1,v=T[0];v>=10;v/=10,d++);for(v=T[0]+=p,p=1;v>=10;v/=10,p++);d!=p&&(s.e++,T[0]==Re&&(T[0]=1));break}else{if(T[b]+=p,T[b]!=Re)break;T[b--]=0,p=1}for(d=T.length;T[--d]===0;T.pop());}s.e>_?s.c=s.e=null:s.e=c?Gt(l,f):je(l,f,"0"),s.s<0?"-"+l:l)}return r.absoluteValue=r.abs=function(){var s=new x(this);return s.s<0&&(s.s=1),s},r.comparedTo=function(s,l){return rt(this,new x(s,l))},r.decimalPlaces=r.dp=function(s,l){var f,m,h,d=this;if(s!=null)return oe(s,0,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s+d.e+1,l);if(!(f=d.c))return null;if(m=((h=f.length-1)-Me(this.e/q))*q,h=f[h])for(;h%10==0;h/=10,m--);return m<0&&(m=0),m},r.dividedBy=r.div=function(s,l){return e(this,new x(s,l),a,o)},r.dividedToIntegerBy=r.idiv=function(s,l){return e(this,new x(s,l),0,1)},r.exponentiatedBy=r.pow=function(s,l){var f,m,h,d,v,p,y,b,w,T=this;if(s=new x(s),s.c&&!s.isInteger())throw Error(be+"Exponent not an integer: "+W(s));if(l!=null&&(l=new x(l)),p=s.e>14,!T.c||!T.c[0]||T.c[0]==1&&!T.e&&T.c.length==1||!s.c||!s.c[0])return w=new x(Math.pow(+W(T),p?s.s*(2-Wt(s)):+W(s))),l?w.mod(l):w;if(y=s.s<0,l){if(l.c?!l.c[0]:!l.s)return new x(NaN);m=!y&&T.isInteger()&&l.isInteger(),m&&(T=T.mod(l))}else{if(s.e>9&&(T.e>0||T.e<-1||(T.e==0?T.c[0]>1||p&&T.c[1]>=24e7:T.c[0]<8e13||p&&T.c[0]<=9999975e7)))return d=T.s<0&&Wt(s)?-0:0,T.e>-1&&(d=1/d),new x(y?1/d:d);k&&(d=ii(k/q+2))}for(p?(f=new x(.5),y&&(s.s=1),b=Wt(s)):(h=Math.abs(+W(s)),b=h%2),w=new x(u);;){if(b){if(w=w.times(T),!w.c)break;d?w.c.length>d&&(w.c.length=d):m&&(w=w.mod(l))}if(h){if(h=Te(h/2),h===0)break;b=h%2}else if(s=s.times(f),z(s,s.e+1,1),s.e>14)b=Wt(s);else{if(h=+W(s),h===0)break;b=h%2}T=T.times(T),d?T.c&&T.c.length>d&&(T.c.length=d):m&&(T=T.mod(l))}return m?w:(y&&(w=u.div(w)),l?w.mod(l):d?z(w,k,o,v):w)},r.integerValue=function(s){var l=new x(this);return s==null?s=o:oe(s,0,8),z(l,l.e+1,s)},r.isEqualTo=r.eq=function(s,l){return rt(this,new x(s,l))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(s,l){return rt(this,new x(s,l))>0},r.isGreaterThanOrEqualTo=r.gte=function(s,l){return(l=rt(this,new x(s,l)))===1||l===0},r.isInteger=function(){return!!this.c&&Me(this.e/q)>this.c.length-2},r.isLessThan=r.lt=function(s,l){return rt(this,new x(s,l))<0},r.isLessThanOrEqualTo=r.lte=function(s,l){return(l=rt(this,new x(s,l)))===-1||l===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(s,l){var f,m,h,d,v=this,p=v.s;if(s=new x(s,l),l=s.s,!p||!l)return new x(NaN);if(p!=l)return s.s=-l,v.plus(s);var y=v.e/q,b=s.e/q,w=v.c,T=s.c;if(!y||!b){if(!w||!T)return w?(s.s=-l,s):new x(T?v:NaN);if(!w[0]||!T[0])return T[0]?(s.s=-l,s):new x(w[0]?v:o==3?-0:0)}if(y=Me(y),b=Me(b),w=w.slice(),p=y-b){for((d=p<0)?(p=-p,h=w):(b=y,h=T),h.reverse(),l=p;l--;h.push(0));h.reverse()}else for(m=(d=(p=w.length)<(l=T.length))?p:l,p=l=0;l0)for(;l--;w[f++]=0);for(l=Re-1;m>p;){if(w[--m]=0;){for(f=0,G=de[h]%se,D=de[h]/se|0,v=y,d=h+v;d>h;)b=K[--v]%se,w=K[v]/se|0,p=D*b+w*G,b=G*b+p%se*se+H[d]+f,f=(b/Q|0)+(p/se|0)+D*w,H[d--]=b%Q;H[d]=f}return f?++m:H.splice(0,1),B(s,H,m)},r.negated=function(){var s=new x(this);return s.s=-s.s||null,s},r.plus=function(s,l){var f,m=this,h=m.s;if(s=new x(s,l),l=s.s,!h||!l)return new x(NaN);if(h!=l)return s.s=-l,m.minus(s);var d=m.e/q,v=s.e/q,p=m.c,y=s.c;if(!d||!v){if(!p||!y)return new x(h/0);if(!p[0]||!y[0])return y[0]?s:new x(p[0]?m:h*0)}if(d=Me(d),v=Me(v),p=p.slice(),h=d-v){for(h>0?(v=d,f=y):(h=-h,f=p),f.reverse();h--;f.push(0));f.reverse()}for(h=p.length,l=y.length,h-l<0&&(f=y,y=p,p=f,l=h),h=0;l;)h=(p[--l]=p[l]+y[l]+h)/Re|0,p[l]=Re===p[l]?0:p[l]%Re;return h&&(p=[h].concat(p),++v),B(s,p,v)},r.precision=r.sd=function(s,l){var f,m,h,d=this;if(s!=null&&s!==!!s)return oe(s,1,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s,l);if(!(f=d.c))return null;if(h=f.length-1,m=h*q+1,h=f[h]){for(;h%10==0;h/=10,m--);for(h=f[0];h>=10;h/=10,m++);}return s&&d.e+1>m&&(m=d.e+1),m},r.shiftedBy=function(s){return oe(s,-9007199254740991,Zi),this.times("1e"+s)},r.squareRoot=r.sqrt=function(){var s,l,f,m,h,d=this,v=d.c,p=d.s,y=d.e,b=a+4,w=new x("0.5");if(p!==1||!v||!v[0])return new x(!p||p<0&&(!v||v[0])?NaN:v?d:1/0);if(p=Math.sqrt(+W(d)),p==0||p==1/0?(l=Ce(v),(l.length+y)%2==0&&(l+="0"),p=Math.sqrt(+l),y=Me((y+1)/2)-(y<0||y%2),p==1/0?l="5e"+y:(l=p.toExponential(),l=l.slice(0,l.indexOf("e")+1)+y),f=new x(l)):f=new x(p+""),f.c[0]){for(y=f.e,p=y+b,p<3&&(p=0);;)if(h=f,f=w.times(h.plus(e(d,h,b,1))),Ce(h.c).slice(0,p)===(l=Ce(f.c)).slice(0,p))if(f.e0&&H>0){for(d=H%p||p,w=D.substr(0,d);d0&&(w+=b+D.slice(d)),G&&(w="-"+w)}m=T?w+(f.decimalSeparator||"")+((y=+f.fractionGroupSize)?T.replace(new RegExp("\\d{"+y+"}\\B","g"),"$&"+(f.fractionGroupSeparator||"")):T):w}return(f.prefix||"")+m+(f.suffix||"")},r.toFraction=function(s){var l,f,m,h,d,v,p,y,b,w,T,G,D=this,H=D.c;if(s!=null&&(p=new x(s),!p.isInteger()&&(p.c||p.s!==1)||p.lt(u)))throw Error(be+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+W(p));if(!H)return new x(D);for(l=new x(u),b=f=new x(u),m=y=new x(u),G=Ce(H),d=l.e=G.length-D.e-1,l.c[0]=ni[(v=d%q)<0?q+v:v],s=!s||p.comparedTo(l)>0?d>0?l:b:p,v=_,_=1/0,p=new x(G),y.c[0]=0;w=e(p,l,0,1),h=f.plus(w.times(m)),h.comparedTo(s)!=1;)f=m,m=h,b=y.plus(w.times(h=b)),y=h,l=p.minus(w.times(h=l)),p=h;return h=e(s.minus(f),m,0,1),y=y.plus(h.times(b)),f=f.plus(h.times(m)),y.s=b.s=D.s,d=d*2,T=e(b,m,d,o).minus(D).abs().comparedTo(e(y,f,d,o).minus(D).abs())<1?[b,m]:[y,f],_=v,T},r.toNumber=function(){return+W(this)},r.toPrecision=function(s,l){return s!=null&&oe(s,1,Ee),N(this,s,l,2)},r.toString=function(s){var l,f=this,m=f.s,h=f.e;return h===null?m?(l="Infinity",m<0&&(l="-"+l)):l="NaN":(s==null?l=h<=g||h>=c?Gt(Ce(f.c),h):je(Ce(f.c),h,"0"):s===10&&O?(f=z(new x(f),a+h+1,o),l=je(Ce(f.c),f.e,"0")):(oe(s,2,C.length,"Base"),l=t(je(Ce(f.c),h,"0"),10,s,m,!0)),m<0&&f.c[0]&&(l="-"+l)),l},r.valueOf=r.toJSON=function(){return W(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,i!=null&&x.set(i),x}function Me(i){var e=i|0;return i>0||i===e?e:e-1}function Ce(i){for(var e,t,n=1,r=i.length,u=i[0]+"";nc^t?1:-1;for(o=(g=r.length)<(c=u.length)?g:c,a=0;au[a]^t?1:-1;return g==c?0:g>c^t?1:-1}function oe(i,e,t,n){if(it||i!==Te(i))throw Error(be+(n||"Argument")+(typeof i=="number"?it?" out of range: ":" not an integer: ":" not a primitive number: ")+String(i))}function Wt(i){var e=i.c.length-1;return Me(i.e/q)==e&&i.c[e]%2!=0}function Gt(i,e){return(i.length>1?i.charAt(0)+"."+i.slice(1):i)+(e<0?"e":"e+")+e}function je(i,e,t){var n,r;if(e<0){for(r=t+".";++e;r+=t);i=r+i}else if(n=i.length,++e>n){for(r=t,e-=n;--e;r+=t);i+=r}else e0){let c=a.left;if(c==null||(g=o(c.key,i),g>0&&(a.left=c.right,c.right=a,a=c,c=a.left,c==null)))break;t==null?n=a:t.left=a,t=a,a=c}else if(g<0){let c=a.right;if(c==null||(g=o(c.key,i),g<0&&(a.right=c.left,c.left=a,a=c,c=a.right,c==null)))break;r==null?u=a:r.right=a,r=a,a=c}else break;return r!=null&&(r.right=a.left,a.left=u),t!=null&&(t.left=a.right,a.right=n),this.root!==a&&(this.root=a,this.splayCount++),g}splayMin(i){let e=i,t=e.left;for(;t!=null;){const n=t;e.left=n.right,n.right=e,e=n,t=e.left}return e}splayMax(i){let e=i,t=e.right;for(;t!=null;){const n=t;e.right=n.left,n.left=e,e=n,t=e.right}return e}_delete(i){if(this.root==null||this.splay(i)!=0)return null;let t=this.root;const n=t,r=t.left;if(this.size--,r==null)this.root=t.right;else{const u=t.right;t=this.splayMax(r),t.right=u,this.root=t}return this.modificationCount++,n}addNewRoot(i,e){this.size++,this.modificationCount++;const t=this.root;if(t==null){this.root=i;return}e<0?(i.left=t,i.right=t.right,t.right=null):(i.right=t,i.left=t.left,t.left=null),this.root=i}_first(){const i=this.root;return i==null?null:(this.root=this.splayMin(i),this.root)}_last(){const i=this.root;return i==null?null:(this.root=this.splayMax(i),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(i){return this.validKey(i)&&this.splay(i)==0}defaultCompare(){return(i,e)=>ie?1:0}wrap(){return{getRoot:()=>this.root,setRoot:i=>{this.root=i},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:i=>{this.splayCount=i},splay:i=>this.splay(i),has:i=>this.has(i)}}},Dt=class Ot extends Pr{constructor(t,n){super();A(this,"root",null);A(this,"compare");A(this,"validKey");A(this,fn,"[object Set]");this.compare=t??this.defaultCompare(),this.validKey=n??(r=>r!=null&&r!=null)}delete(t){return this.validKey(t)?this._delete(t)!=null:!1}deleteAll(t){for(const n of t)this.delete(n)}forEach(t){const n=this[Symbol.iterator]();let r;for(;r=n.next(),!r.done;)t(r.value,r.value,this)}add(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this}addAndReturn(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this.root.key}addAll(t){for(const n of t)this.add(n)}isEmpty(){return this.root==null}isNotEmpty(){return this.root!=null}single(){if(this.size==0)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(this.size==0)throw"Bad state: No element";return this._first().key}last(){if(this.size==0)throw"Bad state: No element";return this._last().key}lastBefore(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)<0)return this.root.key;let r=this.root.left;if(r==null)return null;let u=r.right;for(;u!=null;)r=u,u=r.right;return r.key}firstAfter(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)>0)return this.root.key;let r=this.root.right;if(r==null)return null;let u=r.left;for(;u!=null;)r=u,u=r.left;return r.key}retainAll(t){const n=new Ot(this.compare,this.validKey),r=this.modificationCount;for(const u of t){if(r!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(u)&&this.splay(u)==0&&n.add(this.root.key)}n.size!=this.size&&(this.root=n.root,this.size=n.size,this.modificationCount++)}lookup(t){return!this.validKey(t)||this.splay(t)!=0?null:this.root.key}intersection(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)&&n.add(r);return n}difference(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)||n.add(r);return n}union(t){const n=this.clone();return n.addAll(t),n}clone(){const t=new Ot(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(t){if(t==null)return null;function n(u,a){let o,g;do{if(o=u.left,g=u.right,o!=null){const c=new _t(o.key);a.left=c,n(o,c)}if(g!=null){const c=new _t(g.key);a.right=c,u=g,a=c}}while(g!=null)}const r=new _t(t.key);return n(t,r),r}toSet(){return this.clone()}entries(){return new Ar(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[(cn=Symbol.iterator,fn=Symbol.toStringTag,cn)](){return new Ir(this.wrap())}},Vi=class{constructor(i){A(this,"tree");A(this,"path",new Array);A(this,"modificationCount",null);A(this,"splayCount");this.tree=i,this.splayCount=i.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const i=this.path[this.path.length-1];return this.getValue(i)}rebuildPath(i){this.path.splice(0,this.path.length),this.tree.splay(i),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(i){for(;i!=null;)this.path.push(i),i=i.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(this.modificationCount==null){this.modificationCount=this.tree.getModificationCount();let t=this.tree.getRoot();for(;t!=null;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let i=this.path[this.path.length-1],e=i.right;if(e!=null){for(;e!=null;)this.path.push(e),e=e.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===i;)i=this.path.pop();return this.path.length>0}},Ir=class extends Vi{getValue(i){return i.key}},Ar=class extends Vi{getValue(i){return[i.key,i.key]}},Ki=i=>()=>i,ri=i=>{const e=i?(t,n)=>n.minus(t).abs().isLessThanOrEqualTo(i):Ki(!1);return(t,n)=>e(t,n)?0:t.comparedTo(n)};function Br(i){const e=i?(t,n,r,u,a)=>t.exponentiatedBy(2).isLessThanOrEqualTo(u.minus(n).exponentiatedBy(2).plus(a.minus(r).exponentiatedBy(2)).times(i)):Ki(!1);return(t,n,r)=>{const u=t.x,a=t.y,o=r.x,g=r.y,c=a.minus(g).times(n.x.minus(o)).minus(u.minus(o).times(n.y.minus(g)));return e(c,u,a,o,g)?0:c.comparedTo(0)}}var Wr=i=>i,Gr=i=>{if(i){const e=new Dt(ri(i)),t=new Dt(ri(i)),n=(u,a)=>a.addAndReturn(u),r=u=>({x:n(u.x,e),y:n(u.y,t)});return r({x:new Ae(0),y:new Ae(0)}),r}return Wr},si=i=>({set:e=>{Ze=si(e)},reset:()=>si(i),compare:ri(i),snap:Gr(i),orient:Br(i)}),Ze=si(),St=(i,e)=>i.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(i.ur.x)&&i.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(i.ur.y),oi=(i,e)=>{if(e.ur.x.isLessThan(i.ll.x)||i.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(i.ll.y)||i.ur.y.isLessThan(e.ll.y))return null;const t=i.ll.x.isLessThan(e.ll.x)?e.ll.x:i.ll.x,n=i.ur.x.isLessThan(e.ur.x)?i.ur.x:e.ur.x,r=i.ll.y.isLessThan(e.ll.y)?e.ll.y:i.ll.y,u=i.ur.y.isLessThan(e.ur.y)?i.ur.y:e.ur.y;return{ll:{x:t,y:r},ur:{x:n,y:u}}},zt=(i,e)=>i.x.times(e.y).minus(i.y.times(e.x)),Yi=(i,e)=>i.x.times(e.x).plus(i.y.times(e.y)),Ut=i=>Yi(i,i).sqrt(),Dr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return zt(r,n).div(Ut(r)).div(Ut(n))},zr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return Yi(r,n).div(Ut(r)).div(Ut(n))},Qi=(i,e,t)=>e.y.isZero()?null:{x:i.x.plus(e.x.div(e.y).times(t.minus(i.y))),y:t},Xi=(i,e,t)=>e.x.isZero()?null:{x:t,y:i.y.plus(e.y.div(e.x).times(t.minus(i.x)))},Ur=(i,e,t,n)=>{if(e.x.isZero())return Xi(t,n,i.x);if(n.x.isZero())return Xi(i,e,t.x);if(e.y.isZero())return Qi(t,n,i.y);if(n.y.isZero())return Qi(i,e,t.y);const r=zt(e,n);if(r.isZero())return null;const u={x:t.x.minus(i.x),y:t.y.minus(i.y)},a=zt(u,e).div(r),o=zt(u,n).div(r),g=i.x.plus(o.times(e.x)),c=t.x.plus(a.times(n.x)),E=i.y.plus(o.times(e.y)),_=t.y.plus(a.times(n.y)),M=g.plus(c).div(2),R=E.plus(_).div(2);return{x:M,y:R}},Be=class En{constructor(e,t){A(this,"point");A(this,"isLeft");A(this,"segment");A(this,"otherSE");A(this,"consumedBy");e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}static compare(e,t){const n=En.comparePoints(e.point,t.point);return n!==0?n:(e.point!==t.point&&e.link(t),e.isLeft!==t.isLeft?e.isLeft?1:-1:Ft.compare(e.segment,t.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let n=0,r=t.length;n{const u=r.otherSE;t.set(r,{sine:Dr(this.point,e.point,u.point),cosine:zr(this.point,e.point,u.point)})};return(r,u)=>{t.has(r)||n(r),t.has(u)||n(u);const{sine:a,cosine:o}=t.get(r),{sine:g,cosine:c}=t.get(u);return a.isGreaterThanOrEqualTo(0)&&g.isGreaterThanOrEqualTo(0)?o.isLessThan(c)?1:o.isGreaterThan(c)?-1:0:a.isLessThan(0)&&g.isLessThan(0)?o.isLessThan(c)?-1:o.isGreaterThan(c)?1:0:g.isLessThan(a)?-1:g.isGreaterThan(a)?1:0}}},qr=class pi{constructor(e){A(this,"events");A(this,"poly");A(this,"_isExteriorRing");A(this,"_enclosingRing");this.events=e;for(let t=0,n=e.length;t0&&(e=g)}let t=e.segment.prevInResult(),n=t?t.prevInResult():null;for(;;){if(!t)return null;if(!n)return t.ringOut;if(n.ringOut!==t.ringOut)return((r=n.ringOut)==null?void 0:r.enclosingRing())!==t.ringOut?t.ringOut:(u=t.ringOut)==null?void 0:u.enclosingRing();t=n.prevInResult(),n=t?t.prevInResult():null}}},Ji=class{constructor(i){A(this,"exteriorRing");A(this,"interiorRings");this.exteriorRing=i,i.poly=this,this.interiorRings=[]}addInterior(i){this.interiorRings.push(i),i.poly=this}getGeom(){const i=this.exteriorRing.getGeom();if(i===null)return null;const e=[i];for(let t=0,n=this.interiorRings.length;t0?(this.tree.delete(e),t.push(i)):(this.segments.push(e),e.prev=n)}else{if(n&&r){const u=n.getIntersection(r);if(u!==null){if(!n.isAnEndpoint(u)){const a=this._splitSafely(n,u);for(let o=0,g=a.length;o0)return-1;const M=t.comparePoint(e.rightSE.point);return M!==0?M:-1}if(n.isGreaterThan(r)){if(o.isLessThan(g)&&o.isLessThan(E))return-1;if(o.isGreaterThan(g)&&o.isGreaterThan(E))return 1;const _=t.comparePoint(e.leftSE.point);if(_!==0)return _;const M=e.comparePoint(t.rightSE.point);return M<0?1:M>0?-1:1}if(o.isLessThan(g))return-1;if(o.isGreaterThan(g))return 1;if(u.isLessThan(a)){const _=t.comparePoint(e.rightSE.point);if(_!==0)return _}if(u.isGreaterThan(a)){const _=e.comparePoint(t.rightSE.point);if(_<0)return 1;if(_>0)return-1}if(!u.eq(a)){const _=c.minus(o),M=u.minus(n),R=E.minus(g),k=a.minus(r);if(_.isGreaterThan(M)&&R.isLessThan(k))return 1;if(_.isLessThan(M)&&R.isGreaterThan(k))return-1}return u.isGreaterThan(a)?1:u.isLessThan(a)||c.isLessThan(E)?-1:c.isGreaterThan(E)?1:e.idt.id?1:0}static fromRing(e,t,n){let r,u,a;const o=Be.comparePoints(e,t);if(o<0)r=e,u=t,a=1;else if(o>0)r=t,u=e,a=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const g=new Be(r,!0),c=new Be(u,!1);return new Kt(g,c,[n],[a])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return Ze.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),n=e.bbox(),r=oi(t,n);if(r===null)return null;const u=this.leftSE.point,a=this.rightSE.point,o=e.leftSE.point,g=e.rightSE.point,c=St(t,o)&&this.comparePoint(o)===0,E=St(n,u)&&e.comparePoint(u)===0,_=St(t,g)&&this.comparePoint(g)===0,M=St(n,a)&&e.comparePoint(a)===0;if(E&&c)return M&&!_?a:!M&&_?g:null;if(E)return _&&u.x.eq(g.x)&&u.y.eq(g.y)?null:u;if(c)return M&&a.x.eq(o.x)&&a.y.eq(o.y)?null:o;if(M&&_)return null;if(M)return a;if(_)return g;const R=Ur(u,this.vector(),o,e.vector());return R===null||!St(r,R)?null:Ze.snap(R)}split(e){const t=[],n=e.events!==void 0,r=new Be(e,!0),u=new Be(e,!1),a=this.rightSE;this.replaceRightSE(u),t.push(u),t.push(r);const o=new Kt(r,a,this.rings.slice(),this.windings.slice());return Be.comparePoints(o.leftSE.point,o.rightSE.point)>0&&o.swapEvents(),Be.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(r.checkForConsuming(),u.checkForConsuming()),t}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,n=this.windings.length;t0){const u=t;t=n,n=u}if(t.prev===n){const u=t;t=n,n=u}for(let u=0,a=n.rings.length;ur.length===1&&r[0].isSubject;this._isInResult=n(e)!==n(t);break}}return this._isInResult}},$i=class{constructor(i,e,t){A(this,"poly");A(this,"isExterior");A(this,"segments");A(this,"bbox");if(!Array.isArray(i)||i.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=e,this.isExterior=t,this.segments=[],typeof i[0][0]!="number"||typeof i[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const n=Ze.snap({x:new Ae(i[0][0]),y:new Ae(i[0][1])});this.bbox={ll:{x:n.x,y:n.y},ur:{x:n.x,y:n.y}};let r=n;for(let u=1,a=i.length;uqt.run("union",i,e),Yr=(i,...e)=>qt.run("difference",i,e);Ze.set;function tn(i,e,t){if(i!==null)for(var n,r,u,a,o,g,c,E=0,_=0,M,R=i.type,k=R==="FeatureCollection",I=R==="Feature",C=k?i.features.length:1,O=0;O{t.push(r.coordinates)}),t.length<2)throw new Error("Must have at least 2 geometries");const n=Kr(t[0],...t.slice(1));return n.length===0?null:n.length===1?ti(n[0],e.properties):Fi(n,e.properties)}var nn=Xr;function Jr(i,e={}){if(i.bbox!=null&&e.recompute!==!0)return i.bbox;const t=[1/0,1/0,-1/0,-1/0];return tn(i,n=>{t[0]>n[0]&&(t[0]=n[0]),t[1]>n[1]&&(t[1]=n[1]),t[2]{e.push(r.coordinates)}),e.length<2)throw new Error("Must have at least two features");const t=i.features[0].properties||{},n=Yr(e[0],...e.slice(1));return n.length===0?null:n.length===1?ti(n[0],t):Fi(n,t)}var es=$r;function ts(i){if(!i)throw new Error("geojson is required");var e=[];return Qr(i,function(t){e.push(t)}),Lt(e)}var is=ts;function sn(i,e){const t=es(Lt([ti([[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]]),i]));if(!t)return;t.properties={isMask:!0};const n=Bt(rn(i)),r=(n[2]-n[0])/360/1e3,u=n[0]<-180,a=n[2]>180,o=is(i);if(o.features.length>1&&(u||a))for(const g of o.features){const c=Bt(rn(g));if(a&&c[0]<-180+r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]+=360-r;if(u&&c[2]>180-r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]-=360-r}e(Lt([o.features.length<2?i:nn(o)??i,t]))}const on={fill:{paint:{"fill-color":"#000","fill-opacity":.1},filter:["all",["==",["geometry-type"],"Polygon"],["has","isMask"]]},line:{layout:{"line-cap":"square"},paint:{"line-width":["case",["==",["geometry-type"],"Polygon"],2,3],"line-dasharray":[1,1],"line-color":"#3170fe"},filter:["!",["has","isMask"]]}},jt="mtlr-gc-full-geom",ln="mtlr-gc-full-geom-fill",un="mtlr-gc-full-geom-line";function an(i,e,t=!0,n=!0,r={},u={},a=on){let o;const g=[];let c,E,_;function M(){if(!i.loaded){i.once("load",M);return}const C=a?a===!0?on:a:void 0;if(!(C!=null&&C.fill)&&!(C!=null&&C.line))return;const O=i.getSource(jt);if(O)O.setData(_??Lt([]));else if(_)i.addSource(jt,{type:"geojson",data:_});else return;!i.getLayer(ln)&&(C!=null&&C.fill)&&i.addLayer({...C==null?void 0:C.fill,id:ln,type:"fill",source:jt}),!i.getLayer(un)&&(C!=null&&C.line)&&i.addLayer({...C==null?void 0:C.line,id:un,type:"line",source:jt})}function R(C){_=C,M()}i.on("styledata",()=>{setTimeout(()=>{_&&M()})});const k=C=>{o==null||o({type:"mapClick",coordinates:[C.lngLat.lng,C.lngLat.lat]})};function I(C=!1){if(!e)throw new Error;const O=document.createElement("div");return C&&O.classList.add("marker-interactive"),new or({props:{displayIn:"maplibre"},target:O}),new e.Marker({element:O,offset:[1,-13]})}return{setEventHandler(C){C?(o=C,i.on("click",k)):(o=void 0,i.off("click",k))},flyTo(C,O){i.flyTo({center:C,...O?{zoom:O}:{},...r})},fitBounds(C,O,x){i.fitBounds([[C[0],C[1]],[C[2],C[3]]],{padding:O,...x?{maxZoom:x}:{},...u})},indicateReverse(C){i.getCanvasContainer().style.cursor=C?"crosshair":""},setReverseMarker(C){!e||!t||(E?C?E.setLngLat(C):(E.remove(),E=void 0):C&&(t instanceof Function?E=t(i)??void 0:(E=(typeof t=="object"?new e.Marker(t):I()).setLngLat(C).addTo(i),E.getElement().classList.add("marker-reverse"))))},setFeatures(C,O,x){for(const N of g)N.remove();if(g.length=0,R(void 0),!!e){e:if(O){let N=!1;if(O.geometry.type==="GeometryCollection"){const P=O.geometry.geometries.filter(B=>B.type==="Polygon"||B.type==="MultiPolygon");t:if(P.length>0){const B=nn(Lt(P.map(z=>Et(z))));if(!B)break t;sn({...O,geometry:B.geometry},R),N=!0}else{const B=O.geometry.geometries.filter(z=>z.type==="LineString"||z.type==="MultiLineString");B.length>0&&(R({...O,geometry:{type:"GeometryCollection",geometries:B}}),N=!0)}}if(!N){if(O.geometry.type==="Polygon"||O.geometry.type==="MultiPolygon")sn(O,R);else if(O.geometry.type==="LineString"||O.geometry.type==="MultiLineString"){R(O);break e}}if(!x&&!O.geometry.type.endsWith("Point"))break e;if(t instanceof Function){const P=t(i,O);P&&g.push(P)}else t&&g.push(typeof t=="object"?new e.Marker(t):I().setLngLat(O.center).addTo(i))}if(n)for(const N of C??[]){if(N===O)continue;let P;if(n instanceof Function){if(P=n(i,N),!P)continue}else P=(typeof n=="object"?new e.Marker(n):I(!0)).setLngLat(N.center).setPopup(new e.Popup({offset:[1,-27],closeButton:!1,closeOnMove:!0,className:"maptiler-gc-popup"}).setText(N.place_type[0]==="reverse"?N.place_name:N.place_name.replace(/,.*/,""))).addTo(i);const B=P.getElement();B.addEventListener("click",z=>{z.stopPropagation(),o==null||o({type:"markerClick",id:N.id})}),B.addEventListener("mouseenter",()=>{o==null||o({type:"markerMouseEnter",id:N.id}),P.togglePopup()}),B.addEventListener("mouseleave",()=>{o==null||o({type:"markerMouseLeave",id:N.id}),P.togglePopup()}),g.push(P)}}},setSelectedMarker(C){c&&c.getElement().classList.toggle("marker-selected",!1),c=C>-1?g[C]:void 0,c==null||c.getElement().classList.toggle("marker-selected",!0)},getCenterAndZoom(){const C=i.getCenter();return[i.getZoom(),C.lng,C.lat]}}}function ns(i,e,t){var k,I,C;class n{constructor(x,N){A(this,"type");A(this,"target");this.type=N,this.target=x}}class r extends n{constructor(N,P){super(N,"select");A(this,"feature");Object.assign(this,P)}}class u extends n{constructor(N,P){super(N,"featureslisted");A(this,"features");this.features=P}}class a extends n{constructor(N,P){super(N,"featuresmarked");A(this,"features");this.features=P}}class o extends n{constructor(N,P){super(N,"optionsvisibilitychange");A(this,"optionsVisible");this.optionsVisible=P}}class g extends n{constructor(N,P){super(N,"pick");A(this,"feature");this.feature=P}}class c extends n{constructor(N,P){super(N,"querychange");A(this,"query");this.query=P}}class E extends n{constructor(N,P,B){super(N,"response");A(this,"url");A(this,"featureCollection");this.url=P,this.featureCollection=B}}class _ extends n{constructor(N,P){super(N,"reversetoggle");A(this,"reverse");this.reverse=P}}class M extends i{constructor(N={}){super();Vt(this,k);Vt(this,I);Vt(this,C);kt(this,I,N)}onAddInt(N){const P=document.createElement("div");P.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl mapboxgl-ctrl-group";const{marker:B,showResultMarkers:z,flyTo:W,fullGeometryStyle:s,...l}=ue(this,I),f=typeof W=="boolean"?{}:W,h={mapController:an(N,e,B,z,f,f,s),flyTo:W===void 0?!0:!!W,apiKey:"",...t==null?void 0:t(N,P),...l};return h.apiKey||console.warn("No MapTiler Cloud API key was provided, some or all geocoding requests may fail"),kt(this,k,new kr({target:P,props:h})),ue(this,k).$on("select",d=>{this.fire(new r(this,d.detail))}),ue(this,k).$on("pick",d=>{this.fire(new g(this,d.detail.feature))}),ue(this,k).$on("featureslisted",d=>{this.fire(new u(this,d.detail.features))}),ue(this,k).$on("featuresmarked",d=>{this.fire(new a(this,d.detail.features))}),ue(this,k).$on("response",d=>{this.fire(new E(this,d.detail.url,d.detail.featureCollection))}),ue(this,k).$on("optionsvisibilitychange",d=>{this.fire(new o(this,d.detail.optionsVisible))}),ue(this,k).$on("reversetoggle",d=>{this.fire(new _(this,d.detail.reverse))}),ue(this,k).$on("querychange",d=>{this.fire(new c(this,d.detail.query))}),kt(this,C,P),P}on(N,P){return super.on(N,P)}once(N,P){return super.once(N,P)}off(N,P){return super.off(N,P)}listens(N){return super.listens(N)}setOptions(N){var l;Object.assign(ue(this,I),N);const{marker:P,showResultMarkers:B,flyTo:z,fullGeometryStyle:W,...s}=ue(this,I);(l=ue(this,k))==null||l.$set(s)}setQuery(N,P=!0){var B;(B=ue(this,k))==null||B.setQuery(N,P)}clearMap(){var N;(N=ue(this,k))==null||N.clearMap()}clearList(){var N;(N=ue(this,k))==null||N.clearList()}setReverseMode(N){var P;(P=ue(this,k))==null||P.$set({reverseActive:N})}focus(N){var P;(P=ue(this,k))==null||P.focus(N)}blur(){var N;(N=ue(this,k))==null||N.blur()}onRemove(){var N,P,B;(N=ue(this,k))==null||N.$destroy(),kt(this,k,void 0),(B=(P=ue(this,C))==null?void 0:P.parentNode)==null||B.removeChild(ue(this,C))}}return k=new WeakMap,I=new WeakMap,C=new WeakMap,{MapLibreBasedGeocodingControl:M,events:{SelectEvent:r,FeaturesListedEvent:u,FeaturesMarkedEvent:a,OptionsVisibilityChangeEvent:o,PickEvent:g,QueryChangeEvent:c,ResponseEvent:E,ReverseToggleEvent:_}}}const{MapLibreBasedGeocodingControl:rs,events:et}=ns(dt.Evented,dt);class ss extends rs{onAdd(e){return super.onAddInt(e)}}const os=et.SelectEvent,ls=et.FeaturesListedEvent,us=et.FeaturesMarkedEvent,as=et.OptionsVisibilityChangeEvent,fs=et.PickEvent,cs=et.QueryChangeEvent,hs=et.ResponseEvent,ds=et.ReverseToggleEvent;j.FeaturesListedEvent=ls,j.FeaturesMarkedEvent=us,j.GeocodingControl=ss,j.OptionsVisibilityChangeEvent=as,j.PickEvent=fs,j.QueryChangeEvent=cs,j.ResponseEvent=hs,j.ReverseToggleEvent=ds,j.SelectEvent=os,j.createMapLibreGlMapController=an,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"})}); +//# sourceMappingURL=maplibregl.umd.js.map diff --git a/docs/articles/turf_files/maptiler-geocoding-control-2.1.7/style.css b/docs/articles/turf_files/maptiler-geocoding-control-2.1.7/style.css new file mode 100644 index 0000000..c865c17 --- /dev/null +++ b/docs/articles/turf_files/maptiler-geocoding-control-2.1.7/style.css @@ -0,0 +1 @@ +svg.svelte-d2loi5{display:block;fill:#e15042}.sprite-icon.svelte-w9y5n9.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75;background-repeat:no-repeat}li.svelte-w9y5n9.svelte-w9y5n9{text-align:left;cursor:default;display:grid;grid-template-columns:40px 1fr;color:var(--color-text);padding:8px 0;font-size:14px;line-height:18px;min-width:fit-content;outline:0}li.svelte-w9y5n9.svelte-w9y5n9:first-child{padding-top:10px}li.svelte-w9y5n9.svelte-w9y5n9:last-child{padding-bottom:10px}li.picked.svelte-w9y5n9.svelte-w9y5n9{background-color:#e7edff}li.picked.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#96a4c7;padding-left:4px}li.picked.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#96a4c7}li.selected.svelte-w9y5n9.svelte-w9y5n9{background-color:#f3f6ff}li.selected.svelte-w9y5n9.svelte-w9y5n9{animation:svelte-w9y5n9-backAndForth 5s linear infinite}li.selected.svelte-w9y5n9 .primary.svelte-w9y5n9{color:#2b8bfb}li.selected.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#a2adc7;padding-left:4px}li.selected.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#a2adc7}li.svelte-w9y5n9>img.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75}.texts.svelte-w9y5n9.svelte-w9y5n9{padding:0 17px 0 0}.texts.svelte-w9y5n9>.svelte-w9y5n9{white-space:nowrap;display:block;min-width:fit-content}.primary.svelte-w9y5n9.svelte-w9y5n9{font-weight:600}.secondary.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7;padding-left:4px}.line2.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7}@keyframes svelte-w9y5n9-backAndForth{0%{transform:translate(0)}10%{transform:translate(0)}45%{transform:translate(calc(-100% + 270px))}55%{transform:translate(calc(-100% + 270px))}90%{transform:translate(0)}to{transform:translate(0)}}div.svelte-1ocfouu{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);pointer-events:none;display:flex;align-items:center}.loading-icon.svelte-1ocfouu{animation:svelte-1ocfouu-rotate .8s infinite cubic-bezier(.45,.05,.55,.95)}@keyframes svelte-1ocfouu-rotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}svg.svelte-gzo3ar.svelte-gzo3ar{display:block;fill:#6b7c93;stroke:#6b7c93}.list-icon.svelte-gzo3ar.svelte-gzo3ar{grid-row:1/3;align-self:center;margin:8px}.in-map.svelte-gzo3ar.svelte-gzo3ar{height:30px}.maplibregl-canvas-container .marker-selected{z-index:1}.maplibregl-canvas-container svg.svelte-gzo3ar path.svelte-gzo3ar,.leaflet-map-pane svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#3170fe;stroke:#3170fe}.marker-selected svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#98b7ff;stroke:#3170fe}.marker-reverse svg.svelte-gzo3ar path.svelte-gzo3ar{fill:silver;stroke:gray}.marker-interactive{cursor:pointer!important}.maptiler-gc-popup>.maplibregl-popup-content{padding:2px 8px}svg.svelte-en2qvf{display:block;fill:var(--color-icon-button)}circle.svelte-1aq105l{stroke-width:1.875;fill:none}path.svelte-1aq105l{stroke-width:1.875;stroke-linecap:round}svg.svelte-1aq105l{display:block;stroke:var(--color-icon-button)}form.svelte-bz0zu3.svelte-bz0zu3{font-family:Open Sans,Ubuntu,Helvetica Neue,Arial,Helvetica,sans-serif;position:relative;background-color:#fff;z-index:10;border-radius:4px;margin:0;transition:max-width .25s;box-shadow:0 2px 5px #33335926;--color-text:#444952;--color-icon-button:#444952}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3:after,form.svelte-bz0zu3 .svelte-bz0zu3:before{box-sizing:border-box}form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:29px}form.can-collapse.svelte-bz0zu3 input.svelte-bz0zu3::placeholder{transition:opacity .25s;opacity:0}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3.svelte-bz0zu3:focus-within,form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px}form.svelte-bz0zu3 input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:focus-within input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:hover input.svelte-bz0zu3::placeholder{opacity:1}input.svelte-bz0zu3.svelte-bz0zu3{font:inherit;font-size:14px;flex-grow:1;min-height:29px;background-color:transparent;color:#444952;white-space:nowrap;overflow:hidden;border:0;margin:0;padding:0}input.svelte-bz0zu3.svelte-bz0zu3:focus{color:#444952;outline:0;outline:none;box-shadow:none}ul.svelte-bz0zu3.svelte-bz0zu3,div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{background-color:#fff;border-radius:4px;left:0;list-style:none;margin:0;padding:0;position:absolute;width:100%;top:calc(100% + 6px);overflow:hidden}ul.svelte-bz0zu3.svelte-bz0zu3{font-size:14px;line-height:16px;box-shadow:0 5px 10px #33335926}div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{font:inherit;line-height:18px;font-size:12px;display:flex;gap:16px}div.error.svelte-bz0zu3.svelte-bz0zu3{padding:16px;font-weight:600;color:#e25041;background-color:#fbeae8}div.error.svelte-bz0zu3 div.svelte-bz0zu3{flex-grow:1}div.error.svelte-bz0zu3 svg{flex-shrink:0;width:20px;height:20px}div.error.svelte-bz0zu3 button.svelte-bz0zu3{flex-shrink:0}div.error.svelte-bz0zu3 button.svelte-bz0zu3>svg{width:13px;fill:#e25041}div.error.svelte-bz0zu3 button.svelte-bz0zu3:hover svg,div.error.svelte-bz0zu3 button.svelte-bz0zu3:active svg{fill:#444952}div.no-results.svelte-bz0zu3.svelte-bz0zu3{padding:14px 24px 14px 16px;font-weight:400;color:#6b7c93;box-shadow:0 5px 10px #33335926}div.no-results.svelte-bz0zu3 svg{margin-top:4px;flex-shrink:0;width:20px;height:20px;width:30px;height:30px}.leaflet-bottom ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-left ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-right ul.options.svelte-bz0zu3.svelte-bz0zu3{top:auto;bottom:calc(100% + 6px)}button.svelte-bz0zu3.svelte-bz0zu3{padding:0;margin:0;border:0;background-color:transparent;height:auto;width:auto}button.svelte-bz0zu3.svelte-bz0zu3:hover{background-color:transparent}button.svelte-bz0zu3:hover svg,button.svelte-bz0zu3:active svg{fill:#2b8bfb}.input-group.svelte-bz0zu3.svelte-bz0zu3{display:flex;align-items:stretch;gap:7px;padding-inline:8px;border-radius:4px;overflow:hidden}.input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{outline:#2b8bfb solid 2px}.search-button.svelte-bz0zu3.svelte-bz0zu3{flex-shrink:0}.maplibregl-ctrl-geocoder:not(.maptiler-ctrl) .search-button svg{width:12px!important;transform:translate(.5px)}.clear-button-container.svelte-bz0zu3.svelte-bz0zu3{display:flex;display:none;position:relative;align-items:stretch}.clear-button-container.displayable.svelte-bz0zu3.svelte-bz0zu3{display:flex;flex-shrink:0}.maplibregl-ctrl-geocoder{position:relative;z-index:3}.maptiler-ctrl:not(:empty){box-shadow:none}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3{padding-inline:8px;border:white solid 2px}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{border:#2b8bfb solid 2px;outline:0;outline:none}.maptiler-ctrl form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:33px}.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:focus-within,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px} diff --git a/docs/articles/turf_files/pmtiles-4.3.0/pmtiles.js b/docs/articles/turf_files/pmtiles-4.3.0/pmtiles.js new file mode 100644 index 0000000..1a901ee --- /dev/null +++ b/docs/articles/turf_files/pmtiles-4.3.0/pmtiles.js @@ -0,0 +1,2 @@ +"use strict";var pmtiles=(()=>{var k=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var U=Math.pow;var f=(r,e)=>k(r,"name",{value:e,configurable:!0});var Xe=(r,e)=>{for(var t in e)k(r,t,{get:e[t],enumerable:!0})},_e=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ye(e))!Qe.call(r,i)&&i!==t&&k(r,i,{get:()=>e[i],enumerable:!(n=Je(e,i))||n.enumerable});return r};var et=r=>_e(k({},"__esModule",{value:!0}),r);var m=(r,e,t)=>new Promise((n,i)=>{var a=h=>{try{u(t.next(h))}catch(l){i(l)}},s=h=>{try{u(t.throw(h))}catch(l){i(l)}},u=h=>h.done?n(h.value):Promise.resolve(h.value).then(a,s);u((t=t.apply(r,e)).next())});var Dt={};Xe(Dt,{Compression:()=>Oe,EtagMismatch:()=>B,FetchSource:()=>K,FileSource:()=>oe,PMTiles:()=>P,Protocol:()=>ie,ResolvedValueCache:()=>ue,SharedPromiseCache:()=>G,TileType:()=>se,bytesToHeader:()=>$e,findTile:()=>Fe,getUint64:()=>b,leafletRasterLayer:()=>wt,readVarint:()=>R,tileIdToZxy:()=>Tt,tileTypeExt:()=>Ze,zxyToTileId:()=>Ie});var w=Uint8Array,E=Uint16Array,tt=Int32Array,Me=new w([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ue=new w([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),rt=new w([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ee=f(function(r,e){for(var t=new E(31),n=0;n<31;++n)t[n]=e+=1<>1|(g&21845)<<1,T=(T&52428)>>2|(T&13107)<<2,T=(T&61680)>>4|(T&3855)<<4,re[g]=((T&65280)>>8|(T&255)<<8)>>1;var T,g,F=f(function(r,e,t){for(var n=r.length,i=0,a=new E(e);i>h]=l}else for(u=new E(n),i=0;i>15-r[i]);return u},"hMap"),$=new w(288);for(g=0;g<144;++g)$[g]=8;var g;for(g=144;g<256;++g)$[g]=9;var g;for(g=256;g<280;++g)$[g]=7;var g;for(g=280;g<288;++g)$[g]=8;var g,Re=new w(32);for(g=0;g<32;++g)Re[g]=5;var g;var at=F($,9,1);var st=F(Re,5,1),ee=f(function(r){for(var e=r[0],t=1;te&&(e=r[t]);return e},"max"),z=f(function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},"bits"),te=f(function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},"bits16"),ot=f(function(r){return(r+7)/8|0},"shft"),ut=f(function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new w(r.subarray(e,t))},"slc");var ft=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],y=f(function(r,e,t){var n=new Error(e||ft[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,y),!t)throw n;return n},"err"),ne=f(function(r,e,t,n){var i=r.length,a=n?n.length:0;if(!i||e.f&&!e.l)return t||new w(0);var s=!t,u=s||e.i!=2,h=e.i;s&&(t=new w(i*3));var l=f(function(Te){var Ce=t.length;if(Te>Ce){var De=new w(Math.max(Ce*2,Te));De.set(t),t=De}},"cbuf"),c=e.f||0,o=e.p||0,v=e.b||0,d=e.l,p=e.d,H=e.m,I=e.n,q=i*8;do{if(!d){c=z(r,o,1);var j=z(r,o+1,3);if(o+=3,j)if(j==1)d=at,p=st,H=9,I=5;else if(j==2){var J=z(r,o,31)+257,me=z(r,o+10,15)+4,de=J+z(r,o+5,31)+1;o+=14;for(var O=new w(de),Y=new w(19),x=0;x>4;if(A<16)O[x++]=A;else{var D=0,V=0;for(A==16?(V=3+z(r,o,3),o+=2,D=O[x-1]):A==17?(V=3+z(r,o,7),o+=3):A==18&&(V=11+z(r,o,127),o+=7);V--;)O[x++]=D}}var xe=O.subarray(0,J),C=O.subarray(J);H=ee(xe),I=ee(C),d=F(xe,H,1),p=F(C,I,1)}else y(1);else{var A=ot(o)+4,W=r[A-4]|r[A-3]<<8,N=A+W;if(N>i){h&&y(0);break}u&&l(v+W),t.set(r.subarray(A,N),v),e.b=v+=W,e.p=o=N*8,e.f=c;continue}if(o>q){h&&y(0);break}}u&&l(v+131072);for(var je=(1<>4;if(o+=D&15,o>q){h&&y(0);break}if(D||y(2),M<256)t[v++]=M;else if(M==256){Q=o,d=null;break}else{var be=M-254;if(M>264){var x=M-257,Z=Me[x];be=z(r,o,(1<>4;X||y(3),o+=X&15;var C=it[_];if(_>3){var Z=Ue[_];C+=te(r,o)&(1<q){h&&y(0);break}u&&l(v+131072);var ze=v+be;if(v>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},"gzs"),ct=f(function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0},"gzl");var vt=f(function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&y(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&y(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2},"zls");function gt(r,e){return ne(r,{i:2},e&&e.out,e&&e.dictionary)}f(gt,"inflateSync");function pt(r,e){var t=ht(r);return t+8>r.length&&y(6,"invalid gzip data"),ne(r.subarray(t,-8),{i:2},e&&e.out||new w(ct(r)),e&&e.dictionary)}f(pt,"gunzipSync");function mt(r,e){return ne(r.subarray(vt(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}f(mt,"unzlibSync");function Be(r,e){return r[0]==31&&r[1]==139&&r[2]==8?pt(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?gt(r,e):mt(r,e)}f(Be,"decompressSync");var dt=typeof TextDecoder!="undefined"&&new TextDecoder,yt=0;try{dt.decode(lt,{stream:!0}),yt=1}catch(r){}var wt=f((r,e)=>{let t=!1,n="",i=L.GridLayer.extend({createTile:f((a,s)=>{let u=document.createElement("img"),h=new AbortController,l=h.signal;return u.cancel=()=>{h.abort()},t||(r.getHeader().then(c=>{c.tileType===1?console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):c.tileType===2?n="image/png":c.tileType===3?n="image/jpeg":c.tileType===4?n="image/webp":c.tileType===5&&(n="image/avif")}),t=!0),r.getZxy(a.z,a.x,a.y,l).then(c=>{if(c){let o=new Blob([c.data],{type:n}),v=window.URL.createObjectURL(o);u.src=v,u.cancel=void 0,s(void 0,u)}}).catch(c=>{if(c.name!=="AbortError")throw c}),u},"createTile"),_removeTile:f(function(a){let s=this._tiles[a];s&&(s.el.cancel&&s.el.cancel(),s.el.width=0,s.el.height=0,s.el.deleted=!0,L.DomUtil.remove(s.el),delete this._tiles[a],this.fire("tileunload",{tile:s.el,coords:this._keyToTileCoords(a)}))},"_removeTile")});return new i(e)},"leafletRasterLayer"),xt=f(r=>(e,t)=>{if(t instanceof AbortController)return r(e,t);let n=new AbortController;return r(e,n).then(i=>t(void 0,i.data,i.cacheControl||"",i.expires||""),i=>t(i)).catch(i=>t(i)),{cancel:f(()=>n.abort(),"cancel")}},"v3compat"),ae=class ae{constructor(e){this.tilev4=f((e,t)=>m(this,null,function*(){if(e.type==="json"){let v=e.url.substr(10),d=this.tiles.get(v);if(d||(d=new P(v),this.tiles.set(v,d)),this.metadata)return{data:yield d.getTileJson(e.url)};let p=yield d.getHeader();return(p.minLon>=p.maxLon||p.minLat>=p.maxLat)&&console.error(`Bounds of PMTiles archive ${p.minLon},${p.minLat},${p.maxLon},${p.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:p.minZoom,maxzoom:p.maxZoom,bounds:[p.minLon,p.minLat,p.maxLon,p.maxLat]}}}let n=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),i=e.url.match(n);if(!i)throw new Error("Invalid PMTiles protocol URL");let a=i[1],s=this.tiles.get(a);s||(s=new P(a),this.tiles.set(a,s));let u=i[2],h=i[3],l=i[4],c=yield s.getHeader(),o=yield s==null?void 0:s.getZxy(+u,+h,+l,t.signal);if(o)return{data:new Uint8Array(o.data),cacheControl:o.cacheControl,expires:o.expires};if(c.tileType===1){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4");this.tile=xt(this.tilev4);this.tiles=new Map,this.metadata=(e==null?void 0:e.metadata)||!1,this.errorOnMissingTile=(e==null?void 0:e.errorOnMissingTile)||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};f(ae,"Protocol");var ie=ae;function S(r,e){return(e>>>0)*4294967296+(r>>>0)}f(S,"toNum");function bt(r,e){let t=e.buf,n=t[e.pos++],i=(n&112)>>4;if(n<128||(n=t[e.pos++],i|=(n&127)<<3,n<128)||(n=t[e.pos++],i|=(n&127)<<10,n<128)||(n=t[e.pos++],i|=(n&127)<<17,n<128)||(n=t[e.pos++],i|=(n&127)<<24,n<128)||(n=t[e.pos++],i|=(n&1)<<31,n<128))return S(r,i);throw new Error("Expected varint not more than 10 bytes")}f(bt,"readVarintRemainder");function R(r){let e=r.buf,t=e[r.pos++],n=t&127;return t<128||(t=e[r.pos++],n|=(t&127)<<7,t<128)||(t=e[r.pos++],n|=(t&127)<<14,t<128)||(t=e[r.pos++],n|=(t&127)<<21,t<128)?n:(t=e[r.pos],n|=(t&15)<<28,bt(n,r))}f(R,"readVarint");function He(r,e,t,n){if(n===0){t===1&&(e[0]=r-1-e[0],e[1]=r-1-e[1]);let i=e[0];e[0]=e[1],e[1]=i}}f(He,"rotate");function zt(r,e){let t=U(2,r),n=e,i=e,a=e,s=[0,0],u=1;for(;u26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>U(2,r)-1||t>U(2,r)-1)throw new Error("tile x/y outside zoom level bounds");let n=At[r],i=U(2,r),a=0,s=0,u=0,h=[e,t],l=i/2;for(;l>0;)a=(h[0]&l)>0?1:0,s=(h[1]&l)>0?1:0,u+=l*l*(3*a^s),He(l,h,a,s),l=l/2;return n+u}f(Ie,"zxyToTileId");function Tt(r){let e=0,t=0;for(let n=0;n<27;n++){let i=(1<r)return zt(n,r-e);e+=i}throw new Error("Tile zoom level exceeds max safe number limit (26)")}f(Tt,"tileIdToZxy");var Oe=(a=>(a[a.Unknown=0]="Unknown",a[a.None=1]="None",a[a.Gzip=2]="Gzip",a[a.Brotli=3]="Brotli",a[a.Zstd=4]="Zstd",a))(Oe||{});function fe(r,e){return m(this,null,function*(){if(e===1||e===0)return r;if(e===2){if(typeof globalThis.DecompressionStream=="undefined")return Be(new Uint8Array(r));let t=new Response(r).body;if(!t)throw new Error("Failed to read response stream");let n=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(n).arrayBuffer()}throw new Error("Compression method not supported")})}f(fe,"defaultDecompress");var se=(s=>(s[s.Unknown=0]="Unknown",s[s.Mvt=1]="Mvt",s[s.Png=2]="Png",s[s.Jpeg=3]="Jpeg",s[s.Webp=4]="Webp",s[s.Avif=5]="Avif",s))(se||{});function Ze(r){return r===1?".mvt":r===2?".png":r===3?".jpg":r===4?".webp":r===5?".avif":""}f(Ze,"tileTypeExt");var Ct=127;function Fe(r,e){let t=0,n=r.length-1;for(;t<=n;){let i=n+t>>1,a=e-r[i].tileId;if(a>0)t=i+1;else if(a<0)n=i-1;else return r[i]}return n>=0&&(r[n].runLength===0||e-r[n].tileId-1,a=/Chrome|Chromium|Edg|OPR|Brave/.test(n);this.chromeWindowsNoCache=!1,i&&a&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,n,i){return m(this,null,function*(){let a,s;n?s=n:(a=new AbortController,s=a.signal);let u=new Headers(this.customHeaders);u.set("range",`bytes=${e}-${e+t-1}`);let h;this.mustReload?h="reload":this.chromeWindowsNoCache&&(h="no-store");let l=yield fetch(this.url,{signal:s,cache:h,headers:u});if(e===0&&l.status===416){let d=l.headers.get("Content-Range");if(!d||!d.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let p=+d.substr(8);l=yield fetch(this.url,{signal:s,cache:"reload",headers:{range:`bytes=0-${p-1}`}})}let c=l.headers.get("Etag");if(c!=null&&c.startsWith("W/")&&(c=null),l.status===416||i&&c&&c!==i)throw this.mustReload=!0,new B(`Server returned non-matching ETag ${i} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(l.status>=300)throw new Error(`Bad response code: ${l.status}`);let o=l.headers.get("Content-Length");if(l.status===200&&(!o||+o>t))throw a&&a.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield l.arrayBuffer(),etag:c||void 0,cacheControl:l.headers.get("Cache-Control")||void 0,expires:l.headers.get("Expires")||void 0}})}};f(he,"FetchSource");var K=he;function b(r,e){let t=r.getUint32(e+4,!0),n=r.getUint32(e+0,!0);return t*U(2,32)+n}f(b,"getUint64");function $e(r,e){let t=new DataView(r),n=t.getUint8(7);if(n>3)throw new Error(`Archive is spec version ${n} but this library supports up to spec version 3`);return{specVersion:n,rootDirectoryOffset:b(t,8),rootDirectoryLength:b(t,16),jsonMetadataOffset:b(t,24),jsonMetadataLength:b(t,32),leafDirectoryOffset:b(t,40),leafDirectoryLength:b(t,48),tileDataOffset:b(t,56),tileDataLength:b(t,64),numAddressedTiles:b(t,72),numTileEntries:b(t,80),numTileContents:b(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}f($e,"bytesToHeader");function Ve(r){let e={buf:new Uint8Array(r),pos:0},t=R(e),n=[],i=0;for(let a=0;a0?n[a].offset=n[a-1].offset+n[a-1].length:n[a].offset=s-1}return n}f(Ve,"deserializeIndex");var ce=class ce extends Error{};f(ce,"EtagMismatch");var B=ce;function ke(r,e){return m(this,null,function*(){let t=yield r.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let i=t.data.slice(0,Ct),a=$e(i,t.etag),s=t.data.slice(a.rootDirectoryOffset,a.rootDirectoryOffset+a.rootDirectoryLength),u=`${r.getKey()}|${a.etag||""}|${a.rootDirectoryOffset}|${a.rootDirectoryLength}`,h=Ve(yield e(s,a.internalCompression));return[a,[u,h.length,h]]})}f(ke,"getHeaderAndRoot");function Ke(r,e,t,n,i){return m(this,null,function*(){let a=yield r.getBytes(t,n,void 0,i.etag),s=yield e(a.data,i.internalCompression),u=Ve(s);if(u.length===0)throw new Error("Empty directory is invalid");return u})}f(Ke,"getDirectory");var ve=class ve{constructor(e=100,t=!0,n=fe){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return m(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,n.data;let i=yield ke(e,this.decompress);return i[1]&&this.cache.set(i[1][0],{lastUsed:this.counter++,data:i[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:i[0]}),this.prune(),i[0]})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,s.data;let u=yield Ke(e,this.decompress,t,n,i);return this.cache.set(a,{lastUsed:this.counter++,data:u}),this.prune(),u})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{ke(e,this.decompress).then(u=>{u[1]&&this.cache.set(u[1][0],{lastUsed:this.counter++,data:Promise.resolve(u[1][2])}),a(u[0]),this.prune()}).catch(u=>{s(u)})});return this.cache.set(t,{lastUsed:this.counter++,data:i}),i})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,yield s.data;let u=new Promise((h,l)=>{Ke(e,this.decompress,t,n,i).then(c=>{h(c),this.prune()}).catch(c=>{l(c)})});return this.cache.set(a,{lastUsed:this.counter++,data:u}),u})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{this.getHeader(e).then(s=>{i(),this.invalidations.delete(t)}).catch(s=>{a(s)})});this.invalidations.set(t,n)})}};f(ge,"SharedPromiseCache");var G=ge,pe=class pe{constructor(e,t,n){typeof e=="string"?this.source=new K(e):this.source=e,n?this.decompress=n:this.decompress=fe,t?this.cache=t:this.cache=new G}getHeader(){return m(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,n,i){return m(this,null,function*(){let a=Ie(e,t,n),s=yield this.cache.getHeader(this.source);if(es.maxZoom)return;let u=s.rootDirectoryOffset,h=s.rootDirectoryLength;for(let l=0;l<=3;l++){let c=yield this.cache.getDirectory(this.source,u,h,s),o=Fe(c,a);if(o){if(o.runLength>0){let v=yield this.source.getBytes(s.tileDataOffset+o.offset,o.length,i,s.etag);return{data:yield this.decompress(v.data,s.tileCompression),cacheControl:v.cacheControl,expires:v.expires}}u=s.leafDirectoryOffset+o.offset,h=o.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,n,i){return m(this,null,function*(){try{return yield this.getZxyAttempt(e,t,n,i)}catch(a){if(a instanceof B)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,n,i);throw a}})}getMetadataAttempt(){return m(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),n=yield this.decompress(t.data,e.internalCompression),i=new TextDecoder("utf-8");return JSON.parse(i.decode(n))})}getMetadata(){return m(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof B)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return m(this,null,function*(){let t=yield this.getHeader(),n=yield this.getMetadata(),i=Ze(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${i}`],vector_layers:n.vector_layers,attribution:n.attribution,description:n.description,name:n.name,version:n.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};f(pe,"PMTiles");var P=pe;return et(Dt);})(); +//# sourceMappingURL=pmtiles.js.map \ No newline at end of file diff --git a/docs/articles/turf_files/radius-mode-1.0.0/radius-mode.js b/docs/articles/turf_files/radius-mode-1.0.0/radius-mode.js new file mode 100644 index 0000000..2b7b5bf --- /dev/null +++ b/docs/articles/turf_files/radius-mode-1.0.0/radius-mode.js @@ -0,0 +1,311 @@ +// Radius/Circle drawing mode for Mapbox GL Draw +// Creates a circle by drawing from center to edge +(function (MapboxDraw) { + const DrawLine = MapboxDraw.modes.draw_line_string; + + // Utility function to create a vertex feature + const createVertex = function (parentId, coordinates, path, selected) { + return { + type: "Feature", + properties: { + meta: "vertex", + parent: parentId, + coord_path: path, + active: selected ? "true" : "false" + }, + geometry: { + type: "Point", + coordinates: coordinates + } + }; + }; + + // Utility function to calculate distance between two points in kilometers + const calculateDistance = function (coord1, coord2) { + const lat1 = coord1[1]; + const lon1 = coord1[0]; + const lat2 = coord2[1]; + const lon2 = coord2[0]; + + const R = 6371; // Radius of the Earth in kilometers + const dLat = (lat2 - lat1) * Math.PI / 180; + const dLon = (lon2 - lon1) * Math.PI / 180; + const a = + Math.sin(dLat/2) * Math.sin(dLat/2) + + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * + Math.sin(dLon/2) * Math.sin(dLon/2); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + const distance = R * c; + + return distance; + }; + + // Utility function to create a GeoJSON circle + const createGeoJSONCircle = function (center, radiusInKm, parentId, points) { + points = points || 64; + + const coords = { + latitude: center[1], + longitude: center[0] + }; + + const km = radiusInKm; + const ret = []; + const distanceX = km / (111.32 * Math.cos((coords.latitude * Math.PI) / 180)); + const distanceY = km / 110.574; + + let theta, x, y; + for (let i = 0; i < points; i++) { + theta = (i / points) * (2 * Math.PI); + x = distanceX * Math.cos(theta); + y = distanceY * Math.sin(theta); + + ret.push([coords.longitude + x, coords.latitude + y]); + } + ret.push(ret[0]); + + return { + type: "Feature", + geometry: { + type: "Polygon", + coordinates: [ret] + }, + properties: { + parent: parentId, + meta: "radius" + } + }; + }; + + // Utility function to format distance for display + const getDisplayMeasurements = function (distanceKm) { + let metricUnits = "m"; + let metricFormat = "0,0"; + let metricMeasurement; + + let standardUnits = "feet"; + let standardFormat = "0,0"; + let standardMeasurement; + + metricMeasurement = distanceKm * 1000; // Convert to meters + if (metricMeasurement >= 1000) { + metricMeasurement = metricMeasurement / 1000; + metricUnits = "km"; + metricFormat = "0.00"; + } + + standardMeasurement = distanceKm * 1000 * 3.28084; // Convert to feet + if (standardMeasurement >= 5280) { + standardMeasurement = standardMeasurement / 5280; + standardUnits = "mi"; + standardFormat = "0.00"; + } + + // Simple number formatting (without numeral.js dependency) + const formatNumber = function(num, format) { + if (format === "0,0") { + return Math.round(num).toLocaleString(); + } else if (format === "0.00") { + return num.toFixed(2); + } + return num.toString(); + }; + + return { + metric: formatNumber(metricMeasurement, metricFormat) + " " + metricUnits, + standard: formatNumber(standardMeasurement, standardFormat) + " " + standardUnits + }; + }; + + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RadiusMode = Object.assign({}, DrawLine); + + RadiusMode.onSetup = function (opts) { + const line = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "LineString", + coordinates: [] + } + }); + + this.addFeature(line); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.activateUIButton("line"); + this.setActionableState({ trash: true }); + + return { + line: line, + currentVertexPosition: 0, + direction: "forward" + }; + }; + + RadiusMode.onClick = function (state, e) { + // This ends the drawing after the user creates a second point + if (state.currentVertexPosition === 1) { + // Update the second coordinate in place, don't add at position 0 + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + return this.changeMode("simple_select", { featureIds: [state.line.id] }); + } + + this.updateUIClasses({ mouse: "add" }); + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + + if (state.direction === "forward") { + state.currentVertexPosition += 1; + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + } else { + state.line.addCoordinate(0, e.lngLat.lng, e.lngLat.lat); + } + + return null; + }; + + RadiusMode.onMouseMove = function (state, e) { + if (state.currentVertexPosition === 1) { + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + } + }; + + // Creates the final geojson circle polygon + RadiusMode.onStop = function (state) { + doubleClickZoom.enable(this); + this.activateUIButton(); + + // Check to see if we've deleted this feature + if (this.getFeature(state.line.id) === undefined) return; + + if (state.line.isValid()) { + const lineGeoJson = state.line.toGeoJSON(); + const coords = lineGeoJson.geometry.coordinates; + + if (coords.length >= 2) { + // Calculate radius in kilometers + const radiusKm = calculateDistance(coords[0], coords[1]); + + // Create the circle polygon + const circleFeature = createGeoJSONCircle(coords[0], radiusKm, state.line.id); + + // Add radius property for reference + circleFeature.properties.radius = (radiusKm * 1000).toFixed(1); + + // Remove the meta property that was interfering + delete circleFeature.properties.meta; + delete circleFeature.properties.parent; + + // Delete the temporary line first + this.deleteFeature([state.line.id], { silent: true }); + + // Add the circle feature to the draw instance + const circleDrawFeature = this.newFeature(circleFeature); + this.addFeature(circleDrawFeature); + + this.map.fire("draw.create", { + features: [circleDrawFeature.toGeoJSON()] + }); + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + + this.changeMode("simple_select", {}, { silent: true }); + }; + + RadiusMode.toDisplayFeatures = function (state, geojson, display) { + const isActiveLine = geojson.properties.id === state.line.id; + geojson.properties.active = isActiveLine ? "true" : "false"; + + if (!isActiveLine) return display(geojson); + + // Only render the line if it has at least one real coordinate + if (geojson.geometry.coordinates.length < 2) return null; + + geojson.properties.meta = "feature"; + + // Display center vertex as a point feature + display(createVertex( + state.line.id, + geojson.geometry.coordinates[ + state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1 + ], + "" + (state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1), + false + )); + + // Display the line as it is drawn + display(geojson); + + const coords = geojson.geometry.coordinates; + if (coords.length >= 2) { + const distanceKm = calculateDistance(coords[0], coords[1]); + const displayMeasurements = getDisplayMeasurements(distanceKm); + + // Create custom feature for the current pointer position + const currentVertex = { + type: "Feature", + properties: { + meta: "currentPosition", + radiusMetric: displayMeasurements.metric, + radiusStandard: displayMeasurements.standard, + parent: state.line.id + }, + geometry: { + type: "Point", + coordinates: coords[1] + } + }; + display(currentVertex); + + // Create custom feature for radius circle + const center = coords[0]; + const circleFeature = createGeoJSONCircle(center, distanceKm, state.line.id); + display(circleFeature); + } + + return null; + }; + + RadiusMode.onTrash = function (state) { + this.deleteFeature([state.line.id], { silent: true }); + this.changeMode("simple_select"); + }; + + MapboxDraw.modes.draw_radius = RadiusMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/turf_files/rectangle-mode-1.0.0/rectangle-mode.js b/docs/articles/turf_files/rectangle-mode-1.0.0/rectangle-mode.js new file mode 100644 index 0000000..73af6d6 --- /dev/null +++ b/docs/articles/turf_files/rectangle-mode-1.0.0/rectangle-mode.js @@ -0,0 +1,124 @@ +// Rectangle drawing mode for Mapbox GL Draw +// Adapted from https://github.com/edgespatial/mapbox-gl-draw-rectangle-mode +(function (MapboxDraw) { + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RectangleMode = { + onSetup: function (opts) { + const rectangle = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "Polygon", + coordinates: [[]] + } + }); + + this.addFeature(rectangle); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.setActionableState({ trash: true }); + + return { + rectangle: rectangle + }; + }, + + onClick: function (state, e) { + // If we have a start point and click on a different point, complete the rectangle + if (state.startPoint && + (state.startPoint[0] !== e.lngLat.lng || state.startPoint[1] !== e.lngLat.lat)) { + this.updateUIClasses({ mouse: "pointer" }); + state.endPoint = [e.lngLat.lng, e.lngLat.lat]; + this.changeMode("simple_select", { featuresId: state.rectangle.id }); + return; + } + + // Set the start point + const startPoint = [e.lngLat.lng, e.lngLat.lat]; + state.startPoint = startPoint; + }, + + onMouseMove: function (state, e) { + // Update rectangle coordinates as the mouse moves + if (state.startPoint) { + const startX = state.startPoint[0]; + const startY = state.startPoint[1]; + const endX = e.lngLat.lng; + const endY = e.lngLat.lat; + + state.rectangle.updateCoordinate("0.0", startX, startY); + state.rectangle.updateCoordinate("0.1", endX, startY); + state.rectangle.updateCoordinate("0.2", endX, endY); + state.rectangle.updateCoordinate("0.3", startX, endY); + state.rectangle.updateCoordinate("0.4", startX, startY); + } + }, + + onKeyUp: function (state, e) { + if (e.keyCode === 27) { // Escape key + return this.changeMode("simple_select"); + } + }, + + onStop: function (state) { + doubleClickZoom.enable(this); + this.updateUIClasses({ mouse: "none" }); + this.activateUIButton(); + + if (this.getFeature(state.rectangle.id) !== undefined) { + // Remove the closing coordinate (duplicate of first) + state.rectangle.removeCoordinate("0.4"); + + if (state.rectangle.isValid()) { + this.map.fire("draw.create", { + features: [state.rectangle.toGeoJSON()] + }); + } else { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select", {}, { silent: true }); + } + } + }, + + toDisplayFeatures: function (state, geojson, display) { + const isActiveRectangle = geojson.properties.id === state.rectangle.id; + geojson.properties.active = isActiveRectangle ? "true" : "false"; + + if (!isActiveRectangle) { + return display(geojson); + } + + // Only display the rectangle if we have started drawing + if (state.startPoint) { + return display(geojson); + } + }, + + onTrash: function (state) { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select"); + } + }; + + MapboxDraw.modes.draw_rectangle = RectangleMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/turf_files/turf-7.2.0/turf.min.js b/docs/articles/turf_files/turf-7.2.0/turf.min.js new file mode 100644 index 0000000..635896d --- /dev/null +++ b/docs/articles/turf_files/turf-7.2.0/turf.min.js @@ -0,0 +1,37 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).turf={})}(this,(function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}function u(t,e,n){return(e=y(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function l(t){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},l(t)}function h(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&p(t,e)}function c(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(c=function(){return!!t})()}function f(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}function g(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function p(t,e){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},p(t,e)}function v(t,e){return n(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,o,s,a=[],u=!0,l=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);u=!0);}catch(t){l=!0,i=t}finally{try{if(!u&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw i}}return a}}(t,e)||_(t,e)||g()}function d(t){return function(t){if(Array.isArray(t))return e(t)}(t)||f(t)||_(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function m(t){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},m(t)}function _(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var x=6371008.8,E={centimeters:100*x,centimetres:100*x,degrees:360/(2*Math.PI),feet:3.28084*x,inches:39.37*x,kilometers:x/1e3,kilometres:x/1e3,meters:x,metres:x,miles:x/1609.344,millimeters:1e3*x,millimetres:1e3*x,nauticalmiles:x/1852,radians:1,yards:1.0936*x},k={acres:247105e-9,centimeters:1e4,centimetres:1e4,feet:10.763910417,hectares:1e-4,inches:1550.003100006,kilometers:1e-6,kilometres:1e-6,meters:1,metres:1,miles:386e-9,nauticalmiles:2.9155334959812285e-7,millimeters:1e6,millimetres:1e6,yards:1.195990046};function b(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={type:"Feature"};return(0===n.id||n.id)&&(r.id=n.id),n.bbox&&(r.bbox=n.bbox),r.properties=e||{},r.geometry=t,r}function w(t,e){switch(t){case"Point":return I(e).geometry;case"LineString":return L(e).geometry;case"Polygon":return S(e).geometry;case"MultiPoint":return O(e).geometry;case"MultiLineString":return T(e).geometry;case"MultiPolygon":return R(e).geometry;default:throw new Error(t+" is invalid")}}function I(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("coordinates is required");if(!Array.isArray(t))throw new Error("coordinates must be an Array");if(t.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!U(t[0])||!U(t[1]))throw new Error("coordinates must contain numbers");return b({type:"Point",coordinates:t},e,n)}function N(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return I(t,e)})),n)}function S(t,e){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=a(t);try{for(i.s();!(n=i.n()).done;){var o=n.value;if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(var s=0;s2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return S(t,e)})),n)}function L(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(t.length<2)throw new Error("coordinates must be an array of two or more positions");return b({type:"LineString",coordinates:t},e,n)}function P(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return L(t,e)})),n)}function C(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={type:"FeatureCollection"};return e.id&&(n.id=e.id),e.bbox&&(n.bbox=e.bbox),n.features=t,n}function T(t,e){return b({type:"MultiLineString",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function O(t,e){return b({type:"MultiPoint",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function R(t,e){return b({type:"MultiPolygon",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function A(t,e){return b({type:"GeometryCollection",geometries:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function D(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e&&!(e>=0))throw new Error("precision must be a positive number");var n=Math.pow(10,e||0);return Math.round(t*n)/n}function F(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t*n}function q(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t/n}function V(t,e){return Y(q(t,e))}function G(t){var e=t%360;return e<0&&(e+=360),e}function B(t){return(t%=360)>180?t-360:t<-180?t+360:t}function Y(t){return 180*(t%(2*Math.PI))/Math.PI}function z(t){return t%360*Math.PI/180}function j(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("length must be a positive number");return F(q(t,e),n)}function X(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"meters",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("area must be a positive number");var r=k[e];if(!r)throw new Error("invalid original units");var i=k[n];if(!i)throw new Error("invalid final units");return t/r*i}function U(t){return!isNaN(t)&&null!==t&&!Array.isArray(t)}function Z(t){return null!==t&&"object"===m(t)&&!Array.isArray(t)}function H(t){if(!t)throw new Error("bbox is required");if(!Array.isArray(t))throw new Error("bbox must be an Array");if(4!==t.length&&6!==t.length)throw new Error("bbox must be an Array of 4 or 6 numbers");t.forEach((function(t){if(!U(t))throw new Error("bbox must only contain numbers")}))}function W(t){if(!t)throw new Error("id is required");if(-1===["string","number"].indexOf(m(t)))throw new Error("id must be a number or a string")}var J=Object.freeze({__proto__:null,areaFactors:k,azimuthToBearing:B,bearingToAzimuth:G,convertArea:X,convertLength:j,degreesToRadians:z,earthRadius:x,factors:E,feature:b,featureCollection:C,geometry:w,geometryCollection:A,isNumber:U,isObject:Z,lengthToDegrees:V,lengthToRadians:q,lineString:L,lineStrings:P,multiLineString:T,multiPoint:O,multiPolygon:R,point:I,points:N,polygon:S,polygons:M,radiansToDegrees:Y,radiansToLength:F,round:D,validateBBox:H,validateId:W});function K(t){if(!t)throw new Error("coord is required");if(!Array.isArray(t)){if("Feature"===t.type&&null!==t.geometry&&"Point"===t.geometry.type)return d(t.geometry.coordinates);if("Point"===t.type)return d(t.coordinates)}if(Array.isArray(t)&&t.length>=2&&!Array.isArray(t[0])&&!Array.isArray(t[1]))return d(t);throw new Error("coord must be GeoJSON Point or an Array of numbers")}function Q(t){if(Array.isArray(t))return t;if("Feature"===t.type){if(null!==t.geometry)return t.geometry.coordinates}else if(t.coordinates)return t.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function $(t){if(t.length>1&&U(t[0])&&U(t[1]))return!0;if(Array.isArray(t[0])&&t[0].length)return $(t[0]);throw new Error("coordinates must only contain numbers")}function tt(t,e,n){if(!e||!n)throw new Error("type and name required");if(!t||t.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.type)}function et(t,e,n){if(!t)throw new Error("No feature passed");if(!n)throw new Error(".featureOf() requires a name");if(!t||"Feature"!==t.type||!t.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!t.geometry||t.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.geometry.type)}function nt(t,e,n){if(!t)throw new Error("No featureCollection passed");if(!n)throw new Error(".collectionOf() requires a name");if(!t||"FeatureCollection"!==t.type)throw new Error("Invalid input to "+n+", FeatureCollection required");var r,i=a(t.features);try{for(i.s();!(r=i.n()).done;){var o=r.value;if(!o||"Feature"!==o.type||!o.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!o.geometry||o.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+o.geometry.type)}}catch(t){i.e(t)}finally{i.f()}}function rt(t){return"Feature"===t.type?t.geometry:t}function it(t,e){return"FeatureCollection"===t.type?"FeatureCollection":"GeometryCollection"===t.type?"GeometryCollection":"Feature"===t.type&&null!==t.geometry?t.geometry.type:t.type}var ot=Object.freeze({__proto__:null,collectionOf:nt,containsNumber:$,featureOf:et,geojsonType:tt,getCoord:K,getCoords:Q,getGeom:rt,getType:it});function st(t,e){if(!0===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final)return function(t,e){var n=st(e,t);return n=(n+180)%360}(t,e);var n=K(t),r=K(e),i=z(n[0]),o=z(r[0]),s=z(n[1]),a=z(r[1]),u=Math.sin(o-i)*Math.cos(a),l=Math.cos(s)*Math.sin(a)-Math.sin(s)*Math.cos(a)*Math.cos(o-i);return Y(Math.atan2(u,l))}function at(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=K(t),o=z(i[0]),s=z(i[1]),a=z(n),u=q(e,r.units),l=Math.asin(Math.sin(s)*Math.cos(u)+Math.cos(s)*Math.sin(u)*Math.cos(a));return I([Y(o+Math.atan2(Math.sin(a)*Math.sin(u)*Math.cos(s),Math.cos(u)-Math.sin(s)*Math.sin(l))),Y(l)],r.properties)}function ut(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e),o=z(i[1]-r[1]),s=z(i[0]-r[0]),a=z(r[1]),u=z(i[1]),l=Math.pow(Math.sin(o/2),2)+Math.pow(Math.sin(s/2),2)*Math.cos(a)*Math.cos(u);return F(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)),n.units)}function lt(t,e){var n;return(n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final?ht(K(e),K(t)):ht(K(t),K(e)))>180?-(360-n):n}function ht(t,e){var n=z(t[1]),r=z(e[1]),i=z(e[0]-t[0]);i>Math.PI&&(i-=2*Math.PI),i<-Math.PI&&(i+=2*Math.PI);var o=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(n/2+Math.PI/4));return(Y(Math.atan2(i,o))+360)%360}function ct(t,e,n){if(null!==t)for(var r,i,o,s,a,u,l,h,c=0,f=0,g=t.type,p="FeatureCollection"===g,v="Feature"===g,d=p?t.features.length:1,y=0;ya||f>u||g>l)return s=o,a=n,u=f,l=g,void(i=0);var p=L([s,o],t.properties);if(!1===e(p,n,r,g,i))return!1;i++,s=o}))&&void 0}}}))}function bt(t,e,n){var r=n,i=!1;return kt(t,(function(t,o,s,a,u){r=!1===i&&void 0===n?t:e(r,t,o,s,a,u),i=!0})),r}function wt(t,e){if(!t)throw new Error("geojson is required");xt(t,(function(t,n,r){if(null!==t.geometry){var i=t.geometry.type,o=t.geometry.coordinates;switch(i){case"LineString":if(!1===e(t,n,r,0,0))return!1;break;case"Polygon":for(var s=0;s0){e+=Math.abs(Ot(t[0]));for(var n=1;n=e?(r+2)%e:r+2],a=i[0]*Tt,u=o[1]*Tt;n+=(s[0]*Tt-a)*Math.sin(u),r++}return n*Ct}function Rt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=t.bbox&&!0!==e.recompute)return t.bbox;var n=[1/0,1/0,-1/0,-1/0];return ct(t,(function(t){n[0]>t[0]&&(n[0]=t[0]),n[1]>t[1]&&(n[1]=t[1]),n[2]e[2]&&(n|=2),t[1]e[3]&&(n|=8),n}function qt(t,e){var n,r=[],i=a(t);try{for(i.s();!(n=i.n()).done;){var o=At(n.value,e);o.length>0&&(o[0][0]===o[o.length-1][0]&&o[0][1]===o[o.length-1][1]||o.push(o[0]),o.length>=4&&r.push(o))}}catch(t){i.e(t)}finally{i.f()}return r}function Vt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Number(t[0]),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]);if(6===t.length)throw new Error("@turf/bbox-polygon does not support BBox with 6 positions");var s=[n,r];return S([[s,[i,r],[i,o],[n,o],s]],e.properties,{bbox:t,id:e.id})}var Gt=function(){return s((function t(e){i(this,t),this.points=e.points||[],this.duration=e.duration||1e4,this.sharpness=e.sharpness||.85,this.centers=[],this.controls=[],this.stepLength=e.stepLength||60,this.length=this.points.length,this.delay=0;for(var n=0;nt&&(e.push(r),n=i)}return e}},{key:"vector",value:function(t){var e=this.pos(t+10),n=this.pos(t-10);return{angle:180*Math.atan2(e.y-n.y,e.x-n.x)/3.14,speed:Math.sqrt((n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y)+(n.z-e.z)*(n.z-e.z))}}},{key:"pos",value:function(t){var e=t-this.delay;e<0&&(e=0),e>this.duration&&(e=this.duration-1);var n=e/this.duration;if(n>=1)return this.points[this.length-1];var r=Math.floor((this.points.length-1)*n);return function(t,e,n,r,i){var o=function(t){var e=t*t,n=e*t;return[n,3*e*(1-t),3*t*(1-t)*(1-t),(1-t)*(1-t)*(1-t)]}(t),s={x:i.x*o[0]+r.x*o[1]+n.x*o[2]+e.x*o[3],y:i.y*o[0]+r.y*o[1]+n.y*o[2]+e.y*o[3],z:i.z*o[0]+r.z*o[1]+n.z*o[2]+e.z*o[3]};return s}((this.length-1)*n-r,this.points[r],this.controls[r][1],this.controls[r+1][0],this.points[r+1])}}])}();function Bt(t){for(var e,n,r=Q(t),i=0,o=1;o0}function Yt(t,e){for(var n=0,r=0,i=0,o=0,s=0,a=0,u=0,l=0,h=null,c=null,f=t[0],g=t[1],p=e.length;n0&&l>0)a=l,s=(h=c)[0]-f;else{if(u=c[0]-t[0],l>0&&a<=0){if((o=s*l-u*a)>0)i+=1;else if(0===o)return 0}else if(a>0&&l<=0){if((o=s*l-u*a)<0)i+=1;else if(0===o)return 0}else if(0===l&&a<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&l<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&0===l){if(u<=0&&s>=0)return 0;if(s<=0&&u>=0)return 0}h=c,a=l,s=u}}return i%2!=0}function zt(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("point is required");if(!e)throw new Error("polygon is required");var r=K(t),i=rt(e),o=i.type,s=e.bbox,a=i.coordinates;if(s&&!1===function(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}(r,s))return!1;"Polygon"===o&&(a=[a]);for(var u=!1,l=0;l2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=Q(e),o=0;oi)return!1}else if(0!==g)return!1;return Math.abs(c)===Math.abs(f)&&0===Math.abs(c)?!r&&(n[0]===t[0]&&n[1]===t[1]):r?"start"===r?Math.abs(c)>=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o0?u<=s&&s=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o<=l:l<=o&&o<=a:f>0?u<=s&&s<=h:h<=s&&s<=u}function Ut(t,e){if("Feature"===t.type&&null===t.geometry)return!1;if("Feature"===e.type&&null===e.geometry)return!1;if(!Zt(Rt(t),Rt(e)))return!1;var n,r=a(rt(e).coordinates);try{for(r.s();!(n=r.n()).done;){var i,o=a(n.value);try{for(o.s();!(i=o.n()).done;){if(!zt(i.value,t))return!1}}catch(t){o.e(t)}finally{o.f()}}}catch(t){r.e(t)}finally{r.f()}return!0}function Zt(t,e){return!(t[0]>e[0])&&(!(t[2]e[1])&&!(t[3]0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Kt;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function Kt(t,e){return te?1:0}function Qt(t,e){return t.p.x>e.p.x?1:t.p.xe.p.y?1:-1:1}function $t(t,e){return t.rightSweepEvent.p.x>e.rightSweepEvent.p.x?1:t.rightSweepEvent.p.x0?(h.isLeftEndpoint=!0,l.isLeftEndpoint=!1):(l.isLeftEndpoint=!0,h.isLeftEndpoint=!1),e.push(l),e.push(h),s=a,re+=1}}ee+=1}var oe=s((function t(e){i(this,t),this.leftSweepEvent=e,this.rightSweepEvent=e.otherEvent}));function se(t,e){if(null===t||null===e)return!1;if(t.leftSweepEvent.ringId===e.leftSweepEvent.ringId&&(t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.rightSweepEvent)||t.leftSweepEvent.isSamePoint(e.leftSweepEvent)||t.leftSweepEvent.isSamePoint(e.rightSweepEvent)))return!1;var n=t.leftSweepEvent.p.x,r=t.leftSweepEvent.p.y,i=t.rightSweepEvent.p.x,o=t.rightSweepEvent.p.y,s=e.leftSweepEvent.p.x,a=e.leftSweepEvent.p.y,u=e.rightSweepEvent.p.x,l=e.rightSweepEvent.p.y,h=(l-a)*(i-n)-(u-s)*(o-r),c=(u-s)*(r-a)-(l-a)*(n-s),f=(i-n)*(r-a)-(o-r)*(n-s);if(0===h)return!1;var g=c/h,p=f/h;return g>=0&&g<=1&&p>=0&&p<=1&&[n+g*(i-n),r+g*(o-r)]}var ae=function(t,e){var n=new Jt([],Qt);return function(t,e){if("FeatureCollection"===t.type)for(var n=t.features,r=0;r2&&void 0!==arguments[2]?arguments[2]:{},r=n.removeDuplicates,i=void 0===r||r,o=n.ignoreSelfIntersections,s=void 0===o||o,a=[];"FeatureCollection"===t.type?a=a.concat(t.features):"Feature"===t.type?a.push(t):"LineString"!==t.type&&"Polygon"!==t.type&&"MultiLineString"!==t.type&&"MultiPolygon"!==t.type||a.push(b(t)),"FeatureCollection"===e.type?a=a.concat(e.features):"Feature"===e.type?a.push(e):"LineString"!==e.type&&"Polygon"!==e.type&&"MultiLineString"!==e.type&&"MultiPolygon"!==e.type||a.push(b(e));var u=ae(C(a),s),l=[];if(i){var h={};u.forEach((function(t){var e=t.join(",");h[e]||(h[e]=!0,l.push(t))}))}else l=u;return C(l.map((function(t){return I(t)})))}function le(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t);switch(e.properties||"Feature"!==t.type||(e.properties=t.properties),n.type){case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{};return he(r,i)}(n,e);case"MultiPolygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{},o=[];return r.forEach((function(t){o.push(he(t,i))})),C(o)}(n,e);default:throw new Error("invalid poly")}}function he(t,e){return t.length>1?T(t,e):L(t[0],e)}function ce(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;switch(i){case"MultiPoint":switch(o){case"LineString":return fe(n,r);case"Polygon":return pe(n,r);default:throw new Error("feature2 "+o+" geometry not supported")}case"LineString":switch(o){case"MultiPoint":return fe(r,n);case"LineString":return function(t,e){if(ue(t,e).features.length>0)for(var n=0;n0}function pe(t,e){for(var n=!1,r=!1,i=t.coordinates.length,o=0;o=Math.abs(a)?s>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:a>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1]:Math.abs(s)>=Math.abs(a)?s>0?t[0]0?t[1]2&&void 0!==arguments[2]?arguments[2]:{ignoreSelfIntersections:!0}).ignoreSelfIntersections,r=void 0===n||n,i=!0;return xt(t,(function(t){xt(e,(function(e){if(!1===i)return!1;i=function(t,e,n){switch(t.type){case"Point":switch(e.type){case"Point":return r=t.coordinates,i=e.coordinates,!(r[0]===i[0]&&r[1]===i[1]);case"LineString":return!ye(e,t);case"Polygon":return!zt(t,e)}break;case"LineString":switch(e.type){case"Point":return!ye(t,e);case"LineString":return!function(t,e,n){var r=ue(t,e,{ignoreSelfIntersections:n});if(r.features.length>0)return!0;return!1}(t,e,n);case"Polygon":return!me(e,t,n)}break;case"Polygon":switch(e.type){case"Point":return!zt(e,t);case"LineString":return!me(t,e,n);case"Polygon":return!function(t,e,n){var r,i=a(t.coordinates[0]);try{for(i.s();!(r=i.n()).done;){if(zt(r.value,e))return!0}}catch(t){i.e(t)}finally{i.f()}var o,s=a(e.coordinates[0]);try{for(s.s();!(o=s.n()).done;){if(zt(o.value,t))return!0}}catch(t){s.e(t)}finally{s.f()}var u=ue(le(t),le(e),{ignoreSelfIntersections:n});if(u.features.length>0)return!0;return!1}(e,t,n)}}var r,i;return!1}(t.geometry,e.geometry,r)}))})),i}function ye(t,e){for(var n=0;n0}function _e(t,e,n){var r=n[0]-t[0],i=n[1]-t[1],o=e[0]-t[0],s=e[1]-t[1];return 0==r*s-i*o&&(Math.abs(o)>=Math.abs(s)?o>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:s>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1])}var xe=Object.defineProperty,Ee=function(t,e){return xe(t,"name",{value:e,configurable:!0})},ke=function(){return s((function t(e){var n,r,o;i(this,t),this.direction=!1,this.compareProperties=!0,this.precision=Math.pow(10,-(null!=(n=null==e?void 0:e.precision)?n:17)),this.direction=null!=(r=null==e?void 0:e.direction)&&r,this.compareProperties=null==(o=null==e?void 0:e.compareProperties)||o}),[{key:"compare",value:function(t,e){var n=this;if(t.type!==e.type)return!1;if(!we(t,e))return!1;switch(t.type){case"Point":return this.compareCoord(t.coordinates,e.coordinates);case"LineString":return this.compareLine(t.coordinates,e.coordinates);case"Polygon":return this.comparePolygon(t,e);case"GeometryCollection":return this.compareGeometryCollection(t,e);case"Feature":return this.compareFeature(t,e);case"FeatureCollection":return this.compareFeatureCollection(t,e);default:if(t.type.startsWith("Multi")){var r=Ie(t),i=Ie(e);return r.every((function(t){return i.some((function(e){return n.compare(t,e)}))}))}}return!1}},{key:"compareCoord",value:function(t,e){var n=this;return t.length===e.length&&t.every((function(t,r){return Math.abs(t-e[r])2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!we(t,e))return!1;var i=t,o=e;if(r&&!this.compareCoord(i[0],o[0])){var s=this.fixStartIndex(o,i);if(!s)return!1;o=s}var a=this.compareCoord(i[n],o[n]);return this.direction||a?this.comparePath(i,o):!!this.compareCoord(i[n],o[o.length-(1+n)])&&this.comparePath(i.slice().reverse(),o)}},{key:"fixStartIndex",value:function(t,e){for(var n,r=-1,i=0;i=0&&(n=[].concat(t.slice(r,t.length),t.slice(1,r+1))),n}},{key:"comparePath",value:function(t,e){var n=this;return t.every((function(t,r){return n.compareCoord(t,e[r])}))}},{key:"comparePolygon",value:function(t,e){var n=this;if(this.compareLine(t.coordinates[0],e.coordinates[0],1,!0)){var r=t.coordinates.slice(1,t.coordinates.length),i=e.coordinates.slice(1,e.coordinates.length);return r.every((function(t){return i.some((function(e){return n.compareLine(t,e,1,!0)}))}))}return!1}},{key:"compareGeometryCollection",value:function(t,e){var n=this;return we(t.geometries,e.geometries)&&this.compareBBox(t,e)&&t.geometries.every((function(t,r){return n.compare(t,e.geometries[r])}))}},{key:"compareFeature",value:function(t,e){return t.id===e.id&&(!this.compareProperties||Se(t.properties,e.properties))&&this.compareBBox(t,e)&&this.compare(t.geometry,e.geometry)}},{key:"compareFeatureCollection",value:function(t,e){var n=this;return we(t.features,e.features)&&this.compareBBox(t,e)&&t.features.every((function(t,r){return n.compare(t,e.features[r])}))}},{key:"compareBBox",value:function(t,e){return Boolean(!t.bbox&&!e.bbox)||!(!t.bbox||!e.bbox)&&this.compareCoord(t.bbox,e.bbox)}}])}();Ee(ke,"GeojsonEquality");var be=ke;function we(t,e){return t.coordinates?t.coordinates.length===e.coordinates.length:t.length===e.length}function Ie(t){return t.coordinates.map((function(e){return{type:t.type.replace("Multi",""),coordinates:e}}))}function Ne(t,e,n){return new be(n).compare(t,e)}function Se(t,e){if(null===t&&null===e)return!0;if(null===t||null===e)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(var i=0,o=n;i1&&void 0!==arguments[1]?arguments[1]:{},n="object"===m(e)?e.mutate:e;if(!t)throw new Error("geojson is required");var r=it(t),i=[];switch(r){case"LineString":i=Pe(t,r);break;case"MultiLineString":case"Polygon":Q(t).forEach((function(t){i.push(Pe(t,r))}));break;case"MultiPolygon":Q(t).forEach((function(t){var e=[];t.forEach((function(t){e.push(Pe(t,r))})),i.push(e)}));break;case"Point":return t;case"MultiPoint":var o={};Q(t).forEach((function(t){var e=t.join("-");Object.prototype.hasOwnProperty.call(o,e)||(i.push(t),o[e]=!0)}));break;default:throw new Error(r+" geometry not supported")}return t.coordinates?!0===n?(t.coordinates=i,t):{type:r,coordinates:i}:!0===n?(t.geometry.coordinates=i,t):b({type:r,coordinates:i},t.properties,{bbox:t.bbox,id:t.id})}function Pe(t,e){var n=Q(t);if(2===n.length&&!Ce(n[0],n[1]))return n;var r=[],i=n.length-1,o=r.length;r.push(n[0]);for(var s=1;s2&&Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1))}if(r.push(n[n.length-1]),o=r.length,("Polygon"===e||"MultiPolygon"===e)&&Ce(n[0],n[n.length-1])&&o<4)throw new Error("invalid polygon");return"LineString"===e&&o<3||Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1),r}function Ce(t,e){return t[0]===e[0]&&t[1]===e[1]}function Te(t,e,n){var r=n[0],i=n[1],o=t[0],s=t[1],a=e[0],u=e[1],l=a-o,h=u-s;return 0===(r-o)*h-(i-s)*l&&(Math.abs(l)>=Math.abs(h)?l>0?o<=r&&r<=a:a<=r&&r<=o:h>0?s<=i&&i<=u:u<=i&&i<=s)}function Oe(t,e){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).ignoreSelfIntersections,r=void 0===n||n,i=!1;return xt(t,(function(t){xt(e,(function(e){if(!0===i)return!0;i=!de(t.geometry,e.geometry,{ignoreSelfIntersections:r})}))})),i}function Re(t,e,n,r,i){Ae(t,e,n||0,r||t.length-1,i||Fe)}function Ae(t,e,n,r,i){for(;r>n;){if(r-n>600){var o=r-n+1,s=e-n+1,a=Math.log(o),u=.5*Math.exp(2*a/3),l=.5*Math.sqrt(a*u*(o-u)/o)*(s-o/2<0?-1:1);Ae(t,e,Math.max(n,Math.floor(e-s*u/o+l)),Math.min(r,Math.floor(e+(o-s)*u/o+l)),i)}var h=t[e],c=n,f=r;for(De(t,n,e),i(t[r],h)>0&&De(t,n,r);c0;)f--}0===i(t[n],h)?De(t,n,f):De(t,++f,r),f<=e&&(n=f+1),e<=f&&(r=f-1)}}function De(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function Fe(t,e){return te?1:0}var qe=function(){return s((function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:9;i(this,t),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}),[{key:"all",value:function(){return this._all(this.data,[])}},{key:"search",value:function(t){var e=this.data,n=[];if(!He(t,e))return n;for(var r=this.toBBox,i=[];e;){for(var o=0;o=0&&i[e].children.length>this._maxEntries;)this._split(i,e),e--;this._adjustParentBBoxes(r,i,e)}},{key:"_split",value:function(t,e){var n=t[e],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=We(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,Ge(n,this.toBBox),Ge(s,this.toBBox),e?t[e-1].children.push(s):this._splitRoot(n,s)}},{key:"_splitRoot",value:function(t,e){this.data=We([t,e]),this.data.height=t.height+1,this.data.leaf=!1,Ge(this.data,this.toBBox)}},{key:"_chooseSplitIndex",value:function(t,e,n){for(var r,i,o,s,a,u,l,h=1/0,c=1/0,f=e;f<=n-e;f++){var g=Be(t,0,f,this.toBBox),p=Be(t,f,n,this.toBBox),v=(i=g,o=p,s=void 0,a=void 0,u=void 0,l=void 0,s=Math.max(i.minX,o.minX),a=Math.max(i.minY,o.minY),u=Math.min(i.maxX,o.maxX),l=Math.min(i.maxY,o.maxY),Math.max(0,u-s)*Math.max(0,l-a)),d=Xe(g)+Xe(p);v=e;h--){var c=t.children[h];Ye(s,t.leaf?i(c):c),a+=Ue(s)}return a}},{key:"_adjustParentBBoxes",value:function(t,e,n){for(var r=n;r>=0;r--)Ye(e[r],t)}},{key:"_condense",value:function(t){for(var e,n=t.length-1;n>=0;n--)0===t[n].children.length?n>0?(e=t[n-1].children).splice(e.indexOf(t[n]),1):this.clear():Ge(t[n],this.toBBox)}}])}();function Ve(t,e,n){if(!n)return e.indexOf(t);for(var r=0;r=t.minX&&e.maxY>=t.minY}function We(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Je(t,e,n,r,i){for(var o=[e,n];o.length;)if(!((n=o.pop())-(e=o.pop())<=r)){var s=e+Math.ceil((n-e)/r/2)*r;Re(t,s,e,n,i),o.push(e,s,s,n)}}var Ke=Object.freeze({__proto__:null,default:qe});function Qe(t){var e=new qe(t);return e.insert=function(t){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.insert.call(this,t)},e.load=function(t){var e=[];return Array.isArray(t)?t.forEach((function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})):vt(t,(function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})),qe.prototype.load.call(this,e)},e.remove=function(t,e){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.remove.call(this,t,e)},e.clear=function(){return qe.prototype.clear.call(this)},e.search=function(t){return C(qe.prototype.search.call(this,this.toBBox(t)))},e.collides=function(t){return qe.prototype.collides.call(this,this.toBBox(t))},e.all=function(){return C(qe.prototype.all.call(this))},e.toJSON=function(){return qe.prototype.toJSON.call(this)},e.fromJSON=function(t){return qe.prototype.fromJSON.call(this,t)},e.toBBox=function(t){var e;if(t.bbox)e=t.bbox;else if(Array.isArray(t)&&4===t.length)e=t;else if(Array.isArray(t)&&6===t.length)e=[t[0],t[1],t[3],t[4]];else if("Feature"===t.type)e=Rt(t);else{if("FeatureCollection"!==t.type)throw new Error("invalid geojson");e=Rt(t)}return{minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}},e}function $e(t){if(!t)throw new Error("geojson is required");var e=[];return xt(t,(function(t){!function(t,e){var n=[],r=t.geometry;if(null!==r){switch(r.type){case"Polygon":n=Q(r);break;case"LineString":n=[Q(r)]}n.forEach((function(n){var r=function(t,e){var n=[];return t.reduce((function(t,r){var i=L([t,r],e);return i.bbox=function(t,e){var n=t[0],r=t[1],i=e[0],o=e[1],s=ni?n:i,l=r>o?r:o;return[s,a,u,l]}(t,r),n.push(i),r})),n}(n,t.properties);r.forEach((function(t){t.id=e.length,e.push(t)}))}))}}(t,e)})),C(e)}var tn,en,nn=Object.defineProperty,rn=Object.defineProperties,on=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertySymbols,an=Object.prototype.hasOwnProperty,un=Object.prototype.propertyIsEnumerable,ln=function(t,e,n){return e in t?nn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},hn=function(t,e){for(var n in e||(e={}))an.call(e,n)&&ln(t,n,e[n]);if(sn){var r,i=a(sn(e));try{for(i.s();!(r=i.n()).done;){n=r.value;un.call(e,n)&&ln(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},cn=function(t,e){return rn(t,on(e))};function fn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t||!e)throw new Error("lines and pt are required arguments");var r=K(e),i=I([1/0,1/0],{dist:1/0,index:-1,multiFeatureIndex:-1,location:-1}),o=0;return xt(t,(function(t,s,a){for(var u=Q(t),l=0;lR||pn(p,f)>R?ut(dn(f),dn(g))<=ut(dn(f),dn(p))?[dn(g),!0,!1]:[dn(p),!1,!0]:[dn(f),!1,!1]}function mn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function _n(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var n=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,r.get?r:{enumerable:!0,get:function(){return t[e]}})})),n}var xn=(en||(en=1,tn=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==m(e)&&"object"==m(n)){if(e.constructor!==n.constructor)return!1;var r,i,o;if(Array.isArray(e)){if((r=e.length)!=n.length)return!1;for(i=r;0!=i--;)if(!t(e[i],n[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((r=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(i=r;0!=i--;)if(!Object.prototype.hasOwnProperty.call(n,o[i]))return!1;for(i=r;0!=i--;){var s=o[i];if(!t(e[s],n[s]))return!1}return!0}return e!=e&&n!=n}),tn),En=mn(xn);function kn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r,i=n.tolerance||0,o=[],s=Qe(),a=$e(t);s.load(a);var u=[];return kt(e,(function(t){var e=!1;t&&(vt(s.search(t),(function(n){if(!1===e){var o=Q(t).sort(),s=Q(n).sort();if(En(o,s))e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(o[0],n)&&jt(o[1],n):fn(n,o[0]).properties.dist<=i&&fn(n,o[1]).properties.dist<=i)e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(s[0],t)&&jt(s[1],t):fn(t,s[0]).properties.dist<=i&&fn(t,s[1]).properties.dist<=i)if(r){var a=bn(r,n);a?r=a:u.push(n)}else r=n}})),!1===e&&r&&(o.push(r),u.length&&(o=o.concat(u),u=[]),r=void 0))})),r&&o.push(r),C(o)}function bn(t,e){var n=Q(e),r=Q(t),i=r[0],o=r[r.length-1],s=t.geometry.coordinates;if(En(n[0],i))s.unshift(n[1]);else if(En(n[0],o))s.push(n[1]);else if(En(n[1],i))s.unshift(n[0]);else{if(!En(n[1],o))return;s.push(n[0])}return t}function wn(t,e){var n=G(lt(t[0],t[1])),r=G(lt(e[0],e[1]));return n===r||(r-n)%180==0}function In(t,e){if(t.geometry&&t.geometry.type)return t.geometry.type;if(t.type)return t.type;throw new Error("Invalid GeoJSON object for "+e)}function Nn(t,e){return!!Sn(e.coordinates[0],t.coordinates)||!!Sn(e.coordinates[e.coordinates.length-1],t.coordinates)}function Sn(t,e){return t[0]===e[0]&&t[1]===e[1]}function Mn(t){return t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]}function Ln(t){for(var e=0;ee[0])&&(!(t[2]e[1])&&!(t[3]1&&void 0!==arguments[1]?arguments[1]:{},n=Rt(t);return I([(n[0]+n[2])/2,(n[1]+n[3])/2],e.properties,e)}var Dn,Fn={exports:{}};var qn=(Dn||(Dn=1,function(t,e){t.exports=function(){function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}var y=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getEndCapStyle",value:function(){return this._endCapStyle}},{key:"isSingleSided",value:function(){return this._isSingleSided}},{key:"setQuadrantSegments",value:function(t){this._quadrantSegments=t,0===this._quadrantSegments&&(this._joinStyle=e.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=e.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),t<=0&&(this._quadrantSegments=1),this._joinStyle!==e.JOIN_ROUND&&(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS)}},{key:"getJoinStyle",value:function(){return this._joinStyle}},{key:"setJoinStyle",value:function(t){this._joinStyle=t}},{key:"setSimplifyFactor",value:function(t){this._simplifyFactor=t<0?0:t}},{key:"getSimplifyFactor",value:function(){return this._simplifyFactor}},{key:"getQuadrantSegments",value:function(){return this._quadrantSegments}},{key:"setEndCapStyle",value:function(t){this._endCapStyle=t}},{key:"getMitreLimit",value:function(){return this._mitreLimit}},{key:"setMitreLimit",value:function(t){this._mitreLimit=t}},{key:"setSingleSided",value:function(t){this._isSingleSided=t}}],[{key:"constructor_",value:function(){if(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=e.CAP_ROUND,this._joinStyle=e.JOIN_ROUND,this._mitreLimit=e.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=e.DEFAULT_SIMPLIFY_FACTOR,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.setQuadrantSegments(t)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.setQuadrantSegments(n),this.setEndCapStyle(r)}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];this.setQuadrantSegments(i),this.setEndCapStyle(o),this.setJoinStyle(s),this.setMitreLimit(a)}}},{key:"bufferDistanceError",value:function(t){var e=Math.PI/2/t;return 1-Math.cos(e/2)}}]),e}();y.CAP_ROUND=1,y.CAP_FLAT=2,y.CAP_SQUARE=3,y.JOIN_ROUND=1,y.JOIN_MITRE=2,y.JOIN_BEVEL=3,y.DEFAULT_QUADRANT_SEGMENTS=8,y.DEFAULT_MITRE_LIMIT=5,y.DEFAULT_SIMPLIFY_FACTOR=.01;var _=function(e){r(o,e);var i=c(o);function o(e){var n;return t(this,o),(n=i.call(this,e)).name=Object.keys({Exception:o})[0],n}return n(o,[{key:"toString",value:function(){return this.message}}]),o}(u(Error)),x=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({IllegalArgumentException:i})[0],r}return i}(_),E=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}();function k(){}function b(){}function w(){}var I,N,S,M,L,P,C,T,O=function(){function e(){t(this,e)}return n(e,null,[{key:"equalsWithTolerance",value:function(t,e,n){return Math.abs(t-e)<=n}}]),e}(),R=function(){function e(n,r){t(this,e),this.low=r||0,this.high=n||0}return n(e,null,[{key:"toBinaryString",value:function(t){var e,n="";for(e=2147483648;e>0;e>>>=1)n+=(t.high&e)===e?"1":"0";for(e=2147483648;e>0;e>>>=1)n+=(t.low&e)===e?"1":"0";return n}}]),e}();function A(){}function D(){}A.NaN=NaN,A.isNaN=function(t){return Number.isNaN(t)},A.isInfinite=function(t){return!Number.isFinite(t)},A.MAX_VALUE=Number.MAX_VALUE,A.POSITIVE_INFINITY=Number.POSITIVE_INFINITY,A.NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,"function"==typeof Float64Array&&"function"==typeof Int32Array?(P=2146435072,C=new Float64Array(1),T=new Int32Array(C.buffer),A.doubleToLongBits=function(t){C[0]=t;var e=0|T[0],n=0|T[1];return(n&P)===P&&0!=(1048575&n)&&0!==e&&(e=0,n=2146959360),new R(n,e)},A.longBitsToDouble=function(t){return T[0]=t.low,T[1]=t.high,C[0]}):(I=1023,N=Math.log2,S=Math.floor,M=Math.pow,L=function(){for(var t=53;t>0;t--){var e=M(2,t)-1;if(S(N(e))+1===t)return e}return 0}(),A.doubleToLongBits=function(t){var e,n,r,i,o,s,a,u,l;if(t<0||1/t===Number.NEGATIVE_INFINITY?(s=1<<31,t=-t):s=0,0===t)return new R(u=s,l=0);if(t===1/0)return new R(u=2146435072|s,l=0);if(t!=t)return new R(u=2146959360,l=0);if(i=0,l=0,(e=S(t))>1)if(e<=L)(i=S(N(e)))<=20?(l=0,u=e<<20-i&1048575):(l=e%(n=M(2,r=i-20))<<32-r,u=e/n&1048575);else for(r=e,l=0;0!==(r=S(n=r/2));)i++,l>>>=1,l|=(1&u)<<31,u>>>=1,n!==r&&(u|=524288);if(a=i+I,o=0===e,e=t-e,i<52&&0!==e)for(r=0;;){if((n=2*e)>=1?(e=n-1,o?(a--,o=!1):(r<<=1,r|=1,i++)):(e=n,o?0==--a&&(i++,o=!1):(r<<=1,i++)),20===i)u|=r,r=0;else if(52===i){l|=r;break}if(1===n){i<20?u|=r<<20-i:i<52&&(l|=r<<52-i);break}}return u|=a<<20,new R(u|=s,l)},A.longBitsToDouble=function(t){var e,n,r,i,o=t.high,s=t.low,a=o&1<<31?-1:1;for(r=((2146435072&o)>>20)-I,i=0,n=1<<19,e=1;e<=20;e++)o&n&&(i+=M(2,-e)),n>>>=1;for(n=1<<31,e=21;e<=52;e++)s&n&&(i+=M(2,-e)),n>>>=1;if(-1023===r){if(0===i)return 0*a;r=-1022}else{if(1024===r)return 0===i?a/0:NaN;i+=1}return a*i*M(2,r)});var F=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({RuntimeException:i})[0],r}return i}(_),q=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){if(0===arguments.length)F.constructor_.call(this);else if(1===arguments.length){var t=arguments[0];F.constructor_.call(this,t)}}}]),o}(F),V=function(){function e(){t(this,e)}return n(e,null,[{key:"shouldNeverReachHere",value:function(){if(0===arguments.length)e.shouldNeverReachHere(null);else if(1===arguments.length){var t=arguments[0];throw new q("Should never reach here"+(null!==t?": "+t:""))}}},{key:"isTrue",value:function(){if(1===arguments.length){var t=arguments[0];e.isTrue(t,null)}else if(2===arguments.length){var n=arguments[1];if(!arguments[0])throw null===n?new q:new q(n)}}},{key:"equals",value:function(){if(2===arguments.length){var t=arguments[0],n=arguments[1];e.equals(t,n,null)}else if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2];if(!i.equals(r))throw new q("Expected "+r+" but encountered "+i+(null!==o?": "+o:""))}}}]),e}(),G=new ArrayBuffer(8),B=new Float64Array(G),Y=new Int32Array(G),z=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getM",value:function(){return A.NaN}},{key:"setOrdinate",value:function(t,n){switch(t){case e.X:this.x=n;break;case e.Y:this.y=n;break;case e.Z:this.setZ(n);break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"equals2D",value:function(){if(1===arguments.length){var t=arguments[0];return this.x===t.x&&this.y===t.y}if(2===arguments.length){var e=arguments[0],n=arguments[1];return!!O.equalsWithTolerance(this.x,e.x,n)&&!!O.equalsWithTolerance(this.y,e.y,n)}}},{key:"setM",value:function(t){throw new x("Invalid ordinate index: "+e.M)}},{key:"getZ",value:function(){return this.z}},{key:"getOrdinate",value:function(t){switch(t){case e.X:return this.x;case e.Y:return this.y;case e.Z:return this.getZ()}throw new x("Invalid ordinate index: "+t)}},{key:"equals3D",value:function(t){return this.x===t.x&&this.y===t.y&&(this.getZ()===t.getZ()||A.isNaN(this.getZ())&&A.isNaN(t.getZ()))}},{key:"equals",value:function(t){return t instanceof e&&this.equals2D(t)}},{key:"equalInZ",value:function(t,e){return O.equalsWithTolerance(this.getZ(),t.getZ(),e)}},{key:"setX",value:function(t){this.x=t}},{key:"compareTo",value:function(t){var e=t;return this.xe.x?1:this.ye.y?1:0}},{key:"getX",value:function(){return this.x}},{key:"setZ",value:function(t){this.z=t}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return V.shouldNeverReachHere("this shouldn't happen because this class is Cloneable"),null;throw t}}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+")"}},{key:"distance3D",value:function(t){var e=this.x-t.x,n=this.y-t.y,r=this.getZ()-t.getZ();return Math.sqrt(e*e+n*n+r*r)}},{key:"getY",value:function(){return this.y}},{key:"setY",value:function(t){this.y=t}},{key:"distance",value:function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*t+e.hashCode(this.x))+e.hashCode(this.y)}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}},{key:"interfaces_",get:function(){return[k,b,w]}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.z=null,0===arguments.length)e.constructor_.call(this,0,0);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.x,t.y,t.getZ())}else if(2===arguments.length){var n=arguments[0],r=arguments[1];e.constructor_.call(this,n,r,e.NULL_ORDINATE)}else if(3===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2];this.x=i,this.y=o,this.z=s}}},{key:"hashCode",value:function(t){return B[0]=t,Y[0]^Y[1]}}]),e}(),j=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compare",value:function(t,n){var r=e.compare(t.x,n.x);if(0!==r)return r;var i=e.compare(t.y,n.y);return 0!==i?i:this._dimensionsToTest<=2?0:e.compare(t.getZ(),n.getZ())}},{key:"interfaces_",get:function(){return[D]}}],[{key:"constructor_",value:function(){if(this._dimensionsToTest=2,0===arguments.length)e.constructor_.call(this,2);else if(1===arguments.length){var t=arguments[0];if(2!==t&&3!==t)throw new x("only 2 or 3 dimensions may be specified");this._dimensionsToTest=t}}},{key:"compare",value:function(t,e){return te?1:A.isNaN(t)?A.isNaN(e)?0:-1:A.isNaN(e)?1:0}}]),e}();z.DimensionalComparator=j,z.NULL_ORDINATE=A.NaN,z.X=0,z.Y=1,z.Z=2,z.M=3;var X=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getArea",value:function(){return this.getWidth()*this.getHeight()}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.isNull()?n.isNull():this._maxx===n.getMaxX()&&this._maxy===n.getMaxY()&&this._minx===n.getMinX()&&this._miny===n.getMinY()}},{key:"intersection",value:function(t){if(this.isNull()||t.isNull()||!this.intersects(t))return new e;var n=this._minx>t._minx?this._minx:t._minx,r=this._miny>t._miny?this._miny:t._miny;return new e(n,this._maxx=this._minx&&n.getMaxX()<=this._maxx&&n.getMinY()>=this._miny&&n.getMaxY()<=this._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return!this.isNull()&&r>=this._minx&&r<=this._maxx&&i>=this._miny&&i<=this._maxy}}},{key:"intersects",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return!this.isNull()&&!t.isNull()&&!(t._minx>this._maxx||t._maxxthis._maxy||t._maxythis._maxx||(r.x>i.x?r.x:i.x)this._maxy||(r.y>i.y?r.y:i.y)this._maxx||othis._maxy||sthis._maxx&&(this._maxx=n._maxx),n._minythis._maxy&&(this._maxy=n._maxy))}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.isNull()?(this._minx=r,this._maxx=r,this._miny=i,this._maxy=i):(rthis._maxx&&(this._maxx=r),ithis._maxy&&(this._maxy=i))}}},{key:"minExtent",value:function(){if(this.isNull())return 0;var t=this.getWidth(),e=this.getHeight();return te._minx?1:this._minye._miny?1:this._maxxe._maxx?1:this._maxye._maxy?1:0}},{key:"translate",value:function(t,e){if(this.isNull())return null;this.init(this.getMinX()+t,this.getMaxX()+t,this.getMinY()+e,this.getMaxY()+e)}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"Env["+this._minx+" : "+this._maxx+", "+this._miny+" : "+this._maxy+"]"}},{key:"setToNull",value:function(){this._minx=0,this._maxx=-1,this._miny=0,this._maxy=-1}},{key:"disjoint",value:function(t){return!(!this.isNull()&&!t.isNull())||t._minx>this._maxx||t._maxxthis._maxy||t._maxye?t:e}},{key:"expandBy",value:function(){if(1===arguments.length){var t=arguments[0];this.expandBy(t,t)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];if(this.isNull())return null;this._minx-=e,this._maxx+=e,this._miny-=n,this._maxy+=n,(this._minx>this._maxx||this._miny>this._maxy)&&this.setToNull()}}},{key:"contains",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.covers(t)}if(arguments[0]instanceof z){var n=arguments[0];return this.covers(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return this.covers(r,i)}}},{key:"centre",value:function(){return this.isNull()?null:new z((this.getMinX()+this.getMaxX())/2,(this.getMinY()+this.getMaxY())/2)}},{key:"init",value:function(){if(0===arguments.length)this.setToNull();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this._minx=n._minx,this._maxx=n._maxx,this._miny=n._miny,this._maxy=n._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];ot._maxx&&(e=this._minx-t._maxx);var n=0;return this._maxyt._maxy&&(n=this._miny-t._maxy),0===e?n:0===n?e:Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*(t=37*(t=37*t+z.hashCode(this._minx))+z.hashCode(this._maxx))+z.hashCode(this._miny))+z.hashCode(this._maxy)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,0===arguments.length)this.init();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];this.init(o,s,a,u)}}},{key:"intersects",value:function(){if(3===arguments.length){var t=arguments[0],e=arguments[1],n=arguments[2];return n.x>=(t.xe.x?t.x:e.x)&&n.y>=(t.ye.y?t.y:e.y)}if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=arguments[3],a=Math.min(o.x,s.x),u=Math.max(o.x,s.x),l=Math.min(r.x,i.x),h=Math.max(r.x,i.x);return!(l>u||hu||h=this.size())throw new nt;return this.array[t]}},{key:"push",value:function(t){return this.array.push(t),t}},{key:"pop",value:function(){if(0===this.array.length)throw new et;return this.array.pop()}},{key:"peek",value:function(){if(0===this.array.length)throw new et;return this.array[this.array.length-1]}},{key:"empty",value:function(){return 0===this.array.length}},{key:"isEmpty",value:function(){return this.empty()}},{key:"search",value:function(t){return this.array.indexOf(t)}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}}]),o}(rt);function ot(t,e){return t.interfaces_&&t.interfaces_.indexOf(e)>-1}var st=function(){function e(n){t(this,e),this.str=n}return n(e,[{key:"append",value:function(t){this.str+=t}},{key:"setCharAt",value:function(t,e){this.str=this.str.substr(0,t)+e+this.str.substr(t+1)}},{key:"toString",value:function(){return this.str}}]),e}(),at=function(){function e(n){t(this,e),this.value=n}return n(e,[{key:"intValue",value:function(){return this.value}},{key:"compareTo",value:function(t){return this.valuet?1:0}}],[{key:"compare",value:function(t,e){return te?1:0}},{key:"isNan",value:function(t){return Number.isNaN(t)}},{key:"valueOf",value:function(t){return new e(t)}}]),e}(),ut=function(){function e(){t(this,e)}return n(e,null,[{key:"isWhitespace",value:function(t){return t<=32&&t>=0||127===t}},{key:"toUpperCase",value:function(t){return t.toUpperCase()}}]),e}(),lt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"le",value:function(t){return this._hi9?(c=!0,f="9"):f="0"+h,a.append(f),r=r.subtract(e.valueOf(h)).multiply(e.TEN),c&&r.selfAdd(e.TEN);var g=!0,p=e.magnitude(r._hi);if(p<0&&Math.abs(p)>=u-l&&(g=!1),!g)break}return n[0]=i,a.toString()}},{key:"sqr",value:function(){return this.multiply(this)}},{key:"doubleValue",value:function(){return this._hi+this._lo}},{key:"subtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.add(t.negate())}if("number"==typeof arguments[0]){var n=arguments[0];return this.add(-n)}}},{key:"equals",value:function(){if(1===arguments.length&&arguments[0]instanceof e){var t=arguments[0];return this._hi===t._hi&&this._lo===t._lo}}},{key:"isZero",value:function(){return 0===this._hi&&0===this._lo}},{key:"selfSubtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.isNaN()?this:this.selfAdd(-t._hi,-t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.isNaN()?this:this.selfAdd(-n,0)}}},{key:"getSpecialNumberString",value:function(){return this.isZero()?"0.0":this.isNaN()?"NaN ":null}},{key:"min",value:function(t){return this.le(t)?this:t}},{key:"selfDivide",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfDivide(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfDivide(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null,c=null,f=null;return l=this._hi/r,f=(o=(h=e.SPLIT*l)-(o=h-l))*(a=(f=e.SPLIT*r)-(a=f-r))-(c=l*r)+o*(u=r-a)+(s=l-o)*a+s*u,f=l+(h=(this._hi-c-f+this._lo-l*i)/r),this._hi=f,this._lo=l-f+h,this}}},{key:"dump",value:function(){return"DD<"+this._hi+", "+this._lo+">"}},{key:"divide",value:function(){if(arguments[0]instanceof e){var t=arguments[0],n=null,r=null,i=null,o=null,s=null,a=null,u=null,l=null;return r=(s=this._hi/t._hi)-(n=(a=e.SPLIT*s)-(n=a-s)),l=n*(i=(l=e.SPLIT*t._hi)-(i=l-t._hi))-(u=s*t._hi)+n*(o=t._hi-i)+r*i+r*o,new e(l=s+(a=(this._hi-u-l+this._lo-s*t._lo)/t._hi),s-l+a)}if("number"==typeof arguments[0]){var h=arguments[0];return A.isNaN(h)?e.createNaN():e.copy(this).selfDivide(h,0)}}},{key:"ge",value:function(t){return this._hi>t._hi||this._hi===t._hi&&this._lo>=t._lo}},{key:"pow",value:function(t){if(0===t)return e.valueOf(1);var n=new e(this),r=e.valueOf(1),i=Math.abs(t);if(i>1)for(;i>0;)i%2==1&&r.selfMultiply(n),(i/=2)>0&&(n=n.sqr());else r=n;return t<0?r.reciprocal():r}},{key:"ceil",value:function(){if(this.isNaN())return e.NaN;var t=Math.ceil(this._hi),n=0;return t===this._hi&&(n=Math.ceil(this._lo)),new e(t,n)}},{key:"compareTo",value:function(t){var e=t;return this._hie._hi?1:this._loe._lo?1:0}},{key:"rint",value:function(){return this.isNaN()?this:this.add(.5).floor()}},{key:"setValue",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.init(t),this}if("number"==typeof arguments[0]){var n=arguments[0];return this.init(n),this}}},{key:"max",value:function(t){return this.ge(t)?this:t}},{key:"sqrt",value:function(){if(this.isZero())return e.valueOf(0);if(this.isNegative())return e.NaN;var t=1/Math.sqrt(this._hi),n=this._hi*t,r=e.valueOf(n),i=this.subtract(r.sqr())._hi*(.5*t);return r.add(i)}},{key:"selfAdd",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfAdd(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0],r=null,i=null,o=null,s=null,a=null,u=null;return s=(o=this._hi+n)-(a=o-this._hi),i=(u=(s=n-a+(this._hi-s))+this._lo)+(o-(r=o+u)),this._hi=r+i,this._lo=i+(r-this._hi),this}}else if(2===arguments.length){var l=arguments[0],h=arguments[1],c=null,f=null,g=null,p=null,v=null,d=null,y=null;p=this._hi+l,f=this._lo+h,v=p-(d=p-this._hi),g=f-(y=f-this._lo);var m=(c=p+(d=(v=l-d+(this._hi-v))+f))+(d=(g=h-y+(this._lo-g))+(d+(p-c))),_=d+(c-m);return this._hi=m,this._lo=_,this}}},{key:"selfMultiply",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfMultiply(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfMultiply(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null;o=(l=e.SPLIT*this._hi)-this._hi,h=e.SPLIT*r,o=l-o,s=this._hi-o,a=h-r;var c=(l=this._hi*r)+(h=o*(a=h-a)-l+o*(u=r-a)+s*a+s*u+(this._hi*i+this._lo*r)),f=h+(o=l-c);return this._hi=c,this._lo=f,this}}},{key:"selfSqr",value:function(){return this.selfMultiply(this)}},{key:"floor",value:function(){if(this.isNaN())return e.NaN;var t=Math.floor(this._hi),n=0;return t===this._hi&&(n=Math.floor(this._lo)),new e(t,n)}},{key:"negate",value:function(){return this.isNaN()?this:new e(-this._hi,-this._lo)}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return null;throw t}}},{key:"multiply",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return t.isNaN()?e.createNaN():e.copy(this).selfMultiply(t)}if("number"==typeof arguments[0]){var n=arguments[0];return A.isNaN(n)?e.createNaN():e.copy(this).selfMultiply(n,0)}}},{key:"isNaN",value:function(){return A.isNaN(this._hi)}},{key:"intValue",value:function(){return Math.trunc(this._hi)}},{key:"toString",value:function(){var t=e.magnitude(this._hi);return t>=-3&&t<=20?this.toStandardNotation():this.toSciNotation()}},{key:"toStandardNotation",value:function(){var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!0,n),i=n[0]+1,o=r;if("."===r.charAt(0))o="0"+r;else if(i<0)o="0."+e.stringOfChar("0",-i)+r;else if(-1===r.indexOf(".")){var s=i-r.length;o=r+e.stringOfChar("0",s)+".0"}return this.isNegative()?"-"+o:o}},{key:"reciprocal",value:function(){var t,n,r,i,o=null,s=null,a=null,u=null;t=(r=1/this._hi)-(o=(a=e.SPLIT*r)-(o=a-r)),s=(u=e.SPLIT*this._hi)-this._hi;var l=r+(a=(1-(i=r*this._hi)-(u=o*(s=u-s)-i+o*(n=this._hi-s)+t*s+t*n)-r*this._lo)/this._hi);return new e(l,r-l+a)}},{key:"toSciNotation",value:function(){if(this.isZero())return e.SCI_NOT_ZERO;var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!1,n),i=e.SCI_NOT_EXPONENT_CHAR+n[0];if("0"===r.charAt(0))throw new IllegalStateException("Found leading zero: "+r);var o="";r.length>1&&(o=r.substring(1));var s=r.charAt(0)+"."+o;return this.isNegative()?"-"+s+i:s+i}},{key:"abs",value:function(){return this.isNaN()?e.NaN:this.isNegative()?this.negate():new e(this)}},{key:"isPositive",value:function(){return this._hi>0||0===this._hi&&this._lo>0}},{key:"lt",value:function(t){return this._hit._hi||this._hi===t._hi&&this._lo>t._lo}},{key:"isNegative",value:function(){return this._hi<0||0===this._hi&&this._lo<0}},{key:"trunc",value:function(){return this.isNaN()?e.NaN:this.isPositive()?this.floor():this.ceil()}},{key:"signum",value:function(){return this._hi>0?1:this._hi<0?-1:this._lo>0?1:this._lo<0?-1:0}},{key:"interfaces_",get:function(){return[w,k,b]}}],[{key:"constructor_",value:function(){if(this._hi=0,this._lo=0,0===arguments.length)this.init(0);else if(1===arguments.length){if("number"==typeof arguments[0]){var t=arguments[0];this.init(t)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}else if("string"==typeof arguments[0]){var r=arguments[0];e.constructor_.call(this,e.parse(r))}}else if(2===arguments.length){var i=arguments[0],o=arguments[1];this.init(i,o)}}},{key:"determinant",value:function(){if("number"==typeof arguments[3]&&"number"==typeof arguments[2]&&"number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1],r=arguments[2],i=arguments[3];return e.determinant(e.valueOf(t),e.valueOf(n),e.valueOf(r),e.valueOf(i))}if(arguments[3]instanceof e&&arguments[2]instanceof e&&arguments[0]instanceof e&&arguments[1]instanceof e){var o=arguments[1],s=arguments[2],a=arguments[3];return arguments[0].multiply(a).selfSubtract(o.multiply(s))}}},{key:"sqr",value:function(t){return e.valueOf(t).selfMultiply(t)}},{key:"valueOf",value:function(){if("string"==typeof arguments[0]){var t=arguments[0];return e.parse(t)}if("number"==typeof arguments[0])return new e(arguments[0])}},{key:"sqrt",value:function(t){return e.valueOf(t).sqrt()}},{key:"parse",value:function(t){for(var n=0,r=t.length;ut.isWhitespace(t.charAt(n));)n++;var i=!1;if(n=r);){var c=t.charAt(n);if(n++,ut.isDigit(c)){var f=c-"0";s.selfMultiply(e.TEN),s.selfAdd(f),a++}else{if("."!==c){if("e"===c||"E"===c){var g=t.substring(n);try{l=at.parseInt(g)}catch(e){throw e instanceof NumberFormatException?new NumberFormatException("Invalid exponent "+g+" in string "+t):e}break}throw new NumberFormatException("Unexpected character '"+c+"' at position "+n+" in string "+t)}u=a,h=!0}}var p=s;h||(u=a);var v=a-u-l;if(0===v)p=s;else if(v>0){var d=e.TEN.pow(v);p=s.divide(d)}else if(v<0){var y=e.TEN.pow(-v);p=s.multiply(y)}return i?p.negate():p}},{key:"createNaN",value:function(){return new e(A.NaN,A.NaN)}},{key:"copy",value:function(t){return new e(t)}},{key:"magnitude",value:function(t){var e=Math.abs(t),n=Math.log(e)/Math.log(10),r=Math.trunc(Math.floor(n));return 10*Math.pow(10,r)<=e&&(r+=1),r}},{key:"stringOfChar",value:function(t,e){for(var n=new st,r=0;r0){if(s<=0)return e.signum(a);i=o+s}else{if(!(o<0))return e.signum(a);if(s>=0)return e.signum(a);i=-o-s}var u=e.DP_SAFE_EPSILON*i;return a>=u||-a>=u?e.signum(a):2}},{key:"signum",value:function(t){return t>0?1:t<0?-1:0}}]),e}();ht.DP_SAFE_EPSILON=1e-15;var ct=function(){function e(){t(this,e)}return n(e,[{key:"getM",value:function(t){if(this.hasM()){var e=this.getDimension()-this.getMeasures();return this.getOrdinate(t,e)}return A.NaN}},{key:"setOrdinate",value:function(t,e,n){}},{key:"getZ",value:function(t){return this.hasZ()?this.getOrdinate(t,2):A.NaN}},{key:"size",value:function(){}},{key:"getOrdinate",value:function(t,e){}},{key:"getCoordinate",value:function(){}},{key:"getCoordinateCopy",value:function(t){}},{key:"createCoordinate",value:function(){}},{key:"getDimension",value:function(){}},{key:"hasM",value:function(){return this.getMeasures()>0}},{key:"getX",value:function(t){}},{key:"hasZ",value:function(){return this.getDimension()-this.getMeasures()>2}},{key:"getMeasures",value:function(){return 0}},{key:"expandEnvelope",value:function(t){}},{key:"copy",value:function(){}},{key:"getY",value:function(t){}},{key:"toCoordinateArray",value:function(){}},{key:"interfaces_",get:function(){return[b]}}]),e}();ct.X=0,ct.Y=1,ct.Z=2,ct.M=3;var ft=function(){function e(){t(this,e)}return n(e,null,[{key:"index",value:function(t,e,n){return ht.orientationIndex(t,e,n)}},{key:"isCCW",value:function(){if(arguments[0]instanceof Array){var t=arguments[0],n=t.length-1;if(n<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var r=t[0],i=0,o=1;o<=n;o++){var s=t[o];s.y>r.y&&(r=s,i=o)}var a=i;do{(a-=1)<0&&(a=n)}while(t[a].equals2D(r)&&a!==i);var u=i;do{u=(u+1)%n}while(t[u].equals2D(r)&&u!==i);var l=t[a],h=t[u];if(l.equals2D(r)||h.equals2D(r)||l.equals2D(h))return!1;var c=e.index(l,r,h);return 0===c?l.x>h.x:c>0}if(ot(arguments[0],ct)){var f=arguments[0],g=f.size()-1;if(g<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var p=f.getCoordinate(0),v=0,d=1;d<=g;d++){var y=f.getCoordinate(d);y.y>p.y&&(p=y,v=d)}var m=null,_=v;do{(_-=1)<0&&(_=g),m=f.getCoordinate(_)}while(m.equals2D(p)&&_!==v);var E=null,k=v;do{k=(k+1)%g,E=f.getCoordinate(k)}while(E.equals2D(p)&&k!==v);if(m.equals2D(p)||E.equals2D(p)||m.equals2D(E))return!1;var b=e.index(m,p,E);return 0===b?m.x>E.x:b>0}}}]),e}();ft.CLOCKWISE=-1,ft.RIGHT=ft.CLOCKWISE,ft.COUNTERCLOCKWISE=1,ft.LEFT=ft.COUNTERCLOCKWISE,ft.COLLINEAR=0,ft.STRAIGHT=ft.COLLINEAR;var gt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this._minCoord}},{key:"getRightmostSide",value:function(t,e){var n=this.getRightmostSideOfSegment(t,e);return n<0&&(n=this.getRightmostSideOfSegment(t,e-1)),n<0&&(this._minCoord=null,this.checkForRightmostCoordinate(t)),n}},{key:"findRightmostEdgeAtVertex",value:function(){var t=this._minDe.getEdge().getCoordinates();V.isTrue(this._minIndex>0&&this._minIndexthis._minCoord.y&&n.y>this._minCoord.y&&r===ft.CLOCKWISE)&&(i=!0),i&&(this._minIndex=this._minIndex-1)}},{key:"getRightmostSideOfSegment",value:function(t,e){var n=t.getEdge().getCoordinates();if(e<0||e+1>=n.length)return-1;if(n[e].y===n[e+1].y)return-1;var r=tt.LEFT;return n[e].ythis._minCoord.x)&&(this._minDe=t,this._minIndex=n,this._minCoord=e[n])}},{key:"findRightmostEdgeAtNode",value:function(){var t=this._minDe.getNode().getEdges();this._minDe=t.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)}},{key:"findEdge",value:function(t){for(var e=t.iterator();e.hasNext();){var n=e.next();n.isForward()&&this.checkForRightmostCoordinate(n)}V.isTrue(0!==this._minIndex||this._minCoord.equals(this._minDe.getCoordinate()),"inconsistency in rightmost processing"),0===this._minIndex?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe,this.getRightmostSide(this._minDe,this._minIndex)===tt.LEFT&&(this._orientedDe=this._minDe.getSym())}}],[{key:"constructor_",value:function(){this._minIndex=-1,this._minCoord=null,this._minDe=null,this._orientedDe=null}}]),e}(),pt=function(e){r(o,e);var i=c(o);function o(e,n){var r;return t(this,o),(r=i.call(this,n?e+" [ "+n+" ]":e)).pt=n?new z(n):void 0,r.name=Object.keys({TopologyException:o})[0],r}return n(o,[{key:"getCoordinate",value:function(){return this.pt}}]),o}(F),vt=function(){function e(){t(this,e),this.array=[]}return n(e,[{key:"addLast",value:function(t){this.array.push(t)}},{key:"removeFirst",value:function(){return this.array.shift()}},{key:"isEmpty",value:function(){return 0===this.array.length}}]),e}(),dt=function(e,i){r(s,e);var o=c(s);function s(e){var n;return t(this,s),(n=o.call(this)).array=[],e instanceof H&&n.addAll(e),n}return n(s,[{key:"interfaces_",get:function(){return[rt,H]}},{key:"ensureCapacity",value:function(){}},{key:"add",value:function(t){return 1===arguments.length?this.array.push(t):this.array.splice(arguments[0],0,arguments[1]),!0}},{key:"clear",value:function(){this.array=[]}},{key:"addAll",value:function(t){var e,n=d(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.array.push(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"set",value:function(t,e){var n=this.array[t];return this.array[t]=e,n}},{key:"iterator",value:function(){return new yt(this)}},{key:"get",value:function(t){if(t<0||t>=this.size())throw new nt;return this.array[t]}},{key:"isEmpty",value:function(){return 0===this.array.length}},{key:"sort",value:function(t){t?this.array.sort((function(e,n){return t.compare(e,n)})):this.array.sort()}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}},{key:"remove",value:function(t){for(var e=0,n=this.array.length;e=1&&e.getDepth(tt.LEFT)<=0&&!e.isInteriorAreaEdge()&&e.setInResult(!0)}}},{key:"computeDepths",value:function(t){var e=new Q,n=new vt,r=t.getNode();for(n.addLast(r),e.add(r),t.setVisited(!0);!n.isEmpty();){var i=n.removeFirst();e.add(i),this.computeNodeDepth(i);for(var o=i.getEdges().iterator();o.hasNext();){var s=o.next().getSym();if(!s.isVisited()){var a=s.getNode();e.contains(a)||(n.addLast(a),e.add(a))}}}}},{key:"compareTo",value:function(t){var e=t;return this._rightMostCoord.xe._rightMostCoord.x?1:0}},{key:"getEnvelope",value:function(){if(null===this._env){for(var t=new X,e=this._dirEdgeList.iterator();e.hasNext();)for(var n=e.next().getEdge().getCoordinates(),r=0;re.x?t.x:e.x,a=t.y>e.y?t.y:e.y,u=n.xr.x?n.x:r.x,c=n.y>r.y?n.y:r.y,f=((i>u?i:u)+(sl?o:l)+(an?n:t}if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var r=arguments[0],i=arguments[1],o=arguments[2];return ro?o:r}}},{key:"wrap",value:function(t,e){return t<0?e- -t%e:t%e}},{key:"max",value:function(){if(3===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[0];return t>n&&(n=t),e>n&&(n=e),n}if(4===arguments.length){var r=arguments[1],i=arguments[2],o=arguments[3],s=arguments[0];return r>s&&(s=r),i>s&&(s=i),o>s&&(s=o),s}}},{key:"average",value:function(t,e){return(t+e)/2}}]),e}();Et.LOG_10=Math.log(10);var kt=function(){function e(){t(this,e)}return n(e,null,[{key:"segmentToSegment",value:function(t,n,r,i){if(t.equals(n))return e.pointToSegment(t,r,i);if(r.equals(i))return e.pointToSegment(i,t,n);var o=!1;if(X.intersects(t,n,r,i)){var s=(n.x-t.x)*(i.y-r.y)-(n.y-t.y)*(i.x-r.x);if(0===s)o=!0;else{var a=(t.y-r.y)*(i.x-r.x)-(t.x-r.x)*(i.y-r.y),u=((t.y-r.y)*(n.x-t.x)-(t.x-r.x)*(n.y-t.y))/s,l=a/s;(l<0||l>1||u<0||u>1)&&(o=!0)}}else o=!0;return o?Et.min(e.pointToSegment(t,r,i),e.pointToSegment(n,r,i),e.pointToSegment(r,t,n),e.pointToSegment(i,t,n)):0}},{key:"pointToSegment",value:function(t,e,n){if(e.x===n.x&&e.y===n.y)return t.distance(e);var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/r;if(i<=0)return t.distance(e);if(i>=1)return t.distance(n);var o=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(o)*Math.sqrt(r)}},{key:"pointToLinePerpendicular",value:function(t,e,n){var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(i)*Math.sqrt(r)}},{key:"pointToSegmentString",value:function(t,n){if(0===n.length)throw new x("Line array must contain at least one vertex");for(var r=t.distance(n[0]),i=0;i0)&&(o=a,i=s)}return i}}},{key:"extend",value:function(t,n,r){var i=t.create(r,n.getDimension()),o=n.size();if(e.copy(n,0,i,0,o),o>0)for(var s=o;s0)&&(e=r)}return e}}]),e}(),Mt=function(){function e(){t(this,e)}return n(e,null,[{key:"toDimensionSymbol",value:function(t){switch(t){case e.FALSE:return e.SYM_FALSE;case e.TRUE:return e.SYM_TRUE;case e.DONTCARE:return e.SYM_DONTCARE;case e.P:return e.SYM_P;case e.L:return e.SYM_L;case e.A:return e.SYM_A}throw new x("Unknown dimension value: "+t)}},{key:"toDimensionValue",value:function(t){switch(ut.toUpperCase(t)){case e.SYM_FALSE:return e.FALSE;case e.SYM_TRUE:return e.TRUE;case e.SYM_DONTCARE:return e.DONTCARE;case e.SYM_P:return e.P;case e.SYM_L:return e.L;case e.SYM_A:return e.A}throw new x("Unknown dimension symbol: "+t)}}]),e}();Mt.P=0,Mt.L=1,Mt.A=2,Mt.FALSE=-1,Mt.TRUE=-2,Mt.DONTCARE=-3,Mt.SYM_FALSE="F",Mt.SYM_TRUE="T",Mt.SYM_DONTCARE="*",Mt.SYM_P="0",Mt.SYM_L="1",Mt.SYM_A="2";var Lt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}(),Pt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t,e){}},{key:"isDone",value:function(){}},{key:"isGeometryChanged",value:function(){}}]),e}(),Ct=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"computeEnvelopeInternal",value:function(){return this.isEmpty()?new X:this._points.expandEnvelope(new X)}},{key:"isRing",value:function(){return this.isClosed()&&this.isSimple()}},{key:"getCoordinates",value:function(){return this._points.toCoordinateArray()}},{key:"copyInternal",value:function(){return new s(this._points.copy(),this._factory)}},{key:"equalsExact",value:function(){if(2===arguments.length&&"number"==typeof arguments[1]&&arguments[0]instanceof U){var t=arguments[0],e=arguments[1];if(!this.isEquivalentClass(t))return!1;var n=t;if(this._points.size()!==n._points.size())return!1;for(var r=0;r0){var n=this._points.copy();St.reverse(n),this._points=n}return null}}}},{key:"getCoordinate",value:function(){return this.isEmpty()?null:this._points.getCoordinate(0)}},{key:"getBoundaryDimension",value:function(){return this.isClosed()?Mt.FALSE:0}},{key:"isClosed",value:function(){return!this.isEmpty()&&this.getCoordinateN(0).equals2D(this.getCoordinateN(this.getNumPoints()-1))}},{key:"reverseInternal",value:function(){var t=this._points.copy();return St.reverse(t),this.getFactory().createLineString(t)}},{key:"getEndPoint",value:function(){return this.isEmpty()?null:this.getPointN(this.getNumPoints()-1)}},{key:"getTypeCode",value:function(){return U.TYPECODE_LINESTRING}},{key:"getDimension",value:function(){return 1}},{key:"getLength",value:function(){return It.ofLine(this._points)}},{key:"getNumPoints",value:function(){return this._points.size()}},{key:"compareToSameClass",value:function(){if(1===arguments.length){for(var t=arguments[0],e=0,n=0;e= 2)");this._points=t}},{key:"isCoordinate",value:function(t){for(var e=0;e=1&&this.getCoordinateSequence().size()= 4)")}},{key:"getGeometryType",value:function(){return U.TYPENAME_LINEARRING}}],[{key:"constructor_",value:function(){var t=arguments[0],e=arguments[1];Ct.constructor_.call(this,t,e),this.validateConstruction()}}]),s}(Ct);zt.MINIMUM_VALID_SIZE=4;var jt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}}],[{key:"constructor_",value:function(){if(0===arguments.length)z.constructor_.call(this);else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y)}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y)}}else if(2===arguments.length){var n=arguments[0],r=arguments[1];z.constructor_.call(this,n,r,z.NULL_ORDINATE)}}}]),o}(z);jt.X=0,jt.Y=1,jt.Z=-1,jt.M=-1;var Xt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;case o.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y;case o.M:return this._m}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y),this._m=this.getM()}}else if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2];z.constructor_.call(this,n,r,z.NULL_ORDINATE),this._m=i}}}]),o}(z);Xt.X=0,Xt.Y=1,Xt.Z=-1,Xt.M=2;var Ut=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case z.X:this.x=e;break;case z.Y:this.y=e;break;case z.Z:this.z=e;break;case z.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getOrdinate",value:function(t){switch(t){case z.X:return this.x;case z.Y:return this.y;case z.Z:return this.getZ();case z.M:return this.getM()}throw new x("Invalid ordinate index: "+t)}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e),this._m=this.getM()}}else if(4===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],s=arguments[3];z.constructor_.call(this,n,r,i),this._m=s}}}]),o}(z),Zt=function(){function e(){t(this,e)}return n(e,null,[{key:"measures",value:function(t){return t instanceof jt?0:t instanceof Xt||t instanceof Ut?1:0}},{key:"dimension",value:function(t){return t instanceof jt?2:t instanceof Xt?3:t instanceof Ut?4:3}},{key:"create",value:function(){if(1===arguments.length){var t=arguments[0];return e.create(t,0)}if(2===arguments.length){var n=arguments[0],r=arguments[1];return 2===n?new jt:3===n&&0===r?new z:3===n&&1===r?new Xt:4===n&&1===r?new Ut:new z}}}]),e}(),Ht=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getCoordinate",value:function(t){return this.get(t)}},{key:"addAll",value:function(){if(2===arguments.length&&"boolean"==typeof arguments[1]&&ot(arguments[0],H)){for(var t=arguments[1],e=!1,n=arguments[0].iterator();n.hasNext();)this.add(n.next(),t),e=!0;return e}return f(i(s.prototype),"addAll",this).apply(this,arguments)}},{key:"clone",value:function(){for(var t=f(i(s.prototype),"clone",this).call(this),e=0;e=1&&this.get(this.size()-1).equals2D(r))return null;f(i(s.prototype),"add",this).call(this,r)}else if(arguments[0]instanceof Object&&"boolean"==typeof arguments[1]){var o=arguments[0],a=arguments[1];return this.add(o,a),!0}}else if(3===arguments.length){if("boolean"==typeof arguments[2]&&arguments[0]instanceof Array&&"boolean"==typeof arguments[1]){var u=arguments[0],l=arguments[1];if(arguments[2])for(var h=0;h=0;c--)this.add(u[c],l);return!0}if("boolean"==typeof arguments[2]&&Number.isInteger(arguments[0])&&arguments[1]instanceof z){var g=arguments[0],p=arguments[1];if(!arguments[2]){var v=this.size();if(v>0){if(g>0&&this.get(g-1).equals2D(p))return null;if(g_&&(x=-1);for(var E=m;E!==_;E+=x)this.add(d[E],y);return!0}}},{key:"closeRing",value:function(){if(this.size()>0){var t=this.get(0).copy();this.add(t,!1)}}}],[{key:"constructor_",value:function(){if(0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.ensureCapacity(t.length),this.add(t,!0)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this.ensureCapacity(e.length),this.add(e,n)}}}]),s}(dt);Ht.coordArrayType=new Array(0).fill(null);var Wt=function(){function e(){t(this,e)}return n(e,null,[{key:"isRing",value:function(t){return!(t.length<4||!t[0].equals2D(t[t.length-1]))}},{key:"ptNotInList",value:function(t,n){for(var r=0;r=t?e:[]}},{key:"indexOf",value:function(t,e){for(var n=0;n0)&&(e=t[n]);return e}},{key:"extract",value:function(t,e,n){e=Et.clamp(e,0,t.length);var r=(n=Et.clamp(n,-1,t.length))-e+1;n<0&&(r=0),e>=t.length&&(r=0),nr.length)return 1;if(0===n.length)return 0;var i=Wt.compare(n,r);return Wt.isEqualReversed(n,r)?0:i}},{key:"OLDcompare",value:function(t,e){var n=t,r=e;if(n.lengthr.length)return 1;if(0===n.length)return 0;for(var i=Wt.increasingDirection(n),o=Wt.increasingDirection(r),s=i>0?0:n.length-1,a=o>0?0:n.length-1,u=0;u0){var t=new Qt(17*this._coordinates.length);t.append("("),t.append(this._coordinates[0]);for(var e=1;e3&&(t=3),t<2&&(t=2),new $t(arguments[0],t)}if(3===arguments.length){var e=arguments[2],n=arguments[1]-e;return e>1&&(e=1),n>3&&(n=3),n<2&&(n=2),new $t(arguments[0],n+e,e)}}}},{key:"interfaces_",get:function(){return[bt,w]}}],[{key:"instance",value:function(){return e.instanceObject}}]),e}();te.instanceObject=new te;var ee=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e=0?t:e}}]),e}(),oe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"readResolve",value:function(){return e.nameToTypeMap.get(this._name)}},{key:"toString",value:function(){return this._name}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){this._name=null;var t=arguments[0];this._name=t,e.nameToTypeMap.put(t,this)}}]),e}();oe.nameToTypeMap=new re,ie.Type=oe,ie.FIXED=new oe("FIXED"),ie.FLOATING=new oe("FLOATING"),ie.FLOATING_SINGLE=new oe("FLOATING SINGLE"),ie.maximumPreciseValue=9007199254740992;var se=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e1){if(u instanceof Ft)return this.createMultiPolygon(e.toPolygonArray(t));if(u instanceof Ct)return this.createMultiLineString(e.toLineStringArray(t));if(u instanceof Ot)return this.createMultiPoint(e.toPointArray(t));V.shouldNeverReachHere("Unhandled geometry type: "+u.getGeometryType())}return u}},{key:"createMultiPointFromCoords",value:function(t){return this.createMultiPoint(null!==t?this.getCoordinateSequenceFactory().create(t):null)}},{key:"createPoint",value:function(){if(0===arguments.length)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];return this.createPoint(null!==t?this.getCoordinateSequenceFactory().create([t]):null)}if(ot(arguments[0],ct))return new Ot(arguments[0],this)}}},{key:"getCoordinateSequenceFactory",value:function(){return this._coordinateSequenceFactory}},{key:"createPolygon",value:function(){if(0===arguments.length)return this.createPolygon(null,null);if(1===arguments.length){if(ot(arguments[0],ct)){var t=arguments[0];return this.createPolygon(this.createLinearRing(t))}if(arguments[0]instanceof Array){var e=arguments[0];return this.createPolygon(this.createLinearRing(e))}if(arguments[0]instanceof zt){var n=arguments[0];return this.createPolygon(n,null)}}else if(2===arguments.length)return new Ft(arguments[0],arguments[1],this)}},{key:"getSRID",value:function(){return this._SRID}},{key:"createGeometryCollection",value:function(){return 0===arguments.length?new Bt(null,this):1===arguments.length?new Bt(arguments[0],this):void 0}},{key:"getPrecisionModel",value:function(){return this._precisionModel}},{key:"createLinearRing",value:function(){if(0===arguments.length)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof Array){var t=arguments[0];return this.createLinearRing(null!==t?this.getCoordinateSequenceFactory().create(t):null)}if(ot(arguments[0],ct))return new zt(arguments[0],this)}}},{key:"createMultiPolygon",value:function(){return 0===arguments.length?new ee(null,this):1===arguments.length?new ee(arguments[0],this):void 0}},{key:"createMultiPoint",value:function(){if(0===arguments.length)return new Yt(null,this);if(1===arguments.length){if(arguments[0]instanceof Array)return new Yt(arguments[0],this);if(ot(arguments[0],ct)){var t=arguments[0];if(null===t)return this.createMultiPoint(new Array(0).fill(null));for(var e=new Array(t.size()).fill(null),n=0;n="a"&&t<="z"||t>="A"&&t<="Z"}},{key:"isNumeric_",value:function(t,e){return t>="0"&&t<="9"||"."==t&&!(void 0!==e&&e)}},{key:"isWhiteSpace_",value:function(t){return" "==t||"\t"==t||"\r"==t||"\n"==t}},{key:"nextChar_",value:function(){return this.wkt.charAt(++this.index_)}},{key:"nextToken",value:function(){var t,e=this.nextChar_(),n=this.index_,r=e;if("("==e)t=ve;else if(","==e)t=me;else if(")"==e)t=de;else if(this.isNumeric_(e)||"-"==e)t=ye,r=this.readNumber_();else if(this.isAlpha_(e))t=pe,r=this.readText_();else{if(this.isWhiteSpace_(e))return this.nextToken();if(""!==e)throw new Error("Unexpected character: "+e);t=_e}return{position:n,value:r,type:t}}},{key:"readNumber_",value:function(){var t,e=this.index_,n=!1,r=!1;do{"."==t?n=!0:"e"!=t&&"E"!=t||(r=!0),t=this.nextChar_()}while(this.isNumeric_(t,n)||!r&&("e"==t||"E"==t)||r&&("-"==t||"+"==t));return parseFloat(this.wkt.substring(e,this.index_--))}},{key:"readText_",value:function(){var t,e=this.index_;do{t=this.nextChar_()}while(this.isAlpha_(t));return this.wkt.substring(e,this.index_--).toUpperCase()}}]),e}(),ke=function(){function e(n,r){t(this,e),this.lexer_=n,this.token_,this.layout_=ue,this.factory=r}return n(e,[{key:"consume_",value:function(){this.token_=this.lexer_.nextToken()}},{key:"isTokenType",value:function(t){return this.token_.type==t}},{key:"match",value:function(t){var e=this.isTokenType(t);return e&&this.consume_(),e}},{key:"parse",value:function(){return this.consume_(),this.parseGeometry_()}},{key:"parseGeometryLayout_",value:function(){var t=ue,e=this.token_;if(this.isTokenType(pe)){var n=e.value;"Z"===n?t=le:"M"===n?t=he:"ZM"===n&&(t=ce),t!==ue&&this.consume_()}return t}},{key:"parseGeometryCollectionText_",value:function(){if(this.match(ve)){var t=[];do{t.push(this.parseGeometry_())}while(this.match(me));if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePointText_",value:function(){if(this.match(ve)){var t=this.parsePoint_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return null;throw new Error(this.formatErrorMessage_())}},{key:"parseLineStringText_",value:function(){if(this.match(ve)){var t=this.parsePointList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePolygonText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPointText_",value:function(){var t;if(this.match(ve)){if(t=this.token_.type==ve?this.parsePointTextList_():this.parsePointList_(),this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiLineStringText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPolygonText_",value:function(){if(this.match(ve)){var t=this.parsePolygonTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePoint_",value:function(){for(var t=[],e=this.layout_.length,n=0;n1?t.createPolygon(r[0],r.slice(1)):t.createPolygon(r[0])},r=this.token_;if(this.match(pe)){var i=r.value;if(this.layout_=this.parseGeometryLayout_(),"GEOMETRYCOLLECTION"==i){var o=this.parseGeometryCollectionText_();return t.createGeometryCollection(o)}switch(i){case"POINT":var s=this.parsePointText_();return s?t.createPoint(a(z,g(s))):t.createPoint();case"LINESTRING":var u=this.parseLineStringText_().map(e);return t.createLineString(u);case"LINEARRING":var l=this.parseLineStringText_().map(e);return t.createLinearRing(l);case"POLYGON":var h=this.parsePolygonText_();return h&&0!==h.length?n(h):t.createPolygon();case"MULTIPOINT":var c=this.parseMultiPointText_();if(!c||0===c.length)return t.createMultiPoint();var f=c.map(e).map((function(e){return t.createPoint(e)}));return t.createMultiPoint(f);case"MULTILINESTRING":var p=this.parseMultiLineStringText_().map((function(n){return t.createLineString(n.map(e))}));return t.createMultiLineString(p);case"MULTIPOLYGON":var v=this.parseMultiPolygonText_();if(!v||0===v.length)return t.createMultiPolygon();var d=v.map(n);return t.createMultiPolygon(d);default:throw new Error("Invalid geometry type: "+i)}}throw new Error(this.formatErrorMessage_())}}]),e}();function be(t){if(t.isEmpty())return"";var e=t.getCoordinate(),n=[e.x,e.y];return void 0===e.z||Number.isNaN(e.z)||n.push(e.z),void 0===e.m||Number.isNaN(e.m)||n.push(e.m),n.join(" ")}function we(t){for(var e=t.getCoordinates().map((function(t){var e=[t.x,t.y];return void 0===t.z||Number.isNaN(t.z)||e.push(t.z),void 0===t.m||Number.isNaN(t.m)||e.push(t.m),e})),n=[],r=0,i=e.length;r0&&(e+=" "+r),t.isEmpty()?e+" "+ge:e+" ("+n(t)+")"}var Me=function(){function e(n){t(this,e),this.geometryFactory=n||new ae,this.precisionModel=this.geometryFactory.getPrecisionModel()}return n(e,[{key:"read",value:function(t){var e=new Ee(t);return new ke(e,this.geometryFactory).parse()}},{key:"write",value:function(t){return Se(t)}}]),e}(),Le=function(){function e(n){t(this,e),this.parser=new Me(n)}return n(e,[{key:"write",value:function(t){return this.parser.write(t)}}],[{key:"toLineString",value:function(t,e){if(2!==arguments.length)throw new Error("Not implemented");return"LINESTRING ( "+t.x+" "+t.y+", "+e.x+" "+e.y+" )"}}]),e}(),Pe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getIndexAlongSegment",value:function(t,e){return this.computeIntLineIndex(),this._intLineIndex[t][e]}},{key:"getTopologySummary",value:function(){var t=new Qt;return this.isEndPoint()&&t.append(" endpoint"),this._isProper&&t.append(" proper"),this.isCollinear()&&t.append(" collinear"),t.toString()}},{key:"computeIntersection",value:function(t,e,n,r){this._inputLines[0][0]=t,this._inputLines[0][1]=e,this._inputLines[1][0]=n,this._inputLines[1][1]=r,this._result=this.computeIntersect(t,e,n,r)}},{key:"getIntersectionNum",value:function(){return this._result}},{key:"computeIntLineIndex",value:function(){if(0===arguments.length)null===this._intLineIndex&&(this._intLineIndex=Array(2).fill().map((function(){return Array(2)})),this.computeIntLineIndex(0),this.computeIntLineIndex(1));else if(1===arguments.length){var t=arguments[0];this.getEdgeDistance(t,0)>this.getEdgeDistance(t,1)?(this._intLineIndex[t][0]=0,this._intLineIndex[t][1]=1):(this._intLineIndex[t][0]=1,this._intLineIndex[t][1]=0)}}},{key:"isProper",value:function(){return this.hasIntersection()&&this._isProper}},{key:"setPrecisionModel",value:function(t){this._precisionModel=t}},{key:"isInteriorIntersection",value:function(){if(0===arguments.length)return!!this.isInteriorIntersection(0)||!!this.isInteriorIntersection(1);if(1===arguments.length){for(var t=arguments[0],e=0;ei?r:i;else{var s=Math.abs(t.x-e.x),a=Math.abs(t.y-e.y);0!==(o=r>i?s:a)||t.equals(e)||(o=Math.max(s,a))}return V.isTrue(!(0===o&&!t.equals(e)),"Bad distance calculation"),o}},{key:"nonRobustComputeEdgeDistance",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y,o=Math.sqrt(r*r+i*i);return V.isTrue(!(0===o&&!t.equals(e)),"Invalid distance calculation"),o}}]),e}();Pe.DONT_INTERSECT=0,Pe.DO_INTERSECT=1,Pe.COLLINEAR=2,Pe.NO_INTERSECTION=0,Pe.POINT_INTERSECTION=1,Pe.COLLINEAR_INTERSECTION=2;var Ce=function(e){r(s,e);var o=c(s);function s(){return t(this,s),o.call(this)}return n(s,[{key:"isInSegmentEnvelopes",value:function(t){var e=new X(this._inputLines[0][0],this._inputLines[0][1]),n=new X(this._inputLines[1][0],this._inputLines[1][1]);return e.contains(t)&&n.contains(t)}},{key:"computeIntersection",value:function(){if(3!==arguments.length)return f(i(s.prototype),"computeIntersection",this).apply(this,arguments);var t=arguments[0],e=arguments[1],n=arguments[2];if(this._isProper=!1,X.intersects(e,n,t)&&0===ft.index(e,n,t)&&0===ft.index(n,e,t))return this._isProper=!0,(t.equals(e)||t.equals(n))&&(this._isProper=!1),this._result=Pe.POINT_INTERSECTION,null;this._result=Pe.NO_INTERSECTION}},{key:"intersection",value:function(t,e,n,r){var i=this.intersectionSafe(t,e,n,r);return this.isInSegmentEnvelopes(i)||(i=new z(s.nearestEndpoint(t,e,n,r))),null!==this._precisionModel&&this._precisionModel.makePrecise(i),i}},{key:"checkDD",value:function(t,e,n,r,i){var o=ht.intersection(t,e,n,r),s=this.isInSegmentEnvelopes(o);xt.out.println("DD in env = "+s+" --------------------- "+o),i.distance(o)>1e-4&&xt.out.println("Distance = "+i.distance(o))}},{key:"intersectionSafe",value:function(t,e,n,r){var i=_t.intersection(t,e,n,r);return null===i&&(i=s.nearestEndpoint(t,e,n,r)),i}},{key:"computeCollinearIntersection",value:function(t,e,n,r){var i=X.intersects(t,e,n),o=X.intersects(t,e,r),s=X.intersects(n,r,t),a=X.intersects(n,r,e);return i&&o?(this._intPt[0]=n,this._intPt[1]=r,Pe.COLLINEAR_INTERSECTION):s&&a?(this._intPt[0]=t,this._intPt[1]=e,Pe.COLLINEAR_INTERSECTION):i&&s?(this._intPt[0]=n,this._intPt[1]=t,!n.equals(t)||o||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):i&&a?(this._intPt[0]=n,this._intPt[1]=e,!n.equals(e)||o||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&s?(this._intPt[0]=r,this._intPt[1]=t,!r.equals(t)||i||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&a?(this._intPt[0]=r,this._intPt[1]=e,!r.equals(e)||i||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):Pe.NO_INTERSECTION}},{key:"computeIntersect",value:function(t,e,n,r){if(this._isProper=!1,!X.intersects(t,e,n,r))return Pe.NO_INTERSECTION;var i=ft.index(t,e,n),o=ft.index(t,e,r);if(i>0&&o>0||i<0&&o<0)return Pe.NO_INTERSECTION;var s=ft.index(n,r,t),a=ft.index(n,r,e);return s>0&&a>0||s<0&&a<0?Pe.NO_INTERSECTION:0===i&&0===o&&0===s&&0===a?this.computeCollinearIntersection(t,e,n,r):(0===i||0===o||0===s||0===a?(this._isProper=!1,t.equals2D(n)||t.equals2D(r)?this._intPt[0]=t:e.equals2D(n)||e.equals2D(r)?this._intPt[0]=e:0===i?this._intPt[0]=new z(n):0===o?this._intPt[0]=new z(r):0===s?this._intPt[0]=new z(t):0===a&&(this._intPt[0]=new z(e))):(this._isProper=!0,this._intPt[0]=this.intersection(t,e,n,r)),Pe.POINT_INTERSECTION)}}],[{key:"nearestEndpoint",value:function(t,e,n,r){var i=t,o=kt.pointToSegment(t,n,r),s=kt.pointToSegment(e,n,r);return sr&&(n=e.x,r=t.x),this._p.x>=n&&this._p.x<=r&&(this._isPointOnSegment=!0),null}if(t.y>this._p.y&&e.y<=this._p.y||e.y>this._p.y&&t.y<=this._p.y){var i=ft.index(t,e,this._p);if(i===ft.COLLINEAR)return this._isPointOnSegment=!0,null;e.ythis.location.length){var e=new Array(3).fill(null);e[tt.ON]=this.location[tt.ON],e[tt.LEFT]=Z.NONE,e[tt.RIGHT]=Z.NONE,this.location=e}for(var n=0;n1&&t.append(Z.toLocationSymbol(this.location[tt.LEFT])),t.append(Z.toLocationSymbol(this.location[tt.ON])),this.location.length>1&&t.append(Z.toLocationSymbol(this.location[tt.RIGHT])),t.toString()}},{key:"setLocations",value:function(t,e,n){this.location[tt.ON]=t,this.location[tt.LEFT]=e,this.location[tt.RIGHT]=n}},{key:"get",value:function(t){return t1}},{key:"isAnyNull",value:function(){for(var t=0;tthis._maxNodeDegree&&(this._maxNodeDegree=e),t=this.getNext(t)}while(t!==this._startDe);this._maxNodeDegree*=2}},{key:"addPoints",value:function(t,e,n){var r=t.getCoordinates();if(e){var i=1;n&&(i=0);for(var o=i;o=0;a--)this._pts.add(r[a])}}},{key:"isHole",value:function(){return this._isHole}},{key:"setInResult",value:function(){var t=this._startDe;do{t.getEdge().setInResult(!0),t=t.getNext()}while(t!==this._startDe)}},{key:"containsPoint",value:function(t){var e=this.getLinearRing();if(!e.getEnvelopeInternal().contains(t))return!1;if(!Oe.isInRing(t,e.getCoordinates()))return!1;for(var n=this._holes.iterator();n.hasNext();)if(n.next().containsPoint(t))return!1;return!0}},{key:"addHole",value:function(t){this._holes.add(t)}},{key:"isShell",value:function(){return null===this._shell}},{key:"getLabel",value:function(){return this._label}},{key:"getEdges",value:function(){return this._edges}},{key:"getMaxNodeDegree",value:function(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree}},{key:"getShell",value:function(){return this._shell}},{key:"mergeLabel",value:function(){if(1===arguments.length){var t=arguments[0];this.mergeLabel(t,0),this.mergeLabel(t,1)}else if(2===arguments.length){var e=arguments[1],n=arguments[0].getLocation(e,tt.RIGHT);if(n===Z.NONE)return null;if(this._label.getLocation(e)===Z.NONE)return this._label.setLocation(e,n),null}}},{key:"setShell",value:function(t){this._shell=t,null!==t&&t.addHole(this)}},{key:"toPolygon",value:function(t){for(var e=new Array(this._holes.size()).fill(null),n=0;n=2,"found partial label"),this.computeIM(t)}},{key:"isInResult",value:function(){return this._isInResult}},{key:"isVisited",value:function(){return this._isVisited}}],[{key:"constructor_",value:function(){if(this._label=null,this._isInResult=!1,this._isCovered=!1,this._isCoveredSet=!1,this._isVisited=!1,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._label=t}}}]),e}(),Ge=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isIncidentEdgeInResult",value:function(){for(var t=this.getEdges().getEdges().iterator();t.hasNext();)if(t.next().getEdge().isInResult())return!0;return!1}},{key:"isIsolated",value:function(){return 1===this._label.getGeometryCount()}},{key:"getCoordinate",value:function(){return this._coord}},{key:"print",value:function(t){t.println("node "+this._coord+" lbl: "+this._label)}},{key:"computeIM",value:function(t){}},{key:"computeMergedLocation",value:function(t,e){var n=Z.NONE;if(n=this._label.getLocation(e),!t.isNull(e)){var r=t.getLocation(e);n!==Z.BOUNDARY&&(n=r)}return n}},{key:"setLabel",value:function(){if(2!==arguments.length||!Number.isInteger(arguments[1])||!Number.isInteger(arguments[0]))return f(i(s.prototype),"setLabel",this).apply(this,arguments);var t=arguments[0],e=arguments[1];null===this._label?this._label=new Ae(t,e):this._label.setLocation(t,e)}},{key:"getEdges",value:function(){return this._edges}},{key:"mergeLabel",value:function(){if(arguments[0]instanceof s){var t=arguments[0];this.mergeLabel(t._label)}else if(arguments[0]instanceof Ae)for(var e=arguments[0],n=0;n<2;n++){var r=this.computeMergedLocation(e,n);this._label.getLocation(n)===Z.NONE&&this._label.setLocation(n,r)}}},{key:"add",value:function(t){this._edges.insert(t),t.setNode(this)}},{key:"setLabelBoundary",value:function(t){if(null===this._label)return null;var e=Z.NONE;null!==this._label&&(e=this._label.getLocation(t));var n=null;switch(e){case Z.BOUNDARY:n=Z.INTERIOR;break;case Z.INTERIOR:default:n=Z.BOUNDARY}this._label.setLocation(t,n)}}],[{key:"constructor_",value:function(){this._coord=null,this._edges=null;var t=arguments[0],e=arguments[1];this._coord=t,this._edges=e,this._label=new Ae(0,Z.NONE)}}]),s}(Ve),Be=function(e){r(i,e);var n=c(i);function i(){return t(this,i),n.apply(this,arguments)}return i}(ne);function Ye(t){return null==t?0:t.color}function ze(t){return null==t?null:t.parent}function je(t,e){null!==t&&(t.color=e)}function Xe(t){return null==t?null:t.left}function Ue(t){return null==t?null:t.right}var Ze=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),(e=i.call(this)).root_=null,e.size_=0,e}return n(o,[{key:"get",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return e.value;e=e.right}}return null}},{key:"put",value:function(t,e){if(null===this.root_)return this.root_={key:t,value:e,left:null,right:null,parent:null,color:0,getValue:function(){return this.value},getKey:function(){return this.key}},this.size_=1,null;var n,r,i=this.root_;do{if(n=i,(r=t.compareTo(i.key))<0)i=i.left;else{if(!(r>0)){var o=i.value;return i.value=e,o}i=i.right}}while(null!==i);var s={key:t,left:null,right:null,value:e,parent:n,color:0,getValue:function(){return this.value},getKey:function(){return this.key}};return r<0?n.left=s:n.right=s,this.fixAfterInsertion(s),this.size_++,null}},{key:"fixAfterInsertion",value:function(t){var e;for(t.color=1;null!=t&&t!==this.root_&&1===t.parent.color;)ze(t)===Xe(ze(ze(t)))?1===Ye(e=Ue(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Ue(ze(t))&&(t=ze(t),this.rotateLeft(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateRight(ze(ze(t)))):1===Ye(e=Xe(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Xe(ze(t))&&(t=ze(t),this.rotateRight(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateLeft(ze(ze(t))));this.root_.color=0}},{key:"values",value:function(){var t=new dt,e=this.getFirstEntry();if(null!==e)for(t.add(e.value);null!==(e=o.successor(e));)t.add(e.value);return t}},{key:"entrySet",value:function(){var t=new Q,e=this.getFirstEntry();if(null!==e)for(t.add(e);null!==(e=o.successor(e));)t.add(e);return t}},{key:"rotateLeft",value:function(t){if(null!=t){var e=t.right;t.right=e.left,null!=e.left&&(e.left.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.left===t?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}}},{key:"rotateRight",value:function(t){if(null!=t){var e=t.left;t.left=e.right,null!=e.right&&(e.right.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.right===t?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}}},{key:"getFirstEntry",value:function(){var t=this.root_;if(null!=t)for(;null!=t.left;)t=t.left;return t}},{key:"size",value:function(){return this.size_}},{key:"containsKey",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return!0;e=e.right}}return!1}}],[{key:"successor",value:function(t){var e;if(null===t)return null;if(null!==t.right){for(e=t.right;null!==e.left;)e=e.left;return e}e=t.parent;for(var n=t;null!==e&&n===e.right;)n=e,e=e.parent;return e}}]),o}(Be),He=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"find",value:function(t){return this.nodeMap.get(t)}},{key:"addNode",value:function(){if(arguments[0]instanceof z){var t=arguments[0],e=this.nodeMap.get(t);return null===e&&(e=this.nodeFact.createNode(t),this.nodeMap.put(t,e)),e}if(arguments[0]instanceof Ge){var n=arguments[0],r=this.nodeMap.get(n.getCoordinate());return null===r?(this.nodeMap.put(n.getCoordinate(),n),n):(r.mergeLabel(n),r)}}},{key:"print",value:function(t){for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this.nodeMap.values().iterator()}},{key:"values",value:function(){return this.nodeMap.values()}},{key:"getBoundaryNodes",value:function(t){for(var e=new dt,n=this.iterator();n.hasNext();){var r=n.next();r.getLabel().getLocation(t)===Z.BOUNDARY&&e.add(r)}return e}},{key:"add",value:function(t){var e=t.getCoordinate();this.addNode(e).add(t)}}],[{key:"constructor_",value:function(){this.nodeMap=new Ze,this.nodeFact=null;var t=arguments[0];this.nodeFact=t}}]),e}(),We=function(){function e(){t(this,e)}return n(e,null,[{key:"isNorthern",value:function(t){return t===e.NE||t===e.NW}},{key:"isOpposite",value:function(t,e){return t!==e&&2==(t-e+4)%4}},{key:"commonHalfPlane",value:function(t,e){if(t===e)return t;if(2==(t-e+4)%4)return-1;var n=te?t:e)?3:n}},{key:"isInHalfPlane",value:function(t,n){return n===e.SE?t===e.SE||t===e.SW:t===n||t===n+1}},{key:"quadrant",value:function(){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1];if(0===t&&0===n)throw new x("Cannot compute the quadrant for point ( "+t+", "+n+" )");return t>=0?n>=0?e.NE:e.SE:n>=0?e.NW:e.SW}if(arguments[0]instanceof z&&arguments[1]instanceof z){var r=arguments[0],i=arguments[1];if(i.x===r.x&&i.y===r.y)throw new x("Cannot compute the quadrant for two identical points "+r);return i.x>=r.x?i.y>=r.y?e.NE:e.SE:i.y>=r.y?e.NW:e.SW}}}]),e}();We.NE=0,We.NW=1,We.SW=2,We.SE=3;var Je=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareDirection",value:function(t){return this._dx===t._dx&&this._dy===t._dy?0:this._quadrant>t._quadrant?1:this._quadrant2){o.linkDirectedEdgesForMinimalEdgeRings();var s=o.buildMinimalRings(),a=this.findShell(s);null!==a?(this.placePolygonHoles(a,s),e.add(a)):n.addAll(s)}else r.add(o)}return r}},{key:"buildMaximalEdgeRings",value:function(t){for(var e=new dt,n=t.iterator();n.hasNext();){var r=n.next();if(r.isInResult()&&r.getLabel().isArea()&&null===r.getEdgeRing()){var i=new qe(r,this._geometryFactory);e.add(i),i.setInResult()}}return e}},{key:"placePolygonHoles",value:function(t,e){for(var n=e.iterator();n.hasNext();){var r=n.next();r.isHole()&&r.setShell(t)}}},{key:"getPolygons",value:function(){return this.computePolygons(this._shellList)}},{key:"findShell",value:function(t){for(var e=0,n=null,r=t.iterator();r.hasNext();){var i=r.next();i.isHole()||(n=i,e++)}return V.isTrue(e<=1,"found two shells in MinimalEdgeRing list"),n}},{key:"add",value:function(){if(1===arguments.length){var t=arguments[0];this.add(t.getEdgeEnds(),t.getNodes())}else if(2===arguments.length){var e=arguments[0],n=arguments[1];$e.linkResultDirectedEdges(n);var r=this.buildMaximalEdgeRings(e),i=new dt,o=this.buildMinimalEdgeRings(r,this._shellList,i);this.sortShellsAndHoles(o,this._shellList,i),this.placeFreeHoles(this._shellList,i)}}}],[{key:"constructor_",value:function(){this._geometryFactory=null,this._shellList=new dt;var t=arguments[0];this._geometryFactory=t}},{key:"findEdgeRingContaining",value:function(t,e){for(var n=t.getLinearRing(),r=n.getEnvelopeInternal(),i=n.getCoordinateN(0),o=null,s=null,a=e.iterator();a.hasNext();){var u=a.next(),l=u.getLinearRing(),h=l.getEnvelopeInternal();if(!h.equals(r)&&h.contains(r)){i=Wt.ptNotInList(n.getCoordinates(),l.getCoordinates());var c=!1;Oe.isInRing(i,l.getCoordinates())&&(c=!0),c&&(null===o||s.contains(h))&&(s=(o=u).getLinearRing().getEnvelopeInternal())}}return o}}]),e}(),en=function(){function e(){t(this,e)}return n(e,[{key:"getBounds",value:function(){}}]),e}(),nn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getItem",value:function(){return this._item}},{key:"getBounds",value:function(){return this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){this._bounds=null,this._item=null;var t=arguments[0],e=arguments[1];this._bounds=t,this._item=e}}]),e}(),rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"poll",value:function(){if(this.isEmpty())return null;var t=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),t}},{key:"size",value:function(){return this._size}},{key:"reorder",value:function(t){for(var e=null,n=this._items.get(t);2*t<=this._size&&((e=2*t)!==this._size&&this._items.get(e+1).compareTo(this._items.get(e))<0&&e++,this._items.get(e).compareTo(n)<0);t=e)this._items.set(t,this._items.get(e));this._items.set(t,n)}},{key:"clear",value:function(){this._size=0,this._items.clear()}},{key:"peek",value:function(){return this.isEmpty()?null:this._items.get(1)}},{key:"isEmpty",value:function(){return 0===this._size}},{key:"add",value:function(t){this._items.add(null),this._size+=1;var e=this._size;for(this._items.set(0,t);t.compareTo(this._items.get(Math.trunc(e/2)))<0;e/=2)this._items.set(e,this._items.get(Math.trunc(e/2)));this._items.set(e,t)}}],[{key:"constructor_",value:function(){this._size=null,this._items=null,this._size=0,this._items=new dt,this._items.add(null)}}]),e}(),on=function(){function e(){t(this,e)}return n(e,[{key:"insert",value:function(t,e){}},{key:"remove",value:function(t,e){}},{key:"query",value:function(){}}]),e}(),sn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLevel",value:function(){return this._level}},{key:"size",value:function(){return this._childBoundables.size()}},{key:"getChildBoundables",value:function(){return this._childBoundables}},{key:"addChildBoundable",value:function(t){V.isTrue(null===this._bounds),this._childBoundables.add(t)}},{key:"isEmpty",value:function(){return this._childBoundables.isEmpty()}},{key:"getBounds",value:function(){return null===this._bounds&&(this._bounds=this.computeBounds()),this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){if(this._childBoundables=new dt,this._bounds=null,this._level=null,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._level=t}}}]),e}(),an={reverseOrder:function(){return{compare:function(t,e){return e.compareTo(t)}}},min:function(t){return an.sort(t),t.get(0)},sort:function(t,e){var n=t.toArray();e?At.sort(n,e):At.sort(n);for(var r=t.iterator(),i=0,o=n.length;ie.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,!1,t,n),null):(this.expand(this._boundable2,this._boundable1,!0,t,n),null);if(r)return this.expand(this._boundable1,this._boundable2,!1,t,n),null;if(i)return this.expand(this._boundable2,this._boundable1,!0,t,n),null;throw new x("neither boundable is composite")}},{key:"isLeaves",value:function(){return!(e.isComposite(this._boundable1)||e.isComposite(this._boundable2))}},{key:"compareTo",value:function(t){var e=t;return this._distancee._distance?1:0}},{key:"expand",value:function(t,n,r,i,o){for(var s=t.getChildBoundables().iterator();s.hasNext();){var a=s.next(),u=null;(u=r?new e(n,a,this._itemDistance):new e(a,n,this._itemDistance)).getDistance()-2),r.getLevel()===n)return i.add(r),null;for(var o=r.getChildBoundables().iterator();o.hasNext();){var s=o.next();s instanceof sn?this.boundablesAtLevel(n,s,i):(V.isTrue(s instanceof nn),-1===n&&i.add(s))}return null}}},{key:"query",value:function(){if(1===arguments.length){var t=arguments[0];this.build();var e=new dt;return this.isEmpty()||this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.queryInternal(t,this._root,e),e}if(2===arguments.length){var n=arguments[0],r=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),n)&&this.queryInternal(n,this._root,r)}}},{key:"build",value:function(){if(this._built)return null;this._root=this._itemBoundables.isEmpty()?this.createNode(0):this.createHigherLevels(this._itemBoundables,-1),this._itemBoundables=null,this._built=!0}},{key:"getRoot",value:function(){return this.build(),this._root}},{key:"remove",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];return this.build(),!!this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.remove(t,this._root,e)}if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],o=this.removeItem(r,i);if(o)return!0;for(var s=null,a=r.getChildBoundables().iterator();a.hasNext();){var u=a.next();if(this.getIntersectsOp().intersects(u.getBounds(),n)&&u instanceof sn&&(o=this.remove(n,u,i))){s=u;break}}return null!==s&&s.getChildBoundables().isEmpty()&&r.getChildBoundables().remove(s),o}}},{key:"createHigherLevels",value:function(t,e){V.isTrue(!t.isEmpty());var n=this.createParentBoundables(t,e+1);return 1===n.size()?n.get(0):this.createHigherLevels(n,e+1)}},{key:"depth",value:function(){if(0===arguments.length)return this.isEmpty()?0:(this.build(),this.depth(this._root));if(1===arguments.length){for(var t=0,e=arguments[0].getChildBoundables().iterator();e.hasNext();){var n=e.next();if(n instanceof sn){var r=this.depth(n);r>t&&(t=r)}}return t+1}}},{key:"createParentBoundables",value:function(t,e){V.isTrue(!t.isEmpty());var n=new dt;n.add(this.createNode(e));var r=new dt(t);an.sort(r,this.getComparator());for(var i=r.iterator();i.hasNext();){var o=i.next();this.lastNode(n).getChildBoundables().size()===this.getNodeCapacity()&&n.add(this.createNode(e)),this.lastNode(n).addChildBoundable(o)}return n}},{key:"isEmpty",value:function(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){if(this._root=null,this._built=!1,this._itemBoundables=new dt,this._nodeCapacity=null,0===arguments.length)e.constructor_.call(this,e.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];V.isTrue(t>1,"Node capacity must be greater than 1"),this._nodeCapacity=t}}},{key:"compareDoubles",value:function(t,e){return t>e?1:t0);for(var n=new dt,r=0;r=0;){var u=o.poll(),l=u.getDistance();if(l>=i)break;u.isLeaves()?a.size()l&&(a.poll(),a.add(u)),i=a.peek().getDistance()):u.expandToQueue(o,i)}return s.getItems(a)}}},{key:"createNode",value:function(t){return new pn(t)}},{key:"size",value:function(){return 0===arguments.length?f(i(s.prototype),"size",this).call(this):f(i(s.prototype),"size",this).apply(this,arguments)}},{key:"insert",value:function(){if(!(2===arguments.length&&arguments[1]instanceof Object&&arguments[0]instanceof X))return f(i(s.prototype),"insert",this).apply(this,arguments);var t=arguments[0],e=arguments[1];if(t.isNull())return null;f(i(s.prototype),"insert",this).call(this,t,e)}},{key:"getIntersectsOp",value:function(){return s.intersectsOp}},{key:"verticalSlices",value:function(t,e){for(var n=Math.trunc(Math.ceil(t.size()/e)),r=new Array(e).fill(null),i=t.iterator(),o=0;o0;){var s=o.poll(),a=s.getDistance();if(a>=r)break;s.isLeaves()?(r=a,i=s):s.expandToQueue(o,r)}return null===i?null:[i.getBoundable(0).getItem(),i.getBoundable(1).getItem()]}}else{if(2===arguments.length){var u=arguments[0],l=arguments[1];if(this.isEmpty()||u.isEmpty())return null;var h=new ln(this.getRoot(),u.getRoot(),l);return this.nearestNeighbour(h)}if(3===arguments.length){var c=arguments[2],f=new nn(arguments[0],arguments[1]),g=new ln(this.getRoot(),f,c);return this.nearestNeighbour(g)[0]}if(4===arguments.length){var p=arguments[2],v=arguments[3],d=new nn(arguments[0],arguments[1]),y=new ln(this.getRoot(),d,p);return this.nearestNeighbourK(y,v)}}}},{key:"isWithinDistance",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1],n=A.POSITIVE_INFINITY,r=new rn;for(r.add(t);!r.isEmpty();){var i=r.poll(),o=i.getDistance();if(o>e)return!1;if(i.maximumDistance()<=e)return!0;if(i.isLeaves()){if((n=o)<=e)return!0}else i.expandToQueue(r,n)}return!1}if(3===arguments.length){var s=arguments[0],a=arguments[1],u=arguments[2],l=new ln(this.getRoot(),s.getRoot(),a);return this.isWithinDistance(l,u)}}},{key:"interfaces_",get:function(){return[on,w]}}],[{key:"constructor_",value:function(){if(0===arguments.length)s.constructor_.call(this,s.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];cn.constructor_.call(this,t)}}},{key:"centreX",value:function(t){return s.avg(t.getMinX(),t.getMaxX())}},{key:"avg",value:function(t,e){return(t+e)/2}},{key:"getItems",value:function(t){for(var e=new Array(t.size()).fill(null),n=0;!t.isEmpty();){var r=t.poll();e[n]=r.getBoundable(0).getItem(),n++}return e}},{key:"centreY",value:function(t){return s.avg(t.getMinY(),t.getMaxY())}}]),s}(cn),pn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"computeBounds",value:function(){for(var t=null,e=this.getChildBoundables().iterator();e.hasNext();){var n=e.next();null===t?t=new X(n.getBounds()):t.expandToInclude(n.getBounds())}return t}}],[{key:"constructor_",value:function(){var t=arguments[0];sn.constructor_.call(this,t)}}]),o}(sn);gn.STRtreeNode=pn,gn.xComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreX(t.getBounds()),gn.centreX(e.getBounds()))}}]),e}()),gn.yComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreY(t.getBounds()),gn.centreY(e.getBounds()))}}]),e}()),gn.intersectsOp=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[IntersectsOp]}},{key:"intersects",value:function(t,e){return t.intersects(e)}}]),e}()),gn.DEFAULT_NODE_CAPACITY=10;var vn=function(){function e(){t(this,e)}return n(e,null,[{key:"relativeSign",value:function(t,e){return te?1:0}},{key:"compare",value:function(t,n,r){if(n.equals2D(r))return 0;var i=e.relativeSign(n.x,r.x),o=e.relativeSign(n.y,r.y);switch(t){case 0:return e.compareValue(i,o);case 1:return e.compareValue(o,i);case 2:return e.compareValue(o,-i);case 3:return e.compareValue(-i,o);case 4:return e.compareValue(-i,-o);case 5:return e.compareValue(-o,-i);case 6:return e.compareValue(-o,i);case 7:return e.compareValue(i,-o)}return V.shouldNeverReachHere("invalid octant value"),0}},{key:"compareValue",value:function(t,e){return t<0?-1:t>0?1:e<0?-1:e>0?1:0}}]),e}(),dn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this.coord}},{key:"print",value:function(t){t.print(this.coord),t.print(" seg # = "+this.segmentIndex)}},{key:"compareTo",value:function(t){var e=t;return this.segmentIndexe.segmentIndex?1:this.coord.equals2D(e.coord)?0:this._isInterior?e._isInterior?vn.compare(this._segmentOctant,this.coord,e.coord):1:-1}},{key:"isEndPoint",value:function(t){return 0===this.segmentIndex&&!this._isInterior||this.segmentIndex===t}},{key:"toString",value:function(){return this.segmentIndex+":"+this.coord.toString()}},{key:"isInterior",value:function(){return this._isInterior}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;var t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this._segString=t,this.coord=new z(e),this.segmentIndex=n,this._segmentOctant=r,this._isInterior=!e.equals2D(t.getCoordinate(n))}}]),e}(),yn=function(){function e(){t(this,e)}return n(e,[{key:"hasNext",value:function(){}},{key:"next",value:function(){}},{key:"remove",value:function(){}}]),e}(),mn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getSplitCoordinates",value:function(){var t=new Ht;this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next();this.addEdgeCoordinates(n,r,t),n=r}return t.toCoordinateArray()}},{key:"addCollapsedNodes",value:function(){var t=new dt;this.findCollapsesFromInsertedNodes(t),this.findCollapsesFromExistingVertices(t);for(var e=t.iterator();e.hasNext();){var n=e.next().intValue();this.add(this._edge.getCoordinate(n),n)}}},{key:"createSplitEdgePts",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2;if(2===n)return[new z(t.coord),new z(e.coord)];var r=this._edge.getCoordinate(e.segmentIndex),i=e.isInterior()||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this._edge.getCoordinate(a);return i&&(o[s]=new z(e.coord)),o}},{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"findCollapsesFromExistingVertices",value:function(t){for(var e=0;e=0?n>=0?r>=i?0:1:r>=i?7:6:n>=0?r>=i?3:2:r>=i?4:5}if(arguments[0]instanceof z&&arguments[1]instanceof z){var o=arguments[0],s=arguments[1],a=s.x-o.x,u=s.y-o.y;if(0===a&&0===u)throw new x("Cannot compute the octant for two identical points "+o);return e.octant(a,u)}}}]),e}(),xn=function(){function e(){t(this,e)}return n(e,[{key:"getCoordinates",value:function(){}},{key:"size",value:function(){}},{key:"getCoordinate",value:function(t){}},{key:"isClosed",value:function(){}},{key:"setData",value:function(t){}},{key:"getData",value:function(){}}]),e}(),En=function(){function e(){t(this,e)}return n(e,[{key:"addIntersection",value:function(t,e){}},{key:"interfaces_",get:function(){return[xn]}}]),e}(),kn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinates",value:function(){return this._pts}},{key:"size",value:function(){return this._pts.length}},{key:"getCoordinate",value:function(t){return this._pts[t]}},{key:"isClosed",value:function(){return this._pts[0].equals(this._pts[this._pts.length-1])}},{key:"getSegmentOctant",value:function(t){return t===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(t),this.getCoordinate(t+1))}},{key:"setData",value:function(t){this._data=t}},{key:"safeOctant",value:function(t,e){return t.equals2D(e)?0:_n.octant(t,e)}},{key:"getData",value:function(){return this._data}},{key:"addIntersection",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];this.addIntersectionNode(t,e)}else if(4===arguments.length){var n=arguments[1],r=arguments[3],i=new z(arguments[0].getIntersection(r));this.addIntersection(i,n)}}},{key:"toString",value:function(){return Le.toLineString(new $t(this._pts))}},{key:"getNodeList",value:function(){return this._nodeList}},{key:"addIntersectionNode",value:function(t,e){var n=e,r=n+1;if(r=0&&r>=0||n<=0&&r<=0?Math.max(n,r):0}if(arguments[0]instanceof z){var i=arguments[0];return ft.index(this.p0,this.p1,i)}}},{key:"toGeometry",value:function(t){return t.createLineString([this.p0,this.p1])}},{key:"isVertical",value:function(){return this.p0.x===this.p1.x}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.p0.equals(n.p0)&&this.p1.equals(n.p1)}},{key:"intersection",value:function(t){var e=new Ce;return e.computeIntersection(this.p0,this.p1,t.p0,t.p1),e.hasIntersection()?e.getIntersection(0):null}},{key:"project",value:function(){if(arguments[0]instanceof z){var t=arguments[0];if(t.equals(this.p0)||t.equals(this.p1))return new z(t);var n=this.projectionFactor(t),r=new z;return r.x=this.p0.x+n*(this.p1.x-this.p0.x),r.y=this.p0.y+n*(this.p1.y-this.p0.y),r}if(arguments[0]instanceof e){var i=arguments[0],o=this.projectionFactor(i.p0),s=this.projectionFactor(i.p1);if(o>=1&&s>=1)return null;if(o<=0&&s<=0)return null;var a=this.project(i.p0);o<0&&(a=this.p0),o>1&&(a=this.p1);var u=this.project(i.p1);return s<0&&(u=this.p0),s>1&&(u=this.p1),new e(a,u)}}},{key:"normalize",value:function(){this.p1.compareTo(this.p0)<0&&this.reverse()}},{key:"angle",value:function(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)}},{key:"getCoordinate",value:function(t){return 0===t?this.p0:this.p1}},{key:"distancePerpendicular",value:function(t){return kt.pointToLinePerpendicular(t,this.p0,this.p1)}},{key:"minY",value:function(){return Math.min(this.p0.y,this.p1.y)}},{key:"midPoint",value:function(){return e.midPoint(this.p0,this.p1)}},{key:"projectionFactor",value:function(t){if(t.equals(this.p0))return 0;if(t.equals(this.p1))return 1;var e=this.p1.x-this.p0.x,n=this.p1.y-this.p0.y,r=e*e+n*n;return r<=0?A.NaN:((t.x-this.p0.x)*e+(t.y-this.p0.y)*n)/r}},{key:"closestPoints",value:function(t){var e=this.intersection(t);if(null!==e)return[e,e];var n=new Array(2).fill(null),r=A.MAX_VALUE,i=null,o=this.closestPoint(t.p0);r=o.distance(t.p0),n[0]=o,n[1]=t.p0;var s=this.closestPoint(t.p1);(i=s.distance(t.p1))0&&e<1?this.project(t):this.p0.distance(t)1||A.isNaN(e))&&(e=1),e}},{key:"toString",value:function(){return"LINESTRING( "+this.p0.x+" "+this.p0.y+", "+this.p1.x+" "+this.p1.y+")"}},{key:"isHorizontal",value:function(){return this.p0.y===this.p1.y}},{key:"reflect",value:function(t){var e=this.p1.getY()-this.p0.getY(),n=this.p0.getX()-this.p1.getX(),r=this.p0.getY()*(this.p1.getX()-this.p0.getX())-this.p0.getX()*(this.p1.getY()-this.p0.getY()),i=e*e+n*n,o=e*e-n*n,s=t.getX(),a=t.getY();return new z((-o*s-2*e*n*a-2*e*r)/i,(o*a-2*e*n*s-2*n*r)/i)}},{key:"distance",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return kt.segmentToSegment(this.p0,this.p1,t.p0,t.p1)}if(arguments[0]instanceof z){var n=arguments[0];return kt.pointToSegment(n,this.p0,this.p1)}}},{key:"pointAlong",value:function(t){var e=new z;return e.x=this.p0.x+t*(this.p1.x-this.p0.x),e.y=this.p0.y+t*(this.p1.y-this.p0.y),e}},{key:"hashCode",value:function(){var t=A.doubleToLongBits(this.p0.x);t^=31*A.doubleToLongBits(this.p0.y);var e=Math.trunc(t)^Math.trunc(t>>32),n=A.doubleToLongBits(this.p1.x);return n^=31*A.doubleToLongBits(this.p1.y),e^Math.trunc(n)^Math.trunc(n>>32)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this.p0=null,this.p1=null,0===arguments.length)e.constructor_.call(this,new z,new z);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.p0,t.p1)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.p0=n,this.p1=r}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];e.constructor_.call(this,new z(i,o),new z(s,a))}}},{key:"midPoint",value:function(t,e){return new z((t.x+e.x)/2,(t.y+e.y)/2)}}]),e}(),wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"overlap",value:function(){if(2===arguments.length);else if(4===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[3];arguments[0].getLineSegment(t,this._overlapSeg1),e.getLineSegment(n,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}}}],[{key:"constructor_",value:function(){this._overlapSeg1=new bn,this._overlapSeg2=new bn}}]),e}(),In=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLineSegment",value:function(t,e){e.p0=this._pts[t],e.p1=this._pts[t+1]}},{key:"computeSelect",value:function(t,e,n,r){var i=this._pts[e],o=this._pts[n];if(n-e==1)return r.select(this,e),null;if(!t.intersects(i,o))return null;var s=Math.trunc((e+n)/2);e=t.length-1)return t.length-1;for(var r=We.quadrant(t[n],t[n+1]),i=e+1;in.getId()&&(n.computeOverlaps(i,t),this._nOverlaps++),this._segInt.isDone())return null}}}],[{key:"constructor_",value:function(){if(this._monoChains=new dt,this._index=new gn,this._idCounter=0,this._nodedSegStrings=null,this._nOverlaps=0,0===arguments.length);else if(1===arguments.length){var t=arguments[0];Mn.constructor_.call(this,t)}}}]),o}(Mn),Pn=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"overlap",value:function(){if(4!==arguments.length)return f(i(s.prototype),"overlap",this).apply(this,arguments);var t=arguments[1],e=arguments[2],n=arguments[3],r=arguments[0].getContext(),o=e.getContext();this._si.processIntersections(r,t,o,n)}}],[{key:"constructor_",value:function(){this._si=null;var t=arguments[0];this._si=t}}]),s}(wn);Ln.SegmentOverlapAction=Pn;var Cn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isDeletable",value:function(t,e,n,r){var i=this._inputLine[t],o=this._inputLine[e],s=this._inputLine[n];return!!this.isConcave(i,o,s)&&!!this.isShallow(i,o,s,r)&&this.isShallowSampled(i,o,t,n,r)}},{key:"deleteShallowConcavities",value:function(){for(var t=1,n=this.findNextNonDeletedIndex(t),r=this.findNextNonDeletedIndex(n),i=!1;r=0;r--)this.addPt(t[r])}},{key:"isRedundant",value:function(t){if(this._ptList.size()<1)return!1;var e=this._ptList.get(this._ptList.size()-1);return t.distance(e)Math.PI;)t-=e.PI_TIMES_2;for(;t<=-Math.PI;)t+=e.PI_TIMES_2;return t}},{key:"angle",value:function(){if(1===arguments.length){var t=arguments[0];return Math.atan2(t.y,t.x)}if(2===arguments.length){var e=arguments[0],n=arguments[1],r=n.x-e.x,i=n.y-e.y;return Math.atan2(i,r)}}},{key:"isAcute",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)>0}},{key:"isObtuse",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)<0}},{key:"interiorAngle",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return Math.abs(o-i)}},{key:"normalizePositive",value:function(t){if(t<0){for(;t<0;)t+=e.PI_TIMES_2;t>=e.PI_TIMES_2&&(t=0)}else{for(;t>=e.PI_TIMES_2;)t-=e.PI_TIMES_2;t<0&&(t=0)}return t}},{key:"angleBetween",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return e.diff(i,o)}},{key:"diff",value:function(t,e){var n=null;return(n=tMath.PI&&(n=2*Math.PI-n),n}},{key:"toRadians",value:function(t){return t*Math.PI/180}},{key:"getTurn",value:function(t,n){var r=Math.sin(n-t);return r>0?e.COUNTERCLOCKWISE:r<0?e.CLOCKWISE:e.NONE}},{key:"angleBetweenOriented",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r)-i;return o<=-Math.PI?o+e.PI_TIMES_2:o>Math.PI?o-e.PI_TIMES_2:o}}]),e}();On.PI_TIMES_2=2*Math.PI,On.PI_OVER_2=Math.PI/2,On.PI_OVER_4=Math.PI/4,On.COUNTERCLOCKWISE=ft.COUNTERCLOCKWISE,On.CLOCKWISE=ft.CLOCKWISE,On.NONE=ft.COLLINEAR;var Rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addNextSegment",value:function(t,e){if(this._s0=this._s1,this._s1=this._s2,this._s2=t,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;var n=ft.index(this._s0,this._s1,this._s2),r=n===ft.CLOCKWISE&&this._side===tt.LEFT||n===ft.COUNTERCLOCKWISE&&this._side===tt.RIGHT;0===n?this.addCollinear(e):r?this.addOutsideTurn(n,e):this.addInsideTurn(n,e)}},{key:"addLineEndCap",value:function(t,e){var n=new bn(t,e),r=new bn;this.computeOffsetSegment(n,tt.LEFT,this._distance,r);var i=new bn;this.computeOffsetSegment(n,tt.RIGHT,this._distance,i);var o=e.x-t.x,s=e.y-t.y,a=Math.atan2(s,o);switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:this._segList.addPt(r.p1),this.addDirectedFillet(e,a+Math.PI/2,a-Math.PI/2,ft.CLOCKWISE,this._distance),this._segList.addPt(i.p1);break;case y.CAP_FLAT:this._segList.addPt(r.p1),this._segList.addPt(i.p1);break;case y.CAP_SQUARE:var u=new z;u.x=Math.abs(this._distance)*Math.cos(a),u.y=Math.abs(this._distance)*Math.sin(a);var l=new z(r.p1.x+u.x,r.p1.y+u.y),h=new z(i.p1.x+u.x,i.p1.y+u.y);this._segList.addPt(l),this._segList.addPt(h)}}},{key:"getCoordinates",value:function(){return this._segList.getCoordinates()}},{key:"addMitreJoin",value:function(t,e,n,r){var i=_t.intersection(e.p0,e.p1,n.p0,n.p1);if(null!==i&&(r<=0?1:i.distance(t)/Math.abs(r))<=this._bufParams.getMitreLimit())return this._segList.addPt(i),null;this.addLimitedMitreJoin(e,n,r,this._bufParams.getMitreLimit())}},{key:"addOutsideTurn",value:function(t,n){if(this._offset0.p1.distance(this._offset1.p0)=h&&(a-=2*Math.PI),this._segList.addPt(e),this.addDirectedFillet(t,a,h,r,i),this._segList.addPt(n)}},{key:"addLastSegment",value:function(){this._segList.addPt(this._offset1.p1)}},{key:"initSideSegments",value:function(t,e,n){this._s1=t,this._s2=e,this._side=n,this._seg1.setCoordinates(t,e),this.computeOffsetSegment(this._seg1,n,this._distance,this._offset1)}},{key:"addLimitedMitreJoin",value:function(t,e,n,r){var i=this._seg0.p1,o=On.angle(i,this._seg0.p0),s=On.angleBetweenOriented(this._seg0.p0,i,this._seg1.p1)/2,a=On.normalize(o+s),u=On.normalize(a+Math.PI),l=r*n,h=n-l*Math.abs(Math.sin(s)),c=i.x+l*Math.cos(u),f=i.y+l*Math.sin(u),g=new z(c,f),p=new bn(i,g),v=p.pointAlongOffset(1,h),d=p.pointAlongOffset(1,-h);this._side===tt.LEFT?(this._segList.addPt(v),this._segList.addPt(d)):(this._segList.addPt(d),this._segList.addPt(v))}},{key:"addDirectedFillet",value:function(t,e,n,r,i){var o=r===ft.CLOCKWISE?-1:1,s=Math.abs(e-n),a=Math.trunc(s/this._filletAngleQuantum+.5);if(a<1)return null;for(var u=s/a,l=new z,h=0;h0){var r=new z((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(r);var i=new z((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(i)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}}},{key:"createCircle",value:function(t){var e=new z(t.x+this._distance,t.y);this._segList.addPt(e),this.addDirectedFillet(t,0,2*Math.PI,-1,this._distance),this._segList.closeRing()}},{key:"addBevelJoin",value:function(t,e){this._segList.addPt(t.p1),this._segList.addPt(e.p0)}},{key:"init",value:function(t){this._distance=t,this._maxCurveSegmentError=t*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new Tn,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(t*e.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)}},{key:"addCollinear",value:function(t){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2),this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===y.JOIN_BEVEL||this._bufParams.getJoinStyle()===y.JOIN_MITRE?(t&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,ft.CLOCKWISE,this._distance))}},{key:"closeRing",value:function(){this._segList.closeRing()}},{key:"hasNarrowConcaveAngle",value:function(){return this._hasNarrowConcaveAngle}}],[{key:"constructor_",value:function(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new bn,this._seg1=new bn,this._offset0=new bn,this._offset1=new bn,this._side=0,this._hasNarrowConcaveAngle=!1;var t=arguments[0],n=arguments[1],r=arguments[2];this._precisionModel=t,this._bufParams=n,this._li=new Ce,this._filletAngleQuantum=Math.PI/2/n.getQuadrantSegments(),n.getQuadrantSegments()>=8&&n.getJoinStyle()===y.JOIN_ROUND&&(this._closingSegLengthFactor=e.MAX_CLOSING_SEG_LEN_FACTOR),this.init(r)}}]),e}();Rn.OFFSET_SEGMENT_SEPARATION_FACTOR=.001,Rn.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR=.001,Rn.CURVE_VERTEX_SNAP_DISTANCE_FACTOR=1e-6,Rn.MAX_CLOSING_SEG_LEN_FACTOR=80;var An=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getOffsetCurve",value:function(t,e){if(this._distance=e,0===e)return null;var n=e<0,r=Math.abs(e),i=this.getSegGen(r);t.length<=1?this.computePointCurve(t[0],i):this.computeOffsetCurve(t,n,i);var o=i.getCoordinates();return n&&Wt.reverse(o),o}},{key:"computeSingleSidedBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){n.addSegments(t,!0);var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{n.addSegments(t,!1);var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment(),n.closeRing()}},{key:"computeRingBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);e===tt.RIGHT&&(r=-r);var i=Cn.simplify(t,r),o=i.length-1;n.initSideSegments(i[o-1],i[0],e);for(var s=1;s<=o;s++){var a=1!==s;n.addNextSegment(i[s],a)}n.closeRing()}},{key:"computeLineBufferCurve",value:function(t,e){var n=this.simplifyTolerance(this._distance),r=Cn.simplify(t,n),i=r.length-1;e.initSideSegments(r[0],r[1],tt.LEFT);for(var o=2;o<=i;o++)e.addNextSegment(r[o],!0);e.addLastSegment(),e.addLineEndCap(r[i-1],r[i]);var s=Cn.simplify(t,-n),a=s.length-1;e.initSideSegments(s[a],s[a-1],tt.LEFT);for(var u=a-2;u>=0;u--)e.addNextSegment(s[u],!0);e.addLastSegment(),e.addLineEndCap(s[1],s[0]),e.closeRing()}},{key:"computePointCurve",value:function(t,e){switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:e.createCircle(t);break;case y.CAP_SQUARE:e.createSquare(t)}}},{key:"getLineCurve",value:function(t,e){if(this._distance=e,this.isLineOffsetEmpty(e))return null;var n=Math.abs(e),r=this.getSegGen(n);if(t.length<=1)this.computePointCurve(t[0],r);else if(this._bufParams.isSingleSided()){var i=e<0;this.computeSingleSidedBufferCurve(t,i,r)}else this.computeLineBufferCurve(t,r);return r.getCoordinates()}},{key:"getBufferParameters",value:function(){return this._bufParams}},{key:"simplifyTolerance",value:function(t){return t*this._bufParams.getSimplifyFactor()}},{key:"getRingCurve",value:function(t,n,r){if(this._distance=r,t.length<=2)return this.getLineCurve(t,r);if(0===r)return e.copyCoordinates(t);var i=this.getSegGen(r);return this.computeRingBufferCurve(t,n,i),i.getCoordinates()}},{key:"computeOffsetCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment()}},{key:"isLineOffsetEmpty",value:function(t){return 0===t||t<0&&!this._bufParams.isSingleSided()}},{key:"getSegGen",value:function(t){return new Rn(this._precisionModel,this._bufParams,t)}}],[{key:"constructor_",value:function(){this._distance=0,this._precisionModel=null,this._bufParams=null;var t=arguments[0],e=arguments[1];this._precisionModel=t,this._bufParams=e}},{key:"copyCoordinates",value:function(t){for(var e=new Array(t.length).fill(null),n=0;ni.getMaxY()||this.findStabbedSegments(t,r.getDirectedEdges(),e)}return e}if(3===arguments.length)if(ot(arguments[2],rt)&&arguments[0]instanceof z&&arguments[1]instanceof Ke){for(var o=arguments[0],s=arguments[1],a=arguments[2],u=s.getEdge().getCoordinates(),l=0;lthis._seg.p1.y&&this._seg.reverse(),!(Math.max(this._seg.p0.x,this._seg.p1.x)this._seg.p1.y||ft.index(this._seg.p0,this._seg.p1,o)===ft.RIGHT)){var h=s.getDepth(tt.LEFT);this._seg.p0.equals(u[l])||(h=s.getDepth(tt.RIGHT));var c=new Fn(this._seg,h);a.add(c)}}else if(ot(arguments[2],rt)&&arguments[0]instanceof z&&ot(arguments[1],rt))for(var f=arguments[0],g=arguments[2],p=arguments[1].iterator();p.hasNext();){var v=p.next();v.isForward()&&this.findStabbedSegments(f,v,g)}}},{key:"getDepth",value:function(t){var e=this.findStabbedSegments(t);return 0===e.size()?0:an.min(e)._leftDepth}}],[{key:"constructor_",value:function(){this._subgraphs=null,this._seg=new bn;var t=arguments[0];this._subgraphs=t}}]),e}(),Fn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var e=t;if(this._upwardSeg.minX()>=e._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=e._upwardSeg.minX())return-1;var n=this._upwardSeg.orientationIndex(e._upwardSeg);return 0!==n||0!=(n=-1*e._upwardSeg.orientationIndex(this._upwardSeg))?n:this._upwardSeg.compareTo(e._upwardSeg)}},{key:"compareX",value:function(t,e){var n=t.p0.compareTo(e.p0);return 0!==n?n:t.p1.compareTo(e.p1)}},{key:"toString",value:function(){return this._upwardSeg.toString()}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._upwardSeg=null,this._leftDepth=null;var t=arguments[0],e=arguments[1];this._upwardSeg=new bn(t),this._leftDepth=e}}]),e}();Dn.DepthSegment=Fn;var qn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){_.constructor_.call(this,"Projective point not representable on the Cartesian plane.")}}]),o}(_),Vn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getY",value:function(){var t=this.y/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getX",value:function(){var t=this.x/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getCoordinate",value:function(){var t=new z;return t.x=this.getX(),t.y=this.getY(),t}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.w=null,0===arguments.length)this.x=0,this.y=0,this.w=1;else if(1===arguments.length){var t=arguments[0];this.x=t.x,this.y=t.y,this.w=1}else if(2===arguments.length){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var n=arguments[0],r=arguments[1];this.x=n,this.y=r,this.w=1}else if(arguments[0]instanceof e&&arguments[1]instanceof e){var i=arguments[0],o=arguments[1];this.x=i.y*o.w-o.y*i.w,this.y=o.x*i.w-i.x*o.w,this.w=i.x*o.y-o.x*i.y}else if(arguments[0]instanceof z&&arguments[1]instanceof z){var s=arguments[0],a=arguments[1];this.x=s.y-a.y,this.y=a.x-s.x,this.w=s.x*a.y-a.x*s.y}}else if(3===arguments.length){var u=arguments[0],l=arguments[1],h=arguments[2];this.x=u,this.y=l,this.w=h}else if(4===arguments.length){var c=arguments[0],f=arguments[1],g=arguments[2],p=arguments[3],v=c.y-f.y,d=f.x-c.x,y=c.x*f.y-f.x*c.y,m=g.y-p.y,_=p.x-g.x,x=g.x*p.y-p.x*g.y;this.x=d*x-_*y,this.y=m*y-v*x,this.w=v*_-m*d}}}]),e}(),Gn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"area",value:function(){return e.area(this.p0,this.p1,this.p2)}},{key:"signedArea",value:function(){return e.signedArea(this.p0,this.p1,this.p2)}},{key:"interpolateZ",value:function(t){if(null===t)throw new x("Supplied point is null.");return e.interpolateZ(t,this.p0,this.p1,this.p2)}},{key:"longestSideLength",value:function(){return e.longestSideLength(this.p0,this.p1,this.p2)}},{key:"isAcute",value:function(){return e.isAcute(this.p0,this.p1,this.p2)}},{key:"circumcentre",value:function(){return e.circumcentre(this.p0,this.p1,this.p2)}},{key:"area3D",value:function(){return e.area3D(this.p0,this.p1,this.p2)}},{key:"centroid",value:function(){return e.centroid(this.p0,this.p1,this.p2)}},{key:"inCentre",value:function(){return e.inCentre(this.p0,this.p1,this.p2)}}],[{key:"constructor_",value:function(){this.p0=null,this.p1=null,this.p2=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.p0=t,this.p1=e,this.p2=n}},{key:"area",value:function(t,e,n){return Math.abs(((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2)}},{key:"signedArea",value:function(t,e,n){return((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2}},{key:"det",value:function(t,e,n,r){return t*r-e*n}},{key:"interpolateZ",value:function(t,e,n,r){var i=e.x,o=e.y,s=n.x-i,a=r.x-i,u=n.y-o,l=r.y-o,h=s*l-a*u,c=t.x-i,f=t.y-o,g=(l*c-a*f)/h,p=(-u*c+s*f)/h;return e.getZ()+g*(n.getZ()-e.getZ())+p*(r.getZ()-e.getZ())}},{key:"longestSideLength",value:function(t,e,n){var r=t.distance(e),i=e.distance(n),o=n.distance(t),s=r;return i>s&&(s=i),o>s&&(s=o),s}},{key:"circumcentreDD",value:function(t,e,n){var r=lt.valueOf(t.x).subtract(n.x),i=lt.valueOf(t.y).subtract(n.y),o=lt.valueOf(e.x).subtract(n.x),s=lt.valueOf(e.y).subtract(n.y),a=lt.determinant(r,i,o,s).multiply(2),u=r.sqr().add(i.sqr()),l=o.sqr().add(s.sqr()),h=lt.determinant(i,u,s,l),c=lt.determinant(r,u,o,l),f=lt.valueOf(n.x).subtract(h.divide(a)).doubleValue(),g=lt.valueOf(n.y).add(c.divide(a)).doubleValue();return new z(f,g)}},{key:"isAcute",value:function(t,e,n){return!!On.isAcute(t,e,n)&&!!On.isAcute(e,n,t)&&!!On.isAcute(n,t,e)}},{key:"circumcentre",value:function(t,n,r){var i=r.x,o=r.y,s=t.x-i,a=t.y-o,u=n.x-i,l=n.y-o,h=2*e.det(s,a,u,l),c=e.det(a,s*s+a*a,l,u*u+l*l),f=e.det(s,s*s+a*a,u,u*u+l*l);return new z(i-c/h,o+f/h)}},{key:"perpendicularBisector",value:function(t,e){var n=e.x-t.x,r=e.y-t.y,i=new Vn(t.x+n/2,t.y+r/2,1),o=new Vn(t.x-r+n/2,t.y+n+r/2,1);return new Vn(i,o)}},{key:"angleBisector",value:function(t,e,n){var r=e.distance(t),i=r/(r+e.distance(n)),o=n.x-t.x,s=n.y-t.y;return new z(t.x+i*o,t.y+i*s)}},{key:"area3D",value:function(t,e,n){var r=e.x-t.x,i=e.y-t.y,o=e.getZ()-t.getZ(),s=n.x-t.x,a=n.y-t.y,u=n.getZ()-t.getZ(),l=i*u-o*a,h=o*s-r*u,c=r*a-i*s,f=l*l+h*h+c*c;return Math.sqrt(f)/2}},{key:"centroid",value:function(t,e,n){var r=(t.x+e.x+n.x)/3,i=(t.y+e.y+n.y)/3;return new z(r,i)}},{key:"inCentre",value:function(t,e,n){var r=e.distance(n),i=t.distance(n),o=t.distance(e),s=r+i+o,a=(r*t.x+i*e.x+o*n.x)/s,u=(r*t.y+i*e.y+o*n.y)/s;return new z(a,u)}}]),e}(),Bn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addRingSide",value:function(t,e,n,r,i){if(0===e&&t.length=zt.MINIMUM_VALID_SIZE&&ft.isCCW(t)&&(o=i,s=r,n=tt.opposite(n));var a=this._curveBuilder.getRingCurve(t,n,e);this.addCurve(a,o,s)}},{key:"addRingBothSides",value:function(t,e){this.addRingSide(t,e,tt.LEFT,Z.EXTERIOR,Z.INTERIOR),this.addRingSide(t,e,tt.RIGHT,Z.INTERIOR,Z.EXTERIOR)}},{key:"addPoint",value:function(t){if(this._distance<=0)return null;var e=t.getCoordinates(),n=this._curveBuilder.getLineCurve(e,this._distance);this.addCurve(n,Z.EXTERIOR,Z.INTERIOR)}},{key:"addPolygon",value:function(t){var e=this._distance,n=tt.LEFT;this._distance<0&&(e=-this._distance,n=tt.RIGHT);var r=t.getExteriorRing(),i=Wt.removeRepeatedPoints(r.getCoordinates());if(this._distance<0&&this.isErodedCompletely(r,this._distance))return null;if(this._distance<=0&&i.length<3)return null;this.addRingSide(i,e,n,Z.EXTERIOR,Z.INTERIOR);for(var o=0;o0&&this.isErodedCompletely(s,-this._distance)||this.addRingSide(a,e,tt.opposite(n),Z.INTERIOR,Z.EXTERIOR)}}},{key:"isTriangleErodedCompletely",value:function(t,e){var n=new Gn(t[0],t[1],t[2]),r=n.inCentre();return kt.pointToSegment(r,n.p0,n.p1)i}},{key:"addCollection",value:function(t){for(var e=0;e=this._max)throw new W;var t=this._parent.getGeometryN(this._index++);return t instanceof Bt?(this._subcollectionIterator=new e(t),this._subcollectionIterator.next()):t}},{key:"remove",value:function(){throw new J(this.getClass().getName())}},{key:"hasNext",value:function(){if(this._atStart)return!0;if(null!==this._subcollectionIterator){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)}},{key:"interfaces_",get:function(){return[yn]}}],[{key:"constructor_",value:function(){this._parent=null,this._atStart=null,this._max=null,this._index=null,this._subcollectionIterator=null;var t=arguments[0];this._parent=t,this._atStart=!0,this._index=0,this._max=t.getNumGeometries()}},{key:"isAtomic",value:function(t){return!(t instanceof Bt)}}]),e}(),jn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"locate",value:function(t){return e.locate(t,this._geom)}},{key:"interfaces_",get:function(){return[Yn]}}],[{key:"constructor_",value:function(){this._geom=null;var t=arguments[0];this._geom=t}},{key:"locatePointInPolygon",value:function(t,n){if(n.isEmpty())return Z.EXTERIOR;var r=n.getExteriorRing(),i=e.locatePointInRing(t,r);if(i!==Z.INTERIOR)return i;for(var o=0;o=0;n--){var r=this._edgeList.get(n),i=r.getSym();null===e&&(e=i),null!==t&&i.setNext(t),t=r}e.setNext(t)}},{key:"computeDepths",value:function(){if(1===arguments.length){var t=arguments[0],e=this.findIndex(t),n=t.getDepth(tt.LEFT),r=t.getDepth(tt.RIGHT),i=this.computeDepths(e+1,this._edgeList.size(),n);if(this.computeDepths(0,e,i)!==r)throw new pt("depth mismatch at "+t.getCoordinate())}else if(3===arguments.length){for(var o=arguments[1],s=arguments[2],a=arguments[0];a=0;i--){var o=this._resultAreaEdgeList.get(i),s=o.getSym();switch(null===e&&o.getEdgeRing()===t&&(e=o),r){case this._SCANNING_FOR_INCOMING:if(s.getEdgeRing()!==t)continue;n=s,r=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(o.getEdgeRing()!==t)continue;n.setNextMin(o),r=this._SCANNING_FOR_INCOMING}}r===this._LINKING_TO_OUTGOING&&(V.isTrue(null!==e,"found null for first outgoing dirEdge"),V.isTrue(e.getEdgeRing()===t,"unable to link last incoming dirEdge"),n.setNextMin(e))}},{key:"getOutgoingDegree",value:function(){if(0===arguments.length){for(var t=0,e=this.iterator();e.hasNext();)e.next().isInResult()&&t++;return t}if(1===arguments.length){for(var n=arguments[0],r=0,i=this.iterator();i.hasNext();)i.next().getEdgeRing()===n&&r++;return r}}},{key:"getLabel",value:function(){return this._label}},{key:"findCoveredLineEdges",value:function(){for(var t=Z.NONE,e=this.iterator();e.hasNext();){var n=e.next(),r=n.getSym();if(!n.isLineEdge()){if(n.isInResult()){t=Z.INTERIOR;break}if(r.isInResult()){t=Z.EXTERIOR;break}}}if(t===Z.NONE)return null;for(var i=t,o=this.iterator();o.hasNext();){var s=o.next(),a=s.getSym();s.isLineEdge()?s.getEdge().setCovered(i===Z.INTERIOR):(s.isInResult()&&(i=Z.EXTERIOR),a.isInResult()&&(i=Z.INTERIOR))}}},{key:"computeLabelling",value:function(t){f(i(s.prototype),"computeLabelling",this).call(this,t),this._label=new Ae(Z.NONE);for(var e=this.iterator();e.hasNext();)for(var n=e.next().getEdge().getLabel(),r=0;r<2;r++){var o=n.getLocation(r);o!==Z.INTERIOR&&o!==Z.BOUNDARY||this._label.setLocation(r,Z.INTERIOR)}}}],[{key:"constructor_",value:function(){this._resultAreaEdgeList=null,this._label=null,this._SCANNING_FOR_INCOMING=1,this._LINKING_TO_OUTGOING=2}}]),s}(Xn),Zn=function(e){r(o,e);var i=c(o);function o(){return t(this,o),i.call(this)}return n(o,[{key:"createNode",value:function(t){return new Ge(t,new Un)}}]),o}(Qe),Hn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var n=t;return e.compareOriented(this._pts,this._orientation,n._pts,n._orientation)}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._pts=null,this._orientation=null;var t=arguments[0];this._pts=t,this._orientation=e.orientation(t)}},{key:"orientation",value:function(t){return 1===Wt.increasingDirection(t)}},{key:"compareOriented",value:function(t,e,n,r){for(var i=e?1:-1,o=r?1:-1,s=e?t.length:-1,a=r?n.length:-1,u=e?0:t.length-1,l=r?0:n.length-1;;){var h=t[u].compareTo(n[l]);if(0!==h)return h;var c=(u+=i)===s,f=(l+=o)===a;if(c&&!f)return-1;if(!c&&f)return 1;if(c&&f)return 0}}}]),e}(),Wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.print("MULTILINESTRING ( ");for(var e=0;e0&&t.print(","),t.print("(");for(var r=n.getCoordinates(),i=0;i0&&t.print(","),t.print(r[i].x+" "+r[i].y);t.println(")")}t.print(") ")}},{key:"addAll",value:function(t){for(var e=t.iterator();e.hasNext();)this.add(e.next())}},{key:"findEdgeIndex",value:function(t){for(var e=0;et?1:this.diste?1:0}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this.coord=null,this.segmentIndex=null,this.dist=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.coord=new z(t),this.segmentIndex=e,this.dist=n}}]),e}(),$n=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this._nodeMap.values().iterator()}},{key:"addSplitEdges",value:function(t){this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next(),i=this.createSplitEdge(n,r);t.add(i),n=r}}},{key:"addEndpoints",value:function(){var t=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[t],t,0)}},{key:"createSplitEdge",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2,r=this.edge.pts[e.segmentIndex],i=e.dist>0||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this.edge.pts[a];return i&&(o[s]=e.coord),new or(o,new Ae(this.edge._label))}},{key:"add",value:function(t,e,n){var r=new Qn(t,e,n),i=this._nodeMap.get(r);return null!==i?i:(this._nodeMap.put(r,r),r)}},{key:"isIntersection",value:function(t){for(var e=this.iterator();e.hasNext();)if(e.next().coord.equals(t))return!0;return!1}}],[{key:"constructor_",value:function(){this._nodeMap=new Ze,this.edge=null;var t=arguments[0];this.edge=t}}]),e}(),tr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isIntersects",value:function(){return!this.isDisjoint()}},{key:"isCovers",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"isCoveredBy",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"set",value:function(){if(1===arguments.length)for(var t=arguments[0],e=0;e=0&&e>=0&&this.setAtLeast(t,e,n)}},{key:"isWithin",value:function(){return e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"isTouches",value:function(t,n){return t>n?this.isTouches(n,t):(t===Mt.A&&n===Mt.A||t===Mt.L&&n===Mt.L||t===Mt.L&&n===Mt.A||t===Mt.P&&n===Mt.A||t===Mt.P&&n===Mt.L)&&this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&(e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))}},{key:"isOverlaps",value:function(t,n){return t===Mt.P&&n===Mt.P||t===Mt.A&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&1===this._matrix[Z.INTERIOR][Z.INTERIOR]&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR])}},{key:"isEquals",value:function(t,n){return t===n&&e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"toString",value:function(){for(var t=new Qt("123456789"),e=0;e<3;e++)for(var n=0;n<3;n++)t.setCharAt(3*e+n,Mt.toDimensionSymbol(this._matrix[e][n]));return t.toString()}},{key:"setAll",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this._matrix[e][n]=t}},{key:"get",value:function(t,e){return this._matrix[t][e]}},{key:"transpose",value:function(){var t=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=t,t=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=t,t=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=t,this}},{key:"matches",value:function(t){if(9!==t.length)throw new x("Should be length 9: "+t);for(var n=0;n<3;n++)for(var r=0;r<3;r++)if(!e.matches(this._matrix[n][r],t.charAt(3*n+r)))return!1;return!0}},{key:"add",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this.setAtLeast(e,n,t.get(e,n))}},{key:"isDisjoint",value:function(){return this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.INTERIOR][Z.BOUNDARY]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.BOUNDARY]===Mt.FALSE}},{key:"isCrosses",value:function(t,n){return t===Mt.P&&n===Mt.L||t===Mt.P&&n===Mt.A||t===Mt.L&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR]):t===Mt.L&&n===Mt.P||t===Mt.A&&n===Mt.P||t===Mt.A&&n===Mt.L?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&0===this._matrix[Z.INTERIOR][Z.INTERIOR]}},{key:"interfaces_",get:function(){return[b]}}],[{key:"constructor_",value:function(){if(this._matrix=null,0===arguments.length)this._matrix=Array(3).fill().map((function(){return Array(3)})),this.setAll(Mt.FALSE);else if(1===arguments.length)if("string"==typeof arguments[0]){var t=arguments[0];e.constructor_.call(this),this.set(t)}else if(arguments[0]instanceof e){var n=arguments[0];e.constructor_.call(this),this._matrix[Z.INTERIOR][Z.INTERIOR]=n._matrix[Z.INTERIOR][Z.INTERIOR],this._matrix[Z.INTERIOR][Z.BOUNDARY]=n._matrix[Z.INTERIOR][Z.BOUNDARY],this._matrix[Z.INTERIOR][Z.EXTERIOR]=n._matrix[Z.INTERIOR][Z.EXTERIOR],this._matrix[Z.BOUNDARY][Z.INTERIOR]=n._matrix[Z.BOUNDARY][Z.INTERIOR],this._matrix[Z.BOUNDARY][Z.BOUNDARY]=n._matrix[Z.BOUNDARY][Z.BOUNDARY],this._matrix[Z.BOUNDARY][Z.EXTERIOR]=n._matrix[Z.BOUNDARY][Z.EXTERIOR],this._matrix[Z.EXTERIOR][Z.INTERIOR]=n._matrix[Z.EXTERIOR][Z.INTERIOR],this._matrix[Z.EXTERIOR][Z.BOUNDARY]=n._matrix[Z.EXTERIOR][Z.BOUNDARY],this._matrix[Z.EXTERIOR][Z.EXTERIOR]=n._matrix[Z.EXTERIOR][Z.EXTERIOR]}}},{key:"matches",value:function(){if(Number.isInteger(arguments[0])&&"string"==typeof arguments[1]){var t=arguments[0],n=arguments[1];return n===Mt.SYM_DONTCARE||n===Mt.SYM_TRUE&&(t>=0||t===Mt.TRUE)||n===Mt.SYM_FALSE&&t===Mt.FALSE||n===Mt.SYM_P&&t===Mt.P||n===Mt.SYM_L&&t===Mt.L||n===Mt.SYM_A&&t===Mt.A}if("string"==typeof arguments[0]&&"string"==typeof arguments[1]){var r=arguments[1];return new e(arguments[0]).matches(r)}}},{key:"isTrue",value:function(t){return t>=0||t===Mt.TRUE}}]),e}(),er=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"size",value:function(){return this._size}},{key:"addAll",value:function(t){return null===t||0===t.length?null:(this.ensureCapacity(this._size+t.length),xt.arraycopy(t,0,this._data,this._size,t.length),void(this._size+=t.length))}},{key:"ensureCapacity",value:function(t){if(t<=this._data.length)return null;var e=Math.max(t,2*this._data.length);this._data=At.copyOf(this._data,e)}},{key:"toArray",value:function(){var t=new Array(this._size).fill(null);return xt.arraycopy(this._data,0,t,0,this._size),t}},{key:"add",value:function(t){this.ensureCapacity(this._size+1),this._data[this._size]=t,++this._size}}],[{key:"constructor_",value:function(){if(this._data=null,this._size=0,0===arguments.length)e.constructor_.call(this,10);else if(1===arguments.length){var t=arguments[0];this._data=new Array(t).fill(null)}}}]),e}(),nr=function(){function e(){t(this,e)}return n(e,[{key:"getChainStartIndices",value:function(t){var e=0,n=new er(Math.trunc(t.length/2));n.add(e);do{var r=this.findChainEnd(t,e);n.add(r),e=r}while(en?e:n}},{key:"getMinX",value:function(t){var e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return ee&&(r=1),this._depth[t][n]=r}}}},{key:"getDelta",value:function(t){return this._depth[t][tt.RIGHT]-this._depth[t][tt.LEFT]}},{key:"getLocation",value:function(t,e){return this._depth[t][e]<=0?Z.EXTERIOR:Z.INTERIOR}},{key:"toString",value:function(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}},{key:"add",value:function(){if(1===arguments.length)for(var t=arguments[0],n=0;n<2;n++)for(var r=1;r<3;r++){var i=t.getLocation(n,r);i!==Z.EXTERIOR&&i!==Z.INTERIOR||(this.isNull(n,r)?this._depth[n][r]=e.depthAtLocation(i):this._depth[n][r]+=e.depthAtLocation(i))}else if(3===arguments.length){var o=arguments[0],s=arguments[1];arguments[2]===Z.INTERIOR&&this._depth[o][s]++}}}],[{key:"constructor_",value:function(){this._depth=Array(2).fill().map((function(){return Array(3)}));for(var t=0;t<2;t++)for(var n=0;n<3;n++)this._depth[t][n]=e.NULL_VALUE}},{key:"depthAtLocation",value:function(t){return t===Z.EXTERIOR?0:t===Z.INTERIOR?1:e.NULL_VALUE}}]),e}();ir.NULL_VALUE=-1;var or=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getDepth",value:function(){return this._depth}},{key:"getCollapsedEdge",value:function(){var t=new Array(2).fill(null);return t[0]=this.pts[0],t[1]=this.pts[1],new s(t,Ae.toLineLabel(this._label))}},{key:"isIsolated",value:function(){return this._isIsolated}},{key:"getCoordinates",value:function(){return this.pts}},{key:"setIsolated",value:function(t){this._isIsolated=t}},{key:"setName",value:function(t){this._name=t}},{key:"equals",value:function(t){if(!(t instanceof s))return!1;var e=t;if(this.pts.length!==e.pts.length)return!1;for(var n=!0,r=!0,i=this.pts.length,o=0;o0?this.pts[0]:null;if(1===arguments.length){var t=arguments[0];return this.pts[t]}}},{key:"print",value:function(t){t.print("edge "+this._name+": "),t.print("LINESTRING (");for(var e=0;e0&&t.print(","),t.print(this.pts[e].x+" "+this.pts[e].y);t.print(") "+this._label+" "+this._depthDelta)}},{key:"computeIM",value:function(t){s.updateIM(this._label,t)}},{key:"isCollapsed",value:function(){return!!this._label.isArea()&&3===this.pts.length&&!!this.pts[0].equals(this.pts[2])}},{key:"isClosed",value:function(){return this.pts[0].equals(this.pts[this.pts.length-1])}},{key:"getMaximumSegmentIndex",value:function(){return this.pts.length-1}},{key:"getDepthDelta",value:function(){return this._depthDelta}},{key:"getNumPoints",value:function(){return this.pts.length}},{key:"printReverse",value:function(t){t.print("edge "+this._name+": ");for(var e=this.pts.length-1;e>=0;e--)t.print(this.pts[e]+" ");t.println("")}},{key:"getMonotoneChainEdge",value:function(){return null===this._mce&&(this._mce=new rr(this)),this._mce}},{key:"getEnvelope",value:function(){if(null===this._env){this._env=new X;for(var t=0;t0&&t.append(","),t.append(this.pts[e].x+" "+this.pts[e].y);return t.append(") "+this._label+" "+this._depthDelta),t.toString()}},{key:"isPointwiseEqual",value:function(t){if(this.pts.length!==t.pts.length)return!1;for(var e=0;er||this._maxyo;if(s)return!1;var a=this.intersectsToleranceSquare(t,e);return V.isTrue(!(s&&a),"Found bad envelope test"),a}},{key:"initCorners",value:function(t){var e=.5;this._minx=t.x-e,this._maxx=t.x+e,this._miny=t.y-e,this._maxy=t.y+e,this._corner[0]=new z(this._maxx,this._maxy),this._corner[1]=new z(this._minx,this._maxy),this._corner[2]=new z(this._minx,this._miny),this._corner[3]=new z(this._maxx,this._miny)}},{key:"intersects",value:function(t,e){return 1===this._scaleFactor?this.intersectsScaled(t,e):(this.copyScaled(t,this._p0Scaled),this.copyScaled(e,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}},{key:"scale",value:function(t){return Math.round(t*this._scaleFactor)}},{key:"getCoordinate",value:function(){return this._originalPt}},{key:"copyScaled",value:function(t,e){e.x=this.scale(t.x),e.y=this.scale(t.y)}},{key:"getSafeEnvelope",value:function(){if(null===this._safeEnv){var t=e.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new X(this._originalPt.x-t,this._originalPt.x+t,this._originalPt.y-t,this._originalPt.y+t)}return this._safeEnv}},{key:"intersectsPixelClosure",value:function(t,e){return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.hasIntersection()))))}},{key:"intersectsToleranceSquare",value:function(t,e){var n=!1,r=!1;return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.isProper()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.isProper()||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.isProper()||(this._li.hasIntersection()&&(r=!0),this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.isProper()||n&&r||t.equals(this._pt)||e.equals(this._pt)))))}},{key:"addSnappedNode",value:function(t,e){var n=t.getCoordinate(e),r=t.getCoordinate(e+1);return!!this.intersects(n,r)&&(t.addIntersection(this.getCoordinate(),e),!0)}}],[{key:"constructor_",value:function(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;var t=arguments[0],e=arguments[1],n=arguments[2];if(this._originalPt=t,this._pt=t,this._scaleFactor=e,this._li=n,e<=0)throw new x("Scale factor must be non-zero");1!==e&&(this._pt=new z(this.scale(t.x),this.scale(t.y)),this._p0Scaled=new z,this._p1Scaled=new z),this.initCorners(this._pt)}}]),e}();lr.SAFE_ENV_EXPANSION_FACTOR=.75;var hr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"select",value:function(){if(1===arguments.length);else if(2===arguments.length){var t=arguments[1];arguments[0].getLineSegment(t,this.selectedSegment),this.select(this.selectedSegment)}}}],[{key:"constructor_",value:function(){this.selectedSegment=new bn}}]),e}(),cr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"snap",value:function(){if(1===arguments.length){var e=arguments[0];return this.snap(e,null,-1)}if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=r.getSafeEnvelope(),a=new fr(r,i,o);return this._index.query(s,new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[hn]}},{key:"visitItem",value:function(t){t.select(s,a)}}]),e}())),a.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var t=arguments[0];this._index=t}}]),e}(),fr=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isNodeAdded",value:function(){return this._isNodeAdded}},{key:"select",value:function(){if(!(2===arguments.length&&Number.isInteger(arguments[1])&&arguments[0]instanceof In))return f(i(s.prototype),"select",this).apply(this,arguments);var t=arguments[1],e=arguments[0].getContext();if(this._parentEdge===e&&(t===this._hotPixelVertexIndex||t+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(e,t)}}],[{key:"constructor_",value:function(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var t=arguments[0],e=arguments[1],n=arguments[2];this._hotPixel=t,this._parentEdge=e,this._hotPixelVertexIndex=n}}]),s}(hr);cr.HotPixelSnapAction=fr;var gr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"processIntersections",value:function(t,e,n,r){if(t===n&&e===r)return null;var i=t.getCoordinates()[e],o=t.getCoordinates()[e+1],s=n.getCoordinates()[r],a=n.getCoordinates()[r+1];if(this._li.computeIntersection(i,o,s,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var u=0;u=0;t--){try{this.bufferReducedPrecision(t)}catch(t){if(!(t instanceof pt))throw t;this._saveException=t}if(null!==this._resultGeometry)return null}throw this._saveException}if(1===arguments.length){var n=arguments[0],r=e.precisionScaleFactor(this._argGeom,this._distance,n),i=new ie(r);this.bufferFixedPrecision(i)}}},{key:"computeGeometry",value:function(){if(this.bufferOriginalPrecision(),null!==this._resultGeometry)return null;var t=this._argGeom.getFactory().getPrecisionModel();t.getType()===ie.FIXED?this.bufferFixedPrecision(t):this.bufferReducedPrecision()}},{key:"setQuadrantSegments",value:function(t){this._bufParams.setQuadrantSegments(t)}},{key:"bufferOriginalPrecision",value:function(){try{var t=new sr(this._bufParams);this._resultGeometry=t.buffer(this._argGeom,this._distance)}catch(t){if(!(t instanceof F))throw t;this._saveException=t}}},{key:"getResultGeometry",value:function(t){return this._distance=t,this.computeGeometry(),this._resultGeometry}},{key:"setEndCapStyle",value:function(t){this._bufParams.setEndCapStyle(t)}}],[{key:"constructor_",value:function(){if(this._argGeom=null,this._distance=null,this._bufParams=new y,this._resultGeometry=null,this._saveException=null,1===arguments.length){var t=arguments[0];this._argGeom=t}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this._argGeom=e,this._bufParams=n}}},{key:"bufferOp",value:function(){if(2===arguments.length){var t=arguments[1];return new e(arguments[0]).getResultGeometry(t)}if(3===arguments.length){if(Number.isInteger(arguments[2])&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var n=arguments[1],r=arguments[2],i=new e(arguments[0]);return i.setQuadrantSegments(r),i.getResultGeometry(n)}if(arguments[2]instanceof y&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var o=arguments[1];return new e(arguments[0],arguments[2]).getResultGeometry(o)}}else if(4===arguments.length){var s=arguments[1],a=arguments[2],u=arguments[3],l=new e(arguments[0]);return l.setQuadrantSegments(a),l.setEndCapStyle(u),l.getResultGeometry(s)}}},{key:"precisionScaleFactor",value:function(t,e,n){var r=t.getEnvelopeInternal(),i=Et.max(Math.abs(r.getMaxX()),Math.abs(r.getMaxY()),Math.abs(r.getMinX()),Math.abs(r.getMinY()))+2*(e>0?e:0),o=n-Math.trunc(Math.log(i)/Math.log(10)+1);return Math.pow(10,o)}}]),e}();vr.CAP_ROUND=y.CAP_ROUND,vr.CAP_BUTT=y.CAP_FLAT,vr.CAP_FLAT=y.CAP_FLAT,vr.CAP_SQUARE=y.CAP_SQUARE,vr.MAX_PRECISION_DIGITS=12;var dr=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],yr=function(){function e(n){t(this,e),this.geometryFactory=n||new ae}return n(e,[{key:"read",value:function(t){var e,n=(e="string"==typeof t?JSON.parse(t):t).type;if(!mr[n])throw new Error("Unknown GeoJSON type: "+e.type);return-1!==dr.indexOf(n)?mr[n].call(this,e.coordinates):"GeometryCollection"===n?mr[n].call(this,e.geometries):mr[n].call(this,e)}},{key:"write",value:function(t){var e=t.getGeometryType();if(!_r[e])throw new Error("Geometry is not supported");return _r[e].call(this,t)}}]),e}(),mr={Feature:function(t){var e={};for(var n in t)e[n]=t[n];if(t.geometry){var r=t.geometry.type;if(!mr[r])throw new Error("Unknown GeoJSON type: "+t.type);e.geometry=this.read(t.geometry)}return t.bbox&&(e.bbox=mr.bbox.call(this,t.bbox)),e},FeatureCollection:function(t){var e={};if(t.features){e.features=[];for(var n=0;n1?0:t<-1?Xn:Math.acos(t)}function ir(t){return t>1?Un:t<-1?-Un:Math.asin(t)}function or(){}function sr(t,e){t&&ur.hasOwnProperty(t.type)&&ur[t.type](t,e)}var ar={Feature:function(t,e){sr(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++rXn?t-Hn:t<-Xn?t+Hn:t,e]}function xr(t){return function(e,n){return[(e+=t)>Xn?e-Hn:e<-Xn?e+Hn:e,n]}}function Er(t){var e=xr(t);return e.invert=xr(-t),e}function kr(t,e){var n=tr(t),r=er(t),i=tr(e),o=er(e);function s(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*n+a*r;return[$n(u*i-h*o,a*n-l*r),ir(h*i+u*o)]}return s.invert=function(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*i-u*o;return[$n(u*i+l*o,a*n+h*r),ir(h*n-a*r)]},s}function br(t,e){(e=fr(e))[0]-=t,yr(e);var n=rr(-e[1]);return((-e[2]<0?-n:n)+Hn-jn)%Hn}function wr(){var t,e=[];return{point:function(e,n){t.push([e,n])},lineStart:function(){e.push(t=[])},lineEnd:or,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function Ir(t,e){return Kn(t[0]-e[0])=0;--o)i.point((h=l[o])[0],h[1]);else r(f.x,f.p.x,-1,i);f=f.p}l=(f=f.o).z,g=!g}while(!f.v);i.lineEnd()}}}function Mr(t){if(e=t.length){for(var e,n,r=0,i=t[0];++re?1:t>=e?0:NaN}function Pr(t){for(var e,n,r,i=t.length,o=-1,s=0;++o=0;)for(e=(r=t[i]).length;--e>=0;)n[--s]=r[e];return n}Gn(),Gn(),Gn(),_r.invert=_r,function(t){var e;1===t.length&&(e=t,t=function(t,n){return Lr(e(t),n)})}(Lr);var Cr=1e9,Tr=-Cr;function Or(t,e,n,r){function i(i,o){return t<=i&&i<=n&&e<=o&&o<=r}function o(i,o,a,l){var h=0,c=0;if(null==i||(h=s(i,a))!==(c=s(o,a))||u(i,o)<0^a>0)do{l.point(0===h||3===h?t:n,h>1?r:e)}while((h=(h+a+4)%4)!==c);else l.point(o[0],o[1])}function s(r,i){return Kn(r[0]-t)0?0:3:Kn(r[0]-n)0?2:1:Kn(r[1]-e)0?1:0:i>0?3:2}function a(t,e){return u(t.x,e.x)}function u(t,e){var n=s(t,1),r=s(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){var u,l,h,c,f,g,p,v,d,y,m,_=s,x=wr(),E={point:k,lineStart:function(){E.point=b,l&&l.push(h=[]);y=!0,d=!1,p=v=NaN},lineEnd:function(){u&&(b(c,f),g&&d&&x.rejoin(),u.push(x.result()));E.point=k,d&&_.lineEnd()},polygonStart:function(){_=x,u=[],l=[],m=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,i=l.length;nr&&(f-o)*(r-s)>(g-s)*(t-o)&&++e:g<=r&&(f-o)*(r-s)<(g-s)*(t-o)&&--e;return e}(),n=m&&e,i=(u=Pr(u)).length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),o(null,null,1,s),s.lineEnd()),i&&Sr(u,a,e,o,s),s.polygonEnd());_=s,u=l=h=null}};function k(t,e){i(t,e)&&_.point(t,e)}function b(o,s){var a=i(o,s);if(l&&h.push([o,s]),y)c=o,f=s,g=a,y=!1,a&&(_.lineStart(),_.point(o,s));else if(a&&d)_.point(o,s);else{var u=[p=Math.max(Tr,Math.min(Cr,p)),v=Math.max(Tr,Math.min(Cr,v))],x=[o=Math.max(Tr,Math.min(Cr,o)),s=Math.max(Tr,Math.min(Cr,s))];!function(t,e,n,r,i,o){var s,a=t[0],u=t[1],l=0,h=1,c=e[0]-a,f=e[1]-u;if(s=n-a,c||!(s>0)){if(s/=c,c<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=i-a,c||!(s<0)){if(s/=c,c<0){if(s>h)return;s>l&&(l=s)}else if(c>0){if(s0)){if(s/=f,f<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=o-u,f||!(s<0)){if(s/=f,f<0){if(s>h)return;s>l&&(l=s)}else if(f>0){if(s0&&(t[0]=a+l*c,t[1]=u+l*f),h<1&&(e[0]=a+h*c,e[1]=u+h*f),!0}}}}}(u,x,t,e,n,r)?a&&(_.lineStart(),_.point(o,s),m=!1):(d||(_.lineStart(),_.point(u[0],u[1])),_.point(x[0],x[1]),a||_.lineEnd(),m=!1)}p=o,v=s,d=a}return E}}var Rr=Gn();function Ar(t){return t}Gn(),Gn(),Gn();var Dr=1/0,Fr=Dr,qr=-Dr,Vr=qr,Gr={point:function(t,e){tqr&&(qr=t);eVr&&(Vr=e)},lineStart:or,lineEnd:or,polygonStart:or,polygonEnd:or,result:function(){var t=[[Dr,Fr],[qr,Vr]];return qr=Vr=-(Fr=Dr=1/0),t}};function Br(t,e,n,r){return function(i,o){var s,a,u,l=e(o),h=i.invert(r[0],r[1]),c=wr(),f=e(c),g=!1,p={point:v,lineStart:y,lineEnd:m,polygonStart:function(){p.point=_,p.lineStart=x,p.lineEnd=E,a=[],s=[]},polygonEnd:function(){p.point=v,p.lineStart=y,p.lineEnd=m,a=Pr(a);var t=function(t,e){var n=e[0],r=e[1],i=[er(n),-tr(n),0],o=0,s=0;Rr.reset();for(var a=0,u=t.length;a=0?1:-1,w=b*k,I=w>Xn,N=p*x;if(Rr.add($n(N*b*er(w),v*E+N*tr(w))),o+=I?k+b*Hn:k,I^f>=n^m>=n){var S=pr(fr(c),fr(y));yr(S);var M=pr(i,S);yr(M);var L=(I^k>=0?-1:1)*ir(M[2]);(r>L||r===L&&(S[0]||S[1]))&&(s+=I^k>=0?1:-1)}}return(o<-jn||o0){for(g||(o.polygonStart(),g=!0),o.lineStart(),t=0;t1&&2&i&&l.push(l.pop().concat(l.shift())),a.push(l.filter(Yr))}return p}}function Yr(t){return t.length>1}function zr(t,e){return((t=t.x)[0]<0?t[1]-Un-jn:Un-t[1])-((e=e.x)[0]<0?e[1]-Un-jn:Un-e[1])}Gn();var jr=Br((function(){return!0}),(function(t){var e,n=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,s){var a=o>0?Xn:-Xn,u=Kn(o-n);Kn(u-Xn)0?Un:-Un),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),e=0):i!==a&&u>=Xn&&(Kn(n-i)jn?Qn((er(e)*(o=tr(r))*er(n)-er(r)*(i=tr(e))*er(t))/(i*o*s)):(e+r)/2}(n,r,o,s),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),e=0),t.point(n=o,r=s),i=a},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var i;if(null==t)i=n*Un,r.point(-Xn,i),r.point(0,i),r.point(Xn,i),r.point(Xn,0),r.point(Xn,-i),r.point(0,-i),r.point(-Xn,-i),r.point(-Xn,0),r.point(-Xn,i);else if(Kn(t[0]-e[0])>jn){var o=t[0]0,i=Kn(n)>jn;function o(t,e){return tr(t)*tr(e)>n}function s(t,e,r){var i=[1,0,0],o=pr(fr(t),fr(e)),s=gr(o,o),a=o[0],u=s-a*a;if(!u)return!r&&t;var l=n*s/u,h=-n*a/u,c=pr(i,o),f=dr(i,l);vr(f,dr(o,h));var g=c,p=gr(f,g),v=gr(g,g),d=p*p-v*(gr(f,f)-1);if(!(d<0)){var y=nr(d),m=dr(g,(-p-y)/v);if(vr(m,f),m=cr(m),!r)return m;var _,x=t[0],E=e[0],k=t[1],b=e[1];E0^m[1]<(Kn(m[0]-x)Xn^(x<=m[0]&&m[0]<=E)){var N=dr(g,(-p+y)/v);return vr(N,f),[m,cr(N)]}}}function a(e,n){var i=r?t:Xn-t,o=0;return e<-i?o|=1:e>i&&(o|=2),n<-i?o|=4:n>i&&(o|=8),o}return Br(o,(function(t){var e,n,u,l,h;return{lineStart:function(){l=u=!1,h=1},point:function(c,f){var g,p=[c,f],v=o(c,f),d=r?v?0:a(c,f):v?a(c+(c<0?Xn:-Xn),f):0;if(!e&&(l=u=v)&&t.lineStart(),v!==u&&(!(g=s(e,p))||Ir(e,g)||Ir(p,g))&&(p[0]+=jn,p[1]+=jn,v=o(p[0],p[1])),v!==u)h=0,v?(t.lineStart(),g=s(p,e),t.point(g[0],g[1])):(g=s(e,p),t.point(g[0],g[1]),t.lineEnd()),e=g;else if(i&&e&&r^v){var y;d&n||!(y=s(p,e,!0))||(h=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1])))}!v||e&&Ir(e,p)||t.point(p[0],p[1]),e=p,u=v,n=d},lineEnd:function(){u&&t.lineEnd(),e=null},clean:function(){return h|(l&&u)<<1}}}),(function(n,r,i,o){!function(t,e,n,r,i,o){if(n){var s=tr(e),a=er(e),u=r*n;null==i?(i=e+r*Hn,o=e-u/2):(i=br(s,i),o=br(s,o),(r>0?io)&&(i+=r*Hn));for(var l,h=i;r>0?h>o:h4*e&&v--){var x=s+f,E=a+g,k=u+p,b=nr(x*x+E*E+k*k),w=ir(k/=b),I=Kn(Kn(k)-1)e||Kn((y*L+m*P)/_-.5)>.3||s*f+a*g+u*p2?t[2]%360*Jn:0,M()):[d*Wn,y*Wn,m*Wn]},I.precision=function(t){return arguments.length?(w=Kr(S,b=t*t),L()):nr(b)},I.fitExtent=function(t,e){return Hr(I,t,e)},I.fitSize=function(t,e){return function(t,e,n){return Hr(t,[[0,0],e],n)}(I,t,e)},function(){return e=t.apply(this,arguments),I.invert=e.invert&&N,M()}}((function(){return t}))()}function ti(t){return function(e,n){var r=tr(e),i=tr(n),o=t(r*i);return[o*i*er(e),o*er(n)]}}function ei(t){return function(e,n){var r=nr(e*e+n*n),i=t(r),o=er(i),s=tr(i);return[$n(e*o,r*s),ir(r&&n*o/r)]}}ti((function(t){return nr(2/(1+t))})).invert=ei((function(t){return 2*ir(t/2)}));var ni=ti((function(t){return(t=rr(t))&&t/er(t)}));function ri(){return $r(ni).scale(79.4188).clipAngle(179.999)}function ii(t,e){return[t,e]}ni.invert=ei((function(t){return t})),ii.invert=ii;var oi=Vn.BufferOp,si=Vn.GeoJSONReader,ai=Vn.GeoJSONWriter;function ui(t,e,n,r){var i=t.properties||{},o="Feature"===t.type?t.geometry:t;if("GeometryCollection"===o.type){var s=[];return mt(t,(function(t){var i=ui(t,e,n,r);i&&s.push(i)})),C(s)}var a=function(t){var e=An(t).geometry.coordinates,n=[-e[0],-e[1]];return ri().rotate(n).scale(x)}(o),u={type:o.type,coordinates:hi(o.coordinates,a)},l=(new si).read(u),h=F(q(e,n),"meters"),c=oi.bufferOp(l,h,r);if(!li((c=(new ai).write(c)).coordinates))return b({type:c.type,coordinates:ci(c.coordinates,a)},i)}function li(t){return Array.isArray(t[0])?li(t[0]):isNaN(t[0])}function hi(t,e){return"object"!==m(t[0])?e(t):t.map((function(t){return hi(t,e)}))}function ci(t,e){return"object"!==m(t[0])?e.invert(t):t.map((function(t){return ci(t,e)}))}function fi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return mt(t,(function(t,o,s){var a=e.weight?null==s?void 0:s[e.weight]:void 0;if(!U(a=null==a?1:a))throw new Error("weight value must be a number for feature index "+o);(a=Number(a))>0&&ct(t,(function(t){n+=t[0]*a,r+=t[1]*a,i+=a}))})),I([n/i,r/i],e.properties,e)}function gi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return ct(t,(function(t){n+=t[0],r+=t[1],i++}),!0),I([n/i,r/i],e.properties)}function pi(t,e,n,r,i){var o=r.tolerance||.001,s=0,a=0,u=0,l=0;if(vt(n,(function(e){var n,r=null==(n=e.properties)?void 0:n.weight,i=null==r?1:r;if(!U(i=Number(i)))throw new Error("weight value must be a number");if(i>0){l+=1;var o=i*ut(e,t);0===o&&(o=1);var h=i/o;s+=e.geometry.coordinates[0]*h,a+=e.geometry.coordinates[1]*h,u+=h}})),l<1)throw new Error("no features to measure");var h=s/u,c=a/u;return 1===l||0===i||Math.abs(h-e[0])0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mi;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function mi(t,e){return te?1:0}var _i,xi,Ei,ki,bi,wi=_n(Object.freeze({__proto__:null,default:yi})),Ii={exports:{}};function Ni(){if(bi)return Ii.exports;bi=1;var t=(xi||(xi=1,_i=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=(r-n)/2,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),_i),e=(ki||(ki=1,Ei=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=r-n,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),Ei);return Ii.exports=function(n,r,i,o){return r.length>0&&Array.isArray(r[0])?e(n,r,i,o):t(n,r,i,o)},Ii.exports.nested=e,Ii.exports.flat=t,Ii.exports}var Si,Mi,Li={exports:{}};Li.exports;function Pi(){return Si||(Si=1,function(t,e){!function(t){var e=134217729,n=33306690738754706e-32;function r(t,e,n,r,i){var o,s,a,u,l=e[0],h=r[0],c=0,f=0;h>l==h>-l?(o=l,l=e[++c]):(o=h,h=r[++f]);var g=0;if(cl==h>-l?(a=o-((s=l+o)-l),l=e[++c]):(a=o-((s=h+o)-h),h=r[++f]),o=s,0!==a&&(i[g++]=a);cl==h>-l?(a=o-((s=o+l)-(u=s-o))+(l-u),l=e[++c]):(a=o-((s=o+h)-(u=s-o))+(h-u),h=r[++f]),o=s,0!==a&&(i[g++]=a);for(;c0!=m>0)return _;var x=Math.abs(y+m);return Math.abs(_)>=o*x?_:-function(t,i,o,g,p,v,d){var y,m,_,x,E,k,b,w,I,N,S,M,L,P,C,T,O,R,A=t-p,D=o-p,F=i-v,q=g-v;E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=q-(I=(k=e*q)-(k-q)))-((P=A*q)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=D-(I=(k=e*D)-(k-D)))-((T=F*D)-b*I-w*I-b*N))),u[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),u[1]=L-(S+E)+(E-T),E=(R=M+S)-M,u[2]=M-(R-E)+(S-E),u[3]=R;var V=function(t,e){for(var n=e[0],r=1;r=G||-V>=G)return V;if(y=t-(A+(E=t-A))+(E-p),_=o-(D+(E=o-D))+(E-p),m=i-(F+(E=i-F))+(E-v),x=g-(q+(E=g-q))+(E-v),0===y&&0===m&&0===_&&0===x)return V;if(G=a*d+n*Math.abs(V),(V+=A*x+q*y-(F*_+D*m))>=G||-V>=G)return V;E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=q-(I=(k=e*q)-(k-q)))-((P=y*q)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=D-(I=(k=e*D)-(k-D)))-((T=m*D)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var B=r(4,u,4,f,l);E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=x-(I=(k=e*x)-(k-x)))-((P=A*x)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=_-(I=(k=e*_)-(k-_)))-((T=F*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var Y=r(B,l,4,f,h);E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=x-(I=(k=e*x)-(k-x)))-((P=y*x)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=_-(I=(k=e*_)-(k-_)))-((T=m*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var z=r(Y,h,4,f,c);return c[z-1]}(t,i,g,p,v,d,x)},t.orient2dfast=function(t,e,n,r,i,o){return(e-o)*(n-i)-(t-i)*(r-o)},Object.defineProperty(t,"__esModule",{value:!0})}(e)}(0,Li.exports)),Li.exports}var Ci=function(){if(Mi)return vi.exports;Mi=1;var t=di,e=wi,n=Ni(),r=Pi().orient2d;function i(e,r,i){r=Math.max(0,void 0===r?2:r),i=i||0;var s=function(t){for(var e=t[0],r=t[0],i=t[0],o=t[0],s=0;si[0]&&(i=a),a[1]o[1]&&(o=a)}var u=[e,r,i,o],l=u.slice();for(s=0;s=2&&h(e[e.length-2],e[e.length-1],t[n])<=0;)e.pop();e.push(t[n])}for(var r=[],i=t.length-1;i>=0;i--){for(;r.length>=2&&h(r[r.length-2],r[r.length-1],t[i])<=0;)r.pop();r.push(t[i])}return r.pop(),e.pop(),e.concat(r)}(l)}(e),a=new t(16);a.toBBox=function(t){return{minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]}},a.compareMinX=function(t,e){return t[0]-e[0]},a.compareMinY=function(t,e){return t[1]-e[1]},a.load(e);for(var u,l=[],p=0;pu||c.push({node:v,dist:d})}for(;c.length&&!c.peek().node.children;){var y=c.pop(),m=y.node,_=p(m,n,r),x=p(m,i,o);if(y.dist<_&&y.dist=e.minX&&t[0]<=e.maxX&&t[1]>=e.minY&&t[1]<=e.maxY}function l(t,e,n){for(var r,i,o,s,a=Math.min(t[0],e[0]),u=Math.min(t[1],e[1]),l=Math.max(t[0],e[0]),c=Math.max(t[1],e[1]),f=n.search({minX:a,minY:u,maxX:l,maxY:c}),g=0;g0!=h(r,i,s)>0&&h(o,s,r)>0!=h(o,s,i)>0)return!1;return!0}function h(t,e,n){return r(t[0],t[1],e[0],e[1],n[0],n[1])}function c(t){var e=t.p,n=t.next.p;return t.minX=Math.min(e[0],n[0]),t.minY=Math.min(e[1],n[1]),t.maxX=Math.max(e[0],n[0]),t.maxY=Math.max(e[1],n[1]),t}function f(t,e){var n={p:t,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return e?(n.next=e.next,n.prev=e,e.next.prev=n,e.next=n):(n.prev=n,n.next=n),n}function g(t,e){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function p(t,e,n){var r=e[0],i=e[1],o=n[0]-r,s=n[1]-i;if(0!==o||0!==s){var a=((t[0]-r)*o+(t[1]-i)*s)/(o*o+s*s);a>1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function v(t,e,n,r,i,o,s,a){var u,l,h,c,f=n-t,g=r-e,p=s-i,v=a-o,d=t-i,y=e-o,m=f*f+g*g,_=f*p+g*v,x=p*p+v*v,E=f*d+g*y,k=p*d+v*y,b=m*x-_*_,w=b,I=b;0===b?(l=0,w=1,c=k,I=x):(c=m*k-_*E,(l=_*k-x*E)<0?(l=0,c=k,I=x):l>w&&(l=w,c=k+_,I=x)),c<0?(c=0,-E<0?l=0:-E>m?l=w:(l=-E,w=m)):c>I&&(c=I,-E+_<0?l=0:-E+_>m?l=w:(l=-E+_,w=m));var N=(1-(h=0===c?0:c/I))*i+h*s-((1-(u=0===l?0:l/w))*t+u*n),S=(1-h)*o+h*a-((1-u)*e+u*r);return N*N+S*S}function d(t,e){return t[0]===e[0]?t[1]-e[1]:t[0]-e[0]}return e.default&&(e=e.default),vi.exports=i,vi.exports.default=i,vi.exports}(),Ti=mn(Ci);function Oi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e.concavity=e.concavity||1/0;var n=[];if(ct(t,(function(t){n.push([t[0],t[1]])})),!n.length)return null;var r=Ti(n,e.concavity);return r.length>3?S([r]):null}function Ri(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.steps||64,i=n.properties?n.properties:!Array.isArray(t)&&"Feature"===t.type&&t.properties?t.properties:{},o=[],s=0;s0;r.length0;){var a=t[Math.floor(Math.random()*o)],u=s?a.join("_"):""+a;n[u]||(n[u]=!0,r.push(a))}if(r.length0,u=t[Math.floor(Math.random()*s)];for(a&&u.join("_"),o.push(u);o.length0,y=[];if(s)u="kmrand"==s?r(t,e):"kmpp"==s?i(t,e):s;else for(var m={};u.lengthc&&(c=t[a].y);var g,p=l-u,v=c-h,d=p>v?p:v,y=.5*(l+u),m=.5*(c+h),_=[new so({__sentinel:!0,x:y-20*d,y:m-d},{__sentinel:!0,x:y,y:m+20*d},{__sentinel:!0,x:y+20*d,y:m-d})],x=[],E=[];a=t.length;for(;a--;){for(E.length=0,g=_.length;g--;)(p=t[a].x-_[g].x)>0&&p*p>_[g].r?(x.push(_[g]),_.splice(g,1)):p*p+(v=t[a].y-_[g].y)*v>_[g].r||(E.push(_[g].a,_[g].b,_[g].b,_[g].c,_[g].c,_[g].a),_.splice(g,1));for(uo(E),g=E.length;g;)n=E[--g],e=E[--g],r=t[a],i=n.x-e.x,o=n.y-e.y,s=2*(i*(r.y-n.y)-o*(r.x-n.x)),Math.abs(s)>f&&_.push(new so(e,n,r))}Array.prototype.push.apply(x,_),a=x.length;for(;a--;)(x[a].a.__sentinel||x[a].b.__sentinel||x[a].c.__sentinel)&&x.splice(a,1);return x}(t.features.map((function(t){var r={x:t.geometry.coordinates[0],y:t.geometry.coordinates[1]};return e?r.z=t.properties[e]:3===t.geometry.coordinates.length&&(n=!0,r.z=t.geometry.coordinates[2]),r}))).map((function(t){var e=[t.a.x,t.a.y],r=[t.b.x,t.b.y],i=[t.c.x,t.c.y],o={};return n?(e.push(t.a.z),r.push(t.b.z),i.push(t.c.z)):o={a:t.a.z,b:t.b.z,c:t.c.z},S([[e,r,i,e]],o)})))}var so=s((function t(e,n,r){i(this,t),this.a=e,this.b=n,this.c=r;var o,s,a=n.x-e.x,u=n.y-e.y,l=r.x-e.x,h=r.y-e.y,c=a*(e.x+n.x)+u*(e.y+n.y),f=l*(e.x+r.x)+h*(e.y+r.y),g=2*(a*(r.y-n.y)-u*(r.x-n.x));this.x=(h*c-u*f)/g,this.y=(a*f-l*c)/g,o=this.x-e.x,s=this.y-e.y,this.r=o*o+s*s}));function ao(t,e){return e.x-t.x}function uo(t){var e,n,r,i,o,s=t.length;t:for(;s;)for(n=t[--s],e=t[--s],r=s;r;)if(o=t[--r],e===(i=t[--r])&&n===o||e===o&&n===i){t.splice(s,2),t.splice(r,2),s-=2;continue t}}function lo(t){return t}function ho(t,e){var n=function(t){if(null==t)return lo;var e,n,r=t.scale[0],i=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,a){a||(e=n=0);var u=2,l=t.length,h=new Array(l);for(h[0]=(e+=t[0])*r+o,h[1]=(n+=t[1])*i+s;u1)for(var o,a,u=1,l=s(i[0]);ul&&(a=i[0],i[0]=i[u],i[u]=a,l=o);return i})).filter((function(t){return t.length>0}))}}var po=Object.prototype.hasOwnProperty;function vo(t,e,n,r,i,o){3===arguments.length&&(r=o=Array,i=null);for(var s=new r(t=1<=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},maybeSet:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},get:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)break;h=s[l=l+1&u]}return o},keys:function(){for(var t=[],e=0,n=s.length;e>7^xo[2]^xo[3])}function ko(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=function(){for(var t=vo(1.4*o.length,E,k,Int32Array,-1,Int32Array),e=new Int32Array(o.length),n=0,r=o.length;n=0){var o=c[n];i===e&&o===r||i===r&&o===e||(++g,f[n]=1)}else h[n]=e,c[n]=r}}function E(t){return Eo(o[t])}function k(t,e){return yo(o[t],o[e])}l=h=c=null;var b,w=function(t,e,n,r,i){3===arguments.length&&(r=Array,i=null);for(var o=new r(t=1<=t)throw new Error("full hashset");u=o[a=a+1&s]}return o[a]=r,!0},has:function(r){for(var a=e(r)&s,u=o[a],l=0;u!=i;){if(n(u,r))return!0;if(++l>=t)break;u=o[a=a+1&s]}return!1},values:function(){for(var t=[],e=0,n=o.length;e>1);er&&(r=o),si&&(i=s)}function u(t){t.forEach(a)}function l(t){t.forEach(u)}for(var h in t)o(t[h]);return r>=e&&i>=n?[e,n,r,i]:void 0}(t=Io(t)),r=function(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=s.length+a.length;for(delete t.lines,delete t.rings,r=0,i=s.length;r1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=[],i=It(t,(function(t,e){var n=function(t,e){var n,r=t.geometry.coordinates,i=e.geometry.coordinates,o=Oo(r[0]),s=Oo(r[r.length-1]),a=Oo(i[0]),u=Oo(i[i.length-1]);if(o===u)n=i.concat(r.slice(1));else if(a===s)n=r.concat(i.slice(1));else if(o===a)n=r.slice(1).reverse().concat(i);else{if(s!==u)return null;n=r.concat(i.reverse().slice(1))}return L(n)}(t,e);return n||(r.push(t),e)}));return i&&r.push(i),r.length?1===r.length?r[0]:T(r.map((function(t){return t.coordinates}))):null}function Oo(t){return t[0].toString()+","+t[1].toString()}function Ro(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=function(t){var e={};xt(t,(function(t){e[t.geometry.type]=!0}));var n=Object.keys(e);if(1===n.length)return n[0];return null}(t);if(!r)throw new Error("geojson must be homogenous");var i=t;switch(r){case"LineString":return To(i,e);case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==e.mutate&&void 0!==e.mutate||(t=Ai(t));var n=[];xt(t,(function(t){n.push(t.geometry)}));var r=Lo({geoms:A(n).geometry});return fo(r,r.objects.geoms.geometries)}(i,e);default:throw new Error(r+" is not supported")}}var Ao=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Do=Math.ceil,Fo=Math.floor,qo="[BigNumber Error] ",Vo=qo+"Number primitive has more than 15 significant digits: ",Go=1e14,Bo=14,Yo=9007199254740991,zo=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Xo=1e9;function Uo(t){var e=0|t;return t>0||t===e?e:e-1}function Zo(t){for(var e,n,r=1,i=t.length,o=t[0]+"";rl^n?1:-1;for(a=(u=i.length)<(l=o.length)?u:l,s=0;so[s]^n?1:-1;return u==l?0:u>l^n?1:-1}function Wo(t,e,n,r){if(tn||t!==Fo(t))throw Error(qo+(r||"Argument")+("number"==typeof t?tn?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Jo(t){var e=t.c.length-1;return Uo(t.e/Bo)==e&&t.c[e]%2!=0}function Ko(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Qo(t,e,n){var r,i;if(e<0){for(i=n+".";++e;i+=n);t=i+t}else if(++e>(r=t.length)){for(i=n,e-=r;--e;i+=n);t+=i}else ex?f.c=f.e=null:t.e<_?f.c=[f.e=0]:(f.e=t.e,f.c=t.c.slice()));if((l="number"==typeof t)&&0*t==0){if(f.s=1/t<0?(t=-t,-1):1,t===~~t){for(a=0,u=t;u>=10;u/=10,a++);return void(a>x?f.c=f.e=null:(f.e=a,f.c=[t]))}c=String(t)}else{if(!Ao.test(c=String(t)))return i(f,c,l);f.s=45==c.charCodeAt(0)?(c=c.slice(1),-1):1}(a=c.indexOf("."))>-1&&(c=c.replace(".","")),(u=c.search(/e/i))>0?(a<0&&(a=u),a+=+c.slice(u+1),c=c.substring(0,u)):a<0&&(a=c.length)}else{if(Wo(e,2,I.length,"Base"),10==e&&N)return C(f=new S(t),p+f.e+1,v);if(c=String(t),l="number"==typeof t){if(0*t!=0)return i(f,c,l,e);if(f.s=1/t<0?(c=c.slice(1),-1):1,S.DEBUG&&c.replace(/^0\.0*|\./,"").length>15)throw Error(Vo+t)}else f.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1;for(n=I.slice(0,e),a=u=0,h=c.length;ua){a=h;continue}}else if(!s&&(c==c.toUpperCase()&&(c=c.toLowerCase())||c==c.toLowerCase()&&(c=c.toUpperCase()))){s=!0,u=-1,a=0;continue}return i(f,String(t),l,e)}l=!1,(a=(c=r(c,e,10,f.s)).indexOf("."))>-1?c=c.replace(".",""):a=c.length}for(u=0;48===c.charCodeAt(u);u++);for(h=c.length;48===c.charCodeAt(--h););if(c=c.slice(u,++h)){if(h-=u,l&&S.DEBUG&&h>15&&(t>Yo||t!==Fo(t)))throw Error(Vo+f.s*t);if((a=a-u-1)>x)f.c=f.e=null;else if(a<_)f.c=[f.e=0];else{if(f.e=a,f.c=[],u=(a+1)%Bo,a<0&&(u+=Bo),u=y)?Ko(u,s):Qo(u,s,"0");else if(o=(t=C(new S(t),e,n)).e,a=(u=Zo(t.c)).length,1==r||2==r&&(e<=o||o<=d)){for(;aa){if(--e>0)for(u+=".";e--;u+="0");}else if((e+=o-a)>0)for(o+1==a&&(u+=".");e--;u+="0");return t.s<0&&i?"-"+u:u}function L(t,e){for(var n,r,i=1,o=new S(t[0]);i=10;i/=10,r++);return(n=r+n*Bo-1)>x?t.c=t.e=null:n<_?t.c=[t.e=0]:(t.e=n,t.c=e),t}function C(t,e,n,r){var i,o,s,a,u,l,h,c=t.c,f=zo;if(c){t:{for(i=1,a=c[0];a>=10;a/=10,i++);if((o=e-i)<0)o+=Bo,s=e,u=c[l=0],h=Fo(u/f[i-s-1]%10);else if((l=Do((o+1)/Bo))>=c.length){if(!r)break t;for(;c.length<=l;c.push(0));u=h=0,i=1,s=(o%=Bo)-Bo+1}else{for(u=a=c[l],i=1;a>=10;a/=10,i++);h=(s=(o%=Bo)-Bo+i)<0?0:Fo(u/f[i-s-1]%10)}if(r=r||e<0||null!=c[l+1]||(s<0?u:u%f[i-s-1]),r=n<4?(h||r)&&(0==n||n==(t.s<0?3:2)):h>5||5==h&&(4==n||r||6==n&&(o>0?s>0?u/f[i-s]:0:c[l-1])%10&1||n==(t.s<0?8:7)),e<1||!c[0])return c.length=0,r?(e-=t.e+1,c[0]=f[(Bo-e%Bo)%Bo],t.e=-e||0):c[0]=t.e=0,t;if(0==o?(c.length=l,a=1,l--):(c.length=l+1,a=f[Bo-o],c[l]=s>0?Fo(u/f[i-s]%f[s])*a:0),r)for(;;){if(0==l){for(o=1,s=c[0];s>=10;s/=10,o++);for(s=c[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(t.e++,c[0]==Go&&(c[0]=1));break}if(c[l]+=a,c[l]!=Go)break;c[l--]=0,a=1}for(o=c.length;0===c[--o];c.pop());}t.e>x?t.c=t.e=null:t.e<_&&(t.c=[t.e=0])}return t}function T(t){var e,n=t.e;return null===n?t.toString():(e=Zo(t.c),e=n<=d||n>=y?Ko(e,n):Qo(e,n,"0"),t.s<0?"-"+e:e)}return S.clone=t,S.ROUND_UP=0,S.ROUND_DOWN=1,S.ROUND_CEIL=2,S.ROUND_FLOOR=3,S.ROUND_HALF_UP=4,S.ROUND_HALF_DOWN=5,S.ROUND_HALF_EVEN=6,S.ROUND_HALF_CEIL=7,S.ROUND_HALF_FLOOR=8,S.EUCLID=9,S.config=S.set=function(t){var e,n;if(null!=t){if("object"!=m(t))throw Error(qo+"Object expected: "+t);if(t.hasOwnProperty(e="DECIMAL_PLACES")&&(Wo(n=t[e],0,Xo,e),p=n),t.hasOwnProperty(e="ROUNDING_MODE")&&(Wo(n=t[e],0,8,e),v=n),t.hasOwnProperty(e="EXPONENTIAL_AT")&&((n=t[e])&&n.pop?(Wo(n[0],-Xo,0,e),Wo(n[1],0,Xo,e),d=n[0],y=n[1]):(Wo(n,-Xo,Xo,e),d=-(y=n<0?-n:n))),t.hasOwnProperty(e="RANGE"))if((n=t[e])&&n.pop)Wo(n[0],-Xo,-1,e),Wo(n[1],1,Xo,e),_=n[0],x=n[1];else{if(Wo(n,-Xo,Xo,e),!n)throw Error(qo+e+" cannot be zero: "+n);_=-(x=n<0?-n:n)}if(t.hasOwnProperty(e="CRYPTO")){if((n=t[e])!==!!n)throw Error(qo+e+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw E=!n,Error(qo+"crypto unavailable");E=n}else E=n}if(t.hasOwnProperty(e="MODULO_MODE")&&(Wo(n=t[e],0,9,e),k=n),t.hasOwnProperty(e="POW_PRECISION")&&(Wo(n=t[e],0,Xo,e),b=n),t.hasOwnProperty(e="FORMAT")){if("object"!=m(n=t[e]))throw Error(qo+e+" not an object: "+n);w=n}if(t.hasOwnProperty(e="ALPHABET")){if("string"!=typeof(n=t[e])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(qo+e+" invalid: "+n);N="0123456789"==n.slice(0,10),I=n}}return{DECIMAL_PLACES:p,ROUNDING_MODE:v,EXPONENTIAL_AT:[d,y],RANGE:[_,x],CRYPTO:E,MODULO_MODE:k,POW_PRECISION:b,FORMAT:w,ALPHABET:I}},S.isBigNumber=function(t){if(!t||!0!==t._isBigNumber)return!1;if(!S.DEBUG)return!0;var e,n,r=t.c,i=t.e,o=t.s;t:if("[object Array]"=={}.toString.call(r)){if((1===o||-1===o)&&i>=-Xo&&i<=Xo&&i===Fo(i)){if(0===r[0]){if(0===i&&1===r.length)return!0;break t}if((e=(i+1)%Bo)<1&&(e+=Bo),String(r[0]).length==e){for(e=0;e=Go||n!==Fo(n))break t;if(0!==n)return!0}}}else if(null===r&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(qo+"Invalid BigNumber: "+t)},S.maximum=S.max=function(){return L(arguments,-1)},S.minimum=S.min=function(){return L(arguments,1)},S.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Fo(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(t){var e,n,r,i,o,a=0,u=[],l=new S(g);if(null==t?t=p:Wo(t,0,Xo),i=Do(t/Bo),E)if(crypto.getRandomValues){for(e=crypto.getRandomValues(new Uint32Array(i*=2));a>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),e[a]=n[0],e[a+1]=n[1]):(u.push(o%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw E=!1,Error(qo+"crypto unavailable");for(e=crypto.randomBytes(i*=7);a=9e15?crypto.randomBytes(7).copy(e,a):(u.push(o%1e14),a+=7);a=i/7}if(!E)for(;a=10;o/=10,a++);an-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(r,i,o,s,a){var u,l,h,c,f,g,d,y,m=r.indexOf("."),_=p,x=v;for(m>=0&&(c=b,b=0,r=r.replace(".",""),g=(y=new S(i)).pow(r.length-m),b=c,y.c=e(Qo(Zo(g.c),g.e,"0"),10,o,t),y.e=y.c.length),h=c=(d=e(r,i,o,a?(u=I,t):(u=t,I))).length;0==d[--c];d.pop());if(!d[0])return u.charAt(0);if(m<0?--h:(g.c=d,g.e=h,g.s=s,d=(g=n(g,y,_,x,o)).c,f=g.r,h=g.e),m=d[l=h+_+1],c=o/2,f=f||l<0||null!=d[l+1],f=x<4?(null!=m||f)&&(0==x||x==(g.s<0?3:2)):m>c||m==c&&(4==x||f||6==x&&1&d[l-1]||x==(g.s<0?8:7)),l<1||!d[0])r=f?Qo(u.charAt(1),-_,u.charAt(0)):u.charAt(0);else{if(d.length=l,f)for(--o;++d[--l]>o;)d[l]=0,l||(++h,d=[1].concat(d));for(c=d.length;!d[--c];);for(m=0,r="";m<=c;r+=u.charAt(d[m++]));r=Qo(r,h,u.charAt(0))}return r}}(),n=function(){function t(t,e,n){var r,i,o,s,a=0,u=t.length,l=e%jo,h=e/jo|0;for(t=t.slice();u--;)a=((i=l*(o=t[u]%jo)+(r=h*o+(s=t[u]/jo|0)*l)%jo*jo+a)/n|0)+(r/jo|0)+h*s,t[u]=i%n;return a&&(t=[a].concat(t)),t}function e(t,e,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;ie[i]?1:-1;break}return o}function n(t,e,n,r){for(var i=0;n--;)t[n]-=i,i=t[n]1;t.splice(0,1));}return function(r,i,o,s,a){var u,l,h,c,f,g,p,v,d,y,m,_,x,E,k,b,w,I=r.s==i.s?1:-1,N=r.c,M=i.c;if(!(N&&N[0]&&M&&M[0]))return new S(r.s&&i.s&&(N?!M||N[0]!=M[0]:M)?N&&0==N[0]||!M?0*I:I/0:NaN);for(d=(v=new S(I)).c=[],I=o+(l=r.e-i.e)+1,a||(a=Go,l=Uo(r.e/Bo)-Uo(i.e/Bo),I=I/Bo|0),h=0;M[h]==(N[h]||0);h++);if(M[h]>(N[h]||0)&&l--,I<0)d.push(1),c=!0;else{for(E=N.length,b=M.length,h=0,I+=2,(f=Fo(a/(M[0]+1)))>1&&(M=t(M,f,a),N=t(N,f,a),b=M.length,E=N.length),x=b,m=(y=N.slice(0,b)).length;m=a/2&&k++;do{if(f=0,(u=e(M,y,b,m))<0){if(_=y[0],b!=m&&(_=_*a+(y[1]||0)),(f=Fo(_/k))>1)for(f>=a&&(f=a-1),p=(g=t(M,f,a)).length,m=y.length;1==e(g,y,p,m);)f--,n(g,b=10;I/=10,h++);C(v,o+(v.e=h+l*Bo-1)+1,s,c)}else v.e=l,v.r=+c;return v}}(),a=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,l=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,c=/^\s*\+(?=[\w.])|^\s+|\s+$/g,i=function(t,e,n,r){var i,o=n?e:e.replace(c,"");if(h.test(o))t.s=isNaN(o)?null:o<0?-1:1;else{if(!n&&(o=o.replace(a,(function(t,e,n){return i="x"==(n=n.toLowerCase())?16:"b"==n?2:8,r&&r!=i?t:e})),r&&(i=r,o=o.replace(u,"$1").replace(l,"0.$1")),e!=o))return new S(o,i);if(S.DEBUG)throw Error(qo+"Not a"+(r?" base "+r:"")+" number: "+e);t.s=null}t.c=t.e=null},f.absoluteValue=f.abs=function(){var t=new S(this);return t.s<0&&(t.s=1),t},f.comparedTo=function(t,e){return Ho(this,new S(t,e))},f.decimalPlaces=f.dp=function(t,e){var n,r,i,o=this;if(null!=t)return Wo(t,0,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t+o.e+1,e);if(!(n=o.c))return null;if(r=((i=n.length-1)-Uo(this.e/Bo))*Bo,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},f.dividedBy=f.div=function(t,e){return n(this,new S(t,e),p,v)},f.dividedToIntegerBy=f.idiv=function(t,e){return n(this,new S(t,e),0,1)},f.exponentiatedBy=f.pow=function(t,e){var n,r,i,o,s,a,u,l,h=this;if((t=new S(t)).c&&!t.isInteger())throw Error(qo+"Exponent not an integer: "+T(t));if(null!=e&&(e=new S(e)),s=t.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!t.c||!t.c[0])return l=new S(Math.pow(+T(h),s?t.s*(2-Jo(t)):+T(t))),e?l.mod(e):l;if(a=t.s<0,e){if(e.c?!e.c[0]:!e.s)return new S(NaN);(r=!a&&h.isInteger()&&e.isInteger())&&(h=h.mod(e))}else{if(t.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return o=h.s<0&&Jo(t)?-0:0,h.e>-1&&(o=1/o),new S(a?1/o:o);b&&(o=Do(b/Bo+2))}for(s?(n=new S(.5),a&&(t.s=1),u=Jo(t)):u=(i=Math.abs(+T(t)))%2,l=new S(g);;){if(u){if(!(l=l.times(h)).c)break;o?l.c.length>o&&(l.c.length=o):r&&(l=l.mod(e))}if(i){if(0===(i=Fo(i/2)))break;u=i%2}else if(C(t=t.times(n),t.e+1,1),t.e>14)u=Jo(t);else{if(0===(i=+T(t)))break;u=i%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):r&&(h=h.mod(e))}return r?l:(a&&(l=g.div(l)),e?l.mod(e):o?C(l,b,v,undefined):l)},f.integerValue=function(t){var e=new S(this);return null==t?t=v:Wo(t,0,8),C(e,e.e+1,t)},f.isEqualTo=f.eq=function(t,e){return 0===Ho(this,new S(t,e))},f.isFinite=function(){return!!this.c},f.isGreaterThan=f.gt=function(t,e){return Ho(this,new S(t,e))>0},f.isGreaterThanOrEqualTo=f.gte=function(t,e){return 1===(e=Ho(this,new S(t,e)))||0===e},f.isInteger=function(){return!!this.c&&Uo(this.e/Bo)>this.c.length-2},f.isLessThan=f.lt=function(t,e){return Ho(this,new S(t,e))<0},f.isLessThanOrEqualTo=f.lte=function(t,e){return-1===(e=Ho(this,new S(t,e)))||0===e},f.isNaN=function(){return!this.s},f.isNegative=function(){return this.s<0},f.isPositive=function(){return this.s>0},f.isZero=function(){return!!this.c&&0==this.c[0]},f.minus=function(t,e){var n,r,i,o,s=this,a=s.s;if(e=(t=new S(t,e)).s,!a||!e)return new S(NaN);if(a!=e)return t.s=-e,s.plus(t);var u=s.e/Bo,l=t.e/Bo,h=s.c,c=t.c;if(!u||!l){if(!h||!c)return h?(t.s=-e,t):new S(c?s:NaN);if(!h[0]||!c[0])return c[0]?(t.s=-e,t):new S(h[0]?s:3==v?-0:0)}if(u=Uo(u),l=Uo(l),h=h.slice(),a=u-l){for((o=a<0)?(a=-a,i=h):(l=u,i=c),i.reverse(),e=a;e--;i.push(0));i.reverse()}else for(r=(o=(a=h.length)<(e=c.length))?a:e,a=e=0;e0)for(;e--;h[n++]=0);for(e=Go-1;r>a;){if(h[--r]=0;){for(n=0,f=_[i]%d,g=_[i]/d|0,o=i+(s=u);o>i;)n=((l=f*(l=m[--s]%d)+(a=g*l+(h=m[s]/d|0)*f)%d*d+p[o]+n)/v|0)+(a/d|0)+g*h,p[o--]=l%v;p[o]=n}return n?++r:p.splice(0,1),P(t,p,r)},f.negated=function(){var t=new S(this);return t.s=-t.s||null,t},f.plus=function(t,e){var n,r=this,i=r.s;if(e=(t=new S(t,e)).s,!i||!e)return new S(NaN);if(i!=e)return t.s=-e,r.minus(t);var o=r.e/Bo,s=t.e/Bo,a=r.c,u=t.c;if(!o||!s){if(!a||!u)return new S(i/0);if(!a[0]||!u[0])return u[0]?t:new S(a[0]?r:0*i)}if(o=Uo(o),s=Uo(s),a=a.slice(),i=o-s){for(i>0?(s=o,n=u):(i=-i,n=a),n.reverse();i--;n.push(0));n.reverse()}for((i=a.length)-(e=u.length)<0&&(n=u,u=a,a=n,e=i),i=0;e;)i=(a[--e]=a[e]+u[e]+i)/Go|0,a[e]=Go===a[e]?0:a[e]%Go;return i&&(a=[i].concat(a),++s),P(t,a,s)},f.precision=f.sd=function(t,e){var n,r,i,o=this;if(null!=t&&t!==!!t)return Wo(t,1,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t,e);if(!(n=o.c))return null;if(r=(i=n.length-1)*Bo+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return t&&o.e+1>r&&(r=o.e+1),r},f.shiftedBy=function(t){return Wo(t,-9007199254740991,Yo),this.times("1e"+t)},f.squareRoot=f.sqrt=function(){var t,e,r,i,o,s=this,a=s.c,u=s.s,l=s.e,h=p+4,c=new S("0.5");if(1!==u||!a||!a[0])return new S(!u||u<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(u=Math.sqrt(+T(s)))||u==1/0?(((e=Zo(a)).length+l)%2==0&&(e+="0"),u=Math.sqrt(+e),l=Uo((l+1)/2)-(l<0||l%2),r=new S(e=u==1/0?"5e"+l:(e=u.toExponential()).slice(0,e.indexOf("e")+1)+l)):r=new S(u+""),r.c[0])for((u=(l=r.e)+h)<3&&(u=0);;)if(o=r,r=c.times(o.plus(n(s,o,h,1))),Zo(o.c).slice(0,u)===(e=Zo(r.c)).slice(0,u)){if(r.e0&&p>0){for(o=p%a||a,h=g.substr(0,o);o0&&(h+=l+g.slice(o)),f&&(h="-"+h)}r=c?h+(n.decimalSeparator||"")+((u=+n.fractionGroupSize)?c.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):c):h}return(n.prefix||"")+r+(n.suffix||"")},f.toFraction=function(t){var e,r,i,o,s,a,u,l,h,c,f,p,d=this,y=d.c;if(null!=t&&(!(u=new S(t)).isInteger()&&(u.c||1!==u.s)||u.lt(g)))throw Error(qo+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+T(u));if(!y)return new S(d);for(e=new S(g),h=r=new S(g),i=l=new S(g),p=Zo(y),s=e.e=p.length-d.e-1,e.c[0]=zo[(a=s%Bo)<0?Bo+a:a],t=!t||u.comparedTo(e)>0?s>0?e:h:u,a=x,x=1/0,u=new S(p),l.c[0]=0;c=n(u,e,0,1),1!=(o=r.plus(c.times(i))).comparedTo(t);)r=i,i=o,h=l.plus(c.times(o=h)),l=o,e=u.minus(c.times(o=e)),u=o;return o=n(t.minus(r),i,0,1),l=l.plus(o.times(h)),r=r.plus(o.times(i)),l.s=h.s=d.s,f=n(h,i,s*=2,v).minus(d).abs().comparedTo(n(l,r,s,v).minus(d).abs())<1?[h,i]:[l,r],x=a,f},f.toNumber=function(){return+T(this)},f.toPrecision=function(t,e){return null!=t&&Wo(t,1,Xo),M(this,t,e,2)},f.toString=function(t){var e,n=this,i=n.s,o=n.e;return null===o?i?(e="Infinity",i<0&&(e="-"+e)):e="NaN":(null==t?e=o<=d||o>=y?Ko(Zo(n.c),o):Qo(Zo(n.c),o,"0"):10===t&&N?e=Qo(Zo((n=C(new S(n),p+o+1,v)).c),n.e,"0"):(Wo(t,2,I.length,"Base"),e=r(Qo(Zo(n.c),o,"0"),10,t,i,!0)),i<0&&n.c[0]&&(e="-"+e)),e},f.valueOf=f.toJSON=function(){return T(this)},f._isBigNumber=!0,f[Symbol.toStringTag]="BigNumber",f[Symbol.for("nodejs.util.inspect.custom")]=f.valueOf,null!=e&&S.set(e),S}(),ts=function(t){function e(t){return i(this,e),r(this,e,[t])}return h(e,t),s(e)}(s((function t(e){i(this,t),u(this,"key",void 0),u(this,"left",null),u(this,"right",null),this.key=e}))),es=function(){return s((function t(){i(this,t),u(this,"size",0),u(this,"modificationCount",0),u(this,"splayCount",0)}),[{key:"splay",value:function(t){var e=this.root;if(null==e)return this.compare(t,t),-1;for(var n,r=null,i=null,o=null,s=null,a=e,u=this.compare;;)if((n=u(a.key,t))>0){var l=a.left;if(null==l)break;if((n=u(l.key,t))>0&&(a.left=l.right,l.right=a,null==(l=(a=l).left)))break;null==r?i=a:r.left=a,r=a,a=l}else{if(!(n<0))break;var h=a.right;if(null==h)break;if((n=u(h.key,t))<0&&(a.right=h.left,h.left=a,null==(h=(a=h).right)))break;null==o?s=a:o.right=a,o=a,a=h}return null!=o&&(o.right=a.left,a.left=s),null!=r&&(r.left=a.right,a.right=i),this.root!==a&&(this.root=a,this.splayCount++),n}},{key:"splayMin",value:function(t){for(var e=t,n=e.left;null!=n;){var r=n;e.left=r.right,r.right=e,n=(e=r).left}return e}},{key:"splayMax",value:function(t){for(var e=t,n=e.right;null!=n;){var r=n;e.right=r.left,r.left=e,n=(e=r).right}return e}},{key:"_delete",value:function(t){if(null==this.root)return null;if(0!=this.splay(t))return null;var e=this.root,n=e,r=e.left;if(this.size--,null==r)this.root=e.right;else{var i=e.right;(e=this.splayMax(r)).right=i,this.root=e}return this.modificationCount++,n}},{key:"addNewRoot",value:function(t,e){this.size++,this.modificationCount++;var n=this.root;null!=n?(e<0?(t.left=n,t.right=n.right,n.right=null):(t.right=n,t.left=n.left,n.left=null),this.root=t):this.root=t}},{key:"_first",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMin(t),this.root)}},{key:"_last",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMax(t),this.root)}},{key:"clear",value:function(){this.root=null,this.size=0,this.modificationCount++}},{key:"has",value:function(t){return this.validKey(t)&&0==this.splay(t)}},{key:"defaultCompare",value:function(){return function(t,e){return te?1:0}}},{key:"wrap",value:function(){var t=this;return{getRoot:function(){return t.root},setRoot:function(e){t.root=e},getSize:function(){return t.size},getModificationCount:function(){return t.modificationCount},getSplayCount:function(){return t.splayCount},setSplayCount:function(e){t.splayCount=e},splay:function(e){return t.splay(e)},has:function(e){return t.has(e)}}}}])}(),ns=function(t){function e(t,n){var o;return i(this,e),u(o=r(this,e),"root",null),u(o,"compare",void 0),u(o,"validKey",void 0),u(o,Symbol.toStringTag,"[object Set]"),o.compare=null!=t?t:o.defaultCompare(),o.validKey=null!=n?n:function(t){return null!=t&&null!=t},o}return h(e,t),s(e,[{key:"delete",value:function(t){return!!this.validKey(t)&&null!=this._delete(t)}},{key:"deleteAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.delete(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"forEach",value:function(t){for(var e,n=this[Symbol.iterator]();!(e=n.next()).done;)t(e.value,e.value,this)}},{key:"add",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this}},{key:"addAndReturn",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this.root.key}},{key:"addAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.add(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"isEmpty",value:function(){return null==this.root}},{key:"isNotEmpty",value:function(){return null!=this.root}},{key:"single",value:function(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}},{key:"first",value:function(){if(0==this.size)throw"Bad state: No element";return this._first().key}},{key:"last",value:function(){if(0==this.size)throw"Bad state: No element";return this._last().key}},{key:"lastBefore",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)<0)return this.root.key;var e=this.root.left;if(null==e)return null;for(var n=e.right;null!=n;)n=(e=n).right;return e.key}},{key:"firstAfter",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)>0)return this.root.key;var e=this.root.right;if(null==e)return null;for(var n=e.left;null!=n;)n=(e=n).left;return e.key}},{key:"retainAll",value:function(t){var n,r=new e(this.compare,this.validKey),i=this.modificationCount,o=a(t);try{for(o.s();!(n=o.n()).done;){var s=n.value;if(i!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(s)&&0==this.splay(s)&&r.add(this.root.key)}}catch(t){o.e(t)}finally{o.f()}r.size!=this.size&&(this.root=r.root,this.size=r.size,this.modificationCount++)}},{key:"lookup",value:function(t){return this.validKey(t)?0!=this.splay(t)?null:this.root.key:null}},{key:"intersection",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)&&r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"difference",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)||r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"union",value:function(t){var e=this.clone();return e.addAll(t),e}},{key:"clone",value:function(){var t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}},{key:"copyNode",value:function(t){if(null==t)return null;var e=new ts(t.key);return function t(e,n){var r,i;do{if(r=e.left,i=e.right,null!=r){var o=new ts(r.key);n.left=o,t(r,o)}if(null!=i){var s=new ts(i.key);n.right=s,e=i,n=s}}while(null!=i)}(t,e),e}},{key:"toSet",value:function(){return this.clone()}},{key:"entries",value:function(){return new os(this.wrap())}},{key:"keys",value:function(){return this[Symbol.iterator]()}},{key:"values",value:function(){return this[Symbol.iterator]()}},{key:Symbol.iterator,value:function(){return new is(this.wrap())}}])}(es),rs=function(){return s((function t(e){i(this,t),u(this,"tree",void 0),u(this,"path",new Array),u(this,"modificationCount",null),u(this,"splayCount",void 0),this.tree=e,this.splayCount=e.getSplayCount()}),[{key:Symbol.iterator,value:function(){return this}},{key:"next",value:function(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}},{key:"current",value:function(){if(!this.path.length)return null;var t=this.path[this.path.length-1];return this.getValue(t)}},{key:"rebuildPath",value:function(t){this.path.splice(0,this.path.length),this.tree.splay(t),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}},{key:"findLeftMostDescendent",value:function(t){for(;null!=t;)this.path.push(t),t=t.left}},{key:"moveNext",value:function(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();for(var t=this.tree.getRoot();null!=t;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);var e=this.path[this.path.length-1],n=e.right;if(null!=n){for(;null!=n;)this.path.push(n),n=n.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}}])}(),is=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return t.key}}])}(rs),os=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return[t.key,t.key]}}])}(rs),ss=function(t){return function(){return t}},as=function(t){var e=t?function(e,n){return n.minus(e).abs().isLessThanOrEqualTo(t)}:ss(!1);return function(t,n){return e(t,n)?0:t.comparedTo(n)}};function us(t){var e=t?function(e,n,r,i,o){return e.exponentiatedBy(2).isLessThanOrEqualTo(i.minus(n).exponentiatedBy(2).plus(o.minus(r).exponentiatedBy(2)).times(t))}:ss(!1);return function(t,n,r){var i=t.x,o=t.y,s=r.x,a=r.y,u=o.minus(a).times(n.x.minus(s)).minus(i.minus(s).times(n.y.minus(a)));return e(u,i,o,s,a)?0:u.comparedTo(0)}}var ls=function(t){return t},hs=function(t){if(t){var e=new ns(as(t)),n=new ns(as(t)),r=function(t,e){return e.addAndReturn(t)},i=function(t){return{x:r(t.x,e),y:r(t.y,n)}};return i({x:new $o(0),y:new $o(0)}),i}return ls},cs=function(t){return{set:function(t){fs=cs(t)},reset:function(){return cs(t)},compare:as(t),snap:hs(t),orient:us(t)}},fs=cs(),gs=function(t,e){return t.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(t.ur.x)&&t.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(t.ur.y)},ps=function(t,e){if(e.ur.x.isLessThan(t.ll.x)||t.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(t.ll.y)||t.ur.y.isLessThan(e.ll.y))return null;var n=t.ll.x.isLessThan(e.ll.x)?e.ll.x:t.ll.x,r=t.ur.x.isLessThan(e.ur.x)?t.ur.x:e.ur.x;return{ll:{x:n,y:t.ll.y.isLessThan(e.ll.y)?e.ll.y:t.ll.y},ur:{x:r,y:t.ur.y.isLessThan(e.ur.y)?t.ur.y:e.ur.y}}},vs=function(t,e){return t.x.times(e.y).minus(t.y.times(e.x))},ds=function(t,e){return t.x.times(e.x).plus(t.y.times(e.y))},ys=function(t){return ds(t,t).sqrt()},ms=function(t,e,n){var r={x:e.x.minus(t.x),y:e.y.minus(t.y)},i={x:n.x.minus(t.x),y:n.y.minus(t.y)};return ds(i,r).div(ys(i)).div(ys(r))},_s=function(t,e,n){return e.y.isZero()?null:{x:t.x.plus(e.x.div(e.y).times(n.minus(t.y))),y:n}},xs=function(t,e,n){return e.x.isZero()?null:{x:n,y:t.y.plus(e.y.div(e.x).times(n.minus(t.x)))}},Es=function(){function t(e,n){i(this,t),u(this,"point",void 0),u(this,"isLeft",void 0),u(this,"segment",void 0),u(this,"otherSE",void 0),u(this,"consumedBy",void 0),void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}return s(t,[{key:"link",value:function(t){if(t.point===this.point)throw new Error("Tried to link already linked events");for(var e=t.point.events,n=0,r=e.length;n0&&(t=r)}for(var i=t.segment.prevInResult(),o=i?i.prevInResult():null;;){if(!i)return null;if(!o)return i.ringOut;var s,a;if(o.ringOut!==i.ringOut)return(null===(s=o.ringOut)||void 0===s?void 0:s.enclosingRing())!==i.ringOut?i.ringOut:null===(a=i.ringOut)||void 0===a?void 0:a.enclosingRing();i=o.prevInResult(),o=i?i.prevInResult():null}}}],[{key:"factory",value:function(e){for(var n=[],r=0,i=e.length;r1&&void 0!==arguments[1]?arguments[1]:Ls.compare;i(this,t),u(this,"queue",void 0),u(this,"tree",void 0),u(this,"segments",void 0),this.queue=e,this.tree=new ns(n),this.segments=[]}),[{key:"process",value:function(t){var e=t.segment,n=[];if(t.consumedBy)return t.isLeft?this.queue.delete(t.otherSE):this.tree.delete(e),n;t.isLeft&&this.tree.add(e);var r=e,i=e;do{r=this.tree.lastBefore(r)}while(null!=r&&null!=r.consumedBy);do{i=this.tree.firstAfter(i)}while(null!=i&&null!=i.consumedBy);if(t.isLeft){var o=null;if(r){var s=r.getIntersection(e);if(null!==s&&(e.isAnEndpoint(s)||(o=s),!r.isAnEndpoint(s)))for(var a=this._splitSafely(r,s),u=0,l=a.length;u0?(this.tree.delete(e),n.push(t)):(this.segments.push(e),e.prev=r)}else{if(r&&i){var _=r.getIntersection(i);if(null!==_){if(!r.isAnEndpoint(_))for(var x=this._splitSafely(r,_),E=0,k=x.length;E0&&a.swapEvents(),Es.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}},{key:"swapEvents",value:function(){var t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(var e=0,n=this.windings.length;e0){var o=n;n=r,r=o}if(n.prev===r){var s=n;n=r,r=s}for(var a=0,u=r.rings.length;a0)return-1;var c=e.comparePoint(t.rightSE.point);return 0!==c?c:-1}if(n.isGreaterThan(r)){if(s.isLessThan(a)&&s.isLessThan(l))return-1;if(s.isGreaterThan(a)&&s.isGreaterThan(l))return 1;var f=e.comparePoint(t.leftSE.point);if(0!==f)return f;var g=t.comparePoint(e.rightSE.point);return g<0?1:g>0?-1:1}if(s.isLessThan(a))return-1;if(s.isGreaterThan(a))return 1;if(i.isLessThan(o)){var p=e.comparePoint(t.rightSE.point);if(0!==p)return p}if(i.isGreaterThan(o)){var v=t.comparePoint(e.rightSE.point);if(v<0)return 1;if(v>0)return-1}if(!i.eq(o)){var d=u.minus(s),y=i.minus(n),m=l.minus(a),_=o.minus(r);if(d.isGreaterThan(y)&&m.isLessThan(_))return 1;if(d.isLessThan(y)&&m.isGreaterThan(_))return-1}return i.isGreaterThan(o)?1:i.isLessThan(o)||u.isLessThan(l)?-1:u.isGreaterThan(l)?1:t.ide.id?1:0}},{key:"fromRing",value:function(e,n,r){var i,o,s,a=Es.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else{if(!(a>0))throw new Error("Tried to create degenerate segment at [".concat(e.x,", ").concat(e.y,"]"));i=n,o=e,s=-1}return new t(new Es(i,!0),new Es(o,!1),[r],[s])}}])}(),Ps=function(){return s((function t(e,n,r){if(i(this,t),u(this,"poly",void 0),u(this,"isExterior",void 0),u(this,"segments",void 0),u(this,"bbox",void 0),!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");var o=fs.snap({x:new $o(e[0][0]),y:new $o(e[0][1])});this.bbox={ll:{x:o.x,y:o.y},ur:{x:o.x,y:o.y}};for(var s=o,a=1,l=e.length;a1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r2&&void 0!==arguments[2]?arguments[2]:2,r=K(t),i=K(e),o=r[0]-i[0],s=r[1]-i[1];return 1===n?Math.abs(o)+Math.abs(s):Math.pow(Math.pow(o,n)+Math.pow(s,n),1/n)}function Gs(t,e){var n,r,i=(e=e||{}).threshold||1e4,o=e.p||2,s=null!=(n=e.binary)&&n,a=e.alpha||-1,u=null!=(r=e.standardization)&&r,l=[];vt(t,(function(t){l.push(gi(t))}));for(var h=[],c=0;c3&&void 0!==arguments[3]?arguments[3]:{},i=e<0,o=j(Math.abs(e),r.units,"meters");i&&(o=-Math.abs(o));var s=K(t),a=function(t,e,n,r){r=void 0===r?x:Number(r);var i=e/r,o=t[0]*Math.PI/180,s=z(t[1]),a=z(n),u=i*Math.cos(a),l=s+u;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);var h=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),c=Math.abs(h)>1e-11?u/h:Math.cos(s),f=i*Math.sin(a)/c;return[(180*(o+f)/Math.PI+540)%360-180,180*l/Math.PI]}(s,o,n);return a[0]+=a[0]-s[0]>180?-360:s[0]-a[0]>180?360:0,I(a,r.properties)}function Ys(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e);i[0]+=i[0]-r[0]>180?-360:r[0]-i[0]>180?360:0;var o=function(t,e,n){var r=n=void 0===n?x:Number(n),i=t[1]*Math.PI/180,o=e[1]*Math.PI/180,s=o-i,a=Math.abs(e[0]-t[0])*Math.PI/180;a>Math.PI&&(a-=2*Math.PI);var u=Math.log(Math.tan(o/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),l=Math.abs(u)>1e-11?s/u:Math.cos(i);return Math.sqrt(s*s+l*l*a*a)*r}(r,i);return j(o,"meters",n.units)}function zs(t,e,n){if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.pivot,i=n.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("angle is required");if(0===e)return t;var o=null!=r?r:gi(t);return!1!==i&&void 0!==i||(t=Ai(t)),ct(t,(function(t){var n=lt(o,t)+e,r=Ys(o,t),i=Q(Bs(o,r,n));t[0]=i[0],t[1]=i[1]})),t}function js(t,e,n,r){var i=(r=r||{}).steps||64,o=r.units||"kilometers",s=r.angle||0,a=r.pivot||t,u=r.properties||{};if(!t)throw new Error("center is required");if(!e)throw new Error("xSemiAxis is required");if(!n)throw new Error("ySemiAxis is required");if(!Z(r))throw new Error("options must be an object");if(!U(i))throw new Error("steps must be a number");if(!U(s))throw new Error("angle must be a number");var l=K(t);if("degrees"!==o){var h=Bs(t,e,90,{units:o}),c=Bs(t,n,0,{units:o});e=K(h)[0]-l[0],n=K(c)[1]-l[1]}for(var f=[],g=0;g=-270&&(v=-v),p<-180&&p>=-360&&(d=-d),"degrees"===o){var y=z(s),m=v*Math.cos(y)+d*Math.sin(y),_=d*Math.cos(y)-v*Math.sin(y);v=m,d=_}f.push([v+l[0],d+l[1]])}return f.push(f[0]),"degrees"===o?S([f],u):zs(S([f],u),s,{pivot:a})}function Xs(t){var e=t*Math.PI/180;return Math.tan(e)}function Us(t){return Vt(Rt(t))}function Zs(t){var e=[];return"FeatureCollection"===t.type?vt(t,(function(t){ct(t,(function(n){e.push(I(n,t.properties))}))})):"Feature"===t.type?ct(t,(function(n){e.push(I(n,t.properties))})):ct(t,(function(t){e.push(I(t))})),C(e)}var Hs=Math.PI/180,Ws=180/Math.PI,Js=function(t,e){this.lon=t,this.lat=e,this.x=Hs*t,this.y=Hs*e};Js.prototype.view=function(){return String(this.lon).slice(0,4)+","+String(this.lat).slice(0,4)},Js.prototype.antipode=function(){var t=-1*this.lat,e=this.lon<0?180+this.lon:-1*(180-this.lon);return new Js(e,t)};var Ks=function(){this.coords=[],this.length=0};Ks.prototype.move_to=function(t){this.length++,this.coords.push(t)};var Qs=function(t){this.properties=t||{},this.geometries=[]};Qs.prototype.json=function(){if(this.geometries.length<=0)return{geometry:{type:"LineString",coordinates:null},type:"Feature",properties:this.properties};if(1===this.geometries.length)return{geometry:{type:"LineString",coordinates:this.geometries[0].coords},type:"Feature",properties:this.properties};for(var t=[],e=0;e1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must specify at least 2 geometries");var r=Rs.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)}function ea(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.stringify(n.properties||{}),i=v(t,4),o=i[0],s=i[1],a=i[2],u=i[3],l=(s+u)/2,h=(o+a)/2,c=2*e/ut([o,l],[a,l],n)*(a-o),f=2*e/ut([h,s],[h,u],n)*(u-s),g=c/2,p=2*g,d=Math.sqrt(3)/2*f,y=a-o,m=u-s,_=3/4*p,x=d,E=(y-p)/(p-g/2),k=Math.floor(E),b=(k*_-g/2-y)/2-g/2+_/2,w=Math.floor((m-d)/d),I=(m-w*d)/2,N=w*d-m>d/2;N&&(I-=d/4);for(var S=[],M=[],L=0;L<6;L++){var P=2*Math.PI/6*L;S.push(Math.cos(P)),M.push(Math.sin(P))}for(var T=[],O=0;O<=k;O++)for(var R=0;R<=w;R++){var A=O%2==1;if((0!==R||!A)&&(0!==R||!N)){var D=O*_+o-b,F=R*x+s+I;if(A&&(F-=d/2),!0===n.triangles)ra([D,F],c/2,f/2,JSON.parse(r),S,M).forEach((function(t){n.mask?ta(C([n.mask,t]))&&T.push(t):T.push(t)}));else{var q=na([D,F],c/2,f/2,JSON.parse(r),S,M);n.mask?ta(C([n.mask,q]))&&T.push(q):T.push(q)}}}return C(T)}function na(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=t[0]+e*i[a],l=t[1]+n*o[a];s.push([u,l])}return s.push(s[0].slice()),S([s],r)}function ra(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=[];u.push(t),u.push([t[0]+e*i[a],t[1]+n*o[a]]),u.push([t[0]+e*i[(a+1)%6],t[1]+n*o[(a+1)%6]]),u.push(t),s.push(S([u],r))}return s}function ia(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.mask&&!n.units&&(n.units="kilometers");for(var r=[],i=t[0],o=t[1],s=t[2],a=t[3],u=e/ut([i,o],[s,o],n)*(s-i),l=e/ut([i,o],[i,a],n)*(a-o),h=s-i,c=a-o,f=Math.floor(h/u),g=(c-Math.floor(c/l)*l)/2,p=i+(h-f*u)/2;p<=s;){for(var v=o+g;v<=a;){var d=I([p,v],n.properties);n.mask?Cn(d,n.mask)&&r.push(d):r.push(d),v+=l}p+=u}return C(r)}function oa(t,e,n){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=[],o=t[0],s=t[1],a=t[2],u=t[3],l=a-o,h=j(e,r.units,"degrees"),c=u-s,f=j(n,r.units,"degrees"),g=Math.floor(Math.abs(l)/h),p=Math.floor(Math.abs(c)/f),v=(c-p*f)/2,d=o+(l-g*h)/2,y=0;y2&&void 0!==arguments[2]?arguments[2]:{})}function aa(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=[],i=e/ut([t[0],t[1]],[t[2],t[1]],n)*(t[2]-t[0]),o=e/ut([t[0],t[1]],[t[0],t[3]],n)*(t[3]-t[1]),s=0,a=t[0];a<=t[2];){for(var u=0,l=t[1];l<=t[3];){var h=null,c=null;s%2==0&&u%2==0?(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)):s%2==0&&u%2==1?(h=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties)):u%2==0&&s%2==1?(h=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties),c=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties)):u%2==1&&s%2==1&&(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)),n.mask?(ta(C([n.mask,h]))&&r.push(h),ta(C([n.mask,c]))&&r.push(c)):(r.push(h),r.push(c)),l+=o,u++}s++,a+=i}return C(r)} +/*! + * MarchingSquaresJS + * version 1.3.3 + * https://github.com/RaumZeit/MarchingSquares.js + * + * @license GNU Affero General Public License. + * Copyright (c) 2015-2019 Ronny Lorenz + */ +function ua(t,e,n){return tr&&(i=n,n=r,r=i),tr?(t-r)/(t-e):(t-n)/(t-e)}function ha(t,e,n,r){return t1){for(;0!==o;)o>>=1,a++;r===1<1){for(;0!==s;)s>>=1,u++;i===1<0&&(this.childB=new da(t,e+o,n,r-o,s),this.lowerBound=Math.min(this.lowerBound,this.childB.lowerBound),this.upperBound=Math.max(this.upperBound,this.childB.upperBound),i-s>0&&(this.childC=new da(t,e+o,n+s,r-o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childC.lowerBound),this.upperBound=Math.max(this.upperBound,this.childC.upperBound))),i-s>0&&(this.childD=new da(t,e,n+s,o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childD.lowerBound),this.upperBound=Math.max(this.upperBound,this.childD.upperBound))}}function ya(t){var e,n;if(!t)throw new Error("data is required");if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Error("data must be scalar field, i.e. array of arrays");if(t.length<2)throw new Error("data must contain at least two rows");if((n=t[0].length)<2)throw new Error("data must contain at least two columns");for(e=1;e=e||t[s][r-1]>=e){n=!1;break}if(n&&(t[i-1][0]>=e||t[i-1][r-1]>=e)&&(n=!1),n)for(o=0;o=e||t[i-1][o]>e){n=!1;break}return n}(t,n.threshold)&&(n.linearRing?_.push([[0,0],[0,x],[E,x],[E,0],[0,0]]):_.push([[0,0],[0,x],[E,x],[E,0]])),e.forEach((function(t,N){t.forEach((function(t,S){for(r=null,i=0;i<4;i++)if(r=k[i],"object"===m(t.edges[r])){for(a=[],o=t.edges[r],u=r,l=N,h=S,c=!1,f=[N+o.path[0][0],S+o.path[0][1]],a.push(f);!c&&"object"===m((s=e[l][h]).edges[u]);)if(o=s.edges[u],delete s.edges[u],(g=o.path[1])[0]+=l,g[1]+=h,a.push(g),u=o.move.enter,l+=o.move.x,h+=o.move.y,void 0===e[l]||void 0===e[l][h]){if(!n.linearRing)break;if(p=0,v=0,l===E?(l--,p=0):l<0?(l++,p=2):h===x?(h--,p=3):h<0&&(h++,p=1),l===N&&h===S&&p===I[r]){c=!0,u=r;break}for(;;){if(d=!1,v>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[l]&&void 0!==e[l][h]&&(s=e[l][h],y=k[p],"object"===m(s.edges[y]))){o=s.edges[y],a.push(pa(l,h,p,o.path)),u=y,d=!0;break}if(d)break;if(a.push(va(l,h,p)),h+=w[p],void 0!==e[l+=b[p]]&&void 0!==e[l][h]||(0===p&&h<0||1===p&&l<0||2===p&&h===x||3===p&&l===E)&&(l-=b[p],h-=w[p],p=(p+1)%4,v++),l===N&&h===S&&p===I[r]){c=!0,u=r;break}}}!n.linearRing||a[a.length-1][0]===f[0]&&a[a.length-1][1]===f[1]||a.push(f),_.push(a)}}))})),_}(h,c,r)}a?g.push(f):g=f,"function"==typeof r.successCallback&&r.successCallback(g,t)})),g}function _a(t,e,n,r){var i,o,s,a,u,l,h=0,c=t[n+1][e],f=t[n+1][e+1],g=t[n][e+1],p=t[n][e],v=r.threshold;if(!(isNaN(p)||isNaN(g)||isNaN(f)||isNaN(c))){switch(h|=c>=v?8:0,h|=f>=v?4:0,h|=g>=v?2:0,l={cval:h=+(h|=p>=v?1:0),polygons:[],edges:{},x0:p,x1:g,x2:f,x3:c},h){case 0:r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,0]]);break;case 15:break;case 14:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.left={path:[[0,i],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[a,0]]);break;case 13:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[a,0],[1,o],[1,0]]);break;case 11:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[1,o],[s,1],[1,1]]);break;case 7:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[s,1],[0,i],[0,1]]);break;case 1:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[a,0],[0,i],[0,1],[1,1],[1,0]]);break;case 2:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,o],[a,0]]);break;case 4:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[1,o],[1,0]]);break;case 8:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[s,1],[1,1],[1,0]]);break;case 12:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[1,o],[1,0]]);break;case 9:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[a,0],[s,1],[1,1],[1,0]]);break;case 3:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[0,i],[0,1],[1,1],[1,o]]);break;case 6:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[a,0]]);break;case 10:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),u=(p+g+f+c)/4,r.polygons_full&&(uf&&(v>h&&ph&&vu&&(u=d)}var y=[];if(a&&u0&&Math.abs(x-n[_-1][0])>f){var E=parseFloat(n[_-1][0]),k=parseFloat(n[_-1][1]),b=parseFloat(n[_][0]),w=parseFloat(n[_][1]);if(E>-180&&E-180&&n[_-1][0]h&&E<180&&-180===b&&_+1h&&n[_-1][0]<180){m.push([180,n[_][1]]),_++,m.push([n[_][0],n[_][1]]);continue}if(Eh){var I=E;E=b,b=I;var N=k;k=w,w=N}if(E>h&&b=180&&Eh?180:-180,M]),(m=[]).push([n[_-1][0]>h?-180:180,M]),y.push(m)}else m=[],y.push(m);m.push([x,n[_][1]])}else m.push([n[_][0],n[_][1]])}}else{var L=[];y.push(L);for(var P=0;Pe||this.upperBound=e)&&r.push({x:this.x,y:this.y})),r},da.prototype.cellsBelowThreshold=function(t,e){var n=[];return e=void 0===e||e,this.lowerBound>t||(this.childA||this.childB||this.childC||this.childD?(this.childA&&(n=n.concat(this.childA.cellsBelowThreshold(t,e))),this.childB&&(n=n.concat(this.childB.cellsBelowThreshold(t,e))),this.childD&&(n=n.concat(this.childD.cellsBelowThreshold(t,e))),this.childC&&(n=n.concat(this.childC.cellsBelowThreshold(t,e)))):(e||this.upperBound>=t)&&n.push({x:this.x,y:this.y})),n};var xa={square:function(t,e,n,r,i,o){o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,0]])},triangle_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,a],[s,0],[0,0]])},triangle_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[1,a],[1,0]])},triangle_tr:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[1,s],[a,1],[1,1]])},triangle_tl:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[s,1]])},tetragon_t:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[1,1],[1,s]])},tetragon_r:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[a,1],[1,1],[1,0]])},tetragon_b:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,0]])},tetragon_l:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[a,0]])},tetragon_bl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[a,0]])},tetragon_br:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate_b(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[1,l]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[1,l],[1,u],[a,0]])},tetragon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rb={path:[[1,l],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}}),o.polygons&&t.polygons.push([[1,l],[s,1],[a,1],[1,u]])},tetragon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[0,l]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[a,1],[0,l],[0,u],[s,1]])},tetragon_lr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[1,u],[1,l]])},tetragon_tb:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[l,0],[s,1],[a,1],[u,0]])},pentagon_tr:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[1,a],[1,0]])},pentagon_tl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,0]])},pentagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,a],[s,0]])},pentagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[a,0],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[1,1],[1,0],[a,0]])},pentagon_tr_rl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[1,u],[1,l]])},pentagon_rb_bt:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,n,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[u,0],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[l,1],[1,1],[1,s],[a,0],[u,0]])},pentagon_bl_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[1,l],[1,0]])},pentagon_lt_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[l,0]])},pentagon_bl_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[l,0],[0,s]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[u,0],[l,0]])},pentagon_lt_rl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[u,1],[1,1],[1,l]])},pentagon_tr_bt:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,1],[a,1],[1,u],[1,0],[l,0]])},pentagon_rb_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_b(n,r,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,u],[l,0]])},hexagon_lt_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[1,l],[1,0]])},hexagon_bl_lt:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[1,1],[1,0]])},hexagon_bl_rb:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.rt={path:[[1,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[1,1],[1,l],[a,0]])},hexagon_tr_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[a,1],[1,u],[1,l],[s,0]])},hexagon_lt_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,u],[l,0]])},hexagon_bl_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,1],[u,1],[1,l],[1,0]])},heptagon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[1,1],[1,c],[a,0]])},heptagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate_a(i,r,o.minV,o.maxV),l=o.interpolate_b(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,a],[u,1],[l,1],[1,h],[1,c],[s,0]])},heptagon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[l,1],[1,h],[1,c],[a,0]])},heptagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(i,r,o.minV,o.maxV),h=o.interpolate_b(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[h,1],[1,c]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[h,1],[1,c],[1,0]])},octagon:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate_a(i,r,o.minV,o.maxV),c=o.interpolate_b(i,r,o.minV,o.maxV),f=o.interpolate_b(n,r,o.minV,o.maxV),g=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[c,1],[1,f]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,g],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[c,1],[1,f],[1,g],[a,0]])}};function Ea(t,e,n,r){var i,o,s,a=!1,u=null,l=null,h=null,c=null,f=!1,g=[],p=[],v=[];if(!t)throw new Error("data is required");if(null==e)throw new Error("lowerBound is required");if(null==n)throw new Error("bandWidth is required");if(s=function(t){var e,n,r,i,o;for(i=new fa,t=t||{},o=Object.keys(i),e=0;en||t[a][i-1]n){r=!1;break}if(r&&(t[o-1][0]n||t[o-1][i-1]n)&&(r=!1),r)for(s=0;sn||t[o-1][s]n){r=!1;break}return r}(t,n.minV,n.maxV)&&(n.linearRing?x.push([[0,0],[0,E],[k,E],[k,0],[0,0]]):x.push([[0,0],[0,E],[k,E],[k,0]])),e.forEach((function(t,M){t.forEach((function(t,L){for(r=null,o=0;o<8;o++)if(r=N[o],"object"===m(t.edges[r])){for(i=[],s=t.edges[r],l=r,h=M,c=L,f=!1,g=[M+s.path[0][0],L+s.path[0][1]],i.push(g);!f&&"object"===m((p=e[h][c]).edges[l]);)if(s=p.edges[l],delete p.edges[l],(y=s.path[1])[0]+=h,y[1]+=c,i.push(y),l=s.move.enter,h+=s.move.x,c+=s.move.y,void 0===e[h]||void 0===e[h][c]){if(v=0,d=0,h===k)h--,v=0;else if(h<0)h++,v=2;else if(c===E)c--,v=3;else{if(!(c<0))throw new Error("Left the grid somewhere in the interior!");c++,v=1}if(h===M&&c===L&&v===S[r]){f=!0,l=r;break}for(;;){if(_=!1,d>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[h]&&void 0!==e[h][c])for(p=e[h][c],a=0;ao?2:sf?128:64,s|=uf?32:16,s|=lf?8:4,o=0,i={cval:s=+(s|=hf?2:1),polygons:[],edges:{},x0:h,x1:l,x2:u,x3:a,x:e,y:n},s){case 85:xa.square(i,h,l,u,a,r);case 0:case 170:break;case 169:xa.triangle_bl(i,h,l,u,a,r);break;case 166:xa.triangle_br(i,h,l,u,a,r);break;case 154:xa.triangle_tr(i,h,l,u,a,r);break;case 106:xa.triangle_tl(i,h,l,u,a,r);break;case 1:xa.triangle_bl(i,h,l,u,a,r);break;case 4:xa.triangle_br(i,h,l,u,a,r);break;case 16:xa.triangle_tr(i,h,l,u,a,r);break;case 64:xa.triangle_tl(i,h,l,u,a,r);break;case 168:xa.tetragon_bl(i,h,l,u,a,r);break;case 162:xa.tetragon_br(i,h,l,u,a,r);break;case 138:xa.tetragon_tr(i,h,l,u,a,r);break;case 42:xa.tetragon_tl(i,h,l,u,a,r);break;case 2:xa.tetragon_bl(i,h,l,u,a,r);break;case 8:xa.tetragon_br(i,h,l,u,a,r);break;case 32:xa.tetragon_tr(i,h,l,u,a,r);break;case 128:xa.tetragon_tl(i,h,l,u,a,r);break;case 5:xa.tetragon_b(i,h,l,u,a,r);break;case 20:xa.tetragon_r(i,h,l,u,a,r);break;case 80:xa.tetragon_t(i,h,l,u,a,r);break;case 65:xa.tetragon_l(i,h,l,u,a,r);break;case 165:xa.tetragon_b(i,h,l,u,a,r);break;case 150:xa.tetragon_r(i,h,l,u,a,r);break;case 90:xa.tetragon_t(i,h,l,u,a,r);break;case 105:xa.tetragon_l(i,h,l,u,a,r);break;case 160:xa.tetragon_lr(i,h,l,u,a,r);break;case 130:xa.tetragon_tb(i,h,l,u,a,r);break;case 10:xa.tetragon_lr(i,h,l,u,a,r);break;case 40:xa.tetragon_tb(i,h,l,u,a,r);break;case 101:xa.pentagon_tr(i,h,l,u,a,r);break;case 149:xa.pentagon_tl(i,h,l,u,a,r);break;case 86:xa.pentagon_bl(i,h,l,u,a,r);break;case 89:xa.pentagon_br(i,h,l,u,a,r);break;case 69:xa.pentagon_tr(i,h,l,u,a,r);break;case 21:xa.pentagon_tl(i,h,l,u,a,r);break;case 84:xa.pentagon_bl(i,h,l,u,a,r);break;case 81:xa.pentagon_br(i,h,l,u,a,r);break;case 96:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 24:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 6:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 129:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 74:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 146:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 164:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 41:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 66:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 144:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 36:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 9:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 104:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 26:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 134:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 161:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 37:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 148:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 82:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 73:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 133:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 22:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 88:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 97:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 145:case 25:xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 70:case 100:xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 17:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 68:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 153:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 102:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 152:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 137:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 98:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 38:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 18:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 33:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 72:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 132:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 136:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r));break;case 34:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r))}return i}}var wa=Object.defineProperty,Ia=Object.getOwnPropertySymbols,Na=Object.prototype.hasOwnProperty,Sa=Object.prototype.propertyIsEnumerable,Ma=function(t,e,n){return e in t?wa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},La=function(t,e){for(var n in e||(e={}))Na.call(e,n)&&Ma(t,n,e[n]);if(Ia){var r,i=a(Ia(e));try{for(i.s();!(r=i.n()).done;){n=r.value;Sa.call(e,n)&&Ma(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t};function Pa(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.zProperty||"elevation",r=e.flip,i=e.flags;nt(t,"Point","input must contain Points");for(var o=function(t,e){var n={};vt(t,(function(t){var e=Q(t)[1];n[e]||(n[e]=[]),n[e].push(t)}));var r=Object.keys(n).map((function(t){return n[t].sort((function(t,e){return Q(t)[0]-Q(e)[0]}))})),i=r.sort((function(t,n){return e?Q(t[0])[1]-Q(n[0])[1]:Q(n[0])[1]-Q(t[0])[1]}));return i}(t,r),s=[],a=0;a=0&&l<=1&&(f.onLine1=!0),h>=0&&h<=1&&(f.onLine2=!0),!(!f.onLine1||!f.onLine2)&&[f.x,f.y])}function za(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return bt(t,(function(t,n){var r=n.geometry.coordinates;return t+ut(r[0],r[1],e)}),0)}function ja(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=i.steps||64,s=Xa(n),a=Xa(r),u=Array.isArray(t)||"Feature"!==t.type?{}:t.properties;if(s===a)return L(Ri(t,e,i).geometry.coordinates[0],u);for(var l=s,h=s=h&&c===i.length-1);c++){if(h>e&&0===o.length){if(!(s=e-h))return o.push(i[c]),L(o);a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates)}if(h>=n)return(s=n-h)?(a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates),L(o)):(o.push(i[c]),L(o));if(h>=e&&o.push(i[c]),c===i.length-1)return L(o);h+=ut(i[c],i[c+1],r)}if(h0){var a=r[e-1],u=Wa(n,a);!1!==u&&(a[1]=u,n[0]=u),s.push(a[0]),e===o.length-2&&(s.push(n[0]),s.push(n[1]))}2===o.length&&(s.push(n[0]),s.push(n[1]))}var l,h,c,f,g,p,v,d})),L(s,t.properties)}function Ka(t){var e=t[0],n=t[1],r=t[2],i=t[3];if(ut(t.slice(0,2),[r,n])>=ut(t.slice(0,2),[e,i])){var o=(n+i)/2;return[e,o-(r-e)/2,r,o+(r-e)/2]}var s=(e+r)/2;return[s-(i-n)/2,n,s+(i-n)/2,i]}function Qa(t,e){if(!Z(e=null!=e?e:{}))throw new Error("options is invalid");var n=e.precision,r=e.coordinates,i=e.mutate;if(n=null==n||isNaN(n)?6:n,r=null==r||isNaN(r)?3:r,!t)throw new Error(" is required");if("number"!=typeof n)throw new Error(" must be a number");if("number"!=typeof r)throw new Error(" must be a number");!1!==i&&void 0!==i||(t=JSON.parse(JSON.stringify(t)));var o=Math.pow(10,n);return ct(t,(function(t){!function(t,e,n){t.length>n&&t.splice(n,t.length);for(var r=0;r1&&n.push(L(l)),C(n)}function eu(t,e){if(!e.features.length)throw new Error("lines must contain features");if(1===e.features.length)return e.features[0];var n,r=1/0;return vt(e,(function(e){var i=fn(e,t).properties.dist;iu?(a.unshift(t),u=e):a.push(t)}else a.push(t)})),S(a,e);default:throw new Error("geometry type "+s+" is not supported")}}function iu(t){var e=t[0],n=e[0],r=e[1],i=t[t.length-1],o=i[0],s=i[1];return n===o&&r===s||t.push(e),t}function ou(t){return R(t)}function su(t){var e=[[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]];return t&&(e="Feature"===t.type?t.geometry.coordinates:t.coordinates),S(e)}function au(t){var e,n=0,r=a(t);try{for(r.s();!(e=r.n()).done;){n+=e.value}}catch(t){r.e(t)}finally{r.f()}return n/t.length}var uu=Object.defineProperty,lu=Object.defineProperties,hu=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,fu=Object.prototype.hasOwnProperty,gu=Object.prototype.propertyIsEnumerable,pu=function(t,e,n){return e in t?uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},vu=function(t,e){for(var n in e||(e={}))fu.call(e,n)&&pu(t,n,e[n]);if(cu){var r,i=a(cu(e));try{for(i.s();!(r=i.n()).done;){n=r.value;gu.call(e,n)&&pu(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},du=function(t,e){return lu(t,hu(e))};function yu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("targetPoint is required");if(!e)throw new Error("points is required");var r=1/0,i=0;vt(e,(function(e,o){var s=ut(t,e,n);s2&&void 0!==arguments[2]?arguments[2]:{},o=null!=(n=i.method)?n:"geodesic",s=null!=(r=i.units)?r:"kilometers";if(!t)throw new Error("pt is required");if(Array.isArray(t)?t=I(t):"Point"===t.type?t=b(t):et(t,"Point","point"),!e)throw new Error("line is required");Array.isArray(e)?e=L(e):"LineString"===e.type?e=b(e):et(e,"LineString","line");var a=1/0,u=t.geometry.coordinates;return kt(e,(function(t){if(t){var e=t.geometry.coordinates[0],n=t.geometry.coordinates[1],r=function(t,e,n,r){if("geodesic"===r.method){return fn(L([e,n]).geometry,t,{units:"degrees"}).properties.dist}var i=[n[0]-e[0],n[1]-e[1]],o=[t[0]-e[0],t[1]-e[1]],s=_u(o,i);if(s<=0)return Ys(t,e,{units:"degrees"});var a=_u(i,i);if(a<=s)return Ys(t,n,{units:"degrees"});var u=s/a,l=[e[0]+u*i[0],e[1]+u*i[1]];return Ys(t,l,{units:"degrees"})}(u,e,n,{method:o});r0)-(t<0)||+t}(r*(n[1]-e[1])-o*i)}function Lu(t,e){return e.geometry.coordinates[0].every((function(e){return zt(I(e),t)}))}var Pu=function(){return s((function t(e){i(this,t),this.id=t.buildId(e),this.coordinates=e,this.innerEdges=[],this.outerEdges=[],this.outerEdgesSorted=!1}),[{key:"removeInnerEdge",value:function(t){this.innerEdges=this.innerEdges.filter((function(e){return e.from.id!==t.from.id}))}},{key:"removeOuterEdge",value:function(t){this.outerEdges=this.outerEdges.filter((function(e){return e.to.id!==t.to.id}))}},{key:"addOuterEdge",value:function(t){this.outerEdges.push(t),this.outerEdgesSorted=!1}},{key:"sortOuterEdges",value:function(){var t=this;this.outerEdgesSorted||(this.outerEdges.sort((function(e,n){var r=e.to,i=n.to;if(r.coordinates[0]-t.coordinates[0]>=0&&i.coordinates[0]-t.coordinates[0]<0)return 1;if(r.coordinates[0]-t.coordinates[0]<0&&i.coordinates[0]-t.coordinates[0]>=0)return-1;if(r.coordinates[0]-t.coordinates[0]==0&&i.coordinates[0]-t.coordinates[0]==0)return r.coordinates[1]-t.coordinates[1]>=0||i.coordinates[1]-t.coordinates[1]>=0?r.coordinates[1]-i.coordinates[1]:i.coordinates[1]-r.coordinates[1];var o=Mu(t.coordinates,r.coordinates,i.coordinates);return o<0?1:o>0?-1:Math.pow(r.coordinates[0]-t.coordinates[0],2)+Math.pow(r.coordinates[1]-t.coordinates[1],2)-(Math.pow(i.coordinates[0]-t.coordinates[0],2)+Math.pow(i.coordinates[1]-t.coordinates[1],2))})),this.outerEdgesSorted=!0)}},{key:"getOuterEdges",value:function(){return this.sortOuterEdges(),this.outerEdges}},{key:"getOuterEdge",value:function(t){return this.sortOuterEdges(),this.outerEdges[t]}},{key:"addInnerEdge",value:function(t){this.innerEdges.push(t)}}],[{key:"buildId",value:function(t){return t.join(",")}}])}(),Cu=function(){function t(e,n){i(this,t),this.from=e,this.to=n,this.next=void 0,this.label=void 0,this.symetric=void 0,this.ring=void 0,this.from.addOuterEdge(this),this.to.addInnerEdge(this)}return s(t,[{key:"getSymetric",value:function(){return this.symetric||(this.symetric=new t(this.to,this.from),this.symetric.symetric=this),this.symetric}},{key:"deleteEdge",value:function(){this.from.removeOuterEdge(this),this.to.removeInnerEdge(this)}},{key:"isEqual",value:function(t){return this.from.id===t.from.id&&this.to.id===t.to.id}},{key:"toString",value:function(){return"Edge { ".concat(this.from.id," -> ").concat(this.to.id," }")}},{key:"toLineString",value:function(){return L([this.from.coordinates,this.to.coordinates])}},{key:"compareTo",value:function(t){return Mu(t.from.coordinates,t.to.coordinates,this.to.coordinates)}}])}(),Tu=function(){return s((function t(){i(this,t),this.edges=[],this.polygon=void 0,this.envelope=void 0}),[{key:"push",value:function(t){this.edges.push(t),this.polygon=this.envelope=void 0}},{key:"get",value:function(t){return this.edges[t]}},{key:"length",get:function(){return this.edges.length}},{key:"forEach",value:function(t){this.edges.forEach(t)}},{key:"map",value:function(t){return this.edges.map(t)}},{key:"some",value:function(t){return this.edges.some(t)}},{key:"isValid",value:function(){return!0}},{key:"isHole",value:function(){var t=this,e=this.edges.reduce((function(e,n,r){return n.from.coordinates[1]>t.edges[e].from.coordinates[1]&&(e=r),e}),0),n=(0===e?this.length:e)-1,r=(e+1)%this.length,i=Mu(this.edges[n].from.coordinates,this.edges[e].from.coordinates,this.edges[r].from.coordinates);return 0===i?this.edges[n].from.coordinates[0]>this.edges[r].from.coordinates[0]:i>0}},{key:"toMultiPoint",value:function(){return O(this.edges.map((function(t){return t.from.coordinates})))}},{key:"toPolygon",value:function(){if(this.polygon)return this.polygon;var t=this.edges.map((function(t){return t.from.coordinates}));return t.push(this.edges[0].from.coordinates),this.polygon=S([t])}},{key:"getEnvelope",value:function(){return this.envelope?this.envelope:this.envelope=Us(this.toPolygon())}},{key:"inside",value:function(t){return zt(t,this.toPolygon())}}],[{key:"findEdgeRingContaining",value:function(t,e){var n,r,i=t.getEnvelope();return e.forEach((function(e){var o,s,u,l,h,c,f=e.getEnvelope();if((r&&(n=r.getEnvelope()),s=i,u=(o=f).geometry.coordinates[0].map((function(t){return t[0]})),l=o.geometry.coordinates[0].map((function(t){return t[1]})),h=s.geometry.coordinates[0].map((function(t){return t[0]})),c=s.geometry.coordinates[0].map((function(t){return t[1]})),Math.max.apply(null,u)!==Math.max.apply(null,h)||Math.max.apply(null,l)!==Math.max.apply(null,c)||Math.min.apply(null,u)!==Math.min.apply(null,h)||Math.min.apply(null,l)!==Math.min.apply(null,c))&&Lu(f,i)){var g,p,v=a(t.map((function(t){return t.from.coordinates})));try{var d=function(){var t=p.value;e.some((function(e){return n=t,r=e.from.coordinates,n[0]===r[0]&&n[1]===r[1];var n,r}))||(g=t)};for(v.s();!(p=v.n()).done;)d()}catch(t){v.e(t)}finally{v.f()}g&&e.inside(I(g))&&(r&&!Lu(n,f)||(r=e))}})),r}}])}();var Ou=function(){function t(){i(this,t),this.edges=[],this.nodes={}}return s(t,[{key:"getNode",value:function(t){var e=Pu.buildId(t),n=this.nodes[e];return n||(n=this.nodes[e]=new Pu(t)),n}},{key:"addEdge",value:function(t,e){var n=new Cu(t,e),r=n.getSymetric();this.edges.push(n),this.edges.push(r)}},{key:"deleteDangles",value:function(){var t=this;Object.keys(this.nodes).map((function(e){return t.nodes[e]})).forEach((function(e){return t._removeIfDangle(e)}))}},{key:"_removeIfDangle",value:function(t){var e=this;if(t.innerEdges.length<=1){var n=t.getOuterEdges().map((function(t){return t.to}));this.removeNode(t),n.forEach((function(t){return e._removeIfDangle(t)}))}}},{key:"deleteCutEdges",value:function(){var t=this;this._computeNextCWEdges(),this._findLabeledEdgeRings(),this.edges.forEach((function(e){e.label===e.symetric.label&&(t.removeEdge(e.symetric),t.removeEdge(e))}))}},{key:"_computeNextCWEdges",value:function(t){var e=this;void 0===t?Object.keys(this.nodes).forEach((function(t){return e._computeNextCWEdges(e.nodes[t])})):t.getOuterEdges().forEach((function(e,n){t.getOuterEdge((0===n?t.getOuterEdges().length:n)-1).symetric.next=e}))}},{key:"_computeNextCCWEdges",value:function(t,e){for(var n,r,i=t.getOuterEdges(),o=i.length-1;o>=0;--o){var s=i[o],a=s.symetric,u=void 0,l=void 0;s.label===e&&(u=s),a.label===e&&(l=a),u&&l&&(l&&(r=l),u&&(r&&(r.next=u,r=void 0),n||(n=u)))}r&&(r.next=n)}},{key:"_findLabeledEdgeRings",value:function(){var t=[],e=0;return this.edges.forEach((function(n){if(!(n.label>=0)){t.push(n);var r=n;do{r.label=e,r=r.next}while(!n.isEqual(r));e++}})),t}},{key:"getEdgeRings",value:function(){var t=this;this._computeNextCWEdges(),this.edges.forEach((function(t){t.label=void 0})),this._findLabeledEdgeRings().forEach((function(e){t._findIntersectionNodes(e).forEach((function(n){t._computeNextCCWEdges(n,e.label)}))}));var e=[];return this.edges.forEach((function(n){n.ring||e.push(t._findEdgeRing(n))})),e}},{key:"_findIntersectionNodes",value:function(t){var e=[],n=t,r=function(){var r=0;n.from.getOuterEdges().forEach((function(e){e.label===t.label&&++r})),r>1&&e.push(n.from),n=n.next};do{r()}while(!t.isEqual(n));return e}},{key:"_findEdgeRing",value:function(t){var e=t,n=new Tu;do{n.push(e),e.ring=n,e=e.next}while(!t.isEqual(e));return n}},{key:"removeNode",value:function(t){var e=this;t.getOuterEdges().forEach((function(t){return e.removeEdge(t)})),t.innerEdges.forEach((function(t){return e.removeEdge(t)})),delete this.nodes[t.id]}},{key:"removeEdge",value:function(t){this.edges=this.edges.filter((function(e){return!e.isEqual(t)})),t.deleteEdge()}}],[{key:"fromGeoJson",value:function(e){!function(t){if(!t)throw new Error("No geojson passed");if("FeatureCollection"!==t.type&&"GeometryCollection"!==t.type&&"MultiLineString"!==t.type&&"LineString"!==t.type&&"Feature"!==t.type)throw new Error("Invalid input type '".concat(t.type,"'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature"))}(e);var n=new t;return xt(e,(function(t){et(t,"LineString","Graph::fromGeoJson"),ft(t,(function(t,e){if(t){var r=n.getNode(t),i=n.getNode(e);n.addEdge(r,i)}return e}))})),n}}])}();function Ru(t,e){var n,r;ct(t,(function(t,i,o,s,a){if(r!==a)e.push([]);else{var u=n[0],l=n[1],h=t[0],c=t[1];e[a].push([.75*u+.25*h,.75*l+.25*c]),e[a].push([.25*u+.75*h,.25*l+.75*c])}n=t,r=a}),!1),e.forEach((function(t){t.push(t[0])}))}function Au(t,e){var n,r,i;ct(t,(function(t,o,s,a,u){if(r!==a)e.push([[]]);else if(i!==u)e[a].push([]);else{var l=n[0],h=n[1],c=t[0],f=t[1];e[a][u].push([.75*l+.25*c,.75*h+.25*f]),e[a][u].push([.25*l+.75*c,.25*h+.75*f])}n=t,r=a,i=u}),!1),e.forEach((function(t){t.forEach((function(t){t.push(t[0])}))}))}function Du(t,e,n,r,i){for(var o=0;o0?qu(e,s,r)<0||(r=s):n>0&&u<=0&&(Fu(e,s,i)||(i=s)),n=u}return[r,i]}function Fu(t,e,n){return qu(t,e,n)>0}function qu(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(n[0]-t[0])*(e[1]-t[1])}function Vu(t){return Bu(t,"mercator",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Gu(t){return Bu(t,"wgs84",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Bu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=(n=n||{}).mutate;if(!t)throw new Error("geojson is required");return Array.isArray(t)&&U(t[0])?t="mercator"===e?Yu(t):zu(t):(!0!==r&&(t=Ai(t)),ct(t,(function(t){var n="mercator"===e?Yu(t):zu(t);t[0]=n[0],t[1]=n[1]}))),t}function Yu(t){var e=Math.PI/180,n=6378137,r=20037508.342789244,i=Math.abs(t[0])<=180?t[0]:t[0]-360*function(t){return t<0?-1:t>0?1:0}(t[0]),o=[n*i*e,n*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return o[0]>r&&(o[0]=r),o[0]<-r&&(o[0]=-r),o[1]>r&&(o[1]=r),o[1]<-r&&(o[1]=-r),o}function zu(t){var e=180/Math.PI,n=6378137;return[t[0]*e/n,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/n)))*e]}var ju=Object.freeze({__proto__:null,toMercator:Vu,toWgs84:Gu});var Xu={20:1.07275,15:1.13795,10:1.22385,5:1.3581,2:1.51743,1:1.62762};function Uu(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}function Zu(t){var e=[];return function t(n){return 0===n||1===n?1:e[n]>0?e[n]:e[n]=t(n-1)*n}(t)}function Hu(t){return Ju(t),Wu(t)}function Wu(t){return Array.isArray(t)?el(t):t&&t.bbox?el(t.bbox):[360*tl(),180*tl()]}function Ju(t){null!=t&&(Array.isArray(t)?H(t):null!=t.bbox&&H(t.bbox))}function Ku(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1);for(var n=[],r=0;r1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1),void 0!==e.bbox&&null!==e.bbox||(e.bbox=[-180,-90,180,90]),U(e.num_vertices)&&void 0!==e.num_vertices||(e.num_vertices=10),U(e.max_radial_length)&&void 0!==e.max_radial_length||(e.max_radial_length=10);var n=Math.abs(e.bbox[0]-e.bbox[2]),r=Math.abs(e.bbox[1]-e.bbox[3]),i=Math.min(n/2,r/2);if(e.max_radial_length>i)throw new Error("max_radial_length is greater than the radius of the bbox");for(var o=[e.bbox[0]+e.max_radial_length,e.bbox[1]+e.max_radial_length,e.bbox[2]-e.max_radial_length,e.bbox[3]-e.max_radial_length],s=[],a=function(){var t,n=[],r=d(Array(e.num_vertices+1)).map(Math.random);r.forEach((function(t,e,n){n[e]=e>0?t+n[e-1]:t})),r.forEach((function(t){t=2*t*Math.PI/r[r.length-1];var i=Math.random();n.push([i*(e.max_radial_length||10)*Math.sin(t),i*(e.max_radial_length||10)*Math.cos(t)])})),n[n.length-1]=n[0],n=n.reverse().map((t=Wu(o),function(e){return[e[0]+t[0],e[1]+t[1]]})),s.push(S([n]))},u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox;Ju(n);var r=e.num_vertices,i=e.max_length,o=e.max_rotation;null==t&&(t=1),(!U(r)||void 0===r||r<2)&&(r=10),U(i)&&void 0!==i||(i=1e-4),U(o)&&void 0!==o||(o=Math.PI/8);for(var s=[],a=0;a0;){var l=a.pop();if(l===n)return ll(l);l.closed=!0;for(var h=t.neighbors(l),c=0,f=h.length;c1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function dl(t,e,n,r,i){for(var o,s=r,a=e+1;as&&(o=a,s=u)}s>r&&(o-e>1&&dl(t,e,o,r,i),i.push(t[o]),n-o>1&&dl(t,o,n,r,i))}function yl(t,e){var n=t.length-1,r=[t[0]];return dl(t,0,n,e,r),r.push(t[n]),r}function ml(t,e,n){if(t.length<=2)return t;var r=void 0!==e?e*e:1;return t=n?t:function(t,e){for(var n,r,i,o,s,a=t[0],u=[a],l=1,h=t.length;le&&(u.push(n),a=n);return a!==n&&u.push(n),u}(t,r),t=yl(t,r)}function _l(t,e,n){return t.map((function(t){if(t.length<4)throw new Error("invalid polygon");for(var r=e,i=ml(t,r,n);!xl(i);)i=ml(t,r-=.01*r,n);return i[i.length-1][0]===i[0][0]&&i[i.length-1][1]===i[0][1]||i.push(i[0]),i}))}function xl(t){return!(t.length<3)&&!(3===t.length&&t[2][0]===t[0][0]&&t[2][1]===t[0][1])}function El(t,e){return{x:t[0]-e[0],y:t[1]-e[1]}}cl.prototype.init=function(){this.dirtyNodes=[];for(var t=0;t0&&(this.content[0]=e,this.bubbleUp(0)),t},remove:function(t){var e=this.content.indexOf(t),n=this.content.pop();e!==this.content.length-1&&(this.content[e]=n,this.scoreFunction(n)0;){var n=(t+1>>1)-1,r=this.content[n];if(!(this.scoreFunction(e)80*i){o=a=t[0],s=h=t[1];for(var _=i;_a&&(a=c),g>h&&(h=g);p=0!==(p=Math.max(a-o,h-s))?32767/p:0}return r(y,m,i,o,s,p,0),m}function e(t,e,n,r,i){var o,s;if(i===I(t,e,n,r)>0)for(o=e;o=e;o-=r)s=k(o,t[o],t[o+1],s);return s&&d(s,s.next)&&(b(s),s=s.next),s}function n(t,e){if(!t)return t;e||(e=t);var n,r=t;do{if(n=!1,r.steiner||!d(r,r.next)&&0!==v(r.prev,r,r.next))r=r.next;else{if(b(r),(r=e=r.prev)===r.next)break;n=!0}}while(n||r!==e);return e}function r(t,e,u,l,h,f,g){if(t){!g&&f&&function(t,e,n,r){var i=t;do{0===i.z&&(i.z=c(i.x,i.y,e,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,n,r,i,o,s,a,u,l=1;do{for(n=t,t=null,o=null,s=0;n;){for(s++,r=n,a=0,e=0;e0||u>0&&r;)0!==a&&(0===u||!r||n.z<=r.z)?(i=n,n=n.nextZ,a--):(i=r,r=r.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;n=r}o.nextZ=null,l*=2}while(s>1)}(i)}(t,l,h,f);for(var p,v,d=t;t.prev!==t.next;)if(p=t.prev,v=t.next,f?o(t,l,h,f):i(t))e.push(p.i/u|0),e.push(t.i/u|0),e.push(v.i/u|0),b(t),t=v.next,d=v.next;else if((t=v)===d){g?1===g?r(t=s(n(t),e,u),e,u,l,h,f,2):2===g&&a(t,e,u,l,h,f):r(n(t),e,u,l,h,f,1);break}}}function i(t){var e=t.prev,n=t,r=t.next;if(v(e,n,r)>=0)return!1;for(var i=e.x,o=n.x,s=r.x,a=e.y,u=n.y,l=r.y,h=io?i>s?i:s:o>s?o:s,p=a>u?a>l?a:l:u>l?u:l,d=r.next;d!==e;){if(d.x>=h&&d.x<=f&&d.y>=c&&d.y<=p&&g(i,a,o,u,s,l,d.x,d.y)&&v(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function o(t,e,n,r){var i=t.prev,o=t,s=t.next;if(v(i,o,s)>=0)return!1;for(var a=i.x,u=o.x,l=s.x,h=i.y,f=o.y,p=s.y,d=au?a>l?a:l:u>l?u:l,_=h>f?h>p?h:p:f>p?f:p,x=c(d,y,e,n,r),E=c(m,_,e,n,r),k=t.prevZ,b=t.nextZ;k&&k.z>=x&&b&&b.z<=E;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;if(k=k.prevZ,b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;k&&k.z>=x;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;k=k.prevZ}for(;b&&b.z<=E;){if(b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function s(t,e,r){var i=t;do{var o=i.prev,s=i.next.next;!d(o,s)&&y(o,i,i.next,s)&&x(o,s)&&x(s,o)&&(e.push(o.i/r|0),e.push(i.i/r|0),e.push(s.i/r|0),b(i),b(i.next),i=t=s),i=i.next}while(i!==t);return n(i)}function a(t,e,i,o,s,a){var u=t;do{for(var l=u.next.next;l!==u.prev;){if(u.i!==l.i&&p(u,l)){var h=E(u,l);return u=n(u,u.next),h=n(h,h.next),r(u,e,i,o,s,a,0),void r(h,e,i,o,s,a,0)}l=l.next}u=u.next}while(u!==t)}function u(t,e){return t.x-e.x}function l(t,e){var r=function(t,e){var n,r=e,i=t.x,o=t.y,s=-1/0;do{if(o<=r.y&&o>=r.next.y&&r.next.y!==r.y){var a=r.x+(o-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=i&&a>s&&(s=a,n=r.x=r.x&&r.x>=c&&i!==r.x&&g(on.x||r.x===n.x&&h(n,r)))&&(n=r,p=u)),r=r.next}while(r!==l);return n}(t,e);if(!r)return e;var i=E(r,t);return n(i,i.next),n(r,r.next)}function h(t,e){return v(t.prev,t,e.prev)<0&&v(e.next,t,t.next)<0}function c(t,e,n,r,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function f(t){var e=t,n=t;do{(e.x=(t-s)*(o-a)&&(t-s)*(r-a)>=(n-s)*(e-a)&&(n-s)*(o-a)>=(i-s)*(r-a)}function p(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&y(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(x(t,e)&&x(e,t)&&function(t,e){var n=t,r=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{n.y>o!=n.next.y>o&&n.next.y!==n.y&&i<(n.next.x-n.x)*(o-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==t);return r}(t,e)&&(v(t.prev,t,e.prev)||v(t,e.prev,e))||d(t,e)&&v(t.prev,t,t.next)>0&&v(e.prev,e,e.next)>0)}function v(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function d(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,n,r){var i=_(v(t,e,n)),o=_(v(t,e,r)),s=_(v(n,r,t)),a=_(v(n,r,e));return i!==o&&s!==a||(!(0!==i||!m(t,n,e))||(!(0!==o||!m(t,r,e))||(!(0!==s||!m(n,t,r))||!(0!==a||!m(n,e,r)))))}function m(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function _(t){return t>0?1:t<0?-1:0}function x(t,e){return v(t.prev,t,t.next)<0?v(t,e,t.next)>=0&&v(t,t.prev,e)>=0:v(t,e,t.prev)<0||v(t,t.next,e)<0}function E(t,e){var n=new w(t.i,t.x,t.y),r=new w(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,n.next=i,i.prev=n,r.next=n,n.prev=r,o.next=r,r.prev=o,r}function k(t,e,n,r){var i=new w(t,e,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function b(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 w(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function I(t,e,n,r){for(var i=0,o=e,s=n-r;o0&&(r+=t[i-1].length,n.holes.push(r))}return n},bl.exports}(),Il=mn(wl);function Nl(t){var e=function(t){for(var e=t[0][0].length,n={vertices:[],holes:[],dimensions:e},r=0,i=0;i0&&(r+=t[i-1].length,n.holes.push(r))}return n}(t),n=Il(e.vertices,e.holes,2),r=[],i=[];n.forEach((function(t,r){var o=n[r];i.push([e.vertices[2*o],e.vertices[2*o+1]])}));for(var o=0;o=1||u<=0||l>=1||l<=0))){var v=p,d=!o[v];d&&(o[v]=!0),e?i.push(e(p,t,n,h,c,u,s,a,f,g,l,d)):i.push(p)}}function v(t,e){var n,i,o,s,a=r[t][e],u=r[t][e+1];return a[0]f[e.isect].coord?-1:1}));for(l=[];x.length>0;){var I=x.pop(),N=I.isect,M=I.parent,L=I.winding,P=l.length,T=[f[N].coord],O=N;if(f[N].ringAndEdge1Walkable)var R=f[N].ringAndEdge1,A=f[N].nxtIsectAlongRingAndEdge1;else R=f[N].ringAndEdge2,A=f[N].nxtIsectAlongRingAndEdge2;for(;!Rl(f[N].coord,f[A].coord);){T.push(f[A].coord);var D=void 0;for(r=0;r1)for(e=0;e=0==e}function Ol(t){for(var e=0,n=0;n0)){if(o/=f,f<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=r-u,f||!(o<0)){if(o/=f,f<0){if(o>c)return;o>h&&(h=o)}else if(f>0){if(o0)){if(o/=g,g<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=i-l,g||!(o<0)){if(o/=g,g<0){if(o>c)return;o>h&&(h=o)}else if(g>0){if(o0||c<1)||(h>0&&(t[0]=[u+h*f,l+h*g]),c<1&&(t[1]=[u+c*f,l+c*g]),!0)}}}}}function Hl(t,e,n,r,i){var o=t[1];if(o)return!0;var s,a,u=t[0],l=t.left,h=t.right,c=l[0],f=l[1],g=h[0],p=h[1],v=(c+g)/2,d=(f+p)/2;if(p===f){if(v=r)return;if(c>g){if(u){if(u[1]>=i)return}else u=[v,n];o=[v,i]}else{if(u){if(u[1]1)if(c>g){if(u){if(u[1]>=i)return}else u=[(n-a)/s,n];o=[(i-a)/s,i]}else{if(u){if(u[1]=r)return}else u=[e,s*e+a];o=[r,s*r+a]}else{if(u){if(u[0]=-dh)){var g=u*u+l*l,p=h*h+c*c,v=(c*g-l*p)/f,d=(u*p-h*g)/f,y=$l.pop()||new th;y.arc=t,y.site=i,y.x=v+s,y.y=(y.cy=d+a)+Math.sqrt(v*v+d*d),t.circle=y;for(var m=null,_=gh._;_;)if(y.y<_.y||y.y===_.y&&y.x<=_.x){if(!_.L){m=_.P;break}_=_.L}else{if(!_.R){m=_;break}_=_.R}gh.insert(m,y),m||(Ql=y)}}}}function nh(t){var e=t.circle;e&&(e.P||(Ql=e.N),gh.remove(e),$l.push(e),Gl(e),t.circle=null)}var rh=[];function ih(){Gl(this),this.edge=this.site=this.circle=null}function oh(t){var e=rh.pop()||new ih;return e.site=t,e}function sh(t){nh(t),ch.remove(t),rh.push(t),Gl(t)}function ah(t){var e=t.circle,n=e.x,r=e.cy,i=[n,r],o=t.P,s=t.N,a=[t];sh(t);for(var u=o;u.circle&&Math.abs(n-u.circle.x)vh)a=a.L;else{if(!((i=o-hh(a,s))>vh)){r>-vh?(e=a.P,n=a):i>-vh?(e=a,n=a.N):e=n=a;break}if(!a.R){e=a;break}a=a.R}!function(t){fh[t.index]={site:t,halfedges:[]}}(t);var u=oh(t);if(ch.insert(e,u),e||n){if(e===n)return nh(e),n=oh(e.site),ch.insert(u,n),u.edge=n.edge=jl(e.site,u.site),eh(e),void eh(n);if(n){nh(e),nh(n);var l=e.site,h=l[0],c=l[1],f=t[0]-h,g=t[1]-c,p=n.site,v=p[0]-h,d=p[1]-c,y=2*(f*d-g*v),m=f*f+g*g,_=v*v+d*d,x=[(d*m-g*_)/y+h,(f*_-v*m)/y+c];Ul(n.edge,l,p,x),u.edge=jl(l,t,null,x),n.edge=jl(t,p,null,x),eh(e),eh(n)}else u.edge=jl(e.site,u.site)}}function lh(t,e){var n=t.site,r=n[0],i=n[1],o=i-e;if(!o)return r;var s=t.P;if(!s)return-1/0;var a=(n=s.site)[0],u=n[1],l=u-e;if(!l)return a;var h=a-r,c=1/o-1/l,f=h/l;return c?(-f+Math.sqrt(f*f-2*c*(h*h/(-2*l)-u+l/2+i-o/2)))/c+r:(r+a)/2}function hh(t,e){var n=t.N;if(n)return lh(n,e);var r=t.site;return r[1]===e?r[0]:1/0}var ch,fh,gh,ph,vh=1e-6,dh=1e-12;function yh(t,e){return e[1]-t[1]||e[0]-t[0]}function mh(t,e){var n,r,i,o=t.sort(yh).pop();for(ph=[],fh=new Array(t.length),ch=new Vl,gh=new Vl;;)if(i=Ql,o&&(!i||o[1]vh||Math.abs(i[0][1]-i[1][1])>vh)||delete ph[o]}(s,a,u,l),function(t,e,n,r){var i,o,s,a,u,l,h,c,f,g,p,v,d=fh.length,y=!0;for(i=0;ivh||Math.abs(v-f)>vh)&&(u.splice(a,0,ph.push(Xl(s,g,Math.abs(p-t)vh?[t,Math.abs(c-t)vh?[Math.abs(f-r)vh?[n,Math.abs(c-n)vh?[Math.abs(f-e)=a)return null;var u=t-i.site[0],l=e-i.site[1],h=u*u+l*l;do{i=o.cells[r=s],s=null,i.halfedges.forEach((function(n){var r=o.edges[n],a=r.left;if(a!==i.site&&a||(a=r.right)){var u=t-a[0],l=e-a[1],c=u*u+l*l;c2&&void 0!==arguments[2]?arguments[2]:{},r=rt(t).coordinates,i=0,o=0;o=i&&o===r.length-1);o++){if(i>=e){var s=e-i;if(s){var a=st(r[o],r[o-1])-180;return at(r[o],s,a,n)}return I(r[o])}i+=ut(r[o],r[o+1],n)}return I(r[r.length-1])},t.angle=function(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!Z(r))throw new Error("options is invalid");if(!t)throw new Error("startPoint is required");if(!e)throw new Error("midPoint is required");if(!n)throw new Error("endPoint is required");var i=t,o=e,s=n,a=G(!0!==r.mercator?st(o,i):lt(o,i)),u=G(!0!==r.mercator?st(o,s):lt(o,s));u1&&void 0!==arguments[1]?arguments[1]:{},n=e.resolution||1e4,r=e.sharpness||.85,i=[],o=rt(t).coordinates.map((function(t){return{x:t[0],y:t[1]}})),s=new Gt({duration:n,points:o,sharpness:r}),a=function(t){var e=s.pos(t);Math.floor(t/100)%2==0&&i.push([e.x,e.y])},u=0;u0;else if(n!==u>0)return!0}return!1},t.booleanContains=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type,s=n.coordinates,u=r.coordinates;switch(i){case"Point":if("Point"===o)return Ht(s,u);throw new Error("feature2 "+o+" geometry not supported");case"MultiPoint":switch(o){case"Point":return function(t,e){var n,r=!1;for(n=0;n2&&void 0!==arguments[2]?arguments[2]:{}).precision;if("number"!=typeof(n=null==n||isNaN(n)?6:n)||!(n>=0))throw new Error("precision must be a positive number");return rt(t).type===rt(e).type&&Ne(Le(t),Le(e),{precision:n})},t.booleanIntersects=Oe,t.booleanOverlap=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;if("MultiPoint"===i&&"MultiPoint"!==o||("LineString"===i||"MultiLineString"===i)&&"LineString"!==o&&"MultiLineString"!==o||("Polygon"===i||"MultiPolygon"===i)&&"Polygon"!==o&&"MultiPolygon"!==o)throw new Error("features must be of the same type");if("Point"===i)throw new Error("Point geometry not supported");if(Ne(t,e,{precision:6}))return!1;var s=0;switch(i){case"MultiPoint":for(var a=0;a0},t.booleanParallel=function(t,e){if(!t)throw new Error("line1 is required");if(!e)throw new Error("line2 is required");if("LineString"!==In(t,"line1"))throw new Error("line1 must be a LineString");if("LineString"!==In(e,"line2"))throw new Error("line2 must be a LineString");for(var n=$e(Le(t)).features,r=$e(Le(e)).features,i=0;i1;case"MultiPoint":for(var i=0;i0&&ue(S([r[0]]),S([r[i]])).features.length>1)return!1}return!0;case"MultiPolygon":for(i=0;i0&&ue(S([o[0]]),S([o[s]])).features.length>1)return!1}return!0;default:return!1}},t.booleanWithin=Cn,t.buffer=function(t,e,n){var r=(n=n||{}).units||"kilometers",i=n.steps||8;if(!t)throw new Error("geojson is required");if("object"!==m(n))throw new Error("options must be an object");if("number"!=typeof i)throw new Error("steps must be an number");if(void 0===e)throw new Error("radius is required");if(i<=0)throw new Error("steps must be greater than 0");var o=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){var n=ui(t,e,r,i);n&&o.push(n)})),C(o);case"FeatureCollection":return vt(t,(function(t){var n=ui(t,e,r,i);n&&vt(n,(function(t){t&&o.push(t)}))})),C(o)}return ui(t,e,r,i)},t.center=An,t.centerMean=fi,t.centerMedian=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.counter||10;if(!U(n))throw new Error("counter must be a number");var r=e.weight,i=fi(t,{weight:e.weight}),o=C([]);vt(t,(function(t){var e;o.features.push(gi(t,{properties:{weight:null==(e=t.properties)?void 0:e[r]}}))}));var s={tolerance:e.tolerance,medianCandidates:[]};return pi(i.geometry.coordinates,[0,0],o,s,n)},t.centerOfMass=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(it(e)){case"Point":return I(K(e),n.properties);case"Polygon":var r=[];ct(e,(function(t){r.push(t)}));var i,o,s,a,u,l,h,c,f=gi(e,{properties:n.properties}),g=f.geometry.coordinates,p=0,v=0,d=0,y=r.map((function(t){return[t[0]-g[0],t[1]-g[1]]}));for(i=0;i2&&void 0!==arguments[2]?arguments[2]:{};!0!==n.mutate&&(t=Ai(t));var r=n.minPoints||3,i=V(e,n.units),o=new to(t.features.length),s=t.features.map((function(t){return!1})),a=t.features.map((function(t){return!1})),u=t.features.map((function(t){return!1})),l=t.features.map((function(t){return-1}));o.load(t.features.map((function(t,e){var n=v(t.geometry.coordinates,2),r=n[0],i=n[1];return{minX:r,minY:i,maxX:r,maxY:i,index:e}})));var h=function(n){var r=t.features[n],s=v(r.geometry.coordinates,2),a=s[0],u=s[1],l=Math.max(u-i,-90),h=Math.min(u+i,90),c=l<0&&h>0?i:Math.abs(l)=r){var i=c;c++,s[e]=!0,function(t,e){for(var n=0;n=r&&e.push.apply(e,d(o))}a[i]||(a[i]=!0,l[i]=t)}}(i,n)}else u[e]=!0}})),t.features.forEach((function(e,n){var r=t.features[n];r.properties||(r.properties={}),l[n]>=0?(r.properties.dbscan=u[n]?"edge":"core",r.properties.cluster=l[n]):r.properties.dbscan="noise"})),t},t.clustersKmeans=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.features.length;e.numberOfClusters=e.numberOfClusters||Math.round(Math.sqrt(n/2)),e.numberOfClusters>n&&(e.numberOfClusters=n),!0!==e.mutate&&(t=Ai(t));var r=yt(t),i=r.slice(0,e.numberOfClusters),o=ro(r,e.numberOfClusters,i),s={};return o.centroids.forEach((function(t,e){s[e]=t})),vt(t,(function(t,e){var n=o.idxs[e];t.properties.cluster=n,t.properties.centroid=s[n]})),t},t.collect=function(t,e,n,r){var i=new io(6),o=e.features.map((function(t){var e;return{minX:t.geometry.coordinates[0],minY:t.geometry.coordinates[1],maxX:t.geometry.coordinates[0],maxY:t.geometry.coordinates[1],property:null==(e=t.properties)?void 0:e[n]}}));return i.load(o),t.features.forEach((function(t){t.properties||(t.properties={});var e=Rt(t),n=i.search({minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}),o=[];n.forEach((function(e){zt([e.minX,e.minY],t)&&o.push(e.property)})),t.properties[r]=o})),t},t.collectionOf=nt,t.combine=function(t){var e={MultiPoint:{coordinates:[],properties:[]},MultiLineString:{coordinates:[],properties:[]},MultiPolygon:{coordinates:[],properties:[]}};return vt(t,(function(t){var n,r,i,o;switch(null==(o=t.geometry)?void 0:o.type){case"Point":e.MultiPoint.coordinates.push(t.geometry.coordinates),e.MultiPoint.properties.push(t.properties);break;case"MultiPoint":(n=e.MultiPoint.coordinates).push.apply(n,d(t.geometry.coordinates)),e.MultiPoint.properties.push(t.properties);break;case"LineString":e.MultiLineString.coordinates.push(t.geometry.coordinates),e.MultiLineString.properties.push(t.properties);break;case"MultiLineString":(r=e.MultiLineString.coordinates).push.apply(r,d(t.geometry.coordinates)),e.MultiLineString.properties.push(t.properties);break;case"Polygon":e.MultiPolygon.coordinates.push(t.geometry.coordinates),e.MultiPolygon.properties.push(t.properties);break;case"MultiPolygon":(i=e.MultiPolygon.coordinates).push.apply(i,d(t.geometry.coordinates)),e.MultiPolygon.properties.push(t.properties)}})),C(Object.keys(e).filter((function(t){return e[t].coordinates.length})).sort().map((function(t){return b({type:t,coordinates:e[t].coordinates},{collectedProperties:e[t].properties})})))},t.concave=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.maxEdge||1/0,r=function(t){var e=[],n={};return vt(t,(function(t){if(t.geometry){var r=t.geometry.coordinates.join("-");Object.prototype.hasOwnProperty.call(n,r)||(e.push(t),n[r]=!0)}})),C(e)}(t),i=oo(r);if(i.features=i.features.filter((function(t){var r=t.geometry.coordinates[0][0],i=t.geometry.coordinates[0][1],o=t.geometry.coordinates[0][2],s=ut(r,i,e),a=ut(i,o,e),u=ut(r,o,e);return s<=n&&a<=n&&u<=n})),i.features.length<1)return null;var o=Ro(i);return 1===o.coordinates.length&&(o.coordinates=o.coordinates[0],o.type="Polygon"),b(o)},t.containsNumber=$,t.convertArea=X,t.convertLength=j,t.convex=Oi,t.coordAll=yt,t.coordEach=ct,t.coordReduce=ft,t.createBins=zi,t.degreesToRadians=z,t.destination=at,t.difference=function(t){var e=[];if(mt(t,(function(t){e.push(t.coordinates)})),e.length<2)throw new Error("Must have at least two features");var n=t.features[0].properties||{},r=As.apply(Fs,[e[0]].concat(d(e.slice(1))));return 0===r.length?null:1===r.length?S(r[0],n):R(r,n)},t.dissolve=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.propertyName;nt(t,"Polygon","dissolve");var r=[];if(!n)return qs(R(Os.apply(null,t.features.map((function(t){return t.geometry.coordinates})))));var i={};vt(t,(function(t){t.properties&&(Object.prototype.hasOwnProperty.call(i,t.properties[n])||(i[t.properties[n]]=[]),i[t.properties[n]].push(t))}));for(var o=Object.keys(i),s=0;s1&&void 0!==arguments[1]?arguments[1]:{},o=i.properties,s=null==(e=i.autoComplete)||e,a=null==(n=i.orderCoords)||n;if(null!=(r=i.mutate)&&r||(t=Ai(t)),"FeatureCollection"===t.type){var u=[];return t.features.forEach((function(t){u.push(Q(ru(t,{},s,a)))})),R(u,o)}return ru(t,o,s,a)},t.mask=function(t,e,n){var r,i=null!=(r=null==n?void 0:n.mutate)&&r,o=e;e&&!1===i&&(o=Ai(e));var s,a=su(o);return("FeatureCollection"===t.type?ou(2===(s=t).features.length?Os(s.features[0].geometry.coordinates,s.features[1].geometry.coordinates):Os.apply(Fs,s.features.map((function(t){return t.geometry.coordinates})))):"Feature"===t.type?ou(Os(t.geometry.coordinates)):ou(Os(t.coordinates))).geometry.coordinates.forEach((function(t){a.geometry.coordinates.push(t[0])})),a},t.meta=Mt,t.midpoint=function(t,e){return at(t,ut(t,e)/2,st(t,e))},t.moranIndex=function(t,e){var n,r,i=e.inputField,o=e.threshold||1e5,s=e.p||2,u=null!=(n=e.binary)&&n,l=Gs(t,{alpha:e.alpha||-1,binary:u,p:s,standardization:null==(r=e.standardization)||r,threshold:o}),h=[];vt(t,(function(t){var e=t.properties||{};h.push(e[i])}));for(var c=au(h),f=function(t){var e,n=au(t),r=0,i=a(t);try{for(i.s();!(e=i.n()).done;){var o=e.value;r+=Math.pow(o-n,2)}}catch(t){i.e(t)}finally{i.f()}return r/t.length}(h),g=0,p=0,v=0,d=0,y=l.length,m=0;m2&&void 0!==arguments[2]?arguments[2]:{},r=n.units,i=n.properties||{},o=function(t){var e=[];switch(t.geometry?t.geometry.type:t.type){case"GeometryCollection":return mt(t,(function(t){"Point"===t.type&&e.push({type:"Feature",properties:{},geometry:t})})),{type:"FeatureCollection",features:e};case"FeatureCollection":return t.features=t.features.filter((function(t){return"Point"===t.geometry.type})),t;default:throw new Error("points must be a Point Collection")}}(t);if(!o.features.length)throw new Error("points must contain features");if(!e)throw new Error("line is required");if("LineString"!==it(e))throw new Error("line must be a LineString");var s=1/0,a=null;return vt(o,(function(t){var n=mu(t,e,{units:r});n2&&void 0!==arguments[2]?arguments[2]:{},a=null!=(i=s.method)?i:"geodesic",u=null!=(o=s.units)?o:"kilometers";if(!e)throw new Error("point is required");if(!r)throw new Error("polygon or multi-polygon is required");var l,h=rt(r);if("MultiPolygon"===h.type){var c=h.coordinates.map((function(n){return t(e,S(n),{method:a,units:u})}));return Math.min.apply(Math,d(c.map(Math.abs)))*(zt(e,r)?-1:1)}if(h.coordinates.length>1){var p=h.coordinates.map((function(n){return t(e,S([n]),{method:a,units:u})})),v=n(l=p)||f(l)||_(l)||g(),y=v[0],m=v.slice(1);if(y>=0)return y;var x=Math.min.apply(Math,d(m));return x<0?Math.abs(x):Math.min(x,Math.abs(y))}var E=le(h),k=1/0;return xt(E,(function(t){k=Math.min(k,mu(e,t,{method:a,units:u}))})),zt(e,h)?-k:k},t.points=N,t.pointsWithinPolygon=Su,t.polygon=S,t.polygonSmooth=function(t,e){(e=e||{}).iterations=e.iterations||1;var n=e.iterations,r=[];if(!t)throw new Error("inputPolys is required");return mt(t,(function(t,e,i){if("Polygon"===t.type){for(var o=[[]],s=0;s0&&(u=S(o).geometry),Ru(u,a),o=a.slice(0)}r.push(S(o,i))}else{if("MultiPolygon"!==t.type)throw new Error("geometry is invalid, must be Polygon or MultiPolygon");for(var l=[[[]]],h=0;h0&&(f=R(l).geometry),Au(f,c),l=c.slice(0)}r.push(R(l,i))}})),C(r)},t.polygonTangents=function(t,e){var n,r=Q(t),i=Q(e),o=[],s=[],a=Rt(e),u=0,l=null;switch(r[0]>a[0]&&r[0]a[1]&&r[1]_&&(_=k)}for(var b=[],w=Object.keys(l).length,I=f/w,N=0,S=0;S<_+1;S++)N+=Math.exp(-I)*Math.pow(I,S)/Zu(S),b.push(N);for(var M=[],L=0,P=0;P<_+1;P++){for(var C=0,T=Object.keys(l);CR&&(R=D)}var F=Xu[r]/Math.sqrt(w),q={criticalValue:F,isRandom:!0,maxAbsoluteDifference:R,observedDistribution:M};return R>F&&(q.isRandom=!1),q},t.radiansToDegrees=Y,t.radiansToLength=F,t.random=nl,t.randomLineString=$u,t.randomPoint=Ku,t.randomPolygon=Qu,t.randomPosition=Hu,t.rectangleGrid=oa,t.rewind=function(t){var e,n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(r=r||{}))throw new Error("options is invalid");var i=null!=(e=r.mutate)&&e,o=null!=(n=r.reverse)&&n;if(!t)throw new Error(" is required");if("boolean"!=typeof o)throw new Error(" must be a boolean");if("boolean"!=typeof i)throw new Error(" must be a boolean");i||"Point"===t.type||"MultiPoint"===t.type||(t=Ai(t));var s=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){rl(t,o)})),t;case"FeatureCollection":return vt(t,(function(t){vt(rl(t,o),(function(t){s.push(t)}))})),C(s)}return rl(t,o)},t.rhumbBearing=lt,t.rhumbDestination=Bs,t.rhumbDistance=Ys,t.round=D,t.sample=function(t,e){if(!t)throw new Error("fc is required");if(null==e)throw new Error("num is required");if("number"!=typeof e)throw new Error("num must be a number");var n=C(function(t,e){var n,r,i=t.slice(0),o=t.length,s=o-e;for(;o-- >s;)n=i[r=Math.floor((o+1)*Math.random())],i[r]=i[o],i[o]=n;return i.slice(s)}(t.features,e));return n},t.sector=function(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!Z(i=i||{}))throw new Error("options is invalid");var o=i.properties;if(!t)throw new Error("center is required");if(null==n)throw new Error("bearing1 is required");if(null==r)throw new Error("bearing2 is required");if(!e)throw new Error("radius is required");if("object"!==m(i))throw new Error("options must be an object");if(sl(n)===sl(r))return Ri(t,e,i);var s=Q(t),a=ja(t,e,n,r,i),u=[[s]];return ct(a,(function(t){u[0].push(t)})),u[0].push(s),S(u,o)},t.segmentEach=kt,t.segmentReduce=bt,t.shortestPath=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.obstacles||C([]),i=n.resolution||100;if(!t)throw new Error("start is required");if(!e)throw new Error("end is required");if(i&&(!U(i)||i<=0))throw new Error("options.resolution must be a number, greater than 0");var o=K(t),s=K(e);if(t=I(o),e=I(s),"FeatureCollection"===r.type){if(0===r.features.length)return L([o,s])}else{if("Polygon"!==r.type)throw new Error("invalid obstacles");r=C([b(rt(r))])}var a=r;a.features.push(t),a.features.push(e);var u=v(Rt(al(Vt(Rt(a)),1.15)),4),l=u[0],h=u[1],c=u[2],f=u[3],g=ut([l,h],[c,h],n)/i;a.features.pop(),a.features.pop();for(var p,d,y=g/ut([l,h],[c,h],n)*(c-l),m=g/ut([l,h],[l,f],n)*(f-h),_=c-l,x=f-h,E=Math.floor(_/y),k=Math.floor(x/m),w=(_-E*y)/2,N=[],S=[],M=1/0,P=1/0,T=f-(x-k*m)/2,O=0;T>=h;){for(var R=[],A=[],D=l+w,F=0;D<=c;){var q=I([D,T]),V=pl(q,r);R.push(V?0:1),A.push(D+"|"+T);var G=ut(q,t);!V&&G1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(i=null!=i?i:{}))throw new Error("options is invalid");var o=null!=(e=i.tolerance)?e:1,s=null!=(n=i.highQuality)&&n,a=null!=(r=i.mutate)&&r;if(!t)throw new Error("geojson is required");if(o&&o<0)throw new Error("invalid tolerance");return!0!==a&&(t=Ai(t)),mt(t,(function(t){!function(t,e,n){var r=t.type;if("Point"===r||"MultiPoint"===r)return t;if(Le(t,{mutate:!0}),"GeometryCollection"!==r)switch(r){case"LineString":t.coordinates=ml(t.coordinates,e,n);break;case"MultiLineString":t.coordinates=t.coordinates.map((function(t){return ml(t,e,n)}));break;case"Polygon":t.coordinates=_l(t.coordinates,e,n);break;case"MultiPolygon":t.coordinates=t.coordinates.map((function(t){return _l(t,e,n)}))}}(t,o,s)})),t},t.square=Ka,t.squareGrid=sa,t.standardDeviationalEllipse=function(t,e){var n;if(!Z(e=e||{}))throw new Error("options is invalid");var r=e.steps||64,i=e.weight,o=e.properties||{};if(!U(r))throw new Error("steps must be a number");if(!Z(o))throw new Error("properties must be a number");var s=yt(t).length,a=fi(t,{weight:i}),u=0,l=0,h=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));u+=Math.pow(r.x,2)*n,l+=Math.pow(r.y,2)*n,h+=r.x*r.y*n}));var c=u-l,f=Math.sqrt(Math.pow(c,2)+4*Math.pow(h,2)),g=2*h,p=Math.atan((c+f)/g),v=180*p/Math.PI,d=0,y=0,m=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));d+=Math.pow(r.x*Math.cos(p)-r.y*Math.sin(p),2)*n,y+=Math.pow(r.x*Math.sin(p)+r.y*Math.cos(p),2)*n,m+=n}));var _=Math.sqrt(2*d/m),x=Math.sqrt(2*y/m),E=js(a,_,x,{units:"degrees",angle:v,steps:r,properties:o}),k=Su(t,C([E])),b={meanCenterCoordinates:Q(a),semiMajorAxis:_,semiMinorAxis:x,numberOfFeatures:s,angle:v,percentageWithinEllipse:100*yt(k).length/s};return E.properties=null!=(n=E.properties)?n:{},E.properties.standardDeviationalEllipse=b,E},t.tag=function(t,e,n,r){return t=Ai(t),e=Ai(e),vt(t,(function(t){t.properties||(t.properties={}),vt(e,(function(e){t.properties&&e.properties&&void 0===t.properties[r]&&zt(t,e)&&(t.properties[r]=e.properties[n])}))})),t},t.tesselate=function(t){if(!t.geometry||"Polygon"!==t.geometry.type&&"MultiPolygon"!==t.geometry.type)throw new Error("input must be a Polygon or MultiPolygon");var e={type:"FeatureCollection",features:[]};return"Polygon"===t.geometry.type?e.features=Nl(t.geometry.coordinates):t.geometry.coordinates.forEach((function(t){e.features=e.features.concat(Nl(t))})),e},t.tin=oo,t.toMercator=Vu,t.toWgs84=Gu,t.transformRotate=zs,t.transformScale=al,t.transformTranslate=function(t,e,n,r){if(!Z(r=r||{}))throw new Error("options is invalid");var i=r.units,o=r.zTranslation,s=r.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("distance is required");if(o&&"number"!=typeof o&&isNaN(o))throw new Error("zTranslation is not a number");if(o=void 0!==o?o:0,0===e&&0===o)return t;if(null==n||isNaN(n))throw new Error("direction is required");return e<0&&(e=-e,n+=180),!1!==s&&void 0!==s||(t=Ai(t)),ct(t,(function(t){var r=Q(Bs(t,e,n,{units:i}));t[0]=r[0],t[1]=r[1],o&&3===t.length&&(t[2]+=o)})),t},t.triangleGrid=aa,t.truncate=Qa,t.union=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must have at least 2 geometries");var r=Os.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)},t.unkinkPolygon=function(t){var e=[];return xt(t,(function(t){"Polygon"===t.geometry.type&&vt(Ll(t),(function(n){e.push(S(n.geometry.coordinates,t.properties))}))})),C(e)},t.validateBBox=H,t.validateId=W,t.voronoi=function(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox||[-180,-85,180,85];if(!t)throw new Error("points is required");if(!Array.isArray(n))throw new Error("bbox is invalid");return nt(t,"Point","points"),C(function(){var t=Fl,e=ql,n=null;function r(r){return new mh(r.map((function(n,i){var o=[Math.round(t(n,i,r)/vh)*vh,Math.round(e(n,i,r)/vh)*vh];return o.index=i,o.data=n,o})),n)}return r.polygons=function(t){return r(t).polygons()},r.links=function(t){return r(t).links()},r.triangles=function(t){return r(t).triangles()},r.x=function(e){return arguments.length?(t="function"==typeof e?e:Dl(+e),r):t},r.y=function(t){return arguments.length?(e="function"==typeof t?t:Dl(+t),r):e},r.extent=function(t){return arguments.length?(n=null==t?null:[[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]],r):n&&[[n[0][0],n[0][1]],[n[1][0],n[1][1]]]},r.size=function(t){return arguments.length?(n=null==t?null:[[0,0],[+t[0],+t[1]]],r):n&&[n[1][0]-n[0][0],n[1][1]-n[0][1]]},r}().x((function(t){return t.geometry.coordinates[0]})).y((function(t){return t.geometry.coordinates[1]})).extent([[n[0],n[1]],[n[2],n[3]]]).polygons(t.features).map((function(e,n){return Object.assign(function(t){return(t=t.slice()).push(t[0]),S([t])}(e),{properties:Fi(t.features[n].properties)})})))}})); diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js new file mode 100644 index 0000000..6b2b9e8 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/freehand-mode/freehand-mode.js @@ -0,0 +1,207 @@ +// This code is derived from the ISC-licensed "mapbox-gl-draw-freehand-mode" plugin +// by Ben Ehmke, Eric Dong, and Joe Woodhouse. +// Source: https://github.com/bemky/mapbox-gl-draw-freehand-mode +(function (MapboxDraw) { + const { geojsonTypes, cursors, types, updateActions, modes, events } = + MapboxDraw.constants; + + const FreehandMode = {}; + + FreehandMode.onSetup = function () { + const polygon = this.newFeature({ + type: geojsonTypes.FEATURE, + properties: {}, + geometry: { + type: geojsonTypes.POLYGON, + coordinates: [[]], + }, + }); + + this.addFeature(polygon); + this.clearSelectedFeatures(); + + // Disable map dragging + setTimeout(() => { + if (!this.map || !this.map.dragPan) return; + this.map.dragPan.disable(); + }, 0); + + this.updateUIClasses({ mouse: cursors.ADD }); + this.activateUIButton(types.POLYGON); + this.setActionableState({ + trash: true, + }); + + return { + polygon, + currentVertexPosition: 0, + dragMoving: false, + isDrawing: false, + }; + }; + + FreehandMode.onDrag = FreehandMode.onTouchMove = function (state, e) { + state.dragMoving = true; + state.isDrawing = true; + this.updateUIClasses({ mouse: cursors.ADD }); + state.polygon.updateCoordinate( + `0.${state.currentVertexPosition}`, + e.lngLat.lng, + e.lngLat.lat, + ); + state.currentVertexPosition++; + state.polygon.updateCoordinate( + `0.${state.currentVertexPosition}`, + e.lngLat.lng, + e.lngLat.lat, + ); + }; + + FreehandMode.onMouseUp = function (state) { + if (state.dragMoving) { + this.simplify(state.polygon); + this.updateUIClasses({ mouse: cursors.MOVE }); + this.fireUpdate(); + this.changeMode(modes.SIMPLE_SELECT, { + featureIds: [state.polygon.id], + }); + } + }; + + FreehandMode.fireCreate = function (polygon) { + this.map.fire(events.CREATE, { + features: [polygon.toGeoJSON()], + }); + }; + + FreehandMode.fireUpdate = function () { + this.map.fire(events.UPDATE, { + action: updateActions.MOVE, + features: this.getSelected().map((f) => f.toGeoJSON()), + }); + }; + + FreehandMode.simplify = function (polygon) { + if (!this.map.simplify_freehand) return; + + const tolerance = 1 / Math.pow(1.05, 10 * this.map.getZoom()); + const simplifiedCoords = simplifyGeometry( + polygon.coordinates[0], + tolerance, + ); + polygon.setCoordinates([simplifiedCoords]); + }; + + function simplifyGeometry(points, tolerance) { + if (points.length <= 2) return points; + + const sqTolerance = tolerance * tolerance; + const last = points.length - 1; + const simplified = [points[0]]; + simplifyDPStep(points, 0, last, sqTolerance, simplified); + simplified.push(points[last]); + + return simplified; + } + + function simplifyDPStep(points, first, last, sqTolerance, simplified) { + let maxSqDist = sqTolerance; + let index; + + for (let i = first + 1; i < last; i++) { + const sqDist = getSquareSegmentDistance( + points[i], + points[first], + points[last], + ); + if (sqDist > maxSqDist) { + index = i; + maxSqDist = sqDist; + } + } + + if (maxSqDist > sqTolerance) { + if (index - first > 1) + simplifyDPStep(points, first, index, sqTolerance, simplified); + simplified.push(points[index]); + if (last - index > 1) + simplifyDPStep(points, index, last, sqTolerance, simplified); + } + } + + function getSquareSegmentDistance(p, p1, p2) { + let x = p1[0], + y = p1[1]; + let dx = p2[0] - x, + dy = p2[1] - y; + + if (dx !== 0 || dy !== 0) { + const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy); + if (t > 1) { + x = p2[0]; + y = p2[1]; + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } + + dx = p[0] - x; + dy = p[1] - y; + + return dx * dx + dy * dy; + } + + FreehandMode.onStop = function (state) { + this.updateUIClasses({ mouse: cursors.NONE }); + this.activateUIButton(); + + // Enable map dragging + setTimeout(() => { + if (!this.map || !this.map.dragPan) return; + this.map.dragPan.enable(); + }, 0); + }; + + FreehandMode.toDisplayFeatures = function (state, geojson, display) { + const isActivePolygon = geojson.properties.id === state.polygon.id; + geojson.properties.active = isActivePolygon ? "true" : "false"; + if (!isActivePolygon) return display(geojson); + + // Only render the polygon if it has at least three points + if (geojson.geometry.coordinates[0].length < 3) return; + + const coordinateCount = geojson.geometry.coordinates[0].length; + + // If we have fewer than three coordinates, we need to create a LineString instead of a Polygon + if (coordinateCount < 3) { + const lineCoordinates = [ + [ + geojson.geometry.coordinates[0][0][0], + geojson.geometry.coordinates[0][0][1], + ], + [ + geojson.geometry.coordinates[0][1][0], + geojson.geometry.coordinates[0][1][1], + ], + ]; + return display({ + type: geojsonTypes.FEATURE, + properties: geojson.properties, + geometry: { + coordinates: lineCoordinates, + type: geojsonTypes.LINE_STRING, + }, + }); + } + + return display(geojson); + }; + + FreehandMode.onTrash = function (state) { + this.deleteFeature([state.polygon.id], { silent: true }); + this.changeMode(modes.SIMPLE_SELECT); + }; + + MapboxDraw.modes.draw_freehand = FreehandMode; +})(MapboxDraw); diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js new file mode 100644 index 0000000..16631aa --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/h3j-h3t/h3j_h3t.js @@ -0,0 +1,3 @@ +!function(A){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=A();else if("function"==typeof define&&define.amd)define([],A);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).h3j_h3t=A()}}((function(){return function A(e,r,t){function i(o,a){if(!r[o]){if(!e[o]){var f="function"==typeof require&&require;if(!a&&f)return f(o,!0);if(n)return n(o,!0);var s=new Error("Cannot find module '"+o+"'");throw s.code="MODULE_NOT_FOUND",s}var u=r[o]={exports:{}};e[o][0].call(u.exports,(function(A){return i(e[o][1][A]||A)}),u,u.exports,A,e,r,t)}return r[o].exports}for(var n="function"==typeof require&&require,o=0;o>3}if(n--,1===i||2===i)o+=A.readSVarint(),a+=A.readSVarint(),1===i&&(e&&f.push(e),e=[]),e.push(new t(o,a));else{if(7!==i)throw new Error("unknown command "+i);e&&e.push(e[0].clone())}}return e&&f.push(e),f},i.prototype.bbox=function(){var A=this._pbf;A.pos=this._geometry;for(var e=A.readVarint()+A.pos,r=1,t=0,i=0,n=0,o=1/0,a=-1/0,f=1/0,s=-1/0;A.pos>3}if(t--,1===r||2===r)(i+=A.readSVarint())a&&(a=i),(n+=A.readSVarint())s&&(s=n);else if(7!==r)throw new Error("unknown command "+r)}return[o,f,a,s]},i.prototype.toGeoJSON=function(A,e,r){var t,n,a=this.extent*Math.pow(2,r),f=this.extent*A,s=this.extent*e,u=this.loadGeometry(),l=i.types[this.type];function h(A){for(var e=0;e>3;e=1===t?A.readString():2===t?A.readFloat():3===t?A.readDouble():4===t?A.readVarint64():5===t?A.readVarint():6===t?A.readSVarint():7===t?A.readBoolean():null}return e}(r))}e.exports=i,i.prototype.feature=function(A){if(A<0||A>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[A];var e=this._pbf.readVarint()+this._pbf.pos;return new t(this._pbf,e,this.extent,this._keys,this._values)}},{"./vectortilefeature.js":4}],6:[function(A,e,r){!function(A,t){"object"==typeof r&&void 0!==e?e.exports=t():A.geojsonvt=t()}(this,(function(){"use strict";function A(r,t,i,n){for(var o,a=n,f=i-t>>1,s=i-t,u=r[t],l=r[t+1],h=r[i],c=r[i+1],d=t+3;da)o=d,a=g;else if(g===a){var w=Math.abs(d-f);wn&&(o-t>3&&A(r,t,o,n),r[o+2]=a,i-o>3&&A(r,o,i,n))}function e(A,e,r,t,i,n){var o=i-r,a=n-t;if(0!==o||0!==a){var f=((A-r)*o+(e-t)*a)/(o*o+a*a);f>1?(r=i,t=n):f>0&&(r+=o*f,t+=a*f)}return(o=A-r)*o+(a=e-t)*a}function r(A,e,r,i){var n={id:void 0===A?null:A,type:e,geometry:r,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(A){var e=A.geometry,r=A.type;if("Point"===r||"MultiPoint"===r||"LineString"===r)t(A,e);else if("Polygon"===r||"MultiLineString"===r)for(var i=0;i0&&(a+=i?(n*h-l*o)/2:Math.sqrt(Math.pow(l-n,2)+Math.pow(h-o,2))),n=l,o=h}var c=r.length-3;r[2]=1,A(r,0,c,t),r[c+2]=1,r.size=Math.abs(a),r.start=0,r.end=r.size}function a(A,e,r,t){for(var i=0;i1?1:r}function u(A,e,t,i,n,o,a,f){if(i/=e,o>=(t/=e)&&a=i)return null;for(var s=[],u=0;u=t&&B=i)){var b=[];if("Point"===w||"MultiPoint"===w)l(g,b,t,i,n);else if("LineString"===w)h(g,b,t,i,n,!1,f.lineMetrics);else if("MultiLineString"===w)d(g,b,t,i,n,!1);else if("Polygon"===w)d(g,b,t,i,n,!0);else if("MultiPolygon"===w)for(var v=0;v=r&&o<=t&&(e.push(A[n]),e.push(A[n+1]),e.push(A[n+2]))}}function h(A,e,r,t,i,n,o){for(var a,f,s=c(A),u=0===i?w:p,l=A.start,h=0;hr&&(f=u(s,d,B,v,m,r),o&&(s.start=l+a*f)):k>t?M=r&&(f=u(s,d,B,v,m,r),Q=!0),M>t&&k<=t&&(f=u(s,d,B,v,m,t),Q=!0),!n&&Q&&(o&&(s.end=l+a*f),e.push(s),s=c(A)),o&&(l+=a)}var y=A.length-3;d=A[y],B=A[y+1],b=A[y+2],(k=0===i?d:B)>=r&&k<=t&&g(s,d,B,b),y=s.length-3,n&&y>=3&&(s[y]!==s[0]||s[y+1]!==s[1])&&g(s,s[0],s[1],s[2]),s.length&&e.push(s)}function c(A){var e=[];return e.size=A.size,e.start=A.start,e.end=A.end,e}function d(A,e,r,t,i,n){for(var o=0;oo.maxX&&(o.maxX=u),l>o.maxY&&(o.maxY=l)}return o}function M(A,e,r,t){var i=e.geometry,n=e.type,o=[];if("Point"===n||"MultiPoint"===n)for(var a=0;a0&&e.size<(i?o:t))r.numPoints+=e.length/3;else{for(var a=[],f=0;fo)&&(r.numSimplified++,a.push(e[f]),a.push(e[f+1])),r.numPoints++;i&&function(A,e){for(var r=0,t=0,i=A.length,n=i-2;t0===e)for(t=0,i=A.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(e.promoteId&&e.generateId)throw new Error("promoteId and generateId cannot be used together.");var t=function(A,e){var r=[];if("FeatureCollection"===A.type)for(var t=0;t1&&console.time("creation"),c=this.tiles[h]=k(A,e,r,t,f),this.tileCoords.push({z:e,x:r,y:t}),s)){s>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,r,t,c.numFeatures,c.numPoints,c.numSimplified),console.timeEnd("creation"));var d="z"+e;this.stats[d]=(this.stats[d]||0)+1,this.total++}if(c.source=A,i){if(e===f.maxZoom||e===i)continue;var g=1<1&&console.time("clipping");var w,p,B,b,v,m,M=.5*f.buffer/f.extent,Q=.5-M,y=.5+M,x=1+M;w=p=B=b=null,v=u(A,l,r-M,r+y,0,c.minX,c.maxX,f),m=u(A,l,r+Q,r+x,0,c.minX,c.maxX,f),A=null,v&&(w=u(v,l,t-M,t+y,1,c.minY,c.maxY,f),p=u(v,l,t+Q,t+x,1,c.minY,c.maxY,f),v=null),m&&(B=u(m,l,t-M,t+y,1,c.minY,c.maxY,f),b=u(m,l,t+Q,t+x,1,c.minY,c.maxY,f),m=null),s>1&&console.timeEnd("clipping"),a.push(w||[],e+1,2*r,2*t),a.push(p||[],e+1,2*r,2*t+1),a.push(B||[],e+1,2*r+1,2*t),a.push(b||[],e+1,2*r+1,2*t+1)}}},y.prototype.getTile=function(A,e,r){var t=this.options,i=t.extent,n=t.debug;if(A<0||A>24)return null;var o=1<1&&console.log("drilling down to z%d-%d-%d",A,e,r);for(var f,s=A,u=e,l=r;!f&&s>0;)s--,u=Math.floor(u/2),l=Math.floor(l/2),f=this.tiles[E(s,u,l)];return f&&f.source?(n>1&&console.log("found parent tile z%d-%d-%d",s,u,l),n>1&&console.time("drilling down"),this.splitTile(f.source,s,u,l,A,e,r),n>1&&console.timeEnd("drilling down"),this.tiles[a]?v(this.tiles[a],i):null):null},function(A,e){return new y(A,e)}}))},{}],7:[function(A,e,r){var t=function(A){var e,r=void 0!==(A=A||{})?A:{},t={};for(e in r)r.hasOwnProperty(e)&&(t[e]=r[e]);var i,n=[],o="";document.currentScript&&(o=document.currentScript.src),o=0!==o.indexOf("blob:")?o.substr(0,o.lastIndexOf("/")+1):"",i=function(A,e,r){var t=new XMLHttpRequest;t.open("GET",A,!0),t.responseType="arraybuffer",t.onload=function(){if(200==t.status||0==t.status&&t.response)e(t.response);else{var i=J(A);i?e(i.buffer):r()}},t.onerror=r,t.send(null)};var a=r.print||console.log.bind(console),f=r.printErr||console.warn.bind(console);for(e in t)t.hasOwnProperty(e)&&(r[e]=t[e]);t=null,r.arguments&&(n=r.arguments);var s=0,u=function(){return s};var l=!1;function h(A){var e,t=r["_"+A];return e="Cannot call unknown function "+A+", make sure it is exported",t||fA("Assertion failed: "+e),t}function c(A,e,r,t,i){var n={string:function(A){var e=0;if(null!=A&&0!==A){var r=1+(A.length<<2);(function(A,e,r){(function(A,e,r,t){if(!(t>0))return 0;for(var i=r,n=r+t-1,o=0;o=55296&&a<=57343)a=65536+((1023&a)<<10)|1023&A.charCodeAt(++o);if(a<=127){if(r>=n)break;e[r++]=a}else if(a<=2047){if(r+1>=n)break;e[r++]=192|a>>6,e[r++]=128|63&a}else if(a<=65535){if(r+2>=n)break;e[r++]=224|a>>12,e[r++]=128|a>>6&63,e[r++]=128|63&a}else{if(r+3>=n)break;e[r++]=240|a>>18,e[r++]=128|a>>12&63,e[r++]=128|a>>6&63,e[r++]=128|63&a}}e[r]=0})(A,B,e,r)})(A,e=AA(r),r)}return e},array:function(A){var e=AA(A.length);return function(A,e){p.set(A,e)}(A,e),e}};var o=h(A),a=[],f=0;if(t)for(var s=0;s=t);)++i;if(i-e>16&&A.subarray&&d)return d.decode(A.subarray(e,i));for(var n="";e>10,56320|1023&s)}}else n+=String.fromCharCode((31&o)<<6|a)}else n+=String.fromCharCode(o)}return n}(B,A,e):""}var w,p,B,b,v,m,k;"undefined"!=typeof TextDecoder&&new TextDecoder("utf-16le");function M(A,e){return A%e>0&&(A+=e-A%e),A}function Q(A){w=A,r.HEAP8=p=new Int8Array(A),r.HEAP16=b=new Int16Array(A),r.HEAP32=v=new Int32Array(A),r.HEAPU8=B=new Uint8Array(A),r.HEAPU16=new Uint16Array(A),r.HEAPU32=new Uint32Array(A),r.HEAPF32=m=new Float32Array(A),r.HEAPF64=k=new Float64Array(A)}var y=r.TOTAL_MEMORY||33554432;function E(A){for(;A.length>0;){var e=A.shift();if("function"!=typeof e){var t=e.func;"number"==typeof t?void 0===e.arg?r.dynCall_v(t):r.dynCall_vi(t,e.arg):t(void 0===e.arg?null:e.arg)}else e()}}y=(w=r.buffer?r.buffer:new ArrayBuffer(y)).byteLength,Q(w),v[6004]=5266928;var x=[],D=[],_=[],I=[];var F=Math.abs,C=Math.ceil,P=Math.floor,U=Math.min,G=0,S=null,T=null;r.preloadedImages={},r.preloadedAudios={};var V,H,R=null,L="data:application/octet-stream;base64,";function z(A){return String.prototype.startsWith?A.startsWith(L):0===A.indexOf(L)}R="data:application/octet-stream;base64,AAAAAAAAAAACAAAAAwAAAAEAAAAFAAAABAAAAAYAAAAAAAAAAAAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAYAAAABAAAABAAAAAMAAAAGAAAABQAAAAIAAAAAAAAAAgAAAAMAAAABAAAABAAAAAYAAAAAAAAABQAAAAMAAAAGAAAABAAAAAUAAAAAAAAAAQAAAAIAAAAEAAAABQAAAAYAAAAAAAAAAgAAAAMAAAABAAAABQAAAAIAAAAAAAAAAQAAAAMAAAAGAAAABAAAAAYAAAAAAAAABQAAAAIAAAABAAAABAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAgAAAAMAAAAAAAAAAAAAAAIAAAAAAAAAAQAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAABgAAAAAAAAAFAAAAAAAAAAAAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAIAAAAAAAAABgAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAgAAAAAAAAAAAAAABgAAAAAAAAADAAAAAgAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAUAAAAEAAAAAAAAAAEAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAEAAAAAAAAAAYAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAUAAAACAAAABAAAAAMAAAAIAAAAAQAAAAcAAAAGAAAACQAAAAAAAAADAAAAAgAAAAIAAAAGAAAACgAAAAsAAAAAAAAAAQAAAAUAAAADAAAADQAAAAEAAAAHAAAABAAAAAwAAAAAAAAABAAAAH8AAAAPAAAACAAAAAMAAAAAAAAADAAAAAUAAAACAAAAEgAAAAoAAAAIAAAAAAAAABAAAAAGAAAADgAAAAsAAAARAAAAAQAAAAkAAAACAAAABwAAABUAAAAJAAAAEwAAAAMAAAANAAAAAQAAAAgAAAAFAAAAFgAAABAAAAAEAAAAAAAAAA8AAAAJAAAAEwAAAA4AAAAUAAAAAQAAAAcAAAAGAAAACgAAAAsAAAAYAAAAFwAAAAUAAAACAAAAEgAAAAsAAAARAAAAFwAAABkAAAACAAAABgAAAAoAAAAMAAAAHAAAAA0AAAAaAAAABAAAAA8AAAADAAAADQAAABoAAAAVAAAAHQAAAAMAAAAMAAAABwAAAA4AAAB/AAAAEQAAABsAAAAJAAAAFAAAAAYAAAAPAAAAFgAAABwAAAAfAAAABAAAAAgAAAAMAAAAEAAAABIAAAAhAAAAHgAAAAgAAAAFAAAAFgAAABEAAAALAAAADgAAAAYAAAAjAAAAGQAAABsAAAASAAAAGAAAAB4AAAAgAAAABQAAAAoAAAAQAAAAEwAAACIAAAAUAAAAJAAAAAcAAAAVAAAACQAAABQAAAAOAAAAEwAAAAkAAAAoAAAAGwAAACQAAAAVAAAAJgAAABMAAAAiAAAADQAAAB0AAAAHAAAAFgAAABAAAAApAAAAIQAAAA8AAAAIAAAAHwAAABcAAAAYAAAACwAAAAoAAAAnAAAAJQAAABkAAAAYAAAAfwAAACAAAAAlAAAACgAAABcAAAASAAAAGQAAABcAAAARAAAACwAAAC0AAAAnAAAAIwAAABoAAAAqAAAAHQAAACsAAAAMAAAAHAAAAA0AAAAbAAAAKAAAACMAAAAuAAAADgAAABQAAAARAAAAHAAAAB8AAAAqAAAALAAAAAwAAAAPAAAAGgAAAB0AAAArAAAAJgAAAC8AAAANAAAAGgAAABUAAAAeAAAAIAAAADAAAAAyAAAAEAAAABIAAAAhAAAAHwAAACkAAAAsAAAANQAAAA8AAAAWAAAAHAAAACAAAAAeAAAAGAAAABIAAAA0AAAAMgAAACUAAAAhAAAAHgAAADEAAAAwAAAAFgAAABAAAAApAAAAIgAAABMAAAAmAAAAFQAAADYAAAAkAAAAMwAAACMAAAAuAAAALQAAADgAAAARAAAAGwAAABkAAAAkAAAAFAAAACIAAAATAAAANwAAACgAAAA2AAAAJQAAACcAAAA0AAAAOQAAABgAAAAXAAAAIAAAACYAAAB/AAAAIgAAADMAAAAdAAAALwAAABUAAAAnAAAAJQAAABkAAAAXAAAAOwAAADkAAAAtAAAAKAAAABsAAAAkAAAAFAAAADwAAAAuAAAANwAAACkAAAAxAAAANQAAAD0AAAAWAAAAIQAAAB8AAAAqAAAAOgAAACsAAAA+AAAAHAAAACwAAAAaAAAAKwAAAD4AAAAvAAAAQAAAABoAAAAqAAAAHQAAACwAAAA1AAAAOgAAAEEAAAAcAAAAHwAAACoAAAAtAAAAJwAAACMAAAAZAAAAPwAAADsAAAA4AAAALgAAADwAAAA4AAAARAAAABsAAAAoAAAAIwAAAC8AAAAmAAAAKwAAAB0AAABFAAAAMwAAAEAAAAAwAAAAMQAAAB4AAAAhAAAAQwAAAEIAAAAyAAAAMQAAAH8AAAA9AAAAQgAAACEAAAAwAAAAKQAAADIAAAAwAAAAIAAAAB4AAABGAAAAQwAAADQAAAAzAAAARQAAADYAAABHAAAAJgAAAC8AAAAiAAAANAAAADkAAABGAAAASgAAACAAAAAlAAAAMgAAADUAAAA9AAAAQQAAAEsAAAAfAAAAKQAAACwAAAA2AAAARwAAADcAAABJAAAAIgAAADMAAAAkAAAANwAAACgAAAA2AAAAJAAAAEgAAAA8AAAASQAAADgAAABEAAAAPwAAAE0AAAAjAAAALgAAAC0AAAA5AAAAOwAAAEoAAABOAAAAJQAAACcAAAA0AAAAOgAAAH8AAAA+AAAATAAAACwAAABBAAAAKgAAADsAAAA/AAAATgAAAE8AAAAnAAAALQAAADkAAAA8AAAASAAAAEQAAABQAAAAKAAAADcAAAAuAAAAPQAAADUAAAAxAAAAKQAAAFEAAABLAAAAQgAAAD4AAAArAAAAOgAAACoAAABSAAAAQAAAAEwAAAA/AAAAfwAAADgAAAAtAAAATwAAADsAAABNAAAAQAAAAC8AAAA+AAAAKwAAAFQAAABFAAAAUgAAAEEAAAA6AAAANQAAACwAAABWAAAATAAAAEsAAABCAAAAQwAAAFEAAABVAAAAMQAAADAAAAA9AAAAQwAAAEIAAAAyAAAAMAAAAFcAAABVAAAARgAAAEQAAAA4AAAAPAAAAC4AAABaAAAATQAAAFAAAABFAAAAMwAAAEAAAAAvAAAAWQAAAEcAAABUAAAARgAAAEMAAAA0AAAAMgAAAFMAAABXAAAASgAAAEcAAABZAAAASQAAAFsAAAAzAAAARQAAADYAAABIAAAAfwAAAEkAAAA3AAAAUAAAADwAAABYAAAASQAAAFsAAABIAAAAWAAAADYAAABHAAAANwAAAEoAAABOAAAAUwAAAFwAAAA0AAAAOQAAAEYAAABLAAAAQQAAAD0AAAA1AAAAXgAAAFYAAABRAAAATAAAAFYAAABSAAAAYAAAADoAAABBAAAAPgAAAE0AAAA/AAAARAAAADgAAABdAAAATwAAAFoAAABOAAAASgAAADsAAAA5AAAAXwAAAFwAAABPAAAATwAAAE4AAAA/AAAAOwAAAF0AAABfAAAATQAAAFAAAABEAAAASAAAADwAAABjAAAAWgAAAFgAAABRAAAAVQAAAF4AAABlAAAAPQAAAEIAAABLAAAAUgAAAGAAAABUAAAAYgAAAD4AAABMAAAAQAAAAFMAAAB/AAAASgAAAEYAAABkAAAAVwAAAFwAAABUAAAARQAAAFIAAABAAAAAYQAAAFkAAABiAAAAVQAAAFcAAABlAAAAZgAAAEIAAABDAAAAUQAAAFYAAABMAAAASwAAAEEAAABoAAAAYAAAAF4AAABXAAAAUwAAAGYAAABkAAAAQwAAAEYAAABVAAAAWAAAAEgAAABbAAAASQAAAGMAAABQAAAAaQAAAFkAAABhAAAAWwAAAGcAAABFAAAAVAAAAEcAAABaAAAATQAAAFAAAABEAAAAagAAAF0AAABjAAAAWwAAAEkAAABZAAAARwAAAGkAAABYAAAAZwAAAFwAAABTAAAATgAAAEoAAABsAAAAZAAAAF8AAABdAAAATwAAAFoAAABNAAAAbQAAAF8AAABqAAAAXgAAAFYAAABRAAAASwAAAGsAAABoAAAAZQAAAF8AAABcAAAATwAAAE4AAABtAAAAbAAAAF0AAABgAAAAaAAAAGIAAABuAAAATAAAAFYAAABSAAAAYQAAAH8AAABiAAAAVAAAAGcAAABZAAAAbwAAAGIAAABuAAAAYQAAAG8AAABSAAAAYAAAAFQAAABjAAAAUAAAAGkAAABYAAAAagAAAFoAAABxAAAAZAAAAGYAAABTAAAAVwAAAGwAAAByAAAAXAAAAGUAAABmAAAAawAAAHAAAABRAAAAVQAAAF4AAABmAAAAZQAAAFcAAABVAAAAcgAAAHAAAABkAAAAZwAAAFsAAABhAAAAWQAAAHQAAABpAAAAbwAAAGgAAABrAAAAbgAAAHMAAABWAAAAXgAAAGAAAABpAAAAWAAAAGcAAABbAAAAcQAAAGMAAAB0AAAAagAAAF0AAABjAAAAWgAAAHUAAABtAAAAcQAAAGsAAAB/AAAAZQAAAF4AAABzAAAAaAAAAHAAAABsAAAAZAAAAF8AAABcAAAAdgAAAHIAAABtAAAAbQAAAGwAAABdAAAAXwAAAHUAAAB2AAAAagAAAG4AAABiAAAAaAAAAGAAAAB3AAAAbwAAAHMAAABvAAAAYQAAAG4AAABiAAAAdAAAAGcAAAB3AAAAcAAAAGsAAABmAAAAZQAAAHgAAABzAAAAcgAAAHEAAABjAAAAdAAAAGkAAAB1AAAAagAAAHkAAAByAAAAcAAAAGQAAABmAAAAdgAAAHgAAABsAAAAcwAAAG4AAABrAAAAaAAAAHgAAAB3AAAAcAAAAHQAAABnAAAAdwAAAG8AAABxAAAAaQAAAHkAAAB1AAAAfwAAAG0AAAB2AAAAcQAAAHkAAABqAAAAdgAAAHgAAABsAAAAcgAAAHUAAAB5AAAAbQAAAHcAAABvAAAAcwAAAG4AAAB5AAAAdAAAAHgAAAB4AAAAcwAAAHIAAABwAAAAeQAAAHcAAAB2AAAAeQAAAHQAAAB4AAAAdwAAAHUAAABxAAAAdgAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAEAAAAFAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAIAAAAFAAAAAQAAAAAAAAD/////AQAAAAAAAAADAAAABAAAAAIAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAUAAAABAAAAAAAAAAAAAAABAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAAFAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAQAAAAFAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAADAAAAAAAAAAAAAAABAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAABAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAADAAAABQAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAUAAAAFAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAADAAAAAAAAAAAAAAABAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAADAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAwAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAAAAAP////8DAAAAAAAAAAUAAAACAAAAAAAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAADAAAAAQAAAAAAAAABAAAAAAAAAAAAAAADAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAMAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAMAAAADAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAABQAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAADAAAAAAAAAAAAAAD/////AwAAAAAAAAAFAAAAAgAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAADAAAAAAAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAAAAAADAAAABQAAAAEAAAAAAAAA/////wMAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAEAAAABQAAAAEAAAAAAAAAAwAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAgAAAAUAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAMAAAABAAAAAAAAAAEAAAAAAAAABQAAAAAAAAAAAAAABQAAAAUAAAAAAAAAAAAAAP////8BAAAAAAAAAAMAAAAEAAAAAgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAABQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAUAAAAAAAAAAAAAAAUAAAAFAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAABQAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAQAAAP//////////AQAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAIAAAAAAAAAAAAAAAEAAAACAAAABgAAAAQAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAABwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAoAAAACAAAAAAAAAAAAAAABAAAAAQAAAAUAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAsAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAEAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAIAAAAAAAAAAAAAAAEAAAADAAAABwAAAAYAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAHAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAABAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAOAAAAAgAAAAAAAAAAAAAAAQAAAAAAAAAJAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAwAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAgAAAAAAAAAAAAAAAQAAAAQAAAAIAAAACgAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAsAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAACAAAAAAAAAAAAAAABAAAACwAAAA8AAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA4AAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAgAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAFAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAACAAAAAAAAAAAAAAABAAAADAAAABAAAAAMAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAANAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAIAAAAAAAAAAAAAAAEAAAAKAAAAEwAAAAgAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAADwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABAAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAJAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAgAAAAAAAAAAAAAAAQAAAA0AAAARAAAADQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAABEAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAADQAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAIAAAAAAAAAAAAAAAEAAAAOAAAAEgAAAA8AAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAPAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAAABIAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAEQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAABMAAAACAAAAAAAAAAAAAAABAAAA//////////8TAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAASAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABIAAAAAAAAAGAAAAAAAAAAhAAAAAAAAAB4AAAAAAAAAIAAAAAMAAAAxAAAAAQAAADAAAAADAAAAMgAAAAMAAAAIAAAAAAAAAAUAAAAFAAAACgAAAAUAAAAWAAAAAAAAABAAAAAAAAAAEgAAAAAAAAApAAAAAQAAACEAAAAAAAAAHgAAAAAAAAAEAAAAAAAAAAAAAAAFAAAAAgAAAAUAAAAPAAAAAQAAAAgAAAAAAAAABQAAAAUAAAAfAAAAAQAAABYAAAAAAAAAEAAAAAAAAAACAAAAAAAAAAYAAAAAAAAADgAAAAAAAAAKAAAAAAAAAAsAAAAAAAAAEQAAAAMAAAAYAAAAAQAAABcAAAADAAAAGQAAAAMAAAAAAAAAAAAAAAEAAAAFAAAACQAAAAUAAAAFAAAAAAAAAAIAAAAAAAAABgAAAAAAAAASAAAAAQAAAAoAAAAAAAAACwAAAAAAAAAEAAAAAQAAAAMAAAAFAAAABwAAAAUAAAAIAAAAAQAAAAAAAAAAAAAAAQAAAAUAAAAQAAAAAQAAAAUAAAAAAAAAAgAAAAAAAAAHAAAAAAAAABUAAAAAAAAAJgAAAAAAAAAJAAAAAAAAABMAAAAAAAAAIgAAAAMAAAAOAAAAAQAAABQAAAADAAAAJAAAAAMAAAADAAAAAAAAAA0AAAAFAAAAHQAAAAUAAAABAAAAAAAAAAcAAAAAAAAAFQAAAAAAAAAGAAAAAQAAAAkAAAAAAAAAEwAAAAAAAAAEAAAAAgAAAAwAAAAFAAAAGgAAAAUAAAAAAAAAAQAAAAMAAAAAAAAADQAAAAUAAAACAAAAAQAAAAEAAAAAAAAABwAAAAAAAAAaAAAAAAAAACoAAAAAAAAAOgAAAAAAAAAdAAAAAAAAACsAAAAAAAAAPgAAAAMAAAAmAAAAAQAAAC8AAAADAAAAQAAAAAMAAAAMAAAAAAAAABwAAAAFAAAALAAAAAUAAAANAAAAAAAAABoAAAAAAAAAKgAAAAAAAAAVAAAAAQAAAB0AAAAAAAAAKwAAAAAAAAAEAAAAAwAAAA8AAAAFAAAAHwAAAAUAAAADAAAAAQAAAAwAAAAAAAAAHAAAAAUAAAAHAAAAAQAAAA0AAAAAAAAAGgAAAAAAAAAfAAAAAAAAACkAAAAAAAAAMQAAAAAAAAAsAAAAAAAAADUAAAAAAAAAPQAAAAMAAAA6AAAAAQAAAEEAAAADAAAASwAAAAMAAAAPAAAAAAAAABYAAAAFAAAAIQAAAAUAAAAcAAAAAAAAAB8AAAAAAAAAKQAAAAAAAAAqAAAAAQAAACwAAAAAAAAANQAAAAAAAAAEAAAABAAAAAgAAAAFAAAAEAAAAAUAAAAMAAAAAQAAAA8AAAAAAAAAFgAAAAUAAAAaAAAAAQAAABwAAAAAAAAAHwAAAAAAAAAyAAAAAAAAADAAAAAAAAAAMQAAAAMAAAAgAAAAAAAAAB4AAAADAAAAIQAAAAMAAAAYAAAAAwAAABIAAAADAAAAEAAAAAMAAABGAAAAAAAAAEMAAAAAAAAAQgAAAAMAAAA0AAAAAwAAADIAAAAAAAAAMAAAAAAAAAAlAAAAAwAAACAAAAAAAAAAHgAAAAMAAABTAAAAAAAAAFcAAAADAAAAVQAAAAMAAABKAAAAAwAAAEYAAAAAAAAAQwAAAAAAAAA5AAAAAQAAADQAAAADAAAAMgAAAAAAAAAZAAAAAAAAABcAAAAAAAAAGAAAAAMAAAARAAAAAAAAAAsAAAADAAAACgAAAAMAAAAOAAAAAwAAAAYAAAADAAAAAgAAAAMAAAAtAAAAAAAAACcAAAAAAAAAJQAAAAMAAAAjAAAAAwAAABkAAAAAAAAAFwAAAAAAAAAbAAAAAwAAABEAAAAAAAAACwAAAAMAAAA/AAAAAAAAADsAAAADAAAAOQAAAAMAAAA4AAAAAwAAAC0AAAAAAAAAJwAAAAAAAAAuAAAAAwAAACMAAAADAAAAGQAAAAAAAAAkAAAAAAAAABQAAAAAAAAADgAAAAMAAAAiAAAAAAAAABMAAAADAAAACQAAAAMAAAAmAAAAAwAAABUAAAADAAAABwAAAAMAAAA3AAAAAAAAACgAAAAAAAAAGwAAAAMAAAA2AAAAAwAAACQAAAAAAAAAFAAAAAAAAAAzAAAAAwAAACIAAAAAAAAAEwAAAAMAAABIAAAAAAAAADwAAAADAAAALgAAAAMAAABJAAAAAwAAADcAAAAAAAAAKAAAAAAAAABHAAAAAwAAADYAAAADAAAAJAAAAAAAAABAAAAAAAAAAC8AAAAAAAAAJgAAAAMAAAA+AAAAAAAAACsAAAADAAAAHQAAAAMAAAA6AAAAAwAAACoAAAADAAAAGgAAAAMAAABUAAAAAAAAAEUAAAAAAAAAMwAAAAMAAABSAAAAAwAAAEAAAAAAAAAALwAAAAAAAABMAAAAAwAAAD4AAAAAAAAAKwAAAAMAAABhAAAAAAAAAFkAAAADAAAARwAAAAMAAABiAAAAAwAAAFQAAAAAAAAARQAAAAAAAABgAAAAAwAAAFIAAAADAAAAQAAAAAAAAABLAAAAAAAAAEEAAAAAAAAAOgAAAAMAAAA9AAAAAAAAADUAAAADAAAALAAAAAMAAAAxAAAAAwAAACkAAAADAAAAHwAAAAMAAABeAAAAAAAAAFYAAAAAAAAATAAAAAMAAABRAAAAAwAAAEsAAAAAAAAAQQAAAAAAAABCAAAAAwAAAD0AAAAAAAAANQAAAAMAAABrAAAAAAAAAGgAAAADAAAAYAAAAAMAAABlAAAAAwAAAF4AAAAAAAAAVgAAAAAAAABVAAAAAwAAAFEAAAADAAAASwAAAAAAAAA5AAAAAAAAADsAAAAAAAAAPwAAAAMAAABKAAAAAAAAAE4AAAADAAAATwAAAAMAAABTAAAAAwAAAFwAAAADAAAAXwAAAAMAAAAlAAAAAAAAACcAAAADAAAALQAAAAMAAAA0AAAAAAAAADkAAAAAAAAAOwAAAAAAAABGAAAAAwAAAEoAAAAAAAAATgAAAAMAAAAYAAAAAAAAABcAAAADAAAAGQAAAAMAAAAgAAAAAwAAACUAAAAAAAAAJwAAAAMAAAAyAAAAAwAAADQAAAAAAAAAOQAAAAAAAAAuAAAAAAAAADwAAAAAAAAASAAAAAMAAAA4AAAAAAAAAEQAAAADAAAAUAAAAAMAAAA/AAAAAwAAAE0AAAADAAAAWgAAAAMAAAAbAAAAAAAAACgAAAADAAAANwAAAAMAAAAjAAAAAAAAAC4AAAAAAAAAPAAAAAAAAAAtAAAAAwAAADgAAAAAAAAARAAAAAMAAAAOAAAAAAAAABQAAAADAAAAJAAAAAMAAAARAAAAAwAAABsAAAAAAAAAKAAAAAMAAAAZAAAAAwAAACMAAAAAAAAALgAAAAAAAABHAAAAAAAAAFkAAAAAAAAAYQAAAAMAAABJAAAAAAAAAFsAAAADAAAAZwAAAAMAAABIAAAAAwAAAFgAAAADAAAAaQAAAAMAAAAzAAAAAAAAAEUAAAADAAAAVAAAAAMAAAA2AAAAAAAAAEcAAAAAAAAAWQAAAAAAAAA3AAAAAwAAAEkAAAAAAAAAWwAAAAMAAAAmAAAAAAAAAC8AAAADAAAAQAAAAAMAAAAiAAAAAwAAADMAAAAAAAAARQAAAAMAAAAkAAAAAwAAADYAAAAAAAAARwAAAAAAAABgAAAAAAAAAGgAAAAAAAAAawAAAAMAAABiAAAAAAAAAG4AAAADAAAAcwAAAAMAAABhAAAAAwAAAG8AAAADAAAAdwAAAAMAAABMAAAAAAAAAFYAAAADAAAAXgAAAAMAAABSAAAAAAAAAGAAAAAAAAAAaAAAAAAAAABUAAAAAwAAAGIAAAAAAAAAbgAAAAMAAAA6AAAAAAAAAEEAAAADAAAASwAAAAMAAAA+AAAAAwAAAEwAAAAAAAAAVgAAAAMAAABAAAAAAwAAAFIAAAAAAAAAYAAAAAAAAABVAAAAAAAAAFcAAAAAAAAAUwAAAAMAAABlAAAAAAAAAGYAAAADAAAAZAAAAAMAAABrAAAAAwAAAHAAAAADAAAAcgAAAAMAAABCAAAAAAAAAEMAAAADAAAARgAAAAMAAABRAAAAAAAAAFUAAAAAAAAAVwAAAAAAAABeAAAAAwAAAGUAAAAAAAAAZgAAAAMAAAAxAAAAAAAAADAAAAADAAAAMgAAAAMAAAA9AAAAAwAAAEIAAAAAAAAAQwAAAAMAAABLAAAAAwAAAFEAAAAAAAAAVQAAAAAAAABfAAAAAAAAAFwAAAAAAAAAUwAAAAAAAABPAAAAAAAAAE4AAAAAAAAASgAAAAMAAAA/AAAAAQAAADsAAAADAAAAOQAAAAMAAABtAAAAAAAAAGwAAAAAAAAAZAAAAAUAAABdAAAAAQAAAF8AAAAAAAAAXAAAAAAAAABNAAAAAQAAAE8AAAAAAAAATgAAAAAAAAB1AAAABAAAAHYAAAAFAAAAcgAAAAUAAABqAAAAAQAAAG0AAAAAAAAAbAAAAAAAAABaAAAAAQAAAF0AAAABAAAAXwAAAAAAAABaAAAAAAAAAE0AAAAAAAAAPwAAAAAAAABQAAAAAAAAAEQAAAAAAAAAOAAAAAMAAABIAAAAAQAAADwAAAADAAAALgAAAAMAAABqAAAAAAAAAF0AAAAAAAAATwAAAAUAAABjAAAAAQAAAFoAAAAAAAAATQAAAAAAAABYAAAAAQAAAFAAAAAAAAAARAAAAAAAAAB1AAAAAwAAAG0AAAAFAAAAXwAAAAUAAABxAAAAAQAAAGoAAAAAAAAAXQAAAAAAAABpAAAAAQAAAGMAAAABAAAAWgAAAAAAAABpAAAAAAAAAFgAAAAAAAAASAAAAAAAAABnAAAAAAAAAFsAAAAAAAAASQAAAAMAAABhAAAAAQAAAFkAAAADAAAARwAAAAMAAABxAAAAAAAAAGMAAAAAAAAAUAAAAAUAAAB0AAAAAQAAAGkAAAAAAAAAWAAAAAAAAABvAAAAAQAAAGcAAAAAAAAAWwAAAAAAAAB1AAAAAgAAAGoAAAAFAAAAWgAAAAUAAAB5AAAAAQAAAHEAAAAAAAAAYwAAAAAAAAB3AAAAAQAAAHQAAAABAAAAaQAAAAAAAAB3AAAAAAAAAG8AAAAAAAAAYQAAAAAAAABzAAAAAAAAAG4AAAAAAAAAYgAAAAMAAABrAAAAAQAAAGgAAAADAAAAYAAAAAMAAAB5AAAAAAAAAHQAAAAAAAAAZwAAAAUAAAB4AAAAAQAAAHcAAAAAAAAAbwAAAAAAAABwAAAAAQAAAHMAAAAAAAAAbgAAAAAAAAB1AAAAAQAAAHEAAAAFAAAAaQAAAAUAAAB2AAAAAQAAAHkAAAAAAAAAdAAAAAAAAAByAAAAAQAAAHgAAAABAAAAdwAAAAAAAAByAAAAAAAAAHAAAAAAAAAAawAAAAAAAABkAAAAAAAAAGYAAAAAAAAAZQAAAAMAAABTAAAAAQAAAFcAAAADAAAAVQAAAAMAAAB2AAAAAAAAAHgAAAAAAAAAcwAAAAUAAABsAAAAAQAAAHIAAAAAAAAAcAAAAAAAAABcAAAAAQAAAGQAAAAAAAAAZgAAAAAAAAB1AAAAAAAAAHkAAAAFAAAAdwAAAAUAAABtAAAAAQAAAHYAAAAAAAAAeAAAAAAAAABfAAAAAQAAAGwAAAABAAAAcgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAAAAAAAQAAAAEAAAABAAAAAAAAAAAAAAABAAAAAAAAAAEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAB+ogX28rbpPxqumpJv+fM/165tC4ns9D+XaEnTqUsEQFrOtNlC4PA/3U+0XG6P9b9TdUUBxTTjP4PUp8ex1ty/B1rD/EN43z+lcDi6LLrZP/a45NWEHMY/oJ5ijLDZ+j/xw3rjxWPjP2B8A46ioQdAotff3wla2z+FMSpA1jj+v6b5Y1mtPbS/cIu8K0F457/2esiyJpDNv98k5Ts2NeA/pvljWa09tD88ClUJ60MDQPZ6yLImkM0/4ONKxa0UBcD2uOTVhBzGv5G7JRxGave/8cN648Vj47+HCwtkjAXIv6LX398JWtu/qyheaCAL9D9TdUUBxTTjv4gyTxslhwVAB1rD/EN4378EH/28teoFwH6iBfbytum/F6ztFYdK/r/Xrm0Liez0vwcS6wNGWeO/Ws602ULg8L9TCtRLiLT8P8pi5RexJsw/BlIKPVwR5T95Wyu0/QjnP5PjoT7YYcu/mBhKZ6zrwj8wRYS7NebuP3qW6geh+Ls/SLrixebL3r+pcyymN9XrPwmkNHp7xec/GWNMZVAA17+82s+x2BLiPwn2ytbJ9ek/LgEH1sMS1j8yp/2LhTfeP+SnWwtQBbu/d38gkp5X7z8ytsuHaADGPzUYObdf1+m/7IauECWhwz+cjSACjzniP76Z+wUhN9K/1+GEKzup67+/GYr/04baPw6idWOvsuc/ZedTWsRa5b/EJQOuRzi0v/OncYhHPes/h49PixY53j+i8wWfC03Nvw2idWOvsue/ZedTWsRa5T/EJQOuRzi0P/KncYhHPeu/iY9PixY53r+i8wWfC03NP9anWwtQBbs/d38gkp5X778ytsuHaADGvzUYObdf1+k/74auECWhw7+cjSACjzniv8CZ+wUhN9I/1uGEKzup6z+/GYr/04bavwmkNHp7xee/F2NMZVAA1z+82s+x2BLivwr2ytbJ9em/KwEH1sMS1r8yp/2LhTfev81i5RexJsy/BlIKPVwR5b95Wyu0/Qjnv5DjoT7YYcs/nBhKZ6zrwr8wRYS7Nebuv3OW6geh+Lu/SLrixebL3j+pcyymN9Xrv8rHIFfWehZAMBwUdlo0DECTUc17EOb2PxpVB1SWChdAzjbhb9pTDUDQhmdvECX5P9FlMKCC9+g/IIAzjELgE0DajDngMv8GQFhWDmDPjNs/y1guLh96EkAxPi8k7DIEQJCc4URlhRhA3eLKKLwkEECqpNAyTBD/P6xpjXcDiwVAFtl//cQm4z+Ibt3XKiYTQM7mCLUb3QdAoM1t8yVv7D8aLZv2Nk8UQEAJPV5nQwxAtSsfTCoE9z9TPjXLXIIWQBVanC5W9AtAYM3d7Adm9j++5mQz1FoWQBUThyaVBghAwH5muQsV7T89Q1qv82MUQJoWGOfNuBdAzrkClkmwDkDQjKq77t37Py+g0dtitsE/ZwAMTwVPEUBojepluNwBQGYbtuW+t9w/HNWIJs6MEkDTNuQUSlgEQKxktPP5TcQ/ixbLB8JjEUCwuWjXMQYCQAS/R09FkRdAowpiZjhhDkB7LmlczD/7P01iQmhhsAVAnrtTwDy84z/Z6jfQ2TgTQChOCXMnWwpAhrW3daoz8z/HYJvVPI4VQLT3ik5FcA5Angi7LOZd+z+NNVzDy5gXQBXdvVTFUA1AYNMgOeYe+T8+qHXGCwkXQKQTOKwa5AJA8gFVoEMW0T+FwzJyttIRQAEAAAD/////BwAAAP////8xAAAA/////1cBAAD/////YQkAAP////+nQQAA/////5HLAQD/////95AMAP/////B9lcAAAAAAAAAAAAAAAAAAgAAAP////8OAAAA/////2IAAAD/////rgIAAP/////CEgAA/////06DAAD/////IpcDAP/////uIRkA/////4LtrwAAAAAAAAAAAAAAAAAAAAAAAgAAAP//////////AQAAAAMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////wIAAAD//////////wEAAAAAAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA/////////////////////wEAAAD///////////////8CAAAA////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD///////////////////////////////8CAAAA////////////////AQAAAP////////////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAAAQAAAP//////////AgAAAP//////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAAEAAAD//////////wIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAgAAAAAAAAACAAAAAQAAAAEAAAACAAAAAgAAAAAAAAAFAAAABQAAAAAAAAACAAAAAgAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAABAAAAAgAAAAIAAAACAAAAAAAAAAUAAAAGAAAAAAAAAAIAAAACAAAAAwAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAIAAAAAAAAAAgAAAAEAAAADAAAAAgAAAAIAAAAAAAAABQAAAAcAAAAAAAAAAgAAAAIAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAgAAAAAAAAACAAAAAQAAAAQAAAACAAAAAgAAAAAAAAAFAAAACAAAAAAAAAACAAAAAgAAAAMAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAACAAAAAAAAAAIAAAABAAAAAAAAAAIAAAACAAAAAAAAAAUAAAAJAAAAAAAAAAIAAAACAAAAAwAAAAUAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAIAAAACAAAAAAAAAAMAAAAOAAAAAgAAAAAAAAACAAAAAwAAAAAAAAAAAAAAAgAAAAIAAAADAAAABgAAAAAAAAAAAAAAAAAAAAAAAAALAAAAAgAAAAIAAAAAAAAAAwAAAAoAAAACAAAAAAAAAAIAAAADAAAAAQAAAAAAAAACAAAAAgAAAAMAAAAHAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAACAAAAAgAAAAAAAAADAAAACwAAAAIAAAAAAAAAAgAAAAMAAAACAAAAAAAAAAIAAAACAAAAAwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADQAAAAIAAAACAAAAAAAAAAMAAAAMAAAAAgAAAAAAAAACAAAAAwAAAAMAAAAAAAAAAgAAAAIAAAADAAAACQAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAgAAAAIAAAAAAAAAAwAAAA0AAAACAAAAAAAAAAIAAAADAAAABAAAAAAAAAACAAAAAgAAAAMAAAAKAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAACAAAAAgAAAAAAAAADAAAABgAAAAIAAAAAAAAAAgAAAAMAAAAPAAAAAAAAAAIAAAACAAAAAwAAAAsAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAIAAAACAAAAAAAAAAMAAAAHAAAAAgAAAAAAAAACAAAAAwAAABAAAAAAAAAAAgAAAAIAAAADAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAgAAAAIAAAAAAAAAAwAAAAgAAAACAAAAAAAAAAIAAAADAAAAEQAAAAAAAAACAAAAAgAAAAMAAAANAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAACAAAAAgAAAAAAAAADAAAACQAAAAIAAAAAAAAAAgAAAAMAAAASAAAAAAAAAAIAAAACAAAAAwAAAA4AAAAAAAAAAAAAAAAAAAAAAAAACQAAAAIAAAACAAAAAAAAAAMAAAAFAAAAAgAAAAAAAAACAAAAAwAAABMAAAAAAAAAAgAAAAIAAAADAAAADwAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAgAAAAAAAAACAAAAAQAAABMAAAACAAAAAgAAAAAAAAAFAAAACgAAAAAAAAACAAAAAgAAAAMAAAAQAAAAAAAAAAAAAAAAAAAAAAAAABEAAAACAAAAAAAAAAIAAAABAAAADwAAAAIAAAACAAAAAAAAAAUAAAALAAAAAAAAAAIAAAACAAAAAwAAABEAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAIAAAAAAAAAAgAAAAEAAAAQAAAAAgAAAAIAAAAAAAAABQAAAAwAAAAAAAAAAgAAAAIAAAADAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAATAAAAAgAAAAAAAAACAAAAAQAAABEAAAACAAAAAgAAAAAAAAAFAAAADQAAAAAAAAACAAAAAgAAAAMAAAATAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAACAAAAAAAAAAIAAAABAAAAEgAAAAIAAAACAAAAAAAAAAUAAAAOAAAAAAAAAAIAAAACAAAAAwAAAAIAAAABAAAAAAAAAAEAAAACAAAAAAAAAAAAAAACAAAAAQAAAAAAAAABAAAAAgAAAAEAAAAAAAAAAgAAAAAAAAAFAAAABAAAAAAAAAABAAAABQAAAAAAAAAAAAAABQAAAAQAAAAAAAAAAQAAAAUAAAAEAAAAAAAAAAUAAAAAAAAAAgAAAAEAAAAAAAAAAQAAAAIAAAAAAAAAAAAAAAIAAAABAAAAAAAAAAEAAAACAAAAAQAAAAAAAAACAAAAAgAAAAAAAAABAAAAAAAAAAAAAAAFAAAABAAAAAAAAAABAAAABQAAAAAAAAAAAAAABQAAAAQAAAAAAAAAAQAAAAUAAAAEAAAAAAAAAAUAAAAFAAAAAAAAAAEAAAAAAAAAAAAAAMuhRbbsNlBBYqHW9OmHIkF9XBuqnS31QAK37uYhNMhAOSo3UUupm0DC+6pc6JxvQHV9eseEEEJAzURsCyqlFEB8BQ4NMJjnPyy3tBoS97o/xawXQznRjj89J2K2CZxhP6vX43RIIDQ/S8isgygEBz+LvFHQkmzaPjFFFO7wMq4+AADMLkTtjkIAAOgkJqxhQgAAU7B0MjRCAADwpBcVB0IAAACYP2HaQQAAAIn/Ja5BzczM4Eg6gUHNzMxMU7BTQTMzMzNfgCZBAAAAAEi3+UAAAAAAwGPNQDMzMzMzy6BAmpmZmZkxc0AzMzMzM/NFQDMzMzMzMxlAzczMzMzM7D+ygXSx2U6RQKimJOvQKnpA23hmONTHY0A/AGcxyudNQNb3K647mzZA+S56rrwWIUAm4kUQ+9UJQKre9hGzh/M/BLvoy9WG3T+LmqMf8VHGP2m3nYNV37A/gbFHcyeCmT+cBPWBckiDP61tZACjKW0/q2RbYVUYVj8uDypVyLNAP6jGS5cA5zBBwcqhBdCNGUEGEhQ/JVEDQT6WPnRbNO1AB/AWSJgT1kDfUWNCNLDAQNk+5C33OqlAchWL34QSk0DKvtDIrNV8QNF0G3kFzGVASSeWhBl6UED+/0mNGuk4QGjA/dm/1CJALPLPMql6DEDSHoDrwpP1P2jouzWST+A/egAAAAAAAABKAwAAAAAAAPoWAAAAAAAAyqAAAAAAAAB6ZQQAAAAAAErGHgAAAAAA+mvXAAAAAADK8+MFAAAAAHqqOykAAAAASqmhIAEAAAD6oGvkBwAAAMpm8T43AAAAes+ZuIIBAABKrDQMkwoAAPq1cFUFSgAAyvkUViUGAgAAAAAAAwAAAAYAAAACAAAABQAAAAEAAAAEAAAAAAAAAAAAAAAFAAAAAwAAAAEAAAAGAAAABAAAAAIAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAP////////////////////////////////////8AAAAA/////wAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAP////8AAAAAAAAAAAEAAAABAAAAAAAAAAAAAAD/////AAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAA/////wUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////AAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////////////////////////////wAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAUAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////////////////////////////8AAAAAAQAAAAEAAAABAAAAAQAAAAEAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAABAAAAAAAAAAAAAAABAAAAAQAAAAEAAAAAAAAAAQAAAAAAAAAFAAAAAQAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAAAAAABAAEAAAEBAAAAAAABAAAAAQAAAAEAAQAAAAAAAAAAAAAAAAAAAAAEAAAABAAAAAAAAAACAAAAAQAAAAMAAAAOAAAABgAAAAsAAAACAAAABwAAAAEAAAAYAAAABQAAAAoAAAABAAAABgAAAAAAAAAmAAAABwAAAAwAAAADAAAACAAAAAIAAAAxAAAACQAAAA4AAAAAAAAABQAAAAQAAAA6AAAACAAAAA0AAAAEAAAACQAAAAMAAAA/AAAACwAAAAYAAAAPAAAACgAAABAAAABIAAAADAAAAAcAAAAQAAAACwAAABEAAABTAAAACgAAAAUAAAATAAAADgAAAA8AAABhAAAADQAAAAgAAAARAAAADAAAABIAAABrAAAADgAAAAkAAAASAAAADQAAABMAAAB1AAAADwAAABMAAAARAAAAEgAAABAAAAAHAAAABwAAAAEAAAACAAAABAAAAAMAAAAAAAAAAAAAAAcAAAADAAAAAQAAAAIAAAAFAAAABAAAAAAAAAAAAAAAYWxnb3MuYwBfcG9seWZpbGxJbnRlcm5hbABhZGphY2VudEZhY2VEaXJbdG1wRmlqay5mYWNlXVtmaWprLmZhY2VdID09IEtJAGZhY2VpamsuYwBfZmFjZUlqa1BlbnRUb0dlb0JvdW5kYXJ5AGFkamFjZW50RmFjZURpcltjZW50ZXJJSksuZmFjZV1bZmFjZTJdID09IEtJAF9mYWNlSWprVG9HZW9Cb3VuZGFyeQBwb2x5Z29uLT5uZXh0ID09IE5VTEwAbGlua2VkR2VvLmMAYWRkTmV3TGlua2VkUG9seWdvbgBuZXh0ICE9IE5VTEwAbG9vcCAhPSBOVUxMAGFkZE5ld0xpbmtlZExvb3AAcG9seWdvbi0+Zmlyc3QgPT0gTlVMTABhZGRMaW5rZWRMb29wAGNvb3JkICE9IE5VTEwAYWRkTGlua2VkQ29vcmQAbG9vcC0+Zmlyc3QgPT0gTlVMTABpbm5lckxvb3BzICE9IE5VTEwAbm9ybWFsaXplTXVsdGlQb2x5Z29uAGJib3hlcyAhPSBOVUxMAGNhbmRpZGF0ZXMgIT0gTlVMTABmaW5kUG9seWdvbkZvckhvbGUAY2FuZGlkYXRlQkJveGVzICE9IE5VTEwAcmV2RGlyICE9IElOVkFMSURfRElHSVQAbG9jYWxpai5jAGgzVG9Mb2NhbElqawBiYXNlQ2VsbCAhPSBvcmlnaW5CYXNlQ2VsbAAhKG9yaWdpbk9uUGVudCAmJiBpbmRleE9uUGVudCkAcGVudGFnb25Sb3RhdGlvbnMgPj0gMABkaXJlY3Rpb25Sb3RhdGlvbnMgPj0gMABiYXNlQ2VsbCA9PSBvcmlnaW5CYXNlQ2VsbABiYXNlQ2VsbCAhPSBJTlZBTElEX0JBU0VfQ0VMTABsb2NhbElqa1RvSDMAIV9pc0Jhc2VDZWxsUGVudGFnb24oYmFzZUNlbGwpAGJhc2VDZWxsUm90YXRpb25zID49IDAAd2l0aGluUGVudGFnb25Sb3RhdGlvbnMgPj0gMABncmFwaC0+YnVja2V0cyAhPSBOVUxMAHZlcnRleEdyYXBoLmMAaW5pdFZlcnRleEdyYXBoAG5vZGUgIT0gTlVMTABhZGRWZXJ0ZXhOb2Rl";function Y(A){return A}function O(A){return A.replace(/\b__Z[\w\d_]+/g,(function(A){return A===A?A:A+" ["+A+"]"}))}function j(){var A=new Error;if(!A.stack){try{throw new Error(0)}catch(e){A=e}if(!A.stack)return"(no stack trace available)"}return A.stack.toString()}function N(){return p.length}function Z(A){try{var e=new ArrayBuffer(A);if(e.byteLength!=A)return;return new Int8Array(e).set(p),$(e),Q(e),1}catch(A){}}var W="function"==typeof atob?atob:function(A){var e,r,t,i,n,o,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f="",s=0;A=A.replace(/[^A-Za-z0-9\+\/\=]/g,"");do{e=a.indexOf(A.charAt(s++))<<2|(i=a.indexOf(A.charAt(s++)))>>4,r=(15&i)<<4|(n=a.indexOf(A.charAt(s++)))>>2,t=(3&n)<<6|(o=a.indexOf(A.charAt(s++))),f+=String.fromCharCode(e),64!==n&&(f+=String.fromCharCode(r)),64!==o&&(f+=String.fromCharCode(t))}while(s>2]=A,i[a+4>>2]=e,(a=0!=(0|n))&&(i[n>>2]=0),0|UA(A,e))return I=o,0|(d=1);i[d>>2]=0;A:do{if((0|r)>=1)if(a)for(l=0,h=1,c=1,f=0,a=A;;){if(!(f|l)){if(0==(0|(a=0|U(a,e,4,d)))&0==(0|(e=0|M()))){a=2;break A}if(0|UA(a,e)){a=1;break A}}if(0==(0|(a=0|U(a,e,0|i[16+(l<<2)>>2],d)))&0==(0|(e=0|M()))){a=2;break A}if(i[(A=t+(c<<3)|0)>>2]=a,i[A+4>>2]=e,i[n+(c<<2)>>2]=h,A=(0|(f=f+1|0))==(0|h),u=6==(0|(s=l+1|0)),0|UA(a,e)){a=1;break A}if((0|(h=h+(u&A&1)|0))>(0|r)){a=0;break}l=A?u?0:s:l,c=c+1|0,f=A?0:f}else for(l=0,h=1,c=1,f=0,a=A;;){if(!(f|l)){if(0==(0|(a=0|U(a,e,4,d)))&0==(0|(e=0|M()))){a=2;break A}if(0|UA(a,e)){a=1;break A}}if(0==(0|(a=0|U(a,e,0|i[16+(l<<2)>>2],d)))&0==(0|(e=0|M()))){a=2;break A}if(i[(A=t+(c<<3)|0)>>2]=a,i[A+4>>2]=e,A=(0|(f=f+1|0))==(0|h),u=6==(0|(s=l+1|0)),0|UA(a,e)){a=1;break A}if((0|(h=h+(u&A&1)|0))>(0|r)){a=0;break}l=A?u?0:s:l,c=c+1|0,f=A?0:f}else a=0}while(0);return I=o,0|(d=a)}function P(A,e,r,t,n,o,a){r|=0,t|=0,n|=0,o|=0,a|=0;var f,s,u=0,l=0,h=0,c=0,d=0;if(s=I,I=I+16|0,f=s,0==(0|(A|=0))&0==(0|(e|=0)))I=s;else{if(u=0|Me(0|A,0|e,0|o,((0|o)<0)<<31>>31|0),M(),!(0==(0|(d=0|i[(c=l=t+(u<<3)|0)>>2]))&0==(0|(c=0|i[c+4>>2]))|(h=(0|d)==(0|A)&(0|c)==(0|e))))do{h=(0|(c=0|i[(d=l=t+((u=(u+1|0)%(0|o)|0)<<3)|0)>>2]))==(0|A)&(0|(d=0|i[d+4>>2]))==(0|e)}while(!(0==(0|c)&0==(0|d)|h));u=n+(u<<2)|0,h&&(0|i[u>>2])<=(0|a)||(i[(d=l)>>2]=A,i[d+4>>2]=e,i[u>>2]=a,(0|a)>=(0|r)||(d=a+1|0,i[f>>2]=0,P(c=0|U(A,e,2,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,3,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,1,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,5,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,4,f),0|M(),r,t,n,o,d),i[f>>2]=0,P(c=0|U(A,e,6,f),0|M(),r,t,n,o,d))),I=s}}function U(A,e,r,t){A|=0,e|=0,r|=0;var n,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0;if((0|i[(t|=0)>>2])>0){a=0;do{r=0|fA(r),a=a+1|0}while((0|a)<(0|i[t>>2]))}n=0|Qe(0|A,0|e,45),M(),o=127&n,f=0|GA(A,e),a=0|Qe(0|A,0|e,52),M(),a&=15;A:do{if(a)for(;;){if(h=0|Qe(0|A,0|e,0|(l=3*(15-a|0)|0)),M(),h&=7,c=0==(0|RA(a)),a=a+-1|0,u=0|ye(7,0,0|l),e&=~(0|M()),A=(l=0|ye(0|i[(c?464:48)+(28*h|0)+(r<<2)>>2],0,0|l))|A&~u,e|=0|M(),!(r=0|i[(c?672:256)+(28*h|0)+(r<<2)>>2])){r=0;break A}if(!a){s=6;break}}else s=6}while(0);6==(0|s)&&(A|=h=0|ye(0|(c=0|i[880+(28*o|0)+(r<<2)>>2]),0,45),e=0|M()|-1040385&e,r=0|i[4304+(28*o|0)+(r<<2)>>2],127==(127&c|0)&&(c=0|ye(0|i[880+(28*o|0)+20>>2],0,45),e=0|M()|-1040385&e,r=0|i[4304+(28*o|0)+20>>2],A=0|TA(c|A,e),e=0|M(),i[t>>2]=1+(0|i[t>>2]))),s=0|Qe(0|A,0|e,45),M(),s&=127;A:do{if(0|S(s)){e:do{if(1==(0|GA(A,e))){if((0|o)!=(0|s)){if(0|R(s,0|i[7728+(28*o|0)>>2])){A=0|HA(A,e),f=1,e=0|M();break}A=0|TA(A,e),f=1,e=0|M();break}switch(0|f){case 5:A=0|HA(A,e),e=0|M(),i[t>>2]=5+(0|i[t>>2]),f=0;break e;case 3:A=0|TA(A,e),e=0|M(),i[t>>2]=1+(0|i[t>>2]),f=0;break e;default:return c=0,k(0|(h=0)),0|c}}else f=0}while(0);if((0|r)>0){a=0;do{A=0|SA(A,e),e=0|M(),a=a+1|0}while((0|a)!=(0|r))}if((0|o)!=(0|s)){if(!(0|T(s))){if(0!=(0|f)|5!=(0|GA(A,e)))break;i[t>>2]=1+(0|i[t>>2]);break}switch(127&n){case 8:case 118:break A}3!=(0|GA(A,e))&&(i[t>>2]=1+(0|i[t>>2]))}}else if((0|r)>0){a=0;do{A=0|TA(A,e),e=0|M(),a=a+1|0}while((0|a)!=(0|r))}}while(0);return i[t>>2]=((0|i[t>>2])+r|0)%6|0,c=A,k(0|(h=e)),0|c}function G(A,e,r,t,o,a){e|=0,r|=0,t|=0,o|=0,a|=0;var f,s,u,l,h,c,d,g,w,p=0,B=0,b=0,v=0,m=0,k=0,Q=0,y=0,E=0,x=0,D=0,_=0,F=0,C=0;if(w=I,I=I+48|0,c=w+32|0,d=w+16|0,g=w,(0|(p=0|i[(A|=0)>>2]))<=0)return I=w,0|(_=0);f=A+4|0,s=c+8|0,u=d+8|0,l=g+8|0,h=((0|e)<0)<<31>>31,D=0;A:for(;;){E=(B=0|i[f>>2])+(D<<4)|0,i[c>>2]=i[E>>2],i[c+4>>2]=i[E+4>>2],i[c+8>>2]=i[E+8>>2],i[c+12>>2]=i[E+12>>2],(0|D)==(p+-1|0)?(i[d>>2]=i[B>>2],i[d+4>>2]=i[B+4>>2],i[d+8>>2]=i[B+8>>2],i[d+12>>2]=i[B+12>>2]):(E=B+(D+1<<4)|0,i[d>>2]=i[E>>2],i[d+4>>2]=i[E+4>>2],i[d+8>>2]=i[E+8>>2],i[d+12>>2]=i[E+12>>2]),E=0|N(c,d,r);e:do{if((0|E)>0){x=+(0|E),y=0;r:for(;;){C=+(E-y|0),F=+(0|y),n[g>>3]=+n[c>>3]*C/x+ +n[d>>3]*F/x,n[l>>3]=+n[s>>3]*C/x+ +n[u>>3]*F/x,B=0|Me(0|(k=0|LA(g,r)),0|(Q=0|M()),0|e,0|h),M(),v=0|i[(b=p=a+(B<<3)|0)>>2],b=0|i[b+4>>2];t:do{if(0==(0|v)&0==(0|b))_=14;else for(m=0;;){if((0|m)>(0|e)){p=1;break t}if((0|v)==(0|k)&(0|b)==(0|Q)){p=7;break t}if(0==(0|(v=0|i[(b=p=a+((B=(B+1|0)%(0|e)|0)<<3)|0)>>2]))&0==(0|(b=0|i[b+4>>2]))){_=14;break}m=m+1|0}}while(0);switch(14==(0|_)&&(_=0,0==(0|k)&0==(0|Q)?p=7:(i[p>>2]=k,i[p+4>>2]=Q,p=0|i[t>>2],i[(m=o+(p<<3)|0)>>2]=k,i[m+4>>2]=Q,i[t>>2]=p+1,p=0)),7&p){case 7:case 0:break;default:break r}if((0|E)<=(0|(y=y+1|0))){_=8;break e}}if(0|p){p=-1,_=20;break A}}else _=8}while(0);if(8==(0|_)&&(_=0),(0|(D=D+1|0))>=(0|(p=0|i[A>>2]))){p=0,_=20;break}}return 20==(0|_)?(I=w,0|p):0}function S(A){return 0|i[7728+(28*(A|=0)|0)+16>>2]}function T(A){return 4==(0|(A|=0))|117==(0|A)|0}function V(A){return 0|i[11152+(216*(0|i[(A|=0)>>2])|0)+(72*(0|i[A+4>>2])|0)+(24*(0|i[A+8>>2])|0)+(i[A+12>>2]<<3)>>2]}function H(A){return 0|i[11152+(216*(0|i[(A|=0)>>2])|0)+(72*(0|i[A+4>>2])|0)+(24*(0|i[A+8>>2])|0)+(i[A+12>>2]<<3)+4>>2]}function R(A,e){return e|=0,(0|i[7728+(28*(A|=0)|0)+20>>2])==(0|e)?0|(e=1):0|(e=(0|i[7728+(28*A|0)+24>>2])==(0|e))}function L(A,e){return 0|i[880+(28*(A|=0)|0)+((e|=0)<<2)>>2]}function z(A,e){return e|=0,(0|i[880+(28*(A|=0)|0)>>2])==(0|e)?0|(e=0):(0|i[880+(28*A|0)+4>>2])==(0|e)?0|(e=1):(0|i[880+(28*A|0)+8>>2])==(0|e)?0|(e=2):(0|i[880+(28*A|0)+12>>2])==(0|e)?0|(e=3):(0|i[880+(28*A|0)+16>>2])==(0|e)?0|(e=4):(0|i[880+(28*A|0)+20>>2])==(0|e)?0|(e=5):0|((0|i[880+(28*A|0)+24>>2])==(0|e)?6:7)}function Y(A){return+n[(A|=0)+16>>3]<+n[A+24>>3]|0}function O(A,e){A|=0;var r,t,i=0;return(i=+n[(e|=0)>>3])>=+n[A+8>>3]&&i<=+n[A>>3]?(r=+n[A+16>>3],i=+n[A+24>>3],e=(t=+n[e+8>>3])>=i,A=t<=r&1,r>2]=0,l=l+4|0}while((0|l)<(0|h));return NA(e,o),OA(h=0|i[(l=o)>>2],l=0|i[l+4>>2],r),jA(h,l,t),s=+DA(r,t+8|0),n[r>>3]=+n[A>>3],n[(l=r+8|0)>>3]=+n[A+16>>3],n[t>>3]=+n[A+8>>3],n[(h=t+8|0)>>3]=+n[A+24>>3],u=+DA(r,t),h=~~+B(+u*u/+Ee(+ +f(+(+n[l>>3]-+n[h>>3])/(+n[r>>3]-+n[t>>3])),3)/(s*(2.59807621135*s)*.8)),I=a,0|(0==(0|h)?1:h)}function N(A,e,r){A|=0,e|=0,r|=0;var t,n,o,a,f,s=0,u=0;a=I,I=I+288|0,t=a+264|0,n=a+96|0,u=(s=o=a)+96|0;do{i[s>>2]=0,s=s+4|0}while((0|s)<(0|u));return NA(r,o),OA(s=0|i[(u=o)>>2],u=0|i[u+4>>2],t),jA(s,u,n),f=+DA(t,n+8|0),u=~~+B(+ +DA(A,e)/(2*f)),I=a,0|(0==(0|u)?1:u)}function Z(A,e,r,t){e|=0,r|=0,t|=0,i[(A|=0)>>2]=e,i[A+4>>2]=r,i[A+8>>2]=t}function W(A,e){A|=0;var r,t,o,a,s=0,u=0,l=0,h=0,c=0,d=0,g=0;i[(a=(e|=0)+8|0)>>2]=0,t=+n[A>>3],h=+f(+t),o=+n[A+8>>3],h+=.5*(c=+f(+o)/.8660254037844386),h-=+(0|(s=~~h)),c-=+(0|(A=~~c));do{if(h<.5){if(h<.3333333333333333){if(i[e>>2]=s,c<.5*(h+1)){i[e+4>>2]=A;break}A=A+1|0,i[e+4>>2]=A;break}if(A=(1&!(c<(g=1-h)))+A|0,i[e+4>>2]=A,g<=c&c<2*h){s=s+1|0,i[e>>2]=s;break}i[e>>2]=s;break}if(!(h<.6666666666666666)){if(s=s+1|0,i[e>>2]=s,c<.5*h){i[e+4>>2]=A;break}A=A+1|0,i[e+4>>2]=A;break}if(c<1-h){if(i[e+4>>2]=A,2*h-1>2]=s;break}}else A=A+1|0,i[e+4>>2]=A;s=s+1|0,i[e>>2]=s}while(0);do{if(t<0){if(1&A){s=~~(+(0|s)-(2*(+((d=0|ve(0|s,((0|s)<0)<<31>>31|0,0|(d=(A+1|0)/2|0),((0|d)<0)<<31>>31|0))>>>0)+4294967296*+(0|M()))+1)),i[e>>2]=s;break}s=~~(+(0|s)-2*(+((d=0|ve(0|s,((0|s)<0)<<31>>31|0,0|(d=(0|A)/2|0),((0|d)<0)<<31>>31|0))>>>0)+4294967296*+(0|M()))),i[e>>2]=s;break}}while(0);d=e+4|0,o<0&&(s=s-((1|A<<1)/2|0)|0,i[e>>2]=s,A=0-A|0,i[d>>2]=A),u=A-s|0,(0|s)<0?(l=0-s|0,i[d>>2]=u,i[a>>2]=l,i[e>>2]=0,A=u,s=0):l=0,(0|A)<0&&(s=s-A|0,i[e>>2]=s,l=l-A|0,i[a>>2]=l,i[d>>2]=0,A=0),r=s-l|0,u=A-l|0,(0|l)<0&&(i[e>>2]=r,i[d>>2]=u,i[a>>2]=0,A=u,s=r,l=0),(0|(u=(0|l)<(0|(u=(0|A)<(0|s)?A:s))?l:u))<=0||(i[e>>2]=s-u,i[d>>2]=A-u,i[a>>2]=l-u)}function J(A){var e,r=0,t=0,n=0,o=0,a=0;r=0|i[(A|=0)>>2],t=0|i[(e=A+4|0)>>2],(0|r)<0&&(t=t-r|0,i[e>>2]=t,i[(a=A+8|0)>>2]=(0|i[a>>2])-r,i[A>>2]=0,r=0),(0|t)<0?(r=r-t|0,i[A>>2]=r,o=(0|i[(a=A+8|0)>>2])-t|0,i[a>>2]=o,i[e>>2]=0,t=0):(a=o=A+8|0,o=0|i[o>>2]),(0|o)<0&&(r=r-o|0,i[A>>2]=r,t=t-o|0,i[e>>2]=t,i[a>>2]=0,o=0),(0|(n=(0|o)<(0|(n=(0|t)<(0|r)?t:r))?o:n))<=0||(i[A>>2]=r-n,i[e>>2]=t-n,i[a>>2]=o-n)}function K(A,e){e|=0;var r,t;t=0|i[(A|=0)+8>>2],r=+((0|i[A+4>>2])-t|0),n[e>>3]=+((0|i[A>>2])-t|0)-.5*r,n[e+8>>3]=.8660254037844386*r}function X(A,e,r){A|=0,e|=0,i[(r|=0)>>2]=(0|i[e>>2])+(0|i[A>>2]),i[r+4>>2]=(0|i[e+4>>2])+(0|i[A+4>>2]),i[r+8>>2]=(0|i[e+8>>2])+(0|i[A+8>>2])}function q(A,e,r){A|=0,e|=0,i[(r|=0)>>2]=(0|i[A>>2])-(0|i[e>>2]),i[r+4>>2]=(0|i[A+4>>2])-(0|i[e+4>>2]),i[r+8>>2]=(0|i[A+8>>2])-(0|i[e+8>>2])}function $(A,e){e|=0;var r,t=0;t=0|b(0|i[(A|=0)>>2],e),i[A>>2]=t,r=0|b(0|i[(t=A+4|0)>>2],e),i[t>>2]=r,e=0|b(0|i[(A=A+8|0)>>2],e),i[A>>2]=e}function AA(A){var e,r,t=0,n=0,o=0,a=0,f=0;f=(0|(r=0|i[(A|=0)>>2]))<0,A=(A=(n=(0|(a=((e=(0|(o=(0|i[A+4>>2])-(f?r:0)|0))<0)?0-o|0:0)+((0|i[A+8>>2])-(f?r:0))|0))<0)?0:a)-((o=(0|(n=(0|A)<(0|(n=(0|(t=(e?0:o)-(n?a:0)|0))<(0|(a=(f?0:r)-(e?o:0)-(n?a:0)|0))?t:a))?A:n))>0)?n:0)|0,t=t-(o?n:0)|0;A:do{switch(a-(o?n:0)|0){case 0:switch(0|t){case 0:return 0|(f=0==(0|A)?0:1==(0|A)?1:7);case 1:return 0|(f=0==(0|A)?2:1==(0|A)?3:7);default:break A}case 1:switch(0|t){case 0:return 0|(f=0==(0|A)?4:1==(0|A)?5:7);case 1:if(A)break A;return 0|(A=6);default:break A}}}while(0);return 0|(f=7)}function eA(A){var e,r,t=0,n=0,o=0,a=0,f=0;n=0|i[(e=(A|=0)+8|0)>>2],o=0|we(+((3*(t=(0|i[A>>2])-n|0)|0)-(n=(0|i[(r=A+4|0)>>2])-n|0)|0)/7),i[A>>2]=o,t=0|we(+((n<<1)+t|0)/7),i[r>>2]=t,i[e>>2]=0,n=t-o|0,(0|o)<0?(f=0-o|0,i[r>>2]=n,i[e>>2]=f,i[A>>2]=0,t=n,o=0,n=f):n=0,(0|t)<0&&(o=o-t|0,i[A>>2]=o,n=n-t|0,i[e>>2]=n,i[r>>2]=0,t=0),f=o-n|0,a=t-n|0,(0|n)<0?(i[A>>2]=f,i[r>>2]=a,i[e>>2]=0,t=a,a=f,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|t)<(0|a)?t:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=t-o,i[e>>2]=n-o)}function rA(A){var e,r,t=0,n=0,o=0,a=0,f=0;n=0|i[(e=(A|=0)+8|0)>>2],o=0|we(+(((t=(0|i[A>>2])-n|0)<<1)+(n=(0|i[(r=A+4|0)>>2])-n|0)|0)/7),i[A>>2]=o,t=0|we(+((3*n|0)-t|0)/7),i[r>>2]=t,i[e>>2]=0,n=t-o|0,(0|o)<0?(f=0-o|0,i[r>>2]=n,i[e>>2]=f,i[A>>2]=0,t=n,o=0,n=f):n=0,(0|t)<0&&(o=o-t|0,i[A>>2]=o,n=n-t|0,i[e>>2]=n,i[r>>2]=0,t=0),f=o-n|0,a=t-n|0,(0|n)<0?(i[A>>2]=f,i[r>>2]=a,i[e>>2]=0,t=a,a=f,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|t)<(0|a)?t:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=t-o,i[e>>2]=n-o)}function tA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],o=0|i[(r=A+4|0)>>2],a=0|i[(t=A+8|0)>>2],f=o+(3*n|0)|0,i[A>>2]=f,o=a+(3*o|0)|0,i[r>>2]=o,n=(3*a|0)+n|0,i[t>>2]=n,a=o-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=a,i[t>>2]=n,i[A>>2]=0,o=a,a=0):a=f,(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function iA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=(3*(n=0|i[(r=A+4|0)>>2])|0)+f|0,f=(o=0|i[(t=A+8|0)>>2])+(3*f|0)|0,i[A>>2]=f,i[r>>2]=a,n=(3*o|0)+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,f=0):o=a,(0|o)<0&&(f=f-o|0,i[A>>2]=f,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=f-n|0,a=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=a,i[t>>2]=0,f=e,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|a)<(0|f)?a:f))?n:o))<=0||(i[A>>2]=f-o,i[r>>2]=a-o,i[t>>2]=n-o)}function nA(A,e){A|=0;var r,t,n,o=0,a=0,f=0;((e|=0)+-1|0)>>>0>=6||(f=(0|i[15472+(12*e|0)>>2])+(0|i[A>>2])|0,i[A>>2]=f,n=A+4|0,a=(0|i[15472+(12*e|0)+4>>2])+(0|i[n>>2])|0,i[n>>2]=a,t=A+8|0,e=(0|i[15472+(12*e|0)+8>>2])+(0|i[t>>2])|0,i[t>>2]=e,o=a-f|0,(0|f)<0?(e=e-f|0,i[n>>2]=o,i[t>>2]=e,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,e=e-o|0,i[t>>2]=e,i[n>>2]=0,o=0),r=a-e|0,f=o-e|0,(0|e)<0?(i[A>>2]=r,i[n>>2]=f,i[t>>2]=0,a=r,e=0):f=o,(0|(o=(0|e)<(0|(o=(0|f)<(0|a)?f:a))?e:o))<=0||(i[A>>2]=a-o,i[n>>2]=f-o,i[t>>2]=e-o))}function oA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=(n=0|i[(r=A+4|0)>>2])+f|0,f=(o=0|i[(t=A+8|0)>>2])+f|0,i[A>>2]=f,i[r>>2]=a,n=o+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function aA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],a=0|i[(r=A+4|0)>>2],o=0|i[(t=A+8|0)>>2],f=a+n|0,i[A>>2]=f,a=o+a|0,i[r>>2]=a,n=o+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,a=0):(o=a,a=f),(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function fA(A){switch(0|(A|=0)){case 1:A=5;break;case 5:A=4;break;case 4:A=6;break;case 6:A=2;break;case 2:A=3;break;case 3:A=1}return 0|A}function sA(A){switch(0|(A|=0)){case 1:A=3;break;case 3:A=2;break;case 2:A=6;break;case 6:A=4;break;case 4:A=5;break;case 5:A=1}return 0|A}function uA(A){var e,r,t,n=0,o=0,a=0,f=0;n=0|i[(A|=0)>>2],o=0|i[(r=A+4|0)>>2],a=0|i[(t=A+8|0)>>2],f=o+(n<<1)|0,i[A>>2]=f,o=a+(o<<1)|0,i[r>>2]=o,n=(a<<1)+n|0,i[t>>2]=n,a=o-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=a,i[t>>2]=n,i[A>>2]=0,o=a,a=0):a=f,(0|o)<0&&(a=a-o|0,i[A>>2]=a,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=a-n|0,f=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=f,i[t>>2]=0,a=e,n=0):f=o,(0|(o=(0|n)<(0|(o=(0|f)<(0|a)?f:a))?n:o))<=0||(i[A>>2]=a-o,i[r>>2]=f-o,i[t>>2]=n-o)}function lA(A){var e,r,t,n=0,o=0,a=0,f=0;f=0|i[(A|=0)>>2],a=((n=0|i[(r=A+4|0)>>2])<<1)+f|0,f=(o=0|i[(t=A+8|0)>>2])+(f<<1)|0,i[A>>2]=f,i[r>>2]=a,n=(o<<1)+n|0,i[t>>2]=n,o=a-f|0,(0|f)<0?(n=n-f|0,i[r>>2]=o,i[t>>2]=n,i[A>>2]=0,f=0):o=a,(0|o)<0&&(f=f-o|0,i[A>>2]=f,n=n-o|0,i[t>>2]=n,i[r>>2]=0,o=0),e=f-n|0,a=o-n|0,(0|n)<0?(i[A>>2]=e,i[r>>2]=a,i[t>>2]=0,f=e,n=0):a=o,(0|(o=(0|n)<(0|(o=(0|a)<(0|f)?a:f))?n:o))<=0||(i[A>>2]=f-o,i[r>>2]=a-o,i[t>>2]=n-o)}function hA(A,e){e|=0;var r,t,n,o=0,a=0,f=0;return n=(0|(t=(0|i[(A|=0)>>2])-(0|i[e>>2])|0))<0,r=(0|(a=(0|i[A+4>>2])-(0|i[e+4>>2])-(n?t:0)|0))<0,e=(e=(A=(0|(f=(n?0-t|0:0)+(0|i[A+8>>2])-(0|i[e+8>>2])+(r?0-a|0:0)|0))<0)?0:f)-((a=(0|(A=(0|e)<(0|(A=(0|(o=(r?0:a)-(A?f:0)|0))<(0|(f=(n?0:t)-(r?a:0)-(A?f:0)|0))?o:f))?e:A))>0)?A:0)|0,o=o-(a?A:0)|0,0|((0|(A=(0|(A=f-(a?A:0)|0))>-1?A:0-A|0))>(0|(e=(0|(o=(0|o)>-1?o:0-o|0))>(0|(e=(0|e)>-1?e:0-e|0))?o:e))?A:e)}function cA(A,e){e|=0;var r;r=0|i[(A|=0)+8>>2],i[e>>2]=(0|i[A>>2])-r,i[e+4>>2]=(0|i[A+4>>2])-r}function dA(A,e){e|=0;var r,t,n,o=0,a=0,f=0;a=0|i[(A|=0)>>2],i[e>>2]=a,A=0|i[A+4>>2],i[(t=e+4|0)>>2]=A,i[(n=e+8|0)>>2]=0,o=A-a|0,(0|a)<0?(A=0-a|0,i[t>>2]=o,i[n>>2]=A,i[e>>2]=0,a=0):(o=A,A=0),(0|o)<0&&(a=a-o|0,i[e>>2]=a,A=A-o|0,i[n>>2]=A,i[t>>2]=0,o=0),r=a-A|0,f=o-A|0,(0|A)<0?(i[e>>2]=r,i[t>>2]=f,i[n>>2]=0,o=f,f=r,A=0):f=a,(0|(a=(0|A)<(0|(a=(0|o)<(0|f)?o:f))?A:a))<=0||(i[e>>2]=f-a,i[t>>2]=o-a,i[n>>2]=A-a)}function gA(A){var e,r,t,n;r=(n=0|i[(e=(A|=0)+8|0)>>2])-(0|i[A>>2])|0,i[A>>2]=r,A=(0|i[(t=A+4|0)>>2])-n|0,i[t>>2]=A,i[e>>2]=0-(A+r)}function wA(A){var e,r,t=0,n=0,o=0,a=0,f=0;t=0-(n=0|i[(A|=0)>>2])|0,i[A>>2]=t,i[(e=A+8|0)>>2]=0,a=(o=0|i[(r=A+4|0)>>2])+n|0,(0|n)>0?(i[r>>2]=a,i[e>>2]=n,i[A>>2]=0,t=0,o=a):n=0,(0|o)<0?(f=t-o|0,i[A>>2]=f,n=n-o|0,i[e>>2]=n,i[r>>2]=0,a=f-n|0,t=0-n|0,(0|n)<0?(i[A>>2]=a,i[r>>2]=t,i[e>>2]=0,o=t,n=0):(o=0,a=f)):a=t,(0|(t=(0|n)<(0|(t=(0|o)<(0|a)?o:a))?n:t))<=0||(i[A>>2]=a-t,i[r>>2]=o-t,i[e>>2]=n-t)}function pA(A,e,r,t){e|=0,r|=0,t|=0;var o,a=0,f=0,s=0,u=0;if(o=I,I=I+32|0,function(A,e){e|=0;var r=0,t=0,i=0;r=+n[(A=A|0)>>3],t=+l(+r),r=+h(+r),n[e+16>>3]=r,r=+n[A+8>>3],i=t*+l(+r),n[e>>3]=i,r=t*+h(+r),n[e+8>>3]=r}(A|=0,f=o),i[r>>2]=0,a=+fe(15888,f),(s=+fe(15912,f))>2]=1,a=s),(s=+fe(15936,f))>2]=2,a=s),(s=+fe(15960,f))>2]=3,a=s),(s=+fe(15984,f))>2]=4,a=s),(s=+fe(16008,f))>2]=5,a=s),(s=+fe(16032,f))>2]=6,a=s),(s=+fe(16056,f))>2]=7,a=s),(s=+fe(16080,f))>2]=8,a=s),(s=+fe(16104,f))>2]=9,a=s),(s=+fe(16128,f))>2]=10,a=s),(s=+fe(16152,f))>2]=11,a=s),(s=+fe(16176,f))>2]=12,a=s),(s=+fe(16200,f))>2]=13,a=s),(s=+fe(16224,f))>2]=14,a=s),(s=+fe(16248,f))>2]=15,a=s),(s=+fe(16272,f))>2]=16,a=s),(s=+fe(16296,f))>2]=17,a=s),(s=+fe(16320,f))>2]=18,a=s),(s=+fe(16344,f))>2]=19,a=s),(s=+d(+(1-.5*a)))<1e-16)return i[t>>2]=0,i[t+4>>2]=0,i[t+8>>2]=0,i[t+12>>2]=0,void(I=o);if(r=0|i[r>>2],a=+EA((a=+n[16368+(24*r|0)>>3])-+EA(+function(A,e){A|=0;var r=0,t=0,i=0,o=0,a=0;return o=+n[(e=e|0)>>3],t=+l(+o),i=+n[e+8>>3]-+n[A+8>>3],a=t*+h(+i),r=+n[A>>3],+ +p(+a,+(+h(+o)*+l(+r)-+l(+i)*(t*+h(+r))))}(15568+(r<<4)|0,A))),u=0|RA(e)?+EA(a+-.3334731722518321):a,a=+c(+s)/.381966011250105,(0|e)>0){f=0;do{a*=2.6457513110645907,f=f+1|0}while((0|f)!=(0|e))}s=+l(+u)*a,n[t>>3]=s,u=+h(+u)*a,n[t+8>>3]=u,I=o}function BA(A,e,r,t,o){e|=0,r|=0,t|=0,o|=0;var a=0,u=0;if((a=+function(A){var e=0,r=0;return r=+n[(A=A|0)>>3],e=+n[A+8>>3],+ +s(+(r*r+e*e))}(A|=0))<1e-16)return e=15568+(e<<4)|0,i[o>>2]=i[e>>2],i[o+4>>2]=i[e+4>>2],i[o+8>>2]=i[e+8>>2],void(i[o+12>>2]=i[e+12>>2]);if(u=+p(+ +n[A+8>>3],+ +n[A>>3]),(0|r)>0){A=0;do{a/=2.6457513110645907,A=A+1|0}while((0|A)!=(0|r))}t?(a/=3,r=0==(0|RA(r)),a=+w(.381966011250105*(r?a:a/2.6457513110645907))):(a=+w(.381966011250105*a),0|RA(r)&&(u=+EA(u+.3334731722518321))),function(A,e,r,t){A|=0,e=+e,t|=0;var o=0,a=0,s=0,u=0;if((r=+r)<1e-16)return i[t>>2]=i[A>>2],i[t+4>>2]=i[A+4>>2],i[t+8>>2]=i[A+8>>2],void(i[t+12>>2]=i[A+12>>2]);a=e<0?e+6.283185307179586:e,a=e>=6.283185307179586?a+-6.283185307179586:a;do{if(!(a<1e-16)){if(o=+f(+(a+-3.141592653589793))<1e-16,e=+n[A>>3],o){e-=r,n[t>>3]=e,o=t;break}if(s=+l(+r),r=+h(+r),e=s*+h(+e)+ +l(+a)*(r*+l(+e)),e=+g(+((e=e>1?1:e)<-1?-1:e)),n[t>>3]=e,+f(+(e+-1.5707963267948966))<1e-16)return n[t>>3]=1.5707963267948966,void(n[t+8>>3]=0);if(+f(+(e+1.5707963267948966))<1e-16)return n[t>>3]=-1.5707963267948966,void(n[t+8>>3]=0);if(u=+l(+e),a=r*+h(+a)/u,r=+n[A>>3],e=(s-+h(+e)*+h(+r))/+l(+r)/u,s=a>1?1:a,e=e>1?1:e,(e=+n[A+8>>3]+ +p(+(s<-1?-1:s),+(e<-1?-1:e)))>3.141592653589793)do{e+=-6.283185307179586}while(e>3.141592653589793);if(e<-3.141592653589793)do{e+=6.283185307179586}while(e<-3.141592653589793);return void(n[t+8>>3]=e)}e=+n[A>>3]+r,n[t>>3]=e,o=t}while(0);if(+f(+(e+-1.5707963267948966))<1e-16)return n[o>>3]=1.5707963267948966,void(n[t+8>>3]=0);if(+f(+(e+1.5707963267948966))<1e-16)return n[o>>3]=-1.5707963267948966,void(n[t+8>>3]=0);if((e=+n[A+8>>3])>3.141592653589793)do{e+=-6.283185307179586}while(e>3.141592653589793);if(e<-3.141592653589793)do{e+=6.283185307179586}while(e<-3.141592653589793);n[t+8>>3]=e}(15568+(e<<4)|0,+EA(+n[16368+(24*e|0)>>3]-u),a,o)}function bA(A,e,r){e|=0,r|=0;var t,n;t=I,I=I+16|0,K((A|=0)+4|0,n=t),BA(n,0|i[A>>2],e,0,r),I=t}function vA(A,e,r,t,o){A|=0,e|=0,r|=0,t|=0,o|=0;var a,f,s,u,l,h,c,d,g,w,p,B,b,v,m,k,M,y,E,x,D,_,F=0,C=0,P=0,U=0,G=0,S=0;if(_=I,I=I+272|0,U=_+240|0,E=_,x=_+224|0,D=_+208|0,p=_+176|0,B=_+160|0,b=_+192|0,v=_+144|0,m=_+128|0,k=_+112|0,M=_+96|0,y=_+80|0,i[(F=_+256|0)>>2]=e,i[U>>2]=i[A>>2],i[U+4>>2]=i[A+4>>2],i[U+8>>2]=i[A+8>>2],i[U+12>>2]=i[A+12>>2],mA(U,F,E),i[o>>2]=0,(0|(U=t+r+(5==(0|t)&1)|0))<=(0|r))I=_;else{f=x+4|0,s=p+4|0,u=r+5|0,l=16848+((a=0|i[F>>2])<<2)|0,h=16928+(a<<2)|0,c=m+8|0,d=k+8|0,g=M+8|0,w=D+4|0,P=r;A:for(;;){C=E+(((0|P)%5|0)<<4)|0,i[D>>2]=i[C>>2],i[D+4>>2]=i[C+4>>2],i[D+8>>2]=i[C+8>>2],i[D+12>>2]=i[C+12>>2];do{}while(2==(0|kA(D,a,0,1)));if((0|P)>(0|r)&0!=(0|RA(e))){if(i[p>>2]=i[D>>2],i[p+4>>2]=i[D+4>>2],i[p+8>>2]=i[D+8>>2],i[p+12>>2]=i[D+12>>2],K(f,B),t=0|i[p>>2],F=0|i[17008+(80*t|0)+(i[x>>2]<<2)>>2],i[p>>2]=i[18608+(80*t|0)+(20*F|0)>>2],(0|(C=0|i[18608+(80*t|0)+(20*F|0)+16>>2]))>0){A=0;do{oA(s),A=A+1|0}while((0|A)<(0|C))}switch(C=18608+(80*t|0)+(20*F|0)+4|0,i[b>>2]=i[C>>2],i[b+4>>2]=i[C+4>>2],i[b+8>>2]=i[C+8>>2],$(b,3*(0|i[l>>2])|0),X(s,b,s),J(s),K(s,v),G=+(0|i[h>>2]),n[m>>3]=3*G,n[c>>3]=0,S=-1.5*G,n[k>>3]=S,n[d>>3]=2.598076211353316*G,n[M>>3]=S,n[g>>3]=-2.598076211353316*G,0|i[17008+(80*(0|i[p>>2])|0)+(i[D>>2]<<2)>>2]){case 1:A=k,t=m;break;case 3:A=M,t=k;break;case 2:A=m,t=M;break;default:A=12;break A}oe(B,v,t,A,y),BA(y,0|i[p>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])}if((0|P)<(0|u)&&(K(w,p),BA(p,0|i[D>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])),i[x>>2]=i[D>>2],i[x+4>>2]=i[D+4>>2],i[x+8>>2]=i[D+8>>2],i[x+12>>2]=i[D+12>>2],(0|(P=P+1|0))>=(0|U)){A=3;break}}3!=(0|A)?12==(0|A)&&Q(22474,22521,581,22531):I=_}}function mA(A,e,r){A|=0,e|=0,r|=0;var t,n=0,o=0,a=0,f=0,s=0;t=I,I=I+128|0,o=t,f=20208,s=(a=n=t+64|0)+60|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));f=20272,s=(a=o)+60|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));n=(s=0==(0|RA(0|i[e>>2])))?n:o,uA(o=A+4|0),lA(o),0|RA(0|i[e>>2])&&(iA(o),i[e>>2]=1+(0|i[e>>2])),i[r>>2]=i[A>>2],X(o,n,e=r+4|0),J(e),i[r+16>>2]=i[A>>2],X(o,n+12|0,e=r+20|0),J(e),i[r+32>>2]=i[A>>2],X(o,n+24|0,e=r+36|0),J(e),i[r+48>>2]=i[A>>2],X(o,n+36|0,e=r+52|0),J(e),i[r+64>>2]=i[A>>2],X(o,n+48|0,r=r+68|0),J(r),I=t}function kA(A,e,r,t){r|=0,t|=0;var n,o,a,f,s,u,l=0,h=0,c=0,d=0,g=0;if(u=I,I=I+32|0,s=u+12|0,o=u,g=(A|=0)+4|0,d=0|i[16928+((e|=0)<<2)>>2],d=(f=0!=(0|t))?3*d|0:d,l=0|i[g>>2],n=0|i[(a=A+8|0)>>2],f){if((0|(l=n+l+(t=0|i[(h=A+12|0)>>2])|0))==(0|d))return I=u,0|(g=1);c=h}else l=n+l+(t=0|i[(c=A+12|0)>>2])|0;if((0|l)<=(0|d))return I=u,0|(g=0);do{if((0|t)>0){if(t=0|i[A>>2],(0|n)>0){h=18608+(80*t|0)+60|0,t=A;break}t=18608+(80*t|0)+40|0,r?(Z(s,d,0,0),q(g,s,o),aA(o),X(o,s,g),h=t,t=A):(h=t,t=A)}else h=18608+(80*(0|i[A>>2])|0)+20|0,t=A}while(0);if(i[t>>2]=i[h>>2],(0|i[(l=h+16|0)>>2])>0){t=0;do{oA(g),t=t+1|0}while((0|t)<(0|i[l>>2]))}return A=h+4|0,i[s>>2]=i[A>>2],i[s+4>>2]=i[A+4>>2],i[s+8>>2]=i[A+8>>2],e=0|i[16848+(e<<2)>>2],$(s,f?3*e|0:e),X(g,s,g),J(g),t=f&&((0|i[a>>2])+(0|i[g>>2])+(0|i[c>>2])|0)==(0|d)?1:2,I=u,0|(g=t)}function MA(A,e){A|=0,e|=0;var r=0;do{r=0|kA(A,e,0,1)}while(2==(0|r));return 0|r}function QA(A,e,r,t,o){A|=0,e|=0,r|=0,t|=0,o|=0;var a,f,s,u,l,h,c,d,g,w,p,B,b,v,m,k,M,y,E=0,x=0,D=0,_=0,F=0;if(y=I,I=I+240|0,v=y+208|0,m=y,k=y+192|0,M=y+176|0,g=y+160|0,w=y+144|0,p=y+128|0,B=y+112|0,b=y+96|0,i[(E=y+224|0)>>2]=e,i[v>>2]=i[A>>2],i[v+4>>2]=i[A+4>>2],i[v+8>>2]=i[A+8>>2],i[v+12>>2]=i[A+12>>2],yA(v,E,m),i[o>>2]=0,(0|(d=t+r+(6==(0|t)&1)|0))<=(0|r))I=y;else{f=r+6|0,s=16928+((a=0|i[E>>2])<<2)|0,u=w+8|0,l=p+8|0,h=B+8|0,c=k+4|0,x=0,D=r,t=-1;A:for(;;){if(A=m+((E=(0|D)%6|0)<<4)|0,i[k>>2]=i[A>>2],i[k+4>>2]=i[A+4>>2],i[k+8>>2]=i[A+8>>2],i[k+12>>2]=i[A+12>>2],A=x,x=0|kA(k,a,0,1),(0|D)>(0|r)&0!=(0|RA(e))&&(1!=(0|A)&&(0|i[k>>2])!=(0|t))){switch(K(m+(((E+5|0)%6|0)<<4)+4|0,M),K(m+(E<<4)+4|0,g),_=+(0|i[s>>2]),n[w>>3]=3*_,n[u>>3]=0,F=-1.5*_,n[p>>3]=F,n[l>>3]=2.598076211353316*_,n[B>>3]=F,n[h>>3]=-2.598076211353316*_,E=0|i[v>>2],0|i[17008+(80*E|0)+(((0|t)==(0|E)?0|i[k>>2]:t)<<2)>>2]){case 1:A=p,t=w;break;case 3:A=B,t=p;break;case 2:A=w,t=B;break;default:A=8;break A}oe(M,g,t,A,b),0|ae(M,b)||0|ae(g,b)||(BA(b,0|i[v>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2]))}if((0|D)<(0|f)&&(K(c,M),BA(M,0|i[k>>2],a,1,o+8+(i[o>>2]<<4)|0),i[o>>2]=1+(0|i[o>>2])),(0|(D=D+1|0))>=(0|d)){A=3;break}t=0|i[k>>2]}3!=(0|A)?8==(0|A)&&Q(22557,22521,746,22602):I=y}}function yA(A,e,r){A|=0,e|=0,r|=0;var t,n=0,o=0,a=0,f=0,s=0;t=I,I=I+160|0,o=t,f=20336,s=(a=n=t+80|0)+72|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));f=20416,s=(a=o)+72|0;do{i[a>>2]=i[f>>2],a=a+4|0,f=f+4|0}while((0|a)<(0|s));n=(s=0==(0|RA(0|i[e>>2])))?n:o,uA(o=A+4|0),lA(o),0|RA(0|i[e>>2])&&(iA(o),i[e>>2]=1+(0|i[e>>2])),i[r>>2]=i[A>>2],X(o,n,e=r+4|0),J(e),i[r+16>>2]=i[A>>2],X(o,n+12|0,e=r+20|0),J(e),i[r+32>>2]=i[A>>2],X(o,n+24|0,e=r+36|0),J(e),i[r+48>>2]=i[A>>2],X(o,n+36|0,e=r+52|0),J(e),i[r+64>>2]=i[A>>2],X(o,n+48|0,e=r+68|0),J(e),i[r+80>>2]=i[A>>2],X(o,n+60|0,r=r+84|0),J(r),I=t}function EA(A){var e;return e=(A=+A)<0?A+6.283185307179586:A,+(A>=6.283185307179586?e+-6.283185307179586:e)}function xA(A,e){return e|=0,+f(+(+n[(A|=0)>>3]-+n[e>>3]))<17453292519943298e-27?0|(e=+f(+(+n[A+8>>3]-+n[e+8>>3]))<17453292519943298e-27):0|(e=0)}function DA(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))*6371.007180918475}function _A(A,e,r){A|=0,r|=0;var t,i,o,a,f=0,u=0,d=0,g=0,B=0,b=0;return b=+n[(e|=0)>>3],o=+n[A>>3],B=+h(.5*(b-o)),d=+n[e+8>>3],i=+n[A+8>>3],g=+h(.5*(d-i)),t=+l(+o),a=+l(+b),g=2*+p(+ +s(+(g=B*B+g*(a*t*g))),+ +s(+(1-g))),B=+n[r>>3],b=+h(.5*(B-b)),f=+n[r+8>>3],d=+h(.5*(f-d)),u=+l(+B),d=2*+p(+ +s(+(d=b*b+d*(a*u*d))),+ +s(+(1-d))),B=+h(.5*(o-B)),f=+h(.5*(i-f)),f=2*+p(+ +s(+(f=B*B+f*(t*u*f))),+ +s(+(1-f))),4*+w(+ +s(+ +c(.5*(u=.5*(g+d+f)))*+c(.5*(u-g))*+c(.5*(u-d))*+c(.5*(u-f))))}function IA(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),45),M(),127&e|0}function FA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0;if(!(!0&134217728==(-16777216&(e|=0)|0)))return 0|(e=0);if(o=0|Qe(0|(A|=0),0|e,45),M(),(o&=127)>>>0>121)return 0|(e=0);r=0|Qe(0|A,0|e,52),M(),r&=15;do{if(0|r){for(i=1,t=0;;){if(n=0|Qe(0|A,0|e,3*(15-i|0)|0),M(),0!=(0|(n&=7))&(1^t)){if(1==(0|n)&0!=(0|S(o))){a=0,t=13;break}t=1}if(7==(0|n)){a=0,t=13;break}if(!(i>>>0>>0)){t=9;break}i=i+1|0}if(9==(0|t)){if(15!=(0|r))break;return 0|(a=1)}if(13==(0|t))return 0|a}}while(0);for(;;){if(a=0|Qe(0|A,0|e,3*(14-r|0)|0),M(),!(7==(7&a|0)&!0)){a=0,t=13;break}if(!(r>>>0<14)){a=1,t=13;break}r=r+1|0}return 13==(0|t)?0|a:0}function CA(A,e,r){r|=0;var t=0,i=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|(t&=15))>=(0|r)){if((0|t)!=(0|r))if(r>>>0<=15){if(A|=i=0|ye(0|r,0,52),e=0|M()|-15728641&e,(0|t)>(0|r))do{i=0|ye(7,0,3*(14-r|0)|0),r=r+1|0,A|=i,e=0|M()|e}while((0|r)<(0|t))}else e=0,A=0}else e=0,A=0;return k(0|e),0|A}function PA(A,e,r,t){r|=0,t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(f&=15))<=(0|r)){if((0|f)==(0|r))return i[(r=t)>>2]=A,void(i[r+4>>2]=e);if(n=(0|(u=0|ee(7,r-f|0)))/7|0,s=0|Qe(0|A,0|e,45),M(),0|S(127&s)){A:do{if(f)for(a=1;;){if(o=0|Qe(0|A,0|e,3*(15-a|0)|0),M(),0|(o&=7))break A;if(!(a>>>0>>0)){o=0;break}a=a+1|0}else o=0}while(0);a=0==(0|o)}else a=0;if(l=0|ye(f+1|0,0,52),o=0|M()|-15728641&e,PA(e=(l|A)&~(e=0|ye(7,0,0|(s=3*(14-f|0)|0))),f=o&~(0|M()),r,t),o=t+(n<<3)|0,!a)return PA((l=0|ye(1,0,0|s))|e,0|M()|f,r,o),l=o+(n<<3)|0,PA((u=0|ye(2,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(3,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(4,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(5,0,0|s))|e,0|M()|f,r,l),void PA((u=0|ye(6,0,0|s))|e,0|M()|f,r,l+(n<<3)|0);a=o+(n<<3)|0,(0|u)>6&&(_e(0|o,0,(l=(a>>>0>(u=o+8|0)>>>0?a:u)+-1+(0-o)|0)+8&-8|0),o=u+(l>>>3<<3)|0),PA((l=0|ye(2,0,0|s))|e,0|M()|f,r,o),l=o+(n<<3)|0,PA((u=0|ye(3,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(4,0,0|s))|e,0|M()|f,r,l),l=l+(n<<3)|0,PA((u=0|ye(5,0,0|s))|e,0|M()|f,r,l),PA((u=0|ye(6,0,0|s))|e,0|M()|f,r,l+(n<<3)|0)}}function UA(A,e){var r=0,t=0,i=0;if(i=0|Qe(0|(A|=0),0|(e|=0),45),M(),!(0|S(127&i)))return 0|(i=0);i=0|Qe(0|A,0|e,52),M(),i&=15;A:do{if(i)for(t=1;;){if(r=0|Qe(0|A,0|e,3*(15-t|0)|0),M(),0|(r&=7))break A;if(!(t>>>0>>0)){r=0;break}t=t+1|0}else r=0}while(0);return 0|(i=0==(0|r)&1)}function GA(A,e){var r=0,t=0,i=0;if(i=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(i&=15))return 0|(i=0);for(t=1;;){if(r=0|Qe(0|A,0|e,3*(15-t|0)|0),M(),0|(r&=7)){t=5;break}if(!(t>>>0>>0)){r=0,t=5;break}t=t+1|0}return 5==(0|t)?0|r:0}function SA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0,f=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(f&=15))return f=A,k(0|(a=e)),0|f;for(a=1,r=0;;){t=0|ye(7,0,0|(n=3*(15-a|0)|0)),i=0|M(),o=0|Qe(0|A,0|e,0|n),M(),A=(n=0|ye(0|fA(7&o),0,0|n))|A&~t,e=(o=0|M())|e&~i;A:do{if(!r)if(0==(n&t|0)&0==(o&i|0))r=0;else if(t=0|Qe(0|A,0|e,52),M(),t&=15){r=1;e:for(;;){switch(o=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),7&o){case 1:break e;case 0:break;default:r=1;break A}if(!(r>>>0>>0)){r=1;break A}r=r+1|0}for(r=1;;){if(i=0|Qe(0|A,0|e,0|(o=3*(15-r|0)|0)),M(),n=0|ye(7,0,0|o),e&=~(0|M()),A=A&~n|(o=0|ye(0|fA(7&i),0,0|o)),e=0|e|M(),!(r>>>0>>0)){r=1;break}r=r+1|0}}else r=1}while(0);if(!(a>>>0>>0))break;a=a+1|0}return k(0|e),0|A}function TA(A,e){var r=0,t=0,i=0,n=0,o=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(t&=15))return t=A,k(0|(r=e)),0|t;for(r=1;o=0|Qe(0|A,0|e,0|(n=3*(15-r|0)|0)),M(),i=0|ye(7,0,0|n),e&=~(0|M()),A=(n=0|ye(0|fA(7&o),0,0|n))|A&~i,e=0|M()|e,r>>>0>>0;)r=r+1|0;return k(0|e),0|A}function VA(A,e){var r=0,t=0,i=0,n=0,o=0,a=0,f=0;if(f=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(f&=15))return f=A,k(0|(a=e)),0|f;for(a=1,r=0;;){t=0|ye(7,0,0|(n=3*(15-a|0)|0)),i=0|M(),o=0|Qe(0|A,0|e,0|n),M(),A=(n=0|ye(0|sA(7&o),0,0|n))|A&~t,e=(o=0|M())|e&~i;A:do{if(!r)if(0==(n&t|0)&0==(o&i|0))r=0;else if(t=0|Qe(0|A,0|e,52),M(),t&=15){r=1;e:for(;;){switch(o=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),7&o){case 1:break e;case 0:break;default:r=1;break A}if(!(r>>>0>>0)){r=1;break A}r=r+1|0}for(r=1;;){if(n=0|ye(7,0,0|(i=3*(15-r|0)|0)),o=e&~(0|M()),e=0|Qe(0|A,0|e,0|i),M(),A=A&~n|(e=0|ye(0|sA(7&e),0,0|i)),e=0|o|M(),!(r>>>0>>0)){r=1;break}r=r+1|0}}else r=1}while(0);if(!(a>>>0>>0))break;a=a+1|0}return k(0|e),0|A}function HA(A,e){var r=0,t=0,i=0,n=0,o=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),!(t&=15))return t=A,k(0|(r=e)),0|t;for(r=1;n=0|ye(7,0,0|(o=3*(15-r|0)|0)),i=e&~(0|M()),e=0|Qe(0|A,0|e,0|o),M(),A=(e=0|ye(0|sA(7&e),0,0|o))|A&~n,e=0|M()|i,r>>>0>>0;)r=r+1|0;return k(0|e),0|A}function RA(A){return 0|(0|(A|=0))%2}function LA(A,e){A|=0;var r,t;return t=I,I=I+16|0,r=t,(e|=0)>>>0<=15&&2146435072!=(2146435072&i[A+4>>2]|0)&&2146435072!=(2146435072&i[A+8+4>>2]|0)?(!function(A,e,r){var t,i;t=I,I=I+16|0,pA(A|=0,e|=0,r|=0,i=t),W(i,r+4|0),I=t}(A,e,r),e=0|function(A,e){A|=0;var r,t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0;if(r=I,I=I+64|0,s=r+40|0,n=r+24|0,o=r+12|0,a=r,ye(0|(e|=0),0,52),t=134225919|M(),!e)return(0|i[A+4>>2])>2||(0|i[A+8>>2])>2||(0|i[A+12>>2])>2?(s=0,k(0|(f=0)),I=r,0|s):(ye(0|V(A),0,45),f=0|M()|t,s=-1,k(0|f),I=r,0|s);if(i[s>>2]=i[A>>2],i[s+4>>2]=i[A+4>>2],i[s+8>>2]=i[A+8>>2],i[s+12>>2]=i[A+12>>2],f=s+4|0,(0|e)>0)for(A=-1;i[n>>2]=i[f>>2],i[n+4>>2]=i[f+4>>2],i[n+8>>2]=i[f+8>>2],1&e?(eA(f),i[o>>2]=i[f>>2],i[o+4>>2]=i[f+4>>2],i[o+8>>2]=i[f+8>>2],tA(o)):(rA(f),i[o>>2]=i[f>>2],i[o+4>>2]=i[f+4>>2],i[o+8>>2]=i[f+8>>2],iA(o)),q(n,o,a),J(a),u=0|ye(7,0,0|(l=3*(15-e|0)|0)),t&=~(0|M()),A=(l=0|ye(0|AA(a),0,0|l))|A&~u,t=0|M()|t,(0|e)>1;)e=e+-1|0;else A=-1;A:do{if((0|i[f>>2])<=2&&(0|i[s+8>>2])<=2&&(0|i[s+12>>2])<=2){if(e=0|ye(0|(n=0|V(s)),0,45),e|=A,A=0|M()|-1040385&t,a=0|H(s),!(0|S(n))){if((0|a)<=0)break;for(o=0;;){if(n=0|Qe(0|e,0|A,52),M(),n&=15)for(t=1;s=0|Qe(0|e,0|A,0|(l=3*(15-t|0)|0)),M(),u=0|ye(7,0,0|l),A&=~(0|M()),e=e&~u|(l=0|ye(0|fA(7&s),0,0|l)),A=0|A|M(),t>>>0>>0;)t=t+1|0;if((0|(o=o+1|0))==(0|a))break A}}o=0|Qe(0|e,0|A,52),M(),o&=15;e:do{if(o){t=1;r:for(;;){switch(l=0|Qe(0|e,0|A,3*(15-t|0)|0),M(),7&l){case 1:break r;case 0:break;default:break e}if(!(t>>>0>>0))break e;t=t+1|0}if(0|R(n,0|i[s>>2]))for(t=1;u=0|ye(7,0,0|(s=3*(15-t|0)|0)),l=A&~(0|M()),A=0|Qe(0|e,0|A,0|s),M(),e=e&~u|(A=0|ye(0|sA(7&A),0,0|s)),A=0|l|M(),t>>>0>>0;)t=t+1|0;else for(t=1;s=0|Qe(0|e,0|A,0|(l=3*(15-t|0)|0)),M(),u=0|ye(7,0,0|l),A&=~(0|M()),e=e&~u|(l=0|ye(0|fA(7&s),0,0|l)),A=0|A|M(),t>>>0>>0;)t=t+1|0}}while(0);if((0|a)>0){t=0;do{e=0|SA(e,A),A=0|M(),t=t+1|0}while((0|t)!=(0|a))}}else e=0,A=0}while(0);return l=e,k(0|(u=A)),I=r,0|l}(r,e),A=0|M()):(A=0,e=0),k(0|A),I=t,0|e}function zA(A,e,r){var t,n=0,o=0,a=0;if(t=(r|=0)+4|0,o=0|Qe(0|(A|=0),0|(e|=0),52),M(),o&=15,a=0|Qe(0|A,0|e,45),M(),n=0==(0|o),0|S(127&a)){if(n)return 0|(a=1);n=1}else{if(n)return 0|(a=0);n=0==(0|i[t>>2])&&0==(0|i[r+8>>2])?0!=(0|i[r+12>>2])&1:1}for(r=1;1&r?tA(t):iA(t),a=0|Qe(0|A,0|e,3*(15-r|0)|0),M(),nA(t,7&a),r>>>0>>0;)r=r+1|0;return 0|n}function YA(A,e,r){r|=0;var t,n,o=0,a=0,f=0,s=0,u=0,l=0;n=I,I=I+16|0,t=n,l=0|Qe(0|(A|=0),0|(e|=0),45),M(),l&=127;A:do{if(0!=(0|S(l))&&(f=0|Qe(0|A,0|e,52),M(),0!=(0|(f&=15)))){o=1;e:for(;;){switch(u=0|Qe(0|A,0|e,3*(15-o|0)|0),M(),7&u){case 5:break e;case 0:break;default:o=e;break A}if(!(o>>>0>>0)){o=e;break A}o=o+1|0}for(a=1,o=e;s=0|ye(7,0,0|(e=3*(15-a|0)|0)),u=o&~(0|M()),o=0|Qe(0|A,0|o,0|e),M(),A=A&~s|(o=0|ye(0|sA(7&o),0,0|e)),o=0|u|M(),a>>>0>>0;)a=a+1|0}else o=e}while(0);if(u=7728+(28*l|0)|0,i[r>>2]=i[u>>2],i[r+4>>2]=i[u+4>>2],i[r+8>>2]=i[u+8>>2],i[r+12>>2]=i[u+12>>2],0|zA(A,o,r)){if(s=r+4|0,i[t>>2]=i[s>>2],i[t+4>>2]=i[s+4>>2],i[t+8>>2]=i[s+8>>2],f=0|Qe(0|A,0|o,52),M(),u=15&f,1&f?(iA(s),f=u+1|0):f=u,0|S(l)){A:do{if(u)for(e=1;;){if(a=0|Qe(0|A,0|o,3*(15-e|0)|0),M(),0|(a&=7)){o=a;break A}if(!(e>>>0>>0)){o=0;break}e=e+1|0}else o=0}while(0);o=4==(0|o)&1}else o=0;if(0|kA(r,f,o,0)){if(0|S(l))do{}while(0!=(0|kA(r,f,0,0)));(0|f)!=(0|u)&&rA(s)}else(0|f)!=(0|u)&&(i[s>>2]=i[t>>2],i[s+4>>2]=i[t+4>>2],i[s+8>>2]=i[t+8>>2]);I=n}else I=n}function OA(A,e,r){r|=0;var t,i;t=I,I=I+16|0,YA(A|=0,e|=0,i=t),e=0|Qe(0|A,0|e,52),M(),bA(i,15&e,r),I=t}function jA(A,e,r){r|=0;var t,i,n=0,o=0;i=I,I=I+16|0,YA(A|=0,e|=0,t=i),n=0|Qe(0|A,0|e,45),M(),n=0==(0|S(127&n)),o=0|Qe(0|A,0|e,52),M(),o&=15;A:do{if(!n){if(0|o)for(n=1;;){if(!(0==((0|ye(7,0,3*(15-n|0)|0))&A|0)&0==((0|M())&e|0)))break A;if(!(n>>>0>>0))break;n=n+1|0}return vA(t,o,0,5,r),void(I=i)}}while(0);QA(t,o,0,6,r),I=i}function NA(A,e){e|=0;var r,t=0,n=0,o=0,a=0,f=0,s=0;if(ye(0|(A|=0),0,52),r=134225919|M(),(0|A)<1){n=0,t=0;do{0|S(n)&&(ye(0|n,0,45),f=0|r|M(),i[(A=e+(t<<3)|0)>>2]=-1,i[A+4>>2]=f,t=t+1|0),n=n+1|0}while(122!=(0|n))}else{f=0,t=0;do{if(0|S(f)){for(ye(0|f,0,45),n=1,o=-1,a=0|r|M();o&=~(s=0|ye(7,0,3*(15-n|0)|0)),a&=~(0|M()),(0|n)!=(0|A);)n=n+1|0;i[(s=e+(t<<3)|0)>>2]=o,i[s+4>>2]=a,t=t+1|0}f=f+1|0}while(122!=(0|f))}}function ZA(A,e,r,t){var n,o=0,a=0,f=0,s=0,u=0;if(n=I,I=I+64|0,f=n,(0|(A|=0))==(0|(r|=0))&(0|(e|=0))==(0|(t|=0))|!1|134217728!=(2013265920&e|0)|!1|134217728!=(2013265920&t|0))return I=n,0|(f=0);if(o=0|Qe(0|A,0|e,52),M(),o&=15,a=0|Qe(0|r,0|t,52),M(),(0|o)!=(15&a|0))return I=n,0|(f=0);if(a=o+-1|0,o>>>0>1&&(u=0|CA(A,e,a),s=0|M(),(0|u)==(0|(a=0|CA(r,t,a)))&(0|s)==(0|M()))){if(o=0|Qe(0|A,0|e,0|(a=3*(15^o)|0)),M(),o&=7,a=0|Qe(0|r,0|t,0|a),M(),0==(0|o)|0==(0|(a&=7)))return I=n,0|(u=1);if((0|i[21136+(o<<2)>>2])==(0|a))return I=n,0|(u=1);if((0|i[21168+(o<<2)>>2])==(0|a))return I=n,0|(u=1)}a=(o=f)+56|0;do{i[o>>2]=0,o=o+4|0}while((0|o)<(0|a));return F(A,e,1,f),o=(0|i[(u=f)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+8|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+16|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+24|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+32|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)||(0|i[(u=f+40|0)>>2])==(0|r)&&(0|i[u+4>>2])==(0|t)?1:1&((0|i[(o=f+48|0)>>2])==(0|r)?(0|i[o+4>>2])==(0|t):0),I=n,0|(u=o)}function WA(A,e,r){r|=0;var t,n,o,a,f=0;if(o=I,I=I+16|0,n=o,f=0|Qe(0|(A|=0),0|(e|=0),56),M(),-1==(0|(e=0|function(A,e,r){r|=0;var t=0,n=0;if(t=0|UA(A=A|0,e=e|0),(r+-1|0)>>>0>5)return 0|(r=-1);if(1==(0|r)&(n=0!=(0|t)))return 0|(r=-1);return t=0|function(A,e){var r=0,t=0,n=0,o=0,a=0,f=0,s=0,u=0;if(u=I,I=I+32|0,o=u,YA(A=A|0,e=e|0,n=u+16|0),a=0|IA(A,e),s=0|GA(A,e),function(A,e){A=7728+(28*(A|=0)|0)|0,i[(e|=0)>>2]=i[A>>2],i[e+4>>2]=i[A+4>>2],i[e+8>>2]=i[A+8>>2],i[e+12>>2]=i[A+12>>2]}(a,o),e=0|function(A,e){A|=0;var r=0,t=0;if((e|=0)>>>0>20)return-1;do{if((0|i[11152+(216*e|0)>>2])!=(0|A))if((0|i[11152+(216*e|0)+8>>2])!=(0|A))if((0|i[11152+(216*e|0)+16>>2])!=(0|A))if((0|i[11152+(216*e|0)+24>>2])!=(0|A))if((0|i[11152+(216*e|0)+32>>2])!=(0|A))if((0|i[11152+(216*e|0)+40>>2])!=(0|A))if((0|i[11152+(216*e|0)+48>>2])!=(0|A))if((0|i[11152+(216*e|0)+56>>2])!=(0|A))if((0|i[11152+(216*e|0)+64>>2])!=(0|A))if((0|i[11152+(216*e|0)+72>>2])!=(0|A))if((0|i[11152+(216*e|0)+80>>2])!=(0|A))if((0|i[11152+(216*e|0)+88>>2])!=(0|A))if((0|i[11152+(216*e|0)+96>>2])!=(0|A))if((0|i[11152+(216*e|0)+104>>2])!=(0|A))if((0|i[11152+(216*e|0)+112>>2])!=(0|A))if((0|i[11152+(216*e|0)+120>>2])!=(0|A))if((0|i[11152+(216*e|0)+128>>2])!=(0|A)){if((0|i[11152+(216*e|0)+136>>2])!=(0|A)){if((0|i[11152+(216*e|0)+144>>2])==(0|A)){A=0,r=2,t=0;break}if((0|i[11152+(216*e|0)+152>>2])==(0|A)){A=0,r=2,t=1;break}if((0|i[11152+(216*e|0)+160>>2])==(0|A)){A=0,r=2,t=2;break}if((0|i[11152+(216*e|0)+168>>2])==(0|A)){A=1,r=2,t=0;break}if((0|i[11152+(216*e|0)+176>>2])==(0|A)){A=1,r=2,t=1;break}if((0|i[11152+(216*e|0)+184>>2])==(0|A)){A=1,r=2,t=2;break}if((0|i[11152+(216*e|0)+192>>2])==(0|A)){A=2,r=2,t=0;break}if((0|i[11152+(216*e|0)+200>>2])==(0|A)){A=2,r=2,t=1;break}if((0|i[11152+(216*e|0)+208>>2])==(0|A)){A=2,r=2,t=2;break}return-1}A=2,r=1,t=2}else A=2,r=1,t=1;else A=2,r=1,t=0;else A=1,r=1,t=2;else A=1,r=1,t=1;else A=1,r=1,t=0;else A=0,r=1,t=2;else A=0,r=1,t=1;else A=0,r=1,t=0;else A=2,r=0,t=2;else A=2,r=0,t=1;else A=2,r=0,t=0;else A=1,r=0,t=2;else A=1,r=0,t=1;else A=1,r=0,t=0;else A=0,r=0,t=2;else A=0,r=0,t=1;else A=0,r=0,t=0}while(0);return 0|i[11152+(216*e|0)+(72*r|0)+(24*A|0)+(t<<3)+4>>2]}(a,0|i[n>>2]),!(0|S(a)))return I=u,0|(s=e);switch(0|a){case 4:A=0,r=14;break;case 14:A=1,r=14;break;case 24:A=2,r=14;break;case 38:A=3,r=14;break;case 49:A=4,r=14;break;case 58:A=5,r=14;break;case 63:A=6,r=14;break;case 72:A=7,r=14;break;case 83:A=8,r=14;break;case 97:A=9,r=14;break;case 107:A=10,r=14;break;case 117:A=11,r=14;break;default:f=0,t=0}14==(0|r)&&(f=0|i[22096+(24*A|0)+8>>2],t=0|i[22096+(24*A|0)+16>>2]);(0|(A=0|i[n>>2]))!=(0|i[o>>2])&&(a=0|T(a))|(0|(A=0|i[n>>2]))==(0|t)&&(e=(e+1|0)%6|0);if(3==(0|s)&(0|A)==(0|t))return I=u,0|(s=(e+5|0)%6|0);if(!(5==(0|s)&(0|A)==(0|f)))return I=u,0|(s=e);return I=u,0|(s=(e+1|0)%6|0)}(A,e),n?0|(r=(5-t+(0|i[22384+(r<<2)>>2])|0)%5|0):0|(r=(6-t+(0|i[22416+(r<<2)>>2])|0)%6|0)}(t=(a=!0&268435456==(2013265920&e|0))?A:0,A=a?-2130706433&e|134217728:0,7&f))))return i[r>>2]=0,void(I=o);YA(t,A,n),f=0|Qe(0|t,0|A,52),M(),f&=15,0|UA(t,A)?vA(n,f,e,2,r):QA(n,f,e,2,r),I=o}function JA(A){A|=0;var e,r,t=0;return(e=0|be(1,12))||Q(22691,22646,49,22704),0|(t=0|i[(r=A+4|0)>>2])?(i[(t=t+8|0)>>2]=e,i[r>>2]=e,0|e):(0|i[A>>2]&&Q(22721,22646,61,22744),i[(t=A)>>2]=e,i[r>>2]=e,0|e)}function KA(A,e){A|=0,e|=0;var r,t;return(t=0|pe(24))||Q(22758,22646,78,22772),i[t>>2]=i[e>>2],i[t+4>>2]=i[e+4>>2],i[t+8>>2]=i[e+8>>2],i[t+12>>2]=i[e+12>>2],i[t+16>>2]=0,0|(r=0|i[(e=A+4|0)>>2])?(i[r+16>>2]=t,i[e>>2]=t,0|t):(0|i[A>>2]&&Q(22787,22646,82,22772),i[A>>2]=t,i[e>>2]=t,0|t)}function XA(A){var e,r,t=0,o=0,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,y=0,E=0,x=0,D=0,_=0,I=0,F=0,C=0,P=0,U=0,G=0,S=0;if(0|i[(s=(A|=0)+8|0)>>2])return 0|(S=1);if(!(a=0|i[A>>2]))return 0|(S=0);t=a,o=0;do{o=o+1|0,t=0|i[t+8>>2]}while(0!=(0|t));if(o>>>0<2)return 0|(S=0);(r=0|pe(o<<2))||Q(22807,22646,317,22826),(e=0|pe(o<<5))||Q(22848,22646,321,22826),i[A>>2]=0,i[(D=A+4|0)>>2]=0,i[s>>2]=0,o=0,U=0,x=0,w=0;A:for(;;){if(g=0|i[a>>2]){u=0,l=g;do{if(c=+n[l+8>>3],t=l,l=0|i[l+16>>2],h=+n[(s=(d=0==(0|l))?g:l)+8>>3],+f(+(c-h))>3.141592653589793){S=14;break}u+=(h-c)*(+n[t>>3]+ +n[s>>3])}while(!d);if(14==(0|S)){S=0,u=0,t=g;do{E=+n[t+8>>3],C=0|i[(P=t+16|0)>>2],y=+n[(C=0==(0|C)?g:C)+8>>3],u+=(+n[t>>3]+ +n[C>>3])*((y<0?y+6.283185307179586:y)-(E<0?E+6.283185307179586:E)),t=0|i[(0==(0|t)?a:P)>>2]}while(0!=(0|t))}u>0?(i[r+(U<<2)>>2]=a,U=U+1|0,s=x,t=w):S=19}else S=19;if(19==(0|S)){S=0;do{if(!o){if(w){s=D,l=w+8|0,t=a,o=A;break}if(0|i[A>>2]){S=27;break A}s=D,l=A,t=a,o=A;break}if(0|i[(t=o+8|0)>>2]){S=21;break A}if(!(o=0|be(1,12))){S=23;break A}i[t>>2]=o,s=o+4|0,l=o,t=w}while(0);if(i[l>>2]=a,i[s>>2]=a,l=e+(x<<5)|0,d=0|i[a>>2]){for(n[(g=e+(x<<5)+8|0)>>3]=17976931348623157e292,n[(w=e+(x<<5)+24|0)>>3]=17976931348623157e292,n[l>>3]=-17976931348623157e292,n[(p=e+(x<<5)+16|0)>>3]=-17976931348623157e292,k=17976931348623157e292,M=-17976931348623157e292,s=0,B=d,c=17976931348623157e292,v=17976931348623157e292,m=-17976931348623157e292,h=-17976931348623157e292;u=+n[B>>3],E=+n[B+8>>3],B=0|i[B+16>>2],y=+n[((b=0==(0|B))?d:B)+8>>3],u>3]=u,c=u),E>3]=E,v=E),u>m?n[l>>3]=u:u=m,E>h&&(n[p>>3]=E,h=E),k=E>0&EM?E:M,s|=+f(+(E-y))>3.141592653589793,!b;)m=u;s&&(n[p>>3]=M,n[w>>3]=k)}else i[l>>2]=0,i[l+4>>2]=0,i[l+8>>2]=0,i[l+12>>2]=0,i[l+16>>2]=0,i[l+20>>2]=0,i[l+24>>2]=0,i[l+28>>2]=0;s=x+1|0}if(a=0|i[(P=a+8|0)>>2],i[P>>2]=0,!a){S=45;break}x=s,w=t}if(21==(0|S))Q(22624,22646,35,22658);else if(23==(0|S))Q(22678,22646,37,22658);else if(27==(0|S))Q(22721,22646,61,22744);else if(45==(0|S)){A:do{if((0|U)>0){for(P=0==(0|s),F=s<<2,C=0==(0|A),I=0,t=0;;){if(_=0|i[r+(I<<2)>>2],P)S=73;else{if(!(x=0|pe(F))){S=50;break}if(!(D=0|pe(F))){S=52;break}e:do{if(C)o=0;else{for(s=0,o=0,l=A;a=e+(s<<5)|0,0|qA(0|i[l>>2],a,0|i[_>>2])?(i[x+(o<<2)>>2]=l,i[D+(o<<2)>>2]=a,b=o+1|0):b=o,l=0|i[l+8>>2];)s=s+1|0,o=b;if((0|b)>0)if(a=0|i[x>>2],1==(0|b))o=a;else for(p=0,B=-1,o=a,w=a;;){for(d=0|i[w>>2],a=0,l=0;g=(0|(s=0|i[i[x+(l<<2)>>2]>>2]))==(0|d)?a:a+(1&(0|qA(s,0|i[D+(l<<2)>>2],0|i[d>>2])))|0,(0|(l=l+1|0))!=(0|b);)a=g;if(o=(s=(0|g)>(0|B))?w:o,(0|(a=p+1|0))==(0|b))break e;p=a,B=s?g:B,w=0|i[x+(a<<2)>>2]}else o=0}}while(0);if(Be(x),Be(D),o){if(a=0|i[(s=o+4|0)>>2])o=a+8|0;else if(0|i[o>>2]){S=70;break}i[o>>2]=_,i[s>>2]=_}else S=73}if(73==(0|S)){if(S=0,0|(t=0|i[_>>2]))do{D=t,t=0|i[t+16>>2],Be(D)}while(0!=(0|t));Be(_),t=2}if((0|(I=I+1|0))>=(0|U)){G=t;break A}}50==(0|S)?Q(22863,22646,249,22882):52==(0|S)?Q(22901,22646,252,22882):70==(0|S)&&Q(22721,22646,61,22744)}else G=0}while(0);return Be(r),Be(e),0|(S=G)}return 0}function qA(A,e,r){A|=0;var t,o=0,a=0,f=0,s=0,u=0,l=0,h=0;if(!(0|O(e|=0,r|=0)))return 0|(A=0);if(e=0|Y(e),t=+n[r>>3],o=e&(o=+n[r+8>>3])<0?o+6.283185307179586:o,!(A=0|i[A>>2]))return 0|(A=0);if(e){e=0,r=A;A:for(;;){for(;s=+n[r>>3],l=+n[r+8>>3],h=0|i[(r=r+16|0)>>2],f=+n[(h=0==(0|h)?A:h)>>3],a=+n[h+8>>3],s>f?(u=s,s=l):(u=f,f=s,s=a,a=l),tu;)if(!(r=0|i[r>>2])){r=22;break A}if(o=(s=s<0?s+6.283185307179586:s)==o|(l=a<0?a+6.283185307179586:a)==o?o+-2220446049250313e-31:o,((l+=(t-f)/(u-f)*(s-l))<0?l+6.283185307179586:l)>o&&(e^=1),!(r=0|i[r>>2])){r=22;break}}if(22==(0|r))return 0|e}else{e=0,r=A;A:for(;;){for(;s=+n[r>>3],l=+n[r+8>>3],h=0|i[(r=r+16|0)>>2],f=+n[(h=0==(0|h)?A:h)>>3],a=+n[h+8>>3],s>f?(u=s,s=l):(u=f,f=s,s=a,a=l),tu;)if(!(r=0|i[r>>2])){r=22;break A}if(a+(t-f)/(u-f)*(s-a)>(o=s==o|a==o?o+-2220446049250313e-31:o)&&(e^=1),!(r=0|i[r>>2])){r=22;break}}if(22==(0|r))return 0|e}return 0}function $A(A,e,r,n,o){r|=0,n|=0,o|=0;var a,f,s,u,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0;if(u=I,I=I+32|0,v=u+16|0,s=u,l=0|Qe(0|(A|=0),0|(e|=0),52),M(),l&=15,p=0|Qe(0|r,0|n,52),M(),(0|l)!=(15&p|0))return I=u,0|(v=1);if(g=0|Qe(0|A,0|e,45),M(),g&=127,w=0|Qe(0|r,0|n,45),M(),p=(0|g)!=(0|(w&=127))){if(7==(0|(c=0|z(g,w))))return I=u,0|(v=2);7==(0|(d=0|z(w,g)))?Q(22925,22949,151,22959):(B=c,h=d)}else B=0,h=0;a=0|S(g),f=0|S(w),i[v>>2]=0,i[v+4>>2]=0,i[v+8>>2]=0,i[v+12>>2]=0;do{if(B){if(c=(0|(w=0|i[4304+(28*g|0)+(B<<2)>>2]))>0,f)if(c){g=0,d=r,c=n;do{d=0|VA(d,c),c=0|M(),1==(0|(h=0|sA(h)))&&(h=0|sA(1)),g=g+1|0}while((0|g)!=(0|w));w=h,g=d,d=c}else w=h,g=r,d=n;else if(c){g=0,d=r,c=n;do{d=0|HA(d,c),c=0|M(),h=0|sA(h),g=g+1|0}while((0|g)!=(0|w));w=h,g=d,d=c}else w=h,g=r,d=n;if(zA(g,d,v),p||Q(22972,22949,181,22959),(c=0!=(0|a))&(h=0!=(0|f))&&Q(22999,22949,182,22959),c){if(h=0|GA(A,e),0|t[22032+(7*h|0)+B>>0]){l=3;break}g=d=0|i[21200+(28*h|0)+(B<<2)>>2],b=26}else if(h){if(h=0|GA(g,d),0|t[22032+(7*h|0)+w>>0]){l=4;break}g=0,d=0|i[21200+(28*w|0)+(h<<2)>>2],b=26}else h=0;if(26==(0|b))if((0|d)<=-1&&Q(23030,22949,212,22959),(0|g)<=-1&&Q(23053,22949,213,22959),(0|d)>0){c=v+4|0,h=0;do{aA(c),h=h+1|0}while((0|h)!=(0|d));h=g}else h=g;if(i[s>>2]=0,i[s+4>>2]=0,i[s+8>>2]=0,nA(s,B),0|l)for(;0|RA(l)?tA(s):iA(s),(0|l)>1;)l=l+-1|0;if((0|h)>0){l=0;do{aA(s),l=l+1|0}while((0|l)!=(0|h))}X(b=v+4|0,s,b),J(b),b=50}else if(zA(r,n,v),0!=(0|a)&0!=(0|f))if((0|w)!=(0|g)&&Q(23077,22949,243,22959),h=0|GA(A,e),l=0|GA(r,n),0|t[22032+(7*h|0)+l>>0])l=5;else if((0|(h=0|i[21200+(28*h|0)+(l<<2)>>2]))>0){c=v+4|0,l=0;do{aA(c),l=l+1|0}while((0|l)!=(0|h));b=50}else b=50;else b=50}while(0);return 50==(0|b)&&(l=v+4|0,i[o>>2]=i[l>>2],i[o+4>>2]=i[l+4>>2],i[o+8>>2]=i[l+8>>2],l=0),I=u,0|(v=l)}function Ae(A,e,r,t){r|=0,t|=0;var n,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0;if(o=I,I=I+48|0,s=o+36|0,u=o+24|0,l=o+12|0,h=o,f=0|Qe(0|(A|=0),0|(e|=0),52),M(),f&=15,d=0|Qe(0|A,0|e,45),M(),n=0|S(d&=127),ye(0|f,0,52),p=134225919|M(),i[(w=t)>>2]=-1,i[w+4>>2]=p,!f)return(0|i[r>>2])>1||(0|i[r+4>>2])>1||(0|i[r+8>>2])>1||127==(0|(a=0|L(d,0|AA(r))))?(I=o,0|(p=1)):(g=0|ye(0|a,0,45),w=0|M(),w=-1040385&i[(d=t)+4>>2]|w,i[(p=t)>>2]=i[d>>2]|g,i[p+4>>2]=w,I=o,0|(p=0));for(i[s>>2]=i[r>>2],i[s+4>>2]=i[r+4>>2],i[s+8>>2]=i[r+8>>2];i[u>>2]=i[s>>2],i[u+4>>2]=i[s+4>>2],i[u+8>>2]=i[s+8>>2],0|RA(f)?(eA(s),i[l>>2]=i[s>>2],i[l+4>>2]=i[s+4>>2],i[l+8>>2]=i[s+8>>2],tA(l)):(rA(s),i[l>>2]=i[s>>2],i[l+4>>2]=i[s+4>>2],i[l+8>>2]=i[s+8>>2],iA(l)),q(u,l,h),J(h),B=0|i[(w=t)>>2],w=0|i[w+4>>2],r=0|ye(7,0,0|(b=3*(15-f|0)|0)),w&=~(0|M()),b=0|ye(0|AA(h),0,0|b),w=0|M()|w,i[(p=t)>>2]=b|B&~r,i[p+4>>2]=w,(0|f)>1;)f=f+-1|0;A:do{if((0|i[s>>2])<=1&&(0|i[s+4>>2])<=1&&(0|i[s+8>>2])<=1){h=127==(0|(u=0|L(d,f=0|AA(s))))?0:0|S(u);e:do{if(f){if(n){if(s=21408+(28*(0|GA(A,e))|0)+(f<<2)|0,(0|(s=0|i[s>>2]))>0){r=0;do{f=0|fA(f),r=r+1|0}while((0|r)!=(0|s))}if(1==(0|f)){a=3;break A}127==(0|(r=0|L(d,f)))&&Q(23104,22949,376,23134),0|S(r)?Q(23147,22949,377,23134):(g=s,c=f,a=r)}else g=0,c=f,a=u;if((0|(l=0|i[4304+(28*d|0)+(c<<2)>>2]))<=-1&&Q(23178,22949,384,23134),!h){if((0|g)<=-1&&Q(23030,22949,417,23134),0|g){f=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];do{r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,f=f+1|0}while((0|f)<(0|g))}if((0|l)<=0){f=54;break}for(f=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];;)if(r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,(0|(f=f+1|0))==(0|l)){f=54;break e}}if(7==(0|(u=0|z(a,d)))&&Q(22925,22949,393,23134),r=0|i[(f=t)>>2],f=0|i[f+4>>2],(0|l)>0){s=0;do{r=0|TA(r,f),f=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=f,s=s+1|0}while((0|s)!=(0|l))}if(r=0|GA(r,f),b=0|T(a),(0|(r=0|i[(b?21824:21616)+(28*u|0)+(r<<2)>>2]))<=-1&&Q(23030,22949,412,23134),r){f=0,s=0|i[(u=t)>>2],u=0|i[u+4>>2];do{s=0|SA(s,u),u=0|M(),i[(b=t)>>2]=s,i[b+4>>2]=u,f=f+1|0}while((0|f)<(0|r));f=54}else f=54}else if(0!=(0|n)&0!=(0|h))if(f=21408+(28*(b=0|GA(A,e))|0)+((0|GA(0|i[(f=t)>>2],0|i[f+4>>2]))<<2)|0,(0|(f=0|i[f>>2]))<=-1&&Q(23201,22949,433,23134),f){a=0,r=0|i[(s=t)>>2],s=0|i[s+4>>2];do{r=0|TA(r,s),s=0|M(),i[(b=t)>>2]=r,i[b+4>>2]=s,a=a+1|0}while((0|a)<(0|f));a=u,f=54}else a=u,f=55;else a=u,f=54}while(0);if(54==(0|f)&&h&&(f=55),55==(0|f)&&1==(0|GA(0|i[(b=t)>>2],0|i[b+4>>2]))){a=4;break}p=0|i[(b=t)>>2],b=-1040385&i[b+4>>2],B=0|ye(0|a,0,45),b=0|b|M(),i[(a=t)>>2]=p|B,i[a+4>>2]=b,a=0}else a=2}while(0);return I=o,0|(b=a)}function ee(A,e){var r=0;if(!(e|=0))return 0|(r=1);r=A|=0,A=1;do{A=0|b(0==(1&e|0)?1:r,A),e>>=1,r=0|b(r,r)}while(0!=(0|e));return 0|A}function re(A,e,r){A|=0;var t,o,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0;if(!(0|O(e|=0,r|=0)))return 0|(d=0);if(e=0|Y(e),o=+n[r>>3],a=e&(a=+n[r+8>>3])<0?a+6.283185307179586:a,(0|(d=0|i[A>>2]))<=0)return 0|(d=0);if(t=0|i[A+4>>2],e){e=0,r=-1,A=0;A:for(;;){for(c=A;u=+n[t+(c<<4)>>3],h=+n[t+(c<<4)+8>>3],s=+n[t+((A=(r+2|0)%(0|d)|0)<<4)>>3],f=+n[t+(A<<4)+8>>3],u>s?(l=u,u=h):(l=s,s=u,u=f,f=h),ol;){if(!((0|(r=c+1|0))<(0|d))){r=22;break A}A=c,c=r,r=A}if(a=(u=u<0?u+6.283185307179586:u)==a|(h=f<0?f+6.283185307179586:f)==a?a+-2220446049250313e-31:a,((h+=(o-s)/(l-s)*(u-h))<0?h+6.283185307179586:h)>a&&(e^=1),(0|(A=c+1|0))>=(0|d)){r=22;break}r=c}if(22==(0|r))return 0|e}else{e=0,r=-1,A=0;A:for(;;){for(c=A;u=+n[t+(c<<4)>>3],h=+n[t+(c<<4)+8>>3],s=+n[t+((A=(r+2|0)%(0|d)|0)<<4)>>3],f=+n[t+(A<<4)+8>>3],u>s?(l=u,u=h):(l=s,s=u,u=f,f=h),ol;){if(!((0|(r=c+1|0))<(0|d))){r=22;break A}A=c,c=r,r=A}if(f+(o-s)/(l-s)*(u-f)>(a=u==a|f==a?a+-2220446049250313e-31:a)&&(e^=1),(0|(A=c+1|0))>=(0|d)){r=22;break}r=c}if(22==(0|r))return 0|e}return 0}function te(A,e){e|=0;var r,t,o,a,s,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0;if(!(t=0|i[(A|=0)>>2]))return i[e>>2]=0,i[e+4>>2]=0,i[e+8>>2]=0,i[e+12>>2]=0,i[e+16>>2]=0,i[e+20>>2]=0,i[e+24>>2]=0,void(i[e+28>>2]=0);if(n[(o=e+8|0)>>3]=17976931348623157e292,n[(a=e+24|0)>>3]=17976931348623157e292,n[e>>3]=-17976931348623157e292,n[(s=e+16|0)>>3]=-17976931348623157e292,!((0|t)<=0)){for(r=0|i[A+4>>2],p=17976931348623157e292,B=-17976931348623157e292,b=0,A=-1,c=17976931348623157e292,d=17976931348623157e292,w=-17976931348623157e292,l=-17976931348623157e292,v=0;u=+n[r+(v<<4)>>3],g=+n[r+(v<<4)+8>>3],h=+n[r+(((0|(A=A+2|0))==(0|t)?0:A)<<4)+8>>3],u>3]=u,c=u),g>3]=g,d=g),u>w?n[e>>3]=u:u=w,g>l&&(n[s>>3]=g,l=g),p=g>0&gB?g:B,b|=+f(+(g-h))>3.141592653589793,(0|(A=v+1|0))!=(0|t);)m=v,w=u,v=A,A=m;b&&(n[s>>3]=B,n[a>>3]=p)}}function ie(A,e){e|=0;var r,t=0,o=0,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,Q=0,y=0,E=0;if(B=0|i[(A|=0)>>2]){if(n[(b=e+8|0)>>3]=17976931348623157e292,n[(v=e+24|0)>>3]=17976931348623157e292,n[e>>3]=-17976931348623157e292,n[(m=e+16|0)>>3]=-17976931348623157e292,(0|B)>0){for(a=0|i[A+4>>2],w=17976931348623157e292,p=-17976931348623157e292,o=0,t=-1,h=17976931348623157e292,c=17976931348623157e292,g=-17976931348623157e292,u=-17976931348623157e292,k=0;s=+n[a+(k<<4)>>3],d=+n[a+(k<<4)+8>>3],l=+n[a+(((0|(y=t+2|0))==(0|B)?0:y)<<4)+8>>3],s>3]=s,h=s),d>3]=d,c=d),s>g?n[e>>3]=s:s=g,d>u&&(n[m>>3]=d,u=d),w=d>0&dp?d:p,o|=+f(+(d-l))>3.141592653589793,(0|(t=k+1|0))!=(0|B);)y=k,g=s,k=t,t=y;o&&(n[m>>3]=p,n[v>>3]=w)}}else i[e>>2]=0,i[e+4>>2]=0,i[e+8>>2]=0,i[e+12>>2]=0,i[e+16>>2]=0,i[e+20>>2]=0,i[e+24>>2]=0,i[e+28>>2]=0;if(!((0|(t=0|i[(y=A+8|0)>>2]))<=0)){r=A+12|0,Q=0;do{if(a=0|i[r>>2],o=Q,v=e+((Q=Q+1|0)<<5)|0,m=0|i[a+(o<<3)>>2]){if(n[(k=e+(Q<<5)+8|0)>>3]=17976931348623157e292,n[(A=e+(Q<<5)+24|0)>>3]=17976931348623157e292,n[v>>3]=-17976931348623157e292,n[(M=e+(Q<<5)+16|0)>>3]=-17976931348623157e292,(0|m)>0){for(B=0|i[a+(o<<3)+4>>2],w=17976931348623157e292,p=-17976931348623157e292,a=0,o=-1,b=0,h=17976931348623157e292,c=17976931348623157e292,d=-17976931348623157e292,u=-17976931348623157e292;s=+n[B+(b<<4)>>3],g=+n[B+(b<<4)+8>>3],l=+n[B+(((0|(o=o+2|0))==(0|m)?0:o)<<4)+8>>3],s>3]=s,h=s),g>3]=g,c=g),s>d?n[v>>3]=s:s=d,g>u&&(n[M>>3]=g,u=g),w=g>0&gp?g:p,a|=+f(+(g-l))>3.141592653589793,(0|(o=b+1|0))!=(0|m);)E=b,b=o,d=s,o=E;a&&(n[M>>3]=p,n[A>>3]=w)}}else i[v>>2]=0,i[v+4>>2]=0,i[v+8>>2]=0,i[v+12>>2]=0,i[v+16>>2]=0,i[v+20>>2]=0,i[v+24>>2]=0,i[v+28>>2]=0,t=0|i[y>>2]}while((0|Q)<(0|t))}}function ne(A,e,r){var t=0,n=0,o=0;if(!(0|re(A|=0,e|=0,r|=0)))return 0|(n=0);if((0|i[(n=A+8|0)>>2])<=0)return 0|(n=1);for(t=A+12|0,A=0;;){if(o=A,A=A+1|0,0|re((0|i[t>>2])+(o<<3)|0,e+(A<<5)|0,r)){A=0,t=6;break}if((0|A)>=(0|i[n>>2])){A=1,t=6;break}}return 6==(0|t)?0|A:0}function oe(A,e,r,t,i){e|=0,r|=0,t|=0,i|=0;var o,a,f,s,u,l,h,c=0;s=+n[(A|=0)>>3],f=+n[e>>3]-s,a=+n[A+8>>3],o=+n[e+8>>3]-a,l=+n[r>>3],c=((c=+n[t>>3]-l)*(a-(h=+n[r+8>>3]))-(s-l)*(u=+n[t+8>>3]-h))/(f*u-o*c),n[i>>3]=s+f*c,n[i+8>>3]=a+o*c}function ae(A,e){return e|=0,+n[(A|=0)>>3]!=+n[e>>3]?0|(e=0):0|(e=+n[A+8>>3]==+n[e+8>>3])}function fe(A,e){e|=0;var r,t,i;return+((i=+n[(A|=0)>>3]-+n[e>>3])*i+(t=+n[A+8>>3]-+n[e+8>>3])*t+(r=+n[A+16>>3]-+n[e+16>>3])*r)}function se(A,e,r){A|=0,r|=0;var t=0;(0|(e|=0))>0?(t=0|be(e,4),i[A>>2]=t,t||Q(23230,23253,40,23267)):i[A>>2]=0,i[A+4>>2]=e,i[A+8>>2]=0,i[A+12>>2]=r}function ue(A){var e,r,t,o=0,a=0,s=0,l=0;e=(A|=0)+4|0,r=A+12|0,t=A+8|0;A:for(;;){for(a=0|i[e>>2],o=0;;){if((0|o)>=(0|a))break A;if(s=0|i[A>>2],l=0|i[s+(o<<2)>>2])break;o=o+1|0}o=s+(~~(+f(+ +u(10,+ +(15-(0|i[r>>2])|0))*(+n[l>>3]+ +n[l+8>>3]))%+(0|a))>>>0<<2)|0,a=0|i[o>>2];e:do{if(0|a){if(s=l+32|0,(0|a)==(0|l))i[o>>2]=i[s>>2];else{if(!(o=0|i[(a=a+32|0)>>2]))break;for(;(0|o)!=(0|l);)if(!(o=0|i[(a=o+32|0)>>2]))break e;i[a>>2]=i[s>>2]}Be(l),i[t>>2]=(0|i[t>>2])-1}}while(0)}Be(0|i[A>>2])}function le(A){var e,r=0,t=0;for(e=0|i[(A|=0)+4>>2],t=0;;){if((0|t)>=(0|e)){r=0,t=4;break}if(r=0|i[(0|i[A>>2])+(t<<2)>>2]){t=4;break}t=t+1|0}return 4==(0|t)?0|r:0}function he(A,e){e|=0;var r=0,t=0,o=0,a=0;if(r=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,r=(0|i[A>>2])+(r<<2)|0,!(t=0|i[r>>2]))return 0|(a=1);a=e+32|0;do{if((0|t)!=(0|e)){if(!(r=0|i[t+32>>2]))return 0|(a=1);for(o=r;;){if((0|o)==(0|e)){o=8;break}if(!(r=0|i[o+32>>2])){r=1,o=10;break}t=o,o=r}if(8==(0|o)){i[t+32>>2]=i[a>>2];break}if(10==(0|o))return 0|r}else i[r>>2]=i[a>>2]}while(0);return Be(e),i[(a=A+8|0)>>2]=(0|i[a>>2])-1,0|(a=0)}function ce(A,e,r){A|=0,e|=0,r|=0;var t,o=0,a=0,s=0;(t=0|pe(40))||Q(23283,23253,98,23296),i[t>>2]=i[e>>2],i[t+4>>2]=i[e+4>>2],i[t+8>>2]=i[e+8>>2],i[t+12>>2]=i[e+12>>2],i[(a=t+16|0)>>2]=i[r>>2],i[a+4>>2]=i[r+4>>2],i[a+8>>2]=i[r+8>>2],i[a+12>>2]=i[r+12>>2],i[t+32>>2]=0,a=~~(+f(+ +u(10,+ +(15-(0|i[A+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,a=(0|i[A>>2])+(a<<2)|0,o=0|i[a>>2];do{if(o){for(;!(0|xA(o,e)&&0|xA(o+16|0,r));)if(a=0|i[o+32>>2],!(0|i[(o=0==(0|a)?o:a)+32>>2])){s=10;break}if(10==(0|s)){i[o+32>>2]=t;break}return Be(t),0|(s=o)}i[a>>2]=t}while(0);return i[(s=A+8|0)>>2]=1+(0|i[s>>2]),0|(s=t)}function de(A,e,r){e|=0,r|=0;var t=0,o=0;if(o=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,!(o=0|i[(0|i[A>>2])+(o<<2)>>2]))return 0|(r=0);if(!r){for(A=o;;){if(0|xA(A,e)){t=10;break}if(!(A=0|i[A+32>>2])){A=0,t=10;break}}if(10==(0|t))return 0|A}for(A=o;;){if(0|xA(A,e)&&0|xA(A+16|0,r)){t=10;break}if(!(A=0|i[A+32>>2])){A=0,t=10;break}}return 10==(0|t)?0|A:0}function ge(A,e){e|=0;var r=0;if(r=~~(+f(+ +u(10,+ +(15-(0|i[(A|=0)+12>>2])|0))*(+n[e>>3]+ +n[e+8>>3]))%+(0|i[A+4>>2]))>>>0,!(A=0|i[(0|i[A>>2])+(r<<2)>>2]))return 0|(r=0);for(;;){if(0|xA(A,e)){e=5;break}if(!(A=0|i[A+32>>2])){A=0,e=5;break}}return 5==(0|e)?0|A:0}function we(A){return 0|~~+function(A){return+ +Ie(+(A=+A))}(A=+A)}function pe(A){A|=0;var e,r=0,t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0;e=I,I=I+16|0,d=e;do{if(A>>>0<245){if(A=(l=A>>>0<11?16:A+11&-8)>>>3,3&(t=(c=0|i[5829])>>>A)|0)return n=0|i[(t=(A=23356+((r=(1&t^1)+A|0)<<1<<2)|0)+8|0)>>2],(0|(a=0|i[(o=n+8|0)>>2]))==(0|A)?i[5829]=c&~(1<>2]=A,i[t>>2]=a),k=r<<3,i[n+4>>2]=3|k,i[(k=n+k+4|0)>>2]=1|i[k>>2],I=e,0|(k=o);if(l>>>0>(h=0|i[5831])>>>0){if(0|t)return r=((r=t<>>=s=r>>>12&16)>>>5&8)|s|(a=(r>>>=t)>>>2&4)|(A=(r>>>=a)>>>1&2)|(n=(r>>>=A)>>>1&1))+(r>>>n)|0)<<1<<2)|0)+8|0)>>2],(0|(t=0|i[(s=a+8|0)>>2]))==(0|r)?(A=c&~(1<>2]=r,i[A>>2]=t,A=c),f=(k=n<<3)-l|0,i[a+4>>2]=3|l,i[(o=a+l|0)+4>>2]=1|f,i[a+k>>2]=f,0|h&&(n=0|i[5834],t=23356+((r=h>>>3)<<1<<2)|0,A&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=n,i[r+12>>2]=n,i[n+8>>2]=r,i[n+12>>2]=t),i[5831]=f,i[5834]=o,I=e,0|(k=s);if(a=0|i[5830]){for(t=(a&0-a)-1|0,t=u=0|i[23620+(((n=(t>>>=o=t>>>12&16)>>>5&8)|o|(f=(t>>>=n)>>>2&4)|(s=(t>>>=f)>>>1&2)|(u=(t>>>=s)>>>1&1))+(t>>>u)<<2)>>2],s=u,u=(-8&i[u+4>>2])-l|0;(A=0|i[t+16>>2])||(A=0|i[t+20>>2]);)t=A,s=(o=(f=(-8&i[A+4>>2])-l|0)>>>0>>0)?A:s,u=o?f:u;if((f=s+l|0)>>>0>s>>>0){o=0|i[s+24>>2],r=0|i[s+12>>2];do{if((0|r)==(0|s)){if(!(r=0|i[(A=s+20|0)>>2])&&!(r=0|i[(A=s+16|0)>>2])){t=0;break}for(;;)if(t=0|i[(n=r+20|0)>>2])r=t,A=n;else{if(!(t=0|i[(n=r+16|0)>>2]))break;r=t,A=n}i[A>>2]=0,t=r}else t=0|i[s+8>>2],i[t+12>>2]=r,i[r+8>>2]=t,t=r}while(0);do{if(0|o){if(r=0|i[s+28>>2],(0|s)==(0|i[(A=23620+(r<<2)|0)>>2])){if(i[A>>2]=t,!t){i[5830]=a&~(1<>2])==(0|s)?k:o+20|0)>>2]=t,!t)break;i[t+24>>2]=o,0|(r=0|i[s+16>>2])&&(i[t+16>>2]=r,i[r+24>>2]=t),0|(r=0|i[s+20>>2])&&(i[t+20>>2]=r,i[r+24>>2]=t)}}while(0);return u>>>0<16?(k=u+l|0,i[s+4>>2]=3|k,i[(k=s+k+4|0)>>2]=1|i[k>>2]):(i[s+4>>2]=3|l,i[f+4>>2]=1|u,i[f+u>>2]=u,0|h&&(n=0|i[5834],t=23356+((r=h>>>3)<<1<<2)|0,(r=1<>2]:(i[5829]=r|c,r=t,A=t+8|0),i[A>>2]=n,i[r+12>>2]=n,i[n+8>>2]=r,i[n+12>>2]=t),i[5831]=u,i[5834]=f),I=e,0|(k=s+8|0)}c=l}else c=l}else c=l}else if(A>>>0<=4294967231)if(l=-8&(A=A+11|0),n=0|i[5830]){o=0-l|0,u=(A>>>=8)?l>>>0>16777215?31:l>>>((u=14-((s=((p=A<<(c=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|c|(u=((p<<=s)+245760|0)>>>16&2))+(p<>>15)|0)+7|0)&1|u<<1:0,t=0|i[23620+(u<<2)>>2];A:do{if(t)for(A=0,s=l<<(31==(0|u)?0:25-(u>>>1)|0),a=0;;){if((f=(-8&i[t+4>>2])-l|0)>>>0>>0){if(!f){A=t,o=0,p=65;break A}A=t,o=f}if(a=0==(0|(p=0|i[t+20>>2]))|(0|p)==(0|(t=0|i[t+16+(s>>>31<<2)>>2]))?a:p,!t){t=a,p=61;break}s<<=1}else t=0,A=0,p=61}while(0);if(61==(0|p)){if(0==(0|t)&0==(0|A)){if(!(A=((A=2<>>=f=c>>>12&16)>>>5&8)|f|(s=(c>>>=a)>>>2&4)|(u=(c>>>=s)>>>1&2)|(t=(c>>>=u)>>>1&1))+(c>>>t)<<2)>>2]}t?p=65:(s=A,f=o)}if(65==(0|p))for(a=t;;){if(o=(t=(c=(-8&i[a+4>>2])-l|0)>>>0>>0)?c:o,A=t?a:A,(t=0|i[a+16>>2])||(t=0|i[a+20>>2]),!t){s=A,f=o;break}a=t}if(0!=(0|s)&&f>>>0<((0|i[5831])-l|0)>>>0&&(h=s+l|0)>>>0>s>>>0){a=0|i[s+24>>2],r=0|i[s+12>>2];do{if((0|r)==(0|s)){if(!(r=0|i[(A=s+20|0)>>2])&&!(r=0|i[(A=s+16|0)>>2])){r=0;break}for(;;)if(t=0|i[(o=r+20|0)>>2])r=t,A=o;else{if(!(t=0|i[(o=r+16|0)>>2]))break;r=t,A=o}i[A>>2]=0}else k=0|i[s+8>>2],i[k+12>>2]=r,i[r+8>>2]=k}while(0);do{if(a){if(A=0|i[s+28>>2],(0|s)==(0|i[(t=23620+(A<<2)|0)>>2])){if(i[t>>2]=r,!r){n&=~(1<>2])==(0|s)?k:a+20|0)>>2]=r,!r)break;i[r+24>>2]=a,0|(A=0|i[s+16>>2])&&(i[r+16>>2]=A,i[A+24>>2]=r),(A=0|i[s+20>>2])&&(i[r+20>>2]=A,i[A+24>>2]=r)}}while(0);A:do{if(f>>>0<16)k=f+l|0,i[s+4>>2]=3|k,i[(k=s+k+4|0)>>2]=1|i[k>>2];else{if(i[s+4>>2]=3|l,i[h+4>>2]=1|f,i[h+f>>2]=f,r=f>>>3,f>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=h,i[r+12>>2]=h,i[h+8>>2]=r,i[h+12>>2]=t;break}if(r=23620+((t=(r=f>>>8)?f>>>0>16777215?31:f>>>((t=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(t=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|t<<1:0)<<2)|0,i[h+28>>2]=t,i[(A=h+16|0)+4>>2]=0,i[A>>2]=0,!(n&(A=1<>2]=h,i[h+24>>2]=r,i[h+12>>2]=h,i[h+8>>2]=h;break}r=0|i[r>>2];e:do{if((-8&i[r+4>>2]|0)!=(0|f)){for(n=f<<(31==(0|t)?0:25-(t>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|f)){r=A;break e}n<<=1,r=A}i[t>>2]=h,i[h+24>>2]=r,i[h+12>>2]=h,i[h+8>>2]=h;break A}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=h,i[m>>2]=h,i[h+8>>2]=k,i[h+12>>2]=r,i[h+24>>2]=0}}while(0);return I=e,0|(k=s+8|0)}c=l}else c=l;else c=-1}while(0);if((t=0|i[5831])>>>0>=c>>>0)return r=t-c|0,A=0|i[5834],r>>>0>15?(k=A+c|0,i[5834]=k,i[5831]=r,i[k+4>>2]=1|r,i[A+t>>2]=r,i[A+4>>2]=3|c):(i[5831]=0,i[5834]=0,i[A+4>>2]=3|t,i[(k=A+t+4|0)>>2]=1|i[k>>2]),I=e,0|(k=A+8|0);if((f=0|i[5832])>>>0>c>>>0)return v=f-c|0,i[5832]=v,m=(k=0|i[5835])+c|0,i[5835]=m,i[m+4>>2]=1|v,i[k+4>>2]=3|c,I=e,0|(k=k+8|0);if(0|i[5947]?A=0|i[5949]:(i[5949]=4096,i[5948]=4096,i[5950]=-1,i[5951]=-1,i[5952]=0,i[5940]=0,i[5947]=-16&d^1431655768,A=4096),s=c+48|0,(l=(a=A+(u=c+47|0)|0)&(o=0-A|0))>>>0<=c>>>0)return I=e,0|(k=0);if(0|(A=0|i[5939])&&(d=(h=0|i[5937])+l|0)>>>0<=h>>>0|d>>>0>A>>>0)return I=e,0|(k=0);A:do{if(4&i[5940])r=0,p=143;else{t=0|i[5835];e:do{if(t){for(n=23764;!((d=0|i[n>>2])>>>0<=t>>>0&&(d+(0|i[n+4>>2])|0)>>>0>t>>>0);){if(!(A=0|i[n+8>>2])){p=128;break e}n=A}if((r=a-f&o)>>>0<2147483647)if((0|(A=0|Fe(0|r)))==((0|i[n>>2])+(0|i[n+4>>2])|0)){if(-1!=(0|A)){f=r,a=A,p=145;break A}}else n=A,p=136;else r=0}else p=128}while(0);do{if(128==(0|p))if(-1!=(0|(t=0|Fe(0)))&&(r=t,w=(r=(0==((w=(g=0|i[5948])+-1|0)&r|0)?0:(w+r&0-g)-r|0)+l|0)+(g=0|i[5937])|0,r>>>0>c>>>0&r>>>0<2147483647)){if(0|(d=0|i[5939])&&w>>>0<=g>>>0|w>>>0>d>>>0){r=0;break}if((0|(A=0|Fe(0|r)))==(0|t)){f=r,a=t,p=145;break A}n=A,p=136}else r=0}while(0);do{if(136==(0|p)){if(t=0-r|0,!(s>>>0>r>>>0&r>>>0<2147483647&-1!=(0|n))){if(-1==(0|n)){r=0;break}f=r,a=n,p=145;break A}if((A=u-r+(A=0|i[5949])&0-A)>>>0>=2147483647){f=r,a=n,p=145;break A}if(-1==(0|Fe(0|A))){Fe(0|t),r=0;break}f=A+r|0,a=n,p=145;break A}}while(0);i[5940]=4|i[5940],p=143}}while(0);if(143==(0|p)&&l>>>0<2147483647&&!(-1==(0|(v=0|Fe(0|l)))|1^(b=(B=(w=0|Fe(0))-v|0)>>>0>(c+40|0)>>>0)|v>>>0>>0&-1!=(0|v)&-1!=(0|w)^1)&&(f=b?B:r,a=v,p=145),145==(0|p)){r=(0|i[5937])+f|0,i[5937]=r,r>>>0>(0|i[5938])>>>0&&(i[5938]=r),u=0|i[5835];A:do{if(u){for(r=23764;;){if((0|a)==((A=0|i[r>>2])+(t=0|i[r+4>>2])|0)){p=154;break}if(!(n=0|i[r+8>>2]))break;r=n}if(154==(0|p)&&(m=r+4|0,0==(8&i[r+12>>2]|0))&&a>>>0>u>>>0&A>>>0<=u>>>0){i[m>>2]=t+f,m=u+(v=0==(7&(v=u+8|0)|0)?0:0-v&7)|0,v=(k=(0|i[5832])+f|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[u+k+4>>2]=40,i[5836]=i[5951];break}for(a>>>0<(0|i[5833])>>>0&&(i[5833]=a),t=a+f|0,r=23764;;){if((0|i[r>>2])==(0|t)){p=162;break}if(!(A=0|i[r+8>>2]))break;r=A}if(162==(0|p)&&0==(8&i[r+12>>2]|0)){i[r>>2]=a,i[(h=r+4|0)>>2]=(0|i[h>>2])+f,l=(h=a+(0==(7&(h=a+8|0)|0)?0:0-h&7)|0)+c|0,s=(r=t+(0==(7&(r=t+8|0)|0)?0:0-r&7)|0)-h-c|0,i[h+4>>2]=3|c;e:do{if((0|u)==(0|r))k=(0|i[5832])+s|0,i[5832]=k,i[5835]=l,i[l+4>>2]=1|k;else{if((0|i[5834])==(0|r)){k=(0|i[5831])+s|0,i[5831]=k,i[5834]=l,i[l+4>>2]=1|k,i[l+k>>2]=k;break}if(1==(3&(A=0|i[r+4>>2])|0)){f=-8&A,n=A>>>3;r:do{if(A>>>0<256){if(A=0|i[r+8>>2],(0|(t=0|i[r+12>>2]))==(0|A)){i[5829]=i[5829]&~(1<>2]=t,i[t+8>>2]=A;break}a=0|i[r+24>>2],A=0|i[r+12>>2];do{if((0|A)==(0|r)){if(A=0|i[(n=(t=r+16|0)+4|0)>>2])t=n;else if(!(A=0|i[t>>2])){A=0;break}for(;;)if(n=0|i[(o=A+20|0)>>2])A=n,t=o;else{if(!(n=0|i[(o=A+16|0)>>2]))break;A=n,t=o}i[t>>2]=0}else k=0|i[r+8>>2],i[k+12>>2]=A,i[A+8>>2]=k}while(0);if(!a)break;n=23620+((t=0|i[r+28>>2])<<2)|0;do{if((0|i[n>>2])==(0|r)){if(i[n>>2]=A,0|A)break;i[5830]=i[5830]&~(1<>2])==(0|r)?k:a+20|0)>>2]=A,!A)break r}while(0);if(i[A+24>>2]=a,0|(n=0|i[(t=r+16|0)>>2])&&(i[A+16>>2]=n,i[n+24>>2]=A),!(t=0|i[t+4>>2]))break;i[A+20>>2]=t,i[t+24>>2]=A}while(0);r=r+f|0,o=f+s|0}else o=s;if(i[(r=r+4|0)>>2]=-2&i[r>>2],i[l+4>>2]=1|o,i[l+o>>2]=o,r=o>>>3,o>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=l,i[r+12>>2]=l,i[l+8>>2]=r,i[l+12>>2]=t;break}r=o>>>8;do{if(r){if(o>>>0>16777215){n=31;break}n=o>>>((n=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(n=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|n<<1}else n=0}while(0);if(r=23620+(n<<2)|0,i[l+28>>2]=n,i[(A=l+16|0)+4>>2]=0,i[A>>2]=0,!((A=0|i[5830])&(t=1<>2]=l,i[l+24>>2]=r,i[l+12>>2]=l,i[l+8>>2]=l;break}r=0|i[r>>2];r:do{if((-8&i[r+4>>2]|0)!=(0|o)){for(n=o<<(31==(0|n)?0:25-(n>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|o)){r=A;break r}n<<=1,r=A}i[t>>2]=l,i[l+24>>2]=r,i[l+12>>2]=l,i[l+8>>2]=l;break e}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=l,i[m>>2]=l,i[l+8>>2]=k,i[l+12>>2]=r,i[l+24>>2]=0}}while(0);return I=e,0|(k=h+8|0)}for(r=23764;!((A=0|i[r>>2])>>>0<=u>>>0&&(k=A+(0|i[r+4>>2])|0)>>>0>u>>>0);)r=0|i[r+8>>2];r=(A=(A=(o=k+-47|0)+(0==(7&(A=o+8|0)|0)?0:0-A&7)|0)>>>0<(o=u+16|0)>>>0?u:A)+8|0,m=a+(v=0==(7&(v=a+8|0)|0)?0:0-v&7)|0,v=(t=f+-40|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[a+t+4>>2]=40,i[5836]=i[5951],i[(t=A+4|0)>>2]=27,i[r>>2]=i[5941],i[r+4>>2]=i[5942],i[r+8>>2]=i[5943],i[r+12>>2]=i[5944],i[5941]=a,i[5942]=f,i[5944]=0,i[5943]=r,r=A+24|0;do{m=r,i[(r=r+4|0)>>2]=7}while((m+8|0)>>>0>>0);if((0|A)!=(0|u)){if(a=A-u|0,i[t>>2]=-2&i[t>>2],i[u+4>>2]=1|a,i[A>>2]=a,r=a>>>3,a>>>0<256){t=23356+(r<<1<<2)|0,(A=0|i[5829])&(r=1<>2]:(i[5829]=A|r,r=t,A=t+8|0),i[A>>2]=u,i[r+12>>2]=u,i[u+8>>2]=r,i[u+12>>2]=t;break}if(t=23620+((n=(r=a>>>8)?a>>>0>16777215?31:a>>>((n=14-((v=((k=r<<(m=(r+1048320|0)>>>16&8))+520192|0)>>>16&4)|m|(n=((k<<=v)+245760|0)>>>16&2))+(k<>>15)|0)+7|0)&1|n<<1:0)<<2)|0,i[u+28>>2]=n,i[u+20>>2]=0,i[o>>2]=0,!((r=0|i[5830])&(A=1<>2]=u,i[u+24>>2]=t,i[u+12>>2]=u,i[u+8>>2]=u;break}r=0|i[t>>2];e:do{if((-8&i[r+4>>2]|0)!=(0|a)){for(n=a<<(31==(0|n)?0:25-(n>>>1)|0);A=0|i[(t=r+16+(n>>>31<<2)|0)>>2];){if((-8&i[A+4>>2]|0)==(0|a)){r=A;break e}n<<=1,r=A}i[t>>2]=u,i[u+24>>2]=r,i[u+12>>2]=u,i[u+8>>2]=u;break A}}while(0);k=0|i[(m=r+8|0)>>2],i[k+12>>2]=u,i[m>>2]=u,i[u+8>>2]=k,i[u+12>>2]=r,i[u+24>>2]=0}}else 0==(0|(k=0|i[5833]))|a>>>0>>0&&(i[5833]=a),i[5941]=a,i[5942]=f,i[5944]=0,i[5838]=i[5947],i[5837]=-1,i[5842]=23356,i[5841]=23356,i[5844]=23364,i[5843]=23364,i[5846]=23372,i[5845]=23372,i[5848]=23380,i[5847]=23380,i[5850]=23388,i[5849]=23388,i[5852]=23396,i[5851]=23396,i[5854]=23404,i[5853]=23404,i[5856]=23412,i[5855]=23412,i[5858]=23420,i[5857]=23420,i[5860]=23428,i[5859]=23428,i[5862]=23436,i[5861]=23436,i[5864]=23444,i[5863]=23444,i[5866]=23452,i[5865]=23452,i[5868]=23460,i[5867]=23460,i[5870]=23468,i[5869]=23468,i[5872]=23476,i[5871]=23476,i[5874]=23484,i[5873]=23484,i[5876]=23492,i[5875]=23492,i[5878]=23500,i[5877]=23500,i[5880]=23508,i[5879]=23508,i[5882]=23516,i[5881]=23516,i[5884]=23524,i[5883]=23524,i[5886]=23532,i[5885]=23532,i[5888]=23540,i[5887]=23540,i[5890]=23548,i[5889]=23548,i[5892]=23556,i[5891]=23556,i[5894]=23564,i[5893]=23564,i[5896]=23572,i[5895]=23572,i[5898]=23580,i[5897]=23580,i[5900]=23588,i[5899]=23588,i[5902]=23596,i[5901]=23596,i[5904]=23604,i[5903]=23604,m=a+(v=0==(7&(v=a+8|0)|0)?0:0-v&7)|0,v=(k=f+-40|0)-v|0,i[5835]=m,i[5832]=v,i[m+4>>2]=1|v,i[a+k+4>>2]=40,i[5836]=i[5951]}while(0);if((r=0|i[5832])>>>0>c>>>0)return v=r-c|0,i[5832]=v,m=(k=0|i[5835])+c|0,i[5835]=m,i[m+4>>2]=1|v,i[k+4>>2]=3|c,I=e,0|(k=k+8|0)}return i[(k=23312)>>2]=12,I=e,0|(k=0)}function Be(A){var e=0,r=0,t=0,n=0,o=0,a=0,f=0,s=0;if(A|=0){r=A+-8|0,n=0|i[5833],s=r+(e=-8&(A=0|i[A+-4>>2]))|0;do{if(1&A)f=r,a=r;else{if(t=0|i[r>>2],!(3&A))return;if(o=t+e|0,(a=r+(0-t)|0)>>>0>>0)return;if((0|i[5834])==(0|a)){if(3!=(3&(e=0|i[(A=s+4|0)>>2])|0)){f=a,e=o;break}return i[5831]=o,i[A>>2]=-2&e,i[a+4>>2]=1|o,void(i[a+o>>2]=o)}if(r=t>>>3,t>>>0<256){if(A=0|i[a+8>>2],(0|(e=0|i[a+12>>2]))==(0|A)){i[5829]=i[5829]&~(1<>2]=e,i[e+8>>2]=A,f=a,e=o;break}n=0|i[a+24>>2],A=0|i[a+12>>2];do{if((0|A)==(0|a)){if(A=0|i[(r=(e=a+16|0)+4|0)>>2])e=r;else if(!(A=0|i[e>>2])){A=0;break}for(;;)if(r=0|i[(t=A+20|0)>>2])A=r,e=t;else{if(!(r=0|i[(t=A+16|0)>>2]))break;A=r,e=t}i[e>>2]=0}else f=0|i[a+8>>2],i[f+12>>2]=A,i[A+8>>2]=f}while(0);if(n){if(e=0|i[a+28>>2],(0|i[(r=23620+(e<<2)|0)>>2])==(0|a)){if(i[r>>2]=A,!A){i[5830]=i[5830]&~(1<>2])==(0|a)?f:n+20|0)>>2]=A,!A){f=a,e=o;break}i[A+24>>2]=n,0|(r=0|i[(e=a+16|0)>>2])&&(i[A+16>>2]=r,i[r+24>>2]=A),(e=0|i[e+4>>2])?(i[A+20>>2]=e,i[e+24>>2]=A,f=a,e=o):(f=a,e=o)}else f=a,e=o}}while(0);if(!(a>>>0>=s>>>0)&&1&(t=0|i[(A=s+4|0)>>2])){if(2&t)i[A>>2]=-2&t,i[f+4>>2]=1|e,i[a+e>>2]=e,n=e;else{if((0|i[5835])==(0|s)){if(s=(0|i[5832])+e|0,i[5832]=s,i[5835]=f,i[f+4>>2]=1|s,(0|f)!=(0|i[5834]))return;return i[5834]=0,void(i[5831]=0)}if((0|i[5834])==(0|s))return s=(0|i[5831])+e|0,i[5831]=s,i[5834]=a,i[f+4>>2]=1|s,void(i[a+s>>2]=s);n=(-8&t)+e|0,r=t>>>3;do{if(t>>>0<256){if(e=0|i[s+8>>2],(0|(A=0|i[s+12>>2]))==(0|e)){i[5829]=i[5829]&~(1<>2]=A,i[A+8>>2]=e;break}o=0|i[s+24>>2],A=0|i[s+12>>2];do{if((0|A)==(0|s)){if(A=0|i[(r=(e=s+16|0)+4|0)>>2])e=r;else if(!(A=0|i[e>>2])){r=0;break}for(;;)if(r=0|i[(t=A+20|0)>>2])A=r,e=t;else{if(!(r=0|i[(t=A+16|0)>>2]))break;A=r,e=t}i[e>>2]=0,r=A}else r=0|i[s+8>>2],i[r+12>>2]=A,i[A+8>>2]=r,r=A}while(0);if(0|o){if(A=0|i[s+28>>2],(0|i[(e=23620+(A<<2)|0)>>2])==(0|s)){if(i[e>>2]=r,!r){i[5830]=i[5830]&~(1<>2])==(0|s)?t:o+20|0)>>2]=r,!r)break;i[r+24>>2]=o,0|(e=0|i[(A=s+16|0)>>2])&&(i[r+16>>2]=e,i[e+24>>2]=r),0|(A=0|i[A+4>>2])&&(i[r+20>>2]=A,i[A+24>>2]=r)}}while(0);if(i[f+4>>2]=1|n,i[a+n>>2]=n,(0|f)==(0|i[5834]))return void(i[5831]=n)}if(A=n>>>3,n>>>0<256)return r=23356+(A<<1<<2)|0,(e=0|i[5829])&(A=1<>2]:(i[5829]=e|A,A=r,e=r+8|0),i[e>>2]=f,i[A+12>>2]=f,i[f+8>>2]=A,void(i[f+12>>2]=r);A=23620+((t=(A=n>>>8)?n>>>0>16777215?31:n>>>((t=14-((o=((s=A<<(a=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|a|(t=((s<<=o)+245760|0)>>>16&2))+(s<>>15)|0)+7|0)&1|t<<1:0)<<2)|0,i[f+28>>2]=t,i[f+20>>2]=0,i[f+16>>2]=0,e=0|i[5830],r=1<>2];e:do{if((-8&i[A+4>>2]|0)!=(0|n)){for(t=n<<(31==(0|t)?0:25-(t>>>1)|0);e=0|i[(r=A+16+(t>>>31<<2)|0)>>2];){if((-8&i[e+4>>2]|0)==(0|n)){A=e;break e}t<<=1,A=e}i[r>>2]=f,i[f+24>>2]=A,i[f+12>>2]=f,i[f+8>>2]=f;break A}}while(0);s=0|i[(a=A+8|0)>>2],i[s+12>>2]=f,i[a>>2]=f,i[f+8>>2]=s,i[f+12>>2]=A,i[f+24>>2]=0}else i[5830]=e|r,i[A>>2]=f,i[f+24>>2]=A,i[f+12>>2]=f,i[f+8>>2]=f}while(0);if(s=(0|i[5837])-1|0,i[5837]=s,!(0|s)){for(A=23772;A=0|i[A>>2];)A=A+8|0;i[5837]=-1}}}}function be(A,e){e|=0;var r=0;return(A|=0)?(r=0|b(e,A),(e|A)>>>0>65535&&(r=(0|(r>>>0)/(A>>>0))==(0|e)?r:-1)):r=0,(A=0|pe(r))&&3&i[A+-4>>2]?(_e(0|A,0,0|r),0|A):0|A}function ve(A,e,r,t){return 0|(k(0|(t=(e|=0)-(t|=0)-((r|=0)>>>0>(A|=0)>>>0|0)>>>0)),A-r>>>0|0)}function me(A){return 0|((A|=0)?31-(0|m(A^A-1))|0:32)}function ke(A,e,r,t,n){n|=0;var o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0;if(l=A|=0,a=r|=0,f=c=t|=0,!(u=s=e|=0))return o=0!=(0|n),f?o?(i[n>>2]=0|A,i[n+4>>2]=0&e,n=0,0|(k(0|(c=0)),n)):(n=0,0|(k(0|(c=0)),n)):(o&&(i[n>>2]=(l>>>0)%(a>>>0),i[n+4>>2]=0),n=(l>>>0)/(a>>>0)>>>0,0|(k(0|(c=0)),n));o=0==(0|f);do{if(a){if(!o){if((o=(0|m(0|f))-(0|m(0|u))|0)>>>0<=31){a=h=o+1|0,A=l>>>(h>>>0)&(e=o-31>>31)|u<<(f=31-o|0),e&=u>>>(h>>>0),o=0,f=l<>2]=0|A,i[n+4>>2]=s|0&e,n=0,0|(k(0|(c=0)),n)):(n=0,0|(k(0|(c=0)),n))}if((o=a-1|0)&a|0){a=f=33+(0|m(0|a))-(0|m(0|u))|0,A=(h=32-f|0)-1>>31&u>>>((d=f-32|0)>>>0)|(u<>>(f>>>0))&(e=d>>31),e&=u>>>(f>>>0),o=l<<(g=64-f|0)&(s=h>>31),f=(u<>>(d>>>0))&s|l<>31;break}return 0|n&&(i[n>>2]=o&l,i[n+4>>2]=0),1==(0|a)?(g=0|A,0|(k(0|(d=s|0&e)),g)):(d=u>>>((g=0|me(0|a))>>>0)|0,g=u<<32-g|l>>>(g>>>0)|0,0|(k(0|d),g))}if(o)return 0|n&&(i[n>>2]=(u>>>0)%(a>>>0),i[n+4>>2]=0),g=(u>>>0)/(a>>>0)>>>0,0|(k(0|(d=0)),g);if(!l)return 0|n&&(i[n>>2]=0,i[n+4>>2]=(u>>>0)%(f>>>0)),g=(u>>>0)/(f>>>0)>>>0,0|(k(0|(d=0)),g);if(!((o=f-1|0)&f))return 0|n&&(i[n>>2]=0|A,i[n+4>>2]=o&u|0&e),d=0,g=u>>>((0|me(0|f))>>>0),0|(k(0|d),g);if((o=(0|m(0|f))-(0|m(0|u))|0)>>>0<=30){a=e=o+1|0,A=u<<(f=31-o|0)|l>>>(e>>>0),e=u>>>(e>>>0),o=0,f=l<>2]=0|A,i[n+4>>2]=s|0&e,g=0,0|(k(0|(d=0)),g)):(g=0,0|(k(0|(d=0)),g))}while(0);if(a){u=0|function(A,e,r,t){return 0|(k((e|=0)+(t|=0)+((r=(A|=0)+(r|=0)>>>0)>>>0>>0|0)>>>0|0),0|r)}(0|(h=0|r),0|(l=c|0&t),-1,-1),r=0|M(),s=f,f=0;do{t=s,s=o>>>31|s<<1,o=f|o<<1,ve(0|u,0|r,0|(t=A<<1|t>>>31|0),0|(c=A>>>31|e<<1|0)),f=1&(d=(g=0|M())>>31|((0|g)<0?-1:0)<<1),A=0|ve(0|t,0|c,d&h|0,(((0|g)<0?-1:0)>>31|((0|g)<0?-1:0)<<1)&l|0),e=0|M(),a=a-1|0}while(0!=(0|a));u=s,s=0}else u=f,s=0,f=0;return a=0,0|n&&(i[n>>2]=A,i[n+4>>2]=e),g=-2&(o<<1|0)|f,0|(k(0|(d=(0|o)>>>31|(u|a)<<1|0&(a<<1|o>>>31)|s)),g)}function Me(A,e,r,t){var n,o;return o=I,I=I+16|0,ke(A|=0,e|=0,r|=0,t|=0,n=0|o),I=o,0|(k(0|i[n+4>>2]),0|i[n>>2])}function Qe(A,e,r){return A|=0,e|=0,(0|(r|=0))<32?(k(e>>>r|0),A>>>r|(e&(1<>>r-32|0)}function ye(A,e,r){return A|=0,e|=0,(0|(r|=0))<32?(k(e<>>32-r|0),A<=0?+a(A+.5):+B(A-.5)}function De(A,e,r){A|=0,e|=0;var n,o,a=0;if((0|(r|=0))>=8192)return x(0|A,0|e,0|r),0|A;if(o=0|A,n=A+r|0,(3&A)==(3&e)){for(;3&A;){if(!r)return 0|o;t[A>>0]=0|t[e>>0],A=A+1|0,e=e+1|0,r=r-1|0}for(a=(r=-4&n|0)-64|0;(0|A)<=(0|a);)i[A>>2]=i[e>>2],i[A+4>>2]=i[e+4>>2],i[A+8>>2]=i[e+8>>2],i[A+12>>2]=i[e+12>>2],i[A+16>>2]=i[e+16>>2],i[A+20>>2]=i[e+20>>2],i[A+24>>2]=i[e+24>>2],i[A+28>>2]=i[e+28>>2],i[A+32>>2]=i[e+32>>2],i[A+36>>2]=i[e+36>>2],i[A+40>>2]=i[e+40>>2],i[A+44>>2]=i[e+44>>2],i[A+48>>2]=i[e+48>>2],i[A+52>>2]=i[e+52>>2],i[A+56>>2]=i[e+56>>2],i[A+60>>2]=i[e+60>>2],A=A+64|0,e=e+64|0;for(;(0|A)<(0|r);)i[A>>2]=i[e>>2],A=A+4|0,e=e+4|0}else for(r=n-4|0;(0|A)<(0|r);)t[A>>0]=0|t[e>>0],t[A+1>>0]=0|t[e+1>>0],t[A+2>>0]=0|t[e+2>>0],t[A+3>>0]=0|t[e+3>>0],A=A+4|0,e=e+4|0;for(;(0|A)<(0|n);)t[A>>0]=0|t[e>>0],A=A+1|0,e=e+1|0;return 0|o}function _e(A,e,r){e|=0;var n,o=0,a=0,f=0;if(n=(A|=0)+(r|=0)|0,e&=255,(0|r)>=67){for(;3&A;)t[A>>0]=e,A=A+1|0;for(f=e|e<<8|e<<16|e<<24,a=(o=-4&n|0)-64|0;(0|A)<=(0|a);)i[A>>2]=f,i[A+4>>2]=f,i[A+8>>2]=f,i[A+12>>2]=f,i[A+16>>2]=f,i[A+20>>2]=f,i[A+24>>2]=f,i[A+28>>2]=f,i[A+32>>2]=f,i[A+36>>2]=f,i[A+40>>2]=f,i[A+44>>2]=f,i[A+48>>2]=f,i[A+52>>2]=f,i[A+56>>2]=f,i[A+60>>2]=f,A=A+64|0;for(;(0|A)<(0|o);)i[A>>2]=f,A=A+4|0}for(;(0|A)<(0|n);)t[A>>0]=e,A=A+1|0;return n-r|0}function Ie(A){return(A=+A)>=0?+a(A+.5):+B(A-.5)}function Fe(A){A|=0;var e,r,t;return t=0|E(),(0|A)>0&(0|(e=(r=0|i[o>>2])+A|0))<(0|r)|(0|e)<0?(_(0|e),y(12),-1):(0|e)>(0|t)&&!(0|D(0|e))?(y(12),-1):(i[o>>2]=e,0|r)}return{___uremdi3:Me,_bitshift64Lshr:Qe,_bitshift64Shl:ye,_calloc:be,_cellAreaKm2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))>0){if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1!=(0|e)){A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e))}}else o=0;return I=n,6371.007180918475*o*6371.007180918475},_cellAreaM2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))>0){if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1!=(0|e)){A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e))}}else o=0;return I=n,6371.007180918475*o*6371.007180918475*1e3*1e3},_cellAreaRads2:function(A,e){var r,t,n,o=0;if(n=I,I=I+192|0,t=n,OA(A|=0,e|=0,r=n+168|0),jA(A,e,t),(0|(e=0|i[t>>2]))<=0)return I=n,+(o=0);if(o=+_A(t+8|0,t+8+((1!=(0|e)&1)<<4)|0,r)+0,1==(0|e))return I=n,+o;A=1;do{o+=+_A(t+8+(A<<4)|0,t+8+(((0|(A=A+1|0))%(0|e)|0)<<4)|0,r)}while((0|A)<(0|e));return I=n,+o},_compact:function(A,e,r){e|=0;var t,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,Q=0,y=0,E=0;if(!(r|=0))return 0|(y=0);if(n=0|i[(o=A|=0)>>2],!0&0==(15728640&(o=0|i[o+4>>2])|0)){if((0|r)<=0)return 0|(y=0);if(i[(y=e)>>2]=n,i[y+4>>2]=o,1==(0|r))return 0|(y=0);n=1;do{Q=0|i[(k=A+(n<<3)|0)+4>>2],i[(y=e+(n<<3)|0)>>2]=i[k>>2],i[y+4>>2]=Q,n=n+1|0}while((0|n)!=(0|r));return 0|(n=0)}if(!(Q=0|pe(k=r<<3)))return 0|(y=-3);if(De(0|Q,0|A,0|k),!(t=0|be(r,8)))return Be(Q),0|(y=-3);n=r;A:for(;;){v=0|Qe(0|(h=0|i[(f=Q)>>2]),0|(f=0|i[f+4>>2]),52),M(),m=(v&=15)+-1|0,b=(0|n)>0;e:do{if(b){if(B=((0|n)<0)<<31>>31,w=0|ye(0|m,0,52),p=0|M(),m>>>0>15)for(o=0,A=h,r=f;;){if(!(0==(0|A)&0==(0|r))){if(a=0|Qe(0|A,0|r,52),M(),s=(0|(a&=15))<(0|m),a=(0|a)==(0|m),r=0|Me(0|(l=s?0:a?A:0),0|(A=s?0:a?r:0),0|n,0|B),M(),0==(0|(u=0|i[(s=a=t+(r<<3)|0)>>2]))&0==(0|(s=0|i[s+4>>2])))r=l;else for(w=0,g=r,d=s,r=l;;){if((0|w)>(0|n)){y=41;break A}if((0|u)==(0|r)&(-117440513&d|0)==(0|A)){l=0|Qe(0|u,0|d,56),M(),c=(l&=7)+1|0,p=0|Qe(0|u,0|d,45),M();r:do{if(0|S(127&p)){if(u=0|Qe(0|u,0|d,52),M(),!(u&=15)){s=6;break}for(s=1;;){if(!(0==((p=0|ye(7,0,3*(15-s|0)|0))&r|0)&0==((0|M())&A|0))){s=7;break r}if(!(s>>>0>>0)){s=6;break}s=s+1|0}}else s=7}while(0);if((l+2|0)>>>0>s>>>0){y=51;break A}p=0|ye(0|c,0,56),A=0|M()|-117440513&A,i[(s=a)>>2]=0,i[s+4>>2]=0,s=g,r|=p}else s=(g+1|0)%(0|n)|0;if(0==(0|(u=0|i[(d=a=t+(s<<3)|0)>>2]))&0==(0|(d=0|i[d+4>>2])))break;w=w+1|0,g=s}i[(p=a)>>2]=r,i[p+4>>2]=A}if((0|(o=o+1|0))>=(0|n))break e;A=0|i[(r=Q+(o<<3)|0)>>2],r=0|i[r+4>>2]}for(o=0,A=h,r=f;;){if(!(0==(0|A)&0==(0|r))){if(s=0|Qe(0|A,0|r,52),M(),(0|(s&=15))>=(0|m)){if((0|s)!=(0|m)&&(A|=w,r=-15728641&r|p,s>>>0>=v>>>0)){a=m;do{g=0|ye(7,0,3*(14-a|0)|0),a=a+1|0,A|=g,r=0|M()|r}while(a>>>0>>0)}}else A=0,r=0;if(s=0|Me(0|A,0|r,0|n,0|B),M(),!(0==(0|(l=0|i[(u=a=t+(s<<3)|0)>>2]))&0==(0|(u=0|i[u+4>>2]))))for(g=0;;){if((0|g)>(0|n)){y=41;break A}if((0|l)==(0|A)&(-117440513&u|0)==(0|r)){c=0|Qe(0|l,0|u,56),M(),d=(c&=7)+1|0,E=0|Qe(0|l,0|u,45),M();r:do{if(0|S(127&E)){if(l=0|Qe(0|l,0|u,52),M(),!(l&=15)){u=6;break}for(u=1;;){if(!(0==((E=0|ye(7,0,3*(15-u|0)|0))&A|0)&0==((0|M())&r|0))){u=7;break r}if(!(u>>>0>>0)){u=6;break}u=u+1|0}}else u=7}while(0);if((c+2|0)>>>0>u>>>0){y=51;break A}E=0|ye(0|d,0,56),r=0|M()|-117440513&r,i[(d=a)>>2]=0,i[d+4>>2]=0,A|=E}else s=(s+1|0)%(0|n)|0;if(0==(0|(l=0|i[(u=a=t+(s<<3)|0)>>2]))&0==(0|(u=0|i[u+4>>2])))break;g=g+1|0}i[(E=a)>>2]=A,i[E+4>>2]=r}if((0|(o=o+1|0))>=(0|n))break e;A=0|i[(r=Q+(o<<3)|0)>>2],r=0|i[r+4>>2]}}}while(0);if((n+5|0)>>>0<11){y=99;break}if(!(p=0|be((0|n)/6|0,8))){y=58;break}e:do{if(b){g=0,d=0;do{if(!(0==(0|(o=0|i[(A=s=t+(g<<3)|0)>>2]))&0==(0|(A=0|i[A+4>>2])))){u=0|Qe(0|o,0|A,56),M(),r=(u&=7)+1|0,l=-117440513&A,E=0|Qe(0|o,0|A,45),M();r:do{if(0|S(127&E)){if(c=0|Qe(0|o,0|A,52),M(),0|(c&=15))for(a=1;;){if(!(0==(o&(E=0|ye(7,0,3*(15-a|0)|0))|0)&0==(l&(0|M())|0)))break r;if(!(a>>>0>>0))break;a=a+1|0}o|=A=0|ye(0|r,0,56),A=0|M()|l,i[(r=s)>>2]=o,i[r+4>>2]=A,r=u+2|0}}while(0);7==(0|r)&&(i[(E=p+(d<<3)|0)>>2]=o,i[E+4>>2]=-117440513&A,d=d+1|0)}g=g+1|0}while((0|g)!=(0|n));if(b){if(w=((0|n)<0)<<31>>31,c=0|ye(0|m,0,52),g=0|M(),m>>>0>15)for(A=0,o=0;;){do{if(!(0==(0|h)&0==(0|f))){for(u=0|Qe(0|h,0|f,52),M(),a=(0|(u&=15))<(0|m),u=(0|u)==(0|m),a=0|Me(0|(s=a?0:u?h:0),0|(u=a?0:u?f:0),0|n,0|w),M(),r=0;;){if((0|r)>(0|n)){y=98;break A}if((-117440513&(l=0|i[(E=t+(a<<3)|0)+4>>2])|0)==(0|u)&&(0|i[E>>2])==(0|s)){y=70;break}if((0|i[(E=t+((a=(a+1|0)%(0|n)|0)<<3)|0)>>2])==(0|s)&&(0|i[E+4>>2])==(0|u))break;r=r+1|0}if(70==(0|y)&&(y=0,!0&100663296==(117440512&l|0)))break;i[(E=e+(o<<3)|0)>>2]=h,i[E+4>>2]=f,o=o+1|0}}while(0);if((0|(A=A+1|0))>=(0|n)){n=d;break e}h=0|i[(f=Q+(A<<3)|0)>>2],f=0|i[f+4>>2]}for(A=0,o=0;;){do{if(!(0==(0|h)&0==(0|f))){if(u=0|Qe(0|h,0|f,52),M(),(0|(u&=15))>=(0|m))if((0|u)!=(0|m))if(r=h|c,a=-15728641&f|g,u>>>0>>0)u=a;else{s=m;do{E=0|ye(7,0,3*(14-s|0)|0),s=s+1|0,r|=E,a=0|M()|a}while(s>>>0>>0);u=a}else r=h,u=f;else r=0,u=0;for(s=0|Me(0|r,0|u,0|n,0|w),M(),a=0;;){if((0|a)>(0|n)){y=98;break A}if((-117440513&(l=0|i[(E=t+(s<<3)|0)+4>>2])|0)==(0|u)&&(0|i[E>>2])==(0|r)){y=93;break}if((0|i[(E=t+((s=(s+1|0)%(0|n)|0)<<3)|0)>>2])==(0|r)&&(0|i[E+4>>2])==(0|u))break;a=a+1|0}if(93==(0|y)&&(y=0,!0&100663296==(117440512&l|0)))break;i[(E=e+(o<<3)|0)>>2]=h,i[E+4>>2]=f,o=o+1|0}}while(0);if((0|(A=A+1|0))>=(0|n)){n=d;break e}h=0|i[(f=Q+(A<<3)|0)>>2],f=0|i[f+4>>2]}}else o=0,n=d}else o=0,n=0}while(0);if(_e(0|t,0,0|k),De(0|Q,0|p,n<<3|0),Be(p),!n)break;e=e+(o<<3)|0}return 41==(0|y)?(Be(Q),Be(t),0|(E=-1)):51==(0|y)?(Be(Q),Be(t),0|(E=-2)):58==(0|y)?(Be(Q),Be(t),0|(E=-3)):98==(0|y)?(Be(p),Be(Q),Be(t),0|(E=-1)):(99==(0|y)&&De(0|e,0|Q,n<<3|0),Be(Q),Be(t),0|(E=0))},_destroyLinkedPolygon:function(A){var e=0,r=0,t=0,n=0;if(A|=0)for(t=1;;){if(0|(e=0|i[A>>2]))do{if(0|(r=0|i[e>>2]))do{n=r,r=0|i[r+16>>2],Be(n)}while(0!=(0|r));n=e,e=0|i[e+8>>2],Be(n)}while(0!=(0|e));if(e=A,A=0|i[A+8>>2],t||Be(e),!A)break;t=0}},_edgeLengthKm:function(A){return+ +n[20752+((A|=0)<<3)>>3]},_edgeLengthM:function(A){return+ +n[20880+((A|=0)<<3)>>3]},_emscripten_replace_memory:function(A){return t=new Int8Array(A),new Uint8Array(A),i=new Int32Array(A),new Float32Array(A),n=new Float64Array(A),r=A,!0},_exactEdgeLengthKm:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+c)*+l(+a)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)!=(0|e));return I=t,+(d=6371.007180918475*o)},_exactEdgeLengthM:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+c)*+l(+a)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)!=(0|e));return I=t,+(d=6371.007180918475*o*1e3)},_exactEdgeLengthRads:function(A,e){var r,t,o=0,a=0,f=0,u=0,c=0,d=0;if(t=I,I=I+176|0,WA(A|=0,e|=0,r=t),(0|(A=0|i[r>>2]))<=1)return I=t,+(f=0);e=A+-1|0,A=0,o=0,a=+n[r+8>>3],f=+n[r+16>>3];do{c=a,a=+n[r+8+((A=A+1|0)<<4)>>3],d=+h(.5*(a-c)),u=f,f=+n[r+8+(A<<4)+8>>3],u=d*d+(u=+h(.5*(f-u)))*(+l(+a)*+l(+c)*u),o+=2*+p(+ +s(+u),+ +s(+(1-u)))}while((0|A)<(0|e));return I=t,+o},_experimentalH3ToLocalIj:function(A,e,r,t,i){var n,o;return i|=0,o=I,I=I+16|0,(A=0|$A(A|=0,e|=0,r|=0,t|=0,n=o))||(cA(n,i),A=0),I=o,0|A},_experimentalLocalIjToH3:function(A,e,r,t){var i,n;return A|=0,e|=0,t|=0,i=I,I=I+16|0,dA(r|=0,n=i),t=0|Ae(A,e,n,t),I=i,0|t},_free:Be,_geoToH3:LA,_getDestinationH3IndexFromUnidirectionalEdge:function(A,e){A|=0;var r,t,n=0;return r=I,I=I+16|0,n=r,!0&268435456==(2013265920&(e|=0)|0)?(t=0|Qe(0|A,0|e,56),M(),i[n>>2]=0,n=0|U(A,-2130706433&e|134217728,7&t,n),e=0|M(),k(0|e),I=r,0|n):(n=0,k(0|(e=0)),I=r,0|n)},_getH3IndexesFromUnidirectionalEdge:function(A,e,r){A|=0;var t,n,o,a,f=0;o=I,I=I+16|0,t=o,a=!0&268435456==(2013265920&(e|=0)|0),n=-2130706433&e|134217728,i[(f=r|=0)>>2]=a?A:0,i[f+4>>2]=a?n:0,a?(e=0|Qe(0|A,0|e,56),M(),i[t>>2]=0,A=0|U(A,n,7&e,t),e=0|M()):(A=0,e=0),i[(f=r+8|0)>>2]=A,i[f+4>>2]=e,I=o},_getH3UnidirectionalEdge:function(A,e,r,t){var n,o,a=0,f=0,s=0,u=0,l=0;if(o=I,I=I+16|0,n=o,!(0|ZA(A|=0,e|=0,r|=0,t|=0)))return u=0,k(0|(s=0)),I=o,0|u;for(s=-2130706433&e,a=(a=0==(0|UA(A,e)))?1:2;i[n>>2]=0,f=a+1|0,!((0|(l=0|U(A,e,a,n)))==(0|r)&(0|M())==(0|t));){if(!(f>>>0<7)){a=0,A=0,u=6;break}a=f}return 6==(0|u)?(k(0|a),I=o,0|A):(l=0|ye(0|a,0,56),u=0|s|M()|268435456,l|=A,k(0|u),I=o,0|l)},_getH3UnidirectionalEdgeBoundary:WA,_getH3UnidirectionalEdgesFromHexagon:function(A,e,r){r|=0;var t,n=0;t=0==(0|UA(A|=0,e|=0)),e&=-2130706433,i[(n=r)>>2]=t?A:0,i[n+4>>2]=t?285212672|e:0,i[(n=r+8|0)>>2]=A,i[n+4>>2]=301989888|e,i[(n=r+16|0)>>2]=A,i[n+4>>2]=318767104|e,i[(n=r+24|0)>>2]=A,i[n+4>>2]=335544320|e,i[(n=r+32|0)>>2]=A,i[n+4>>2]=352321536|e,i[(r=r+40|0)>>2]=A,i[r+4>>2]=369098752|e},_getOriginH3IndexFromUnidirectionalEdge:function(A,e){var r;return A|=0,k(0|((r=!0&268435456==(2013265920&(e|=0)|0))?-2130706433&e|134217728:0)),0|(r?A:0)},_getPentagonIndexes:NA,_getRes0Indexes:function(A){A|=0;var e=0,r=0,t=0;e=0;do{ye(0|e,0,45),t=134225919|M(),i[(r=A+(e<<3)|0)>>2]=-1,i[r+4>>2]=t,e=e+1|0}while(122!=(0|e))},_h3Distance:function(A,e,r,t){var i,n,o;return r|=0,t|=0,o=I,I=I+32|0,n=o,A=0==(0|$A(A|=0,e|=0,A,e,i=o+12|0))&&0==(0|$A(A,e,r,t,n))?0|hA(i,n):-1,I=o,0|A},_h3GetBaseCell:IA,_h3GetFaces:function A(e,r,t){t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0;n=I,I=I+128|0,h=n+112|0,f=n+96|0,c=n,a=0|Qe(0|(e|=0),0|(r|=0),52),M(),u=15&a,i[h>>2]=u,s=0|Qe(0|e,0|r,45),M(),s&=127;A:do{if(0|S(s)){if(0|u)for(o=1;;){if(!(0==((l=0|ye(7,0,3*(15-o|0)|0))&e|0)&0==((0|M())&r|0))){a=0;break A}if(!(o>>>0>>0))break;o=o+1|0}if(!(1&a))return l=0|ye(u+1|0,0,52),c=0|M()|-15728641&r,A((l|e)&~(h=0|ye(7,0,3*(14-u|0)|0)),c&~(0|M()),t),void(I=n);a=1}else a=0}while(0);YA(e,r,f),a?(mA(f,h,c),l=5):(yA(f,h,c),l=6);A:do{if(0|S(s))if(u)for(o=1;;){if(!(0==((s=0|ye(7,0,3*(15-o|0)|0))&e|0)&0==((0|M())&r|0))){o=8;break A}if(!(o>>>0>>0)){o=20;break}o=o+1|0}else o=20;else o=8}while(0);if(_e(0|t,-1,0|o),a){a=0;do{for(MA(f=c+(a<<4)|0,0|i[h>>2]),f=0|i[f>>2],o=0;!(-1==(0|(u=0|i[(s=t+(o<<2)|0)>>2]))|(0|u)==(0|f));)o=o+1|0;i[s>>2]=f,a=a+1|0}while((0|a)!=(0|l))}else{a=0;do{for(kA(f=c+(a<<4)|0,0|i[h>>2],0,1),f=0|i[f>>2],o=0;!(-1==(0|(u=0|i[(s=t+(o<<2)|0)>>2]))|(0|u)==(0|f));)o=o+1|0;i[s>>2]=f,a=a+1|0}while((0|a)!=(0|l))}I=n},_h3GetResolution:function(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),52),M(),15&e|0},_h3IndexesAreNeighbors:ZA,_h3IsPentagon:UA,_h3IsResClassIII:function(A,e){return e=0|Qe(0|(A|=0),0|(e|=0),52),M(),1&e|0},_h3IsValid:FA,_h3Line:function(A,e,r,t,n){r|=0,t|=0,n|=0;var o,a=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,M=0,Q=0;if(o=I,I=I+48|0,s=o+12|0,M=o,0==(0|$A(A|=0,e|=0,A,e,a=o+24|0))&&0==(0|$A(A,e,r,t,s))){if((0|(k=0|hA(a,s)))<0)return I=o,0|(M=k);for(i[a>>2]=0,i[a+4>>2]=0,i[a+8>>2]=0,i[s>>2]=0,i[s+4>>2]=0,i[s+8>>2]=0,$A(A,e,A,e,a),$A(A,e,r,t,s),gA(a),gA(s),k?(w=+(0|k),m=a,r=c=0|i[a>>2],t=d=0|i[(b=a+4|0)>>2],a=g=0|i[(v=a+8|0)>>2],p=+((0|i[s>>2])-c|0)/w,B=+((0|i[s+4>>2])-d|0)/w,w=+((0|i[s+8>>2])-g|0)/w):(b=t=a+4|0,v=g=a+8|0,m=a,r=0|i[a>>2],t=0|i[t>>2],a=0|i[g>>2],p=0,B=0,w=0),i[M>>2]=r,i[(g=M+4|0)>>2]=t,i[(d=M+8|0)>>2]=a,c=0;;){Q=p*(l=+(0|c))+ +(0|r),u=B*l+ +(0|i[b>>2]),l=w*l+ +(0|i[v>>2]),t=~~+xe(+Q),s=~~+xe(+u),r=~~+xe(+l),Q=+f(+(+(0|t)-Q)),u=+f(+(+(0|s)-u)),l=+f(+(+(0|r)-l));do{if(!(Q>u&Q>l)){if(h=0-t|0,u>l){a=h-r|0;break}a=s,r=h-s|0;break}t=0-(s+r)|0,a=s}while(0);if(i[M>>2]=t,i[g>>2]=a,i[d>>2]=r,wA(M),Ae(A,e,M,n+(c<<3)|0),(0|c)==(0|k))break;c=c+1|0,r=0|i[m>>2]}return I=o,0|(M=0)}return I=o,0|(M=-1)},_h3LineSize:function(A,e,r,t){var i,n,o;return r|=0,t|=0,o=I,I=I+32|0,n=o,A=0==(0|$A(A|=0,e|=0,A,e,i=o+12|0))&&0==(0|$A(A,e,r,t,n))?0|hA(i,n):-1,I=o,(A>>>31^1)+A|0},_h3SetToLinkedGeo:function(A,e,r){r|=0;var t,n,o,a=0;if(o=I,I=I+32|0,t=o,function(A,e,r){A|=0,r|=0;var t,n,o=0,a=0,f=0,s=0,u=0;if(n=I,I=I+176|0,t=n,(0|(e|=0))<1)return se(r,0,0),void(I=n);s=0|Qe(0|i[(s=A)>>2],0|i[s+4>>2],52),M(),se(r,(0|e)>6?e:6,15&s),s=0;do{if(jA(0|i[(o=A+(s<<3)|0)>>2],0|i[o+4>>2],t),(0|(o=0|i[t>>2]))>0){u=0;do{f=t+8+(u<<4)|0,(a=0|de(r,o=t+8+(((0|(u=u+1|0))%(0|o)|0)<<4)|0,f))?he(r,a):ce(r,f,o),o=0|i[t>>2]}while((0|u)<(0|o))}s=s+1|0}while((0|s)!=(0|e));I=n}(A|=0,e|=0,n=o+16|0),i[r>>2]=0,i[r+4>>2]=0,i[r+8>>2]=0,!(A=0|le(n)))return XA(r),ue(n),void(I=o);do{e=0|JA(r);do{KA(e,A),a=A+16|0,i[t>>2]=i[a>>2],i[t+4>>2]=i[a+4>>2],i[t+8>>2]=i[a+8>>2],i[t+12>>2]=i[a+12>>2],he(n,A),A=0|ge(n,t)}while(0!=(0|A));A=0|le(n)}while(0!=(0|A));XA(r),ue(n),I=o},_h3ToCenterChild:function(A,e,r){r|=0;var t=0,i=0;if(t=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(t&=15))<=(0|r)){if((0|t)!=(0|r)&&(A|=i=0|ye(0|r,0,52),e=0|M()|-15728641&e,(0|t)<(0|r)))do{i=0|ye(7,0,3*(14-t|0)|0),t=t+1|0,A&=~i,e&=~(0|M())}while((0|t)<(0|r))}else e=0,A=0;return k(0|e),0|A},_h3ToChildren:PA,_h3ToGeo:OA,_h3ToGeoBoundary:jA,_h3ToParent:CA,_h3UnidirectionalEdgeIsValid:function(A,e){var r=0;if(!(!0&268435456==(2013265920&(e|=0)|0)))return 0|(r=0);switch(r=0|Qe(0|(A|=0),0|e,56),M(),7&r){case 0:case 7:return 0|(r=0)}return!0&16777216==(117440512&e|0)&0!=(0|UA(A,r=-2130706433&e|134217728))?0|(r=0):0|(r=0|FA(A,r))},_hexAreaKm2:function(A){return+ +n[20496+((A|=0)<<3)>>3]},_hexAreaM2:function(A){return+ +n[20624+((A|=0)<<3)>>3]},_hexRing:function(A,e,r,t){A|=0,e|=0,t|=0;var n,o=0,a=0,f=0,s=0,u=0,l=0,h=0;if(n=I,I=I+16|0,h=n,!(r|=0))return i[(h=t)>>2]=A,i[h+4>>2]=e,I=n,0|(h=0);i[h>>2]=0;A:do{if(0|UA(A,e))A=1;else{if(a=(0|r)>0){o=0,l=A;do{if(0==(0|(l=0|U(l,e,4,h)))&0==(0|(e=0|M()))){A=2;break A}if(o=o+1|0,0|UA(l,e)){A=1;break A}}while((0|o)<(0|r));if(i[(u=t)>>2]=l,i[u+4>>2]=e,u=r+-1|0,a){a=0,f=1,o=l,A=e;do{if(0==(0|(o=0|U(o,A,2,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(f<<3)|0)>>2]=o,i[s+4>>2]=A,f=f+1|0,0|UA(o,A)){A=1;break A}a=a+1|0}while((0|a)<(0|r));s=0,a=f;do{if(0==(0|(o=0|U(o,A,3,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(f=t+(a<<3)|0)>>2]=o,i[f+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}s=s+1|0}while((0|s)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,1,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,5,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));f=0;do{if(0==(0|(o=0|U(o,A,4,h)))&0==(0|(A=0|M()))){A=2;break A}if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,a=a+1|0,0|UA(o,A)){A=1;break A}f=f+1|0}while((0|f)<(0|r));for(f=0;;){if(0==(0|(o=0|U(o,A,6,h)))&0==(0|(A=0|M()))){A=2;break A}if((0|f)!=(0|u)){if(i[(s=t+(a<<3)|0)>>2]=o,i[s+4>>2]=A,0|UA(o,A)){A=1;break A}a=a+1|0}if((0|(f=f+1|0))>=(0|r)){f=l,a=e;break}}}else f=l,o=l,a=e,A=e}else i[(f=t)>>2]=A,i[f+4>>2]=e,f=A,o=A,a=e,A=e;A=1&((0|f)!=(0|o)|(0|a)!=(0|A))}}while(0);return I=n,0|(h=A)},_i64Subtract:ve,_kRing:F,_kRingDistances:function(A,e,r,t,i){var n;if(0|C(A|=0,e|=0,r|=0,t|=0,i|=0)){if(_e(0|t,0,(n=1+(0|b(3*r|0,r+1|0))|0)<<3|0),0|i)return _e(0|i,0,n<<2|0),void P(A,e,r,t,i,n,0);(i=0|be(n,4))&&(P(A,e,r,t,i,n,0),Be(i))}},_llvm_minnum_f64:Ee,_llvm_round_f64:xe,_malloc:pe,_maxFaceCount:function(A,e){var r=0,t=0;if(t=0|Qe(0|(A|=0),0|(e|=0),45),M(),!(0|S(127&t)))return 0|(t=2);if(t=0|Qe(0|A,0|e,52),M(),!(t&=15))return 0|(t=5);for(r=1;;){if(!(0==((0|ye(7,0,3*(15-r|0)|0))&A|0)&0==((0|M())&e|0))){r=2,A=6;break}if(!(r>>>0>>0)){r=5,A=6;break}r=r+1|0}return 6==(0|A)?0|r:0},_maxH3ToChildrenSize:function(A,e,r){return r|=0,A=0|Qe(0|(A|=0),0|(e|=0),52),M(),(0|r)<16&(0|(A&=15))<=(0|r)?0|(r=0|ee(7,r-A|0)):0|(r=0)},_maxKringSize:function(A){return 1+(0|b(3*(A|=0)|0,A+1|0))|0},_maxPolyfillSize:function(A,e){e|=0;var r,t=0,n=0,o=0,a=0,f=0;if(r=I,I=I+48|0,o=r+8|0,n=r,a=0|i[(f=A|=0)+4>>2],i[(t=n)>>2]=i[f>>2],i[t+4>>2]=a,te(n,o),o=0|j(o,e),e=0|i[n>>2],(0|(n=0|i[A+8>>2]))<=0)return I=r,0|(f=(f=(a=(0|o)<(0|(f=e)))?f:o)+12|0);t=0|i[A+12>>2],A=0;do{e=(0|i[t+(A<<3)>>2])+e|0,A=A+1|0}while((0|A)<(0|n));return I=r,0|(f=(f=(f=(0|o)<(0|e))?e:o)+12|0)},_maxUncompactSize:function(A,e,r){A|=0,r|=0;var t=0,n=0,o=0,a=0;if((0|(e|=0))<=0)return 0|(r=0);if((0|r)>=16){for(t=0;;){if(!(0==(0|i[(a=A+(t<<3)|0)>>2])&0==(0|i[a+4>>2]))){t=-1,n=13;break}if((0|(t=t+1|0))>=(0|e)){t=0,n=13;break}}if(13==(0|n))return 0|t}t=0,a=0;A:for(;;){o=0|i[(n=A+(a<<3)|0)>>2],n=0|i[n+4>>2];do{if(!(0==(0|o)&0==(0|n))){if(n=0|Qe(0|o,0|n,52),M(),(0|(n&=15))>(0|r)){t=-1,n=13;break A}if((0|n)==(0|r)){t=t+1|0;break}t=(0|ee(7,r-n|0))+t|0;break}}while(0);if((0|(a=a+1|0))>=(0|e)){n=13;break}}return 13==(0|n)?0|t:0},_memcpy:De,_memset:_e,_numHexagons:function(A){var e;return A=0|i[(e=21008+((A|=0)<<3)|0)>>2],k(0|i[e+4>>2]),0|A},_pentagonIndexCount:function(){return 12},_pointDistKm:DA,_pointDistM:function(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))*6371.007180918475*1e3},_pointDistRads:function(A,e){A|=0;var r,t,i,o=0;return t=+n[(e|=0)>>3],r=+n[A>>3],o=(i=+h(.5*(t-r)))*i+(o=+h(.5*(+n[e+8>>3]-+n[A+8>>3])))*(+l(+t)*+l(+r)*o),2*+p(+ +s(+o),+ +s(+(1-o)))},_polyfill:function(A,e,r){var t,n=0,o=0,a=0,f=0,s=0;if(t=I,I=I+48|0,n=t+8|0,o=t,0|function(A,e,r){e|=0,r|=0;var t=0,n=0,o=0,a=0,f=0,s=0,u=0,l=0,h=0,c=0,d=0,g=0,w=0,p=0,B=0,b=0,v=0,m=0,k=0,y=0,E=0,x=0,D=0,_=0,F=0,U=0,S=0,T=0,V=0,H=0;H=I,I=I+112|0,U=H+80|0,s=H+72|0,S=H,T=H+56|0,(V=0|pe(32+(i[(u=(A=A|0)+8|0)>>2]<<5)|0))||Q(22848,22448,800,22456);if(ie(A,V),t=0|i[(o=A)+4>>2],i[(f=s)>>2]=i[o>>2],i[f+4>>2]=t,te(s,U),f=0|j(U,e),t=0|i[s>>2],(0|(o=0|i[u>>2]))>0){a=0|i[A+12>>2],n=0;do{t=(0|i[a+(n<<3)>>2])+t|0,n=n+1|0}while((0|n)!=(0|o))}if(n=0|be(F=(f=(0|f)<(0|t)?t:f)+12|0,8),l=0|be(F,8),i[U>>2]=0,_=0|i[(D=A)+4>>2],i[(t=s)>>2]=i[D>>2],i[t+4>>2]=_,0|(t=0|G(s,F,e,U,n,l)))return Be(n),Be(l),Be(V),I=H,0|(V=t);A:do{if((0|i[u>>2])>0){for(o=A+12|0,t=0;a=0|G((0|i[o>>2])+(t<<3)|0,F,e,U,n,l),t=t+1|0,!(0|a);)if((0|t)>=(0|i[u>>2]))break A;return Be(n),Be(l),Be(V),I=H,0|(V=a)}}while(0);(0|f)>-12&&_e(0|l,0,((0|F)>1?F:1)<<3|0);A:do{if((0|i[U>>2])>0){_=((0|F)<0)<<31>>31,m=n,k=l,y=n,E=n,x=l,D=n,t=n,p=n,B=l,b=l,v=l,n=l;e:for(;;){for(w=0|i[U>>2],d=0,g=0,o=0;;){f=(a=S)+56|0;do{i[a>>2]=0,a=a+4|0}while((0|a)<(0|f));if(0|C(s=0|i[(e=m+(d<<3)|0)>>2],e=0|i[e+4>>2],1,S,0)){f=(a=S)+56|0;do{i[a>>2]=0,a=a+4|0}while((0|a)<(0|f));0|(a=0|be(7,4))&&(P(s,e,1,S,a,7,0),Be(a))}c=0;do{l=0|i[(h=S+(c<<3)|0)>>2],h=0|i[h+4>>2];r:do{if(!(0==(0|l)&0==(0|h))){if(s=0|Me(0|l,0|h,0|F,0|_),M(),!(0==(0|(e=0|i[(f=a=r+(s<<3)|0)>>2]))&0==(0|(f=0|i[f+4>>2]))))for(u=0;;){if((0|u)>(0|F))break e;if((0|e)==(0|l)&(0|f)==(0|h))break r;if(0==(0|(e=0|i[(f=a=r+((s=(s+1|0)%(0|F)|0)<<3)|0)>>2]))&0==(0|(f=0|i[f+4>>2])))break;u=u+1|0}0==(0|l)&0==(0|h)||(OA(l,h,T),0|ne(A,V,T)&&(i[(u=a)>>2]=l,i[u+4>>2]=h,i[(u=k+(o<<3)|0)>>2]=l,i[u+4>>2]=h,o=o+1|0))}}while(0);c=c+1|0}while(c>>>0<7);if((0|(g=g+1|0))>=(0|w))break;d=d+1|0}if((0|w)>0&&_e(0|y,0,w<<3|0),i[U>>2]=o,!((0|o)>0))break A;l=n,h=v,c=D,d=b,g=B,w=k,n=p,v=t,b=E,B=y,p=l,t=h,D=x,x=c,E=d,y=g,k=m,m=w}return Be(E),Be(x),Be(V),I=H,0|(V=-1)}t=l}while(0);return Be(V),Be(n),Be(t),I=H,0|(V=0)}(A|=0,e|=0,r|=0)){if(a=0|i[(s=A)+4>>2],i[(f=o)>>2]=i[s>>2],i[f+4>>2]=a,te(o,n),f=0|j(n,e),e=0|i[o>>2],(0|(a=0|i[A+8>>2]))>0){o=0|i[A+12>>2],n=0;do{e=(0|i[o+(n<<3)>>2])+e|0,n=n+1|0}while((0|n)!=(0|a))}(0|(e=(0|f)<(0|e)?e:f))<=-12||_e(0|r,0,8+(((0|(s=e+11|0))>0?s:0)<<3)|0),I=t}else I=t},_res0IndexCount:function(){return 122},_round:Ie,_sbrk:Fe,_sizeOfCoordIJ:function(){return 8},_sizeOfGeoBoundary:function(){return 168},_sizeOfGeoCoord:function(){return 16},_sizeOfGeoPolygon:function(){return 16},_sizeOfGeofence:function(){return 8},_sizeOfH3Index:function(){return 8},_sizeOfLinkedGeoPolygon:function(){return 12},_uncompact:function(A,e,r,t,n){A|=0,r|=0,t|=0,n|=0;var o=0,a=0,f=0,s=0,u=0,l=0;if((0|(e|=0))<=0)return 0|(n=0);if((0|n)>=16){for(o=0;;){if(!(0==(0|i[(l=A+(o<<3)|0)>>2])&0==(0|i[l+4>>2]))){o=14;break}if((0|(o=o+1|0))>=(0|e)){a=0,o=16;break}}if(14==(0|o))return 0|((0|t)>0?-2:-1);if(16==(0|o))return 0|a}o=0,l=0;A:for(;;){a=0|i[(f=u=A+(l<<3)|0)>>2],f=0|i[f+4>>2];do{if(!(0==(0|a)&0==(0|f))){if((0|o)>=(0|t)){a=-1,o=16;break A}if(s=0|Qe(0|a,0|f,52),M(),(0|(s&=15))>(0|n)){a=-2,o=16;break A}if((0|s)==(0|n)){i[(u=r+(o<<3)|0)>>2]=a,i[u+4>>2]=f,o=o+1|0;break}if((0|(a=(0|ee(7,n-s|0))+o|0))>(0|t)){a=-1,o=16;break A}PA(0|i[u>>2],0|i[u+4>>2],n,r+(o<<3)|0),o=a}}while(0);if((0|(l=l+1|0))>=(0|e)){a=0,o=16;break}}return 16==(0|o)?0|a:0},establishStackSpace:function(A,e){I=A|=0},stackAlloc:function(A){var e;return e=I,I=(I=I+(A|=0)|0)+15&-16,0|e},stackRestore:function(A){I=A|=0},stackSave:function(){return 0|I}}}({Math:Math,Int8Array:Int8Array,Int32Array:Int32Array,Uint8Array:Uint8Array,Float32Array:Float32Array,Float64Array:Float64Array},{a:fA,b:function(A){s=A},c:u,d:function(A,e,r,t){fA("Assertion failed: "+g(A)+", at: "+[e?g(e):"unknown filename",r,t?g(t):"unknown function"])},e:function(A){return r.___errno_location&&(v[r.___errno_location()>>2]=A),A},f:N,g:function(A,e,r){B.set(B.subarray(e,e+r),A)},h:function(A){var e=N(),r=16777216,t=2130706432;if(A>t)return!1;for(var i=Math.max(e,16777216);i>0]=e;break;case"i16":b[A>>1]=e;break;case"i32":v[A>>2]=e;break;case"i64":H=[e>>>0,(V=e,+F(V)>=1?V>0?(0|U(+P(V/4294967296),4294967295))>>>0:~~+C((V-+(~~V>>>0))/4294967296)>>>0:0)],v[A>>2]=H[0],v[A+4>>2]=H[1];break;case"float":m[A>>2]=e;break;case"double":k[A>>3]=e;break;default:fA("invalid type for setValue: "+r)}},r.getValue=function(A,e,r){switch("*"===(e=e||"i8").charAt(e.length-1)&&(e="i32"),e){case"i1":case"i8":return p[A>>0];case"i16":return b[A>>1];case"i32":case"i64":return v[A>>2];case"float":return m[A>>2];case"double":return k[A>>3];default:fA("invalid type for getValue: "+e)}return null},r.getTempRet0=u,R){z(R)||(K=R,R=r.locateFile?r.locateFile(K,o):o+K),G++,r.monitorRunDependencies&&r.monitorRunDependencies(G);var tA=function(A){A.byteLength&&(A=new Uint8Array(A)),B.set(A,8),r.memoryInitializerRequest&&delete r.memoryInitializerRequest.response,function(A){if(G--,r.monitorRunDependencies&&r.monitorRunDependencies(G),0==G&&(null!==S&&(clearInterval(S),S=null),T)){var e=T;T=null,e()}}()},iA=function(){i(R,tA,(function(){throw"could not load memory initializer "+R}))},nA=J(R);if(nA)tA(nA.buffer);else if(r.memoryInitializerRequest){var oA=function(){var A=r.memoryInitializerRequest,e=A.response;if(200!==A.status&&0!==A.status){var t=J(r.memoryInitializerRequestURL);if(!t)return console.warn("a problem seems to have happened with Module.memoryInitializerRequest, status: "+A.status+", retrying "+R),void iA();e=t.buffer}tA(e)};r.memoryInitializerRequest.response?setTimeout(oA,0):r.memoryInitializerRequest.addEventListener("load",oA)}else iA()}function aA(A){function e(){X||(X=!0,l||(E(D),E(_),r.onRuntimeInitialized&&r.onRuntimeInitialized(),function(){if(r.postRun)for("function"==typeof r.postRun&&(r.postRun=[r.postRun]);r.postRun.length;)A=r.postRun.shift(),I.unshift(A);var A;E(I)}()))}A=A||n,G>0||(!function(){if(r.preRun)for("function"==typeof r.preRun&&(r.preRun=[r.preRun]);r.preRun.length;)A=r.preRun.shift(),x.unshift(A);var A;E(x)}(),G>0||(r.setStatus?(r.setStatus("Running..."),setTimeout((function(){setTimeout((function(){r.setStatus("")}),1),e()}),1)):e()))}function fA(A){throw r.onAbort&&r.onAbort(A),a(A+=""),f(A),l=!0,"abort("+A+"). Build with -s ASSERTIONS=1 for more info."}if(T=function A(){X||aA(),X||(T=A)},r.run=aA,r.abort=fA,r.preInit)for("function"==typeof r.preInit&&(r.preInit=[r.preInit]);r.preInit.length>0;)r.preInit.pop()();return aA(),A}("object"==typeof t?t:{}),i="number",n={};[["sizeOfH3Index",i],["sizeOfGeoCoord",i],["sizeOfGeoBoundary",i],["sizeOfGeoPolygon",i],["sizeOfGeofence",i],["sizeOfLinkedGeoPolygon",i],["sizeOfCoordIJ",i],["h3IsValid",i,[i,i]],["geoToH3",i,[i,i,i]],["h3ToGeo",null,[i,i,i]],["h3ToGeoBoundary",null,[i,i,i]],["maxKringSize",i,[i]],["kRing",null,[i,i,i,i]],["kRingDistances",null,[i,i,i,i,i]],["hexRing",null,[i,i,i,i]],["maxPolyfillSize",i,[i,i]],["polyfill",null,[i,i,i]],["h3SetToLinkedGeo",null,[i,i,i]],["destroyLinkedPolygon",null,[i]],["compact",i,[i,i,i]],["uncompact",i,[i,i,i,i,i]],["maxUncompactSize",i,[i,i,i]],["h3IsPentagon",i,[i,i]],["h3IsResClassIII",i,[i,i]],["h3GetBaseCell",i,[i,i]],["h3GetResolution",i,[i,i]],["maxFaceCount",i,[i,i]],["h3GetFaces",null,[i,i,i]],["h3ToParent",i,[i,i,i]],["h3ToChildren",null,[i,i,i,i]],["h3ToCenterChild",i,[i,i,i]],["maxH3ToChildrenSize",i,[i,i,i]],["h3IndexesAreNeighbors",i,[i,i,i,i]],["getH3UnidirectionalEdge",i,[i,i,i,i]],["getOriginH3IndexFromUnidirectionalEdge",i,[i,i]],["getDestinationH3IndexFromUnidirectionalEdge",i,[i,i]],["h3UnidirectionalEdgeIsValid",i,[i,i]],["getH3IndexesFromUnidirectionalEdge",null,[i,i,i]],["getH3UnidirectionalEdgesFromHexagon",null,[i,i,i]],["getH3UnidirectionalEdgeBoundary",null,[i,i,i]],["h3Distance",i,[i,i,i,i]],["h3Line",i,[i,i,i,i,i]],["h3LineSize",i,[i,i,i,i]],["experimentalH3ToLocalIj",i,[i,i,i,i,i]],["experimentalLocalIjToH3",i,[i,i,i,i]],["hexAreaM2",i,[i]],["hexAreaKm2",i,[i]],["edgeLengthM",i,[i]],["edgeLengthKm",i,[i]],["pointDistM",i,[i,i]],["pointDistKm",i,[i,i]],["pointDistRads",i,[i,i]],["cellAreaM2",i,[i,i]],["cellAreaKm2",i,[i,i]],["cellAreaRads2",i,[i,i]],["exactEdgeLengthM",i,[i,i]],["exactEdgeLengthKm",i,[i,i]],["exactEdgeLengthRads",i,[i,i]],["numHexagons",i,[i]],["getRes0Indexes",null,[i]],["res0IndexCount",i],["getPentagonIndexes",null,[i,i]],["pentagonIndexCount",i]].forEach((function(A){n[A[0]]=t.cwrap.apply(t,A)}));var o=16,a=n.sizeOfH3Index(),f=n.sizeOfGeoCoord(),s=n.sizeOfGeoBoundary(),u=n.sizeOfGeoPolygon(),l=n.sizeOfGeofence(),h=n.sizeOfLinkedGeoPolygon(),c=n.sizeOfCoordIJ(),d={m:"m",m2:"m2",km:"km",km2:"km2",rads:"rads",rads2:"rads2"};function g(A){if("number"!=typeof A||A<0||A>15||Math.floor(A)!==A)throw new Error("Invalid resolution: "+A)}var w=/[^0-9a-fA-F]/;function p(A){if(Array.isArray(A)&&2===A.length&&Number.isInteger(A[0])&&Number.isInteger(A[1]))return A;if("string"!=typeof A||w.test(A))return[0,0];var e=parseInt(A.substring(0,A.length-8),o);return[parseInt(A.substring(A.length-8),o),e]}function B(A){if(A>=0)return A.toString(o);var e=v(8,(A&=2147483647).toString(o));return e=(parseInt(e[0],o)+8).toString(o)+e.substring(1)}function b(A,e){return B(e)+v(8,B(A))}function v(A,e){for(var r=A-e.length,t="",i=0;i=0&&r.push(n)}return r}(a,o);return t._free(a),f},r.h3GetResolution=function(A){var e=p(A),r=e[0],t=e[1];return n.h3IsValid(r,t)?n.h3GetResolution(r,t):-1},r.geoToH3=function(A,e,r){var i=t._malloc(f);t.HEAPF64.set([A,e].map(U),i/8);var o=M(n.geoToH3(i,r));return t._free(i),o},r.h3ToGeo=function(A){var e=t._malloc(f),r=p(A),i=r[0],o=r[1];n.h3ToGeo(i,o,e);var a=I(e);return t._free(e),a},r.h3ToGeoBoundary=function(A,e){var r=t._malloc(s),i=p(A),o=i[0],a=i[1];n.h3ToGeoBoundary(o,a,r);var f=C(r,e,e);return t._free(r),f},r.h3ToParent=function(A,e){var r=p(A),t=r[0],i=r[1];return M(n.h3ToParent(t,i,e))},r.h3ToChildren=function(A,e){if(!P(A))return[];var r=p(A),i=r[0],o=r[1],f=n.maxH3ToChildrenSize(i,o,e),s=t._calloc(f,a);n.h3ToChildren(i,o,e,s);var u=E(s,f);return t._free(s),u},r.h3ToCenterChild=function(A,e){var r=p(A),t=r[0],i=r[1];return M(n.h3ToCenterChild(t,i,e))},r.kRing=function(A,e){var r=p(A),i=r[0],o=r[1],f=n.maxKringSize(e),s=t._calloc(f,a);n.kRing(i,o,e,s);var u=E(s,f);return t._free(s),u},r.kRingDistances=function(A,e){var r=p(A),i=r[0],o=r[1],f=n.maxKringSize(e),s=t._calloc(f,a),u=t._calloc(f,4);n.kRingDistances(i,o,e,s,u);for(var l=[],h=0;h0){r=t._calloc(i,l);for(var f=0;f0){for(var n=t.getValue(A+r,"i32"),o=0;o */ +r.read=function(A,e,r,t,i){var n,o,a=8*i-t-1,f=(1<>1,u=-7,l=r?i-1:0,h=r?-1:1,c=A[e+l];for(l+=h,n=c&(1<<-u)-1,c>>=-u,u+=a;u>0;n=256*n+A[e+l],l+=h,u-=8);for(o=n&(1<<-u)-1,n>>=-u,u+=t;u>0;o=256*o+A[e+l],l+=h,u-=8);if(0===n)n=1-s;else{if(n===f)return o?NaN:1/0*(c?-1:1);o+=Math.pow(2,t),n-=s}return(c?-1:1)*o*Math.pow(2,n-t)},r.write=function(A,e,r,t,i,n){var o,a,f,s=8*n-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,c=t?0:n-1,d=t?1:-1,g=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=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(f=Math.pow(2,-o))<1&&(o--,f*=2),(e+=o+l>=1?h/f:h*Math.pow(2,1-l))*f>=2&&(o++,f/=2),o+l>=u?(a=0,o=u):o+l>=1?(a=(e*f-1)*Math.pow(2,i),o+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),o=0));i>=8;A[r+c]=255&a,c+=d,a/=256,i-=8);for(o=o<0;A[r+c]=255&o,c+=d,o/=256,s-=8);A[r+c-d]|=128*g}},{}],9:[function(A,e,r){"use strict";e.exports=i;var t=A("ieee754");function i(A){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(A)?A:new Uint8Array(A||0),this.pos=0,this.type=0,this.length=this.buf.length}i.Varint=0,i.Fixed64=1,i.Bytes=2,i.Fixed32=5;var n=4294967296,o=1/n,a="undefined"==typeof TextDecoder?null:new TextDecoder("utf8");function f(A){return A.type===i.Bytes?A.readVarint()+A.pos:A.pos+1}function s(A,e,r){return r?4294967296*e+(A>>>0):4294967296*(e>>>0)+(A>>>0)}function u(A,e,r){var t=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(t);for(var i=r.pos-1;i>=A;i--)r.buf[i+t]=r.buf[i]}function l(A,e){for(var r=0;r>>8,A[r+2]=e>>>16,A[r+3]=e>>>24}function k(A,e){return(A[e]|A[e+1]<<8|A[e+2]<<16)+(A[e+3]<<24)}i.prototype={destroy:function(){this.buf=null},readFields:function(A,e,r){for(r=r||this.length;this.pos>3,n=this.pos;this.type=7&t,A(i,e,this),this.pos===n&&this.skip(t)}return e},readMessage:function(A,e){return this.readFields(A,e,this.readVarint()+this.pos)},readFixed32:function(){var A=v(this.buf,this.pos);return this.pos+=4,A},readSFixed32:function(){var A=k(this.buf,this.pos);return this.pos+=4,A},readFixed64:function(){var A=v(this.buf,this.pos)+v(this.buf,this.pos+4)*n;return this.pos+=8,A},readSFixed64:function(){var A=v(this.buf,this.pos)+k(this.buf,this.pos+4)*n;return this.pos+=8,A},readFloat:function(){var A=t.read(this.buf,this.pos,!0,23,4);return this.pos+=4,A},readDouble:function(){var A=t.read(this.buf,this.pos,!0,52,8);return this.pos+=8,A},readVarint:function(A){var e,r,t=this.buf;return e=127&(r=t[this.pos++]),r<128?e:(e|=(127&(r=t[this.pos++]))<<7,r<128?e:(e|=(127&(r=t[this.pos++]))<<14,r<128?e:(e|=(127&(r=t[this.pos++]))<<21,r<128?e:function(A,e,r){var t,i,n=r.buf;if(i=n[r.pos++],t=(112&i)>>4,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<3,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<10,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<17,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(127&i)<<24,i<128)return s(A,t,e);if(i=n[r.pos++],t|=(1&i)<<31,i<128)return s(A,t,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=t[this.pos]))<<28,A,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var A=this.readVarint();return A%2==1?(A+1)/-2:A/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var A=this.readVarint()+this.pos,e=this.pos;return this.pos=A,A-e>=12&&a?function(A,e,r){return a.decode(A.subarray(e,r))}(this.buf,e,A):function(A,e,r){var t="",i=e;for(;i239?4:f>223?3:f>191?2:1;if(i+u>r)break;1===u?f<128&&(s=f):2===u?128==(192&(n=A[i+1]))&&(s=(31&f)<<6|63&n)<=127&&(s=null):3===u?(n=A[i+1],o=A[i+2],128==(192&n)&&128==(192&o)&&((s=(15&f)<<12|(63&n)<<6|63&o)<=2047||s>=55296&&s<=57343)&&(s=null)):4===u&&(n=A[i+1],o=A[i+2],a=A[i+3],128==(192&n)&&128==(192&o)&&128==(192&a)&&((s=(15&f)<<18|(63&n)<<12|(63&o)<<6|63&a)<=65535||s>=1114112)&&(s=null)),null===s?(s=65533,u=1):s>65535&&(s-=65536,t+=String.fromCharCode(s>>>10&1023|55296),s=56320|1023&s),t+=String.fromCharCode(s),i+=u}return t}(this.buf,e,A)},readBytes:function(){var A=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,A);return this.pos=A,e},readPackedVarint:function(A,e){if(this.type!==i.Bytes)return A.push(this.readVarint(e));var r=f(this);for(A=A||[];this.pos127;);else if(e===i.Bytes)this.pos=this.readVarint()+this.pos;else if(e===i.Fixed32)this.pos+=4;else{if(e!==i.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(A,e){this.writeVarint(A<<3|e)},realloc:function(A){for(var e=this.length||16;e268435455||A<0?function(A,e){var r,t;A>=0?(r=A%4294967296|0,t=A/4294967296|0):(t=~(-A/4294967296),4294967295^(r=~(-A%4294967296))?r=r+1|0:(r=0,t=t+1|0));if(A>=0x10000000000000000||A<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(A,e,r){r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos++]=127&A|128,A>>>=7,r.buf[r.pos]=127&A}(r,0,e),function(A,e){var r=(7&A)<<4;if(e.buf[e.pos++]|=r|((A>>>=3)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;if(e.buf[e.pos++]=127&A|((A>>>=7)?128:0),!A)return;e.buf[e.pos++]=127&A}(t,e)}(A,this):(this.realloc(4),this.buf[this.pos++]=127&A|(A>127?128:0),A<=127||(this.buf[this.pos++]=127&(A>>>=7)|(A>127?128:0),A<=127||(this.buf[this.pos++]=127&(A>>>=7)|(A>127?128:0),A<=127||(this.buf[this.pos++]=A>>>7&127))))},writeSVarint:function(A){this.writeVarint(A<0?2*-A-1:2*A)},writeBoolean:function(A){this.writeVarint(Boolean(A))},writeString:function(A){A=String(A),this.realloc(4*A.length),this.pos++;var e=this.pos;this.pos=function(A,e,r){for(var t,i,n=0;n55295&&t<57344){if(!i){t>56319||n+1===e.length?(A[r++]=239,A[r++]=191,A[r++]=189):i=t;continue}if(t<56320){A[r++]=239,A[r++]=191,A[r++]=189,i=t;continue}t=i-55296<<10|t-56320|65536,i=null}else i&&(A[r++]=239,A[r++]=191,A[r++]=189,i=null);t<128?A[r++]=t:(t<2048?A[r++]=t>>6|192:(t<65536?A[r++]=t>>12|224:(A[r++]=t>>18|240,A[r++]=t>>12&63|128),A[r++]=t>>6&63|128),A[r++]=63&t|128)}return r}(this.buf,A,this.pos);var r=this.pos-e;r>=128&&u(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r},writeFloat:function(A){this.realloc(4),t.write(this.buf,A,this.pos,!0,23,4),this.pos+=4},writeDouble:function(A){this.realloc(8),t.write(this.buf,A,this.pos,!0,52,8),this.pos+=8},writeBytes:function(A){var e=A.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&u(r,t,this),this.pos=r-1,this.writeVarint(t),this.pos+=t},writeMessage:function(A,e,r){this.writeTag(A,i.Bytes),this.writeRawMessage(e,r)},writePackedVarint:function(A,e){e.length&&this.writeMessage(A,l,e)},writePackedSVarint:function(A,e){e.length&&this.writeMessage(A,h,e)},writePackedBoolean:function(A,e){e.length&&this.writeMessage(A,g,e)},writePackedFloat:function(A,e){e.length&&this.writeMessage(A,c,e)},writePackedDouble:function(A,e){e.length&&this.writeMessage(A,d,e)},writePackedFixed32:function(A,e){e.length&&this.writeMessage(A,w,e)},writePackedSFixed32:function(A,e){e.length&&this.writeMessage(A,p,e)},writePackedFixed64:function(A,e){e.length&&this.writeMessage(A,B,e)},writePackedSFixed64:function(A,e){e.length&&this.writeMessage(A,b,e)},writeBytesField:function(A,e){this.writeTag(A,i.Bytes),this.writeBytes(e)},writeFixed32Field:function(A,e){this.writeTag(A,i.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(A,e){this.writeTag(A,i.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(A,e){this.writeTag(A,i.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(A,e){this.writeTag(A,i.Fixed64),this.writeSFixed64(e)},writeVarintField:function(A,e){this.writeTag(A,i.Varint),this.writeVarint(e)},writeSVarintField:function(A,e){this.writeTag(A,i.Varint),this.writeSVarint(e)},writeStringField:function(A,e){this.writeTag(A,i.Bytes),this.writeString(e)},writeFloatField:function(A,e){this.writeTag(A,i.Fixed32),this.writeFloat(e)},writeDoubleField:function(A,e){this.writeTag(A,i.Fixed64),this.writeDouble(e)},writeBooleanField:function(A,e){this.writeVarintField(A,Boolean(e))}}},{ieee754:8}],10:[function(A,e,r){var t=A("pbf"),i=A("./lib/geojson_wrapper");function n(A){var e=new t;return function(A,e){for(var r in A.layers)e.writeMessage(3,o,A.layers[r])}(A,e),e.finish()}function o(A,e){var r;e.writeVarintField(15,A.version||1),e.writeStringField(1,A.name||""),e.writeVarintField(5,A.extent||4096);var t={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r>31}function l(A,e){for(var r=A.loadGeometry(),t=A.type,i=0,n=0,o=r.length,a=0;anew Promise(((r,t)=>{var i;r((i=e,{type:"FeatureCollection",features:A.cells.map((A=>{const e={properties:A,geometry:{type:i.geometry_type,coordinates:i.generate(A.h3id)}};return i.promoteID||(e.id=parseInt(A.h3id,16)),e}))}))})),a=A=>{const e=["type","data","maxzoom","attribution","buffer","filter","tolerance","cluster","clusterRadius","clusterMaxZoom","clusterMinPoints","clusterProperties","lineMetrics","generateId","promoteId"];return f(A,((A,r)=>e.includes(A)))},f=(A,e)=>Object.fromEntries(Object.entries(A).filter((([A,r])=>e(A,r))));t.Map.prototype.addH3TSource=function(A,e){const r=Object.assign({},n,e,{type:"vector",format:"pbf"});r.generate=A=>"Polygon"===r.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),r.promoteId&&(r.promoteId="h3id"),t.addProtocol("h3tiles",((A,e)=>{const t=`http${!1===r.https?"":"s"}://${A.url.split("://")[1]}`,n=A.url.split(/\/|\./i),a=n.length,f=n.slice(a-4,a-1).map((A=>1*A)),s=new AbortController,u=s.signal;let l;r.timeout>0&&setTimeout((()=>s.abort()),r.timeout),fetch(t,{signal:u}).then((A=>{if(A.ok)return l=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,r))).then((A=>{const t=i.tovt(A).getTile(...f),n={};n[r.sourcelayer]=t;const o=i.topbf.fromGeojsonVt(n,{version:2});r.debug&&console.log(`${f}: ${A.features.length} features, ${(performance.now()-l).toFixed(0)} ms`),e(null,o,null,null)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Tile .../${f.join("/")}.h3t is taking too long to fetch`),e(new Error(A))}))})),this.addSource(A,(A=>{const e=["type","url","tiles","bounds","scheme","minzoom","maxzoom","attribution","promoteId","volatile"];return f(A,((A,r)=>e.includes(A)))})(r))};t.Map.prototype.addH3JSource=function(A,e){const r=new AbortController,t=r.signal,f=Object.assign({},n,e,{type:"geojson"});let s;if(f.generate=A=>"Polygon"===f.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),f.promoteId&&(f.promoteId="h3id"),f.timeout>0&&setTimeout((()=>r.abort()),f.timeout),"string"==typeof f.data)return f.timeout>0&&setTimeout((()=>r.abort()),f.timeout),new Promise(((e,r)=>{fetch(f.data,{signal:t}).then((A=>{if(A.ok)return s=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,f))).then((r=>{f.data=r,this.addSource(A,a(f)),f.debug&&console.log(`${r.features.length} features, ${(performance.now()-s).toFixed(0)} ms`),e(this)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Source file ${f.data} is taking too long to fetch`),console.error(A.message)}))}));o(f.data,f).then((e=>(f.data=e,this.addSource(A,a(f)),new Promise(((A,e)=>A(this))))))};t.Map.prototype.setH3JData=function(A,e,r){const t=Object.assign({},n,r);t.generate=A=>"Polygon"===t.geometry_type?[i.h3.h3ToGeoBoundary(A,!0)]:i.h3.h3ToGeo(A).reverse(),t.promoteId&&(t.promoteId="h3id");const a=new AbortController,f=a.signal,s=this.getSource(A);let u;"string"==typeof e?(t.timeout>0&&setTimeout((()=>a.abort()),t.timeout),fetch(e,{signal:f}).then((A=>{if(A.ok)return u=performance.now(),A.json();throw new Error(A.statusText)})).then((A=>o(A,t))).then((A=>{s.setData(A),t.debug&&console.log(`${A.features.length} features, ${(performance.now()-u).toFixed(0)} ms`)})).catch((A=>{"AbortError"===A.name&&(A.message=`Timeout: Data file ${e} is taking too long to fetch`),console.error(A.message)}))):o(e,t).then((A=>s.setData(A)))}},{"geojson-vt":6,"h3-js":7,"vt-pbf":10}]},{},[12])(12)})); \ No newline at end of file diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css b/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css new file mode 100644 index 0000000..0347a27 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.css @@ -0,0 +1,88 @@ + +/* Override default control style */ +.mapbox-gl-draw_ctrl-bottom-left, +.mapbox-gl-draw_ctrl-top-left { + margin-left:0; + border-radius:0 4px 4px 0; +} +.mapbox-gl-draw_ctrl-top-right, +.mapbox-gl-draw_ctrl-bottom-right { + margin-right:0; + border-radius:4px 0 0 4px; +} + +.mapbox-gl-draw_ctrl-draw-btn { + border-color:rgba(0,0,0,0.9); + color:rgba(255,255,255,0.5); + width:30px; + height:30px; +} + +.mapbox-gl-draw_ctrl-draw-btn.active, +.mapbox-gl-draw_ctrl-draw-btn.active:hover { + background-color:rgb(0 0 0/5%); +} +.mapbox-gl-draw_ctrl-draw-btn { + background-repeat: no-repeat; + background-position: center; +} + +.mapbox-gl-draw_point { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m10 2c-3.3 0-6 2.7-6 6s6 9 6 9 6-5.7 6-9-2.7-6-6-6zm0 2c2.1 0 3.8 1.7 3.8 3.8 0 1.5-1.8 3.9-2.9 5.2h-1.7c-1.1-1.4-2.9-3.8-2.9-5.2-.1-2.1 1.6-3.8 3.7-3.8z"/>%3C/svg>'); +} +.mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m15 12.3v-4.6c.6-.3 1-1 1-1.7 0-1.1-.9-2-2-2-.7 0-1.4.4-1.7 1h-4.6c-.3-.6-1-1-1.7-1-1.1 0-2 .9-2 2 0 .7.4 1.4 1 1.7v4.6c-.6.3-1 1-1 1.7 0 1.1.9 2 2 2 .7 0 1.4-.4 1.7-1h4.6c.3.6 1 1 1.7 1 1.1 0 2-.9 2-2 0-.7-.4-1.4-1-1.7zm-8-.3v-4l1-1h4l1 1v4l-1 1h-4z"/>%3C/svg>'); +} +.mapbox-gl-draw_line { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m13.5 3.5c-1.4 0-2.5 1.1-2.5 2.5 0 .3 0 .6.2.9l-3.8 3.8c-.3-.1-.6-.2-.9-.2-1.4 0-2.5 1.1-2.5 2.5s1.1 2.5 2.5 2.5 2.5-1.1 2.5-2.5c0-.3 0-.6-.2-.9l3.8-3.8c.3.1.6.2.9.2 1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5z"/>%3C/svg>'); +} +.mapbox-gl-draw_trash { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="M10,3.4 c-0.8,0-1.5,0.5-1.8,1.2H5l-1,1v1h12v-1l-1-1h-3.2C11.5,3.9,10.8,3.4,10,3.4z M5,8v7c0,1,1,2,2,2h6c1,0,2-1,2-2V8h-2v5.5h-1.5V8h-3 v5.5H7V8H5z"/>%3C/svg>'); +} +.mapbox-gl-draw_uncombine { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m12 2c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l1 1c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-1-1c-.2-.2-.4-.3-.7-.3zm4 4c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l1 1c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-1-1c-.2-.2-.4-.3-.7-.3zm-7 1c-1 0-1 1-.5 1.5.3.3 1 1 1 1l-1 1s-.5.5 0 1 1 0 1 0l1-1 1 1c.5.5 1.5.5 1.5-.5v-4zm-5 3c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l4.9 4.9c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-4.9-4.9c-.1-.2-.4-.3-.7-.3z"/>%3C/svg>'); +} +.mapbox-gl-draw_combine { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="M12.1,2c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l4.9,4.9c0.4,0.4,1,0.4,1.4,0l1-1 c0.4-0.4,0.4-1,0-1.4l-4.9-4.9C12.6,2.1,12.3,2,12.1,2z M8,8C7,8,7,9,7.5,9.5c0.3,0.3,1,1,1,1l-1,1c0,0-0.5,0.5,0,1s1,0,1,0l1-1l1,1 C11,13,12,13,12,12V8H8z M4,10c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l1,1c0.4,0.4,1,0.4,1.4,0l1-1c0.4-0.4,0.4-1,0-1.4 l-1-1C4.5,10.1,4.3,10,4,10z M8,14c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l1,1c0.4,0.4,1,0.4,1.4,0l1-1 c0.4-0.4,0.4-1,0-1.4l-1-1C8.5,14.1,8.3,14,8,14z"/>%3C/svg>'); +} + +.mapboxgl-map.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: pointer; +} +.mapboxgl-map.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mouse-add .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: crosshair; +} +.mapboxgl-map.mouse-move.mode-direct_select .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: grab; + cursor: -moz-grab; + cursor: -webkit-grab; +} +.mapboxgl-map.mode-direct_select.feature-vertex.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mode-direct_select.feature-midpoint.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: cell; +} +.mapboxgl-map.mode-direct_select.feature-feature.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mode-static.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: grab; + cursor: -moz-grab; + cursor: -webkit-grab; +} + +.mapbox-gl-draw_boxselect { + pointer-events: none; + position: absolute; + top: 0; + left: 0; + width: 0; + height: 0; + background: rgba(0,0,0,.1); + border: 2px dotted #fff; + opacity: 0.5; +} diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js new file mode 100644 index 0000000..271f1f7 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-gl-draw/mapbox-gl-draw.js @@ -0,0 +1,2 @@ +var e,t;e=this,t=function(){const e=function(e,t){const o={drag:[],click:[],mousemove:[],mousedown:[],mouseup:[],mouseout:[],keydown:[],keyup:[],touchstart:[],touchmove:[],touchend:[],tap:[]},n={on(e,t,n){if(void 0===o[e])throw new Error(`Invalid event type: ${e}`);o[e].push({selector:t,fn:n})},render(e){t.store.featureChanged(e)}},r=function(e,r){const i=o[e];let s=i.length;for(;s--;){const e=i[s];if(e.selector(r)){e.fn.call(n,r)||t.store.render(),t.ui.updateMapClasses();break}}};return e.start.call(n),{render:e.render,stop(){e.stop&&e.stop()},trash(){e.trash&&(e.trash(),t.store.render())},combineFeatures(){e.combineFeatures&&e.combineFeatures()},uncombineFeatures(){e.uncombineFeatures&&e.uncombineFeatures()},drag(e){r("drag",e)},click(e){r("click",e)},mousemove(e){r("mousemove",e)},mousedown(e){r("mousedown",e)},mouseup(e){r("mouseup",e)},mouseout(e){r("mouseout",e)},keydown(e){r("keydown",e)},keyup(e){r("keyup",e)},touchstart(e){r("touchstart",e)},touchmove(e){r("touchmove",e)},touchend(e){r("touchend",e)},tap(e){r("tap",e)}}};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var o,n,r={},i={};function s(){return o||(o=1,i.RADIUS=6378137,i.FLATTENING=1/298.257223563,i.POLAR_RADIUS=6356752.3142),i}var a=function(){if(n)return r;n=1;var e=s();function t(e){var t=0;if(e&&e.length>0){t+=Math.abs(o(e[0]));for(var n=1;n2){for(c=0;c(e.geometry.type===h.POLYGON&&(e.area=c.geometry({type:h.FEATURE,property:{},geometry:e.geometry})),e))).sort(S).map((e=>(delete e.area,e)))}function L(e,t=0){return[[e.point.x-t,e.point.y-t],[e.point.x+t,e.point.y+t]]}function M(e){if(this._items={},this._nums={},this._length=e?e.length:0,e)for(let t=0,o=e.length;t{e.push({k:t,v:this._items[t]})})),Object.keys(this._nums).forEach((t=>{e.push({k:JSON.parse(t),v:this._nums[t]})})),e.sort(((e,t)=>e.v-t.v)).map((e=>e.k))},M.prototype.clear=function(){return this._length=0,this._items={},this._nums={},this};const N=[y.FEATURE,y.MIDPOINT,y.VERTEX];var b={click:function(e,t,o){return x(e,t,o,o.options.clickBuffer)},touch:function(e,t,o){return x(e,t,o,o.options.touchBuffer)}};function x(e,t,o,n){if(null===o.map)return[];const r=e?L(e,n):t,i={};o.options.styles&&(i.layers=o.options.styles.map((e=>e.id)).filter((e=>null!=o.map.getLayer(e))));const s=o.map.queryRenderedFeatures(r,i).filter((e=>-1!==N.indexOf(e.properties.meta))),a=new M,c=[];return s.forEach((e=>{const t=e.properties.id;a.has(t)||(a.add(t),c.push(e))})),O(c)}function A(e,t){const o=b.click(e,null,t),n={mouse:d.NONE};return o[0]&&(n.mouse=o[0].properties.active===E.ACTIVE?d.MOVE:d.POINTER,n.feature=o[0].properties.meta),-1!==t.events.currentModeName().indexOf("draw")&&(n.mouse=d.ADD),t.ui.queueMapClasses(n),t.ui.updateMapClasses(),o[0]}function P(e,t){const o=e.x-t.x,n=e.y-t.y;return Math.sqrt(o*o+n*n)}const F=4,R=12,w=500;function D(e,t,o={}){const n=null!=o.fineTolerance?o.fineTolerance:F,r=null!=o.grossTolerance?o.grossTolerance:R,i=null!=o.interval?o.interval:w;e.point=e.point||t.point,e.time=e.time||t.time;const s=P(e.point,t.point);return s(o=t)=>{let n="",r=0|o;for(;r--;)n+=e[Math.random()*e.length|0];return n})("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",32);function B(){return G()}const j=function(e,t){this.ctx=e,this.properties=t.properties||{},this.coordinates=t.geometry.coordinates,this.id=t.id||B(),this.type=t.geometry.type};j.prototype.changed=function(){this.ctx.store.featureChanged(this.id)},j.prototype.incomingCoords=function(e){this.setCoordinates(e)},j.prototype.setCoordinates=function(e){this.coordinates=e,this.changed()},j.prototype.getCoordinates=function(){return JSON.parse(JSON.stringify(this.coordinates))},j.prototype.setProperty=function(e,t){this.properties[e]=t},j.prototype.toGeoJSON=function(){return JSON.parse(JSON.stringify({id:this.id,type:h.FEATURE,properties:this.properties,geometry:{coordinates:this.getCoordinates(),type:this.type}}))},j.prototype.internal=function(e){const t={id:this.id,meta:y.FEATURE,"meta:type":this.type,active:E.INACTIVE,mode:e};if(this.ctx.options.userProperties)for(const e in this.properties)t[`user_${e}`]=this.properties[e];return{type:h.FEATURE,properties:t,geometry:{coordinates:this.getCoordinates(),type:this.type}}};const J=function(e,t){j.call(this,e,t)};(J.prototype=Object.create(j.prototype)).isValid=function(){return"number"==typeof this.coordinates[0]&&"number"==typeof this.coordinates[1]},J.prototype.updateCoordinate=function(e,t,o){this.coordinates=3===arguments.length?[t,o]:[e,t],this.changed()},J.prototype.getCoordinate=function(){return this.getCoordinates()};const $=function(e,t){j.call(this,e,t)};($.prototype=Object.create(j.prototype)).isValid=function(){return this.coordinates.length>1},$.prototype.addCoordinate=function(e,t,o){this.changed();const n=parseInt(e,10);this.coordinates.splice(n,0,[t,o])},$.prototype.getCoordinate=function(e){const t=parseInt(e,10);return JSON.parse(JSON.stringify(this.coordinates[t]))},$.prototype.removeCoordinate=function(e){this.changed(),this.coordinates.splice(parseInt(e,10),1)},$.prototype.updateCoordinate=function(e,t,o){const n=parseInt(e,10);this.coordinates[n]=[t,o],this.changed()};const Y=function(e,t){j.call(this,e,t),this.coordinates=this.coordinates.map((e=>e.slice(0,-1)))};(Y.prototype=Object.create(j.prototype)).isValid=function(){return 0!==this.coordinates.length&&this.coordinates.every((e=>e.length>2))},Y.prototype.incomingCoords=function(e){this.coordinates=e.map((e=>e.slice(0,-1))),this.changed()},Y.prototype.setCoordinates=function(e){this.coordinates=e,this.changed()},Y.prototype.addCoordinate=function(e,t,o){this.changed();const n=e.split(".").map((e=>parseInt(e,10)));this.coordinates[n[0]].splice(n[1],0,[t,o])},Y.prototype.removeCoordinate=function(e){this.changed();const t=e.split(".").map((e=>parseInt(e,10))),o=this.coordinates[t[0]];o&&(o.splice(t[1],1),o.length<3&&this.coordinates.splice(t[0],1))},Y.prototype.getCoordinate=function(e){const t=e.split(".").map((e=>parseInt(e,10))),o=this.coordinates[t[0]];return JSON.parse(JSON.stringify(o[t[1]]))},Y.prototype.getCoordinates=function(){return this.coordinates.map((e=>e.concat([e[0]])))},Y.prototype.updateCoordinate=function(e,t,o){this.changed();const n=e.split("."),r=parseInt(n[0],10),i=parseInt(n[1],10);void 0===this.coordinates[r]&&(this.coordinates[r]=[]),this.coordinates[r][i]=[t,o]};const H={MultiPoint:J,MultiLineString:$,MultiPolygon:Y},X=(e,t,o,n,r)=>{const i=o.split("."),s=parseInt(i[0],10),a=i[1]?i.slice(1).join("."):null;return e[s][t](a,n,r)},q=function(e,t){if(j.call(this,e,t),delete this.coordinates,this.model=H[t.geometry.type],void 0===this.model)throw new TypeError(`${t.geometry.type} is not a valid type`);this.features=this._coordinatesToFeatures(t.geometry.coordinates)};function Z(e){this.map=e.map,this.drawConfig=JSON.parse(JSON.stringify(e.options||{})),this._ctx=e}(q.prototype=Object.create(j.prototype))._coordinatesToFeatures=function(e){const t=this.model.bind(this);return e.map((e=>new t(this.ctx,{id:B(),type:h.FEATURE,properties:{},geometry:{coordinates:e,type:this.type.replace("Multi","")}})))},q.prototype.isValid=function(){return this.features.every((e=>e.isValid()))},q.prototype.setCoordinates=function(e){this.features=this._coordinatesToFeatures(e),this.changed()},q.prototype.getCoordinate=function(e){return X(this.features,"getCoordinate",e)},q.prototype.getCoordinates=function(){return JSON.parse(JSON.stringify(this.features.map((e=>e.type===h.POLYGON?e.getCoordinates():e.coordinates))))},q.prototype.updateCoordinate=function(e,t,o){X(this.features,"updateCoordinate",e,t,o),this.changed()},q.prototype.addCoordinate=function(e,t,o){X(this.features,"addCoordinate",e,t,o),this.changed()},q.prototype.removeCoordinate=function(e){X(this.features,"removeCoordinate",e),this.changed()},q.prototype.getFeatures=function(){return this.features},Z.prototype.setSelected=function(e){return this._ctx.store.setSelected(e)},Z.prototype.setSelectedCoordinates=function(e){this._ctx.store.setSelectedCoordinates(e),e.reduce(((e,t)=>(void 0===e[t.feature_id]&&(e[t.feature_id]=!0,this._ctx.store.get(t.feature_id).changed()),e)),{})},Z.prototype.getSelected=function(){return this._ctx.store.getSelected()},Z.prototype.getSelectedIds=function(){return this._ctx.store.getSelectedIds()},Z.prototype.isSelected=function(e){return this._ctx.store.isSelected(e)},Z.prototype.getFeature=function(e){return this._ctx.store.get(e)},Z.prototype.select=function(e){return this._ctx.store.select(e)},Z.prototype.deselect=function(e){return this._ctx.store.deselect(e)},Z.prototype.deleteFeature=function(e,t={}){return this._ctx.store.delete(e,t)},Z.prototype.addFeature=function(e,t={}){return this._ctx.store.add(e,t)},Z.prototype.clearSelectedFeatures=function(){return this._ctx.store.clearSelected()},Z.prototype.clearSelectedCoordinates=function(){return this._ctx.store.clearSelectedCoordinates()},Z.prototype.setActionableState=function(e={}){const t={trash:e.trash||!1,combineFeatures:e.combineFeatures||!1,uncombineFeatures:e.uncombineFeatures||!1};return this._ctx.events.actionable(t)},Z.prototype.changeMode=function(e,t={},o={}){return this._ctx.events.changeMode(e,t,o)},Z.prototype.fire=function(e,t){return this._ctx.events.fire(e,t)},Z.prototype.updateUIClasses=function(e){return this._ctx.ui.queueMapClasses(e)},Z.prototype.activateUIButton=function(e){return this._ctx.ui.setActiveButton(e)},Z.prototype.featuresAt=function(e,t,o="click"){if("click"!==o&&"touch"!==o)throw new Error("invalid buffer type");return b[o](e,t,this._ctx)},Z.prototype.newFeature=function(e){const t=e.geometry.type;return t===h.POINT?new J(this._ctx,e):t===h.LINE_STRING?new $(this._ctx,e):t===h.POLYGON?new Y(this._ctx,e):new q(this._ctx,e)},Z.prototype.isInstanceOf=function(e,t){if(e===h.POINT)return t instanceof J;if(e===h.LINE_STRING)return t instanceof $;if(e===h.POLYGON)return t instanceof Y;if("MultiFeature"===e)return t instanceof q;throw new Error(`Unknown feature class: ${e}`)},Z.prototype.doRender=function(e){return this._ctx.store.featureChanged(e)},Z.prototype.onSetup=function(){},Z.prototype.onDrag=function(){},Z.prototype.onClick=function(){},Z.prototype.onMouseMove=function(){},Z.prototype.onMouseDown=function(){},Z.prototype.onMouseUp=function(){},Z.prototype.onMouseOut=function(){},Z.prototype.onKeyUp=function(){},Z.prototype.onKeyDown=function(){},Z.prototype.onTouchStart=function(){},Z.prototype.onTouchMove=function(){},Z.prototype.onTouchEnd=function(){},Z.prototype.onTap=function(){},Z.prototype.onStop=function(){},Z.prototype.onTrash=function(){},Z.prototype.onCombineFeature=function(){},Z.prototype.onUncombineFeature=function(){},Z.prototype.toDisplayFeatures=function(){throw new Error("You must overwrite toDisplayFeatures")};const W={drag:"onDrag",click:"onClick",mousemove:"onMouseMove",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseout:"onMouseOut",keyup:"onKeyUp",keydown:"onKeyDown",touchstart:"onTouchStart",touchmove:"onTouchMove",touchend:"onTouchEnd",tap:"onTap"},K=Object.keys(W);function z(e){const t=Object.keys(e);return function(o,n={}){let r={};const i=t.reduce(((t,o)=>(t[o]=e[o],t)),new Z(o));return{start(){r=i.onSetup(n),K.forEach((t=>{const o=W[t];let n=()=>!1;var s;e[o]&&(n=()=>!0),this.on(t,n,(s=o,e=>i[s](r,e)))}))},stop(){i.onStop(r)},trash(){i.onTrash(r)},combineFeatures(){i.onCombineFeatures(r)},uncombineFeatures(){i.onUncombineFeatures(r)},render(e,t){i.toDisplayFeatures(r,e,t)}}}}function Q(e){return[].concat(e).filter((e=>void 0!==e))}function ee(){const e=this;if(!e.ctx.map||void 0===e.ctx.map.getSource(l.HOT))return a();const t=e.ctx.events.currentModeName();e.ctx.ui.queueMapClasses({mode:t});let o=[],n=[];e.isDirty?n=e.getAllIds():(o=e.getChangedIds().filter((t=>void 0!==e.get(t))),n=e.sources.hot.filter((t=>t.properties.id&&-1===o.indexOf(t.properties.id)&&void 0!==e.get(t.properties.id))).map((e=>e.properties.id))),e.sources.hot=[];const r=e.sources.cold.length;e.sources.cold=e.isDirty?[]:e.sources.cold.filter((e=>{const t=e.properties.id||e.properties.parent;return-1===o.indexOf(t)}));const i=r!==e.sources.cold.length||n.length>0;function s(o,n){const r=e.get(o).internal(t);e.ctx.events.currentModeRender(r,(o=>{o.properties.mode=t,e.sources[n].push(o)}))}function a(){e.isDirty=!1,e.clearChangedIds()}o.forEach((e=>s(e,"hot"))),n.forEach((e=>s(e,"cold"))),i&&e.ctx.map.getSource(l.COLD).setData({type:h.FEATURE_COLLECTION,features:e.sources.cold}),e.ctx.map.getSource(l.HOT).setData({type:h.FEATURE_COLLECTION,features:e.sources.hot}),a()}function te(e){let t;this._features={},this._featureIds=new M,this._selectedFeatureIds=new M,this._selectedCoordinates=[],this._changedFeatureIds=new M,this._emitSelectionChange=!1,this._mapInitialConfig={},this.ctx=e,this.sources={hot:[],cold:[]},this.render=()=>{t||(t=requestAnimationFrame((()=>{t=null,ee.call(this),this._emitSelectionChange&&(this.ctx.events.fire(g.SELECTION_CHANGE,{features:this.getSelected().map((e=>e.toGeoJSON())),points:this.getSelectedCoordinates().map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e.coordinates}})))}),this._emitSelectionChange=!1),this.ctx.events.fire(g.RENDER,{})})))},this.isDirty=!1}function oe(e,t={}){const o=e._selectedCoordinates.filter((t=>e._selectedFeatureIds.has(t.feature_id)));e._selectedCoordinates.length===o.length||t.silent||(e._emitSelectionChange=!0),e._selectedCoordinates=o}te.prototype.createRenderBatch=function(){const e=this.render;let t=0;return this.render=function(){t++},()=>{this.render=e,t>0&&this.render()}},te.prototype.setDirty=function(){return this.isDirty=!0,this},te.prototype.featureCreated=function(e,t={}){if(this._changedFeatureIds.add(e),!0!==(null!=t.silent?t.silent:this.ctx.options.suppressAPIEvents)){const t=this.get(e);this.ctx.events.fire(g.CREATE,{features:[t.toGeoJSON()]})}return this},te.prototype.featureChanged=function(e,t={}){return this._changedFeatureIds.add(e),!0!==(null!=t.silent?t.silent:this.ctx.options.suppressAPIEvents)&&this.ctx.events.fire(g.UPDATE,{action:t.action?t.action:m.CHANGE_COORDINATES,features:[this.get(e).toGeoJSON()]}),this},te.prototype.getChangedIds=function(){return this._changedFeatureIds.values()},te.prototype.clearChangedIds=function(){return this._changedFeatureIds.clear(),this},te.prototype.getAllIds=function(){return this._featureIds.values()},te.prototype.add=function(e,t={}){return this._features[e.id]=e,this._featureIds.add(e.id),this.featureCreated(e.id,{silent:t.silent}),this},te.prototype.delete=function(e,t={}){const o=[];return Q(e).forEach((e=>{this._featureIds.has(e)&&(this._featureIds.delete(e),this._selectedFeatureIds.delete(e),t.silent||-1===o.indexOf(this._features[e])&&o.push(this._features[e].toGeoJSON()),delete this._features[e],this.isDirty=!0)})),o.length&&this.ctx.events.fire(g.DELETE,{features:o}),oe(this,t),this},te.prototype.get=function(e){return this._features[e]},te.prototype.getAll=function(){return Object.keys(this._features).map((e=>this._features[e]))},te.prototype.select=function(e,t={}){return Q(e).forEach((e=>{this._selectedFeatureIds.has(e)||(this._selectedFeatureIds.add(e),this._changedFeatureIds.add(e),t.silent||(this._emitSelectionChange=!0))})),this},te.prototype.deselect=function(e,t={}){return Q(e).forEach((e=>{this._selectedFeatureIds.has(e)&&(this._selectedFeatureIds.delete(e),this._changedFeatureIds.add(e),t.silent||(this._emitSelectionChange=!0))})),oe(this,t),this},te.prototype.clearSelected=function(e={}){return this.deselect(this._selectedFeatureIds.values(),{silent:e.silent}),this},te.prototype.setSelected=function(e,t={}){return e=Q(e),this.deselect(this._selectedFeatureIds.values().filter((t=>-1===e.indexOf(t))),{silent:t.silent}),this.select(e.filter((e=>!this._selectedFeatureIds.has(e))),{silent:t.silent}),this},te.prototype.setSelectedCoordinates=function(e){return this._selectedCoordinates=e,this._emitSelectionChange=!0,this},te.prototype.clearSelectedCoordinates=function(){return this._selectedCoordinates=[],this._emitSelectionChange=!0,this},te.prototype.getSelectedIds=function(){return this._selectedFeatureIds.values()},te.prototype.getSelected=function(){return this.getSelectedIds().map((e=>this.get(e)))},te.prototype.getSelectedCoordinates=function(){return this._selectedCoordinates.map((e=>({coordinates:this.get(e.feature_id).getCoordinate(e.coord_path)})))},te.prototype.isSelected=function(e){return this._selectedFeatureIds.has(e)},te.prototype.setFeatureProperty=function(e,t,o,n={}){this.get(e).setProperty(t,o),this.featureChanged(e,{silent:n.silent,action:m.CHANGE_PROPERTIES})},te.prototype.storeMapConfig=function(){T.forEach((e=>{this.ctx.map[e]&&(this._mapInitialConfig[e]=this.ctx.map[e].isEnabled())}))},te.prototype.restoreMapConfig=function(){Object.keys(this._mapInitialConfig).forEach((e=>{this._mapInitialConfig[e]?this.ctx.map[e].enable():this.ctx.map[e].disable()}))},te.prototype.getInitialConfigValue=function(e){return void 0===this._mapInitialConfig[e]||this._mapInitialConfig[e]};const ne=["mode","feature","mouse"];function re(t){let o=null,n=null;const r={onRemove(){return t.map.off("load",r.connect),clearInterval(n),r.removeLayers(),t.store.restoreMapConfig(),t.ui.removeButtons(),t.events.removeEventListeners(),t.ui.clearMapClasses(),t.boxZoomInitial&&t.map.boxZoom.enable(),t.map=null,t.container=null,t.store=null,o&&o.parentNode&&o.parentNode.removeChild(o),o=null,this},connect(){t.map.off("load",r.connect),clearInterval(n),r.addLayers(),t.store.storeMapConfig(),t.events.addEventListeners()},onAdd(i){if(t.map=i,t.events=function(t){const o=Object.keys(t.options.modes).reduce(((e,o)=>(e[o]=z(t.options.modes[o]),e)),{});let n={},r={};const i={};let s=null,a=null;i.drag=function(e,o){o({point:e.point,time:(new Date).getTime()})?(t.ui.queueMapClasses({mouse:d.DRAG}),a.drag(e)):e.originalEvent.stopPropagation()},i.mousedrag=function(e){i.drag(e,(e=>!D(n,e)))},i.touchdrag=function(e){i.drag(e,(e=>!V(r,e)))},i.mousemove=function(e){if(1===(void 0!==e.originalEvent.buttons?e.originalEvent.buttons:e.originalEvent.which))return i.mousedrag(e);const o=A(e,t);e.featureTarget=o,a.mousemove(e)},i.mousedown=function(e){n={time:(new Date).getTime(),point:e.point};const o=A(e,t);e.featureTarget=o,a.mousedown(e)},i.mouseup=function(e){const o=A(e,t);e.featureTarget=o,D(n,{point:e.point,time:(new Date).getTime()})?a.click(e):a.mouseup(e)},i.mouseout=function(e){a.mouseout(e)},i.touchstart=function(e){if(!t.options.touchEnabled)return;r={time:(new Date).getTime(),point:e.point};const o=b.touch(e,null,t)[0];e.featureTarget=o,a.touchstart(e)},i.touchmove=function(e){if(t.options.touchEnabled)return a.touchmove(e),i.touchdrag(e)},i.touchend=function(e){if(e.originalEvent.preventDefault(),!t.options.touchEnabled)return;const o=b.touch(e,null,t)[0];e.featureTarget=o,V(r,{time:(new Date).getTime(),point:e.point})?a.tap(e):a.touchend(e)};const c=e=>!(8===e||46===e||e>=48&&e<=57);function l(n,r,i={}){a.stop();const c=o[n];if(void 0===c)throw new Error(`${n} is not valid`);s=n;const u=c(t,r);a=e(u,t),i.silent||t.map.fire(g.MODE_CHANGE,{mode:n}),t.store.setDirty(),t.store.render()}i.keydown=function(e){(e.srcElement||e.target).classList.contains(u.CANVAS)&&(8!==e.keyCode&&46!==e.keyCode||!t.options.controls.trash?c(e.keyCode)?a.keydown(e):49===e.keyCode&&t.options.controls.point?l(f.DRAW_POINT):50===e.keyCode&&t.options.controls.line_string?l(f.DRAW_LINE_STRING):51===e.keyCode&&t.options.controls.polygon&&l(f.DRAW_POLYGON):(e.preventDefault(),a.trash()))},i.keyup=function(e){c(e.keyCode)&&a.keyup(e)},i.zoomend=function(){t.store.changeZoom()},i.data=function(e){if("style"===e.dataType){const{setup:e,map:o,options:n,store:r}=t;n.styles.some((e=>o.getLayer(e.id)))||(e.addLayers(),r.setDirty(),r.render())}};const p={trash:!1,combineFeatures:!1,uncombineFeatures:!1};return{start(){s=t.options.defaultMode,a=e(o[s](t),t)},changeMode:l,actionable:function(e){let o=!1;Object.keys(e).forEach((t=>{if(void 0===p[t])throw new Error("Invalid action type");p[t]!==e[t]&&(o=!0),p[t]=e[t]})),o&&t.map.fire(g.ACTIONABLE,{actions:p})},currentModeName:()=>s,currentModeRender:(e,t)=>a.render(e,t),fire(e,o){t.map&&t.map.fire(e,o)},addEventListeners(){t.map.on("mousemove",i.mousemove),t.map.on("mousedown",i.mousedown),t.map.on("mouseup",i.mouseup),t.map.on("data",i.data),t.map.on("touchmove",i.touchmove),t.map.on("touchstart",i.touchstart),t.map.on("touchend",i.touchend),t.container.addEventListener("mouseout",i.mouseout),t.options.keybindings&&(t.container.addEventListener("keydown",i.keydown),t.container.addEventListener("keyup",i.keyup))},removeEventListeners(){t.map.off("mousemove",i.mousemove),t.map.off("mousedown",i.mousedown),t.map.off("mouseup",i.mouseup),t.map.off("data",i.data),t.map.off("touchmove",i.touchmove),t.map.off("touchstart",i.touchstart),t.map.off("touchend",i.touchend),t.container.removeEventListener("mouseout",i.mouseout),t.options.keybindings&&(t.container.removeEventListener("keydown",i.keydown),t.container.removeEventListener("keyup",i.keyup))},trash(e){a.trash(e)},combineFeatures(){a.combineFeatures()},uncombineFeatures(){a.uncombineFeatures()},getMode:()=>s}}(t),t.ui=function(e){const t={};let o=null,n={mode:null,feature:null,mouse:null},r={mode:null,feature:null,mouse:null};function i(e){r=Object.assign(r,e)}function s(){if(!e.container)return;const t=[],o=[];ne.forEach((e=>{r[e]!==n[e]&&(t.push(`${e}-${n[e]}`),null!==r[e]&&o.push(`${e}-${r[e]}`))})),t.length>0&&e.container.classList.remove(...t),o.length>0&&e.container.classList.add(...o),n=Object.assign(n,r)}function a(e,t={}){const n=document.createElement("button");return n.className=`${u.CONTROL_BUTTON} ${t.className}`,n.setAttribute("title",t.title),t.container.appendChild(n),n.addEventListener("click",(n=>{if(n.preventDefault(),n.stopPropagation(),n.target===o)return c(),void t.onDeactivate();l(e),t.onActivate()}),!0),n}function c(){o&&(o.classList.remove(u.ACTIVE_BUTTON),o=null)}function l(e){c();const n=t[e];n&&n&&"trash"!==e&&(n.classList.add(u.ACTIVE_BUTTON),o=n)}return{setActiveButton:l,queueMapClasses:i,updateMapClasses:s,clearMapClasses:function(){i({mode:null,feature:null,mouse:null}),s()},addButtons:function(){const o=e.options.controls,n=document.createElement("div");return n.className=`${u.CONTROL_GROUP} ${u.CONTROL_BASE}`,o?(o[p.LINE]&&(t[p.LINE]=a(p.LINE,{container:n,className:u.CONTROL_BUTTON_LINE,title:"LineString tool "+(e.options.keybindings?"(l)":""),onActivate:()=>e.events.changeMode(f.DRAW_LINE_STRING),onDeactivate:()=>e.events.trash()})),o[p.POLYGON]&&(t[p.POLYGON]=a(p.POLYGON,{container:n,className:u.CONTROL_BUTTON_POLYGON,title:"Polygon tool "+(e.options.keybindings?"(p)":""),onActivate:()=>e.events.changeMode(f.DRAW_POLYGON),onDeactivate:()=>e.events.trash()})),o[p.POINT]&&(t[p.POINT]=a(p.POINT,{container:n,className:u.CONTROL_BUTTON_POINT,title:"Marker tool "+(e.options.keybindings?"(m)":""),onActivate:()=>e.events.changeMode(f.DRAW_POINT),onDeactivate:()=>e.events.trash()})),o.trash&&(t.trash=a("trash",{container:n,className:u.CONTROL_BUTTON_TRASH,title:"Delete",onActivate:()=>{e.events.trash()}})),o.combine_features&&(t.combine_features=a("combineFeatures",{container:n,className:u.CONTROL_BUTTON_COMBINE_FEATURES,title:"Combine",onActivate:()=>{e.events.combineFeatures()}})),o.uncombine_features&&(t.uncombine_features=a("uncombineFeatures",{container:n,className:u.CONTROL_BUTTON_UNCOMBINE_FEATURES,title:"Uncombine",onActivate:()=>{e.events.uncombineFeatures()}})),n):n},removeButtons:function(){Object.keys(t).forEach((e=>{const o=t[e];o.parentNode&&o.parentNode.removeChild(o),delete t[e]}))}}}(t),t.container=i.getContainer(),t.store=new te(t),o=t.ui.addButtons(),t.options.boxSelect){t.boxZoomInitial=i.boxZoom.isEnabled(),i.boxZoom.disable();const e=i.dragPan.isEnabled();i.dragPan.disable(),i.dragPan.enable(),e||i.dragPan.disable()}return i.loaded()?r.connect():(i.on("load",r.connect),n=setInterval((()=>{i.loaded()&&r.connect()}),16)),t.events.start(),o},addLayers(){t.map.addSource(l.COLD,{data:{type:h.FEATURE_COLLECTION,features:[]},type:"geojson"}),t.map.addSource(l.HOT,{data:{type:h.FEATURE_COLLECTION,features:[]},type:"geojson"}),t.options.styles.forEach((e=>{t.map.addLayer(e)})),t.store.setDirty(!0),t.store.render()},removeLayers(){t.options.styles.forEach((e=>{t.map.getLayer(e.id)&&t.map.removeLayer(e.id)})),t.map.getSource(l.COLD)&&t.map.removeSource(l.COLD),t.map.getSource(l.HOT)&&t.map.removeSource(l.HOT)}};return t.setup=r,r}const ie="#3bb2d0",se="#fbb03b",ae="#fff";var ce=[{id:"gl-draw-polygon-fill",type:"fill",filter:["all",["==","$type","Polygon"]],paint:{"fill-color":["case",["==",["get","active"],"true"],se,ie],"fill-opacity":.1}},{id:"gl-draw-lines",type:"line",filter:["any",["==","$type","LineString"],["==","$type","Polygon"]],layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":["case",["==",["get","active"],"true"],se,ie],"line-dasharray":["case",["==",["get","active"],"true"],[.2,2],[2,0]],"line-width":2}},{id:"gl-draw-point-outer",type:"circle",filter:["all",["==","$type","Point"],["==","meta","feature"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],7,5],"circle-color":ae}},{id:"gl-draw-point-inner",type:"circle",filter:["all",["==","$type","Point"],["==","meta","feature"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],5,3],"circle-color":["case",["==",["get","active"],"true"],se,ie]}},{id:"gl-draw-vertex-outer",type:"circle",filter:["all",["==","$type","Point"],["==","meta","vertex"],["!=","mode","simple_select"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],7,5],"circle-color":ae}},{id:"gl-draw-vertex-inner",type:"circle",filter:["all",["==","$type","Point"],["==","meta","vertex"],["!=","mode","simple_select"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],5,3],"circle-color":se}},{id:"gl-draw-midpoint",type:"circle",filter:["all",["==","meta","midpoint"]],paint:{"circle-radius":3,"circle-color":se}}];function ue(e){return function(t){const o=t.featureTarget;return!!o&&!!o.properties&&o.properties.meta===e}}function le(e){return!!e.originalEvent&&!!e.originalEvent.shiftKey&&0===e.originalEvent.button}function de(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.active===E.ACTIVE&&e.featureTarget.properties.meta===y.FEATURE}function pe(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.active===E.INACTIVE&&e.featureTarget.properties.meta===y.FEATURE}function he(e){return void 0===e.featureTarget}function fe(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.meta===y.FEATURE}function ge(e){const t=e.featureTarget;return!!t&&!!t.properties&&t.properties.meta===y.VERTEX}function me(e){return!!e.originalEvent&&!0===e.originalEvent.shiftKey}function ye(e){return 27===e.keyCode}function Ee(e){return 13===e.keyCode}var Te=Object.freeze({__proto__:null,isActiveFeature:de,isEnterKey:Ee,isEscapeKey:ye,isFeature:fe,isInactiveFeature:pe,isOfMetaType:ue,isShiftDown:me,isShiftMousedown:le,isTrue:function(){return!0},isVertex:ge,noTarget:he});function Ce(e,t){this.x=e,this.y=t}function _e(e,t){const o=t.getBoundingClientRect();return new Ce(e.clientX-o.left-(t.clientLeft||0),e.clientY-o.top-(t.clientTop||0))}function ve(e,t,o,n){return{type:h.FEATURE,properties:{meta:y.VERTEX,parent:e,coord_path:o,active:n?E.ACTIVE:E.INACTIVE},geometry:{type:h.POINT,coordinates:t}}}function Ie(e,t,o){const n=t.geometry.coordinates,r=o.geometry.coordinates;if(n[1]>_||n[1]_||r[1]{const u=null!=o?`${o}.${a}`:String(a),l=ve(i,e,u,c(u));if(t.midpoints&&r){const e=Ie(i,r,l);e&&s.push(e)}r=l;const d=JSON.stringify(e);n!==d&&s.push(l),0===a&&(n=d)}))}function c(e){return!!t.selectedPaths&&-1!==t.selectedPaths.indexOf(e)}return n===h.POINT?s.push(ve(i,r,o,c(o))):n===h.POLYGON?r.forEach(((e,t)=>{a(e,null!==o?`${o}.${t}`:String(t))})):n===h.LINE_STRING?a(r,o):0===n.indexOf(h.MULTI_PREFIX)&&function(){const o=n.replace(h.MULTI_PREFIX,"");r.forEach(((n,r)=>{const i={type:h.FEATURE,properties:e.properties,geometry:{type:o,coordinates:n}};s=s.concat(Se(i,t,r))}))}(),s}Ce.prototype={clone(){return new Ce(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){const t=e.x-this.x,o=e.y-this.y;return t*t+o*o},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){const t=e[0]*this.x+e[1]*this.y,o=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=o,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){const e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){const t=Math.cos(e),o=Math.sin(e),n=t*this.x-o*this.y,r=o*this.x+t*this.y;return this.x=n,this.y=r,this},_rotateAround(e,t){const o=Math.cos(e),n=Math.sin(e),r=t.x+o*(this.x-t.x)-n*(this.y-t.y),i=t.y+n*(this.x-t.x)+o*(this.y-t.y);return this.x=r,this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:Ce},Ce.convert=function(e){if(e instanceof Ce)return e;if(Array.isArray(e))return new Ce(+e[0],+e[1]);if(void 0!==e.x&&void 0!==e.y)return new Ce(+e.x,+e.y);throw new Error("Expected [x, y] or {x, y} point format")};var Oe={enable(e){setTimeout((()=>{e.map&&e.map.doubleClickZoom&&e._ctx&&e._ctx.store&&e._ctx.store.getInitialConfigValue&&e._ctx.store.getInitialConfigValue("doubleClickZoom")&&e.map.doubleClickZoom.enable()}),0)},disable(e){setTimeout((()=>{e.map&&e.map.doubleClickZoom&&e.map.doubleClickZoom.disable()}),0)}};const{LAT_MIN:Le,LAT_MAX:Me,LAT_RENDERED_MIN:Ne,LAT_RENDERED_MAX:be,LNG_MIN:xe,LNG_MAX:Ae}=v;function Pe(e,t){let o=Le,n=Me,r=Le,i=Me,s=Ae,a=xe;e.forEach((e=>{const t=function(e){const t={Point:0,LineString:1,Polygon:2,MultiPoint:1,MultiLineString:2,MultiPolygon:3}[e.geometry.type],o=[e.geometry.coordinates].flat(t),n=o.map((e=>e[0])),r=o.map((e=>e[1])),i=e=>Math.min.apply(null,e),s=e=>Math.max.apply(null,e);return[i(n),i(r),s(n),s(r)]}(e),c=t[1],u=t[3],l=t[0],d=t[2];c>o&&(o=c),ur&&(r=u),ca&&(a=d)}));const c=t;return o+c.lat>be&&(c.lat=be-o),r+c.lat>Me&&(c.lat=Me-r),n+c.lat=Ae&&(c.lng-=360*Math.ceil(Math.abs(c.lng)/360)),c}function Fe(e,t){const o=Pe(e.map((e=>e.toGeoJSON())),t);e.forEach((e=>{const t=e.getCoordinates(),n=e=>{const t={lng:e[0]+o.lng,lat:e[1]+o.lat};return[t.lng,t.lat]},r=e=>e.map((e=>n(e))),i=e=>e.map((e=>r(e)));let s;e.type===h.POINT?s=n(t):e.type===h.LINE_STRING||e.type===h.MULTI_POINT?s=t.map(n):e.type===h.POLYGON||e.type===h.MULTI_LINE_STRING?s=t.map(r):e.type===h.MULTI_POLYGON&&(s=t.map(i)),e.incomingCoords(s)}))}const Re={onSetup:function(e){const t={dragMoveLocation:null,boxSelectStartLocation:null,boxSelectElement:void 0,boxSelecting:!1,canBoxSelect:!1,dragMoving:!1,canDragMove:!1,initialDragPanState:this.map.dragPan.isEnabled(),initiallySelectedFeatureIds:e.featureIds||[]};return this.setSelected(t.initiallySelectedFeatureIds.filter((e=>void 0!==this.getFeature(e)))),this.fireActionable(),this.setActionableState({combineFeatures:!0,uncombineFeatures:!0,trash:!0}),t},fireUpdate:function(){this.fire(g.UPDATE,{action:m.MOVE,features:this.getSelected().map((e=>e.toGeoJSON()))})},fireActionable:function(){const e=this.getSelected(),t=e.filter((e=>this.isInstanceOf("MultiFeature",e)));let o=!1;if(e.length>1){o=!0;const t=e[0].type.replace("Multi","");e.forEach((e=>{e.type.replace("Multi","")!==t&&(o=!1)}))}const n=t.length>0,r=e.length>0;this.setActionableState({combineFeatures:o,uncombineFeatures:n,trash:r})},getUniqueIds:function(e){return e.length?e.map((e=>e.properties.id)).filter((e=>void 0!==e)).reduce(((e,t)=>(e.add(t),e)),new M).values():[]},stopExtendedInteractions:function(e){e.boxSelectElement&&(e.boxSelectElement.parentNode&&e.boxSelectElement.parentNode.removeChild(e.boxSelectElement),e.boxSelectElement=null),(e.canDragMove||e.canBoxSelect)&&!0===e.initialDragPanState&&this.map.dragPan.enable(),e.boxSelecting=!1,e.canBoxSelect=!1,e.dragMoving=!1,e.canDragMove=!1},onStop:function(){Oe.enable(this)},onMouseMove:function(e,t){return fe(t)&&e.dragMoving&&this.fireUpdate(),this.stopExtendedInteractions(e),!0},onMouseOut:function(e){return!e.dragMoving||this.fireUpdate()}};Re.onTap=Re.onClick=function(e,t){return he(t)?this.clickAnywhere(e,t):ue(y.VERTEX)(t)?this.clickOnVertex(e,t):fe(t)?this.clickOnFeature(e,t):void 0},Re.clickAnywhere=function(e){const t=this.getSelectedIds();t.length&&(this.clearSelectedFeatures(),t.forEach((e=>this.doRender(e)))),Oe.enable(this),this.stopExtendedInteractions(e)},Re.clickOnVertex=function(e,t){this.changeMode(f.DIRECT_SELECT,{featureId:t.featureTarget.properties.parent,coordPath:t.featureTarget.properties.coord_path,startPos:t.lngLat}),this.updateUIClasses({mouse:d.MOVE})},Re.startOnActiveFeature=function(e,t){this.stopExtendedInteractions(e),this.map.dragPan.disable(),this.doRender(t.featureTarget.properties.id),e.canDragMove=!0,e.dragMoveLocation=t.lngLat},Re.clickOnFeature=function(e,t){Oe.disable(this),this.stopExtendedInteractions(e);const o=me(t),n=this.getSelectedIds(),r=t.featureTarget.properties.id,i=this.isSelected(r);if(!o&&i&&this.getFeature(r).type!==h.POINT)return this.changeMode(f.DIRECT_SELECT,{featureId:r});i&&o?(this.deselect(r),this.updateUIClasses({mouse:d.POINTER}),1===n.length&&Oe.enable(this)):!i&&o?(this.select(r),this.updateUIClasses({mouse:d.MOVE})):i||o||(n.forEach((e=>this.doRender(e))),this.setSelected(r),this.updateUIClasses({mouse:d.MOVE})),this.doRender(r)},Re.onMouseDown=function(e,t){return e.initialDragPanState=this.map.dragPan.isEnabled(),de(t)?this.startOnActiveFeature(e,t):this.drawConfig.boxSelect&&le(t)?this.startBoxSelect(e,t):void 0},Re.startBoxSelect=function(e,t){this.stopExtendedInteractions(e),this.map.dragPan.disable(),e.boxSelectStartLocation=_e(t.originalEvent,this.map.getContainer()),e.canBoxSelect=!0},Re.onTouchStart=function(e,t){if(de(t))return this.startOnActiveFeature(e,t)},Re.onDrag=function(e,t){return e.canDragMove?this.dragMove(e,t):this.drawConfig.boxSelect&&e.canBoxSelect?this.whileBoxSelect(e,t):void 0},Re.whileBoxSelect=function(e,t){e.boxSelecting=!0,this.updateUIClasses({mouse:d.ADD}),e.boxSelectElement||(e.boxSelectElement=document.createElement("div"),e.boxSelectElement.classList.add(u.BOX_SELECT),this.map.getContainer().appendChild(e.boxSelectElement));const o=_e(t.originalEvent,this.map.getContainer()),n=Math.min(e.boxSelectStartLocation.x,o.x),r=Math.max(e.boxSelectStartLocation.x,o.x),i=Math.min(e.boxSelectStartLocation.y,o.y),s=Math.max(e.boxSelectStartLocation.y,o.y),a=`translate(${n}px, ${i}px)`;e.boxSelectElement.style.transform=a,e.boxSelectElement.style.WebkitTransform=a,e.boxSelectElement.style.width=r-n+"px",e.boxSelectElement.style.height=s-i+"px"},Re.dragMove=function(e,t){e.dragMoving=!0,t.originalEvent.stopPropagation();const o={lng:t.lngLat.lng-e.dragMoveLocation.lng,lat:t.lngLat.lat-e.dragMoveLocation.lat};Fe(this.getSelected(),o),e.dragMoveLocation=t.lngLat},Re.onTouchEnd=Re.onMouseUp=function(e,t){if(e.dragMoving)this.fireUpdate();else if(e.boxSelecting){const o=[e.boxSelectStartLocation,_e(t.originalEvent,this.map.getContainer())],n=this.featuresAt(null,o,"click"),r=this.getUniqueIds(n).filter((e=>!this.isSelected(e)));r.length&&(this.select(r),r.forEach((e=>this.doRender(e))),this.updateUIClasses({mouse:d.MOVE}))}this.stopExtendedInteractions(e)},Re.toDisplayFeatures=function(e,t,o){t.properties.active=this.isSelected(t.properties.id)?E.ACTIVE:E.INACTIVE,o(t),this.fireActionable(),t.properties.active===E.ACTIVE&&t.geometry.type!==h.POINT&&Se(t).forEach(o)},Re.onTrash=function(){this.deleteFeature(this.getSelectedIds()),this.fireActionable()},Re.onCombineFeatures=function(){const e=this.getSelected();if(0===e.length||e.length<2)return;const t=[],o=[],n=e[0].type.replace("Multi","");for(let r=0;r{t.push(e)})):t.push(i.getCoordinates()),o.push(i.toGeoJSON())}if(o.length>1){const e=this.newFeature({type:h.FEATURE,properties:o[0].properties,geometry:{type:`Multi${n}`,coordinates:t}});this.addFeature(e),this.deleteFeature(this.getSelectedIds(),{silent:!0}),this.setSelected([e.id]),this.fire(g.COMBINE_FEATURES,{createdFeatures:[e.toGeoJSON()],deletedFeatures:o})}this.fireActionable()},Re.onUncombineFeatures=function(){const e=this.getSelected();if(0===e.length)return;const t=[],o=[];for(let n=0;n{this.addFeature(e),e.properties=r.properties,t.push(e.toGeoJSON()),this.select([e.id])})),this.deleteFeature(r.id,{silent:!0}),o.push(r.toGeoJSON()))}t.length>1&&this.fire(g.UNCOMBINE_FEATURES,{createdFeatures:t,deletedFeatures:o}),this.fireActionable()};const we=ue(y.VERTEX),De=ue(y.MIDPOINT),Ue={fireUpdate:function(){this.fire(g.UPDATE,{action:m.CHANGE_COORDINATES,features:this.getSelected().map((e=>e.toGeoJSON()))})},fireActionable:function(e){this.setActionableState({combineFeatures:!1,uncombineFeatures:!1,trash:e.selectedCoordPaths.length>0})},startDragging:function(e,t){e.initialDragPanState=this.map.dragPan.isEnabled(),this.map.dragPan.disable(),e.canDragMove=!0,e.dragMoveLocation=t.lngLat},stopDragging:function(e){e.canDragMove&&!0===e.initialDragPanState&&this.map.dragPan.enable(),e.dragMoving=!1,e.canDragMove=!1,e.dragMoveLocation=null},onVertex:function(e,t){this.startDragging(e,t);const o=t.featureTarget.properties,n=e.selectedCoordPaths.indexOf(o.coord_path);me(t)||-1!==n?me(t)&&-1===n&&e.selectedCoordPaths.push(o.coord_path):e.selectedCoordPaths=[o.coord_path];const r=this.pathsToCoordinates(e.featureId,e.selectedCoordPaths);this.setSelectedCoordinates(r)},onMidpoint:function(e,t){this.startDragging(e,t);const o=t.featureTarget.properties;e.feature.addCoordinate(o.coord_path,o.lng,o.lat),this.fireUpdate(),e.selectedCoordPaths=[o.coord_path]},pathsToCoordinates:function(e,t){return t.map((t=>({feature_id:e,coord_path:t})))},onFeature:function(e,t){0===e.selectedCoordPaths.length?this.startDragging(e,t):this.stopDragging(e)},dragFeature:function(e,t,o){Fe(this.getSelected(),o),e.dragMoveLocation=t.lngLat},dragVertex:function(e,t,o){const n=e.selectedCoordPaths.map((t=>e.feature.getCoordinate(t))),r=Pe(n.map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e}}))),o);for(let t=0;tt.localeCompare(e,"en",{numeric:!0}))).forEach((t=>e.feature.removeCoordinate(t))),this.fireUpdate(),e.selectedCoordPaths=[],this.clearSelectedCoordinates(),this.fireActionable(e),!1===e.feature.isValid()&&(this.deleteFeature([e.featureId]),this.changeMode(f.SIMPLE_SELECT,{}))},onMouseMove:function(e,t){const o=de(t),n=we(t),r=De(t),i=0===e.selectedCoordPaths.length;return o&&i||n&&!i?this.updateUIClasses({mouse:d.MOVE}):this.updateUIClasses({mouse:d.NONE}),(n||o||r)&&e.dragMoving&&this.fireUpdate(),this.stopDragging(e),!0},onMouseOut:function(e){return e.dragMoving&&this.fireUpdate(),!0}};Ue.onTouchStart=Ue.onMouseDown=function(e,t){return we(t)?this.onVertex(e,t):de(t)?this.onFeature(e,t):De(t)?this.onMidpoint(e,t):void 0},Ue.onDrag=function(e,t){if(!0!==e.canDragMove)return;e.dragMoving=!0,t.originalEvent.stopPropagation();const o={lng:t.lngLat.lng-e.dragMoveLocation.lng,lat:t.lngLat.lat-e.dragMoveLocation.lat};e.selectedCoordPaths.length>0?this.dragVertex(e,t,o):this.dragFeature(e,t,o),e.dragMoveLocation=t.lngLat},Ue.onClick=function(e,t){return he(t)?this.clickNoTarget(e,t):de(t)?this.clickActiveFeature(e,t):pe(t)?this.clickInactive(e,t):void this.stopDragging(e)},Ue.onTap=function(e,t){return he(t)?this.clickNoTarget(e,t):de(t)?this.clickActiveFeature(e,t):pe(t)?this.clickInactive(e,t):void 0},Ue.onTouchEnd=Ue.onMouseUp=function(e){e.dragMoving&&this.fireUpdate(),this.stopDragging(e)};const ke={};function Ve(e,t){return!!e.lngLat&&e.lngLat.lng===t[0]&&e.lngLat.lat===t[1]}ke.onSetup=function(){const e=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:[]}});return this.addFeature(e),this.clearSelectedFeatures(),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.POINT),this.setActionableState({trash:!0}),{point:e}},ke.stopDrawingAndRemove=function(e){this.deleteFeature([e.point.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)},ke.onTap=ke.onClick=function(e,t){this.updateUIClasses({mouse:d.MOVE}),e.point.updateCoordinate("",t.lngLat.lng,t.lngLat.lat),this.fire(g.CREATE,{features:[e.point.toGeoJSON()]}),this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.point.id]})},ke.onStop=function(e){this.activateUIButton(),e.point.getCoordinate().length||this.deleteFeature([e.point.id],{silent:!0})},ke.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.point.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t)},ke.onTrash=ke.stopDrawingAndRemove,ke.onKeyUp=function(e,t){if(ye(t)||Ee(t))return this.stopDrawingAndRemove(e,t)};const Ge={onSetup:function(){const e=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.POLYGON,coordinates:[[]]}});return this.addFeature(e),this.clearSelectedFeatures(),Oe.disable(this),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.POLYGON),this.setActionableState({trash:!0}),{polygon:e,currentVertexPosition:0}},clickAnywhere:function(e,t){if(e.currentVertexPosition>0&&Ve(t,e.polygon.coordinates[0][e.currentVertexPosition-1]))return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]});this.updateUIClasses({mouse:d.ADD}),e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat),e.currentVertexPosition++,e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat)},clickOnVertex:function(e){return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]})},onMouseMove:function(e,t){e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat),ge(t)&&this.updateUIClasses({mouse:d.POINTER})}};Ge.onTap=Ge.onClick=function(e,t){return ge(t)?this.clickOnVertex(e,t):this.clickAnywhere(e,t)},Ge.onKeyUp=function(e,t){ye(t)?(this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)):Ee(t)&&this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]})},Ge.onStop=function(e){this.updateUIClasses({mouse:d.NONE}),Oe.enable(this),this.activateUIButton(),void 0!==this.getFeature(e.polygon.id)&&(e.polygon.removeCoordinate(`0.${e.currentVertexPosition}`),e.polygon.isValid()?this.fire(g.CREATE,{features:[e.polygon.toGeoJSON()]}):(this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT,{},{silent:!0})))},Ge.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.polygon.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t);if(0===t.geometry.coordinates.length)return;const r=t.geometry.coordinates[0].length;if(!(r<3)){if(t.properties.meta=y.FEATURE,o(ve(e.polygon.id,t.geometry.coordinates[0][0],"0.0",!1)),r>3){const n=t.geometry.coordinates[0].length-3;o(ve(e.polygon.id,t.geometry.coordinates[0][n],`0.${n}`,!1))}if(r<=4){const e=[[t.geometry.coordinates[0][0][0],t.geometry.coordinates[0][0][1]],[t.geometry.coordinates[0][1][0],t.geometry.coordinates[0][1][1]]];if(o({type:h.FEATURE,properties:t.properties,geometry:{coordinates:e,type:h.LINE_STRING}}),3===r)return}return o(t)}},Ge.onTrash=function(e){this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)};const Be={onSetup:function(e){const t=(e=e||{}).featureId;let o,n,r="forward";if(t){if(o=this.getFeature(t),!o)throw new Error("Could not find a feature with the provided featureId");let i=e.from;if(i&&"Feature"===i.type&&i.geometry&&"Point"===i.geometry.type&&(i=i.geometry),i&&"Point"===i.type&&i.coordinates&&2===i.coordinates.length&&(i=i.coordinates),!i||!Array.isArray(i))throw new Error("Please use the `from` property to indicate which point to continue the line from");const s=o.coordinates.length-1;if(o.coordinates[s][0]===i[0]&&o.coordinates[s][1]===i[1])n=s+1,o.addCoordinate(n,...o.coordinates[s]);else{if(o.coordinates[0][0]!==i[0]||o.coordinates[0][1]!==i[1])throw new Error("`from` should match the point at either the start or the end of the provided LineString");r="backwards",n=0,o.addCoordinate(n,...o.coordinates[0])}}else o=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.LINE_STRING,coordinates:[]}}),n=0,this.addFeature(o);return this.clearSelectedFeatures(),Oe.disable(this),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.LINE),this.setActionableState({trash:!0}),{line:o,currentVertexPosition:n,direction:r}},clickAnywhere:function(e,t){if(e.currentVertexPosition>0&&Ve(t,e.line.coordinates[e.currentVertexPosition-1])||"backwards"===e.direction&&Ve(t,e.line.coordinates[e.currentVertexPosition+1]))return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]});this.updateUIClasses({mouse:d.ADD}),e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat),"forward"===e.direction?(e.currentVertexPosition++,e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat)):e.line.addCoordinate(0,t.lngLat.lng,t.lngLat.lat)},clickOnVertex:function(e){return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]})},onMouseMove:function(e,t){e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat),ge(t)&&this.updateUIClasses({mouse:d.POINTER})}};Be.onTap=Be.onClick=function(e,t){if(ge(t))return this.clickOnVertex(e,t);this.clickAnywhere(e,t)},Be.onKeyUp=function(e,t){Ee(t)?this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]}):ye(t)&&(this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT))},Be.onStop=function(e){Oe.enable(this),this.activateUIButton(),void 0!==this.getFeature(e.line.id)&&(e.line.removeCoordinate(`${e.currentVertexPosition}`),e.line.isValid()?this.fire(g.CREATE,{features:[e.line.toGeoJSON()]}):(this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT,{},{silent:!0})))},Be.onTrash=function(e){this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)},Be.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.line.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t);t.geometry.coordinates.length<2||(t.properties.meta=y.FEATURE,o(ve(e.line.id,t.geometry.coordinates["forward"===e.direction?t.geometry.coordinates.length-2:1],""+("forward"===e.direction?t.geometry.coordinates.length-2:1),!1)),o(t))};var je={simple_select:Re,direct_select:Ue,draw_point:ke,draw_polygon:Ge,draw_line_string:Be};const Je={defaultMode:f.SIMPLE_SELECT,keybindings:!0,touchEnabled:!0,clickBuffer:2,touchBuffer:25,boxSelect:!0,displayControlsDefault:!0,styles:ce,modes:je,controls:{},userProperties:!1,suppressAPIEvents:!0},$e={point:!0,line_string:!0,polygon:!0,trash:!0,combine_features:!0,uncombine_features:!0},Ye={point:!1,line_string:!1,polygon:!1,trash:!1,combine_features:!1,uncombine_features:!1};function He(e,t){return e.map((e=>e.source?e:Object.assign({},e,{id:`${e.id}.${t}`,source:"hot"===t?l.HOT:l.COLD})))}var Xe,qe,Ze,We,Ke=t(qe?Xe:(qe=1,Xe=function e(t,o){if(t===o)return!0;if(t&&o&&"object"==typeof t&&"object"==typeof o){if(t.constructor!==o.constructor)return!1;var n,r,i;if(Array.isArray(t)){if((n=t.length)!=o.length)return!1;for(r=n;0!=r--;)if(!e(t[r],o[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===o.source&&t.flags===o.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===o.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===o.toString();if((n=(i=Object.keys(t)).length)!==Object.keys(o).length)return!1;for(r=n;0!=r--;)if(!Object.prototype.hasOwnProperty.call(o,i[r]))return!1;for(r=n;0!=r--;){var s=i[r];if(!e(t[s],o[s]))return!1}return!0}return t!=t&&o!=o})),ze=function(){if(We)return Ze;We=1,Ze=function(t){if(!t||!t.type)return null;var o=e[t.type];return o?"geometry"===o?{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:t}]}:"feature"===o?{type:"FeatureCollection",features:[t]}:"featurecollection"===o?t:void 0:null};var e={Point:"geometry",MultiPoint:"geometry",LineString:"geometry",MultiLineString:"geometry",Polygon:"geometry",MultiPolygon:"geometry",GeometryCollection:"geometry",Feature:"feature",FeatureCollection:"featurecollection"};return Ze}(),Qe=t(ze);function et(e,t){return e.length===t.length&&JSON.stringify(e.map((e=>e)).sort())===JSON.stringify(t.map((e=>e)).sort())}const tt={Polygon:Y,LineString:$,Point:J,MultiPolygon:q,MultiLineString:q,MultiPoint:q};var ot=Object.freeze({__proto__:null,CommonSelectors:Te,ModeHandler:e,StringSet:M,constrainFeatureMovement:Pe,createMidPoint:Ie,createSupplementaryPoints:Se,createVertex:ve,doubleClickZoom:Oe,euclideanDistance:P,featuresAt:b,getFeatureAtAndSetCursors:A,isClick:D,isEventAtCoordinates:Ve,isTap:V,mapEventToBoundingBox:L,moveFeatures:Fe,sortFeatures:O,stringSetsAreEqual:et,theme:ce,toDenseArray:Q});const nt=function(e,t){const o={options:e=function(e={}){let t=Object.assign({},e);return e.controls||(t.controls={}),!1===e.displayControlsDefault?t.controls=Object.assign({},Ye,e.controls):t.controls=Object.assign({},$e,e.controls),t=Object.assign({},Je,t),t.styles=He(t.styles,"cold").concat(He(t.styles,"hot")),t}(e)};t=function(e,t){t.modes=f;const o=void 0===e.options.suppressAPIEvents||!!e.options.suppressAPIEvents;return t.getFeatureIdsAt=function(t){return b.click({point:t},null,e).map((e=>e.properties.id))},t.getSelectedIds=function(){return e.store.getSelectedIds()},t.getSelected=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getSelectedIds().map((t=>e.store.get(t))).map((e=>e.toGeoJSON()))}},t.getSelectedPoints=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getSelectedCoordinates().map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e.coordinates}})))}},t.set=function(o){if(void 0===o.type||o.type!==h.FEATURE_COLLECTION||!Array.isArray(o.features))throw new Error("Invalid FeatureCollection");const n=e.store.createRenderBatch();let r=e.store.getAllIds().slice();const i=t.add(o),s=new M(i);return r=r.filter((e=>!s.has(e))),r.length&&t.delete(r),n(),i},t.add=function(t){const n=JSON.parse(JSON.stringify(Qe(t))).features.map((t=>{if(t.id=t.id||B(),null===t.geometry)throw new Error("Invalid geometry: null");if(void 0===e.store.get(t.id)||e.store.get(t.id).type!==t.geometry.type){const n=tt[t.geometry.type];if(void 0===n)throw new Error(`Invalid geometry type: ${t.geometry.type}.`);const r=new n(e,t);e.store.add(r,{silent:o})}else{const n=e.store.get(t.id),r=n.properties;n.properties=t.properties,Ke(r,t.properties)||e.store.featureChanged(n.id,{silent:o}),Ke(n.getCoordinates(),t.geometry.coordinates)||n.incomingCoords(t.geometry.coordinates)}return t.id}));return e.store.render(),n},t.get=function(t){const o=e.store.get(t);if(o)return o.toGeoJSON()},t.getAll=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getAll().map((e=>e.toGeoJSON()))}},t.delete=function(n){return e.store.delete(n,{silent:o}),t.getMode()!==f.DIRECT_SELECT||e.store.getSelectedIds().length?e.store.render():e.events.changeMode(f.SIMPLE_SELECT,void 0,{silent:o}),t},t.deleteAll=function(){return e.store.delete(e.store.getAllIds(),{silent:o}),t.getMode()===f.DIRECT_SELECT?e.events.changeMode(f.SIMPLE_SELECT,void 0,{silent:o}):e.store.render(),t},t.changeMode=function(n,r={}){return n===f.SIMPLE_SELECT&&t.getMode()===f.SIMPLE_SELECT?(et(r.featureIds||[],e.store.getSelectedIds())||(e.store.setSelected(r.featureIds,{silent:o}),e.store.render()),t):(n===f.DIRECT_SELECT&&t.getMode()===f.DIRECT_SELECT&&r.featureId===e.store.getSelectedIds()[0]||e.events.changeMode(n,r,{silent:o}),t)},t.getMode=function(){return e.events.getMode()},t.trash=function(){return e.events.trash({silent:o}),t},t.combineFeatures=function(){return e.events.combineFeatures({silent:o}),t},t.uncombineFeatures=function(){return e.events.uncombineFeatures({silent:o}),t},t.setFeatureProperty=function(n,r,i){return e.store.setFeatureProperty(n,r,i,{silent:o}),t},t}(o,t),o.api=t;const n=re(o);return t.onAdd=n.onAdd,t.onRemove=n.onRemove,t.types=p,t.options=e,t};function rt(e){nt(e,this)}return rt.modes=je,rt.constants=v,rt.lib=ot,rt},"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).MapboxDraw=t(); +//# sourceMappingURL=mapbox-gl-draw.js.map diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js new file mode 100644 index 0000000..e2b91ff --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-gl-globe-minimap/bundle.js @@ -0,0 +1 @@ +var MapboxGLGlobeMinimap=function(){"use strict";class t{constructor(){this._partials=new Float64Array(32),this._n=0}add(t){const n=this._partials;let e=0;for(let r=0;r0){for(o=t[--i];i>0&&(n=o,e=t[--i],o=n+e,r=e-(o-n),!r););i>0&&(r<0&&t[i-1]<0||r>0&&t[i-1]>0)&&(e=2*r,n=o+e,e==n-o&&(o=n))}return o}}function n(t){return Array.from(function*(t){for(const n of t)yield*n}(t))}var e={value:()=>{}};function r(){for(var t,n=0,e=arguments.length,r={};n=0&&(n=t.slice(e+1),t=t.slice(0,e)),t&&!r.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))),l=-1,s=a.length;if(!(arguments.length<2)){if(null!=n&&"function"!=typeof n)throw new Error("invalid callback: "+n);for(;++l0)for(var e,r,i=new Array(e),o=0;o=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),l.hasOwnProperty(n)?{space:l[n],local:t}:t}function c(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===a&&n.documentElement.namespaceURI===a?n.createElement(t):n.createElementNS(e,t)}}function f(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function h(t){var n=s(t);return(n.local?f:c)(n)}function p(){}function d(t){return null==t?p:function(){return this.querySelector(t)}}function v(){return[]}function g(t){return null==t?v:function(){return this.querySelectorAll(t)}}function y(t){return function(){return null==(n=t.apply(this,arguments))?[]:Array.isArray(n)?n:Array.from(n);var n}}function _(t){return function(){return this.matches(t)}}function m(t){return function(n){return n.matches(t)}}var w=Array.prototype.find;function b(){return this.firstElementChild}var x=Array.prototype.filter;function E(){return Array.from(this.children)}function S(t){return new Array(t.length)}function N(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}function k(t,n,e,r,i,o){for(var u,a=0,l=n.length,s=o.length;an?1:t>=n?0:NaN}function P(t){return function(){this.removeAttribute(t)}}function j(t){return function(){this.removeAttributeNS(t.space,t.local)}}function R(t,n){return function(){this.setAttribute(t,n)}}function T(t,n){return function(){this.setAttributeNS(t.space,t.local,n)}}function q(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttribute(t):this.setAttribute(t,e)}}function O(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}}function L(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function X(t){return function(){this.style.removeProperty(t)}}function z(t,n,e){return function(){this.style.setProperty(t,n,e)}}function D(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}function H(t,n){return t.style.getPropertyValue(n)||L(t).getComputedStyle(t,null).getPropertyValue(n)}function I(t){return function(){delete this[t]}}function Y(t,n){return function(){this[t]=n}}function B(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}function F(t){return t.trim().split(/^|\s+/)}function V(t){return t.classList||new G(t)}function G(t){this._node=t,this._names=F(t.getAttribute("class")||"")}function U(t,n){for(var e=V(t),r=-1,i=n.length;++r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var gt=[null];function yt(t,n){this._groups=t,this._parents=n}function _t(){return new yt([[document.documentElement]],gt)}function mt(t){return"string"==typeof t?new yt([[document.querySelector(t)]],[document.documentElement]):new yt([[t]],gt)}function wt(t,n,e){t.prototype=n.prototype=e,e.constructor=t}function bt(t,n){var e=Object.create(t.prototype);for(var r in n)e[r]=n[r];return e}function xt(){}yt.prototype=_t.prototype={constructor:yt,select:function(t){"function"!=typeof t&&(t=d(t));for(var n=this._groups,e=n.length,r=new Array(e),i=0;i=b&&(b=w+1);!(m=y[b])&&++b=0;)(r=i[o])&&(u&&4^r.compareDocumentPosition(u)&&u.parentNode.insertBefore(r,u),u=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=C);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?X:"function"==typeof n?D:z)(t,n,null==e?"":e)):H(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?I:"function"==typeof n?B:Y)(t,n)):this.node()[t]},classed:function(t,n){var e=F(t+"");if(arguments.length<2){for(var r=V(this.node()),i=-1,o=e.length;++i=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}}))}(t+""),u=o.length;if(!(arguments.length<2)){for(a=n?ht:ft,r=0;r>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):8===e?Dt(n>>24&255,n>>16&255,n>>8&255,(255&n)/255):4===e?Dt(n>>12&15|n>>8&240,n>>8&15|n>>4&240,n>>4&15|240&n,((15&n)<<4|15&n)/255):null):(n=$t.exec(t))?new It(n[1],n[2],n[3],1):(n=Ct.exec(t))?new It(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=Pt.exec(t))?Dt(n[1],n[2],n[3],n[4]):(n=jt.exec(t))?Dt(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=Rt.exec(t))?Ut(n[1],n[2]/100,n[3]/100,1):(n=Tt.exec(t))?Ut(n[1],n[2]/100,n[3]/100,n[4]):qt.hasOwnProperty(t)?zt(qt[t]):"transparent"===t?new It(NaN,NaN,NaN,0):null}function zt(t){return new It(t>>16&255,t>>8&255,255&t,1)}function Dt(t,n,e,r){return r<=0&&(t=n=e=NaN),new It(t,n,e,r)}function Ht(t,n,e,r){return 1===arguments.length?((i=t)instanceof xt||(i=Xt(i)),i?new It((i=i.rgb()).r,i.g,i.b,i.opacity):new It):new It(t,n,e,null==r?1:r);var i}function It(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function Yt(){return`#${Gt(this.r)}${Gt(this.g)}${Gt(this.b)}`}function Bt(){const t=Ft(this.opacity);return`${1===t?"rgb(":"rgba("}${Vt(this.r)}, ${Vt(this.g)}, ${Vt(this.b)}${1===t?")":`, ${t})`}`}function Ft(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Vt(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Gt(t){return((t=Vt(t))<16?"0":"")+t.toString(16)}function Ut(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new Wt(t,n,e,r)}function Zt(t){if(t instanceof Wt)return new Wt(t.h,t.s,t.l,t.opacity);if(t instanceof xt||(t=Xt(t)),!t)return new Wt;if(t instanceof Wt)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),u=NaN,a=o-i,l=(o+i)/2;return a?(u=n===o?(e-r)/a+6*(e0&&l<1?0:u,new Wt(u,a,l,t.opacity)}function Wt(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function Kt(t){return(t=(t||0)%360)<0?t+360:t}function Jt(t){return Math.max(0,Math.min(1,t||0))}function Qt(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}wt(xt,Xt,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:Ot,formatHex:Ot,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return Zt(this).formatHsl()},formatRgb:Lt,toString:Lt}),wt(It,Ht,bt(xt,{brighter(t){return t=null==t?St:Math.pow(St,t),new It(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?Et:Math.pow(Et,t),new It(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new It(Vt(this.r),Vt(this.g),Vt(this.b),Ft(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Yt,formatHex:Yt,formatHex8:function(){return`#${Gt(this.r)}${Gt(this.g)}${Gt(this.b)}${Gt(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:Bt,toString:Bt})),wt(Wt,(function(t,n,e,r){return 1===arguments.length?Zt(t):new Wt(t,n,e,null==r?1:r)}),bt(xt,{brighter(t){return t=null==t?St:Math.pow(St,t),new Wt(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?Et:Math.pow(Et,t),new Wt(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new It(Qt(t>=240?t-240:t+120,i,r),Qt(t,i,r),Qt(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new Wt(Kt(this.h),Jt(this.s),Jt(this.l),Ft(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=Ft(this.opacity);return`${1===t?"hsl(":"hsla("}${Kt(this.h)}, ${100*Jt(this.s)}%, ${100*Jt(this.l)}%${1===t?")":`, ${t})`}`}}));var tn=t=>()=>t;function nn(t){return 1==(t=+t)?en:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):tn(isNaN(n)?e:n)}}function en(t,n){var e=n-t;return e?function(t,n){return function(e){return t+e*n}}(t,e):tn(isNaN(t)?n:t)}var rn=function t(n){var e=nn(n);function r(t,n){var r=e((t=Ht(t)).r,(n=Ht(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),u=en(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=u(n),t+""}}return r.gamma=t,r}(1);function on(t,n){n||(n=[]);var e,r=t?Math.min(n.length,t.length):0,i=n.slice();return function(o){for(e=0;eo&&(i=n.slice(o,i),a[u]?a[u]+=i:a[++u]=i),(e=e[0])===(r=r[0])?a[u]?a[u]+=r:a[++u]=r:(a[++u]=null,l.push({i:u,x:ln(e,r)})),o=fn.lastIndex;return o180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:ln(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,u.rotate,a,l),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:ln(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,u.skewX,a,l),function(t,n,e,r,o,u){if(t!==e||n!==r){var a=o.push(i(o)+"scale(",null,",",null,")");u.push({i:a-4,x:ln(t,e)},{i:a-2,x:ln(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,u.scaleX,u.scaleY,a,l),o=u=null,function(t){for(var n,e=-1,r=l.length;++e=0&&n._call.call(void 0,t),n=n._next;--En}()}finally{En=0,function(){var t,n,e=mn,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:mn=n);wn=t,Xn(r)}(),An=0}}function Ln(){var t=Cn.now(),n=t-Mn;n>kn&&($n-=n,Mn=t)}function Xn(t){En||(Sn&&(Sn=clearTimeout(Sn)),t-An>24?(t<1/0&&(Sn=setTimeout(On,t-Cn.now()-$n)),Nn&&(Nn=clearInterval(Nn))):(Nn||(Mn=Cn.now(),Nn=setInterval(Ln,kn)),En=1,Pn(On)))}function zn(t,n,e){var r=new Tn;return n=null==n?0:+n,r.restart((e=>{r.stop(),t(e+n)}),n,e),r}Tn.prototype=qn.prototype={constructor:Tn,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?jn():+e)+(null==n?0:+n),this._next||wn===this||(wn?wn._next=this:mn=this,wn=this),this._call=t,this._time=e,Xn()},stop:function(){this._call&&(this._call=null,this._time=1/0,Xn())}};var Dn=r("start","end","cancel","interrupt"),Hn=[],In=0,Yn=1,Bn=2,Fn=3,Vn=4,Gn=5,Un=6;function Zn(t,n,e,r,i,o){var u=t.__transition;if(u){if(e in u)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(t){e.state=Yn,e.timer.restart(u,e.delay,e.time),e.delay<=t&&u(t-e.delay)}function u(o){var s,c,f,h;if(e.state!==Yn)return l();for(s in i)if((h=i[s]).name===e.name){if(h.state===Fn)return zn(u);h.state===Vn?(h.state=Un,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[s]):+sIn)throw new Error("too late; already scheduled");return e}function Kn(t,n){var e=Jn(t,n);if(e.state>Fn)throw new Error("too late; already running");return e}function Jn(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function Qn(t,n){var e,r;return function(){var i=Kn(this,t),o=i.tween;if(o!==e)for(var u=0,a=(r=e=o).length;u=0&&(t=t.slice(0,n)),!t||"start"===t}))}(n)?Wn:Kn;return function(){var u=o(this,t),a=u.on;a!==r&&(i=(r=a).copy()).on(n,e),u.on=i}}(e,t,n))},attr:function(t,n){var e=s(t),r="transform"===e?xn:ee;return this.attrTween(t,"function"==typeof n?(e.local?le:ae)(e,r,ne(this,"attr."+t,n)):null==n?(e.local?ie:re)(e):(e.local?ue:oe)(e,r,n))},attrTween:function(t,n){var e="attr."+t;if(arguments.length<2)return(e=this.tween(e))&&e._value;if(null==n)return this.tween(e,null);if("function"!=typeof n)throw new Error;var r=s(t);return this.tween(e,(r.local?se:ce)(r,n))},style:function(t,n,e){var r="transform"==(t+="")?bn:ee;return null==n?this.styleTween(t,function(t,n){var e,r,i;return function(){var o=H(this,t),u=(this.style.removeProperty(t),H(this,t));return o===u?null:o===e&&u===r?i:i=n(e=o,r=u)}}(t,r)).on("end.style."+t,ge(t)):"function"==typeof n?this.styleTween(t,function(t,n,e){var r,i,o;return function(){var u=H(this,t),a=e(this),l=a+"";return null==a&&(this.style.removeProperty(t),l=a=H(this,t)),u===l?null:u===r&&l===i?o:(i=l,o=n(r=u,a))}}(t,r,ne(this,"style."+t,n))).each(function(t,n){var e,r,i,o,u="style."+n,a="end."+u;return function(){var l=Kn(this,t),s=l.on,c=null==l.value[u]?o||(o=ge(n)):void 0;s===e&&i===c||(r=(e=s).copy()).on(a,i=c),l.on=r}}(this._id,t)):this.styleTween(t,function(t,n,e){var r,i,o=e+"";return function(){var u=H(this,t);return u===o?null:u===r?i:i=n(r=u,e)}}(t,r,n),e).on("end.style."+t,null)},styleTween:function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,function(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&function(t,n,e){return function(r){this.style.setProperty(t,n.call(this,r),e)}}(t,o,e)),r}return o._value=n,o}(t,n,null==e?"":e))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var n=t(this);this.textContent=null==n?"":n}}(ne(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},textTween:function(t){var n="text";if(arguments.length<1)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;return this.tween(n,function(t){var n,e;function r(){var r=t.apply(this,arguments);return r!==e&&(n=(e=r)&&function(t){return function(n){this.textContent=t.call(this,n)}}(r)),n}return r._value=t,r}(t))},remove:function(){return this.on("end.remove",function(t){return function(){var n=this.parentNode;for(var e in this.__transition)if(+e!==t)return;n&&n.removeChild(this)}}(this._id))},tween:function(t,n){var e=this._id;if(t+="",arguments.length<2){for(var r,i=Jn(this.node(),e).tween,o=0,u=i.length;oBn&&e.state0?1:t<0?-1:0},Xe=Math.sqrt;function ze(t){return t>1?Me:t<-1?-Me:Math.asin(t)}function De(){}function He(t,n){t&&Ye.hasOwnProperty(t.type)&&Ye[t.type](t,n)}var Ie={Feature:function(t,n){He(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++rke&&(t-=Math.round(t/$e)*$e),[t,n]}function er(t){return function(n,e){return je(n+=t)>ke&&(n-=Math.round(n/$e)*$e),[n,e]}}function rr(t){var n=er(t);return n.invert=er(-t),n}function ir(t,n){var e=qe(t),r=Oe(t),i=qe(n),o=Oe(n);function u(t,n){var u=qe(n),a=qe(t)*u,l=Oe(t)*u,s=Oe(n),c=s*e+a*r;return[Te(l*i-c*o,a*e-s*r),ze(c*i+l*o)]}return u.invert=function(t,n){var u=qe(n),a=qe(t)*u,l=Oe(t)*u,s=Oe(n),c=s*i-l*o;return[Te(l*i+s*o,a*e+c*r),ze(c*e-a*r)]},u}function or(t,n){(n=Ue(n))[0]-=t,Qe(n);var e,r=(e=-n[1])>1?0:e<-1?ke:Math.acos(e);return((-n[2]<0?-r:r)+$e-Se)%$e}function ur(){var t,n=[];return{point:function(n,e,r){t.push([n,e,r])},lineStart:function(){n.push(t=[])},lineEnd:De,rejoin:function(){n.length>1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function ar(t,n){return je(t[0]-n[0])=0;--o)i.point((c=s[o])[0],c[1]);else r(h.x,h.p.x,-1,i);h=h.p}s=(h=h.o).z,p=!p}while(!h.v);i.lineEnd()}}}function cr(t){if(n=t.length){for(var n,e,r=0,i=t[0];++r=0?1:-1,M=k*N,A=M>ke,$=y*E;if(s.add(Te($*k*Oe(M),_*S+$*qe(M))),a+=A?N+k*$e:N,A^v>=r^b>=r){var C=We(Ue(d),Ue(w));Qe(C);var P=We(u,C);Qe(P);var j=(A^N>=0?-1:1)*ze(P[2]);(i>j||i===j&&(C[0]||C[1]))&&(l+=A^N>=0?1:-1)}}return(a<-Se||a0){for(p||(u.polygonStart(),p=!0),u.lineStart(),t=0;t1&&2&i&&o.push(o.pop().concat(o.shift())),l.push(o.filter(pr))}return d}}function pr(t){return t.length>1}function dr(t,n){return((t=t.x)[0]<0?t[1]-Me-Se:Me-t[1])-((n=n.x)[0]<0?n[1]-Me-Se:Me-n[1])}nr.invert=nr;var vr=hr((function(){return!0}),(function(t){var n,e=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),n=1},point:function(o,u){var a=o>0?ke:-ke,l=je(o-e);je(l-ke)0?Me:-Me),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),n=0):i!==a&&l>=ke&&(je(e-i)Se?Re((Oe(n)*(o=qe(r))*Oe(e)-Oe(r)*(i=qe(n))*Oe(t))/(i*o*u)):(n+r)/2}(e,r,o,u),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),n=0),t.point(e=o,r=u),i=a},lineEnd:function(){t.lineEnd(),e=r=NaN},clean:function(){return 2-n}}}),(function(t,n,e,r){var i;if(null==t)i=e*Me,r.point(-ke,i),r.point(0,i),r.point(ke,i),r.point(ke,0),r.point(ke,-i),r.point(0,-i),r.point(-ke,-i),r.point(-ke,0),r.point(-ke,i);else if(je(t[0]-n[0])>Se){var o=t[0]0,i=je(n)>Se;function o(t,e){return qe(t)*qe(e)>n}function u(t,e,r){var i=[1,0,0],o=We(Ue(t),Ue(e)),u=Ze(o,o),a=o[0],l=u-a*a;if(!l)return!r&&t;var s=n*u/l,c=-n*a/l,f=We(i,o),h=Je(i,s);Ke(h,Je(o,c));var p=f,d=Ze(h,p),v=Ze(p,p),g=d*d-v*(Ze(h,h)-1);if(!(g<0)){var y=Xe(g),_=Je(p,(-d-y)/v);if(Ke(_,h),_=Ge(_),!r)return _;var m,w=t[0],b=e[0],x=t[1],E=e[1];b0^_[1]<(je(_[0]-w)ke^(w<=_[0]&&_[0]<=b)){var k=Je(p,(-d+y)/v);return Ke(k,h),[_,Ge(k)]}}}function a(n,e){var i=r?t:ke-t,o=0;return n<-i?o|=1:n>i&&(o|=2),e<-i?o|=4:e>i&&(o|=8),o}return hr(o,(function(t){var n,e,l,s,c;return{lineStart:function(){s=l=!1,c=1},point:function(f,h){var p,d=[f,h],v=o(f,h),g=r?v?0:a(f,h):v?a(f+(f<0?ke:-ke),h):0;if(!n&&(s=l=v)&&t.lineStart(),v!==l&&(!(p=u(n,d))||ar(n,p)||ar(d,p))&&(d[2]=1),v!==l)c=0,v?(t.lineStart(),p=u(d,n),t.point(p[0],p[1])):(p=u(n,d),t.point(p[0],p[1],2),t.lineEnd()),n=p;else if(i&&n&&r^v){var y;g&e||!(y=u(d,n,!0))||(c=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1],3)))}!v||n&&ar(n,d)||t.point(d[0],d[1]),n=d,l=v,e=g},lineEnd:function(){l&&t.lineEnd(),n=null},clean:function(){return c|(s&&l)<<1}}}),(function(n,r,i,o){!function(t,n,e,r,i,o){if(e){var u=qe(n),a=Oe(n),l=r*e;null==i?(i=n+r*$e,o=n-l/2):(i=or(u,i),o=or(u,o),(r>0?io)&&(i+=r*$e));for(var s,c=i;r>0?c>o:c0)do{l.point(0===c||3===c?t:r,c>1?i:e)}while((c=(c+u+4)%4)!==f);else l.point(o[0],o[1])}function a(n,i){return je(n[0]-t)0?0:3:je(n[0]-r)0?2:1:je(n[1]-e)0?1:0:i>0?3:2}function l(t,n){return s(t.x,n.x)}function s(t,n){var e=a(t,1),r=a(n,1);return e!==r?e-r:0===e?n[1]-t[1]:1===e?t[0]-n[0]:2===e?t[1]-n[1]:n[0]-t[0]}return function(a){var s,c,f,h,p,d,v,g,y,_,m,w=a,b=ur(),x={point:E,lineStart:function(){x.point=S,c&&c.push(f=[]);_=!0,y=!1,v=g=NaN},lineEnd:function(){s&&(S(h,p),d&&y&&b.rejoin(),s.push(b.result()));x.point=E,y&&w.lineEnd()},polygonStart:function(){w=b,s=[],c=[],m=!0},polygonEnd:function(){var e=function(){for(var n=0,e=0,r=c.length;ei&&(h-o)*(i-u)>(p-u)*(t-o)&&++n:p<=i&&(h-o)*(i-u)<(p-u)*(t-o)&&--n;return n}(),r=m&&e,o=(s=n(s)).length;(r||o)&&(a.polygonStart(),r&&(a.lineStart(),u(null,null,1,a),a.lineEnd()),o&&sr(s,l,e,u,a),a.polygonEnd());w=a,s=c=f=null}};function E(t,n){o(t,n)&&w.point(t,n)}function S(n,u){var a=o(n,u);if(c&&f.push([n,u]),_)h=n,p=u,d=a,_=!1,a&&(w.lineStart(),w.point(n,u));else if(a&&y)w.point(n,u);else{var l=[v=Math.max(_r,Math.min(yr,v)),g=Math.max(_r,Math.min(yr,g))],s=[n=Math.max(_r,Math.min(yr,n)),u=Math.max(_r,Math.min(yr,u))];!function(t,n,e,r,i,o){var u,a=t[0],l=t[1],s=0,c=1,f=n[0]-a,h=n[1]-l;if(u=e-a,f||!(u>0)){if(u/=f,f<0){if(u0){if(u>c)return;u>s&&(s=u)}if(u=i-a,f||!(u<0)){if(u/=f,f<0){if(u>c)return;u>s&&(s=u)}else if(f>0){if(u0)){if(u/=h,h<0){if(u0){if(u>c)return;u>s&&(s=u)}if(u=o-l,h||!(u<0)){if(u/=h,h<0){if(u>c)return;u>s&&(s=u)}else if(h>0){if(u0&&(t[0]=a+s*f,t[1]=l+s*h),c<1&&(n[0]=a+c*f,n[1]=l+c*h),!0}}}}}(l,s,t,e,r,i)?a&&(w.lineStart(),w.point(n,u),m=!1):(y||(w.lineStart(),w.point(l[0],l[1])),w.point(s[0],s[1]),a||w.lineEnd(),m=!1)}v=n,g=u,y=a}return x}}var wr,br,xr,Er,Sr=t=>t,Nr=new t,kr=new t,Mr={point:De,lineStart:De,lineEnd:De,polygonStart:function(){Mr.lineStart=Ar,Mr.lineEnd=Pr},polygonEnd:function(){Mr.lineStart=Mr.lineEnd=Mr.point=De,Nr.add(je(kr)),kr=new t},result:function(){var n=Nr/2;return Nr=new t,n}};function Ar(){Mr.point=$r}function $r(t,n){Mr.point=Cr,wr=xr=t,br=Er=n}function Cr(t,n){kr.add(Er*t-xr*n),xr=t,Er=n}function Pr(){Cr(wr,br)}var jr=1/0,Rr=jr,Tr=-jr,qr=Tr,Or={point:function(t,n){tTr&&(Tr=t);nqr&&(qr=n)},lineStart:De,lineEnd:De,polygonStart:De,polygonEnd:De,result:function(){var t=[[jr,Rr],[Tr,qr]];return Tr=qr=-(Rr=jr=1/0),t}};var Lr,Xr,zr,Dr,Hr=0,Ir=0,Yr=0,Br=0,Fr=0,Vr=0,Gr=0,Ur=0,Zr=0,Wr={point:Kr,lineStart:Jr,lineEnd:ni,polygonStart:function(){Wr.lineStart=ei,Wr.lineEnd=ri},polygonEnd:function(){Wr.point=Kr,Wr.lineStart=Jr,Wr.lineEnd=ni},result:function(){var t=Zr?[Gr/Zr,Ur/Zr]:Vr?[Br/Vr,Fr/Vr]:Yr?[Hr/Yr,Ir/Yr]:[NaN,NaN];return Hr=Ir=Yr=Br=Fr=Vr=Gr=Ur=Zr=0,t}};function Kr(t,n){Hr+=t,Ir+=n,++Yr}function Jr(){Wr.point=Qr}function Qr(t,n){Wr.point=ti,Kr(zr=t,Dr=n)}function ti(t,n){var e=t-zr,r=n-Dr,i=Xe(e*e+r*r);Br+=i*(zr+t)/2,Fr+=i*(Dr+n)/2,Vr+=i,Kr(zr=t,Dr=n)}function ni(){Wr.point=Kr}function ei(){Wr.point=ii}function ri(){oi(Lr,Xr)}function ii(t,n){Wr.point=oi,Kr(Lr=zr=t,Xr=Dr=n)}function oi(t,n){var e=t-zr,r=n-Dr,i=Xe(e*e+r*r);Br+=i*(zr+t)/2,Fr+=i*(Dr+n)/2,Vr+=i,Gr+=(i=Dr*t-zr*n)*(zr+t),Ur+=i*(Dr+n),Zr+=3*i,Kr(zr=t,Dr=n)}function ui(t){this._context=t}ui.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._context.moveTo(t,n),this._point=1;break;case 1:this._context.lineTo(t,n);break;default:this._context.moveTo(t+this._radius,n),this._context.arc(t,n,this._radius,0,$e)}},result:De};var ai,li,si,ci,fi,hi=new t,pi={point:De,lineStart:function(){pi.point=di},lineEnd:function(){ai&&vi(li,si),pi.point=De},polygonStart:function(){ai=!0},polygonEnd:function(){ai=null},result:function(){var n=+hi;return hi=new t,n}};function di(t,n){pi.point=vi,li=ci=t,si=fi=n}function vi(t,n){ci-=t,fi-=n,hi.add(Xe(ci*ci+fi*fi)),ci=t,fi=n}let gi,yi,_i,mi;class wi{constructor(t){this._append=null==t?bi:function(t){const n=Math.floor(t);if(!(n>=0))throw new RangeError(`invalid digits: ${t}`);if(n>15)return bi;if(n!==gi){const t=10**n;gi=n,yi=function(n){let e=1;this._+=n[0];for(const r=n.length;e4*n&&v--){var w=u+h,b=a+p,x=l+d,E=Xe(w*w+b*b+x*x),S=ze(x/=E),N=je(je(x)-1)n||je((y*$+_*C)/m-.5)>.3||u*h+a*p+l*d2?t[2]%360*Pe:0,$()):[g*Ce,y*Ce,_*Ce]},M.angle=function(t){return arguments.length?(m=t%360*Pe,$()):m*Ce},M.reflectX=function(t){return arguments.length?(w=t?-1:1,$()):w<0},M.reflectY=function(t){return arguments.length?(b=t?-1:1,$()):b<0},M.precision=function(t){return arguments.length?(u=Ai(a,k=t*t),C()):Xe(k)},M.fitExtent=function(t,n){return Ni(M,t,n)},M.fitSize=function(t,n){return function(t,n,e){return Ni(t,[[0,0],n],e)}(M,t,n)},M.fitWidth=function(t,n){return function(t,n,e){return Si(t,(function(e){var r=+n,i=r/(e[1][0]-e[0][0]),o=(r-i*(e[1][0]+e[0][0]))/2,u=-i*e[0][1];t.scale(150*i).translate([o,u])}),e)}(M,t,n)},M.fitHeight=function(t,n){return function(t,n,e){return Si(t,(function(e){var r=+n,i=r/(e[1][1]-e[0][1]),o=-i*e[0][0],u=(r-i*(e[1][1]+e[0][1]))/2;t.scale(150*i).translate([o,u])}),e)}(M,t,n)},function(){return n=t.apply(this,arguments),M.invert=n.invert&&A,$()}}((function(){return t}))()}function Ri(t,n){return[qe(n)*Oe(t),Oe(n)]}function Ti(t,n,e){this.k=t,this.x=n,this.y=e}function qi(t){return t}function Oi(t,n){var e=n.id,r=n.bbox,i=null==n.properties?{}:n.properties,o=function(t,n){var e=function(t){if(null==t)return qi;var n,e,r=t.scale[0],i=t.scale[1],o=t.translate[0],u=t.translate[1];return function(t,a){a||(n=e=0);var l=2,s=t.length,c=new Array(s);for(c[0]=(n+=t[0])*r+o,c[1]=(e+=t[1])*i+u;l=0))throw new RangeError(`invalid digits: ${t}`);i=n}return null===n&&(r=new wi(i)),u},u.projection(t).digits(i).context(n)}(this.projection,r),this.globe={type:"Sphere"},this.land=(o=Li,"GeometryCollection"===(u=Li.objects.land).type?{type:"FeatureCollection",features:u.geometries.map((function(t){return Oi(o,t)}))}:Oi(o,u)),this._update(),n.on("move",this._update.bind(this))},_draw_marker:function(){const{globeSize:t,markerSize:n,markerColor:e}=this.options;mt(Xi).append("svg").attr("width",t).attr("height",t).attr("style","position: absolute; left: 0; top: 0;").append("path").attr("opacity",0).attr("d","M5.36018 5.33333C5.36018 4.59722 5.61972 3.96875 6.13881 3.44792C6.65789 2.92708 7.28426 2.66667 8.0179 2.66667C8.75154 2.66667 9.3779 2.92708 9.89699 3.44792C10.4161 3.96875 10.6756 4.59722 10.6756 5.33333C10.6756 6.06944 10.4161 6.69792 9.89699 7.21875C9.3779 7.73958 8.75154 8 8.0179 8C7.28426 8 6.65789 7.73958 6.13881 7.21875C5.61972 6.69792 5.36018 6.06944 5.36018 5.33333ZM2.70246 5.33333C2.70246 6.09028 2.81666 6.7118 3.04506 7.19792L6.824 15.2604C6.93474 15.4896 7.09911 15.6701 7.31713 15.8021C7.53515 15.934 7.76874 16 8.0179 16C8.26706 16 8.50065 15.934 8.71866 15.8021C8.93668 15.6701 9.09759 15.4896 9.20141 15.2604L12.9907 7.19792C13.2191 6.71181 13.3333 6.09028 13.3333 5.33333C13.3333 3.86111 12.8142 2.60417 11.7761 1.5625C10.7379 0.520833 9.48518 -8.13254e-07 8.0179 -9.41527e-07C6.55062 -1.0698e-06 5.29789 0.520832 4.25972 1.5625C3.22155 2.60417 2.70246 3.86111 2.70246 5.33333Z").attr("transform",`scale(${n}, ${n}), translate(${t*(1/n)/2-8}, ${t*(1/n)/2-16})`).attr("style","fill:"+e).transition().duration(100).attr("opacity",1)},_update:function(){const t=this,n=this._parentMap.getCenter();me().duration(this.initialTween?1e3:1).tween("rotate",(function(){const e=pn(t.projection.rotate(),[-n.lng,-n.lat]);return function(n){t.projection.rotate(e(n)),t.context.clearRect(0,0,t.canvas.width,t.canvas.height),t.context.fillStyle=t.options.waterColor,t.context.beginPath(),t.path(t.globe),t.context.fill(),t.context.fillStyle=t.options.landColor,t.context.beginPath(),t.path(t.land),t.context.fill()}})).on("end",(()=>{t.initialTween&&(t._draw_marker(),t.initialTween=!1)}))},_createContainer:function(t){const{globeSize:n,id:e}=this.options,r=document.createElement("div");return r.className="mapboxgl-ctrl-globe-minimap mapboxgl-ctrl",r.setAttribute("style","width: "+n+"; height: "+n+";"),r.addEventListener("contextmenu",this._preventDefault),t.getContainer().appendChild(r),""!==e&&(r.id=e),r},_preventDefault:function(t){t.preventDefault()}},window.GlobeMinimap=zi,zi}(); diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js new file mode 100644 index 0000000..207d876 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js @@ -0,0 +1,1102 @@ +/** + * mapbox-pmtiles v1.1.0 - Optimized Version with Lifecycle Management + * Original source: https://github.com/am2222/mapbox-pmtiles by Majid Hojati + * License: MIT + * + * This is an optimized version of the mapbox-pmtiles library that provides + * better performance for large datasets through: + * - Configurable resource management + * - Instance-scoped worker pools and caches + * - Proper lifecycle management and cleanup + * - Reference counting for shared resources + * - Enhanced error handling and timeouts + * - Memory optimization with size-based LRU caches + * + * Last updated: 2025 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + // Global shared resources with reference counting + const GLOBAL_SHARED_RESOURCES = { + // Protocol cache - expensive to duplicate, shared with reference counting + protocolCache: new Map(), // url -> { protocol, instance, refCount } + + // Metadata cache - small and shareable + metadataCache: new Map(), // cacheKey -> data + + // Pre-calculated world sizes for common zoom levels (static, no cleanup needed) + worldSizeCache: new Array(25).fill(null).map((_, z) => Math.pow(2, z)), + + // Global cleanup registry + activeManagers: new Set(), + + // Debug/development features + debug: false, + performanceMetrics: new Map(), + }; + + /** + * Default configuration options + */ + const DEFAULT_OPTIONS = { + workerPoolSize: 4, + tileCacheSize: 1000, + tileCacheMaxMemoryMB: 100, + metadataCacheSize: 100, + enableSharedProtocols: true, + requestTimeoutMs: 30000, + enableDebugLogging: false, + enablePerformanceMetrics: false, + }; + + /** + * LRU Cache implementation with size-based eviction + */ + class LRUCache { + constructor(maxSize, maxMemoryBytes = Infinity) { + this.maxSize = maxSize; + this.maxMemoryBytes = maxMemoryBytes; + this.cache = new Map(); + this.currentMemoryBytes = 0; + } + + get(key) { + if (this.cache.has(key)) { + // Move to end (most recently used) + const value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return value.data; + } + return undefined; + } + + set(key, data, estimatedSize = 0) { + // Remove if exists + if (this.cache.has(key)) { + const existing = this.cache.get(key); + this.currentMemoryBytes -= existing.size; + this.cache.delete(key); + } + + // Evict old entries if necessary + while ( + this.cache.size >= this.maxSize || + this.currentMemoryBytes + estimatedSize > this.maxMemoryBytes + ) { + const firstKey = this.cache.keys().next().value; + if (!firstKey) break; + + const firstValue = this.cache.get(firstKey); + this.currentMemoryBytes -= firstValue.size; + this.cache.delete(firstKey); + } + + // Add new entry + this.cache.set(key, { data, size: estimatedSize }); + this.currentMemoryBytes += estimatedSize; + } + + has(key) { + return this.cache.has(key); + } + + delete(key) { + if (this.cache.has(key)) { + const value = this.cache.get(key); + this.currentMemoryBytes -= value.size; + this.cache.delete(key); + return true; + } + return false; + } + + clear() { + this.cache.clear(); + this.currentMemoryBytes = 0; + } + + get size() { + return this.cache.size; + } + + getMemoryUsage() { + return { + entries: this.cache.size, + memoryBytes: this.currentMemoryBytes, + memoryMB: this.currentMemoryBytes / (1024 * 1024), + }; + } + } + + /** + * Resource Manager - handles per-instance resources and lifecycle + */ + class PMTilesResourceManager { + constructor(options = {}) { + this.config = { ...DEFAULT_OPTIONS, ...options }; + this.destroyed = false; + this.paused = false; + this.dispatcher = null; + + // Instance-scoped resources + this.workerPool = []; + this.workerPoolIndex = 0; + this.tileCache = new LRUCache( + this.config.tileCacheSize, + this.config.tileCacheMaxMemoryMB * 1024 * 1024, + ); + this.pendingRequests = new Map(); + this.activeRequests = new Set(); + + // Performance tracking + this.metrics = { + tilesLoaded: 0, + cacheHits: 0, + cacheMisses: 0, + memoryPeakMB: 0, + averageLoadTimeMs: 0, + }; + + // Register for global cleanup + GLOBAL_SHARED_RESOURCES.activeManagers.add(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager created", this.config); + } + } + + /** + * Initialize worker pool + */ + initializeWorkerPool(dispatcher) { + if (this.destroyed) return; + + // Store dispatcher reference + if (dispatcher) { + this.dispatcher = dispatcher; + } + + if (this.workerPool.length === 0 && this.dispatcher) { + for (let i = 0; i < this.config.workerPoolSize; i++) { + try { + this.workerPool.push(this.dispatcher.getActor()); + } catch (error) { + console.warn("[PMTiles] Failed to create worker:", error); + } + } + + if (this.config.enableDebugLogging) { + console.log( + `[PMTiles] Initialized worker pool with ${this.workerPool.length} workers`, + ); + } + } + } + + /** + * Get next worker from pool (round-robin) + */ + getWorkerFromPool() { + if (this.destroyed) { + return null; + } + + // Try to initialize workers if not done yet + if (this.workerPool.length === 0 && this.dispatcher) { + this.initializeWorkerPool(this.dispatcher); + } + + if (this.workerPool.length === 0) { + if (this.config.enableDebugLogging) { + console.warn( + "[PMTiles] Worker pool is empty, dispatcher available:", + !!this.dispatcher, + ); + } + return null; + } + + const worker = this.workerPool[this.workerPoolIndex]; + this.workerPoolIndex = + (this.workerPoolIndex + 1) % this.workerPool.length; + return worker; + } + + /** + * Get or create protocol instance with reference counting + */ + getProtocol(url) { + if (this.destroyed) return null; + + if (!this.config.enableSharedProtocols) { + // Create instance-specific protocol + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + return { protocol, instance }; + } + + // Use shared protocol with reference counting + if (!GLOBAL_SHARED_RESOURCES.protocolCache.has(url)) { + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + GLOBAL_SHARED_RESOURCES.protocolCache.set(url, { + protocol, + instance, + refCount: 0, + }); + } + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + cached.refCount++; + return cached; + } + + /** + * Release protocol reference + */ + releaseProtocol(url) { + if (!this.config.enableSharedProtocols) return; + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + if (cached) { + cached.refCount--; + if (cached.refCount <= 0) { + GLOBAL_SHARED_RESOURCES.protocolCache.delete(url); + + if (this.config.enableDebugLogging) { + console.log(`[PMTiles] Released protocol for ${url}`); + } + } + } + } + + /** + * Cache key for tiles + */ + getTileCacheKey(url, z, x, y) { + return `${url}:${z}:${x}:${y}`; + } + + /** + * Add tile to cache with size estimation + */ + addToTileCache(key, data) { + if (this.destroyed) return; + + let estimatedSize = 0; + if (data instanceof ImageBitmap) { + // Rough estimation: width * height * 4 bytes per pixel + estimatedSize = data.width * data.height * 4; + } else if (data && data.byteLength) { + estimatedSize = data.byteLength; + } else { + estimatedSize = 10000; // Default estimate + } + + this.tileCache.set(key, data, estimatedSize); + + // Update peak memory usage + const memoryUsage = this.tileCache.getMemoryUsage(); + this.metrics.memoryPeakMB = Math.max( + this.metrics.memoryPeakMB, + memoryUsage.memoryMB, + ); + } + + /** + * Get cached metadata + */ + getCachedMetadata(cacheKey) { + return GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + } + + /** + * Set cached metadata + */ + setCachedMetadata(cacheKey, data) { + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, data); + } + + /** + * Pause all operations + */ + pause() { + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager paused"); + } + } + + /** + * Resume operations + */ + resume() { + this.paused = false; + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager resumed"); + } + } + + /** + * Get performance metrics + */ + getMetrics() { + return { + ...this.metrics, + tileCache: this.tileCache.getMemoryUsage(), + workerPoolSize: this.workerPool.length, + pendingRequests: this.pendingRequests.size, + isPaused: this.paused, + isDestroyed: this.destroyed, + }; + } + + /** + * Destroy and cleanup all resources + */ + destroy() { + if (this.destroyed) return; + + this.destroyed = true; + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + // Clear caches + this.tileCache.clear(); + + // Clear worker pool references + this.workerPool.length = 0; + + // Remove from global registry + GLOBAL_SHARED_RESOURCES.activeManagers.delete(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager destroyed", this.getMetrics()); + } + } + } + + /** + * Global cleanup function + */ + const cleanup = () => { + for (const manager of GLOBAL_SHARED_RESOURCES.activeManagers) { + manager.destroy(); + } + GLOBAL_SHARED_RESOURCES.protocolCache.clear(); + GLOBAL_SHARED_RESOURCES.metadataCache.clear(); + }; + + // Register global cleanup + if (typeof window !== "undefined") { + window.addEventListener("beforeunload", cleanup); + } + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + + // Pre-calculate mercator bounds + this._mercatorBounds = { + west: mercatorXFromLng(this.bounds.getWest()), + north: mercatorYFromLat(this.bounds.getNorth()), + east: mercatorXFromLng(this.bounds.getEast()), + south: mercatorYFromLat(this.bounds.getSouth()), + }; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + // Use pre-calculated world size + const worldSize = + GLOBAL_SHARED_RESOURCES.worldSizeCache[tileID.z] || + Math.pow(2, tileID.z); + + // Use pre-calculated mercator bounds + const level = { + minX: Math.floor(this._mercatorBounds.west * worldSize), + minY: Math.floor(this._mercatorBounds.north * worldSize), + maxX: Math.ceil(this._mercatorBounds.east * worldSize), + maxY: Math.ceil(this._mercatorBounds.south * worldSize), + }; + + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + /** + * Enhanced PMTiles Source with lifecycle management + */ + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + + // Extract PMTiles-specific options + const pmtilesOptions = { + workerPoolSize: options.workerPoolSize, + tileCacheSize: options.tileCacheSize, + tileCacheMaxMemoryMB: options.tileCacheMaxMemoryMB, + metadataCacheSize: options.metadataCacheSize, + enableSharedProtocols: options.enableSharedProtocols, + requestTimeoutMs: options.requestTimeoutMs, + enableDebugLogging: options.enableDebugLogging, + enablePerformanceMetrics: options.enablePerformanceMetrics, + }; + + // Initialize resource manager + this.resourceManager = new PMTilesResourceManager(pmtilesOptions); + + // Standard source properties + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = _dispatcher; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._implementation = options; + + // Initialize worker pool + this.resourceManager.initializeWorkerPool(_dispatcher); + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + return; + } + + const { url } = options; + this.url = url; + this.tileSize = 512; + + // Get protocol instance + this.protocolInfo = this.resourceManager.getProtocol(url); + if (!this.protocolInfo) { + this.fire( + new ErrorEvent(new Error(`Failed to create protocol for ${url}`)), + ); + return; + } + + this._protocol = this.protocolInfo.protocol; + this._instance = this.protocolInfo.instance; + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + } + + static async getMetadata(url) { + // Check cache first + const cacheKey = `${url}:metadata`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const metadata = await instance.getMetadata(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, metadata); + return metadata; + } + + static async getHeader(url) { + // Check cache first + const cacheKey = `${url}:header`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const header = await instance.getHeader(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, header); + return header; + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (this.resourceManager.destroyed) return; + + if (!tile.destroy) { + tile.destroy = () => {}; + } + if (!tile.abort) { + tile.abort = () => { + tile.aborted = true; + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + }; + } + } + + /** + * Pause tile loading + */ + pause() { + this.resourceManager.pause(); + } + + /** + * Resume tile loading + */ + resume() { + this.resourceManager.resume(); + } + + /** + * Get performance metrics + */ + getMetrics() { + return this.resourceManager.getMetrics(); + } + + /** + * Destroy source and cleanup resources + */ + destroy() { + if (this.protocolInfo && this.url) { + this.resourceManager.releaseProtocol(this.url); + } + + this.resourceManager.destroy(); + this._loaded = false; + } + + async load(callback) { + if (this.resourceManager.destroyed) { + const error = new Error("Source has been destroyed"); + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + // Check metadata cache first + const headerKey = `${this.url}:header`; + const metadataKey = `${this.url}:metadata`; + + let header, tileJSON; + + const cachedHeader = this.resourceManager.getCachedMetadata(headerKey); + const cachedMetadata = + this.resourceManager.getCachedMetadata(metadataKey); + + if (cachedHeader && cachedMetadata) { + header = cachedHeader; + tileJSON = cachedMetadata; + } else { + try { + // Load and cache + [header, tileJSON] = await Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]); + this.resourceManager.setCachedMetadata(headerKey, header); + this.resourceManager.setCachedMetadata(metadataKey, tileJSON); + } catch (error) { + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + } + + try { + extend(this, tileJSON); + this.header = header; + const { tileType, minZoom, maxZoom, minLon, minLat, maxLon, maxLat } = + header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes(this.tileType) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { dataType: "source", sourceDataType: "metadata" }), + ); + this.fire( + new Event("data", { dataType: "source", sourceDataType: "content" }), + ); + } catch (err2) { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + } + } + + loaded() { + return this._loaded && !this.resourceManager.destroyed; + } + + loadVectorTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + const startTime = Date.now(); + var _a2, _b2, _c; + + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + + // Update metrics + this.resourceManager.metrics.tilesLoaded++; + const loadTime = Date.now() - startTime; + this.resourceManager.metrics.averageLoadTimeMs = + (this.resourceManager.metrics.averageLoadTimeMs + loadTime) / 2; + + if (tile.aborted) return callback(null); + + // Handle abort errors gracefully + if (err2 && err2.name === "AbortError") { + return callback(null); + } + + if (err2 && err2.status !== 404) { + return callback(err2); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + // Handle abort errors gracefully + if (error && (error.name === "AbortError" || error.code === 20)) { + return done.call(this, null); + } + done.call(this, error); + return; + } + + params.data = { + cacheControl, + expires, + rawData: data, + }; + + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + // Use shared worker pool + tile.actor = this.resourceManager.getWorkerFromPool(); + + // Fallback to dispatcher if worker pool failed + if (!tile.actor && this.dispatcher) { + try { + tile.actor = this.dispatcher.getActor(); + } catch (error) { + console.warn("[PMTiles] Failed to get fallback worker:", error); + return callback(new Error("No workers available")); + } + } + + if (!tile.actor) { + return callback(new Error("No workers available")); + } + + // Create request with timeout + const requestPromise = this._protocol.tile({ ...request }, afterLoad); + + // Add timeout if configured + if (this.resourceManager.config.requestTimeoutMs > 0) { + const timeoutId = setTimeout(() => { + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + done.call(this, new Error("Request timeout")); + }, this.resourceManager.config.requestTimeoutMs); + + const originalCancel = requestPromise.cancel; + requestPromise.cancel = () => { + clearTimeout(timeoutId); + if (originalCancel) originalCancel(); + }; + } + + tile.request = requestPromise; + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + if (this.resourceManager.destroyed) return; + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + var _a2, _b2; + + // Check tile cache first + const cacheKey = this.resourceManager.getTileCacheKey( + this.url, + tile.tileID.canonical.z, + tile.tileID.canonical.x, + tile.tileID.canonical.y, + ); + + if (this.resourceManager.tileCache.has(cacheKey)) { + this.resourceManager.metrics.cacheHits++; + const cachedData = this.resourceManager.tileCache.get(cacheKey); + this.loadRasterTileData(tile, cachedData); + tile.state = "loaded"; + return callback(null); + } + + this.resourceManager.metrics.cacheMisses++; + + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + + // Optimized raster tile loading - try direct ArrayBuffer first + const arrayBuffer = data.buffer || data; + window + .createImageBitmap(arrayBuffer) + .then((imageBitmap) => { + // Cache the decoded image + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + // Fallback to blob method + const blob = new window.Blob([new Uint8Array(data)], { + type: this.contentType, + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error(`Can't decode image for ${this.id}: ${error}`), + ); + }); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + this.fixTile(tile); + const controller = new AbortController(); + + // Add timeout if configured + let timeoutId; + if (this.resourceManager.config.requestTimeoutMs > 0) { + timeoutId = setTimeout(() => { + controller.abort(); + }, this.resourceManager.config.requestTimeoutMs); + } + + tile.request = { + cancel: () => { + if (timeoutId) clearTimeout(timeoutId); + controller.abort(); + }, + }; + + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (timeoutId) clearTimeout(timeoutId); + + // Handle abort errors gracefully + if (error.name === "AbortError" || error.code === 20) { + delete tile.request; + return callback(null); + } + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Expose cleanup function + PmTilesSource.cleanup = cleanup; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; + global.PMTilesResourceManager = PMTilesResourceManager; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js new file mode 100644 index 0000000..2130749 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/mapbox-pmtiles/pmtiles-source.js @@ -0,0 +1,459 @@ +/** + * mapbox-pmtiles v1.0.53 + * Original source: https://github.com/am2222/mapbox-pmtiles + * License: MIT + * + * This is a vendored copy of the mapbox-pmtiles library that provides + * PMTiles support for Mapbox GL JS by implementing a custom source type. + * + * Last updated: 2024 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + const worldSize = Math.pow(2, tileID.z); + const level = { + minX: Math.floor(mercatorXFromLng(this.bounds.getWest()) * worldSize), + minY: Math.floor(mercatorYFromLat(this.bounds.getNorth()) * worldSize), + maxX: Math.ceil(mercatorXFromLng(this.bounds.getEast()) * worldSize), + maxY: Math.ceil(mercatorYFromLat(this.bounds.getSouth()) * worldSize), + }; + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = void 0; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._dataType = "vector"; + this.dispatcher = _dispatcher; + this._implementation = options; + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + } + + const { url } = options; + this.reparseOverscaled = true; + this.scheme = "xyz"; + this.tileSize = 512; + this._loaded = false; + this.type = "vector"; + this._protocol = new pmtiles.Protocol(); + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + const pmtilesInstance = new pmtiles.PMTiles(url); + this._protocol.add(pmtilesInstance); + this._instance = pmtilesInstance; + } + + static async getMetadata(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getMetadata(); + } + + static async getHeader(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getHeader(); + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (!tile.destroy) { + tile.destroy = () => {}; + } + } + + async load(callback) { + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + return Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]) + .then(([header, tileJSON]) => { + extend(this, tileJSON); + this.header = header; + const { + specVersion, + clustered, + tileType, + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + centerZoom, + centerLon, + centerLat, + } = header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes( + this.tileType, + ) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "metadata", + }), + ); + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "content", + }), + ); + }) + .catch((err2) => { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + }); + } + + loaded() { + return this._loaded; + } + + loadVectorTile(tile, callback) { + var _a2, _b2, _c; + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + if (tile.aborted) return callback(null); + if (err2 && err2.status !== 404) { + return callback(err2); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + done.call(this, error); + return; + } + params.data = { + cacheControl, + expires, + rawData: data, + }; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + tile.actor = this._tileWorkers[url] = + this._tileWorkers[url] || this.dispatcher.getActor(); + tile.request = this._protocol.tile({ ...request }, afterLoad); + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + var _a2, _b2; + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + const blob = new window.Blob([new Uint8Array(data)], { + type: "image/png", + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error( + `Can't infer data type for ${this.id}, only raster data supported at the moment. ${error}`, + ), + ); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + this.fixTile(tile); + const controller = new AbortController(); + tile.request = { cancel: () => controller.abort() }; + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (error.code === 20) return; + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; +})(typeof window !== "undefined" ? window : this); diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css b/docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css new file mode 100644 index 0000000..16b2196 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.css @@ -0,0 +1,44 @@ +.maplibregl-compare { + background-color: #fff; + position: absolute; + width: 2px; + height: 100%; + z-index: 1; +} +.maplibregl-compare .compare-swiper-vertical { + background-color: #3887be; + box-shadow: inset 0 0 0 2px #fff; + display: inline-block; + border-radius: 50%; + position: absolute; + width: 60px; + height: 60px; + top: 50%; + left: -30px; + margin: -30px 1px 0; + color: #fff; + cursor: ew-resize; + background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgd2lkdGg9IjYwIiAgIGhlaWdodD0iNjAiICAgdmVyc2lvbj0iMS4xIiAgIHZpZXdCb3g9IjAgMCA2MCA2MCIgICBpZD0ic3ZnNTQzNCIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxK2RldmVsK29zeG1lbnUgcjEyOTExIiAgIHNvZGlwb2RpOmRvY25hbWU9Imwtci5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE1NDQ0Ij4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgICAgPGRjOnRpdGxlPjwvZGM6dGl0bGU+ICAgICAgPC9jYzpXb3JrPiAgICA8L3JkZjpSREY+ICA8L21ldGFkYXRhPiAgPGRlZnMgICAgIGlkPSJkZWZzNTQ0MiIgLz4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTI4NiIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9Ijc1MSIgICAgIGlkPSJuYW1lZHZpZXc1NDQwIiAgICAgc2hvd2dyaWQ9InRydWUiICAgICBpbmtzY2FwZTp6b29tPSI0IiAgICAgaW5rc2NhcGU6Y3g9IjI1Ljg4OTgzMSIgICAgIGlua3NjYXBlOmN5PSIzNC4zODE4MzMiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyMyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjAiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJzdmc1NDM0IiAgICAgaW5rc2NhcGU6b2JqZWN0LW5vZGVzPSJ0cnVlIiAgICAgaW5rc2NhcGU6c25hcC1zbW9vdGgtbm9kZXM9InRydWUiPiAgICA8aW5rc2NhcGU6Z3JpZCAgICAgICB0eXBlPSJ4eWdyaWQiICAgICAgIGlkPSJncmlkNTk4OSIgLz4gIDwvc29kaXBvZGk6bmFtZWR2aWV3PiAgPHBhdGggICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjFweDtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIiAgICAgZD0iTSAyNSAyNCBMIDE2IDMwIEwgMjUgMzYgTCAyNSAyNCB6IE0gMzUgMjQgTCAzNSAzNiBMIDQ0IDMwIEwgMzUgMjQgeiAiICAgICBpZD0icGF0aDU5OTUiIC8+PC9zdmc+); +} + +.maplibregl-compare-horizontal { + position: relative; + width: 100%; + height: 2px; +} +.maplibregl-compare .compare-swiper-horizontal { + background-color: #3887be; + box-shadow: inset 0 0 0 2px #fff; + display: inline-block; + border-radius: 50%; + position: absolute; + width: 60px; + height: 60px; + top: 50%; + left: 50%; + margin: -30px 1px 0; + color: #fff; + cursor: ns-resize; + background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgd2lkdGg9IjYwIiAgIGhlaWdodD0iNjAiICAgdmVyc2lvbj0iMS4xIiAgIHZpZXdCb3g9IjAgMCA2MCA2MCIgICBpZD0ic3ZnNTQzNCIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxK2RldmVsK29zeG1lbnUgcjEyOTExIiAgIHNvZGlwb2RpOmRvY25hbWU9Imwtci5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE1NDQ0Ij4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgICAgPGRjOnRpdGxlPjwvZGM6dGl0bGU+ICAgICAgPC9jYzpXb3JrPiAgICA8L3JkZjpSREY+ICA8L21ldGFkYXRhPiAgPGRlZnMgICAgIGlkPSJkZWZzNTQ0MiIgLz4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTI4NiIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9Ijc1MSIgICAgIGlkPSJuYW1lZHZpZXc1NDQwIiAgICAgc2hvd2dyaWQ9InRydWUiICAgICBpbmtzY2FwZTp6b29tPSI0IiAgICAgaW5rc2NhcGU6Y3g9IjI1Ljg4OTgzMSIgICAgIGlua3NjYXBlOmN5PSIzNC4zODE4MzMiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyMyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjAiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJzdmc1NDM0IiAgICAgaW5rc2NhcGU6b2JqZWN0LW5vZGVzPSJ0cnVlIiAgICAgaW5rc2NhcGU6c25hcC1zbW9vdGgtbm9kZXM9InRydWUiPiAgICA8aW5rc2NhcGU6Z3JpZCAgICAgICB0eXBlPSJ4eWdyaWQiICAgICAgIGlkPSJncmlkNTk4OSIgLz4gIDwvc29kaXBvZGk6bmFtZWR2aWV3PiAgPHBhdGggICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjFweDtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIiAgICAgZD0iTSAyNSAyNCBMIDE2IDMwIEwgMjUgMzYgTCAyNSAyNCB6IE0gMzUgMjQgTCAzNSAzNiBMIDQ0IDMwIEwgMzUgMjQgeiAiICAgICBpZD0icGF0aDU5OTUiIC8+PC9zdmc+); + transform: rotate(90deg); +} diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js new file mode 100644 index 0000000..71e47d5 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-compare/maplibre-gl-compare.js @@ -0,0 +1 @@ +!function o(i,r,s){function h(t,e){if(!r[t]){if(!i[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(u)return u(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=r[t]={exports:{}},i[t][0].call(n.exports,function(e){return h(i[t][1][e]||e)},n,n.exports,o,i,r,s)}return r[t].exports}for(var u="function"==typeof require&&require,e=0;ethis._bounds.width?this._bounds.width:e},_getY:function(e){e=(e=e.touches?e.touches[0]:e).clientY-this._bounds.top;return e=(e=e<0?0:e)>this._bounds.height?this._bounds.height:e},setSlider:function(e){this._setPosition(e)},on:function(e,t){return this._ev.on(e,t),this},fire:function(e,t){return this._ev.emit(e,t),this},off:function(e,t){return this._ev.removeListener(e,t),this},remove:function(){this._clearSync(),this._mapB.off("resize",this._onResize);var e=this._mapA.getContainer();e&&(e.style.clip=null,e.removeEventListener("mousemove",this._onMove));e=this._mapB.getContainer();e&&(e.style.clip=null,e.removeEventListener("mousemove",this._onMove)),this._swiper.removeEventListener("mousedown",this._onDown),this._swiper.removeEventListener("touchstart",this._onDown),this._controlContainer.remove()}},window.maplibregl?maplibregl.Compare=o:void 0!==t&&(t.exports=o)},{"@mapbox/mapbox-gl-sync-move":2,events:3}],2:[function(e,t,n){t.exports=function(){var e=arguments.length;if(1===e)t=arguments[0];else for(var t=[],n=0;nn&&!r.warned&&(r.warned=!0,(n=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit")).name="MaxListenersExceededWarning",n.emitter=e,n.type=t,n.count=r.length,n=n,console&&console.warn&&console.warn(n))),e}function l(e,t,n){e={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},t=function(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}.bind(e);return t.listener=n,e.wrapFn=t}function p(e,t,n){e=e._events;if(void 0===e)return[];t=e[t];return void 0===t?[]:"function"==typeof t?n?[t.listener||t]:[t]:n?function(e){for(var t=new Array(e.length),n=0;n * { + z-index: 2; + position: absolute; + right: 8px; + top: 7px; + display: none; +} + +.maplibregl-ctrl-geocoder, +.maplibregl-ctrl-geocoder .suggestions { + box-shadow: 0 0 10px 2px rgba(0, 0, 0, 0.1); +} + +/* Collapsed */ +.maplibregl-ctrl-geocoder.maplibregl-ctrl-geocoder--collapsed { + width: 50px; + min-width: 50px; + transition: width 0.25s, min-width 0.25s; +} + +/* Suggestions */ +.maplibregl-ctrl-geocoder .suggestions { + background-color: #fff; + border-radius: 4px; + left: 0; + list-style: none; + margin: 0; + padding: 0; + position: absolute; + width: 100%; + top: 110%; /* fallback */ + top: calc(100% + 6px); + z-index: 1000; + overflow: hidden; + font-size: 15px; +} + +.maplibregl-ctrl-bottom-left .suggestions, +.maplibregl-ctrl-bottom-right .suggestions { + top: auto; + bottom: 100%; +} + +.maplibregl-ctrl-geocoder .suggestions > li > a { + cursor: default; + display: block; + padding: 6px 12px; + color: #404040; +} + +.maplibregl-ctrl-geocoder .suggestions > .active > a, +.maplibregl-ctrl-geocoder .suggestions > li > a:hover { + color: #404040; + background-color: #f3f3f3; + text-decoration: none; + cursor: pointer; +} + +.maplibregl-ctrl-geocoder--suggestion { + display: flex; + flex-direction: row; + align-items: center; +} + +.maplibre-ctrl-geocoder--suggestion-icon { + min-width: 30px; + min-height: 24px; + max-width: 30px; + max-height: 24px; + padding-right: 12px; +} + +.maplibregl-ctrl-geocoder--suggestion-info { + display: flex; + flex-direction: column; +} + +.maplibregl-ctrl-geocoder--suggestion-match { + font-weight: bold; +} + +.maplibregl-ctrl-geocoder--suggestion-title, +.maplibregl-ctrl-geocoder--suggestion-address { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +.maplibregl-ctrl-geocoder--result { + display: flex; + flex-direction: row; + align-items: center; +} + +.maplibre-ctrl-geocoder--result-icon { + min-width: 30px; + min-height: 24px; + max-width: 30px; + max-height: 24px; + padding-right: 12px; +} + +.maplibregl-ctrl-geocoder--result-title { + font-weight: bold; +} + +.maplibregl-ctrl-geocoder--result-title, +.maplibregl-ctrl-geocoder--result-address { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +/* Icons */ +.maplibregl-ctrl-geocoder--icon { + display: inline-block; + vertical-align: middle; + speak: none; + fill: #757575; + top: 15px; +} + +.maplibregl-ctrl-geocoder--icon-search { + position: absolute; + top: 13px; + left: 12px; + width: 23px; + height: 23px; +} + +.maplibregl-ctrl-geocoder--button { + padding: 0; + margin: 0; + border: none; + cursor: pointer; + background: #fff; + line-height: 1; +} + +.maplibregl-ctrl-geocoder--icon-close { + width: 20px; + height: 20px; + margin-top: 8px; + margin-right: 3px; +} + +.maplibregl-ctrl-geocoder--button:hover .maplibregl-ctrl-geocoder--icon-close { + fill: #909090; +} + +.maplibregl-ctrl-geocoder--icon-loading { + width: 26px; + height: 26px; + margin-top: 5px; + margin-right: 0px; + -moz-animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); + -webkit-animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); + animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); +} + +/* Animation */ +@-webkit-keyframes rotate { + from { + -webkit-transform: rotate(0); + transform: rotate(0); + } + to { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +@keyframes rotate { + from { + -webkit-transform: rotate(0); + transform: rotate(0); + } + to { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +/* Media queries*/ +@media screen and (min-width: 640px) { + .maplibregl-ctrl-geocoder.maplibregl-ctrl-geocoder--collapsed { + width: 36px; + min-width: 36px; + } + + .maplibregl-ctrl-geocoder { + width: 33.3333%; + font-size: 15px; + line-height: 20px; + max-width: 360px; + } + .maplibregl-ctrl-geocoder .suggestions { + font-size: 13px; + } + + .maplibregl-ctrl-geocoder--icon { + top: 8px; + } + + .maplibregl-ctrl-geocoder--icon-close { + width: 16px; + height: 16px; + margin-top: 3px; + margin-right: 0; + } + + .maplibregl-ctrl-geocoder--icon-search { + left: 7px; + width: 20px; + height: 20px; + } + + .maplibregl-ctrl-geocoder--input { + height: 36px; + padding: 6px 35px; + } + + .maplibregl-ctrl-geocoder--icon-loading { + width: 26px; + height: 26px; + margin-top: -2px; + margin-right: -5px; + } + + .maplibre-gl-geocoder--error { + color: #909090; + padding: 6px 12px; + font-size: 16px; + text-align: center; + } +} diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js new file mode 100644 index 0000000..e285a1a --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl-geocoder/maplibre-gl-geocoder.min.js @@ -0,0 +1,2 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.MaplibreGeocoder=t()}}(function(){return function(){function t(e,i,n){function s(o,l){if(!i[o]){if(!e[o]){var a="function"==typeof require&&require;if(!l&&a)return a(o,!0);if(r)return r(o,!0);var h=new Error("Cannot find module '"+o+"'");throw h.code="MODULE_NOT_FOUND",h}var u=i[o]={exports:{}};e[o][0].call(u.exports,function(t){return s(e[o][1][t]||t)},u,u.exports,t,e,i,n)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o
'+e[0]+'
'+e.splice(1,e.length).join(",")+"
"}var i=t.text,n=i.toLowerCase().indexOf(this.query.toLowerCase()),s=this.query.length;return'
'+i.substring(0,n)+''+i.substring(n,n+s)+""+i.substring(n+s)+"
"},popupRender:function(t){var e=t.place_name.split(",");return'"},showResultMarkers:!0,debounceSearch:200},addTo:function(t){function e(t,e){if(!document.body.contains(e))throw new Error("Element provided to #addTo() exists, but is not in the DOM");var i=t.onAdd();e.appendChild(i)}if(t._controlContainer)t.addControl(this);else if(t instanceof HTMLElement)e(this,t);else{if("string"!=typeof t)throw new Error("Error: addTo must be a maplibre-gl-js map, an html element, or a CSS selector query for a single html element");var i=document.querySelectorAll(t);if(0===i.length)throw new Error("Element ",t,"not found.");if(i.length>1)throw new Error("Geocoder can only be added to a single html element");e(this,i[0])}},onAdd:function(t){if(t&&"string"!=typeof t&&(this._map=t),this.setLanguage(),this.options.localGeocoderOnly&&!this.options.localGeocoder)throw new Error("A localGeocoder function must be specified to use localGeocoderOnly mode");this._onChange=this._onChange.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPaste=this._onPaste.bind(this),this._onBlur=this._onBlur.bind(this),this._showButton=this._showButton.bind(this),this._hideButton=this._hideButton.bind(this),this._onQueryResult=this._onQueryResult.bind(this),this.clear=this.clear.bind(this),this._updateProximity=this._updateProximity.bind(this),this._collapse=this._collapse.bind(this),this._unCollapse=this._unCollapse.bind(this),this._clear=this._clear.bind(this),this._clearOnBlur=this._clearOnBlur.bind(this);var e=this.container=document.createElement("div");e.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl";var i=this.createIcon("search",'');this._inputEl=document.createElement("input"),this._inputEl.type="text",this._inputEl.className="mapboxgl-ctrl-geocoder--input maplibregl-ctrl-geocoder--input",this.setPlaceholder(),this.options.collapsed&&(this._collapse(),this.container.addEventListener("mouseenter",this._unCollapse),this.container.addEventListener("mouseleave",this._collapse),this._inputEl.addEventListener("focus",this._unCollapse)),(this.options.collapsed||this.options.clearOnBlur)&&this._inputEl.addEventListener("blur",this._onBlur),this._inputEl.addEventListener("keydown",r(this._onKeyDown,this.options.debounceSearch)),this._inputEl.addEventListener("paste",this._onPaste),this._inputEl.addEventListener("change",this._onChange),this.container.addEventListener("mouseenter",this._showButton),this.container.addEventListener("mouseleave",this._hideButton);var n=document.createElement("div");n.classList.add("mapboxgl-ctrl-geocoder--pin-right","maplibregl-ctrl-geocoder--pin-right"),this._clearEl=document.createElement("button"),this._clearEl.setAttribute("aria-label","Clear"),this._clearEl.addEventListener("click",this.clear),this._clearEl.className="mapboxgl-ctrl-geocoder--button maplibregl-ctrl-geocoder--button";var o=this.createIcon("close",'');return this._clearEl.appendChild(o),this._loadingEl=this.createIcon("loading",''),n.appendChild(this._clearEl),n.appendChild(this._loadingEl),e.appendChild(i),e.appendChild(this._inputEl),e.appendChild(n),this._typeahead=new s(this._inputEl,[],{filter:!1,minLength:this.options.minLength,limit:this.options.limit,noInitialSelection:!0}),this.setRenderFunction(this.options.render),this._typeahead.getItemValue=this.options.getItemValue,this.mapMarker=null,this.resultMarkers=[],this._handleMarker=this._handleMarker.bind(this),this._handleResultMarkers=this._handleResultMarkers.bind(this),this._map&&(this.options.trackProximity&&(this._updateProximity(),this._map.on("moveend",this._updateProximity)),this._maplibregl=this.options.maplibregl,!this._maplibregl&&this.options.marker&&(console.error("No maplibregl detected in options. Map markers are disabled. Please set options.maplibregl."),this.options.marker=!1)),e},createIcon:function(t,e){var i=document.createElementNS("http://www.w3.org/2000/svg","svg");if(i.setAttribute("class","mapboxgl-ctrl-geocoder--icon mapboxgl-ctrl-geocoder--icon-"+t+" maplibregl-ctrl-geocoder--icon maplibregl-ctrl-geocoder--icon-"+t),i.setAttribute("viewBox","0 0 18 18"),i.setAttribute("xml:space","preserve"),i.setAttribute("width",18),i.setAttribute("height",18),"innerHTML"in i)i.innerHTML=e;else{var n=document.createElement("div");n.innerHTML=""+e.valueOf().toString()+"";var s=n.firstChild,r=s.firstChild;i.appendChild(r)}return i},onRemove:function(){return this.container.parentNode.removeChild(this.container),this.options.trackProximity&&this._map&&this._map.off("moveend",this._updateProximity),this._removeMarker(),this._map=null,this},_onPaste:function(t){var e=(t.clipboardData||window.clipboardData).getData("text");e.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(e)},_onKeyDown:function(t){if(27===t.keyCode&&this.options.clearAndBlurOnEsc)return this._clear(t),this._inputEl.blur();var e=t.target&&t.target.shadowRoot?t.target.shadowRoot.activeElement:t.target;if(!(e?e.value:""))return this.fresh=!0,9!==t.keyCode&&this.clear(t),this._clearEl.style.display="none";if(!t.metaKey&&-1===[9,27,37,39,38,40].indexOf(t.keyCode)){if(13===t.keyCode){if(this.options.showResultsWhileTyping)return void(null==this._typeahead.selected&&this.geocoderApi.getSuggestions?this._geocode(e.value,!0):null==this._typeahead.selected&&this.options.showResultMarkers&&this._fitBoundsForMarkers());this._typeahead.selected||this._geocode(e.value)}e.value.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(e.value)}},_showButton:function(){this._inputEl.value.length>0&&(this._clearEl.style.display="block")},_hideButton:function(){this._typeahead.selected&&(this._clearEl.style.display="none")},_onBlur:function(t){this.options.clearOnBlur&&this._clearOnBlur(t),this.options.collapsed&&this._collapse()},_onChange:function(){var t=this._typeahead.selected;if(t&&!t.geometry)t.placeId?this._geocode(t.placeId,!0,!0):this._geocode(t.text,!0);else if(t&&JSON.stringify(t)!==this.lastSelected){if(this._clearEl.style.display="none",this.options.flyTo){var e;if(this._removeResultMarkers(),t.properties&&a[t.properties.short_code])e=o({},this.options.flyTo),this._map&&this._map.fitBounds(a[t.properties.short_code].bbox,e);else if(t.bbox){var i=t.bbox;e=o({},this.options.flyTo),this._map&&this._map.fitBounds([[i[0],i[1]],[i[2],i[3]]],e)}else{var n={zoom:this.options.zoom};e=o({},n,this.options.flyTo),t.center?e.center=t.center:t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(e.center=t.geometry.coordinates),this._map&&this._map.flyTo(e)}}this.options.marker&&this._maplibregl&&this._handleMarker(t),this._inputEl.focus(),this._inputEl.scrollLeft=0,this._inputEl.setSelectionRange(0,0),this.lastSelected=JSON.stringify(t),this._typeahead.selected=null,this._eventEmitter.emit("result",{result:t})}},_getConfigForRequest:function(){var t=["bbox","limit","proximity","countries","types","language","reverseMode"],e=this;return t.reduce(function(t,i){return e.options[i]&&(["countries","types","language"].indexOf(i)>-1?t[i]=e.options[i].split(/[\s,]+/):t[i]=e.options[i],"proximity"===i&&e.options[i]&&"number"==typeof e.options[i].longitude&&"number"==typeof e.options[i].latitude&&(t[i]=[e.options[i].longitude,e.options[i].latitude])),t},{})},_geocode:function(t,e,i){this._loadingEl.style.display="block",this._eventEmitter.emit("loading",{query:t}),this.inputString=t;var n,s=null,r=this._getConfigForRequest();if(this.options.localGeocoderOnly)n=Promise.resolve();else if(this.options.reverseGeocode&&/(-?\d+\.?\d*)[, ]+(-?\d+\.?\d*)[ ]*$/.test(t)){var l=t.split(/[\s(,)?]+/).map(function(t){return parseFloat(t,10)}).reverse();r.types&&r.types[0],r=o(r,{query:l,limit:1}),"proximity"in r&&delete r.proximity,n=this.geocoderApi.reverseGeocode(r)}else r=o(r,{query:t}),n=this.geocoderApi.getSuggestions?e?this.geocoderApi.searchByPlaceId&&i?this.geocoderApi.searchByPlaceId(r):this.geocoderApi.forwardGeocode(r):this.geocoderApi.getSuggestions(r):this.geocoderApi.forwardGeocode(r);var a=[];this.options.localGeocoder&&((a=this.options.localGeocoder(t))||(a=[]));var h=[];return n.catch(function(t){s=t}.bind(this)).then(function(e){this._loadingEl.style.display="none";var i={};return i=e||{type:"FeatureCollection",features:[]},i.config=r,this.fresh&&(this.fresh=!1),i.features=i.features?a.concat(i.features):a,this.options.externalGeocoder?(h=this.options.externalGeocoder(t,i.features,r)||[],h.then(function(t){return i.features=i.features?t.concat(i.features):t,i},function(){return i})):i}.bind(this)).then(function(t){if(s)throw s;this.options.filter&&t.features.length&&(t.features=t.features.filter(this.options.filter));var i=[];i=t.suggestions?t.suggestions:t.place?[t.place]:t.features,i.length?(this._clearEl.style.display="block",this._typeahead.update(i),(!this.options.showResultsWhileTyping||e)&&this.options.showResultMarkers&&(t.features.length>0||t.place)&&this._fitBoundsForMarkers(),this._eventEmitter.emit("results",t)):(this._clearEl.style.display="none",this._typeahead.selected=null,this._renderNoResults(),this._eventEmitter.emit("results",t))}.bind(this)).catch(function(t){this._loadingEl.style.display="none",a.length&&this.options.localGeocoder||h.length&&this.options.externalGeocoder?(this._clearEl.style.display="block",this._typeahead.update(a)):(this._clearEl.style.display="none",this._typeahead.selected=null,this._renderError()),this._eventEmitter.emit("results",{features:a}),this._eventEmitter.emit("error",{error:t})}.bind(this)),n},_clear:function(t){t&&t.preventDefault(),this._inputEl.value="",this._typeahead.selected=null,this._typeahead.clear(),this._onChange(),this._clearEl.style.display="none",this._removeMarker(),this._removeResultMarkers(),this.lastSelected=null,this._eventEmitter.emit("clear"),this.fresh=!0},clear:function(t){this._clear(t),this._inputEl.focus()},_clearOnBlur:function(t){var e=this;t.relatedTarget&&e._clear(t)},_onQueryResult:function(t){var e=t;if(e.features.length){var i=e.features[0];this._typeahead.selected=i,this._inputEl.value=i.place_name,this._onChange()}},_updateProximity:function(){if(this._map)if(this._map.getZoom()>9){var t=this._map.getCenter().wrap();this.setProximity({longitude:t.lng,latitude:t.lat})}else this.setProximity(null)},_collapse:function(){this._inputEl.value||this._inputEl===document.activeElement||this.container.classList.add("mapboxgl-ctrl-geocoder--collapsed","maplibregl-ctrl-geocoder--collapsed")},_unCollapse:function(){this.container.classList.remove("mapboxgl-ctrl-geocoder--collapsed","maplibregl-ctrl-geocoder--collapsed")},query:function(t){return this._geocode(t).then(this._onQueryResult),this},_renderError:function(){this._renderMessage("
There was an error reaching the server
")},_renderNoResults:function(){this._renderMessage("
No results found
")},_renderMessage:function(t){this._typeahead.update([]),this._typeahead.selected=null,this._typeahead.clear(),this._typeahead.renderError(t)},_getPlaceholderText:function(){if(this.options.placeholder)return this.options.placeholder;if(this.options.language){var t=this.options.language.split(",")[0],e=u.language(t),i=h.placeholder[e];if(i)return i}return"Search"},_fitBoundsForMarkers:function(){if(!(this._typeahead.data.length<1)){var t=this._typeahead.data.filter(function(t){return"string"!=typeof t}).slice(0,this.options.limit);if(this._clearEl.style.display="none",this.options.flyTo&&this._maplibregl&&this._map){var e={padding:100},i=o({},e,this.options.flyTo),n=new this._maplibregl.LngLatBounds;t.forEach(function(t){n.extend(t.geometry.coordinates)}),this._map.fitBounds(n.toArray(),i)}return t.length>0&&this._maplibregl&&this._handleResultMarkers(t),this}},setInput:function(t){return this._inputEl.value=t,this._typeahead.selected=null,this._typeahead.clear(),t.length>=this.options.minLength&&this.options.showResultsWhileTyping&&this._geocode(t),this},setProximity:function(t){return this.options.proximity=t,this},getProximity:function(){return this.options.proximity},setRenderFunction:function(t){return t&&"function"==typeof t&&(this._typeahead.render=t),this},getRenderFunction:function(){return this._typeahead.render},setLanguage:function(t){var e=navigator.language||navigator.userLanguage||navigator.browserLanguage;return this.options.language=t||this.options.language||e,this},getLanguage:function(){return this.options.language},getZoom:function(){return this.options.zoom},setZoom:function(t){return this.options.zoom=t,this},getFlyTo:function(){return this.options.flyTo},setFlyTo:function(t){return this.options.flyTo=t,this},getPlaceholder:function(){return this.options.placeholder},setPlaceholder:function(t){return this.placeholder=t||this._getPlaceholderText(),this._inputEl.placeholder=this.placeholder,this._inputEl.setAttribute("aria-label",this.placeholder),this},getBbox:function(){return this.options.bbox},setBbox:function(t){return this.options.bbox=t,this},getCountries:function(){return this.options.countries},setCountries:function(t){return this.options.countries=t,this},getTypes:function(){return this.options.types},setTypes:function(t){return this.options.types=t,this},getMinLength:function(){return this.options.minLength},setMinLength:function(t){return this.options.minLength=t,this._typeahead&&(this._typeahead.options.minLength=t),this},getLimit:function(){return this.options.limit},setLimit:function(t){return this.options.limit=t,this._typeahead&&(this._typeahead.options.limit=t),this},getFilter:function(){return this.options.filter},setFilter:function(t){return this.options.filter=t,this},setGeocoderApi:function(t){return this.geocoderApi=t,this},getGeocoderApi:function(){return this.geocoderApi},_handleMarker:function(t){if(this._map){this._removeMarker();var e={color:"#4668F2"},i=o({},e,this.options.marker);this.mapMarker=new this._maplibregl.Marker(i);var n;if(this.options.popup){var s={},r=o({},s,this.options.popup);n=new this._maplibregl.Popup(r).setHTML(this.options.popupRender(t))}return t.center?(this.mapMarker.setLngLat(t.center).addTo(this._map),this.options.popup&&this.mapMarker.setPopup(n)):t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(this.mapMarker.setLngLat(t.geometry.coordinates).addTo(this._map),this.options.popup&&this.mapMarker.setPopup(n)),this}},_removeMarker:function(){this.mapMarker&&(this.mapMarker.remove(),this.mapMarker=null)},_handleResultMarkers:function(t){if(this._map){this._removeResultMarkers();var e={color:"#4668F2"},i=o({},e,this.options.showResultMarkers);return t.forEach(function(t){if(this.options.showResultMarkers&&this.options.showResultMarkers.element){var e=this.options.showResultMarkers.element.cloneNode(!0);i=o(i,{element:e})}var n,s=new this._maplibregl.Marker(o({},i,{element:e}));if(this.options.popup){var r={},l=o({},r,this.options.popup);n=new this._maplibregl.Popup(l).setHTML(this.options.popupRender(t))}t.center?(s.setLngLat(t.center).addTo(this._map),this.options.popup&&s.setPopup(n)):t.geometry&&t.geometry.type&&"Point"===t.geometry.type&&t.geometry.coordinates&&(s.setLngLat(t.geometry.coordinates).addTo(this._map),this.options.popup&&s.setPopup(n)),this.resultMarkers.push(s)}.bind(this)),this}},_removeResultMarkers:function(){this.resultMarkers&&this.resultMarkers.length>0&&(this.resultMarkers.forEach(function(t){t.remove()}),this.resultMarkers=[])},on:function(t,e){return this._eventEmitter.on(t,e),this},off:function(t,e){return this._eventEmitter.removeListener(t,e),this}},e.exports=n},{"./exceptions":1,"./localization":3,events:4,"lodash.debounce":6,subtag:7,"suggestions-list":8,xtend:11}],3:[function(t,e,i){"use strict";var n={de:"Suche",it:"Ricerca",en:"Search",nl:"Zoeken",fr:"Chercher",ca:"Cerca",he:"לחפש",ja:"サーチ",lv:"Meklēt",pt:"Procurar",sr:"Претрага",zh:"搜索",cs:"Vyhledávání",hu:"Keresés",ka:"ძიება",nb:"Søke",sk:"Vyhľadávanie",th:"ค้นหา",fi:"Hae",is:"Leita",ko:"수색",pl:"Szukaj",sl:"Iskanje",fa:"جستجو",ru:"Поиск"};e.exports={placeholder:n}},{}],4:[function(t,e,i){function n(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=w(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}function s(t){return void 0===t._maxListeners?n.defaultMaxListeners:t._maxListeners}function r(t,e,i){if(e)t.call(i);else for(var n=t.length,s=m(t,n),r=0;r0&&l.length>r){l.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+l.length+' "'+String(e)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=l.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",a.name,a.message)}}else l=o[e]=i,++t._eventsCount;return t}function c(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var t=new Array(arguments.length),e=0;e1&&(e=arguments[1]),e instanceof Error)throw e;var d=new Error('Unhandled "error" event. ('+e+")");throw d.context=e,d}if(!(i=c[t]))return!1;var f="function"==typeof i;switch(n=arguments.length){case 1:r(i,f,this);break;case 2:o(i,f,this,arguments[1]);break;case 3:l(i,f,this,arguments[1],arguments[2]);break;case 4:a(i,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(n-1),u=1;u=0;r--)if(i[r]===e||i[r].listener===e){o=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():g(i,s),1===i.length&&(n[t]=i[0]),n.removeListener&&this.emit("removeListener",t,o||e)}return this},n.prototype.removeAllListeners=function(t){var e,i,n;if(!(i=this._events))return this;if(!i.removeListener)return 0===arguments.length?(this._events=w(null),this._eventsCount=0):i[t]&&(0==--this._eventsCount?this._events=w(null):delete i[t]),this;if(0===arguments.length){var s,r=x(i);for(n=0;n=0;n--)this.removeListener(t,e[n]);return this},n.prototype.listeners=function(t){return d(this,t,!0)},n.prototype.rawListeners=function(t){return d(this,t,!1)},n.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):f.call(t,e)},n.prototype.listenerCount=f,n.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],5:[function(t,e,i){!function(){var t=this,n={};void 0!==i?e.exports=n:t.fuzzy=n,n.simpleFilter=function(t,e){return e.filter(function(e){return n.test(t,e)})},n.test=function(t,e){return null!==n.match(t,e)},n.match=function(t,e,i){i=i||{};var n,s=0,r=[],o=e.length,l=0,a=0,h=i.pre||"",u=i.post||"",c=i.caseSensitive&&e||e.toLowerCase();t=i.caseSensitive&&t||t.toLowerCase();for(var p=0;p=e||i<0||C&&n>=v}function u(){var t=x();if(h(t))return c(t);_=setTimeout(u,a(t))}function c(t){return _=void 0,M&&g?s(t):(g=m=void 0,y)}function p(){void 0!==_&&clearTimeout(_),L=0,g=E=m=_=void 0}function d(){return void 0===_?y:c(x())}function f(){var t=x(),i=h(t);if(g=arguments,m=this,E=t,i){if(void 0===_)return r(E);if(C)return _=setTimeout(u,e),s(E)}return void 0===_&&(_=setTimeout(u,e)),y}var g,m,v,y,_,E,L=0,k=!1,C=!1,M=!0;if("function"!=typeof t)throw new TypeError(l);return e=o(e)||0,n(i)&&(k=!!i.leading,C="maxWait"in i,v=C?b(o(i.maxWait)||0,e):v,M="trailing"in i?!!i.trailing:M),f.cancel=p,f.flush=d,f}function n(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function s(t){return!!t&&"object"==typeof t}function r(t){return"symbol"==typeof t||s(t)&&_.call(t)==h}function o(t){if("number"==typeof t)return t;if(r(t))return a;if(n(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=n(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(u,"");var i=p.test(t);return i||d.test(t)?f(t.slice(2),i?2:8):c.test(t)?a:+t}var l="Expected a function",a=NaN,h="[object Symbol]",u=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,d=/^0o[0-7]+$/i,f=parseInt,g="object"==typeof t&&t&&t.Object===Object&&t,m="object"==typeof self&&self&&self.Object===Object&&self,v=g||m||Function("return this")(),y=Object.prototype,_=y.toString,b=Math.max,w=Math.min,x=function(){return v.Date.now()};e.exports=i}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],7:[function(t,e,i){!function(t,i,n){void 0!==e&&e.exports?e.exports=n():t.subtag=n()}(this,0,function(){function t(t){return t.match(o)||[]}function e(e){return t(e).filter(function(t,e){return t&&e})}function i(e){return e=t(e),{language:e[1]||r,extlang:e[2]||r,script:e[3]||r,region:e[4]||r}}function n(t,e,i){Object.defineProperty(t,e,{value:i,enumerable:!0})}function s(e,s,o){function l(i){return t(i)[e]||r}n(l,"pattern",s),n(i,o,l)}var r="",o=/^([a-zA-Z]{2,3})(?:[_-]+([a-zA-Z]{3})(?=$|[_-]+))?(?:[_-]+([a-zA-Z]{4})(?=$|[_-]+))?(?:[_-]+([a-zA-Z]{2}|[0-9]{3})(?=$|[_-]+))?/;return s(1,/^[a-zA-Z]{2,3}$/,"language"),s(2,/^[a-zA-Z]{3}$/,"extlang"),s(3,/^[a-zA-Z]{4}$/,"script"),s(4,/^[a-zA-Z]{2}$|^[0-9]{3}$/,"region"),n(i,"split",e),i})},{}],8:[function(t,e,i){"use strict";var n=t("./src/suggestions");e.exports=n,"undefined"!=typeof window&&(window.Suggestions=n)},{"./src/suggestions":10}],9:[function(t,e,i){"use strict";var n=function(t){return this.component=t,this.items=[],this.active=t.options.noInitialSelection?-1:0,this.wrapper=document.createElement("div"),this.wrapper.className="suggestions-wrapper",this.element=document.createElement("ul"),this.element.className="suggestions",this.wrapper.appendChild(this.element),this.selectingListItem=!1,t.el.parentNode.insertBefore(this.wrapper,t.el.nextSibling),this};n.prototype.show=function(){this.element.style.display="block"},n.prototype.hide=function(){this.element.style.display="none"},n.prototype.add=function(t){this.items.push(t)},n.prototype.clear=function(){this.items=[],this.active=this.component.options.noInitialSelection?-1:0},n.prototype.isEmpty=function(){return!this.items.length},n.prototype.isVisible=function(){return"block"===this.element.style.display},n.prototype.draw=function(){if(this.element.innerHTML="", +0===this.items.length)return void this.hide();for(var t=0;t=this.items.length-1?0:this.active+1)},n.prototype.drawError=function(t){var e=document.createElement("li");e.innerHTML=t,this.element.appendChild(e),this.show()},e.exports=n},{}],10:[function(t,e,i){"use strict";var n=t("xtend"),s=t("fuzzy"),r=t("./list"),o=function(t,e,i){return i=i||{},this.options=n({minLength:2,limit:5,filter:!0,hideOnBlur:!0,noInitialSelection:!0},i),this.el=t,this.data=e||[],this.list=new r(this),this.query="",this.selected=null,this.list.draw(),this.el.addEventListener("keyup",function(t){this.handleKeyUp(t.keyCode,t)}.bind(this),!1),this.el.addEventListener("keydown",function(t){this.handleKeyDown(t)}.bind(this)),this.el.addEventListener("focus",function(){this.handleFocus()}.bind(this)),this.el.addEventListener("blur",function(){this.handleBlur()}.bind(this)),this.el.addEventListener("paste",function(t){this.handlePaste(t)}.bind(this)),this.render=this.options.render?this.options.render.bind(this):this.render.bind(this),this.getItemValue=this.options.getItemValue?this.options.getItemValue.bind(this):this.getItemValue.bind(this),this};o.prototype.handleKeyUp=function(t,e){if(40!==t&&38!==t&&27!==t&&9!==t)return 13===t?void(this.list.items[this.list.active]&&(this.list.handleMouseUp(this.list.items[this.list.active]),e.stopPropagation())):void this.handleInputChange(this.el.value)},o.prototype.handleKeyDown=function(t){switch(t.keyCode){case 13:this.list.active>=0&&(this.list.selectingListItem=!0);break;case 9:this.list.isEmpty()||(this.list.isVisible()&&t.preventDefault(),this.value(this.list.active>=0?this.list.items[this.list.active].original:null),this.list.hide());break;case 27:this.list.isEmpty()||this.list.hide();break;case 38:this.list.previous();break;case 40:this.list.next()}},o.prototype.handleBlur=function(){!this.list.selectingListItem&&this.options.hideOnBlur&&this.list.hide()},o.prototype.handlePaste=function(t){if(t.clipboardData)this.handleInputChange(t.clipboardData.getData("Text"));else{var e=this;setTimeout(function(){e.handleInputChange(t.target.value)},100)}},o.prototype.handleInputChange=function(t){if(this.query=this.normalize(t),this.list.clear(),this.query.length-1},o.prototype.value=function(t){if(this.selected=t,this.el.value=this.getItemValue(t||{place_name:this.query}),document.createEvent){var e=document.createEvent("HTMLEvents");e.initEvent("change",!0,!1),this.el.dispatchEvent(e)}else this.el.fireEvent("onchange")},o.prototype.getCandidates=function(t){var e,i={pre:"",post:"",extract:function(t){return this.getItemValue(t)}.bind(this)};this.options.filter?(e=s.filter(this.query,this.data,i),e=e.map(function(t){return{original:t.original,string:this.render(t.original,t.string)}}.bind(this))):e=this.data.map(function(t){return{original:t,string:this.render(t)}}.bind(this)),t(e)},o.prototype.getItemValue=function(t){return t},o.prototype.render=function(t,e){if(e)return e;for(var i=t.original?this.getItemValue(t.original):this.getItemValue(t),n=this.normalize(i),s=n.lastIndexOf(this.query);s>-1;){var r=s+this.query.length;i=i.slice(0,s)+""+i.slice(s,r)+""+i.slice(r),s=n.slice(0,s).lastIndexOf(this.query)}return i},o.prototype.renderError=function(t){this.list.drawError(t)},e.exports=o},{"./list":9,fuzzy:5,xtend:11}],11:[function(t,e,i){function n(){for(var t={},e=0;e.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:hsla(0,0%,100%,.5);background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:rgba(0,0,0,.05)}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:hsla(0,0%,100%,.75);border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:rgba(0,0,0,.05)}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px rgba(0,0,0,.35);box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:rgba(0,0,0,.4);color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media (hover:none),(pointer:coarse){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999} \ No newline at end of file diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js new file mode 100644 index 0000000..53dd1e0 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/maplibre-gl/maplibre-gl.js @@ -0,0 +1,59 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v5.7.2/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory()); +})(this, (function () { 'use strict'; + +/* eslint-disable */ + +var maplibregl = {}; +var modules = {}; +function define(moduleName, _dependencies, moduleFactory) { + modules[moduleName] = moduleFactory; + + // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) + if (moduleName !== 'index') { + return; + } + + // we assume that when an index module is initializing then other modules are loaded already + var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);' + + var sharedModule = {}; + // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) + // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) + // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following + modules.shared(sharedModule); + modules.index(maplibregl, sharedModule); + + if (typeof window !== 'undefined') { + maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); + } + + return maplibregl; +}; + + + +define("shared",["exports"],(function(t){"use strict";function e(t,e,r,n){return new(r||(r=Promise))((function(i,s){function a(t){try{l(n.next(t));}catch(t){s(t);}}function o(t){try{l(n.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(a,o);}l((n=n.apply(t,e||[])).next());}))}function r(t,e){this.x=t,this.y=e;}function n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,s;"function"==typeof SuppressedError&&SuppressedError,r.prototype={clone(){return new r(this.x,this.y)},add(t){return this.clone()._add(t)},sub(t){return this.clone()._sub(t)},multByPoint(t){return this.clone()._multByPoint(t)},divByPoint(t){return this.clone()._divByPoint(t)},mult(t){return this.clone()._mult(t)},div(t){return this.clone()._div(t)},rotate(t){return this.clone()._rotate(t)},rotateAround(t,e){return this.clone()._rotateAround(t,e)},matMult(t){return this.clone()._matMult(t)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(t){return this.x===t.x&&this.y===t.y},dist(t){return Math.sqrt(this.distSqr(t))},distSqr(t){const e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle(){return Math.atan2(this.y,this.x)},angleTo(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith(t){return this.angleWithSep(t.x,t.y)},angleWithSep(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult(t){const e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add(t){return this.x+=t.x,this.y+=t.y,this},_sub(t){return this.x-=t.x,this.y-=t.y,this},_mult(t){return this.x*=t,this.y*=t,this},_div(t){return this.x/=t,this.y/=t,this},_multByPoint(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint(t){return this.x/=t.x,this.y/=t.y,this},_unit(){return this._div(this.mag()),this},_perp(){const t=this.y;return this.y=this.x,this.x=-t,this},_rotate(t){const e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround(t,e){const r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:r},r.convert=function(t){if(t instanceof r)return t;if(Array.isArray(t))return new r(+t[0],+t[1]);if(void 0!==t.x&&void 0!==t.y)return new r(+t.x,+t.y);throw new Error("Expected [x, y] or {x, y} point format")};var a=function(){if(s)return i;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return s=1,i=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},i}(),o=n(a);let l,u;function c(){return null==l&&(l="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),l}function h(){if(null==u&&(u=!1,c())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:!0});if(e){for(let r=0;r4&&void 0!==arguments[4]?arguments[4]:"zyx",s=Math.PI/360;e*=s,n*=s,r*=s;var a=Math.sin(e),o=Math.cos(e),l=Math.sin(r),u=Math.cos(r),c=Math.sin(n),h=Math.cos(n);switch(i){case "xyz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "xzy":t[0]=a*u*h-o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h+a*l*c;break;case "yxz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;case "yzx":t[0]=a*u*h+o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h-a*l*c;break;case "zxy":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "zyx":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;default:throw new Error("Unknown angle order "+i)}return t}function I(){var t=new f(2);return f!=Float32Array&&(t[0]=0,t[1]=0),t}function z(t,e){var r=new f(2);return r[0]=t,r[1]=e,r}m(),_=new f(4),f!=Float32Array&&(_[0]=0,_[1]=0,_[2]=0,_[3]=0),m(),x(1,0,0),x(0,1,0),k(),k(),d(),I();const P=8192;function C(t,e,r){return e*(P/(t.tileSize*Math.pow(2,r-t.tileID.overscaledZ)))}function E(t,e){return (t%e+e)%e}function T(t,e,r){return t*(1-r)+e*r}function B(t){if(t<=0)return 0;if(t>=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function V(t,e,r,n){const i=new o(t,e,r,n);return t=>i.solve(t)}const F=V(.25,.1,.25,1);function $(t,e,r){return Math.min(r,Math.max(e,t))}function D(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function L(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let O=1;function R(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function U(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}function j(t){return Array.isArray(t)?t.map(j):"object"==typeof t&&t?R(t,j):t}const N={};function q(t){N[t]||("undefined"!=typeof console&&console.warn(t),N[t]=!0);}function G(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function X(t){return "undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}let Z=null;function Y(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const H="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function K(t,r,n,i,s){return e(this,void 0,void 0,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const e=new VideoFrame(t,{timestamp:0});try{const a=null==e?void 0:e.format;if(!a||!a.startsWith("BGR")&&!a.startsWith("RGB"))throw new Error(`Unrecognized format ${a}`);const o=a.startsWith("BGR"),l=new Uint8ClampedArray(i*s*4);if(yield e.copyTo(l,function(t,e,r,n,i){const s=4*Math.max(-e,0),a=(Math.max(0,r)-r)*n*4+s,o=4*n,l=Math.max(0,e),u=Math.max(0,r);return {rect:{x:l,y:u,width:Math.min(t.width,e+n)-l,height:Math.min(t.height,r+i)-u},layout:[{offset:a,stride:o}]}}(t,r,n,i,s)),o)for(let t=0;t{t.removeEventListener(e,r,n);}}}function tt(t){return t*Math.PI/180}function et(t){return t/Math.PI*180}const rt={touchstart:!0,touchmove:!0,touchmoveWindow:!0,touchend:!0,touchcancel:!0},nt={dblclick:!0,click:!0,mouseover:!0,mouseout:!0,mousedown:!0,mousemove:!0,mousemoveWindow:!0,mouseup:!0,mouseupWindow:!0,contextmenu:!0,wheel:!0},it="AbortError";function st(){return new Error(it)}const at={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function ot(t){return at.REGISTERED_PROTOCOLS[t.substring(0,t.indexOf("://"))]}const lt="global-dispatcher";class ut extends Error{constructor(t,e,r,n){super(`AJAXError: ${e} (${t}): ${r}`),this.status=t,this.statusText=e,this.url=r,this.body=n;}}const ct=()=>X(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,ht=function(t,r){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const e=ot(t.url);if(e)return e(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:lt},r)}if(!(/^file:/.test(n=t.url)||/^file:/.test(ct())&&!/^\w+:/.test(n))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,r){return e(this,void 0,void 0,(function*(){const e=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:ct(),signal:r.signal});let n,i;"json"!==t.type||e.headers.has("Accept")||e.headers.set("Accept","application/json");try{n=yield fetch(e);}catch(e){throw new ut(0,e.message,t.url,new Blob)}if(!n.ok){const e=yield n.blob();throw new ut(n.status,n.statusText,t.url,e)}i="arrayBuffer"===t.type||"image"===t.type?n.arrayBuffer():"json"===t.type?n.json():n.text();const s=yield i;if(r.signal.aborted)throw st();return {data:s,cacheControl:n.headers.get("Cache-Control"),expires:n.headers.get("Expires")}}))}(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:!0,targetMapId:lt},r)}var n;return function(t,e){return new Promise(((r,n)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,!0),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||void 0===i?void 0:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{n(new Error(s.statusText));},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response);}catch(t){return void n(t)}r({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires")});}else {const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});n(new ut(s.status,s.statusText,t.url,e));}},e.signal.addEventListener("abort",(()=>{s.abort(),n(st());})),s.send(t.body);}))}(t,r)};function pt(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return !0;const e=new URL(t),r=window.location;return e.protocol===r.protocol&&e.host===r.host}function ft(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function dt(t,e,r){if(r&&r[t]){const n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}class yt{constructor(t,e={}){L(this,e),this.type=t;}}class mt extends yt{constructor(t,e={}){super("error",L({error:t},e));}}class gt{on(t,e){return this._listeners=this._listeners||{},ft(t,e,this._listeners),{unsubscribe:()=>{this.off(t,e);}}}off(t,e){return dt(t,e,this._listeners),dt(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},ft(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new yt(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)dt(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(L(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof mt&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var xt={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},state:{type:"state",default:{}},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},"font-faces":{type:"array",value:"fontFaces"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},"color-relief":{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_color-relief","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const vt=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function bt(t,e){const r={};for(const e in t)"ref"!==e&&(r[e]=t[e]);return vt.forEach((t=>{t in e&&(r[t]=e[t]);})),r}function wt(t,e){if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return !1;for(let r=0;r`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const Jt=[Vt,Ft,$t,Dt,Lt,Ot,Nt,Rt,Ht(Ut),qt,Xt,Gt,Zt,Yt];function Wt(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Wt(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of Jt)if(!Wt(t,e))return null}return `Expected ${Kt(t)} but found ${Kt(e)} instead.`}function Qt(t,e){return e.some((e=>e.kind===t.kind))}function te(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function ee(t,e){return "array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const re=.96422,ne=.82521,ie=4/29,se=6/29,ae=3*se*se,oe=se*se*se,le=Math.PI/180,ue=180/Math.PI;function ce(t){return (t%=360)<0&&(t+=360),t}function he([t,e,r,n]){let i,s;const a=fe((.2225045*(t=pe(t))+.7168786*(e=pe(e))+.0606169*(r=pe(r)))/1);t===e&&e===r?i=s=a:(i=fe((.4360747*t+.3850649*e+.1430804*r)/re),s=fe((.0139322*t+.0971045*e+.7141733*r)/ne));const o=116*a-16;return [o<0?0:o,500*(i-a),200*(a-s),n]}function pe(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function fe(t){return t>oe?Math.pow(t,1/3):t/ae+ie}function de([t,e,r,n]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,a=isNaN(r)?i:i-r/200;return i=1*me(i),s=re*me(s),a=ne*me(a),[ye(3.1338561*s-1.6168667*i-.4906146*a),ye(-.9787684*s+1.9161415*i+.033454*a),ye(.0719453*s-.2289914*i+1.4052427*a),n]}function ye(t){return (t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function me(t){return t>se?t*t*t:ae*(t-ie)}const ge=Object.hasOwn||function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};function xe(t,e){return ge(t,e)?t[e]:void 0}function ve(t){return parseInt(t.padEnd(2,t),16)/255}function be(t,e){return we(e?t/100:t,0,1)}function we(t,e,r){return Math.min(Math.max(e,t),r)}function _e(t){return !t.some(Number.isNaN)}const Se={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function Ae(t,e,r){return t+r*(e-t)}function ke(t,e,r){return t.map(((t,n)=>Ae(t,e[n],r)))}class Me{constructor(t,e,r,n=1,i=!0){this.r=t,this.g=e,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[t,e,r,n]));}static parse(t){if(t instanceof Me)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return [0,0,0,0];const e=xe(Se,t);if(e){const[t,r,n]=e;return [t/255,r/255,n/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let r=1;return [ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,r,n,i,s,a,o,l,u,c,h,p]=e,f=[i||" ",o||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[n,a,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[we(+r/e,0,1),we(+s/e,0,1),we(+l/e,0,1),h?be(+h,p):1];if(_e(t))return t}}return}}const r=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[t,e,n,i,s,a,o,l,u]=r,c=[n||" ",s||" ",o].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,we(+i,0,100),we(+a,0,100),l?be(+l,u):1];if(_e(t))return function([t,e,r,n]){function i(n){const i=(n+t/30)%12,s=e*Math.min(r,1-r);return r-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=ce(t),e/=100,r/=100,[i(0),i(8),i(4),n]}(t)}}}(t);return e?new Me(...e,!1):void 0}get rgb(){const{r:t,g:e,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[t/i,e/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,r,n,i]=he(t),s=Math.sqrt(r*r+n*n);return [Math.round(1e4*s)?ce(Math.atan2(n,r)*ue):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",he(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,r,n]=this.rgb;return `rgba(${[t,e,r].map((t=>Math.round(255*t))).join(",")},${n})`}static interpolate(t,e,r,n="rgb"){switch(n){case "rgb":{const[n,i,s,a]=ke(t.rgb,e.rgb,r);return new Me(n,i,s,a,!1)}case "hcl":{const[n,i,s,a]=t.hcl,[o,l,u,c]=e.hcl;let h,p;if(isNaN(n)||isNaN(o))isNaN(n)?isNaN(o)?h=NaN:(h=o,1!==s&&0!==s||(p=l)):(h=n,1!==u&&0!==u||(p=i));else {let t=o-n;o>n&&t>180?t-=360:o180&&(t+=360),h=n+r*t;}const[f,d,y,m]=function([t,e,r,n]){return t=isNaN(t)?0:t*le,de([r,Math.cos(t)*e,Math.sin(t)*e,n])}([h,null!=p?p:Ae(i,l,r),Ae(s,u,r),Ae(a,c,r)]);return new Me(f,d,y,m,!1)}case "lab":{const[n,i,s,a]=de(ke(t.lab,e.lab,r));return new Me(n,i,s,a,!1)}}}}Me.black=new Me(0,0,0,1),Me.white=new Me(1,1,1,1),Me.transparent=new Me(0,0,0,0),Me.red=new Me(1,0,0,1);class Ie{constructor(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const ze=["bottom","center","top"];class Pe{constructor(t,e,r,n,i,s){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i,this.verticalAlign=s;}}class Ce{constructor(t){this.sections=t;}static fromString(t){return new Ce([new Pe(t,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof Ce?t:Ce.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class Ee{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Ee)return t;if("number"==typeof t)return new Ee([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]];}return new Ee(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Ee(ke(t.values,e.values,r))}}class Te{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Te)return t;if("number"==typeof t)return new Te([t]);if(Array.isArray(t)){for(const e of t)if("number"!=typeof e)return;return new Te(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Te(ke(t.values,e.values,r))}}class Be{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Be)return t;if("string"==typeof t){const e=Me.parse(t);if(!e)return;return new Be([e])}if(!Array.isArray(t))return;const e=[];for(const r of t){if("string"!=typeof r)return;const t=Me.parse(r);if(!t)return;e.push(t);}return new Be(e)}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r,n="rgb"){const i=[];if(t.values.length!=e.values.length)throw new Error(`colorArray: Arrays have mismatched length (${t.values.length} vs. ${e.values.length}), cannot interpolate.`);for(let s=0;s=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Re(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof Le||t instanceof Me||t instanceof Ie||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De)return !0;if(Array.isArray(t)){for(const e of t)if(!Re(e))return !1;return !0}if("object"==typeof t){for(const e in t)if(!Re(t[e]))return !1;return !0}return !1}function Ue(t){if(null===t)return Vt;if("string"==typeof t)return $t;if("boolean"==typeof t)return Dt;if("number"==typeof t)return Ft;if(t instanceof Me)return Lt;if(t instanceof Le)return Ot;if(t instanceof Ie)return jt;if(t instanceof Ce)return Nt;if(t instanceof Ee)return qt;if(t instanceof Te)return Xt;if(t instanceof Be)return Gt;if(t instanceof $e)return Yt;if(t instanceof De)return Zt;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=Ue(e);if(r){if(r===t)continue;r=Ut;break}r=t;}return Ht(r||Ut,e)}return Rt}function je(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof Me||t instanceof Le||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De?t.toString():JSON.stringify(t)}class Ne{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Re(t[1]))return e.error("invalid value");const r=t[1];let n=Ue(r);const i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new Ne(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return !0}}const qe={string:$t,number:Ft,boolean:Dt,object:Rt};class Ge{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r,n=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const r=t[1];if("string"!=typeof r||!(r in qe)||"object"===r)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=qe[r],n++;}else i=Ut;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],n++;}r=Ht(i,s);}else {if(!qe[i])throw new Error(`Types doesn't contain name = ${i}`);r=qe[i];}const s=[];for(;nt.outputDefined()))}}const Xe={"to-boolean":Dt,"to-color":Lt,"to-number":Ft,"to-string":$t};class Ze{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[0];if(!Xe[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");const n=Xe[r],i=[];for(let r=1;r4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:Oe(e[0],e[1],e[2],e[3]),!r))return new Me(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new Ve(r||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "padding":{let e;for(const r of this.args){e=r.evaluate(t);const n=Ee.parse(e);if(n)return n}throw new Ve(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "numberArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Te.parse(e);if(n)return n}throw new Ve(`Could not parse numberArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "colorArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Be.parse(e);if(n)return n}throw new Ve(`Could not parse colorArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "variableAnchorOffsetCollection":{let e;for(const r of this.args){e=r.evaluate(t);const n=$e.parse(e);if(n)return n}throw new Ve(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "number":{let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new Ve(`Could not convert ${JSON.stringify(e)} to number.`)}case "formatted":return Ce.fromString(je(this.args[0].evaluate(t)));case "resolvedImage":return De.fromString(je(this.args[0].evaluate(t)));case "projectionDefinition":return this.args[0].evaluate(t);default:return je(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}const Ye=["Unknown","Point","LineString","Polygon"];class He{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null;}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?Ye[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache.get(t);return e||(e=Me.parse(t),this._parseColorCache.set(t,e)),e}}class Ke{constructor(t,e,r=[],n,i=new Bt,s=[]){this.registry=t,this.path=r,this.key=r.map((t=>`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=n,this._isConstant=e;}parse(t,e,r,n,i={}){return e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return "assert"===r?new Ge(e,[t]):"coerce"===r?new Ze(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const n=t[0];if("string"!=typeof n)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[n];if(i){let n=i.parse(t,this);if(!n)return null;if(this.expectedType){const t=this.expectedType,i=n.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind){if("projectionDefinition"===t.kind&&["string","array"].includes(i.kind)||["color","formatted","resolvedImage"].includes(t.kind)&&["value","string"].includes(i.kind)||["padding","numberArray"].includes(t.kind)&&["value","number","array"].includes(i.kind)||"colorArray"===t.kind&&["value","string","array"].includes(i.kind)||"variableAnchorOffsetCollection"===t.kind&&["value","array"].includes(i.kind))n=r(n,t,e.typeAnnotation||"coerce");else if(this.checkSubtype(t,i))return null}else n=r(n,t,e.typeAnnotation||"assert");}if(!(n instanceof Ne)&&"resolvedImage"!==n.type.kind&&this._isConstant(n)){const t=new He;try{n=new Ne(n.type,n.evaluate(t));}catch(t){return this.error(t.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Ke(this.registry,this._isConstant,n,e||null,i,this.errors)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new Tt(r,t));}checkSubtype(t,e){const r=Wt(t,e);return r&&this.error(r),r}}class Je{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new Ve(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new Ve(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return !1}}class tr{constructor(t,e){this.type=Dt,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);return r&&n?Qt(r.type,[Dt,$t,Ft,Vt,Ut])?new tr(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);if(!te(r,["string","array"]))throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return !0}}class er{constructor(t,e,r){this.type=Ft,this.needle=t,this.haystack=e,this.fromIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);if(!r||!n)return null;if(!Qt(r.type,[Dt,$t,Ft,Vt,Ut]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new er(r,n,i):null}return new er(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(t)),te(r,["string"])){const t=r.indexOf(e,n);return -1===t?-1:[...r.slice(0,t)].length}if(te(r,["array"]))return r.indexOf(e,n);throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return !1}}class rr{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(r){if(u.checkSubtype(r,Ue(t)))return null}else r=Ue(t);if(void 0!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length;}const c=e.parse(l,a,n);if(!c)return null;n=n||c.type,s.push(c);}const a=e.parse(t[1],1,Ut);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,n);return o?"value"!==a.type.kind&&e.concat(1).checkSubtype(r,a.type)?null:new rr(r,n,a,i,s,o):null}evaluate(t){const e=this.input.evaluate(t);return (Ue(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class nr{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class ir{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ft);if(!r||!n)return null;if(!Qt(r.type,[Ht(Ut),$t,Ut]))return e.error(`Expected first argument to be of type array or string, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new ir(r.type,r,n,i):null}return new ir(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);let n;if(this.endIndex&&(n=this.endIndex.evaluate(t)),te(e,["string"]))return [...e].slice(r,n).join("");if(te(e,["array"]))return e.slice(r,n);throw new Ve(`Expected first argument to be of type array or string, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return !1}}function sr(t,e){const r=t.length-1;let n,i,s=0,a=r,o=0;for(;s<=a;)if(o=Math.floor((s+a)/2),n=t[o],i=t[o+1],n<=e){if(o===r||ee))throw new Ve("Input is not a number.");a=o-1;}return 0}class ar{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',o);const u=e.parse(a,l,i);if(!u)return null;i=i||u.type,n.push([s,u]);}return new ar(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[sr(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function or(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var lr,ur,cr=function(){if(ur)return lr;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return ur=1,lr=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},lr}(),hr=or(cr);class pr{constructor(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e);}static interpolationFactor(t,e,r,n){let i=0;if("exponential"===t.name)i=fr(e,t.base,r,n);else if("linear"===t.name)i=fr(e,1,r,n);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new hr(s[0],s[1],s[2],s[3]).solve(fr(e,1,r,n));}return i}static parse(t,e){let[r,n,i,...s]=t;if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){const t=n[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:t};}else {if("cubic-bezier"!==n[0])return e.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const t=n.slice(1);if(4!==t.length||t.some((t=>"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,Ft),!i)return null;const a=[];let o=null;"interpolate-hcl"!==r&&"interpolate-lab"!==r||e.expectedType==Gt?e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType):o=Lt;for(let t=0;t=r)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,o);if(!u)return null;o=o||u.type,a.push([r,u]);}return ee(o,Ft)||ee(o,Ot)||ee(o,Lt)||ee(o,qt)||ee(o,Xt)||ee(o,Gt)||ee(o,Yt)||ee(o,Ht(Ft))?new pr(o,r,n,i,a):e.error(`Type ${Kt(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=sr(e,n),a=pr.interpolationFactor(this.interpolation,n,e[s],e[s+1]),o=r[s].evaluate(t),l=r[s+1].evaluate(t);switch(this.operator){case "interpolate":switch(this.type.kind){case "number":return Ae(o,l,a);case "color":return Me.interpolate(o,l,a);case "padding":return Ee.interpolate(o,l,a);case "colorArray":return Be.interpolate(o,l,a);case "numberArray":return Te.interpolate(o,l,a);case "variableAnchorOffsetCollection":return $e.interpolate(o,l,a);case "array":return ke(o,l,a);case "projectionDefinition":return Le.interpolate(o,l,a)}case "interpolate-hcl":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"hcl");case "colorArray":return Be.interpolate(o,l,a,"hcl")}case "interpolate-lab":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"lab");case "colorArray":return Be.interpolate(o,l,a,"lab")}}}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function fr(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}const dr={color:Me.interpolate,number:Ae,padding:Ee.interpolate,numberArray:Te.interpolate,colorArray:Be.interpolate,variableAnchorOffsetCollection:$e.interpolate,array:ke};class yr{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r=null;const n=e.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const n of t.slice(1)){const t=e.parse(n,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!t)return null;r=r||t.type,i.push(t);}if(!r)throw new Error("No output type");const s=n&&i.some((t=>Wt(n,t.type)));return new yr(s?Ut:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(t),r&&r instanceof De&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break;return r}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function mr(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function gr(t,e,r,n){return 0===n.compare(e,r)}function xr(t,e,r){const n="=="!==t&&"!="!==t;return class i{constructor(t,e,r){this.type=Dt,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const r=t[0];let s=e.parse(t[1],1,Ut);if(!s)return null;if(!mr(r,s.type))return e.concat(1).error(`"${r}" comparisons are not supported for type '${Kt(s.type)}'.`);let a=e.parse(t[2],2,Ut);if(!a)return null;if(!mr(r,a.type))return e.concat(2).error(`"${r}" comparisons are not supported for type '${Kt(a.type)}'.`);if(s.type.kind!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error(`Cannot compare types '${Kt(s.type)}' and '${Kt(a.type)}'.`);n&&("value"===s.type.kind&&"value"!==a.type.kind?s=new Ge(a.type,[s]):"value"!==s.type.kind&&"value"===a.type.kind&&(a=new Ge(s.type,[a])));let o=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error("Cannot use collator to compare non-string types.");if(o=e.parse(t[3],3,jt),!o)return null}return new i(s,a,o)}evaluate(i){const s=this.lhs.evaluate(i),a=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=Ue(s),r=Ue(a);if(e.kind!==r.kind||"string"!==e.kind&&"number"!==e.kind)throw new Ve(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=Ue(s),r=Ue(a);if("string"!==t.kind||"string"!==r.kind)return e(i,s,a)}return this.collator?r(i,s,a,this.collator.evaluate(i)):e(i,s,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return !0}}}const vr=xr("==",(function(t,e,r){return e===r}),gr),br=xr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !gr(0,e,r,n)})),wr=xr("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),Sr=xr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),Ar=xr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class kr{constructor(t,e,r){this.type=jt,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");const n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,Dt);if(!n)return null;const i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Dt);if(!i)return null;let s=null;return r.locale&&(s=e.parse(r.locale,1,$t),!s)?null:new kr(n,i,s)}evaluate(t){return new Ie(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);}outputDefined(){return !1}}class Mr{constructor(t,e,r,n,i){this.type=$t,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=e.parse(n.locale,1,$t),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,$t),!s))return null;let a=null;if(n["min-fraction-digits"]&&(a=e.parse(n["min-fraction-digits"],1,Ft),!a))return null;let o=null;return n["max-fraction-digits"]&&(o=e.parse(n["max-fraction-digits"],1,Ft),!o)?null:new Mr(r,i,s,a,o)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return !1}}class Ir{constructor(t){this.type=Nt,this.sections=t;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");const n=[];let i=!1;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&"object"==typeof s&&!Array.isArray(s)){i=!1;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,Ft),!t))return null;let r=null;if(s["text-font"]&&(r=e.parse(s["text-font"],1,Ht($t)),!r))return null;let a=null;if(s["text-color"]&&(a=e.parse(s["text-color"],1,Lt),!a))return null;let o=null;if(s["vertical-align"]){if("string"==typeof s["vertical-align"]&&!ze.includes(s["vertical-align"]))return e.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${s["vertical-align"]}' instead.`);if(o=e.parse(s["vertical-align"],1,$t),!o)return null}const l=n[n.length-1];l.scale=t,l.font=r,l.textColor=a,l.verticalAlign=o;}else {const s=e.parse(t[r],1,Ut);if(!s)return null;const a=s.type.kind;if("string"!==a&&"value"!==a&&"null"!==a&&"resolvedImage"!==a)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:s,scale:null,font:null,textColor:null,verticalAlign:null});}}return new Ir(n)}evaluate(t){return new Ce(this.sections.map((e=>{const r=e.content.evaluate(t);return Ue(r)===Zt?new Pe("",r,null,null,null,e.verticalAlign?e.verticalAlign.evaluate(t):null):new Pe(je(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null,e.verticalAlign?e.verticalAlign.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor),e.verticalAlign&&t(e.verticalAlign);}outputDefined(){return !1}}class zr{constructor(t){this.type=Zt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,$t);return r?new zr(r):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),r=De.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r}eachChild(t){t(this.input);}outputDefined(){return !1}}class Pr{constructor(t){this.type=Ft,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${Kt(r.type)} instead.`):new Pr(r):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return [...e].length;if(Array.isArray(e))return e.length;throw new Ve(`Expected value to be of type string or array, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return !1}}const Cr=8192;function Er(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*Cr),Math.round(n*i*Cr)]}function Tr(t,e){const r=Math.pow(2,e.z);return [(i=(t[0]/Cr+e.x)/r,360*i-180),(n=(t[1]/Cr+e.y)/r,360/Math.PI*Math.atan(Math.exp((180-360*n)*Math.PI/180))-90)];var n,i;}function Br(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function Vr(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function Fr(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],a=t[1]-r[1];return n*a-s*i==0&&n*s<=0&&i*a<=0}function $r(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!jr(t,e,r,n)||!jr(r,n,t,e));var i,s;}function Dr(t,e,r){for(const n of r)for(let r=0;r(i=t)[1]!=(a=o[e+1])[1]>i[1]&&i[0]<(a[0]-s[0])*(i[1]-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}var i,s,a;return n}function Or(t,e){for(const r of e)if(Lr(t,r))return !0;return !1}function Rr(t,e){for(const r of t)if(!Lr(r,e))return !1;for(let r=0;r0&&o<0||a<0&&o>0}function Nr(t,e,r){const n=[];for(let i=0;ir[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i;}Br(e,t);}function Xr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];Gr(n,e,r,i),a.push(n);}return a}function Zr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];Br(e,r),t.push(r);}a.push(t);}if(e[2]-e[0]<=i/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const n of t)Gr(n,e,r,i);}var o;return a}class Yr{constructor(t,e){this.type=Dt,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const r of e.features){const{type:e,coordinates:n}=r.geometry;"Polygon"===e&&t.push(n),"MultiPolygon"===e&&t.push(...n);}if(t.length)return new Yr(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new Yr(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new Yr(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Lr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Or(t,s))return !1}return !0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Rr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Ur(t,s))return !1}return !0}(t,this.geometries)}return !1}eachChild(){}outputDefined(){return !0}}let Hr=class{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}};function Kr(t,e,r=0,n=t.length-1,i=Wr){for(;n>r;){if(n-r>600){const s=n-r+1,a=e-r+1,o=Math.log(s),l=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*l*(s-l)/s)*(a-s/2<0?-1:1);Kr(t,e,Math.max(r,Math.floor(e-a*l/s+u)),Math.min(n,Math.floor(e+(s-a)*l/s+u)),i);}const s=t[e];let a=r,o=n;for(Jr(t,r,e),i(t[n],s)>0&&Jr(t,r,n);a0;)o--;}0===i(t[r],s)?Jr(t,r,o):(o++,Jr(t,o,n)),o<=e&&(r=o+1),e<=o&&(n=o-1);}}function Jr(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function Wr(t,e){return te?1:0}function Qr(t,e){if(t.length<=1)return [t];const r=[];let n,i;for(const e of t){const t=en(e);0!==t&&(e.area=Math.abs(t),void 0===i&&(i=t<0),i===t<0?(n&&r.push(n),n=[e]):n.push(e));}if(n&&r.push(n),e>1)for(let t=0;t1?(l=t[o+1][0],u=t[o+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function on(t,e){return e[0]-t[0]}function ln(t){return t[1]-t[0]+1}function un(t,e){return t[1]>=t[0]&&t[1]t[1])return [null,null];const r=ln(t);if(e){if(2===r)return [t,null];const e=Math.floor(r/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===r)return [t,null];const n=Math.floor(r/2)-1;return [[t[0],t[0]+n],[t[0]+n+1,t[1]]]}function hn(t,e){if(!un(e,t.length))return [1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=e[0];n<=e[1];++n)Br(r,t[n]);return r}function pn(t){const e=[1/0,1/0,-1/0,-1/0];for(const r of t)for(const t of r)Br(e,t);return e}function fn(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function dn(t,e,r){if(!fn(t)||!fn(e))return NaN;let n=0,i=0;return t[2]e[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if(Vr(i,s)){if(wn(t,e))return 0}else if(wn(e,t))return 0;let a=1/0;for(const n of t)for(let t=0,i=n.length,s=i-1;t0;){const i=a.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(ln(l)<=u){if(!un(l,t.length))return NaN;if(e){const e=bn(t,l,r,n);if(isNaN(e)||0===e)return e;s=Math.min(s,e);}else for(let e=l[0];e<=l[1];++e){const i=vn(t[e],r,n);if(s=Math.min(s,i),0===s)return 0}}else {const r=cn(l,e);Sn(a,s,n,t,o,r[0]),Sn(a,s,n,t,o,r[1]);}}return s}function Mn(t,e,r,n,i,s=1/0){let a=Math.min(s,i.distance(t[0],r[0]));if(0===a)return a;const o=new Hr([[0,[0,t.length-1],[0,r.length-1]]],on);for(;o.length>0;){const s=o.pop();if(s[0]>=a)continue;const l=s[1],u=s[2],c=e?50:100,h=n?50:100;if(ln(l)<=c&&ln(u)<=h){if(!un(l,t.length)&&un(u,r.length))return NaN;let s;if(e&&n)s=gn(t,l,r,u,i),a=Math.min(a,s);else if(e&&!n){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=yn(r[t],e,i),a=Math.min(a,s),0===a)return a}else if(!e&&n){const e=r.slice(u[0],u[1]+1);for(let r=l[0];r<=l[1];++r)if(s=yn(t[r],e,i),a=Math.min(a,s),0===a)return a}else s=xn(t,l,r,u,i),a=Math.min(a,s);}else {const s=cn(l,e),c=cn(u,n);An(o,a,i,t,r,s[0],c[0]),An(o,a,i,t,r,s[0],c[1]),An(o,a,i,t,r,s[1],c[0]),An(o,a,i,t,r,s[1],c[1]);}}return a}function In(t){return "MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class zn{constructor(t,e){this.type=Ft,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new zn(e,e.features.map((t=>In(t.geometry))).flat());if("Feature"===e.type)return new zn(e,In(e.geometry));if("type"in e&&"coordinates"in e)return new zn(e,In(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!1,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!1,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!1,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!0,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!0,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!0,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const r=t.geometry();if(0===r.length||0===r[0].length)return NaN;const n=Qr(r,0).map((e=>e.map((e=>e.map((e=>Tr([e.x,e.y],t.canonical))))))),i=new an(n[0][0][0][1]);let s=1/0;for(const t of e)for(const e of n){switch(t.type){case "Point":s=Math.min(s,kn([t.coordinates],!1,e,i,s));break;case "LineString":s=Math.min(s,kn(t.coordinates,!0,e,i,s));break;case "Polygon":s=Math.min(s,_n(e,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return !0}}class Pn{constructor(t){this.type=Ut,this.key=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=t[1];return null==r?e.error("Global state property must be defined."):"string"!=typeof r?e.error(`Global state property must be string, but found ${typeof t[1]} instead.`):new Pn(r)}evaluate(t){var e;const r=null===(e=t.globals)||void 0===e?void 0:e.globalState;return r&&0!==Object.keys(r).length?xe(r,this.key):null}eachChild(){}outputDefined(){return !1}}const Cn={"==":vr,"!=":br,">":_r,"<":wr,">=":Ar,"<=":Sr,array:Ge,at:Qe,boolean:Ge,case:nr,coalesce:yr,collator:kr,format:Ir,image:zr,in:tr,"index-of":er,interpolate:pr,"interpolate-hcl":pr,"interpolate-lab":pr,length:Pr,let:Je,literal:Ne,match:rr,number:Ge,"number-format":Mr,object:Ge,slice:ir,step:ar,string:Ge,"to-boolean":Ze,"to-color":Ze,"to-number":Ze,"to-string":Ze,var:We,within:Yr,distance:zn,"global-state":Pn};class En{constructor(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return !1}static parse(t,e){const r=t[0],n=En.definitions[r];if(!n)return e.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let o=null;for(const[n,s]of a){o=new Ke(e.registry,$n,e.path,null,e.scope);const a=[];let l=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(Kt).join(", ")})`:`(${Kt(e.type)}...)`;var e;})).join(" | "),n=[];for(let r=1;r{r=e?r&&$n(t):r&&t instanceof Ne;})),!!r&&Dn(t)&&On(t,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function Dn(t){if(t instanceof En){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}if(t instanceof Yr)return !1;if(t instanceof zn)return !1;let e=!0;return t.eachChild((t=>{e&&!Dn(t)&&(e=!1);})),e}function Ln(t){if(t instanceof En&&"feature-state"===t.name)return !1;let e=!0;return t.eachChild((t=>{e&&!Ln(t)&&(e=!1);})),e}function On(t,e){if(t instanceof En&&e.indexOf(t.name)>=0)return !1;let r=!0;return t.eachChild((t=>{r&&!On(t,e)&&(r=!1);})),r}function Rn(t){return {result:"success",value:t}}function Un(t){return {result:"error",value:t}}function jn(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Nn(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function qn(t){return !!t.expression&&t.expression.interpolated}function Gn(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Xn(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)&&Ue(t)===Rt}function Zn(t){return t}function Yn(t,e){const r=t.stops&&"object"==typeof t.stops[0][0],n=r||!(r||void 0!==t.property),i=t.type||(qn(e)?"exponential":"interval"),s=function(t){switch(t.type){case "color":return Me.parse;case "padding":return Ee.parse;case "numberArray":return Te.parse;case "colorArray":return Be.parse;default:return null}}(e);if(s&&((t=Et({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],s(t[1])]))),t.default=s(t.default?t.default:e.default)),t.colorSpace&&"rgb"!==(a=t.colorSpace)&&"hcl"!==a&&"lab"!==a)throw new Error(`Unknown color space: "${t.colorSpace}"`);var a;const o=function(t){switch(t){case "exponential":return Wn;case "interval":return Jn;case "categorical":return Kn;case "identity":return Qn;default:throw new Error(`Unknown function type "${t}"`)}}(i);let l,u;if("categorical"===i){l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0];}if(r){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>Wn({stops:i,base:t.base},e,r).evaluate(r,n)}}if(n){const r="exponential"===i?{name:"exponential",base:void 0!==t.base?t.base:1}:null;return {kind:"camera",interpolationType:r,interpolationFactor:pr.interpolationFactor.bind(void 0,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>o(t,e,r,l,u)}}return {kind:"source",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:void 0;return void 0===i?Hn(t.default,e.default):o(t,e,i,l,u)}}}function Hn(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Kn(t,e,r,n,i){return Hn(typeof r===i?n[r]:void 0,t.default,e.default)}function Jn(t,e,r){if("number"!==Gn(r))return Hn(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=sr(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function Wn(t,e,r){const n=void 0!==t.base?t.base:1;if("number"!==Gn(r))return Hn(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=sr(t.stops.map((t=>t[0])),r),a=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),o=t.stops[s][1],l=t.stops[s+1][1],u=dr[e.type]||Zn;return "function"==typeof o.evaluate?{evaluate(...e){const r=o.evaluate.apply(void 0,e),n=l.evaluate.apply(void 0,e);if(void 0!==r&&void 0!==n)return u(r,n,a,t.colorSpace)}}:u(o,l,a,t.colorSpace)}function Qn(t,e,r){switch(e.type){case "color":r=Me.parse(r);break;case "formatted":r=Ce.fromString(r.toString());break;case "resolvedImage":r=De.fromString(r.toString());break;case "padding":r=Ee.parse(r);break;case "colorArray":r=Be.parse(r);break;case "numberArray":r=Te.parse(r);break;default:Gn(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0);}return Hn(r,t.default,e.default)}En.register(Cn,{error:[{kind:"error"},[$t],(t,[e])=>{throw new Ve(e.evaluate(t))}],typeof:[$t,[Ut],(t,[e])=>Kt(Ue(e.evaluate(t)))],"to-rgba":[Ht(Ft,4),[Lt],(t,[e])=>{const[r,n,i,s]=e.evaluate(t).rgb;return [255*r,255*n,255*i,s]}],rgb:[Lt,[Ft,Ft,Ft],Tn],rgba:[Lt,[Ft,Ft,Ft,Ft],Tn],has:{type:Dt,overloads:[[[$t],(t,[e])=>Bn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Bn(e.evaluate(t),r.evaluate(t))]]},get:{type:Ut,overloads:[[[$t],(t,[e])=>Vn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Vn(e.evaluate(t),r.evaluate(t))]]},"feature-state":[Ut,[$t],(t,[e])=>Vn(e.evaluate(t),t.featureState||{})],properties:[Rt,[],t=>t.properties()],"geometry-type":[$t,[],t=>t.geometryType()],id:[Ut,[],t=>t.id()],zoom:[Ft,[],t=>t.globals.zoom],"heatmap-density":[Ft,[],t=>t.globals.heatmapDensity||0],elevation:[Ft,[],t=>t.globals.elevation||0],"line-progress":[Ft,[],t=>t.globals.lineProgress||0],accumulated:[Ut,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[Ft,Fn(Ft),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],"*":[Ft,Fn(Ft),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],"-":{type:Ft,overloads:[[[Ft,Ft],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[Ft],(t,[e])=>-e.evaluate(t)]]},"/":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],"%":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[Ft,[],()=>Math.LN2],pi:[Ft,[],()=>Math.PI],e:[Ft,[],()=>Math.E],"^":[Ft,[Ft,Ft],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[Ft,[Ft],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))],log2:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[Ft,[Ft],(t,[e])=>Math.sin(e.evaluate(t))],cos:[Ft,[Ft],(t,[e])=>Math.cos(e.evaluate(t))],tan:[Ft,[Ft],(t,[e])=>Math.tan(e.evaluate(t))],asin:[Ft,[Ft],(t,[e])=>Math.asin(e.evaluate(t))],acos:[Ft,[Ft],(t,[e])=>Math.acos(e.evaluate(t))],atan:[Ft,[Ft],(t,[e])=>Math.atan(e.evaluate(t))],min:[Ft,Fn(Ft),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[Ft,Fn(Ft),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[Ft,[Ft],(t,[e])=>Math.abs(e.evaluate(t))],round:[Ft,[Ft],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[Ft,[Ft],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[Ft,[Ft],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[Dt,[$t,Ut],(t,[e,r])=>t.properties()[e.value]===r.value],"filter-id-==":[Dt,[Ut],(t,[e])=>t.id()===e.value],"filter-type-==":[Dt,[$t],(t,[e])=>t.geometryType()===e.value],"filter-<":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],"filter-<=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],"filter->=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],"filter-has":[Dt,[Ut],(t,[e])=>e.value in t.properties()],"filter-has-id":[Dt,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[Dt,[Ht($t)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[Dt,[Ht(Ut)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[Dt,[$t,Ht(Ut)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[Dt,[$t,Ht(Ut)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(!r.evaluate(t))return !1;return !0}]]},any:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(r.evaluate(t))return !0;return !1}]]},"!":[Dt,[Dt],(t,[e])=>!e.evaluate(t)],"is-supported-script":[Dt,[$t],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return !r||r(e.evaluate(t))}],upcase:[$t,[$t],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[$t,[$t],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[$t,Fn(Ut),(t,e)=>e.map((e=>je(e.evaluate(t)))).join("")],"resolved-locale":[$t,[jt],(t,[e])=>e.evaluate(t).resolvedLocale()]});class ti{constructor(t,e,r){this.expression=t,this._warningHistory={},this._evaluator=new He,this._defaultValue=e?function(t){if("color"===t.type&&Xn(t.default))return new Me(0,0,0,0);switch(t.type){case "color":return Me.parse(t.default)||null;case "padding":return Ee.parse(t.default)||null;case "numberArray":return Te.parse(t.default)||null;case "colorArray":return Be.parse(t.default)||null;case "variableAnchorOffsetCollection":return $e.parse(t.default)||null;case "projectionDefinition":return Le.parse(t.default)||null;default:return void 0===t.default?null:t.default}}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null,this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s){this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new Ve(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function ei(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Cn}function ri(t,e,r){const n=new Ke(Cn,$n,[],e?function(t){const e={color:Lt,string:$t,number:Ft,enum:$t,boolean:Dt,formatted:Nt,padding:qt,numberArray:Xt,colorArray:Gt,projectionDefinition:Ot,resolvedImage:Zt,variableAnchorOffsetCollection:Yt};return "array"===t.type?Ht(e[t.value]||Ut,t.length):e[t.type]}(e):void 0),i=n.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return i?Rn(new ti(i,e,r)):Un(n.errors)}class ni{constructor(t,e,r){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}}class ii{constructor(t,e,r,n,i){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this.interpolationType=n,this._globalState=i;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?pr.interpolationFactor(this.interpolationType,t,e,r):0}}function si(t,e,r){const n=ri(t,e,r);if("error"===n.result)return n;const i=n.value.expression,s=Dn(i);if(!s&&!jn(e))return Un([new Tt("","data expressions not supported")]);const a=On(i,["zoom"]);if(!a&&!Nn(e))return Un([new Tt("","zoom expressions not supported")]);const o=oi(i);return o||a?o instanceof Tt?Un([o]):o instanceof pr&&!qn(e)?Un([new Tt("",'"interpolate" expressions cannot be used with this property')]):Rn(o?new ii(s?"camera":"composite",n.value,o.labels,o instanceof pr?o.interpolation:void 0,r):new ni(s?"constant":"source",n.value,r)):Un([new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class ai{constructor(t,e){this._parameters=t,this._specification=e,Et(this,Yn(this._parameters,this._specification));}static deserialize(t){return new ai(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function oi(t){let e=null;if(t instanceof Je)e=oi(t.result);else if(t instanceof yr){for(const r of t.args)if(e=oi(r),e)break}else (t instanceof ar||t instanceof pr)&&t.input instanceof En&&"zoom"===t.input.name&&(e=t);return e instanceof Tt||t.eachChild((t=>{const r=oi(t);r instanceof Tt?e=r:!e&&r?e=new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&r&&e!==r&&(e=new Tt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),e}function li(t,e=new Set){return t instanceof Pn&&e.add(t.key),t.eachChild((t=>{li(t,e);})),e}function ui(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case "has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case "in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case "!in":case "!has":case "none":return !1;case "==":case "!=":case ">":case ">=":case "<":case "<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case "any":case "all":for(const e of t.slice(1))if(!ui(e)&&"boolean"!=typeof e)return !1;return !0;default:return !0}}const ci={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function hi(t,e){if(null==t)return {filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};ui(t)||(t=di(t));const r=ri(t,ci,e);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return {filter:(t,e,n)=>r.value.evaluate(t,e,{},n),needGeometry:fi(t),getGlobalStateRefs:()=>li(r.value.expression)}}function pi(t,e){return te?1:0}function fi(t){if(!Array.isArray(t))return !1;if("within"===t[0]||"distance"===t[0])return !0;for(let e=1;e"===e||"<="===e||">="===e?yi(t[1],t[2],e):"any"===e?(r=t.slice(1),["any"].concat(r.map(di))):"all"===e?["all"].concat(t.slice(1).map(di)):"none"===e?["all"].concat(t.slice(1).map(di).map(xi)):"in"===e?mi(t[1],t.slice(2)):"!in"===e?xi(mi(t[1],t.slice(2))):"has"===e?gi(t[1]):"!has"!==e||xi(gi(t[1]));var r;}function yi(t,e,r){switch(t){case "$type":return [`filter-type-${r}`,e];case "$id":return [`filter-id-${r}`,e];default:return [`filter-${r}`,t,e]}}function mi(t,e){if(0===e.length)return !1;switch(t){case "$type":return ["filter-type-in",["literal",e]];case "$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(pi)]]:["filter-in-small",t,["literal",e]]}}function gi(t){switch(t){case "$type":return !0;case "$id":return ["filter-has-id"];default:return ["filter-has",t]}}function xi(t){return ["!",t]}function vi(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const r of t)e+=`${vi(r)},`;return `${e}]`}const r=Object.keys(t).sort();let n="{";for(let e=0;en.maximum?[new Ct(e,r,`${r} is greater than the maximum value ${n.maximum}`)]:[]}function Ii(t){const e=t.valueSpec,r=_i(t.value.type);let n,i,s,a={};const o="categorical"!==r&&void 0===t.value.property,l=!o,u="array"===Gn(t.value.stops)&&"array"===Gn(t.value.stops[0])&&"object"===Gn(t.value.stops[0][0]),c=Ai({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===r)return [new Ct(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const n=t.value;return e=e.concat(ki({key:t.key,value:n,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===Gn(n)&&0===n.length&&e.push(new Ct(t.key,n,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===r&&o&&c.push(new Ct(t.key,t.value,'missing required property "property"')),"identity"===r||t.value.stops||c.push(new Ct(t.key,t.value,'missing required property "stops"')),"exponential"===r&&t.valueSpec.expression&&!qn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!jn(t.valueSpec)?c.push(new Ct(t.key,t.value,"property functions not supported")):o&&!Nn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"zoom functions not supported"))),"categorical"!==r&&!u||void 0!==t.value.property||c.push(new Ct(t.key,t.value,'"property" property is required')),c;function h(t){let r=[];const n=t.value,o=t.key;if("array"!==Gn(n))return [new Ct(o,n,`array expected, ${Gn(n)} found`)];if(2!==n.length)return [new Ct(o,n,`array length 2 expected, length ${n.length} found`)];if(u){if("object"!==Gn(n[0]))return [new Ct(o,n,`object expected, ${Gn(n[0])} found`)];if(void 0===n[0].zoom)return [new Ct(o,n,"object stop key must have zoom")];if(void 0===n[0].value)return [new Ct(o,n,"object stop key must have value")];if(s&&s>_i(n[0].zoom))return [new Ct(o,n[0].zoom,"stop zoom values must appear in ascending order")];_i(n[0].zoom)!==s&&(s=_i(n[0].zoom),i=void 0,a={}),r=r.concat(Ai({key:`${o}[0]`,value:n[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Mi,value:p}}));}else r=r.concat(p({key:`${o}[0]`,value:n[0],validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},n));return ei(Si(n[1]))?r.concat([new Ct(`${o}[1]`,n[1],"expressions are not allowed in function stops.")]):r.concat(t.validateSpec({key:`${o}[1]`,value:n[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const o=Gn(t.value),l=_i(t.value),u=null!==t.value?t.value:s;if(n){if(o!==n)return [new Ct(t.key,u,`${o} stop domain type must match previous stop domain type ${n}`)]}else n=o;if("number"!==o&&"string"!==o&&"boolean"!==o)return [new Ct(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==o&&"categorical"!==r){let n=`number expected, ${o} found`;return jn(e)&&void 0===r&&(n+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new Ct(t.key,u,n)]}return "categorical"!==r||"number"!==o||isFinite(l)&&Math.floor(l)===l?"categorical"!==r&&"number"===o&&void 0!==i&&lnew Ct(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new Ct(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!On(r,["zoom","feature-state"]))return [new Ct(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!Dn(r))return [new Ct(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function Pi(t){const e=t.key,r=t.value,n=Gn(r);return "string"!==n?[new Ct(e,r,`color expected, ${n} found`)]:Me.parse(String(r))?[]:[new Ct(e,r,`color expected, "${r}" found`)]}function Ci(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${n.values.join(", ")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${Object.keys(n.values).join(", ")}], ${JSON.stringify(r)} found`)),i}function Ei(t){return ui(Si(t.value))?zi(Et({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):Ti(t)}function Ti(t){const e=t.value,r=t.key;if("array"!==Gn(e))return [new Ct(r,e,`array expected, ${Gn(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return [new Ct(r,e,"filter array must have at least 1 element")];switch(s=s.concat(Ci({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),_i(e[0])){case "<":case "<=":case ">":case ">=":e.length>=2&&"$type"===_i(e[1])&&s.push(new Ct(r,e,`"$type" cannot be use with operator "${e[0]}"`));case "==":case "!=":3!==e.length&&s.push(new Ct(r,e,`filter array for operator "${e[0]}" must have 3 elements`));case "in":case "!in":e.length>=2&&(i=Gn(e[1]),"string"!==i&&s.push(new Ct(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let a=2;a{t in r&&e.push(new Ct(n,r[t],`"${t}" is prohibited for ref layers`));})),i.layers.forEach((e=>{_i(e.id)===o&&(t=e);})),t?t.ref?e.push(new Ct(n,r.ref,"ref cannot reference another ref layer")):a=_i(t.type):e.push(new Ct(n,r.ref,`ref layer "${o}" not found`));}else if("background"!==a)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&_i(t.type);t?"vector"===s&&"raster"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster source`)):"raster-dem"!==s&&"hillshade"===a||"raster-dem"!==s&&"color-relief"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster-dem source`)):"raster"===s&&"raster"!==a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a vector source`)):"vector"!==s||r["source-layer"]?"raster-dem"===s&&"hillshade"!==a&&"color-relief"!==a?e.push(new Ct(n,r.source,"raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.")):"line"!==a||!r.paint||!r.paint["line-gradient"]||"geojson"===s&&t.lineMetrics||e.push(new Ct(n,r,`layer "${r.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new Ct(n,r,`layer "${r.id}" must specify a "source-layer"`)):e.push(new Ct(n,r.source,`source "${r.source}" not found`));}else e.push(new Ct(n,r,'missing required property "source"'));return e=e.concat(Ai({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:r,objectKey:"type"}),filter:Ei,layout:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Fi(Et({layerType:a},t))}}),paint:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Vi(Et({layerType:a},t))}})}})),e}function Di(t){const e=t.value,r=t.key,n=Gn(e);return "string"!==n?[new Ct(r,e,`string expected, ${n} found`)]:[]}const Li={promoteId:function({key:t,value:e}){if("string"===Gn(e))return Di({key:t,value:e});{const r=[];for(const n in e)r.push(...Di({key:`${t}.${n}`,value:e[n]}));return r}}};function Oi(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return [new Ct(r,e,'"type" is required')];const a=_i(e.type);let o;switch(a){case "vector":case "raster":return o=Ai({key:r,value:e,valueSpec:n[`source_${a.replace("-","_")}`],style:t.style,styleSpec:n,objectElementValidators:Li,validateSpec:s}),o;case "raster-dem":return o=function(t){var e;const r=null!==(e=t.sourceName)&&void 0!==e?e:"",n=t.value,i=t.styleSpec,s=i.source_raster_dem,a=t.style;let o=[];const l=Gn(n);if(void 0===n)return o;if("object"!==l)return o.push(new Ct("source_raster_dem",n,`object expected, ${l} found`)),o;const u="custom"===_i(n.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in n)!u&&c.includes(e)?o.push(new Ct(e,n[e],`In "${r}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?o=o.concat(t.validateSpec({key:e,value:n[e],valueSpec:s[e],validateSpec:t.validateSpec,style:a,styleSpec:i})):o.push(new Ct(e,n[e],`unknown property "${e}"`));return o}({sourceName:r,value:e,style:t.style,styleSpec:n,validateSpec:s}),o;case "geojson":if(o=Ai({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,validateSpec:s,objectElementValidators:Li}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],s="string"==typeof n?[n,["accumulated"],["get",t]]:n;o.push(...zi({key:`${r}.${t}.map`,value:i,expressionContext:"cluster-map"})),o.push(...zi({key:`${r}.${t}.reduce`,value:s,expressionContext:"cluster-reduce"}));}return o;case "video":return Ai({key:r,value:e,valueSpec:n.source_video,style:i,validateSpec:s,styleSpec:n});case "image":return Ai({key:r,value:e,valueSpec:n.source_image,style:i,validateSpec:s,styleSpec:n});case "canvas":return [new Ct(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Ci({key:`${r}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]}})}}function Ri(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("light",e,`object expected, ${a} found`)]),s;for(const a in e){const o=a.match(/^(.*)-transition$/);s=s.concat(o&&n[o[1]]&&n[o[1]].transition?t.validateSpec({key:a,value:e[a],valueSpec:r.transition,validateSpec:t.validateSpec,style:i,styleSpec:r}):n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);}return s}function Ui(t){const e=t.value,r=t.styleSpec,n=r.sky,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("sky",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a}function ji(t){const e=t.value,r=t.styleSpec,n=r.terrain,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("terrain",e,`object expected, ${a} found`)]),s;for(const a in e)s=s.concat(n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);return s}function Ni(t){let e=[];const r=t.value,n=t.key;if(Array.isArray(r)){const i=[],s=[];for(const a in r)r[a].id&&i.includes(r[a].id)&&e.push(new Ct(n,r,`all the sprites' ids must be unique, but ${r[a].id} is duplicated`)),i.push(r[a].id),r[a].url&&s.includes(r[a].url)&&e.push(new Ct(n,r,`all the sprites' URLs must be unique, but ${r[a].url} is duplicated`)),s.push(r[a].url),e=e.concat(Ai({key:`${n}[${a}]`,value:r[a],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:t.validateSpec}));return e}return Di({key:n,value:r})}function qi(t){return e=t.value,Boolean(e)&&e.constructor===Object?[]:[new Ct(t.key,t.value,`object expected, ${Gn(t.value)} found`)];var e;}const Gi={"*":()=>[],array:ki,boolean:function(t){const e=t.value,r=t.key,n=Gn(e);return "boolean"!==n?[new Ct(r,e,`boolean expected, ${n} found`)]:[]},number:Mi,color:Pi,constants:wi,enum:Ci,filter:Ei,function:Ii,layer:$i,object:Ai,source:Oi,light:Ri,sky:Ui,terrain:ji,projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("projection",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a},projectionDefinition:function(t){const e=t.key;let r=t.value;r=r instanceof String?r.valueOf():r;const n=Gn(r);return "array"!==n||function(t){return Array.isArray(t)&&3===t.length&&"string"==typeof t[0]&&"string"==typeof t[1]&&"number"==typeof t[2]}(r)||function(t){return !!["interpolate","step","literal"].includes(t[0])}(r)?["array","string"].includes(n)?[]:[new Ct(e,r,`projection expected, invalid type "${n}" found`)]:[new Ct(e,r,`projection expected, invalid array ${JSON.stringify(r)} found`)]},string:Di,formatted:function(t){return 0===Di(t).length?[]:zi(t)},resolvedImage:function(t){return 0===Di(t).length?[]:zi(t)},padding:function(t){const e=t.key,r=t.value;if("array"===Gn(r)){if(r.length<1||r.length>4)return [new Ct(e,r,`padding requires 1 to 4 values; ${r.length} values found`)];const n={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(r=r.concat(wi({key:"constants",value:t.constants}))),Ki(r)}function Hi(t){return function(e){return t({...e,validateSpec:Xi})}}function Ki(t){return [].concat(t).sort(((t,e)=>t.line-e.line))}function Ji(t){return function(...e){return Ki(t.apply(this,e))}}Yi.source=Ji(Hi(Oi)),Yi.sprite=Ji(Hi(Ni)),Yi.glyphs=Ji(Hi(Zi)),Yi.light=Ji(Hi(Ri)),Yi.sky=Ji(Hi(Ui)),Yi.terrain=Ji(Hi(ji)),Yi.state=Ji(Hi(qi)),Yi.layer=Ji(Hi($i)),Yi.filter=Ji(Hi(Ei)),Yi.paintProperty=Ji(Hi(Vi)),Yi.layoutProperty=Ji(Hi(Fi));const Wi=Yi,Qi=Wi.light,ts=Wi.sky,es=Wi.paintProperty,rs=Wi.layoutProperty;function ns(t,e){let r=!1;if(e&&e.length)for(const n of e)t.fire(new mt(new Error(n.message))),r=!0;return r}class is{constructor(t,e,r){const n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(let t=0;t=u[l+0]&&n>=u[l+1])?(a[h]=!0,s.push(i[h])):a[h]=!1;}}}}_forEachCell(t,e,r,n,i,s,a,o){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!o||o(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,r,n,u,s,a,o))return}}_convertFromCellCoord(t){return (t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let r=0;for(let t=0;t=0)continue;const s=t[n];i[n]=ss[r].shallow.indexOf(n)>=0?s:cs(s,e);}t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==r&&(i.$name=r),i}function hs(t){if(us(t))return t;if(Array.isArray(t))return t.map(hs);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=ls(t)||"Object";if(!ss[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:r}=ss[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const r of Object.keys(t)){if("$name"===r)continue;const i=t[r];n[r]=ss[e].shallow.indexOf(r)>=0?i:hs(i);}return n}class ps{constructor(){this.first=!0;}update(t,e){const r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Hiragana:t=>t>=12352&&t<=12447,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"CJK Unified Ideographs":t=>t>=19968&&t<=40959,"Hangul Syllables":t=>t>=44032&&t<=55215,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function ds(t){for(const e of t)if(bs(e.charCodeAt(0)))return !0;return !1}function ys(t){for(const e of t)if(!xs(e.charCodeAt(0)))return !1;return !0}function ms(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const gs=ms(["Arab","Dupl","Mong","Ougr","Syrc"]);function xs(t){return !gs.test(String.fromCodePoint(t))}const vs=ms(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function bs(t){return !(746!==t&&747!==t&&(t<4352||!(fs["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||fs["CJK Compatibility"](t)||fs["CJK Strokes"](t)||!(!fs["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||fs["Enclosed CJK Letters and Months"](t)||fs["Ideographic Description Characters"](t)||fs.Kanbun(t)||fs.Katakana(t)&&12540!==t||!(!fs["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!fs["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||fs["Vertical Forms"](t)||fs["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||vs.test(String.fromCodePoint(t)))))}function ws(t){return !(bs(t)||function(t){return !!(fs["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||fs["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||fs["Letterlike Symbols"](t)||fs["Number Forms"](t)||fs["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||fs["Control Pictures"](t)&&9251!==t||fs["Optical Character Recognition"](t)||fs["Enclosed Alphanumerics"](t)||fs["Geometric Shapes"](t)||fs["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||fs["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||fs["CJK Symbols and Punctuation"](t)||fs.Katakana(t)||fs["Private Use Area"](t)||fs["CJK Compatibility Forms"](t)||fs["Small Form Variants"](t)||fs["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}const _s=ms(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Ss(t){return _s.test(String.fromCodePoint(t))}function As(t,e){return !(!e&&Ss(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||fs.Khmer(t))}function ks(t){for(const e of t)if(Ss(e.charCodeAt(0)))return !0;return !1}const Ms=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{};}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL;}getState(){return {pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){if(Ms.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText,this.loadScriptResolve();}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(t,r){return e(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if("loading"!==t.pluginStatus)return this.setState(t),t;const e=t.pluginURL,n=new Promise((t=>{this.loadScriptResolve=t;}));r(e);const i=new Promise((t=>setTimeout((()=>t()),this.TIMEOUT)));if(yield Promise.race([n,i]),this.isParsed()){const t={pluginStatus:"loaded",pluginURL:e};return this.setState(t),t}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${e}`)}))}};class Is{constructor(t,e){this.isSupportedScript=zs,this.zoom=t,e?(this.now=e.now||0,this.fadeDuration=e.fadeDuration||0,this.zoomHistory=e.zoomHistory||new ps,this.transition=e.transition||{}):(this.now=0,this.fadeDuration=0,this.zoomHistory=new ps,this.transition={});}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}}}function zs(t){return function(t,e){for(const r of t)if(!As(r.charCodeAt(0),e))return !1;return !0}(t,"loaded"===Ms.getRTLTextPluginStatus())}class Ps{constructor(t,e,r){this.property=t,this.value=e,this.expression=function(t,e,r){if(Xn(t))return new ai(t,e);if(ei(t)){const n=si(t,e,r);if("error"===n.result)throw new Error(n.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return n.value}{let r=t;return "color"===e.type&&"string"==typeof t?r=Me.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"numberArray"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"colorArray"!==e.type||"string"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)?r=$e.parse(t):"projectionDefinition"===e.type&&"string"==typeof t&&(r=Le.parse(t)):r=Be.parse(t):r=Te.parse(t):r=Ee.parse(t),{globalStateRefs:new Set,_globalState:null,kind:"constant",evaluate:()=>r}}}(void 0===e?t.specification.default:e,t.specification,r);}isDataDriven(){return "source"===this.expression.kind||"composite"===this.expression.kind}getGlobalStateRefs(){return this.expression.globalStateRefs||new Set}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class Cs{constructor(t,e){this.property=t,this.value=new Ps(t,void 0,e);}transitioned(t,e){return new Ts(this.property,this.value,e,L({},t.transition,this.transition),t.now)}untransitioned(){return new Ts(this.property,this.value,null,{},0)}}class Es{constructor(t,e){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues),this._globalState=e;}getValue(t){return j(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].value=new Ps(this._values[t].property,null===e?void 0:j(e),this._globalState);}getTransition(t){return j(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].transition=j(e)||void 0;}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r);const n=this.getTransition(e);void 0!==n&&(t[`${e}-transition`]=n);}return t}transitioned(t,e){const r=new Bs(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new Bs(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class Ts{constructor(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(nn.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Rs{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new Is(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Is(Math.floor(e.zoom),e)),t.expression.evaluate(new Is(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Us{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)}interpolate(){return !1}}class js{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const r=t[e];r.specification.overridable&&this.overridableProperties.push(e);const n=this.defaultPropertyValues[e]=new Ps(r,void 0,void 0),i=this.defaultTransitionablePropertyValues[e]=new Cs(r,void 0);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}}}as("DataDrivenProperty",Ls),as("DataConstantProperty",Ds),as("CrossFadedDataDrivenProperty",Os),as("CrossFadedProperty",Rs),as("ColorRampProperty",Us);const Ns="-transition";class qs extends gt{constructor(t,e,r){if(super(),this.id=t.id,this.type=t.type,this._globalState=r,this._featureFilter={filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter,this._featureFilter=hi(t.filter,r)),e.layout&&(this._unevaluatedLayout=new Vs(e.layout,r)),e.paint)){this._transitionablePaint=new Es(e.paint,r);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new $s(e.paint);}}setFilter(t){this.filter=t,this._featureFilter=hi(t,this._globalState);}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}getLayoutAffectingGlobalStateRefs(){const t=new Set;if(this._unevaluatedLayout)for(const e in this._unevaluatedLayout._values){const r=this._unevaluatedLayout._values[e];for(const e of r.getGlobalStateRefs())t.add(e);}for(const e of this._featureFilter.getGlobalStateRefs())t.add(e);return t}getPaintAffectingGlobalStateRefs(){var t;const e=new globalThis.Map;if(this._transitionablePaint)for(const r in this._transitionablePaint._values){const n=this._transitionablePaint._values[r].value;for(const i of n.getGlobalStateRefs()){const s=null!==(t=e.get(i))&&void 0!==t?t:[];s.push({name:r,value:n.value}),e.set(i,s);}}return e}setLayoutProperty(t,e,r={}){null!=e&&this._validate(rs,`layers.${this.id}.layout.${t}`,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);}getPaintProperty(t){return t.endsWith(Ns)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(es,`layers.${this.id}.paint.${t}`,t,e,r))return !1;if(t.endsWith(Ns))return this._transitionablePaint.setTransition(t.slice(0,-11),e||void 0),!1;{const r=this._transitionablePaint._values[t],n="cross-faded-data-driven"===r.property.specification["property-type"],i=r.value.isDataDriven(),s=r.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const a=this._transitionablePaint._values[t].value;return a.isDataDriven()||i||n||this._handleOverridablePaintPropertyUpdate(t,s,a)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,r){return !1}isHidden(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),U(t,((t,e)=>!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return (!i||!1!==i.validate)&&ns(this,t.call(Wi,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:xt,style:{glyphs:!0,sprite:!0}}))}is3D(){return !1}isTileClipped(){return !1}hasOffscreenPass(){return !1}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof Fs&&jn(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1}}const Gs={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Xs{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class Zs{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Ys(t,e=1){let r=0,n=0;return {members:t.map((t=>{const i=Gs[t.type].BYTES_PER_ELEMENT,s=r=Hs(r,Math.max(e,i)),a=t.components||1;return n=Math.max(n,i),r+=i*a,{name:t.name,type:t.type,components:a,offset:s}})),size:Hs(r,Math.max(n,e)),alignment:e}}function Hs(t,e){return Math.ceil(t/e)*e}class Ks extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}Ks.prototype.bytesPerElement=4,as("StructArrayLayout2i4",Ks);class Js extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}Js.prototype.bytesPerElement=6,as("StructArrayLayout3i6",Js);class Ws extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}Ws.prototype.bytesPerElement=8,as("StructArrayLayout4i8",Ws);class Qs extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}Qs.prototype.bytesPerElement=12,as("StructArrayLayout2i4i12",Qs);class ta extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=4*t,l=8*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.uint8[l+4]=n,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=a,t}}ta.prototype.bytesPerElement=8,as("StructArrayLayout2i4ub8",ta);class ea extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}ea.prototype.bytesPerElement=8,as("StructArrayLayout2f8",ea);class ra extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,s,a,o,l,u)}emplace(t,e,r,n,i,s,a,o,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=r,this.uint16[h+2]=n,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=a,this.uint16[h+6]=o,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}ra.prototype.bytesPerElement=20,as("StructArrayLayout10ui20",ra);class na extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,a,o,l,u,c,h)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=a,this.uint16[f+6]=o,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}na.prototype.bytesPerElement=24,as("StructArrayLayout4i4ui4i24",na);class ia extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}ia.prototype.bytesPerElement=12,as("StructArrayLayout3f12",ia);class sa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}sa.prototype.bytesPerElement=4,as("StructArrayLayout1ul4",sa);class aa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,s,a,o,l)}emplace(t,e,r,n,i,s,a,o,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=r,this.int16[c+2]=n,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=a,this.uint32[h+3]=o,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}aa.prototype.bytesPerElement=20,as("StructArrayLayout6i1ul2ui20",aa);class oa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}oa.prototype.bytesPerElement=12,as("StructArrayLayout2i2i2i12",oa);class la extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.int16[o+6]=i,this.int16[o+7]=s,t}}la.prototype.bytesPerElement=16,as("StructArrayLayout2f1f2i16",la);class ua extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=16*t,l=4*t,u=8*t;return this.uint8[o+0]=e,this.uint8[o+1]=r,this.float32[l+1]=n,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=a,t}}ua.prototype.bytesPerElement=16,as("StructArrayLayout2ub2f2i16",ua);class ca extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}ca.prototype.bytesPerElement=6,as("StructArrayLayout3ui6",ca);class ha extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=r,this.uint16[x+2]=n,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=a,this.uint32[v+4]=o,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}ha.prototype.bytesPerElement=48,as("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",ha);class pa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I){const z=this.length;return this.resize(z+1),this.emplace(z,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I,z){const P=32*t,C=16*t;return this.int16[P+0]=e,this.int16[P+1]=r,this.int16[P+2]=n,this.int16[P+3]=i,this.int16[P+4]=s,this.int16[P+5]=a,this.int16[P+6]=o,this.int16[P+7]=l,this.uint16[P+8]=u,this.uint16[P+9]=c,this.uint16[P+10]=h,this.uint16[P+11]=p,this.uint16[P+12]=f,this.uint16[P+13]=d,this.uint16[P+14]=y,this.uint16[P+15]=m,this.uint16[P+16]=g,this.uint16[P+17]=x,this.uint16[P+18]=v,this.uint16[P+19]=b,this.uint16[P+20]=w,this.uint16[P+21]=_,this.uint16[P+22]=S,this.uint32[C+12]=A,this.float32[C+13]=k,this.float32[C+14]=M,this.uint16[P+30]=I,this.uint16[P+31]=z,t}}pa.prototype.bytesPerElement=64,as("StructArrayLayout8i15ui1ul2f2ui64",pa);class fa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}fa.prototype.bytesPerElement=4,as("StructArrayLayout1f4",fa);class da extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}da.prototype.bytesPerElement=12,as("StructArrayLayout1ui2f12",da);class ya extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t}}ya.prototype.bytesPerElement=8,as("StructArrayLayout1ul2ui8",ya);class ma extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}ma.prototype.bytesPerElement=4,as("StructArrayLayout2ui4",ma);class ga extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}ga.prototype.bytesPerElement=2,as("StructArrayLayout1ui2",ga);class xa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}xa.prototype.bytesPerElement=16,as("StructArrayLayout4f16",xa);class va extends Xs{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new r(this.anchorPointX,this.anchorPointY)}}va.prototype.size=20;class ba extends aa{get(t){return new va(this,t)}}as("CollisionBoxArray",ba);class wa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t;}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}wa.prototype.size=48;class _a extends ha{get(t){return new wa(this,t)}}as("PlacedSymbolArray",_a);class Sa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t;}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}Sa.prototype.size=64;class Aa extends pa{get(t){return new Sa(this,t)}}as("SymbolInstanceArray",Aa);class ka extends fa{getoffsetX(t){return this.float32[1*t+0]}}as("GlyphOffsetArray",ka);class Ma extends Js{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}as("SymbolLineVertexArray",Ma);class Ia extends Xs{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}Ia.prototype.size=12;class za extends da{get(t){return new Ia(this,t)}}as("TextAnchorOffsetArray",za);class Pa extends Xs{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}Pa.prototype.size=8;class Ca extends ya{get(t){return new Pa(this,t)}}as("FeatureIndexArray",Ca);class Ea extends Ks{}class Ta extends Ks{}class Ba extends Ks{}class Va extends Qs{}class Fa extends ta{}class $a extends ea{}class Da extends ra{}class La extends na{}class Oa extends ia{}class Ra extends sa{}class Ua extends oa{}class ja extends ua{}class Na extends ca{}class qa extends ma{}const Ga=Ys([{name:"a_pos",components:2,type:"Int16"}],4),{members:Xa}=Ga;class Za{constructor(t=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=t;}prepareSegment(t,e,r,n){const i=this.segments[this.segments.length-1];return t>Za.MAX_VERTEX_ARRAY_LENGTH&&q(`Max vertices per segment is ${Za.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${Za.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!i||i.vertexLength+t>Za.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n?this.createNewSegment(e,r,n):i}createNewSegment(t,e,r){const n={vertexOffset:t.length,primitiveOffset:e.length,vertexLength:0,primitiveLength:0,vaos:{}};return void 0!==r&&(n.sortKey=r),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(n),n}getOrCreateLatestSegment(t,e,r){return this.prepareSegment(0,t,e,r)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0;}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,r,n){return new Za([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function Ya(t,e){return 256*(t=$(Math.floor(t),0,255))+$(Math.floor(e),0,255)}Za.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,as("SegmentVector",Za);const Ha=Ys([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var Ka,Ja,Wa,Qa={exports:{}},to={exports:{}},eo={exports:{}},ro=function(){if(Wa)return Qa.exports;Wa=1;var t=(Ka||(Ka=1,to.exports=function(t,e){var r,n,i,s,a,o,l,u;for(n=t.length-(r=3&t.length),i=e,a=3432918353,o=461845907,u=0;u>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0}),to.exports),e=(Ja||(Ja=1,eo.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0}),eo.exports);return Qa.exports=t,Qa.exports.murmur3=t,Qa.exports.murmur2=e,Qa.exports}(),no=n(ro);class io{constructor(){this.ids=[],this.positions=[],this.indexed=!1;}add(t,e,r,n){this.ids.push(so(t)),this.positions.push(e,r,n);}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=so(t);let r=0,n=this.ids.length-1;for(;r>1;this.ids[t]>=e?n=t:r=t+1;}const i=[];for(;this.ids[r]===e;)i.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return i}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return ao(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}}static deserialize(t){const e=new io;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e}}function so(t){const e=+t;return !isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:no(String(t))}function ao(t,e,r,n){for(;r>1];let s=r-1,a=n+1;for(;;){do{s++;}while(t[s]i);if(s>=a)break;oo(t,s,a),oo(e,3*s,3*a),oo(e,3*s+1,3*a+1),oo(e,3*s+2,3*a+2);}a-r`u_${t}`)),this.type=r;}setUniform(t,e,r){t.set(r.constantOr(this.value));}getBinding(t,e,r){return "color"===this.type?new ho(t,e):new uo(t,e)}}class mo{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;}setUniform(t,e,r,n){const i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);}getBinding(t,e,r){return "u_pattern"===r.substr(0,9)?new co(t,e):new uo(t,e)}}class go{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?2:1,offset:0}))),this.paintVertexArray=new n;}populatePaintArray(t,e,r){const n=this.paintVertexArray.length,i=this.expression.evaluate(new Is(0,r),e,{},r.canonical,[],r.formattedSection);this.paintVertexArray.resize(t),this._setPaintValue(n,t,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(0,i),r,n);this._setPaintValue(t,e,s);}_setPaintValue(t,e,r){if("color"===this.type){const n=fo(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,r){const n=this.expression.evaluate(new Is(this.zoom,r),e,{},r.canonical,[],r.formattedSection),i=this.expression.evaluate(new Is(this.zoom+1,r),e,{},r.canonical,[],r.formattedSection),s=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(s,t,n,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(this.zoom,i),r,n),a=this.expression.evaluate(new Is(this.zoom+1,i),r,n);this._setPaintValue(t,e,s,a);}_setPaintValue(t,e,r,n){if("color"===this.type){const i=fo(r),s=fo(n);for(let r=t;r`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof go||r instanceof xo)for(let e=0;e!0){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new bo(n,e,r);this.needsUpload=!1,this._featureMap=new io,this._bufferOffset=0;}populatePaintArrays(t,e,r,n){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;}updatePaintArrays(t,e,r,n){for(const i of r)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,n)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}function _o(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function So(t,e,r){const n={color:{source:ea,composite:xa},number:{source:fa,composite:ea}},i=function(t){return {"line-pattern":{source:Da,composite:Da},"fill-pattern":{source:Da,composite:Da},"fill-extrusion-pattern":{source:Da,composite:Da}}[t]}(t);return i&&i[r]||n[e][r]}as("ConstantBinder",yo),as("CrossFadedConstantBinder",mo),as("SourceExpressionBinder",go),as("CrossFadedCompositeBinder",vo),as("CompositeExpressionBinder",xo),as("ProgramConfiguration",bo,{omit:["_buffers"]}),as("ProgramConfigurationSet",wo);const Ao=Math.pow(2,14)-1,ko=-Ao-1;function Mo(t){const e=P/t.extent,r=t.loadGeometry();for(let t=0;tr.x+1||sr.y+1)&&q("Geometry exceeds allowed extent, reduce your vector tile buffer size");}}return r}function Io(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?Mo(t):[]}}const zo=-32768;function Po(t,e,r,n,i){t.emplaceBack(zo+8*e+n,zo+8*r+i);}class Co{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Ta,this.indexArray=new Na,this.segments=new Za,this.programConfigurations=new wo(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){const n=this.layers[0],i=[];let s=null,a=!1,o="heatmap"===n.type;if("circle"===n.type){const t=n;s=t.layout.get("circle-sort-key"),a=!s.isConstant(),o=o||"map"===t.paint.get("circle-pitch-alignment");}const l=o?e.subdivisionGranularity.circle:1;for(const{feature:e,id:n,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=a?s.evaluate(u,{},r):void 0,h={id:n,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};i.push(h);}a&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of i){const{geometry:i,index:s,sourceLayerIndex:a}=n,o=t[s].feature;this.addFeature(n,i,s,r,l),e.featureIndex.insert(o,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Xa),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,r,n,i=1){let s;switch(i){case 1:s=[0,7];break;case 3:s=[0,2,5,7];break;case 5:s=[0,1,3,4,6,7];break;case 7:s=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${i}; valid values are 1, 3, 5, 7.`)}const a=s.length;for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=P||n<0||n>=P)continue;const i=this.segments.prepareSegment(a*a,this.layoutVertexArray,this.indexArray,t.sortKey),o=i.vertexLength;for(let t=0;t1){if(Fo(t,e))return !0;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function Oo(t,e){let r,n,i,s=!1;for(let a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s);}return s}function Ro(t,e){let r=!1;for(let n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-s.x)*(e.y-s.y)/(a.y-s.y)+s.x&&(r=!r);}return r}function Uo(t,e,r){const n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;const s=G(t,e,r[0]);return s!==G(t,e,r[1])||s!==G(t,e,r[2])||s!==G(t,e,r[3])}function jo(t,e,r){const n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function No(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function qo(t,e,n,i,s){if(!e[0]&&!e[1])return t;const a=r.convert(e)._mult(s);"viewport"===n&&a._rotate(-i);const o=[];for(let e=0;eKo(t,e,r,n)))}(l,i,a,o),f=u),Ho({queryGeometry:p,size:f,transform:i,unwrappedTileID:a,getElevation:o,pitchAlignment:h,pitchScale:c},n)}}class el extends Co{}let rl;as("HeatmapBucket",el,{omit:["layers"]});var nl={get paint(){return rl=rl||new js({"heatmap-radius":new Ls(xt.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Ls(xt.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Ds(xt.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Us(xt.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Ds(xt.paint_heatmap["heatmap-opacity"])})}};function il(t,{width:e,height:r},n,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*r*n)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*r*n}`)}else i=new Uint8Array(e*r*n);return t.width=e,t.height=r,t.data=i,t}function sl(t,{width:e,height:r},n){if(e===t.width&&r===t.height)return;const i=il({},{width:e,height:r},n);al(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,r)},n),t.width=e,t.height=r,t.data=i.data;}function al(t,e,r,n,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const a=t.data,o=e.data;if(a===o)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=a;const o=t.expression.evaluate(e);i.setPixel(n/4/r,s/4,o);};if(t.clips)for(let e=0,i=0;ethis.max&&(this.max=r),r=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)}unpack(t,e,r){return t*this.redFactor+e*this.greenFactor+r*this.blueFactor-this.baseShift}pack(t){return vl(t,this.getUnpackVector())}getPixels(){return new ll({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,a=r*this.dim+this.dim;switch(e){case -1:n=i-1;break;case 1:i=n+1;}switch(r){case -1:s=a-1;break;case 1:a=s+1;}const o=-e*this.dim,l=-r*this.dim;for(let e=s;e0)for(let i=e;i=e;i-=n)s=Zl(i/n|0,t[i],t[i+1],s);return s&&Ul(s,s.next)&&(Yl(s),s=s.next),s}function Ml(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!Ul(n,n.next)&&0!==Rl(n.prev,n,n.next))n=n.next;else {if(Yl(n),n=e=n.prev,n===n.next)break;r=!0;}}while(r||n!==e);return e}function Il(t,e,r,n,i,s,a){if(!t)return;!a&&s&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=Fl(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let s=null;for(e=0;i;){e++;let a=i,o=0;for(let t=0;t0||l>0&&a;)0!==o&&(0===l||!a||i.z<=a.z)?(n=i,i=i.nextZ,o--):(n=a,a=a.nextZ,l--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;i=a;}s.nextZ=null,r*=2;}while(e>1)}(i);}(t,n,i,s);let o=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?Pl(t,n,i,s):zl(t))e.push(l.i,t.i,u.i),Yl(t),t=u.next,o=u.next;else if((t=u)===o){a?1===a?Il(t=Cl(Ml(t),e),e,r,n,i,s,2):2===a&&El(t,e,r,n,i,s):Il(Ml(t),e,r,n,i,s,1);break}}}function zl(t){const e=t.prev,r=t,n=t.next;if(Rl(e,r,n)>=0)return !1;const i=e.x,s=r.x,a=n.x,o=e.y,l=r.y,u=n.y,c=Math.min(i,s,a),h=Math.min(o,l,u),p=Math.max(i,s,a),f=Math.max(o,l,u);let d=n.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&Ll(i,o,s,l,a,u,d.x,d.y)&&Rl(d.prev,d,d.next)>=0)return !1;d=d.next;}return !0}function Pl(t,e,r,n){const i=t.prev,s=t,a=t.next;if(Rl(i,s,a)>=0)return !1;const o=i.x,l=s.x,u=a.x,c=i.y,h=s.y,p=a.y,f=Math.min(o,l,u),d=Math.min(c,h,p),y=Math.max(o,l,u),m=Math.max(c,h,p),g=Fl(f,d,e,r,n),x=Fl(y,m,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}return !0}function Cl(t,e){let r=t;do{const n=r.prev,i=r.next.next;!Ul(n,i)&&jl(n,r,r.next,i)&&Gl(n,i)&&Gl(i,n)&&(e.push(n.i,r.i,i.i),Yl(r),Yl(r.next),r=t=i),r=r.next;}while(r!==t);return Ml(r)}function El(t,e,r,n,i,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Ol(a,t)){let o=Xl(a,t);return a=Ml(a,a.next),o=Ml(o,o.next),Il(a,e,r,n,i,s,0),void Il(o,e,r,n,i,s,0)}t=t.next;}a=a.next;}while(a!==t)}function Tl(t,e){let r=t.x-e.x;return 0===r&&(r=t.y-e.y,0===r)&&(r=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)),r}function Bl(t,e){const r=function(t,e){let r=e;const n=t.x,i=t.y;let s,a=-1/0;if(Ul(t,r))return r;do{if(Ul(t,r.next))return r.next;if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){const t=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(t<=n&&t>a&&(a=t,s=r.x=r.x&&r.x>=l&&n!==r.x&&Dl(is.x||r.x===s.x&&Vl(s,r)))&&(s=r,c=e);}r=r.next;}while(r!==o);return s}(t,e);if(!r)return e;const n=Xl(r,t);return Ml(n,n.next),Ml(r,r.next)}function Vl(t,e){return Rl(t.prev,t,e.prev)<0&&Rl(e.next,t,t.next)<0}function Fl(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function $l(t){let e=t,r=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(r-a)*(e-o)&&(r-a)*(s-o)>=(i-a)*(n-o)}function Ll(t,e,r,n,i,s,a,o){return !(t===a&&e===o)&&Dl(t,e,r,n,i,s,a,o)}function Ol(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&jl(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(Gl(t,e)&&Gl(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Rl(t.prev,t,e.prev)||Rl(t,e.prev,e))||Ul(t,e)&&Rl(t.prev,t,t.next)>0&&Rl(e.prev,e,e.next)>0)}function Rl(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Ul(t,e){return t.x===e.x&&t.y===e.y}function jl(t,e,r,n){const i=ql(Rl(t,e,r)),s=ql(Rl(t,e,n)),a=ql(Rl(r,n,t)),o=ql(Rl(r,n,e));return i!==s&&a!==o||!(0!==i||!Nl(t,r,e))||!(0!==s||!Nl(t,n,e))||!(0!==a||!Nl(r,t,n))||!(0!==o||!Nl(r,e,n))}function Nl(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function ql(t){return t>0?1:t<0?-1:0}function Gl(t,e){return Rl(t.prev,t,t.next)<0?Rl(t,e,t.next)>=0&&Rl(t,t.prev,e)>=0:Rl(t,e,t.prev)<0||Rl(t,t.next,e)<0}function Xl(t,e){const r=Hl(t.i,t.x,t.y),n=Hl(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function Zl(t,e,r,n){const i=Hl(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Yl(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 Hl(t,e,r){return {i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class Kl{constructor(t,e){if(e>t)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=t,this._minGranularity=e;}getGranularityForZoomLevel(t){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||e>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const r=0|Math.round(t),n=0|Math.round(e),i=this._getKey(r,n);if(this._vertexDictionary.has(i))return this._vertexDictionary.get(i);const s=this._vertexBuffer.length/2;return this._vertexDictionary.set(i,s),this._vertexBuffer.push(r,n),s}_subdivideTrianglesScanline(t){if(this._granularity<2)return function(t,e){const r=[];for(let n=0;n0?(r.push(i),r.push(a),r.push(s)):(r.push(i),r.push(s),r.push(a));}return r}(this._vertexBuffer,t);const e=[],r=t.length;for(let n=0;n=1||v<=0)||y&&(oi)){u>=n&&u<=i&&s.push(r[(t+1)%3]);continue}!y&&x>0&&s.push(this._vertexToIndex(a+p*x,o+f*x));const b=a+p*Math.max(x,0),w=a+p*Math.min(v,1);d||this._generateIntraEdgeVertices(s,a,o,l,u,b,w),!y&&v<1&&s.push(this._vertexToIndex(a+p*v,o+f*v)),(y||u>=n&&u<=i)&&s.push(r[(t+1)%3]),!y&&(u<=n||u>=i)&&this._generateInterEdgeVertices(s,a,o,l,u,c,h,w,n,i);}return s}_generateIntraEdgeVertices(t,e,r,n,i,s,a){const o=n-e,l=i-r,u=0===l,c=u?Math.min(e,n):Math.min(s,a),h=u?Math.max(e,n):Math.max(s,a),p=Math.floor(c/this._granularityCellSize)+1,f=Math.ceil(h/this._granularityCellSize)-1;if(u?e=p;n--){const i=n*this._granularityCellSize;t.push(this._vertexToIndex(i,r+l*(i-e)/o));}}_generateInterEdgeVertices(t,e,r,n,i,s,a,o,l,u){const c=i-r,h=s-n,p=a-i,f=(l-i)/p,d=(u-i)/p,y=Math.min(f,d),m=Math.max(f,d),g=n+h*y;let x=Math.floor(Math.min(g,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(g,o)/this._granularityCellSize)-1,b=o=1||m<=0){const t=r-a,n=s+(e-s)*Math.min((l-a)/t,(u-a)/t);x=Math.floor(Math.min(n,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(n,o)/this._granularityCellSize)-1,b=o0?u:l;if(b)for(let e=x;e<=v;e++)t.push(this._vertexToIndex(e*this._granularityCellSize,_));else for(let e=v;e>=x;e--)t.push(this._vertexToIndex(e*this._granularityCellSize,_));}_generateOutline(t){const e=[];for(const r of t){const t=ru(r,this._granularity,!0),n=this._pointArrayToIndices(t),i=[];for(let t=1;ti!=(s===Wl)?(t.push(e),t.push(r),t.push(this._vertexToIndex(n,s)),t.push(r),t.push(this._vertexToIndex(i,s)),t.push(this._vertexToIndex(n,s))):(t.push(r),t.push(e),t.push(this._vertexToIndex(n,s)),t.push(this._vertexToIndex(i,s)),t.push(r),t.push(this._vertexToIndex(n,s)));}_fillPoles(t,e,r){const n=this._vertexBuffer,i=P,s=t.length;for(let a=2;a80*r){o=t[0],l=t[1];let e=o,n=l;for(let s=r;se&&(e=r),i>n&&(n=i);}u=Math.max(e-o,n-l),u=0!==u?32767/u:0;}return Il(s,a,r,o,l,u,0),a}(r,n),e=this._convertIndices(r,t);i=this._subdivideTrianglesScanline(e);}catch(t){console.error(t);}let s=[];return e&&(s=this._generateOutline(t)),this._ensureNoPoleVertices(),this._handlePoles(i),{verticesFlattened:this._vertexBuffer,indicesTriangles:i,indicesLineList:s}}_convertIndices(t,e){const r=[];for(let n=0;n0?(Math.floor(x/o)+1)*o:(Math.ceil(x/o)-1)*o,e=y>0?(Math.floor(v/o)+1)*o:(Math.ceil(v/o)-1)*o,n=Math.abs(x-t),i=Math.abs(v-e),s=Math.abs(x-c),a=Math.abs(v-h),u=p?n/m:Number.POSITIVE_INFINITY,b=f?i/g:Number.POSITIVE_INFINITY;if((s<=n||!p)&&(a<=i||!f))break;if(u=0?a-1:s-1,i=(o+1)%s,l=t[2*e[n]],u=t[2*e[i]],c=t[2*e[a]],h=t[2*e[a]+1],p=t[2*e[o]+1];let f=!1;if(lu)f=!1;else {const r=p-h,s=-(t[2*e[o]]-c),a=h((u-c)*r+(t[2*e[i]+1]-h)*s)*a&&(f=!0);}if(f){const t=e[n],i=e[a],l=e[o];t!==i&&t!==l&&i!==l&&r.push(l,i,t),a--,a<0&&(a=s-1);}else {const t=e[i],n=e[a],l=e[o];t!==n&&t!==l&&n!==l&&r.push(l,n,t),o++,o>=s&&(o=0);}if(n===i)break}}function iu(t,e,r,n,i,s,a,o,l){const u=i.length/2,c=a&&o&&l;if(uZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,y=!0,m=!0,g=!0,c=0);const x=su(a,n,s,o,p,y,u),v=su(a,n,s,o,f,m,u),b=su(a,n,s,o,d,g,u);r.emplaceBack(c+x-l,c+v-l,c+b-l),u.primitiveLength++;}}(e,r,n,i,s,t),c&&function(t,e,r,n,i,s){const a=[];for(let t=0;tZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,d=!0,y=!0,c=0);const m=su(a,n,s,o,i,d,u),g=su(a,n,s,o,h,y,u);r.emplaceBack(c+m-l,c+g-l),u.primitiveLength++;}}}(a,r,o,i,l,t),e.forceNewSegmentOnNextPrepare(),null==a||a.forceNewSegmentOnNextPrepare();}function su(t,e,r,n,i,s,a){if(s){const s=n.count;return r(e[2*i],e[2*i+1]),t[i]=n.count,n.count++,a.vertexLength++,s}return t[i]}class au{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Ba,this.indexArray=new Na,this.indexArray2=new qa,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.segments2=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("fill",this.layers,e);const n=this.layers[0].layout.get("fill-sort-key"),i=!n.isConstant(),s=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=Io(a,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),c,r))continue;const h=i?n.evaluate(c,{},r,e.availableImages):void 0,p={id:o,properties:a.properties,type:a.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:Mo(a),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("fill",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,_l),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,r,n,i,s){for(const t of Qr(e,500)){const e=eu(t,n,s.fill.getGranularityForZoomLevel(n.z)),r=this.layoutVertexArray;iu(((t,e)=>{r.emplaceBack(t,e);}),this.segments,this.layoutVertexArray,this.indexArray,e.verticesFlattened,e.indicesTriangles,this.segments2,this.indexArray2,e.indicesLineList);}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}}let ou,lu;as("FillBucket",au,{omit:["layers","patternFeatures"]});var uu={get paint(){return lu=lu||new js({"fill-antialias":new Ds(xt.paint_fill["fill-antialias"]),"fill-opacity":new Ls(xt.paint_fill["fill-opacity"]),"fill-color":new Ls(xt.paint_fill["fill-color"]),"fill-outline-color":new Ls(xt.paint_fill["fill-outline-color"]),"fill-translate":new Ds(xt.paint_fill["fill-translate"]),"fill-translate-anchor":new Ds(xt.paint_fill["fill-translate-anchor"]),"fill-pattern":new Os(xt.paint_fill["fill-pattern"])})},get layout(){return ou=ou||new js({"fill-sort-key":new Ls(xt.layout_fill["fill-sort-key"])})}};class cu extends qs{constructor(t,e){super(t,uu,e);}recalculate(t,e){super.recalculate(t,e);const r=this.paint._values["fill-outline-color"];"constant"===r.value.kind&&void 0===r.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);}createBucket(t){return new au(t)}queryRadius(){return No(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:t,geometry:e,transform:r,pixelsToTileUnits:n}){return Bo(qo(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-r.bearingInRadians,n),e)}isTileClipped(){return !0}}const hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),pu=Ys([{name:"a_centroid",components:2,type:"Int16"}],4),{members:fu}=hu;class du{constructor(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this.id=void 0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(yu,this,e);}loadGeometry(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos,n=[];let i,s=1,a=0,o=0,l=0;for(;t.pos>3;}if(a--,1===s||2===s)o+=t.readSVarint(),l+=t.readSVarint(),1===s&&(i&&n.push(i),i=[]),i&&i.push(new r(o,l));else {if(7!==s)throw new Error(`unknown command ${s}`);i&&i.push(i[0].clone());}}return i&&n.push(i),n}bbox(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos;let r=1,n=0,i=0,s=0,a=1/0,o=-1/0,l=1/0,u=-1/0;for(;t.pos>3;}if(n--,1===r||2===r)i+=t.readSVarint(),s+=t.readSVarint(),io&&(o=i),su&&(u=s);else if(7!==r)throw new Error(`unknown command ${r}`)}return [a,l,o,u]}toGeoJSON(t,e,r){const n=this.extent*Math.pow(2,r),i=this.extent*t,s=this.extent*e,a=this.loadGeometry();function o(t){return [360*(t.x+i)/n-180,360/Math.PI*Math.atan(Math.exp((1-2*(t.y+s)/n)*Math.PI))-90]}function l(t){return t.map(o)}let u;if(1===this.type){const t=[];for(const e of a)t.push(e[0]);const e=l(t);u=1===t.length?{type:"Point",coordinates:e[0]}:{type:"MultiPoint",coordinates:e};}else if(2===this.type){const t=a.map(l);u=1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t};}else {if(3!==this.type)throw new Error("unknown feature type");{const t=function(t){const e=t.length;if(e<=1)return [t];const r=[];let n,i;for(let s=0;s=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];const e=this._pbf.readVarint()+this._pbf.pos;return new du(this._pbf,e,this.extent,this._keys,this._values)}}function xu(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){let e=null;const r=t.readVarint()+t.pos;for(;t.pos>3;e=1===r?t.readString():2===r?t.readFloat():3===r?t.readDouble():4===r?t.readVarint64():5===r?t.readVarint():6===r?t.readSVarint():7===r?t.readBoolean():null;}if(null==e)throw new Error("unknown feature value");return e}(r));}class vu{constructor(t,e){this.layers=t.readFields(bu,{},e);}}function bu(t,e,r){if(3===t){const t=new gu(r,r.readVarint()+r.pos);t.length&&(e[t.name]=t);}}const wu=Math.pow(2,13);function _u(t,e,r,n,i,s,a,o){t.emplaceBack(e,r,2*Math.floor(n*wu)+a,i*wu*2,s*wu*2,Math.round(o));}class Su{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Va,this.centroidVertexArray=new Ea,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.features=[],this.hasPattern=Sl("fill-extrusion",this.layers,e);for(const{feature:n,id:i,index:s,sourceLayerIndex:a}of t){const t=this.layers[0]._featureFilter.needGeometry,o=Io(n,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),o,r))continue;const l={id:i,sourceLayerIndex:a,index:s,geometry:t?o.geometry:Mo(n),properties:n.properties,type:n.type,patterns:{}};this.hasPattern?this.features.push(Al("fill-extrusion",this.layers,l,{zoom:this.zoom},e)):this.addFeature(l,l.geometry,s,r,{},e.subdivisionGranularity),e.featureIndex.insert(n,l.geometry,s,a,this.index,!0);}}addFeatures(t,e,r){for(const n of this.features){const{geometry:i}=n;this.addFeature(n,i,n.index,e,r,t.subdivisionGranularity);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,fu),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,pu.members,!0),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy());}addFeature(t,e,r,n,i,s){for(const r of Qr(e,500)){const e={x:0,y:0,sampleCount:0},i=this.layoutVertexArray.length;this.processPolygon(e,n,t,r,s);const a=this.layoutVertexArray.length-i,o=Math.floor(e.x/e.sampleCount),l=Math.floor(e.y/e.sampleCount);for(let t=0;t{_u(u,t,e,0,0,1,1,0);}),this.segments,this.layoutVertexArray,this.indexArray,l.verticesFlattened,l.indicesTriangles);}_generateSideFaces(t,e){let r=0;for(let n=1;nZa.MAX_VERTEX_ARRAY_LENGTH&&(e.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const a=i.sub(s)._perp()._unit(),o=s.dist(i);r+o>32768&&(r=0),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,1,r),r+=o,_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,1,r);const l=e.segment.vertexLength;this.indexArray.emplaceBack(l,l+2,l+1),this.indexArray.emplaceBack(l+1,l+2,l+3),e.segment.vertexLength+=4,e.segment.primitiveLength+=2;}}}function Au(t,e){for(let r=0;rP)||t.y===e.y&&(t.y<0||t.y>P)}function Mu(t){return t.every((t=>t.x<0))||t.every((t=>t.x>P))||t.every((t=>t.y<0))||t.every((t=>t.y>P))}let Iu;as("FillExtrusionBucket",Su,{omit:["layers","features"]});var zu={get paint(){return Iu=Iu||new js({"fill-extrusion-opacity":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Os(xt["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class Pu extends qs{constructor(t,e){super(t,zu,e);}createBucket(t){return new Su(t)}queryRadius(){return No(this.paint.get("fill-extrusion-translate"))}is3D(){return !0}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a,pixelPosMatrix:o}){const l=qo(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-s.bearingInRadians,a),u=this.paint.get("fill-extrusion-height").evaluate(e,n),c=this.paint.get("fill-extrusion-base").evaluate(e,n),h=function(t,e){const n=[];for(const i of t){const t=[i.x,i.y,0,1];A(t,t,e),n.push(new r(t[0]/t[3],t[1]/t[3]));}return n}(l,o),p=function(t,e,n,i){const s=[],a=[],o=i[8]*e,l=i[9]*e,u=i[10]*e,c=i[11]*e,h=i[8]*n,p=i[9]*n,f=i[10]*n,d=i[11]*n;for(const e of t){const t=[],n=[];for(const s of e){const e=s.x,a=s.y,y=i[0]*e+i[4]*a+i[12],m=i[1]*e+i[5]*a+i[13],g=i[2]*e+i[6]*a+i[14],x=i[3]*e+i[7]*a+i[15],v=g+u,b=x+c,w=y+h,_=m+p,S=g+f,A=x+d,k=new r((y+o)/b,(m+l)/b);k.z=v/b,t.push(k);const M=new r(w/A,_/A);M.z=S/A,n.push(M);}s.push(t),a.push(n);}return [s,a]}(i,c,u,o);return function(t,e,r){let n=1/0;Bo(r,e)&&(n=Eu(r,e[0]));for(let i=0;it.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new Fa,this.layoutVertexArray2=new $a,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("line",this.layers,e);const n=this.layers[0].layout.get("line-sort-key"),i=!n.isConstant(),s=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=i?n.evaluate(u,{},r):void 0,h={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("line",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,Fu)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Bu),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return {start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i,s){const a=this.layers[0].layout,o=a.get("line-join").evaluate(t,{}),l=a.get("line-cap"),u=a.get("line-miter-limit"),c=a.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,o,l,u,c,n,s);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}addLine(t,e,r,n,i,s,a,o){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,t=ru(t,a?o.line.getGranularityForZoomLevel(a.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[u-1].equals(t[u-2]);)u--;let c=0;for(;c0;if(w&&e>c){const t=f.dist(d);if(t>2*h){const e=f.sub(f.sub(d)._mult(h/t)._round());this.updateDistance(d,e),this.addCurrentVertex(e,m,0,0,p),d=e;}}const S=d&&y;let A=S?r:l?"butt":n;if(S&&"round"===A&&(vi&&(A="bevel"),"bevel"===A&&(v>2&&(A="flipbevel"),v100)a=g.mult(-1);else {const t=v*m.add(g).mag()/m.sub(g).mag();a._perp()._mult(t*(_?-1:1));}this.addCurrentVertex(f,a,0,0,p),this.addCurrentVertex(f,a.mult(-1),0,0,p);}else if("bevel"===A||"fakeround"===A){const t=-Math.sqrt(v*v-1),e=_?t:0,r=_?0:t;if(d&&this.addCurrentVertex(f,m,e,r,p),"fakeround"===A){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*h){const e=f.add(y.sub(f)._mult(h/t)._round());this.updateDistance(f,e),this.addCurrentVertex(e,g,0,0,p),f=e;}}}}addCurrentVertex(t,e,r,n,i,s=!1){const a=e.y*n-e.x,o=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,!1,r,i),this.addHalfVertex(t,a,o,s,!0,-n,i),this.distance>Du/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,r,n,i,s));}addHalfVertex({x:t,y:e},r,n,i,s,a,o){const l=.5*(this.lineClips?this.scaledDistance*(Du-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,u,this.e2),o.primitiveLength++),s?this.e2=u:this.e1=u;}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}}let Ou,Ru;as("LineBucket",Lu,{omit:["layers","patternFeatures"]});var Uu={get paint(){return Ru=Ru||new js({"line-opacity":new Ls(xt.paint_line["line-opacity"]),"line-color":new Ls(xt.paint_line["line-color"]),"line-translate":new Ds(xt.paint_line["line-translate"]),"line-translate-anchor":new Ds(xt.paint_line["line-translate-anchor"]),"line-width":new Ls(xt.paint_line["line-width"]),"line-gap-width":new Ls(xt.paint_line["line-gap-width"]),"line-offset":new Ls(xt.paint_line["line-offset"]),"line-blur":new Ls(xt.paint_line["line-blur"]),"line-dasharray":new Rs(xt.paint_line["line-dasharray"]),"line-pattern":new Os(xt.paint_line["line-pattern"]),"line-gradient":new Us(xt.paint_line["line-gradient"])})},get layout(){return Ou=Ou||new js({"line-cap":new Ds(xt.layout_line["line-cap"]),"line-join":new Ls(xt.layout_line["line-join"]),"line-miter-limit":new Ds(xt.layout_line["line-miter-limit"]),"line-round-limit":new Ds(xt.layout_line["line-round-limit"]),"line-sort-key":new Ls(xt.layout_line["line-sort-key"])})}};class ju extends Ls{possiblyEvaluate(t,e){return e=new Is(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=L({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}let Nu;class qu extends qs{constructor(t,e){super(t,Uu,e),this.gradientVersion=0,Nu||(Nu=new ju(Uu.paint.properties["line-width"].specification),Nu.useIntegerZoom=!0);}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return void 0!==t._styleExpression}(t)&&t._styleExpression.expression instanceof ar,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=Nu.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t);}createBucket(t){return new Lu(t)}queryRadius(t){const e=t,r=Gu(jo("line-width",this,e),jo("line-gap-width",this,e)),n=jo("line-offset",this,e);return r/2+Math.abs(n)+No(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a}){const o=qo(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-s.bearingInRadians,a),l=a/2*Gu(this.paint.get("line-width").evaluate(e,n),this.paint.get("line-gap-width").evaluate(e,n)),u=this.paint.get("line-offset").evaluate(e,n);return u&&(i=function(t,e){const n=[];for(let i=0;i=3)for(let e=0;e0?e+2*t:t}const Xu=Ys([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Zu=Ys([{name:"a_projected_pos",components:3,type:"Float32"}],4);Ys([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Yu=Ys([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Ys([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const Hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Ku=Ys([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Ju(t,e,r){return t.sections.forEach((t=>{t.text=function(t,e,r){const n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Ms.applyArabicShaping&&(t=Ms.applyArabicShaping(t)),t}(t.text,e,r);})),t}Ys([{name:"triangle",components:3,type:"Uint16"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Ys([{type:"Float32",name:"offsetX"}]),Ys([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Ys([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const Wu={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Qu=24;const tc=4294967296,ec=1/tc,rc="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class nc{constructor(t=new Uint8Array(16)){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length;}readFields(t,e,r=this.length){for(;this.pos>3,i=this.pos;this.type=7&r,t(n,e,this),this.pos===i&&this.skip(r);}return e}readMessage(t,e){return this.readFields(t,e,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*tc;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*tc;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const e=this.buf;let r,n;return n=e[this.pos++],r=127&n,n<128?r:(n=e[this.pos++],r|=(127&n)<<7,n<128?r:(n=e[this.pos++],r|=(127&n)<<14,n<128?r:(n=e[this.pos++],r|=(127&n)<<21,n<128?r:(n=e[this.pos],r|=(15&n)<<28,function(t,e,r){const n=r.buf;let i,s;if(s=n[r.pos++],i=(112&s)>>4,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<3,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<10,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<17,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<24,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(1&s)<<31,s<128)return ic(t,i,e);throw new Error("Expected varint not more than 10 bytes")}(r,t,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2==1?(t+1)/-2:t/2}readBoolean(){return Boolean(this.readVarint())}readString(){const t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&rc?rc.decode(this.buf.subarray(e,t)):function(t,e,r){let n="",i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+u>r)break;1===u?e<128&&(l=e):2===u?(s=t[i+1],128==(192&s)&&(l=(31&e)<<6|63&s,l<=127&&(l=null))):3===u?(s=t[i+1],a=t[i+2],128==(192&s)&&128==(192&a)&&(l=(15&e)<<12|(63&s)<<6|63&a,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===u&&(s=t[i+1],a=t[i+2],o=t[i+3],128==(192&s)&&128==(192&a)&&128==(192&o)&&(l=(15&e)<<18|(63&s)<<12|(63&a)<<6|63&o,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,u=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=u;}return n}(this.buf,e,t)}readBytes(){const t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e}readPackedVarint(t=[],e){const r=this.readPackedEnd();for(;this.pos127;);else if(2===e)this.pos=this.readVarint()+this.pos;else if(5===e)this.pos+=4;else {if(1!==e)throw new Error(`Unimplemented type: ${e}`);this.pos+=8;}}writeTag(t,e){this.writeVarint(t<<3|e);}realloc(t){let e=this.length||16;for(;e268435455||t<0?function(t,e){let r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(r=~(-t%4294967296),n=~(-t/4294967296),4294967295^r?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){const r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(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(t){this.writeVarint(t<0?2*-t-1:2*t);}writeBoolean(t){this.writeVarint(+t);}writeString(t){t=String(t),this.realloc(4*t.length),this.pos++;const e=this.pos;this.pos=function(t,e,r){for(let n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);const r=this.pos-e;r>=128&&sc(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4;}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8;}writeBytes(t){const e=t.length;this.writeVarint(e),this.realloc(e);for(let r=0;r=128&&sc(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;}writeMessage(t,e,r){this.writeTag(t,2),this.writeRawMessage(e,r);}writePackedVarint(t,e){e.length&&this.writeMessage(t,ac,e);}writePackedSVarint(t,e){e.length&&this.writeMessage(t,oc,e);}writePackedBoolean(t,e){e.length&&this.writeMessage(t,cc,e);}writePackedFloat(t,e){e.length&&this.writeMessage(t,lc,e);}writePackedDouble(t,e){e.length&&this.writeMessage(t,uc,e);}writePackedFixed32(t,e){e.length&&this.writeMessage(t,hc,e);}writePackedSFixed32(t,e){e.length&&this.writeMessage(t,pc,e);}writePackedFixed64(t,e){e.length&&this.writeMessage(t,fc,e);}writePackedSFixed64(t,e){e.length&&this.writeMessage(t,dc,e);}writeBytesField(t,e){this.writeTag(t,2),this.writeBytes(e);}writeFixed32Field(t,e){this.writeTag(t,5),this.writeFixed32(e);}writeSFixed32Field(t,e){this.writeTag(t,5),this.writeSFixed32(e);}writeFixed64Field(t,e){this.writeTag(t,1),this.writeFixed64(e);}writeSFixed64Field(t,e){this.writeTag(t,1),this.writeSFixed64(e);}writeVarintField(t,e){this.writeTag(t,0),this.writeVarint(e);}writeSVarintField(t,e){this.writeTag(t,0),this.writeSVarint(e);}writeStringField(t,e){this.writeTag(t,2),this.writeString(e);}writeFloatField(t,e){this.writeTag(t,5),this.writeFloat(e);}writeDoubleField(t,e){this.writeTag(t,1),this.writeDouble(e);}writeBooleanField(t,e){this.writeVarintField(t,+e);}}function ic(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function sc(t,e,r){const n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(let e=r.pos-1;e>=t;e--)r.buf[e+n]=r.buf[e];}function ac(t,e){for(let r=0;re.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();e&&t=0&&r>=t&&kc[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e);}substring(t,e){const r=new Sc;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}getMaxImageSize(t){let e=0,r=0;for(let n=0;n=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Ac(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=Sc.fromFeature(e,s);let g;p===t.ao.vertical&&m.verticalizePunctuation();const{processBidirectionalText:x,processStyledBidirectionalText:v}=Ms;if(x&&1===m.sections.length){g=[];const t=x(m.toString(),Bc(m,c,a,r,i,d));for(const e of t){const t=new Sc;t.text=e,t.sections=m.sections;for(let r=0;r=0;let u=0;for(let r=0;ru){const t=Math.ceil(s/u);i*=t/a,a=t;}return {x1:n,y1:i,x2:n+s,y2:i+a}}function Nc(t,e,r,n,i,s){const a=t.image;let o;if(a.content){const t=a.content,e=a.pixelRatio||1;o=[t[0]/e,t[1]/e,a.displaySize[0]-t[2]/e,a.displaySize[1]-t[3]/e];}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===r||"both"===r?(f=i[0]+l-n[3],h=i[0]+u+n[1]):(f=i[0]+(l+u-a.displaySize[0])/2,h=f+a.displaySize[0]);const d=e.top*s,y=e.bottom*s;return "height"===r||"both"===r?(c=i[1]+d-n[0],p=i[1]+y+n[2]):(c=i[1]+(d+y-a.displaySize[1])/2,p=c+a.displaySize[1]),{image:a,top:c,right:h,bottom:p,left:f,collisionPadding:o}}const qc=128,Gc=32640;function Xc(t,e){const{expression:r}=e;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new Is(t+1))};if("source"===r.kind)return {kind:"source"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;it.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];const r=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Xc(this.zoom,r["text-size"]),this.iconSizeData=Xc(this.zoom,r["icon-size"]);const n=this.layers[0].layout,i=n.get("symbol-sort-key"),s=n.get("symbol-z-order");this.canOverlap="never"!==Zc(n,"text-overlap","text-allow-overlap")||"never"!==Zc(n,"icon-overlap","icon-allow-overlap")||n.get("text-ignore-placement")||n.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!i.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===n.get("symbol-placement")&&(this.writingModes=n.get("text-writing-mode").map((e=>t.ao[e]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID;}createArrays(){this.text=new Wc(new wo(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new Wc(new wo(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new ka,this.lineVertexArray=new Ma,this.symbolInstances=new Aa,this.textAnchorOffsets=new za;}calculateGlyphDependencies(t,e,r,n,i){for(let s=0;s0)&&("constant"!==a.value.kind||a.value.value.length>0),c="constant"!==l.value.kind||!!l.value.value||Object.keys(l.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!u&&!c)return;const p=r.iconDependencies,f=r.glyphDependencies,d=r.availableImages,y=new Is(this.zoom);for(const{feature:r,id:o,index:l,sourceLayerIndex:m}of e){const e=i._featureFilter.needGeometry,g=Io(r,e);if(!i._featureFilter.filter(y,g,n))continue;let x,v;if(e||(g.geometry=Mo(r)),u){const t=i.getValueAndResolveTokens("text-field",g,n,d),e=Ce.factory(t),r=this.hasRTLText=this.hasRTLText||Jc(e);(!r||"unavailable"===Ms.getRTLTextPluginStatus()||r&&Ms.isParsed())&&(x=Ju(e,i,g));}if(c){const t=i.getValueAndResolveTokens("icon-image",g,n,d);v=t instanceof De?t:De.fromString(t);}if(!x&&!v)continue;const b=this.sortFeaturesByKey?h.evaluate(g,{},n):void 0;if(this.features.push({id:o,text:x,icon:v,index:l,sourceLayerIndex:m,geometry:g.geometry,properties:r.properties,type:du.types[r.type],sortKey:b}),v&&(p[v.name]=!0),x){const e=a.evaluate(g,{},n).join(","),r="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(t.ao.vertical)>=0;for(const t of x.sections)if(t.image)p[t.image.name]=!0;else {const n=ds(x.toString()),i=t.fontStack||e,s=f[i]=f[i]||{};this.calculateGlyphDependencies(t.text,s,r,this.allowVerticalPlacement,n);}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++;}function a(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function o(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return `${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}));}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(void 0!==t.segment){let r=t.dist(e[t.segment+1]),n=t.dist(e[t.segment]);const i={};for(let n=t.segment+1;n=0;r--)i[r]={x:e[r].x,y:e[r].y,tileUnitDistanceFromAnchor:n},r>0&&(n+=e[r-1].dist(e[r]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,r)=>{t>=0&&r.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t);})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}let eh,rh;as("SymbolBucket",th,{omit:["layers","collisionBoxArray","features","compareText"]}),th.MAX_GLYPHS=65535,th.addDynamicAttributes=Kc;var nh={get paint(){return rh=rh||new js({"icon-opacity":new Ls(xt.paint_symbol["icon-opacity"]),"icon-color":new Ls(xt.paint_symbol["icon-color"]),"icon-halo-color":new Ls(xt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Ls(xt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Ls(xt.paint_symbol["icon-halo-blur"]),"icon-translate":new Ds(xt.paint_symbol["icon-translate"]),"icon-translate-anchor":new Ds(xt.paint_symbol["icon-translate-anchor"]),"text-opacity":new Ls(xt.paint_symbol["text-opacity"]),"text-color":new Ls(xt.paint_symbol["text-color"],{runtimeType:Lt,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new Ls(xt.paint_symbol["text-halo-color"]),"text-halo-width":new Ls(xt.paint_symbol["text-halo-width"]),"text-halo-blur":new Ls(xt.paint_symbol["text-halo-blur"]),"text-translate":new Ds(xt.paint_symbol["text-translate"]),"text-translate-anchor":new Ds(xt.paint_symbol["text-translate-anchor"])})},get layout(){return eh=eh||new js({"symbol-placement":new Ds(xt.layout_symbol["symbol-placement"]),"symbol-spacing":new Ds(xt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Ds(xt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Ls(xt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Ds(xt.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new Ds(xt.layout_symbol["icon-allow-overlap"]),"icon-overlap":new Ds(xt.layout_symbol["icon-overlap"]),"icon-ignore-placement":new Ds(xt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Ds(xt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Ds(xt.layout_symbol["icon-rotation-alignment"]),"icon-size":new Ls(xt.layout_symbol["icon-size"]),"icon-text-fit":new Ds(xt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Ds(xt.layout_symbol["icon-text-fit-padding"]),"icon-image":new Ls(xt.layout_symbol["icon-image"]),"icon-rotate":new Ls(xt.layout_symbol["icon-rotate"]),"icon-padding":new Ls(xt.layout_symbol["icon-padding"]),"icon-keep-upright":new Ds(xt.layout_symbol["icon-keep-upright"]),"icon-offset":new Ls(xt.layout_symbol["icon-offset"]),"icon-anchor":new Ls(xt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Ds(xt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Ds(xt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Ds(xt.layout_symbol["text-rotation-alignment"]),"text-field":new Ls(xt.layout_symbol["text-field"]),"text-font":new Ls(xt.layout_symbol["text-font"]),"text-size":new Ls(xt.layout_symbol["text-size"]),"text-max-width":new Ls(xt.layout_symbol["text-max-width"]),"text-line-height":new Ds(xt.layout_symbol["text-line-height"]),"text-letter-spacing":new Ls(xt.layout_symbol["text-letter-spacing"]),"text-justify":new Ls(xt.layout_symbol["text-justify"]),"text-radial-offset":new Ls(xt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Ds(xt.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Ls(xt.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Ls(xt.layout_symbol["text-anchor"]),"text-max-angle":new Ds(xt.layout_symbol["text-max-angle"]),"text-writing-mode":new Ds(xt.layout_symbol["text-writing-mode"]),"text-rotate":new Ls(xt.layout_symbol["text-rotate"]),"text-padding":new Ds(xt.layout_symbol["text-padding"]),"text-keep-upright":new Ds(xt.layout_symbol["text-keep-upright"]),"text-transform":new Ls(xt.layout_symbol["text-transform"]),"text-offset":new Ls(xt.layout_symbol["text-offset"]),"text-allow-overlap":new Ds(xt.layout_symbol["text-allow-overlap"]),"text-overlap":new Ds(xt.layout_symbol["text-overlap"]),"text-ignore-placement":new Ds(xt.layout_symbol["text-ignore-placement"]),"text-optional":new Ds(xt.layout_symbol["text-optional"])})}};class ih{constructor(t){if(void 0===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:Vt,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return !1}serialize(){return null}}as("FormatSectionOverride",ih,{omit:["defaultValue"]});class sh extends qs{constructor(t,e){super(t,nh,e);}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const r of t)e.indexOf(r)<0&&e.push(r);this.layout._values["text-writing-mode"]=e;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||ei(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>t&&r in t?String(t[r]):""))}(e.properties,i)}createBucket(t){return new th(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of nh.paint.overridableProperties){if(!sh.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new ih(e),n=new ti(r,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new ni("source",n):new ii("composite",n,e.value.zoomStops),this.paint._values[t]=new Fs(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,r){return !(!this.layout||e.isDataDriven()||r.isDataDriven())&&sh.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get("text-field"),n=nh.paint.properties[e];let i=!1;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=!0)};if("constant"===r.value.kind&&r.value.value instanceof Ce)s(r.value.value.sections);else if("source"===r.value.kind||"composite"===r.value.kind){const t=e=>{i||(e instanceof Ne&&Ue(e.value)===Nt?s(e.value.sections):e instanceof Ir?s(e.sections):e.eachChild(t));},e=r.value;e._styleExpression&&t(e._styleExpression.expression);}return i}}let ah;var oh={get paint(){return ah=ah||new js({"background-color":new Ds(xt.paint_background["background-color"]),"background-pattern":new Rs(xt.paint_background["background-pattern"]),"background-opacity":new Ds(xt.paint_background["background-opacity"])})}};class lh extends qs{constructor(t,e){super(t,oh,e);}}let uh;var ch={get paint(){return uh=uh||new js({"raster-opacity":new Ds(xt.paint_raster["raster-opacity"]),"raster-hue-rotate":new Ds(xt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Ds(xt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Ds(xt.paint_raster["raster-brightness-max"]),"raster-saturation":new Ds(xt.paint_raster["raster-saturation"]),"raster-contrast":new Ds(xt.paint_raster["raster-contrast"]),"raster-resampling":new Ds(xt.paint_raster["raster-resampling"]),"raster-fade-duration":new Ds(xt.paint_raster["raster-fade-duration"])})}};class hh extends qs{constructor(t,e){super(t,ch,e);}}class ph extends qs{constructor(t,e){super(t,{},e),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},this.implementation=t;}is3D(){return "3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return !1}serialize(){throw new Error("Custom layers cannot be serialized")}}class fh{constructor(t){this._methodToThrottle=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle();});}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle();}),0));}remove(){delete this._channel,this._methodToThrottle=()=>{};}}const dh={once:!0},yh=6371008.8;class mh{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new mh(D(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return yh*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof mh)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new mh(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new mh(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const gh=2*Math.PI*yh;function xh(t){return gh*Math.cos(t*Math.PI/180)}function vh(t){return (180+t)/360}function bh(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function wh(t,e){return t/xh(e)}function _h(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}function Sh(t,e){return t*xh(_h(e))}class Ah{constructor(t,e,r=0){this.x=+t,this.y=+e,this.z=+r;}static fromLngLat(t,e=0){const r=mh.convert(t);return new Ah(vh(r.lng),bh(r.lat),wh(e,r.lat))}toLngLat(){return new mh(360*this.x-180,_h(this.y))}toAltitude(){return Sh(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/gh*(t=_h(this.y),1/Math.cos(t*Math.PI/180));var t;}}function kh(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}class Mh{constructor(t,e,r){if(!function(t,e,r){return !(t<0||t>25||r<0||r>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,r))throw new Error(`x=${e}, y=${r}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=r,this.key=Ph(0,t,t,e,r);}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,r){const n=(s=this.y,a=this.z,o=kh(256*(i=this.x),256*(s=Math.pow(2,a)-s-1),a),l=kh(256*(i+1),256*(s+1),a),o[0]+","+o[1]+","+l[0]+","+l[1]);var i,s,a,o,l;const u=function(t,e,r){let n,i="";for(let s=t;s>0;s--)n=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,n)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new r((t.x*e-this.x)*P,(t.y*e-this.y)*P)}toString(){return `${this.z}/${this.x}/${this.y}`}}class Ih{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Ph(t,e.z,e.z,e.x,e.y);}}class zh{constructor(t,e,r,n,i){if(this.terrainRttPosMatrix32f=null,t= z; overscaledZ = ${t}; z = ${r}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Mh(r,+n,+i),this.key=Ph(e,t,r,n,i);}clone(){return new zh(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new zh(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new zh(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const r=this.canonical.z-t;return t>this.canonical.z?Ph(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Ph(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}isChildOf(t){if(t.wrap!==this.wrap)return !1;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new zh(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new zh(e,this.wrap,e,r,n),new zh(e,this.wrap,e,r+1,n),new zh(e,this.wrap,e,r,n+1),new zh(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.ythis.maxX||this.minY>this.maxY)&&(this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0),this}shrinkBy(t){return this.expandBy(-t)}map(t){const e=new Eh;return e.extend(t(new r(this.minX,this.minY))),e.extend(t(new r(this.maxX,this.minY))),e.extend(t(new r(this.minX,this.maxY))),e.extend(t(new r(this.maxX,this.maxY))),e}static fromPoints(t){const e=new Eh;for(const r of t)e.extend(r);return e}contains(t){return t.x>=this.minX&&t.x<=this.maxX&&t.y>=this.minY&&t.y<=this.maxY}empty(){return this.minX>this.maxX}width(){return this.maxX-this.minX}height(){return this.maxY-this.minY}covers(t){return !this.empty()&&!t.empty()&&t.minX>=this.minX&&t.maxX<=this.maxX&&t.minY>=this.minY&&t.maxY<=this.maxY}intersects(t){return !this.empty()&&!t.empty()&&t.minX<=this.maxX&&t.maxX>=this.minX&&t.minY<=this.maxY&&t.maxY>=this.minY}}class Th{constructor(t){this._stringToNumber={},this._numberToString=[];for(let e=0;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class Bh{constructor(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}class Vh{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new is(P,16,0),this.grid3D=new is(P,16,0),this.featureIndexArray=new Ca,this.promoteId=e;}insert(t,e,r,n,i,s){const a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);const o=s?this.grid3D:this.grid;for(let t=0;t=0&&n[3]>=0&&o.insert(a,n[0],n[1],n[2],n[3]);}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new vu(new nc(this.rawTileData)).layers,this.sourceLayerCoder=new Th(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,n,i){this.loadVTLayers();const s=t.params,a=P/t.tileSize/t.scale,o=hi(s.filter,s.globalState),l=t.queryGeometry,u=t.queryPadding*a,c=Eh.fromPoints(l),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=Eh.fromPoints(t.cameraQueryGeometry).expandBy(u),f=this.grid3D.query(p.minX,p.minY,p.maxX,p.maxY,((e,n,i,s)=>function(t,e,n,i,s){for(const r of t)if(e<=r.x&&n<=r.y&&i>=r.x&&s>=r.y)return !0;const a=[new r(e,n),new r(e,s),new r(i,s),new r(i,n)];if(t.length>2)for(const e of a)if(Ro(t,e))return !0;for(let e=0;e(p||(p=Mo(e)),r.queryIntersectsFeature({queryGeometry:l,feature:e,featureState:n,geometry:p,zoom:this.z,transform:t.transform,pixelsToTileUnits:a,pixelPosMatrix:t.pixelPosMatrix,unwrappedTileID:this.tileID.toUnwrapped(),getElevation:t.getElevation}))));}return d}loadMatchingFeature(t,e,r,n,i,s,a,o,l,u,c){const h=this.bucketLayerIDs[e];if(s&&!h.some((t=>s.has(t))))return;const p=this.sourceLayerCoder.decode(r),f=this.vtLayers[p].feature(n);if(i.needGeometry){const t=Io(f,!0);if(!i.filter(new Is(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new Is(this.tileID.overscaledZ),f))return;const d=this.getId(f,p);for(let e=0;e{const a=e instanceof $s?e.get(s):null;return a&&a.evaluate?a.evaluate(r,n,i):a}))}function $h(t,e){return e-t}function Dh(t,e,n,i,s){const a=[];for(let o=0;o=i&&c.x>=i||(o.x>=i?o=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round():c.x>=i&&(c=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round()),o.y>=s&&c.y>=s||(o.y>=s?o=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round():c.y>=s&&(c=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round()),u&&o.equals(u[u.length-1])||(u=[o],a.push(u)),u.push(c)))));}}return a}as("FeatureIndex",Vh,{omit:["rawTileData","sourceLayerCoder"]});class Lh extends r{constructor(t,e,r,n){super(t,e),this.angle=r,void 0!==n&&(this.segment=n);}clone(){return new Lh(this.x,this.y,this.angle,this.segment)}}function Oh(t,e,r,n,i){if(void 0===e.segment||0===r)return !0;let s=e,a=e.segment+1,o=0;for(;o>-r/2;){if(a--,a<0)return !1;o-=t[a].dist(s),s=t[a];}o+=t[a].dist(t[a+1]),a++;const l=[];let u=0;for(;on;)u-=l.shift().angleDelta;if(u>i)return !1;a++,o+=e.dist(r);}return !0}function Rh(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=dr.number(n.x,i.x,c),p=dr.number(n.y,i.y,c),f=new Lh(h,p,i.angleTo(n),r);return f._round(),!a||Oh(t,f,o,a,e)?f:void 0}l+=s;}}function qh(t,e,r,n,i,s,a,o,l){const u=Uh(n,s,a),c=jh(n,i),h=c*a,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new Lh(g,x,y,e);r._round(),n&&!Oh(t,r,s,n,i)||f.push(r);}}h+=d;}return o||f.length||a||(f=Gh(t,h/2,r,n,i,s,a,!0,l)),f}function Xh(t,e,n,i){const s=[],a=t.image,o=a.pixelRatio,l=a.paddedRect.w-2,u=a.paddedRect.h-2;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=a.stretchX||[[0,l]],p=a.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=l-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,S=m,A=0,k=g;if(a.content&&i){const e=a.content,r=e[2]-e[0],n=e[3]-e[1];(a.textFitWidth||a.textFitHeight)&&(c=jc(t)),x=Zh(h,0,e[0]),b=Zh(p,0,e[1]),v=Zh(h,e[0],e[2]),w=Zh(p,e[1],e[3]),_=e[0]-x,A=e[1]-b,S=r-v,k=n-w;}const M=c.x1,I=c.y1,z=c.x2-M,P=c.y2-I,C=(t,i,s,l)=>{const u=Hh(t.stretch-x,v,z,M),c=Kh(t.fixed-_,S,t.stretch,d),h=Hh(i.stretch-b,w,P,I),p=Kh(i.fixed-A,k,i.stretch,y),f=Hh(s.stretch-x,v,z,M),m=Kh(s.fixed-_,S,s.stretch,d),g=Hh(l.stretch-b,w,P,I),C=Kh(l.fixed-A,k,l.stretch,y),E=new r(u,h),T=new r(f,h),B=new r(f,g),V=new r(u,g),F=new r(c/o,p/o),$=new r(m/o,C/o),D=e*Math.PI/180;if(D){const t=Math.sin(D),e=Math.cos(D),r=[e,-t,t,e];E._matMult(r),T._matMult(r),V._matMult(r),B._matMult(r);}const L=t.stretch+t.fixed,O=i.stretch+i.fixed;return {tl:E,tr:T,bl:V,br:B,tex:{x:a.paddedRect.x+1+L,y:a.paddedRect.y+1+O,w:s.stretch+s.fixed-L,h:l.stretch+l.fixed-O},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:F,pixelOffsetBR:$,minFontScaleX:S/o/z,minFontScaleY:k/o/P,isSDF:n}};if(i&&(a.stretchX||a.stretchY)){const t=Yh(h,m,d),e=Yh(p,g,y);for(let r=0;r0&&(n=Math.max(10,n),this.circleDiameter=n);}else {const u=(null===(h=a.image)||void 0===h?void 0:h.content)&&(a.image.textFitWidth||a.image.textFitHeight)?jc(a):{x1:a.left,y1:a.top,x2:a.right,y2:a.bottom};u.y1=u.y1*o-l[0],u.y2=u.y2*o+l[2],u.x1=u.x1*o-l[3],u.x2=u.x2*o+l[1];const p=a.collisionPadding;if(p&&(u.x1-=p[0]*o,u.y1-=p[1]*o,u.x2+=p[2]*o,u.y2+=p[3]*o),c){const t=new r(u.x1,u.y1),e=new r(u.x2,u.y1),n=new r(u.x1,u.y2),i=new r(u.x2,u.y2),s=c*Math.PI/180;t._rotate(s),e._rotate(s),n._rotate(s),i._rotate(s),u.x1=Math.min(t.x,e.x,n.x,i.x),u.x2=Math.max(t.x,e.x,n.x,i.x),u.y1=Math.min(t.y,e.y,n.y,i.y),u.y2=Math.max(t.y,e.y,n.y,i.y);}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,n,i,s);}this.boxEndIndex=t.length;}}class Wh{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}}function Qh(t,e=1,n=!1){const i=Eh.fromPoints(t[0]),s=Math.min(i.width(),i.height());let a=s/2;const o=new Wh([],tp),{minX:l,minY:u,maxX:c,maxY:h}=i;if(0===s)return new r(l,u);for(let e=l;ep.d||!p.d)&&(p=r,n&&console.log("found best %d after %d probes",Math.round(1e4*r.d)/1e4,f)),r.max-p.d<=e||(a=r.h/2,o.push(new ep(r.p.x-a,r.p.y-a,a,t)),o.push(new ep(r.p.x+a,r.p.y-a,a,t)),o.push(new ep(r.p.x-a,r.p.y+a,a,t)),o.push(new ep(r.p.x+a,r.p.y+a,a,t)),f+=4);}return n&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function tp(t,e){return e.max-t.max}function ep(t,e,n,i){this.p=new r(t,e),this.h=n,this.d=function(t,e){let r=!1,n=1/0;for(let i=0;it.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(r=!r),n=Math.min(n,Lo(t,i,o));}}return (r?1:-1)*Math.sqrt(n)}(this.p,i),this.max=this.d+this.h*Math.SQRT2;}var rp;t.aE=void 0,(rp=t.aE||(t.aE={}))[rp.center=1]="center",rp[rp.left=2]="left",rp[rp.right=3]="right",rp[rp.top=4]="top",rp[rp.bottom=5]="bottom",rp[rp["top-left"]=6]="top-left",rp[rp["top-right"]=7]="top-right",rp[rp["bottom-left"]=8]="bottom-left",rp[rp["bottom-right"]=9]="bottom-right";const np=Number.POSITIVE_INFINITY;function ip(t,e){return e[1]!==np?function(t,e,r){let n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case "top-right":case "top-left":case "top":i=r-7;break;case "bottom-right":case "bottom-left":case "bottom":i=7-r;}switch(t){case "top-right":case "bottom-right":case "right":n=-e;break;case "top-left":case "bottom-left":case "left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){let r=0,n=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case "top-right":case "top-left":n=i-7;break;case "bottom-right":case "bottom-left":n=7-i;break;case "bottom":n=7-e;break;case "top":n=e-7;}switch(t){case "top-right":case "bottom-right":r=-i;break;case "top-left":case "bottom-left":r=i;break;case "left":r=e;break;case "right":r=-e;}return [r,n]}(t,e[0])}function sp(t,e,r){var n;const i=t.layout,s=null===(n=i.get("text-variable-anchor-offset"))||void 0===n?void 0:n.evaluate(e,{},r);if(s){const t=s.values,e=[];for(let r=0;rt*Qu));n.startsWith("top")?i[1]-=7:n.startsWith("bottom")&&(i[1]+=7),e[r+1]=i;}return new $e(e)}const a=i.get("text-variable-anchor");if(a){let n;n=void 0!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},r)*Qu,np]:i.get("text-offset").evaluate(e,{},r).map((t=>t*Qu));const s=[];for(const t of a)s.push(t,ip(t,n));return new $e(s)}return null}function ap(t){switch(t){case "right":case "top-right":case "bottom-right":return "right";case "left":case "top-left":case "bottom-left":return "left"}return "center"}function op(e,r,n,i,s,a,o,l,u,c,h,p){let f=a.textMaxSize.evaluate(r,{});void 0===f&&(f=o);const d=e.layers[0].layout,y=d.get("icon-offset").evaluate(r,{},h),m=up(n.horizontal),g=o/24,x=e.tilePixelRatio*g,v=e.tilePixelRatio*f/24,b=e.tilePixelRatio*l,w=e.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*e.tilePixelRatio,S=function(t,e,r,n=1){const i=t.get("icon-padding").evaluate(e,{},r),s=i&&i.values;return [s[0]*n,s[1]*n,s[2]*n,s[3]*n]}(d,r,h,e.tilePixelRatio),A=d.get("text-max-angle")/180*Math.PI,k="viewport"!==d.get("text-rotation-alignment")&&"point"!==d.get("symbol-placement"),M="map"===d.get("icon-rotation-alignment")&&"point"!==d.get("symbol-placement"),I=d.get("symbol-placement"),z=w/2,C=d.get("icon-text-fit");let E;i&&"none"!==C&&(e.allowVerticalPlacement&&n.vertical&&(E=Nc(i,n.vertical,C,d.get("icon-text-fit-padding"),y,g)),m&&(i=Nc(i,m,C,d.get("icon-text-fit-padding"),y,g)));const T=h?p.line.getGranularityForZoomLevel(h.z):1,B=(l,p)=>{p.x<0||p.x>=P||p.y<0||p.y>=P||function(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k){const M=e.addToLineVertexArray(r,n);let I,z,P,C,E=0,T=0,B=0,V=0,F=-1,$=-1;const D={};let L=no("");if(e.allowVerticalPlacement&&i.vertical){const t=l.layout.get("text-rotate").evaluate(w,{},A)+90;P=new Jh(u,r,c,h,p,i.vertical,f,d,y,t),o&&(C=new Jh(u,r,c,h,p,o,g,x,y,t));}if(s){const n=l.layout.get("icon-rotate").evaluate(w,{}),i="none"!==l.layout.get("icon-text-fit"),a=Xh(s,n,S,i),f=o?Xh(o,n,S,i):void 0;z=new Jh(u,r,c,h,p,s,g,x,!1,n),E=4*a.length;const d=e.iconSizeData;let y=null;"source"===d.kind?(y=[qc*l.layout.get("icon-size").evaluate(w,{})],y[0]>Gc&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)):"composite"===d.kind&&(y=[qc*_.compositeIconSizes[0].evaluate(w,{},A),qc*_.compositeIconSizes[1].evaluate(w,{},A)],(y[0]>Gc||y[1]>Gc)&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)),e.addSymbols(e.icon,a,y,b,v,w,t.ao.none,r,M.lineStartIndex,M.lineLength,-1,A),F=e.icon.placedSymbolArray.length-1,f&&(T=4*f.length,e.addSymbols(e.icon,f,y,b,v,w,t.ao.vertical,r,M.lineStartIndex,M.lineLength,-1,A),$=e.icon.placedSymbolArray.length-1);}const O=Object.keys(i.horizontal);for(const n of O){const s=i.horizontal[n];if(!I){L=no(s.text);const t=l.layout.get("text-rotate").evaluate(w,{},A);I=new Jh(u,r,c,h,p,s,f,d,y,t);}const o=1===s.positionedLines.length;if(B+=lp(e,r,s,a,l,y,w,m,M,i.vertical?t.ao.horizontal:t.ao.horizontalOnly,o?O:[n],D,F,_,A),o)break}i.vertical&&(V+=lp(e,r,i.vertical,a,l,y,w,m,M,t.ao.vertical,["vertical"],D,$,_,A));const R=I?I.boxStartIndex:e.collisionBoxArray.length,U=I?I.boxEndIndex:e.collisionBoxArray.length,j=P?P.boxStartIndex:e.collisionBoxArray.length,N=P?P.boxEndIndex:e.collisionBoxArray.length,G=z?z.boxStartIndex:e.collisionBoxArray.length,X=z?z.boxEndIndex:e.collisionBoxArray.length,Z=C?C.boxStartIndex:e.collisionBoxArray.length,Y=C?C.boxEndIndex:e.collisionBoxArray.length;let H=-1;const K=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=K(I,H),H=K(P,H),H=K(z,H),H=K(C,H);const J=H>-1?1:0;J&&(H*=k/Qu),e.glyphOffsetArray.length>=th.MAX_GLYPHS&&q("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==w.sortKey&&e.addToSortKeyRanges(e.symbolInstances.length,w.sortKey);const W=sp(l,w,A),[Q,tt]=function(e,r){const n=e.length,i=null==r?void 0:r.values;if((null==i?void 0:i.length)>0)for(let r=0;r=0?D.right:-1,D.center>=0?D.center:-1,D.left>=0?D.left:-1,D.vertical||-1,F,$,L,R,U,j,N,G,X,Z,Y,c,B,V,E,T,J,0,f,H,Q,tt);}(e,p,l,n,i,s,E,e.layers[0],e.collisionBoxArray,r.index,r.sourceLayerIndex,e.index,x,[_,_,_,_],k,u,b,S,M,y,r,a,c,h,o);};if("line"===I)for(const t of Dh(r.geometry,0,0,P,P)){const r=ru(t,T),s=qh(r,w,A,n.vertical||m,i,24,v,e.overscaling,P);for(const t of s)m&&cp(e,m.text,z,t)||B(r,t);}else if("line-center"===I){for(const t of r.geometry)if(t.length>1){const e=ru(t,T),r=Nh(e,A,n.vertical||m,i,24,v);r&&B(e,r);}}else if("Polygon"===r.type)for(const t of Qr(r.geometry,0)){const e=Qh(t,16);B(ru(t[0],T,!0),new Lh(e.x,e.y,0));}else if("LineString"===r.type)for(const t of r.geometry){const e=ru(t,T);B(e,new Lh(e[0].x,e[0].y,0));}else if("Point"===r.type)for(const t of r.geometry)for(const e of t)B([e],new Lh(e.x,e.y,0));}function lp(t,e,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=function(t,e,n,i,s,a,o,l){const u=i.layout.get("text-rotate").evaluate(a,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const i of t.positionedGlyphs){if(!i.rect)continue;const a=i.rect||{};let h=4,p=!0,f=1,d=0;const y=(s||l)&&i.vertical,m=i.metrics.advance*i.scale/2;if(l&&e.verticalizable&&(d=t.lineOffset/2-(i.imageName?-(Qu-i.metrics.width*i.scale)/2:(i.scale-1)*Qu)),i.imageName){const t=o[i.imageName];p=t.sdf,f=t.pixelRatio,h=1/f;}const g=s?[i.x+m,i.y]:[0,0];let x=s?[0,0]:[i.x+m+n[0],i.y+n[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=i.metrics.isDoubleResolution?2:1,w=(i.metrics.left-h)*i.scale-m+x[0],_=(-i.metrics.top-h)*i.scale+x[1],S=w+a.w/b*i.scale/f,A=_+a.h/b*i.scale/f,k=new r(w,_),M=new r(S,_),I=new r(w,A),z=new r(S,A);if(y){const t=new r(-m,m- -17),e=-Math.PI/2,n=12-m,s=new r(22-n,-(i.imageName?n:0)),a=new r(...v);k._rotateAround(e,t)._add(s)._add(a),M._rotateAround(e,t)._add(s)._add(a),I._rotateAround(e,t)._add(s)._add(a),z._rotateAround(e,t)._add(s)._add(a);}if(u){const t=Math.sin(u),e=Math.cos(u),r=[e,-t,t,e];k._matMult(r),M._matMult(r),I._matMult(r),z._matMult(r);}const P=new r(0,0),C=new r(0,0);c.push({tl:k,tr:M,bl:I,br:z,tex:a,writingMode:e.writingMode,glyphOffset:g,sectionIndex:i.sectionIndex,isSDF:p,pixelOffsetTL:P,pixelOffsetBR:C,minFontScaleX:0,minFontScaleY:0});}return c}(0,n,l,s,a,o,i,t.allowVerticalPlacement),g=t.textSizeData;let x=null;"source"===g.kind?(x=[qc*s.layout.get("text-size").evaluate(o,{})],x[0]>Gc&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)):"composite"===g.kind&&(x=[qc*d.compositeTextSizes[0].evaluate(o,{},y),qc*d.compositeTextSizes[1].evaluate(o,{},y)],(x[0]>Gc||x[1]>Gc)&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)),t.addSymbols(t.text,m,x,l,a,o,c,e,u.lineStartIndex,u.lineLength,f,y);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*m.length}function up(t){for(const e in t)return t[e];return null}function cp(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=hp[15&r];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new pp(a,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=hp.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+s+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return fp(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,r,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:a}=this,o=[0,i.length-1,0],l=[];for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=a){for(let a=h;a<=c;a++){const o=s[2*a],u=s[2*a+1];o>=t&&o<=r&&u>=e&&u<=n&&l.push(i[a]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?r>=f:n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return l}within(t,e,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:n,coords:i,nodeSize:s}=this,a=[0,n.length-1,0],o=[],l=r*r;for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)gp(i[2*r],i[2*r+1],t,e)<=l&&o.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];gp(f,d,t,e)<=l&&o.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return o}}function fp(t,e,r,n,i,s){if(i-n<=r)return;const a=n+i>>1;dp(t,e,a,n,i,s),fp(t,e,r,n,a-1,1-s),fp(t,e,r,a+1,i,1-s);}function dp(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const a=i-n+1,o=r-n+1,l=Math.log(a),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(a-u)/a)*(o-a/2<0?-1:1);dp(t,e,r,Math.max(n,Math.floor(r-o*u/a+c)),Math.min(i,Math.floor(r+(a-o)*u/a+c)),s);}const a=e[2*r+s];let o=n,l=i;for(yp(t,e,n,r),e[2*i+s]>a&&yp(t,e,n,i);oa;)l--;}e[2*n+s]===a?yp(t,e,n,l):(l++,yp(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1);}}function yp(t,e,r,n){mp(t,r,n),mp(e,2*r,2*n),mp(e,2*r+1,2*n+1);}function mp(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function gp(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}var xp;t.cx=void 0,(xp=t.cx||(t.cx={})).create="create",xp.load="load",xp.fullLoad="fullLoad";let vp=null,bp=[];const wp=1e3/60,_p="loadTime",Sp="fullLoadTime",Ap={mark(t){performance.mark(t);},frame(t){const e=t;null!=vp&&bp.push(e-vp),vp=e;},clearMetrics(){vp=null,bp=[],performance.clearMeasures(_p),performance.clearMeasures(Sp);for(const e in t.cx)performance.clearMarks(t.cx[e]);},getPerformanceMetrics(){performance.measure(_p,t.cx.create,t.cx.load),performance.measure(Sp,t.cx.create,t.cx.fullLoad);const e=performance.getEntriesByName(_p)[0].duration,r=performance.getEntriesByName(Sp)[0].duration,n=bp.length,i=1/(bp.reduce(((t,e)=>t+e),0)/n/1e3),s=bp.filter((t=>t>wp)).reduce(((t,e)=>t+(e-wp)/wp),0);return {loadTime:e,fullLoadTime:r,fps:i,percentDroppedFrames:s/(n+s)*100,totalFrames:n}}};t.$=P,t.A=f,t.B=function([t,e,r]){return e+=90,e*=Math.PI/180,r*=Math.PI/180,{x:t*Math.cos(e)*Math.sin(r),y:t*Math.sin(e)*Math.sin(r),z:t*Math.cos(r)}},t.C=dr,t.D=Ds,t.E=gt,t.F=Is,t.G=ts,t.H=function(t){if(null==Z){const e=t.navigator?t.navigator.userAgent:null;Z=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return Z},t.I=vc,t.J=class{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new fh((()=>this.process())),this.subscription=Q(this.target,"message",(t=>this.receive(t)),!1),this.globalScope=X(self)?t:window;}registerMessageHandler(t,e){this.messageHandlers[t]=e;}sendAsync(t,e){return new Promise(((r,n)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10),s=e?Q(e.signal,"abort",(()=>{null==s||s.unsubscribe(),delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e);}),dh):null;this.resolveRejects[i]={resolve:t=>{null==s||s.unsubscribe(),r(t);},reject:t=>{null==s||s.unsubscribe(),n(t);}};const a=[],o=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:cs(t.data,a)});this.target.postMessage(o,{transfer:a});}))}receive(t){const e=t.data,r=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[r];const t=this.abortControllers[r];return delete this.abortControllers[r],void(t&&t.abort())}if(X(self)||e.mustQueue)return this.tasks[r]=e,this.taskQueue.push(r),void this.invoker.trigger();this.processTask(r,e);}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e);}processTask(t,r){return e(this,void 0,void 0,(function*(){if(""===r.type){const e=this.resolveRejects[t];if(delete this.resolveRejects[t],!e)return;return void(r.error?e.reject(hs(r.error)):e.resolve(hs(r.data)))}if(!this.messageHandlers[r.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${r.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const e=hs(r.data),n=new AbortController;this.abortControllers[t]=n;try{const i=yield this.messageHandlers[r.type](r.sourceMapId,e,n);this.completeTask(t,null,i);}catch(e){this.completeTask(t,e);}}))}completeTask(t,e,r){const n=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?cs(e):null,data:cs(r,n)};this.target.postMessage(i,{transfer:n});}remove(){this.invoker.remove(),this.subscription.unsubscribe();}},t.K=lt,t.L=function(){var t=new f(16);return f!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.M=function(t,e,r){var n,i,s,a,o,l,u,c,h,p,f,d,y=r[0],m=r[1],g=r[2];return e===t?(t[12]=e[0]*y+e[4]*m+e[8]*g+e[12],t[13]=e[1]*y+e[5]*m+e[9]*g+e[13],t[14]=e[2]*y+e[6]*m+e[10]*g+e[14],t[15]=e[3]*y+e[7]*m+e[11]*g+e[15]):(i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=n=e[0],t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=n*y+o*m+h*g+e[12],t[13]=i*y+l*m+p*g+e[13],t[14]=s*y+u*m+f*g+e[14],t[15]=a*y+c*m+d*g+e[15]),t},t.N=function(t,e,r){var n=r[0],i=r[1],s=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.O=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],y=e[12],m=e[13],g=e[14],x=e[15],v=r[0],b=r[1],w=r[2],_=r[3];return t[0]=v*n+b*o+w*h+_*y,t[1]=v*i+b*l+w*p+_*m,t[2]=v*s+b*u+w*f+_*g,t[3]=v*a+b*c+w*d+_*x,t[4]=(v=r[4])*n+(b=r[5])*o+(w=r[6])*h+(_=r[7])*y,t[5]=v*i+b*l+w*p+_*m,t[6]=v*s+b*u+w*f+_*g,t[7]=v*a+b*c+w*d+_*x,t[8]=(v=r[8])*n+(b=r[9])*o+(w=r[10])*h+(_=r[11])*y,t[9]=v*i+b*l+w*p+_*m,t[10]=v*s+b*u+w*f+_*g,t[11]=v*a+b*c+w*d+_*x,t[12]=(v=r[12])*n+(b=r[13])*o+(w=r[14])*h+(_=r[15])*y,t[13]=v*i+b*l+w*p+_*m,t[14]=v*s+b*u+w*f+_*g,t[15]=v*a+b*c+w*d+_*x,t},t.P=r,t.Q=function(t,e){const r={};for(let n=0;n!n.has(t.id)))),o.update&&(o.update=o.update.filter((t=>!n.has(t.id))));const i=new Set((null!==(r=t.add)&&void 0!==r?r:[]).map((t=>t.id)));e.remove=e.remove.filter((t=>!i.has(t)));}if(e.remove){const t=new Set(o.remove?o.remove.concat(e.remove):e.remove);o.remove=Array.from(t.values());}if(e.add){const t=o.add?o.add.concat(e.add):e.add,r=new Map(t.map((t=>[t.id,t])));o.add=Array.from(r.values());}if(e.update){const t=new Map(null===(n=o.update)||void 0===n?void 0:n.map((t=>[t.id,t])));for(const r of e.update){const e=null!==(i=t.get(r.id))&&void 0!==i?i:{id:r.id};r.newGeometry&&(e.newGeometry=r.newGeometry),r.addOrUpdateProperties&&(e.addOrUpdateProperties=(null!==(s=e.addOrUpdateProperties)&&void 0!==s?s:[]).concat(r.addOrUpdateProperties)),r.removeProperties&&(e.removeProperties=(null!==(a=e.removeProperties)&&void 0!==a?a:[]).concat(r.removeProperties)),r.removeAllProperties&&(e.removeAllProperties=!0),t.set(r.id,e);}o.update=Array.from(t.values());}return o.remove&&o.add&&(o.remove=o.remove.filter((t=>-1===o.add.findIndex((e=>e.id===t))))),o},t.a1=Ah,t.a2=Eh,t.a3=25,t.a4=Mh,t.a5=t=>{const e=window.document.createElement("video");return e.muted=!0,new Promise((r=>{e.onloadstart=()=>{r(e);};for(const r of t){const t=window.document.createElement("source");pt(r)||(e.crossOrigin="Anonymous"),t.src=r,e.appendChild(t);}}))},t.a6=Ct,t.a7=function(){return O++},t.a8=ba,t.a9=th,t.aA=function(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return [e,r,n,i]},t.aB=Qu,t.aC=C,t.aD=function(t,e,r,n,i=!1){if(!r[0]&&!r[1])return [0,0];const s=i?"map"===n?-t.bearingInRadians:0:"viewport"===n?t.bearingInRadians:0;if(s){const t=Math.sin(s),e=Math.cos(s);r=[r[0]*e-r[1]*t,r[0]*t+r[1]*e];}return [i?r[0]:C(e,r[0],t.zoom),i?r[1]:C(e,r[1],t.zoom)]},t.aF=Zc,t.aG=ap,t.aH=Vc,t.aI=pp,t.aJ=Ys,t.aK=Jl,t.aL=Ea,t.aM=Za,t.aN=Na,t.aO=D,t.aP=et,t.aQ=Sh,t.aR=b,t.aS=v,t.aT=function(t){var e=new f(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.aU=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t},t.aV=function(t,e){var r=e[0],n=e[1],i=e[2],s=r*r+n*n+i*i;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t},t.aW=w,t.aX=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.aY=function(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t},t.aZ=g,t.a_=function(t,e,r){const n=e[0]*r[0]+e[1]*r[1]+e[2]*r[2];return 0===n?null:(-(t[0]*r[0]+t[1]*r[1]+t[2]*r[2])-r[3])/n},t.aa=hi,t.ab=Io,t.ac=Bh,t.ad=function(t){const e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,r,n,i)=>{const s=n||i;return e[r]=!s||s.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t;}return e},t.ae=tt,t.af=function(t){return Math.pow(2,t)},t.ag=y,t.ah=$,t.ai=85.051129,t.aj=wh,t.ak=function(t){return Math.log(t)/Math.LN2},t.al=function(t){var e=t[0],r=t[1];return e*e+r*r},t.am=function(t,e){const r=[];for(const n in t)n in e||r.push(n);return r},t.an=function(t,e){let r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){const{interpolationType:i,minZoom:s,maxZoom:a}=t,o=i?$(pr.interpolationFactor(i,e,s,a),0,1):0;"camera"===t.kind?n=dr.number(t.minSize,t.maxSize,o):r=o;}return {uSizeT:r,uSize:n}},t.ap=function(t,{uSize:e,uSizeT:r},{lowerSize:n,upperSize:i}){return "source"===t.kind?n/qc:"composite"===t.kind?dr.number(n/qc,i/qc,r):e},t.aq=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],y=e[13],m=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,w=n*l-i*o,_=n*u-s*o,S=i*u-s*l,A=c*y-h*d,k=c*m-p*d,M=c*g-f*d,I=h*m-p*y,z=h*g-f*y,P=p*g-f*m,C=x*P-v*z+b*I+w*M-_*k+S*A;return C?(t[0]=(o*P-l*z+u*I)*(C=1/C),t[1]=(i*z-n*P-s*I)*C,t[2]=(y*S-m*_+g*w)*C,t[3]=(p*_-h*S-f*w)*C,t[4]=(l*M-a*P-u*k)*C,t[5]=(r*P-i*M+s*k)*C,t[6]=(m*b-d*S-g*v)*C,t[7]=(c*S-p*b+f*v)*C,t[8]=(a*z-o*M+u*A)*C,t[9]=(n*M-r*z-s*A)*C,t[10]=(d*_-y*b+g*x)*C,t[11]=(h*b-c*_-f*x)*C,t[12]=(o*k-a*I-l*A)*C,t[13]=(r*I-n*k+i*A)*C,t[14]=(y*v-d*w-m*x)*C,t[15]=(c*w-h*v+p*x)*C,t):null},t.ar=I,t.as=function(t){var e=t[0],r=t[1];return Math.sqrt(e*e+r*r)},t.at=function(t){return t[0]=0,t[1]=0,t},t.au=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t},t.av=Kc,t.aw=A,t.ax=function(t,e,n,i){const s=e.y-t.y,a=e.x-t.x,o=i.y-n.y,l=i.x-n.x,u=o*a-l*s;if(0===u)return null;const c=(l*(t.y-n.y)-o*(t.x-n.x))/u;return new r(t.x+c*a,t.y+c*s)},t.ay=Dh,t.az=Eo,t.b=Y,t.b$=class extends la{},t.b0=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t},t.b1=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]},t.b2=Ih,t.b3=Ph,t.b4=function(t,e,r,n,i){var s=1/Math.tan(e/2);if(t[0]=s/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=s,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0){var a=1/(n-i);t[10]=(i+n)*a,t[14]=2*i*n*a;}else t[10]=-1,t[14]=-2*n;return t},t.b5=function(t){var e=new f(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.b6=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[4],c=e[5],h=e[6],p=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i+u*n,t[1]=a*i+c*n,t[2]=o*i+h*n,t[3]=l*i+p*n,t[4]=u*i-s*n,t[5]=c*i-a*n,t[6]=h*i-o*n,t[7]=p*i-l*n,t},t.b7=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=s*i+u*n,t[5]=a*i+c*n,t[6]=o*i+h*n,t[7]=l*i+p*n,t[8]=u*i-s*n,t[9]=c*i-a*n,t[10]=h*i-o*n,t[11]=p*i-l*n,t},t.b8=function(){const t=new Float32Array(16);return y(t),t},t.b9=function(){const t=new Float64Array(16);return y(t),t},t.bA=function(t,e){const r=E(t,360),n=E(e,360),i=n-r,s=n>r?i-360:i+360;return Math.abs(i)0?a:-a},t.bD=function(t,e){const r=E(t,2*Math.PI),n=E(e,2*Math.PI);return Math.min(Math.abs(r-n),Math.abs(r-n+2*Math.PI),Math.abs(r-n-2*Math.PI))},t.bE=function(){const t={},e=xt.$version;for(const r in xt.$root){const n=xt.$root[r];if(n.required){let i=null;i="version"===r?e:"array"===n.type?[]:{},null!=i&&(t[r]=i);}}return t},t.bF=ps,t.bG=ct,t.bH=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(let n=0;n{"source"in t&&n[t.source]?r.push({command:"removeLayer",args:[t.id]}):s.push(t);})),r=r.concat(i),function(t,e,r){e=e||[];const n=(t=t||[]).map(zt),i=e.map(zt),s=t.reduce(Pt,{}),a=e.reduce(Pt,{}),o=n.slice(),l=Object.create(null);let u,c,h,p,f;for(let t=0,e=0;tp?(i=Math.acos(s),a=Math.sin(i),o=Math.sin((1-n)*i)/a,l=Math.sin(n*i)/a):(o=1-n,l=n),t[0]=o*u+l*d,t[1]=o*c+l*y,t[2]=o*h+l*m,t[3]=o*f+l*g,t},t.bd=function(t){const e=new Float64Array(9);var r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v;h=(i=(n=t)[0])*(l=i+i),p=(s=n[1])*l,d=(a=n[2])*l,y=a*(u=s+s),g=(o=n[3])*l,x=o*u,v=o*(c=a+a),(r=e)[0]=1-(f=s*u)-(m=a*c),r[3]=p-v,r[6]=d+x,r[1]=p+v,r[4]=1-h-m,r[7]=y-g,r[2]=d-x,r[5]=y+g,r[8]=1-h-f;const b=et(-Math.asin($(e[2],-1,1)));let w,_;return Math.hypot(e[5],e[8])<.001?(w=0,_=-et(Math.atan2(e[3],e[4]))):(w=et(0===e[5]&&0===e[8]?0:Math.atan2(e[5],e[8])),_=et(0===e[1]&&0===e[0]?0:Math.atan2(e[1],e[0]))),{roll:w,pitch:b+90,bearing:_}},t.be=function(t,e){return t.roll==e.roll&&t.pitch==e.pitch&&t.bearing==e.bearing},t.bf=Me,t.bg=uo,t.bh=Wl,t.bi=Ql,t.bj=Kl,t.bk=T,t.bl=B,t.bm=Le,t.bn=function(t,e,r,n,i){return T(n,i,$((t-e)/(r-e),0,1))},t.bo=E,t.bp=function(){return new Float64Array(3)},t.bq=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t},t.br=M,t.bs=function(t,e,r){var n=r[0],i=r[1],s=r[2],a=r[3],o=e[0],l=e[1],u=e[2],c=i*u-s*l,h=s*o-n*u,p=n*l-i*o;return t[0]=o+a*(c+=c)+i*(p+=p)-s*(h+=h),t[1]=l+a*h+s*c-n*p,t[2]=u+a*p+n*h-i*c,t},t.bt=function(t,e,r){const n=(i=[t[0],t[1],t[2],e[0],e[1],e[2],r[0],r[1],r[2]])[0]*((c=i[8])*(a=i[4])-(o=i[5])*(u=i[7]))+i[1]*(-c*(s=i[3])+o*(l=i[6]))+i[2]*(u*s-a*l);var i,s,a,o,l,u,c;if(0===n)return null;const h=w([],[e[0],e[1],e[2]],[r[0],r[1],r[2]]),p=w([],[r[0],r[1],r[2]],[t[0],t[1],t[2]]),f=w([],[t[0],t[1],t[2]],[e[0],e[1],e[2]]),d=b([],h,-t[3]);return v(d,d,b([],p,-e[3])),v(d,d,b([],f,-r[3])),b(d,d,1/n),d},t.bu=yh,t.bv=function(){return new Float64Array(4)},t.bw=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),s[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),s[2]=i[2],t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bx=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0],s[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),s[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.by=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),s[1]=i[1],s[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bz=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i-u*n,t[1]=a*i-c*n,t[2]=o*i-h*n,t[3]=l*i-p*n,t[8]=s*n+u*i,t[9]=a*n+c*i,t[10]=o*n+h*i,t[11]=l*n+p*i,t},t.c=st,t.c0=Ku,t.c1=class extends ca{},t.c2=cl,t.c3=function(t){return t<=1?1:Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},t.c4=ul,t.c5=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[3]*n+r[7]*i+r[11]*s+r[15];return t[0]=(r[0]*n+r[4]*i+r[8]*s+r[12])/(a=a||1),t[1]=(r[1]*n+r[5]*i+r[9]*s+r[13])/a,t[2]=(r[2]*n+r[6]*i+r[10]*s+r[14])/a,t},t.c6=class extends Ws{},t.c7=class extends ga{},t.c8=function(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[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]},t.c9=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=t[9],f=t[10],d=t[11],y=t[12],m=t[13],g=t[14],x=t[15],v=e[0],b=e[1],w=e[2],_=e[3],S=e[4],A=e[5],k=e[6],M=e[7],I=e[8],z=e[9],P=e[10],C=e[11],E=e[12],T=e[13],B=e[14],V=e[15];return Math.abs(r-v)<=p*Math.max(1,Math.abs(r),Math.abs(v))&&Math.abs(n-b)<=p*Math.max(1,Math.abs(n),Math.abs(b))&&Math.abs(i-w)<=p*Math.max(1,Math.abs(i),Math.abs(w))&&Math.abs(s-_)<=p*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(a-S)<=p*Math.max(1,Math.abs(a),Math.abs(S))&&Math.abs(o-A)<=p*Math.max(1,Math.abs(o),Math.abs(A))&&Math.abs(l-k)<=p*Math.max(1,Math.abs(l),Math.abs(k))&&Math.abs(u-M)<=p*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(c-I)<=p*Math.max(1,Math.abs(c),Math.abs(I))&&Math.abs(h-z)<=p*Math.max(1,Math.abs(h),Math.abs(z))&&Math.abs(f-P)<=p*Math.max(1,Math.abs(f),Math.abs(P))&&Math.abs(d-C)<=p*Math.max(1,Math.abs(d),Math.abs(C))&&Math.abs(y-E)<=p*Math.max(1,Math.abs(y),Math.abs(E))&&Math.abs(m-T)<=p*Math.max(1,Math.abs(m),Math.abs(T))&&Math.abs(g-B)<=p*Math.max(1,Math.abs(g),Math.abs(B))&&Math.abs(x-V)<=p*Math.max(1,Math.abs(x),Math.abs(V))},t.cA=function(t,e){at.REGISTERED_PROTOCOLS[t]=e;},t.cB=function(t){delete at.REGISTERED_PROTOCOLS[t];},t.cC=function(t,e){const r={};for(let n=0;nt*Qu));}let v=o?"center":n.get("text-justify").evaluate(i,{},e.canonical);const b="point"===n.get("symbol-placement")?n.get("text-max-width").evaluate(i,{},e.canonical)*Qu:1/0,w=()=>{e.bucket.allowVerticalPlacement&&ds(s)&&(d.vertical=Ac(y,e.glyphMap,e.glyphPositions,e.imagePositions,c,b,a,m,"left",f,g,t.ao.vertical,!0,p,h));};if(!o&&x){const r=new Set;if("auto"===v)for(let t=0;t0||(null===(i=r.addOrUpdateProperties)||void 0===i?void 0:i.length)>0);if((r.newGeometry||r.removeAllProperties||o)&&(e=Object.assign({},e),t.set(r.id,e),o&&(e.properties=Object.assign({},e.properties))),r.newGeometry&&(e.geometry=r.newGeometry),r.removeAllProperties)e.properties={};else if((null===(s=r.removeProperties)||void 0===s?void 0:s.length)>0)for(const t of r.removeProperties)Object.prototype.hasOwnProperty.call(e.properties,t)&&delete e.properties[t];if((null===(a=r.addOrUpdateProperties)||void 0===a?void 0:a.length)>0)for(const{key:t,value:n}of r.addOrUpdateProperties)e.properties[t]=n;}},t.cX=Ms,t.ca=function(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[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.cb=t=>"symbol"===t.type,t.cc=t=>"circle"===t.type,t.cd=t=>"heatmap"===t.type,t.ce=t=>"line"===t.type,t.cf=t=>"fill"===t.type,t.cg=t=>"fill-extrusion"===t.type,t.ch=t=>"hillshade"===t.type,t.ci=t=>"color-relief"===t.type,t.cj=t=>"raster"===t.type,t.ck=t=>"background"===t.type,t.cl=t=>"custom"===t.type,t.cm=V,t.cn=function(t,e,r){const n=z(e.x-r.x,e.y-r.y),i=z(t.x-r.x,t.y-r.y);var s,a;return et(Math.atan2(n[0]*i[1]-n[1]*i[0],(s=n)[0]*(a=i)[0]+s[1]*a[1]))},t.co=F,t.cp=function(t,e){return nt[e]&&(t instanceof MouseEvent||t instanceof WheelEvent)},t.cq=function(t,e){return rt[e]&&"touches"in t},t.cr=function(t){return rt[t]||nt[t]},t.cs=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t},t.ct=function(t,e){const{x:r,y:n}=Ah.fromLngLat(e);return !(t<0||t>25||n<0||n>=1||r<0||r>=1)},t.cu=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.cv=class extends Js{},t.cw=Ap,t.cy=function(t){return t.message===it},t.cz=ut,t.d=pt,t.e=L,t.f=t=>e(void 0,void 0,void 0,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),t.g=ot,t.h=t=>new Promise(((e,r)=>{const n=new Image;n.onload=()=>{e(n),URL.revokeObjectURL(n.src),n.onload=null,window.requestAnimationFrame((()=>{n.src=H;}));},n.onerror=()=>r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const i=new Blob([new Uint8Array(t)],{type:"image/png"});n.src=t.byteLength?URL.createObjectURL(i):H;})),t.i=X,t.j=(t,e)=>ht(L(t,{type:"json"}),e),t.k=mt,t.l=yt,t.m=ht,t.n=(t,e)=>ht(L(t,{type:"arrayBuffer"}),e),t.o=function(t){return new nc(t).readFields(yc,[])},t.p=xc,t.q=ol,t.r=js,t.s=Q,t.t=Es,t.u=fs,t.v=xt,t.w=q,t.x=Qi,t.y=ns,t.z=Wi;})); + +define("worker",["./shared"],(function(e){"use strict";class t{constructor(e,t){this.keyCache={},e&&this.replace(e,t);}replace(e,t){this._layerConfigs={},this._layers={},this.update(e,[],t);}update(t,i,o){for(const i of t){this._layerConfigs[i.id]=i;const t=this._layers[i.id]=e.bJ(i,o);t._featureFilter=e.aa(t.filter,o),this.keyCache[i.id]&&delete this.keyCache[i.id];}for(const e of i)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const s=e.cC(Object.values(this._layerConfigs),this.keyCache);for(const e of s){const t=e.map((e=>this._layers[e.id])),i=t[0];if("none"===i.visibility)continue;const o=i.source||"";let s=this.familiesBySource[o];s||(s=this.familiesBySource[o]={});const n=i.sourceLayer||"_geojsonTileLayer";let r=s[n];r||(r=s[n]=[]),r.push(t);}}}class i{constructor(t){const i={},o=[];for(const e in t){const s=t[e],n=i[e]={};for(const e in s){const t=s[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const i={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};o.push(i),n[e]={rect:i,metrics:t.metrics};}}const{w:s,h:n}=e.p(o),r=new e.q({width:s||1,height:n||1});for(const o in t){const s=t[o];for(const t in s){const n=s[+t];if(!n||0===n.bitmap.width||0===n.bitmap.height)continue;const a=i[o][t].rect;e.q.copy(n.bitmap,r,{x:0,y:0},{x:a.x+1,y:a.y+1},n.bitmap);}}this.image=r,this.positions=i;}}e.cD("GlyphAtlas",i);class o{constructor(t){this.tileID=new e.Z(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[];}parse(t,o,n,r,a){return e._(this,void 0,void 0,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.a8;const l=new e.cE(Object.keys(t.layers).sort()),c=new e.cF(this.tileID,this.promoteId);c.bucketLayerIDs=[];const u={},h={featureIndex:c,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:n,subdivisionGranularity:a},d=o.familiesBySource[this.source];for(const i in d){const o=t.layers[i];if(!o)continue;1===o.version&&e.w(`Vector tile source "${this.source}" layer "${i}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const r=l.encode(i),a=[];for(let e=0;e=i.maxzoom||"none"!==i.visibility&&(s(t,this.zoom,n),(u[i.id]=i.createBucket({index:c.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:r,sourceID:this.source})).populate(a,h,this.tileID.canonical),c.bucketLayerIDs.push(t.map((e=>e.id))));}}const f=e.bN(h.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?void 0:e.abort())),this.inFlightDependencies=[];let g=Promise.resolve({});if(Object.keys(f).length){const e=new AbortController;this.inFlightDependencies.push(e),g=r.sendAsync({type:"GG",data:{stacks:f,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const p=Object.keys(h.iconDependencies);let m=Promise.resolve({});if(p.length){const e=new AbortController;this.inFlightDependencies.push(e),m=r.sendAsync({type:"GI",data:{icons:p,source:this.source,tileID:this.tileID,type:"icons"}},e);}const y=Object.keys(h.patternDependencies);let v=Promise.resolve({});if(y.length){const e=new AbortController;this.inFlightDependencies.push(e),v=r.sendAsync({type:"GI",data:{icons:y,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const[w,x,b]=yield Promise.all([g,m,v]),S=new i(w),_=new e.cG(x,b);for(const t in u){const i=u[t];i instanceof e.a9?(s(i.layers,this.zoom,n),e.cH({bucket:i,glyphMap:w,glyphPositions:S.positions,imageMap:x,imagePositions:_.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:h.subdivisionGranularity})):i.hasPattern&&(i instanceof e.cI||i instanceof e.cJ||i instanceof e.cK)&&(s(i.layers,this.zoom,n),i.addFeatures(h,this.tileID.canonical,_.patternPositions));}return this.status="done",{buckets:Object.values(u).filter((e=>!e.isEmpty())),featureIndex:c,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:S.image,imageAtlas:_,glyphMap:this.returnDependencies?w:null,iconMap:this.returnDependencies?x:null,glyphPositions:this.returnDependencies?S.positions:null}}))}}function s(t,i,o){const s=new e.F(i);for(const e of t)e.recalculate(s,o);}class n{constructor(e,t,i){this.actor=e,this.layerIndex=t,this.availableImages=i,this.fetching={},this.loading={},this.loaded={};}loadVectorTile(t,i){return e._(this,void 0,void 0,(function*(){const o=yield e.n(t.request,i);try{return {vectorTile:new e.cL(new e.cM(o.data)),rawData:o.data,cacheControl:o.cacheControl,expires:o.expires}}catch(e){const i=new Uint8Array(o.data);let s=`Unable to parse the tile at ${t.request.url}, `;throw s+=31===i[0]&&139===i[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${e.message}`,new Error(s)}}))}loadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid,s=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.cN(t.request),n=new o(t);this.loading[i]=n;const r=new AbortController;n.abort=r;try{const o=yield this.loadVectorTile(t,r);if(delete this.loading[i],!o)return null;const a=o.rawData,l={};o.expires&&(l.expires=o.expires),o.cacheControl&&(l.cacheControl=o.cacheControl);const c={};if(s){const e=s.finish();e&&(c.resourceTiming=JSON.parse(JSON.stringify(e)));}n.vectorTile=o.vectorTile;const u=n.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);this.loaded[i]=n,this.fetching[i]={rawTileData:a,cacheControl:l,resourceTiming:c};try{const t=yield u;return e.e({rawTileData:a.slice(0)},t,l,c)}finally{delete this.fetching[i];}}catch(e){throw delete this.loading[i],n.status="done",this.loaded[i]=n,e}}))}reloadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid;if(!this.loaded||!this.loaded[i])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const o=this.loaded[i];if(o.showCollisionBoxes=t.showCollisionBoxes,"parsing"===o.status){const s=yield o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);let n;if(this.fetching[i]){const{rawTileData:t,cacheControl:o,resourceTiming:r}=this.fetching[i];delete this.fetching[i],n=e.e({rawTileData:t.slice(0)},s,o,r);}else n=s;return n}if("done"===o.status&&o.vectorTile)return o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity)}))}abortTile(t){return e._(this,void 0,void 0,(function*(){const e=this.loading,i=t.uid;e&&e[i]&&e[i].abort&&(e[i].abort.abort(),delete e[i]);}))}removeTile(t){return e._(this,void 0,void 0,(function*(){this.loaded&&this.loaded[t.uid]&&delete this.loaded[t.uid];}))}}class r{constructor(){this.loaded={};}loadTile(t){return e._(this,void 0,void 0,(function*(){const{uid:i,encoding:o,rawImageData:s,redFactor:n,greenFactor:r,blueFactor:a,baseShift:l}=t,c=s.width+2,u=s.height+2,h=e.b(s)?new e.R({width:c,height:u},yield e.cO(s,-1,-1,c,u)):s,d=new e.cP(i,h,o,n,r,a,l);return this.loaded=this.loaded||{},this.loaded[i]=d,d}))}removeTile(e){const t=this.loaded,i=e.uid;t&&t[i]&&delete t[i];}}var a,l,c=function(){if(l)return a;function e(e,i){if(0!==e.length){t(e[0],i);for(var o=1;o=Math.abs(a)?i-l+a:a-l+i,i=l;}i+o>=0!=!!t&&e.reverse();}return l=1,a=function t(i,o){var s,n=i&&i.type;if("FeatureCollection"===n)for(s=0;s>31}function v(e,t){const i=e.loadGeometry(),o=e.type;let s=0,n=0;for(const r of i){let i=1;1===o&&(i=r.length),t.writeVarint(m(1,i));const a=3===o?r.length-1:r.length;for(let e=0;ee},b=Math.fround||(S=new Float32Array(1),e=>(S[0]=+e,S[0]));var S;class _{constructor(e){this.options=Object.assign(Object.create(x),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:i,maxZoom:o}=this.options;t&&console.time("total time");const s=`prepare ${e.length} points`;t&&console.time(s),this.points=e;const n=[];for(let t=0;t=i;e--){const i=+Date.now();r=this.trees[e]=this._createTree(this._cluster(r,e)),t&&console.log("z%d: %d clusters in %dms",e,r.numItems,+Date.now()-i);}return t&&console.timeEnd("total time"),this}getClusters(e,t){let i=((e[0]+180)%360+360)%360-180;const o=Math.max(-90,Math.min(90,e[1]));let s=180===e[2]?180:((e[2]+180)%360+360)%360-180;const n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)i=-180,s=180;else if(i>s){const e=this.getClusters([i,o,180,n],t),r=this.getClusters([-180,o,s,n],t);return e.concat(r)}const r=this.trees[this._limitZoom(t)],a=r.range(k(i),P(n),k(s),P(o)),l=r.data,c=[];for(const e of a){const t=this.stride*e;c.push(l[t+5]>1?M(l,t,this.clusterProps):this.points[l[t+3]]);}return c}getChildren(e){const t=this._getOriginId(e),i=this._getOriginZoom(e),o="No cluster with the specified id.",s=this.trees[i];if(!s)throw new Error(o);const n=s.data;if(t*this.stride>=n.length)throw new Error(o);const r=this.options.radius/(this.options.extent*Math.pow(2,i-1)),a=s.within(n[t*this.stride],n[t*this.stride+1],r),l=[];for(const t of a){const i=t*this.stride;n[i+4]===e&&l.push(n[i+5]>1?M(n,i,this.clusterProps):this.points[n[i+3]]);}if(0===l.length)throw new Error(o);return l}getLeaves(e,t,i){const o=[];return this._appendLeaves(o,e,t=t||10,i=i||0,0),o}getTile(e,t,i){const o=this.trees[this._limitZoom(e)],s=Math.pow(2,e),{extent:n,radius:r}=this.options,a=r/n,l=(i-a)/s,c=(i+1+a)/s,u={features:[]};return this._addTileFeatures(o.range((t-a)/s,l,(t+1+a)/s,c),o.data,t,i,s,u),0===t&&this._addTileFeatures(o.range(1-a/s,l,1,c),o.data,s,i,s,u),t===s-1&&this._addTileFeatures(o.range(0,l,a/s,c),o.data,-1,i,s,u),u.features.length?u:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const i=this.getChildren(e);if(t++,1!==i.length)break;e=i[0].properties.cluster_id;}return t}_appendLeaves(e,t,i,o,s){const n=this.getChildren(t);for(const t of n){const n=t.properties;if(n&&n.cluster?s+n.point_count<=o?s+=n.point_count:s=this._appendLeaves(e,n.cluster_id,i,o,s):s1;let l,c,u;if(a)l=I(t,e,this.clusterProps),c=t[e],u=t[e+1];else {const i=this.points[t[e+3]];l=i.properties;const[o,s]=i.geometry.coordinates;c=k(o),u=P(s);}const h={type:1,geometry:[[Math.round(this.options.extent*(c*s-i)),Math.round(this.options.extent*(u*s-o))]],tags:l};let d;d=a||this.options.generateId?t[e+3]:this.points[t[e+3]].id,void 0!==d&&(h.id=d),n.features.push(h);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:i,extent:o,reduce:s,minPoints:n}=this.options,r=i/(o*Math.pow(2,t)),a=e.data,l=[],c=this.stride;for(let i=0;it&&(f+=a[i+5]);}if(f>d&&f>=n){let e,n=o*d,r=u*d,g=-1;const p=(i/c<<5)+(t+1)+this.points.length;for(const o of h){const l=o*c;if(a[l+2]<=t)continue;a[l+2]=t;const u=a[l+5];n+=a[l]*u,r+=a[l+1]*u,a[l+4]=p,s&&(e||(e=this._map(a,i,!0),g=this.clusterProps.length,this.clusterProps.push(e)),s(e,this._map(a,l)));}a[i+4]=p,l.push(n/f,r/f,1/0,p,-1,f),s&&l.push(g);}else {for(let e=0;e1)for(const e of h){const i=e*c;if(!(a[i+2]<=t)){a[i+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,i){if(e[t+5]>1){const o=this.clusterProps[e[t+6]];return i?Object.assign({},o):o}const o=this.points[e[t+3]].properties,s=this.options.map(o);return i&&s===o?Object.assign({},s):s}}function M(e,t,i){return {type:"Feature",id:e[t+3],properties:I(e,t,i),geometry:{type:"Point",coordinates:[(o=e[t],360*(o-.5)),T(e[t+1])]}};var o;}function I(e,t,i){const o=e[t+5],s=o>=1e4?`${Math.round(o/1e3)}k`:o>=1e3?Math.round(o/100)/10+"k":o,n=e[t+6],r=-1===n?{}:Object.assign({},i[n]);return Object.assign(r,{cluster:!0,cluster_id:e[t+3],point_count:o,point_count_abbreviated:s})}function k(e){return e/360+.5}function P(e){const t=Math.sin(e*Math.PI/180),i=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return i<0?0:i>1?1:i}function T(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function D(e,t,i,o){let s=o;const n=t+(i-t>>1);let r,a=i-t;const l=e[t],c=e[t+1],u=e[i],h=e[i+1];for(let o=t+3;os)r=o,s=t;else if(t===s){const e=Math.abs(o-n);eo&&(r-t>3&&D(e,t,r,o),e[r+2]=s,i-r>3&&D(e,r,i,o));}function C(e,t,i,o,s,n){let r=s-i,a=n-o;if(0!==r||0!==a){const l=((e-i)*r+(t-o)*a)/(r*r+a*a);l>1?(i=s,o=n):l>0&&(i+=r*l,o+=a*l);}return r=e-i,a=t-o,r*r+a*a}function L(e,t,i,o){const s={id:null==e?null:e,type:t,geometry:i,tags:o,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===t||"MultiPoint"===t||"LineString"===t)O(s,i);else if("Polygon"===t)O(s,i[0]);else if("MultiLineString"===t)for(const e of i)O(s,e);else if("MultiPolygon"===t)for(const e of i)O(s,e[0]);return s}function O(e,t){for(let i=0;i0&&(r+=o?(s*l-a*n)/2:Math.sqrt(Math.pow(a-s,2)+Math.pow(l-n,2))),s=a,n=l;}const a=t.length-3;t[2]=1,D(t,0,a,i),t[a+2]=1,t.size=Math.abs(r),t.start=0,t.end=t.size;}function G(e,t,i,o){for(let s=0;s1?1:i}function j(e,t,i,o,s,n,r,a){if(o/=t,n>=(i/=t)&&r=o)return null;const l=[];for(const t of e){const e=t.geometry;let n=t.type;const r=0===s?t.minX:t.minY,c=0===s?t.maxX:t.maxY;if(r>=i&&c=o)continue;let u=[];if("Point"===n||"MultiPoint"===n)N(e,u,i,o,s);else if("LineString"===n)R(e,u,i,o,s,!1,a.lineMetrics);else if("MultiLineString"===n)J(e,u,i,o,s,!1);else if("Polygon"===n)J(e,u,i,o,s,!0);else if("MultiPolygon"===n)for(const t of e){const e=[];J(t,e,i,o,s,!0),e.length&&u.push(e);}if(u.length){if(a.lineMetrics&&"LineString"===n){for(const e of u)l.push(L(t.id,n,e,t.tags));continue}"LineString"!==n&&"MultiLineString"!==n||(1===u.length?(n="LineString",u=u[0]):n="MultiLineString"),"Point"!==n&&"MultiPoint"!==n||(n=3===u.length?"Point":"MultiPoint"),l.push(L(t.id,n,u,t.tags));}}return l.length?l:null}function N(e,t,i,o,s){for(let n=0;n=i&&r<=o&&Y(t,e[n],e[n+1],e[n+2]);}}function R(e,t,i,o,s,n,r){let a=W(e);const l=0===s?q:X;let c,u,h=e.start;for(let d=0;di&&(u=l(a,f,g,m,y,i),r&&(a.start=h+c*u)):v>o?w=i&&(u=l(a,f,g,m,y,i),x=!0),w>o&&v<=o&&(u=l(a,f,g,m,y,o),x=!0),!n&&x&&(r&&(a.end=h+c*u),t.push(a),a=W(e)),r&&(h+=c);}let d=e.length-3;const f=e[d],g=e[d+1],p=0===s?f:g;p>=i&&p<=o&&Y(a,f,g,e[d+2]),d=a.length-3,n&&d>=3&&(a[d]!==a[0]||a[d+1]!==a[1])&&Y(a,a[0],a[1],a[2]),a.length&&t.push(a);}function W(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function J(e,t,i,o,s,n){for(const r of e)R(r,t,i,o,s,n,!1);}function Y(e,t,i,o){e.push(t,i,o);}function q(e,t,i,o,s,n){const r=(n-t)/(o-t);return Y(e,n,i+(s-i)*r,1),r}function X(e,t,i,o,s,n){const r=(n-i)/(s-i);return Y(e,t+(o-t)*r,n,1),r}function H(e,t){const i=[];for(let o=0;o0&&t.size<(s?r:o))return void(i.numPoints+=t.length/3);const a=[];for(let e=0;er)&&(i.numSimplified++,a.push(t[e],t[e+1])),i.numPoints++;s&&function(e,t){let i=0;for(let t=0,o=e.length,s=o-2;t0===t)for(let t=0,i=e.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");let o=function(e,t){const i=[];if("FeatureCollection"===e.type)for(let o=0;o1&&console.time("creation"),d=this.tiles[h]=U(e,t,i,o,l),this.tileCoords.push({z:t,x:i,y:o}),c)){c>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,i,o,d.numFeatures,d.numPoints,d.numSimplified),console.timeEnd("creation"));const e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++;}if(d.source=e,null==s){if(t===l.indexMaxZoom||d.numPoints<=l.indexMaxPoints)continue}else {if(t===l.maxZoom||t===s)continue;if(null!=s){const e=s-t;if(i!==n>>e||o!==r>>e)continue}}if(d.source=null,0===e.length)continue;c>1&&console.time("clipping");const f=.5*l.buffer/l.extent,g=.5-f,p=.5+f,m=1+f;let y=null,v=null,w=null,x=null,b=j(e,u,i-f,i+p,0,d.minX,d.maxX,l),S=j(e,u,i+g,i+m,0,d.minX,d.maxX,l);e=null,b&&(y=j(b,u,o-f,o+p,1,d.minY,d.maxY,l),v=j(b,u,o+g,o+m,1,d.minY,d.maxY,l),b=null),S&&(w=j(S,u,o-f,o+p,1,d.minY,d.maxY,l),x=j(S,u,o+g,o+m,1,d.minY,d.maxY,l),S=null),c>1&&console.timeEnd("clipping"),a.push(y||[],t+1,2*i,2*o),a.push(v||[],t+1,2*i,2*o+1),a.push(w||[],t+1,2*i+1,2*o),a.push(x||[],t+1,2*i+1,2*o+1);}}getTile(e,t,i){e=+e,t=+t,i=+i;const o=this.options,{extent:s,debug:n}=o;if(e<0||e>24)return null;const r=1<1&&console.log("drilling down to z%d-%d-%d",e,t,i);let l,c=e,u=t,h=i;for(;!l&&c>0;)c--,u>>=1,h>>=1,l=this.tiles[ie(c,u,h)];return l&&l.source?(n>1&&(console.log("found parent tile z%d-%d-%d",c,u,h),console.time("drilling down")),this.splitTile(l.source,c,u,h,e,t,i),n>1&&console.timeEnd("drilling down"),this.tiles[a]?B(this.tiles[a],s):null):null}}function ie(e,t,i){return 32*((1<{r.properties=e;const t={};for(const e of a)t[e]=o[e].evaluate(n,r);return t},t.reduce=(e,t)=>{r.properties=t;for(const t of a)n.accumulated=e[t],e[t]=s[t].evaluate(n,r);},t}(t)).load(i.features):function(e,t){return new te(e,t)}(i,t.geojsonVtOptions),this.loaded={};const s={data:i};if(o){const e=o.finish();e&&(s.resourceTiming={},s.resourceTiming[t.source]=JSON.parse(JSON.stringify(e)));}return s}catch(t){if(delete this._pendingRequest,e.cy(t))return {abandoned:!0};throw t}}))}getData(){return e._(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(e){const t=this.loaded;return t&&t[e.uid]?super.reloadTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){let o=yield this.loadGeoJSON(t,i);if(delete this._pendingRequest,"object"!=typeof o)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(u(o,!0),t.filter){const i=e.cT(t.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===i.result)throw new Error(i.value.map((e=>`${e.key}: ${e.message}`)).join(", "));const s=o.features.filter((e=>i.value.evaluate({zoom:0},e)));o={type:"FeatureCollection",features:s};}return o}))}loadGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){const{promoteId:o}=t;if(t.request){const s=yield e.j(t.request,i);return this._dataUpdateable=e.cV(s.data,o)?e.cU(s.data,o):void 0,s.data}if("string"==typeof t.data)try{const i=JSON.parse(t.data);return this._dataUpdateable=e.cV(i,o)?e.cU(i,o):void 0,i}catch(e){throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}if(!t.dataDiff)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${t.source}`);return e.cW(this._dataUpdateable,t.dataDiff,o),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(t){return e._(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset)}}class se{constructor(t){this.self=t,this.actor=new e.J(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=new Map,this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.cA,this.self.removeProtocol=e.cB,this.self.registerRTLTextPlugin=t=>{e.cX.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,i)=>e._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(t,i.source).removeTile(i);})))),this.actor.registerMessageHandler("GCEZ",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterExpansionZoom(i)})))),this.actor.registerMessageHandler("GCC",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterChildren(i)})))),this.actor.registerMessageHandler("GCL",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterLeaves(i)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("GD",((e,t)=>this._getWorkerSource(e,t.type,t.source).getData())),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,i)=>e._(this,void 0,void 0,(function*(){if(!this.workerSources[t]||!this.workerSources[t][i.type]||!this.workerSources[t][i.type][i.source])return;const e=this.workerSources[t][i.type][i.source];delete this.workerSources[t][i.type][i.source],void 0!==e.removeSource&&e.removeSource(i);})))),this.actor.registerMessageHandler("RM",(t=>e._(this,void 0,void 0,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t],this.globalStates.delete(t);})))),this.actor.registerMessageHandler("SR",((t,i)=>e._(this,void 0,void 0,(function*(){this.referrer=i;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,i)=>e._(this,void 0,void 0,(function*(){this.self.importScripts(i);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).update(i.layers,i.removedIds,this._getGlobalState(t));})))),this.actor.registerMessageHandler("UGS",((t,i)=>e._(this,void 0,void 0,(function*(){const e=this._getGlobalState(t);for(const t in i)e[t]=i[t];})))),this.actor.registerMessageHandler("SL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).replace(i,this._getGlobalState(t));}))));}_getGlobalState(e){let t=this.globalStates.get(e);return t||(t={},this.globalStates.set(e,t)),t}_setImages(t,i){return e._(this,void 0,void 0,(function*(){this.availableImages[t]=i;for(const e in this.workerSources[t]){const o=this.workerSources[t][e];for(const e in o)o[e].availableImages=i;}}))}_syncRTLPluginState(t,i){return e._(this,void 0,void 0,(function*(){return yield e.cX.syncState(i,this.self.importScripts)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(e){let i=this.layerIndexes[e];return i||(i=this.layerIndexes[e]=new t),i}_getWorkerSource(e,t,i){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][i]){const o={sendAsync:(t,i)=>(t.targetMapId=e,this.actor.sendAsync(t,i))};switch(t){case "vector":this.workerSources[e][t][i]=new n(o,this._getLayerIndex(e),this._getAvailableImages(e));break;case "geojson":this.workerSources[e][t][i]=new oe(o,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][i]=new this.externalWorkerSourceTypes[t](o,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][t][i]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new r),this.demWorkerSources[e][t]}}return e.i(self)&&(self.worker=new se(self)),se})); + +define("index",["exports","./shared"],(function(e,t){"use strict";var i="5.7.2";function o(){var e=new t.A(4);return t.A!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}let r,a;const s={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frame(e,i,o){const r=requestAnimationFrame((e=>{a(),i(e);})),{unsubscribe:a}=t.s(e.signal,"abort",(()=>{a(),cancelAnimationFrame(r),o(t.c());}),!1);},frameAsync(e){return new Promise(((t,i)=>{this.frame(e,t,i);}))},getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(r||(r=document.createElement("a")),r.href=e,r.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==a&&(a=matchMedia("(prefers-reduced-motion: reduce)")),a.matches)}};class n{static testProp(e){if(!n.docStyle)return e[0];for(let t=0;t{window.removeEventListener("click",n.suppressClickInternal,!0);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,o){const r=i.boundingClientRect;return new t.P((o.clientX-r.left)/i.x-e.clientLeft,(o.clientY-r.top)/i.y-e.clientTop)}static mousePos(e,t){const i=n.getScale(e);return n.getPoint(e,i,t)}static touchPos(e,t){const i=[],o=n.getScale(e);for(let r=0;r{c&&_(c),c=null,d=!0;},h.onerror=()=>{u=!0,c=null;},h.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(e){let i,o,r,a;e.resetRequestQueue=()=>{i=[],o=0,r=0,a={};},e.addThrottleControl=e=>{const t=r++;return a[t]=e,t},e.removeThrottleControl=e=>{delete a[e],n();},e.getImage=(e,o,r=!0)=>new Promise(((a,s)=>{l.supported&&(e.headers||(e.headers={}),e.headers.accept="image/webp,*/*"),t.e(e,{type:"image"}),i.push({abortController:o,requestParameters:e,supportImageRefresh:r,state:"queued",onError:e=>{s(e);},onSuccess:e=>{a(e);}}),n();}));const s=e=>t._(this,void 0,void 0,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:r,onError:a,onSuccess:s,abortController:l}=e,h=!1===r&&!t.i(self)&&!t.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),!0));o++;const u=h?c(i,l):t.m(i,l);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.b(i.data)?s(i):i.data&&s({data:yield(d=i.data,"function"==typeof createImageBitmap?t.f(d):t.h(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,a(t);}finally{o--,n();}var d;})),n=()=>{const e=(()=>{for(const e of Object.keys(a))if(a[e]())return !0;return !1})()?t.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=o;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:s(e);}},c=(e,i)=>new Promise(((o,r)=>{const a=new Image,s=e.url,n=e.credentials;n&&"include"===n?a.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.d(s))&&(a.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{a.src="",r(t.c());})),a.fetchPriority="high",a.onload=()=>{a.onerror=a.onload=null,o({data:a});},a.onerror=()=>{a.onerror=a.onload=null,i.signal.aborted||r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));},a.src=s;}));}(p||(p={})),p.resetRequestQueue();class m{constructor(e){this._transformRequestFn=null!=e?e:null;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}function f(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:o,url:r}of e){const e=`${o}${r}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:o,url:r}));}}return t}function g(e,t,i){try{const o=new URL(e);return o.pathname+=`${t}${i}`,o.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}function v(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class b extends t.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.R({width:1,height:1}),this.dirty=!0;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.R({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let o=!0;const r=i.data||i.spriteData;return this._validateStretch(i.stretchX,r&&r.width)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchX" value`))),o=!1),this._validateStretch(i.stretchY,r&&r.height)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchY" value`))),o=!1),this._validateContent(i.content,i)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "content" value`))),o=!1),o}_validateStretch(e,t){if(!e)return !0;let i=0;for(const o of e){if(o[0]{let o=!0;if(!this.isLoaded())for(const t of e)this.images[t]||(o=!1);this.isLoaded()||o?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const o of e){let e=this.getImage(o);e||(this.fire(new t.l("styleimagemissing",{id:o})),e=this.getImage(o)),e?i[o]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.w(`Image "${o}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);}return i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],o=this.getImage(e);if(!o)return null;if(i&&i.position.version===o.version)return i.position;if(i)i.position.version=o.version;else {const i={w:o.data.width+2,h:o.data.height+2,x:0,y:0},r=new t.I(i,o);this.patterns[e]={bin:i,position:r};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const i=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new t.T(e,this.atlasImage,i.RGBA),this.atlasTexture.bind(i.LINEAR,i.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:o}=t.p(e),r=this.atlasImage;r.resize({width:i||1,height:o||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],o=i.x+1,a=i.y+1,s=this.getImage(e).data,n=s.width,l=s.height;t.R.copy(s,r,{x:0,y:0},{x:o,y:a},{width:n,height:l}),t.R.copy(s,r,{x:0,y:l-1},{x:o,y:a-1},{width:n,height:1}),t.R.copy(s,r,{x:0,y:0},{x:o,y:a+l},{width:n,height:1}),t.R.copy(s,r,{x:n-1,y:0},{x:o-1,y:a},{width:1,height:l}),t.R.copy(s,r,{x:0,y:0},{x:o+n,y:a},{width:1,height:l});}this.dirty=!0;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=!0;const e=this.getImage(i);e||t.w(`Image with ID: "${i}" was not found`),v(e)&&this.updateImage(i,e);}}}const x=1e20;function y(e,t,i,o,r,a,s,n,l){for(let c=t;c-1);l++,a[l]=n,s[l]=c,s[l+1]=x;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(t.ranges[r])return {stack:e,id:i,glyph:o};if(!this.url)throw new Error("glyphsUrl is not set");if(!t.requests[r]){const i=T.loadGlyphRange(e,r,this.url,this.requestManager);t.requests[r]=i;}const a=yield t.requests[r];for(const e in a)this._doesCharSupportLocalGlyph(+e)||(t.glyphs[+e]=a[+e]);return t.ranges[r]=!0,{stack:e,id:i,glyph:a[i]||null}}))}_doesCharSupportLocalGlyph(e){return !!this.localIdeographFontFamily&&(/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(e))||t.u["CJK Unified Ideographs"](e)||t.u["Hangul Syllables"](e)||t.u.Hiragana(e)||t.u.Katakana(e)||t.u["CJK Symbols and Punctuation"](e)||t.u["Halfwidth and Fullwidth Forms"](e))}_tinySDF(e,i,o){const r=this.localIdeographFontFamily;if(!r)return;if(!this._doesCharSupportLocalGlyph(o))return;let a=e.tinySDF;if(!a){let t="400";/bold/i.test(i)?t="900":/medium/i.test(i)?t="500":/light/i.test(i)&&(t="200"),a=e.tinySDF=new T.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,lang:this.lang,fontFamily:r,fontWeight:t});}const s=a.draw(String.fromCharCode(o));return {id:o,bitmap:new t.q({width:s.width||60,height:s.height||60},s.data),metrics:{width:s.glyphWidth/2||24,height:s.glyphHeight/2||24,left:s.glyphLeft/2+.5||0,top:s.glyphTop/2-27.5||-8,advance:s.glyphAdvance/2||24,isDoubleResolution:!0}}}}T.loadGlyphRange=function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=256*i,s=a+255,n=r.transformRequest(o.replace("{fontstack}",e).replace("{range}",`${a}-${s}`),"Glyphs"),l=yield t.n(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${a}-${s}`);const c={};for(const e of t.o(l.data))c[e.id]=e;return c}))},T.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:o=.25,fontFamily:r="sans-serif",fontWeight:a="normal",fontStyle:s="normal",lang:n=null}={}){this.buffer=t,this.cutoff=o,this.radius=i,this.lang=n;const l=this.size=e+4*t,c=this._createCanvas(l),h=this.ctx=c.getContext("2d",{willReadFrequently:!0});h.font=`${s} ${a} ${e}px ${r}`,h.textBaseline="alphabetic",h.textAlign="left",h.fillStyle="black",this.gridOuter=new Float64Array(l*l),this.gridInner=new Float64Array(l*l),this.f=new Float64Array(l),this.z=new Float64Array(l+1),this.v=new Uint16Array(l);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:o,actualBoundingBoxLeft:r,actualBoundingBoxRight:a}=this.ctx.measureText(e),s=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(a-r))),l=Math.min(this.size-this.buffer,s+Math.ceil(o)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:s,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;this.lang&&(p.lang=this.lang),p.clearRect(m,m,n,l),p.fillText(e,m,m+s);const v=p.getImageData(m,m,n,l);g.fill(x,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[o]=e<0?e*e:0;}}y(g,0,0,c,h,c,this.f,this.v,this.z),y(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(s=e[++a]);const l=Math.abs(n-s.left),c=Math.abs(n-s.right),h=Math.min(l,c);let u;const d=t/i*(o+1);if(s.isDash){const e=o-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=o-Math.sqrt(h*h+d*d);this.data[r+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],o=e[t+1];i.zeroLength?e.splice(t,1):o&&o.isDash===i.isDash&&(o.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const o=this.width*this.nextRow;let r=0,a=e[r];for(let t=0;t1&&(a=e[++r]);const i=Math.abs(t-a.left),s=Math.abs(t-a.right),n=Math.min(i,s);this.data[o+t]=Math.max(0,Math.min(255,(a.isDash?n:-n)+128));}}addDash(e,i){const o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.w("LineAtlas out of space"),null;let a=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[R]}numActive(){return Object.keys(this.active).length}}const D=Math.floor(s.hardwareConcurrency/2);let A,L;function k(){return A||(A=new z),A}z.workerCount=t.H(globalThis)?Math.max(Math.min(D,3),1):1;class F{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const o=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}}function B(){return L||(L=new F(k(),t.K),L.registerMessageHandler("GR",((e,i,o)=>t.m(i,o)))),L}function O(e,i){const o=t.L();return t.M(o,o,[1,1,0]),t.N(o,o,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.O(o,o,e.calculatePosMatrix(i.toUnwrapped())):o}function j(e,t,i,o,r,a,s){var n;const l=function(e,t,i){if(e)for(const o of e){const e=t[o];if(e&&e.source===i&&"fill-extrusion"===e.type)return !0}else for(const e in t){const o=t[e];if(o.source===i&&"fill-extrusion"===o.type)return !0}return !1}(null!==(n=null==r?void 0:r.layers)&&void 0!==n?n:null,t,e.id),c=a.maxPitchScaleFactor(),h=e.tilesIn(o,c,l);h.sort(N);const u=[];for(const o of h)u.push({wrappedTileID:o.tileID.wrapped().key,queryResults:o.tile.queryRenderedFeatures(t,i,e._state,o.queryGeometry,o.cameraQueryGeometry,o.scale,r,a,c,O(e.transform,o.tileID),s?(e,t)=>s(o.tileID,e,t):void 0)});return function(e,t){for(const i in e)for(const o of e[i])U(o,t);return e}(function(e){const t={},i={};for(const o of e){const e=o.queryResults,r=o.wrappedTileID,a=i[r]=i[r]||{};for(const i in e){const o=e[i],r=a[i]=a[i]||{},s=t[i]=t[i]||[];for(const e of o)r[e.featureIndex]||(r[e.featureIndex]=!0,s.push(e));}}return t}(u),e)}function N(e,t){const i=e.tileID,o=t.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}function U(e,t){const i=e.feature,o=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=o;}function Z(e,i,o){return t._(this,void 0,void 0,(function*(){let r=e;if(e.url?r=(yield t.j(i.transformRequest(e.url,"Source"),o)).data:yield s.frameAsync(o),!r)return null;const a=t.Q(t.e(r,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in r&&r.vector_layers&&(a.vectorLayerIds=r.vector_layers.map((e=>e.id))),a}))}class G{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}extend(e){const i=this._sw,o=this._ne;let r,a;if(e instanceof t.S)r=e,a=e;else {if(!(e instanceof G))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(G.convert(e)):this.extend(t.S.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.S.convert(e)):this;if(r=e._sw,a=e._ne,!r||!a)return this}return i||o?(i.lng=Math.min(r.lng,i.lng),i.lat=Math.min(r.lat,i.lat),o.lng=Math.max(a.lng,o.lng),o.lat=Math.max(a.lat,o.lat)):(this._sw=new t.S(r.lng,r.lat),this._ne=new t.S(a.lng,a.lat)),this}getCenter(){return new t.S((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new t.S(this.getWest(),this.getNorth())}getSouthEast(){return new t.S(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(e){const{lng:i,lat:o}=t.S.convert(e);let r=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(r=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=o&&o<=this._ne.lat&&r}static convert(e){return e instanceof G?e:e?new G(e):e}static fromLngLat(e,i=0){const o=360*i/40075017,r=o/Math.cos(Math.PI/180*e.lat);return new G(new t.S(e.lng-r,e.lat-o),new t.S(e.lng+r,e.lat+o))}adjustAntiMeridian(){const e=new t.S(this._sw.lng,this._sw.lat),i=new t.S(this._ne.lng,this._ne.lat);return new G(e,e.lng>i.lng?new t.S(i.lng+360,i.lat):i)}}class V{constructor(e,t,i){this.bounds=G.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),o=Math.floor(t.V(this.bounds.getWest())*i),r=Math.floor(t.U(this.bounds.getNorth())*i),a=Math.ceil(t.V(this.bounds.getEast())*i),s=Math.ceil(t.U(this.bounds.getSouth())*i);return e.x>=o&&e.x=r&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.e({},this._options)}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};i.request.collectResourceTiming=this._collectResourceTiming;let o="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),o="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:o,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_afterTileLoadWorkerResponse(e,t){if(t&&t.resourceTiming&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return !1}}class q extends t.E{constructor(e,i,o,r){super(),this.id=e,this.dispatcher=o,this.setEventedParent(r),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.e({type:"raster"},i),t.e(this,t.Q(i,["url","scheme","tileSize"]));}load(){return t._(this,arguments,void 0,(function*(e=!1){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield Z(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,i&&(t.e(this,i),i.bounds&&(this.tileBounds=new V(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.l("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(!0);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.e({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const o=yield p.getImage(this.map._requestManager.transformRequest(i,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(o&&o.data){this.map._refreshExpiredTiles&&(o.cacheControl||o.expires)&&e.setExpiryData({cacheControl:o.cacheControl,expires:o.expires});const i=this.map.painter.context,r=i.gl,a=o.data;e.texture=this.map.painter.getTileTexture(a.width),e.texture?e.texture.update(a,{useMipmap:!0}):(e.texture=new t.T(i,a,r.RGBA,{useMipmap:!0}),e.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return !1}}class W extends q{constructor(e,i,o,r){super(e,i,o,r),this.type="raster-dem",this.maxzoom=22,this._options=t.e({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),o=this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield p.getImage(o,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const o=i.data;this.map._refreshExpiredTiles&&(i.cacheControl||i.expires)&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const r=t.b(o)&&t.W()?o:yield this.readImageNow(o),a={type:this.type,uid:e.uid,source:this.id,rawImageData:r,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!e.actor||"expired"===e.state){e.actor=this.dispatcher.getActor();const t=yield e.actor.sendAsync({type:"LDT",data:a});e.dem=t,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t._(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&t.X()){const i=e.width+2,o=e.height+2;try{return new t.R({width:i,height:o},yield t.Y(e,-1,-1,i,o))}catch(e){}}return s.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,o=Math.pow(2,i.z),r=(i.x-1+o)%o,a=0===i.x?e.wrap-1:e.wrap,s=(i.x+1+o)%o,n=i.x+1===o?e.wrap+1:e.wrap,l={};return l[new t.Z(e.overscaledZ,a,i.z,r,i.y).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y).key]={backfilled:!1},i.y>0&&(l[new t.Z(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y-1).key]={backfilled:!1}),i.y+1e.coordinates)).flat(1/0):e.coordinates.flat(1/0)}getBounds(){return t._(this,void 0,void 0,(function*(){const e=new G,t=yield this.getData();let i;switch(t.type){case "FeatureCollection":i=t.features.map((e=>this.getCoordinatesFromGeometry(e.geometry))).flat(1/0);break;case "Feature":i=this.getCoordinatesFromGeometry(t.geometry);break;default:i=this.getCoordinatesFromGeometry(t);}if(0==i.length)return e;for(let t=0;t0&&t.e(r,{resourceTiming:i}),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"metadata"}))),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"content"})));}catch(e){if(this._isUpdatingWorker=!1,this._removed)return void this.fire(new t.l("dataabort",{dataType:"source"}));this.fire(new t.k(e));}finally{(this._pendingWorkerUpdate.data||this._pendingWorkerUpdate.diff)&&this._updateWorkerData();}}))}loaded(){return !this._isUpdatingWorker&&void 0===this._pendingWorkerUpdate.data&&void 0===this._pendingWorkerUpdate.diff}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};e.abortController=new AbortController;const o=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(o,this.map.painter,"RT"===t);}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=!0;}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return !1}}class X extends t.E{constructor(e,t,i,o){super(),this.flippedWindingOrder=!1,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(o),this.options=t;}load(e){return t._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield p.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.a1.fromLngLat);var o;return this.tileID=function(e){const i=t.a2.fromPoints(e),o=i.width(),r=i.height(),a=Math.max(o,r),s=Math.max(0,Math.floor(-Math.log(a)/Math.LN2)),n=Math.pow(2,s);return new t.a4(s,Math.floor((i.minX+i.maxX)/2*n),Math.floor((i.minY+i.maxY)/2*n))}(i),this.terrainTileRanges=this._getOverlappingTileRanges(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((o=this.tileCoords)[1].x-o[0].x)*(o[2].y-o[0].y)-(o[1].y-o[0].y)*(o[2].x-o[0].x)<0,this.fire(new t.l("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new t.T(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t._(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return !1}_getOverlappingTileRanges(e){const{minX:i,minY:o,maxX:r,maxY:a}=t.a2.fromPoints(e),s={};for(let e=0;e<=t.a3;e++){const t=Math.pow(2,e),n=Math.floor(i*t),l=Math.floor(o*t),c=Math.floor(r*t),h=Math.floor(a*t);s[e]={minTileX:n,minTileY:l,maxTileX:c,maxTileY:h};}return s}}class K extends X{constructor(e,t,i,o){super(e,t,i,o),this.roundZoom=!0,this.type="video",this.options=t;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!1;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,"Source").url);try{const e=yield t.a5(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.k(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.k(new t.a6(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.T(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class Y extends X{constructor(e,i,o,r){super(e,i,o,r),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.k(new t.a6(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.k(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,o=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.T(i,this.canvas,o.RGBA,{premultiply:!0});let r=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=!0);}r&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return !0;return !1}}const Q={},J=e=>{switch(e){case "geojson":return H;case "image":return X;case "raster":return q;case "raster-dem":return W;case "vector":return $;case "video":return K;case "canvas":return Y}return Q[e]},ee="RTLPluginLoaded";class te extends t.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=B();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t._(this,arguments,void 0,(function*(e,t=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=s.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.l(ee));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let ie=null;function oe(){return ie||(ie=new te),ie}class re{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=e,this.uid=t.a7(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(e){const t=e+this.timeAdded;tt.getLayer(e))).filter(Boolean);if(0!==e.length){o.layers=e,o.stateDependentLayerIds&&(o.stateDependentLayers=o.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=o;}}return i}(e.buckets,null==i?void 0:i.style),this.hasSymbolBuckets=!1;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9){if(this.hasSymbolBuckets=!0,!o)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9&&i.hasRTLText){this.hasRTLText=!0,oe().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.a8;}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const i=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new t.T(e,this.imageAtlas.image,i.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new t.T(e,this.glyphAtlasImage,i.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,o,r,a,s,n,l,c,h){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:o,cameraQueryGeometry:r,scale:a,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:s,queryPadding:this.queryPadding*l,getElevation:h},e,t,i):{}}querySourceFeatures(e,i){const o=this.latestFeatureIndex;if(!o||!o.rawTileData)return;const r=o.loadVTLayers(),a=i&&i.sourceLayer?i.sourceLayer:"",s=r._geojsonTileLayer||r[a];if(!s)return;const n=t.aa(null==i?void 0:i.filter,null==i?void 0:i.globalState),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=!1;else if(i)if(this.expirationTime{this.remove(e,r);}),i)),this.data[o].push(r),this.order.push(o),this.order.length>this.max){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}has(e){return e.wrapped().key in this.data}getAndRemove(e){return this.has(e)?this._getAndRemoveByKey(e.wrapped().key):null}_getAndRemoveByKey(e){const t=this.data[e].shift();return t.timeout&&clearTimeout(t.timeout),0===this.data[e].length&&delete this.data[e],this.order.splice(this.order.indexOf(e),1),t.value}getByKey(e){const t=this.data[e];return t?t[0].value:null}get(e){return this.has(e)?this.data[e.wrapped().key][0].value:null}remove(e,t){if(!this.has(e))return this;const i=e.wrapped().key,o=void 0===t?0:this.data[i].indexOf(t),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(e){for(this.max=e;this.order.length>this.max;){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}filter(e){const t=[];for(const i in this.data)for(const o of this.data[i])e(o.value)||t.push(o);for(const e of t)this.remove(e.value.tileID,e);}}class se{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(e,i,o){const r=String(i);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][r]=this.stateChanges[e][r]||{},t.e(this.stateChanges[e][r],o),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==r&&(this.deletedStates[e][t]=null);}else if(this.deletedStates[e]&&null===this.deletedStates[e][r]){this.deletedStates[e][r]={};for(const t in this.state[e][r])o[t]||(this.deletedStates[e][r][t]=null);}else for(const t in o)this.deletedStates[e]&&this.deletedStates[e][r]&&null===this.deletedStates[e][r][t]&&delete this.deletedStates[e][r][t];}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const o=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&void 0!==t)null!==this.deletedStates[e][o]&&(this.deletedStates[e][o]=this.deletedStates[e][o]||{},this.deletedStates[e][o][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][o])for(i in this.deletedStates[e][o]={},this.stateChanges[e][o])this.deletedStates[e][o][i]=null;else this.deletedStates[e][o]=null;else this.deletedStates[e]=null;}getState(e,i){const o=String(i),r=t.e({},(this.state[e]||{})[o],(this.stateChanges[e]||{})[o]);if(null===this.deletedStates[e])return {};if(this.deletedStates[e]){const t=this.deletedStates[e][i];if(null===t)return {};for(const e in t)delete r[e];}return r}initializeTileState(e,t){e.setFeatureState(this.state,t);}coalesceChanges(e,i){const o={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const i={};for(const o in this.stateChanges[e])this.state[e][o]||(this.state[e][o]={}),t.e(this.state[e][o],this.stateChanges[e][o]),i[o]=this.state[e][o];o[e]=i;}for(const e in this.deletedStates){this.state[e]=this.state[e]||{};const i={};if(null===this.deletedStates[e])for(const t in this.state[e])i[t]={},this.state[e][t]={};else for(const t in this.deletedStates[e]){if(null===this.deletedStates[e][t])this.state[e][t]={};else for(const i of Object.keys(this.deletedStates[e][t]))delete this.state[e][t][i];i[t]=this.state[e][t];}o[e]=o[e]||{},t.e(o[e],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(o).length)for(const t in e)e[t].setFeatureState(o,i);}}const ne=89.25;function le(e,i){const o=t.ah(i.lat,-t.ai,t.ai);return new t.P(t.V(i.lng)*e,t.U(o)*e)}function ce(e,i){return new t.a1(i.x/e,i.y/e).toLngLat()}function he(e){return e.cameraToCenterDistance*Math.min(.85*Math.tan(t.ae(90-e.pitch)),Math.tan(t.ae(ne-e.pitch)))}function ue(e,i){const o=e.canonical,r=i/t.af(o.z),a=o.x+Math.pow(2,o.z)*e.wrap,s=t.ag(new Float64Array(16));return t.M(s,s,[a*r,o.y*r,0]),t.N(s,s,[r/t.$,r/t.$,1]),s}function de(e,i,o,r,a){const s=t.a1.fromLngLat(e,i),n=a*t.aj(1,e.lat),l=n*Math.cos(t.ae(o)),c=Math.sqrt(n*n-l*l),h=c*Math.sin(t.ae(-r)),u=c*Math.cos(t.ae(-r));return new t.a1(s.x+h,s.y+u,s.z+l)}function _e(e,t,i){const o=t.intersectsFrustum(e);if(!i||0===o)return o;const r=t.intersectsPlane(i);return 0===r?0:2===o&&2===r?2:1}function pe(e,t,i){let o=0;const r=(i-t)/10;for(let a=0;a<10;a++)o+=r*Math.pow(Math.cos(t+(a+.5)/10*(i-t)),e);return o}function me(e,i){return function(o,r,a,s,n){const l=2*((e-1)/t.ak(Math.cos(t.ae(ne-n))/Math.cos(t.ae(ne)))-1),c=Math.acos(a/s),h=2*pe(l-1,0,t.ae(n/2)),u=Math.min(t.ae(ne),c+t.ae(n/2)),d=pe(l-1,Math.min(u,c-t.ae(n/2)),u),_=Math.atan(r/a),p=Math.hypot(r,a);let m=o;return m+=t.ak(s/p/Math.max(.5,Math.cos(t.ae(n/2)))),m+=l*t.ak(Math.cos(_))/2,m-=t.ak(Math.max(1,d/h/i))/2,m}}const fe=me(9.314,3);function ge(e,i){const o=(i.roundZoom?Math.round:Math.floor)(e.zoom+t.ak(e.tileSize/i.tileSize));return Math.max(0,o)}function ve(e,i){const o=e.getCameraFrustum(),r=e.getClippingPlane(),a=e.screenPointToMercatorCoordinate(e.getCameraPoint()),s=t.a1.fromLngLat(e.center,e.elevation);a.z=s.z+Math.cos(e.pitchInRadians)*e.cameraToCenterDistance/e.worldSize;const n=e.getCoveringTilesDetailsProvider(),l=n.allowVariableZoom(e,i),c=ge(e,i),h=i.minzoom||0,u=void 0!==i.maxzoom?i.maxzoom:e.maxZoom,d=Math.min(Math.max(0,c),u),_=Math.pow(2,d),p=[_*a.x,_*a.y,0],m=[_*s.x,_*s.y,0],f=Math.hypot(s.x-a.x,s.y-a.y),g=Math.abs(s.z-a.z),v=Math.hypot(f,g),b=e=>({zoom:0,x:0,y:0,wrap:e,fullyVisible:!1}),x=[],y=[];if(e.renderWorldCopies&&n.allowWorldCopies())for(let e=1;e<=3;e++)x.push(b(-e)),x.push(b(e));for(x.push(b(0));x.length>0;){const _=x.pop(),f=_.x,b=_.y;let w=_.fullyVisible;const T={x:f,y:b,z:_.zoom},P=n.getTileBoundingVolume(T,_.wrap,e.elevation,i);if(!w){const e=_e(o,P,r);if(0===e)continue;w=2===e;}const C=n.distanceToTile2d(a.x,a.y,T,P);let I=c;l&&(I=(i.calculateTileZoom||fe)(e.zoom+t.ak(e.tileSize/i.tileSize),C,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const M=Math.min(I,u);if(_.wrap=n.getWrap(s,T,_.wrap),_.zoom>=M){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return y.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}const be=t.a2.fromPoints([new t.P(0,0),new t.P(t.$,t.$)]);class xe extends t.E{constructor(e,t,i){super(),this.id=e,this.dispatcher=i,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=!1;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,o)=>{const r=new(J(t.type))(e,t,i,o);if(r.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${r.id}`);return r})(e,t,i,this),this._tiles={},this._cache=new ae(0,(e=>this._unloadTile(e))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new se,this._didEmitContent=!1,this._updated=!1;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e);}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return !0;if(!this._updated)return !1;for(const e in this._tiles){const t=this._tiles[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}return !0}getSource(){return this._source}pause(){this._paused=!0;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,o){return t._(this,void 0,void 0,(function*(){try{yield this._source.loadTile(e),this._tileLoaded(e,i,o);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.k(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.l("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const t in this._tiles){const i=this._tiles[t];i.upload(e),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(ye).map((e=>e.key))}getRenderableIds(e){const i=[];for(const t in this._tiles)this._isIdRenderable(t,e)&&i.push(this._tiles[t]);return e?i.sort(((e,i)=>{const o=e.tileID,r=i.tileID,a=new t.P(o.canonical.x,o.canonical.y)._rotate(-this.transform.bearingInRadians),s=new t.P(r.canonical.x,r.canonical.y)._rotate(-this.transform.bearingInRadians);return o.overscaledZ-r.overscaledZ||s.y-a.y||s.x-a.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(ye).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return !!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())}reload(e){if(this._paused)this._shouldReloadOnResume=!0;else {this._cache.reset();for(const t in this._tiles)e?this._reloadTile(t,"expired"):"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading");}}_reloadTile(e,i){return t._(this,void 0,void 0,(function*(){const t=this._tiles[e];t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,o){e.timeAdded=s.now(),"expired"===o&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.l("data",{dataType:"source",tile:e,coord:e.tileID}));}_backfillDEM(e){const t=this.getRenderableIds();for(let o=0;o1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,o),e.neighboringTiles&&e.neighboringTiles[a]&&(e.neighboringTiles[a].backfilled=!0)));}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,o){for(const r in this._tiles){let a=this._tiles[r];if(o[r]||!a.hasData()||a.tileID.overscaledZ<=t||a.tileID.overscaledZ>i)continue;let s=a.tileID;for(;a&&a.tileID.overscaledZ>t+1;){const e=a.tileID.scaledTo(a.tileID.overscaledZ-1);a=this._tiles[e.key],a&&a.hasData()&&(s=e);}let n=s;for(;n.overscaledZ>t;)if(n=n.scaledTo(n.overscaledZ-1),e[n.key]||e[n.canonical.key]){o[s.key]=s;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),o=this._getLoadedTile(t);if(o)return o}}findLoadedSibling(e){return this._getLoadedTile(e)}_getLoadedTile(e){const t=this._tiles[e.key];return t&&t.hasData()?t:this._cache.getByKey(e.wrapped().key)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,o=Math.ceil(e.height/this._source.tileSize)+1,r=Math.floor(i*o*(null===this._maxTileCacheZoomLevels?t.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),a="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(a);}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e={};for(const i in this._tiles){const o=this._tiles[i];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),e[o.tileID.key]=o;}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(e,this._tiles[e]);}}_updateCoveredAndRetainedTiles(e,t,i,o,r,a){const n={},l={},c=Object.keys(e),h=s.now();for(const i of c){const o=e[i],r=this._tiles[i];if(!r||0!==r.fadeEndTime&&r.fadeEndTime<=h)continue;const a=this.findLoadedParent(o,t),s=this.findLoadedSibling(o),c=a||s||null;c&&(this._addTile(c.tileID),n[c.tileID.key]=c.tileID),l[i]=o;}this._retainLoadedChildren(l,o,i,e);for(const t in n)e[t]||(this._coveredTiles[t]=!0,e[t]=n[t]);if(a){const t={},i={};for(const e of r)this._tiles[e.key].hasData()?t[e.key]=e:i[e.key]=e;for(const o in i){const r=i[o].children(this._source.maxzoom);this._tiles[r[0].key]&&this._tiles[r[1].key]&&this._tiles[r[2].key]&&this._tiles[r[3].key]&&(t[r[0].key]=e[r[0].key]=r[0],t[r[1].key]=e[r[1].key]=r[1],t[r[2].key]=e[r[2].key]=r[2],t[r[3].key]=e[r[3].key]=r[3],delete i[o]);}for(const o in i){const r=i[o],a=this.findLoadedParent(r,this._source.minzoom),s=this.findLoadedSibling(r),n=a||s||null;if(n){t[n.tileID.key]=e[n.tileID.key]=n.tileID;for(const e in t)t[e].isChildOf(n.tileID)&&delete t[e];}}for(const e in this._tiles)t[e]||(this._coveredTiles[e]=!0);}}update(e,i){if(!this._sourceLoaded||this._paused)return;let o;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?o=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.Z(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(o=ve(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(o=o.filter((e=>this._source.hasTile(e))))):o=[];const r=ge(e,this._source),a=Math.max(r-xe.maxOverzooming,this._source.minzoom),s=Math.max(r+xe.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const e={};for(const t of o)if(t.canonical.z>this._source.minzoom){const i=t.scaledTo(t.canonical.z-1);e[i.key]=i;const o=t.scaledTo(Math.max(this._source.minzoom,Math.min(t.canonical.z,5)));e[o.key]=o;}o=o.concat(Object.values(e));}const n=0===o.length&&!this._updated&&this._didEmitContent;this._updated=!0,n&&this.fire(new t.l("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(o,r);we(this._source.type)&&this._updateCoveredAndRetainedTiles(l,a,s,r,o,i);for(const e in l)this._tiles[e].clearFadeHold();const c=t.am(this._tiles,l);for(const e of c){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const o={},r={},a=Math.max(t-xe.maxOverzooming,this._source.minzoom),s=Math.max(t+xe.maxUnderzooming,this._source.minzoom),n={};for(const i of e){const e=this._addTile(i);o[i.key]=i,e.hasData()||tthis._source.maxzoom){const e=s.children(this._source.maxzoom)[0],t=this.getTile(e);if(t&&t.hasData()){o[e.key]=e;continue}}else {const e=s.children(this._source.maxzoom);if(4===e.length&&o[e[0].key]&&o[e[1].key]&&o[e[2].key]&&o[e[3].key])continue;if(1===e.length&&o[e[0].key])continue}let n=e.wasRequested();for(let t=s.overscaledZ-1;t>=a;--t){const a=s.scaledTo(t);if(r[a.key])break;if(r[a.key]=!0,e=this.getTile(a),!e&&n&&(e=this._addTile(a)),e){const t=e.hasData();if((t||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||n)&&(o[a.key]=a),n=e.wasRequested(),t)break}}}return o}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,o=this._tiles[e].tileID;for(;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}t.push(o.key);const e=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;o=e;}for(const e of t)this._loadedParentTiles[e]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const e in this._tiles){const t=this._tiles[e].tileID,i=this._getLoadedTile(t);this._loadedSiblingTiles[t.key]=i;}}_addTile(e){let i=this._tiles[e.key];if(i)return i;i=this._cache.getAndRemove(e),i&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));const o=i;return i||(i=new re(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._tiles[e.key]=i,o||this._source.fire(new t.l("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}refreshTiles(e){for(const t in this._tiles)(this._isIdRenderable(t)||"errored"==this._tiles[t].state)&&e.some((e=>e.equals(this._tiles[t].tileID.canonical)))&&this._reloadTile(t,"expired");}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=!0,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){const t=e.sourceDataType;"source"===e.dataType&&"metadata"===t&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===t&&(this.reload(e.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0);}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e in this._tiles)this._removeTile(e);this._cache.reset();}tilesIn(e,i,o){const r=[],a=this.transform;if(!a)return r;const s=a.getCoveringTilesDetailsProvider().allowWorldCopies(),n=o?a.getCameraQueryGeometry(e):e,l=e=>a.screenPointToMercatorCoordinate(e,this.terrain),c=this.transformBbox(e,l,!s),h=this.transformBbox(n,l,!s),u=this.getIds(),d=t.a2.fromPoints(h);for(let e=0;ee.getTilePoint(new t.a1(i.x,i.y))));if(i.expandBy(_),i.intersects(be)){const t=c.map((t=>e.getTilePoint(t))),i=h.map((t=>e.getTilePoint(t)));r.push({tile:o,tileID:s?e:e.unwrapTo(0),queryGeometry:t,cameraQueryGeometry:i,scale:l});}}}return r}transformBbox(e,i,o){let r=e.map(i);if(o){const o=t.a2.fromPoints(e);o.shrinkBy(.001*Math.min(o.width(),o.height()));const a=o.map(i);t.a2.fromPoints(r).covers(a)||(r=r.map((e=>e.x>.5?new t.a1(e.x-1,e.y,e.z):e)));}return r}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._tiles[e].tileID));return this.transform&&this.transform.populateCache(t),t}hasTransition(){if(this._source.hasTransition())return !0;if(we(this._source.type)){const e=s.now();for(const t in this._tiles)if(this._tiles[t].fadeEndTime>=e)return !0}return !1}setFeatureState(e,t,i){this._state.updateState(e=e||"_geojsonTileLayer",t,i);}removeFeatureState(e,t,i){this._state.removeFeatureState(e=e||"_geojsonTileLayer",t,i);}getFeatureState(e,t){return this._state.getState(e=e||"_geojsonTileLayer",t)}setDependencies(e,t,i){const o=this._tiles[e];o&&o.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)));}}function ye(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),o=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||o-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function we(e){return "raster"===e||"image"===e||"video"===e}xe.maxOverzooming=10,xe.maxUnderzooming=3;class Te{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(r-s)/n:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))}}function Pe(e,t){let i=!0;return "always"===e||"never"!==e&&"never"!==t||(i=!1),i}class Ce{constructor(e,t,i){const o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||o<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=o){if(r)return [{key:null,x1:e,y1:t,x2:i,y2:o}];for(let e=0;e0}hitTestCircle(e,t,i,o,r){const a=e-i,s=e+i,n=t-i,l=t+i;if(s<0||a>this.width||l<0||n>this.height)return !1;const c=[];return this._forEachCell(a,n,s,l,this._queryCellCircle,c,{hitTest:!0,overlapMode:o,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},r),c.length>0}_queryCell(e,t,i,o,r,a,s,n){const{seenUids:l,hitTest:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const r=this.bboxes;for(const s of u)if(!l.box[s]){l.box[s]=!0;const u=4*s,d=this.boxKeys[s];if(e<=r[u+2]&&t<=r[u+3]&&i>=r[u+0]&&o>=r[u+1]&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))&&(a.push({key:d,x1:r[u],y1:r[u+1],x2:r[u+2],y2:r[u+3]}),c))return !0}}const d=this.circleCells[r];if(null!==d){const r=this.circles;for(const s of d)if(!l.circle[s]){l.circle[s]=!0;const u=3*s,d=this.circleKeys[s];if(this._circleAndRectCollide(r[u],r[u+1],r[u+2],e,t,i,o)&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))){const e=r[u],t=r[u+1],i=r[u+2];if(a.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return !0}}}return !1}_queryCellCircle(e,t,i,o,r,a,s,n){const{circle:l,seenUids:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=!0;const i=4*t,o=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}const d=this.circleCells[r];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=!0;const i=3*t,o=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}}_forEachCell(e,t,i,o,r,a,s,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(o);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(r.call(this,e,t,i,o,this.xCellCount*l+d,a,s,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,o,r,a){const s=o-e,n=r-t,l=i+a;return l*l>s*s+n*n}_circleAndRectCollide(e,t,i,o,r,a,s){const n=(a-o)/2,l=Math.abs(e-(o+n));if(l>n+i)return !1;const c=(s-r)/2,h=Math.abs(t-(r+c));if(h>c+i)return !1;if(l<=n||h<=c)return !0;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function Ie(e,i,r){const a=t.L();if(!e){const{vecSouth:e,vecEast:t}=Se(i),r=o();r[0]=t[0],r[1]=t[1],r[2]=e[0],r[3]=e[1],s=r,(d=(l=(n=r)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(s[0]=u*(d=1/d),s[1]=-c*d,s[2]=-h*d,s[3]=l*d),a[0]=r[0],a[1]=r[1],a[4]=r[2],a[5]=r[3];}var s,n,l,c,h,u,d;return t.N(a,a,[1/r,1/r,1]),a}function Me(e,i,o,r){if(e){const e=t.L();if(!i){const{vecSouth:t,vecEast:i}=Se(o);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.N(e,e,[r,r,1]),e}return o.pixelsToClipSpaceMatrix}function Se(e){const i=Math.cos(e.rollInRadians),o=Math.sin(e.rollInRadians),r=Math.cos(e.pitchInRadians),a=Math.cos(e.bearingInRadians),s=Math.sin(e.bearingInRadians),n=t.ar();n[0]=-a*r*o-s*i,n[1]=-s*r*o+a*i;const l=t.as(n);l<1e-9?t.at(n):t.au(n,n,1/l);const c=t.ar();c[0]=a*r*i-s*o,c[1]=s*r*i+a*o;const h=t.as(c);return h<1e-9?t.at(c):t.au(c,c,1/h),{vecEast:c,vecSouth:n}}function Ee(e,i,o,r){let a;r?(a=[e,i,r(e,i),1],t.aw(a,a,o)):(a=[e,i,0,1],qe(a,a,o));const s=a[3];return {point:new t.P(a[0]/s,a[1]/s),signedDistanceFromCamera:s,isOccluded:!1}}function Re(e,t){return .5+e/t*.5}function ze(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function De(e,i,o,r,a,s,n,l,c,h,u,d,_){const p=o?e.textSizeData:e.iconSizeData,m=t.an(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=o?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,b=o?e.text.placedSymbolArray:e.icon.placedSymbolArray,x=i.transform.width/i.transform.height;let y=!1;for(let o=0;oMath.abs(o.x-i.x)*r?{useVertical:!0}:(e===t.ao.vertical?i.yo.x)?{needsFlipping:!0}:null}function ke(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:o,symbol:r,fontSize:a,flip:s,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=a/24,_=r.lineOffsetX*d,p=r.lineOffsetY*d;let m;if(r.numGlyphs>1){const e=r.glyphStartIndex+r.numGlyphs,t=r.lineStartIndex,a=r.lineStartIndex+r.lineLength,c=Ae(d,l,_,p,s,r,u,i);if(!c)return {notEnoughRoom:!0};const f=je(c.first.point.x,c.first.point.y,i,o),g=je(c.last.point.x,c.last.point.y,i,o);if(n&&!s){const e=Le(r.writingMode,f,g,h);if(e)return e}m=[c.first];for(let o=r.glyphStartIndex+1;o0?n.point:Fe(i.tileAnchorPoint,s,e,1,i),c=je(e.x,e.y,i,o),u=je(l.x,l.y,i,o),d=Le(r.writingMode,c,u,h);if(d)return d}const e=Ge(d*l.getoffsetX(r.glyphStartIndex),_,p,s,r.segment,r.lineStartIndex,r.lineStartIndex+r.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:!0};m=[e];}for(const e of m)t.av(c,e.point,e.angle);return {}}function Fe(e,t,i,o,r){const a=e.add(e.sub(t)._unit()),s=Oe(a.x,a.y,r).point,n=i.sub(s);return i.add(n._mult(o/n.mag()))}function Be(e,i,o){const r=i.projectionCache;if(r.projections[e])return r.projections[e];const a=new t.P(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),s=Oe(a.x,a.y,i);if(s.signedDistanceFromCamera>0)return r.projections[e]=s.point,r.anyProjectionOccluded=r.anyProjectionOccluded||s.isOccluded,s.point;const n=e-o.direction;return Fe(0===o.distanceFromAnchor?i.tileAnchorPoint:new t.P(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),a,o.previousVertex,o.absOffsetX-o.distanceFromAnchor+1,i)}function Oe(e,t,i){const o=e+i.translation[0],r=t+i.translation[1];let a;return i.pitchWithMap?(a=Ee(o,r,i.pitchedLabelPlaneMatrix,i.getElevation),a.isOccluded=!1):(a=i.transform.projectTileCoordinates(o,r,i.unwrappedTileID,i.getElevation),a.point.x=(.5*a.point.x+.5)*i.width,a.point.y=(.5*-a.point.y+.5)*i.height),a}function je(e,i,o,r){if(o.pitchWithMap){const a=[e,i,0,1];return t.aw(a,a,r),o.transform.projectTileCoordinates(a[0]/a[3],a[1]/a[3],o.unwrappedTileID,o.getElevation).point}return {x:e/o.width*2-1,y:1-i/o.height*2}}function Ne(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function Ue(e,t,i){return e._unit()._perp()._mult(t*i)}function Ze(e,i,o,r,a,s,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=o.add(i);if(e+c.direction=a)return l.projectionCache.offsets[e]=h,h;const u=Be(e+c.direction,l,c),d=Ue(u.sub(o),n,c.direction),_=o.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.ax(s,h,_,p)||h,l.projectionCache.offsets[e]}function Ge(e,t,i,o,r,a,s,n,l){const c=o?e-t:e+t;let h=c>0?1:-1,u=0;o&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?a+r:a+r+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Oe(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,b=0;const x=Math.abs(c),y=[];let w;for(;v+b<=x;){if(_+=h,_=s)return null;v+=b,g=f,m=p;const e={absOffsetX:x,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=Be(_,n,e),0===i)y.push(g),w=f.sub(g);else {let t;const o=f.sub(g);t=0===o.mag()?Ue(Be(_+h,n,e).sub(f),i,h):Ue(o,i,h),m||(m=g.add(t)),p=Ze(_,t,f,a,s,m,i,n,e),y.push(m),w=p.sub(m);}b=w.mag();}const T=w._mult((x-v)/b)._add(m||g),P=u+Math.atan2(f.y-g.y,f.x-g.x);return y.push(T),{point:T,angle:l?P:0,path:y}}const Ve=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function $e(e,t){for(let i=0;i=1;e--)_.push(s.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=o.x&&i.x<=r.x&&e.y>=o.y&&i.y<=r.y?[_]:i.xr.x||i.yr.y?[]:t.ay([_],o.x,o.y,r.x,r.y);}for(const t of f){a.reset(t,.25*i);let o=0;o=a.length<=.5*i?1:Math.ceil(a.paddedLength/p)+1;for(let t=0;t{const t=Ee(e.x,e.y,o,i.getElevation),r=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return r.point.x=(.5*r.point.x+.5)*i.width,r.point.y=(.5*-r.point.y+.5)*i.height,r}))}(e,i);return function(e){let t=0,i=0,o=0,r=0;for(let a=0;ai&&(i=r,t=o));return e.slice(t,t+i)}(o)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[],o=new t.a2;for(const r of e){const e=new t.P(r.x+We,r.y+We);o.extend(e),i.push(e);}const{minX:r,minY:a,maxX:s,maxY:n}=o,l=this.grid.query(r,a,s,n).concat(this.ignoredGrid.query(r,a,s,n)),c={},h={};for(const e of l){const o=e.key;if(void 0===c[o.bucketInstanceId]&&(c[o.bucketInstanceId]={}),c[o.bucketInstanceId][o.featureIndex])continue;const r=[new t.P(e.x1,e.y1),new t.P(e.x2,e.y1),new t.P(e.x2,e.y2),new t.P(e.x1,e.y2)];t.az(i,r)&&(c[o.bucketInstanceId][o.featureIndex]=!0,void 0===h[o.bucketInstanceId]&&(h[o.bucketInstanceId]=[]),h[o.bucketInstanceId].push(o.featureIndex));}return h}insertCollisionBox(e,t,i,o,r,a){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,o,r,a){const s=i?this.ignoredGrid:this.grid,n={bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t};for(let t=0;t=this.screenRightBoundary||othis.screenBottomBoundary}isInsideGrid(e,t,i,o){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,r,c,u)));E=e.some((e=>!e.isOccluded)),S=e.map((e=>new t.P(e.x,e.y)));}else E=!0;return {box:t.aA(S),allPointsOccluded:!E}}}class Xe{constructor(e,t,i,o){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):o&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class Ke{constructor(e,t,i,o,r){this.text=new Xe(e?e.text:null,t,i,r),this.icon=new Xe(e?e.icon:null,t,o,r);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ye{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class Qe{constructor(e,t,i,o,r){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=r;}}class Je{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function et(e,i,o,r,a){const{horizontalAlign:s,verticalAlign:n}=t.aH(e);return new t.P(-(s-.5)*i+r[0]*a,-(n-.5)*o+r[1]*a)}class tt{constructor(e,t,i,o,r){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new He(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new Je(o),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=r,r&&(r.prevPlacement=void 0),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,o)=>t.getElevation(e,i,o):null}getBucketParts(e,i,o,r){const a=o.getBucket(i),s=o.latestFeatureIndex;if(!a||!s||i.id!==a.layerIds[0])return;const n=o.collisionBoxArray,l=a.layers[0].layout,c=a.layers[0].paint,h=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),u=o.tileSize/t.$,d=o.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.aC(o,1,this.transform.zoom),m=t.aD(this.collisionIndex.transform,o,c.get("text-translate"),c.get("text-translate-anchor")),f=t.aD(this.collisionIndex.transform,o,c.get("icon-translate"),c.get("icon-translate-anchor")),g=Ie(_,this.transform,p);this.retainedQueryData[a.bucketInstanceId]=new Qe(a.bucketInstanceId,s,a.sourceLayerIndex,a.index,o.tileID);const v={bucket:a,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:o.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.an(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(r)for(const t of a.sortKeyRanges){const{sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r}=t;e.push({sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v,b,x){const y=t.aE[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=et(y,o,r,w,a),P=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,s,f,u.predicate,b,T,x);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,s,g,u.predicate,b,T,x).placeable)&&P.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:o,height:r,anchor:y,textBoxScale:a,prevAnchor:e},this.markUsedJustification(p,y,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:P}}}placeLayerBucketPart(e,i,o){const{bucket:r,layout:a,translationText:s,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=a.get("text-optional"),f=a.get("icon-optional"),g=t.aF(a,"text-overlap","text-allow-overlap"),v="always"===g,b=t.aF(a,"icon-overlap","icon-allow-overlap"),x="always"===b,y="map"===a.get("text-rotation-alignment"),w="map"===a.get("text-pitch-alignment"),T="none"!==a.get("icon-text-fit"),P="viewport-y"===a.get("symbol-z-order"),C=v&&(x||!r.hasIconData()||f),I=x&&(v||!r.hasTextData()||m);!r.collisionArrays&&d&&r.deserializeCollisionBoxes(d);const M=this.retainedQueryData[r.bucketInstanceId].tileID,S=this._getTerrainElevationFunc(M),E=this.transform.getFastPathSimpleProjectionMatrix(M),R=(e,d,x)=>{var P,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new Ye(!1,!1,!1));let z=!1,D=!1,A=!0,L=null,k={box:null,placeable:!1,offscreen:null,occluded:!1},F={placeable:!1},B=null,O=null,j=null,N=0,U=0,Z=0;d.textFeatureIndex?N=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(N=e.featureIndex),d.verticalTextFeatureIndex&&(U=d.verticalTextFeatureIndex);const G=d.textBox;if(G){const i=i=>{let o=t.ao.horizontal;if(r.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,o=t,this.markUsedOrientation(r,o,e));}return o},a=(i,o)=>{if(r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of r.writingModes)if(e===t.ao.vertical?(k=o(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const o=(t,i)=>{const o=this.collisionIndex.placeCollisionBox(t,g,h,M,l,w,y,s,p.predicate,S,void 0,E);return o&&o.placeable&&(this.markUsedOrientation(r,i,e),this.placedOrientations[e.crossTileID]=i),o};a((()=>o(G,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?o(i,t.ao.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.aE[null===(R=null===(P=this.prevPlacement)||void 0===P?void 0:P.variableOffsets[e.crossTileID])||void 0===R?void 0:R.anchor];const m=(t,i,a)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===b?i:null;let x=null,P="never"===g?1:2,C="never";_&&P++;for(let i=0;im(G,d.iconBox,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.ao.vertical):{box:null,occluded:!0,offscreen:null}})),k&&(z=k.placeable,A=k.offscreen);const f=i(k&&k.placeable);if(!z&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(r,t.anchor,e,f));}}}if(B=k,z=B&&B.placeable,A=B&&B.offscreen,e.useRuntimeCollisionCircles){const i=r.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.ap(r.textSizeData,_,i),h=a.get("text-padding");O=this.collisionIndex.placeCollisionCircles(g,i,r.lineVertexArray,r.glyphOffsetArray,n,l,c,o,w,p.predicate,e.collisionCircleDiameter,h,s,S),O.circles.length&&O.collisionDetected&&!o&&t.w("Collisions detected, but collision boxes are not shown"),z=v||O.circles.length>0&&!O.collisionDetected,A=A&&O.offscreen;}if(d.iconFeatureIndex&&(Z=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,b,h,M,l,w,y,n,p.predicate,S,T&&L?L:void 0,E);F&&F.placeable&&d.verticalIconBox?(j=e(d.verticalIconBox),D=j.placeable):(j=e(d.iconBox),D=j.placeable),A=A&&j.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,$=f||0===e.numIconVertices;V||$?$?V||(D=D&&z):z=D&&z:D=z=D&&z;const q=D&&j.placeable;if(z&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,a.get("text-ignore-placement"),r.bucketInstanceId,F&&F.placeable&&U?U:N,p.ID),q&&this.collisionIndex.insertCollisionBox(j.box,b,a.get("icon-ignore-placement"),r.bucketInstanceId,Z,p.ID),O&&z&&this.collisionIndex.insertCollisionCircles(O.circles,g,a.get("text-ignore-placement"),r.bucketInstanceId,N,p.ID),o&&this.storeCollisionData(r.bucketInstanceId,x,d,B,j,O),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===r.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new Ye((z||C)&&!(null==B?void 0:B.occluded),(D||I)&&!(null==j?void 0:j.occluded),A||r.justReloaded),i[e.crossTileID]=!0;};if(P){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=r.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(r.symbolInstances.get(i),r.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=a>=0&&t!==a?0:o.crossTileID);}markUsedOrientation(e,i,o){const r=i===t.ao.horizontal||i===t.ao.horizontalOnly?i:0,a=i===t.ao.vertical?i:0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];for(const t of s)e.text.placedSymbolArray.get(t).placedOrientation=r;o.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).placedOrientation=a);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=!1;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const o=t?t.symbolFadeChange(e):1,r=t?t.opacities:{},a=t?t.variableOffsets:{},s=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],a=r[e];a?(this.opacities[e]=new Ke(a,o,t.text,t.icon),i=i||t.text!==a.text.placed||t.icon!==a.icon.placed):(this.opacities[e]=new Ke(null,o,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in r){const t=r[e];if(!this.opacities[e]){const r=new Ke(t,o,!1,!1);r.isHidden()||(this.opacities[e]=r,i=i||t.text.placed||t.icon.placed);}}for(const e in a)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=a[e]);for(const e in s)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=s[e]);if(t&&void 0===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const o of t){const t=o.getBucket(e);t&&o.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,o.tileID,i,o.collisionBoxArray);}}updateBucketOpacities(e,i,o,r){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=!1),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=!1),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const a=e.layers[0],s=a.layout,n=new Ke(null,0,!1,!1,!0),l=s.get("text-allow-overlap"),c=s.get("icon-allow-overlap"),h=a._unevaluatedLayout.hasValue("text-variable-anchor")||a._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===s.get("text-rotation-alignment"),d="map"===s.get("text-pitch-alignment"),_="none"!==s.get("icon-text-fit"),p=new Ke(null,0,l&&(c||!e.hasIconData()||s.get("icon-optional")),c&&(l||!e.hasTextData()||s.get("text-optional")),!0);!e.collisionArrays&&r&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(r);const m=(e,t,i)=>{for(let o=0;o0,v=this.placedOrientations[r.crossTileID],b=v===t.ao.vertical,x=v===t.ao.horizontal||v===t.ao.horizontalOnly;if(a>0||s>0){const t=ht(c.text);m(e.text,a,b?ut:t),m(e.text,s,x?ut:t);const i=c.text.isHidden();[r.rightJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||b?1:0);})),r.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).hidden=i||x?1:0);const o=this.variableOffsets[r.crossTileID];o&&this.markUsedJustification(e,o.anchor,r,v);const n=this.placedOrientations[r.crossTileID];n&&(this.markUsedJustification(e,"left",r,n),this.markUsedOrientation(e,n,r));}if(g){const t=ht(c.icon),i=!(_&&r.verticalPlacedIconSymbolIndex&&b);r.placedIconSymbolIndex>=0&&(m(e.icon,r.numIconVertices,i?t:ut),e.icon.placedSymbolArray.get(r.placedIconSymbolIndex).hidden=c.icon.isHidden()),r.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,r.numVerticalIconVertices,i?ut:t),e.icon.placedSymbolArray.get(r.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const y=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const o=e.collisionArrays[i];if(o){let i=new t.P(0,0);if(o.textBox||o.verticalTextBox){let t=!0;if(h){const e=this.variableOffsets[l];e?(i=et(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=!1;}if(o.textBox||o.verticalTextBox){let r;o.textBox&&(r=b),o.verticalTextBox&&(r=x),it(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||r,y.text,i.x,i.y);}}if(o.iconBox||o.verticalIconBox){const t=Boolean(!x&&o.verticalIconBox);let r;o.iconBox&&(r=t),o.verticalIconBox&&(r=!t),it(e.iconCollisionBox.collisionVertexArray,c.icon.placed,r,y.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=!0;}}function it(e,t,i,o,r,a){o&&0!==o.length||(o=[0,0,0,0]);const s=o[0]-We,n=o[1]-We,l=o[2]-We,c=o[3]-We;e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,c),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,c);}const ot=Math.pow(2,25),rt=Math.pow(2,24),at=Math.pow(2,17),st=Math.pow(2,16),nt=Math.pow(2,9),lt=Math.pow(2,8),ct=Math.pow(2,1);function ht(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*ot+t*rt+i*at+t*st+i*nt+t*lt+i*ct+t}const ut=0;class dt{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,o,r){const a=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&s.now()-o>2;for(;this._currentPlacementIndex>=0;){const o=t[e[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if("symbol"===o.type&&(!o.minzoom||o.minzoom<=a)&&(!o.maxzoom||o.maxzoom>a)){if(this._inProgressLayer||(this._inProgressLayer=new dt(o)),this._inProgressLayer.continuePlacement(i[o.source],this.placement,this._showCollisionBoxes,o,r))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(e){return this.placement.commit(e),this.placement}}const pt=512/t.$/2;class mt{constructor(e,i,o){this.tileID=e,this.bucketInstanceId=o,this._symbolsByKey={};const r=new Map;for(let e=0;e({x:Math.floor(e.anchorX*pt),y:Math.floor(e.anchorY*pt)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(o.positions.length>128){const e=new t.aI(o.positions.length,16,Uint16Array);for(const{x:t,y:i}of o.positions)e.add(t,i);e.finish(),delete o.positions,o.index=e;}this._symbolsByKey[e]=o;}}getScaledCoordinates(e,i){const{x:o,y:r,z:a}=this.tileID.canonical,{x:s,y:n,z:l}=i.canonical,c=pt/Math.pow(2,l-a),h=(n*t.$+e.anchorY)*c,u=r*t.$*pt;return {x:Math.floor((s*t.$+e.anchorX)*c-o*t.$*pt),y:Math.floor(h-u)}}findMatches(e,t,i){const o=this.tileID.canonical.ze))}}class ft{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class gt{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],o={};for(const e in i){const r=i[e];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+t),o[r.tileID.key]=r;}this.indexes[e]=o;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in r){const a=r[i];a.tileID.isChildOf(e)&&a.findMatches(t.symbolInstances,e,o);}else {const a=r[e.scaledTo(Number(i)).key];a&&a.findMatches(t.symbolInstances,e,o);}}for(let e=0;e{t[e]=!0;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var bt="void main() {fragColor=vec4(1.0);}";const xt={prelude:yt("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:yt("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:yt("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:yt("uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:yt("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:yt("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:yt(bt,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:yt("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:yt("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:yt("in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:yt("in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),colorRelief:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform int u_color_ramp_size;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {float x=(float(stop)+0.5)/float(u_color_ramp_size);vec4 data=texture(u_elevation_stops,vec2(x,0))*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int r=(u_color_ramp_size-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else\n{l=m;el_l=el_m;}}float x=(float(l)+(el-el_l)/(el_r-el_l)+0.5)/float(u_color_ramp_size);fragColor=u_opacity*texture(u_color_stops,vec2(x,0));\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_dimension;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),debug:yt("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}","in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:yt(bt,"in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:yt("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:yt("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:yt("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:yt("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:yt("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {vec2 epsilon=1.0/u_dimension;float tileSize=u_dimension.x-2.0;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))*tileSize/pow(2.0,exaggeration+(28.2562-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+0.5,deriv.y/8.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:yt("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];\n#define PI 3.141592653589793\n#define STANDARD 0\n#define COMBINED 1\n#define IGOR 2\n#define MULTIDIRECTIONAL 3\n#define BASIC 4\nfloat get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);}void igor_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float aspect=get_aspect(deriv);float azimuth=u_azimuths[0]+PI;float slope_stength=atan(length(deriv))*2.0/PI;float aspect_strength=1.0-abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);float shadow_strength=slope_stength*aspect_strength;float highlight_strength=slope_stength*(1.0-aspect_strength);fragColor=u_shadows[0]*shadow_strength+u_highlights[0]*highlight_strength;}void standard_hillshade(vec2 deriv){float azimuth=u_azimuths[0]+PI;float slope=atan(0.625*length(deriv));float aspect=get_aspect(deriv);float intensity=u_exaggeration;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadows[0],u_highlights[0],shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;}void basic_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor=u_highlights[0]*(2.0*shade-1.0);}else\n{fragColor=u_shadows[0]*(1.0-2.0*shade);}}void multidirectional_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;fragColor=vec4(0,0,0,0);for(int i=0; i < NUM_ILLUMINATION_SOURCES; i++){float cos_alt=cos(u_altitudes[i]);float sin_alt=sin(u_altitudes[i]);float cos_az=-cos(u_azimuths[i]);float sin_az=-sin(u_azimuths[i]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor+=u_highlights[i]*(2.0*shade-1.0)/float(NUM_ILLUMINATION_SOURCES);}else\n{fragColor+=u_shadows[i]*(1.0-2.0*shade)/float(NUM_ILLUMINATION_SOURCES);}}}void combined_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=acos((sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv)));cang=clamp(cang,0.0,PI/2.0);float shade=cang*atan(length(deriv))*4.0/PI/PI;float highlight=(PI/2.0-cang)*atan(length(deriv))*4.0/PI/PI;fragColor=u_shadows[0]*shade+u_highlights[0]*highlight;}void main() {vec4 pixel=texture(u_image,v_pos);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));vec2 deriv=((pixel.rg*8.0)-4.0)/scaleFactor;if (u_method==BASIC) {basic_hillshade(deriv);} else if (u_method==COMBINED) {combined_hillshade(deriv);} else if (u_method==IGOR) {igor_hillshade(deriv);} else if (u_method==MULTIDIRECTIONAL) {multidirectional_hillshade(deriv);} else if (u_method==STANDARD) {standard_hillshade(deriv);} else {standard_hillshade(deriv);}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:yt("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:yt("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0);vec4 color1=texture(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:yt("uniform sampler2D u_texture;in vec2 v_tex;in float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;fragColor=texture(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_tex;out float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:yt("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:yt("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;fragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:yt("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}","in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:yt("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}","in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:yt("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:yt("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:yt("in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}","in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:yt("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function yt(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o=t.match(/in ([\w]+) ([\w]+)/g),r=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=a?a.concat(r):r,n={};return {fragmentSource:e=e.replace(i,((e,t,i,o,r)=>(n[r]=!0,"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nin ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = u_${r};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,o,r)=>{const a="float"===o?"vec2":"vec4",s=r.match(/color/)?"color":a;return n[r]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\nout ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`})),staticAttributes:o,staticUniforms:s}}class wt{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var Tt=t.aJ([{name:"a_pos",type:"Int16",components:2}]);const Pt="#define PROJECTION_MERCATOR",Ct="mercator";class It{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return !1}get shaderVariantName(){return Ct}get shaderDefine(){return Pt}get shaderPreludeCode(){return xt.projectionMercator}get vertexShaderPreludeCode(){return xt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.aK.noSubdivision}get useGlobeControls(){return !1}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(e){}getMeshFromTileID(e,i,o,r,a){if(this._cachedMesh)return this._cachedMesh;const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(t.$,0),s.emplaceBack(0,t.$),s.emplaceBack(t.$,t.$);const n=e.createVertexBuffer(s,Tt.members),l=t.aM.simpleSegment(0,0,4,2),c=new t.aN;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new wt(n,h,l),this._cachedMesh}recalculate(){}hasTransition(){return !1}setErrorQueryLatitudeDegrees(e){}}class Mt{constructor(e=0,t=0,i=0,o=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=o;}interpolate(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.C.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.C.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.C.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.C.number(e.right,i.right,o)),this}getCenter(e,i){const o=t.ah((this.left+e-this.right)/2,0,e),r=t.ah((this.top+i-this.bottom)/2,0,i);return new t.P(o,r)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new Mt(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function St(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function Et(e){return Math.max(0,Math.floor(e))}class Rt{constructor(e,i,o,r,a,s){this._callbacks=e,this._tileSize=512,this._renderWorldCopies=void 0===s||!!s,this._minZoom=i||0,this._maxZoom=o||22,this._minPitch=null==r?0:r,this._maxPitch=null==a?60:a,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.S(0,0),this._elevation=0,this._zoom=0,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new Mt,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=!0;}apply(e,i,o){this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new Mt(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,this._cameraToCenterDistance=e.cameraToCenterDistance,this._nearZ=e.nearZ,this._farZ=e.farZ,this._autoCalculateNearFarZ=!o&&e.autoCalculateNearFarZ,i&&this._constrain(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e;}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const i=t.aO(e,-180,180)*Math.PI/180;var r,a,s,n,l,c,h,u,d;this._bearingInRadians!==i&&(this._unmodified=!1,this._bearingInRadians=i,this._calcMatrices(),this._rotationMatrix=o(),r=this._rotationMatrix,s=-this._bearingInRadians,n=(a=this._rotationMatrix)[0],l=a[1],c=a[2],h=a[3],u=Math.sin(s),d=Math.cos(s),r[0]=n*d+c*u,r[1]=l*d+h*u,r[2]=n*-u+c*d,r[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.ah(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=!1,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=!1,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.aP(this._fovInRadians)}setFov(e){e=t.ah(e,.1,150),this.fov!==e&&(this._unmodified=!1,this._fovInRadians=t.ae(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const i=this.getConstrained(this._center,e).zoom;this._zoom!==i&&(this._unmodified=!1,this._zoom=i,this._tileZoom=Math.max(0,Math.floor(i)),this._scale=t.af(i),this._constrain(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(e,t){this._autoCalculateNearFarZ=!1,this._nearZ=e,this._farZ=t,this._calcMatrices();}clearNearFarZOverride(){this._autoCalculateNearFarZ=!0,this._calcMatrices();}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices();}resize(e,t,i=!0){this._width=e,this._height=t,i&&this._constrain(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new G([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-t.ai,t.ai]);}getConstrained(e,t){return this._callbacks.getConstrained(e,t)}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{const{minX:o,minY:r,maxX:a,maxY:s}=t.a2.fromPoints(i).extend(e);return [new t.P(o,r),new t.P(a,r),new t.P(a,s),new t.P(o,s),new t.P(o,r)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const e=this._unmodified,{center:t,zoom:i}=this.getConstrained(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=!1;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.ag(new Float64Array(16));t.N(e,e,[this._width/2,-this._height/2,1]),t.M(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.ag(new Float64Array(16)),t.N(e,e,[1,-1,1]),t.M(e,e,[-1,-1,0]),t.N(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height;}this._callbacks.calcMatrices();}calculateCenterFromCameraLngLatAlt(e,i,o,r){const a=void 0!==o?o:this.bearing,s=r=void 0!==r?r:this.pitch,n=t.a1.fromLngLat(e,i),l=-Math.cos(t.ae(s)),c=Math.sin(t.ae(s)),h=c*Math.sin(t.ae(a)),u=-c*Math.cos(t.ae(a));let d=this.elevation;const _=i-d;let p;l*_>=0||Math.abs(l)<.1?(p=1e4,d=i+p*l):p=-_/l;let m,f,g=t.aQ(1,n.y),v=0;do{if(v+=1,v>10)break;f=p/g,m=new t.a1(n.x+h*f,n.y+u*f),g=1/m.meterInMercatorCoordinateUnits();}while(Math.abs(p-f*g)>1e-12);return {center:m.toLngLat(),elevation:d,zoom:t.ak(this.height/2/Math.tan(this.fovInRadians/2)/f/this.tileSize)}}recalculateZoomAndCenter(e){if(this.elevation-e==0)return;const i=t.aj(1,this.center.lat)*this.worldSize,o=this.cameraToCenterDistance/i,r=t.a1.fromLngLat(this.center,this.elevation),a=de(this.center,this.elevation,this.pitch,this.bearing,o);this._elevation=e;const s=this.calculateCenterFromCameraLngLatAlt(a.toLngLat(),t.aQ(a.z,r.y),this.bearing,this.pitch);this._elevation=s.elevation,this._center=s.center,this.setZoom(s.zoom);}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.P(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/e).toLngLat()}getMercatorTileCoordinates(e){if(!e)return [0,0,1,1];const i=e.canonical.z>=0?1<this.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[o]*this.min[o],i+=e[o]*this.max[o]):(i+=e[o]*this.min[o],t+=e[o]*this.max[o]);return t>=0?2:i<0?0:1}}class Dt{distanceToTile2d(e,t,i,o){const r=o.distanceX([e,t]),a=o.distanceY([e,t]);return Math.hypot(r,a)}getWrap(e,t,i){return i}getTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}const c=1<r}allowWorldCopies(){return !0}prepareNextFrame(){}}class At{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,o=0,r,a){const s=a?[[6,5,4],[0,1,2],[0,3,7],[2,1,5],[3,2,6],[0,4,5]]:[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]],n=Math.pow(2,o),l=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((o=>function(e,i,o,r){const a=t.aw([],e,i),s=1/a[3]/o*r;return t.aY(a,a,[s,s,1/a[3],s])}(o,e,i,n)));r&&function(e,i,o,r){const a=r?4:0,s=r?0:4;let n=0;const l=[],c=[];for(let i=0;i<4;i++){const o=t.aU([],e[i+s],e[i+a]),r=t.aZ(o);t.aR(o,o,1/r),l.push(r),c.push(o);}for(let i=0;i<4;i++){const r=t.a_(e[i+a],c[i],o);n=null!==r&&r>=0?Math.max(n,r):Math.max(n,l[i]);}const h=function(e,i){const o=t.aU([],e[i[0]],e[i[1]]),r=t.aU([],e[i[2]],e[i[1]]),a=[0,0,0,0];return t.aV(a,t.aW([],o,r)),a[3]=-t.aX(a,e[i[0]]),a}(e,i),u=function(e,i){const o=t.a$(e),r=t.b0([],e,1/o),a=t.aU([],i,t.aR([],r,t.aX(i,r))),s=t.a$(a);if(s>0){const e=Math.sqrt(1-r[3]*r[3]),o=t.aR([],r,-r[3]),n=t.aS([],o,t.aR([],a,e/s));return t.b1(i,n)}return null}(o,h);if(null!==u){const e=u/t.aX(c[0],h);n=Math.min(n,e);}for(let t=0;t<4;t++){const i=Math.min(n,l[t]);e[t+s]=[e[t+a][0]+c[t][0]*i,e[t+a][1]+c[t][1]*i,e[t+a][2]+c[t][2]*i,1];}}(l,s[0],r,a);const c=s.map((e=>{const i=t.aU([],l[e[0]],l[e[1]]),o=t.aU([],l[e[2]],l[e[1]]),r=t.aV([],t.aW([],i,o)),a=-t.aX(r,l[e[1]]);return r.concat(a)})),h=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of l)for(let t=0;t<3;t++)h[t]=Math.min(h[t],e[t]),u[t]=Math.max(u[t],e[t]);return new At(l,c,new zt(h,u))}}class Lt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e,t){}constructor(e,t,i,o,r){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)},e,t,i,o,r),this._coveringTilesDetailsProvider=new Dt;}clone(){const e=new Lt;return e.apply(this),e}apply(e,t,i){this._helper.apply(e,t,i);}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.b2(0,e)];if(this._helper._renderWorldCopies){const o=this.screenPointToMercatorCoordinate(new t.P(0,0)),r=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,0)),a=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,this._helper._height)),s=this.screenPointToMercatorCoordinate(new t.P(0,this._helper._height)),n=Math.floor(Math.min(o.x,r.x,a.x,s.x)),l=Math.floor(Math.max(o.x,r.x,a.x,s.x)),c=1;for(let o=n-c;o<=l+c;o++)0!==o&&i.push(new t.b2(o,e));}return i}getCameraFrustum(){return At.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const t=this.screenPointToLocation(this.centerPoint,e),i=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(i);}setLocationAtPoint(e,i){const o=t.aj(this.elevation,this.center.lat),r=this.screenPointToMercatorCoordinateAtZ(i,o),a=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,o),s=t.a1.fromLngLat(e),n=new t.a1(s.x-(r.x-a.x),s.y-(r.y-a.y));this.setCenter(null==n?void 0:n.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,i){return i?this.coordinatePoint(t.a1.fromLngLat(e),i.getElevationForLngLatZoom(e,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(t.a1.fromLngLat(e))}screenPointToLocation(e,t){var i;return null===(i=this.screenPointToMercatorCoordinate(e,t))||void 0===i?void 0:i.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const o=i||0,r=[e.x,e.y,0,1],a=[e.x,e.y,1,1];t.aw(r,r,this._pixelMatrixInverse),t.aw(a,a,this._pixelMatrixInverse);const s=r[3],n=a[3],l=r[1]/s,c=a[1]/n,h=r[2]/s,u=a[2]/n,d=h===u?0:(o-h)/(u-h);return new t.a1(t.C.number(r[0]/s,a[0]/n,d)/this.worldSize,t.C.number(l,c,d)/this.worldSize,o)}coordinatePoint(e,i=0,o=this._pixelMatrix){const r=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.aw(r,r,o),new t.P(r[0]/r[3],r[1]/r[3])}getBounds(){const e=Math.max(0,this._helper._height/2-he(this));return (new G).extend(this.screenPointToLocation(new t.P(0,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.P(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-he(this)}calculatePosMatrix(e,i=!1,o){var r;const a=null!==(r=e.key)&&void 0!==r?r:t.b3(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),s=i?this._alignedPosMatrixCache:this._posMatrixCache;if(s.has(a)){const e=s.get(a);return o?e.f32:e.f64}const n=ue(e,this.worldSize);t.O(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return s.set(a,l),o?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,o=this._fogMatrixCacheF32;if(o.has(i))return o.get(i);const r=ue(e,this.worldSize);return t.O(r,this._fogMatrix,r),o.set(i,new Float32Array(r)),o.get(i)}getConstrained(e,i){i=t.ah(+i,this.minZoom,this.maxZoom);const o={center:new t.S(e.lng,e.lat),zoom:i};let r=this._helper._lngRange;if(!this._helper._renderWorldCopies&&null===r){const e=180-1e-10;r=[-e,e];}const a=this.tileSize*t.af(o.zoom);let s=0,n=a,l=0,c=a,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;s=t.U(e[1])*a,n=t.U(e[0])*a,n-s<_&&(h=_/(n-s));}r&&(l=t.aO(t.V(r[0])*a,0,a),c=t.aO(t.V(r[1])*a,0,a),cn&&(g=n-e);}if(r){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.aO(p,e-a/2,e+a/2));const o=d/2;i-oc&&(f=c-o);}if(void 0!==f||void 0!==g){const e=new t.P(null!=f?f:p,null!=g?g:m);o.center=ce(a,e).wrap();}return o}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}_calculateNearFarZIfNeeded(e,i,o){if(!this._helper.autoCalculateNearFarZ)return;const r=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),a=e-r*this._helper._pixelPerMeter/Math.cos(i),s=r<0?a:e,n=Math.PI/2+this.pitchInRadians,l=t.ae(this.fov)*(Math.abs(Math.cos(t.ae(this.roll)))*this.height+Math.abs(Math.sin(t.ae(this.roll)))*this.width)/this.height*(.5+o.y/this.height),c=Math.sin(l)*s/Math.sin(t.ah(Math.PI-n-l,.01,Math.PI-.01)),h=he(this),u=Math.atan(h/this._helper.cameraToCenterDistance),d=t.ae(.75),_=u>d?2*u*(.5+o.y/(2*h)):d,p=Math.sin(_)*s/Math.sin(t.ah(Math.PI-n-_,.01,Math.PI-.01)),m=Math.min(c,p);this._helper._farZ=1.01*(Math.cos(Math.PI/2-i)*m+s),this._helper._nearZ=this._helper._height/50;}_calcMatrices(){if(!this._helper._height)return;const e=this.centerOffset,i=le(this.worldSize,this.center),o=i.x,r=i.y;this._helper._pixelPerMeter=t.aj(1,this.center.lat)*this.worldSize;const a=t.ae(Math.min(this.pitch,ne)),s=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(a));let n;this._calculateNearFarZIfNeeded(s,a,e),n=new Float64Array(16),t.b4(n,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),t.aq(this._invProjMatrix,n),n[8]=2*-e.x/this._helper._width,n[9]=2*e.y/this._helper._height,this._projectionMatrix=t.b5(n),t.N(n,n,[1,-1,1]),t.M(n,n,[0,0,-this._helper.cameraToCenterDistance]),t.b6(n,n,-this.rollInRadians),t.b7(n,n,this.pitchInRadians),t.b6(n,n,-this.bearingInRadians),t.M(n,n,[-o,-r,0]),this._mercatorMatrix=t.N([],n,[this.worldSize,this.worldSize,this.worldSize]),t.N(n,n,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n),t.M(n,n,[0,0,-this.elevation]),this._viewProjMatrix=n,this._invViewProjMatrix=t.aq([],n);const l=[0,0,-1,1];t.aw(l,l,this._invViewProjMatrix),this._cameraPosition=[l[0]/l[3],l[1]/l[3],l[2]/l[3]],this._fogMatrix=new Float64Array(16),t.b4(this._fogMatrix,this.fovInRadians,this.width/this.height,s,this._helper._farZ),this._fogMatrix[8]=2*-e.x/this.width,this._fogMatrix[9]=2*e.y/this.height,t.N(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.b6(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.b7(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.b6(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.M(this._fogMatrix,this._fogMatrix,[-o,-r,0]),t.N(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n);const c=this._helper._width%2/2,h=this._helper._height%2/2,u=Math.cos(this.bearingInRadians),d=Math.sin(-this.bearingInRadians),_=o-Math.round(o)+u*c+d*h,p=r-Math.round(r)+u*h+d*c,m=new Float64Array(n);if(t.M(m,m,[_>.5?_-1:_,p>.5?p-1:p,0]),this._alignedProjMatrix=m,n=t.aq(new Float64Array(16),this._pixelMatrix),!n)throw new Error("failed to invert matrix");this._pixelMatrixInverse=n,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.P(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.aw(i,i,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/e).toLngLat()}lngLatToCameraDepth(e,i){const o=t.a1.fromLngLat(e),r=[o.x*this.worldSize,o.y*this.worldSize,i,1];return t.aw(r,r,this._viewProjMatrix),r[2]/r[3]}getProjectionData(e){const{overscaledTileID:i,aligned:o,applyTerrainMatrix:r}=e,a=this._helper.getMercatorTileCoordinates(i),s=i?this.calculatePosMatrix(i,o,!0):null;let n;return n=i&&i.terrainRttPosMatrix32f&&r?i.terrainRttPosMatrix32f:s||t.b8(),{mainMatrix:n,tileMercatorCoords:a,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:n}}isLocationOccluded(e){return !1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,i){return 1}transformLightDirection(e){return t.aT(e)}getRayDirectionFromPixel(e){throw new Error("Not implemented.")}projectTileCoordinates(e,i,o,r){const a=this.calculatePosMatrix(o);let s;r?(s=[e,i,r(e,i),1],t.aw(s,s,a)):(s=[e,i,0,1],qe(s,s,a));const n=s[3];return {point:new t.P(s[0]/n,s[1]/n),signedDistanceFromCamera:n,isOccluded:!1}}populateCache(e){for(const t of e)this.calculatePosMatrix(t);}getMatrixForModel(e,i){const o=t.a1.fromLngLat(e,i),r=o.meterInMercatorCoordinateUnits(),a=t.b9();return t.M(a,a,[o.x,o.y,o.z]),t.b6(a,a,Math.PI),t.b7(a,a,Math.PI/2),t.N(a,a,[-r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=new t.Z(0,0,0,0,0),o=this.getProjectionData({overscaledTileID:i,applyGlobeMatrix:e}),r=ue(i,this.worldSize);t.O(r,this._viewProjMatrix,r),o.tileMercatorCoords=[0,0,1,1];const a=[t.$,t.$,this.worldSize/this._helper.pixelsPerMeter],s=t.ba();return t.N(s,r,a),o.fallbackMatrix=s,o.mainMatrix=s,o}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}}function kt(){t.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");}function Ft(e){if(e.useSlerp)if(e.k<1){const i=t.bb(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),o=t.bb(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),r=new Float64Array(4);t.bc(r,i,o,e.k);const a=t.bd(r);e.tr.setRoll(a.roll),e.tr.setPitch(a.pitch),e.tr.setBearing(a.bearing);}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(t.C.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(t.C.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(t.C.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k));}function Bt(e,i,o,r,a){const s=a.padding,n=le(a.worldSize,o.getNorthWest()),l=le(a.worldSize,o.getNorthEast()),c=le(a.worldSize,o.getSouthEast()),h=le(a.worldSize,o.getSouthWest()),u=t.ae(-r),d=n.rotate(u),_=l.rotate(u),p=c.rotate(u),m=h.rotate(u),f=new t.P(Math.max(d.x,_.x,m.x,p.x),Math.max(d.y,_.y,m.y,p.y)),g=new t.P(Math.min(d.x,_.x,m.x,p.x),Math.min(d.y,_.y,m.y,p.y)),v=f.sub(g),b=(a.width-(s.left+s.right+i.left+i.right))/v.x,x=(a.height-(s.top+s.bottom+i.top+i.bottom))/v.y;if(x<0||b<0)return void kt();const y=Math.min(t.ak(a.scale*Math.min(b,x)),e.maxZoom),w=t.P.convert(e.offset),T=new t.P((i.left-i.right)/2,(i.top-i.bottom)/2).rotate(t.ae(r)),P=w.add(T).mult(a.scale/t.af(y));return {center:ce(a.worldSize,n.add(c).div(2).sub(P)),zoom:y,bearing:r}}class Ot{get useGlobeControls(){return !1}handlePanInertia(e,t){const i=e.mag(),o=Math.abs(he(t));return {easingOffset:e.mult(Math.min(.75*o/i,1)),easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta);}handleMapControlsPan(e,t,i){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(i,e.around);}cameraForBoxAndBearing(e,t,i,o,r){return Bt(e,t,i,o,r)}handleJumpToCenterZoom(e,i){e.zoom!==(void 0!==i.zoom?+i.zoom:e.zoom)&&e.setZoom(+i.zoom),void 0!==i.center&&e.setCenter(t.S.convert(i.center));}handleEaseTo(e,i){const o=e.zoom,r=e.padding,a={roll:e.roll,pitch:e.pitch,bearing:e.bearing},s={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},n=void 0!==i.zoom,l=!e.isPaddingEqual(i.padding);let c=!1;const h=n?+i.zoom:e.zoom;let u=e.centerPoint.add(i.offsetAsPoint);const d=e.screenPointToLocation(u),{center:_,zoom:p}=e.getConstrained(t.S.convert(i.center||d),null!=h?h:o);St(e,_);const m=le(e.worldSize,d),f=le(e.worldSize,_).sub(m),g=t.af(p-o);return c=p!==o,{easeFunc:n=>{if(c&&e.setZoom(t.C.number(o,p,n)),t.be(a,s)||Ft({startEulerAngles:a,endEulerAngles:s,tr:e,k:n,useSlerp:a.roll!=s.roll}),l&&(e.interpolatePadding(r,i.padding,n),u=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const i=t.af(e.zoom-o),r=p>o?Math.min(2,g):Math.max(.5,g),a=Math.pow(r,1-n),s=ce(e.worldSize,m.add(f.mult(n*a)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?s.wrap():s,u);}},isZooming:c,elevationCenter:_}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.zoom,a=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),o?+i.zoom:r),s=a.center,n=a.zoom;St(e,s);const l=le(e.worldSize,i.locationAtOffset),c=le(e.worldSize,s).sub(l),h=c.mag(),u=t.af(n-r);let d;if(void 0!==i.minZoom){const o=Math.min(+i.minZoom,r,n),a=e.getConstrained(s,o).zoom;d=t.af(a-r);}return {easeFunc:(i,o,a,h)=>{e.setZoom(1===i?n:r+t.ak(o));const u=1===i?s:ce(e.worldSize,l.add(c.mult(a)).mult(o));e.setLocationAtPoint(e.renderWorldCopies?u.wrap():u,h);},scaleOfZoom:u,targetCenter:s,scaleOfMinZoom:d,pixelPathLength:h}}}class jt{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}jt.Replace=[1,0],jt.disabled=new jt(jt.Replace,t.bf.transparent,[!1,!1,!1,!1]),jt.unblended=new jt(jt.Replace,t.bf.transparent,[!0,!0,!0,!0]),jt.alphaBlended=new jt([1,771],t.bf.transparent,[!0,!0,!0,!0]);const Nt=2305;class Ut{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}Ut.disabled=new Ut(!1,1029,Nt),Ut.backCCW=new Ut(!0,1029,Nt),Ut.frontCCW=new Ut(!0,1028,Nt);class Zt{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Zt.ReadOnly=!1,Zt.ReadWrite=!0,Zt.disabled=new Zt(519,Zt.ReadOnly,[0,1]);const Gt=7680;class Vt{constructor(e,t,i,o,r,a){this.test=e,this.ref=t,this.mask=i,this.fail=o,this.depthFail=r,this.pass=a;}}Vt.disabled=new Vt({func:519,mask:0},0,0,Gt,Gt,Gt);const $t=new WeakMap;function qt(e){var t;if($t.has(e))return $t.get(e);{const i=null===(t=e.getParameter(e.VERSION))||void 0===t?void 0:t.startsWith("WebGL 2.0");return $t.set(e,i),i}}class Wt{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,o=i.gl;this._texFormat=o.RGBA,this._texType=o.UNSIGNED_BYTE;const r=new t.aL;r.emplaceBack(-1,-1),r.emplaceBack(2,-1),r.emplaceBack(-1,2);const a=new t.aN;a.emplaceBack(0,1,2),this._fullscreenTriangle=new wt(i.createVertexBuffer(r,Tt.members),i.createIndexBuffer(a),t.aM.simpleSegment(0,0,r.length,a.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(o.TEXTURE1);const s=o.createTexture();o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texImage2D(o.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(s),qt(o)&&(this._pbo=o.createBuffer(),o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.bufferData(o.PIXEL_PACK_BUFFER,4,o.STREAM_READ),o.bindBuffer(o.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const o=this._cachedRenderContext.context,r=o.gl;if(this._bindFramebuffer(),o.viewport.set([0,0,this._texWidth,this._texHeight]),o.clear({color:t.bf.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(o,r.TRIANGLES,Zt.disabled,Vt.disabled,jt.unblended,Ut.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&qt(r)){r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.readBuffer(r.COLOR_ATTACHMENT0),r.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),r.bindBuffer(r.PIXEL_PACK_BUFFER,null);const e=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);r.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&qt(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=Wt._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const Ht=t.$/128;function Xt(e,i){const o=void 0!==e.granularity?Math.max(e.granularity,1):1,r=o+(e.generateBorders?2:0),a=o+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),s=r+1,n=a+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=o+(e.generateBorders?1:0),u=o+(e.generateBorders||e.extendToSouthPole?1:0),d=s*n,_=r*a*6,p=s*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g=0;for(let i=c;i<=u;i++)for(let r=l;r<=h;r++){let a=r/o*t.$;-1===r&&(a=-Ht),r===o+1&&(a=t.$+Ht);let s=i/o*t.$;-1===i&&(s=e.extendToNorthPole?t.bh:-Ht),i===o+1&&(s=e.extendToSouthPole?t.bi:t.$+Ht),f[g++]=a,f[g++]=s;}const v=m?new Uint32Array(_):new Uint16Array(_);let b=0;for(let e=0;e0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return "globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy();}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e);}getMeshFromTileID(e,t,i,o,r){return this.currentProjection.getMeshFromTileID(e,t,i,o,r)}setProjection(e){this._transitionable.setValue("type",(null==e?void 0:e.type)||"mercator");}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e);}}function ei(e){const t=oi(e.worldSize,e.center.lat);return 2*Math.PI*t}function ti(e,i,o,r,a){const s=1/(1<1e-6){const r=e[0]/o,a=Math.acos(e[2]/o),s=(r>0?a:-a)/Math.PI*180;return new t.S(t.aO(s,-180,180),i)}return new t.S(0,i)}function ai(e){return Math.cos(e*Math.PI/180)}function si(e,i){const o=ai(e),r=ai(i);return t.ak(r/o)}function ni(e,i){const o=e.rotate(i.bearingInRadians),r=i.zoom+si(i.center.lat,0),a=t.bk(1/ai(i.center.lat),1/ai(Math.min(Math.abs(i.center.lat),60)),t.bn(r,7,3,0,1)),s=360/ei({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.S(i.center.lng-o.x*s*a,t.ah(i.center.lat+o.y*s,-t.ai,t.ai))}function li(e){const t=.5*e,i=Math.sin(t),o=Math.cos(t);return Math.log(i+o)-Math.log(o-i)}function ci(e,i,o,r){const a=e.lat+o*r;if(Math.abs(o)>1){const s=(Math.sign(e.lat+o)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+o)*Math.PI/180,l=li(s+r*(n-s)),c=li(s),h=li(n);return new t.S(e.lng+i*((l-c)/(h-c)),a)}return new t.S(e.lng+i*r,a)}class hi{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._boundingVolumeFactory=e;}swapBuffers(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1;}getTileBoundingVolume(e,t,i,o){const r=`${e.z}_${e.x}_${e.y}_${(null==o?void 0:o.terrain)?"t":""}`,a=this._cache.get(r);if(a)return a;const s=this._cachePrevious.get(r);if(s)return this._cache.set(r,s),s;const n=this._boundingVolumeFactory(e,t,i,o);return this._cache.set(r,n),this._hadAnyChanges=!0,n}}class ui{constructor(e,t,i,o){this.min=i,this.max=o,this.points=e,this.planes=t;}static fromAabb(e,t){const i=[];for(let o=0;o<8;o++)i.push([1&~o?e[0]:t[0],1==(o>>1&1)?t[1]:e[1],1==(o>>2&1)?t[2]:e[2]]);return new ui(i,[[-1,0,0,t[0]],[1,0,0,-e[0]],[0,-1,0,t[1]],[0,1,0,-e[1]],[0,0,-1,t[2]],[0,0,1,-e[2]]],e,t)}static fromCenterSizeAngles(e,i,o){const r=t.br([],o[0],o[1],o[2]),a=t.bs([],[i[0],0,0],r),s=t.bs([],[0,i[1],0],r),n=t.bs([],[0,0,i[2]],r),l=[...e],c=[...e];for(let t=0;t<8;t++)for(let i=0;i<3;i++){const o=e[i]+a[i]*(1&~t?-1:1)+s[i]*(1==(t>>1&1)?1:-1)+n[i]*(1==(t>>2&1)?1:-1);l[i]=Math.min(l[i],o),c[i]=Math.max(c[i],o);}const h=[];for(let i=0;i<8;i++){const o=[...e];t.aS(o,o,t.aR([],a,1&~i?-1:1)),t.aS(o,o,t.aR([],s,1==(i>>1&1)?1:-1)),t.aS(o,o,t.aR([],n,1==(i>>2&1)?1:-1)),h.push(o);}return new ui(h,[[...a,-t.aX(a,h[0])],[...s,-t.aX(s,h[0])],[...n,-t.aX(n,h[0])],[-a[0],-a[1],-a[2],-t.aX(a,h[7])],[-s[0],-s[1],-s[2],-t.aX(s,h[7])],[-n[0],-n[1],-n[2],-t.aX(n,h[7])]],l,c)}intersectsFrustum(e){let t=!0;const i=this.points.length,o=this.planes.length,r=e.planes.length,a=e.points.length;for(let o=0;o=0&&a++;}if(0===a)return 0;a=0&&o++;}if(0===o)return 0}return 1}intersectsPlane(e){const t=this.points.length;let i=0;for(let o=0;o=0&&i++;}return i===t?2:0===i?0:1}}function di(e,t,i){const o=e-t;return o<0?-o:Math.max(0,o-i)}function _i(e,t,i,o,r){const a=e-i;let s;return s=a<0?Math.min(-a,1+a-r):a>1?Math.min(Math.max(a-r,0),1-a):0,Math.max(s,di(t,o,r))}class pi{constructor(){this._boundingVolumeCache=new hi(this._computeTileBoundingVolume);}prepareNextFrame(){this._boundingVolumeCache.swapBuffers();}distanceToTile2d(e,t,i,o){const r=1<4}allowWorldCopies(){return !1}getTileBoundingVolume(e,t,i,o){return this._boundingVolumeCache.getTileBoundingVolume(e,t,i,o)}_computeTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}if(n/=t.bu,l/=t.bu,n+=1,l+=1,e.z<=0)return ui.fromAabb([-l,-l,-l],[l,l,l]);if(1===e.z)return ui.fromAabb([0===e.x?-l:0,0===e.y?0:-l,-l],[0===e.x?0:l,0===e.y?l:0,l]);{const i=[ti(0,0,e.x,e.y,e.z),ti(t.$,0,e.x,e.y,e.z),ti(t.$,t.$,e.x,e.y,e.z),ti(0,t.$,e.x,e.y,e.z)],o=[];for(const e of i)o.push(t.aR([],e,l));if(l!==n)for(const e of i)o.push(t.aR([],e,n));0===e.y&&o.push([0,1,0]),e.y===(1<=(1<{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._coveringTilesDetailsProvider=new pi;}clone(){const e=new fi;return e.apply(this),e}apply(e,t){this._globeLatitudeErrorCorrectionRadians=t||0,this._helper.apply(e);}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const e=t.bp();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(e){const{overscaledTileID:t,applyGlobeMatrix:i}=e,o=this._helper.getMercatorTileCoordinates(t);return {mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:o,clippingPlane:this._cachedClippingPlane,projectionTransition:i?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(e){const i=this.pitchInRadians,o=this.cameraToCenterDistance/e,r=Math.sin(i)*o,a=Math.cos(i)*o+1,s=1/Math.sqrt(r*r+a*a)*1;let n=-r,l=a;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];t.bw(h,h,[0,0,0],-this.bearingInRadians),t.bx(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.by(h,h,[0,0,0],this.center.lng*Math.PI/180);const u=1/t.aZ(h);return t.aR(h,h,u),[...h,-s*u]}isLocationOccluded(e){return !this.isSurfacePointVisible(ii(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,o=this._helper._center.lat*Math.PI/180,r=Math.cos(o),a=[Math.sin(i)*r,Math.sin(o),Math.cos(i)*r],s=[a[2],0,-a[0]],n=[0,0,0];t.aW(n,s,a),t.aV(s,s),t.aV(n,n);const l=[0,0,0];return t.aV(l,[s[0]*e[0]+n[0]*e[1]+a[0]*e[2],s[1]*e[0]+n[1]*e[1]+a[1]*e[2],s[2]*e[0]+n[2]*e[1]+a[2]*e[2]]),l}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(e,i,o){const r=function(e,i,o){const r=1/(1<a&&(a=i),on&&(n=o);}const h=[c.lng+s,c.lat+l,c.lng+a,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new G(h)}getConstrained(e,i){const o=t.ah(e.lat,-t.ai,t.ai),r=t.ah(+i,this.minZoom+si(0,o),this.maxZoom);return {center:new t.S(e.lng,o),zoom:r}}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,i){const o=ii(this.unprojectScreenPoint(i)),r=ii(e),a=t.bp();t.bB(a);const s=t.bp();t.by(s,o,a,-this.center.lng*Math.PI/180),t.bx(s,s,a,this.center.lat*Math.PI/180);const n=r[0]*r[0]+r[2]*r[2],l=s[0]*s[0];if(n=-g&&p<=g,b=f>=-g&&f<=g;let x,y;if(v&&b){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.bD(u,e)+t.bD(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return !1;const i=t.bv();return t.aw(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const o=t.aX(e,i),r=t.bp(),a=t.bp();t.aR(a,i,o),t.aU(r,e,a);const s=1-t.aX(r,r);if(s<0)return null;const n=t.aX(e,e)-1,l=-o+(o<0?1:-1)*Math.sqrt(s),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,o=this.getRayDirectionFromPixel(e),r=this.rayPlanetIntersection(i,o);if(r){const e=t.bp();t.aS(e,i,[o[0]*r.tMin,o[1]*r.tMin,o[2]*r.tMin]);const a=t.bp();return t.aV(a,e),ri(a)}const a=this._cachedClippingPlane,s=a[0]*o[0]+a[1]*o[1]+a[2]*o[2],n=-t.b1(a,i)/s,l=t.bp();if(n>0)t.aS(l,i,[o[0]*n,o[1]*n,o[2]*n]);else {const e=t.bp();t.aS(e,i,[2*o[0],2*o[1],2*o[2]]);const r=t.b1(this._cachedClippingPlane,e);t.aU(l,e,[this._cachedClippingPlane[0]*r,this._cachedClippingPlane[1]*r,this._cachedClippingPlane[2]*r]);}const c=function(e){const i=t.bp();return i[0]=e[0]*-e[3],i[1]=e[1]*-e[3],i[2]=e[2]*-e[3],{center:i,radius:Math.sqrt(1-e[3]*e[3])}}(a);return ri(function(e,i,o){const r=t.bp();t.aU(r,o,e);const a=t.bp();return t.bq(a,e,r,i/t.a$(r)),a}(c.center,c.radius,l))}getMatrixForModel(e,i){const o=t.S.convert(e),r=1/t.bu,a=t.b9();return t.bz(a,a,o.lng/180*Math.PI),t.b7(a,a,-o.lat/180*Math.PI),t.M(a,a,[0,0,1+i/t.bu]),t.b7(a,a,.5*Math.PI),t.N(a,a,[r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=this.getProjectionData({overscaledTileID:new t.Z(0,0,0,0,0),applyGlobeMatrix:e});return i.tileMercatorCoords=[0,0,1,1],i}getFastPathSimpleProjectionMatrix(e){}}class gi{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame(),this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame();}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._globeness=1,this._mercatorTransform=new Lt,this._verticalPerspectiveTransform=new fi;}clone(){const e=new gi;return e._globeness=this._globeness,e._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,e.apply(this),e}apply(e){this._helper.apply(e),this._mercatorTransform.apply(this),this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians);}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){const t=this._mercatorTransform.getProjectionData(e),i=this._verticalPerspectiveTransform.getProjectionData(e);return {mainMatrix:this.isGlobeRendering?i.mainMatrix:t.mainMatrix,clippingPlane:i.clippingPlane,tileMercatorCoords:i.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return t.bk(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return t.bk(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,i,o){const r=this._mercatorTransform.getPitchedTextCorrection(e,i,o),a=this._verticalPerspectiveTransform.getPitchedTextCorrection(e,i,o);return t.bk(r,a,this._globeness)}projectTileCoordinates(e,t,i,o){return this.currentTransform.projectTileCoordinates(e,t,i,o)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ);}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this._mercatorTransform.recalculateZoomAndCenter(e),this._verticalPerspectiveTransform.recalculateZoomAndCenter(e);}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e);}getBounds(){return this.currentTransform.getBounds()}getConstrained(e,t){return this.currentTransform.getConstrained(e,t)}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,t){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,t),void this.apply(this._mercatorTransform);this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform);}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getMatrixForModel(e,t){return this.currentTransform.getMatrixForModel(e,t)}getProjectionDataForCustomLayer(e=!0){const t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;const i=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return i.fallbackMatrix=t.mainMatrix,i}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}}class vi{get useGlobeControls(){return !0}handlePanInertia(e,i){const o=ni(e,i);return Math.abs(o.lng-i.center.lng)>180&&(o.lng=i.center.lng+179.5*Math.sign(o.lng-i.center.lng)),{easingCenter:o,easingOffset:new t.P(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){const o=e.around,r=i.screenPointToLocation(o);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const a=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const s=i.zoom-a;if(0===s)return;const n=t.bA(i.center.lng,r.lng),l=n/(Math.abs(n/180)+1),c=t.bA(i.center.lat,r.lat),h=i.getRayDirectionFromPixel(o),u=i.cameraPosition,d=-1*t.aX(u,h),_=t.bp();t.aS(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.aZ(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=oi(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.bn(f,.9,.5,1,.25),v=(1-t.af(-s))*Math.min(m,g),b=i.center.lat,x=i.zoom,y=new t.S(i.center.lng+l*v,t.ah(i.center.lat+c*v,-t.ai,t.ai));i.setLocationAtPoint(r,o);const w=i.center,T=t.bn(Math.abs(n),45,85,0,1),P=t.bn(f,.75,.35,0,1),C=Math.pow(Math.max(T,P),.25),I=t.bA(w.lng,y.lng),M=t.bA(w.lat,y.lat);i.setCenter(new t.S(w.lng+I*C,w.lat+M*C).wrap()),i.setZoom(x+si(b,i.center.lat));}handleMapControlsPan(e,t,i){if(!e.panDelta)return;const o=t.center.lat,r=t.zoom;t.setCenter(ni(e.panDelta,t).wrap()),t.setZoom(r+si(o,t.center.lat));}cameraForBoxAndBearing(e,i,o,r,a){const s=Bt(e,i,o,r,a),n=i.left/a.width*2-1,l=(a.width-i.right)/a.width*2-1,c=i.top/a.height*-2+1,h=(a.height-i.bottom)/a.height*-2+1,u=t.bA(o.getWest(),o.getEast())<0,d=u?o.getEast():o.getWest(),_=u?o.getWest():o.getEast(),p=Math.max(o.getNorth(),o.getSouth()),m=Math.min(o.getNorth(),o.getSouth()),f=d+.5*t.bA(d,_),g=p+.5*t.bA(p,m),v=a.clone();v.setCenter(s.center),v.setBearing(s.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(s.zoom);const b=v.modelViewProjectionMatrix,x=[ii(o.getNorthWest()),ii(o.getNorthEast()),ii(o.getSouthWest()),ii(o.getSouthEast()),ii(new t.S(_,g)),ii(new t.S(d,g)),ii(new t.S(f,p)),ii(new t.S(f,m))],y=ii(s.center);let w=Number.POSITIVE_INFINITY;for(const e of x)n<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",n))),l>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",l))),c>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",c))),h<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",h)));if(Number.isFinite(w)&&0!==w)return s.zoom=v.zoom+t.ak(w),s;kt();}handleJumpToCenterZoom(e,i){const o=e.center.lat,r=e.getConstrained(i.center?t.S.convert(i.center):e.center,e.zoom).center;e.setCenter(r.wrap());const a=void 0!==i.zoom?+i.zoom:e.zoom+si(o,r.lat);e.zoom!==a&&e.setZoom(a);}handleEaseTo(e,i){const o=e.zoom,r=e.center,a=e.padding,s={roll:e.roll,pitch:e.pitch,bearing:e.bearing},n={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},l=void 0!==i.zoom,c=!e.isPaddingEqual(i.padding);let h=!1;const u=i.center?t.S.convert(i.center):r,d=e.getConstrained(u,o).center;St(e,d);const _=e.clone();_.setCenter(d),_.setZoom(l?+i.zoom:o+si(r.lat,u.lat)),_.setBearing(i.bearing);const p=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));_.setLocationAtPoint(d,p);const m=(i.offset&&i.offsetAsPoint.mag())>0?_.center:d,f=l?+i.zoom:o+si(r.lat,m.lat),g=o+si(r.lat,0),v=f+si(m.lat,0),b=t.bA(r.lng,m.lng),x=t.bA(r.lat,m.lat),y=t.af(v-g);return h=f!==o,{easeFunc:o=>{if(t.be(s,n)||Ft({startEulerAngles:s,endEulerAngles:n,tr:e,k:o,useSlerp:s.roll!=n.roll}),c&&e.interpolatePadding(a,i.padding,o),i.around)t.w("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=v>g?Math.min(2,y):Math.max(.5,y),i=Math.pow(t,1-o),a=ci(r,b,x,o*i);e.setCenter(a.wrap());}if(h){const i=t.C.number(g,v,o)+si(0,e.center.lat);e.setZoom(i);}},isZooming:h,elevationCenter:m}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.center,a=e.zoom,s=e.padding,n=!e.isPaddingEqual(i.padding),l=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),a).center,c=o?+i.zoom:e.zoom+si(e.center.lat,l.lat),h=e.clone();h.setCenter(l),h.setZoom(c),h.setBearing(i.bearing);const u=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));h.setLocationAtPoint(l,u);const d=h.center;St(e,d);const _=function(e,i,o){const r=ii(i),a=ii(o),s=t.aX(r,a),n=Math.acos(s),l=ei(e);return n/(2*Math.PI)*l}(e,r,d),p=a+si(r.lat,0),m=c+si(d.lat,0),f=t.af(m-p);let g;if("number"==typeof i.minZoom){const o=+i.minZoom+si(d.lat,0),r=Math.min(o,p,m)+si(0,d.lat),a=e.getConstrained(d,r).zoom+si(d.lat,0);g=t.af(a-p);}const v=t.bA(r.lng,d.lng),b=t.bA(r.lat,d.lat);return {easeFunc:(o,a,l,h)=>{const u=ci(r,v,b,l);n&&e.interpolatePadding(s,i.padding,o);const _=1===o?d:u;e.setCenter(_.wrap());const m=p+t.ak(a);e.setZoom(1===o?c:m+si(0,_.lat));},scaleOfZoom:f,targetCenter:d,scaleOfMinZoom:g,pixelPathLength:_}}static solveVectorScale(e,t,i,o,r){const a="x"===o?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],s=[i[3],i[7],i[11],i[15]],n=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],l=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],c=t[0]*a[0]+t[1]*a[1]+t[2]*a[2],h=t[0]*s[0]+t[1]*s[1]+t[2]*s[2];return c+r*l===n+r*h||s[3]*(n-c)+a[3]*(h-l)+n*h==c*l?null:(c+a[3]-r*h-r*s[3])/(c-n-r*h+r*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.y(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),yi=t.bE();class wi extends t.E{constructor(e,i={}){var o,r;super(),this._rtlPluginLoaded=()=>{for(const e in this.sourceCaches){const t=this.sourceCaches[e].getSource().type;"vector"!==t&&"geojson"!==t||this.sourceCaches[e].reload();}},this.map=e,this.dispatcher=new F(k(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.imageManager=new b,this.imageManager.setEventedParent(this);const a=(null===(o=e._container)||void 0===o?void 0:o.lang)||"undefined"!=typeof document&&(null===(r=document.documentElement)||void 0===r?void 0:r.lang)||void 0;this.glyphManager=new T(e._requestManager,i.localIdeographFontFamily,a),this.lineAtlas=new E(256,512),this.crossTileSymbolIndex=new vt,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.bF,this._loaded=!1,this._availableImages=[],this._globalState={},this._resetUpdates(),this.dispatcher.broadcast("SR",t.bG()),oe().on(ee,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.sourceCaches[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}setGlobalStateProperty(e,i){var o,r,a;this._checkLoaded();const s=null===i?null!==(a=null===(r=null===(o=this.stylesheet.state)||void 0===o?void 0:o[e])||void 0===r?void 0:r.default)&&void 0!==a?a:null:i;if(t.bH(s,this._globalState[e]))return this;this._globalState[e]=s,this._applyGlobalStateChanges([e]);}getGlobalState(){return this._globalState}setGlobalState(e){this._checkLoaded();const i=[];for(const o in e)!t.bH(this._globalState[o],e[o].default)&&(i.push(o),this._globalState[o]=e[o].default);this._applyGlobalStateChanges(i);}_applyGlobalStateChanges(e){if(0===e.length)return;const t=new Set,i={};for(const o of e){i[o]=this._globalState[o];for(const e in this._layers){const i=this._layers[e],r=i.getLayoutAffectingGlobalStateRefs(),a=i.getPaintAffectingGlobalStateRefs();if(r.has(o)&&t.add(i.source),a.has(o))for(const{name:e,value:t}of a.get(o))this._updatePaintProperty(i,e,t);}}this.dispatcher.broadcast("UGS",i);for(const e in this.sourceCaches)t.has(e)&&(this._reloadSource(e),this._changed=!0);}loadURL(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const r=this.map._requestManager.transformRequest(e,"Style");this._loadStyleRequest=new AbortController;const a=this._loadStyleRequest;t.j(r,this._loadStyleRequest).then((e=>{this._loadStyleRequest=null,this._load(e.data,i,o);})).catch((e=>{this._loadStyleRequest=null,e&&!a.signal.aborted&&this.fire(new t.k(e));}));}loadJSON(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,s.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=!1!==i.validate,this._load(e,i,o);})).catch((()=>{}));}loadEmpty(){this.fire(new t.l("dataloading",{dataType:"style"})),this._load(yi,{validate:!1});}_load(e,i,o){var r,a;let s=i.transformStyle?i.transformStyle(o,e):e;if(!i.validate||!xi(this,t.z(s))){s=Object.assign({},s),this._loaded=!0,this.stylesheet=s;for(const e in s.sources)this.addSource(e,s.sources[e],{validate:!1});s.sprite?this._loadSprite(s.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(s.glyphs),this._createLayers(),this.light=new I(this.stylesheet.light),this._setProjectionInternal((null===(r=this.stylesheet.projection)||void 0===r?void 0:r.type)||"mercator"),this.sky=new S(this.stylesheet.sky),this.map.setTerrain(null!==(a=this.stylesheet.terrain)&&void 0!==a?a:null),this.fire(new t.l("data",{dataType:"style"})),this.fire(new t.l("style.load"));}}_createLayers(){var e;const i=t.bI(this.stylesheet.layers);this.setGlobalState(null!==(e=this.stylesheet.state)&&void 0!==e?e:null),this.dispatcher.broadcast("SL",i),this._order=i.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const e of i){const i=t.bJ(e,this._globalState);i.setEventedParent(this,{layer:{id:e.id}}),this._layers[e.id]=i;}}_loadSprite(e,i=!1,o=void 0){let r;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=f(e),n=o>1?"@2x":"",l={},c={};for(const{id:e,url:o}of a){const a=i.transformRequest(g(o,n,".json"),"SpriteJSON");l[e]=t.j(a,r);const s=i.transformRequest(g(o,n,".png"),"SpriteImage");c[e]=p.getImage(s,r);}return yield Promise.all([...Object.values(l),...Object.values(c)]),function(e,i){return t._(this,void 0,void 0,(function*(){const t={};for(const o in e){t[o]={};const r=s.getImageCanvasContext((yield i[o]).data),a=(yield e[o]).data;for(const e in a){const{width:i,height:s,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=a[e];t[o][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:s,x:n,y:l,context:r}};}}return t}))}(l,c)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const o=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of o)this.imageManager.removeImage(e),this._changedImages[e]=!0;for(const o in e[t]){const r="default"===t?o:`${t}:${o}`;this._spritesImagesIds[t].push(r),r in this.imageManager.images?this.imageManager.updateImage(r,e[t][o],!1):this.imageManager.addImage(r,e[t][o]),i&&(this._changedImages[r]=!0);}}})).catch((e=>{this._spriteRequest=null,r=e,this.fire(new t.k(r));})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),i&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"})),o&&o(r);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}_validateLayer(e){const i=this.sourceCaches[e.source];if(!i)return;const o=e.sourceLayer;if(!o)return;const r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.k(new Error(`Source layer "${o}" does not exist on source "${r.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(const e in this.sourceCaches)if(!this.sourceCaches[e].loaded())return !1;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=!1){const o=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.bK(o):o);const r=[];for(const a of e)if(o[a]){const e=i?t.bK(o[a]):o[a];r.push(e);}return r}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){var e,t,i;if(null===(e=this.light)||void 0===e?void 0:e.hasTransition())return !0;if(null===(t=this.sky)||void 0===t?void 0:t.hasTransition())return !0;if(null===(i=this.projection)||void 0===i?void 0:i.hasTransition())return !0;for(const e in this.sourceCaches)if(this.sourceCaches[e].hasTransition())return !0;for(const e in this._layers)if(this._layers[e].hasTransition())return !0;return !1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const o={};for(const e in this.sourceCaches){const t=this.sourceCaches[e];o[e]=t.used,t.used=!1;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.sourceCaches[i.source].used=!0);}for(const e in o){const i=this.sourceCaches[e];!!o[e]!=!!i.used&&i.fire(new t.l("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.projection.recalculate(e),this.z=e.zoom,i&&this.fire(new t.l("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,!1),removedIds:t});}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1;}setState(e,i={}){var o;this._checkLoaded();const r=this.serialize();if(e=i.transformStyle?i.transformStyle(r,e):e,(null===(o=i.validate)||void 0===o||o)&&xi(this,t.z(e)))return !1;(e=t.bK(e)).layers=t.bI(e.layers);const a=t.bL(r,e),s=this._getOperationsToPerform(a);if(s.unimplemented.length>0)throw new Error(`Unimplemented: ${s.unimplemented.join(", ")}.`);if(0===s.operations.length)return !1;for(const e of s.operations)e();return this.stylesheet=e,this._serializedLayers=null,!0}_getOperationsToPerform(e){const t=[],i=[];for(const o of e)switch(o.command){case "setCenter":case "setZoom":case "setBearing":case "setPitch":case "setRoll":continue;case "addLayer":t.push((()=>this.addLayer.apply(this,o.args)));break;case "removeLayer":t.push((()=>this.removeLayer.apply(this,o.args)));break;case "setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,o.args)));break;case "setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,o.args)));break;case "setFilter":t.push((()=>this.setFilter.apply(this,o.args)));break;case "addSource":t.push((()=>this.addSource.apply(this,o.args)));break;case "removeSource":t.push((()=>this.removeSource.apply(this,o.args)));break;case "setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,o.args)));break;case "setLight":t.push((()=>this.setLight.apply(this,o.args)));break;case "setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,o.args)));break;case "setGlyphs":t.push((()=>this.setGlyphs.apply(this,o.args)));break;case "setSprite":t.push((()=>this.setSprite.apply(this,o.args)));break;case "setTerrain":t.push((()=>this.map.setTerrain.apply(this,o.args)));break;case "setSky":t.push((()=>this.setSky.apply(this,o.args)));break;case "setProjection":this.setProjection.apply(this,o.args);break;case "setGlobalState":t.push((()=>this.setGlobalState.apply(this,o.args)));break;case "setTransition":t.push((()=>{}));break;default:i.push(o.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,o={}){if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.z.source,`sources.${e}`,i,null,o))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const r=this.sourceCaches[e]=new xe(e,i,this.dispatcher);r.style=this,r.setEventedParent(this,(()=>({isSourceLoaded:r.loaded(),source:r.serialize(),sourceId:e}))),r.onAdd(this.map),this._changed=!0;}removeSource(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.k(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],i.fire(new t.l("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=!0;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error(`There is no source with this ID=${e}`);const i=this.sourceCaches[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=!0;}getSource(e){return this.sourceCaches[e]&&this.sourceCaches[e].getSource()}addLayer(e,i,o={}){this._checkLoaded();const r=e.id;if(this.getLayer(r))return void this.fire(new t.k(new Error(`Layer "${r}" already exists on this map.`)));let a;if("custom"===e.type){if(xi(this,t.bM(e)))return;a=t.bJ(e,this._globalState);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(r,e.source),e=t.bK(e),e=t.e(e,{source:r})),this._validate(t.z.layer,`layers.${r}`,e,{arrayIndex:-1},o))return;a=t.bJ(e,this._globalState),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}});}const s=i?this._order.indexOf(i):this._order.length;if(i&&-1===s)this.fire(new t.k(new Error(`Cannot add layer "${r}" before non-existing layer "${i}".`)));else {if(this._order.splice(s,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){const e=this._removedLayers[r];delete this._removedLayers[r],e.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=!0,!this._layers[e])return void this.fire(new t.k(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const o=this._order.indexOf(e);this._order.splice(o,1);const r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.k(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.k(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,o){this._checkLoaded();const r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.k(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,o={}){this._checkLoaded();const r=this.getLayer(e);if(r){if(!t.bH(r.filter,i))return null==i?(r.setFilter(void 0),void this._updateLayer(r)):void(this._validate(t.z.filter,`layers.${r.id}.filter`,i,null,o)||(r.setFilter(t.bK(i)),this._updateLayer(r)))}else this.fire(new t.k(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.bK(this.getLayer(e).filter)}setLayoutProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.k(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getPaintProperty(i),o)||this._updatePaintProperty(a,i,o,r):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}_updatePaintProperty(e,t,i,o={}){e.setPaintProperty(t,i,o)&&this._updateLayer(e),this._changed=!0,this._updatedPaintProps[e.id]=!0,this._serializedLayers=null;}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0===a)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const s=a.getSource().type;"geojson"===s&&r?this.fire(new t.k(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==s||r?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const o=e.source,r=this.sourceCaches[o];if(void 0===r)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const a=r.getSource().type,s="vector"===a?e.sourceLayer:void 0;"vector"!==a||s?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.k(new Error("A feature id is required to remove its specific state property."))):r.removeFeatureState(s,e.id,i):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r)return "vector"!==r.getSource().type||o?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id)):void this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.k(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.bN(this.sourceCaches,(e=>e.serialize())),i=this._serializeByIds(this._order,!0),o=this.map.getTerrain()||void 0,r=this.stylesheet;return t.bO({version:r.version,name:r.name,metadata:r.metadata,light:r.light,sky:r.sky,center:r.center,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,sprite:r.sprite,glyphs:r.glyphs,transition:r.transition,projection:r.projection,sources:e,layers:i,terrain:o},(e=>void 0!==e))}_updateLayer(e){this._updatedLayers[e.id]=!0,e.source&&!this._updatedSources[e.source]&&"raster"!==this.sourceCaches[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.sourceCaches[e.source].pause()),this._serializedLayers=null,this._changed=!0;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},o=[];for(let r=this._order.length-1;r>=0;r--){const a=this._order[r];if(t(a)){i[a]=r;for(const t of e){const e=t[a];if(e)for(const t of e)o.push(t);}}}o.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const r=[];for(let a=this._order.length-1;a>=0;a--){const s=this._order[a];if(t(s))for(let e=o.length-1;e>=0;e--){const t=o[e].feature;if(i[t.layer.id]this.map.terrain.getElevation(e,t,i):void 0));return this.placement&&a.push(function(e,t,i,o,r,a,s){const n={},l=a.queryRenderedSymbols(o),c=[];for(const e of Object.keys(l).map(Number))c.push(s[e]);c.sort(N);for(const i of c){const o=i.featureIndex.lookupSymbolFeatures(l[i.bucketInstanceId],t,i.bucketIndex,i.sourceLayerIndex,{filterSpec:r.filter,globalState:r.globalState},r.layers,r.availableImages,e);for(const e in o){const t=n[e]=n[e]||[],r=o[e];r.sort(((e,t)=>{const o=i.featureSortOrder;if(o){const i=o.indexOf(e.featureIndex);return o.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of r)t.push(e);}}return function(e,t,i){for(const o in e)for(const r of e[o])U(r,i[t[o].source]);return e}(n,e,i)}(this._layers,s,this.sourceCaches,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(a)}querySourceFeatures(e,i){(null==i?void 0:i.filter)&&this._validate(t.z.filter,"querySourceFeatures.filter",i.filter,null,i);const o=this.sourceCaches[e];return o?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),o=[],r={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const o=this.crossTileSymbolIndex.addLayer(i,l[i.source],e.center.lng);a=a||o;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((r=r||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(s.now(),e.zoom))&&(this.pauseablePlacement=new _t(e,this.map.terrain,this._order,r,t,i,o,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(s.now()),n=!0),a&&this.pauseablePlacement.placement.setStale()),n||a)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,l[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(s.now())}_releaseSymbolFadeTiles(){for(const e in this.sourceCaches)this.sourceCaches[e].releaseSymbolFadeTiles();}getImages(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.z.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}addSprite(e,i,o={},r){this._checkLoaded();const a=[{id:e,url:i}],s=[...f(this.stylesheet.sprite),...a];this._validate(t.z.sprite,"sprite",s,null,o)||(this.stylesheet.sprite=s,this._loadSprite(a,!0,r));}removeSprite(e){this._checkLoaded();const i=f(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=!0;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:void 0,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}else this.fire(new t.k(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return f(this.stylesheet.sprite)}setSprite(e,i={},o){this._checkLoaded(),e&&this._validate(t.z.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,!0,o):(this._unloadSprite(),o&&o(null)));}}var Ti=t.aJ([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class Pi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;}bind(e,t,i,o,r,a,s,n,l){this.context=e;let c=this.boundPaintVertexBuffers.length!==o.length;for(let e=0;!c&&e({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:o?o.properties.get("fog-color"):t.bf.white,u_fog_ground_blend:o?o.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:a?0:o?o.calculateFogBlendOpacity(r):0,u_horizon_color:o?o.properties.get("horizon-color"):t.bf.white,u_horizon_fog_blend:o?o.properties.get("horizon-fog-blend"):1,u_is_globe_mode:a?1:0}),Ii={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function Mi(e){const t=[];for(let i=0;i({u_depth:new t.bP(e,i.u_depth),u_terrain:new t.bP(e,i.u_terrain),u_terrain_dim:new t.bg(e,i.u_terrain_dim),u_terrain_matrix:new t.bR(e,i.u_terrain_matrix),u_terrain_unpack:new t.bS(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.bg(e,i.u_terrain_exaggeration)}))(e,C),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.bR(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.bS(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.bS(e,i.u_projection_clipping_plane),u_projection_transition:new t.bg(e,i.u_projection_transition),u_projection_fallback_matrix:new t.bR(e,i.u_projection_fallback_matrix)}))(e,C),this.binderUniforms=o?o.getUniforms(e,C):[];}draw(e,t,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v){const b=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(o),e.setColorMode(r),e.setCullFace(a),n){e.activeTexture.set(b.TEXTURE2),b.bindTexture(b.TEXTURE_2D,n.depthTexture),e.activeTexture.set(b.TEXTURE3),b.bindTexture(b.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[Ii[e]].set(l[e]);if(s)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(s[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let x=0;switch(t){case b.LINES:x=2;break;case b.TRIANGLES:x=3;break;case b.LINE_STRIP:x=1;}for(const i of d.get()){const o=i.vaos||(i.vaos={});(o[c]||(o[c]=new Pi)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),b.drawElements(t,i.primitiveLength*x,b.UNSIGNED_SHORT,i.primitiveOffset*x*2);}}}function Ei(e,i,o){const r=1/t.aC(o,1,i.transform.tileZoom),a=Math.pow(2,o.tileID.overscaledZ),s=o.tileSize*Math.pow(2,i.transform.tileZoom)/a,n=s*(o.tileID.canonical.x+o.tileID.wrap*a),l=s*o.tileID.canonical.y;return {u_image:0,u_texsize:o.imageAtlasTexture.size,u_scale:[r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Ri=(e,i,o,r)=>{const a=e.style.light,s=a.properties.get("position"),n=[s.x,s.y,s.z],l=t.bV();"viewport"===a.properties.get("anchor")&&t.bW(l,e.transform.bearingInRadians),t.bX(n,n,l);const c=e.transform.transformLightDirection(n),h=a.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:o,u_fill_translate:r}},zi=(e,i,o,r,a,s,n)=>t.e(Ri(e,i,o,r),Ei(s,e,n),{u_height_factor:-Math.pow(2,a.overscaledZ)/n.tileSize/8}),Di=(e,i,o,r)=>t.e(Ei(i,e,o),{u_fill_translate:r}),Ai=(e,t)=>({u_world:e,u_fill_translate:t}),Li=(e,i,o,r,a)=>t.e(Di(e,i,o,a),{u_world:r}),ki=(e,i,o,r,a)=>{const s=e.transform;let n,l,c=0;if("map"===o.paint.get("circle-pitch-alignment")){const e=t.aC(i,1,s.zoom);n=!0,l=[e,e],c=e/(t.$*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*a;}else n=!1,l=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===o.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:r}},Fi=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),Bi=e=>({u_viewport_size:[e.width,e.height]}),Oi=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),ji=(e,i,o,r)=>{const a=t.aC(e,1,i)/(t.$*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*r;return {u_extrude_scale:t.aC(e,1,i),u_intensity:o,u_globe_extrude_scale:a}},Ni=(e,i,o,r)=>{const a=t.L();t.bY(a,0,e.width,e.height,0,0,1);const s=e.context.gl;return {u_matrix:a,u_world:[s.drawingBufferWidth,s.drawingBufferHeight],u_image:o,u_color_ramp:r,u_opacity:i.paint.get("heatmap-opacity")}},Ui=(e,t,i)=>{const o=i.paint.get("hillshade-accent-color");let r;switch(i.paint.get("hillshade-method")){case "basic":r=4;break;case "combined":r=1;break;case "igor":r=2;break;case "multidirectional":r=3;break;default:r=0;}const a=i.getIlluminationProperties();for(let t=0;t{const o=i.stride,r=t.L();return t.bY(r,0,t.$,-t.$,0,0,1),t.M(r,r,[0,-t.$,0]),{u_matrix:r,u_image:1,u_dimension:[o,o],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function Gi(e,i){const o=Math.pow(2,i.canonical.z),r=i.canonical.y;return [new t.a1(0,r/o).toLngLat().lat,new t.a1(0,(r+1)/o).toLngLat().lat]}const Vi=(e,t,i=0)=>({u_image:0,u_unpack:t.getUnpackVector(),u_dimension:[t.stride,t.stride],u_elevation_stops:1,u_color_stops:4,u_color_ramp_size:i,u_opacity:e.paint.get("color-relief-opacity")}),$i=(e,i,o,r)=>{const a=e.transform;return {u_translation:Ki(e,i,o),u_ratio:r/t.aC(i,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},qi=(e,i,o,r,a)=>t.e($i(e,i,o,r),{u_image:0,u_image_height:a}),Wi=(e,i,o,r,a)=>{const s=e.transform,n=Xi(i,s);return {u_translation:Ki(e,i,o),u_texsize:i.imageAtlasTexture.size,u_ratio:r/t.aC(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},Hi=(e,i,o,r,a,s)=>{const n=e.lineAtlas,l=Xi(i,e.transform),c="round"===o.layout.get("line-cap"),h=n.getDash(a.from,c),u=n.getDash(a.to,c),d=h.width*s.fromScale,_=u.width*s.toScale;return t.e($i(e,i,o,r),{u_patternscale_a:[l/d,-h.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*e.pixelRatio)/2,u_image:0,u_tex_y_a:h.y,u_tex_y_b:u.y,u_mix:s.t})};function Xi(e,i){return 1/t.aC(e,1,i.tileZoom)}function Ki(e,i,o){return t.aD(e.transform,i,o.paint.get("line-translate"),o.paint.get("line-translate-anchor"))}const Yi=(e,t,i,o,r)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*o.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:o.paint.get("raster-brightness-min"),u_brightness_high:o.paint.get("raster-brightness-max"),u_saturation_factor:(s=o.paint.get("raster-saturation"),s>0?1-1/(1.001-s):-s),u_contrast_factor:(a=o.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Qi(o.paint.get("raster-hue-rotate")),u_coords_top:[r[0].x,r[0].y,r[1].x,r[1].y],u_coords_bottom:[r[3].x,r[3].y,r[2].x,r[2].y]};var a,s;};function Qi(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const Ji=(e,t,i,o,r,a,s,n,l,c,h,u,d)=>{const _=s.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+o,u_is_along_line:r,u_is_variable_anchor:a,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},eo=(e,i,o,r,a,s,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.e(Ji(e,i,o,r,a,s,n,l,c,h,u,d,p),{u_gamma_scale:r?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:1})},to=(e,i,o,r,a,s,n,l,c,h,u,d,_)=>t.e(eo(e,i,o,r,a,s,n,l,c,h,!0,u,0,_),{u_texsize_icon:d,u_texture_icon:1}),io=(e,t)=>({u_opacity:e,u_color:t}),oo=(e,i,o,r,a)=>t.e(function(e,i,o,r){const a=o.imageManager.getPattern(e.from.toString()),s=o.imageManager.getPattern(e.to.toString()),{width:n,height:l}=o.imageManager.getPixelSize(),c=Math.pow(2,r.tileID.overscaledZ),h=r.tileSize*Math.pow(2,o.transform.tileZoom)/c,u=h*(r.tileID.canonical.x+r.tileID.wrap*c),d=h*r.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:s.tl,u_pattern_br_b:s.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:s.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.aC(r,1,o.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(o,a,i,r),{u_opacity:e}),ro=(e,t)=>{},ao={fillExtrusion:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_height_factor:new t.bg(e,i.u_height_factor),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.bU(e,i.u_world),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_scale_with_map:new t.bP(e,i.u_scale_with_map),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_extrude_scale:new t.bU(e,i.u_extrude_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale),u_translate:new t.bU(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.bU(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.bU(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.bQ(e,i.u_color),u_overlay:new t.bP(e,i.u_overlay),u_overlay_scale:new t.bg(e,i.u_overlay_scale)}),depth:ro,clippingMask:ro,heatmap:(e,i)=>({u_extrude_scale:new t.bg(e,i.u_extrude_scale),u_intensity:new t.bg(e,i.u_intensity),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_color_ramp:new t.bP(e,i.u_color_ramp),u_opacity:new t.bg(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.bP(e,i.u_image),u_latrange:new t.bU(e,i.u_latrange),u_exaggeration:new t.bg(e,i.u_exaggeration),u_altitudes:new t.b_(e,i.u_altitudes),u_azimuths:new t.b_(e,i.u_azimuths),u_accent:new t.bQ(e,i.u_accent),u_method:new t.bP(e,i.u_method),u_shadows:new t.bZ(e,i.u_shadows),u_highlights:new t.bZ(e,i.u_highlights)}),hillshadePrepare:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_image:new t.bP(e,i.u_image),u_dimension:new t.bU(e,i.u_dimension),u_zoom:new t.bg(e,i.u_zoom),u_unpack:new t.bS(e,i.u_unpack)}),colorRelief:(e,i)=>({u_image:new t.bP(e,i.u_image),u_unpack:new t.bS(e,i.u_unpack),u_dimension:new t.bU(e,i.u_dimension),u_elevation_stops:new t.bP(e,i.u_elevation_stops),u_color_stops:new t.bP(e,i.u_color_stops),u_color_ramp_size:new t.bP(e,i.u_color_ramp_size),u_opacity:new t.bg(e,i.u_opacity)}),line:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_image:new t.bP(e,i.u_image),u_image_height:new t.bg(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_texsize:new t.bU(e,i.u_texsize),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_image:new t.bP(e,i.u_image),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_patternscale_a:new t.bU(e,i.u_patternscale_a),u_patternscale_b:new t.bU(e,i.u_patternscale_b),u_sdfgamma:new t.bg(e,i.u_sdfgamma),u_image:new t.bP(e,i.u_image),u_tex_y_a:new t.bg(e,i.u_tex_y_a),u_tex_y_b:new t.bg(e,i.u_tex_y_b),u_mix:new t.bg(e,i.u_mix)}),raster:(e,i)=>({u_tl_parent:new t.bU(e,i.u_tl_parent),u_scale_parent:new t.bg(e,i.u_scale_parent),u_buffer_scale:new t.bg(e,i.u_buffer_scale),u_fade_t:new t.bg(e,i.u_fade_t),u_opacity:new t.bg(e,i.u_opacity),u_image0:new t.bP(e,i.u_image0),u_image1:new t.bP(e,i.u_image1),u_brightness_low:new t.bg(e,i.u_brightness_low),u_brightness_high:new t.bg(e,i.u_brightness_high),u_saturation_factor:new t.bg(e,i.u_saturation_factor),u_contrast_factor:new t.bg(e,i.u_contrast_factor),u_spin_weights:new t.bT(e,i.u_spin_weights),u_coords_top:new t.bS(e,i.u_coords_top),u_coords_bottom:new t.bS(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texsize_icon:new t.bU(e,i.u_texsize_icon),u_texture:new t.bP(e,i.u_texture),u_texture_icon:new t.bP(e,i.u_texture_icon),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_color:new t.bQ(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_image:new t.bP(e,i.u_image),u_pattern_tl_a:new t.bU(e,i.u_pattern_tl_a),u_pattern_br_a:new t.bU(e,i.u_pattern_br_a),u_pattern_tl_b:new t.bU(e,i.u_pattern_tl_b),u_pattern_br_b:new t.bU(e,i.u_pattern_br_b),u_texsize:new t.bU(e,i.u_texsize),u_mix:new t.bg(e,i.u_mix),u_pattern_size_a:new t.bU(e,i.u_pattern_size_a),u_pattern_size_b:new t.bU(e,i.u_pattern_size_b),u_scale_a:new t.bg(e,i.u_scale_a),u_scale_b:new t.bg(e,i.u_scale_b),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.bg(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_ele_delta:new t.bg(e,i.u_ele_delta),u_fog_matrix:new t.bR(e,i.u_fog_matrix),u_fog_color:new t.bQ(e,i.u_fog_color),u_fog_ground_blend:new t.bg(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.bg(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon_fog_blend:new t.bg(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.bg(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.bg(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_terrain_coords_id:new t.bg(e,i.u_terrain_coords_id),u_ele_delta:new t.bg(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.bg(e,i.u_input),u_output_expected:new t.bg(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.bT(e,i.u_sun_pos),u_atmosphere_blend:new t.bg(e,i.u_atmosphere_blend),u_globe_position:new t.bT(e,i.u_globe_position),u_globe_radius:new t.bg(e,i.u_globe_radius),u_inv_proj_matrix:new t.bR(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.bQ(e,i.u_sky_color),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon:new t.bU(e,i.u_horizon),u_horizon_normal:new t.bU(e,i.u_horizon_normal),u_sky_horizon_blend:new t.bg(e,i.u_sky_horizon_blend),u_sky_blend:new t.bg(e,i.u_sky_blend)})};class so{constructor(e,t,i){this.context=e;const o=e.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const no={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class lo{constructor(e,t,i,o){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=o,this.context=e;const r=e.gl;this.buffer=r.createBuffer(),e.bindVertexBuffer.set(this.buffer),r.bufferData(r.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(s,l.LINES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Fi(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),o.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!a||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.b$;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:S,angle:E});}else $e(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===o.layout.get("text-rotation-alignment");De(c,e,a,O,j,v,h,i,l.toUnwrapped(),f.width,f.height,U,t);}const $=a&&P||V,q=b||$?Yo:v?O:e.transform.clipSpaceToPixelsMatrix,W=p&&0!==o.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1);let H;H=p?c.iconsInText?to(T.kind,E,x,v,b,$,e,q,N,U,z,k,I):eo(T.kind,E,x,v,b,$,e,q,N,U,a,z,0,I):Ji(T.kind,E,x,v,b,$,e,q,N,U,a,z,I);const X={program:S,buffers:u,uniformValues:H,projectionData:Z,atlasTexture:D,atlasTextureIcon:F,atlasInterpolation:A,atlasInterpolationIcon:L,isSDF:p,hasHalo:W};if(y&&c.canOverlap){w=!0;const e=u.segments.get();for(const i of e)C.push({segments:new t.aM([i]),sortKey:i.sortKey,state:X,terrainData:R});}else C.push({segments:u.segments,sortKey:0,state:X,terrainData:R});}w&&C.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of C){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const r=i.uniformValues;i.hasHalo&&(r.u_is_halo=1,or(i.buffers,t.segments,o,e,i.program,T,u,d,r,i.projectionData,t.terrainData)),r.u_is_halo=0;}or(i.buffers,t.segments,o,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function or(e,t,i,o,r,a,s,n,l,c,h){const u=o.context;r.draw(u,u.gl.TRIANGLES,a,s,n,Ut.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,o.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function rr(e,i,o,r,a){const s=e.context,n=s.gl,l=Vt.disabled,c=new jt([n.ONE,n.ONE],t.bf.transparent,[!0,!0,!0,!0]),h=i.getBucket(o);if(!h)return;const u=r.key;let d=o.heatmapFbos.get(u);d||(d=sr(s,i.tileSize,i.tileSize),o.heatmapFbos.set(u,d)),s.bindFramebuffer.set(d.framebuffer),s.viewport.set([0,0,i.tileSize,i.tileSize]),s.clear({color:t.bf.transparent});const _=h.programConfigurations.get(o.id),p=e.useProgram("heatmap",_,!a),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),f=e.style.map.terrain.getTerrainData(r);p.draw(s,n.TRIANGLES,Zt.disabled,l,c,Ut.disabled,ji(i,e.transform.zoom,o.paint.get("heatmap-intensity"),1),f,m,o.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,o.paint,e.transform.zoom,_);}function ar(e,t,i,o,r){const a=e.context,s=a.gl,n=e.transform;a.setColorMode(e.colorModeForRenderPass());const l=nr(a,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,h.colorAttachment.get()),a.activeTexture.set(s.TEXTURE1),l.bind(s.LINEAR,s.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:r,applyGlobeMatrix:!o});e.useProgram("heatmapTexture").draw(a,s.TRIANGLES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Ni(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function sr(e,t,i){var o,r;const a=e.gl,s=a.createTexture();a.bindTexture(a.TEXTURE_2D,s),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR);const n=null!==(o=e.HALF_FLOAT)&&void 0!==o?o:a.UNSIGNED_BYTE,l=null!==(r=e.RGBA16F)&&void 0!==r?r:a.RGBA;a.texImage2D(a.TEXTURE_2D,0,l,t,i,0,a.RGBA,n,null);const c=e.createFramebuffer(t,i,!1,!1);return c.colorAttachment.set(s),c}function nr(e,i){return i.colorRampTexture||(i.colorRampTexture=new t.T(e,i.colorRamp,e.gl.RGBA)),i.colorRampTexture}function lr(e,t,i,o,r){if(!i||!o||!o.imageAtlas)return;const a=o.imageAtlas.patternPositions;let s=a[i.to.toString()],n=a[i.from.toString()];if(!s&&n&&(s=n),!n&&s&&(n=s),!s||!n){const e=r.getPaintProperty(t);s=a[e],n=a[e];}s&&n&&e.setConstantPatternPositions(s,n);}function cr(e,i,o,r,a,s,n,l){const c=e.context.gl,h="fill-pattern",u=o.paint.get(h),d=u&&u.constantOr(1),_=o.getCrossfadeParameters();let p,m,f,g,v;const b=e.transform,x=o.paint.get("fill-translate"),y=o.paint.get("fill-translate-anchor");n?(m=d&&!o.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",p=c.LINES):(m=d?"fillPattern":"fill",p=c.TRIANGLES);const w=u.constantOr(null);for(const u of r){const r=i.getTile(u);if(d&&!r.patternsLoaded())continue;const T=r.getBucket(o);if(!T)continue;const P=T.programConfigurations.get(o.id),C=e.useProgram(m,P),I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(u);d&&(e.context.activeTexture.set(c.TEXTURE0),r.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),P.updatePaintBuffers(_)),lr(P,h,w,r,o);const M=b.getProjectionData({overscaledTileID:u,applyGlobeMatrix:!l,applyTerrainMatrix:!0}),S=t.aD(b,r,x,y);if(n){g=T.indexBuffer2,v=T.segments2;const t=[c.drawingBufferWidth,c.drawingBufferHeight];f="fillOutlinePattern"===m&&d?Li(e,_,r,t,S):Ai(t,S);}else g=T.indexBuffer,v=T.segments,f=d?Di(e,_,r,S):{u_fill_translate:S};const E=e.stencilModeForClipping(u);C.draw(e.context,p,a,E,s,Ut.backCCW,f,I,M,o.id,T.layoutVertexBuffer,g,v,o.paint,e.transform.zoom,P);}}function hr(e,i,o,r,a,s,n,l){const c=e.context,h=c.gl,u="fill-extrusion-pattern",d=o.paint.get(u),_=d.constantOr(1),p=o.getCrossfadeParameters(),m=o.paint.get("fill-extrusion-opacity"),f=d.constantOr(null),g=e.transform;for(const d of r){const r=i.getTile(d),v=r.getBucket(o);if(!v)continue;const b=e.style.map.terrain&&e.style.map.terrain.getTerrainData(d),x=v.programConfigurations.get(o.id),y=e.useProgram(_?"fillExtrusionPattern":"fillExtrusion",x);_&&(e.context.activeTexture.set(h.TEXTURE0),r.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),x.updatePaintBuffers(p));const w=g.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!l,applyTerrainMatrix:!0});lr(x,u,f,r,o);const T=t.aD(g,r,o.paint.get("fill-extrusion-translate"),o.paint.get("fill-extrusion-translate-anchor")),P=o.paint.get("fill-extrusion-vertical-gradient"),C=_?zi(e,P,m,T,d,p,r):Ri(e,P,m,T);y.draw(c,c.gl.TRIANGLES,a,s,n,Ut.backCCW,C,b,w,o.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,o.paint,e.transform.zoom,x,e.style.map.terrain&&v.centroidVertexBuffer);}}function ur(e,t,i,o,r,a,s,n,l){var c;const h=e.style.projection,u=e.context,d=e.transform,_=u.gl,p=[`#define NUM_ILLUMINATION_SOURCES ${i.paint.get("hillshade-highlight-color").values.length}`],m=e.useProgram("hillshade",null,!1,p),f=!e.options.moving;for(const p of o){const o=t.getTile(p),g=o.fbo;if(!g)continue;const v=h.getMeshFromTileID(u,p.canonical,n,!0,"raster"),b=null===(c=e.style.map.terrain)||void 0===c?void 0:c.getTerrainData(p);u.activeTexture.set(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g.colorAttachment.get());const x=d.getProjectionData({overscaledTileID:p,aligned:f,applyGlobeMatrix:!l,applyTerrainMatrix:!0});m.draw(u,_.TRIANGLES,a,r[p.overscaledZ],s,Ut.backCCW,Ui(e,o,i),b,x,i.id,v.vertexBuffer,v.indexBuffer,v.segments);}}function dr(e,i,o,r,a,s,n,l,c){var h;const u=e.style.projection,d=e.context,_=e.transform,p=d.gl,m=e.useProgram("colorRelief"),f=!e.options.moving;let g=!0,v=0;for(const b of r){const r=i.getTile(b),x=r.dem;if(g){const e=p.getParameter(p.MAX_TEXTURE_SIZE),{elevationTexture:t,colorTexture:i}=o.getColorRampTextures(d,e,x.getUnpackVector());d.activeTexture.set(p.TEXTURE1),t.bind(p.NEAREST,p.CLAMP_TO_EDGE),d.activeTexture.set(p.TEXTURE4),i.bind(p.LINEAR,p.CLAMP_TO_EDGE),g=!1,v=t.size[0];}if(!x||!x.data)continue;const y=x.stride,w=x.getPixels();if(d.activeTexture.set(p.TEXTURE0),d.pixelStoreUnpackPremultiplyAlpha.set(!1),r.demTexture=r.demTexture||e.getTileTexture(y),r.demTexture){const e=r.demTexture;e.update(w,{premultiply:!1}),e.bind(p.LINEAR,p.CLAMP_TO_EDGE);}else r.demTexture=new t.T(d,w,p.RGBA,{premultiply:!1}),r.demTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE);const T=u.getMeshFromTileID(d,b.canonical,l,!0,"raster"),P=null===(h=e.style.map.terrain)||void 0===h?void 0:h.getTerrainData(b),C=_.getProjectionData({overscaledTileID:b,aligned:f,applyGlobeMatrix:!c,applyTerrainMatrix:!0});m.draw(d,p.TRIANGLES,s,a[b.overscaledZ],n,Ut.backCCW,Vi(o,r.dem,v),P,C,o.id,T.vertexBuffer,T.indexBuffer,T.segments);}}const _r=[new t.P(0,0),new t.P(t.$,0),new t.P(t.$,t.$),new t.P(0,t.$)];function pr(e,t,i,o,r,a,s,n,l=!1,c=!1){const h=o[o.length-1].overscaledZ,u=e.context,d=u.gl,_=e.useProgram("raster"),p=e.transform,m=e.style.projection,f=e.colorModeForRenderPass(),g=!e.options.moving;for(const v of o){const o=e.getDepthModeForSublayer(v.overscaledZ-h,1===i.paint.get("raster-opacity")?Zt.ReadWrite:Zt.ReadOnly,d.LESS),b=t.getTile(v);b.registerFadeDuration(i.paint.get("raster-fade-duration"));const x=t.findLoadedParent(v,0),y=t.findLoadedSibling(v),w=mr(b,x||y||null,t,i,e.transform,e.style.map.terrain);let T,P;const C="nearest"===i.paint.get("raster-resampling")?d.NEAREST:d.LINEAR;u.activeTexture.set(d.TEXTURE0),b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),u.activeTexture.set(d.TEXTURE1),x?(x.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),T=Math.pow(2,x.tileID.overscaledZ-b.tileID.overscaledZ),P=[b.tileID.canonical.x*T%1,b.tileID.canonical.y*T%1]):b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),b.texture.useMipmap&&u.extTextureFilterAnisotropic&&e.transform.pitch>20&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(v),M=p.getProjectionData({overscaledTileID:v,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),S=Yi(P||[0,0],T||1,w,i,n),E=m.getMeshFromTileID(u,v.canonical,a,s,"raster");_.draw(u,d.TRIANGLES,o,r?r[v.overscaledZ]:Vt.disabled,f,l?Ut.frontCCW:Ut.backCCW,S,I,M,i.id,E.vertexBuffer,E.indexBuffer,E.segments);}}function mr(e,i,o,r,a,n){const l=r.paint.get("raster-fade-duration");if(!n&&l>0){const r=s.now(),n=(r-e.timeAdded)/l,c=i?(r-i.timeAdded)/l:-1,h=o.getSource(),u=ge(a,{tileSize:h.tileSize,roundZoom:h.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-u)>Math.abs(e.tileID.overscaledZ-u),_=d&&e.refreshedUponExpiration?1:t.ah(d?n:1-c,0,1);return e.refreshedUponExpiration&&n>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-_}:{opacity:_,mix:0}}return {opacity:1,mix:0}}const fr=new t.bf(1,0,0,1),gr=new t.bf(0,1,0,1),vr=new t.bf(0,0,1,1),br=new t.bf(1,0,1,1),xr=new t.bf(0,1,1,1);function yr(e,t,i,o){Tr(e,0,t+i/2,e.transform.width,i,o);}function wr(e,t,i,o){Tr(e,t-i/2,0,i,e.transform.height,o);}function Tr(e,t,i,o,r,a){const s=e.context,n=s.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,o*e.pixelRatio,r*e.pixelRatio),s.clear({color:a}),n.disable(n.SCISSOR_TEST);}function Pr(e,i,o){const r=e.context,a=r.gl,s=e.useProgram("debug"),n=Zt.disabled,l=Vt.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(o);r.activeTexture.set(a.TEXTURE0);const d=i.getTileByID(o.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(o).tileSize,m=512/Math.min(p,512)*(o.overscaledZ/e.transform.zoom)*.5;let f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=` => ${o.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,o=e.context.gl,r=e.debugOverlayCanvas.getContext("2d");r.clearRect(0,0,i.width,i.height),r.shadowColor="white",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle="white",r.textBaseline="top",r.font="bold 36px Open Sans, sans-serif",r.fillText(t,5,5),r.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:o,applyGlobeMatrix:!0,applyTerrainMatrix:!0});s.draw(r,a.TRIANGLES,n,l,jt.alphaBlended,Ut.disabled,Oi(t.bf.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),s.draw(r,a.LINE_STRIP,n,l,c,Ut.disabled,Oi(t.bf.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function Cr(e,t,i,o){const{isRenderingGlobe:r}=o,a=e.context,s=a.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain");a.bindFramebuffer.set(null),a.viewport.set([0,0,e.width,e.height]);for(const o of i){const i=t.getTerrainMesh(o.tileID),u=e.renderToTexture.getTexture(o),d=t.getTerrainData(o.tileID);a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,u.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(o.tileID.toUnwrapped()),m=Ci(_,p,e.style.sky,n.pitch,r),f=n.getProjectionData({overscaledTileID:o.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});h.draw(a,s.TRIANGLES,c,Vt.disabled,l,Ut.backCCW,m,d,f,"terrain",i.vertexBuffer,i.indexBuffer,i.segments);}}function Ir(e,i){if(!i.mesh){const o=new t.aL;o.emplaceBack(-1,-1),o.emplaceBack(1,-1),o.emplaceBack(1,1),o.emplaceBack(-1,1);const r=new t.aN;r.emplaceBack(0,1,2),r.emplaceBack(0,2,3),i.mesh=new wt(e.createVertexBuffer(o,Tt.members),e.createIndexBuffer(r),t.aM.simpleSegment(0,0,o.length,r.length));}return i.mesh}class Mr{constructor(e,i){this.context=new Ho(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:t.ag(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=xe.maxUnderzooming+xe.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new vt;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.aL;i.emplaceBack(0,0),i.emplaceBack(t.$,0),i.emplaceBack(0,t.$),i.emplaceBack(t.$,t.$),this.tileExtentBuffer=e.createVertexBuffer(i,Tt.members),this.tileExtentSegments=t.aM.simpleSegment(0,0,4,2);const o=new t.aL;o.emplaceBack(0,0),o.emplaceBack(t.$,0),o.emplaceBack(0,t.$),o.emplaceBack(t.$,t.$),this.debugBuffer=e.createVertexBuffer(o,Tt.members),this.debugSegments=t.aM.simpleSegment(0,0,4,5);const r=new t.c6;r.emplaceBack(0,0,0,0),r.emplaceBack(t.$,0,t.$,0),r.emplaceBack(0,t.$,0,t.$),r.emplaceBack(t.$,t.$,t.$,t.$),this.rasterBoundsBuffer=e.createVertexBuffer(r,Ti.members),this.rasterBoundsSegments=t.aM.simpleSegment(0,0,4,2);const a=new t.aL;a.emplaceBack(0,0),a.emplaceBack(t.$,0),a.emplaceBack(0,t.$),a.emplaceBack(t.$,t.$),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(a,Tt.members),this.rasterBoundsSegmentsPosOnly=t.aM.simpleSegment(0,0,4,5);const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(1,0),s.emplaceBack(0,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,Tt.members),this.viewportSegments=t.aM.simpleSegment(0,0,4,2);const n=new t.c7;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.aN;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new Vt({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new wt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const o=t.L();t.bY(o,0,this.width,this.height,0,0,1),t.N(o,o,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const r={mainMatrix:o,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:o};this.useProgram("clippingMask",null,!0).draw(e,i.TRIANGLES,Zt.disabled,this.stencilClearMode,jt.disabled,Ut.disabled,null,null,r,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const o=this.context;o.setColorMode(jt.disabled),o.setDepthMode(Zt.disabled);const r={};for(const e of t)r[e.key]=this.nextStencilID++;this._renderTileMasks(r,t,i,!0),this._renderTileMasks(r,t,i,!1),this._tileClippingMaskIDs=r;}_renderTileMasks(e,t,i,o){const r=this.context,a=r.gl,s=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=s.getMeshFromTileID(this.context,c.canonical,o,!0,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!i,applyTerrainMatrix:!0});l.draw(r,a.TRIANGLES,Zt.disabled,new Vt({func:a.ALWAYS,mask:0},t,255,a.KEEP,a.KEEP,a.REPLACE),jt.disabled,i?Ut.disabled:Ut.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,o=this.transform,r=this.useProgram("depth"),a=this.getDepthModeFor3D(),s=ve(o,{tileSize:o.tileSize});for(const n of s){const s=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,!0,!0,"raster"),c=o.getProjectionData({overscaledTileID:n,applyGlobeMatrix:!0,applyTerrainMatrix:!0});r.draw(e,t.TRIANGLES,a,Vt.disabled,jt.disabled,Ut.backCCW,null,s,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new Vt({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new Vt({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(r>1){this.currentStencilSource=void 0,this.nextStencilID+r>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(this.clearStencil(),r>1){const e={},a={};for(let i=0;i0};for(const e in n){const t=n[e];t.used&&t.prepare(this.context),l[e]=t.getVisibleCoordinates(!1),c[e]=l[e].slice().reverse(),h[e]=t.getVisibleCoordinates(!0).reverse();}this.opaquePassCutoff=1/0;for(let e=0;ethis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.bf.black:t.bf.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,o=i.gl,r=((e,t,i)=>{const o=Math.cos(t.rollInRadians),r=Math.sin(t.rollInRadians),a=he(t),s=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-a*r)*i,(t.height/2+a*o)*i],u_horizon_normal:[-r,o],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:s}})(t,e.style.map.transform,e.pixelRatio),a=new Zt(o.LEQUAL,Zt.ReadWrite,[0,1]),s=Vt.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=Ir(i,t);l.draw(i,o.TRIANGLES,a,s,n,Ut.disabled,r,null,void 0,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=a.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[a[this.currentLayer]],t=n[e.source],i=l[e.source];this._renderTileClippingMasks(e,i,!1),this.renderLayer(this,t,e,i,u);}this.renderPass="translucent";let d=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:o,u_inv_proj_matrix:r}))(c,u,[p[0],p[1],p[2]],d,_),f=Ir(r,i);s.draw(r,a.TRIANGLES,n,Vt.disabled,jt.alphaBlended,Ut.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const o=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.sourceCaches[i.source]]:[])),r=o.filter((e=>"vector"===e.getSource().type)),a=o.filter((e=>"vector"!==e.getSource().type)),s=e=>{(!i||i.getSource().maxzooms(e))),i||a.forEach((e=>s(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let o=0;ou.getElevation(a,e,t):null;er(s,d,_,c,h,f,i,p,g,t.aD(h,e,n,l),a.toUnwrapped(),o);}}}(r,e,o,i,o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),a),0!==o.paint.get("icon-opacity").constantOr(1)&&ir(e,i,o,r,!1,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),o.layout.get("icon-rotation-alignment"),o.layout.get("icon-pitch-alignment"),o.layout.get("icon-keep-upright"),l,c,n),0!==o.paint.get("text-opacity").constantOr(1)&&ir(e,i,o,r,!0,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&(Ko(e,i,o,r,!0),Ko(e,i,o,r,!1));}(e,i,o,r,this.style.placement.variableOffsets,a):t.cc(o)?function(e,i,o,r,a){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:s}=a,n=o.paint.get("circle-opacity"),l=o.paint.get("circle-stroke-width"),c=o.paint.get("circle-stroke-opacity"),h=!o.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Zt.ReadOnly),m=Vt.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let a=0;ae.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:r,layoutVertexBuffer:a,indexBuffer:s,uniformValues:n,terrainData:l,projectionData:c}=t.state;r.draw(u,d.TRIANGLES,p,m,f,Ut.backCCW,n,l,c,o.id,a,s,t.segments,o.paint,e.transform.zoom,i);}}(e,i,o,r,a):t.cd(o)?function(e,i,o,r,a){if(0===o.paint.get("heatmap-opacity"))return;const s=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=a;if(e.style.map.terrain){for(const t of r){const r=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?rr(e,r,o,t,l):"translucent"===e.renderPass&&ar(e,o,t,n,l));}s.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,o,r){const a=e.context,s=a.gl,n=e.transform,l=Vt.disabled,c=new jt([s.ONE,s.ONE],t.bf.transparent,[!0,!0,!0,!0]);((function(e,i,o){const r=e.gl;e.activeTexture.set(r.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let a=o.heatmapFbos.get(t.c2);a?(r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer)):(a=sr(e,i.width/4,i.height/4),o.heatmapFbos.set(t.c2,a));}))(a,e,o),a.clear({color:t.bf.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return !1;if(!e.from||!e.to)return !0;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=!1,o=[]){this.cache=this.cache||{};const r=!!this.style.map.terrain,a=this.style.projection,s=i?xt.projectionMercator:a.shaderPreludeCode,n=i?Pt:a.shaderDefine,l=e+(t?t.cacheKey:"")+`/${i?Ct:a.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(r?"/terrain":"")+(o?`/${o.join("/")}`:"");return this.cache[l]||(this.cache[l]=new Si(this.context,xt[e],t,ao[e],this._showOverdrawInspector,r,s,n,o)),this.cache[l]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Sr(e,t){let i,o=!1,r=null,a=null;const s=()=>{r=null,o&&(e.apply(a,i),r=setTimeout(s,t),o=!1);};return (...e)=>(o=!0,a=this,i=e,r||s(),r)}class Er{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(!this._isValidHash(e))return !1;const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let o=window.location.hash.replace(i,"");o.startsWith("#&")?o=o.slice(0,1)+o.slice(2):"#"===o&&(o="");let r=window.location.href.replace(/(#.+)?$/,o);r=r.replace("&&","&"),window.history.replaceState(window.history.state,null,r);},this._updateHash=Sr(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,o=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),r=Math.pow(10,o),a=Math.round(t.lng*r)/r,s=Math.round(t.lat*r)/r,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${a}/${s}/${i}`:`${i}/${s}/${a}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const o=i.split("=")[0];return o===e?(t=!0,`${o}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return !1;try{new t.S(+e[2],+e[1]);}catch(e){return !1}const i=+e[0],o=+(e[3]||0),r=+(e[4]||0);return i>=this._map.getMinZoom()&&i<=this._map.getMaxZoom()&&o>=-180&&o<=180&&r>=this._map.getMinPitch()&&r<=this._map.getMaxPitch()}}const Rr={linearity:.3,easing:t.cm(0,0,.3,1)},zr=t.e({deceleration:2500,maxSpeed:1400},Rr),Dr=t.e({deceleration:20,maxSpeed:1400},Rr),Ar=t.e({deceleration:1e3,maxSpeed:360},Rr),Lr=t.e({deceleration:1e3,maxSpeed:90},Rr),kr=t.e({deceleration:1e3,maxSpeed:360},Rr);class Fr{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:s.now(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=s.now();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const o=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,r={};if(i.pan.mag()){const a=Or(i.pan.mag(),o,t.e({},zr,e||{})),s=i.pan.mult(a.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(s,this._map.transform);r.center=n.easingCenter,r.offset=n.easingOffset,Br(r,a);}if(i.zoom){const e=Or(i.zoom,o,Dr);r.zoom=this._map.transform.zoom+e.amount,Br(r,e);}if(i.bearing){const e=Or(i.bearing,o,Ar);r.bearing=this._map.transform.bearing+t.ah(e.amount,-179,179),Br(r,e);}if(i.pitch){const e=Or(i.pitch,o,Lr);r.pitch=this._map.transform.pitch+e.amount,Br(r,e);}if(i.roll){const e=Or(i.roll,o,kr);r.roll=this._map.transform.roll+t.ah(e.amount,-179,179),Br(r,e);}if(r.zoom||r.bearing){const e=void 0===i.pinchAround?i.around:i.pinchAround;r.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.e(r,{noMoveStart:!0})}}function Br(e,t){(!e.duration||e.durationi.unproject(e))),l=a.reduce(((e,t,i,o)=>e.add(t.div(o.length))),new t.P(0,0));super(e,{points:a,point:l,lngLats:s,lngLat:i.unproject(l),originalEvent:o}),this._defaultPrevented=!1;}}class Ur extends t.l{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=!1;}}class Zr{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new Ur(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new jr(e.type,this._map,e))}mouseup(e){this._map.fire(new jr(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new jr(e.type,this._map,e));}dblclick(e){return this._firePreventable(new jr(e.type,this._map,e))}mouseover(e){this._map.fire(new jr(e.type,this._map,e));}mouseout(e){this._map.fire(new jr(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Nr(e.type,this._map,e))}touchmove(e){this._map.fire(new Nr(e.type,this._map,e));}touchend(e){this._map.fire(new Nr(e.type,this._map,e));}touchcancel(e){this._map.fire(new Nr(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Gr{constructor(e){this._map=e;}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new jr(e.type,this._map,e));}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new jr("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new jr(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Vr{constructor(e){this._map=e;}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return {lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class $r{constructor(e,t){this._map=e,this._tr=new Vr(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(n.disableDrag(),this._startPos=this._lastPos=t,this._active=!0);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(o,r,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.l(e,{originalEvent:i}))}}function qr(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let o=0;othis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){const i=new t.P(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=qr(o,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const o=qr(i,t);for(const e in this.touches){const t=o[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Hr{constructor(e){this.singleTap=new Wr(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const o=this.singleTap.touchend(e,t,i);if(o){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(o)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}}}class Xr{constructor(e){this._tr=new Vr(e),this._zoomIn=new Hr({numTouches:1,numTaps:2}),this._zoomOut=new Hr({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const o=this._zoomIn.touchend(e,t,i),r=this._zoomOut.touchend(e,t,i),a=this._tr;return o?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom+1,around:a.unproject(o)},{originalEvent:e})}):r?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom-1,around:a.unproject(r)},{originalEvent:e})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class Kr{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0));}dragMove(e,t){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const o=Array.isArray(t)?t[0]:t;return !this._moved&&o.dist(i)!0}),t=new ta){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t;}_executeRelevantHandler(e,t,i){return e instanceof MouseEvent?t(e):"undefined"!=typeof TouchEvent&&e instanceof TouchEvent?i(e):void 0}startMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.startMove(e)),(e=>this.oneFingerTouchMoveStateManager.startMove(e)));}endMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.endMove(e)),(e=>this.oneFingerTouchMoveStateManager.endMove(e)));}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}const oa=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};class ra{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=!1,this._touches={},this._sum=new t.P(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,o){o.length>0&&(this._active=!0);const r=qr(o,i),a=new t.P(0,0),s=new t.P(0,0);let n=0;for(const e in r){const t=r[e],i=this._touches[e];i&&(a._add(t),s._add(t.sub(i)),n++,r[e]=t);}if(this._touches=r,this._shouldBePrevented(n)||!s.mag())return;const l=s.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class da extends aa{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,ua(e[0].sub(e[1]))&&(this._valid=!1);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const o=e[0].sub(this._lastPoints[0]),r=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const o=e.mag()>=2,r=t.mag()>=2;if(!o&&!r)return;if(!o||!r)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const a=e.y>0==t.y>0;return ua(e)&&ua(t)&&a}}const _a={panStep:100,bearingStep:15,pitchStep:10};class pa{constructor(e){this._tr=new Vr(e);const t=_a;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1;}reset(){this._active=!1;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,o=0,r=0,a=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),r=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),r=1);break;case 38:e.shiftKey?o=1:(e.preventDefault(),a=-1);break;case 40:e.shiftKey?o=-1:(e.preventDefault(),a=1);break;default:return}return this._rotationDisabled&&(i=0,o=0),{cameraAnimation:s=>{const n=this._tr;s.easeTo({duration:300,easeId:"keyboardHandler",easing:ma,zoom:t?Math.round(n.zoom)+t*(e.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+o*this._pitchStep,offset:[-r*this._panStep,-a*this._panStep],center:n.center},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function ma(e){return e*(2-e)}const fa=4.000244140625,ga=1/450;class va{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new Vr(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=ga;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=!1);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=s.now(),o=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%fa==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":o>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(o*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=n.mousePos(this._map.getCanvas(),e),o=this._tr;this._aroundPoint=this._aroundCenter?o.transform.locationToScreenPoint(t.S.convert(o.center)):i,this._frameId||(this._frameId=!0,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>fa?this._wheelZoomRate:this._defaultZoomRate;let o=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==o&&(o=1/o);const r="number"!=typeof this._targetZoom?e.scale:t.af(this._targetZoom);this._targetZoom=e.getConstrained(e.getCameraLngLat(),t.ak(r*o)).zoom,"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,o=this._startZoom,r=this._easing;let a,n=!1;if("wheel"===this._type&&o&&r){const e=s.now()-this._lastWheelEventTime,l=Math.min((e+5)/200,1),c=r(l);a=t.C.number(o,i,c),l<1?this._frameId||(this._frameId=!0):n=!0;}else a=i,n=!0;return this._active=!0,n&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=a,{noInertia:!0,needsRenderFrame:!n,zoomDelta:a-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.co;if(this._prevEase){const e=this._prevEase,o=(s.now()-e.start)/e.duration,r=e.easing(o+.01)-e.easing(o),a=.27/Math.sqrt(r*r+1e-4)*.01,n=Math.sqrt(.0729-a*a);i=t.cm(a,n,.25,1);}return this._prevEase={start:s.now(),duration:e,easing:i},i}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class ba{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class xa{constructor(e){this._tr=new Vr(e),this.reset();}reset(){this._active=!1;}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ya{constructor(){this._tap=new Hr({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const o=t[0],r=e.timeStamp-this._tapTime<500,a=this._tapPoint.dist(o)<30;r&&a?i.length>0&&(this._swipePoint=o,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const o=t[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,e.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const o=this._tap.touchend(e,t,i);o&&(this._tapTime=e.timeStamp,this._tapPoint=o);}}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class wa{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Ta{constructor(e,t,i,o){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=o;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Pa{constructor(e,t,i,o){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class Ca{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=!1;}isActive(){return !1}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=n.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),o=document.createElement("div");o.className="maplibregl-desktop-message",o.textContent=t,this._container.appendChild(o);const r=document.createElement("div");r.className="maplibregl-mobile-message",r.textContent=i,this._container.appendChild(r),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(n.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=!0;}disable(){this._enabled=!1,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.l("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const Ia=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Ma extends t.l{}function Sa(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class Ea{constructor(e,i){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,i)=>{if("blur"===e.type)return void this.stop(!0);this._updatingCamera=!0;const o="renderFrame"===e.type?void 0:e,r={needsRenderFrame:!1},a={},s={};for(const{handlerName:l,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let u;if(this._blockedByActive(s,h,l))c.reset();else if(c[i||e.type]){if(t.cp(e,i||e.type)){const t=n.mousePos(this._map.getCanvas(),e);u=c[i||e.type](e,t);}else if(t.cq(e,i||e.type)){const t=this._getMapTouches(e.touches),o=n.touchPos(this._map.getCanvas(),t);u=c[i||e.type](e,o,t);}else t.cr(i||e.type)||(u=c[i||e.type](e));this.mergeHandlerResult(r,a,u,l,o),u&&u.needsRenderFrame&&this._triggerRenderFrame();}(u||c.isActive())&&(s[l]=c);}const l={};for(const e in this._previousActiveHandlers)s[e]||(l[e]=o);this._previousActiveHandlers=s,(Object.keys(l).length||Sa(r))&&(this._changes.push([r,a,l]),this._triggerRenderFrame()),(Object.keys(s).length||Sa(r))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:c}=r;c&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],c(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Fr(e),this._bearingSnap=i.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(i);const o=this._el;this._listeners=[[o,"touchstart",{passive:!0}],[o,"touchmove",{passive:!1}],[o,"touchend",void 0],[o,"touchcancel",void 0],[o,"mousedown",void 0],[o,"mousemove",void 0],[o,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[o,"mouseover",void 0],[o,"mouseout",void 0],[o,"dblclick",void 0],[o,"click",void 0],[o,"keydown",{capture:!1}],[o,"keyup",void 0],[o,"wheel",{passive:!1}],[o,"contextmenu",void 0],[window,"blur",void 0]];for(const[e,t,i]of this._listeners)n.addEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)n.removeEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const i=this._map,o=i.getCanvasContainer();this._add("mapEvent",new Zr(i,e));const r=i.boxZoom=new $r(i,e);this._add("boxZoom",r),e.interactive&&e.boxZoom&&r.enable();const a=i.cooperativeGestures=new Ca(i,e.cooperativeGestures);this._add("cooperativeGestures",a),e.cooperativeGestures&&a.enable();const s=new Xr(i),l=new xa(i);i.doubleClickZoom=new ba(l,s),this._add("tapZoom",s),this._add("clickZoom",l),e.interactive&&e.doubleClickZoom&&i.doubleClickZoom.enable();const c=new ya;this._add("tapDragZoom",c);const h=i.touchPitch=new da(i);this._add("touchPitch",h),e.interactive&&e.touchPitch&&i.touchPitch.enable(e.touchPitch);const u=()=>i.project(i.getCenter()),d=function({enable:e,clickTolerance:i,aroundCenter:o=!0,minPixelCenterThreshold:r=100,rotateDegreesPerPixelMoved:a=.8},s){const l=new ea({checkCorrectEvent:e=>0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:i,move:(e,i)=>{const n=s();if(o&&Math.abs(n.y-e.y)>r)return {bearingDelta:t.cn(new t.P(e.x,i.y),i,n)};let l=(i.x-e.x)*a;return o&&i.y0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)});return new Kr({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:o,enable:e,assignEvents:oa})}(e),p=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3},o){const r=new ea({checkCorrectEvent:e=>2===n.mouseButton(e)&&e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>{const r=o();let a=(t.x-e.x)*i;return t.y0===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:i,enable:e,assignEvents:oa})}(e),f=new ra(e,i);i.dragPan=new wa(o,m,f),this._add("mousePan",m),this._add("touchPan",f,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&i.dragPan.enable(e.dragPan);const g=new ha,v=new la;i.touchZoomRotate=new Pa(o,v,g,c),this._add("touchRotate",g,["touchPan","touchZoom"]),this._add("touchZoom",v,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&i.touchZoomRotate.enable(e.touchZoomRotate);const b=i.scrollZoom=new va(i,(()=>this._triggerRenderFrame()));this._add("scrollZoom",b,["mousePan"]),e.interactive&&e.scrollZoom&&i.scrollZoom.enable(e.scrollZoom);const x=i.keyboard=new pa(i);this._add("keyboard",x),e.interactive&&e.keyboard&&i.keyboard.enable(),this._add("blockableMapEvent",new Gr(i));}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(Ia(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const o in e)if(o!==i&&(!t||t.indexOf(o)<0))return !0;return !1}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,o,r,a){if(!o)return;t.e(e,o);const s={handlerName:r,originalEvent:o.originalEvent||a};void 0!==o.zoomDelta&&(i.zoom=s),void 0!==o.panDelta&&(i.drag=s),void 0!==o.rollDelta&&(i.roll=s),void 0!==o.pitchDelta&&(i.pitch=s),void 0!==o.bearingDelta&&(i.rotate=s);}_applyChanges(){const e={},i={},o={};for(const[r,a,s]of this._changes)r.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(r.panDelta)),r.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+r.zoomDelta),r.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+r.bearingDelta),r.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+r.pitchDelta),r.rollDelta&&(e.rollDelta=(e.rollDelta||0)+r.rollDelta),void 0!==r.around&&(e.around=r.around),void 0!==r.pinchAround&&(e.pinchAround=r.pinchAround),r.noInertia&&(e.noInertia=r.noInertia),t.e(i,a),t.e(o,s);this._updateMapTransform(e,i,o),this._changes=[];}_updateMapTransform(e,t,i){const o=this._map,r=o._getTransformForUpdate(),a=o.terrain;if(!(Sa(e)||a&&this._terrainMovement))return this._fireEvents(t,i,!0);o._stop(!0);let{panDelta:s,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;void 0!==d&&(u=d),u=u||o.transform.centerPoint,a&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const _={panDelta:s,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const p=u.distSqr(r.centerPoint)<.01?r.center:r.screenPointToLocation(s?u.sub(s):u);a?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._terrainMovement||!t.drag&&!t.zoom?t.drag&&this._terrainMovement?r.setCenter(r.screenPointToLocation(r.centerPoint.sub(s))):this._map.cameraHelper.handleMapControlsPan(_,r,p):(this._terrainMovement=!0,this._map._elevationFreeze=!0,this._map.cameraHelper.handleMapControlsPan(_,r,p))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._map.cameraHelper.handleMapControlsPan(_,r,p)),o._applyUpdatedTransform(r),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0);}_fireEvents(e,i,o){const r=Ia(this._eventsInProgress),a=Ia(e),n={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(n[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!r&&a&&this._fireEvent("movestart",a.originalEvent);for(const e in n)this._fireEvent(e,n[e]);a&&this._fireEvent("move",a.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const l={};let c;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:o}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],c=i[t]||o,l[`${e}end`]=c);}for(const e in l)this._fireEvent(e,l[e]);const h=Ia(this._eventsInProgress),u=(r||a)&&!h;if(u&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(o&&u){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new Ma("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}class Ra extends t.E{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((s.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=i.bearingSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.S(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,o){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},i),o)}panTo(e,i,o){return this.easeTo(t.e({center:e},i),o)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,o){return this.easeTo(t.e({zoom:e},i),o)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.l("movestart",i)).fire(new t.l("move",i)).fire(new t.l("moveend",i))),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,o){return this.easeTo(t.e({bearing:e},i),o)}resetNorth(e,i){return this.rotateTo(0,t.e({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){f.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,o={}){this._moving=!0,i||o.moving||this.fire(new t.l("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.l("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.l("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.l("pitchstart",e)),this._rolling&&!o.rolling&&this.fire(new t.l("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0;}_updateElevation(e){void 0!==this._elevationStart&&void 0!==this._elevationCenter||this._prepareElevation(this.transform.center),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.C.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),o=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:o,zoom:r,roll:a,pitch:s,bearing:n,elevation:l}=e(t);o&&t.setCenter(o),void 0!==l&&t.setElevation(l),void 0!==r&&t.setZoom(r),void 0!==a&&t.setRoll(a),void 0!==s&&t.setPitch(s),void 0!==n&&t.setBearing(n),i.apply(t);}this.transform.apply(i);}_fireMoveEvents(e){this.fire(new t.l("move",e)),this._zooming&&this.fire(new t.l("zoom",e)),this._rotating&&this.fire(new t.l("rotate",e)),this._pitching&&this.fire(new t.l("pitch",e)),this._rolling&&this.fire(new t.l("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const o=this._zooming,r=this._rotating,a=this._pitching,s=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,o&&this.fire(new t.l("zoomend",e)),r&&this.fire(new t.l("rotateend",e)),a&&this.fire(new t.l("pitchend",e)),s&&this.fire(new t.l("rollend",e)),this.fire(new t.l("moveend",e));}flyTo(e,i){if(!e.essential&&s.prefersReducedMotion){const o=t.Q(e,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(o,i)}this.stop(),e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.co},e);const o=this._getTransformForUpdate(),r=o.bearing,a=o.pitch,n=o.roll,l=o.padding,c="bearing"in e?this._normalizeBearing(e.bearing,r):r,h="pitch"in e?+e.pitch:a,u="roll"in e?this._normalizeBearing(e.roll,n):n,d="padding"in e?e.padding:o.padding,_=t.P.convert(e.offset);let p=o.centerPoint.add(_);const m=o.screenPointToLocation(p),f=this.cameraHelper.handleFlyTo(o,{bearing:c,pitch:h,roll:u,padding:d,locationAtOffset:m,offsetAsPoint:_,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(o.width,o.height),b=v/f.scaleOfZoom,x=f.pixelPathLength;"number"==typeof f.scaleOfMinZoom&&(g=Math.sqrt(v/f.scaleOfMinZoom/x*2));const y=g*g;function w(e){const t=(b*b-v*v+(e?-1:1)*y*y*x*x)/(2*(e?b:v)*y*x);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function P(e){return (Math.exp(e)+Math.exp(-e))/2}const C=w(!1);let I=function(e){return P(C)/P(C+g*e)},M=function(e){return v*((P(C)*(T(t=C+g*e)/P(t))-T(C))/y)/x;var t;},S=(w(!0)-C)/g;if(Math.abs(x)<2e-6||!isFinite(S)){if(Math.abs(v-b)<1e-6)return this.easeTo(e,i);const t=b0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*S/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=r!==c,this._pitching=h!==a,this._rolling=u!==n,this._padding=!o.isPaddingEqual(d),this._prepareEase(i,!1),this.terrain&&this._prepareElevation(f.targetCenter),this._ease((s=>{const m=s*S,g=1/I(m),v=M(m);this._rotating&&o.setBearing(t.C.number(r,c,s)),this._pitching&&o.setPitch(t.C.number(a,h,s)),this._rolling&&o.setRoll(t.C.number(n,u,s)),this._padding&&(o.interpolatePadding(l,d,s),p=o.centerPoint.add(_)),f.easeFunc(s,g,v,p),this.terrain&&!e.freezeElevation&&this._updateElevation(s),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=s.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.aO(e,-180,180);const o=Math.abs(e-i);return Math.abs(e-360-i)MapLibre
'};class Da{constructor(e=za){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=n.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=n.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=n.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.sourceCaches;for(const i in t){const o=t[i];if(o.used||o.usedForTerrain){const t=o.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let o=i+1;o=0)return !1;return !0}));const i=e.join(" | ");i!==this._attribHTML&&(this._attribHTML=i,e.length?(this._innerContainer.innerHTML=n.sanitize(i),this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Aa{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=n.create("div","maplibregl-ctrl");const t=n.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){n.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0;}}class La{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}var ka=t.aJ([{name:"a_pos3d",type:"Int16",components:3}]);class Fa extends t.E{constructor(e){super(),this._lastTilesetChange=s.now(),this.sourceCache=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize;}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null;}update(e,i){this.sourceCache.update(e,i),this._renderableTilesKeys=[];const o={};for(const r of ve(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:i,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))o[r.key]=!0,this._renderableTilesKeys.push(r.key),this._tiles[r.key]||(r.terrainRttPosMatrix32f=new Float64Array(16),t.bY(r.terrainRttPosMatrix32f,0,t.$,t.$,0,0,1),this._tiles[r.key]=new re(r,this.tileSize),this._lastTilesetChange=s.now());for(const e in this._tiles)o[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e,t){return t?this._getTerrainCoordsForTileRanges(e,t):this._getTerrainCoordsForRegularTile(e)}_getTerrainCoordsForRegularTile(e){const i={};for(const o of this._renderableTilesKeys){const r=this._tiles[o].tileID,a=e.clone(),s=t.ba();if(r.canonical.equals(e.canonical))t.bY(s,0,t.$,t.$,0,0,1);else if(r.canonical.isChildOf(e.canonical)){const i=r.canonical.z-e.canonical.z,o=r.canonical.x-(r.canonical.x>>i<>i<>i;t.bY(s,0,n,n,0,0,1),t.M(s,s,[-o*n,-a*n,0]);}else {if(!e.canonical.isChildOf(r.canonical))continue;{const i=e.canonical.z-r.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i;t.bY(s,0,t.$,t.$,0,0,1),t.M(s,s,[o*n,a*n,0]),t.N(s,s,[1/2**i,1/2**i,0]);}}a.terrainRttPosMatrix32f=new Float32Array(s),i[o]=a;}return i}_getTerrainCoordsForTileRanges(e,i){const o={};for(const r of this._renderableTilesKeys){const a=this._tiles[r].tileID;if(!this._isWithinTileRanges(a,i))continue;const s=e.clone(),n=t.ba();if(a.canonical.z===e.canonical.z){const i=e.canonical.x-a.canonical.x,o=e.canonical.y-a.canonical.y;t.bY(n,0,t.$,t.$,0,0,1),t.M(n,n,[i*t.$,o*t.$,0]);}else if(a.canonical.z>e.canonical.z){const i=a.canonical.z-e.canonical.z,o=a.canonical.x-(a.canonical.x>>i<>i<>i),l=e.canonical.y-(a.canonical.y>>i),c=t.$>>i;t.bY(n,0,c,c,0,0,1),t.M(n,n,[-o*c+s*t.$,-r*c+l*t.$,0]);}else {const i=e.canonical.z-a.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i)-a.canonical.x,l=(e.canonical.y>>i)-a.canonical.y,c=t.$<i.maxzoom&&(o=i.maxzoom),o=i.minzoom&&(!r||!r.dem);)r=this.sourceCache.getTileByID(e.scaledTo(o--).key);return r}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}_isWithinTileRanges(e,t){return t[e.canonical.z]&&e.canonical.x>=t[e.canonical.z].minTileX&&e.canonical.x<=t[e.canonical.z].maxTileX&&e.canonical.y>=t[e.canonical.z].minTileY&&e.canonical.y<=t[e.canonical.z].maxTileY}}class Ba{constructor(e,t,i){this._meshCache={},this.painter=e,this.sourceCache=new Fa(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(e,i,o,r=t.$){var a;if(!(i>=0&&i=0&&oe.canonical.z&&(e.canonical.z>=o?r=e.canonical.z-o:t.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const a=e.canonical.x-(e.canonical.x>>r<>r<>8<<4|e>>8,i[t+3]=0;const o=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),r=new t.T(e,o,e.gl.RGBA,{premultiply:!1});return r.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=r,r}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(!0);const i=new Uint8Array(4),o=this.painter.context,r=o.gl,a=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),s=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);o.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),r.readPixels(a,n-s-1,1,1,r.RGBA,r.UNSIGNED_BYTE,i),o.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.sourceCache.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<0,r=o&&0===e.canonical.y,a=o&&e.canonical.y===(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const ja={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class Na{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new Oa(e.context,30,t.sourceCache.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.sourceCaches){this._coordsAscending[t]={};const i=e.sourceCaches[t].getVisibleCoordinates(),o=e.sourceCaches[t].getSource(),r=o instanceof X?o.terrainTileRanges:null;for(const e of i){const i=this.terrain.sourceCache.getTerrainCoords(e,r);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._coordsAscendingStr={};for(const t of e._order){const i=e._layers[t],o=i.source;if(ja[i.type]&&!this._coordsAscendingStr[o]){this._coordsAscendingStr[o]={};for(const e in this._coordsAscending[o])this._coordsAscendingStr[o][e]=this._coordsAscending[o][e].map((e=>e.key)).sort().join();}}for(const e of this._renderableTiles)for(const t in this._coordsAscendingStr){const i=this._coordsAscendingStr[t][e.tileID.key];i&&i!==e.rttCoords[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return !1;const o=Object.assign(Object.assign({},i),{isRenderingToTexture:!0}),r=e.type,a=this.painter,s=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(ja[r]&&(this._prevType&&ja[this._prevType]||this._stacks.push([]),this._prevType=r,this._stacks[this._stacks.length-1].push(e.id),!s))return !0;if(ja[this._prevType]||ja[r]&&s){this._prevType=r;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const r of this._renderableTiles){if(this.pool.isFull()&&(Cr(this.painter,this.terrain,this._rttTiles,o),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(r),r.rtt[e]){const t=this.pool.getObjectForId(r.rtt[e].id);if(t.stamp===r.rtt[e].stamp){this.pool.useObject(t);continue}}const s=this.pool.getOrCreateFreeObject();this.pool.useObject(s),this.pool.stampObject(s),r.rtt[e]={id:s.id,stamp:s.stamp},a.context.bindFramebuffer.set(s.fbo.framebuffer),a.context.clear({color:t.bf.transparent,stencil:0}),a.currentStencilSource=void 0;for(let e=0;e{this.startMove(e,n.mousePos(this.element,e)),n.addEventListener(window,"mousemove",this.mousemove),n.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=e=>{this.move(e,n.mousePos(this.element,e));},this.mouseup=e=>{this._rotatePitchHandler.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),n.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.addEventListener(window,"touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHandler.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10,this.element=i;const r=new ia;this._rotatePitchHandler=new Kr({clickTolerance:3,move:(e,r)=>{const a=i.getBoundingClientRect(),s=new t.P((a.bottom-a.top)/2,(a.right-a.left)/2);return {bearingDelta:t.cn(new t.P(e.x,r.y),r,s),pitchDelta:o?-.5*(r.y-e.y):void 0}},moveStateManager:r,enable:!0,assignEvents:()=>{}}),this.map=e,n.addEventListener(i,"mousedown",this.mousedown),n.addEventListener(i,"touchstart",this.touchstart,{passive:!1}),n.addEventListener(i,"touchcancel",this.reset);}startMove(e,t){this._rotatePitchHandler.dragStart(e,t),n.disableDrag();}move(e,t){const i=this.map,{bearingDelta:o,pitchDelta:r}=this._rotatePitchHandler.dragMove(e,t)||{};o&&i.setBearing(i.getBearing()+o),r&&i.setPitch(i.getPitch()+r);}off(){const e=this.element;n.removeEventListener(e,"mousedown",this.mousedown),n.removeEventListener(e,"touchstart",this.touchstart,{passive:!1}),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend),n.removeEventListener(e,"touchcancel",this.reset),this.offTemp();}offTemp(){n.enableDrag(),n.removeEventListener(window,"mousemove",this.mousemove),n.removeEventListener(window,"mouseup",this.mouseup),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend);}}let qa;function Wa(e,i,o,r=!1){if(r||!o.getCoveringTilesDetailsProvider().allowWorldCopies())return null==e?void 0:e.wrap();const a=new t.S(e.lng,e.lat);if(e=new t.S(e.lng,e.lat),i){const r=new t.S(e.lng-360,e.lat),a=new t.S(e.lng+360,e.lat),s=o.locationToScreenPoint(e).distSqr(i);o.locationToScreenPoint(r).distSqr(i)180;){const t=o.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=o.width&&t.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==a.lng&&o.isPointOnMapSurface(o.locationToScreenPoint(e))?e:a}const Ha={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Xa(e,t,i){const o=e.classList;for(const e in Ha)o.remove(`maplibregl-${i}-anchor-${e}`);o.add(`maplibregl-${i}-anchor-${t}`);}class Ka extends t.E{constructor(e){if(super(),this._onKeyPress=e=>{const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{if(!this._map)return;const t=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?void 0:e.type)||"render"===(null==e?void 0:e.type)&&!t)&&this._map.once("render",this._update),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let i="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?i=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(i=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),n.setTransform(this._element,`${Ha[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${i}`),s.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.l("dragstart"))),this.fire(new t.l("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.l("dragend")),this._state="inactive";},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||!1,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(null==e?void 0:e.opacity,null==e?void 0:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.P.convert(e&&e.offset||[0,0]);else {this._defaultMarker=!0,this._element=n.create("div");const i=n.createNS("http://www.w3.org/2000/svg","svg"),o=41,r=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${o}px`),i.setAttributeNS(null,"width",`${r}px`),i.setAttributeNS(null,"viewBox",`0 0 ${r} ${o}`);const a=n.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"stroke","none"),a.setAttributeNS(null,"stroke-width","1"),a.setAttributeNS(null,"fill","none"),a.setAttributeNS(null,"fill-rule","evenodd");const s=n.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"fill-rule","nonzero");const l=n.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"transform","translate(3.0, 29.0)"),l.setAttributeNS(null,"fill","#000000");const c=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const e of c){const t=n.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),l.appendChild(t);}const h=n.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);const u=n.createNS("http://www.w3.org/2000/svg","path");u.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(u);const d=n.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");const _=n.createNS("http://www.w3.org/2000/svg","path");_.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(_);const p=n.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const m=n.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(8.0, 8.0)");const f=n.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#000000"),f.setAttributeNS(null,"opacity","0.25"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962");const g=n.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#FFFFFF"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962"),m.appendChild(f),m.appendChild(g),s.appendChild(l),s.appendChild(h),s.appendChild(d),s.appendChild(p),s.appendChild(m),i.appendChild(s),i.setAttributeNS(null,"height",o*this._scale+"px"),i.setAttributeNS(null,"width",r*this._scale+"px"),this._element.appendChild(i),this._offset=t.P.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),Xa(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),n.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,o=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-t],"bottom-left":[o,-1*(t-i+o)],"bottom-right":[-o,-1*(t-i+o)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=!1){var i,o;const r=null===(i=this._map)||void 0===i?void 0:i.terrain,a=this._map.transform.isLocationOccluded(this._lngLat);if(!r||a){const e=a?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const s=this._map,n=s.terrain.depthAtPoint(this._pos),l=s.terrain.getElevationForLngLatZoom(this._lngLat,s.transform.tileZoom);if(s.transform.lngLatToCameraDepth(this._lngLat,l)-n<.006)return void(this._element.style.opacity=this._opacity);const c=-this._offset.y/s.transform.pixelsPerMeter,h=Math.sin(s.getPitch()*Math.PI/180)*c,u=s.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),d=s.transform.lngLatToCameraDepth(this._lngLat,l+h)-u>.006;(null===(o=this._popup)||void 0===o?void 0:o.isOpen())&&d&&this._popup.remove(),this._element.style.opacity=d?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return (void 0===this._opacity||void 0===e&&void 0===t)&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==e&&(this._opacity=e),void 0!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(!0),this}}const Ya={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let Qa=0,Ja=!1;const es={maxWidth:100,unit:"metric"};function ts(e,t,i){const o=i&&i.maxWidth||100,r=e._container.clientHeight/2,a=e._container.clientWidth/2,s=e.unproject([a-o/2,r]),n=e.unproject([a+o/2,r]),l=Math.round(e.project(n).x-e.project(s).x),c=Math.min(o,l,e._container.clientWidth),h=s.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?is(t,c,i/5280,e._getUIString("ScaleControl.Miles")):is(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?is(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?is(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):is(t,c,h,e._getUIString("ScaleControl.Meters"));}function is(e,t,i,o){const r=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(r/i)+"px",e.innerHTML=`${r} ${o}`;}const os={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1,locationOccludedOpacity:void 0},rs=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function as(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(i,i),"top-right":new t.P(-i,i),bottom:new t.P(0,-e),"bottom-left":new t.P(i,-i),"bottom-right":new t.P(-i,-i),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){const i=t.P.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e["top-left"]||[0,0]),"top-right":t.P.convert(e["top-right"]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e["bottom-left"]||[0,0]),"bottom-right":t.P.convert(e["bottom-right"]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return as(new t.P(0,0))}const ss=i;e.AJAXError=t.cz,e.Event=t.l,e.Evented=t.E,e.LngLat=t.S,e.MercatorCoordinate=t.a1,e.Point=t.P,e.addProtocol=t.cA,e.config=t.a,e.removeProtocol=t.cB,e.AttributionControl=Da,e.BoxZoomHandler=$r,e.CanvasSource=Y,e.CooperativeGesturesHandler=Ca,e.DoubleClickZoomHandler=ba,e.DragPanHandler=wa,e.DragRotateHandler=Ta,e.EdgeInsets=Mt,e.FullscreenControl=class extends t.E{constructor(e={}){super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(e=null==t?void 0:t.shadowRoot)||void 0===e?void 0:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){n.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=n.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);n.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new t.l("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.l("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=H,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.l("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "BACKGROUND":case "BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.l("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.S(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.e({bearing:r},this.options.fitBoundsOptions),s=G.fromLngLat(i,o);this._map.fitBounds(s,a,{geolocateSource:!0});},this._updateMarker=e=>{if(e){const i=new t.S(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this._updateCircleRadiusIfNeeded();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded();},this._onError=e=>{if(this._map){if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Ja)return;this.options.trackUserLocation&&this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.l("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=n.create("button","maplibregl-ctrl-geolocate",this._container),n.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0);},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.w("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=n.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new Ka({element:this._dotElement}),this._circleElement=n.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ka({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onUpdate),this._map.on("move",this._onUpdate),this._map.on("rotate",this._onUpdate),this._map.on("pitch",this._onUpdate)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(e=>{const i=(null==e?void 0:e[0])instanceof ResizeObserverEntry;e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||i||this._map.isZooming()||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.l("trackuserlocationend")),this.fire(new t.l("userlocationlostfocus")));}));}},this.options=t.e({},Ya,e);}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t._(this,arguments,void 0,(function*(e=!1){if(void 0!==qa&&!e)return qa;if(void 0===window.navigator.permissions)return qa=!!window.navigator.geolocation,qa;try{const e=yield window.navigator.permissions.query({name:"geolocation"});qa="denied"!==e.state;}catch(e){qa=!!window.navigator.geolocation;}return qa}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),n.remove(this._container),this._map.off("zoom",this._onUpdate),this._map.off("move",this._onUpdate),this._map.off("rotate",this._onUpdate),this._map.off("pitch",this._onUpdate),this._map=void 0,Qa=0,Ja=!1;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case "WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case "ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadiusIfNeeded(){const e=this._userLocationDotMarker.getLngLat();if(!(this.options.showUserLocation&&this.options.showAccuracyCircle&&this._accuracy&&e))return;const t=this._map.project(e),i=this._map.unproject([t.x+100,t.y]),o=e.distanceTo(i)/100,r=2*this._accuracy/o;this._circleElement.style.width=`${r.toFixed(2)}px`,this._circleElement.style.height=`${r.toFixed(2)}px`;}trigger(){if(!this._setup)return t.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case "OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.l("trackuserlocationstart"));break;case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":case "BACKGROUND_ERROR":Qa--,Ja=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new t.l("trackuserlocationend"));break;case "BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.l("trackuserlocationstart")),this.fire(new t.l("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case "WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),Qa++,Qa>1?(e={maximumAge:6e5,timeout:0},Ja=!0):(e=this.options.positionOptions,Ja=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||void 0===e?void 0:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||void 0===e?void 0:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=n.create("button","maplibregl-ctrl-globe",this._container),n.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0;}},e.Hash=Er,e.ImageSource=X,e.KeyboardHandler=pa,e.LngLatBounds=G,e.LogoControl=Aa,e.Map=class extends Ra{constructor(e){var i,o;t.cw.mark(t.cx.create);const r=Object.assign(Object.assign(Object.assign({},Ga),e),{canvasContextAttributes:Object.assign(Object.assign({},Ga.canvasContextAttributes),e.canvasContextAttributes)});if(null!=r.minZoom&&null!=r.maxZoom&&r.minZoom>r.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=r.minPitch&&null!=r.maxPitch&&r.minPitch>r.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=r.minPitch&&r.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=r.maxPitch&&r.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const a=new Lt,s=new Ot;if(void 0!==r.minZoom&&a.setMinZoom(r.minZoom),void 0!==r.maxZoom&&a.setMaxZoom(r.maxZoom),void 0!==r.minPitch&&a.setMinPitch(r.minPitch),void 0!==r.maxPitch&&a.setMaxPitch(r.maxPitch),void 0!==r.renderWorldCopies&&a.setRenderWorldCopies(r.renderWorldCopies),super(a,s,{bearingSnap:r.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new La,this._controls=[],this._mapId=t.a7(),this._contextLost=e=>{e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new t.l("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._setupPainter(),this.resize(),this._update(),this.fire(new t.l("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update();},this._interactive=r.interactive,this._maxTileCacheSize=r.maxTileCacheSize,this._maxTileCacheZoomLevels=r.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},r.canvasContextAttributes),this._trackResize=!0===r.trackResize,this._bearingSnap=r.bearingSnap,this._centerClampedToGround=r.centerClampedToGround,this._refreshExpiredTiles=!0===r.refreshExpiredTiles,this._fadeDuration=r.fadeDuration,this._crossSourceCollisions=!0===r.crossSourceCollisions,this._collectResourceTiming=!0===r.collectResourceTiming,this._locale=Object.assign(Object.assign({},Ua),r.locale),this._clickTolerance=r.clickTolerance,this._overridePixelRatio=r.pixelRatio,this._maxCanvasSize=r.maxCanvasSize,this.transformCameraUpdate=r.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===r.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=p.addThrottleControl((()=>this.isMoving())),this._requestManager=new m(r.transformRequest),"string"==typeof r.container){if(this._container=document.getElementById(r.container),!this._container)throw new Error(`Container '${r.container}' not found.`)}else {if(!(r.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=r.container;}if(r.maxBounds&&this.setMaxBounds(r.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0);})),this.once("idle",(()=>{this._idleTriggered=!0;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let e=!1;const t=Sr((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{e?t(i):e=!0;})),this._resizeObserver.observe(this._container);}this.handlers=new Ea(this,r),this._hash=r.hash&&new Er("string"==typeof r.hash&&r.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:r.center,elevation:r.elevation,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,roll:r.roll}),r.bounds&&(this.resize(),this.fitBounds(r.bounds,t.e({},r.fitBoundsOptions,{duration:0}))));const n="string"==typeof r.style||!("globe"===(null===(o=null===(i=r.style)||void 0===i?void 0:i.projection)||void 0===o?void 0:o.type));this.resize(null,n),this._localIdeographFontFamily=r.localIdeographFontFamily,this._validateStyle=r.validateStyle,r.style&&this.setStyle(r.style,{localIdeographFontFamily:r.localIdeographFontFamily}),r.attributionControl&&this.addControl(new Da("boolean"==typeof r.attributionControl?void 0:r.attributionControl)),r.maplibreLogo&&this.addControl(new Aa,r.logoPosition),this.on("style.load",(()=>{if(n||this._resizeTransform(),this.transform.unmodified){const e=t.Q(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.l(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.l(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.l("sourcedataabort",e));}));}_getMapId(){return this._mapId}setGlobalStateProperty(e,t){return this.style.setGlobalStateProperty(e,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(e,i){if(void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.k(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const o=e.onAdd(this);this._controls.push(e);const r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.k(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}coveringTiles(e){return ve(this.transform,e)}calculateCameraOptionsFromTo(e,t,i,o){return null==o&&this.terrain&&(o=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(e,t,i,o)}resize(e,i=!0){const[o,r]=this._containerDimensions(),a=this._getClampedPixelRatio(o,r);if(this._resizeCanvas(o,r,a),this.painter.resize(o,r,a),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const t=this._getClampedPixelRatio(o,r);this._resizeCanvas(o,r,t),this.painter.resize(o,r,t);}this._resizeTransform(i);const s=!this._moving;return s&&(this.stop(),this.fire(new t.l("movestart",e)).fire(new t.l("move",e))),this.fire(new t.l("resize",e)),s&&this.fire(new t.l("moveend",e)),this}_resizeTransform(e=!0){var t;const[i,o]=this._containerDimensions();this.transform.resize(i,o,e),null===(t=this._requestedCameraState)||void 0===t||t.resize(i,o,e);}_getClampedPixelRatio(e,t){const{0:i,1:o}=this._maxCanvasSize,r=this.getPixelRatio(),a=e*r,s=t*r;return Math.min(a>i?i/a:1,s>o?o/s:1)*r}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&void 0!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(G.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom)return this.transform.setMinZoom(e),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(e),this._update(),this.getZoom()>e&&this.setZoom(e),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.setMinPitch(e),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch)return this.transform.setMaxPitch(e),this._update(),this.getPitch()>e&&this.setPitch(e),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.S.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||void 0===e?void 0:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||void 0===e?void 0:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||void 0===e?void 0:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e))),s=0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[];s.length?o||(o=!0,i.call(this,new jr(e,this,r.originalEvent,{features:s}))):o=!1;};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:()=>{o=!1;}}}}if("mouseleave"===e||"mouseout"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e)));(0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[]).length?o=!0:o&&(o=!1,i.call(this,new jr(e,this,r.originalEvent)));},a=t=>{o&&(o=!1,i.call(this,new jr(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:a}}}{const o=e=>{const o=t.filter((e=>this.getLayer(e))),r=0!==o.length?this.queryRenderedFeatures(e.point,{layers:o}):[];r.length&&(e.features=r,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:o}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const o=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in r.delegates)this.off(e,r.delegates[e]);return void o.splice(e,1)}}}on(e,t,i){if(void 0===i)return super.on(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);this._saveDelegatedListener(e,r);for(const e in r.delegates)this.on(e,r.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,o,i);}}}once(e,t,i){if(void 0===i)return super.once(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);for(const t in r.delegates){const a=r.delegates[t];r.delegates[t]=(...t)=>{this._removeDelegatedListener(e,o,i),a(...t);};}this._saveDelegatedListener(e,r);for(const e in r.delegates)this.once(e,r.delegates[e]);return this}off(e,t,i){return void 0===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let o;const r=e instanceof t.P||Array.isArray(e),a=r?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(r?{}:e)||{},a instanceof t.P||"number"==typeof a[0])o=[t.P.convert(a)];else {const e=t.P.convert(a[0]),i=t.P.convert(a[1]);o=[e,new t.P(i.x,e.y),i,new t.P(e.x,i.y),e];}return this.style.queryRenderedFeatures(o,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return !1!==(i=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,o;if(t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const r=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new wi(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,r):this.style.loadJSON(e,t,r),this):(null===(o=null===(i=this.style)||void 0===i?void 0:i.projection)||void 0===o||o.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new wi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){if("string"==typeof e){const o=this._requestManager.transformRequest(e,"Style");t.j(o,new AbortController).then((e=>{this._updateDiff(e.data,i);})).catch((e=>{e&&this.fire(new t.k(e));}));}else "object"==typeof e&&this._updateDiff(e,i);}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(o){t.w(`Unable to perform style diff: ${o.message||o.error||o}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():t.w("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){const i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.k(new Error(`There is no source with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.sourceCaches[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const o=this.style._layers[i];"hillshade"===o.type&&o.source===e.source&&t.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality."),"color-relief"===o.type&&o.source===e.source&&t.w("You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");}this.terrain=new Ba(this.painter,i,e),this.painter.renderToTexture=new Na(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{var i;"style"===t.dataType?this.terrain.sourceCache.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),"image"===(null===(i=t.source)||void 0===i?void 0:i.type)?this.terrain.sourceCache.freeRtt():this.terrain.sourceCache.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.l("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||void 0===e?void 0:e.options)&&void 0!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.sourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}}return !0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}setSourceTileLodParams(e,t,i){if(i){const o=this.getSource(i);if(!o)throw new Error(`There is no source with ID "${i}", cannot set LOD parameters`);o.calculateTileZoom=me(Math.max(1,e),Math.max(1,t));}else for(const i in this.style.sourceCaches)this.style.sourceCaches[i].getSource().calculateTileZoom=me(Math.max(1,e),Math.max(1,t));return this._update(!0),this}refreshTiles(e,i){const o=this.style.sourceCaches[e];if(!o)throw new Error(`There is no source cache with ID "${e}", cannot refresh tile`);void 0===i?o.reload(!0):o.refreshTiles(i.map((e=>new t.a4(e.z,e.x,e.y))));}addImage(e,i,o={}){const{pixelRatio:r=1,sdf:a=!1,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u}=o;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.b(i))){if(void 0===i.width||void 0===i.height)return this.fire(new t.k(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:o,height:s,data:d}=i,_=i;return this.style.addImage(e,{data:new t.R({width:o,height:s},new Uint8Array(d)),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:o,height:d,data:_}=s.getImageData(i);this.style.addImage(e,{data:new t.R({width:o,height:d},_),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0});}}updateImage(e,i){const o=this.style.getImage(e);if(!o)return this.fire(new t.k(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const r=i instanceof HTMLImageElement||t.b(i)?s.getImageData(i):i,{width:a,height:n,data:l}=r;if(void 0===a||void 0===n)return this.fire(new t.k(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(a!==o.data.width||n!==o.data.height)return this.fire(new t.k(new Error("The width and height of the updated image must be that same as the previous version of the image")));const c=!(i instanceof HTMLImageElement||t.b(i));return o.data.replace(l,c),this.style.updateImage(e,o),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.k(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(e);}loadImage(e){return p.getImage(this._requestManager.transformRequest(e,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(!0)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,o={}){return this.style.setPaintProperty(e,t,i,o),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,o={}){return this.style.setLayoutProperty(e,t,i,o),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(!0);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=n.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=n.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),o=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],o);const r=this._controlContainer=n.create("div","maplibregl-control-container",e),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{a[e]=n.create("div",`maplibregl-ctrl-${e} `,r);})),this._container.addEventListener("scroll",this._onMapScroll,!1);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0});let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:!0});let i=null;if(i=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e),!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new Mr(i,this.transform),l.testSupport(i);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.l("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){var i,o,r,a,n;const l=this._idleTriggered?this._fadeDuration:0,c=(null===(i=this.style.projection)||void 0===i?void 0:i.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let h=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,i=s.now();this.style.zoomHistory.update(e,i);const o=new t.F(e,{now:i,fadeDuration:l,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),r=o.crossFadingFactor();1===r&&r===this._crossFadingFactor||(h=!0,this._crossFadingFactor=r),this.style.update(o);}const u=(null===(o=this.style.projection)||void 0===o?void 0:o.transitionState)>0!==c;null===(r=this.style.projection)||void 0===r||r.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(a=this.style.projection)||void 0===a?void 0:a.transitionState,null===(n=this.style.projection)||void 0===n?void 0:n.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||u)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,l,this._crossSourceCollisions,u),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:l,showPadding:this.showPadding}),this.fire(new t.l("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,t.cw.mark(t.cx.load),this.fire(new t.l("load"))),this.style&&(this.style.hasTransitions()||h)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const d=this._sourcesDirty||this._styleDirty||this._placementDirty;return d||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.l("idle")),!this._loaded||this._fullyLoaded||d||(this._fullyLoaded=!0,t.cw.mark(t.cx.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),p.removeThrottleControl(this._imageQueueHandle),null===(e=this._resizeObserver)||void 0===e||e.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?void 0:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),n.remove(this._canvasContainer),n.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),t.cw.clearMetrics(),this._removed=!0,this.fire(new t.l("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,s.frame(this._frameRequest,(e=>{t.cw.frame(e),this._frameRequest=null;try{this._render(e);}catch(e){if(!t.cy(e)&&!function(e){return e.message===qo}(e))throw e}}),(()=>{})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return Za}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}},e.MapMouseEvent=jr,e.MapTouchEvent=Nr,e.MapWheelEvent=Ur,e.Marker=Ka,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.e({},Va,e),this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=n.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new $a(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){n.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=n.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.E{constructor(e){super(),this._updateOpacity=()=>{void 0!==this.options.locationOccludedOpacity&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:"");},this.remove=()=>(this._content&&n.remove(this._content),this._container&&(n.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new t.l("close"))),this),this._onMouseUp=e=>{this._update(e.point);},this._onMouseMove=e=>{this._update(e.point);},this._onDrag=e=>{this._update(e.point);},this._update=e=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=n.create("div","maplibregl-popup",this._map.getContainer()),this._tip=n.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer");}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),this._trackPointer&&!e)return;const t=this._flatPos=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&e?e:this._map.transform.locationToScreenPoint(this._lngLat));let i=this.options.anchor;const o=as(this.options.offset);if(!i){const e=this._container.offsetWidth,r=this._container.offsetHeight;let a;a=t.y+o.bottom.ythis._map.transform.height-r?["bottom"]:[],t.xthis._map.transform.width-e/2&&a.push("right"),i=0===a.length?"bottom":a.join("-");}let r=t.add(o[i]);this.options.subpixelPositioning||(r=r.round()),n.setTransform(this._container,`${Ha[i]} translate(${r.x}px,${r.y}px)`),Xa(this._container,i,"popup"),this._updateOpacity();},this._onClose=()=>{this.remove();},this.options=t.e(Object.create(os),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.l("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let o;for(i.innerHTML=e;o=i.firstChild,o;)t.appendChild(o);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||void 0===e?void 0:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=n.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}_createCloseButton(){this.options.closeButton&&(this._closeButton=n.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(rs);e&&e.focus();}},e.RasterDEMTileSource=W,e.RasterTileSource=q,e.ScaleControl=class{constructor(e){this._onMove=()=>{ts(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,ts(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},es),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){n.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;}},e.ScrollZoomHandler=va,e.Style=wi,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=n.create("button","maplibregl-ctrl-terrain",this._container),n.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){n.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0;}},e.TwoFingersTouchPitchHandler=da,e.TwoFingersTouchRotateHandler=ha,e.TwoFingersTouchZoomHandler=la,e.TwoFingersTouchZoomRotateHandler=Pa,e.VectorTileSource=$,e.VideoSource=K,e.addSourceType=(e,i)=>t._(void 0,void 0,void 0,(function*(){if(J(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{Q[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=A;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(R),A=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},e.createTileMesh=Xt,e.getMaxParallelImageRequests=function(){return t.a.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},e.getVersion=function(){return ss},e.getWorkerCount=function(){return z.workerCount},e.getWorkerUrl=function(){return t.a.WORKER_URL},e.importScriptInWorkers=function(e){return B().broadcast("IS",e)},e.prewarm=function(){k().acquire(R);},e.setMaxParallelImageRequests=function(e){t.a.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setRTLTextPlugin=function(e,t){return oe().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){z.workerCount=e;},e.setWorkerUrl=function(e){t.a.WORKER_URL=e;};})); + +// +// Our custom intro provides a specialized "define()" function, called by the +// AMD modules below, that sets up the worker blob URL and then executes the +// main module, storing its exported value as 'maplibregl' + + +var maplibregl$1 = maplibregl; + +return maplibregl$1; + +})); +//# sourceMappingURL=maplibre-gl.js.map diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt b/docs/articles/turf_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt new file mode 100644 index 0000000..624d1f1 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/LICENSE.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2023, MapTiler +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js new file mode 100644 index 0000000..0fe7116 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/maplibregl.umd.js @@ -0,0 +1,14 @@ +(function(j,ee){typeof exports=="object"&&typeof module<"u"?ee(exports,require("maplibre-gl")):typeof define=="function"&&define.amd?define(["exports","maplibre-gl"],ee):(j=typeof globalThis<"u"?globalThis:j||self,ee(j.maplibreglMaptilerGeocoder={},j.maplibregl))})(this,function(j,ee){"use strict";var Ws=Object.defineProperty;var bn=j=>{throw TypeError(j)};var Gs=(j,ee,me)=>ee in j?Ws(j,ee,{enumerable:!0,configurable:!0,writable:!0,value:me}):j[ee]=me;var A=(j,ee,me)=>Gs(j,typeof ee!="symbol"?ee+"":ee,me),wn=(j,ee,me)=>ee.has(j)||bn("Cannot "+me);var ue=(j,ee,me)=>(wn(j,ee,"read from private field"),me?me.call(j):ee.get(j)),Vt=(j,ee,me)=>ee.has(j)?bn("Cannot add the same private member more than once"):ee instanceof WeakSet?ee.add(j):ee.set(j,me),kt=(j,ee,me,dt)=>(wn(j,ee,"write to private field"),dt?dt.call(j,me):ee.set(j,me),me);var fn,cn;function me(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const dt=me(ee);function ne(){}function Ln(i,e){for(const t in e)i[t]=e[t];return i}function yi(i){return i()}function vi(){return Object.create(null)}function Ue(i){i.forEach(yi)}function bi(i){return typeof i=="function"}function Ke(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}let Rt;function ye(i,e){return i===e?!0:(Rt||(Rt=document.createElement("a")),Rt.href=e,i===Rt.href)}function _n(i){return Object.keys(i).length===0}function Sn(i,e,t,n){if(i){const r=wi(i,e,t,n);return i[0](r)}}function wi(i,e,t,n){return i[1]&&n?Ln(t.ctx.slice(),i[1](n(e))):t.ctx}function xn(i,e,t,n){return i[2],e.dirty}function Tn(i,e,t,n,r,u){if(r){const a=wi(e,t,n,u);i.p(a,r)}}function Mn(i){if(i.ctx.length>32){const e=[],t=i.ctx.length/32;for(let n=0;ni.removeEventListener(e,t,n)}function Nn(i){return function(e){return e.preventDefault(),i.call(this,e)}}function S(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function kn(i){return Array.from(i.childNodes)}function gt(i,e){e=""+e,i.data!==e&&(i.data=e)}function Ei(i,e){i.value=e??""}function Ie(i,e,t){i.classList.toggle(e,!!t)}function On(i,e,{bubbles:t=!1,cancelable:n=!1}={}){return new CustomEvent(i,{detail:e,bubbles:t,cancelable:n})}let mt;function pt(i){mt=i}function Li(){if(!mt)throw new Error("Function called outside component initialization");return mt}function Rn(i){Li().$$.on_destroy.push(i)}function _i(){const i=Li();return(e,t,{cancelable:n=!1}={})=>{const r=i.$$.callbacks[e];if(r){const u=On(e,t,{cancelable:n});return r.slice().forEach(a=>{a.call(i,u)}),!u.defaultPrevented}return!0}}function Pn(i,e){const t=i.$$.callbacks[e.type];t&&t.slice().forEach(n=>n.call(this,e))}const ut=[],Yt=[];let at=[];const Si=[],In=Promise.resolve();let Qt=!1;function An(){Qt||(Qt=!0,In.then(xi))}function Xt(i){at.push(i)}const Jt=new Set;let ft=0;function xi(){if(ft!==0)return;const i=mt;do{try{for(;fti.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),at=e}const It=new Set;let nt;function yt(){nt={r:0,c:[],p:nt}}function vt(){nt.r||Ue(nt.c),nt=nt.p}function re(i,e){i&&i.i&&(It.delete(i),i.i(e))}function fe(i,e,t,n){if(i&&i.o){if(It.has(i))return;It.add(i),nt.c.push(()=>{It.delete(i),n&&(t&&i.d(1),n())}),i.o(e)}else n&&n()}function Ti(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function Gn(i,e){fe(i,1,1,()=>{e.delete(i.key)})}function Dn(i,e,t,n,r,u,a,o,g,c,E,_){let M=i.length,R=u.length,k=M;const I={};for(;k--;)I[i[k].key]=k;const C=[],O=new Map,x=new Map,N=[];for(k=R;k--;){const W=_(r,u,k),s=t(W);let l=a.get(s);l?N.push(()=>l.p(W,e)):(l=c(s,W),l.c()),O.set(s,C[k]=l),s in I&&x.set(s,Math.abs(k-I[s]))}const P=new Set,B=new Set;function z(W){re(W,1),W.m(o,E),a.set(W.key,W),E=W.first,R--}for(;M&&R;){const W=C[R-1],s=i[M-1],l=W.key,f=s.key;W===s?(E=W.first,M--,R--):O.has(f)?!a.has(l)||P.has(l)?z(W):B.has(f)?M--:x.get(l)>x.get(f)?(B.add(l),z(W)):(P.add(f),M--):(g(s,a),M--)}for(;M--;){const W=i[M];O.has(W.key)||g(W,a)}for(;R;)z(C[R-1]);return Ue(N),C}function Qe(i){i&&i.c()}function qe(i,e,t){const{fragment:n,after_update:r}=i.$$;n&&n.m(e,t),Xt(()=>{const u=i.$$.on_mount.map(yi).filter(bi);i.$$.on_destroy?i.$$.on_destroy.push(...u):Ue(u),i.$$.on_mount=[]}),r.forEach(Xt)}function Fe(i,e){const t=i.$$;t.fragment!==null&&(Wn(t.after_update),Ue(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function zn(i,e){i.$$.dirty[0]===-1&&(ut.push(i),An(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<{const k=R.length?R[0]:M;return c.ctx&&r(c.ctx[_],c.ctx[_]=k)&&(!c.skip_bound&&c.bound[_]&&c.bound[_](k),E&&zn(i,_)),M}):[],c.update(),E=!0,Ue(c.before_update),c.fragment=n?n(c.ctx):!1,e.target){if(e.hydrate){const _=kn(e.target);c.fragment&&c.fragment.l(_),_.forEach($)}else c.fragment&&c.fragment.c();e.intro&&re(i.$$.fragment),qe(i,e.target,e.anchor),xi()}pt(g)}class Je{constructor(){A(this,"$$");A(this,"$$set")}$destroy(){Fe(this,1),this.$destroy=ne}$on(e,t){if(!bi(t))return ne;const n=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return n.push(t),()=>{const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}$set(e){this.$$set&&!_n(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Un="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Un);function qn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M13.12.706a.982.982 0 0 0-1.391 0L6.907 5.517 2.087.696a.982.982 0 1 0-1.391 1.39l4.821 4.821L.696 11.73a.982.982 0 1 0 1.39 1.39l4.821-4.821 4.822 4.821a.982.982 0 1 0 1.39-1.39L8.298 6.908l4.821-4.822a.988.988 0 0 0 0-1.38Z"),S(e,"viewBox","0 0 14 14"),S(e,"width","13"),S(e,"height","13"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Mi extends Je{constructor(e){super(),Xe(this,e,null,qn,Ke,{})}}function Fn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M15 0C6.705 0 0 6.705 0 15C0 23.295 6.705 30 15 30C23.295 30 30 23.295 30 15C30 6.705 23.295 0 15 0ZM22.5 20.385L20.385 22.5L15 17.115L9.615 22.5L7.5 20.385L12.885 15L7.5 9.615L9.615 7.5L15 12.885L20.385 7.5L22.5 9.615L17.115 15L22.5 20.385Z"),S(e,"viewBox","0 0 30 30"),S(e,"fill","none"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"class","svelte-d2loi5")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Ci extends Je{constructor(e){super(),Xe(this,e,null,Fn,Ke,{})}}function jn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"area.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"area.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Zn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"reverse.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"reverse.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Hn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"poi.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"poi.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Vn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"postal_code.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"postal_code.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Kn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"street.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"street.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Yn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"road.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"road.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Qn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"housenumber.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"housenumber.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Xn(i){let e,t,n,r;return{c(){e=Y("img"),ye(e.src,t=i[5])||S(e,"src",t),S(e,"alt",i[4]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(u,a){te(u,e,a),n||(r=he(e,"error",i[14]),n=!0)},p(u,a){a&32&&!ye(e.src,t=u[5])&&S(e,"src",t),a&16&&S(e,"alt",u[4]),a&128&&S(e,"title",u[7])},d(u){u&&$(e),n=!1,r()}}}function Jn(i){let e,t;return{c(){e=Y("div"),S(e,"class","sprite-icon svelte-w9y5n9"),S(e,"style",t=` + width: ${i[6].width/xe}px; + height: ${i[6].height/xe}px; + background-image: url(${i[3]}sprite${$t}.png); + background-position: -${i[6].x/xe}px -${i[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `),S(e,"title",i[7])},m(n,r){te(n,e,r)},p(n,r){r&72&&t!==(t=` + width: ${n[6].width/xe}px; + height: ${n[6].height/xe}px; + background-image: url(${n[3]}sprite${$t}.png); + background-position: -${n[6].x/xe}px -${n[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `)&&S(e,"style",t),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Ni(i){let e,t;return{c(){e=Y("span"),t=Ye(i[7]),S(e,"class","secondary svelte-w9y5n9")},m(n,r){te(n,e,r),V(e,t)},p(n,r){r&128&>(t,n[7])},d(n){n&&$(e)}}}function $n(i){let e,t,n,r,u,a,o,g,c,E=(i[8]?i[0].place_name:i[0].place_name.replace(/,.*/,""))+"",_,M,R=i[2]==="always"||i[2]!=="never"&&!i[0].address&&!i[0].id.startsWith("road.")&&!i[0].id.startsWith("address.")&&!i[0].id.startsWith("postal_code.")&&(!i[0].id.startsWith("poi.")||!i[5])&&!i[8],k,I,C=(i[8]?"":i[0].place_name.replace(/[^,]*,?\s*/,""))+"",O,x,N,P,B,z;function W(m,h){return h&1&&(t=null),h&1&&(n=null),h&1&&(r=null),h&1&&(u=null),Oe&&m[6]?Jn:m[5]?Xn:m[0].address?Qn:(t==null&&(t=!!m[0].id.startsWith("road.")),t?Yn:(n==null&&(n=!!m[0].id.startsWith("address.")),n?Kn:(r==null&&(r=!!m[0].id.startsWith("postal_code.")),r?Vn:(u==null&&(u=!!m[0].id.startsWith("poi.")),u?Hn:m[8]?Zn:jn))))}let s=W(i,-1),l=s(i),f=R&&Ni(i);return{c(){e=Y("li"),l.c(),a=we(),o=Y("span"),g=Y("span"),c=Y("span"),_=Ye(E),M=we(),f&&f.c(),k=we(),I=Y("span"),O=Ye(C),S(c,"class","primary svelte-w9y5n9"),S(g,"class","svelte-w9y5n9"),S(I,"class","line2 svelte-w9y5n9"),S(o,"class","texts svelte-w9y5n9"),S(e,"tabindex","-1"),S(e,"role","option"),S(e,"aria-selected",x=i[1]==="selected"),S(e,"aria-checked",N=i[1]==="picked"),S(e,"class",P=Pt(i[1])+" svelte-w9y5n9")},m(m,h){te(m,e,h),l.m(e,null),V(e,a),V(e,o),V(o,g),V(g,c),V(c,_),V(g,M),f&&f.m(g,null),V(o,k),V(o,I),V(I,O),B||(z=[he(e,"mouseenter",i[13]),he(e,"focus",i[15]),he(e,"click",i[16])],B=!0)},p(m,[h]){s===(s=W(m,h))&&l?l.p(m,h):(l.d(1),l=s(m),l&&(l.c(),l.m(e,a))),h&257&&E!==(E=(m[8]?m[0].place_name:m[0].place_name.replace(/,.*/,""))+"")&>(_,E),h&293&&(R=m[2]==="always"||m[2]!=="never"&&!m[0].address&&!m[0].id.startsWith("road.")&&!m[0].id.startsWith("address.")&&!m[0].id.startsWith("postal_code.")&&(!m[0].id.startsWith("poi.")||!m[5])&&!m[8]),R?f?f.p(m,h):(f=Ni(m),f.c(),f.m(g,null)):f&&(f.d(1),f=null),h&257&&C!==(C=(m[8]?"":m[0].place_name.replace(/[^,]*,?\s*/,""))+"")&>(O,C),h&2&&x!==(x=m[1]==="selected")&&S(e,"aria-selected",x),h&2&&N!==(N=m[1]==="picked")&&S(e,"aria-checked",N),h&2&&P!==(P=Pt(m[1])+" svelte-w9y5n9")&&S(e,"class",P)},i:ne,o:ne,d(m){m&&$(e),l.d(),f&&f.d(),B=!1,Ue(z)}}}const ki=typeof devicePixelRatio>"u"?1:devicePixelRatio>1.25,$t=ki?"@2x":"",xe=ki?2:1;let Oe,At;function er(i,e,t){let n,r,u,{feature:a}=e,{style:o="default"}=e,{showPlaceType:g}=e,{missingIconsCache:c}=e,{iconsBaseUrl:E}=e;const _=_i();let M,R,k,I;function C(){At??(At=fetch(`${E}sprite${$t}.json`).then(s=>s.json()).then(s=>{Oe=s}).catch(()=>{Oe=null}))}function O(){R&&c.add(R),x()}function x(){Oe!==void 0?N():(C(),At==null||At.then(N))}function N(){do{if(I--,t(4,M=n==null?void 0:n[I]),t(6,k=M?Oe==null?void 0:Oe.icons[M]:void 0),k)break;t(5,R=M?E+M.replace(/ /g,"_")+".svg":void 0)}while(I>-1&&(!R||c.has(R)))}function P(s){Pn.call(this,i,s)}const B=()=>O(),z=()=>_("select",void 0),W=s=>{document.activeElement!==s.target&&_("select",void 0)};return i.$$set=s=>{"feature"in s&&t(0,a=s.feature),"style"in s&&t(1,o=s.style),"showPlaceType"in s&&t(2,g=s.showPlaceType),"missingIconsCache"in s&&t(11,c=s.missingIconsCache),"iconsBaseUrl"in s&&t(3,E=s.iconsBaseUrl)},i.$$.update=()=>{var s,l,f,m,h;i.$$.dirty&1&&t(12,n=(s=a.properties)==null?void 0:s.categories),i.$$.dirty&1&&t(8,r=a.place_type[0]==="reverse"),i.$$.dirty&1&&t(7,u=((f=(l=a.properties)==null?void 0:l.categories)==null?void 0:f.join(", "))??((h=(m=a.properties)==null?void 0:m.place_type_name)==null?void 0:h[0])??a.place_type[0]),i.$$.dirty&4096&&(I=(n==null?void 0:n.length)??0,x())},[a,o,g,E,M,R,k,u,r,_,O,c,n,P,B,z,W]}class tr extends Je{constructor(e){super(),Xe(this,e,er,$n,Ke,{feature:0,style:1,showPlaceType:2,missingIconsCache:11,iconsBaseUrl:3})}}function ir(i){let e;return{c(){e=Y("div"),e.innerHTML='',S(e,"class","svelte-1ocfouu")},m(t,n){te(t,e,n)},p:ne,i:ne,o:ne,d(t){t&&$(e)}}}class nr extends Je{constructor(e){super(),Xe(this,e,null,ir,Ke,{})}}function rr(i){let e,t,n;return{c(){e=ke("svg"),t=ke("path"),S(t,"stroke-width","4"),S(t,"d","M 5,33.103579 C 5,17.607779 18.457,5 35,5 C 51.543,5 65,17.607779 65,33.103579 C 65,56.388679 40.4668,76.048179 36.6112,79.137779 C 36.3714,79.329879 36.2116,79.457979 36.1427,79.518879 C 35.8203,79.800879 35.4102,79.942779 35,79.942779 C 34.5899,79.942779 34.1797,79.800879 33.8575,79.518879 C 33.7886,79.457979 33.6289,79.330079 33.3893,79.138079 C 29.5346,76.049279 5,56.389379 5,33.103579 Z M 35.0001,49.386379 C 43.1917,49.386379 49.8323,42.646079 49.8323,34.331379 C 49.8323,26.016779 43.1917,19.276479 35.0001,19.276479 C 26.8085,19.276479 20.1679,26.016779 20.1679,34.331379 C 20.1679,42.646079 26.8085,49.386379 35.0001,49.386379 Z"),S(t,"class","svelte-gzo3ar"),S(e,"width",n=i[0]==="list"?20:void 0),S(e,"viewBox","0 0 70 85"),S(e,"fill","none"),S(e,"class","svelte-gzo3ar"),Ie(e,"in-map",i[0]!=="list"),Ie(e,"list-icon",i[0]==="list")},m(r,u){te(r,e,u),V(e,t)},p(r,[u]){u&1&&n!==(n=r[0]==="list"?20:void 0)&&S(e,"width",n),u&1&&Ie(e,"in-map",r[0]!=="list"),u&1&&Ie(e,"list-icon",r[0]==="list")},i:ne,o:ne,d(r){r&&$(e)}}}function sr(i,e,t){let{displayIn:n}=e;return i.$$set=r=>{"displayIn"in r&&t(0,n=r.displayIn)},[n]}class or extends Je{constructor(e){super(),Xe(this,e,sr,rr,Ke,{displayIn:0})}}function lr(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M30.003-26.765C13.46-26.765 0-14.158 0 1.337c0 23.286 24.535 42.952 28.39 46.04.24.192.402.316.471.376.323.282.732.424 1.142.424.41 0 .82-.142 1.142-.424.068-.06.231-.183.471-.376 3.856-3.09 28.39-22.754 28.39-46.04 0-15.495-13.46-28.102-30.003-28.102Zm1.757 12.469c4.38 0 7.858 1.052 10.431 3.158 2.595 2.105 3.89 4.913 3.89 8.422 0 2.34-.53 4.362-1.593 6.063-1.063 1.702-3.086 3.616-6.063 5.742-2.042 1.51-3.337 2.659-3.89 3.446-.532.787-.8 1.82-.8 3.096v1.914h-8.449V15.18c0-2.041.434-3.815 1.306-5.325.872-1.51 2.467-3.118 4.785-4.82 2.233-1.594 3.7-2.89 4.402-3.889a5.582 5.582 0 0 0 1.087-3.35c0-1.382-.51-2.435-1.531-3.158-1.02-.723-2.45-1.087-4.28-1.087-3.19 0-6.826 1.047-10.91 3.131l-3.472-6.986c4.742-2.659 9.77-3.992 15.087-3.992Zm-1.88 37.324c1.765 0 3.124.472 4.08 1.408.98.936 1.47 2.276 1.47 4.02 0 1.68-.49 3.007-1.47 3.985-.977.957-2.336 1.435-4.08 1.435-1.787 0-3.171-.465-4.15-1.4-.978-.958-1.47-2.298-1.47-4.02 0-1.787.48-3.14 1.436-4.054.957-.915 2.355-1.374 4.184-1.374Z"),S(e,"viewBox","0 0 60.006 21.412"),S(e,"width","14"),S(e,"height","20"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class ur extends Je{constructor(e){super(),Xe(this,e,null,lr,Ke,{})}}function ar(i){let e,t,n;return{c(){e=ke("svg"),t=ke("circle"),n=ke("path"),S(t,"cx","4.789"),S(t,"cy","4.787"),S(t,"r","3.85"),S(t,"class","svelte-1aq105l"),S(n,"d","M12.063 12.063 7.635 7.635"),S(n,"class","svelte-1aq105l"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"width","13"),S(e,"height","13"),S(e,"viewBox","0 0 13 13"),S(e,"class","svelte-1aq105l")},m(r,u){te(r,e,u),V(e,t),V(e,n)},p:ne,i:ne,o:ne,d(r){r&&$(e)}}}class fr extends Je{constructor(e){super(),Xe(this,e,null,ar,Ke,{})}}function cr(i,e,t){const n=e[1],r=e[0],u=n-r;return i===n&&t?i:((i-r)%u+u)%u+r}function Bt(i){const e=[...i];return e[2]Math.abs((e[0]-360+e[2])/2)?e[0]-=360:e[2]+=360),e}let bt;async function hr(i,e,t){const n=i==null?void 0:i.getCenterAndZoom();for(const r of e??[])if(!(n&&(r.minZoom!=null&&r.minZoom>n[0]||r.maxZoom!=null&&r.maxZoomDate.now()){if(!bt.coords)break e;return bt.coords}let u;try{return u=await new Promise((a,o)=>{t.signal.addEventListener("abort",()=>{o(Error("aborted"))}),navigator.geolocation.getCurrentPosition(g=>{a([g.coords.longitude,g.coords.latitude].map(c=>c.toFixed(6)).join(","))},g=>{o(g)},r)}),u}catch{}finally{r.cachedLocationExpiry&&(bt={time:Date.now(),coords:u})}if(t.signal.aborted)return}if(r.type==="server-geolocation")return"ip";if(n&&r.type==="map-center")return n[1].toFixed(6)+","+n[2].toFixed(6)}}const dr=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(EAST|WEST|[EW])?$/i,Oi=/^([+-]?[0-8]?[0-9])\s+([0-5]?[0-9]\.\d{3,})[\s,]{1,}([+-]?[0-1]?[0-9]?[0-9])\s+([0-5]?[0-9]\.\d{3,})$/,Ri=/^(NORTH|SOUTH|[NS])?[\s]*([+-]?[0-8]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(NORTH|SOUTH|[NS])?[\s]*[,/;]?[\s]*(EAST|WEST|[EW])?[\s]*([+-]?[0-1]?[0-9]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(EAST|WEST|[EW])?$/i,Pi=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(EAST|WEST|[EW])?$/i,Ii=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)\s*(EAST|WEST|[EW])?$/i,Ai=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|’’|´´|["″”\.])?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|´´|’’|["″”\.])?\s*(EAST|WEST|[EW])?$/i;function gr(i){if(!["DMS","DM","DD"].includes(i))throw new Error("invalid format specified");if(this.decimalCoordinates&&this.decimalCoordinates.trim()){const e=this.decimalCoordinates.split(",").map(R=>Number(R.trim())),t=Number(e[0]),n=Number(e[1]),r=Math.abs(t),u=Math.abs(n),a=t>0?"N":"S",o=n>0?"E":"W";let g;i=="DD"&&(g=`${r}° ${a}, ${u}° ${o}`);const c=Math.floor(r),E=Math.floor(u),_=(r-c)*60,M=(u-E)*60;if(i=="DM"){let R=Bi(_,3).toFixed(3).padStart(6,"0"),k=Bi(M,3).toFixed(3).padStart(6,"0");R.endsWith(".000")&&k.endsWith(".000")&&(R=R.replace(/\.000$/,""),k=k.replace(/\.000$/,"")),g=`${c}° ${R}' ${a}, ${E}° ${k}' ${o}`}if(i=="DMS"){const R=Math.floor(_),k=Math.floor(M);let I=((_-R)*60).toFixed(1).padStart(4,"0"),C=((M-k)*60).toFixed(1).padStart(4,"0");const O=R.toString().padStart(2,"0"),x=k.toString().padStart(2,"0");I.endsWith(".0")&&C.endsWith(".0")&&(I=I.replace(/\.0$/,""),C=C.replace(/\.0$/,"")),g=`${c}° ${O}' ${I}" ${a}, ${E}° ${x}' ${C}" ${o}`}return g}else throw new Error("no decimal coordinates to convert")}function Bi(i,e){const t=Math.pow(10,e);return Math.round((i+Number.EPSILON)*t)/t}function ei(i,e){e||(e=5),i=i.replace(/\s+/g," ").trim();let t=null,n=null,r="",u="",a=null,o=[],g=!1;if(dr.test(i))throw new Error("invalid coordinate value");if(Oi.test(i))if(o=Oi.exec(i),g=wt(o),g)t=Math.abs(o[1])+o[2]/60,Number(o[1])<0&&(t*=-1),n=Math.abs(o[3])+o[4]/60,Number(o[3])<0&&(n*=-1),a="DM";else throw new Error("invalid coordinate format");else if(Ri.test(i))if(o=Ri.exec(i),g=wt(o),g){if(t=o[2],n=o[6],t.includes(",")&&(t=t.replace(",",".")),n.includes(",")&&(n=n.replace(",",".")),a="DD",Number(Math.round(t))==Number(t))throw new Error("integer only coordinate provided");if(Number(Math.round(n))==Number(n))throw new Error("integer only coordinate provided");o[1]?(r=o[1],u=o[5]):o[4]&&(r=o[4],u=o[8])}else throw new Error("invalid decimal coordinate format");else if(Pi.test(i))if(o=Pi.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[9])),o[11]&&(n+=o[11]/60),o[13]&&(n+=o[13].replace(",",".")/3600),parseInt(o[9])<0&&(n=-1*n),o[1]?(r=o[1],u=o[8]):o[7]&&(r=o[7],u=o[14]);else throw new Error("invalid DMS coordinates format");else if(Ii.test(i))if(o=Ii.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6]/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12]/60),o[14]&&(n+=o[14]/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid DMS coordinates format");else if(Ai.test(i)){if(o=Ai.exec(i),g=wt(o),o.filter(c=>c).length<=5)throw new Error("invalid coordinates format");if(g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4].replace(",",".")/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12].replace(",",".")/60),o[14]&&(n+=o[14].replace(",",".")/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid coordinates format")}if(g){if(Math.abs(n)>=180)throw new Error("invalid longitude value");if(Math.abs(t)>=90)throw new Error("invalid latitude value");if(r&&!u||!r&&u)throw new Error("invalid coordinates value");if(r&&r==u)throw new Error("invalid coordinates format");t.toString().includes(",")&&(t=t.replace(",",".")),n.toString().includes(",")&&(n=n.replace(",","."));let c=/S|SOUTH/i;c.test(r)&&t>0&&(t=-1*t),c=/W|WEST/i,c.test(u)&&n>0&&(n=-1*n);const E=o[0].trim();let _,M;const R=/[,/;\u0020]/g,k=E.match(R);if(k==null){const O=Math.floor(i.length/2);_=E.substring(0,O).trim(),M=E.substring(O).trim()}else{let O;k.length%2==1?O=Math.floor(k.length/2):O=k.length/2-1;let x=0;if(O==0)x=E.indexOf(k[0]),_=E.substring(0,x).trim(),M=E.substring(x+1).trim();else{let N=0,P=0;for(;N<=O;)x=E.indexOf(k[N],P),P=x+1,N++;_=E.substring(0,x).trim(),M=E.substring(x+1).trim()}}const I=_.split(".");if(I.length==2&&I[1]==0&&I[1].length!=2)throw new Error("invalid coordinates format");const C=M.split(".");if(C.length==2&&C[1]==0&&C[1].length!=2)throw new Error("invalid coordinates format");if(/^\d+$/.test(_)||/^\d+$/.test(M))throw new Error("degree only coordinate/s provided");return t=Number(Number(t).toFixed(e)),n=Number(Number(n).toFixed(e)),Object.freeze({verbatimCoordinates:E,verbatimLatitude:_,verbatimLongitude:M,decimalLatitude:t,decimalLongitude:n,decimalCoordinates:`${t},${n}`,originalFormat:a,closeEnough:mr,toCoordinateFormat:gr})}else throw new Error("coordinates pattern match failed")}function wt(i){if(!isNaN(i[0]))return!1;const e=[...i];if(e.shift(),e.length%2>0)return!1;const t=/^[-+]?\d+([\.,]\d+)?$/,n=/[eastsouthnorthwest]+/i,r=e.length/2;for(let u=0;u{e.decimalLatitude?i.push(e):i.push({...e,...vr})}),[...i,...br,...wr]}const Lr=Er();ei.formats=Lr.map(i=>i.verbatimCoordinates);const _r=ei;function Gi(i,e,t){const n=i.slice();return n[97]=e[t],n[99]=t,n}function Di(i){let e,t,n,r,u;return t=new Mi({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[3]),S(e,"class","svelte-bz0zu3")},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[78]),r=!0)},p(a,o){(!n||o[0]&8)&&S(e,"title",a[3])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function zi(i){let e,t;return e=new nr({}),{c(){Qe(e.$$.fragment)},m(n,r){qe(e,n,r),t=!0},i(n){t||(re(e.$$.fragment,n),t=!0)},o(n){fe(e.$$.fragment,n),t=!1},d(n){Fe(e,n)}}}function Ui(i){let e,t,n,r,u;return t=new ur({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[10]),S(e,"class","svelte-bz0zu3"),Ie(e,"active",i[0])},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[79]),r=!0)},p(a,o){(!n||o[0]&1024)&&S(e,"title",a[10]),(!n||o[0]&1)&&Ie(e,"active",a[0])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function Sr(i){let e,t=[],n=new Map,r,u,a,o=Ti(i[13]);const g=c=>c[97].id+(c[97].address?","+c[97].address:"");for(let c=0;c{B=null}),vt()):B?(B.p(d,v),v[0]&1048576&&re(B,1)):(B=Di(d),B.c(),re(B,1),B.m(c,E)),d[20]?z?v[0]&1048576&&re(z,1):(z=zi(),z.c(),re(z,1),z.m(c,null)):z&&(yt(),fe(z,1,1,()=>{z=null}),vt()),(!O||v[0]&2)&&Ie(c,"displayable",d[1]!==""),d[6]==="button"?W?(W.p(d,v),v[0]&64&&re(W,1)):(W=Ui(d),W.c(),re(W,1),W.m(n,M)):W&&(yt(),fe(W,1,1,()=>{W=null}),vt()),l&&l.p&&(!O||v[2]&128)&&Tn(l,s,d,d[69],O?xn(s,d[69],v,null):Mn(d[69]),null);let p=k;k=h(d),k===p?~k&&m[k].p(d,v):(I&&(yt(),fe(m[p],1,1,()=>{m[p]=null}),vt()),~k?(I=m[k],I?I.p(d,v):(I=m[k]=f[k](d),I.c()),re(I,1),I.m(t,null)):I=null),(!O||v[0]&4&&C!==(C=Pt(d[2])+" svelte-bz0zu3"))&&S(t,"class",C),(!O||v[0]&38)&&Ie(t,"can-collapse",d[5]&&d[1]==="")},i(d){O||(re(P),re(u.$$.fragment,d),re(B),re(z),re(W),re(l,d),re(I),O=!0)},o(d){fe(P),fe(u.$$.fragment,d),fe(B),fe(z),fe(W),fe(l,d),fe(I),O=!1},d(d){d&&($(e),$(t)),Fe(u),i[72](null),B&&B.d(),z&&z.d(),W&&W.d(),l&&l.d(d),~k&&m[k].d(),x=!1,Ue(N)}}}function Nr(i,e,t){let n,r,u,{$$slots:a={},$$scope:o}=e;const g={continental_marine:4,country:4,major_landform:8,region:5,subregion:6,county:7,joint_municipality:8,joint_submunicipality:9,municipality:10,municipal_district:11,locality:12,neighbourhood:13,place:14,postal_code:14,road:16,poi:17,address:18,"poi.peak":15,"poi.shop":18,"poi.cafe":18,"poi.restaurant":18,"poi.aerodrome":13};let{class:c=void 0}=e,{apiKey:E=void 0}=e,{bbox:_=void 0}=e,{clearButtonTitle:M="clear"}=e,{clearOnBlur:R=!1}=e,{clearListOnPick:k=!1}=e,{keepListOpen:I=!1}=e,{collapsed:C=!1}=e,{country:O=void 0}=e,{debounceSearch:x=200}=e,{enableReverse:N="never"}=e,{errorMessage:P="Something went wrong…"}=e,{filter:B=()=>!0}=e,{flyTo:z=!0}=e,{fuzzyMatch:W=!0}=e,{language:s=void 0}=e,{limit:l=void 0}=e;const f=41415112612;let{reverseGeocodingLimit:m=f}=e,{mapController:h=void 0}=e,{minLength:d=2}=e,{noResultsMessage:v="Oops! Looks like you're trying to predict something that's not quite right. We can't seem to find what you're looking for. Maybe try double-checking your spelling or try a different search term. Keep on typing - we'll do our best to get you where you need to go!"}=e,{placeholder:p="Search"}=e,{proximity:y=[{type:"server-geolocation"}]}=e,{reverseActive:b=N==="always"}=e,{reverseButtonTitle:w="toggle reverse geocoding"}=e,{searchValue:T=""}=e,{pickedResultStyle:G="full-geometry"}=e,{showPlaceType:D="if-needed"}=e,{showResultsWhileTyping:H=!0}=e,{selectFirst:Q=!0}=e,{flyToSelected:se=!1}=e,{markerOnSelected:Z=!0}=e,{types:K=void 0}=e;const de=[];let{reverseGeocodingTypes:He=de}=e,{exhaustiveReverseGeocoding:st=!1}=e,{excludeTypes:ot=!1}=e;const Le=void 0;let{reverseGeocodingExcludeTypes:We=Le}=e,{zoom:pe=g}=e,{apiUrl:ge="https://api.maptiler.com/geocoding"}=e,{fetchParameters:ie={}}=e,{iconsBaseUrl:hn="https://cdn.maptiler.com/maptiler-geocoding-control/v2.1.7/icons/"}=e,{adjustUrlQuery:ui=()=>{}}=e,{adjustUrl:ai=()=>{}}=e;function gs(L){Pe.focus(L)}function ms(){Pe.blur()}function dn(L,le=!0,ae=!1){t(1,T=L),le?(t(15,X=-1),mn()):(pn(void 0,!ae,ae),setTimeout(()=>{Pe.focus(),Pe.select()}))}function ps(){t(13,F=void 0),t(14,U=void 0),t(15,X=-1)}function ys(){t(64,ce=[]),t(14,U=void 0)}let F,ce,U,gn="",Pe,X=-1,Ge,Zt=[],lt,ct,ht,fi,Ve=!1;const vs=new Set,tt=_i();Rn(()=>{h&&(h.setEventHandler(void 0),h.indicateReverse(!1),h.setSelectedMarker(-1),h.setFeatures(void 0,void 0,!1))});function mn(L){if(t(17,Ve=!1),ct&&(clearTimeout(ct),ct=void 0),X>-1&&F)t(14,U=F[X]),t(1,T=U.place_type[0]==="reverse"?U.place_name:U.place_name.replace(/,.*/,"")),t(19,Ge=void 0),t(64,ce=void 0),t(15,X=-1);else if(T){const le=L||!ci(T);hi(T,{exact:!0}).then(()=>{t(64,ce=F),t(14,U=void 0),le&&bs()}).catch(ae=>t(19,Ge=ae))}}function ci(L){try{return _r(L,6)}catch{return!1}}async function hi(L,{byId:le=!1,exact:ae=!1}={}){var Se,De,it;t(19,Ge=void 0),lt==null||lt.abort();const _e=new AbortController;t(20,lt=_e);try{const J=ci(L),Mt=new URL(ge+"/"+encodeURIComponent(J?J.decimalLongitude+","+J.decimalLatitude:L)+".json"),Ne=Mt.searchParams;s!==void 0&&Ne.set("language",Array.isArray(s)?s.join(","):s??"");const[mi]=(h==null?void 0:h.getCenterAndZoom())??[];let ze=(Se=!J||He===de?K:He)==null?void 0:Se.map(ve=>typeof ve=="string"?ve:mi===void 0||(ve[0]??0)<=mi&&mi<(ve[1]??1/0)?ve[2]:void 0).filter(ve=>ve!==void 0);ze&&(ze=[...new Set(ze)],Ne.set("types",ze.join(",")));const vn=!J||We===Le?ot:We;if(vn&&Ne.set("excludeTypes",String(vn)),_&&Ne.set("bbox",_.map(ve=>ve.toFixed(6)).join(",")),O&&Ne.set("country",Array.isArray(O)?O.join(","):O),!le&&!J){const ve=await hr(h,y,_e);ve&&Ne.set("proximity",ve),(ae||!H)&&Ne.set("autocomplete","false"),Ne.set("fuzzyMatch",String(W))}const Ct=m===f?l:m;Ct!==void 0&&Ct>1&&(ze==null?void 0:ze.length)!==1&&console.warn("For reverse geocoding when limit > 1 then types must contain single value."),J?(Ct===1||Ct!==void 0&&(st||(ze==null?void 0:ze.length)===1))&&Ne.set("limit",String(Ct)):l!==void 0&&Ne.set("limit",String(l)),E&&Ne.set("key",E),ui(Ne),ai(Mt);const Bs=Mt.searchParams.get("types")===""&&Mt.searchParams.get("excludeTypes")!=="true",Ht=Mt.toString();if(Ht===gn){le?(k&&t(13,F=void 0),t(14,U=Zt[0])):(t(13,F=Zt),((De=F[X])==null?void 0:De.id)!==(r==null?void 0:r.id)&&t(15,X=-1));return}gn=Ht;let Nt;if(Bs)Nt={type:"FeatureCollection",features:[]};else{const ve=await fetch(Ht,{signal:_e.signal,...ie});if(!ve.ok)throw new Error(await ve.text());Nt=await ve.json()}tt("response",{url:Ht,featureCollection:Nt}),le?(k&&t(13,F=void 0),t(14,U=Nt.features[0]),Zt=[U]):(t(13,F=Nt.features.filter(B)),J&&F.unshift({type:"Feature",properties:{},id:"reverse_"+J.decimalLongitude+"_"+J.decimalLatitude,text:J.decimalLatitude+", "+J.decimalLongitude,place_name:J.decimalLatitude+", "+J.decimalLongitude,place_type:["reverse"],center:[J.decimalLongitude,J.decimalLatitude],bbox:[J.decimalLongitude,J.decimalLatitude,J.decimalLongitude,J.decimalLatitude],geometry:{type:"Point",coordinates:[J.decimalLongitude,J.decimalLatitude]}}),Zt=F,((it=F[X])==null?void 0:it.id)!==(r==null?void 0:r.id)&&t(15,X=-1),J&&Pe.focus())}catch(J){if(J&&typeof J=="object"&&"name"in J&&J.name==="AbortError")return;throw J}finally{_e===lt&&t(20,lt=void 0)}}function bs(){var _e;if(!(ce!=null&&ce.length)||!z)return;const L=[180,90,-180,-90],le=!ce.some(Se=>!Se.matching_text);let ae;for(const Se of ce){const De=Tt(Se);if(ae=ae===void 0?De:De===void 0?ae:Math.max(ae,De),le||!Se.matching_text)for(const it of[0,1,2,3])L[it]=Math[it<2?"min":"max"](L[it],((_e=Se.bbox)==null?void 0:_e[it])??Se.center[it%2])}h&&ce.length>0&&(U&&L[0]===L[2]&&L[1]===L[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(L),50,ae))}function di(){!U||!h||(!U.bbox||U.bbox[0]===U.bbox[2]&&U.bbox[1]===U.bbox[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(U.bbox),50,Tt(U)))}function Tt(L){var ae;if(!L.bbox||L.bbox[0]!==L.bbox[2]&&L.bbox[1]!==L.bbox[3])return;const le=L.id.replace(/\..*/,"");return(Array.isArray((ae=L.properties)==null?void 0:ae.categories)?L.properties.categories.reduce((_e,Se)=>{const De=pe[le+"."+Se];return _e===void 0?De:De===void 0?_e:Math.max(_e,De)},void 0):void 0)??pe[le]}function ws(L){t(0,b=N==="always"),t(13,F=void 0),t(14,U=void 0),t(15,X=-1),dn(L[1].toFixed(6)+", "+cr(L[0],[-180,180],!0).toFixed(6),!1,!0)}function Es(L){if(!F)return;let le=L.key==="ArrowDown"?1:L.key==="ArrowUp"?-1:0;le&&(Pe.focus(),t(17,Ve=!0),L.preventDefault(),U&&X===-1&&t(15,X=F.findIndex(ae=>ae.id===(U==null?void 0:U.id))),X===(U||Q?0:-1)&&le===-1&&t(15,X=F.length),t(15,X+=le),X>=F.length&&t(15,X=-1),X<0&&(U||Q)&&t(15,X=0))}function pn(L,le=!0,ae=!1){if(t(19,Ge=void 0),t(14,U=void 0),t(17,Ve=!0),H||ae){if(ct&&clearTimeout(ct),T.length{hi(_e).catch(Se=>t(19,Ge=Se))},le?x:0)}else t(13,F=void 0),t(19,Ge=void 0)}function gi(L){U&&(U==null?void 0:U.id)===(L==null?void 0:L.id)?di():(t(14,U=L),t(1,T=L.place_name))}function yn(L){t(15,X=L)}function Ls(){(!Q||U)&&t(15,X=-1),se&&di()}const _s=()=>Pe.focus();function Ss(L){Yt[L?"unshift":"push"](()=>{Pe=L,t(18,Pe)})}function xs(){T=this.value,t(1,T),t(17,Ve),t(31,R),t(16,ht)}const Ts=()=>t(17,Ve=!0),Ms=()=>t(17,Ve=!1),Cs=()=>t(17,Ve=!0),Ns=()=>t(14,U=void 0),ks=()=>{t(1,T=""),t(14,U=void 0),Pe.focus()},Os=()=>t(0,b=!b),Rs=()=>t(19,Ge=void 0),Ps=L=>yn(L),Is=L=>gi(L),As=()=>{};return i.$$set=L=>{"class"in L&&t(2,c=L.class),"apiKey"in L&&t(29,E=L.apiKey),"bbox"in L&&t(30,_=L.bbox),"clearButtonTitle"in L&&t(3,M=L.clearButtonTitle),"clearOnBlur"in L&&t(31,R=L.clearOnBlur),"clearListOnPick"in L&&t(32,k=L.clearListOnPick),"keepListOpen"in L&&t(4,I=L.keepListOpen),"collapsed"in L&&t(5,C=L.collapsed),"country"in L&&t(33,O=L.country),"debounceSearch"in L&&t(34,x=L.debounceSearch),"enableReverse"in L&&t(6,N=L.enableReverse),"errorMessage"in L&&t(7,P=L.errorMessage),"filter"in L&&t(35,B=L.filter),"flyTo"in L&&t(36,z=L.flyTo),"fuzzyMatch"in L&&t(37,W=L.fuzzyMatch),"language"in L&&t(38,s=L.language),"limit"in L&&t(39,l=L.limit),"reverseGeocodingLimit"in L&&t(40,m=L.reverseGeocodingLimit),"mapController"in L&&t(41,h=L.mapController),"minLength"in L&&t(42,d=L.minLength),"noResultsMessage"in L&&t(8,v=L.noResultsMessage),"placeholder"in L&&t(9,p=L.placeholder),"proximity"in L&&t(43,y=L.proximity),"reverseActive"in L&&t(0,b=L.reverseActive),"reverseButtonTitle"in L&&t(10,w=L.reverseButtonTitle),"searchValue"in L&&t(1,T=L.searchValue),"pickedResultStyle"in L&&t(44,G=L.pickedResultStyle),"showPlaceType"in L&&t(11,D=L.showPlaceType),"showResultsWhileTyping"in L&&t(45,H=L.showResultsWhileTyping),"selectFirst"in L&&t(46,Q=L.selectFirst),"flyToSelected"in L&&t(47,se=L.flyToSelected),"markerOnSelected"in L&&t(48,Z=L.markerOnSelected),"types"in L&&t(49,K=L.types),"reverseGeocodingTypes"in L&&t(50,He=L.reverseGeocodingTypes),"exhaustiveReverseGeocoding"in L&&t(51,st=L.exhaustiveReverseGeocoding),"excludeTypes"in L&&t(52,ot=L.excludeTypes),"reverseGeocodingExcludeTypes"in L&&t(53,We=L.reverseGeocodingExcludeTypes),"zoom"in L&&t(54,pe=L.zoom),"apiUrl"in L&&t(55,ge=L.apiUrl),"fetchParameters"in L&&t(56,ie=L.fetchParameters),"iconsBaseUrl"in L&&t(12,hn=L.iconsBaseUrl),"adjustUrlQuery"in L&&t(57,ui=L.adjustUrlQuery),"adjustUrl"in L&&t(58,ai=L.adjustUrl),"$$scope"in L&&t(69,o=L.$$scope)},i.$$.update=()=>{if(i.$$.dirty[0]&64&&t(0,b=N==="always"),i.$$.dirty[0]&16384|i.$$.dirty[1]&8192&&G!=="marker-only"&&U&&!U.address&&U.geometry.type==="Point"&&U.place_type[0]!=="reverse"&&hi(U.id,{byId:!0}).catch(L=>t(19,Ge=L)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1058|i.$$.dirty[2]&8&&(h&&U&&U.id!==fi&&z&&(di(),k&&t(13,F=void 0),t(64,ce=void 0),t(15,X=-1)),t(65,fi=U==null?void 0:U.id)),i.$$.dirty[0]&196608|i.$$.dirty[1]&1&&setTimeout(()=>{t(16,ht=Ve),R&&!ht&&t(1,T="")}),i.$$.dirty[0]&8194|i.$$.dirty[1]&2048&&T.length{switch(L.type){case"mapClick":b&&ws(L.coordinates);break;case"markerClick":{const le=F==null?void 0:F.find(ae=>ae.id===L.id);le&&gi(le)}break;case"markerMouseEnter":ce&&t(15,X=ht?(F==null?void 0:F.findIndex(le=>le.id===L.id))??-1:-1);break;case"markerMouseLeave":ce&&t(15,X=-1);break}}),i.$$.dirty[0]&40960&&t(66,r=F==null?void 0:F[X]),i.$$.dirty[1]&66592|i.$$.dirty[2]&16&&h&&r&&z&&se&&h.flyTo(r.center,Tt(r)),i.$$.dirty[1]&8192&&t(68,n=G==="full-geometry-including-polygon-center-marker"),i.$$.dirty[1]&132096|i.$$.dirty[2]&64&&(Z||h==null||h.setFeatures(void 0,void 0,n)),i.$$.dirty[0]&16384|i.$$.dirty[1]&132096|i.$$.dirty[2]&84&&h&&Z&&!ce&&(h.setFeatures(r?[r]:void 0,U,n),h.setSelectedMarker(r?0:-1)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1024|i.$$.dirty[2]&68&&h&&h.setFeatures(ce,U,n),i.$$.dirty[0]&32768|i.$$.dirty[1]&1024|i.$$.dirty[2]&4&&ce&&h&&h.setSelectedMarker(X),i.$$.dirty[0]&2|i.$$.dirty[1]&1024&&h){const L=ci(T);h.setReverseMarker(L?[L.decimalLongitude,L.decimalLatitude]:void 0)}i.$$.dirty[2]&16&&tt("select",{feature:r}),i.$$.dirty[0]&16384&&tt("pick",{feature:U}),i.$$.dirty[0]&73744&&t(67,u=!!(F!=null&&F.length)&&(ht||I)),i.$$.dirty[2]&32&&tt("optionsvisibilitychange",{optionsVisible:u}),i.$$.dirty[0]&8192&&tt("featureslisted",{features:F}),i.$$.dirty[2]&4&&tt("featuresmarked",{features:ce}),i.$$.dirty[0]&1&&tt("reversetoggle",{reverse:b}),i.$$.dirty[0]&2&&tt("querychange",{query:T}),i.$$.dirty[0]&1|i.$$.dirty[1]&1024&&h&&h.indicateReverse(b)},[b,T,c,M,I,C,N,P,v,p,w,D,hn,F,U,X,ht,Ve,Pe,Ge,lt,vs,mn,Es,pn,gi,yn,Ls,g,E,_,R,k,O,x,B,z,W,s,l,m,h,d,y,G,H,Q,se,Z,K,He,st,ot,We,pe,ge,ie,ui,ai,gs,ms,dn,ps,ys,ce,fi,r,u,n,o,a,_s,Ss,xs,Ts,Ms,Cs,Ns,ks,Os,Rs,Ps,Is,As]}let kr=class extends Je{constructor(e){super(),Xe(this,e,Nr,Cr,Ke,{ZOOM_DEFAULTS:28,class:2,apiKey:29,bbox:30,clearButtonTitle:3,clearOnBlur:31,clearListOnPick:32,keepListOpen:4,collapsed:5,country:33,debounceSearch:34,enableReverse:6,errorMessage:7,filter:35,flyTo:36,fuzzyMatch:37,language:38,limit:39,reverseGeocodingLimit:40,mapController:41,minLength:42,noResultsMessage:8,placeholder:9,proximity:43,reverseActive:0,reverseButtonTitle:10,searchValue:1,pickedResultStyle:44,showPlaceType:11,showResultsWhileTyping:45,selectFirst:46,flyToSelected:47,markerOnSelected:48,types:49,reverseGeocodingTypes:50,exhaustiveReverseGeocoding:51,excludeTypes:52,reverseGeocodingExcludeTypes:53,zoom:54,apiUrl:55,fetchParameters:56,iconsBaseUrl:12,adjustUrlQuery:57,adjustUrl:58,focus:59,blur:60,setQuery:61,clearList:62,clearMap:63},null,[-1,-1,-1,-1])}get ZOOM_DEFAULTS(){return this.$$.ctx[28]}get focus(){return this.$$.ctx[59]}get blur(){return this.$$.ctx[60]}get setQuery(){return this.$$.ctx[61]}get clearList(){return this.$$.ctx[62]}get clearMap(){return this.$$.ctx[63]}};function Et(i,e,t={}){const n={type:"Feature"};return(t.id===0||t.id)&&(n.id=t.id),t.bbox&&(n.bbox=t.bbox),n.properties=e||{},n.geometry=i,n}function ti(i,e,t={}){for(const r of i){if(r.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(r[r.length-1].length!==r[0].length)throw new Error("First and last Position are not equivalent.");for(let u=0;u_?w.c=w.e=null:s.e=10;v/=10,d++);d>_?w.c=w.e=null:(w.e=d,w.c=[s]);return}b=String(s)}else{if(!Or.test(b=String(s)))return n(w,b,p);w.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(v=b.search(/e/i))>0?(d<0&&(d=v),d+=+b.slice(v+1),b=b.substring(0,v)):d<0&&(d=b.length)}else{if(oe(l,2,C.length,"Base"),l==10&&O)return w=new x(s),z(w,a+w.e+1,o);if(b=String(s),p=typeof s=="number"){if(s*0!=0)return n(w,b,p,l);if(w.s=1/s<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(ji+s)}else w.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(f=C.slice(0,l),d=v=0,y=b.length;vd){d=y;continue}}else if(!h&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){h=!0,v=-1,d=0;continue}return n(w,String(s),p,l)}p=!1,b=t(b,l,10,w.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(v=0;b.charCodeAt(v)===48;v++);for(y=b.length;b.charCodeAt(--y)===48;);if(b=b.slice(v,++y)){if(y-=v,p&&x.DEBUG&&y>15&&(s>Zi||s!==Te(s)))throw Error(ji+w.s*s);if((d=d-v-1)>_)w.c=w.e=null;else if(d=-1e9&&h<=Ee&&h===Te(h)){if(m[0]===0){if(h===0&&m.length===1)return!0;break e}if(l=(h+1)%q,l<1&&(l+=q),String(m[0]).length==l){for(l=0;l=Re||f!==Te(f))break e;if(f!==0)return!0}}}else if(m===null&&h===null&&(d===null||d===1||d===-1))return!0;throw Error(be+"Invalid BigNumber: "+s)},x.maximum=x.max=function(){return P(arguments,-1)},x.minimum=x.min=function(){return P(arguments,1)},x.random=function(){var s=9007199254740992,l=Math.random()*s&2097151?function(){return Te(Math.random()*s)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(f){var m,h,d,v,p,y=0,b=[],w=new x(u);if(f==null?f=a:oe(f,0,Ee),v=ii(f/q),M)if(crypto.getRandomValues){for(m=crypto.getRandomValues(new Uint32Array(v*=2));y>>11),p>=9e15?(h=crypto.getRandomValues(new Uint32Array(2)),m[y]=h[0],m[y+1]=h[1]):(b.push(p%1e14),y+=2);y=v/2}else if(crypto.randomBytes){for(m=crypto.randomBytes(v*=7);y=9e15?crypto.randomBytes(7).copy(m,y):(b.push(p%1e14),y+=7);y=v/7}else throw M=!1,Error(be+"crypto unavailable");if(!M)for(;y=10;p/=10,y++);yh-1&&(p[v+1]==null&&(p[v+1]=0),p[v+1]+=p[v]/h|0,p[v]%=h)}return p.reverse()}return function(f,m,h,d,v){var p,y,b,w,T,G,D,H,Q=f.indexOf("."),se=a,Z=o;for(Q>=0&&(w=k,k=0,f=f.replace(".",""),H=new x(m),G=H.pow(f.length-Q),k=w,H.c=l(je(Ce(G.c),G.e,"0"),10,h,s),H.e=H.c.length),D=l(f,m,h,v?(p=C,s):(p=s,C)),b=w=D.length;D[--w]==0;D.pop());if(!D[0])return p.charAt(0);if(Q<0?--b:(G.c=D,G.e=b,G.s=d,G=e(G,H,se,Z,h),D=G.c,T=G.r,b=G.e),y=b+se+1,Q=D[y],w=h/2,T=T||y<0||D[y+1]!=null,T=Z<4?(Q!=null||T)&&(Z==0||Z==(G.s<0?3:2)):Q>w||Q==w&&(Z==4||T||Z==6&&D[y-1]&1||Z==(G.s<0?8:7)),y<1||!D[0])f=T?je(p.charAt(1),-se,p.charAt(0)):p.charAt(0);else{if(D.length=y,T)for(--h;++D[--y]>h;)D[y]=0,y||(++b,D=[1].concat(D));for(w=D.length;!D[--w];);for(Q=0,f="";Q<=w;f+=p.charAt(D[Q++]));f=je(f,b,p.charAt(0))}return f}}(),e=function(){function s(m,h,d){var v,p,y,b,w=0,T=m.length,G=h%$e,D=h/$e|0;for(m=m.slice();T--;)y=m[T]%$e,b=m[T]/$e|0,v=D*y+b*G,p=G*y+v%$e*$e+w,w=(p/d|0)+(v/$e|0)+D*b,m[T]=p%d;return w&&(m=[w].concat(m)),m}function l(m,h,d,v){var p,y;if(d!=v)y=d>v?1:-1;else for(p=y=0;ph[p]?1:-1;break}return y}function f(m,h,d,v){for(var p=0;d--;)m[d]-=p,p=m[d]1;m.splice(0,1));}return function(m,h,d,v,p){var y,b,w,T,G,D,H,Q,se,Z,K,de,He,st,ot,Le,We,pe=m.s==h.s?1:-1,ge=m.c,ie=h.c;if(!ge||!ge[0]||!ie||!ie[0])return new x(!m.s||!h.s||(ge?ie&&ge[0]==ie[0]:!ie)?NaN:ge&&ge[0]==0||!ie?pe*0:pe/0);for(Q=new x(pe),se=Q.c=[],b=m.e-h.e,pe=d+b+1,p||(p=Re,b=Me(m.e/q)-Me(h.e/q),pe=pe/q|0),w=0;ie[w]==(ge[w]||0);w++);if(ie[w]>(ge[w]||0)&&b--,pe<0)se.push(1),T=!0;else{for(st=ge.length,Le=ie.length,w=0,pe+=2,G=Te(p/(ie[0]+1)),G>1&&(ie=s(ie,G,p),ge=s(ge,G,p),Le=ie.length,st=ge.length),He=Le,Z=ge.slice(0,Le),K=Z.length;K=p/2&&ot++;do{if(G=0,y=l(ie,Z,Le,K),y<0){if(de=Z[0],Le!=K&&(de=de*p+(Z[1]||0)),G=Te(de/ot),G>1)for(G>=p&&(G=p-1),D=s(ie,G,p),H=D.length,K=Z.length;l(D,Z,H,K)==1;)G--,f(D,Le=10;pe/=10,w++);z(Q,d+(Q.e=w+b*q-1)+1,v,T)}else Q.e=b,Q.r=+T;return Q}}();function N(s,l,f,m){var h,d,v,p,y;if(f==null?f=o:oe(f,0,8),!s.c)return s.toString();if(h=s.c[0],v=s.e,l==null)y=Ce(s.c),y=m==1||m==2&&(v<=g||v>=c)?Gt(y,v):je(y,v,"0");else if(s=z(new x(s),l,f),d=s.e,y=Ce(s.c),p=y.length,m==1||m==2&&(l<=d||d<=g)){for(;pp){if(--l>0)for(y+=".";l--;y+="0");}else if(l+=d-p,l>0)for(d+1==p&&(y+=".");l--;y+="0");return s.s<0&&h?"-"+y:y}function P(s,l){for(var f,m,h=1,d=new x(s[0]);h=10;h/=10,m++);return(f=m+f*q-1)>_?s.c=s.e=null:f=10;p/=10,h++);if(d=l-h,d<0)d+=q,v=l,y=T[b=0],w=Te(y/G[h-v-1]%10);else if(b=ii((d+1)/q),b>=T.length)if(m){for(;T.length<=b;T.push(0));y=w=0,h=1,d%=q,v=d-q+1}else break e;else{for(y=p=T[b],h=1;p>=10;p/=10,h++);d%=q,v=d-q+h,w=v<0?0:Te(y/G[h-v-1]%10)}if(m=m||l<0||T[b+1]!=null||(v<0?y:y%G[h-v-1]),m=f<4?(w||m)&&(f==0||f==(s.s<0?3:2)):w>5||w==5&&(f==4||m||f==6&&(d>0?v>0?y/G[h-v]:0:T[b-1])%10&1||f==(s.s<0?8:7)),l<1||!T[0])return T.length=0,m?(l-=s.e+1,T[0]=G[(q-l%q)%q],s.e=-l||0):T[0]=s.e=0,s;if(d==0?(T.length=b,p=1,b--):(T.length=b+1,p=G[q-d],T[b]=v>0?Te(y/G[h-v]%G[v])*p:0),m)for(;;)if(b==0){for(d=1,v=T[0];v>=10;v/=10,d++);for(v=T[0]+=p,p=1;v>=10;v/=10,p++);d!=p&&(s.e++,T[0]==Re&&(T[0]=1));break}else{if(T[b]+=p,T[b]!=Re)break;T[b--]=0,p=1}for(d=T.length;T[--d]===0;T.pop());}s.e>_?s.c=s.e=null:s.e=c?Gt(l,f):je(l,f,"0"),s.s<0?"-"+l:l)}return r.absoluteValue=r.abs=function(){var s=new x(this);return s.s<0&&(s.s=1),s},r.comparedTo=function(s,l){return rt(this,new x(s,l))},r.decimalPlaces=r.dp=function(s,l){var f,m,h,d=this;if(s!=null)return oe(s,0,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s+d.e+1,l);if(!(f=d.c))return null;if(m=((h=f.length-1)-Me(this.e/q))*q,h=f[h])for(;h%10==0;h/=10,m--);return m<0&&(m=0),m},r.dividedBy=r.div=function(s,l){return e(this,new x(s,l),a,o)},r.dividedToIntegerBy=r.idiv=function(s,l){return e(this,new x(s,l),0,1)},r.exponentiatedBy=r.pow=function(s,l){var f,m,h,d,v,p,y,b,w,T=this;if(s=new x(s),s.c&&!s.isInteger())throw Error(be+"Exponent not an integer: "+W(s));if(l!=null&&(l=new x(l)),p=s.e>14,!T.c||!T.c[0]||T.c[0]==1&&!T.e&&T.c.length==1||!s.c||!s.c[0])return w=new x(Math.pow(+W(T),p?s.s*(2-Wt(s)):+W(s))),l?w.mod(l):w;if(y=s.s<0,l){if(l.c?!l.c[0]:!l.s)return new x(NaN);m=!y&&T.isInteger()&&l.isInteger(),m&&(T=T.mod(l))}else{if(s.e>9&&(T.e>0||T.e<-1||(T.e==0?T.c[0]>1||p&&T.c[1]>=24e7:T.c[0]<8e13||p&&T.c[0]<=9999975e7)))return d=T.s<0&&Wt(s)?-0:0,T.e>-1&&(d=1/d),new x(y?1/d:d);k&&(d=ii(k/q+2))}for(p?(f=new x(.5),y&&(s.s=1),b=Wt(s)):(h=Math.abs(+W(s)),b=h%2),w=new x(u);;){if(b){if(w=w.times(T),!w.c)break;d?w.c.length>d&&(w.c.length=d):m&&(w=w.mod(l))}if(h){if(h=Te(h/2),h===0)break;b=h%2}else if(s=s.times(f),z(s,s.e+1,1),s.e>14)b=Wt(s);else{if(h=+W(s),h===0)break;b=h%2}T=T.times(T),d?T.c&&T.c.length>d&&(T.c.length=d):m&&(T=T.mod(l))}return m?w:(y&&(w=u.div(w)),l?w.mod(l):d?z(w,k,o,v):w)},r.integerValue=function(s){var l=new x(this);return s==null?s=o:oe(s,0,8),z(l,l.e+1,s)},r.isEqualTo=r.eq=function(s,l){return rt(this,new x(s,l))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(s,l){return rt(this,new x(s,l))>0},r.isGreaterThanOrEqualTo=r.gte=function(s,l){return(l=rt(this,new x(s,l)))===1||l===0},r.isInteger=function(){return!!this.c&&Me(this.e/q)>this.c.length-2},r.isLessThan=r.lt=function(s,l){return rt(this,new x(s,l))<0},r.isLessThanOrEqualTo=r.lte=function(s,l){return(l=rt(this,new x(s,l)))===-1||l===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(s,l){var f,m,h,d,v=this,p=v.s;if(s=new x(s,l),l=s.s,!p||!l)return new x(NaN);if(p!=l)return s.s=-l,v.plus(s);var y=v.e/q,b=s.e/q,w=v.c,T=s.c;if(!y||!b){if(!w||!T)return w?(s.s=-l,s):new x(T?v:NaN);if(!w[0]||!T[0])return T[0]?(s.s=-l,s):new x(w[0]?v:o==3?-0:0)}if(y=Me(y),b=Me(b),w=w.slice(),p=y-b){for((d=p<0)?(p=-p,h=w):(b=y,h=T),h.reverse(),l=p;l--;h.push(0));h.reverse()}else for(m=(d=(p=w.length)<(l=T.length))?p:l,p=l=0;l0)for(;l--;w[f++]=0);for(l=Re-1;m>p;){if(w[--m]=0;){for(f=0,G=de[h]%se,D=de[h]/se|0,v=y,d=h+v;d>h;)b=K[--v]%se,w=K[v]/se|0,p=D*b+w*G,b=G*b+p%se*se+H[d]+f,f=(b/Q|0)+(p/se|0)+D*w,H[d--]=b%Q;H[d]=f}return f?++m:H.splice(0,1),B(s,H,m)},r.negated=function(){var s=new x(this);return s.s=-s.s||null,s},r.plus=function(s,l){var f,m=this,h=m.s;if(s=new x(s,l),l=s.s,!h||!l)return new x(NaN);if(h!=l)return s.s=-l,m.minus(s);var d=m.e/q,v=s.e/q,p=m.c,y=s.c;if(!d||!v){if(!p||!y)return new x(h/0);if(!p[0]||!y[0])return y[0]?s:new x(p[0]?m:h*0)}if(d=Me(d),v=Me(v),p=p.slice(),h=d-v){for(h>0?(v=d,f=y):(h=-h,f=p),f.reverse();h--;f.push(0));f.reverse()}for(h=p.length,l=y.length,h-l<0&&(f=y,y=p,p=f,l=h),h=0;l;)h=(p[--l]=p[l]+y[l]+h)/Re|0,p[l]=Re===p[l]?0:p[l]%Re;return h&&(p=[h].concat(p),++v),B(s,p,v)},r.precision=r.sd=function(s,l){var f,m,h,d=this;if(s!=null&&s!==!!s)return oe(s,1,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s,l);if(!(f=d.c))return null;if(h=f.length-1,m=h*q+1,h=f[h]){for(;h%10==0;h/=10,m--);for(h=f[0];h>=10;h/=10,m++);}return s&&d.e+1>m&&(m=d.e+1),m},r.shiftedBy=function(s){return oe(s,-9007199254740991,Zi),this.times("1e"+s)},r.squareRoot=r.sqrt=function(){var s,l,f,m,h,d=this,v=d.c,p=d.s,y=d.e,b=a+4,w=new x("0.5");if(p!==1||!v||!v[0])return new x(!p||p<0&&(!v||v[0])?NaN:v?d:1/0);if(p=Math.sqrt(+W(d)),p==0||p==1/0?(l=Ce(v),(l.length+y)%2==0&&(l+="0"),p=Math.sqrt(+l),y=Me((y+1)/2)-(y<0||y%2),p==1/0?l="5e"+y:(l=p.toExponential(),l=l.slice(0,l.indexOf("e")+1)+y),f=new x(l)):f=new x(p+""),f.c[0]){for(y=f.e,p=y+b,p<3&&(p=0);;)if(h=f,f=w.times(h.plus(e(d,h,b,1))),Ce(h.c).slice(0,p)===(l=Ce(f.c)).slice(0,p))if(f.e0&&H>0){for(d=H%p||p,w=D.substr(0,d);d0&&(w+=b+D.slice(d)),G&&(w="-"+w)}m=T?w+(f.decimalSeparator||"")+((y=+f.fractionGroupSize)?T.replace(new RegExp("\\d{"+y+"}\\B","g"),"$&"+(f.fractionGroupSeparator||"")):T):w}return(f.prefix||"")+m+(f.suffix||"")},r.toFraction=function(s){var l,f,m,h,d,v,p,y,b,w,T,G,D=this,H=D.c;if(s!=null&&(p=new x(s),!p.isInteger()&&(p.c||p.s!==1)||p.lt(u)))throw Error(be+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+W(p));if(!H)return new x(D);for(l=new x(u),b=f=new x(u),m=y=new x(u),G=Ce(H),d=l.e=G.length-D.e-1,l.c[0]=ni[(v=d%q)<0?q+v:v],s=!s||p.comparedTo(l)>0?d>0?l:b:p,v=_,_=1/0,p=new x(G),y.c[0]=0;w=e(p,l,0,1),h=f.plus(w.times(m)),h.comparedTo(s)!=1;)f=m,m=h,b=y.plus(w.times(h=b)),y=h,l=p.minus(w.times(h=l)),p=h;return h=e(s.minus(f),m,0,1),y=y.plus(h.times(b)),f=f.plus(h.times(m)),y.s=b.s=D.s,d=d*2,T=e(b,m,d,o).minus(D).abs().comparedTo(e(y,f,d,o).minus(D).abs())<1?[b,m]:[y,f],_=v,T},r.toNumber=function(){return+W(this)},r.toPrecision=function(s,l){return s!=null&&oe(s,1,Ee),N(this,s,l,2)},r.toString=function(s){var l,f=this,m=f.s,h=f.e;return h===null?m?(l="Infinity",m<0&&(l="-"+l)):l="NaN":(s==null?l=h<=g||h>=c?Gt(Ce(f.c),h):je(Ce(f.c),h,"0"):s===10&&O?(f=z(new x(f),a+h+1,o),l=je(Ce(f.c),f.e,"0")):(oe(s,2,C.length,"Base"),l=t(je(Ce(f.c),h,"0"),10,s,m,!0)),m<0&&f.c[0]&&(l="-"+l)),l},r.valueOf=r.toJSON=function(){return W(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,i!=null&&x.set(i),x}function Me(i){var e=i|0;return i>0||i===e?e:e-1}function Ce(i){for(var e,t,n=1,r=i.length,u=i[0]+"";nc^t?1:-1;for(o=(g=r.length)<(c=u.length)?g:c,a=0;au[a]^t?1:-1;return g==c?0:g>c^t?1:-1}function oe(i,e,t,n){if(it||i!==Te(i))throw Error(be+(n||"Argument")+(typeof i=="number"?it?" out of range: ":" not an integer: ":" not a primitive number: ")+String(i))}function Wt(i){var e=i.c.length-1;return Me(i.e/q)==e&&i.c[e]%2!=0}function Gt(i,e){return(i.length>1?i.charAt(0)+"."+i.slice(1):i)+(e<0?"e":"e+")+e}function je(i,e,t){var n,r;if(e<0){for(r=t+".";++e;r+=t);i=r+i}else if(n=i.length,++e>n){for(r=t,e-=n;--e;r+=t);i+=r}else e0){let c=a.left;if(c==null||(g=o(c.key,i),g>0&&(a.left=c.right,c.right=a,a=c,c=a.left,c==null)))break;t==null?n=a:t.left=a,t=a,a=c}else if(g<0){let c=a.right;if(c==null||(g=o(c.key,i),g<0&&(a.right=c.left,c.left=a,a=c,c=a.right,c==null)))break;r==null?u=a:r.right=a,r=a,a=c}else break;return r!=null&&(r.right=a.left,a.left=u),t!=null&&(t.left=a.right,a.right=n),this.root!==a&&(this.root=a,this.splayCount++),g}splayMin(i){let e=i,t=e.left;for(;t!=null;){const n=t;e.left=n.right,n.right=e,e=n,t=e.left}return e}splayMax(i){let e=i,t=e.right;for(;t!=null;){const n=t;e.right=n.left,n.left=e,e=n,t=e.right}return e}_delete(i){if(this.root==null||this.splay(i)!=0)return null;let t=this.root;const n=t,r=t.left;if(this.size--,r==null)this.root=t.right;else{const u=t.right;t=this.splayMax(r),t.right=u,this.root=t}return this.modificationCount++,n}addNewRoot(i,e){this.size++,this.modificationCount++;const t=this.root;if(t==null){this.root=i;return}e<0?(i.left=t,i.right=t.right,t.right=null):(i.right=t,i.left=t.left,t.left=null),this.root=i}_first(){const i=this.root;return i==null?null:(this.root=this.splayMin(i),this.root)}_last(){const i=this.root;return i==null?null:(this.root=this.splayMax(i),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(i){return this.validKey(i)&&this.splay(i)==0}defaultCompare(){return(i,e)=>ie?1:0}wrap(){return{getRoot:()=>this.root,setRoot:i=>{this.root=i},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:i=>{this.splayCount=i},splay:i=>this.splay(i),has:i=>this.has(i)}}},Dt=class Ot extends Pr{constructor(t,n){super();A(this,"root",null);A(this,"compare");A(this,"validKey");A(this,fn,"[object Set]");this.compare=t??this.defaultCompare(),this.validKey=n??(r=>r!=null&&r!=null)}delete(t){return this.validKey(t)?this._delete(t)!=null:!1}deleteAll(t){for(const n of t)this.delete(n)}forEach(t){const n=this[Symbol.iterator]();let r;for(;r=n.next(),!r.done;)t(r.value,r.value,this)}add(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this}addAndReturn(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this.root.key}addAll(t){for(const n of t)this.add(n)}isEmpty(){return this.root==null}isNotEmpty(){return this.root!=null}single(){if(this.size==0)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(this.size==0)throw"Bad state: No element";return this._first().key}last(){if(this.size==0)throw"Bad state: No element";return this._last().key}lastBefore(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)<0)return this.root.key;let r=this.root.left;if(r==null)return null;let u=r.right;for(;u!=null;)r=u,u=r.right;return r.key}firstAfter(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)>0)return this.root.key;let r=this.root.right;if(r==null)return null;let u=r.left;for(;u!=null;)r=u,u=r.left;return r.key}retainAll(t){const n=new Ot(this.compare,this.validKey),r=this.modificationCount;for(const u of t){if(r!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(u)&&this.splay(u)==0&&n.add(this.root.key)}n.size!=this.size&&(this.root=n.root,this.size=n.size,this.modificationCount++)}lookup(t){return!this.validKey(t)||this.splay(t)!=0?null:this.root.key}intersection(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)&&n.add(r);return n}difference(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)||n.add(r);return n}union(t){const n=this.clone();return n.addAll(t),n}clone(){const t=new Ot(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(t){if(t==null)return null;function n(u,a){let o,g;do{if(o=u.left,g=u.right,o!=null){const c=new _t(o.key);a.left=c,n(o,c)}if(g!=null){const c=new _t(g.key);a.right=c,u=g,a=c}}while(g!=null)}const r=new _t(t.key);return n(t,r),r}toSet(){return this.clone()}entries(){return new Ar(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[(cn=Symbol.iterator,fn=Symbol.toStringTag,cn)](){return new Ir(this.wrap())}},Vi=class{constructor(i){A(this,"tree");A(this,"path",new Array);A(this,"modificationCount",null);A(this,"splayCount");this.tree=i,this.splayCount=i.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const i=this.path[this.path.length-1];return this.getValue(i)}rebuildPath(i){this.path.splice(0,this.path.length),this.tree.splay(i),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(i){for(;i!=null;)this.path.push(i),i=i.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(this.modificationCount==null){this.modificationCount=this.tree.getModificationCount();let t=this.tree.getRoot();for(;t!=null;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let i=this.path[this.path.length-1],e=i.right;if(e!=null){for(;e!=null;)this.path.push(e),e=e.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===i;)i=this.path.pop();return this.path.length>0}},Ir=class extends Vi{getValue(i){return i.key}},Ar=class extends Vi{getValue(i){return[i.key,i.key]}},Ki=i=>()=>i,ri=i=>{const e=i?(t,n)=>n.minus(t).abs().isLessThanOrEqualTo(i):Ki(!1);return(t,n)=>e(t,n)?0:t.comparedTo(n)};function Br(i){const e=i?(t,n,r,u,a)=>t.exponentiatedBy(2).isLessThanOrEqualTo(u.minus(n).exponentiatedBy(2).plus(a.minus(r).exponentiatedBy(2)).times(i)):Ki(!1);return(t,n,r)=>{const u=t.x,a=t.y,o=r.x,g=r.y,c=a.minus(g).times(n.x.minus(o)).minus(u.minus(o).times(n.y.minus(g)));return e(c,u,a,o,g)?0:c.comparedTo(0)}}var Wr=i=>i,Gr=i=>{if(i){const e=new Dt(ri(i)),t=new Dt(ri(i)),n=(u,a)=>a.addAndReturn(u),r=u=>({x:n(u.x,e),y:n(u.y,t)});return r({x:new Ae(0),y:new Ae(0)}),r}return Wr},si=i=>({set:e=>{Ze=si(e)},reset:()=>si(i),compare:ri(i),snap:Gr(i),orient:Br(i)}),Ze=si(),St=(i,e)=>i.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(i.ur.x)&&i.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(i.ur.y),oi=(i,e)=>{if(e.ur.x.isLessThan(i.ll.x)||i.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(i.ll.y)||i.ur.y.isLessThan(e.ll.y))return null;const t=i.ll.x.isLessThan(e.ll.x)?e.ll.x:i.ll.x,n=i.ur.x.isLessThan(e.ur.x)?i.ur.x:e.ur.x,r=i.ll.y.isLessThan(e.ll.y)?e.ll.y:i.ll.y,u=i.ur.y.isLessThan(e.ur.y)?i.ur.y:e.ur.y;return{ll:{x:t,y:r},ur:{x:n,y:u}}},zt=(i,e)=>i.x.times(e.y).minus(i.y.times(e.x)),Yi=(i,e)=>i.x.times(e.x).plus(i.y.times(e.y)),Ut=i=>Yi(i,i).sqrt(),Dr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return zt(r,n).div(Ut(r)).div(Ut(n))},zr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return Yi(r,n).div(Ut(r)).div(Ut(n))},Qi=(i,e,t)=>e.y.isZero()?null:{x:i.x.plus(e.x.div(e.y).times(t.minus(i.y))),y:t},Xi=(i,e,t)=>e.x.isZero()?null:{x:t,y:i.y.plus(e.y.div(e.x).times(t.minus(i.x)))},Ur=(i,e,t,n)=>{if(e.x.isZero())return Xi(t,n,i.x);if(n.x.isZero())return Xi(i,e,t.x);if(e.y.isZero())return Qi(t,n,i.y);if(n.y.isZero())return Qi(i,e,t.y);const r=zt(e,n);if(r.isZero())return null;const u={x:t.x.minus(i.x),y:t.y.minus(i.y)},a=zt(u,e).div(r),o=zt(u,n).div(r),g=i.x.plus(o.times(e.x)),c=t.x.plus(a.times(n.x)),E=i.y.plus(o.times(e.y)),_=t.y.plus(a.times(n.y)),M=g.plus(c).div(2),R=E.plus(_).div(2);return{x:M,y:R}},Be=class En{constructor(e,t){A(this,"point");A(this,"isLeft");A(this,"segment");A(this,"otherSE");A(this,"consumedBy");e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}static compare(e,t){const n=En.comparePoints(e.point,t.point);return n!==0?n:(e.point!==t.point&&e.link(t),e.isLeft!==t.isLeft?e.isLeft?1:-1:Ft.compare(e.segment,t.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let n=0,r=t.length;n{const u=r.otherSE;t.set(r,{sine:Dr(this.point,e.point,u.point),cosine:zr(this.point,e.point,u.point)})};return(r,u)=>{t.has(r)||n(r),t.has(u)||n(u);const{sine:a,cosine:o}=t.get(r),{sine:g,cosine:c}=t.get(u);return a.isGreaterThanOrEqualTo(0)&&g.isGreaterThanOrEqualTo(0)?o.isLessThan(c)?1:o.isGreaterThan(c)?-1:0:a.isLessThan(0)&&g.isLessThan(0)?o.isLessThan(c)?-1:o.isGreaterThan(c)?1:0:g.isLessThan(a)?-1:g.isGreaterThan(a)?1:0}}},qr=class pi{constructor(e){A(this,"events");A(this,"poly");A(this,"_isExteriorRing");A(this,"_enclosingRing");this.events=e;for(let t=0,n=e.length;t0&&(e=g)}let t=e.segment.prevInResult(),n=t?t.prevInResult():null;for(;;){if(!t)return null;if(!n)return t.ringOut;if(n.ringOut!==t.ringOut)return((r=n.ringOut)==null?void 0:r.enclosingRing())!==t.ringOut?t.ringOut:(u=t.ringOut)==null?void 0:u.enclosingRing();t=n.prevInResult(),n=t?t.prevInResult():null}}},Ji=class{constructor(i){A(this,"exteriorRing");A(this,"interiorRings");this.exteriorRing=i,i.poly=this,this.interiorRings=[]}addInterior(i){this.interiorRings.push(i),i.poly=this}getGeom(){const i=this.exteriorRing.getGeom();if(i===null)return null;const e=[i];for(let t=0,n=this.interiorRings.length;t0?(this.tree.delete(e),t.push(i)):(this.segments.push(e),e.prev=n)}else{if(n&&r){const u=n.getIntersection(r);if(u!==null){if(!n.isAnEndpoint(u)){const a=this._splitSafely(n,u);for(let o=0,g=a.length;o0)return-1;const M=t.comparePoint(e.rightSE.point);return M!==0?M:-1}if(n.isGreaterThan(r)){if(o.isLessThan(g)&&o.isLessThan(E))return-1;if(o.isGreaterThan(g)&&o.isGreaterThan(E))return 1;const _=t.comparePoint(e.leftSE.point);if(_!==0)return _;const M=e.comparePoint(t.rightSE.point);return M<0?1:M>0?-1:1}if(o.isLessThan(g))return-1;if(o.isGreaterThan(g))return 1;if(u.isLessThan(a)){const _=t.comparePoint(e.rightSE.point);if(_!==0)return _}if(u.isGreaterThan(a)){const _=e.comparePoint(t.rightSE.point);if(_<0)return 1;if(_>0)return-1}if(!u.eq(a)){const _=c.minus(o),M=u.minus(n),R=E.minus(g),k=a.minus(r);if(_.isGreaterThan(M)&&R.isLessThan(k))return 1;if(_.isLessThan(M)&&R.isGreaterThan(k))return-1}return u.isGreaterThan(a)?1:u.isLessThan(a)||c.isLessThan(E)?-1:c.isGreaterThan(E)?1:e.idt.id?1:0}static fromRing(e,t,n){let r,u,a;const o=Be.comparePoints(e,t);if(o<0)r=e,u=t,a=1;else if(o>0)r=t,u=e,a=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const g=new Be(r,!0),c=new Be(u,!1);return new Kt(g,c,[n],[a])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return Ze.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),n=e.bbox(),r=oi(t,n);if(r===null)return null;const u=this.leftSE.point,a=this.rightSE.point,o=e.leftSE.point,g=e.rightSE.point,c=St(t,o)&&this.comparePoint(o)===0,E=St(n,u)&&e.comparePoint(u)===0,_=St(t,g)&&this.comparePoint(g)===0,M=St(n,a)&&e.comparePoint(a)===0;if(E&&c)return M&&!_?a:!M&&_?g:null;if(E)return _&&u.x.eq(g.x)&&u.y.eq(g.y)?null:u;if(c)return M&&a.x.eq(o.x)&&a.y.eq(o.y)?null:o;if(M&&_)return null;if(M)return a;if(_)return g;const R=Ur(u,this.vector(),o,e.vector());return R===null||!St(r,R)?null:Ze.snap(R)}split(e){const t=[],n=e.events!==void 0,r=new Be(e,!0),u=new Be(e,!1),a=this.rightSE;this.replaceRightSE(u),t.push(u),t.push(r);const o=new Kt(r,a,this.rings.slice(),this.windings.slice());return Be.comparePoints(o.leftSE.point,o.rightSE.point)>0&&o.swapEvents(),Be.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(r.checkForConsuming(),u.checkForConsuming()),t}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,n=this.windings.length;t0){const u=t;t=n,n=u}if(t.prev===n){const u=t;t=n,n=u}for(let u=0,a=n.rings.length;ur.length===1&&r[0].isSubject;this._isInResult=n(e)!==n(t);break}}return this._isInResult}},$i=class{constructor(i,e,t){A(this,"poly");A(this,"isExterior");A(this,"segments");A(this,"bbox");if(!Array.isArray(i)||i.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=e,this.isExterior=t,this.segments=[],typeof i[0][0]!="number"||typeof i[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const n=Ze.snap({x:new Ae(i[0][0]),y:new Ae(i[0][1])});this.bbox={ll:{x:n.x,y:n.y},ur:{x:n.x,y:n.y}};let r=n;for(let u=1,a=i.length;uqt.run("union",i,e),Yr=(i,...e)=>qt.run("difference",i,e);Ze.set;function tn(i,e,t){if(i!==null)for(var n,r,u,a,o,g,c,E=0,_=0,M,R=i.type,k=R==="FeatureCollection",I=R==="Feature",C=k?i.features.length:1,O=0;O{t.push(r.coordinates)}),t.length<2)throw new Error("Must have at least 2 geometries");const n=Kr(t[0],...t.slice(1));return n.length===0?null:n.length===1?ti(n[0],e.properties):Fi(n,e.properties)}var nn=Xr;function Jr(i,e={}){if(i.bbox!=null&&e.recompute!==!0)return i.bbox;const t=[1/0,1/0,-1/0,-1/0];return tn(i,n=>{t[0]>n[0]&&(t[0]=n[0]),t[1]>n[1]&&(t[1]=n[1]),t[2]{e.push(r.coordinates)}),e.length<2)throw new Error("Must have at least two features");const t=i.features[0].properties||{},n=Yr(e[0],...e.slice(1));return n.length===0?null:n.length===1?ti(n[0],t):Fi(n,t)}var es=$r;function ts(i){if(!i)throw new Error("geojson is required");var e=[];return Qr(i,function(t){e.push(t)}),Lt(e)}var is=ts;function sn(i,e){const t=es(Lt([ti([[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]]),i]));if(!t)return;t.properties={isMask:!0};const n=Bt(rn(i)),r=(n[2]-n[0])/360/1e3,u=n[0]<-180,a=n[2]>180,o=is(i);if(o.features.length>1&&(u||a))for(const g of o.features){const c=Bt(rn(g));if(a&&c[0]<-180+r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]+=360-r;if(u&&c[2]>180-r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]-=360-r}e(Lt([o.features.length<2?i:nn(o)??i,t]))}const on={fill:{paint:{"fill-color":"#000","fill-opacity":.1},filter:["all",["==",["geometry-type"],"Polygon"],["has","isMask"]]},line:{layout:{"line-cap":"square"},paint:{"line-width":["case",["==",["geometry-type"],"Polygon"],2,3],"line-dasharray":[1,1],"line-color":"#3170fe"},filter:["!",["has","isMask"]]}},jt="mtlr-gc-full-geom",ln="mtlr-gc-full-geom-fill",un="mtlr-gc-full-geom-line";function an(i,e,t=!0,n=!0,r={},u={},a=on){let o;const g=[];let c,E,_;function M(){if(!i.loaded){i.once("load",M);return}const C=a?a===!0?on:a:void 0;if(!(C!=null&&C.fill)&&!(C!=null&&C.line))return;const O=i.getSource(jt);if(O)O.setData(_??Lt([]));else if(_)i.addSource(jt,{type:"geojson",data:_});else return;!i.getLayer(ln)&&(C!=null&&C.fill)&&i.addLayer({...C==null?void 0:C.fill,id:ln,type:"fill",source:jt}),!i.getLayer(un)&&(C!=null&&C.line)&&i.addLayer({...C==null?void 0:C.line,id:un,type:"line",source:jt})}function R(C){_=C,M()}i.on("styledata",()=>{setTimeout(()=>{_&&M()})});const k=C=>{o==null||o({type:"mapClick",coordinates:[C.lngLat.lng,C.lngLat.lat]})};function I(C=!1){if(!e)throw new Error;const O=document.createElement("div");return C&&O.classList.add("marker-interactive"),new or({props:{displayIn:"maplibre"},target:O}),new e.Marker({element:O,offset:[1,-13]})}return{setEventHandler(C){C?(o=C,i.on("click",k)):(o=void 0,i.off("click",k))},flyTo(C,O){i.flyTo({center:C,...O?{zoom:O}:{},...r})},fitBounds(C,O,x){i.fitBounds([[C[0],C[1]],[C[2],C[3]]],{padding:O,...x?{maxZoom:x}:{},...u})},indicateReverse(C){i.getCanvasContainer().style.cursor=C?"crosshair":""},setReverseMarker(C){!e||!t||(E?C?E.setLngLat(C):(E.remove(),E=void 0):C&&(t instanceof Function?E=t(i)??void 0:(E=(typeof t=="object"?new e.Marker(t):I()).setLngLat(C).addTo(i),E.getElement().classList.add("marker-reverse"))))},setFeatures(C,O,x){for(const N of g)N.remove();if(g.length=0,R(void 0),!!e){e:if(O){let N=!1;if(O.geometry.type==="GeometryCollection"){const P=O.geometry.geometries.filter(B=>B.type==="Polygon"||B.type==="MultiPolygon");t:if(P.length>0){const B=nn(Lt(P.map(z=>Et(z))));if(!B)break t;sn({...O,geometry:B.geometry},R),N=!0}else{const B=O.geometry.geometries.filter(z=>z.type==="LineString"||z.type==="MultiLineString");B.length>0&&(R({...O,geometry:{type:"GeometryCollection",geometries:B}}),N=!0)}}if(!N){if(O.geometry.type==="Polygon"||O.geometry.type==="MultiPolygon")sn(O,R);else if(O.geometry.type==="LineString"||O.geometry.type==="MultiLineString"){R(O);break e}}if(!x&&!O.geometry.type.endsWith("Point"))break e;if(t instanceof Function){const P=t(i,O);P&&g.push(P)}else t&&g.push(typeof t=="object"?new e.Marker(t):I().setLngLat(O.center).addTo(i))}if(n)for(const N of C??[]){if(N===O)continue;let P;if(n instanceof Function){if(P=n(i,N),!P)continue}else P=(typeof n=="object"?new e.Marker(n):I(!0)).setLngLat(N.center).setPopup(new e.Popup({offset:[1,-27],closeButton:!1,closeOnMove:!0,className:"maptiler-gc-popup"}).setText(N.place_type[0]==="reverse"?N.place_name:N.place_name.replace(/,.*/,""))).addTo(i);const B=P.getElement();B.addEventListener("click",z=>{z.stopPropagation(),o==null||o({type:"markerClick",id:N.id})}),B.addEventListener("mouseenter",()=>{o==null||o({type:"markerMouseEnter",id:N.id}),P.togglePopup()}),B.addEventListener("mouseleave",()=>{o==null||o({type:"markerMouseLeave",id:N.id}),P.togglePopup()}),g.push(P)}}},setSelectedMarker(C){c&&c.getElement().classList.toggle("marker-selected",!1),c=C>-1?g[C]:void 0,c==null||c.getElement().classList.toggle("marker-selected",!0)},getCenterAndZoom(){const C=i.getCenter();return[i.getZoom(),C.lng,C.lat]}}}function ns(i,e,t){var k,I,C;class n{constructor(x,N){A(this,"type");A(this,"target");this.type=N,this.target=x}}class r extends n{constructor(N,P){super(N,"select");A(this,"feature");Object.assign(this,P)}}class u extends n{constructor(N,P){super(N,"featureslisted");A(this,"features");this.features=P}}class a extends n{constructor(N,P){super(N,"featuresmarked");A(this,"features");this.features=P}}class o extends n{constructor(N,P){super(N,"optionsvisibilitychange");A(this,"optionsVisible");this.optionsVisible=P}}class g extends n{constructor(N,P){super(N,"pick");A(this,"feature");this.feature=P}}class c extends n{constructor(N,P){super(N,"querychange");A(this,"query");this.query=P}}class E extends n{constructor(N,P,B){super(N,"response");A(this,"url");A(this,"featureCollection");this.url=P,this.featureCollection=B}}class _ extends n{constructor(N,P){super(N,"reversetoggle");A(this,"reverse");this.reverse=P}}class M extends i{constructor(N={}){super();Vt(this,k);Vt(this,I);Vt(this,C);kt(this,I,N)}onAddInt(N){const P=document.createElement("div");P.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl mapboxgl-ctrl-group";const{marker:B,showResultMarkers:z,flyTo:W,fullGeometryStyle:s,...l}=ue(this,I),f=typeof W=="boolean"?{}:W,h={mapController:an(N,e,B,z,f,f,s),flyTo:W===void 0?!0:!!W,apiKey:"",...t==null?void 0:t(N,P),...l};return h.apiKey||console.warn("No MapTiler Cloud API key was provided, some or all geocoding requests may fail"),kt(this,k,new kr({target:P,props:h})),ue(this,k).$on("select",d=>{this.fire(new r(this,d.detail))}),ue(this,k).$on("pick",d=>{this.fire(new g(this,d.detail.feature))}),ue(this,k).$on("featureslisted",d=>{this.fire(new u(this,d.detail.features))}),ue(this,k).$on("featuresmarked",d=>{this.fire(new a(this,d.detail.features))}),ue(this,k).$on("response",d=>{this.fire(new E(this,d.detail.url,d.detail.featureCollection))}),ue(this,k).$on("optionsvisibilitychange",d=>{this.fire(new o(this,d.detail.optionsVisible))}),ue(this,k).$on("reversetoggle",d=>{this.fire(new _(this,d.detail.reverse))}),ue(this,k).$on("querychange",d=>{this.fire(new c(this,d.detail.query))}),kt(this,C,P),P}on(N,P){return super.on(N,P)}once(N,P){return super.once(N,P)}off(N,P){return super.off(N,P)}listens(N){return super.listens(N)}setOptions(N){var l;Object.assign(ue(this,I),N);const{marker:P,showResultMarkers:B,flyTo:z,fullGeometryStyle:W,...s}=ue(this,I);(l=ue(this,k))==null||l.$set(s)}setQuery(N,P=!0){var B;(B=ue(this,k))==null||B.setQuery(N,P)}clearMap(){var N;(N=ue(this,k))==null||N.clearMap()}clearList(){var N;(N=ue(this,k))==null||N.clearList()}setReverseMode(N){var P;(P=ue(this,k))==null||P.$set({reverseActive:N})}focus(N){var P;(P=ue(this,k))==null||P.focus(N)}blur(){var N;(N=ue(this,k))==null||N.blur()}onRemove(){var N,P,B;(N=ue(this,k))==null||N.$destroy(),kt(this,k,void 0),(B=(P=ue(this,C))==null?void 0:P.parentNode)==null||B.removeChild(ue(this,C))}}return k=new WeakMap,I=new WeakMap,C=new WeakMap,{MapLibreBasedGeocodingControl:M,events:{SelectEvent:r,FeaturesListedEvent:u,FeaturesMarkedEvent:a,OptionsVisibilityChangeEvent:o,PickEvent:g,QueryChangeEvent:c,ResponseEvent:E,ReverseToggleEvent:_}}}const{MapLibreBasedGeocodingControl:rs,events:et}=ns(dt.Evented,dt);class ss extends rs{onAdd(e){return super.onAddInt(e)}}const os=et.SelectEvent,ls=et.FeaturesListedEvent,us=et.FeaturesMarkedEvent,as=et.OptionsVisibilityChangeEvent,fs=et.PickEvent,cs=et.QueryChangeEvent,hs=et.ResponseEvent,ds=et.ReverseToggleEvent;j.FeaturesListedEvent=ls,j.FeaturesMarkedEvent=us,j.GeocodingControl=ss,j.OptionsVisibilityChangeEvent=as,j.PickEvent=fs,j.QueryChangeEvent=cs,j.ResponseEvent=hs,j.ReverseToggleEvent=ds,j.SelectEvent=os,j.createMapLibreGlMapController=an,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"})}); +//# sourceMappingURL=maplibregl.umd.js.map diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css b/docs/articles/turf_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css new file mode 100644 index 0000000..c865c17 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/maptiler-geocoding-control/style.css @@ -0,0 +1 @@ +svg.svelte-d2loi5{display:block;fill:#e15042}.sprite-icon.svelte-w9y5n9.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75;background-repeat:no-repeat}li.svelte-w9y5n9.svelte-w9y5n9{text-align:left;cursor:default;display:grid;grid-template-columns:40px 1fr;color:var(--color-text);padding:8px 0;font-size:14px;line-height:18px;min-width:fit-content;outline:0}li.svelte-w9y5n9.svelte-w9y5n9:first-child{padding-top:10px}li.svelte-w9y5n9.svelte-w9y5n9:last-child{padding-bottom:10px}li.picked.svelte-w9y5n9.svelte-w9y5n9{background-color:#e7edff}li.picked.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#96a4c7;padding-left:4px}li.picked.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#96a4c7}li.selected.svelte-w9y5n9.svelte-w9y5n9{background-color:#f3f6ff}li.selected.svelte-w9y5n9.svelte-w9y5n9{animation:svelte-w9y5n9-backAndForth 5s linear infinite}li.selected.svelte-w9y5n9 .primary.svelte-w9y5n9{color:#2b8bfb}li.selected.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#a2adc7;padding-left:4px}li.selected.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#a2adc7}li.svelte-w9y5n9>img.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75}.texts.svelte-w9y5n9.svelte-w9y5n9{padding:0 17px 0 0}.texts.svelte-w9y5n9>.svelte-w9y5n9{white-space:nowrap;display:block;min-width:fit-content}.primary.svelte-w9y5n9.svelte-w9y5n9{font-weight:600}.secondary.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7;padding-left:4px}.line2.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7}@keyframes svelte-w9y5n9-backAndForth{0%{transform:translate(0)}10%{transform:translate(0)}45%{transform:translate(calc(-100% + 270px))}55%{transform:translate(calc(-100% + 270px))}90%{transform:translate(0)}to{transform:translate(0)}}div.svelte-1ocfouu{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);pointer-events:none;display:flex;align-items:center}.loading-icon.svelte-1ocfouu{animation:svelte-1ocfouu-rotate .8s infinite cubic-bezier(.45,.05,.55,.95)}@keyframes svelte-1ocfouu-rotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}svg.svelte-gzo3ar.svelte-gzo3ar{display:block;fill:#6b7c93;stroke:#6b7c93}.list-icon.svelte-gzo3ar.svelte-gzo3ar{grid-row:1/3;align-self:center;margin:8px}.in-map.svelte-gzo3ar.svelte-gzo3ar{height:30px}.maplibregl-canvas-container .marker-selected{z-index:1}.maplibregl-canvas-container svg.svelte-gzo3ar path.svelte-gzo3ar,.leaflet-map-pane svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#3170fe;stroke:#3170fe}.marker-selected svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#98b7ff;stroke:#3170fe}.marker-reverse svg.svelte-gzo3ar path.svelte-gzo3ar{fill:silver;stroke:gray}.marker-interactive{cursor:pointer!important}.maptiler-gc-popup>.maplibregl-popup-content{padding:2px 8px}svg.svelte-en2qvf{display:block;fill:var(--color-icon-button)}circle.svelte-1aq105l{stroke-width:1.875;fill:none}path.svelte-1aq105l{stroke-width:1.875;stroke-linecap:round}svg.svelte-1aq105l{display:block;stroke:var(--color-icon-button)}form.svelte-bz0zu3.svelte-bz0zu3{font-family:Open Sans,Ubuntu,Helvetica Neue,Arial,Helvetica,sans-serif;position:relative;background-color:#fff;z-index:10;border-radius:4px;margin:0;transition:max-width .25s;box-shadow:0 2px 5px #33335926;--color-text:#444952;--color-icon-button:#444952}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3:after,form.svelte-bz0zu3 .svelte-bz0zu3:before{box-sizing:border-box}form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:29px}form.can-collapse.svelte-bz0zu3 input.svelte-bz0zu3::placeholder{transition:opacity .25s;opacity:0}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3.svelte-bz0zu3:focus-within,form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px}form.svelte-bz0zu3 input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:focus-within input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:hover input.svelte-bz0zu3::placeholder{opacity:1}input.svelte-bz0zu3.svelte-bz0zu3{font:inherit;font-size:14px;flex-grow:1;min-height:29px;background-color:transparent;color:#444952;white-space:nowrap;overflow:hidden;border:0;margin:0;padding:0}input.svelte-bz0zu3.svelte-bz0zu3:focus{color:#444952;outline:0;outline:none;box-shadow:none}ul.svelte-bz0zu3.svelte-bz0zu3,div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{background-color:#fff;border-radius:4px;left:0;list-style:none;margin:0;padding:0;position:absolute;width:100%;top:calc(100% + 6px);overflow:hidden}ul.svelte-bz0zu3.svelte-bz0zu3{font-size:14px;line-height:16px;box-shadow:0 5px 10px #33335926}div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{font:inherit;line-height:18px;font-size:12px;display:flex;gap:16px}div.error.svelte-bz0zu3.svelte-bz0zu3{padding:16px;font-weight:600;color:#e25041;background-color:#fbeae8}div.error.svelte-bz0zu3 div.svelte-bz0zu3{flex-grow:1}div.error.svelte-bz0zu3 svg{flex-shrink:0;width:20px;height:20px}div.error.svelte-bz0zu3 button.svelte-bz0zu3{flex-shrink:0}div.error.svelte-bz0zu3 button.svelte-bz0zu3>svg{width:13px;fill:#e25041}div.error.svelte-bz0zu3 button.svelte-bz0zu3:hover svg,div.error.svelte-bz0zu3 button.svelte-bz0zu3:active svg{fill:#444952}div.no-results.svelte-bz0zu3.svelte-bz0zu3{padding:14px 24px 14px 16px;font-weight:400;color:#6b7c93;box-shadow:0 5px 10px #33335926}div.no-results.svelte-bz0zu3 svg{margin-top:4px;flex-shrink:0;width:20px;height:20px;width:30px;height:30px}.leaflet-bottom ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-left ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-right ul.options.svelte-bz0zu3.svelte-bz0zu3{top:auto;bottom:calc(100% + 6px)}button.svelte-bz0zu3.svelte-bz0zu3{padding:0;margin:0;border:0;background-color:transparent;height:auto;width:auto}button.svelte-bz0zu3.svelte-bz0zu3:hover{background-color:transparent}button.svelte-bz0zu3:hover svg,button.svelte-bz0zu3:active svg{fill:#2b8bfb}.input-group.svelte-bz0zu3.svelte-bz0zu3{display:flex;align-items:stretch;gap:7px;padding-inline:8px;border-radius:4px;overflow:hidden}.input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{outline:#2b8bfb solid 2px}.search-button.svelte-bz0zu3.svelte-bz0zu3{flex-shrink:0}.maplibregl-ctrl-geocoder:not(.maptiler-ctrl) .search-button svg{width:12px!important;transform:translate(.5px)}.clear-button-container.svelte-bz0zu3.svelte-bz0zu3{display:flex;display:none;position:relative;align-items:stretch}.clear-button-container.displayable.svelte-bz0zu3.svelte-bz0zu3{display:flex;flex-shrink:0}.maplibregl-ctrl-geocoder{position:relative;z-index:3}.maptiler-ctrl:not(:empty){box-shadow:none}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3{padding-inline:8px;border:white solid 2px}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{border:#2b8bfb solid 2px;outline:0;outline:none}.maptiler-ctrl form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:33px}.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:focus-within,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px} diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js new file mode 100644 index 0000000..1a901ee --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/pmtiles/pmtiles.js @@ -0,0 +1,2 @@ +"use strict";var pmtiles=(()=>{var k=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var U=Math.pow;var f=(r,e)=>k(r,"name",{value:e,configurable:!0});var Xe=(r,e)=>{for(var t in e)k(r,t,{get:e[t],enumerable:!0})},_e=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ye(e))!Qe.call(r,i)&&i!==t&&k(r,i,{get:()=>e[i],enumerable:!(n=Je(e,i))||n.enumerable});return r};var et=r=>_e(k({},"__esModule",{value:!0}),r);var m=(r,e,t)=>new Promise((n,i)=>{var a=h=>{try{u(t.next(h))}catch(l){i(l)}},s=h=>{try{u(t.throw(h))}catch(l){i(l)}},u=h=>h.done?n(h.value):Promise.resolve(h.value).then(a,s);u((t=t.apply(r,e)).next())});var Dt={};Xe(Dt,{Compression:()=>Oe,EtagMismatch:()=>B,FetchSource:()=>K,FileSource:()=>oe,PMTiles:()=>P,Protocol:()=>ie,ResolvedValueCache:()=>ue,SharedPromiseCache:()=>G,TileType:()=>se,bytesToHeader:()=>$e,findTile:()=>Fe,getUint64:()=>b,leafletRasterLayer:()=>wt,readVarint:()=>R,tileIdToZxy:()=>Tt,tileTypeExt:()=>Ze,zxyToTileId:()=>Ie});var w=Uint8Array,E=Uint16Array,tt=Int32Array,Me=new w([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ue=new w([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),rt=new w([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ee=f(function(r,e){for(var t=new E(31),n=0;n<31;++n)t[n]=e+=1<>1|(g&21845)<<1,T=(T&52428)>>2|(T&13107)<<2,T=(T&61680)>>4|(T&3855)<<4,re[g]=((T&65280)>>8|(T&255)<<8)>>1;var T,g,F=f(function(r,e,t){for(var n=r.length,i=0,a=new E(e);i>h]=l}else for(u=new E(n),i=0;i>15-r[i]);return u},"hMap"),$=new w(288);for(g=0;g<144;++g)$[g]=8;var g;for(g=144;g<256;++g)$[g]=9;var g;for(g=256;g<280;++g)$[g]=7;var g;for(g=280;g<288;++g)$[g]=8;var g,Re=new w(32);for(g=0;g<32;++g)Re[g]=5;var g;var at=F($,9,1);var st=F(Re,5,1),ee=f(function(r){for(var e=r[0],t=1;te&&(e=r[t]);return e},"max"),z=f(function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},"bits"),te=f(function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},"bits16"),ot=f(function(r){return(r+7)/8|0},"shft"),ut=f(function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new w(r.subarray(e,t))},"slc");var ft=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],y=f(function(r,e,t){var n=new Error(e||ft[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,y),!t)throw n;return n},"err"),ne=f(function(r,e,t,n){var i=r.length,a=n?n.length:0;if(!i||e.f&&!e.l)return t||new w(0);var s=!t,u=s||e.i!=2,h=e.i;s&&(t=new w(i*3));var l=f(function(Te){var Ce=t.length;if(Te>Ce){var De=new w(Math.max(Ce*2,Te));De.set(t),t=De}},"cbuf"),c=e.f||0,o=e.p||0,v=e.b||0,d=e.l,p=e.d,H=e.m,I=e.n,q=i*8;do{if(!d){c=z(r,o,1);var j=z(r,o+1,3);if(o+=3,j)if(j==1)d=at,p=st,H=9,I=5;else if(j==2){var J=z(r,o,31)+257,me=z(r,o+10,15)+4,de=J+z(r,o+5,31)+1;o+=14;for(var O=new w(de),Y=new w(19),x=0;x>4;if(A<16)O[x++]=A;else{var D=0,V=0;for(A==16?(V=3+z(r,o,3),o+=2,D=O[x-1]):A==17?(V=3+z(r,o,7),o+=3):A==18&&(V=11+z(r,o,127),o+=7);V--;)O[x++]=D}}var xe=O.subarray(0,J),C=O.subarray(J);H=ee(xe),I=ee(C),d=F(xe,H,1),p=F(C,I,1)}else y(1);else{var A=ot(o)+4,W=r[A-4]|r[A-3]<<8,N=A+W;if(N>i){h&&y(0);break}u&&l(v+W),t.set(r.subarray(A,N),v),e.b=v+=W,e.p=o=N*8,e.f=c;continue}if(o>q){h&&y(0);break}}u&&l(v+131072);for(var je=(1<>4;if(o+=D&15,o>q){h&&y(0);break}if(D||y(2),M<256)t[v++]=M;else if(M==256){Q=o,d=null;break}else{var be=M-254;if(M>264){var x=M-257,Z=Me[x];be=z(r,o,(1<>4;X||y(3),o+=X&15;var C=it[_];if(_>3){var Z=Ue[_];C+=te(r,o)&(1<q){h&&y(0);break}u&&l(v+131072);var ze=v+be;if(v>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},"gzs"),ct=f(function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0},"gzl");var vt=f(function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&y(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&y(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2},"zls");function gt(r,e){return ne(r,{i:2},e&&e.out,e&&e.dictionary)}f(gt,"inflateSync");function pt(r,e){var t=ht(r);return t+8>r.length&&y(6,"invalid gzip data"),ne(r.subarray(t,-8),{i:2},e&&e.out||new w(ct(r)),e&&e.dictionary)}f(pt,"gunzipSync");function mt(r,e){return ne(r.subarray(vt(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}f(mt,"unzlibSync");function Be(r,e){return r[0]==31&&r[1]==139&&r[2]==8?pt(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?gt(r,e):mt(r,e)}f(Be,"decompressSync");var dt=typeof TextDecoder!="undefined"&&new TextDecoder,yt=0;try{dt.decode(lt,{stream:!0}),yt=1}catch(r){}var wt=f((r,e)=>{let t=!1,n="",i=L.GridLayer.extend({createTile:f((a,s)=>{let u=document.createElement("img"),h=new AbortController,l=h.signal;return u.cancel=()=>{h.abort()},t||(r.getHeader().then(c=>{c.tileType===1?console.error("Error: archive contains MVT vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details."):c.tileType===2?n="image/png":c.tileType===3?n="image/jpeg":c.tileType===4?n="image/webp":c.tileType===5&&(n="image/avif")}),t=!0),r.getZxy(a.z,a.x,a.y,l).then(c=>{if(c){let o=new Blob([c.data],{type:n}),v=window.URL.createObjectURL(o);u.src=v,u.cancel=void 0,s(void 0,u)}}).catch(c=>{if(c.name!=="AbortError")throw c}),u},"createTile"),_removeTile:f(function(a){let s=this._tiles[a];s&&(s.el.cancel&&s.el.cancel(),s.el.width=0,s.el.height=0,s.el.deleted=!0,L.DomUtil.remove(s.el),delete this._tiles[a],this.fire("tileunload",{tile:s.el,coords:this._keyToTileCoords(a)}))},"_removeTile")});return new i(e)},"leafletRasterLayer"),xt=f(r=>(e,t)=>{if(t instanceof AbortController)return r(e,t);let n=new AbortController;return r(e,n).then(i=>t(void 0,i.data,i.cacheControl||"",i.expires||""),i=>t(i)).catch(i=>t(i)),{cancel:f(()=>n.abort(),"cancel")}},"v3compat"),ae=class ae{constructor(e){this.tilev4=f((e,t)=>m(this,null,function*(){if(e.type==="json"){let v=e.url.substr(10),d=this.tiles.get(v);if(d||(d=new P(v),this.tiles.set(v,d)),this.metadata)return{data:yield d.getTileJson(e.url)};let p=yield d.getHeader();return(p.minLon>=p.maxLon||p.minLat>=p.maxLat)&&console.error(`Bounds of PMTiles archive ${p.minLon},${p.minLat},${p.maxLon},${p.maxLat} are not valid.`),{data:{tiles:[`${e.url}/{z}/{x}/{y}`],minzoom:p.minZoom,maxzoom:p.maxZoom,bounds:[p.minLon,p.minLat,p.maxLon,p.maxLat]}}}let n=new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/),i=e.url.match(n);if(!i)throw new Error("Invalid PMTiles protocol URL");let a=i[1],s=this.tiles.get(a);s||(s=new P(a),this.tiles.set(a,s));let u=i[2],h=i[3],l=i[4],c=yield s.getHeader(),o=yield s==null?void 0:s.getZxy(+u,+h,+l,t.signal);if(o)return{data:new Uint8Array(o.data),cacheControl:o.cacheControl,expires:o.expires};if(c.tileType===1){if(this.errorOnMissingTile)throw new Error("Tile not found.");return{data:new Uint8Array}}return{data:null}}),"tilev4");this.tile=xt(this.tilev4);this.tiles=new Map,this.metadata=(e==null?void 0:e.metadata)||!1,this.errorOnMissingTile=(e==null?void 0:e.errorOnMissingTile)||!1}add(e){this.tiles.set(e.source.getKey(),e)}get(e){return this.tiles.get(e)}};f(ae,"Protocol");var ie=ae;function S(r,e){return(e>>>0)*4294967296+(r>>>0)}f(S,"toNum");function bt(r,e){let t=e.buf,n=t[e.pos++],i=(n&112)>>4;if(n<128||(n=t[e.pos++],i|=(n&127)<<3,n<128)||(n=t[e.pos++],i|=(n&127)<<10,n<128)||(n=t[e.pos++],i|=(n&127)<<17,n<128)||(n=t[e.pos++],i|=(n&127)<<24,n<128)||(n=t[e.pos++],i|=(n&1)<<31,n<128))return S(r,i);throw new Error("Expected varint not more than 10 bytes")}f(bt,"readVarintRemainder");function R(r){let e=r.buf,t=e[r.pos++],n=t&127;return t<128||(t=e[r.pos++],n|=(t&127)<<7,t<128)||(t=e[r.pos++],n|=(t&127)<<14,t<128)||(t=e[r.pos++],n|=(t&127)<<21,t<128)?n:(t=e[r.pos],n|=(t&15)<<28,bt(n,r))}f(R,"readVarint");function He(r,e,t,n){if(n===0){t===1&&(e[0]=r-1-e[0],e[1]=r-1-e[1]);let i=e[0];e[0]=e[1],e[1]=i}}f(He,"rotate");function zt(r,e){let t=U(2,r),n=e,i=e,a=e,s=[0,0],u=1;for(;u26)throw new Error("Tile zoom level exceeds max safe number limit (26)");if(e>U(2,r)-1||t>U(2,r)-1)throw new Error("tile x/y outside zoom level bounds");let n=At[r],i=U(2,r),a=0,s=0,u=0,h=[e,t],l=i/2;for(;l>0;)a=(h[0]&l)>0?1:0,s=(h[1]&l)>0?1:0,u+=l*l*(3*a^s),He(l,h,a,s),l=l/2;return n+u}f(Ie,"zxyToTileId");function Tt(r){let e=0,t=0;for(let n=0;n<27;n++){let i=(1<r)return zt(n,r-e);e+=i}throw new Error("Tile zoom level exceeds max safe number limit (26)")}f(Tt,"tileIdToZxy");var Oe=(a=>(a[a.Unknown=0]="Unknown",a[a.None=1]="None",a[a.Gzip=2]="Gzip",a[a.Brotli=3]="Brotli",a[a.Zstd=4]="Zstd",a))(Oe||{});function fe(r,e){return m(this,null,function*(){if(e===1||e===0)return r;if(e===2){if(typeof globalThis.DecompressionStream=="undefined")return Be(new Uint8Array(r));let t=new Response(r).body;if(!t)throw new Error("Failed to read response stream");let n=t.pipeThrough(new globalThis.DecompressionStream("gzip"));return new Response(n).arrayBuffer()}throw new Error("Compression method not supported")})}f(fe,"defaultDecompress");var se=(s=>(s[s.Unknown=0]="Unknown",s[s.Mvt=1]="Mvt",s[s.Png=2]="Png",s[s.Jpeg=3]="Jpeg",s[s.Webp=4]="Webp",s[s.Avif=5]="Avif",s))(se||{});function Ze(r){return r===1?".mvt":r===2?".png":r===3?".jpg":r===4?".webp":r===5?".avif":""}f(Ze,"tileTypeExt");var Ct=127;function Fe(r,e){let t=0,n=r.length-1;for(;t<=n;){let i=n+t>>1,a=e-r[i].tileId;if(a>0)t=i+1;else if(a<0)n=i-1;else return r[i]}return n>=0&&(r[n].runLength===0||e-r[n].tileId-1,a=/Chrome|Chromium|Edg|OPR|Brave/.test(n);this.chromeWindowsNoCache=!1,i&&a&&(this.chromeWindowsNoCache=!0)}getKey(){return this.url}setHeaders(e){this.customHeaders=e}getBytes(e,t,n,i){return m(this,null,function*(){let a,s;n?s=n:(a=new AbortController,s=a.signal);let u=new Headers(this.customHeaders);u.set("range",`bytes=${e}-${e+t-1}`);let h;this.mustReload?h="reload":this.chromeWindowsNoCache&&(h="no-store");let l=yield fetch(this.url,{signal:s,cache:h,headers:u});if(e===0&&l.status===416){let d=l.headers.get("Content-Range");if(!d||!d.startsWith("bytes */"))throw new Error("Missing content-length on 416 response");let p=+d.substr(8);l=yield fetch(this.url,{signal:s,cache:"reload",headers:{range:`bytes=0-${p-1}`}})}let c=l.headers.get("Etag");if(c!=null&&c.startsWith("W/")&&(c=null),l.status===416||i&&c&&c!==i)throw this.mustReload=!0,new B(`Server returned non-matching ETag ${i} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);if(l.status>=300)throw new Error(`Bad response code: ${l.status}`);let o=l.headers.get("Content-Length");if(l.status===200&&(!o||+o>t))throw a&&a.abort(),new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");return{data:yield l.arrayBuffer(),etag:c||void 0,cacheControl:l.headers.get("Cache-Control")||void 0,expires:l.headers.get("Expires")||void 0}})}};f(he,"FetchSource");var K=he;function b(r,e){let t=r.getUint32(e+4,!0),n=r.getUint32(e+0,!0);return t*U(2,32)+n}f(b,"getUint64");function $e(r,e){let t=new DataView(r),n=t.getUint8(7);if(n>3)throw new Error(`Archive is spec version ${n} but this library supports up to spec version 3`);return{specVersion:n,rootDirectoryOffset:b(t,8),rootDirectoryLength:b(t,16),jsonMetadataOffset:b(t,24),jsonMetadataLength:b(t,32),leafDirectoryOffset:b(t,40),leafDirectoryLength:b(t,48),tileDataOffset:b(t,56),tileDataLength:b(t,64),numAddressedTiles:b(t,72),numTileEntries:b(t,80),numTileContents:b(t,88),clustered:t.getUint8(96)===1,internalCompression:t.getUint8(97),tileCompression:t.getUint8(98),tileType:t.getUint8(99),minZoom:t.getUint8(100),maxZoom:t.getUint8(101),minLon:t.getInt32(102,!0)/1e7,minLat:t.getInt32(106,!0)/1e7,maxLon:t.getInt32(110,!0)/1e7,maxLat:t.getInt32(114,!0)/1e7,centerZoom:t.getUint8(118),centerLon:t.getInt32(119,!0)/1e7,centerLat:t.getInt32(123,!0)/1e7,etag:e}}f($e,"bytesToHeader");function Ve(r){let e={buf:new Uint8Array(r),pos:0},t=R(e),n=[],i=0;for(let a=0;a0?n[a].offset=n[a-1].offset+n[a-1].length:n[a].offset=s-1}return n}f(Ve,"deserializeIndex");var ce=class ce extends Error{};f(ce,"EtagMismatch");var B=ce;function ke(r,e){return m(this,null,function*(){let t=yield r.getBytes(0,16384);if(new DataView(t.data).getUint16(0,!0)!==19792)throw new Error("Wrong magic number for PMTiles archive");let i=t.data.slice(0,Ct),a=$e(i,t.etag),s=t.data.slice(a.rootDirectoryOffset,a.rootDirectoryOffset+a.rootDirectoryLength),u=`${r.getKey()}|${a.etag||""}|${a.rootDirectoryOffset}|${a.rootDirectoryLength}`,h=Ve(yield e(s,a.internalCompression));return[a,[u,h.length,h]]})}f(ke,"getHeaderAndRoot");function Ke(r,e,t,n,i){return m(this,null,function*(){let a=yield r.getBytes(t,n,void 0,i.etag),s=yield e(a.data,i.internalCompression),u=Ve(s);if(u.length===0)throw new Error("Empty directory is invalid");return u})}f(Ke,"getDirectory");var ve=class ve{constructor(e=100,t=!0,n=fe){this.cache=new Map,this.maxCacheEntries=e,this.counter=1,this.decompress=n}getHeader(e){return m(this,null,function*(){let t=e.getKey(),n=this.cache.get(t);if(n)return n.lastUsed=this.counter++,n.data;let i=yield ke(e,this.decompress);return i[1]&&this.cache.set(i[1][0],{lastUsed:this.counter++,data:i[1][2]}),this.cache.set(t,{lastUsed:this.counter++,data:i[0]}),this.prune(),i[0]})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,s.data;let u=yield Ke(e,this.decompress,t,n,i);return this.cache.set(a,{lastUsed:this.counter++,data:u}),this.prune(),u})}prune(){if(this.cache.size>this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{ke(e,this.decompress).then(u=>{u[1]&&this.cache.set(u[1][0],{lastUsed:this.counter++,data:Promise.resolve(u[1][2])}),a(u[0]),this.prune()}).catch(u=>{s(u)})});return this.cache.set(t,{lastUsed:this.counter++,data:i}),i})}getDirectory(e,t,n,i){return m(this,null,function*(){let a=`${e.getKey()}|${i.etag||""}|${t}|${n}`,s=this.cache.get(a);if(s)return s.lastUsed=this.counter++,yield s.data;let u=new Promise((h,l)=>{Ke(e,this.decompress,t,n,i).then(c=>{h(c),this.prune()}).catch(c=>{l(c)})});return this.cache.set(a,{lastUsed:this.counter++,data:u}),u})}prune(){if(this.cache.size>=this.maxCacheEntries){let e=1/0,t;this.cache.forEach((n,i)=>{n.lastUsed{this.getHeader(e).then(s=>{i(),this.invalidations.delete(t)}).catch(s=>{a(s)})});this.invalidations.set(t,n)})}};f(ge,"SharedPromiseCache");var G=ge,pe=class pe{constructor(e,t,n){typeof e=="string"?this.source=new K(e):this.source=e,n?this.decompress=n:this.decompress=fe,t?this.cache=t:this.cache=new G}getHeader(){return m(this,null,function*(){return yield this.cache.getHeader(this.source)})}getZxyAttempt(e,t,n,i){return m(this,null,function*(){let a=Ie(e,t,n),s=yield this.cache.getHeader(this.source);if(es.maxZoom)return;let u=s.rootDirectoryOffset,h=s.rootDirectoryLength;for(let l=0;l<=3;l++){let c=yield this.cache.getDirectory(this.source,u,h,s),o=Fe(c,a);if(o){if(o.runLength>0){let v=yield this.source.getBytes(s.tileDataOffset+o.offset,o.length,i,s.etag);return{data:yield this.decompress(v.data,s.tileCompression),cacheControl:v.cacheControl,expires:v.expires}}u=s.leafDirectoryOffset+o.offset,h=o.length}else return}throw new Error("Maximum directory depth exceeded")})}getZxy(e,t,n,i){return m(this,null,function*(){try{return yield this.getZxyAttempt(e,t,n,i)}catch(a){if(a instanceof B)return this.cache.invalidate(this.source),yield this.getZxyAttempt(e,t,n,i);throw a}})}getMetadataAttempt(){return m(this,null,function*(){let e=yield this.cache.getHeader(this.source),t=yield this.source.getBytes(e.jsonMetadataOffset,e.jsonMetadataLength,void 0,e.etag),n=yield this.decompress(t.data,e.internalCompression),i=new TextDecoder("utf-8");return JSON.parse(i.decode(n))})}getMetadata(){return m(this,null,function*(){try{return yield this.getMetadataAttempt()}catch(e){if(e instanceof B)return this.cache.invalidate(this.source),yield this.getMetadataAttempt();throw e}})}getTileJson(e){return m(this,null,function*(){let t=yield this.getHeader(),n=yield this.getMetadata(),i=Ze(t.tileType);return{tilejson:"3.0.0",scheme:"xyz",tiles:[`${e}/{z}/{x}/{y}${i}`],vector_layers:n.vector_layers,attribution:n.attribution,description:n.description,name:n.name,version:n.version,bounds:[t.minLon,t.minLat,t.maxLon,t.maxLat],center:[t.centerLon,t.centerLat,t.centerZoom],minzoom:t.minZoom,maxzoom:t.maxZoom}})}};f(pe,"PMTiles");var P=pe;return et(Dt);})(); +//# sourceMappingURL=pmtiles.js.map \ No newline at end of file diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js new file mode 100644 index 0000000..2b7b5bf --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/radius-mode/radius-mode.js @@ -0,0 +1,311 @@ +// Radius/Circle drawing mode for Mapbox GL Draw +// Creates a circle by drawing from center to edge +(function (MapboxDraw) { + const DrawLine = MapboxDraw.modes.draw_line_string; + + // Utility function to create a vertex feature + const createVertex = function (parentId, coordinates, path, selected) { + return { + type: "Feature", + properties: { + meta: "vertex", + parent: parentId, + coord_path: path, + active: selected ? "true" : "false" + }, + geometry: { + type: "Point", + coordinates: coordinates + } + }; + }; + + // Utility function to calculate distance between two points in kilometers + const calculateDistance = function (coord1, coord2) { + const lat1 = coord1[1]; + const lon1 = coord1[0]; + const lat2 = coord2[1]; + const lon2 = coord2[0]; + + const R = 6371; // Radius of the Earth in kilometers + const dLat = (lat2 - lat1) * Math.PI / 180; + const dLon = (lon2 - lon1) * Math.PI / 180; + const a = + Math.sin(dLat/2) * Math.sin(dLat/2) + + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * + Math.sin(dLon/2) * Math.sin(dLon/2); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + const distance = R * c; + + return distance; + }; + + // Utility function to create a GeoJSON circle + const createGeoJSONCircle = function (center, radiusInKm, parentId, points) { + points = points || 64; + + const coords = { + latitude: center[1], + longitude: center[0] + }; + + const km = radiusInKm; + const ret = []; + const distanceX = km / (111.32 * Math.cos((coords.latitude * Math.PI) / 180)); + const distanceY = km / 110.574; + + let theta, x, y; + for (let i = 0; i < points; i++) { + theta = (i / points) * (2 * Math.PI); + x = distanceX * Math.cos(theta); + y = distanceY * Math.sin(theta); + + ret.push([coords.longitude + x, coords.latitude + y]); + } + ret.push(ret[0]); + + return { + type: "Feature", + geometry: { + type: "Polygon", + coordinates: [ret] + }, + properties: { + parent: parentId, + meta: "radius" + } + }; + }; + + // Utility function to format distance for display + const getDisplayMeasurements = function (distanceKm) { + let metricUnits = "m"; + let metricFormat = "0,0"; + let metricMeasurement; + + let standardUnits = "feet"; + let standardFormat = "0,0"; + let standardMeasurement; + + metricMeasurement = distanceKm * 1000; // Convert to meters + if (metricMeasurement >= 1000) { + metricMeasurement = metricMeasurement / 1000; + metricUnits = "km"; + metricFormat = "0.00"; + } + + standardMeasurement = distanceKm * 1000 * 3.28084; // Convert to feet + if (standardMeasurement >= 5280) { + standardMeasurement = standardMeasurement / 5280; + standardUnits = "mi"; + standardFormat = "0.00"; + } + + // Simple number formatting (without numeral.js dependency) + const formatNumber = function(num, format) { + if (format === "0,0") { + return Math.round(num).toLocaleString(); + } else if (format === "0.00") { + return num.toFixed(2); + } + return num.toString(); + }; + + return { + metric: formatNumber(metricMeasurement, metricFormat) + " " + metricUnits, + standard: formatNumber(standardMeasurement, standardFormat) + " " + standardUnits + }; + }; + + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RadiusMode = Object.assign({}, DrawLine); + + RadiusMode.onSetup = function (opts) { + const line = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "LineString", + coordinates: [] + } + }); + + this.addFeature(line); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.activateUIButton("line"); + this.setActionableState({ trash: true }); + + return { + line: line, + currentVertexPosition: 0, + direction: "forward" + }; + }; + + RadiusMode.onClick = function (state, e) { + // This ends the drawing after the user creates a second point + if (state.currentVertexPosition === 1) { + // Update the second coordinate in place, don't add at position 0 + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + return this.changeMode("simple_select", { featureIds: [state.line.id] }); + } + + this.updateUIClasses({ mouse: "add" }); + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + + if (state.direction === "forward") { + state.currentVertexPosition += 1; + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + } else { + state.line.addCoordinate(0, e.lngLat.lng, e.lngLat.lat); + } + + return null; + }; + + RadiusMode.onMouseMove = function (state, e) { + if (state.currentVertexPosition === 1) { + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + } + }; + + // Creates the final geojson circle polygon + RadiusMode.onStop = function (state) { + doubleClickZoom.enable(this); + this.activateUIButton(); + + // Check to see if we've deleted this feature + if (this.getFeature(state.line.id) === undefined) return; + + if (state.line.isValid()) { + const lineGeoJson = state.line.toGeoJSON(); + const coords = lineGeoJson.geometry.coordinates; + + if (coords.length >= 2) { + // Calculate radius in kilometers + const radiusKm = calculateDistance(coords[0], coords[1]); + + // Create the circle polygon + const circleFeature = createGeoJSONCircle(coords[0], radiusKm, state.line.id); + + // Add radius property for reference + circleFeature.properties.radius = (radiusKm * 1000).toFixed(1); + + // Remove the meta property that was interfering + delete circleFeature.properties.meta; + delete circleFeature.properties.parent; + + // Delete the temporary line first + this.deleteFeature([state.line.id], { silent: true }); + + // Add the circle feature to the draw instance + const circleDrawFeature = this.newFeature(circleFeature); + this.addFeature(circleDrawFeature); + + this.map.fire("draw.create", { + features: [circleDrawFeature.toGeoJSON()] + }); + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + + this.changeMode("simple_select", {}, { silent: true }); + }; + + RadiusMode.toDisplayFeatures = function (state, geojson, display) { + const isActiveLine = geojson.properties.id === state.line.id; + geojson.properties.active = isActiveLine ? "true" : "false"; + + if (!isActiveLine) return display(geojson); + + // Only render the line if it has at least one real coordinate + if (geojson.geometry.coordinates.length < 2) return null; + + geojson.properties.meta = "feature"; + + // Display center vertex as a point feature + display(createVertex( + state.line.id, + geojson.geometry.coordinates[ + state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1 + ], + "" + (state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1), + false + )); + + // Display the line as it is drawn + display(geojson); + + const coords = geojson.geometry.coordinates; + if (coords.length >= 2) { + const distanceKm = calculateDistance(coords[0], coords[1]); + const displayMeasurements = getDisplayMeasurements(distanceKm); + + // Create custom feature for the current pointer position + const currentVertex = { + type: "Feature", + properties: { + meta: "currentPosition", + radiusMetric: displayMeasurements.metric, + radiusStandard: displayMeasurements.standard, + parent: state.line.id + }, + geometry: { + type: "Point", + coordinates: coords[1] + } + }; + display(currentVertex); + + // Create custom feature for radius circle + const center = coords[0]; + const circleFeature = createGeoJSONCircle(center, distanceKm, state.line.id); + display(circleFeature); + } + + return null; + }; + + RadiusMode.onTrash = function (state) { + this.deleteFeature([state.line.id], { silent: true }); + this.changeMode("simple_select"); + }; + + MapboxDraw.modes.draw_radius = RadiusMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js new file mode 100644 index 0000000..73af6d6 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/rectangle-mode/rectangle-mode.js @@ -0,0 +1,124 @@ +// Rectangle drawing mode for Mapbox GL Draw +// Adapted from https://github.com/edgespatial/mapbox-gl-draw-rectangle-mode +(function (MapboxDraw) { + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RectangleMode = { + onSetup: function (opts) { + const rectangle = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "Polygon", + coordinates: [[]] + } + }); + + this.addFeature(rectangle); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.setActionableState({ trash: true }); + + return { + rectangle: rectangle + }; + }, + + onClick: function (state, e) { + // If we have a start point and click on a different point, complete the rectangle + if (state.startPoint && + (state.startPoint[0] !== e.lngLat.lng || state.startPoint[1] !== e.lngLat.lat)) { + this.updateUIClasses({ mouse: "pointer" }); + state.endPoint = [e.lngLat.lng, e.lngLat.lat]; + this.changeMode("simple_select", { featuresId: state.rectangle.id }); + return; + } + + // Set the start point + const startPoint = [e.lngLat.lng, e.lngLat.lat]; + state.startPoint = startPoint; + }, + + onMouseMove: function (state, e) { + // Update rectangle coordinates as the mouse moves + if (state.startPoint) { + const startX = state.startPoint[0]; + const startY = state.startPoint[1]; + const endX = e.lngLat.lng; + const endY = e.lngLat.lat; + + state.rectangle.updateCoordinate("0.0", startX, startY); + state.rectangle.updateCoordinate("0.1", endX, startY); + state.rectangle.updateCoordinate("0.2", endX, endY); + state.rectangle.updateCoordinate("0.3", startX, endY); + state.rectangle.updateCoordinate("0.4", startX, startY); + } + }, + + onKeyUp: function (state, e) { + if (e.keyCode === 27) { // Escape key + return this.changeMode("simple_select"); + } + }, + + onStop: function (state) { + doubleClickZoom.enable(this); + this.updateUIClasses({ mouse: "none" }); + this.activateUIButton(); + + if (this.getFeature(state.rectangle.id) !== undefined) { + // Remove the closing coordinate (duplicate of first) + state.rectangle.removeCoordinate("0.4"); + + if (state.rectangle.isValid()) { + this.map.fire("draw.create", { + features: [state.rectangle.toGeoJSON()] + }); + } else { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select", {}, { silent: true }); + } + } + }, + + toDisplayFeatures: function (state, geojson, display) { + const isActiveRectangle = geojson.properties.id === state.rectangle.id; + geojson.properties.active = isActiveRectangle ? "true" : "false"; + + if (!isActiveRectangle) { + return display(geojson); + } + + // Only display the rectangle if we have started drawing + if (state.startPoint) { + return display(geojson); + } + }, + + onTrash: function (state) { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select"); + } + }; + + MapboxDraw.modes.draw_rectangle = RectangleMode; +})(MapboxDraw); \ No newline at end of file diff --git a/docs/articles/turf_files/turf-operations-1.0.0/lib/turf/turf.min.js b/docs/articles/turf_files/turf-operations-1.0.0/lib/turf/turf.min.js new file mode 100644 index 0000000..635896d --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/lib/turf/turf.min.js @@ -0,0 +1,37 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).turf={})}(this,(function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}function u(t,e,n){return(e=y(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function l(t){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},l(t)}function h(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&p(t,e)}function c(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(c=function(){return!!t})()}function f(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}function g(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function p(t,e){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},p(t,e)}function v(t,e){return n(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,o,s,a=[],u=!0,l=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);u=!0);}catch(t){l=!0,i=t}finally{try{if(!u&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw i}}return a}}(t,e)||_(t,e)||g()}function d(t){return function(t){if(Array.isArray(t))return e(t)}(t)||f(t)||_(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function m(t){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},m(t)}function _(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var x=6371008.8,E={centimeters:100*x,centimetres:100*x,degrees:360/(2*Math.PI),feet:3.28084*x,inches:39.37*x,kilometers:x/1e3,kilometres:x/1e3,meters:x,metres:x,miles:x/1609.344,millimeters:1e3*x,millimetres:1e3*x,nauticalmiles:x/1852,radians:1,yards:1.0936*x},k={acres:247105e-9,centimeters:1e4,centimetres:1e4,feet:10.763910417,hectares:1e-4,inches:1550.003100006,kilometers:1e-6,kilometres:1e-6,meters:1,metres:1,miles:386e-9,nauticalmiles:2.9155334959812285e-7,millimeters:1e6,millimetres:1e6,yards:1.195990046};function b(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={type:"Feature"};return(0===n.id||n.id)&&(r.id=n.id),n.bbox&&(r.bbox=n.bbox),r.properties=e||{},r.geometry=t,r}function w(t,e){switch(t){case"Point":return I(e).geometry;case"LineString":return L(e).geometry;case"Polygon":return S(e).geometry;case"MultiPoint":return O(e).geometry;case"MultiLineString":return T(e).geometry;case"MultiPolygon":return R(e).geometry;default:throw new Error(t+" is invalid")}}function I(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("coordinates is required");if(!Array.isArray(t))throw new Error("coordinates must be an Array");if(t.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!U(t[0])||!U(t[1]))throw new Error("coordinates must contain numbers");return b({type:"Point",coordinates:t},e,n)}function N(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return I(t,e)})),n)}function S(t,e){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=a(t);try{for(i.s();!(n=i.n()).done;){var o=n.value;if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(var s=0;s2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return S(t,e)})),n)}function L(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(t.length<2)throw new Error("coordinates must be an array of two or more positions");return b({type:"LineString",coordinates:t},e,n)}function P(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return L(t,e)})),n)}function C(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={type:"FeatureCollection"};return e.id&&(n.id=e.id),e.bbox&&(n.bbox=e.bbox),n.features=t,n}function T(t,e){return b({type:"MultiLineString",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function O(t,e){return b({type:"MultiPoint",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function R(t,e){return b({type:"MultiPolygon",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function A(t,e){return b({type:"GeometryCollection",geometries:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function D(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e&&!(e>=0))throw new Error("precision must be a positive number");var n=Math.pow(10,e||0);return Math.round(t*n)/n}function F(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t*n}function q(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t/n}function V(t,e){return Y(q(t,e))}function G(t){var e=t%360;return e<0&&(e+=360),e}function B(t){return(t%=360)>180?t-360:t<-180?t+360:t}function Y(t){return 180*(t%(2*Math.PI))/Math.PI}function z(t){return t%360*Math.PI/180}function j(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("length must be a positive number");return F(q(t,e),n)}function X(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"meters",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("area must be a positive number");var r=k[e];if(!r)throw new Error("invalid original units");var i=k[n];if(!i)throw new Error("invalid final units");return t/r*i}function U(t){return!isNaN(t)&&null!==t&&!Array.isArray(t)}function Z(t){return null!==t&&"object"===m(t)&&!Array.isArray(t)}function H(t){if(!t)throw new Error("bbox is required");if(!Array.isArray(t))throw new Error("bbox must be an Array");if(4!==t.length&&6!==t.length)throw new Error("bbox must be an Array of 4 or 6 numbers");t.forEach((function(t){if(!U(t))throw new Error("bbox must only contain numbers")}))}function W(t){if(!t)throw new Error("id is required");if(-1===["string","number"].indexOf(m(t)))throw new Error("id must be a number or a string")}var J=Object.freeze({__proto__:null,areaFactors:k,azimuthToBearing:B,bearingToAzimuth:G,convertArea:X,convertLength:j,degreesToRadians:z,earthRadius:x,factors:E,feature:b,featureCollection:C,geometry:w,geometryCollection:A,isNumber:U,isObject:Z,lengthToDegrees:V,lengthToRadians:q,lineString:L,lineStrings:P,multiLineString:T,multiPoint:O,multiPolygon:R,point:I,points:N,polygon:S,polygons:M,radiansToDegrees:Y,radiansToLength:F,round:D,validateBBox:H,validateId:W});function K(t){if(!t)throw new Error("coord is required");if(!Array.isArray(t)){if("Feature"===t.type&&null!==t.geometry&&"Point"===t.geometry.type)return d(t.geometry.coordinates);if("Point"===t.type)return d(t.coordinates)}if(Array.isArray(t)&&t.length>=2&&!Array.isArray(t[0])&&!Array.isArray(t[1]))return d(t);throw new Error("coord must be GeoJSON Point or an Array of numbers")}function Q(t){if(Array.isArray(t))return t;if("Feature"===t.type){if(null!==t.geometry)return t.geometry.coordinates}else if(t.coordinates)return t.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function $(t){if(t.length>1&&U(t[0])&&U(t[1]))return!0;if(Array.isArray(t[0])&&t[0].length)return $(t[0]);throw new Error("coordinates must only contain numbers")}function tt(t,e,n){if(!e||!n)throw new Error("type and name required");if(!t||t.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.type)}function et(t,e,n){if(!t)throw new Error("No feature passed");if(!n)throw new Error(".featureOf() requires a name");if(!t||"Feature"!==t.type||!t.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!t.geometry||t.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.geometry.type)}function nt(t,e,n){if(!t)throw new Error("No featureCollection passed");if(!n)throw new Error(".collectionOf() requires a name");if(!t||"FeatureCollection"!==t.type)throw new Error("Invalid input to "+n+", FeatureCollection required");var r,i=a(t.features);try{for(i.s();!(r=i.n()).done;){var o=r.value;if(!o||"Feature"!==o.type||!o.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!o.geometry||o.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+o.geometry.type)}}catch(t){i.e(t)}finally{i.f()}}function rt(t){return"Feature"===t.type?t.geometry:t}function it(t,e){return"FeatureCollection"===t.type?"FeatureCollection":"GeometryCollection"===t.type?"GeometryCollection":"Feature"===t.type&&null!==t.geometry?t.geometry.type:t.type}var ot=Object.freeze({__proto__:null,collectionOf:nt,containsNumber:$,featureOf:et,geojsonType:tt,getCoord:K,getCoords:Q,getGeom:rt,getType:it});function st(t,e){if(!0===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final)return function(t,e){var n=st(e,t);return n=(n+180)%360}(t,e);var n=K(t),r=K(e),i=z(n[0]),o=z(r[0]),s=z(n[1]),a=z(r[1]),u=Math.sin(o-i)*Math.cos(a),l=Math.cos(s)*Math.sin(a)-Math.sin(s)*Math.cos(a)*Math.cos(o-i);return Y(Math.atan2(u,l))}function at(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=K(t),o=z(i[0]),s=z(i[1]),a=z(n),u=q(e,r.units),l=Math.asin(Math.sin(s)*Math.cos(u)+Math.cos(s)*Math.sin(u)*Math.cos(a));return I([Y(o+Math.atan2(Math.sin(a)*Math.sin(u)*Math.cos(s),Math.cos(u)-Math.sin(s)*Math.sin(l))),Y(l)],r.properties)}function ut(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e),o=z(i[1]-r[1]),s=z(i[0]-r[0]),a=z(r[1]),u=z(i[1]),l=Math.pow(Math.sin(o/2),2)+Math.pow(Math.sin(s/2),2)*Math.cos(a)*Math.cos(u);return F(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)),n.units)}function lt(t,e){var n;return(n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final?ht(K(e),K(t)):ht(K(t),K(e)))>180?-(360-n):n}function ht(t,e){var n=z(t[1]),r=z(e[1]),i=z(e[0]-t[0]);i>Math.PI&&(i-=2*Math.PI),i<-Math.PI&&(i+=2*Math.PI);var o=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(n/2+Math.PI/4));return(Y(Math.atan2(i,o))+360)%360}function ct(t,e,n){if(null!==t)for(var r,i,o,s,a,u,l,h,c=0,f=0,g=t.type,p="FeatureCollection"===g,v="Feature"===g,d=p?t.features.length:1,y=0;ya||f>u||g>l)return s=o,a=n,u=f,l=g,void(i=0);var p=L([s,o],t.properties);if(!1===e(p,n,r,g,i))return!1;i++,s=o}))&&void 0}}}))}function bt(t,e,n){var r=n,i=!1;return kt(t,(function(t,o,s,a,u){r=!1===i&&void 0===n?t:e(r,t,o,s,a,u),i=!0})),r}function wt(t,e){if(!t)throw new Error("geojson is required");xt(t,(function(t,n,r){if(null!==t.geometry){var i=t.geometry.type,o=t.geometry.coordinates;switch(i){case"LineString":if(!1===e(t,n,r,0,0))return!1;break;case"Polygon":for(var s=0;s0){e+=Math.abs(Ot(t[0]));for(var n=1;n=e?(r+2)%e:r+2],a=i[0]*Tt,u=o[1]*Tt;n+=(s[0]*Tt-a)*Math.sin(u),r++}return n*Ct}function Rt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=t.bbox&&!0!==e.recompute)return t.bbox;var n=[1/0,1/0,-1/0,-1/0];return ct(t,(function(t){n[0]>t[0]&&(n[0]=t[0]),n[1]>t[1]&&(n[1]=t[1]),n[2]e[2]&&(n|=2),t[1]e[3]&&(n|=8),n}function qt(t,e){var n,r=[],i=a(t);try{for(i.s();!(n=i.n()).done;){var o=At(n.value,e);o.length>0&&(o[0][0]===o[o.length-1][0]&&o[0][1]===o[o.length-1][1]||o.push(o[0]),o.length>=4&&r.push(o))}}catch(t){i.e(t)}finally{i.f()}return r}function Vt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Number(t[0]),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]);if(6===t.length)throw new Error("@turf/bbox-polygon does not support BBox with 6 positions");var s=[n,r];return S([[s,[i,r],[i,o],[n,o],s]],e.properties,{bbox:t,id:e.id})}var Gt=function(){return s((function t(e){i(this,t),this.points=e.points||[],this.duration=e.duration||1e4,this.sharpness=e.sharpness||.85,this.centers=[],this.controls=[],this.stepLength=e.stepLength||60,this.length=this.points.length,this.delay=0;for(var n=0;nt&&(e.push(r),n=i)}return e}},{key:"vector",value:function(t){var e=this.pos(t+10),n=this.pos(t-10);return{angle:180*Math.atan2(e.y-n.y,e.x-n.x)/3.14,speed:Math.sqrt((n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y)+(n.z-e.z)*(n.z-e.z))}}},{key:"pos",value:function(t){var e=t-this.delay;e<0&&(e=0),e>this.duration&&(e=this.duration-1);var n=e/this.duration;if(n>=1)return this.points[this.length-1];var r=Math.floor((this.points.length-1)*n);return function(t,e,n,r,i){var o=function(t){var e=t*t,n=e*t;return[n,3*e*(1-t),3*t*(1-t)*(1-t),(1-t)*(1-t)*(1-t)]}(t),s={x:i.x*o[0]+r.x*o[1]+n.x*o[2]+e.x*o[3],y:i.y*o[0]+r.y*o[1]+n.y*o[2]+e.y*o[3],z:i.z*o[0]+r.z*o[1]+n.z*o[2]+e.z*o[3]};return s}((this.length-1)*n-r,this.points[r],this.controls[r][1],this.controls[r+1][0],this.points[r+1])}}])}();function Bt(t){for(var e,n,r=Q(t),i=0,o=1;o0}function Yt(t,e){for(var n=0,r=0,i=0,o=0,s=0,a=0,u=0,l=0,h=null,c=null,f=t[0],g=t[1],p=e.length;n0&&l>0)a=l,s=(h=c)[0]-f;else{if(u=c[0]-t[0],l>0&&a<=0){if((o=s*l-u*a)>0)i+=1;else if(0===o)return 0}else if(a>0&&l<=0){if((o=s*l-u*a)<0)i+=1;else if(0===o)return 0}else if(0===l&&a<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&l<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&0===l){if(u<=0&&s>=0)return 0;if(s<=0&&u>=0)return 0}h=c,a=l,s=u}}return i%2!=0}function zt(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("point is required");if(!e)throw new Error("polygon is required");var r=K(t),i=rt(e),o=i.type,s=e.bbox,a=i.coordinates;if(s&&!1===function(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}(r,s))return!1;"Polygon"===o&&(a=[a]);for(var u=!1,l=0;l2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=Q(e),o=0;oi)return!1}else if(0!==g)return!1;return Math.abs(c)===Math.abs(f)&&0===Math.abs(c)?!r&&(n[0]===t[0]&&n[1]===t[1]):r?"start"===r?Math.abs(c)>=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o0?u<=s&&s=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o<=l:l<=o&&o<=a:f>0?u<=s&&s<=h:h<=s&&s<=u}function Ut(t,e){if("Feature"===t.type&&null===t.geometry)return!1;if("Feature"===e.type&&null===e.geometry)return!1;if(!Zt(Rt(t),Rt(e)))return!1;var n,r=a(rt(e).coordinates);try{for(r.s();!(n=r.n()).done;){var i,o=a(n.value);try{for(o.s();!(i=o.n()).done;){if(!zt(i.value,t))return!1}}catch(t){o.e(t)}finally{o.f()}}}catch(t){r.e(t)}finally{r.f()}return!0}function Zt(t,e){return!(t[0]>e[0])&&(!(t[2]e[1])&&!(t[3]0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Kt;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function Kt(t,e){return te?1:0}function Qt(t,e){return t.p.x>e.p.x?1:t.p.xe.p.y?1:-1:1}function $t(t,e){return t.rightSweepEvent.p.x>e.rightSweepEvent.p.x?1:t.rightSweepEvent.p.x0?(h.isLeftEndpoint=!0,l.isLeftEndpoint=!1):(l.isLeftEndpoint=!0,h.isLeftEndpoint=!1),e.push(l),e.push(h),s=a,re+=1}}ee+=1}var oe=s((function t(e){i(this,t),this.leftSweepEvent=e,this.rightSweepEvent=e.otherEvent}));function se(t,e){if(null===t||null===e)return!1;if(t.leftSweepEvent.ringId===e.leftSweepEvent.ringId&&(t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.rightSweepEvent)||t.leftSweepEvent.isSamePoint(e.leftSweepEvent)||t.leftSweepEvent.isSamePoint(e.rightSweepEvent)))return!1;var n=t.leftSweepEvent.p.x,r=t.leftSweepEvent.p.y,i=t.rightSweepEvent.p.x,o=t.rightSweepEvent.p.y,s=e.leftSweepEvent.p.x,a=e.leftSweepEvent.p.y,u=e.rightSweepEvent.p.x,l=e.rightSweepEvent.p.y,h=(l-a)*(i-n)-(u-s)*(o-r),c=(u-s)*(r-a)-(l-a)*(n-s),f=(i-n)*(r-a)-(o-r)*(n-s);if(0===h)return!1;var g=c/h,p=f/h;return g>=0&&g<=1&&p>=0&&p<=1&&[n+g*(i-n),r+g*(o-r)]}var ae=function(t,e){var n=new Jt([],Qt);return function(t,e){if("FeatureCollection"===t.type)for(var n=t.features,r=0;r2&&void 0!==arguments[2]?arguments[2]:{},r=n.removeDuplicates,i=void 0===r||r,o=n.ignoreSelfIntersections,s=void 0===o||o,a=[];"FeatureCollection"===t.type?a=a.concat(t.features):"Feature"===t.type?a.push(t):"LineString"!==t.type&&"Polygon"!==t.type&&"MultiLineString"!==t.type&&"MultiPolygon"!==t.type||a.push(b(t)),"FeatureCollection"===e.type?a=a.concat(e.features):"Feature"===e.type?a.push(e):"LineString"!==e.type&&"Polygon"!==e.type&&"MultiLineString"!==e.type&&"MultiPolygon"!==e.type||a.push(b(e));var u=ae(C(a),s),l=[];if(i){var h={};u.forEach((function(t){var e=t.join(",");h[e]||(h[e]=!0,l.push(t))}))}else l=u;return C(l.map((function(t){return I(t)})))}function le(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t);switch(e.properties||"Feature"!==t.type||(e.properties=t.properties),n.type){case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{};return he(r,i)}(n,e);case"MultiPolygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{},o=[];return r.forEach((function(t){o.push(he(t,i))})),C(o)}(n,e);default:throw new Error("invalid poly")}}function he(t,e){return t.length>1?T(t,e):L(t[0],e)}function ce(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;switch(i){case"MultiPoint":switch(o){case"LineString":return fe(n,r);case"Polygon":return pe(n,r);default:throw new Error("feature2 "+o+" geometry not supported")}case"LineString":switch(o){case"MultiPoint":return fe(r,n);case"LineString":return function(t,e){if(ue(t,e).features.length>0)for(var n=0;n0}function pe(t,e){for(var n=!1,r=!1,i=t.coordinates.length,o=0;o=Math.abs(a)?s>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:a>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1]:Math.abs(s)>=Math.abs(a)?s>0?t[0]0?t[1]2&&void 0!==arguments[2]?arguments[2]:{ignoreSelfIntersections:!0}).ignoreSelfIntersections,r=void 0===n||n,i=!0;return xt(t,(function(t){xt(e,(function(e){if(!1===i)return!1;i=function(t,e,n){switch(t.type){case"Point":switch(e.type){case"Point":return r=t.coordinates,i=e.coordinates,!(r[0]===i[0]&&r[1]===i[1]);case"LineString":return!ye(e,t);case"Polygon":return!zt(t,e)}break;case"LineString":switch(e.type){case"Point":return!ye(t,e);case"LineString":return!function(t,e,n){var r=ue(t,e,{ignoreSelfIntersections:n});if(r.features.length>0)return!0;return!1}(t,e,n);case"Polygon":return!me(e,t,n)}break;case"Polygon":switch(e.type){case"Point":return!zt(e,t);case"LineString":return!me(t,e,n);case"Polygon":return!function(t,e,n){var r,i=a(t.coordinates[0]);try{for(i.s();!(r=i.n()).done;){if(zt(r.value,e))return!0}}catch(t){i.e(t)}finally{i.f()}var o,s=a(e.coordinates[0]);try{for(s.s();!(o=s.n()).done;){if(zt(o.value,t))return!0}}catch(t){s.e(t)}finally{s.f()}var u=ue(le(t),le(e),{ignoreSelfIntersections:n});if(u.features.length>0)return!0;return!1}(e,t,n)}}var r,i;return!1}(t.geometry,e.geometry,r)}))})),i}function ye(t,e){for(var n=0;n0}function _e(t,e,n){var r=n[0]-t[0],i=n[1]-t[1],o=e[0]-t[0],s=e[1]-t[1];return 0==r*s-i*o&&(Math.abs(o)>=Math.abs(s)?o>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:s>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1])}var xe=Object.defineProperty,Ee=function(t,e){return xe(t,"name",{value:e,configurable:!0})},ke=function(){return s((function t(e){var n,r,o;i(this,t),this.direction=!1,this.compareProperties=!0,this.precision=Math.pow(10,-(null!=(n=null==e?void 0:e.precision)?n:17)),this.direction=null!=(r=null==e?void 0:e.direction)&&r,this.compareProperties=null==(o=null==e?void 0:e.compareProperties)||o}),[{key:"compare",value:function(t,e){var n=this;if(t.type!==e.type)return!1;if(!we(t,e))return!1;switch(t.type){case"Point":return this.compareCoord(t.coordinates,e.coordinates);case"LineString":return this.compareLine(t.coordinates,e.coordinates);case"Polygon":return this.comparePolygon(t,e);case"GeometryCollection":return this.compareGeometryCollection(t,e);case"Feature":return this.compareFeature(t,e);case"FeatureCollection":return this.compareFeatureCollection(t,e);default:if(t.type.startsWith("Multi")){var r=Ie(t),i=Ie(e);return r.every((function(t){return i.some((function(e){return n.compare(t,e)}))}))}}return!1}},{key:"compareCoord",value:function(t,e){var n=this;return t.length===e.length&&t.every((function(t,r){return Math.abs(t-e[r])2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!we(t,e))return!1;var i=t,o=e;if(r&&!this.compareCoord(i[0],o[0])){var s=this.fixStartIndex(o,i);if(!s)return!1;o=s}var a=this.compareCoord(i[n],o[n]);return this.direction||a?this.comparePath(i,o):!!this.compareCoord(i[n],o[o.length-(1+n)])&&this.comparePath(i.slice().reverse(),o)}},{key:"fixStartIndex",value:function(t,e){for(var n,r=-1,i=0;i=0&&(n=[].concat(t.slice(r,t.length),t.slice(1,r+1))),n}},{key:"comparePath",value:function(t,e){var n=this;return t.every((function(t,r){return n.compareCoord(t,e[r])}))}},{key:"comparePolygon",value:function(t,e){var n=this;if(this.compareLine(t.coordinates[0],e.coordinates[0],1,!0)){var r=t.coordinates.slice(1,t.coordinates.length),i=e.coordinates.slice(1,e.coordinates.length);return r.every((function(t){return i.some((function(e){return n.compareLine(t,e,1,!0)}))}))}return!1}},{key:"compareGeometryCollection",value:function(t,e){var n=this;return we(t.geometries,e.geometries)&&this.compareBBox(t,e)&&t.geometries.every((function(t,r){return n.compare(t,e.geometries[r])}))}},{key:"compareFeature",value:function(t,e){return t.id===e.id&&(!this.compareProperties||Se(t.properties,e.properties))&&this.compareBBox(t,e)&&this.compare(t.geometry,e.geometry)}},{key:"compareFeatureCollection",value:function(t,e){var n=this;return we(t.features,e.features)&&this.compareBBox(t,e)&&t.features.every((function(t,r){return n.compare(t,e.features[r])}))}},{key:"compareBBox",value:function(t,e){return Boolean(!t.bbox&&!e.bbox)||!(!t.bbox||!e.bbox)&&this.compareCoord(t.bbox,e.bbox)}}])}();Ee(ke,"GeojsonEquality");var be=ke;function we(t,e){return t.coordinates?t.coordinates.length===e.coordinates.length:t.length===e.length}function Ie(t){return t.coordinates.map((function(e){return{type:t.type.replace("Multi",""),coordinates:e}}))}function Ne(t,e,n){return new be(n).compare(t,e)}function Se(t,e){if(null===t&&null===e)return!0;if(null===t||null===e)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(var i=0,o=n;i1&&void 0!==arguments[1]?arguments[1]:{},n="object"===m(e)?e.mutate:e;if(!t)throw new Error("geojson is required");var r=it(t),i=[];switch(r){case"LineString":i=Pe(t,r);break;case"MultiLineString":case"Polygon":Q(t).forEach((function(t){i.push(Pe(t,r))}));break;case"MultiPolygon":Q(t).forEach((function(t){var e=[];t.forEach((function(t){e.push(Pe(t,r))})),i.push(e)}));break;case"Point":return t;case"MultiPoint":var o={};Q(t).forEach((function(t){var e=t.join("-");Object.prototype.hasOwnProperty.call(o,e)||(i.push(t),o[e]=!0)}));break;default:throw new Error(r+" geometry not supported")}return t.coordinates?!0===n?(t.coordinates=i,t):{type:r,coordinates:i}:!0===n?(t.geometry.coordinates=i,t):b({type:r,coordinates:i},t.properties,{bbox:t.bbox,id:t.id})}function Pe(t,e){var n=Q(t);if(2===n.length&&!Ce(n[0],n[1]))return n;var r=[],i=n.length-1,o=r.length;r.push(n[0]);for(var s=1;s2&&Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1))}if(r.push(n[n.length-1]),o=r.length,("Polygon"===e||"MultiPolygon"===e)&&Ce(n[0],n[n.length-1])&&o<4)throw new Error("invalid polygon");return"LineString"===e&&o<3||Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1),r}function Ce(t,e){return t[0]===e[0]&&t[1]===e[1]}function Te(t,e,n){var r=n[0],i=n[1],o=t[0],s=t[1],a=e[0],u=e[1],l=a-o,h=u-s;return 0===(r-o)*h-(i-s)*l&&(Math.abs(l)>=Math.abs(h)?l>0?o<=r&&r<=a:a<=r&&r<=o:h>0?s<=i&&i<=u:u<=i&&i<=s)}function Oe(t,e){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).ignoreSelfIntersections,r=void 0===n||n,i=!1;return xt(t,(function(t){xt(e,(function(e){if(!0===i)return!0;i=!de(t.geometry,e.geometry,{ignoreSelfIntersections:r})}))})),i}function Re(t,e,n,r,i){Ae(t,e,n||0,r||t.length-1,i||Fe)}function Ae(t,e,n,r,i){for(;r>n;){if(r-n>600){var o=r-n+1,s=e-n+1,a=Math.log(o),u=.5*Math.exp(2*a/3),l=.5*Math.sqrt(a*u*(o-u)/o)*(s-o/2<0?-1:1);Ae(t,e,Math.max(n,Math.floor(e-s*u/o+l)),Math.min(r,Math.floor(e+(o-s)*u/o+l)),i)}var h=t[e],c=n,f=r;for(De(t,n,e),i(t[r],h)>0&&De(t,n,r);c0;)f--}0===i(t[n],h)?De(t,n,f):De(t,++f,r),f<=e&&(n=f+1),e<=f&&(r=f-1)}}function De(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function Fe(t,e){return te?1:0}var qe=function(){return s((function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:9;i(this,t),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}),[{key:"all",value:function(){return this._all(this.data,[])}},{key:"search",value:function(t){var e=this.data,n=[];if(!He(t,e))return n;for(var r=this.toBBox,i=[];e;){for(var o=0;o=0&&i[e].children.length>this._maxEntries;)this._split(i,e),e--;this._adjustParentBBoxes(r,i,e)}},{key:"_split",value:function(t,e){var n=t[e],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=We(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,Ge(n,this.toBBox),Ge(s,this.toBBox),e?t[e-1].children.push(s):this._splitRoot(n,s)}},{key:"_splitRoot",value:function(t,e){this.data=We([t,e]),this.data.height=t.height+1,this.data.leaf=!1,Ge(this.data,this.toBBox)}},{key:"_chooseSplitIndex",value:function(t,e,n){for(var r,i,o,s,a,u,l,h=1/0,c=1/0,f=e;f<=n-e;f++){var g=Be(t,0,f,this.toBBox),p=Be(t,f,n,this.toBBox),v=(i=g,o=p,s=void 0,a=void 0,u=void 0,l=void 0,s=Math.max(i.minX,o.minX),a=Math.max(i.minY,o.minY),u=Math.min(i.maxX,o.maxX),l=Math.min(i.maxY,o.maxY),Math.max(0,u-s)*Math.max(0,l-a)),d=Xe(g)+Xe(p);v=e;h--){var c=t.children[h];Ye(s,t.leaf?i(c):c),a+=Ue(s)}return a}},{key:"_adjustParentBBoxes",value:function(t,e,n){for(var r=n;r>=0;r--)Ye(e[r],t)}},{key:"_condense",value:function(t){for(var e,n=t.length-1;n>=0;n--)0===t[n].children.length?n>0?(e=t[n-1].children).splice(e.indexOf(t[n]),1):this.clear():Ge(t[n],this.toBBox)}}])}();function Ve(t,e,n){if(!n)return e.indexOf(t);for(var r=0;r=t.minX&&e.maxY>=t.minY}function We(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Je(t,e,n,r,i){for(var o=[e,n];o.length;)if(!((n=o.pop())-(e=o.pop())<=r)){var s=e+Math.ceil((n-e)/r/2)*r;Re(t,s,e,n,i),o.push(e,s,s,n)}}var Ke=Object.freeze({__proto__:null,default:qe});function Qe(t){var e=new qe(t);return e.insert=function(t){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.insert.call(this,t)},e.load=function(t){var e=[];return Array.isArray(t)?t.forEach((function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})):vt(t,(function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})),qe.prototype.load.call(this,e)},e.remove=function(t,e){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.remove.call(this,t,e)},e.clear=function(){return qe.prototype.clear.call(this)},e.search=function(t){return C(qe.prototype.search.call(this,this.toBBox(t)))},e.collides=function(t){return qe.prototype.collides.call(this,this.toBBox(t))},e.all=function(){return C(qe.prototype.all.call(this))},e.toJSON=function(){return qe.prototype.toJSON.call(this)},e.fromJSON=function(t){return qe.prototype.fromJSON.call(this,t)},e.toBBox=function(t){var e;if(t.bbox)e=t.bbox;else if(Array.isArray(t)&&4===t.length)e=t;else if(Array.isArray(t)&&6===t.length)e=[t[0],t[1],t[3],t[4]];else if("Feature"===t.type)e=Rt(t);else{if("FeatureCollection"!==t.type)throw new Error("invalid geojson");e=Rt(t)}return{minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}},e}function $e(t){if(!t)throw new Error("geojson is required");var e=[];return xt(t,(function(t){!function(t,e){var n=[],r=t.geometry;if(null!==r){switch(r.type){case"Polygon":n=Q(r);break;case"LineString":n=[Q(r)]}n.forEach((function(n){var r=function(t,e){var n=[];return t.reduce((function(t,r){var i=L([t,r],e);return i.bbox=function(t,e){var n=t[0],r=t[1],i=e[0],o=e[1],s=ni?n:i,l=r>o?r:o;return[s,a,u,l]}(t,r),n.push(i),r})),n}(n,t.properties);r.forEach((function(t){t.id=e.length,e.push(t)}))}))}}(t,e)})),C(e)}var tn,en,nn=Object.defineProperty,rn=Object.defineProperties,on=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertySymbols,an=Object.prototype.hasOwnProperty,un=Object.prototype.propertyIsEnumerable,ln=function(t,e,n){return e in t?nn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},hn=function(t,e){for(var n in e||(e={}))an.call(e,n)&&ln(t,n,e[n]);if(sn){var r,i=a(sn(e));try{for(i.s();!(r=i.n()).done;){n=r.value;un.call(e,n)&&ln(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},cn=function(t,e){return rn(t,on(e))};function fn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t||!e)throw new Error("lines and pt are required arguments");var r=K(e),i=I([1/0,1/0],{dist:1/0,index:-1,multiFeatureIndex:-1,location:-1}),o=0;return xt(t,(function(t,s,a){for(var u=Q(t),l=0;lR||pn(p,f)>R?ut(dn(f),dn(g))<=ut(dn(f),dn(p))?[dn(g),!0,!1]:[dn(p),!1,!0]:[dn(f),!1,!1]}function mn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function _n(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var n=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,r.get?r:{enumerable:!0,get:function(){return t[e]}})})),n}var xn=(en||(en=1,tn=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==m(e)&&"object"==m(n)){if(e.constructor!==n.constructor)return!1;var r,i,o;if(Array.isArray(e)){if((r=e.length)!=n.length)return!1;for(i=r;0!=i--;)if(!t(e[i],n[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((r=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(i=r;0!=i--;)if(!Object.prototype.hasOwnProperty.call(n,o[i]))return!1;for(i=r;0!=i--;){var s=o[i];if(!t(e[s],n[s]))return!1}return!0}return e!=e&&n!=n}),tn),En=mn(xn);function kn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r,i=n.tolerance||0,o=[],s=Qe(),a=$e(t);s.load(a);var u=[];return kt(e,(function(t){var e=!1;t&&(vt(s.search(t),(function(n){if(!1===e){var o=Q(t).sort(),s=Q(n).sort();if(En(o,s))e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(o[0],n)&&jt(o[1],n):fn(n,o[0]).properties.dist<=i&&fn(n,o[1]).properties.dist<=i)e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(s[0],t)&&jt(s[1],t):fn(t,s[0]).properties.dist<=i&&fn(t,s[1]).properties.dist<=i)if(r){var a=bn(r,n);a?r=a:u.push(n)}else r=n}})),!1===e&&r&&(o.push(r),u.length&&(o=o.concat(u),u=[]),r=void 0))})),r&&o.push(r),C(o)}function bn(t,e){var n=Q(e),r=Q(t),i=r[0],o=r[r.length-1],s=t.geometry.coordinates;if(En(n[0],i))s.unshift(n[1]);else if(En(n[0],o))s.push(n[1]);else if(En(n[1],i))s.unshift(n[0]);else{if(!En(n[1],o))return;s.push(n[0])}return t}function wn(t,e){var n=G(lt(t[0],t[1])),r=G(lt(e[0],e[1]));return n===r||(r-n)%180==0}function In(t,e){if(t.geometry&&t.geometry.type)return t.geometry.type;if(t.type)return t.type;throw new Error("Invalid GeoJSON object for "+e)}function Nn(t,e){return!!Sn(e.coordinates[0],t.coordinates)||!!Sn(e.coordinates[e.coordinates.length-1],t.coordinates)}function Sn(t,e){return t[0]===e[0]&&t[1]===e[1]}function Mn(t){return t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]}function Ln(t){for(var e=0;ee[0])&&(!(t[2]e[1])&&!(t[3]1&&void 0!==arguments[1]?arguments[1]:{},n=Rt(t);return I([(n[0]+n[2])/2,(n[1]+n[3])/2],e.properties,e)}var Dn,Fn={exports:{}};var qn=(Dn||(Dn=1,function(t,e){t.exports=function(){function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}var y=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getEndCapStyle",value:function(){return this._endCapStyle}},{key:"isSingleSided",value:function(){return this._isSingleSided}},{key:"setQuadrantSegments",value:function(t){this._quadrantSegments=t,0===this._quadrantSegments&&(this._joinStyle=e.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=e.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),t<=0&&(this._quadrantSegments=1),this._joinStyle!==e.JOIN_ROUND&&(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS)}},{key:"getJoinStyle",value:function(){return this._joinStyle}},{key:"setJoinStyle",value:function(t){this._joinStyle=t}},{key:"setSimplifyFactor",value:function(t){this._simplifyFactor=t<0?0:t}},{key:"getSimplifyFactor",value:function(){return this._simplifyFactor}},{key:"getQuadrantSegments",value:function(){return this._quadrantSegments}},{key:"setEndCapStyle",value:function(t){this._endCapStyle=t}},{key:"getMitreLimit",value:function(){return this._mitreLimit}},{key:"setMitreLimit",value:function(t){this._mitreLimit=t}},{key:"setSingleSided",value:function(t){this._isSingleSided=t}}],[{key:"constructor_",value:function(){if(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=e.CAP_ROUND,this._joinStyle=e.JOIN_ROUND,this._mitreLimit=e.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=e.DEFAULT_SIMPLIFY_FACTOR,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.setQuadrantSegments(t)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.setQuadrantSegments(n),this.setEndCapStyle(r)}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];this.setQuadrantSegments(i),this.setEndCapStyle(o),this.setJoinStyle(s),this.setMitreLimit(a)}}},{key:"bufferDistanceError",value:function(t){var e=Math.PI/2/t;return 1-Math.cos(e/2)}}]),e}();y.CAP_ROUND=1,y.CAP_FLAT=2,y.CAP_SQUARE=3,y.JOIN_ROUND=1,y.JOIN_MITRE=2,y.JOIN_BEVEL=3,y.DEFAULT_QUADRANT_SEGMENTS=8,y.DEFAULT_MITRE_LIMIT=5,y.DEFAULT_SIMPLIFY_FACTOR=.01;var _=function(e){r(o,e);var i=c(o);function o(e){var n;return t(this,o),(n=i.call(this,e)).name=Object.keys({Exception:o})[0],n}return n(o,[{key:"toString",value:function(){return this.message}}]),o}(u(Error)),x=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({IllegalArgumentException:i})[0],r}return i}(_),E=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}();function k(){}function b(){}function w(){}var I,N,S,M,L,P,C,T,O=function(){function e(){t(this,e)}return n(e,null,[{key:"equalsWithTolerance",value:function(t,e,n){return Math.abs(t-e)<=n}}]),e}(),R=function(){function e(n,r){t(this,e),this.low=r||0,this.high=n||0}return n(e,null,[{key:"toBinaryString",value:function(t){var e,n="";for(e=2147483648;e>0;e>>>=1)n+=(t.high&e)===e?"1":"0";for(e=2147483648;e>0;e>>>=1)n+=(t.low&e)===e?"1":"0";return n}}]),e}();function A(){}function D(){}A.NaN=NaN,A.isNaN=function(t){return Number.isNaN(t)},A.isInfinite=function(t){return!Number.isFinite(t)},A.MAX_VALUE=Number.MAX_VALUE,A.POSITIVE_INFINITY=Number.POSITIVE_INFINITY,A.NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,"function"==typeof Float64Array&&"function"==typeof Int32Array?(P=2146435072,C=new Float64Array(1),T=new Int32Array(C.buffer),A.doubleToLongBits=function(t){C[0]=t;var e=0|T[0],n=0|T[1];return(n&P)===P&&0!=(1048575&n)&&0!==e&&(e=0,n=2146959360),new R(n,e)},A.longBitsToDouble=function(t){return T[0]=t.low,T[1]=t.high,C[0]}):(I=1023,N=Math.log2,S=Math.floor,M=Math.pow,L=function(){for(var t=53;t>0;t--){var e=M(2,t)-1;if(S(N(e))+1===t)return e}return 0}(),A.doubleToLongBits=function(t){var e,n,r,i,o,s,a,u,l;if(t<0||1/t===Number.NEGATIVE_INFINITY?(s=1<<31,t=-t):s=0,0===t)return new R(u=s,l=0);if(t===1/0)return new R(u=2146435072|s,l=0);if(t!=t)return new R(u=2146959360,l=0);if(i=0,l=0,(e=S(t))>1)if(e<=L)(i=S(N(e)))<=20?(l=0,u=e<<20-i&1048575):(l=e%(n=M(2,r=i-20))<<32-r,u=e/n&1048575);else for(r=e,l=0;0!==(r=S(n=r/2));)i++,l>>>=1,l|=(1&u)<<31,u>>>=1,n!==r&&(u|=524288);if(a=i+I,o=0===e,e=t-e,i<52&&0!==e)for(r=0;;){if((n=2*e)>=1?(e=n-1,o?(a--,o=!1):(r<<=1,r|=1,i++)):(e=n,o?0==--a&&(i++,o=!1):(r<<=1,i++)),20===i)u|=r,r=0;else if(52===i){l|=r;break}if(1===n){i<20?u|=r<<20-i:i<52&&(l|=r<<52-i);break}}return u|=a<<20,new R(u|=s,l)},A.longBitsToDouble=function(t){var e,n,r,i,o=t.high,s=t.low,a=o&1<<31?-1:1;for(r=((2146435072&o)>>20)-I,i=0,n=1<<19,e=1;e<=20;e++)o&n&&(i+=M(2,-e)),n>>>=1;for(n=1<<31,e=21;e<=52;e++)s&n&&(i+=M(2,-e)),n>>>=1;if(-1023===r){if(0===i)return 0*a;r=-1022}else{if(1024===r)return 0===i?a/0:NaN;i+=1}return a*i*M(2,r)});var F=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({RuntimeException:i})[0],r}return i}(_),q=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){if(0===arguments.length)F.constructor_.call(this);else if(1===arguments.length){var t=arguments[0];F.constructor_.call(this,t)}}}]),o}(F),V=function(){function e(){t(this,e)}return n(e,null,[{key:"shouldNeverReachHere",value:function(){if(0===arguments.length)e.shouldNeverReachHere(null);else if(1===arguments.length){var t=arguments[0];throw new q("Should never reach here"+(null!==t?": "+t:""))}}},{key:"isTrue",value:function(){if(1===arguments.length){var t=arguments[0];e.isTrue(t,null)}else if(2===arguments.length){var n=arguments[1];if(!arguments[0])throw null===n?new q:new q(n)}}},{key:"equals",value:function(){if(2===arguments.length){var t=arguments[0],n=arguments[1];e.equals(t,n,null)}else if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2];if(!i.equals(r))throw new q("Expected "+r+" but encountered "+i+(null!==o?": "+o:""))}}}]),e}(),G=new ArrayBuffer(8),B=new Float64Array(G),Y=new Int32Array(G),z=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getM",value:function(){return A.NaN}},{key:"setOrdinate",value:function(t,n){switch(t){case e.X:this.x=n;break;case e.Y:this.y=n;break;case e.Z:this.setZ(n);break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"equals2D",value:function(){if(1===arguments.length){var t=arguments[0];return this.x===t.x&&this.y===t.y}if(2===arguments.length){var e=arguments[0],n=arguments[1];return!!O.equalsWithTolerance(this.x,e.x,n)&&!!O.equalsWithTolerance(this.y,e.y,n)}}},{key:"setM",value:function(t){throw new x("Invalid ordinate index: "+e.M)}},{key:"getZ",value:function(){return this.z}},{key:"getOrdinate",value:function(t){switch(t){case e.X:return this.x;case e.Y:return this.y;case e.Z:return this.getZ()}throw new x("Invalid ordinate index: "+t)}},{key:"equals3D",value:function(t){return this.x===t.x&&this.y===t.y&&(this.getZ()===t.getZ()||A.isNaN(this.getZ())&&A.isNaN(t.getZ()))}},{key:"equals",value:function(t){return t instanceof e&&this.equals2D(t)}},{key:"equalInZ",value:function(t,e){return O.equalsWithTolerance(this.getZ(),t.getZ(),e)}},{key:"setX",value:function(t){this.x=t}},{key:"compareTo",value:function(t){var e=t;return this.xe.x?1:this.ye.y?1:0}},{key:"getX",value:function(){return this.x}},{key:"setZ",value:function(t){this.z=t}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return V.shouldNeverReachHere("this shouldn't happen because this class is Cloneable"),null;throw t}}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+")"}},{key:"distance3D",value:function(t){var e=this.x-t.x,n=this.y-t.y,r=this.getZ()-t.getZ();return Math.sqrt(e*e+n*n+r*r)}},{key:"getY",value:function(){return this.y}},{key:"setY",value:function(t){this.y=t}},{key:"distance",value:function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*t+e.hashCode(this.x))+e.hashCode(this.y)}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}},{key:"interfaces_",get:function(){return[k,b,w]}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.z=null,0===arguments.length)e.constructor_.call(this,0,0);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.x,t.y,t.getZ())}else if(2===arguments.length){var n=arguments[0],r=arguments[1];e.constructor_.call(this,n,r,e.NULL_ORDINATE)}else if(3===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2];this.x=i,this.y=o,this.z=s}}},{key:"hashCode",value:function(t){return B[0]=t,Y[0]^Y[1]}}]),e}(),j=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compare",value:function(t,n){var r=e.compare(t.x,n.x);if(0!==r)return r;var i=e.compare(t.y,n.y);return 0!==i?i:this._dimensionsToTest<=2?0:e.compare(t.getZ(),n.getZ())}},{key:"interfaces_",get:function(){return[D]}}],[{key:"constructor_",value:function(){if(this._dimensionsToTest=2,0===arguments.length)e.constructor_.call(this,2);else if(1===arguments.length){var t=arguments[0];if(2!==t&&3!==t)throw new x("only 2 or 3 dimensions may be specified");this._dimensionsToTest=t}}},{key:"compare",value:function(t,e){return te?1:A.isNaN(t)?A.isNaN(e)?0:-1:A.isNaN(e)?1:0}}]),e}();z.DimensionalComparator=j,z.NULL_ORDINATE=A.NaN,z.X=0,z.Y=1,z.Z=2,z.M=3;var X=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getArea",value:function(){return this.getWidth()*this.getHeight()}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.isNull()?n.isNull():this._maxx===n.getMaxX()&&this._maxy===n.getMaxY()&&this._minx===n.getMinX()&&this._miny===n.getMinY()}},{key:"intersection",value:function(t){if(this.isNull()||t.isNull()||!this.intersects(t))return new e;var n=this._minx>t._minx?this._minx:t._minx,r=this._miny>t._miny?this._miny:t._miny;return new e(n,this._maxx=this._minx&&n.getMaxX()<=this._maxx&&n.getMinY()>=this._miny&&n.getMaxY()<=this._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return!this.isNull()&&r>=this._minx&&r<=this._maxx&&i>=this._miny&&i<=this._maxy}}},{key:"intersects",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return!this.isNull()&&!t.isNull()&&!(t._minx>this._maxx||t._maxxthis._maxy||t._maxythis._maxx||(r.x>i.x?r.x:i.x)this._maxy||(r.y>i.y?r.y:i.y)this._maxx||othis._maxy||sthis._maxx&&(this._maxx=n._maxx),n._minythis._maxy&&(this._maxy=n._maxy))}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.isNull()?(this._minx=r,this._maxx=r,this._miny=i,this._maxy=i):(rthis._maxx&&(this._maxx=r),ithis._maxy&&(this._maxy=i))}}},{key:"minExtent",value:function(){if(this.isNull())return 0;var t=this.getWidth(),e=this.getHeight();return te._minx?1:this._minye._miny?1:this._maxxe._maxx?1:this._maxye._maxy?1:0}},{key:"translate",value:function(t,e){if(this.isNull())return null;this.init(this.getMinX()+t,this.getMaxX()+t,this.getMinY()+e,this.getMaxY()+e)}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"Env["+this._minx+" : "+this._maxx+", "+this._miny+" : "+this._maxy+"]"}},{key:"setToNull",value:function(){this._minx=0,this._maxx=-1,this._miny=0,this._maxy=-1}},{key:"disjoint",value:function(t){return!(!this.isNull()&&!t.isNull())||t._minx>this._maxx||t._maxxthis._maxy||t._maxye?t:e}},{key:"expandBy",value:function(){if(1===arguments.length){var t=arguments[0];this.expandBy(t,t)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];if(this.isNull())return null;this._minx-=e,this._maxx+=e,this._miny-=n,this._maxy+=n,(this._minx>this._maxx||this._miny>this._maxy)&&this.setToNull()}}},{key:"contains",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.covers(t)}if(arguments[0]instanceof z){var n=arguments[0];return this.covers(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return this.covers(r,i)}}},{key:"centre",value:function(){return this.isNull()?null:new z((this.getMinX()+this.getMaxX())/2,(this.getMinY()+this.getMaxY())/2)}},{key:"init",value:function(){if(0===arguments.length)this.setToNull();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this._minx=n._minx,this._maxx=n._maxx,this._miny=n._miny,this._maxy=n._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];ot._maxx&&(e=this._minx-t._maxx);var n=0;return this._maxyt._maxy&&(n=this._miny-t._maxy),0===e?n:0===n?e:Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*(t=37*(t=37*t+z.hashCode(this._minx))+z.hashCode(this._maxx))+z.hashCode(this._miny))+z.hashCode(this._maxy)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,0===arguments.length)this.init();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];this.init(o,s,a,u)}}},{key:"intersects",value:function(){if(3===arguments.length){var t=arguments[0],e=arguments[1],n=arguments[2];return n.x>=(t.xe.x?t.x:e.x)&&n.y>=(t.ye.y?t.y:e.y)}if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=arguments[3],a=Math.min(o.x,s.x),u=Math.max(o.x,s.x),l=Math.min(r.x,i.x),h=Math.max(r.x,i.x);return!(l>u||hu||h=this.size())throw new nt;return this.array[t]}},{key:"push",value:function(t){return this.array.push(t),t}},{key:"pop",value:function(){if(0===this.array.length)throw new et;return this.array.pop()}},{key:"peek",value:function(){if(0===this.array.length)throw new et;return this.array[this.array.length-1]}},{key:"empty",value:function(){return 0===this.array.length}},{key:"isEmpty",value:function(){return this.empty()}},{key:"search",value:function(t){return this.array.indexOf(t)}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}}]),o}(rt);function ot(t,e){return t.interfaces_&&t.interfaces_.indexOf(e)>-1}var st=function(){function e(n){t(this,e),this.str=n}return n(e,[{key:"append",value:function(t){this.str+=t}},{key:"setCharAt",value:function(t,e){this.str=this.str.substr(0,t)+e+this.str.substr(t+1)}},{key:"toString",value:function(){return this.str}}]),e}(),at=function(){function e(n){t(this,e),this.value=n}return n(e,[{key:"intValue",value:function(){return this.value}},{key:"compareTo",value:function(t){return this.valuet?1:0}}],[{key:"compare",value:function(t,e){return te?1:0}},{key:"isNan",value:function(t){return Number.isNaN(t)}},{key:"valueOf",value:function(t){return new e(t)}}]),e}(),ut=function(){function e(){t(this,e)}return n(e,null,[{key:"isWhitespace",value:function(t){return t<=32&&t>=0||127===t}},{key:"toUpperCase",value:function(t){return t.toUpperCase()}}]),e}(),lt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"le",value:function(t){return this._hi9?(c=!0,f="9"):f="0"+h,a.append(f),r=r.subtract(e.valueOf(h)).multiply(e.TEN),c&&r.selfAdd(e.TEN);var g=!0,p=e.magnitude(r._hi);if(p<0&&Math.abs(p)>=u-l&&(g=!1),!g)break}return n[0]=i,a.toString()}},{key:"sqr",value:function(){return this.multiply(this)}},{key:"doubleValue",value:function(){return this._hi+this._lo}},{key:"subtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.add(t.negate())}if("number"==typeof arguments[0]){var n=arguments[0];return this.add(-n)}}},{key:"equals",value:function(){if(1===arguments.length&&arguments[0]instanceof e){var t=arguments[0];return this._hi===t._hi&&this._lo===t._lo}}},{key:"isZero",value:function(){return 0===this._hi&&0===this._lo}},{key:"selfSubtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.isNaN()?this:this.selfAdd(-t._hi,-t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.isNaN()?this:this.selfAdd(-n,0)}}},{key:"getSpecialNumberString",value:function(){return this.isZero()?"0.0":this.isNaN()?"NaN ":null}},{key:"min",value:function(t){return this.le(t)?this:t}},{key:"selfDivide",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfDivide(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfDivide(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null,c=null,f=null;return l=this._hi/r,f=(o=(h=e.SPLIT*l)-(o=h-l))*(a=(f=e.SPLIT*r)-(a=f-r))-(c=l*r)+o*(u=r-a)+(s=l-o)*a+s*u,f=l+(h=(this._hi-c-f+this._lo-l*i)/r),this._hi=f,this._lo=l-f+h,this}}},{key:"dump",value:function(){return"DD<"+this._hi+", "+this._lo+">"}},{key:"divide",value:function(){if(arguments[0]instanceof e){var t=arguments[0],n=null,r=null,i=null,o=null,s=null,a=null,u=null,l=null;return r=(s=this._hi/t._hi)-(n=(a=e.SPLIT*s)-(n=a-s)),l=n*(i=(l=e.SPLIT*t._hi)-(i=l-t._hi))-(u=s*t._hi)+n*(o=t._hi-i)+r*i+r*o,new e(l=s+(a=(this._hi-u-l+this._lo-s*t._lo)/t._hi),s-l+a)}if("number"==typeof arguments[0]){var h=arguments[0];return A.isNaN(h)?e.createNaN():e.copy(this).selfDivide(h,0)}}},{key:"ge",value:function(t){return this._hi>t._hi||this._hi===t._hi&&this._lo>=t._lo}},{key:"pow",value:function(t){if(0===t)return e.valueOf(1);var n=new e(this),r=e.valueOf(1),i=Math.abs(t);if(i>1)for(;i>0;)i%2==1&&r.selfMultiply(n),(i/=2)>0&&(n=n.sqr());else r=n;return t<0?r.reciprocal():r}},{key:"ceil",value:function(){if(this.isNaN())return e.NaN;var t=Math.ceil(this._hi),n=0;return t===this._hi&&(n=Math.ceil(this._lo)),new e(t,n)}},{key:"compareTo",value:function(t){var e=t;return this._hie._hi?1:this._loe._lo?1:0}},{key:"rint",value:function(){return this.isNaN()?this:this.add(.5).floor()}},{key:"setValue",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.init(t),this}if("number"==typeof arguments[0]){var n=arguments[0];return this.init(n),this}}},{key:"max",value:function(t){return this.ge(t)?this:t}},{key:"sqrt",value:function(){if(this.isZero())return e.valueOf(0);if(this.isNegative())return e.NaN;var t=1/Math.sqrt(this._hi),n=this._hi*t,r=e.valueOf(n),i=this.subtract(r.sqr())._hi*(.5*t);return r.add(i)}},{key:"selfAdd",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfAdd(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0],r=null,i=null,o=null,s=null,a=null,u=null;return s=(o=this._hi+n)-(a=o-this._hi),i=(u=(s=n-a+(this._hi-s))+this._lo)+(o-(r=o+u)),this._hi=r+i,this._lo=i+(r-this._hi),this}}else if(2===arguments.length){var l=arguments[0],h=arguments[1],c=null,f=null,g=null,p=null,v=null,d=null,y=null;p=this._hi+l,f=this._lo+h,v=p-(d=p-this._hi),g=f-(y=f-this._lo);var m=(c=p+(d=(v=l-d+(this._hi-v))+f))+(d=(g=h-y+(this._lo-g))+(d+(p-c))),_=d+(c-m);return this._hi=m,this._lo=_,this}}},{key:"selfMultiply",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfMultiply(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfMultiply(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null;o=(l=e.SPLIT*this._hi)-this._hi,h=e.SPLIT*r,o=l-o,s=this._hi-o,a=h-r;var c=(l=this._hi*r)+(h=o*(a=h-a)-l+o*(u=r-a)+s*a+s*u+(this._hi*i+this._lo*r)),f=h+(o=l-c);return this._hi=c,this._lo=f,this}}},{key:"selfSqr",value:function(){return this.selfMultiply(this)}},{key:"floor",value:function(){if(this.isNaN())return e.NaN;var t=Math.floor(this._hi),n=0;return t===this._hi&&(n=Math.floor(this._lo)),new e(t,n)}},{key:"negate",value:function(){return this.isNaN()?this:new e(-this._hi,-this._lo)}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return null;throw t}}},{key:"multiply",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return t.isNaN()?e.createNaN():e.copy(this).selfMultiply(t)}if("number"==typeof arguments[0]){var n=arguments[0];return A.isNaN(n)?e.createNaN():e.copy(this).selfMultiply(n,0)}}},{key:"isNaN",value:function(){return A.isNaN(this._hi)}},{key:"intValue",value:function(){return Math.trunc(this._hi)}},{key:"toString",value:function(){var t=e.magnitude(this._hi);return t>=-3&&t<=20?this.toStandardNotation():this.toSciNotation()}},{key:"toStandardNotation",value:function(){var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!0,n),i=n[0]+1,o=r;if("."===r.charAt(0))o="0"+r;else if(i<0)o="0."+e.stringOfChar("0",-i)+r;else if(-1===r.indexOf(".")){var s=i-r.length;o=r+e.stringOfChar("0",s)+".0"}return this.isNegative()?"-"+o:o}},{key:"reciprocal",value:function(){var t,n,r,i,o=null,s=null,a=null,u=null;t=(r=1/this._hi)-(o=(a=e.SPLIT*r)-(o=a-r)),s=(u=e.SPLIT*this._hi)-this._hi;var l=r+(a=(1-(i=r*this._hi)-(u=o*(s=u-s)-i+o*(n=this._hi-s)+t*s+t*n)-r*this._lo)/this._hi);return new e(l,r-l+a)}},{key:"toSciNotation",value:function(){if(this.isZero())return e.SCI_NOT_ZERO;var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!1,n),i=e.SCI_NOT_EXPONENT_CHAR+n[0];if("0"===r.charAt(0))throw new IllegalStateException("Found leading zero: "+r);var o="";r.length>1&&(o=r.substring(1));var s=r.charAt(0)+"."+o;return this.isNegative()?"-"+s+i:s+i}},{key:"abs",value:function(){return this.isNaN()?e.NaN:this.isNegative()?this.negate():new e(this)}},{key:"isPositive",value:function(){return this._hi>0||0===this._hi&&this._lo>0}},{key:"lt",value:function(t){return this._hit._hi||this._hi===t._hi&&this._lo>t._lo}},{key:"isNegative",value:function(){return this._hi<0||0===this._hi&&this._lo<0}},{key:"trunc",value:function(){return this.isNaN()?e.NaN:this.isPositive()?this.floor():this.ceil()}},{key:"signum",value:function(){return this._hi>0?1:this._hi<0?-1:this._lo>0?1:this._lo<0?-1:0}},{key:"interfaces_",get:function(){return[w,k,b]}}],[{key:"constructor_",value:function(){if(this._hi=0,this._lo=0,0===arguments.length)this.init(0);else if(1===arguments.length){if("number"==typeof arguments[0]){var t=arguments[0];this.init(t)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}else if("string"==typeof arguments[0]){var r=arguments[0];e.constructor_.call(this,e.parse(r))}}else if(2===arguments.length){var i=arguments[0],o=arguments[1];this.init(i,o)}}},{key:"determinant",value:function(){if("number"==typeof arguments[3]&&"number"==typeof arguments[2]&&"number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1],r=arguments[2],i=arguments[3];return e.determinant(e.valueOf(t),e.valueOf(n),e.valueOf(r),e.valueOf(i))}if(arguments[3]instanceof e&&arguments[2]instanceof e&&arguments[0]instanceof e&&arguments[1]instanceof e){var o=arguments[1],s=arguments[2],a=arguments[3];return arguments[0].multiply(a).selfSubtract(o.multiply(s))}}},{key:"sqr",value:function(t){return e.valueOf(t).selfMultiply(t)}},{key:"valueOf",value:function(){if("string"==typeof arguments[0]){var t=arguments[0];return e.parse(t)}if("number"==typeof arguments[0])return new e(arguments[0])}},{key:"sqrt",value:function(t){return e.valueOf(t).sqrt()}},{key:"parse",value:function(t){for(var n=0,r=t.length;ut.isWhitespace(t.charAt(n));)n++;var i=!1;if(n=r);){var c=t.charAt(n);if(n++,ut.isDigit(c)){var f=c-"0";s.selfMultiply(e.TEN),s.selfAdd(f),a++}else{if("."!==c){if("e"===c||"E"===c){var g=t.substring(n);try{l=at.parseInt(g)}catch(e){throw e instanceof NumberFormatException?new NumberFormatException("Invalid exponent "+g+" in string "+t):e}break}throw new NumberFormatException("Unexpected character '"+c+"' at position "+n+" in string "+t)}u=a,h=!0}}var p=s;h||(u=a);var v=a-u-l;if(0===v)p=s;else if(v>0){var d=e.TEN.pow(v);p=s.divide(d)}else if(v<0){var y=e.TEN.pow(-v);p=s.multiply(y)}return i?p.negate():p}},{key:"createNaN",value:function(){return new e(A.NaN,A.NaN)}},{key:"copy",value:function(t){return new e(t)}},{key:"magnitude",value:function(t){var e=Math.abs(t),n=Math.log(e)/Math.log(10),r=Math.trunc(Math.floor(n));return 10*Math.pow(10,r)<=e&&(r+=1),r}},{key:"stringOfChar",value:function(t,e){for(var n=new st,r=0;r0){if(s<=0)return e.signum(a);i=o+s}else{if(!(o<0))return e.signum(a);if(s>=0)return e.signum(a);i=-o-s}var u=e.DP_SAFE_EPSILON*i;return a>=u||-a>=u?e.signum(a):2}},{key:"signum",value:function(t){return t>0?1:t<0?-1:0}}]),e}();ht.DP_SAFE_EPSILON=1e-15;var ct=function(){function e(){t(this,e)}return n(e,[{key:"getM",value:function(t){if(this.hasM()){var e=this.getDimension()-this.getMeasures();return this.getOrdinate(t,e)}return A.NaN}},{key:"setOrdinate",value:function(t,e,n){}},{key:"getZ",value:function(t){return this.hasZ()?this.getOrdinate(t,2):A.NaN}},{key:"size",value:function(){}},{key:"getOrdinate",value:function(t,e){}},{key:"getCoordinate",value:function(){}},{key:"getCoordinateCopy",value:function(t){}},{key:"createCoordinate",value:function(){}},{key:"getDimension",value:function(){}},{key:"hasM",value:function(){return this.getMeasures()>0}},{key:"getX",value:function(t){}},{key:"hasZ",value:function(){return this.getDimension()-this.getMeasures()>2}},{key:"getMeasures",value:function(){return 0}},{key:"expandEnvelope",value:function(t){}},{key:"copy",value:function(){}},{key:"getY",value:function(t){}},{key:"toCoordinateArray",value:function(){}},{key:"interfaces_",get:function(){return[b]}}]),e}();ct.X=0,ct.Y=1,ct.Z=2,ct.M=3;var ft=function(){function e(){t(this,e)}return n(e,null,[{key:"index",value:function(t,e,n){return ht.orientationIndex(t,e,n)}},{key:"isCCW",value:function(){if(arguments[0]instanceof Array){var t=arguments[0],n=t.length-1;if(n<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var r=t[0],i=0,o=1;o<=n;o++){var s=t[o];s.y>r.y&&(r=s,i=o)}var a=i;do{(a-=1)<0&&(a=n)}while(t[a].equals2D(r)&&a!==i);var u=i;do{u=(u+1)%n}while(t[u].equals2D(r)&&u!==i);var l=t[a],h=t[u];if(l.equals2D(r)||h.equals2D(r)||l.equals2D(h))return!1;var c=e.index(l,r,h);return 0===c?l.x>h.x:c>0}if(ot(arguments[0],ct)){var f=arguments[0],g=f.size()-1;if(g<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var p=f.getCoordinate(0),v=0,d=1;d<=g;d++){var y=f.getCoordinate(d);y.y>p.y&&(p=y,v=d)}var m=null,_=v;do{(_-=1)<0&&(_=g),m=f.getCoordinate(_)}while(m.equals2D(p)&&_!==v);var E=null,k=v;do{k=(k+1)%g,E=f.getCoordinate(k)}while(E.equals2D(p)&&k!==v);if(m.equals2D(p)||E.equals2D(p)||m.equals2D(E))return!1;var b=e.index(m,p,E);return 0===b?m.x>E.x:b>0}}}]),e}();ft.CLOCKWISE=-1,ft.RIGHT=ft.CLOCKWISE,ft.COUNTERCLOCKWISE=1,ft.LEFT=ft.COUNTERCLOCKWISE,ft.COLLINEAR=0,ft.STRAIGHT=ft.COLLINEAR;var gt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this._minCoord}},{key:"getRightmostSide",value:function(t,e){var n=this.getRightmostSideOfSegment(t,e);return n<0&&(n=this.getRightmostSideOfSegment(t,e-1)),n<0&&(this._minCoord=null,this.checkForRightmostCoordinate(t)),n}},{key:"findRightmostEdgeAtVertex",value:function(){var t=this._minDe.getEdge().getCoordinates();V.isTrue(this._minIndex>0&&this._minIndexthis._minCoord.y&&n.y>this._minCoord.y&&r===ft.CLOCKWISE)&&(i=!0),i&&(this._minIndex=this._minIndex-1)}},{key:"getRightmostSideOfSegment",value:function(t,e){var n=t.getEdge().getCoordinates();if(e<0||e+1>=n.length)return-1;if(n[e].y===n[e+1].y)return-1;var r=tt.LEFT;return n[e].ythis._minCoord.x)&&(this._minDe=t,this._minIndex=n,this._minCoord=e[n])}},{key:"findRightmostEdgeAtNode",value:function(){var t=this._minDe.getNode().getEdges();this._minDe=t.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)}},{key:"findEdge",value:function(t){for(var e=t.iterator();e.hasNext();){var n=e.next();n.isForward()&&this.checkForRightmostCoordinate(n)}V.isTrue(0!==this._minIndex||this._minCoord.equals(this._minDe.getCoordinate()),"inconsistency in rightmost processing"),0===this._minIndex?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe,this.getRightmostSide(this._minDe,this._minIndex)===tt.LEFT&&(this._orientedDe=this._minDe.getSym())}}],[{key:"constructor_",value:function(){this._minIndex=-1,this._minCoord=null,this._minDe=null,this._orientedDe=null}}]),e}(),pt=function(e){r(o,e);var i=c(o);function o(e,n){var r;return t(this,o),(r=i.call(this,n?e+" [ "+n+" ]":e)).pt=n?new z(n):void 0,r.name=Object.keys({TopologyException:o})[0],r}return n(o,[{key:"getCoordinate",value:function(){return this.pt}}]),o}(F),vt=function(){function e(){t(this,e),this.array=[]}return n(e,[{key:"addLast",value:function(t){this.array.push(t)}},{key:"removeFirst",value:function(){return this.array.shift()}},{key:"isEmpty",value:function(){return 0===this.array.length}}]),e}(),dt=function(e,i){r(s,e);var o=c(s);function s(e){var n;return t(this,s),(n=o.call(this)).array=[],e instanceof H&&n.addAll(e),n}return n(s,[{key:"interfaces_",get:function(){return[rt,H]}},{key:"ensureCapacity",value:function(){}},{key:"add",value:function(t){return 1===arguments.length?this.array.push(t):this.array.splice(arguments[0],0,arguments[1]),!0}},{key:"clear",value:function(){this.array=[]}},{key:"addAll",value:function(t){var e,n=d(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.array.push(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"set",value:function(t,e){var n=this.array[t];return this.array[t]=e,n}},{key:"iterator",value:function(){return new yt(this)}},{key:"get",value:function(t){if(t<0||t>=this.size())throw new nt;return this.array[t]}},{key:"isEmpty",value:function(){return 0===this.array.length}},{key:"sort",value:function(t){t?this.array.sort((function(e,n){return t.compare(e,n)})):this.array.sort()}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}},{key:"remove",value:function(t){for(var e=0,n=this.array.length;e=1&&e.getDepth(tt.LEFT)<=0&&!e.isInteriorAreaEdge()&&e.setInResult(!0)}}},{key:"computeDepths",value:function(t){var e=new Q,n=new vt,r=t.getNode();for(n.addLast(r),e.add(r),t.setVisited(!0);!n.isEmpty();){var i=n.removeFirst();e.add(i),this.computeNodeDepth(i);for(var o=i.getEdges().iterator();o.hasNext();){var s=o.next().getSym();if(!s.isVisited()){var a=s.getNode();e.contains(a)||(n.addLast(a),e.add(a))}}}}},{key:"compareTo",value:function(t){var e=t;return this._rightMostCoord.xe._rightMostCoord.x?1:0}},{key:"getEnvelope",value:function(){if(null===this._env){for(var t=new X,e=this._dirEdgeList.iterator();e.hasNext();)for(var n=e.next().getEdge().getCoordinates(),r=0;re.x?t.x:e.x,a=t.y>e.y?t.y:e.y,u=n.xr.x?n.x:r.x,c=n.y>r.y?n.y:r.y,f=((i>u?i:u)+(sl?o:l)+(an?n:t}if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var r=arguments[0],i=arguments[1],o=arguments[2];return ro?o:r}}},{key:"wrap",value:function(t,e){return t<0?e- -t%e:t%e}},{key:"max",value:function(){if(3===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[0];return t>n&&(n=t),e>n&&(n=e),n}if(4===arguments.length){var r=arguments[1],i=arguments[2],o=arguments[3],s=arguments[0];return r>s&&(s=r),i>s&&(s=i),o>s&&(s=o),s}}},{key:"average",value:function(t,e){return(t+e)/2}}]),e}();Et.LOG_10=Math.log(10);var kt=function(){function e(){t(this,e)}return n(e,null,[{key:"segmentToSegment",value:function(t,n,r,i){if(t.equals(n))return e.pointToSegment(t,r,i);if(r.equals(i))return e.pointToSegment(i,t,n);var o=!1;if(X.intersects(t,n,r,i)){var s=(n.x-t.x)*(i.y-r.y)-(n.y-t.y)*(i.x-r.x);if(0===s)o=!0;else{var a=(t.y-r.y)*(i.x-r.x)-(t.x-r.x)*(i.y-r.y),u=((t.y-r.y)*(n.x-t.x)-(t.x-r.x)*(n.y-t.y))/s,l=a/s;(l<0||l>1||u<0||u>1)&&(o=!0)}}else o=!0;return o?Et.min(e.pointToSegment(t,r,i),e.pointToSegment(n,r,i),e.pointToSegment(r,t,n),e.pointToSegment(i,t,n)):0}},{key:"pointToSegment",value:function(t,e,n){if(e.x===n.x&&e.y===n.y)return t.distance(e);var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/r;if(i<=0)return t.distance(e);if(i>=1)return t.distance(n);var o=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(o)*Math.sqrt(r)}},{key:"pointToLinePerpendicular",value:function(t,e,n){var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(i)*Math.sqrt(r)}},{key:"pointToSegmentString",value:function(t,n){if(0===n.length)throw new x("Line array must contain at least one vertex");for(var r=t.distance(n[0]),i=0;i0)&&(o=a,i=s)}return i}}},{key:"extend",value:function(t,n,r){var i=t.create(r,n.getDimension()),o=n.size();if(e.copy(n,0,i,0,o),o>0)for(var s=o;s0)&&(e=r)}return e}}]),e}(),Mt=function(){function e(){t(this,e)}return n(e,null,[{key:"toDimensionSymbol",value:function(t){switch(t){case e.FALSE:return e.SYM_FALSE;case e.TRUE:return e.SYM_TRUE;case e.DONTCARE:return e.SYM_DONTCARE;case e.P:return e.SYM_P;case e.L:return e.SYM_L;case e.A:return e.SYM_A}throw new x("Unknown dimension value: "+t)}},{key:"toDimensionValue",value:function(t){switch(ut.toUpperCase(t)){case e.SYM_FALSE:return e.FALSE;case e.SYM_TRUE:return e.TRUE;case e.SYM_DONTCARE:return e.DONTCARE;case e.SYM_P:return e.P;case e.SYM_L:return e.L;case e.SYM_A:return e.A}throw new x("Unknown dimension symbol: "+t)}}]),e}();Mt.P=0,Mt.L=1,Mt.A=2,Mt.FALSE=-1,Mt.TRUE=-2,Mt.DONTCARE=-3,Mt.SYM_FALSE="F",Mt.SYM_TRUE="T",Mt.SYM_DONTCARE="*",Mt.SYM_P="0",Mt.SYM_L="1",Mt.SYM_A="2";var Lt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}(),Pt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t,e){}},{key:"isDone",value:function(){}},{key:"isGeometryChanged",value:function(){}}]),e}(),Ct=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"computeEnvelopeInternal",value:function(){return this.isEmpty()?new X:this._points.expandEnvelope(new X)}},{key:"isRing",value:function(){return this.isClosed()&&this.isSimple()}},{key:"getCoordinates",value:function(){return this._points.toCoordinateArray()}},{key:"copyInternal",value:function(){return new s(this._points.copy(),this._factory)}},{key:"equalsExact",value:function(){if(2===arguments.length&&"number"==typeof arguments[1]&&arguments[0]instanceof U){var t=arguments[0],e=arguments[1];if(!this.isEquivalentClass(t))return!1;var n=t;if(this._points.size()!==n._points.size())return!1;for(var r=0;r0){var n=this._points.copy();St.reverse(n),this._points=n}return null}}}},{key:"getCoordinate",value:function(){return this.isEmpty()?null:this._points.getCoordinate(0)}},{key:"getBoundaryDimension",value:function(){return this.isClosed()?Mt.FALSE:0}},{key:"isClosed",value:function(){return!this.isEmpty()&&this.getCoordinateN(0).equals2D(this.getCoordinateN(this.getNumPoints()-1))}},{key:"reverseInternal",value:function(){var t=this._points.copy();return St.reverse(t),this.getFactory().createLineString(t)}},{key:"getEndPoint",value:function(){return this.isEmpty()?null:this.getPointN(this.getNumPoints()-1)}},{key:"getTypeCode",value:function(){return U.TYPECODE_LINESTRING}},{key:"getDimension",value:function(){return 1}},{key:"getLength",value:function(){return It.ofLine(this._points)}},{key:"getNumPoints",value:function(){return this._points.size()}},{key:"compareToSameClass",value:function(){if(1===arguments.length){for(var t=arguments[0],e=0,n=0;e= 2)");this._points=t}},{key:"isCoordinate",value:function(t){for(var e=0;e=1&&this.getCoordinateSequence().size()= 4)")}},{key:"getGeometryType",value:function(){return U.TYPENAME_LINEARRING}}],[{key:"constructor_",value:function(){var t=arguments[0],e=arguments[1];Ct.constructor_.call(this,t,e),this.validateConstruction()}}]),s}(Ct);zt.MINIMUM_VALID_SIZE=4;var jt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}}],[{key:"constructor_",value:function(){if(0===arguments.length)z.constructor_.call(this);else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y)}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y)}}else if(2===arguments.length){var n=arguments[0],r=arguments[1];z.constructor_.call(this,n,r,z.NULL_ORDINATE)}}}]),o}(z);jt.X=0,jt.Y=1,jt.Z=-1,jt.M=-1;var Xt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;case o.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y;case o.M:return this._m}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y),this._m=this.getM()}}else if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2];z.constructor_.call(this,n,r,z.NULL_ORDINATE),this._m=i}}}]),o}(z);Xt.X=0,Xt.Y=1,Xt.Z=-1,Xt.M=2;var Ut=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case z.X:this.x=e;break;case z.Y:this.y=e;break;case z.Z:this.z=e;break;case z.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getOrdinate",value:function(t){switch(t){case z.X:return this.x;case z.Y:return this.y;case z.Z:return this.getZ();case z.M:return this.getM()}throw new x("Invalid ordinate index: "+t)}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e),this._m=this.getM()}}else if(4===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],s=arguments[3];z.constructor_.call(this,n,r,i),this._m=s}}}]),o}(z),Zt=function(){function e(){t(this,e)}return n(e,null,[{key:"measures",value:function(t){return t instanceof jt?0:t instanceof Xt||t instanceof Ut?1:0}},{key:"dimension",value:function(t){return t instanceof jt?2:t instanceof Xt?3:t instanceof Ut?4:3}},{key:"create",value:function(){if(1===arguments.length){var t=arguments[0];return e.create(t,0)}if(2===arguments.length){var n=arguments[0],r=arguments[1];return 2===n?new jt:3===n&&0===r?new z:3===n&&1===r?new Xt:4===n&&1===r?new Ut:new z}}}]),e}(),Ht=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getCoordinate",value:function(t){return this.get(t)}},{key:"addAll",value:function(){if(2===arguments.length&&"boolean"==typeof arguments[1]&&ot(arguments[0],H)){for(var t=arguments[1],e=!1,n=arguments[0].iterator();n.hasNext();)this.add(n.next(),t),e=!0;return e}return f(i(s.prototype),"addAll",this).apply(this,arguments)}},{key:"clone",value:function(){for(var t=f(i(s.prototype),"clone",this).call(this),e=0;e=1&&this.get(this.size()-1).equals2D(r))return null;f(i(s.prototype),"add",this).call(this,r)}else if(arguments[0]instanceof Object&&"boolean"==typeof arguments[1]){var o=arguments[0],a=arguments[1];return this.add(o,a),!0}}else if(3===arguments.length){if("boolean"==typeof arguments[2]&&arguments[0]instanceof Array&&"boolean"==typeof arguments[1]){var u=arguments[0],l=arguments[1];if(arguments[2])for(var h=0;h=0;c--)this.add(u[c],l);return!0}if("boolean"==typeof arguments[2]&&Number.isInteger(arguments[0])&&arguments[1]instanceof z){var g=arguments[0],p=arguments[1];if(!arguments[2]){var v=this.size();if(v>0){if(g>0&&this.get(g-1).equals2D(p))return null;if(g_&&(x=-1);for(var E=m;E!==_;E+=x)this.add(d[E],y);return!0}}},{key:"closeRing",value:function(){if(this.size()>0){var t=this.get(0).copy();this.add(t,!1)}}}],[{key:"constructor_",value:function(){if(0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.ensureCapacity(t.length),this.add(t,!0)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this.ensureCapacity(e.length),this.add(e,n)}}}]),s}(dt);Ht.coordArrayType=new Array(0).fill(null);var Wt=function(){function e(){t(this,e)}return n(e,null,[{key:"isRing",value:function(t){return!(t.length<4||!t[0].equals2D(t[t.length-1]))}},{key:"ptNotInList",value:function(t,n){for(var r=0;r=t?e:[]}},{key:"indexOf",value:function(t,e){for(var n=0;n0)&&(e=t[n]);return e}},{key:"extract",value:function(t,e,n){e=Et.clamp(e,0,t.length);var r=(n=Et.clamp(n,-1,t.length))-e+1;n<0&&(r=0),e>=t.length&&(r=0),nr.length)return 1;if(0===n.length)return 0;var i=Wt.compare(n,r);return Wt.isEqualReversed(n,r)?0:i}},{key:"OLDcompare",value:function(t,e){var n=t,r=e;if(n.lengthr.length)return 1;if(0===n.length)return 0;for(var i=Wt.increasingDirection(n),o=Wt.increasingDirection(r),s=i>0?0:n.length-1,a=o>0?0:n.length-1,u=0;u0){var t=new Qt(17*this._coordinates.length);t.append("("),t.append(this._coordinates[0]);for(var e=1;e3&&(t=3),t<2&&(t=2),new $t(arguments[0],t)}if(3===arguments.length){var e=arguments[2],n=arguments[1]-e;return e>1&&(e=1),n>3&&(n=3),n<2&&(n=2),new $t(arguments[0],n+e,e)}}}},{key:"interfaces_",get:function(){return[bt,w]}}],[{key:"instance",value:function(){return e.instanceObject}}]),e}();te.instanceObject=new te;var ee=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e=0?t:e}}]),e}(),oe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"readResolve",value:function(){return e.nameToTypeMap.get(this._name)}},{key:"toString",value:function(){return this._name}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){this._name=null;var t=arguments[0];this._name=t,e.nameToTypeMap.put(t,this)}}]),e}();oe.nameToTypeMap=new re,ie.Type=oe,ie.FIXED=new oe("FIXED"),ie.FLOATING=new oe("FLOATING"),ie.FLOATING_SINGLE=new oe("FLOATING SINGLE"),ie.maximumPreciseValue=9007199254740992;var se=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e1){if(u instanceof Ft)return this.createMultiPolygon(e.toPolygonArray(t));if(u instanceof Ct)return this.createMultiLineString(e.toLineStringArray(t));if(u instanceof Ot)return this.createMultiPoint(e.toPointArray(t));V.shouldNeverReachHere("Unhandled geometry type: "+u.getGeometryType())}return u}},{key:"createMultiPointFromCoords",value:function(t){return this.createMultiPoint(null!==t?this.getCoordinateSequenceFactory().create(t):null)}},{key:"createPoint",value:function(){if(0===arguments.length)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];return this.createPoint(null!==t?this.getCoordinateSequenceFactory().create([t]):null)}if(ot(arguments[0],ct))return new Ot(arguments[0],this)}}},{key:"getCoordinateSequenceFactory",value:function(){return this._coordinateSequenceFactory}},{key:"createPolygon",value:function(){if(0===arguments.length)return this.createPolygon(null,null);if(1===arguments.length){if(ot(arguments[0],ct)){var t=arguments[0];return this.createPolygon(this.createLinearRing(t))}if(arguments[0]instanceof Array){var e=arguments[0];return this.createPolygon(this.createLinearRing(e))}if(arguments[0]instanceof zt){var n=arguments[0];return this.createPolygon(n,null)}}else if(2===arguments.length)return new Ft(arguments[0],arguments[1],this)}},{key:"getSRID",value:function(){return this._SRID}},{key:"createGeometryCollection",value:function(){return 0===arguments.length?new Bt(null,this):1===arguments.length?new Bt(arguments[0],this):void 0}},{key:"getPrecisionModel",value:function(){return this._precisionModel}},{key:"createLinearRing",value:function(){if(0===arguments.length)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof Array){var t=arguments[0];return this.createLinearRing(null!==t?this.getCoordinateSequenceFactory().create(t):null)}if(ot(arguments[0],ct))return new zt(arguments[0],this)}}},{key:"createMultiPolygon",value:function(){return 0===arguments.length?new ee(null,this):1===arguments.length?new ee(arguments[0],this):void 0}},{key:"createMultiPoint",value:function(){if(0===arguments.length)return new Yt(null,this);if(1===arguments.length){if(arguments[0]instanceof Array)return new Yt(arguments[0],this);if(ot(arguments[0],ct)){var t=arguments[0];if(null===t)return this.createMultiPoint(new Array(0).fill(null));for(var e=new Array(t.size()).fill(null),n=0;n="a"&&t<="z"||t>="A"&&t<="Z"}},{key:"isNumeric_",value:function(t,e){return t>="0"&&t<="9"||"."==t&&!(void 0!==e&&e)}},{key:"isWhiteSpace_",value:function(t){return" "==t||"\t"==t||"\r"==t||"\n"==t}},{key:"nextChar_",value:function(){return this.wkt.charAt(++this.index_)}},{key:"nextToken",value:function(){var t,e=this.nextChar_(),n=this.index_,r=e;if("("==e)t=ve;else if(","==e)t=me;else if(")"==e)t=de;else if(this.isNumeric_(e)||"-"==e)t=ye,r=this.readNumber_();else if(this.isAlpha_(e))t=pe,r=this.readText_();else{if(this.isWhiteSpace_(e))return this.nextToken();if(""!==e)throw new Error("Unexpected character: "+e);t=_e}return{position:n,value:r,type:t}}},{key:"readNumber_",value:function(){var t,e=this.index_,n=!1,r=!1;do{"."==t?n=!0:"e"!=t&&"E"!=t||(r=!0),t=this.nextChar_()}while(this.isNumeric_(t,n)||!r&&("e"==t||"E"==t)||r&&("-"==t||"+"==t));return parseFloat(this.wkt.substring(e,this.index_--))}},{key:"readText_",value:function(){var t,e=this.index_;do{t=this.nextChar_()}while(this.isAlpha_(t));return this.wkt.substring(e,this.index_--).toUpperCase()}}]),e}(),ke=function(){function e(n,r){t(this,e),this.lexer_=n,this.token_,this.layout_=ue,this.factory=r}return n(e,[{key:"consume_",value:function(){this.token_=this.lexer_.nextToken()}},{key:"isTokenType",value:function(t){return this.token_.type==t}},{key:"match",value:function(t){var e=this.isTokenType(t);return e&&this.consume_(),e}},{key:"parse",value:function(){return this.consume_(),this.parseGeometry_()}},{key:"parseGeometryLayout_",value:function(){var t=ue,e=this.token_;if(this.isTokenType(pe)){var n=e.value;"Z"===n?t=le:"M"===n?t=he:"ZM"===n&&(t=ce),t!==ue&&this.consume_()}return t}},{key:"parseGeometryCollectionText_",value:function(){if(this.match(ve)){var t=[];do{t.push(this.parseGeometry_())}while(this.match(me));if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePointText_",value:function(){if(this.match(ve)){var t=this.parsePoint_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return null;throw new Error(this.formatErrorMessage_())}},{key:"parseLineStringText_",value:function(){if(this.match(ve)){var t=this.parsePointList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePolygonText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPointText_",value:function(){var t;if(this.match(ve)){if(t=this.token_.type==ve?this.parsePointTextList_():this.parsePointList_(),this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiLineStringText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPolygonText_",value:function(){if(this.match(ve)){var t=this.parsePolygonTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePoint_",value:function(){for(var t=[],e=this.layout_.length,n=0;n1?t.createPolygon(r[0],r.slice(1)):t.createPolygon(r[0])},r=this.token_;if(this.match(pe)){var i=r.value;if(this.layout_=this.parseGeometryLayout_(),"GEOMETRYCOLLECTION"==i){var o=this.parseGeometryCollectionText_();return t.createGeometryCollection(o)}switch(i){case"POINT":var s=this.parsePointText_();return s?t.createPoint(a(z,g(s))):t.createPoint();case"LINESTRING":var u=this.parseLineStringText_().map(e);return t.createLineString(u);case"LINEARRING":var l=this.parseLineStringText_().map(e);return t.createLinearRing(l);case"POLYGON":var h=this.parsePolygonText_();return h&&0!==h.length?n(h):t.createPolygon();case"MULTIPOINT":var c=this.parseMultiPointText_();if(!c||0===c.length)return t.createMultiPoint();var f=c.map(e).map((function(e){return t.createPoint(e)}));return t.createMultiPoint(f);case"MULTILINESTRING":var p=this.parseMultiLineStringText_().map((function(n){return t.createLineString(n.map(e))}));return t.createMultiLineString(p);case"MULTIPOLYGON":var v=this.parseMultiPolygonText_();if(!v||0===v.length)return t.createMultiPolygon();var d=v.map(n);return t.createMultiPolygon(d);default:throw new Error("Invalid geometry type: "+i)}}throw new Error(this.formatErrorMessage_())}}]),e}();function be(t){if(t.isEmpty())return"";var e=t.getCoordinate(),n=[e.x,e.y];return void 0===e.z||Number.isNaN(e.z)||n.push(e.z),void 0===e.m||Number.isNaN(e.m)||n.push(e.m),n.join(" ")}function we(t){for(var e=t.getCoordinates().map((function(t){var e=[t.x,t.y];return void 0===t.z||Number.isNaN(t.z)||e.push(t.z),void 0===t.m||Number.isNaN(t.m)||e.push(t.m),e})),n=[],r=0,i=e.length;r0&&(e+=" "+r),t.isEmpty()?e+" "+ge:e+" ("+n(t)+")"}var Me=function(){function e(n){t(this,e),this.geometryFactory=n||new ae,this.precisionModel=this.geometryFactory.getPrecisionModel()}return n(e,[{key:"read",value:function(t){var e=new Ee(t);return new ke(e,this.geometryFactory).parse()}},{key:"write",value:function(t){return Se(t)}}]),e}(),Le=function(){function e(n){t(this,e),this.parser=new Me(n)}return n(e,[{key:"write",value:function(t){return this.parser.write(t)}}],[{key:"toLineString",value:function(t,e){if(2!==arguments.length)throw new Error("Not implemented");return"LINESTRING ( "+t.x+" "+t.y+", "+e.x+" "+e.y+" )"}}]),e}(),Pe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getIndexAlongSegment",value:function(t,e){return this.computeIntLineIndex(),this._intLineIndex[t][e]}},{key:"getTopologySummary",value:function(){var t=new Qt;return this.isEndPoint()&&t.append(" endpoint"),this._isProper&&t.append(" proper"),this.isCollinear()&&t.append(" collinear"),t.toString()}},{key:"computeIntersection",value:function(t,e,n,r){this._inputLines[0][0]=t,this._inputLines[0][1]=e,this._inputLines[1][0]=n,this._inputLines[1][1]=r,this._result=this.computeIntersect(t,e,n,r)}},{key:"getIntersectionNum",value:function(){return this._result}},{key:"computeIntLineIndex",value:function(){if(0===arguments.length)null===this._intLineIndex&&(this._intLineIndex=Array(2).fill().map((function(){return Array(2)})),this.computeIntLineIndex(0),this.computeIntLineIndex(1));else if(1===arguments.length){var t=arguments[0];this.getEdgeDistance(t,0)>this.getEdgeDistance(t,1)?(this._intLineIndex[t][0]=0,this._intLineIndex[t][1]=1):(this._intLineIndex[t][0]=1,this._intLineIndex[t][1]=0)}}},{key:"isProper",value:function(){return this.hasIntersection()&&this._isProper}},{key:"setPrecisionModel",value:function(t){this._precisionModel=t}},{key:"isInteriorIntersection",value:function(){if(0===arguments.length)return!!this.isInteriorIntersection(0)||!!this.isInteriorIntersection(1);if(1===arguments.length){for(var t=arguments[0],e=0;ei?r:i;else{var s=Math.abs(t.x-e.x),a=Math.abs(t.y-e.y);0!==(o=r>i?s:a)||t.equals(e)||(o=Math.max(s,a))}return V.isTrue(!(0===o&&!t.equals(e)),"Bad distance calculation"),o}},{key:"nonRobustComputeEdgeDistance",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y,o=Math.sqrt(r*r+i*i);return V.isTrue(!(0===o&&!t.equals(e)),"Invalid distance calculation"),o}}]),e}();Pe.DONT_INTERSECT=0,Pe.DO_INTERSECT=1,Pe.COLLINEAR=2,Pe.NO_INTERSECTION=0,Pe.POINT_INTERSECTION=1,Pe.COLLINEAR_INTERSECTION=2;var Ce=function(e){r(s,e);var o=c(s);function s(){return t(this,s),o.call(this)}return n(s,[{key:"isInSegmentEnvelopes",value:function(t){var e=new X(this._inputLines[0][0],this._inputLines[0][1]),n=new X(this._inputLines[1][0],this._inputLines[1][1]);return e.contains(t)&&n.contains(t)}},{key:"computeIntersection",value:function(){if(3!==arguments.length)return f(i(s.prototype),"computeIntersection",this).apply(this,arguments);var t=arguments[0],e=arguments[1],n=arguments[2];if(this._isProper=!1,X.intersects(e,n,t)&&0===ft.index(e,n,t)&&0===ft.index(n,e,t))return this._isProper=!0,(t.equals(e)||t.equals(n))&&(this._isProper=!1),this._result=Pe.POINT_INTERSECTION,null;this._result=Pe.NO_INTERSECTION}},{key:"intersection",value:function(t,e,n,r){var i=this.intersectionSafe(t,e,n,r);return this.isInSegmentEnvelopes(i)||(i=new z(s.nearestEndpoint(t,e,n,r))),null!==this._precisionModel&&this._precisionModel.makePrecise(i),i}},{key:"checkDD",value:function(t,e,n,r,i){var o=ht.intersection(t,e,n,r),s=this.isInSegmentEnvelopes(o);xt.out.println("DD in env = "+s+" --------------------- "+o),i.distance(o)>1e-4&&xt.out.println("Distance = "+i.distance(o))}},{key:"intersectionSafe",value:function(t,e,n,r){var i=_t.intersection(t,e,n,r);return null===i&&(i=s.nearestEndpoint(t,e,n,r)),i}},{key:"computeCollinearIntersection",value:function(t,e,n,r){var i=X.intersects(t,e,n),o=X.intersects(t,e,r),s=X.intersects(n,r,t),a=X.intersects(n,r,e);return i&&o?(this._intPt[0]=n,this._intPt[1]=r,Pe.COLLINEAR_INTERSECTION):s&&a?(this._intPt[0]=t,this._intPt[1]=e,Pe.COLLINEAR_INTERSECTION):i&&s?(this._intPt[0]=n,this._intPt[1]=t,!n.equals(t)||o||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):i&&a?(this._intPt[0]=n,this._intPt[1]=e,!n.equals(e)||o||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&s?(this._intPt[0]=r,this._intPt[1]=t,!r.equals(t)||i||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&a?(this._intPt[0]=r,this._intPt[1]=e,!r.equals(e)||i||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):Pe.NO_INTERSECTION}},{key:"computeIntersect",value:function(t,e,n,r){if(this._isProper=!1,!X.intersects(t,e,n,r))return Pe.NO_INTERSECTION;var i=ft.index(t,e,n),o=ft.index(t,e,r);if(i>0&&o>0||i<0&&o<0)return Pe.NO_INTERSECTION;var s=ft.index(n,r,t),a=ft.index(n,r,e);return s>0&&a>0||s<0&&a<0?Pe.NO_INTERSECTION:0===i&&0===o&&0===s&&0===a?this.computeCollinearIntersection(t,e,n,r):(0===i||0===o||0===s||0===a?(this._isProper=!1,t.equals2D(n)||t.equals2D(r)?this._intPt[0]=t:e.equals2D(n)||e.equals2D(r)?this._intPt[0]=e:0===i?this._intPt[0]=new z(n):0===o?this._intPt[0]=new z(r):0===s?this._intPt[0]=new z(t):0===a&&(this._intPt[0]=new z(e))):(this._isProper=!0,this._intPt[0]=this.intersection(t,e,n,r)),Pe.POINT_INTERSECTION)}}],[{key:"nearestEndpoint",value:function(t,e,n,r){var i=t,o=kt.pointToSegment(t,n,r),s=kt.pointToSegment(e,n,r);return sr&&(n=e.x,r=t.x),this._p.x>=n&&this._p.x<=r&&(this._isPointOnSegment=!0),null}if(t.y>this._p.y&&e.y<=this._p.y||e.y>this._p.y&&t.y<=this._p.y){var i=ft.index(t,e,this._p);if(i===ft.COLLINEAR)return this._isPointOnSegment=!0,null;e.ythis.location.length){var e=new Array(3).fill(null);e[tt.ON]=this.location[tt.ON],e[tt.LEFT]=Z.NONE,e[tt.RIGHT]=Z.NONE,this.location=e}for(var n=0;n1&&t.append(Z.toLocationSymbol(this.location[tt.LEFT])),t.append(Z.toLocationSymbol(this.location[tt.ON])),this.location.length>1&&t.append(Z.toLocationSymbol(this.location[tt.RIGHT])),t.toString()}},{key:"setLocations",value:function(t,e,n){this.location[tt.ON]=t,this.location[tt.LEFT]=e,this.location[tt.RIGHT]=n}},{key:"get",value:function(t){return t1}},{key:"isAnyNull",value:function(){for(var t=0;tthis._maxNodeDegree&&(this._maxNodeDegree=e),t=this.getNext(t)}while(t!==this._startDe);this._maxNodeDegree*=2}},{key:"addPoints",value:function(t,e,n){var r=t.getCoordinates();if(e){var i=1;n&&(i=0);for(var o=i;o=0;a--)this._pts.add(r[a])}}},{key:"isHole",value:function(){return this._isHole}},{key:"setInResult",value:function(){var t=this._startDe;do{t.getEdge().setInResult(!0),t=t.getNext()}while(t!==this._startDe)}},{key:"containsPoint",value:function(t){var e=this.getLinearRing();if(!e.getEnvelopeInternal().contains(t))return!1;if(!Oe.isInRing(t,e.getCoordinates()))return!1;for(var n=this._holes.iterator();n.hasNext();)if(n.next().containsPoint(t))return!1;return!0}},{key:"addHole",value:function(t){this._holes.add(t)}},{key:"isShell",value:function(){return null===this._shell}},{key:"getLabel",value:function(){return this._label}},{key:"getEdges",value:function(){return this._edges}},{key:"getMaxNodeDegree",value:function(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree}},{key:"getShell",value:function(){return this._shell}},{key:"mergeLabel",value:function(){if(1===arguments.length){var t=arguments[0];this.mergeLabel(t,0),this.mergeLabel(t,1)}else if(2===arguments.length){var e=arguments[1],n=arguments[0].getLocation(e,tt.RIGHT);if(n===Z.NONE)return null;if(this._label.getLocation(e)===Z.NONE)return this._label.setLocation(e,n),null}}},{key:"setShell",value:function(t){this._shell=t,null!==t&&t.addHole(this)}},{key:"toPolygon",value:function(t){for(var e=new Array(this._holes.size()).fill(null),n=0;n=2,"found partial label"),this.computeIM(t)}},{key:"isInResult",value:function(){return this._isInResult}},{key:"isVisited",value:function(){return this._isVisited}}],[{key:"constructor_",value:function(){if(this._label=null,this._isInResult=!1,this._isCovered=!1,this._isCoveredSet=!1,this._isVisited=!1,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._label=t}}}]),e}(),Ge=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isIncidentEdgeInResult",value:function(){for(var t=this.getEdges().getEdges().iterator();t.hasNext();)if(t.next().getEdge().isInResult())return!0;return!1}},{key:"isIsolated",value:function(){return 1===this._label.getGeometryCount()}},{key:"getCoordinate",value:function(){return this._coord}},{key:"print",value:function(t){t.println("node "+this._coord+" lbl: "+this._label)}},{key:"computeIM",value:function(t){}},{key:"computeMergedLocation",value:function(t,e){var n=Z.NONE;if(n=this._label.getLocation(e),!t.isNull(e)){var r=t.getLocation(e);n!==Z.BOUNDARY&&(n=r)}return n}},{key:"setLabel",value:function(){if(2!==arguments.length||!Number.isInteger(arguments[1])||!Number.isInteger(arguments[0]))return f(i(s.prototype),"setLabel",this).apply(this,arguments);var t=arguments[0],e=arguments[1];null===this._label?this._label=new Ae(t,e):this._label.setLocation(t,e)}},{key:"getEdges",value:function(){return this._edges}},{key:"mergeLabel",value:function(){if(arguments[0]instanceof s){var t=arguments[0];this.mergeLabel(t._label)}else if(arguments[0]instanceof Ae)for(var e=arguments[0],n=0;n<2;n++){var r=this.computeMergedLocation(e,n);this._label.getLocation(n)===Z.NONE&&this._label.setLocation(n,r)}}},{key:"add",value:function(t){this._edges.insert(t),t.setNode(this)}},{key:"setLabelBoundary",value:function(t){if(null===this._label)return null;var e=Z.NONE;null!==this._label&&(e=this._label.getLocation(t));var n=null;switch(e){case Z.BOUNDARY:n=Z.INTERIOR;break;case Z.INTERIOR:default:n=Z.BOUNDARY}this._label.setLocation(t,n)}}],[{key:"constructor_",value:function(){this._coord=null,this._edges=null;var t=arguments[0],e=arguments[1];this._coord=t,this._edges=e,this._label=new Ae(0,Z.NONE)}}]),s}(Ve),Be=function(e){r(i,e);var n=c(i);function i(){return t(this,i),n.apply(this,arguments)}return i}(ne);function Ye(t){return null==t?0:t.color}function ze(t){return null==t?null:t.parent}function je(t,e){null!==t&&(t.color=e)}function Xe(t){return null==t?null:t.left}function Ue(t){return null==t?null:t.right}var Ze=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),(e=i.call(this)).root_=null,e.size_=0,e}return n(o,[{key:"get",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return e.value;e=e.right}}return null}},{key:"put",value:function(t,e){if(null===this.root_)return this.root_={key:t,value:e,left:null,right:null,parent:null,color:0,getValue:function(){return this.value},getKey:function(){return this.key}},this.size_=1,null;var n,r,i=this.root_;do{if(n=i,(r=t.compareTo(i.key))<0)i=i.left;else{if(!(r>0)){var o=i.value;return i.value=e,o}i=i.right}}while(null!==i);var s={key:t,left:null,right:null,value:e,parent:n,color:0,getValue:function(){return this.value},getKey:function(){return this.key}};return r<0?n.left=s:n.right=s,this.fixAfterInsertion(s),this.size_++,null}},{key:"fixAfterInsertion",value:function(t){var e;for(t.color=1;null!=t&&t!==this.root_&&1===t.parent.color;)ze(t)===Xe(ze(ze(t)))?1===Ye(e=Ue(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Ue(ze(t))&&(t=ze(t),this.rotateLeft(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateRight(ze(ze(t)))):1===Ye(e=Xe(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Xe(ze(t))&&(t=ze(t),this.rotateRight(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateLeft(ze(ze(t))));this.root_.color=0}},{key:"values",value:function(){var t=new dt,e=this.getFirstEntry();if(null!==e)for(t.add(e.value);null!==(e=o.successor(e));)t.add(e.value);return t}},{key:"entrySet",value:function(){var t=new Q,e=this.getFirstEntry();if(null!==e)for(t.add(e);null!==(e=o.successor(e));)t.add(e);return t}},{key:"rotateLeft",value:function(t){if(null!=t){var e=t.right;t.right=e.left,null!=e.left&&(e.left.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.left===t?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}}},{key:"rotateRight",value:function(t){if(null!=t){var e=t.left;t.left=e.right,null!=e.right&&(e.right.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.right===t?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}}},{key:"getFirstEntry",value:function(){var t=this.root_;if(null!=t)for(;null!=t.left;)t=t.left;return t}},{key:"size",value:function(){return this.size_}},{key:"containsKey",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return!0;e=e.right}}return!1}}],[{key:"successor",value:function(t){var e;if(null===t)return null;if(null!==t.right){for(e=t.right;null!==e.left;)e=e.left;return e}e=t.parent;for(var n=t;null!==e&&n===e.right;)n=e,e=e.parent;return e}}]),o}(Be),He=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"find",value:function(t){return this.nodeMap.get(t)}},{key:"addNode",value:function(){if(arguments[0]instanceof z){var t=arguments[0],e=this.nodeMap.get(t);return null===e&&(e=this.nodeFact.createNode(t),this.nodeMap.put(t,e)),e}if(arguments[0]instanceof Ge){var n=arguments[0],r=this.nodeMap.get(n.getCoordinate());return null===r?(this.nodeMap.put(n.getCoordinate(),n),n):(r.mergeLabel(n),r)}}},{key:"print",value:function(t){for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this.nodeMap.values().iterator()}},{key:"values",value:function(){return this.nodeMap.values()}},{key:"getBoundaryNodes",value:function(t){for(var e=new dt,n=this.iterator();n.hasNext();){var r=n.next();r.getLabel().getLocation(t)===Z.BOUNDARY&&e.add(r)}return e}},{key:"add",value:function(t){var e=t.getCoordinate();this.addNode(e).add(t)}}],[{key:"constructor_",value:function(){this.nodeMap=new Ze,this.nodeFact=null;var t=arguments[0];this.nodeFact=t}}]),e}(),We=function(){function e(){t(this,e)}return n(e,null,[{key:"isNorthern",value:function(t){return t===e.NE||t===e.NW}},{key:"isOpposite",value:function(t,e){return t!==e&&2==(t-e+4)%4}},{key:"commonHalfPlane",value:function(t,e){if(t===e)return t;if(2==(t-e+4)%4)return-1;var n=te?t:e)?3:n}},{key:"isInHalfPlane",value:function(t,n){return n===e.SE?t===e.SE||t===e.SW:t===n||t===n+1}},{key:"quadrant",value:function(){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1];if(0===t&&0===n)throw new x("Cannot compute the quadrant for point ( "+t+", "+n+" )");return t>=0?n>=0?e.NE:e.SE:n>=0?e.NW:e.SW}if(arguments[0]instanceof z&&arguments[1]instanceof z){var r=arguments[0],i=arguments[1];if(i.x===r.x&&i.y===r.y)throw new x("Cannot compute the quadrant for two identical points "+r);return i.x>=r.x?i.y>=r.y?e.NE:e.SE:i.y>=r.y?e.NW:e.SW}}}]),e}();We.NE=0,We.NW=1,We.SW=2,We.SE=3;var Je=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareDirection",value:function(t){return this._dx===t._dx&&this._dy===t._dy?0:this._quadrant>t._quadrant?1:this._quadrant2){o.linkDirectedEdgesForMinimalEdgeRings();var s=o.buildMinimalRings(),a=this.findShell(s);null!==a?(this.placePolygonHoles(a,s),e.add(a)):n.addAll(s)}else r.add(o)}return r}},{key:"buildMaximalEdgeRings",value:function(t){for(var e=new dt,n=t.iterator();n.hasNext();){var r=n.next();if(r.isInResult()&&r.getLabel().isArea()&&null===r.getEdgeRing()){var i=new qe(r,this._geometryFactory);e.add(i),i.setInResult()}}return e}},{key:"placePolygonHoles",value:function(t,e){for(var n=e.iterator();n.hasNext();){var r=n.next();r.isHole()&&r.setShell(t)}}},{key:"getPolygons",value:function(){return this.computePolygons(this._shellList)}},{key:"findShell",value:function(t){for(var e=0,n=null,r=t.iterator();r.hasNext();){var i=r.next();i.isHole()||(n=i,e++)}return V.isTrue(e<=1,"found two shells in MinimalEdgeRing list"),n}},{key:"add",value:function(){if(1===arguments.length){var t=arguments[0];this.add(t.getEdgeEnds(),t.getNodes())}else if(2===arguments.length){var e=arguments[0],n=arguments[1];$e.linkResultDirectedEdges(n);var r=this.buildMaximalEdgeRings(e),i=new dt,o=this.buildMinimalEdgeRings(r,this._shellList,i);this.sortShellsAndHoles(o,this._shellList,i),this.placeFreeHoles(this._shellList,i)}}}],[{key:"constructor_",value:function(){this._geometryFactory=null,this._shellList=new dt;var t=arguments[0];this._geometryFactory=t}},{key:"findEdgeRingContaining",value:function(t,e){for(var n=t.getLinearRing(),r=n.getEnvelopeInternal(),i=n.getCoordinateN(0),o=null,s=null,a=e.iterator();a.hasNext();){var u=a.next(),l=u.getLinearRing(),h=l.getEnvelopeInternal();if(!h.equals(r)&&h.contains(r)){i=Wt.ptNotInList(n.getCoordinates(),l.getCoordinates());var c=!1;Oe.isInRing(i,l.getCoordinates())&&(c=!0),c&&(null===o||s.contains(h))&&(s=(o=u).getLinearRing().getEnvelopeInternal())}}return o}}]),e}(),en=function(){function e(){t(this,e)}return n(e,[{key:"getBounds",value:function(){}}]),e}(),nn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getItem",value:function(){return this._item}},{key:"getBounds",value:function(){return this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){this._bounds=null,this._item=null;var t=arguments[0],e=arguments[1];this._bounds=t,this._item=e}}]),e}(),rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"poll",value:function(){if(this.isEmpty())return null;var t=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),t}},{key:"size",value:function(){return this._size}},{key:"reorder",value:function(t){for(var e=null,n=this._items.get(t);2*t<=this._size&&((e=2*t)!==this._size&&this._items.get(e+1).compareTo(this._items.get(e))<0&&e++,this._items.get(e).compareTo(n)<0);t=e)this._items.set(t,this._items.get(e));this._items.set(t,n)}},{key:"clear",value:function(){this._size=0,this._items.clear()}},{key:"peek",value:function(){return this.isEmpty()?null:this._items.get(1)}},{key:"isEmpty",value:function(){return 0===this._size}},{key:"add",value:function(t){this._items.add(null),this._size+=1;var e=this._size;for(this._items.set(0,t);t.compareTo(this._items.get(Math.trunc(e/2)))<0;e/=2)this._items.set(e,this._items.get(Math.trunc(e/2)));this._items.set(e,t)}}],[{key:"constructor_",value:function(){this._size=null,this._items=null,this._size=0,this._items=new dt,this._items.add(null)}}]),e}(),on=function(){function e(){t(this,e)}return n(e,[{key:"insert",value:function(t,e){}},{key:"remove",value:function(t,e){}},{key:"query",value:function(){}}]),e}(),sn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLevel",value:function(){return this._level}},{key:"size",value:function(){return this._childBoundables.size()}},{key:"getChildBoundables",value:function(){return this._childBoundables}},{key:"addChildBoundable",value:function(t){V.isTrue(null===this._bounds),this._childBoundables.add(t)}},{key:"isEmpty",value:function(){return this._childBoundables.isEmpty()}},{key:"getBounds",value:function(){return null===this._bounds&&(this._bounds=this.computeBounds()),this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){if(this._childBoundables=new dt,this._bounds=null,this._level=null,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._level=t}}}]),e}(),an={reverseOrder:function(){return{compare:function(t,e){return e.compareTo(t)}}},min:function(t){return an.sort(t),t.get(0)},sort:function(t,e){var n=t.toArray();e?At.sort(n,e):At.sort(n);for(var r=t.iterator(),i=0,o=n.length;ie.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,!1,t,n),null):(this.expand(this._boundable2,this._boundable1,!0,t,n),null);if(r)return this.expand(this._boundable1,this._boundable2,!1,t,n),null;if(i)return this.expand(this._boundable2,this._boundable1,!0,t,n),null;throw new x("neither boundable is composite")}},{key:"isLeaves",value:function(){return!(e.isComposite(this._boundable1)||e.isComposite(this._boundable2))}},{key:"compareTo",value:function(t){var e=t;return this._distancee._distance?1:0}},{key:"expand",value:function(t,n,r,i,o){for(var s=t.getChildBoundables().iterator();s.hasNext();){var a=s.next(),u=null;(u=r?new e(n,a,this._itemDistance):new e(a,n,this._itemDistance)).getDistance()-2),r.getLevel()===n)return i.add(r),null;for(var o=r.getChildBoundables().iterator();o.hasNext();){var s=o.next();s instanceof sn?this.boundablesAtLevel(n,s,i):(V.isTrue(s instanceof nn),-1===n&&i.add(s))}return null}}},{key:"query",value:function(){if(1===arguments.length){var t=arguments[0];this.build();var e=new dt;return this.isEmpty()||this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.queryInternal(t,this._root,e),e}if(2===arguments.length){var n=arguments[0],r=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),n)&&this.queryInternal(n,this._root,r)}}},{key:"build",value:function(){if(this._built)return null;this._root=this._itemBoundables.isEmpty()?this.createNode(0):this.createHigherLevels(this._itemBoundables,-1),this._itemBoundables=null,this._built=!0}},{key:"getRoot",value:function(){return this.build(),this._root}},{key:"remove",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];return this.build(),!!this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.remove(t,this._root,e)}if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],o=this.removeItem(r,i);if(o)return!0;for(var s=null,a=r.getChildBoundables().iterator();a.hasNext();){var u=a.next();if(this.getIntersectsOp().intersects(u.getBounds(),n)&&u instanceof sn&&(o=this.remove(n,u,i))){s=u;break}}return null!==s&&s.getChildBoundables().isEmpty()&&r.getChildBoundables().remove(s),o}}},{key:"createHigherLevels",value:function(t,e){V.isTrue(!t.isEmpty());var n=this.createParentBoundables(t,e+1);return 1===n.size()?n.get(0):this.createHigherLevels(n,e+1)}},{key:"depth",value:function(){if(0===arguments.length)return this.isEmpty()?0:(this.build(),this.depth(this._root));if(1===arguments.length){for(var t=0,e=arguments[0].getChildBoundables().iterator();e.hasNext();){var n=e.next();if(n instanceof sn){var r=this.depth(n);r>t&&(t=r)}}return t+1}}},{key:"createParentBoundables",value:function(t,e){V.isTrue(!t.isEmpty());var n=new dt;n.add(this.createNode(e));var r=new dt(t);an.sort(r,this.getComparator());for(var i=r.iterator();i.hasNext();){var o=i.next();this.lastNode(n).getChildBoundables().size()===this.getNodeCapacity()&&n.add(this.createNode(e)),this.lastNode(n).addChildBoundable(o)}return n}},{key:"isEmpty",value:function(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){if(this._root=null,this._built=!1,this._itemBoundables=new dt,this._nodeCapacity=null,0===arguments.length)e.constructor_.call(this,e.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];V.isTrue(t>1,"Node capacity must be greater than 1"),this._nodeCapacity=t}}},{key:"compareDoubles",value:function(t,e){return t>e?1:t0);for(var n=new dt,r=0;r=0;){var u=o.poll(),l=u.getDistance();if(l>=i)break;u.isLeaves()?a.size()l&&(a.poll(),a.add(u)),i=a.peek().getDistance()):u.expandToQueue(o,i)}return s.getItems(a)}}},{key:"createNode",value:function(t){return new pn(t)}},{key:"size",value:function(){return 0===arguments.length?f(i(s.prototype),"size",this).call(this):f(i(s.prototype),"size",this).apply(this,arguments)}},{key:"insert",value:function(){if(!(2===arguments.length&&arguments[1]instanceof Object&&arguments[0]instanceof X))return f(i(s.prototype),"insert",this).apply(this,arguments);var t=arguments[0],e=arguments[1];if(t.isNull())return null;f(i(s.prototype),"insert",this).call(this,t,e)}},{key:"getIntersectsOp",value:function(){return s.intersectsOp}},{key:"verticalSlices",value:function(t,e){for(var n=Math.trunc(Math.ceil(t.size()/e)),r=new Array(e).fill(null),i=t.iterator(),o=0;o0;){var s=o.poll(),a=s.getDistance();if(a>=r)break;s.isLeaves()?(r=a,i=s):s.expandToQueue(o,r)}return null===i?null:[i.getBoundable(0).getItem(),i.getBoundable(1).getItem()]}}else{if(2===arguments.length){var u=arguments[0],l=arguments[1];if(this.isEmpty()||u.isEmpty())return null;var h=new ln(this.getRoot(),u.getRoot(),l);return this.nearestNeighbour(h)}if(3===arguments.length){var c=arguments[2],f=new nn(arguments[0],arguments[1]),g=new ln(this.getRoot(),f,c);return this.nearestNeighbour(g)[0]}if(4===arguments.length){var p=arguments[2],v=arguments[3],d=new nn(arguments[0],arguments[1]),y=new ln(this.getRoot(),d,p);return this.nearestNeighbourK(y,v)}}}},{key:"isWithinDistance",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1],n=A.POSITIVE_INFINITY,r=new rn;for(r.add(t);!r.isEmpty();){var i=r.poll(),o=i.getDistance();if(o>e)return!1;if(i.maximumDistance()<=e)return!0;if(i.isLeaves()){if((n=o)<=e)return!0}else i.expandToQueue(r,n)}return!1}if(3===arguments.length){var s=arguments[0],a=arguments[1],u=arguments[2],l=new ln(this.getRoot(),s.getRoot(),a);return this.isWithinDistance(l,u)}}},{key:"interfaces_",get:function(){return[on,w]}}],[{key:"constructor_",value:function(){if(0===arguments.length)s.constructor_.call(this,s.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];cn.constructor_.call(this,t)}}},{key:"centreX",value:function(t){return s.avg(t.getMinX(),t.getMaxX())}},{key:"avg",value:function(t,e){return(t+e)/2}},{key:"getItems",value:function(t){for(var e=new Array(t.size()).fill(null),n=0;!t.isEmpty();){var r=t.poll();e[n]=r.getBoundable(0).getItem(),n++}return e}},{key:"centreY",value:function(t){return s.avg(t.getMinY(),t.getMaxY())}}]),s}(cn),pn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"computeBounds",value:function(){for(var t=null,e=this.getChildBoundables().iterator();e.hasNext();){var n=e.next();null===t?t=new X(n.getBounds()):t.expandToInclude(n.getBounds())}return t}}],[{key:"constructor_",value:function(){var t=arguments[0];sn.constructor_.call(this,t)}}]),o}(sn);gn.STRtreeNode=pn,gn.xComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreX(t.getBounds()),gn.centreX(e.getBounds()))}}]),e}()),gn.yComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreY(t.getBounds()),gn.centreY(e.getBounds()))}}]),e}()),gn.intersectsOp=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[IntersectsOp]}},{key:"intersects",value:function(t,e){return t.intersects(e)}}]),e}()),gn.DEFAULT_NODE_CAPACITY=10;var vn=function(){function e(){t(this,e)}return n(e,null,[{key:"relativeSign",value:function(t,e){return te?1:0}},{key:"compare",value:function(t,n,r){if(n.equals2D(r))return 0;var i=e.relativeSign(n.x,r.x),o=e.relativeSign(n.y,r.y);switch(t){case 0:return e.compareValue(i,o);case 1:return e.compareValue(o,i);case 2:return e.compareValue(o,-i);case 3:return e.compareValue(-i,o);case 4:return e.compareValue(-i,-o);case 5:return e.compareValue(-o,-i);case 6:return e.compareValue(-o,i);case 7:return e.compareValue(i,-o)}return V.shouldNeverReachHere("invalid octant value"),0}},{key:"compareValue",value:function(t,e){return t<0?-1:t>0?1:e<0?-1:e>0?1:0}}]),e}(),dn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this.coord}},{key:"print",value:function(t){t.print(this.coord),t.print(" seg # = "+this.segmentIndex)}},{key:"compareTo",value:function(t){var e=t;return this.segmentIndexe.segmentIndex?1:this.coord.equals2D(e.coord)?0:this._isInterior?e._isInterior?vn.compare(this._segmentOctant,this.coord,e.coord):1:-1}},{key:"isEndPoint",value:function(t){return 0===this.segmentIndex&&!this._isInterior||this.segmentIndex===t}},{key:"toString",value:function(){return this.segmentIndex+":"+this.coord.toString()}},{key:"isInterior",value:function(){return this._isInterior}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;var t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this._segString=t,this.coord=new z(e),this.segmentIndex=n,this._segmentOctant=r,this._isInterior=!e.equals2D(t.getCoordinate(n))}}]),e}(),yn=function(){function e(){t(this,e)}return n(e,[{key:"hasNext",value:function(){}},{key:"next",value:function(){}},{key:"remove",value:function(){}}]),e}(),mn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getSplitCoordinates",value:function(){var t=new Ht;this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next();this.addEdgeCoordinates(n,r,t),n=r}return t.toCoordinateArray()}},{key:"addCollapsedNodes",value:function(){var t=new dt;this.findCollapsesFromInsertedNodes(t),this.findCollapsesFromExistingVertices(t);for(var e=t.iterator();e.hasNext();){var n=e.next().intValue();this.add(this._edge.getCoordinate(n),n)}}},{key:"createSplitEdgePts",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2;if(2===n)return[new z(t.coord),new z(e.coord)];var r=this._edge.getCoordinate(e.segmentIndex),i=e.isInterior()||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this._edge.getCoordinate(a);return i&&(o[s]=new z(e.coord)),o}},{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"findCollapsesFromExistingVertices",value:function(t){for(var e=0;e=0?n>=0?r>=i?0:1:r>=i?7:6:n>=0?r>=i?3:2:r>=i?4:5}if(arguments[0]instanceof z&&arguments[1]instanceof z){var o=arguments[0],s=arguments[1],a=s.x-o.x,u=s.y-o.y;if(0===a&&0===u)throw new x("Cannot compute the octant for two identical points "+o);return e.octant(a,u)}}}]),e}(),xn=function(){function e(){t(this,e)}return n(e,[{key:"getCoordinates",value:function(){}},{key:"size",value:function(){}},{key:"getCoordinate",value:function(t){}},{key:"isClosed",value:function(){}},{key:"setData",value:function(t){}},{key:"getData",value:function(){}}]),e}(),En=function(){function e(){t(this,e)}return n(e,[{key:"addIntersection",value:function(t,e){}},{key:"interfaces_",get:function(){return[xn]}}]),e}(),kn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinates",value:function(){return this._pts}},{key:"size",value:function(){return this._pts.length}},{key:"getCoordinate",value:function(t){return this._pts[t]}},{key:"isClosed",value:function(){return this._pts[0].equals(this._pts[this._pts.length-1])}},{key:"getSegmentOctant",value:function(t){return t===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(t),this.getCoordinate(t+1))}},{key:"setData",value:function(t){this._data=t}},{key:"safeOctant",value:function(t,e){return t.equals2D(e)?0:_n.octant(t,e)}},{key:"getData",value:function(){return this._data}},{key:"addIntersection",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];this.addIntersectionNode(t,e)}else if(4===arguments.length){var n=arguments[1],r=arguments[3],i=new z(arguments[0].getIntersection(r));this.addIntersection(i,n)}}},{key:"toString",value:function(){return Le.toLineString(new $t(this._pts))}},{key:"getNodeList",value:function(){return this._nodeList}},{key:"addIntersectionNode",value:function(t,e){var n=e,r=n+1;if(r=0&&r>=0||n<=0&&r<=0?Math.max(n,r):0}if(arguments[0]instanceof z){var i=arguments[0];return ft.index(this.p0,this.p1,i)}}},{key:"toGeometry",value:function(t){return t.createLineString([this.p0,this.p1])}},{key:"isVertical",value:function(){return this.p0.x===this.p1.x}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.p0.equals(n.p0)&&this.p1.equals(n.p1)}},{key:"intersection",value:function(t){var e=new Ce;return e.computeIntersection(this.p0,this.p1,t.p0,t.p1),e.hasIntersection()?e.getIntersection(0):null}},{key:"project",value:function(){if(arguments[0]instanceof z){var t=arguments[0];if(t.equals(this.p0)||t.equals(this.p1))return new z(t);var n=this.projectionFactor(t),r=new z;return r.x=this.p0.x+n*(this.p1.x-this.p0.x),r.y=this.p0.y+n*(this.p1.y-this.p0.y),r}if(arguments[0]instanceof e){var i=arguments[0],o=this.projectionFactor(i.p0),s=this.projectionFactor(i.p1);if(o>=1&&s>=1)return null;if(o<=0&&s<=0)return null;var a=this.project(i.p0);o<0&&(a=this.p0),o>1&&(a=this.p1);var u=this.project(i.p1);return s<0&&(u=this.p0),s>1&&(u=this.p1),new e(a,u)}}},{key:"normalize",value:function(){this.p1.compareTo(this.p0)<0&&this.reverse()}},{key:"angle",value:function(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)}},{key:"getCoordinate",value:function(t){return 0===t?this.p0:this.p1}},{key:"distancePerpendicular",value:function(t){return kt.pointToLinePerpendicular(t,this.p0,this.p1)}},{key:"minY",value:function(){return Math.min(this.p0.y,this.p1.y)}},{key:"midPoint",value:function(){return e.midPoint(this.p0,this.p1)}},{key:"projectionFactor",value:function(t){if(t.equals(this.p0))return 0;if(t.equals(this.p1))return 1;var e=this.p1.x-this.p0.x,n=this.p1.y-this.p0.y,r=e*e+n*n;return r<=0?A.NaN:((t.x-this.p0.x)*e+(t.y-this.p0.y)*n)/r}},{key:"closestPoints",value:function(t){var e=this.intersection(t);if(null!==e)return[e,e];var n=new Array(2).fill(null),r=A.MAX_VALUE,i=null,o=this.closestPoint(t.p0);r=o.distance(t.p0),n[0]=o,n[1]=t.p0;var s=this.closestPoint(t.p1);(i=s.distance(t.p1))0&&e<1?this.project(t):this.p0.distance(t)1||A.isNaN(e))&&(e=1),e}},{key:"toString",value:function(){return"LINESTRING( "+this.p0.x+" "+this.p0.y+", "+this.p1.x+" "+this.p1.y+")"}},{key:"isHorizontal",value:function(){return this.p0.y===this.p1.y}},{key:"reflect",value:function(t){var e=this.p1.getY()-this.p0.getY(),n=this.p0.getX()-this.p1.getX(),r=this.p0.getY()*(this.p1.getX()-this.p0.getX())-this.p0.getX()*(this.p1.getY()-this.p0.getY()),i=e*e+n*n,o=e*e-n*n,s=t.getX(),a=t.getY();return new z((-o*s-2*e*n*a-2*e*r)/i,(o*a-2*e*n*s-2*n*r)/i)}},{key:"distance",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return kt.segmentToSegment(this.p0,this.p1,t.p0,t.p1)}if(arguments[0]instanceof z){var n=arguments[0];return kt.pointToSegment(n,this.p0,this.p1)}}},{key:"pointAlong",value:function(t){var e=new z;return e.x=this.p0.x+t*(this.p1.x-this.p0.x),e.y=this.p0.y+t*(this.p1.y-this.p0.y),e}},{key:"hashCode",value:function(){var t=A.doubleToLongBits(this.p0.x);t^=31*A.doubleToLongBits(this.p0.y);var e=Math.trunc(t)^Math.trunc(t>>32),n=A.doubleToLongBits(this.p1.x);return n^=31*A.doubleToLongBits(this.p1.y),e^Math.trunc(n)^Math.trunc(n>>32)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this.p0=null,this.p1=null,0===arguments.length)e.constructor_.call(this,new z,new z);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.p0,t.p1)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.p0=n,this.p1=r}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];e.constructor_.call(this,new z(i,o),new z(s,a))}}},{key:"midPoint",value:function(t,e){return new z((t.x+e.x)/2,(t.y+e.y)/2)}}]),e}(),wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"overlap",value:function(){if(2===arguments.length);else if(4===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[3];arguments[0].getLineSegment(t,this._overlapSeg1),e.getLineSegment(n,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}}}],[{key:"constructor_",value:function(){this._overlapSeg1=new bn,this._overlapSeg2=new bn}}]),e}(),In=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLineSegment",value:function(t,e){e.p0=this._pts[t],e.p1=this._pts[t+1]}},{key:"computeSelect",value:function(t,e,n,r){var i=this._pts[e],o=this._pts[n];if(n-e==1)return r.select(this,e),null;if(!t.intersects(i,o))return null;var s=Math.trunc((e+n)/2);e=t.length-1)return t.length-1;for(var r=We.quadrant(t[n],t[n+1]),i=e+1;in.getId()&&(n.computeOverlaps(i,t),this._nOverlaps++),this._segInt.isDone())return null}}}],[{key:"constructor_",value:function(){if(this._monoChains=new dt,this._index=new gn,this._idCounter=0,this._nodedSegStrings=null,this._nOverlaps=0,0===arguments.length);else if(1===arguments.length){var t=arguments[0];Mn.constructor_.call(this,t)}}}]),o}(Mn),Pn=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"overlap",value:function(){if(4!==arguments.length)return f(i(s.prototype),"overlap",this).apply(this,arguments);var t=arguments[1],e=arguments[2],n=arguments[3],r=arguments[0].getContext(),o=e.getContext();this._si.processIntersections(r,t,o,n)}}],[{key:"constructor_",value:function(){this._si=null;var t=arguments[0];this._si=t}}]),s}(wn);Ln.SegmentOverlapAction=Pn;var Cn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isDeletable",value:function(t,e,n,r){var i=this._inputLine[t],o=this._inputLine[e],s=this._inputLine[n];return!!this.isConcave(i,o,s)&&!!this.isShallow(i,o,s,r)&&this.isShallowSampled(i,o,t,n,r)}},{key:"deleteShallowConcavities",value:function(){for(var t=1,n=this.findNextNonDeletedIndex(t),r=this.findNextNonDeletedIndex(n),i=!1;r=0;r--)this.addPt(t[r])}},{key:"isRedundant",value:function(t){if(this._ptList.size()<1)return!1;var e=this._ptList.get(this._ptList.size()-1);return t.distance(e)Math.PI;)t-=e.PI_TIMES_2;for(;t<=-Math.PI;)t+=e.PI_TIMES_2;return t}},{key:"angle",value:function(){if(1===arguments.length){var t=arguments[0];return Math.atan2(t.y,t.x)}if(2===arguments.length){var e=arguments[0],n=arguments[1],r=n.x-e.x,i=n.y-e.y;return Math.atan2(i,r)}}},{key:"isAcute",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)>0}},{key:"isObtuse",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)<0}},{key:"interiorAngle",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return Math.abs(o-i)}},{key:"normalizePositive",value:function(t){if(t<0){for(;t<0;)t+=e.PI_TIMES_2;t>=e.PI_TIMES_2&&(t=0)}else{for(;t>=e.PI_TIMES_2;)t-=e.PI_TIMES_2;t<0&&(t=0)}return t}},{key:"angleBetween",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return e.diff(i,o)}},{key:"diff",value:function(t,e){var n=null;return(n=tMath.PI&&(n=2*Math.PI-n),n}},{key:"toRadians",value:function(t){return t*Math.PI/180}},{key:"getTurn",value:function(t,n){var r=Math.sin(n-t);return r>0?e.COUNTERCLOCKWISE:r<0?e.CLOCKWISE:e.NONE}},{key:"angleBetweenOriented",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r)-i;return o<=-Math.PI?o+e.PI_TIMES_2:o>Math.PI?o-e.PI_TIMES_2:o}}]),e}();On.PI_TIMES_2=2*Math.PI,On.PI_OVER_2=Math.PI/2,On.PI_OVER_4=Math.PI/4,On.COUNTERCLOCKWISE=ft.COUNTERCLOCKWISE,On.CLOCKWISE=ft.CLOCKWISE,On.NONE=ft.COLLINEAR;var Rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addNextSegment",value:function(t,e){if(this._s0=this._s1,this._s1=this._s2,this._s2=t,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;var n=ft.index(this._s0,this._s1,this._s2),r=n===ft.CLOCKWISE&&this._side===tt.LEFT||n===ft.COUNTERCLOCKWISE&&this._side===tt.RIGHT;0===n?this.addCollinear(e):r?this.addOutsideTurn(n,e):this.addInsideTurn(n,e)}},{key:"addLineEndCap",value:function(t,e){var n=new bn(t,e),r=new bn;this.computeOffsetSegment(n,tt.LEFT,this._distance,r);var i=new bn;this.computeOffsetSegment(n,tt.RIGHT,this._distance,i);var o=e.x-t.x,s=e.y-t.y,a=Math.atan2(s,o);switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:this._segList.addPt(r.p1),this.addDirectedFillet(e,a+Math.PI/2,a-Math.PI/2,ft.CLOCKWISE,this._distance),this._segList.addPt(i.p1);break;case y.CAP_FLAT:this._segList.addPt(r.p1),this._segList.addPt(i.p1);break;case y.CAP_SQUARE:var u=new z;u.x=Math.abs(this._distance)*Math.cos(a),u.y=Math.abs(this._distance)*Math.sin(a);var l=new z(r.p1.x+u.x,r.p1.y+u.y),h=new z(i.p1.x+u.x,i.p1.y+u.y);this._segList.addPt(l),this._segList.addPt(h)}}},{key:"getCoordinates",value:function(){return this._segList.getCoordinates()}},{key:"addMitreJoin",value:function(t,e,n,r){var i=_t.intersection(e.p0,e.p1,n.p0,n.p1);if(null!==i&&(r<=0?1:i.distance(t)/Math.abs(r))<=this._bufParams.getMitreLimit())return this._segList.addPt(i),null;this.addLimitedMitreJoin(e,n,r,this._bufParams.getMitreLimit())}},{key:"addOutsideTurn",value:function(t,n){if(this._offset0.p1.distance(this._offset1.p0)=h&&(a-=2*Math.PI),this._segList.addPt(e),this.addDirectedFillet(t,a,h,r,i),this._segList.addPt(n)}},{key:"addLastSegment",value:function(){this._segList.addPt(this._offset1.p1)}},{key:"initSideSegments",value:function(t,e,n){this._s1=t,this._s2=e,this._side=n,this._seg1.setCoordinates(t,e),this.computeOffsetSegment(this._seg1,n,this._distance,this._offset1)}},{key:"addLimitedMitreJoin",value:function(t,e,n,r){var i=this._seg0.p1,o=On.angle(i,this._seg0.p0),s=On.angleBetweenOriented(this._seg0.p0,i,this._seg1.p1)/2,a=On.normalize(o+s),u=On.normalize(a+Math.PI),l=r*n,h=n-l*Math.abs(Math.sin(s)),c=i.x+l*Math.cos(u),f=i.y+l*Math.sin(u),g=new z(c,f),p=new bn(i,g),v=p.pointAlongOffset(1,h),d=p.pointAlongOffset(1,-h);this._side===tt.LEFT?(this._segList.addPt(v),this._segList.addPt(d)):(this._segList.addPt(d),this._segList.addPt(v))}},{key:"addDirectedFillet",value:function(t,e,n,r,i){var o=r===ft.CLOCKWISE?-1:1,s=Math.abs(e-n),a=Math.trunc(s/this._filletAngleQuantum+.5);if(a<1)return null;for(var u=s/a,l=new z,h=0;h0){var r=new z((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(r);var i=new z((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(i)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}}},{key:"createCircle",value:function(t){var e=new z(t.x+this._distance,t.y);this._segList.addPt(e),this.addDirectedFillet(t,0,2*Math.PI,-1,this._distance),this._segList.closeRing()}},{key:"addBevelJoin",value:function(t,e){this._segList.addPt(t.p1),this._segList.addPt(e.p0)}},{key:"init",value:function(t){this._distance=t,this._maxCurveSegmentError=t*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new Tn,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(t*e.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)}},{key:"addCollinear",value:function(t){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2),this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===y.JOIN_BEVEL||this._bufParams.getJoinStyle()===y.JOIN_MITRE?(t&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,ft.CLOCKWISE,this._distance))}},{key:"closeRing",value:function(){this._segList.closeRing()}},{key:"hasNarrowConcaveAngle",value:function(){return this._hasNarrowConcaveAngle}}],[{key:"constructor_",value:function(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new bn,this._seg1=new bn,this._offset0=new bn,this._offset1=new bn,this._side=0,this._hasNarrowConcaveAngle=!1;var t=arguments[0],n=arguments[1],r=arguments[2];this._precisionModel=t,this._bufParams=n,this._li=new Ce,this._filletAngleQuantum=Math.PI/2/n.getQuadrantSegments(),n.getQuadrantSegments()>=8&&n.getJoinStyle()===y.JOIN_ROUND&&(this._closingSegLengthFactor=e.MAX_CLOSING_SEG_LEN_FACTOR),this.init(r)}}]),e}();Rn.OFFSET_SEGMENT_SEPARATION_FACTOR=.001,Rn.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR=.001,Rn.CURVE_VERTEX_SNAP_DISTANCE_FACTOR=1e-6,Rn.MAX_CLOSING_SEG_LEN_FACTOR=80;var An=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getOffsetCurve",value:function(t,e){if(this._distance=e,0===e)return null;var n=e<0,r=Math.abs(e),i=this.getSegGen(r);t.length<=1?this.computePointCurve(t[0],i):this.computeOffsetCurve(t,n,i);var o=i.getCoordinates();return n&&Wt.reverse(o),o}},{key:"computeSingleSidedBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){n.addSegments(t,!0);var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{n.addSegments(t,!1);var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment(),n.closeRing()}},{key:"computeRingBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);e===tt.RIGHT&&(r=-r);var i=Cn.simplify(t,r),o=i.length-1;n.initSideSegments(i[o-1],i[0],e);for(var s=1;s<=o;s++){var a=1!==s;n.addNextSegment(i[s],a)}n.closeRing()}},{key:"computeLineBufferCurve",value:function(t,e){var n=this.simplifyTolerance(this._distance),r=Cn.simplify(t,n),i=r.length-1;e.initSideSegments(r[0],r[1],tt.LEFT);for(var o=2;o<=i;o++)e.addNextSegment(r[o],!0);e.addLastSegment(),e.addLineEndCap(r[i-1],r[i]);var s=Cn.simplify(t,-n),a=s.length-1;e.initSideSegments(s[a],s[a-1],tt.LEFT);for(var u=a-2;u>=0;u--)e.addNextSegment(s[u],!0);e.addLastSegment(),e.addLineEndCap(s[1],s[0]),e.closeRing()}},{key:"computePointCurve",value:function(t,e){switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:e.createCircle(t);break;case y.CAP_SQUARE:e.createSquare(t)}}},{key:"getLineCurve",value:function(t,e){if(this._distance=e,this.isLineOffsetEmpty(e))return null;var n=Math.abs(e),r=this.getSegGen(n);if(t.length<=1)this.computePointCurve(t[0],r);else if(this._bufParams.isSingleSided()){var i=e<0;this.computeSingleSidedBufferCurve(t,i,r)}else this.computeLineBufferCurve(t,r);return r.getCoordinates()}},{key:"getBufferParameters",value:function(){return this._bufParams}},{key:"simplifyTolerance",value:function(t){return t*this._bufParams.getSimplifyFactor()}},{key:"getRingCurve",value:function(t,n,r){if(this._distance=r,t.length<=2)return this.getLineCurve(t,r);if(0===r)return e.copyCoordinates(t);var i=this.getSegGen(r);return this.computeRingBufferCurve(t,n,i),i.getCoordinates()}},{key:"computeOffsetCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment()}},{key:"isLineOffsetEmpty",value:function(t){return 0===t||t<0&&!this._bufParams.isSingleSided()}},{key:"getSegGen",value:function(t){return new Rn(this._precisionModel,this._bufParams,t)}}],[{key:"constructor_",value:function(){this._distance=0,this._precisionModel=null,this._bufParams=null;var t=arguments[0],e=arguments[1];this._precisionModel=t,this._bufParams=e}},{key:"copyCoordinates",value:function(t){for(var e=new Array(t.length).fill(null),n=0;ni.getMaxY()||this.findStabbedSegments(t,r.getDirectedEdges(),e)}return e}if(3===arguments.length)if(ot(arguments[2],rt)&&arguments[0]instanceof z&&arguments[1]instanceof Ke){for(var o=arguments[0],s=arguments[1],a=arguments[2],u=s.getEdge().getCoordinates(),l=0;lthis._seg.p1.y&&this._seg.reverse(),!(Math.max(this._seg.p0.x,this._seg.p1.x)this._seg.p1.y||ft.index(this._seg.p0,this._seg.p1,o)===ft.RIGHT)){var h=s.getDepth(tt.LEFT);this._seg.p0.equals(u[l])||(h=s.getDepth(tt.RIGHT));var c=new Fn(this._seg,h);a.add(c)}}else if(ot(arguments[2],rt)&&arguments[0]instanceof z&&ot(arguments[1],rt))for(var f=arguments[0],g=arguments[2],p=arguments[1].iterator();p.hasNext();){var v=p.next();v.isForward()&&this.findStabbedSegments(f,v,g)}}},{key:"getDepth",value:function(t){var e=this.findStabbedSegments(t);return 0===e.size()?0:an.min(e)._leftDepth}}],[{key:"constructor_",value:function(){this._subgraphs=null,this._seg=new bn;var t=arguments[0];this._subgraphs=t}}]),e}(),Fn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var e=t;if(this._upwardSeg.minX()>=e._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=e._upwardSeg.minX())return-1;var n=this._upwardSeg.orientationIndex(e._upwardSeg);return 0!==n||0!=(n=-1*e._upwardSeg.orientationIndex(this._upwardSeg))?n:this._upwardSeg.compareTo(e._upwardSeg)}},{key:"compareX",value:function(t,e){var n=t.p0.compareTo(e.p0);return 0!==n?n:t.p1.compareTo(e.p1)}},{key:"toString",value:function(){return this._upwardSeg.toString()}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._upwardSeg=null,this._leftDepth=null;var t=arguments[0],e=arguments[1];this._upwardSeg=new bn(t),this._leftDepth=e}}]),e}();Dn.DepthSegment=Fn;var qn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){_.constructor_.call(this,"Projective point not representable on the Cartesian plane.")}}]),o}(_),Vn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getY",value:function(){var t=this.y/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getX",value:function(){var t=this.x/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getCoordinate",value:function(){var t=new z;return t.x=this.getX(),t.y=this.getY(),t}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.w=null,0===arguments.length)this.x=0,this.y=0,this.w=1;else if(1===arguments.length){var t=arguments[0];this.x=t.x,this.y=t.y,this.w=1}else if(2===arguments.length){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var n=arguments[0],r=arguments[1];this.x=n,this.y=r,this.w=1}else if(arguments[0]instanceof e&&arguments[1]instanceof e){var i=arguments[0],o=arguments[1];this.x=i.y*o.w-o.y*i.w,this.y=o.x*i.w-i.x*o.w,this.w=i.x*o.y-o.x*i.y}else if(arguments[0]instanceof z&&arguments[1]instanceof z){var s=arguments[0],a=arguments[1];this.x=s.y-a.y,this.y=a.x-s.x,this.w=s.x*a.y-a.x*s.y}}else if(3===arguments.length){var u=arguments[0],l=arguments[1],h=arguments[2];this.x=u,this.y=l,this.w=h}else if(4===arguments.length){var c=arguments[0],f=arguments[1],g=arguments[2],p=arguments[3],v=c.y-f.y,d=f.x-c.x,y=c.x*f.y-f.x*c.y,m=g.y-p.y,_=p.x-g.x,x=g.x*p.y-p.x*g.y;this.x=d*x-_*y,this.y=m*y-v*x,this.w=v*_-m*d}}}]),e}(),Gn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"area",value:function(){return e.area(this.p0,this.p1,this.p2)}},{key:"signedArea",value:function(){return e.signedArea(this.p0,this.p1,this.p2)}},{key:"interpolateZ",value:function(t){if(null===t)throw new x("Supplied point is null.");return e.interpolateZ(t,this.p0,this.p1,this.p2)}},{key:"longestSideLength",value:function(){return e.longestSideLength(this.p0,this.p1,this.p2)}},{key:"isAcute",value:function(){return e.isAcute(this.p0,this.p1,this.p2)}},{key:"circumcentre",value:function(){return e.circumcentre(this.p0,this.p1,this.p2)}},{key:"area3D",value:function(){return e.area3D(this.p0,this.p1,this.p2)}},{key:"centroid",value:function(){return e.centroid(this.p0,this.p1,this.p2)}},{key:"inCentre",value:function(){return e.inCentre(this.p0,this.p1,this.p2)}}],[{key:"constructor_",value:function(){this.p0=null,this.p1=null,this.p2=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.p0=t,this.p1=e,this.p2=n}},{key:"area",value:function(t,e,n){return Math.abs(((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2)}},{key:"signedArea",value:function(t,e,n){return((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2}},{key:"det",value:function(t,e,n,r){return t*r-e*n}},{key:"interpolateZ",value:function(t,e,n,r){var i=e.x,o=e.y,s=n.x-i,a=r.x-i,u=n.y-o,l=r.y-o,h=s*l-a*u,c=t.x-i,f=t.y-o,g=(l*c-a*f)/h,p=(-u*c+s*f)/h;return e.getZ()+g*(n.getZ()-e.getZ())+p*(r.getZ()-e.getZ())}},{key:"longestSideLength",value:function(t,e,n){var r=t.distance(e),i=e.distance(n),o=n.distance(t),s=r;return i>s&&(s=i),o>s&&(s=o),s}},{key:"circumcentreDD",value:function(t,e,n){var r=lt.valueOf(t.x).subtract(n.x),i=lt.valueOf(t.y).subtract(n.y),o=lt.valueOf(e.x).subtract(n.x),s=lt.valueOf(e.y).subtract(n.y),a=lt.determinant(r,i,o,s).multiply(2),u=r.sqr().add(i.sqr()),l=o.sqr().add(s.sqr()),h=lt.determinant(i,u,s,l),c=lt.determinant(r,u,o,l),f=lt.valueOf(n.x).subtract(h.divide(a)).doubleValue(),g=lt.valueOf(n.y).add(c.divide(a)).doubleValue();return new z(f,g)}},{key:"isAcute",value:function(t,e,n){return!!On.isAcute(t,e,n)&&!!On.isAcute(e,n,t)&&!!On.isAcute(n,t,e)}},{key:"circumcentre",value:function(t,n,r){var i=r.x,o=r.y,s=t.x-i,a=t.y-o,u=n.x-i,l=n.y-o,h=2*e.det(s,a,u,l),c=e.det(a,s*s+a*a,l,u*u+l*l),f=e.det(s,s*s+a*a,u,u*u+l*l);return new z(i-c/h,o+f/h)}},{key:"perpendicularBisector",value:function(t,e){var n=e.x-t.x,r=e.y-t.y,i=new Vn(t.x+n/2,t.y+r/2,1),o=new Vn(t.x-r+n/2,t.y+n+r/2,1);return new Vn(i,o)}},{key:"angleBisector",value:function(t,e,n){var r=e.distance(t),i=r/(r+e.distance(n)),o=n.x-t.x,s=n.y-t.y;return new z(t.x+i*o,t.y+i*s)}},{key:"area3D",value:function(t,e,n){var r=e.x-t.x,i=e.y-t.y,o=e.getZ()-t.getZ(),s=n.x-t.x,a=n.y-t.y,u=n.getZ()-t.getZ(),l=i*u-o*a,h=o*s-r*u,c=r*a-i*s,f=l*l+h*h+c*c;return Math.sqrt(f)/2}},{key:"centroid",value:function(t,e,n){var r=(t.x+e.x+n.x)/3,i=(t.y+e.y+n.y)/3;return new z(r,i)}},{key:"inCentre",value:function(t,e,n){var r=e.distance(n),i=t.distance(n),o=t.distance(e),s=r+i+o,a=(r*t.x+i*e.x+o*n.x)/s,u=(r*t.y+i*e.y+o*n.y)/s;return new z(a,u)}}]),e}(),Bn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addRingSide",value:function(t,e,n,r,i){if(0===e&&t.length=zt.MINIMUM_VALID_SIZE&&ft.isCCW(t)&&(o=i,s=r,n=tt.opposite(n));var a=this._curveBuilder.getRingCurve(t,n,e);this.addCurve(a,o,s)}},{key:"addRingBothSides",value:function(t,e){this.addRingSide(t,e,tt.LEFT,Z.EXTERIOR,Z.INTERIOR),this.addRingSide(t,e,tt.RIGHT,Z.INTERIOR,Z.EXTERIOR)}},{key:"addPoint",value:function(t){if(this._distance<=0)return null;var e=t.getCoordinates(),n=this._curveBuilder.getLineCurve(e,this._distance);this.addCurve(n,Z.EXTERIOR,Z.INTERIOR)}},{key:"addPolygon",value:function(t){var e=this._distance,n=tt.LEFT;this._distance<0&&(e=-this._distance,n=tt.RIGHT);var r=t.getExteriorRing(),i=Wt.removeRepeatedPoints(r.getCoordinates());if(this._distance<0&&this.isErodedCompletely(r,this._distance))return null;if(this._distance<=0&&i.length<3)return null;this.addRingSide(i,e,n,Z.EXTERIOR,Z.INTERIOR);for(var o=0;o0&&this.isErodedCompletely(s,-this._distance)||this.addRingSide(a,e,tt.opposite(n),Z.INTERIOR,Z.EXTERIOR)}}},{key:"isTriangleErodedCompletely",value:function(t,e){var n=new Gn(t[0],t[1],t[2]),r=n.inCentre();return kt.pointToSegment(r,n.p0,n.p1)i}},{key:"addCollection",value:function(t){for(var e=0;e=this._max)throw new W;var t=this._parent.getGeometryN(this._index++);return t instanceof Bt?(this._subcollectionIterator=new e(t),this._subcollectionIterator.next()):t}},{key:"remove",value:function(){throw new J(this.getClass().getName())}},{key:"hasNext",value:function(){if(this._atStart)return!0;if(null!==this._subcollectionIterator){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)}},{key:"interfaces_",get:function(){return[yn]}}],[{key:"constructor_",value:function(){this._parent=null,this._atStart=null,this._max=null,this._index=null,this._subcollectionIterator=null;var t=arguments[0];this._parent=t,this._atStart=!0,this._index=0,this._max=t.getNumGeometries()}},{key:"isAtomic",value:function(t){return!(t instanceof Bt)}}]),e}(),jn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"locate",value:function(t){return e.locate(t,this._geom)}},{key:"interfaces_",get:function(){return[Yn]}}],[{key:"constructor_",value:function(){this._geom=null;var t=arguments[0];this._geom=t}},{key:"locatePointInPolygon",value:function(t,n){if(n.isEmpty())return Z.EXTERIOR;var r=n.getExteriorRing(),i=e.locatePointInRing(t,r);if(i!==Z.INTERIOR)return i;for(var o=0;o=0;n--){var r=this._edgeList.get(n),i=r.getSym();null===e&&(e=i),null!==t&&i.setNext(t),t=r}e.setNext(t)}},{key:"computeDepths",value:function(){if(1===arguments.length){var t=arguments[0],e=this.findIndex(t),n=t.getDepth(tt.LEFT),r=t.getDepth(tt.RIGHT),i=this.computeDepths(e+1,this._edgeList.size(),n);if(this.computeDepths(0,e,i)!==r)throw new pt("depth mismatch at "+t.getCoordinate())}else if(3===arguments.length){for(var o=arguments[1],s=arguments[2],a=arguments[0];a=0;i--){var o=this._resultAreaEdgeList.get(i),s=o.getSym();switch(null===e&&o.getEdgeRing()===t&&(e=o),r){case this._SCANNING_FOR_INCOMING:if(s.getEdgeRing()!==t)continue;n=s,r=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(o.getEdgeRing()!==t)continue;n.setNextMin(o),r=this._SCANNING_FOR_INCOMING}}r===this._LINKING_TO_OUTGOING&&(V.isTrue(null!==e,"found null for first outgoing dirEdge"),V.isTrue(e.getEdgeRing()===t,"unable to link last incoming dirEdge"),n.setNextMin(e))}},{key:"getOutgoingDegree",value:function(){if(0===arguments.length){for(var t=0,e=this.iterator();e.hasNext();)e.next().isInResult()&&t++;return t}if(1===arguments.length){for(var n=arguments[0],r=0,i=this.iterator();i.hasNext();)i.next().getEdgeRing()===n&&r++;return r}}},{key:"getLabel",value:function(){return this._label}},{key:"findCoveredLineEdges",value:function(){for(var t=Z.NONE,e=this.iterator();e.hasNext();){var n=e.next(),r=n.getSym();if(!n.isLineEdge()){if(n.isInResult()){t=Z.INTERIOR;break}if(r.isInResult()){t=Z.EXTERIOR;break}}}if(t===Z.NONE)return null;for(var i=t,o=this.iterator();o.hasNext();){var s=o.next(),a=s.getSym();s.isLineEdge()?s.getEdge().setCovered(i===Z.INTERIOR):(s.isInResult()&&(i=Z.EXTERIOR),a.isInResult()&&(i=Z.INTERIOR))}}},{key:"computeLabelling",value:function(t){f(i(s.prototype),"computeLabelling",this).call(this,t),this._label=new Ae(Z.NONE);for(var e=this.iterator();e.hasNext();)for(var n=e.next().getEdge().getLabel(),r=0;r<2;r++){var o=n.getLocation(r);o!==Z.INTERIOR&&o!==Z.BOUNDARY||this._label.setLocation(r,Z.INTERIOR)}}}],[{key:"constructor_",value:function(){this._resultAreaEdgeList=null,this._label=null,this._SCANNING_FOR_INCOMING=1,this._LINKING_TO_OUTGOING=2}}]),s}(Xn),Zn=function(e){r(o,e);var i=c(o);function o(){return t(this,o),i.call(this)}return n(o,[{key:"createNode",value:function(t){return new Ge(t,new Un)}}]),o}(Qe),Hn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var n=t;return e.compareOriented(this._pts,this._orientation,n._pts,n._orientation)}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._pts=null,this._orientation=null;var t=arguments[0];this._pts=t,this._orientation=e.orientation(t)}},{key:"orientation",value:function(t){return 1===Wt.increasingDirection(t)}},{key:"compareOriented",value:function(t,e,n,r){for(var i=e?1:-1,o=r?1:-1,s=e?t.length:-1,a=r?n.length:-1,u=e?0:t.length-1,l=r?0:n.length-1;;){var h=t[u].compareTo(n[l]);if(0!==h)return h;var c=(u+=i)===s,f=(l+=o)===a;if(c&&!f)return-1;if(!c&&f)return 1;if(c&&f)return 0}}}]),e}(),Wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.print("MULTILINESTRING ( ");for(var e=0;e0&&t.print(","),t.print("(");for(var r=n.getCoordinates(),i=0;i0&&t.print(","),t.print(r[i].x+" "+r[i].y);t.println(")")}t.print(") ")}},{key:"addAll",value:function(t){for(var e=t.iterator();e.hasNext();)this.add(e.next())}},{key:"findEdgeIndex",value:function(t){for(var e=0;et?1:this.diste?1:0}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this.coord=null,this.segmentIndex=null,this.dist=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.coord=new z(t),this.segmentIndex=e,this.dist=n}}]),e}(),$n=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this._nodeMap.values().iterator()}},{key:"addSplitEdges",value:function(t){this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next(),i=this.createSplitEdge(n,r);t.add(i),n=r}}},{key:"addEndpoints",value:function(){var t=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[t],t,0)}},{key:"createSplitEdge",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2,r=this.edge.pts[e.segmentIndex],i=e.dist>0||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this.edge.pts[a];return i&&(o[s]=e.coord),new or(o,new Ae(this.edge._label))}},{key:"add",value:function(t,e,n){var r=new Qn(t,e,n),i=this._nodeMap.get(r);return null!==i?i:(this._nodeMap.put(r,r),r)}},{key:"isIntersection",value:function(t){for(var e=this.iterator();e.hasNext();)if(e.next().coord.equals(t))return!0;return!1}}],[{key:"constructor_",value:function(){this._nodeMap=new Ze,this.edge=null;var t=arguments[0];this.edge=t}}]),e}(),tr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isIntersects",value:function(){return!this.isDisjoint()}},{key:"isCovers",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"isCoveredBy",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"set",value:function(){if(1===arguments.length)for(var t=arguments[0],e=0;e=0&&e>=0&&this.setAtLeast(t,e,n)}},{key:"isWithin",value:function(){return e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"isTouches",value:function(t,n){return t>n?this.isTouches(n,t):(t===Mt.A&&n===Mt.A||t===Mt.L&&n===Mt.L||t===Mt.L&&n===Mt.A||t===Mt.P&&n===Mt.A||t===Mt.P&&n===Mt.L)&&this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&(e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))}},{key:"isOverlaps",value:function(t,n){return t===Mt.P&&n===Mt.P||t===Mt.A&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&1===this._matrix[Z.INTERIOR][Z.INTERIOR]&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR])}},{key:"isEquals",value:function(t,n){return t===n&&e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"toString",value:function(){for(var t=new Qt("123456789"),e=0;e<3;e++)for(var n=0;n<3;n++)t.setCharAt(3*e+n,Mt.toDimensionSymbol(this._matrix[e][n]));return t.toString()}},{key:"setAll",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this._matrix[e][n]=t}},{key:"get",value:function(t,e){return this._matrix[t][e]}},{key:"transpose",value:function(){var t=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=t,t=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=t,t=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=t,this}},{key:"matches",value:function(t){if(9!==t.length)throw new x("Should be length 9: "+t);for(var n=0;n<3;n++)for(var r=0;r<3;r++)if(!e.matches(this._matrix[n][r],t.charAt(3*n+r)))return!1;return!0}},{key:"add",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this.setAtLeast(e,n,t.get(e,n))}},{key:"isDisjoint",value:function(){return this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.INTERIOR][Z.BOUNDARY]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.BOUNDARY]===Mt.FALSE}},{key:"isCrosses",value:function(t,n){return t===Mt.P&&n===Mt.L||t===Mt.P&&n===Mt.A||t===Mt.L&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR]):t===Mt.L&&n===Mt.P||t===Mt.A&&n===Mt.P||t===Mt.A&&n===Mt.L?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&0===this._matrix[Z.INTERIOR][Z.INTERIOR]}},{key:"interfaces_",get:function(){return[b]}}],[{key:"constructor_",value:function(){if(this._matrix=null,0===arguments.length)this._matrix=Array(3).fill().map((function(){return Array(3)})),this.setAll(Mt.FALSE);else if(1===arguments.length)if("string"==typeof arguments[0]){var t=arguments[0];e.constructor_.call(this),this.set(t)}else if(arguments[0]instanceof e){var n=arguments[0];e.constructor_.call(this),this._matrix[Z.INTERIOR][Z.INTERIOR]=n._matrix[Z.INTERIOR][Z.INTERIOR],this._matrix[Z.INTERIOR][Z.BOUNDARY]=n._matrix[Z.INTERIOR][Z.BOUNDARY],this._matrix[Z.INTERIOR][Z.EXTERIOR]=n._matrix[Z.INTERIOR][Z.EXTERIOR],this._matrix[Z.BOUNDARY][Z.INTERIOR]=n._matrix[Z.BOUNDARY][Z.INTERIOR],this._matrix[Z.BOUNDARY][Z.BOUNDARY]=n._matrix[Z.BOUNDARY][Z.BOUNDARY],this._matrix[Z.BOUNDARY][Z.EXTERIOR]=n._matrix[Z.BOUNDARY][Z.EXTERIOR],this._matrix[Z.EXTERIOR][Z.INTERIOR]=n._matrix[Z.EXTERIOR][Z.INTERIOR],this._matrix[Z.EXTERIOR][Z.BOUNDARY]=n._matrix[Z.EXTERIOR][Z.BOUNDARY],this._matrix[Z.EXTERIOR][Z.EXTERIOR]=n._matrix[Z.EXTERIOR][Z.EXTERIOR]}}},{key:"matches",value:function(){if(Number.isInteger(arguments[0])&&"string"==typeof arguments[1]){var t=arguments[0],n=arguments[1];return n===Mt.SYM_DONTCARE||n===Mt.SYM_TRUE&&(t>=0||t===Mt.TRUE)||n===Mt.SYM_FALSE&&t===Mt.FALSE||n===Mt.SYM_P&&t===Mt.P||n===Mt.SYM_L&&t===Mt.L||n===Mt.SYM_A&&t===Mt.A}if("string"==typeof arguments[0]&&"string"==typeof arguments[1]){var r=arguments[1];return new e(arguments[0]).matches(r)}}},{key:"isTrue",value:function(t){return t>=0||t===Mt.TRUE}}]),e}(),er=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"size",value:function(){return this._size}},{key:"addAll",value:function(t){return null===t||0===t.length?null:(this.ensureCapacity(this._size+t.length),xt.arraycopy(t,0,this._data,this._size,t.length),void(this._size+=t.length))}},{key:"ensureCapacity",value:function(t){if(t<=this._data.length)return null;var e=Math.max(t,2*this._data.length);this._data=At.copyOf(this._data,e)}},{key:"toArray",value:function(){var t=new Array(this._size).fill(null);return xt.arraycopy(this._data,0,t,0,this._size),t}},{key:"add",value:function(t){this.ensureCapacity(this._size+1),this._data[this._size]=t,++this._size}}],[{key:"constructor_",value:function(){if(this._data=null,this._size=0,0===arguments.length)e.constructor_.call(this,10);else if(1===arguments.length){var t=arguments[0];this._data=new Array(t).fill(null)}}}]),e}(),nr=function(){function e(){t(this,e)}return n(e,[{key:"getChainStartIndices",value:function(t){var e=0,n=new er(Math.trunc(t.length/2));n.add(e);do{var r=this.findChainEnd(t,e);n.add(r),e=r}while(en?e:n}},{key:"getMinX",value:function(t){var e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return ee&&(r=1),this._depth[t][n]=r}}}},{key:"getDelta",value:function(t){return this._depth[t][tt.RIGHT]-this._depth[t][tt.LEFT]}},{key:"getLocation",value:function(t,e){return this._depth[t][e]<=0?Z.EXTERIOR:Z.INTERIOR}},{key:"toString",value:function(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}},{key:"add",value:function(){if(1===arguments.length)for(var t=arguments[0],n=0;n<2;n++)for(var r=1;r<3;r++){var i=t.getLocation(n,r);i!==Z.EXTERIOR&&i!==Z.INTERIOR||(this.isNull(n,r)?this._depth[n][r]=e.depthAtLocation(i):this._depth[n][r]+=e.depthAtLocation(i))}else if(3===arguments.length){var o=arguments[0],s=arguments[1];arguments[2]===Z.INTERIOR&&this._depth[o][s]++}}}],[{key:"constructor_",value:function(){this._depth=Array(2).fill().map((function(){return Array(3)}));for(var t=0;t<2;t++)for(var n=0;n<3;n++)this._depth[t][n]=e.NULL_VALUE}},{key:"depthAtLocation",value:function(t){return t===Z.EXTERIOR?0:t===Z.INTERIOR?1:e.NULL_VALUE}}]),e}();ir.NULL_VALUE=-1;var or=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getDepth",value:function(){return this._depth}},{key:"getCollapsedEdge",value:function(){var t=new Array(2).fill(null);return t[0]=this.pts[0],t[1]=this.pts[1],new s(t,Ae.toLineLabel(this._label))}},{key:"isIsolated",value:function(){return this._isIsolated}},{key:"getCoordinates",value:function(){return this.pts}},{key:"setIsolated",value:function(t){this._isIsolated=t}},{key:"setName",value:function(t){this._name=t}},{key:"equals",value:function(t){if(!(t instanceof s))return!1;var e=t;if(this.pts.length!==e.pts.length)return!1;for(var n=!0,r=!0,i=this.pts.length,o=0;o0?this.pts[0]:null;if(1===arguments.length){var t=arguments[0];return this.pts[t]}}},{key:"print",value:function(t){t.print("edge "+this._name+": "),t.print("LINESTRING (");for(var e=0;e0&&t.print(","),t.print(this.pts[e].x+" "+this.pts[e].y);t.print(") "+this._label+" "+this._depthDelta)}},{key:"computeIM",value:function(t){s.updateIM(this._label,t)}},{key:"isCollapsed",value:function(){return!!this._label.isArea()&&3===this.pts.length&&!!this.pts[0].equals(this.pts[2])}},{key:"isClosed",value:function(){return this.pts[0].equals(this.pts[this.pts.length-1])}},{key:"getMaximumSegmentIndex",value:function(){return this.pts.length-1}},{key:"getDepthDelta",value:function(){return this._depthDelta}},{key:"getNumPoints",value:function(){return this.pts.length}},{key:"printReverse",value:function(t){t.print("edge "+this._name+": ");for(var e=this.pts.length-1;e>=0;e--)t.print(this.pts[e]+" ");t.println("")}},{key:"getMonotoneChainEdge",value:function(){return null===this._mce&&(this._mce=new rr(this)),this._mce}},{key:"getEnvelope",value:function(){if(null===this._env){this._env=new X;for(var t=0;t0&&t.append(","),t.append(this.pts[e].x+" "+this.pts[e].y);return t.append(") "+this._label+" "+this._depthDelta),t.toString()}},{key:"isPointwiseEqual",value:function(t){if(this.pts.length!==t.pts.length)return!1;for(var e=0;er||this._maxyo;if(s)return!1;var a=this.intersectsToleranceSquare(t,e);return V.isTrue(!(s&&a),"Found bad envelope test"),a}},{key:"initCorners",value:function(t){var e=.5;this._minx=t.x-e,this._maxx=t.x+e,this._miny=t.y-e,this._maxy=t.y+e,this._corner[0]=new z(this._maxx,this._maxy),this._corner[1]=new z(this._minx,this._maxy),this._corner[2]=new z(this._minx,this._miny),this._corner[3]=new z(this._maxx,this._miny)}},{key:"intersects",value:function(t,e){return 1===this._scaleFactor?this.intersectsScaled(t,e):(this.copyScaled(t,this._p0Scaled),this.copyScaled(e,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}},{key:"scale",value:function(t){return Math.round(t*this._scaleFactor)}},{key:"getCoordinate",value:function(){return this._originalPt}},{key:"copyScaled",value:function(t,e){e.x=this.scale(t.x),e.y=this.scale(t.y)}},{key:"getSafeEnvelope",value:function(){if(null===this._safeEnv){var t=e.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new X(this._originalPt.x-t,this._originalPt.x+t,this._originalPt.y-t,this._originalPt.y+t)}return this._safeEnv}},{key:"intersectsPixelClosure",value:function(t,e){return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.hasIntersection()))))}},{key:"intersectsToleranceSquare",value:function(t,e){var n=!1,r=!1;return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.isProper()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.isProper()||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.isProper()||(this._li.hasIntersection()&&(r=!0),this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.isProper()||n&&r||t.equals(this._pt)||e.equals(this._pt)))))}},{key:"addSnappedNode",value:function(t,e){var n=t.getCoordinate(e),r=t.getCoordinate(e+1);return!!this.intersects(n,r)&&(t.addIntersection(this.getCoordinate(),e),!0)}}],[{key:"constructor_",value:function(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;var t=arguments[0],e=arguments[1],n=arguments[2];if(this._originalPt=t,this._pt=t,this._scaleFactor=e,this._li=n,e<=0)throw new x("Scale factor must be non-zero");1!==e&&(this._pt=new z(this.scale(t.x),this.scale(t.y)),this._p0Scaled=new z,this._p1Scaled=new z),this.initCorners(this._pt)}}]),e}();lr.SAFE_ENV_EXPANSION_FACTOR=.75;var hr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"select",value:function(){if(1===arguments.length);else if(2===arguments.length){var t=arguments[1];arguments[0].getLineSegment(t,this.selectedSegment),this.select(this.selectedSegment)}}}],[{key:"constructor_",value:function(){this.selectedSegment=new bn}}]),e}(),cr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"snap",value:function(){if(1===arguments.length){var e=arguments[0];return this.snap(e,null,-1)}if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=r.getSafeEnvelope(),a=new fr(r,i,o);return this._index.query(s,new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[hn]}},{key:"visitItem",value:function(t){t.select(s,a)}}]),e}())),a.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var t=arguments[0];this._index=t}}]),e}(),fr=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isNodeAdded",value:function(){return this._isNodeAdded}},{key:"select",value:function(){if(!(2===arguments.length&&Number.isInteger(arguments[1])&&arguments[0]instanceof In))return f(i(s.prototype),"select",this).apply(this,arguments);var t=arguments[1],e=arguments[0].getContext();if(this._parentEdge===e&&(t===this._hotPixelVertexIndex||t+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(e,t)}}],[{key:"constructor_",value:function(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var t=arguments[0],e=arguments[1],n=arguments[2];this._hotPixel=t,this._parentEdge=e,this._hotPixelVertexIndex=n}}]),s}(hr);cr.HotPixelSnapAction=fr;var gr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"processIntersections",value:function(t,e,n,r){if(t===n&&e===r)return null;var i=t.getCoordinates()[e],o=t.getCoordinates()[e+1],s=n.getCoordinates()[r],a=n.getCoordinates()[r+1];if(this._li.computeIntersection(i,o,s,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var u=0;u=0;t--){try{this.bufferReducedPrecision(t)}catch(t){if(!(t instanceof pt))throw t;this._saveException=t}if(null!==this._resultGeometry)return null}throw this._saveException}if(1===arguments.length){var n=arguments[0],r=e.precisionScaleFactor(this._argGeom,this._distance,n),i=new ie(r);this.bufferFixedPrecision(i)}}},{key:"computeGeometry",value:function(){if(this.bufferOriginalPrecision(),null!==this._resultGeometry)return null;var t=this._argGeom.getFactory().getPrecisionModel();t.getType()===ie.FIXED?this.bufferFixedPrecision(t):this.bufferReducedPrecision()}},{key:"setQuadrantSegments",value:function(t){this._bufParams.setQuadrantSegments(t)}},{key:"bufferOriginalPrecision",value:function(){try{var t=new sr(this._bufParams);this._resultGeometry=t.buffer(this._argGeom,this._distance)}catch(t){if(!(t instanceof F))throw t;this._saveException=t}}},{key:"getResultGeometry",value:function(t){return this._distance=t,this.computeGeometry(),this._resultGeometry}},{key:"setEndCapStyle",value:function(t){this._bufParams.setEndCapStyle(t)}}],[{key:"constructor_",value:function(){if(this._argGeom=null,this._distance=null,this._bufParams=new y,this._resultGeometry=null,this._saveException=null,1===arguments.length){var t=arguments[0];this._argGeom=t}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this._argGeom=e,this._bufParams=n}}},{key:"bufferOp",value:function(){if(2===arguments.length){var t=arguments[1];return new e(arguments[0]).getResultGeometry(t)}if(3===arguments.length){if(Number.isInteger(arguments[2])&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var n=arguments[1],r=arguments[2],i=new e(arguments[0]);return i.setQuadrantSegments(r),i.getResultGeometry(n)}if(arguments[2]instanceof y&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var o=arguments[1];return new e(arguments[0],arguments[2]).getResultGeometry(o)}}else if(4===arguments.length){var s=arguments[1],a=arguments[2],u=arguments[3],l=new e(arguments[0]);return l.setQuadrantSegments(a),l.setEndCapStyle(u),l.getResultGeometry(s)}}},{key:"precisionScaleFactor",value:function(t,e,n){var r=t.getEnvelopeInternal(),i=Et.max(Math.abs(r.getMaxX()),Math.abs(r.getMaxY()),Math.abs(r.getMinX()),Math.abs(r.getMinY()))+2*(e>0?e:0),o=n-Math.trunc(Math.log(i)/Math.log(10)+1);return Math.pow(10,o)}}]),e}();vr.CAP_ROUND=y.CAP_ROUND,vr.CAP_BUTT=y.CAP_FLAT,vr.CAP_FLAT=y.CAP_FLAT,vr.CAP_SQUARE=y.CAP_SQUARE,vr.MAX_PRECISION_DIGITS=12;var dr=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],yr=function(){function e(n){t(this,e),this.geometryFactory=n||new ae}return n(e,[{key:"read",value:function(t){var e,n=(e="string"==typeof t?JSON.parse(t):t).type;if(!mr[n])throw new Error("Unknown GeoJSON type: "+e.type);return-1!==dr.indexOf(n)?mr[n].call(this,e.coordinates):"GeometryCollection"===n?mr[n].call(this,e.geometries):mr[n].call(this,e)}},{key:"write",value:function(t){var e=t.getGeometryType();if(!_r[e])throw new Error("Geometry is not supported");return _r[e].call(this,t)}}]),e}(),mr={Feature:function(t){var e={};for(var n in t)e[n]=t[n];if(t.geometry){var r=t.geometry.type;if(!mr[r])throw new Error("Unknown GeoJSON type: "+t.type);e.geometry=this.read(t.geometry)}return t.bbox&&(e.bbox=mr.bbox.call(this,t.bbox)),e},FeatureCollection:function(t){var e={};if(t.features){e.features=[];for(var n=0;n1?0:t<-1?Xn:Math.acos(t)}function ir(t){return t>1?Un:t<-1?-Un:Math.asin(t)}function or(){}function sr(t,e){t&&ur.hasOwnProperty(t.type)&&ur[t.type](t,e)}var ar={Feature:function(t,e){sr(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++rXn?t-Hn:t<-Xn?t+Hn:t,e]}function xr(t){return function(e,n){return[(e+=t)>Xn?e-Hn:e<-Xn?e+Hn:e,n]}}function Er(t){var e=xr(t);return e.invert=xr(-t),e}function kr(t,e){var n=tr(t),r=er(t),i=tr(e),o=er(e);function s(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*n+a*r;return[$n(u*i-h*o,a*n-l*r),ir(h*i+u*o)]}return s.invert=function(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*i-u*o;return[$n(u*i+l*o,a*n+h*r),ir(h*n-a*r)]},s}function br(t,e){(e=fr(e))[0]-=t,yr(e);var n=rr(-e[1]);return((-e[2]<0?-n:n)+Hn-jn)%Hn}function wr(){var t,e=[];return{point:function(e,n){t.push([e,n])},lineStart:function(){e.push(t=[])},lineEnd:or,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function Ir(t,e){return Kn(t[0]-e[0])=0;--o)i.point((h=l[o])[0],h[1]);else r(f.x,f.p.x,-1,i);f=f.p}l=(f=f.o).z,g=!g}while(!f.v);i.lineEnd()}}}function Mr(t){if(e=t.length){for(var e,n,r=0,i=t[0];++re?1:t>=e?0:NaN}function Pr(t){for(var e,n,r,i=t.length,o=-1,s=0;++o=0;)for(e=(r=t[i]).length;--e>=0;)n[--s]=r[e];return n}Gn(),Gn(),Gn(),_r.invert=_r,function(t){var e;1===t.length&&(e=t,t=function(t,n){return Lr(e(t),n)})}(Lr);var Cr=1e9,Tr=-Cr;function Or(t,e,n,r){function i(i,o){return t<=i&&i<=n&&e<=o&&o<=r}function o(i,o,a,l){var h=0,c=0;if(null==i||(h=s(i,a))!==(c=s(o,a))||u(i,o)<0^a>0)do{l.point(0===h||3===h?t:n,h>1?r:e)}while((h=(h+a+4)%4)!==c);else l.point(o[0],o[1])}function s(r,i){return Kn(r[0]-t)0?0:3:Kn(r[0]-n)0?2:1:Kn(r[1]-e)0?1:0:i>0?3:2}function a(t,e){return u(t.x,e.x)}function u(t,e){var n=s(t,1),r=s(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){var u,l,h,c,f,g,p,v,d,y,m,_=s,x=wr(),E={point:k,lineStart:function(){E.point=b,l&&l.push(h=[]);y=!0,d=!1,p=v=NaN},lineEnd:function(){u&&(b(c,f),g&&d&&x.rejoin(),u.push(x.result()));E.point=k,d&&_.lineEnd()},polygonStart:function(){_=x,u=[],l=[],m=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,i=l.length;nr&&(f-o)*(r-s)>(g-s)*(t-o)&&++e:g<=r&&(f-o)*(r-s)<(g-s)*(t-o)&&--e;return e}(),n=m&&e,i=(u=Pr(u)).length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),o(null,null,1,s),s.lineEnd()),i&&Sr(u,a,e,o,s),s.polygonEnd());_=s,u=l=h=null}};function k(t,e){i(t,e)&&_.point(t,e)}function b(o,s){var a=i(o,s);if(l&&h.push([o,s]),y)c=o,f=s,g=a,y=!1,a&&(_.lineStart(),_.point(o,s));else if(a&&d)_.point(o,s);else{var u=[p=Math.max(Tr,Math.min(Cr,p)),v=Math.max(Tr,Math.min(Cr,v))],x=[o=Math.max(Tr,Math.min(Cr,o)),s=Math.max(Tr,Math.min(Cr,s))];!function(t,e,n,r,i,o){var s,a=t[0],u=t[1],l=0,h=1,c=e[0]-a,f=e[1]-u;if(s=n-a,c||!(s>0)){if(s/=c,c<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=i-a,c||!(s<0)){if(s/=c,c<0){if(s>h)return;s>l&&(l=s)}else if(c>0){if(s0)){if(s/=f,f<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=o-u,f||!(s<0)){if(s/=f,f<0){if(s>h)return;s>l&&(l=s)}else if(f>0){if(s0&&(t[0]=a+l*c,t[1]=u+l*f),h<1&&(e[0]=a+h*c,e[1]=u+h*f),!0}}}}}(u,x,t,e,n,r)?a&&(_.lineStart(),_.point(o,s),m=!1):(d||(_.lineStart(),_.point(u[0],u[1])),_.point(x[0],x[1]),a||_.lineEnd(),m=!1)}p=o,v=s,d=a}return E}}var Rr=Gn();function Ar(t){return t}Gn(),Gn(),Gn();var Dr=1/0,Fr=Dr,qr=-Dr,Vr=qr,Gr={point:function(t,e){tqr&&(qr=t);eVr&&(Vr=e)},lineStart:or,lineEnd:or,polygonStart:or,polygonEnd:or,result:function(){var t=[[Dr,Fr],[qr,Vr]];return qr=Vr=-(Fr=Dr=1/0),t}};function Br(t,e,n,r){return function(i,o){var s,a,u,l=e(o),h=i.invert(r[0],r[1]),c=wr(),f=e(c),g=!1,p={point:v,lineStart:y,lineEnd:m,polygonStart:function(){p.point=_,p.lineStart=x,p.lineEnd=E,a=[],s=[]},polygonEnd:function(){p.point=v,p.lineStart=y,p.lineEnd=m,a=Pr(a);var t=function(t,e){var n=e[0],r=e[1],i=[er(n),-tr(n),0],o=0,s=0;Rr.reset();for(var a=0,u=t.length;a=0?1:-1,w=b*k,I=w>Xn,N=p*x;if(Rr.add($n(N*b*er(w),v*E+N*tr(w))),o+=I?k+b*Hn:k,I^f>=n^m>=n){var S=pr(fr(c),fr(y));yr(S);var M=pr(i,S);yr(M);var L=(I^k>=0?-1:1)*ir(M[2]);(r>L||r===L&&(S[0]||S[1]))&&(s+=I^k>=0?1:-1)}}return(o<-jn||o0){for(g||(o.polygonStart(),g=!0),o.lineStart(),t=0;t1&&2&i&&l.push(l.pop().concat(l.shift())),a.push(l.filter(Yr))}return p}}function Yr(t){return t.length>1}function zr(t,e){return((t=t.x)[0]<0?t[1]-Un-jn:Un-t[1])-((e=e.x)[0]<0?e[1]-Un-jn:Un-e[1])}Gn();var jr=Br((function(){return!0}),(function(t){var e,n=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,s){var a=o>0?Xn:-Xn,u=Kn(o-n);Kn(u-Xn)0?Un:-Un),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),e=0):i!==a&&u>=Xn&&(Kn(n-i)jn?Qn((er(e)*(o=tr(r))*er(n)-er(r)*(i=tr(e))*er(t))/(i*o*s)):(e+r)/2}(n,r,o,s),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),e=0),t.point(n=o,r=s),i=a},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var i;if(null==t)i=n*Un,r.point(-Xn,i),r.point(0,i),r.point(Xn,i),r.point(Xn,0),r.point(Xn,-i),r.point(0,-i),r.point(-Xn,-i),r.point(-Xn,0),r.point(-Xn,i);else if(Kn(t[0]-e[0])>jn){var o=t[0]0,i=Kn(n)>jn;function o(t,e){return tr(t)*tr(e)>n}function s(t,e,r){var i=[1,0,0],o=pr(fr(t),fr(e)),s=gr(o,o),a=o[0],u=s-a*a;if(!u)return!r&&t;var l=n*s/u,h=-n*a/u,c=pr(i,o),f=dr(i,l);vr(f,dr(o,h));var g=c,p=gr(f,g),v=gr(g,g),d=p*p-v*(gr(f,f)-1);if(!(d<0)){var y=nr(d),m=dr(g,(-p-y)/v);if(vr(m,f),m=cr(m),!r)return m;var _,x=t[0],E=e[0],k=t[1],b=e[1];E0^m[1]<(Kn(m[0]-x)Xn^(x<=m[0]&&m[0]<=E)){var N=dr(g,(-p+y)/v);return vr(N,f),[m,cr(N)]}}}function a(e,n){var i=r?t:Xn-t,o=0;return e<-i?o|=1:e>i&&(o|=2),n<-i?o|=4:n>i&&(o|=8),o}return Br(o,(function(t){var e,n,u,l,h;return{lineStart:function(){l=u=!1,h=1},point:function(c,f){var g,p=[c,f],v=o(c,f),d=r?v?0:a(c,f):v?a(c+(c<0?Xn:-Xn),f):0;if(!e&&(l=u=v)&&t.lineStart(),v!==u&&(!(g=s(e,p))||Ir(e,g)||Ir(p,g))&&(p[0]+=jn,p[1]+=jn,v=o(p[0],p[1])),v!==u)h=0,v?(t.lineStart(),g=s(p,e),t.point(g[0],g[1])):(g=s(e,p),t.point(g[0],g[1]),t.lineEnd()),e=g;else if(i&&e&&r^v){var y;d&n||!(y=s(p,e,!0))||(h=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1])))}!v||e&&Ir(e,p)||t.point(p[0],p[1]),e=p,u=v,n=d},lineEnd:function(){u&&t.lineEnd(),e=null},clean:function(){return h|(l&&u)<<1}}}),(function(n,r,i,o){!function(t,e,n,r,i,o){if(n){var s=tr(e),a=er(e),u=r*n;null==i?(i=e+r*Hn,o=e-u/2):(i=br(s,i),o=br(s,o),(r>0?io)&&(i+=r*Hn));for(var l,h=i;r>0?h>o:h4*e&&v--){var x=s+f,E=a+g,k=u+p,b=nr(x*x+E*E+k*k),w=ir(k/=b),I=Kn(Kn(k)-1)e||Kn((y*L+m*P)/_-.5)>.3||s*f+a*g+u*p2?t[2]%360*Jn:0,M()):[d*Wn,y*Wn,m*Wn]},I.precision=function(t){return arguments.length?(w=Kr(S,b=t*t),L()):nr(b)},I.fitExtent=function(t,e){return Hr(I,t,e)},I.fitSize=function(t,e){return function(t,e,n){return Hr(t,[[0,0],e],n)}(I,t,e)},function(){return e=t.apply(this,arguments),I.invert=e.invert&&N,M()}}((function(){return t}))()}function ti(t){return function(e,n){var r=tr(e),i=tr(n),o=t(r*i);return[o*i*er(e),o*er(n)]}}function ei(t){return function(e,n){var r=nr(e*e+n*n),i=t(r),o=er(i),s=tr(i);return[$n(e*o,r*s),ir(r&&n*o/r)]}}ti((function(t){return nr(2/(1+t))})).invert=ei((function(t){return 2*ir(t/2)}));var ni=ti((function(t){return(t=rr(t))&&t/er(t)}));function ri(){return $r(ni).scale(79.4188).clipAngle(179.999)}function ii(t,e){return[t,e]}ni.invert=ei((function(t){return t})),ii.invert=ii;var oi=Vn.BufferOp,si=Vn.GeoJSONReader,ai=Vn.GeoJSONWriter;function ui(t,e,n,r){var i=t.properties||{},o="Feature"===t.type?t.geometry:t;if("GeometryCollection"===o.type){var s=[];return mt(t,(function(t){var i=ui(t,e,n,r);i&&s.push(i)})),C(s)}var a=function(t){var e=An(t).geometry.coordinates,n=[-e[0],-e[1]];return ri().rotate(n).scale(x)}(o),u={type:o.type,coordinates:hi(o.coordinates,a)},l=(new si).read(u),h=F(q(e,n),"meters"),c=oi.bufferOp(l,h,r);if(!li((c=(new ai).write(c)).coordinates))return b({type:c.type,coordinates:ci(c.coordinates,a)},i)}function li(t){return Array.isArray(t[0])?li(t[0]):isNaN(t[0])}function hi(t,e){return"object"!==m(t[0])?e(t):t.map((function(t){return hi(t,e)}))}function ci(t,e){return"object"!==m(t[0])?e.invert(t):t.map((function(t){return ci(t,e)}))}function fi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return mt(t,(function(t,o,s){var a=e.weight?null==s?void 0:s[e.weight]:void 0;if(!U(a=null==a?1:a))throw new Error("weight value must be a number for feature index "+o);(a=Number(a))>0&&ct(t,(function(t){n+=t[0]*a,r+=t[1]*a,i+=a}))})),I([n/i,r/i],e.properties,e)}function gi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return ct(t,(function(t){n+=t[0],r+=t[1],i++}),!0),I([n/i,r/i],e.properties)}function pi(t,e,n,r,i){var o=r.tolerance||.001,s=0,a=0,u=0,l=0;if(vt(n,(function(e){var n,r=null==(n=e.properties)?void 0:n.weight,i=null==r?1:r;if(!U(i=Number(i)))throw new Error("weight value must be a number");if(i>0){l+=1;var o=i*ut(e,t);0===o&&(o=1);var h=i/o;s+=e.geometry.coordinates[0]*h,a+=e.geometry.coordinates[1]*h,u+=h}})),l<1)throw new Error("no features to measure");var h=s/u,c=a/u;return 1===l||0===i||Math.abs(h-e[0])0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mi;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function mi(t,e){return te?1:0}var _i,xi,Ei,ki,bi,wi=_n(Object.freeze({__proto__:null,default:yi})),Ii={exports:{}};function Ni(){if(bi)return Ii.exports;bi=1;var t=(xi||(xi=1,_i=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=(r-n)/2,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),_i),e=(ki||(ki=1,Ei=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=r-n,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),Ei);return Ii.exports=function(n,r,i,o){return r.length>0&&Array.isArray(r[0])?e(n,r,i,o):t(n,r,i,o)},Ii.exports.nested=e,Ii.exports.flat=t,Ii.exports}var Si,Mi,Li={exports:{}};Li.exports;function Pi(){return Si||(Si=1,function(t,e){!function(t){var e=134217729,n=33306690738754706e-32;function r(t,e,n,r,i){var o,s,a,u,l=e[0],h=r[0],c=0,f=0;h>l==h>-l?(o=l,l=e[++c]):(o=h,h=r[++f]);var g=0;if(cl==h>-l?(a=o-((s=l+o)-l),l=e[++c]):(a=o-((s=h+o)-h),h=r[++f]),o=s,0!==a&&(i[g++]=a);cl==h>-l?(a=o-((s=o+l)-(u=s-o))+(l-u),l=e[++c]):(a=o-((s=o+h)-(u=s-o))+(h-u),h=r[++f]),o=s,0!==a&&(i[g++]=a);for(;c0!=m>0)return _;var x=Math.abs(y+m);return Math.abs(_)>=o*x?_:-function(t,i,o,g,p,v,d){var y,m,_,x,E,k,b,w,I,N,S,M,L,P,C,T,O,R,A=t-p,D=o-p,F=i-v,q=g-v;E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=q-(I=(k=e*q)-(k-q)))-((P=A*q)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=D-(I=(k=e*D)-(k-D)))-((T=F*D)-b*I-w*I-b*N))),u[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),u[1]=L-(S+E)+(E-T),E=(R=M+S)-M,u[2]=M-(R-E)+(S-E),u[3]=R;var V=function(t,e){for(var n=e[0],r=1;r=G||-V>=G)return V;if(y=t-(A+(E=t-A))+(E-p),_=o-(D+(E=o-D))+(E-p),m=i-(F+(E=i-F))+(E-v),x=g-(q+(E=g-q))+(E-v),0===y&&0===m&&0===_&&0===x)return V;if(G=a*d+n*Math.abs(V),(V+=A*x+q*y-(F*_+D*m))>=G||-V>=G)return V;E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=q-(I=(k=e*q)-(k-q)))-((P=y*q)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=D-(I=(k=e*D)-(k-D)))-((T=m*D)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var B=r(4,u,4,f,l);E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=x-(I=(k=e*x)-(k-x)))-((P=A*x)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=_-(I=(k=e*_)-(k-_)))-((T=F*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var Y=r(B,l,4,f,h);E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=x-(I=(k=e*x)-(k-x)))-((P=y*x)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=_-(I=(k=e*_)-(k-_)))-((T=m*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var z=r(Y,h,4,f,c);return c[z-1]}(t,i,g,p,v,d,x)},t.orient2dfast=function(t,e,n,r,i,o){return(e-o)*(n-i)-(t-i)*(r-o)},Object.defineProperty(t,"__esModule",{value:!0})}(e)}(0,Li.exports)),Li.exports}var Ci=function(){if(Mi)return vi.exports;Mi=1;var t=di,e=wi,n=Ni(),r=Pi().orient2d;function i(e,r,i){r=Math.max(0,void 0===r?2:r),i=i||0;var s=function(t){for(var e=t[0],r=t[0],i=t[0],o=t[0],s=0;si[0]&&(i=a),a[1]o[1]&&(o=a)}var u=[e,r,i,o],l=u.slice();for(s=0;s=2&&h(e[e.length-2],e[e.length-1],t[n])<=0;)e.pop();e.push(t[n])}for(var r=[],i=t.length-1;i>=0;i--){for(;r.length>=2&&h(r[r.length-2],r[r.length-1],t[i])<=0;)r.pop();r.push(t[i])}return r.pop(),e.pop(),e.concat(r)}(l)}(e),a=new t(16);a.toBBox=function(t){return{minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]}},a.compareMinX=function(t,e){return t[0]-e[0]},a.compareMinY=function(t,e){return t[1]-e[1]},a.load(e);for(var u,l=[],p=0;pu||c.push({node:v,dist:d})}for(;c.length&&!c.peek().node.children;){var y=c.pop(),m=y.node,_=p(m,n,r),x=p(m,i,o);if(y.dist<_&&y.dist=e.minX&&t[0]<=e.maxX&&t[1]>=e.minY&&t[1]<=e.maxY}function l(t,e,n){for(var r,i,o,s,a=Math.min(t[0],e[0]),u=Math.min(t[1],e[1]),l=Math.max(t[0],e[0]),c=Math.max(t[1],e[1]),f=n.search({minX:a,minY:u,maxX:l,maxY:c}),g=0;g0!=h(r,i,s)>0&&h(o,s,r)>0!=h(o,s,i)>0)return!1;return!0}function h(t,e,n){return r(t[0],t[1],e[0],e[1],n[0],n[1])}function c(t){var e=t.p,n=t.next.p;return t.minX=Math.min(e[0],n[0]),t.minY=Math.min(e[1],n[1]),t.maxX=Math.max(e[0],n[0]),t.maxY=Math.max(e[1],n[1]),t}function f(t,e){var n={p:t,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return e?(n.next=e.next,n.prev=e,e.next.prev=n,e.next=n):(n.prev=n,n.next=n),n}function g(t,e){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function p(t,e,n){var r=e[0],i=e[1],o=n[0]-r,s=n[1]-i;if(0!==o||0!==s){var a=((t[0]-r)*o+(t[1]-i)*s)/(o*o+s*s);a>1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function v(t,e,n,r,i,o,s,a){var u,l,h,c,f=n-t,g=r-e,p=s-i,v=a-o,d=t-i,y=e-o,m=f*f+g*g,_=f*p+g*v,x=p*p+v*v,E=f*d+g*y,k=p*d+v*y,b=m*x-_*_,w=b,I=b;0===b?(l=0,w=1,c=k,I=x):(c=m*k-_*E,(l=_*k-x*E)<0?(l=0,c=k,I=x):l>w&&(l=w,c=k+_,I=x)),c<0?(c=0,-E<0?l=0:-E>m?l=w:(l=-E,w=m)):c>I&&(c=I,-E+_<0?l=0:-E+_>m?l=w:(l=-E+_,w=m));var N=(1-(h=0===c?0:c/I))*i+h*s-((1-(u=0===l?0:l/w))*t+u*n),S=(1-h)*o+h*a-((1-u)*e+u*r);return N*N+S*S}function d(t,e){return t[0]===e[0]?t[1]-e[1]:t[0]-e[0]}return e.default&&(e=e.default),vi.exports=i,vi.exports.default=i,vi.exports}(),Ti=mn(Ci);function Oi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e.concavity=e.concavity||1/0;var n=[];if(ct(t,(function(t){n.push([t[0],t[1]])})),!n.length)return null;var r=Ti(n,e.concavity);return r.length>3?S([r]):null}function Ri(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.steps||64,i=n.properties?n.properties:!Array.isArray(t)&&"Feature"===t.type&&t.properties?t.properties:{},o=[],s=0;s0;r.length0;){var a=t[Math.floor(Math.random()*o)],u=s?a.join("_"):""+a;n[u]||(n[u]=!0,r.push(a))}if(r.length0,u=t[Math.floor(Math.random()*s)];for(a&&u.join("_"),o.push(u);o.length0,y=[];if(s)u="kmrand"==s?r(t,e):"kmpp"==s?i(t,e):s;else for(var m={};u.lengthc&&(c=t[a].y);var g,p=l-u,v=c-h,d=p>v?p:v,y=.5*(l+u),m=.5*(c+h),_=[new so({__sentinel:!0,x:y-20*d,y:m-d},{__sentinel:!0,x:y,y:m+20*d},{__sentinel:!0,x:y+20*d,y:m-d})],x=[],E=[];a=t.length;for(;a--;){for(E.length=0,g=_.length;g--;)(p=t[a].x-_[g].x)>0&&p*p>_[g].r?(x.push(_[g]),_.splice(g,1)):p*p+(v=t[a].y-_[g].y)*v>_[g].r||(E.push(_[g].a,_[g].b,_[g].b,_[g].c,_[g].c,_[g].a),_.splice(g,1));for(uo(E),g=E.length;g;)n=E[--g],e=E[--g],r=t[a],i=n.x-e.x,o=n.y-e.y,s=2*(i*(r.y-n.y)-o*(r.x-n.x)),Math.abs(s)>f&&_.push(new so(e,n,r))}Array.prototype.push.apply(x,_),a=x.length;for(;a--;)(x[a].a.__sentinel||x[a].b.__sentinel||x[a].c.__sentinel)&&x.splice(a,1);return x}(t.features.map((function(t){var r={x:t.geometry.coordinates[0],y:t.geometry.coordinates[1]};return e?r.z=t.properties[e]:3===t.geometry.coordinates.length&&(n=!0,r.z=t.geometry.coordinates[2]),r}))).map((function(t){var e=[t.a.x,t.a.y],r=[t.b.x,t.b.y],i=[t.c.x,t.c.y],o={};return n?(e.push(t.a.z),r.push(t.b.z),i.push(t.c.z)):o={a:t.a.z,b:t.b.z,c:t.c.z},S([[e,r,i,e]],o)})))}var so=s((function t(e,n,r){i(this,t),this.a=e,this.b=n,this.c=r;var o,s,a=n.x-e.x,u=n.y-e.y,l=r.x-e.x,h=r.y-e.y,c=a*(e.x+n.x)+u*(e.y+n.y),f=l*(e.x+r.x)+h*(e.y+r.y),g=2*(a*(r.y-n.y)-u*(r.x-n.x));this.x=(h*c-u*f)/g,this.y=(a*f-l*c)/g,o=this.x-e.x,s=this.y-e.y,this.r=o*o+s*s}));function ao(t,e){return e.x-t.x}function uo(t){var e,n,r,i,o,s=t.length;t:for(;s;)for(n=t[--s],e=t[--s],r=s;r;)if(o=t[--r],e===(i=t[--r])&&n===o||e===o&&n===i){t.splice(s,2),t.splice(r,2),s-=2;continue t}}function lo(t){return t}function ho(t,e){var n=function(t){if(null==t)return lo;var e,n,r=t.scale[0],i=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,a){a||(e=n=0);var u=2,l=t.length,h=new Array(l);for(h[0]=(e+=t[0])*r+o,h[1]=(n+=t[1])*i+s;u1)for(var o,a,u=1,l=s(i[0]);ul&&(a=i[0],i[0]=i[u],i[u]=a,l=o);return i})).filter((function(t){return t.length>0}))}}var po=Object.prototype.hasOwnProperty;function vo(t,e,n,r,i,o){3===arguments.length&&(r=o=Array,i=null);for(var s=new r(t=1<=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},maybeSet:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},get:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)break;h=s[l=l+1&u]}return o},keys:function(){for(var t=[],e=0,n=s.length;e>7^xo[2]^xo[3])}function ko(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=function(){for(var t=vo(1.4*o.length,E,k,Int32Array,-1,Int32Array),e=new Int32Array(o.length),n=0,r=o.length;n=0){var o=c[n];i===e&&o===r||i===r&&o===e||(++g,f[n]=1)}else h[n]=e,c[n]=r}}function E(t){return Eo(o[t])}function k(t,e){return yo(o[t],o[e])}l=h=c=null;var b,w=function(t,e,n,r,i){3===arguments.length&&(r=Array,i=null);for(var o=new r(t=1<=t)throw new Error("full hashset");u=o[a=a+1&s]}return o[a]=r,!0},has:function(r){for(var a=e(r)&s,u=o[a],l=0;u!=i;){if(n(u,r))return!0;if(++l>=t)break;u=o[a=a+1&s]}return!1},values:function(){for(var t=[],e=0,n=o.length;e>1);er&&(r=o),si&&(i=s)}function u(t){t.forEach(a)}function l(t){t.forEach(u)}for(var h in t)o(t[h]);return r>=e&&i>=n?[e,n,r,i]:void 0}(t=Io(t)),r=function(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=s.length+a.length;for(delete t.lines,delete t.rings,r=0,i=s.length;r1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=[],i=It(t,(function(t,e){var n=function(t,e){var n,r=t.geometry.coordinates,i=e.geometry.coordinates,o=Oo(r[0]),s=Oo(r[r.length-1]),a=Oo(i[0]),u=Oo(i[i.length-1]);if(o===u)n=i.concat(r.slice(1));else if(a===s)n=r.concat(i.slice(1));else if(o===a)n=r.slice(1).reverse().concat(i);else{if(s!==u)return null;n=r.concat(i.reverse().slice(1))}return L(n)}(t,e);return n||(r.push(t),e)}));return i&&r.push(i),r.length?1===r.length?r[0]:T(r.map((function(t){return t.coordinates}))):null}function Oo(t){return t[0].toString()+","+t[1].toString()}function Ro(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=function(t){var e={};xt(t,(function(t){e[t.geometry.type]=!0}));var n=Object.keys(e);if(1===n.length)return n[0];return null}(t);if(!r)throw new Error("geojson must be homogenous");var i=t;switch(r){case"LineString":return To(i,e);case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==e.mutate&&void 0!==e.mutate||(t=Ai(t));var n=[];xt(t,(function(t){n.push(t.geometry)}));var r=Lo({geoms:A(n).geometry});return fo(r,r.objects.geoms.geometries)}(i,e);default:throw new Error(r+" is not supported")}}var Ao=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Do=Math.ceil,Fo=Math.floor,qo="[BigNumber Error] ",Vo=qo+"Number primitive has more than 15 significant digits: ",Go=1e14,Bo=14,Yo=9007199254740991,zo=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Xo=1e9;function Uo(t){var e=0|t;return t>0||t===e?e:e-1}function Zo(t){for(var e,n,r=1,i=t.length,o=t[0]+"";rl^n?1:-1;for(a=(u=i.length)<(l=o.length)?u:l,s=0;so[s]^n?1:-1;return u==l?0:u>l^n?1:-1}function Wo(t,e,n,r){if(tn||t!==Fo(t))throw Error(qo+(r||"Argument")+("number"==typeof t?tn?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Jo(t){var e=t.c.length-1;return Uo(t.e/Bo)==e&&t.c[e]%2!=0}function Ko(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Qo(t,e,n){var r,i;if(e<0){for(i=n+".";++e;i+=n);t=i+t}else if(++e>(r=t.length)){for(i=n,e-=r;--e;i+=n);t+=i}else ex?f.c=f.e=null:t.e<_?f.c=[f.e=0]:(f.e=t.e,f.c=t.c.slice()));if((l="number"==typeof t)&&0*t==0){if(f.s=1/t<0?(t=-t,-1):1,t===~~t){for(a=0,u=t;u>=10;u/=10,a++);return void(a>x?f.c=f.e=null:(f.e=a,f.c=[t]))}c=String(t)}else{if(!Ao.test(c=String(t)))return i(f,c,l);f.s=45==c.charCodeAt(0)?(c=c.slice(1),-1):1}(a=c.indexOf("."))>-1&&(c=c.replace(".","")),(u=c.search(/e/i))>0?(a<0&&(a=u),a+=+c.slice(u+1),c=c.substring(0,u)):a<0&&(a=c.length)}else{if(Wo(e,2,I.length,"Base"),10==e&&N)return C(f=new S(t),p+f.e+1,v);if(c=String(t),l="number"==typeof t){if(0*t!=0)return i(f,c,l,e);if(f.s=1/t<0?(c=c.slice(1),-1):1,S.DEBUG&&c.replace(/^0\.0*|\./,"").length>15)throw Error(Vo+t)}else f.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1;for(n=I.slice(0,e),a=u=0,h=c.length;ua){a=h;continue}}else if(!s&&(c==c.toUpperCase()&&(c=c.toLowerCase())||c==c.toLowerCase()&&(c=c.toUpperCase()))){s=!0,u=-1,a=0;continue}return i(f,String(t),l,e)}l=!1,(a=(c=r(c,e,10,f.s)).indexOf("."))>-1?c=c.replace(".",""):a=c.length}for(u=0;48===c.charCodeAt(u);u++);for(h=c.length;48===c.charCodeAt(--h););if(c=c.slice(u,++h)){if(h-=u,l&&S.DEBUG&&h>15&&(t>Yo||t!==Fo(t)))throw Error(Vo+f.s*t);if((a=a-u-1)>x)f.c=f.e=null;else if(a<_)f.c=[f.e=0];else{if(f.e=a,f.c=[],u=(a+1)%Bo,a<0&&(u+=Bo),u=y)?Ko(u,s):Qo(u,s,"0");else if(o=(t=C(new S(t),e,n)).e,a=(u=Zo(t.c)).length,1==r||2==r&&(e<=o||o<=d)){for(;aa){if(--e>0)for(u+=".";e--;u+="0");}else if((e+=o-a)>0)for(o+1==a&&(u+=".");e--;u+="0");return t.s<0&&i?"-"+u:u}function L(t,e){for(var n,r,i=1,o=new S(t[0]);i=10;i/=10,r++);return(n=r+n*Bo-1)>x?t.c=t.e=null:n<_?t.c=[t.e=0]:(t.e=n,t.c=e),t}function C(t,e,n,r){var i,o,s,a,u,l,h,c=t.c,f=zo;if(c){t:{for(i=1,a=c[0];a>=10;a/=10,i++);if((o=e-i)<0)o+=Bo,s=e,u=c[l=0],h=Fo(u/f[i-s-1]%10);else if((l=Do((o+1)/Bo))>=c.length){if(!r)break t;for(;c.length<=l;c.push(0));u=h=0,i=1,s=(o%=Bo)-Bo+1}else{for(u=a=c[l],i=1;a>=10;a/=10,i++);h=(s=(o%=Bo)-Bo+i)<0?0:Fo(u/f[i-s-1]%10)}if(r=r||e<0||null!=c[l+1]||(s<0?u:u%f[i-s-1]),r=n<4?(h||r)&&(0==n||n==(t.s<0?3:2)):h>5||5==h&&(4==n||r||6==n&&(o>0?s>0?u/f[i-s]:0:c[l-1])%10&1||n==(t.s<0?8:7)),e<1||!c[0])return c.length=0,r?(e-=t.e+1,c[0]=f[(Bo-e%Bo)%Bo],t.e=-e||0):c[0]=t.e=0,t;if(0==o?(c.length=l,a=1,l--):(c.length=l+1,a=f[Bo-o],c[l]=s>0?Fo(u/f[i-s]%f[s])*a:0),r)for(;;){if(0==l){for(o=1,s=c[0];s>=10;s/=10,o++);for(s=c[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(t.e++,c[0]==Go&&(c[0]=1));break}if(c[l]+=a,c[l]!=Go)break;c[l--]=0,a=1}for(o=c.length;0===c[--o];c.pop());}t.e>x?t.c=t.e=null:t.e<_&&(t.c=[t.e=0])}return t}function T(t){var e,n=t.e;return null===n?t.toString():(e=Zo(t.c),e=n<=d||n>=y?Ko(e,n):Qo(e,n,"0"),t.s<0?"-"+e:e)}return S.clone=t,S.ROUND_UP=0,S.ROUND_DOWN=1,S.ROUND_CEIL=2,S.ROUND_FLOOR=3,S.ROUND_HALF_UP=4,S.ROUND_HALF_DOWN=5,S.ROUND_HALF_EVEN=6,S.ROUND_HALF_CEIL=7,S.ROUND_HALF_FLOOR=8,S.EUCLID=9,S.config=S.set=function(t){var e,n;if(null!=t){if("object"!=m(t))throw Error(qo+"Object expected: "+t);if(t.hasOwnProperty(e="DECIMAL_PLACES")&&(Wo(n=t[e],0,Xo,e),p=n),t.hasOwnProperty(e="ROUNDING_MODE")&&(Wo(n=t[e],0,8,e),v=n),t.hasOwnProperty(e="EXPONENTIAL_AT")&&((n=t[e])&&n.pop?(Wo(n[0],-Xo,0,e),Wo(n[1],0,Xo,e),d=n[0],y=n[1]):(Wo(n,-Xo,Xo,e),d=-(y=n<0?-n:n))),t.hasOwnProperty(e="RANGE"))if((n=t[e])&&n.pop)Wo(n[0],-Xo,-1,e),Wo(n[1],1,Xo,e),_=n[0],x=n[1];else{if(Wo(n,-Xo,Xo,e),!n)throw Error(qo+e+" cannot be zero: "+n);_=-(x=n<0?-n:n)}if(t.hasOwnProperty(e="CRYPTO")){if((n=t[e])!==!!n)throw Error(qo+e+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw E=!n,Error(qo+"crypto unavailable");E=n}else E=n}if(t.hasOwnProperty(e="MODULO_MODE")&&(Wo(n=t[e],0,9,e),k=n),t.hasOwnProperty(e="POW_PRECISION")&&(Wo(n=t[e],0,Xo,e),b=n),t.hasOwnProperty(e="FORMAT")){if("object"!=m(n=t[e]))throw Error(qo+e+" not an object: "+n);w=n}if(t.hasOwnProperty(e="ALPHABET")){if("string"!=typeof(n=t[e])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(qo+e+" invalid: "+n);N="0123456789"==n.slice(0,10),I=n}}return{DECIMAL_PLACES:p,ROUNDING_MODE:v,EXPONENTIAL_AT:[d,y],RANGE:[_,x],CRYPTO:E,MODULO_MODE:k,POW_PRECISION:b,FORMAT:w,ALPHABET:I}},S.isBigNumber=function(t){if(!t||!0!==t._isBigNumber)return!1;if(!S.DEBUG)return!0;var e,n,r=t.c,i=t.e,o=t.s;t:if("[object Array]"=={}.toString.call(r)){if((1===o||-1===o)&&i>=-Xo&&i<=Xo&&i===Fo(i)){if(0===r[0]){if(0===i&&1===r.length)return!0;break t}if((e=(i+1)%Bo)<1&&(e+=Bo),String(r[0]).length==e){for(e=0;e=Go||n!==Fo(n))break t;if(0!==n)return!0}}}else if(null===r&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(qo+"Invalid BigNumber: "+t)},S.maximum=S.max=function(){return L(arguments,-1)},S.minimum=S.min=function(){return L(arguments,1)},S.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Fo(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(t){var e,n,r,i,o,a=0,u=[],l=new S(g);if(null==t?t=p:Wo(t,0,Xo),i=Do(t/Bo),E)if(crypto.getRandomValues){for(e=crypto.getRandomValues(new Uint32Array(i*=2));a>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),e[a]=n[0],e[a+1]=n[1]):(u.push(o%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw E=!1,Error(qo+"crypto unavailable");for(e=crypto.randomBytes(i*=7);a=9e15?crypto.randomBytes(7).copy(e,a):(u.push(o%1e14),a+=7);a=i/7}if(!E)for(;a=10;o/=10,a++);an-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(r,i,o,s,a){var u,l,h,c,f,g,d,y,m=r.indexOf("."),_=p,x=v;for(m>=0&&(c=b,b=0,r=r.replace(".",""),g=(y=new S(i)).pow(r.length-m),b=c,y.c=e(Qo(Zo(g.c),g.e,"0"),10,o,t),y.e=y.c.length),h=c=(d=e(r,i,o,a?(u=I,t):(u=t,I))).length;0==d[--c];d.pop());if(!d[0])return u.charAt(0);if(m<0?--h:(g.c=d,g.e=h,g.s=s,d=(g=n(g,y,_,x,o)).c,f=g.r,h=g.e),m=d[l=h+_+1],c=o/2,f=f||l<0||null!=d[l+1],f=x<4?(null!=m||f)&&(0==x||x==(g.s<0?3:2)):m>c||m==c&&(4==x||f||6==x&&1&d[l-1]||x==(g.s<0?8:7)),l<1||!d[0])r=f?Qo(u.charAt(1),-_,u.charAt(0)):u.charAt(0);else{if(d.length=l,f)for(--o;++d[--l]>o;)d[l]=0,l||(++h,d=[1].concat(d));for(c=d.length;!d[--c];);for(m=0,r="";m<=c;r+=u.charAt(d[m++]));r=Qo(r,h,u.charAt(0))}return r}}(),n=function(){function t(t,e,n){var r,i,o,s,a=0,u=t.length,l=e%jo,h=e/jo|0;for(t=t.slice();u--;)a=((i=l*(o=t[u]%jo)+(r=h*o+(s=t[u]/jo|0)*l)%jo*jo+a)/n|0)+(r/jo|0)+h*s,t[u]=i%n;return a&&(t=[a].concat(t)),t}function e(t,e,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;ie[i]?1:-1;break}return o}function n(t,e,n,r){for(var i=0;n--;)t[n]-=i,i=t[n]1;t.splice(0,1));}return function(r,i,o,s,a){var u,l,h,c,f,g,p,v,d,y,m,_,x,E,k,b,w,I=r.s==i.s?1:-1,N=r.c,M=i.c;if(!(N&&N[0]&&M&&M[0]))return new S(r.s&&i.s&&(N?!M||N[0]!=M[0]:M)?N&&0==N[0]||!M?0*I:I/0:NaN);for(d=(v=new S(I)).c=[],I=o+(l=r.e-i.e)+1,a||(a=Go,l=Uo(r.e/Bo)-Uo(i.e/Bo),I=I/Bo|0),h=0;M[h]==(N[h]||0);h++);if(M[h]>(N[h]||0)&&l--,I<0)d.push(1),c=!0;else{for(E=N.length,b=M.length,h=0,I+=2,(f=Fo(a/(M[0]+1)))>1&&(M=t(M,f,a),N=t(N,f,a),b=M.length,E=N.length),x=b,m=(y=N.slice(0,b)).length;m=a/2&&k++;do{if(f=0,(u=e(M,y,b,m))<0){if(_=y[0],b!=m&&(_=_*a+(y[1]||0)),(f=Fo(_/k))>1)for(f>=a&&(f=a-1),p=(g=t(M,f,a)).length,m=y.length;1==e(g,y,p,m);)f--,n(g,b=10;I/=10,h++);C(v,o+(v.e=h+l*Bo-1)+1,s,c)}else v.e=l,v.r=+c;return v}}(),a=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,l=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,c=/^\s*\+(?=[\w.])|^\s+|\s+$/g,i=function(t,e,n,r){var i,o=n?e:e.replace(c,"");if(h.test(o))t.s=isNaN(o)?null:o<0?-1:1;else{if(!n&&(o=o.replace(a,(function(t,e,n){return i="x"==(n=n.toLowerCase())?16:"b"==n?2:8,r&&r!=i?t:e})),r&&(i=r,o=o.replace(u,"$1").replace(l,"0.$1")),e!=o))return new S(o,i);if(S.DEBUG)throw Error(qo+"Not a"+(r?" base "+r:"")+" number: "+e);t.s=null}t.c=t.e=null},f.absoluteValue=f.abs=function(){var t=new S(this);return t.s<0&&(t.s=1),t},f.comparedTo=function(t,e){return Ho(this,new S(t,e))},f.decimalPlaces=f.dp=function(t,e){var n,r,i,o=this;if(null!=t)return Wo(t,0,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t+o.e+1,e);if(!(n=o.c))return null;if(r=((i=n.length-1)-Uo(this.e/Bo))*Bo,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},f.dividedBy=f.div=function(t,e){return n(this,new S(t,e),p,v)},f.dividedToIntegerBy=f.idiv=function(t,e){return n(this,new S(t,e),0,1)},f.exponentiatedBy=f.pow=function(t,e){var n,r,i,o,s,a,u,l,h=this;if((t=new S(t)).c&&!t.isInteger())throw Error(qo+"Exponent not an integer: "+T(t));if(null!=e&&(e=new S(e)),s=t.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!t.c||!t.c[0])return l=new S(Math.pow(+T(h),s?t.s*(2-Jo(t)):+T(t))),e?l.mod(e):l;if(a=t.s<0,e){if(e.c?!e.c[0]:!e.s)return new S(NaN);(r=!a&&h.isInteger()&&e.isInteger())&&(h=h.mod(e))}else{if(t.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return o=h.s<0&&Jo(t)?-0:0,h.e>-1&&(o=1/o),new S(a?1/o:o);b&&(o=Do(b/Bo+2))}for(s?(n=new S(.5),a&&(t.s=1),u=Jo(t)):u=(i=Math.abs(+T(t)))%2,l=new S(g);;){if(u){if(!(l=l.times(h)).c)break;o?l.c.length>o&&(l.c.length=o):r&&(l=l.mod(e))}if(i){if(0===(i=Fo(i/2)))break;u=i%2}else if(C(t=t.times(n),t.e+1,1),t.e>14)u=Jo(t);else{if(0===(i=+T(t)))break;u=i%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):r&&(h=h.mod(e))}return r?l:(a&&(l=g.div(l)),e?l.mod(e):o?C(l,b,v,undefined):l)},f.integerValue=function(t){var e=new S(this);return null==t?t=v:Wo(t,0,8),C(e,e.e+1,t)},f.isEqualTo=f.eq=function(t,e){return 0===Ho(this,new S(t,e))},f.isFinite=function(){return!!this.c},f.isGreaterThan=f.gt=function(t,e){return Ho(this,new S(t,e))>0},f.isGreaterThanOrEqualTo=f.gte=function(t,e){return 1===(e=Ho(this,new S(t,e)))||0===e},f.isInteger=function(){return!!this.c&&Uo(this.e/Bo)>this.c.length-2},f.isLessThan=f.lt=function(t,e){return Ho(this,new S(t,e))<0},f.isLessThanOrEqualTo=f.lte=function(t,e){return-1===(e=Ho(this,new S(t,e)))||0===e},f.isNaN=function(){return!this.s},f.isNegative=function(){return this.s<0},f.isPositive=function(){return this.s>0},f.isZero=function(){return!!this.c&&0==this.c[0]},f.minus=function(t,e){var n,r,i,o,s=this,a=s.s;if(e=(t=new S(t,e)).s,!a||!e)return new S(NaN);if(a!=e)return t.s=-e,s.plus(t);var u=s.e/Bo,l=t.e/Bo,h=s.c,c=t.c;if(!u||!l){if(!h||!c)return h?(t.s=-e,t):new S(c?s:NaN);if(!h[0]||!c[0])return c[0]?(t.s=-e,t):new S(h[0]?s:3==v?-0:0)}if(u=Uo(u),l=Uo(l),h=h.slice(),a=u-l){for((o=a<0)?(a=-a,i=h):(l=u,i=c),i.reverse(),e=a;e--;i.push(0));i.reverse()}else for(r=(o=(a=h.length)<(e=c.length))?a:e,a=e=0;e0)for(;e--;h[n++]=0);for(e=Go-1;r>a;){if(h[--r]=0;){for(n=0,f=_[i]%d,g=_[i]/d|0,o=i+(s=u);o>i;)n=((l=f*(l=m[--s]%d)+(a=g*l+(h=m[s]/d|0)*f)%d*d+p[o]+n)/v|0)+(a/d|0)+g*h,p[o--]=l%v;p[o]=n}return n?++r:p.splice(0,1),P(t,p,r)},f.negated=function(){var t=new S(this);return t.s=-t.s||null,t},f.plus=function(t,e){var n,r=this,i=r.s;if(e=(t=new S(t,e)).s,!i||!e)return new S(NaN);if(i!=e)return t.s=-e,r.minus(t);var o=r.e/Bo,s=t.e/Bo,a=r.c,u=t.c;if(!o||!s){if(!a||!u)return new S(i/0);if(!a[0]||!u[0])return u[0]?t:new S(a[0]?r:0*i)}if(o=Uo(o),s=Uo(s),a=a.slice(),i=o-s){for(i>0?(s=o,n=u):(i=-i,n=a),n.reverse();i--;n.push(0));n.reverse()}for((i=a.length)-(e=u.length)<0&&(n=u,u=a,a=n,e=i),i=0;e;)i=(a[--e]=a[e]+u[e]+i)/Go|0,a[e]=Go===a[e]?0:a[e]%Go;return i&&(a=[i].concat(a),++s),P(t,a,s)},f.precision=f.sd=function(t,e){var n,r,i,o=this;if(null!=t&&t!==!!t)return Wo(t,1,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t,e);if(!(n=o.c))return null;if(r=(i=n.length-1)*Bo+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return t&&o.e+1>r&&(r=o.e+1),r},f.shiftedBy=function(t){return Wo(t,-9007199254740991,Yo),this.times("1e"+t)},f.squareRoot=f.sqrt=function(){var t,e,r,i,o,s=this,a=s.c,u=s.s,l=s.e,h=p+4,c=new S("0.5");if(1!==u||!a||!a[0])return new S(!u||u<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(u=Math.sqrt(+T(s)))||u==1/0?(((e=Zo(a)).length+l)%2==0&&(e+="0"),u=Math.sqrt(+e),l=Uo((l+1)/2)-(l<0||l%2),r=new S(e=u==1/0?"5e"+l:(e=u.toExponential()).slice(0,e.indexOf("e")+1)+l)):r=new S(u+""),r.c[0])for((u=(l=r.e)+h)<3&&(u=0);;)if(o=r,r=c.times(o.plus(n(s,o,h,1))),Zo(o.c).slice(0,u)===(e=Zo(r.c)).slice(0,u)){if(r.e0&&p>0){for(o=p%a||a,h=g.substr(0,o);o0&&(h+=l+g.slice(o)),f&&(h="-"+h)}r=c?h+(n.decimalSeparator||"")+((u=+n.fractionGroupSize)?c.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):c):h}return(n.prefix||"")+r+(n.suffix||"")},f.toFraction=function(t){var e,r,i,o,s,a,u,l,h,c,f,p,d=this,y=d.c;if(null!=t&&(!(u=new S(t)).isInteger()&&(u.c||1!==u.s)||u.lt(g)))throw Error(qo+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+T(u));if(!y)return new S(d);for(e=new S(g),h=r=new S(g),i=l=new S(g),p=Zo(y),s=e.e=p.length-d.e-1,e.c[0]=zo[(a=s%Bo)<0?Bo+a:a],t=!t||u.comparedTo(e)>0?s>0?e:h:u,a=x,x=1/0,u=new S(p),l.c[0]=0;c=n(u,e,0,1),1!=(o=r.plus(c.times(i))).comparedTo(t);)r=i,i=o,h=l.plus(c.times(o=h)),l=o,e=u.minus(c.times(o=e)),u=o;return o=n(t.minus(r),i,0,1),l=l.plus(o.times(h)),r=r.plus(o.times(i)),l.s=h.s=d.s,f=n(h,i,s*=2,v).minus(d).abs().comparedTo(n(l,r,s,v).minus(d).abs())<1?[h,i]:[l,r],x=a,f},f.toNumber=function(){return+T(this)},f.toPrecision=function(t,e){return null!=t&&Wo(t,1,Xo),M(this,t,e,2)},f.toString=function(t){var e,n=this,i=n.s,o=n.e;return null===o?i?(e="Infinity",i<0&&(e="-"+e)):e="NaN":(null==t?e=o<=d||o>=y?Ko(Zo(n.c),o):Qo(Zo(n.c),o,"0"):10===t&&N?e=Qo(Zo((n=C(new S(n),p+o+1,v)).c),n.e,"0"):(Wo(t,2,I.length,"Base"),e=r(Qo(Zo(n.c),o,"0"),10,t,i,!0)),i<0&&n.c[0]&&(e="-"+e)),e},f.valueOf=f.toJSON=function(){return T(this)},f._isBigNumber=!0,f[Symbol.toStringTag]="BigNumber",f[Symbol.for("nodejs.util.inspect.custom")]=f.valueOf,null!=e&&S.set(e),S}(),ts=function(t){function e(t){return i(this,e),r(this,e,[t])}return h(e,t),s(e)}(s((function t(e){i(this,t),u(this,"key",void 0),u(this,"left",null),u(this,"right",null),this.key=e}))),es=function(){return s((function t(){i(this,t),u(this,"size",0),u(this,"modificationCount",0),u(this,"splayCount",0)}),[{key:"splay",value:function(t){var e=this.root;if(null==e)return this.compare(t,t),-1;for(var n,r=null,i=null,o=null,s=null,a=e,u=this.compare;;)if((n=u(a.key,t))>0){var l=a.left;if(null==l)break;if((n=u(l.key,t))>0&&(a.left=l.right,l.right=a,null==(l=(a=l).left)))break;null==r?i=a:r.left=a,r=a,a=l}else{if(!(n<0))break;var h=a.right;if(null==h)break;if((n=u(h.key,t))<0&&(a.right=h.left,h.left=a,null==(h=(a=h).right)))break;null==o?s=a:o.right=a,o=a,a=h}return null!=o&&(o.right=a.left,a.left=s),null!=r&&(r.left=a.right,a.right=i),this.root!==a&&(this.root=a,this.splayCount++),n}},{key:"splayMin",value:function(t){for(var e=t,n=e.left;null!=n;){var r=n;e.left=r.right,r.right=e,n=(e=r).left}return e}},{key:"splayMax",value:function(t){for(var e=t,n=e.right;null!=n;){var r=n;e.right=r.left,r.left=e,n=(e=r).right}return e}},{key:"_delete",value:function(t){if(null==this.root)return null;if(0!=this.splay(t))return null;var e=this.root,n=e,r=e.left;if(this.size--,null==r)this.root=e.right;else{var i=e.right;(e=this.splayMax(r)).right=i,this.root=e}return this.modificationCount++,n}},{key:"addNewRoot",value:function(t,e){this.size++,this.modificationCount++;var n=this.root;null!=n?(e<0?(t.left=n,t.right=n.right,n.right=null):(t.right=n,t.left=n.left,n.left=null),this.root=t):this.root=t}},{key:"_first",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMin(t),this.root)}},{key:"_last",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMax(t),this.root)}},{key:"clear",value:function(){this.root=null,this.size=0,this.modificationCount++}},{key:"has",value:function(t){return this.validKey(t)&&0==this.splay(t)}},{key:"defaultCompare",value:function(){return function(t,e){return te?1:0}}},{key:"wrap",value:function(){var t=this;return{getRoot:function(){return t.root},setRoot:function(e){t.root=e},getSize:function(){return t.size},getModificationCount:function(){return t.modificationCount},getSplayCount:function(){return t.splayCount},setSplayCount:function(e){t.splayCount=e},splay:function(e){return t.splay(e)},has:function(e){return t.has(e)}}}}])}(),ns=function(t){function e(t,n){var o;return i(this,e),u(o=r(this,e),"root",null),u(o,"compare",void 0),u(o,"validKey",void 0),u(o,Symbol.toStringTag,"[object Set]"),o.compare=null!=t?t:o.defaultCompare(),o.validKey=null!=n?n:function(t){return null!=t&&null!=t},o}return h(e,t),s(e,[{key:"delete",value:function(t){return!!this.validKey(t)&&null!=this._delete(t)}},{key:"deleteAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.delete(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"forEach",value:function(t){for(var e,n=this[Symbol.iterator]();!(e=n.next()).done;)t(e.value,e.value,this)}},{key:"add",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this}},{key:"addAndReturn",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this.root.key}},{key:"addAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.add(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"isEmpty",value:function(){return null==this.root}},{key:"isNotEmpty",value:function(){return null!=this.root}},{key:"single",value:function(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}},{key:"first",value:function(){if(0==this.size)throw"Bad state: No element";return this._first().key}},{key:"last",value:function(){if(0==this.size)throw"Bad state: No element";return this._last().key}},{key:"lastBefore",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)<0)return this.root.key;var e=this.root.left;if(null==e)return null;for(var n=e.right;null!=n;)n=(e=n).right;return e.key}},{key:"firstAfter",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)>0)return this.root.key;var e=this.root.right;if(null==e)return null;for(var n=e.left;null!=n;)n=(e=n).left;return e.key}},{key:"retainAll",value:function(t){var n,r=new e(this.compare,this.validKey),i=this.modificationCount,o=a(t);try{for(o.s();!(n=o.n()).done;){var s=n.value;if(i!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(s)&&0==this.splay(s)&&r.add(this.root.key)}}catch(t){o.e(t)}finally{o.f()}r.size!=this.size&&(this.root=r.root,this.size=r.size,this.modificationCount++)}},{key:"lookup",value:function(t){return this.validKey(t)?0!=this.splay(t)?null:this.root.key:null}},{key:"intersection",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)&&r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"difference",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)||r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"union",value:function(t){var e=this.clone();return e.addAll(t),e}},{key:"clone",value:function(){var t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}},{key:"copyNode",value:function(t){if(null==t)return null;var e=new ts(t.key);return function t(e,n){var r,i;do{if(r=e.left,i=e.right,null!=r){var o=new ts(r.key);n.left=o,t(r,o)}if(null!=i){var s=new ts(i.key);n.right=s,e=i,n=s}}while(null!=i)}(t,e),e}},{key:"toSet",value:function(){return this.clone()}},{key:"entries",value:function(){return new os(this.wrap())}},{key:"keys",value:function(){return this[Symbol.iterator]()}},{key:"values",value:function(){return this[Symbol.iterator]()}},{key:Symbol.iterator,value:function(){return new is(this.wrap())}}])}(es),rs=function(){return s((function t(e){i(this,t),u(this,"tree",void 0),u(this,"path",new Array),u(this,"modificationCount",null),u(this,"splayCount",void 0),this.tree=e,this.splayCount=e.getSplayCount()}),[{key:Symbol.iterator,value:function(){return this}},{key:"next",value:function(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}},{key:"current",value:function(){if(!this.path.length)return null;var t=this.path[this.path.length-1];return this.getValue(t)}},{key:"rebuildPath",value:function(t){this.path.splice(0,this.path.length),this.tree.splay(t),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}},{key:"findLeftMostDescendent",value:function(t){for(;null!=t;)this.path.push(t),t=t.left}},{key:"moveNext",value:function(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();for(var t=this.tree.getRoot();null!=t;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);var e=this.path[this.path.length-1],n=e.right;if(null!=n){for(;null!=n;)this.path.push(n),n=n.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}}])}(),is=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return t.key}}])}(rs),os=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return[t.key,t.key]}}])}(rs),ss=function(t){return function(){return t}},as=function(t){var e=t?function(e,n){return n.minus(e).abs().isLessThanOrEqualTo(t)}:ss(!1);return function(t,n){return e(t,n)?0:t.comparedTo(n)}};function us(t){var e=t?function(e,n,r,i,o){return e.exponentiatedBy(2).isLessThanOrEqualTo(i.minus(n).exponentiatedBy(2).plus(o.minus(r).exponentiatedBy(2)).times(t))}:ss(!1);return function(t,n,r){var i=t.x,o=t.y,s=r.x,a=r.y,u=o.minus(a).times(n.x.minus(s)).minus(i.minus(s).times(n.y.minus(a)));return e(u,i,o,s,a)?0:u.comparedTo(0)}}var ls=function(t){return t},hs=function(t){if(t){var e=new ns(as(t)),n=new ns(as(t)),r=function(t,e){return e.addAndReturn(t)},i=function(t){return{x:r(t.x,e),y:r(t.y,n)}};return i({x:new $o(0),y:new $o(0)}),i}return ls},cs=function(t){return{set:function(t){fs=cs(t)},reset:function(){return cs(t)},compare:as(t),snap:hs(t),orient:us(t)}},fs=cs(),gs=function(t,e){return t.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(t.ur.x)&&t.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(t.ur.y)},ps=function(t,e){if(e.ur.x.isLessThan(t.ll.x)||t.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(t.ll.y)||t.ur.y.isLessThan(e.ll.y))return null;var n=t.ll.x.isLessThan(e.ll.x)?e.ll.x:t.ll.x,r=t.ur.x.isLessThan(e.ur.x)?t.ur.x:e.ur.x;return{ll:{x:n,y:t.ll.y.isLessThan(e.ll.y)?e.ll.y:t.ll.y},ur:{x:r,y:t.ur.y.isLessThan(e.ur.y)?t.ur.y:e.ur.y}}},vs=function(t,e){return t.x.times(e.y).minus(t.y.times(e.x))},ds=function(t,e){return t.x.times(e.x).plus(t.y.times(e.y))},ys=function(t){return ds(t,t).sqrt()},ms=function(t,e,n){var r={x:e.x.minus(t.x),y:e.y.minus(t.y)},i={x:n.x.minus(t.x),y:n.y.minus(t.y)};return ds(i,r).div(ys(i)).div(ys(r))},_s=function(t,e,n){return e.y.isZero()?null:{x:t.x.plus(e.x.div(e.y).times(n.minus(t.y))),y:n}},xs=function(t,e,n){return e.x.isZero()?null:{x:n,y:t.y.plus(e.y.div(e.x).times(n.minus(t.x)))}},Es=function(){function t(e,n){i(this,t),u(this,"point",void 0),u(this,"isLeft",void 0),u(this,"segment",void 0),u(this,"otherSE",void 0),u(this,"consumedBy",void 0),void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}return s(t,[{key:"link",value:function(t){if(t.point===this.point)throw new Error("Tried to link already linked events");for(var e=t.point.events,n=0,r=e.length;n0&&(t=r)}for(var i=t.segment.prevInResult(),o=i?i.prevInResult():null;;){if(!i)return null;if(!o)return i.ringOut;var s,a;if(o.ringOut!==i.ringOut)return(null===(s=o.ringOut)||void 0===s?void 0:s.enclosingRing())!==i.ringOut?i.ringOut:null===(a=i.ringOut)||void 0===a?void 0:a.enclosingRing();i=o.prevInResult(),o=i?i.prevInResult():null}}}],[{key:"factory",value:function(e){for(var n=[],r=0,i=e.length;r1&&void 0!==arguments[1]?arguments[1]:Ls.compare;i(this,t),u(this,"queue",void 0),u(this,"tree",void 0),u(this,"segments",void 0),this.queue=e,this.tree=new ns(n),this.segments=[]}),[{key:"process",value:function(t){var e=t.segment,n=[];if(t.consumedBy)return t.isLeft?this.queue.delete(t.otherSE):this.tree.delete(e),n;t.isLeft&&this.tree.add(e);var r=e,i=e;do{r=this.tree.lastBefore(r)}while(null!=r&&null!=r.consumedBy);do{i=this.tree.firstAfter(i)}while(null!=i&&null!=i.consumedBy);if(t.isLeft){var o=null;if(r){var s=r.getIntersection(e);if(null!==s&&(e.isAnEndpoint(s)||(o=s),!r.isAnEndpoint(s)))for(var a=this._splitSafely(r,s),u=0,l=a.length;u0?(this.tree.delete(e),n.push(t)):(this.segments.push(e),e.prev=r)}else{if(r&&i){var _=r.getIntersection(i);if(null!==_){if(!r.isAnEndpoint(_))for(var x=this._splitSafely(r,_),E=0,k=x.length;E0&&a.swapEvents(),Es.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}},{key:"swapEvents",value:function(){var t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(var e=0,n=this.windings.length;e0){var o=n;n=r,r=o}if(n.prev===r){var s=n;n=r,r=s}for(var a=0,u=r.rings.length;a0)return-1;var c=e.comparePoint(t.rightSE.point);return 0!==c?c:-1}if(n.isGreaterThan(r)){if(s.isLessThan(a)&&s.isLessThan(l))return-1;if(s.isGreaterThan(a)&&s.isGreaterThan(l))return 1;var f=e.comparePoint(t.leftSE.point);if(0!==f)return f;var g=t.comparePoint(e.rightSE.point);return g<0?1:g>0?-1:1}if(s.isLessThan(a))return-1;if(s.isGreaterThan(a))return 1;if(i.isLessThan(o)){var p=e.comparePoint(t.rightSE.point);if(0!==p)return p}if(i.isGreaterThan(o)){var v=t.comparePoint(e.rightSE.point);if(v<0)return 1;if(v>0)return-1}if(!i.eq(o)){var d=u.minus(s),y=i.minus(n),m=l.minus(a),_=o.minus(r);if(d.isGreaterThan(y)&&m.isLessThan(_))return 1;if(d.isLessThan(y)&&m.isGreaterThan(_))return-1}return i.isGreaterThan(o)?1:i.isLessThan(o)||u.isLessThan(l)?-1:u.isGreaterThan(l)?1:t.ide.id?1:0}},{key:"fromRing",value:function(e,n,r){var i,o,s,a=Es.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else{if(!(a>0))throw new Error("Tried to create degenerate segment at [".concat(e.x,", ").concat(e.y,"]"));i=n,o=e,s=-1}return new t(new Es(i,!0),new Es(o,!1),[r],[s])}}])}(),Ps=function(){return s((function t(e,n,r){if(i(this,t),u(this,"poly",void 0),u(this,"isExterior",void 0),u(this,"segments",void 0),u(this,"bbox",void 0),!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");var o=fs.snap({x:new $o(e[0][0]),y:new $o(e[0][1])});this.bbox={ll:{x:o.x,y:o.y},ur:{x:o.x,y:o.y}};for(var s=o,a=1,l=e.length;a1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r2&&void 0!==arguments[2]?arguments[2]:2,r=K(t),i=K(e),o=r[0]-i[0],s=r[1]-i[1];return 1===n?Math.abs(o)+Math.abs(s):Math.pow(Math.pow(o,n)+Math.pow(s,n),1/n)}function Gs(t,e){var n,r,i=(e=e||{}).threshold||1e4,o=e.p||2,s=null!=(n=e.binary)&&n,a=e.alpha||-1,u=null!=(r=e.standardization)&&r,l=[];vt(t,(function(t){l.push(gi(t))}));for(var h=[],c=0;c3&&void 0!==arguments[3]?arguments[3]:{},i=e<0,o=j(Math.abs(e),r.units,"meters");i&&(o=-Math.abs(o));var s=K(t),a=function(t,e,n,r){r=void 0===r?x:Number(r);var i=e/r,o=t[0]*Math.PI/180,s=z(t[1]),a=z(n),u=i*Math.cos(a),l=s+u;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);var h=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),c=Math.abs(h)>1e-11?u/h:Math.cos(s),f=i*Math.sin(a)/c;return[(180*(o+f)/Math.PI+540)%360-180,180*l/Math.PI]}(s,o,n);return a[0]+=a[0]-s[0]>180?-360:s[0]-a[0]>180?360:0,I(a,r.properties)}function Ys(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e);i[0]+=i[0]-r[0]>180?-360:r[0]-i[0]>180?360:0;var o=function(t,e,n){var r=n=void 0===n?x:Number(n),i=t[1]*Math.PI/180,o=e[1]*Math.PI/180,s=o-i,a=Math.abs(e[0]-t[0])*Math.PI/180;a>Math.PI&&(a-=2*Math.PI);var u=Math.log(Math.tan(o/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),l=Math.abs(u)>1e-11?s/u:Math.cos(i);return Math.sqrt(s*s+l*l*a*a)*r}(r,i);return j(o,"meters",n.units)}function zs(t,e,n){if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.pivot,i=n.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("angle is required");if(0===e)return t;var o=null!=r?r:gi(t);return!1!==i&&void 0!==i||(t=Ai(t)),ct(t,(function(t){var n=lt(o,t)+e,r=Ys(o,t),i=Q(Bs(o,r,n));t[0]=i[0],t[1]=i[1]})),t}function js(t,e,n,r){var i=(r=r||{}).steps||64,o=r.units||"kilometers",s=r.angle||0,a=r.pivot||t,u=r.properties||{};if(!t)throw new Error("center is required");if(!e)throw new Error("xSemiAxis is required");if(!n)throw new Error("ySemiAxis is required");if(!Z(r))throw new Error("options must be an object");if(!U(i))throw new Error("steps must be a number");if(!U(s))throw new Error("angle must be a number");var l=K(t);if("degrees"!==o){var h=Bs(t,e,90,{units:o}),c=Bs(t,n,0,{units:o});e=K(h)[0]-l[0],n=K(c)[1]-l[1]}for(var f=[],g=0;g=-270&&(v=-v),p<-180&&p>=-360&&(d=-d),"degrees"===o){var y=z(s),m=v*Math.cos(y)+d*Math.sin(y),_=d*Math.cos(y)-v*Math.sin(y);v=m,d=_}f.push([v+l[0],d+l[1]])}return f.push(f[0]),"degrees"===o?S([f],u):zs(S([f],u),s,{pivot:a})}function Xs(t){var e=t*Math.PI/180;return Math.tan(e)}function Us(t){return Vt(Rt(t))}function Zs(t){var e=[];return"FeatureCollection"===t.type?vt(t,(function(t){ct(t,(function(n){e.push(I(n,t.properties))}))})):"Feature"===t.type?ct(t,(function(n){e.push(I(n,t.properties))})):ct(t,(function(t){e.push(I(t))})),C(e)}var Hs=Math.PI/180,Ws=180/Math.PI,Js=function(t,e){this.lon=t,this.lat=e,this.x=Hs*t,this.y=Hs*e};Js.prototype.view=function(){return String(this.lon).slice(0,4)+","+String(this.lat).slice(0,4)},Js.prototype.antipode=function(){var t=-1*this.lat,e=this.lon<0?180+this.lon:-1*(180-this.lon);return new Js(e,t)};var Ks=function(){this.coords=[],this.length=0};Ks.prototype.move_to=function(t){this.length++,this.coords.push(t)};var Qs=function(t){this.properties=t||{},this.geometries=[]};Qs.prototype.json=function(){if(this.geometries.length<=0)return{geometry:{type:"LineString",coordinates:null},type:"Feature",properties:this.properties};if(1===this.geometries.length)return{geometry:{type:"LineString",coordinates:this.geometries[0].coords},type:"Feature",properties:this.properties};for(var t=[],e=0;e1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must specify at least 2 geometries");var r=Rs.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)}function ea(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.stringify(n.properties||{}),i=v(t,4),o=i[0],s=i[1],a=i[2],u=i[3],l=(s+u)/2,h=(o+a)/2,c=2*e/ut([o,l],[a,l],n)*(a-o),f=2*e/ut([h,s],[h,u],n)*(u-s),g=c/2,p=2*g,d=Math.sqrt(3)/2*f,y=a-o,m=u-s,_=3/4*p,x=d,E=(y-p)/(p-g/2),k=Math.floor(E),b=(k*_-g/2-y)/2-g/2+_/2,w=Math.floor((m-d)/d),I=(m-w*d)/2,N=w*d-m>d/2;N&&(I-=d/4);for(var S=[],M=[],L=0;L<6;L++){var P=2*Math.PI/6*L;S.push(Math.cos(P)),M.push(Math.sin(P))}for(var T=[],O=0;O<=k;O++)for(var R=0;R<=w;R++){var A=O%2==1;if((0!==R||!A)&&(0!==R||!N)){var D=O*_+o-b,F=R*x+s+I;if(A&&(F-=d/2),!0===n.triangles)ra([D,F],c/2,f/2,JSON.parse(r),S,M).forEach((function(t){n.mask?ta(C([n.mask,t]))&&T.push(t):T.push(t)}));else{var q=na([D,F],c/2,f/2,JSON.parse(r),S,M);n.mask?ta(C([n.mask,q]))&&T.push(q):T.push(q)}}}return C(T)}function na(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=t[0]+e*i[a],l=t[1]+n*o[a];s.push([u,l])}return s.push(s[0].slice()),S([s],r)}function ra(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=[];u.push(t),u.push([t[0]+e*i[a],t[1]+n*o[a]]),u.push([t[0]+e*i[(a+1)%6],t[1]+n*o[(a+1)%6]]),u.push(t),s.push(S([u],r))}return s}function ia(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.mask&&!n.units&&(n.units="kilometers");for(var r=[],i=t[0],o=t[1],s=t[2],a=t[3],u=e/ut([i,o],[s,o],n)*(s-i),l=e/ut([i,o],[i,a],n)*(a-o),h=s-i,c=a-o,f=Math.floor(h/u),g=(c-Math.floor(c/l)*l)/2,p=i+(h-f*u)/2;p<=s;){for(var v=o+g;v<=a;){var d=I([p,v],n.properties);n.mask?Cn(d,n.mask)&&r.push(d):r.push(d),v+=l}p+=u}return C(r)}function oa(t,e,n){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=[],o=t[0],s=t[1],a=t[2],u=t[3],l=a-o,h=j(e,r.units,"degrees"),c=u-s,f=j(n,r.units,"degrees"),g=Math.floor(Math.abs(l)/h),p=Math.floor(Math.abs(c)/f),v=(c-p*f)/2,d=o+(l-g*h)/2,y=0;y2&&void 0!==arguments[2]?arguments[2]:{})}function aa(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=[],i=e/ut([t[0],t[1]],[t[2],t[1]],n)*(t[2]-t[0]),o=e/ut([t[0],t[1]],[t[0],t[3]],n)*(t[3]-t[1]),s=0,a=t[0];a<=t[2];){for(var u=0,l=t[1];l<=t[3];){var h=null,c=null;s%2==0&&u%2==0?(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)):s%2==0&&u%2==1?(h=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties)):u%2==0&&s%2==1?(h=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties),c=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties)):u%2==1&&s%2==1&&(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)),n.mask?(ta(C([n.mask,h]))&&r.push(h),ta(C([n.mask,c]))&&r.push(c)):(r.push(h),r.push(c)),l+=o,u++}s++,a+=i}return C(r)} +/*! + * MarchingSquaresJS + * version 1.3.3 + * https://github.com/RaumZeit/MarchingSquares.js + * + * @license GNU Affero General Public License. + * Copyright (c) 2015-2019 Ronny Lorenz + */ +function ua(t,e,n){return tr&&(i=n,n=r,r=i),tr?(t-r)/(t-e):(t-n)/(t-e)}function ha(t,e,n,r){return t1){for(;0!==o;)o>>=1,a++;r===1<1){for(;0!==s;)s>>=1,u++;i===1<0&&(this.childB=new da(t,e+o,n,r-o,s),this.lowerBound=Math.min(this.lowerBound,this.childB.lowerBound),this.upperBound=Math.max(this.upperBound,this.childB.upperBound),i-s>0&&(this.childC=new da(t,e+o,n+s,r-o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childC.lowerBound),this.upperBound=Math.max(this.upperBound,this.childC.upperBound))),i-s>0&&(this.childD=new da(t,e,n+s,o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childD.lowerBound),this.upperBound=Math.max(this.upperBound,this.childD.upperBound))}}function ya(t){var e,n;if(!t)throw new Error("data is required");if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Error("data must be scalar field, i.e. array of arrays");if(t.length<2)throw new Error("data must contain at least two rows");if((n=t[0].length)<2)throw new Error("data must contain at least two columns");for(e=1;e=e||t[s][r-1]>=e){n=!1;break}if(n&&(t[i-1][0]>=e||t[i-1][r-1]>=e)&&(n=!1),n)for(o=0;o=e||t[i-1][o]>e){n=!1;break}return n}(t,n.threshold)&&(n.linearRing?_.push([[0,0],[0,x],[E,x],[E,0],[0,0]]):_.push([[0,0],[0,x],[E,x],[E,0]])),e.forEach((function(t,N){t.forEach((function(t,S){for(r=null,i=0;i<4;i++)if(r=k[i],"object"===m(t.edges[r])){for(a=[],o=t.edges[r],u=r,l=N,h=S,c=!1,f=[N+o.path[0][0],S+o.path[0][1]],a.push(f);!c&&"object"===m((s=e[l][h]).edges[u]);)if(o=s.edges[u],delete s.edges[u],(g=o.path[1])[0]+=l,g[1]+=h,a.push(g),u=o.move.enter,l+=o.move.x,h+=o.move.y,void 0===e[l]||void 0===e[l][h]){if(!n.linearRing)break;if(p=0,v=0,l===E?(l--,p=0):l<0?(l++,p=2):h===x?(h--,p=3):h<0&&(h++,p=1),l===N&&h===S&&p===I[r]){c=!0,u=r;break}for(;;){if(d=!1,v>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[l]&&void 0!==e[l][h]&&(s=e[l][h],y=k[p],"object"===m(s.edges[y]))){o=s.edges[y],a.push(pa(l,h,p,o.path)),u=y,d=!0;break}if(d)break;if(a.push(va(l,h,p)),h+=w[p],void 0!==e[l+=b[p]]&&void 0!==e[l][h]||(0===p&&h<0||1===p&&l<0||2===p&&h===x||3===p&&l===E)&&(l-=b[p],h-=w[p],p=(p+1)%4,v++),l===N&&h===S&&p===I[r]){c=!0,u=r;break}}}!n.linearRing||a[a.length-1][0]===f[0]&&a[a.length-1][1]===f[1]||a.push(f),_.push(a)}}))})),_}(h,c,r)}a?g.push(f):g=f,"function"==typeof r.successCallback&&r.successCallback(g,t)})),g}function _a(t,e,n,r){var i,o,s,a,u,l,h=0,c=t[n+1][e],f=t[n+1][e+1],g=t[n][e+1],p=t[n][e],v=r.threshold;if(!(isNaN(p)||isNaN(g)||isNaN(f)||isNaN(c))){switch(h|=c>=v?8:0,h|=f>=v?4:0,h|=g>=v?2:0,l={cval:h=+(h|=p>=v?1:0),polygons:[],edges:{},x0:p,x1:g,x2:f,x3:c},h){case 0:r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,0]]);break;case 15:break;case 14:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.left={path:[[0,i],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[a,0]]);break;case 13:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[a,0],[1,o],[1,0]]);break;case 11:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[1,o],[s,1],[1,1]]);break;case 7:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[s,1],[0,i],[0,1]]);break;case 1:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[a,0],[0,i],[0,1],[1,1],[1,0]]);break;case 2:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,o],[a,0]]);break;case 4:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[1,o],[1,0]]);break;case 8:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[s,1],[1,1],[1,0]]);break;case 12:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[1,o],[1,0]]);break;case 9:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[a,0],[s,1],[1,1],[1,0]]);break;case 3:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[0,i],[0,1],[1,1],[1,o]]);break;case 6:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[a,0]]);break;case 10:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),u=(p+g+f+c)/4,r.polygons_full&&(uf&&(v>h&&ph&&vu&&(u=d)}var y=[];if(a&&u0&&Math.abs(x-n[_-1][0])>f){var E=parseFloat(n[_-1][0]),k=parseFloat(n[_-1][1]),b=parseFloat(n[_][0]),w=parseFloat(n[_][1]);if(E>-180&&E-180&&n[_-1][0]h&&E<180&&-180===b&&_+1h&&n[_-1][0]<180){m.push([180,n[_][1]]),_++,m.push([n[_][0],n[_][1]]);continue}if(Eh){var I=E;E=b,b=I;var N=k;k=w,w=N}if(E>h&&b=180&&Eh?180:-180,M]),(m=[]).push([n[_-1][0]>h?-180:180,M]),y.push(m)}else m=[],y.push(m);m.push([x,n[_][1]])}else m.push([n[_][0],n[_][1]])}}else{var L=[];y.push(L);for(var P=0;Pe||this.upperBound=e)&&r.push({x:this.x,y:this.y})),r},da.prototype.cellsBelowThreshold=function(t,e){var n=[];return e=void 0===e||e,this.lowerBound>t||(this.childA||this.childB||this.childC||this.childD?(this.childA&&(n=n.concat(this.childA.cellsBelowThreshold(t,e))),this.childB&&(n=n.concat(this.childB.cellsBelowThreshold(t,e))),this.childD&&(n=n.concat(this.childD.cellsBelowThreshold(t,e))),this.childC&&(n=n.concat(this.childC.cellsBelowThreshold(t,e)))):(e||this.upperBound>=t)&&n.push({x:this.x,y:this.y})),n};var xa={square:function(t,e,n,r,i,o){o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,0]])},triangle_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,a],[s,0],[0,0]])},triangle_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[1,a],[1,0]])},triangle_tr:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[1,s],[a,1],[1,1]])},triangle_tl:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[s,1]])},tetragon_t:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[1,1],[1,s]])},tetragon_r:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[a,1],[1,1],[1,0]])},tetragon_b:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,0]])},tetragon_l:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[a,0]])},tetragon_bl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[a,0]])},tetragon_br:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate_b(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[1,l]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[1,l],[1,u],[a,0]])},tetragon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rb={path:[[1,l],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}}),o.polygons&&t.polygons.push([[1,l],[s,1],[a,1],[1,u]])},tetragon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[0,l]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[a,1],[0,l],[0,u],[s,1]])},tetragon_lr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[1,u],[1,l]])},tetragon_tb:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[l,0],[s,1],[a,1],[u,0]])},pentagon_tr:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[1,a],[1,0]])},pentagon_tl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,0]])},pentagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,a],[s,0]])},pentagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[a,0],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[1,1],[1,0],[a,0]])},pentagon_tr_rl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[1,u],[1,l]])},pentagon_rb_bt:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,n,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[u,0],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[l,1],[1,1],[1,s],[a,0],[u,0]])},pentagon_bl_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[1,l],[1,0]])},pentagon_lt_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[l,0]])},pentagon_bl_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[l,0],[0,s]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[u,0],[l,0]])},pentagon_lt_rl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[u,1],[1,1],[1,l]])},pentagon_tr_bt:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,1],[a,1],[1,u],[1,0],[l,0]])},pentagon_rb_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_b(n,r,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,u],[l,0]])},hexagon_lt_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[1,l],[1,0]])},hexagon_bl_lt:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[1,1],[1,0]])},hexagon_bl_rb:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.rt={path:[[1,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[1,1],[1,l],[a,0]])},hexagon_tr_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[a,1],[1,u],[1,l],[s,0]])},hexagon_lt_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,u],[l,0]])},hexagon_bl_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,1],[u,1],[1,l],[1,0]])},heptagon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[1,1],[1,c],[a,0]])},heptagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate_a(i,r,o.minV,o.maxV),l=o.interpolate_b(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,a],[u,1],[l,1],[1,h],[1,c],[s,0]])},heptagon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[l,1],[1,h],[1,c],[a,0]])},heptagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(i,r,o.minV,o.maxV),h=o.interpolate_b(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[h,1],[1,c]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[h,1],[1,c],[1,0]])},octagon:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate_a(i,r,o.minV,o.maxV),c=o.interpolate_b(i,r,o.minV,o.maxV),f=o.interpolate_b(n,r,o.minV,o.maxV),g=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[c,1],[1,f]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,g],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[c,1],[1,f],[1,g],[a,0]])}};function Ea(t,e,n,r){var i,o,s,a=!1,u=null,l=null,h=null,c=null,f=!1,g=[],p=[],v=[];if(!t)throw new Error("data is required");if(null==e)throw new Error("lowerBound is required");if(null==n)throw new Error("bandWidth is required");if(s=function(t){var e,n,r,i,o;for(i=new fa,t=t||{},o=Object.keys(i),e=0;en||t[a][i-1]n){r=!1;break}if(r&&(t[o-1][0]n||t[o-1][i-1]n)&&(r=!1),r)for(s=0;sn||t[o-1][s]n){r=!1;break}return r}(t,n.minV,n.maxV)&&(n.linearRing?x.push([[0,0],[0,E],[k,E],[k,0],[0,0]]):x.push([[0,0],[0,E],[k,E],[k,0]])),e.forEach((function(t,M){t.forEach((function(t,L){for(r=null,o=0;o<8;o++)if(r=N[o],"object"===m(t.edges[r])){for(i=[],s=t.edges[r],l=r,h=M,c=L,f=!1,g=[M+s.path[0][0],L+s.path[0][1]],i.push(g);!f&&"object"===m((p=e[h][c]).edges[l]);)if(s=p.edges[l],delete p.edges[l],(y=s.path[1])[0]+=h,y[1]+=c,i.push(y),l=s.move.enter,h+=s.move.x,c+=s.move.y,void 0===e[h]||void 0===e[h][c]){if(v=0,d=0,h===k)h--,v=0;else if(h<0)h++,v=2;else if(c===E)c--,v=3;else{if(!(c<0))throw new Error("Left the grid somewhere in the interior!");c++,v=1}if(h===M&&c===L&&v===S[r]){f=!0,l=r;break}for(;;){if(_=!1,d>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[h]&&void 0!==e[h][c])for(p=e[h][c],a=0;ao?2:sf?128:64,s|=uf?32:16,s|=lf?8:4,o=0,i={cval:s=+(s|=hf?2:1),polygons:[],edges:{},x0:h,x1:l,x2:u,x3:a,x:e,y:n},s){case 85:xa.square(i,h,l,u,a,r);case 0:case 170:break;case 169:xa.triangle_bl(i,h,l,u,a,r);break;case 166:xa.triangle_br(i,h,l,u,a,r);break;case 154:xa.triangle_tr(i,h,l,u,a,r);break;case 106:xa.triangle_tl(i,h,l,u,a,r);break;case 1:xa.triangle_bl(i,h,l,u,a,r);break;case 4:xa.triangle_br(i,h,l,u,a,r);break;case 16:xa.triangle_tr(i,h,l,u,a,r);break;case 64:xa.triangle_tl(i,h,l,u,a,r);break;case 168:xa.tetragon_bl(i,h,l,u,a,r);break;case 162:xa.tetragon_br(i,h,l,u,a,r);break;case 138:xa.tetragon_tr(i,h,l,u,a,r);break;case 42:xa.tetragon_tl(i,h,l,u,a,r);break;case 2:xa.tetragon_bl(i,h,l,u,a,r);break;case 8:xa.tetragon_br(i,h,l,u,a,r);break;case 32:xa.tetragon_tr(i,h,l,u,a,r);break;case 128:xa.tetragon_tl(i,h,l,u,a,r);break;case 5:xa.tetragon_b(i,h,l,u,a,r);break;case 20:xa.tetragon_r(i,h,l,u,a,r);break;case 80:xa.tetragon_t(i,h,l,u,a,r);break;case 65:xa.tetragon_l(i,h,l,u,a,r);break;case 165:xa.tetragon_b(i,h,l,u,a,r);break;case 150:xa.tetragon_r(i,h,l,u,a,r);break;case 90:xa.tetragon_t(i,h,l,u,a,r);break;case 105:xa.tetragon_l(i,h,l,u,a,r);break;case 160:xa.tetragon_lr(i,h,l,u,a,r);break;case 130:xa.tetragon_tb(i,h,l,u,a,r);break;case 10:xa.tetragon_lr(i,h,l,u,a,r);break;case 40:xa.tetragon_tb(i,h,l,u,a,r);break;case 101:xa.pentagon_tr(i,h,l,u,a,r);break;case 149:xa.pentagon_tl(i,h,l,u,a,r);break;case 86:xa.pentagon_bl(i,h,l,u,a,r);break;case 89:xa.pentagon_br(i,h,l,u,a,r);break;case 69:xa.pentagon_tr(i,h,l,u,a,r);break;case 21:xa.pentagon_tl(i,h,l,u,a,r);break;case 84:xa.pentagon_bl(i,h,l,u,a,r);break;case 81:xa.pentagon_br(i,h,l,u,a,r);break;case 96:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 24:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 6:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 129:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 74:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 146:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 164:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 41:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 66:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 144:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 36:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 9:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 104:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 26:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 134:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 161:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 37:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 148:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 82:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 73:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 133:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 22:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 88:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 97:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 145:case 25:xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 70:case 100:xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 17:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 68:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 153:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 102:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 152:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 137:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 98:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 38:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 18:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 33:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 72:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 132:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 136:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r));break;case 34:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r))}return i}}var wa=Object.defineProperty,Ia=Object.getOwnPropertySymbols,Na=Object.prototype.hasOwnProperty,Sa=Object.prototype.propertyIsEnumerable,Ma=function(t,e,n){return e in t?wa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},La=function(t,e){for(var n in e||(e={}))Na.call(e,n)&&Ma(t,n,e[n]);if(Ia){var r,i=a(Ia(e));try{for(i.s();!(r=i.n()).done;){n=r.value;Sa.call(e,n)&&Ma(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t};function Pa(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.zProperty||"elevation",r=e.flip,i=e.flags;nt(t,"Point","input must contain Points");for(var o=function(t,e){var n={};vt(t,(function(t){var e=Q(t)[1];n[e]||(n[e]=[]),n[e].push(t)}));var r=Object.keys(n).map((function(t){return n[t].sort((function(t,e){return Q(t)[0]-Q(e)[0]}))})),i=r.sort((function(t,n){return e?Q(t[0])[1]-Q(n[0])[1]:Q(n[0])[1]-Q(t[0])[1]}));return i}(t,r),s=[],a=0;a=0&&l<=1&&(f.onLine1=!0),h>=0&&h<=1&&(f.onLine2=!0),!(!f.onLine1||!f.onLine2)&&[f.x,f.y])}function za(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return bt(t,(function(t,n){var r=n.geometry.coordinates;return t+ut(r[0],r[1],e)}),0)}function ja(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=i.steps||64,s=Xa(n),a=Xa(r),u=Array.isArray(t)||"Feature"!==t.type?{}:t.properties;if(s===a)return L(Ri(t,e,i).geometry.coordinates[0],u);for(var l=s,h=s=h&&c===i.length-1);c++){if(h>e&&0===o.length){if(!(s=e-h))return o.push(i[c]),L(o);a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates)}if(h>=n)return(s=n-h)?(a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates),L(o)):(o.push(i[c]),L(o));if(h>=e&&o.push(i[c]),c===i.length-1)return L(o);h+=ut(i[c],i[c+1],r)}if(h0){var a=r[e-1],u=Wa(n,a);!1!==u&&(a[1]=u,n[0]=u),s.push(a[0]),e===o.length-2&&(s.push(n[0]),s.push(n[1]))}2===o.length&&(s.push(n[0]),s.push(n[1]))}var l,h,c,f,g,p,v,d})),L(s,t.properties)}function Ka(t){var e=t[0],n=t[1],r=t[2],i=t[3];if(ut(t.slice(0,2),[r,n])>=ut(t.slice(0,2),[e,i])){var o=(n+i)/2;return[e,o-(r-e)/2,r,o+(r-e)/2]}var s=(e+r)/2;return[s-(i-n)/2,n,s+(i-n)/2,i]}function Qa(t,e){if(!Z(e=null!=e?e:{}))throw new Error("options is invalid");var n=e.precision,r=e.coordinates,i=e.mutate;if(n=null==n||isNaN(n)?6:n,r=null==r||isNaN(r)?3:r,!t)throw new Error(" is required");if("number"!=typeof n)throw new Error(" must be a number");if("number"!=typeof r)throw new Error(" must be a number");!1!==i&&void 0!==i||(t=JSON.parse(JSON.stringify(t)));var o=Math.pow(10,n);return ct(t,(function(t){!function(t,e,n){t.length>n&&t.splice(n,t.length);for(var r=0;r1&&n.push(L(l)),C(n)}function eu(t,e){if(!e.features.length)throw new Error("lines must contain features");if(1===e.features.length)return e.features[0];var n,r=1/0;return vt(e,(function(e){var i=fn(e,t).properties.dist;iu?(a.unshift(t),u=e):a.push(t)}else a.push(t)})),S(a,e);default:throw new Error("geometry type "+s+" is not supported")}}function iu(t){var e=t[0],n=e[0],r=e[1],i=t[t.length-1],o=i[0],s=i[1];return n===o&&r===s||t.push(e),t}function ou(t){return R(t)}function su(t){var e=[[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]];return t&&(e="Feature"===t.type?t.geometry.coordinates:t.coordinates),S(e)}function au(t){var e,n=0,r=a(t);try{for(r.s();!(e=r.n()).done;){n+=e.value}}catch(t){r.e(t)}finally{r.f()}return n/t.length}var uu=Object.defineProperty,lu=Object.defineProperties,hu=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,fu=Object.prototype.hasOwnProperty,gu=Object.prototype.propertyIsEnumerable,pu=function(t,e,n){return e in t?uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},vu=function(t,e){for(var n in e||(e={}))fu.call(e,n)&&pu(t,n,e[n]);if(cu){var r,i=a(cu(e));try{for(i.s();!(r=i.n()).done;){n=r.value;gu.call(e,n)&&pu(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},du=function(t,e){return lu(t,hu(e))};function yu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("targetPoint is required");if(!e)throw new Error("points is required");var r=1/0,i=0;vt(e,(function(e,o){var s=ut(t,e,n);s2&&void 0!==arguments[2]?arguments[2]:{},o=null!=(n=i.method)?n:"geodesic",s=null!=(r=i.units)?r:"kilometers";if(!t)throw new Error("pt is required");if(Array.isArray(t)?t=I(t):"Point"===t.type?t=b(t):et(t,"Point","point"),!e)throw new Error("line is required");Array.isArray(e)?e=L(e):"LineString"===e.type?e=b(e):et(e,"LineString","line");var a=1/0,u=t.geometry.coordinates;return kt(e,(function(t){if(t){var e=t.geometry.coordinates[0],n=t.geometry.coordinates[1],r=function(t,e,n,r){if("geodesic"===r.method){return fn(L([e,n]).geometry,t,{units:"degrees"}).properties.dist}var i=[n[0]-e[0],n[1]-e[1]],o=[t[0]-e[0],t[1]-e[1]],s=_u(o,i);if(s<=0)return Ys(t,e,{units:"degrees"});var a=_u(i,i);if(a<=s)return Ys(t,n,{units:"degrees"});var u=s/a,l=[e[0]+u*i[0],e[1]+u*i[1]];return Ys(t,l,{units:"degrees"})}(u,e,n,{method:o});r0)-(t<0)||+t}(r*(n[1]-e[1])-o*i)}function Lu(t,e){return e.geometry.coordinates[0].every((function(e){return zt(I(e),t)}))}var Pu=function(){return s((function t(e){i(this,t),this.id=t.buildId(e),this.coordinates=e,this.innerEdges=[],this.outerEdges=[],this.outerEdgesSorted=!1}),[{key:"removeInnerEdge",value:function(t){this.innerEdges=this.innerEdges.filter((function(e){return e.from.id!==t.from.id}))}},{key:"removeOuterEdge",value:function(t){this.outerEdges=this.outerEdges.filter((function(e){return e.to.id!==t.to.id}))}},{key:"addOuterEdge",value:function(t){this.outerEdges.push(t),this.outerEdgesSorted=!1}},{key:"sortOuterEdges",value:function(){var t=this;this.outerEdgesSorted||(this.outerEdges.sort((function(e,n){var r=e.to,i=n.to;if(r.coordinates[0]-t.coordinates[0]>=0&&i.coordinates[0]-t.coordinates[0]<0)return 1;if(r.coordinates[0]-t.coordinates[0]<0&&i.coordinates[0]-t.coordinates[0]>=0)return-1;if(r.coordinates[0]-t.coordinates[0]==0&&i.coordinates[0]-t.coordinates[0]==0)return r.coordinates[1]-t.coordinates[1]>=0||i.coordinates[1]-t.coordinates[1]>=0?r.coordinates[1]-i.coordinates[1]:i.coordinates[1]-r.coordinates[1];var o=Mu(t.coordinates,r.coordinates,i.coordinates);return o<0?1:o>0?-1:Math.pow(r.coordinates[0]-t.coordinates[0],2)+Math.pow(r.coordinates[1]-t.coordinates[1],2)-(Math.pow(i.coordinates[0]-t.coordinates[0],2)+Math.pow(i.coordinates[1]-t.coordinates[1],2))})),this.outerEdgesSorted=!0)}},{key:"getOuterEdges",value:function(){return this.sortOuterEdges(),this.outerEdges}},{key:"getOuterEdge",value:function(t){return this.sortOuterEdges(),this.outerEdges[t]}},{key:"addInnerEdge",value:function(t){this.innerEdges.push(t)}}],[{key:"buildId",value:function(t){return t.join(",")}}])}(),Cu=function(){function t(e,n){i(this,t),this.from=e,this.to=n,this.next=void 0,this.label=void 0,this.symetric=void 0,this.ring=void 0,this.from.addOuterEdge(this),this.to.addInnerEdge(this)}return s(t,[{key:"getSymetric",value:function(){return this.symetric||(this.symetric=new t(this.to,this.from),this.symetric.symetric=this),this.symetric}},{key:"deleteEdge",value:function(){this.from.removeOuterEdge(this),this.to.removeInnerEdge(this)}},{key:"isEqual",value:function(t){return this.from.id===t.from.id&&this.to.id===t.to.id}},{key:"toString",value:function(){return"Edge { ".concat(this.from.id," -> ").concat(this.to.id," }")}},{key:"toLineString",value:function(){return L([this.from.coordinates,this.to.coordinates])}},{key:"compareTo",value:function(t){return Mu(t.from.coordinates,t.to.coordinates,this.to.coordinates)}}])}(),Tu=function(){return s((function t(){i(this,t),this.edges=[],this.polygon=void 0,this.envelope=void 0}),[{key:"push",value:function(t){this.edges.push(t),this.polygon=this.envelope=void 0}},{key:"get",value:function(t){return this.edges[t]}},{key:"length",get:function(){return this.edges.length}},{key:"forEach",value:function(t){this.edges.forEach(t)}},{key:"map",value:function(t){return this.edges.map(t)}},{key:"some",value:function(t){return this.edges.some(t)}},{key:"isValid",value:function(){return!0}},{key:"isHole",value:function(){var t=this,e=this.edges.reduce((function(e,n,r){return n.from.coordinates[1]>t.edges[e].from.coordinates[1]&&(e=r),e}),0),n=(0===e?this.length:e)-1,r=(e+1)%this.length,i=Mu(this.edges[n].from.coordinates,this.edges[e].from.coordinates,this.edges[r].from.coordinates);return 0===i?this.edges[n].from.coordinates[0]>this.edges[r].from.coordinates[0]:i>0}},{key:"toMultiPoint",value:function(){return O(this.edges.map((function(t){return t.from.coordinates})))}},{key:"toPolygon",value:function(){if(this.polygon)return this.polygon;var t=this.edges.map((function(t){return t.from.coordinates}));return t.push(this.edges[0].from.coordinates),this.polygon=S([t])}},{key:"getEnvelope",value:function(){return this.envelope?this.envelope:this.envelope=Us(this.toPolygon())}},{key:"inside",value:function(t){return zt(t,this.toPolygon())}}],[{key:"findEdgeRingContaining",value:function(t,e){var n,r,i=t.getEnvelope();return e.forEach((function(e){var o,s,u,l,h,c,f=e.getEnvelope();if((r&&(n=r.getEnvelope()),s=i,u=(o=f).geometry.coordinates[0].map((function(t){return t[0]})),l=o.geometry.coordinates[0].map((function(t){return t[1]})),h=s.geometry.coordinates[0].map((function(t){return t[0]})),c=s.geometry.coordinates[0].map((function(t){return t[1]})),Math.max.apply(null,u)!==Math.max.apply(null,h)||Math.max.apply(null,l)!==Math.max.apply(null,c)||Math.min.apply(null,u)!==Math.min.apply(null,h)||Math.min.apply(null,l)!==Math.min.apply(null,c))&&Lu(f,i)){var g,p,v=a(t.map((function(t){return t.from.coordinates})));try{var d=function(){var t=p.value;e.some((function(e){return n=t,r=e.from.coordinates,n[0]===r[0]&&n[1]===r[1];var n,r}))||(g=t)};for(v.s();!(p=v.n()).done;)d()}catch(t){v.e(t)}finally{v.f()}g&&e.inside(I(g))&&(r&&!Lu(n,f)||(r=e))}})),r}}])}();var Ou=function(){function t(){i(this,t),this.edges=[],this.nodes={}}return s(t,[{key:"getNode",value:function(t){var e=Pu.buildId(t),n=this.nodes[e];return n||(n=this.nodes[e]=new Pu(t)),n}},{key:"addEdge",value:function(t,e){var n=new Cu(t,e),r=n.getSymetric();this.edges.push(n),this.edges.push(r)}},{key:"deleteDangles",value:function(){var t=this;Object.keys(this.nodes).map((function(e){return t.nodes[e]})).forEach((function(e){return t._removeIfDangle(e)}))}},{key:"_removeIfDangle",value:function(t){var e=this;if(t.innerEdges.length<=1){var n=t.getOuterEdges().map((function(t){return t.to}));this.removeNode(t),n.forEach((function(t){return e._removeIfDangle(t)}))}}},{key:"deleteCutEdges",value:function(){var t=this;this._computeNextCWEdges(),this._findLabeledEdgeRings(),this.edges.forEach((function(e){e.label===e.symetric.label&&(t.removeEdge(e.symetric),t.removeEdge(e))}))}},{key:"_computeNextCWEdges",value:function(t){var e=this;void 0===t?Object.keys(this.nodes).forEach((function(t){return e._computeNextCWEdges(e.nodes[t])})):t.getOuterEdges().forEach((function(e,n){t.getOuterEdge((0===n?t.getOuterEdges().length:n)-1).symetric.next=e}))}},{key:"_computeNextCCWEdges",value:function(t,e){for(var n,r,i=t.getOuterEdges(),o=i.length-1;o>=0;--o){var s=i[o],a=s.symetric,u=void 0,l=void 0;s.label===e&&(u=s),a.label===e&&(l=a),u&&l&&(l&&(r=l),u&&(r&&(r.next=u,r=void 0),n||(n=u)))}r&&(r.next=n)}},{key:"_findLabeledEdgeRings",value:function(){var t=[],e=0;return this.edges.forEach((function(n){if(!(n.label>=0)){t.push(n);var r=n;do{r.label=e,r=r.next}while(!n.isEqual(r));e++}})),t}},{key:"getEdgeRings",value:function(){var t=this;this._computeNextCWEdges(),this.edges.forEach((function(t){t.label=void 0})),this._findLabeledEdgeRings().forEach((function(e){t._findIntersectionNodes(e).forEach((function(n){t._computeNextCCWEdges(n,e.label)}))}));var e=[];return this.edges.forEach((function(n){n.ring||e.push(t._findEdgeRing(n))})),e}},{key:"_findIntersectionNodes",value:function(t){var e=[],n=t,r=function(){var r=0;n.from.getOuterEdges().forEach((function(e){e.label===t.label&&++r})),r>1&&e.push(n.from),n=n.next};do{r()}while(!t.isEqual(n));return e}},{key:"_findEdgeRing",value:function(t){var e=t,n=new Tu;do{n.push(e),e.ring=n,e=e.next}while(!t.isEqual(e));return n}},{key:"removeNode",value:function(t){var e=this;t.getOuterEdges().forEach((function(t){return e.removeEdge(t)})),t.innerEdges.forEach((function(t){return e.removeEdge(t)})),delete this.nodes[t.id]}},{key:"removeEdge",value:function(t){this.edges=this.edges.filter((function(e){return!e.isEqual(t)})),t.deleteEdge()}}],[{key:"fromGeoJson",value:function(e){!function(t){if(!t)throw new Error("No geojson passed");if("FeatureCollection"!==t.type&&"GeometryCollection"!==t.type&&"MultiLineString"!==t.type&&"LineString"!==t.type&&"Feature"!==t.type)throw new Error("Invalid input type '".concat(t.type,"'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature"))}(e);var n=new t;return xt(e,(function(t){et(t,"LineString","Graph::fromGeoJson"),ft(t,(function(t,e){if(t){var r=n.getNode(t),i=n.getNode(e);n.addEdge(r,i)}return e}))})),n}}])}();function Ru(t,e){var n,r;ct(t,(function(t,i,o,s,a){if(r!==a)e.push([]);else{var u=n[0],l=n[1],h=t[0],c=t[1];e[a].push([.75*u+.25*h,.75*l+.25*c]),e[a].push([.25*u+.75*h,.25*l+.75*c])}n=t,r=a}),!1),e.forEach((function(t){t.push(t[0])}))}function Au(t,e){var n,r,i;ct(t,(function(t,o,s,a,u){if(r!==a)e.push([[]]);else if(i!==u)e[a].push([]);else{var l=n[0],h=n[1],c=t[0],f=t[1];e[a][u].push([.75*l+.25*c,.75*h+.25*f]),e[a][u].push([.25*l+.75*c,.25*h+.75*f])}n=t,r=a,i=u}),!1),e.forEach((function(t){t.forEach((function(t){t.push(t[0])}))}))}function Du(t,e,n,r,i){for(var o=0;o0?qu(e,s,r)<0||(r=s):n>0&&u<=0&&(Fu(e,s,i)||(i=s)),n=u}return[r,i]}function Fu(t,e,n){return qu(t,e,n)>0}function qu(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(n[0]-t[0])*(e[1]-t[1])}function Vu(t){return Bu(t,"mercator",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Gu(t){return Bu(t,"wgs84",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Bu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=(n=n||{}).mutate;if(!t)throw new Error("geojson is required");return Array.isArray(t)&&U(t[0])?t="mercator"===e?Yu(t):zu(t):(!0!==r&&(t=Ai(t)),ct(t,(function(t){var n="mercator"===e?Yu(t):zu(t);t[0]=n[0],t[1]=n[1]}))),t}function Yu(t){var e=Math.PI/180,n=6378137,r=20037508.342789244,i=Math.abs(t[0])<=180?t[0]:t[0]-360*function(t){return t<0?-1:t>0?1:0}(t[0]),o=[n*i*e,n*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return o[0]>r&&(o[0]=r),o[0]<-r&&(o[0]=-r),o[1]>r&&(o[1]=r),o[1]<-r&&(o[1]=-r),o}function zu(t){var e=180/Math.PI,n=6378137;return[t[0]*e/n,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/n)))*e]}var ju=Object.freeze({__proto__:null,toMercator:Vu,toWgs84:Gu});var Xu={20:1.07275,15:1.13795,10:1.22385,5:1.3581,2:1.51743,1:1.62762};function Uu(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}function Zu(t){var e=[];return function t(n){return 0===n||1===n?1:e[n]>0?e[n]:e[n]=t(n-1)*n}(t)}function Hu(t){return Ju(t),Wu(t)}function Wu(t){return Array.isArray(t)?el(t):t&&t.bbox?el(t.bbox):[360*tl(),180*tl()]}function Ju(t){null!=t&&(Array.isArray(t)?H(t):null!=t.bbox&&H(t.bbox))}function Ku(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1);for(var n=[],r=0;r1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1),void 0!==e.bbox&&null!==e.bbox||(e.bbox=[-180,-90,180,90]),U(e.num_vertices)&&void 0!==e.num_vertices||(e.num_vertices=10),U(e.max_radial_length)&&void 0!==e.max_radial_length||(e.max_radial_length=10);var n=Math.abs(e.bbox[0]-e.bbox[2]),r=Math.abs(e.bbox[1]-e.bbox[3]),i=Math.min(n/2,r/2);if(e.max_radial_length>i)throw new Error("max_radial_length is greater than the radius of the bbox");for(var o=[e.bbox[0]+e.max_radial_length,e.bbox[1]+e.max_radial_length,e.bbox[2]-e.max_radial_length,e.bbox[3]-e.max_radial_length],s=[],a=function(){var t,n=[],r=d(Array(e.num_vertices+1)).map(Math.random);r.forEach((function(t,e,n){n[e]=e>0?t+n[e-1]:t})),r.forEach((function(t){t=2*t*Math.PI/r[r.length-1];var i=Math.random();n.push([i*(e.max_radial_length||10)*Math.sin(t),i*(e.max_radial_length||10)*Math.cos(t)])})),n[n.length-1]=n[0],n=n.reverse().map((t=Wu(o),function(e){return[e[0]+t[0],e[1]+t[1]]})),s.push(S([n]))},u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox;Ju(n);var r=e.num_vertices,i=e.max_length,o=e.max_rotation;null==t&&(t=1),(!U(r)||void 0===r||r<2)&&(r=10),U(i)&&void 0!==i||(i=1e-4),U(o)&&void 0!==o||(o=Math.PI/8);for(var s=[],a=0;a0;){var l=a.pop();if(l===n)return ll(l);l.closed=!0;for(var h=t.neighbors(l),c=0,f=h.length;c1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function dl(t,e,n,r,i){for(var o,s=r,a=e+1;as&&(o=a,s=u)}s>r&&(o-e>1&&dl(t,e,o,r,i),i.push(t[o]),n-o>1&&dl(t,o,n,r,i))}function yl(t,e){var n=t.length-1,r=[t[0]];return dl(t,0,n,e,r),r.push(t[n]),r}function ml(t,e,n){if(t.length<=2)return t;var r=void 0!==e?e*e:1;return t=n?t:function(t,e){for(var n,r,i,o,s,a=t[0],u=[a],l=1,h=t.length;le&&(u.push(n),a=n);return a!==n&&u.push(n),u}(t,r),t=yl(t,r)}function _l(t,e,n){return t.map((function(t){if(t.length<4)throw new Error("invalid polygon");for(var r=e,i=ml(t,r,n);!xl(i);)i=ml(t,r-=.01*r,n);return i[i.length-1][0]===i[0][0]&&i[i.length-1][1]===i[0][1]||i.push(i[0]),i}))}function xl(t){return!(t.length<3)&&!(3===t.length&&t[2][0]===t[0][0]&&t[2][1]===t[0][1])}function El(t,e){return{x:t[0]-e[0],y:t[1]-e[1]}}cl.prototype.init=function(){this.dirtyNodes=[];for(var t=0;t0&&(this.content[0]=e,this.bubbleUp(0)),t},remove:function(t){var e=this.content.indexOf(t),n=this.content.pop();e!==this.content.length-1&&(this.content[e]=n,this.scoreFunction(n)0;){var n=(t+1>>1)-1,r=this.content[n];if(!(this.scoreFunction(e)80*i){o=a=t[0],s=h=t[1];for(var _=i;_a&&(a=c),g>h&&(h=g);p=0!==(p=Math.max(a-o,h-s))?32767/p:0}return r(y,m,i,o,s,p,0),m}function e(t,e,n,r,i){var o,s;if(i===I(t,e,n,r)>0)for(o=e;o=e;o-=r)s=k(o,t[o],t[o+1],s);return s&&d(s,s.next)&&(b(s),s=s.next),s}function n(t,e){if(!t)return t;e||(e=t);var n,r=t;do{if(n=!1,r.steiner||!d(r,r.next)&&0!==v(r.prev,r,r.next))r=r.next;else{if(b(r),(r=e=r.prev)===r.next)break;n=!0}}while(n||r!==e);return e}function r(t,e,u,l,h,f,g){if(t){!g&&f&&function(t,e,n,r){var i=t;do{0===i.z&&(i.z=c(i.x,i.y,e,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,n,r,i,o,s,a,u,l=1;do{for(n=t,t=null,o=null,s=0;n;){for(s++,r=n,a=0,e=0;e0||u>0&&r;)0!==a&&(0===u||!r||n.z<=r.z)?(i=n,n=n.nextZ,a--):(i=r,r=r.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;n=r}o.nextZ=null,l*=2}while(s>1)}(i)}(t,l,h,f);for(var p,v,d=t;t.prev!==t.next;)if(p=t.prev,v=t.next,f?o(t,l,h,f):i(t))e.push(p.i/u|0),e.push(t.i/u|0),e.push(v.i/u|0),b(t),t=v.next,d=v.next;else if((t=v)===d){g?1===g?r(t=s(n(t),e,u),e,u,l,h,f,2):2===g&&a(t,e,u,l,h,f):r(n(t),e,u,l,h,f,1);break}}}function i(t){var e=t.prev,n=t,r=t.next;if(v(e,n,r)>=0)return!1;for(var i=e.x,o=n.x,s=r.x,a=e.y,u=n.y,l=r.y,h=io?i>s?i:s:o>s?o:s,p=a>u?a>l?a:l:u>l?u:l,d=r.next;d!==e;){if(d.x>=h&&d.x<=f&&d.y>=c&&d.y<=p&&g(i,a,o,u,s,l,d.x,d.y)&&v(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function o(t,e,n,r){var i=t.prev,o=t,s=t.next;if(v(i,o,s)>=0)return!1;for(var a=i.x,u=o.x,l=s.x,h=i.y,f=o.y,p=s.y,d=au?a>l?a:l:u>l?u:l,_=h>f?h>p?h:p:f>p?f:p,x=c(d,y,e,n,r),E=c(m,_,e,n,r),k=t.prevZ,b=t.nextZ;k&&k.z>=x&&b&&b.z<=E;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;if(k=k.prevZ,b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;k&&k.z>=x;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;k=k.prevZ}for(;b&&b.z<=E;){if(b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function s(t,e,r){var i=t;do{var o=i.prev,s=i.next.next;!d(o,s)&&y(o,i,i.next,s)&&x(o,s)&&x(s,o)&&(e.push(o.i/r|0),e.push(i.i/r|0),e.push(s.i/r|0),b(i),b(i.next),i=t=s),i=i.next}while(i!==t);return n(i)}function a(t,e,i,o,s,a){var u=t;do{for(var l=u.next.next;l!==u.prev;){if(u.i!==l.i&&p(u,l)){var h=E(u,l);return u=n(u,u.next),h=n(h,h.next),r(u,e,i,o,s,a,0),void r(h,e,i,o,s,a,0)}l=l.next}u=u.next}while(u!==t)}function u(t,e){return t.x-e.x}function l(t,e){var r=function(t,e){var n,r=e,i=t.x,o=t.y,s=-1/0;do{if(o<=r.y&&o>=r.next.y&&r.next.y!==r.y){var a=r.x+(o-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=i&&a>s&&(s=a,n=r.x=r.x&&r.x>=c&&i!==r.x&&g(on.x||r.x===n.x&&h(n,r)))&&(n=r,p=u)),r=r.next}while(r!==l);return n}(t,e);if(!r)return e;var i=E(r,t);return n(i,i.next),n(r,r.next)}function h(t,e){return v(t.prev,t,e.prev)<0&&v(e.next,t,t.next)<0}function c(t,e,n,r,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function f(t){var e=t,n=t;do{(e.x=(t-s)*(o-a)&&(t-s)*(r-a)>=(n-s)*(e-a)&&(n-s)*(o-a)>=(i-s)*(r-a)}function p(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&y(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(x(t,e)&&x(e,t)&&function(t,e){var n=t,r=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{n.y>o!=n.next.y>o&&n.next.y!==n.y&&i<(n.next.x-n.x)*(o-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==t);return r}(t,e)&&(v(t.prev,t,e.prev)||v(t,e.prev,e))||d(t,e)&&v(t.prev,t,t.next)>0&&v(e.prev,e,e.next)>0)}function v(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function d(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,n,r){var i=_(v(t,e,n)),o=_(v(t,e,r)),s=_(v(n,r,t)),a=_(v(n,r,e));return i!==o&&s!==a||(!(0!==i||!m(t,n,e))||(!(0!==o||!m(t,r,e))||(!(0!==s||!m(n,t,r))||!(0!==a||!m(n,e,r)))))}function m(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function _(t){return t>0?1:t<0?-1:0}function x(t,e){return v(t.prev,t,t.next)<0?v(t,e,t.next)>=0&&v(t,t.prev,e)>=0:v(t,e,t.prev)<0||v(t,t.next,e)<0}function E(t,e){var n=new w(t.i,t.x,t.y),r=new w(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,n.next=i,i.prev=n,r.next=n,n.prev=r,o.next=r,r.prev=o,r}function k(t,e,n,r){var i=new w(t,e,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function b(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 w(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function I(t,e,n,r){for(var i=0,o=e,s=n-r;o0&&(r+=t[i-1].length,n.holes.push(r))}return n},bl.exports}(),Il=mn(wl);function Nl(t){var e=function(t){for(var e=t[0][0].length,n={vertices:[],holes:[],dimensions:e},r=0,i=0;i0&&(r+=t[i-1].length,n.holes.push(r))}return n}(t),n=Il(e.vertices,e.holes,2),r=[],i=[];n.forEach((function(t,r){var o=n[r];i.push([e.vertices[2*o],e.vertices[2*o+1]])}));for(var o=0;o=1||u<=0||l>=1||l<=0))){var v=p,d=!o[v];d&&(o[v]=!0),e?i.push(e(p,t,n,h,c,u,s,a,f,g,l,d)):i.push(p)}}function v(t,e){var n,i,o,s,a=r[t][e],u=r[t][e+1];return a[0]f[e.isect].coord?-1:1}));for(l=[];x.length>0;){var I=x.pop(),N=I.isect,M=I.parent,L=I.winding,P=l.length,T=[f[N].coord],O=N;if(f[N].ringAndEdge1Walkable)var R=f[N].ringAndEdge1,A=f[N].nxtIsectAlongRingAndEdge1;else R=f[N].ringAndEdge2,A=f[N].nxtIsectAlongRingAndEdge2;for(;!Rl(f[N].coord,f[A].coord);){T.push(f[A].coord);var D=void 0;for(r=0;r1)for(e=0;e=0==e}function Ol(t){for(var e=0,n=0;n0)){if(o/=f,f<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=r-u,f||!(o<0)){if(o/=f,f<0){if(o>c)return;o>h&&(h=o)}else if(f>0){if(o0)){if(o/=g,g<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=i-l,g||!(o<0)){if(o/=g,g<0){if(o>c)return;o>h&&(h=o)}else if(g>0){if(o0||c<1)||(h>0&&(t[0]=[u+h*f,l+h*g]),c<1&&(t[1]=[u+c*f,l+c*g]),!0)}}}}}function Hl(t,e,n,r,i){var o=t[1];if(o)return!0;var s,a,u=t[0],l=t.left,h=t.right,c=l[0],f=l[1],g=h[0],p=h[1],v=(c+g)/2,d=(f+p)/2;if(p===f){if(v=r)return;if(c>g){if(u){if(u[1]>=i)return}else u=[v,n];o=[v,i]}else{if(u){if(u[1]1)if(c>g){if(u){if(u[1]>=i)return}else u=[(n-a)/s,n];o=[(i-a)/s,i]}else{if(u){if(u[1]=r)return}else u=[e,s*e+a];o=[r,s*r+a]}else{if(u){if(u[0]=-dh)){var g=u*u+l*l,p=h*h+c*c,v=(c*g-l*p)/f,d=(u*p-h*g)/f,y=$l.pop()||new th;y.arc=t,y.site=i,y.x=v+s,y.y=(y.cy=d+a)+Math.sqrt(v*v+d*d),t.circle=y;for(var m=null,_=gh._;_;)if(y.y<_.y||y.y===_.y&&y.x<=_.x){if(!_.L){m=_.P;break}_=_.L}else{if(!_.R){m=_;break}_=_.R}gh.insert(m,y),m||(Ql=y)}}}}function nh(t){var e=t.circle;e&&(e.P||(Ql=e.N),gh.remove(e),$l.push(e),Gl(e),t.circle=null)}var rh=[];function ih(){Gl(this),this.edge=this.site=this.circle=null}function oh(t){var e=rh.pop()||new ih;return e.site=t,e}function sh(t){nh(t),ch.remove(t),rh.push(t),Gl(t)}function ah(t){var e=t.circle,n=e.x,r=e.cy,i=[n,r],o=t.P,s=t.N,a=[t];sh(t);for(var u=o;u.circle&&Math.abs(n-u.circle.x)vh)a=a.L;else{if(!((i=o-hh(a,s))>vh)){r>-vh?(e=a.P,n=a):i>-vh?(e=a,n=a.N):e=n=a;break}if(!a.R){e=a;break}a=a.R}!function(t){fh[t.index]={site:t,halfedges:[]}}(t);var u=oh(t);if(ch.insert(e,u),e||n){if(e===n)return nh(e),n=oh(e.site),ch.insert(u,n),u.edge=n.edge=jl(e.site,u.site),eh(e),void eh(n);if(n){nh(e),nh(n);var l=e.site,h=l[0],c=l[1],f=t[0]-h,g=t[1]-c,p=n.site,v=p[0]-h,d=p[1]-c,y=2*(f*d-g*v),m=f*f+g*g,_=v*v+d*d,x=[(d*m-g*_)/y+h,(f*_-v*m)/y+c];Ul(n.edge,l,p,x),u.edge=jl(l,t,null,x),n.edge=jl(t,p,null,x),eh(e),eh(n)}else u.edge=jl(e.site,u.site)}}function lh(t,e){var n=t.site,r=n[0],i=n[1],o=i-e;if(!o)return r;var s=t.P;if(!s)return-1/0;var a=(n=s.site)[0],u=n[1],l=u-e;if(!l)return a;var h=a-r,c=1/o-1/l,f=h/l;return c?(-f+Math.sqrt(f*f-2*c*(h*h/(-2*l)-u+l/2+i-o/2)))/c+r:(r+a)/2}function hh(t,e){var n=t.N;if(n)return lh(n,e);var r=t.site;return r[1]===e?r[0]:1/0}var ch,fh,gh,ph,vh=1e-6,dh=1e-12;function yh(t,e){return e[1]-t[1]||e[0]-t[0]}function mh(t,e){var n,r,i,o=t.sort(yh).pop();for(ph=[],fh=new Array(t.length),ch=new Vl,gh=new Vl;;)if(i=Ql,o&&(!i||o[1]vh||Math.abs(i[0][1]-i[1][1])>vh)||delete ph[o]}(s,a,u,l),function(t,e,n,r){var i,o,s,a,u,l,h,c,f,g,p,v,d=fh.length,y=!0;for(i=0;ivh||Math.abs(v-f)>vh)&&(u.splice(a,0,ph.push(Xl(s,g,Math.abs(p-t)vh?[t,Math.abs(c-t)vh?[Math.abs(f-r)vh?[n,Math.abs(c-n)vh?[Math.abs(f-e)=a)return null;var u=t-i.site[0],l=e-i.site[1],h=u*u+l*l;do{i=o.cells[r=s],s=null,i.halfedges.forEach((function(n){var r=o.edges[n],a=r.left;if(a!==i.site&&a||(a=r.right)){var u=t-a[0],l=e-a[1],c=u*u+l*l;c2&&void 0!==arguments[2]?arguments[2]:{},r=rt(t).coordinates,i=0,o=0;o=i&&o===r.length-1);o++){if(i>=e){var s=e-i;if(s){var a=st(r[o],r[o-1])-180;return at(r[o],s,a,n)}return I(r[o])}i+=ut(r[o],r[o+1],n)}return I(r[r.length-1])},t.angle=function(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!Z(r))throw new Error("options is invalid");if(!t)throw new Error("startPoint is required");if(!e)throw new Error("midPoint is required");if(!n)throw new Error("endPoint is required");var i=t,o=e,s=n,a=G(!0!==r.mercator?st(o,i):lt(o,i)),u=G(!0!==r.mercator?st(o,s):lt(o,s));u1&&void 0!==arguments[1]?arguments[1]:{},n=e.resolution||1e4,r=e.sharpness||.85,i=[],o=rt(t).coordinates.map((function(t){return{x:t[0],y:t[1]}})),s=new Gt({duration:n,points:o,sharpness:r}),a=function(t){var e=s.pos(t);Math.floor(t/100)%2==0&&i.push([e.x,e.y])},u=0;u0;else if(n!==u>0)return!0}return!1},t.booleanContains=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type,s=n.coordinates,u=r.coordinates;switch(i){case"Point":if("Point"===o)return Ht(s,u);throw new Error("feature2 "+o+" geometry not supported");case"MultiPoint":switch(o){case"Point":return function(t,e){var n,r=!1;for(n=0;n2&&void 0!==arguments[2]?arguments[2]:{}).precision;if("number"!=typeof(n=null==n||isNaN(n)?6:n)||!(n>=0))throw new Error("precision must be a positive number");return rt(t).type===rt(e).type&&Ne(Le(t),Le(e),{precision:n})},t.booleanIntersects=Oe,t.booleanOverlap=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;if("MultiPoint"===i&&"MultiPoint"!==o||("LineString"===i||"MultiLineString"===i)&&"LineString"!==o&&"MultiLineString"!==o||("Polygon"===i||"MultiPolygon"===i)&&"Polygon"!==o&&"MultiPolygon"!==o)throw new Error("features must be of the same type");if("Point"===i)throw new Error("Point geometry not supported");if(Ne(t,e,{precision:6}))return!1;var s=0;switch(i){case"MultiPoint":for(var a=0;a0},t.booleanParallel=function(t,e){if(!t)throw new Error("line1 is required");if(!e)throw new Error("line2 is required");if("LineString"!==In(t,"line1"))throw new Error("line1 must be a LineString");if("LineString"!==In(e,"line2"))throw new Error("line2 must be a LineString");for(var n=$e(Le(t)).features,r=$e(Le(e)).features,i=0;i1;case"MultiPoint":for(var i=0;i0&&ue(S([r[0]]),S([r[i]])).features.length>1)return!1}return!0;case"MultiPolygon":for(i=0;i0&&ue(S([o[0]]),S([o[s]])).features.length>1)return!1}return!0;default:return!1}},t.booleanWithin=Cn,t.buffer=function(t,e,n){var r=(n=n||{}).units||"kilometers",i=n.steps||8;if(!t)throw new Error("geojson is required");if("object"!==m(n))throw new Error("options must be an object");if("number"!=typeof i)throw new Error("steps must be an number");if(void 0===e)throw new Error("radius is required");if(i<=0)throw new Error("steps must be greater than 0");var o=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){var n=ui(t,e,r,i);n&&o.push(n)})),C(o);case"FeatureCollection":return vt(t,(function(t){var n=ui(t,e,r,i);n&&vt(n,(function(t){t&&o.push(t)}))})),C(o)}return ui(t,e,r,i)},t.center=An,t.centerMean=fi,t.centerMedian=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.counter||10;if(!U(n))throw new Error("counter must be a number");var r=e.weight,i=fi(t,{weight:e.weight}),o=C([]);vt(t,(function(t){var e;o.features.push(gi(t,{properties:{weight:null==(e=t.properties)?void 0:e[r]}}))}));var s={tolerance:e.tolerance,medianCandidates:[]};return pi(i.geometry.coordinates,[0,0],o,s,n)},t.centerOfMass=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(it(e)){case"Point":return I(K(e),n.properties);case"Polygon":var r=[];ct(e,(function(t){r.push(t)}));var i,o,s,a,u,l,h,c,f=gi(e,{properties:n.properties}),g=f.geometry.coordinates,p=0,v=0,d=0,y=r.map((function(t){return[t[0]-g[0],t[1]-g[1]]}));for(i=0;i2&&void 0!==arguments[2]?arguments[2]:{};!0!==n.mutate&&(t=Ai(t));var r=n.minPoints||3,i=V(e,n.units),o=new to(t.features.length),s=t.features.map((function(t){return!1})),a=t.features.map((function(t){return!1})),u=t.features.map((function(t){return!1})),l=t.features.map((function(t){return-1}));o.load(t.features.map((function(t,e){var n=v(t.geometry.coordinates,2),r=n[0],i=n[1];return{minX:r,minY:i,maxX:r,maxY:i,index:e}})));var h=function(n){var r=t.features[n],s=v(r.geometry.coordinates,2),a=s[0],u=s[1],l=Math.max(u-i,-90),h=Math.min(u+i,90),c=l<0&&h>0?i:Math.abs(l)=r){var i=c;c++,s[e]=!0,function(t,e){for(var n=0;n=r&&e.push.apply(e,d(o))}a[i]||(a[i]=!0,l[i]=t)}}(i,n)}else u[e]=!0}})),t.features.forEach((function(e,n){var r=t.features[n];r.properties||(r.properties={}),l[n]>=0?(r.properties.dbscan=u[n]?"edge":"core",r.properties.cluster=l[n]):r.properties.dbscan="noise"})),t},t.clustersKmeans=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.features.length;e.numberOfClusters=e.numberOfClusters||Math.round(Math.sqrt(n/2)),e.numberOfClusters>n&&(e.numberOfClusters=n),!0!==e.mutate&&(t=Ai(t));var r=yt(t),i=r.slice(0,e.numberOfClusters),o=ro(r,e.numberOfClusters,i),s={};return o.centroids.forEach((function(t,e){s[e]=t})),vt(t,(function(t,e){var n=o.idxs[e];t.properties.cluster=n,t.properties.centroid=s[n]})),t},t.collect=function(t,e,n,r){var i=new io(6),o=e.features.map((function(t){var e;return{minX:t.geometry.coordinates[0],minY:t.geometry.coordinates[1],maxX:t.geometry.coordinates[0],maxY:t.geometry.coordinates[1],property:null==(e=t.properties)?void 0:e[n]}}));return i.load(o),t.features.forEach((function(t){t.properties||(t.properties={});var e=Rt(t),n=i.search({minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}),o=[];n.forEach((function(e){zt([e.minX,e.minY],t)&&o.push(e.property)})),t.properties[r]=o})),t},t.collectionOf=nt,t.combine=function(t){var e={MultiPoint:{coordinates:[],properties:[]},MultiLineString:{coordinates:[],properties:[]},MultiPolygon:{coordinates:[],properties:[]}};return vt(t,(function(t){var n,r,i,o;switch(null==(o=t.geometry)?void 0:o.type){case"Point":e.MultiPoint.coordinates.push(t.geometry.coordinates),e.MultiPoint.properties.push(t.properties);break;case"MultiPoint":(n=e.MultiPoint.coordinates).push.apply(n,d(t.geometry.coordinates)),e.MultiPoint.properties.push(t.properties);break;case"LineString":e.MultiLineString.coordinates.push(t.geometry.coordinates),e.MultiLineString.properties.push(t.properties);break;case"MultiLineString":(r=e.MultiLineString.coordinates).push.apply(r,d(t.geometry.coordinates)),e.MultiLineString.properties.push(t.properties);break;case"Polygon":e.MultiPolygon.coordinates.push(t.geometry.coordinates),e.MultiPolygon.properties.push(t.properties);break;case"MultiPolygon":(i=e.MultiPolygon.coordinates).push.apply(i,d(t.geometry.coordinates)),e.MultiPolygon.properties.push(t.properties)}})),C(Object.keys(e).filter((function(t){return e[t].coordinates.length})).sort().map((function(t){return b({type:t,coordinates:e[t].coordinates},{collectedProperties:e[t].properties})})))},t.concave=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.maxEdge||1/0,r=function(t){var e=[],n={};return vt(t,(function(t){if(t.geometry){var r=t.geometry.coordinates.join("-");Object.prototype.hasOwnProperty.call(n,r)||(e.push(t),n[r]=!0)}})),C(e)}(t),i=oo(r);if(i.features=i.features.filter((function(t){var r=t.geometry.coordinates[0][0],i=t.geometry.coordinates[0][1],o=t.geometry.coordinates[0][2],s=ut(r,i,e),a=ut(i,o,e),u=ut(r,o,e);return s<=n&&a<=n&&u<=n})),i.features.length<1)return null;var o=Ro(i);return 1===o.coordinates.length&&(o.coordinates=o.coordinates[0],o.type="Polygon"),b(o)},t.containsNumber=$,t.convertArea=X,t.convertLength=j,t.convex=Oi,t.coordAll=yt,t.coordEach=ct,t.coordReduce=ft,t.createBins=zi,t.degreesToRadians=z,t.destination=at,t.difference=function(t){var e=[];if(mt(t,(function(t){e.push(t.coordinates)})),e.length<2)throw new Error("Must have at least two features");var n=t.features[0].properties||{},r=As.apply(Fs,[e[0]].concat(d(e.slice(1))));return 0===r.length?null:1===r.length?S(r[0],n):R(r,n)},t.dissolve=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.propertyName;nt(t,"Polygon","dissolve");var r=[];if(!n)return qs(R(Os.apply(null,t.features.map((function(t){return t.geometry.coordinates})))));var i={};vt(t,(function(t){t.properties&&(Object.prototype.hasOwnProperty.call(i,t.properties[n])||(i[t.properties[n]]=[]),i[t.properties[n]].push(t))}));for(var o=Object.keys(i),s=0;s1&&void 0!==arguments[1]?arguments[1]:{},o=i.properties,s=null==(e=i.autoComplete)||e,a=null==(n=i.orderCoords)||n;if(null!=(r=i.mutate)&&r||(t=Ai(t)),"FeatureCollection"===t.type){var u=[];return t.features.forEach((function(t){u.push(Q(ru(t,{},s,a)))})),R(u,o)}return ru(t,o,s,a)},t.mask=function(t,e,n){var r,i=null!=(r=null==n?void 0:n.mutate)&&r,o=e;e&&!1===i&&(o=Ai(e));var s,a=su(o);return("FeatureCollection"===t.type?ou(2===(s=t).features.length?Os(s.features[0].geometry.coordinates,s.features[1].geometry.coordinates):Os.apply(Fs,s.features.map((function(t){return t.geometry.coordinates})))):"Feature"===t.type?ou(Os(t.geometry.coordinates)):ou(Os(t.coordinates))).geometry.coordinates.forEach((function(t){a.geometry.coordinates.push(t[0])})),a},t.meta=Mt,t.midpoint=function(t,e){return at(t,ut(t,e)/2,st(t,e))},t.moranIndex=function(t,e){var n,r,i=e.inputField,o=e.threshold||1e5,s=e.p||2,u=null!=(n=e.binary)&&n,l=Gs(t,{alpha:e.alpha||-1,binary:u,p:s,standardization:null==(r=e.standardization)||r,threshold:o}),h=[];vt(t,(function(t){var e=t.properties||{};h.push(e[i])}));for(var c=au(h),f=function(t){var e,n=au(t),r=0,i=a(t);try{for(i.s();!(e=i.n()).done;){var o=e.value;r+=Math.pow(o-n,2)}}catch(t){i.e(t)}finally{i.f()}return r/t.length}(h),g=0,p=0,v=0,d=0,y=l.length,m=0;m2&&void 0!==arguments[2]?arguments[2]:{},r=n.units,i=n.properties||{},o=function(t){var e=[];switch(t.geometry?t.geometry.type:t.type){case"GeometryCollection":return mt(t,(function(t){"Point"===t.type&&e.push({type:"Feature",properties:{},geometry:t})})),{type:"FeatureCollection",features:e};case"FeatureCollection":return t.features=t.features.filter((function(t){return"Point"===t.geometry.type})),t;default:throw new Error("points must be a Point Collection")}}(t);if(!o.features.length)throw new Error("points must contain features");if(!e)throw new Error("line is required");if("LineString"!==it(e))throw new Error("line must be a LineString");var s=1/0,a=null;return vt(o,(function(t){var n=mu(t,e,{units:r});n2&&void 0!==arguments[2]?arguments[2]:{},a=null!=(i=s.method)?i:"geodesic",u=null!=(o=s.units)?o:"kilometers";if(!e)throw new Error("point is required");if(!r)throw new Error("polygon or multi-polygon is required");var l,h=rt(r);if("MultiPolygon"===h.type){var c=h.coordinates.map((function(n){return t(e,S(n),{method:a,units:u})}));return Math.min.apply(Math,d(c.map(Math.abs)))*(zt(e,r)?-1:1)}if(h.coordinates.length>1){var p=h.coordinates.map((function(n){return t(e,S([n]),{method:a,units:u})})),v=n(l=p)||f(l)||_(l)||g(),y=v[0],m=v.slice(1);if(y>=0)return y;var x=Math.min.apply(Math,d(m));return x<0?Math.abs(x):Math.min(x,Math.abs(y))}var E=le(h),k=1/0;return xt(E,(function(t){k=Math.min(k,mu(e,t,{method:a,units:u}))})),zt(e,h)?-k:k},t.points=N,t.pointsWithinPolygon=Su,t.polygon=S,t.polygonSmooth=function(t,e){(e=e||{}).iterations=e.iterations||1;var n=e.iterations,r=[];if(!t)throw new Error("inputPolys is required");return mt(t,(function(t,e,i){if("Polygon"===t.type){for(var o=[[]],s=0;s0&&(u=S(o).geometry),Ru(u,a),o=a.slice(0)}r.push(S(o,i))}else{if("MultiPolygon"!==t.type)throw new Error("geometry is invalid, must be Polygon or MultiPolygon");for(var l=[[[]]],h=0;h0&&(f=R(l).geometry),Au(f,c),l=c.slice(0)}r.push(R(l,i))}})),C(r)},t.polygonTangents=function(t,e){var n,r=Q(t),i=Q(e),o=[],s=[],a=Rt(e),u=0,l=null;switch(r[0]>a[0]&&r[0]a[1]&&r[1]_&&(_=k)}for(var b=[],w=Object.keys(l).length,I=f/w,N=0,S=0;S<_+1;S++)N+=Math.exp(-I)*Math.pow(I,S)/Zu(S),b.push(N);for(var M=[],L=0,P=0;P<_+1;P++){for(var C=0,T=Object.keys(l);CR&&(R=D)}var F=Xu[r]/Math.sqrt(w),q={criticalValue:F,isRandom:!0,maxAbsoluteDifference:R,observedDistribution:M};return R>F&&(q.isRandom=!1),q},t.radiansToDegrees=Y,t.radiansToLength=F,t.random=nl,t.randomLineString=$u,t.randomPoint=Ku,t.randomPolygon=Qu,t.randomPosition=Hu,t.rectangleGrid=oa,t.rewind=function(t){var e,n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(r=r||{}))throw new Error("options is invalid");var i=null!=(e=r.mutate)&&e,o=null!=(n=r.reverse)&&n;if(!t)throw new Error(" is required");if("boolean"!=typeof o)throw new Error(" must be a boolean");if("boolean"!=typeof i)throw new Error(" must be a boolean");i||"Point"===t.type||"MultiPoint"===t.type||(t=Ai(t));var s=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){rl(t,o)})),t;case"FeatureCollection":return vt(t,(function(t){vt(rl(t,o),(function(t){s.push(t)}))})),C(s)}return rl(t,o)},t.rhumbBearing=lt,t.rhumbDestination=Bs,t.rhumbDistance=Ys,t.round=D,t.sample=function(t,e){if(!t)throw new Error("fc is required");if(null==e)throw new Error("num is required");if("number"!=typeof e)throw new Error("num must be a number");var n=C(function(t,e){var n,r,i=t.slice(0),o=t.length,s=o-e;for(;o-- >s;)n=i[r=Math.floor((o+1)*Math.random())],i[r]=i[o],i[o]=n;return i.slice(s)}(t.features,e));return n},t.sector=function(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!Z(i=i||{}))throw new Error("options is invalid");var o=i.properties;if(!t)throw new Error("center is required");if(null==n)throw new Error("bearing1 is required");if(null==r)throw new Error("bearing2 is required");if(!e)throw new Error("radius is required");if("object"!==m(i))throw new Error("options must be an object");if(sl(n)===sl(r))return Ri(t,e,i);var s=Q(t),a=ja(t,e,n,r,i),u=[[s]];return ct(a,(function(t){u[0].push(t)})),u[0].push(s),S(u,o)},t.segmentEach=kt,t.segmentReduce=bt,t.shortestPath=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.obstacles||C([]),i=n.resolution||100;if(!t)throw new Error("start is required");if(!e)throw new Error("end is required");if(i&&(!U(i)||i<=0))throw new Error("options.resolution must be a number, greater than 0");var o=K(t),s=K(e);if(t=I(o),e=I(s),"FeatureCollection"===r.type){if(0===r.features.length)return L([o,s])}else{if("Polygon"!==r.type)throw new Error("invalid obstacles");r=C([b(rt(r))])}var a=r;a.features.push(t),a.features.push(e);var u=v(Rt(al(Vt(Rt(a)),1.15)),4),l=u[0],h=u[1],c=u[2],f=u[3],g=ut([l,h],[c,h],n)/i;a.features.pop(),a.features.pop();for(var p,d,y=g/ut([l,h],[c,h],n)*(c-l),m=g/ut([l,h],[l,f],n)*(f-h),_=c-l,x=f-h,E=Math.floor(_/y),k=Math.floor(x/m),w=(_-E*y)/2,N=[],S=[],M=1/0,P=1/0,T=f-(x-k*m)/2,O=0;T>=h;){for(var R=[],A=[],D=l+w,F=0;D<=c;){var q=I([D,T]),V=pl(q,r);R.push(V?0:1),A.push(D+"|"+T);var G=ut(q,t);!V&&G1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(i=null!=i?i:{}))throw new Error("options is invalid");var o=null!=(e=i.tolerance)?e:1,s=null!=(n=i.highQuality)&&n,a=null!=(r=i.mutate)&&r;if(!t)throw new Error("geojson is required");if(o&&o<0)throw new Error("invalid tolerance");return!0!==a&&(t=Ai(t)),mt(t,(function(t){!function(t,e,n){var r=t.type;if("Point"===r||"MultiPoint"===r)return t;if(Le(t,{mutate:!0}),"GeometryCollection"!==r)switch(r){case"LineString":t.coordinates=ml(t.coordinates,e,n);break;case"MultiLineString":t.coordinates=t.coordinates.map((function(t){return ml(t,e,n)}));break;case"Polygon":t.coordinates=_l(t.coordinates,e,n);break;case"MultiPolygon":t.coordinates=t.coordinates.map((function(t){return _l(t,e,n)}))}}(t,o,s)})),t},t.square=Ka,t.squareGrid=sa,t.standardDeviationalEllipse=function(t,e){var n;if(!Z(e=e||{}))throw new Error("options is invalid");var r=e.steps||64,i=e.weight,o=e.properties||{};if(!U(r))throw new Error("steps must be a number");if(!Z(o))throw new Error("properties must be a number");var s=yt(t).length,a=fi(t,{weight:i}),u=0,l=0,h=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));u+=Math.pow(r.x,2)*n,l+=Math.pow(r.y,2)*n,h+=r.x*r.y*n}));var c=u-l,f=Math.sqrt(Math.pow(c,2)+4*Math.pow(h,2)),g=2*h,p=Math.atan((c+f)/g),v=180*p/Math.PI,d=0,y=0,m=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));d+=Math.pow(r.x*Math.cos(p)-r.y*Math.sin(p),2)*n,y+=Math.pow(r.x*Math.sin(p)+r.y*Math.cos(p),2)*n,m+=n}));var _=Math.sqrt(2*d/m),x=Math.sqrt(2*y/m),E=js(a,_,x,{units:"degrees",angle:v,steps:r,properties:o}),k=Su(t,C([E])),b={meanCenterCoordinates:Q(a),semiMajorAxis:_,semiMinorAxis:x,numberOfFeatures:s,angle:v,percentageWithinEllipse:100*yt(k).length/s};return E.properties=null!=(n=E.properties)?n:{},E.properties.standardDeviationalEllipse=b,E},t.tag=function(t,e,n,r){return t=Ai(t),e=Ai(e),vt(t,(function(t){t.properties||(t.properties={}),vt(e,(function(e){t.properties&&e.properties&&void 0===t.properties[r]&&zt(t,e)&&(t.properties[r]=e.properties[n])}))})),t},t.tesselate=function(t){if(!t.geometry||"Polygon"!==t.geometry.type&&"MultiPolygon"!==t.geometry.type)throw new Error("input must be a Polygon or MultiPolygon");var e={type:"FeatureCollection",features:[]};return"Polygon"===t.geometry.type?e.features=Nl(t.geometry.coordinates):t.geometry.coordinates.forEach((function(t){e.features=e.features.concat(Nl(t))})),e},t.tin=oo,t.toMercator=Vu,t.toWgs84=Gu,t.transformRotate=zs,t.transformScale=al,t.transformTranslate=function(t,e,n,r){if(!Z(r=r||{}))throw new Error("options is invalid");var i=r.units,o=r.zTranslation,s=r.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("distance is required");if(o&&"number"!=typeof o&&isNaN(o))throw new Error("zTranslation is not a number");if(o=void 0!==o?o:0,0===e&&0===o)return t;if(null==n||isNaN(n))throw new Error("direction is required");return e<0&&(e=-e,n+=180),!1!==s&&void 0!==s||(t=Ai(t)),ct(t,(function(t){var r=Q(Bs(t,e,n,{units:i}));t[0]=r[0],t[1]=r[1],o&&3===t.length&&(t[2]+=o)})),t},t.triangleGrid=aa,t.truncate=Qa,t.union=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must have at least 2 geometries");var r=Os.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)},t.unkinkPolygon=function(t){var e=[];return xt(t,(function(t){"Polygon"===t.geometry.type&&vt(Ll(t),(function(n){e.push(S(n.geometry.coordinates,t.properties))}))})),C(e)},t.validateBBox=H,t.validateId=W,t.voronoi=function(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox||[-180,-85,180,85];if(!t)throw new Error("points is required");if(!Array.isArray(n))throw new Error("bbox is invalid");return nt(t,"Point","points"),C(function(){var t=Fl,e=ql,n=null;function r(r){return new mh(r.map((function(n,i){var o=[Math.round(t(n,i,r)/vh)*vh,Math.round(e(n,i,r)/vh)*vh];return o.index=i,o.data=n,o})),n)}return r.polygons=function(t){return r(t).polygons()},r.links=function(t){return r(t).links()},r.triangles=function(t){return r(t).triangles()},r.x=function(e){return arguments.length?(t="function"==typeof e?e:Dl(+e),r):t},r.y=function(t){return arguments.length?(e="function"==typeof t?t:Dl(+t),r):e},r.extent=function(t){return arguments.length?(n=null==t?null:[[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]],r):n&&[[n[0][0],n[0][1]],[n[1][0],n[1][1]]]},r.size=function(t){return arguments.length?(n=null==t?null:[[0,0],[+t[0],+t[1]]],r):n&&[n[1][0]-n[0][0],n[1][1]-n[0][1]]},r}().x((function(t){return t.geometry.coordinates[0]})).y((function(t){return t.geometry.coordinates[1]})).extent([[n[0],n[1]],[n[2],n[3]]]).polygons(t.features).map((function(e,n){return Object.assign(function(t){return(t=t.slice()).push(t[0]),S([t])}(e),{properties:Fi(t.features[n].properties)})})))}})); diff --git a/docs/articles/turf_files/turf-operations-1.0.0/mapboxgl.js b/docs/articles/turf_files/turf-operations-1.0.0/mapboxgl.js new file mode 100644 index 0000000..c0d6d59 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/mapboxgl.js @@ -0,0 +1,3910 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "mapboxgl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + + // Register PMTiles source type if available + if ( + typeof MapboxPmTilesSource !== "undefined" && + typeof pmtiles !== "undefined" + ) { + try { + mapboxgl.Style.setSourceType( + PMTILES_SOURCE_TYPE, + MapboxPmTilesSource, + ); + console.log("PMTiles support enabled for Mapbox GL JS"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + mapboxgl.accessToken = x.access_token; + + map = new mapboxgl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + projection: x.projection, + parallels: x.parallels, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } else { + // Handle custom source types (like pmtile-source) + const sourceOptions = { type: source.type }; + + // Copy all properties except id + for (const [key, value] of Object.entries(source)) { + if (key !== "id") { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + // Set rain effect if provided + if (x.rain) { + map.setRain(x.rain); + } + + // Set snow effect if provided + if (x.snow) { + map.setSnow(x.snow); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + geocoder.on("result", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + } + + if (x.draw_control && x.draw_control.enabled) { + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + console.log("Geolocate event triggered"); + console.log("Element ID:", el.id); + console.log("Event coords:", event.coords); + + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + map.setProjection(projectionConfig.projection); + } + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId, (err, zoom) => { + if (err) return; + + map.easeTo({ + center: features[0].geometry.coordinates, + zoom: zoom, + }); + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("mapboxgl-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if (window._mapboxPopups && window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + "style[data-mapgl-legend-css]", + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] && + window._mapboxHandlers[layerId].click + ) { + map.off( + "click", + layerId, + window._mapboxHandlers[layerId].click, + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Store handler reference + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + if (!window._mapboxHandlers[layerId]) { + window._mapboxHandlers[layerId] = {}; + } + window._mapboxHandlers[layerId].click = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push(drawControl); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach(layerId => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + // Remove all legend elements + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clean up any legend styles associated with this map + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => { + style.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "mapboxgl-ctrl mapboxgl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map.loadImage(imageInfo.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image, imageInfo.options); + } + }); + }); + } else if (message.url) { + map.loadImage(message.url, function (error, image) { + if (error) { + console.error("Error loading image:", error); + return; + } + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image, message.options); + } + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_rain") { + if (message.remove) { + map.setRain(null); + } else if (message.rain) { + map.setRain(message.rain); + } + } else if (message.type === "set_snow") { + if (message.remove) { + map.setSnow(null); + } else if (message.snow) { + map.setSnow(message.snow); + } + } else if (message.type === "set_projection") { + const projection = message.projection; + map.setProjection(projection); + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } + } + }); +} diff --git a/docs/articles/turf_files/turf-operations-1.0.0/mapboxgl.yaml b/docs/articles/turf_files/turf-operations-1.0.0/mapboxgl.yaml new file mode 100644 index 0000000..6a5c2f7 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/mapboxgl.yaml @@ -0,0 +1,65 @@ +dependencies: + - name: mapbox-gl-js + version: "3.15.0" + src: + href: "https://api.mapbox.com/mapbox-gl-js/v3.15.0/" + script: + - "mapbox-gl.js" + stylesheet: + - "mapbox-gl.css" + - name: mapbox-gl-draw + version: "1.5.0" + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.5.0/" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: mapbox-gl-geocoder + version: 5.0.0 + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/" + script: + - "mapbox-gl-geocoder.min.js" + stylesheet: + - "mapbox-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: mapbox-pmtiles + version: 1.1.0 + src: "htmlwidgets/lib/mapbox-pmtiles" + script: + - "pmtiles-source-optimized-v2.js" + - name: turf + version: "7.2.0" + src: "htmlwidgets/lib/turf" + script: + - "turf.min.js" + - name: turf-operations + version: "1.0.0" + src: "htmlwidgets" + script: + - "turf-operations.js" diff --git a/docs/articles/turf_files/turf-operations-1.0.0/mapboxgl_compare.js b/docs/articles/turf_files/turf-operations-1.0.0/mapboxgl_compare.js new file mode 100644 index 0000000..780fbd6 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/mapboxgl_compare.js @@ -0,0 +1,3192 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +HTMLWidgets.widget({ + name: "mapboxgl_compare", + + type: "output", + + factory: function (el, width, height) { + // Store maps and compare object to allow access during Shiny updates + let beforeMap, afterMap, compareControl, draw; + + return { + renderValue: function (x) { + if (typeof mapboxgl === "undefined") { + console.error("Mapbox GL JS is not loaded."); + return; + } + if (typeof mapboxgl.Compare === "undefined") { + console.error("Mapbox GL Compare plugin is not loaded."); + return; + } + + // Register PMTiles source type if available + if (typeof MapboxPmTilesSource !== "undefined" && typeof pmtiles !== "undefined") { + try { + mapboxgl.Style.setSourceType(PMTILES_SOURCE_TYPE, MapboxPmTilesSource); + console.log("PMTiles support enabled for Mapbox GL JS Compare"); + } catch (e) { + console.warn("Failed to register PMTiles source type:", e); + } + } + + // Create container divs for the maps + const beforeContainerId = `${el.id}-before`; + const afterContainerId = `${el.id}-after`; + + // Different HTML structure based on mode + if (x.mode === "sync") { + // Side-by-side sync mode + const containerStyle = + x.orientation === "horizontal" + ? `display: flex; flex-direction: column; width: 100%; height: 100%;` + : `display: flex; flex-direction: row; width: 100%; height: 100%;`; + + const mapStyle = + x.orientation === "horizontal" + ? `width: 100%; height: 50%; position: relative;` + : `width: 50%; height: 100%; position: relative;`; + + el.innerHTML = ` +
+
+
+
+ `; + } else { + // Default swipe mode + el.innerHTML = ` +
+
+ `; + } + + beforeMap = new mapboxgl.Map({ + container: beforeContainerId, + style: x.map1.style, + center: x.map1.center, + zoom: x.map1.zoom, + bearing: x.map1.bearing, + pitch: x.map1.pitch, + projection: x.map1.projection, + accessToken: x.map1.access_token, + ...x.map1.additional_params, + }); + + afterMap = new mapboxgl.Map({ + container: afterContainerId, + style: x.map2.style, + center: x.map2.center, + zoom: x.map2.zoom, + bearing: x.map2.bearing, + pitch: x.map2.pitch, + projection: x.map2.projection, + accessToken: x.map2.access_token, + ...x.map2.additional_params, + }); + + // Set the global access token + mapboxgl.accessToken = x.map1.access_token; + + if (x.mode === "swipe") { + // Only create the swiper in swipe mode + compareControl = new mapboxgl.Compare( + beforeMap, + afterMap, + `#${el.id}`, + { + mousemove: x.mousemove, + orientation: x.orientation, + }, + ); + + // Apply custom swiper color if provided + if (x.swiper_color) { + const swiperSelector = + x.orientation === "vertical" + ? ".mapboxgl-compare .compare-swiper-vertical" + : ".mapboxgl-compare .compare-swiper-horizontal"; + + const styleEl = document.createElement("style"); + styleEl.innerHTML = `${swiperSelector} { background-color: ${x.swiper_color}; }`; + document.head.appendChild(styleEl); + } + } else { + // For sync mode, we directly leverage the sync-move module's approach + + // Function to synchronize maps as seen in the mapbox-gl-sync-move module + const syncMaps = () => { + // Array of maps to sync + const maps = [beforeMap, afterMap]; + // Array of move event handlers + const moveHandlers = []; + + // Setup the sync between maps + maps.forEach((map, index) => { + // Create a handler for each map that syncs all other maps + moveHandlers[index] = (e) => { + // Disable all move events temporarily + maps.forEach((m, i) => { + m.off("move", moveHandlers[i]); + }); + + // Get the state from the map that triggered the event + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Apply this state to all other maps + maps + .filter((m, i) => i !== index) + .forEach((m) => { + m.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + }); + + // Re-enable move events + maps.forEach((m, i) => { + m.on("move", moveHandlers[i]); + }); + }; + + // Add the move handler to each map + map.on("move", moveHandlers[index]); + }); + }; + + // Initialize the sync + syncMaps(); + } + + // Ensure both maps resize correctly + beforeMap.on("load", function () { + beforeMap.resize(); + applyMapModifications(beforeMap, x.map1); + + // Setup Shiny event handlers for the before map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(beforeMap, el.id, "before"); + } + }); + + afterMap.on("load", function () { + afterMap.resize(); + applyMapModifications(afterMap, x.map2); + + // Setup Shiny event handlers for the after map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(afterMap, el.id, "after"); + } + + // Add compare-level legends after both maps are loaded + if (x.compare_legends && Array.isArray(x.compare_legends)) { + x.compare_legends.forEach(function(legendInfo) { + // Add CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendInfo.css; + legendCss.setAttribute("data-mapgl-legend-css", el.id); + document.head.appendChild(legendCss); + + // Create legend element + const legend = document.createElement("div"); + legend.innerHTML = legendInfo.html; + legend.classList.add("mapboxgl-legend"); + + // Append to the appropriate container based on target + if (legendInfo.target === "compare") { + // Append to the main compare container + el.appendChild(legend); + } else if (legendInfo.target === "before") { + // Append to the before map container + beforeMap.getContainer().appendChild(legend); + } else if (legendInfo.target === "after") { + // Append to the after map container + afterMap.getContainer().appendChild(legend); + } + }); + } + }); + + // Handle Shiny messages + if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler( + "mapboxgl-compare-proxy", + function (data) { + if (data.id !== el.id) return; + + // Get the message and determine which map to target + var message = data.message; + var map = message.map === "before" ? beforeMap : afterMap; + + if (!map) return; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Process the message based on type + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "promoteId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "data" && + key !== "generateId" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tiles" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster-dem") { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "tileSize" && + key !== "maxzoom" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "url" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function (key) { + if ( + key !== "id" && + key !== "type" && + key !== "urls" && + key !== "coordinates" + ) { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types (like pmtile-source) + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function (key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup( + e, + map, + message.layer.popup, + message.layer.id, + ); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = + clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + message.layer.tooltip, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = e.features[0].id; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: true, + }); + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { + hover: false, + }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error( + "Failed to add layer via proxy: ", + message.layer, + e, + ); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + if ( + window._mapboxPopups && + window._mapboxPopups[message.layer_id] + ) { + window._mapboxPopups[message.layer_id].remove(); + delete window._mapboxPopups[message.layer_id]; + } + + if (map.getLayer(message.layer_id)) { + // Remove tooltip handlers + if ( + window._mapboxHandlers && + window._mapboxHandlers[message.layer_id] + ) { + const handlers = window._mapboxHandlers[message.layer_id]; + if (handlers.mousemove) { + map.off( + "mousemove", + message.layer_id, + handlers.mousemove, + ); + } + if (handlers.mouseleave) { + map.off( + "mouseleave", + message.layer_id, + handlers.mouseleave, + ); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer_id]; + } + + // Remove click handlers for popups + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer_id] + ) { + map.off( + "click", + message.layer_id, + window._mapboxClickHandlers[message.layer_id], + ); + delete window._mapboxClickHandlers[message.layer_id]; + } + + // Remove the layer + map.removeLayer(message.layer_id); + } + if (map.getSource(message.layer_id)) { + map.removeSource(message.layer_id); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer_id]; + delete layerState.paintProperties[message.layer_id]; + delete layerState.layoutProperties[message.layer_id]; + delete layerState.tooltips[message.layer_id]; + delete layerState.popups[message.layer_id]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty( + message.layer, + message.name, + message.value, + ); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "add_legend") { + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + + // Append legend to the correct map container + const targetContainer = map.getContainer(); + targetContainer.appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Save the current view state + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Apply the new style + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + // Identify user-added sources (those not in the original style) + // We'll assume any source that's not "composite", "mapbox", or starts with "mapbox-" is user-added + for (const sourceId in currentStyle.sources) { + if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") + ) { + userSourceIds.push(sourceId); + const source = currentStyle.sources[sourceId]; + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find( + (l) => l.id === layerId, + ); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + } + + // Identify layers using user-added sources + currentStyle.layers.forEach(function (layer) { + if (userSourceIds.includes(layer.source)) { + userLayers.push(layer); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + + // Remove existing tooltip handlers first + map.off("mousemove", layerId); + map.off("mouseleave", layerId); + + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on("mousemove", layerId, function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }); + + map.on("mouseleave", layerId, function () { + onMouseLeaveTooltip(map, tooltip); + }); + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + delete window._mapboxClickHandlers[layerId]; + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + } + + // Change the style + map.setStyle(message.style, { + config: message.config, + diff: message.diff, + }); + + // Restore the view state after the style has loaded + map.once("style.load", function () { + map.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + + // Re-apply map modifications + if (map === beforeMap) { + applyMapModifications(map, x.map1); + } else { + applyMapModifications(map, x.map2); + } + }); + } else if (message.type === "add_navigation_control") { + const nav = new mapboxgl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".mapboxgl-ctrl.mapboxgl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "navigation", control: nav }); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + customControlContainer.innerHTML = controlOptions.html; + customControlContainer.className = "mapboxgl-ctrl"; + if (controlOptions.className) { + customControlContainer.className += " " + controlOptions.className; + } + + // Create the custom control object + const customControl = { + onAdd: function(map) { + return customControlContainer; + }, + onRemove: function() { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild(customControlContainer); + } + } + }; + + map.addControl(customControl, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + + // Store control with proper type + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = + "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + const resetControlObj = { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }; + + map.addControl(resetControlObj, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "reset", control: resetControlObj }); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(draw, message.source, map); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + if (map._mapgl_draw) { + const features = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + if (draw) { + if (map._mapgl_draw) map._mapgl_draw.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + if (draw) { + if (message.data.clear_existing) { + if (map._mapgl_draw) map._mapgl_draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.mapboxglMarkers) { + window.mapboxglMarkers.forEach(function (marker) { + marker.remove(); + }); + window.mapboxglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new mapboxgl.FullscreenControl(); + map.addControl(fullscreen, position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "fullscreen", control: fullscreen }); + } else if (message.type === "add_scale_control") { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "scale", control: scaleControl }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(data.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(data.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(data.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(data.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "geolocate", control: geolocate }); + } else if (message.type === "add_geocoder_control") { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl(geocoder, message.position || "top-right"); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "geocoder", control: geocoder }); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + + // Handle use_icon parameter + let className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + + if (message.use_icon) { + className += " icon-only"; + } + + layersControl.className = className; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `.layers-control { background-color: ${colors.background} !important; }`; + } + if (colors.text) { + css += `.layers-control a { color: ${colors.text} !important; }`; + } + if (colors.activeBackground) { + css += `.layers-control a.active { background-color: ${colors.activeBackground} !important; }`; + } + if (colors.activeText) { + css += `.layers-control a.active { color: ${colors.activeText} !important; }`; + } + if (colors.hoverBackground) { + css += `.layers-control a:hover { background-color: ${colors.hoverBackground} !important; }`; + } + if (colors.hoverText) { + css += `.layers-control a:hover { color: ${colors.hoverText} !important; }`; + } + if (colors.toggleButtonBackground) { + css += `.layers-control .toggle-button { background-color: ${colors.toggleButtonBackground} + !important; }`; + } + if (colors.toggleButtonText) { + css += `.layers-control .toggle-button { color: ${colors.toggleButtonText} !important; }`; + } + + styleEl.innerHTML = css; + document.head.appendChild(styleEl); + } + + document.getElementById(data.id).appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + message.layers || + map.getStyle().layers.map((layer) => layer.id); + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + toggleButton.textContent = "Layers"; + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "layers", control: layersControl }); + } else if (message.type === "add_globe_minimap") { + // Add the globe minimap control + const minimap = new MapboxGlobeMinimap({ + center: map.getCenter(), + zoom: map.getZoom(), + bearing: map.getBearing(), + pitch: map.getPitch(), + globeSize: message.globe_size, + landColor: message.land_color, + waterColor: message.water_color, + markerColor: message.marker_color, + markerSize: message.marker_size, + }); + + map.addControl(minimap, message.position); + + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + map.controls.push({ type: "globe_minimap", control: minimap }); + } else if (message.type === "set_rain") { + if (message.rain) { + map.setRain(message.rain); + } else { + map.setRain(null); + } + } else if (message.type === "set_snow") { + if (message.snow) { + map.setSnow(message.snow); + } else { + map.setSnow(null); + } + } else if (message.type === "set_projection") { + map.setProjection(message.projection); + } else if (message.type === "set_source") { + if (map.getLayer(message.layer)) { + const sourceId = map.getLayer(message.layer).source; + map.getSource(sourceId).setData(JSON.parse(message.source)); + } + } else if (message.type === "set_tooltip") { + // Track tooltip state + layerState.tooltips[message.layer] = message.tooltip; + + if (map.getLayer(message.layer)) { + // Remove any existing tooltip handlers + map.off("mousemove", message.layer); + map.off("mouseleave", message.layer); + + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on("mousemove", message.layer, function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[message.tooltip]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }); + + map.on("mouseleave", message.layer, function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }); + } + } else if (message.type === "set_popup") { + // Track popup state + layerState.popups[message.layer] = message.popup; + + if (map.getLayer(message.layer)) { + // Remove any existing popup click handlers for this layer + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[message.layer] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Remove any existing popup for this layer + if ( + window._mapboxPopups && + window._mapboxPopups[message.layer] + ) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Create new click handler for popup + const clickHandler = function (e) { + onClickPopup(e, map, message.popup, message.layer); + }; + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer] = clickHandler; + + // Add click handler + map.on("click", message.layer, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer, function () { + map.getCanvas().style.cursor = ""; + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } + } else if (message.type === "set_opacity") { + // Set opacity for all fill layers + const style = map.getStyle(); + if (style && style.layers) { + style.layers.forEach(function (layer) { + if (layer.type === "fill" && map.getLayer(layer.id)) { + map.setPaintProperty( + layer.id, + "fill-opacity", + message.opacity, + ); + } + }); + } + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection) + ); + } else if (message.type === "clear_controls") { + // Handle clear_controls for compare widgets + if (!message.controls || message.controls.length === 0) { + // Clear all controls + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + } + } + }, + ); + } + + function setupShinyEvents(map, parentId, mapType) { + // Set view state on move end + map.on("moveend", function () { + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_view", { + center: [center.lng, center.lat], + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + } + }); + + // Send clicked point coordinates to Shiny + map.on("click", function (e) { + // Check if this map's draw control is active and in a drawing mode + let isDrawing = false; + if (map._mapgl_draw && map._mapgl_draw.getMode) { + const mode = map._mapgl_draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + // Filter out draw layers + const nonDrawFeatures = features.filter(feature => + !feature.layer.id.includes('gl-draw') && + !feature.source.includes('gl-draw') + ); + + if (nonDrawFeatures.length > 0) { + const feature = nonDrawFeatures[0]; + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }); + } + } else { + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_feature_click", null); + } + } + } + + // Always send regular click event + if (window.Shiny) { + Shiny.setInputValue(parentId + "_" + mapType + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }); + } + }); + + // Add hover events if enabled for this map + const mapConfig = (mapType === "before") ? x.map1 : x.map2; + if (mapConfig.hover_events && mapConfig.hover_events.enabled) { + map.on("mousemove", function (e) { + if (window.Shiny) { + // Feature hover events + if (mapConfig.hover_events.features) { + const options = mapConfig.hover_events.layer_id + ? { layers: Array.isArray(mapConfig.hover_events.layer_id) + ? mapConfig.hover_events.layer_id + : mapConfig.hover_events.layer_id.split(',').map(id => id.trim()) } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if(features.length > 0) { + const feature = features[0]; + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } else { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + null + ); + } + } + + // Coordinate hover events + if (mapConfig.hover_events.coordinates) { + Shiny.setInputValue( + parentId + "_" + mapType + "_hover", + { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } + } + }); + } + } + + function applyMapModifications(map, mapData) { + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + // Note: tooltip handlers are already defined at the top of the file + + // Set config properties if provided + if (mapData.config_properties) { + mapData.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + // Process H3J sources if provided + if (mapData.h3j_sources) { + mapData.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + }); + } + + if (mapData.markers) { + if (!window.mapboxglMarkers) { + window.mapboxglMarkers = []; + } + mapData.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new mapboxgl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new mapboxgl.Popup({ offset: 25 }).setText(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + } + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + } + }); + } + + window.mapboxglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (mapData.sources) { + mapData.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceConfig = { + type: "vector", + url: source.url, + }; + if (source.promoteId) { + sourceConfig.promoteId = source.promoteId; + } + map.addSource(source.id, sourceConfig); + } else if (source.type === "geojson") { + const geojsonData = source.data; + map.addSource(source.id, { + type: "geojson", + data: geojsonData, + generateId: true, + }); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + // Add layers if provided + if (mapData.layers) { + mapData.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + map.on("click", layer.id, function (e) { + const description = e.features[0].properties[layer.popup]; + + new mapboxgl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + }); + } + + if (layer.tooltip) { + const tooltip = new mapboxgl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = e.features[0].id; + map.setFeatureState( + { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: true }, + ); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + }); + } + + // Set terrain if provided + if (mapData.terrain) { + map.setTerrain({ + source: mapData.terrain.source, + exaggeration: mapData.terrain.exaggeration, + }); + } + + // Set fog + if (mapData.fog) { + map.setFog(mapData.fog); + } + + // Set rain effect if provided + if (mapData.rain) { + map.setRain(mapData.rain); + } + + // Set snow effect if provided + if (mapData.snow) { + map.setSnow(mapData.snow); + } + + if (mapData.fitBounds) { + map.fitBounds(mapData.fitBounds.bounds, mapData.fitBounds.options); + } + if (mapData.flyTo) { + map.flyTo(mapData.flyTo); + } + if (mapData.easeTo) { + map.easeTo(mapData.easeTo); + } + if (mapData.setCenter) { + map.setCenter(mapData.setCenter); + } + if (mapData.setZoom) { + map.setZoom(mapData.setZoom); + } + + // Apply moveLayer operations if provided + if (mapData.moveLayer) { + mapData.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + if (mapData.jumpTo) { + map.jumpTo(mapData.jumpTo); + } + + // Add custom images if provided + if (mapData.images && Array.isArray(mapData.images)) { + mapData.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (mapData.images) { + console.error("mapData.images is not an array:", mapData.images); + } + + // Remove existing legends only from this specific map container + const mapContainer = map.getContainer(); + const existingLegends = mapContainer.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + + // Don't remove all legend styles globally - they might belong to other maps + // Only remove styles when the entire widget is being recreated + + if (mapData.legend_html && mapData.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = mapData.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", el.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = mapData.legend_html; + legend.classList.add("mapboxgl-legend"); + + // Append legend to the correct map container instead of main container + const mapContainer = map.getContainer(); + mapContainer.appendChild(legend); + } + + // Add fullscreen control if enabled + if ( + mapData.fullscreen_control && + mapData.fullscreen_control.enabled + ) { + const position = mapData.fullscreen_control.position || "top-right"; + map.addControl(new mapboxgl.FullscreenControl(), position); + } + + // Add navigation control if enabled + if (mapData.navigation_control) { + const nav = new mapboxgl.NavigationControl({ + showCompass: mapData.navigation_control.show_compass, + showZoom: mapData.navigation_control.show_zoom, + visualizePitch: mapData.navigation_control.visualize_pitch, + }); + map.addControl(nav, mapData.navigation_control.position); + } + + // Add scale control if enabled + if (mapData.scale_control) { + const scaleControl = new mapboxgl.ScaleControl({ + maxWidth: mapData.scale_control.maxWidth, + unit: mapData.scale_control.unit, + }); + map.addControl(scaleControl, mapData.scale_control.position); + map.controls.push(scaleControl); + } + + // Add geolocate control if enabled + if (mapData.geolocate_control) { + const geolocate = new mapboxgl.GeolocateControl({ + positionOptions: mapData.geolocate_control.positionOptions, + trackUserLocation: mapData.geolocate_control.trackUserLocation, + showAccuracyCircle: mapData.geolocate_control.showAccuracyCircle, + showUserLocation: mapData.geolocate_control.showUserLocation, + showUserHeading: mapData.geolocate_control.showUserHeading, + fitBoundsOptions: mapData.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, mapData.geolocate_control.position); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Helper function to generate draw styles based on parameters + function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "midpoint"], + ], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: [ + "all", + ["==", "meta", "vertex"], + ["==", "$type", "Point"], + ], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: [ + "all", + ["==", "meta", "vertex"], + ["==", "$type", "Point"], + ], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } + } + + // Add geocoder control if enabled + if (mapData.geocoder_control) { + const geocoderOptions = { + accessToken: mapboxgl.accessToken, + mapboxgl: mapboxgl, + ...mapData.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + const geocoder = new MapboxGeocoder(geocoderOptions); + + map.addControl( + geocoder, + mapData.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Handle geocoder results in Shiny mode + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e.result, + time: new Date(), + }); + }); + } + + // Add draw control if enabled + if (mapData.draw_control) { + if (mapData.draw_control && mapData.draw_control.enabled) { + let drawOptions = mapData.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (mapData.draw_control.styling) { + const generatedStyles = generateDrawStyles( + mapData.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (mapData.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + mapData.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (mapData.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (mapData.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, mapData.draw_control.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add custom mode buttons and styling + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".mapboxgl-ctrl-group"); + + // Add rectangle styling and button + if (mapData.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + drawControl.changeMode('draw_rectangle'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + } + + // Add radius styling and button + if (mapData.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + drawControl.changeMode('draw_radius'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + } + }, 100); + + // Add initial features if provided + if (mapData.draw_control.source) { + addSourceFeaturesToDraw(drawControl, mapData.draw_control.source, map); + } + + // Process any queued features + if (mapData.draw_features_queue) { + mapData.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + if (map._mapgl_draw) map._mapgl_draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Apply orientation styling + if (mapData.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".mapboxgl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (mapData.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.mapboxgl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${mapData.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + // Helper function for updating drawn features + function updateDrawnFeatures() { + if (HTMLWidgets.shinyMode && map._mapgl_draw) { + const features = map._mapgl_draw ? map._mapgl_draw.getAll() : null; + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(features), + ); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + } + + // Add reset control if enabled + if (mapData.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = "mapboxgl-ctrl-icon mapboxgl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "mapboxgl-ctrl mapboxgl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: mapData.reset_control.animate, + }; + + if (mapData.reset_control.duration) { + initialView.duration = mapData.reset_control.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + mapData.reset_control.position, + ); + } + + // Add the layers control if provided + if (mapData.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = mapData.layers_control.control_id; + + // Handle use_icon parameter + let className = mapData.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + + layersControl.className = className; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = mapData.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + mapData.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = mapData.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (mapData.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + if (mapData.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + } + }, + + resize: function (width, height) { + // Code to handle resizing if necessary + }, + }; + }, +}); diff --git a/docs/articles/turf_files/turf-operations-1.0.0/mapboxgl_compare.yaml b/docs/articles/turf_files/turf-operations-1.0.0/mapboxgl_compare.yaml new file mode 100644 index 0000000..55f1563 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/mapboxgl_compare.yaml @@ -0,0 +1,57 @@ +dependencies: + - name: mapbox-gl-js + version: "3.15.0" + src: + href: "https://api.mapbox.com/mapbox-gl-js/" + script: + - "v3.15.0/mapbox-gl.js" + - "plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.js" + stylesheet: + - "v3.15.0/mapbox-gl.css" + - "plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.css" + - name: mapbox-gl-draw + version: "1.4.3" + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.3/" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: mapbox-gl-geocoder + version: 5.0.0 + src: + href: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/" + script: + - "mapbox-gl-geocoder.min.js" + stylesheet: + - "mapbox-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: mapbox-pmtiles + version: 1.1.0 + src: "htmlwidgets/lib/mapbox-pmtiles" + script: + - "pmtiles-source-optimized-v2.js" diff --git a/docs/articles/turf_files/turf-operations-1.0.0/maplibregl.js b/docs/articles/turf_files/turf-operations-1.0.0/maplibregl.js new file mode 100644 index 0000000..5937d02 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/maplibregl.js @@ -0,0 +1,5048 @@ +// Measurement functionality +function createMeasurementBox(map) { + const box = document.createElement('div'); + box.id = `measurement-box-${map._container.id}`; + box.className = 'mapgl-measurement-box'; + box.style.cssText = ` + position: absolute; + bottom: 45px; + left: 10px; + background: white; + padding: 10px 15px; + border-radius: 4px; + box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.4; + z-index: 1; + display: none; + min-width: 120px; + max-width: 200px; + border: 1px solid rgba(0,0,0,0.1); + `; + + box.innerHTML = ` +
+ Measurement +
+
+
+
+
+ `; + + map.getContainer().appendChild(box); + return box; +} + +function calculateDrawingMeasurements(mode, state, coords) { + try { + if (mode === 'draw_line_string' && coords && coords.length >= 2) { + const line = turf.lineString(coords); + const distance = turf.length(line, {units: 'kilometers'}); + return { type: 'distance', value: distance }; + } + + else if ((mode === 'draw_polygon' || mode === 'draw_freehand') && coords && coords.length >= 3) { + // Ensure polygon is closed by adding first point at end if needed + const closedCoords = [...coords]; + if (closedCoords[0][0] !== closedCoords[closedCoords.length - 1][0] || + closedCoords[0][1] !== closedCoords[closedCoords.length - 1][1]) { + closedCoords.push(closedCoords[0]); + } + + try { + const polygon = turf.polygon([closedCoords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } catch (error) { + return null; + } + } + + else if (mode === 'draw_rectangle' && coords && coords.length >= 4) { + const polygon = turf.polygon([coords]); + const area = turf.area(polygon) / 1000000; // Convert to km² + const perimeter = turf.length(turf.polygonToLine(polygon), {units: 'kilometers'}); + return { type: 'area', value: area, perimeter: perimeter }; + } + + else if (mode === 'draw_radius' && coords && coords.length >= 2) { + const center = turf.point(coords[0]); + const edge = turf.point(coords[1]); + const radius = turf.distance(center, edge, {units: 'kilometers'}); + const area = Math.PI * radius * radius; // πr² + return { type: 'radius', value: radius, area: area }; + } + } catch (e) { + return null; + } + + return null; +} + +function formatMeasurements(measurements, units) { + if (!measurements) return { primary: '', secondary: '' }; + + const formatDistance = function(km) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (km < 1) { + result.push(`${(km * 1000).toFixed(0)} m`); + } else { + result.push(`${km.toFixed(2)} km`); + } + } + + if (units === 'imperial' || units === 'both') { + const miles = km * 0.621371; + if (miles < 0.1) { + result.push(`${(miles * 5280).toFixed(0)} ft`); + } else { + result.push(`${miles.toFixed(2)} mi`); + } + } + + return result; + }; + + const formatArea = function(sqKm) { + let result = []; + + if (units === 'metric' || units === 'both') { + if (sqKm < 0.01) { + result.push(`${(sqKm * 1000000).toFixed(0)} m²`); + } else if (sqKm < 1) { + result.push(`${(sqKm * 100).toFixed(2)} ha`); + } else { + result.push(`${sqKm.toFixed(2)} km²`); + } + } + + if (units === 'imperial' || units === 'both') { + const sqMiles = sqKm * 0.386102; + if (sqMiles < 0.001) { + result.push(`${(sqMiles * 640).toFixed(2)} acres`); + } else { + result.push(`${sqMiles.toFixed(3)} mi²`); + } + } + + return result; + }; + + if (measurements.type === 'distance') { + const formatted = formatDistance(measurements.value); + return { + primary: formatted[0] || '', + secondary: formatted[1] || '' + }; + } + + else if (measurements.type === 'area') { + const areaFormatted = formatArea(measurements.value); + const perimeterFormatted = formatDistance(measurements.perimeter); + + if (units === 'both') { + return { + primary: areaFormatted[0] || '', + secondary: `${areaFormatted[1] || ''} • ${perimeterFormatted[0] || ''}` + }; + } else { + return { + primary: areaFormatted[0] || '', + secondary: `Perimeter: ${perimeterFormatted[0] || ''}` + }; + } + } + + else if (measurements.type === 'radius') { + const distFormatted = formatDistance(measurements.value); + const areaFormatted = formatArea(measurements.area); + + return { + primary: `Radius: ${distFormatted[0] || ''}`, + secondary: units === 'both' ? + `${distFormatted[1] || ''} • ${areaFormatted[0] || ''}` : + `Area: ${areaFormatted[0] || ''}` + }; + } + + return { primary: '', secondary: '' }; +} + +function updateMeasurementDisplay(box, measurements, units) { + const primary = box.querySelector('#measurement-primary'); + const secondary = box.querySelector('#measurement-secondary'); + + const formatted = formatMeasurements(measurements, units); + + if (formatted.primary) { + primary.textContent = formatted.primary; + secondary.textContent = formatted.secondary; + box.style.display = 'block'; + } else { + box.style.display = 'none'; + } +} + +function initializeMeasurements(map, draw, units) { + const measurementBox = createMeasurementBox(map); + const DRAWING_MODES = ['draw_line_string', 'draw_polygon', 'draw_rectangle', 'draw_radius', 'draw_freehand']; + + // Store original handlers + const originalHandlers = {}; + + DRAWING_MODES.forEach(mode => { + const modeObj = MapboxDraw.modes[mode]; + if (!modeObj) return; + + + // Wrap onClick for polygon mode (better for click-based drawing) + if (modeObj.onClick && mode === 'draw_polygon') { + originalHandlers[mode + '_onClick'] = modeObj.onClick; + modeObj.onClick = function(state, e) { + const result = originalHandlers[mode + '_onClick'].call(this, state, e); + + // For polygon mode, show measurements after each click + if (state.polygon && state.polygon.coordinates && state.polygon.coordinates[0].length >= 3) { + const coords = state.polygon.coordinates[0]; + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + + return result; + }; + } + + // Wrap onMouseMove for real-time updates (lines, rectangles, radius) + if (modeObj.onMouseMove && mode !== 'draw_polygon') { + originalHandlers[mode + '_onMouseMove'] = modeObj.onMouseMove; + modeObj.onMouseMove = function(state, e) { + originalHandlers[mode + '_onMouseMove'].call(this, state, e); + + let coords = null; + if (state.line && state.line.coordinates) { + coords = [...state.line.coordinates, [e.lngLat.lng, e.lngLat.lat]]; + } else if (state.rectangle && state.rectangle.coordinates) { + coords = state.rectangle.coordinates[0]; + } + + if (coords) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + }; + } + + // Wrap onDrag for freehand mode + if (modeObj.onDrag) { + originalHandlers[mode + '_onDrag'] = modeObj.onDrag; + modeObj.onDrag = function(state, e) { + const result = originalHandlers[mode + '_onDrag'].call(this, state, e); + + if (state.polygon && state.polygon.coordinates) { + const coords = state.polygon.coordinates[0]; + if (coords.length >= 3) { + const measurements = calculateDrawingMeasurements(mode, state, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + return result; + }; + } + }); + + // Hide measurement box when drawing stops and handle button states + map.on('draw.modechange', (e) => { + if (e.mode === 'simple_select') { + measurementBox.style.display = 'none'; + // Reset button states when switching to select mode + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + } + }); + + map.on('draw.create', () => { + measurementBox.style.display = 'none'; + // Reset button states when drawing is completed + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + if (drawControlGroup) { + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + } + }); + + map.on('draw.delete', () => { + measurementBox.style.display = 'none'; + }); + + // Special handling for freehand mode using data update events + map.on('draw.update', (e) => { + const currentMode = draw.getMode(); + + if (currentMode === 'draw_freehand' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_freehand', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + + // Also handle editing mode - when features are being edited + if (currentMode === 'direct_select' && e.features && e.features[0]) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } + }); + + // Show measurements when selecting features for editing + map.on('draw.selectionchange', (e) => { + if (e.features && e.features.length > 0) { + const feature = e.features[0]; + if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates[0].length >= 3) { + const coords = feature.geometry.coordinates[0]; + const measurements = calculateDrawingMeasurements('draw_polygon', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } else if (feature.geometry.type === 'LineString' && feature.geometry.coordinates.length >= 2) { + const coords = feature.geometry.coordinates; + const measurements = calculateDrawingMeasurements('draw_line_string', {}, coords); + updateMeasurementDisplay(measurementBox, measurements, units); + } + } else { + // No features selected, hide measurement box + measurementBox.style.display = 'none'; + } + }); +} + +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case "get": + return properties[expression[1]]; + case "concat": + return expression + .slice(1) + .map((item) => evaluateExpression(item, properties)) + .join(""); + case "to-string": + return String(evaluateExpression(expression[1], properties)); + case "to-number": + return Number(evaluateExpression(expression[1], properties)); + case "number-format": + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || "en-US"; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty("min-fraction-digits")) { + formatOptions.minimumFractionDigits = options["min-fraction-digits"]; + } + if (options.hasOwnProperty("max-fraction-digits")) { + formatOptions.maximumFractionDigits = options["max-fraction-digits"]; + } + if (options.hasOwnProperty("min-integer-digits")) { + formatOptions.minimumIntegerDigits = options["min-integer-digits"]; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) + formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty("useGrouping")) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression( + tooltipProperty, + e.features[0].properties, + ); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + window._mapboxPopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on("close", function () { + if (window._mapboxPopups[layerId] === popup) { + delete window._mapboxPopups[layerId]; + } + }); +} + +// Helper function to generate draw styles based on parameters +function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + id: "gl-draw-point-active", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "true"], + ], + paint: { + "circle-radius": styling.vertex_radius + 2, + "circle-color": styling.active_color, + }, + }, + { + id: "gl-draw-point", + type: "circle", + filter: [ + "all", + ["==", "$type", "Point"], + ["==", "meta", "feature"], + ["==", "active", "false"], + ], + paint: { + "circle-radius": styling.vertex_radius, + "circle-color": styling.point_color, + }, + }, + // Line styles + { + id: "gl-draw-line", + type: "line", + filter: ["all", ["==", "$type", "LineString"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Polygon fill + { + id: "gl-draw-polygon-fill", + type: "fill", + filter: ["all", ["==", "$type", "Polygon"]], + paint: { + "fill-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-outline-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.fill_color, + ], + "fill-opacity": styling.fill_opacity, + }, + }, + // Polygon outline + { + id: "gl-draw-polygon-stroke", + type: "line", + filter: ["all", ["==", "$type", "Polygon"]], + layout: { + "line-cap": "round", + "line-join": "round", + }, + paint: { + "line-color": [ + "case", + ["==", ["get", "active"], "true"], + styling.active_color, + styling.line_color, + ], + "line-width": styling.line_width, + }, + }, + // Midpoints + { + id: "gl-draw-polygon-midpoint", + type: "circle", + filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]], + paint: { + "circle-radius": 3, + "circle-color": styling.active_color, + }, + }, + // Vertex point halos + { + id: "gl-draw-vertex-halo-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 4, + styling.vertex_radius + 2, + ], + "circle-color": "#FFF", + }, + }, + // Vertex points + { + id: "gl-draw-vertex-active", + type: "circle", + filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"]], + paint: { + "circle-radius": [ + "case", + ["==", ["get", "active"], "true"], + styling.vertex_radius + 2, + styling.vertex_radius, + ], + "circle-color": styling.active_color, + }, + }, + ]; +} + +// Helper function to add features from a source to draw +function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn("Source not found or has no data:", sourceId); + } +} + +HTMLWidgets.widget({ + name: "maplibregl", + + type: "output", + + factory: function (el, width, height) { + let map; + let draw; + + return { + renderValue: function (x) { + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + + map = new maplibregl.Map({ + container: el.id, + style: x.style, + center: x.center, + zoom: x.zoom, + bearing: x.bearing, + pitch: x.pitch, + ...x.additional_params, + }); + + map.controls = []; + + map.on("style.load", function () { + map.resize(); + + if (HTMLWidgets.shinyMode) { + map.on("load", function () { + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.setInputValue(el.id + "_zoom", zoom); + Shiny.setInputValue(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.setInputValue(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + + map.on("moveend", function (e) { + var map = e.target; + var bounds = map.getBounds(); + var center = map.getCenter(); + var zoom = map.getZoom(); + + Shiny.onInputChange(el.id + "_zoom", zoom); + Shiny.onInputChange(el.id + "_center", { + lng: center.lng, + lat: center.lat, + }); + Shiny.onInputChange(el.id + "_bbox", { + xmin: bounds.getWest(), + ymin: bounds.getSouth(), + xmax: bounds.getEast(), + ymax: bounds.getNorth(), + }); + }); + } + + // Set config properties if provided + if (x.config_properties) { + x.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + if (x.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + x.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + if (HTMLWidgets.shinyMode) { + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(el.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (x.sources) { + x.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceOptions = { + type: "vector", + url: source.url, + }; + // Add promoteId if provided + if (source.promoteId) { + sourceOptions.promoteId = source.promoteId; + } + // Add any other additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "url"].includes(key)) { + sourceOptions[key] = value; + } + } + map.addSource(source.id, sourceOptions); + } else if (source.type === "geojson") { + const geojsonData = source.data; + const sourceOptions = { + type: "geojson", + data: geojsonData, + generateId: source.generateId, + }; + + // Add additional options + for (const [key, value] of Object.entries(source)) { + if (!["id", "type", "data", "generateId"].includes(key)) { + sourceOptions[key] = value; + } + } + + map.addSource(source.id, sourceOptions); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + function add_my_layers(layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.filter) { + layerConfig["filter"] = layer.filter; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layer.id] = clickHandler; + + // Add the click handler + map.on("click", layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function. + // We need to pass 'e', 'map', 'tooltip', and 'layer.tooltip' to onMouseMoveTooltip. + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, layer.tooltip); + }; + + // Create a reference to the mouseleave handler function. + // We need to pass 'map' and 'tooltip' to onMouseLeaveTooltip. + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references, not anonymous functions. + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handler references so you can remove them later if needed + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof layer.source === "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }; + if (layer.source_layer) { + featureState.sourceLayer = layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(layer.id, key) || layer.paint[key]; + map.setPaintProperty(layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer: ", layer, e); + } + } + if (x.h3j_sources) { + x.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + + // A bit hacky? + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + }); + } + + // Add layers if provided + if (x.layers) { + x.layers.forEach((layer) => add_my_layers(layer)); + } + + // Apply setFilter if provided + if (x.setFilter) { + x.setFilter.forEach(function (filter) { + map.setFilter(filter.layer, filter.filter); + }); + } + + // Apply moveLayer operations if provided + if (x.moveLayer) { + x.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + + // Set terrain if provided + if (x.terrain) { + map.setTerrain({ + source: x.terrain.source, + exaggeration: x.terrain.exaggeration, + }); + } + + // Set fog + if (x.fog) { + map.setFog(x.fog); + } + + if (x.fitBounds) { + map.fitBounds(x.fitBounds.bounds, x.fitBounds.options); + } + if (x.flyTo) { + map.flyTo(x.flyTo); + } + if (x.easeTo) { + map.easeTo(x.easeTo); + } + if (x.setCenter) { + map.setCenter(x.setCenter); + } + if (x.setZoom) { + map.setZoom(x.setZoom); + } + if (x.jumpTo) { + map.jumpTo(x.jumpTo); + } + + // Add scale control if enabled + if (x.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: x.scale_control.maxWidth, + unit: x.scale_control.unit, + }); + map.addControl(scaleControl, x.scale_control.position); + map.controls.push(scaleControl); + } + + // Add globe control if enabled + if (x.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, x.globe_control.position); + map.controls.push(globeControl); + } + + // Add custom controls if any are defined + if (x.custom_controls) { + Object.keys(x.custom_controls).forEach(function (key) { + const controlOptions = x.custom_controls[key]; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl( + customControl, + controlOptions.position || "top-right", + ); + map.controls.push(customControl); + }); + } + + // Add globe minimap if enabled + if (x.globe_minimap && x.globe_minimap.enabled) { + const globeMinimapOptions = { + globeSize: x.globe_minimap.globe_size, + landColor: x.globe_minimap.land_color, + waterColor: x.globe_minimap.water_color, + markerColor: x.globe_minimap.marker_color, + markerSize: x.globe_minimap.marker_size, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, x.globe_minimap.position); + map.controls.push(globeMinimap); + } + + if (x.setProjection) { + x.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + map.setProjection(projection); + } + }); + } + + // Add geocoder control if enabled + if (x.geocoder_control) { + const provider = x.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: x.geocoder_control.api_key, + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...x.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder(geocoderApi, geocoderOptions); + } + + map.addControl( + geocoder, + x.geocoder_control.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + if (x.draw_control && x.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = + "maplibregl-ctrl-group"; + + let drawOptions = x.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (x.draw_control.styling) { + const generatedStyles = generateDrawStyles( + x.draw_control.styling, + ); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (x.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + x.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (x.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (x.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: "#fbb03b", + point_color: "#3bb2d0", + line_color: "#3bb2d0", + fill_color: "#3bb2d0", + fill_opacity: 0.1, + line_width: 2, + }); + } + + draw = new MapboxDraw(drawOptions); + map.addControl(draw, x.draw_control.position); + map.controls.push(draw); + + // Add lasso icon CSS for freehand mode + if (x.draw_control.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add rectangle icon CSS if rectangle mode is enabled + if (x.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add radius/circle icon CSS if radius mode is enabled + if (x.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add measurement functionality if enabled + if (x.draw_control.show_measurements) { + initializeMeasurements(map, draw, x.draw_control.measurement_units); + } + + // Add initial features if provided + if (x.draw_control.source) { + addSourceFeaturesToDraw(draw, x.draw_control.source, map); + } + + // Process any queued features + if (x.draw_features_queue) { + x.draw_features_queue.forEach(function (data) { + if (data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, data.source, map); + }); + } + + // Add custom mode buttons + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + + if (x.draw_control.rectangle && drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + draw.changeMode('draw_rectangle'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + + if (x.draw_control.radius && drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + draw.changeMode('draw_radius'); + // Update active state + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + }, 100); + + // Apply orientation styling + if (x.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (x.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${x.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } + + function updateDrawnFeatures() { + if (draw) { + var drawnFeatures = draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + if (!x.add) { + const existingLegends = el.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + } + + if (x.legend_html && x.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = x.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = x.legend_html; + legend.classList.add("mapboxgl-legend"); + el.appendChild(legend); + } + + // Add fullscreen control if enabled + if (x.fullscreen_control && x.fullscreen_control.enabled) { + const position = x.fullscreen_control.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } + + // Add geolocate control if enabled + if (x.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: x.geolocate_control.positionOptions, + trackUserLocation: x.geolocate_control.trackUserLocation, + showAccuracyCircle: x.geolocate_control.showAccuracyCircle, + showUserLocation: x.geolocate_control.showUserLocation, + showUserHeading: x.geolocate_control.showUserHeading, + fitBoundsOptions: x.geolocate_control.fitBoundsOptions, + }); + map.addControl(geolocate, x.geolocate_control.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } + + // Add navigation control if enabled + if (x.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: x.navigation_control.show_compass, + showZoom: x.navigation_control.show_zoom, + visualizePitch: x.navigation_control.visualize_pitch, + }); + map.addControl(nav, x.navigation_control.position); + map.controls.push(nav); + + if (x.navigation_control.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } + + // Add reset control if enabled + if (x.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + // Initialize with empty object, will be populated after map loads + let initialView = {}; + + // Capture the initial view after the map has loaded and all view operations are complete + map.once("load", function () { + initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: x.reset_control.animate, + }; + + if (x.reset_control.duration) { + initialView.duration = x.reset_control.duration; + } + }); + + resetControl.onclick = function () { + // Only reset if we have captured the initial view + if (initialView.center) { + map.easeTo(initialView); + } + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + x.reset_control.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } + + if (x.images && Array.isArray(x.images)) { + x.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage(imageInfo.url); + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (x.images) { + console.error("x.images is not an array:", x.images); + } + + // Add the layers control if provided + if (x.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = x.layers_control.control_id; + layersControl.className = x.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = x.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = + (x.layers_control.margin_top || 10) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 10) + "px"; + layersControl.style.left = + (x.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = + (x.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = + (x.layers_control.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (x.layers_control.custom_colors) { + const colors = x.layers_control.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${x.layers_control.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${x.layers_control.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${x.layers_control.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${x.layers_control.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${x.layers_control.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${x.layers_control.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + x.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = x.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse( + this.getAttribute("data-layer-ids"), + ); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (x.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (x.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + } + + // If clusters are present, add event handling + map.getStyle().layers.forEach((layer) => { + if (layer.id.includes("-clusters")) { + map.on("click", layer.id, async (e) => { + const features = map.queryRenderedFeatures(e.point, { + layers: [layer.id], + }); + const clusterId = features[0].properties.cluster_id; + const zoom = await map + .getSource(layer.source) + .getClusterExpansionZoom(clusterId); + map.easeTo({ + center: features[0].geometry.coordinates, + zoom, + }); + }); + + map.on("mouseenter", layer.id, () => { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layer.id, () => { + map.getCanvas().style.cursor = ""; + }); + } + }); + + // Add click event listener in shinyMode + if (HTMLWidgets.shinyMode) { + map.on("click", function (e) { + // Check if draw control is active and in a drawing mode + let isDrawing = false; + if (typeof draw !== 'undefined' && draw) { + const mode = draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_click", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_click", null); + } + } + + // Event listener for the map (always fire this) + Shiny.onInputChange(el.id + "_click", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + }); + + // add hover listener for shinyMode if enabled + if (x.hover_events && x.hover_events.enabled) { + map.on("mousemove", function (e) { + // Feature hover events + if (x.hover_events.features) { + const options = x.hover_events.layer_id + ? { + layers: Array.isArray(x.hover_events.layer_id) + ? x.hover_events.layer_id + : x.hover_events.layer_id + .split(",") + .map((id) => id.trim()), + } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if (features.length > 0) { + const feature = features[0]; + Shiny.onInputChange(el.id + "_feature_hover", { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } else { + Shiny.onInputChange(el.id + "_feature_hover", null); + } + } + + // Coordinate hover events + if (x.hover_events.coordinates) { + Shiny.onInputChange(el.id + "_hover", { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + }); + } + }); + } + } + + // Process turf operations for static maps + if (x.turf_operations) { + processTurfOperationsOnLoad(map, x.turf_operations, el.id); + } + + el.map = map; + }); + el.map = map; + }, + + getMap: function () { + return map; // Return the map instance + }, + + getDraw: function () { + return draw; // Return the draw instance + }, + + getDrawnFeatures: function () { + return ( + this.drawFeatures || { + type: "FeatureCollection", + features: [], + } + ); + }, + + resize: function (width, height) { + if (map) { + map.resize(); + } + }, + }; + }, +}); + +if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler("maplibre-proxy", function (data) { + var widget = HTMLWidgets.find("#" + data.id); + if (!widget) return; + var map = widget.getMap(); + if (map) { + var message = data.message; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {}, // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Helper function to update drawn features + function updateDrawnFeatures() { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + var drawnFeatures = drawControl.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + map.addSource(message.source); + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer(message.layer, message.layer.before_id); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Initialize popup tracking if it doesn't exist + if (!window._mapboxPopups) { + window._mapboxPopups = {}; + } + + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on("click", message.layer.id, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer.id, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, message.layer.tooltip); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on("mousemove", message.layer.id, mouseMoveHandler); + map.on("mouseleave", message.layer.id, mouseLeaveHandler); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[message.layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", message.layer.id, function (e) { + if (e.features.length > 0) { + // Check if the feature has an id + const featureId = e.features[0].id; + + // Only proceed if the feature has an id + if (featureId !== undefined && featureId !== null) { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = featureId; + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: true }); + } + } + }); + + map.on("mouseleave", message.layer.id, function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer.source === "string" + ? message.layer.source + : message.layer.id, + id: hoveredFeatureId, + }; + if (message.layer.source_layer) { + featureState.sourceLayer = message.layer.source_layer; + } + map.setFeatureState(featureState, { hover: false }); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach(function (key) { + const originalPaint = + map.getPaintProperty(message.layer.id, key) || + message.layer.paint[key]; + map.setPaintProperty(message.layer.id, key, [ + "case", + ["boolean", ["feature-state", "hover"], false], + jsHoverOptions[key], + originalPaint, + ]); + }); + } + } catch (e) { + console.error("Failed to add layer via proxy: ", message.layer, e); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer key + if (window._mapboxPopups[message.layer]) { + window._mapboxPopups[message.layer].remove(); + delete window._mapboxPopups[message.layer]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if ( + message.layer && + message.layer.id && + window._mapboxPopups[message.layer.id] + ) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer)) { + // Remove tooltip handlers + if (window._mapboxHandlers && window._mapboxHandlers[message.layer]) { + const handlers = window._mapboxHandlers[message.layer]; + if (handlers.mousemove) { + map.off("mousemove", message.layer, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", message.layer, handlers.mouseleave); + } + // Clean up the reference + delete window._mapboxHandlers[message.layer]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer key + if (window._mapboxClickHandlers[message.layer]) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer], + ); + delete window._mapboxClickHandlers[message.layer]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if ( + message.layer && + message.layer.id && + window._mapboxClickHandlers[message.layer.id] + ) { + map.off( + "click", + message.layer, + window._mapboxClickHandlers[message.layer.id], + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer); + } + if (map.getSource(message.layer)) { + map.removeSource(message.layer); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer]; + delete layerState.paintProperties[message.layer]; + delete layerState.layoutProperties[message.layer]; + delete layerState.tooltips[message.layer]; + delete layerState.popups[message.layer]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty(message.layer, message.name, message.value); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = + message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find((layer) => layer.id === layerId); + const currentPaintProperty = map.getPaintProperty( + layerId, + propertyName, + ); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + newValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + // No hover options, just set the new value directly + map.setPaintProperty(layerId, propertyName, newValue); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection), + ); + } else if (message.type === "add_legend") { + // Extract legend ID from HTML to track it + const legendIdMatch = message.html.match(/id="([^"]+)"/); + const legendId = legendIdMatch ? legendIdMatch[1] : null; + + if (!message.add) { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${data.id}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Clear legend state when replacing all legends + layerState.legends = {}; + } + + // Track legend state + if (legendId) { + layerState.legends[legendId] = { + html: message.html, + css: message.legend_css, + }; + } + + const legendCss = document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute("data-mapgl-legend-css", data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("mapboxgl-legend"); + document.getElementById(data.id).appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + console.log( + "[MapGL Debug] set_style called with preserve_layers:", + preserveLayers, + ); + console.log( + "[MapGL Debug] message.preserve_layers:", + message.preserve_layers, + ); + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log( + "[MapGL Debug] Current style sources:", + Object.keys(currentStyle.sources), + ); + console.log( + "[MapGL Debug] Current style layers:", + currentStyle.layers.map((l) => l.id), + ); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function (layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log( + "[MapGL Debug] Found source from test layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + // If the paint property has a hover case, it's user-added + (layer.paint && + Object.values(layer.paint).some( + (value) => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover", + )) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if (!isBaseMapSource) { + console.log( + "[MapGL Debug] Found user source from layer:", + layer.source, + ); + userSourceIds.push(layer.source); + } else { + console.log( + "[MapGL Debug] Not adding base map source from layer:", + layer.source, + ); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + console.log( + "[MapGL Debug] Examining source:", + sourceId, + "type:", + source.type, + ); + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if ( + source.url && + typeof source.url === "string" && + (source.url.includes("data:application/json") || + source.url.includes("blob:")) + ) { + console.log( + "[MapGL Debug] Found user source with data URL:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !( + sourceId.startsWith("maptiler") && !sourceId.includes("user") + ) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) && // Filter basemap sources but keep user ones + sourceId !== "satellite" && // Filter MapTiler satellite source specifically + sourceId !== "aerial" // Filter aerial imagery sources + ) { + console.log( + "[MapGL Debug] Found user source via filtering:", + sourceId, + ); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } else { + console.log( + "[MapGL Debug] Filtered out base map source:", + sourceId, + ); + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find((l) => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function (layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = + layerSource && + layerSource.type === "vector" && + (layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler")); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log( + "[MapGL Debug] Including user layer:", + layer.id, + "source:", + layer.source, + ); + } else if (isBaseMapSource) { + console.log( + "[MapGL Debug] Excluding base map layer:", + layer.id, + "source:", + layer.source, + ); + } + }); + + // Log detected user sources and layers + console.log("[MapGL Debug] Detected user sources:", userSourceIds); + console.log( + "[MapGL Debug] Detected user layers:", + userLayers.map((l) => l.id), + ); + console.log( + "[MapGL Debug] Will preserve", + userLayers.length, + "user layers", + ); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map((id) => ({ + id, + source: currentStyle.sources[id], + })), + layers: userLayers, + }; + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function () { + console.log("[MapGL Debug] style.load event fired"); + + try { + // Re-add user sources + userSourceIds.forEach(function (sourceId) { + try { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + console.log("[MapGL Debug] Re-adding source:", sourceId); + map.addSource(sourceId, source); + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding source:", + sourceId, + err, + ); + } + }); + + // Re-add user layers + userLayers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Re-adding layer:", layer.id); + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log( + "[MapGL Debug] Re-adding mousemove handler for:", + layer.id, + ); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log( + "[MapGL Debug] Re-adding mouseleave handler for:", + layer.id, + ); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log( + "[MapGL Debug] Restoring tooltip for:", + layerId, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error re-adding layer:", + layer.id, + err, + ); + } + }); + } catch (err) { + console.error("[MapGL Debug] Error in style.load handler:", err); + } + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Restoring filter for layer:", + layerId, + ); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log( + "[MapGL Debug] Restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Restoring tooltip:", + layerId, + tooltipProperty, + ); + + // Remove existing tooltip handlers first + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + // Create new tooltip + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Restoring popup:", + layerId, + popupProperty, + ); + + // Remove existing popup handlers first + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + // Create new popup handler + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + // Add hover effects for cursor + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log("[MapGL Debug] Restoring legend:", legendId); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute("data-mapgl-legend-css", mapId); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off("style.load", onStyleLoad); + }; + + map.on("style.load", onStyleLoad); + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function () { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Backup restoration needed for layers", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } else { + console.log( + "[MapGL Debug] Backup check: layers already restored properly", + ); + } + } + } catch (err) { + console.error( + "[MapGL Debug] Error in backup restoration:", + err, + ); + } + }, 500); // 500ms delay - faster recovery + + // Add a second backup with a bit more delay in case the first one fails + setTimeout(function () { + try { + console.log("[MapGL Debug] Running second backup layer check"); + const mapId = map.getContainer().id; + const preserved = + window._mapglPreservedData && + window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log( + "[MapGL Debug] Second backup restoration needed", + ); + + // Re-add sources first + preserved.sources.forEach(function (src) { + try { + if (!map.getSource(src.id)) { + console.log( + "[MapGL Debug] Second backup: adding source", + src.id, + ); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding source", + src.id, + err, + ); + } + }); + + // Then re-add layers + preserved.layers.forEach(function (layer) { + try { + if (!map.getLayer(layer.id)) { + console.log( + "[MapGL Debug] Second backup: adding layer", + layer.id, + ); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log( + "[MapGL Debug] Second backup: restoring tooltip for", + layer.id, + ); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function (e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[tooltipProperty]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }; + + const mouseLeaveHandler = function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if ( + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][0] === "boolean" && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover" + ) { + // This is a hover-enabled paint property + console.log( + "[MapGL Debug] Second backup: restoring hover style for", + layer.id, + key, + ); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error( + "[MapGL Debug] Second backup: error adding layer", + layer.id, + err, + ); + } + }); + + // Restore tracked layer modifications in second backup + const mapId = map.getContainer().id; + const savedLayerState = + window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log( + "[MapGL Debug] Second backup: restoring tracked layer modifications", + ); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log( + "[MapGL Debug] Second backup: restoring filter for layer:", + layerId, + ); + map.setFilter( + layerId, + savedLayerState.filters[layerId], + ); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + console.log( + "[MapGL Debug] Second backup: restoring paint property:", + layerId, + propertyName, + savedValue, + ); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty( + layerId, + propertyName, + ); + if ( + currentValue && + Array.isArray(currentValue) && + currentValue[0] === "case" + ) { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + map.setPaintProperty( + layerId, + propertyName, + savedValue, + ); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = + savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log( + "[MapGL Debug] Second backup: restoring layout property:", + layerId, + propertyName, + properties[propertyName], + ); + map.setLayoutProperty( + layerId, + propertyName, + properties[propertyName], + ); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = + savedLayerState.tooltips[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring tooltip:", + layerId, + tooltipProperty, + ); + + if ( + window._mapboxHandlers && + window._mapboxHandlers[layerId] + ) { + if (window._mapboxHandlers[layerId].mousemove) { + map.off( + "mousemove", + layerId, + window._mapboxHandlers[layerId].mousemove, + ); + } + if (window._mapboxHandlers[layerId].mouseleave) { + map.off( + "mouseleave", + layerId, + window._mapboxHandlers[layerId].mouseleave, + ); + } + } + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + tooltipProperty, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log( + "[MapGL Debug] Second backup: restoring popup:", + layerId, + popupProperty, + ); + + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off( + "click", + layerId, + window._mapboxClickHandlers[layerId], + ); + } + + const clickHandler = function (e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } + } + + // Restore legends + if (Object.keys(savedLayerState.legends).length > 0) { + // Clear any existing legends first to prevent stacking + const existingLegends = document.querySelectorAll( + `#${mapId} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => legend.remove()); + + // Clear existing legend styles + const legendStyles = document.querySelectorAll( + `style[data-mapgl-legend-css="${mapId}"]`, + ); + legendStyles.forEach((style) => style.remove()); + + // Restore each legend + for (const legendId in savedLayerState.legends) { + const legendData = savedLayerState.legends[legendId]; + console.log( + "[MapGL Debug] Second backup: restoring legend:", + legendId, + ); + + // Add legend CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendData.css; + legendCss.setAttribute( + "data-mapgl-legend-css", + mapId, + ); + document.head.appendChild(legendCss); + + // Add legend HTML + const legend = document.createElement("div"); + legend.innerHTML = legendData.html; + legend.classList.add("mapboxgl-legend"); + const mapContainer = document.getElementById(mapId); + if (mapContainer) { + mapContainer.appendChild(legend); + } + } + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Error in second backup:", err); + } + }, 1000); // 1 second delay for second backup + } + } + + // Change the style + console.log( + "[MapGL Debug] About to call setStyle with:", + message.style, + ); + console.log("[MapGL Debug] setStyle diff option:", message.diff); + map.setStyle(message.style, { diff: message.diff }); + + if (message.config) { + Object.keys(message.config).forEach(function (key) { + map.setConfigProperty("basemap", key, message.config[key]); + }); + } + } else if (message.type === "add_navigation_control") { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + map.controls.push({ type: "navigation", control: nav }); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:not(.mapbox-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: MapboxDraw.modes.draw_freehand, + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Create the draw control + var drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store the draw control on the widget for later access + widget.drawControl = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map + .getContainer() + .querySelector(".mapbox-gl-draw_polygon"); + if (polygonButton) { + polygonButton.title = "Freehand polygon tool (p)"; + } + }, 100); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(drawControl, message.source, map); + } + + // Apply orientation styling + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector("#mapgl-draw-download-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-draw-download-styles"; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)", + ); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement("button"); + downloadBtn.className = "mapbox-gl-draw_download"; + downloadBtn.title = "Download drawn features as GeoJSON"; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener("click", () => { + // Get all drawn features + const data = drawControl.getAll(); + + if (data.features.length === 0) { + alert( + "No features to download. Please draw something first!", + ); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: "application/json" }); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.download = `${message.download_filename || "drawn-features"}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + const features = drawControl.getAll(); + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if (message.type === "clear_drawn_features") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + drawControl.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type.startsWith("turf_")) { + // Delegate to shared turf operations module + handleTurfOperation(map, message, data.id); + } else if (message.type === "add_features_to_draw") { + var drawControl = widget.drawControl || widget.getDraw(); + if (drawControl) { + if (message.data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn("Draw control not initialized"); + } + } else if (message.type === "add_markers") { + if (!window.maplibreMarkers) { + window.maplibreMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker(markerOptions) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ offset: 25 }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue(data.id + "_marker_" + markerId, { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }); + }); + } + + window.maplibreMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreMarkers) { + window.maplibreMarkers.forEach(function (marker) { + marker.remove(); + }); + window.maplibreglMarkers = []; + } + } else if (message.type === "add_fullscreen_control") { + const position = message.position || "top-right"; + const fullscreen = new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl(scaleControl, message.options.position); + map.controls.push(scaleControl); + } else if (message.type === "add_reset_control") { + const resetControl = document.createElement("button"); + resetControl.className = "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }, + message.position, + ); + + map.controls.push({ + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild(resetContainer); + }, + }); + } else if (message.type === "add_geolocate_control") { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: message.options.positionOptions, + trackUserLocation: message.options.trackUserLocation, + showAccuracyCircle: message.options.showAccuracyCircle, + showUserLocation: message.options.showUserLocation, + showUserHeading: message.options.showUserHeading, + fitBoundsOptions: message.options.fitBoundsOptions, + }); + map.addControl(geolocate, message.options.position); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue(el.id + "_geolocate_error", { + message: "Location permission denied", + time: new Date(), + }); + } + }); + } + } else if (message.type === "add_geocoder_control") { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl( + maptilerOptions, + ); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + (feature.bbox[2] - feature.bbox[0]) / 2, + feature.bbox[1] + (feature.bbox[3] - feature.bbox[1]) / 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: feature.properties.display_name, + properties: feature.properties, + text: feature.properties.display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error(`Failed to forwardGeocode with error: ${e}`); + } + + return { + features, + }; + }, + }; + geocoder = new MaplibreGeocoder(geocoderApi, { + maplibregl: maplibregl, + placeholder: message.options.placeholder, + collapsed: message.options.collapsed, + }); + } + + map.addControl(geocoder, message.options.position); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector( + ".maplibregl-ctrl-geocoder", + ); + if (controlContainer) { + controlContainer.style.maxWidth = "300px"; + controlContainer.style.width = "auto"; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("result", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } else if (message.type === "add_layers_control") { + const layersControl = document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `#${message.control_id} { background-color: ${colors.background}; }\n`; + } + + if (colors.text) { + css += `#${message.control_id} a { color: ${colors.text}; }\n`; + } + + if (colors.active) { + css += `#${message.control_id} a.active { background-color: ${colors.active}; }\n`; + css += `#${message.control_id} .toggle-button { background-color: ${colors.active}; }\n`; + } + + if (colors.activeText) { + css += `#${message.control_id} a.active { color: ${colors.activeText}; }\n`; + css += `#${message.control_id} .toggle-button { color: ${colors.activeText}; }\n`; + } + + if (colors.hover) { + css += `#${message.control_id} a:hover { background-color: ${colors.hover}; }\n`; + css += `#${message.control_id} .toggle-button:hover { background-color: ${colors.hover}; }\n`; + } + + styleEl.textContent = css; + document.head.appendChild(styleEl); + } + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + let layers = message.layers || []; + let layersConfig = message.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) + ? config.ids + : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + layerIds.forEach((layerId) => { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + } + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "none"); + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + }); + this.className = ""; + } else { + layerIds.forEach((layerId) => { + map.setLayoutProperty(layerId, "visibility", "visible"); + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + // Ensure layers is always an array + if (!Array.isArray(layers)) { + layers = [layers]; + } + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + + // Check if the layer visibility is set to "none" initially + const initialVisibility = map.getLayoutProperty( + layerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Also hide any associated legends if the layer is initially hidden + if (initialVisibility === "none") { + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${layerId}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } + + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + if (visibility === "visible") { + map.setLayoutProperty(clickedLayer, "visibility", "none"); + this.className = ""; + + // Hide associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = "none"; + }); + } else { + this.className = "active"; + map.setLayoutProperty(clickedLayer, "visibility", "visible"); + + // Show associated legends + const associatedLegends = document.querySelectorAll( + `.mapboxgl-legend[data-layer-id="${clickedLayer}"]`, + ); + associatedLegends.forEach((legend) => { + legend.style.display = ""; + }); + } + }; + + layersList.appendChild(link); + }); + } + + if (message.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + // Use stacked layers icon instead of text if requested + if (message.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore(toggleButton, layersList); + } + + const mapContainer = document.getElementById(data.id); + if (mapContainer) { + mapContainer.appendChild(layersControl); + } else { + console.error(`Cannot find map container with ID ${data.id}`); + } + } else if (message.type === "clear_legend") { + if (message.ids && Array.isArray(message.ids)) { + message.ids.forEach((id) => { + const legend = document.querySelector( + `#${data.id} div[id="${id}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[id]; + }); + } else if (message.ids) { + const legend = document.querySelector( + `#${data.id} div[id="${message.ids}"]`, + ); + if (legend) { + legend.remove(); + } + // Remove from legend state + delete layerState.legends[message.ids]; + } else { + const existingLegends = document.querySelectorAll( + `#${data.id} .mapboxgl-legend`, + ); + existingLegends.forEach((legend) => { + legend.remove(); + }); + + // Clear all legend state + layerState.legends = {}; + } + } else if (message.type === "clear_controls") { + // If no specific controls specified, clear all + if (!message.controls || message.controls.length === 0) { + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + + // Remove globe minimap if it exists + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + + // Handle special controls that aren't in the controls array + controlsToRemove.forEach((controlType) => { + if (controlType === "layers") { + const layersControl = document.querySelector( + `#${data.id} .layers-control`, + ); + if (layersControl) { + layersControl.remove(); + } + } else if (controlType === "globe_minimap") { + const globeMinimap = document.querySelector( + ".mapboxgl-ctrl-globe-minimap", + ); + if (globeMinimap) { + globeMinimap.remove(); + } + } + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer(message.layer, message.before); + } else { + map.moveLayer(message.layer); + } + } else { + console.error("Layer not found:", message.layer); + } + } else if (message.type === "add_image") { + if (Array.isArray(message.images)) { + message.images.forEach(function (imageInfo) { + map + .loadImage(imageInfo.url) + .then((image) => { + if (!map.hasImage(imageInfo.id)) { + map.addImage(imageInfo.id, image.data, imageInfo.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + }); + } else if (message.url) { + map + .loadImage(message.url) + .then((image) => { + if (!map.hasImage(message.imageId)) { + map.addImage(message.imageId, image.data, message.options); + } + }) + .catch((error) => { + console.error("Error loading image:", error); + }); + } else { + console.error("Invalid image data:", message); + } + } else if (message.type === "set_tooltip") { + const layerId = message.layer; + const newTooltipProperty = message.tooltip; + + // Track tooltip state + layerState.tooltips[layerId] = newTooltipProperty; + + // If there's an active tooltip open, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Remove old handlers if any + if (window._mapboxHandlers && window._mapboxHandlers[layerId]) { + const handlers = window._mapboxHandlers[layerId]; + if (handlers.mousemove) { + map.off("mousemove", layerId, handlers.mousemove); + } + if (handlers.mouseleave) { + map.off("mouseleave", layerId, handlers.mouseleave); + } + delete window._mapboxHandlers[layerId]; + } + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define new handlers referencing the updated tooltip property + const mouseMoveHandler = function (e) { + onMouseMoveTooltip(e, map, tooltip, newTooltipProperty); + }; + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Add the new event handlers + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers so we can remove/update them in the future + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } else if (message.type === "set_popup") { + const layerId = message.layer; + const newPopupProperty = message.popup; + + // Track popup state + layerState.popups[layerId] = newPopupProperty; + + // Remove any existing popup for this layer + if (window._mapboxPopups && window._mapboxPopups[layerId]) { + window._mapboxPopups[layerId].remove(); + delete window._mapboxPopups[layerId]; + } + + // Remove old click handler if any + if ( + window._mapboxClickHandlers && + window._mapboxClickHandlers[layerId] + ) { + map.off("click", layerId, window._mapboxClickHandlers[layerId]); + delete window._mapboxClickHandlers[layerId]; + } + + // Remove old hover handlers for cursor change + map.off("mouseenter", layerId); + map.off("mouseleave", layerId); + + // Create new click handler + const clickHandler = function (e) { + onClickPopup(e, map, newPopupProperty, layerId); + }; + + // Add the new event handler + map.on("click", layerId, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layerId, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layerId, function () { + map.getCanvas().style.cursor = ""; + }); + + // Store handler reference + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[layerId] = clickHandler; + } else if (message.type === "set_source") { + const layerId = message.layer; + const newData = message.source; + const layerObject = map.getLayer(layerId); + + if (!layerObject) { + console.error("Layer not found: ", layerId); + return; + } + + const sourceId = layerObject.source; + const sourceObject = map.getSource(sourceId); + + if (!sourceObject) { + console.error("Source not found: ", sourceId); + return; + } + + // Update the geojson data + sourceObject.setData(newData); + } else if (message.type === "set_projection") { + if (map.loaded()) { + const projection = + typeof message.projection === "string" + ? { type: message.projection } + : message.projection; + + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection:", e); + } + } else { + console.error("Map not loaded yet"); + } + } else if (message.type === "add_globe_minimap") { + const globeMinimapOptions = { + globeSize: message.options.globe_size || 100, + landColor: message.options.land_color || "#404040", + waterColor: message.options.water_color || "#090909", + markerColor: message.options.marker_color || "#1da1f2", + markerSize: message.options.marker_size || 2, + }; + const globeMinimap = new GlobeMinimap(globeMinimapOptions); + map.addControl(globeMinimap, message.position || "bottom-left"); + map.controls.push(globeMinimap); + } else if (message.type === "add_globe_control") { + const globeControl = new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } + } + }); +} diff --git a/docs/articles/turf_files/turf-operations-1.0.0/maplibregl.yaml b/docs/articles/turf_files/turf-operations-1.0.0/maplibregl.yaml new file mode 100644 index 0000000..f6679e5 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/maplibregl.yaml @@ -0,0 +1,69 @@ +dependencies: + - name: maplibre-gl + version: "5.7.2" + src: "htmlwidgets/lib/maplibre-gl" + script: + - "maplibre-gl.js" + stylesheet: + - "maplibre-gl.css" + - name: mapbox-gl-draw + version: "1.5.0" + src: "htmlwidgets/lib/mapbox-gl-draw" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: maplibre-gl-geocoder + version: 1.5.0 + src: "htmlwidgets/lib/maplibre-gl-geocoder" + script: + - "maplibre-gl-geocoder.min.js" + stylesheet: + - "maplibre-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: h3j-h3t + version: 0.9.2 + src: "htmlwidgets/lib/h3j-h3t" + script: + - "h3j_h3t.js" + - name: maptiler-geocoding-control + version: 2.1.7 + src: "htmlwidgets/lib/maptiler-geocoding-control" + script: + - "maplibregl.umd.js" + stylesheet: + - "style.css" + - name: turf + version: "7.2.0" + src: "htmlwidgets/lib/turf" + script: + - "turf.min.js" + - name: turf-operations + version: "1.0.0" + src: "htmlwidgets" + script: + - "turf-operations.js" diff --git a/docs/articles/turf_files/turf-operations-1.0.0/maplibregl_compare.js b/docs/articles/turf_files/turf-operations-1.0.0/maplibregl_compare.js new file mode 100644 index 0000000..a0e0caf --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/maplibregl_compare.js @@ -0,0 +1,4138 @@ +function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case 'get': + return properties[expression[1]]; + case 'concat': + return expression.slice(1).map(item => evaluateExpression(item, properties)).join(''); + case 'to-string': + return String(evaluateExpression(expression[1], properties)); + case 'to-number': + return Number(evaluateExpression(expression[1], properties)); + case 'number-format': + const value = evaluateExpression(expression[1], properties); + const options = expression[2] || {}; + + // Handle locale option + const locale = options.locale || 'en-US'; + + // Build Intl.NumberFormat options + const formatOptions = {}; + + // Style options + if (options.style) formatOptions.style = options.style; // 'decimal', 'currency', 'percent', 'unit' + if (options.currency) formatOptions.currency = options.currency; + if (options.unit) formatOptions.unit = options.unit; + + // Digit options + if (options.hasOwnProperty('min-fraction-digits')) { + formatOptions.minimumFractionDigits = options['min-fraction-digits']; + } + if (options.hasOwnProperty('max-fraction-digits')) { + formatOptions.maximumFractionDigits = options['max-fraction-digits']; + } + if (options.hasOwnProperty('min-integer-digits')) { + formatOptions.minimumIntegerDigits = options['min-integer-digits']; + } + + // Notation options + if (options.notation) formatOptions.notation = options.notation; // 'standard', 'scientific', 'engineering', 'compact' + if (options.compactDisplay) formatOptions.compactDisplay = options.compactDisplay; // 'short', 'long' + + // Grouping + if (options.hasOwnProperty('useGrouping')) { + formatOptions.useGrouping = options.useGrouping; + } + + return new Intl.NumberFormat(locale, formatOptions).format(value); + default: + // For literals and other simple values + return expression; + } +} + +function onMouseMoveTooltip(e, map, tooltipPopup, tooltipProperty) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + // Clear any existing active tooltip first to prevent stacking + if (window._activeTooltip && window._activeTooltip !== tooltipPopup) { + window._activeTooltip.remove(); + } + + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(tooltipProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup.setLngLat(e.lngLat).setHTML(description).addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } +} + +function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } +} + +function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._maplibrePopups && window._maplibrePopups[layerId]) { + window._maplibrePopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._maplibrePopups) { + window._maplibrePopups = {}; + } + window._maplibrePopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on('close', function() { + if (window._maplibrePopups[layerId] === popup) { + delete window._maplibrePopups[layerId]; + } + }); +} + +HTMLWidgets.widget({ + name: "maplibregl_compare", + + type: "output", + + factory: function (el, width, height) { + // Store maps and compare object to allow access during Shiny updates + let beforeMap, afterMap, compareControl, draw; + + return { + renderValue: function (x) { + + if (typeof maplibregl === "undefined") { + console.error("Maplibre GL JS is not loaded."); + return; + } + if (typeof maplibregl.Compare === "undefined") { + console.error("Maplibre GL Compare plugin is not loaded."); + return; + } + + // Add PMTiles support + if (typeof pmtiles !== "undefined") { + let protocol = new pmtiles.Protocol({ metadata: true }); + maplibregl.addProtocol("pmtiles", protocol.tile); + } + + // Create container divs for the maps + const beforeContainerId = `${el.id}-before`; + const afterContainerId = `${el.id}-after`; + + // Different HTML structure based on mode + if (x.mode === "sync") { + // Side-by-side sync mode + const containerStyle = + x.orientation === "horizontal" + ? `display: flex; flex-direction: column; width: 100%; height: 100%;` + : `display: flex; flex-direction: row; width: 100%; height: 100%;`; + + const mapStyle = + x.orientation === "horizontal" + ? `width: 100%; height: 50%; position: relative;` + : `width: 50%; height: 100%; position: relative;`; + + el.innerHTML = ` +
+
+
+
+ `; + } else { + // Default swipe mode + el.innerHTML = ` +
+
+ `; + } + + beforeMap = new maplibregl.Map({ + container: beforeContainerId, + style: x.map1.style, + center: x.map1.center, + zoom: x.map1.zoom, + bearing: x.map1.bearing, + pitch: x.map1.pitch, + accessToken: x.map1.access_token, + ...x.map1.additional_params, + }); + + // Initialize controls array + beforeMap.controls = []; + + afterMap = new maplibregl.Map({ + container: afterContainerId, + style: x.map2.style, + center: x.map2.center, + zoom: x.map2.zoom, + bearing: x.map2.bearing, + pitch: x.map2.pitch, + accessToken: x.map2.access_token, + ...x.map2.additional_params, + }); + + // Initialize controls array + afterMap.controls = []; + + if (x.mode === "swipe") { + // Only create the swiper in swipe mode + compareControl = new maplibregl.Compare( + beforeMap, + afterMap, + `#${el.id}`, + { + mousemove: x.mousemove, + orientation: x.orientation, + }, + ); + + // Apply custom swiper color if provided + if (x.swiper_color) { + const swiperSelector = x.orientation === "vertical" ? + ".maplibregl-compare .compare-swiper-vertical" : + ".maplibregl-compare .compare-swiper-horizontal"; + + const styleEl = document.createElement('style'); + styleEl.innerHTML = `${swiperSelector} { background-color: ${x.swiper_color}; }`; + document.head.appendChild(styleEl); + } + } else { + // For sync mode, we directly leverage the sync-move module's approach + + // Function to synchronize maps as seen in the mapbox-gl-sync-move module + const syncMaps = () => { + // Array of maps to sync + const maps = [beforeMap, afterMap]; + // Array of move event handlers + const moveHandlers = []; + + // Setup the sync between maps + maps.forEach((map, index) => { + // Create a handler for each map that syncs all other maps + moveHandlers[index] = (e) => { + // Disable all move events temporarily + maps.forEach((m, i) => { + m.off("move", moveHandlers[i]); + }); + + // Get the state from the map that triggered the event + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Apply this state to all other maps + maps.filter((m, i) => i !== index).forEach( + (m) => { + m.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + }, + ); + + // Re-enable move events + maps.forEach((m, i) => { + m.on("move", moveHandlers[i]); + }); + }; + + // Add the move handler to each map + map.on("move", moveHandlers[index]); + }); + }; + + // Initialize the sync + syncMaps(); + } + + // Ensure both maps resize correctly + beforeMap.on("load", function () { + beforeMap.resize(); + applyMapModifications(beforeMap, x.map1); + + // Setup Shiny event handlers for the before map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(beforeMap, el.id, "before"); + } + }); + + afterMap.on("load", function () { + afterMap.resize(); + applyMapModifications(afterMap, x.map2); + + // Setup Shiny event handlers for the after map + if (HTMLWidgets.shinyMode) { + setupShinyEvents(afterMap, el.id, "after"); + } + + // Add compare-level legends after both maps are loaded + if (x.compare_legends && Array.isArray(x.compare_legends)) { + x.compare_legends.forEach(function(legendInfo) { + // Add CSS + const legendCss = document.createElement("style"); + legendCss.innerHTML = legendInfo.css; + legendCss.setAttribute("data-mapgl-legend-css", el.id); + document.head.appendChild(legendCss); + + // Create legend element + const legend = document.createElement("div"); + legend.innerHTML = legendInfo.html; + legend.classList.add("mapboxgl-legend"); + + // Append to the appropriate container based on target + if (legendInfo.target === "compare") { + // Append to the main compare container + el.appendChild(legend); + } else if (legendInfo.target === "before") { + // Append to the before map container + beforeMap.getContainer().appendChild(legend); + } else if (legendInfo.target === "after") { + // Append to the after map container + afterMap.getContainer().appendChild(legend); + } + }); + } + }); + + // Define updateDrawnFeatures function for the draw tool + window.updateDrawnFeatures = function () { + if (draw) { + const features = draw.getAll(); + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(features), + ); + } + }; + + // Handle Shiny messages + if (HTMLWidgets.shinyMode) { + Shiny.addCustomMessageHandler( + "maplibre-compare-proxy", + function (data) { + if (data.id !== el.id) return; + + // Get the message and determine which map to target + var message = data.message; + var map = + message.map === "before" ? beforeMap : afterMap; + + if (!map) return; + + // Initialize layer state tracking if not already present + if (!window._mapglLayerState) { + window._mapglLayerState = {}; + } + const mapId = map.getContainer().id; + if (!window._mapglLayerState[mapId]) { + window._mapglLayerState[mapId] = { + filters: {}, // layerId -> filter expression + paintProperties: {}, // layerId -> {propertyName -> value} + layoutProperties: {}, // layerId -> {propertyName -> value} + tooltips: {}, // layerId -> tooltip property + popups: {}, // layerId -> popup property + legends: {} // legendId -> {html: string, css: string} + }; + } + const layerState = window._mapglLayerState[mapId]; + + // Process the message based on type + if (message.type === "set_filter") { + map.setFilter(message.layer, message.filter); + // Track filter state for layer restoration + layerState.filters[message.layer] = message.filter; + } else if (message.type === "add_source") { + if (message.source.type === "vector") { + const sourceConfig = { + type: "vector", + url: message.source.url, + }; + // Add promoteId if provided + if (message.source.promoteId) { + sourceConfig.promoteId = message.source.promoteId; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "promoteId") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "geojson") { + const sourceConfig = { + type: "geojson", + data: message.source.data, + generateId: message.source.generateId, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "data" && key !== "generateId") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "raster") { + const sourceConfig = { + type: "raster", + tileSize: message.source.tileSize, + }; + if (message.source.url) { + sourceConfig.url = message.source.url; + } else if (message.source.tiles) { + sourceConfig.tiles = message.source.tiles; + } + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "tiles" && key !== "tileSize" && key !== "maxzoom") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if ( + message.source.type === "raster-dem" + ) { + const sourceConfig = { + type: "raster-dem", + url: message.source.url, + tileSize: message.source.tileSize, + }; + if (message.source.maxzoom) { + sourceConfig.maxzoom = message.source.maxzoom; + } + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "tileSize" && key !== "maxzoom") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "image") { + const sourceConfig = { + type: "image", + url: message.source.url, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "url" && key !== "coordinates") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else if (message.source.type === "video") { + const sourceConfig = { + type: "video", + urls: message.source.urls, + coordinates: message.source.coordinates, + }; + // Add any other properties from the source object + Object.keys(message.source).forEach(function(key) { + if (key !== "id" && key !== "type" && key !== "urls" && key !== "coordinates") { + sourceConfig[key] = message.source[key]; + } + }); + map.addSource(message.source.id, sourceConfig); + } else { + // Handle custom source types + const sourceConfig = { type: message.source.type }; + + // Copy all properties except id + Object.keys(message.source).forEach(function(key) { + if (key !== "id") { + sourceConfig[key] = message.source[key]; + } + }); + + map.addSource(message.source.id, sourceConfig); + } + } else if (message.type === "add_layer") { + try { + if (message.layer.before_id) { + map.addLayer( + message.layer, + message.layer.before_id, + ); + } else { + map.addLayer(message.layer); + } + + // Add popups or tooltips if provided + if (message.layer.popup) { + // Create click handler for this layer + const clickHandler = function (e) { + onClickPopup(e, map, message.layer.popup, message.layer.id); + }; + + // Store these handler references so we can remove them later if needed + if (!window._mapboxClickHandlers) { + window._mapboxClickHandlers = {}; + } + window._mapboxClickHandlers[message.layer.id] = clickHandler; + + // Add the click handler + map.on( + "click", + message.layer.id, + clickHandler + ); + + // Change cursor to pointer when hovering over the layer + map.on( + "mouseenter", + message.layer.id, + function () { + map.getCanvas().style.cursor = + "pointer"; + }, + ); + + // Change cursor back to default when leaving the layer + map.on( + "mouseleave", + message.layer.id, + function () { + map.getCanvas().style.cursor = + ""; + }, + ); + } + + if (message.layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Define named handler functions: + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + message.layer.tooltip, + ); + }; + + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach handlers by reference: + map.on( + "mousemove", + message.layer.id, + mouseMoveHandler, + ); + map.on( + "mouseleave", + message.layer.id, + mouseLeaveHandler, + ); + + // Store these handler references for later removal: + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[ + message.layer.id + ] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (message.layer.hover_options) { + const jsHoverOptions = {}; + for (const [ + key, + value, + ] of Object.entries( + message.layer.hover_options, + )) { + const jsKey = key.replace( + /_/g, + "-", + ); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on( + "mousemove", + message.layer.id, + function (e) { + if (e.features.length > 0) { + if ( + hoveredFeatureId !== + null + ) { + const featureState = { + source: + typeof message + .layer + .source === + "string" + ? message + .layer + .source + : message + .layer + .id, + id: hoveredFeatureId, + }; + if ( + message.layer + .source_layer + ) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState( + featureState, + { + hover: false, + }, + ); + } + hoveredFeatureId = + e.features[0].id; + const featureState = { + source: + typeof message.layer + .source === + "string" + ? message.layer + .source + : message.layer + .id, + id: hoveredFeatureId, + }; + if ( + message.layer + .source_layer + ) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState( + featureState, + { + hover: true, + }, + ); + } + }, + ); + + map.on( + "mouseleave", + message.layer.id, + function () { + if (hoveredFeatureId !== null) { + const featureState = { + source: + typeof message.layer + .source === + "string" + ? message.layer + .source + : message.layer + .id, + id: hoveredFeatureId, + }; + if ( + message.layer + .source_layer + ) { + featureState.sourceLayer = + message.layer.source_layer; + } + map.setFeatureState( + featureState, + { + hover: false, + }, + ); + } + hoveredFeatureId = null; + }, + ); + + Object.keys(jsHoverOptions).forEach( + function (key) { + const originalPaint = + map.getPaintProperty( + message.layer.id, + key, + ) || + message.layer.paint[key]; + map.setPaintProperty( + message.layer.id, + key, + [ + "case", + [ + "boolean", + [ + "feature-state", + "hover", + ], + false, + ], + jsHoverOptions[key], + originalPaint, + ], + ); + }, + ); + } + } catch (e) { + console.error( + "Failed to add layer via proxy: ", + message.layer, + e, + ); + } + } else if (message.type === "remove_layer") { + // If there's an active tooltip, remove it first + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // If there's an active popup for this layer, remove it + // Check both message.layer_id and message.layer.id as keys due to different message formats + if (window._mapboxPopups) { + // First check if we have a popup stored with message.layer_id key + if (window._mapboxPopups[message.layer_id]) { + window._mapboxPopups[message.layer_id].remove(); + delete window._mapboxPopups[message.layer_id]; + } + + // Also check if we have a popup stored with message.layer.id key, which happens when added via add_layer + if (message.layer && message.layer.id && window._mapboxPopups[message.layer.id]) { + window._mapboxPopups[message.layer.id].remove(); + delete window._mapboxPopups[message.layer.id]; + } + } + + if (map.getLayer(message.layer_id)) { + // Remove tooltip handlers + if ( + window._mapboxHandlers && + window._mapboxHandlers[message.layer_id] + ) { + const handlers = + window._mapboxHandlers[ + message.layer_id + ]; + if (handlers.mousemove) { + map.off( + "mousemove", + message.layer_id, + handlers.mousemove, + ); + } + if (handlers.mouseleave) { + map.off( + "mouseleave", + message.layer_id, + handlers.mouseleave, + ); + } + // Clean up the reference + delete window._mapboxHandlers[ + message.layer_id + ]; + } + + // Remove click handlers for popups + if (window._mapboxClickHandlers) { + // First check for handlers stored with message.layer_id key + if (window._mapboxClickHandlers[message.layer_id]) { + map.off( + "click", + message.layer_id, + window._mapboxClickHandlers[message.layer_id] + ); + delete window._mapboxClickHandlers[message.layer_id]; + } + + // Also check for handlers stored with message.layer.id key from add_layer + if (message.layer && message.layer.id && window._mapboxClickHandlers[message.layer.id]) { + map.off( + "click", + message.layer_id, + window._mapboxClickHandlers[message.layer.id] + ); + delete window._mapboxClickHandlers[message.layer.id]; + } + } + + // Remove the layer + map.removeLayer(message.layer_id); + } + if (map.getSource(message.layer_id)) { + map.removeSource(message.layer_id); + } + + // Clean up tracked layer state + const mapId = map.getContainer().id; + if (window._mapglLayerState && window._mapglLayerState[mapId]) { + const layerState = window._mapglLayerState[mapId]; + delete layerState.filters[message.layer_id]; + delete layerState.paintProperties[message.layer_id]; + delete layerState.layoutProperties[message.layer_id]; + delete layerState.tooltips[message.layer_id]; + delete layerState.popups[message.layer_id]; + // Note: legends are not tied to specific layers, so we don't clear them here + } + } else if (message.type === "fit_bounds") { + map.fitBounds(message.bounds, message.options); + } else if (message.type === "fly_to") { + map.flyTo(message.options); + } else if (message.type === "ease_to") { + map.easeTo(message.options); + } else if (message.type === "set_center") { + map.setCenter(message.center); + } else if (message.type === "set_zoom") { + map.setZoom(message.zoom); + } else if (message.type === "jump_to") { + map.jumpTo(message.options); + } else if (message.type === "set_layout_property") { + map.setLayoutProperty( + message.layer, + message.name, + message.value, + ); + // Track layout property state for layer restoration + if (!layerState.layoutProperties[message.layer]) { + layerState.layoutProperties[message.layer] = {}; + } + layerState.layoutProperties[message.layer][message.name] = message.value; + } else if (message.type === "set_paint_property") { + const layerId = message.layer; + const propertyName = message.name; + const newValue = message.value; + + // Check if the layer has hover options + const layerStyle = map + .getStyle() + .layers.find( + (layer) => layer.id === layerId, + ); + const currentPaintProperty = + map.getPaintProperty(layerId, propertyName); + + if ( + currentPaintProperty && + Array.isArray(currentPaintProperty) && + currentPaintProperty[0] === "case" + ) { + // This property has hover options, so we need to preserve them + const hoverValue = currentPaintProperty[2]; + const newPaintProperty = [ + "case", + [ + "boolean", + ["feature-state", "hover"], + false, + ], + hoverValue, + newValue, + ]; + map.setPaintProperty( + layerId, + propertyName, + newPaintProperty, + ); + } else { + // No hover options, just set the new value directly + map.setPaintProperty( + layerId, + propertyName, + newValue, + ); + } + // Track paint property state for layer restoration + if (!layerState.paintProperties[layerId]) { + layerState.paintProperties[layerId] = {}; + } + layerState.paintProperties[layerId][propertyName] = newValue; + } else if (message.type === "add_legend") { + if (!message.add) { + const existingLegends = + document.querySelectorAll( + `#${data.id} .maplibregl-legend`, + ); + existingLegends.forEach((legend) => + legend.remove(), + ); + + // Clean up any existing legend styles that might have been added + const legendStyles = document.querySelectorAll(`style[data-mapgl-legend-css="${data.id}"]`); + legendStyles.forEach((style) => style.remove()); + } + + const legendCss = + document.createElement("style"); + legendCss.innerHTML = message.legend_css; + legendCss.setAttribute('data-mapgl-legend-css', data.id); // Mark this style for later cleanup + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = message.html; + legend.classList.add("maplibregl-legend"); + + // Append legend to the correct map container + const targetContainer = map.getContainer(); + targetContainer.appendChild(legend); + } else if (message.type === "set_config_property") { + map.setConfigProperty( + message.importId, + message.configName, + message.value, + ); + } else if (message.type === "set_style") { + // Save the current view state + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + // Default preserve_layers to true if not specified + const preserveLayers = message.preserve_layers !== false; + + // If we should preserve layers and sources + if (preserveLayers) { + // Store the current style before changing it + const currentStyle = map.getStyle(); + const userSourceIds = []; + const userLayers = []; + + console.log("[MapGL Debug] Current style sources:", Object.keys(currentStyle.sources)); + console.log("[MapGL Debug] Current style layers:", currentStyle.layers.map(l => l.id)); + + // Store layer IDs we know were added by the user via R code + // This is the most reliable way to identify user-added layers + const knownUserLayerIds = []; + + // For each layer in the current style, determine if it's a user-added layer + currentStyle.layers.forEach(function(layer) { + const layerId = layer.id; + + // Critical: Check for nc_counties specifically since we know that's used in the test app + if (layerId === "nc_counties") { + console.log("[MapGL Debug] Found explicit test layer:", layerId); + knownUserLayerIds.push(layerId); + if (layer.source && !userSourceIds.includes(layer.source)) { + console.log("[MapGL Debug] Found source from test layer:", layer.source); + userSourceIds.push(layer.source); + } + return; // Skip other checks for this layer + } + + // These are common patterns for user-added layers from R code + if ( + // Specific layer IDs from the R package + layerId.endsWith("_counties") || + layerId.endsWith("_label") || + layerId.endsWith("_layer") || + + // Look for hover handlers - only user-added layers have these + (window._mapboxHandlers && window._mapboxHandlers[layerId]) || + + // If the layer ID contains these strings, it's likely user-added + layerId.includes("user") || + layerId.includes("custom") || + + // If the paint property has a hover case, it's user-added + (layer.paint && Object.values(layer.paint).some(value => + Array.isArray(value) && + value[0] === "case" && + Array.isArray(value[1]) && + value[1][1] && + Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && + value[1][1][1] === "hover")) + ) { + console.log("[MapGL Debug] Found user layer:", layerId); + knownUserLayerIds.push(layerId); + // Only include its source if it's not a base map source + if (layer.source && !userSourceIds.includes(layer.source)) { + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = layerSource && layerSource.type === "vector" && ( + layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler") + ); + + if (!isBaseMapSource) { + console.log("[MapGL Debug] Found user source from layer:", layer.source); + userSourceIds.push(layer.source); + } else { + console.log("[MapGL Debug] Not adding base map source from layer:", layer.source); + } + } + } + }); + + // For each source, determine if it's a user-added source + for (const sourceId in currentStyle.sources) { + const source = currentStyle.sources[sourceId]; + + // Strategy 1: All GeoJSON sources are likely user-added + if (source.type === "geojson") { + console.log("[MapGL Debug] Found user GeoJSON source:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 2: Check for source data URL patterns typical of R-generated data + else if (source.url && typeof source.url === 'string' && + (source.url.includes("data:application/json") || + source.url.includes("blob:"))) { + console.log("[MapGL Debug] Found user source with data URL:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + // Strategy 3: Standard filtering - exclude common base map sources + else if ( + sourceId !== "composite" && + sourceId !== "mapbox" && + !sourceId.startsWith("mapbox-") && + sourceId !== "openmaptiles" && // Common in MapLibre styles + !(sourceId.startsWith("carto") && sourceId !== "carto-source") && // Filter CARTO base sources but keep user ones + !(sourceId.startsWith("maptiler") && !sourceId.includes("user")) && // Filter MapTiler sources but keep user ones + !sourceId.includes("terrain") && // Common terrain sources + !sourceId.includes("hillshade") && // Common hillshade sources + !(sourceId.includes("basemap") && !sourceId.includes("user")) // Filter basemap sources but keep user ones + ) { + console.log("[MapGL Debug] Found user source via filtering:", sourceId); + if (!userSourceIds.includes(sourceId)) { + userSourceIds.push(sourceId); + } + } + + // Store layer-specific handler references + if (window._mapboxHandlers) { + const handlers = window._mapboxHandlers; + for (const layerId in handlers) { + // Find layers associated with this source + const layer = currentStyle.layers.find(l => l.id === layerId); + if (layer && layer.source === sourceId) { + layer._handlers = handlers[layerId]; + } + } + } + } + + // Identify layers using user-added sources or known user layer IDs + // ONLY include layers that use genuinely user-added sources (not base map sources) + currentStyle.layers.forEach(function(layer) { + // Check if this layer uses a genuine user source (not filtered out base map sources) + const usesUserSource = userSourceIds.includes(layer.source); + const isKnownUserLayer = knownUserLayerIds.includes(layer.id); + + // Additional check: exclude layers that use base map sources even if they were temporarily added to userSourceIds + const layerSource = currentStyle.sources[layer.source]; + const isBaseMapSource = layerSource && layerSource.type === "vector" && ( + layer.source === "composite" || + layer.source === "mapbox" || + layer.source.startsWith("mapbox-") || + layer.source === "openmaptiles" || + layer.source.startsWith("carto") || + layer.source.startsWith("maptiler") + ); + + if ((usesUserSource || isKnownUserLayer) && !isBaseMapSource) { + userLayers.push(layer); + console.log("[MapGL Debug] Including user layer:", layer.id, "source:", layer.source); + } else if (isBaseMapSource) { + console.log("[MapGL Debug] Excluding base map layer:", layer.id, "source:", layer.source); + } + }); + + // Set up event listener to re-add sources and layers after style loads + const onStyleLoad = function() { + // Re-add user sources + userSourceIds.forEach(function(sourceId) { + if (!map.getSource(sourceId)) { + const source = currentStyle.sources[sourceId]; + map.addSource(sourceId, source); + } + }); + + // Re-add user layers + userLayers.forEach(function(layer) { + if (!map.getLayer(layer.id)) { + map.addLayer(layer); + + // Re-add event handlers for tooltips and hover effects + if (layer._handlers) { + const handlers = layer._handlers; + + if (handlers.mousemove) { + console.log("[MapGL Debug] Re-adding mousemove handler for:", layer.id); + map.on("mousemove", layer.id, handlers.mousemove); + } + + if (handlers.mouseleave) { + console.log("[MapGL Debug] Re-adding mouseleave handler for:", layer.id); + map.on("mouseleave", layer.id, handlers.mouseleave); + } + } + + // Check if we need to restore tooltip handlers + const layerId = layer.id; + if (layerId === "nc_counties" || layer.tooltip) { + console.log("[MapGL Debug] Restoring tooltip for:", layerId); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false + }); + + // Re-add tooltip handlers + const tooltipProperty = layer.tooltip || "NAME"; + + const mouseMoveHandler = function(e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = e.features[0].properties[tooltipProperty]; + tooltip.setLngLat(e.lngLat).setHTML(description).addTo(map); + } + }; + + const mouseLeaveHandler = function() { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layerId, mouseMoveHandler); + map.on("mouseleave", layerId, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layerId] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler + }; + } + + // Recreate hover states if needed + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if (Array.isArray(value) && value[0] === "case" && + Array.isArray(value[1]) && value[1][0] === "boolean" && + value[1][1][0] === "feature-state" && value[1][1][1] === "hover") { + // This is a hover-enabled paint property + map.setPaintProperty(layer.id, key, value); + } + } + } + } + }); + + // Clear any active tooltips before restoration to prevent stacking + if (window._activeTooltip) { + window._activeTooltip.remove(); + delete window._activeTooltip; + } + + // Restore tracked layer modifications + const mapId = map.getContainer().id; + const savedLayerState = window._mapglLayerState && window._mapglLayerState[mapId]; + if (savedLayerState) { + console.log("[MapGL Debug] Restoring tracked layer modifications"); + + // Restore filters + for (const layerId in savedLayerState.filters) { + if (map.getLayer(layerId)) { + console.log("[MapGL Debug] Restoring filter for layer:", layerId); + map.setFilter(layerId, savedLayerState.filters[layerId]); + } + } + + // Restore paint properties + for (const layerId in savedLayerState.paintProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.paintProperties[layerId]; + for (const propertyName in properties) { + const savedValue = properties[propertyName]; + + console.log("[MapGL Debug] Restoring paint property:", layerId, propertyName, savedValue); + + // Check if layer has hover effects that need to be preserved + const currentValue = map.getPaintProperty(layerId, propertyName); + if (currentValue && Array.isArray(currentValue) && currentValue[0] === "case") { + // Preserve hover effects while updating base value + const hoverValue = currentValue[2]; + const newPaintProperty = [ + "case", + ["boolean", ["feature-state", "hover"], false], + hoverValue, + savedValue, + ]; + map.setPaintProperty(layerId, propertyName, newPaintProperty); + } else { + map.setPaintProperty(layerId, propertyName, savedValue); + } + } + } + } + + // Restore layout properties + for (const layerId in savedLayerState.layoutProperties) { + if (map.getLayer(layerId)) { + const properties = savedLayerState.layoutProperties[layerId]; + for (const propertyName in properties) { + console.log("[MapGL Debug] Restoring layout property:", layerId, propertyName, properties[propertyName]); + map.setLayoutProperty(layerId, propertyName, properties[propertyName]); + } + } + } + + // Restore tooltips + for (const layerId in savedLayerState.tooltips) { + if (map.getLayer(layerId)) { + const tooltipProperty = savedLayerState.tooltips[layerId]; + console.log("[MapGL Debug] Restoring tooltip:", layerId, tooltipProperty); + + // Remove existing tooltip handlers first + map.off("mousemove", layerId); + map.off("mouseleave", layerId); + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on("mousemove", layerId, function (e) { + onMouseMoveTooltip(e, map, tooltip, tooltipProperty); + }); + + map.on("mouseleave", layerId, function () { + onMouseLeaveTooltip(map, tooltip); + }); + } + } + + // Restore popups + for (const layerId in savedLayerState.popups) { + if (map.getLayer(layerId)) { + const popupProperty = savedLayerState.popups[layerId]; + console.log("[MapGL Debug] Restoring popup:", layerId, popupProperty); + + // Remove existing popup handlers first + if (window._maplibreClickHandlers && window._maplibreClickHandlers[layerId]) { + map.off("click", layerId, window._maplibreClickHandlers[layerId]); + delete window._maplibreClickHandlers[layerId]; + } + + const clickHandler = function(e) { + onClickPopup(e, map, popupProperty, layerId); + }; + + map.on("click", layerId, clickHandler); + + if (!window._maplibreClickHandlers) { + window._maplibreClickHandlers = {}; + } + window._maplibreClickHandlers[layerId] = clickHandler; + } + } + } + + // Remove this listener to avoid adding the same layers multiple times + map.off('style.load', onStyleLoad); + }; + + map.on('style.load', onStyleLoad); + + // Store them for potential use outside the onStyleLoad event + // This helps in case the event timing is different in MapLibre + if (!window._mapglPreservedData) { + window._mapglPreservedData = {}; + } + window._mapglPreservedData[map.getContainer().id] = { + sources: userSourceIds.map(id => ({id, source: currentStyle.sources[id]})), + layers: userLayers + }; + + // Add a backup mechanism specific to MapLibre + // Some MapLibre styles or versions may have different event timing + if (userLayers.length > 0) { + // Set a timeout to check if layers were added after a reasonable delay + setTimeout(function() { + try { + console.log("[MapGL Debug] Running backup layer check"); + const mapId = map.getContainer().id; + const preserved = window._mapglPreservedData && window._mapglPreservedData[mapId]; + + if (preserved) { + // Check if user layers were successfully restored + const firstLayerId = preserved.layers[0]?.id; + if (firstLayerId && !map.getLayer(firstLayerId)) { + console.log("[MapGL Debug] Backup restoration needed for layers"); + + // Re-add sources first + preserved.sources.forEach(function(src) { + try { + if (!map.getSource(src.id)) { + console.log("[MapGL Debug] Backup: adding source", src.id); + map.addSource(src.id, src.source); + } + } catch (err) { + console.error("[MapGL Debug] Backup: error adding source", src.id, err); + } + }); + + // Then re-add layers + preserved.layers.forEach(function(layer) { + try { + if (!map.getLayer(layer.id)) { + console.log("[MapGL Debug] Backup: adding layer", layer.id); + map.addLayer(layer); + + // Check for nc_counties layer to restore tooltip + if (layer.id === "nc_counties") { + console.log("[MapGL Debug] Backup: restoring tooltip for", layer.id); + + // Create a new tooltip popup + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false + }); + + // Re-add tooltip handlers + const tooltipProperty = "NAME"; + + const mouseMoveHandler = function(e) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + const description = e.features[0].properties[tooltipProperty]; + tooltip.setLngLat(e.lngLat).setHTML(description).addTo(map); + } + }; + + const mouseLeaveHandler = function() { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }; + + map.on("mousemove", layer.id, mouseMoveHandler); + map.on("mouseleave", layer.id, mouseLeaveHandler); + + // Store these handlers + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler + }; + } + + // Restore hover states + if (layer.paint) { + for (const key in layer.paint) { + const value = layer.paint[key]; + if (Array.isArray(value) && value[0] === "case" && + Array.isArray(value[1]) && value[1][0] === "boolean" && + value[1][1] && Array.isArray(value[1][1]) && + value[1][1][0] === "feature-state" && value[1][1][1] === "hover") { + // This is a hover-enabled paint property + console.log("[MapGL Debug] Backup: restoring hover style for", layer.id, key); + map.setPaintProperty(layer.id, key, value); + } + } + } + } + } catch (err) { + console.error("[MapGL Debug] Backup: error adding layer", layer.id, err); + } + }); + } else { + console.log("[MapGL Debug] Backup check: layers already restored properly"); + } + } + } catch (err) { + console.error("[MapGL Debug] Error in backup restoration:", err); + } + }, 500); // 500ms delay - faster recovery + } + } + + // Apply the new style + map.setStyle(message.style, { + diff: message.diff, + }); + + if (message.config) { + Object.keys(message.config).forEach( + function (key) { + map.setConfigProperty( + "basemap", + key, + message.config[key], + ); + }, + ); + } + + // Restore the view state after the style has loaded + map.once("style.load", function () { + map.jumpTo({ + center: center, + zoom: zoom, + bearing: bearing, + pitch: pitch, + }); + + // Re-apply map modifications + if (map === beforeMap) { + applyMapModifications(map, x.map1); + } else { + applyMapModifications(map, x.map2); + } + }); + } else if ( + message.type === "add_navigation_control" + ) { + const nav = new maplibregl.NavigationControl({ + showCompass: message.options.show_compass, + showZoom: message.options.show_zoom, + visualizePitch: + message.options.visualize_pitch, + }); + map.addControl(nav, message.position); + + if (message.orientation === "horizontal") { + const navBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl.maplibregl-ctrl-group:not(.maplibre-gl-draw_ctrl-draw-btn)", + ); + if (navBar) { + navBar.style.display = "flex"; + navBar.style.flexDirection = "row"; + } + } + map.controls.push({ type: "navigation", control: nav }); + } else if (message.type === "add_reset_control") { + const resetControl = + document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute( + "aria-label", + "Reset", + ); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = + "background-color 0.2s"; + resetControl.addEventListener( + "mouseover", + function () { + this.style.backgroundColor = "#f0f0f0"; + }, + ); + resetControl.addEventListener( + "mouseout", + function () { + this.style.backgroundColor = "white"; + }, + ); + + const resetContainer = + document.createElement("div"); + resetContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: message.animate, + }; + + if (message.duration) { + initialView.duration = message.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild( + resetContainer, + ); + }, + }, + message.position, + ); + // Add to controls array + map.controls.push(resetControl); + } else if (message.type === "add_draw_control") { + let drawOptions = message.options || {}; + if (message.freehand) { + drawOptions = Object.assign( + {}, + drawOptions, + { + modes: Object.assign( + {}, + MapboxDraw.modes, + { + draw_polygon: + MapboxDraw.modes + .draw_freehand, + }, + ), + }, + ); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add event listeners + map.on( + "draw.create", + window.updateDrawnFeatures, + ); + map.on( + "draw.delete", + window.updateDrawnFeatures, + ); + map.on( + "draw.update", + window.updateDrawnFeatures, + ); + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector( + ".maplibregl-ctrl-group", + ); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + } else if (message.type === "get_drawn_features") { + if (draw) { + const features = draw + ? draw.getAll() + : null; + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if ( + message.type === "clear_drawn_features" + ) { + if (draw) { + draw.deleteAll(); + // Update the drawn features + window.updateDrawnFeatures(); + } + } else if (message.type === "add_markers") { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + message.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: + marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker( + markerOptions, + ) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setHTML(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + Shiny.setInputValue( + data.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + + mapMarker.on("dragend", function () { + const lngLat = + mapMarker.getLngLat(); + Shiny.setInputValue( + data.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + }); + } + + window.maplibreglMarkers.push(mapMarker); + }); + } else if (message.type === "clear_markers") { + if (window.maplibreglMarkers) { + window.maplibreglMarkers.forEach( + function (marker) { + marker.remove(); + }, + ); + window.maplibreglMarkers = []; + } + } else if ( + message.type === "add_fullscreen_control" + ) { + const position = + message.position || "top-right"; + const fullscreen = + new maplibregl.FullscreenControl(); + map.addControl(fullscreen, position); + map.controls.push(fullscreen); + } else if (message.type === "add_scale_control") { + const scaleControl = + new maplibregl.ScaleControl({ + maxWidth: message.options.maxWidth, + unit: message.options.unit, + }); + map.addControl( + scaleControl, + message.options.position, + ); + map.controls.push(scaleControl); + } else if ( + message.type === "add_geolocate_control" + ) { + const geolocate = + new maplibregl.GeolocateControl({ + positionOptions: + message.options.positionOptions, + trackUserLocation: + message.options.trackUserLocation, + showAccuracyCircle: + message.options.showAccuracyCircle, + showUserLocation: + message.options.showUserLocation, + showUserHeading: + message.options.showUserHeading, + fitBoundsOptions: + message.options.fitBoundsOptions, + }); + map.addControl( + geolocate, + message.options.position, + ); + map.controls.push(geolocate); + + if (HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue( + data.id + "_geolocate", + { + coords: event.coords, + time: new Date(), + }, + ); + }); + + geolocate.on( + "trackuserlocationstart", + function () { + Shiny.setInputValue( + data.id + "_geolocate_tracking", + { + status: "start", + time: new Date(), + }, + ); + }, + ); + + geolocate.on( + "trackuserlocationend", + function () { + Shiny.setInputValue( + data.id + "_geolocate_tracking", + { + status: "end", + time: new Date(), + }, + ); + }, + ); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue( + data.id + "_geolocate_error", + { + message: + "Location permission denied", + time: new Date(), + }, + ); + } + }); + } + } else if ( + message.type === "add_geocoder_control" + ) { + const provider = message.options.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: message.options.api_key, + maplibregl: maplibregl, + ...message.options, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = + await fetch(request); + const geojson = + await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - + feature.bbox[0]) / + 2, + feature.bbox[1] + + (feature.bbox[3] - + feature.bbox[1]) / + 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: + feature.properties + .display_name, + properties: + feature.properties, + text: feature.properties + .display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error( + `Failed to forwardGeocode with error: ${e}`, + ); + } + + return { + features, + }; + }, + }; + + const geocoderOptions = { + maplibregl: maplibregl, + ...message.options, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if ( + typeof geocoderOptions.collapsed === + "undefined" + ) + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder( + geocoderApi, + geocoderOptions, + ); + } + + map.addControl( + geocoder, + message.options.position || "top-right", + ); + map.controls.push(geocoder); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(data.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } else if (message.type === "add_layers_control") { + const layersControl = + document.createElement("div"); + layersControl.id = message.control_id; + layersControl.className = message.collapsible + ? "layers-control collapsible" + : "layers-control"; + layersControl.style.position = "absolute"; + + // Set the position correctly + const position = message.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (message.margin_top || 10) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (message.margin_bottom || 30) + "px"; + layersControl.style.left = (message.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (message.margin_bottom || 40) + "px"; + layersControl.style.right = (message.margin_right || 10) + "px"; + } + + // Apply custom colors if provided + if (message.custom_colors) { + const colors = message.custom_colors; + + // Create a style element for custom colors + const styleEl = + document.createElement("style"); + let css = ""; + + if (colors.background) { + css += `.layers-control { background-color: ${colors.background} !important; }`; + } + if (colors.text) { + css += `.layers-control a { color: ${colors.text} !important; }`; + } + if (colors.activeBackground) { + css += `.layers-control a.active { background-color: ${colors.activeBackground} !important; }`; + } + if (colors.activeText) { + css += `.layers-control a.active { color: ${colors.activeText} !important; }`; + } + if (colors.hoverBackground) { + css += `.layers-control a:hover { background-color: ${colors.hoverBackground} !important; }`; + } + if (colors.hoverText) { + css += `.layers-control a:hover { color: ${colors.hoverText} !important; }`; + } + if (colors.toggleButtonBackground) { + css += `.layers-control .toggle-button { background-color: ${colors.toggleButtonBackground} + !important; }`; + } + if (colors.toggleButtonText) { + css += `.layers-control .toggle-button { color: ${colors.toggleButtonText} !important; }`; + } + + styleEl.innerHTML = css; + document.head.appendChild(styleEl); + } + + document + .getElementById(data.id) + .appendChild(layersControl); + + const layersList = + document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + message.layers || + map + .getStyle() + .layers.map((layer) => layer.id); + + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = + map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty( + clickedLayer, + "visibility", + "none", + ); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + } + }; + + layersList.appendChild(link); + }); + + // Handle collapsible behavior + if (message.collapsible) { + const toggleButton = + document.createElement("div"); + toggleButton.className = "toggle-button"; + toggleButton.textContent = "Layers"; + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore( + toggleButton, + layersList, + ); + } + } else if (message.type === "add_globe_minimap") { + // Add the globe minimap control if supported + if (typeof MapboxGlobeMinimap !== "undefined") { + const minimap = new MapboxGlobeMinimap({ + center: map.getCenter(), + zoom: map.getZoom(), + bearing: map.getBearing(), + pitch: map.getPitch(), + globeSize: message.globe_size, + landColor: message.land_color, + waterColor: message.water_color, + markerColor: message.marker_color, + markerSize: message.marker_size, + }); + + map.addControl(minimap, message.position); + } else { + console.warn( + "MapboxGlobeMinimap is not defined", + ); + } + } else if (message.type === "add_globe_control") { + // Add the globe control + const globeControl = + new maplibregl.GlobeControl(); + map.addControl(globeControl, message.position); + map.controls.push(globeControl); + } else if (message.type === "add_draw_control") { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = message.options || {}; + + // Generate styles if styling parameters provided + if (message.styling) { + const generatedStyles = generateDrawStyles(message.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (message.freehand) { + drawOptions = Object.assign( + {}, + drawOptions, + { + modes: Object.assign( + {}, + MapboxDraw.modes, + { + draw_polygon: + MapboxDraw.modes + .draw_freehand, + }, + ), + // defaultMode: 'draw_polygon' # Don't set the default yet + }, + ); + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: '#fbb03b', + point_color: '#3bb2d0', + line_color: '#3bb2d0', + fill_color: '#3bb2d0', + fill_opacity: 0.1, + line_width: 2 + }); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, message.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add lasso icon CSS for freehand mode + if (message.freehand) { + if (!document.querySelector("#mapgl-freehand-lasso-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-freehand-lasso-styles"; + style.textContent = ` + .mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Cpath d="M 7 3 C 5 2.5, 3.5 3, 3 5 C 2.5 7, 3 8.5, 4 9.5 C 5 10.5, 5.5 11.5, 5 13 C 4.5 14.5, 5 15.5, 6.5 16 C 8 16.5, 9.5 16, 11 15 C 12.5 14, 13.5 13, 14.5 11.5 C 15.5 10, 16 8.5, 15.5 7 C 15 5.5, 14 4.5, 12.5 3.5 C 11 2.5, 9 2.5, 7 3 Z" fill="none" stroke="%23000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/%3E%3C/svg%3E') !important; + } + `; + document.head.appendChild(style); + } + + // Update tooltip for freehand mode + setTimeout(() => { + const polygonButton = map.getContainer().querySelector('.mapbox-gl-draw_polygon'); + if (polygonButton) { + polygonButton.title = 'Freehand polygon tool (p)'; + } + }, 100); + } + + // Add initial features if provided + if (message.source) { + addSourceFeaturesToDraw(draw, message.source, map); + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + + if (message.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (message.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${message.download_filename || 'drawn-features'}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + } else if (message.type === "get_drawn_features") { + if (draw) { + const features = draw + ? draw.getAll() + : null; + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(features), + ); + } else { + Shiny.setInputValue( + data.id + "_drawn_features", + JSON.stringify(null), + ); + } + } else if ( + message.type === "clear_drawn_features" + ) { + if (draw) { + draw.deleteAll(); + // Update the drawn features + updateDrawnFeatures(); + } + } else if (message.type === "add_features_to_draw") { + if (draw) { + if (message.data.clear_existing) { + draw.deleteAll(); + } + addSourceFeaturesToDraw(draw, message.data.source, map); + // Update the drawn features + updateDrawnFeatures(); + } else { + console.warn('Draw control not initialized'); + } + } else if (message.type === "set_projection") { + // Only if maplibre supports projection + if (typeof map.setProjection === "function") { + map.setProjection(message.projection); + } + } else if (message.type === "set_source") { + if (map.getLayer(message.layer)) { + const sourceId = map.getLayer( + message.layer, + ).source; + map.getSource(sourceId).setData( + JSON.parse(message.source), + ); + } + } else if (message.type === "set_tooltip") { + // Track tooltip state + layerState.tooltips[message.layer] = message.tooltip; + + if (map.getLayer(message.layer)) { + // Remove any existing tooltip handlers + map.off("mousemove", message.layer); + map.off("mouseleave", message.layer); + + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + map.on( + "mousemove", + message.layer, + function (e) { + map.getCanvas().style.cursor = + "pointer"; + if (e.features.length > 0) { + const description = + e.features[0].properties[ + message.tooltip + ]; + tooltip + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + } + }, + ); + + map.on( + "mouseleave", + message.layer, + function () { + map.getCanvas().style.cursor = ""; + tooltip.remove(); + }, + ); + } + } else if (message.type === "set_popup") { + // Track popup state + layerState.popups[message.layer] = message.popup; + + if (map.getLayer(message.layer)) { + // Remove any existing popup click handlers for this layer + if (window._maplibreClickHandlers && window._maplibreClickHandlers[message.layer]) { + map.off("click", message.layer, window._maplibreClickHandlers[message.layer]); + delete window._maplibreClickHandlers[message.layer]; + } + + // Remove any existing popup for this layer + if (window._maplibrePopups && window._maplibrePopups[message.layer]) { + window._maplibrePopups[message.layer].remove(); + delete window._maplibrePopups[message.layer]; + } + + // Create new click handler for popup + const clickHandler = function (e) { + onClickPopup(e, map, message.popup, message.layer); + }; + + // Store handler reference + if (!window._maplibreClickHandlers) { + window._maplibreClickHandlers = {}; + } + window._maplibreClickHandlers[message.layer] = clickHandler; + + // Add click handler + map.on("click", message.layer, clickHandler); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", message.layer, function () { + map.getCanvas().style.cursor = "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", message.layer, function () { + map.getCanvas().style.cursor = ""; + }); + } + } else if (message.type === "move_layer") { + if (map.getLayer(message.layer)) { + if (message.before) { + map.moveLayer( + message.layer, + message.before, + ); + } else { + map.moveLayer(message.layer); + } + } + } else if (message.type === "set_opacity") { + // Set opacity for all fill layers + const style = map.getStyle(); + if (style && style.layers) { + style.layers.forEach(function (layer) { + if ( + layer.type === "fill" && + map.getLayer(layer.id) + ) { + map.setPaintProperty( + layer.id, + "fill-opacity", + message.opacity, + ); + } + }); + } + } else if (message.type === "add_custom_control") { + const controlOptions = message.options; + const customControlContainer = document.createElement("div"); + + if (controlOptions.className) { + customControlContainer.className = controlOptions.className; + } else { + customControlContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + } + + customControlContainer.innerHTML = controlOptions.html; + + const customControl = { + onAdd: function () { + return customControlContainer; + }, + onRemove: function () { + if (customControlContainer.parentNode) { + customControlContainer.parentNode.removeChild( + customControlContainer, + ); + } + }, + }; + + map.addControl(customControl, controlOptions.position || "top-right"); + map.controls.push({ type: message.control_id, control: customControl }); + } else if (message.type === "query_rendered_features") { + // Query rendered features + let queryOptions = {}; + if (message.layers) { + // Ensure layers is always an array + queryOptions.layers = Array.isArray(message.layers) + ? message.layers + : [message.layers]; + } + if (message.filter) queryOptions.filter = message.filter; + + let features; + if (message.geometry) { + features = map.queryRenderedFeatures(message.geometry, queryOptions); + } else { + // No geometry specified - query entire viewport + features = map.queryRenderedFeatures(queryOptions); + } + + // Deduplicate features by id or by properties if no id + const uniqueFeatures = new Map(); + features.forEach(function (feature) { + let key; + if (feature.id !== undefined && feature.id !== null) { + key = feature.id; + } else { + // Create a key from properties if no id available + key = JSON.stringify(feature.properties); + } + + if (!uniqueFeatures.has(key)) { + uniqueFeatures.set(key, feature); + } + }); + + // Convert to GeoJSON FeatureCollection + const deduplicatedFeatures = Array.from(uniqueFeatures.values()); + const featureCollection = { + type: "FeatureCollection", + features: deduplicatedFeatures, + }; + + Shiny.setInputValue( + data.id + "_queried_features", + JSON.stringify(featureCollection) + ); + } else if (message.type === "clear_controls") { + // Handle clear_controls for compare widgets + if (!message.controls || message.controls.length === 0) { + // Clear all controls + map.controls.forEach((controlObj) => { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + }); + map.controls = []; + } else { + // Clear specific controls + const controlsToRemove = Array.isArray(message.controls) + ? message.controls + : [message.controls]; + + map.controls = map.controls.filter((controlObj) => { + if (controlsToRemove.includes(controlObj.type)) { + if (controlObj.control) { + map.removeControl(controlObj.control); + } + return false; // Remove from array + } + return true; // Keep in array + }); + } + } + }, + ); + } + + function setupShinyEvents(map, parentId, mapType) { + // Set view state on move end + map.on("moveend", function () { + const center = map.getCenter(); + const zoom = map.getZoom(); + const bearing = map.getBearing(); + const pitch = map.getPitch(); + + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_view", + { + center: [center.lng, center.lat], + zoom: zoom, + bearing: bearing, + pitch: pitch, + }, + ); + } + }); + + // Send clicked point coordinates to Shiny + map.on("click", function (e) { + // Check if this map's draw control is active and in a drawing mode + let isDrawing = false; + if (map._mapgl_draw && map._mapgl_draw.getMode) { + const mode = map._mapgl_draw.getMode(); + isDrawing = mode === 'draw_point' || + mode === 'draw_line_string' || + mode === 'draw_polygon'; + console.log(`[${mapType}] Draw mode: ${mode}, isDrawing: ${isDrawing}`); + } else { + console.log(`[${mapType}] No draw control found`); + } + + // Only process feature clicks if not actively drawing + if (!isDrawing) { + const features = map.queryRenderedFeatures(e.point); + // Filter out draw layers + const nonDrawFeatures = features.filter(feature => + !feature.layer.id.includes('gl-draw') && + !feature.source.includes('gl-draw') + ); + console.log(`[${mapType}] Features found: ${features.length}, non-draw: ${nonDrawFeatures.length}`); + + if (nonDrawFeatures.length > 0) { + const feature = nonDrawFeatures[0]; + console.log(`[${mapType}] Feature click detected, layer: ${feature.layer.id}`); + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_click", + { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }, + ); + } + } else { + console.log(`[${mapType}] No non-draw features found at click point`); + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_click", + null + ); + } + } + } else { + console.log(`[${mapType}] Feature click suppressed - currently drawing`); + } + + // Always send regular click event + if (window.Shiny) { + Shiny.setInputValue( + parentId + "_" + mapType + "_click", + { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: Date.now(), + }, + ); + } + }); + + // Add hover events if enabled for this map + const mapConfig = (mapType === "before") ? x.map1 : x.map2; + if (mapConfig.hover_events && mapConfig.hover_events.enabled) { + map.on("mousemove", function (e) { + if (window.Shiny) { + // Feature hover events + if (mapConfig.hover_events.features) { + const options = mapConfig.hover_events.layer_id + ? { layers: Array.isArray(mapConfig.hover_events.layer_id) + ? mapConfig.hover_events.layer_id + : mapConfig.hover_events.layer_id.split(',').map(id => id.trim()) } + : undefined; + const features = map.queryRenderedFeatures(e.point, options); + + if(features.length > 0) { + const feature = features[0]; + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + { + id: feature.id, + properties: feature.properties, + layer: feature.layer.id, + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } else { + Shiny.setInputValue( + parentId + "_" + mapType + "_feature_hover", + null + ); + } + } + + // Coordinate hover events + if (mapConfig.hover_events.coordinates) { + Shiny.setInputValue( + parentId + "_" + mapType + "_hover", + { + lng: e.lngLat.lng, + lat: e.lngLat.lat, + time: new Date(), + } + ); + } + } + }); + } + } + + function applyMapModifications(map, mapData) { + // Initialize controls array if it doesn't exist + if (!map.controls) { + map.controls = []; + } + // Define the tooltip handler functions to match the ones in maplibregl.js + function onMouseMoveTooltip( + e, + map, + tooltipPopup, + tooltipProperty, + ) { + map.getCanvas().style.cursor = "pointer"; + if (e.features.length > 0) { + let description; + + // Check if tooltipProperty is an expression (array) or a simple property name (string) + if (Array.isArray(tooltipProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(tooltipProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[tooltipProperty]; + } + + tooltipPopup + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to currently active tooltip + window._activeTooltip = tooltipPopup; + } else { + tooltipPopup.remove(); + // If this was the active tooltip, clear the reference + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } + } + + function onMouseLeaveTooltip(map, tooltipPopup) { + map.getCanvas().style.cursor = ""; + tooltipPopup.remove(); + if (window._activeTooltip === tooltipPopup) { + delete window._activeTooltip; + } + } + + function evaluateExpression(expression, properties) { + if (!Array.isArray(expression)) { + return expression; + } + + const operator = expression[0]; + + switch (operator) { + case 'get': + return properties[expression[1]]; + case 'concat': + return expression.slice(1).map(item => evaluateExpression(item, properties)).join(''); + case 'to-string': + return String(evaluateExpression(expression[1], properties)); + case 'to-number': + return Number(evaluateExpression(expression[1], properties)); + default: + // For literals and other simple values + return expression; + } + } + + function onClickPopup(e, map, popupProperty, layerId) { + let description; + + // Check if popupProperty is an expression (array) or a simple property name (string) + if (Array.isArray(popupProperty)) { + // It's an expression, evaluate it + description = evaluateExpression(popupProperty, e.features[0].properties); + } else { + // It's a property name, get the value + description = e.features[0].properties[popupProperty]; + } + + // Remove any existing popup for this layer + if (window._maplibrePopups && window._maplibrePopups[layerId]) { + window._maplibrePopups[layerId].remove(); + } + + // Create and show the popup + const popup = new maplibregl.Popup() + .setLngLat(e.lngLat) + .setHTML(description) + .addTo(map); + + // Store reference to this popup + if (!window._maplibrePopups) { + window._maplibrePopups = {}; + } + window._maplibrePopups[layerId] = popup; + + // Remove reference when popup is closed + popup.on('close', function() { + if (window._maplibrePopups[layerId] === popup) { + delete window._maplibrePopups[layerId]; + } + }); + } + + // Set config properties if provided + if (mapData.config_properties) { + mapData.config_properties.forEach(function (config) { + map.setConfigProperty( + config.importId, + config.configName, + config.value, + ); + }); + } + + // Process H3J sources if provided + if (mapData.h3j_sources) { + mapData.h3j_sources.forEach(async function (source) { + await map.addH3JSource(source.id, { + data: source.url, + }); + }); + } + + if (mapData.markers) { + if (!window.maplibreglMarkers) { + window.maplibreglMarkers = []; + } + mapData.markers.forEach(function (marker) { + const markerOptions = { + color: marker.color, + rotation: marker.rotation, + draggable: marker.options.draggable || false, + ...marker.options, + }; + const mapMarker = new maplibregl.Marker( + markerOptions, + ) + .setLngLat([marker.lng, marker.lat]) + .addTo(map); + + if (marker.popup) { + mapMarker.setPopup( + new maplibregl.Popup({ + offset: 25, + }).setText(marker.popup), + ); + } + + const markerId = marker.id; + if (markerId) { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + } + + mapMarker.on("dragend", function () { + const lngLat = mapMarker.getLngLat(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_marker_" + markerId, + { + id: markerId, + lng: lngLat.lng, + lat: lngLat.lat, + }, + ); + } + }); + } + + window.maplibreglMarkers.push(mapMarker); + }); + } + + // Add sources if provided + if (mapData.sources) { + mapData.sources.forEach(function (source) { + if (source.type === "vector") { + const sourceConfig = { + type: "vector", + url: source.url, + }; + if (source.promoteId) { + sourceConfig.promoteId = source.promoteId; + } + map.addSource(source.id, sourceConfig); + } else if (source.type === "geojson") { + map.addSource(source.id, { + type: "geojson", + data: source.data, + generateId: source.generateId !== false, + }); + } else if (source.type === "raster") { + if (source.url) { + map.addSource(source.id, { + type: "raster", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.tiles) { + map.addSource(source.id, { + type: "raster", + tiles: source.tiles, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } + } else if (source.type === "raster-dem") { + map.addSource(source.id, { + type: "raster-dem", + url: source.url, + tileSize: source.tileSize, + maxzoom: source.maxzoom, + }); + } else if (source.type === "image") { + map.addSource(source.id, { + type: "image", + url: source.url, + coordinates: source.coordinates, + }); + } else if (source.type === "video") { + map.addSource(source.id, { + type: "video", + urls: source.urls, + coordinates: source.coordinates, + }); + } + }); + } + + // Add layers if provided + if (mapData.layers) { + mapData.layers.forEach(function (layer) { + try { + const layerConfig = { + id: layer.id, + type: layer.type, + source: layer.source, + layout: layer.layout || {}, + paint: layer.paint || {}, + }; + + // Check if source is an object and set generateId if source type is 'geojson' + if ( + typeof layer.source === "object" && + layer.source.type === "geojson" + ) { + layerConfig.source.generateId = true; + } else if (typeof layer.source === "string") { + // Handle string source if needed + layerConfig.source = layer.source; + } + + if (layer.source_layer) { + layerConfig["source-layer"] = + layer.source_layer; + } + + if (layer.slot) { + layerConfig["slot"] = layer.slot; + } + + if (layer.minzoom) { + layerConfig["minzoom"] = layer.minzoom; + } + + if (layer.maxzoom) { + layerConfig["maxzoom"] = layer.maxzoom; + } + + if (layer.before_id) { + map.addLayer(layerConfig, layer.before_id); + } else { + map.addLayer(layerConfig); + } + + // Add popups or tooltips if provided + if (layer.popup) { + map.on("click", layer.id, function (e) { + onClickPopup(e, map, layer.popup, layer.id); + }); + + // Change cursor to pointer when hovering over the layer + map.on("mouseenter", layer.id, function () { + map.getCanvas().style.cursor = + "pointer"; + }); + + // Change cursor back to default when leaving the layer + map.on("mouseleave", layer.id, function () { + map.getCanvas().style.cursor = ""; + }); + } + + if (layer.tooltip) { + const tooltip = new maplibregl.Popup({ + closeButton: false, + closeOnClick: false, + }); + + // Create a reference to the mousemove handler function + const mouseMoveHandler = function (e) { + onMouseMoveTooltip( + e, + map, + tooltip, + layer.tooltip, + ); + }; + + // Create a reference to the mouseleave handler function + const mouseLeaveHandler = function () { + onMouseLeaveTooltip(map, tooltip); + }; + + // Attach the named handler references + map.on( + "mousemove", + layer.id, + mouseMoveHandler, + ); + map.on( + "mouseleave", + layer.id, + mouseLeaveHandler, + ); + + // Store these handler references + if (!window._mapboxHandlers) { + window._mapboxHandlers = {}; + } + window._mapboxHandlers[layer.id] = { + mousemove: mouseMoveHandler, + mouseleave: mouseLeaveHandler, + }; + } + + // Add hover effect if provided + if (layer.hover_options) { + const jsHoverOptions = {}; + for (const [key, value] of Object.entries( + layer.hover_options, + )) { + const jsKey = key.replace(/_/g, "-"); + jsHoverOptions[jsKey] = value; + } + + let hoveredFeatureId = null; + + map.on("mousemove", layer.id, function (e) { + if (e.features.length > 0) { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === + "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = e.features[0].id; + map.setFeatureState( + { + source: + typeof layer.source === + "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: true }, + ); + } + }); + + map.on("mouseleave", layer.id, function () { + if (hoveredFeatureId !== null) { + map.setFeatureState( + { + source: + typeof layer.source === + "string" + ? layer.source + : layer.id, + id: hoveredFeatureId, + }, + { hover: false }, + ); + } + hoveredFeatureId = null; + }); + + Object.keys(jsHoverOptions).forEach( + function (key) { + const originalPaint = + map.getPaintProperty( + layer.id, + key, + ) || layer.paint[key]; + map.setPaintProperty( + layer.id, + key, + [ + "case", + [ + "boolean", + [ + "feature-state", + "hover", + ], + false, + ], + jsHoverOptions[key], + originalPaint, + ], + ); + }, + ); + } + } catch (e) { + console.error( + "Failed to add layer: ", + layer, + e, + ); + } + }); + } + + // Set terrain if provided + if (mapData.terrain) { + map.setTerrain({ + source: mapData.terrain.source, + exaggeration: mapData.terrain.exaggeration, + }); + } + + // Set fog + if (mapData.fog) { + map.setFog(mapData.fog); + } + + if (mapData.fitBounds) { + map.fitBounds( + mapData.fitBounds.bounds, + mapData.fitBounds.options, + ); + } + if (mapData.flyTo) { + map.flyTo(mapData.flyTo); + } + if (mapData.easeTo) { + map.easeTo(mapData.easeTo); + } + if (mapData.setCenter) { + map.setCenter(mapData.setCenter); + } + if (mapData.setZoom) { + map.setZoom(mapData.setZoom); + } + + // Apply moveLayer operations if provided + if (mapData.moveLayer) { + mapData.moveLayer.forEach(function (moveOp) { + if (map.getLayer(moveOp.layer)) { + if (moveOp.before) { + map.moveLayer(moveOp.layer, moveOp.before); + } else { + map.moveLayer(moveOp.layer); + } + } + }); + } + if (mapData.jumpTo) { + map.jumpTo(mapData.jumpTo); + } + + // Add custom images if provided + if (mapData.images && Array.isArray(mapData.images)) { + mapData.images.forEach(async function (imageInfo) { + try { + const image = await map.loadImage( + imageInfo.url, + ); + if (!map.hasImage(imageInfo.id)) { + map.addImage( + imageInfo.id, + image.data, + imageInfo.options, + ); + } + } catch (error) { + console.error("Error loading image:", error); + } + }); + } else if (mapData.images) { + console.error( + "mapData.images is not an array:", + mapData.images, + ); + } + + // Remove existing legends only from this specific map container + const mapContainer = map.getContainer(); + const existingLegends = mapContainer.querySelectorAll(".mapboxgl-legend"); + existingLegends.forEach((legend) => legend.remove()); + + if (mapData.legend_html && mapData.legend_css) { + const legendCss = document.createElement("style"); + legendCss.innerHTML = mapData.legend_css; + document.head.appendChild(legendCss); + + const legend = document.createElement("div"); + legend.innerHTML = mapData.legend_html; + legend.classList.add("mapboxgl-legend"); + + // Append legend to the correct map container instead of main container + mapContainer.appendChild(legend); + } + + // Add fullscreen control if enabled + if ( + mapData.fullscreen_control && + mapData.fullscreen_control.enabled + ) { + const position = + mapData.fullscreen_control.position || "top-right"; + map.addControl( + new maplibregl.FullscreenControl(), + position, + ); + } + + // Helper function to generate draw styles based on parameters + function generateDrawStyles(styling) { + if (!styling) return null; + + return [ + // Point styles + { + 'id': 'gl-draw-point-active', + 'type': 'circle', + 'filter': ['all', + ['==', '$type', 'Point'], + ['==', 'meta', 'feature'], + ['==', 'active', 'true']], + 'paint': { + 'circle-radius': styling.vertex_radius + 2, + 'circle-color': styling.active_color + } + }, + { + 'id': 'gl-draw-point', + 'type': 'circle', + 'filter': ['all', + ['==', '$type', 'Point'], + ['==', 'meta', 'feature'], + ['==', 'active', 'false']], + 'paint': { + 'circle-radius': styling.vertex_radius, + 'circle-color': styling.point_color + } + }, + // Line styles + { + 'id': 'gl-draw-line', + 'type': 'line', + 'filter': ['all', ['==', '$type', 'LineString']], + 'layout': { + 'line-cap': 'round', + 'line-join': 'round' + }, + 'paint': { + 'line-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.line_color + ], + 'line-width': styling.line_width + } + }, + // Polygon fill + { + 'id': 'gl-draw-polygon-fill', + 'type': 'fill', + 'filter': ['all', ['==', '$type', 'Polygon']], + 'paint': { + 'fill-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.fill_color + ], + 'fill-outline-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.fill_color + ], + 'fill-opacity': styling.fill_opacity + } + }, + // Polygon outline + { + 'id': 'gl-draw-polygon-stroke', + 'type': 'line', + 'filter': ['all', ['==', '$type', 'Polygon']], + 'layout': { + 'line-cap': 'round', + 'line-join': 'round' + }, + 'paint': { + 'line-color': ['case', + ['==', ['get', 'active'], 'true'], styling.active_color, + styling.line_color + ], + 'line-width': styling.line_width + } + }, + // Midpoints + { + 'id': 'gl-draw-polygon-midpoint', + 'type': 'circle', + 'filter': ['all', + ['==', '$type', 'Point'], + ['==', 'meta', 'midpoint']], + 'paint': { + 'circle-radius': 3, + 'circle-color': styling.active_color + } + }, + // Vertex point halos + { + 'id': 'gl-draw-vertex-halo-active', + 'type': 'circle', + 'filter': ['all', + ['==', 'meta', 'vertex'], + ['==', '$type', 'Point']], + 'paint': { + 'circle-radius': ['case', + ['==', ['get', 'active'], 'true'], styling.vertex_radius + 4, + styling.vertex_radius + 2 + ], + 'circle-color': '#FFF' + } + }, + // Vertex points + { + 'id': 'gl-draw-vertex-active', + 'type': 'circle', + 'filter': ['all', + ['==', 'meta', 'vertex'], + ['==', '$type', 'Point']], + 'paint': { + 'circle-radius': ['case', + ['==', ['get', 'active'], 'true'], styling.vertex_radius + 2, + styling.vertex_radius + ], + 'circle-color': styling.active_color + } + } + ]; + } + + // Helper function to add features from a source to draw + function addSourceFeaturesToDraw(draw, sourceId, map) { + const source = map.getSource(sourceId); + if (source && source._data) { + draw.add(source._data); + } else { + console.warn('Source not found or has no data:', sourceId); + } + } + + if (mapData.scale_control) { + const scaleControl = new maplibregl.ScaleControl({ + maxWidth: mapData.scale_control.maxWidth, + unit: mapData.scale_control.unit, + }); + map.addControl( + scaleControl, + mapData.scale_control.position, + ); + map.controls.push(scaleControl); + } + + // Add navigation control if enabled + if (mapData.navigation_control) { + const nav = new maplibregl.NavigationControl({ + showCompass: + mapData.navigation_control.show_compass, + showZoom: mapData.navigation_control.show_zoom, + visualizePitch: + mapData.navigation_control.visualize_pitch, + }); + map.addControl( + nav, + mapData.navigation_control.position, + ); + map.controls.push({ type: "navigation", control: nav }); + } + + // Add geolocate control if enabled + if (mapData.geolocate_control) { + const geolocate = new maplibregl.GeolocateControl({ + positionOptions: + mapData.geolocate_control.positionOptions, + trackUserLocation: + mapData.geolocate_control.trackUserLocation, + showAccuracyCircle: + mapData.geolocate_control.showAccuracyCircle, + showUserLocation: + mapData.geolocate_control.showUserLocation, + showUserHeading: + mapData.geolocate_control.showUserHeading, + fitBoundsOptions: + mapData.geolocate_control.fitBoundsOptions, + }); + map.addControl( + geolocate, + mapData.geolocate_control.position, + ); + + map.controls.push(geolocate); + } + + // Add globe control if enabled + if (mapData.globe_control) { + const globeControl = new maplibregl.GlobeControl(); + map.addControl( + globeControl, + mapData.globe_control.position, + ); + map.controls.push(globeControl); + } + + // Add draw control if enabled + if (mapData.draw_control && mapData.draw_control.enabled) { + MapboxDraw.constants.classes.CONTROL_BASE = "maplibregl-ctrl"; + MapboxDraw.constants.classes.CONTROL_PREFIX = "maplibregl-ctrl-"; + MapboxDraw.constants.classes.CONTROL_GROUP = "maplibregl-ctrl-group"; + + let drawOptions = mapData.draw_control.options || {}; + + // Generate styles if styling parameters provided + if (mapData.draw_control.styling) { + const generatedStyles = generateDrawStyles(mapData.draw_control.styling); + if (generatedStyles) { + drawOptions.styles = generatedStyles; + } + } + + if (mapData.draw_control.freehand) { + drawOptions = Object.assign({}, drawOptions, { + modes: Object.assign({}, MapboxDraw.modes, { + draw_polygon: Object.assign( + {}, + MapboxDraw.modes.draw_freehand, + { + // Store the simplify_freehand option on the map object + onSetup: function (opts) { + const state = + MapboxDraw.modes.draw_freehand.onSetup.call( + this, + opts, + ); + this.map.simplify_freehand = + mapData.draw_control.simplify_freehand; + return state; + }, + }, + ), + }), + // defaultMode: 'draw_polygon' # Don't set the default yet + }); + } + + // Add rectangle mode if enabled + if (mapData.draw_control.rectangle) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_rectangle = MapboxDraw.modes.draw_rectangle; + } + + // Add radius mode if enabled + if (mapData.draw_control.radius) { + if (!drawOptions.modes) { + drawOptions.modes = Object.assign({}, MapboxDraw.modes); + } + drawOptions.modes.draw_radius = MapboxDraw.modes.draw_radius; + } + + // Fix MapLibre compatibility - ensure we always have custom styles + if (!drawOptions.styles) { + drawOptions.styles = generateDrawStyles({ + vertex_radius: 5, + active_color: '#fbb03b', + point_color: '#3bb2d0', + line_color: '#3bb2d0', + fill_color: '#3bb2d0', + fill_opacity: 0.1, + line_width: 2 + }); + } + + const drawControl = new MapboxDraw(drawOptions); + map.addControl(drawControl, mapData.draw_control.position); + map.controls.push({ type: "draw", control: drawControl }); + + // Store draw control on map for feature click detection + map._mapgl_draw = drawControl; + + // Add custom mode buttons and styling + setTimeout(() => { + const drawControlGroup = map.getContainer().querySelector(".maplibregl-ctrl-group"); + + // Add rectangle styling and button + if (mapData.draw_control.rectangle) { + if (!document.querySelector("#mapgl-rectangle-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-rectangle-styles"; + style.textContent = ` + .mapbox-gl-draw_rectangle { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Crect x="4" y="5" width="12" height="10" fill="none" stroke="%23000000" stroke-width="2"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_rectangle:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_rectangle.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const rectangleBtn = document.createElement("button"); + rectangleBtn.className = "mapbox-gl-draw_rectangle"; + rectangleBtn.title = "Rectangle tool"; + rectangleBtn.type = "button"; + rectangleBtn.onclick = function() { + drawControl.changeMode('draw_rectangle'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + rectangleBtn.classList.add('active'); + }; + drawControlGroup.appendChild(rectangleBtn); + } + } + + // Add radius styling and button + if (mapData.draw_control.radius) { + if (!document.querySelector("#mapgl-radius-styles")) { + const style = document.createElement("style"); + style.id = "mapgl-radius-styles"; + style.textContent = ` + .mapbox-gl-draw_radius { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"%3E%3Ccircle cx="10" cy="10" r="7" fill="none" stroke="%23000000" stroke-width="2"/%3E%3Ccircle cx="10" cy="10" r="1.5" fill="%23000000"/%3E%3C/svg%3E') !important; + background-repeat: no-repeat !important; + background-position: center !important; + } + .mapbox-gl-draw_radius:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_radius.active { + background-color: rgba(0, 0, 0, 0.05); + } + `; + document.head.appendChild(style); + } + + if (drawControlGroup) { + const radiusBtn = document.createElement("button"); + radiusBtn.className = "mapbox-gl-draw_radius"; + radiusBtn.title = "Radius/Circle tool"; + radiusBtn.type = "button"; + radiusBtn.onclick = function() { + drawControl.changeMode('draw_radius'); + drawControlGroup.querySelectorAll('button').forEach(btn => btn.classList.remove('active')); + radiusBtn.classList.add('active'); + }; + drawControlGroup.appendChild(radiusBtn); + } + } + }, 100); + + // Add initial features if provided + if (mapData.draw_control.source) { + addSourceFeaturesToDraw(drawControl, mapData.draw_control.source, map); + } + + // Process any queued features + if (mapData.draw_features_queue) { + mapData.draw_features_queue.forEach(function(data) { + if (data.clear_existing) { + drawControl.deleteAll(); + } + addSourceFeaturesToDraw(drawControl, data.source, map); + }); + } + + // Apply orientation styling + if (mapData.draw_control.orientation === "horizontal") { + const drawBar = map + .getContainer() + .querySelector(".maplibregl-ctrl-group"); + if (drawBar) { + drawBar.style.display = "flex"; + drawBar.style.flexDirection = "row"; + } + } + + // Add download button if requested + if (mapData.draw_control.download_button) { + // Add CSS for download button if not already added + if (!document.querySelector('#mapgl-draw-download-styles')) { + const style = document.createElement('style'); + style.id = 'mapgl-draw-download-styles'; + style.textContent = ` + .mapbox-gl-draw_download { + background: transparent; + border: none; + cursor: pointer; + display: block; + height: 30px; + width: 30px; + padding: 0; + outline: none; + } + .mapbox-gl-draw_download:hover { + background-color: rgba(0, 0, 0, 0.05); + } + .mapbox-gl-draw_download svg { + width: 20px; + height: 20px; + margin: 5px; + fill: #333; + } + `; + document.head.appendChild(style); + } + + // Small delay to ensure Draw control is fully rendered + setTimeout(() => { + // Find the Draw control button group + const drawButtons = map.getContainer().querySelector('.maplibregl-ctrl-group:has(.mapbox-gl-draw_polygon)'); + + if (drawButtons) { + // Create download button + const downloadBtn = document.createElement('button'); + downloadBtn.className = 'mapbox-gl-draw_download'; + downloadBtn.title = 'Download drawn features as GeoJSON'; + + // Add SVG download icon + downloadBtn.innerHTML = ` + + + + `; + + downloadBtn.addEventListener('click', () => { + // Get all drawn features + const data = draw.getAll(); + + if (data.features.length === 0) { + alert('No features to download. Please draw something first!'); + return; + } + + // Convert to string with nice formatting + const dataStr = JSON.stringify(data, null, 2); + + // Create blob and download + const blob = new Blob([dataStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = `${mapData.draw_control.download_filename}.geojson`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }); + + // Append to the Draw control button group + drawButtons.appendChild(downloadBtn); + } + }, 100); + } + + // Helper function for updating drawn features + function updateDrawnFeatures() { + if (HTMLWidgets.shinyMode && draw) { + const features = draw.getAll(); + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(features), + ); + } + } + + // Add event listeners + map.on("draw.create", updateDrawnFeatures); + map.on("draw.delete", updateDrawnFeatures); + map.on("draw.update", updateDrawnFeatures); + } + + if (mapData.geolocate_control && HTMLWidgets.shinyMode) { + geolocate.on("geolocate", function (event) { + Shiny.setInputValue(el.id + "_geolocate", { + coords: event.coords, + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationstart", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "start", + time: new Date(), + }); + }); + + geolocate.on("trackuserlocationend", function () { + Shiny.setInputValue(el.id + "_geolocate_tracking", { + status: "end", + time: new Date(), + }); + }); + + geolocate.on("error", function (error) { + if (error.error.code === 1) { + Shiny.setInputValue( + el.id + "_geolocate_error", + { + message: "Location permission denied", + time: new Date(), + }, + ); + } + }); + } + + // Add geocoder control if enabled + if (mapData.geocoder_control) { + const provider = mapData.geocoder_control.provider || "osm"; + let geocoder; + + if (provider === "maptiler") { + // MapTiler geocoder + const maptilerOptions = { + apiKey: mapData.geocoder_control.api_key, + maplibregl: maplibregl, + ...mapData.geocoder_control, + }; + + // Create MapTiler geocoder + geocoder = new maplibreglMaptilerGeocoder.GeocodingControl(maptilerOptions); + } else { + // OSM/Nominatim geocoder (default) + const geocoderApi = { + forwardGeocode: async (config) => { + const features = []; + try { + const request = `https://nominatim.openstreetmap.org/search?q=${ + config.query + }&format=geojson&polygon_geojson=1&addressdetails=1`; + const response = await fetch(request); + const geojson = await response.json(); + for (const feature of geojson.features) { + const center = [ + feature.bbox[0] + + (feature.bbox[2] - + feature.bbox[0]) / + 2, + feature.bbox[1] + + (feature.bbox[3] - + feature.bbox[1]) / + 2, + ]; + const point = { + type: "Feature", + geometry: { + type: "Point", + coordinates: center, + }, + place_name: + feature.properties.display_name, + properties: feature.properties, + text: feature.properties + .display_name, + place_type: ["place"], + center, + }; + features.push(point); + } + } catch (e) { + console.error( + `Failed to forwardGeocode with error: ${e}`, + ); + } + + return { + features, + }; + }, + }; + const geocoderOptions = { + maplibregl: maplibregl, + ...mapData.geocoder_control, + }; + + // Set default values if not provided + if (!geocoderOptions.placeholder) + geocoderOptions.placeholder = "Search"; + if (typeof geocoderOptions.collapsed === "undefined") + geocoderOptions.collapsed = false; + + geocoder = new MaplibreGeocoder( + geocoderApi, + geocoderOptions, + ); + } + + map.addControl( + geocoder, + mapData.geocoder_control.position || "top-right", + ); + + // Apply CSS fix for MapTiler geocoder to prevent cutoff + if (provider === "maptiler") { + setTimeout(() => { + const controlContainer = document.querySelector('.maplibregl-ctrl-geocoder'); + if (controlContainer) { + controlContainer.style.maxWidth = '300px'; + controlContainer.style.width = 'auto'; + } + }, 100); + } + + // Handle geocoder results in Shiny mode + if (HTMLWidgets.shinyMode) { + if (provider === "maptiler") { + // MapTiler uses different event names + geocoder.on("pick", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } else { + // OSM geocoder + geocoder.on("results", function (e) { + Shiny.setInputValue(el.id + "_geocoder", { + result: e, + time: new Date(), + }); + }); + } + } + } + + // Add reset control if enabled + if (mapData.reset_control) { + const resetControl = document.createElement("button"); + resetControl.className = + "maplibregl-ctrl-icon maplibregl-ctrl-reset"; + resetControl.type = "button"; + resetControl.setAttribute("aria-label", "Reset"); + resetControl.innerHTML = "⟲"; + resetControl.style.fontSize = "30px"; + resetControl.style.fontWeight = "bold"; + resetControl.style.backgroundColor = "white"; + resetControl.style.border = "none"; + resetControl.style.cursor = "pointer"; + resetControl.style.padding = "0"; + resetControl.style.width = "30px"; + resetControl.style.height = "30px"; + resetControl.style.display = "flex"; + resetControl.style.justifyContent = "center"; + resetControl.style.alignItems = "center"; + resetControl.style.transition = "background-color 0.2s"; + resetControl.addEventListener("mouseover", function () { + this.style.backgroundColor = "#f0f0f0"; + }); + resetControl.addEventListener("mouseout", function () { + this.style.backgroundColor = "white"; + }); + + const resetContainer = document.createElement("div"); + resetContainer.className = + "maplibregl-ctrl maplibregl-ctrl-group"; + resetContainer.appendChild(resetControl); + + const initialView = { + center: map.getCenter(), + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing(), + animate: mapData.reset_control.animate, + }; + + if (mapData.reset_control.duration) { + initialView.duration = + mapData.reset_control.duration; + } + + resetControl.onclick = function () { + map.easeTo(initialView); + }; + + map.addControl( + { + onAdd: function () { + return resetContainer; + }, + onRemove: function () { + resetContainer.parentNode.removeChild( + resetContainer, + ); + }, + }, + mapData.reset_control.position, + ); + } + + + function updateDrawnFeatures() { + if (map._mapgl_draw) { + var drawnFeatures = map._mapgl_draw.getAll(); + if (HTMLWidgets.shinyMode) { + Shiny.setInputValue( + el.id + "_drawn_features", + JSON.stringify(drawnFeatures), + ); + } + // Store drawn features in the widget's data + if (el.querySelector) { + var widget = HTMLWidgets.find("#" + el.id); + if (widget) { + widget.drawFeatures = drawnFeatures; + } + } + } + } + + // Add the layers control if provided + if (mapData.layers_control) { + const layersControl = document.createElement("div"); + layersControl.id = mapData.layers_control.control_id; + + // Handle use_icon parameter + let className = mapData.layers_control.collapsible + ? "layers-control collapsible" + : "layers-control"; + + layersControl.className = className; + layersControl.style.position = "absolute"; + + // Set the position correctly - fix position bug by using correct CSS positioning + const position = + mapData.layers_control.position || "top-left"; + if (position === "top-left") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "top-right") { + layersControl.style.top = (mapData.layers_control.margin_top || 10) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } else if (position === "bottom-left") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 30) + "px"; + layersControl.style.left = (mapData.layers_control.margin_left || 10) + "px"; + } else if (position === "bottom-right") { + layersControl.style.bottom = (mapData.layers_control.margin_bottom || 40) + "px"; + layersControl.style.right = (mapData.layers_control.margin_right || 10) + "px"; + } + + el.appendChild(layersControl); + + const layersList = document.createElement("div"); + layersList.className = "layers-list"; + layersControl.appendChild(layersList); + + // Fetch layers to be included in the control + let layers = + mapData.layers_control.layers || + map.getStyle().layers.map((layer) => layer.id); + let layersConfig = mapData.layers_control.layers_config; + + // If we have a layers_config, use that; otherwise fall back to original behavior + if (layersConfig && Array.isArray(layersConfig)) { + layersConfig.forEach((config, index) => { + const link = document.createElement("a"); + // Ensure config.ids is always an array + const layerIds = Array.isArray(config.ids) ? config.ids : [config.ids]; + link.id = layerIds.join("-"); + link.href = "#"; + link.textContent = config.label; + link.setAttribute("data-layer-ids", JSON.stringify(layerIds)); + link.setAttribute("data-layer-type", config.type); + + // Check if the first layer's visibility is set to "none" initially + const firstLayerId = layerIds[0]; + const initialVisibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + link.className = initialVisibility === "none" ? "" : "active"; + + // Show or hide layer(s) when the toggle is clicked + link.onclick = function (e) { + e.preventDefault(); + e.stopPropagation(); + + const layerIds = JSON.parse(this.getAttribute("data-layer-ids")); + const firstLayerId = layerIds[0]; + const visibility = map.getLayoutProperty( + firstLayerId, + "visibility", + ); + + // Toggle visibility for all layer IDs in the group + if (visibility === "visible") { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "none"); + }); + this.className = ""; + } else { + layerIds.forEach(layerId => { + map.setLayoutProperty(layerId, "visibility", "visible"); + }); + this.className = "active"; + } + }; + + layersList.appendChild(link); + }); + } else { + // Fallback to original behavior for simple layer arrays + layers.forEach((layerId, index) => { + const link = document.createElement("a"); + link.id = layerId; + link.href = "#"; + link.textContent = layerId; + link.className = "active"; + + // Show or hide layer when the toggle is clicked + link.onclick = function (e) { + const clickedLayer = this.textContent; + e.preventDefault(); + e.stopPropagation(); + + const visibility = map.getLayoutProperty( + clickedLayer, + "visibility", + ); + + // Toggle layer visibility by changing the layout object's visibility property + if (visibility === "visible") { + map.setLayoutProperty( + clickedLayer, + "visibility", + "none", + ); + this.className = ""; + } else { + this.className = "active"; + map.setLayoutProperty( + clickedLayer, + "visibility", + "visible", + ); + } + }; + + layersList.appendChild(link); + }); + } + + // Handle collapsible behavior + if (mapData.layers_control.collapsible) { + const toggleButton = document.createElement("div"); + toggleButton.className = "toggle-button"; + + if (mapData.layers_control.use_icon) { + // Add icon-only class to the control for compact styling + layersControl.classList.add("icon-only"); + + // More GIS-like layers stack icon + toggleButton.innerHTML = ` + + + + `; + toggleButton.style.display = "flex"; + toggleButton.style.alignItems = "center"; + toggleButton.style.justifyContent = "center"; + } else { + toggleButton.textContent = "Layers"; + } + + toggleButton.onclick = function () { + layersControl.classList.toggle("open"); + }; + layersControl.insertBefore( + toggleButton, + layersList, + ); + } + } + + // Set projection if provided (after all other setup is complete) + if (mapData.setProjection && mapData.setProjection.length > 0) { + mapData.setProjection.forEach(function (projectionConfig) { + if (projectionConfig.projection) { + const projection = + typeof projectionConfig.projection === "string" + ? { type: projectionConfig.projection } + : projectionConfig.projection; + try { + map.setProjection(projection); + } catch (e) { + console.error("Failed to set projection in compare view:", e); + } + } + }); + } + } + }, + + resize: function (width, height) { + // Code to handle resizing if necessary + }, + }; + }, +}); diff --git a/docs/articles/turf_files/turf-operations-1.0.0/maplibregl_compare.yaml b/docs/articles/turf_files/turf-operations-1.0.0/maplibregl_compare.yaml new file mode 100644 index 0000000..a72887c --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/maplibregl_compare.yaml @@ -0,0 +1,67 @@ +dependencies: + - name: maplibre-gl + version: "5.7.2" + src: "htmlwidgets/lib/maplibre-gl" + script: + - "maplibre-gl.js" + stylesheet: + - "maplibre-gl.css" + - name: maplibre-gl-compare + version: "0.5" + src: "htmlwidgets/lib/maplibre-gl-compare" + script: + - "maplibre-gl-compare.js" + stylesheet: + - "maplibre-gl-compare.css" + - name: mapbox-gl-draw + version: "1.5.0" + src: "htmlwidgets/lib/mapbox-gl-draw" + script: + - "mapbox-gl-draw.js" + stylesheet: + - "mapbox-gl-draw.css" + - name: freehand-mode + version: 1.0.0 + src: "htmlwidgets/lib/freehand-mode" + script: + - "freehand-mode.js" + - name: rectangle-mode + version: 1.0.0 + src: "htmlwidgets/lib/rectangle-mode" + script: + - "rectangle-mode.js" + - name: radius-mode + version: 1.0.0 + src: "htmlwidgets/lib/radius-mode" + script: + - "radius-mode.js" + - name: maplibre-gl-geocoder + version: 1.5.0 + src: "htmlwidgets/lib/maplibre-gl-geocoder" + script: + - "maplibre-gl-geocoder.min.js" + stylesheet: + - "maplibre-gl-geocoder.css" + - name: mapbox-gl-globe-minimap + version: 1.2.1 + src: "htmlwidgets/lib/mapbox-gl-globe-minimap" + script: + - "bundle.js" + - name: pmtiles + version: 4.3.0 + src: "htmlwidgets/lib/pmtiles" + script: + - "pmtiles.js" + - name: h3j-h3t + version: 0.9.2 + src: "htmlwidgets/lib/h3j-h3t" + script: + - "h3j_h3t.js" + - name: maptiler-geocoding-control + version: 2.1.7 + src: + href: "https://cdn.maptiler.com/maptiler-geocoding-control/v2.1.7/" + script: + - "maplibregl.umd.js" + stylesheet: + - "style.css" diff --git a/docs/articles/turf_files/turf-operations-1.0.0/styles/filter-control.css b/docs/articles/turf_files/turf-operations-1.0.0/styles/filter-control.css new file mode 100644 index 0000000..e6096c3 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/styles/filter-control.css @@ -0,0 +1,65 @@ +.filter-control { + background: #fff; + position: absolute; + z-index: 1; + border-radius: 3px; + width: 200px; + border: 1px solid rgba(0, 0, 0, 0.4); + font-family: 'Open Sans', sans-serif; + margin: 10px; + padding: 10px; +} + +.filter-control .filter-title { + font-weight: bold; + margin-bottom: 10px; + text-align: center; +} + +.filter-control input[type="range"] { + width: 100%; + margin: 10px 0; +} + +.filter-control .range-value { + text-align: center; + margin-top: 5px; +} + +.filter-control .checkbox-group { + display: flex; + flex-direction: column; + gap: 5px; +} + +.filter-control .checkbox-group label { + display: flex; + align-items: center; + gap: 5px; +} + +.filter-control .toggle-button { + background: darkgrey; + color: #ffffff; + text-align: center; + cursor: pointer; + padding: 5px 0; + border-radius: 3px 3px 0 0; + margin: -10px -10px 10px -10px; +} + +.filter-control .toggle-button:hover { + background: grey; +} + +.filter-control .filter-content { + display: block; +} + +.filter-control.collapsible .filter-content { + display: none; +} + +.filter-control.collapsible.open .filter-content { + display: block; +} \ No newline at end of file diff --git a/docs/articles/turf_files/turf-operations-1.0.0/styles/layers-control.css b/docs/articles/turf_files/turf-operations-1.0.0/styles/layers-control.css new file mode 100644 index 0000000..8551228 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/styles/layers-control.css @@ -0,0 +1,123 @@ +.layers-control { + background: #fff; + position: absolute; + z-index: 1; + border-radius: 4px; + width: 120px; + border: 1px solid rgba(0, 0, 0, 0.15); + font-family: "Open Sans", sans-serif; + margin: 0px; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15); + overflow: hidden; + transition: all 0.2s ease-in-out; +} + +.layers-control a { + font-size: 13px; + color: #404040; + display: block; + margin: 0; + padding: 10px; + text-decoration: none; + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + text-align: center; + transition: all 0.15s ease-in-out; + font-weight: normal; +} + +.layers-control a:last-child { + border: none; +} + +.layers-control a:hover { + background-color: #f8f8f8; + color: #1a1a1a; +} + +.layers-control a.active { + background-color: #4a90e2; + color: #ffffff; + font-weight: 500; +} + +.layers-control a.active:hover { + background: #3b7ed2; +} + +.layers-control .toggle-button { + display: none; + background: #4a90e2; + color: #ffffff; + text-align: center; + cursor: pointer; + padding: 8px 0; + border-radius: 4px 4px 0 0; + font-weight: 500; + letter-spacing: 0.3px; + box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.05) inset; + transition: all 0.15s ease-in-out; +} + +.layers-control .toggle-button:hover { + background: #3b7ed2; +} + +.layers-control .layers-list { + display: block; +} + +.layers-control.collapsible .toggle-button { + display: block; + border-bottom: 1px solid rgba(0, 0, 0, 0.25); +} + +.layers-control.collapsible .layers-list { + display: none; + opacity: 0; + max-height: 0; + transition: + opacity 0.25s ease, + max-height 0.25s ease; +} + +.layers-control.collapsible.open .layers-list { + display: block; + opacity: 1; + max-height: 500px; /* Large enough value to accommodate all content */ +} + +/* Compact icon styling */ +.layers-control.collapsible.icon-only { + width: auto; + min-width: 36px; + border-radius: 4px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); + transform: translateZ( + 0 + ); /* Force hardware acceleration for smoother animations */ +} + +.layers-control.collapsible.icon-only .toggle-button { + border-radius: 4px; + padding: 8px; + width: 36px; + height: 36px; + box-sizing: border-box; + margin: 0; + border-bottom: none; + display: flex; + align-items: center; + justify-content: center; + box-shadow: none; +} + +.layers-control.collapsible.icon-only.open { + width: 120px; + box-shadow: 0 3px 10px rgba(0, 0, 0, 0.25); +} + +.layers-control.collapsible.icon-only.open .toggle-button { + border-radius: 4px 4px 0 0; + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + width: 100%; +} diff --git a/docs/articles/turf_files/turf-operations-1.0.0/turf-operations.js b/docs/articles/turf_files/turf-operations-1.0.0/turf-operations.js new file mode 100644 index 0000000..2b4e514 --- /dev/null +++ b/docs/articles/turf_files/turf-operations-1.0.0/turf-operations.js @@ -0,0 +1,967 @@ +// Turf.js operations module for mapgl +// Shared operations that work with both mapboxgl and maplibre maps + +// Process turf operations on map initialization (for static maps) +function processTurfOperationsOnLoad(map, turfOperations, widgetId) { + if (!turfOperations || turfOperations.length === 0) return; + + // Wait for map to be fully loaded, then execute operations + map.on('load', function() { + // Add a small delay to ensure all layers are loaded + setTimeout(function() { + turfOperations.forEach(function(operation) { + try { + handleTurfOperation(map, operation, widgetId); + } catch (error) { + console.error(`Error processing turf operation ${operation.type}:`, error); + } + }); + }, 100); + }); +} + +// Main handler for all turf operations +function handleTurfOperation(map, message, widgetId) { + try { + switch (message.type) { + case "turf_buffer": + executeTurfBuffer(map, message, widgetId); + break; + case "turf_union": + executeTurfUnion(map, message, widgetId); + break; + case "turf_intersect": + executeTurfIntersect(map, message, widgetId); + break; + case "turf_difference": + executeTurfDifference(map, message, widgetId); + break; + case "turf_convex_hull": + executeTurfConvexHull(map, message, widgetId); + break; + case "turf_concave_hull": + executeTurfConcaveHull(map, message, widgetId); + break; + case "turf_voronoi": + executeTurfVoronoi(map, message, widgetId); + break; + case "turf_distance": + executeTurfDistance(map, message, widgetId); + break; + case "turf_area": + executeTurfArea(map, message, widgetId); + break; + case "turf_centroid": + executeTurfCentroid(map, message, widgetId); + break; + case "turf_center_of_mass": + executeTurfCenterOfMass(map, message, widgetId); + break; + case "turf_filter": + executeTurfFilter(map, message, widgetId); + break; + default: + console.warn(`Unknown turf operation: ${message.type}`); + } + } catch (error) { + console.error(`Error executing turf operation ${message.type}:`, error); + if (HTMLWidgets.shinyMode && message.send_to_r) { + Shiny.setInputValue(widgetId + "_turf_error", { + operation: message.type, + error: error.message, + timestamp: Date.now() + }); + } + } +} + +// Helper function to get input data for turf operations +function getInputData(map, message) { + // If coordinates provided, create point or points client-side + if (message.coordinates) { + // Handle single coordinate pair + if (typeof message.coordinates[0] === 'number') { + return turf.point(message.coordinates); + } + // Handle multiple coordinate pairs + if (Array.isArray(message.coordinates[0])) { + const points = message.coordinates.map(coord => turf.point(coord)); + return { + type: "FeatureCollection", + features: points + }; + } + } + + // If GeoJSON data provided directly + if (message.data) { + // Check if data is already an object (shouldn't happen) or string + if (typeof message.data === 'string') { + return JSON.parse(message.data); + } else { + // If it's already an object, return as-is + return message.data; + } + } + + // If layer_id provided, get from existing layer + if (message.layer_id) { + return getSourceData(map, message.layer_id); + } + + throw new Error("No valid input data provided (coordinates, data, or layer_id)"); +} + +// Helper function to get source data from a layer +function getSourceData(map, layerId) { + // First try to get from existing source + const source = map.getSource(layerId); + if (source) { + // Check for _data property (GeoJSON sources) + if (source._data) { + return source._data; + } + // Check for data property + if (source.data) { + return source.data; + } + } + + // Try with _source suffix (common pattern in mapgl) + const sourceWithSuffix = map.getSource(layerId + "_source"); + if (sourceWithSuffix) { + if (sourceWithSuffix._data) { + return sourceWithSuffix._data; + } + if (sourceWithSuffix.data) { + return sourceWithSuffix.data; + } + } + + // Query rendered features as fallback + try { + const features = map.queryRenderedFeatures({ layers: [layerId] }); + if (features.length > 0) { + return { + type: "FeatureCollection", + features: features + }; + } + } catch (e) { + // Layer might not exist, continue to error + } + + throw new Error(`Could not find source data for layer: ${layerId}`); +} + +// Helper function to add result source to map +function addResultSource(map, result, sourceId) { + if (!sourceId) return; + + // Ensure result is valid GeoJSON + if (!result) { + result = { + type: "FeatureCollection", + features: [] + }; + } + + // Check if source exists, update data or create new + const existingSource = map.getSource(sourceId); + if (existingSource) { + // Update existing source data + existingSource.setData(result); + } else { + // Add new source with result data + map.addSource(sourceId, { + type: "geojson", + data: result, + generateId: true + }); + } +} + +// Helper function to send result to R via Shiny input +function sendResultToR(widgetId, operation, result, metadata = {}, inputId = null) { + if (HTMLWidgets.shinyMode && inputId) { + Shiny.setInputValue(widgetId + "_turf_" + inputId, { + operation: operation, + result: result, + metadata: metadata, + timestamp: Date.now() + }); + } +} + +// Buffer operation +function executeTurfBuffer(map, message, widgetId) { + const inputData = getInputData(map, message); + + const buffered = turf.buffer(inputData, message.radius, { + units: message.units || "meters" + }); + + if (message.source_id) { + addResultSource(map, buffered, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "buffer", buffered, { + radius: message.radius, + units: message.units || "meters" + }, message.input_id); + } +} + +// Union operation +function executeTurfUnion(map, message, widgetId) { + const inputData = getInputData(map, message); + + let result; + if (inputData.type === "FeatureCollection" && inputData.features.length > 1) { + // Use turf.union with properly formatted FeatureCollection + const union = turf.union(turf.featureCollection(inputData.features)); + + result = union ? { + type: "FeatureCollection", + features: [union] + } : { + type: "FeatureCollection", + features: [] + }; + } else if (inputData.type === "FeatureCollection" && inputData.features.length === 1) { + // Single feature, return as-is + result = { + type: "FeatureCollection", + features: [inputData.features[0]] + }; + } else { + // Single feature, return as-is in FeatureCollection + result = { + type: "FeatureCollection", + features: [inputData] + }; + } + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "union", result, {}, message.input_id); + } +} + +// Intersect operation +function executeTurfIntersect(map, message, widgetId) { + const sourceData1 = getInputData(map, message); + + // Get second geometry data + let sourceData2; + if (message.data_2) { + // Handle data_2 directly + if (typeof message.data_2 === 'string') { + sourceData2 = JSON.parse(message.data_2); + } else { + sourceData2 = message.data_2; + } + } else if (message.layer_id_2) { + // Handle layer_id_2 as before + sourceData2 = getSourceData(map, message.layer_id_2); + } else { + throw new Error("Either data_2 or layer_id_2 must be provided for intersect operation"); + } + + // Extract features arrays + const features1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features : [sourceData1]; + const features2 = sourceData2.type === "FeatureCollection" ? + sourceData2.features : [sourceData2]; + + // Collect all intersection results + const resultFeatures = []; + + features1.forEach((feature1, index1) => { + if (!feature1 || !feature1.geometry) { + console.warn(`Skipping invalid feature at index ${index1}`); + return; + } + + features2.forEach((feature2, index2) => { + if (!feature2 || !feature2.geometry) { + return; + } + + // Use booleanIntersects for efficient filtering + if (turf.booleanIntersects(feature1, feature2)) { + try { + // Use turf.intersect with options to preserve properties + const intersection = turf.intersect( + turf.featureCollection([feature1, feature2]), + { properties: feature1.properties } + ); + + if (intersection) { + // Ensure properties are preserved (fallback if options didn't work) + if (!intersection.properties || Object.keys(intersection.properties).length === 0) { + intersection.properties = { ...feature1.properties }; + } + resultFeatures.push(intersection); + } + } catch (error) { + console.error(`Error intersecting features ${index1} and ${index2}:`, error); + } + } + }); + }); + + const result = { + type: "FeatureCollection", + features: resultFeatures + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "intersect", result, {}, message.input_id); + } +} + +// Difference operation +function executeTurfDifference(map, message, widgetId) { + const sourceData1 = getInputData(map, message); + + // Get second geometry data + let sourceData2; + if (message.data_2) { + // Handle data_2 directly + if (typeof message.data_2 === 'string') { + sourceData2 = JSON.parse(message.data_2); + } else { + sourceData2 = message.data_2; + } + } else if (message.layer_id_2) { + // Handle layer_id_2 as before + sourceData2 = getSourceData(map, message.layer_id_2); + } else { + throw new Error("Either data_2 or layer_id_2 must be provided for difference operation"); + } + + // Extract features arrays + const features1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features : [sourceData1]; + const features2 = sourceData2.type === "FeatureCollection" ? + sourceData2.features : [sourceData2]; + + // Process each feature in features1 + const resultFeatures = []; + + features1.forEach((feature1, index) => { + if (!feature1 || !feature1.geometry) { + console.warn(`Skipping invalid feature at index ${index}`); + return; + } + + // Start with the original feature + let currentFeature = feature1; + + // Apply difference with each feature from features2 + for (const feature2 of features2) { + if (!feature2 || !feature2.geometry || !currentFeature) { + continue; + } + + // Use booleanIntersects for efficient filtering + if (turf.booleanIntersects(currentFeature, feature2)) { + try { + const diff = turf.difference(turf.featureCollection([currentFeature, feature2])); + + if (diff) { + // Preserve properties from the original feature + diff.properties = { ...feature1.properties }; + currentFeature = diff; + } else { + // Feature was completely erased + currentFeature = null; + break; + } + } catch (error) { + console.error("Error in difference operation:", error); + // Keep the current feature unchanged on error + } + } + // If no intersection, currentFeature remains unchanged + } + + // Add the result if it still exists + if (currentFeature) { + resultFeatures.push(currentFeature); + } + }); + + const result = { + type: "FeatureCollection", + features: resultFeatures + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "difference", result, {}, message.input_id); + } +} + +// Convex hull operation +function executeTurfConvexHull(map, message, widgetId) { + const inputData = getInputData(map, message); + + // Ensure we have valid input data + if (!inputData) { + console.warn("No input data for convex hull"); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + // Check for minimum points if it's a FeatureCollection + if (inputData.type === "FeatureCollection" && inputData.features.length < 3) { + console.warn("Convex hull requires at least 3 points, got:", inputData.features.length); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + const hull = turf.convex(inputData); + + const result = hull ? { + type: "FeatureCollection", + features: [hull] + } : { + type: "FeatureCollection", + features: [] + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "convex_hull", result, {}, message.input_id); + } +} + +// Concave hull operation +function executeTurfConcaveHull(map, message, widgetId) { + const inputData = getInputData(map, message); + + // Ensure we have a FeatureCollection of Points for turf.concave + let pointCollection; + if (inputData.type === "FeatureCollection") { + // Filter to only Point geometries and ensure it's a proper FeatureCollection + const pointFeatures = inputData.features.filter(feature => + feature.geometry && feature.geometry.type === "Point" + ); + pointCollection = turf.featureCollection(pointFeatures); + } else if (inputData.type === "Feature" && inputData.geometry.type === "Point") { + // Single point - wrap in FeatureCollection + pointCollection = turf.featureCollection([inputData]); + } else { + console.warn("Concave hull requires Point geometries, received:", inputData); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + // Check if we have enough points (need at least 3 for a hull) + if (!pointCollection.features || pointCollection.features.length < 3) { + console.warn("Concave hull requires at least 3 points, got:", pointCollection.features?.length || 0); + const result = { + type: "FeatureCollection", + features: [] + }; + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + return; + } + + // Smart max_edge calculation with fallback + let hull = null; + let actualMaxEdge = message.max_edge; + + if (message.max_edge) { + // User specified max_edge, try it first + hull = turf.concave(pointCollection, { + maxEdge: message.max_edge, + units: message.units || "kilometers" + }); + } + + // If no hull or user didn't specify max_edge, try to find optimal value + if (!hull) { + // Calculate distances between all points to find reasonable max_edge + const distances = []; + const features = pointCollection.features; + + for (let i = 0; i < features.length; i++) { + for (let j = i + 1; j < features.length; j++) { + const dist = turf.distance(features[i], features[j], { + units: message.units || "kilometers" + }); + distances.push(dist); + } + } + + // Sort distances and try different percentiles as max_edge + distances.sort((a, b) => a - b); + const percentiles = [0.6, 0.7, 0.8, 0.9]; // Try 60th, 70th, 80th, 90th percentiles + + for (const percentile of percentiles) { + const index = Math.floor(distances.length * percentile); + const testMaxEdge = distances[index]; + + hull = turf.concave(pointCollection, { + maxEdge: testMaxEdge, + units: message.units || "kilometers" + }); + + if (hull) { + actualMaxEdge = testMaxEdge; + console.log(`Auto-calculated max_edge: ${testMaxEdge.toFixed(2)} ${message.units || "kilometers"}`); + break; + } + } + + // Final fallback - use convex hull if concave fails + if (!hull) { + console.warn("Concave hull failed, falling back to convex hull"); + hull = turf.convex(pointCollection); + actualMaxEdge = "convex_fallback"; + } + } + + const result = hull ? { + type: "FeatureCollection", + features: [hull] + } : { + type: "FeatureCollection", + features: [] + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "concave_hull", result, { + max_edge: message.max_edge, + units: message.units || "kilometers" + }, message.input_id); + } +} + +// Voronoi operation +function executeTurfVoronoi(map, message, widgetId) { + const inputData = getInputData(map, message); + + const options = {}; + let finalBbox = null; + let clippingData = null; + + // Handle bbox parameter + if (message.bbox) { + // Direct bbox array [minX, minY, maxX, maxY] + options.bbox = message.bbox; + finalBbox = message.bbox; + } else if (message.bbox_layer_id) { + // Extract bbox from layer + try { + const bboxSourceData = getSourceData(map, message.bbox_layer_id); + if (bboxSourceData) { + // Calculate bbox from layer data + const bbox = turf.bbox(bboxSourceData); + options.bbox = bbox; + finalBbox = bbox; + // Keep the layer data for potential intersection clipping + clippingData = bboxSourceData; + } + } catch (error) { + console.warn(`Could not extract bbox from layer ${message.bbox_layer_id}:`, error); + } + } + + let voronoi = turf.voronoi(inputData, options); + + // If we have clipping data (from bbox_layer_id), intersect each Voronoi polygon + if (voronoi && clippingData && clippingData.type === "FeatureCollection") { + const clippedFeatures = []; + + for (const voronoiFeature of voronoi.features) { + try { + // Try to intersect with each feature in the clipping layer + for (const clipFeature of clippingData.features) { + const intersection = turf.intersect(turf.featureCollection([voronoiFeature, clipFeature])); + if (intersection) { + clippedFeatures.push(intersection); + } + } + } catch (error) { + // If intersection fails, keep original feature + clippedFeatures.push(voronoiFeature); + } + } + + voronoi = { + type: "FeatureCollection", + features: clippedFeatures + }; + } + + // If property parameter is provided, use turf.collect to transfer attributes from points to polygons + if (voronoi && message.property && inputData.type === "FeatureCollection") { + try { + // Use turf.collect to gather point properties within each Voronoi polygon + const collected = turf.collect(voronoi, inputData, message.property, `${message.property}_collected`); + + // Since each Voronoi polygon should contain exactly one point, extract the single value from the array + for (const feature of collected.features) { + const collectedValues = feature.properties[`${message.property}_collected`]; + if (collectedValues && collectedValues.length > 0) { + // Take the first (and should be only) value and assign it directly to the property name + feature.properties[message.property] = collectedValues[0]; + // Remove the temporary array property + delete feature.properties[`${message.property}_collected`]; + } + } + + voronoi = collected; + } catch (error) { + console.warn(`Failed to collect property '${message.property}' from points to Voronoi polygons:`, error); + // Continue with uncollected voronoi if collection fails + } + } + + if (message.source_id && voronoi) { + addResultSource(map, voronoi, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "voronoi", voronoi, { + bbox: finalBbox, + bbox_layer_id: message.bbox_layer_id + }, message.input_id); + } +} + +// Distance operation +function executeTurfDistance(map, message, widgetId) { + let feature1, feature2; + + // Get first feature + if (message.coordinates) { + feature1 = turf.point(message.coordinates); + } else if (message.data) { + const sourceData1 = JSON.parse(message.data); + feature1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features[0] : sourceData1; + } else if (message.layer_id) { + const sourceData1 = getSourceData(map, message.layer_id); + feature1 = sourceData1.type === "FeatureCollection" ? + sourceData1.features[0] : sourceData1; + } + + // Get second feature + if (message.coordinates_2) { + feature2 = turf.point(message.coordinates_2); + } else if (message.layer_id_2) { + const sourceData2 = getSourceData(map, message.layer_id_2); + feature2 = sourceData2.type === "FeatureCollection" ? + sourceData2.features[0] : sourceData2; + } + + const distance = turf.distance(feature1, feature2, { + units: message.units || "kilometers" + }); + + if (message.input_id) { + sendResultToR(widgetId, "distance", distance, { + units: message.units || "kilometers" + }, message.input_id); + } +} + +// Area operation +function executeTurfArea(map, message, widgetId) { + const inputData = getInputData(map, message); + + const area = turf.area(inputData); + + if (message.input_id) { + sendResultToR(widgetId, "area", area, { + units: "square_meters" + }, message.input_id); + } +} + +// Centroid operation (using turf.centroid - vertex average method) +function executeTurfCentroid(map, message, widgetId) { + const inputData = getInputData(map, message); + + const centroids = []; + + // Handle both single features and FeatureCollections + const features = inputData.type === "FeatureCollection" ? inputData.features : [inputData]; + + // Calculate centroid for each individual feature using turf.centroid + for (const feature of features) { + const centroid = turf.centroid(feature); + + // Preserve all properties from the source feature + if (feature.properties) { + centroid.properties = { ...feature.properties }; + } + + centroids.push(centroid); + } + + const result = { + type: "FeatureCollection", + features: centroids + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "centroid", result, {}, message.input_id); + } +} + +// Center of Mass operation (replaces centroid for better accuracy) +function executeTurfCenterOfMass(map, message, widgetId) { + const inputData = getInputData(map, message); + + const centers = []; + + // Handle both single features and FeatureCollections + const features = inputData.type === "FeatureCollection" ? inputData.features : [inputData]; + + // Calculate center of mass for each individual feature + for (const feature of features) { + const centerOfMass = turf.centerOfMass(feature, {}); + + // Preserve all properties from the source feature + if (feature.properties) { + centerOfMass.properties = { ...feature.properties }; + } + + centers.push(centerOfMass); + } + + const result = { + type: "FeatureCollection", + features: centers + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "center_of_mass", result, {}, message.input_id); + } +} + +// Filter operation +function executeTurfFilter(map, message, widgetId) { + const sourceData = getInputData(map, message); + + // Get filter geometry data + let filterData; + if (message.filter_data) { + // Handle filter_data directly + if (typeof message.filter_data === 'string') { + filterData = JSON.parse(message.filter_data); + } else { + filterData = message.filter_data; + } + } else if (message.filter_layer_id) { + // Handle filter_layer_id as before + filterData = getSourceData(map, message.filter_layer_id); + } else { + throw new Error("Either filter_data or filter_layer_id must be provided for filter operation"); + } + + // Extract features arrays + const features = sourceData.type === "FeatureCollection" ? + sourceData.features : [sourceData]; + const filterFeatures = filterData.type === "FeatureCollection" ? + filterData.features : [filterData]; + + // Collect filtered results + const resultFeatures = []; + + features.forEach((feature, index) => { + if (!feature || !feature.geometry) { + console.warn(`Skipping invalid feature at index ${index}`); + return; + } + + // Check if this feature matches the predicate against any filter feature + let matches = false; + + for (const filterFeature of filterFeatures) { + if (!filterFeature || !filterFeature.geometry) { + continue; + } + + try { + // Handle MultiPolygon geometries for within/contains predicates + if ((feature.geometry.type === 'MultiPolygon' || filterFeature.geometry.type === 'MultiPolygon') && + (message.predicate === 'within' || message.predicate === 'contains')) { + + // MultiPolygon handling for 'within' + if (message.predicate === 'within') { + if (feature.geometry.type === 'MultiPolygon') { + // All parts of the MultiPolygon must be within the filter + const polygons = feature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: feature.properties + })); + matches = polygons.every(poly => { + try { + return turf.booleanWithin(poly, filterFeature); + } catch (e) { + return false; + } + }); + } else if (filterFeature.geometry.type === 'MultiPolygon') { + // Feature must be within at least one part of the MultiPolygon + const polygons = filterFeature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: filterFeature.properties + })); + matches = polygons.some(poly => { + try { + return turf.booleanWithin(feature, poly); + } catch (e) { + return false; + } + }); + } + } + // MultiPolygon handling for 'contains' + else if (message.predicate === 'contains') { + if (feature.geometry.type === 'MultiPolygon') { + // At least one part of the MultiPolygon must contain the filter + const polygons = feature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: feature.properties + })); + matches = polygons.some(poly => { + try { + return turf.booleanContains(poly, filterFeature); + } catch (e) { + return false; + } + }); + } else if (filterFeature.geometry.type === 'MultiPolygon') { + // Feature must be contained by at least one part of the MultiPolygon + const polygons = filterFeature.geometry.coordinates.map(coords => ({ + type: 'Feature', + geometry: { type: 'Polygon', coordinates: coords }, + properties: filterFeature.properties + })); + matches = polygons.some(poly => { + try { + return turf.booleanContains(poly, feature); + } catch (e) { + return false; + } + }); + } + } + } else { + // Use the appropriate boolean function based on predicate + switch (message.predicate) { + case "intersects": + matches = turf.booleanIntersects(feature, filterFeature); + break; + case "within": + matches = turf.booleanWithin(feature, filterFeature); + break; + case "contains": + matches = turf.booleanContains(feature, filterFeature); + break; + case "crosses": + matches = turf.booleanCrosses(feature, filterFeature); + break; + case "disjoint": + matches = turf.booleanDisjoint(feature, filterFeature); + break; + default: + console.warn(`Unknown predicate: ${message.predicate}`); + continue; + } + } + + if (matches) { + break; // Found a match, no need to check other filter features + } + } catch (error) { + console.error(`Error testing predicate ${message.predicate}:`, error); + continue; + } + } + + // If this feature matches the predicate, add it to results + if (matches) { + // Preserve all properties from the original feature + const resultFeature = { + ...feature, + properties: { ...feature.properties } + }; + resultFeatures.push(resultFeature); + } + }); + + const result = { + type: "FeatureCollection", + features: resultFeatures + }; + + if (message.source_id) { + addResultSource(map, result, message.source_id); + } + + if (message.input_id) { + sendResultToR(widgetId, "filter", result, { + predicate: message.predicate, + filtered_count: resultFeatures.length, + total_count: features.length + }, message.input_id); + } +} \ No newline at end of file diff --git a/inst/htmlwidgets/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js b/inst/htmlwidgets/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js new file mode 100644 index 0000000..207d876 --- /dev/null +++ b/inst/htmlwidgets/lib/mapbox-pmtiles/pmtiles-source-optimized-v2.js @@ -0,0 +1,1102 @@ +/** + * mapbox-pmtiles v1.1.0 - Optimized Version with Lifecycle Management + * Original source: https://github.com/am2222/mapbox-pmtiles by Majid Hojati + * License: MIT + * + * This is an optimized version of the mapbox-pmtiles library that provides + * better performance for large datasets through: + * - Configurable resource management + * - Instance-scoped worker pools and caches + * - Proper lifecycle management and cleanup + * - Reference counting for shared resources + * - Enhanced error handling and timeouts + * - Memory optimization with size-based LRU caches + * + * Last updated: 2025 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + // Global shared resources with reference counting + const GLOBAL_SHARED_RESOURCES = { + // Protocol cache - expensive to duplicate, shared with reference counting + protocolCache: new Map(), // url -> { protocol, instance, refCount } + + // Metadata cache - small and shareable + metadataCache: new Map(), // cacheKey -> data + + // Pre-calculated world sizes for common zoom levels (static, no cleanup needed) + worldSizeCache: new Array(25).fill(null).map((_, z) => Math.pow(2, z)), + + // Global cleanup registry + activeManagers: new Set(), + + // Debug/development features + debug: false, + performanceMetrics: new Map(), + }; + + /** + * Default configuration options + */ + const DEFAULT_OPTIONS = { + workerPoolSize: 4, + tileCacheSize: 1000, + tileCacheMaxMemoryMB: 100, + metadataCacheSize: 100, + enableSharedProtocols: true, + requestTimeoutMs: 30000, + enableDebugLogging: false, + enablePerformanceMetrics: false, + }; + + /** + * LRU Cache implementation with size-based eviction + */ + class LRUCache { + constructor(maxSize, maxMemoryBytes = Infinity) { + this.maxSize = maxSize; + this.maxMemoryBytes = maxMemoryBytes; + this.cache = new Map(); + this.currentMemoryBytes = 0; + } + + get(key) { + if (this.cache.has(key)) { + // Move to end (most recently used) + const value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return value.data; + } + return undefined; + } + + set(key, data, estimatedSize = 0) { + // Remove if exists + if (this.cache.has(key)) { + const existing = this.cache.get(key); + this.currentMemoryBytes -= existing.size; + this.cache.delete(key); + } + + // Evict old entries if necessary + while ( + this.cache.size >= this.maxSize || + this.currentMemoryBytes + estimatedSize > this.maxMemoryBytes + ) { + const firstKey = this.cache.keys().next().value; + if (!firstKey) break; + + const firstValue = this.cache.get(firstKey); + this.currentMemoryBytes -= firstValue.size; + this.cache.delete(firstKey); + } + + // Add new entry + this.cache.set(key, { data, size: estimatedSize }); + this.currentMemoryBytes += estimatedSize; + } + + has(key) { + return this.cache.has(key); + } + + delete(key) { + if (this.cache.has(key)) { + const value = this.cache.get(key); + this.currentMemoryBytes -= value.size; + this.cache.delete(key); + return true; + } + return false; + } + + clear() { + this.cache.clear(); + this.currentMemoryBytes = 0; + } + + get size() { + return this.cache.size; + } + + getMemoryUsage() { + return { + entries: this.cache.size, + memoryBytes: this.currentMemoryBytes, + memoryMB: this.currentMemoryBytes / (1024 * 1024), + }; + } + } + + /** + * Resource Manager - handles per-instance resources and lifecycle + */ + class PMTilesResourceManager { + constructor(options = {}) { + this.config = { ...DEFAULT_OPTIONS, ...options }; + this.destroyed = false; + this.paused = false; + this.dispatcher = null; + + // Instance-scoped resources + this.workerPool = []; + this.workerPoolIndex = 0; + this.tileCache = new LRUCache( + this.config.tileCacheSize, + this.config.tileCacheMaxMemoryMB * 1024 * 1024, + ); + this.pendingRequests = new Map(); + this.activeRequests = new Set(); + + // Performance tracking + this.metrics = { + tilesLoaded: 0, + cacheHits: 0, + cacheMisses: 0, + memoryPeakMB: 0, + averageLoadTimeMs: 0, + }; + + // Register for global cleanup + GLOBAL_SHARED_RESOURCES.activeManagers.add(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager created", this.config); + } + } + + /** + * Initialize worker pool + */ + initializeWorkerPool(dispatcher) { + if (this.destroyed) return; + + // Store dispatcher reference + if (dispatcher) { + this.dispatcher = dispatcher; + } + + if (this.workerPool.length === 0 && this.dispatcher) { + for (let i = 0; i < this.config.workerPoolSize; i++) { + try { + this.workerPool.push(this.dispatcher.getActor()); + } catch (error) { + console.warn("[PMTiles] Failed to create worker:", error); + } + } + + if (this.config.enableDebugLogging) { + console.log( + `[PMTiles] Initialized worker pool with ${this.workerPool.length} workers`, + ); + } + } + } + + /** + * Get next worker from pool (round-robin) + */ + getWorkerFromPool() { + if (this.destroyed) { + return null; + } + + // Try to initialize workers if not done yet + if (this.workerPool.length === 0 && this.dispatcher) { + this.initializeWorkerPool(this.dispatcher); + } + + if (this.workerPool.length === 0) { + if (this.config.enableDebugLogging) { + console.warn( + "[PMTiles] Worker pool is empty, dispatcher available:", + !!this.dispatcher, + ); + } + return null; + } + + const worker = this.workerPool[this.workerPoolIndex]; + this.workerPoolIndex = + (this.workerPoolIndex + 1) % this.workerPool.length; + return worker; + } + + /** + * Get or create protocol instance with reference counting + */ + getProtocol(url) { + if (this.destroyed) return null; + + if (!this.config.enableSharedProtocols) { + // Create instance-specific protocol + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + return { protocol, instance }; + } + + // Use shared protocol with reference counting + if (!GLOBAL_SHARED_RESOURCES.protocolCache.has(url)) { + const protocol = new pmtiles.Protocol(); + const instance = new pmtiles.PMTiles(url); + protocol.add(instance); + GLOBAL_SHARED_RESOURCES.protocolCache.set(url, { + protocol, + instance, + refCount: 0, + }); + } + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + cached.refCount++; + return cached; + } + + /** + * Release protocol reference + */ + releaseProtocol(url) { + if (!this.config.enableSharedProtocols) return; + + const cached = GLOBAL_SHARED_RESOURCES.protocolCache.get(url); + if (cached) { + cached.refCount--; + if (cached.refCount <= 0) { + GLOBAL_SHARED_RESOURCES.protocolCache.delete(url); + + if (this.config.enableDebugLogging) { + console.log(`[PMTiles] Released protocol for ${url}`); + } + } + } + } + + /** + * Cache key for tiles + */ + getTileCacheKey(url, z, x, y) { + return `${url}:${z}:${x}:${y}`; + } + + /** + * Add tile to cache with size estimation + */ + addToTileCache(key, data) { + if (this.destroyed) return; + + let estimatedSize = 0; + if (data instanceof ImageBitmap) { + // Rough estimation: width * height * 4 bytes per pixel + estimatedSize = data.width * data.height * 4; + } else if (data && data.byteLength) { + estimatedSize = data.byteLength; + } else { + estimatedSize = 10000; // Default estimate + } + + this.tileCache.set(key, data, estimatedSize); + + // Update peak memory usage + const memoryUsage = this.tileCache.getMemoryUsage(); + this.metrics.memoryPeakMB = Math.max( + this.metrics.memoryPeakMB, + memoryUsage.memoryMB, + ); + } + + /** + * Get cached metadata + */ + getCachedMetadata(cacheKey) { + return GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + } + + /** + * Set cached metadata + */ + setCachedMetadata(cacheKey, data) { + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, data); + } + + /** + * Pause all operations + */ + pause() { + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager paused"); + } + } + + /** + * Resume operations + */ + resume() { + this.paused = false; + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager resumed"); + } + } + + /** + * Get performance metrics + */ + getMetrics() { + return { + ...this.metrics, + tileCache: this.tileCache.getMemoryUsage(), + workerPoolSize: this.workerPool.length, + pendingRequests: this.pendingRequests.size, + isPaused: this.paused, + isDestroyed: this.destroyed, + }; + } + + /** + * Destroy and cleanup all resources + */ + destroy() { + if (this.destroyed) return; + + this.destroyed = true; + this.paused = true; + + // Cancel all pending requests + for (const [key, request] of this.pendingRequests) { + if (request.cancel) { + request.cancel(); + } + } + this.pendingRequests.clear(); + + // Clear caches + this.tileCache.clear(); + + // Clear worker pool references + this.workerPool.length = 0; + + // Remove from global registry + GLOBAL_SHARED_RESOURCES.activeManagers.delete(this); + + if (this.config.enableDebugLogging) { + console.log("[PMTiles] Resource manager destroyed", this.getMetrics()); + } + } + } + + /** + * Global cleanup function + */ + const cleanup = () => { + for (const manager of GLOBAL_SHARED_RESOURCES.activeManagers) { + manager.destroy(); + } + GLOBAL_SHARED_RESOURCES.protocolCache.clear(); + GLOBAL_SHARED_RESOURCES.metadataCache.clear(); + }; + + // Register global cleanup + if (typeof window !== "undefined") { + window.addEventListener("beforeunload", cleanup); + } + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + + // Pre-calculate mercator bounds + this._mercatorBounds = { + west: mercatorXFromLng(this.bounds.getWest()), + north: mercatorYFromLat(this.bounds.getNorth()), + east: mercatorXFromLng(this.bounds.getEast()), + south: mercatorYFromLat(this.bounds.getSouth()), + }; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + // Use pre-calculated world size + const worldSize = + GLOBAL_SHARED_RESOURCES.worldSizeCache[tileID.z] || + Math.pow(2, tileID.z); + + // Use pre-calculated mercator bounds + const level = { + minX: Math.floor(this._mercatorBounds.west * worldSize), + minY: Math.floor(this._mercatorBounds.north * worldSize), + maxX: Math.ceil(this._mercatorBounds.east * worldSize), + maxY: Math.ceil(this._mercatorBounds.south * worldSize), + }; + + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + /** + * Enhanced PMTiles Source with lifecycle management + */ + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + + // Extract PMTiles-specific options + const pmtilesOptions = { + workerPoolSize: options.workerPoolSize, + tileCacheSize: options.tileCacheSize, + tileCacheMaxMemoryMB: options.tileCacheMaxMemoryMB, + metadataCacheSize: options.metadataCacheSize, + enableSharedProtocols: options.enableSharedProtocols, + requestTimeoutMs: options.requestTimeoutMs, + enableDebugLogging: options.enableDebugLogging, + enablePerformanceMetrics: options.enablePerformanceMetrics, + }; + + // Initialize resource manager + this.resourceManager = new PMTilesResourceManager(pmtilesOptions); + + // Standard source properties + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = _dispatcher; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._implementation = options; + + // Initialize worker pool + this.resourceManager.initializeWorkerPool(_dispatcher); + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + return; + } + + const { url } = options; + this.url = url; + this.tileSize = 512; + + // Get protocol instance + this.protocolInfo = this.resourceManager.getProtocol(url); + if (!this.protocolInfo) { + this.fire( + new ErrorEvent(new Error(`Failed to create protocol for ${url}`)), + ); + return; + } + + this._protocol = this.protocolInfo.protocol; + this._instance = this.protocolInfo.instance; + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + } + + static async getMetadata(url) { + // Check cache first + const cacheKey = `${url}:metadata`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const metadata = await instance.getMetadata(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, metadata); + return metadata; + } + + static async getHeader(url) { + // Check cache first + const cacheKey = `${url}:header`; + const cached = GLOBAL_SHARED_RESOURCES.metadataCache.get(cacheKey); + if (cached) { + return cached; + } + + const instance = new pmtiles.PMTiles(url); + const header = await instance.getHeader(); + GLOBAL_SHARED_RESOURCES.metadataCache.set(cacheKey, header); + return header; + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (this.resourceManager.destroyed) return; + + if (!tile.destroy) { + tile.destroy = () => {}; + } + if (!tile.abort) { + tile.abort = () => { + tile.aborted = true; + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + }; + } + } + + /** + * Pause tile loading + */ + pause() { + this.resourceManager.pause(); + } + + /** + * Resume tile loading + */ + resume() { + this.resourceManager.resume(); + } + + /** + * Get performance metrics + */ + getMetrics() { + return this.resourceManager.getMetrics(); + } + + /** + * Destroy source and cleanup resources + */ + destroy() { + if (this.protocolInfo && this.url) { + this.resourceManager.releaseProtocol(this.url); + } + + this.resourceManager.destroy(); + this._loaded = false; + } + + async load(callback) { + if (this.resourceManager.destroyed) { + const error = new Error("Source has been destroyed"); + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + // Check metadata cache first + const headerKey = `${this.url}:header`; + const metadataKey = `${this.url}:metadata`; + + let header, tileJSON; + + const cachedHeader = this.resourceManager.getCachedMetadata(headerKey); + const cachedMetadata = + this.resourceManager.getCachedMetadata(metadataKey); + + if (cachedHeader && cachedMetadata) { + header = cachedHeader; + tileJSON = cachedMetadata; + } else { + try { + // Load and cache + [header, tileJSON] = await Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]); + this.resourceManager.setCachedMetadata(headerKey, header); + this.resourceManager.setCachedMetadata(metadataKey, tileJSON); + } catch (error) { + this.fire(new ErrorEvent(error)); + if (callback) callback(error); + return; + } + } + + try { + extend(this, tileJSON); + this.header = header; + const { tileType, minZoom, maxZoom, minLon, minLat, maxLon, maxLat } = + header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes(this.tileType) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { dataType: "source", sourceDataType: "metadata" }), + ); + this.fire( + new Event("data", { dataType: "source", sourceDataType: "content" }), + ); + } catch (err2) { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + } + } + + loaded() { + return this._loaded && !this.resourceManager.destroyed; + } + + loadVectorTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + const startTime = Date.now(); + var _a2, _b2, _c; + + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + + // Update metrics + this.resourceManager.metrics.tilesLoaded++; + const loadTime = Date.now() - startTime; + this.resourceManager.metrics.averageLoadTimeMs = + (this.resourceManager.metrics.averageLoadTimeMs + loadTime) / 2; + + if (tile.aborted) return callback(null); + + // Handle abort errors gracefully + if (err2 && err2.name === "AbortError") { + return callback(null); + } + + if (err2 && err2.status !== 404) { + return callback(err2); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + // Handle abort errors gracefully + if (error && (error.name === "AbortError" || error.code === 20)) { + return done.call(this, null); + } + done.call(this, error); + return; + } + + params.data = { + cacheControl, + expires, + rawData: data, + }; + + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + // Use shared worker pool + tile.actor = this.resourceManager.getWorkerFromPool(); + + // Fallback to dispatcher if worker pool failed + if (!tile.actor && this.dispatcher) { + try { + tile.actor = this.dispatcher.getActor(); + } catch (error) { + console.warn("[PMTiles] Failed to get fallback worker:", error); + return callback(new Error("No workers available")); + } + } + + if (!tile.actor) { + return callback(new Error("No workers available")); + } + + // Create request with timeout + const requestPromise = this._protocol.tile({ ...request }, afterLoad); + + // Add timeout if configured + if (this.resourceManager.config.requestTimeoutMs > 0) { + const timeoutId = setTimeout(() => { + if (tile.request && tile.request.cancel) { + tile.request.cancel(); + } + done.call(this, new Error("Request timeout")); + }, this.resourceManager.config.requestTimeoutMs); + + const originalCancel = requestPromise.cancel; + requestPromise.cancel = () => { + clearTimeout(timeoutId); + if (originalCancel) originalCancel(); + }; + } + + tile.request = requestPromise; + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + if (this.resourceManager.destroyed) return; + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + if (this.resourceManager.destroyed || this.resourceManager.paused) { + return callback(null); + } + + var _a2, _b2; + + // Check tile cache first + const cacheKey = this.resourceManager.getTileCacheKey( + this.url, + tile.tileID.canonical.z, + tile.tileID.canonical.x, + tile.tileID.canonical.y, + ); + + if (this.resourceManager.tileCache.has(cacheKey)) { + this.resourceManager.metrics.cacheHits++; + const cachedData = this.resourceManager.tileCache.get(cacheKey); + this.loadRasterTileData(tile, cachedData); + tile.state = "loaded"; + return callback(null); + } + + this.resourceManager.metrics.cacheMisses++; + + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + + // Optimized raster tile loading - try direct ArrayBuffer first + const arrayBuffer = data.buffer || data; + window + .createImageBitmap(arrayBuffer) + .then((imageBitmap) => { + // Cache the decoded image + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + // Fallback to blob method + const blob = new window.Blob([new Uint8Array(data)], { + type: this.contentType, + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.resourceManager.addToTileCache(cacheKey, imageBitmap); + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error(`Can't decode image for ${this.id}: ${error}`), + ); + }); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + + this.fixTile(tile); + const controller = new AbortController(); + + // Add timeout if configured + let timeoutId; + if (this.resourceManager.config.requestTimeoutMs > 0) { + timeoutId = setTimeout(() => { + controller.abort(); + }, this.resourceManager.config.requestTimeoutMs); + } + + tile.request = { + cancel: () => { + if (timeoutId) clearTimeout(timeoutId); + controller.abort(); + }, + }; + + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (timeoutId) clearTimeout(timeoutId); + + // Handle abort errors gracefully + if (error.name === "AbortError" || error.code === 20) { + delete tile.request; + return callback(null); + } + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Expose cleanup function + PmTilesSource.cleanup = cleanup; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; + global.PMTilesResourceManager = PMTilesResourceManager; +})(typeof window !== "undefined" ? window : this); diff --git a/inst/htmlwidgets/lib/mapbox-pmtiles/pmtiles-source.js b/inst/htmlwidgets/lib/mapbox-pmtiles/pmtiles-source.js new file mode 100644 index 0000000..2130749 --- /dev/null +++ b/inst/htmlwidgets/lib/mapbox-pmtiles/pmtiles-source.js @@ -0,0 +1,459 @@ +/** + * mapbox-pmtiles v1.0.53 + * Original source: https://github.com/am2222/mapbox-pmtiles + * License: MIT + * + * This is a vendored copy of the mapbox-pmtiles library that provides + * PMTiles support for Mapbox GL JS by implementing a custom source type. + * + * Last updated: 2024 + */ + +// Note: This version assumes mapboxgl and pmtiles are already loaded as globals +(function (global) { + "use strict"; + + // Helper functions + var __pow = Math.pow; + var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x2) => + x2.done + ? resolve(x2.value) + : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); + }; + + // Check dependencies + if (typeof mapboxgl === "undefined") { + console.error("mapbox-pmtiles: Mapbox GL JS is not loaded"); + return; + } + if (typeof pmtiles === "undefined") { + console.error("mapbox-pmtiles: PMTiles library is not loaded"); + return; + } + + const VectorTileSourceImpl = mapboxgl.Style.getSourceType("vector"); + const SOURCE_TYPE = "pmtile-source"; + + const extend = (dest, ...sources) => { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; + }; + + const mercatorXFromLng = (lng) => { + return (180 + lng) / 360; + }; + + const mercatorYFromLat = (lat) => { + return ( + (180 - + (180 / Math.PI) * + Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360))) / + 360 + ); + }; + + class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = mapboxgl.LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + } + + validateBounds(bounds) { + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [ + Math.max(-180, bounds[0]), + Math.max(-90, bounds[1]), + Math.min(180, bounds[2]), + Math.min(90, bounds[3]), + ]; + } + + contains(tileID) { + const worldSize = Math.pow(2, tileID.z); + const level = { + minX: Math.floor(mercatorXFromLng(this.bounds.getWest()) * worldSize), + minY: Math.floor(mercatorYFromLat(this.bounds.getNorth()) * worldSize), + maxX: Math.ceil(mercatorXFromLng(this.bounds.getEast()) * worldSize), + maxY: Math.ceil(mercatorYFromLat(this.bounds.getSouth()) * worldSize), + }; + const hit = + tileID.x >= level.minX && + tileID.x < level.maxX && + tileID.y >= level.minY && + tileID.y < level.maxY; + return hit; + } + } + + class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } + } + + class ErrorEvent extends Event { + constructor(error, data = {}) { + super("error", extend({ error }, data)); + } + } + + class PmTilesSource extends VectorTileSourceImpl { + constructor(id, options, _dispatcher, _eventedParent) { + super(...[id, options, _dispatcher, _eventedParent]); + this.scheme = "xyz"; + this.roundZoom = true; + this.type = "vector"; + this.dispatcher = void 0; + this.reparseOverscaled = true; + this._loaded = false; + this._dataType = "vector"; + this.id = id; + this._dataType = "vector"; + this.dispatcher = _dispatcher; + this._implementation = options; + + if (!this._implementation) { + this.fire( + new ErrorEvent( + new Error(`Missing options for ${this.id} ${SOURCE_TYPE} source`), + ), + ); + } + + const { url } = options; + this.reparseOverscaled = true; + this.scheme = "xyz"; + this.tileSize = 512; + this._loaded = false; + this.type = "vector"; + this._protocol = new pmtiles.Protocol(); + this.tiles = [`pmtiles://${url}/{z}/{x}/{y}`]; + const pmtilesInstance = new pmtiles.PMTiles(url); + this._protocol.add(pmtilesInstance); + this._instance = pmtilesInstance; + } + + static async getMetadata(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getMetadata(); + } + + static async getHeader(url) { + const instance = new pmtiles.PMTiles(url); + return instance.getHeader(); + } + + getExtent() { + if (!this.header) + return [ + [-180, -90], + [180, 90], + ]; + const { minLon, minLat, maxLon, maxLat } = this.header; + return [minLon, minLat, maxLon, maxLat]; + } + + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + fixTile(tile) { + if (!tile.destroy) { + tile.destroy = () => {}; + } + } + + async load(callback) { + this._loaded = false; + this.fire(new Event("dataloading", { dataType: "source" })); + + return Promise.all([ + this._instance.getHeader(), + this._instance.getMetadata(), + ]) + .then(([header, tileJSON]) => { + extend(this, tileJSON); + this.header = header; + const { + specVersion, + clustered, + tileType, + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + centerZoom, + centerLon, + centerLat, + } = header; + const requiredVariables = [ + minZoom, + maxZoom, + minLon, + minLat, + maxLon, + maxLat, + ]; + + if ( + !requiredVariables.includes(void 0) && + !requiredVariables.includes(null) + ) { + this.tileBounds = new TileBounds( + [minLon, minLat, maxLon, maxLat], + minZoom, + maxZoom, + ); + this.minzoom = minZoom; + this.maxzoom = maxZoom; + } + + if (this.maxzoom == void 0) { + console.warn( + "The maxzoom parameter is not defined in the source json. This can cause memory leak. So make sure to define maxzoom in the layer", + ); + } + + this.minzoom = Number.parseInt(this.minzoom.toString()) || 0; + this.maxzoom = Number.parseInt(this.maxzoom.toString()) || 0; + this._loaded = true; + this.tileType = tileType; + + switch (tileType) { + case pmtiles.TileType.Png: + this.contentType = "image/png"; + break; + case pmtiles.TileType.Jpeg: + this.contentType = "image/jpeg"; + break; + case pmtiles.TileType.Webp: + this.contentType = "image/webp"; + break; + case pmtiles.TileType.Avif: + this.contentType = "image/avif"; + break; + case pmtiles.TileType.Mvt: + this.contentType = "application/vnd.mapbox-vector-tile"; + break; + } + + if ( + [pmtiles.TileType.Jpeg, pmtiles.TileType.Png].includes( + this.tileType, + ) + ) { + this.loadTile = this.loadRasterTile; + this.type = "raster"; + } else if (this.tileType === pmtiles.TileType.Mvt) { + this.loadTile = this.loadVectorTile; + this.type = "vector"; + } else { + this.fire(new ErrorEvent(new Error("Unsupported Tile Type"))); + } + + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "metadata", + }), + ); + this.fire( + new Event("data", { + dataType: "source", + sourceDataType: "content", + }), + ); + }) + .catch((err2) => { + this.fire(new ErrorEvent(err2)); + if (callback) callback(err2); + }); + } + + loaded() { + return this._loaded; + } + + loadVectorTile(tile, callback) { + var _a2, _b2, _c; + const done = (err2, data) => { + var _a3, _b3; + delete tile.request; + if (tile.aborted) return callback(null); + if (err2 && err2.status !== 404) { + return callback(err2); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if ( + ((_a3 = this.map) == null ? void 0 : _a3._refreshExpiredTiles) && + data + ) + tile.setExpiryData(data); + tile.loadVectorData( + data, + (_b3 = this.map) == null ? void 0 : _b3.painter, + ); + callback(null); + if (tile.reloadCallback) { + this.loadVectorTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + const params = { + request, + data: {}, + uid: tile.uid, + tileID: tile.tileID, + tileZoom: tile.tileZoom, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: "vector", + source: this.id, + scope: this.scope, + showCollisionBoxes: + (_c = this.map) == null ? void 0 : _c.showCollisionBoxes, + promoteId: this.promoteId, + isSymbolTile: tile.isSymbolTile, + extraShadowCaster: tile.isExtraShadowCaster, + }; + + const afterLoad = (error, data, cacheControl, expires) => { + if (error || !data) { + done.call(this, error); + return; + } + params.data = { + cacheControl, + expires, + rawData: data, + }; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + if (tile.actor) + tile.actor.send("loadTile", params, done.bind(this), void 0, true); + }; + + this.fixTile(tile); + if (!tile.actor || tile.state === "expired") { + tile.actor = this._tileWorkers[url] = + this._tileWorkers[url] || this.dispatcher.getActor(); + tile.request = this._protocol.tile({ ...request }, afterLoad); + } else if (tile.state === "loading") { + tile.reloadCallback = callback; + } else { + tile.request = this._protocol.tile({ ...tile, url }, afterLoad); + } + } + + loadRasterTileData(tile, data) { + tile.setTexture(data, this.map.painter); + } + + loadRasterTile(tile, callback) { + var _a2, _b2; + const done = ({ data, cacheControl, expires }) => { + delete tile.request; + if (tile.aborted) return callback(null); + if (data === null || data === void 0) { + const emptyImage = { + width: this.tileSize, + height: this.tileSize, + data: null, + }; + this.loadRasterTileData(tile, emptyImage); + tile.state = "loaded"; + return callback(null); + } + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + if (this.map._refreshExpiredTiles) + tile.setExpiryData({ cacheControl, expires }); + const blob = new window.Blob([new Uint8Array(data)], { + type: "image/png", + }); + window + .createImageBitmap(blob) + .then((imageBitmap) => { + this.loadRasterTileData(tile, imageBitmap); + tile.state = "loaded"; + callback(null); + }) + .catch((error) => { + tile.state = "errored"; + return callback( + new Error( + `Can't infer data type for ${this.id}, only raster data supported at the moment. ${error}`, + ), + ); + }); + }; + + const url = + (_a2 = this.map) == null + ? void 0 + : _a2._requestManager.normalizeTileURL( + tile.tileID.canonical.url(this.tiles, this.scheme), + ); + const request = + (_b2 = this.map) == null + ? void 0 + : _b2._requestManager.transformRequest(url, "Tile"); + this.fixTile(tile); + const controller = new AbortController(); + tile.request = { cancel: () => controller.abort() }; + this._protocol + .tile(request, controller) + .then(done.bind(this)) + .catch((error) => { + if (error.code === 20) return; + tile.state = "errored"; + callback(error); + }); + } + } + + PmTilesSource.SOURCE_TYPE = SOURCE_TYPE; + + // Export to global scope + global.MapboxPmTilesSource = PmTilesSource; + global.PMTILES_SOURCE_TYPE = SOURCE_TYPE; +})(typeof window !== "undefined" ? window : this); diff --git a/inst/htmlwidgets/lib/maptiler-geocoding-control/LICENSE.txt b/inst/htmlwidgets/lib/maptiler-geocoding-control/LICENSE.txt new file mode 100644 index 0000000..624d1f1 --- /dev/null +++ b/inst/htmlwidgets/lib/maptiler-geocoding-control/LICENSE.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2023, MapTiler +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/inst/htmlwidgets/lib/maptiler-geocoding-control/maplibregl.umd.js b/inst/htmlwidgets/lib/maptiler-geocoding-control/maplibregl.umd.js new file mode 100644 index 0000000..0fe7116 --- /dev/null +++ b/inst/htmlwidgets/lib/maptiler-geocoding-control/maplibregl.umd.js @@ -0,0 +1,14 @@ +(function(j,ee){typeof exports=="object"&&typeof module<"u"?ee(exports,require("maplibre-gl")):typeof define=="function"&&define.amd?define(["exports","maplibre-gl"],ee):(j=typeof globalThis<"u"?globalThis:j||self,ee(j.maplibreglMaptilerGeocoder={},j.maplibregl))})(this,function(j,ee){"use strict";var Ws=Object.defineProperty;var bn=j=>{throw TypeError(j)};var Gs=(j,ee,me)=>ee in j?Ws(j,ee,{enumerable:!0,configurable:!0,writable:!0,value:me}):j[ee]=me;var A=(j,ee,me)=>Gs(j,typeof ee!="symbol"?ee+"":ee,me),wn=(j,ee,me)=>ee.has(j)||bn("Cannot "+me);var ue=(j,ee,me)=>(wn(j,ee,"read from private field"),me?me.call(j):ee.get(j)),Vt=(j,ee,me)=>ee.has(j)?bn("Cannot add the same private member more than once"):ee instanceof WeakSet?ee.add(j):ee.set(j,me),kt=(j,ee,me,dt)=>(wn(j,ee,"write to private field"),dt?dt.call(j,me):ee.set(j,me),me);var fn,cn;function me(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const dt=me(ee);function ne(){}function Ln(i,e){for(const t in e)i[t]=e[t];return i}function yi(i){return i()}function vi(){return Object.create(null)}function Ue(i){i.forEach(yi)}function bi(i){return typeof i=="function"}function Ke(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}let Rt;function ye(i,e){return i===e?!0:(Rt||(Rt=document.createElement("a")),Rt.href=e,i===Rt.href)}function _n(i){return Object.keys(i).length===0}function Sn(i,e,t,n){if(i){const r=wi(i,e,t,n);return i[0](r)}}function wi(i,e,t,n){return i[1]&&n?Ln(t.ctx.slice(),i[1](n(e))):t.ctx}function xn(i,e,t,n){return i[2],e.dirty}function Tn(i,e,t,n,r,u){if(r){const a=wi(e,t,n,u);i.p(a,r)}}function Mn(i){if(i.ctx.length>32){const e=[],t=i.ctx.length/32;for(let n=0;ni.removeEventListener(e,t,n)}function Nn(i){return function(e){return e.preventDefault(),i.call(this,e)}}function S(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function kn(i){return Array.from(i.childNodes)}function gt(i,e){e=""+e,i.data!==e&&(i.data=e)}function Ei(i,e){i.value=e??""}function Ie(i,e,t){i.classList.toggle(e,!!t)}function On(i,e,{bubbles:t=!1,cancelable:n=!1}={}){return new CustomEvent(i,{detail:e,bubbles:t,cancelable:n})}let mt;function pt(i){mt=i}function Li(){if(!mt)throw new Error("Function called outside component initialization");return mt}function Rn(i){Li().$$.on_destroy.push(i)}function _i(){const i=Li();return(e,t,{cancelable:n=!1}={})=>{const r=i.$$.callbacks[e];if(r){const u=On(e,t,{cancelable:n});return r.slice().forEach(a=>{a.call(i,u)}),!u.defaultPrevented}return!0}}function Pn(i,e){const t=i.$$.callbacks[e.type];t&&t.slice().forEach(n=>n.call(this,e))}const ut=[],Yt=[];let at=[];const Si=[],In=Promise.resolve();let Qt=!1;function An(){Qt||(Qt=!0,In.then(xi))}function Xt(i){at.push(i)}const Jt=new Set;let ft=0;function xi(){if(ft!==0)return;const i=mt;do{try{for(;fti.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),at=e}const It=new Set;let nt;function yt(){nt={r:0,c:[],p:nt}}function vt(){nt.r||Ue(nt.c),nt=nt.p}function re(i,e){i&&i.i&&(It.delete(i),i.i(e))}function fe(i,e,t,n){if(i&&i.o){if(It.has(i))return;It.add(i),nt.c.push(()=>{It.delete(i),n&&(t&&i.d(1),n())}),i.o(e)}else n&&n()}function Ti(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function Gn(i,e){fe(i,1,1,()=>{e.delete(i.key)})}function Dn(i,e,t,n,r,u,a,o,g,c,E,_){let M=i.length,R=u.length,k=M;const I={};for(;k--;)I[i[k].key]=k;const C=[],O=new Map,x=new Map,N=[];for(k=R;k--;){const W=_(r,u,k),s=t(W);let l=a.get(s);l?N.push(()=>l.p(W,e)):(l=c(s,W),l.c()),O.set(s,C[k]=l),s in I&&x.set(s,Math.abs(k-I[s]))}const P=new Set,B=new Set;function z(W){re(W,1),W.m(o,E),a.set(W.key,W),E=W.first,R--}for(;M&&R;){const W=C[R-1],s=i[M-1],l=W.key,f=s.key;W===s?(E=W.first,M--,R--):O.has(f)?!a.has(l)||P.has(l)?z(W):B.has(f)?M--:x.get(l)>x.get(f)?(B.add(l),z(W)):(P.add(f),M--):(g(s,a),M--)}for(;M--;){const W=i[M];O.has(W.key)||g(W,a)}for(;R;)z(C[R-1]);return Ue(N),C}function Qe(i){i&&i.c()}function qe(i,e,t){const{fragment:n,after_update:r}=i.$$;n&&n.m(e,t),Xt(()=>{const u=i.$$.on_mount.map(yi).filter(bi);i.$$.on_destroy?i.$$.on_destroy.push(...u):Ue(u),i.$$.on_mount=[]}),r.forEach(Xt)}function Fe(i,e){const t=i.$$;t.fragment!==null&&(Wn(t.after_update),Ue(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function zn(i,e){i.$$.dirty[0]===-1&&(ut.push(i),An(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<{const k=R.length?R[0]:M;return c.ctx&&r(c.ctx[_],c.ctx[_]=k)&&(!c.skip_bound&&c.bound[_]&&c.bound[_](k),E&&zn(i,_)),M}):[],c.update(),E=!0,Ue(c.before_update),c.fragment=n?n(c.ctx):!1,e.target){if(e.hydrate){const _=kn(e.target);c.fragment&&c.fragment.l(_),_.forEach($)}else c.fragment&&c.fragment.c();e.intro&&re(i.$$.fragment),qe(i,e.target,e.anchor),xi()}pt(g)}class Je{constructor(){A(this,"$$");A(this,"$$set")}$destroy(){Fe(this,1),this.$destroy=ne}$on(e,t){if(!bi(t))return ne;const n=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return n.push(t),()=>{const r=n.indexOf(t);r!==-1&&n.splice(r,1)}}$set(e){this.$$set&&!_n(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Un="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Un);function qn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M13.12.706a.982.982 0 0 0-1.391 0L6.907 5.517 2.087.696a.982.982 0 1 0-1.391 1.39l4.821 4.821L.696 11.73a.982.982 0 1 0 1.39 1.39l4.821-4.821 4.822 4.821a.982.982 0 1 0 1.39-1.39L8.298 6.908l4.821-4.822a.988.988 0 0 0 0-1.38Z"),S(e,"viewBox","0 0 14 14"),S(e,"width","13"),S(e,"height","13"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Mi extends Je{constructor(e){super(),Xe(this,e,null,qn,Ke,{})}}function Fn(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M15 0C6.705 0 0 6.705 0 15C0 23.295 6.705 30 15 30C23.295 30 30 23.295 30 15C30 6.705 23.295 0 15 0ZM22.5 20.385L20.385 22.5L15 17.115L9.615 22.5L7.5 20.385L12.885 15L7.5 9.615L9.615 7.5L15 12.885L20.385 7.5L22.5 9.615L17.115 15L22.5 20.385Z"),S(e,"viewBox","0 0 30 30"),S(e,"fill","none"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"class","svelte-d2loi5")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class Ci extends Je{constructor(e){super(),Xe(this,e,null,Fn,Ke,{})}}function jn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"area.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"area.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Zn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"reverse.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"reverse.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Hn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"poi.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"poi.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Vn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"postal_code.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"postal_code.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Kn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"street.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"street.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Yn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"road.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"road.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Qn(i){let e,t;return{c(){e=Y("img"),ye(e.src,t=i[3]+"housenumber.svg")||S(e,"src",t),S(e,"alt",i[7]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(n,r){te(n,e,r)},p(n,r){r&8&&!ye(e.src,t=n[3]+"housenumber.svg")&&S(e,"src",t),r&128&&S(e,"alt",n[7]),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Xn(i){let e,t,n,r;return{c(){e=Y("img"),ye(e.src,t=i[5])||S(e,"src",t),S(e,"alt",i[4]),S(e,"title",i[7]),S(e,"class","svelte-w9y5n9")},m(u,a){te(u,e,a),n||(r=he(e,"error",i[14]),n=!0)},p(u,a){a&32&&!ye(e.src,t=u[5])&&S(e,"src",t),a&16&&S(e,"alt",u[4]),a&128&&S(e,"title",u[7])},d(u){u&&$(e),n=!1,r()}}}function Jn(i){let e,t;return{c(){e=Y("div"),S(e,"class","sprite-icon svelte-w9y5n9"),S(e,"style",t=` + width: ${i[6].width/xe}px; + height: ${i[6].height/xe}px; + background-image: url(${i[3]}sprite${$t}.png); + background-position: -${i[6].x/xe}px -${i[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `),S(e,"title",i[7])},m(n,r){te(n,e,r)},p(n,r){r&72&&t!==(t=` + width: ${n[6].width/xe}px; + height: ${n[6].height/xe}px; + background-image: url(${n[3]}sprite${$t}.png); + background-position: -${n[6].x/xe}px -${n[6].y/xe}px; + background-size: ${Oe.width/xe}px ${Oe.height/xe}px; + `)&&S(e,"style",t),r&128&&S(e,"title",n[7])},d(n){n&&$(e)}}}function Ni(i){let e,t;return{c(){e=Y("span"),t=Ye(i[7]),S(e,"class","secondary svelte-w9y5n9")},m(n,r){te(n,e,r),V(e,t)},p(n,r){r&128&>(t,n[7])},d(n){n&&$(e)}}}function $n(i){let e,t,n,r,u,a,o,g,c,E=(i[8]?i[0].place_name:i[0].place_name.replace(/,.*/,""))+"",_,M,R=i[2]==="always"||i[2]!=="never"&&!i[0].address&&!i[0].id.startsWith("road.")&&!i[0].id.startsWith("address.")&&!i[0].id.startsWith("postal_code.")&&(!i[0].id.startsWith("poi.")||!i[5])&&!i[8],k,I,C=(i[8]?"":i[0].place_name.replace(/[^,]*,?\s*/,""))+"",O,x,N,P,B,z;function W(m,h){return h&1&&(t=null),h&1&&(n=null),h&1&&(r=null),h&1&&(u=null),Oe&&m[6]?Jn:m[5]?Xn:m[0].address?Qn:(t==null&&(t=!!m[0].id.startsWith("road.")),t?Yn:(n==null&&(n=!!m[0].id.startsWith("address.")),n?Kn:(r==null&&(r=!!m[0].id.startsWith("postal_code.")),r?Vn:(u==null&&(u=!!m[0].id.startsWith("poi.")),u?Hn:m[8]?Zn:jn))))}let s=W(i,-1),l=s(i),f=R&&Ni(i);return{c(){e=Y("li"),l.c(),a=we(),o=Y("span"),g=Y("span"),c=Y("span"),_=Ye(E),M=we(),f&&f.c(),k=we(),I=Y("span"),O=Ye(C),S(c,"class","primary svelte-w9y5n9"),S(g,"class","svelte-w9y5n9"),S(I,"class","line2 svelte-w9y5n9"),S(o,"class","texts svelte-w9y5n9"),S(e,"tabindex","-1"),S(e,"role","option"),S(e,"aria-selected",x=i[1]==="selected"),S(e,"aria-checked",N=i[1]==="picked"),S(e,"class",P=Pt(i[1])+" svelte-w9y5n9")},m(m,h){te(m,e,h),l.m(e,null),V(e,a),V(e,o),V(o,g),V(g,c),V(c,_),V(g,M),f&&f.m(g,null),V(o,k),V(o,I),V(I,O),B||(z=[he(e,"mouseenter",i[13]),he(e,"focus",i[15]),he(e,"click",i[16])],B=!0)},p(m,[h]){s===(s=W(m,h))&&l?l.p(m,h):(l.d(1),l=s(m),l&&(l.c(),l.m(e,a))),h&257&&E!==(E=(m[8]?m[0].place_name:m[0].place_name.replace(/,.*/,""))+"")&>(_,E),h&293&&(R=m[2]==="always"||m[2]!=="never"&&!m[0].address&&!m[0].id.startsWith("road.")&&!m[0].id.startsWith("address.")&&!m[0].id.startsWith("postal_code.")&&(!m[0].id.startsWith("poi.")||!m[5])&&!m[8]),R?f?f.p(m,h):(f=Ni(m),f.c(),f.m(g,null)):f&&(f.d(1),f=null),h&257&&C!==(C=(m[8]?"":m[0].place_name.replace(/[^,]*,?\s*/,""))+"")&>(O,C),h&2&&x!==(x=m[1]==="selected")&&S(e,"aria-selected",x),h&2&&N!==(N=m[1]==="picked")&&S(e,"aria-checked",N),h&2&&P!==(P=Pt(m[1])+" svelte-w9y5n9")&&S(e,"class",P)},i:ne,o:ne,d(m){m&&$(e),l.d(),f&&f.d(),B=!1,Ue(z)}}}const ki=typeof devicePixelRatio>"u"?1:devicePixelRatio>1.25,$t=ki?"@2x":"",xe=ki?2:1;let Oe,At;function er(i,e,t){let n,r,u,{feature:a}=e,{style:o="default"}=e,{showPlaceType:g}=e,{missingIconsCache:c}=e,{iconsBaseUrl:E}=e;const _=_i();let M,R,k,I;function C(){At??(At=fetch(`${E}sprite${$t}.json`).then(s=>s.json()).then(s=>{Oe=s}).catch(()=>{Oe=null}))}function O(){R&&c.add(R),x()}function x(){Oe!==void 0?N():(C(),At==null||At.then(N))}function N(){do{if(I--,t(4,M=n==null?void 0:n[I]),t(6,k=M?Oe==null?void 0:Oe.icons[M]:void 0),k)break;t(5,R=M?E+M.replace(/ /g,"_")+".svg":void 0)}while(I>-1&&(!R||c.has(R)))}function P(s){Pn.call(this,i,s)}const B=()=>O(),z=()=>_("select",void 0),W=s=>{document.activeElement!==s.target&&_("select",void 0)};return i.$$set=s=>{"feature"in s&&t(0,a=s.feature),"style"in s&&t(1,o=s.style),"showPlaceType"in s&&t(2,g=s.showPlaceType),"missingIconsCache"in s&&t(11,c=s.missingIconsCache),"iconsBaseUrl"in s&&t(3,E=s.iconsBaseUrl)},i.$$.update=()=>{var s,l,f,m,h;i.$$.dirty&1&&t(12,n=(s=a.properties)==null?void 0:s.categories),i.$$.dirty&1&&t(8,r=a.place_type[0]==="reverse"),i.$$.dirty&1&&t(7,u=((f=(l=a.properties)==null?void 0:l.categories)==null?void 0:f.join(", "))??((h=(m=a.properties)==null?void 0:m.place_type_name)==null?void 0:h[0])??a.place_type[0]),i.$$.dirty&4096&&(I=(n==null?void 0:n.length)??0,x())},[a,o,g,E,M,R,k,u,r,_,O,c,n,P,B,z,W]}class tr extends Je{constructor(e){super(),Xe(this,e,er,$n,Ke,{feature:0,style:1,showPlaceType:2,missingIconsCache:11,iconsBaseUrl:3})}}function ir(i){let e;return{c(){e=Y("div"),e.innerHTML='',S(e,"class","svelte-1ocfouu")},m(t,n){te(t,e,n)},p:ne,i:ne,o:ne,d(t){t&&$(e)}}}class nr extends Je{constructor(e){super(),Xe(this,e,null,ir,Ke,{})}}function rr(i){let e,t,n;return{c(){e=ke("svg"),t=ke("path"),S(t,"stroke-width","4"),S(t,"d","M 5,33.103579 C 5,17.607779 18.457,5 35,5 C 51.543,5 65,17.607779 65,33.103579 C 65,56.388679 40.4668,76.048179 36.6112,79.137779 C 36.3714,79.329879 36.2116,79.457979 36.1427,79.518879 C 35.8203,79.800879 35.4102,79.942779 35,79.942779 C 34.5899,79.942779 34.1797,79.800879 33.8575,79.518879 C 33.7886,79.457979 33.6289,79.330079 33.3893,79.138079 C 29.5346,76.049279 5,56.389379 5,33.103579 Z M 35.0001,49.386379 C 43.1917,49.386379 49.8323,42.646079 49.8323,34.331379 C 49.8323,26.016779 43.1917,19.276479 35.0001,19.276479 C 26.8085,19.276479 20.1679,26.016779 20.1679,34.331379 C 20.1679,42.646079 26.8085,49.386379 35.0001,49.386379 Z"),S(t,"class","svelte-gzo3ar"),S(e,"width",n=i[0]==="list"?20:void 0),S(e,"viewBox","0 0 70 85"),S(e,"fill","none"),S(e,"class","svelte-gzo3ar"),Ie(e,"in-map",i[0]!=="list"),Ie(e,"list-icon",i[0]==="list")},m(r,u){te(r,e,u),V(e,t)},p(r,[u]){u&1&&n!==(n=r[0]==="list"?20:void 0)&&S(e,"width",n),u&1&&Ie(e,"in-map",r[0]!=="list"),u&1&&Ie(e,"list-icon",r[0]==="list")},i:ne,o:ne,d(r){r&&$(e)}}}function sr(i,e,t){let{displayIn:n}=e;return i.$$set=r=>{"displayIn"in r&&t(0,n=r.displayIn)},[n]}class or extends Je{constructor(e){super(),Xe(this,e,sr,rr,Ke,{displayIn:0})}}function lr(i){let e,t;return{c(){e=ke("svg"),t=ke("path"),S(t,"d","M30.003-26.765C13.46-26.765 0-14.158 0 1.337c0 23.286 24.535 42.952 28.39 46.04.24.192.402.316.471.376.323.282.732.424 1.142.424.41 0 .82-.142 1.142-.424.068-.06.231-.183.471-.376 3.856-3.09 28.39-22.754 28.39-46.04 0-15.495-13.46-28.102-30.003-28.102Zm1.757 12.469c4.38 0 7.858 1.052 10.431 3.158 2.595 2.105 3.89 4.913 3.89 8.422 0 2.34-.53 4.362-1.593 6.063-1.063 1.702-3.086 3.616-6.063 5.742-2.042 1.51-3.337 2.659-3.89 3.446-.532.787-.8 1.82-.8 3.096v1.914h-8.449V15.18c0-2.041.434-3.815 1.306-5.325.872-1.51 2.467-3.118 4.785-4.82 2.233-1.594 3.7-2.89 4.402-3.889a5.582 5.582 0 0 0 1.087-3.35c0-1.382-.51-2.435-1.531-3.158-1.02-.723-2.45-1.087-4.28-1.087-3.19 0-6.826 1.047-10.91 3.131l-3.472-6.986c4.742-2.659 9.77-3.992 15.087-3.992Zm-1.88 37.324c1.765 0 3.124.472 4.08 1.408.98.936 1.47 2.276 1.47 4.02 0 1.68-.49 3.007-1.47 3.985-.977.957-2.336 1.435-4.08 1.435-1.787 0-3.171-.465-4.15-1.4-.978-.958-1.47-2.298-1.47-4.02 0-1.787.48-3.14 1.436-4.054.957-.915 2.355-1.374 4.184-1.374Z"),S(e,"viewBox","0 0 60.006 21.412"),S(e,"width","14"),S(e,"height","20"),S(e,"class","svelte-en2qvf")},m(n,r){te(n,e,r),V(e,t)},p:ne,i:ne,o:ne,d(n){n&&$(e)}}}class ur extends Je{constructor(e){super(),Xe(this,e,null,lr,Ke,{})}}function ar(i){let e,t,n;return{c(){e=ke("svg"),t=ke("circle"),n=ke("path"),S(t,"cx","4.789"),S(t,"cy","4.787"),S(t,"r","3.85"),S(t,"class","svelte-1aq105l"),S(n,"d","M12.063 12.063 7.635 7.635"),S(n,"class","svelte-1aq105l"),S(e,"xmlns","http://www.w3.org/2000/svg"),S(e,"width","13"),S(e,"height","13"),S(e,"viewBox","0 0 13 13"),S(e,"class","svelte-1aq105l")},m(r,u){te(r,e,u),V(e,t),V(e,n)},p:ne,i:ne,o:ne,d(r){r&&$(e)}}}class fr extends Je{constructor(e){super(),Xe(this,e,null,ar,Ke,{})}}function cr(i,e,t){const n=e[1],r=e[0],u=n-r;return i===n&&t?i:((i-r)%u+u)%u+r}function Bt(i){const e=[...i];return e[2]Math.abs((e[0]-360+e[2])/2)?e[0]-=360:e[2]+=360),e}let bt;async function hr(i,e,t){const n=i==null?void 0:i.getCenterAndZoom();for(const r of e??[])if(!(n&&(r.minZoom!=null&&r.minZoom>n[0]||r.maxZoom!=null&&r.maxZoomDate.now()){if(!bt.coords)break e;return bt.coords}let u;try{return u=await new Promise((a,o)=>{t.signal.addEventListener("abort",()=>{o(Error("aborted"))}),navigator.geolocation.getCurrentPosition(g=>{a([g.coords.longitude,g.coords.latitude].map(c=>c.toFixed(6)).join(","))},g=>{o(g)},r)}),u}catch{}finally{r.cachedLocationExpiry&&(bt={time:Date.now(),coords:u})}if(t.signal.aborted)return}if(r.type==="server-geolocation")return"ip";if(n&&r.type==="map-center")return n[1].toFixed(6)+","+n[2].toFixed(6)}}const dr=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([6-9][0-9])\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*(EAST|WEST|[EW])?$/i,Oi=/^([+-]?[0-8]?[0-9])\s+([0-5]?[0-9]\.\d{3,})[\s,]{1,}([+-]?[0-1]?[0-9]?[0-9])\s+([0-5]?[0-9]\.\d{3,})$/,Ri=/^(NORTH|SOUTH|[NS])?[\s]*([+-]?[0-8]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(NORTH|SOUTH|[NS])?[\s]*[,/;]?[\s]*(EAST|WEST|[EW])?[\s]*([+-]?[0-1]?[0-9]?[0-9](?:[\.,]\d{3,}))[\s]*([•º°]?)[\s]*(EAST|WEST|[EW])?$/i,Pi=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(\.)\s*([0-5]?[0-9])\s*(\.)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(EAST|WEST|[EW])?$/i,Ii=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*(D(?:EG)?(?:REES)?)\s*([0-5]?[0-9])\s*(M(?:IN)?(?:UTES)?)\s*((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(S(?:EC)?(?:ONDS)?)\s*(EAST|WEST|[EW])?$/i,Ai=/^(NORTH|SOUTH|[NS])?\s*([+-]?[0-8]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|’’|´´|["″”\.])?\s*(NORTH|SOUTH|[NS])?(?:\s*[,/;]\s*|\s*)(EAST|WEST|[EW])?\s*([+-]?[0-1]?[0-9]?[0-9])\s*([•º°\.:]|D(?:EG)?(?:REES)?)?\s*,?([0-5]?[0-9](?:[\.,]\d{1,})?)?\s*(['′´’\.:]|M(?:IN)?(?:UTES)?)?\s*,?((?:[0-5]?[0-9])(?:[\.,]\d{1,3})?)?\s*(''|′′|´´|’’|["″”\.])?\s*(EAST|WEST|[EW])?$/i;function gr(i){if(!["DMS","DM","DD"].includes(i))throw new Error("invalid format specified");if(this.decimalCoordinates&&this.decimalCoordinates.trim()){const e=this.decimalCoordinates.split(",").map(R=>Number(R.trim())),t=Number(e[0]),n=Number(e[1]),r=Math.abs(t),u=Math.abs(n),a=t>0?"N":"S",o=n>0?"E":"W";let g;i=="DD"&&(g=`${r}° ${a}, ${u}° ${o}`);const c=Math.floor(r),E=Math.floor(u),_=(r-c)*60,M=(u-E)*60;if(i=="DM"){let R=Bi(_,3).toFixed(3).padStart(6,"0"),k=Bi(M,3).toFixed(3).padStart(6,"0");R.endsWith(".000")&&k.endsWith(".000")&&(R=R.replace(/\.000$/,""),k=k.replace(/\.000$/,"")),g=`${c}° ${R}' ${a}, ${E}° ${k}' ${o}`}if(i=="DMS"){const R=Math.floor(_),k=Math.floor(M);let I=((_-R)*60).toFixed(1).padStart(4,"0"),C=((M-k)*60).toFixed(1).padStart(4,"0");const O=R.toString().padStart(2,"0"),x=k.toString().padStart(2,"0");I.endsWith(".0")&&C.endsWith(".0")&&(I=I.replace(/\.0$/,""),C=C.replace(/\.0$/,"")),g=`${c}° ${O}' ${I}" ${a}, ${E}° ${x}' ${C}" ${o}`}return g}else throw new Error("no decimal coordinates to convert")}function Bi(i,e){const t=Math.pow(10,e);return Math.round((i+Number.EPSILON)*t)/t}function ei(i,e){e||(e=5),i=i.replace(/\s+/g," ").trim();let t=null,n=null,r="",u="",a=null,o=[],g=!1;if(dr.test(i))throw new Error("invalid coordinate value");if(Oi.test(i))if(o=Oi.exec(i),g=wt(o),g)t=Math.abs(o[1])+o[2]/60,Number(o[1])<0&&(t*=-1),n=Math.abs(o[3])+o[4]/60,Number(o[3])<0&&(n*=-1),a="DM";else throw new Error("invalid coordinate format");else if(Ri.test(i))if(o=Ri.exec(i),g=wt(o),g){if(t=o[2],n=o[6],t.includes(",")&&(t=t.replace(",",".")),n.includes(",")&&(n=n.replace(",",".")),a="DD",Number(Math.round(t))==Number(t))throw new Error("integer only coordinate provided");if(Number(Math.round(n))==Number(n))throw new Error("integer only coordinate provided");o[1]?(r=o[1],u=o[5]):o[4]&&(r=o[4],u=o[8])}else throw new Error("invalid decimal coordinate format");else if(Pi.test(i))if(o=Pi.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[9])),o[11]&&(n+=o[11]/60),o[13]&&(n+=o[13].replace(",",".")/3600),parseInt(o[9])<0&&(n=-1*n),o[1]?(r=o[1],u=o[8]):o[7]&&(r=o[7],u=o[14]);else throw new Error("invalid DMS coordinates format");else if(Ii.test(i))if(o=Ii.exec(i),g=wt(o),g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4]/60,a="DM"),o[6]&&(t+=o[6]/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12]/60),o[14]&&(n+=o[14]/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid DMS coordinates format");else if(Ai.test(i)){if(o=Ai.exec(i),g=wt(o),o.filter(c=>c).length<=5)throw new Error("invalid coordinates format");if(g)t=Math.abs(parseInt(o[2])),o[4]&&(t+=o[4].replace(",",".")/60,a="DM"),o[6]&&(t+=o[6].replace(",",".")/3600,a="DMS"),parseInt(o[2])<0&&(t=-1*t),n=Math.abs(parseInt(o[10])),o[12]&&(n+=o[12].replace(",",".")/60),o[14]&&(n+=o[14].replace(",",".")/3600),parseInt(o[10])<0&&(n=-1*n),o[1]?(r=o[1],u=o[9]):o[8]&&(r=o[8],u=o[16]);else throw new Error("invalid coordinates format")}if(g){if(Math.abs(n)>=180)throw new Error("invalid longitude value");if(Math.abs(t)>=90)throw new Error("invalid latitude value");if(r&&!u||!r&&u)throw new Error("invalid coordinates value");if(r&&r==u)throw new Error("invalid coordinates format");t.toString().includes(",")&&(t=t.replace(",",".")),n.toString().includes(",")&&(n=n.replace(",","."));let c=/S|SOUTH/i;c.test(r)&&t>0&&(t=-1*t),c=/W|WEST/i,c.test(u)&&n>0&&(n=-1*n);const E=o[0].trim();let _,M;const R=/[,/;\u0020]/g,k=E.match(R);if(k==null){const O=Math.floor(i.length/2);_=E.substring(0,O).trim(),M=E.substring(O).trim()}else{let O;k.length%2==1?O=Math.floor(k.length/2):O=k.length/2-1;let x=0;if(O==0)x=E.indexOf(k[0]),_=E.substring(0,x).trim(),M=E.substring(x+1).trim();else{let N=0,P=0;for(;N<=O;)x=E.indexOf(k[N],P),P=x+1,N++;_=E.substring(0,x).trim(),M=E.substring(x+1).trim()}}const I=_.split(".");if(I.length==2&&I[1]==0&&I[1].length!=2)throw new Error("invalid coordinates format");const C=M.split(".");if(C.length==2&&C[1]==0&&C[1].length!=2)throw new Error("invalid coordinates format");if(/^\d+$/.test(_)||/^\d+$/.test(M))throw new Error("degree only coordinate/s provided");return t=Number(Number(t).toFixed(e)),n=Number(Number(n).toFixed(e)),Object.freeze({verbatimCoordinates:E,verbatimLatitude:_,verbatimLongitude:M,decimalLatitude:t,decimalLongitude:n,decimalCoordinates:`${t},${n}`,originalFormat:a,closeEnough:mr,toCoordinateFormat:gr})}else throw new Error("coordinates pattern match failed")}function wt(i){if(!isNaN(i[0]))return!1;const e=[...i];if(e.shift(),e.length%2>0)return!1;const t=/^[-+]?\d+([\.,]\d+)?$/,n=/[eastsouthnorthwest]+/i,r=e.length/2;for(let u=0;u{e.decimalLatitude?i.push(e):i.push({...e,...vr})}),[...i,...br,...wr]}const Lr=Er();ei.formats=Lr.map(i=>i.verbatimCoordinates);const _r=ei;function Gi(i,e,t){const n=i.slice();return n[97]=e[t],n[99]=t,n}function Di(i){let e,t,n,r,u;return t=new Mi({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[3]),S(e,"class","svelte-bz0zu3")},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[78]),r=!0)},p(a,o){(!n||o[0]&8)&&S(e,"title",a[3])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function zi(i){let e,t;return e=new nr({}),{c(){Qe(e.$$.fragment)},m(n,r){qe(e,n,r),t=!0},i(n){t||(re(e.$$.fragment,n),t=!0)},o(n){fe(e.$$.fragment,n),t=!1},d(n){Fe(e,n)}}}function Ui(i){let e,t,n,r,u;return t=new ur({}),{c(){e=Y("button"),Qe(t.$$.fragment),S(e,"type","button"),S(e,"title",i[10]),S(e,"class","svelte-bz0zu3"),Ie(e,"active",i[0])},m(a,o){te(a,e,o),qe(t,e,null),n=!0,r||(u=he(e,"click",i[79]),r=!0)},p(a,o){(!n||o[0]&1024)&&S(e,"title",a[10]),(!n||o[0]&1)&&Ie(e,"active",a[0])},i(a){n||(re(t.$$.fragment,a),n=!0)},o(a){fe(t.$$.fragment,a),n=!1},d(a){a&&$(e),Fe(t),r=!1,u()}}}function Sr(i){let e,t=[],n=new Map,r,u,a,o=Ti(i[13]);const g=c=>c[97].id+(c[97].address?","+c[97].address:"");for(let c=0;c{B=null}),vt()):B?(B.p(d,v),v[0]&1048576&&re(B,1)):(B=Di(d),B.c(),re(B,1),B.m(c,E)),d[20]?z?v[0]&1048576&&re(z,1):(z=zi(),z.c(),re(z,1),z.m(c,null)):z&&(yt(),fe(z,1,1,()=>{z=null}),vt()),(!O||v[0]&2)&&Ie(c,"displayable",d[1]!==""),d[6]==="button"?W?(W.p(d,v),v[0]&64&&re(W,1)):(W=Ui(d),W.c(),re(W,1),W.m(n,M)):W&&(yt(),fe(W,1,1,()=>{W=null}),vt()),l&&l.p&&(!O||v[2]&128)&&Tn(l,s,d,d[69],O?xn(s,d[69],v,null):Mn(d[69]),null);let p=k;k=h(d),k===p?~k&&m[k].p(d,v):(I&&(yt(),fe(m[p],1,1,()=>{m[p]=null}),vt()),~k?(I=m[k],I?I.p(d,v):(I=m[k]=f[k](d),I.c()),re(I,1),I.m(t,null)):I=null),(!O||v[0]&4&&C!==(C=Pt(d[2])+" svelte-bz0zu3"))&&S(t,"class",C),(!O||v[0]&38)&&Ie(t,"can-collapse",d[5]&&d[1]==="")},i(d){O||(re(P),re(u.$$.fragment,d),re(B),re(z),re(W),re(l,d),re(I),O=!0)},o(d){fe(P),fe(u.$$.fragment,d),fe(B),fe(z),fe(W),fe(l,d),fe(I),O=!1},d(d){d&&($(e),$(t)),Fe(u),i[72](null),B&&B.d(),z&&z.d(),W&&W.d(),l&&l.d(d),~k&&m[k].d(),x=!1,Ue(N)}}}function Nr(i,e,t){let n,r,u,{$$slots:a={},$$scope:o}=e;const g={continental_marine:4,country:4,major_landform:8,region:5,subregion:6,county:7,joint_municipality:8,joint_submunicipality:9,municipality:10,municipal_district:11,locality:12,neighbourhood:13,place:14,postal_code:14,road:16,poi:17,address:18,"poi.peak":15,"poi.shop":18,"poi.cafe":18,"poi.restaurant":18,"poi.aerodrome":13};let{class:c=void 0}=e,{apiKey:E=void 0}=e,{bbox:_=void 0}=e,{clearButtonTitle:M="clear"}=e,{clearOnBlur:R=!1}=e,{clearListOnPick:k=!1}=e,{keepListOpen:I=!1}=e,{collapsed:C=!1}=e,{country:O=void 0}=e,{debounceSearch:x=200}=e,{enableReverse:N="never"}=e,{errorMessage:P="Something went wrong…"}=e,{filter:B=()=>!0}=e,{flyTo:z=!0}=e,{fuzzyMatch:W=!0}=e,{language:s=void 0}=e,{limit:l=void 0}=e;const f=41415112612;let{reverseGeocodingLimit:m=f}=e,{mapController:h=void 0}=e,{minLength:d=2}=e,{noResultsMessage:v="Oops! Looks like you're trying to predict something that's not quite right. We can't seem to find what you're looking for. Maybe try double-checking your spelling or try a different search term. Keep on typing - we'll do our best to get you where you need to go!"}=e,{placeholder:p="Search"}=e,{proximity:y=[{type:"server-geolocation"}]}=e,{reverseActive:b=N==="always"}=e,{reverseButtonTitle:w="toggle reverse geocoding"}=e,{searchValue:T=""}=e,{pickedResultStyle:G="full-geometry"}=e,{showPlaceType:D="if-needed"}=e,{showResultsWhileTyping:H=!0}=e,{selectFirst:Q=!0}=e,{flyToSelected:se=!1}=e,{markerOnSelected:Z=!0}=e,{types:K=void 0}=e;const de=[];let{reverseGeocodingTypes:He=de}=e,{exhaustiveReverseGeocoding:st=!1}=e,{excludeTypes:ot=!1}=e;const Le=void 0;let{reverseGeocodingExcludeTypes:We=Le}=e,{zoom:pe=g}=e,{apiUrl:ge="https://api.maptiler.com/geocoding"}=e,{fetchParameters:ie={}}=e,{iconsBaseUrl:hn="https://cdn.maptiler.com/maptiler-geocoding-control/v2.1.7/icons/"}=e,{adjustUrlQuery:ui=()=>{}}=e,{adjustUrl:ai=()=>{}}=e;function gs(L){Pe.focus(L)}function ms(){Pe.blur()}function dn(L,le=!0,ae=!1){t(1,T=L),le?(t(15,X=-1),mn()):(pn(void 0,!ae,ae),setTimeout(()=>{Pe.focus(),Pe.select()}))}function ps(){t(13,F=void 0),t(14,U=void 0),t(15,X=-1)}function ys(){t(64,ce=[]),t(14,U=void 0)}let F,ce,U,gn="",Pe,X=-1,Ge,Zt=[],lt,ct,ht,fi,Ve=!1;const vs=new Set,tt=_i();Rn(()=>{h&&(h.setEventHandler(void 0),h.indicateReverse(!1),h.setSelectedMarker(-1),h.setFeatures(void 0,void 0,!1))});function mn(L){if(t(17,Ve=!1),ct&&(clearTimeout(ct),ct=void 0),X>-1&&F)t(14,U=F[X]),t(1,T=U.place_type[0]==="reverse"?U.place_name:U.place_name.replace(/,.*/,"")),t(19,Ge=void 0),t(64,ce=void 0),t(15,X=-1);else if(T){const le=L||!ci(T);hi(T,{exact:!0}).then(()=>{t(64,ce=F),t(14,U=void 0),le&&bs()}).catch(ae=>t(19,Ge=ae))}}function ci(L){try{return _r(L,6)}catch{return!1}}async function hi(L,{byId:le=!1,exact:ae=!1}={}){var Se,De,it;t(19,Ge=void 0),lt==null||lt.abort();const _e=new AbortController;t(20,lt=_e);try{const J=ci(L),Mt=new URL(ge+"/"+encodeURIComponent(J?J.decimalLongitude+","+J.decimalLatitude:L)+".json"),Ne=Mt.searchParams;s!==void 0&&Ne.set("language",Array.isArray(s)?s.join(","):s??"");const[mi]=(h==null?void 0:h.getCenterAndZoom())??[];let ze=(Se=!J||He===de?K:He)==null?void 0:Se.map(ve=>typeof ve=="string"?ve:mi===void 0||(ve[0]??0)<=mi&&mi<(ve[1]??1/0)?ve[2]:void 0).filter(ve=>ve!==void 0);ze&&(ze=[...new Set(ze)],Ne.set("types",ze.join(",")));const vn=!J||We===Le?ot:We;if(vn&&Ne.set("excludeTypes",String(vn)),_&&Ne.set("bbox",_.map(ve=>ve.toFixed(6)).join(",")),O&&Ne.set("country",Array.isArray(O)?O.join(","):O),!le&&!J){const ve=await hr(h,y,_e);ve&&Ne.set("proximity",ve),(ae||!H)&&Ne.set("autocomplete","false"),Ne.set("fuzzyMatch",String(W))}const Ct=m===f?l:m;Ct!==void 0&&Ct>1&&(ze==null?void 0:ze.length)!==1&&console.warn("For reverse geocoding when limit > 1 then types must contain single value."),J?(Ct===1||Ct!==void 0&&(st||(ze==null?void 0:ze.length)===1))&&Ne.set("limit",String(Ct)):l!==void 0&&Ne.set("limit",String(l)),E&&Ne.set("key",E),ui(Ne),ai(Mt);const Bs=Mt.searchParams.get("types")===""&&Mt.searchParams.get("excludeTypes")!=="true",Ht=Mt.toString();if(Ht===gn){le?(k&&t(13,F=void 0),t(14,U=Zt[0])):(t(13,F=Zt),((De=F[X])==null?void 0:De.id)!==(r==null?void 0:r.id)&&t(15,X=-1));return}gn=Ht;let Nt;if(Bs)Nt={type:"FeatureCollection",features:[]};else{const ve=await fetch(Ht,{signal:_e.signal,...ie});if(!ve.ok)throw new Error(await ve.text());Nt=await ve.json()}tt("response",{url:Ht,featureCollection:Nt}),le?(k&&t(13,F=void 0),t(14,U=Nt.features[0]),Zt=[U]):(t(13,F=Nt.features.filter(B)),J&&F.unshift({type:"Feature",properties:{},id:"reverse_"+J.decimalLongitude+"_"+J.decimalLatitude,text:J.decimalLatitude+", "+J.decimalLongitude,place_name:J.decimalLatitude+", "+J.decimalLongitude,place_type:["reverse"],center:[J.decimalLongitude,J.decimalLatitude],bbox:[J.decimalLongitude,J.decimalLatitude,J.decimalLongitude,J.decimalLatitude],geometry:{type:"Point",coordinates:[J.decimalLongitude,J.decimalLatitude]}}),Zt=F,((it=F[X])==null?void 0:it.id)!==(r==null?void 0:r.id)&&t(15,X=-1),J&&Pe.focus())}catch(J){if(J&&typeof J=="object"&&"name"in J&&J.name==="AbortError")return;throw J}finally{_e===lt&&t(20,lt=void 0)}}function bs(){var _e;if(!(ce!=null&&ce.length)||!z)return;const L=[180,90,-180,-90],le=!ce.some(Se=>!Se.matching_text);let ae;for(const Se of ce){const De=Tt(Se);if(ae=ae===void 0?De:De===void 0?ae:Math.max(ae,De),le||!Se.matching_text)for(const it of[0,1,2,3])L[it]=Math[it<2?"min":"max"](L[it],((_e=Se.bbox)==null?void 0:_e[it])??Se.center[it%2])}h&&ce.length>0&&(U&&L[0]===L[2]&&L[1]===L[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(L),50,ae))}function di(){!U||!h||(!U.bbox||U.bbox[0]===U.bbox[2]&&U.bbox[1]===U.bbox[3]?h.flyTo(U.center,Tt(U)):h.fitBounds(Bt(U.bbox),50,Tt(U)))}function Tt(L){var ae;if(!L.bbox||L.bbox[0]!==L.bbox[2]&&L.bbox[1]!==L.bbox[3])return;const le=L.id.replace(/\..*/,"");return(Array.isArray((ae=L.properties)==null?void 0:ae.categories)?L.properties.categories.reduce((_e,Se)=>{const De=pe[le+"."+Se];return _e===void 0?De:De===void 0?_e:Math.max(_e,De)},void 0):void 0)??pe[le]}function ws(L){t(0,b=N==="always"),t(13,F=void 0),t(14,U=void 0),t(15,X=-1),dn(L[1].toFixed(6)+", "+cr(L[0],[-180,180],!0).toFixed(6),!1,!0)}function Es(L){if(!F)return;let le=L.key==="ArrowDown"?1:L.key==="ArrowUp"?-1:0;le&&(Pe.focus(),t(17,Ve=!0),L.preventDefault(),U&&X===-1&&t(15,X=F.findIndex(ae=>ae.id===(U==null?void 0:U.id))),X===(U||Q?0:-1)&&le===-1&&t(15,X=F.length),t(15,X+=le),X>=F.length&&t(15,X=-1),X<0&&(U||Q)&&t(15,X=0))}function pn(L,le=!0,ae=!1){if(t(19,Ge=void 0),t(14,U=void 0),t(17,Ve=!0),H||ae){if(ct&&clearTimeout(ct),T.length{hi(_e).catch(Se=>t(19,Ge=Se))},le?x:0)}else t(13,F=void 0),t(19,Ge=void 0)}function gi(L){U&&(U==null?void 0:U.id)===(L==null?void 0:L.id)?di():(t(14,U=L),t(1,T=L.place_name))}function yn(L){t(15,X=L)}function Ls(){(!Q||U)&&t(15,X=-1),se&&di()}const _s=()=>Pe.focus();function Ss(L){Yt[L?"unshift":"push"](()=>{Pe=L,t(18,Pe)})}function xs(){T=this.value,t(1,T),t(17,Ve),t(31,R),t(16,ht)}const Ts=()=>t(17,Ve=!0),Ms=()=>t(17,Ve=!1),Cs=()=>t(17,Ve=!0),Ns=()=>t(14,U=void 0),ks=()=>{t(1,T=""),t(14,U=void 0),Pe.focus()},Os=()=>t(0,b=!b),Rs=()=>t(19,Ge=void 0),Ps=L=>yn(L),Is=L=>gi(L),As=()=>{};return i.$$set=L=>{"class"in L&&t(2,c=L.class),"apiKey"in L&&t(29,E=L.apiKey),"bbox"in L&&t(30,_=L.bbox),"clearButtonTitle"in L&&t(3,M=L.clearButtonTitle),"clearOnBlur"in L&&t(31,R=L.clearOnBlur),"clearListOnPick"in L&&t(32,k=L.clearListOnPick),"keepListOpen"in L&&t(4,I=L.keepListOpen),"collapsed"in L&&t(5,C=L.collapsed),"country"in L&&t(33,O=L.country),"debounceSearch"in L&&t(34,x=L.debounceSearch),"enableReverse"in L&&t(6,N=L.enableReverse),"errorMessage"in L&&t(7,P=L.errorMessage),"filter"in L&&t(35,B=L.filter),"flyTo"in L&&t(36,z=L.flyTo),"fuzzyMatch"in L&&t(37,W=L.fuzzyMatch),"language"in L&&t(38,s=L.language),"limit"in L&&t(39,l=L.limit),"reverseGeocodingLimit"in L&&t(40,m=L.reverseGeocodingLimit),"mapController"in L&&t(41,h=L.mapController),"minLength"in L&&t(42,d=L.minLength),"noResultsMessage"in L&&t(8,v=L.noResultsMessage),"placeholder"in L&&t(9,p=L.placeholder),"proximity"in L&&t(43,y=L.proximity),"reverseActive"in L&&t(0,b=L.reverseActive),"reverseButtonTitle"in L&&t(10,w=L.reverseButtonTitle),"searchValue"in L&&t(1,T=L.searchValue),"pickedResultStyle"in L&&t(44,G=L.pickedResultStyle),"showPlaceType"in L&&t(11,D=L.showPlaceType),"showResultsWhileTyping"in L&&t(45,H=L.showResultsWhileTyping),"selectFirst"in L&&t(46,Q=L.selectFirst),"flyToSelected"in L&&t(47,se=L.flyToSelected),"markerOnSelected"in L&&t(48,Z=L.markerOnSelected),"types"in L&&t(49,K=L.types),"reverseGeocodingTypes"in L&&t(50,He=L.reverseGeocodingTypes),"exhaustiveReverseGeocoding"in L&&t(51,st=L.exhaustiveReverseGeocoding),"excludeTypes"in L&&t(52,ot=L.excludeTypes),"reverseGeocodingExcludeTypes"in L&&t(53,We=L.reverseGeocodingExcludeTypes),"zoom"in L&&t(54,pe=L.zoom),"apiUrl"in L&&t(55,ge=L.apiUrl),"fetchParameters"in L&&t(56,ie=L.fetchParameters),"iconsBaseUrl"in L&&t(12,hn=L.iconsBaseUrl),"adjustUrlQuery"in L&&t(57,ui=L.adjustUrlQuery),"adjustUrl"in L&&t(58,ai=L.adjustUrl),"$$scope"in L&&t(69,o=L.$$scope)},i.$$.update=()=>{if(i.$$.dirty[0]&64&&t(0,b=N==="always"),i.$$.dirty[0]&16384|i.$$.dirty[1]&8192&&G!=="marker-only"&&U&&!U.address&&U.geometry.type==="Point"&&U.place_type[0]!=="reverse"&&hi(U.id,{byId:!0}).catch(L=>t(19,Ge=L)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1058|i.$$.dirty[2]&8&&(h&&U&&U.id!==fi&&z&&(di(),k&&t(13,F=void 0),t(64,ce=void 0),t(15,X=-1)),t(65,fi=U==null?void 0:U.id)),i.$$.dirty[0]&196608|i.$$.dirty[1]&1&&setTimeout(()=>{t(16,ht=Ve),R&&!ht&&t(1,T="")}),i.$$.dirty[0]&8194|i.$$.dirty[1]&2048&&T.length{switch(L.type){case"mapClick":b&&ws(L.coordinates);break;case"markerClick":{const le=F==null?void 0:F.find(ae=>ae.id===L.id);le&&gi(le)}break;case"markerMouseEnter":ce&&t(15,X=ht?(F==null?void 0:F.findIndex(le=>le.id===L.id))??-1:-1);break;case"markerMouseLeave":ce&&t(15,X=-1);break}}),i.$$.dirty[0]&40960&&t(66,r=F==null?void 0:F[X]),i.$$.dirty[1]&66592|i.$$.dirty[2]&16&&h&&r&&z&&se&&h.flyTo(r.center,Tt(r)),i.$$.dirty[1]&8192&&t(68,n=G==="full-geometry-including-polygon-center-marker"),i.$$.dirty[1]&132096|i.$$.dirty[2]&64&&(Z||h==null||h.setFeatures(void 0,void 0,n)),i.$$.dirty[0]&16384|i.$$.dirty[1]&132096|i.$$.dirty[2]&84&&h&&Z&&!ce&&(h.setFeatures(r?[r]:void 0,U,n),h.setSelectedMarker(r?0:-1)),i.$$.dirty[0]&16384|i.$$.dirty[1]&1024|i.$$.dirty[2]&68&&h&&h.setFeatures(ce,U,n),i.$$.dirty[0]&32768|i.$$.dirty[1]&1024|i.$$.dirty[2]&4&&ce&&h&&h.setSelectedMarker(X),i.$$.dirty[0]&2|i.$$.dirty[1]&1024&&h){const L=ci(T);h.setReverseMarker(L?[L.decimalLongitude,L.decimalLatitude]:void 0)}i.$$.dirty[2]&16&&tt("select",{feature:r}),i.$$.dirty[0]&16384&&tt("pick",{feature:U}),i.$$.dirty[0]&73744&&t(67,u=!!(F!=null&&F.length)&&(ht||I)),i.$$.dirty[2]&32&&tt("optionsvisibilitychange",{optionsVisible:u}),i.$$.dirty[0]&8192&&tt("featureslisted",{features:F}),i.$$.dirty[2]&4&&tt("featuresmarked",{features:ce}),i.$$.dirty[0]&1&&tt("reversetoggle",{reverse:b}),i.$$.dirty[0]&2&&tt("querychange",{query:T}),i.$$.dirty[0]&1|i.$$.dirty[1]&1024&&h&&h.indicateReverse(b)},[b,T,c,M,I,C,N,P,v,p,w,D,hn,F,U,X,ht,Ve,Pe,Ge,lt,vs,mn,Es,pn,gi,yn,Ls,g,E,_,R,k,O,x,B,z,W,s,l,m,h,d,y,G,H,Q,se,Z,K,He,st,ot,We,pe,ge,ie,ui,ai,gs,ms,dn,ps,ys,ce,fi,r,u,n,o,a,_s,Ss,xs,Ts,Ms,Cs,Ns,ks,Os,Rs,Ps,Is,As]}let kr=class extends Je{constructor(e){super(),Xe(this,e,Nr,Cr,Ke,{ZOOM_DEFAULTS:28,class:2,apiKey:29,bbox:30,clearButtonTitle:3,clearOnBlur:31,clearListOnPick:32,keepListOpen:4,collapsed:5,country:33,debounceSearch:34,enableReverse:6,errorMessage:7,filter:35,flyTo:36,fuzzyMatch:37,language:38,limit:39,reverseGeocodingLimit:40,mapController:41,minLength:42,noResultsMessage:8,placeholder:9,proximity:43,reverseActive:0,reverseButtonTitle:10,searchValue:1,pickedResultStyle:44,showPlaceType:11,showResultsWhileTyping:45,selectFirst:46,flyToSelected:47,markerOnSelected:48,types:49,reverseGeocodingTypes:50,exhaustiveReverseGeocoding:51,excludeTypes:52,reverseGeocodingExcludeTypes:53,zoom:54,apiUrl:55,fetchParameters:56,iconsBaseUrl:12,adjustUrlQuery:57,adjustUrl:58,focus:59,blur:60,setQuery:61,clearList:62,clearMap:63},null,[-1,-1,-1,-1])}get ZOOM_DEFAULTS(){return this.$$.ctx[28]}get focus(){return this.$$.ctx[59]}get blur(){return this.$$.ctx[60]}get setQuery(){return this.$$.ctx[61]}get clearList(){return this.$$.ctx[62]}get clearMap(){return this.$$.ctx[63]}};function Et(i,e,t={}){const n={type:"Feature"};return(t.id===0||t.id)&&(n.id=t.id),t.bbox&&(n.bbox=t.bbox),n.properties=e||{},n.geometry=i,n}function ti(i,e,t={}){for(const r of i){if(r.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(r[r.length-1].length!==r[0].length)throw new Error("First and last Position are not equivalent.");for(let u=0;u_?w.c=w.e=null:s.e=10;v/=10,d++);d>_?w.c=w.e=null:(w.e=d,w.c=[s]);return}b=String(s)}else{if(!Or.test(b=String(s)))return n(w,b,p);w.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(v=b.search(/e/i))>0?(d<0&&(d=v),d+=+b.slice(v+1),b=b.substring(0,v)):d<0&&(d=b.length)}else{if(oe(l,2,C.length,"Base"),l==10&&O)return w=new x(s),z(w,a+w.e+1,o);if(b=String(s),p=typeof s=="number"){if(s*0!=0)return n(w,b,p,l);if(w.s=1/s<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(ji+s)}else w.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(f=C.slice(0,l),d=v=0,y=b.length;vd){d=y;continue}}else if(!h&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){h=!0,v=-1,d=0;continue}return n(w,String(s),p,l)}p=!1,b=t(b,l,10,w.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(v=0;b.charCodeAt(v)===48;v++);for(y=b.length;b.charCodeAt(--y)===48;);if(b=b.slice(v,++y)){if(y-=v,p&&x.DEBUG&&y>15&&(s>Zi||s!==Te(s)))throw Error(ji+w.s*s);if((d=d-v-1)>_)w.c=w.e=null;else if(d=-1e9&&h<=Ee&&h===Te(h)){if(m[0]===0){if(h===0&&m.length===1)return!0;break e}if(l=(h+1)%q,l<1&&(l+=q),String(m[0]).length==l){for(l=0;l=Re||f!==Te(f))break e;if(f!==0)return!0}}}else if(m===null&&h===null&&(d===null||d===1||d===-1))return!0;throw Error(be+"Invalid BigNumber: "+s)},x.maximum=x.max=function(){return P(arguments,-1)},x.minimum=x.min=function(){return P(arguments,1)},x.random=function(){var s=9007199254740992,l=Math.random()*s&2097151?function(){return Te(Math.random()*s)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(f){var m,h,d,v,p,y=0,b=[],w=new x(u);if(f==null?f=a:oe(f,0,Ee),v=ii(f/q),M)if(crypto.getRandomValues){for(m=crypto.getRandomValues(new Uint32Array(v*=2));y>>11),p>=9e15?(h=crypto.getRandomValues(new Uint32Array(2)),m[y]=h[0],m[y+1]=h[1]):(b.push(p%1e14),y+=2);y=v/2}else if(crypto.randomBytes){for(m=crypto.randomBytes(v*=7);y=9e15?crypto.randomBytes(7).copy(m,y):(b.push(p%1e14),y+=7);y=v/7}else throw M=!1,Error(be+"crypto unavailable");if(!M)for(;y=10;p/=10,y++);yh-1&&(p[v+1]==null&&(p[v+1]=0),p[v+1]+=p[v]/h|0,p[v]%=h)}return p.reverse()}return function(f,m,h,d,v){var p,y,b,w,T,G,D,H,Q=f.indexOf("."),se=a,Z=o;for(Q>=0&&(w=k,k=0,f=f.replace(".",""),H=new x(m),G=H.pow(f.length-Q),k=w,H.c=l(je(Ce(G.c),G.e,"0"),10,h,s),H.e=H.c.length),D=l(f,m,h,v?(p=C,s):(p=s,C)),b=w=D.length;D[--w]==0;D.pop());if(!D[0])return p.charAt(0);if(Q<0?--b:(G.c=D,G.e=b,G.s=d,G=e(G,H,se,Z,h),D=G.c,T=G.r,b=G.e),y=b+se+1,Q=D[y],w=h/2,T=T||y<0||D[y+1]!=null,T=Z<4?(Q!=null||T)&&(Z==0||Z==(G.s<0?3:2)):Q>w||Q==w&&(Z==4||T||Z==6&&D[y-1]&1||Z==(G.s<0?8:7)),y<1||!D[0])f=T?je(p.charAt(1),-se,p.charAt(0)):p.charAt(0);else{if(D.length=y,T)for(--h;++D[--y]>h;)D[y]=0,y||(++b,D=[1].concat(D));for(w=D.length;!D[--w];);for(Q=0,f="";Q<=w;f+=p.charAt(D[Q++]));f=je(f,b,p.charAt(0))}return f}}(),e=function(){function s(m,h,d){var v,p,y,b,w=0,T=m.length,G=h%$e,D=h/$e|0;for(m=m.slice();T--;)y=m[T]%$e,b=m[T]/$e|0,v=D*y+b*G,p=G*y+v%$e*$e+w,w=(p/d|0)+(v/$e|0)+D*b,m[T]=p%d;return w&&(m=[w].concat(m)),m}function l(m,h,d,v){var p,y;if(d!=v)y=d>v?1:-1;else for(p=y=0;ph[p]?1:-1;break}return y}function f(m,h,d,v){for(var p=0;d--;)m[d]-=p,p=m[d]1;m.splice(0,1));}return function(m,h,d,v,p){var y,b,w,T,G,D,H,Q,se,Z,K,de,He,st,ot,Le,We,pe=m.s==h.s?1:-1,ge=m.c,ie=h.c;if(!ge||!ge[0]||!ie||!ie[0])return new x(!m.s||!h.s||(ge?ie&&ge[0]==ie[0]:!ie)?NaN:ge&&ge[0]==0||!ie?pe*0:pe/0);for(Q=new x(pe),se=Q.c=[],b=m.e-h.e,pe=d+b+1,p||(p=Re,b=Me(m.e/q)-Me(h.e/q),pe=pe/q|0),w=0;ie[w]==(ge[w]||0);w++);if(ie[w]>(ge[w]||0)&&b--,pe<0)se.push(1),T=!0;else{for(st=ge.length,Le=ie.length,w=0,pe+=2,G=Te(p/(ie[0]+1)),G>1&&(ie=s(ie,G,p),ge=s(ge,G,p),Le=ie.length,st=ge.length),He=Le,Z=ge.slice(0,Le),K=Z.length;K=p/2&&ot++;do{if(G=0,y=l(ie,Z,Le,K),y<0){if(de=Z[0],Le!=K&&(de=de*p+(Z[1]||0)),G=Te(de/ot),G>1)for(G>=p&&(G=p-1),D=s(ie,G,p),H=D.length,K=Z.length;l(D,Z,H,K)==1;)G--,f(D,Le=10;pe/=10,w++);z(Q,d+(Q.e=w+b*q-1)+1,v,T)}else Q.e=b,Q.r=+T;return Q}}();function N(s,l,f,m){var h,d,v,p,y;if(f==null?f=o:oe(f,0,8),!s.c)return s.toString();if(h=s.c[0],v=s.e,l==null)y=Ce(s.c),y=m==1||m==2&&(v<=g||v>=c)?Gt(y,v):je(y,v,"0");else if(s=z(new x(s),l,f),d=s.e,y=Ce(s.c),p=y.length,m==1||m==2&&(l<=d||d<=g)){for(;pp){if(--l>0)for(y+=".";l--;y+="0");}else if(l+=d-p,l>0)for(d+1==p&&(y+=".");l--;y+="0");return s.s<0&&h?"-"+y:y}function P(s,l){for(var f,m,h=1,d=new x(s[0]);h=10;h/=10,m++);return(f=m+f*q-1)>_?s.c=s.e=null:f=10;p/=10,h++);if(d=l-h,d<0)d+=q,v=l,y=T[b=0],w=Te(y/G[h-v-1]%10);else if(b=ii((d+1)/q),b>=T.length)if(m){for(;T.length<=b;T.push(0));y=w=0,h=1,d%=q,v=d-q+1}else break e;else{for(y=p=T[b],h=1;p>=10;p/=10,h++);d%=q,v=d-q+h,w=v<0?0:Te(y/G[h-v-1]%10)}if(m=m||l<0||T[b+1]!=null||(v<0?y:y%G[h-v-1]),m=f<4?(w||m)&&(f==0||f==(s.s<0?3:2)):w>5||w==5&&(f==4||m||f==6&&(d>0?v>0?y/G[h-v]:0:T[b-1])%10&1||f==(s.s<0?8:7)),l<1||!T[0])return T.length=0,m?(l-=s.e+1,T[0]=G[(q-l%q)%q],s.e=-l||0):T[0]=s.e=0,s;if(d==0?(T.length=b,p=1,b--):(T.length=b+1,p=G[q-d],T[b]=v>0?Te(y/G[h-v]%G[v])*p:0),m)for(;;)if(b==0){for(d=1,v=T[0];v>=10;v/=10,d++);for(v=T[0]+=p,p=1;v>=10;v/=10,p++);d!=p&&(s.e++,T[0]==Re&&(T[0]=1));break}else{if(T[b]+=p,T[b]!=Re)break;T[b--]=0,p=1}for(d=T.length;T[--d]===0;T.pop());}s.e>_?s.c=s.e=null:s.e=c?Gt(l,f):je(l,f,"0"),s.s<0?"-"+l:l)}return r.absoluteValue=r.abs=function(){var s=new x(this);return s.s<0&&(s.s=1),s},r.comparedTo=function(s,l){return rt(this,new x(s,l))},r.decimalPlaces=r.dp=function(s,l){var f,m,h,d=this;if(s!=null)return oe(s,0,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s+d.e+1,l);if(!(f=d.c))return null;if(m=((h=f.length-1)-Me(this.e/q))*q,h=f[h])for(;h%10==0;h/=10,m--);return m<0&&(m=0),m},r.dividedBy=r.div=function(s,l){return e(this,new x(s,l),a,o)},r.dividedToIntegerBy=r.idiv=function(s,l){return e(this,new x(s,l),0,1)},r.exponentiatedBy=r.pow=function(s,l){var f,m,h,d,v,p,y,b,w,T=this;if(s=new x(s),s.c&&!s.isInteger())throw Error(be+"Exponent not an integer: "+W(s));if(l!=null&&(l=new x(l)),p=s.e>14,!T.c||!T.c[0]||T.c[0]==1&&!T.e&&T.c.length==1||!s.c||!s.c[0])return w=new x(Math.pow(+W(T),p?s.s*(2-Wt(s)):+W(s))),l?w.mod(l):w;if(y=s.s<0,l){if(l.c?!l.c[0]:!l.s)return new x(NaN);m=!y&&T.isInteger()&&l.isInteger(),m&&(T=T.mod(l))}else{if(s.e>9&&(T.e>0||T.e<-1||(T.e==0?T.c[0]>1||p&&T.c[1]>=24e7:T.c[0]<8e13||p&&T.c[0]<=9999975e7)))return d=T.s<0&&Wt(s)?-0:0,T.e>-1&&(d=1/d),new x(y?1/d:d);k&&(d=ii(k/q+2))}for(p?(f=new x(.5),y&&(s.s=1),b=Wt(s)):(h=Math.abs(+W(s)),b=h%2),w=new x(u);;){if(b){if(w=w.times(T),!w.c)break;d?w.c.length>d&&(w.c.length=d):m&&(w=w.mod(l))}if(h){if(h=Te(h/2),h===0)break;b=h%2}else if(s=s.times(f),z(s,s.e+1,1),s.e>14)b=Wt(s);else{if(h=+W(s),h===0)break;b=h%2}T=T.times(T),d?T.c&&T.c.length>d&&(T.c.length=d):m&&(T=T.mod(l))}return m?w:(y&&(w=u.div(w)),l?w.mod(l):d?z(w,k,o,v):w)},r.integerValue=function(s){var l=new x(this);return s==null?s=o:oe(s,0,8),z(l,l.e+1,s)},r.isEqualTo=r.eq=function(s,l){return rt(this,new x(s,l))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(s,l){return rt(this,new x(s,l))>0},r.isGreaterThanOrEqualTo=r.gte=function(s,l){return(l=rt(this,new x(s,l)))===1||l===0},r.isInteger=function(){return!!this.c&&Me(this.e/q)>this.c.length-2},r.isLessThan=r.lt=function(s,l){return rt(this,new x(s,l))<0},r.isLessThanOrEqualTo=r.lte=function(s,l){return(l=rt(this,new x(s,l)))===-1||l===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(s,l){var f,m,h,d,v=this,p=v.s;if(s=new x(s,l),l=s.s,!p||!l)return new x(NaN);if(p!=l)return s.s=-l,v.plus(s);var y=v.e/q,b=s.e/q,w=v.c,T=s.c;if(!y||!b){if(!w||!T)return w?(s.s=-l,s):new x(T?v:NaN);if(!w[0]||!T[0])return T[0]?(s.s=-l,s):new x(w[0]?v:o==3?-0:0)}if(y=Me(y),b=Me(b),w=w.slice(),p=y-b){for((d=p<0)?(p=-p,h=w):(b=y,h=T),h.reverse(),l=p;l--;h.push(0));h.reverse()}else for(m=(d=(p=w.length)<(l=T.length))?p:l,p=l=0;l0)for(;l--;w[f++]=0);for(l=Re-1;m>p;){if(w[--m]=0;){for(f=0,G=de[h]%se,D=de[h]/se|0,v=y,d=h+v;d>h;)b=K[--v]%se,w=K[v]/se|0,p=D*b+w*G,b=G*b+p%se*se+H[d]+f,f=(b/Q|0)+(p/se|0)+D*w,H[d--]=b%Q;H[d]=f}return f?++m:H.splice(0,1),B(s,H,m)},r.negated=function(){var s=new x(this);return s.s=-s.s||null,s},r.plus=function(s,l){var f,m=this,h=m.s;if(s=new x(s,l),l=s.s,!h||!l)return new x(NaN);if(h!=l)return s.s=-l,m.minus(s);var d=m.e/q,v=s.e/q,p=m.c,y=s.c;if(!d||!v){if(!p||!y)return new x(h/0);if(!p[0]||!y[0])return y[0]?s:new x(p[0]?m:h*0)}if(d=Me(d),v=Me(v),p=p.slice(),h=d-v){for(h>0?(v=d,f=y):(h=-h,f=p),f.reverse();h--;f.push(0));f.reverse()}for(h=p.length,l=y.length,h-l<0&&(f=y,y=p,p=f,l=h),h=0;l;)h=(p[--l]=p[l]+y[l]+h)/Re|0,p[l]=Re===p[l]?0:p[l]%Re;return h&&(p=[h].concat(p),++v),B(s,p,v)},r.precision=r.sd=function(s,l){var f,m,h,d=this;if(s!=null&&s!==!!s)return oe(s,1,Ee),l==null?l=o:oe(l,0,8),z(new x(d),s,l);if(!(f=d.c))return null;if(h=f.length-1,m=h*q+1,h=f[h]){for(;h%10==0;h/=10,m--);for(h=f[0];h>=10;h/=10,m++);}return s&&d.e+1>m&&(m=d.e+1),m},r.shiftedBy=function(s){return oe(s,-9007199254740991,Zi),this.times("1e"+s)},r.squareRoot=r.sqrt=function(){var s,l,f,m,h,d=this,v=d.c,p=d.s,y=d.e,b=a+4,w=new x("0.5");if(p!==1||!v||!v[0])return new x(!p||p<0&&(!v||v[0])?NaN:v?d:1/0);if(p=Math.sqrt(+W(d)),p==0||p==1/0?(l=Ce(v),(l.length+y)%2==0&&(l+="0"),p=Math.sqrt(+l),y=Me((y+1)/2)-(y<0||y%2),p==1/0?l="5e"+y:(l=p.toExponential(),l=l.slice(0,l.indexOf("e")+1)+y),f=new x(l)):f=new x(p+""),f.c[0]){for(y=f.e,p=y+b,p<3&&(p=0);;)if(h=f,f=w.times(h.plus(e(d,h,b,1))),Ce(h.c).slice(0,p)===(l=Ce(f.c)).slice(0,p))if(f.e0&&H>0){for(d=H%p||p,w=D.substr(0,d);d0&&(w+=b+D.slice(d)),G&&(w="-"+w)}m=T?w+(f.decimalSeparator||"")+((y=+f.fractionGroupSize)?T.replace(new RegExp("\\d{"+y+"}\\B","g"),"$&"+(f.fractionGroupSeparator||"")):T):w}return(f.prefix||"")+m+(f.suffix||"")},r.toFraction=function(s){var l,f,m,h,d,v,p,y,b,w,T,G,D=this,H=D.c;if(s!=null&&(p=new x(s),!p.isInteger()&&(p.c||p.s!==1)||p.lt(u)))throw Error(be+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+W(p));if(!H)return new x(D);for(l=new x(u),b=f=new x(u),m=y=new x(u),G=Ce(H),d=l.e=G.length-D.e-1,l.c[0]=ni[(v=d%q)<0?q+v:v],s=!s||p.comparedTo(l)>0?d>0?l:b:p,v=_,_=1/0,p=new x(G),y.c[0]=0;w=e(p,l,0,1),h=f.plus(w.times(m)),h.comparedTo(s)!=1;)f=m,m=h,b=y.plus(w.times(h=b)),y=h,l=p.minus(w.times(h=l)),p=h;return h=e(s.minus(f),m,0,1),y=y.plus(h.times(b)),f=f.plus(h.times(m)),y.s=b.s=D.s,d=d*2,T=e(b,m,d,o).minus(D).abs().comparedTo(e(y,f,d,o).minus(D).abs())<1?[b,m]:[y,f],_=v,T},r.toNumber=function(){return+W(this)},r.toPrecision=function(s,l){return s!=null&&oe(s,1,Ee),N(this,s,l,2)},r.toString=function(s){var l,f=this,m=f.s,h=f.e;return h===null?m?(l="Infinity",m<0&&(l="-"+l)):l="NaN":(s==null?l=h<=g||h>=c?Gt(Ce(f.c),h):je(Ce(f.c),h,"0"):s===10&&O?(f=z(new x(f),a+h+1,o),l=je(Ce(f.c),f.e,"0")):(oe(s,2,C.length,"Base"),l=t(je(Ce(f.c),h,"0"),10,s,m,!0)),m<0&&f.c[0]&&(l="-"+l)),l},r.valueOf=r.toJSON=function(){return W(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,i!=null&&x.set(i),x}function Me(i){var e=i|0;return i>0||i===e?e:e-1}function Ce(i){for(var e,t,n=1,r=i.length,u=i[0]+"";nc^t?1:-1;for(o=(g=r.length)<(c=u.length)?g:c,a=0;au[a]^t?1:-1;return g==c?0:g>c^t?1:-1}function oe(i,e,t,n){if(it||i!==Te(i))throw Error(be+(n||"Argument")+(typeof i=="number"?it?" out of range: ":" not an integer: ":" not a primitive number: ")+String(i))}function Wt(i){var e=i.c.length-1;return Me(i.e/q)==e&&i.c[e]%2!=0}function Gt(i,e){return(i.length>1?i.charAt(0)+"."+i.slice(1):i)+(e<0?"e":"e+")+e}function je(i,e,t){var n,r;if(e<0){for(r=t+".";++e;r+=t);i=r+i}else if(n=i.length,++e>n){for(r=t,e-=n;--e;r+=t);i+=r}else e0){let c=a.left;if(c==null||(g=o(c.key,i),g>0&&(a.left=c.right,c.right=a,a=c,c=a.left,c==null)))break;t==null?n=a:t.left=a,t=a,a=c}else if(g<0){let c=a.right;if(c==null||(g=o(c.key,i),g<0&&(a.right=c.left,c.left=a,a=c,c=a.right,c==null)))break;r==null?u=a:r.right=a,r=a,a=c}else break;return r!=null&&(r.right=a.left,a.left=u),t!=null&&(t.left=a.right,a.right=n),this.root!==a&&(this.root=a,this.splayCount++),g}splayMin(i){let e=i,t=e.left;for(;t!=null;){const n=t;e.left=n.right,n.right=e,e=n,t=e.left}return e}splayMax(i){let e=i,t=e.right;for(;t!=null;){const n=t;e.right=n.left,n.left=e,e=n,t=e.right}return e}_delete(i){if(this.root==null||this.splay(i)!=0)return null;let t=this.root;const n=t,r=t.left;if(this.size--,r==null)this.root=t.right;else{const u=t.right;t=this.splayMax(r),t.right=u,this.root=t}return this.modificationCount++,n}addNewRoot(i,e){this.size++,this.modificationCount++;const t=this.root;if(t==null){this.root=i;return}e<0?(i.left=t,i.right=t.right,t.right=null):(i.right=t,i.left=t.left,t.left=null),this.root=i}_first(){const i=this.root;return i==null?null:(this.root=this.splayMin(i),this.root)}_last(){const i=this.root;return i==null?null:(this.root=this.splayMax(i),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(i){return this.validKey(i)&&this.splay(i)==0}defaultCompare(){return(i,e)=>ie?1:0}wrap(){return{getRoot:()=>this.root,setRoot:i=>{this.root=i},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:i=>{this.splayCount=i},splay:i=>this.splay(i),has:i=>this.has(i)}}},Dt=class Ot extends Pr{constructor(t,n){super();A(this,"root",null);A(this,"compare");A(this,"validKey");A(this,fn,"[object Set]");this.compare=t??this.defaultCompare(),this.validKey=n??(r=>r!=null&&r!=null)}delete(t){return this.validKey(t)?this._delete(t)!=null:!1}deleteAll(t){for(const n of t)this.delete(n)}forEach(t){const n=this[Symbol.iterator]();let r;for(;r=n.next(),!r.done;)t(r.value,r.value,this)}add(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this}addAndReturn(t){const n=this.splay(t);return n!=0&&this.addNewRoot(new _t(t),n),this.root.key}addAll(t){for(const n of t)this.add(n)}isEmpty(){return this.root==null}isNotEmpty(){return this.root!=null}single(){if(this.size==0)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(this.size==0)throw"Bad state: No element";return this._first().key}last(){if(this.size==0)throw"Bad state: No element";return this._last().key}lastBefore(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)<0)return this.root.key;let r=this.root.left;if(r==null)return null;let u=r.right;for(;u!=null;)r=u,u=r.right;return r.key}firstAfter(t){if(t==null)throw"Invalid arguments(s)";if(this.root==null)return null;if(this.splay(t)>0)return this.root.key;let r=this.root.right;if(r==null)return null;let u=r.left;for(;u!=null;)r=u,u=r.left;return r.key}retainAll(t){const n=new Ot(this.compare,this.validKey),r=this.modificationCount;for(const u of t){if(r!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(u)&&this.splay(u)==0&&n.add(this.root.key)}n.size!=this.size&&(this.root=n.root,this.size=n.size,this.modificationCount++)}lookup(t){return!this.validKey(t)||this.splay(t)!=0?null:this.root.key}intersection(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)&&n.add(r);return n}difference(t){const n=new Ot(this.compare,this.validKey);for(const r of this)t.has(r)||n.add(r);return n}union(t){const n=this.clone();return n.addAll(t),n}clone(){const t=new Ot(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(t){if(t==null)return null;function n(u,a){let o,g;do{if(o=u.left,g=u.right,o!=null){const c=new _t(o.key);a.left=c,n(o,c)}if(g!=null){const c=new _t(g.key);a.right=c,u=g,a=c}}while(g!=null)}const r=new _t(t.key);return n(t,r),r}toSet(){return this.clone()}entries(){return new Ar(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[(cn=Symbol.iterator,fn=Symbol.toStringTag,cn)](){return new Ir(this.wrap())}},Vi=class{constructor(i){A(this,"tree");A(this,"path",new Array);A(this,"modificationCount",null);A(this,"splayCount");this.tree=i,this.splayCount=i.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const i=this.path[this.path.length-1];return this.getValue(i)}rebuildPath(i){this.path.splice(0,this.path.length),this.tree.splay(i),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(i){for(;i!=null;)this.path.push(i),i=i.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(this.modificationCount==null){this.modificationCount=this.tree.getModificationCount();let t=this.tree.getRoot();for(;t!=null;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let i=this.path[this.path.length-1],e=i.right;if(e!=null){for(;e!=null;)this.path.push(e),e=e.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===i;)i=this.path.pop();return this.path.length>0}},Ir=class extends Vi{getValue(i){return i.key}},Ar=class extends Vi{getValue(i){return[i.key,i.key]}},Ki=i=>()=>i,ri=i=>{const e=i?(t,n)=>n.minus(t).abs().isLessThanOrEqualTo(i):Ki(!1);return(t,n)=>e(t,n)?0:t.comparedTo(n)};function Br(i){const e=i?(t,n,r,u,a)=>t.exponentiatedBy(2).isLessThanOrEqualTo(u.minus(n).exponentiatedBy(2).plus(a.minus(r).exponentiatedBy(2)).times(i)):Ki(!1);return(t,n,r)=>{const u=t.x,a=t.y,o=r.x,g=r.y,c=a.minus(g).times(n.x.minus(o)).minus(u.minus(o).times(n.y.minus(g)));return e(c,u,a,o,g)?0:c.comparedTo(0)}}var Wr=i=>i,Gr=i=>{if(i){const e=new Dt(ri(i)),t=new Dt(ri(i)),n=(u,a)=>a.addAndReturn(u),r=u=>({x:n(u.x,e),y:n(u.y,t)});return r({x:new Ae(0),y:new Ae(0)}),r}return Wr},si=i=>({set:e=>{Ze=si(e)},reset:()=>si(i),compare:ri(i),snap:Gr(i),orient:Br(i)}),Ze=si(),St=(i,e)=>i.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(i.ur.x)&&i.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(i.ur.y),oi=(i,e)=>{if(e.ur.x.isLessThan(i.ll.x)||i.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(i.ll.y)||i.ur.y.isLessThan(e.ll.y))return null;const t=i.ll.x.isLessThan(e.ll.x)?e.ll.x:i.ll.x,n=i.ur.x.isLessThan(e.ur.x)?i.ur.x:e.ur.x,r=i.ll.y.isLessThan(e.ll.y)?e.ll.y:i.ll.y,u=i.ur.y.isLessThan(e.ur.y)?i.ur.y:e.ur.y;return{ll:{x:t,y:r},ur:{x:n,y:u}}},zt=(i,e)=>i.x.times(e.y).minus(i.y.times(e.x)),Yi=(i,e)=>i.x.times(e.x).plus(i.y.times(e.y)),Ut=i=>Yi(i,i).sqrt(),Dr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return zt(r,n).div(Ut(r)).div(Ut(n))},zr=(i,e,t)=>{const n={x:e.x.minus(i.x),y:e.y.minus(i.y)},r={x:t.x.minus(i.x),y:t.y.minus(i.y)};return Yi(r,n).div(Ut(r)).div(Ut(n))},Qi=(i,e,t)=>e.y.isZero()?null:{x:i.x.plus(e.x.div(e.y).times(t.minus(i.y))),y:t},Xi=(i,e,t)=>e.x.isZero()?null:{x:t,y:i.y.plus(e.y.div(e.x).times(t.minus(i.x)))},Ur=(i,e,t,n)=>{if(e.x.isZero())return Xi(t,n,i.x);if(n.x.isZero())return Xi(i,e,t.x);if(e.y.isZero())return Qi(t,n,i.y);if(n.y.isZero())return Qi(i,e,t.y);const r=zt(e,n);if(r.isZero())return null;const u={x:t.x.minus(i.x),y:t.y.minus(i.y)},a=zt(u,e).div(r),o=zt(u,n).div(r),g=i.x.plus(o.times(e.x)),c=t.x.plus(a.times(n.x)),E=i.y.plus(o.times(e.y)),_=t.y.plus(a.times(n.y)),M=g.plus(c).div(2),R=E.plus(_).div(2);return{x:M,y:R}},Be=class En{constructor(e,t){A(this,"point");A(this,"isLeft");A(this,"segment");A(this,"otherSE");A(this,"consumedBy");e.events===void 0?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}static compare(e,t){const n=En.comparePoints(e.point,t.point);return n!==0?n:(e.point!==t.point&&e.link(t),e.isLeft!==t.isLeft?e.isLeft?1:-1:Ft.compare(e.segment,t.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let n=0,r=t.length;n{const u=r.otherSE;t.set(r,{sine:Dr(this.point,e.point,u.point),cosine:zr(this.point,e.point,u.point)})};return(r,u)=>{t.has(r)||n(r),t.has(u)||n(u);const{sine:a,cosine:o}=t.get(r),{sine:g,cosine:c}=t.get(u);return a.isGreaterThanOrEqualTo(0)&&g.isGreaterThanOrEqualTo(0)?o.isLessThan(c)?1:o.isGreaterThan(c)?-1:0:a.isLessThan(0)&&g.isLessThan(0)?o.isLessThan(c)?-1:o.isGreaterThan(c)?1:0:g.isLessThan(a)?-1:g.isGreaterThan(a)?1:0}}},qr=class pi{constructor(e){A(this,"events");A(this,"poly");A(this,"_isExteriorRing");A(this,"_enclosingRing");this.events=e;for(let t=0,n=e.length;t0&&(e=g)}let t=e.segment.prevInResult(),n=t?t.prevInResult():null;for(;;){if(!t)return null;if(!n)return t.ringOut;if(n.ringOut!==t.ringOut)return((r=n.ringOut)==null?void 0:r.enclosingRing())!==t.ringOut?t.ringOut:(u=t.ringOut)==null?void 0:u.enclosingRing();t=n.prevInResult(),n=t?t.prevInResult():null}}},Ji=class{constructor(i){A(this,"exteriorRing");A(this,"interiorRings");this.exteriorRing=i,i.poly=this,this.interiorRings=[]}addInterior(i){this.interiorRings.push(i),i.poly=this}getGeom(){const i=this.exteriorRing.getGeom();if(i===null)return null;const e=[i];for(let t=0,n=this.interiorRings.length;t0?(this.tree.delete(e),t.push(i)):(this.segments.push(e),e.prev=n)}else{if(n&&r){const u=n.getIntersection(r);if(u!==null){if(!n.isAnEndpoint(u)){const a=this._splitSafely(n,u);for(let o=0,g=a.length;o0)return-1;const M=t.comparePoint(e.rightSE.point);return M!==0?M:-1}if(n.isGreaterThan(r)){if(o.isLessThan(g)&&o.isLessThan(E))return-1;if(o.isGreaterThan(g)&&o.isGreaterThan(E))return 1;const _=t.comparePoint(e.leftSE.point);if(_!==0)return _;const M=e.comparePoint(t.rightSE.point);return M<0?1:M>0?-1:1}if(o.isLessThan(g))return-1;if(o.isGreaterThan(g))return 1;if(u.isLessThan(a)){const _=t.comparePoint(e.rightSE.point);if(_!==0)return _}if(u.isGreaterThan(a)){const _=e.comparePoint(t.rightSE.point);if(_<0)return 1;if(_>0)return-1}if(!u.eq(a)){const _=c.minus(o),M=u.minus(n),R=E.minus(g),k=a.minus(r);if(_.isGreaterThan(M)&&R.isLessThan(k))return 1;if(_.isLessThan(M)&&R.isGreaterThan(k))return-1}return u.isGreaterThan(a)?1:u.isLessThan(a)||c.isLessThan(E)?-1:c.isGreaterThan(E)?1:e.idt.id?1:0}static fromRing(e,t,n){let r,u,a;const o=Be.comparePoints(e,t);if(o<0)r=e,u=t,a=1;else if(o>0)r=t,u=e,a=-1;else throw new Error(`Tried to create degenerate segment at [${e.x}, ${e.y}]`);const g=new Be(r,!0),c=new Be(u,!1);return new Kt(g,c,[n],[a])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return Ze.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),n=e.bbox(),r=oi(t,n);if(r===null)return null;const u=this.leftSE.point,a=this.rightSE.point,o=e.leftSE.point,g=e.rightSE.point,c=St(t,o)&&this.comparePoint(o)===0,E=St(n,u)&&e.comparePoint(u)===0,_=St(t,g)&&this.comparePoint(g)===0,M=St(n,a)&&e.comparePoint(a)===0;if(E&&c)return M&&!_?a:!M&&_?g:null;if(E)return _&&u.x.eq(g.x)&&u.y.eq(g.y)?null:u;if(c)return M&&a.x.eq(o.x)&&a.y.eq(o.y)?null:o;if(M&&_)return null;if(M)return a;if(_)return g;const R=Ur(u,this.vector(),o,e.vector());return R===null||!St(r,R)?null:Ze.snap(R)}split(e){const t=[],n=e.events!==void 0,r=new Be(e,!0),u=new Be(e,!1),a=this.rightSE;this.replaceRightSE(u),t.push(u),t.push(r);const o=new Kt(r,a,this.rings.slice(),this.windings.slice());return Be.comparePoints(o.leftSE.point,o.rightSE.point)>0&&o.swapEvents(),Be.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(r.checkForConsuming(),u.checkForConsuming()),t}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,n=this.windings.length;t0){const u=t;t=n,n=u}if(t.prev===n){const u=t;t=n,n=u}for(let u=0,a=n.rings.length;ur.length===1&&r[0].isSubject;this._isInResult=n(e)!==n(t);break}}return this._isInResult}},$i=class{constructor(i,e,t){A(this,"poly");A(this,"isExterior");A(this,"segments");A(this,"bbox");if(!Array.isArray(i)||i.length===0)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=e,this.isExterior=t,this.segments=[],typeof i[0][0]!="number"||typeof i[0][1]!="number")throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const n=Ze.snap({x:new Ae(i[0][0]),y:new Ae(i[0][1])});this.bbox={ll:{x:n.x,y:n.y},ur:{x:n.x,y:n.y}};let r=n;for(let u=1,a=i.length;uqt.run("union",i,e),Yr=(i,...e)=>qt.run("difference",i,e);Ze.set;function tn(i,e,t){if(i!==null)for(var n,r,u,a,o,g,c,E=0,_=0,M,R=i.type,k=R==="FeatureCollection",I=R==="Feature",C=k?i.features.length:1,O=0;O{t.push(r.coordinates)}),t.length<2)throw new Error("Must have at least 2 geometries");const n=Kr(t[0],...t.slice(1));return n.length===0?null:n.length===1?ti(n[0],e.properties):Fi(n,e.properties)}var nn=Xr;function Jr(i,e={}){if(i.bbox!=null&&e.recompute!==!0)return i.bbox;const t=[1/0,1/0,-1/0,-1/0];return tn(i,n=>{t[0]>n[0]&&(t[0]=n[0]),t[1]>n[1]&&(t[1]=n[1]),t[2]{e.push(r.coordinates)}),e.length<2)throw new Error("Must have at least two features");const t=i.features[0].properties||{},n=Yr(e[0],...e.slice(1));return n.length===0?null:n.length===1?ti(n[0],t):Fi(n,t)}var es=$r;function ts(i){if(!i)throw new Error("geojson is required");var e=[];return Qr(i,function(t){e.push(t)}),Lt(e)}var is=ts;function sn(i,e){const t=es(Lt([ti([[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]]),i]));if(!t)return;t.properties={isMask:!0};const n=Bt(rn(i)),r=(n[2]-n[0])/360/1e3,u=n[0]<-180,a=n[2]>180,o=is(i);if(o.features.length>1&&(u||a))for(const g of o.features){const c=Bt(rn(g));if(a&&c[0]<-180+r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]+=360-r;if(u&&c[2]>180-r)for(const E of g.geometry.coordinates)for(const _ of E)_[0]-=360-r}e(Lt([o.features.length<2?i:nn(o)??i,t]))}const on={fill:{paint:{"fill-color":"#000","fill-opacity":.1},filter:["all",["==",["geometry-type"],"Polygon"],["has","isMask"]]},line:{layout:{"line-cap":"square"},paint:{"line-width":["case",["==",["geometry-type"],"Polygon"],2,3],"line-dasharray":[1,1],"line-color":"#3170fe"},filter:["!",["has","isMask"]]}},jt="mtlr-gc-full-geom",ln="mtlr-gc-full-geom-fill",un="mtlr-gc-full-geom-line";function an(i,e,t=!0,n=!0,r={},u={},a=on){let o;const g=[];let c,E,_;function M(){if(!i.loaded){i.once("load",M);return}const C=a?a===!0?on:a:void 0;if(!(C!=null&&C.fill)&&!(C!=null&&C.line))return;const O=i.getSource(jt);if(O)O.setData(_??Lt([]));else if(_)i.addSource(jt,{type:"geojson",data:_});else return;!i.getLayer(ln)&&(C!=null&&C.fill)&&i.addLayer({...C==null?void 0:C.fill,id:ln,type:"fill",source:jt}),!i.getLayer(un)&&(C!=null&&C.line)&&i.addLayer({...C==null?void 0:C.line,id:un,type:"line",source:jt})}function R(C){_=C,M()}i.on("styledata",()=>{setTimeout(()=>{_&&M()})});const k=C=>{o==null||o({type:"mapClick",coordinates:[C.lngLat.lng,C.lngLat.lat]})};function I(C=!1){if(!e)throw new Error;const O=document.createElement("div");return C&&O.classList.add("marker-interactive"),new or({props:{displayIn:"maplibre"},target:O}),new e.Marker({element:O,offset:[1,-13]})}return{setEventHandler(C){C?(o=C,i.on("click",k)):(o=void 0,i.off("click",k))},flyTo(C,O){i.flyTo({center:C,...O?{zoom:O}:{},...r})},fitBounds(C,O,x){i.fitBounds([[C[0],C[1]],[C[2],C[3]]],{padding:O,...x?{maxZoom:x}:{},...u})},indicateReverse(C){i.getCanvasContainer().style.cursor=C?"crosshair":""},setReverseMarker(C){!e||!t||(E?C?E.setLngLat(C):(E.remove(),E=void 0):C&&(t instanceof Function?E=t(i)??void 0:(E=(typeof t=="object"?new e.Marker(t):I()).setLngLat(C).addTo(i),E.getElement().classList.add("marker-reverse"))))},setFeatures(C,O,x){for(const N of g)N.remove();if(g.length=0,R(void 0),!!e){e:if(O){let N=!1;if(O.geometry.type==="GeometryCollection"){const P=O.geometry.geometries.filter(B=>B.type==="Polygon"||B.type==="MultiPolygon");t:if(P.length>0){const B=nn(Lt(P.map(z=>Et(z))));if(!B)break t;sn({...O,geometry:B.geometry},R),N=!0}else{const B=O.geometry.geometries.filter(z=>z.type==="LineString"||z.type==="MultiLineString");B.length>0&&(R({...O,geometry:{type:"GeometryCollection",geometries:B}}),N=!0)}}if(!N){if(O.geometry.type==="Polygon"||O.geometry.type==="MultiPolygon")sn(O,R);else if(O.geometry.type==="LineString"||O.geometry.type==="MultiLineString"){R(O);break e}}if(!x&&!O.geometry.type.endsWith("Point"))break e;if(t instanceof Function){const P=t(i,O);P&&g.push(P)}else t&&g.push(typeof t=="object"?new e.Marker(t):I().setLngLat(O.center).addTo(i))}if(n)for(const N of C??[]){if(N===O)continue;let P;if(n instanceof Function){if(P=n(i,N),!P)continue}else P=(typeof n=="object"?new e.Marker(n):I(!0)).setLngLat(N.center).setPopup(new e.Popup({offset:[1,-27],closeButton:!1,closeOnMove:!0,className:"maptiler-gc-popup"}).setText(N.place_type[0]==="reverse"?N.place_name:N.place_name.replace(/,.*/,""))).addTo(i);const B=P.getElement();B.addEventListener("click",z=>{z.stopPropagation(),o==null||o({type:"markerClick",id:N.id})}),B.addEventListener("mouseenter",()=>{o==null||o({type:"markerMouseEnter",id:N.id}),P.togglePopup()}),B.addEventListener("mouseleave",()=>{o==null||o({type:"markerMouseLeave",id:N.id}),P.togglePopup()}),g.push(P)}}},setSelectedMarker(C){c&&c.getElement().classList.toggle("marker-selected",!1),c=C>-1?g[C]:void 0,c==null||c.getElement().classList.toggle("marker-selected",!0)},getCenterAndZoom(){const C=i.getCenter();return[i.getZoom(),C.lng,C.lat]}}}function ns(i,e,t){var k,I,C;class n{constructor(x,N){A(this,"type");A(this,"target");this.type=N,this.target=x}}class r extends n{constructor(N,P){super(N,"select");A(this,"feature");Object.assign(this,P)}}class u extends n{constructor(N,P){super(N,"featureslisted");A(this,"features");this.features=P}}class a extends n{constructor(N,P){super(N,"featuresmarked");A(this,"features");this.features=P}}class o extends n{constructor(N,P){super(N,"optionsvisibilitychange");A(this,"optionsVisible");this.optionsVisible=P}}class g extends n{constructor(N,P){super(N,"pick");A(this,"feature");this.feature=P}}class c extends n{constructor(N,P){super(N,"querychange");A(this,"query");this.query=P}}class E extends n{constructor(N,P,B){super(N,"response");A(this,"url");A(this,"featureCollection");this.url=P,this.featureCollection=B}}class _ extends n{constructor(N,P){super(N,"reversetoggle");A(this,"reverse");this.reverse=P}}class M extends i{constructor(N={}){super();Vt(this,k);Vt(this,I);Vt(this,C);kt(this,I,N)}onAddInt(N){const P=document.createElement("div");P.className="mapboxgl-ctrl-geocoder mapboxgl-ctrl maplibregl-ctrl-geocoder maplibregl-ctrl mapboxgl-ctrl-group";const{marker:B,showResultMarkers:z,flyTo:W,fullGeometryStyle:s,...l}=ue(this,I),f=typeof W=="boolean"?{}:W,h={mapController:an(N,e,B,z,f,f,s),flyTo:W===void 0?!0:!!W,apiKey:"",...t==null?void 0:t(N,P),...l};return h.apiKey||console.warn("No MapTiler Cloud API key was provided, some or all geocoding requests may fail"),kt(this,k,new kr({target:P,props:h})),ue(this,k).$on("select",d=>{this.fire(new r(this,d.detail))}),ue(this,k).$on("pick",d=>{this.fire(new g(this,d.detail.feature))}),ue(this,k).$on("featureslisted",d=>{this.fire(new u(this,d.detail.features))}),ue(this,k).$on("featuresmarked",d=>{this.fire(new a(this,d.detail.features))}),ue(this,k).$on("response",d=>{this.fire(new E(this,d.detail.url,d.detail.featureCollection))}),ue(this,k).$on("optionsvisibilitychange",d=>{this.fire(new o(this,d.detail.optionsVisible))}),ue(this,k).$on("reversetoggle",d=>{this.fire(new _(this,d.detail.reverse))}),ue(this,k).$on("querychange",d=>{this.fire(new c(this,d.detail.query))}),kt(this,C,P),P}on(N,P){return super.on(N,P)}once(N,P){return super.once(N,P)}off(N,P){return super.off(N,P)}listens(N){return super.listens(N)}setOptions(N){var l;Object.assign(ue(this,I),N);const{marker:P,showResultMarkers:B,flyTo:z,fullGeometryStyle:W,...s}=ue(this,I);(l=ue(this,k))==null||l.$set(s)}setQuery(N,P=!0){var B;(B=ue(this,k))==null||B.setQuery(N,P)}clearMap(){var N;(N=ue(this,k))==null||N.clearMap()}clearList(){var N;(N=ue(this,k))==null||N.clearList()}setReverseMode(N){var P;(P=ue(this,k))==null||P.$set({reverseActive:N})}focus(N){var P;(P=ue(this,k))==null||P.focus(N)}blur(){var N;(N=ue(this,k))==null||N.blur()}onRemove(){var N,P,B;(N=ue(this,k))==null||N.$destroy(),kt(this,k,void 0),(B=(P=ue(this,C))==null?void 0:P.parentNode)==null||B.removeChild(ue(this,C))}}return k=new WeakMap,I=new WeakMap,C=new WeakMap,{MapLibreBasedGeocodingControl:M,events:{SelectEvent:r,FeaturesListedEvent:u,FeaturesMarkedEvent:a,OptionsVisibilityChangeEvent:o,PickEvent:g,QueryChangeEvent:c,ResponseEvent:E,ReverseToggleEvent:_}}}const{MapLibreBasedGeocodingControl:rs,events:et}=ns(dt.Evented,dt);class ss extends rs{onAdd(e){return super.onAddInt(e)}}const os=et.SelectEvent,ls=et.FeaturesListedEvent,us=et.FeaturesMarkedEvent,as=et.OptionsVisibilityChangeEvent,fs=et.PickEvent,cs=et.QueryChangeEvent,hs=et.ResponseEvent,ds=et.ReverseToggleEvent;j.FeaturesListedEvent=ls,j.FeaturesMarkedEvent=us,j.GeocodingControl=ss,j.OptionsVisibilityChangeEvent=as,j.PickEvent=fs,j.QueryChangeEvent=cs,j.ResponseEvent=hs,j.ReverseToggleEvent=ds,j.SelectEvent=os,j.createMapLibreGlMapController=an,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"})}); +//# sourceMappingURL=maplibregl.umd.js.map diff --git a/inst/htmlwidgets/lib/maptiler-geocoding-control/style.css b/inst/htmlwidgets/lib/maptiler-geocoding-control/style.css new file mode 100644 index 0000000..c865c17 --- /dev/null +++ b/inst/htmlwidgets/lib/maptiler-geocoding-control/style.css @@ -0,0 +1 @@ +svg.svelte-d2loi5{display:block;fill:#e15042}.sprite-icon.svelte-w9y5n9.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75;background-repeat:no-repeat}li.svelte-w9y5n9.svelte-w9y5n9{text-align:left;cursor:default;display:grid;grid-template-columns:40px 1fr;color:var(--color-text);padding:8px 0;font-size:14px;line-height:18px;min-width:fit-content;outline:0}li.svelte-w9y5n9.svelte-w9y5n9:first-child{padding-top:10px}li.svelte-w9y5n9.svelte-w9y5n9:last-child{padding-bottom:10px}li.picked.svelte-w9y5n9.svelte-w9y5n9{background-color:#e7edff}li.picked.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#96a4c7;padding-left:4px}li.picked.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#96a4c7}li.selected.svelte-w9y5n9.svelte-w9y5n9{background-color:#f3f6ff}li.selected.svelte-w9y5n9.svelte-w9y5n9{animation:svelte-w9y5n9-backAndForth 5s linear infinite}li.selected.svelte-w9y5n9 .primary.svelte-w9y5n9{color:#2b8bfb}li.selected.svelte-w9y5n9 .secondary.svelte-w9y5n9{color:#a2adc7;padding-left:4px}li.selected.svelte-w9y5n9 .line2.svelte-w9y5n9{color:#a2adc7}li.svelte-w9y5n9>img.svelte-w9y5n9{align-self:center;justify-self:center;opacity:.75}.texts.svelte-w9y5n9.svelte-w9y5n9{padding:0 17px 0 0}.texts.svelte-w9y5n9>.svelte-w9y5n9{white-space:nowrap;display:block;min-width:fit-content}.primary.svelte-w9y5n9.svelte-w9y5n9{font-weight:600}.secondary.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7;padding-left:4px}.line2.svelte-w9y5n9.svelte-w9y5n9{color:#aeb6c7}@keyframes svelte-w9y5n9-backAndForth{0%{transform:translate(0)}10%{transform:translate(0)}45%{transform:translate(calc(-100% + 270px))}55%{transform:translate(calc(-100% + 270px))}90%{transform:translate(0)}to{transform:translate(0)}}div.svelte-1ocfouu{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);pointer-events:none;display:flex;align-items:center}.loading-icon.svelte-1ocfouu{animation:svelte-1ocfouu-rotate .8s infinite cubic-bezier(.45,.05,.55,.95)}@keyframes svelte-1ocfouu-rotate{0%{-webkit-transform:rotate(0);transform:rotate(0)}to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}svg.svelte-gzo3ar.svelte-gzo3ar{display:block;fill:#6b7c93;stroke:#6b7c93}.list-icon.svelte-gzo3ar.svelte-gzo3ar{grid-row:1/3;align-self:center;margin:8px}.in-map.svelte-gzo3ar.svelte-gzo3ar{height:30px}.maplibregl-canvas-container .marker-selected{z-index:1}.maplibregl-canvas-container svg.svelte-gzo3ar path.svelte-gzo3ar,.leaflet-map-pane svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#3170fe;stroke:#3170fe}.marker-selected svg.svelte-gzo3ar path.svelte-gzo3ar{fill:#98b7ff;stroke:#3170fe}.marker-reverse svg.svelte-gzo3ar path.svelte-gzo3ar{fill:silver;stroke:gray}.marker-interactive{cursor:pointer!important}.maptiler-gc-popup>.maplibregl-popup-content{padding:2px 8px}svg.svelte-en2qvf{display:block;fill:var(--color-icon-button)}circle.svelte-1aq105l{stroke-width:1.875;fill:none}path.svelte-1aq105l{stroke-width:1.875;stroke-linecap:round}svg.svelte-1aq105l{display:block;stroke:var(--color-icon-button)}form.svelte-bz0zu3.svelte-bz0zu3{font-family:Open Sans,Ubuntu,Helvetica Neue,Arial,Helvetica,sans-serif;position:relative;background-color:#fff;z-index:10;border-radius:4px;margin:0;transition:max-width .25s;box-shadow:0 2px 5px #33335926;--color-text:#444952;--color-icon-button:#444952}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3,form.svelte-bz0zu3 .svelte-bz0zu3:after,form.svelte-bz0zu3 .svelte-bz0zu3:before{box-sizing:border-box}form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:29px}form.can-collapse.svelte-bz0zu3 input.svelte-bz0zu3::placeholder{transition:opacity .25s;opacity:0}form.svelte-bz0zu3.svelte-bz0zu3,form.svelte-bz0zu3.svelte-bz0zu3:focus-within,form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px}form.svelte-bz0zu3 input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:focus-within input.svelte-bz0zu3::placeholder,form.svelte-bz0zu3:hover input.svelte-bz0zu3::placeholder{opacity:1}input.svelte-bz0zu3.svelte-bz0zu3{font:inherit;font-size:14px;flex-grow:1;min-height:29px;background-color:transparent;color:#444952;white-space:nowrap;overflow:hidden;border:0;margin:0;padding:0}input.svelte-bz0zu3.svelte-bz0zu3:focus{color:#444952;outline:0;outline:none;box-shadow:none}ul.svelte-bz0zu3.svelte-bz0zu3,div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{background-color:#fff;border-radius:4px;left:0;list-style:none;margin:0;padding:0;position:absolute;width:100%;top:calc(100% + 6px);overflow:hidden}ul.svelte-bz0zu3.svelte-bz0zu3{font-size:14px;line-height:16px;box-shadow:0 5px 10px #33335926}div.error.svelte-bz0zu3.svelte-bz0zu3,div.no-results.svelte-bz0zu3.svelte-bz0zu3{font:inherit;line-height:18px;font-size:12px;display:flex;gap:16px}div.error.svelte-bz0zu3.svelte-bz0zu3{padding:16px;font-weight:600;color:#e25041;background-color:#fbeae8}div.error.svelte-bz0zu3 div.svelte-bz0zu3{flex-grow:1}div.error.svelte-bz0zu3 svg{flex-shrink:0;width:20px;height:20px}div.error.svelte-bz0zu3 button.svelte-bz0zu3{flex-shrink:0}div.error.svelte-bz0zu3 button.svelte-bz0zu3>svg{width:13px;fill:#e25041}div.error.svelte-bz0zu3 button.svelte-bz0zu3:hover svg,div.error.svelte-bz0zu3 button.svelte-bz0zu3:active svg{fill:#444952}div.no-results.svelte-bz0zu3.svelte-bz0zu3{padding:14px 24px 14px 16px;font-weight:400;color:#6b7c93;box-shadow:0 5px 10px #33335926}div.no-results.svelte-bz0zu3 svg{margin-top:4px;flex-shrink:0;width:20px;height:20px;width:30px;height:30px}.leaflet-bottom ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-left ul.options.svelte-bz0zu3.svelte-bz0zu3,.maplibregl-ctrl-bottom-right ul.options.svelte-bz0zu3.svelte-bz0zu3{top:auto;bottom:calc(100% + 6px)}button.svelte-bz0zu3.svelte-bz0zu3{padding:0;margin:0;border:0;background-color:transparent;height:auto;width:auto}button.svelte-bz0zu3.svelte-bz0zu3:hover{background-color:transparent}button.svelte-bz0zu3:hover svg,button.svelte-bz0zu3:active svg{fill:#2b8bfb}.input-group.svelte-bz0zu3.svelte-bz0zu3{display:flex;align-items:stretch;gap:7px;padding-inline:8px;border-radius:4px;overflow:hidden}.input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{outline:#2b8bfb solid 2px}.search-button.svelte-bz0zu3.svelte-bz0zu3{flex-shrink:0}.maplibregl-ctrl-geocoder:not(.maptiler-ctrl) .search-button svg{width:12px!important;transform:translate(.5px)}.clear-button-container.svelte-bz0zu3.svelte-bz0zu3{display:flex;display:none;position:relative;align-items:stretch}.clear-button-container.displayable.svelte-bz0zu3.svelte-bz0zu3{display:flex;flex-shrink:0}.maplibregl-ctrl-geocoder{position:relative;z-index:3}.maptiler-ctrl:not(:empty){box-shadow:none}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3{padding-inline:8px;border:white solid 2px}.maptiler-ctrl .input-group.svelte-bz0zu3.svelte-bz0zu3:focus-within{border:#2b8bfb solid 2px;outline:0;outline:none}.maptiler-ctrl form.can-collapse.svelte-bz0zu3.svelte-bz0zu3{max-width:33px}.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:focus-within,.maptiler-ctrl form.svelte-bz0zu3.svelte-bz0zu3:hover{width:270px;max-width:270px} diff --git a/inst/htmlwidgets/lib/radius-mode/radius-mode.js b/inst/htmlwidgets/lib/radius-mode/radius-mode.js new file mode 100644 index 0000000..2b7b5bf --- /dev/null +++ b/inst/htmlwidgets/lib/radius-mode/radius-mode.js @@ -0,0 +1,311 @@ +// Radius/Circle drawing mode for Mapbox GL Draw +// Creates a circle by drawing from center to edge +(function (MapboxDraw) { + const DrawLine = MapboxDraw.modes.draw_line_string; + + // Utility function to create a vertex feature + const createVertex = function (parentId, coordinates, path, selected) { + return { + type: "Feature", + properties: { + meta: "vertex", + parent: parentId, + coord_path: path, + active: selected ? "true" : "false" + }, + geometry: { + type: "Point", + coordinates: coordinates + } + }; + }; + + // Utility function to calculate distance between two points in kilometers + const calculateDistance = function (coord1, coord2) { + const lat1 = coord1[1]; + const lon1 = coord1[0]; + const lat2 = coord2[1]; + const lon2 = coord2[0]; + + const R = 6371; // Radius of the Earth in kilometers + const dLat = (lat2 - lat1) * Math.PI / 180; + const dLon = (lon2 - lon1) * Math.PI / 180; + const a = + Math.sin(dLat/2) * Math.sin(dLat/2) + + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * + Math.sin(dLon/2) * Math.sin(dLon/2); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + const distance = R * c; + + return distance; + }; + + // Utility function to create a GeoJSON circle + const createGeoJSONCircle = function (center, radiusInKm, parentId, points) { + points = points || 64; + + const coords = { + latitude: center[1], + longitude: center[0] + }; + + const km = radiusInKm; + const ret = []; + const distanceX = km / (111.32 * Math.cos((coords.latitude * Math.PI) / 180)); + const distanceY = km / 110.574; + + let theta, x, y; + for (let i = 0; i < points; i++) { + theta = (i / points) * (2 * Math.PI); + x = distanceX * Math.cos(theta); + y = distanceY * Math.sin(theta); + + ret.push([coords.longitude + x, coords.latitude + y]); + } + ret.push(ret[0]); + + return { + type: "Feature", + geometry: { + type: "Polygon", + coordinates: [ret] + }, + properties: { + parent: parentId, + meta: "radius" + } + }; + }; + + // Utility function to format distance for display + const getDisplayMeasurements = function (distanceKm) { + let metricUnits = "m"; + let metricFormat = "0,0"; + let metricMeasurement; + + let standardUnits = "feet"; + let standardFormat = "0,0"; + let standardMeasurement; + + metricMeasurement = distanceKm * 1000; // Convert to meters + if (metricMeasurement >= 1000) { + metricMeasurement = metricMeasurement / 1000; + metricUnits = "km"; + metricFormat = "0.00"; + } + + standardMeasurement = distanceKm * 1000 * 3.28084; // Convert to feet + if (standardMeasurement >= 5280) { + standardMeasurement = standardMeasurement / 5280; + standardUnits = "mi"; + standardFormat = "0.00"; + } + + // Simple number formatting (without numeral.js dependency) + const formatNumber = function(num, format) { + if (format === "0,0") { + return Math.round(num).toLocaleString(); + } else if (format === "0.00") { + return num.toFixed(2); + } + return num.toString(); + }; + + return { + metric: formatNumber(metricMeasurement, metricFormat) + " " + metricUnits, + standard: formatNumber(standardMeasurement, standardFormat) + " " + standardUnits + }; + }; + + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RadiusMode = Object.assign({}, DrawLine); + + RadiusMode.onSetup = function (opts) { + const line = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "LineString", + coordinates: [] + } + }); + + this.addFeature(line); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.activateUIButton("line"); + this.setActionableState({ trash: true }); + + return { + line: line, + currentVertexPosition: 0, + direction: "forward" + }; + }; + + RadiusMode.onClick = function (state, e) { + // This ends the drawing after the user creates a second point + if (state.currentVertexPosition === 1) { + // Update the second coordinate in place, don't add at position 0 + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + return this.changeMode("simple_select", { featureIds: [state.line.id] }); + } + + this.updateUIClasses({ mouse: "add" }); + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + + if (state.direction === "forward") { + state.currentVertexPosition += 1; + state.line.updateCoordinate( + state.currentVertexPosition, + e.lngLat.lng, + e.lngLat.lat + ); + } else { + state.line.addCoordinate(0, e.lngLat.lng, e.lngLat.lat); + } + + return null; + }; + + RadiusMode.onMouseMove = function (state, e) { + if (state.currentVertexPosition === 1) { + state.line.updateCoordinate(1, e.lngLat.lng, e.lngLat.lat); + } + }; + + // Creates the final geojson circle polygon + RadiusMode.onStop = function (state) { + doubleClickZoom.enable(this); + this.activateUIButton(); + + // Check to see if we've deleted this feature + if (this.getFeature(state.line.id) === undefined) return; + + if (state.line.isValid()) { + const lineGeoJson = state.line.toGeoJSON(); + const coords = lineGeoJson.geometry.coordinates; + + if (coords.length >= 2) { + // Calculate radius in kilometers + const radiusKm = calculateDistance(coords[0], coords[1]); + + // Create the circle polygon + const circleFeature = createGeoJSONCircle(coords[0], radiusKm, state.line.id); + + // Add radius property for reference + circleFeature.properties.radius = (radiusKm * 1000).toFixed(1); + + // Remove the meta property that was interfering + delete circleFeature.properties.meta; + delete circleFeature.properties.parent; + + // Delete the temporary line first + this.deleteFeature([state.line.id], { silent: true }); + + // Add the circle feature to the draw instance + const circleDrawFeature = this.newFeature(circleFeature); + this.addFeature(circleDrawFeature); + + this.map.fire("draw.create", { + features: [circleDrawFeature.toGeoJSON()] + }); + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + } else { + this.deleteFeature([state.line.id], { silent: true }); + } + + this.changeMode("simple_select", {}, { silent: true }); + }; + + RadiusMode.toDisplayFeatures = function (state, geojson, display) { + const isActiveLine = geojson.properties.id === state.line.id; + geojson.properties.active = isActiveLine ? "true" : "false"; + + if (!isActiveLine) return display(geojson); + + // Only render the line if it has at least one real coordinate + if (geojson.geometry.coordinates.length < 2) return null; + + geojson.properties.meta = "feature"; + + // Display center vertex as a point feature + display(createVertex( + state.line.id, + geojson.geometry.coordinates[ + state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1 + ], + "" + (state.direction === "forward" + ? geojson.geometry.coordinates.length - 2 + : 1), + false + )); + + // Display the line as it is drawn + display(geojson); + + const coords = geojson.geometry.coordinates; + if (coords.length >= 2) { + const distanceKm = calculateDistance(coords[0], coords[1]); + const displayMeasurements = getDisplayMeasurements(distanceKm); + + // Create custom feature for the current pointer position + const currentVertex = { + type: "Feature", + properties: { + meta: "currentPosition", + radiusMetric: displayMeasurements.metric, + radiusStandard: displayMeasurements.standard, + parent: state.line.id + }, + geometry: { + type: "Point", + coordinates: coords[1] + } + }; + display(currentVertex); + + // Create custom feature for radius circle + const center = coords[0]; + const circleFeature = createGeoJSONCircle(center, distanceKm, state.line.id); + display(circleFeature); + } + + return null; + }; + + RadiusMode.onTrash = function (state) { + this.deleteFeature([state.line.id], { silent: true }); + this.changeMode("simple_select"); + }; + + MapboxDraw.modes.draw_radius = RadiusMode; +})(MapboxDraw); \ No newline at end of file diff --git a/inst/htmlwidgets/lib/rectangle-mode/rectangle-mode.js b/inst/htmlwidgets/lib/rectangle-mode/rectangle-mode.js new file mode 100644 index 0000000..73af6d6 --- /dev/null +++ b/inst/htmlwidgets/lib/rectangle-mode/rectangle-mode.js @@ -0,0 +1,124 @@ +// Rectangle drawing mode for Mapbox GL Draw +// Adapted from https://github.com/edgespatial/mapbox-gl-draw-rectangle-mode +(function (MapboxDraw) { + const doubleClickZoom = { + enable: function (ctx) { + setTimeout(function () { + if (!ctx.map || !ctx.map.doubleClickZoom) return; + if (ctx._ctx && ctx._ctx.store && ctx._ctx.store.getInitialConfigValue) { + if (ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) { + ctx.map.doubleClickZoom.enable(); + } + } + }, 0); + }, + disable: function (ctx) { + setTimeout(function () { + if (ctx.map && ctx.map.doubleClickZoom) { + ctx.map.doubleClickZoom.disable(); + } + }, 0); + } + }; + + const RectangleMode = { + onSetup: function (opts) { + const rectangle = this.newFeature({ + type: "Feature", + properties: {}, + geometry: { + type: "Polygon", + coordinates: [[]] + } + }); + + this.addFeature(rectangle); + this.clearSelectedFeatures(); + doubleClickZoom.disable(this); + this.updateUIClasses({ mouse: "add" }); + this.setActionableState({ trash: true }); + + return { + rectangle: rectangle + }; + }, + + onClick: function (state, e) { + // If we have a start point and click on a different point, complete the rectangle + if (state.startPoint && + (state.startPoint[0] !== e.lngLat.lng || state.startPoint[1] !== e.lngLat.lat)) { + this.updateUIClasses({ mouse: "pointer" }); + state.endPoint = [e.lngLat.lng, e.lngLat.lat]; + this.changeMode("simple_select", { featuresId: state.rectangle.id }); + return; + } + + // Set the start point + const startPoint = [e.lngLat.lng, e.lngLat.lat]; + state.startPoint = startPoint; + }, + + onMouseMove: function (state, e) { + // Update rectangle coordinates as the mouse moves + if (state.startPoint) { + const startX = state.startPoint[0]; + const startY = state.startPoint[1]; + const endX = e.lngLat.lng; + const endY = e.lngLat.lat; + + state.rectangle.updateCoordinate("0.0", startX, startY); + state.rectangle.updateCoordinate("0.1", endX, startY); + state.rectangle.updateCoordinate("0.2", endX, endY); + state.rectangle.updateCoordinate("0.3", startX, endY); + state.rectangle.updateCoordinate("0.4", startX, startY); + } + }, + + onKeyUp: function (state, e) { + if (e.keyCode === 27) { // Escape key + return this.changeMode("simple_select"); + } + }, + + onStop: function (state) { + doubleClickZoom.enable(this); + this.updateUIClasses({ mouse: "none" }); + this.activateUIButton(); + + if (this.getFeature(state.rectangle.id) !== undefined) { + // Remove the closing coordinate (duplicate of first) + state.rectangle.removeCoordinate("0.4"); + + if (state.rectangle.isValid()) { + this.map.fire("draw.create", { + features: [state.rectangle.toGeoJSON()] + }); + } else { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select", {}, { silent: true }); + } + } + }, + + toDisplayFeatures: function (state, geojson, display) { + const isActiveRectangle = geojson.properties.id === state.rectangle.id; + geojson.properties.active = isActiveRectangle ? "true" : "false"; + + if (!isActiveRectangle) { + return display(geojson); + } + + // Only display the rectangle if we have started drawing + if (state.startPoint) { + return display(geojson); + } + }, + + onTrash: function (state) { + this.deleteFeature([state.rectangle.id], { silent: true }); + this.changeMode("simple_select"); + } + }; + + MapboxDraw.modes.draw_rectangle = RectangleMode; +})(MapboxDraw); \ No newline at end of file diff --git a/inst/htmlwidgets/lib/turf/turf.min.js b/inst/htmlwidgets/lib/turf/turf.min.js new file mode 100644 index 0000000..635896d --- /dev/null +++ b/inst/htmlwidgets/lib/turf/turf.min.js @@ -0,0 +1,37 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).turf={})}(this,(function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}function u(t,e,n){return(e=y(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function l(t){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},l(t)}function h(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&p(t,e)}function c(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(c=function(){return!!t})()}function f(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}function g(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function p(t,e){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},p(t,e)}function v(t,e){return n(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,o,s,a=[],u=!0,l=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);u=!0);}catch(t){l=!0,i=t}finally{try{if(!u&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw i}}return a}}(t,e)||_(t,e)||g()}function d(t){return function(t){if(Array.isArray(t))return e(t)}(t)||f(t)||_(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function m(t){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},m(t)}function _(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var x=6371008.8,E={centimeters:100*x,centimetres:100*x,degrees:360/(2*Math.PI),feet:3.28084*x,inches:39.37*x,kilometers:x/1e3,kilometres:x/1e3,meters:x,metres:x,miles:x/1609.344,millimeters:1e3*x,millimetres:1e3*x,nauticalmiles:x/1852,radians:1,yards:1.0936*x},k={acres:247105e-9,centimeters:1e4,centimetres:1e4,feet:10.763910417,hectares:1e-4,inches:1550.003100006,kilometers:1e-6,kilometres:1e-6,meters:1,metres:1,miles:386e-9,nauticalmiles:2.9155334959812285e-7,millimeters:1e6,millimetres:1e6,yards:1.195990046};function b(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={type:"Feature"};return(0===n.id||n.id)&&(r.id=n.id),n.bbox&&(r.bbox=n.bbox),r.properties=e||{},r.geometry=t,r}function w(t,e){switch(t){case"Point":return I(e).geometry;case"LineString":return L(e).geometry;case"Polygon":return S(e).geometry;case"MultiPoint":return O(e).geometry;case"MultiLineString":return T(e).geometry;case"MultiPolygon":return R(e).geometry;default:throw new Error(t+" is invalid")}}function I(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("coordinates is required");if(!Array.isArray(t))throw new Error("coordinates must be an Array");if(t.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!U(t[0])||!U(t[1]))throw new Error("coordinates must contain numbers");return b({type:"Point",coordinates:t},e,n)}function N(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return I(t,e)})),n)}function S(t,e){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=a(t);try{for(i.s();!(n=i.n()).done;){var o=n.value;if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(var s=0;s2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return S(t,e)})),n)}function L(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(t.length<2)throw new Error("coordinates must be an array of two or more positions");return b({type:"LineString",coordinates:t},e,n)}function P(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return C(t.map((function(t){return L(t,e)})),n)}function C(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={type:"FeatureCollection"};return e.id&&(n.id=e.id),e.bbox&&(n.bbox=e.bbox),n.features=t,n}function T(t,e){return b({type:"MultiLineString",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function O(t,e){return b({type:"MultiPoint",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function R(t,e){return b({type:"MultiPolygon",coordinates:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function A(t,e){return b({type:"GeometryCollection",geometries:t},e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}function D(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e&&!(e>=0))throw new Error("precision must be a positive number");var n=Math.pow(10,e||0);return Math.round(t*n)/n}function F(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t*n}function q(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=E[e];if(!n)throw new Error(e+" units is invalid");return t/n}function V(t,e){return Y(q(t,e))}function G(t){var e=t%360;return e<0&&(e+=360),e}function B(t){return(t%=360)>180?t-360:t<-180?t+360:t}function Y(t){return 180*(t%(2*Math.PI))/Math.PI}function z(t){return t%360*Math.PI/180}function j(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"kilometers",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("length must be a positive number");return F(q(t,e),n)}function X(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"meters",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"kilometers";if(!(t>=0))throw new Error("area must be a positive number");var r=k[e];if(!r)throw new Error("invalid original units");var i=k[n];if(!i)throw new Error("invalid final units");return t/r*i}function U(t){return!isNaN(t)&&null!==t&&!Array.isArray(t)}function Z(t){return null!==t&&"object"===m(t)&&!Array.isArray(t)}function H(t){if(!t)throw new Error("bbox is required");if(!Array.isArray(t))throw new Error("bbox must be an Array");if(4!==t.length&&6!==t.length)throw new Error("bbox must be an Array of 4 or 6 numbers");t.forEach((function(t){if(!U(t))throw new Error("bbox must only contain numbers")}))}function W(t){if(!t)throw new Error("id is required");if(-1===["string","number"].indexOf(m(t)))throw new Error("id must be a number or a string")}var J=Object.freeze({__proto__:null,areaFactors:k,azimuthToBearing:B,bearingToAzimuth:G,convertArea:X,convertLength:j,degreesToRadians:z,earthRadius:x,factors:E,feature:b,featureCollection:C,geometry:w,geometryCollection:A,isNumber:U,isObject:Z,lengthToDegrees:V,lengthToRadians:q,lineString:L,lineStrings:P,multiLineString:T,multiPoint:O,multiPolygon:R,point:I,points:N,polygon:S,polygons:M,radiansToDegrees:Y,radiansToLength:F,round:D,validateBBox:H,validateId:W});function K(t){if(!t)throw new Error("coord is required");if(!Array.isArray(t)){if("Feature"===t.type&&null!==t.geometry&&"Point"===t.geometry.type)return d(t.geometry.coordinates);if("Point"===t.type)return d(t.coordinates)}if(Array.isArray(t)&&t.length>=2&&!Array.isArray(t[0])&&!Array.isArray(t[1]))return d(t);throw new Error("coord must be GeoJSON Point or an Array of numbers")}function Q(t){if(Array.isArray(t))return t;if("Feature"===t.type){if(null!==t.geometry)return t.geometry.coordinates}else if(t.coordinates)return t.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function $(t){if(t.length>1&&U(t[0])&&U(t[1]))return!0;if(Array.isArray(t[0])&&t[0].length)return $(t[0]);throw new Error("coordinates must only contain numbers")}function tt(t,e,n){if(!e||!n)throw new Error("type and name required");if(!t||t.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.type)}function et(t,e,n){if(!t)throw new Error("No feature passed");if(!n)throw new Error(".featureOf() requires a name");if(!t||"Feature"!==t.type||!t.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!t.geometry||t.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+t.geometry.type)}function nt(t,e,n){if(!t)throw new Error("No featureCollection passed");if(!n)throw new Error(".collectionOf() requires a name");if(!t||"FeatureCollection"!==t.type)throw new Error("Invalid input to "+n+", FeatureCollection required");var r,i=a(t.features);try{for(i.s();!(r=i.n()).done;){var o=r.value;if(!o||"Feature"!==o.type||!o.geometry)throw new Error("Invalid input to "+n+", Feature with geometry required");if(!o.geometry||o.geometry.type!==e)throw new Error("Invalid input to "+n+": must be a "+e+", given "+o.geometry.type)}}catch(t){i.e(t)}finally{i.f()}}function rt(t){return"Feature"===t.type?t.geometry:t}function it(t,e){return"FeatureCollection"===t.type?"FeatureCollection":"GeometryCollection"===t.type?"GeometryCollection":"Feature"===t.type&&null!==t.geometry?t.geometry.type:t.type}var ot=Object.freeze({__proto__:null,collectionOf:nt,containsNumber:$,featureOf:et,geojsonType:tt,getCoord:K,getCoords:Q,getGeom:rt,getType:it});function st(t,e){if(!0===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final)return function(t,e){var n=st(e,t);return n=(n+180)%360}(t,e);var n=K(t),r=K(e),i=z(n[0]),o=z(r[0]),s=z(n[1]),a=z(r[1]),u=Math.sin(o-i)*Math.cos(a),l=Math.cos(s)*Math.sin(a)-Math.sin(s)*Math.cos(a)*Math.cos(o-i);return Y(Math.atan2(u,l))}function at(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=K(t),o=z(i[0]),s=z(i[1]),a=z(n),u=q(e,r.units),l=Math.asin(Math.sin(s)*Math.cos(u)+Math.cos(s)*Math.sin(u)*Math.cos(a));return I([Y(o+Math.atan2(Math.sin(a)*Math.sin(u)*Math.cos(s),Math.cos(u)-Math.sin(s)*Math.sin(l))),Y(l)],r.properties)}function ut(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e),o=z(i[1]-r[1]),s=z(i[0]-r[0]),a=z(r[1]),u=z(i[1]),l=Math.pow(Math.sin(o/2),2)+Math.pow(Math.sin(s/2),2)*Math.cos(a)*Math.cos(u);return F(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)),n.units)}function lt(t,e){var n;return(n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).final?ht(K(e),K(t)):ht(K(t),K(e)))>180?-(360-n):n}function ht(t,e){var n=z(t[1]),r=z(e[1]),i=z(e[0]-t[0]);i>Math.PI&&(i-=2*Math.PI),i<-Math.PI&&(i+=2*Math.PI);var o=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(n/2+Math.PI/4));return(Y(Math.atan2(i,o))+360)%360}function ct(t,e,n){if(null!==t)for(var r,i,o,s,a,u,l,h,c=0,f=0,g=t.type,p="FeatureCollection"===g,v="Feature"===g,d=p?t.features.length:1,y=0;ya||f>u||g>l)return s=o,a=n,u=f,l=g,void(i=0);var p=L([s,o],t.properties);if(!1===e(p,n,r,g,i))return!1;i++,s=o}))&&void 0}}}))}function bt(t,e,n){var r=n,i=!1;return kt(t,(function(t,o,s,a,u){r=!1===i&&void 0===n?t:e(r,t,o,s,a,u),i=!0})),r}function wt(t,e){if(!t)throw new Error("geojson is required");xt(t,(function(t,n,r){if(null!==t.geometry){var i=t.geometry.type,o=t.geometry.coordinates;switch(i){case"LineString":if(!1===e(t,n,r,0,0))return!1;break;case"Polygon":for(var s=0;s0){e+=Math.abs(Ot(t[0]));for(var n=1;n=e?(r+2)%e:r+2],a=i[0]*Tt,u=o[1]*Tt;n+=(s[0]*Tt-a)*Math.sin(u),r++}return n*Ct}function Rt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=t.bbox&&!0!==e.recompute)return t.bbox;var n=[1/0,1/0,-1/0,-1/0];return ct(t,(function(t){n[0]>t[0]&&(n[0]=t[0]),n[1]>t[1]&&(n[1]=t[1]),n[2]e[2]&&(n|=2),t[1]e[3]&&(n|=8),n}function qt(t,e){var n,r=[],i=a(t);try{for(i.s();!(n=i.n()).done;){var o=At(n.value,e);o.length>0&&(o[0][0]===o[o.length-1][0]&&o[0][1]===o[o.length-1][1]||o.push(o[0]),o.length>=4&&r.push(o))}}catch(t){i.e(t)}finally{i.f()}return r}function Vt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Number(t[0]),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]);if(6===t.length)throw new Error("@turf/bbox-polygon does not support BBox with 6 positions");var s=[n,r];return S([[s,[i,r],[i,o],[n,o],s]],e.properties,{bbox:t,id:e.id})}var Gt=function(){return s((function t(e){i(this,t),this.points=e.points||[],this.duration=e.duration||1e4,this.sharpness=e.sharpness||.85,this.centers=[],this.controls=[],this.stepLength=e.stepLength||60,this.length=this.points.length,this.delay=0;for(var n=0;nt&&(e.push(r),n=i)}return e}},{key:"vector",value:function(t){var e=this.pos(t+10),n=this.pos(t-10);return{angle:180*Math.atan2(e.y-n.y,e.x-n.x)/3.14,speed:Math.sqrt((n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y)+(n.z-e.z)*(n.z-e.z))}}},{key:"pos",value:function(t){var e=t-this.delay;e<0&&(e=0),e>this.duration&&(e=this.duration-1);var n=e/this.duration;if(n>=1)return this.points[this.length-1];var r=Math.floor((this.points.length-1)*n);return function(t,e,n,r,i){var o=function(t){var e=t*t,n=e*t;return[n,3*e*(1-t),3*t*(1-t)*(1-t),(1-t)*(1-t)*(1-t)]}(t),s={x:i.x*o[0]+r.x*o[1]+n.x*o[2]+e.x*o[3],y:i.y*o[0]+r.y*o[1]+n.y*o[2]+e.y*o[3],z:i.z*o[0]+r.z*o[1]+n.z*o[2]+e.z*o[3]};return s}((this.length-1)*n-r,this.points[r],this.controls[r][1],this.controls[r+1][0],this.points[r+1])}}])}();function Bt(t){for(var e,n,r=Q(t),i=0,o=1;o0}function Yt(t,e){for(var n=0,r=0,i=0,o=0,s=0,a=0,u=0,l=0,h=null,c=null,f=t[0],g=t[1],p=e.length;n0&&l>0)a=l,s=(h=c)[0]-f;else{if(u=c[0]-t[0],l>0&&a<=0){if((o=s*l-u*a)>0)i+=1;else if(0===o)return 0}else if(a>0&&l<=0){if((o=s*l-u*a)<0)i+=1;else if(0===o)return 0}else if(0===l&&a<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&l<0){if(0===(o=s*l-u*a))return 0}else if(0===a&&0===l){if(u<=0&&s>=0)return 0;if(s<=0&&u>=0)return 0}h=c,a=l,s=u}}return i%2!=0}function zt(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("point is required");if(!e)throw new Error("polygon is required");var r=K(t),i=rt(e),o=i.type,s=e.bbox,a=i.coordinates;if(s&&!1===function(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}(r,s))return!1;"Polygon"===o&&(a=[a]);for(var u=!1,l=0;l2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=Q(e),o=0;oi)return!1}else if(0!==g)return!1;return Math.abs(c)===Math.abs(f)&&0===Math.abs(c)?!r&&(n[0]===t[0]&&n[1]===t[1]):r?"start"===r?Math.abs(c)>=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o0?u<=s&&s=Math.abs(f)?c>0?a0?u=Math.abs(f)?c>0?a<=o&&o<=l:l<=o&&o<=a:f>0?u<=s&&s<=h:h<=s&&s<=u}function Ut(t,e){if("Feature"===t.type&&null===t.geometry)return!1;if("Feature"===e.type&&null===e.geometry)return!1;if(!Zt(Rt(t),Rt(e)))return!1;var n,r=a(rt(e).coordinates);try{for(r.s();!(n=r.n()).done;){var i,o=a(n.value);try{for(o.s();!(i=o.n()).done;){if(!zt(i.value,t))return!1}}catch(t){o.e(t)}finally{o.f()}}}catch(t){r.e(t)}finally{r.f()}return!0}function Zt(t,e){return!(t[0]>e[0])&&(!(t[2]e[1])&&!(t[3]0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Kt;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function Kt(t,e){return te?1:0}function Qt(t,e){return t.p.x>e.p.x?1:t.p.xe.p.y?1:-1:1}function $t(t,e){return t.rightSweepEvent.p.x>e.rightSweepEvent.p.x?1:t.rightSweepEvent.p.x0?(h.isLeftEndpoint=!0,l.isLeftEndpoint=!1):(l.isLeftEndpoint=!0,h.isLeftEndpoint=!1),e.push(l),e.push(h),s=a,re+=1}}ee+=1}var oe=s((function t(e){i(this,t),this.leftSweepEvent=e,this.rightSweepEvent=e.otherEvent}));function se(t,e){if(null===t||null===e)return!1;if(t.leftSweepEvent.ringId===e.leftSweepEvent.ringId&&(t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.leftSweepEvent)||t.rightSweepEvent.isSamePoint(e.rightSweepEvent)||t.leftSweepEvent.isSamePoint(e.leftSweepEvent)||t.leftSweepEvent.isSamePoint(e.rightSweepEvent)))return!1;var n=t.leftSweepEvent.p.x,r=t.leftSweepEvent.p.y,i=t.rightSweepEvent.p.x,o=t.rightSweepEvent.p.y,s=e.leftSweepEvent.p.x,a=e.leftSweepEvent.p.y,u=e.rightSweepEvent.p.x,l=e.rightSweepEvent.p.y,h=(l-a)*(i-n)-(u-s)*(o-r),c=(u-s)*(r-a)-(l-a)*(n-s),f=(i-n)*(r-a)-(o-r)*(n-s);if(0===h)return!1;var g=c/h,p=f/h;return g>=0&&g<=1&&p>=0&&p<=1&&[n+g*(i-n),r+g*(o-r)]}var ae=function(t,e){var n=new Jt([],Qt);return function(t,e){if("FeatureCollection"===t.type)for(var n=t.features,r=0;r2&&void 0!==arguments[2]?arguments[2]:{},r=n.removeDuplicates,i=void 0===r||r,o=n.ignoreSelfIntersections,s=void 0===o||o,a=[];"FeatureCollection"===t.type?a=a.concat(t.features):"Feature"===t.type?a.push(t):"LineString"!==t.type&&"Polygon"!==t.type&&"MultiLineString"!==t.type&&"MultiPolygon"!==t.type||a.push(b(t)),"FeatureCollection"===e.type?a=a.concat(e.features):"Feature"===e.type?a.push(e):"LineString"!==e.type&&"Polygon"!==e.type&&"MultiLineString"!==e.type&&"MultiPolygon"!==e.type||a.push(b(e));var u=ae(C(a),s),l=[];if(i){var h={};u.forEach((function(t){var e=t.join(",");h[e]||(h[e]=!0,l.push(t))}))}else l=u;return C(l.map((function(t){return I(t)})))}function le(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t);switch(e.properties||"Feature"!==t.type||(e.properties=t.properties),n.type){case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{};return he(r,i)}(n,e);case"MultiPolygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rt(t),r=n.coordinates,i=e.properties?e.properties:"Feature"===t.type?t.properties:{},o=[];return r.forEach((function(t){o.push(he(t,i))})),C(o)}(n,e);default:throw new Error("invalid poly")}}function he(t,e){return t.length>1?T(t,e):L(t[0],e)}function ce(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;switch(i){case"MultiPoint":switch(o){case"LineString":return fe(n,r);case"Polygon":return pe(n,r);default:throw new Error("feature2 "+o+" geometry not supported")}case"LineString":switch(o){case"MultiPoint":return fe(r,n);case"LineString":return function(t,e){if(ue(t,e).features.length>0)for(var n=0;n0}function pe(t,e){for(var n=!1,r=!1,i=t.coordinates.length,o=0;o=Math.abs(a)?s>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:a>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1]:Math.abs(s)>=Math.abs(a)?s>0?t[0]0?t[1]2&&void 0!==arguments[2]?arguments[2]:{ignoreSelfIntersections:!0}).ignoreSelfIntersections,r=void 0===n||n,i=!0;return xt(t,(function(t){xt(e,(function(e){if(!1===i)return!1;i=function(t,e,n){switch(t.type){case"Point":switch(e.type){case"Point":return r=t.coordinates,i=e.coordinates,!(r[0]===i[0]&&r[1]===i[1]);case"LineString":return!ye(e,t);case"Polygon":return!zt(t,e)}break;case"LineString":switch(e.type){case"Point":return!ye(t,e);case"LineString":return!function(t,e,n){var r=ue(t,e,{ignoreSelfIntersections:n});if(r.features.length>0)return!0;return!1}(t,e,n);case"Polygon":return!me(e,t,n)}break;case"Polygon":switch(e.type){case"Point":return!zt(e,t);case"LineString":return!me(t,e,n);case"Polygon":return!function(t,e,n){var r,i=a(t.coordinates[0]);try{for(i.s();!(r=i.n()).done;){if(zt(r.value,e))return!0}}catch(t){i.e(t)}finally{i.f()}var o,s=a(e.coordinates[0]);try{for(s.s();!(o=s.n()).done;){if(zt(o.value,t))return!0}}catch(t){s.e(t)}finally{s.f()}var u=ue(le(t),le(e),{ignoreSelfIntersections:n});if(u.features.length>0)return!0;return!1}(e,t,n)}}var r,i;return!1}(t.geometry,e.geometry,r)}))})),i}function ye(t,e){for(var n=0;n0}function _e(t,e,n){var r=n[0]-t[0],i=n[1]-t[1],o=e[0]-t[0],s=e[1]-t[1];return 0==r*s-i*o&&(Math.abs(o)>=Math.abs(s)?o>0?t[0]<=n[0]&&n[0]<=e[0]:e[0]<=n[0]&&n[0]<=t[0]:s>0?t[1]<=n[1]&&n[1]<=e[1]:e[1]<=n[1]&&n[1]<=t[1])}var xe=Object.defineProperty,Ee=function(t,e){return xe(t,"name",{value:e,configurable:!0})},ke=function(){return s((function t(e){var n,r,o;i(this,t),this.direction=!1,this.compareProperties=!0,this.precision=Math.pow(10,-(null!=(n=null==e?void 0:e.precision)?n:17)),this.direction=null!=(r=null==e?void 0:e.direction)&&r,this.compareProperties=null==(o=null==e?void 0:e.compareProperties)||o}),[{key:"compare",value:function(t,e){var n=this;if(t.type!==e.type)return!1;if(!we(t,e))return!1;switch(t.type){case"Point":return this.compareCoord(t.coordinates,e.coordinates);case"LineString":return this.compareLine(t.coordinates,e.coordinates);case"Polygon":return this.comparePolygon(t,e);case"GeometryCollection":return this.compareGeometryCollection(t,e);case"Feature":return this.compareFeature(t,e);case"FeatureCollection":return this.compareFeatureCollection(t,e);default:if(t.type.startsWith("Multi")){var r=Ie(t),i=Ie(e);return r.every((function(t){return i.some((function(e){return n.compare(t,e)}))}))}}return!1}},{key:"compareCoord",value:function(t,e){var n=this;return t.length===e.length&&t.every((function(t,r){return Math.abs(t-e[r])2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!we(t,e))return!1;var i=t,o=e;if(r&&!this.compareCoord(i[0],o[0])){var s=this.fixStartIndex(o,i);if(!s)return!1;o=s}var a=this.compareCoord(i[n],o[n]);return this.direction||a?this.comparePath(i,o):!!this.compareCoord(i[n],o[o.length-(1+n)])&&this.comparePath(i.slice().reverse(),o)}},{key:"fixStartIndex",value:function(t,e){for(var n,r=-1,i=0;i=0&&(n=[].concat(t.slice(r,t.length),t.slice(1,r+1))),n}},{key:"comparePath",value:function(t,e){var n=this;return t.every((function(t,r){return n.compareCoord(t,e[r])}))}},{key:"comparePolygon",value:function(t,e){var n=this;if(this.compareLine(t.coordinates[0],e.coordinates[0],1,!0)){var r=t.coordinates.slice(1,t.coordinates.length),i=e.coordinates.slice(1,e.coordinates.length);return r.every((function(t){return i.some((function(e){return n.compareLine(t,e,1,!0)}))}))}return!1}},{key:"compareGeometryCollection",value:function(t,e){var n=this;return we(t.geometries,e.geometries)&&this.compareBBox(t,e)&&t.geometries.every((function(t,r){return n.compare(t,e.geometries[r])}))}},{key:"compareFeature",value:function(t,e){return t.id===e.id&&(!this.compareProperties||Se(t.properties,e.properties))&&this.compareBBox(t,e)&&this.compare(t.geometry,e.geometry)}},{key:"compareFeatureCollection",value:function(t,e){var n=this;return we(t.features,e.features)&&this.compareBBox(t,e)&&t.features.every((function(t,r){return n.compare(t,e.features[r])}))}},{key:"compareBBox",value:function(t,e){return Boolean(!t.bbox&&!e.bbox)||!(!t.bbox||!e.bbox)&&this.compareCoord(t.bbox,e.bbox)}}])}();Ee(ke,"GeojsonEquality");var be=ke;function we(t,e){return t.coordinates?t.coordinates.length===e.coordinates.length:t.length===e.length}function Ie(t){return t.coordinates.map((function(e){return{type:t.type.replace("Multi",""),coordinates:e}}))}function Ne(t,e,n){return new be(n).compare(t,e)}function Se(t,e){if(null===t&&null===e)return!0;if(null===t||null===e)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(var i=0,o=n;i1&&void 0!==arguments[1]?arguments[1]:{},n="object"===m(e)?e.mutate:e;if(!t)throw new Error("geojson is required");var r=it(t),i=[];switch(r){case"LineString":i=Pe(t,r);break;case"MultiLineString":case"Polygon":Q(t).forEach((function(t){i.push(Pe(t,r))}));break;case"MultiPolygon":Q(t).forEach((function(t){var e=[];t.forEach((function(t){e.push(Pe(t,r))})),i.push(e)}));break;case"Point":return t;case"MultiPoint":var o={};Q(t).forEach((function(t){var e=t.join("-");Object.prototype.hasOwnProperty.call(o,e)||(i.push(t),o[e]=!0)}));break;default:throw new Error(r+" geometry not supported")}return t.coordinates?!0===n?(t.coordinates=i,t):{type:r,coordinates:i}:!0===n?(t.geometry.coordinates=i,t):b({type:r,coordinates:i},t.properties,{bbox:t.bbox,id:t.id})}function Pe(t,e){var n=Q(t);if(2===n.length&&!Ce(n[0],n[1]))return n;var r=[],i=n.length-1,o=r.length;r.push(n[0]);for(var s=1;s2&&Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1))}if(r.push(n[n.length-1]),o=r.length,("Polygon"===e||"MultiPolygon"===e)&&Ce(n[0],n[n.length-1])&&o<4)throw new Error("invalid polygon");return"LineString"===e&&o<3||Te(r[o-3],r[o-1],r[o-2])&&r.splice(r.length-2,1),r}function Ce(t,e){return t[0]===e[0]&&t[1]===e[1]}function Te(t,e,n){var r=n[0],i=n[1],o=t[0],s=t[1],a=e[0],u=e[1],l=a-o,h=u-s;return 0===(r-o)*h-(i-s)*l&&(Math.abs(l)>=Math.abs(h)?l>0?o<=r&&r<=a:a<=r&&r<=o:h>0?s<=i&&i<=u:u<=i&&i<=s)}function Oe(t,e){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).ignoreSelfIntersections,r=void 0===n||n,i=!1;return xt(t,(function(t){xt(e,(function(e){if(!0===i)return!0;i=!de(t.geometry,e.geometry,{ignoreSelfIntersections:r})}))})),i}function Re(t,e,n,r,i){Ae(t,e,n||0,r||t.length-1,i||Fe)}function Ae(t,e,n,r,i){for(;r>n;){if(r-n>600){var o=r-n+1,s=e-n+1,a=Math.log(o),u=.5*Math.exp(2*a/3),l=.5*Math.sqrt(a*u*(o-u)/o)*(s-o/2<0?-1:1);Ae(t,e,Math.max(n,Math.floor(e-s*u/o+l)),Math.min(r,Math.floor(e+(o-s)*u/o+l)),i)}var h=t[e],c=n,f=r;for(De(t,n,e),i(t[r],h)>0&&De(t,n,r);c0;)f--}0===i(t[n],h)?De(t,n,f):De(t,++f,r),f<=e&&(n=f+1),e<=f&&(r=f-1)}}function De(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function Fe(t,e){return te?1:0}var qe=function(){return s((function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:9;i(this,t),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}),[{key:"all",value:function(){return this._all(this.data,[])}},{key:"search",value:function(t){var e=this.data,n=[];if(!He(t,e))return n;for(var r=this.toBBox,i=[];e;){for(var o=0;o=0&&i[e].children.length>this._maxEntries;)this._split(i,e),e--;this._adjustParentBBoxes(r,i,e)}},{key:"_split",value:function(t,e){var n=t[e],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=We(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,Ge(n,this.toBBox),Ge(s,this.toBBox),e?t[e-1].children.push(s):this._splitRoot(n,s)}},{key:"_splitRoot",value:function(t,e){this.data=We([t,e]),this.data.height=t.height+1,this.data.leaf=!1,Ge(this.data,this.toBBox)}},{key:"_chooseSplitIndex",value:function(t,e,n){for(var r,i,o,s,a,u,l,h=1/0,c=1/0,f=e;f<=n-e;f++){var g=Be(t,0,f,this.toBBox),p=Be(t,f,n,this.toBBox),v=(i=g,o=p,s=void 0,a=void 0,u=void 0,l=void 0,s=Math.max(i.minX,o.minX),a=Math.max(i.minY,o.minY),u=Math.min(i.maxX,o.maxX),l=Math.min(i.maxY,o.maxY),Math.max(0,u-s)*Math.max(0,l-a)),d=Xe(g)+Xe(p);v=e;h--){var c=t.children[h];Ye(s,t.leaf?i(c):c),a+=Ue(s)}return a}},{key:"_adjustParentBBoxes",value:function(t,e,n){for(var r=n;r>=0;r--)Ye(e[r],t)}},{key:"_condense",value:function(t){for(var e,n=t.length-1;n>=0;n--)0===t[n].children.length?n>0?(e=t[n-1].children).splice(e.indexOf(t[n]),1):this.clear():Ge(t[n],this.toBBox)}}])}();function Ve(t,e,n){if(!n)return e.indexOf(t);for(var r=0;r=t.minX&&e.maxY>=t.minY}function We(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Je(t,e,n,r,i){for(var o=[e,n];o.length;)if(!((n=o.pop())-(e=o.pop())<=r)){var s=e+Math.ceil((n-e)/r/2)*r;Re(t,s,e,n,i),o.push(e,s,s,n)}}var Ke=Object.freeze({__proto__:null,default:qe});function Qe(t){var e=new qe(t);return e.insert=function(t){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.insert.call(this,t)},e.load=function(t){var e=[];return Array.isArray(t)?t.forEach((function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})):vt(t,(function(t){if("Feature"!==t.type)throw new Error("invalid features");t.bbox=t.bbox?t.bbox:Rt(t),e.push(t)})),qe.prototype.load.call(this,e)},e.remove=function(t,e){if("Feature"!==t.type)throw new Error("invalid feature");return t.bbox=t.bbox?t.bbox:Rt(t),qe.prototype.remove.call(this,t,e)},e.clear=function(){return qe.prototype.clear.call(this)},e.search=function(t){return C(qe.prototype.search.call(this,this.toBBox(t)))},e.collides=function(t){return qe.prototype.collides.call(this,this.toBBox(t))},e.all=function(){return C(qe.prototype.all.call(this))},e.toJSON=function(){return qe.prototype.toJSON.call(this)},e.fromJSON=function(t){return qe.prototype.fromJSON.call(this,t)},e.toBBox=function(t){var e;if(t.bbox)e=t.bbox;else if(Array.isArray(t)&&4===t.length)e=t;else if(Array.isArray(t)&&6===t.length)e=[t[0],t[1],t[3],t[4]];else if("Feature"===t.type)e=Rt(t);else{if("FeatureCollection"!==t.type)throw new Error("invalid geojson");e=Rt(t)}return{minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}},e}function $e(t){if(!t)throw new Error("geojson is required");var e=[];return xt(t,(function(t){!function(t,e){var n=[],r=t.geometry;if(null!==r){switch(r.type){case"Polygon":n=Q(r);break;case"LineString":n=[Q(r)]}n.forEach((function(n){var r=function(t,e){var n=[];return t.reduce((function(t,r){var i=L([t,r],e);return i.bbox=function(t,e){var n=t[0],r=t[1],i=e[0],o=e[1],s=ni?n:i,l=r>o?r:o;return[s,a,u,l]}(t,r),n.push(i),r})),n}(n,t.properties);r.forEach((function(t){t.id=e.length,e.push(t)}))}))}}(t,e)})),C(e)}var tn,en,nn=Object.defineProperty,rn=Object.defineProperties,on=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertySymbols,an=Object.prototype.hasOwnProperty,un=Object.prototype.propertyIsEnumerable,ln=function(t,e,n){return e in t?nn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},hn=function(t,e){for(var n in e||(e={}))an.call(e,n)&&ln(t,n,e[n]);if(sn){var r,i=a(sn(e));try{for(i.s();!(r=i.n()).done;){n=r.value;un.call(e,n)&&ln(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},cn=function(t,e){return rn(t,on(e))};function fn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t||!e)throw new Error("lines and pt are required arguments");var r=K(e),i=I([1/0,1/0],{dist:1/0,index:-1,multiFeatureIndex:-1,location:-1}),o=0;return xt(t,(function(t,s,a){for(var u=Q(t),l=0;lR||pn(p,f)>R?ut(dn(f),dn(g))<=ut(dn(f),dn(p))?[dn(g),!0,!1]:[dn(p),!1,!0]:[dn(f),!1,!1]}function mn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function _n(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var n=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,r.get?r:{enumerable:!0,get:function(){return t[e]}})})),n}var xn=(en||(en=1,tn=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==m(e)&&"object"==m(n)){if(e.constructor!==n.constructor)return!1;var r,i,o;if(Array.isArray(e)){if((r=e.length)!=n.length)return!1;for(i=r;0!=i--;)if(!t(e[i],n[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((r=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(i=r;0!=i--;)if(!Object.prototype.hasOwnProperty.call(n,o[i]))return!1;for(i=r;0!=i--;){var s=o[i];if(!t(e[s],n[s]))return!1}return!0}return e!=e&&n!=n}),tn),En=mn(xn);function kn(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r,i=n.tolerance||0,o=[],s=Qe(),a=$e(t);s.load(a);var u=[];return kt(e,(function(t){var e=!1;t&&(vt(s.search(t),(function(n){if(!1===e){var o=Q(t).sort(),s=Q(n).sort();if(En(o,s))e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(o[0],n)&&jt(o[1],n):fn(n,o[0]).properties.dist<=i&&fn(n,o[1]).properties.dist<=i)e=!0,r=r?bn(r,t)||r:t;else if(0===i?jt(s[0],t)&&jt(s[1],t):fn(t,s[0]).properties.dist<=i&&fn(t,s[1]).properties.dist<=i)if(r){var a=bn(r,n);a?r=a:u.push(n)}else r=n}})),!1===e&&r&&(o.push(r),u.length&&(o=o.concat(u),u=[]),r=void 0))})),r&&o.push(r),C(o)}function bn(t,e){var n=Q(e),r=Q(t),i=r[0],o=r[r.length-1],s=t.geometry.coordinates;if(En(n[0],i))s.unshift(n[1]);else if(En(n[0],o))s.push(n[1]);else if(En(n[1],i))s.unshift(n[0]);else{if(!En(n[1],o))return;s.push(n[0])}return t}function wn(t,e){var n=G(lt(t[0],t[1])),r=G(lt(e[0],e[1]));return n===r||(r-n)%180==0}function In(t,e){if(t.geometry&&t.geometry.type)return t.geometry.type;if(t.type)return t.type;throw new Error("Invalid GeoJSON object for "+e)}function Nn(t,e){return!!Sn(e.coordinates[0],t.coordinates)||!!Sn(e.coordinates[e.coordinates.length-1],t.coordinates)}function Sn(t,e){return t[0]===e[0]&&t[1]===e[1]}function Mn(t){return t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]}function Ln(t){for(var e=0;ee[0])&&(!(t[2]e[1])&&!(t[3]1&&void 0!==arguments[1]?arguments[1]:{},n=Rt(t);return I([(n[0]+n[2])/2,(n[1]+n[3])/2],e.properties,e)}var Dn,Fn={exports:{}};var qn=(Dn||(Dn=1,function(t,e){t.exports=function(){function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}var y=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getEndCapStyle",value:function(){return this._endCapStyle}},{key:"isSingleSided",value:function(){return this._isSingleSided}},{key:"setQuadrantSegments",value:function(t){this._quadrantSegments=t,0===this._quadrantSegments&&(this._joinStyle=e.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=e.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),t<=0&&(this._quadrantSegments=1),this._joinStyle!==e.JOIN_ROUND&&(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS)}},{key:"getJoinStyle",value:function(){return this._joinStyle}},{key:"setJoinStyle",value:function(t){this._joinStyle=t}},{key:"setSimplifyFactor",value:function(t){this._simplifyFactor=t<0?0:t}},{key:"getSimplifyFactor",value:function(){return this._simplifyFactor}},{key:"getQuadrantSegments",value:function(){return this._quadrantSegments}},{key:"setEndCapStyle",value:function(t){this._endCapStyle=t}},{key:"getMitreLimit",value:function(){return this._mitreLimit}},{key:"setMitreLimit",value:function(t){this._mitreLimit=t}},{key:"setSingleSided",value:function(t){this._isSingleSided=t}}],[{key:"constructor_",value:function(){if(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=e.CAP_ROUND,this._joinStyle=e.JOIN_ROUND,this._mitreLimit=e.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=e.DEFAULT_SIMPLIFY_FACTOR,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.setQuadrantSegments(t)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.setQuadrantSegments(n),this.setEndCapStyle(r)}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];this.setQuadrantSegments(i),this.setEndCapStyle(o),this.setJoinStyle(s),this.setMitreLimit(a)}}},{key:"bufferDistanceError",value:function(t){var e=Math.PI/2/t;return 1-Math.cos(e/2)}}]),e}();y.CAP_ROUND=1,y.CAP_FLAT=2,y.CAP_SQUARE=3,y.JOIN_ROUND=1,y.JOIN_MITRE=2,y.JOIN_BEVEL=3,y.DEFAULT_QUADRANT_SEGMENTS=8,y.DEFAULT_MITRE_LIMIT=5,y.DEFAULT_SIMPLIFY_FACTOR=.01;var _=function(e){r(o,e);var i=c(o);function o(e){var n;return t(this,o),(n=i.call(this,e)).name=Object.keys({Exception:o})[0],n}return n(o,[{key:"toString",value:function(){return this.message}}]),o}(u(Error)),x=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({IllegalArgumentException:i})[0],r}return i}(_),E=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}();function k(){}function b(){}function w(){}var I,N,S,M,L,P,C,T,O=function(){function e(){t(this,e)}return n(e,null,[{key:"equalsWithTolerance",value:function(t,e,n){return Math.abs(t-e)<=n}}]),e}(),R=function(){function e(n,r){t(this,e),this.low=r||0,this.high=n||0}return n(e,null,[{key:"toBinaryString",value:function(t){var e,n="";for(e=2147483648;e>0;e>>>=1)n+=(t.high&e)===e?"1":"0";for(e=2147483648;e>0;e>>>=1)n+=(t.low&e)===e?"1":"0";return n}}]),e}();function A(){}function D(){}A.NaN=NaN,A.isNaN=function(t){return Number.isNaN(t)},A.isInfinite=function(t){return!Number.isFinite(t)},A.MAX_VALUE=Number.MAX_VALUE,A.POSITIVE_INFINITY=Number.POSITIVE_INFINITY,A.NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,"function"==typeof Float64Array&&"function"==typeof Int32Array?(P=2146435072,C=new Float64Array(1),T=new Int32Array(C.buffer),A.doubleToLongBits=function(t){C[0]=t;var e=0|T[0],n=0|T[1];return(n&P)===P&&0!=(1048575&n)&&0!==e&&(e=0,n=2146959360),new R(n,e)},A.longBitsToDouble=function(t){return T[0]=t.low,T[1]=t.high,C[0]}):(I=1023,N=Math.log2,S=Math.floor,M=Math.pow,L=function(){for(var t=53;t>0;t--){var e=M(2,t)-1;if(S(N(e))+1===t)return e}return 0}(),A.doubleToLongBits=function(t){var e,n,r,i,o,s,a,u,l;if(t<0||1/t===Number.NEGATIVE_INFINITY?(s=1<<31,t=-t):s=0,0===t)return new R(u=s,l=0);if(t===1/0)return new R(u=2146435072|s,l=0);if(t!=t)return new R(u=2146959360,l=0);if(i=0,l=0,(e=S(t))>1)if(e<=L)(i=S(N(e)))<=20?(l=0,u=e<<20-i&1048575):(l=e%(n=M(2,r=i-20))<<32-r,u=e/n&1048575);else for(r=e,l=0;0!==(r=S(n=r/2));)i++,l>>>=1,l|=(1&u)<<31,u>>>=1,n!==r&&(u|=524288);if(a=i+I,o=0===e,e=t-e,i<52&&0!==e)for(r=0;;){if((n=2*e)>=1?(e=n-1,o?(a--,o=!1):(r<<=1,r|=1,i++)):(e=n,o?0==--a&&(i++,o=!1):(r<<=1,i++)),20===i)u|=r,r=0;else if(52===i){l|=r;break}if(1===n){i<20?u|=r<<20-i:i<52&&(l|=r<<52-i);break}}return u|=a<<20,new R(u|=s,l)},A.longBitsToDouble=function(t){var e,n,r,i,o=t.high,s=t.low,a=o&1<<31?-1:1;for(r=((2146435072&o)>>20)-I,i=0,n=1<<19,e=1;e<=20;e++)o&n&&(i+=M(2,-e)),n>>>=1;for(n=1<<31,e=21;e<=52;e++)s&n&&(i+=M(2,-e)),n>>>=1;if(-1023===r){if(0===i)return 0*a;r=-1022}else{if(1024===r)return 0===i?a/0:NaN;i+=1}return a*i*M(2,r)});var F=function(e){r(i,e);var n=c(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).name=Object.keys({RuntimeException:i})[0],r}return i}(_),q=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){if(0===arguments.length)F.constructor_.call(this);else if(1===arguments.length){var t=arguments[0];F.constructor_.call(this,t)}}}]),o}(F),V=function(){function e(){t(this,e)}return n(e,null,[{key:"shouldNeverReachHere",value:function(){if(0===arguments.length)e.shouldNeverReachHere(null);else if(1===arguments.length){var t=arguments[0];throw new q("Should never reach here"+(null!==t?": "+t:""))}}},{key:"isTrue",value:function(){if(1===arguments.length){var t=arguments[0];e.isTrue(t,null)}else if(2===arguments.length){var n=arguments[1];if(!arguments[0])throw null===n?new q:new q(n)}}},{key:"equals",value:function(){if(2===arguments.length){var t=arguments[0],n=arguments[1];e.equals(t,n,null)}else if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2];if(!i.equals(r))throw new q("Expected "+r+" but encountered "+i+(null!==o?": "+o:""))}}}]),e}(),G=new ArrayBuffer(8),B=new Float64Array(G),Y=new Int32Array(G),z=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getM",value:function(){return A.NaN}},{key:"setOrdinate",value:function(t,n){switch(t){case e.X:this.x=n;break;case e.Y:this.y=n;break;case e.Z:this.setZ(n);break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"equals2D",value:function(){if(1===arguments.length){var t=arguments[0];return this.x===t.x&&this.y===t.y}if(2===arguments.length){var e=arguments[0],n=arguments[1];return!!O.equalsWithTolerance(this.x,e.x,n)&&!!O.equalsWithTolerance(this.y,e.y,n)}}},{key:"setM",value:function(t){throw new x("Invalid ordinate index: "+e.M)}},{key:"getZ",value:function(){return this.z}},{key:"getOrdinate",value:function(t){switch(t){case e.X:return this.x;case e.Y:return this.y;case e.Z:return this.getZ()}throw new x("Invalid ordinate index: "+t)}},{key:"equals3D",value:function(t){return this.x===t.x&&this.y===t.y&&(this.getZ()===t.getZ()||A.isNaN(this.getZ())&&A.isNaN(t.getZ()))}},{key:"equals",value:function(t){return t instanceof e&&this.equals2D(t)}},{key:"equalInZ",value:function(t,e){return O.equalsWithTolerance(this.getZ(),t.getZ(),e)}},{key:"setX",value:function(t){this.x=t}},{key:"compareTo",value:function(t){var e=t;return this.xe.x?1:this.ye.y?1:0}},{key:"getX",value:function(){return this.x}},{key:"setZ",value:function(t){this.z=t}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return V.shouldNeverReachHere("this shouldn't happen because this class is Cloneable"),null;throw t}}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+")"}},{key:"distance3D",value:function(t){var e=this.x-t.x,n=this.y-t.y,r=this.getZ()-t.getZ();return Math.sqrt(e*e+n*n+r*r)}},{key:"getY",value:function(){return this.y}},{key:"setY",value:function(t){this.y=t}},{key:"distance",value:function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*t+e.hashCode(this.x))+e.hashCode(this.y)}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}},{key:"interfaces_",get:function(){return[k,b,w]}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.z=null,0===arguments.length)e.constructor_.call(this,0,0);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.x,t.y,t.getZ())}else if(2===arguments.length){var n=arguments[0],r=arguments[1];e.constructor_.call(this,n,r,e.NULL_ORDINATE)}else if(3===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2];this.x=i,this.y=o,this.z=s}}},{key:"hashCode",value:function(t){return B[0]=t,Y[0]^Y[1]}}]),e}(),j=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compare",value:function(t,n){var r=e.compare(t.x,n.x);if(0!==r)return r;var i=e.compare(t.y,n.y);return 0!==i?i:this._dimensionsToTest<=2?0:e.compare(t.getZ(),n.getZ())}},{key:"interfaces_",get:function(){return[D]}}],[{key:"constructor_",value:function(){if(this._dimensionsToTest=2,0===arguments.length)e.constructor_.call(this,2);else if(1===arguments.length){var t=arguments[0];if(2!==t&&3!==t)throw new x("only 2 or 3 dimensions may be specified");this._dimensionsToTest=t}}},{key:"compare",value:function(t,e){return te?1:A.isNaN(t)?A.isNaN(e)?0:-1:A.isNaN(e)?1:0}}]),e}();z.DimensionalComparator=j,z.NULL_ORDINATE=A.NaN,z.X=0,z.Y=1,z.Z=2,z.M=3;var X=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getArea",value:function(){return this.getWidth()*this.getHeight()}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.isNull()?n.isNull():this._maxx===n.getMaxX()&&this._maxy===n.getMaxY()&&this._minx===n.getMinX()&&this._miny===n.getMinY()}},{key:"intersection",value:function(t){if(this.isNull()||t.isNull()||!this.intersects(t))return new e;var n=this._minx>t._minx?this._minx:t._minx,r=this._miny>t._miny?this._miny:t._miny;return new e(n,this._maxx=this._minx&&n.getMaxX()<=this._maxx&&n.getMinY()>=this._miny&&n.getMaxY()<=this._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return!this.isNull()&&r>=this._minx&&r<=this._maxx&&i>=this._miny&&i<=this._maxy}}},{key:"intersects",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return!this.isNull()&&!t.isNull()&&!(t._minx>this._maxx||t._maxxthis._maxy||t._maxythis._maxx||(r.x>i.x?r.x:i.x)this._maxy||(r.y>i.y?r.y:i.y)this._maxx||othis._maxy||sthis._maxx&&(this._maxx=n._maxx),n._minythis._maxy&&(this._maxy=n._maxy))}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.isNull()?(this._minx=r,this._maxx=r,this._miny=i,this._maxy=i):(rthis._maxx&&(this._maxx=r),ithis._maxy&&(this._maxy=i))}}},{key:"minExtent",value:function(){if(this.isNull())return 0;var t=this.getWidth(),e=this.getHeight();return te._minx?1:this._minye._miny?1:this._maxxe._maxx?1:this._maxye._maxy?1:0}},{key:"translate",value:function(t,e){if(this.isNull())return null;this.init(this.getMinX()+t,this.getMaxX()+t,this.getMinY()+e,this.getMaxY()+e)}},{key:"copy",value:function(){return new e(this)}},{key:"toString",value:function(){return"Env["+this._minx+" : "+this._maxx+", "+this._miny+" : "+this._maxy+"]"}},{key:"setToNull",value:function(){this._minx=0,this._maxx=-1,this._miny=0,this._maxy=-1}},{key:"disjoint",value:function(t){return!(!this.isNull()&&!t.isNull())||t._minx>this._maxx||t._maxxthis._maxy||t._maxye?t:e}},{key:"expandBy",value:function(){if(1===arguments.length){var t=arguments[0];this.expandBy(t,t)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];if(this.isNull())return null;this._minx-=e,this._maxx+=e,this._miny-=n,this._maxy+=n,(this._minx>this._maxx||this._miny>this._maxy)&&this.setToNull()}}},{key:"contains",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.covers(t)}if(arguments[0]instanceof z){var n=arguments[0];return this.covers(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];return this.covers(r,i)}}},{key:"centre",value:function(){return this.isNull()?null:new z((this.getMinX()+this.getMaxX())/2,(this.getMinY()+this.getMaxY())/2)}},{key:"init",value:function(){if(0===arguments.length)this.setToNull();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this._minx=n._minx,this._maxx=n._maxx,this._miny=n._miny,this._maxy=n._maxy}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];ot._maxx&&(e=this._minx-t._maxx);var n=0;return this._maxyt._maxy&&(n=this._miny-t._maxy),0===e?n:0===n?e:Math.sqrt(e*e+n*n)}},{key:"hashCode",value:function(){var t=17;return 37*(t=37*(t=37*(t=37*t+z.hashCode(this._minx))+z.hashCode(this._maxx))+z.hashCode(this._miny))+z.hashCode(this._maxy)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,0===arguments.length)this.init();else if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r.x,i.x,r.y,i.y)}else if(4===arguments.length){var o=arguments[0],s=arguments[1],a=arguments[2],u=arguments[3];this.init(o,s,a,u)}}},{key:"intersects",value:function(){if(3===arguments.length){var t=arguments[0],e=arguments[1],n=arguments[2];return n.x>=(t.xe.x?t.x:e.x)&&n.y>=(t.ye.y?t.y:e.y)}if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=arguments[3],a=Math.min(o.x,s.x),u=Math.max(o.x,s.x),l=Math.min(r.x,i.x),h=Math.max(r.x,i.x);return!(l>u||hu||h=this.size())throw new nt;return this.array[t]}},{key:"push",value:function(t){return this.array.push(t),t}},{key:"pop",value:function(){if(0===this.array.length)throw new et;return this.array.pop()}},{key:"peek",value:function(){if(0===this.array.length)throw new et;return this.array[this.array.length-1]}},{key:"empty",value:function(){return 0===this.array.length}},{key:"isEmpty",value:function(){return this.empty()}},{key:"search",value:function(t){return this.array.indexOf(t)}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}}]),o}(rt);function ot(t,e){return t.interfaces_&&t.interfaces_.indexOf(e)>-1}var st=function(){function e(n){t(this,e),this.str=n}return n(e,[{key:"append",value:function(t){this.str+=t}},{key:"setCharAt",value:function(t,e){this.str=this.str.substr(0,t)+e+this.str.substr(t+1)}},{key:"toString",value:function(){return this.str}}]),e}(),at=function(){function e(n){t(this,e),this.value=n}return n(e,[{key:"intValue",value:function(){return this.value}},{key:"compareTo",value:function(t){return this.valuet?1:0}}],[{key:"compare",value:function(t,e){return te?1:0}},{key:"isNan",value:function(t){return Number.isNaN(t)}},{key:"valueOf",value:function(t){return new e(t)}}]),e}(),ut=function(){function e(){t(this,e)}return n(e,null,[{key:"isWhitespace",value:function(t){return t<=32&&t>=0||127===t}},{key:"toUpperCase",value:function(t){return t.toUpperCase()}}]),e}(),lt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"le",value:function(t){return this._hi9?(c=!0,f="9"):f="0"+h,a.append(f),r=r.subtract(e.valueOf(h)).multiply(e.TEN),c&&r.selfAdd(e.TEN);var g=!0,p=e.magnitude(r._hi);if(p<0&&Math.abs(p)>=u-l&&(g=!1),!g)break}return n[0]=i,a.toString()}},{key:"sqr",value:function(){return this.multiply(this)}},{key:"doubleValue",value:function(){return this._hi+this._lo}},{key:"subtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.add(t.negate())}if("number"==typeof arguments[0]){var n=arguments[0];return this.add(-n)}}},{key:"equals",value:function(){if(1===arguments.length&&arguments[0]instanceof e){var t=arguments[0];return this._hi===t._hi&&this._lo===t._lo}}},{key:"isZero",value:function(){return 0===this._hi&&0===this._lo}},{key:"selfSubtract",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.isNaN()?this:this.selfAdd(-t._hi,-t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.isNaN()?this:this.selfAdd(-n,0)}}},{key:"getSpecialNumberString",value:function(){return this.isZero()?"0.0":this.isNaN()?"NaN ":null}},{key:"min",value:function(t){return this.le(t)?this:t}},{key:"selfDivide",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfDivide(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfDivide(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null,c=null,f=null;return l=this._hi/r,f=(o=(h=e.SPLIT*l)-(o=h-l))*(a=(f=e.SPLIT*r)-(a=f-r))-(c=l*r)+o*(u=r-a)+(s=l-o)*a+s*u,f=l+(h=(this._hi-c-f+this._lo-l*i)/r),this._hi=f,this._lo=l-f+h,this}}},{key:"dump",value:function(){return"DD<"+this._hi+", "+this._lo+">"}},{key:"divide",value:function(){if(arguments[0]instanceof e){var t=arguments[0],n=null,r=null,i=null,o=null,s=null,a=null,u=null,l=null;return r=(s=this._hi/t._hi)-(n=(a=e.SPLIT*s)-(n=a-s)),l=n*(i=(l=e.SPLIT*t._hi)-(i=l-t._hi))-(u=s*t._hi)+n*(o=t._hi-i)+r*i+r*o,new e(l=s+(a=(this._hi-u-l+this._lo-s*t._lo)/t._hi),s-l+a)}if("number"==typeof arguments[0]){var h=arguments[0];return A.isNaN(h)?e.createNaN():e.copy(this).selfDivide(h,0)}}},{key:"ge",value:function(t){return this._hi>t._hi||this._hi===t._hi&&this._lo>=t._lo}},{key:"pow",value:function(t){if(0===t)return e.valueOf(1);var n=new e(this),r=e.valueOf(1),i=Math.abs(t);if(i>1)for(;i>0;)i%2==1&&r.selfMultiply(n),(i/=2)>0&&(n=n.sqr());else r=n;return t<0?r.reciprocal():r}},{key:"ceil",value:function(){if(this.isNaN())return e.NaN;var t=Math.ceil(this._hi),n=0;return t===this._hi&&(n=Math.ceil(this._lo)),new e(t,n)}},{key:"compareTo",value:function(t){var e=t;return this._hie._hi?1:this._loe._lo?1:0}},{key:"rint",value:function(){return this.isNaN()?this:this.add(.5).floor()}},{key:"setValue",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return this.init(t),this}if("number"==typeof arguments[0]){var n=arguments[0];return this.init(n),this}}},{key:"max",value:function(t){return this.ge(t)?this:t}},{key:"sqrt",value:function(){if(this.isZero())return e.valueOf(0);if(this.isNegative())return e.NaN;var t=1/Math.sqrt(this._hi),n=this._hi*t,r=e.valueOf(n),i=this.subtract(r.sqr())._hi*(.5*t);return r.add(i)}},{key:"selfAdd",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfAdd(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0],r=null,i=null,o=null,s=null,a=null,u=null;return s=(o=this._hi+n)-(a=o-this._hi),i=(u=(s=n-a+(this._hi-s))+this._lo)+(o-(r=o+u)),this._hi=r+i,this._lo=i+(r-this._hi),this}}else if(2===arguments.length){var l=arguments[0],h=arguments[1],c=null,f=null,g=null,p=null,v=null,d=null,y=null;p=this._hi+l,f=this._lo+h,v=p-(d=p-this._hi),g=f-(y=f-this._lo);var m=(c=p+(d=(v=l-d+(this._hi-v))+f))+(d=(g=h-y+(this._lo-g))+(d+(p-c))),_=d+(c-m);return this._hi=m,this._lo=_,this}}},{key:"selfMultiply",value:function(){if(1===arguments.length){if(arguments[0]instanceof e){var t=arguments[0];return this.selfMultiply(t._hi,t._lo)}if("number"==typeof arguments[0]){var n=arguments[0];return this.selfMultiply(n,0)}}else if(2===arguments.length){var r=arguments[0],i=arguments[1],o=null,s=null,a=null,u=null,l=null,h=null;o=(l=e.SPLIT*this._hi)-this._hi,h=e.SPLIT*r,o=l-o,s=this._hi-o,a=h-r;var c=(l=this._hi*r)+(h=o*(a=h-a)-l+o*(u=r-a)+s*a+s*u+(this._hi*i+this._lo*r)),f=h+(o=l-c);return this._hi=c,this._lo=f,this}}},{key:"selfSqr",value:function(){return this.selfMultiply(this)}},{key:"floor",value:function(){if(this.isNaN())return e.NaN;var t=Math.floor(this._hi),n=0;return t===this._hi&&(n=Math.floor(this._lo)),new e(t,n)}},{key:"negate",value:function(){return this.isNaN()?this:new e(-this._hi,-this._lo)}},{key:"clone",value:function(){try{return null}catch(t){if(t instanceof CloneNotSupportedException)return null;throw t}}},{key:"multiply",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return t.isNaN()?e.createNaN():e.copy(this).selfMultiply(t)}if("number"==typeof arguments[0]){var n=arguments[0];return A.isNaN(n)?e.createNaN():e.copy(this).selfMultiply(n,0)}}},{key:"isNaN",value:function(){return A.isNaN(this._hi)}},{key:"intValue",value:function(){return Math.trunc(this._hi)}},{key:"toString",value:function(){var t=e.magnitude(this._hi);return t>=-3&&t<=20?this.toStandardNotation():this.toSciNotation()}},{key:"toStandardNotation",value:function(){var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!0,n),i=n[0]+1,o=r;if("."===r.charAt(0))o="0"+r;else if(i<0)o="0."+e.stringOfChar("0",-i)+r;else if(-1===r.indexOf(".")){var s=i-r.length;o=r+e.stringOfChar("0",s)+".0"}return this.isNegative()?"-"+o:o}},{key:"reciprocal",value:function(){var t,n,r,i,o=null,s=null,a=null,u=null;t=(r=1/this._hi)-(o=(a=e.SPLIT*r)-(o=a-r)),s=(u=e.SPLIT*this._hi)-this._hi;var l=r+(a=(1-(i=r*this._hi)-(u=o*(s=u-s)-i+o*(n=this._hi-s)+t*s+t*n)-r*this._lo)/this._hi);return new e(l,r-l+a)}},{key:"toSciNotation",value:function(){if(this.isZero())return e.SCI_NOT_ZERO;var t=this.getSpecialNumberString();if(null!==t)return t;var n=new Array(1).fill(null),r=this.extractSignificantDigits(!1,n),i=e.SCI_NOT_EXPONENT_CHAR+n[0];if("0"===r.charAt(0))throw new IllegalStateException("Found leading zero: "+r);var o="";r.length>1&&(o=r.substring(1));var s=r.charAt(0)+"."+o;return this.isNegative()?"-"+s+i:s+i}},{key:"abs",value:function(){return this.isNaN()?e.NaN:this.isNegative()?this.negate():new e(this)}},{key:"isPositive",value:function(){return this._hi>0||0===this._hi&&this._lo>0}},{key:"lt",value:function(t){return this._hit._hi||this._hi===t._hi&&this._lo>t._lo}},{key:"isNegative",value:function(){return this._hi<0||0===this._hi&&this._lo<0}},{key:"trunc",value:function(){return this.isNaN()?e.NaN:this.isPositive()?this.floor():this.ceil()}},{key:"signum",value:function(){return this._hi>0?1:this._hi<0?-1:this._lo>0?1:this._lo<0?-1:0}},{key:"interfaces_",get:function(){return[w,k,b]}}],[{key:"constructor_",value:function(){if(this._hi=0,this._lo=0,0===arguments.length)this.init(0);else if(1===arguments.length){if("number"==typeof arguments[0]){var t=arguments[0];this.init(t)}else if(arguments[0]instanceof e){var n=arguments[0];this.init(n)}else if("string"==typeof arguments[0]){var r=arguments[0];e.constructor_.call(this,e.parse(r))}}else if(2===arguments.length){var i=arguments[0],o=arguments[1];this.init(i,o)}}},{key:"determinant",value:function(){if("number"==typeof arguments[3]&&"number"==typeof arguments[2]&&"number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1],r=arguments[2],i=arguments[3];return e.determinant(e.valueOf(t),e.valueOf(n),e.valueOf(r),e.valueOf(i))}if(arguments[3]instanceof e&&arguments[2]instanceof e&&arguments[0]instanceof e&&arguments[1]instanceof e){var o=arguments[1],s=arguments[2],a=arguments[3];return arguments[0].multiply(a).selfSubtract(o.multiply(s))}}},{key:"sqr",value:function(t){return e.valueOf(t).selfMultiply(t)}},{key:"valueOf",value:function(){if("string"==typeof arguments[0]){var t=arguments[0];return e.parse(t)}if("number"==typeof arguments[0])return new e(arguments[0])}},{key:"sqrt",value:function(t){return e.valueOf(t).sqrt()}},{key:"parse",value:function(t){for(var n=0,r=t.length;ut.isWhitespace(t.charAt(n));)n++;var i=!1;if(n=r);){var c=t.charAt(n);if(n++,ut.isDigit(c)){var f=c-"0";s.selfMultiply(e.TEN),s.selfAdd(f),a++}else{if("."!==c){if("e"===c||"E"===c){var g=t.substring(n);try{l=at.parseInt(g)}catch(e){throw e instanceof NumberFormatException?new NumberFormatException("Invalid exponent "+g+" in string "+t):e}break}throw new NumberFormatException("Unexpected character '"+c+"' at position "+n+" in string "+t)}u=a,h=!0}}var p=s;h||(u=a);var v=a-u-l;if(0===v)p=s;else if(v>0){var d=e.TEN.pow(v);p=s.divide(d)}else if(v<0){var y=e.TEN.pow(-v);p=s.multiply(y)}return i?p.negate():p}},{key:"createNaN",value:function(){return new e(A.NaN,A.NaN)}},{key:"copy",value:function(t){return new e(t)}},{key:"magnitude",value:function(t){var e=Math.abs(t),n=Math.log(e)/Math.log(10),r=Math.trunc(Math.floor(n));return 10*Math.pow(10,r)<=e&&(r+=1),r}},{key:"stringOfChar",value:function(t,e){for(var n=new st,r=0;r0){if(s<=0)return e.signum(a);i=o+s}else{if(!(o<0))return e.signum(a);if(s>=0)return e.signum(a);i=-o-s}var u=e.DP_SAFE_EPSILON*i;return a>=u||-a>=u?e.signum(a):2}},{key:"signum",value:function(t){return t>0?1:t<0?-1:0}}]),e}();ht.DP_SAFE_EPSILON=1e-15;var ct=function(){function e(){t(this,e)}return n(e,[{key:"getM",value:function(t){if(this.hasM()){var e=this.getDimension()-this.getMeasures();return this.getOrdinate(t,e)}return A.NaN}},{key:"setOrdinate",value:function(t,e,n){}},{key:"getZ",value:function(t){return this.hasZ()?this.getOrdinate(t,2):A.NaN}},{key:"size",value:function(){}},{key:"getOrdinate",value:function(t,e){}},{key:"getCoordinate",value:function(){}},{key:"getCoordinateCopy",value:function(t){}},{key:"createCoordinate",value:function(){}},{key:"getDimension",value:function(){}},{key:"hasM",value:function(){return this.getMeasures()>0}},{key:"getX",value:function(t){}},{key:"hasZ",value:function(){return this.getDimension()-this.getMeasures()>2}},{key:"getMeasures",value:function(){return 0}},{key:"expandEnvelope",value:function(t){}},{key:"copy",value:function(){}},{key:"getY",value:function(t){}},{key:"toCoordinateArray",value:function(){}},{key:"interfaces_",get:function(){return[b]}}]),e}();ct.X=0,ct.Y=1,ct.Z=2,ct.M=3;var ft=function(){function e(){t(this,e)}return n(e,null,[{key:"index",value:function(t,e,n){return ht.orientationIndex(t,e,n)}},{key:"isCCW",value:function(){if(arguments[0]instanceof Array){var t=arguments[0],n=t.length-1;if(n<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var r=t[0],i=0,o=1;o<=n;o++){var s=t[o];s.y>r.y&&(r=s,i=o)}var a=i;do{(a-=1)<0&&(a=n)}while(t[a].equals2D(r)&&a!==i);var u=i;do{u=(u+1)%n}while(t[u].equals2D(r)&&u!==i);var l=t[a],h=t[u];if(l.equals2D(r)||h.equals2D(r)||l.equals2D(h))return!1;var c=e.index(l,r,h);return 0===c?l.x>h.x:c>0}if(ot(arguments[0],ct)){var f=arguments[0],g=f.size()-1;if(g<3)throw new x("Ring has fewer than 4 points, so orientation cannot be determined");for(var p=f.getCoordinate(0),v=0,d=1;d<=g;d++){var y=f.getCoordinate(d);y.y>p.y&&(p=y,v=d)}var m=null,_=v;do{(_-=1)<0&&(_=g),m=f.getCoordinate(_)}while(m.equals2D(p)&&_!==v);var E=null,k=v;do{k=(k+1)%g,E=f.getCoordinate(k)}while(E.equals2D(p)&&k!==v);if(m.equals2D(p)||E.equals2D(p)||m.equals2D(E))return!1;var b=e.index(m,p,E);return 0===b?m.x>E.x:b>0}}}]),e}();ft.CLOCKWISE=-1,ft.RIGHT=ft.CLOCKWISE,ft.COUNTERCLOCKWISE=1,ft.LEFT=ft.COUNTERCLOCKWISE,ft.COLLINEAR=0,ft.STRAIGHT=ft.COLLINEAR;var gt=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this._minCoord}},{key:"getRightmostSide",value:function(t,e){var n=this.getRightmostSideOfSegment(t,e);return n<0&&(n=this.getRightmostSideOfSegment(t,e-1)),n<0&&(this._minCoord=null,this.checkForRightmostCoordinate(t)),n}},{key:"findRightmostEdgeAtVertex",value:function(){var t=this._minDe.getEdge().getCoordinates();V.isTrue(this._minIndex>0&&this._minIndexthis._minCoord.y&&n.y>this._minCoord.y&&r===ft.CLOCKWISE)&&(i=!0),i&&(this._minIndex=this._minIndex-1)}},{key:"getRightmostSideOfSegment",value:function(t,e){var n=t.getEdge().getCoordinates();if(e<0||e+1>=n.length)return-1;if(n[e].y===n[e+1].y)return-1;var r=tt.LEFT;return n[e].ythis._minCoord.x)&&(this._minDe=t,this._minIndex=n,this._minCoord=e[n])}},{key:"findRightmostEdgeAtNode",value:function(){var t=this._minDe.getNode().getEdges();this._minDe=t.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)}},{key:"findEdge",value:function(t){for(var e=t.iterator();e.hasNext();){var n=e.next();n.isForward()&&this.checkForRightmostCoordinate(n)}V.isTrue(0!==this._minIndex||this._minCoord.equals(this._minDe.getCoordinate()),"inconsistency in rightmost processing"),0===this._minIndex?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe,this.getRightmostSide(this._minDe,this._minIndex)===tt.LEFT&&(this._orientedDe=this._minDe.getSym())}}],[{key:"constructor_",value:function(){this._minIndex=-1,this._minCoord=null,this._minDe=null,this._orientedDe=null}}]),e}(),pt=function(e){r(o,e);var i=c(o);function o(e,n){var r;return t(this,o),(r=i.call(this,n?e+" [ "+n+" ]":e)).pt=n?new z(n):void 0,r.name=Object.keys({TopologyException:o})[0],r}return n(o,[{key:"getCoordinate",value:function(){return this.pt}}]),o}(F),vt=function(){function e(){t(this,e),this.array=[]}return n(e,[{key:"addLast",value:function(t){this.array.push(t)}},{key:"removeFirst",value:function(){return this.array.shift()}},{key:"isEmpty",value:function(){return 0===this.array.length}}]),e}(),dt=function(e,i){r(s,e);var o=c(s);function s(e){var n;return t(this,s),(n=o.call(this)).array=[],e instanceof H&&n.addAll(e),n}return n(s,[{key:"interfaces_",get:function(){return[rt,H]}},{key:"ensureCapacity",value:function(){}},{key:"add",value:function(t){return 1===arguments.length?this.array.push(t):this.array.splice(arguments[0],0,arguments[1]),!0}},{key:"clear",value:function(){this.array=[]}},{key:"addAll",value:function(t){var e,n=d(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.array.push(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"set",value:function(t,e){var n=this.array[t];return this.array[t]=e,n}},{key:"iterator",value:function(){return new yt(this)}},{key:"get",value:function(t){if(t<0||t>=this.size())throw new nt;return this.array[t]}},{key:"isEmpty",value:function(){return 0===this.array.length}},{key:"sort",value:function(t){t?this.array.sort((function(e,n){return t.compare(e,n)})):this.array.sort()}},{key:"size",value:function(){return this.array.length}},{key:"toArray",value:function(){return this.array.slice()}},{key:"remove",value:function(t){for(var e=0,n=this.array.length;e=1&&e.getDepth(tt.LEFT)<=0&&!e.isInteriorAreaEdge()&&e.setInResult(!0)}}},{key:"computeDepths",value:function(t){var e=new Q,n=new vt,r=t.getNode();for(n.addLast(r),e.add(r),t.setVisited(!0);!n.isEmpty();){var i=n.removeFirst();e.add(i),this.computeNodeDepth(i);for(var o=i.getEdges().iterator();o.hasNext();){var s=o.next().getSym();if(!s.isVisited()){var a=s.getNode();e.contains(a)||(n.addLast(a),e.add(a))}}}}},{key:"compareTo",value:function(t){var e=t;return this._rightMostCoord.xe._rightMostCoord.x?1:0}},{key:"getEnvelope",value:function(){if(null===this._env){for(var t=new X,e=this._dirEdgeList.iterator();e.hasNext();)for(var n=e.next().getEdge().getCoordinates(),r=0;re.x?t.x:e.x,a=t.y>e.y?t.y:e.y,u=n.xr.x?n.x:r.x,c=n.y>r.y?n.y:r.y,f=((i>u?i:u)+(sl?o:l)+(an?n:t}if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var r=arguments[0],i=arguments[1],o=arguments[2];return ro?o:r}}},{key:"wrap",value:function(t,e){return t<0?e- -t%e:t%e}},{key:"max",value:function(){if(3===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[0];return t>n&&(n=t),e>n&&(n=e),n}if(4===arguments.length){var r=arguments[1],i=arguments[2],o=arguments[3],s=arguments[0];return r>s&&(s=r),i>s&&(s=i),o>s&&(s=o),s}}},{key:"average",value:function(t,e){return(t+e)/2}}]),e}();Et.LOG_10=Math.log(10);var kt=function(){function e(){t(this,e)}return n(e,null,[{key:"segmentToSegment",value:function(t,n,r,i){if(t.equals(n))return e.pointToSegment(t,r,i);if(r.equals(i))return e.pointToSegment(i,t,n);var o=!1;if(X.intersects(t,n,r,i)){var s=(n.x-t.x)*(i.y-r.y)-(n.y-t.y)*(i.x-r.x);if(0===s)o=!0;else{var a=(t.y-r.y)*(i.x-r.x)-(t.x-r.x)*(i.y-r.y),u=((t.y-r.y)*(n.x-t.x)-(t.x-r.x)*(n.y-t.y))/s,l=a/s;(l<0||l>1||u<0||u>1)&&(o=!0)}}else o=!0;return o?Et.min(e.pointToSegment(t,r,i),e.pointToSegment(n,r,i),e.pointToSegment(r,t,n),e.pointToSegment(i,t,n)):0}},{key:"pointToSegment",value:function(t,e,n){if(e.x===n.x&&e.y===n.y)return t.distance(e);var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/r;if(i<=0)return t.distance(e);if(i>=1)return t.distance(n);var o=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(o)*Math.sqrt(r)}},{key:"pointToLinePerpendicular",value:function(t,e,n){var r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),i=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(i)*Math.sqrt(r)}},{key:"pointToSegmentString",value:function(t,n){if(0===n.length)throw new x("Line array must contain at least one vertex");for(var r=t.distance(n[0]),i=0;i0)&&(o=a,i=s)}return i}}},{key:"extend",value:function(t,n,r){var i=t.create(r,n.getDimension()),o=n.size();if(e.copy(n,0,i,0,o),o>0)for(var s=o;s0)&&(e=r)}return e}}]),e}(),Mt=function(){function e(){t(this,e)}return n(e,null,[{key:"toDimensionSymbol",value:function(t){switch(t){case e.FALSE:return e.SYM_FALSE;case e.TRUE:return e.SYM_TRUE;case e.DONTCARE:return e.SYM_DONTCARE;case e.P:return e.SYM_P;case e.L:return e.SYM_L;case e.A:return e.SYM_A}throw new x("Unknown dimension value: "+t)}},{key:"toDimensionValue",value:function(t){switch(ut.toUpperCase(t)){case e.SYM_FALSE:return e.FALSE;case e.SYM_TRUE:return e.TRUE;case e.SYM_DONTCARE:return e.DONTCARE;case e.SYM_P:return e.P;case e.SYM_L:return e.L;case e.SYM_A:return e.A}throw new x("Unknown dimension symbol: "+t)}}]),e}();Mt.P=0,Mt.L=1,Mt.A=2,Mt.FALSE=-1,Mt.TRUE=-2,Mt.DONTCARE=-3,Mt.SYM_FALSE="F",Mt.SYM_TRUE="T",Mt.SYM_DONTCARE="*",Mt.SYM_P="0",Mt.SYM_L="1",Mt.SYM_A="2";var Lt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t){}}]),e}(),Pt=function(){function e(){t(this,e)}return n(e,[{key:"filter",value:function(t,e){}},{key:"isDone",value:function(){}},{key:"isGeometryChanged",value:function(){}}]),e}(),Ct=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"computeEnvelopeInternal",value:function(){return this.isEmpty()?new X:this._points.expandEnvelope(new X)}},{key:"isRing",value:function(){return this.isClosed()&&this.isSimple()}},{key:"getCoordinates",value:function(){return this._points.toCoordinateArray()}},{key:"copyInternal",value:function(){return new s(this._points.copy(),this._factory)}},{key:"equalsExact",value:function(){if(2===arguments.length&&"number"==typeof arguments[1]&&arguments[0]instanceof U){var t=arguments[0],e=arguments[1];if(!this.isEquivalentClass(t))return!1;var n=t;if(this._points.size()!==n._points.size())return!1;for(var r=0;r0){var n=this._points.copy();St.reverse(n),this._points=n}return null}}}},{key:"getCoordinate",value:function(){return this.isEmpty()?null:this._points.getCoordinate(0)}},{key:"getBoundaryDimension",value:function(){return this.isClosed()?Mt.FALSE:0}},{key:"isClosed",value:function(){return!this.isEmpty()&&this.getCoordinateN(0).equals2D(this.getCoordinateN(this.getNumPoints()-1))}},{key:"reverseInternal",value:function(){var t=this._points.copy();return St.reverse(t),this.getFactory().createLineString(t)}},{key:"getEndPoint",value:function(){return this.isEmpty()?null:this.getPointN(this.getNumPoints()-1)}},{key:"getTypeCode",value:function(){return U.TYPECODE_LINESTRING}},{key:"getDimension",value:function(){return 1}},{key:"getLength",value:function(){return It.ofLine(this._points)}},{key:"getNumPoints",value:function(){return this._points.size()}},{key:"compareToSameClass",value:function(){if(1===arguments.length){for(var t=arguments[0],e=0,n=0;e= 2)");this._points=t}},{key:"isCoordinate",value:function(t){for(var e=0;e=1&&this.getCoordinateSequence().size()= 4)")}},{key:"getGeometryType",value:function(){return U.TYPENAME_LINEARRING}}],[{key:"constructor_",value:function(){var t=arguments[0],e=arguments[1];Ct.constructor_.call(this,t,e),this.validateConstruction()}}]),s}(Ct);zt.MINIMUM_VALID_SIZE=4;var jt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ()}}],[{key:"constructor_",value:function(){if(0===arguments.length)z.constructor_.call(this);else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y)}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y)}}else if(2===arguments.length){var n=arguments[0],r=arguments[1];z.constructor_.call(this,n,r,z.NULL_ORDINATE)}}}]),o}(z);jt.X=0,jt.Y=1,jt.Z=-1,jt.M=-1;var Xt=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case o.X:this.x=e;break;case o.Y:this.y=e;break;case o.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getZ",value:function(){return z.NULL_ORDINATE}},{key:"getOrdinate",value:function(t){switch(t){case o.X:return this.x;case o.Y:return this.y;case o.M:return this._m}throw new x("Invalid ordinate index: "+t)}},{key:"setZ",value:function(t){throw new x("CoordinateXY dimension 2 does not support z-ordinate")}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t.x,t.y),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e.x,e.y),this._m=this.getM()}}else if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2];z.constructor_.call(this,n,r,z.NULL_ORDINATE),this._m=i}}}]),o}(z);Xt.X=0,Xt.Y=1,Xt.Z=-1,Xt.M=2;var Ut=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"getM",value:function(){return this._m}},{key:"setOrdinate",value:function(t,e){switch(t){case z.X:this.x=e;break;case z.Y:this.y=e;break;case z.Z:this.z=e;break;case z.M:this._m=e;break;default:throw new x("Invalid ordinate index: "+t)}}},{key:"setM",value:function(t){this._m=t}},{key:"getOrdinate",value:function(t){switch(t){case z.X:return this.x;case z.Y:return this.y;case z.Z:return this.getZ();case z.M:return this.getM()}throw new x("Invalid ordinate index: "+t)}},{key:"copy",value:function(){return new o(this)}},{key:"toString",value:function(){return"("+this.x+", "+this.y+", "+this.getZ()+" m="+this.getM()+")"}},{key:"setCoordinate",value:function(t){this.x=t.x,this.y=t.y,this.z=t.getZ(),this._m=t.getM()}}],[{key:"constructor_",value:function(){if(this._m=null,0===arguments.length)z.constructor_.call(this),this._m=0;else if(1===arguments.length){if(arguments[0]instanceof o){var t=arguments[0];z.constructor_.call(this,t),this._m=t._m}else if(arguments[0]instanceof z){var e=arguments[0];z.constructor_.call(this,e),this._m=this.getM()}}else if(4===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],s=arguments[3];z.constructor_.call(this,n,r,i),this._m=s}}}]),o}(z),Zt=function(){function e(){t(this,e)}return n(e,null,[{key:"measures",value:function(t){return t instanceof jt?0:t instanceof Xt||t instanceof Ut?1:0}},{key:"dimension",value:function(t){return t instanceof jt?2:t instanceof Xt?3:t instanceof Ut?4:3}},{key:"create",value:function(){if(1===arguments.length){var t=arguments[0];return e.create(t,0)}if(2===arguments.length){var n=arguments[0],r=arguments[1];return 2===n?new jt:3===n&&0===r?new z:3===n&&1===r?new Xt:4===n&&1===r?new Ut:new z}}}]),e}(),Ht=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getCoordinate",value:function(t){return this.get(t)}},{key:"addAll",value:function(){if(2===arguments.length&&"boolean"==typeof arguments[1]&&ot(arguments[0],H)){for(var t=arguments[1],e=!1,n=arguments[0].iterator();n.hasNext();)this.add(n.next(),t),e=!0;return e}return f(i(s.prototype),"addAll",this).apply(this,arguments)}},{key:"clone",value:function(){for(var t=f(i(s.prototype),"clone",this).call(this),e=0;e=1&&this.get(this.size()-1).equals2D(r))return null;f(i(s.prototype),"add",this).call(this,r)}else if(arguments[0]instanceof Object&&"boolean"==typeof arguments[1]){var o=arguments[0],a=arguments[1];return this.add(o,a),!0}}else if(3===arguments.length){if("boolean"==typeof arguments[2]&&arguments[0]instanceof Array&&"boolean"==typeof arguments[1]){var u=arguments[0],l=arguments[1];if(arguments[2])for(var h=0;h=0;c--)this.add(u[c],l);return!0}if("boolean"==typeof arguments[2]&&Number.isInteger(arguments[0])&&arguments[1]instanceof z){var g=arguments[0],p=arguments[1];if(!arguments[2]){var v=this.size();if(v>0){if(g>0&&this.get(g-1).equals2D(p))return null;if(g_&&(x=-1);for(var E=m;E!==_;E+=x)this.add(d[E],y);return!0}}},{key:"closeRing",value:function(){if(this.size()>0){var t=this.get(0).copy();this.add(t,!1)}}}],[{key:"constructor_",value:function(){if(0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.ensureCapacity(t.length),this.add(t,!0)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this.ensureCapacity(e.length),this.add(e,n)}}}]),s}(dt);Ht.coordArrayType=new Array(0).fill(null);var Wt=function(){function e(){t(this,e)}return n(e,null,[{key:"isRing",value:function(t){return!(t.length<4||!t[0].equals2D(t[t.length-1]))}},{key:"ptNotInList",value:function(t,n){for(var r=0;r=t?e:[]}},{key:"indexOf",value:function(t,e){for(var n=0;n0)&&(e=t[n]);return e}},{key:"extract",value:function(t,e,n){e=Et.clamp(e,0,t.length);var r=(n=Et.clamp(n,-1,t.length))-e+1;n<0&&(r=0),e>=t.length&&(r=0),nr.length)return 1;if(0===n.length)return 0;var i=Wt.compare(n,r);return Wt.isEqualReversed(n,r)?0:i}},{key:"OLDcompare",value:function(t,e){var n=t,r=e;if(n.lengthr.length)return 1;if(0===n.length)return 0;for(var i=Wt.increasingDirection(n),o=Wt.increasingDirection(r),s=i>0?0:n.length-1,a=o>0?0:n.length-1,u=0;u0){var t=new Qt(17*this._coordinates.length);t.append("("),t.append(this._coordinates[0]);for(var e=1;e3&&(t=3),t<2&&(t=2),new $t(arguments[0],t)}if(3===arguments.length){var e=arguments[2],n=arguments[1]-e;return e>1&&(e=1),n>3&&(n=3),n<2&&(n=2),new $t(arguments[0],n+e,e)}}}},{key:"interfaces_",get:function(){return[bt,w]}}],[{key:"instance",value:function(){return e.instanceObject}}]),e}();te.instanceObject=new te;var ee=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e=0?t:e}}]),e}(),oe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"readResolve",value:function(){return e.nameToTypeMap.get(this._name)}},{key:"toString",value:function(){return this._name}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){this._name=null;var t=arguments[0];this._name=t,e.nameToTypeMap.put(t,this)}}]),e}();oe.nameToTypeMap=new re,ie.Type=oe,ie.FIXED=new oe("FIXED"),ie.FLOATING=new oe("FLOATING"),ie.FLOATING_SINGLE=new oe("FLOATING SINGLE"),ie.maximumPreciseValue=9007199254740992;var se=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"copyInternal",value:function(){for(var t=new Array(this._geometries.length).fill(null),e=0;e1){if(u instanceof Ft)return this.createMultiPolygon(e.toPolygonArray(t));if(u instanceof Ct)return this.createMultiLineString(e.toLineStringArray(t));if(u instanceof Ot)return this.createMultiPoint(e.toPointArray(t));V.shouldNeverReachHere("Unhandled geometry type: "+u.getGeometryType())}return u}},{key:"createMultiPointFromCoords",value:function(t){return this.createMultiPoint(null!==t?this.getCoordinateSequenceFactory().create(t):null)}},{key:"createPoint",value:function(){if(0===arguments.length)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof z){var t=arguments[0];return this.createPoint(null!==t?this.getCoordinateSequenceFactory().create([t]):null)}if(ot(arguments[0],ct))return new Ot(arguments[0],this)}}},{key:"getCoordinateSequenceFactory",value:function(){return this._coordinateSequenceFactory}},{key:"createPolygon",value:function(){if(0===arguments.length)return this.createPolygon(null,null);if(1===arguments.length){if(ot(arguments[0],ct)){var t=arguments[0];return this.createPolygon(this.createLinearRing(t))}if(arguments[0]instanceof Array){var e=arguments[0];return this.createPolygon(this.createLinearRing(e))}if(arguments[0]instanceof zt){var n=arguments[0];return this.createPolygon(n,null)}}else if(2===arguments.length)return new Ft(arguments[0],arguments[1],this)}},{key:"getSRID",value:function(){return this._SRID}},{key:"createGeometryCollection",value:function(){return 0===arguments.length?new Bt(null,this):1===arguments.length?new Bt(arguments[0],this):void 0}},{key:"getPrecisionModel",value:function(){return this._precisionModel}},{key:"createLinearRing",value:function(){if(0===arguments.length)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof Array){var t=arguments[0];return this.createLinearRing(null!==t?this.getCoordinateSequenceFactory().create(t):null)}if(ot(arguments[0],ct))return new zt(arguments[0],this)}}},{key:"createMultiPolygon",value:function(){return 0===arguments.length?new ee(null,this):1===arguments.length?new ee(arguments[0],this):void 0}},{key:"createMultiPoint",value:function(){if(0===arguments.length)return new Yt(null,this);if(1===arguments.length){if(arguments[0]instanceof Array)return new Yt(arguments[0],this);if(ot(arguments[0],ct)){var t=arguments[0];if(null===t)return this.createMultiPoint(new Array(0).fill(null));for(var e=new Array(t.size()).fill(null),n=0;n="a"&&t<="z"||t>="A"&&t<="Z"}},{key:"isNumeric_",value:function(t,e){return t>="0"&&t<="9"||"."==t&&!(void 0!==e&&e)}},{key:"isWhiteSpace_",value:function(t){return" "==t||"\t"==t||"\r"==t||"\n"==t}},{key:"nextChar_",value:function(){return this.wkt.charAt(++this.index_)}},{key:"nextToken",value:function(){var t,e=this.nextChar_(),n=this.index_,r=e;if("("==e)t=ve;else if(","==e)t=me;else if(")"==e)t=de;else if(this.isNumeric_(e)||"-"==e)t=ye,r=this.readNumber_();else if(this.isAlpha_(e))t=pe,r=this.readText_();else{if(this.isWhiteSpace_(e))return this.nextToken();if(""!==e)throw new Error("Unexpected character: "+e);t=_e}return{position:n,value:r,type:t}}},{key:"readNumber_",value:function(){var t,e=this.index_,n=!1,r=!1;do{"."==t?n=!0:"e"!=t&&"E"!=t||(r=!0),t=this.nextChar_()}while(this.isNumeric_(t,n)||!r&&("e"==t||"E"==t)||r&&("-"==t||"+"==t));return parseFloat(this.wkt.substring(e,this.index_--))}},{key:"readText_",value:function(){var t,e=this.index_;do{t=this.nextChar_()}while(this.isAlpha_(t));return this.wkt.substring(e,this.index_--).toUpperCase()}}]),e}(),ke=function(){function e(n,r){t(this,e),this.lexer_=n,this.token_,this.layout_=ue,this.factory=r}return n(e,[{key:"consume_",value:function(){this.token_=this.lexer_.nextToken()}},{key:"isTokenType",value:function(t){return this.token_.type==t}},{key:"match",value:function(t){var e=this.isTokenType(t);return e&&this.consume_(),e}},{key:"parse",value:function(){return this.consume_(),this.parseGeometry_()}},{key:"parseGeometryLayout_",value:function(){var t=ue,e=this.token_;if(this.isTokenType(pe)){var n=e.value;"Z"===n?t=le:"M"===n?t=he:"ZM"===n&&(t=ce),t!==ue&&this.consume_()}return t}},{key:"parseGeometryCollectionText_",value:function(){if(this.match(ve)){var t=[];do{t.push(this.parseGeometry_())}while(this.match(me));if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePointText_",value:function(){if(this.match(ve)){var t=this.parsePoint_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return null;throw new Error(this.formatErrorMessage_())}},{key:"parseLineStringText_",value:function(){if(this.match(ve)){var t=this.parsePointList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePolygonText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPointText_",value:function(){var t;if(this.match(ve)){if(t=this.token_.type==ve?this.parsePointTextList_():this.parsePointList_(),this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiLineStringText_",value:function(){if(this.match(ve)){var t=this.parseLineStringTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parseMultiPolygonText_",value:function(){if(this.match(ve)){var t=this.parsePolygonTextList_();if(this.match(de))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}},{key:"parsePoint_",value:function(){for(var t=[],e=this.layout_.length,n=0;n1?t.createPolygon(r[0],r.slice(1)):t.createPolygon(r[0])},r=this.token_;if(this.match(pe)){var i=r.value;if(this.layout_=this.parseGeometryLayout_(),"GEOMETRYCOLLECTION"==i){var o=this.parseGeometryCollectionText_();return t.createGeometryCollection(o)}switch(i){case"POINT":var s=this.parsePointText_();return s?t.createPoint(a(z,g(s))):t.createPoint();case"LINESTRING":var u=this.parseLineStringText_().map(e);return t.createLineString(u);case"LINEARRING":var l=this.parseLineStringText_().map(e);return t.createLinearRing(l);case"POLYGON":var h=this.parsePolygonText_();return h&&0!==h.length?n(h):t.createPolygon();case"MULTIPOINT":var c=this.parseMultiPointText_();if(!c||0===c.length)return t.createMultiPoint();var f=c.map(e).map((function(e){return t.createPoint(e)}));return t.createMultiPoint(f);case"MULTILINESTRING":var p=this.parseMultiLineStringText_().map((function(n){return t.createLineString(n.map(e))}));return t.createMultiLineString(p);case"MULTIPOLYGON":var v=this.parseMultiPolygonText_();if(!v||0===v.length)return t.createMultiPolygon();var d=v.map(n);return t.createMultiPolygon(d);default:throw new Error("Invalid geometry type: "+i)}}throw new Error(this.formatErrorMessage_())}}]),e}();function be(t){if(t.isEmpty())return"";var e=t.getCoordinate(),n=[e.x,e.y];return void 0===e.z||Number.isNaN(e.z)||n.push(e.z),void 0===e.m||Number.isNaN(e.m)||n.push(e.m),n.join(" ")}function we(t){for(var e=t.getCoordinates().map((function(t){var e=[t.x,t.y];return void 0===t.z||Number.isNaN(t.z)||e.push(t.z),void 0===t.m||Number.isNaN(t.m)||e.push(t.m),e})),n=[],r=0,i=e.length;r0&&(e+=" "+r),t.isEmpty()?e+" "+ge:e+" ("+n(t)+")"}var Me=function(){function e(n){t(this,e),this.geometryFactory=n||new ae,this.precisionModel=this.geometryFactory.getPrecisionModel()}return n(e,[{key:"read",value:function(t){var e=new Ee(t);return new ke(e,this.geometryFactory).parse()}},{key:"write",value:function(t){return Se(t)}}]),e}(),Le=function(){function e(n){t(this,e),this.parser=new Me(n)}return n(e,[{key:"write",value:function(t){return this.parser.write(t)}}],[{key:"toLineString",value:function(t,e){if(2!==arguments.length)throw new Error("Not implemented");return"LINESTRING ( "+t.x+" "+t.y+", "+e.x+" "+e.y+" )"}}]),e}(),Pe=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getIndexAlongSegment",value:function(t,e){return this.computeIntLineIndex(),this._intLineIndex[t][e]}},{key:"getTopologySummary",value:function(){var t=new Qt;return this.isEndPoint()&&t.append(" endpoint"),this._isProper&&t.append(" proper"),this.isCollinear()&&t.append(" collinear"),t.toString()}},{key:"computeIntersection",value:function(t,e,n,r){this._inputLines[0][0]=t,this._inputLines[0][1]=e,this._inputLines[1][0]=n,this._inputLines[1][1]=r,this._result=this.computeIntersect(t,e,n,r)}},{key:"getIntersectionNum",value:function(){return this._result}},{key:"computeIntLineIndex",value:function(){if(0===arguments.length)null===this._intLineIndex&&(this._intLineIndex=Array(2).fill().map((function(){return Array(2)})),this.computeIntLineIndex(0),this.computeIntLineIndex(1));else if(1===arguments.length){var t=arguments[0];this.getEdgeDistance(t,0)>this.getEdgeDistance(t,1)?(this._intLineIndex[t][0]=0,this._intLineIndex[t][1]=1):(this._intLineIndex[t][0]=1,this._intLineIndex[t][1]=0)}}},{key:"isProper",value:function(){return this.hasIntersection()&&this._isProper}},{key:"setPrecisionModel",value:function(t){this._precisionModel=t}},{key:"isInteriorIntersection",value:function(){if(0===arguments.length)return!!this.isInteriorIntersection(0)||!!this.isInteriorIntersection(1);if(1===arguments.length){for(var t=arguments[0],e=0;ei?r:i;else{var s=Math.abs(t.x-e.x),a=Math.abs(t.y-e.y);0!==(o=r>i?s:a)||t.equals(e)||(o=Math.max(s,a))}return V.isTrue(!(0===o&&!t.equals(e)),"Bad distance calculation"),o}},{key:"nonRobustComputeEdgeDistance",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y,o=Math.sqrt(r*r+i*i);return V.isTrue(!(0===o&&!t.equals(e)),"Invalid distance calculation"),o}}]),e}();Pe.DONT_INTERSECT=0,Pe.DO_INTERSECT=1,Pe.COLLINEAR=2,Pe.NO_INTERSECTION=0,Pe.POINT_INTERSECTION=1,Pe.COLLINEAR_INTERSECTION=2;var Ce=function(e){r(s,e);var o=c(s);function s(){return t(this,s),o.call(this)}return n(s,[{key:"isInSegmentEnvelopes",value:function(t){var e=new X(this._inputLines[0][0],this._inputLines[0][1]),n=new X(this._inputLines[1][0],this._inputLines[1][1]);return e.contains(t)&&n.contains(t)}},{key:"computeIntersection",value:function(){if(3!==arguments.length)return f(i(s.prototype),"computeIntersection",this).apply(this,arguments);var t=arguments[0],e=arguments[1],n=arguments[2];if(this._isProper=!1,X.intersects(e,n,t)&&0===ft.index(e,n,t)&&0===ft.index(n,e,t))return this._isProper=!0,(t.equals(e)||t.equals(n))&&(this._isProper=!1),this._result=Pe.POINT_INTERSECTION,null;this._result=Pe.NO_INTERSECTION}},{key:"intersection",value:function(t,e,n,r){var i=this.intersectionSafe(t,e,n,r);return this.isInSegmentEnvelopes(i)||(i=new z(s.nearestEndpoint(t,e,n,r))),null!==this._precisionModel&&this._precisionModel.makePrecise(i),i}},{key:"checkDD",value:function(t,e,n,r,i){var o=ht.intersection(t,e,n,r),s=this.isInSegmentEnvelopes(o);xt.out.println("DD in env = "+s+" --------------------- "+o),i.distance(o)>1e-4&&xt.out.println("Distance = "+i.distance(o))}},{key:"intersectionSafe",value:function(t,e,n,r){var i=_t.intersection(t,e,n,r);return null===i&&(i=s.nearestEndpoint(t,e,n,r)),i}},{key:"computeCollinearIntersection",value:function(t,e,n,r){var i=X.intersects(t,e,n),o=X.intersects(t,e,r),s=X.intersects(n,r,t),a=X.intersects(n,r,e);return i&&o?(this._intPt[0]=n,this._intPt[1]=r,Pe.COLLINEAR_INTERSECTION):s&&a?(this._intPt[0]=t,this._intPt[1]=e,Pe.COLLINEAR_INTERSECTION):i&&s?(this._intPt[0]=n,this._intPt[1]=t,!n.equals(t)||o||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):i&&a?(this._intPt[0]=n,this._intPt[1]=e,!n.equals(e)||o||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&s?(this._intPt[0]=r,this._intPt[1]=t,!r.equals(t)||i||a?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):o&&a?(this._intPt[0]=r,this._intPt[1]=e,!r.equals(e)||i||s?Pe.COLLINEAR_INTERSECTION:Pe.POINT_INTERSECTION):Pe.NO_INTERSECTION}},{key:"computeIntersect",value:function(t,e,n,r){if(this._isProper=!1,!X.intersects(t,e,n,r))return Pe.NO_INTERSECTION;var i=ft.index(t,e,n),o=ft.index(t,e,r);if(i>0&&o>0||i<0&&o<0)return Pe.NO_INTERSECTION;var s=ft.index(n,r,t),a=ft.index(n,r,e);return s>0&&a>0||s<0&&a<0?Pe.NO_INTERSECTION:0===i&&0===o&&0===s&&0===a?this.computeCollinearIntersection(t,e,n,r):(0===i||0===o||0===s||0===a?(this._isProper=!1,t.equals2D(n)||t.equals2D(r)?this._intPt[0]=t:e.equals2D(n)||e.equals2D(r)?this._intPt[0]=e:0===i?this._intPt[0]=new z(n):0===o?this._intPt[0]=new z(r):0===s?this._intPt[0]=new z(t):0===a&&(this._intPt[0]=new z(e))):(this._isProper=!0,this._intPt[0]=this.intersection(t,e,n,r)),Pe.POINT_INTERSECTION)}}],[{key:"nearestEndpoint",value:function(t,e,n,r){var i=t,o=kt.pointToSegment(t,n,r),s=kt.pointToSegment(e,n,r);return sr&&(n=e.x,r=t.x),this._p.x>=n&&this._p.x<=r&&(this._isPointOnSegment=!0),null}if(t.y>this._p.y&&e.y<=this._p.y||e.y>this._p.y&&t.y<=this._p.y){var i=ft.index(t,e,this._p);if(i===ft.COLLINEAR)return this._isPointOnSegment=!0,null;e.ythis.location.length){var e=new Array(3).fill(null);e[tt.ON]=this.location[tt.ON],e[tt.LEFT]=Z.NONE,e[tt.RIGHT]=Z.NONE,this.location=e}for(var n=0;n1&&t.append(Z.toLocationSymbol(this.location[tt.LEFT])),t.append(Z.toLocationSymbol(this.location[tt.ON])),this.location.length>1&&t.append(Z.toLocationSymbol(this.location[tt.RIGHT])),t.toString()}},{key:"setLocations",value:function(t,e,n){this.location[tt.ON]=t,this.location[tt.LEFT]=e,this.location[tt.RIGHT]=n}},{key:"get",value:function(t){return t1}},{key:"isAnyNull",value:function(){for(var t=0;tthis._maxNodeDegree&&(this._maxNodeDegree=e),t=this.getNext(t)}while(t!==this._startDe);this._maxNodeDegree*=2}},{key:"addPoints",value:function(t,e,n){var r=t.getCoordinates();if(e){var i=1;n&&(i=0);for(var o=i;o=0;a--)this._pts.add(r[a])}}},{key:"isHole",value:function(){return this._isHole}},{key:"setInResult",value:function(){var t=this._startDe;do{t.getEdge().setInResult(!0),t=t.getNext()}while(t!==this._startDe)}},{key:"containsPoint",value:function(t){var e=this.getLinearRing();if(!e.getEnvelopeInternal().contains(t))return!1;if(!Oe.isInRing(t,e.getCoordinates()))return!1;for(var n=this._holes.iterator();n.hasNext();)if(n.next().containsPoint(t))return!1;return!0}},{key:"addHole",value:function(t){this._holes.add(t)}},{key:"isShell",value:function(){return null===this._shell}},{key:"getLabel",value:function(){return this._label}},{key:"getEdges",value:function(){return this._edges}},{key:"getMaxNodeDegree",value:function(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree}},{key:"getShell",value:function(){return this._shell}},{key:"mergeLabel",value:function(){if(1===arguments.length){var t=arguments[0];this.mergeLabel(t,0),this.mergeLabel(t,1)}else if(2===arguments.length){var e=arguments[1],n=arguments[0].getLocation(e,tt.RIGHT);if(n===Z.NONE)return null;if(this._label.getLocation(e)===Z.NONE)return this._label.setLocation(e,n),null}}},{key:"setShell",value:function(t){this._shell=t,null!==t&&t.addHole(this)}},{key:"toPolygon",value:function(t){for(var e=new Array(this._holes.size()).fill(null),n=0;n=2,"found partial label"),this.computeIM(t)}},{key:"isInResult",value:function(){return this._isInResult}},{key:"isVisited",value:function(){return this._isVisited}}],[{key:"constructor_",value:function(){if(this._label=null,this._isInResult=!1,this._isCovered=!1,this._isCoveredSet=!1,this._isVisited=!1,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._label=t}}}]),e}(),Ge=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isIncidentEdgeInResult",value:function(){for(var t=this.getEdges().getEdges().iterator();t.hasNext();)if(t.next().getEdge().isInResult())return!0;return!1}},{key:"isIsolated",value:function(){return 1===this._label.getGeometryCount()}},{key:"getCoordinate",value:function(){return this._coord}},{key:"print",value:function(t){t.println("node "+this._coord+" lbl: "+this._label)}},{key:"computeIM",value:function(t){}},{key:"computeMergedLocation",value:function(t,e){var n=Z.NONE;if(n=this._label.getLocation(e),!t.isNull(e)){var r=t.getLocation(e);n!==Z.BOUNDARY&&(n=r)}return n}},{key:"setLabel",value:function(){if(2!==arguments.length||!Number.isInteger(arguments[1])||!Number.isInteger(arguments[0]))return f(i(s.prototype),"setLabel",this).apply(this,arguments);var t=arguments[0],e=arguments[1];null===this._label?this._label=new Ae(t,e):this._label.setLocation(t,e)}},{key:"getEdges",value:function(){return this._edges}},{key:"mergeLabel",value:function(){if(arguments[0]instanceof s){var t=arguments[0];this.mergeLabel(t._label)}else if(arguments[0]instanceof Ae)for(var e=arguments[0],n=0;n<2;n++){var r=this.computeMergedLocation(e,n);this._label.getLocation(n)===Z.NONE&&this._label.setLocation(n,r)}}},{key:"add",value:function(t){this._edges.insert(t),t.setNode(this)}},{key:"setLabelBoundary",value:function(t){if(null===this._label)return null;var e=Z.NONE;null!==this._label&&(e=this._label.getLocation(t));var n=null;switch(e){case Z.BOUNDARY:n=Z.INTERIOR;break;case Z.INTERIOR:default:n=Z.BOUNDARY}this._label.setLocation(t,n)}}],[{key:"constructor_",value:function(){this._coord=null,this._edges=null;var t=arguments[0],e=arguments[1];this._coord=t,this._edges=e,this._label=new Ae(0,Z.NONE)}}]),s}(Ve),Be=function(e){r(i,e);var n=c(i);function i(){return t(this,i),n.apply(this,arguments)}return i}(ne);function Ye(t){return null==t?0:t.color}function ze(t){return null==t?null:t.parent}function je(t,e){null!==t&&(t.color=e)}function Xe(t){return null==t?null:t.left}function Ue(t){return null==t?null:t.right}var Ze=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),(e=i.call(this)).root_=null,e.size_=0,e}return n(o,[{key:"get",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return e.value;e=e.right}}return null}},{key:"put",value:function(t,e){if(null===this.root_)return this.root_={key:t,value:e,left:null,right:null,parent:null,color:0,getValue:function(){return this.value},getKey:function(){return this.key}},this.size_=1,null;var n,r,i=this.root_;do{if(n=i,(r=t.compareTo(i.key))<0)i=i.left;else{if(!(r>0)){var o=i.value;return i.value=e,o}i=i.right}}while(null!==i);var s={key:t,left:null,right:null,value:e,parent:n,color:0,getValue:function(){return this.value},getKey:function(){return this.key}};return r<0?n.left=s:n.right=s,this.fixAfterInsertion(s),this.size_++,null}},{key:"fixAfterInsertion",value:function(t){var e;for(t.color=1;null!=t&&t!==this.root_&&1===t.parent.color;)ze(t)===Xe(ze(ze(t)))?1===Ye(e=Ue(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Ue(ze(t))&&(t=ze(t),this.rotateLeft(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateRight(ze(ze(t)))):1===Ye(e=Xe(ze(ze(t))))?(je(ze(t),0),je(e,0),je(ze(ze(t)),1),t=ze(ze(t))):(t===Xe(ze(t))&&(t=ze(t),this.rotateRight(t)),je(ze(t),0),je(ze(ze(t)),1),this.rotateLeft(ze(ze(t))));this.root_.color=0}},{key:"values",value:function(){var t=new dt,e=this.getFirstEntry();if(null!==e)for(t.add(e.value);null!==(e=o.successor(e));)t.add(e.value);return t}},{key:"entrySet",value:function(){var t=new Q,e=this.getFirstEntry();if(null!==e)for(t.add(e);null!==(e=o.successor(e));)t.add(e);return t}},{key:"rotateLeft",value:function(t){if(null!=t){var e=t.right;t.right=e.left,null!=e.left&&(e.left.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.left===t?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}}},{key:"rotateRight",value:function(t){if(null!=t){var e=t.left;t.left=e.right,null!=e.right&&(e.right.parent=t),e.parent=t.parent,null==t.parent?this.root_=e:t.parent.right===t?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}}},{key:"getFirstEntry",value:function(){var t=this.root_;if(null!=t)for(;null!=t.left;)t=t.left;return t}},{key:"size",value:function(){return this.size_}},{key:"containsKey",value:function(t){for(var e=this.root_;null!==e;){var n=t.compareTo(e.key);if(n<0)e=e.left;else{if(!(n>0))return!0;e=e.right}}return!1}}],[{key:"successor",value:function(t){var e;if(null===t)return null;if(null!==t.right){for(e=t.right;null!==e.left;)e=e.left;return e}e=t.parent;for(var n=t;null!==e&&n===e.right;)n=e,e=e.parent;return e}}]),o}(Be),He=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"find",value:function(t){return this.nodeMap.get(t)}},{key:"addNode",value:function(){if(arguments[0]instanceof z){var t=arguments[0],e=this.nodeMap.get(t);return null===e&&(e=this.nodeFact.createNode(t),this.nodeMap.put(t,e)),e}if(arguments[0]instanceof Ge){var n=arguments[0],r=this.nodeMap.get(n.getCoordinate());return null===r?(this.nodeMap.put(n.getCoordinate(),n),n):(r.mergeLabel(n),r)}}},{key:"print",value:function(t){for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this.nodeMap.values().iterator()}},{key:"values",value:function(){return this.nodeMap.values()}},{key:"getBoundaryNodes",value:function(t){for(var e=new dt,n=this.iterator();n.hasNext();){var r=n.next();r.getLabel().getLocation(t)===Z.BOUNDARY&&e.add(r)}return e}},{key:"add",value:function(t){var e=t.getCoordinate();this.addNode(e).add(t)}}],[{key:"constructor_",value:function(){this.nodeMap=new Ze,this.nodeFact=null;var t=arguments[0];this.nodeFact=t}}]),e}(),We=function(){function e(){t(this,e)}return n(e,null,[{key:"isNorthern",value:function(t){return t===e.NE||t===e.NW}},{key:"isOpposite",value:function(t,e){return t!==e&&2==(t-e+4)%4}},{key:"commonHalfPlane",value:function(t,e){if(t===e)return t;if(2==(t-e+4)%4)return-1;var n=te?t:e)?3:n}},{key:"isInHalfPlane",value:function(t,n){return n===e.SE?t===e.SE||t===e.SW:t===n||t===n+1}},{key:"quadrant",value:function(){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var t=arguments[0],n=arguments[1];if(0===t&&0===n)throw new x("Cannot compute the quadrant for point ( "+t+", "+n+" )");return t>=0?n>=0?e.NE:e.SE:n>=0?e.NW:e.SW}if(arguments[0]instanceof z&&arguments[1]instanceof z){var r=arguments[0],i=arguments[1];if(i.x===r.x&&i.y===r.y)throw new x("Cannot compute the quadrant for two identical points "+r);return i.x>=r.x?i.y>=r.y?e.NE:e.SE:i.y>=r.y?e.NW:e.SW}}}]),e}();We.NE=0,We.NW=1,We.SW=2,We.SE=3;var Je=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareDirection",value:function(t){return this._dx===t._dx&&this._dy===t._dy?0:this._quadrant>t._quadrant?1:this._quadrant2){o.linkDirectedEdgesForMinimalEdgeRings();var s=o.buildMinimalRings(),a=this.findShell(s);null!==a?(this.placePolygonHoles(a,s),e.add(a)):n.addAll(s)}else r.add(o)}return r}},{key:"buildMaximalEdgeRings",value:function(t){for(var e=new dt,n=t.iterator();n.hasNext();){var r=n.next();if(r.isInResult()&&r.getLabel().isArea()&&null===r.getEdgeRing()){var i=new qe(r,this._geometryFactory);e.add(i),i.setInResult()}}return e}},{key:"placePolygonHoles",value:function(t,e){for(var n=e.iterator();n.hasNext();){var r=n.next();r.isHole()&&r.setShell(t)}}},{key:"getPolygons",value:function(){return this.computePolygons(this._shellList)}},{key:"findShell",value:function(t){for(var e=0,n=null,r=t.iterator();r.hasNext();){var i=r.next();i.isHole()||(n=i,e++)}return V.isTrue(e<=1,"found two shells in MinimalEdgeRing list"),n}},{key:"add",value:function(){if(1===arguments.length){var t=arguments[0];this.add(t.getEdgeEnds(),t.getNodes())}else if(2===arguments.length){var e=arguments[0],n=arguments[1];$e.linkResultDirectedEdges(n);var r=this.buildMaximalEdgeRings(e),i=new dt,o=this.buildMinimalEdgeRings(r,this._shellList,i);this.sortShellsAndHoles(o,this._shellList,i),this.placeFreeHoles(this._shellList,i)}}}],[{key:"constructor_",value:function(){this._geometryFactory=null,this._shellList=new dt;var t=arguments[0];this._geometryFactory=t}},{key:"findEdgeRingContaining",value:function(t,e){for(var n=t.getLinearRing(),r=n.getEnvelopeInternal(),i=n.getCoordinateN(0),o=null,s=null,a=e.iterator();a.hasNext();){var u=a.next(),l=u.getLinearRing(),h=l.getEnvelopeInternal();if(!h.equals(r)&&h.contains(r)){i=Wt.ptNotInList(n.getCoordinates(),l.getCoordinates());var c=!1;Oe.isInRing(i,l.getCoordinates())&&(c=!0),c&&(null===o||s.contains(h))&&(s=(o=u).getLinearRing().getEnvelopeInternal())}}return o}}]),e}(),en=function(){function e(){t(this,e)}return n(e,[{key:"getBounds",value:function(){}}]),e}(),nn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getItem",value:function(){return this._item}},{key:"getBounds",value:function(){return this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){this._bounds=null,this._item=null;var t=arguments[0],e=arguments[1];this._bounds=t,this._item=e}}]),e}(),rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"poll",value:function(){if(this.isEmpty())return null;var t=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),t}},{key:"size",value:function(){return this._size}},{key:"reorder",value:function(t){for(var e=null,n=this._items.get(t);2*t<=this._size&&((e=2*t)!==this._size&&this._items.get(e+1).compareTo(this._items.get(e))<0&&e++,this._items.get(e).compareTo(n)<0);t=e)this._items.set(t,this._items.get(e));this._items.set(t,n)}},{key:"clear",value:function(){this._size=0,this._items.clear()}},{key:"peek",value:function(){return this.isEmpty()?null:this._items.get(1)}},{key:"isEmpty",value:function(){return 0===this._size}},{key:"add",value:function(t){this._items.add(null),this._size+=1;var e=this._size;for(this._items.set(0,t);t.compareTo(this._items.get(Math.trunc(e/2)))<0;e/=2)this._items.set(e,this._items.get(Math.trunc(e/2)));this._items.set(e,t)}}],[{key:"constructor_",value:function(){this._size=null,this._items=null,this._size=0,this._items=new dt,this._items.add(null)}}]),e}(),on=function(){function e(){t(this,e)}return n(e,[{key:"insert",value:function(t,e){}},{key:"remove",value:function(t,e){}},{key:"query",value:function(){}}]),e}(),sn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLevel",value:function(){return this._level}},{key:"size",value:function(){return this._childBoundables.size()}},{key:"getChildBoundables",value:function(){return this._childBoundables}},{key:"addChildBoundable",value:function(t){V.isTrue(null===this._bounds),this._childBoundables.add(t)}},{key:"isEmpty",value:function(){return this._childBoundables.isEmpty()}},{key:"getBounds",value:function(){return null===this._bounds&&(this._bounds=this.computeBounds()),this._bounds}},{key:"interfaces_",get:function(){return[en,w]}}],[{key:"constructor_",value:function(){if(this._childBoundables=new dt,this._bounds=null,this._level=null,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._level=t}}}]),e}(),an={reverseOrder:function(){return{compare:function(t,e){return e.compareTo(t)}}},min:function(t){return an.sort(t),t.get(0)},sort:function(t,e){var n=t.toArray();e?At.sort(n,e):At.sort(n);for(var r=t.iterator(),i=0,o=n.length;ie.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,!1,t,n),null):(this.expand(this._boundable2,this._boundable1,!0,t,n),null);if(r)return this.expand(this._boundable1,this._boundable2,!1,t,n),null;if(i)return this.expand(this._boundable2,this._boundable1,!0,t,n),null;throw new x("neither boundable is composite")}},{key:"isLeaves",value:function(){return!(e.isComposite(this._boundable1)||e.isComposite(this._boundable2))}},{key:"compareTo",value:function(t){var e=t;return this._distancee._distance?1:0}},{key:"expand",value:function(t,n,r,i,o){for(var s=t.getChildBoundables().iterator();s.hasNext();){var a=s.next(),u=null;(u=r?new e(n,a,this._itemDistance):new e(a,n,this._itemDistance)).getDistance()-2),r.getLevel()===n)return i.add(r),null;for(var o=r.getChildBoundables().iterator();o.hasNext();){var s=o.next();s instanceof sn?this.boundablesAtLevel(n,s,i):(V.isTrue(s instanceof nn),-1===n&&i.add(s))}return null}}},{key:"query",value:function(){if(1===arguments.length){var t=arguments[0];this.build();var e=new dt;return this.isEmpty()||this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.queryInternal(t,this._root,e),e}if(2===arguments.length){var n=arguments[0],r=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),n)&&this.queryInternal(n,this._root,r)}}},{key:"build",value:function(){if(this._built)return null;this._root=this._itemBoundables.isEmpty()?this.createNode(0):this.createHigherLevels(this._itemBoundables,-1),this._itemBoundables=null,this._built=!0}},{key:"getRoot",value:function(){return this.build(),this._root}},{key:"remove",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];return this.build(),!!this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.remove(t,this._root,e)}if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],o=this.removeItem(r,i);if(o)return!0;for(var s=null,a=r.getChildBoundables().iterator();a.hasNext();){var u=a.next();if(this.getIntersectsOp().intersects(u.getBounds(),n)&&u instanceof sn&&(o=this.remove(n,u,i))){s=u;break}}return null!==s&&s.getChildBoundables().isEmpty()&&r.getChildBoundables().remove(s),o}}},{key:"createHigherLevels",value:function(t,e){V.isTrue(!t.isEmpty());var n=this.createParentBoundables(t,e+1);return 1===n.size()?n.get(0):this.createHigherLevels(n,e+1)}},{key:"depth",value:function(){if(0===arguments.length)return this.isEmpty()?0:(this.build(),this.depth(this._root));if(1===arguments.length){for(var t=0,e=arguments[0].getChildBoundables().iterator();e.hasNext();){var n=e.next();if(n instanceof sn){var r=this.depth(n);r>t&&(t=r)}}return t+1}}},{key:"createParentBoundables",value:function(t,e){V.isTrue(!t.isEmpty());var n=new dt;n.add(this.createNode(e));var r=new dt(t);an.sort(r,this.getComparator());for(var i=r.iterator();i.hasNext();){var o=i.next();this.lastNode(n).getChildBoundables().size()===this.getNodeCapacity()&&n.add(this.createNode(e)),this.lastNode(n).addChildBoundable(o)}return n}},{key:"isEmpty",value:function(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()}},{key:"interfaces_",get:function(){return[w]}}],[{key:"constructor_",value:function(){if(this._root=null,this._built=!1,this._itemBoundables=new dt,this._nodeCapacity=null,0===arguments.length)e.constructor_.call(this,e.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];V.isTrue(t>1,"Node capacity must be greater than 1"),this._nodeCapacity=t}}},{key:"compareDoubles",value:function(t,e){return t>e?1:t0);for(var n=new dt,r=0;r=0;){var u=o.poll(),l=u.getDistance();if(l>=i)break;u.isLeaves()?a.size()l&&(a.poll(),a.add(u)),i=a.peek().getDistance()):u.expandToQueue(o,i)}return s.getItems(a)}}},{key:"createNode",value:function(t){return new pn(t)}},{key:"size",value:function(){return 0===arguments.length?f(i(s.prototype),"size",this).call(this):f(i(s.prototype),"size",this).apply(this,arguments)}},{key:"insert",value:function(){if(!(2===arguments.length&&arguments[1]instanceof Object&&arguments[0]instanceof X))return f(i(s.prototype),"insert",this).apply(this,arguments);var t=arguments[0],e=arguments[1];if(t.isNull())return null;f(i(s.prototype),"insert",this).call(this,t,e)}},{key:"getIntersectsOp",value:function(){return s.intersectsOp}},{key:"verticalSlices",value:function(t,e){for(var n=Math.trunc(Math.ceil(t.size()/e)),r=new Array(e).fill(null),i=t.iterator(),o=0;o0;){var s=o.poll(),a=s.getDistance();if(a>=r)break;s.isLeaves()?(r=a,i=s):s.expandToQueue(o,r)}return null===i?null:[i.getBoundable(0).getItem(),i.getBoundable(1).getItem()]}}else{if(2===arguments.length){var u=arguments[0],l=arguments[1];if(this.isEmpty()||u.isEmpty())return null;var h=new ln(this.getRoot(),u.getRoot(),l);return this.nearestNeighbour(h)}if(3===arguments.length){var c=arguments[2],f=new nn(arguments[0],arguments[1]),g=new ln(this.getRoot(),f,c);return this.nearestNeighbour(g)[0]}if(4===arguments.length){var p=arguments[2],v=arguments[3],d=new nn(arguments[0],arguments[1]),y=new ln(this.getRoot(),d,p);return this.nearestNeighbourK(y,v)}}}},{key:"isWithinDistance",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1],n=A.POSITIVE_INFINITY,r=new rn;for(r.add(t);!r.isEmpty();){var i=r.poll(),o=i.getDistance();if(o>e)return!1;if(i.maximumDistance()<=e)return!0;if(i.isLeaves()){if((n=o)<=e)return!0}else i.expandToQueue(r,n)}return!1}if(3===arguments.length){var s=arguments[0],a=arguments[1],u=arguments[2],l=new ln(this.getRoot(),s.getRoot(),a);return this.isWithinDistance(l,u)}}},{key:"interfaces_",get:function(){return[on,w]}}],[{key:"constructor_",value:function(){if(0===arguments.length)s.constructor_.call(this,s.DEFAULT_NODE_CAPACITY);else if(1===arguments.length){var t=arguments[0];cn.constructor_.call(this,t)}}},{key:"centreX",value:function(t){return s.avg(t.getMinX(),t.getMaxX())}},{key:"avg",value:function(t,e){return(t+e)/2}},{key:"getItems",value:function(t){for(var e=new Array(t.size()).fill(null),n=0;!t.isEmpty();){var r=t.poll();e[n]=r.getBoundable(0).getItem(),n++}return e}},{key:"centreY",value:function(t){return s.avg(t.getMinY(),t.getMaxY())}}]),s}(cn),pn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,[{key:"computeBounds",value:function(){for(var t=null,e=this.getChildBoundables().iterator();e.hasNext();){var n=e.next();null===t?t=new X(n.getBounds()):t.expandToInclude(n.getBounds())}return t}}],[{key:"constructor_",value:function(){var t=arguments[0];sn.constructor_.call(this,t)}}]),o}(sn);gn.STRtreeNode=pn,gn.xComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreX(t.getBounds()),gn.centreX(e.getBounds()))}}]),e}()),gn.yComparator=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[D]}},{key:"compare",value:function(t,e){return cn.compareDoubles(gn.centreY(t.getBounds()),gn.centreY(e.getBounds()))}}]),e}()),gn.intersectsOp=new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[IntersectsOp]}},{key:"intersects",value:function(t,e){return t.intersects(e)}}]),e}()),gn.DEFAULT_NODE_CAPACITY=10;var vn=function(){function e(){t(this,e)}return n(e,null,[{key:"relativeSign",value:function(t,e){return te?1:0}},{key:"compare",value:function(t,n,r){if(n.equals2D(r))return 0;var i=e.relativeSign(n.x,r.x),o=e.relativeSign(n.y,r.y);switch(t){case 0:return e.compareValue(i,o);case 1:return e.compareValue(o,i);case 2:return e.compareValue(o,-i);case 3:return e.compareValue(-i,o);case 4:return e.compareValue(-i,-o);case 5:return e.compareValue(-o,-i);case 6:return e.compareValue(-o,i);case 7:return e.compareValue(i,-o)}return V.shouldNeverReachHere("invalid octant value"),0}},{key:"compareValue",value:function(t,e){return t<0?-1:t>0?1:e<0?-1:e>0?1:0}}]),e}(),dn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinate",value:function(){return this.coord}},{key:"print",value:function(t){t.print(this.coord),t.print(" seg # = "+this.segmentIndex)}},{key:"compareTo",value:function(t){var e=t;return this.segmentIndexe.segmentIndex?1:this.coord.equals2D(e.coord)?0:this._isInterior?e._isInterior?vn.compare(this._segmentOctant,this.coord,e.coord):1:-1}},{key:"isEndPoint",value:function(t){return 0===this.segmentIndex&&!this._isInterior||this.segmentIndex===t}},{key:"toString",value:function(){return this.segmentIndex+":"+this.coord.toString()}},{key:"isInterior",value:function(){return this._isInterior}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;var t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this._segString=t,this.coord=new z(e),this.segmentIndex=n,this._segmentOctant=r,this._isInterior=!e.equals2D(t.getCoordinate(n))}}]),e}(),yn=function(){function e(){t(this,e)}return n(e,[{key:"hasNext",value:function(){}},{key:"next",value:function(){}},{key:"remove",value:function(){}}]),e}(),mn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getSplitCoordinates",value:function(){var t=new Ht;this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next();this.addEdgeCoordinates(n,r,t),n=r}return t.toCoordinateArray()}},{key:"addCollapsedNodes",value:function(){var t=new dt;this.findCollapsesFromInsertedNodes(t),this.findCollapsesFromExistingVertices(t);for(var e=t.iterator();e.hasNext();){var n=e.next().intValue();this.add(this._edge.getCoordinate(n),n)}}},{key:"createSplitEdgePts",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2;if(2===n)return[new z(t.coord),new z(e.coord)];var r=this._edge.getCoordinate(e.segmentIndex),i=e.isInterior()||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this._edge.getCoordinate(a);return i&&(o[s]=new z(e.coord)),o}},{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"findCollapsesFromExistingVertices",value:function(t){for(var e=0;e=0?n>=0?r>=i?0:1:r>=i?7:6:n>=0?r>=i?3:2:r>=i?4:5}if(arguments[0]instanceof z&&arguments[1]instanceof z){var o=arguments[0],s=arguments[1],a=s.x-o.x,u=s.y-o.y;if(0===a&&0===u)throw new x("Cannot compute the octant for two identical points "+o);return e.octant(a,u)}}}]),e}(),xn=function(){function e(){t(this,e)}return n(e,[{key:"getCoordinates",value:function(){}},{key:"size",value:function(){}},{key:"getCoordinate",value:function(t){}},{key:"isClosed",value:function(){}},{key:"setData",value:function(t){}},{key:"getData",value:function(){}}]),e}(),En=function(){function e(){t(this,e)}return n(e,[{key:"addIntersection",value:function(t,e){}},{key:"interfaces_",get:function(){return[xn]}}]),e}(),kn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getCoordinates",value:function(){return this._pts}},{key:"size",value:function(){return this._pts.length}},{key:"getCoordinate",value:function(t){return this._pts[t]}},{key:"isClosed",value:function(){return this._pts[0].equals(this._pts[this._pts.length-1])}},{key:"getSegmentOctant",value:function(t){return t===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(t),this.getCoordinate(t+1))}},{key:"setData",value:function(t){this._data=t}},{key:"safeOctant",value:function(t,e){return t.equals2D(e)?0:_n.octant(t,e)}},{key:"getData",value:function(){return this._data}},{key:"addIntersection",value:function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];this.addIntersectionNode(t,e)}else if(4===arguments.length){var n=arguments[1],r=arguments[3],i=new z(arguments[0].getIntersection(r));this.addIntersection(i,n)}}},{key:"toString",value:function(){return Le.toLineString(new $t(this._pts))}},{key:"getNodeList",value:function(){return this._nodeList}},{key:"addIntersectionNode",value:function(t,e){var n=e,r=n+1;if(r=0&&r>=0||n<=0&&r<=0?Math.max(n,r):0}if(arguments[0]instanceof z){var i=arguments[0];return ft.index(this.p0,this.p1,i)}}},{key:"toGeometry",value:function(t){return t.createLineString([this.p0,this.p1])}},{key:"isVertical",value:function(){return this.p0.x===this.p1.x}},{key:"equals",value:function(t){if(!(t instanceof e))return!1;var n=t;return this.p0.equals(n.p0)&&this.p1.equals(n.p1)}},{key:"intersection",value:function(t){var e=new Ce;return e.computeIntersection(this.p0,this.p1,t.p0,t.p1),e.hasIntersection()?e.getIntersection(0):null}},{key:"project",value:function(){if(arguments[0]instanceof z){var t=arguments[0];if(t.equals(this.p0)||t.equals(this.p1))return new z(t);var n=this.projectionFactor(t),r=new z;return r.x=this.p0.x+n*(this.p1.x-this.p0.x),r.y=this.p0.y+n*(this.p1.y-this.p0.y),r}if(arguments[0]instanceof e){var i=arguments[0],o=this.projectionFactor(i.p0),s=this.projectionFactor(i.p1);if(o>=1&&s>=1)return null;if(o<=0&&s<=0)return null;var a=this.project(i.p0);o<0&&(a=this.p0),o>1&&(a=this.p1);var u=this.project(i.p1);return s<0&&(u=this.p0),s>1&&(u=this.p1),new e(a,u)}}},{key:"normalize",value:function(){this.p1.compareTo(this.p0)<0&&this.reverse()}},{key:"angle",value:function(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)}},{key:"getCoordinate",value:function(t){return 0===t?this.p0:this.p1}},{key:"distancePerpendicular",value:function(t){return kt.pointToLinePerpendicular(t,this.p0,this.p1)}},{key:"minY",value:function(){return Math.min(this.p0.y,this.p1.y)}},{key:"midPoint",value:function(){return e.midPoint(this.p0,this.p1)}},{key:"projectionFactor",value:function(t){if(t.equals(this.p0))return 0;if(t.equals(this.p1))return 1;var e=this.p1.x-this.p0.x,n=this.p1.y-this.p0.y,r=e*e+n*n;return r<=0?A.NaN:((t.x-this.p0.x)*e+(t.y-this.p0.y)*n)/r}},{key:"closestPoints",value:function(t){var e=this.intersection(t);if(null!==e)return[e,e];var n=new Array(2).fill(null),r=A.MAX_VALUE,i=null,o=this.closestPoint(t.p0);r=o.distance(t.p0),n[0]=o,n[1]=t.p0;var s=this.closestPoint(t.p1);(i=s.distance(t.p1))0&&e<1?this.project(t):this.p0.distance(t)1||A.isNaN(e))&&(e=1),e}},{key:"toString",value:function(){return"LINESTRING( "+this.p0.x+" "+this.p0.y+", "+this.p1.x+" "+this.p1.y+")"}},{key:"isHorizontal",value:function(){return this.p0.y===this.p1.y}},{key:"reflect",value:function(t){var e=this.p1.getY()-this.p0.getY(),n=this.p0.getX()-this.p1.getX(),r=this.p0.getY()*(this.p1.getX()-this.p0.getX())-this.p0.getX()*(this.p1.getY()-this.p0.getY()),i=e*e+n*n,o=e*e-n*n,s=t.getX(),a=t.getY();return new z((-o*s-2*e*n*a-2*e*r)/i,(o*a-2*e*n*s-2*n*r)/i)}},{key:"distance",value:function(){if(arguments[0]instanceof e){var t=arguments[0];return kt.segmentToSegment(this.p0,this.p1,t.p0,t.p1)}if(arguments[0]instanceof z){var n=arguments[0];return kt.pointToSegment(n,this.p0,this.p1)}}},{key:"pointAlong",value:function(t){var e=new z;return e.x=this.p0.x+t*(this.p1.x-this.p0.x),e.y=this.p0.y+t*(this.p1.y-this.p0.y),e}},{key:"hashCode",value:function(){var t=A.doubleToLongBits(this.p0.x);t^=31*A.doubleToLongBits(this.p0.y);var e=Math.trunc(t)^Math.trunc(t>>32),n=A.doubleToLongBits(this.p1.x);return n^=31*A.doubleToLongBits(this.p1.y),e^Math.trunc(n)^Math.trunc(n>>32)}},{key:"interfaces_",get:function(){return[k,w]}}],[{key:"constructor_",value:function(){if(this.p0=null,this.p1=null,0===arguments.length)e.constructor_.call(this,new z,new z);else if(1===arguments.length){var t=arguments[0];e.constructor_.call(this,t.p0,t.p1)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.p0=n,this.p1=r}else if(4===arguments.length){var i=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];e.constructor_.call(this,new z(i,o),new z(s,a))}}},{key:"midPoint",value:function(t,e){return new z((t.x+e.x)/2,(t.y+e.y)/2)}}]),e}(),wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"overlap",value:function(){if(2===arguments.length);else if(4===arguments.length){var t=arguments[1],e=arguments[2],n=arguments[3];arguments[0].getLineSegment(t,this._overlapSeg1),e.getLineSegment(n,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}}}],[{key:"constructor_",value:function(){this._overlapSeg1=new bn,this._overlapSeg2=new bn}}]),e}(),In=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getLineSegment",value:function(t,e){e.p0=this._pts[t],e.p1=this._pts[t+1]}},{key:"computeSelect",value:function(t,e,n,r){var i=this._pts[e],o=this._pts[n];if(n-e==1)return r.select(this,e),null;if(!t.intersects(i,o))return null;var s=Math.trunc((e+n)/2);e=t.length-1)return t.length-1;for(var r=We.quadrant(t[n],t[n+1]),i=e+1;in.getId()&&(n.computeOverlaps(i,t),this._nOverlaps++),this._segInt.isDone())return null}}}],[{key:"constructor_",value:function(){if(this._monoChains=new dt,this._index=new gn,this._idCounter=0,this._nodedSegStrings=null,this._nOverlaps=0,0===arguments.length);else if(1===arguments.length){var t=arguments[0];Mn.constructor_.call(this,t)}}}]),o}(Mn),Pn=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"overlap",value:function(){if(4!==arguments.length)return f(i(s.prototype),"overlap",this).apply(this,arguments);var t=arguments[1],e=arguments[2],n=arguments[3],r=arguments[0].getContext(),o=e.getContext();this._si.processIntersections(r,t,o,n)}}],[{key:"constructor_",value:function(){this._si=null;var t=arguments[0];this._si=t}}]),s}(wn);Ln.SegmentOverlapAction=Pn;var Cn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isDeletable",value:function(t,e,n,r){var i=this._inputLine[t],o=this._inputLine[e],s=this._inputLine[n];return!!this.isConcave(i,o,s)&&!!this.isShallow(i,o,s,r)&&this.isShallowSampled(i,o,t,n,r)}},{key:"deleteShallowConcavities",value:function(){for(var t=1,n=this.findNextNonDeletedIndex(t),r=this.findNextNonDeletedIndex(n),i=!1;r=0;r--)this.addPt(t[r])}},{key:"isRedundant",value:function(t){if(this._ptList.size()<1)return!1;var e=this._ptList.get(this._ptList.size()-1);return t.distance(e)Math.PI;)t-=e.PI_TIMES_2;for(;t<=-Math.PI;)t+=e.PI_TIMES_2;return t}},{key:"angle",value:function(){if(1===arguments.length){var t=arguments[0];return Math.atan2(t.y,t.x)}if(2===arguments.length){var e=arguments[0],n=arguments[1],r=n.x-e.x,i=n.y-e.y;return Math.atan2(i,r)}}},{key:"isAcute",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)>0}},{key:"isObtuse",value:function(t,e,n){var r=t.x-e.x,i=t.y-e.y;return r*(n.x-e.x)+i*(n.y-e.y)<0}},{key:"interiorAngle",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return Math.abs(o-i)}},{key:"normalizePositive",value:function(t){if(t<0){for(;t<0;)t+=e.PI_TIMES_2;t>=e.PI_TIMES_2&&(t=0)}else{for(;t>=e.PI_TIMES_2;)t-=e.PI_TIMES_2;t<0&&(t=0)}return t}},{key:"angleBetween",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r);return e.diff(i,o)}},{key:"diff",value:function(t,e){var n=null;return(n=tMath.PI&&(n=2*Math.PI-n),n}},{key:"toRadians",value:function(t){return t*Math.PI/180}},{key:"getTurn",value:function(t,n){var r=Math.sin(n-t);return r>0?e.COUNTERCLOCKWISE:r<0?e.CLOCKWISE:e.NONE}},{key:"angleBetweenOriented",value:function(t,n,r){var i=e.angle(n,t),o=e.angle(n,r)-i;return o<=-Math.PI?o+e.PI_TIMES_2:o>Math.PI?o-e.PI_TIMES_2:o}}]),e}();On.PI_TIMES_2=2*Math.PI,On.PI_OVER_2=Math.PI/2,On.PI_OVER_4=Math.PI/4,On.COUNTERCLOCKWISE=ft.COUNTERCLOCKWISE,On.CLOCKWISE=ft.CLOCKWISE,On.NONE=ft.COLLINEAR;var Rn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addNextSegment",value:function(t,e){if(this._s0=this._s1,this._s1=this._s2,this._s2=t,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;var n=ft.index(this._s0,this._s1,this._s2),r=n===ft.CLOCKWISE&&this._side===tt.LEFT||n===ft.COUNTERCLOCKWISE&&this._side===tt.RIGHT;0===n?this.addCollinear(e):r?this.addOutsideTurn(n,e):this.addInsideTurn(n,e)}},{key:"addLineEndCap",value:function(t,e){var n=new bn(t,e),r=new bn;this.computeOffsetSegment(n,tt.LEFT,this._distance,r);var i=new bn;this.computeOffsetSegment(n,tt.RIGHT,this._distance,i);var o=e.x-t.x,s=e.y-t.y,a=Math.atan2(s,o);switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:this._segList.addPt(r.p1),this.addDirectedFillet(e,a+Math.PI/2,a-Math.PI/2,ft.CLOCKWISE,this._distance),this._segList.addPt(i.p1);break;case y.CAP_FLAT:this._segList.addPt(r.p1),this._segList.addPt(i.p1);break;case y.CAP_SQUARE:var u=new z;u.x=Math.abs(this._distance)*Math.cos(a),u.y=Math.abs(this._distance)*Math.sin(a);var l=new z(r.p1.x+u.x,r.p1.y+u.y),h=new z(i.p1.x+u.x,i.p1.y+u.y);this._segList.addPt(l),this._segList.addPt(h)}}},{key:"getCoordinates",value:function(){return this._segList.getCoordinates()}},{key:"addMitreJoin",value:function(t,e,n,r){var i=_t.intersection(e.p0,e.p1,n.p0,n.p1);if(null!==i&&(r<=0?1:i.distance(t)/Math.abs(r))<=this._bufParams.getMitreLimit())return this._segList.addPt(i),null;this.addLimitedMitreJoin(e,n,r,this._bufParams.getMitreLimit())}},{key:"addOutsideTurn",value:function(t,n){if(this._offset0.p1.distance(this._offset1.p0)=h&&(a-=2*Math.PI),this._segList.addPt(e),this.addDirectedFillet(t,a,h,r,i),this._segList.addPt(n)}},{key:"addLastSegment",value:function(){this._segList.addPt(this._offset1.p1)}},{key:"initSideSegments",value:function(t,e,n){this._s1=t,this._s2=e,this._side=n,this._seg1.setCoordinates(t,e),this.computeOffsetSegment(this._seg1,n,this._distance,this._offset1)}},{key:"addLimitedMitreJoin",value:function(t,e,n,r){var i=this._seg0.p1,o=On.angle(i,this._seg0.p0),s=On.angleBetweenOriented(this._seg0.p0,i,this._seg1.p1)/2,a=On.normalize(o+s),u=On.normalize(a+Math.PI),l=r*n,h=n-l*Math.abs(Math.sin(s)),c=i.x+l*Math.cos(u),f=i.y+l*Math.sin(u),g=new z(c,f),p=new bn(i,g),v=p.pointAlongOffset(1,h),d=p.pointAlongOffset(1,-h);this._side===tt.LEFT?(this._segList.addPt(v),this._segList.addPt(d)):(this._segList.addPt(d),this._segList.addPt(v))}},{key:"addDirectedFillet",value:function(t,e,n,r,i){var o=r===ft.CLOCKWISE?-1:1,s=Math.abs(e-n),a=Math.trunc(s/this._filletAngleQuantum+.5);if(a<1)return null;for(var u=s/a,l=new z,h=0;h0){var r=new z((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(r);var i=new z((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(i)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}}},{key:"createCircle",value:function(t){var e=new z(t.x+this._distance,t.y);this._segList.addPt(e),this.addDirectedFillet(t,0,2*Math.PI,-1,this._distance),this._segList.closeRing()}},{key:"addBevelJoin",value:function(t,e){this._segList.addPt(t.p1),this._segList.addPt(e.p0)}},{key:"init",value:function(t){this._distance=t,this._maxCurveSegmentError=t*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new Tn,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(t*e.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)}},{key:"addCollinear",value:function(t){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2),this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===y.JOIN_BEVEL||this._bufParams.getJoinStyle()===y.JOIN_MITRE?(t&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,ft.CLOCKWISE,this._distance))}},{key:"closeRing",value:function(){this._segList.closeRing()}},{key:"hasNarrowConcaveAngle",value:function(){return this._hasNarrowConcaveAngle}}],[{key:"constructor_",value:function(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new bn,this._seg1=new bn,this._offset0=new bn,this._offset1=new bn,this._side=0,this._hasNarrowConcaveAngle=!1;var t=arguments[0],n=arguments[1],r=arguments[2];this._precisionModel=t,this._bufParams=n,this._li=new Ce,this._filletAngleQuantum=Math.PI/2/n.getQuadrantSegments(),n.getQuadrantSegments()>=8&&n.getJoinStyle()===y.JOIN_ROUND&&(this._closingSegLengthFactor=e.MAX_CLOSING_SEG_LEN_FACTOR),this.init(r)}}]),e}();Rn.OFFSET_SEGMENT_SEPARATION_FACTOR=.001,Rn.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR=.001,Rn.CURVE_VERTEX_SNAP_DISTANCE_FACTOR=1e-6,Rn.MAX_CLOSING_SEG_LEN_FACTOR=80;var An=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getOffsetCurve",value:function(t,e){if(this._distance=e,0===e)return null;var n=e<0,r=Math.abs(e),i=this.getSegGen(r);t.length<=1?this.computePointCurve(t[0],i):this.computeOffsetCurve(t,n,i);var o=i.getCoordinates();return n&&Wt.reverse(o),o}},{key:"computeSingleSidedBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){n.addSegments(t,!0);var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{n.addSegments(t,!1);var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment(),n.closeRing()}},{key:"computeRingBufferCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);e===tt.RIGHT&&(r=-r);var i=Cn.simplify(t,r),o=i.length-1;n.initSideSegments(i[o-1],i[0],e);for(var s=1;s<=o;s++){var a=1!==s;n.addNextSegment(i[s],a)}n.closeRing()}},{key:"computeLineBufferCurve",value:function(t,e){var n=this.simplifyTolerance(this._distance),r=Cn.simplify(t,n),i=r.length-1;e.initSideSegments(r[0],r[1],tt.LEFT);for(var o=2;o<=i;o++)e.addNextSegment(r[o],!0);e.addLastSegment(),e.addLineEndCap(r[i-1],r[i]);var s=Cn.simplify(t,-n),a=s.length-1;e.initSideSegments(s[a],s[a-1],tt.LEFT);for(var u=a-2;u>=0;u--)e.addNextSegment(s[u],!0);e.addLastSegment(),e.addLineEndCap(s[1],s[0]),e.closeRing()}},{key:"computePointCurve",value:function(t,e){switch(this._bufParams.getEndCapStyle()){case y.CAP_ROUND:e.createCircle(t);break;case y.CAP_SQUARE:e.createSquare(t)}}},{key:"getLineCurve",value:function(t,e){if(this._distance=e,this.isLineOffsetEmpty(e))return null;var n=Math.abs(e),r=this.getSegGen(n);if(t.length<=1)this.computePointCurve(t[0],r);else if(this._bufParams.isSingleSided()){var i=e<0;this.computeSingleSidedBufferCurve(t,i,r)}else this.computeLineBufferCurve(t,r);return r.getCoordinates()}},{key:"getBufferParameters",value:function(){return this._bufParams}},{key:"simplifyTolerance",value:function(t){return t*this._bufParams.getSimplifyFactor()}},{key:"getRingCurve",value:function(t,n,r){if(this._distance=r,t.length<=2)return this.getLineCurve(t,r);if(0===r)return e.copyCoordinates(t);var i=this.getSegGen(r);return this.computeRingBufferCurve(t,n,i),i.getCoordinates()}},{key:"computeOffsetCurve",value:function(t,e,n){var r=this.simplifyTolerance(this._distance);if(e){var i=Cn.simplify(t,-r),o=i.length-1;n.initSideSegments(i[o],i[o-1],tt.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(i[s],!0)}else{var a=Cn.simplify(t,r),u=a.length-1;n.initSideSegments(a[0],a[1],tt.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment()}},{key:"isLineOffsetEmpty",value:function(t){return 0===t||t<0&&!this._bufParams.isSingleSided()}},{key:"getSegGen",value:function(t){return new Rn(this._precisionModel,this._bufParams,t)}}],[{key:"constructor_",value:function(){this._distance=0,this._precisionModel=null,this._bufParams=null;var t=arguments[0],e=arguments[1];this._precisionModel=t,this._bufParams=e}},{key:"copyCoordinates",value:function(t){for(var e=new Array(t.length).fill(null),n=0;ni.getMaxY()||this.findStabbedSegments(t,r.getDirectedEdges(),e)}return e}if(3===arguments.length)if(ot(arguments[2],rt)&&arguments[0]instanceof z&&arguments[1]instanceof Ke){for(var o=arguments[0],s=arguments[1],a=arguments[2],u=s.getEdge().getCoordinates(),l=0;lthis._seg.p1.y&&this._seg.reverse(),!(Math.max(this._seg.p0.x,this._seg.p1.x)this._seg.p1.y||ft.index(this._seg.p0,this._seg.p1,o)===ft.RIGHT)){var h=s.getDepth(tt.LEFT);this._seg.p0.equals(u[l])||(h=s.getDepth(tt.RIGHT));var c=new Fn(this._seg,h);a.add(c)}}else if(ot(arguments[2],rt)&&arguments[0]instanceof z&&ot(arguments[1],rt))for(var f=arguments[0],g=arguments[2],p=arguments[1].iterator();p.hasNext();){var v=p.next();v.isForward()&&this.findStabbedSegments(f,v,g)}}},{key:"getDepth",value:function(t){var e=this.findStabbedSegments(t);return 0===e.size()?0:an.min(e)._leftDepth}}],[{key:"constructor_",value:function(){this._subgraphs=null,this._seg=new bn;var t=arguments[0];this._subgraphs=t}}]),e}(),Fn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var e=t;if(this._upwardSeg.minX()>=e._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=e._upwardSeg.minX())return-1;var n=this._upwardSeg.orientationIndex(e._upwardSeg);return 0!==n||0!=(n=-1*e._upwardSeg.orientationIndex(this._upwardSeg))?n:this._upwardSeg.compareTo(e._upwardSeg)}},{key:"compareX",value:function(t,e){var n=t.p0.compareTo(e.p0);return 0!==n?n:t.p1.compareTo(e.p1)}},{key:"toString",value:function(){return this._upwardSeg.toString()}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._upwardSeg=null,this._leftDepth=null;var t=arguments[0],e=arguments[1];this._upwardSeg=new bn(t),this._leftDepth=e}}]),e}();Dn.DepthSegment=Fn;var qn=function(e){r(o,e);var i=c(o);function o(){var e;return t(this,o),e=i.call(this),o.constructor_.apply(l(e),arguments),e}return n(o,null,[{key:"constructor_",value:function(){_.constructor_.call(this,"Projective point not representable on the Cartesian plane.")}}]),o}(_),Vn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"getY",value:function(){var t=this.y/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getX",value:function(){var t=this.x/this.w;if(A.isNaN(t)||A.isInfinite(t))throw new qn;return t}},{key:"getCoordinate",value:function(){var t=new z;return t.x=this.getX(),t.y=this.getY(),t}}],[{key:"constructor_",value:function(){if(this.x=null,this.y=null,this.w=null,0===arguments.length)this.x=0,this.y=0,this.w=1;else if(1===arguments.length){var t=arguments[0];this.x=t.x,this.y=t.y,this.w=1}else if(2===arguments.length){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var n=arguments[0],r=arguments[1];this.x=n,this.y=r,this.w=1}else if(arguments[0]instanceof e&&arguments[1]instanceof e){var i=arguments[0],o=arguments[1];this.x=i.y*o.w-o.y*i.w,this.y=o.x*i.w-i.x*o.w,this.w=i.x*o.y-o.x*i.y}else if(arguments[0]instanceof z&&arguments[1]instanceof z){var s=arguments[0],a=arguments[1];this.x=s.y-a.y,this.y=a.x-s.x,this.w=s.x*a.y-a.x*s.y}}else if(3===arguments.length){var u=arguments[0],l=arguments[1],h=arguments[2];this.x=u,this.y=l,this.w=h}else if(4===arguments.length){var c=arguments[0],f=arguments[1],g=arguments[2],p=arguments[3],v=c.y-f.y,d=f.x-c.x,y=c.x*f.y-f.x*c.y,m=g.y-p.y,_=p.x-g.x,x=g.x*p.y-p.x*g.y;this.x=d*x-_*y,this.y=m*y-v*x,this.w=v*_-m*d}}}]),e}(),Gn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"area",value:function(){return e.area(this.p0,this.p1,this.p2)}},{key:"signedArea",value:function(){return e.signedArea(this.p0,this.p1,this.p2)}},{key:"interpolateZ",value:function(t){if(null===t)throw new x("Supplied point is null.");return e.interpolateZ(t,this.p0,this.p1,this.p2)}},{key:"longestSideLength",value:function(){return e.longestSideLength(this.p0,this.p1,this.p2)}},{key:"isAcute",value:function(){return e.isAcute(this.p0,this.p1,this.p2)}},{key:"circumcentre",value:function(){return e.circumcentre(this.p0,this.p1,this.p2)}},{key:"area3D",value:function(){return e.area3D(this.p0,this.p1,this.p2)}},{key:"centroid",value:function(){return e.centroid(this.p0,this.p1,this.p2)}},{key:"inCentre",value:function(){return e.inCentre(this.p0,this.p1,this.p2)}}],[{key:"constructor_",value:function(){this.p0=null,this.p1=null,this.p2=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.p0=t,this.p1=e,this.p2=n}},{key:"area",value:function(t,e,n){return Math.abs(((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2)}},{key:"signedArea",value:function(t,e,n){return((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2}},{key:"det",value:function(t,e,n,r){return t*r-e*n}},{key:"interpolateZ",value:function(t,e,n,r){var i=e.x,o=e.y,s=n.x-i,a=r.x-i,u=n.y-o,l=r.y-o,h=s*l-a*u,c=t.x-i,f=t.y-o,g=(l*c-a*f)/h,p=(-u*c+s*f)/h;return e.getZ()+g*(n.getZ()-e.getZ())+p*(r.getZ()-e.getZ())}},{key:"longestSideLength",value:function(t,e,n){var r=t.distance(e),i=e.distance(n),o=n.distance(t),s=r;return i>s&&(s=i),o>s&&(s=o),s}},{key:"circumcentreDD",value:function(t,e,n){var r=lt.valueOf(t.x).subtract(n.x),i=lt.valueOf(t.y).subtract(n.y),o=lt.valueOf(e.x).subtract(n.x),s=lt.valueOf(e.y).subtract(n.y),a=lt.determinant(r,i,o,s).multiply(2),u=r.sqr().add(i.sqr()),l=o.sqr().add(s.sqr()),h=lt.determinant(i,u,s,l),c=lt.determinant(r,u,o,l),f=lt.valueOf(n.x).subtract(h.divide(a)).doubleValue(),g=lt.valueOf(n.y).add(c.divide(a)).doubleValue();return new z(f,g)}},{key:"isAcute",value:function(t,e,n){return!!On.isAcute(t,e,n)&&!!On.isAcute(e,n,t)&&!!On.isAcute(n,t,e)}},{key:"circumcentre",value:function(t,n,r){var i=r.x,o=r.y,s=t.x-i,a=t.y-o,u=n.x-i,l=n.y-o,h=2*e.det(s,a,u,l),c=e.det(a,s*s+a*a,l,u*u+l*l),f=e.det(s,s*s+a*a,u,u*u+l*l);return new z(i-c/h,o+f/h)}},{key:"perpendicularBisector",value:function(t,e){var n=e.x-t.x,r=e.y-t.y,i=new Vn(t.x+n/2,t.y+r/2,1),o=new Vn(t.x-r+n/2,t.y+n+r/2,1);return new Vn(i,o)}},{key:"angleBisector",value:function(t,e,n){var r=e.distance(t),i=r/(r+e.distance(n)),o=n.x-t.x,s=n.y-t.y;return new z(t.x+i*o,t.y+i*s)}},{key:"area3D",value:function(t,e,n){var r=e.x-t.x,i=e.y-t.y,o=e.getZ()-t.getZ(),s=n.x-t.x,a=n.y-t.y,u=n.getZ()-t.getZ(),l=i*u-o*a,h=o*s-r*u,c=r*a-i*s,f=l*l+h*h+c*c;return Math.sqrt(f)/2}},{key:"centroid",value:function(t,e,n){var r=(t.x+e.x+n.x)/3,i=(t.y+e.y+n.y)/3;return new z(r,i)}},{key:"inCentre",value:function(t,e,n){var r=e.distance(n),i=t.distance(n),o=t.distance(e),s=r+i+o,a=(r*t.x+i*e.x+o*n.x)/s,u=(r*t.y+i*e.y+o*n.y)/s;return new z(a,u)}}]),e}(),Bn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"addRingSide",value:function(t,e,n,r,i){if(0===e&&t.length=zt.MINIMUM_VALID_SIZE&&ft.isCCW(t)&&(o=i,s=r,n=tt.opposite(n));var a=this._curveBuilder.getRingCurve(t,n,e);this.addCurve(a,o,s)}},{key:"addRingBothSides",value:function(t,e){this.addRingSide(t,e,tt.LEFT,Z.EXTERIOR,Z.INTERIOR),this.addRingSide(t,e,tt.RIGHT,Z.INTERIOR,Z.EXTERIOR)}},{key:"addPoint",value:function(t){if(this._distance<=0)return null;var e=t.getCoordinates(),n=this._curveBuilder.getLineCurve(e,this._distance);this.addCurve(n,Z.EXTERIOR,Z.INTERIOR)}},{key:"addPolygon",value:function(t){var e=this._distance,n=tt.LEFT;this._distance<0&&(e=-this._distance,n=tt.RIGHT);var r=t.getExteriorRing(),i=Wt.removeRepeatedPoints(r.getCoordinates());if(this._distance<0&&this.isErodedCompletely(r,this._distance))return null;if(this._distance<=0&&i.length<3)return null;this.addRingSide(i,e,n,Z.EXTERIOR,Z.INTERIOR);for(var o=0;o0&&this.isErodedCompletely(s,-this._distance)||this.addRingSide(a,e,tt.opposite(n),Z.INTERIOR,Z.EXTERIOR)}}},{key:"isTriangleErodedCompletely",value:function(t,e){var n=new Gn(t[0],t[1],t[2]),r=n.inCentre();return kt.pointToSegment(r,n.p0,n.p1)i}},{key:"addCollection",value:function(t){for(var e=0;e=this._max)throw new W;var t=this._parent.getGeometryN(this._index++);return t instanceof Bt?(this._subcollectionIterator=new e(t),this._subcollectionIterator.next()):t}},{key:"remove",value:function(){throw new J(this.getClass().getName())}},{key:"hasNext",value:function(){if(this._atStart)return!0;if(null!==this._subcollectionIterator){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)}},{key:"interfaces_",get:function(){return[yn]}}],[{key:"constructor_",value:function(){this._parent=null,this._atStart=null,this._max=null,this._index=null,this._subcollectionIterator=null;var t=arguments[0];this._parent=t,this._atStart=!0,this._index=0,this._max=t.getNumGeometries()}},{key:"isAtomic",value:function(t){return!(t instanceof Bt)}}]),e}(),jn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"locate",value:function(t){return e.locate(t,this._geom)}},{key:"interfaces_",get:function(){return[Yn]}}],[{key:"constructor_",value:function(){this._geom=null;var t=arguments[0];this._geom=t}},{key:"locatePointInPolygon",value:function(t,n){if(n.isEmpty())return Z.EXTERIOR;var r=n.getExteriorRing(),i=e.locatePointInRing(t,r);if(i!==Z.INTERIOR)return i;for(var o=0;o=0;n--){var r=this._edgeList.get(n),i=r.getSym();null===e&&(e=i),null!==t&&i.setNext(t),t=r}e.setNext(t)}},{key:"computeDepths",value:function(){if(1===arguments.length){var t=arguments[0],e=this.findIndex(t),n=t.getDepth(tt.LEFT),r=t.getDepth(tt.RIGHT),i=this.computeDepths(e+1,this._edgeList.size(),n);if(this.computeDepths(0,e,i)!==r)throw new pt("depth mismatch at "+t.getCoordinate())}else if(3===arguments.length){for(var o=arguments[1],s=arguments[2],a=arguments[0];a=0;i--){var o=this._resultAreaEdgeList.get(i),s=o.getSym();switch(null===e&&o.getEdgeRing()===t&&(e=o),r){case this._SCANNING_FOR_INCOMING:if(s.getEdgeRing()!==t)continue;n=s,r=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(o.getEdgeRing()!==t)continue;n.setNextMin(o),r=this._SCANNING_FOR_INCOMING}}r===this._LINKING_TO_OUTGOING&&(V.isTrue(null!==e,"found null for first outgoing dirEdge"),V.isTrue(e.getEdgeRing()===t,"unable to link last incoming dirEdge"),n.setNextMin(e))}},{key:"getOutgoingDegree",value:function(){if(0===arguments.length){for(var t=0,e=this.iterator();e.hasNext();)e.next().isInResult()&&t++;return t}if(1===arguments.length){for(var n=arguments[0],r=0,i=this.iterator();i.hasNext();)i.next().getEdgeRing()===n&&r++;return r}}},{key:"getLabel",value:function(){return this._label}},{key:"findCoveredLineEdges",value:function(){for(var t=Z.NONE,e=this.iterator();e.hasNext();){var n=e.next(),r=n.getSym();if(!n.isLineEdge()){if(n.isInResult()){t=Z.INTERIOR;break}if(r.isInResult()){t=Z.EXTERIOR;break}}}if(t===Z.NONE)return null;for(var i=t,o=this.iterator();o.hasNext();){var s=o.next(),a=s.getSym();s.isLineEdge()?s.getEdge().setCovered(i===Z.INTERIOR):(s.isInResult()&&(i=Z.EXTERIOR),a.isInResult()&&(i=Z.INTERIOR))}}},{key:"computeLabelling",value:function(t){f(i(s.prototype),"computeLabelling",this).call(this,t),this._label=new Ae(Z.NONE);for(var e=this.iterator();e.hasNext();)for(var n=e.next().getEdge().getLabel(),r=0;r<2;r++){var o=n.getLocation(r);o!==Z.INTERIOR&&o!==Z.BOUNDARY||this._label.setLocation(r,Z.INTERIOR)}}}],[{key:"constructor_",value:function(){this._resultAreaEdgeList=null,this._label=null,this._SCANNING_FOR_INCOMING=1,this._LINKING_TO_OUTGOING=2}}]),s}(Xn),Zn=function(e){r(o,e);var i=c(o);function o(){return t(this,o),i.call(this)}return n(o,[{key:"createNode",value:function(t){return new Ge(t,new Un)}}]),o}(Qe),Hn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"compareTo",value:function(t){var n=t;return e.compareOriented(this._pts,this._orientation,n._pts,n._orientation)}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this._pts=null,this._orientation=null;var t=arguments[0];this._pts=t,this._orientation=e.orientation(t)}},{key:"orientation",value:function(t){return 1===Wt.increasingDirection(t)}},{key:"compareOriented",value:function(t,e,n,r){for(var i=e?1:-1,o=r?1:-1,s=e?t.length:-1,a=r?n.length:-1,u=e?0:t.length-1,l=r?0:n.length-1;;){var h=t[u].compareTo(n[l]);if(0!==h)return h;var c=(u+=i)===s,f=(l+=o)===a;if(c&&!f)return-1;if(!c&&f)return 1;if(c&&f)return 0}}}]),e}(),Wn=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.print("MULTILINESTRING ( ");for(var e=0;e0&&t.print(","),t.print("(");for(var r=n.getCoordinates(),i=0;i0&&t.print(","),t.print(r[i].x+" "+r[i].y);t.println(")")}t.print(") ")}},{key:"addAll",value:function(t){for(var e=t.iterator();e.hasNext();)this.add(e.next())}},{key:"findEdgeIndex",value:function(t){for(var e=0;et?1:this.diste?1:0}},{key:"interfaces_",get:function(){return[k]}}],[{key:"constructor_",value:function(){this.coord=null,this.segmentIndex=null,this.dist=null;var t=arguments[0],e=arguments[1],n=arguments[2];this.coord=new z(t),this.segmentIndex=e,this.dist=n}}]),e}(),$n=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"print",value:function(t){t.println("Intersections:");for(var e=this.iterator();e.hasNext();)e.next().print(t)}},{key:"iterator",value:function(){return this._nodeMap.values().iterator()}},{key:"addSplitEdges",value:function(t){this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var r=e.next(),i=this.createSplitEdge(n,r);t.add(i),n=r}}},{key:"addEndpoints",value:function(){var t=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[t],t,0)}},{key:"createSplitEdge",value:function(t,e){var n=e.segmentIndex-t.segmentIndex+2,r=this.edge.pts[e.segmentIndex],i=e.dist>0||!e.coord.equals2D(r);i||n--;var o=new Array(n).fill(null),s=0;o[s++]=new z(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this.edge.pts[a];return i&&(o[s]=e.coord),new or(o,new Ae(this.edge._label))}},{key:"add",value:function(t,e,n){var r=new Qn(t,e,n),i=this._nodeMap.get(r);return null!==i?i:(this._nodeMap.put(r,r),r)}},{key:"isIntersection",value:function(t){for(var e=this.iterator();e.hasNext();)if(e.next().coord.equals(t))return!0;return!1}}],[{key:"constructor_",value:function(){this._nodeMap=new Ze,this.edge=null;var t=arguments[0];this.edge=t}}]),e}(),tr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"isIntersects",value:function(){return!this.isDisjoint()}},{key:"isCovers",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"isCoveredBy",value:function(){return(e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])||e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"set",value:function(){if(1===arguments.length)for(var t=arguments[0],e=0;e=0&&e>=0&&this.setAtLeast(t,e,n)}},{key:"isWithin",value:function(){return e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE}},{key:"isTouches",value:function(t,n){return t>n?this.isTouches(n,t):(t===Mt.A&&n===Mt.A||t===Mt.L&&n===Mt.L||t===Mt.L&&n===Mt.A||t===Mt.P&&n===Mt.A||t===Mt.P&&n===Mt.L)&&this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&(e.isTrue(this._matrix[Z.INTERIOR][Z.BOUNDARY])||e.isTrue(this._matrix[Z.BOUNDARY][Z.INTERIOR])||e.isTrue(this._matrix[Z.BOUNDARY][Z.BOUNDARY]))}},{key:"isOverlaps",value:function(t,n){return t===Mt.P&&n===Mt.P||t===Mt.A&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&1===this._matrix[Z.INTERIOR][Z.INTERIOR]&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR])}},{key:"isEquals",value:function(t,n){return t===n&&e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&this._matrix[Z.INTERIOR][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.EXTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.EXTERIOR][Z.BOUNDARY]===Mt.FALSE}},{key:"toString",value:function(){for(var t=new Qt("123456789"),e=0;e<3;e++)for(var n=0;n<3;n++)t.setCharAt(3*e+n,Mt.toDimensionSymbol(this._matrix[e][n]));return t.toString()}},{key:"setAll",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this._matrix[e][n]=t}},{key:"get",value:function(t,e){return this._matrix[t][e]}},{key:"transpose",value:function(){var t=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=t,t=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=t,t=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=t,this}},{key:"matches",value:function(t){if(9!==t.length)throw new x("Should be length 9: "+t);for(var n=0;n<3;n++)for(var r=0;r<3;r++)if(!e.matches(this._matrix[n][r],t.charAt(3*n+r)))return!1;return!0}},{key:"add",value:function(t){for(var e=0;e<3;e++)for(var n=0;n<3;n++)this.setAtLeast(e,n,t.get(e,n))}},{key:"isDisjoint",value:function(){return this._matrix[Z.INTERIOR][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.INTERIOR][Z.BOUNDARY]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.INTERIOR]===Mt.FALSE&&this._matrix[Z.BOUNDARY][Z.BOUNDARY]===Mt.FALSE}},{key:"isCrosses",value:function(t,n){return t===Mt.P&&n===Mt.L||t===Mt.P&&n===Mt.A||t===Mt.L&&n===Mt.A?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.INTERIOR][Z.EXTERIOR]):t===Mt.L&&n===Mt.P||t===Mt.A&&n===Mt.P||t===Mt.A&&n===Mt.L?e.isTrue(this._matrix[Z.INTERIOR][Z.INTERIOR])&&e.isTrue(this._matrix[Z.EXTERIOR][Z.INTERIOR]):t===Mt.L&&n===Mt.L&&0===this._matrix[Z.INTERIOR][Z.INTERIOR]}},{key:"interfaces_",get:function(){return[b]}}],[{key:"constructor_",value:function(){if(this._matrix=null,0===arguments.length)this._matrix=Array(3).fill().map((function(){return Array(3)})),this.setAll(Mt.FALSE);else if(1===arguments.length)if("string"==typeof arguments[0]){var t=arguments[0];e.constructor_.call(this),this.set(t)}else if(arguments[0]instanceof e){var n=arguments[0];e.constructor_.call(this),this._matrix[Z.INTERIOR][Z.INTERIOR]=n._matrix[Z.INTERIOR][Z.INTERIOR],this._matrix[Z.INTERIOR][Z.BOUNDARY]=n._matrix[Z.INTERIOR][Z.BOUNDARY],this._matrix[Z.INTERIOR][Z.EXTERIOR]=n._matrix[Z.INTERIOR][Z.EXTERIOR],this._matrix[Z.BOUNDARY][Z.INTERIOR]=n._matrix[Z.BOUNDARY][Z.INTERIOR],this._matrix[Z.BOUNDARY][Z.BOUNDARY]=n._matrix[Z.BOUNDARY][Z.BOUNDARY],this._matrix[Z.BOUNDARY][Z.EXTERIOR]=n._matrix[Z.BOUNDARY][Z.EXTERIOR],this._matrix[Z.EXTERIOR][Z.INTERIOR]=n._matrix[Z.EXTERIOR][Z.INTERIOR],this._matrix[Z.EXTERIOR][Z.BOUNDARY]=n._matrix[Z.EXTERIOR][Z.BOUNDARY],this._matrix[Z.EXTERIOR][Z.EXTERIOR]=n._matrix[Z.EXTERIOR][Z.EXTERIOR]}}},{key:"matches",value:function(){if(Number.isInteger(arguments[0])&&"string"==typeof arguments[1]){var t=arguments[0],n=arguments[1];return n===Mt.SYM_DONTCARE||n===Mt.SYM_TRUE&&(t>=0||t===Mt.TRUE)||n===Mt.SYM_FALSE&&t===Mt.FALSE||n===Mt.SYM_P&&t===Mt.P||n===Mt.SYM_L&&t===Mt.L||n===Mt.SYM_A&&t===Mt.A}if("string"==typeof arguments[0]&&"string"==typeof arguments[1]){var r=arguments[1];return new e(arguments[0]).matches(r)}}},{key:"isTrue",value:function(t){return t>=0||t===Mt.TRUE}}]),e}(),er=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"size",value:function(){return this._size}},{key:"addAll",value:function(t){return null===t||0===t.length?null:(this.ensureCapacity(this._size+t.length),xt.arraycopy(t,0,this._data,this._size,t.length),void(this._size+=t.length))}},{key:"ensureCapacity",value:function(t){if(t<=this._data.length)return null;var e=Math.max(t,2*this._data.length);this._data=At.copyOf(this._data,e)}},{key:"toArray",value:function(){var t=new Array(this._size).fill(null);return xt.arraycopy(this._data,0,t,0,this._size),t}},{key:"add",value:function(t){this.ensureCapacity(this._size+1),this._data[this._size]=t,++this._size}}],[{key:"constructor_",value:function(){if(this._data=null,this._size=0,0===arguments.length)e.constructor_.call(this,10);else if(1===arguments.length){var t=arguments[0];this._data=new Array(t).fill(null)}}}]),e}(),nr=function(){function e(){t(this,e)}return n(e,[{key:"getChainStartIndices",value:function(t){var e=0,n=new er(Math.trunc(t.length/2));n.add(e);do{var r=this.findChainEnd(t,e);n.add(r),e=r}while(en?e:n}},{key:"getMinX",value:function(t){var e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return ee&&(r=1),this._depth[t][n]=r}}}},{key:"getDelta",value:function(t){return this._depth[t][tt.RIGHT]-this._depth[t][tt.LEFT]}},{key:"getLocation",value:function(t,e){return this._depth[t][e]<=0?Z.EXTERIOR:Z.INTERIOR}},{key:"toString",value:function(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}},{key:"add",value:function(){if(1===arguments.length)for(var t=arguments[0],n=0;n<2;n++)for(var r=1;r<3;r++){var i=t.getLocation(n,r);i!==Z.EXTERIOR&&i!==Z.INTERIOR||(this.isNull(n,r)?this._depth[n][r]=e.depthAtLocation(i):this._depth[n][r]+=e.depthAtLocation(i))}else if(3===arguments.length){var o=arguments[0],s=arguments[1];arguments[2]===Z.INTERIOR&&this._depth[o][s]++}}}],[{key:"constructor_",value:function(){this._depth=Array(2).fill().map((function(){return Array(3)}));for(var t=0;t<2;t++)for(var n=0;n<3;n++)this._depth[t][n]=e.NULL_VALUE}},{key:"depthAtLocation",value:function(t){return t===Z.EXTERIOR?0:t===Z.INTERIOR?1:e.NULL_VALUE}}]),e}();ir.NULL_VALUE=-1;var or=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"getDepth",value:function(){return this._depth}},{key:"getCollapsedEdge",value:function(){var t=new Array(2).fill(null);return t[0]=this.pts[0],t[1]=this.pts[1],new s(t,Ae.toLineLabel(this._label))}},{key:"isIsolated",value:function(){return this._isIsolated}},{key:"getCoordinates",value:function(){return this.pts}},{key:"setIsolated",value:function(t){this._isIsolated=t}},{key:"setName",value:function(t){this._name=t}},{key:"equals",value:function(t){if(!(t instanceof s))return!1;var e=t;if(this.pts.length!==e.pts.length)return!1;for(var n=!0,r=!0,i=this.pts.length,o=0;o0?this.pts[0]:null;if(1===arguments.length){var t=arguments[0];return this.pts[t]}}},{key:"print",value:function(t){t.print("edge "+this._name+": "),t.print("LINESTRING (");for(var e=0;e0&&t.print(","),t.print(this.pts[e].x+" "+this.pts[e].y);t.print(") "+this._label+" "+this._depthDelta)}},{key:"computeIM",value:function(t){s.updateIM(this._label,t)}},{key:"isCollapsed",value:function(){return!!this._label.isArea()&&3===this.pts.length&&!!this.pts[0].equals(this.pts[2])}},{key:"isClosed",value:function(){return this.pts[0].equals(this.pts[this.pts.length-1])}},{key:"getMaximumSegmentIndex",value:function(){return this.pts.length-1}},{key:"getDepthDelta",value:function(){return this._depthDelta}},{key:"getNumPoints",value:function(){return this.pts.length}},{key:"printReverse",value:function(t){t.print("edge "+this._name+": ");for(var e=this.pts.length-1;e>=0;e--)t.print(this.pts[e]+" ");t.println("")}},{key:"getMonotoneChainEdge",value:function(){return null===this._mce&&(this._mce=new rr(this)),this._mce}},{key:"getEnvelope",value:function(){if(null===this._env){this._env=new X;for(var t=0;t0&&t.append(","),t.append(this.pts[e].x+" "+this.pts[e].y);return t.append(") "+this._label+" "+this._depthDelta),t.toString()}},{key:"isPointwiseEqual",value:function(t){if(this.pts.length!==t.pts.length)return!1;for(var e=0;er||this._maxyo;if(s)return!1;var a=this.intersectsToleranceSquare(t,e);return V.isTrue(!(s&&a),"Found bad envelope test"),a}},{key:"initCorners",value:function(t){var e=.5;this._minx=t.x-e,this._maxx=t.x+e,this._miny=t.y-e,this._maxy=t.y+e,this._corner[0]=new z(this._maxx,this._maxy),this._corner[1]=new z(this._minx,this._maxy),this._corner[2]=new z(this._minx,this._miny),this._corner[3]=new z(this._maxx,this._miny)}},{key:"intersects",value:function(t,e){return 1===this._scaleFactor?this.intersectsScaled(t,e):(this.copyScaled(t,this._p0Scaled),this.copyScaled(e,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}},{key:"scale",value:function(t){return Math.round(t*this._scaleFactor)}},{key:"getCoordinate",value:function(){return this._originalPt}},{key:"copyScaled",value:function(t,e){e.x=this.scale(t.x),e.y=this.scale(t.y)}},{key:"getSafeEnvelope",value:function(){if(null===this._safeEnv){var t=e.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new X(this._originalPt.x-t,this._originalPt.x+t,this._originalPt.y-t,this._originalPt.y+t)}return this._safeEnv}},{key:"intersectsPixelClosure",value:function(t,e){return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.hasIntersection()))))}},{key:"intersectsToleranceSquare",value:function(t,e){var n=!1,r=!1;return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.isProper()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.isProper()||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.isProper()||(this._li.hasIntersection()&&(r=!0),this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.isProper()||n&&r||t.equals(this._pt)||e.equals(this._pt)))))}},{key:"addSnappedNode",value:function(t,e){var n=t.getCoordinate(e),r=t.getCoordinate(e+1);return!!this.intersects(n,r)&&(t.addIntersection(this.getCoordinate(),e),!0)}}],[{key:"constructor_",value:function(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;var t=arguments[0],e=arguments[1],n=arguments[2];if(this._originalPt=t,this._pt=t,this._scaleFactor=e,this._li=n,e<=0)throw new x("Scale factor must be non-zero");1!==e&&(this._pt=new z(this.scale(t.x),this.scale(t.y)),this._p0Scaled=new z,this._p1Scaled=new z),this.initCorners(this._pt)}}]),e}();lr.SAFE_ENV_EXPANSION_FACTOR=.75;var hr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"select",value:function(){if(1===arguments.length);else if(2===arguments.length){var t=arguments[1];arguments[0].getLineSegment(t,this.selectedSegment),this.select(this.selectedSegment)}}}],[{key:"constructor_",value:function(){this.selectedSegment=new bn}}]),e}(),cr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"snap",value:function(){if(1===arguments.length){var e=arguments[0];return this.snap(e,null,-1)}if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],s=r.getSafeEnvelope(),a=new fr(r,i,o);return this._index.query(s,new(function(){function e(){t(this,e)}return n(e,[{key:"interfaces_",get:function(){return[hn]}},{key:"visitItem",value:function(t){t.select(s,a)}}]),e}())),a.isNodeAdded()}}}],[{key:"constructor_",value:function(){this._index=null;var t=arguments[0];this._index=t}}]),e}(),fr=function(e){r(s,e);var o=c(s);function s(){var e;return t(this,s),e=o.call(this),s.constructor_.apply(l(e),arguments),e}return n(s,[{key:"isNodeAdded",value:function(){return this._isNodeAdded}},{key:"select",value:function(){if(!(2===arguments.length&&Number.isInteger(arguments[1])&&arguments[0]instanceof In))return f(i(s.prototype),"select",this).apply(this,arguments);var t=arguments[1],e=arguments[0].getContext();if(this._parentEdge===e&&(t===this._hotPixelVertexIndex||t+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(e,t)}}],[{key:"constructor_",value:function(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var t=arguments[0],e=arguments[1],n=arguments[2];this._hotPixel=t,this._parentEdge=e,this._hotPixelVertexIndex=n}}]),s}(hr);cr.HotPixelSnapAction=fr;var gr=function(){function e(){t(this,e),e.constructor_.apply(this,arguments)}return n(e,[{key:"processIntersections",value:function(t,e,n,r){if(t===n&&e===r)return null;var i=t.getCoordinates()[e],o=t.getCoordinates()[e+1],s=n.getCoordinates()[r],a=n.getCoordinates()[r+1];if(this._li.computeIntersection(i,o,s,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var u=0;u=0;t--){try{this.bufferReducedPrecision(t)}catch(t){if(!(t instanceof pt))throw t;this._saveException=t}if(null!==this._resultGeometry)return null}throw this._saveException}if(1===arguments.length){var n=arguments[0],r=e.precisionScaleFactor(this._argGeom,this._distance,n),i=new ie(r);this.bufferFixedPrecision(i)}}},{key:"computeGeometry",value:function(){if(this.bufferOriginalPrecision(),null!==this._resultGeometry)return null;var t=this._argGeom.getFactory().getPrecisionModel();t.getType()===ie.FIXED?this.bufferFixedPrecision(t):this.bufferReducedPrecision()}},{key:"setQuadrantSegments",value:function(t){this._bufParams.setQuadrantSegments(t)}},{key:"bufferOriginalPrecision",value:function(){try{var t=new sr(this._bufParams);this._resultGeometry=t.buffer(this._argGeom,this._distance)}catch(t){if(!(t instanceof F))throw t;this._saveException=t}}},{key:"getResultGeometry",value:function(t){return this._distance=t,this.computeGeometry(),this._resultGeometry}},{key:"setEndCapStyle",value:function(t){this._bufParams.setEndCapStyle(t)}}],[{key:"constructor_",value:function(){if(this._argGeom=null,this._distance=null,this._bufParams=new y,this._resultGeometry=null,this._saveException=null,1===arguments.length){var t=arguments[0];this._argGeom=t}else if(2===arguments.length){var e=arguments[0],n=arguments[1];this._argGeom=e,this._bufParams=n}}},{key:"bufferOp",value:function(){if(2===arguments.length){var t=arguments[1];return new e(arguments[0]).getResultGeometry(t)}if(3===arguments.length){if(Number.isInteger(arguments[2])&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var n=arguments[1],r=arguments[2],i=new e(arguments[0]);return i.setQuadrantSegments(r),i.getResultGeometry(n)}if(arguments[2]instanceof y&&arguments[0]instanceof U&&"number"==typeof arguments[1]){var o=arguments[1];return new e(arguments[0],arguments[2]).getResultGeometry(o)}}else if(4===arguments.length){var s=arguments[1],a=arguments[2],u=arguments[3],l=new e(arguments[0]);return l.setQuadrantSegments(a),l.setEndCapStyle(u),l.getResultGeometry(s)}}},{key:"precisionScaleFactor",value:function(t,e,n){var r=t.getEnvelopeInternal(),i=Et.max(Math.abs(r.getMaxX()),Math.abs(r.getMaxY()),Math.abs(r.getMinX()),Math.abs(r.getMinY()))+2*(e>0?e:0),o=n-Math.trunc(Math.log(i)/Math.log(10)+1);return Math.pow(10,o)}}]),e}();vr.CAP_ROUND=y.CAP_ROUND,vr.CAP_BUTT=y.CAP_FLAT,vr.CAP_FLAT=y.CAP_FLAT,vr.CAP_SQUARE=y.CAP_SQUARE,vr.MAX_PRECISION_DIGITS=12;var dr=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"],yr=function(){function e(n){t(this,e),this.geometryFactory=n||new ae}return n(e,[{key:"read",value:function(t){var e,n=(e="string"==typeof t?JSON.parse(t):t).type;if(!mr[n])throw new Error("Unknown GeoJSON type: "+e.type);return-1!==dr.indexOf(n)?mr[n].call(this,e.coordinates):"GeometryCollection"===n?mr[n].call(this,e.geometries):mr[n].call(this,e)}},{key:"write",value:function(t){var e=t.getGeometryType();if(!_r[e])throw new Error("Geometry is not supported");return _r[e].call(this,t)}}]),e}(),mr={Feature:function(t){var e={};for(var n in t)e[n]=t[n];if(t.geometry){var r=t.geometry.type;if(!mr[r])throw new Error("Unknown GeoJSON type: "+t.type);e.geometry=this.read(t.geometry)}return t.bbox&&(e.bbox=mr.bbox.call(this,t.bbox)),e},FeatureCollection:function(t){var e={};if(t.features){e.features=[];for(var n=0;n1?0:t<-1?Xn:Math.acos(t)}function ir(t){return t>1?Un:t<-1?-Un:Math.asin(t)}function or(){}function sr(t,e){t&&ur.hasOwnProperty(t.type)&&ur[t.type](t,e)}var ar={Feature:function(t,e){sr(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++rXn?t-Hn:t<-Xn?t+Hn:t,e]}function xr(t){return function(e,n){return[(e+=t)>Xn?e-Hn:e<-Xn?e+Hn:e,n]}}function Er(t){var e=xr(t);return e.invert=xr(-t),e}function kr(t,e){var n=tr(t),r=er(t),i=tr(e),o=er(e);function s(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*n+a*r;return[$n(u*i-h*o,a*n-l*r),ir(h*i+u*o)]}return s.invert=function(t,e){var s=tr(e),a=tr(t)*s,u=er(t)*s,l=er(e),h=l*i-u*o;return[$n(u*i+l*o,a*n+h*r),ir(h*n-a*r)]},s}function br(t,e){(e=fr(e))[0]-=t,yr(e);var n=rr(-e[1]);return((-e[2]<0?-n:n)+Hn-jn)%Hn}function wr(){var t,e=[];return{point:function(e,n){t.push([e,n])},lineStart:function(){e.push(t=[])},lineEnd:or,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function Ir(t,e){return Kn(t[0]-e[0])=0;--o)i.point((h=l[o])[0],h[1]);else r(f.x,f.p.x,-1,i);f=f.p}l=(f=f.o).z,g=!g}while(!f.v);i.lineEnd()}}}function Mr(t){if(e=t.length){for(var e,n,r=0,i=t[0];++re?1:t>=e?0:NaN}function Pr(t){for(var e,n,r,i=t.length,o=-1,s=0;++o=0;)for(e=(r=t[i]).length;--e>=0;)n[--s]=r[e];return n}Gn(),Gn(),Gn(),_r.invert=_r,function(t){var e;1===t.length&&(e=t,t=function(t,n){return Lr(e(t),n)})}(Lr);var Cr=1e9,Tr=-Cr;function Or(t,e,n,r){function i(i,o){return t<=i&&i<=n&&e<=o&&o<=r}function o(i,o,a,l){var h=0,c=0;if(null==i||(h=s(i,a))!==(c=s(o,a))||u(i,o)<0^a>0)do{l.point(0===h||3===h?t:n,h>1?r:e)}while((h=(h+a+4)%4)!==c);else l.point(o[0],o[1])}function s(r,i){return Kn(r[0]-t)0?0:3:Kn(r[0]-n)0?2:1:Kn(r[1]-e)0?1:0:i>0?3:2}function a(t,e){return u(t.x,e.x)}function u(t,e){var n=s(t,1),r=s(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){var u,l,h,c,f,g,p,v,d,y,m,_=s,x=wr(),E={point:k,lineStart:function(){E.point=b,l&&l.push(h=[]);y=!0,d=!1,p=v=NaN},lineEnd:function(){u&&(b(c,f),g&&d&&x.rejoin(),u.push(x.result()));E.point=k,d&&_.lineEnd()},polygonStart:function(){_=x,u=[],l=[],m=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,i=l.length;nr&&(f-o)*(r-s)>(g-s)*(t-o)&&++e:g<=r&&(f-o)*(r-s)<(g-s)*(t-o)&&--e;return e}(),n=m&&e,i=(u=Pr(u)).length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),o(null,null,1,s),s.lineEnd()),i&&Sr(u,a,e,o,s),s.polygonEnd());_=s,u=l=h=null}};function k(t,e){i(t,e)&&_.point(t,e)}function b(o,s){var a=i(o,s);if(l&&h.push([o,s]),y)c=o,f=s,g=a,y=!1,a&&(_.lineStart(),_.point(o,s));else if(a&&d)_.point(o,s);else{var u=[p=Math.max(Tr,Math.min(Cr,p)),v=Math.max(Tr,Math.min(Cr,v))],x=[o=Math.max(Tr,Math.min(Cr,o)),s=Math.max(Tr,Math.min(Cr,s))];!function(t,e,n,r,i,o){var s,a=t[0],u=t[1],l=0,h=1,c=e[0]-a,f=e[1]-u;if(s=n-a,c||!(s>0)){if(s/=c,c<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=i-a,c||!(s<0)){if(s/=c,c<0){if(s>h)return;s>l&&(l=s)}else if(c>0){if(s0)){if(s/=f,f<0){if(s0){if(s>h)return;s>l&&(l=s)}if(s=o-u,f||!(s<0)){if(s/=f,f<0){if(s>h)return;s>l&&(l=s)}else if(f>0){if(s0&&(t[0]=a+l*c,t[1]=u+l*f),h<1&&(e[0]=a+h*c,e[1]=u+h*f),!0}}}}}(u,x,t,e,n,r)?a&&(_.lineStart(),_.point(o,s),m=!1):(d||(_.lineStart(),_.point(u[0],u[1])),_.point(x[0],x[1]),a||_.lineEnd(),m=!1)}p=o,v=s,d=a}return E}}var Rr=Gn();function Ar(t){return t}Gn(),Gn(),Gn();var Dr=1/0,Fr=Dr,qr=-Dr,Vr=qr,Gr={point:function(t,e){tqr&&(qr=t);eVr&&(Vr=e)},lineStart:or,lineEnd:or,polygonStart:or,polygonEnd:or,result:function(){var t=[[Dr,Fr],[qr,Vr]];return qr=Vr=-(Fr=Dr=1/0),t}};function Br(t,e,n,r){return function(i,o){var s,a,u,l=e(o),h=i.invert(r[0],r[1]),c=wr(),f=e(c),g=!1,p={point:v,lineStart:y,lineEnd:m,polygonStart:function(){p.point=_,p.lineStart=x,p.lineEnd=E,a=[],s=[]},polygonEnd:function(){p.point=v,p.lineStart=y,p.lineEnd=m,a=Pr(a);var t=function(t,e){var n=e[0],r=e[1],i=[er(n),-tr(n),0],o=0,s=0;Rr.reset();for(var a=0,u=t.length;a=0?1:-1,w=b*k,I=w>Xn,N=p*x;if(Rr.add($n(N*b*er(w),v*E+N*tr(w))),o+=I?k+b*Hn:k,I^f>=n^m>=n){var S=pr(fr(c),fr(y));yr(S);var M=pr(i,S);yr(M);var L=(I^k>=0?-1:1)*ir(M[2]);(r>L||r===L&&(S[0]||S[1]))&&(s+=I^k>=0?1:-1)}}return(o<-jn||o0){for(g||(o.polygonStart(),g=!0),o.lineStart(),t=0;t1&&2&i&&l.push(l.pop().concat(l.shift())),a.push(l.filter(Yr))}return p}}function Yr(t){return t.length>1}function zr(t,e){return((t=t.x)[0]<0?t[1]-Un-jn:Un-t[1])-((e=e.x)[0]<0?e[1]-Un-jn:Un-e[1])}Gn();var jr=Br((function(){return!0}),(function(t){var e,n=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,s){var a=o>0?Xn:-Xn,u=Kn(o-n);Kn(u-Xn)0?Un:-Un),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),e=0):i!==a&&u>=Xn&&(Kn(n-i)jn?Qn((er(e)*(o=tr(r))*er(n)-er(r)*(i=tr(e))*er(t))/(i*o*s)):(e+r)/2}(n,r,o,s),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),e=0),t.point(n=o,r=s),i=a},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var i;if(null==t)i=n*Un,r.point(-Xn,i),r.point(0,i),r.point(Xn,i),r.point(Xn,0),r.point(Xn,-i),r.point(0,-i),r.point(-Xn,-i),r.point(-Xn,0),r.point(-Xn,i);else if(Kn(t[0]-e[0])>jn){var o=t[0]0,i=Kn(n)>jn;function o(t,e){return tr(t)*tr(e)>n}function s(t,e,r){var i=[1,0,0],o=pr(fr(t),fr(e)),s=gr(o,o),a=o[0],u=s-a*a;if(!u)return!r&&t;var l=n*s/u,h=-n*a/u,c=pr(i,o),f=dr(i,l);vr(f,dr(o,h));var g=c,p=gr(f,g),v=gr(g,g),d=p*p-v*(gr(f,f)-1);if(!(d<0)){var y=nr(d),m=dr(g,(-p-y)/v);if(vr(m,f),m=cr(m),!r)return m;var _,x=t[0],E=e[0],k=t[1],b=e[1];E0^m[1]<(Kn(m[0]-x)Xn^(x<=m[0]&&m[0]<=E)){var N=dr(g,(-p+y)/v);return vr(N,f),[m,cr(N)]}}}function a(e,n){var i=r?t:Xn-t,o=0;return e<-i?o|=1:e>i&&(o|=2),n<-i?o|=4:n>i&&(o|=8),o}return Br(o,(function(t){var e,n,u,l,h;return{lineStart:function(){l=u=!1,h=1},point:function(c,f){var g,p=[c,f],v=o(c,f),d=r?v?0:a(c,f):v?a(c+(c<0?Xn:-Xn),f):0;if(!e&&(l=u=v)&&t.lineStart(),v!==u&&(!(g=s(e,p))||Ir(e,g)||Ir(p,g))&&(p[0]+=jn,p[1]+=jn,v=o(p[0],p[1])),v!==u)h=0,v?(t.lineStart(),g=s(p,e),t.point(g[0],g[1])):(g=s(e,p),t.point(g[0],g[1]),t.lineEnd()),e=g;else if(i&&e&&r^v){var y;d&n||!(y=s(p,e,!0))||(h=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1])))}!v||e&&Ir(e,p)||t.point(p[0],p[1]),e=p,u=v,n=d},lineEnd:function(){u&&t.lineEnd(),e=null},clean:function(){return h|(l&&u)<<1}}}),(function(n,r,i,o){!function(t,e,n,r,i,o){if(n){var s=tr(e),a=er(e),u=r*n;null==i?(i=e+r*Hn,o=e-u/2):(i=br(s,i),o=br(s,o),(r>0?io)&&(i+=r*Hn));for(var l,h=i;r>0?h>o:h4*e&&v--){var x=s+f,E=a+g,k=u+p,b=nr(x*x+E*E+k*k),w=ir(k/=b),I=Kn(Kn(k)-1)e||Kn((y*L+m*P)/_-.5)>.3||s*f+a*g+u*p2?t[2]%360*Jn:0,M()):[d*Wn,y*Wn,m*Wn]},I.precision=function(t){return arguments.length?(w=Kr(S,b=t*t),L()):nr(b)},I.fitExtent=function(t,e){return Hr(I,t,e)},I.fitSize=function(t,e){return function(t,e,n){return Hr(t,[[0,0],e],n)}(I,t,e)},function(){return e=t.apply(this,arguments),I.invert=e.invert&&N,M()}}((function(){return t}))()}function ti(t){return function(e,n){var r=tr(e),i=tr(n),o=t(r*i);return[o*i*er(e),o*er(n)]}}function ei(t){return function(e,n){var r=nr(e*e+n*n),i=t(r),o=er(i),s=tr(i);return[$n(e*o,r*s),ir(r&&n*o/r)]}}ti((function(t){return nr(2/(1+t))})).invert=ei((function(t){return 2*ir(t/2)}));var ni=ti((function(t){return(t=rr(t))&&t/er(t)}));function ri(){return $r(ni).scale(79.4188).clipAngle(179.999)}function ii(t,e){return[t,e]}ni.invert=ei((function(t){return t})),ii.invert=ii;var oi=Vn.BufferOp,si=Vn.GeoJSONReader,ai=Vn.GeoJSONWriter;function ui(t,e,n,r){var i=t.properties||{},o="Feature"===t.type?t.geometry:t;if("GeometryCollection"===o.type){var s=[];return mt(t,(function(t){var i=ui(t,e,n,r);i&&s.push(i)})),C(s)}var a=function(t){var e=An(t).geometry.coordinates,n=[-e[0],-e[1]];return ri().rotate(n).scale(x)}(o),u={type:o.type,coordinates:hi(o.coordinates,a)},l=(new si).read(u),h=F(q(e,n),"meters"),c=oi.bufferOp(l,h,r);if(!li((c=(new ai).write(c)).coordinates))return b({type:c.type,coordinates:ci(c.coordinates,a)},i)}function li(t){return Array.isArray(t[0])?li(t[0]):isNaN(t[0])}function hi(t,e){return"object"!==m(t[0])?e(t):t.map((function(t){return hi(t,e)}))}function ci(t,e){return"object"!==m(t[0])?e.invert(t):t.map((function(t){return ci(t,e)}))}function fi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return mt(t,(function(t,o,s){var a=e.weight?null==s?void 0:s[e.weight]:void 0;if(!U(a=null==a?1:a))throw new Error("weight value must be a number for feature index "+o);(a=Number(a))>0&&ct(t,(function(t){n+=t[0]*a,r+=t[1]*a,i+=a}))})),I([n/i,r/i],e.properties,e)}function gi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=0,i=0;return ct(t,(function(t){n+=t[0],r+=t[1],i++}),!0),I([n/i,r/i],e.properties)}function pi(t,e,n,r,i){var o=r.tolerance||.001,s=0,a=0,u=0,l=0;if(vt(n,(function(e){var n,r=null==(n=e.properties)?void 0:n.weight,i=null==r?1:r;if(!U(i=Number(i)))throw new Error("weight value must be a number");if(i>0){l+=1;var o=i*ut(e,t);0===o&&(o=1);var h=i/o;s+=e.geometry.coordinates[0]*h,a+=e.geometry.coordinates[1]*h,u+=h}})),l<1)throw new Error("no features to measure");var h=s/u,c=a/u;return 1===l||0===i||Math.abs(h-e[0])0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mi;if(i(this,t),this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r)}),[{key:"push",value:function(t){this.data.push(t),this.length++,this._up(this.length-1)}},{key:"pop",value:function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}}},{key:"peek",value:function(){return this.data[0]}},{key:"_up",value:function(t){for(var e=this.data,n=this.compare,r=e[t];t>0;){var i=t-1>>1,o=e[i];if(n(r,o)>=0)break;e[t]=o,t=i}e[t]=r}},{key:"_down",value:function(t){for(var e=this.data,n=this.compare,r=this.length>>1,i=e[t];t=0)break;e[t]=s,t=o}e[t]=i}}])}();function mi(t,e){return te?1:0}var _i,xi,Ei,ki,bi,wi=_n(Object.freeze({__proto__:null,default:yi})),Ii={exports:{}};function Ni(){if(bi)return Ii.exports;bi=1;var t=(xi||(xi=1,_i=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=(r-n)/2,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),_i),e=(ki||(ki=1,Ei=function(t,e,n,r){var i=t[0],o=t[1],s=!1;void 0===n&&(n=0),void 0===r&&(r=e.length);for(var a=r-n,u=0,l=a-1;uo!=g>o&&i<(f-h)*(o-c)/(g-c)+h&&(s=!s)}return s}),Ei);return Ii.exports=function(n,r,i,o){return r.length>0&&Array.isArray(r[0])?e(n,r,i,o):t(n,r,i,o)},Ii.exports.nested=e,Ii.exports.flat=t,Ii.exports}var Si,Mi,Li={exports:{}};Li.exports;function Pi(){return Si||(Si=1,function(t,e){!function(t){var e=134217729,n=33306690738754706e-32;function r(t,e,n,r,i){var o,s,a,u,l=e[0],h=r[0],c=0,f=0;h>l==h>-l?(o=l,l=e[++c]):(o=h,h=r[++f]);var g=0;if(cl==h>-l?(a=o-((s=l+o)-l),l=e[++c]):(a=o-((s=h+o)-h),h=r[++f]),o=s,0!==a&&(i[g++]=a);cl==h>-l?(a=o-((s=o+l)-(u=s-o))+(l-u),l=e[++c]):(a=o-((s=o+h)-(u=s-o))+(h-u),h=r[++f]),o=s,0!==a&&(i[g++]=a);for(;c0!=m>0)return _;var x=Math.abs(y+m);return Math.abs(_)>=o*x?_:-function(t,i,o,g,p,v,d){var y,m,_,x,E,k,b,w,I,N,S,M,L,P,C,T,O,R,A=t-p,D=o-p,F=i-v,q=g-v;E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=q-(I=(k=e*q)-(k-q)))-((P=A*q)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=D-(I=(k=e*D)-(k-D)))-((T=F*D)-b*I-w*I-b*N))),u[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),u[1]=L-(S+E)+(E-T),E=(R=M+S)-M,u[2]=M-(R-E)+(S-E),u[3]=R;var V=function(t,e){for(var n=e[0],r=1;r=G||-V>=G)return V;if(y=t-(A+(E=t-A))+(E-p),_=o-(D+(E=o-D))+(E-p),m=i-(F+(E=i-F))+(E-v),x=g-(q+(E=g-q))+(E-v),0===y&&0===m&&0===_&&0===x)return V;if(G=a*d+n*Math.abs(V),(V+=A*x+q*y-(F*_+D*m))>=G||-V>=G)return V;E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=q-(I=(k=e*q)-(k-q)))-((P=y*q)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=D-(I=(k=e*D)-(k-D)))-((T=m*D)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var B=r(4,u,4,f,l);E=(C=(w=A-(b=(k=e*A)-(k-A)))*(N=x-(I=(k=e*x)-(k-x)))-((P=A*x)-b*I-w*I-b*N))-(S=C-(O=(w=F-(b=(k=e*F)-(k-F)))*(N=_-(I=(k=e*_)-(k-_)))-((T=F*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var Y=r(B,l,4,f,h);E=(C=(w=y-(b=(k=e*y)-(k-y)))*(N=x-(I=(k=e*x)-(k-x)))-((P=y*x)-b*I-w*I-b*N))-(S=C-(O=(w=m-(b=(k=e*m)-(k-m)))*(N=_-(I=(k=e*_)-(k-_)))-((T=m*_)-b*I-w*I-b*N))),f[0]=C-(S+E)+(E-O),E=(L=P-((M=P+S)-(E=M-P))+(S-E))-(S=L-T),f[1]=L-(S+E)+(E-T),E=(R=M+S)-M,f[2]=M-(R-E)+(S-E),f[3]=R;var z=r(Y,h,4,f,c);return c[z-1]}(t,i,g,p,v,d,x)},t.orient2dfast=function(t,e,n,r,i,o){return(e-o)*(n-i)-(t-i)*(r-o)},Object.defineProperty(t,"__esModule",{value:!0})}(e)}(0,Li.exports)),Li.exports}var Ci=function(){if(Mi)return vi.exports;Mi=1;var t=di,e=wi,n=Ni(),r=Pi().orient2d;function i(e,r,i){r=Math.max(0,void 0===r?2:r),i=i||0;var s=function(t){for(var e=t[0],r=t[0],i=t[0],o=t[0],s=0;si[0]&&(i=a),a[1]o[1]&&(o=a)}var u=[e,r,i,o],l=u.slice();for(s=0;s=2&&h(e[e.length-2],e[e.length-1],t[n])<=0;)e.pop();e.push(t[n])}for(var r=[],i=t.length-1;i>=0;i--){for(;r.length>=2&&h(r[r.length-2],r[r.length-1],t[i])<=0;)r.pop();r.push(t[i])}return r.pop(),e.pop(),e.concat(r)}(l)}(e),a=new t(16);a.toBBox=function(t){return{minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]}},a.compareMinX=function(t,e){return t[0]-e[0]},a.compareMinY=function(t,e){return t[1]-e[1]},a.load(e);for(var u,l=[],p=0;pu||c.push({node:v,dist:d})}for(;c.length&&!c.peek().node.children;){var y=c.pop(),m=y.node,_=p(m,n,r),x=p(m,i,o);if(y.dist<_&&y.dist=e.minX&&t[0]<=e.maxX&&t[1]>=e.minY&&t[1]<=e.maxY}function l(t,e,n){for(var r,i,o,s,a=Math.min(t[0],e[0]),u=Math.min(t[1],e[1]),l=Math.max(t[0],e[0]),c=Math.max(t[1],e[1]),f=n.search({minX:a,minY:u,maxX:l,maxY:c}),g=0;g0!=h(r,i,s)>0&&h(o,s,r)>0!=h(o,s,i)>0)return!1;return!0}function h(t,e,n){return r(t[0],t[1],e[0],e[1],n[0],n[1])}function c(t){var e=t.p,n=t.next.p;return t.minX=Math.min(e[0],n[0]),t.minY=Math.min(e[1],n[1]),t.maxX=Math.max(e[0],n[0]),t.maxY=Math.max(e[1],n[1]),t}function f(t,e){var n={p:t,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return e?(n.next=e.next,n.prev=e,e.next.prev=n,e.next=n):(n.prev=n,n.next=n),n}function g(t,e){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function p(t,e,n){var r=e[0],i=e[1],o=n[0]-r,s=n[1]-i;if(0!==o||0!==s){var a=((t[0]-r)*o+(t[1]-i)*s)/(o*o+s*s);a>1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function v(t,e,n,r,i,o,s,a){var u,l,h,c,f=n-t,g=r-e,p=s-i,v=a-o,d=t-i,y=e-o,m=f*f+g*g,_=f*p+g*v,x=p*p+v*v,E=f*d+g*y,k=p*d+v*y,b=m*x-_*_,w=b,I=b;0===b?(l=0,w=1,c=k,I=x):(c=m*k-_*E,(l=_*k-x*E)<0?(l=0,c=k,I=x):l>w&&(l=w,c=k+_,I=x)),c<0?(c=0,-E<0?l=0:-E>m?l=w:(l=-E,w=m)):c>I&&(c=I,-E+_<0?l=0:-E+_>m?l=w:(l=-E+_,w=m));var N=(1-(h=0===c?0:c/I))*i+h*s-((1-(u=0===l?0:l/w))*t+u*n),S=(1-h)*o+h*a-((1-u)*e+u*r);return N*N+S*S}function d(t,e){return t[0]===e[0]?t[1]-e[1]:t[0]-e[0]}return e.default&&(e=e.default),vi.exports=i,vi.exports.default=i,vi.exports}(),Ti=mn(Ci);function Oi(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e.concavity=e.concavity||1/0;var n=[];if(ct(t,(function(t){n.push([t[0],t[1]])})),!n.length)return null;var r=Ti(n,e.concavity);return r.length>3?S([r]):null}function Ri(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.steps||64,i=n.properties?n.properties:!Array.isArray(t)&&"Feature"===t.type&&t.properties?t.properties:{},o=[],s=0;s0;r.length0;){var a=t[Math.floor(Math.random()*o)],u=s?a.join("_"):""+a;n[u]||(n[u]=!0,r.push(a))}if(r.length0,u=t[Math.floor(Math.random()*s)];for(a&&u.join("_"),o.push(u);o.length0,y=[];if(s)u="kmrand"==s?r(t,e):"kmpp"==s?i(t,e):s;else for(var m={};u.lengthc&&(c=t[a].y);var g,p=l-u,v=c-h,d=p>v?p:v,y=.5*(l+u),m=.5*(c+h),_=[new so({__sentinel:!0,x:y-20*d,y:m-d},{__sentinel:!0,x:y,y:m+20*d},{__sentinel:!0,x:y+20*d,y:m-d})],x=[],E=[];a=t.length;for(;a--;){for(E.length=0,g=_.length;g--;)(p=t[a].x-_[g].x)>0&&p*p>_[g].r?(x.push(_[g]),_.splice(g,1)):p*p+(v=t[a].y-_[g].y)*v>_[g].r||(E.push(_[g].a,_[g].b,_[g].b,_[g].c,_[g].c,_[g].a),_.splice(g,1));for(uo(E),g=E.length;g;)n=E[--g],e=E[--g],r=t[a],i=n.x-e.x,o=n.y-e.y,s=2*(i*(r.y-n.y)-o*(r.x-n.x)),Math.abs(s)>f&&_.push(new so(e,n,r))}Array.prototype.push.apply(x,_),a=x.length;for(;a--;)(x[a].a.__sentinel||x[a].b.__sentinel||x[a].c.__sentinel)&&x.splice(a,1);return x}(t.features.map((function(t){var r={x:t.geometry.coordinates[0],y:t.geometry.coordinates[1]};return e?r.z=t.properties[e]:3===t.geometry.coordinates.length&&(n=!0,r.z=t.geometry.coordinates[2]),r}))).map((function(t){var e=[t.a.x,t.a.y],r=[t.b.x,t.b.y],i=[t.c.x,t.c.y],o={};return n?(e.push(t.a.z),r.push(t.b.z),i.push(t.c.z)):o={a:t.a.z,b:t.b.z,c:t.c.z},S([[e,r,i,e]],o)})))}var so=s((function t(e,n,r){i(this,t),this.a=e,this.b=n,this.c=r;var o,s,a=n.x-e.x,u=n.y-e.y,l=r.x-e.x,h=r.y-e.y,c=a*(e.x+n.x)+u*(e.y+n.y),f=l*(e.x+r.x)+h*(e.y+r.y),g=2*(a*(r.y-n.y)-u*(r.x-n.x));this.x=(h*c-u*f)/g,this.y=(a*f-l*c)/g,o=this.x-e.x,s=this.y-e.y,this.r=o*o+s*s}));function ao(t,e){return e.x-t.x}function uo(t){var e,n,r,i,o,s=t.length;t:for(;s;)for(n=t[--s],e=t[--s],r=s;r;)if(o=t[--r],e===(i=t[--r])&&n===o||e===o&&n===i){t.splice(s,2),t.splice(r,2),s-=2;continue t}}function lo(t){return t}function ho(t,e){var n=function(t){if(null==t)return lo;var e,n,r=t.scale[0],i=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,a){a||(e=n=0);var u=2,l=t.length,h=new Array(l);for(h[0]=(e+=t[0])*r+o,h[1]=(n+=t[1])*i+s;u1)for(var o,a,u=1,l=s(i[0]);ul&&(a=i[0],i[0]=i[u],i[u]=a,l=o);return i})).filter((function(t){return t.length>0}))}}var po=Object.prototype.hasOwnProperty;function vo(t,e,n,r,i,o){3===arguments.length&&(r=o=Array,i=null);for(var s=new r(t=1<=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},maybeSet:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)throw new Error("full hashmap");h=s[l=l+1&u]}return s[l]=r,a[l]=o,o},get:function(r,o){for(var l=e(r)&u,h=s[l],c=0;h!=i;){if(n(h,r))return a[l];if(++c>=t)break;h=s[l=l+1&u]}return o},keys:function(){for(var t=[],e=0,n=s.length;e>7^xo[2]^xo[3])}function ko(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=function(){for(var t=vo(1.4*o.length,E,k,Int32Array,-1,Int32Array),e=new Int32Array(o.length),n=0,r=o.length;n=0){var o=c[n];i===e&&o===r||i===r&&o===e||(++g,f[n]=1)}else h[n]=e,c[n]=r}}function E(t){return Eo(o[t])}function k(t,e){return yo(o[t],o[e])}l=h=c=null;var b,w=function(t,e,n,r,i){3===arguments.length&&(r=Array,i=null);for(var o=new r(t=1<=t)throw new Error("full hashset");u=o[a=a+1&s]}return o[a]=r,!0},has:function(r){for(var a=e(r)&s,u=o[a],l=0;u!=i;){if(n(u,r))return!0;if(++l>=t)break;u=o[a=a+1&s]}return!1},values:function(){for(var t=[],e=0,n=o.length;e>1);er&&(r=o),si&&(i=s)}function u(t){t.forEach(a)}function l(t){t.forEach(u)}for(var h in t)o(t[h]);return r>=e&&i>=n?[e,n,r,i]:void 0}(t=Io(t)),r=function(t){var e,n,r,i,o=t.coordinates,s=t.lines,a=t.rings,u=s.length+a.length;for(delete t.lines,delete t.rings,r=0,i=s.length;r1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=[],i=It(t,(function(t,e){var n=function(t,e){var n,r=t.geometry.coordinates,i=e.geometry.coordinates,o=Oo(r[0]),s=Oo(r[r.length-1]),a=Oo(i[0]),u=Oo(i[i.length-1]);if(o===u)n=i.concat(r.slice(1));else if(a===s)n=r.concat(i.slice(1));else if(o===a)n=r.slice(1).reverse().concat(i);else{if(s!==u)return null;n=r.concat(i.reverse().slice(1))}return L(n)}(t,e);return n||(r.push(t),e)}));return i&&r.push(i),r.length?1===r.length?r[0]:T(r.map((function(t){return t.coordinates}))):null}function Oo(t){return t[0].toString()+","+t[1].toString()}function Ro(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.mutate;if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==n&&void 0!==n||(t=Ai(t));var r=function(t){var e={};xt(t,(function(t){e[t.geometry.type]=!0}));var n=Object.keys(e);if(1===n.length)return n[0];return null}(t);if(!r)throw new Error("geojson must be homogenous");var i=t;switch(r){case"LineString":return To(i,e);case"Polygon":return function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("FeatureCollection"!==it(t))throw new Error("geojson must be a FeatureCollection");if(!t.features.length)throw new Error("geojson is empty");!1!==e.mutate&&void 0!==e.mutate||(t=Ai(t));var n=[];xt(t,(function(t){n.push(t.geometry)}));var r=Lo({geoms:A(n).geometry});return fo(r,r.objects.geoms.geometries)}(i,e);default:throw new Error(r+" is not supported")}}var Ao=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Do=Math.ceil,Fo=Math.floor,qo="[BigNumber Error] ",Vo=qo+"Number primitive has more than 15 significant digits: ",Go=1e14,Bo=14,Yo=9007199254740991,zo=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],jo=1e7,Xo=1e9;function Uo(t){var e=0|t;return t>0||t===e?e:e-1}function Zo(t){for(var e,n,r=1,i=t.length,o=t[0]+"";rl^n?1:-1;for(a=(u=i.length)<(l=o.length)?u:l,s=0;so[s]^n?1:-1;return u==l?0:u>l^n?1:-1}function Wo(t,e,n,r){if(tn||t!==Fo(t))throw Error(qo+(r||"Argument")+("number"==typeof t?tn?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Jo(t){var e=t.c.length-1;return Uo(t.e/Bo)==e&&t.c[e]%2!=0}function Ko(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Qo(t,e,n){var r,i;if(e<0){for(i=n+".";++e;i+=n);t=i+t}else if(++e>(r=t.length)){for(i=n,e-=r;--e;i+=n);t+=i}else ex?f.c=f.e=null:t.e<_?f.c=[f.e=0]:(f.e=t.e,f.c=t.c.slice()));if((l="number"==typeof t)&&0*t==0){if(f.s=1/t<0?(t=-t,-1):1,t===~~t){for(a=0,u=t;u>=10;u/=10,a++);return void(a>x?f.c=f.e=null:(f.e=a,f.c=[t]))}c=String(t)}else{if(!Ao.test(c=String(t)))return i(f,c,l);f.s=45==c.charCodeAt(0)?(c=c.slice(1),-1):1}(a=c.indexOf("."))>-1&&(c=c.replace(".","")),(u=c.search(/e/i))>0?(a<0&&(a=u),a+=+c.slice(u+1),c=c.substring(0,u)):a<0&&(a=c.length)}else{if(Wo(e,2,I.length,"Base"),10==e&&N)return C(f=new S(t),p+f.e+1,v);if(c=String(t),l="number"==typeof t){if(0*t!=0)return i(f,c,l,e);if(f.s=1/t<0?(c=c.slice(1),-1):1,S.DEBUG&&c.replace(/^0\.0*|\./,"").length>15)throw Error(Vo+t)}else f.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1;for(n=I.slice(0,e),a=u=0,h=c.length;ua){a=h;continue}}else if(!s&&(c==c.toUpperCase()&&(c=c.toLowerCase())||c==c.toLowerCase()&&(c=c.toUpperCase()))){s=!0,u=-1,a=0;continue}return i(f,String(t),l,e)}l=!1,(a=(c=r(c,e,10,f.s)).indexOf("."))>-1?c=c.replace(".",""):a=c.length}for(u=0;48===c.charCodeAt(u);u++);for(h=c.length;48===c.charCodeAt(--h););if(c=c.slice(u,++h)){if(h-=u,l&&S.DEBUG&&h>15&&(t>Yo||t!==Fo(t)))throw Error(Vo+f.s*t);if((a=a-u-1)>x)f.c=f.e=null;else if(a<_)f.c=[f.e=0];else{if(f.e=a,f.c=[],u=(a+1)%Bo,a<0&&(u+=Bo),u=y)?Ko(u,s):Qo(u,s,"0");else if(o=(t=C(new S(t),e,n)).e,a=(u=Zo(t.c)).length,1==r||2==r&&(e<=o||o<=d)){for(;aa){if(--e>0)for(u+=".";e--;u+="0");}else if((e+=o-a)>0)for(o+1==a&&(u+=".");e--;u+="0");return t.s<0&&i?"-"+u:u}function L(t,e){for(var n,r,i=1,o=new S(t[0]);i=10;i/=10,r++);return(n=r+n*Bo-1)>x?t.c=t.e=null:n<_?t.c=[t.e=0]:(t.e=n,t.c=e),t}function C(t,e,n,r){var i,o,s,a,u,l,h,c=t.c,f=zo;if(c){t:{for(i=1,a=c[0];a>=10;a/=10,i++);if((o=e-i)<0)o+=Bo,s=e,u=c[l=0],h=Fo(u/f[i-s-1]%10);else if((l=Do((o+1)/Bo))>=c.length){if(!r)break t;for(;c.length<=l;c.push(0));u=h=0,i=1,s=(o%=Bo)-Bo+1}else{for(u=a=c[l],i=1;a>=10;a/=10,i++);h=(s=(o%=Bo)-Bo+i)<0?0:Fo(u/f[i-s-1]%10)}if(r=r||e<0||null!=c[l+1]||(s<0?u:u%f[i-s-1]),r=n<4?(h||r)&&(0==n||n==(t.s<0?3:2)):h>5||5==h&&(4==n||r||6==n&&(o>0?s>0?u/f[i-s]:0:c[l-1])%10&1||n==(t.s<0?8:7)),e<1||!c[0])return c.length=0,r?(e-=t.e+1,c[0]=f[(Bo-e%Bo)%Bo],t.e=-e||0):c[0]=t.e=0,t;if(0==o?(c.length=l,a=1,l--):(c.length=l+1,a=f[Bo-o],c[l]=s>0?Fo(u/f[i-s]%f[s])*a:0),r)for(;;){if(0==l){for(o=1,s=c[0];s>=10;s/=10,o++);for(s=c[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(t.e++,c[0]==Go&&(c[0]=1));break}if(c[l]+=a,c[l]!=Go)break;c[l--]=0,a=1}for(o=c.length;0===c[--o];c.pop());}t.e>x?t.c=t.e=null:t.e<_&&(t.c=[t.e=0])}return t}function T(t){var e,n=t.e;return null===n?t.toString():(e=Zo(t.c),e=n<=d||n>=y?Ko(e,n):Qo(e,n,"0"),t.s<0?"-"+e:e)}return S.clone=t,S.ROUND_UP=0,S.ROUND_DOWN=1,S.ROUND_CEIL=2,S.ROUND_FLOOR=3,S.ROUND_HALF_UP=4,S.ROUND_HALF_DOWN=5,S.ROUND_HALF_EVEN=6,S.ROUND_HALF_CEIL=7,S.ROUND_HALF_FLOOR=8,S.EUCLID=9,S.config=S.set=function(t){var e,n;if(null!=t){if("object"!=m(t))throw Error(qo+"Object expected: "+t);if(t.hasOwnProperty(e="DECIMAL_PLACES")&&(Wo(n=t[e],0,Xo,e),p=n),t.hasOwnProperty(e="ROUNDING_MODE")&&(Wo(n=t[e],0,8,e),v=n),t.hasOwnProperty(e="EXPONENTIAL_AT")&&((n=t[e])&&n.pop?(Wo(n[0],-Xo,0,e),Wo(n[1],0,Xo,e),d=n[0],y=n[1]):(Wo(n,-Xo,Xo,e),d=-(y=n<0?-n:n))),t.hasOwnProperty(e="RANGE"))if((n=t[e])&&n.pop)Wo(n[0],-Xo,-1,e),Wo(n[1],1,Xo,e),_=n[0],x=n[1];else{if(Wo(n,-Xo,Xo,e),!n)throw Error(qo+e+" cannot be zero: "+n);_=-(x=n<0?-n:n)}if(t.hasOwnProperty(e="CRYPTO")){if((n=t[e])!==!!n)throw Error(qo+e+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw E=!n,Error(qo+"crypto unavailable");E=n}else E=n}if(t.hasOwnProperty(e="MODULO_MODE")&&(Wo(n=t[e],0,9,e),k=n),t.hasOwnProperty(e="POW_PRECISION")&&(Wo(n=t[e],0,Xo,e),b=n),t.hasOwnProperty(e="FORMAT")){if("object"!=m(n=t[e]))throw Error(qo+e+" not an object: "+n);w=n}if(t.hasOwnProperty(e="ALPHABET")){if("string"!=typeof(n=t[e])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(qo+e+" invalid: "+n);N="0123456789"==n.slice(0,10),I=n}}return{DECIMAL_PLACES:p,ROUNDING_MODE:v,EXPONENTIAL_AT:[d,y],RANGE:[_,x],CRYPTO:E,MODULO_MODE:k,POW_PRECISION:b,FORMAT:w,ALPHABET:I}},S.isBigNumber=function(t){if(!t||!0!==t._isBigNumber)return!1;if(!S.DEBUG)return!0;var e,n,r=t.c,i=t.e,o=t.s;t:if("[object Array]"=={}.toString.call(r)){if((1===o||-1===o)&&i>=-Xo&&i<=Xo&&i===Fo(i)){if(0===r[0]){if(0===i&&1===r.length)return!0;break t}if((e=(i+1)%Bo)<1&&(e+=Bo),String(r[0]).length==e){for(e=0;e=Go||n!==Fo(n))break t;if(0!==n)return!0}}}else if(null===r&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(qo+"Invalid BigNumber: "+t)},S.maximum=S.max=function(){return L(arguments,-1)},S.minimum=S.min=function(){return L(arguments,1)},S.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Fo(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(t){var e,n,r,i,o,a=0,u=[],l=new S(g);if(null==t?t=p:Wo(t,0,Xo),i=Do(t/Bo),E)if(crypto.getRandomValues){for(e=crypto.getRandomValues(new Uint32Array(i*=2));a>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),e[a]=n[0],e[a+1]=n[1]):(u.push(o%1e14),a+=2);a=i/2}else{if(!crypto.randomBytes)throw E=!1,Error(qo+"crypto unavailable");for(e=crypto.randomBytes(i*=7);a=9e15?crypto.randomBytes(7).copy(e,a):(u.push(o%1e14),a+=7);a=i/7}if(!E)for(;a=10;o/=10,a++);an-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(r,i,o,s,a){var u,l,h,c,f,g,d,y,m=r.indexOf("."),_=p,x=v;for(m>=0&&(c=b,b=0,r=r.replace(".",""),g=(y=new S(i)).pow(r.length-m),b=c,y.c=e(Qo(Zo(g.c),g.e,"0"),10,o,t),y.e=y.c.length),h=c=(d=e(r,i,o,a?(u=I,t):(u=t,I))).length;0==d[--c];d.pop());if(!d[0])return u.charAt(0);if(m<0?--h:(g.c=d,g.e=h,g.s=s,d=(g=n(g,y,_,x,o)).c,f=g.r,h=g.e),m=d[l=h+_+1],c=o/2,f=f||l<0||null!=d[l+1],f=x<4?(null!=m||f)&&(0==x||x==(g.s<0?3:2)):m>c||m==c&&(4==x||f||6==x&&1&d[l-1]||x==(g.s<0?8:7)),l<1||!d[0])r=f?Qo(u.charAt(1),-_,u.charAt(0)):u.charAt(0);else{if(d.length=l,f)for(--o;++d[--l]>o;)d[l]=0,l||(++h,d=[1].concat(d));for(c=d.length;!d[--c];);for(m=0,r="";m<=c;r+=u.charAt(d[m++]));r=Qo(r,h,u.charAt(0))}return r}}(),n=function(){function t(t,e,n){var r,i,o,s,a=0,u=t.length,l=e%jo,h=e/jo|0;for(t=t.slice();u--;)a=((i=l*(o=t[u]%jo)+(r=h*o+(s=t[u]/jo|0)*l)%jo*jo+a)/n|0)+(r/jo|0)+h*s,t[u]=i%n;return a&&(t=[a].concat(t)),t}function e(t,e,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;ie[i]?1:-1;break}return o}function n(t,e,n,r){for(var i=0;n--;)t[n]-=i,i=t[n]1;t.splice(0,1));}return function(r,i,o,s,a){var u,l,h,c,f,g,p,v,d,y,m,_,x,E,k,b,w,I=r.s==i.s?1:-1,N=r.c,M=i.c;if(!(N&&N[0]&&M&&M[0]))return new S(r.s&&i.s&&(N?!M||N[0]!=M[0]:M)?N&&0==N[0]||!M?0*I:I/0:NaN);for(d=(v=new S(I)).c=[],I=o+(l=r.e-i.e)+1,a||(a=Go,l=Uo(r.e/Bo)-Uo(i.e/Bo),I=I/Bo|0),h=0;M[h]==(N[h]||0);h++);if(M[h]>(N[h]||0)&&l--,I<0)d.push(1),c=!0;else{for(E=N.length,b=M.length,h=0,I+=2,(f=Fo(a/(M[0]+1)))>1&&(M=t(M,f,a),N=t(N,f,a),b=M.length,E=N.length),x=b,m=(y=N.slice(0,b)).length;m=a/2&&k++;do{if(f=0,(u=e(M,y,b,m))<0){if(_=y[0],b!=m&&(_=_*a+(y[1]||0)),(f=Fo(_/k))>1)for(f>=a&&(f=a-1),p=(g=t(M,f,a)).length,m=y.length;1==e(g,y,p,m);)f--,n(g,b=10;I/=10,h++);C(v,o+(v.e=h+l*Bo-1)+1,s,c)}else v.e=l,v.r=+c;return v}}(),a=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,l=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,c=/^\s*\+(?=[\w.])|^\s+|\s+$/g,i=function(t,e,n,r){var i,o=n?e:e.replace(c,"");if(h.test(o))t.s=isNaN(o)?null:o<0?-1:1;else{if(!n&&(o=o.replace(a,(function(t,e,n){return i="x"==(n=n.toLowerCase())?16:"b"==n?2:8,r&&r!=i?t:e})),r&&(i=r,o=o.replace(u,"$1").replace(l,"0.$1")),e!=o))return new S(o,i);if(S.DEBUG)throw Error(qo+"Not a"+(r?" base "+r:"")+" number: "+e);t.s=null}t.c=t.e=null},f.absoluteValue=f.abs=function(){var t=new S(this);return t.s<0&&(t.s=1),t},f.comparedTo=function(t,e){return Ho(this,new S(t,e))},f.decimalPlaces=f.dp=function(t,e){var n,r,i,o=this;if(null!=t)return Wo(t,0,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t+o.e+1,e);if(!(n=o.c))return null;if(r=((i=n.length-1)-Uo(this.e/Bo))*Bo,i=n[i])for(;i%10==0;i/=10,r--);return r<0&&(r=0),r},f.dividedBy=f.div=function(t,e){return n(this,new S(t,e),p,v)},f.dividedToIntegerBy=f.idiv=function(t,e){return n(this,new S(t,e),0,1)},f.exponentiatedBy=f.pow=function(t,e){var n,r,i,o,s,a,u,l,h=this;if((t=new S(t)).c&&!t.isInteger())throw Error(qo+"Exponent not an integer: "+T(t));if(null!=e&&(e=new S(e)),s=t.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!t.c||!t.c[0])return l=new S(Math.pow(+T(h),s?t.s*(2-Jo(t)):+T(t))),e?l.mod(e):l;if(a=t.s<0,e){if(e.c?!e.c[0]:!e.s)return new S(NaN);(r=!a&&h.isInteger()&&e.isInteger())&&(h=h.mod(e))}else{if(t.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return o=h.s<0&&Jo(t)?-0:0,h.e>-1&&(o=1/o),new S(a?1/o:o);b&&(o=Do(b/Bo+2))}for(s?(n=new S(.5),a&&(t.s=1),u=Jo(t)):u=(i=Math.abs(+T(t)))%2,l=new S(g);;){if(u){if(!(l=l.times(h)).c)break;o?l.c.length>o&&(l.c.length=o):r&&(l=l.mod(e))}if(i){if(0===(i=Fo(i/2)))break;u=i%2}else if(C(t=t.times(n),t.e+1,1),t.e>14)u=Jo(t);else{if(0===(i=+T(t)))break;u=i%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):r&&(h=h.mod(e))}return r?l:(a&&(l=g.div(l)),e?l.mod(e):o?C(l,b,v,undefined):l)},f.integerValue=function(t){var e=new S(this);return null==t?t=v:Wo(t,0,8),C(e,e.e+1,t)},f.isEqualTo=f.eq=function(t,e){return 0===Ho(this,new S(t,e))},f.isFinite=function(){return!!this.c},f.isGreaterThan=f.gt=function(t,e){return Ho(this,new S(t,e))>0},f.isGreaterThanOrEqualTo=f.gte=function(t,e){return 1===(e=Ho(this,new S(t,e)))||0===e},f.isInteger=function(){return!!this.c&&Uo(this.e/Bo)>this.c.length-2},f.isLessThan=f.lt=function(t,e){return Ho(this,new S(t,e))<0},f.isLessThanOrEqualTo=f.lte=function(t,e){return-1===(e=Ho(this,new S(t,e)))||0===e},f.isNaN=function(){return!this.s},f.isNegative=function(){return this.s<0},f.isPositive=function(){return this.s>0},f.isZero=function(){return!!this.c&&0==this.c[0]},f.minus=function(t,e){var n,r,i,o,s=this,a=s.s;if(e=(t=new S(t,e)).s,!a||!e)return new S(NaN);if(a!=e)return t.s=-e,s.plus(t);var u=s.e/Bo,l=t.e/Bo,h=s.c,c=t.c;if(!u||!l){if(!h||!c)return h?(t.s=-e,t):new S(c?s:NaN);if(!h[0]||!c[0])return c[0]?(t.s=-e,t):new S(h[0]?s:3==v?-0:0)}if(u=Uo(u),l=Uo(l),h=h.slice(),a=u-l){for((o=a<0)?(a=-a,i=h):(l=u,i=c),i.reverse(),e=a;e--;i.push(0));i.reverse()}else for(r=(o=(a=h.length)<(e=c.length))?a:e,a=e=0;e0)for(;e--;h[n++]=0);for(e=Go-1;r>a;){if(h[--r]=0;){for(n=0,f=_[i]%d,g=_[i]/d|0,o=i+(s=u);o>i;)n=((l=f*(l=m[--s]%d)+(a=g*l+(h=m[s]/d|0)*f)%d*d+p[o]+n)/v|0)+(a/d|0)+g*h,p[o--]=l%v;p[o]=n}return n?++r:p.splice(0,1),P(t,p,r)},f.negated=function(){var t=new S(this);return t.s=-t.s||null,t},f.plus=function(t,e){var n,r=this,i=r.s;if(e=(t=new S(t,e)).s,!i||!e)return new S(NaN);if(i!=e)return t.s=-e,r.minus(t);var o=r.e/Bo,s=t.e/Bo,a=r.c,u=t.c;if(!o||!s){if(!a||!u)return new S(i/0);if(!a[0]||!u[0])return u[0]?t:new S(a[0]?r:0*i)}if(o=Uo(o),s=Uo(s),a=a.slice(),i=o-s){for(i>0?(s=o,n=u):(i=-i,n=a),n.reverse();i--;n.push(0));n.reverse()}for((i=a.length)-(e=u.length)<0&&(n=u,u=a,a=n,e=i),i=0;e;)i=(a[--e]=a[e]+u[e]+i)/Go|0,a[e]=Go===a[e]?0:a[e]%Go;return i&&(a=[i].concat(a),++s),P(t,a,s)},f.precision=f.sd=function(t,e){var n,r,i,o=this;if(null!=t&&t!==!!t)return Wo(t,1,Xo),null==e?e=v:Wo(e,0,8),C(new S(o),t,e);if(!(n=o.c))return null;if(r=(i=n.length-1)*Bo+1,i=n[i]){for(;i%10==0;i/=10,r--);for(i=n[0];i>=10;i/=10,r++);}return t&&o.e+1>r&&(r=o.e+1),r},f.shiftedBy=function(t){return Wo(t,-9007199254740991,Yo),this.times("1e"+t)},f.squareRoot=f.sqrt=function(){var t,e,r,i,o,s=this,a=s.c,u=s.s,l=s.e,h=p+4,c=new S("0.5");if(1!==u||!a||!a[0])return new S(!u||u<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(u=Math.sqrt(+T(s)))||u==1/0?(((e=Zo(a)).length+l)%2==0&&(e+="0"),u=Math.sqrt(+e),l=Uo((l+1)/2)-(l<0||l%2),r=new S(e=u==1/0?"5e"+l:(e=u.toExponential()).slice(0,e.indexOf("e")+1)+l)):r=new S(u+""),r.c[0])for((u=(l=r.e)+h)<3&&(u=0);;)if(o=r,r=c.times(o.plus(n(s,o,h,1))),Zo(o.c).slice(0,u)===(e=Zo(r.c)).slice(0,u)){if(r.e0&&p>0){for(o=p%a||a,h=g.substr(0,o);o0&&(h+=l+g.slice(o)),f&&(h="-"+h)}r=c?h+(n.decimalSeparator||"")+((u=+n.fractionGroupSize)?c.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):c):h}return(n.prefix||"")+r+(n.suffix||"")},f.toFraction=function(t){var e,r,i,o,s,a,u,l,h,c,f,p,d=this,y=d.c;if(null!=t&&(!(u=new S(t)).isInteger()&&(u.c||1!==u.s)||u.lt(g)))throw Error(qo+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+T(u));if(!y)return new S(d);for(e=new S(g),h=r=new S(g),i=l=new S(g),p=Zo(y),s=e.e=p.length-d.e-1,e.c[0]=zo[(a=s%Bo)<0?Bo+a:a],t=!t||u.comparedTo(e)>0?s>0?e:h:u,a=x,x=1/0,u=new S(p),l.c[0]=0;c=n(u,e,0,1),1!=(o=r.plus(c.times(i))).comparedTo(t);)r=i,i=o,h=l.plus(c.times(o=h)),l=o,e=u.minus(c.times(o=e)),u=o;return o=n(t.minus(r),i,0,1),l=l.plus(o.times(h)),r=r.plus(o.times(i)),l.s=h.s=d.s,f=n(h,i,s*=2,v).minus(d).abs().comparedTo(n(l,r,s,v).minus(d).abs())<1?[h,i]:[l,r],x=a,f},f.toNumber=function(){return+T(this)},f.toPrecision=function(t,e){return null!=t&&Wo(t,1,Xo),M(this,t,e,2)},f.toString=function(t){var e,n=this,i=n.s,o=n.e;return null===o?i?(e="Infinity",i<0&&(e="-"+e)):e="NaN":(null==t?e=o<=d||o>=y?Ko(Zo(n.c),o):Qo(Zo(n.c),o,"0"):10===t&&N?e=Qo(Zo((n=C(new S(n),p+o+1,v)).c),n.e,"0"):(Wo(t,2,I.length,"Base"),e=r(Qo(Zo(n.c),o,"0"),10,t,i,!0)),i<0&&n.c[0]&&(e="-"+e)),e},f.valueOf=f.toJSON=function(){return T(this)},f._isBigNumber=!0,f[Symbol.toStringTag]="BigNumber",f[Symbol.for("nodejs.util.inspect.custom")]=f.valueOf,null!=e&&S.set(e),S}(),ts=function(t){function e(t){return i(this,e),r(this,e,[t])}return h(e,t),s(e)}(s((function t(e){i(this,t),u(this,"key",void 0),u(this,"left",null),u(this,"right",null),this.key=e}))),es=function(){return s((function t(){i(this,t),u(this,"size",0),u(this,"modificationCount",0),u(this,"splayCount",0)}),[{key:"splay",value:function(t){var e=this.root;if(null==e)return this.compare(t,t),-1;for(var n,r=null,i=null,o=null,s=null,a=e,u=this.compare;;)if((n=u(a.key,t))>0){var l=a.left;if(null==l)break;if((n=u(l.key,t))>0&&(a.left=l.right,l.right=a,null==(l=(a=l).left)))break;null==r?i=a:r.left=a,r=a,a=l}else{if(!(n<0))break;var h=a.right;if(null==h)break;if((n=u(h.key,t))<0&&(a.right=h.left,h.left=a,null==(h=(a=h).right)))break;null==o?s=a:o.right=a,o=a,a=h}return null!=o&&(o.right=a.left,a.left=s),null!=r&&(r.left=a.right,a.right=i),this.root!==a&&(this.root=a,this.splayCount++),n}},{key:"splayMin",value:function(t){for(var e=t,n=e.left;null!=n;){var r=n;e.left=r.right,r.right=e,n=(e=r).left}return e}},{key:"splayMax",value:function(t){for(var e=t,n=e.right;null!=n;){var r=n;e.right=r.left,r.left=e,n=(e=r).right}return e}},{key:"_delete",value:function(t){if(null==this.root)return null;if(0!=this.splay(t))return null;var e=this.root,n=e,r=e.left;if(this.size--,null==r)this.root=e.right;else{var i=e.right;(e=this.splayMax(r)).right=i,this.root=e}return this.modificationCount++,n}},{key:"addNewRoot",value:function(t,e){this.size++,this.modificationCount++;var n=this.root;null!=n?(e<0?(t.left=n,t.right=n.right,n.right=null):(t.right=n,t.left=n.left,n.left=null),this.root=t):this.root=t}},{key:"_first",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMin(t),this.root)}},{key:"_last",value:function(){var t=this.root;return null==t?null:(this.root=this.splayMax(t),this.root)}},{key:"clear",value:function(){this.root=null,this.size=0,this.modificationCount++}},{key:"has",value:function(t){return this.validKey(t)&&0==this.splay(t)}},{key:"defaultCompare",value:function(){return function(t,e){return te?1:0}}},{key:"wrap",value:function(){var t=this;return{getRoot:function(){return t.root},setRoot:function(e){t.root=e},getSize:function(){return t.size},getModificationCount:function(){return t.modificationCount},getSplayCount:function(){return t.splayCount},setSplayCount:function(e){t.splayCount=e},splay:function(e){return t.splay(e)},has:function(e){return t.has(e)}}}}])}(),ns=function(t){function e(t,n){var o;return i(this,e),u(o=r(this,e),"root",null),u(o,"compare",void 0),u(o,"validKey",void 0),u(o,Symbol.toStringTag,"[object Set]"),o.compare=null!=t?t:o.defaultCompare(),o.validKey=null!=n?n:function(t){return null!=t&&null!=t},o}return h(e,t),s(e,[{key:"delete",value:function(t){return!!this.validKey(t)&&null!=this._delete(t)}},{key:"deleteAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.delete(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"forEach",value:function(t){for(var e,n=this[Symbol.iterator]();!(e=n.next()).done;)t(e.value,e.value,this)}},{key:"add",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this}},{key:"addAndReturn",value:function(t){var e=this.splay(t);return 0!=e&&this.addNewRoot(new ts(t),e),this.root.key}},{key:"addAll",value:function(t){var e,n=a(t);try{for(n.s();!(e=n.n()).done;){var r=e.value;this.add(r)}}catch(t){n.e(t)}finally{n.f()}}},{key:"isEmpty",value:function(){return null==this.root}},{key:"isNotEmpty",value:function(){return null!=this.root}},{key:"single",value:function(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}},{key:"first",value:function(){if(0==this.size)throw"Bad state: No element";return this._first().key}},{key:"last",value:function(){if(0==this.size)throw"Bad state: No element";return this._last().key}},{key:"lastBefore",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)<0)return this.root.key;var e=this.root.left;if(null==e)return null;for(var n=e.right;null!=n;)n=(e=n).right;return e.key}},{key:"firstAfter",value:function(t){if(null==t)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(t)>0)return this.root.key;var e=this.root.right;if(null==e)return null;for(var n=e.left;null!=n;)n=(e=n).left;return e.key}},{key:"retainAll",value:function(t){var n,r=new e(this.compare,this.validKey),i=this.modificationCount,o=a(t);try{for(o.s();!(n=o.n()).done;){var s=n.value;if(i!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(s)&&0==this.splay(s)&&r.add(this.root.key)}}catch(t){o.e(t)}finally{o.f()}r.size!=this.size&&(this.root=r.root,this.size=r.size,this.modificationCount++)}},{key:"lookup",value:function(t){return this.validKey(t)?0!=this.splay(t)?null:this.root.key:null}},{key:"intersection",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)&&r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"difference",value:function(t){var n,r=new e(this.compare,this.validKey),i=a(this);try{for(i.s();!(n=i.n()).done;){var o=n.value;t.has(o)||r.add(o)}}catch(t){i.e(t)}finally{i.f()}return r}},{key:"union",value:function(t){var e=this.clone();return e.addAll(t),e}},{key:"clone",value:function(){var t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}},{key:"copyNode",value:function(t){if(null==t)return null;var e=new ts(t.key);return function t(e,n){var r,i;do{if(r=e.left,i=e.right,null!=r){var o=new ts(r.key);n.left=o,t(r,o)}if(null!=i){var s=new ts(i.key);n.right=s,e=i,n=s}}while(null!=i)}(t,e),e}},{key:"toSet",value:function(){return this.clone()}},{key:"entries",value:function(){return new os(this.wrap())}},{key:"keys",value:function(){return this[Symbol.iterator]()}},{key:"values",value:function(){return this[Symbol.iterator]()}},{key:Symbol.iterator,value:function(){return new is(this.wrap())}}])}(es),rs=function(){return s((function t(e){i(this,t),u(this,"tree",void 0),u(this,"path",new Array),u(this,"modificationCount",null),u(this,"splayCount",void 0),this.tree=e,this.splayCount=e.getSplayCount()}),[{key:Symbol.iterator,value:function(){return this}},{key:"next",value:function(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}},{key:"current",value:function(){if(!this.path.length)return null;var t=this.path[this.path.length-1];return this.getValue(t)}},{key:"rebuildPath",value:function(t){this.path.splice(0,this.path.length),this.tree.splay(t),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}},{key:"findLeftMostDescendent",value:function(t){for(;null!=t;)this.path.push(t),t=t.left}},{key:"moveNext",value:function(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();for(var t=this.tree.getRoot();null!=t;)this.path.push(t),t=t.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);var e=this.path[this.path.length-1],n=e.right;if(null!=n){for(;null!=n;)this.path.push(n),n=n.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}}])}(),is=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return t.key}}])}(rs),os=function(t){function e(){return i(this,e),r(this,e,arguments)}return h(e,t),s(e,[{key:"getValue",value:function(t){return[t.key,t.key]}}])}(rs),ss=function(t){return function(){return t}},as=function(t){var e=t?function(e,n){return n.minus(e).abs().isLessThanOrEqualTo(t)}:ss(!1);return function(t,n){return e(t,n)?0:t.comparedTo(n)}};function us(t){var e=t?function(e,n,r,i,o){return e.exponentiatedBy(2).isLessThanOrEqualTo(i.minus(n).exponentiatedBy(2).plus(o.minus(r).exponentiatedBy(2)).times(t))}:ss(!1);return function(t,n,r){var i=t.x,o=t.y,s=r.x,a=r.y,u=o.minus(a).times(n.x.minus(s)).minus(i.minus(s).times(n.y.minus(a)));return e(u,i,o,s,a)?0:u.comparedTo(0)}}var ls=function(t){return t},hs=function(t){if(t){var e=new ns(as(t)),n=new ns(as(t)),r=function(t,e){return e.addAndReturn(t)},i=function(t){return{x:r(t.x,e),y:r(t.y,n)}};return i({x:new $o(0),y:new $o(0)}),i}return ls},cs=function(t){return{set:function(t){fs=cs(t)},reset:function(){return cs(t)},compare:as(t),snap:hs(t),orient:us(t)}},fs=cs(),gs=function(t,e){return t.ll.x.isLessThanOrEqualTo(e.x)&&e.x.isLessThanOrEqualTo(t.ur.x)&&t.ll.y.isLessThanOrEqualTo(e.y)&&e.y.isLessThanOrEqualTo(t.ur.y)},ps=function(t,e){if(e.ur.x.isLessThan(t.ll.x)||t.ur.x.isLessThan(e.ll.x)||e.ur.y.isLessThan(t.ll.y)||t.ur.y.isLessThan(e.ll.y))return null;var n=t.ll.x.isLessThan(e.ll.x)?e.ll.x:t.ll.x,r=t.ur.x.isLessThan(e.ur.x)?t.ur.x:e.ur.x;return{ll:{x:n,y:t.ll.y.isLessThan(e.ll.y)?e.ll.y:t.ll.y},ur:{x:r,y:t.ur.y.isLessThan(e.ur.y)?t.ur.y:e.ur.y}}},vs=function(t,e){return t.x.times(e.y).minus(t.y.times(e.x))},ds=function(t,e){return t.x.times(e.x).plus(t.y.times(e.y))},ys=function(t){return ds(t,t).sqrt()},ms=function(t,e,n){var r={x:e.x.minus(t.x),y:e.y.minus(t.y)},i={x:n.x.minus(t.x),y:n.y.minus(t.y)};return ds(i,r).div(ys(i)).div(ys(r))},_s=function(t,e,n){return e.y.isZero()?null:{x:t.x.plus(e.x.div(e.y).times(n.minus(t.y))),y:n}},xs=function(t,e,n){return e.x.isZero()?null:{x:n,y:t.y.plus(e.y.div(e.x).times(n.minus(t.x)))}},Es=function(){function t(e,n){i(this,t),u(this,"point",void 0),u(this,"isLeft",void 0),u(this,"segment",void 0),u(this,"otherSE",void 0),u(this,"consumedBy",void 0),void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=n}return s(t,[{key:"link",value:function(t){if(t.point===this.point)throw new Error("Tried to link already linked events");for(var e=t.point.events,n=0,r=e.length;n0&&(t=r)}for(var i=t.segment.prevInResult(),o=i?i.prevInResult():null;;){if(!i)return null;if(!o)return i.ringOut;var s,a;if(o.ringOut!==i.ringOut)return(null===(s=o.ringOut)||void 0===s?void 0:s.enclosingRing())!==i.ringOut?i.ringOut:null===(a=i.ringOut)||void 0===a?void 0:a.enclosingRing();i=o.prevInResult(),o=i?i.prevInResult():null}}}],[{key:"factory",value:function(e){for(var n=[],r=0,i=e.length;r1&&void 0!==arguments[1]?arguments[1]:Ls.compare;i(this,t),u(this,"queue",void 0),u(this,"tree",void 0),u(this,"segments",void 0),this.queue=e,this.tree=new ns(n),this.segments=[]}),[{key:"process",value:function(t){var e=t.segment,n=[];if(t.consumedBy)return t.isLeft?this.queue.delete(t.otherSE):this.tree.delete(e),n;t.isLeft&&this.tree.add(e);var r=e,i=e;do{r=this.tree.lastBefore(r)}while(null!=r&&null!=r.consumedBy);do{i=this.tree.firstAfter(i)}while(null!=i&&null!=i.consumedBy);if(t.isLeft){var o=null;if(r){var s=r.getIntersection(e);if(null!==s&&(e.isAnEndpoint(s)||(o=s),!r.isAnEndpoint(s)))for(var a=this._splitSafely(r,s),u=0,l=a.length;u0?(this.tree.delete(e),n.push(t)):(this.segments.push(e),e.prev=r)}else{if(r&&i){var _=r.getIntersection(i);if(null!==_){if(!r.isAnEndpoint(_))for(var x=this._splitSafely(r,_),E=0,k=x.length;E0&&a.swapEvents(),Es.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),r&&(i.checkForConsuming(),o.checkForConsuming()),n}},{key:"swapEvents",value:function(){var t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(var e=0,n=this.windings.length;e0){var o=n;n=r,r=o}if(n.prev===r){var s=n;n=r,r=s}for(var a=0,u=r.rings.length;a0)return-1;var c=e.comparePoint(t.rightSE.point);return 0!==c?c:-1}if(n.isGreaterThan(r)){if(s.isLessThan(a)&&s.isLessThan(l))return-1;if(s.isGreaterThan(a)&&s.isGreaterThan(l))return 1;var f=e.comparePoint(t.leftSE.point);if(0!==f)return f;var g=t.comparePoint(e.rightSE.point);return g<0?1:g>0?-1:1}if(s.isLessThan(a))return-1;if(s.isGreaterThan(a))return 1;if(i.isLessThan(o)){var p=e.comparePoint(t.rightSE.point);if(0!==p)return p}if(i.isGreaterThan(o)){var v=t.comparePoint(e.rightSE.point);if(v<0)return 1;if(v>0)return-1}if(!i.eq(o)){var d=u.minus(s),y=i.minus(n),m=l.minus(a),_=o.minus(r);if(d.isGreaterThan(y)&&m.isLessThan(_))return 1;if(d.isLessThan(y)&&m.isGreaterThan(_))return-1}return i.isGreaterThan(o)?1:i.isLessThan(o)||u.isLessThan(l)?-1:u.isGreaterThan(l)?1:t.ide.id?1:0}},{key:"fromRing",value:function(e,n,r){var i,o,s,a=Es.comparePoints(e,n);if(a<0)i=e,o=n,s=1;else{if(!(a>0))throw new Error("Tried to create degenerate segment at [".concat(e.x,", ").concat(e.y,"]"));i=n,o=e,s=-1}return new t(new Es(i,!0),new Es(o,!1),[r],[s])}}])}(),Ps=function(){return s((function t(e,n,r){if(i(this,t),u(this,"poly",void 0),u(this,"isExterior",void 0),u(this,"segments",void 0),u(this,"bbox",void 0),!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");var o=fs.snap({x:new $o(e[0][0]),y:new $o(e[0][1])});this.bbox={ll:{x:o.x,y:o.y},ur:{x:o.x,y:o.y}};for(var s=o,a=1,l=e.length;a1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r1?e-1:0),r=1;r2&&void 0!==arguments[2]?arguments[2]:2,r=K(t),i=K(e),o=r[0]-i[0],s=r[1]-i[1];return 1===n?Math.abs(o)+Math.abs(s):Math.pow(Math.pow(o,n)+Math.pow(s,n),1/n)}function Gs(t,e){var n,r,i=(e=e||{}).threshold||1e4,o=e.p||2,s=null!=(n=e.binary)&&n,a=e.alpha||-1,u=null!=(r=e.standardization)&&r,l=[];vt(t,(function(t){l.push(gi(t))}));for(var h=[],c=0;c3&&void 0!==arguments[3]?arguments[3]:{},i=e<0,o=j(Math.abs(e),r.units,"meters");i&&(o=-Math.abs(o));var s=K(t),a=function(t,e,n,r){r=void 0===r?x:Number(r);var i=e/r,o=t[0]*Math.PI/180,s=z(t[1]),a=z(n),u=i*Math.cos(a),l=s+u;Math.abs(l)>Math.PI/2&&(l=l>0?Math.PI-l:-Math.PI-l);var h=Math.log(Math.tan(l/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),c=Math.abs(h)>1e-11?u/h:Math.cos(s),f=i*Math.sin(a)/c;return[(180*(o+f)/Math.PI+540)%360-180,180*l/Math.PI]}(s,o,n);return a[0]+=a[0]-s[0]>180?-360:s[0]-a[0]>180?360:0,I(a,r.properties)}function Ys(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=K(t),i=K(e);i[0]+=i[0]-r[0]>180?-360:r[0]-i[0]>180?360:0;var o=function(t,e,n){var r=n=void 0===n?x:Number(n),i=t[1]*Math.PI/180,o=e[1]*Math.PI/180,s=o-i,a=Math.abs(e[0]-t[0])*Math.PI/180;a>Math.PI&&(a-=2*Math.PI);var u=Math.log(Math.tan(o/2+Math.PI/4)/Math.tan(i/2+Math.PI/4)),l=Math.abs(u)>1e-11?s/u:Math.cos(i);return Math.sqrt(s*s+l*l*a*a)*r}(r,i);return j(o,"meters",n.units)}function zs(t,e,n){if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.pivot,i=n.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("angle is required");if(0===e)return t;var o=null!=r?r:gi(t);return!1!==i&&void 0!==i||(t=Ai(t)),ct(t,(function(t){var n=lt(o,t)+e,r=Ys(o,t),i=Q(Bs(o,r,n));t[0]=i[0],t[1]=i[1]})),t}function js(t,e,n,r){var i=(r=r||{}).steps||64,o=r.units||"kilometers",s=r.angle||0,a=r.pivot||t,u=r.properties||{};if(!t)throw new Error("center is required");if(!e)throw new Error("xSemiAxis is required");if(!n)throw new Error("ySemiAxis is required");if(!Z(r))throw new Error("options must be an object");if(!U(i))throw new Error("steps must be a number");if(!U(s))throw new Error("angle must be a number");var l=K(t);if("degrees"!==o){var h=Bs(t,e,90,{units:o}),c=Bs(t,n,0,{units:o});e=K(h)[0]-l[0],n=K(c)[1]-l[1]}for(var f=[],g=0;g=-270&&(v=-v),p<-180&&p>=-360&&(d=-d),"degrees"===o){var y=z(s),m=v*Math.cos(y)+d*Math.sin(y),_=d*Math.cos(y)-v*Math.sin(y);v=m,d=_}f.push([v+l[0],d+l[1]])}return f.push(f[0]),"degrees"===o?S([f],u):zs(S([f],u),s,{pivot:a})}function Xs(t){var e=t*Math.PI/180;return Math.tan(e)}function Us(t){return Vt(Rt(t))}function Zs(t){var e=[];return"FeatureCollection"===t.type?vt(t,(function(t){ct(t,(function(n){e.push(I(n,t.properties))}))})):"Feature"===t.type?ct(t,(function(n){e.push(I(n,t.properties))})):ct(t,(function(t){e.push(I(t))})),C(e)}var Hs=Math.PI/180,Ws=180/Math.PI,Js=function(t,e){this.lon=t,this.lat=e,this.x=Hs*t,this.y=Hs*e};Js.prototype.view=function(){return String(this.lon).slice(0,4)+","+String(this.lat).slice(0,4)},Js.prototype.antipode=function(){var t=-1*this.lat,e=this.lon<0?180+this.lon:-1*(180-this.lon);return new Js(e,t)};var Ks=function(){this.coords=[],this.length=0};Ks.prototype.move_to=function(t){this.length++,this.coords.push(t)};var Qs=function(t){this.properties=t||{},this.geometries=[]};Qs.prototype.json=function(){if(this.geometries.length<=0)return{geometry:{type:"LineString",coordinates:null},type:"Feature",properties:this.properties};if(1===this.geometries.length)return{geometry:{type:"LineString",coordinates:this.geometries[0].coords},type:"Feature",properties:this.properties};for(var t=[],e=0;e1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must specify at least 2 geometries");var r=Rs.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)}function ea(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.stringify(n.properties||{}),i=v(t,4),o=i[0],s=i[1],a=i[2],u=i[3],l=(s+u)/2,h=(o+a)/2,c=2*e/ut([o,l],[a,l],n)*(a-o),f=2*e/ut([h,s],[h,u],n)*(u-s),g=c/2,p=2*g,d=Math.sqrt(3)/2*f,y=a-o,m=u-s,_=3/4*p,x=d,E=(y-p)/(p-g/2),k=Math.floor(E),b=(k*_-g/2-y)/2-g/2+_/2,w=Math.floor((m-d)/d),I=(m-w*d)/2,N=w*d-m>d/2;N&&(I-=d/4);for(var S=[],M=[],L=0;L<6;L++){var P=2*Math.PI/6*L;S.push(Math.cos(P)),M.push(Math.sin(P))}for(var T=[],O=0;O<=k;O++)for(var R=0;R<=w;R++){var A=O%2==1;if((0!==R||!A)&&(0!==R||!N)){var D=O*_+o-b,F=R*x+s+I;if(A&&(F-=d/2),!0===n.triangles)ra([D,F],c/2,f/2,JSON.parse(r),S,M).forEach((function(t){n.mask?ta(C([n.mask,t]))&&T.push(t):T.push(t)}));else{var q=na([D,F],c/2,f/2,JSON.parse(r),S,M);n.mask?ta(C([n.mask,q]))&&T.push(q):T.push(q)}}}return C(T)}function na(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=t[0]+e*i[a],l=t[1]+n*o[a];s.push([u,l])}return s.push(s[0].slice()),S([s],r)}function ra(t,e,n,r,i,o){for(var s=[],a=0;a<6;a++){var u=[];u.push(t),u.push([t[0]+e*i[a],t[1]+n*o[a]]),u.push([t[0]+e*i[(a+1)%6],t[1]+n*o[(a+1)%6]]),u.push(t),s.push(S([u],r))}return s}function ia(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.mask&&!n.units&&(n.units="kilometers");for(var r=[],i=t[0],o=t[1],s=t[2],a=t[3],u=e/ut([i,o],[s,o],n)*(s-i),l=e/ut([i,o],[i,a],n)*(a-o),h=s-i,c=a-o,f=Math.floor(h/u),g=(c-Math.floor(c/l)*l)/2,p=i+(h-f*u)/2;p<=s;){for(var v=o+g;v<=a;){var d=I([p,v],n.properties);n.mask?Cn(d,n.mask)&&r.push(d):r.push(d),v+=l}p+=u}return C(r)}function oa(t,e,n){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=[],o=t[0],s=t[1],a=t[2],u=t[3],l=a-o,h=j(e,r.units,"degrees"),c=u-s,f=j(n,r.units,"degrees"),g=Math.floor(Math.abs(l)/h),p=Math.floor(Math.abs(c)/f),v=(c-p*f)/2,d=o+(l-g*h)/2,y=0;y2&&void 0!==arguments[2]?arguments[2]:{})}function aa(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=[],i=e/ut([t[0],t[1]],[t[2],t[1]],n)*(t[2]-t[0]),o=e/ut([t[0],t[1]],[t[0],t[3]],n)*(t[3]-t[1]),s=0,a=t[0];a<=t[2];){for(var u=0,l=t[1];l<=t[3];){var h=null,c=null;s%2==0&&u%2==0?(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)):s%2==0&&u%2==1?(h=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties)):u%2==0&&s%2==1?(h=S([[[a,l],[a,l+o],[a+i,l+o],[a,l]]],n.properties),c=S([[[a,l],[a+i,l+o],[a+i,l],[a,l]]],n.properties)):u%2==1&&s%2==1&&(h=S([[[a,l],[a,l+o],[a+i,l],[a,l]]],n.properties),c=S([[[a,l+o],[a+i,l+o],[a+i,l],[a,l+o]]],n.properties)),n.mask?(ta(C([n.mask,h]))&&r.push(h),ta(C([n.mask,c]))&&r.push(c)):(r.push(h),r.push(c)),l+=o,u++}s++,a+=i}return C(r)} +/*! + * MarchingSquaresJS + * version 1.3.3 + * https://github.com/RaumZeit/MarchingSquares.js + * + * @license GNU Affero General Public License. + * Copyright (c) 2015-2019 Ronny Lorenz + */ +function ua(t,e,n){return tr&&(i=n,n=r,r=i),tr?(t-r)/(t-e):(t-n)/(t-e)}function ha(t,e,n,r){return t1){for(;0!==o;)o>>=1,a++;r===1<1){for(;0!==s;)s>>=1,u++;i===1<0&&(this.childB=new da(t,e+o,n,r-o,s),this.lowerBound=Math.min(this.lowerBound,this.childB.lowerBound),this.upperBound=Math.max(this.upperBound,this.childB.upperBound),i-s>0&&(this.childC=new da(t,e+o,n+s,r-o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childC.lowerBound),this.upperBound=Math.max(this.upperBound,this.childC.upperBound))),i-s>0&&(this.childD=new da(t,e,n+s,o,i-s),this.lowerBound=Math.min(this.lowerBound,this.childD.lowerBound),this.upperBound=Math.max(this.upperBound,this.childD.upperBound))}}function ya(t){var e,n;if(!t)throw new Error("data is required");if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Error("data must be scalar field, i.e. array of arrays");if(t.length<2)throw new Error("data must contain at least two rows");if((n=t[0].length)<2)throw new Error("data must contain at least two columns");for(e=1;e=e||t[s][r-1]>=e){n=!1;break}if(n&&(t[i-1][0]>=e||t[i-1][r-1]>=e)&&(n=!1),n)for(o=0;o=e||t[i-1][o]>e){n=!1;break}return n}(t,n.threshold)&&(n.linearRing?_.push([[0,0],[0,x],[E,x],[E,0],[0,0]]):_.push([[0,0],[0,x],[E,x],[E,0]])),e.forEach((function(t,N){t.forEach((function(t,S){for(r=null,i=0;i<4;i++)if(r=k[i],"object"===m(t.edges[r])){for(a=[],o=t.edges[r],u=r,l=N,h=S,c=!1,f=[N+o.path[0][0],S+o.path[0][1]],a.push(f);!c&&"object"===m((s=e[l][h]).edges[u]);)if(o=s.edges[u],delete s.edges[u],(g=o.path[1])[0]+=l,g[1]+=h,a.push(g),u=o.move.enter,l+=o.move.x,h+=o.move.y,void 0===e[l]||void 0===e[l][h]){if(!n.linearRing)break;if(p=0,v=0,l===E?(l--,p=0):l<0?(l++,p=2):h===x?(h--,p=3):h<0&&(h++,p=1),l===N&&h===S&&p===I[r]){c=!0,u=r;break}for(;;){if(d=!1,v>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[l]&&void 0!==e[l][h]&&(s=e[l][h],y=k[p],"object"===m(s.edges[y]))){o=s.edges[y],a.push(pa(l,h,p,o.path)),u=y,d=!0;break}if(d)break;if(a.push(va(l,h,p)),h+=w[p],void 0!==e[l+=b[p]]&&void 0!==e[l][h]||(0===p&&h<0||1===p&&l<0||2===p&&h===x||3===p&&l===E)&&(l-=b[p],h-=w[p],p=(p+1)%4,v++),l===N&&h===S&&p===I[r]){c=!0,u=r;break}}}!n.linearRing||a[a.length-1][0]===f[0]&&a[a.length-1][1]===f[1]||a.push(f),_.push(a)}}))})),_}(h,c,r)}a?g.push(f):g=f,"function"==typeof r.successCallback&&r.successCallback(g,t)})),g}function _a(t,e,n,r){var i,o,s,a,u,l,h=0,c=t[n+1][e],f=t[n+1][e+1],g=t[n][e+1],p=t[n][e],v=r.threshold;if(!(isNaN(p)||isNaN(g)||isNaN(f)||isNaN(c))){switch(h|=c>=v?8:0,h|=f>=v?4:0,h|=g>=v?2:0,l={cval:h=+(h|=p>=v?1:0),polygons:[],edges:{},x0:p,x1:g,x2:f,x3:c},h){case 0:r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,0]]);break;case 15:break;case 14:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.left={path:[[0,i],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[a,0]]);break;case 13:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[a,0],[1,o],[1,0]]);break;case 11:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[1,o],[s,1],[1,1]]);break;case 7:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[s,1],[0,i],[0,1]]);break;case 1:i=r.interpolate(p,c,v),a=r.interpolate(p,g,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[a,0],[0,i],[0,1],[1,1],[1,0]]);break;case 2:a=r.interpolate(p,g,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[1,1],[1,o],[a,0]]);break;case 4:o=r.interpolate(g,f,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[1,o],[1,0]]);break;case 8:i=r.interpolate(p,c,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[s,1],[1,1],[1,0]]);break;case 12:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.left={path:[[0,i],[1,o]],move:{x:1,y:0,enter:"left"}}),r.polygons&&l.polygons.push([[0,0],[0,i],[1,o],[1,0]]);break;case 9:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.bottom={path:[[a,0],[s,1]],move:{x:0,y:1,enter:"bottom"}}),r.polygons&&l.polygons.push([[a,0],[s,1],[1,1],[1,0]]);break;case 3:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),r.polygons_full&&(l.edges.right={path:[[1,o],[0,i]],move:{x:-1,y:0,enter:"right"}}),r.polygons&&l.polygons.push([[0,i],[0,1],[1,1],[1,o]]);break;case 6:a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),r.polygons_full&&(l.edges.top={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"top"}}),r.polygons&&l.polygons.push([[0,0],[0,1],[s,1],[a,0]]);break;case 10:i=r.interpolate(p,c,v),o=r.interpolate(g,f,v),a=r.interpolate(p,g,v),s=r.interpolate(c,f,v),u=(p+g+f+c)/4,r.polygons_full&&(uf&&(v>h&&ph&&vu&&(u=d)}var y=[];if(a&&u0&&Math.abs(x-n[_-1][0])>f){var E=parseFloat(n[_-1][0]),k=parseFloat(n[_-1][1]),b=parseFloat(n[_][0]),w=parseFloat(n[_][1]);if(E>-180&&E-180&&n[_-1][0]h&&E<180&&-180===b&&_+1h&&n[_-1][0]<180){m.push([180,n[_][1]]),_++,m.push([n[_][0],n[_][1]]);continue}if(Eh){var I=E;E=b,b=I;var N=k;k=w,w=N}if(E>h&&b=180&&Eh?180:-180,M]),(m=[]).push([n[_-1][0]>h?-180:180,M]),y.push(m)}else m=[],y.push(m);m.push([x,n[_][1]])}else m.push([n[_][0],n[_][1]])}}else{var L=[];y.push(L);for(var P=0;Pe||this.upperBound=e)&&r.push({x:this.x,y:this.y})),r},da.prototype.cellsBelowThreshold=function(t,e){var n=[];return e=void 0===e||e,this.lowerBound>t||(this.childA||this.childB||this.childC||this.childD?(this.childA&&(n=n.concat(this.childA.cellsBelowThreshold(t,e))),this.childB&&(n=n.concat(this.childB.cellsBelowThreshold(t,e))),this.childD&&(n=n.concat(this.childD.cellsBelowThreshold(t,e))),this.childC&&(n=n.concat(this.childC.cellsBelowThreshold(t,e)))):(e||this.upperBound>=t)&&n.push({x:this.x,y:this.y})),n};var xa={square:function(t,e,n,r,i,o){o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,0]])},triangle_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,a],[s,0],[0,0]])},triangle_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[1,a],[1,0]])},triangle_tr:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[1,s],[a,1],[1,1]])},triangle_tl:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[s,1]])},tetragon_t:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[0,a]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,a],[0,1],[1,1],[1,s]])},tetragon_r:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[a,1],[1,1],[1,0]])},tetragon_b:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,0]])},tetragon_l:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[a,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[a,0]])},tetragon_bl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[a,0]])},tetragon_br:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate_b(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[1,l]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[1,l],[1,u],[a,0]])},tetragon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rb={path:[[1,l],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}}),o.polygons&&t.polygons.push([[1,l],[s,1],[a,1],[1,u]])},tetragon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(e,i,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[0,l]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[a,1],[0,l],[0,u],[s,1]])},tetragon_lr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[1,u],[1,l]])},tetragon_tb:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.tr={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}}),o.polygons&&t.polygons.push([[l,0],[s,1],[a,1],[u,0]])},pentagon_tr:function(t,e,n,r,i,o){var s=o.interpolate(i,r,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[s,1],[1,a]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[s,1],[1,a],[1,0]])},pentagon_tl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,0]])},pentagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,a],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[1,1],[1,a],[s,0]])},pentagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[a,0],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[1,1],[1,0],[a,0]])},pentagon_tr_rl:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rt"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[1,u],[1,l]])},pentagon_rb_bt:function(t,e,n,r,i,o){var s=o.interpolate(n,r,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,n,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.rt={path:[[1,s],[a,0]],move:{x:0,y:-1,enter:"tr"}},t.edges.bl={path:[[u,0],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[l,1],[1,1],[1,s],[a,0],[u,0]])},pentagon_bl_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[1,l],[1,0]])},pentagon_lt_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[l,0]])},pentagon_bl_tb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(e,n,o.minV,o.maxV),l=o.interpolate_a(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[l,0],[0,s]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[a,1],[u,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[0,s],[0,1],[a,1],[u,0],[l,0]])},pentagon_lt_rl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,i,o.minV,o.maxV),a=o.interpolate_b(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,i,o.minV,o.maxV);o.polygons_full&&(t.edges.lt={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,l],[0,s]],move:{x:-1,y:0,enter:"rb"}}),o.polygons&&t.polygons.push([[0,s],[0,a],[u,1],[1,1],[1,l]])},pentagon_tr_bt:function(t,e,n,r,i,o){var s=o.interpolate_a(i,r,o.minV,o.maxV),a=o.interpolate_b(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[l,0],[s,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,1],[a,1],[1,u],[1,0],[l,0]])},pentagon_rb_lr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_b(n,r,o.minV,o.maxV),u=o.interpolate_a(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[1,a]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[1,a],[1,u],[l,0]])},hexagon_lt_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate_a(i,r,o.minV,o.maxV),u=o.interpolate_b(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[u,1],[1,l],[1,0]])},hexagon_bl_lt:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"br"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[1,1],[1,0]])},hexagon_bl_rb:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.rt={path:[[1,l],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[1,1],[1,l],[a,0]])},hexagon_tr_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate_b(n,r,o.minV,o.maxV),l=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.tl={path:[[a,1],[1,u]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,l],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,1],[a,1],[1,u],[1,l],[s,0]])},hexagon_lt_rb:function(t,e,n,r,i,o){var s=o.interpolate(e,i,o.minV,o.maxV),a=o.interpolate(i,r,o.minV,o.maxV),u=o.interpolate(n,r,o.minV,o.maxV),l=o.interpolate(e,n,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,s],[a,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,u],[l,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,s],[a,1],[1,1],[1,u],[l,0]])},hexagon_bl_tr:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate(i,r,o.minV,o.maxV),l=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[u,1],[1,l]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,1],[u,1],[1,l],[1,0]])},heptagon_tr:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"br"}},t.edges.rt={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[1,1],[1,c],[a,0]])},heptagon_bl:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate(e,i,o.minV,o.maxV),u=o.interpolate_a(i,r,o.minV,o.maxV),l=o.interpolate_b(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.lb={path:[[0,a],[u,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[s,0]],move:{x:0,y:-1,enter:"tl"}}),o.polygons&&t.polygons.push([[0,0],[0,a],[u,1],[l,1],[1,h],[1,c],[s,0]])},heptagon_tl:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate(e,i,o.minV,o.maxV),l=o.interpolate(i,r,o.minV,o.maxV),h=o.interpolate_b(n,r,o.minV,o.maxV),c=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rt"}},t.edges.tl={path:[[l,1],[1,h]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,c],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,1],[l,1],[1,h],[1,c],[a,0]])},heptagon_br:function(t,e,n,r,i,o){var s=o.interpolate(e,n,o.minV,o.maxV),a=o.interpolate_a(e,i,o.minV,o.maxV),u=o.interpolate_b(e,i,o.minV,o.maxV),l=o.interpolate_a(i,r,o.minV,o.maxV),h=o.interpolate_b(i,r,o.minV,o.maxV),c=o.interpolate(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.br={path:[[s,0],[0,a]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,u],[l,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[h,1],[1,c]],move:{x:1,y:0,enter:"lb"}}),o.polygons&&t.polygons.push([[s,0],[0,a],[0,u],[l,1],[h,1],[1,c],[1,0]])},octagon:function(t,e,n,r,i,o){var s=o.interpolate_a(e,n,o.minV,o.maxV),a=o.interpolate_b(e,n,o.minV,o.maxV),u=o.interpolate_a(e,i,o.minV,o.maxV),l=o.interpolate_b(e,i,o.minV,o.maxV),h=o.interpolate_a(i,r,o.minV,o.maxV),c=o.interpolate_b(i,r,o.minV,o.maxV),f=o.interpolate_b(n,r,o.minV,o.maxV),g=o.interpolate_a(n,r,o.minV,o.maxV);o.polygons_full&&(t.edges.bl={path:[[s,0],[0,u]],move:{x:-1,y:0,enter:"rb"}},t.edges.lt={path:[[0,l],[h,1]],move:{x:0,y:1,enter:"bl"}},t.edges.tr={path:[[c,1],[1,f]],move:{x:1,y:0,enter:"lt"}},t.edges.rb={path:[[1,g],[a,0]],move:{x:0,y:-1,enter:"tr"}}),o.polygons&&t.polygons.push([[s,0],[0,u],[0,l],[h,1],[c,1],[1,f],[1,g],[a,0]])}};function Ea(t,e,n,r){var i,o,s,a=!1,u=null,l=null,h=null,c=null,f=!1,g=[],p=[],v=[];if(!t)throw new Error("data is required");if(null==e)throw new Error("lowerBound is required");if(null==n)throw new Error("bandWidth is required");if(s=function(t){var e,n,r,i,o;for(i=new fa,t=t||{},o=Object.keys(i),e=0;en||t[a][i-1]n){r=!1;break}if(r&&(t[o-1][0]n||t[o-1][i-1]n)&&(r=!1),r)for(s=0;sn||t[o-1][s]n){r=!1;break}return r}(t,n.minV,n.maxV)&&(n.linearRing?x.push([[0,0],[0,E],[k,E],[k,0],[0,0]]):x.push([[0,0],[0,E],[k,E],[k,0]])),e.forEach((function(t,M){t.forEach((function(t,L){for(r=null,o=0;o<8;o++)if(r=N[o],"object"===m(t.edges[r])){for(i=[],s=t.edges[r],l=r,h=M,c=L,f=!1,g=[M+s.path[0][0],L+s.path[0][1]],i.push(g);!f&&"object"===m((p=e[h][c]).edges[l]);)if(s=p.edges[l],delete p.edges[l],(y=s.path[1])[0]+=h,y[1]+=c,i.push(y),l=s.move.enter,h+=s.move.x,c+=s.move.y,void 0===e[h]||void 0===e[h][c]){if(v=0,d=0,h===k)h--,v=0;else if(h<0)h++,v=2;else if(c===E)c--,v=3;else{if(!(c<0))throw new Error("Left the grid somewhere in the interior!");c++,v=1}if(h===M&&c===L&&v===S[r]){f=!0,l=r;break}for(;;){if(_=!1,d>4)throw new Error("Direction change counter overflow! This should never happen!");if(void 0!==e[h]&&void 0!==e[h][c])for(p=e[h][c],a=0;ao?2:sf?128:64,s|=uf?32:16,s|=lf?8:4,o=0,i={cval:s=+(s|=hf?2:1),polygons:[],edges:{},x0:h,x1:l,x2:u,x3:a,x:e,y:n},s){case 85:xa.square(i,h,l,u,a,r);case 0:case 170:break;case 169:xa.triangle_bl(i,h,l,u,a,r);break;case 166:xa.triangle_br(i,h,l,u,a,r);break;case 154:xa.triangle_tr(i,h,l,u,a,r);break;case 106:xa.triangle_tl(i,h,l,u,a,r);break;case 1:xa.triangle_bl(i,h,l,u,a,r);break;case 4:xa.triangle_br(i,h,l,u,a,r);break;case 16:xa.triangle_tr(i,h,l,u,a,r);break;case 64:xa.triangle_tl(i,h,l,u,a,r);break;case 168:xa.tetragon_bl(i,h,l,u,a,r);break;case 162:xa.tetragon_br(i,h,l,u,a,r);break;case 138:xa.tetragon_tr(i,h,l,u,a,r);break;case 42:xa.tetragon_tl(i,h,l,u,a,r);break;case 2:xa.tetragon_bl(i,h,l,u,a,r);break;case 8:xa.tetragon_br(i,h,l,u,a,r);break;case 32:xa.tetragon_tr(i,h,l,u,a,r);break;case 128:xa.tetragon_tl(i,h,l,u,a,r);break;case 5:xa.tetragon_b(i,h,l,u,a,r);break;case 20:xa.tetragon_r(i,h,l,u,a,r);break;case 80:xa.tetragon_t(i,h,l,u,a,r);break;case 65:xa.tetragon_l(i,h,l,u,a,r);break;case 165:xa.tetragon_b(i,h,l,u,a,r);break;case 150:xa.tetragon_r(i,h,l,u,a,r);break;case 90:xa.tetragon_t(i,h,l,u,a,r);break;case 105:xa.tetragon_l(i,h,l,u,a,r);break;case 160:xa.tetragon_lr(i,h,l,u,a,r);break;case 130:xa.tetragon_tb(i,h,l,u,a,r);break;case 10:xa.tetragon_lr(i,h,l,u,a,r);break;case 40:xa.tetragon_tb(i,h,l,u,a,r);break;case 101:xa.pentagon_tr(i,h,l,u,a,r);break;case 149:xa.pentagon_tl(i,h,l,u,a,r);break;case 86:xa.pentagon_bl(i,h,l,u,a,r);break;case 89:xa.pentagon_br(i,h,l,u,a,r);break;case 69:xa.pentagon_tr(i,h,l,u,a,r);break;case 21:xa.pentagon_tl(i,h,l,u,a,r);break;case 84:xa.pentagon_bl(i,h,l,u,a,r);break;case 81:xa.pentagon_br(i,h,l,u,a,r);break;case 96:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 24:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 6:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 129:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 74:xa.pentagon_tr_rl(i,h,l,u,a,r);break;case 146:xa.pentagon_rb_bt(i,h,l,u,a,r);break;case 164:xa.pentagon_bl_lr(i,h,l,u,a,r);break;case 41:xa.pentagon_lt_tb(i,h,l,u,a,r);break;case 66:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 144:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 36:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 9:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 104:xa.pentagon_bl_tb(i,h,l,u,a,r);break;case 26:xa.pentagon_lt_rl(i,h,l,u,a,r);break;case 134:xa.pentagon_tr_bt(i,h,l,u,a,r);break;case 161:xa.pentagon_rb_lr(i,h,l,u,a,r);break;case 37:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 148:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 82:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 73:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 133:xa.hexagon_lt_tr(i,h,l,u,a,r);break;case 22:xa.hexagon_bl_lt(i,h,l,u,a,r);break;case 88:xa.hexagon_bl_rb(i,h,l,u,a,r);break;case 97:xa.hexagon_tr_rb(i,h,l,u,a,r);break;case 145:case 25:xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 70:case 100:xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 17:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 68:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 153:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.triangle_tr(i,h,l,u,a,r)):xa.hexagon_lt_rb(i,h,l,u,a,r);break;case 102:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.triangle_br(i,h,l,u,a,r)):xa.hexagon_bl_tr(i,h,l,u,a,r);break;case 152:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 137:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 98:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 38:2===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 18:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tr(i,h,l,u,a,r),xa.tetragon_bl(i,h,l,u,a,r)):xa.heptagon_tr(i,h,l,u,a,r);break;case 33:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):xa.heptagon_bl(i,h,l,u,a,r);break;case 72:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):xa.heptagon_tl(i,h,l,u,a,r);break;case 132:0===(o=ka(h,l,u,a,c,f))?(xa.triangle_br(i,h,l,u,a,r),xa.tetragon_tl(i,h,l,u,a,r)):xa.heptagon_br(i,h,l,u,a,r);break;case 136:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r));break;case 34:0===(o=ka(h,l,u,a,c,f))?(xa.tetragon_bl(i,h,l,u,a,r),xa.tetragon_tr(i,h,l,u,a,r)):1===o?xa.octagon(i,h,l,u,a,r):(xa.tetragon_tl(i,h,l,u,a,r),xa.tetragon_br(i,h,l,u,a,r))}return i}}var wa=Object.defineProperty,Ia=Object.getOwnPropertySymbols,Na=Object.prototype.hasOwnProperty,Sa=Object.prototype.propertyIsEnumerable,Ma=function(t,e,n){return e in t?wa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},La=function(t,e){for(var n in e||(e={}))Na.call(e,n)&&Ma(t,n,e[n]);if(Ia){var r,i=a(Ia(e));try{for(i.s();!(r=i.n()).done;){n=r.value;Sa.call(e,n)&&Ma(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t};function Pa(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.zProperty||"elevation",r=e.flip,i=e.flags;nt(t,"Point","input must contain Points");for(var o=function(t,e){var n={};vt(t,(function(t){var e=Q(t)[1];n[e]||(n[e]=[]),n[e].push(t)}));var r=Object.keys(n).map((function(t){return n[t].sort((function(t,e){return Q(t)[0]-Q(e)[0]}))})),i=r.sort((function(t,n){return e?Q(t[0])[1]-Q(n[0])[1]:Q(n[0])[1]-Q(t[0])[1]}));return i}(t,r),s=[],a=0;a=0&&l<=1&&(f.onLine1=!0),h>=0&&h<=1&&(f.onLine2=!0),!(!f.onLine1||!f.onLine2)&&[f.x,f.y])}function za(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return bt(t,(function(t,n){var r=n.geometry.coordinates;return t+ut(r[0],r[1],e)}),0)}function ja(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=i.steps||64,s=Xa(n),a=Xa(r),u=Array.isArray(t)||"Feature"!==t.type?{}:t.properties;if(s===a)return L(Ri(t,e,i).geometry.coordinates[0],u);for(var l=s,h=s=h&&c===i.length-1);c++){if(h>e&&0===o.length){if(!(s=e-h))return o.push(i[c]),L(o);a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates)}if(h>=n)return(s=n-h)?(a=st(i[c],i[c-1])-180,u=at(i[c],s,a,r),o.push(u.geometry.coordinates),L(o)):(o.push(i[c]),L(o));if(h>=e&&o.push(i[c]),c===i.length-1)return L(o);h+=ut(i[c],i[c+1],r)}if(h0){var a=r[e-1],u=Wa(n,a);!1!==u&&(a[1]=u,n[0]=u),s.push(a[0]),e===o.length-2&&(s.push(n[0]),s.push(n[1]))}2===o.length&&(s.push(n[0]),s.push(n[1]))}var l,h,c,f,g,p,v,d})),L(s,t.properties)}function Ka(t){var e=t[0],n=t[1],r=t[2],i=t[3];if(ut(t.slice(0,2),[r,n])>=ut(t.slice(0,2),[e,i])){var o=(n+i)/2;return[e,o-(r-e)/2,r,o+(r-e)/2]}var s=(e+r)/2;return[s-(i-n)/2,n,s+(i-n)/2,i]}function Qa(t,e){if(!Z(e=null!=e?e:{}))throw new Error("options is invalid");var n=e.precision,r=e.coordinates,i=e.mutate;if(n=null==n||isNaN(n)?6:n,r=null==r||isNaN(r)?3:r,!t)throw new Error(" is required");if("number"!=typeof n)throw new Error(" must be a number");if("number"!=typeof r)throw new Error(" must be a number");!1!==i&&void 0!==i||(t=JSON.parse(JSON.stringify(t)));var o=Math.pow(10,n);return ct(t,(function(t){!function(t,e,n){t.length>n&&t.splice(n,t.length);for(var r=0;r1&&n.push(L(l)),C(n)}function eu(t,e){if(!e.features.length)throw new Error("lines must contain features");if(1===e.features.length)return e.features[0];var n,r=1/0;return vt(e,(function(e){var i=fn(e,t).properties.dist;iu?(a.unshift(t),u=e):a.push(t)}else a.push(t)})),S(a,e);default:throw new Error("geometry type "+s+" is not supported")}}function iu(t){var e=t[0],n=e[0],r=e[1],i=t[t.length-1],o=i[0],s=i[1];return n===o&&r===s||t.push(e),t}function ou(t){return R(t)}function su(t){var e=[[[180,90],[-180,90],[-180,-90],[180,-90],[180,90]]];return t&&(e="Feature"===t.type?t.geometry.coordinates:t.coordinates),S(e)}function au(t){var e,n=0,r=a(t);try{for(r.s();!(e=r.n()).done;){n+=e.value}}catch(t){r.e(t)}finally{r.f()}return n/t.length}var uu=Object.defineProperty,lu=Object.defineProperties,hu=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,fu=Object.prototype.hasOwnProperty,gu=Object.prototype.propertyIsEnumerable,pu=function(t,e,n){return e in t?uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n},vu=function(t,e){for(var n in e||(e={}))fu.call(e,n)&&pu(t,n,e[n]);if(cu){var r,i=a(cu(e));try{for(i.s();!(r=i.n()).done;){n=r.value;gu.call(e,n)&&pu(t,n,e[n])}}catch(t){i.e(t)}finally{i.f()}}return t},du=function(t,e){return lu(t,hu(e))};function yu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)throw new Error("targetPoint is required");if(!e)throw new Error("points is required");var r=1/0,i=0;vt(e,(function(e,o){var s=ut(t,e,n);s2&&void 0!==arguments[2]?arguments[2]:{},o=null!=(n=i.method)?n:"geodesic",s=null!=(r=i.units)?r:"kilometers";if(!t)throw new Error("pt is required");if(Array.isArray(t)?t=I(t):"Point"===t.type?t=b(t):et(t,"Point","point"),!e)throw new Error("line is required");Array.isArray(e)?e=L(e):"LineString"===e.type?e=b(e):et(e,"LineString","line");var a=1/0,u=t.geometry.coordinates;return kt(e,(function(t){if(t){var e=t.geometry.coordinates[0],n=t.geometry.coordinates[1],r=function(t,e,n,r){if("geodesic"===r.method){return fn(L([e,n]).geometry,t,{units:"degrees"}).properties.dist}var i=[n[0]-e[0],n[1]-e[1]],o=[t[0]-e[0],t[1]-e[1]],s=_u(o,i);if(s<=0)return Ys(t,e,{units:"degrees"});var a=_u(i,i);if(a<=s)return Ys(t,n,{units:"degrees"});var u=s/a,l=[e[0]+u*i[0],e[1]+u*i[1]];return Ys(t,l,{units:"degrees"})}(u,e,n,{method:o});r0)-(t<0)||+t}(r*(n[1]-e[1])-o*i)}function Lu(t,e){return e.geometry.coordinates[0].every((function(e){return zt(I(e),t)}))}var Pu=function(){return s((function t(e){i(this,t),this.id=t.buildId(e),this.coordinates=e,this.innerEdges=[],this.outerEdges=[],this.outerEdgesSorted=!1}),[{key:"removeInnerEdge",value:function(t){this.innerEdges=this.innerEdges.filter((function(e){return e.from.id!==t.from.id}))}},{key:"removeOuterEdge",value:function(t){this.outerEdges=this.outerEdges.filter((function(e){return e.to.id!==t.to.id}))}},{key:"addOuterEdge",value:function(t){this.outerEdges.push(t),this.outerEdgesSorted=!1}},{key:"sortOuterEdges",value:function(){var t=this;this.outerEdgesSorted||(this.outerEdges.sort((function(e,n){var r=e.to,i=n.to;if(r.coordinates[0]-t.coordinates[0]>=0&&i.coordinates[0]-t.coordinates[0]<0)return 1;if(r.coordinates[0]-t.coordinates[0]<0&&i.coordinates[0]-t.coordinates[0]>=0)return-1;if(r.coordinates[0]-t.coordinates[0]==0&&i.coordinates[0]-t.coordinates[0]==0)return r.coordinates[1]-t.coordinates[1]>=0||i.coordinates[1]-t.coordinates[1]>=0?r.coordinates[1]-i.coordinates[1]:i.coordinates[1]-r.coordinates[1];var o=Mu(t.coordinates,r.coordinates,i.coordinates);return o<0?1:o>0?-1:Math.pow(r.coordinates[0]-t.coordinates[0],2)+Math.pow(r.coordinates[1]-t.coordinates[1],2)-(Math.pow(i.coordinates[0]-t.coordinates[0],2)+Math.pow(i.coordinates[1]-t.coordinates[1],2))})),this.outerEdgesSorted=!0)}},{key:"getOuterEdges",value:function(){return this.sortOuterEdges(),this.outerEdges}},{key:"getOuterEdge",value:function(t){return this.sortOuterEdges(),this.outerEdges[t]}},{key:"addInnerEdge",value:function(t){this.innerEdges.push(t)}}],[{key:"buildId",value:function(t){return t.join(",")}}])}(),Cu=function(){function t(e,n){i(this,t),this.from=e,this.to=n,this.next=void 0,this.label=void 0,this.symetric=void 0,this.ring=void 0,this.from.addOuterEdge(this),this.to.addInnerEdge(this)}return s(t,[{key:"getSymetric",value:function(){return this.symetric||(this.symetric=new t(this.to,this.from),this.symetric.symetric=this),this.symetric}},{key:"deleteEdge",value:function(){this.from.removeOuterEdge(this),this.to.removeInnerEdge(this)}},{key:"isEqual",value:function(t){return this.from.id===t.from.id&&this.to.id===t.to.id}},{key:"toString",value:function(){return"Edge { ".concat(this.from.id," -> ").concat(this.to.id," }")}},{key:"toLineString",value:function(){return L([this.from.coordinates,this.to.coordinates])}},{key:"compareTo",value:function(t){return Mu(t.from.coordinates,t.to.coordinates,this.to.coordinates)}}])}(),Tu=function(){return s((function t(){i(this,t),this.edges=[],this.polygon=void 0,this.envelope=void 0}),[{key:"push",value:function(t){this.edges.push(t),this.polygon=this.envelope=void 0}},{key:"get",value:function(t){return this.edges[t]}},{key:"length",get:function(){return this.edges.length}},{key:"forEach",value:function(t){this.edges.forEach(t)}},{key:"map",value:function(t){return this.edges.map(t)}},{key:"some",value:function(t){return this.edges.some(t)}},{key:"isValid",value:function(){return!0}},{key:"isHole",value:function(){var t=this,e=this.edges.reduce((function(e,n,r){return n.from.coordinates[1]>t.edges[e].from.coordinates[1]&&(e=r),e}),0),n=(0===e?this.length:e)-1,r=(e+1)%this.length,i=Mu(this.edges[n].from.coordinates,this.edges[e].from.coordinates,this.edges[r].from.coordinates);return 0===i?this.edges[n].from.coordinates[0]>this.edges[r].from.coordinates[0]:i>0}},{key:"toMultiPoint",value:function(){return O(this.edges.map((function(t){return t.from.coordinates})))}},{key:"toPolygon",value:function(){if(this.polygon)return this.polygon;var t=this.edges.map((function(t){return t.from.coordinates}));return t.push(this.edges[0].from.coordinates),this.polygon=S([t])}},{key:"getEnvelope",value:function(){return this.envelope?this.envelope:this.envelope=Us(this.toPolygon())}},{key:"inside",value:function(t){return zt(t,this.toPolygon())}}],[{key:"findEdgeRingContaining",value:function(t,e){var n,r,i=t.getEnvelope();return e.forEach((function(e){var o,s,u,l,h,c,f=e.getEnvelope();if((r&&(n=r.getEnvelope()),s=i,u=(o=f).geometry.coordinates[0].map((function(t){return t[0]})),l=o.geometry.coordinates[0].map((function(t){return t[1]})),h=s.geometry.coordinates[0].map((function(t){return t[0]})),c=s.geometry.coordinates[0].map((function(t){return t[1]})),Math.max.apply(null,u)!==Math.max.apply(null,h)||Math.max.apply(null,l)!==Math.max.apply(null,c)||Math.min.apply(null,u)!==Math.min.apply(null,h)||Math.min.apply(null,l)!==Math.min.apply(null,c))&&Lu(f,i)){var g,p,v=a(t.map((function(t){return t.from.coordinates})));try{var d=function(){var t=p.value;e.some((function(e){return n=t,r=e.from.coordinates,n[0]===r[0]&&n[1]===r[1];var n,r}))||(g=t)};for(v.s();!(p=v.n()).done;)d()}catch(t){v.e(t)}finally{v.f()}g&&e.inside(I(g))&&(r&&!Lu(n,f)||(r=e))}})),r}}])}();var Ou=function(){function t(){i(this,t),this.edges=[],this.nodes={}}return s(t,[{key:"getNode",value:function(t){var e=Pu.buildId(t),n=this.nodes[e];return n||(n=this.nodes[e]=new Pu(t)),n}},{key:"addEdge",value:function(t,e){var n=new Cu(t,e),r=n.getSymetric();this.edges.push(n),this.edges.push(r)}},{key:"deleteDangles",value:function(){var t=this;Object.keys(this.nodes).map((function(e){return t.nodes[e]})).forEach((function(e){return t._removeIfDangle(e)}))}},{key:"_removeIfDangle",value:function(t){var e=this;if(t.innerEdges.length<=1){var n=t.getOuterEdges().map((function(t){return t.to}));this.removeNode(t),n.forEach((function(t){return e._removeIfDangle(t)}))}}},{key:"deleteCutEdges",value:function(){var t=this;this._computeNextCWEdges(),this._findLabeledEdgeRings(),this.edges.forEach((function(e){e.label===e.symetric.label&&(t.removeEdge(e.symetric),t.removeEdge(e))}))}},{key:"_computeNextCWEdges",value:function(t){var e=this;void 0===t?Object.keys(this.nodes).forEach((function(t){return e._computeNextCWEdges(e.nodes[t])})):t.getOuterEdges().forEach((function(e,n){t.getOuterEdge((0===n?t.getOuterEdges().length:n)-1).symetric.next=e}))}},{key:"_computeNextCCWEdges",value:function(t,e){for(var n,r,i=t.getOuterEdges(),o=i.length-1;o>=0;--o){var s=i[o],a=s.symetric,u=void 0,l=void 0;s.label===e&&(u=s),a.label===e&&(l=a),u&&l&&(l&&(r=l),u&&(r&&(r.next=u,r=void 0),n||(n=u)))}r&&(r.next=n)}},{key:"_findLabeledEdgeRings",value:function(){var t=[],e=0;return this.edges.forEach((function(n){if(!(n.label>=0)){t.push(n);var r=n;do{r.label=e,r=r.next}while(!n.isEqual(r));e++}})),t}},{key:"getEdgeRings",value:function(){var t=this;this._computeNextCWEdges(),this.edges.forEach((function(t){t.label=void 0})),this._findLabeledEdgeRings().forEach((function(e){t._findIntersectionNodes(e).forEach((function(n){t._computeNextCCWEdges(n,e.label)}))}));var e=[];return this.edges.forEach((function(n){n.ring||e.push(t._findEdgeRing(n))})),e}},{key:"_findIntersectionNodes",value:function(t){var e=[],n=t,r=function(){var r=0;n.from.getOuterEdges().forEach((function(e){e.label===t.label&&++r})),r>1&&e.push(n.from),n=n.next};do{r()}while(!t.isEqual(n));return e}},{key:"_findEdgeRing",value:function(t){var e=t,n=new Tu;do{n.push(e),e.ring=n,e=e.next}while(!t.isEqual(e));return n}},{key:"removeNode",value:function(t){var e=this;t.getOuterEdges().forEach((function(t){return e.removeEdge(t)})),t.innerEdges.forEach((function(t){return e.removeEdge(t)})),delete this.nodes[t.id]}},{key:"removeEdge",value:function(t){this.edges=this.edges.filter((function(e){return!e.isEqual(t)})),t.deleteEdge()}}],[{key:"fromGeoJson",value:function(e){!function(t){if(!t)throw new Error("No geojson passed");if("FeatureCollection"!==t.type&&"GeometryCollection"!==t.type&&"MultiLineString"!==t.type&&"LineString"!==t.type&&"Feature"!==t.type)throw new Error("Invalid input type '".concat(t.type,"'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature"))}(e);var n=new t;return xt(e,(function(t){et(t,"LineString","Graph::fromGeoJson"),ft(t,(function(t,e){if(t){var r=n.getNode(t),i=n.getNode(e);n.addEdge(r,i)}return e}))})),n}}])}();function Ru(t,e){var n,r;ct(t,(function(t,i,o,s,a){if(r!==a)e.push([]);else{var u=n[0],l=n[1],h=t[0],c=t[1];e[a].push([.75*u+.25*h,.75*l+.25*c]),e[a].push([.25*u+.75*h,.25*l+.75*c])}n=t,r=a}),!1),e.forEach((function(t){t.push(t[0])}))}function Au(t,e){var n,r,i;ct(t,(function(t,o,s,a,u){if(r!==a)e.push([[]]);else if(i!==u)e[a].push([]);else{var l=n[0],h=n[1],c=t[0],f=t[1];e[a][u].push([.75*l+.25*c,.75*h+.25*f]),e[a][u].push([.25*l+.75*c,.25*h+.75*f])}n=t,r=a,i=u}),!1),e.forEach((function(t){t.forEach((function(t){t.push(t[0])}))}))}function Du(t,e,n,r,i){for(var o=0;o0?qu(e,s,r)<0||(r=s):n>0&&u<=0&&(Fu(e,s,i)||(i=s)),n=u}return[r,i]}function Fu(t,e,n){return qu(t,e,n)>0}function qu(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(n[0]-t[0])*(e[1]-t[1])}function Vu(t){return Bu(t,"mercator",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Gu(t){return Bu(t,"wgs84",arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}function Bu(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=(n=n||{}).mutate;if(!t)throw new Error("geojson is required");return Array.isArray(t)&&U(t[0])?t="mercator"===e?Yu(t):zu(t):(!0!==r&&(t=Ai(t)),ct(t,(function(t){var n="mercator"===e?Yu(t):zu(t);t[0]=n[0],t[1]=n[1]}))),t}function Yu(t){var e=Math.PI/180,n=6378137,r=20037508.342789244,i=Math.abs(t[0])<=180?t[0]:t[0]-360*function(t){return t<0?-1:t>0?1:0}(t[0]),o=[n*i*e,n*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return o[0]>r&&(o[0]=r),o[0]<-r&&(o[0]=-r),o[1]>r&&(o[1]=r),o[1]<-r&&(o[1]=-r),o}function zu(t){var e=180/Math.PI,n=6378137;return[t[0]*e/n,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/n)))*e]}var ju=Object.freeze({__proto__:null,toMercator:Vu,toWgs84:Gu});var Xu={20:1.07275,15:1.13795,10:1.22385,5:1.3581,2:1.51743,1:1.62762};function Uu(t,e){return e[0]<=t[0]&&e[1]<=t[1]&&e[2]>=t[0]&&e[3]>=t[1]}function Zu(t){var e=[];return function t(n){return 0===n||1===n?1:e[n]>0?e[n]:e[n]=t(n-1)*n}(t)}function Hu(t){return Ju(t),Wu(t)}function Wu(t){return Array.isArray(t)?el(t):t&&t.bbox?el(t.bbox):[360*tl(),180*tl()]}function Ju(t){null!=t&&(Array.isArray(t)?H(t):null!=t.bbox&&H(t.bbox))}function Ku(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1);for(var n=[],r=0;r1&&void 0!==arguments[1]?arguments[1]:{};Ju(e.bbox),null==t&&(t=1),void 0!==e.bbox&&null!==e.bbox||(e.bbox=[-180,-90,180,90]),U(e.num_vertices)&&void 0!==e.num_vertices||(e.num_vertices=10),U(e.max_radial_length)&&void 0!==e.max_radial_length||(e.max_radial_length=10);var n=Math.abs(e.bbox[0]-e.bbox[2]),r=Math.abs(e.bbox[1]-e.bbox[3]),i=Math.min(n/2,r/2);if(e.max_radial_length>i)throw new Error("max_radial_length is greater than the radius of the bbox");for(var o=[e.bbox[0]+e.max_radial_length,e.bbox[1]+e.max_radial_length,e.bbox[2]-e.max_radial_length,e.bbox[3]-e.max_radial_length],s=[],a=function(){var t,n=[],r=d(Array(e.num_vertices+1)).map(Math.random);r.forEach((function(t,e,n){n[e]=e>0?t+n[e-1]:t})),r.forEach((function(t){t=2*t*Math.PI/r[r.length-1];var i=Math.random();n.push([i*(e.max_radial_length||10)*Math.sin(t),i*(e.max_radial_length||10)*Math.cos(t)])})),n[n.length-1]=n[0],n=n.reverse().map((t=Wu(o),function(e){return[e[0]+t[0],e[1]+t[1]]})),s.push(S([n]))},u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox;Ju(n);var r=e.num_vertices,i=e.max_length,o=e.max_rotation;null==t&&(t=1),(!U(r)||void 0===r||r<2)&&(r=10),U(i)&&void 0!==i||(i=1e-4),U(o)&&void 0!==o||(o=Math.PI/8);for(var s=[],a=0;a0;){var l=a.pop();if(l===n)return ll(l);l.closed=!0;for(var h=t.neighbors(l),c=0,f=h.length;c1?(r=n[0],i=n[1]):a>0&&(r+=o*a,i+=s*a)}return(o=t[0]-r)*o+(s=t[1]-i)*s}function dl(t,e,n,r,i){for(var o,s=r,a=e+1;as&&(o=a,s=u)}s>r&&(o-e>1&&dl(t,e,o,r,i),i.push(t[o]),n-o>1&&dl(t,o,n,r,i))}function yl(t,e){var n=t.length-1,r=[t[0]];return dl(t,0,n,e,r),r.push(t[n]),r}function ml(t,e,n){if(t.length<=2)return t;var r=void 0!==e?e*e:1;return t=n?t:function(t,e){for(var n,r,i,o,s,a=t[0],u=[a],l=1,h=t.length;le&&(u.push(n),a=n);return a!==n&&u.push(n),u}(t,r),t=yl(t,r)}function _l(t,e,n){return t.map((function(t){if(t.length<4)throw new Error("invalid polygon");for(var r=e,i=ml(t,r,n);!xl(i);)i=ml(t,r-=.01*r,n);return i[i.length-1][0]===i[0][0]&&i[i.length-1][1]===i[0][1]||i.push(i[0]),i}))}function xl(t){return!(t.length<3)&&!(3===t.length&&t[2][0]===t[0][0]&&t[2][1]===t[0][1])}function El(t,e){return{x:t[0]-e[0],y:t[1]-e[1]}}cl.prototype.init=function(){this.dirtyNodes=[];for(var t=0;t0&&(this.content[0]=e,this.bubbleUp(0)),t},remove:function(t){var e=this.content.indexOf(t),n=this.content.pop();e!==this.content.length-1&&(this.content[e]=n,this.scoreFunction(n)0;){var n=(t+1>>1)-1,r=this.content[n];if(!(this.scoreFunction(e)80*i){o=a=t[0],s=h=t[1];for(var _=i;_a&&(a=c),g>h&&(h=g);p=0!==(p=Math.max(a-o,h-s))?32767/p:0}return r(y,m,i,o,s,p,0),m}function e(t,e,n,r,i){var o,s;if(i===I(t,e,n,r)>0)for(o=e;o=e;o-=r)s=k(o,t[o],t[o+1],s);return s&&d(s,s.next)&&(b(s),s=s.next),s}function n(t,e){if(!t)return t;e||(e=t);var n,r=t;do{if(n=!1,r.steiner||!d(r,r.next)&&0!==v(r.prev,r,r.next))r=r.next;else{if(b(r),(r=e=r.prev)===r.next)break;n=!0}}while(n||r!==e);return e}function r(t,e,u,l,h,f,g){if(t){!g&&f&&function(t,e,n,r){var i=t;do{0===i.z&&(i.z=c(i.x,i.y,e,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,n,r,i,o,s,a,u,l=1;do{for(n=t,t=null,o=null,s=0;n;){for(s++,r=n,a=0,e=0;e0||u>0&&r;)0!==a&&(0===u||!r||n.z<=r.z)?(i=n,n=n.nextZ,a--):(i=r,r=r.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;n=r}o.nextZ=null,l*=2}while(s>1)}(i)}(t,l,h,f);for(var p,v,d=t;t.prev!==t.next;)if(p=t.prev,v=t.next,f?o(t,l,h,f):i(t))e.push(p.i/u|0),e.push(t.i/u|0),e.push(v.i/u|0),b(t),t=v.next,d=v.next;else if((t=v)===d){g?1===g?r(t=s(n(t),e,u),e,u,l,h,f,2):2===g&&a(t,e,u,l,h,f):r(n(t),e,u,l,h,f,1);break}}}function i(t){var e=t.prev,n=t,r=t.next;if(v(e,n,r)>=0)return!1;for(var i=e.x,o=n.x,s=r.x,a=e.y,u=n.y,l=r.y,h=io?i>s?i:s:o>s?o:s,p=a>u?a>l?a:l:u>l?u:l,d=r.next;d!==e;){if(d.x>=h&&d.x<=f&&d.y>=c&&d.y<=p&&g(i,a,o,u,s,l,d.x,d.y)&&v(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function o(t,e,n,r){var i=t.prev,o=t,s=t.next;if(v(i,o,s)>=0)return!1;for(var a=i.x,u=o.x,l=s.x,h=i.y,f=o.y,p=s.y,d=au?a>l?a:l:u>l?u:l,_=h>f?h>p?h:p:f>p?f:p,x=c(d,y,e,n,r),E=c(m,_,e,n,r),k=t.prevZ,b=t.nextZ;k&&k.z>=x&&b&&b.z<=E;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;if(k=k.prevZ,b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;k&&k.z>=x;){if(k.x>=d&&k.x<=m&&k.y>=y&&k.y<=_&&k!==i&&k!==s&&g(a,h,u,f,l,p,k.x,k.y)&&v(k.prev,k,k.next)>=0)return!1;k=k.prevZ}for(;b&&b.z<=E;){if(b.x>=d&&b.x<=m&&b.y>=y&&b.y<=_&&b!==i&&b!==s&&g(a,h,u,f,l,p,b.x,b.y)&&v(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function s(t,e,r){var i=t;do{var o=i.prev,s=i.next.next;!d(o,s)&&y(o,i,i.next,s)&&x(o,s)&&x(s,o)&&(e.push(o.i/r|0),e.push(i.i/r|0),e.push(s.i/r|0),b(i),b(i.next),i=t=s),i=i.next}while(i!==t);return n(i)}function a(t,e,i,o,s,a){var u=t;do{for(var l=u.next.next;l!==u.prev;){if(u.i!==l.i&&p(u,l)){var h=E(u,l);return u=n(u,u.next),h=n(h,h.next),r(u,e,i,o,s,a,0),void r(h,e,i,o,s,a,0)}l=l.next}u=u.next}while(u!==t)}function u(t,e){return t.x-e.x}function l(t,e){var r=function(t,e){var n,r=e,i=t.x,o=t.y,s=-1/0;do{if(o<=r.y&&o>=r.next.y&&r.next.y!==r.y){var a=r.x+(o-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=i&&a>s&&(s=a,n=r.x=r.x&&r.x>=c&&i!==r.x&&g(on.x||r.x===n.x&&h(n,r)))&&(n=r,p=u)),r=r.next}while(r!==l);return n}(t,e);if(!r)return e;var i=E(r,t);return n(i,i.next),n(r,r.next)}function h(t,e){return v(t.prev,t,e.prev)<0&&v(e.next,t,t.next)<0}function c(t,e,n,r,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function f(t){var e=t,n=t;do{(e.x=(t-s)*(o-a)&&(t-s)*(r-a)>=(n-s)*(e-a)&&(n-s)*(o-a)>=(i-s)*(r-a)}function p(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&y(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(x(t,e)&&x(e,t)&&function(t,e){var n=t,r=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{n.y>o!=n.next.y>o&&n.next.y!==n.y&&i<(n.next.x-n.x)*(o-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==t);return r}(t,e)&&(v(t.prev,t,e.prev)||v(t,e.prev,e))||d(t,e)&&v(t.prev,t,t.next)>0&&v(e.prev,e,e.next)>0)}function v(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function d(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,n,r){var i=_(v(t,e,n)),o=_(v(t,e,r)),s=_(v(n,r,t)),a=_(v(n,r,e));return i!==o&&s!==a||(!(0!==i||!m(t,n,e))||(!(0!==o||!m(t,r,e))||(!(0!==s||!m(n,t,r))||!(0!==a||!m(n,e,r)))))}function m(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function _(t){return t>0?1:t<0?-1:0}function x(t,e){return v(t.prev,t,t.next)<0?v(t,e,t.next)>=0&&v(t,t.prev,e)>=0:v(t,e,t.prev)<0||v(t,t.next,e)<0}function E(t,e){var n=new w(t.i,t.x,t.y),r=new w(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,n.next=i,i.prev=n,r.next=n,n.prev=r,o.next=r,r.prev=o,r}function k(t,e,n,r){var i=new w(t,e,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function b(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 w(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function I(t,e,n,r){for(var i=0,o=e,s=n-r;o0&&(r+=t[i-1].length,n.holes.push(r))}return n},bl.exports}(),Il=mn(wl);function Nl(t){var e=function(t){for(var e=t[0][0].length,n={vertices:[],holes:[],dimensions:e},r=0,i=0;i0&&(r+=t[i-1].length,n.holes.push(r))}return n}(t),n=Il(e.vertices,e.holes,2),r=[],i=[];n.forEach((function(t,r){var o=n[r];i.push([e.vertices[2*o],e.vertices[2*o+1]])}));for(var o=0;o=1||u<=0||l>=1||l<=0))){var v=p,d=!o[v];d&&(o[v]=!0),e?i.push(e(p,t,n,h,c,u,s,a,f,g,l,d)):i.push(p)}}function v(t,e){var n,i,o,s,a=r[t][e],u=r[t][e+1];return a[0]f[e.isect].coord?-1:1}));for(l=[];x.length>0;){var I=x.pop(),N=I.isect,M=I.parent,L=I.winding,P=l.length,T=[f[N].coord],O=N;if(f[N].ringAndEdge1Walkable)var R=f[N].ringAndEdge1,A=f[N].nxtIsectAlongRingAndEdge1;else R=f[N].ringAndEdge2,A=f[N].nxtIsectAlongRingAndEdge2;for(;!Rl(f[N].coord,f[A].coord);){T.push(f[A].coord);var D=void 0;for(r=0;r1)for(e=0;e=0==e}function Ol(t){for(var e=0,n=0;n0)){if(o/=f,f<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=r-u,f||!(o<0)){if(o/=f,f<0){if(o>c)return;o>h&&(h=o)}else if(f>0){if(o0)){if(o/=g,g<0){if(o0){if(o>c)return;o>h&&(h=o)}if(o=i-l,g||!(o<0)){if(o/=g,g<0){if(o>c)return;o>h&&(h=o)}else if(g>0){if(o0||c<1)||(h>0&&(t[0]=[u+h*f,l+h*g]),c<1&&(t[1]=[u+c*f,l+c*g]),!0)}}}}}function Hl(t,e,n,r,i){var o=t[1];if(o)return!0;var s,a,u=t[0],l=t.left,h=t.right,c=l[0],f=l[1],g=h[0],p=h[1],v=(c+g)/2,d=(f+p)/2;if(p===f){if(v=r)return;if(c>g){if(u){if(u[1]>=i)return}else u=[v,n];o=[v,i]}else{if(u){if(u[1]1)if(c>g){if(u){if(u[1]>=i)return}else u=[(n-a)/s,n];o=[(i-a)/s,i]}else{if(u){if(u[1]=r)return}else u=[e,s*e+a];o=[r,s*r+a]}else{if(u){if(u[0]=-dh)){var g=u*u+l*l,p=h*h+c*c,v=(c*g-l*p)/f,d=(u*p-h*g)/f,y=$l.pop()||new th;y.arc=t,y.site=i,y.x=v+s,y.y=(y.cy=d+a)+Math.sqrt(v*v+d*d),t.circle=y;for(var m=null,_=gh._;_;)if(y.y<_.y||y.y===_.y&&y.x<=_.x){if(!_.L){m=_.P;break}_=_.L}else{if(!_.R){m=_;break}_=_.R}gh.insert(m,y),m||(Ql=y)}}}}function nh(t){var e=t.circle;e&&(e.P||(Ql=e.N),gh.remove(e),$l.push(e),Gl(e),t.circle=null)}var rh=[];function ih(){Gl(this),this.edge=this.site=this.circle=null}function oh(t){var e=rh.pop()||new ih;return e.site=t,e}function sh(t){nh(t),ch.remove(t),rh.push(t),Gl(t)}function ah(t){var e=t.circle,n=e.x,r=e.cy,i=[n,r],o=t.P,s=t.N,a=[t];sh(t);for(var u=o;u.circle&&Math.abs(n-u.circle.x)vh)a=a.L;else{if(!((i=o-hh(a,s))>vh)){r>-vh?(e=a.P,n=a):i>-vh?(e=a,n=a.N):e=n=a;break}if(!a.R){e=a;break}a=a.R}!function(t){fh[t.index]={site:t,halfedges:[]}}(t);var u=oh(t);if(ch.insert(e,u),e||n){if(e===n)return nh(e),n=oh(e.site),ch.insert(u,n),u.edge=n.edge=jl(e.site,u.site),eh(e),void eh(n);if(n){nh(e),nh(n);var l=e.site,h=l[0],c=l[1],f=t[0]-h,g=t[1]-c,p=n.site,v=p[0]-h,d=p[1]-c,y=2*(f*d-g*v),m=f*f+g*g,_=v*v+d*d,x=[(d*m-g*_)/y+h,(f*_-v*m)/y+c];Ul(n.edge,l,p,x),u.edge=jl(l,t,null,x),n.edge=jl(t,p,null,x),eh(e),eh(n)}else u.edge=jl(e.site,u.site)}}function lh(t,e){var n=t.site,r=n[0],i=n[1],o=i-e;if(!o)return r;var s=t.P;if(!s)return-1/0;var a=(n=s.site)[0],u=n[1],l=u-e;if(!l)return a;var h=a-r,c=1/o-1/l,f=h/l;return c?(-f+Math.sqrt(f*f-2*c*(h*h/(-2*l)-u+l/2+i-o/2)))/c+r:(r+a)/2}function hh(t,e){var n=t.N;if(n)return lh(n,e);var r=t.site;return r[1]===e?r[0]:1/0}var ch,fh,gh,ph,vh=1e-6,dh=1e-12;function yh(t,e){return e[1]-t[1]||e[0]-t[0]}function mh(t,e){var n,r,i,o=t.sort(yh).pop();for(ph=[],fh=new Array(t.length),ch=new Vl,gh=new Vl;;)if(i=Ql,o&&(!i||o[1]vh||Math.abs(i[0][1]-i[1][1])>vh)||delete ph[o]}(s,a,u,l),function(t,e,n,r){var i,o,s,a,u,l,h,c,f,g,p,v,d=fh.length,y=!0;for(i=0;ivh||Math.abs(v-f)>vh)&&(u.splice(a,0,ph.push(Xl(s,g,Math.abs(p-t)vh?[t,Math.abs(c-t)vh?[Math.abs(f-r)vh?[n,Math.abs(c-n)vh?[Math.abs(f-e)=a)return null;var u=t-i.site[0],l=e-i.site[1],h=u*u+l*l;do{i=o.cells[r=s],s=null,i.halfedges.forEach((function(n){var r=o.edges[n],a=r.left;if(a!==i.site&&a||(a=r.right)){var u=t-a[0],l=e-a[1],c=u*u+l*l;c2&&void 0!==arguments[2]?arguments[2]:{},r=rt(t).coordinates,i=0,o=0;o=i&&o===r.length-1);o++){if(i>=e){var s=e-i;if(s){var a=st(r[o],r[o-1])-180;return at(r[o],s,a,n)}return I(r[o])}i+=ut(r[o],r[o+1],n)}return I(r[r.length-1])},t.angle=function(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!Z(r))throw new Error("options is invalid");if(!t)throw new Error("startPoint is required");if(!e)throw new Error("midPoint is required");if(!n)throw new Error("endPoint is required");var i=t,o=e,s=n,a=G(!0!==r.mercator?st(o,i):lt(o,i)),u=G(!0!==r.mercator?st(o,s):lt(o,s));u1&&void 0!==arguments[1]?arguments[1]:{},n=e.resolution||1e4,r=e.sharpness||.85,i=[],o=rt(t).coordinates.map((function(t){return{x:t[0],y:t[1]}})),s=new Gt({duration:n,points:o,sharpness:r}),a=function(t){var e=s.pos(t);Math.floor(t/100)%2==0&&i.push([e.x,e.y])},u=0;u0;else if(n!==u>0)return!0}return!1},t.booleanContains=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type,s=n.coordinates,u=r.coordinates;switch(i){case"Point":if("Point"===o)return Ht(s,u);throw new Error("feature2 "+o+" geometry not supported");case"MultiPoint":switch(o){case"Point":return function(t,e){var n,r=!1;for(n=0;n2&&void 0!==arguments[2]?arguments[2]:{}).precision;if("number"!=typeof(n=null==n||isNaN(n)?6:n)||!(n>=0))throw new Error("precision must be a positive number");return rt(t).type===rt(e).type&&Ne(Le(t),Le(e),{precision:n})},t.booleanIntersects=Oe,t.booleanOverlap=function(t,e){var n=rt(t),r=rt(e),i=n.type,o=r.type;if("MultiPoint"===i&&"MultiPoint"!==o||("LineString"===i||"MultiLineString"===i)&&"LineString"!==o&&"MultiLineString"!==o||("Polygon"===i||"MultiPolygon"===i)&&"Polygon"!==o&&"MultiPolygon"!==o)throw new Error("features must be of the same type");if("Point"===i)throw new Error("Point geometry not supported");if(Ne(t,e,{precision:6}))return!1;var s=0;switch(i){case"MultiPoint":for(var a=0;a0},t.booleanParallel=function(t,e){if(!t)throw new Error("line1 is required");if(!e)throw new Error("line2 is required");if("LineString"!==In(t,"line1"))throw new Error("line1 must be a LineString");if("LineString"!==In(e,"line2"))throw new Error("line2 must be a LineString");for(var n=$e(Le(t)).features,r=$e(Le(e)).features,i=0;i1;case"MultiPoint":for(var i=0;i0&&ue(S([r[0]]),S([r[i]])).features.length>1)return!1}return!0;case"MultiPolygon":for(i=0;i0&&ue(S([o[0]]),S([o[s]])).features.length>1)return!1}return!0;default:return!1}},t.booleanWithin=Cn,t.buffer=function(t,e,n){var r=(n=n||{}).units||"kilometers",i=n.steps||8;if(!t)throw new Error("geojson is required");if("object"!==m(n))throw new Error("options must be an object");if("number"!=typeof i)throw new Error("steps must be an number");if(void 0===e)throw new Error("radius is required");if(i<=0)throw new Error("steps must be greater than 0");var o=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){var n=ui(t,e,r,i);n&&o.push(n)})),C(o);case"FeatureCollection":return vt(t,(function(t){var n=ui(t,e,r,i);n&&vt(n,(function(t){t&&o.push(t)}))})),C(o)}return ui(t,e,r,i)},t.center=An,t.centerMean=fi,t.centerMedian=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.counter||10;if(!U(n))throw new Error("counter must be a number");var r=e.weight,i=fi(t,{weight:e.weight}),o=C([]);vt(t,(function(t){var e;o.features.push(gi(t,{properties:{weight:null==(e=t.properties)?void 0:e[r]}}))}));var s={tolerance:e.tolerance,medianCandidates:[]};return pi(i.geometry.coordinates,[0,0],o,s,n)},t.centerOfMass=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(it(e)){case"Point":return I(K(e),n.properties);case"Polygon":var r=[];ct(e,(function(t){r.push(t)}));var i,o,s,a,u,l,h,c,f=gi(e,{properties:n.properties}),g=f.geometry.coordinates,p=0,v=0,d=0,y=r.map((function(t){return[t[0]-g[0],t[1]-g[1]]}));for(i=0;i2&&void 0!==arguments[2]?arguments[2]:{};!0!==n.mutate&&(t=Ai(t));var r=n.minPoints||3,i=V(e,n.units),o=new to(t.features.length),s=t.features.map((function(t){return!1})),a=t.features.map((function(t){return!1})),u=t.features.map((function(t){return!1})),l=t.features.map((function(t){return-1}));o.load(t.features.map((function(t,e){var n=v(t.geometry.coordinates,2),r=n[0],i=n[1];return{minX:r,minY:i,maxX:r,maxY:i,index:e}})));var h=function(n){var r=t.features[n],s=v(r.geometry.coordinates,2),a=s[0],u=s[1],l=Math.max(u-i,-90),h=Math.min(u+i,90),c=l<0&&h>0?i:Math.abs(l)=r){var i=c;c++,s[e]=!0,function(t,e){for(var n=0;n=r&&e.push.apply(e,d(o))}a[i]||(a[i]=!0,l[i]=t)}}(i,n)}else u[e]=!0}})),t.features.forEach((function(e,n){var r=t.features[n];r.properties||(r.properties={}),l[n]>=0?(r.properties.dbscan=u[n]?"edge":"core",r.properties.cluster=l[n]):r.properties.dbscan="noise"})),t},t.clustersKmeans=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.features.length;e.numberOfClusters=e.numberOfClusters||Math.round(Math.sqrt(n/2)),e.numberOfClusters>n&&(e.numberOfClusters=n),!0!==e.mutate&&(t=Ai(t));var r=yt(t),i=r.slice(0,e.numberOfClusters),o=ro(r,e.numberOfClusters,i),s={};return o.centroids.forEach((function(t,e){s[e]=t})),vt(t,(function(t,e){var n=o.idxs[e];t.properties.cluster=n,t.properties.centroid=s[n]})),t},t.collect=function(t,e,n,r){var i=new io(6),o=e.features.map((function(t){var e;return{minX:t.geometry.coordinates[0],minY:t.geometry.coordinates[1],maxX:t.geometry.coordinates[0],maxY:t.geometry.coordinates[1],property:null==(e=t.properties)?void 0:e[n]}}));return i.load(o),t.features.forEach((function(t){t.properties||(t.properties={});var e=Rt(t),n=i.search({minX:e[0],minY:e[1],maxX:e[2],maxY:e[3]}),o=[];n.forEach((function(e){zt([e.minX,e.minY],t)&&o.push(e.property)})),t.properties[r]=o})),t},t.collectionOf=nt,t.combine=function(t){var e={MultiPoint:{coordinates:[],properties:[]},MultiLineString:{coordinates:[],properties:[]},MultiPolygon:{coordinates:[],properties:[]}};return vt(t,(function(t){var n,r,i,o;switch(null==(o=t.geometry)?void 0:o.type){case"Point":e.MultiPoint.coordinates.push(t.geometry.coordinates),e.MultiPoint.properties.push(t.properties);break;case"MultiPoint":(n=e.MultiPoint.coordinates).push.apply(n,d(t.geometry.coordinates)),e.MultiPoint.properties.push(t.properties);break;case"LineString":e.MultiLineString.coordinates.push(t.geometry.coordinates),e.MultiLineString.properties.push(t.properties);break;case"MultiLineString":(r=e.MultiLineString.coordinates).push.apply(r,d(t.geometry.coordinates)),e.MultiLineString.properties.push(t.properties);break;case"Polygon":e.MultiPolygon.coordinates.push(t.geometry.coordinates),e.MultiPolygon.properties.push(t.properties);break;case"MultiPolygon":(i=e.MultiPolygon.coordinates).push.apply(i,d(t.geometry.coordinates)),e.MultiPolygon.properties.push(t.properties)}})),C(Object.keys(e).filter((function(t){return e[t].coordinates.length})).sort().map((function(t){return b({type:t,coordinates:e[t].coordinates},{collectedProperties:e[t].properties})})))},t.concave=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.maxEdge||1/0,r=function(t){var e=[],n={};return vt(t,(function(t){if(t.geometry){var r=t.geometry.coordinates.join("-");Object.prototype.hasOwnProperty.call(n,r)||(e.push(t),n[r]=!0)}})),C(e)}(t),i=oo(r);if(i.features=i.features.filter((function(t){var r=t.geometry.coordinates[0][0],i=t.geometry.coordinates[0][1],o=t.geometry.coordinates[0][2],s=ut(r,i,e),a=ut(i,o,e),u=ut(r,o,e);return s<=n&&a<=n&&u<=n})),i.features.length<1)return null;var o=Ro(i);return 1===o.coordinates.length&&(o.coordinates=o.coordinates[0],o.type="Polygon"),b(o)},t.containsNumber=$,t.convertArea=X,t.convertLength=j,t.convex=Oi,t.coordAll=yt,t.coordEach=ct,t.coordReduce=ft,t.createBins=zi,t.degreesToRadians=z,t.destination=at,t.difference=function(t){var e=[];if(mt(t,(function(t){e.push(t.coordinates)})),e.length<2)throw new Error("Must have at least two features");var n=t.features[0].properties||{},r=As.apply(Fs,[e[0]].concat(d(e.slice(1))));return 0===r.length?null:1===r.length?S(r[0],n):R(r,n)},t.dissolve=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.propertyName;nt(t,"Polygon","dissolve");var r=[];if(!n)return qs(R(Os.apply(null,t.features.map((function(t){return t.geometry.coordinates})))));var i={};vt(t,(function(t){t.properties&&(Object.prototype.hasOwnProperty.call(i,t.properties[n])||(i[t.properties[n]]=[]),i[t.properties[n]].push(t))}));for(var o=Object.keys(i),s=0;s1&&void 0!==arguments[1]?arguments[1]:{},o=i.properties,s=null==(e=i.autoComplete)||e,a=null==(n=i.orderCoords)||n;if(null!=(r=i.mutate)&&r||(t=Ai(t)),"FeatureCollection"===t.type){var u=[];return t.features.forEach((function(t){u.push(Q(ru(t,{},s,a)))})),R(u,o)}return ru(t,o,s,a)},t.mask=function(t,e,n){var r,i=null!=(r=null==n?void 0:n.mutate)&&r,o=e;e&&!1===i&&(o=Ai(e));var s,a=su(o);return("FeatureCollection"===t.type?ou(2===(s=t).features.length?Os(s.features[0].geometry.coordinates,s.features[1].geometry.coordinates):Os.apply(Fs,s.features.map((function(t){return t.geometry.coordinates})))):"Feature"===t.type?ou(Os(t.geometry.coordinates)):ou(Os(t.coordinates))).geometry.coordinates.forEach((function(t){a.geometry.coordinates.push(t[0])})),a},t.meta=Mt,t.midpoint=function(t,e){return at(t,ut(t,e)/2,st(t,e))},t.moranIndex=function(t,e){var n,r,i=e.inputField,o=e.threshold||1e5,s=e.p||2,u=null!=(n=e.binary)&&n,l=Gs(t,{alpha:e.alpha||-1,binary:u,p:s,standardization:null==(r=e.standardization)||r,threshold:o}),h=[];vt(t,(function(t){var e=t.properties||{};h.push(e[i])}));for(var c=au(h),f=function(t){var e,n=au(t),r=0,i=a(t);try{for(i.s();!(e=i.n()).done;){var o=e.value;r+=Math.pow(o-n,2)}}catch(t){i.e(t)}finally{i.f()}return r/t.length}(h),g=0,p=0,v=0,d=0,y=l.length,m=0;m2&&void 0!==arguments[2]?arguments[2]:{},r=n.units,i=n.properties||{},o=function(t){var e=[];switch(t.geometry?t.geometry.type:t.type){case"GeometryCollection":return mt(t,(function(t){"Point"===t.type&&e.push({type:"Feature",properties:{},geometry:t})})),{type:"FeatureCollection",features:e};case"FeatureCollection":return t.features=t.features.filter((function(t){return"Point"===t.geometry.type})),t;default:throw new Error("points must be a Point Collection")}}(t);if(!o.features.length)throw new Error("points must contain features");if(!e)throw new Error("line is required");if("LineString"!==it(e))throw new Error("line must be a LineString");var s=1/0,a=null;return vt(o,(function(t){var n=mu(t,e,{units:r});n2&&void 0!==arguments[2]?arguments[2]:{},a=null!=(i=s.method)?i:"geodesic",u=null!=(o=s.units)?o:"kilometers";if(!e)throw new Error("point is required");if(!r)throw new Error("polygon or multi-polygon is required");var l,h=rt(r);if("MultiPolygon"===h.type){var c=h.coordinates.map((function(n){return t(e,S(n),{method:a,units:u})}));return Math.min.apply(Math,d(c.map(Math.abs)))*(zt(e,r)?-1:1)}if(h.coordinates.length>1){var p=h.coordinates.map((function(n){return t(e,S([n]),{method:a,units:u})})),v=n(l=p)||f(l)||_(l)||g(),y=v[0],m=v.slice(1);if(y>=0)return y;var x=Math.min.apply(Math,d(m));return x<0?Math.abs(x):Math.min(x,Math.abs(y))}var E=le(h),k=1/0;return xt(E,(function(t){k=Math.min(k,mu(e,t,{method:a,units:u}))})),zt(e,h)?-k:k},t.points=N,t.pointsWithinPolygon=Su,t.polygon=S,t.polygonSmooth=function(t,e){(e=e||{}).iterations=e.iterations||1;var n=e.iterations,r=[];if(!t)throw new Error("inputPolys is required");return mt(t,(function(t,e,i){if("Polygon"===t.type){for(var o=[[]],s=0;s0&&(u=S(o).geometry),Ru(u,a),o=a.slice(0)}r.push(S(o,i))}else{if("MultiPolygon"!==t.type)throw new Error("geometry is invalid, must be Polygon or MultiPolygon");for(var l=[[[]]],h=0;h0&&(f=R(l).geometry),Au(f,c),l=c.slice(0)}r.push(R(l,i))}})),C(r)},t.polygonTangents=function(t,e){var n,r=Q(t),i=Q(e),o=[],s=[],a=Rt(e),u=0,l=null;switch(r[0]>a[0]&&r[0]a[1]&&r[1]_&&(_=k)}for(var b=[],w=Object.keys(l).length,I=f/w,N=0,S=0;S<_+1;S++)N+=Math.exp(-I)*Math.pow(I,S)/Zu(S),b.push(N);for(var M=[],L=0,P=0;P<_+1;P++){for(var C=0,T=Object.keys(l);CR&&(R=D)}var F=Xu[r]/Math.sqrt(w),q={criticalValue:F,isRandom:!0,maxAbsoluteDifference:R,observedDistribution:M};return R>F&&(q.isRandom=!1),q},t.radiansToDegrees=Y,t.radiansToLength=F,t.random=nl,t.randomLineString=$u,t.randomPoint=Ku,t.randomPolygon=Qu,t.randomPosition=Hu,t.rectangleGrid=oa,t.rewind=function(t){var e,n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(r=r||{}))throw new Error("options is invalid");var i=null!=(e=r.mutate)&&e,o=null!=(n=r.reverse)&&n;if(!t)throw new Error(" is required");if("boolean"!=typeof o)throw new Error(" must be a boolean");if("boolean"!=typeof i)throw new Error(" must be a boolean");i||"Point"===t.type||"MultiPoint"===t.type||(t=Ai(t));var s=[];switch(t.type){case"GeometryCollection":return mt(t,(function(t){rl(t,o)})),t;case"FeatureCollection":return vt(t,(function(t){vt(rl(t,o),(function(t){s.push(t)}))})),C(s)}return rl(t,o)},t.rhumbBearing=lt,t.rhumbDestination=Bs,t.rhumbDistance=Ys,t.round=D,t.sample=function(t,e){if(!t)throw new Error("fc is required");if(null==e)throw new Error("num is required");if("number"!=typeof e)throw new Error("num must be a number");var n=C(function(t,e){var n,r,i=t.slice(0),o=t.length,s=o-e;for(;o-- >s;)n=i[r=Math.floor((o+1)*Math.random())],i[r]=i[o],i[o]=n;return i.slice(s)}(t.features,e));return n},t.sector=function(t,e,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(!Z(i=i||{}))throw new Error("options is invalid");var o=i.properties;if(!t)throw new Error("center is required");if(null==n)throw new Error("bearing1 is required");if(null==r)throw new Error("bearing2 is required");if(!e)throw new Error("radius is required");if("object"!==m(i))throw new Error("options must be an object");if(sl(n)===sl(r))return Ri(t,e,i);var s=Q(t),a=ja(t,e,n,r,i),u=[[s]];return ct(a,(function(t){u[0].push(t)})),u[0].push(s),S(u,o)},t.segmentEach=kt,t.segmentReduce=bt,t.shortestPath=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Z(n=n||{}))throw new Error("options is invalid");var r=n.obstacles||C([]),i=n.resolution||100;if(!t)throw new Error("start is required");if(!e)throw new Error("end is required");if(i&&(!U(i)||i<=0))throw new Error("options.resolution must be a number, greater than 0");var o=K(t),s=K(e);if(t=I(o),e=I(s),"FeatureCollection"===r.type){if(0===r.features.length)return L([o,s])}else{if("Polygon"!==r.type)throw new Error("invalid obstacles");r=C([b(rt(r))])}var a=r;a.features.push(t),a.features.push(e);var u=v(Rt(al(Vt(Rt(a)),1.15)),4),l=u[0],h=u[1],c=u[2],f=u[3],g=ut([l,h],[c,h],n)/i;a.features.pop(),a.features.pop();for(var p,d,y=g/ut([l,h],[c,h],n)*(c-l),m=g/ut([l,h],[l,f],n)*(f-h),_=c-l,x=f-h,E=Math.floor(_/y),k=Math.floor(x/m),w=(_-E*y)/2,N=[],S=[],M=1/0,P=1/0,T=f-(x-k*m)/2,O=0;T>=h;){for(var R=[],A=[],D=l+w,F=0;D<=c;){var q=I([D,T]),V=pl(q,r);R.push(V?0:1),A.push(D+"|"+T);var G=ut(q,t);!V&&G1&&void 0!==arguments[1]?arguments[1]:{};if(!Z(i=null!=i?i:{}))throw new Error("options is invalid");var o=null!=(e=i.tolerance)?e:1,s=null!=(n=i.highQuality)&&n,a=null!=(r=i.mutate)&&r;if(!t)throw new Error("geojson is required");if(o&&o<0)throw new Error("invalid tolerance");return!0!==a&&(t=Ai(t)),mt(t,(function(t){!function(t,e,n){var r=t.type;if("Point"===r||"MultiPoint"===r)return t;if(Le(t,{mutate:!0}),"GeometryCollection"!==r)switch(r){case"LineString":t.coordinates=ml(t.coordinates,e,n);break;case"MultiLineString":t.coordinates=t.coordinates.map((function(t){return ml(t,e,n)}));break;case"Polygon":t.coordinates=_l(t.coordinates,e,n);break;case"MultiPolygon":t.coordinates=t.coordinates.map((function(t){return _l(t,e,n)}))}}(t,o,s)})),t},t.square=Ka,t.squareGrid=sa,t.standardDeviationalEllipse=function(t,e){var n;if(!Z(e=e||{}))throw new Error("options is invalid");var r=e.steps||64,i=e.weight,o=e.properties||{};if(!U(r))throw new Error("steps must be a number");if(!Z(o))throw new Error("properties must be a number");var s=yt(t).length,a=fi(t,{weight:i}),u=0,l=0,h=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));u+=Math.pow(r.x,2)*n,l+=Math.pow(r.y,2)*n,h+=r.x*r.y*n}));var c=u-l,f=Math.sqrt(Math.pow(c,2)+4*Math.pow(h,2)),g=2*h,p=Math.atan((c+f)/g),v=180*p/Math.PI,d=0,y=0,m=0;vt(t,(function(t){var e,n=i&&(null==(e=t.properties)?void 0:e[i])||1,r=El(Q(t),Q(a));d+=Math.pow(r.x*Math.cos(p)-r.y*Math.sin(p),2)*n,y+=Math.pow(r.x*Math.sin(p)+r.y*Math.cos(p),2)*n,m+=n}));var _=Math.sqrt(2*d/m),x=Math.sqrt(2*y/m),E=js(a,_,x,{units:"degrees",angle:v,steps:r,properties:o}),k=Su(t,C([E])),b={meanCenterCoordinates:Q(a),semiMajorAxis:_,semiMinorAxis:x,numberOfFeatures:s,angle:v,percentageWithinEllipse:100*yt(k).length/s};return E.properties=null!=(n=E.properties)?n:{},E.properties.standardDeviationalEllipse=b,E},t.tag=function(t,e,n,r){return t=Ai(t),e=Ai(e),vt(t,(function(t){t.properties||(t.properties={}),vt(e,(function(e){t.properties&&e.properties&&void 0===t.properties[r]&&zt(t,e)&&(t.properties[r]=e.properties[n])}))})),t},t.tesselate=function(t){if(!t.geometry||"Polygon"!==t.geometry.type&&"MultiPolygon"!==t.geometry.type)throw new Error("input must be a Polygon or MultiPolygon");var e={type:"FeatureCollection",features:[]};return"Polygon"===t.geometry.type?e.features=Nl(t.geometry.coordinates):t.geometry.coordinates.forEach((function(t){e.features=e.features.concat(Nl(t))})),e},t.tin=oo,t.toMercator=Vu,t.toWgs84=Gu,t.transformRotate=zs,t.transformScale=al,t.transformTranslate=function(t,e,n,r){if(!Z(r=r||{}))throw new Error("options is invalid");var i=r.units,o=r.zTranslation,s=r.mutate;if(!t)throw new Error("geojson is required");if(null==e||isNaN(e))throw new Error("distance is required");if(o&&"number"!=typeof o&&isNaN(o))throw new Error("zTranslation is not a number");if(o=void 0!==o?o:0,0===e&&0===o)return t;if(null==n||isNaN(n))throw new Error("direction is required");return e<0&&(e=-e,n+=180),!1!==s&&void 0!==s||(t=Ai(t)),ct(t,(function(t){var r=Q(Bs(t,e,n,{units:i}));t[0]=r[0],t[1]=r[1],o&&3===t.length&&(t[2]+=o)})),t},t.triangleGrid=aa,t.truncate=Qa,t.union=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];if(mt(t,(function(t){n.push(t.coordinates)})),n.length<2)throw new Error("Must have at least 2 geometries");var r=Os.apply(Fs,[n[0]].concat(d(n.slice(1))));return 0===r.length?null:1===r.length?S(r[0],e.properties):R(r,e.properties)},t.unkinkPolygon=function(t){var e=[];return xt(t,(function(t){"Polygon"===t.geometry.type&&vt(Ll(t),(function(n){e.push(S(n.geometry.coordinates,t.properties))}))})),C(e)},t.validateBBox=H,t.validateId=W,t.voronoi=function(t,e){if(!Z(e=e||{}))throw new Error("options is invalid");var n=e.bbox||[-180,-85,180,85];if(!t)throw new Error("points is required");if(!Array.isArray(n))throw new Error("bbox is invalid");return nt(t,"Point","points"),C(function(){var t=Fl,e=ql,n=null;function r(r){return new mh(r.map((function(n,i){var o=[Math.round(t(n,i,r)/vh)*vh,Math.round(e(n,i,r)/vh)*vh];return o.index=i,o.data=n,o})),n)}return r.polygons=function(t){return r(t).polygons()},r.links=function(t){return r(t).links()},r.triangles=function(t){return r(t).triangles()},r.x=function(e){return arguments.length?(t="function"==typeof e?e:Dl(+e),r):t},r.y=function(t){return arguments.length?(e="function"==typeof t?t:Dl(+t),r):e},r.extent=function(t){return arguments.length?(n=null==t?null:[[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]],r):n&&[[n[0][0],n[0][1]],[n[1][0],n[1][1]]]},r.size=function(t){return arguments.length?(n=null==t?null:[[0,0],[+t[0],+t[1]]],r):n&&[n[1][0]-n[0][0],n[1][1]-n[0][1]]},r}().x((function(t){return t.geometry.coordinates[0]})).y((function(t){return t.geometry.coordinates[1]})).extent([[n[0],n[1]],[n[2],n[3]]]).polygons(t.features).map((function(e,n){return Object.assign(function(t){return(t=t.slice()).push(t[0]),S([t])}(e),{properties:Fi(t.features[n].properties)})})))}}));
").addClass(errClass).css("position", "absolute") + .css("top", el.offsetTop) + .css("left", el.offsetLeft) + // setting width can push out the page size, forcing otherwise + // unnecessary scrollbars to appear and making it impossible for + // the element to shrink; so use max-width instead + .css("maxWidth", el.offsetWidth) + .css("height", el.offsetHeight); + errorDiv.text(err.message); + $el.after(errorDiv); + + // Really dumb way to keep the size/position of the error in sync with + // the parent element as the window is resized or whatever. + var intId = setInterval(function() { + if (!errorDiv[0].parentElement) { + clearInterval(intId); + return; + } + errorDiv + .css("top", el.offsetTop) + .css("left", el.offsetLeft) + .css("maxWidth", el.offsetWidth) + .css("height", el.offsetHeight); + }, 500); + } + } + }, + clearError: function(el) { + var $el = $(el); + var display = $el.data("restore-display-mode"); + $el.data("restore-display-mode", null); + + if (display === "inline" || display === "inline-block") { + if (display) + $el.css("display", display); + $(el.nextSibling).filter(".htmlwidgets-error").remove(); + } else if (display === "block"){ + $el.css("visibility", "inherit"); + $(el.nextSibling).filter(".htmlwidgets-error").remove(); + } + }, + sizing: {} + }; + + // Called by widget bindings to register a new type of widget. The definition + // object can contain the following properties: + // - name (required) - A string indicating the binding name, which will be + // used by default as the CSS classname to look for. + // - initialize (optional) - A function(el) that will be called once per + // widget element; if a value is returned, it will be passed as the third + // value to renderValue. + // - renderValue (required) - A function(el, data, initValue) that will be + // called with data. Static contexts will cause this to be called once per + // element; Shiny apps will cause this to be called multiple times per + // element, as the data changes. + window.HTMLWidgets.widget = function(definition) { + if (!definition.name) { + throw new Error("Widget must have a name"); + } + if (!definition.type) { + throw new Error("Widget must have a type"); + } + // Currently we only support output widgets + if (definition.type !== "output") { + throw new Error("Unrecognized widget type '" + definition.type + "'"); + } + // TODO: Verify that .name is a valid CSS classname + + // Support new-style instance-bound definitions. Old-style class-bound + // definitions have one widget "object" per widget per type/class of + // widget; the renderValue and resize methods on such widget objects + // take el and instance arguments, because the widget object can't + // store them. New-style instance-bound definitions have one widget + // object per widget instance; the definition that's passed in doesn't + // provide renderValue or resize methods at all, just the single method + // factory(el, width, height) + // which returns an object that has renderValue(x) and resize(w, h). + // This enables a far more natural programming style for the widget + // author, who can store per-instance state using either OO-style + // instance fields or functional-style closure variables (I guess this + // is in contrast to what can only be called C-style pseudo-OO which is + // what we required before). + if (definition.factory) { + definition = createLegacyDefinitionAdapter(definition); + } + + if (!definition.renderValue) { + throw new Error("Widget must have a renderValue function"); + } + + // For static rendering (non-Shiny), use a simple widget registration + // scheme. We also use this scheme for Shiny apps/documents that also + // contain static widgets. + window.HTMLWidgets.widgets = window.HTMLWidgets.widgets || []; + // Merge defaults into the definition; don't mutate the original definition. + var staticBinding = extend({}, defaults, definition); + overrideMethod(staticBinding, "find", function(superfunc) { + return function(scope) { + var results = superfunc(scope); + // Filter out Shiny outputs, we only want the static kind + return filterByClass(results, "html-widget-output", false); + }; + }); + window.HTMLWidgets.widgets.push(staticBinding); + + if (shinyMode) { + // Shiny is running. Register the definition with an output binding. + // The definition itself will not be the output binding, instead + // we will make an output binding object that delegates to the + // definition. This is because we foolishly used the same method + // name (renderValue) for htmlwidgets definition and Shiny bindings + // but they actually have quite different semantics (the Shiny + // bindings receive data that includes lots of metadata that it + // strips off before calling htmlwidgets renderValue). We can't + // just ignore the difference because in some widgets it's helpful + // to call this.renderValue() from inside of resize(), and if + // we're not delegating, then that call will go to the Shiny + // version instead of the htmlwidgets version. + + // Merge defaults with definition, without mutating either. + var bindingDef = extend({}, defaults, definition); + + // This object will be our actual Shiny binding. + var shinyBinding = new Shiny.OutputBinding(); + + // With a few exceptions, we'll want to simply use the bindingDef's + // version of methods if they are available, otherwise fall back to + // Shiny's defaults. NOTE: If Shiny's output bindings gain additional + // methods in the future, and we want them to be overrideable by + // HTMLWidget binding definitions, then we'll need to add them to this + // list. + delegateMethod(shinyBinding, bindingDef, "getId"); + delegateMethod(shinyBinding, bindingDef, "onValueChange"); + delegateMethod(shinyBinding, bindingDef, "onValueError"); + delegateMethod(shinyBinding, bindingDef, "renderError"); + delegateMethod(shinyBinding, bindingDef, "clearError"); + delegateMethod(shinyBinding, bindingDef, "showProgress"); + + // The find, renderValue, and resize are handled differently, because we + // want to actually decorate the behavior of the bindingDef methods. + + shinyBinding.find = function(scope) { + var results = bindingDef.find(scope); + + // Only return elements that are Shiny outputs, not static ones + var dynamicResults = results.filter(".html-widget-output"); + + // It's possible that whatever caused Shiny to think there might be + // new dynamic outputs, also caused there to be new static outputs. + // Since there might be lots of different htmlwidgets bindings, we + // schedule execution for later--no need to staticRender multiple + // times. + if (results.length !== dynamicResults.length) + scheduleStaticRender(); + + return dynamicResults; + }; + + // Wrap renderValue to handle initialization, which unfortunately isn't + // supported natively by Shiny at the time of this writing. + + shinyBinding.renderValue = function(el, data) { + Shiny.renderDependencies(data.deps); + // Resolve strings marked as javascript literals to objects + if (!(data.evals instanceof Array)) data.evals = [data.evals]; + for (var i = 0; data.evals && i < data.evals.length; i++) { + window.HTMLWidgets.evaluateStringMember(data.x, data.evals[i]); + } + if (!bindingDef.renderOnNullValue) { + if (data.x === null) { + el.style.visibility = "hidden"; + return; + } else { + el.style.visibility = "inherit"; + } + } + if (!elementData(el, "initialized")) { + initSizing(el); + + elementData(el, "initialized", true); + if (bindingDef.initialize) { + var rect = el.getBoundingClientRect(); + var result = bindingDef.initialize(el, rect.width, rect.height); + elementData(el, "init_result", result); + } + } + bindingDef.renderValue(el, data.x, elementData(el, "init_result")); + evalAndRun(data.jsHooks.render, elementData(el, "init_result"), [el, data.x]); + }; + + // Only override resize if bindingDef implements it + if (bindingDef.resize) { + shinyBinding.resize = function(el, width, height) { + // Shiny can call resize before initialize/renderValue have been + // called, which doesn't make sense for widgets. + if (elementData(el, "initialized")) { + bindingDef.resize(el, width, height, elementData(el, "init_result")); + } + }; + } + + Shiny.outputBindings.register(shinyBinding, bindingDef.name); + } + }; + + var scheduleStaticRenderTimerId = null; + function scheduleStaticRender() { + if (!scheduleStaticRenderTimerId) { + scheduleStaticRenderTimerId = setTimeout(function() { + scheduleStaticRenderTimerId = null; + window.HTMLWidgets.staticRender(); + }, 1); + } + } + + // Render static widgets after the document finishes loading + // Statically render all elements that are of this widget's class + window.HTMLWidgets.staticRender = function() { + var bindings = window.HTMLWidgets.widgets || []; + forEach(bindings, function(binding) { + var matches = binding.find(document.documentElement); + forEach(matches, function(el) { + var sizeObj = initSizing(el, binding); + + var getSize = function(el) { + if (sizeObj) { + return {w: sizeObj.getWidth(), h: sizeObj.getHeight()} + } else { + var rect = el.getBoundingClientRect(); + return {w: rect.width, h: rect.height} + } + }; + + if (hasClass(el, "html-widget-static-bound")) + return; + el.className = el.className + " html-widget-static-bound"; + + var initResult; + if (binding.initialize) { + var size = getSize(el); + initResult = binding.initialize(el, size.w, size.h); + elementData(el, "init_result", initResult); + } + + if (binding.resize) { + var lastSize = getSize(el); + var resizeHandler = function(e) { + var size = getSize(el); + if (size.w === 0 && size.h === 0) + return; + if (size.w === lastSize.w && size.h === lastSize.h) + return; + lastSize = size; + binding.resize(el, size.w, size.h, initResult); + }; + + on(window, "resize", resizeHandler); + + // This is needed for cases where we're running in a Shiny + // app, but the widget itself is not a Shiny output, but + // rather a simple static widget. One example of this is + // an rmarkdown document that has runtime:shiny and widget + // that isn't in a render function. Shiny only knows to + // call resize handlers for Shiny outputs, not for static + // widgets, so we do it ourselves. + if (window.jQuery) { + window.jQuery(document).on( + "shown.htmlwidgets shown.bs.tab.htmlwidgets shown.bs.collapse.htmlwidgets", + resizeHandler + ); + window.jQuery(document).on( + "hidden.htmlwidgets hidden.bs.tab.htmlwidgets hidden.bs.collapse.htmlwidgets", + resizeHandler + ); + } + + // This is needed for the specific case of ioslides, which + // flips slides between display:none and display:block. + // Ideally we would not have to have ioslide-specific code + // here, but rather have ioslides raise a generic event, + // but the rmarkdown package just went to CRAN so the + // window to getting that fixed may be long. + if (window.addEventListener) { + // It's OK to limit this to window.addEventListener + // browsers because ioslides itself only supports + // such browsers. + on(document, "slideenter", resizeHandler); + on(document, "slideleave", resizeHandler); + } + } + + var scriptData = document.querySelector("script[data-for='" + el.id + "'][type='application/json']"); + if (scriptData) { + var data = JSON.parse(scriptData.textContent || scriptData.text); + // Resolve strings marked as javascript literals to objects + if (!(data.evals instanceof Array)) data.evals = [data.evals]; + for (var k = 0; data.evals && k < data.evals.length; k++) { + window.HTMLWidgets.evaluateStringMember(data.x, data.evals[k]); + } + binding.renderValue(el, data.x, initResult); + evalAndRun(data.jsHooks.render, initResult, [el, data.x]); + } + }); + }); + + invokePostRenderHandlers(); + } + + + function has_jQuery3() { + if (!window.jQuery) { + return false; + } + var $version = window.jQuery.fn.jquery; + var $major_version = parseInt($version.split(".")[0]); + return $major_version >= 3; + } + + /* + / Shiny 1.4 bumped jQuery from 1.x to 3.x which means jQuery's + / on-ready handler (i.e., $(fn)) is now asyncronous (i.e., it now + / really means $(setTimeout(fn)). + / https://jquery.com/upgrade-guide/3.0/#breaking-change-document-ready-handlers-are-now-asynchronous + / + / Since Shiny uses $() to schedule initShiny, shiny>=1.4 calls initShiny + / one tick later than it did before, which means staticRender() is + / called renderValue() earlier than (advanced) widget authors might be expecting. + / https://github.com/rstudio/shiny/issues/2630 + / + / For a concrete example, leaflet has some methods (e.g., updateBounds) + / which reference Shiny methods registered in initShiny (e.g., setInputValue). + / Since leaflet is privy to this life-cycle, it knows to use setTimeout() to + / delay execution of those methods (until Shiny methods are ready) + / https://github.com/rstudio/leaflet/blob/18ec981/javascript/src/index.js#L266-L268 + / + / Ideally widget authors wouldn't need to use this setTimeout() hack that + / leaflet uses to call Shiny methods on a staticRender(). In the long run, + / the logic initShiny should be broken up so that method registration happens + / right away, but binding happens later. + */ + function maybeStaticRenderLater() { + if (shinyMode && has_jQuery3()) { + window.jQuery(window.HTMLWidgets.staticRender); + } else { + window.HTMLWidgets.staticRender(); + } + } + + if (document.addEventListener) { + document.addEventListener("DOMContentLoaded", function() { + document.removeEventListener("DOMContentLoaded", arguments.callee, false); + maybeStaticRenderLater(); + }, false); + } else if (document.attachEvent) { + document.attachEvent("onreadystatechange", function() { + if (document.readyState === "complete") { + document.detachEvent("onreadystatechange", arguments.callee); + maybeStaticRenderLater(); + } + }); + } + + + window.HTMLWidgets.getAttachmentUrl = function(depname, key) { + // If no key, default to the first item + if (typeof(key) === "undefined") + key = 1; + + var link = document.getElementById(depname + "-" + key + "-attachment"); + if (!link) { + throw new Error("Attachment " + depname + "/" + key + " not found in document"); + } + return link.getAttribute("href"); + }; + + window.HTMLWidgets.dataframeToD3 = function(df) { + var names = []; + var length; + for (var name in df) { + if (df.hasOwnProperty(name)) + names.push(name); + if (typeof(df[name]) !== "object" || typeof(df[name].length) === "undefined") { + throw new Error("All fields must be arrays"); + } else if (typeof(length) !== "undefined" && length !== df[name].length) { + throw new Error("All fields must be arrays of the same length"); + } + length = df[name].length; + } + var results = []; + var item; + for (var row = 0; row < length; row++) { + item = {}; + for (var col = 0; col < names.length; col++) { + item[names[col]] = df[names[col]][row]; + } + results.push(item); + } + return results; + }; + + window.HTMLWidgets.transposeArray2D = function(array) { + if (array.length === 0) return array; + var newArray = array[0].map(function(col, i) { + return array.map(function(row) { + return row[i] + }) + }); + return newArray; + }; + // Split value at splitChar, but allow splitChar to be escaped + // using escapeChar. Any other characters escaped by escapeChar + // will be included as usual (including escapeChar itself). + function splitWithEscape(value, splitChar, escapeChar) { + var results = []; + var escapeMode = false; + var currentResult = ""; + for (var pos = 0; pos < value.length; pos++) { + if (!escapeMode) { + if (value[pos] === splitChar) { + results.push(currentResult); + currentResult = ""; + } else if (value[pos] === escapeChar) { + escapeMode = true; + } else { + currentResult += value[pos]; + } + } else { + currentResult += value[pos]; + escapeMode = false; + } + } + if (currentResult !== "") { + results.push(currentResult); + } + return results; + } + // Function authored by Yihui/JJ Allaire + window.HTMLWidgets.evaluateStringMember = function(o, member) { + var parts = splitWithEscape(member, '.', '\\'); + for (var i = 0, l = parts.length; i < l; i++) { + var part = parts[i]; + // part may be a character or 'numeric' member name + if (o !== null && typeof o === "object" && part in o) { + if (i == (l - 1)) { // if we are at the end of the line then evalulate + if (typeof o[part] === "string") + o[part] = tryEval(o[part]); + } else { // otherwise continue to next embedded object + o = o[part]; + } + } + } + }; + + // Retrieve the HTMLWidget instance (i.e. the return value of an + // HTMLWidget binding's initialize() or factory() function) + // associated with an element, or null if none. + window.HTMLWidgets.getInstance = function(el) { + return elementData(el, "init_result"); + }; + + // Finds the first element in the scope that matches the selector, + // and returns the HTMLWidget instance (i.e. the return value of + // an HTMLWidget binding's initialize() or factory() function) + // associated with that element, if any. If no element matches the + // selector, or the first matching element has no HTMLWidget + // instance associated with it, then null is returned. + // + // The scope argument is optional, and defaults to window.document. + window.HTMLWidgets.find = function(scope, selector) { + if (arguments.length == 1) { + selector = scope; + scope = document; + } + + var el = scope.querySelector(selector); + if (el === null) { + return null; + } else { + return window.HTMLWidgets.getInstance(el); + } + }; + + // Finds all elements in the scope that match the selector, and + // returns the HTMLWidget instances (i.e. the return values of + // an HTMLWidget binding's initialize() or factory() function) + // associated with the elements, in an array. If elements that + // match the selector don't have an associated HTMLWidget + // instance, the returned array will contain nulls. + // + // The scope argument is optional, and defaults to window.document. + window.HTMLWidgets.findAll = function(scope, selector) { + if (arguments.length == 1) { + selector = scope; + scope = document; + } + + var nodes = scope.querySelectorAll(selector); + var results = []; + for (var i = 0; i < nodes.length; i++) { + results.push(window.HTMLWidgets.getInstance(nodes[i])); + } + return results; + }; + + var postRenderHandlers = []; + function invokePostRenderHandlers() { + while (postRenderHandlers.length) { + var handler = postRenderHandlers.shift(); + if (handler) { + handler(); + } + } + } + + // Register the given callback function to be invoked after the + // next time static widgets are rendered. + window.HTMLWidgets.addPostRenderHandler = function(callback) { + postRenderHandlers.push(callback); + }; + + // Takes a new-style instance-bound definition, and returns an + // old-style class-bound definition. This saves us from having + // to rewrite all the logic in this file to accomodate both + // types of definitions. + function createLegacyDefinitionAdapter(defn) { + var result = { + name: defn.name, + type: defn.type, + initialize: function(el, width, height) { + return defn.factory(el, width, height); + }, + renderValue: function(el, x, instance) { + return instance.renderValue(x); + }, + resize: function(el, width, height, instance) { + return instance.resize(width, height); + } + }; + + if (defn.find) + result.find = defn.find; + if (defn.renderError) + result.renderError = defn.renderError; + if (defn.clearError) + result.clearError = defn.clearError; + + return result; + } +})(); diff --git a/docs/articles/turf_files/layers-control-1.0.0/filter-control.css b/docs/articles/turf_files/layers-control-1.0.0/filter-control.css new file mode 100644 index 0000000..e6096c3 --- /dev/null +++ b/docs/articles/turf_files/layers-control-1.0.0/filter-control.css @@ -0,0 +1,65 @@ +.filter-control { + background: #fff; + position: absolute; + z-index: 1; + border-radius: 3px; + width: 200px; + border: 1px solid rgba(0, 0, 0, 0.4); + font-family: 'Open Sans', sans-serif; + margin: 10px; + padding: 10px; +} + +.filter-control .filter-title { + font-weight: bold; + margin-bottom: 10px; + text-align: center; +} + +.filter-control input[type="range"] { + width: 100%; + margin: 10px 0; +} + +.filter-control .range-value { + text-align: center; + margin-top: 5px; +} + +.filter-control .checkbox-group { + display: flex; + flex-direction: column; + gap: 5px; +} + +.filter-control .checkbox-group label { + display: flex; + align-items: center; + gap: 5px; +} + +.filter-control .toggle-button { + background: darkgrey; + color: #ffffff; + text-align: center; + cursor: pointer; + padding: 5px 0; + border-radius: 3px 3px 0 0; + margin: -10px -10px 10px -10px; +} + +.filter-control .toggle-button:hover { + background: grey; +} + +.filter-control .filter-content { + display: block; +} + +.filter-control.collapsible .filter-content { + display: none; +} + +.filter-control.collapsible.open .filter-content { + display: block; +} \ No newline at end of file diff --git a/docs/articles/turf_files/layers-control-1.0.0/layers-control.css b/docs/articles/turf_files/layers-control-1.0.0/layers-control.css new file mode 100644 index 0000000..8551228 --- /dev/null +++ b/docs/articles/turf_files/layers-control-1.0.0/layers-control.css @@ -0,0 +1,123 @@ +.layers-control { + background: #fff; + position: absolute; + z-index: 1; + border-radius: 4px; + width: 120px; + border: 1px solid rgba(0, 0, 0, 0.15); + font-family: "Open Sans", sans-serif; + margin: 0px; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15); + overflow: hidden; + transition: all 0.2s ease-in-out; +} + +.layers-control a { + font-size: 13px; + color: #404040; + display: block; + margin: 0; + padding: 10px; + text-decoration: none; + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + text-align: center; + transition: all 0.15s ease-in-out; + font-weight: normal; +} + +.layers-control a:last-child { + border: none; +} + +.layers-control a:hover { + background-color: #f8f8f8; + color: #1a1a1a; +} + +.layers-control a.active { + background-color: #4a90e2; + color: #ffffff; + font-weight: 500; +} + +.layers-control a.active:hover { + background: #3b7ed2; +} + +.layers-control .toggle-button { + display: none; + background: #4a90e2; + color: #ffffff; + text-align: center; + cursor: pointer; + padding: 8px 0; + border-radius: 4px 4px 0 0; + font-weight: 500; + letter-spacing: 0.3px; + box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.05) inset; + transition: all 0.15s ease-in-out; +} + +.layers-control .toggle-button:hover { + background: #3b7ed2; +} + +.layers-control .layers-list { + display: block; +} + +.layers-control.collapsible .toggle-button { + display: block; + border-bottom: 1px solid rgba(0, 0, 0, 0.25); +} + +.layers-control.collapsible .layers-list { + display: none; + opacity: 0; + max-height: 0; + transition: + opacity 0.25s ease, + max-height 0.25s ease; +} + +.layers-control.collapsible.open .layers-list { + display: block; + opacity: 1; + max-height: 500px; /* Large enough value to accommodate all content */ +} + +/* Compact icon styling */ +.layers-control.collapsible.icon-only { + width: auto; + min-width: 36px; + border-radius: 4px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); + transform: translateZ( + 0 + ); /* Force hardware acceleration for smoother animations */ +} + +.layers-control.collapsible.icon-only .toggle-button { + border-radius: 4px; + padding: 8px; + width: 36px; + height: 36px; + box-sizing: border-box; + margin: 0; + border-bottom: none; + display: flex; + align-items: center; + justify-content: center; + box-shadow: none; +} + +.layers-control.collapsible.icon-only.open { + width: 120px; + box-shadow: 0 3px 10px rgba(0, 0, 0, 0.25); +} + +.layers-control.collapsible.icon-only.open .toggle-button { + border-radius: 4px 4px 0 0; + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + width: 100%; +} diff --git a/docs/articles/turf_files/mapbox-gl-draw-1.5.0/mapbox-gl-draw.css b/docs/articles/turf_files/mapbox-gl-draw-1.5.0/mapbox-gl-draw.css new file mode 100644 index 0000000..0347a27 --- /dev/null +++ b/docs/articles/turf_files/mapbox-gl-draw-1.5.0/mapbox-gl-draw.css @@ -0,0 +1,88 @@ + +/* Override default control style */ +.mapbox-gl-draw_ctrl-bottom-left, +.mapbox-gl-draw_ctrl-top-left { + margin-left:0; + border-radius:0 4px 4px 0; +} +.mapbox-gl-draw_ctrl-top-right, +.mapbox-gl-draw_ctrl-bottom-right { + margin-right:0; + border-radius:4px 0 0 4px; +} + +.mapbox-gl-draw_ctrl-draw-btn { + border-color:rgba(0,0,0,0.9); + color:rgba(255,255,255,0.5); + width:30px; + height:30px; +} + +.mapbox-gl-draw_ctrl-draw-btn.active, +.mapbox-gl-draw_ctrl-draw-btn.active:hover { + background-color:rgb(0 0 0/5%); +} +.mapbox-gl-draw_ctrl-draw-btn { + background-repeat: no-repeat; + background-position: center; +} + +.mapbox-gl-draw_point { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m10 2c-3.3 0-6 2.7-6 6s6 9 6 9 6-5.7 6-9-2.7-6-6-6zm0 2c2.1 0 3.8 1.7 3.8 3.8 0 1.5-1.8 3.9-2.9 5.2h-1.7c-1.1-1.4-2.9-3.8-2.9-5.2-.1-2.1 1.6-3.8 3.7-3.8z"/>%3C/svg>'); +} +.mapbox-gl-draw_polygon { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m15 12.3v-4.6c.6-.3 1-1 1-1.7 0-1.1-.9-2-2-2-.7 0-1.4.4-1.7 1h-4.6c-.3-.6-1-1-1.7-1-1.1 0-2 .9-2 2 0 .7.4 1.4 1 1.7v4.6c-.6.3-1 1-1 1.7 0 1.1.9 2 2 2 .7 0 1.4-.4 1.7-1h4.6c.3.6 1 1 1.7 1 1.1 0 2-.9 2-2 0-.7-.4-1.4-1-1.7zm-8-.3v-4l1-1h4l1 1v4l-1 1h-4z"/>%3C/svg>'); +} +.mapbox-gl-draw_line { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m13.5 3.5c-1.4 0-2.5 1.1-2.5 2.5 0 .3 0 .6.2.9l-3.8 3.8c-.3-.1-.6-.2-.9-.2-1.4 0-2.5 1.1-2.5 2.5s1.1 2.5 2.5 2.5 2.5-1.1 2.5-2.5c0-.3 0-.6-.2-.9l3.8-3.8c.3.1.6.2.9.2 1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5z"/>%3C/svg>'); +} +.mapbox-gl-draw_trash { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="M10,3.4 c-0.8,0-1.5,0.5-1.8,1.2H5l-1,1v1h12v-1l-1-1h-3.2C11.5,3.9,10.8,3.4,10,3.4z M5,8v7c0,1,1,2,2,2h6c1,0,2-1,2-2V8h-2v5.5h-1.5V8h-3 v5.5H7V8H5z"/>%3C/svg>'); +} +.mapbox-gl-draw_uncombine { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="m12 2c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l1 1c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-1-1c-.2-.2-.4-.3-.7-.3zm4 4c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l1 1c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-1-1c-.2-.2-.4-.3-.7-.3zm-7 1c-1 0-1 1-.5 1.5.3.3 1 1 1 1l-1 1s-.5.5 0 1 1 0 1 0l1-1 1 1c.5.5 1.5.5 1.5-.5v-4zm-5 3c-.3 0-.5.1-.7.3l-1 1c-.4.4-.4 1 0 1.4l4.9 4.9c.4.4 1 .4 1.4 0l1-1c.4-.4.4-1 0-1.4l-4.9-4.9c-.1-.2-.4-.3-.7-.3z"/>%3C/svg>'); +} +.mapbox-gl-draw_combine { + background-image: url('data:image/svg+xml;utf8,%3Csvg xmlns="http://www.w3.org/2000/svg" width="20" height="20">%3Cpath d="M12.1,2c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l4.9,4.9c0.4,0.4,1,0.4,1.4,0l1-1 c0.4-0.4,0.4-1,0-1.4l-4.9-4.9C12.6,2.1,12.3,2,12.1,2z M8,8C7,8,7,9,7.5,9.5c0.3,0.3,1,1,1,1l-1,1c0,0-0.5,0.5,0,1s1,0,1,0l1-1l1,1 C11,13,12,13,12,12V8H8z M4,10c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l1,1c0.4,0.4,1,0.4,1.4,0l1-1c0.4-0.4,0.4-1,0-1.4 l-1-1C4.5,10.1,4.3,10,4,10z M8,14c-0.3,0-0.5,0.1-0.7,0.3l-1,1c-0.4,0.4-0.4,1,0,1.4l1,1c0.4,0.4,1,0.4,1.4,0l1-1 c0.4-0.4,0.4-1,0-1.4l-1-1C8.5,14.1,8.3,14,8,14z"/>%3C/svg>'); +} + +.mapboxgl-map.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: pointer; +} +.mapboxgl-map.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mouse-add .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: crosshair; +} +.mapboxgl-map.mouse-move.mode-direct_select .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: grab; + cursor: -moz-grab; + cursor: -webkit-grab; +} +.mapboxgl-map.mode-direct_select.feature-vertex.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mode-direct_select.feature-midpoint.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: cell; +} +.mapboxgl-map.mode-direct_select.feature-feature.mouse-move .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: move; +} +.mapboxgl-map.mode-static.mouse-pointer .mapboxgl-canvas-container.mapboxgl-interactive { + cursor: grab; + cursor: -moz-grab; + cursor: -webkit-grab; +} + +.mapbox-gl-draw_boxselect { + pointer-events: none; + position: absolute; + top: 0; + left: 0; + width: 0; + height: 0; + background: rgba(0,0,0,.1); + border: 2px dotted #fff; + opacity: 0.5; +} diff --git a/docs/articles/turf_files/mapbox-gl-draw-1.5.0/mapbox-gl-draw.js b/docs/articles/turf_files/mapbox-gl-draw-1.5.0/mapbox-gl-draw.js new file mode 100644 index 0000000..271f1f7 --- /dev/null +++ b/docs/articles/turf_files/mapbox-gl-draw-1.5.0/mapbox-gl-draw.js @@ -0,0 +1,2 @@ +var e,t;e=this,t=function(){const e=function(e,t){const o={drag:[],click:[],mousemove:[],mousedown:[],mouseup:[],mouseout:[],keydown:[],keyup:[],touchstart:[],touchmove:[],touchend:[],tap:[]},n={on(e,t,n){if(void 0===o[e])throw new Error(`Invalid event type: ${e}`);o[e].push({selector:t,fn:n})},render(e){t.store.featureChanged(e)}},r=function(e,r){const i=o[e];let s=i.length;for(;s--;){const e=i[s];if(e.selector(r)){e.fn.call(n,r)||t.store.render(),t.ui.updateMapClasses();break}}};return e.start.call(n),{render:e.render,stop(){e.stop&&e.stop()},trash(){e.trash&&(e.trash(),t.store.render())},combineFeatures(){e.combineFeatures&&e.combineFeatures()},uncombineFeatures(){e.uncombineFeatures&&e.uncombineFeatures()},drag(e){r("drag",e)},click(e){r("click",e)},mousemove(e){r("mousemove",e)},mousedown(e){r("mousedown",e)},mouseup(e){r("mouseup",e)},mouseout(e){r("mouseout",e)},keydown(e){r("keydown",e)},keyup(e){r("keyup",e)},touchstart(e){r("touchstart",e)},touchmove(e){r("touchmove",e)},touchend(e){r("touchend",e)},tap(e){r("tap",e)}}};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var o,n,r={},i={};function s(){return o||(o=1,i.RADIUS=6378137,i.FLATTENING=1/298.257223563,i.POLAR_RADIUS=6356752.3142),i}var a=function(){if(n)return r;n=1;var e=s();function t(e){var t=0;if(e&&e.length>0){t+=Math.abs(o(e[0]));for(var n=1;n2){for(c=0;c(e.geometry.type===h.POLYGON&&(e.area=c.geometry({type:h.FEATURE,property:{},geometry:e.geometry})),e))).sort(S).map((e=>(delete e.area,e)))}function L(e,t=0){return[[e.point.x-t,e.point.y-t],[e.point.x+t,e.point.y+t]]}function M(e){if(this._items={},this._nums={},this._length=e?e.length:0,e)for(let t=0,o=e.length;t{e.push({k:t,v:this._items[t]})})),Object.keys(this._nums).forEach((t=>{e.push({k:JSON.parse(t),v:this._nums[t]})})),e.sort(((e,t)=>e.v-t.v)).map((e=>e.k))},M.prototype.clear=function(){return this._length=0,this._items={},this._nums={},this};const N=[y.FEATURE,y.MIDPOINT,y.VERTEX];var b={click:function(e,t,o){return x(e,t,o,o.options.clickBuffer)},touch:function(e,t,o){return x(e,t,o,o.options.touchBuffer)}};function x(e,t,o,n){if(null===o.map)return[];const r=e?L(e,n):t,i={};o.options.styles&&(i.layers=o.options.styles.map((e=>e.id)).filter((e=>null!=o.map.getLayer(e))));const s=o.map.queryRenderedFeatures(r,i).filter((e=>-1!==N.indexOf(e.properties.meta))),a=new M,c=[];return s.forEach((e=>{const t=e.properties.id;a.has(t)||(a.add(t),c.push(e))})),O(c)}function A(e,t){const o=b.click(e,null,t),n={mouse:d.NONE};return o[0]&&(n.mouse=o[0].properties.active===E.ACTIVE?d.MOVE:d.POINTER,n.feature=o[0].properties.meta),-1!==t.events.currentModeName().indexOf("draw")&&(n.mouse=d.ADD),t.ui.queueMapClasses(n),t.ui.updateMapClasses(),o[0]}function P(e,t){const o=e.x-t.x,n=e.y-t.y;return Math.sqrt(o*o+n*n)}const F=4,R=12,w=500;function D(e,t,o={}){const n=null!=o.fineTolerance?o.fineTolerance:F,r=null!=o.grossTolerance?o.grossTolerance:R,i=null!=o.interval?o.interval:w;e.point=e.point||t.point,e.time=e.time||t.time;const s=P(e.point,t.point);return s(o=t)=>{let n="",r=0|o;for(;r--;)n+=e[Math.random()*e.length|0];return n})("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",32);function B(){return G()}const j=function(e,t){this.ctx=e,this.properties=t.properties||{},this.coordinates=t.geometry.coordinates,this.id=t.id||B(),this.type=t.geometry.type};j.prototype.changed=function(){this.ctx.store.featureChanged(this.id)},j.prototype.incomingCoords=function(e){this.setCoordinates(e)},j.prototype.setCoordinates=function(e){this.coordinates=e,this.changed()},j.prototype.getCoordinates=function(){return JSON.parse(JSON.stringify(this.coordinates))},j.prototype.setProperty=function(e,t){this.properties[e]=t},j.prototype.toGeoJSON=function(){return JSON.parse(JSON.stringify({id:this.id,type:h.FEATURE,properties:this.properties,geometry:{coordinates:this.getCoordinates(),type:this.type}}))},j.prototype.internal=function(e){const t={id:this.id,meta:y.FEATURE,"meta:type":this.type,active:E.INACTIVE,mode:e};if(this.ctx.options.userProperties)for(const e in this.properties)t[`user_${e}`]=this.properties[e];return{type:h.FEATURE,properties:t,geometry:{coordinates:this.getCoordinates(),type:this.type}}};const J=function(e,t){j.call(this,e,t)};(J.prototype=Object.create(j.prototype)).isValid=function(){return"number"==typeof this.coordinates[0]&&"number"==typeof this.coordinates[1]},J.prototype.updateCoordinate=function(e,t,o){this.coordinates=3===arguments.length?[t,o]:[e,t],this.changed()},J.prototype.getCoordinate=function(){return this.getCoordinates()};const $=function(e,t){j.call(this,e,t)};($.prototype=Object.create(j.prototype)).isValid=function(){return this.coordinates.length>1},$.prototype.addCoordinate=function(e,t,o){this.changed();const n=parseInt(e,10);this.coordinates.splice(n,0,[t,o])},$.prototype.getCoordinate=function(e){const t=parseInt(e,10);return JSON.parse(JSON.stringify(this.coordinates[t]))},$.prototype.removeCoordinate=function(e){this.changed(),this.coordinates.splice(parseInt(e,10),1)},$.prototype.updateCoordinate=function(e,t,o){const n=parseInt(e,10);this.coordinates[n]=[t,o],this.changed()};const Y=function(e,t){j.call(this,e,t),this.coordinates=this.coordinates.map((e=>e.slice(0,-1)))};(Y.prototype=Object.create(j.prototype)).isValid=function(){return 0!==this.coordinates.length&&this.coordinates.every((e=>e.length>2))},Y.prototype.incomingCoords=function(e){this.coordinates=e.map((e=>e.slice(0,-1))),this.changed()},Y.prototype.setCoordinates=function(e){this.coordinates=e,this.changed()},Y.prototype.addCoordinate=function(e,t,o){this.changed();const n=e.split(".").map((e=>parseInt(e,10)));this.coordinates[n[0]].splice(n[1],0,[t,o])},Y.prototype.removeCoordinate=function(e){this.changed();const t=e.split(".").map((e=>parseInt(e,10))),o=this.coordinates[t[0]];o&&(o.splice(t[1],1),o.length<3&&this.coordinates.splice(t[0],1))},Y.prototype.getCoordinate=function(e){const t=e.split(".").map((e=>parseInt(e,10))),o=this.coordinates[t[0]];return JSON.parse(JSON.stringify(o[t[1]]))},Y.prototype.getCoordinates=function(){return this.coordinates.map((e=>e.concat([e[0]])))},Y.prototype.updateCoordinate=function(e,t,o){this.changed();const n=e.split("."),r=parseInt(n[0],10),i=parseInt(n[1],10);void 0===this.coordinates[r]&&(this.coordinates[r]=[]),this.coordinates[r][i]=[t,o]};const H={MultiPoint:J,MultiLineString:$,MultiPolygon:Y},X=(e,t,o,n,r)=>{const i=o.split("."),s=parseInt(i[0],10),a=i[1]?i.slice(1).join("."):null;return e[s][t](a,n,r)},q=function(e,t){if(j.call(this,e,t),delete this.coordinates,this.model=H[t.geometry.type],void 0===this.model)throw new TypeError(`${t.geometry.type} is not a valid type`);this.features=this._coordinatesToFeatures(t.geometry.coordinates)};function Z(e){this.map=e.map,this.drawConfig=JSON.parse(JSON.stringify(e.options||{})),this._ctx=e}(q.prototype=Object.create(j.prototype))._coordinatesToFeatures=function(e){const t=this.model.bind(this);return e.map((e=>new t(this.ctx,{id:B(),type:h.FEATURE,properties:{},geometry:{coordinates:e,type:this.type.replace("Multi","")}})))},q.prototype.isValid=function(){return this.features.every((e=>e.isValid()))},q.prototype.setCoordinates=function(e){this.features=this._coordinatesToFeatures(e),this.changed()},q.prototype.getCoordinate=function(e){return X(this.features,"getCoordinate",e)},q.prototype.getCoordinates=function(){return JSON.parse(JSON.stringify(this.features.map((e=>e.type===h.POLYGON?e.getCoordinates():e.coordinates))))},q.prototype.updateCoordinate=function(e,t,o){X(this.features,"updateCoordinate",e,t,o),this.changed()},q.prototype.addCoordinate=function(e,t,o){X(this.features,"addCoordinate",e,t,o),this.changed()},q.prototype.removeCoordinate=function(e){X(this.features,"removeCoordinate",e),this.changed()},q.prototype.getFeatures=function(){return this.features},Z.prototype.setSelected=function(e){return this._ctx.store.setSelected(e)},Z.prototype.setSelectedCoordinates=function(e){this._ctx.store.setSelectedCoordinates(e),e.reduce(((e,t)=>(void 0===e[t.feature_id]&&(e[t.feature_id]=!0,this._ctx.store.get(t.feature_id).changed()),e)),{})},Z.prototype.getSelected=function(){return this._ctx.store.getSelected()},Z.prototype.getSelectedIds=function(){return this._ctx.store.getSelectedIds()},Z.prototype.isSelected=function(e){return this._ctx.store.isSelected(e)},Z.prototype.getFeature=function(e){return this._ctx.store.get(e)},Z.prototype.select=function(e){return this._ctx.store.select(e)},Z.prototype.deselect=function(e){return this._ctx.store.deselect(e)},Z.prototype.deleteFeature=function(e,t={}){return this._ctx.store.delete(e,t)},Z.prototype.addFeature=function(e,t={}){return this._ctx.store.add(e,t)},Z.prototype.clearSelectedFeatures=function(){return this._ctx.store.clearSelected()},Z.prototype.clearSelectedCoordinates=function(){return this._ctx.store.clearSelectedCoordinates()},Z.prototype.setActionableState=function(e={}){const t={trash:e.trash||!1,combineFeatures:e.combineFeatures||!1,uncombineFeatures:e.uncombineFeatures||!1};return this._ctx.events.actionable(t)},Z.prototype.changeMode=function(e,t={},o={}){return this._ctx.events.changeMode(e,t,o)},Z.prototype.fire=function(e,t){return this._ctx.events.fire(e,t)},Z.prototype.updateUIClasses=function(e){return this._ctx.ui.queueMapClasses(e)},Z.prototype.activateUIButton=function(e){return this._ctx.ui.setActiveButton(e)},Z.prototype.featuresAt=function(e,t,o="click"){if("click"!==o&&"touch"!==o)throw new Error("invalid buffer type");return b[o](e,t,this._ctx)},Z.prototype.newFeature=function(e){const t=e.geometry.type;return t===h.POINT?new J(this._ctx,e):t===h.LINE_STRING?new $(this._ctx,e):t===h.POLYGON?new Y(this._ctx,e):new q(this._ctx,e)},Z.prototype.isInstanceOf=function(e,t){if(e===h.POINT)return t instanceof J;if(e===h.LINE_STRING)return t instanceof $;if(e===h.POLYGON)return t instanceof Y;if("MultiFeature"===e)return t instanceof q;throw new Error(`Unknown feature class: ${e}`)},Z.prototype.doRender=function(e){return this._ctx.store.featureChanged(e)},Z.prototype.onSetup=function(){},Z.prototype.onDrag=function(){},Z.prototype.onClick=function(){},Z.prototype.onMouseMove=function(){},Z.prototype.onMouseDown=function(){},Z.prototype.onMouseUp=function(){},Z.prototype.onMouseOut=function(){},Z.prototype.onKeyUp=function(){},Z.prototype.onKeyDown=function(){},Z.prototype.onTouchStart=function(){},Z.prototype.onTouchMove=function(){},Z.prototype.onTouchEnd=function(){},Z.prototype.onTap=function(){},Z.prototype.onStop=function(){},Z.prototype.onTrash=function(){},Z.prototype.onCombineFeature=function(){},Z.prototype.onUncombineFeature=function(){},Z.prototype.toDisplayFeatures=function(){throw new Error("You must overwrite toDisplayFeatures")};const W={drag:"onDrag",click:"onClick",mousemove:"onMouseMove",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseout:"onMouseOut",keyup:"onKeyUp",keydown:"onKeyDown",touchstart:"onTouchStart",touchmove:"onTouchMove",touchend:"onTouchEnd",tap:"onTap"},K=Object.keys(W);function z(e){const t=Object.keys(e);return function(o,n={}){let r={};const i=t.reduce(((t,o)=>(t[o]=e[o],t)),new Z(o));return{start(){r=i.onSetup(n),K.forEach((t=>{const o=W[t];let n=()=>!1;var s;e[o]&&(n=()=>!0),this.on(t,n,(s=o,e=>i[s](r,e)))}))},stop(){i.onStop(r)},trash(){i.onTrash(r)},combineFeatures(){i.onCombineFeatures(r)},uncombineFeatures(){i.onUncombineFeatures(r)},render(e,t){i.toDisplayFeatures(r,e,t)}}}}function Q(e){return[].concat(e).filter((e=>void 0!==e))}function ee(){const e=this;if(!e.ctx.map||void 0===e.ctx.map.getSource(l.HOT))return a();const t=e.ctx.events.currentModeName();e.ctx.ui.queueMapClasses({mode:t});let o=[],n=[];e.isDirty?n=e.getAllIds():(o=e.getChangedIds().filter((t=>void 0!==e.get(t))),n=e.sources.hot.filter((t=>t.properties.id&&-1===o.indexOf(t.properties.id)&&void 0!==e.get(t.properties.id))).map((e=>e.properties.id))),e.sources.hot=[];const r=e.sources.cold.length;e.sources.cold=e.isDirty?[]:e.sources.cold.filter((e=>{const t=e.properties.id||e.properties.parent;return-1===o.indexOf(t)}));const i=r!==e.sources.cold.length||n.length>0;function s(o,n){const r=e.get(o).internal(t);e.ctx.events.currentModeRender(r,(o=>{o.properties.mode=t,e.sources[n].push(o)}))}function a(){e.isDirty=!1,e.clearChangedIds()}o.forEach((e=>s(e,"hot"))),n.forEach((e=>s(e,"cold"))),i&&e.ctx.map.getSource(l.COLD).setData({type:h.FEATURE_COLLECTION,features:e.sources.cold}),e.ctx.map.getSource(l.HOT).setData({type:h.FEATURE_COLLECTION,features:e.sources.hot}),a()}function te(e){let t;this._features={},this._featureIds=new M,this._selectedFeatureIds=new M,this._selectedCoordinates=[],this._changedFeatureIds=new M,this._emitSelectionChange=!1,this._mapInitialConfig={},this.ctx=e,this.sources={hot:[],cold:[]},this.render=()=>{t||(t=requestAnimationFrame((()=>{t=null,ee.call(this),this._emitSelectionChange&&(this.ctx.events.fire(g.SELECTION_CHANGE,{features:this.getSelected().map((e=>e.toGeoJSON())),points:this.getSelectedCoordinates().map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e.coordinates}})))}),this._emitSelectionChange=!1),this.ctx.events.fire(g.RENDER,{})})))},this.isDirty=!1}function oe(e,t={}){const o=e._selectedCoordinates.filter((t=>e._selectedFeatureIds.has(t.feature_id)));e._selectedCoordinates.length===o.length||t.silent||(e._emitSelectionChange=!0),e._selectedCoordinates=o}te.prototype.createRenderBatch=function(){const e=this.render;let t=0;return this.render=function(){t++},()=>{this.render=e,t>0&&this.render()}},te.prototype.setDirty=function(){return this.isDirty=!0,this},te.prototype.featureCreated=function(e,t={}){if(this._changedFeatureIds.add(e),!0!==(null!=t.silent?t.silent:this.ctx.options.suppressAPIEvents)){const t=this.get(e);this.ctx.events.fire(g.CREATE,{features:[t.toGeoJSON()]})}return this},te.prototype.featureChanged=function(e,t={}){return this._changedFeatureIds.add(e),!0!==(null!=t.silent?t.silent:this.ctx.options.suppressAPIEvents)&&this.ctx.events.fire(g.UPDATE,{action:t.action?t.action:m.CHANGE_COORDINATES,features:[this.get(e).toGeoJSON()]}),this},te.prototype.getChangedIds=function(){return this._changedFeatureIds.values()},te.prototype.clearChangedIds=function(){return this._changedFeatureIds.clear(),this},te.prototype.getAllIds=function(){return this._featureIds.values()},te.prototype.add=function(e,t={}){return this._features[e.id]=e,this._featureIds.add(e.id),this.featureCreated(e.id,{silent:t.silent}),this},te.prototype.delete=function(e,t={}){const o=[];return Q(e).forEach((e=>{this._featureIds.has(e)&&(this._featureIds.delete(e),this._selectedFeatureIds.delete(e),t.silent||-1===o.indexOf(this._features[e])&&o.push(this._features[e].toGeoJSON()),delete this._features[e],this.isDirty=!0)})),o.length&&this.ctx.events.fire(g.DELETE,{features:o}),oe(this,t),this},te.prototype.get=function(e){return this._features[e]},te.prototype.getAll=function(){return Object.keys(this._features).map((e=>this._features[e]))},te.prototype.select=function(e,t={}){return Q(e).forEach((e=>{this._selectedFeatureIds.has(e)||(this._selectedFeatureIds.add(e),this._changedFeatureIds.add(e),t.silent||(this._emitSelectionChange=!0))})),this},te.prototype.deselect=function(e,t={}){return Q(e).forEach((e=>{this._selectedFeatureIds.has(e)&&(this._selectedFeatureIds.delete(e),this._changedFeatureIds.add(e),t.silent||(this._emitSelectionChange=!0))})),oe(this,t),this},te.prototype.clearSelected=function(e={}){return this.deselect(this._selectedFeatureIds.values(),{silent:e.silent}),this},te.prototype.setSelected=function(e,t={}){return e=Q(e),this.deselect(this._selectedFeatureIds.values().filter((t=>-1===e.indexOf(t))),{silent:t.silent}),this.select(e.filter((e=>!this._selectedFeatureIds.has(e))),{silent:t.silent}),this},te.prototype.setSelectedCoordinates=function(e){return this._selectedCoordinates=e,this._emitSelectionChange=!0,this},te.prototype.clearSelectedCoordinates=function(){return this._selectedCoordinates=[],this._emitSelectionChange=!0,this},te.prototype.getSelectedIds=function(){return this._selectedFeatureIds.values()},te.prototype.getSelected=function(){return this.getSelectedIds().map((e=>this.get(e)))},te.prototype.getSelectedCoordinates=function(){return this._selectedCoordinates.map((e=>({coordinates:this.get(e.feature_id).getCoordinate(e.coord_path)})))},te.prototype.isSelected=function(e){return this._selectedFeatureIds.has(e)},te.prototype.setFeatureProperty=function(e,t,o,n={}){this.get(e).setProperty(t,o),this.featureChanged(e,{silent:n.silent,action:m.CHANGE_PROPERTIES})},te.prototype.storeMapConfig=function(){T.forEach((e=>{this.ctx.map[e]&&(this._mapInitialConfig[e]=this.ctx.map[e].isEnabled())}))},te.prototype.restoreMapConfig=function(){Object.keys(this._mapInitialConfig).forEach((e=>{this._mapInitialConfig[e]?this.ctx.map[e].enable():this.ctx.map[e].disable()}))},te.prototype.getInitialConfigValue=function(e){return void 0===this._mapInitialConfig[e]||this._mapInitialConfig[e]};const ne=["mode","feature","mouse"];function re(t){let o=null,n=null;const r={onRemove(){return t.map.off("load",r.connect),clearInterval(n),r.removeLayers(),t.store.restoreMapConfig(),t.ui.removeButtons(),t.events.removeEventListeners(),t.ui.clearMapClasses(),t.boxZoomInitial&&t.map.boxZoom.enable(),t.map=null,t.container=null,t.store=null,o&&o.parentNode&&o.parentNode.removeChild(o),o=null,this},connect(){t.map.off("load",r.connect),clearInterval(n),r.addLayers(),t.store.storeMapConfig(),t.events.addEventListeners()},onAdd(i){if(t.map=i,t.events=function(t){const o=Object.keys(t.options.modes).reduce(((e,o)=>(e[o]=z(t.options.modes[o]),e)),{});let n={},r={};const i={};let s=null,a=null;i.drag=function(e,o){o({point:e.point,time:(new Date).getTime()})?(t.ui.queueMapClasses({mouse:d.DRAG}),a.drag(e)):e.originalEvent.stopPropagation()},i.mousedrag=function(e){i.drag(e,(e=>!D(n,e)))},i.touchdrag=function(e){i.drag(e,(e=>!V(r,e)))},i.mousemove=function(e){if(1===(void 0!==e.originalEvent.buttons?e.originalEvent.buttons:e.originalEvent.which))return i.mousedrag(e);const o=A(e,t);e.featureTarget=o,a.mousemove(e)},i.mousedown=function(e){n={time:(new Date).getTime(),point:e.point};const o=A(e,t);e.featureTarget=o,a.mousedown(e)},i.mouseup=function(e){const o=A(e,t);e.featureTarget=o,D(n,{point:e.point,time:(new Date).getTime()})?a.click(e):a.mouseup(e)},i.mouseout=function(e){a.mouseout(e)},i.touchstart=function(e){if(!t.options.touchEnabled)return;r={time:(new Date).getTime(),point:e.point};const o=b.touch(e,null,t)[0];e.featureTarget=o,a.touchstart(e)},i.touchmove=function(e){if(t.options.touchEnabled)return a.touchmove(e),i.touchdrag(e)},i.touchend=function(e){if(e.originalEvent.preventDefault(),!t.options.touchEnabled)return;const o=b.touch(e,null,t)[0];e.featureTarget=o,V(r,{time:(new Date).getTime(),point:e.point})?a.tap(e):a.touchend(e)};const c=e=>!(8===e||46===e||e>=48&&e<=57);function l(n,r,i={}){a.stop();const c=o[n];if(void 0===c)throw new Error(`${n} is not valid`);s=n;const u=c(t,r);a=e(u,t),i.silent||t.map.fire(g.MODE_CHANGE,{mode:n}),t.store.setDirty(),t.store.render()}i.keydown=function(e){(e.srcElement||e.target).classList.contains(u.CANVAS)&&(8!==e.keyCode&&46!==e.keyCode||!t.options.controls.trash?c(e.keyCode)?a.keydown(e):49===e.keyCode&&t.options.controls.point?l(f.DRAW_POINT):50===e.keyCode&&t.options.controls.line_string?l(f.DRAW_LINE_STRING):51===e.keyCode&&t.options.controls.polygon&&l(f.DRAW_POLYGON):(e.preventDefault(),a.trash()))},i.keyup=function(e){c(e.keyCode)&&a.keyup(e)},i.zoomend=function(){t.store.changeZoom()},i.data=function(e){if("style"===e.dataType){const{setup:e,map:o,options:n,store:r}=t;n.styles.some((e=>o.getLayer(e.id)))||(e.addLayers(),r.setDirty(),r.render())}};const p={trash:!1,combineFeatures:!1,uncombineFeatures:!1};return{start(){s=t.options.defaultMode,a=e(o[s](t),t)},changeMode:l,actionable:function(e){let o=!1;Object.keys(e).forEach((t=>{if(void 0===p[t])throw new Error("Invalid action type");p[t]!==e[t]&&(o=!0),p[t]=e[t]})),o&&t.map.fire(g.ACTIONABLE,{actions:p})},currentModeName:()=>s,currentModeRender:(e,t)=>a.render(e,t),fire(e,o){t.map&&t.map.fire(e,o)},addEventListeners(){t.map.on("mousemove",i.mousemove),t.map.on("mousedown",i.mousedown),t.map.on("mouseup",i.mouseup),t.map.on("data",i.data),t.map.on("touchmove",i.touchmove),t.map.on("touchstart",i.touchstart),t.map.on("touchend",i.touchend),t.container.addEventListener("mouseout",i.mouseout),t.options.keybindings&&(t.container.addEventListener("keydown",i.keydown),t.container.addEventListener("keyup",i.keyup))},removeEventListeners(){t.map.off("mousemove",i.mousemove),t.map.off("mousedown",i.mousedown),t.map.off("mouseup",i.mouseup),t.map.off("data",i.data),t.map.off("touchmove",i.touchmove),t.map.off("touchstart",i.touchstart),t.map.off("touchend",i.touchend),t.container.removeEventListener("mouseout",i.mouseout),t.options.keybindings&&(t.container.removeEventListener("keydown",i.keydown),t.container.removeEventListener("keyup",i.keyup))},trash(e){a.trash(e)},combineFeatures(){a.combineFeatures()},uncombineFeatures(){a.uncombineFeatures()},getMode:()=>s}}(t),t.ui=function(e){const t={};let o=null,n={mode:null,feature:null,mouse:null},r={mode:null,feature:null,mouse:null};function i(e){r=Object.assign(r,e)}function s(){if(!e.container)return;const t=[],o=[];ne.forEach((e=>{r[e]!==n[e]&&(t.push(`${e}-${n[e]}`),null!==r[e]&&o.push(`${e}-${r[e]}`))})),t.length>0&&e.container.classList.remove(...t),o.length>0&&e.container.classList.add(...o),n=Object.assign(n,r)}function a(e,t={}){const n=document.createElement("button");return n.className=`${u.CONTROL_BUTTON} ${t.className}`,n.setAttribute("title",t.title),t.container.appendChild(n),n.addEventListener("click",(n=>{if(n.preventDefault(),n.stopPropagation(),n.target===o)return c(),void t.onDeactivate();l(e),t.onActivate()}),!0),n}function c(){o&&(o.classList.remove(u.ACTIVE_BUTTON),o=null)}function l(e){c();const n=t[e];n&&n&&"trash"!==e&&(n.classList.add(u.ACTIVE_BUTTON),o=n)}return{setActiveButton:l,queueMapClasses:i,updateMapClasses:s,clearMapClasses:function(){i({mode:null,feature:null,mouse:null}),s()},addButtons:function(){const o=e.options.controls,n=document.createElement("div");return n.className=`${u.CONTROL_GROUP} ${u.CONTROL_BASE}`,o?(o[p.LINE]&&(t[p.LINE]=a(p.LINE,{container:n,className:u.CONTROL_BUTTON_LINE,title:"LineString tool "+(e.options.keybindings?"(l)":""),onActivate:()=>e.events.changeMode(f.DRAW_LINE_STRING),onDeactivate:()=>e.events.trash()})),o[p.POLYGON]&&(t[p.POLYGON]=a(p.POLYGON,{container:n,className:u.CONTROL_BUTTON_POLYGON,title:"Polygon tool "+(e.options.keybindings?"(p)":""),onActivate:()=>e.events.changeMode(f.DRAW_POLYGON),onDeactivate:()=>e.events.trash()})),o[p.POINT]&&(t[p.POINT]=a(p.POINT,{container:n,className:u.CONTROL_BUTTON_POINT,title:"Marker tool "+(e.options.keybindings?"(m)":""),onActivate:()=>e.events.changeMode(f.DRAW_POINT),onDeactivate:()=>e.events.trash()})),o.trash&&(t.trash=a("trash",{container:n,className:u.CONTROL_BUTTON_TRASH,title:"Delete",onActivate:()=>{e.events.trash()}})),o.combine_features&&(t.combine_features=a("combineFeatures",{container:n,className:u.CONTROL_BUTTON_COMBINE_FEATURES,title:"Combine",onActivate:()=>{e.events.combineFeatures()}})),o.uncombine_features&&(t.uncombine_features=a("uncombineFeatures",{container:n,className:u.CONTROL_BUTTON_UNCOMBINE_FEATURES,title:"Uncombine",onActivate:()=>{e.events.uncombineFeatures()}})),n):n},removeButtons:function(){Object.keys(t).forEach((e=>{const o=t[e];o.parentNode&&o.parentNode.removeChild(o),delete t[e]}))}}}(t),t.container=i.getContainer(),t.store=new te(t),o=t.ui.addButtons(),t.options.boxSelect){t.boxZoomInitial=i.boxZoom.isEnabled(),i.boxZoom.disable();const e=i.dragPan.isEnabled();i.dragPan.disable(),i.dragPan.enable(),e||i.dragPan.disable()}return i.loaded()?r.connect():(i.on("load",r.connect),n=setInterval((()=>{i.loaded()&&r.connect()}),16)),t.events.start(),o},addLayers(){t.map.addSource(l.COLD,{data:{type:h.FEATURE_COLLECTION,features:[]},type:"geojson"}),t.map.addSource(l.HOT,{data:{type:h.FEATURE_COLLECTION,features:[]},type:"geojson"}),t.options.styles.forEach((e=>{t.map.addLayer(e)})),t.store.setDirty(!0),t.store.render()},removeLayers(){t.options.styles.forEach((e=>{t.map.getLayer(e.id)&&t.map.removeLayer(e.id)})),t.map.getSource(l.COLD)&&t.map.removeSource(l.COLD),t.map.getSource(l.HOT)&&t.map.removeSource(l.HOT)}};return t.setup=r,r}const ie="#3bb2d0",se="#fbb03b",ae="#fff";var ce=[{id:"gl-draw-polygon-fill",type:"fill",filter:["all",["==","$type","Polygon"]],paint:{"fill-color":["case",["==",["get","active"],"true"],se,ie],"fill-opacity":.1}},{id:"gl-draw-lines",type:"line",filter:["any",["==","$type","LineString"],["==","$type","Polygon"]],layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":["case",["==",["get","active"],"true"],se,ie],"line-dasharray":["case",["==",["get","active"],"true"],[.2,2],[2,0]],"line-width":2}},{id:"gl-draw-point-outer",type:"circle",filter:["all",["==","$type","Point"],["==","meta","feature"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],7,5],"circle-color":ae}},{id:"gl-draw-point-inner",type:"circle",filter:["all",["==","$type","Point"],["==","meta","feature"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],5,3],"circle-color":["case",["==",["get","active"],"true"],se,ie]}},{id:"gl-draw-vertex-outer",type:"circle",filter:["all",["==","$type","Point"],["==","meta","vertex"],["!=","mode","simple_select"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],7,5],"circle-color":ae}},{id:"gl-draw-vertex-inner",type:"circle",filter:["all",["==","$type","Point"],["==","meta","vertex"],["!=","mode","simple_select"]],paint:{"circle-radius":["case",["==",["get","active"],"true"],5,3],"circle-color":se}},{id:"gl-draw-midpoint",type:"circle",filter:["all",["==","meta","midpoint"]],paint:{"circle-radius":3,"circle-color":se}}];function ue(e){return function(t){const o=t.featureTarget;return!!o&&!!o.properties&&o.properties.meta===e}}function le(e){return!!e.originalEvent&&!!e.originalEvent.shiftKey&&0===e.originalEvent.button}function de(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.active===E.ACTIVE&&e.featureTarget.properties.meta===y.FEATURE}function pe(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.active===E.INACTIVE&&e.featureTarget.properties.meta===y.FEATURE}function he(e){return void 0===e.featureTarget}function fe(e){return!!e.featureTarget&&!!e.featureTarget.properties&&e.featureTarget.properties.meta===y.FEATURE}function ge(e){const t=e.featureTarget;return!!t&&!!t.properties&&t.properties.meta===y.VERTEX}function me(e){return!!e.originalEvent&&!0===e.originalEvent.shiftKey}function ye(e){return 27===e.keyCode}function Ee(e){return 13===e.keyCode}var Te=Object.freeze({__proto__:null,isActiveFeature:de,isEnterKey:Ee,isEscapeKey:ye,isFeature:fe,isInactiveFeature:pe,isOfMetaType:ue,isShiftDown:me,isShiftMousedown:le,isTrue:function(){return!0},isVertex:ge,noTarget:he});function Ce(e,t){this.x=e,this.y=t}function _e(e,t){const o=t.getBoundingClientRect();return new Ce(e.clientX-o.left-(t.clientLeft||0),e.clientY-o.top-(t.clientTop||0))}function ve(e,t,o,n){return{type:h.FEATURE,properties:{meta:y.VERTEX,parent:e,coord_path:o,active:n?E.ACTIVE:E.INACTIVE},geometry:{type:h.POINT,coordinates:t}}}function Ie(e,t,o){const n=t.geometry.coordinates,r=o.geometry.coordinates;if(n[1]>_||n[1]_||r[1]{const u=null!=o?`${o}.${a}`:String(a),l=ve(i,e,u,c(u));if(t.midpoints&&r){const e=Ie(i,r,l);e&&s.push(e)}r=l;const d=JSON.stringify(e);n!==d&&s.push(l),0===a&&(n=d)}))}function c(e){return!!t.selectedPaths&&-1!==t.selectedPaths.indexOf(e)}return n===h.POINT?s.push(ve(i,r,o,c(o))):n===h.POLYGON?r.forEach(((e,t)=>{a(e,null!==o?`${o}.${t}`:String(t))})):n===h.LINE_STRING?a(r,o):0===n.indexOf(h.MULTI_PREFIX)&&function(){const o=n.replace(h.MULTI_PREFIX,"");r.forEach(((n,r)=>{const i={type:h.FEATURE,properties:e.properties,geometry:{type:o,coordinates:n}};s=s.concat(Se(i,t,r))}))}(),s}Ce.prototype={clone(){return new Ce(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){const t=e.x-this.x,o=e.y-this.y;return t*t+o*o},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){const t=e[0]*this.x+e[1]*this.y,o=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=o,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){const e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){const t=Math.cos(e),o=Math.sin(e),n=t*this.x-o*this.y,r=o*this.x+t*this.y;return this.x=n,this.y=r,this},_rotateAround(e,t){const o=Math.cos(e),n=Math.sin(e),r=t.x+o*(this.x-t.x)-n*(this.y-t.y),i=t.y+n*(this.x-t.x)+o*(this.y-t.y);return this.x=r,this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:Ce},Ce.convert=function(e){if(e instanceof Ce)return e;if(Array.isArray(e))return new Ce(+e[0],+e[1]);if(void 0!==e.x&&void 0!==e.y)return new Ce(+e.x,+e.y);throw new Error("Expected [x, y] or {x, y} point format")};var Oe={enable(e){setTimeout((()=>{e.map&&e.map.doubleClickZoom&&e._ctx&&e._ctx.store&&e._ctx.store.getInitialConfigValue&&e._ctx.store.getInitialConfigValue("doubleClickZoom")&&e.map.doubleClickZoom.enable()}),0)},disable(e){setTimeout((()=>{e.map&&e.map.doubleClickZoom&&e.map.doubleClickZoom.disable()}),0)}};const{LAT_MIN:Le,LAT_MAX:Me,LAT_RENDERED_MIN:Ne,LAT_RENDERED_MAX:be,LNG_MIN:xe,LNG_MAX:Ae}=v;function Pe(e,t){let o=Le,n=Me,r=Le,i=Me,s=Ae,a=xe;e.forEach((e=>{const t=function(e){const t={Point:0,LineString:1,Polygon:2,MultiPoint:1,MultiLineString:2,MultiPolygon:3}[e.geometry.type],o=[e.geometry.coordinates].flat(t),n=o.map((e=>e[0])),r=o.map((e=>e[1])),i=e=>Math.min.apply(null,e),s=e=>Math.max.apply(null,e);return[i(n),i(r),s(n),s(r)]}(e),c=t[1],u=t[3],l=t[0],d=t[2];c>o&&(o=c),ur&&(r=u),ca&&(a=d)}));const c=t;return o+c.lat>be&&(c.lat=be-o),r+c.lat>Me&&(c.lat=Me-r),n+c.lat=Ae&&(c.lng-=360*Math.ceil(Math.abs(c.lng)/360)),c}function Fe(e,t){const o=Pe(e.map((e=>e.toGeoJSON())),t);e.forEach((e=>{const t=e.getCoordinates(),n=e=>{const t={lng:e[0]+o.lng,lat:e[1]+o.lat};return[t.lng,t.lat]},r=e=>e.map((e=>n(e))),i=e=>e.map((e=>r(e)));let s;e.type===h.POINT?s=n(t):e.type===h.LINE_STRING||e.type===h.MULTI_POINT?s=t.map(n):e.type===h.POLYGON||e.type===h.MULTI_LINE_STRING?s=t.map(r):e.type===h.MULTI_POLYGON&&(s=t.map(i)),e.incomingCoords(s)}))}const Re={onSetup:function(e){const t={dragMoveLocation:null,boxSelectStartLocation:null,boxSelectElement:void 0,boxSelecting:!1,canBoxSelect:!1,dragMoving:!1,canDragMove:!1,initialDragPanState:this.map.dragPan.isEnabled(),initiallySelectedFeatureIds:e.featureIds||[]};return this.setSelected(t.initiallySelectedFeatureIds.filter((e=>void 0!==this.getFeature(e)))),this.fireActionable(),this.setActionableState({combineFeatures:!0,uncombineFeatures:!0,trash:!0}),t},fireUpdate:function(){this.fire(g.UPDATE,{action:m.MOVE,features:this.getSelected().map((e=>e.toGeoJSON()))})},fireActionable:function(){const e=this.getSelected(),t=e.filter((e=>this.isInstanceOf("MultiFeature",e)));let o=!1;if(e.length>1){o=!0;const t=e[0].type.replace("Multi","");e.forEach((e=>{e.type.replace("Multi","")!==t&&(o=!1)}))}const n=t.length>0,r=e.length>0;this.setActionableState({combineFeatures:o,uncombineFeatures:n,trash:r})},getUniqueIds:function(e){return e.length?e.map((e=>e.properties.id)).filter((e=>void 0!==e)).reduce(((e,t)=>(e.add(t),e)),new M).values():[]},stopExtendedInteractions:function(e){e.boxSelectElement&&(e.boxSelectElement.parentNode&&e.boxSelectElement.parentNode.removeChild(e.boxSelectElement),e.boxSelectElement=null),(e.canDragMove||e.canBoxSelect)&&!0===e.initialDragPanState&&this.map.dragPan.enable(),e.boxSelecting=!1,e.canBoxSelect=!1,e.dragMoving=!1,e.canDragMove=!1},onStop:function(){Oe.enable(this)},onMouseMove:function(e,t){return fe(t)&&e.dragMoving&&this.fireUpdate(),this.stopExtendedInteractions(e),!0},onMouseOut:function(e){return!e.dragMoving||this.fireUpdate()}};Re.onTap=Re.onClick=function(e,t){return he(t)?this.clickAnywhere(e,t):ue(y.VERTEX)(t)?this.clickOnVertex(e,t):fe(t)?this.clickOnFeature(e,t):void 0},Re.clickAnywhere=function(e){const t=this.getSelectedIds();t.length&&(this.clearSelectedFeatures(),t.forEach((e=>this.doRender(e)))),Oe.enable(this),this.stopExtendedInteractions(e)},Re.clickOnVertex=function(e,t){this.changeMode(f.DIRECT_SELECT,{featureId:t.featureTarget.properties.parent,coordPath:t.featureTarget.properties.coord_path,startPos:t.lngLat}),this.updateUIClasses({mouse:d.MOVE})},Re.startOnActiveFeature=function(e,t){this.stopExtendedInteractions(e),this.map.dragPan.disable(),this.doRender(t.featureTarget.properties.id),e.canDragMove=!0,e.dragMoveLocation=t.lngLat},Re.clickOnFeature=function(e,t){Oe.disable(this),this.stopExtendedInteractions(e);const o=me(t),n=this.getSelectedIds(),r=t.featureTarget.properties.id,i=this.isSelected(r);if(!o&&i&&this.getFeature(r).type!==h.POINT)return this.changeMode(f.DIRECT_SELECT,{featureId:r});i&&o?(this.deselect(r),this.updateUIClasses({mouse:d.POINTER}),1===n.length&&Oe.enable(this)):!i&&o?(this.select(r),this.updateUIClasses({mouse:d.MOVE})):i||o||(n.forEach((e=>this.doRender(e))),this.setSelected(r),this.updateUIClasses({mouse:d.MOVE})),this.doRender(r)},Re.onMouseDown=function(e,t){return e.initialDragPanState=this.map.dragPan.isEnabled(),de(t)?this.startOnActiveFeature(e,t):this.drawConfig.boxSelect&&le(t)?this.startBoxSelect(e,t):void 0},Re.startBoxSelect=function(e,t){this.stopExtendedInteractions(e),this.map.dragPan.disable(),e.boxSelectStartLocation=_e(t.originalEvent,this.map.getContainer()),e.canBoxSelect=!0},Re.onTouchStart=function(e,t){if(de(t))return this.startOnActiveFeature(e,t)},Re.onDrag=function(e,t){return e.canDragMove?this.dragMove(e,t):this.drawConfig.boxSelect&&e.canBoxSelect?this.whileBoxSelect(e,t):void 0},Re.whileBoxSelect=function(e,t){e.boxSelecting=!0,this.updateUIClasses({mouse:d.ADD}),e.boxSelectElement||(e.boxSelectElement=document.createElement("div"),e.boxSelectElement.classList.add(u.BOX_SELECT),this.map.getContainer().appendChild(e.boxSelectElement));const o=_e(t.originalEvent,this.map.getContainer()),n=Math.min(e.boxSelectStartLocation.x,o.x),r=Math.max(e.boxSelectStartLocation.x,o.x),i=Math.min(e.boxSelectStartLocation.y,o.y),s=Math.max(e.boxSelectStartLocation.y,o.y),a=`translate(${n}px, ${i}px)`;e.boxSelectElement.style.transform=a,e.boxSelectElement.style.WebkitTransform=a,e.boxSelectElement.style.width=r-n+"px",e.boxSelectElement.style.height=s-i+"px"},Re.dragMove=function(e,t){e.dragMoving=!0,t.originalEvent.stopPropagation();const o={lng:t.lngLat.lng-e.dragMoveLocation.lng,lat:t.lngLat.lat-e.dragMoveLocation.lat};Fe(this.getSelected(),o),e.dragMoveLocation=t.lngLat},Re.onTouchEnd=Re.onMouseUp=function(e,t){if(e.dragMoving)this.fireUpdate();else if(e.boxSelecting){const o=[e.boxSelectStartLocation,_e(t.originalEvent,this.map.getContainer())],n=this.featuresAt(null,o,"click"),r=this.getUniqueIds(n).filter((e=>!this.isSelected(e)));r.length&&(this.select(r),r.forEach((e=>this.doRender(e))),this.updateUIClasses({mouse:d.MOVE}))}this.stopExtendedInteractions(e)},Re.toDisplayFeatures=function(e,t,o){t.properties.active=this.isSelected(t.properties.id)?E.ACTIVE:E.INACTIVE,o(t),this.fireActionable(),t.properties.active===E.ACTIVE&&t.geometry.type!==h.POINT&&Se(t).forEach(o)},Re.onTrash=function(){this.deleteFeature(this.getSelectedIds()),this.fireActionable()},Re.onCombineFeatures=function(){const e=this.getSelected();if(0===e.length||e.length<2)return;const t=[],o=[],n=e[0].type.replace("Multi","");for(let r=0;r{t.push(e)})):t.push(i.getCoordinates()),o.push(i.toGeoJSON())}if(o.length>1){const e=this.newFeature({type:h.FEATURE,properties:o[0].properties,geometry:{type:`Multi${n}`,coordinates:t}});this.addFeature(e),this.deleteFeature(this.getSelectedIds(),{silent:!0}),this.setSelected([e.id]),this.fire(g.COMBINE_FEATURES,{createdFeatures:[e.toGeoJSON()],deletedFeatures:o})}this.fireActionable()},Re.onUncombineFeatures=function(){const e=this.getSelected();if(0===e.length)return;const t=[],o=[];for(let n=0;n{this.addFeature(e),e.properties=r.properties,t.push(e.toGeoJSON()),this.select([e.id])})),this.deleteFeature(r.id,{silent:!0}),o.push(r.toGeoJSON()))}t.length>1&&this.fire(g.UNCOMBINE_FEATURES,{createdFeatures:t,deletedFeatures:o}),this.fireActionable()};const we=ue(y.VERTEX),De=ue(y.MIDPOINT),Ue={fireUpdate:function(){this.fire(g.UPDATE,{action:m.CHANGE_COORDINATES,features:this.getSelected().map((e=>e.toGeoJSON()))})},fireActionable:function(e){this.setActionableState({combineFeatures:!1,uncombineFeatures:!1,trash:e.selectedCoordPaths.length>0})},startDragging:function(e,t){e.initialDragPanState=this.map.dragPan.isEnabled(),this.map.dragPan.disable(),e.canDragMove=!0,e.dragMoveLocation=t.lngLat},stopDragging:function(e){e.canDragMove&&!0===e.initialDragPanState&&this.map.dragPan.enable(),e.dragMoving=!1,e.canDragMove=!1,e.dragMoveLocation=null},onVertex:function(e,t){this.startDragging(e,t);const o=t.featureTarget.properties,n=e.selectedCoordPaths.indexOf(o.coord_path);me(t)||-1!==n?me(t)&&-1===n&&e.selectedCoordPaths.push(o.coord_path):e.selectedCoordPaths=[o.coord_path];const r=this.pathsToCoordinates(e.featureId,e.selectedCoordPaths);this.setSelectedCoordinates(r)},onMidpoint:function(e,t){this.startDragging(e,t);const o=t.featureTarget.properties;e.feature.addCoordinate(o.coord_path,o.lng,o.lat),this.fireUpdate(),e.selectedCoordPaths=[o.coord_path]},pathsToCoordinates:function(e,t){return t.map((t=>({feature_id:e,coord_path:t})))},onFeature:function(e,t){0===e.selectedCoordPaths.length?this.startDragging(e,t):this.stopDragging(e)},dragFeature:function(e,t,o){Fe(this.getSelected(),o),e.dragMoveLocation=t.lngLat},dragVertex:function(e,t,o){const n=e.selectedCoordPaths.map((t=>e.feature.getCoordinate(t))),r=Pe(n.map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e}}))),o);for(let t=0;tt.localeCompare(e,"en",{numeric:!0}))).forEach((t=>e.feature.removeCoordinate(t))),this.fireUpdate(),e.selectedCoordPaths=[],this.clearSelectedCoordinates(),this.fireActionable(e),!1===e.feature.isValid()&&(this.deleteFeature([e.featureId]),this.changeMode(f.SIMPLE_SELECT,{}))},onMouseMove:function(e,t){const o=de(t),n=we(t),r=De(t),i=0===e.selectedCoordPaths.length;return o&&i||n&&!i?this.updateUIClasses({mouse:d.MOVE}):this.updateUIClasses({mouse:d.NONE}),(n||o||r)&&e.dragMoving&&this.fireUpdate(),this.stopDragging(e),!0},onMouseOut:function(e){return e.dragMoving&&this.fireUpdate(),!0}};Ue.onTouchStart=Ue.onMouseDown=function(e,t){return we(t)?this.onVertex(e,t):de(t)?this.onFeature(e,t):De(t)?this.onMidpoint(e,t):void 0},Ue.onDrag=function(e,t){if(!0!==e.canDragMove)return;e.dragMoving=!0,t.originalEvent.stopPropagation();const o={lng:t.lngLat.lng-e.dragMoveLocation.lng,lat:t.lngLat.lat-e.dragMoveLocation.lat};e.selectedCoordPaths.length>0?this.dragVertex(e,t,o):this.dragFeature(e,t,o),e.dragMoveLocation=t.lngLat},Ue.onClick=function(e,t){return he(t)?this.clickNoTarget(e,t):de(t)?this.clickActiveFeature(e,t):pe(t)?this.clickInactive(e,t):void this.stopDragging(e)},Ue.onTap=function(e,t){return he(t)?this.clickNoTarget(e,t):de(t)?this.clickActiveFeature(e,t):pe(t)?this.clickInactive(e,t):void 0},Ue.onTouchEnd=Ue.onMouseUp=function(e){e.dragMoving&&this.fireUpdate(),this.stopDragging(e)};const ke={};function Ve(e,t){return!!e.lngLat&&e.lngLat.lng===t[0]&&e.lngLat.lat===t[1]}ke.onSetup=function(){const e=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:[]}});return this.addFeature(e),this.clearSelectedFeatures(),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.POINT),this.setActionableState({trash:!0}),{point:e}},ke.stopDrawingAndRemove=function(e){this.deleteFeature([e.point.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)},ke.onTap=ke.onClick=function(e,t){this.updateUIClasses({mouse:d.MOVE}),e.point.updateCoordinate("",t.lngLat.lng,t.lngLat.lat),this.fire(g.CREATE,{features:[e.point.toGeoJSON()]}),this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.point.id]})},ke.onStop=function(e){this.activateUIButton(),e.point.getCoordinate().length||this.deleteFeature([e.point.id],{silent:!0})},ke.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.point.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t)},ke.onTrash=ke.stopDrawingAndRemove,ke.onKeyUp=function(e,t){if(ye(t)||Ee(t))return this.stopDrawingAndRemove(e,t)};const Ge={onSetup:function(){const e=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.POLYGON,coordinates:[[]]}});return this.addFeature(e),this.clearSelectedFeatures(),Oe.disable(this),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.POLYGON),this.setActionableState({trash:!0}),{polygon:e,currentVertexPosition:0}},clickAnywhere:function(e,t){if(e.currentVertexPosition>0&&Ve(t,e.polygon.coordinates[0][e.currentVertexPosition-1]))return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]});this.updateUIClasses({mouse:d.ADD}),e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat),e.currentVertexPosition++,e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat)},clickOnVertex:function(e){return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]})},onMouseMove:function(e,t){e.polygon.updateCoordinate(`0.${e.currentVertexPosition}`,t.lngLat.lng,t.lngLat.lat),ge(t)&&this.updateUIClasses({mouse:d.POINTER})}};Ge.onTap=Ge.onClick=function(e,t){return ge(t)?this.clickOnVertex(e,t):this.clickAnywhere(e,t)},Ge.onKeyUp=function(e,t){ye(t)?(this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)):Ee(t)&&this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.polygon.id]})},Ge.onStop=function(e){this.updateUIClasses({mouse:d.NONE}),Oe.enable(this),this.activateUIButton(),void 0!==this.getFeature(e.polygon.id)&&(e.polygon.removeCoordinate(`0.${e.currentVertexPosition}`),e.polygon.isValid()?this.fire(g.CREATE,{features:[e.polygon.toGeoJSON()]}):(this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT,{},{silent:!0})))},Ge.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.polygon.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t);if(0===t.geometry.coordinates.length)return;const r=t.geometry.coordinates[0].length;if(!(r<3)){if(t.properties.meta=y.FEATURE,o(ve(e.polygon.id,t.geometry.coordinates[0][0],"0.0",!1)),r>3){const n=t.geometry.coordinates[0].length-3;o(ve(e.polygon.id,t.geometry.coordinates[0][n],`0.${n}`,!1))}if(r<=4){const e=[[t.geometry.coordinates[0][0][0],t.geometry.coordinates[0][0][1]],[t.geometry.coordinates[0][1][0],t.geometry.coordinates[0][1][1]]];if(o({type:h.FEATURE,properties:t.properties,geometry:{coordinates:e,type:h.LINE_STRING}}),3===r)return}return o(t)}},Ge.onTrash=function(e){this.deleteFeature([e.polygon.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)};const Be={onSetup:function(e){const t=(e=e||{}).featureId;let o,n,r="forward";if(t){if(o=this.getFeature(t),!o)throw new Error("Could not find a feature with the provided featureId");let i=e.from;if(i&&"Feature"===i.type&&i.geometry&&"Point"===i.geometry.type&&(i=i.geometry),i&&"Point"===i.type&&i.coordinates&&2===i.coordinates.length&&(i=i.coordinates),!i||!Array.isArray(i))throw new Error("Please use the `from` property to indicate which point to continue the line from");const s=o.coordinates.length-1;if(o.coordinates[s][0]===i[0]&&o.coordinates[s][1]===i[1])n=s+1,o.addCoordinate(n,...o.coordinates[s]);else{if(o.coordinates[0][0]!==i[0]||o.coordinates[0][1]!==i[1])throw new Error("`from` should match the point at either the start or the end of the provided LineString");r="backwards",n=0,o.addCoordinate(n,...o.coordinates[0])}}else o=this.newFeature({type:h.FEATURE,properties:{},geometry:{type:h.LINE_STRING,coordinates:[]}}),n=0,this.addFeature(o);return this.clearSelectedFeatures(),Oe.disable(this),this.updateUIClasses({mouse:d.ADD}),this.activateUIButton(p.LINE),this.setActionableState({trash:!0}),{line:o,currentVertexPosition:n,direction:r}},clickAnywhere:function(e,t){if(e.currentVertexPosition>0&&Ve(t,e.line.coordinates[e.currentVertexPosition-1])||"backwards"===e.direction&&Ve(t,e.line.coordinates[e.currentVertexPosition+1]))return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]});this.updateUIClasses({mouse:d.ADD}),e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat),"forward"===e.direction?(e.currentVertexPosition++,e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat)):e.line.addCoordinate(0,t.lngLat.lng,t.lngLat.lat)},clickOnVertex:function(e){return this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]})},onMouseMove:function(e,t){e.line.updateCoordinate(e.currentVertexPosition,t.lngLat.lng,t.lngLat.lat),ge(t)&&this.updateUIClasses({mouse:d.POINTER})}};Be.onTap=Be.onClick=function(e,t){if(ge(t))return this.clickOnVertex(e,t);this.clickAnywhere(e,t)},Be.onKeyUp=function(e,t){Ee(t)?this.changeMode(f.SIMPLE_SELECT,{featureIds:[e.line.id]}):ye(t)&&(this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT))},Be.onStop=function(e){Oe.enable(this),this.activateUIButton(),void 0!==this.getFeature(e.line.id)&&(e.line.removeCoordinate(`${e.currentVertexPosition}`),e.line.isValid()?this.fire(g.CREATE,{features:[e.line.toGeoJSON()]}):(this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT,{},{silent:!0})))},Be.onTrash=function(e){this.deleteFeature([e.line.id],{silent:!0}),this.changeMode(f.SIMPLE_SELECT)},Be.toDisplayFeatures=function(e,t,o){const n=t.properties.id===e.line.id;if(t.properties.active=n?E.ACTIVE:E.INACTIVE,!n)return o(t);t.geometry.coordinates.length<2||(t.properties.meta=y.FEATURE,o(ve(e.line.id,t.geometry.coordinates["forward"===e.direction?t.geometry.coordinates.length-2:1],""+("forward"===e.direction?t.geometry.coordinates.length-2:1),!1)),o(t))};var je={simple_select:Re,direct_select:Ue,draw_point:ke,draw_polygon:Ge,draw_line_string:Be};const Je={defaultMode:f.SIMPLE_SELECT,keybindings:!0,touchEnabled:!0,clickBuffer:2,touchBuffer:25,boxSelect:!0,displayControlsDefault:!0,styles:ce,modes:je,controls:{},userProperties:!1,suppressAPIEvents:!0},$e={point:!0,line_string:!0,polygon:!0,trash:!0,combine_features:!0,uncombine_features:!0},Ye={point:!1,line_string:!1,polygon:!1,trash:!1,combine_features:!1,uncombine_features:!1};function He(e,t){return e.map((e=>e.source?e:Object.assign({},e,{id:`${e.id}.${t}`,source:"hot"===t?l.HOT:l.COLD})))}var Xe,qe,Ze,We,Ke=t(qe?Xe:(qe=1,Xe=function e(t,o){if(t===o)return!0;if(t&&o&&"object"==typeof t&&"object"==typeof o){if(t.constructor!==o.constructor)return!1;var n,r,i;if(Array.isArray(t)){if((n=t.length)!=o.length)return!1;for(r=n;0!=r--;)if(!e(t[r],o[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===o.source&&t.flags===o.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===o.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===o.toString();if((n=(i=Object.keys(t)).length)!==Object.keys(o).length)return!1;for(r=n;0!=r--;)if(!Object.prototype.hasOwnProperty.call(o,i[r]))return!1;for(r=n;0!=r--;){var s=i[r];if(!e(t[s],o[s]))return!1}return!0}return t!=t&&o!=o})),ze=function(){if(We)return Ze;We=1,Ze=function(t){if(!t||!t.type)return null;var o=e[t.type];return o?"geometry"===o?{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:t}]}:"feature"===o?{type:"FeatureCollection",features:[t]}:"featurecollection"===o?t:void 0:null};var e={Point:"geometry",MultiPoint:"geometry",LineString:"geometry",MultiLineString:"geometry",Polygon:"geometry",MultiPolygon:"geometry",GeometryCollection:"geometry",Feature:"feature",FeatureCollection:"featurecollection"};return Ze}(),Qe=t(ze);function et(e,t){return e.length===t.length&&JSON.stringify(e.map((e=>e)).sort())===JSON.stringify(t.map((e=>e)).sort())}const tt={Polygon:Y,LineString:$,Point:J,MultiPolygon:q,MultiLineString:q,MultiPoint:q};var ot=Object.freeze({__proto__:null,CommonSelectors:Te,ModeHandler:e,StringSet:M,constrainFeatureMovement:Pe,createMidPoint:Ie,createSupplementaryPoints:Se,createVertex:ve,doubleClickZoom:Oe,euclideanDistance:P,featuresAt:b,getFeatureAtAndSetCursors:A,isClick:D,isEventAtCoordinates:Ve,isTap:V,mapEventToBoundingBox:L,moveFeatures:Fe,sortFeatures:O,stringSetsAreEqual:et,theme:ce,toDenseArray:Q});const nt=function(e,t){const o={options:e=function(e={}){let t=Object.assign({},e);return e.controls||(t.controls={}),!1===e.displayControlsDefault?t.controls=Object.assign({},Ye,e.controls):t.controls=Object.assign({},$e,e.controls),t=Object.assign({},Je,t),t.styles=He(t.styles,"cold").concat(He(t.styles,"hot")),t}(e)};t=function(e,t){t.modes=f;const o=void 0===e.options.suppressAPIEvents||!!e.options.suppressAPIEvents;return t.getFeatureIdsAt=function(t){return b.click({point:t},null,e).map((e=>e.properties.id))},t.getSelectedIds=function(){return e.store.getSelectedIds()},t.getSelected=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getSelectedIds().map((t=>e.store.get(t))).map((e=>e.toGeoJSON()))}},t.getSelectedPoints=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getSelectedCoordinates().map((e=>({type:h.FEATURE,properties:{},geometry:{type:h.POINT,coordinates:e.coordinates}})))}},t.set=function(o){if(void 0===o.type||o.type!==h.FEATURE_COLLECTION||!Array.isArray(o.features))throw new Error("Invalid FeatureCollection");const n=e.store.createRenderBatch();let r=e.store.getAllIds().slice();const i=t.add(o),s=new M(i);return r=r.filter((e=>!s.has(e))),r.length&&t.delete(r),n(),i},t.add=function(t){const n=JSON.parse(JSON.stringify(Qe(t))).features.map((t=>{if(t.id=t.id||B(),null===t.geometry)throw new Error("Invalid geometry: null");if(void 0===e.store.get(t.id)||e.store.get(t.id).type!==t.geometry.type){const n=tt[t.geometry.type];if(void 0===n)throw new Error(`Invalid geometry type: ${t.geometry.type}.`);const r=new n(e,t);e.store.add(r,{silent:o})}else{const n=e.store.get(t.id),r=n.properties;n.properties=t.properties,Ke(r,t.properties)||e.store.featureChanged(n.id,{silent:o}),Ke(n.getCoordinates(),t.geometry.coordinates)||n.incomingCoords(t.geometry.coordinates)}return t.id}));return e.store.render(),n},t.get=function(t){const o=e.store.get(t);if(o)return o.toGeoJSON()},t.getAll=function(){return{type:h.FEATURE_COLLECTION,features:e.store.getAll().map((e=>e.toGeoJSON()))}},t.delete=function(n){return e.store.delete(n,{silent:o}),t.getMode()!==f.DIRECT_SELECT||e.store.getSelectedIds().length?e.store.render():e.events.changeMode(f.SIMPLE_SELECT,void 0,{silent:o}),t},t.deleteAll=function(){return e.store.delete(e.store.getAllIds(),{silent:o}),t.getMode()===f.DIRECT_SELECT?e.events.changeMode(f.SIMPLE_SELECT,void 0,{silent:o}):e.store.render(),t},t.changeMode=function(n,r={}){return n===f.SIMPLE_SELECT&&t.getMode()===f.SIMPLE_SELECT?(et(r.featureIds||[],e.store.getSelectedIds())||(e.store.setSelected(r.featureIds,{silent:o}),e.store.render()),t):(n===f.DIRECT_SELECT&&t.getMode()===f.DIRECT_SELECT&&r.featureId===e.store.getSelectedIds()[0]||e.events.changeMode(n,r,{silent:o}),t)},t.getMode=function(){return e.events.getMode()},t.trash=function(){return e.events.trash({silent:o}),t},t.combineFeatures=function(){return e.events.combineFeatures({silent:o}),t},t.uncombineFeatures=function(){return e.events.uncombineFeatures({silent:o}),t},t.setFeatureProperty=function(n,r,i){return e.store.setFeatureProperty(n,r,i,{silent:o}),t},t}(o,t),o.api=t;const n=re(o);return t.onAdd=n.onAdd,t.onRemove=n.onRemove,t.types=p,t.options=e,t};function rt(e){nt(e,this)}return rt.modes=je,rt.constants=v,rt.lib=ot,rt},"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).MapboxDraw=t(); +//# sourceMappingURL=mapbox-gl-draw.js.map diff --git a/docs/articles/turf_files/mapbox-gl-globe-minimap-1.2.1/bundle.js b/docs/articles/turf_files/mapbox-gl-globe-minimap-1.2.1/bundle.js new file mode 100644 index 0000000..e2b91ff --- /dev/null +++ b/docs/articles/turf_files/mapbox-gl-globe-minimap-1.2.1/bundle.js @@ -0,0 +1 @@ +var MapboxGLGlobeMinimap=function(){"use strict";class t{constructor(){this._partials=new Float64Array(32),this._n=0}add(t){const n=this._partials;let e=0;for(let r=0;r0){for(o=t[--i];i>0&&(n=o,e=t[--i],o=n+e,r=e-(o-n),!r););i>0&&(r<0&&t[i-1]<0||r>0&&t[i-1]>0)&&(e=2*r,n=o+e,e==n-o&&(o=n))}return o}}function n(t){return Array.from(function*(t){for(const n of t)yield*n}(t))}var e={value:()=>{}};function r(){for(var t,n=0,e=arguments.length,r={};n=0&&(n=t.slice(e+1),t=t.slice(0,e)),t&&!r.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))),l=-1,s=a.length;if(!(arguments.length<2)){if(null!=n&&"function"!=typeof n)throw new Error("invalid callback: "+n);for(;++l0)for(var e,r,i=new Array(e),o=0;o=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),l.hasOwnProperty(n)?{space:l[n],local:t}:t}function c(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===a&&n.documentElement.namespaceURI===a?n.createElement(t):n.createElementNS(e,t)}}function f(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function h(t){var n=s(t);return(n.local?f:c)(n)}function p(){}function d(t){return null==t?p:function(){return this.querySelector(t)}}function v(){return[]}function g(t){return null==t?v:function(){return this.querySelectorAll(t)}}function y(t){return function(){return null==(n=t.apply(this,arguments))?[]:Array.isArray(n)?n:Array.from(n);var n}}function _(t){return function(){return this.matches(t)}}function m(t){return function(n){return n.matches(t)}}var w=Array.prototype.find;function b(){return this.firstElementChild}var x=Array.prototype.filter;function E(){return Array.from(this.children)}function S(t){return new Array(t.length)}function N(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}function k(t,n,e,r,i,o){for(var u,a=0,l=n.length,s=o.length;an?1:t>=n?0:NaN}function P(t){return function(){this.removeAttribute(t)}}function j(t){return function(){this.removeAttributeNS(t.space,t.local)}}function R(t,n){return function(){this.setAttribute(t,n)}}function T(t,n){return function(){this.setAttributeNS(t.space,t.local,n)}}function q(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttribute(t):this.setAttribute(t,e)}}function O(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}}function L(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function X(t){return function(){this.style.removeProperty(t)}}function z(t,n,e){return function(){this.style.setProperty(t,n,e)}}function D(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}function H(t,n){return t.style.getPropertyValue(n)||L(t).getComputedStyle(t,null).getPropertyValue(n)}function I(t){return function(){delete this[t]}}function Y(t,n){return function(){this[t]=n}}function B(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}function F(t){return t.trim().split(/^|\s+/)}function V(t){return t.classList||new G(t)}function G(t){this._node=t,this._names=F(t.getAttribute("class")||"")}function U(t,n){for(var e=V(t),r=-1,i=n.length;++r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var gt=[null];function yt(t,n){this._groups=t,this._parents=n}function _t(){return new yt([[document.documentElement]],gt)}function mt(t){return"string"==typeof t?new yt([[document.querySelector(t)]],[document.documentElement]):new yt([[t]],gt)}function wt(t,n,e){t.prototype=n.prototype=e,e.constructor=t}function bt(t,n){var e=Object.create(t.prototype);for(var r in n)e[r]=n[r];return e}function xt(){}yt.prototype=_t.prototype={constructor:yt,select:function(t){"function"!=typeof t&&(t=d(t));for(var n=this._groups,e=n.length,r=new Array(e),i=0;i=b&&(b=w+1);!(m=y[b])&&++b=0;)(r=i[o])&&(u&&4^r.compareDocumentPosition(u)&&u.parentNode.insertBefore(r,u),u=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=C);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?X:"function"==typeof n?D:z)(t,n,null==e?"":e)):H(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?I:"function"==typeof n?B:Y)(t,n)):this.node()[t]},classed:function(t,n){var e=F(t+"");if(arguments.length<2){for(var r=V(this.node()),i=-1,o=e.length;++i=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}}))}(t+""),u=o.length;if(!(arguments.length<2)){for(a=n?ht:ft,r=0;r>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):8===e?Dt(n>>24&255,n>>16&255,n>>8&255,(255&n)/255):4===e?Dt(n>>12&15|n>>8&240,n>>8&15|n>>4&240,n>>4&15|240&n,((15&n)<<4|15&n)/255):null):(n=$t.exec(t))?new It(n[1],n[2],n[3],1):(n=Ct.exec(t))?new It(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=Pt.exec(t))?Dt(n[1],n[2],n[3],n[4]):(n=jt.exec(t))?Dt(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=Rt.exec(t))?Ut(n[1],n[2]/100,n[3]/100,1):(n=Tt.exec(t))?Ut(n[1],n[2]/100,n[3]/100,n[4]):qt.hasOwnProperty(t)?zt(qt[t]):"transparent"===t?new It(NaN,NaN,NaN,0):null}function zt(t){return new It(t>>16&255,t>>8&255,255&t,1)}function Dt(t,n,e,r){return r<=0&&(t=n=e=NaN),new It(t,n,e,r)}function Ht(t,n,e,r){return 1===arguments.length?((i=t)instanceof xt||(i=Xt(i)),i?new It((i=i.rgb()).r,i.g,i.b,i.opacity):new It):new It(t,n,e,null==r?1:r);var i}function It(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function Yt(){return`#${Gt(this.r)}${Gt(this.g)}${Gt(this.b)}`}function Bt(){const t=Ft(this.opacity);return`${1===t?"rgb(":"rgba("}${Vt(this.r)}, ${Vt(this.g)}, ${Vt(this.b)}${1===t?")":`, ${t})`}`}function Ft(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Vt(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Gt(t){return((t=Vt(t))<16?"0":"")+t.toString(16)}function Ut(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new Wt(t,n,e,r)}function Zt(t){if(t instanceof Wt)return new Wt(t.h,t.s,t.l,t.opacity);if(t instanceof xt||(t=Xt(t)),!t)return new Wt;if(t instanceof Wt)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),u=NaN,a=o-i,l=(o+i)/2;return a?(u=n===o?(e-r)/a+6*(e0&&l<1?0:u,new Wt(u,a,l,t.opacity)}function Wt(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function Kt(t){return(t=(t||0)%360)<0?t+360:t}function Jt(t){return Math.max(0,Math.min(1,t||0))}function Qt(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}wt(xt,Xt,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:Ot,formatHex:Ot,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return Zt(this).formatHsl()},formatRgb:Lt,toString:Lt}),wt(It,Ht,bt(xt,{brighter(t){return t=null==t?St:Math.pow(St,t),new It(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?Et:Math.pow(Et,t),new It(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new It(Vt(this.r),Vt(this.g),Vt(this.b),Ft(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Yt,formatHex:Yt,formatHex8:function(){return`#${Gt(this.r)}${Gt(this.g)}${Gt(this.b)}${Gt(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:Bt,toString:Bt})),wt(Wt,(function(t,n,e,r){return 1===arguments.length?Zt(t):new Wt(t,n,e,null==r?1:r)}),bt(xt,{brighter(t){return t=null==t?St:Math.pow(St,t),new Wt(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?Et:Math.pow(Et,t),new Wt(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new It(Qt(t>=240?t-240:t+120,i,r),Qt(t,i,r),Qt(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new Wt(Kt(this.h),Jt(this.s),Jt(this.l),Ft(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=Ft(this.opacity);return`${1===t?"hsl(":"hsla("}${Kt(this.h)}, ${100*Jt(this.s)}%, ${100*Jt(this.l)}%${1===t?")":`, ${t})`}`}}));var tn=t=>()=>t;function nn(t){return 1==(t=+t)?en:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):tn(isNaN(n)?e:n)}}function en(t,n){var e=n-t;return e?function(t,n){return function(e){return t+e*n}}(t,e):tn(isNaN(t)?n:t)}var rn=function t(n){var e=nn(n);function r(t,n){var r=e((t=Ht(t)).r,(n=Ht(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),u=en(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=u(n),t+""}}return r.gamma=t,r}(1);function on(t,n){n||(n=[]);var e,r=t?Math.min(n.length,t.length):0,i=n.slice();return function(o){for(e=0;eo&&(i=n.slice(o,i),a[u]?a[u]+=i:a[++u]=i),(e=e[0])===(r=r[0])?a[u]?a[u]+=r:a[++u]=r:(a[++u]=null,l.push({i:u,x:ln(e,r)})),o=fn.lastIndex;return o180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:ln(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,u.rotate,a,l),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:ln(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,u.skewX,a,l),function(t,n,e,r,o,u){if(t!==e||n!==r){var a=o.push(i(o)+"scale(",null,",",null,")");u.push({i:a-4,x:ln(t,e)},{i:a-2,x:ln(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,u.scaleX,u.scaleY,a,l),o=u=null,function(t){for(var n,e=-1,r=l.length;++e=0&&n._call.call(void 0,t),n=n._next;--En}()}finally{En=0,function(){var t,n,e=mn,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:mn=n);wn=t,Xn(r)}(),An=0}}function Ln(){var t=Cn.now(),n=t-Mn;n>kn&&($n-=n,Mn=t)}function Xn(t){En||(Sn&&(Sn=clearTimeout(Sn)),t-An>24?(t<1/0&&(Sn=setTimeout(On,t-Cn.now()-$n)),Nn&&(Nn=clearInterval(Nn))):(Nn||(Mn=Cn.now(),Nn=setInterval(Ln,kn)),En=1,Pn(On)))}function zn(t,n,e){var r=new Tn;return n=null==n?0:+n,r.restart((e=>{r.stop(),t(e+n)}),n,e),r}Tn.prototype=qn.prototype={constructor:Tn,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?jn():+e)+(null==n?0:+n),this._next||wn===this||(wn?wn._next=this:mn=this,wn=this),this._call=t,this._time=e,Xn()},stop:function(){this._call&&(this._call=null,this._time=1/0,Xn())}};var Dn=r("start","end","cancel","interrupt"),Hn=[],In=0,Yn=1,Bn=2,Fn=3,Vn=4,Gn=5,Un=6;function Zn(t,n,e,r,i,o){var u=t.__transition;if(u){if(e in u)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(t){e.state=Yn,e.timer.restart(u,e.delay,e.time),e.delay<=t&&u(t-e.delay)}function u(o){var s,c,f,h;if(e.state!==Yn)return l();for(s in i)if((h=i[s]).name===e.name){if(h.state===Fn)return zn(u);h.state===Vn?(h.state=Un,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[s]):+sIn)throw new Error("too late; already scheduled");return e}function Kn(t,n){var e=Jn(t,n);if(e.state>Fn)throw new Error("too late; already running");return e}function Jn(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function Qn(t,n){var e,r;return function(){var i=Kn(this,t),o=i.tween;if(o!==e)for(var u=0,a=(r=e=o).length;u=0&&(t=t.slice(0,n)),!t||"start"===t}))}(n)?Wn:Kn;return function(){var u=o(this,t),a=u.on;a!==r&&(i=(r=a).copy()).on(n,e),u.on=i}}(e,t,n))},attr:function(t,n){var e=s(t),r="transform"===e?xn:ee;return this.attrTween(t,"function"==typeof n?(e.local?le:ae)(e,r,ne(this,"attr."+t,n)):null==n?(e.local?ie:re)(e):(e.local?ue:oe)(e,r,n))},attrTween:function(t,n){var e="attr."+t;if(arguments.length<2)return(e=this.tween(e))&&e._value;if(null==n)return this.tween(e,null);if("function"!=typeof n)throw new Error;var r=s(t);return this.tween(e,(r.local?se:ce)(r,n))},style:function(t,n,e){var r="transform"==(t+="")?bn:ee;return null==n?this.styleTween(t,function(t,n){var e,r,i;return function(){var o=H(this,t),u=(this.style.removeProperty(t),H(this,t));return o===u?null:o===e&&u===r?i:i=n(e=o,r=u)}}(t,r)).on("end.style."+t,ge(t)):"function"==typeof n?this.styleTween(t,function(t,n,e){var r,i,o;return function(){var u=H(this,t),a=e(this),l=a+"";return null==a&&(this.style.removeProperty(t),l=a=H(this,t)),u===l?null:u===r&&l===i?o:(i=l,o=n(r=u,a))}}(t,r,ne(this,"style."+t,n))).each(function(t,n){var e,r,i,o,u="style."+n,a="end."+u;return function(){var l=Kn(this,t),s=l.on,c=null==l.value[u]?o||(o=ge(n)):void 0;s===e&&i===c||(r=(e=s).copy()).on(a,i=c),l.on=r}}(this._id,t)):this.styleTween(t,function(t,n,e){var r,i,o=e+"";return function(){var u=H(this,t);return u===o?null:u===r?i:i=n(r=u,e)}}(t,r,n),e).on("end.style."+t,null)},styleTween:function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,function(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&function(t,n,e){return function(r){this.style.setProperty(t,n.call(this,r),e)}}(t,o,e)),r}return o._value=n,o}(t,n,null==e?"":e))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var n=t(this);this.textContent=null==n?"":n}}(ne(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},textTween:function(t){var n="text";if(arguments.length<1)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;return this.tween(n,function(t){var n,e;function r(){var r=t.apply(this,arguments);return r!==e&&(n=(e=r)&&function(t){return function(n){this.textContent=t.call(this,n)}}(r)),n}return r._value=t,r}(t))},remove:function(){return this.on("end.remove",function(t){return function(){var n=this.parentNode;for(var e in this.__transition)if(+e!==t)return;n&&n.removeChild(this)}}(this._id))},tween:function(t,n){var e=this._id;if(t+="",arguments.length<2){for(var r,i=Jn(this.node(),e).tween,o=0,u=i.length;oBn&&e.state0?1:t<0?-1:0},Xe=Math.sqrt;function ze(t){return t>1?Me:t<-1?-Me:Math.asin(t)}function De(){}function He(t,n){t&&Ye.hasOwnProperty(t.type)&&Ye[t.type](t,n)}var Ie={Feature:function(t,n){He(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++rke&&(t-=Math.round(t/$e)*$e),[t,n]}function er(t){return function(n,e){return je(n+=t)>ke&&(n-=Math.round(n/$e)*$e),[n,e]}}function rr(t){var n=er(t);return n.invert=er(-t),n}function ir(t,n){var e=qe(t),r=Oe(t),i=qe(n),o=Oe(n);function u(t,n){var u=qe(n),a=qe(t)*u,l=Oe(t)*u,s=Oe(n),c=s*e+a*r;return[Te(l*i-c*o,a*e-s*r),ze(c*i+l*o)]}return u.invert=function(t,n){var u=qe(n),a=qe(t)*u,l=Oe(t)*u,s=Oe(n),c=s*i-l*o;return[Te(l*i+s*o,a*e+c*r),ze(c*e-a*r)]},u}function or(t,n){(n=Ue(n))[0]-=t,Qe(n);var e,r=(e=-n[1])>1?0:e<-1?ke:Math.acos(e);return((-n[2]<0?-r:r)+$e-Se)%$e}function ur(){var t,n=[];return{point:function(n,e,r){t.push([n,e,r])},lineStart:function(){n.push(t=[])},lineEnd:De,rejoin:function(){n.length>1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function ar(t,n){return je(t[0]-n[0])=0;--o)i.point((c=s[o])[0],c[1]);else r(h.x,h.p.x,-1,i);h=h.p}s=(h=h.o).z,p=!p}while(!h.v);i.lineEnd()}}}function cr(t){if(n=t.length){for(var n,e,r=0,i=t[0];++r=0?1:-1,M=k*N,A=M>ke,$=y*E;if(s.add(Te($*k*Oe(M),_*S+$*qe(M))),a+=A?N+k*$e:N,A^v>=r^b>=r){var C=We(Ue(d),Ue(w));Qe(C);var P=We(u,C);Qe(P);var j=(A^N>=0?-1:1)*ze(P[2]);(i>j||i===j&&(C[0]||C[1]))&&(l+=A^N>=0?1:-1)}}return(a<-Se||a0){for(p||(u.polygonStart(),p=!0),u.lineStart(),t=0;t1&&2&i&&o.push(o.pop().concat(o.shift())),l.push(o.filter(pr))}return d}}function pr(t){return t.length>1}function dr(t,n){return((t=t.x)[0]<0?t[1]-Me-Se:Me-t[1])-((n=n.x)[0]<0?n[1]-Me-Se:Me-n[1])}nr.invert=nr;var vr=hr((function(){return!0}),(function(t){var n,e=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),n=1},point:function(o,u){var a=o>0?ke:-ke,l=je(o-e);je(l-ke)0?Me:-Me),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(o,r),n=0):i!==a&&l>=ke&&(je(e-i)Se?Re((Oe(n)*(o=qe(r))*Oe(e)-Oe(r)*(i=qe(n))*Oe(t))/(i*o*u)):(n+r)/2}(e,r,o,u),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(a,r),n=0),t.point(e=o,r=u),i=a},lineEnd:function(){t.lineEnd(),e=r=NaN},clean:function(){return 2-n}}}),(function(t,n,e,r){var i;if(null==t)i=e*Me,r.point(-ke,i),r.point(0,i),r.point(ke,i),r.point(ke,0),r.point(ke,-i),r.point(0,-i),r.point(-ke,-i),r.point(-ke,0),r.point(-ke,i);else if(je(t[0]-n[0])>Se){var o=t[0]0,i=je(n)>Se;function o(t,e){return qe(t)*qe(e)>n}function u(t,e,r){var i=[1,0,0],o=We(Ue(t),Ue(e)),u=Ze(o,o),a=o[0],l=u-a*a;if(!l)return!r&&t;var s=n*u/l,c=-n*a/l,f=We(i,o),h=Je(i,s);Ke(h,Je(o,c));var p=f,d=Ze(h,p),v=Ze(p,p),g=d*d-v*(Ze(h,h)-1);if(!(g<0)){var y=Xe(g),_=Je(p,(-d-y)/v);if(Ke(_,h),_=Ge(_),!r)return _;var m,w=t[0],b=e[0],x=t[1],E=e[1];b0^_[1]<(je(_[0]-w)ke^(w<=_[0]&&_[0]<=b)){var k=Je(p,(-d+y)/v);return Ke(k,h),[_,Ge(k)]}}}function a(n,e){var i=r?t:ke-t,o=0;return n<-i?o|=1:n>i&&(o|=2),e<-i?o|=4:e>i&&(o|=8),o}return hr(o,(function(t){var n,e,l,s,c;return{lineStart:function(){s=l=!1,c=1},point:function(f,h){var p,d=[f,h],v=o(f,h),g=r?v?0:a(f,h):v?a(f+(f<0?ke:-ke),h):0;if(!n&&(s=l=v)&&t.lineStart(),v!==l&&(!(p=u(n,d))||ar(n,p)||ar(d,p))&&(d[2]=1),v!==l)c=0,v?(t.lineStart(),p=u(d,n),t.point(p[0],p[1])):(p=u(n,d),t.point(p[0],p[1],2),t.lineEnd()),n=p;else if(i&&n&&r^v){var y;g&e||!(y=u(d,n,!0))||(c=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1],3)))}!v||n&&ar(n,d)||t.point(d[0],d[1]),n=d,l=v,e=g},lineEnd:function(){l&&t.lineEnd(),n=null},clean:function(){return c|(s&&l)<<1}}}),(function(n,r,i,o){!function(t,n,e,r,i,o){if(e){var u=qe(n),a=Oe(n),l=r*e;null==i?(i=n+r*$e,o=n-l/2):(i=or(u,i),o=or(u,o),(r>0?io)&&(i+=r*$e));for(var s,c=i;r>0?c>o:c0)do{l.point(0===c||3===c?t:r,c>1?i:e)}while((c=(c+u+4)%4)!==f);else l.point(o[0],o[1])}function a(n,i){return je(n[0]-t)0?0:3:je(n[0]-r)0?2:1:je(n[1]-e)0?1:0:i>0?3:2}function l(t,n){return s(t.x,n.x)}function s(t,n){var e=a(t,1),r=a(n,1);return e!==r?e-r:0===e?n[1]-t[1]:1===e?t[0]-n[0]:2===e?t[1]-n[1]:n[0]-t[0]}return function(a){var s,c,f,h,p,d,v,g,y,_,m,w=a,b=ur(),x={point:E,lineStart:function(){x.point=S,c&&c.push(f=[]);_=!0,y=!1,v=g=NaN},lineEnd:function(){s&&(S(h,p),d&&y&&b.rejoin(),s.push(b.result()));x.point=E,y&&w.lineEnd()},polygonStart:function(){w=b,s=[],c=[],m=!0},polygonEnd:function(){var e=function(){for(var n=0,e=0,r=c.length;ei&&(h-o)*(i-u)>(p-u)*(t-o)&&++n:p<=i&&(h-o)*(i-u)<(p-u)*(t-o)&&--n;return n}(),r=m&&e,o=(s=n(s)).length;(r||o)&&(a.polygonStart(),r&&(a.lineStart(),u(null,null,1,a),a.lineEnd()),o&&sr(s,l,e,u,a),a.polygonEnd());w=a,s=c=f=null}};function E(t,n){o(t,n)&&w.point(t,n)}function S(n,u){var a=o(n,u);if(c&&f.push([n,u]),_)h=n,p=u,d=a,_=!1,a&&(w.lineStart(),w.point(n,u));else if(a&&y)w.point(n,u);else{var l=[v=Math.max(_r,Math.min(yr,v)),g=Math.max(_r,Math.min(yr,g))],s=[n=Math.max(_r,Math.min(yr,n)),u=Math.max(_r,Math.min(yr,u))];!function(t,n,e,r,i,o){var u,a=t[0],l=t[1],s=0,c=1,f=n[0]-a,h=n[1]-l;if(u=e-a,f||!(u>0)){if(u/=f,f<0){if(u0){if(u>c)return;u>s&&(s=u)}if(u=i-a,f||!(u<0)){if(u/=f,f<0){if(u>c)return;u>s&&(s=u)}else if(f>0){if(u0)){if(u/=h,h<0){if(u0){if(u>c)return;u>s&&(s=u)}if(u=o-l,h||!(u<0)){if(u/=h,h<0){if(u>c)return;u>s&&(s=u)}else if(h>0){if(u0&&(t[0]=a+s*f,t[1]=l+s*h),c<1&&(n[0]=a+c*f,n[1]=l+c*h),!0}}}}}(l,s,t,e,r,i)?a&&(w.lineStart(),w.point(n,u),m=!1):(y||(w.lineStart(),w.point(l[0],l[1])),w.point(s[0],s[1]),a||w.lineEnd(),m=!1)}v=n,g=u,y=a}return x}}var wr,br,xr,Er,Sr=t=>t,Nr=new t,kr=new t,Mr={point:De,lineStart:De,lineEnd:De,polygonStart:function(){Mr.lineStart=Ar,Mr.lineEnd=Pr},polygonEnd:function(){Mr.lineStart=Mr.lineEnd=Mr.point=De,Nr.add(je(kr)),kr=new t},result:function(){var n=Nr/2;return Nr=new t,n}};function Ar(){Mr.point=$r}function $r(t,n){Mr.point=Cr,wr=xr=t,br=Er=n}function Cr(t,n){kr.add(Er*t-xr*n),xr=t,Er=n}function Pr(){Cr(wr,br)}var jr=1/0,Rr=jr,Tr=-jr,qr=Tr,Or={point:function(t,n){tTr&&(Tr=t);nqr&&(qr=n)},lineStart:De,lineEnd:De,polygonStart:De,polygonEnd:De,result:function(){var t=[[jr,Rr],[Tr,qr]];return Tr=qr=-(Rr=jr=1/0),t}};var Lr,Xr,zr,Dr,Hr=0,Ir=0,Yr=0,Br=0,Fr=0,Vr=0,Gr=0,Ur=0,Zr=0,Wr={point:Kr,lineStart:Jr,lineEnd:ni,polygonStart:function(){Wr.lineStart=ei,Wr.lineEnd=ri},polygonEnd:function(){Wr.point=Kr,Wr.lineStart=Jr,Wr.lineEnd=ni},result:function(){var t=Zr?[Gr/Zr,Ur/Zr]:Vr?[Br/Vr,Fr/Vr]:Yr?[Hr/Yr,Ir/Yr]:[NaN,NaN];return Hr=Ir=Yr=Br=Fr=Vr=Gr=Ur=Zr=0,t}};function Kr(t,n){Hr+=t,Ir+=n,++Yr}function Jr(){Wr.point=Qr}function Qr(t,n){Wr.point=ti,Kr(zr=t,Dr=n)}function ti(t,n){var e=t-zr,r=n-Dr,i=Xe(e*e+r*r);Br+=i*(zr+t)/2,Fr+=i*(Dr+n)/2,Vr+=i,Kr(zr=t,Dr=n)}function ni(){Wr.point=Kr}function ei(){Wr.point=ii}function ri(){oi(Lr,Xr)}function ii(t,n){Wr.point=oi,Kr(Lr=zr=t,Xr=Dr=n)}function oi(t,n){var e=t-zr,r=n-Dr,i=Xe(e*e+r*r);Br+=i*(zr+t)/2,Fr+=i*(Dr+n)/2,Vr+=i,Gr+=(i=Dr*t-zr*n)*(zr+t),Ur+=i*(Dr+n),Zr+=3*i,Kr(zr=t,Dr=n)}function ui(t){this._context=t}ui.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._context.moveTo(t,n),this._point=1;break;case 1:this._context.lineTo(t,n);break;default:this._context.moveTo(t+this._radius,n),this._context.arc(t,n,this._radius,0,$e)}},result:De};var ai,li,si,ci,fi,hi=new t,pi={point:De,lineStart:function(){pi.point=di},lineEnd:function(){ai&&vi(li,si),pi.point=De},polygonStart:function(){ai=!0},polygonEnd:function(){ai=null},result:function(){var n=+hi;return hi=new t,n}};function di(t,n){pi.point=vi,li=ci=t,si=fi=n}function vi(t,n){ci-=t,fi-=n,hi.add(Xe(ci*ci+fi*fi)),ci=t,fi=n}let gi,yi,_i,mi;class wi{constructor(t){this._append=null==t?bi:function(t){const n=Math.floor(t);if(!(n>=0))throw new RangeError(`invalid digits: ${t}`);if(n>15)return bi;if(n!==gi){const t=10**n;gi=n,yi=function(n){let e=1;this._+=n[0];for(const r=n.length;e4*n&&v--){var w=u+h,b=a+p,x=l+d,E=Xe(w*w+b*b+x*x),S=ze(x/=E),N=je(je(x)-1)n||je((y*$+_*C)/m-.5)>.3||u*h+a*p+l*d2?t[2]%360*Pe:0,$()):[g*Ce,y*Ce,_*Ce]},M.angle=function(t){return arguments.length?(m=t%360*Pe,$()):m*Ce},M.reflectX=function(t){return arguments.length?(w=t?-1:1,$()):w<0},M.reflectY=function(t){return arguments.length?(b=t?-1:1,$()):b<0},M.precision=function(t){return arguments.length?(u=Ai(a,k=t*t),C()):Xe(k)},M.fitExtent=function(t,n){return Ni(M,t,n)},M.fitSize=function(t,n){return function(t,n,e){return Ni(t,[[0,0],n],e)}(M,t,n)},M.fitWidth=function(t,n){return function(t,n,e){return Si(t,(function(e){var r=+n,i=r/(e[1][0]-e[0][0]),o=(r-i*(e[1][0]+e[0][0]))/2,u=-i*e[0][1];t.scale(150*i).translate([o,u])}),e)}(M,t,n)},M.fitHeight=function(t,n){return function(t,n,e){return Si(t,(function(e){var r=+n,i=r/(e[1][1]-e[0][1]),o=-i*e[0][0],u=(r-i*(e[1][1]+e[0][1]))/2;t.scale(150*i).translate([o,u])}),e)}(M,t,n)},function(){return n=t.apply(this,arguments),M.invert=n.invert&&A,$()}}((function(){return t}))()}function Ri(t,n){return[qe(n)*Oe(t),Oe(n)]}function Ti(t,n,e){this.k=t,this.x=n,this.y=e}function qi(t){return t}function Oi(t,n){var e=n.id,r=n.bbox,i=null==n.properties?{}:n.properties,o=function(t,n){var e=function(t){if(null==t)return qi;var n,e,r=t.scale[0],i=t.scale[1],o=t.translate[0],u=t.translate[1];return function(t,a){a||(n=e=0);var l=2,s=t.length,c=new Array(s);for(c[0]=(n+=t[0])*r+o,c[1]=(e+=t[1])*i+u;l=0))throw new RangeError(`invalid digits: ${t}`);i=n}return null===n&&(r=new wi(i)),u},u.projection(t).digits(i).context(n)}(this.projection,r),this.globe={type:"Sphere"},this.land=(o=Li,"GeometryCollection"===(u=Li.objects.land).type?{type:"FeatureCollection",features:u.geometries.map((function(t){return Oi(o,t)}))}:Oi(o,u)),this._update(),n.on("move",this._update.bind(this))},_draw_marker:function(){const{globeSize:t,markerSize:n,markerColor:e}=this.options;mt(Xi).append("svg").attr("width",t).attr("height",t).attr("style","position: absolute; left: 0; top: 0;").append("path").attr("opacity",0).attr("d","M5.36018 5.33333C5.36018 4.59722 5.61972 3.96875 6.13881 3.44792C6.65789 2.92708 7.28426 2.66667 8.0179 2.66667C8.75154 2.66667 9.3779 2.92708 9.89699 3.44792C10.4161 3.96875 10.6756 4.59722 10.6756 5.33333C10.6756 6.06944 10.4161 6.69792 9.89699 7.21875C9.3779 7.73958 8.75154 8 8.0179 8C7.28426 8 6.65789 7.73958 6.13881 7.21875C5.61972 6.69792 5.36018 6.06944 5.36018 5.33333ZM2.70246 5.33333C2.70246 6.09028 2.81666 6.7118 3.04506 7.19792L6.824 15.2604C6.93474 15.4896 7.09911 15.6701 7.31713 15.8021C7.53515 15.934 7.76874 16 8.0179 16C8.26706 16 8.50065 15.934 8.71866 15.8021C8.93668 15.6701 9.09759 15.4896 9.20141 15.2604L12.9907 7.19792C13.2191 6.71181 13.3333 6.09028 13.3333 5.33333C13.3333 3.86111 12.8142 2.60417 11.7761 1.5625C10.7379 0.520833 9.48518 -8.13254e-07 8.0179 -9.41527e-07C6.55062 -1.0698e-06 5.29789 0.520832 4.25972 1.5625C3.22155 2.60417 2.70246 3.86111 2.70246 5.33333Z").attr("transform",`scale(${n}, ${n}), translate(${t*(1/n)/2-8}, ${t*(1/n)/2-16})`).attr("style","fill:"+e).transition().duration(100).attr("opacity",1)},_update:function(){const t=this,n=this._parentMap.getCenter();me().duration(this.initialTween?1e3:1).tween("rotate",(function(){const e=pn(t.projection.rotate(),[-n.lng,-n.lat]);return function(n){t.projection.rotate(e(n)),t.context.clearRect(0,0,t.canvas.width,t.canvas.height),t.context.fillStyle=t.options.waterColor,t.context.beginPath(),t.path(t.globe),t.context.fill(),t.context.fillStyle=t.options.landColor,t.context.beginPath(),t.path(t.land),t.context.fill()}})).on("end",(()=>{t.initialTween&&(t._draw_marker(),t.initialTween=!1)}))},_createContainer:function(t){const{globeSize:n,id:e}=this.options,r=document.createElement("div");return r.className="mapboxgl-ctrl-globe-minimap mapboxgl-ctrl",r.setAttribute("style","width: "+n+"; height: "+n+";"),r.addEventListener("contextmenu",this._preventDefault),t.getContainer().appendChild(r),""!==e&&(r.id=e),r},_preventDefault:function(t){t.preventDefault()}},window.GlobeMinimap=zi,zi}(); diff --git a/docs/articles/getting-started_files/maplibre-gl-5.5.0/LICENSE.txt b/docs/articles/turf_files/maplibre-gl-5.6.0/LICENSE.txt similarity index 100% rename from docs/articles/getting-started_files/maplibre-gl-5.5.0/LICENSE.txt rename to docs/articles/turf_files/maplibre-gl-5.6.0/LICENSE.txt diff --git a/docs/articles/getting-started_files/maplibre-gl-5.3.0/maplibre-gl.css b/docs/articles/turf_files/maplibre-gl-5.6.0/maplibre-gl.css similarity index 100% rename from docs/articles/getting-started_files/maplibre-gl-5.3.0/maplibre-gl.css rename to docs/articles/turf_files/maplibre-gl-5.6.0/maplibre-gl.css diff --git a/docs/articles/turf_files/maplibre-gl-5.6.0/maplibre-gl.js b/docs/articles/turf_files/maplibre-gl-5.6.0/maplibre-gl.js new file mode 100644 index 0000000..eb76da6 --- /dev/null +++ b/docs/articles/turf_files/maplibre-gl-5.6.0/maplibre-gl.js @@ -0,0 +1,59 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v5.6.0/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory()); +})(this, (function () { 'use strict'; + +/* eslint-disable */ + +var maplibregl = {}; +var modules = {}; +function define(moduleName, _dependencies, moduleFactory) { + modules[moduleName] = moduleFactory; + + // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) + if (moduleName !== 'index') { + return; + } + + // we assume that when an index module is initializing then other modules are loaded already + var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);' + + var sharedModule = {}; + // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) + // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) + // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following + modules.shared(sharedModule); + modules.index(maplibregl, sharedModule); + + if (typeof window !== 'undefined') { + maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); + } + + return maplibregl; +}; + + + +define("shared",["exports"],(function(t){"use strict";function e(t,e,r,n){return new(r||(r=Promise))((function(i,s){function a(t){try{l(n.next(t));}catch(t){s(t);}}function o(t){try{l(n.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(a,o);}l((n=n.apply(t,e||[])).next());}))}function r(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var n,i;function s(){if(i)return n;function t(t,e){this.x=t,this.y=e;}return i=1,n=t,t.prototype={clone:function(){return new t(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},t.convert=function(e){return e instanceof t?e:Array.isArray(e)?new t(e[0],e[1]):e},n}"function"==typeof SuppressedError&&SuppressedError;var a,o,l=r(s()),u=function(){if(o)return a;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return o=1,a=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},a}(),c=r(u);let h,p;function f(){return null==h&&(h="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),h}function d(){if(null==p&&(p=!1,f())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:!0});if(e){for(let r=0;r=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function $(t,e,r,n){const i=new c(t,e,r,n);return t=>i.solve(t)}const D=$(.25,.1,.25,1);function O(t,e,r){return Math.min(r,Math.max(e,t))}function R(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function j(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let N=1;function U(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function q(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}function G(t){return Array.isArray(t)?t.map(G):"object"==typeof t&&t?U(t,G):t}const X={};function Z(t){X[t]||("undefined"!=typeof console&&console.warn(t),X[t]=!0);}function Y(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function H(t){return "undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}let K=null;function J(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const W="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function Q(t,r,n,i,s){return e(this,void 0,void 0,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const e=new VideoFrame(t,{timestamp:0});try{const a=null==e?void 0:e.format;if(!a||!a.startsWith("BGR")&&!a.startsWith("RGB"))throw new Error(`Unrecognized format ${a}`);const o=a.startsWith("BGR"),l=new Uint8ClampedArray(i*s*4);if(yield e.copyTo(l,function(t,e,r,n,i){const s=4*Math.max(1,0),a=(Math.max(0,r)-r)*n*4+s,o=4*n,l=Math.max(0,e),u=Math.max(0,r);return {rect:{x:l,y:u,width:Math.min(t.width,e+n)-l,height:Math.min(t.height,r+i)-u},layout:[{offset:a,stride:o}]}}(t,r,n,i,s)),o)for(let t=0;t{t.removeEventListener(e,r,n);}}}function nt(t){return t*Math.PI/180}function it(t){return t/Math.PI*180}const st={touchstart:!0,touchmove:!0,touchmoveWindow:!0,touchend:!0,touchcancel:!0},at={dblclick:!0,click:!0,mouseover:!0,mouseout:!0,mousedown:!0,mousemove:!0,mousemoveWindow:!0,mouseup:!0,mouseupWindow:!0,contextmenu:!0,wheel:!0},ot="AbortError";function lt(){return new Error(ot)}const ut={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function ct(t){return ut.REGISTERED_PROTOCOLS[t.substring(0,t.indexOf("://"))]}const ht="global-dispatcher";class pt extends Error{constructor(t,e,r,n){super(`AJAXError: ${e} (${t}): ${r}`),this.status=t,this.statusText=e,this.url=r,this.body=n;}}const ft=()=>H(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,dt=function(t,r){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const e=ct(t.url);if(e)return e(t,r);if(H(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:ht},r)}if(!(/^file:/.test(n=t.url)||/^file:/.test(ft())&&!/^\w+:/.test(n))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,r){return e(this,void 0,void 0,(function*(){const e=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:ft(),signal:r.signal});let n,i;"json"!==t.type||e.headers.has("Accept")||e.headers.set("Accept","application/json");try{n=yield fetch(e);}catch(e){throw new pt(0,e.message,t.url,new Blob)}if(!n.ok){const e=yield n.blob();throw new pt(n.status,n.statusText,t.url,e)}i="arrayBuffer"===t.type||"image"===t.type?n.arrayBuffer():"json"===t.type?n.json():n.text();const s=yield i;if(r.signal.aborted)throw lt();return {data:s,cacheControl:n.headers.get("Cache-Control"),expires:n.headers.get("Expires")}}))}(t,r);if(H(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:!0,targetMapId:ht},r)}var n;return function(t,e){return new Promise(((r,n)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,!0),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||void 0===i?void 0:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{n(new Error(s.statusText));},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response);}catch(t){return void n(t)}r({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires")});}else {const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});n(new pt(s.status,s.statusText,t.url,e));}},e.signal.addEventListener("abort",(()=>{s.abort(),n(lt());})),s.send(t.body);}))}(t,r)};function yt(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return !0;const e=new URL(t),r=window.location;return e.protocol===r.protocol&&e.host===r.host}function mt(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function gt(t,e,r){if(r&&r[t]){const n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}class xt{constructor(t,e={}){j(this,e),this.type=t;}}class vt extends xt{constructor(t,e={}){super("error",j({error:t},e));}}class bt{on(t,e){return this._listeners=this._listeners||{},mt(t,e,this._listeners),{unsubscribe:()=>{this.off(t,e);}}}off(t,e){return gt(t,e,this._listeners),gt(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},mt(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new xt(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)gt(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(j(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof vt&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var wt={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},state:{type:"state",default:{}},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},"color-relief":{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_color-relief","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const _t=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function St(t,e){const r={};for(const e in t)"ref"!==e&&(r[e]=t[e]);return _t.forEach((t=>{t in e&&(r[t]=e[t]);})),r}function At(t,e){if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return !1;for(let r=0;r`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const te=[$t,Dt,Ot,Rt,jt,Nt,Xt,Ut,Wt(qt),Zt,Ht,Yt,Kt,Jt];function ee(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!ee(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of te)if(!ee(t,e))return null}return `Expected ${Qt(t)} but found ${Qt(e)} instead.`}function re(t,e){return e.some((e=>e.kind===t.kind))}function ne(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function ie(t,e){return "array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const se=.96422,ae=.82521,oe=4/29,le=6/29,ue=3*le*le,ce=le*le*le,he=Math.PI/180,pe=180/Math.PI;function fe(t){return (t%=360)<0&&(t+=360),t}function de([t,e,r,n]){let i,s;const a=me((.2225045*(t=ye(t))+.7168786*(e=ye(e))+.0606169*(r=ye(r)))/1);t===e&&e===r?i=s=a:(i=me((.4360747*t+.3850649*e+.1430804*r)/se),s=me((.0139322*t+.0971045*e+.7141733*r)/ae));const o=116*a-16;return [o<0?0:o,500*(i-a),200*(a-s),n]}function ye(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function me(t){return t>ce?Math.pow(t,1/3):t/ue+oe}function ge([t,e,r,n]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,a=isNaN(r)?i:i-r/200;return i=1*ve(i),s=se*ve(s),a=ae*ve(a),[xe(3.1338561*s-1.6168667*i-.4906146*a),xe(-.9787684*s+1.9161415*i+.033454*a),xe(.0719453*s-.2289914*i+1.4052427*a),n]}function xe(t){return (t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function ve(t){return t>le?t*t*t:ue*(t-oe)}const be=Object.hasOwn||function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};function we(t,e){return be(t,e)?t[e]:void 0}function _e(t){return parseInt(t.padEnd(2,t),16)/255}function Se(t,e){return Ae(e?t/100:t,0,1)}function Ae(t,e,r){return Math.min(Math.max(e,t),r)}function ke(t){return !t.some(Number.isNaN)}const Me={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function Ie(t,e,r){return t+r*(e-t)}function ze(t,e,r){return t.map(((t,n)=>Ie(t,e[n],r)))}class Pe{constructor(t,e,r,n=1,i=!0){this.r=t,this.g=e,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[t,e,r,n]));}static parse(t){if(t instanceof Pe)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return [0,0,0,0];const e=we(Me,t);if(e){const[t,r,n]=e;return [t/255,r/255,n/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let r=1;return [_e(t.slice(r,r+=e)),_e(t.slice(r,r+=e)),_e(t.slice(r,r+=e)),_e(t.slice(r,r+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,r,n,i,s,a,o,l,u,c,h,p]=e,f=[i||" ",o||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[n,a,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[Ae(+r/e,0,1),Ae(+s/e,0,1),Ae(+l/e,0,1),h?Se(+h,p):1];if(ke(t))return t}}return}}const r=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[t,e,n,i,s,a,o,l,u]=r,c=[n||" ",s||" ",o].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,Ae(+i,0,100),Ae(+a,0,100),l?Se(+l,u):1];if(ke(t))return function([t,e,r,n]){function i(n){const i=(n+t/30)%12,s=e*Math.min(r,1-r);return r-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=fe(t),e/=100,r/=100,[i(0),i(8),i(4),n]}(t)}}}(t);return e?new Pe(...e,!1):void 0}get rgb(){const{r:t,g:e,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[t/i,e/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,r,n,i]=de(t),s=Math.sqrt(r*r+n*n);return [Math.round(1e4*s)?fe(Math.atan2(n,r)*pe):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",de(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,r,n]=this.rgb;return `rgba(${[t,e,r].map((t=>Math.round(255*t))).join(",")},${n})`}static interpolate(t,e,r,n="rgb"){switch(n){case "rgb":{const[n,i,s,a]=ze(t.rgb,e.rgb,r);return new Pe(n,i,s,a,!1)}case "hcl":{const[n,i,s,a]=t.hcl,[o,l,u,c]=e.hcl;let h,p;if(isNaN(n)||isNaN(o))isNaN(n)?isNaN(o)?h=NaN:(h=o,1!==s&&0!==s||(p=l)):(h=n,1!==u&&0!==u||(p=i));else {let t=o-n;o>n&&t>180?t-=360:o180&&(t+=360),h=n+r*t;}const[f,d,y,m]=function([t,e,r,n]){return t=isNaN(t)?0:t*he,ge([r,Math.cos(t)*e,Math.sin(t)*e,n])}([h,null!=p?p:Ie(i,l,r),Ie(s,u,r),Ie(a,c,r)]);return new Pe(f,d,y,m,!1)}case "lab":{const[n,i,s,a]=ge(ze(t.lab,e.lab,r));return new Pe(n,i,s,a,!1)}}}}Pe.black=new Pe(0,0,0,1),Pe.white=new Pe(1,1,1,1),Pe.transparent=new Pe(0,0,0,0),Pe.red=new Pe(1,0,0,1);class Ce{constructor(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const Be=["bottom","center","top"];class Ee{constructor(t,e,r,n,i,s){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i,this.verticalAlign=s;}}class Te{constructor(t){this.sections=t;}static fromString(t){return new Te([new Ee(t,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof Te?t:Te.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class Ve{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Ve)return t;if("number"==typeof t)return new Ve([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]];}return new Ve(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Ve(ze(t.values,e.values,r))}}class Fe{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Fe)return t;if("number"==typeof t)return new Fe([t]);if(Array.isArray(t)){for(const e of t)if("number"!=typeof e)return;return new Fe(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Fe(ze(t.values,e.values,r))}}class Le{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Le)return t;if("string"==typeof t){const e=Pe.parse(t);if(!e)return;return new Le([e])}if(!Array.isArray(t))return;const e=[];for(const r of t){if("string"!=typeof r)return;const t=Pe.parse(r);if(!t)return;e.push(t);}return new Le(e)}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r,n="rgb"){const i=[];if(t.values.length!=e.values.length)throw new Error(`colorArray: Arrays have mismatched length (${t.values.length} vs. ${e.values.length}), cannot interpolate.`);for(let s=0;s=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Ue(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof je||t instanceof Pe||t instanceof Ce||t instanceof Te||t instanceof Ve||t instanceof Fe||t instanceof Le||t instanceof Oe||t instanceof Re)return !0;if(Array.isArray(t)){for(const e of t)if(!Ue(e))return !1;return !0}if("object"==typeof t){for(const e in t)if(!Ue(t[e]))return !1;return !0}return !1}function qe(t){if(null===t)return $t;if("string"==typeof t)return Ot;if("boolean"==typeof t)return Rt;if("number"==typeof t)return Dt;if(t instanceof Pe)return jt;if(t instanceof je)return Nt;if(t instanceof Ce)return Gt;if(t instanceof Te)return Xt;if(t instanceof Ve)return Zt;if(t instanceof Fe)return Ht;if(t instanceof Le)return Yt;if(t instanceof Oe)return Jt;if(t instanceof Re)return Kt;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=qe(e);if(r){if(r===t)continue;r=qt;break}r=t;}return Wt(r||qt,e)}return Ut}function Ge(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof Pe||t instanceof je||t instanceof Te||t instanceof Ve||t instanceof Fe||t instanceof Le||t instanceof Oe||t instanceof Re?t.toString():JSON.stringify(t)}class Xe{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Ue(t[1]))return e.error("invalid value");const r=t[1];let n=qe(r);const i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new Xe(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return !0}}const Ze={string:Ot,number:Dt,boolean:Rt,object:Ut};class Ye{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r,n=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const r=t[1];if("string"!=typeof r||!(r in Ze)||"object"===r)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=Ze[r],n++;}else i=qt;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],n++;}r=Wt(i,s);}else {if(!Ze[i])throw new Error(`Types doesn't contain name = ${i}`);r=Ze[i];}const s=[];for(;nt.outputDefined()))}}const He={"to-boolean":Rt,"to-color":jt,"to-number":Dt,"to-string":Ot};class Ke{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[0];if(!He[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");const n=He[r],i=[];for(let r=1;r4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:Ne(e[0],e[1],e[2],e[3]),!r))return new Pe(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new $e(r||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "padding":{let e;for(const r of this.args){e=r.evaluate(t);const n=Ve.parse(e);if(n)return n}throw new $e(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "numberArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Fe.parse(e);if(n)return n}throw new $e(`Could not parse numberArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "colorArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Le.parse(e);if(n)return n}throw new $e(`Could not parse colorArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "variableAnchorOffsetCollection":{let e;for(const r of this.args){e=r.evaluate(t);const n=Oe.parse(e);if(n)return n}throw new $e(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "number":{let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new $e(`Could not convert ${JSON.stringify(e)} to number.`)}case "formatted":return Te.fromString(Ge(this.args[0].evaluate(t)));case "resolvedImage":return Re.fromString(Ge(this.args[0].evaluate(t)));case "projectionDefinition":return this.args[0].evaluate(t);default:return Ge(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}const Je=["Unknown","Point","LineString","Polygon"];class We{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null;}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?Je[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache.get(t);return e||(e=Pe.parse(t),this._parseColorCache.set(t,e)),e}}class Qe{constructor(t,e,r=[],n,i=new Lt,s=[]){this.registry=t,this.path=r,this.key=r.map((t=>`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=n,this._isConstant=e;}parse(t,e,r,n,i={}){return e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return "assert"===r?new Ye(e,[t]):"coerce"===r?new Ke(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const n=t[0];if("string"!=typeof n)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[n];if(i){let n=i.parse(t,this);if(!n)return null;if(this.expectedType){const t=this.expectedType,i=n.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind){if("projectionDefinition"===t.kind&&["string","array"].includes(i.kind)||["color","formatted","resolvedImage"].includes(t.kind)&&["value","string"].includes(i.kind)||["padding","numberArray"].includes(t.kind)&&["value","number","array"].includes(i.kind)||"colorArray"===t.kind&&["value","string","array"].includes(i.kind)||"variableAnchorOffsetCollection"===t.kind&&["value","array"].includes(i.kind))n=r(n,t,e.typeAnnotation||"coerce");else if(this.checkSubtype(t,i))return null}else n=r(n,t,e.typeAnnotation||"assert");}if(!(n instanceof Xe)&&"resolvedImage"!==n.type.kind&&this._isConstant(n)){const t=new We;try{n=new Xe(n.type,n.evaluate(t));}catch(t){return this.error(t.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Qe(this.registry,this._isConstant,n,e||null,i,this.errors)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new Ft(r,t));}checkSubtype(t,e){const r=ee(t,e);return r&&this.error(r),r}}class tr{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new $e(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new $e(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return !1}}class nr{constructor(t,e){this.type=Rt,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,qt),n=e.parse(t[2],2,qt);return r&&n?re(r.type,[Rt,Ot,Dt,$t,qt])?new nr(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Qt(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!ne(e,["boolean","string","number","null"]))throw new $e(`Expected first argument to be of type boolean, string, number or null, but found ${Qt(qe(e))} instead.`);if(!ne(r,["string","array"]))throw new $e(`Expected second argument to be of type array or string, but found ${Qt(qe(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return !0}}class ir{constructor(t,e,r){this.type=Dt,this.needle=t,this.haystack=e,this.fromIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,qt),n=e.parse(t[2],2,qt);if(!r||!n)return null;if(!re(r.type,[Rt,Ot,Dt,$t,qt]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Qt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Dt);return i?new ir(r,n,i):null}return new ir(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!ne(e,["boolean","string","number","null"]))throw new $e(`Expected first argument to be of type boolean, string, number or null, but found ${Qt(qe(e))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(t)),ne(r,["string"])){const t=r.indexOf(e,n);return -1===t?-1:[...r.slice(0,t)].length}if(ne(r,["array"]))return r.indexOf(e,n);throw new $e(`Expected second argument to be of type array or string, but found ${Qt(qe(r))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return !1}}class sr{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(r){if(u.checkSubtype(r,qe(t)))return null}else r=qe(t);if(void 0!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length;}const c=e.parse(l,a,n);if(!c)return null;n=n||c.type,s.push(c);}const a=e.parse(t[1],1,qt);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,n);return o?"value"!==a.type.kind&&e.concat(1).checkSubtype(r,a.type)?null:new sr(r,n,a,i,s,o):null}evaluate(t){const e=this.input.evaluate(t);return (qe(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class ar{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class or{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,qt),n=e.parse(t[2],2,Dt);if(!r||!n)return null;if(!re(r.type,[Wt(qt),Ot,qt]))return e.error(`Expected first argument to be of type array or string, but found ${Qt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Dt);return i?new or(r.type,r,n,i):null}return new or(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);let n;if(this.endIndex&&(n=this.endIndex.evaluate(t)),ne(e,["string"]))return [...e].slice(r,n).join("");if(ne(e,["array"]))return e.slice(r,n);throw new $e(`Expected first argument to be of type array or string, but found ${Qt(qe(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return !1}}function lr(t,e){const r=t.length-1;let n,i,s=0,a=r,o=0;for(;s<=a;)if(o=Math.floor((s+a)/2),n=t[o],i=t[o+1],n<=e){if(o===r||ee))throw new $e("Input is not a number.");a=o-1;}return 0}class ur{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const r=e.parse(t[1],1,Dt);if(!r)return null;const n=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',o);const u=e.parse(a,l,i);if(!u)return null;i=i||u.type,n.push([s,u]);}return new ur(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[lr(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function cr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var hr,pr,fr=function(){if(pr)return hr;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return pr=1,hr=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},hr}(),dr=cr(fr);class yr{constructor(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e);}static interpolationFactor(t,e,r,n){let i=0;if("exponential"===t.name)i=mr(e,t.base,r,n);else if("linear"===t.name)i=mr(e,1,r,n);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new dr(s[0],s[1],s[2],s[3]).solve(mr(e,1,r,n));}return i}static parse(t,e){let[r,n,i,...s]=t;if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){const t=n[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:t};}else {if("cubic-bezier"!==n[0])return e.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const t=n.slice(1);if(4!==t.length||t.some((t=>"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,Dt),!i)return null;const a=[];let o=null;"interpolate-hcl"!==r&&"interpolate-lab"!==r||e.expectedType==Yt?e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType):o=jt;for(let t=0;t=r)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,o);if(!u)return null;o=o||u.type,a.push([r,u]);}return ie(o,Dt)||ie(o,Nt)||ie(o,jt)||ie(o,Zt)||ie(o,Ht)||ie(o,Yt)||ie(o,Jt)||ie(o,Wt(Dt))?new yr(o,r,n,i,a):e.error(`Type ${Qt(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=lr(e,n),a=yr.interpolationFactor(this.interpolation,n,e[s],e[s+1]),o=r[s].evaluate(t),l=r[s+1].evaluate(t);switch(this.operator){case "interpolate":switch(this.type.kind){case "number":return Ie(o,l,a);case "color":return Pe.interpolate(o,l,a);case "padding":return Ve.interpolate(o,l,a);case "colorArray":return Le.interpolate(o,l,a);case "numberArray":return Fe.interpolate(o,l,a);case "variableAnchorOffsetCollection":return Oe.interpolate(o,l,a);case "array":return ze(o,l,a);case "projectionDefinition":return je.interpolate(o,l,a)}case "interpolate-hcl":switch(this.type.kind){case "color":return Pe.interpolate(o,l,a,"hcl");case "colorArray":return Le.interpolate(o,l,a,"hcl")}case "interpolate-lab":switch(this.type.kind){case "color":return Pe.interpolate(o,l,a,"lab");case "colorArray":return Le.interpolate(o,l,a,"lab")}}}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function mr(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}const gr={color:Pe.interpolate,number:Ie,padding:Ve.interpolate,numberArray:Fe.interpolate,colorArray:Le.interpolate,variableAnchorOffsetCollection:Oe.interpolate,array:ze};class xr{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r=null;const n=e.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const n of t.slice(1)){const t=e.parse(n,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!t)return null;r=r||t.type,i.push(t);}if(!r)throw new Error("No output type");const s=n&&i.some((t=>ee(n,t.type)));return new xr(s?qt:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(t),r&&r instanceof Re&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break;return r}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function vr(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function br(t,e,r,n){return 0===n.compare(e,r)}function wr(t,e,r){const n="=="!==t&&"!="!==t;return class i{constructor(t,e,r){this.type=Rt,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const r=t[0];let s=e.parse(t[1],1,qt);if(!s)return null;if(!vr(r,s.type))return e.concat(1).error(`"${r}" comparisons are not supported for type '${Qt(s.type)}'.`);let a=e.parse(t[2],2,qt);if(!a)return null;if(!vr(r,a.type))return e.concat(2).error(`"${r}" comparisons are not supported for type '${Qt(a.type)}'.`);if(s.type.kind!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error(`Cannot compare types '${Qt(s.type)}' and '${Qt(a.type)}'.`);n&&("value"===s.type.kind&&"value"!==a.type.kind?s=new Ye(a.type,[s]):"value"!==s.type.kind&&"value"===a.type.kind&&(a=new Ye(s.type,[a])));let o=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error("Cannot use collator to compare non-string types.");if(o=e.parse(t[3],3,Gt),!o)return null}return new i(s,a,o)}evaluate(i){const s=this.lhs.evaluate(i),a=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=qe(s),r=qe(a);if(e.kind!==r.kind||"string"!==e.kind&&"number"!==e.kind)throw new $e(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=qe(s),r=qe(a);if("string"!==t.kind||"string"!==r.kind)return e(i,s,a)}return this.collator?r(i,s,a,this.collator.evaluate(i)):e(i,s,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return !0}}}const _r=wr("==",(function(t,e,r){return e===r}),br),Sr=wr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !br(0,e,r,n)})),Ar=wr("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),Mr=wr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),Ir=wr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class zr{constructor(t,e,r){this.type=Gt,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");const n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,Rt);if(!n)return null;const i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Rt);if(!i)return null;let s=null;return r.locale&&(s=e.parse(r.locale,1,Ot),!s)?null:new zr(n,i,s)}evaluate(t){return new Ce(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);}outputDefined(){return !1}}class Pr{constructor(t,e,r,n,i){this.type=Ot,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,Dt);if(!r)return null;const n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=e.parse(n.locale,1,Ot),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,Ot),!s))return null;let a=null;if(n["min-fraction-digits"]&&(a=e.parse(n["min-fraction-digits"],1,Dt),!a))return null;let o=null;return n["max-fraction-digits"]&&(o=e.parse(n["max-fraction-digits"],1,Dt),!o)?null:new Pr(r,i,s,a,o)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return !1}}class Cr{constructor(t){this.type=Xt,this.sections=t;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");const n=[];let i=!1;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&"object"==typeof s&&!Array.isArray(s)){i=!1;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,Dt),!t))return null;let r=null;if(s["text-font"]&&(r=e.parse(s["text-font"],1,Wt(Ot)),!r))return null;let a=null;if(s["text-color"]&&(a=e.parse(s["text-color"],1,jt),!a))return null;let o=null;if(s["vertical-align"]){if("string"==typeof s["vertical-align"]&&!Be.includes(s["vertical-align"]))return e.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${s["vertical-align"]}' instead.`);if(o=e.parse(s["vertical-align"],1,Ot),!o)return null}const l=n[n.length-1];l.scale=t,l.font=r,l.textColor=a,l.verticalAlign=o;}else {const s=e.parse(t[r],1,qt);if(!s)return null;const a=s.type.kind;if("string"!==a&&"value"!==a&&"null"!==a&&"resolvedImage"!==a)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:s,scale:null,font:null,textColor:null,verticalAlign:null});}}return new Cr(n)}evaluate(t){return new Te(this.sections.map((e=>{const r=e.content.evaluate(t);return qe(r)===Kt?new Ee("",r,null,null,null,e.verticalAlign?e.verticalAlign.evaluate(t):null):new Ee(Ge(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null,e.verticalAlign?e.verticalAlign.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor),e.verticalAlign&&t(e.verticalAlign);}outputDefined(){return !1}}class Br{constructor(t){this.type=Kt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,Ot);return r?new Br(r):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),r=Re.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r}eachChild(t){t(this.input);}outputDefined(){return !1}}class Er{constructor(t){this.type=Dt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${Qt(r.type)} instead.`):new Er(r):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return [...e].length;if(Array.isArray(e))return e.length;throw new $e(`Expected value to be of type string or array, but found ${Qt(qe(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return !1}}const Tr=8192;function Vr(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*Tr),Math.round(n*i*Tr)]}function Fr(t,e){const r=Math.pow(2,e.z);return [(i=(t[0]/Tr+e.x)/r,360*i-180),(n=(t[1]/Tr+e.y)/r,360/Math.PI*Math.atan(Math.exp((180-360*n)*Math.PI/180))-90)];var n,i;}function Lr(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function $r(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function Dr(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],a=t[1]-r[1];return n*a-s*i==0&&n*s<=0&&i*a<=0}function Or(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!Gr(t,e,r,n)||!Gr(r,n,t,e));var i,s;}function Rr(t,e,r){for(const n of r)for(let r=0;r(i=t)[1]!=(a=o[e+1])[1]>i[1]&&i[0]<(a[0]-s[0])*(i[1]-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}var i,s,a;return n}function Nr(t,e){for(const r of e)if(jr(t,r))return !0;return !1}function Ur(t,e){for(const r of t)if(!jr(r,e))return !1;for(let r=0;r0&&o<0||a<0&&o>0}function Xr(t,e,r){const n=[];for(let i=0;ir[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i;}Lr(e,t);}function Hr(t,e,r,n){const i=Math.pow(2,n.z)*Tr,s=[n.x*Tr,n.y*Tr],a=[];for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];Yr(n,e,r,i),a.push(n);}return a}function Kr(t,e,r,n){const i=Math.pow(2,n.z)*Tr,s=[n.x*Tr,n.y*Tr],a=[];for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];Lr(e,r),t.push(r);}a.push(t);}if(e[2]-e[0]<=i/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const n of t)Yr(n,e,r,i);}var o;return a}class Jr{constructor(t,e){this.type=Rt,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Ue(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const r of e.features){const{type:e,coordinates:n}=r.geometry;"Polygon"===e&&t.push(n),"MultiPolygon"===e&&t.push(...n);}if(t.length)return new Jr(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new Jr(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new Jr(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Xr(e.coordinates,n,i),a=Hr(t.geometry(),r,n,i);if(!$r(r,n))return !1;for(const t of a)if(!jr(t,s))return !1}if("MultiPolygon"===e.type){const s=Zr(e.coordinates,n,i),a=Hr(t.geometry(),r,n,i);if(!$r(r,n))return !1;for(const t of a)if(!Nr(t,s))return !1}return !0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Xr(e.coordinates,n,i),a=Kr(t.geometry(),r,n,i);if(!$r(r,n))return !1;for(const t of a)if(!Ur(t,s))return !1}if("MultiPolygon"===e.type){const s=Zr(e.coordinates,n,i),a=Kr(t.geometry(),r,n,i);if(!$r(r,n))return !1;for(const t of a)if(!qr(t,s))return !1}return !0}(t,this.geometries)}return !1}eachChild(){}outputDefined(){return !0}}let Wr=class{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}};function Qr(t,e,r=0,n=t.length-1,i=en){for(;n>r;){if(n-r>600){const s=n-r+1,a=e-r+1,o=Math.log(s),l=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*l*(s-l)/s)*(a-s/2<0?-1:1);Qr(t,e,Math.max(r,Math.floor(e-a*l/s+u)),Math.min(n,Math.floor(e+(s-a)*l/s+u)),i);}const s=t[e];let a=r,o=n;for(tn(t,r,e),i(t[n],s)>0&&tn(t,r,n);a0;)o--;}0===i(t[r],s)?tn(t,r,o):(o++,tn(t,o,n)),o<=e&&(r=o+1),e<=o&&(n=o-1);}}function tn(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function en(t,e){return te?1:0}function rn(t,e){if(t.length<=1)return [t];const r=[];let n,i;for(const e of t){const t=sn(e);0!==t&&(e.area=Math.abs(t),void 0===i&&(i=t<0),i===t<0?(n&&r.push(n),n=[e]):n.push(e));}if(n&&r.push(n),e>1)for(let t=0;t1?(l=t[o+1][0],u=t[o+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function cn(t,e){return e[0]-t[0]}function hn(t){return t[1]-t[0]+1}function pn(t,e){return t[1]>=t[0]&&t[1]t[1])return [null,null];const r=hn(t);if(e){if(2===r)return [t,null];const e=Math.floor(r/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===r)return [t,null];const n=Math.floor(r/2)-1;return [[t[0],t[0]+n],[t[0]+n+1,t[1]]]}function dn(t,e){if(!pn(e,t.length))return [1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=e[0];n<=e[1];++n)Lr(r,t[n]);return r}function yn(t){const e=[1/0,1/0,-1/0,-1/0];for(const r of t)for(const t of r)Lr(e,t);return e}function mn(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function gn(t,e,r){if(!mn(t)||!mn(e))return NaN;let n=0,i=0;return t[2]e[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if($r(i,s)){if(An(t,e))return 0}else if(An(e,t))return 0;let a=1/0;for(const n of t)for(let t=0,i=n.length,s=i-1;t0;){const i=a.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(hn(l)<=u){if(!pn(l,t.length))return NaN;if(e){const e=Sn(t,l,r,n);if(isNaN(e)||0===e)return e;s=Math.min(s,e);}else for(let e=l[0];e<=l[1];++e){const i=_n(t[e],r,n);if(s=Math.min(s,i),0===s)return 0}}else {const r=fn(l,e);Mn(a,s,n,t,o,r[0]),Mn(a,s,n,t,o,r[1]);}}return s}function Pn(t,e,r,n,i,s=1/0){let a=Math.min(s,i.distance(t[0],r[0]));if(0===a)return a;const o=new Wr([[0,[0,t.length-1],[0,r.length-1]]],cn);for(;o.length>0;){const s=o.pop();if(s[0]>=a)continue;const l=s[1],u=s[2],c=e?50:100,h=n?50:100;if(hn(l)<=c&&hn(u)<=h){if(!pn(l,t.length)&&pn(u,r.length))return NaN;let s;if(e&&n)s=bn(t,l,r,u,i),a=Math.min(a,s);else if(e&&!n){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=xn(r[t],e,i),a=Math.min(a,s),0===a)return a}else if(!e&&n){const e=r.slice(u[0],u[1]+1);for(let r=l[0];r<=l[1];++r)if(s=xn(t[r],e,i),a=Math.min(a,s),0===a)return a}else s=wn(t,l,r,u,i),a=Math.min(a,s);}else {const s=fn(l,e),c=fn(u,n);In(o,a,i,t,r,s[0],c[0]),In(o,a,i,t,r,s[0],c[1]),In(o,a,i,t,r,s[1],c[0]),In(o,a,i,t,r,s[1],c[1]);}}return a}function Cn(t){return "MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class Bn{constructor(t,e){this.type=Dt,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Ue(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new Bn(e,e.features.map((t=>Cn(t.geometry))).flat());if("Feature"===e.type)return new Bn(e,Cn(e.geometry));if("type"in e&&"coordinates"in e)return new Bn(e,Cn(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Fr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new un(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Pn(n,!1,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Pn(n,!1,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,zn(n,!1,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Fr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new un(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Pn(n,!0,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Pn(n,!0,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,zn(n,!0,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const r=t.geometry();if(0===r.length||0===r[0].length)return NaN;const n=rn(r,0).map((e=>e.map((e=>e.map((e=>Fr([e.x,e.y],t.canonical))))))),i=new un(n[0][0][0][1]);let s=1/0;for(const t of e)for(const e of n){switch(t.type){case "Point":s=Math.min(s,zn([t.coordinates],!1,e,i,s));break;case "LineString":s=Math.min(s,zn(t.coordinates,!0,e,i,s));break;case "Polygon":s=Math.min(s,kn(e,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return !0}}class En{constructor(t){this.type=qt,this.key=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=t[1];return null==r?e.error("Global state property must be defined."):"string"!=typeof r?e.error(`Global state property must be string, but found ${typeof t[1]} instead.`):new En(r)}evaluate(t){var e;const r=null===(e=t.globals)||void 0===e?void 0:e.globalState;return r&&0!==Object.keys(r).length?we(r,this.key):null}eachChild(){}outputDefined(){return !1}}const Tn={"==":_r,"!=":Sr,">":kr,"<":Ar,">=":Ir,"<=":Mr,array:Ye,at:rr,boolean:Ye,case:ar,coalesce:xr,collator:zr,format:Cr,image:Br,in:nr,"index-of":ir,interpolate:yr,"interpolate-hcl":yr,"interpolate-lab":yr,length:Er,let:tr,literal:Xe,match:sr,number:Ye,"number-format":Pr,object:Ye,slice:or,step:ur,string:Ye,"to-boolean":Ke,"to-color":Ke,"to-number":Ke,"to-string":Ke,var:er,within:Jr,distance:Bn,"global-state":En};class Vn{constructor(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return !1}static parse(t,e){const r=t[0],n=Vn.definitions[r];if(!n)return e.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let o=null;for(const[n,s]of a){o=new Qe(e.registry,On,e.path,null,e.scope);const a=[];let l=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(Qt).join(", ")})`:`(${Qt(e.type)}...)`;var e;})).join(" | "),n=[];for(let r=1;r{r=e?r&&On(t):r&&t instanceof Xe;})),!!r&&Rn(t)&&Nn(t,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function Rn(t){if(t instanceof Vn){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}if(t instanceof Jr)return !1;if(t instanceof Bn)return !1;let e=!0;return t.eachChild((t=>{e&&!Rn(t)&&(e=!1);})),e}function jn(t){if(t instanceof Vn&&"feature-state"===t.name)return !1;let e=!0;return t.eachChild((t=>{e&&!jn(t)&&(e=!1);})),e}function Nn(t,e){if(t instanceof Vn&&e.indexOf(t.name)>=0)return !1;let r=!0;return t.eachChild((t=>{r&&!Nn(t,e)&&(r=!1);})),r}function Un(t){return {result:"success",value:t}}function qn(t){return {result:"error",value:t}}function Gn(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Xn(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function Zn(t){return !!t.expression&&t.expression.interpolated}function Yn(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Hn(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)&&qe(t)===Ut}function Kn(t){return t}function Jn(t,e){const r=t.stops&&"object"==typeof t.stops[0][0],n=r||!(r||void 0!==t.property),i=t.type||(Zn(e)?"exponential":"interval"),s=function(t){switch(t.type){case "color":return Pe.parse;case "padding":return Ve.parse;case "numberArray":return Fe.parse;case "colorArray":return Le.parse;default:return null}}(e);if(s&&((t=Vt({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],s(t[1])]))),t.default=s(t.default?t.default:e.default)),t.colorSpace&&"rgb"!==(a=t.colorSpace)&&"hcl"!==a&&"lab"!==a)throw new Error(`Unknown color space: "${t.colorSpace}"`);var a;const o=function(t){switch(t){case "exponential":return ei;case "interval":return ti;case "categorical":return Qn;case "identity":return ri;default:throw new Error(`Unknown function type "${t}"`)}}(i);let l,u;if("categorical"===i){l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0];}if(r){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>ei({stops:i,base:t.base},e,r).evaluate(r,n)}}if(n){const r="exponential"===i?{name:"exponential",base:void 0!==t.base?t.base:1}:null;return {kind:"camera",interpolationType:r,interpolationFactor:yr.interpolationFactor.bind(void 0,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>o(t,e,r,l,u)}}return {kind:"source",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:void 0;return void 0===i?Wn(t.default,e.default):o(t,e,i,l,u)}}}function Wn(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Qn(t,e,r,n,i){return Wn(typeof r===i?n[r]:void 0,t.default,e.default)}function ti(t,e,r){if("number"!==Yn(r))return Wn(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=lr(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function ei(t,e,r){const n=void 0!==t.base?t.base:1;if("number"!==Yn(r))return Wn(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=lr(t.stops.map((t=>t[0])),r),a=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),o=t.stops[s][1],l=t.stops[s+1][1],u=gr[e.type]||Kn;return "function"==typeof o.evaluate?{evaluate(...e){const r=o.evaluate.apply(void 0,e),n=l.evaluate.apply(void 0,e);if(void 0!==r&&void 0!==n)return u(r,n,a,t.colorSpace)}}:u(o,l,a,t.colorSpace)}function ri(t,e,r){switch(e.type){case "color":r=Pe.parse(r);break;case "formatted":r=Te.fromString(r.toString());break;case "resolvedImage":r=Re.fromString(r.toString());break;case "padding":r=Ve.parse(r);break;case "colorArray":r=Le.parse(r);break;case "numberArray":r=Fe.parse(r);break;default:Yn(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0);}return Wn(r,t.default,e.default)}Vn.register(Tn,{error:[{kind:"error"},[Ot],(t,[e])=>{throw new $e(e.evaluate(t))}],typeof:[Ot,[qt],(t,[e])=>Qt(qe(e.evaluate(t)))],"to-rgba":[Wt(Dt,4),[jt],(t,[e])=>{const[r,n,i,s]=e.evaluate(t).rgb;return [255*r,255*n,255*i,s]}],rgb:[jt,[Dt,Dt,Dt],Fn],rgba:[jt,[Dt,Dt,Dt,Dt],Fn],has:{type:Rt,overloads:[[[Ot],(t,[e])=>Ln(e.evaluate(t),t.properties())],[[Ot,Ut],(t,[e,r])=>Ln(e.evaluate(t),r.evaluate(t))]]},get:{type:qt,overloads:[[[Ot],(t,[e])=>$n(e.evaluate(t),t.properties())],[[Ot,Ut],(t,[e,r])=>$n(e.evaluate(t),r.evaluate(t))]]},"feature-state":[qt,[Ot],(t,[e])=>$n(e.evaluate(t),t.featureState||{})],properties:[Ut,[],t=>t.properties()],"geometry-type":[Ot,[],t=>t.geometryType()],id:[qt,[],t=>t.id()],zoom:[Dt,[],t=>t.globals.zoom],"heatmap-density":[Dt,[],t=>t.globals.heatmapDensity||0],elevation:[Dt,[],t=>t.globals.elevation||0],"line-progress":[Dt,[],t=>t.globals.lineProgress||0],accumulated:[qt,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[Dt,Dn(Dt),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],"*":[Dt,Dn(Dt),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],"-":{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[Dt],(t,[e])=>-e.evaluate(t)]]},"/":[Dt,[Dt,Dt],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],"%":[Dt,[Dt,Dt],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[Dt,[],()=>Math.LN2],pi:[Dt,[],()=>Math.PI],e:[Dt,[],()=>Math.E],"^":[Dt,[Dt,Dt],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[Dt,[Dt],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[Dt,[Dt],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[Dt,[Dt],(t,[e])=>Math.log(e.evaluate(t))],log2:[Dt,[Dt],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[Dt,[Dt],(t,[e])=>Math.sin(e.evaluate(t))],cos:[Dt,[Dt],(t,[e])=>Math.cos(e.evaluate(t))],tan:[Dt,[Dt],(t,[e])=>Math.tan(e.evaluate(t))],asin:[Dt,[Dt],(t,[e])=>Math.asin(e.evaluate(t))],acos:[Dt,[Dt],(t,[e])=>Math.acos(e.evaluate(t))],atan:[Dt,[Dt],(t,[e])=>Math.atan(e.evaluate(t))],min:[Dt,Dn(Dt),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[Dt,Dn(Dt),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[Dt,[Dt],(t,[e])=>Math.abs(e.evaluate(t))],round:[Dt,[Dt],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[Dt,[Dt],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[Dt,[Dt],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[Rt,[Ot,qt],(t,[e,r])=>t.properties()[e.value]===r.value],"filter-id-==":[Rt,[qt],(t,[e])=>t.id()===e.value],"filter-type-==":[Rt,[Ot],(t,[e])=>t.geometryType()===e.value],"filter-<":[Rt,[Ot,qt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r":[Rt,[Ot,qt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[Rt,[qt],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],"filter-<=":[Rt,[Ot,qt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[Rt,[qt],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],"filter->=":[Rt,[Ot,qt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[Rt,[qt],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],"filter-has":[Rt,[qt],(t,[e])=>e.value in t.properties()],"filter-has-id":[Rt,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[Rt,[Wt(Ot)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[Rt,[Wt(qt)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[Rt,[Ot,Wt(qt)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[Rt,[Ot,Wt(qt)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:Rt,overloads:[[[Rt,Rt],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[Dn(Rt),(t,e)=>{for(const r of e)if(!r.evaluate(t))return !1;return !0}]]},any:{type:Rt,overloads:[[[Rt,Rt],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[Dn(Rt),(t,e)=>{for(const r of e)if(r.evaluate(t))return !0;return !1}]]},"!":[Rt,[Rt],(t,[e])=>!e.evaluate(t)],"is-supported-script":[Rt,[Ot],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return !r||r(e.evaluate(t))}],upcase:[Ot,[Ot],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[Ot,[Ot],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[Ot,Dn(qt),(t,e)=>e.map((e=>Ge(e.evaluate(t)))).join("")],"resolved-locale":[Ot,[Gt],(t,[e])=>e.evaluate(t).resolvedLocale()]});class ni{constructor(t,e){this.expression=t,this._warningHistory={},this._evaluator=new We,this._defaultValue=e?function(t){if("color"===t.type&&Hn(t.default))return new Pe(0,0,0,0);switch(t.type){case "color":return Pe.parse(t.default)||null;case "padding":return Ve.parse(t.default)||null;case "numberArray":return Fe.parse(t.default)||null;case "colorArray":return Le.parse(t.default)||null;case "variableAnchorOffsetCollection":return Oe.parse(t.default)||null;case "projectionDefinition":return je.parse(t.default)||null;default:return void 0===t.default?null:t.default}}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new $e(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function ii(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Tn}function si(t,e){const r=new Qe(Tn,On,[],e?function(t){const e={color:jt,string:Ot,number:Dt,enum:Ot,boolean:Rt,formatted:Xt,padding:Zt,numberArray:Ht,colorArray:Yt,projectionDefinition:Nt,resolvedImage:Kt,variableAnchorOffsetCollection:Jt};return "array"===t.type?Wt(e[t.value]||qt,t.length):e[t.type]}(e):void 0),n=r.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return n?Un(new ni(n,e)):qn(r.errors)}class ai{constructor(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!jn(e.expression),this.globalStateRefs=hi(e.expression);}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._styleExpression.evaluate(t,e,r,n,i,s)}}class oi{constructor(t,e,r,n){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!jn(e.expression),this.globalStateRefs=hi(e.expression),this.interpolationType=n;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?yr.interpolationFactor(this.interpolationType,t,e,r):0}}function li(t,e){const r=si(t,e);if("error"===r.result)return r;const n=r.value.expression,i=Rn(n);if(!i&&!Gn(e))return qn([new Ft("","data expressions not supported")]);const s=Nn(n,["zoom"]);if(!s&&!Xn(e))return qn([new Ft("","zoom expressions not supported")]);const a=ci(n);return a||s?a instanceof Ft?qn([a]):a instanceof yr&&!Zn(e)?qn([new Ft("",'"interpolate" expressions cannot be used with this property')]):Un(a?new oi(i?"camera":"composite",r.value,a.labels,a instanceof yr?a.interpolation:void 0):new ai(i?"constant":"source",r.value)):qn([new Ft("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class ui{constructor(t,e){this._parameters=t,this._specification=e,Vt(this,Jn(this._parameters,this._specification));}static deserialize(t){return new ui(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function ci(t){let e=null;if(t instanceof tr)e=ci(t.result);else if(t instanceof xr){for(const r of t.args)if(e=ci(r),e)break}else (t instanceof ur||t instanceof yr)&&t.input instanceof Vn&&"zoom"===t.input.name&&(e=t);return e instanceof Ft||t.eachChild((t=>{const r=ci(t);r instanceof Ft?e=r:!e&&r?e=new Ft("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&r&&e!==r&&(e=new Ft("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),e}function hi(t,e=new Set){return t instanceof En&&e.add(t.key),t.eachChild((t=>{hi(t,e);})),e}function pi(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case "has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case "in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case "!in":case "!has":case "none":return !1;case "==":case "!=":case ">":case ">=":case "<":case "<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case "any":case "all":for(const e of t.slice(1))if(!pi(e)&&"boolean"!=typeof e)return !1;return !0;default:return !0}}const fi={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function di(t){if(null==t)return {filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};pi(t)||(t=gi(t));const e=si(t,fi);if("error"===e.result)throw new Error(e.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return {filter:(t,r,n)=>e.value.evaluate(t,r,{},n),needGeometry:mi(t),getGlobalStateRefs:()=>hi(e.value.expression)}}function yi(t,e){return te?1:0}function mi(t){if(!Array.isArray(t))return !1;if("within"===t[0]||"distance"===t[0])return !0;for(let e=1;e"===e||"<="===e||">="===e?xi(t[1],t[2],e):"any"===e?(r=t.slice(1),["any"].concat(r.map(gi))):"all"===e?["all"].concat(t.slice(1).map(gi)):"none"===e?["all"].concat(t.slice(1).map(gi).map(wi)):"in"===e?vi(t[1],t.slice(2)):"!in"===e?wi(vi(t[1],t.slice(2))):"has"===e?bi(t[1]):"!has"!==e||wi(bi(t[1]));var r;}function xi(t,e,r){switch(t){case "$type":return [`filter-type-${r}`,e];case "$id":return [`filter-id-${r}`,e];default:return [`filter-${r}`,t,e]}}function vi(t,e){if(0===e.length)return !1;switch(t){case "$type":return ["filter-type-in",["literal",e]];case "$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(yi)]]:["filter-in-small",t,["literal",e]]}}function bi(t){switch(t){case "$type":return !0;case "$id":return ["filter-has-id"];default:return ["filter-has",t]}}function wi(t){return ["!",t]}function _i(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const r of t)e+=`${_i(r)},`;return `${e}]`}const r=Object.keys(t).sort();let n="{";for(let e=0;en.maximum?[new Tt(e,r,`${r} is greater than the maximum value ${n.maximum}`)]:[]}function Ci(t){const e=t.valueSpec,r=ki(t.value.type);let n,i,s,a={};const o="categorical"!==r&&void 0===t.value.property,l=!o,u="array"===Yn(t.value.stops)&&"array"===Yn(t.value.stops[0])&&"object"===Yn(t.value.stops[0][0]),c=Ii({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===r)return [new Tt(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const n=t.value;return e=e.concat(zi({key:t.key,value:n,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===Yn(n)&&0===n.length&&e.push(new Tt(t.key,n,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===r&&o&&c.push(new Tt(t.key,t.value,'missing required property "property"')),"identity"===r||t.value.stops||c.push(new Tt(t.key,t.value,'missing required property "stops"')),"exponential"===r&&t.valueSpec.expression&&!Zn(t.valueSpec)&&c.push(new Tt(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!Gn(t.valueSpec)?c.push(new Tt(t.key,t.value,"property functions not supported")):o&&!Xn(t.valueSpec)&&c.push(new Tt(t.key,t.value,"zoom functions not supported"))),"categorical"!==r&&!u||void 0!==t.value.property||c.push(new Tt(t.key,t.value,'"property" property is required')),c;function h(t){let r=[];const n=t.value,o=t.key;if("array"!==Yn(n))return [new Tt(o,n,`array expected, ${Yn(n)} found`)];if(2!==n.length)return [new Tt(o,n,`array length 2 expected, length ${n.length} found`)];if(u){if("object"!==Yn(n[0]))return [new Tt(o,n,`object expected, ${Yn(n[0])} found`)];if(void 0===n[0].zoom)return [new Tt(o,n,"object stop key must have zoom")];if(void 0===n[0].value)return [new Tt(o,n,"object stop key must have value")];if(s&&s>ki(n[0].zoom))return [new Tt(o,n[0].zoom,"stop zoom values must appear in ascending order")];ki(n[0].zoom)!==s&&(s=ki(n[0].zoom),i=void 0,a={}),r=r.concat(Ii({key:`${o}[0]`,value:n[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Pi,value:p}}));}else r=r.concat(p({key:`${o}[0]`,value:n[0],validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},n));return ii(Mi(n[1]))?r.concat([new Tt(`${o}[1]`,n[1],"expressions are not allowed in function stops.")]):r.concat(t.validateSpec({key:`${o}[1]`,value:n[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const o=Yn(t.value),l=ki(t.value),u=null!==t.value?t.value:s;if(n){if(o!==n)return [new Tt(t.key,u,`${o} stop domain type must match previous stop domain type ${n}`)]}else n=o;if("number"!==o&&"string"!==o&&"boolean"!==o)return [new Tt(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==o&&"categorical"!==r){let n=`number expected, ${o} found`;return Gn(e)&&void 0===r&&(n+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new Tt(t.key,u,n)]}return "categorical"!==r||"number"!==o||isFinite(l)&&Math.floor(l)===l?"categorical"!==r&&"number"===o&&void 0!==i&&lnew Tt(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new Tt(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!jn(r))return [new Tt(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!jn(r))return [new Tt(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!Nn(r,["zoom","feature-state"]))return [new Tt(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!Rn(r))return [new Tt(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function Ei(t){const e=t.key,r=t.value,n=Yn(r);return "string"!==n?[new Tt(e,r,`color expected, ${n} found`)]:Pe.parse(String(r))?[]:[new Tt(e,r,`color expected, "${r}" found`)]}function Ti(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(ki(r))&&i.push(new Tt(e,r,`expected one of [${n.values.join(", ")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(ki(r))&&i.push(new Tt(e,r,`expected one of [${Object.keys(n.values).join(", ")}], ${JSON.stringify(r)} found`)),i}function Vi(t){return pi(Mi(t.value))?Bi(Vt({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):Fi(t)}function Fi(t){const e=t.value,r=t.key;if("array"!==Yn(e))return [new Tt(r,e,`array expected, ${Yn(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return [new Tt(r,e,"filter array must have at least 1 element")];switch(s=s.concat(Ti({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),ki(e[0])){case "<":case "<=":case ">":case ">=":e.length>=2&&"$type"===ki(e[1])&&s.push(new Tt(r,e,`"$type" cannot be use with operator "${e[0]}"`));case "==":case "!=":3!==e.length&&s.push(new Tt(r,e,`filter array for operator "${e[0]}" must have 3 elements`));case "in":case "!in":e.length>=2&&(i=Yn(e[1]),"string"!==i&&s.push(new Tt(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let a=2;a{t in r&&e.push(new Tt(n,r[t],`"${t}" is prohibited for ref layers`));})),i.layers.forEach((e=>{ki(e.id)===o&&(t=e);})),t?t.ref?e.push(new Tt(n,r.ref,"ref cannot reference another ref layer")):a=ki(t.type):e.push(new Tt(n,r.ref,`ref layer "${o}" not found`));}else if("background"!==a)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&ki(t.type);t?"vector"===s&&"raster"===a?e.push(new Tt(n,r.source,`layer "${r.id}" requires a raster source`)):"raster-dem"!==s&&"hillshade"===a||"raster-dem"!==s&&"color-relief"===a?e.push(new Tt(n,r.source,`layer "${r.id}" requires a raster-dem source`)):"raster"===s&&"raster"!==a?e.push(new Tt(n,r.source,`layer "${r.id}" requires a vector source`)):"vector"!==s||r["source-layer"]?"raster-dem"===s&&"hillshade"!==a&&"color-relief"!==a?e.push(new Tt(n,r.source,"raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.")):"line"!==a||!r.paint||!r.paint["line-gradient"]||"geojson"===s&&t.lineMetrics||e.push(new Tt(n,r,`layer "${r.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new Tt(n,r,`layer "${r.id}" must specify a "source-layer"`)):e.push(new Tt(n,r.source,`source "${r.source}" not found`));}else e.push(new Tt(n,r,'missing required property "source"'));return e=e.concat(Ii({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:r,objectKey:"type"}),filter:Vi,layout:t=>Ii({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Di(Vt({layerType:a},t))}}),paint:t=>Ii({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>$i(Vt({layerType:a},t))}})}})),e}function Ri(t){const e=t.value,r=t.key,n=Yn(e);return "string"!==n?[new Tt(r,e,`string expected, ${n} found`)]:[]}const ji={promoteId:function({key:t,value:e}){if("string"===Yn(e))return Ri({key:t,value:e});{const r=[];for(const n in e)r.push(...Ri({key:`${t}.${n}`,value:e[n]}));return r}}};function Ni(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return [new Tt(r,e,'"type" is required')];const a=ki(e.type);let o;switch(a){case "vector":case "raster":return o=Ii({key:r,value:e,valueSpec:n[`source_${a.replace("-","_")}`],style:t.style,styleSpec:n,objectElementValidators:ji,validateSpec:s}),o;case "raster-dem":return o=function(t){var e;const r=null!==(e=t.sourceName)&&void 0!==e?e:"",n=t.value,i=t.styleSpec,s=i.source_raster_dem,a=t.style;let o=[];const l=Yn(n);if(void 0===n)return o;if("object"!==l)return o.push(new Tt("source_raster_dem",n,`object expected, ${l} found`)),o;const u="custom"===ki(n.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in n)!u&&c.includes(e)?o.push(new Tt(e,n[e],`In "${r}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?o=o.concat(t.validateSpec({key:e,value:n[e],valueSpec:s[e],validateSpec:t.validateSpec,style:a,styleSpec:i})):o.push(new Tt(e,n[e],`unknown property "${e}"`));return o}({sourceName:r,value:e,style:t.style,styleSpec:n,validateSpec:s}),o;case "geojson":if(o=Ii({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,validateSpec:s,objectElementValidators:ji}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],s="string"==typeof n?[n,["accumulated"],["get",t]]:n;o.push(...Bi({key:`${r}.${t}.map`,value:i,expressionContext:"cluster-map"})),o.push(...Bi({key:`${r}.${t}.reduce`,value:s,expressionContext:"cluster-reduce"}));}return o;case "video":return Ii({key:r,value:e,valueSpec:n.source_video,style:i,validateSpec:s,styleSpec:n});case "image":return Ii({key:r,value:e,valueSpec:n.source_image,style:i,validateSpec:s,styleSpec:n});case "canvas":return [new Tt(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Ti({key:`${r}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]}})}}function Ui(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const a=Yn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Tt("light",e,`object expected, ${a} found`)]),s;for(const a in e){const o=a.match(/^(.*)-transition$/);s=s.concat(o&&n[o[1]]&&n[o[1]].transition?t.validateSpec({key:a,value:e[a],valueSpec:r.transition,validateSpec:t.validateSpec,style:i,styleSpec:r}):n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Tt(a,e[a],`unknown property "${a}"`)]);}return s}function qi(t){const e=t.value,r=t.styleSpec,n=r.sky,i=t.style,s=Yn(e);if(void 0===e)return [];if("object"!==s)return [new Tt("sky",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Tt(s,e[s],`unknown property "${s}"`)]);return a}function Gi(t){const e=t.value,r=t.styleSpec,n=r.terrain,i=t.style;let s=[];const a=Yn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Tt("terrain",e,`object expected, ${a} found`)]),s;for(const a in e)s=s.concat(n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Tt(a,e[a],`unknown property "${a}"`)]);return s}function Xi(t){let e=[];const r=t.value,n=t.key;if(Array.isArray(r)){const i=[],s=[];for(const a in r)r[a].id&&i.includes(r[a].id)&&e.push(new Tt(n,r,`all the sprites' ids must be unique, but ${r[a].id} is duplicated`)),i.push(r[a].id),r[a].url&&s.includes(r[a].url)&&e.push(new Tt(n,r,`all the sprites' URLs must be unique, but ${r[a].url} is duplicated`)),s.push(r[a].url),e=e.concat(Ii({key:`${n}[${a}]`,value:r[a],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:t.validateSpec}));return e}return Ri({key:n,value:r})}function Zi(t){return e=t.value,Boolean(e)&&e.constructor===Object?[]:[new Tt(t.key,t.value,`object expected, ${Yn(t.value)} found`)];var e;}const Yi={"*":()=>[],array:zi,boolean:function(t){const e=t.value,r=t.key,n=Yn(e);return "boolean"!==n?[new Tt(r,e,`boolean expected, ${n} found`)]:[]},number:Pi,color:Ei,constants:Ai,enum:Ti,filter:Vi,function:Ci,layer:Oi,object:Ii,source:Ni,light:Ui,sky:qi,terrain:Gi,projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style,s=Yn(e);if(void 0===e)return [];if("object"!==s)return [new Tt("projection",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Tt(s,e[s],`unknown property "${s}"`)]);return a},projectionDefinition:function(t){const e=t.key;let r=t.value;r=r instanceof String?r.valueOf():r;const n=Yn(r);return "array"!==n||function(t){return Array.isArray(t)&&3===t.length&&"string"==typeof t[0]&&"string"==typeof t[1]&&"number"==typeof t[2]}(r)||function(t){return !!["interpolate","step","literal"].includes(t[0])}(r)?["array","string"].includes(n)?[]:[new Tt(e,r,`projection expected, invalid type "${n}" found`)]:[new Tt(e,r,`projection expected, invalid array ${JSON.stringify(r)} found`)]},string:Ri,formatted:function(t){return 0===Ri(t).length?[]:Bi(t)},resolvedImage:function(t){return 0===Ri(t).length?[]:Bi(t)},padding:function(t){const e=t.key,r=t.value;if("array"===Yn(r)){if(r.length<1||r.length>4)return [new Tt(e,r,`padding requires 1 to 4 values; ${r.length} values found`)];const n={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(r=r.concat(Ai({key:"constants",value:t.constants}))),Qi(r)}function Wi(t){return function(e){return t({...e,validateSpec:Hi})}}function Qi(t){return [].concat(t).sort(((t,e)=>t.line-e.line))}function ts(t){return function(...e){return Qi(t.apply(this,e))}}Ji.source=ts(Wi(Ni)),Ji.sprite=ts(Wi(Xi)),Ji.glyphs=ts(Wi(Ki)),Ji.light=ts(Wi(Ui)),Ji.sky=ts(Wi(qi)),Ji.terrain=ts(Wi(Gi)),Ji.state=ts(Wi(Zi)),Ji.layer=ts(Wi(Oi)),Ji.filter=ts(Wi(Vi)),Ji.paintProperty=ts(Wi($i)),Ji.layoutProperty=ts(Wi(Di));const es=Ji,rs=es.light,ns=es.sky,is=es.paintProperty,ss=es.layoutProperty;function as(t,e){let r=!1;if(e&&e.length)for(const n of e)t.fire(new vt(new Error(n.message))),r=!0;return r}class os{constructor(t,e,r){const n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(let t=0;t=u[l+0]&&n>=u[l+1])?(a[h]=!0,s.push(i[h])):a[h]=!1;}}}}_forEachCell(t,e,r,n,i,s,a,o){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!o||o(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,r,n,u,s,a,o))return}}_convertFromCellCoord(t){return (t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let r=0;for(let t=0;t=0)continue;const s=t[n];i[n]=ls[r].shallow.indexOf(n)>=0?s:fs(s,e);}t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==r&&(i.$name=r),i}function ds(t){if(ps(t))return t;if(Array.isArray(t))return t.map(ds);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=hs(t)||"Object";if(!ls[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:r}=ls[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const r of Object.keys(t)){if("$name"===r)continue;const i=t[r];n[r]=ls[e].shallow.indexOf(r)>=0?i:ds(i);}return n}class ys{constructor(){this.first=!0;}update(t,e){const r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Hiragana:t=>t>=12352&&t<=12447,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"CJK Unified Ideographs":t=>t>=19968&&t<=40959,"Hangul Syllables":t=>t>=44032&&t<=55215,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function gs(t){for(const e of t)if(Ss(e.charCodeAt(0)))return !0;return !1}function xs(t){for(const e of t)if(!ws(e.charCodeAt(0)))return !1;return !0}function vs(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const bs=vs(["Arab","Dupl","Mong","Ougr","Syrc"]);function ws(t){return !bs.test(String.fromCodePoint(t))}const _s=vs(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function Ss(t){return !(746!==t&&747!==t&&(t<4352||!(ms["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||ms["CJK Compatibility"](t)||ms["CJK Strokes"](t)||!(!ms["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||ms["Enclosed CJK Letters and Months"](t)||ms["Ideographic Description Characters"](t)||ms.Kanbun(t)||ms.Katakana(t)&&12540!==t||!(!ms["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!ms["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||ms["Vertical Forms"](t)||ms["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||_s.test(String.fromCodePoint(t)))))}function As(t){return !(Ss(t)||function(t){return !!(ms["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||ms["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||ms["Letterlike Symbols"](t)||ms["Number Forms"](t)||ms["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||ms["Control Pictures"](t)&&9251!==t||ms["Optical Character Recognition"](t)||ms["Enclosed Alphanumerics"](t)||ms["Geometric Shapes"](t)||ms["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||ms["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||ms["CJK Symbols and Punctuation"](t)||ms.Katakana(t)||ms["Private Use Area"](t)||ms["CJK Compatibility Forms"](t)||ms["Small Form Variants"](t)||ms["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}const ks=vs(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Ms(t){return ks.test(String.fromCodePoint(t))}function Is(t,e){return !(!e&&Ms(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||ms.Khmer(t))}function zs(t){for(const e of t)if(Ms(e.charCodeAt(0)))return !0;return !1}const Ps=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{};}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL;}getState(){return {pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){if(Ps.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText,this.loadScriptResolve();}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(t,r){return e(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if("loading"!==t.pluginStatus)return this.setState(t),t;const e=t.pluginURL,n=new Promise((t=>{this.loadScriptResolve=t;}));r(e);const i=new Promise((t=>setTimeout((()=>t()),this.TIMEOUT)));if(yield Promise.race([n,i]),this.isParsed()){const t={pluginStatus:"loaded",pluginURL:e};return this.setState(t),t}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${e}`)}))}};class Cs{constructor(t,e){this.zoom=t,e?(this.now=e.now||0,this.fadeDuration=e.fadeDuration||0,this.zoomHistory=e.zoomHistory||new ys,this.transition=e.transition||{},this.globalState=e.globalState||{}):(this.now=0,this.fadeDuration=0,this.zoomHistory=new ys,this.transition={},this.globalState={});}isSupportedScript(t){return function(t,e){for(const r of t)if(!Is(r.charCodeAt(0),e))return !1;return !0}(t,"loaded"===Ps.getRTLTextPluginStatus())}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}}}class Bs{constructor(t,e){this.property=t,this.value=e,this.expression=function(t,e){if(Hn(t))return new ui(t,e);if(ii(t)){const r=li(t,e);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return r.value}{let r=t;return "color"===e.type&&"string"==typeof t?r=Pe.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"numberArray"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"colorArray"!==e.type||"string"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)?r=Oe.parse(t):"projectionDefinition"===e.type&&"string"==typeof t&&(r=je.parse(t)):r=Le.parse(t):r=Fe.parse(t):r=Ve.parse(t),{globalStateRefs:new Set,kind:"constant",evaluate:()=>r}}}(void 0===e?t.specification.default:e,t.specification);}isDataDriven(){return "source"===this.expression.kind||"composite"===this.expression.kind}getGlobalStateRefs(){return this.expression.globalStateRefs||new Set}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class Es{constructor(t){this.property=t,this.value=new Bs(t,void 0);}transitioned(t,e){return new Vs(this.property,this.value,e,j({},t.transition,this.transition),t.now)}untransitioned(){return new Vs(this.property,this.value,null,{},0)}}class Ts{constructor(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues);}getValue(t){return G(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Es(this._values[t].property)),this._values[t].value=new Bs(this._values[t].property,null===e?void 0:G(e));}getTransition(t){return G(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Es(this._values[t].property)),this._values[t].transition=G(e)||void 0;}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r);const n=this.getTransition(e);void 0!==n&&(t[`${e}-transition`]=n);}return t}transitioned(t,e){const r=new Fs(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new Fs(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class Vs{constructor(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(nn.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Ns{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new Cs(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Cs(Math.floor(e.zoom),e)),t.expression.evaluate(new Cs(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Us{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)}interpolate(){return !1}}class qs{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const r=t[e];r.specification.overridable&&this.overridableProperties.push(e);const n=this.defaultPropertyValues[e]=new Bs(r,void 0),i=this.defaultTransitionablePropertyValues[e]=new Es(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}}}us("DataDrivenProperty",Rs),us("DataConstantProperty",Os),us("CrossFadedDataDrivenProperty",js),us("CrossFadedProperty",Ns),us("ColorRampProperty",Us);const Gs="-transition";class Xs extends bt{constructor(t,e){if(super(),this.id=t.id,this.type=t.type,this._featureFilter={filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter,this._featureFilter=di(t.filter)),e.layout&&(this._unevaluatedLayout=new Ls(e.layout)),e.paint)){this._transitionablePaint=new Ts(e.paint);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Ds(e.paint);}}setFilter(t){this.filter=t,this._featureFilter=di(t);}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}getLayoutAffectingGlobalStateRefs(){const t=new Set;if(this._unevaluatedLayout)for(const e in this._unevaluatedLayout._values){const r=this._unevaluatedLayout._values[e];for(const e of r.getGlobalStateRefs())t.add(e);}for(const e of this._featureFilter.getGlobalStateRefs())t.add(e);return t}setLayoutProperty(t,e,r={}){null!=e&&this._validate(ss,`layers.${this.id}.layout.${t}`,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);}getPaintProperty(t){return t.endsWith(Gs)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(is,`layers.${this.id}.paint.${t}`,t,e,r))return !1;if(t.endsWith(Gs))return this._transitionablePaint.setTransition(t.slice(0,-11),e||void 0),!1;{const r=this._transitionablePaint._values[t],n="cross-faded-data-driven"===r.property.specification["property-type"],i=r.value.isDataDriven(),s=r.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const a=this._transitionablePaint._values[t].value;return a.isDataDriven()||i||n||this._handleOverridablePaintPropertyUpdate(t,s,a)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,r){return !1}isHidden(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),q(t,((t,e)=>!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return (!i||!1!==i.validate)&&as(this,t.call(es,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:wt,style:{glyphs:!0,sprite:!0}}))}is3D(){return !1}isTileClipped(){return !1}hasOffscreenPass(){return !1}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof $s&&Gn(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1}}const Zs={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Ys{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class Hs{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Ks(t,e=1){let r=0,n=0;return {members:t.map((t=>{const i=Zs[t.type].BYTES_PER_ELEMENT,s=r=Js(r,Math.max(e,i)),a=t.components||1;return n=Math.max(n,i),r+=i*a,{name:t.name,type:t.type,components:a,offset:s}})),size:Js(r,Math.max(n,e)),alignment:e}}function Js(t,e){return Math.ceil(t/e)*e}class Ws extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}Ws.prototype.bytesPerElement=4,us("StructArrayLayout2i4",Ws);class Qs extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}Qs.prototype.bytesPerElement=6,us("StructArrayLayout3i6",Qs);class ta extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}ta.prototype.bytesPerElement=8,us("StructArrayLayout4i8",ta);class ea extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}ea.prototype.bytesPerElement=12,us("StructArrayLayout2i4i12",ea);class ra extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=4*t,l=8*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.uint8[l+4]=n,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=a,t}}ra.prototype.bytesPerElement=8,us("StructArrayLayout2i4ub8",ra);class na extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}na.prototype.bytesPerElement=8,us("StructArrayLayout2f8",na);class ia extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,s,a,o,l,u)}emplace(t,e,r,n,i,s,a,o,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=r,this.uint16[h+2]=n,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=a,this.uint16[h+6]=o,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}ia.prototype.bytesPerElement=20,us("StructArrayLayout10ui20",ia);class sa extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,a,o,l,u,c,h)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=a,this.uint16[f+6]=o,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}sa.prototype.bytesPerElement=24,us("StructArrayLayout4i4ui4i24",sa);class aa extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}aa.prototype.bytesPerElement=12,us("StructArrayLayout3f12",aa);class oa extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}oa.prototype.bytesPerElement=4,us("StructArrayLayout1ul4",oa);class la extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,s,a,o,l)}emplace(t,e,r,n,i,s,a,o,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=r,this.int16[c+2]=n,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=a,this.uint32[h+3]=o,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}la.prototype.bytesPerElement=20,us("StructArrayLayout6i1ul2ui20",la);class ua extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}ua.prototype.bytesPerElement=12,us("StructArrayLayout2i2i2i12",ua);class ca extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.int16[o+6]=i,this.int16[o+7]=s,t}}ca.prototype.bytesPerElement=16,us("StructArrayLayout2f1f2i16",ca);class ha extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=16*t,l=4*t,u=8*t;return this.uint8[o+0]=e,this.uint8[o+1]=r,this.float32[l+1]=n,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=a,t}}ha.prototype.bytesPerElement=16,us("StructArrayLayout2ub2f2i16",ha);class pa extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}pa.prototype.bytesPerElement=6,us("StructArrayLayout3ui6",pa);class fa extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=r,this.uint16[x+2]=n,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=a,this.uint32[v+4]=o,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}fa.prototype.bytesPerElement=48,us("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",fa);class da extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I){const z=this.length;return this.resize(z+1),this.emplace(z,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I,z){const P=32*t,C=16*t;return this.int16[P+0]=e,this.int16[P+1]=r,this.int16[P+2]=n,this.int16[P+3]=i,this.int16[P+4]=s,this.int16[P+5]=a,this.int16[P+6]=o,this.int16[P+7]=l,this.uint16[P+8]=u,this.uint16[P+9]=c,this.uint16[P+10]=h,this.uint16[P+11]=p,this.uint16[P+12]=f,this.uint16[P+13]=d,this.uint16[P+14]=y,this.uint16[P+15]=m,this.uint16[P+16]=g,this.uint16[P+17]=x,this.uint16[P+18]=v,this.uint16[P+19]=b,this.uint16[P+20]=w,this.uint16[P+21]=_,this.uint16[P+22]=S,this.uint32[C+12]=A,this.float32[C+13]=k,this.float32[C+14]=M,this.uint16[P+30]=I,this.uint16[P+31]=z,t}}da.prototype.bytesPerElement=64,us("StructArrayLayout8i15ui1ul2f2ui64",da);class ya extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}ya.prototype.bytesPerElement=4,us("StructArrayLayout1f4",ya);class ma extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}ma.prototype.bytesPerElement=12,us("StructArrayLayout1ui2f12",ma);class ga extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t}}ga.prototype.bytesPerElement=8,us("StructArrayLayout1ul2ui8",ga);class xa extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}xa.prototype.bytesPerElement=4,us("StructArrayLayout2ui4",xa);class va extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}va.prototype.bytesPerElement=2,us("StructArrayLayout1ui2",va);class ba extends Hs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}ba.prototype.bytesPerElement=16,us("StructArrayLayout4f16",ba);class wa extends Ys{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new l(this.anchorPointX,this.anchorPointY)}}wa.prototype.size=20;class _a extends la{get(t){return new wa(this,t)}}us("CollisionBoxArray",_a);class Sa extends Ys{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t;}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}Sa.prototype.size=48;class Aa extends fa{get(t){return new Sa(this,t)}}us("PlacedSymbolArray",Aa);class ka extends Ys{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t;}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}ka.prototype.size=64;class Ma extends da{get(t){return new ka(this,t)}}us("SymbolInstanceArray",Ma);class Ia extends ya{getoffsetX(t){return this.float32[1*t+0]}}us("GlyphOffsetArray",Ia);class za extends Qs{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}us("SymbolLineVertexArray",za);class Pa extends Ys{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}Pa.prototype.size=12;class Ca extends ma{get(t){return new Pa(this,t)}}us("TextAnchorOffsetArray",Ca);class Ba extends Ys{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}Ba.prototype.size=8;class Ea extends ga{get(t){return new Ba(this,t)}}us("FeatureIndexArray",Ea);class Ta extends Ws{}class Va extends Ws{}class Fa extends Ws{}class La extends ea{}class $a extends ra{}class Da extends na{}class Oa extends ia{}class Ra extends sa{}class ja extends aa{}class Na extends oa{}class Ua extends ua{}class qa extends ha{}class Ga extends pa{}class Xa extends xa{}const Za=Ks([{name:"a_pos",components:2,type:"Int16"}],4),{members:Ya}=Za;class Ha{constructor(t=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=t;}prepareSegment(t,e,r,n){const i=this.segments[this.segments.length-1];return t>Ha.MAX_VERTEX_ARRAY_LENGTH&&Z(`Max vertices per segment is ${Ha.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${Ha.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!i||i.vertexLength+t>Ha.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n?this.createNewSegment(e,r,n):i}createNewSegment(t,e,r){const n={vertexOffset:t.length,primitiveOffset:e.length,vertexLength:0,primitiveLength:0,vaos:{}};return void 0!==r&&(n.sortKey=r),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(n),n}getOrCreateLatestSegment(t,e,r){return this.prepareSegment(0,t,e,r)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0;}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,r,n){return new Ha([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function Ka(t,e){return 256*(t=O(Math.floor(t),0,255))+O(Math.floor(e),0,255)}Ha.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,us("SegmentVector",Ha);const Ja=Ks([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var Wa,Qa,to,eo={exports:{}},ro={exports:{}},no={exports:{}},io=function(){if(to)return eo.exports;to=1;var t=(Wa||(Wa=1,ro.exports=function(t,e){var r,n,i,s,a,o,l,u;for(n=t.length-(r=3&t.length),i=e,a=3432918353,o=461845907,u=0;u>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0}),ro.exports),e=(Qa||(Qa=1,no.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0}),no.exports);return eo.exports=t,eo.exports.murmur3=t,eo.exports.murmur2=e,eo.exports}(),so=r(io);class ao{constructor(){this.ids=[],this.positions=[],this.indexed=!1;}add(t,e,r,n){this.ids.push(oo(t)),this.positions.push(e,r,n);}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=oo(t);let r=0,n=this.ids.length-1;for(;r>1;this.ids[t]>=e?n=t:r=t+1;}const i=[];for(;this.ids[r]===e;)i.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return i}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return lo(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}}static deserialize(t){const e=new ao;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e}}function oo(t){const e=+t;return !isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:so(String(t))}function lo(t,e,r,n){for(;r>1];let s=r-1,a=n+1;for(;;){do{s++;}while(t[s]i);if(s>=a)break;uo(t,s,a),uo(e,3*s,3*a),uo(e,3*s+1,3*a+1),uo(e,3*s+2,3*a+2);}a-r`u_${t}`)),this.type=r;}setUniform(t,e,r){t.set(r.constantOr(this.value));}getBinding(t,e,r){return "color"===this.type?new fo(t,e):new ho(t,e)}}class xo{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;}setUniform(t,e,r,n){const i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);}getBinding(t,e,r){return "u_pattern"===r.substr(0,9)?new po(t,e):new ho(t,e)}}class vo{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?2:1,offset:0}))),this.paintVertexArray=new n;}populatePaintArray(t,e,r,n,i){const s=this.paintVertexArray.length,a=this.expression.evaluate(new Cs(0),e,{},n,[],i);this.paintVertexArray.resize(t),this._setPaintValue(s,t,a);}updatePaintArray(t,e,r,n){const i=this.expression.evaluate({zoom:0},r,n);this._setPaintValue(t,e,i);}_setPaintValue(t,e,r){if("color"===this.type){const n=mo(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Cs(this.zoom),e,{},n,[],i),a=this.expression.evaluate(new Cs(this.zoom+1),e,{},n,[],i),o=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(o,t,s,a);}updatePaintArray(t,e,r,n){const i=this.expression.evaluate({zoom:this.zoom},r,n),s=this.expression.evaluate({zoom:this.zoom+1},r,n);this._setPaintValue(t,e,i,s);}_setPaintValue(t,e,r,n){if("color"===this.type){const i=mo(r),s=mo(n);for(let r=t;r`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof vo||r instanceof bo)for(let e=0;e!0){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new _o(n,e,r);this.needsUpload=!1,this._featureMap=new ao,this._bufferOffset=0;}populatePaintArrays(t,e,r,n,i,s){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n,i,s);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;}updatePaintArrays(t,e,r,n){for(const i of r)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,n)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}function Ao(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function ko(t,e,r){const n={color:{source:na,composite:ba},number:{source:ya,composite:na}},i=function(t){return {"line-pattern":{source:Oa,composite:Oa},"fill-pattern":{source:Oa,composite:Oa},"fill-extrusion-pattern":{source:Oa,composite:Oa}}[t]}(t);return i&&i[r]||n[e][r]}us("ConstantBinder",go),us("CrossFadedConstantBinder",xo),us("SourceExpressionBinder",vo),us("CrossFadedCompositeBinder",wo),us("CompositeExpressionBinder",bo),us("ProgramConfiguration",_o,{omit:["_buffers"]}),us("ProgramConfigurationSet",So);const Mo=Math.pow(2,14)-1,Io=-Mo-1;function zo(t){const e=E/t.extent,r=t.loadGeometry();for(let t=0;tr.x+1||sr.y+1)&&Z("Geometry exceeds allowed extent, reduce your vector tile buffer size");}}return r}function Po(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?zo(t):[]}}const Co=-32768;function Bo(t,e,r,n,i){t.emplaceBack(Co+8*e+n,Co+8*r+i);}class Eo{constructor(t){this.zoom=t.zoom,this.globalState=t.globalState,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Va,this.indexArray=new Ga,this.segments=new Ha,this.programConfigurations=new So(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){const n=this.layers[0],i=[];let s=null,a=!1,o="heatmap"===n.type;if("circle"===n.type){const t=n;s=t.layout.get("circle-sort-key"),a=!s.isConstant(),o=o||"map"===t.paint.get("circle-pitch-alignment");}const l=o?e.subdivisionGranularity.circle:1;for(const{feature:e,id:n,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Po(e,t);if(!this.layers[0]._featureFilter.filter(new Cs(this.zoom,{globalState:this.globalState}),u,r))continue;const c=a?s.evaluate(u,{},r):void 0,h={id:n,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:zo(e),patterns:{},sortKey:c};i.push(h);}a&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of i){const{geometry:i,index:s,sourceLayerIndex:a}=n,o=t[s].feature;this.addFeature(n,i,s,r,l),e.featureIndex.insert(o,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Ya),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,r,n,i=1){let s;switch(i){case 1:s=[0,7];break;case 3:s=[0,2,5,7];break;case 5:s=[0,1,3,4,6,7];break;case 7:s=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${i}; valid values are 1, 3, 5, 7.`)}const a=s.length;for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=E||n<0||n>=E)continue;const i=this.segments.prepareSegment(a*a,this.layoutVertexArray,this.indexArray,t.sortKey),o=i.vertexLength;for(let t=0;t1){if($o(t,e))return !0;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function jo(t,e){let r,n,i,s=!1;for(let a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s);}return s}function No(t,e){let r=!1;for(let n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-s.x)*(e.y-s.y)/(a.y-s.y)+s.x&&(r=!r);}return r}function Uo(t,e,r){const n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;const s=Y(t,e,r[0]);return s!==Y(t,e,r[1])||s!==Y(t,e,r[2])||s!==Y(t,e,r[3])}function qo(t,e,r){const n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function Go(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function Xo(t,e,r,n,i){if(!e[0]&&!e[1])return t;const s=l.convert(e)._mult(i);"viewport"===r&&s._rotate(-n);const a=[];for(let e=0;eJo(t,e,r,n)))}(l,i,a,o),p=c?u*s:u;for(const t of n)for(const e of t){const t=c?e:Jo(e,i,a,o);let r=p;const n=i.projectTileCoordinates(e.x,e.y,a,o).signedDistanceFromCamera;if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?r*=n/i.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(r*=i.cameraToCenterDistance/n),Vo(h,t,r))return !0}return !1}}function Jo(t,e,r,n){const i=e.projectTileCoordinates(t.x,t.y,r,n).point;return new l((.5*i.x+.5)*e.width,(.5*-i.y+.5)*e.height)}class Wo extends Eo{}let Qo;us("HeatmapBucket",Wo,{omit:["layers"]});var tl={get paint(){return Qo=Qo||new qs({"heatmap-radius":new Rs(wt.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Rs(wt.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Os(wt.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Us(wt.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Os(wt.paint_heatmap["heatmap-opacity"])})}};function el(t,{width:e,height:r},n,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*r*n)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*r*n}`)}else i=new Uint8Array(e*r*n);return t.width=e,t.height=r,t.data=i,t}function rl(t,{width:e,height:r},n){if(e===t.width&&r===t.height)return;const i=el({},{width:e,height:r},n);nl(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,r)},n),t.width=e,t.height=r,t.data=i.data;}function nl(t,e,r,n,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const a=t.data,o=e.data;if(a===o)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=a;const o=t.expression.evaluate(e);i.setPixel(n/4/r,s/4,o);};if(t.clips)for(let e=0,i=0;ethis.max&&(this.max=r),r=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)}unpack(t,e,r){return t*this.redFactor+e*this.greenFactor+r*this.blueFactor-this.baseShift}pack(t){return ml(t,this.getUnpackVector())}getPixels(){return new sl({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,a=r*this.dim+this.dim;switch(e){case -1:n=i-1;break;case 1:i=n+1;}switch(r){case -1:s=a-1;break;case 1:a=s+1;}const o=-e*this.dim,l=-r*this.dim;for(let e=s;e0)for(let i=e;i=e;i-=n)s=ql(i/n|0,t[i],t[i+1],s);return s&&Dl(s,s.next)&&(Gl(s),s=s.next),s}function Sl(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!Dl(n,n.next)&&0!==$l(n.prev,n,n.next))n=n.next;else {if(Gl(n),n=e=n.prev,n===n.next)break;r=!0;}}while(r||n!==e);return e}function Al(t,e,r,n,i,s,a){if(!t)return;!a&&s&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=El(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let s=null;for(e=0;i;){e++;let a=i,o=0;for(let t=0;t0||l>0&&a;)0!==o&&(0===l||!a||i.z<=a.z)?(n=i,i=i.nextZ,o--):(n=a,a=a.nextZ,l--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;i=a;}s.nextZ=null,r*=2;}while(e>1)}(i);}(t,n,i,s);let o=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?Ml(t,n,i,s):kl(t))e.push(l.i,t.i,u.i),Gl(t),t=u.next,o=u.next;else if((t=u)===o){a?1===a?Al(t=Il(Sl(t),e),e,r,n,i,s,2):2===a&&zl(t,e,r,n,i,s):Al(Sl(t),e,r,n,i,s,1);break}}}function kl(t){const e=t.prev,r=t,n=t.next;if($l(e,r,n)>=0)return !1;const i=e.x,s=r.x,a=n.x,o=e.y,l=r.y,u=n.y,c=Math.min(i,s,a),h=Math.min(o,l,u),p=Math.max(i,s,a),f=Math.max(o,l,u);let d=n.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&Fl(i,o,s,l,a,u,d.x,d.y)&&$l(d.prev,d,d.next)>=0)return !1;d=d.next;}return !0}function Ml(t,e,r,n){const i=t.prev,s=t,a=t.next;if($l(i,s,a)>=0)return !1;const o=i.x,l=s.x,u=a.x,c=i.y,h=s.y,p=a.y,f=Math.min(o,l,u),d=Math.min(c,h,p),y=Math.max(o,l,u),m=Math.max(c,h,p),g=El(f,d,e,r,n),x=El(y,m,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Fl(o,c,l,h,u,p,v.x,v.y)&&$l(v.prev,v,v.next)>=0)return !1;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Fl(o,c,l,h,u,p,b.x,b.y)&&$l(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Fl(o,c,l,h,u,p,v.x,v.y)&&$l(v.prev,v,v.next)>=0)return !1;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Fl(o,c,l,h,u,p,b.x,b.y)&&$l(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}return !0}function Il(t,e){let r=t;do{const n=r.prev,i=r.next.next;!Dl(n,i)&&Ol(n,r,r.next,i)&&Nl(n,i)&&Nl(i,n)&&(e.push(n.i,r.i,i.i),Gl(r),Gl(r.next),r=t=i),r=r.next;}while(r!==t);return Sl(r)}function zl(t,e,r,n,i,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Ll(a,t)){let o=Ul(a,t);return a=Sl(a,a.next),o=Sl(o,o.next),Al(a,e,r,n,i,s,0),void Al(o,e,r,n,i,s,0)}t=t.next;}a=a.next;}while(a!==t)}function Pl(t,e){let r=t.x-e.x;return 0===r&&(r=t.y-e.y,0===r)&&(r=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)),r}function Cl(t,e){const r=function(t,e){let r=e;const n=t.x,i=t.y;let s,a=-1/0;if(Dl(t,r))return r;do{if(Dl(t,r.next))return r.next;if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){const t=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(t<=n&&t>a&&(a=t,s=r.x=r.x&&r.x>=l&&n!==r.x&&Vl(is.x||r.x===s.x&&Bl(s,r)))&&(s=r,c=e);}r=r.next;}while(r!==o);return s}(t,e);if(!r)return e;const n=Ul(r,t);return Sl(n,n.next),Sl(r,r.next)}function Bl(t,e){return $l(t.prev,t,e.prev)<0&&$l(e.next,t,t.next)<0}function El(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Tl(t){let e=t,r=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(r-a)*(e-o)&&(r-a)*(s-o)>=(i-a)*(n-o)}function Fl(t,e,r,n,i,s,a,o){return !(t===a&&e===o)&&Vl(t,e,r,n,i,s,a,o)}function Ll(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&Ol(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(Nl(t,e)&&Nl(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&($l(t.prev,t,e.prev)||$l(t,e.prev,e))||Dl(t,e)&&$l(t.prev,t,t.next)>0&&$l(e.prev,e,e.next)>0)}function $l(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Dl(t,e){return t.x===e.x&&t.y===e.y}function Ol(t,e,r,n){const i=jl($l(t,e,r)),s=jl($l(t,e,n)),a=jl($l(r,n,t)),o=jl($l(r,n,e));return i!==s&&a!==o||!(0!==i||!Rl(t,r,e))||!(0!==s||!Rl(t,n,e))||!(0!==a||!Rl(r,t,n))||!(0!==o||!Rl(r,e,n))}function Rl(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function jl(t){return t>0?1:t<0?-1:0}function Nl(t,e){return $l(t.prev,t,t.next)<0?$l(t,e,t.next)>=0&&$l(t,t.prev,e)>=0:$l(t,e,t.prev)<0||$l(t,t.next,e)<0}function Ul(t,e){const r=Xl(t.i,t.x,t.y),n=Xl(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function ql(t,e,r,n){const i=Xl(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Gl(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 Xl(t,e,r){return {i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class Zl{constructor(t,e){if(e>t)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=t,this._minGranularity=e;}getGranularityForZoomLevel(t){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||e>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const r=0|Math.round(t),n=0|Math.round(e),i=this._getKey(r,n);if(this._vertexDictionary.has(i))return this._vertexDictionary.get(i);const s=this._vertexBuffer.length/2;return this._vertexDictionary.set(i,s),this._vertexBuffer.push(r,n),s}_subdivideTrianglesScanline(t){if(this._granularity<2)return function(t,e){const r=[];for(let n=0;n0?(r.push(i),r.push(a),r.push(s)):(r.push(i),r.push(s),r.push(a));}return r}(this._vertexBuffer,t);const e=[],r=t.length;for(let n=0;n=1||v<=0)||y&&(oi)){u>=n&&u<=i&&s.push(r[(t+1)%3]);continue}!y&&x>0&&s.push(this._vertexToIndex(a+p*x,o+f*x));const b=a+p*Math.max(x,0),w=a+p*Math.min(v,1);d||this._generateIntraEdgeVertices(s,a,o,l,u,b,w),!y&&v<1&&s.push(this._vertexToIndex(a+p*v,o+f*v)),(y||u>=n&&u<=i)&&s.push(r[(t+1)%3]),!y&&(u<=n||u>=i)&&this._generateInterEdgeVertices(s,a,o,l,u,c,h,w,n,i);}return s}_generateIntraEdgeVertices(t,e,r,n,i,s,a){const o=n-e,l=i-r,u=0===l,c=u?Math.min(e,n):Math.min(s,a),h=u?Math.max(e,n):Math.max(s,a),p=Math.floor(c/this._granularityCellSize)+1,f=Math.ceil(h/this._granularityCellSize)-1;if(u?e=p;n--){const i=n*this._granularityCellSize;t.push(this._vertexToIndex(i,r+l*(i-e)/o));}}_generateInterEdgeVertices(t,e,r,n,i,s,a,o,l,u){const c=i-r,h=s-n,p=a-i,f=(l-i)/p,d=(u-i)/p,y=Math.min(f,d),m=Math.max(f,d),g=n+h*y;let x=Math.floor(Math.min(g,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(g,o)/this._granularityCellSize)-1,b=o=1||m<=0){const t=r-a,n=s+(e-s)*Math.min((l-a)/t,(u-a)/t);x=Math.floor(Math.min(n,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(n,o)/this._granularityCellSize)-1,b=o0?u:l;if(b)for(let e=x;e<=v;e++)t.push(this._vertexToIndex(e*this._granularityCellSize,_));else for(let e=v;e>=x;e--)t.push(this._vertexToIndex(e*this._granularityCellSize,_));}_generateOutline(t){const e=[];for(const r of t){const t=Ql(r,this._granularity,!0),n=this._pointArrayToIndices(t),i=[];for(let t=1;ti!=(s===Hl)?(t.push(e),t.push(r),t.push(this._vertexToIndex(n,s)),t.push(r),t.push(this._vertexToIndex(i,s)),t.push(this._vertexToIndex(n,s))):(t.push(r),t.push(e),t.push(this._vertexToIndex(n,s)),t.push(this._vertexToIndex(i,s)),t.push(r),t.push(this._vertexToIndex(n,s)));}_fillPoles(t,e,r){const n=this._vertexBuffer,i=E,s=t.length;for(let a=2;a80*r){o=1/0,l=1/0;let e=-1/0,n=-1/0;for(let s=r;se&&(e=r),i>n&&(n=i);}u=Math.max(e-o,n-l),u=0!==u?32767/u:0;}return Al(s,a,r,o,l,u,0),a}(r,n),e=this._convertIndices(r,t);i=this._subdivideTrianglesScanline(e);}catch(t){console.error(t);}let s=[];return e&&(s=this._generateOutline(t)),this._ensureNoPoleVertices(),this._handlePoles(i),{verticesFlattened:this._vertexBuffer,indicesTriangles:i,indicesLineList:s}}_convertIndices(t,e){const r=[];for(let n=0;n0?(Math.floor(x/a)+1)*a:(Math.ceil(x/a)-1)*a,e=y>0?(Math.floor(v/a)+1)*a:(Math.ceil(v/a)-1)*a,r=Math.abs(x-t),n=Math.abs(v-e),i=Math.abs(x-c),s=Math.abs(v-h),u=p?r/m:Number.POSITIVE_INFINITY,b=f?n/g:Number.POSITIVE_INFINITY;if((i<=r||!p)&&(s<=n||!f))break;if(u=0?a-1:s-1,i=(o+1)%s,l=t[2*e[n]],u=t[2*e[i]],c=t[2*e[a]],h=t[2*e[a]+1],p=t[2*e[o]+1];let f=!1;if(lu)f=!1;else {const r=p-h,s=-(t[2*e[o]]-c),a=h((u-c)*r+(t[2*e[i]+1]-h)*s)*a&&(f=!0);}if(f){const t=e[n],i=e[a],l=e[o];t!==i&&t!==l&&i!==l&&r.push(l,i,t),a--,a<0&&(a=s-1);}else {const t=e[i],n=e[a],l=e[o];t!==n&&t!==l&&n!==l&&r.push(l,n,t),o++,o>=s&&(o=0);}if(n===i)break}}function eu(t,e,r,n,i,s,a,o,l){const u=i.length/2,c=a&&o&&l;if(uHa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,y=!0,m=!0,g=!0,c=0);const x=ru(a,n,s,o,p,y,u),v=ru(a,n,s,o,f,m,u),b=ru(a,n,s,o,d,g,u);r.emplaceBack(c+x-l,c+v-l,c+b-l),u.primitiveLength++;}}(e,r,n,i,s,t),c&&function(t,e,r,n,i,s){const a=[];for(let t=0;tHa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,d=!0,y=!0,c=0);const m=ru(a,n,s,o,i,d,u),g=ru(a,n,s,o,h,y,u);r.emplaceBack(c+m-l,c+g-l),u.primitiveLength++;}}}(a,r,o,i,l,t),e.forceNewSegmentOnNextPrepare(),null==a||a.forceNewSegmentOnNextPrepare();}function ru(t,e,r,n,i,s,a){if(s){const s=n.count;return r(e[2*i],e[2*i+1]),t[i]=n.count,n.count++,a.vertexLength++,s}return t[i]}class nu{constructor(t){this.zoom=t.zoom,this.globalState=t.globalState,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Fa,this.indexArray=new Ga,this.indexArray2=new Xa,this.programConfigurations=new So(t.layers,t.zoom),this.segments=new Ha,this.segments2=new Ha,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=bl("fill",this.layers,e);const n=this.layers[0].layout.get("fill-sort-key"),i=!n.isConstant(),s=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=Po(a,t);if(!this.layers[0]._featureFilter.filter(new Cs(this.zoom,{globalState:this.globalState}),c,r))continue;const h=i?n.evaluate(c,{},r,e.availableImages):void 0,p={id:o,properties:a.properties,type:a.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:zo(a),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=wl("fill",this.layers,n,this.zoom,e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,vl),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,r,n,i,s){for(const t of rn(e,500)){const e=Wl(t,n,s.fill.getGranularityForZoomLevel(n.z)),r=this.layoutVertexArray;eu(((t,e)=>{r.emplaceBack(t,e);}),this.segments,this.layoutVertexArray,this.indexArray,e.verticesFlattened,e.indicesTriangles,this.segments2,this.indexArray2,e.indicesLineList);}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);}}let iu,su;us("FillBucket",nu,{omit:["layers","patternFeatures"]});var au={get paint(){return su=su||new qs({"fill-antialias":new Os(wt.paint_fill["fill-antialias"]),"fill-opacity":new Rs(wt.paint_fill["fill-opacity"]),"fill-color":new Rs(wt.paint_fill["fill-color"]),"fill-outline-color":new Rs(wt.paint_fill["fill-outline-color"]),"fill-translate":new Os(wt.paint_fill["fill-translate"]),"fill-translate-anchor":new Os(wt.paint_fill["fill-translate-anchor"]),"fill-pattern":new js(wt.paint_fill["fill-pattern"])})},get layout(){return iu=iu||new qs({"fill-sort-key":new Rs(wt.layout_fill["fill-sort-key"])})}};class ou extends Xs{constructor(t){super(t,au);}recalculate(t,e){super.recalculate(t,e);const r=this.paint._values["fill-outline-color"];"constant"===r.value.kind&&void 0===r.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);}createBucket(t){return new nu(t)}queryRadius(){return Go(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:t,geometry:e,transform:r,pixelsToTileUnits:n}){return Fo(Xo(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-r.bearingInRadians,n),e)}isTileClipped(){return !0}}const lu=Ks([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),uu=Ks([{name:"a_centroid",components:2,type:"Int16"}],4),{members:cu}=lu;var hu,pu,fu,du,yu,mu,gu,xu={};function vu(){if(pu)return hu;pu=1;var t=s();function e(t,e,n,i,s){this.properties={},this.extent=n,this.type=0,this._pbf=t,this._geometry=-1,this._keys=i,this._values=s,t.readFields(r,this,e);}function r(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){for(var r=t.readVarint()+t.pos;t.pos>3;}if(s--,1===i||2===i)a+=e.readSVarint(),o+=e.readSVarint(),1===i&&(r&&l.push(r),r=[]),r.push(new t(a,o));else {if(7!==i)throw new Error("unknown command "+i);r&&r.push(r[0].clone());}}return r&&l.push(r),l},e.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,s=0,a=1/0,o=-1/0,l=1/0,u=-1/0;t.pos>3;}if(n--,1===r||2===r)(i+=t.readSVarint())o&&(o=i),(s+=t.readSVarint())u&&(u=s);else if(7!==r)throw new Error("unknown command "+r)}return [a,l,o,u]},e.prototype.toGeoJSON=function(t,r,i){var s,a,o=this.extent*Math.pow(2,i),l=this.extent*t,u=this.extent*r,c=this.loadGeometry(),h=e.types[this.type];function p(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}return e}(r));}return fu=e,e.prototype.feature=function(e){if(e<0||e>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[e];var r=this._pbf.readVarint()+this._pbf.pos;return new t(this._pbf,r,this.extent,this._keys,this._values)},fu}function wu(){return gu||(gu=1,xu.VectorTile=function(){if(mu)return yu;mu=1;var t=bu();function e(e,r,n){if(3===e){var i=new t(n,n.readVarint()+n.pos);i.length&&(r[i.name]=i);}}return yu=function(t,r){this.layers=t.readFields(e,{},r);},yu}(),xu.VectorTileFeature=vu(),xu.VectorTileLayer=bu()),xu}var _u=r(wu());const Su=_u.VectorTileFeature.types,Au=Math.pow(2,13);function ku(t,e,r,n,i,s,a,o){t.emplaceBack(e,r,2*Math.floor(n*Au)+a,i*Au*2,s*Au*2,Math.round(o));}class Mu{constructor(t){this.zoom=t.zoom,this.globalState=t.globalState,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new La,this.centroidVertexArray=new Ta,this.indexArray=new Ga,this.programConfigurations=new So(t.layers,t.zoom),this.segments=new Ha,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.features=[],this.hasPattern=bl("fill-extrusion",this.layers,e);for(const{feature:n,id:i,index:s,sourceLayerIndex:a}of t){const t=this.layers[0]._featureFilter.needGeometry,o=Po(n,t);if(!this.layers[0]._featureFilter.filter(new Cs(this.zoom,{globalState:this.globalState}),o,r))continue;const l={id:i,sourceLayerIndex:a,index:s,geometry:t?o.geometry:zo(n),properties:n.properties,type:n.type,patterns:{}};this.hasPattern?this.features.push(wl("fill-extrusion",this.layers,l,this.zoom,e)):this.addFeature(l,l.geometry,s,r,{},e.subdivisionGranularity),e.featureIndex.insert(n,l.geometry,s,a,this.index,!0);}}addFeatures(t,e,r){for(const n of this.features){const{geometry:i}=n;this.addFeature(n,i,n.index,e,r,t.subdivisionGranularity);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,cu),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,uu.members,!0),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy());}addFeature(t,e,r,n,i,s){for(const r of rn(e,500)){const e={x:0,y:0,sampleCount:0},i=this.layoutVertexArray.length;this.processPolygon(e,n,t,r,s);const a=this.layoutVertexArray.length-i,o=Math.floor(e.x/e.sampleCount),l=Math.floor(e.y/e.sampleCount);for(let t=0;t{ku(u,t,e,0,0,1,1,0);}),this.segments,this.layoutVertexArray,this.indexArray,l.verticesFlattened,l.indicesTriangles);}_generateSideFaces(t,e){let r=0;for(let n=1;nHa.MAX_VERTEX_ARRAY_LENGTH&&(e.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const a=i.sub(s)._perp()._unit(),o=s.dist(i);r+o>32768&&(r=0),ku(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,0,r),ku(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,1,r),r+=o,ku(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,0,r),ku(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,1,r);const l=e.segment.vertexLength;this.indexArray.emplaceBack(l,l+2,l+1),this.indexArray.emplaceBack(l+1,l+2,l+3),e.segment.vertexLength+=4,e.segment.primitiveLength+=2;}}}function Iu(t,e){for(let r=0;rE)||t.y===e.y&&(t.y<0||t.y>E)}function Pu(t){return t.every((t=>t.x<0))||t.every((t=>t.x>E))||t.every((t=>t.y<0))||t.every((t=>t.y>E))}let Cu;us("FillExtrusionBucket",Mu,{omit:["layers","features"]});var Bu={get paint(){return Cu=Cu||new qs({"fill-extrusion-opacity":new Os(wt["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Rs(wt["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Os(wt["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Os(wt["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new js(wt["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Rs(wt["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Rs(wt["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new Os(wt["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class Eu extends Xs{constructor(t){super(t,Bu);}createBucket(t){return new Mu(t)}queryRadius(){return Go(this.paint.get("fill-extrusion-translate"))}is3D(){return !0}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:r,geometry:n,transform:i,pixelsToTileUnits:s,pixelPosMatrix:a}){const o=Xo(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-i.bearingInRadians,s),u=this.paint.get("fill-extrusion-height").evaluate(e,r),c=this.paint.get("fill-extrusion-base").evaluate(e,r),h=function(t,e){const r=[];for(const n of t){const t=[n.x,n.y,0,1];I(t,t,e),r.push(new l(t[0]/t[3],t[1]/t[3]));}return r}(o,a),p=function(t,e,r,n){const i=[],s=[],a=n[8]*e,o=n[9]*e,u=n[10]*e,c=n[11]*e,h=n[8]*r,p=n[9]*r,f=n[10]*r,d=n[11]*r;for(const e of t){const t=[],r=[];for(const i of e){const e=i.x,s=i.y,y=n[0]*e+n[4]*s+n[12],m=n[1]*e+n[5]*s+n[13],g=n[2]*e+n[6]*s+n[14],x=n[3]*e+n[7]*s+n[15],v=g+u,b=x+c,w=y+h,_=m+p,S=g+f,A=x+d,k=new l((y+a)/b,(m+o)/b);k.z=v/b,t.push(k);const M=new l(w/A,_/A);M.z=S/A,r.push(M);}i.push(t),s.push(r);}return [i,s]}(n,c,u,a);return function(t,e,r){let n=1/0;Fo(r,e)&&(n=Vu(r,e[0]));for(let i=0;it.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new $a,this.layoutVertexArray2=new Da,this.indexArray=new Ga,this.programConfigurations=new So(t.layers,t.zoom),this.segments=new Ha,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=bl("line",this.layers,e);const n=this.layers[0].layout.get("line-sort-key"),i=!n.isConstant(),s=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Po(e,t);if(!this.layers[0]._featureFilter.filter(new Cs(this.zoom,{globalState:this.globalState}),u,r))continue;const c=i?n.evaluate(u,{},r):void 0,h={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:zo(e),patterns:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=wl("line",this.layers,n,this.zoom,e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,Du)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Lu),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return {start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i,s){const a=this.layers[0].layout,o=a.get("line-join").evaluate(t,{}),l=a.get("line-cap"),u=a.get("line-miter-limit"),c=a.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,o,l,u,c,n,s);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);}addLine(t,e,r,n,i,s,a,o){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,t=Ql(t,a?o.line.getGranularityForZoomLevel(a.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[u-1].equals(t[u-2]);)u--;let c=0;for(;c0;if(w&&e>c){const t=f.dist(d);if(t>2*h){const e=f.sub(f.sub(d)._mult(h/t)._round());this.updateDistance(d,e),this.addCurrentVertex(e,m,0,0,p),d=e;}}const S=d&&y;let A=S?r:l?"butt":n;if(S&&"round"===A&&(vi&&(A="bevel"),"bevel"===A&&(v>2&&(A="flipbevel"),v100)a=g.mult(-1);else {const t=v*m.add(g).mag()/m.sub(g).mag();a._perp()._mult(t*(_?-1:1));}this.addCurrentVertex(f,a,0,0,p),this.addCurrentVertex(f,a.mult(-1),0,0,p);}else if("bevel"===A||"fakeround"===A){const t=-Math.sqrt(v*v-1),e=_?t:0,r=_?0:t;if(d&&this.addCurrentVertex(f,m,e,r,p),"fakeround"===A){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*h){const e=f.add(y.sub(f)._mult(h/t)._round());this.updateDistance(f,e),this.addCurrentVertex(e,g,0,0,p),f=e;}}}}addCurrentVertex(t,e,r,n,i,s=!1){const a=e.y*n-e.x,o=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,!1,r,i),this.addHalfVertex(t,a,o,s,!0,-n,i),this.distance>ju/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,r,n,i,s));}addHalfVertex({x:t,y:e},r,n,i,s,a,o){const l=.5*(this.lineClips?this.scaledDistance*(ju-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,u,this.e2),o.primitiveLength++),s?this.e2=u:this.e1=u;}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}}let Uu,qu;us("LineBucket",Nu,{omit:["layers","patternFeatures"]});var Gu={get paint(){return qu=qu||new qs({"line-opacity":new Rs(wt.paint_line["line-opacity"]),"line-color":new Rs(wt.paint_line["line-color"]),"line-translate":new Os(wt.paint_line["line-translate"]),"line-translate-anchor":new Os(wt.paint_line["line-translate-anchor"]),"line-width":new Rs(wt.paint_line["line-width"]),"line-gap-width":new Rs(wt.paint_line["line-gap-width"]),"line-offset":new Rs(wt.paint_line["line-offset"]),"line-blur":new Rs(wt.paint_line["line-blur"]),"line-dasharray":new Ns(wt.paint_line["line-dasharray"]),"line-pattern":new js(wt.paint_line["line-pattern"]),"line-gradient":new Us(wt.paint_line["line-gradient"])})},get layout(){return Uu=Uu||new qs({"line-cap":new Os(wt.layout_line["line-cap"]),"line-join":new Rs(wt.layout_line["line-join"]),"line-miter-limit":new Os(wt.layout_line["line-miter-limit"]),"line-round-limit":new Os(wt.layout_line["line-round-limit"]),"line-sort-key":new Rs(wt.layout_line["line-sort-key"])})}};class Xu extends Rs{possiblyEvaluate(t,e){return e=new Cs(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=j({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}let Zu;class Yu extends Xs{constructor(t){super(t,Gu),this.gradientVersion=0,Zu||(Zu=new Xu(Gu.paint.properties["line-width"].specification),Zu.useIntegerZoom=!0);}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return void 0!==t._styleExpression}(t)&&t._styleExpression.expression instanceof ur,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=Zu.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t);}createBucket(t){return new Nu(t)}queryRadius(t){const e=t,r=Hu(qo("line-width",this,e),qo("line-gap-width",this,e)),n=qo("line-offset",this,e);return r/2+Math.abs(n)+Go(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:r,geometry:n,transform:i,pixelsToTileUnits:s}){const a=Xo(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-i.bearingInRadians,s),o=s/2*Hu(this.paint.get("line-width").evaluate(e,r),this.paint.get("line-gap-width").evaluate(e,r)),u=this.paint.get("line-offset").evaluate(e,r);return u&&(n=function(t,e){const r=[];for(let n=0;n=3)for(let e=0;e0?e+2*t:t}const Ku=Ks([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Ju=Ks([{name:"a_projected_pos",components:3,type:"Float32"}],4);Ks([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Wu=Ks([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Ks([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const Qu=Ks([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),tc=Ks([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function ec(t,e,r){return t.sections.forEach((t=>{t.text=function(t,e,r){const n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Ps.applyArabicShaping&&(t=Ps.applyArabicShaping(t)),t}(t.text,e,r);})),t}Ks([{name:"triangle",components:3,type:"Uint16"}]),Ks([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Ks([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Ks([{type:"Float32",name:"offsetX"}]),Ks([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Ks([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const rc={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var nc,ic,sc,ac=24,oc={};function lc(){return nc||(nc=1,oc.read=function(t,e,r,n,i){var s,a,o=8*i-n-1,l=(1<>1,c=-7,h=r?i-1:0,p=r?-1:1,f=t[e+h];for(h+=p,s=f&(1<<-c)-1,f>>=-c,c+=o;c>0;s=256*s+t[e+h],h+=p,c-=8);for(a=s&(1<<-c)-1,s>>=-c,c+=n;c>0;a=256*a+t[e+h],h+=p,c-=8);if(0===s)s=1-u;else {if(s===l)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),s-=u;}return (f?-1:1)*a*Math.pow(2,s-n)},oc.write=function(t,e,r,n,i,s){var a,o,l,u=8*s-i-1,c=(1<>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-1,d=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=c):(a=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-a))<1&&(a--,l*=2),(e+=a+h>=1?p/l:p*Math.pow(2,1-h))*l>=2&&(a++,l/=2),a+h>=c?(o=0,a=c):a+h>=1?(o=(e*l-1)*Math.pow(2,i),a+=h):(o=e*Math.pow(2,h-1)*Math.pow(2,i),a=0));i>=8;t[r+f]=255&o,f+=d,o/=256,i-=8);for(a=a<0;t[r+f]=255&a,f+=d,a/=256,u-=8);t[r+f-d]|=128*y;}),oc}function uc(){if(sc)return ic;sc=1,ic=e;var t=lc();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 r=4294967296,n=1/r,i="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");function s(t){return t.type===e.Bytes?t.readVarint()+t.pos:t.pos+1}function a(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function o(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i];}function l(t,e){for(var r=0;r>>8,t[r+2]=e>>>16,t[r+3]=e>>>24;}function v(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}return e.prototype={destroy:function(){this.buf=null;},readFields:function(t,e,r){for(r=r||this.length;this.pos>3,s=this.pos;this.type=7&n,t(i,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=g(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=v(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=g(this.buf,this.pos)+g(this.buf,this.pos+4)*r;return this.pos+=8,t},readSFixed64:function(){var t=g(this.buf,this.pos)+v(this.buf,this.pos+4)*r;return this.pos+=8,t},readFloat:function(){var e=t.read(this.buf,this.pos,!0,23,4);return this.pos+=4,e},readDouble:function(){var e=t.read(this.buf,this.pos,!0,52,8);return this.pos+=8,e},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,s=r.buf;if(n=(112&(i=s[r.pos++]))>>4,i<128)return a(t,n,e);if(n|=(127&(i=s[r.pos++]))<<3,i<128)return a(t,n,e);if(n|=(127&(i=s[r.pos++]))<<10,i<128)return a(t,n,e);if(n|=(127&(i=s[r.pos++]))<<17,i<128)return a(t,n,e);if(n|=(127&(i=s[r.pos++]))<<24,i<128)return a(t,n,e);if(n|=(1&(i=s[r.pos++]))<<31,i<128)return a(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=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&&i?function(t,e,r){return i.decode(t.subarray(e,r))}(this.buf,e,t):function(t,e,r){for(var n="",i=e;i239?4:l>223?3:l>191?2:1;if(i+c>r)break;1===c?l<128&&(u=l):2===c?128==(192&(s=t[i+1]))&&(u=(31&l)<<6|63&s)<=127&&(u=null):3===c?(a=t[i+2],128==(192&(s=t[i+1]))&&128==(192&a)&&((u=(15&l)<<12|(63&s)<<6|63&a)<=2047||u>=55296&&u<=57343)&&(u=null)):4===c&&(a=t[i+2],o=t[i+3],128==(192&(s=t[i+1]))&&128==(192&a)&&128==(192&o)&&((u=(15&l)<<18|(63&s)<<12|(63&a)<<6|63&o)<=65535||u>=1114112)&&(u=null)),null===u?(u=65533,c=1):u>65535&&(u-=65536,n+=String.fromCharCode(u>>>10&1023|55296),u=56320|1023&u),n+=String.fromCharCode(u),i+=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,r){if(this.type!==e.Bytes)return t.push(this.readVarint(r));var n=s(this);for(t=t||[];this.pos127;);else if(r===e.Bytes)this.pos=this.readVarint()+this.pos;else if(r===e.Fixed32)this.pos+=4;else {if(r!==e.Fixed64)throw new Error("Unimplemented type: "+r);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 r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(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,r){for(var n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&o(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;},writeFloat:function(e){this.realloc(4),t.write(this.buf,e,this.pos,!0,23,4),this.pos+=4;},writeDouble:function(e){this.realloc(8),t.write(this.buf,e,this.pos,!0,52,8),this.pos+=8;},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&o(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;},writeMessage:function(t,r,n){this.writeTag(t,e.Bytes),this.writeRawMessage(r,n);},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,l,e);},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,u,e);},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,p,e);},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,c,e);},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,h,e);},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,f,e);},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,d,e);},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,y,e);},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,m,e);},writeBytesField:function(t,r){this.writeTag(t,e.Bytes),this.writeBytes(r);},writeFixed32Field:function(t,r){this.writeTag(t,e.Fixed32),this.writeFixed32(r);},writeSFixed32Field:function(t,r){this.writeTag(t,e.Fixed32),this.writeSFixed32(r);},writeFixed64Field:function(t,r){this.writeTag(t,e.Fixed64),this.writeFixed64(r);},writeSFixed64Field:function(t,r){this.writeTag(t,e.Fixed64),this.writeSFixed64(r);},writeVarintField:function(t,r){this.writeTag(t,e.Varint),this.writeVarint(r);},writeSVarintField:function(t,r){this.writeTag(t,e.Varint),this.writeSVarint(r);},writeStringField:function(t,r){this.writeTag(t,e.Bytes),this.writeString(r);},writeFloatField:function(t,r){this.writeTag(t,e.Fixed32),this.writeFloat(r);},writeDoubleField:function(t,r){this.writeTag(t,e.Fixed64),this.writeDouble(r);},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e));}},ic}var cc,hc=r(uc());function pc(t,e,r){1===t&&r.readMessage(fc,e);}function fc(t,e,r){if(3===t){const{id:t,bitmap:n,width:i,height:s,left:a,top:o,advance:l}=r.readMessage(dc,{});e.push({id:t,bitmap:new il({width:i+6,height:s+6},n),metrics:{width:i,height:s,left:a,top:o,advance:l}});}}function dc(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint());}function yc(t){let e=0,r=0;for(const n of t)e+=n.w*n.h,r=Math.max(r,n.w);t.sort(((t,e)=>e.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();t=0&&r>=t&&wc[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e);}substring(t,e){const r=new vc;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}getMaxImageSize(t){let e=0,r=0;for(let n=0;n=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function bc(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=vc.fromFeature(e,s);let g;p===t.an.vertical&&m.verticalizePunctuation();const{processBidirectionalText:x,processStyledBidirectionalText:v}=Ps;if(x&&1===m.sections.length){g=[];const t=x(m.toString(),Pc(m,c,a,r,i,d));for(const e of t){const t=new vc;t.text=e,t.sections=m.sections;for(let r=0;r=0;let u=0;for(let r=0;ru){const t=Math.ceil(s/u);i*=t/a,a=t;}return {x1:n,y1:i,x2:n+s,y2:i+a}}function Oc(t,e,r,n,i,s){const a=t.image;let o;if(a.content){const t=a.content,e=a.pixelRatio||1;o=[t[0]/e,t[1]/e,a.displaySize[0]-t[2]/e,a.displaySize[1]-t[3]/e];}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===r||"both"===r?(f=i[0]+l-n[3],h=i[0]+u+n[1]):(f=i[0]+(l+u-a.displaySize[0])/2,h=f+a.displaySize[0]);const d=e.top*s,y=e.bottom*s;return "height"===r||"both"===r?(c=i[1]+d-n[0],p=i[1]+y+n[2]):(c=i[1]+(d+y-a.displaySize[1])/2,p=c+a.displaySize[1]),{image:a,top:c,right:h,bottom:p,left:f,collisionPadding:o}}const Rc=128,jc=32640;function Nc(t,e){const{expression:r}=e;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new Cs(t+1))};if("source"===r.kind)return {kind:"source"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;it.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];const r=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Nc(this.zoom,r["text-size"]),this.iconSizeData=Nc(this.zoom,r["icon-size"]);const n=this.layers[0].layout,i=n.get("symbol-sort-key"),s=n.get("symbol-z-order");this.canOverlap="never"!==Uc(n,"text-overlap","text-allow-overlap")||"never"!==Uc(n,"icon-overlap","icon-allow-overlap")||n.get("text-ignore-placement")||n.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!i.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===n.get("symbol-placement")&&(this.writingModes=n.get("text-writing-mode").map((e=>t.an[e]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID;}createArrays(){this.text=new Hc(new So(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new Hc(new So(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new Ia,this.lineVertexArray=new za,this.symbolInstances=new Ma,this.textAnchorOffsets=new Ca;}calculateGlyphDependencies(t,e,r,n,i){for(let s=0;s0)&&("constant"!==a.value.kind||a.value.value.length>0),c="constant"!==l.value.kind||!!l.value.value||Object.keys(l.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!u&&!c)return;const p=r.iconDependencies,f=r.glyphDependencies,d=r.availableImages,y=new Cs(this.zoom,{globalState:this.globalState});for(const{feature:r,id:o,index:l,sourceLayerIndex:m}of e){const e=i._featureFilter.needGeometry,g=Po(r,e);if(!i._featureFilter.filter(y,g,n))continue;let x,v;if(e||(g.geometry=zo(r)),u){const t=i.getValueAndResolveTokens("text-field",g,n,d),e=Te.factory(t),r=this.hasRTLText=this.hasRTLText||Yc(e);(!r||"unavailable"===Ps.getRTLTextPluginStatus()||r&&Ps.isParsed())&&(x=ec(e,i,g));}if(c){const t=i.getValueAndResolveTokens("icon-image",g,n,d);v=t instanceof Re?t:Re.fromString(t);}if(!x&&!v)continue;const b=this.sortFeaturesByKey?h.evaluate(g,{},n):void 0;if(this.features.push({id:o,text:x,icon:v,index:l,sourceLayerIndex:m,geometry:g.geometry,properties:r.properties,type:qc[r.type],sortKey:b}),v&&(p[v.name]=!0),x){const e=a.evaluate(g,{},n).join(","),r="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(t.an.vertical)>=0;for(const t of x.sections)if(t.image)p[t.image.name]=!0;else {const n=gs(x.toString()),i=t.fontStack||e,s=f[i]=f[i]||{};this.calculateGlyphDependencies(t.text,s,r,this.allowVerticalPlacement,n);}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++;}function a(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function o(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return `${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,r),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,r));}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(void 0!==t.segment){let r=t.dist(e[t.segment+1]),n=t.dist(e[t.segment]);const i={};for(let n=t.segment+1;n=0;r--)i[r]={x:e[r].x,y:e[r].y,tileUnitDistanceFromAnchor:n},r>0&&(n+=e[r-1].dist(e[r]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,r)=>{t>=0&&r.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t);})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}let Wc,Qc;us("SymbolBucket",Jc,{omit:["layers","collisionBoxArray","features","compareText"]}),Jc.MAX_GLYPHS=65535,Jc.addDynamicAttributes=Zc;var th={get paint(){return Qc=Qc||new qs({"icon-opacity":new Rs(wt.paint_symbol["icon-opacity"]),"icon-color":new Rs(wt.paint_symbol["icon-color"]),"icon-halo-color":new Rs(wt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Rs(wt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Rs(wt.paint_symbol["icon-halo-blur"]),"icon-translate":new Os(wt.paint_symbol["icon-translate"]),"icon-translate-anchor":new Os(wt.paint_symbol["icon-translate-anchor"]),"text-opacity":new Rs(wt.paint_symbol["text-opacity"]),"text-color":new Rs(wt.paint_symbol["text-color"],{runtimeType:jt,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new Rs(wt.paint_symbol["text-halo-color"]),"text-halo-width":new Rs(wt.paint_symbol["text-halo-width"]),"text-halo-blur":new Rs(wt.paint_symbol["text-halo-blur"]),"text-translate":new Os(wt.paint_symbol["text-translate"]),"text-translate-anchor":new Os(wt.paint_symbol["text-translate-anchor"])})},get layout(){return Wc=Wc||new qs({"symbol-placement":new Os(wt.layout_symbol["symbol-placement"]),"symbol-spacing":new Os(wt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Os(wt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Rs(wt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Os(wt.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new Os(wt.layout_symbol["icon-allow-overlap"]),"icon-overlap":new Os(wt.layout_symbol["icon-overlap"]),"icon-ignore-placement":new Os(wt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Os(wt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Os(wt.layout_symbol["icon-rotation-alignment"]),"icon-size":new Rs(wt.layout_symbol["icon-size"]),"icon-text-fit":new Os(wt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Os(wt.layout_symbol["icon-text-fit-padding"]),"icon-image":new Rs(wt.layout_symbol["icon-image"]),"icon-rotate":new Rs(wt.layout_symbol["icon-rotate"]),"icon-padding":new Rs(wt.layout_symbol["icon-padding"]),"icon-keep-upright":new Os(wt.layout_symbol["icon-keep-upright"]),"icon-offset":new Rs(wt.layout_symbol["icon-offset"]),"icon-anchor":new Rs(wt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Os(wt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Os(wt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Os(wt.layout_symbol["text-rotation-alignment"]),"text-field":new Rs(wt.layout_symbol["text-field"]),"text-font":new Rs(wt.layout_symbol["text-font"]),"text-size":new Rs(wt.layout_symbol["text-size"]),"text-max-width":new Rs(wt.layout_symbol["text-max-width"]),"text-line-height":new Os(wt.layout_symbol["text-line-height"]),"text-letter-spacing":new Rs(wt.layout_symbol["text-letter-spacing"]),"text-justify":new Rs(wt.layout_symbol["text-justify"]),"text-radial-offset":new Rs(wt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Os(wt.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Rs(wt.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Rs(wt.layout_symbol["text-anchor"]),"text-max-angle":new Os(wt.layout_symbol["text-max-angle"]),"text-writing-mode":new Os(wt.layout_symbol["text-writing-mode"]),"text-rotate":new Rs(wt.layout_symbol["text-rotate"]),"text-padding":new Os(wt.layout_symbol["text-padding"]),"text-keep-upright":new Os(wt.layout_symbol["text-keep-upright"]),"text-transform":new Rs(wt.layout_symbol["text-transform"]),"text-offset":new Rs(wt.layout_symbol["text-offset"]),"text-allow-overlap":new Os(wt.layout_symbol["text-allow-overlap"]),"text-overlap":new Os(wt.layout_symbol["text-overlap"]),"text-ignore-placement":new Os(wt.layout_symbol["text-ignore-placement"]),"text-optional":new Os(wt.layout_symbol["text-optional"])})}};class eh{constructor(t){if(void 0===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:$t,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return !1}serialize(){return null}}us("FormatSectionOverride",eh,{omit:["defaultValue"]});class rh extends Xs{constructor(t){super(t,th);}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const r of t)e.indexOf(r)<0&&e.push(r);this.layout._values["text-writing-mode"]=e;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||ii(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>t&&r in t?String(t[r]):""))}(e.properties,i)}createBucket(t){return new Jc(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of th.paint.overridableProperties){if(!rh.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new eh(e),n=new ni(r,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new ai("source",n):new oi("composite",n,e.value.zoomStops),this.paint._values[t]=new $s(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,r){return !(!this.layout||e.isDataDriven()||r.isDataDriven())&&rh.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get("text-field"),n=th.paint.properties[e];let i=!1;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=!0)};if("constant"===r.value.kind&&r.value.value instanceof Te)s(r.value.value.sections);else if("source"===r.value.kind){const t=e=>{i||(e instanceof Xe&&qe(e.value)===Xt?s(e.value.sections):e instanceof Cr?s(e.sections):e.eachChild(t));},e=r.value;e._styleExpression&&t(e._styleExpression.expression);}return i}}let nh;var ih={get paint(){return nh=nh||new qs({"background-color":new Os(wt.paint_background["background-color"]),"background-pattern":new Ns(wt.paint_background["background-pattern"]),"background-opacity":new Os(wt.paint_background["background-opacity"])})}};class sh extends Xs{constructor(t){super(t,ih);}}let ah;var oh={get paint(){return ah=ah||new qs({"raster-opacity":new Os(wt.paint_raster["raster-opacity"]),"raster-hue-rotate":new Os(wt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Os(wt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Os(wt.paint_raster["raster-brightness-max"]),"raster-saturation":new Os(wt.paint_raster["raster-saturation"]),"raster-contrast":new Os(wt.paint_raster["raster-contrast"]),"raster-resampling":new Os(wt.paint_raster["raster-resampling"]),"raster-fade-duration":new Os(wt.paint_raster["raster-fade-duration"])})}};class lh extends Xs{constructor(t){super(t,oh);}}class uh extends Xs{constructor(t){super(t,{}),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},this.implementation=t;}is3D(){return "3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return !1}serialize(){throw new Error("Custom layers cannot be serialized")}}class ch{constructor(t){this._methodToThrottle=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle();});}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle();}),0));}remove(){delete this._channel,this._methodToThrottle=()=>{};}}const hh={once:!0},ph=6371008.8;class fh{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new fh(R(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return ph*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof fh)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new fh(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new fh(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const dh=2*Math.PI*ph;function yh(t){return dh*Math.cos(t*Math.PI/180)}function mh(t){return (180+t)/360}function gh(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function xh(t,e){return t/yh(e)}function vh(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}function bh(t,e){return t*yh(vh(e))}class wh{constructor(t,e,r=0){this.x=+t,this.y=+e,this.z=+r;}static fromLngLat(t,e=0){const r=fh.convert(t);return new wh(mh(r.lng),gh(r.lat),xh(e,r.lat))}toLngLat(){return new fh(360*this.x-180,vh(this.y))}toAltitude(){return bh(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/dh*(t=vh(this.y),1/Math.cos(t*Math.PI/180));var t;}}function _h(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}class Sh{constructor(t,e,r){if(!function(t,e,r){return !(t<0||t>25||r<0||r>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,r))throw new Error(`x=${e}, y=${r}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=r,this.key=Mh(0,t,t,e,r);}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,r){const n=(s=this.y,a=this.z,o=_h(256*(i=this.x),256*(s=Math.pow(2,a)-s-1),a),l=_h(256*(i+1),256*(s+1),a),o[0]+","+o[1]+","+l[0]+","+l[1]);var i,s,a,o,l;const u=function(t,e,r){let n,i="";for(let s=t;s>0;s--)n=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,n)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new l((t.x*e-this.x)*E,(t.y*e-this.y)*E)}toString(){return `${this.z}/${this.x}/${this.y}`}}class Ah{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Mh(t,e.z,e.z,e.x,e.y);}}class kh{constructor(t,e,r,n,i){if(this.terrainRttPosMatrix32f=null,t= z; overscaledZ = ${t}; z = ${r}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Sh(r,+n,+i),this.key=Mh(e,t,r,n,i);}clone(){return new kh(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new kh(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new kh(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const r=this.canonical.z-t;return t>this.canonical.z?Mh(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Mh(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}isChildOf(t){if(t.wrap!==this.wrap)return !1;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new kh(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new kh(e,this.wrap,e,r,n),new kh(e,this.wrap,e,r+1,n),new kh(e,this.wrap,e,r,n+1),new kh(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.ythis.maxX||this.minY>this.maxY)&&(this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0),this}shrinkBy(t){return this.expandBy(-t)}map(t){const e=new Ih;return e.extend(t(new l(this.minX,this.minY))),e.extend(t(new l(this.maxX,this.minY))),e.extend(t(new l(this.minX,this.maxY))),e.extend(t(new l(this.maxX,this.maxY))),e}static fromPoints(t){const e=new Ih;for(const r of t)e.extend(r);return e}contains(t){return t.x>=this.minX&&t.x<=this.maxX&&t.y>=this.minY&&t.y<=this.maxY}empty(){return this.minX>this.maxX}width(){return this.maxX-this.minX}height(){return this.maxY-this.minY}covers(t){return !this.empty()&&!t.empty()&&t.minX>=this.minX&&t.maxX<=this.maxX&&t.minY>=this.minY&&t.maxY<=this.maxY}intersects(t){return !this.empty()&&!t.empty()&&t.minX<=this.maxX&&t.maxX>=this.minX&&t.minY<=this.maxY&&t.maxY>=this.minY}}class zh{constructor(t){this._stringToNumber={},this._numberToString=[];for(let e=0;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class Ph{constructor(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}class Ch{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new os(E,16,0),this.grid3D=new os(E,16,0),this.featureIndexArray=new Ea,this.promoteId=e;}insert(t,e,r,n,i,s){const a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);const o=s?this.grid3D:this.grid;for(let t=0;t=0&&n[3]>=0&&o.insert(a,n[0],n[1],n[2],n[3]);}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new _u.VectorTile(new hc(this.rawTileData)).layers,this.sourceLayerCoder=new zh(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,r,n){this.loadVTLayers();const i=t.params,s=E/t.tileSize/t.scale,a=di(i.filter),o=t.queryGeometry,u=t.queryPadding*s,c=Ih.fromPoints(o),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=Ih.fromPoints(t.cameraQueryGeometry).expandBy(u),f=this.grid3D.query(p.minX,p.minY,p.maxX,p.maxY,((e,r,n,i)=>function(t,e,r,n,i){for(const s of t)if(e<=s.x&&r<=s.y&&n>=s.x&&i>=s.y)return !0;const s=[new l(e,r),new l(e,i),new l(n,i),new l(n,r)];if(t.length>2)for(const e of s)if(No(t,e))return !0;for(let e=0;e(p||(p=zo(e)),r.queryIntersectsFeature({queryGeometry:o,feature:e,featureState:n,geometry:p,zoom:this.z,transform:t.transform,pixelsToTileUnits:s,pixelPosMatrix:t.pixelPosMatrix,unwrappedTileID:this.tileID.toUnwrapped(),getElevation:t.getElevation}))));}return d}loadMatchingFeature(t,e,r,n,i,s,a,o,l,u,c){const h=this.bucketLayerIDs[e];if(s&&!h.some((t=>s.has(t))))return;const p=this.sourceLayerCoder.decode(r),f=this.vtLayers[p].feature(n);if(i.needGeometry){const t=Po(f,!0);if(!i.filter(new Cs(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new Cs(this.tileID.overscaledZ),f))return;const d=this.getId(f,p);for(let e=0;e{const a=e instanceof Ds?e.get(s):null;return a&&a.evaluate?a.evaluate(r,n,i):a}))}function Eh(t,e){return e-t}function Th(t,e,r,n,i){const s=[];for(let a=0;a=n&&c.x>=n||(a.x>=n?a=new l(n,a.y+(n-a.x)/(c.x-a.x)*(c.y-a.y))._round():c.x>=n&&(c=new l(n,a.y+(n-a.x)/(c.x-a.x)*(c.y-a.y))._round()),a.y>=i&&c.y>=i||(a.y>=i?a=new l(a.x+(i-a.y)/(c.y-a.y)*(c.x-a.x),i)._round():c.y>=i&&(c=new l(a.x+(i-a.y)/(c.y-a.y)*(c.x-a.x),i)._round()),u&&a.equals(u[u.length-1])||(u=[a],s.push(u)),u.push(c)))));}}return s}us("FeatureIndex",Ch,{omit:["rawTileData","sourceLayerCoder"]});class Vh extends l{constructor(t,e,r,n){super(t,e),this.angle=r,void 0!==n&&(this.segment=n);}clone(){return new Vh(this.x,this.y,this.angle,this.segment)}}function Fh(t,e,r,n,i){if(void 0===e.segment||0===r)return !0;let s=e,a=e.segment+1,o=0;for(;o>-r/2;){if(a--,a<0)return !1;o-=t[a].dist(s),s=t[a];}o+=t[a].dist(t[a+1]),a++;const l=[];let u=0;for(;on;)u-=l.shift().angleDelta;if(u>i)return !1;a++,o+=e.dist(r);}return !0}function Lh(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=gr.number(n.x,i.x,c),p=gr.number(n.y,i.y,c),f=new Vh(h,p,i.angleTo(n),r);return f._round(),!a||Fh(t,f,o,a,e)?f:void 0}l+=s;}}function Rh(t,e,r,n,i,s,a,o,l){const u=$h(n,s,a),c=Dh(n,i),h=c*a,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new Vh(g,x,y,e);r._round(),n&&!Fh(t,r,s,n,i)||f.push(r);}}h+=d;}return o||f.length||a||(f=jh(t,h/2,r,n,i,s,a,!0,l)),f}function Nh(t,e,r,n){const i=[],s=t.image,a=s.pixelRatio,o=s.paddedRect.w-2,u=s.paddedRect.h-2;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=s.stretchX||[[0,o]],p=s.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=o-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,S=m,A=0,k=g;if(s.content&&n){const e=s.content,r=e[2]-e[0],n=e[3]-e[1];(s.textFitWidth||s.textFitHeight)&&(c=Dc(t)),x=Uh(h,0,e[0]),b=Uh(p,0,e[1]),v=Uh(h,e[0],e[2]),w=Uh(p,e[1],e[3]),_=e[0]-x,A=e[1]-b,S=r-v,k=n-w;}const M=c.x1,I=c.y1,z=c.x2-M,P=c.y2-I,C=(t,n,i,o)=>{const u=Gh(t.stretch-x,v,z,M),c=Xh(t.fixed-_,S,t.stretch,d),h=Gh(n.stretch-b,w,P,I),p=Xh(n.fixed-A,k,n.stretch,y),f=Gh(i.stretch-x,v,z,M),m=Xh(i.fixed-_,S,i.stretch,d),g=Gh(o.stretch-b,w,P,I),C=Xh(o.fixed-A,k,o.stretch,y),B=new l(u,h),E=new l(f,h),T=new l(f,g),V=new l(u,g),F=new l(c/a,p/a),L=new l(m/a,C/a),$=e*Math.PI/180;if($){const t=Math.sin($),e=Math.cos($),r=[e,-t,t,e];B._matMult(r),E._matMult(r),V._matMult(r),T._matMult(r);}const D=t.stretch+t.fixed,O=n.stretch+n.fixed;return {tl:B,tr:E,bl:V,br:T,tex:{x:s.paddedRect.x+1+D,y:s.paddedRect.y+1+O,w:i.stretch+i.fixed-D,h:o.stretch+o.fixed-O},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:F,pixelOffsetBR:L,minFontScaleX:S/a/z,minFontScaleY:k/a/P,isSDF:r}};if(n&&(s.stretchX||s.stretchY)){const t=qh(h,m,d),e=qh(p,g,y);for(let r=0;r0&&(n=Math.max(10,n),this.circleDiameter=n);}else {const u=(null===(h=s.image)||void 0===h?void 0:h.content)&&(s.image.textFitWidth||s.image.textFitHeight)?Dc(s):{x1:s.left,y1:s.top,x2:s.right,y2:s.bottom};u.y1=u.y1*a-o[0],u.y2=u.y2*a+o[2],u.x1=u.x1*a-o[3],u.x2=u.x2*a+o[1];const p=s.collisionPadding;if(p&&(u.x1-=p[0]*a,u.y1-=p[1]*a,u.x2+=p[2]*a,u.y2+=p[3]*a),c){const t=new l(u.x1,u.y1),e=new l(u.x2,u.y1),r=new l(u.x1,u.y2),n=new l(u.x2,u.y2),i=c*Math.PI/180;t._rotate(i),e._rotate(i),r._rotate(i),n._rotate(i),u.x1=Math.min(t.x,e.x,r.x,n.x),u.x2=Math.max(t.x,e.x,r.x,n.x),u.y1=Math.min(t.y,e.y,r.y,n.y),u.y2=Math.max(t.y,e.y,r.y,n.y);}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,r,n,i);}this.boxEndIndex=t.length;}}class Yh{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}}function Hh(t,e=1,r=!1){const n=Ih.fromPoints(t[0]),i=Math.min(n.width(),n.height());let s=i/2;const a=new Yh([],Kh),{minX:o,minY:u,maxX:c,maxY:h}=n;if(0===i)return new l(o,u);for(let e=o;ep.d||!p.d)&&(p=n,r&&console.log("found best %d after %d probes",Math.round(1e4*n.d)/1e4,f)),n.max-p.d<=e||(s=n.h/2,a.push(new Jh(n.p.x-s,n.p.y-s,s,t)),a.push(new Jh(n.p.x+s,n.p.y-s,s,t)),a.push(new Jh(n.p.x-s,n.p.y+s,s,t)),a.push(new Jh(n.p.x+s,n.p.y+s,s,t)),f+=4);}return r&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function Kh(t,e){return e.max-t.max}function Jh(t,e,r,n){this.p=new l(t,e),this.h=r,this.d=function(t,e){let r=!1,n=1/0;for(let i=0;it.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(r=!r),n=Math.min(n,Ro(t,i,o));}}return (r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2;}var Wh;t.aD=void 0,(Wh=t.aD||(t.aD={}))[Wh.center=1]="center",Wh[Wh.left=2]="left",Wh[Wh.right=3]="right",Wh[Wh.top=4]="top",Wh[Wh.bottom=5]="bottom",Wh[Wh["top-left"]=6]="top-left",Wh[Wh["top-right"]=7]="top-right",Wh[Wh["bottom-left"]=8]="bottom-left",Wh[Wh["bottom-right"]=9]="bottom-right";const Qh=Number.POSITIVE_INFINITY;function tp(t,e){return e[1]!==Qh?function(t,e,r){let n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case "top-right":case "top-left":case "top":i=r-7;break;case "bottom-right":case "bottom-left":case "bottom":i=7-r;}switch(t){case "top-right":case "bottom-right":case "right":n=-e;break;case "top-left":case "bottom-left":case "left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){let r=0,n=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case "top-right":case "top-left":n=i-7;break;case "bottom-right":case "bottom-left":n=7-i;break;case "bottom":n=7-e;break;case "top":n=e-7;}switch(t){case "top-right":case "bottom-right":r=-i;break;case "top-left":case "bottom-left":r=i;break;case "left":r=e;break;case "right":r=-e;}return [r,n]}(t,e[0])}function ep(t,e,r){var n;const i=t.layout,s=null===(n=i.get("text-variable-anchor-offset"))||void 0===n?void 0:n.evaluate(e,{},r);if(s){const t=s.values,e=[];for(let r=0;rt*ac));n.startsWith("top")?i[1]-=7:n.startsWith("bottom")&&(i[1]+=7),e[r+1]=i;}return new Oe(e)}const a=i.get("text-variable-anchor");if(a){let n;n=void 0!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},r)*ac,Qh]:i.get("text-offset").evaluate(e,{},r).map((t=>t*ac));const s=[];for(const t of a)s.push(t,tp(t,n));return new Oe(s)}return null}function rp(t){switch(t){case "right":case "top-right":case "bottom-right":return "right";case "left":case "top-left":case "bottom-left":return "left"}return "center"}function np(e,r,n,i,s,a,o,l,u,c,h,p){let f=a.textMaxSize.evaluate(r,{});void 0===f&&(f=o);const d=e.layers[0].layout,y=d.get("icon-offset").evaluate(r,{},h),m=sp(n.horizontal),g=o/24,x=e.tilePixelRatio*g,v=e.tilePixelRatio*f/24,b=e.tilePixelRatio*l,w=e.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*e.tilePixelRatio,S=function(t,e,r,n=1){const i=t.get("icon-padding").evaluate(e,{},r),s=i&&i.values;return [s[0]*n,s[1]*n,s[2]*n,s[3]*n]}(d,r,h,e.tilePixelRatio),A=d.get("text-max-angle")/180*Math.PI,k="viewport"!==d.get("text-rotation-alignment")&&"point"!==d.get("symbol-placement"),M="map"===d.get("icon-rotation-alignment")&&"point"!==d.get("symbol-placement"),I=d.get("symbol-placement"),z=w/2,P=d.get("icon-text-fit");let C;i&&"none"!==P&&(e.allowVerticalPlacement&&n.vertical&&(C=Oc(i,n.vertical,P,d.get("icon-text-fit-padding"),y,g)),m&&(i=Oc(i,m,P,d.get("icon-text-fit-padding"),y,g)));const B=h?p.line.getGranularityForZoomLevel(h.z):1,T=(l,p)=>{p.x<0||p.x>=E||p.y<0||p.y>=E||function(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k){const M=e.addToLineVertexArray(r,n);let I,z,P,C,B=0,E=0,T=0,V=0,F=-1,L=-1;const $={};let D=so("");if(e.allowVerticalPlacement&&i.vertical){const t=l.layout.get("text-rotate").evaluate(w,{},A)+90;P=new Zh(u,r,c,h,p,i.vertical,f,d,y,t),o&&(C=new Zh(u,r,c,h,p,o,g,x,y,t));}if(s){const n=l.layout.get("icon-rotate").evaluate(w,{}),i="none"!==l.layout.get("icon-text-fit"),a=Nh(s,n,S,i),f=o?Nh(o,n,S,i):void 0;z=new Zh(u,r,c,h,p,s,g,x,!1,n),B=4*a.length;const d=e.iconSizeData;let y=null;"source"===d.kind?(y=[Rc*l.layout.get("icon-size").evaluate(w,{})],y[0]>jc&&Z(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)):"composite"===d.kind&&(y=[Rc*_.compositeIconSizes[0].evaluate(w,{},A),Rc*_.compositeIconSizes[1].evaluate(w,{},A)],(y[0]>jc||y[1]>jc)&&Z(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)),e.addSymbols(e.icon,a,y,b,v,w,t.an.none,r,M.lineStartIndex,M.lineLength,-1,A),F=e.icon.placedSymbolArray.length-1,f&&(E=4*f.length,e.addSymbols(e.icon,f,y,b,v,w,t.an.vertical,r,M.lineStartIndex,M.lineLength,-1,A),L=e.icon.placedSymbolArray.length-1);}const O=Object.keys(i.horizontal);for(const n of O){const s=i.horizontal[n];if(!I){D=so(s.text);const t=l.layout.get("text-rotate").evaluate(w,{},A);I=new Zh(u,r,c,h,p,s,f,d,y,t);}const o=1===s.positionedLines.length;if(T+=ip(e,r,s,a,l,y,w,m,M,i.vertical?t.an.horizontal:t.an.horizontalOnly,o?O:[n],$,F,_,A),o)break}i.vertical&&(V+=ip(e,r,i.vertical,a,l,y,w,m,M,t.an.vertical,["vertical"],$,L,_,A));const R=I?I.boxStartIndex:e.collisionBoxArray.length,j=I?I.boxEndIndex:e.collisionBoxArray.length,N=P?P.boxStartIndex:e.collisionBoxArray.length,U=P?P.boxEndIndex:e.collisionBoxArray.length,q=z?z.boxStartIndex:e.collisionBoxArray.length,G=z?z.boxEndIndex:e.collisionBoxArray.length,X=C?C.boxStartIndex:e.collisionBoxArray.length,Y=C?C.boxEndIndex:e.collisionBoxArray.length;let H=-1;const K=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=K(I,H),H=K(P,H),H=K(z,H),H=K(C,H);const J=H>-1?1:0;J&&(H*=k/ac),e.glyphOffsetArray.length>=Jc.MAX_GLYPHS&&Z("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==w.sortKey&&e.addToSortKeyRanges(e.symbolInstances.length,w.sortKey);const W=ep(l,w,A),[Q,tt]=function(e,r){const n=e.length,i=null==r?void 0:r.values;if((null==i?void 0:i.length)>0)for(let r=0;r=0?$.right:-1,$.center>=0?$.center:-1,$.left>=0?$.left:-1,$.vertical||-1,F,L,D,R,j,N,U,q,G,X,Y,c,T,V,B,E,J,0,f,H,Q,tt);}(e,p,l,n,i,s,C,e.layers[0],e.collisionBoxArray,r.index,r.sourceLayerIndex,e.index,x,[_,_,_,_],k,u,b,S,M,y,r,a,c,h,o);};if("line"===I)for(const t of Th(r.geometry,0,0,E,E)){const r=Ql(t,B),s=Rh(r,w,A,n.vertical||m,i,24,v,e.overscaling,E);for(const t of s)m&&ap(e,m.text,z,t)||T(r,t);}else if("line-center"===I){for(const t of r.geometry)if(t.length>1){const e=Ql(t,B),r=Oh(e,A,n.vertical||m,i,24,v);r&&T(e,r);}}else if("Polygon"===r.type)for(const t of rn(r.geometry,0)){const e=Hh(t,16);T(Ql(t[0],B,!0),new Vh(e.x,e.y,0));}else if("LineString"===r.type)for(const t of r.geometry){const e=Ql(t,B);T(e,new Vh(e[0].x,e[0].y,0));}else if("Point"===r.type)for(const t of r.geometry)for(const e of t)T([e],new Vh(e.x,e.y,0));}function ip(t,e,r,n,i,s,a,o,u,c,h,p,f,d,y){const m=function(t,e,r,n,i,s,a,o){const u=n.layout.get("text-rotate").evaluate(s,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const n of t.positionedGlyphs){if(!n.rect)continue;const s=n.rect||{};let h=4,p=!0,f=1,d=0;const y=(i||o)&&n.vertical,m=n.metrics.advance*n.scale/2;if(o&&e.verticalizable&&(d=t.lineOffset/2-(n.imageName?-(ac-n.metrics.width*n.scale)/2:(n.scale-1)*ac)),n.imageName){const t=a[n.imageName];p=t.sdf,f=t.pixelRatio,h=1/f;}const g=i?[n.x+m,n.y]:[0,0];let x=i?[0,0]:[n.x+m+r[0],n.y+r[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=n.metrics.isDoubleResolution?2:1,w=(n.metrics.left-h)*n.scale-m+x[0],_=(-n.metrics.top-h)*n.scale+x[1],S=w+s.w/b*n.scale/f,A=_+s.h/b*n.scale/f,k=new l(w,_),M=new l(S,_),I=new l(w,A),z=new l(S,A);if(y){const t=new l(-m,m- -17),e=-Math.PI/2,r=12-m,i=new l(22-r,-(n.imageName?r:0)),s=new l(...v);k._rotateAround(e,t)._add(i)._add(s),M._rotateAround(e,t)._add(i)._add(s),I._rotateAround(e,t)._add(i)._add(s),z._rotateAround(e,t)._add(i)._add(s);}if(u){const t=Math.sin(u),e=Math.cos(u),r=[e,-t,t,e];k._matMult(r),M._matMult(r),I._matMult(r),z._matMult(r);}const P=new l(0,0),C=new l(0,0);c.push({tl:k,tr:M,bl:I,br:z,tex:s,writingMode:e.writingMode,glyphOffset:g,sectionIndex:n.sectionIndex,isSDF:p,pixelOffsetTL:P,pixelOffsetBR:C,minFontScaleX:0,minFontScaleY:0});}return c}(0,r,o,i,s,a,n,t.allowVerticalPlacement),g=t.textSizeData;let x=null;"source"===g.kind?(x=[Rc*i.layout.get("text-size").evaluate(a,{})],x[0]>jc&&Z(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)):"composite"===g.kind&&(x=[Rc*d.compositeTextSizes[0].evaluate(a,{},y),Rc*d.compositeTextSizes[1].evaluate(a,{},y)],(x[0]>jc||x[1]>jc)&&Z(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)),t.addSymbols(t.text,m,x,o,s,a,c,e,u.lineStartIndex,u.lineLength,f,y);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*m.length}function sp(t){for(const e in t)return t[e];return null}function ap(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=op[15&r];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new lp(a,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=op.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+s+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return up(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,r,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:a}=this,o=[0,i.length-1,0],l=[];for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=a){for(let a=h;a<=c;a++){const o=s[2*a],u=s[2*a+1];o>=t&&o<=r&&u>=e&&u<=n&&l.push(i[a]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?r>=f:n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return l}within(t,e,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:n,coords:i,nodeSize:s}=this,a=[0,n.length-1,0],o=[],l=r*r;for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)fp(i[2*r],i[2*r+1],t,e)<=l&&o.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];fp(f,d,t,e)<=l&&o.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return o}}function up(t,e,r,n,i,s){if(i-n<=r)return;const a=n+i>>1;cp(t,e,a,n,i,s),up(t,e,r,n,a-1,1-s),up(t,e,r,a+1,i,1-s);}function cp(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const a=i-n+1,o=r-n+1,l=Math.log(a),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(a-u)/a)*(o-a/2<0?-1:1);cp(t,e,r,Math.max(n,Math.floor(r-o*u/a+c)),Math.min(i,Math.floor(r+(a-o)*u/a+c)),s);}const a=e[2*r+s];let o=n,l=i;for(hp(t,e,n,r),e[2*i+s]>a&&hp(t,e,n,i);oa;)l--;}e[2*n+s]===a?hp(t,e,n,l):(l++,hp(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1);}}function hp(t,e,r,n){pp(t,r,n),pp(e,2*r,2*n),pp(e,2*r+1,2*n+1);}function pp(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function fp(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}var dp;t.cw=void 0,(dp=t.cw||(t.cw={})).create="create",dp.load="load",dp.fullLoad="fullLoad";let yp=null,mp=[];const gp=1e3/60,xp="loadTime",vp="fullLoadTime",bp={mark(t){performance.mark(t);},frame(t){const e=t;null!=yp&&mp.push(e-yp),yp=e;},clearMetrics(){yp=null,mp=[],performance.clearMeasures(xp),performance.clearMeasures(vp);for(const e in t.cw)performance.clearMarks(t.cw[e]);},getPerformanceMetrics(){performance.measure(xp,t.cw.create,t.cw.load),performance.measure(vp,t.cw.create,t.cw.fullLoad);const e=performance.getEntriesByName(xp)[0].duration,r=performance.getEntriesByName(vp)[0].duration,n=mp.length,i=1/(mp.reduce(((t,e)=>t+e),0)/n/1e3),s=mp.filter((t=>t>gp)).reduce(((t,e)=>t+(e-gp)/gp),0);return {loadTime:e,fullLoadTime:r,fps:i,percentDroppedFrames:s/(n+s)*100,totalFrames:n}}};t.$=E,t.A=m,t.B=function([t,e,r]){return e+=90,e*=Math.PI/180,r*=Math.PI/180,{x:t*Math.cos(e)*Math.sin(r),y:t*Math.sin(e)*Math.sin(r),z:t*Math.cos(r)}},t.C=gr,t.D=Os,t.E=bt,t.F=Cs,t.G=ns,t.H=function(t){if(null==K){const e=t.navigator?t.navigator.userAgent:null;K=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return K},t.I=mc,t.J=class{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new ch((()=>this.process())),this.subscription=rt(this.target,"message",(t=>this.receive(t)),!1),this.globalScope=H(self)?t:window;}registerMessageHandler(t,e){this.messageHandlers[t]=e;}sendAsync(t,e){return new Promise(((r,n)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10),s=e?rt(e.signal,"abort",(()=>{null==s||s.unsubscribe(),delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e);}),hh):null;this.resolveRejects[i]={resolve:t=>{null==s||s.unsubscribe(),r(t);},reject:t=>{null==s||s.unsubscribe(),n(t);}};const a=[],o=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:fs(t.data,a)});this.target.postMessage(o,{transfer:a});}))}receive(t){const e=t.data,r=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[r];const t=this.abortControllers[r];return delete this.abortControllers[r],void(t&&t.abort())}if(H(self)||e.mustQueue)return this.tasks[r]=e,this.taskQueue.push(r),void this.invoker.trigger();this.processTask(r,e);}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e);}processTask(t,r){return e(this,void 0,void 0,(function*(){if(""===r.type){const e=this.resolveRejects[t];if(delete this.resolveRejects[t],!e)return;return void(r.error?e.reject(ds(r.error)):e.resolve(ds(r.data)))}if(!this.messageHandlers[r.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${r.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const e=ds(r.data),n=new AbortController;this.abortControllers[t]=n;try{const i=yield this.messageHandlers[r.type](r.sourceMapId,e,n);this.completeTask(t,null,i);}catch(e){this.completeTask(t,e);}}))}completeTask(t,e,r){const n=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?fs(e):null,data:fs(r,n)};this.target.postMessage(i,{transfer:n});}remove(){this.invoker.remove(),this.subscription.unsubscribe();}},t.K=ht,t.L=function(){var t=new m(16);return m!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.M=function(t,e,r){var n,i,s,a,o,l,u,c,h,p,f,d,y=r[0],m=r[1],g=r[2];return e===t?(t[12]=e[0]*y+e[4]*m+e[8]*g+e[12],t[13]=e[1]*y+e[5]*m+e[9]*g+e[13],t[14]=e[2]*y+e[6]*m+e[10]*g+e[14],t[15]=e[3]*y+e[7]*m+e[11]*g+e[15]):(i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=n=e[0],t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=n*y+o*m+h*g+e[12],t[13]=i*y+l*m+p*g+e[13],t[14]=s*y+u*m+f*g+e[14],t[15]=a*y+c*m+d*g+e[15]),t},t.N=function(t,e,r){var n=r[0],i=r[1],s=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.O=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],y=e[12],m=e[13],g=e[14],x=e[15],v=r[0],b=r[1],w=r[2],_=r[3];return t[0]=v*n+b*o+w*h+_*y,t[1]=v*i+b*l+w*p+_*m,t[2]=v*s+b*u+w*f+_*g,t[3]=v*a+b*c+w*d+_*x,t[4]=(v=r[4])*n+(b=r[5])*o+(w=r[6])*h+(_=r[7])*y,t[5]=v*i+b*l+w*p+_*m,t[6]=v*s+b*u+w*f+_*g,t[7]=v*a+b*c+w*d+_*x,t[8]=(v=r[8])*n+(b=r[9])*o+(w=r[10])*h+(_=r[11])*y,t[9]=v*i+b*l+w*p+_*m,t[10]=v*s+b*u+w*f+_*g,t[11]=v*a+b*c+w*d+_*x,t[12]=(v=r[12])*n+(b=r[13])*o+(w=r[14])*h+(_=r[15])*y,t[13]=v*i+b*l+w*p+_*m,t[14]=v*s+b*u+w*f+_*g,t[15]=v*a+b*c+w*d+_*x,t},t.P=l,t.Q=function(t,e){const r={};for(let n=0;n{const e=window.document.createElement("video");return e.muted=!0,new Promise((r=>{e.onloadstart=()=>{r(e);};for(const r of t){const t=window.document.createElement("source");yt(r)||(e.crossOrigin="Anonymous"),t.src=r,e.appendChild(t);}}))},t.a5=Tt,t.a6=function(){return N++},t.a7=_a,t.a8=Jc,t.a9=di,t.aA=ac,t.aB=T,t.aC=function(t,e,r,n,i=!1){if(!r[0]&&!r[1])return [0,0];const s=i?"map"===n?-t.bearingInRadians:0:"viewport"===n?t.bearingInRadians:0;if(s){const t=Math.sin(s),e=Math.cos(s);r=[r[0]*e-r[1]*t,r[0]*t+r[1]*e];}return [i?r[0]:T(e,r[0],t.zoom),i?r[1]:T(e,r[1],t.zoom)]},t.aE=Uc,t.aF=rp,t.aG=Cc,t.aH=lp,t.aI=Ks,t.aJ=Yl,t.aK=Ta,t.aL=Ha,t.aM=Ga,t.aN=R,t.aO=it,t.aP=bh,t.aQ=S,t.aR=_,t.aS=function(t){var e=new m(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.aT=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t},t.aU=function(t,e){var r=e[0],n=e[1],i=e[2],s=r*r+n*n+i*i;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t},t.aV=A,t.aW=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.aX=function(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t},t.aY=b,t.aZ=function(t,e,r){const n=e[0]*r[0]+e[1]*r[1]+e[2]*r[2];return 0===n?null:(-(t[0]*r[0]+t[1]*r[1]+t[2]*r[2])-r[3])/n},t.a_=M,t.aa=Po,t.ab=Ph,t.ac=function(t){const e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,r,n,i)=>{const s=n||i;return e[r]=!s||s.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t;}return e},t.ad=nt,t.ae=function(t){return Math.pow(2,t)},t.af=x,t.ag=O,t.ah=85.051129,t.ai=xh,t.aj=function(t){return Math.log(t)/Math.LN2},t.ak=function(t){var e=t[0],r=t[1];return e*e+r*r},t.al=function(t,e){const r=[];for(const n in t)n in e||r.push(n);return r},t.am=function(t,e){let r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){const{interpolationType:i,minZoom:s,maxZoom:a}=t,o=i?O(yr.interpolationFactor(i,e,s,a),0,1):0;"camera"===t.kind?n=gr.number(t.minSize,t.maxSize,o):r=o;}return {uSizeT:r,uSize:n}},t.ao=function(t,{uSize:e,uSizeT:r},{lowerSize:n,upperSize:i}){return "source"===t.kind?n/Rc:"composite"===t.kind?gr.number(n/Rc,i/Rc,r):e},t.ap=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],y=e[13],m=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,w=n*l-i*o,_=n*u-s*o,S=i*u-s*l,A=c*y-h*d,k=c*m-p*d,M=c*g-f*d,I=h*m-p*y,z=h*g-f*y,P=p*g-f*m,C=x*P-v*z+b*I+w*M-_*k+S*A;return C?(t[0]=(o*P-l*z+u*I)*(C=1/C),t[1]=(i*z-n*P-s*I)*C,t[2]=(y*S-m*_+g*w)*C,t[3]=(p*_-h*S-f*w)*C,t[4]=(l*M-a*P-u*k)*C,t[5]=(r*P-i*M+s*k)*C,t[6]=(m*b-d*S-g*v)*C,t[7]=(c*S-p*b+f*v)*C,t[8]=(a*z-o*M+u*A)*C,t[9]=(n*M-r*z-s*A)*C,t[10]=(d*_-y*b+g*x)*C,t[11]=(h*b-c*_-f*x)*C,t[12]=(o*k-a*I-l*A)*C,t[13]=(r*I-n*k+i*A)*C,t[14]=(y*v-d*w-m*x)*C,t[15]=(c*w-h*v+p*x)*C,t):null},t.aq=C,t.ar=function(t){return Math.hypot(t[0],t[1])},t.as=function(t){return t[0]=0,t[1]=0,t},t.at=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t},t.au=Zc,t.av=I,t.aw=function(t,e,r,n){const i=e.y-t.y,s=e.x-t.x,a=n.y-r.y,o=n.x-r.x,u=a*s-o*i;if(0===u)return null;const c=(o*(t.y-r.y)-a*(t.x-r.x))/u;return new l(t.x+c*s,t.y+c*i)},t.ax=Th,t.ay=To,t.az=function(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return [e,r,n,i]},t.b=J,t.b$=tc,t.b0=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]},t.b1=Ah,t.b2=Mh,t.b3=function(t,e,r,n,i){var s,a=1/Math.tan(e/2);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0?(t[10]=(i+n)*(s=1/(n-i)),t[14]=2*i*n*s):(t[10]=-1,t[14]=-2*n),t},t.b4=function(t){var e=new m(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.b5=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[4],c=e[5],h=e[6],p=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i+u*n,t[1]=a*i+c*n,t[2]=o*i+h*n,t[3]=l*i+p*n,t[4]=u*i-s*n,t[5]=c*i-a*n,t[6]=h*i-o*n,t[7]=p*i-l*n,t},t.b6=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=s*i+u*n,t[5]=a*i+c*n,t[6]=o*i+h*n,t[7]=l*i+p*n,t[8]=u*i-s*n,t[9]=c*i-a*n,t[10]=h*i-o*n,t[11]=p*i-l*n,t},t.b7=function(){const t=new Float32Array(16);return x(t),t},t.b8=function(){const t=new Float64Array(16);return x(t),t},t.b9=function(){return new Float64Array(16)},t.bA=function(t){return t[0]=0,t[1]=0,t[2]=0,t},t.bB=function(t,e,r,n){const i=Math.sqrt(t*t+e*e),s=Math.sqrt(r*r+n*n);t/=i,e/=i,r/=s,n/=s;const a=Math.acos(t*r+e*n);return -e*r+t*n>0?a:-a},t.bC=function(t,e){const r=V(t,2*Math.PI),n=V(e,2*Math.PI);return Math.min(Math.abs(r-n),Math.abs(r-n+2*Math.PI),Math.abs(r-n-2*Math.PI))},t.bD=function(){const t={},e=wt.$version;for(const r in wt.$root){const n=wt.$root[r];if(n.required){let i=null;i="version"===r?e:"array"===n.type?[]:{},null!=i&&(t[r]=i);}}return t},t.bE=ys,t.bF=ft,t.bG=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(let n=0;n{"source"in t&&n[t.source]?r.push({command:"removeLayer",args:[t.id]}):s.push(t);})),r=r.concat(i),function(t,e,r){e=e||[];const n=(t=t||[]).map(Bt),i=e.map(Bt),s=t.reduce(Et,{}),a=e.reduce(Et,{}),o=n.slice(),l=Object.create(null);let u,c,h,p,f;for(let t=0,e=0;ty?(i=Math.acos(s),a=Math.sin(i),o=Math.sin((1-n)*i)/a,l=Math.sin(n*i)/a):(o=1-n,l=n),t[0]=o*u+l*f,t[1]=o*c+l*d,t[2]=o*h+l*m,t[3]=o*p+l*g,t},t.bc=function(t){const e=new Float64Array(9);var r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v;h=(i=(n=t)[0])*(l=i+i),p=(s=n[1])*l,d=(a=n[2])*l,y=a*(u=s+s),g=(o=n[3])*l,x=o*u,v=o*(c=a+a),(r=e)[0]=1-(f=s*u)-(m=a*c),r[3]=p-v,r[6]=d+x,r[1]=p+v,r[4]=1-h-m,r[7]=y-g,r[2]=d-x,r[5]=y+g,r[8]=1-h-f;const b=it(-Math.asin(O(e[2],-1,1)));let w,_;return Math.hypot(e[5],e[8])<.001?(w=0,_=-it(Math.atan2(e[3],e[4]))):(w=it(0===e[5]&&0===e[8]?0:Math.atan2(e[5],e[8])),_=it(0===e[1]&&0===e[0]?0:Math.atan2(e[1],e[0]))),{roll:w,pitch:b+90,bearing:_}},t.bd=function(t,e){return t.roll==e.roll&&t.pitch==e.pitch&&t.bearing==e.bearing},t.be=Pe,t.bf=ho,t.bg=Hl,t.bh=Kl,t.bi=Zl,t.bj=F,t.bk=L,t.bl=je,t.bm=function(t,e,r,n,i){return F(n,i,O((t-e)/(r-e),0,1))},t.bn=V,t.bo=function(){return new Float64Array(3)},t.bp=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t},t.bq=P,t.br=function(t,e,r){var n=r[0],i=r[1],s=r[2],a=e[0],o=e[1],l=e[2],u=i*l-s*o,c=s*a-n*l,h=n*o-i*a,p=i*h-s*c,f=s*u-n*h,d=n*c-i*u,y=2*r[3];return c*=y,h*=y,f*=2,d*=2,t[0]=a+(u*=y)+(p*=2),t[1]=o+c+f,t[2]=l+h+d,t},t.bs=function(t,e,r){const n=(i=[t[0],t[1],t[2],e[0],e[1],e[2],r[0],r[1],r[2]])[0]*((c=i[8])*(a=i[4])-(o=i[5])*(u=i[7]))+i[1]*(-c*(s=i[3])+o*(l=i[6]))+i[2]*(u*s-a*l);var i,s,a,o,l,u,c;if(0===n)return null;const h=A([],[e[0],e[1],e[2]],[r[0],r[1],r[2]]),p=A([],[r[0],r[1],r[2]],[t[0],t[1],t[2]]),f=A([],[t[0],t[1],t[2]],[e[0],e[1],e[2]]),d=S([],h,-t[3]);return _(d,d,S([],p,-e[3])),_(d,d,S([],f,-r[3])),S(d,d,1/n),d},t.bt=ph,t.bu=function(){return new Float64Array(4)},t.bv=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),s[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),s[2]=i[2],t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bw=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0],s[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),s[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bx=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),s[1]=i[1],s[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.by=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i-u*n,t[1]=a*i-c*n,t[2]=o*i-h*n,t[3]=l*i-p*n,t[8]=s*n+u*i,t[9]=a*n+c*i,t[10]=o*n+h*i,t[11]=l*n+p*i,t},t.bz=function(t,e){const r=V(t,360),n=V(e,360),i=n-r,s=n>r?i-360:i+360;return Math.abs(i)t*ac));}let v=o?"center":n.get("text-justify").evaluate(i,{},e.canonical);const b="point"===n.get("symbol-placement")?n.get("text-max-width").evaluate(i,{},e.canonical)*ac:1/0,w=()=>{e.bucket.allowVerticalPlacement&&gs(s)&&(d.vertical=bc(y,e.glyphMap,e.glyphPositions,e.imagePositions,c,b,a,m,"left",f,g,t.an.vertical,!0,p,h));};if(!o&&x){const r=new Set;if("auto"===v)for(let t=0;t"symbol"===t.type,t.cb=t=>"circle"===t.type,t.cc=t=>"heatmap"===t.type,t.cd=t=>"line"===t.type,t.ce=t=>"fill"===t.type,t.cf=t=>"fill-extrusion"===t.type,t.cg=t=>"hillshade"===t.type,t.ch=t=>"color-relief"===t.type,t.ci=t=>"raster"===t.type,t.cj=t=>"background"===t.type,t.ck=t=>"custom"===t.type,t.cl=$,t.cm=function(t,e,r){const n=B(e.x-r.x,e.y-r.y),i=B(t.x-r.x,t.y-r.y);var s,a;return it(Math.atan2(n[0]*i[1]-n[1]*i[0],(s=n)[0]*(a=i)[0]+s[1]*a[1]))},t.cn=D,t.co=function(t,e){return at[e]&&(t instanceof MouseEvent||t instanceof WheelEvent)},t.cp=function(t,e){return st[e]&&"touches"in t},t.cq=function(t){return st[t]||at[t]},t.cr=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t},t.cs=function(t,e){const{x:r,y:n}=wh.fromLngLat(e);return !(t<0||t>25||n<0||n>=1||r<0||r>=1)},t.ct=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.cu=class extends Qs{},t.cv=bp,t.cx=function(t){return t.message===ot},t.cy=pt,t.cz=function(t,e){ut.REGISTERED_PROTOCOLS[t]=e;},t.d=yt,t.e=j,t.f=t=>e(void 0,void 0,void 0,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),t.g=ct,t.h=t=>new Promise(((e,r)=>{const n=new Image;n.onload=()=>{e(n),URL.revokeObjectURL(n.src),n.onload=null,window.requestAnimationFrame((()=>{n.src=W;}));},n.onerror=()=>r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const i=new Blob([new Uint8Array(t)],{type:"image/png"});n.src=t.byteLength?URL.createObjectURL(i):W;})),t.i=H,t.j=(t,e)=>dt(j(t,{type:"json"}),e),t.k=vt,t.l=xt,t.m=dt,t.n=(t,e)=>dt(j(t,{type:"arrayBuffer"}),e),t.o=function(t){return new hc(t).readFields(pc,[])},t.p=yc,t.q=il,t.r=qs,t.s=rt,t.t=Ts,t.u=ms,t.v=wt,t.w=Z,t.x=rs,t.y=as,t.z=es;})); + +define("worker",["./shared"],(function(e){"use strict";class t{constructor(e){this.keyCache={},e&&this.replace(e);}replace(e){this._layerConfigs={},this._layers={},this.update(e,[]);}update(t,o){for(const o of t){this._layerConfigs[o.id]=o;const t=this._layers[o.id]=e.bI(o);t._featureFilter=e.a9(t.filter),this.keyCache[o.id]&&delete this.keyCache[o.id];}for(const e of o)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const i=e.cB(Object.values(this._layerConfigs),this.keyCache);for(const e of i){const t=e.map((e=>this._layers[e.id])),o=t[0];if("none"===o.visibility)continue;const i=o.source||"";let r=this.familiesBySource[i];r||(r=this.familiesBySource[i]={});const s=o.sourceLayer||"_geojsonTileLayer";let n=r[s];n||(n=r[s]=[]),n.push(t);}}}class o{constructor(t){const o={},i=[];for(const e in t){const r=t[e],s=o[e]={};for(const e in r){const t=r[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const o={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};i.push(o),s[e]={rect:o,metrics:t.metrics};}}const{w:r,h:s}=e.p(i),n=new e.q({width:r||1,height:s||1});for(const i in t){const r=t[i];for(const t in r){const s=r[+t];if(!s||0===s.bitmap.width||0===s.bitmap.height)continue;const a=o[i][t].rect;e.q.copy(s.bitmap,n,{x:0,y:0},{x:a.x+1,y:a.y+1},s.bitmap);}}this.image=n,this.positions=o;}}e.cC("GlyphAtlas",o);class i{constructor(t){this.tileID=new e.Z(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[],this.globalState=t.globalState;}parse(t,i,s,n,a){return e._(this,void 0,void 0,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.a7;const l=new e.cD(Object.keys(t.layers).sort()),c=new e.cE(this.tileID,this.promoteId);c.bucketLayerIDs=[];const u={},h={featureIndex:c,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:s,subdivisionGranularity:a},d=i.familiesBySource[this.source];for(const o in d){const i=t.layers[o];if(!i)continue;1===i.version&&e.w(`Vector tile source "${this.source}" layer "${o}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const n=l.encode(o),a=[];for(let e=0;e=o.maxzoom||"none"!==o.visibility&&(r(t,this.zoom,s),(u[o.id]=o.createBucket({index:c.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:n,sourceID:this.source,globalState:this.globalState})).populate(a,h,this.tileID.canonical),c.bucketLayerIDs.push(t.map((e=>e.id))));}}const f=e.bM(h.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?void 0:e.abort())),this.inFlightDependencies=[];let g=Promise.resolve({});if(Object.keys(f).length){const e=new AbortController;this.inFlightDependencies.push(e),g=n.sendAsync({type:"GG",data:{stacks:f,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const p=Object.keys(h.iconDependencies);let m=Promise.resolve({});if(p.length){const e=new AbortController;this.inFlightDependencies.push(e),m=n.sendAsync({type:"GI",data:{icons:p,source:this.source,tileID:this.tileID,type:"icons"}},e);}const y=Object.keys(h.patternDependencies);let v=Promise.resolve({});if(y.length){const e=new AbortController;this.inFlightDependencies.push(e),v=n.sendAsync({type:"GI",data:{icons:y,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const[w,x,b]=yield Promise.all([g,m,v]),S=new o(w),_=new e.cF(x,b);for(const t in u){const o=u[t];o instanceof e.a8?(r(o.layers,this.zoom,s),e.cG({bucket:o,glyphMap:w,glyphPositions:S.positions,imageMap:x,imagePositions:_.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:h.subdivisionGranularity})):o.hasPattern&&(o instanceof e.cH||o instanceof e.cI||o instanceof e.cJ)&&(r(o.layers,this.zoom,s),o.addFeatures(h,this.tileID.canonical,_.patternPositions));}return this.status="done",{buckets:Object.values(u).filter((e=>!e.isEmpty())),featureIndex:c,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:S.image,imageAtlas:_,glyphMap:this.returnDependencies?w:null,iconMap:this.returnDependencies?x:null,glyphPositions:this.returnDependencies?S.positions:null}}))}}function r(t,o,i){const r=new e.F(o);for(const e of t)e.recalculate(r,i);}class s{constructor(e,t,o){this.actor=e,this.layerIndex=t,this.availableImages=o,this.fetching={},this.loading={},this.loaded={};}loadVectorTile(t,o){return e._(this,void 0,void 0,(function*(){const i=yield e.n(t.request,o);try{return {vectorTile:new e.cK.VectorTile(new e.cL(i.data)),rawData:i.data,cacheControl:i.cacheControl,expires:i.expires}}catch(e){const o=new Uint8Array(i.data);let r=`Unable to parse the tile at ${t.request.url}, `;throw r+=31===o[0]&&139===o[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${e.message}`,new Error(r)}}))}loadTile(t){return e._(this,void 0,void 0,(function*(){const o=t.uid,r=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.cM(t.request),s=new i(t);this.loading[o]=s;const n=new AbortController;s.abort=n;try{const i=yield this.loadVectorTile(t,n);if(delete this.loading[o],!i)return null;const a=i.rawData,l={};i.expires&&(l.expires=i.expires),i.cacheControl&&(l.cacheControl=i.cacheControl);const c={};if(r){const e=r.finish();e&&(c.resourceTiming=JSON.parse(JSON.stringify(e)));}s.vectorTile=i.vectorTile;const u=s.parse(i.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);this.loaded[o]=s,this.fetching[o]={rawTileData:a,cacheControl:l,resourceTiming:c};try{const t=yield u;return e.e({rawTileData:a.slice(0)},t,l,c)}finally{delete this.fetching[o];}}catch(e){throw delete this.loading[o],s.status="done",this.loaded[o]=s,e}}))}reloadTile(t){return e._(this,void 0,void 0,(function*(){const o=t.uid;if(!this.loaded||!this.loaded[o])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const i=this.loaded[o];if(i.showCollisionBoxes=t.showCollisionBoxes,i.globalState=t.globalState,"parsing"===i.status){const r=yield i.parse(i.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);let s;if(this.fetching[o]){const{rawTileData:t,cacheControl:i,resourceTiming:n}=this.fetching[o];delete this.fetching[o],s=e.e({rawTileData:t.slice(0)},r,i,n);}else s=r;return s}if("done"===i.status&&i.vectorTile)return i.parse(i.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity)}))}abortTile(t){return e._(this,void 0,void 0,(function*(){const e=this.loading,o=t.uid;e&&e[o]&&e[o].abort&&(e[o].abort.abort(),delete e[o]);}))}removeTile(t){return e._(this,void 0,void 0,(function*(){this.loaded&&this.loaded[t.uid]&&delete this.loaded[t.uid];}))}}class n{constructor(){this.loaded={};}loadTile(t){return e._(this,void 0,void 0,(function*(){const{uid:o,encoding:i,rawImageData:r,redFactor:s,greenFactor:n,blueFactor:a,baseShift:l}=t,c=r.width+2,u=r.height+2,h=e.b(r)?new e.R({width:c,height:u},yield e.cN(r,-1,-1,c,u)):r,d=new e.cO(o,h,i,s,n,a,l);return this.loaded=this.loaded||{},this.loaded[o]=d,d}))}removeTile(e){const t=this.loaded,o=e.uid;t&&t[o]&&delete t[o];}}var a,l,c=function(){if(l)return a;function e(e,o){if(0!==e.length){t(e[0],o);for(var i=1;i=Math.abs(a)?o-l+a:a-l+o,o=l;}o+i>=0!=!!t&&e.reverse();}return l=1,a=function t(o,i){var r,s=o&&o.type;if("FeatureCollection"===s)for(r=0;r>31}function c(e,t){for(var o=e.loadGeometry(),i=e.type,r=0,s=0,n=o.length,c=0;ce},b=Math.fround||(S=new Float32Array(1),e=>(S[0]=+e,S[0]));var S;class _{constructor(e){this.options=Object.assign(Object.create(x),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:o,maxZoom:i}=this.options;t&&console.time("total time");const r=`prepare ${e.length} points`;t&&console.time(r),this.points=e;const s=[];for(let t=0;t=o;e--){const o=+Date.now();n=this.trees[e]=this._createTree(this._cluster(n,e)),t&&console.log("z%d: %d clusters in %dms",e,n.numItems,+Date.now()-o);}return t&&console.timeEnd("total time"),this}getClusters(e,t){let o=((e[0]+180)%360+360)%360-180;const i=Math.max(-90,Math.min(90,e[1]));let r=180===e[2]?180:((e[2]+180)%360+360)%360-180;const s=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)o=-180,r=180;else if(o>r){const e=this.getClusters([o,i,180,s],t),n=this.getClusters([-180,i,r,s],t);return e.concat(n)}const n=this.trees[this._limitZoom(t)],a=n.range(P(o),k(s),P(r),k(i)),l=n.data,c=[];for(const e of a){const t=this.stride*e;c.push(l[t+5]>1?M(l,t,this.clusterProps):this.points[l[t+3]]);}return c}getChildren(e){const t=this._getOriginId(e),o=this._getOriginZoom(e),i="No cluster with the specified id.",r=this.trees[o];if(!r)throw new Error(i);const s=r.data;if(t*this.stride>=s.length)throw new Error(i);const n=this.options.radius/(this.options.extent*Math.pow(2,o-1)),a=r.within(s[t*this.stride],s[t*this.stride+1],n),l=[];for(const t of a){const o=t*this.stride;s[o+4]===e&&l.push(s[o+5]>1?M(s,o,this.clusterProps):this.points[s[o+3]]);}if(0===l.length)throw new Error(i);return l}getLeaves(e,t,o){const i=[];return this._appendLeaves(i,e,t=t||10,o=o||0,0),i}getTile(e,t,o){const i=this.trees[this._limitZoom(e)],r=Math.pow(2,e),{extent:s,radius:n}=this.options,a=n/s,l=(o-a)/r,c=(o+1+a)/r,u={features:[]};return this._addTileFeatures(i.range((t-a)/r,l,(t+1+a)/r,c),i.data,t,o,r,u),0===t&&this._addTileFeatures(i.range(1-a/r,l,1,c),i.data,r,o,r,u),t===r-1&&this._addTileFeatures(i.range(0,l,a/r,c),i.data,-1,o,r,u),u.features.length?u:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const o=this.getChildren(e);if(t++,1!==o.length)break;e=o[0].properties.cluster_id;}return t}_appendLeaves(e,t,o,i,r){const s=this.getChildren(t);for(const t of s){const s=t.properties;if(s&&s.cluster?r+s.point_count<=i?r+=s.point_count:r=this._appendLeaves(e,s.cluster_id,o,i,r):r1;let l,c,u;if(a)l=I(t,e,this.clusterProps),c=t[e],u=t[e+1];else {const o=this.points[t[e+3]];l=o.properties;const[i,r]=o.geometry.coordinates;c=P(i),u=k(r);}const h={type:1,geometry:[[Math.round(this.options.extent*(c*r-o)),Math.round(this.options.extent*(u*r-i))]],tags:l};let d;d=a||this.options.generateId?t[e+3]:this.points[t[e+3]].id,void 0!==d&&(h.id=d),s.features.push(h);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:o,extent:i,reduce:r,minPoints:s}=this.options,n=o/(i*Math.pow(2,t)),a=e.data,l=[],c=this.stride;for(let o=0;ot&&(f+=a[o+5]);}if(f>d&&f>=s){let e,s=i*d,n=u*d,g=-1;const p=(o/c<<5)+(t+1)+this.points.length;for(const i of h){const l=i*c;if(a[l+2]<=t)continue;a[l+2]=t;const u=a[l+5];s+=a[l]*u,n+=a[l+1]*u,a[l+4]=p,r&&(e||(e=this._map(a,o,!0),g=this.clusterProps.length,this.clusterProps.push(e)),r(e,this._map(a,l)));}a[o+4]=p,l.push(s/f,n/f,1/0,p,-1,f),r&&l.push(g);}else {for(let e=0;e1)for(const e of h){const o=e*c;if(!(a[o+2]<=t)){a[o+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,o){if(e[t+5]>1){const i=this.clusterProps[e[t+6]];return o?Object.assign({},i):i}const i=this.points[e[t+3]].properties,r=this.options.map(i);return o&&r===i?Object.assign({},r):r}}function M(e,t,o){return {type:"Feature",id:e[t+3],properties:I(e,t,o),geometry:{type:"Point",coordinates:[(i=e[t],360*(i-.5)),T(e[t+1])]}};var i;}function I(e,t,o){const i=e[t+5],r=i>=1e4?`${Math.round(i/1e3)}k`:i>=1e3?Math.round(i/100)/10+"k":i,s=e[t+6],n=-1===s?{}:Object.assign({},o[s]);return Object.assign(n,{cluster:!0,cluster_id:e[t+3],point_count:i,point_count_abbreviated:r})}function P(e){return e/360+.5}function k(e){const t=Math.sin(e*Math.PI/180),o=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return o<0?0:o>1?1:o}function T(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function D(e,t,o,i){let r=i;const s=t+(o-t>>1);let n,a=o-t;const l=e[t],c=e[t+1],u=e[o],h=e[o+1];for(let i=t+3;ir)n=i,r=t;else if(t===r){const e=Math.abs(i-s);ei&&(n-t>3&&D(e,t,n,i),e[n+2]=r,o-n>3&&D(e,n,o,i));}function C(e,t,o,i,r,s){let n=r-o,a=s-i;if(0!==n||0!==a){const l=((e-o)*n+(t-i)*a)/(n*n+a*a);l>1?(o=r,i=s):l>0&&(o+=n*l,i+=a*l);}return n=e-o,a=t-i,n*n+a*a}function O(e,t,o,i){const r={id:null==e?null:e,type:t,geometry:o,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===t||"MultiPoint"===t||"LineString"===t)L(r,o);else if("Polygon"===t)L(r,o[0]);else if("MultiLineString"===t)for(const e of o)L(r,e);else if("MultiPolygon"===t)for(const e of o)L(r,e[0]);return r}function L(e,t){for(let o=0;o0&&(n+=i?(r*l-a*s)/2:Math.sqrt(Math.pow(a-r,2)+Math.pow(l-s,2))),r=a,s=l;}const a=t.length-3;t[2]=1,D(t,0,a,o),t[a+2]=1,t.size=Math.abs(n),t.start=0,t.end=t.size;}function A(e,t,o,i){for(let r=0;r1?1:o}function Z(e,t,o,i,r,s,n,a){if(i/=t,s>=(o/=t)&&n=i)return null;const l=[];for(const t of e){const e=t.geometry;let s=t.type;const n=0===r?t.minX:t.minY,c=0===r?t.maxX:t.maxY;if(n>=o&&c=i)continue;let u=[];if("Point"===s||"MultiPoint"===s)N(e,u,o,i,r);else if("LineString"===s)J(e,u,o,i,r,!1,a.lineMetrics);else if("MultiLineString"===s)W(e,u,o,i,r,!1);else if("Polygon"===s)W(e,u,o,i,r,!0);else if("MultiPolygon"===s)for(const t of e){const e=[];W(t,e,o,i,r,!0),e.length&&u.push(e);}if(u.length){if(a.lineMetrics&&"LineString"===s){for(const e of u)l.push(O(t.id,s,e,t.tags));continue}"LineString"!==s&&"MultiLineString"!==s||(1===u.length?(s="LineString",u=u[0]):s="MultiLineString"),"Point"!==s&&"MultiPoint"!==s||(s=3===u.length?"Point":"MultiPoint"),l.push(O(t.id,s,u,t.tags));}}return l.length?l:null}function N(e,t,o,i,r){for(let s=0;s=o&&n<=i&&Y(t,e[s],e[s+1],e[s+2]);}}function J(e,t,o,i,r,s,n){let a=R(e);const l=0===r?V:q;let c,u,h=e.start;for(let d=0;do&&(u=l(a,f,g,m,y,o),n&&(a.start=h+c*u)):v>i?w=o&&(u=l(a,f,g,m,y,o),x=!0),w>i&&v<=i&&(u=l(a,f,g,m,y,i),x=!0),!s&&x&&(n&&(a.end=h+c*u),t.push(a),a=R(e)),n&&(h+=c);}let d=e.length-3;const f=e[d],g=e[d+1],p=0===r?f:g;p>=o&&p<=i&&Y(a,f,g,e[d+2]),d=a.length-3,s&&d>=3&&(a[d]!==a[0]||a[d+1]!==a[1])&&Y(a,a[0],a[1],a[2]),a.length&&t.push(a);}function R(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function W(e,t,o,i,r,s){for(const n of e)J(n,t,o,i,r,s,!1);}function Y(e,t,o,i){e.push(t,o,i);}function V(e,t,o,i,r,s){const n=(s-t)/(i-t);return Y(e,s,o+(r-o)*n,1),n}function q(e,t,o,i,r,s){const n=(s-o)/(r-o);return Y(e,t+(i-t)*n,s,1),n}function H(e,t){const o=[];for(let i=0;i0&&t.size<(r?n:i))return void(o.numPoints+=t.length/3);const a=[];for(let e=0;en)&&(o.numSimplified++,a.push(t[e],t[e+1])),o.numPoints++;r&&function(e,t){let o=0;for(let t=0,i=e.length,r=i-2;t0===t)for(let t=0,o=e.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");let i=function(e,t){const o=[];if("FeatureCollection"===e.type)for(let i=0;i1&&console.time("creation"),d=this.tiles[h]=U(e,t,o,i,l),this.tileCoords.push({z:t,x:o,y:i}),c)){c>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,o,i,d.numFeatures,d.numPoints,d.numSimplified),console.timeEnd("creation"));const e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++;}if(d.source=e,null==r){if(t===l.indexMaxZoom||d.numPoints<=l.indexMaxPoints)continue}else {if(t===l.maxZoom||t===r)continue;if(null!=r){const e=r-t;if(o!==s>>e||i!==n>>e)continue}}if(d.source=null,0===e.length)continue;c>1&&console.time("clipping");const f=.5*l.buffer/l.extent,g=.5-f,p=.5+f,m=1+f;let y=null,v=null,w=null,x=null,b=Z(e,u,o-f,o+p,0,d.minX,d.maxX,l),S=Z(e,u,o+g,o+m,0,d.minX,d.maxX,l);e=null,b&&(y=Z(b,u,i-f,i+p,1,d.minY,d.maxY,l),v=Z(b,u,i+g,i+m,1,d.minY,d.maxY,l),b=null),S&&(w=Z(S,u,i-f,i+p,1,d.minY,d.maxY,l),x=Z(S,u,i+g,i+m,1,d.minY,d.maxY,l),S=null),c>1&&console.timeEnd("clipping"),a.push(y||[],t+1,2*o,2*i),a.push(v||[],t+1,2*o,2*i+1),a.push(w||[],t+1,2*o+1,2*i),a.push(x||[],t+1,2*o+1,2*i+1);}}getTile(e,t,o){e=+e,t=+t,o=+o;const i=this.options,{extent:r,debug:s}=i;if(e<0||e>24)return null;const n=1<1&&console.log("drilling down to z%d-%d-%d",e,t,o);let l,c=e,u=t,h=o;for(;!l&&c>0;)c--,u>>=1,h>>=1,l=this.tiles[oe(c,u,h)];return l&&l.source?(s>1&&(console.log("found parent tile z%d-%d-%d",c,u,h),console.time("drilling down")),this.splitTile(l.source,c,u,h,e,t,o),s>1&&console.timeEnd("drilling down"),this.tiles[a]?B(this.tiles[a],r):null):null}}function oe(e,t,o){return 32*((1<{n.properties=e;const t={};for(const e of a)t[e]=i[e].evaluate(s,n);return t},t.reduce=(e,t)=>{n.properties=t;for(const t of a)s.accumulated=e[t],e[t]=r[t].evaluate(s,n);},t}(t)).load((yield this._pendingData).features):(r=yield this._pendingData,new te(r,t.geojsonVtOptions)),this.loaded={};const o={};if(i){const e=i.finish();e&&(o.resourceTiming={},o.resourceTiming[t.source]=JSON.parse(JSON.stringify(e)));}return o}catch(t){if(delete this._pendingRequest,e.cx(t))return {abandoned:!0};throw t}var r;}))}getData(){return e._(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(e){const t=this.loaded;return t&&t[e.uid]?super.reloadTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,o){return e._(this,void 0,void 0,(function*(){let i=yield this.loadGeoJSON(t,o);if(delete this._pendingRequest,"object"!=typeof i)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(u(i,!0),t.filter){const o=e.cT(t.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===o.result)throw new Error(o.value.map((e=>`${e.key}: ${e.message}`)).join(", "));const r=i.features.filter((e=>o.value.evaluate({zoom:0},e)));i={type:"FeatureCollection",features:r};}return i}))}loadGeoJSON(t,o){return e._(this,void 0,void 0,(function*(){const{promoteId:i}=t;if(t.request){const r=yield e.j(t.request,o);return this._dataUpdateable=re(r.data,i)?se(r.data,i):void 0,r.data}if("string"==typeof t.data)try{const e=JSON.parse(t.data);return this._dataUpdateable=re(e,i)?se(e,i):void 0,e}catch(e){throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}if(!t.dataDiff)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${t.source}`);return function(e,t,o){var i,r,s,n;if(t.removeAll&&e.clear(),t.remove)for(const o of t.remove)e.delete(o);if(t.add)for(const i of t.add){const t=ie(i,o);null!=t&&e.set(t,i);}if(t.update)for(const o of t.update){let t=e.get(o.id);if(null==t)continue;const a=!o.removeAllProperties&&((null===(i=o.removeProperties)||void 0===i?void 0:i.length)>0||(null===(r=o.addOrUpdateProperties)||void 0===r?void 0:r.length)>0);if((o.newGeometry||o.removeAllProperties||a)&&(t=Object.assign({},t),e.set(o.id,t),a&&(t.properties=Object.assign({},t.properties))),o.newGeometry&&(t.geometry=o.newGeometry),o.removeAllProperties)t.properties={};else if((null===(s=o.removeProperties)||void 0===s?void 0:s.length)>0)for(const e of o.removeProperties)Object.prototype.hasOwnProperty.call(t.properties,e)&&delete t.properties[e];if((null===(n=o.addOrUpdateProperties)||void 0===n?void 0:n.length)>0)for(const{key:e,value:i}of o.addOrUpdateProperties)t.properties[e]=i;}}(this._dataUpdateable,t.dataDiff,i),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(t){return e._(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset)}}class ae{constructor(t){this.self=t,this.actor=new e.J(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.cz,this.self.removeProtocol=e.cA,this.self.registerRTLTextPlugin=t=>{e.cU.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,o)=>e._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(t,o.source).removeTile(o);})))),this.actor.registerMessageHandler("GCEZ",((t,o)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,o.type,o.source).getClusterExpansionZoom(o)})))),this.actor.registerMessageHandler("GCC",((t,o)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,o.type,o.source).getClusterChildren(o)})))),this.actor.registerMessageHandler("GCL",((t,o)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,o.type,o.source).getClusterLeaves(o)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("GD",((e,t)=>this._getWorkerSource(e,t.type,t.source).getData())),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,o)=>e._(this,void 0,void 0,(function*(){if(!this.workerSources[t]||!this.workerSources[t][o.type]||!this.workerSources[t][o.type][o.source])return;const e=this.workerSources[t][o.type][o.source];delete this.workerSources[t][o.type][o.source],void 0!==e.removeSource&&e.removeSource(o);})))),this.actor.registerMessageHandler("RM",(t=>e._(this,void 0,void 0,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t];})))),this.actor.registerMessageHandler("SR",((t,o)=>e._(this,void 0,void 0,(function*(){this.referrer=o;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,o)=>e._(this,void 0,void 0,(function*(){this.self.importScripts(o);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,o)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).update(o.layers,o.removedIds);})))),this.actor.registerMessageHandler("SL",((t,o)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).replace(o);}))));}_setImages(t,o){return e._(this,void 0,void 0,(function*(){this.availableImages[t]=o;for(const e in this.workerSources[t]){const i=this.workerSources[t][e];for(const e in i)i[e].availableImages=o;}}))}_syncRTLPluginState(t,o){return e._(this,void 0,void 0,(function*(){return yield e.cU.syncState(o,this.self.importScripts)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(e){let o=this.layerIndexes[e];return o||(o=this.layerIndexes[e]=new t),o}_getWorkerSource(e,t,o){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][o]){const i={sendAsync:(t,o)=>(t.targetMapId=e,this.actor.sendAsync(t,o))};switch(t){case "vector":this.workerSources[e][t][o]=new s(i,this._getLayerIndex(e),this._getAvailableImages(e));break;case "geojson":this.workerSources[e][t][o]=new ne(i,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][o]=new this.externalWorkerSourceTypes[t](i,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][t][o]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new n),this.demWorkerSources[e][t]}}return e.i(self)&&(self.worker=new ae(self)),ae})); + +define("index",["exports","./shared"],(function(e,t){"use strict";var i="5.6.0";function o(){var e=new t.A(4);return t.A!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}let r,a;const s={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frame(e,i,o){const r=requestAnimationFrame((e=>{a(),i(e);})),{unsubscribe:a}=t.s(e.signal,"abort",(()=>{a(),cancelAnimationFrame(r),o(t.c());}),!1);},frameAsync(e){return new Promise(((t,i)=>{this.frame(e,t,i);}))},getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(r||(r=document.createElement("a")),r.href=e,r.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==a&&(a=matchMedia("(prefers-reduced-motion: reduce)")),a.matches)}};class n{static testProp(e){if(!n.docStyle)return e[0];for(let t=0;t{window.removeEventListener("click",n.suppressClickInternal,!0);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,o){const r=i.boundingClientRect;return new t.P((o.clientX-r.left)/i.x-e.clientLeft,(o.clientY-r.top)/i.y-e.clientTop)}static mousePos(e,t){const i=n.getScale(e);return n.getPoint(e,i,t)}static touchPos(e,t){const i=[],o=n.getScale(e);for(let r=0;r{c&&_(c),c=null,d=!0;},h.onerror=()=>{u=!0,c=null;},h.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(e){let i,o,r,a;e.resetRequestQueue=()=>{i=[],o=0,r=0,a={};},e.addThrottleControl=e=>{const t=r++;return a[t]=e,t},e.removeThrottleControl=e=>{delete a[e],n();},e.getImage=(e,o,r=!0)=>new Promise(((a,s)=>{l.supported&&(e.headers||(e.headers={}),e.headers.accept="image/webp,*/*"),t.e(e,{type:"image"}),i.push({abortController:o,requestParameters:e,supportImageRefresh:r,state:"queued",onError:e=>{s(e);},onSuccess:e=>{a(e);}}),n();}));const s=e=>t._(this,void 0,void 0,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:r,onError:a,onSuccess:s,abortController:l}=e,h=!1===r&&!t.i(self)&&!t.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),!0));o++;const u=h?c(i,l):t.m(i,l);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.b(i.data)?s(i):i.data&&s({data:yield(d=i.data,"function"==typeof createImageBitmap?t.f(d):t.h(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,a(t);}finally{o--,n();}var d;})),n=()=>{const e=(()=>{for(const e of Object.keys(a))if(a[e]())return !0;return !1})()?t.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=o;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:s(e);}},c=(e,i)=>new Promise(((o,r)=>{const a=new Image,s=e.url,n=e.credentials;n&&"include"===n?a.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.d(s))&&(a.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{a.src="",r(t.c());})),a.fetchPriority="high",a.onload=()=>{a.onerror=a.onload=null,o({data:a});},a.onerror=()=>{a.onerror=a.onload=null,i.signal.aborted||r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));},a.src=s;}));}(p||(p={})),p.resetRequestQueue();class m{constructor(e){this._transformRequestFn=e;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}function f(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:o,url:r}of e){const e=`${o}${r}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:o,url:r}));}}return t}function g(e,t,i){try{const o=new URL(e);return o.pathname+=`${t}${i}`,o.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}function v(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class b extends t.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.R({width:1,height:1}),this.dirty=!0;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.R({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let o=!0;const r=i.data||i.spriteData;return this._validateStretch(i.stretchX,r&&r.width)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchX" value`))),o=!1),this._validateStretch(i.stretchY,r&&r.height)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchY" value`))),o=!1),this._validateContent(i.content,i)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "content" value`))),o=!1),o}_validateStretch(e,t){if(!e)return !0;let i=0;for(const o of e){if(o[0]{let o=!0;if(!this.isLoaded())for(const t of e)this.images[t]||(o=!1);this.isLoaded()||o?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const o of e){let e=this.getImage(o);e||(this.fire(new t.l("styleimagemissing",{id:o})),e=this.getImage(o)),e?i[o]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.w(`Image "${o}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);}return i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],o=this.getImage(e);if(!o)return null;if(i&&i.position.version===o.version)return i.position;if(i)i.position.version=o.version;else {const i={w:o.data.width+2,h:o.data.height+2,x:0,y:0},r=new t.I(i,o);this.patterns[e]={bin:i,position:r};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const i=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new t.T(e,this.atlasImage,i.RGBA),this.atlasTexture.bind(i.LINEAR,i.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:o}=t.p(e),r=this.atlasImage;r.resize({width:i||1,height:o||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],o=i.x+1,a=i.y+1,s=this.getImage(e).data,n=s.width,l=s.height;t.R.copy(s,r,{x:0,y:0},{x:o,y:a},{width:n,height:l}),t.R.copy(s,r,{x:0,y:l-1},{x:o,y:a-1},{width:n,height:1}),t.R.copy(s,r,{x:0,y:0},{x:o,y:a+l},{width:n,height:1}),t.R.copy(s,r,{x:n-1,y:0},{x:o-1,y:a},{width:1,height:l}),t.R.copy(s,r,{x:0,y:0},{x:o+n,y:a},{width:1,height:l});}this.dirty=!0;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=!0;const e=this.getImage(i);e||t.w(`Image with ID: "${i}" was not found`),v(e)&&this.updateImage(i,e);}}}const x=1e20;function y(e,t,i,o,r,a,s,n,l){for(let c=t;c-1);l++,a[l]=n,s[l]=c,s[l+1]=x;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(t.ranges[r])return {stack:e,id:i,glyph:o};if(!this.url)throw new Error("glyphsUrl is not set");if(!t.requests[r]){const i=T.loadGlyphRange(e,r,this.url,this.requestManager);t.requests[r]=i;}const a=yield t.requests[r];for(const e in a)this._doesCharSupportLocalGlyph(+e)||(t.glyphs[+e]=a[+e]);return t.ranges[r]=!0,{stack:e,id:i,glyph:a[i]||null}}))}_doesCharSupportLocalGlyph(e){return !!this.localIdeographFontFamily&&(/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(e))||t.u["CJK Unified Ideographs"](e)||t.u["Hangul Syllables"](e)||t.u.Hiragana(e)||t.u.Katakana(e)||t.u["CJK Symbols and Punctuation"](e)||t.u["Halfwidth and Fullwidth Forms"](e))}_tinySDF(e,i,o){const r=this.localIdeographFontFamily;if(!r)return;if(!this._doesCharSupportLocalGlyph(o))return;let a=e.tinySDF;if(!a){let t="400";/bold/i.test(i)?t="900":/medium/i.test(i)?t="500":/light/i.test(i)&&(t="200"),a=e.tinySDF=new T.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,fontFamily:r,fontWeight:t});}const s=a.draw(String.fromCharCode(o));return {id:o,bitmap:new t.q({width:s.width||60,height:s.height||60},s.data),metrics:{width:s.glyphWidth/2||24,height:s.glyphHeight/2||24,left:s.glyphLeft/2+.5||0,top:s.glyphTop/2-27.5||-8,advance:s.glyphAdvance/2||24,isDoubleResolution:!0}}}}T.loadGlyphRange=function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=256*i,s=a+255,n=r.transformRequest(o.replace("{fontstack}",e).replace("{range}",`${a}-${s}`),"Glyphs"),l=yield t.n(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${a}-${s}`);const c={};for(const e of t.o(l.data))c[e.id]=e;return c}))},T.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:o=.25,fontFamily:r="sans-serif",fontWeight:a="normal",fontStyle:s="normal"}={}){this.buffer=t,this.cutoff=o,this.radius=i;const n=this.size=e+4*t,l=this._createCanvas(n),c=this.ctx=l.getContext("2d",{willReadFrequently:!0});c.font=`${s} ${a} ${e}px ${r}`,c.textBaseline="alphabetic",c.textAlign="left",c.fillStyle="black",this.gridOuter=new Float64Array(n*n),this.gridInner=new Float64Array(n*n),this.f=new Float64Array(n),this.z=new Float64Array(n+1),this.v=new Uint16Array(n);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:o,actualBoundingBoxLeft:r,actualBoundingBoxRight:a}=this.ctx.measureText(e),s=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(a-r))),l=Math.min(this.size-this.buffer,s+Math.ceil(o)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:s,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;p.clearRect(m,m,n,l),p.fillText(e,m,m+s);const v=p.getImageData(m,m,n,l);g.fill(x,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[o]=e<0?e*e:0;}}y(g,0,0,c,h,c,this.f,this.v,this.z),y(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(s=e[++a]);const l=Math.abs(n-s.left),c=Math.abs(n-s.right),h=Math.min(l,c);let u;const d=t/i*(o+1);if(s.isDash){const e=o-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=o-Math.sqrt(h*h+d*d);this.data[r+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],o=e[t+1];i.zeroLength?e.splice(t,1):o&&o.isDash===i.isDash&&(o.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const o=this.width*this.nextRow;let r=0,a=e[r];for(let t=0;t1&&(a=e[++r]);const i=Math.abs(t-a.left),s=Math.abs(t-a.right),n=Math.min(i,s);this.data[o+t]=Math.max(0,Math.min(255,(a.isDash?n:-n)+128));}}addDash(e,i){const o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.w("LineAtlas out of space"),null;let a=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[R]}numActive(){return Object.keys(this.active).length}}const D=Math.floor(s.hardwareConcurrency/2);let A,L;function k(){return A||(A=new z),A}z.workerCount=t.H(globalThis)?Math.max(Math.min(D,3),1):1;class F{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const o=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}}function B(){return L||(L=new F(k(),t.K),L.registerMessageHandler("GR",((e,i,o)=>t.m(i,o)))),L}function O(e,i){const o=t.L();return t.M(o,o,[1,1,0]),t.N(o,o,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.O(o,o,e.calculatePosMatrix(i.toUnwrapped())):o}function j(e,t,i,o,r,a,s){var n;const l=function(e,t,i){if(e)for(const o of e){const e=t[o];if(e&&e.source===i&&"fill-extrusion"===e.type)return !0}else for(const e in t){const o=t[e];if(o.source===i&&"fill-extrusion"===o.type)return !0}return !1}(null!==(n=null==r?void 0:r.layers)&&void 0!==n?n:null,t,e.id),c=a.maxPitchScaleFactor(),h=e.tilesIn(o,c,l);h.sort(N);const u=[];for(const o of h)u.push({wrappedTileID:o.tileID.wrapped().key,queryResults:o.tile.queryRenderedFeatures(t,i,e._state,o.queryGeometry,o.cameraQueryGeometry,o.scale,r,a,c,O(e.transform,o.tileID),s?(e,t)=>s(o.tileID,e,t):void 0)});return function(e,t){for(const i in e)for(const o of e[i])Z(o,t);return e}(function(e){const t={},i={};for(const o of e){const e=o.queryResults,r=o.wrappedTileID,a=i[r]=i[r]||{};for(const i in e){const o=e[i],r=a[i]=a[i]||{},s=t[i]=t[i]||[];for(const e of o)r[e.featureIndex]||(r[e.featureIndex]=!0,s.push(e));}}return t}(u),e)}function N(e,t){const i=e.tileID,o=t.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}function Z(e,t){const i=e.feature,o=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=o;}function U(e,i,o){return t._(this,void 0,void 0,(function*(){let r=e;if(e.url?r=(yield t.j(i.transformRequest(e.url,"Source"),o)).data:yield s.frameAsync(o),!r)return null;const a=t.Q(t.e(r,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in r&&r.vector_layers&&(a.vectorLayerIds=r.vector_layers.map((e=>e.id))),a}))}class G{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}extend(e){const i=this._sw,o=this._ne;let r,a;if(e instanceof t.S)r=e,a=e;else {if(!(e instanceof G))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(G.convert(e)):this.extend(t.S.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.S.convert(e)):this;if(r=e._sw,a=e._ne,!r||!a)return this}return i||o?(i.lng=Math.min(r.lng,i.lng),i.lat=Math.min(r.lat,i.lat),o.lng=Math.max(a.lng,o.lng),o.lat=Math.max(a.lat,o.lat)):(this._sw=new t.S(r.lng,r.lat),this._ne=new t.S(a.lng,a.lat)),this}getCenter(){return new t.S((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new t.S(this.getWest(),this.getNorth())}getSouthEast(){return new t.S(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(e){const{lng:i,lat:o}=t.S.convert(e);let r=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(r=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=o&&o<=this._ne.lat&&r}static convert(e){return e instanceof G?e:e?new G(e):e}static fromLngLat(e,i=0){const o=360*i/40075017,r=o/Math.cos(Math.PI/180*e.lat);return new G(new t.S(e.lng-r,e.lat-o),new t.S(e.lng+r,e.lat+o))}adjustAntiMeridian(){const e=new t.S(this._sw.lng,this._sw.lat),i=new t.S(this._ne.lng,this._ne.lat);return new G(e,e.lng>i.lng?new t.S(i.lng+360,i.lat):i)}}class V{constructor(e,t,i){this.bounds=G.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),o=Math.floor(t.V(this.bounds.getWest())*i),r=Math.floor(t.U(this.bounds.getNorth())*i),a=Math.ceil(t.V(this.bounds.getEast())*i),s=Math.ceil(t.U(this.bounds.getSouth())*i);return e.x>=o&&e.x=r&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.e({},this._options)}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity,globalState:this.map.getGlobalState()};i.request.collectResourceTiming=this._collectResourceTiming;let o="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),o="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:o,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_afterTileLoadWorkerResponse(e,t){if(t&&t.resourceTiming&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return !1}}class q extends t.E{constructor(e,i,o,r){super(),this.id=e,this.dispatcher=o,this.setEventedParent(r),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.e({type:"raster"},i),t.e(this,t.Q(i,["url","scheme","tileSize"]));}load(){return t._(this,arguments,void 0,(function*(e=!1){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield U(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,i&&(t.e(this,i),i.bounds&&(this.tileBounds=new V(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.l("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this.fire(new t.k(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(!0);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.e({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const o=yield p.getImage(this.map._requestManager.transformRequest(i,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(o&&o.data){this.map._refreshExpiredTiles&&(o.cacheControl||o.expires)&&e.setExpiryData({cacheControl:o.cacheControl,expires:o.expires});const i=this.map.painter.context,r=i.gl,a=o.data;e.texture=this.map.painter.getTileTexture(a.width),e.texture?e.texture.update(a,{useMipmap:!0}):(e.texture=new t.T(i,a,r.RGBA,{useMipmap:!0}),e.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return !1}}class W extends q{constructor(e,i,o,r){super(e,i,o,r),this.type="raster-dem",this.maxzoom=22,this._options=t.e({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),o=this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield p.getImage(o,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const o=i.data;this.map._refreshExpiredTiles&&(i.cacheControl||i.expires)&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const r=t.b(o)&&t.W()?o:yield this.readImageNow(o),a={type:this.type,uid:e.uid,source:this.id,rawImageData:r,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!e.actor||"expired"===e.state){e.actor=this.dispatcher.getActor();const t=yield e.actor.sendAsync({type:"LDT",data:a});e.dem=t,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t._(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&t.X()){const i=e.width+2,o=e.height+2;try{return new t.R({width:i,height:o},yield t.Y(e,-1,-1,i,o))}catch(e){}}return s.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,o=Math.pow(2,i.z),r=(i.x-1+o)%o,a=0===i.x?e.wrap-1:e.wrap,s=(i.x+1+o)%o,n=i.x+1===o?e.wrap+1:e.wrap,l={};return l[new t.Z(e.overscaledZ,a,i.z,r,i.y).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y).key]={backfilled:!1},i.y>0&&(l[new t.Z(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y-1).key]={backfilled:!1}),i.y+1e.coordinates)).flat(1/0):e.coordinates.flat(1/0)}getBounds(){return t._(this,void 0,void 0,(function*(){const e=new G,t=yield this.getData();let i;switch(t.type){case "FeatureCollection":i=t.features.map((e=>this.getCoordinatesFromGeometry(e.geometry))).flat(1/0);break;case "Feature":i=this.getCoordinatesFromGeometry(t.geometry);break;default:i=this.getCoordinatesFromGeometry(t);}if(0==i.length)return e;for(let t=0;t0&&t.e(r,{resourceTiming:o}),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"metadata"}))),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"content"})));}catch(e){if(this._pendingLoads--,this._removed)return void this.fire(new t.l("dataabort",{dataType:"source"}));this.fire(new t.k(e));}}))}loaded(){return 0===this._pendingLoads}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity,globalState:this.map.getGlobalState()};e.abortController=new AbortController;const o=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(o,this.map.painter,"RT"===t);}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=!0;}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return !1}}class X extends t.E{constructor(e,t,i,o){super(),this.flippedWindingOrder=!1,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(o),this.options=t;}load(e){return t._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield p.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.a0.fromLngLat);var o;return this.tileID=function(e){const i=t.a1.fromPoints(e),o=i.width(),r=i.height(),a=Math.max(o,r),s=Math.max(0,Math.floor(-Math.log(a)/Math.LN2)),n=Math.pow(2,s);return new t.a3(s,Math.floor((i.minX+i.maxX)/2*n),Math.floor((i.minY+i.maxY)/2*n))}(i),this.terrainTileRanges=this._getOverlappingTileRanges(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((o=this.tileCoords)[1].x-o[0].x)*(o[2].y-o[0].y)-(o[1].y-o[0].y)*(o[2].x-o[0].x)<0,this.fire(new t.l("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new t.T(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t._(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return !1}_getOverlappingTileRanges(e){const{minX:i,minY:o,maxX:r,maxY:a}=t.a1.fromPoints(e),s={};for(let e=0;e<=t.a2;e++){const t=Math.pow(2,e),n=Math.floor(i*t),l=Math.floor(o*t),c=Math.floor(r*t),h=Math.floor(a*t);s[e]={minTileX:n,minTileY:l,maxTileX:c,maxTileY:h};}return s}}class K extends X{constructor(e,t,i,o){super(e,t,i,o),this.roundZoom=!0,this.type="video",this.options=t;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!1;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,"Source").url);try{const e=yield t.a4(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.k(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.k(new t.a5(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.T(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class Y extends X{constructor(e,i,o,r){super(e,i,o,r),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.k(new t.a5(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.k(new t.a5(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.k(new t.a5(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.k(new t.a5(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.k(new t.a5(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.k(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,o=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.T(i,this.canvas,o.RGBA,{premultiply:!0});let r=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=!0);}r&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return !0;return !1}}const Q={},J=e=>{switch(e){case "geojson":return H;case "image":return X;case "raster":return q;case "raster-dem":return W;case "vector":return $;case "video":return K;case "canvas":return Y}return Q[e]},ee="RTLPluginLoaded";class te extends t.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=B();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t._(this,arguments,void 0,(function*(e,t=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=s.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.l(ee));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let ie=null;function oe(){return ie||(ie=new te),ie}class re{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=e,this.uid=t.a6(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(e){const t=e+this.timeAdded;tt.getLayer(e))).filter(Boolean);if(0!==e.length){o.layers=e,o.stateDependentLayerIds&&(o.stateDependentLayers=o.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=o;}}return i}(e.buckets,null==i?void 0:i.style),this.hasSymbolBuckets=!1;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a8){if(this.hasSymbolBuckets=!0,!o)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a8&&i.hasRTLText){this.hasRTLText=!0,oe().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.a7;}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const i=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new t.T(e,this.imageAtlas.image,i.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new t.T(e,this.glyphAtlasImage,i.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,o,r,a,s,n,l,c,h){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:o,cameraQueryGeometry:r,scale:a,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:s,queryPadding:this.queryPadding*l,getElevation:h},e,t,i):{}}querySourceFeatures(e,i){const o=this.latestFeatureIndex;if(!o||!o.rawTileData)return;const r=o.loadVTLayers(),a=i&&i.sourceLayer?i.sourceLayer:"",s=r._geojsonTileLayer||r[a];if(!s)return;const n=t.a9(i&&i.filter),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=!1;else if(i)if(this.expirationTime{this.remove(e,r);}),i)),this.data[o].push(r),this.order.push(o),this.order.length>this.max){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}has(e){return e.wrapped().key in this.data}getAndRemove(e){return this.has(e)?this._getAndRemoveByKey(e.wrapped().key):null}_getAndRemoveByKey(e){const t=this.data[e].shift();return t.timeout&&clearTimeout(t.timeout),0===this.data[e].length&&delete this.data[e],this.order.splice(this.order.indexOf(e),1),t.value}getByKey(e){const t=this.data[e];return t?t[0].value:null}get(e){return this.has(e)?this.data[e.wrapped().key][0].value:null}remove(e,t){if(!this.has(e))return this;const i=e.wrapped().key,o=void 0===t?0:this.data[i].indexOf(t),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(e){for(this.max=e;this.order.length>this.max;){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}filter(e){const t=[];for(const i in this.data)for(const o of this.data[i])e(o.value)||t.push(o);for(const e of t)this.remove(e.value.tileID,e);}}class se{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(e,i,o){const r=String(i);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][r]=this.stateChanges[e][r]||{},t.e(this.stateChanges[e][r],o),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==r&&(this.deletedStates[e][t]=null);}else if(this.deletedStates[e]&&null===this.deletedStates[e][r]){this.deletedStates[e][r]={};for(const t in this.state[e][r])o[t]||(this.deletedStates[e][r][t]=null);}else for(const t in o)this.deletedStates[e]&&this.deletedStates[e][r]&&null===this.deletedStates[e][r][t]&&delete this.deletedStates[e][r][t];}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const o=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&void 0!==t)null!==this.deletedStates[e][o]&&(this.deletedStates[e][o]=this.deletedStates[e][o]||{},this.deletedStates[e][o][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][o])for(i in this.deletedStates[e][o]={},this.stateChanges[e][o])this.deletedStates[e][o][i]=null;else this.deletedStates[e][o]=null;else this.deletedStates[e]=null;}getState(e,i){const o=String(i),r=t.e({},(this.state[e]||{})[o],(this.stateChanges[e]||{})[o]);if(null===this.deletedStates[e])return {};if(this.deletedStates[e]){const t=this.deletedStates[e][i];if(null===t)return {};for(const e in t)delete r[e];}return r}initializeTileState(e,t){e.setFeatureState(this.state,t);}coalesceChanges(e,i){const o={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const i={};for(const o in this.stateChanges[e])this.state[e][o]||(this.state[e][o]={}),t.e(this.state[e][o],this.stateChanges[e][o]),i[o]=this.state[e][o];o[e]=i;}for(const e in this.deletedStates){this.state[e]=this.state[e]||{};const i={};if(null===this.deletedStates[e])for(const t in this.state[e])i[t]={},this.state[e][t]={};else for(const t in this.deletedStates[e]){if(null===this.deletedStates[e][t])this.state[e][t]={};else for(const i of Object.keys(this.deletedStates[e][t]))delete this.state[e][t][i];i[t]=this.state[e][t];}o[e]=o[e]||{},t.e(o[e],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(o).length)for(const t in e)e[t].setFeatureState(o,i);}}const ne=89.25;function le(e,i){const o=t.ag(i.lat,-85.051129,t.ah);return new t.P(t.V(i.lng)*e,t.U(o)*e)}function ce(e,i){return new t.a0(i.x/e,i.y/e).toLngLat()}function he(e){return e.cameraToCenterDistance*Math.min(.85*Math.tan(t.ad(90-e.pitch)),Math.tan(t.ad(ne-e.pitch)))}function ue(e,i){const o=e.canonical,r=i/t.ae(o.z),a=o.x+Math.pow(2,o.z)*e.wrap,s=t.af(new Float64Array(16));return t.M(s,s,[a*r,o.y*r,0]),t.N(s,s,[r/t.$,r/t.$,1]),s}function de(e,i,o,r,a){const s=t.a0.fromLngLat(e,i),n=a*t.ai(1,e.lat),l=n*Math.cos(t.ad(o)),c=Math.sqrt(n*n-l*l),h=c*Math.sin(t.ad(-r)),u=c*Math.cos(t.ad(-r));return new t.a0(s.x+h,s.y+u,s.z+l)}function _e(e,t,i){const o=t.intersectsFrustum(e);if(!i||0===o)return o;const r=t.intersectsPlane(i);return 0===r?0:2===o&&2===r?2:1}function pe(e,t,i){let o=0;const r=(i-t)/10;for(let a=0;a<10;a++)o+=r*Math.pow(Math.cos(t+(a+.5)/10*(i-t)),e);return o}function me(e,i){return function(o,r,a,s,n){const l=2*((e-1)/t.aj(Math.cos(t.ad(ne-n))/Math.cos(t.ad(ne)))-1),c=Math.acos(a/s),h=2*pe(l-1,0,t.ad(n/2)),u=Math.min(t.ad(ne),c+t.ad(n/2)),d=pe(l-1,Math.min(u,c-t.ad(n/2)),u),_=Math.atan(r/a),p=Math.hypot(r,a);let m=o;return m+=t.aj(s/p/Math.max(.5,Math.cos(t.ad(n/2)))),m+=l*t.aj(Math.cos(_))/2,m-=t.aj(Math.max(1,d/h/i))/2,m}}const fe=me(9.314,3);function ge(e,i){const o=(i.roundZoom?Math.round:Math.floor)(e.zoom+t.aj(e.tileSize/i.tileSize));return Math.max(0,o)}function ve(e,i){const o=e.getCameraFrustum(),r=e.getClippingPlane(),a=e.screenPointToMercatorCoordinate(e.getCameraPoint()),s=t.a0.fromLngLat(e.center,e.elevation);a.z=s.z+Math.cos(e.pitchInRadians)*e.cameraToCenterDistance/e.worldSize;const n=e.getCoveringTilesDetailsProvider(),l=n.allowVariableZoom(e,i),c=ge(e,i),h=i.minzoom||0,u=void 0!==i.maxzoom?i.maxzoom:e.maxZoom,d=Math.min(Math.max(0,c),u),_=Math.pow(2,d),p=[_*a.x,_*a.y,0],m=[_*s.x,_*s.y,0],f=Math.hypot(s.x-a.x,s.y-a.y),g=Math.abs(s.z-a.z),v=Math.hypot(f,g),b=e=>({zoom:0,x:0,y:0,wrap:e,fullyVisible:!1}),x=[],y=[];if(e.renderWorldCopies&&n.allowWorldCopies())for(let e=1;e<=3;e++)x.push(b(-e)),x.push(b(e));for(x.push(b(0));x.length>0;){const _=x.pop(),f=_.x,b=_.y;let w=_.fullyVisible;const T={x:f,y:b,z:_.zoom},P=n.getTileBoundingVolume(T,_.wrap,e.elevation,i);if(!w){const e=_e(o,P,r);if(0===e)continue;w=2===e;}const C=n.distanceToTile2d(a.x,a.y,T,P);let I=c;l&&(I=(i.calculateTileZoom||fe)(e.zoom+t.aj(e.tileSize/i.tileSize),C,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const M=Math.min(I,u);if(_.wrap=n.getWrap(s,T,_.wrap),_.zoom>=M){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return y.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}const be=t.a1.fromPoints([new t.P(0,0),new t.P(t.$,t.$)]);class xe extends t.E{constructor(e,t,i){super(),this.id=e,this.dispatcher=i,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=!1;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,o)=>{const r=new(J(t.type))(e,t,i,o);if(r.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${r.id}`);return r})(e,t,i,this),this._tiles={},this._cache=new ae(0,(e=>this._unloadTile(e))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new se,this._didEmitContent=!1,this._updated=!1;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e);}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return !0;if(!this._updated)return !1;for(const e in this._tiles){const t=this._tiles[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}return !0}getSource(){return this._source}pause(){this._paused=!0;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,o){return t._(this,void 0,void 0,(function*(){try{yield this._source.loadTile(e),this._tileLoaded(e,i,o);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.k(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.l("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const t in this._tiles){const i=this._tiles[t];i.upload(e),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(ye).map((e=>e.key))}getRenderableIds(e){const i=[];for(const t in this._tiles)this._isIdRenderable(t,e)&&i.push(this._tiles[t]);return e?i.sort(((e,i)=>{const o=e.tileID,r=i.tileID,a=new t.P(o.canonical.x,o.canonical.y)._rotate(-this.transform.bearingInRadians),s=new t.P(r.canonical.x,r.canonical.y)._rotate(-this.transform.bearingInRadians);return o.overscaledZ-r.overscaledZ||s.y-a.y||s.x-a.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(ye).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return !!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())}reload(e){if(this._paused)this._shouldReloadOnResume=!0;else {this._cache.reset();for(const t in this._tiles)e?this._reloadTile(t,"expired"):"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading");}}_reloadTile(e,i){return t._(this,void 0,void 0,(function*(){const t=this._tiles[e];t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,o){e.timeAdded=s.now(),"expired"===o&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.l("data",{dataType:"source",tile:e,coord:e.tileID}));}_backfillDEM(e){const t=this.getRenderableIds();for(let o=0;o1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,o),e.neighboringTiles&&e.neighboringTiles[a]&&(e.neighboringTiles[a].backfilled=!0)));}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,o){for(const r in this._tiles){let a=this._tiles[r];if(o[r]||!a.hasData()||a.tileID.overscaledZ<=t||a.tileID.overscaledZ>i)continue;let s=a.tileID;for(;a&&a.tileID.overscaledZ>t+1;){const e=a.tileID.scaledTo(a.tileID.overscaledZ-1);a=this._tiles[e.key],a&&a.hasData()&&(s=e);}let n=s;for(;n.overscaledZ>t;)if(n=n.scaledTo(n.overscaledZ-1),e[n.key]||e[n.canonical.key]){o[s.key]=s;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),o=this._getLoadedTile(t);if(o)return o}}findLoadedSibling(e){return this._getLoadedTile(e)}_getLoadedTile(e){const t=this._tiles[e.key];return t&&t.hasData()?t:this._cache.getByKey(e.wrapped().key)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,o=Math.ceil(e.height/this._source.tileSize)+1,r=Math.floor(i*o*(null===this._maxTileCacheZoomLevels?t.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),a="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(a);}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e={};for(const i in this._tiles){const o=this._tiles[i];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),e[o.tileID.key]=o;}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(e,this._tiles[e]);}}_updateCoveredAndRetainedTiles(e,t,i,o,r,a){const n={},l={},c=Object.keys(e),h=s.now();for(const i of c){const o=e[i],r=this._tiles[i];if(!r||0!==r.fadeEndTime&&r.fadeEndTime<=h)continue;const a=this.findLoadedParent(o,t),s=this.findLoadedSibling(o),c=a||s||null;c&&(this._addTile(c.tileID),n[c.tileID.key]=c.tileID),l[i]=o;}this._retainLoadedChildren(l,o,i,e);for(const t in n)e[t]||(this._coveredTiles[t]=!0,e[t]=n[t]);if(a){const t={},i={};for(const e of r)this._tiles[e.key].hasData()?t[e.key]=e:i[e.key]=e;for(const o in i){const r=i[o].children(this._source.maxzoom);this._tiles[r[0].key]&&this._tiles[r[1].key]&&this._tiles[r[2].key]&&this._tiles[r[3].key]&&(t[r[0].key]=e[r[0].key]=r[0],t[r[1].key]=e[r[1].key]=r[1],t[r[2].key]=e[r[2].key]=r[2],t[r[3].key]=e[r[3].key]=r[3],delete i[o]);}for(const o in i){const r=i[o],a=this.findLoadedParent(r,this._source.minzoom),s=this.findLoadedSibling(r),n=a||s||null;if(n){t[n.tileID.key]=e[n.tileID.key]=n.tileID;for(const e in t)t[e].isChildOf(n.tileID)&&delete t[e];}}for(const e in this._tiles)t[e]||(this._coveredTiles[e]=!0);}}update(e,i){if(!this._sourceLoaded||this._paused)return;let o;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?o=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.Z(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(o=ve(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(o=o.filter((e=>this._source.hasTile(e))))):o=[];const r=ge(e,this._source),a=Math.max(r-xe.maxOverzooming,this._source.minzoom),s=Math.max(r+xe.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const e={};for(const t of o)if(t.canonical.z>this._source.minzoom){const i=t.scaledTo(t.canonical.z-1);e[i.key]=i;const o=t.scaledTo(Math.max(this._source.minzoom,Math.min(t.canonical.z,5)));e[o.key]=o;}o=o.concat(Object.values(e));}const n=0===o.length&&!this._updated&&this._didEmitContent;this._updated=!0,n&&this.fire(new t.l("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(o,r);we(this._source.type)&&this._updateCoveredAndRetainedTiles(l,a,s,r,o,i);for(const e in l)this._tiles[e].clearFadeHold();const c=t.al(this._tiles,l);for(const e of c){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const o={},r={},a=Math.max(t-xe.maxOverzooming,this._source.minzoom),s=Math.max(t+xe.maxUnderzooming,this._source.minzoom),n={};for(const i of e){const e=this._addTile(i);o[i.key]=i,e.hasData()||tthis._source.maxzoom){const e=s.children(this._source.maxzoom)[0],t=this.getTile(e);if(t&&t.hasData()){o[e.key]=e;continue}}else {const e=s.children(this._source.maxzoom);if(o[e[0].key]&&o[e[1].key]&&o[e[2].key]&&o[e[3].key])continue}let n=e.wasRequested();for(let t=s.overscaledZ-1;t>=a;--t){const a=s.scaledTo(t);if(r[a.key])break;if(r[a.key]=!0,e=this.getTile(a),!e&&n&&(e=this._addTile(a)),e){const t=e.hasData();if((t||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||n)&&(o[a.key]=a),n=e.wasRequested(),t)break}}}return o}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,o=this._tiles[e].tileID;for(;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}t.push(o.key);const e=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;o=e;}for(const e of t)this._loadedParentTiles[e]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const e in this._tiles){const t=this._tiles[e].tileID,i=this._getLoadedTile(t);this._loadedSiblingTiles[t.key]=i;}}_addTile(e){let i=this._tiles[e.key];if(i)return i;i=this._cache.getAndRemove(e),i&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));const o=i;return i||(i=new re(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._tiles[e.key]=i,o||this._source.fire(new t.l("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}refreshTiles(e){for(const t in this._tiles)(this._isIdRenderable(t)||"errored"==this._tiles[t].state)&&e.some((e=>e.equals(this._tiles[t].tileID.canonical)))&&this._reloadTile(t,"expired");}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=!0,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){const t=e.sourceDataType;"source"===e.dataType&&"metadata"===t&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===t&&(this.reload(e.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0);}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e in this._tiles)this._removeTile(e);this._cache.reset();}tilesIn(e,i,o){const r=[],a=this.transform;if(!a)return r;const s=a.getCoveringTilesDetailsProvider().allowWorldCopies(),n=o?a.getCameraQueryGeometry(e):e,l=e=>a.screenPointToMercatorCoordinate(e,this.terrain),c=this.transformBbox(e,l,!s),h=this.transformBbox(n,l,!s),u=this.getIds(),d=t.a1.fromPoints(h);for(let e=0;ee.getTilePoint(new t.a0(i.x,i.y))));if(i.expandBy(_),i.intersects(be)){const t=c.map((t=>e.getTilePoint(t))),i=h.map((t=>e.getTilePoint(t)));r.push({tile:o,tileID:s?e:e.unwrapTo(0),queryGeometry:t,cameraQueryGeometry:i,scale:l});}}}return r}transformBbox(e,i,o){let r=e.map(i);if(o){const o=t.a1.fromPoints(e);o.shrinkBy(.001*Math.min(o.width(),o.height()));const a=o.map(i);t.a1.fromPoints(r).covers(a)||(r=r.map((e=>e.x>.5?new t.a0(e.x-1,e.y,e.z):e)));}return r}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._tiles[e].tileID));return this.transform&&this.transform.populateCache(t),t}hasTransition(){if(this._source.hasTransition())return !0;if(we(this._source.type)){const e=s.now();for(const t in this._tiles)if(this._tiles[t].fadeEndTime>=e)return !0}return !1}setFeatureState(e,t,i){this._state.updateState(e=e||"_geojsonTileLayer",t,i);}removeFeatureState(e,t,i){this._state.removeFeatureState(e=e||"_geojsonTileLayer",t,i);}getFeatureState(e,t){return this._state.getState(e=e||"_geojsonTileLayer",t)}setDependencies(e,t,i){const o=this._tiles[e];o&&o.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)));}}function ye(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),o=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||o-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function we(e){return "raster"===e||"image"===e||"video"===e}xe.maxOverzooming=10,xe.maxUnderzooming=3;class Te{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(r-s)/n:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))}}function Pe(e,t){let i=!0;return "always"===e||"never"!==e&&"never"!==t||(i=!1),i}class Ce{constructor(e,t,i){const o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||o<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=o){if(r)return [{key:null,x1:e,y1:t,x2:i,y2:o}];for(let e=0;e0}hitTestCircle(e,t,i,o,r){const a=e-i,s=e+i,n=t-i,l=t+i;if(s<0||a>this.width||l<0||n>this.height)return !1;const c=[];return this._forEachCell(a,n,s,l,this._queryCellCircle,c,{hitTest:!0,overlapMode:o,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},r),c.length>0}_queryCell(e,t,i,o,r,a,s,n){const{seenUids:l,hitTest:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const r=this.bboxes;for(const s of u)if(!l.box[s]){l.box[s]=!0;const u=4*s,d=this.boxKeys[s];if(e<=r[u+2]&&t<=r[u+3]&&i>=r[u+0]&&o>=r[u+1]&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))&&(a.push({key:d,x1:r[u],y1:r[u+1],x2:r[u+2],y2:r[u+3]}),c))return !0}}const d=this.circleCells[r];if(null!==d){const r=this.circles;for(const s of d)if(!l.circle[s]){l.circle[s]=!0;const u=3*s,d=this.circleKeys[s];if(this._circleAndRectCollide(r[u],r[u+1],r[u+2],e,t,i,o)&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))){const e=r[u],t=r[u+1],i=r[u+2];if(a.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return !0}}}return !1}_queryCellCircle(e,t,i,o,r,a,s,n){const{circle:l,seenUids:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=!0;const i=4*t,o=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}const d=this.circleCells[r];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=!0;const i=3*t,o=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}}_forEachCell(e,t,i,o,r,a,s,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(o);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(r.call(this,e,t,i,o,this.xCellCount*l+d,a,s,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,o,r,a){const s=o-e,n=r-t,l=i+a;return l*l>s*s+n*n}_circleAndRectCollide(e,t,i,o,r,a,s){const n=(a-o)/2,l=Math.abs(e-(o+n));if(l>n+i)return !1;const c=(s-r)/2,h=Math.abs(t-(r+c));if(h>c+i)return !1;if(l<=n||h<=c)return !0;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function Ie(e,i,r){const a=t.L();if(!e){const{vecSouth:e,vecEast:t}=Se(i),r=o();r[0]=t[0],r[1]=t[1],r[2]=e[0],r[3]=e[1],s=r,(d=(l=(n=r)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(s[0]=u*(d=1/d),s[1]=-c*d,s[2]=-h*d,s[3]=l*d),a[0]=r[0],a[1]=r[1],a[4]=r[2],a[5]=r[3];}var s,n,l,c,h,u,d;return t.N(a,a,[1/r,1/r,1]),a}function Me(e,i,o,r){if(e){const e=t.L();if(!i){const{vecSouth:t,vecEast:i}=Se(o);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.N(e,e,[r,r,1]),e}return o.pixelsToClipSpaceMatrix}function Se(e){const i=Math.cos(e.rollInRadians),o=Math.sin(e.rollInRadians),r=Math.cos(e.pitchInRadians),a=Math.cos(e.bearingInRadians),s=Math.sin(e.bearingInRadians),n=t.aq();n[0]=-a*r*o-s*i,n[1]=-s*r*o+a*i;const l=t.ar(n);l<1e-9?t.as(n):t.at(n,n,1/l);const c=t.aq();c[0]=a*r*i-s*o,c[1]=s*r*i+a*o;const h=t.ar(c);return h<1e-9?t.as(c):t.at(c,c,1/h),{vecEast:c,vecSouth:n}}function Ee(e,i,o,r){let a;r?(a=[e,i,r(e,i),1],t.av(a,a,o)):(a=[e,i,0,1],qe(a,a,o));const s=a[3];return {point:new t.P(a[0]/s,a[1]/s),signedDistanceFromCamera:s,isOccluded:!1}}function Re(e,t){return .5+e/t*.5}function ze(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function De(e,i,o,r,a,s,n,l,c,h,u,d,_){const p=o?e.textSizeData:e.iconSizeData,m=t.am(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=o?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,b=o?e.text.placedSymbolArray:e.icon.placedSymbolArray,x=i.transform.width/i.transform.height;let y=!1;for(let o=0;oMath.abs(o.x-i.x)*r?{useVertical:!0}:(e===t.an.vertical?i.yo.x)?{needsFlipping:!0}:null}function ke(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:o,symbol:r,fontSize:a,flip:s,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=a/24,_=r.lineOffsetX*d,p=r.lineOffsetY*d;let m;if(r.numGlyphs>1){const e=r.glyphStartIndex+r.numGlyphs,t=r.lineStartIndex,a=r.lineStartIndex+r.lineLength,c=Ae(d,l,_,p,s,r,u,i);if(!c)return {notEnoughRoom:!0};const f=je(c.first.point.x,c.first.point.y,i,o),g=je(c.last.point.x,c.last.point.y,i,o);if(n&&!s){const e=Le(r.writingMode,f,g,h);if(e)return e}m=[c.first];for(let o=r.glyphStartIndex+1;o0?n.point:Fe(i.tileAnchorPoint,s,e,1,i),c=je(e.x,e.y,i,o),u=je(l.x,l.y,i,o),d=Le(r.writingMode,c,u,h);if(d)return d}const e=Ge(d*l.getoffsetX(r.glyphStartIndex),_,p,s,r.segment,r.lineStartIndex,r.lineStartIndex+r.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:!0};m=[e];}for(const e of m)t.au(c,e.point,e.angle);return {}}function Fe(e,t,i,o,r){const a=e.add(e.sub(t)._unit()),s=Oe(a.x,a.y,r).point,n=i.sub(s);return i.add(n._mult(o/n.mag()))}function Be(e,i,o){const r=i.projectionCache;if(r.projections[e])return r.projections[e];const a=new t.P(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),s=Oe(a.x,a.y,i);if(s.signedDistanceFromCamera>0)return r.projections[e]=s.point,r.anyProjectionOccluded=r.anyProjectionOccluded||s.isOccluded,s.point;const n=e-o.direction;return Fe(0===o.distanceFromAnchor?i.tileAnchorPoint:new t.P(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),a,o.previousVertex,o.absOffsetX-o.distanceFromAnchor+1,i)}function Oe(e,t,i){const o=e+i.translation[0],r=t+i.translation[1];let a;return i.pitchWithMap?(a=Ee(o,r,i.pitchedLabelPlaneMatrix,i.getElevation),a.isOccluded=!1):(a=i.transform.projectTileCoordinates(o,r,i.unwrappedTileID,i.getElevation),a.point.x=(.5*a.point.x+.5)*i.width,a.point.y=(.5*-a.point.y+.5)*i.height),a}function je(e,i,o,r){if(o.pitchWithMap){const a=[e,i,0,1];return t.av(a,a,r),o.transform.projectTileCoordinates(a[0]/a[3],a[1]/a[3],o.unwrappedTileID,o.getElevation).point}return {x:e/o.width*2-1,y:i/o.height*2-1}}function Ne(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function Ze(e,t,i){return e._unit()._perp()._mult(t*i)}function Ue(e,i,o,r,a,s,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=o.add(i);if(e+c.direction=a)return l.projectionCache.offsets[e]=h,h;const u=Be(e+c.direction,l,c),d=Ze(u.sub(o),n,c.direction),_=o.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.aw(s,h,_,p)||h,l.projectionCache.offsets[e]}function Ge(e,t,i,o,r,a,s,n,l){const c=o?e-t:e+t;let h=c>0?1:-1,u=0;o&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?a+r:a+r+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Oe(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,b=0;const x=Math.abs(c),y=[];let w;for(;v+b<=x;){if(_+=h,_=s)return null;v+=b,g=f,m=p;const e={absOffsetX:x,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=Be(_,n,e),0===i)y.push(g),w=f.sub(g);else {let t;const o=f.sub(g);t=0===o.mag()?Ze(Be(_+h,n,e).sub(f),i,h):Ze(o,i,h),m||(m=g.add(t)),p=Ue(_,t,f,a,s,m,i,n,e),y.push(m),w=p.sub(m);}b=w.mag();}const T=w._mult((x-v)/b)._add(m||g),P=u+Math.atan2(f.y-g.y,f.x-g.x);return y.push(T),{point:T,angle:l?P:0,path:y}}const Ve=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function $e(e,t){for(let i=0;i=1;e--)_.push(s.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=o.x&&i.x<=r.x&&e.y>=o.y&&i.y<=r.y?[_]:i.xr.x||i.yr.y?[]:t.ax([_],o.x,o.y,r.x,r.y);}for(const t of f){a.reset(t,.25*i);let o=0;o=a.length<=.5*i?1:Math.ceil(a.paddedLength/p)+1;for(let t=0;t{const t=Ee(e.x,e.y,o,i.getElevation),r=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return r.point.x=(.5*r.point.x+.5)*i.width,r.point.y=(.5*-r.point.y+.5)*i.height,r}))}(e,i);return function(e){let t=0,i=0,o=0,r=0;for(let a=0;ai&&(i=r,t=o));return e.slice(t,t+i)}(o)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[],o=new t.a1;for(const r of e){const e=new t.P(r.x+We,r.y+We);o.extend(e),i.push(e);}const{minX:r,minY:a,maxX:s,maxY:n}=o,l=this.grid.query(r,a,s,n).concat(this.ignoredGrid.query(r,a,s,n)),c={},h={};for(const e of l){const o=e.key;if(void 0===c[o.bucketInstanceId]&&(c[o.bucketInstanceId]={}),c[o.bucketInstanceId][o.featureIndex])continue;const r=[new t.P(e.x1,e.y1),new t.P(e.x2,e.y1),new t.P(e.x2,e.y2),new t.P(e.x1,e.y2)];t.ay(i,r)&&(c[o.bucketInstanceId][o.featureIndex]=!0,void 0===h[o.bucketInstanceId]&&(h[o.bucketInstanceId]=[]),h[o.bucketInstanceId].push(o.featureIndex));}return h}insertCollisionBox(e,t,i,o,r,a){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,o,r,a){const s=i?this.ignoredGrid:this.grid,n={bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t};for(let t=0;t=this.screenRightBoundary||othis.screenBottomBoundary}isInsideGrid(e,t,i,o){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,r,c,u)));E=e.some((e=>!e.isOccluded)),S=e.map((e=>new t.P(e.x,e.y)));}else E=!0;return {box:t.az(S),allPointsOccluded:!E}}}class Xe{constructor(e,t,i,o){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):o&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class Ke{constructor(e,t,i,o,r){this.text=new Xe(e?e.text:null,t,i,r),this.icon=new Xe(e?e.icon:null,t,o,r);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ye{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class Qe{constructor(e,t,i,o,r){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=r;}}class Je{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function et(e,i,o,r,a){const{horizontalAlign:s,verticalAlign:n}=t.aG(e);return new t.P(-(s-.5)*i+r[0]*a,-(n-.5)*o+r[1]*a)}class tt{constructor(e,t,i,o,r){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new He(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new Je(o),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=r,r&&(r.prevPlacement=void 0),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,o)=>t.getElevation(e,i,o):null}getBucketParts(e,i,o,r){const a=o.getBucket(i),s=o.latestFeatureIndex;if(!a||!s||i.id!==a.layerIds[0])return;const n=o.collisionBoxArray,l=a.layers[0].layout,c=a.layers[0].paint,h=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),u=o.tileSize/t.$,d=o.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.aB(o,1,this.transform.zoom),m=t.aC(this.collisionIndex.transform,o,c.get("text-translate"),c.get("text-translate-anchor")),f=t.aC(this.collisionIndex.transform,o,c.get("icon-translate"),c.get("icon-translate-anchor")),g=Ie(_,this.transform,p);this.retainedQueryData[a.bucketInstanceId]=new Qe(a.bucketInstanceId,s,a.sourceLayerIndex,a.index,o.tileID);const v={bucket:a,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:o.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.am(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(r)for(const t of a.sortKeyRanges){const{sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r}=t;e.push({sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v,b,x){const y=t.aD[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=et(y,o,r,w,a),P=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,s,f,u.predicate,b,T,x);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,s,g,u.predicate,b,T,x).placeable)&&P.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:o,height:r,anchor:y,textBoxScale:a,prevAnchor:e},this.markUsedJustification(p,y,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:P}}}placeLayerBucketPart(e,i,o){const{bucket:r,layout:a,translationText:s,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=a.get("text-optional"),f=a.get("icon-optional"),g=t.aE(a,"text-overlap","text-allow-overlap"),v="always"===g,b=t.aE(a,"icon-overlap","icon-allow-overlap"),x="always"===b,y="map"===a.get("text-rotation-alignment"),w="map"===a.get("text-pitch-alignment"),T="none"!==a.get("icon-text-fit"),P="viewport-y"===a.get("symbol-z-order"),C=v&&(x||!r.hasIconData()||f),I=x&&(v||!r.hasTextData()||m);!r.collisionArrays&&d&&r.deserializeCollisionBoxes(d);const M=this.retainedQueryData[r.bucketInstanceId].tileID,S=this._getTerrainElevationFunc(M),E=this.transform.getFastPathSimpleProjectionMatrix(M),R=(e,d,x)=>{var P,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new Ye(!1,!1,!1));let z=!1,D=!1,A=!0,L=null,k={box:null,placeable:!1,offscreen:null,occluded:!1},F={placeable:!1},B=null,O=null,j=null,N=0,Z=0,U=0;d.textFeatureIndex?N=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(N=e.featureIndex),d.verticalTextFeatureIndex&&(Z=d.verticalTextFeatureIndex);const G=d.textBox;if(G){const i=i=>{let o=t.an.horizontal;if(r.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,o=t,this.markUsedOrientation(r,o,e));}return o},a=(i,o)=>{if(r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of r.writingModes)if(e===t.an.vertical?(k=o(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const o=(t,i)=>{const o=this.collisionIndex.placeCollisionBox(t,g,h,M,l,w,y,s,p.predicate,S,void 0,E);return o&&o.placeable&&(this.markUsedOrientation(r,i,e),this.placedOrientations[e.crossTileID]=i),o};a((()=>o(G,t.an.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?o(i,t.an.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.aD[null===(R=null===(P=this.prevPlacement)||void 0===P?void 0:P.variableOffsets[e.crossTileID])||void 0===R?void 0:R.anchor];const m=(t,i,a)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===b?i:null;let x=null,P="never"===g?1:2,C="never";_&&P++;for(let i=0;im(G,d.iconBox,t.an.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.an.vertical):{box:null,occluded:!0,offscreen:null}})),k&&(z=k.placeable,A=k.offscreen);const f=i(k&&k.placeable);if(!z&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(r,t.anchor,e,f));}}}if(B=k,z=B&&B.placeable,A=B&&B.offscreen,e.useRuntimeCollisionCircles){const i=r.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.ao(r.textSizeData,_,i),h=a.get("text-padding");O=this.collisionIndex.placeCollisionCircles(g,i,r.lineVertexArray,r.glyphOffsetArray,n,l,c,o,w,p.predicate,e.collisionCircleDiameter,h,s,S),O.circles.length&&O.collisionDetected&&!o&&t.w("Collisions detected, but collision boxes are not shown"),z=v||O.circles.length>0&&!O.collisionDetected,A=A&&O.offscreen;}if(d.iconFeatureIndex&&(U=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,b,h,M,l,w,y,n,p.predicate,S,T&&L?L:void 0,E);F&&F.placeable&&d.verticalIconBox?(j=e(d.verticalIconBox),D=j.placeable):(j=e(d.iconBox),D=j.placeable),A=A&&j.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,$=f||0===e.numIconVertices;V||$?$?V||(D=D&&z):z=D&&z:D=z=D&&z;const q=D&&j.placeable;if(z&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,a.get("text-ignore-placement"),r.bucketInstanceId,F&&F.placeable&&Z?Z:N,p.ID),q&&this.collisionIndex.insertCollisionBox(j.box,b,a.get("icon-ignore-placement"),r.bucketInstanceId,U,p.ID),O&&z&&this.collisionIndex.insertCollisionCircles(O.circles,g,a.get("text-ignore-placement"),r.bucketInstanceId,N,p.ID),o&&this.storeCollisionData(r.bucketInstanceId,x,d,B,j,O),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===r.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new Ye((z||C)&&!(null==B?void 0:B.occluded),(D||I)&&!(null==j?void 0:j.occluded),A||r.justReloaded),i[e.crossTileID]=!0;};if(P){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=r.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(r.symbolInstances.get(i),r.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=a>=0&&t!==a?0:o.crossTileID);}markUsedOrientation(e,i,o){const r=i===t.an.horizontal||i===t.an.horizontalOnly?i:0,a=i===t.an.vertical?i:0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];for(const t of s)e.text.placedSymbolArray.get(t).placedOrientation=r;o.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).placedOrientation=a);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=!1;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const o=t?t.symbolFadeChange(e):1,r=t?t.opacities:{},a=t?t.variableOffsets:{},s=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],a=r[e];a?(this.opacities[e]=new Ke(a,o,t.text,t.icon),i=i||t.text!==a.text.placed||t.icon!==a.icon.placed):(this.opacities[e]=new Ke(null,o,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in r){const t=r[e];if(!this.opacities[e]){const r=new Ke(t,o,!1,!1);r.isHidden()||(this.opacities[e]=r,i=i||t.text.placed||t.icon.placed);}}for(const e in a)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=a[e]);for(const e in s)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=s[e]);if(t&&void 0===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const o of t){const t=o.getBucket(e);t&&o.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,o.tileID,i,o.collisionBoxArray);}}updateBucketOpacities(e,i,o,r){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=!1),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=!1),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const a=e.layers[0],s=a.layout,n=new Ke(null,0,!1,!1,!0),l=s.get("text-allow-overlap"),c=s.get("icon-allow-overlap"),h=a._unevaluatedLayout.hasValue("text-variable-anchor")||a._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===s.get("text-rotation-alignment"),d="map"===s.get("text-pitch-alignment"),_="none"!==s.get("icon-text-fit"),p=new Ke(null,0,l&&(c||!e.hasIconData()||s.get("icon-optional")),c&&(l||!e.hasTextData()||s.get("text-optional")),!0);!e.collisionArrays&&r&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(r);const m=(e,t,i)=>{for(let o=0;o0,v=this.placedOrientations[r.crossTileID],b=v===t.an.vertical,x=v===t.an.horizontal||v===t.an.horizontalOnly;if(a>0||s>0){const t=ht(c.text);m(e.text,a,b?ut:t),m(e.text,s,x?ut:t);const i=c.text.isHidden();[r.rightJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||b?1:0);})),r.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).hidden=i||x?1:0);const o=this.variableOffsets[r.crossTileID];o&&this.markUsedJustification(e,o.anchor,r,v);const n=this.placedOrientations[r.crossTileID];n&&(this.markUsedJustification(e,"left",r,n),this.markUsedOrientation(e,n,r));}if(g){const t=ht(c.icon),i=!(_&&r.verticalPlacedIconSymbolIndex&&b);r.placedIconSymbolIndex>=0&&(m(e.icon,r.numIconVertices,i?t:ut),e.icon.placedSymbolArray.get(r.placedIconSymbolIndex).hidden=c.icon.isHidden()),r.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,r.numVerticalIconVertices,i?ut:t),e.icon.placedSymbolArray.get(r.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const y=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const o=e.collisionArrays[i];if(o){let i=new t.P(0,0);if(o.textBox||o.verticalTextBox){let t=!0;if(h){const e=this.variableOffsets[l];e?(i=et(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=!1;}if(o.textBox||o.verticalTextBox){let r;o.textBox&&(r=b),o.verticalTextBox&&(r=x),it(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||r,y.text,i.x,i.y);}}if(o.iconBox||o.verticalIconBox){const t=Boolean(!x&&o.verticalIconBox);let r;o.iconBox&&(r=t),o.verticalIconBox&&(r=!t),it(e.iconCollisionBox.collisionVertexArray,c.icon.placed,r,y.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=!0;}}function it(e,t,i,o,r,a){o&&0!==o.length||(o=[0,0,0,0]);const s=o[0]-We,n=o[1]-We,l=o[2]-We,c=o[3]-We;e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,c),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,c);}const ot=Math.pow(2,25),rt=Math.pow(2,24),at=Math.pow(2,17),st=Math.pow(2,16),nt=Math.pow(2,9),lt=Math.pow(2,8),ct=Math.pow(2,1);function ht(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*ot+t*rt+i*at+t*st+i*nt+t*lt+i*ct+t}const ut=0;class dt{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,o,r){const a=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&s.now()-o>2;for(;this._currentPlacementIndex>=0;){const o=t[e[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if("symbol"===o.type&&(!o.minzoom||o.minzoom<=a)&&(!o.maxzoom||o.maxzoom>a)){if(this._inProgressLayer||(this._inProgressLayer=new dt(o)),this._inProgressLayer.continuePlacement(i[o.source],this.placement,this._showCollisionBoxes,o,r))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(e){return this.placement.commit(e),this.placement}}const pt=512/t.$/2;class mt{constructor(e,i,o){this.tileID=e,this.bucketInstanceId=o,this._symbolsByKey={};const r=new Map;for(let e=0;e({x:Math.floor(e.anchorX*pt),y:Math.floor(e.anchorY*pt)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(o.positions.length>128){const e=new t.aH(o.positions.length,16,Uint16Array);for(const{x:t,y:i}of o.positions)e.add(t,i);e.finish(),delete o.positions,o.index=e;}this._symbolsByKey[e]=o;}}getScaledCoordinates(e,i){const{x:o,y:r,z:a}=this.tileID.canonical,{x:s,y:n,z:l}=i.canonical,c=pt/Math.pow(2,l-a),h=(n*t.$+e.anchorY)*c,u=r*t.$*pt;return {x:Math.floor((s*t.$+e.anchorX)*c-o*t.$*pt),y:Math.floor(h-u)}}findMatches(e,t,i){const o=this.tileID.canonical.ze))}}class ft{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class gt{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],o={};for(const e in i){const r=i[e];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+t),o[r.tileID.key]=r;}this.indexes[e]=o;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in r){const a=r[i];a.tileID.isChildOf(e)&&a.findMatches(t.symbolInstances,e,o);}else {const a=r[e.scaledTo(Number(i)).key];a&&a.findMatches(t.symbolInstances,e,o);}}for(let e=0;e{t[e]=!0;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var bt="void main() {fragColor=vec4(1.0);}";const xt={prelude:yt("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:yt("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:yt("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:yt("uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:yt("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:yt("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:yt(bt,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:yt("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:yt("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:yt("in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:yt("in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),colorRelief:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {float x=(float(stop)+0.5)/float(textureSize(u_elevation_stops,0)[0]);vec4 data=texture(u_elevation_stops,vec2(x,0))*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int num_elevation_stops=textureSize(u_elevation_stops,0)[0];int r=(num_elevation_stops-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else\n{l=m;el_l=el_m;}}float x=(float(l)+(el-el_l)/(el_r-el_l)+0.5)/float(textureSize(u_color_stops,0)[0]);fragColor=u_opacity*texture(u_color_stops,vec2(x,0));\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_dimension;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),debug:yt("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}","in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:yt(bt,"in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:yt("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:yt("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:yt("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:yt("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:yt("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {vec2 epsilon=1.0/u_dimension;float tileSize=u_dimension.x-2.0;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))*tileSize/pow(2.0,exaggeration+(28.2562-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+0.5,deriv.y/8.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:yt("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];\n#define PI 3.141592653589793\n#define STANDARD 0\n#define COMBINED 1\n#define IGOR 2\n#define MULTIDIRECTIONAL 3\n#define BASIC 4\nfloat get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);}void igor_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float aspect=get_aspect(deriv);float azimuth=u_azimuths[0]+PI;float slope_stength=atan(length(deriv))*2.0/PI;float aspect_strength=1.0-abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);float shadow_strength=slope_stength*aspect_strength;float highlight_strength=slope_stength*(1.0-aspect_strength);fragColor=u_shadows[0]*shadow_strength+u_highlights[0]*highlight_strength;}void standard_hillshade(vec2 deriv){float azimuth=u_azimuths[0]+PI;float slope=atan(0.625*length(deriv));float aspect=get_aspect(deriv);float intensity=u_exaggeration;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadows[0],u_highlights[0],shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;}void basic_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor=u_highlights[0]*(2.0*shade-1.0);}else\n{fragColor=u_shadows[0]*(1.0-2.0*shade);}}void multidirectional_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;fragColor=vec4(0,0,0,0);for(int i=0; i < NUM_ILLUMINATION_SOURCES; i++){float cos_alt=cos(u_altitudes[i]);float sin_alt=sin(u_altitudes[i]);float cos_az=-cos(u_azimuths[i]);float sin_az=-sin(u_azimuths[i]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor+=u_highlights[i]*(2.0*shade-1.0)/float(NUM_ILLUMINATION_SOURCES);}else\n{fragColor+=u_shadows[i]*(1.0-2.0*shade)/float(NUM_ILLUMINATION_SOURCES);}}}void combined_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=acos((sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv)));cang=clamp(cang,0.0,PI/2.0);float shade=cang*atan(length(deriv))*4.0/PI/PI;float highlight=(PI/2.0-cang)*atan(length(deriv))*4.0/PI/PI;fragColor=u_shadows[0]*shade+u_highlights[0]*highlight;}void main() {vec4 pixel=texture(u_image,v_pos);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));vec2 deriv=((pixel.rg*8.0)-4.0)/scaleFactor;switch(u_method){case BASIC:\nbasic_hillshade(deriv);break;case COMBINED:\ncombined_hillshade(deriv);break;case IGOR:\nigor_hillshade(deriv);break;case MULTIDIRECTIONAL:\nmultidirectional_hillshade(deriv);break;case STANDARD:\ndefault:\nstandard_hillshade(deriv);break;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:yt("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:yt("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0);vec4 color1=texture(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:yt("uniform sampler2D u_texture;in vec2 v_tex;in float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;fragColor=texture(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_tex;out float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:yt("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:yt("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;fragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:yt("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}","in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:yt("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}","in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:yt("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:yt("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:yt("in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}","in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:yt("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function yt(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o=t.match(/in ([\w]+) ([\w]+)/g),r=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=a?a.concat(r):r,n={};return {fragmentSource:e=e.replace(i,((e,t,i,o,r)=>(n[r]=!0,"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nin ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = u_${r};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,o,r)=>{const a="float"===o?"vec2":"vec4",s=r.match(/color/)?"color":a;return n[r]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\nout ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`})),staticAttributes:o,staticUniforms:s}}class wt{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var Tt=t.aI([{name:"a_pos",type:"Int16",components:2}]);const Pt="#define PROJECTION_MERCATOR",Ct="mercator";class It{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return !1}get shaderVariantName(){return Ct}get shaderDefine(){return Pt}get shaderPreludeCode(){return xt.projectionMercator}get vertexShaderPreludeCode(){return xt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.aJ.noSubdivision}get useGlobeControls(){return !1}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(e){}getMeshFromTileID(e,i,o,r,a){if(this._cachedMesh)return this._cachedMesh;const s=new t.aK;s.emplaceBack(0,0),s.emplaceBack(t.$,0),s.emplaceBack(0,t.$),s.emplaceBack(t.$,t.$);const n=e.createVertexBuffer(s,Tt.members),l=t.aL.simpleSegment(0,0,4,2),c=new t.aM;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new wt(n,h,l),this._cachedMesh}recalculate(){}hasTransition(){return !1}setErrorQueryLatitudeDegrees(e){}}class Mt{constructor(e=0,t=0,i=0,o=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=o;}interpolate(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.C.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.C.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.C.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.C.number(e.right,i.right,o)),this}getCenter(e,i){const o=t.ag((this.left+e-this.right)/2,0,e),r=t.ag((this.top+i-this.bottom)/2,0,i);return new t.P(o,r)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new Mt(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function St(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function Et(e){return Math.max(0,Math.floor(e))}class Rt{constructor(e,i,o,r,a,s){this._callbacks=e,this._tileSize=512,this._renderWorldCopies=void 0===s||!!s,this._minZoom=i||0,this._maxZoom=o||22,this._minPitch=null==r?0:r,this._maxPitch=null==a?60:a,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.S(0,0),this._elevation=0,this._zoom=0,this._tileZoom=Et(this._zoom),this._scale=t.ae(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new Mt,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=!0;}apply(e,i,o){this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=Et(this._zoom),this._scale=t.ae(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new Mt(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,this._cameraToCenterDistance=e.cameraToCenterDistance,this._nearZ=e.nearZ,this._farZ=e.farZ,this._autoCalculateNearFarZ=!o&&e.autoCalculateNearFarZ,i&&this._constrain(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e;}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const i=t.aN(e,-180,180)*Math.PI/180;var r,a,s,n,l,c,h,u,d;this._bearingInRadians!==i&&(this._unmodified=!1,this._bearingInRadians=i,this._calcMatrices(),this._rotationMatrix=o(),r=this._rotationMatrix,s=-this._bearingInRadians,n=(a=this._rotationMatrix)[0],l=a[1],c=a[2],h=a[3],u=Math.sin(s),d=Math.cos(s),r[0]=n*d+c*u,r[1]=l*d+h*u,r[2]=n*-u+c*d,r[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.ag(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=!1,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=!1,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.aO(this._fovInRadians)}setFov(e){e=t.ag(e,.1,150),this.fov!==e&&(this._unmodified=!1,this._fovInRadians=t.ad(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const i=this.getConstrained(this._center,e).zoom;this._zoom!==i&&(this._unmodified=!1,this._zoom=i,this._tileZoom=Math.max(0,Math.floor(i)),this._scale=t.ae(i),this._constrain(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(e,t){this._autoCalculateNearFarZ=!1,this._nearZ=e,this._farZ=t,this._calcMatrices();}clearNearFarZOverride(){this._autoCalculateNearFarZ=!0,this._calcMatrices();}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices();}resize(e,t,i=!0){this._width=e,this._height=t,i&&this._constrain(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new G([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-85.051129,t.ah]);}getConstrained(e,t){return this._callbacks.getConstrained(e,t)}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{const{minX:o,minY:r,maxX:a,maxY:s}=t.a1.fromPoints(i).extend(e);return [new t.P(o,r),new t.P(a,r),new t.P(a,s),new t.P(o,s),new t.P(o,r)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const e=this._unmodified,{center:t,zoom:i}=this.getConstrained(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=!1;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.af(new Float64Array(16));t.N(e,e,[this._width/2,-this._height/2,1]),t.M(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.af(new Float64Array(16)),t.N(e,e,[1,-1,1]),t.M(e,e,[-1,-1,0]),t.N(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height;}this._callbacks.calcMatrices();}calculateCenterFromCameraLngLatAlt(e,i,o,r){const a=void 0!==o?o:this.bearing,s=r=void 0!==r?r:this.pitch,n=t.a0.fromLngLat(e,i),l=-Math.cos(t.ad(s)),c=Math.sin(t.ad(s)),h=c*Math.sin(t.ad(a)),u=-c*Math.cos(t.ad(a));let d=this.elevation;const _=i-d;let p;l*_>=0||Math.abs(l)<.1?(p=1e4,d=i+p*l):p=-_/l;let m,f,g=t.aP(1,n.y),v=0;do{if(v+=1,v>10)break;f=p/g,m=new t.a0(n.x+h*f,n.y+u*f),g=1/m.meterInMercatorCoordinateUnits();}while(Math.abs(p-f*g)>1e-12);return {center:m.toLngLat(),elevation:d,zoom:t.aj(this.height/2/Math.tan(this.fovInRadians/2)/f/this.tileSize)}}recalculateZoomAndCenter(e){if(this.elevation-e==0)return;const i=t.ai(1,this.center.lat)*this.worldSize,o=this.cameraToCenterDistance/i,r=t.a0.fromLngLat(this.center,this.elevation),a=de(this.center,this.elevation,this.pitch,this.bearing,o);this._elevation=e;const s=this.calculateCenterFromCameraLngLatAlt(a.toLngLat(),t.aP(a.z,r.y),this.bearing,this.pitch);this._elevation=s.elevation,this._center=s.center,this.setZoom(s.zoom);}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.P(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const e=t.ai(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/e).toLngLat()}getMercatorTileCoordinates(e){if(!e)return [0,0,1,1];const i=e.canonical.z>=0?1<this.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[o]*this.min[o],i+=e[o]*this.max[o]):(i+=e[o]*this.min[o],t+=e[o]*this.max[o]);return t>=0?2:i<0?0:1}}class Dt{distanceToTile2d(e,t,i,o){const r=o.distanceX([e,t]),a=o.distanceY([e,t]);return Math.hypot(r,a)}getWrap(e,t,i){return i}getTileBoundingVolume(e,i,o,r){var a,s;let n=o,l=o;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:o,l=null!==(s=h.maxElevation)&&void 0!==s?s:o;}const c=1<r}allowWorldCopies(){return !0}prepareNextFrame(){}}class At{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,o=0,r,a){const s=a?[[6,5,4],[0,1,2],[0,3,7],[2,1,5],[3,2,6],[0,4,5]]:[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]],n=Math.pow(2,o),l=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((o=>function(e,i,o,r){const a=t.av([],e,i),s=1/a[3]/o*r;return t.aX(a,a,[s,s,1/a[3],s])}(o,e,i,n)));r&&function(e,i,o,r){const a=r?4:0,s=r?0:4;let n=0;const l=[],c=[];for(let i=0;i<4;i++){const o=t.aT([],e[i+s],e[i+a]),r=t.aY(o);t.aQ(o,o,1/r),l.push(r),c.push(o);}for(let i=0;i<4;i++){const r=t.aZ(e[i+a],c[i],o);n=null!==r&&r>=0?Math.max(n,r):Math.max(n,l[i]);}const h=function(e,i){const o=t.aT([],e[i[0]],e[i[1]]),r=t.aT([],e[i[2]],e[i[1]]),a=[0,0,0,0];return t.aU(a,t.aV([],o,r)),a[3]=-t.aW(a,e[i[0]]),a}(e,i),u=function(e,i){const o=t.a_(e),r=t.a$([],e,1/o),a=t.aT([],i,t.aQ([],r,t.aW(i,r))),s=t.a_(a);if(s>0){const e=Math.sqrt(1-r[3]*r[3]),o=t.aQ([],r,-r[3]),n=t.aR([],o,t.aQ([],a,e/s));return t.b0(i,n)}return null}(o,h);if(null!==u){const e=u/t.aW(c[0],h);n=Math.min(n,e);}for(let t=0;t<4;t++){const i=Math.min(n,l[t]);e[t+s]=[e[t+a][0]+c[t][0]*i,e[t+a][1]+c[t][1]*i,e[t+a][2]+c[t][2]*i,1];}}(l,s[0],r,a);const c=s.map((e=>{const i=t.aT([],l[e[0]],l[e[1]]),o=t.aT([],l[e[2]],l[e[1]]),r=t.aU([],t.aV([],i,o)),a=-t.aW(r,l[e[1]]);return r.concat(a)})),h=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of l)for(let t=0;t<3;t++)h[t]=Math.min(h[t],e[t]),u[t]=Math.max(u[t],e[t]);return new At(l,c,new zt(h,u))}}class Lt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e,t){}constructor(e,t,i,o,r){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)},e,t,i,o,r),this._coveringTilesDetailsProvider=new Dt;}clone(){const e=new Lt;return e.apply(this),e}apply(e,t,i){this._helper.apply(e,t,i);}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.b1(0,e)];if(this._helper._renderWorldCopies){const o=this.screenPointToMercatorCoordinate(new t.P(0,0)),r=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,0)),a=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,this._helper._height)),s=this.screenPointToMercatorCoordinate(new t.P(0,this._helper._height)),n=Math.floor(Math.min(o.x,r.x,a.x,s.x)),l=Math.floor(Math.max(o.x,r.x,a.x,s.x)),c=1;for(let o=n-c;o<=l+c;o++)0!==o&&i.push(new t.b1(o,e));}return i}getCameraFrustum(){return At.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const t=this.screenPointToLocation(this.centerPoint,e),i=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(i);}setLocationAtPoint(e,i){const o=t.ai(this.elevation,this.center.lat),r=this.screenPointToMercatorCoordinateAtZ(i,o),a=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,o),s=t.a0.fromLngLat(e),n=new t.a0(s.x-(r.x-a.x),s.y-(r.y-a.y));this.setCenter(null==n?void 0:n.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,i){return i?this.coordinatePoint(t.a0.fromLngLat(e),i.getElevationForLngLatZoom(e,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(t.a0.fromLngLat(e))}screenPointToLocation(e,t){var i;return null===(i=this.screenPointToMercatorCoordinate(e,t))||void 0===i?void 0:i.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const o=i||0,r=[e.x,e.y,0,1],a=[e.x,e.y,1,1];t.av(r,r,this._pixelMatrixInverse),t.av(a,a,this._pixelMatrixInverse);const s=r[3],n=a[3],l=r[1]/s,c=a[1]/n,h=r[2]/s,u=a[2]/n,d=h===u?0:(o-h)/(u-h);return new t.a0(t.C.number(r[0]/s,a[0]/n,d)/this.worldSize,t.C.number(l,c,d)/this.worldSize,o)}coordinatePoint(e,i=0,o=this._pixelMatrix){const r=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.av(r,r,o),new t.P(r[0]/r[3],r[1]/r[3])}getBounds(){const e=Math.max(0,this._helper._height/2-he(this));return (new G).extend(this.screenPointToLocation(new t.P(0,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.P(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-he(this)}calculatePosMatrix(e,i=!1,o){var r;const a=null!==(r=e.key)&&void 0!==r?r:t.b2(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),s=i?this._alignedPosMatrixCache:this._posMatrixCache;if(s.has(a)){const e=s.get(a);return o?e.f32:e.f64}const n=ue(e,this.worldSize);t.O(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return s.set(a,l),o?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,o=this._fogMatrixCacheF32;if(o.has(i))return o.get(i);const r=ue(e,this.worldSize);return t.O(r,this._fogMatrix,r),o.set(i,new Float32Array(r)),o.get(i)}getConstrained(e,i){i=t.ag(+i,this.minZoom,this.maxZoom);const o={center:new t.S(e.lng,e.lat),zoom:i};let r=this._helper._lngRange;this._helper._renderWorldCopies||null!==r||(r=[-179.9999999999,180-1e-10]);const a=this.tileSize*t.ae(o.zoom);let s=0,n=a,l=0,c=a,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;s=t.U(e[1])*a,n=t.U(e[0])*a,n-s<_&&(h=_/(n-s));}r&&(l=t.aN(t.V(r[0])*a,0,a),c=t.aN(t.V(r[1])*a,0,a),cn&&(g=n-e);}if(r){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.aN(p,e-a/2,e+a/2));const o=d/2;i-oc&&(f=c-o);}if(void 0!==f||void 0!==g){const e=new t.P(null!=f?f:p,null!=g?g:m);o.center=ce(a,e).wrap();}return o}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}_calculateNearFarZIfNeeded(e,i,o){if(!this._helper.autoCalculateNearFarZ)return;const r=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),a=e-r*this._helper._pixelPerMeter/Math.cos(i),s=r<0?a:e,n=Math.PI/2+this.pitchInRadians,l=t.ad(this.fov)*(Math.abs(Math.cos(t.ad(this.roll)))*this.height+Math.abs(Math.sin(t.ad(this.roll)))*this.width)/this.height*(.5+o.y/this.height),c=Math.sin(l)*s/Math.sin(t.ag(Math.PI-n-l,.01,Math.PI-.01)),h=he(this),u=Math.atan(h/this._helper.cameraToCenterDistance),d=t.ad(.75),_=u>d?2*u*(.5+o.y/(2*h)):d,p=Math.sin(_)*s/Math.sin(t.ag(Math.PI-n-_,.01,Math.PI-.01)),m=Math.min(c,p);this._helper._farZ=1.01*(Math.cos(Math.PI/2-i)*m+s),this._helper._nearZ=this._helper._height/50;}_calcMatrices(){if(!this._helper._height)return;const e=this.centerOffset,i=le(this.worldSize,this.center),o=i.x,r=i.y;this._helper._pixelPerMeter=t.ai(1,this.center.lat)*this.worldSize;const a=t.ad(Math.min(this.pitch,ne)),s=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(a));let n;this._calculateNearFarZIfNeeded(s,a,e),n=new Float64Array(16),t.b3(n,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),t.ap(this._invProjMatrix,n),n[8]=2*-e.x/this._helper._width,n[9]=2*e.y/this._helper._height,this._projectionMatrix=t.b4(n),t.N(n,n,[1,-1,1]),t.M(n,n,[0,0,-this._helper.cameraToCenterDistance]),t.b5(n,n,-this.rollInRadians),t.b6(n,n,this.pitchInRadians),t.b5(n,n,-this.bearingInRadians),t.M(n,n,[-o,-r,0]),this._mercatorMatrix=t.N([],n,[this.worldSize,this.worldSize,this.worldSize]),t.N(n,n,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n),t.M(n,n,[0,0,-this.elevation]),this._viewProjMatrix=n,this._invViewProjMatrix=t.ap([],n);const l=[0,0,-1,1];t.av(l,l,this._invViewProjMatrix),this._cameraPosition=[l[0]/l[3],l[1]/l[3],l[2]/l[3]],this._fogMatrix=new Float64Array(16),t.b3(this._fogMatrix,this.fovInRadians,this.width/this.height,s,this._helper._farZ),this._fogMatrix[8]=2*-e.x/this.width,this._fogMatrix[9]=2*e.y/this.height,t.N(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.b5(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.b6(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.b5(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.M(this._fogMatrix,this._fogMatrix,[-o,-r,0]),t.N(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n);const c=this._helper._width%2/2,h=this._helper._height%2/2,u=Math.cos(this.bearingInRadians),d=Math.sin(-this.bearingInRadians),_=o-Math.round(o)+u*c+d*h,p=r-Math.round(r)+u*h+d*c,m=new Float64Array(n);if(t.M(m,m,[_>.5?_-1:_,p>.5?p-1:p,0]),this._alignedProjMatrix=m,n=t.ap(new Float64Array(16),this._pixelMatrix),!n)throw new Error("failed to invert matrix");this._pixelMatrixInverse=n,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.P(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.av(i,i,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const e=t.ai(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/e).toLngLat()}lngLatToCameraDepth(e,i){const o=t.a0.fromLngLat(e),r=[o.x*this.worldSize,o.y*this.worldSize,i,1];return t.av(r,r,this._viewProjMatrix),r[2]/r[3]}getProjectionData(e){const{overscaledTileID:i,aligned:o,applyTerrainMatrix:r}=e,a=this._helper.getMercatorTileCoordinates(i),s=i?this.calculatePosMatrix(i,o,!0):null;let n;return n=i&&i.terrainRttPosMatrix32f&&r?i.terrainRttPosMatrix32f:s||t.b7(),{mainMatrix:n,tileMercatorCoords:a,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:n}}isLocationOccluded(e){return !1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,i){return 1}transformLightDirection(e){return t.aS(e)}getRayDirectionFromPixel(e){throw new Error("Not implemented.")}projectTileCoordinates(e,i,o,r){const a=this.calculatePosMatrix(o);let s;r?(s=[e,i,r(e,i),1],t.av(s,s,a)):(s=[e,i,0,1],qe(s,s,a));const n=s[3];return {point:new t.P(s[0]/n,s[1]/n),signedDistanceFromCamera:n,isOccluded:!1}}populateCache(e){for(const t of e)this.calculatePosMatrix(t);}getMatrixForModel(e,i){const o=t.a0.fromLngLat(e,i),r=o.meterInMercatorCoordinateUnits(),a=t.b8();return t.M(a,a,[o.x,o.y,o.z]),t.b5(a,a,Math.PI),t.b6(a,a,Math.PI/2),t.N(a,a,[-r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=new t.Z(0,0,0,0,0),o=this.getProjectionData({overscaledTileID:i,applyGlobeMatrix:e}),r=ue(i,this.worldSize);t.O(r,this._viewProjMatrix,r),o.tileMercatorCoords=[0,0,1,1];const a=[t.$,t.$,this.worldSize/this._helper.pixelsPerMeter],s=t.b9();return t.N(s,r,a),o.fallbackMatrix=s,o.mainMatrix=s,o}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}}function kt(){t.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");}function Ft(e){if(e.useSlerp)if(e.k<1){const i=t.ba(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),o=t.ba(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),r=new Float64Array(4);t.bb(r,i,o,e.k);const a=t.bc(r);e.tr.setRoll(a.roll),e.tr.setPitch(a.pitch),e.tr.setBearing(a.bearing);}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(t.C.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(t.C.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(t.C.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k));}function Bt(e,i,o,r,a){const s=a.padding,n=le(a.worldSize,o.getNorthWest()),l=le(a.worldSize,o.getNorthEast()),c=le(a.worldSize,o.getSouthEast()),h=le(a.worldSize,o.getSouthWest()),u=t.ad(-r),d=n.rotate(u),_=l.rotate(u),p=c.rotate(u),m=h.rotate(u),f=new t.P(Math.max(d.x,_.x,m.x,p.x),Math.max(d.y,_.y,m.y,p.y)),g=new t.P(Math.min(d.x,_.x,m.x,p.x),Math.min(d.y,_.y,m.y,p.y)),v=f.sub(g),b=(a.width-(s.left+s.right+i.left+i.right))/v.x,x=(a.height-(s.top+s.bottom+i.top+i.bottom))/v.y;if(x<0||b<0)return void kt();const y=Math.min(t.aj(a.scale*Math.min(b,x)),e.maxZoom),w=t.P.convert(e.offset),T=new t.P((i.left-i.right)/2,(i.top-i.bottom)/2).rotate(t.ad(r)),P=w.add(T).mult(a.scale/t.ae(y));return {center:ce(a.worldSize,n.add(c).div(2).sub(P)),zoom:y,bearing:r}}class Ot{get useGlobeControls(){return !1}handlePanInertia(e,t){return {easingOffset:e,easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta);}handleMapControlsPan(e,t,i){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(i,e.around);}cameraForBoxAndBearing(e,t,i,o,r){return Bt(e,t,i,o,r)}handleJumpToCenterZoom(e,i){e.zoom!==(void 0!==i.zoom?+i.zoom:e.zoom)&&e.setZoom(+i.zoom),void 0!==i.center&&e.setCenter(t.S.convert(i.center));}handleEaseTo(e,i){const o=e.zoom,r=e.padding,a={roll:e.roll,pitch:e.pitch,bearing:e.bearing},s={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},n=void 0!==i.zoom,l=!e.isPaddingEqual(i.padding);let c=!1;const h=n?+i.zoom:e.zoom;let u=e.centerPoint.add(i.offsetAsPoint);const d=e.screenPointToLocation(u),{center:_,zoom:p}=e.getConstrained(t.S.convert(i.center||d),null!=h?h:o);St(e,_);const m=le(e.worldSize,d),f=le(e.worldSize,_).sub(m),g=t.ae(p-o);return c=p!==o,{easeFunc:n=>{if(c&&e.setZoom(t.C.number(o,p,n)),t.bd(a,s)||Ft({startEulerAngles:a,endEulerAngles:s,tr:e,k:n,useSlerp:a.roll!=s.roll}),l&&(e.interpolatePadding(r,i.padding,n),u=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const i=t.ae(e.zoom-o),r=p>o?Math.min(2,g):Math.max(.5,g),a=Math.pow(r,1-n),s=ce(e.worldSize,m.add(f.mult(n*a)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?s.wrap():s,u);}},isZooming:c,elevationCenter:_}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.zoom,a=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),o?+i.zoom:r),s=a.center,n=a.zoom;St(e,s);const l=le(e.worldSize,i.locationAtOffset),c=le(e.worldSize,s).sub(l),h=c.mag(),u=t.ae(n-r);let d;if(void 0!==i.minZoom){const o=Math.min(+i.minZoom,r,n),a=e.getConstrained(s,o).zoom;d=t.ae(a-r);}return {easeFunc:(i,o,a,h)=>{e.setZoom(1===i?n:r+t.aj(o));const u=1===i?s:ce(e.worldSize,l.add(c.mult(a)).mult(o));e.setLocationAtPoint(e.renderWorldCopies?u.wrap():u,h);},scaleOfZoom:u,targetCenter:s,scaleOfMinZoom:d,pixelPathLength:h}}}class jt{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}jt.Replace=[1,0],jt.disabled=new jt(jt.Replace,t.be.transparent,[!1,!1,!1,!1]),jt.unblended=new jt(jt.Replace,t.be.transparent,[!0,!0,!0,!0]),jt.alphaBlended=new jt([1,771],t.be.transparent,[!0,!0,!0,!0]);const Nt=2305;class Zt{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}Zt.disabled=new Zt(!1,1029,Nt),Zt.backCCW=new Zt(!0,1029,Nt),Zt.frontCCW=new Zt(!0,1028,Nt);class Ut{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Ut.ReadOnly=!1,Ut.ReadWrite=!0,Ut.disabled=new Ut(519,Ut.ReadOnly,[0,1]);const Gt=7680;class Vt{constructor(e,t,i,o,r,a){this.test=e,this.ref=t,this.mask=i,this.fail=o,this.depthFail=r,this.pass=a;}}Vt.disabled=new Vt({func:519,mask:0},0,0,Gt,Gt,Gt);const $t=new WeakMap;function qt(e){var t;if($t.has(e))return $t.get(e);{const i=null===(t=e.getParameter(e.VERSION))||void 0===t?void 0:t.startsWith("WebGL 2.0");return $t.set(e,i),i}}class Wt{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,o=i.gl;this._texFormat=o.RGBA,this._texType=o.UNSIGNED_BYTE;const r=new t.aK;r.emplaceBack(-1,-1),r.emplaceBack(2,-1),r.emplaceBack(-1,2);const a=new t.aM;a.emplaceBack(0,1,2),this._fullscreenTriangle=new wt(i.createVertexBuffer(r,Tt.members),i.createIndexBuffer(a),t.aL.simpleSegment(0,0,r.length,a.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(o.TEXTURE1);const s=o.createTexture();o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texImage2D(o.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(s),qt(o)&&(this._pbo=o.createBuffer(),o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.bufferData(o.PIXEL_PACK_BUFFER,4,o.STREAM_READ),o.bindBuffer(o.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const o=this._cachedRenderContext.context,r=o.gl;if(this._bindFramebuffer(),o.viewport.set([0,0,this._texWidth,this._texHeight]),o.clear({color:t.be.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(o,r.TRIANGLES,Ut.disabled,Vt.disabled,jt.unblended,Zt.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&qt(r)){r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.readBuffer(r.COLOR_ATTACHMENT0),r.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),r.bindBuffer(r.PIXEL_PACK_BUFFER,null);const e=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);r.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&qt(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=Wt._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const Ht=t.$/128;function Xt(e,i){const o=void 0!==e.granularity?Math.max(e.granularity,1):1,r=o+(e.generateBorders?2:0),a=o+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),s=r+1,n=a+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=o+(e.generateBorders?1:0),u=o+(e.generateBorders||e.extendToSouthPole?1:0),d=s*n,_=r*a*6,p=s*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g=0;for(let i=c;i<=u;i++)for(let r=l;r<=h;r++){let a=r/o*t.$;-1===r&&(a=-64),r===o+1&&(a=t.$+Ht);let s=i/o*t.$;-1===i&&(s=e.extendToNorthPole?t.bg:-64),i===o+1&&(s=e.extendToSouthPole?t.bh:t.$+Ht),f[g++]=a,f[g++]=s;}const v=m?new Uint32Array(_):new Uint16Array(_);let b=0;for(let e=0;e0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return "globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy();}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e);}getMeshFromTileID(e,t,i,o,r){return this.currentProjection.getMeshFromTileID(e,t,i,o,r)}setProjection(e){this._transitionable.setValue("type",(null==e?void 0:e.type)||"mercator");}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e);}}function ei(e){const t=oi(e.worldSize,e.center.lat);return 2*Math.PI*t}function ti(e,i,o,r,a){const s=1/(1<1e-6){const r=e[0]/o,a=Math.acos(e[2]/o),s=(r>0?a:-a)/Math.PI*180;return new t.S(t.aN(s,-180,180),i)}return new t.S(0,i)}function ai(e){return Math.cos(e*Math.PI/180)}function si(e,i){const o=ai(e),r=ai(i);return t.aj(r/o)}function ni(e,i){const o=e.rotate(i.bearingInRadians),r=i.zoom+si(i.center.lat,0),a=t.bj(1/ai(i.center.lat),1/ai(Math.min(Math.abs(i.center.lat),60)),t.bm(r,7,3,0,1)),s=360/ei({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.S(i.center.lng-o.x*s*a,t.ag(i.center.lat+o.y*s,-85.051129,t.ah))}function li(e){const t=.5*e,i=Math.sin(t),o=Math.cos(t);return Math.log(i+o)-Math.log(o-i)}function ci(e,i,o,r){const a=e.lat+o*r;if(Math.abs(o)>1){const s=(Math.sign(e.lat+o)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+o)*Math.PI/180,l=li(s+r*(n-s)),c=li(s),h=li(n);return new t.S(e.lng+i*((l-c)/(h-c)),a)}return new t.S(e.lng+i*r,a)}class hi{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._boundingVolumeFactory=e;}swapBuffers(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1;}getTileBoundingVolume(e,t,i,o){const r=`${e.z}_${e.x}_${e.y}_${(null==o?void 0:o.terrain)?"t":""}`,a=this._cache.get(r);if(a)return a;const s=this._cachePrevious.get(r);if(s)return this._cache.set(r,s),s;const n=this._boundingVolumeFactory(e,t,i,o);return this._cache.set(r,n),this._hadAnyChanges=!0,n}}class ui{constructor(e,t,i,o){this.min=i,this.max=o,this.points=e,this.planes=t;}static fromAabb(e,t){const i=[];for(let o=0;o<8;o++)i.push([1&~o?e[0]:t[0],1==(o>>1&1)?t[1]:e[1],1==(o>>2&1)?t[2]:e[2]]);return new ui(i,[[-1,0,0,t[0]],[1,0,0,-e[0]],[0,-1,0,t[1]],[0,1,0,-e[1]],[0,0,-1,t[2]],[0,0,1,-e[2]]],e,t)}static fromCenterSizeAngles(e,i,o){const r=t.bq([],o[0],o[1],o[2]),a=t.br([],[i[0],0,0],r),s=t.br([],[0,i[1],0],r),n=t.br([],[0,0,i[2]],r),l=[...e],c=[...e];for(let t=0;t<8;t++)for(let i=0;i<3;i++){const o=e[i]+a[i]*(1&~t?-1:1)+s[i]*(1==(t>>1&1)?1:-1)+n[i]*(1==(t>>2&1)?1:-1);l[i]=Math.min(l[i],o),c[i]=Math.max(c[i],o);}const h=[];for(let i=0;i<8;i++){const o=[...e];t.aR(o,o,t.aQ([],a,1&~i?-1:1)),t.aR(o,o,t.aQ([],s,1==(i>>1&1)?1:-1)),t.aR(o,o,t.aQ([],n,1==(i>>2&1)?1:-1)),h.push(o);}return new ui(h,[[...a,-t.aW(a,h[0])],[...s,-t.aW(s,h[0])],[...n,-t.aW(n,h[0])],[-a[0],-a[1],-a[2],-t.aW(a,h[7])],[-s[0],-s[1],-s[2],-t.aW(s,h[7])],[-n[0],-n[1],-n[2],-t.aW(n,h[7])]],l,c)}intersectsFrustum(e){let t=!0;const i=this.points.length,o=this.planes.length,r=e.planes.length,a=e.points.length;for(let o=0;o=0&&a++;}if(0===a)return 0;a=0&&o++;}if(0===o)return 0}return 1}intersectsPlane(e){const t=this.points.length;let i=0;for(let o=0;o=0&&i++;}return i===t?2:0===i?0:1}}function di(e,t,i){const o=e-t;return o<0?-o:Math.max(0,o-i)}function _i(e,t,i,o,r){const a=e-i;let s;return s=a<0?Math.min(-a,1+a-r):a>1?Math.min(Math.max(a-r,0),1-a):0,Math.max(s,di(t,o,r))}class pi{constructor(){this._boundingVolumeCache=new hi(this._computeTileBoundingVolume);}prepareNextFrame(){this._boundingVolumeCache.swapBuffers();}distanceToTile2d(e,t,i,o){const r=1<4}allowWorldCopies(){return !1}getTileBoundingVolume(e,t,i,o){return this._boundingVolumeCache.getTileBoundingVolume(e,t,i,o)}_computeTileBoundingVolume(e,i,o,r){var a,s;let n=o,l=o;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:o,l=null!==(s=h.maxElevation)&&void 0!==s?s:o;}if(n/=t.bt,l/=t.bt,n+=1,l+=1,e.z<=0)return ui.fromAabb([-l,-l,-l],[l,l,l]);if(1===e.z)return ui.fromAabb([0===e.x?-l:0,0===e.y?0:-l,-l],[0===e.x?0:l,0===e.y?l:0,l]);{const i=[ti(0,0,e.x,e.y,e.z),ti(t.$,0,e.x,e.y,e.z),ti(t.$,t.$,e.x,e.y,e.z),ti(0,t.$,e.x,e.y,e.z)],o=[];for(const e of i)o.push(t.aQ([],e,l));if(l!==n)for(const e of i)o.push(t.aQ([],e,n));0===e.y&&o.push([0,1,0]),e.y===(1<=(1<{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._coveringTilesDetailsProvider=new pi;}clone(){const e=new fi;return e.apply(this),e}apply(e,t){this._globeLatitudeErrorCorrectionRadians=t||0,this._helper.apply(e);}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const e=t.bo();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(e){const{overscaledTileID:t,applyGlobeMatrix:i}=e,o=this._helper.getMercatorTileCoordinates(t);return {mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:o,clippingPlane:this._cachedClippingPlane,projectionTransition:i?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(e){const i=this.pitchInRadians,o=this.cameraToCenterDistance/e,r=Math.sin(i)*o,a=Math.cos(i)*o+1,s=1/Math.sqrt(r*r+a*a)*1;let n=-r,l=a;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];t.bv(h,h,[0,0,0],-this.bearingInRadians),t.bw(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.bx(h,h,[0,0,0],this.center.lng*Math.PI/180);const u=1/t.aY(h);return t.aQ(h,h,u),[...h,-s*u]}isLocationOccluded(e){return !this.isSurfacePointVisible(ii(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,o=this._helper._center.lat*Math.PI/180,r=Math.cos(o),a=[Math.sin(i)*r,Math.sin(o),Math.cos(i)*r],s=[a[2],0,-a[0]],n=[0,0,0];t.aV(n,s,a),t.aU(s,s),t.aU(n,n);const l=[0,0,0];return t.aU(l,[s[0]*e[0]+n[0]*e[1]+a[0]*e[2],s[1]*e[0]+n[1]*e[1]+a[1]*e[2],s[2]*e[0]+n[2]*e[1]+a[2]*e[2]]),l}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(e,i,o){const r=function(e,i,o){const r=1/(1<a&&(a=i),on&&(n=o);}const h=[c.lng+s,c.lat+l,c.lng+a,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new G(h)}getConstrained(e,i){const o=t.ag(e.lat,-85.051129,t.ah),r=t.ag(+i,this.minZoom+si(0,o),this.maxZoom);return {center:new t.S(e.lng,o),zoom:r}}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,i){const o=ii(this.unprojectScreenPoint(i)),r=ii(e),a=t.bo();t.bA(a);const s=t.bo();t.bx(s,o,a,-this.center.lng*Math.PI/180),t.bw(s,s,a,this.center.lat*Math.PI/180);const n=r[0]*r[0]+r[2]*r[2],l=s[0]*s[0];if(n=-g&&p<=g,b=f>=-g&&f<=g;let x,y;if(v&&b){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.bC(u,e)+t.bC(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return !1;const i=t.bu();return t.av(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const o=t.aW(e,i),r=t.bo(),a=t.bo();t.aQ(a,i,o),t.aT(r,e,a);const s=1-t.aW(r,r);if(s<0)return null;const n=t.aW(e,e)-1,l=-o+(o<0?1:-1)*Math.sqrt(s),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,o=this.getRayDirectionFromPixel(e),r=this.rayPlanetIntersection(i,o);if(r){const e=t.bo();t.aR(e,i,[o[0]*r.tMin,o[1]*r.tMin,o[2]*r.tMin]);const a=t.bo();return t.aU(a,e),ri(a)}const a=this._cachedClippingPlane,s=a[0]*o[0]+a[1]*o[1]+a[2]*o[2],n=-t.b0(a,i)/s,l=t.bo();if(n>0)t.aR(l,i,[o[0]*n,o[1]*n,o[2]*n]);else {const e=t.bo();t.aR(e,i,[2*o[0],2*o[1],2*o[2]]);const r=t.b0(this._cachedClippingPlane,e);t.aT(l,e,[this._cachedClippingPlane[0]*r,this._cachedClippingPlane[1]*r,this._cachedClippingPlane[2]*r]);}const c=function(e){const i=t.bo();return i[0]=e[0]*-e[3],i[1]=e[1]*-e[3],i[2]=e[2]*-e[3],{center:i,radius:Math.sqrt(1-e[3]*e[3])}}(a);return ri(function(e,i,o){const r=t.bo();t.aT(r,o,e);const a=t.bo();return t.bp(a,e,r,i/t.a_(r)),a}(c.center,c.radius,l))}getMatrixForModel(e,i){const o=t.S.convert(e),r=1/t.bt,a=t.b8();return t.by(a,a,o.lng/180*Math.PI),t.b6(a,a,-o.lat/180*Math.PI),t.M(a,a,[0,0,1+i/t.bt]),t.b6(a,a,.5*Math.PI),t.N(a,a,[r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=this.getProjectionData({overscaledTileID:new t.Z(0,0,0,0,0),applyGlobeMatrix:e});return i.tileMercatorCoords=[0,0,1,1],i}getFastPathSimpleProjectionMatrix(e){}}class gi{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame(),this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame();}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._globeness=1,this._mercatorTransform=new Lt,this._verticalPerspectiveTransform=new fi;}clone(){const e=new gi;return e._globeness=this._globeness,e._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,e.apply(this),e}apply(e){this._helper.apply(e),this._mercatorTransform.apply(this),this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians);}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){const t=this._mercatorTransform.getProjectionData(e),i=this._verticalPerspectiveTransform.getProjectionData(e);return {mainMatrix:this.isGlobeRendering?i.mainMatrix:t.mainMatrix,clippingPlane:i.clippingPlane,tileMercatorCoords:i.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return t.bj(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return t.bj(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,i,o){const r=this._mercatorTransform.getPitchedTextCorrection(e,i,o),a=this._verticalPerspectiveTransform.getPitchedTextCorrection(e,i,o);return t.bj(r,a,this._globeness)}projectTileCoordinates(e,t,i,o){return this.currentTransform.projectTileCoordinates(e,t,i,o)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ);}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this._mercatorTransform.recalculateZoomAndCenter(e),this._verticalPerspectiveTransform.recalculateZoomAndCenter(e);}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e);}getBounds(){return this.currentTransform.getBounds()}getConstrained(e,t){return this.currentTransform.getConstrained(e,t)}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,t){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,t),void this.apply(this._mercatorTransform);this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform);}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getMatrixForModel(e,t){return this.currentTransform.getMatrixForModel(e,t)}getProjectionDataForCustomLayer(e=!0){const t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;const i=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return i.fallbackMatrix=t.mainMatrix,i}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}}class vi{get useGlobeControls(){return !0}handlePanInertia(e,i){const o=ni(e,i);return Math.abs(o.lng-i.center.lng)>180&&(o.lng=i.center.lng+179.5*Math.sign(o.lng-i.center.lng)),{easingCenter:o,easingOffset:new t.P(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){const o=e.around,r=i.screenPointToLocation(o);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const a=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const s=i.zoom-a;if(0===s)return;const n=t.bz(i.center.lng,r.lng),l=n/(Math.abs(n/180)+1),c=t.bz(i.center.lat,r.lat),h=i.getRayDirectionFromPixel(o),u=i.cameraPosition,d=-1*t.aW(u,h),_=t.bo();t.aR(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.aY(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=oi(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.bm(f,.9,.5,1,.25),v=(1-t.ae(-s))*Math.min(m,g),b=i.center.lat,x=i.zoom,y=new t.S(i.center.lng+l*v,t.ag(i.center.lat+c*v,-85.051129,t.ah));i.setLocationAtPoint(r,o);const w=i.center,T=t.bm(Math.abs(n),45,85,0,1),P=t.bm(f,.75,.35,0,1),C=Math.pow(Math.max(T,P),.25),I=t.bz(w.lng,y.lng),M=t.bz(w.lat,y.lat);i.setCenter(new t.S(w.lng+I*C,w.lat+M*C).wrap()),i.setZoom(x+si(b,i.center.lat));}handleMapControlsPan(e,t,i){if(!e.panDelta)return;const o=t.center.lat,r=t.zoom;t.setCenter(ni(e.panDelta,t).wrap()),t.setZoom(r+si(o,t.center.lat));}cameraForBoxAndBearing(e,i,o,r,a){const s=Bt(e,i,o,r,a),n=i.left/a.width*2-1,l=(a.width-i.right)/a.width*2-1,c=i.top/a.height*-2+1,h=(a.height-i.bottom)/a.height*-2+1,u=t.bz(o.getWest(),o.getEast())<0,d=u?o.getEast():o.getWest(),_=u?o.getWest():o.getEast(),p=Math.max(o.getNorth(),o.getSouth()),m=Math.min(o.getNorth(),o.getSouth()),f=d+.5*t.bz(d,_),g=p+.5*t.bz(p,m),v=a.clone();v.setCenter(s.center),v.setBearing(s.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(s.zoom);const b=v.modelViewProjectionMatrix,x=[ii(o.getNorthWest()),ii(o.getNorthEast()),ii(o.getSouthWest()),ii(o.getSouthEast()),ii(new t.S(_,g)),ii(new t.S(d,g)),ii(new t.S(f,p)),ii(new t.S(f,m))],y=ii(s.center);let w=Number.POSITIVE_INFINITY;for(const e of x)n<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",n))),l>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",l))),c>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",c))),h<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",h)));if(Number.isFinite(w)&&0!==w)return s.zoom=v.zoom+t.aj(w),s;kt();}handleJumpToCenterZoom(e,i){const o=e.center.lat,r=e.getConstrained(i.center?t.S.convert(i.center):e.center,e.zoom).center;e.setCenter(r.wrap());const a=void 0!==i.zoom?+i.zoom:e.zoom+si(o,r.lat);e.zoom!==a&&e.setZoom(a);}handleEaseTo(e,i){const o=e.zoom,r=e.center,a=e.padding,s={roll:e.roll,pitch:e.pitch,bearing:e.bearing},n={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},l=void 0!==i.zoom,c=!e.isPaddingEqual(i.padding);let h=!1;const u=i.center?t.S.convert(i.center):r,d=e.getConstrained(u,o).center;St(e,d);const _=e.clone();_.setCenter(d),_.setZoom(l?+i.zoom:o+si(r.lat,u.lat)),_.setBearing(i.bearing);const p=new t.P(t.ag(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ag(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));_.setLocationAtPoint(d,p);const m=(i.offset&&i.offsetAsPoint.mag())>0?_.center:d,f=l?+i.zoom:o+si(r.lat,m.lat),g=o+si(r.lat,0),v=f+si(m.lat,0),b=t.bz(r.lng,m.lng),x=t.bz(r.lat,m.lat),y=t.ae(v-g);return h=f!==o,{easeFunc:o=>{if(t.bd(s,n)||Ft({startEulerAngles:s,endEulerAngles:n,tr:e,k:o,useSlerp:s.roll!=n.roll}),c&&e.interpolatePadding(a,i.padding,o),i.around)t.w("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=v>g?Math.min(2,y):Math.max(.5,y),i=Math.pow(t,1-o),a=ci(r,b,x,o*i);e.setCenter(a.wrap());}if(h){const i=t.C.number(g,v,o)+si(0,e.center.lat);e.setZoom(i);}},isZooming:h,elevationCenter:m}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.center,a=e.zoom,s=e.padding,n=!e.isPaddingEqual(i.padding),l=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),a).center,c=o?+i.zoom:e.zoom+si(e.center.lat,l.lat),h=e.clone();h.setCenter(l),h.setZoom(c),h.setBearing(i.bearing);const u=new t.P(t.ag(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ag(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));h.setLocationAtPoint(l,u);const d=h.center;St(e,d);const _=function(e,i,o){const r=ii(i),a=ii(o),s=t.aW(r,a),n=Math.acos(s),l=ei(e);return n/(2*Math.PI)*l}(e,r,d),p=a+si(r.lat,0),m=c+si(d.lat,0),f=t.ae(m-p);let g;if("number"==typeof i.minZoom){const o=+i.minZoom+si(d.lat,0),r=Math.min(o,p,m)+si(0,d.lat),a=e.getConstrained(d,r).zoom+si(d.lat,0);g=t.ae(a-p);}const v=t.bz(r.lng,d.lng),b=t.bz(r.lat,d.lat);return {easeFunc:(o,a,l,h)=>{const u=ci(r,v,b,l);n&&e.interpolatePadding(s,i.padding,o);const _=1===o?d:u;e.setCenter(_.wrap());const m=p+t.aj(a);e.setZoom(1===o?c:m+si(0,_.lat));},scaleOfZoom:f,targetCenter:d,scaleOfMinZoom:g,pixelPathLength:_}}static solveVectorScale(e,t,i,o,r){const a="x"===o?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],s=[i[3],i[7],i[11],i[15]],n=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],l=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],c=t[0]*a[0]+t[1]*a[1]+t[2]*a[2],h=t[0]*s[0]+t[1]*s[1]+t[2]*s[2];return c+r*l===n+r*h||s[3]*(n-c)+a[3]*(h-l)+n*h==c*l?null:(c+a[3]-r*h-r*s[3])/(c-n-r*h+r*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.y(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),yi=t.bD();class wi extends t.E{constructor(e,i={}){super(),this._rtlPluginLoaded=()=>{for(const e in this.sourceCaches){const t=this.sourceCaches[e].getSource().type;"vector"!==t&&"geojson"!==t||this.sourceCaches[e].reload();}},this.map=e,this.dispatcher=new F(k(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.imageManager=new b,this.imageManager.setEventedParent(this),this.glyphManager=new T(e._requestManager,i.localIdeographFontFamily),this.lineAtlas=new E(256,512),this.crossTileSymbolIndex=new vt,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.bE,this._loaded=!1,this._availableImages=[],this._globalState={},this._resetUpdates(),this.dispatcher.broadcast("SR",t.bF()),oe().on(ee,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.sourceCaches[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}setGlobalStateProperty(e,i){var o,r,a;this._checkLoaded();const s=null===i?null!==(a=null===(r=null===(o=this.stylesheet.state)||void 0===o?void 0:o[e])||void 0===r?void 0:r.default)&&void 0!==a?a:null:i;if(t.bG(s,this._globalState[e]))return this;this._globalState[e]=s;const n=this._findGlobalStateAffectedSources([e]);for(const e in this.sourceCaches)n.has(e)&&(this._reloadSource(e),this._changed=!0);}getGlobalState(){return this._globalState}setGlobalState(e){this._checkLoaded();const i=[];for(const o in e)!t.bG(this._globalState[o],e[o].default)&&(i.push(o),this._globalState[o]=e[o].default);const o=this._findGlobalStateAffectedSources(i);for(const e in this.sourceCaches)o.has(e)&&(this._reloadSource(e),this._changed=!0);}_findGlobalStateAffectedSources(e){if(0===e.length)return new Set;const t=new Set;for(const i in this._layers){const o=this._layers[i],r=o.getLayoutAffectingGlobalStateRefs();for(const i of e)r.has(i)&&t.add(o.source);}return t}loadURL(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const r=this.map._requestManager.transformRequest(e,"Style");this._loadStyleRequest=new AbortController;const a=this._loadStyleRequest;t.j(r,this._loadStyleRequest).then((e=>{this._loadStyleRequest=null,this._load(e.data,i,o);})).catch((e=>{this._loadStyleRequest=null,e&&!a.signal.aborted&&this.fire(new t.k(e));}));}loadJSON(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,s.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=!1!==i.validate,this._load(e,i,o);})).catch((()=>{}));}loadEmpty(){this.fire(new t.l("dataloading",{dataType:"style"})),this._load(yi,{validate:!1});}_load(e,i,o){var r,a,s;const n=i.transformStyle?i.transformStyle(o,e):e;if(!i.validate||!xi(this,t.z(n))){this._loaded=!0,this.stylesheet=n;for(const e in n.sources)this.addSource(e,n.sources[e],{validate:!1});n.sprite?this._loadSprite(n.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(n.glyphs),this._createLayers(),this.light=new I(this.stylesheet.light),this._setProjectionInternal((null===(r=this.stylesheet.projection)||void 0===r?void 0:r.type)||"mercator"),this.sky=new S(this.stylesheet.sky),this.map.setTerrain(null!==(a=this.stylesheet.terrain)&&void 0!==a?a:null),this.setGlobalState(null!==(s=this.stylesheet.state)&&void 0!==s?s:null),this.fire(new t.l("data",{dataType:"style"})),this.fire(new t.l("style.load"));}}_createLayers(){const e=t.bH(this.stylesheet.layers);this.dispatcher.broadcast("SL",e),this._order=e.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const i of e){const e=t.bI(i);e.setEventedParent(this,{layer:{id:i.id}}),this._layers[i.id]=e;}}_loadSprite(e,i=!1,o=void 0){let r;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=f(e),n=o>1?"@2x":"",l={},c={};for(const{id:e,url:o}of a){const a=i.transformRequest(g(o,n,".json"),"SpriteJSON");l[e]=t.j(a,r);const s=i.transformRequest(g(o,n,".png"),"SpriteImage");c[e]=p.getImage(s,r);}return yield Promise.all([...Object.values(l),...Object.values(c)]),function(e,i){return t._(this,void 0,void 0,(function*(){const t={};for(const o in e){t[o]={};const r=s.getImageCanvasContext((yield i[o]).data),a=(yield e[o]).data;for(const e in a){const{width:i,height:s,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=a[e];t[o][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:s,x:n,y:l,context:r}};}}return t}))}(l,c)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const o=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of o)this.imageManager.removeImage(e),this._changedImages[e]=!0;for(const o in e[t]){const r="default"===t?o:`${t}:${o}`;this._spritesImagesIds[t].push(r),r in this.imageManager.images?this.imageManager.updateImage(r,e[t][o],!1):this.imageManager.addImage(r,e[t][o]),i&&(this._changedImages[r]=!0);}}})).catch((e=>{this._spriteRequest=null,r=e,this.fire(new t.k(r));})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),i&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"})),o&&o(r);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}_validateLayer(e){const i=this.sourceCaches[e.source];if(!i)return;const o=e.sourceLayer;if(!o)return;const r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.k(new Error(`Source layer "${o}" does not exist on source "${r.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(const e in this.sourceCaches)if(!this.sourceCaches[e].loaded())return !1;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=!1){const o=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.bJ(o):o);const r=[];for(const a of e)if(o[a]){const e=i?t.bJ(o[a]):o[a];r.push(e);}return r}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){var e,t,i;if(null===(e=this.light)||void 0===e?void 0:e.hasTransition())return !0;if(null===(t=this.sky)||void 0===t?void 0:t.hasTransition())return !0;if(null===(i=this.projection)||void 0===i?void 0:i.hasTransition())return !0;for(const e in this.sourceCaches)if(this.sourceCaches[e].hasTransition())return !0;for(const e in this._layers)if(this._layers[e].hasTransition())return !0;return !1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const o={};for(const e in this.sourceCaches){const t=this.sourceCaches[e];o[e]=t.used,t.used=!1;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.sourceCaches[i.source].used=!0);}for(const e in o){const i=this.sourceCaches[e];!!o[e]!=!!i.used&&i.fire(new t.l("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.projection.recalculate(e),this.z=e.zoom,i&&this.fire(new t.l("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,!1),removedIds:t});}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1;}setState(e,i={}){var o;this._checkLoaded();const r=this.serialize();if(e=i.transformStyle?i.transformStyle(r,e):e,(null===(o=i.validate)||void 0===o||o)&&xi(this,t.z(e)))return !1;(e=t.bJ(e)).layers=t.bH(e.layers);const a=t.bK(r,e),s=this._getOperationsToPerform(a);if(s.unimplemented.length>0)throw new Error(`Unimplemented: ${s.unimplemented.join(", ")}.`);if(0===s.operations.length)return !1;for(const e of s.operations)e();return this.stylesheet=e,this._serializedLayers=null,!0}_getOperationsToPerform(e){const t=[],i=[];for(const o of e)switch(o.command){case "setCenter":case "setZoom":case "setBearing":case "setPitch":case "setRoll":continue;case "addLayer":t.push((()=>this.addLayer.apply(this,o.args)));break;case "removeLayer":t.push((()=>this.removeLayer.apply(this,o.args)));break;case "setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,o.args)));break;case "setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,o.args)));break;case "setFilter":t.push((()=>this.setFilter.apply(this,o.args)));break;case "addSource":t.push((()=>this.addSource.apply(this,o.args)));break;case "removeSource":t.push((()=>this.removeSource.apply(this,o.args)));break;case "setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,o.args)));break;case "setLight":t.push((()=>this.setLight.apply(this,o.args)));break;case "setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,o.args)));break;case "setGlyphs":t.push((()=>this.setGlyphs.apply(this,o.args)));break;case "setSprite":t.push((()=>this.setSprite.apply(this,o.args)));break;case "setTerrain":t.push((()=>this.map.setTerrain.apply(this,o.args)));break;case "setSky":t.push((()=>this.setSky.apply(this,o.args)));break;case "setProjection":this.setProjection.apply(this,o.args);break;case "setGlobalState":t.push((()=>this.setGlobalState.apply(this,o.args)));break;case "setTransition":t.push((()=>{}));break;default:i.push(o.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,o={}){if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.z.source,`sources.${e}`,i,null,o))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const r=this.sourceCaches[e]=new xe(e,i,this.dispatcher);r.style=this,r.setEventedParent(this,(()=>({isSourceLoaded:r.loaded(),source:r.serialize(),sourceId:e}))),r.onAdd(this.map),this._changed=!0;}removeSource(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.k(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],i.fire(new t.l("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=!0;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error(`There is no source with this ID=${e}`);const i=this.sourceCaches[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=!0;}getSource(e){return this.sourceCaches[e]&&this.sourceCaches[e].getSource()}addLayer(e,i,o={}){this._checkLoaded();const r=e.id;if(this.getLayer(r))return void this.fire(new t.k(new Error(`Layer "${r}" already exists on this map.`)));let a;if("custom"===e.type){if(xi(this,t.bL(e)))return;a=t.bI(e);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(r,e.source),e=t.bJ(e),e=t.e(e,{source:r})),this._validate(t.z.layer,`layers.${r}`,e,{arrayIndex:-1},o))return;a=t.bI(e),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}});}const s=i?this._order.indexOf(i):this._order.length;if(i&&-1===s)this.fire(new t.k(new Error(`Cannot add layer "${r}" before non-existing layer "${i}".`)));else {if(this._order.splice(s,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){const e=this._removedLayers[r];delete this._removedLayers[r],e.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=!0,!this._layers[e])return void this.fire(new t.k(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const o=this._order.indexOf(e);this._order.splice(o,1);const r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.k(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.k(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,o){this._checkLoaded();const r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.k(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,o={}){this._checkLoaded();const r=this.getLayer(e);if(r){if(!t.bG(r.filter,i))return null==i?(r.setFilter(void 0),void this._updateLayer(r)):void(this._validate(t.z.filter,`layers.${r.id}.filter`,i,null,o)||(r.setFilter(t.bJ(i)),this._updateLayer(r)))}else this.fire(new t.k(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.bJ(this.getLayer(e).filter)}setLayoutProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bG(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.k(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bG(a.getPaintProperty(i),o)||(a.setPaintProperty(i,o,r)&&this._updateLayer(a),this._changed=!0,this._updatedPaintProps[e]=!0,this._serializedLayers=null):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0===a)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const s=a.getSource().type;"geojson"===s&&r?this.fire(new t.k(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==s||r?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const o=e.source,r=this.sourceCaches[o];if(void 0===r)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const a=r.getSource().type,s="vector"===a?e.sourceLayer:void 0;"vector"!==a||s?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.k(new Error("A feature id is required to remove its specific state property."))):r.removeFeatureState(s,e.id,i):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r)return "vector"!==r.getSource().type||o?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id)):void this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.k(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.bM(this.sourceCaches,(e=>e.serialize())),i=this._serializeByIds(this._order,!0),o=this.map.getTerrain()||void 0,r=this.stylesheet;return t.bN({version:r.version,name:r.name,metadata:r.metadata,light:r.light,sky:r.sky,center:r.center,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,sprite:r.sprite,glyphs:r.glyphs,transition:r.transition,projection:r.projection,sources:e,layers:i,terrain:o},(e=>void 0!==e))}_updateLayer(e){this._updatedLayers[e.id]=!0,e.source&&!this._updatedSources[e.source]&&"raster"!==this.sourceCaches[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.sourceCaches[e.source].pause()),this._serializedLayers=null,this._changed=!0;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},o=[];for(let r=this._order.length-1;r>=0;r--){const a=this._order[r];if(t(a)){i[a]=r;for(const t of e){const e=t[a];if(e)for(const t of e)o.push(t);}}}o.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const r=[];for(let a=this._order.length-1;a>=0;a--){const s=this._order[a];if(t(s))for(let e=o.length-1;e>=0;e--){const t=o[e].feature;if(i[t.layer.id]this.map.terrain.getElevation(e,t,i):void 0));return this.placement&&a.push(function(e,t,i,o,r,a,s){const n={},l=a.queryRenderedSymbols(o),c=[];for(const e of Object.keys(l).map(Number))c.push(s[e]);c.sort(N);for(const i of c){const o=i.featureIndex.lookupSymbolFeatures(l[i.bucketInstanceId],t,i.bucketIndex,i.sourceLayerIndex,r.filter,r.layers,r.availableImages,e);for(const e in o){const t=n[e]=n[e]||[],r=o[e];r.sort(((e,t)=>{const o=i.featureSortOrder;if(o){const i=o.indexOf(e.featureIndex);return o.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of r)t.push(e);}}return function(e,t,i){for(const o in e)for(const r of e[o])Z(r,i[t[o].source]);return e}(n,e,i)}(this._layers,s,this.sourceCaches,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(a)}querySourceFeatures(e,i){i&&i.filter&&this._validate(t.z.filter,"querySourceFeatures.filter",i.filter,null,i);const o=this.sourceCaches[e];return o?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),o=[],r={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const o=this.crossTileSymbolIndex.addLayer(i,l[i.source],e.center.lng);a=a||o;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((r=r||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(s.now(),e.zoom))&&(this.pauseablePlacement=new _t(e,this.map.terrain,this._order,r,t,i,o,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(s.now()),n=!0),a&&this.pauseablePlacement.placement.setStale()),n||a)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,l[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(s.now())}_releaseSymbolFadeTiles(){for(const e in this.sourceCaches)this.sourceCaches[e].releaseSymbolFadeTiles();}getImages(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.z.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}addSprite(e,i,o={},r){this._checkLoaded();const a=[{id:e,url:i}],s=[...f(this.stylesheet.sprite),...a];this._validate(t.z.sprite,"sprite",s,null,o)||(this.stylesheet.sprite=s,this._loadSprite(a,!0,r));}removeSprite(e){this._checkLoaded();const i=f(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=!0;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:void 0,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}else this.fire(new t.k(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return f(this.stylesheet.sprite)}setSprite(e,i={},o){this._checkLoaded(),e&&this._validate(t.z.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,!0,o):(this._unloadSprite(),o&&o(null)));}}var Ti=t.aI([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class Pi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;}bind(e,t,i,o,r,a,s,n,l){this.context=e;let c=this.boundPaintVertexBuffers.length!==o.length;for(let e=0;!c&&e({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:o?o.properties.get("fog-color"):t.be.white,u_fog_ground_blend:o?o.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:a?0:o?o.calculateFogBlendOpacity(r):0,u_horizon_color:o?o.properties.get("horizon-color"):t.be.white,u_horizon_fog_blend:o?o.properties.get("horizon-fog-blend"):1,u_is_globe_mode:a?1:0}),Ii={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function Mi(e){const t=[];for(let i=0;i({u_depth:new t.bO(e,i.u_depth),u_terrain:new t.bO(e,i.u_terrain),u_terrain_dim:new t.bf(e,i.u_terrain_dim),u_terrain_matrix:new t.bQ(e,i.u_terrain_matrix),u_terrain_unpack:new t.bR(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.bf(e,i.u_terrain_exaggeration)}))(e,C),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.bQ(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.bR(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.bR(e,i.u_projection_clipping_plane),u_projection_transition:new t.bf(e,i.u_projection_transition),u_projection_fallback_matrix:new t.bQ(e,i.u_projection_fallback_matrix)}))(e,C),this.binderUniforms=o?o.getUniforms(e,C):[];}draw(e,t,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v){const b=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(o),e.setColorMode(r),e.setCullFace(a),n){e.activeTexture.set(b.TEXTURE2),b.bindTexture(b.TEXTURE_2D,n.depthTexture),e.activeTexture.set(b.TEXTURE3),b.bindTexture(b.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[Ii[e]].set(l[e]);if(s)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(s[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let x=0;switch(t){case b.LINES:x=2;break;case b.TRIANGLES:x=3;break;case b.LINE_STRIP:x=1;}for(const i of d.get()){const o=i.vaos||(i.vaos={});(o[c]||(o[c]=new Pi)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),b.drawElements(t,i.primitiveLength*x,b.UNSIGNED_SHORT,i.primitiveOffset*x*2);}}}function Ei(e,i,o){const r=1/t.aB(o,1,i.transform.tileZoom),a=Math.pow(2,o.tileID.overscaledZ),s=o.tileSize*Math.pow(2,i.transform.tileZoom)/a,n=s*(o.tileID.canonical.x+o.tileID.wrap*a),l=s*o.tileID.canonical.y;return {u_image:0,u_texsize:o.imageAtlasTexture.size,u_scale:[r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Ri=(e,i,o,r)=>{const a=e.style.light,s=a.properties.get("position"),n=[s.x,s.y,s.z],l=t.bU();"viewport"===a.properties.get("anchor")&&t.bV(l,e.transform.bearingInRadians),t.bW(n,n,l);const c=e.transform.transformLightDirection(n),h=a.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:o,u_fill_translate:r}},zi=(e,i,o,r,a,s,n)=>t.e(Ri(e,i,o,r),Ei(s,e,n),{u_height_factor:-Math.pow(2,a.overscaledZ)/n.tileSize/8}),Di=(e,i,o,r)=>t.e(Ei(i,e,o),{u_fill_translate:r}),Ai=(e,t)=>({u_world:e,u_fill_translate:t}),Li=(e,i,o,r,a)=>t.e(Di(e,i,o,a),{u_world:r}),ki=(e,i,o,r,a)=>{const s=e.transform;let n,l,c=0;if("map"===o.paint.get("circle-pitch-alignment")){const e=t.aB(i,1,s.zoom);n=!0,l=[e,e],c=e/(t.$*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*a;}else n=!1,l=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===o.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:r}},Fi=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),Bi=e=>({u_viewport_size:[e.width,e.height]}),Oi=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),ji=(e,i,o,r)=>{const a=t.aB(e,1,i)/(t.$*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*r;return {u_extrude_scale:t.aB(e,1,i),u_intensity:o,u_globe_extrude_scale:a}},Ni=(e,i,o,r)=>{const a=t.L();t.bX(a,0,e.width,e.height,0,0,1);const s=e.context.gl;return {u_matrix:a,u_world:[s.drawingBufferWidth,s.drawingBufferHeight],u_image:o,u_color_ramp:r,u_opacity:i.paint.get("heatmap-opacity")}},Zi=(e,t,i)=>{const o=i.paint.get("hillshade-accent-color");let r;switch(i.paint.get("hillshade-method")){case "basic":r=4;break;case "combined":r=1;break;case "igor":r=2;break;case "multidirectional":r=3;break;default:r=0;}const a=i.getIlluminationProperties();for(let t=0;t{const o=i.stride,r=t.L();return t.bX(r,0,t.$,-8192,0,0,1),t.M(r,r,[0,-8192,0]),{u_matrix:r,u_image:1,u_dimension:[o,o],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function Gi(e,i){const o=Math.pow(2,i.canonical.z),r=i.canonical.y;return [new t.a0(0,r/o).toLngLat().lat,new t.a0(0,(r+1)/o).toLngLat().lat]}const Vi=(e,t)=>({u_image:0,u_unpack:t.getUnpackVector(),u_dimension:[t.stride,t.stride],u_elevation_stops:1,u_color_stops:4,u_opacity:e.paint.get("color-relief-opacity")}),$i=(e,i,o,r)=>{const a=e.transform;return {u_translation:Ki(e,i,o),u_ratio:r/t.aB(i,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},qi=(e,i,o,r,a)=>t.e($i(e,i,o,r),{u_image:0,u_image_height:a}),Wi=(e,i,o,r,a)=>{const s=e.transform,n=Xi(i,s);return {u_translation:Ki(e,i,o),u_texsize:i.imageAtlasTexture.size,u_ratio:r/t.aB(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},Hi=(e,i,o,r,a,s)=>{const n=e.lineAtlas,l=Xi(i,e.transform),c="round"===o.layout.get("line-cap"),h=n.getDash(a.from,c),u=n.getDash(a.to,c),d=h.width*s.fromScale,_=u.width*s.toScale;return t.e($i(e,i,o,r),{u_patternscale_a:[l/d,-h.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*e.pixelRatio)/2,u_image:0,u_tex_y_a:h.y,u_tex_y_b:u.y,u_mix:s.t})};function Xi(e,i){return 1/t.aB(e,1,i.tileZoom)}function Ki(e,i,o){return t.aC(e.transform,i,o.paint.get("line-translate"),o.paint.get("line-translate-anchor"))}const Yi=(e,t,i,o,r)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*o.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:o.paint.get("raster-brightness-min"),u_brightness_high:o.paint.get("raster-brightness-max"),u_saturation_factor:(s=o.paint.get("raster-saturation"),s>0?1-1/(1.001-s):-s),u_contrast_factor:(a=o.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Qi(o.paint.get("raster-hue-rotate")),u_coords_top:[r[0].x,r[0].y,r[1].x,r[1].y],u_coords_bottom:[r[3].x,r[3].y,r[2].x,r[2].y]};var a,s;};function Qi(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const Ji=(e,t,i,o,r,a,s,n,l,c,h,u,d)=>{const _=s.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+o,u_is_along_line:r,u_is_variable_anchor:a,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},eo=(e,i,o,r,a,s,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.e(Ji(e,i,o,r,a,s,n,l,c,h,u,d,p),{u_gamma_scale:r?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:1})},to=(e,i,o,r,a,s,n,l,c,h,u,d,_)=>t.e(eo(e,i,o,r,a,s,n,l,c,h,!0,u,0,_),{u_texsize_icon:d,u_texture_icon:1}),io=(e,t)=>({u_opacity:e,u_color:t}),oo=(e,i,o,r,a)=>t.e(function(e,i,o,r){const a=o.imageManager.getPattern(e.from.toString()),s=o.imageManager.getPattern(e.to.toString()),{width:n,height:l}=o.imageManager.getPixelSize(),c=Math.pow(2,r.tileID.overscaledZ),h=r.tileSize*Math.pow(2,o.transform.tileZoom)/c,u=h*(r.tileID.canonical.x+r.tileID.wrap*c),d=h*r.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:s.tl,u_pattern_br_b:s.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:s.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.aB(r,1,o.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(o,a,i,r),{u_opacity:e}),ro=(e,t)=>{},ao={fillExtrusion:(e,i)=>({u_lightpos:new t.bS(e,i.u_lightpos),u_lightpos_globe:new t.bS(e,i.u_lightpos_globe),u_lightintensity:new t.bf(e,i.u_lightintensity),u_lightcolor:new t.bS(e,i.u_lightcolor),u_vertical_gradient:new t.bf(e,i.u_vertical_gradient),u_opacity:new t.bf(e,i.u_opacity),u_fill_translate:new t.bT(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.bS(e,i.u_lightpos),u_lightpos_globe:new t.bS(e,i.u_lightpos_globe),u_lightintensity:new t.bf(e,i.u_lightintensity),u_lightcolor:new t.bS(e,i.u_lightcolor),u_vertical_gradient:new t.bf(e,i.u_vertical_gradient),u_height_factor:new t.bf(e,i.u_height_factor),u_opacity:new t.bf(e,i.u_opacity),u_fill_translate:new t.bT(e,i.u_fill_translate),u_image:new t.bO(e,i.u_image),u_texsize:new t.bT(e,i.u_texsize),u_pixel_coord_upper:new t.bT(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bT(e,i.u_pixel_coord_lower),u_scale:new t.bS(e,i.u_scale),u_fade:new t.bf(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.bT(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.bO(e,i.u_image),u_texsize:new t.bT(e,i.u_texsize),u_pixel_coord_upper:new t.bT(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bT(e,i.u_pixel_coord_lower),u_scale:new t.bS(e,i.u_scale),u_fade:new t.bf(e,i.u_fade),u_fill_translate:new t.bT(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.bT(e,i.u_world),u_fill_translate:new t.bT(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.bT(e,i.u_world),u_image:new t.bO(e,i.u_image),u_texsize:new t.bT(e,i.u_texsize),u_pixel_coord_upper:new t.bT(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bT(e,i.u_pixel_coord_lower),u_scale:new t.bS(e,i.u_scale),u_fade:new t.bf(e,i.u_fade),u_fill_translate:new t.bT(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.bf(e,i.u_camera_to_center_distance),u_scale_with_map:new t.bO(e,i.u_scale_with_map),u_pitch_with_map:new t.bO(e,i.u_pitch_with_map),u_extrude_scale:new t.bT(e,i.u_extrude_scale),u_device_pixel_ratio:new t.bf(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.bf(e,i.u_globe_extrude_scale),u_translate:new t.bT(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.bT(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.bT(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.bP(e,i.u_color),u_overlay:new t.bO(e,i.u_overlay),u_overlay_scale:new t.bf(e,i.u_overlay_scale)}),depth:ro,clippingMask:ro,heatmap:(e,i)=>({u_extrude_scale:new t.bf(e,i.u_extrude_scale),u_intensity:new t.bf(e,i.u_intensity),u_globe_extrude_scale:new t.bf(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.bQ(e,i.u_matrix),u_world:new t.bT(e,i.u_world),u_image:new t.bO(e,i.u_image),u_color_ramp:new t.bO(e,i.u_color_ramp),u_opacity:new t.bf(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.bO(e,i.u_image),u_latrange:new t.bT(e,i.u_latrange),u_exaggeration:new t.bf(e,i.u_exaggeration),u_altitudes:new t.bZ(e,i.u_altitudes),u_azimuths:new t.bZ(e,i.u_azimuths),u_accent:new t.bP(e,i.u_accent),u_method:new t.bO(e,i.u_method),u_shadows:new t.bY(e,i.u_shadows),u_highlights:new t.bY(e,i.u_highlights)}),hillshadePrepare:(e,i)=>({u_matrix:new t.bQ(e,i.u_matrix),u_image:new t.bO(e,i.u_image),u_dimension:new t.bT(e,i.u_dimension),u_zoom:new t.bf(e,i.u_zoom),u_unpack:new t.bR(e,i.u_unpack)}),colorRelief:(e,i)=>({u_image:new t.bO(e,i.u_image),u_unpack:new t.bR(e,i.u_unpack),u_dimension:new t.bT(e,i.u_dimension),u_elevation_stops:new t.bO(e,i.u_elevation_stops),u_color_stops:new t.bO(e,i.u_color_stops),u_opacity:new t.bf(e,i.u_opacity)}),line:(e,i)=>({u_translation:new t.bT(e,i.u_translation),u_ratio:new t.bf(e,i.u_ratio),u_device_pixel_ratio:new t.bf(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bT(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.bT(e,i.u_translation),u_ratio:new t.bf(e,i.u_ratio),u_device_pixel_ratio:new t.bf(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bT(e,i.u_units_to_pixels),u_image:new t.bO(e,i.u_image),u_image_height:new t.bf(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.bT(e,i.u_translation),u_texsize:new t.bT(e,i.u_texsize),u_ratio:new t.bf(e,i.u_ratio),u_device_pixel_ratio:new t.bf(e,i.u_device_pixel_ratio),u_image:new t.bO(e,i.u_image),u_units_to_pixels:new t.bT(e,i.u_units_to_pixels),u_scale:new t.bS(e,i.u_scale),u_fade:new t.bf(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.bT(e,i.u_translation),u_ratio:new t.bf(e,i.u_ratio),u_device_pixel_ratio:new t.bf(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bT(e,i.u_units_to_pixels),u_patternscale_a:new t.bT(e,i.u_patternscale_a),u_patternscale_b:new t.bT(e,i.u_patternscale_b),u_sdfgamma:new t.bf(e,i.u_sdfgamma),u_image:new t.bO(e,i.u_image),u_tex_y_a:new t.bf(e,i.u_tex_y_a),u_tex_y_b:new t.bf(e,i.u_tex_y_b),u_mix:new t.bf(e,i.u_mix)}),raster:(e,i)=>({u_tl_parent:new t.bT(e,i.u_tl_parent),u_scale_parent:new t.bf(e,i.u_scale_parent),u_buffer_scale:new t.bf(e,i.u_buffer_scale),u_fade_t:new t.bf(e,i.u_fade_t),u_opacity:new t.bf(e,i.u_opacity),u_image0:new t.bO(e,i.u_image0),u_image1:new t.bO(e,i.u_image1),u_brightness_low:new t.bf(e,i.u_brightness_low),u_brightness_high:new t.bf(e,i.u_brightness_high),u_saturation_factor:new t.bf(e,i.u_saturation_factor),u_contrast_factor:new t.bf(e,i.u_contrast_factor),u_spin_weights:new t.bS(e,i.u_spin_weights),u_coords_top:new t.bR(e,i.u_coords_top),u_coords_bottom:new t.bR(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.bO(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bO(e,i.u_is_size_feature_constant),u_size_t:new t.bf(e,i.u_size_t),u_size:new t.bf(e,i.u_size),u_camera_to_center_distance:new t.bf(e,i.u_camera_to_center_distance),u_pitch:new t.bf(e,i.u_pitch),u_rotate_symbol:new t.bO(e,i.u_rotate_symbol),u_aspect_ratio:new t.bf(e,i.u_aspect_ratio),u_fade_change:new t.bf(e,i.u_fade_change),u_label_plane_matrix:new t.bQ(e,i.u_label_plane_matrix),u_coord_matrix:new t.bQ(e,i.u_coord_matrix),u_is_text:new t.bO(e,i.u_is_text),u_pitch_with_map:new t.bO(e,i.u_pitch_with_map),u_is_along_line:new t.bO(e,i.u_is_along_line),u_is_variable_anchor:new t.bO(e,i.u_is_variable_anchor),u_texsize:new t.bT(e,i.u_texsize),u_texture:new t.bO(e,i.u_texture),u_translation:new t.bT(e,i.u_translation),u_pitched_scale:new t.bf(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.bO(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bO(e,i.u_is_size_feature_constant),u_size_t:new t.bf(e,i.u_size_t),u_size:new t.bf(e,i.u_size),u_camera_to_center_distance:new t.bf(e,i.u_camera_to_center_distance),u_pitch:new t.bf(e,i.u_pitch),u_rotate_symbol:new t.bO(e,i.u_rotate_symbol),u_aspect_ratio:new t.bf(e,i.u_aspect_ratio),u_fade_change:new t.bf(e,i.u_fade_change),u_label_plane_matrix:new t.bQ(e,i.u_label_plane_matrix),u_coord_matrix:new t.bQ(e,i.u_coord_matrix),u_is_text:new t.bO(e,i.u_is_text),u_pitch_with_map:new t.bO(e,i.u_pitch_with_map),u_is_along_line:new t.bO(e,i.u_is_along_line),u_is_variable_anchor:new t.bO(e,i.u_is_variable_anchor),u_texsize:new t.bT(e,i.u_texsize),u_texture:new t.bO(e,i.u_texture),u_gamma_scale:new t.bf(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bf(e,i.u_device_pixel_ratio),u_is_halo:new t.bO(e,i.u_is_halo),u_translation:new t.bT(e,i.u_translation),u_pitched_scale:new t.bf(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.bO(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bO(e,i.u_is_size_feature_constant),u_size_t:new t.bf(e,i.u_size_t),u_size:new t.bf(e,i.u_size),u_camera_to_center_distance:new t.bf(e,i.u_camera_to_center_distance),u_pitch:new t.bf(e,i.u_pitch),u_rotate_symbol:new t.bO(e,i.u_rotate_symbol),u_aspect_ratio:new t.bf(e,i.u_aspect_ratio),u_fade_change:new t.bf(e,i.u_fade_change),u_label_plane_matrix:new t.bQ(e,i.u_label_plane_matrix),u_coord_matrix:new t.bQ(e,i.u_coord_matrix),u_is_text:new t.bO(e,i.u_is_text),u_pitch_with_map:new t.bO(e,i.u_pitch_with_map),u_is_along_line:new t.bO(e,i.u_is_along_line),u_is_variable_anchor:new t.bO(e,i.u_is_variable_anchor),u_texsize:new t.bT(e,i.u_texsize),u_texsize_icon:new t.bT(e,i.u_texsize_icon),u_texture:new t.bO(e,i.u_texture),u_texture_icon:new t.bO(e,i.u_texture_icon),u_gamma_scale:new t.bf(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bf(e,i.u_device_pixel_ratio),u_is_halo:new t.bO(e,i.u_is_halo),u_translation:new t.bT(e,i.u_translation),u_pitched_scale:new t.bf(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.bf(e,i.u_opacity),u_color:new t.bP(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.bf(e,i.u_opacity),u_image:new t.bO(e,i.u_image),u_pattern_tl_a:new t.bT(e,i.u_pattern_tl_a),u_pattern_br_a:new t.bT(e,i.u_pattern_br_a),u_pattern_tl_b:new t.bT(e,i.u_pattern_tl_b),u_pattern_br_b:new t.bT(e,i.u_pattern_br_b),u_texsize:new t.bT(e,i.u_texsize),u_mix:new t.bf(e,i.u_mix),u_pattern_size_a:new t.bT(e,i.u_pattern_size_a),u_pattern_size_b:new t.bT(e,i.u_pattern_size_b),u_scale_a:new t.bf(e,i.u_scale_a),u_scale_b:new t.bf(e,i.u_scale_b),u_pixel_coord_upper:new t.bT(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bT(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.bf(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.bO(e,i.u_texture),u_ele_delta:new t.bf(e,i.u_ele_delta),u_fog_matrix:new t.bQ(e,i.u_fog_matrix),u_fog_color:new t.bP(e,i.u_fog_color),u_fog_ground_blend:new t.bf(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.bf(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.bP(e,i.u_horizon_color),u_horizon_fog_blend:new t.bf(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.bf(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.bf(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.bO(e,i.u_texture),u_terrain_coords_id:new t.bf(e,i.u_terrain_coords_id),u_ele_delta:new t.bf(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.bf(e,i.u_input),u_output_expected:new t.bf(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.bS(e,i.u_sun_pos),u_atmosphere_blend:new t.bf(e,i.u_atmosphere_blend),u_globe_position:new t.bS(e,i.u_globe_position),u_globe_radius:new t.bf(e,i.u_globe_radius),u_inv_proj_matrix:new t.bQ(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.bP(e,i.u_sky_color),u_horizon_color:new t.bP(e,i.u_horizon_color),u_horizon:new t.bT(e,i.u_horizon),u_horizon_normal:new t.bT(e,i.u_horizon_normal),u_sky_horizon_blend:new t.bf(e,i.u_sky_horizon_blend),u_sky_blend:new t.bf(e,i.u_sky_blend)})};class so{constructor(e,t,i){this.context=e;const o=e.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const no={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class lo{constructor(e,t,i,o){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=o,this.context=e;const r=e.gl;this.buffer=r.createBuffer(),e.bindVertexBuffer.set(this.buffer),r.bufferData(r.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(s,l.LINES,Ut.disabled,Vt.disabled,e.colorModeForRenderPass(),Zt.disabled,Fi(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),o.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!a||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.b_;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:S,angle:E});}else $e(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===o.layout.get("text-rotation-alignment");De(c,e,a,O,j,v,h,i,l.toUnwrapped(),f.width,f.height,Z,t);}const $=a&&P||V,q=b||$?Yo:v?O:e.transform.clipSpaceToPixelsMatrix,W=p&&0!==o.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1);let H;H=p?c.iconsInText?to(T.kind,E,x,v,b,$,e,q,N,Z,z,k,I):eo(T.kind,E,x,v,b,$,e,q,N,Z,a,z,0,I):Ji(T.kind,E,x,v,b,$,e,q,N,Z,a,z,I);const X={program:S,buffers:u,uniformValues:H,projectionData:U,atlasTexture:D,atlasTextureIcon:F,atlasInterpolation:A,atlasInterpolationIcon:L,isSDF:p,hasHalo:W};if(y&&c.canOverlap){w=!0;const e=u.segments.get();for(const i of e)C.push({segments:new t.aL([i]),sortKey:i.sortKey,state:X,terrainData:R});}else C.push({segments:u.segments,sortKey:0,state:X,terrainData:R});}w&&C.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of C){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const r=i.uniformValues;i.hasHalo&&(r.u_is_halo=1,or(i.buffers,t.segments,o,e,i.program,T,u,d,r,i.projectionData,t.terrainData)),r.u_is_halo=0;}or(i.buffers,t.segments,o,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function or(e,t,i,o,r,a,s,n,l,c,h){const u=o.context;r.draw(u,u.gl.TRIANGLES,a,s,n,Zt.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,o.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function rr(e,i,o,r,a){const s=e.context,n=s.gl,l=Vt.disabled,c=new jt([n.ONE,n.ONE],t.be.transparent,[!0,!0,!0,!0]),h=i.getBucket(o);if(!h)return;const u=r.key;let d=o.heatmapFbos.get(u);d||(d=sr(s,i.tileSize,i.tileSize),o.heatmapFbos.set(u,d)),s.bindFramebuffer.set(d.framebuffer),s.viewport.set([0,0,i.tileSize,i.tileSize]),s.clear({color:t.be.transparent});const _=h.programConfigurations.get(o.id),p=e.useProgram("heatmap",_,!a),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),f=e.style.map.terrain.getTerrainData(r);p.draw(s,n.TRIANGLES,Ut.disabled,l,c,Zt.disabled,ji(i,e.transform.zoom,o.paint.get("heatmap-intensity"),1),f,m,o.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,o.paint,e.transform.zoom,_);}function ar(e,t,i,o,r){const a=e.context,s=a.gl,n=e.transform;a.setColorMode(e.colorModeForRenderPass());const l=nr(a,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,h.colorAttachment.get()),a.activeTexture.set(s.TEXTURE1),l.bind(s.LINEAR,s.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:r,applyGlobeMatrix:!o});e.useProgram("heatmapTexture").draw(a,s.TRIANGLES,Ut.disabled,Vt.disabled,e.colorModeForRenderPass(),Zt.disabled,Ni(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function sr(e,t,i){var o,r;const a=e.gl,s=a.createTexture();a.bindTexture(a.TEXTURE_2D,s),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR);const n=null!==(o=e.HALF_FLOAT)&&void 0!==o?o:a.UNSIGNED_BYTE,l=null!==(r=e.RGBA16F)&&void 0!==r?r:a.RGBA;a.texImage2D(a.TEXTURE_2D,0,l,t,i,0,a.RGBA,n,null);const c=e.createFramebuffer(t,i,!1,!1);return c.colorAttachment.set(s),c}function nr(e,i){return i.colorRampTexture||(i.colorRampTexture=new t.T(e,i.colorRamp,e.gl.RGBA)),i.colorRampTexture}function lr(e,t,i,o,r){if(!i||!o||!o.imageAtlas)return;const a=o.imageAtlas.patternPositions;let s=a[i.to.toString()],n=a[i.from.toString()];if(!s&&n&&(s=n),!n&&s&&(n=s),!s||!n){const e=r.getPaintProperty(t);s=a[e],n=a[e];}s&&n&&e.setConstantPatternPositions(s,n);}function cr(e,i,o,r,a,s,n,l){const c=e.context.gl,h="fill-pattern",u=o.paint.get(h),d=u&&u.constantOr(1),_=o.getCrossfadeParameters();let p,m,f,g,v;const b=e.transform,x=o.paint.get("fill-translate"),y=o.paint.get("fill-translate-anchor");n?(m=d&&!o.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",p=c.LINES):(m=d?"fillPattern":"fill",p=c.TRIANGLES);const w=u.constantOr(null);for(const u of r){const r=i.getTile(u);if(d&&!r.patternsLoaded())continue;const T=r.getBucket(o);if(!T)continue;const P=T.programConfigurations.get(o.id),C=e.useProgram(m,P),I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(u);d&&(e.context.activeTexture.set(c.TEXTURE0),r.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),P.updatePaintBuffers(_)),lr(P,h,w,r,o);const M=b.getProjectionData({overscaledTileID:u,applyGlobeMatrix:!l,applyTerrainMatrix:!0}),S=t.aC(b,r,x,y);if(n){g=T.indexBuffer2,v=T.segments2;const t=[c.drawingBufferWidth,c.drawingBufferHeight];f="fillOutlinePattern"===m&&d?Li(e,_,r,t,S):Ai(t,S);}else g=T.indexBuffer,v=T.segments,f=d?Di(e,_,r,S):{u_fill_translate:S};const E=e.stencilModeForClipping(u);C.draw(e.context,p,a,E,s,Zt.backCCW,f,I,M,o.id,T.layoutVertexBuffer,g,v,o.paint,e.transform.zoom,P);}}function hr(e,i,o,r,a,s,n,l){const c=e.context,h=c.gl,u="fill-extrusion-pattern",d=o.paint.get(u),_=d.constantOr(1),p=o.getCrossfadeParameters(),m=o.paint.get("fill-extrusion-opacity"),f=d.constantOr(null),g=e.transform;for(const d of r){const r=i.getTile(d),v=r.getBucket(o);if(!v)continue;const b=e.style.map.terrain&&e.style.map.terrain.getTerrainData(d),x=v.programConfigurations.get(o.id),y=e.useProgram(_?"fillExtrusionPattern":"fillExtrusion",x);_&&(e.context.activeTexture.set(h.TEXTURE0),r.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),x.updatePaintBuffers(p));const w=g.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!l,applyTerrainMatrix:!0});lr(x,u,f,r,o);const T=t.aC(g,r,o.paint.get("fill-extrusion-translate"),o.paint.get("fill-extrusion-translate-anchor")),P=o.paint.get("fill-extrusion-vertical-gradient"),C=_?zi(e,P,m,T,d,p,r):Ri(e,P,m,T);y.draw(c,c.gl.TRIANGLES,a,s,n,Zt.backCCW,C,b,w,o.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,o.paint,e.transform.zoom,x,e.style.map.terrain&&v.centroidVertexBuffer);}}function ur(e,t,i,o,r,a,s,n,l){var c;const h=e.style.projection,u=e.context,d=e.transform,_=u.gl,p=[`#define NUM_ILLUMINATION_SOURCES ${i.paint.get("hillshade-highlight-color").values.length}`],m=e.useProgram("hillshade",null,!1,p),f=!e.options.moving;for(const p of o){const o=t.getTile(p),g=o.fbo;if(!g)continue;const v=h.getMeshFromTileID(u,p.canonical,n,!0,"raster"),b=null===(c=e.style.map.terrain)||void 0===c?void 0:c.getTerrainData(p);u.activeTexture.set(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g.colorAttachment.get());const x=d.getProjectionData({overscaledTileID:p,aligned:f,applyGlobeMatrix:!l,applyTerrainMatrix:!0});m.draw(u,_.TRIANGLES,a,r[p.overscaledZ],s,Zt.backCCW,Zi(e,o,i),b,x,i.id,v.vertexBuffer,v.indexBuffer,v.segments);}}function dr(e,i,o,r,a,s,n,l,c){var h;const u=e.style.projection,d=e.context,_=e.transform,p=d.gl,m=e.useProgram("colorRelief"),f=!e.options.moving;let g=!0;for(const v of r){const r=i.getTile(v),b=r.dem;if(g){const e=p.getParameter(p.MAX_TEXTURE_SIZE),{elevationTexture:t,colorTexture:i}=o.getColorRampTextures(d,e,b.getUnpackVector());d.activeTexture.set(p.TEXTURE1),t.bind(p.NEAREST,p.CLAMP_TO_EDGE),d.activeTexture.set(p.TEXTURE4),i.bind(p.LINEAR,p.CLAMP_TO_EDGE),g=!1;}if(!b||!b.data)continue;const x=b.stride,y=b.getPixels();if(d.activeTexture.set(p.TEXTURE0),d.pixelStoreUnpackPremultiplyAlpha.set(!1),r.demTexture=r.demTexture||e.getTileTexture(x),r.demTexture){const e=r.demTexture;e.update(y,{premultiply:!1}),e.bind(p.LINEAR,p.CLAMP_TO_EDGE);}else r.demTexture=new t.T(d,y,p.RGBA,{premultiply:!1}),r.demTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE);const w=u.getMeshFromTileID(d,v.canonical,l,!0,"raster"),T=null===(h=e.style.map.terrain)||void 0===h?void 0:h.getTerrainData(v),P=_.getProjectionData({overscaledTileID:v,aligned:f,applyGlobeMatrix:!c,applyTerrainMatrix:!0});m.draw(d,p.TRIANGLES,s,a[v.overscaledZ],n,Zt.backCCW,Vi(o,r.dem),T,P,o.id,w.vertexBuffer,w.indexBuffer,w.segments);}}const _r=[new t.P(0,0),new t.P(t.$,0),new t.P(t.$,t.$),new t.P(0,t.$)];function pr(e,t,i,o,r,a,s,n,l=!1,c=!1){const h=o[o.length-1].overscaledZ,u=e.context,d=u.gl,_=e.useProgram("raster"),p=e.transform,m=e.style.projection,f=e.colorModeForRenderPass(),g=!e.options.moving;for(const v of o){const o=e.getDepthModeForSublayer(v.overscaledZ-h,1===i.paint.get("raster-opacity")?Ut.ReadWrite:Ut.ReadOnly,d.LESS),b=t.getTile(v);b.registerFadeDuration(i.paint.get("raster-fade-duration"));const x=t.findLoadedParent(v,0),y=t.findLoadedSibling(v),w=mr(b,x||y||null,t,i,e.transform,e.style.map.terrain);let T,P;const C="nearest"===i.paint.get("raster-resampling")?d.NEAREST:d.LINEAR;u.activeTexture.set(d.TEXTURE0),b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),u.activeTexture.set(d.TEXTURE1),x?(x.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),T=Math.pow(2,x.tileID.overscaledZ-b.tileID.overscaledZ),P=[b.tileID.canonical.x*T%1,b.tileID.canonical.y*T%1]):b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),b.texture.useMipmap&&u.extTextureFilterAnisotropic&&e.transform.pitch>20&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(v),M=p.getProjectionData({overscaledTileID:v,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),S=Yi(P||[0,0],T||1,w,i,n),E=m.getMeshFromTileID(u,v.canonical,a,s,"raster");_.draw(u,d.TRIANGLES,o,r?r[v.overscaledZ]:Vt.disabled,f,l?Zt.frontCCW:Zt.backCCW,S,I,M,i.id,E.vertexBuffer,E.indexBuffer,E.segments);}}function mr(e,i,o,r,a,n){const l=r.paint.get("raster-fade-duration");if(!n&&l>0){const r=s.now(),n=(r-e.timeAdded)/l,c=i?(r-i.timeAdded)/l:-1,h=o.getSource(),u=ge(a,{tileSize:h.tileSize,roundZoom:h.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-u)>Math.abs(e.tileID.overscaledZ-u),_=d&&e.refreshedUponExpiration?1:t.ag(d?n:1-c,0,1);return e.refreshedUponExpiration&&n>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-_}:{opacity:_,mix:0}}return {opacity:1,mix:0}}const fr=new t.be(1,0,0,1),gr=new t.be(0,1,0,1),vr=new t.be(0,0,1,1),br=new t.be(1,0,1,1),xr=new t.be(0,1,1,1);function yr(e,t,i,o){Tr(e,0,t+i/2,e.transform.width,i,o);}function wr(e,t,i,o){Tr(e,t-i/2,0,i,e.transform.height,o);}function Tr(e,t,i,o,r,a){const s=e.context,n=s.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,o*e.pixelRatio,r*e.pixelRatio),s.clear({color:a}),n.disable(n.SCISSOR_TEST);}function Pr(e,i,o){const r=e.context,a=r.gl,s=e.useProgram("debug"),n=Ut.disabled,l=Vt.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(o);r.activeTexture.set(a.TEXTURE0);const d=i.getTileByID(o.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(o).tileSize,m=512/Math.min(p,512)*(o.overscaledZ/e.transform.zoom)*.5;let f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=` => ${o.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,o=e.context.gl,r=e.debugOverlayCanvas.getContext("2d");r.clearRect(0,0,i.width,i.height),r.shadowColor="white",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle="white",r.textBaseline="top",r.font="bold 36px Open Sans, sans-serif",r.fillText(t,5,5),r.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:o,applyGlobeMatrix:!0,applyTerrainMatrix:!0});s.draw(r,a.TRIANGLES,n,l,jt.alphaBlended,Zt.disabled,Oi(t.be.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),s.draw(r,a.LINE_STRIP,n,l,c,Zt.disabled,Oi(t.be.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function Cr(e,t,i,o){const{isRenderingGlobe:r}=o,a=e.context,s=a.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain");a.bindFramebuffer.set(null),a.viewport.set([0,0,e.width,e.height]);for(const o of i){const i=t.getTerrainMesh(o.tileID),u=e.renderToTexture.getTexture(o),d=t.getTerrainData(o.tileID);a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,u.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(o.tileID.toUnwrapped()),m=Ci(_,p,e.style.sky,n.pitch,r),f=n.getProjectionData({overscaledTileID:o.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});h.draw(a,s.TRIANGLES,c,Vt.disabled,l,Zt.backCCW,m,d,f,"terrain",i.vertexBuffer,i.indexBuffer,i.segments);}}function Ir(e,i){if(!i.mesh){const o=new t.aK;o.emplaceBack(-1,-1),o.emplaceBack(1,-1),o.emplaceBack(1,1),o.emplaceBack(-1,1);const r=new t.aM;r.emplaceBack(0,1,2),r.emplaceBack(0,2,3),i.mesh=new wt(e.createVertexBuffer(o,Tt.members),e.createIndexBuffer(r),t.aL.simpleSegment(0,0,o.length,r.length));}return i.mesh}class Mr{constructor(e,i){this.context=new Ho(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:t.af(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=xe.maxUnderzooming+xe.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new vt;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.aK;i.emplaceBack(0,0),i.emplaceBack(t.$,0),i.emplaceBack(0,t.$),i.emplaceBack(t.$,t.$),this.tileExtentBuffer=e.createVertexBuffer(i,Tt.members),this.tileExtentSegments=t.aL.simpleSegment(0,0,4,2);const o=new t.aK;o.emplaceBack(0,0),o.emplaceBack(t.$,0),o.emplaceBack(0,t.$),o.emplaceBack(t.$,t.$),this.debugBuffer=e.createVertexBuffer(o,Tt.members),this.debugSegments=t.aL.simpleSegment(0,0,4,5);const r=new t.c5;r.emplaceBack(0,0,0,0),r.emplaceBack(t.$,0,t.$,0),r.emplaceBack(0,t.$,0,t.$),r.emplaceBack(t.$,t.$,t.$,t.$),this.rasterBoundsBuffer=e.createVertexBuffer(r,Ti.members),this.rasterBoundsSegments=t.aL.simpleSegment(0,0,4,2);const a=new t.aK;a.emplaceBack(0,0),a.emplaceBack(t.$,0),a.emplaceBack(0,t.$),a.emplaceBack(t.$,t.$),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(a,Tt.members),this.rasterBoundsSegmentsPosOnly=t.aL.simpleSegment(0,0,4,5);const s=new t.aK;s.emplaceBack(0,0),s.emplaceBack(1,0),s.emplaceBack(0,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,Tt.members),this.viewportSegments=t.aL.simpleSegment(0,0,4,2);const n=new t.c6;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.aM;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new Vt({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new wt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const o=t.L();t.bX(o,0,this.width,this.height,0,0,1),t.N(o,o,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const r={mainMatrix:o,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:o};this.useProgram("clippingMask",null,!0).draw(e,i.TRIANGLES,Ut.disabled,this.stencilClearMode,jt.disabled,Zt.disabled,null,null,r,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const o=this.context;o.setColorMode(jt.disabled),o.setDepthMode(Ut.disabled);const r={};for(const e of t)r[e.key]=this.nextStencilID++;this._renderTileMasks(r,t,i,!0),this._renderTileMasks(r,t,i,!1),this._tileClippingMaskIDs=r;}_renderTileMasks(e,t,i,o){const r=this.context,a=r.gl,s=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=s.getMeshFromTileID(this.context,c.canonical,o,!0,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!i,applyTerrainMatrix:!0});l.draw(r,a.TRIANGLES,Ut.disabled,new Vt({func:a.ALWAYS,mask:0},t,255,a.KEEP,a.KEEP,a.REPLACE),jt.disabled,i?Zt.disabled:Zt.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,o=this.transform,r=this.useProgram("depth"),a=this.getDepthModeFor3D(),s=ve(o,{tileSize:o.tileSize});for(const n of s){const s=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,!0,!0,"raster"),c=o.getProjectionData({overscaledTileID:n,applyGlobeMatrix:!0,applyTerrainMatrix:!0});r.draw(e,t.TRIANGLES,a,Vt.disabled,jt.disabled,Zt.backCCW,null,s,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new Vt({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new Vt({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(r>1){this.currentStencilSource=void 0,this.nextStencilID+r>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(this.clearStencil(),r>1){const e={},a={};for(let i=0;i0};for(const e in n){const t=n[e];t.used&&t.prepare(this.context),l[e]=t.getVisibleCoordinates(!1),c[e]=l[e].slice().reverse(),h[e]=t.getVisibleCoordinates(!0).reverse();}this.opaquePassCutoff=1/0;for(let e=0;ethis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.be.black:t.be.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,o=i.gl,r=((e,t,i)=>{const o=Math.cos(t.rollInRadians),r=Math.sin(t.rollInRadians),a=he(t),s=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-a*r)*i,(t.height/2+a*o)*i],u_horizon_normal:[-r,o],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:s}})(t,e.style.map.transform,e.pixelRatio),a=new Ut(o.LEQUAL,Ut.ReadWrite,[0,1]),s=Vt.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=Ir(i,t);l.draw(i,o.TRIANGLES,a,s,n,Zt.disabled,r,null,void 0,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=a.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[a[this.currentLayer]],t=n[e.source],i=l[e.source];this._renderTileClippingMasks(e,i,!1),this.renderLayer(this,t,e,i,u);}this.renderPass="translucent";let d=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:o,u_inv_proj_matrix:r}))(c,u,[p[0],p[1],p[2]],d,_),f=Ir(r,i);s.draw(r,a.TRIANGLES,n,Vt.disabled,jt.alphaBlended,Zt.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const o=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.sourceCaches[i.source]]:[])),r=o.filter((e=>"vector"===e.getSource().type)),a=o.filter((e=>"vector"!==e.getSource().type)),s=e=>{(!i||i.getSource().maxzooms(e))),i||a.forEach((e=>s(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let o=0;ou.getElevation(a,e,t):null;er(s,d,_,c,h,f,i,p,g,t.aC(h,e,n,l),a.toUnwrapped(),o);}}}(r,e,o,i,o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),a),0!==o.paint.get("icon-opacity").constantOr(1)&&ir(e,i,o,r,!1,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),o.layout.get("icon-rotation-alignment"),o.layout.get("icon-pitch-alignment"),o.layout.get("icon-keep-upright"),l,c,n),0!==o.paint.get("text-opacity").constantOr(1)&&ir(e,i,o,r,!0,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&(Ko(e,i,o,r,!0),Ko(e,i,o,r,!1));}(e,i,o,r,this.style.placement.variableOffsets,a):t.cb(o)?function(e,i,o,r,a){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:s}=a,n=o.paint.get("circle-opacity"),l=o.paint.get("circle-stroke-width"),c=o.paint.get("circle-stroke-opacity"),h=!o.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Ut.ReadOnly),m=Vt.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let a=0;ae.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:r,layoutVertexBuffer:a,indexBuffer:s,uniformValues:n,terrainData:l,projectionData:c}=t.state;r.draw(u,d.TRIANGLES,p,m,f,Zt.backCCW,n,l,c,o.id,a,s,t.segments,o.paint,e.transform.zoom,i);}}(e,i,o,r,a):t.cc(o)?function(e,i,o,r,a){if(0===o.paint.get("heatmap-opacity"))return;const s=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=a;if(e.style.map.terrain){for(const t of r){const r=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?rr(e,r,o,t,l):"translucent"===e.renderPass&&ar(e,o,t,n,l));}s.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,o,r){const a=e.context,s=a.gl,n=e.transform,l=Vt.disabled,c=new jt([s.ONE,s.ONE],t.be.transparent,[!0,!0,!0,!0]);((function(e,i,o){const r=e.gl;e.activeTexture.set(r.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let a=o.heatmapFbos.get(t.c1);a?(r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer)):(a=sr(e,i.width/4,i.height/4),o.heatmapFbos.set(t.c1,a));}))(a,e,o),a.clear({color:t.be.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return !1;if(!e.from||!e.to)return !0;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=!1,o=[]){this.cache=this.cache||{};const r=!!this.style.map.terrain,a=this.style.projection,s=i?xt.projectionMercator:a.shaderPreludeCode,n=i?Pt:a.shaderDefine,l=e+(t?t.cacheKey:"")+`/${i?Ct:a.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(r?"/terrain":"")+(o?`/${o.join("/")}`:"");return this.cache[l]||(this.cache[l]=new Si(this.context,xt[e],t,ao[e],this._showOverdrawInspector,r,s,n,o)),this.cache[l]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Sr(e,t){let i,o=!1,r=null,a=null;const s=()=>{r=null,o&&(e.apply(a,i),r=setTimeout(s,t),o=!1);};return (...e)=>(o=!0,a=this,i=e,r||s(),r)}class Er{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(!this._isValidHash(e))return !1;const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let o=window.location.hash.replace(i,"");o.startsWith("#&")?o=o.slice(0,1)+o.slice(2):"#"===o&&(o="");let r=window.location.href.replace(/(#.+)?$/,o);r=r.replace("&&","&"),window.history.replaceState(window.history.state,null,r);},this._updateHash=Sr(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,o=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),r=Math.pow(10,o),a=Math.round(t.lng*r)/r,s=Math.round(t.lat*r)/r,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${a}/${s}/${i}`:`${i}/${s}/${a}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const o=i.split("=")[0];return o===e?(t=!0,`${o}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return !1;try{new t.S(+e[2],+e[1]);}catch(e){return !1}const i=+e[0],o=+(e[3]||0),r=+(e[4]||0);return i>=this._map.getMinZoom()&&i<=this._map.getMaxZoom()&&o>=-180&&o<=180&&r>=this._map.getMinPitch()&&r<=this._map.getMaxPitch()}}const Rr={linearity:.3,easing:t.cl(0,0,.3,1)},zr=t.e({deceleration:2500,maxSpeed:1400},Rr),Dr=t.e({deceleration:20,maxSpeed:1400},Rr),Ar=t.e({deceleration:1e3,maxSpeed:360},Rr),Lr=t.e({deceleration:1e3,maxSpeed:90},Rr),kr=t.e({deceleration:1e3,maxSpeed:360},Rr);class Fr{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:s.now(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=s.now();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const o=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,r={};if(i.pan.mag()){const a=Or(i.pan.mag(),o,t.e({},zr,e||{})),s=i.pan.mult(a.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(s,this._map.transform);r.center=n.easingCenter,r.offset=n.easingOffset,Br(r,a);}if(i.zoom){const e=Or(i.zoom,o,Dr);r.zoom=this._map.transform.zoom+e.amount,Br(r,e);}if(i.bearing){const e=Or(i.bearing,o,Ar);r.bearing=this._map.transform.bearing+t.ag(e.amount,-179,179),Br(r,e);}if(i.pitch){const e=Or(i.pitch,o,Lr);r.pitch=this._map.transform.pitch+e.amount,Br(r,e);}if(i.roll){const e=Or(i.roll,o,kr);r.roll=this._map.transform.roll+t.ag(e.amount,-179,179),Br(r,e);}if(r.zoom||r.bearing){const e=void 0===i.pinchAround?i.around:i.pinchAround;r.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.e(r,{noMoveStart:!0})}}function Br(e,t){(!e.duration||e.durationi.unproject(e))),l=a.reduce(((e,t,i,o)=>e.add(t.div(o.length))),new t.P(0,0));super(e,{points:a,point:l,lngLats:s,lngLat:i.unproject(l),originalEvent:o}),this._defaultPrevented=!1;}}class Zr extends t.l{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=!1;}}class Ur{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new Zr(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new jr(e.type,this._map,e))}mouseup(e){this._map.fire(new jr(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new jr(e.type,this._map,e));}dblclick(e){return this._firePreventable(new jr(e.type,this._map,e))}mouseover(e){this._map.fire(new jr(e.type,this._map,e));}mouseout(e){this._map.fire(new jr(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Nr(e.type,this._map,e))}touchmove(e){this._map.fire(new Nr(e.type,this._map,e));}touchend(e){this._map.fire(new Nr(e.type,this._map,e));}touchcancel(e){this._map.fire(new Nr(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Gr{constructor(e){this._map=e;}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new jr(e.type,this._map,e));}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new jr("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new jr(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Vr{constructor(e){this._map=e;}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return {lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class $r{constructor(e,t){this._map=e,this._tr=new Vr(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(n.disableDrag(),this._startPos=this._lastPos=t,this._active=!0);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(o,r,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.l(e,{originalEvent:i}))}}function qr(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let o=0;othis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){const i=new t.P(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=qr(o,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const o=qr(i,t);for(const e in this.touches){const t=o[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Hr{constructor(e){this.singleTap=new Wr(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const o=this.singleTap.touchend(e,t,i);if(o){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(o)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}}}class Xr{constructor(e){this._tr=new Vr(e),this._zoomIn=new Hr({numTouches:1,numTaps:2}),this._zoomOut=new Hr({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const o=this._zoomIn.touchend(e,t,i),r=this._zoomOut.touchend(e,t,i),a=this._tr;return o?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom+1,around:a.unproject(o)},{originalEvent:e})}):r?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom-1,around:a.unproject(r)},{originalEvent:e})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class Kr{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0));}dragMove(e,t){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const o=Array.isArray(t)?t[0]:t;return !this._moved&&o.dist(i)!0}),t=new ta){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t;}_executeRelevantHandler(e,t,i){return e instanceof MouseEvent?t(e):"undefined"!=typeof TouchEvent&&e instanceof TouchEvent?i(e):void 0}startMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.startMove(e)),(e=>this.oneFingerTouchMoveStateManager.startMove(e)));}endMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.endMove(e)),(e=>this.oneFingerTouchMoveStateManager.endMove(e)));}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}const oa=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};class ra{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=!1,this._touches={},this._sum=new t.P(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,o){o.length>0&&(this._active=!0);const r=qr(o,i),a=new t.P(0,0),s=new t.P(0,0);let n=0;for(const e in r){const t=r[e],i=this._touches[e];i&&(a._add(t),s._add(t.sub(i)),n++,r[e]=t);}if(this._touches=r,this._shouldBePrevented(n)||!s.mag())return;const l=s.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class da extends aa{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,ua(e[0].sub(e[1]))&&(this._valid=!1);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const o=e[0].sub(this._lastPoints[0]),r=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const o=e.mag()>=2,r=t.mag()>=2;if(!o&&!r)return;if(!o||!r)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const a=e.y>0==t.y>0;return ua(e)&&ua(t)&&a}}const _a={panStep:100,bearingStep:15,pitchStep:10};class pa{constructor(e){this._tr=new Vr(e);const t=_a;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1;}reset(){this._active=!1;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,o=0,r=0,a=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),r=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),r=1);break;case 38:e.shiftKey?o=1:(e.preventDefault(),a=-1);break;case 40:e.shiftKey?o=-1:(e.preventDefault(),a=1);break;default:return}return this._rotationDisabled&&(i=0,o=0),{cameraAnimation:s=>{const n=this._tr;s.easeTo({duration:300,easeId:"keyboardHandler",easing:ma,zoom:t?Math.round(n.zoom)+t*(e.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+o*this._pitchStep,offset:[-r*this._panStep,-a*this._panStep],center:n.center},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function ma(e){return e*(2-e)}const fa=4.000244140625,ga=1/450;class va{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new Vr(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=ga;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=!1);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=s.now(),o=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%fa==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":o>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(o*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=n.mousePos(this._map.getCanvas(),e),o=this._tr;this._aroundPoint=this._aroundCenter?o.transform.locationToScreenPoint(t.S.convert(o.center)):i,this._frameId||(this._frameId=!0,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>fa?this._wheelZoomRate:this._defaultZoomRate;let o=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==o&&(o=1/o);const r="number"!=typeof this._targetZoom?e.scale:t.ae(this._targetZoom);this._targetZoom=e.getConstrained(e.getCameraLngLat(),t.aj(r*o)).zoom,"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,o=this._startZoom,r=this._easing;let a,n=!1;if("wheel"===this._type&&o&&r){const e=s.now()-this._lastWheelEventTime,l=Math.min((e+5)/200,1),c=r(l);a=t.C.number(o,i,c),l<1?this._frameId||(this._frameId=!0):n=!0;}else a=i,n=!0;return this._active=!0,n&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=a,{noInertia:!0,needsRenderFrame:!n,zoomDelta:a-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.cn;if(this._prevEase){const e=this._prevEase,o=(s.now()-e.start)/e.duration,r=e.easing(o+.01)-e.easing(o),a=.27/Math.sqrt(r*r+1e-4)*.01,n=Math.sqrt(.0729-a*a);i=t.cl(a,n,.25,1);}return this._prevEase={start:s.now(),duration:e,easing:i},i}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class ba{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class xa{constructor(e){this._tr=new Vr(e),this.reset();}reset(){this._active=!1;}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ya{constructor(){this._tap=new Hr({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const o=t[0],r=e.timeStamp-this._tapTime<500,a=this._tapPoint.dist(o)<30;r&&a?i.length>0&&(this._swipePoint=o,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const o=t[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,e.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const o=this._tap.touchend(e,t,i);o&&(this._tapTime=e.timeStamp,this._tapPoint=o);}}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class wa{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Ta{constructor(e,t,i,o){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=o;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Pa{constructor(e,t,i,o){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class Ca{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=!1;}isActive(){return !1}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=n.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),o=document.createElement("div");o.className="maplibregl-desktop-message",o.textContent=t,this._container.appendChild(o);const r=document.createElement("div");r.className="maplibregl-mobile-message",r.textContent=i,this._container.appendChild(r),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(n.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=!0;}disable(){this._enabled=!1,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.l("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const Ia=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Ma extends t.l{}function Sa(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class Ea{constructor(e,i){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,i)=>{if("blur"===e.type)return void this.stop(!0);this._updatingCamera=!0;const o="renderFrame"===e.type?void 0:e,r={needsRenderFrame:!1},a={},s={};for(const{handlerName:l,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let u;if(this._blockedByActive(s,h,l))c.reset();else if(c[i||e.type]){if(t.co(e,i||e.type)){const t=n.mousePos(this._map.getCanvas(),e);u=c[i||e.type](e,t);}else if(t.cp(e,i||e.type)){const t=this._getMapTouches(e.touches),o=n.touchPos(this._map.getCanvas(),t);u=c[i||e.type](e,o,t);}else t.cq(i||e.type)||(u=c[i||e.type](e));this.mergeHandlerResult(r,a,u,l,o),u&&u.needsRenderFrame&&this._triggerRenderFrame();}(u||c.isActive())&&(s[l]=c);}const l={};for(const e in this._previousActiveHandlers)s[e]||(l[e]=o);this._previousActiveHandlers=s,(Object.keys(l).length||Sa(r))&&(this._changes.push([r,a,l]),this._triggerRenderFrame()),(Object.keys(s).length||Sa(r))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:c}=r;c&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],c(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Fr(e),this._bearingSnap=i.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(i);const o=this._el;this._listeners=[[o,"touchstart",{passive:!0}],[o,"touchmove",{passive:!1}],[o,"touchend",void 0],[o,"touchcancel",void 0],[o,"mousedown",void 0],[o,"mousemove",void 0],[o,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[o,"mouseover",void 0],[o,"mouseout",void 0],[o,"dblclick",void 0],[o,"click",void 0],[o,"keydown",{capture:!1}],[o,"keyup",void 0],[o,"wheel",{passive:!1}],[o,"contextmenu",void 0],[window,"blur",void 0]];for(const[e,t,i]of this._listeners)n.addEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)n.removeEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const i=this._map,o=i.getCanvasContainer();this._add("mapEvent",new Ur(i,e));const r=i.boxZoom=new $r(i,e);this._add("boxZoom",r),e.interactive&&e.boxZoom&&r.enable();const a=i.cooperativeGestures=new Ca(i,e.cooperativeGestures);this._add("cooperativeGestures",a),e.cooperativeGestures&&a.enable();const s=new Xr(i),l=new xa(i);i.doubleClickZoom=new ba(l,s),this._add("tapZoom",s),this._add("clickZoom",l),e.interactive&&e.doubleClickZoom&&i.doubleClickZoom.enable();const c=new ya;this._add("tapDragZoom",c);const h=i.touchPitch=new da(i);this._add("touchPitch",h),e.interactive&&e.touchPitch&&i.touchPitch.enable(e.touchPitch);const u=()=>i.project(i.getCenter()),d=function({enable:e,clickTolerance:i,aroundCenter:o=!0,minPixelCenterThreshold:r=100,rotateDegreesPerPixelMoved:a=.8},s){const l=new ea({checkCorrectEvent:e=>0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:i,move:(e,i)=>{const n=s();if(o&&Math.abs(n.y-e.y)>r)return {bearingDelta:t.cm(new t.P(e.x,i.y),i,n)};let l=(i.x-e.x)*a;return o&&i.y0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)});return new Kr({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:o,enable:e,assignEvents:oa})}(e),p=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3},o){const r=new ea({checkCorrectEvent:e=>2===n.mouseButton(e)&&e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>{const r=o();let a=(t.x-e.x)*i;return t.y0===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:i,enable:e,assignEvents:oa})}(e),f=new ra(e,i);i.dragPan=new wa(o,m,f),this._add("mousePan",m),this._add("touchPan",f,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&i.dragPan.enable(e.dragPan);const g=new ha,v=new la;i.touchZoomRotate=new Pa(o,v,g,c),this._add("touchRotate",g,["touchPan","touchZoom"]),this._add("touchZoom",v,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&i.touchZoomRotate.enable(e.touchZoomRotate);const b=i.scrollZoom=new va(i,(()=>this._triggerRenderFrame()));this._add("scrollZoom",b,["mousePan"]),e.interactive&&e.scrollZoom&&i.scrollZoom.enable(e.scrollZoom);const x=i.keyboard=new pa(i);this._add("keyboard",x),e.interactive&&e.keyboard&&i.keyboard.enable(),this._add("blockableMapEvent",new Gr(i));}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(Ia(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const o in e)if(o!==i&&(!t||t.indexOf(o)<0))return !0;return !1}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,o,r,a){if(!o)return;t.e(e,o);const s={handlerName:r,originalEvent:o.originalEvent||a};void 0!==o.zoomDelta&&(i.zoom=s),void 0!==o.panDelta&&(i.drag=s),void 0!==o.rollDelta&&(i.roll=s),void 0!==o.pitchDelta&&(i.pitch=s),void 0!==o.bearingDelta&&(i.rotate=s);}_applyChanges(){const e={},i={},o={};for(const[r,a,s]of this._changes)r.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(r.panDelta)),r.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+r.zoomDelta),r.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+r.bearingDelta),r.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+r.pitchDelta),r.rollDelta&&(e.rollDelta=(e.rollDelta||0)+r.rollDelta),void 0!==r.around&&(e.around=r.around),void 0!==r.pinchAround&&(e.pinchAround=r.pinchAround),r.noInertia&&(e.noInertia=r.noInertia),t.e(i,a),t.e(o,s);this._updateMapTransform(e,i,o),this._changes=[];}_updateMapTransform(e,t,i){const o=this._map,r=o._getTransformForUpdate(),a=o.terrain;if(!(Sa(e)||a&&this._terrainMovement))return this._fireEvents(t,i,!0);o._stop(!0);let{panDelta:s,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;void 0!==d&&(u=d),u=u||o.transform.centerPoint,a&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const _={panDelta:s,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const p=u.distSqr(r.centerPoint)<.01?r.center:r.screenPointToLocation(s?u.sub(s):u);a?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._terrainMovement||!t.drag&&!t.zoom?t.drag&&this._terrainMovement?r.setCenter(r.screenPointToLocation(r.centerPoint.sub(s))):this._map.cameraHelper.handleMapControlsPan(_,r,p):(this._terrainMovement=!0,this._map._elevationFreeze=!0,this._map.cameraHelper.handleMapControlsPan(_,r,p))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._map.cameraHelper.handleMapControlsPan(_,r,p)),o._applyUpdatedTransform(r),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0);}_fireEvents(e,i,o){const r=Ia(this._eventsInProgress),a=Ia(e),n={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(n[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!r&&a&&this._fireEvent("movestart",a.originalEvent);for(const e in n)this._fireEvent(e,n[e]);a&&this._fireEvent("move",a.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const l={};let c;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:o}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],c=i[t]||o,l[`${e}end`]=c);}for(const e in l)this._fireEvent(e,l[e]);const h=Ia(this._eventsInProgress),u=(r||a)&&!h;if(u&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(o&&u){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new Ma("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}class Ra extends t.E{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((s.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=i.bearingSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.S(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,o){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},i),o)}panTo(e,i,o){return this.easeTo(t.e({center:e},i),o)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,o){return this.easeTo(t.e({zoom:e},i),o)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.l("movestart",i)).fire(new t.l("move",i)).fire(new t.l("moveend",i))),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,o){return this.easeTo(t.e({bearing:e},i),o)}resetNorth(e,i){return this.rotateTo(0,t.e({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){f.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,o={}){this._moving=!0,i||o.moving||this.fire(new t.l("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.l("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.l("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.l("pitchstart",e)),this._rolling&&!o.rolling&&this.fire(new t.l("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0;}_updateElevation(e){this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.C.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),o=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:o,zoom:r,roll:a,pitch:s,bearing:n,elevation:l}=e(t);o&&t.setCenter(o),void 0!==l&&t.setElevation(l),void 0!==r&&t.setZoom(r),void 0!==a&&t.setRoll(a),void 0!==s&&t.setPitch(s),void 0!==n&&t.setBearing(n),i.apply(t);}this.transform.apply(i);}_fireMoveEvents(e){this.fire(new t.l("move",e)),this._zooming&&this.fire(new t.l("zoom",e)),this._rotating&&this.fire(new t.l("rotate",e)),this._pitching&&this.fire(new t.l("pitch",e)),this._rolling&&this.fire(new t.l("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const o=this._zooming,r=this._rotating,a=this._pitching,s=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,o&&this.fire(new t.l("zoomend",e)),r&&this.fire(new t.l("rotateend",e)),a&&this.fire(new t.l("pitchend",e)),s&&this.fire(new t.l("rollend",e)),this.fire(new t.l("moveend",e));}flyTo(e,i){if(!e.essential&&s.prefersReducedMotion){const o=t.Q(e,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(o,i)}this.stop(),e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.cn},e);const o=this._getTransformForUpdate(),r=o.bearing,a=o.pitch,n=o.roll,l=o.padding,c="bearing"in e?this._normalizeBearing(e.bearing,r):r,h="pitch"in e?+e.pitch:a,u="roll"in e?this._normalizeBearing(e.roll,n):n,d="padding"in e?e.padding:o.padding,_=t.P.convert(e.offset);let p=o.centerPoint.add(_);const m=o.screenPointToLocation(p),f=this.cameraHelper.handleFlyTo(o,{bearing:c,pitch:h,roll:u,padding:d,locationAtOffset:m,offsetAsPoint:_,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(o.width,o.height),b=v/f.scaleOfZoom,x=f.pixelPathLength;"number"==typeof f.scaleOfMinZoom&&(g=Math.sqrt(v/f.scaleOfMinZoom/x*2));const y=g*g;function w(e){const t=(b*b-v*v+(e?-1:1)*y*y*x*x)/(2*(e?b:v)*y*x);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function P(e){return (Math.exp(e)+Math.exp(-e))/2}const C=w(!1);let I=function(e){return P(C)/P(C+g*e)},M=function(e){return v*((P(C)*(T(t=C+g*e)/P(t))-T(C))/y)/x;var t;},S=(w(!0)-C)/g;if(Math.abs(x)<2e-6||!isFinite(S)){if(Math.abs(v-b)<1e-6)return this.easeTo(e,i);const t=b0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*S/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=r!==c,this._pitching=h!==a,this._rolling=u!==n,this._padding=!o.isPaddingEqual(d),this._prepareEase(i,!1),this.terrain&&this._prepareElevation(f.targetCenter),this._ease((s=>{const m=s*S,g=1/I(m),v=M(m);this._rotating&&o.setBearing(t.C.number(r,c,s)),this._pitching&&o.setPitch(t.C.number(a,h,s)),this._rolling&&o.setRoll(t.C.number(n,u,s)),this._padding&&(o.interpolatePadding(l,d,s),p=o.centerPoint.add(_)),f.easeFunc(s,g,v,p),this.terrain&&!e.freezeElevation&&this._updateElevation(s),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=s.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.aN(e,-180,180);const o=Math.abs(e-i);return Math.abs(e-360-i)MapLibre'};class Da{constructor(e=za){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=n.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=n.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=n.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.sourceCaches;for(const i in t){const o=t[i];if(o.used||o.usedForTerrain){const t=o.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let o=i+1;o=0)return !1;return !0}));const i=e.join(" | ");i!==this._attribHTML&&(this._attribHTML=i,e.length?(this._innerContainer.innerHTML=n.sanitize(i),this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Aa{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=n.create("div","maplibregl-ctrl");const t=n.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){n.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0;}}class La{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}var ka=t.aI([{name:"a_pos3d",type:"Int16",components:3}]);class Fa extends t.E{constructor(e){super(),this._lastTilesetChange=s.now(),this.sourceCache=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize;}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null;}update(e,i){this.sourceCache.update(e,i),this._renderableTilesKeys=[];const o={};for(const r of ve(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:i,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))o[r.key]=!0,this._renderableTilesKeys.push(r.key),this._tiles[r.key]||(r.terrainRttPosMatrix32f=new Float64Array(16),t.bX(r.terrainRttPosMatrix32f,0,t.$,t.$,0,0,1),this._tiles[r.key]=new re(r,this.tileSize),this._lastTilesetChange=s.now());for(const e in this._tiles)o[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e,t){return t?this._getTerrainCoordsForTileRanges(e,t):this._getTerrainCoordsForRegularTile(e)}_getTerrainCoordsForRegularTile(e){const i={};for(const o of this._renderableTilesKeys){const r=this._tiles[o].tileID,a=e.clone(),s=t.b9();if(r.canonical.equals(e.canonical))t.bX(s,0,t.$,t.$,0,0,1);else if(r.canonical.isChildOf(e.canonical)){const i=r.canonical.z-e.canonical.z,o=r.canonical.x-(r.canonical.x>>i<>i<>i;t.bX(s,0,n,n,0,0,1),t.M(s,s,[-o*n,-a*n,0]);}else {if(!e.canonical.isChildOf(r.canonical))continue;{const i=e.canonical.z-r.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i;t.bX(s,0,t.$,t.$,0,0,1),t.M(s,s,[o*n,a*n,0]),t.N(s,s,[1/2**i,1/2**i,0]);}}a.terrainRttPosMatrix32f=new Float32Array(s),i[o]=a;}return i}_getTerrainCoordsForTileRanges(e,i){const o={};for(const r of this._renderableTilesKeys){const a=this._tiles[r].tileID;if(!this._isWithinTileRanges(a,i))continue;const s=e.clone(),n=t.b9();if(a.canonical.z===e.canonical.z){const i=e.canonical.x-a.canonical.x,o=e.canonical.y-a.canonical.y;t.bX(n,0,t.$,t.$,0,0,1),t.M(n,n,[i*t.$,o*t.$,0]);}else if(a.canonical.z>e.canonical.z){const i=a.canonical.z-e.canonical.z,o=a.canonical.x-(a.canonical.x>>i<>i<>i),l=e.canonical.y-(a.canonical.y>>i),c=t.$>>i;t.bX(n,0,c,c,0,0,1),t.M(n,n,[-o*c+s*t.$,-r*c+l*t.$,0]);}else {const i=e.canonical.z-a.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i)-a.canonical.x,l=(e.canonical.y>>i)-a.canonical.y,c=t.$<i.maxzoom&&(o=i.maxzoom),o=i.minzoom&&(!r||!r.dem);)r=this.sourceCache.getTileByID(e.scaledTo(o--).key);return r}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}_isWithinTileRanges(e,t){return t[e.canonical.z]&&e.canonical.x>=t[e.canonical.z].minTileX&&e.canonical.x<=t[e.canonical.z].maxTileX&&e.canonical.y>=t[e.canonical.z].minTileY&&e.canonical.y<=t[e.canonical.z].maxTileY}}class Ba{constructor(e,t,i){this._meshCache={},this.painter=e,this.sourceCache=new Fa(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(e,i,o,r=t.$){var a;if(!(i>=0&&i=0&&oe.canonical.z&&(e.canonical.z>=o?r=e.canonical.z-o:t.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const a=e.canonical.x-(e.canonical.x>>r<>r<>8<<4|e>>8,i[t+3]=0;const o=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),r=new t.T(e,o,e.gl.RGBA,{premultiply:!1});return r.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=r,r}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(!0);const i=new Uint8Array(4),o=this.painter.context,r=o.gl,a=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),s=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);o.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),r.readPixels(a,n-s-1,1,1,r.RGBA,r.UNSIGNED_BYTE,i),o.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.sourceCache.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<0,r=o&&0===e.canonical.y,a=o&&e.canonical.y===(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const ja={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class Na{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new Oa(e.context,30,t.sourceCache.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.sourceCaches){this._coordsAscending[t]={};const i=e.sourceCaches[t].getVisibleCoordinates(),o=e.sourceCaches[t].getSource(),r=o instanceof X?o.terrainTileRanges:null;for(const e of i){const i=this.terrain.sourceCache.getTerrainCoords(e,r);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._coordsAscendingStr={};for(const t of e._order){const i=e._layers[t],o=i.source;if(ja[i.type]&&!this._coordsAscendingStr[o]){this._coordsAscendingStr[o]={};for(const e in this._coordsAscending[o])this._coordsAscendingStr[o][e]=this._coordsAscending[o][e].map((e=>e.key)).sort().join();}}for(const e of this._renderableTiles)for(const t in this._coordsAscendingStr){const i=this._coordsAscendingStr[t][e.tileID.key];i&&i!==e.rttCoords[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return !1;const o=Object.assign(Object.assign({},i),{isRenderingToTexture:!0}),r=e.type,a=this.painter,s=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(ja[r]&&(this._prevType&&ja[this._prevType]||this._stacks.push([]),this._prevType=r,this._stacks[this._stacks.length-1].push(e.id),!s))return !0;if(ja[this._prevType]||ja[r]&&s){this._prevType=r;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const r of this._renderableTiles){if(this.pool.isFull()&&(Cr(this.painter,this.terrain,this._rttTiles,o),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(r),r.rtt[e]){const t=this.pool.getObjectForId(r.rtt[e].id);if(t.stamp===r.rtt[e].stamp){this.pool.useObject(t);continue}}const s=this.pool.getOrCreateFreeObject();this.pool.useObject(s),this.pool.stampObject(s),r.rtt[e]={id:s.id,stamp:s.stamp},a.context.bindFramebuffer.set(s.fbo.framebuffer),a.context.clear({color:t.be.transparent,stencil:0}),a.currentStencilSource=void 0;for(let e=0;e{this.startMove(e,n.mousePos(this.element,e)),n.addEventListener(window,"mousemove",this.mousemove),n.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=e=>{this.move(e,n.mousePos(this.element,e));},this.mouseup=e=>{this._rotatePitchHanlder.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),n.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.addEventListener(window,"touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHanlder.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10,this.element=i;const r=new ia;this._rotatePitchHanlder=new Kr({clickTolerance:3,move:(e,r)=>{const a=i.getBoundingClientRect(),s=new t.P((a.bottom-a.top)/2,(a.right-a.left)/2);return {bearingDelta:t.cm(new t.P(e.x,r.y),r,s),pitchDelta:o?-.5*(r.y-e.y):void 0}},moveStateManager:r,enable:!0,assignEvents:()=>{}}),this.map=e,n.addEventListener(i,"mousedown",this.mousedown),n.addEventListener(i,"touchstart",this.touchstart,{passive:!1}),n.addEventListener(i,"touchcancel",this.reset);}startMove(e,t){this._rotatePitchHanlder.dragStart(e,t),n.disableDrag();}move(e,t){const i=this.map,{bearingDelta:o,pitchDelta:r}=this._rotatePitchHanlder.dragMove(e,t)||{};o&&i.setBearing(i.getBearing()+o),r&&i.setPitch(i.getPitch()+r);}off(){const e=this.element;n.removeEventListener(e,"mousedown",this.mousedown),n.removeEventListener(e,"touchstart",this.touchstart,{passive:!1}),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend),n.removeEventListener(e,"touchcancel",this.reset),this.offTemp();}offTemp(){n.enableDrag(),n.removeEventListener(window,"mousemove",this.mousemove),n.removeEventListener(window,"mouseup",this.mouseup),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend);}}let qa;function Wa(e,i,o,r=!1){if(r||!o.getCoveringTilesDetailsProvider().allowWorldCopies())return null==e?void 0:e.wrap();const a=new t.S(e.lng,e.lat);if(e=new t.S(e.lng,e.lat),i){const r=new t.S(e.lng-360,e.lat),a=new t.S(e.lng+360,e.lat),s=o.locationToScreenPoint(e).distSqr(i);o.locationToScreenPoint(r).distSqr(i)180;){const t=o.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=o.width&&t.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==a.lng&&o.isPointOnMapSurface(o.locationToScreenPoint(e))?e:a}const Ha={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Xa(e,t,i){const o=e.classList;for(const e in Ha)o.remove(`maplibregl-${i}-anchor-${e}`);o.add(`maplibregl-${i}-anchor-${t}`);}class Ka extends t.E{constructor(e){if(super(),this._onKeyPress=e=>{const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{if(!this._map)return;const t=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?void 0:e.type)||"render"===(null==e?void 0:e.type)&&!t)&&this._map.once("render",this._update),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let i="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?i=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(i=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),n.setTransform(this._element,`${Ha[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${i}`),s.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.l("dragstart"))),this.fire(new t.l("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.l("dragend")),this._state="inactive";},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||!1,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(null==e?void 0:e.opacity,null==e?void 0:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.P.convert(e&&e.offset||[0,0]);else {this._defaultMarker=!0,this._element=n.create("div");const i=n.createNS("http://www.w3.org/2000/svg","svg"),o=41,r=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${o}px`),i.setAttributeNS(null,"width",`${r}px`),i.setAttributeNS(null,"viewBox",`0 0 ${r} ${o}`);const a=n.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"stroke","none"),a.setAttributeNS(null,"stroke-width","1"),a.setAttributeNS(null,"fill","none"),a.setAttributeNS(null,"fill-rule","evenodd");const s=n.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"fill-rule","nonzero");const l=n.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"transform","translate(3.0, 29.0)"),l.setAttributeNS(null,"fill","#000000");const c=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const e of c){const t=n.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),l.appendChild(t);}const h=n.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);const u=n.createNS("http://www.w3.org/2000/svg","path");u.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(u);const d=n.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");const _=n.createNS("http://www.w3.org/2000/svg","path");_.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(_);const p=n.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const m=n.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(8.0, 8.0)");const f=n.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#000000"),f.setAttributeNS(null,"opacity","0.25"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962");const g=n.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#FFFFFF"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962"),m.appendChild(f),m.appendChild(g),s.appendChild(l),s.appendChild(h),s.appendChild(d),s.appendChild(p),s.appendChild(m),i.appendChild(s),i.setAttributeNS(null,"height",o*this._scale+"px"),i.setAttributeNS(null,"width",r*this._scale+"px"),this._element.appendChild(i),this._offset=t.P.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),Xa(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),n.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,o=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[o,-1*(t-i+o)],"bottom-right":[-o,-1*(t-i+o)],left:[i,-1*(t-i)],right:[-13.5,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=!1){var i,o;const r=null===(i=this._map)||void 0===i?void 0:i.terrain,a=this._map.transform.isLocationOccluded(this._lngLat);if(!r||a){const e=a?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const s=this._map,n=s.terrain.depthAtPoint(this._pos),l=s.terrain.getElevationForLngLatZoom(this._lngLat,s.transform.tileZoom);if(s.transform.lngLatToCameraDepth(this._lngLat,l)-n<.006)return void(this._element.style.opacity=this._opacity);const c=-this._offset.y/s.transform.pixelsPerMeter,h=Math.sin(s.getPitch()*Math.PI/180)*c,u=s.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),d=s.transform.lngLatToCameraDepth(this._lngLat,l+h)-u>.006;(null===(o=this._popup)||void 0===o?void 0:o.isOpen())&&d&&this._popup.remove(),this._element.style.opacity=d?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return (void 0===this._opacity||void 0===e&&void 0===t)&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==e&&(this._opacity=e),void 0!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(!0),this}}const Ya={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let Qa=0,Ja=!1;const es={maxWidth:100,unit:"metric"};function ts(e,t,i){const o=i&&i.maxWidth||100,r=e._container.clientHeight/2,a=e._container.clientWidth/2,s=e.unproject([a-o/2,r]),n=e.unproject([a+o/2,r]),l=Math.round(e.project(n).x-e.project(s).x),c=Math.min(o,l,e._container.clientWidth),h=s.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?is(t,c,i/5280,e._getUIString("ScaleControl.Miles")):is(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?is(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?is(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):is(t,c,h,e._getUIString("ScaleControl.Meters"));}function is(e,t,i,o){const r=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(r/i)+"px",e.innerHTML=`${r} ${o}`;}const os={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1,locationOccludedOpacity:void 0},rs=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function as(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(i,i),"top-right":new t.P(-i,i),bottom:new t.P(0,-e),"bottom-left":new t.P(i,-i),"bottom-right":new t.P(-i,-i),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){const i=t.P.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e["top-left"]||[0,0]),"top-right":t.P.convert(e["top-right"]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e["bottom-left"]||[0,0]),"bottom-right":t.P.convert(e["bottom-right"]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return as(new t.P(0,0))}const ss=i;e.AJAXError=t.cy,e.Event=t.l,e.Evented=t.E,e.LngLat=t.S,e.MercatorCoordinate=t.a0,e.Point=t.P,e.addProtocol=t.cz,e.config=t.a,e.removeProtocol=t.cA,e.AttributionControl=Da,e.BoxZoomHandler=$r,e.CanvasSource=Y,e.CooperativeGesturesHandler=Ca,e.DoubleClickZoomHandler=ba,e.DragPanHandler=wa,e.DragRotateHandler=Ta,e.EdgeInsets=Mt,e.FullscreenControl=class extends t.E{constructor(e={}){super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(e=null==t?void 0:t.shadowRoot)||void 0===e?void 0:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){n.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=n.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);n.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new t.l("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.l("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=H,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.l("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "BACKGROUND":case "BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.l("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.S(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.e({bearing:r},this.options.fitBoundsOptions),s=G.fromLngLat(i,o);this._map.fitBounds(s,a,{geolocateSource:!0});},this._updateMarker=e=>{if(e){const i=new t.S(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onZoom=()=>{this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();},this._onError=e=>{if(this._map){if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Ja)return;this.options.trackUserLocation&&this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.l("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=n.create("button","maplibregl-ctrl-geolocate",this._container),n.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0);},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.w("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=n.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new Ka({element:this._dotElement}),this._circleElement=n.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ka({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(e=>{e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||e.originalEvent&&"resize"===e.originalEvent.type||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.l("trackuserlocationend")),this.fire(new t.l("userlocationlostfocus")));}));}},this.options=t.e({},Ya,e);}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t._(this,arguments,void 0,(function*(e=!1){if(void 0!==qa&&!e)return qa;if(void 0===window.navigator.permissions)return qa=!!window.navigator.geolocation,qa;try{const e=yield window.navigator.permissions.query({name:"geolocation"});qa="denied"!==e.state;}catch(e){qa=!!window.navigator.geolocation;}return qa}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),n.remove(this._container),this._map.off("zoom",this._onZoom),this._map=void 0,Qa=0,Ja=!1;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case "WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case "ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadius(){const e=this._map.getBounds(),t=e.getSouthEast(),i=e.getNorthEast(),o=t.distanceTo(i),r=Math.ceil(this._accuracy/(o/this._map._container.clientHeight)*2);this._circleElement.style.width=`${r}px`,this._circleElement.style.height=`${r}px`;}trigger(){if(!this._setup)return t.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case "OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.l("trackuserlocationstart"));break;case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":case "BACKGROUND_ERROR":Qa--,Ja=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new t.l("trackuserlocationend"));break;case "BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.l("trackuserlocationstart")),this.fire(new t.l("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case "WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),Qa++,Qa>1?(e={maximumAge:6e5,timeout:0},Ja=!0):(e=this.options.positionOptions,Ja=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||void 0===e?void 0:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||void 0===e?void 0:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=n.create("button","maplibregl-ctrl-globe",this._container),n.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0;}},e.Hash=Er,e.ImageSource=X,e.KeyboardHandler=pa,e.LngLatBounds=G,e.LogoControl=Aa,e.Map=class extends Ra{constructor(e){var i,o;t.cv.mark(t.cw.create);const r=Object.assign(Object.assign(Object.assign({},Ga),e),{canvasContextAttributes:Object.assign(Object.assign({},Ga.canvasContextAttributes),e.canvasContextAttributes)});if(null!=r.minZoom&&null!=r.maxZoom&&r.minZoom>r.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=r.minPitch&&null!=r.maxPitch&&r.minPitch>r.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=r.minPitch&&r.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=r.maxPitch&&r.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const a=new Lt,s=new Ot;if(void 0!==r.minZoom&&a.setMinZoom(r.minZoom),void 0!==r.maxZoom&&a.setMaxZoom(r.maxZoom),void 0!==r.minPitch&&a.setMinPitch(r.minPitch),void 0!==r.maxPitch&&a.setMaxPitch(r.maxPitch),void 0!==r.renderWorldCopies&&a.setRenderWorldCopies(r.renderWorldCopies),super(a,s,{bearingSnap:r.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new La,this._controls=[],this._mapId=t.a6(),this._contextLost=e=>{e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new t.l("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._setupPainter(),this.resize(),this._update(),this.fire(new t.l("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update();},this._interactive=r.interactive,this._maxTileCacheSize=r.maxTileCacheSize,this._maxTileCacheZoomLevels=r.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},r.canvasContextAttributes),this._trackResize=!0===r.trackResize,this._bearingSnap=r.bearingSnap,this._centerClampedToGround=r.centerClampedToGround,this._refreshExpiredTiles=!0===r.refreshExpiredTiles,this._fadeDuration=r.fadeDuration,this._crossSourceCollisions=!0===r.crossSourceCollisions,this._collectResourceTiming=!0===r.collectResourceTiming,this._locale=Object.assign(Object.assign({},Za),r.locale),this._clickTolerance=r.clickTolerance,this._overridePixelRatio=r.pixelRatio,this._maxCanvasSize=r.maxCanvasSize,this.transformCameraUpdate=r.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===r.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=p.addThrottleControl((()=>this.isMoving())),this._requestManager=new m(r.transformRequest),"string"==typeof r.container){if(this._container=document.getElementById(r.container),!this._container)throw new Error(`Container '${r.container}' not found.`)}else {if(!(r.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=r.container;}if(r.maxBounds&&this.setMaxBounds(r.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0);})),this.once("idle",(()=>{this._idleTriggered=!0;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let e=!1;const t=Sr((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{e?t(i):e=!0;})),this._resizeObserver.observe(this._container);}this.handlers=new Ea(this,r),this._hash=r.hash&&new Er("string"==typeof r.hash&&r.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:r.center,elevation:r.elevation,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,roll:r.roll}),r.bounds&&(this.resize(),this.fitBounds(r.bounds,t.e({},r.fitBoundsOptions,{duration:0}))));const n="string"==typeof r.style||!("globe"===(null===(o=null===(i=r.style)||void 0===i?void 0:i.projection)||void 0===o?void 0:o.type));this.resize(null,n),this._localIdeographFontFamily=r.localIdeographFontFamily,this._validateStyle=r.validateStyle,r.style&&this.setStyle(r.style,{localIdeographFontFamily:r.localIdeographFontFamily}),r.attributionControl&&this.addControl(new Da("boolean"==typeof r.attributionControl?void 0:r.attributionControl)),r.maplibreLogo&&this.addControl(new Aa,r.logoPosition),this.on("style.load",(()=>{if(n||this._resizeTransform(),this.transform.unmodified){const e=t.Q(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.l(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.l(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.l("sourcedataabort",e));}));}_getMapId(){return this._mapId}setGlobalStateProperty(e,t){return this.style.setGlobalStateProperty(e,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(e,i){if(void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.k(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const o=e.onAdd(this);this._controls.push(e);const r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.k(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}calculateCameraOptionsFromTo(e,t,i,o){return null==o&&this.terrain&&(o=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(e,t,i,o)}resize(e,i=!0){const[o,r]=this._containerDimensions(),a=this._getClampedPixelRatio(o,r);if(this._resizeCanvas(o,r,a),this.painter.resize(o,r,a),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const t=this._getClampedPixelRatio(o,r);this._resizeCanvas(o,r,t),this.painter.resize(o,r,t);}this._resizeTransform(i);const s=!this._moving;return s&&(this.stop(),this.fire(new t.l("movestart",e)).fire(new t.l("move",e))),this.fire(new t.l("resize",e)),s&&this.fire(new t.l("moveend",e)),this}_resizeTransform(e=!0){var t;const[i,o]=this._containerDimensions();this.transform.resize(i,o,e),null===(t=this._requestedCameraState)||void 0===t||t.resize(i,o,e);}_getClampedPixelRatio(e,t){const{0:i,1:o}=this._maxCanvasSize,r=this.getPixelRatio(),a=e*r,s=t*r;return Math.min(a>i?i/a:1,s>o?o/s:1)*r}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&void 0!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(G.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom)return this.transform.setMinZoom(e),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(e),this._update(),this.getZoom()>e&&this.setZoom(e),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.setMinPitch(e),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch)return this.transform.setMaxPitch(e),this._update(),this.getPitch()>e&&this.setPitch(e),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.S.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||void 0===e?void 0:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||void 0===e?void 0:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||void 0===e?void 0:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e))),s=0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[];s.length?o||(o=!0,i.call(this,new jr(e,this,r.originalEvent,{features:s}))):o=!1;};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:()=>{o=!1;}}}}if("mouseleave"===e||"mouseout"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e)));(0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[]).length?o=!0:o&&(o=!1,i.call(this,new jr(e,this,r.originalEvent)));},a=t=>{o&&(o=!1,i.call(this,new jr(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:a}}}{const o=e=>{const o=t.filter((e=>this.getLayer(e))),r=0!==o.length?this.queryRenderedFeatures(e.point,{layers:o}):[];r.length&&(e.features=r,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:o}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const o=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in r.delegates)this.off(e,r.delegates[e]);return void o.splice(e,1)}}}on(e,t,i){if(void 0===i)return super.on(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);this._saveDelegatedListener(e,r);for(const e in r.delegates)this.on(e,r.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,o,i);}}}once(e,t,i){if(void 0===i)return super.once(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);for(const t in r.delegates){const a=r.delegates[t];r.delegates[t]=(...t)=>{this._removeDelegatedListener(e,o,i),a(...t);};}this._saveDelegatedListener(e,r);for(const e in r.delegates)this.once(e,r.delegates[e]);return this}off(e,t,i){return void 0===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let o;const r=e instanceof t.P||Array.isArray(e),a=r?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(r?{}:e)||{},a instanceof t.P||"number"==typeof a[0])o=[t.P.convert(a)];else {const e=t.P.convert(a[0]),i=t.P.convert(a[1]);o=[e,new t.P(i.x,e.y),i,new t.P(e.x,i.y),e];}return this.style.queryRenderedFeatures(o,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return !1!==(i=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,o;if(t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const r=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new wi(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,r):this.style.loadJSON(e,t,r),this):(null===(o=null===(i=this.style)||void 0===i?void 0:i.projection)||void 0===o||o.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new wi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){if("string"==typeof e){const o=this._requestManager.transformRequest(e,"Style");t.j(o,new AbortController).then((e=>{this._updateDiff(e.data,i);})).catch((e=>{e&&this.fire(new t.k(e));}));}else "object"==typeof e&&this._updateDiff(e,i);}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(o){t.w(`Unable to perform style diff: ${o.message||o.error||o}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():t.w("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){const i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.k(new Error(`There is no source with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.sourceCaches[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const o=this.style._layers[i];"hillshade"===o.type&&o.source===e.source&&t.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality."),"color-relief"===o.type&&o.source===e.source&&t.w("You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");}this.terrain=new Ba(this.painter,i,e),this.painter.renderToTexture=new Na(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{var i;"style"===t.dataType?this.terrain.sourceCache.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),"image"===(null===(i=t.source)||void 0===i?void 0:i.type)?this.terrain.sourceCache.freeRtt():this.terrain.sourceCache.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.l("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||void 0===e?void 0:e.options)&&void 0!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.sourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}}return !0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}setSourceTileLodParams(e,t,i){if(i){const o=this.getSource(i);if(!o)throw new Error(`There is no source with ID "${i}", cannot set LOD parameters`);o.calculateTileZoom=me(Math.max(1,e),Math.max(1,t));}else for(const i in this.style.sourceCaches)this.style.sourceCaches[i].getSource().calculateTileZoom=me(Math.max(1,e),Math.max(1,t));return this._update(!0),this}refreshTiles(e,i){const o=this.style.sourceCaches[e];if(!o)throw new Error(`There is no source cache with ID "${e}", cannot refresh tile`);void 0===i?o.reload(!0):o.refreshTiles(i.map((e=>new t.a3(e.z,e.x,e.y))));}addImage(e,i,o={}){const{pixelRatio:r=1,sdf:a=!1,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u}=o;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.b(i))){if(void 0===i.width||void 0===i.height)return this.fire(new t.k(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:o,height:s,data:d}=i,_=i;return this.style.addImage(e,{data:new t.R({width:o,height:s},new Uint8Array(d)),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:o,height:d,data:_}=s.getImageData(i);this.style.addImage(e,{data:new t.R({width:o,height:d},_),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0});}}updateImage(e,i){const o=this.style.getImage(e);if(!o)return this.fire(new t.k(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const r=i instanceof HTMLImageElement||t.b(i)?s.getImageData(i):i,{width:a,height:n,data:l}=r;if(void 0===a||void 0===n)return this.fire(new t.k(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(a!==o.data.width||n!==o.data.height)return this.fire(new t.k(new Error("The width and height of the updated image must be that same as the previous version of the image")));const c=!(i instanceof HTMLImageElement||t.b(i));return o.data.replace(l,c),this.style.updateImage(e,o),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.k(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(e);}loadImage(e){return p.getImage(this._requestManager.transformRequest(e,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(!0)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,o={}){return this.style.setPaintProperty(e,t,i,o),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,o={}){return this.style.setLayoutProperty(e,t,i,o),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(!0);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=n.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=n.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),o=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],o);const r=this._controlContainer=n.create("div","maplibregl-control-container",e),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{a[e]=n.create("div",`maplibregl-ctrl-${e} `,r);})),this._container.addEventListener("scroll",this._onMapScroll,!1);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0});let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:!0});let i=null;if(i=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e),!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new Mr(i,this.transform),l.testSupport(i);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.l("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){var i,o,r,a,n;const l=this._idleTriggered?this._fadeDuration:0,c=(null===(i=this.style.projection)||void 0===i?void 0:i.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let h=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,i=s.now();this.style.zoomHistory.update(e,i);const o=new t.F(e,{now:i,fadeDuration:l,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition(),globalState:this.style.getGlobalState()}),r=o.crossFadingFactor();1===r&&r===this._crossFadingFactor||(h=!0,this._crossFadingFactor=r),this.style.update(o);}const u=(null===(o=this.style.projection)||void 0===o?void 0:o.transitionState)>0!==c;null===(r=this.style.projection)||void 0===r||r.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(a=this.style.projection)||void 0===a?void 0:a.transitionState,null===(n=this.style.projection)||void 0===n?void 0:n.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||u)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,l,this._crossSourceCollisions,u),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:l,showPadding:this.showPadding}),this.fire(new t.l("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,t.cv.mark(t.cw.load),this.fire(new t.l("load"))),this.style&&(this.style.hasTransitions()||h)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const d=this._sourcesDirty||this._styleDirty||this._placementDirty;return d||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.l("idle")),!this._loaded||this._fullyLoaded||d||(this._fullyLoaded=!0,t.cv.mark(t.cw.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),p.removeThrottleControl(this._imageQueueHandle),null===(e=this._resizeObserver)||void 0===e||e.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?void 0:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),n.remove(this._canvasContainer),n.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),t.cv.clearMetrics(),this._removed=!0,this.fire(new t.l("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,s.frame(this._frameRequest,(e=>{t.cv.frame(e),this._frameRequest=null;try{this._render(e);}catch(e){if(!t.cx(e)&&!function(e){return e.message===qo}(e))throw e}}),(()=>{})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return Ua}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}},e.MapMouseEvent=jr,e.MapTouchEvent=Nr,e.MapWheelEvent=Zr,e.Marker=Ka,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.e({},Va,e),this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=n.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new $a(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){n.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=n.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.E{constructor(e){super(),this._updateOpacity=()=>{void 0!==this.options.locationOccludedOpacity&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:void 0);},this.remove=()=>(this._content&&n.remove(this._content),this._container&&(n.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new t.l("close"))),this),this._onMouseUp=e=>{this._update(e.point);},this._onMouseMove=e=>{this._update(e.point);},this._onDrag=e=>{this._update(e.point);},this._update=e=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=n.create("div","maplibregl-popup",this._map.getContainer()),this._tip=n.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer");}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),this._trackPointer&&!e)return;const t=this._flatPos=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&e?e:this._map.transform.locationToScreenPoint(this._lngLat));let i=this.options.anchor;const o=as(this.options.offset);if(!i){const e=this._container.offsetWidth,r=this._container.offsetHeight;let a;a=t.y+o.bottom.ythis._map.transform.height-r?["bottom"]:[],t.xthis._map.transform.width-e/2&&a.push("right"),i=0===a.length?"bottom":a.join("-");}let r=t.add(o[i]);this.options.subpixelPositioning||(r=r.round()),n.setTransform(this._container,`${Ha[i]} translate(${r.x}px,${r.y}px)`),Xa(this._container,i,"popup"),this._updateOpacity();},this._onClose=()=>{this.remove();},this.options=t.e(Object.create(os),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.l("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let o;for(i.innerHTML=e;o=i.firstChild,o;)t.appendChild(o);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||void 0===e?void 0:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=n.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}_createCloseButton(){this.options.closeButton&&(this._closeButton=n.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(rs);e&&e.focus();}},e.RasterDEMTileSource=W,e.RasterTileSource=q,e.ScaleControl=class{constructor(e){this._onMove=()=>{ts(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,ts(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},es),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){n.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;}},e.ScrollZoomHandler=va,e.Style=wi,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=n.create("button","maplibregl-ctrl-terrain",this._container),n.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){n.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0;}},e.TwoFingersTouchPitchHandler=da,e.TwoFingersTouchRotateHandler=ha,e.TwoFingersTouchZoomHandler=la,e.TwoFingersTouchZoomRotateHandler=Pa,e.VectorTileSource=$,e.VideoSource=K,e.addSourceType=(e,i)=>t._(void 0,void 0,void 0,(function*(){if(J(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{Q[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=A;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(R),A=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},e.createTileMesh=Xt,e.getMaxParallelImageRequests=function(){return t.a.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},e.getVersion=function(){return ss},e.getWorkerCount=function(){return z.workerCount},e.getWorkerUrl=function(){return t.a.WORKER_URL},e.importScriptInWorkers=function(e){return B().broadcast("IS",e)},e.prewarm=function(){k().acquire(R);},e.setMaxParallelImageRequests=function(e){t.a.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setRTLTextPlugin=function(e,t){return oe().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){z.workerCount=e;},e.setWorkerUrl=function(e){t.a.WORKER_URL=e;};})); + +// +// Our custom intro provides a specialized "define()" function, called by the +// AMD modules below, that sets up the worker blob URL and then executes the +// main module, storing its exported value as 'maplibregl' + + +var maplibregl$1 = maplibregl; + +return maplibregl$1; + +})); +//# sourceMappingURL=maplibre-gl.js.map diff --git a/docs/articles/layers-overview_files/maplibre-gl-4.4.1/LICENSE.txt b/docs/articles/turf_files/maplibre-gl-5.7.2/LICENSE.txt similarity index 100% rename from docs/articles/layers-overview_files/maplibre-gl-4.4.1/LICENSE.txt rename to docs/articles/turf_files/maplibre-gl-5.7.2/LICENSE.txt diff --git a/docs/articles/turf_files/maplibre-gl-5.7.2/maplibre-gl.css b/docs/articles/turf_files/maplibre-gl-5.7.2/maplibre-gl.css new file mode 100644 index 0000000..3f86747 --- /dev/null +++ b/docs/articles/turf_files/maplibre-gl-5.7.2/maplibre-gl.css @@ -0,0 +1 @@ +.maplibregl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgb(0,0,0,0)}.maplibregl-canvas{left:0;position:absolute;top:0}.maplibregl-map:fullscreen{height:100%;width:100%}.maplibregl-ctrl-group button.maplibregl-ctrl-compass{touch-action:none}.maplibregl-canvas-container.maplibregl-interactive,.maplibregl-ctrl-group button.maplibregl-ctrl-compass{cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-canvas-container.maplibregl-interactive.maplibregl-track-pointer{cursor:pointer}.maplibregl-canvas-container.maplibregl-interactive:active,.maplibregl-ctrl-group button.maplibregl-ctrl-compass:active{cursor:grabbing}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-canvas-container.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:pinch-zoom}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:none}.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures,.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-ctrl-bottom-left,.maplibregl-ctrl-bottom-right,.maplibregl-ctrl-top-left,.maplibregl-ctrl-top-right{pointer-events:none;position:absolute;z-index:2}.maplibregl-ctrl-top-left{left:0;top:0}.maplibregl-ctrl-top-right{right:0;top:0}.maplibregl-ctrl-bottom-left{bottom:0;left:0}.maplibregl-ctrl-bottom-right{bottom:0;right:0}.maplibregl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.maplibregl-ctrl-top-left .maplibregl-ctrl{float:left;margin:10px 0 0 10px}.maplibregl-ctrl-top-right .maplibregl-ctrl{float:right;margin:10px 10px 0 0}.maplibregl-ctrl-bottom-left .maplibregl-ctrl{float:left;margin:0 0 10px 10px}.maplibregl-ctrl-bottom-right .maplibregl-ctrl{float:right;margin:0 10px 10px 0}.maplibregl-ctrl-group{background:#fff;border-radius:4px}.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px rgba(0,0,0,.1)}@media (forced-colors:active){.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.maplibregl-ctrl-group button{background-color:transparent;border:0;box-sizing:border-box;cursor:pointer;display:block;height:29px;outline:none;padding:0;width:29px}.maplibregl-ctrl-group button+button{border-top:1px solid #ddd}.maplibregl-ctrl button .maplibregl-ctrl-icon{background-position:50%;background-repeat:no-repeat;display:block;height:100%;width:100%}@media (forced-colors:active){.maplibregl-ctrl-icon{background-color:transparent}.maplibregl-ctrl-group button+button{border-top:1px solid ButtonText}}.maplibregl-ctrl button::-moz-focus-inner{border:0;padding:0}.maplibregl-ctrl-attrib-button:focus,.maplibregl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl button:disabled{cursor:not-allowed}.maplibregl-ctrl button:disabled .maplibregl-ctrl-icon{opacity:.25}@media (hover:hover){.maplibregl-ctrl button:not(:disabled):hover{background-color:rgba(0,0,0,.05)}}.maplibregl-ctrl button:not(:disabled):active{background-color:rgba(0,0,0,.05)}.maplibregl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.maplibregl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.maplibregl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.maplibregl-ctrl-group button:focus:only-child{border-radius:inherit}.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-globe .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none' stroke='%23333' viewBox='0 0 22 22'%3E%3Ccircle cx='11' cy='11' r='8.5'/%3E%3Cpath d='M17.5 11c0 4.819-3.02 8.5-6.5 8.5S4.5 15.819 4.5 11 7.52 2.5 11 2.5s6.5 3.681 6.5 8.5Z'/%3E%3Cpath d='M13.5 11c0 2.447-.331 4.64-.853 6.206-.262.785-.562 1.384-.872 1.777-.314.399-.58.517-.775.517s-.461-.118-.775-.517c-.31-.393-.61-.992-.872-1.777C8.831 15.64 8.5 13.446 8.5 11s.331-4.64.853-6.206c.262-.785.562-1.384.872-1.777.314-.399.58-.517.775-.517s.461.118.775.517c.31.393.61.992.872 1.777.522 1.565.853 3.76.853 6.206Z'/%3E%3Cpath d='M11 7.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138q.07-.058.224-.138c.299-.151.763-.302 1.379-.434C7.378 5.666 9.091 5.5 11 5.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138q-.07.058-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428ZM4.486 6.436ZM11 16.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138 1.3 1.3 0 0 1 .224-.138c.299-.151.763-.302 1.379-.434C7.378 14.666 9.091 14.5 11 14.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138a1.3 1.3 0 0 1-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428Zm-6.514-1.064ZM11 12.5c-2.46 0-4.672-.222-6.255-.574-.796-.177-1.406-.38-1.805-.59a1.5 1.5 0 0 1-.39-.272.3.3 0 0 1-.047-.064.3.3 0 0 1 .048-.064c.066-.073.189-.167.389-.272.399-.21 1.009-.413 1.805-.59C6.328 9.722 8.54 9.5 11 9.5s4.672.222 6.256.574c.795.177 1.405.38 1.804.59.2.105.323.2.39.272a.3.3 0 0 1 .047.064.3.3 0 0 1-.048.064 1.4 1.4 0 0 1-.389.272c-.399.21-1.009.413-1.804.59-1.584.352-3.796.574-6.256.574Zm-8.501-1.51v.002zm0 .018v.002zm17.002.002v-.002zm0-.018v-.002z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-globe-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none' stroke='%2333b5e5' viewBox='0 0 22 22'%3E%3Ccircle cx='11' cy='11' r='8.5'/%3E%3Cpath d='M17.5 11c0 4.819-3.02 8.5-6.5 8.5S4.5 15.819 4.5 11 7.52 2.5 11 2.5s6.5 3.681 6.5 8.5Z'/%3E%3Cpath d='M13.5 11c0 2.447-.331 4.64-.853 6.206-.262.785-.562 1.384-.872 1.777-.314.399-.58.517-.775.517s-.461-.118-.775-.517c-.31-.393-.61-.992-.872-1.777C8.831 15.64 8.5 13.446 8.5 11s.331-4.64.853-6.206c.262-.785.562-1.384.872-1.777.314-.399.58-.517.775-.517s.461.118.775.517c.31.393.61.992.872 1.777.522 1.565.853 3.76.853 6.206Z'/%3E%3Cpath d='M11 7.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138q.07-.058.224-.138c.299-.151.763-.302 1.379-.434C7.378 5.666 9.091 5.5 11 5.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138q-.07.058-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428ZM4.486 6.436ZM11 16.5c-1.909 0-3.622-.166-4.845-.428-.616-.132-1.08-.283-1.379-.434a1.3 1.3 0 0 1-.224-.138 1.3 1.3 0 0 1 .224-.138c.299-.151.763-.302 1.379-.434C7.378 14.666 9.091 14.5 11 14.5s3.622.166 4.845.428c.616.132 1.08.283 1.379.434.105.053.177.1.224.138a1.3 1.3 0 0 1-.224.138c-.299.151-.763.302-1.379.434-1.223.262-2.936.428-4.845.428Zm-6.514-1.064ZM11 12.5c-2.46 0-4.672-.222-6.255-.574-.796-.177-1.406-.38-1.805-.59a1.5 1.5 0 0 1-.39-.272.3.3 0 0 1-.047-.064.3.3 0 0 1 .048-.064c.066-.073.189-.167.389-.272.399-.21 1.009-.413 1.805-.59C6.328 9.722 8.54 9.5 11 9.5s4.672.222 6.256.574c.795.177 1.405.38 1.804.59.2.105.323.2.39.272a.3.3 0 0 1 .047.064.3.3 0 0 1-.048.064 1.4 1.4 0 0 1-.389.272c-.399.21-1.009.413-1.804.59-1.584.352-3.796.574-6.256.574Zm-8.501-1.51v.002zm0 .018v.002zm17.002.002v-.002zm0-.018v-.002z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%23333' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%2333b5e5' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23aaa' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-waiting .maplibregl-ctrl-icon{animation:maplibregl-spin 2s linear infinite}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23999' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23666' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}}@keyframes maplibregl-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E");background-repeat:no-repeat;cursor:pointer;display:block;height:23px;margin:0 0 -4px -4px;overflow:hidden;width:88px}a.maplibregl-ctrl-logo.maplibregl-compact{width:14px}@media (forced-colors:active){a.maplibregl-ctrl-logo{background-color:transparent;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}.maplibregl-ctrl.maplibregl-ctrl-attrib{background-color:hsla(0,0%,100%,.5);margin:0;padding:0 5px}@media screen{.maplibregl-ctrl-attrib.maplibregl-compact{background-color:#fff;border-radius:12px;box-sizing:content-box;color:#000;margin:10px;min-height:20px;padding:2px 24px 2px 0;position:relative}.maplibregl-ctrl-attrib.maplibregl-compact-show{padding:2px 28px 2px 8px;visibility:visible}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:hsla(0,0%,100%,.5);background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:rgba(0,0,0,.05)}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:hsla(0,0%,100%,.75);border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:rgba(0,0,0,.05)}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px rgba(0,0,0,.35);box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:rgba(0,0,0,.4);color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media (hover:none),(pointer:coarse){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999} \ No newline at end of file diff --git a/docs/articles/turf_files/maplibre-gl-5.7.2/maplibre-gl.js b/docs/articles/turf_files/maplibre-gl-5.7.2/maplibre-gl.js new file mode 100644 index 0000000..53dd1e0 --- /dev/null +++ b/docs/articles/turf_files/maplibre-gl-5.7.2/maplibre-gl.js @@ -0,0 +1,59 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v5.7.2/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory()); +})(this, (function () { 'use strict'; + +/* eslint-disable */ + +var maplibregl = {}; +var modules = {}; +function define(moduleName, _dependencies, moduleFactory) { + modules[moduleName] = moduleFactory; + + // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) + if (moduleName !== 'index') { + return; + } + + // we assume that when an index module is initializing then other modules are loaded already + var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);' + + var sharedModule = {}; + // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) + // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) + // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following + modules.shared(sharedModule); + modules.index(maplibregl, sharedModule); + + if (typeof window !== 'undefined') { + maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); + } + + return maplibregl; +}; + + + +define("shared",["exports"],(function(t){"use strict";function e(t,e,r,n){return new(r||(r=Promise))((function(i,s){function a(t){try{l(n.next(t));}catch(t){s(t);}}function o(t){try{l(n.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(a,o);}l((n=n.apply(t,e||[])).next());}))}function r(t,e){this.x=t,this.y=e;}function n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,s;"function"==typeof SuppressedError&&SuppressedError,r.prototype={clone(){return new r(this.x,this.y)},add(t){return this.clone()._add(t)},sub(t){return this.clone()._sub(t)},multByPoint(t){return this.clone()._multByPoint(t)},divByPoint(t){return this.clone()._divByPoint(t)},mult(t){return this.clone()._mult(t)},div(t){return this.clone()._div(t)},rotate(t){return this.clone()._rotate(t)},rotateAround(t,e){return this.clone()._rotateAround(t,e)},matMult(t){return this.clone()._matMult(t)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(t){return this.x===t.x&&this.y===t.y},dist(t){return Math.sqrt(this.distSqr(t))},distSqr(t){const e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle(){return Math.atan2(this.y,this.x)},angleTo(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith(t){return this.angleWithSep(t.x,t.y)},angleWithSep(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult(t){const e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add(t){return this.x+=t.x,this.y+=t.y,this},_sub(t){return this.x-=t.x,this.y-=t.y,this},_mult(t){return this.x*=t,this.y*=t,this},_div(t){return this.x/=t,this.y/=t,this},_multByPoint(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint(t){return this.x/=t.x,this.y/=t.y,this},_unit(){return this._div(this.mag()),this},_perp(){const t=this.y;return this.y=this.x,this.x=-t,this},_rotate(t){const e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround(t,e){const r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:r},r.convert=function(t){if(t instanceof r)return t;if(Array.isArray(t))return new r(+t[0],+t[1]);if(void 0!==t.x&&void 0!==t.y)return new r(+t.x,+t.y);throw new Error("Expected [x, y] or {x, y} point format")};var a=function(){if(s)return i;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return s=1,i=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},i}(),o=n(a);let l,u;function c(){return null==l&&(l="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),l}function h(){if(null==u&&(u=!1,c())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:!0});if(e){for(let r=0;r4&&void 0!==arguments[4]?arguments[4]:"zyx",s=Math.PI/360;e*=s,n*=s,r*=s;var a=Math.sin(e),o=Math.cos(e),l=Math.sin(r),u=Math.cos(r),c=Math.sin(n),h=Math.cos(n);switch(i){case "xyz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "xzy":t[0]=a*u*h-o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h+a*l*c;break;case "yxz":t[0]=a*u*h+o*l*c,t[1]=o*l*h-a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;case "yzx":t[0]=a*u*h+o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h-a*l*c;break;case "zxy":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c+a*l*h,t[3]=o*u*h-a*l*c;break;case "zyx":t[0]=a*u*h-o*l*c,t[1]=o*l*h+a*u*c,t[2]=o*u*c-a*l*h,t[3]=o*u*h+a*l*c;break;default:throw new Error("Unknown angle order "+i)}return t}function I(){var t=new f(2);return f!=Float32Array&&(t[0]=0,t[1]=0),t}function z(t,e){var r=new f(2);return r[0]=t,r[1]=e,r}m(),_=new f(4),f!=Float32Array&&(_[0]=0,_[1]=0,_[2]=0,_[3]=0),m(),x(1,0,0),x(0,1,0),k(),k(),d(),I();const P=8192;function C(t,e,r){return e*(P/(t.tileSize*Math.pow(2,r-t.tileID.overscaledZ)))}function E(t,e){return (t%e+e)%e}function T(t,e,r){return t*(1-r)+e*r}function B(t){if(t<=0)return 0;if(t>=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function V(t,e,r,n){const i=new o(t,e,r,n);return t=>i.solve(t)}const F=V(.25,.1,.25,1);function $(t,e,r){return Math.min(r,Math.max(e,t))}function D(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function L(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let O=1;function R(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function U(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}function j(t){return Array.isArray(t)?t.map(j):"object"==typeof t&&t?R(t,j):t}const N={};function q(t){N[t]||("undefined"!=typeof console&&console.warn(t),N[t]=!0);}function G(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function X(t){return "undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}let Z=null;function Y(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const H="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function K(t,r,n,i,s){return e(this,void 0,void 0,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const e=new VideoFrame(t,{timestamp:0});try{const a=null==e?void 0:e.format;if(!a||!a.startsWith("BGR")&&!a.startsWith("RGB"))throw new Error(`Unrecognized format ${a}`);const o=a.startsWith("BGR"),l=new Uint8ClampedArray(i*s*4);if(yield e.copyTo(l,function(t,e,r,n,i){const s=4*Math.max(-e,0),a=(Math.max(0,r)-r)*n*4+s,o=4*n,l=Math.max(0,e),u=Math.max(0,r);return {rect:{x:l,y:u,width:Math.min(t.width,e+n)-l,height:Math.min(t.height,r+i)-u},layout:[{offset:a,stride:o}]}}(t,r,n,i,s)),o)for(let t=0;t{t.removeEventListener(e,r,n);}}}function tt(t){return t*Math.PI/180}function et(t){return t/Math.PI*180}const rt={touchstart:!0,touchmove:!0,touchmoveWindow:!0,touchend:!0,touchcancel:!0},nt={dblclick:!0,click:!0,mouseover:!0,mouseout:!0,mousedown:!0,mousemove:!0,mousemoveWindow:!0,mouseup:!0,mouseupWindow:!0,contextmenu:!0,wheel:!0},it="AbortError";function st(){return new Error(it)}const at={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function ot(t){return at.REGISTERED_PROTOCOLS[t.substring(0,t.indexOf("://"))]}const lt="global-dispatcher";class ut extends Error{constructor(t,e,r,n){super(`AJAXError: ${e} (${t}): ${r}`),this.status=t,this.statusText=e,this.url=r,this.body=n;}}const ct=()=>X(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,ht=function(t,r){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const e=ot(t.url);if(e)return e(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:lt},r)}if(!(/^file:/.test(n=t.url)||/^file:/.test(ct())&&!/^\w+:/.test(n))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,r){return e(this,void 0,void 0,(function*(){const e=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:ct(),signal:r.signal});let n,i;"json"!==t.type||e.headers.has("Accept")||e.headers.set("Accept","application/json");try{n=yield fetch(e);}catch(e){throw new ut(0,e.message,t.url,new Blob)}if(!n.ok){const e=yield n.blob();throw new ut(n.status,n.statusText,t.url,e)}i="arrayBuffer"===t.type||"image"===t.type?n.arrayBuffer():"json"===t.type?n.json():n.text();const s=yield i;if(r.signal.aborted)throw st();return {data:s,cacheControl:n.headers.get("Cache-Control"),expires:n.headers.get("Expires")}}))}(t,r);if(X(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:!0,targetMapId:lt},r)}var n;return function(t,e){return new Promise(((r,n)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,!0),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||void 0===i?void 0:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{n(new Error(s.statusText));},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response);}catch(t){return void n(t)}r({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires")});}else {const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});n(new ut(s.status,s.statusText,t.url,e));}},e.signal.addEventListener("abort",(()=>{s.abort(),n(st());})),s.send(t.body);}))}(t,r)};function pt(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return !0;const e=new URL(t),r=window.location;return e.protocol===r.protocol&&e.host===r.host}function ft(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function dt(t,e,r){if(r&&r[t]){const n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}class yt{constructor(t,e={}){L(this,e),this.type=t;}}class mt extends yt{constructor(t,e={}){super("error",L({error:t},e));}}class gt{on(t,e){return this._listeners=this._listeners||{},ft(t,e,this._listeners),{unsubscribe:()=>{this.off(t,e);}}}off(t,e){return dt(t,e,this._listeners),dt(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},ft(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new yt(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)dt(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(L(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof mt&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var xt={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},state:{type:"state",default:{}},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},"font-faces":{type:"array",value:"fontFaces"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},"color-relief":{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_color-relief","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_color-relief":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_color-relief","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"numberArray",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-altitude":{type:"numberArray",default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"colorArray",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"colorArray",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-method":{type:"enum",values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:"standard",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},"paint_color-relief":{"color-relief-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"color-relief-color":{type:"color",transition:!1,expression:{interpolated:!0,parameters:["elevation"]},"property-type":"color-ramp"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const vt=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function bt(t,e){const r={};for(const e in t)"ref"!==e&&(r[e]=t[e]);return vt.forEach((t=>{t in e&&(r[t]=e[t]);})),r}function wt(t,e){if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return !1;for(let r=0;r`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const Jt=[Vt,Ft,$t,Dt,Lt,Ot,Nt,Rt,Ht(Ut),qt,Xt,Gt,Zt,Yt];function Wt(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Wt(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of Jt)if(!Wt(t,e))return null}return `Expected ${Kt(t)} but found ${Kt(e)} instead.`}function Qt(t,e){return e.some((e=>e.kind===t.kind))}function te(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function ee(t,e){return "array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const re=.96422,ne=.82521,ie=4/29,se=6/29,ae=3*se*se,oe=se*se*se,le=Math.PI/180,ue=180/Math.PI;function ce(t){return (t%=360)<0&&(t+=360),t}function he([t,e,r,n]){let i,s;const a=fe((.2225045*(t=pe(t))+.7168786*(e=pe(e))+.0606169*(r=pe(r)))/1);t===e&&e===r?i=s=a:(i=fe((.4360747*t+.3850649*e+.1430804*r)/re),s=fe((.0139322*t+.0971045*e+.7141733*r)/ne));const o=116*a-16;return [o<0?0:o,500*(i-a),200*(a-s),n]}function pe(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function fe(t){return t>oe?Math.pow(t,1/3):t/ae+ie}function de([t,e,r,n]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,a=isNaN(r)?i:i-r/200;return i=1*me(i),s=re*me(s),a=ne*me(a),[ye(3.1338561*s-1.6168667*i-.4906146*a),ye(-.9787684*s+1.9161415*i+.033454*a),ye(.0719453*s-.2289914*i+1.4052427*a),n]}function ye(t){return (t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function me(t){return t>se?t*t*t:ae*(t-ie)}const ge=Object.hasOwn||function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};function xe(t,e){return ge(t,e)?t[e]:void 0}function ve(t){return parseInt(t.padEnd(2,t),16)/255}function be(t,e){return we(e?t/100:t,0,1)}function we(t,e,r){return Math.min(Math.max(e,t),r)}function _e(t){return !t.some(Number.isNaN)}const Se={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function Ae(t,e,r){return t+r*(e-t)}function ke(t,e,r){return t.map(((t,n)=>Ae(t,e[n],r)))}class Me{constructor(t,e,r,n=1,i=!0){this.r=t,this.g=e,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[t,e,r,n]));}static parse(t){if(t instanceof Me)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return [0,0,0,0];const e=xe(Se,t);if(e){const[t,r,n]=e;return [t/255,r/255,n/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let r=1;return [ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+=e)),ve(t.slice(r,r+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,r,n,i,s,a,o,l,u,c,h,p]=e,f=[i||" ",o||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[n,a,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[we(+r/e,0,1),we(+s/e,0,1),we(+l/e,0,1),h?be(+h,p):1];if(_e(t))return t}}return}}const r=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[t,e,n,i,s,a,o,l,u]=r,c=[n||" ",s||" ",o].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,we(+i,0,100),we(+a,0,100),l?be(+l,u):1];if(_e(t))return function([t,e,r,n]){function i(n){const i=(n+t/30)%12,s=e*Math.min(r,1-r);return r-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=ce(t),e/=100,r/=100,[i(0),i(8),i(4),n]}(t)}}}(t);return e?new Me(...e,!1):void 0}get rgb(){const{r:t,g:e,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[t/i,e/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,r,n,i]=he(t),s=Math.sqrt(r*r+n*n);return [Math.round(1e4*s)?ce(Math.atan2(n,r)*ue):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",he(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,r,n]=this.rgb;return `rgba(${[t,e,r].map((t=>Math.round(255*t))).join(",")},${n})`}static interpolate(t,e,r,n="rgb"){switch(n){case "rgb":{const[n,i,s,a]=ke(t.rgb,e.rgb,r);return new Me(n,i,s,a,!1)}case "hcl":{const[n,i,s,a]=t.hcl,[o,l,u,c]=e.hcl;let h,p;if(isNaN(n)||isNaN(o))isNaN(n)?isNaN(o)?h=NaN:(h=o,1!==s&&0!==s||(p=l)):(h=n,1!==u&&0!==u||(p=i));else {let t=o-n;o>n&&t>180?t-=360:o180&&(t+=360),h=n+r*t;}const[f,d,y,m]=function([t,e,r,n]){return t=isNaN(t)?0:t*le,de([r,Math.cos(t)*e,Math.sin(t)*e,n])}([h,null!=p?p:Ae(i,l,r),Ae(s,u,r),Ae(a,c,r)]);return new Me(f,d,y,m,!1)}case "lab":{const[n,i,s,a]=de(ke(t.lab,e.lab,r));return new Me(n,i,s,a,!1)}}}}Me.black=new Me(0,0,0,1),Me.white=new Me(1,1,1,1),Me.transparent=new Me(0,0,0,0),Me.red=new Me(1,0,0,1);class Ie{constructor(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}const ze=["bottom","center","top"];class Pe{constructor(t,e,r,n,i,s){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i,this.verticalAlign=s;}}class Ce{constructor(t){this.sections=t;}static fromString(t){return new Ce([new Pe(t,null,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof Ce?t:Ce.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class Ee{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Ee)return t;if("number"==typeof t)return new Ee([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]];}return new Ee(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Ee(ke(t.values,e.values,r))}}class Te{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Te)return t;if("number"==typeof t)return new Te([t]);if(Array.isArray(t)){for(const e of t)if("number"!=typeof e)return;return new Te(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new Te(ke(t.values,e.values,r))}}class Be{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Be)return t;if("string"==typeof t){const e=Me.parse(t);if(!e)return;return new Be([e])}if(!Array.isArray(t))return;const e=[];for(const r of t){if("string"!=typeof r)return;const t=Me.parse(r);if(!t)return;e.push(t);}return new Be(e)}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r,n="rgb"){const i=[];if(t.values.length!=e.values.length)throw new Error(`colorArray: Arrays have mismatched length (${t.values.length} vs. ${e.values.length}), cannot interpolate.`);for(let s=0;s=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Re(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof Le||t instanceof Me||t instanceof Ie||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De)return !0;if(Array.isArray(t)){for(const e of t)if(!Re(e))return !1;return !0}if("object"==typeof t){for(const e in t)if(!Re(t[e]))return !1;return !0}return !1}function Ue(t){if(null===t)return Vt;if("string"==typeof t)return $t;if("boolean"==typeof t)return Dt;if("number"==typeof t)return Ft;if(t instanceof Me)return Lt;if(t instanceof Le)return Ot;if(t instanceof Ie)return jt;if(t instanceof Ce)return Nt;if(t instanceof Ee)return qt;if(t instanceof Te)return Xt;if(t instanceof Be)return Gt;if(t instanceof $e)return Yt;if(t instanceof De)return Zt;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=Ue(e);if(r){if(r===t)continue;r=Ut;break}r=t;}return Ht(r||Ut,e)}return Rt}function je(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof Me||t instanceof Le||t instanceof Ce||t instanceof Ee||t instanceof Te||t instanceof Be||t instanceof $e||t instanceof De?t.toString():JSON.stringify(t)}class Ne{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Re(t[1]))return e.error("invalid value");const r=t[1];let n=Ue(r);const i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new Ne(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return !0}}const qe={string:$t,number:Ft,boolean:Dt,object:Rt};class Ge{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r,n=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const r=t[1];if("string"!=typeof r||!(r in qe)||"object"===r)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=qe[r],n++;}else i=Ut;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],n++;}r=Ht(i,s);}else {if(!qe[i])throw new Error(`Types doesn't contain name = ${i}`);r=qe[i];}const s=[];for(;nt.outputDefined()))}}const Xe={"to-boolean":Dt,"to-color":Lt,"to-number":Ft,"to-string":$t};class Ze{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[0];if(!Xe[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");const n=Xe[r],i=[];for(let r=1;r4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:Oe(e[0],e[1],e[2],e[3]),!r))return new Me(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new Ve(r||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "padding":{let e;for(const r of this.args){e=r.evaluate(t);const n=Ee.parse(e);if(n)return n}throw new Ve(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "numberArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Te.parse(e);if(n)return n}throw new Ve(`Could not parse numberArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "colorArray":{let e;for(const r of this.args){e=r.evaluate(t);const n=Be.parse(e);if(n)return n}throw new Ve(`Could not parse colorArray from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "variableAnchorOffsetCollection":{let e;for(const r of this.args){e=r.evaluate(t);const n=$e.parse(e);if(n)return n}throw new Ve(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case "number":{let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new Ve(`Could not convert ${JSON.stringify(e)} to number.`)}case "formatted":return Ce.fromString(je(this.args[0].evaluate(t)));case "resolvedImage":return De.fromString(je(this.args[0].evaluate(t)));case "projectionDefinition":return this.args[0].evaluate(t);default:return je(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}const Ye=["Unknown","Point","LineString","Polygon"];class He{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=new Map,this.availableImages=null,this.canonical=null;}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?Ye[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache.get(t);return e||(e=Me.parse(t),this._parseColorCache.set(t,e)),e}}class Ke{constructor(t,e,r=[],n,i=new Bt,s=[]){this.registry=t,this.path=r,this.key=r.map((t=>`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=n,this._isConstant=e;}parse(t,e,r,n,i={}){return e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return "assert"===r?new Ge(e,[t]):"coerce"===r?new Ze(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const n=t[0];if("string"!=typeof n)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[n];if(i){let n=i.parse(t,this);if(!n)return null;if(this.expectedType){const t=this.expectedType,i=n.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind){if("projectionDefinition"===t.kind&&["string","array"].includes(i.kind)||["color","formatted","resolvedImage"].includes(t.kind)&&["value","string"].includes(i.kind)||["padding","numberArray"].includes(t.kind)&&["value","number","array"].includes(i.kind)||"colorArray"===t.kind&&["value","string","array"].includes(i.kind)||"variableAnchorOffsetCollection"===t.kind&&["value","array"].includes(i.kind))n=r(n,t,e.typeAnnotation||"coerce");else if(this.checkSubtype(t,i))return null}else n=r(n,t,e.typeAnnotation||"assert");}if(!(n instanceof Ne)&&"resolvedImage"!==n.type.kind&&this._isConstant(n)){const t=new He;try{n=new Ne(n.type,n.evaluate(t));}catch(t){return this.error(t.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Ke(this.registry,this._isConstant,n,e||null,i,this.errors)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new Tt(r,t));}checkSubtype(t,e){const r=Wt(t,e);return r&&this.error(r),r}}class Je{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new Ve(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new Ve(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return !1}}class tr{constructor(t,e){this.type=Dt,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);return r&&n?Qt(r.type,[Dt,$t,Ft,Vt,Ut])?new tr(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);if(!te(r,["string","array"]))throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return !0}}class er{constructor(t,e,r){this.type=Ft,this.needle=t,this.haystack=e,this.fromIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);if(!r||!n)return null;if(!Qt(r.type,[Dt,$t,Ft,Vt,Ut]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new er(r,n,i):null}return new er(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!te(e,["boolean","string","number","null"]))throw new Ve(`Expected first argument to be of type boolean, string, number or null, but found ${Kt(Ue(e))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(t)),te(r,["string"])){const t=r.indexOf(e,n);return -1===t?-1:[...r.slice(0,t)].length}if(te(r,["array"]))return r.indexOf(e,n);throw new Ve(`Expected second argument to be of type array or string, but found ${Kt(Ue(r))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return !1}}class rr{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(r){if(u.checkSubtype(r,Ue(t)))return null}else r=Ue(t);if(void 0!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length;}const c=e.parse(l,a,n);if(!c)return null;n=n||c.type,s.push(c);}const a=e.parse(t[1],1,Ut);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,n);return o?"value"!==a.type.kind&&e.concat(1).checkSubtype(r,a.type)?null:new rr(r,n,a,i,s,o):null}evaluate(t){const e=this.input.evaluate(t);return (Ue(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class nr{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class ir{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ft);if(!r||!n)return null;if(!Qt(r.type,[Ht(Ut),$t,Ut]))return e.error(`Expected first argument to be of type array or string, but found ${Kt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,Ft);return i?new ir(r.type,r,n,i):null}return new ir(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);let n;if(this.endIndex&&(n=this.endIndex.evaluate(t)),te(e,["string"]))return [...e].slice(r,n).join("");if(te(e,["array"]))return e.slice(r,n);throw new Ve(`Expected first argument to be of type array or string, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return !1}}function sr(t,e){const r=t.length-1;let n,i,s=0,a=r,o=0;for(;s<=a;)if(o=Math.floor((s+a)/2),n=t[o],i=t[o+1],n<=e){if(o===r||ee))throw new Ve("Input is not a number.");a=o-1;}return 0}class ar{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',o);const u=e.parse(a,l,i);if(!u)return null;i=i||u.type,n.push([s,u]);}return new ar(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[sr(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function or(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var lr,ur,cr=function(){if(ur)return lr;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return ur=1,lr=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},lr}(),hr=or(cr);class pr{constructor(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e);}static interpolationFactor(t,e,r,n){let i=0;if("exponential"===t.name)i=fr(e,t.base,r,n);else if("linear"===t.name)i=fr(e,1,r,n);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new hr(s[0],s[1],s[2],s[3]).solve(fr(e,1,r,n));}return i}static parse(t,e){let[r,n,i,...s]=t;if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){const t=n[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:t};}else {if("cubic-bezier"!==n[0])return e.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const t=n.slice(1);if(4!==t.length||t.some((t=>"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,Ft),!i)return null;const a=[];let o=null;"interpolate-hcl"!==r&&"interpolate-lab"!==r||e.expectedType==Gt?e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType):o=Lt;for(let t=0;t=r)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,o);if(!u)return null;o=o||u.type,a.push([r,u]);}return ee(o,Ft)||ee(o,Ot)||ee(o,Lt)||ee(o,qt)||ee(o,Xt)||ee(o,Gt)||ee(o,Yt)||ee(o,Ht(Ft))?new pr(o,r,n,i,a):e.error(`Type ${Kt(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=sr(e,n),a=pr.interpolationFactor(this.interpolation,n,e[s],e[s+1]),o=r[s].evaluate(t),l=r[s+1].evaluate(t);switch(this.operator){case "interpolate":switch(this.type.kind){case "number":return Ae(o,l,a);case "color":return Me.interpolate(o,l,a);case "padding":return Ee.interpolate(o,l,a);case "colorArray":return Be.interpolate(o,l,a);case "numberArray":return Te.interpolate(o,l,a);case "variableAnchorOffsetCollection":return $e.interpolate(o,l,a);case "array":return ke(o,l,a);case "projectionDefinition":return Le.interpolate(o,l,a)}case "interpolate-hcl":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"hcl");case "colorArray":return Be.interpolate(o,l,a,"hcl")}case "interpolate-lab":switch(this.type.kind){case "color":return Me.interpolate(o,l,a,"lab");case "colorArray":return Be.interpolate(o,l,a,"lab")}}}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function fr(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}const dr={color:Me.interpolate,number:Ae,padding:Ee.interpolate,numberArray:Te.interpolate,colorArray:Be.interpolate,variableAnchorOffsetCollection:$e.interpolate,array:ke};class yr{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r=null;const n=e.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const n of t.slice(1)){const t=e.parse(n,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!t)return null;r=r||t.type,i.push(t);}if(!r)throw new Error("No output type");const s=n&&i.some((t=>Wt(n,t.type)));return new yr(s?Ut:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(t),r&&r instanceof De&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break;return r}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function mr(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function gr(t,e,r,n){return 0===n.compare(e,r)}function xr(t,e,r){const n="=="!==t&&"!="!==t;return class i{constructor(t,e,r){this.type=Dt,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const r=t[0];let s=e.parse(t[1],1,Ut);if(!s)return null;if(!mr(r,s.type))return e.concat(1).error(`"${r}" comparisons are not supported for type '${Kt(s.type)}'.`);let a=e.parse(t[2],2,Ut);if(!a)return null;if(!mr(r,a.type))return e.concat(2).error(`"${r}" comparisons are not supported for type '${Kt(a.type)}'.`);if(s.type.kind!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error(`Cannot compare types '${Kt(s.type)}' and '${Kt(a.type)}'.`);n&&("value"===s.type.kind&&"value"!==a.type.kind?s=new Ge(a.type,[s]):"value"!==s.type.kind&&"value"===a.type.kind&&(a=new Ge(s.type,[a])));let o=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error("Cannot use collator to compare non-string types.");if(o=e.parse(t[3],3,jt),!o)return null}return new i(s,a,o)}evaluate(i){const s=this.lhs.evaluate(i),a=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=Ue(s),r=Ue(a);if(e.kind!==r.kind||"string"!==e.kind&&"number"!==e.kind)throw new Ve(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=Ue(s),r=Ue(a);if("string"!==t.kind||"string"!==r.kind)return e(i,s,a)}return this.collator?r(i,s,a,this.collator.evaluate(i)):e(i,s,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return !0}}}const vr=xr("==",(function(t,e,r){return e===r}),gr),br=xr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !gr(0,e,r,n)})),wr=xr("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),Sr=xr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),Ar=xr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class kr{constructor(t,e,r){this.type=jt,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");const n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,Dt);if(!n)return null;const i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Dt);if(!i)return null;let s=null;return r.locale&&(s=e.parse(r.locale,1,$t),!s)?null:new kr(n,i,s)}evaluate(t){return new Ie(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);}outputDefined(){return !1}}class Mr{constructor(t,e,r,n,i){this.type=$t,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,Ft);if(!r)return null;const n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=e.parse(n.locale,1,$t),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,$t),!s))return null;let a=null;if(n["min-fraction-digits"]&&(a=e.parse(n["min-fraction-digits"],1,Ft),!a))return null;let o=null;return n["max-fraction-digits"]&&(o=e.parse(n["max-fraction-digits"],1,Ft),!o)?null:new Mr(r,i,s,a,o)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return !1}}class Ir{constructor(t){this.type=Nt,this.sections=t;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");const n=[];let i=!1;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&"object"==typeof s&&!Array.isArray(s)){i=!1;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,Ft),!t))return null;let r=null;if(s["text-font"]&&(r=e.parse(s["text-font"],1,Ht($t)),!r))return null;let a=null;if(s["text-color"]&&(a=e.parse(s["text-color"],1,Lt),!a))return null;let o=null;if(s["vertical-align"]){if("string"==typeof s["vertical-align"]&&!ze.includes(s["vertical-align"]))return e.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${s["vertical-align"]}' instead.`);if(o=e.parse(s["vertical-align"],1,$t),!o)return null}const l=n[n.length-1];l.scale=t,l.font=r,l.textColor=a,l.verticalAlign=o;}else {const s=e.parse(t[r],1,Ut);if(!s)return null;const a=s.type.kind;if("string"!==a&&"value"!==a&&"null"!==a&&"resolvedImage"!==a)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:s,scale:null,font:null,textColor:null,verticalAlign:null});}}return new Ir(n)}evaluate(t){return new Ce(this.sections.map((e=>{const r=e.content.evaluate(t);return Ue(r)===Zt?new Pe("",r,null,null,null,e.verticalAlign?e.verticalAlign.evaluate(t):null):new Pe(je(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null,e.verticalAlign?e.verticalAlign.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor),e.verticalAlign&&t(e.verticalAlign);}outputDefined(){return !1}}class zr{constructor(t){this.type=Zt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,$t);return r?new zr(r):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),r=De.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r}eachChild(t){t(this.input);}outputDefined(){return !1}}class Pr{constructor(t){this.type=Ft,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${Kt(r.type)} instead.`):new Pr(r):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return [...e].length;if(Array.isArray(e))return e.length;throw new Ve(`Expected value to be of type string or array, but found ${Kt(Ue(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return !1}}const Cr=8192;function Er(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*Cr),Math.round(n*i*Cr)]}function Tr(t,e){const r=Math.pow(2,e.z);return [(i=(t[0]/Cr+e.x)/r,360*i-180),(n=(t[1]/Cr+e.y)/r,360/Math.PI*Math.atan(Math.exp((180-360*n)*Math.PI/180))-90)];var n,i;}function Br(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function Vr(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function Fr(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],a=t[1]-r[1];return n*a-s*i==0&&n*s<=0&&i*a<=0}function $r(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!jr(t,e,r,n)||!jr(r,n,t,e));var i,s;}function Dr(t,e,r){for(const n of r)for(let r=0;r(i=t)[1]!=(a=o[e+1])[1]>i[1]&&i[0]<(a[0]-s[0])*(i[1]-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}var i,s,a;return n}function Or(t,e){for(const r of e)if(Lr(t,r))return !0;return !1}function Rr(t,e){for(const r of t)if(!Lr(r,e))return !1;for(let r=0;r0&&o<0||a<0&&o>0}function Nr(t,e,r){const n=[];for(let i=0;ir[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i;}Br(e,t);}function Xr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];Gr(n,e,r,i),a.push(n);}return a}function Zr(t,e,r,n){const i=Math.pow(2,n.z)*Cr,s=[n.x*Cr,n.y*Cr],a=[];for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];Br(e,r),t.push(r);}a.push(t);}if(e[2]-e[0]<=i/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const n of t)Gr(n,e,r,i);}var o;return a}class Yr{constructor(t,e){this.type=Dt,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const r of e.features){const{type:e,coordinates:n}=r.geometry;"Polygon"===e&&t.push(n),"MultiPolygon"===e&&t.push(...n);}if(t.length)return new Yr(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new Yr(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new Yr(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Lr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Xr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Or(t,s))return !1}return !0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Nr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Rr(t,s))return !1}if("MultiPolygon"===e.type){const s=qr(e.coordinates,n,i),a=Zr(t.geometry(),r,n,i);if(!Vr(r,n))return !1;for(const t of a)if(!Ur(t,s))return !1}return !0}(t,this.geometries)}return !1}eachChild(){}outputDefined(){return !0}}let Hr=class{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}};function Kr(t,e,r=0,n=t.length-1,i=Wr){for(;n>r;){if(n-r>600){const s=n-r+1,a=e-r+1,o=Math.log(s),l=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*l*(s-l)/s)*(a-s/2<0?-1:1);Kr(t,e,Math.max(r,Math.floor(e-a*l/s+u)),Math.min(n,Math.floor(e+(s-a)*l/s+u)),i);}const s=t[e];let a=r,o=n;for(Jr(t,r,e),i(t[n],s)>0&&Jr(t,r,n);a0;)o--;}0===i(t[r],s)?Jr(t,r,o):(o++,Jr(t,o,n)),o<=e&&(r=o+1),e<=o&&(n=o-1);}}function Jr(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function Wr(t,e){return te?1:0}function Qr(t,e){if(t.length<=1)return [t];const r=[];let n,i;for(const e of t){const t=en(e);0!==t&&(e.area=Math.abs(t),void 0===i&&(i=t<0),i===t<0?(n&&r.push(n),n=[e]):n.push(e));}if(n&&r.push(n),e>1)for(let t=0;t1?(l=t[o+1][0],u=t[o+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function on(t,e){return e[0]-t[0]}function ln(t){return t[1]-t[0]+1}function un(t,e){return t[1]>=t[0]&&t[1]t[1])return [null,null];const r=ln(t);if(e){if(2===r)return [t,null];const e=Math.floor(r/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===r)return [t,null];const n=Math.floor(r/2)-1;return [[t[0],t[0]+n],[t[0]+n+1,t[1]]]}function hn(t,e){if(!un(e,t.length))return [1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=e[0];n<=e[1];++n)Br(r,t[n]);return r}function pn(t){const e=[1/0,1/0,-1/0,-1/0];for(const r of t)for(const t of r)Br(e,t);return e}function fn(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function dn(t,e,r){if(!fn(t)||!fn(e))return NaN;let n=0,i=0;return t[2]e[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if(Vr(i,s)){if(wn(t,e))return 0}else if(wn(e,t))return 0;let a=1/0;for(const n of t)for(let t=0,i=n.length,s=i-1;t0;){const i=a.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(ln(l)<=u){if(!un(l,t.length))return NaN;if(e){const e=bn(t,l,r,n);if(isNaN(e)||0===e)return e;s=Math.min(s,e);}else for(let e=l[0];e<=l[1];++e){const i=vn(t[e],r,n);if(s=Math.min(s,i),0===s)return 0}}else {const r=cn(l,e);Sn(a,s,n,t,o,r[0]),Sn(a,s,n,t,o,r[1]);}}return s}function Mn(t,e,r,n,i,s=1/0){let a=Math.min(s,i.distance(t[0],r[0]));if(0===a)return a;const o=new Hr([[0,[0,t.length-1],[0,r.length-1]]],on);for(;o.length>0;){const s=o.pop();if(s[0]>=a)continue;const l=s[1],u=s[2],c=e?50:100,h=n?50:100;if(ln(l)<=c&&ln(u)<=h){if(!un(l,t.length)&&un(u,r.length))return NaN;let s;if(e&&n)s=gn(t,l,r,u,i),a=Math.min(a,s);else if(e&&!n){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=yn(r[t],e,i),a=Math.min(a,s),0===a)return a}else if(!e&&n){const e=r.slice(u[0],u[1]+1);for(let r=l[0];r<=l[1];++r)if(s=yn(t[r],e,i),a=Math.min(a,s),0===a)return a}else s=xn(t,l,r,u,i),a=Math.min(a,s);}else {const s=cn(l,e),c=cn(u,n);An(o,a,i,t,r,s[0],c[0]),An(o,a,i,t,r,s[0],c[1]),An(o,a,i,t,r,s[1],c[0]),An(o,a,i,t,r,s[1],c[1]);}}return a}function In(t){return "MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class zn{constructor(t,e){this.type=Ft,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Re(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new zn(e,e.features.map((t=>In(t.geometry))).flat());if("Feature"===e.type)return new zn(e,In(e.geometry));if("type"in e&&"coordinates"in e)return new zn(e,In(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!1,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!1,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!1,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Tr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new an(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case "Point":s=Math.min(s,Mn(n,!0,[t.coordinates],!1,i,s));break;case "LineString":s=Math.min(s,Mn(n,!0,t.coordinates,!0,i,s));break;case "Polygon":s=Math.min(s,kn(n,!0,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const r=t.geometry();if(0===r.length||0===r[0].length)return NaN;const n=Qr(r,0).map((e=>e.map((e=>e.map((e=>Tr([e.x,e.y],t.canonical))))))),i=new an(n[0][0][0][1]);let s=1/0;for(const t of e)for(const e of n){switch(t.type){case "Point":s=Math.min(s,kn([t.coordinates],!1,e,i,s));break;case "LineString":s=Math.min(s,kn(t.coordinates,!0,e,i,s));break;case "Polygon":s=Math.min(s,_n(e,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return !0}}class Pn{constructor(t){this.type=Ut,this.key=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=t[1];return null==r?e.error("Global state property must be defined."):"string"!=typeof r?e.error(`Global state property must be string, but found ${typeof t[1]} instead.`):new Pn(r)}evaluate(t){var e;const r=null===(e=t.globals)||void 0===e?void 0:e.globalState;return r&&0!==Object.keys(r).length?xe(r,this.key):null}eachChild(){}outputDefined(){return !1}}const Cn={"==":vr,"!=":br,">":_r,"<":wr,">=":Ar,"<=":Sr,array:Ge,at:Qe,boolean:Ge,case:nr,coalesce:yr,collator:kr,format:Ir,image:zr,in:tr,"index-of":er,interpolate:pr,"interpolate-hcl":pr,"interpolate-lab":pr,length:Pr,let:Je,literal:Ne,match:rr,number:Ge,"number-format":Mr,object:Ge,slice:ir,step:ar,string:Ge,"to-boolean":Ze,"to-color":Ze,"to-number":Ze,"to-string":Ze,var:We,within:Yr,distance:zn,"global-state":Pn};class En{constructor(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return !1}static parse(t,e){const r=t[0],n=En.definitions[r];if(!n)return e.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let o=null;for(const[n,s]of a){o=new Ke(e.registry,$n,e.path,null,e.scope);const a=[];let l=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(Kt).join(", ")})`:`(${Kt(e.type)}...)`;var e;})).join(" | "),n=[];for(let r=1;r{r=e?r&&$n(t):r&&t instanceof Ne;})),!!r&&Dn(t)&&On(t,["zoom","heatmap-density","elevation","line-progress","accumulated","is-supported-script"])}function Dn(t){if(t instanceof En){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}if(t instanceof Yr)return !1;if(t instanceof zn)return !1;let e=!0;return t.eachChild((t=>{e&&!Dn(t)&&(e=!1);})),e}function Ln(t){if(t instanceof En&&"feature-state"===t.name)return !1;let e=!0;return t.eachChild((t=>{e&&!Ln(t)&&(e=!1);})),e}function On(t,e){if(t instanceof En&&e.indexOf(t.name)>=0)return !1;let r=!0;return t.eachChild((t=>{r&&!On(t,e)&&(r=!1);})),r}function Rn(t){return {result:"success",value:t}}function Un(t){return {result:"error",value:t}}function jn(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Nn(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function qn(t){return !!t.expression&&t.expression.interpolated}function Gn(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Xn(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)&&Ue(t)===Rt}function Zn(t){return t}function Yn(t,e){const r=t.stops&&"object"==typeof t.stops[0][0],n=r||!(r||void 0!==t.property),i=t.type||(qn(e)?"exponential":"interval"),s=function(t){switch(t.type){case "color":return Me.parse;case "padding":return Ee.parse;case "numberArray":return Te.parse;case "colorArray":return Be.parse;default:return null}}(e);if(s&&((t=Et({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],s(t[1])]))),t.default=s(t.default?t.default:e.default)),t.colorSpace&&"rgb"!==(a=t.colorSpace)&&"hcl"!==a&&"lab"!==a)throw new Error(`Unknown color space: "${t.colorSpace}"`);var a;const o=function(t){switch(t){case "exponential":return Wn;case "interval":return Jn;case "categorical":return Kn;case "identity":return Qn;default:throw new Error(`Unknown function type "${t}"`)}}(i);let l,u;if("categorical"===i){l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0];}if(r){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>Wn({stops:i,base:t.base},e,r).evaluate(r,n)}}if(n){const r="exponential"===i?{name:"exponential",base:void 0!==t.base?t.base:1}:null;return {kind:"camera",interpolationType:r,interpolationFactor:pr.interpolationFactor.bind(void 0,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>o(t,e,r,l,u)}}return {kind:"source",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:void 0;return void 0===i?Hn(t.default,e.default):o(t,e,i,l,u)}}}function Hn(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Kn(t,e,r,n,i){return Hn(typeof r===i?n[r]:void 0,t.default,e.default)}function Jn(t,e,r){if("number"!==Gn(r))return Hn(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=sr(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function Wn(t,e,r){const n=void 0!==t.base?t.base:1;if("number"!==Gn(r))return Hn(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=sr(t.stops.map((t=>t[0])),r),a=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),o=t.stops[s][1],l=t.stops[s+1][1],u=dr[e.type]||Zn;return "function"==typeof o.evaluate?{evaluate(...e){const r=o.evaluate.apply(void 0,e),n=l.evaluate.apply(void 0,e);if(void 0!==r&&void 0!==n)return u(r,n,a,t.colorSpace)}}:u(o,l,a,t.colorSpace)}function Qn(t,e,r){switch(e.type){case "color":r=Me.parse(r);break;case "formatted":r=Ce.fromString(r.toString());break;case "resolvedImage":r=De.fromString(r.toString());break;case "padding":r=Ee.parse(r);break;case "colorArray":r=Be.parse(r);break;case "numberArray":r=Te.parse(r);break;default:Gn(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0);}return Hn(r,t.default,e.default)}En.register(Cn,{error:[{kind:"error"},[$t],(t,[e])=>{throw new Ve(e.evaluate(t))}],typeof:[$t,[Ut],(t,[e])=>Kt(Ue(e.evaluate(t)))],"to-rgba":[Ht(Ft,4),[Lt],(t,[e])=>{const[r,n,i,s]=e.evaluate(t).rgb;return [255*r,255*n,255*i,s]}],rgb:[Lt,[Ft,Ft,Ft],Tn],rgba:[Lt,[Ft,Ft,Ft,Ft],Tn],has:{type:Dt,overloads:[[[$t],(t,[e])=>Bn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Bn(e.evaluate(t),r.evaluate(t))]]},get:{type:Ut,overloads:[[[$t],(t,[e])=>Vn(e.evaluate(t),t.properties())],[[$t,Rt],(t,[e,r])=>Vn(e.evaluate(t),r.evaluate(t))]]},"feature-state":[Ut,[$t],(t,[e])=>Vn(e.evaluate(t),t.featureState||{})],properties:[Rt,[],t=>t.properties()],"geometry-type":[$t,[],t=>t.geometryType()],id:[Ut,[],t=>t.id()],zoom:[Ft,[],t=>t.globals.zoom],"heatmap-density":[Ft,[],t=>t.globals.heatmapDensity||0],elevation:[Ft,[],t=>t.globals.elevation||0],"line-progress":[Ft,[],t=>t.globals.lineProgress||0],accumulated:[Ut,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[Ft,Fn(Ft),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],"*":[Ft,Fn(Ft),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],"-":{type:Ft,overloads:[[[Ft,Ft],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[Ft],(t,[e])=>-e.evaluate(t)]]},"/":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],"%":[Ft,[Ft,Ft],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[Ft,[],()=>Math.LN2],pi:[Ft,[],()=>Math.PI],e:[Ft,[],()=>Math.E],"^":[Ft,[Ft,Ft],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[Ft,[Ft],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))],log2:[Ft,[Ft],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[Ft,[Ft],(t,[e])=>Math.sin(e.evaluate(t))],cos:[Ft,[Ft],(t,[e])=>Math.cos(e.evaluate(t))],tan:[Ft,[Ft],(t,[e])=>Math.tan(e.evaluate(t))],asin:[Ft,[Ft],(t,[e])=>Math.asin(e.evaluate(t))],acos:[Ft,[Ft],(t,[e])=>Math.acos(e.evaluate(t))],atan:[Ft,[Ft],(t,[e])=>Math.atan(e.evaluate(t))],min:[Ft,Fn(Ft),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[Ft,Fn(Ft),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[Ft,[Ft],(t,[e])=>Math.abs(e.evaluate(t))],round:[Ft,[Ft],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[Ft,[Ft],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[Ft,[Ft],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[Dt,[$t,Ut],(t,[e,r])=>t.properties()[e.value]===r.value],"filter-id-==":[Dt,[Ut],(t,[e])=>t.id()===e.value],"filter-type-==":[Dt,[$t],(t,[e])=>t.geometryType()===e.value],"filter-<":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],"filter-<=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],"filter->=":[Dt,[$t,Ut],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[Dt,[Ut],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],"filter-has":[Dt,[Ut],(t,[e])=>e.value in t.properties()],"filter-has-id":[Dt,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[Dt,[Ht($t)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[Dt,[Ht(Ut)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[Dt,[$t,Ht(Ut)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[Dt,[$t,Ht(Ut)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(!r.evaluate(t))return !1;return !0}]]},any:{type:Dt,overloads:[[[Dt,Dt],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[Fn(Dt),(t,e)=>{for(const r of e)if(r.evaluate(t))return !0;return !1}]]},"!":[Dt,[Dt],(t,[e])=>!e.evaluate(t)],"is-supported-script":[Dt,[$t],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return !r||r(e.evaluate(t))}],upcase:[$t,[$t],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[$t,[$t],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[$t,Fn(Ut),(t,e)=>e.map((e=>je(e.evaluate(t)))).join("")],"resolved-locale":[$t,[jt],(t,[e])=>e.evaluate(t).resolvedLocale()]});class ti{constructor(t,e,r){this.expression=t,this._warningHistory={},this._evaluator=new He,this._defaultValue=e?function(t){if("color"===t.type&&Xn(t.default))return new Me(0,0,0,0);switch(t.type){case "color":return Me.parse(t.default)||null;case "padding":return Ee.parse(t.default)||null;case "numberArray":return Te.parse(t.default)||null;case "colorArray":return Be.parse(t.default)||null;case "variableAnchorOffsetCollection":return $e.parse(t.default)||null;case "projectionDefinition":return Le.parse(t.default)||null;default:return void 0===t.default?null:t.default}}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null,this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s){this._globalState&&(t={...t,globalState:this._globalState}),this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new Ve(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function ei(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Cn}function ri(t,e,r){const n=new Ke(Cn,$n,[],e?function(t){const e={color:Lt,string:$t,number:Ft,enum:$t,boolean:Dt,formatted:Nt,padding:qt,numberArray:Xt,colorArray:Gt,projectionDefinition:Ot,resolvedImage:Zt,variableAnchorOffsetCollection:Yt};return "array"===t.type?Ht(e[t.value]||Ut,t.length):e[t.type]}(e):void 0),i=n.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return i?Rn(new ti(i,e,r)):Un(n.errors)}class ni{constructor(t,e,r){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this._globalState=r;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}}class ii{constructor(t,e,r,n,i){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!Ln(e.expression),this.globalStateRefs=li(e.expression),this.interpolationType=n,this._globalState=i;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._globalState&&(t={...t,globalState:this._globalState}),this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?pr.interpolationFactor(this.interpolationType,t,e,r):0}}function si(t,e,r){const n=ri(t,e,r);if("error"===n.result)return n;const i=n.value.expression,s=Dn(i);if(!s&&!jn(e))return Un([new Tt("","data expressions not supported")]);const a=On(i,["zoom"]);if(!a&&!Nn(e))return Un([new Tt("","zoom expressions not supported")]);const o=oi(i);return o||a?o instanceof Tt?Un([o]):o instanceof pr&&!qn(e)?Un([new Tt("",'"interpolate" expressions cannot be used with this property')]):Rn(o?new ii(s?"camera":"composite",n.value,o.labels,o instanceof pr?o.interpolation:void 0,r):new ni(s?"constant":"source",n.value,r)):Un([new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class ai{constructor(t,e){this._parameters=t,this._specification=e,Et(this,Yn(this._parameters,this._specification));}static deserialize(t){return new ai(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function oi(t){let e=null;if(t instanceof Je)e=oi(t.result);else if(t instanceof yr){for(const r of t.args)if(e=oi(r),e)break}else (t instanceof ar||t instanceof pr)&&t.input instanceof En&&"zoom"===t.input.name&&(e=t);return e instanceof Tt||t.eachChild((t=>{const r=oi(t);r instanceof Tt?e=r:!e&&r?e=new Tt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&r&&e!==r&&(e=new Tt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),e}function li(t,e=new Set){return t instanceof Pn&&e.add(t.key),t.eachChild((t=>{li(t,e);})),e}function ui(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case "has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case "in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case "!in":case "!has":case "none":return !1;case "==":case "!=":case ">":case ">=":case "<":case "<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case "any":case "all":for(const e of t.slice(1))if(!ui(e)&&"boolean"!=typeof e)return !1;return !0;default:return !0}}const ci={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function hi(t,e){if(null==t)return {filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set};ui(t)||(t=di(t));const r=ri(t,ci,e);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return {filter:(t,e,n)=>r.value.evaluate(t,e,{},n),needGeometry:fi(t),getGlobalStateRefs:()=>li(r.value.expression)}}function pi(t,e){return te?1:0}function fi(t){if(!Array.isArray(t))return !1;if("within"===t[0]||"distance"===t[0])return !0;for(let e=1;e"===e||"<="===e||">="===e?yi(t[1],t[2],e):"any"===e?(r=t.slice(1),["any"].concat(r.map(di))):"all"===e?["all"].concat(t.slice(1).map(di)):"none"===e?["all"].concat(t.slice(1).map(di).map(xi)):"in"===e?mi(t[1],t.slice(2)):"!in"===e?xi(mi(t[1],t.slice(2))):"has"===e?gi(t[1]):"!has"!==e||xi(gi(t[1]));var r;}function yi(t,e,r){switch(t){case "$type":return [`filter-type-${r}`,e];case "$id":return [`filter-id-${r}`,e];default:return [`filter-${r}`,t,e]}}function mi(t,e){if(0===e.length)return !1;switch(t){case "$type":return ["filter-type-in",["literal",e]];case "$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(pi)]]:["filter-in-small",t,["literal",e]]}}function gi(t){switch(t){case "$type":return !0;case "$id":return ["filter-has-id"];default:return ["filter-has",t]}}function xi(t){return ["!",t]}function vi(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const r of t)e+=`${vi(r)},`;return `${e}]`}const r=Object.keys(t).sort();let n="{";for(let e=0;en.maximum?[new Ct(e,r,`${r} is greater than the maximum value ${n.maximum}`)]:[]}function Ii(t){const e=t.valueSpec,r=_i(t.value.type);let n,i,s,a={};const o="categorical"!==r&&void 0===t.value.property,l=!o,u="array"===Gn(t.value.stops)&&"array"===Gn(t.value.stops[0])&&"object"===Gn(t.value.stops[0][0]),c=Ai({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===r)return [new Ct(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const n=t.value;return e=e.concat(ki({key:t.key,value:n,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===Gn(n)&&0===n.length&&e.push(new Ct(t.key,n,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===r&&o&&c.push(new Ct(t.key,t.value,'missing required property "property"')),"identity"===r||t.value.stops||c.push(new Ct(t.key,t.value,'missing required property "stops"')),"exponential"===r&&t.valueSpec.expression&&!qn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!jn(t.valueSpec)?c.push(new Ct(t.key,t.value,"property functions not supported")):o&&!Nn(t.valueSpec)&&c.push(new Ct(t.key,t.value,"zoom functions not supported"))),"categorical"!==r&&!u||void 0!==t.value.property||c.push(new Ct(t.key,t.value,'"property" property is required')),c;function h(t){let r=[];const n=t.value,o=t.key;if("array"!==Gn(n))return [new Ct(o,n,`array expected, ${Gn(n)} found`)];if(2!==n.length)return [new Ct(o,n,`array length 2 expected, length ${n.length} found`)];if(u){if("object"!==Gn(n[0]))return [new Ct(o,n,`object expected, ${Gn(n[0])} found`)];if(void 0===n[0].zoom)return [new Ct(o,n,"object stop key must have zoom")];if(void 0===n[0].value)return [new Ct(o,n,"object stop key must have value")];if(s&&s>_i(n[0].zoom))return [new Ct(o,n[0].zoom,"stop zoom values must appear in ascending order")];_i(n[0].zoom)!==s&&(s=_i(n[0].zoom),i=void 0,a={}),r=r.concat(Ai({key:`${o}[0]`,value:n[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Mi,value:p}}));}else r=r.concat(p({key:`${o}[0]`,value:n[0],validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},n));return ei(Si(n[1]))?r.concat([new Ct(`${o}[1]`,n[1],"expressions are not allowed in function stops.")]):r.concat(t.validateSpec({key:`${o}[1]`,value:n[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const o=Gn(t.value),l=_i(t.value),u=null!==t.value?t.value:s;if(n){if(o!==n)return [new Ct(t.key,u,`${o} stop domain type must match previous stop domain type ${n}`)]}else n=o;if("number"!==o&&"string"!==o&&"boolean"!==o)return [new Ct(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==o&&"categorical"!==r){let n=`number expected, ${o} found`;return jn(e)&&void 0===r&&(n+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new Ct(t.key,u,n)]}return "categorical"!==r||"number"!==o||isFinite(l)&&Math.floor(l)===l?"categorical"!==r&&"number"===o&&void 0!==i&&lnew Ct(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new Ct(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!Ln(r))return [new Ct(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!On(r,["zoom","feature-state"]))return [new Ct(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!Dn(r))return [new Ct(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function Pi(t){const e=t.key,r=t.value,n=Gn(r);return "string"!==n?[new Ct(e,r,`color expected, ${n} found`)]:Me.parse(String(r))?[]:[new Ct(e,r,`color expected, "${r}" found`)]}function Ci(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${n.values.join(", ")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(_i(r))&&i.push(new Ct(e,r,`expected one of [${Object.keys(n.values).join(", ")}], ${JSON.stringify(r)} found`)),i}function Ei(t){return ui(Si(t.value))?zi(Et({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):Ti(t)}function Ti(t){const e=t.value,r=t.key;if("array"!==Gn(e))return [new Ct(r,e,`array expected, ${Gn(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return [new Ct(r,e,"filter array must have at least 1 element")];switch(s=s.concat(Ci({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),_i(e[0])){case "<":case "<=":case ">":case ">=":e.length>=2&&"$type"===_i(e[1])&&s.push(new Ct(r,e,`"$type" cannot be use with operator "${e[0]}"`));case "==":case "!=":3!==e.length&&s.push(new Ct(r,e,`filter array for operator "${e[0]}" must have 3 elements`));case "in":case "!in":e.length>=2&&(i=Gn(e[1]),"string"!==i&&s.push(new Ct(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let a=2;a{t in r&&e.push(new Ct(n,r[t],`"${t}" is prohibited for ref layers`));})),i.layers.forEach((e=>{_i(e.id)===o&&(t=e);})),t?t.ref?e.push(new Ct(n,r.ref,"ref cannot reference another ref layer")):a=_i(t.type):e.push(new Ct(n,r.ref,`ref layer "${o}" not found`));}else if("background"!==a)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&_i(t.type);t?"vector"===s&&"raster"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster source`)):"raster-dem"!==s&&"hillshade"===a||"raster-dem"!==s&&"color-relief"===a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a raster-dem source`)):"raster"===s&&"raster"!==a?e.push(new Ct(n,r.source,`layer "${r.id}" requires a vector source`)):"vector"!==s||r["source-layer"]?"raster-dem"===s&&"hillshade"!==a&&"color-relief"!==a?e.push(new Ct(n,r.source,"raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.")):"line"!==a||!r.paint||!r.paint["line-gradient"]||"geojson"===s&&t.lineMetrics||e.push(new Ct(n,r,`layer "${r.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new Ct(n,r,`layer "${r.id}" must specify a "source-layer"`)):e.push(new Ct(n,r.source,`source "${r.source}" not found`));}else e.push(new Ct(n,r,'missing required property "source"'));return e=e.concat(Ai({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:r,objectKey:"type"}),filter:Ei,layout:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Fi(Et({layerType:a},t))}}),paint:t=>Ai({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Vi(Et({layerType:a},t))}})}})),e}function Di(t){const e=t.value,r=t.key,n=Gn(e);return "string"!==n?[new Ct(r,e,`string expected, ${n} found`)]:[]}const Li={promoteId:function({key:t,value:e}){if("string"===Gn(e))return Di({key:t,value:e});{const r=[];for(const n in e)r.push(...Di({key:`${t}.${n}`,value:e[n]}));return r}}};function Oi(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return [new Ct(r,e,'"type" is required')];const a=_i(e.type);let o;switch(a){case "vector":case "raster":return o=Ai({key:r,value:e,valueSpec:n[`source_${a.replace("-","_")}`],style:t.style,styleSpec:n,objectElementValidators:Li,validateSpec:s}),o;case "raster-dem":return o=function(t){var e;const r=null!==(e=t.sourceName)&&void 0!==e?e:"",n=t.value,i=t.styleSpec,s=i.source_raster_dem,a=t.style;let o=[];const l=Gn(n);if(void 0===n)return o;if("object"!==l)return o.push(new Ct("source_raster_dem",n,`object expected, ${l} found`)),o;const u="custom"===_i(n.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in n)!u&&c.includes(e)?o.push(new Ct(e,n[e],`In "${r}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?o=o.concat(t.validateSpec({key:e,value:n[e],valueSpec:s[e],validateSpec:t.validateSpec,style:a,styleSpec:i})):o.push(new Ct(e,n[e],`unknown property "${e}"`));return o}({sourceName:r,value:e,style:t.style,styleSpec:n,validateSpec:s}),o;case "geojson":if(o=Ai({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,validateSpec:s,objectElementValidators:Li}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],s="string"==typeof n?[n,["accumulated"],["get",t]]:n;o.push(...zi({key:`${r}.${t}.map`,value:i,expressionContext:"cluster-map"})),o.push(...zi({key:`${r}.${t}.reduce`,value:s,expressionContext:"cluster-reduce"}));}return o;case "video":return Ai({key:r,value:e,valueSpec:n.source_video,style:i,validateSpec:s,styleSpec:n});case "image":return Ai({key:r,value:e,valueSpec:n.source_image,style:i,validateSpec:s,styleSpec:n});case "canvas":return [new Ct(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Ci({key:`${r}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]}})}}function Ri(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("light",e,`object expected, ${a} found`)]),s;for(const a in e){const o=a.match(/^(.*)-transition$/);s=s.concat(o&&n[o[1]]&&n[o[1]].transition?t.validateSpec({key:a,value:e[a],valueSpec:r.transition,validateSpec:t.validateSpec,style:i,styleSpec:r}):n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);}return s}function Ui(t){const e=t.value,r=t.styleSpec,n=r.sky,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("sky",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a}function ji(t){const e=t.value,r=t.styleSpec,n=r.terrain,i=t.style;let s=[];const a=Gn(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new Ct("terrain",e,`object expected, ${a} found`)]),s;for(const a in e)s=s.concat(n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new Ct(a,e[a],`unknown property "${a}"`)]);return s}function Ni(t){let e=[];const r=t.value,n=t.key;if(Array.isArray(r)){const i=[],s=[];for(const a in r)r[a].id&&i.includes(r[a].id)&&e.push(new Ct(n,r,`all the sprites' ids must be unique, but ${r[a].id} is duplicated`)),i.push(r[a].id),r[a].url&&s.includes(r[a].url)&&e.push(new Ct(n,r,`all the sprites' URLs must be unique, but ${r[a].url} is duplicated`)),s.push(r[a].url),e=e.concat(Ai({key:`${n}[${a}]`,value:r[a],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:t.validateSpec}));return e}return Di({key:n,value:r})}function qi(t){return e=t.value,Boolean(e)&&e.constructor===Object?[]:[new Ct(t.key,t.value,`object expected, ${Gn(t.value)} found`)];var e;}const Gi={"*":()=>[],array:ki,boolean:function(t){const e=t.value,r=t.key,n=Gn(e);return "boolean"!==n?[new Ct(r,e,`boolean expected, ${n} found`)]:[]},number:Mi,color:Pi,constants:wi,enum:Ci,filter:Ei,function:Ii,layer:$i,object:Ai,source:Oi,light:Ri,sky:Ui,terrain:ji,projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style,s=Gn(e);if(void 0===e)return [];if("object"!==s)return [new Ct("projection",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new Ct(s,e[s],`unknown property "${s}"`)]);return a},projectionDefinition:function(t){const e=t.key;let r=t.value;r=r instanceof String?r.valueOf():r;const n=Gn(r);return "array"!==n||function(t){return Array.isArray(t)&&3===t.length&&"string"==typeof t[0]&&"string"==typeof t[1]&&"number"==typeof t[2]}(r)||function(t){return !!["interpolate","step","literal"].includes(t[0])}(r)?["array","string"].includes(n)?[]:[new Ct(e,r,`projection expected, invalid type "${n}" found`)]:[new Ct(e,r,`projection expected, invalid array ${JSON.stringify(r)} found`)]},string:Di,formatted:function(t){return 0===Di(t).length?[]:zi(t)},resolvedImage:function(t){return 0===Di(t).length?[]:zi(t)},padding:function(t){const e=t.key,r=t.value;if("array"===Gn(r)){if(r.length<1||r.length>4)return [new Ct(e,r,`padding requires 1 to 4 values; ${r.length} values found`)];const n={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(r=r.concat(wi({key:"constants",value:t.constants}))),Ki(r)}function Hi(t){return function(e){return t({...e,validateSpec:Xi})}}function Ki(t){return [].concat(t).sort(((t,e)=>t.line-e.line))}function Ji(t){return function(...e){return Ki(t.apply(this,e))}}Yi.source=Ji(Hi(Oi)),Yi.sprite=Ji(Hi(Ni)),Yi.glyphs=Ji(Hi(Zi)),Yi.light=Ji(Hi(Ri)),Yi.sky=Ji(Hi(Ui)),Yi.terrain=Ji(Hi(ji)),Yi.state=Ji(Hi(qi)),Yi.layer=Ji(Hi($i)),Yi.filter=Ji(Hi(Ei)),Yi.paintProperty=Ji(Hi(Vi)),Yi.layoutProperty=Ji(Hi(Fi));const Wi=Yi,Qi=Wi.light,ts=Wi.sky,es=Wi.paintProperty,rs=Wi.layoutProperty;function ns(t,e){let r=!1;if(e&&e.length)for(const n of e)t.fire(new mt(new Error(n.message))),r=!0;return r}class is{constructor(t,e,r){const n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(let t=0;t=u[l+0]&&n>=u[l+1])?(a[h]=!0,s.push(i[h])):a[h]=!1;}}}}_forEachCell(t,e,r,n,i,s,a,o){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!o||o(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,r,n,u,s,a,o))return}}_convertFromCellCoord(t){return (t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let r=0;for(let t=0;t=0)continue;const s=t[n];i[n]=ss[r].shallow.indexOf(n)>=0?s:cs(s,e);}t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==r&&(i.$name=r),i}function hs(t){if(us(t))return t;if(Array.isArray(t))return t.map(hs);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=ls(t)||"Object";if(!ss[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:r}=ss[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const r of Object.keys(t)){if("$name"===r)continue;const i=t[r];n[r]=ss[e].shallow.indexOf(r)>=0?i:hs(i);}return n}class ps{constructor(){this.first=!0;}update(t,e){const r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Hiragana:t=>t>=12352&&t<=12447,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"CJK Unified Ideographs":t=>t>=19968&&t<=40959,"Hangul Syllables":t=>t>=44032&&t<=55215,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function ds(t){for(const e of t)if(bs(e.charCodeAt(0)))return !0;return !1}function ys(t){for(const e of t)if(!xs(e.charCodeAt(0)))return !1;return !0}function ms(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const gs=ms(["Arab","Dupl","Mong","Ougr","Syrc"]);function xs(t){return !gs.test(String.fromCodePoint(t))}const vs=ms(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function bs(t){return !(746!==t&&747!==t&&(t<4352||!(fs["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||fs["CJK Compatibility"](t)||fs["CJK Strokes"](t)||!(!fs["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||fs["Enclosed CJK Letters and Months"](t)||fs["Ideographic Description Characters"](t)||fs.Kanbun(t)||fs.Katakana(t)&&12540!==t||!(!fs["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!fs["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||fs["Vertical Forms"](t)||fs["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||vs.test(String.fromCodePoint(t)))))}function ws(t){return !(bs(t)||function(t){return !!(fs["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||fs["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||fs["Letterlike Symbols"](t)||fs["Number Forms"](t)||fs["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||fs["Control Pictures"](t)&&9251!==t||fs["Optical Character Recognition"](t)||fs["Enclosed Alphanumerics"](t)||fs["Geometric Shapes"](t)||fs["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||fs["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||fs["CJK Symbols and Punctuation"](t)||fs.Katakana(t)||fs["Private Use Area"](t)||fs["CJK Compatibility Forms"](t)||fs["Small Form Variants"](t)||fs["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}const _s=ms(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Ss(t){return _s.test(String.fromCodePoint(t))}function As(t,e){return !(!e&&Ss(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||fs.Khmer(t))}function ks(t){for(const e of t)if(Ss(e.charCodeAt(0)))return !0;return !1}const Ms=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{};}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL;}getState(){return {pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){if(Ms.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText,this.loadScriptResolve();}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(t,r){return e(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if("loading"!==t.pluginStatus)return this.setState(t),t;const e=t.pluginURL,n=new Promise((t=>{this.loadScriptResolve=t;}));r(e);const i=new Promise((t=>setTimeout((()=>t()),this.TIMEOUT)));if(yield Promise.race([n,i]),this.isParsed()){const t={pluginStatus:"loaded",pluginURL:e};return this.setState(t),t}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${e}`)}))}};class Is{constructor(t,e){this.isSupportedScript=zs,this.zoom=t,e?(this.now=e.now||0,this.fadeDuration=e.fadeDuration||0,this.zoomHistory=e.zoomHistory||new ps,this.transition=e.transition||{}):(this.now=0,this.fadeDuration=0,this.zoomHistory=new ps,this.transition={});}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}}}function zs(t){return function(t,e){for(const r of t)if(!As(r.charCodeAt(0),e))return !1;return !0}(t,"loaded"===Ms.getRTLTextPluginStatus())}class Ps{constructor(t,e,r){this.property=t,this.value=e,this.expression=function(t,e,r){if(Xn(t))return new ai(t,e);if(ei(t)){const n=si(t,e,r);if("error"===n.result)throw new Error(n.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return n.value}{let r=t;return "color"===e.type&&"string"==typeof t?r=Me.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"numberArray"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"colorArray"!==e.type||"string"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)?r=$e.parse(t):"projectionDefinition"===e.type&&"string"==typeof t&&(r=Le.parse(t)):r=Be.parse(t):r=Te.parse(t):r=Ee.parse(t),{globalStateRefs:new Set,_globalState:null,kind:"constant",evaluate:()=>r}}}(void 0===e?t.specification.default:e,t.specification,r);}isDataDriven(){return "source"===this.expression.kind||"composite"===this.expression.kind}getGlobalStateRefs(){return this.expression.globalStateRefs||new Set}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class Cs{constructor(t,e){this.property=t,this.value=new Ps(t,void 0,e);}transitioned(t,e){return new Ts(this.property,this.value,e,L({},t.transition,this.transition),t.now)}untransitioned(){return new Ts(this.property,this.value,null,{},0)}}class Es{constructor(t,e){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues),this._globalState=e;}getValue(t){return j(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].value=new Ps(this._values[t].property,null===e?void 0:j(e),this._globalState);}getTransition(t){return j(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Cs(this._values[t].property,this._globalState)),this._values[t].transition=j(e)||void 0;}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r);const n=this.getTransition(e);void 0!==n&&(t[`${e}-transition`]=n);}return t}transitioned(t,e){const r=new Bs(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new Bs(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class Ts{constructor(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(nn.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Rs{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new Is(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Is(Math.floor(e.zoom),e)),t.expression.evaluate(new Is(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Us{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)}interpolate(){return !1}}class js{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const r=t[e];r.specification.overridable&&this.overridableProperties.push(e);const n=this.defaultPropertyValues[e]=new Ps(r,void 0,void 0),i=this.defaultTransitionablePropertyValues[e]=new Cs(r,void 0);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}}}as("DataDrivenProperty",Ls),as("DataConstantProperty",Ds),as("CrossFadedDataDrivenProperty",Os),as("CrossFadedProperty",Rs),as("ColorRampProperty",Us);const Ns="-transition";class qs extends gt{constructor(t,e,r){if(super(),this.id=t.id,this.type=t.type,this._globalState=r,this._featureFilter={filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>new Set},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter,this._featureFilter=hi(t.filter,r)),e.layout&&(this._unevaluatedLayout=new Vs(e.layout,r)),e.paint)){this._transitionablePaint=new Es(e.paint,r);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new $s(e.paint);}}setFilter(t){this.filter=t,this._featureFilter=hi(t,this._globalState);}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}getLayoutAffectingGlobalStateRefs(){const t=new Set;if(this._unevaluatedLayout)for(const e in this._unevaluatedLayout._values){const r=this._unevaluatedLayout._values[e];for(const e of r.getGlobalStateRefs())t.add(e);}for(const e of this._featureFilter.getGlobalStateRefs())t.add(e);return t}getPaintAffectingGlobalStateRefs(){var t;const e=new globalThis.Map;if(this._transitionablePaint)for(const r in this._transitionablePaint._values){const n=this._transitionablePaint._values[r].value;for(const i of n.getGlobalStateRefs()){const s=null!==(t=e.get(i))&&void 0!==t?t:[];s.push({name:r,value:n.value}),e.set(i,s);}}return e}setLayoutProperty(t,e,r={}){null!=e&&this._validate(rs,`layers.${this.id}.layout.${t}`,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);}getPaintProperty(t){return t.endsWith(Ns)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(es,`layers.${this.id}.paint.${t}`,t,e,r))return !1;if(t.endsWith(Ns))return this._transitionablePaint.setTransition(t.slice(0,-11),e||void 0),!1;{const r=this._transitionablePaint._values[t],n="cross-faded-data-driven"===r.property.specification["property-type"],i=r.value.isDataDriven(),s=r.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const a=this._transitionablePaint._values[t].value;return a.isDataDriven()||i||n||this._handleOverridablePaintPropertyUpdate(t,s,a)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,r){return !1}isHidden(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),U(t,((t,e)=>!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return (!i||!1!==i.validate)&&ns(this,t.call(Wi,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:xt,style:{glyphs:!0,sprite:!0}}))}is3D(){return !1}isTileClipped(){return !1}hasOffscreenPass(){return !1}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof Fs&&jn(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1}}const Gs={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Xs{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class Zs{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Ys(t,e=1){let r=0,n=0;return {members:t.map((t=>{const i=Gs[t.type].BYTES_PER_ELEMENT,s=r=Hs(r,Math.max(e,i)),a=t.components||1;return n=Math.max(n,i),r+=i*a,{name:t.name,type:t.type,components:a,offset:s}})),size:Hs(r,Math.max(n,e)),alignment:e}}function Hs(t,e){return Math.ceil(t/e)*e}class Ks extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}Ks.prototype.bytesPerElement=4,as("StructArrayLayout2i4",Ks);class Js extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}Js.prototype.bytesPerElement=6,as("StructArrayLayout3i6",Js);class Ws extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}Ws.prototype.bytesPerElement=8,as("StructArrayLayout4i8",Ws);class Qs extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}Qs.prototype.bytesPerElement=12,as("StructArrayLayout2i4i12",Qs);class ta extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=4*t,l=8*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.uint8[l+4]=n,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=a,t}}ta.prototype.bytesPerElement=8,as("StructArrayLayout2i4ub8",ta);class ea extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}ea.prototype.bytesPerElement=8,as("StructArrayLayout2f8",ea);class ra extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,s,a,o,l,u)}emplace(t,e,r,n,i,s,a,o,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=r,this.uint16[h+2]=n,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=a,this.uint16[h+6]=o,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}ra.prototype.bytesPerElement=20,as("StructArrayLayout10ui20",ra);class na extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,a,o,l,u,c,h)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=a,this.uint16[f+6]=o,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}na.prototype.bytesPerElement=24,as("StructArrayLayout4i4ui4i24",na);class ia extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}ia.prototype.bytesPerElement=12,as("StructArrayLayout3f12",ia);class sa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}sa.prototype.bytesPerElement=4,as("StructArrayLayout1ul4",sa);class aa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,s,a,o,l)}emplace(t,e,r,n,i,s,a,o,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=r,this.int16[c+2]=n,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=a,this.uint32[h+3]=o,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}aa.prototype.bytesPerElement=20,as("StructArrayLayout6i1ul2ui20",aa);class oa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}oa.prototype.bytesPerElement=12,as("StructArrayLayout2i2i2i12",oa);class la extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.int16[o+6]=i,this.int16[o+7]=s,t}}la.prototype.bytesPerElement=16,as("StructArrayLayout2f1f2i16",la);class ua extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=16*t,l=4*t,u=8*t;return this.uint8[o+0]=e,this.uint8[o+1]=r,this.float32[l+1]=n,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=a,t}}ua.prototype.bytesPerElement=16,as("StructArrayLayout2ub2f2i16",ua);class ca extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}ca.prototype.bytesPerElement=6,as("StructArrayLayout3ui6",ca);class ha extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=r,this.uint16[x+2]=n,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=a,this.uint32[v+4]=o,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}ha.prototype.bytesPerElement=48,as("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",ha);class pa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I){const z=this.length;return this.resize(z+1),this.emplace(z,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I,z){const P=32*t,C=16*t;return this.int16[P+0]=e,this.int16[P+1]=r,this.int16[P+2]=n,this.int16[P+3]=i,this.int16[P+4]=s,this.int16[P+5]=a,this.int16[P+6]=o,this.int16[P+7]=l,this.uint16[P+8]=u,this.uint16[P+9]=c,this.uint16[P+10]=h,this.uint16[P+11]=p,this.uint16[P+12]=f,this.uint16[P+13]=d,this.uint16[P+14]=y,this.uint16[P+15]=m,this.uint16[P+16]=g,this.uint16[P+17]=x,this.uint16[P+18]=v,this.uint16[P+19]=b,this.uint16[P+20]=w,this.uint16[P+21]=_,this.uint16[P+22]=S,this.uint32[C+12]=A,this.float32[C+13]=k,this.float32[C+14]=M,this.uint16[P+30]=I,this.uint16[P+31]=z,t}}pa.prototype.bytesPerElement=64,as("StructArrayLayout8i15ui1ul2f2ui64",pa);class fa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}fa.prototype.bytesPerElement=4,as("StructArrayLayout1f4",fa);class da extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}da.prototype.bytesPerElement=12,as("StructArrayLayout1ui2f12",da);class ya extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t}}ya.prototype.bytesPerElement=8,as("StructArrayLayout1ul2ui8",ya);class ma extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}ma.prototype.bytesPerElement=4,as("StructArrayLayout2ui4",ma);class ga extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}ga.prototype.bytesPerElement=2,as("StructArrayLayout1ui2",ga);class xa extends Zs{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}xa.prototype.bytesPerElement=16,as("StructArrayLayout4f16",xa);class va extends Xs{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new r(this.anchorPointX,this.anchorPointY)}}va.prototype.size=20;class ba extends aa{get(t){return new va(this,t)}}as("CollisionBoxArray",ba);class wa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t;}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}wa.prototype.size=48;class _a extends ha{get(t){return new wa(this,t)}}as("PlacedSymbolArray",_a);class Sa extends Xs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t;}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}Sa.prototype.size=64;class Aa extends pa{get(t){return new Sa(this,t)}}as("SymbolInstanceArray",Aa);class ka extends fa{getoffsetX(t){return this.float32[1*t+0]}}as("GlyphOffsetArray",ka);class Ma extends Js{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}as("SymbolLineVertexArray",Ma);class Ia extends Xs{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}Ia.prototype.size=12;class za extends da{get(t){return new Ia(this,t)}}as("TextAnchorOffsetArray",za);class Pa extends Xs{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}Pa.prototype.size=8;class Ca extends ya{get(t){return new Pa(this,t)}}as("FeatureIndexArray",Ca);class Ea extends Ks{}class Ta extends Ks{}class Ba extends Ks{}class Va extends Qs{}class Fa extends ta{}class $a extends ea{}class Da extends ra{}class La extends na{}class Oa extends ia{}class Ra extends sa{}class Ua extends oa{}class ja extends ua{}class Na extends ca{}class qa extends ma{}const Ga=Ys([{name:"a_pos",components:2,type:"Int16"}],4),{members:Xa}=Ga;class Za{constructor(t=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=t;}prepareSegment(t,e,r,n){const i=this.segments[this.segments.length-1];return t>Za.MAX_VERTEX_ARRAY_LENGTH&&q(`Max vertices per segment is ${Za.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${Za.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!i||i.vertexLength+t>Za.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n?this.createNewSegment(e,r,n):i}createNewSegment(t,e,r){const n={vertexOffset:t.length,primitiveOffset:e.length,vertexLength:0,primitiveLength:0,vaos:{}};return void 0!==r&&(n.sortKey=r),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(n),n}getOrCreateLatestSegment(t,e,r){return this.prepareSegment(0,t,e,r)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0;}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,r,n){return new Za([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function Ya(t,e){return 256*(t=$(Math.floor(t),0,255))+$(Math.floor(e),0,255)}Za.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,as("SegmentVector",Za);const Ha=Ys([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var Ka,Ja,Wa,Qa={exports:{}},to={exports:{}},eo={exports:{}},ro=function(){if(Wa)return Qa.exports;Wa=1;var t=(Ka||(Ka=1,to.exports=function(t,e){var r,n,i,s,a,o,l,u;for(n=t.length-(r=3&t.length),i=e,a=3432918353,o=461845907,u=0;u>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0}),to.exports),e=(Ja||(Ja=1,eo.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0}),eo.exports);return Qa.exports=t,Qa.exports.murmur3=t,Qa.exports.murmur2=e,Qa.exports}(),no=n(ro);class io{constructor(){this.ids=[],this.positions=[],this.indexed=!1;}add(t,e,r,n){this.ids.push(so(t)),this.positions.push(e,r,n);}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=so(t);let r=0,n=this.ids.length-1;for(;r>1;this.ids[t]>=e?n=t:r=t+1;}const i=[];for(;this.ids[r]===e;)i.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return i}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return ao(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}}static deserialize(t){const e=new io;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e}}function so(t){const e=+t;return !isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:no(String(t))}function ao(t,e,r,n){for(;r>1];let s=r-1,a=n+1;for(;;){do{s++;}while(t[s]i);if(s>=a)break;oo(t,s,a),oo(e,3*s,3*a),oo(e,3*s+1,3*a+1),oo(e,3*s+2,3*a+2);}a-r`u_${t}`)),this.type=r;}setUniform(t,e,r){t.set(r.constantOr(this.value));}getBinding(t,e,r){return "color"===this.type?new ho(t,e):new uo(t,e)}}class mo{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;}setUniform(t,e,r,n){const i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);}getBinding(t,e,r){return "u_pattern"===r.substr(0,9)?new co(t,e):new uo(t,e)}}class go{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?2:1,offset:0}))),this.paintVertexArray=new n;}populatePaintArray(t,e,r){const n=this.paintVertexArray.length,i=this.expression.evaluate(new Is(0,r),e,{},r.canonical,[],r.formattedSection);this.paintVertexArray.resize(t),this._setPaintValue(n,t,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(0,i),r,n);this._setPaintValue(t,e,s);}_setPaintValue(t,e,r){if("color"===this.type){const n=fo(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,r){const n=this.expression.evaluate(new Is(this.zoom,r),e,{},r.canonical,[],r.formattedSection),i=this.expression.evaluate(new Is(this.zoom+1,r),e,{},r.canonical,[],r.formattedSection),s=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(s,t,n,i);}updatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Is(this.zoom,i),r,n),a=this.expression.evaluate(new Is(this.zoom+1,i),r,n);this._setPaintValue(t,e,s,a);}_setPaintValue(t,e,r,n){if("color"===this.type){const i=fo(r),s=fo(n);for(let r=t;r`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof go||r instanceof xo)for(let e=0;e!0){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new bo(n,e,r);this.needsUpload=!1,this._featureMap=new io,this._bufferOffset=0;}populatePaintArrays(t,e,r,n){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;}updatePaintArrays(t,e,r,n){for(const i of r)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,n)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}function _o(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function So(t,e,r){const n={color:{source:ea,composite:xa},number:{source:fa,composite:ea}},i=function(t){return {"line-pattern":{source:Da,composite:Da},"fill-pattern":{source:Da,composite:Da},"fill-extrusion-pattern":{source:Da,composite:Da}}[t]}(t);return i&&i[r]||n[e][r]}as("ConstantBinder",yo),as("CrossFadedConstantBinder",mo),as("SourceExpressionBinder",go),as("CrossFadedCompositeBinder",vo),as("CompositeExpressionBinder",xo),as("ProgramConfiguration",bo,{omit:["_buffers"]}),as("ProgramConfigurationSet",wo);const Ao=Math.pow(2,14)-1,ko=-Ao-1;function Mo(t){const e=P/t.extent,r=t.loadGeometry();for(let t=0;tr.x+1||sr.y+1)&&q("Geometry exceeds allowed extent, reduce your vector tile buffer size");}}return r}function Io(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?Mo(t):[]}}const zo=-32768;function Po(t,e,r,n,i){t.emplaceBack(zo+8*e+n,zo+8*r+i);}class Co{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Ta,this.indexArray=new Na,this.segments=new Za,this.programConfigurations=new wo(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){const n=this.layers[0],i=[];let s=null,a=!1,o="heatmap"===n.type;if("circle"===n.type){const t=n;s=t.layout.get("circle-sort-key"),a=!s.isConstant(),o=o||"map"===t.paint.get("circle-pitch-alignment");}const l=o?e.subdivisionGranularity.circle:1;for(const{feature:e,id:n,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=a?s.evaluate(u,{},r):void 0,h={id:n,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};i.push(h);}a&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of i){const{geometry:i,index:s,sourceLayerIndex:a}=n,o=t[s].feature;this.addFeature(n,i,s,r,l),e.featureIndex.insert(o,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Xa),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,r,n,i=1){let s;switch(i){case 1:s=[0,7];break;case 3:s=[0,2,5,7];break;case 5:s=[0,1,3,4,6,7];break;case 7:s=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${i}; valid values are 1, 3, 5, 7.`)}const a=s.length;for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=P||n<0||n>=P)continue;const i=this.segments.prepareSegment(a*a,this.layoutVertexArray,this.indexArray,t.sortKey),o=i.vertexLength;for(let t=0;t1){if(Fo(t,e))return !0;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function Oo(t,e){let r,n,i,s=!1;for(let a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s);}return s}function Ro(t,e){let r=!1;for(let n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-s.x)*(e.y-s.y)/(a.y-s.y)+s.x&&(r=!r);}return r}function Uo(t,e,r){const n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;const s=G(t,e,r[0]);return s!==G(t,e,r[1])||s!==G(t,e,r[2])||s!==G(t,e,r[3])}function jo(t,e,r){const n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function No(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function qo(t,e,n,i,s){if(!e[0]&&!e[1])return t;const a=r.convert(e)._mult(s);"viewport"===n&&a._rotate(-i);const o=[];for(let e=0;eKo(t,e,r,n)))}(l,i,a,o),f=u),Ho({queryGeometry:p,size:f,transform:i,unwrappedTileID:a,getElevation:o,pitchAlignment:h,pitchScale:c},n)}}class el extends Co{}let rl;as("HeatmapBucket",el,{omit:["layers"]});var nl={get paint(){return rl=rl||new js({"heatmap-radius":new Ls(xt.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Ls(xt.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Ds(xt.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Us(xt.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Ds(xt.paint_heatmap["heatmap-opacity"])})}};function il(t,{width:e,height:r},n,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*r*n)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*r*n}`)}else i=new Uint8Array(e*r*n);return t.width=e,t.height=r,t.data=i,t}function sl(t,{width:e,height:r},n){if(e===t.width&&r===t.height)return;const i=il({},{width:e,height:r},n);al(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,r)},n),t.width=e,t.height=r,t.data=i.data;}function al(t,e,r,n,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const a=t.data,o=e.data;if(a===o)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=a;const o=t.expression.evaluate(e);i.setPixel(n/4/r,s/4,o);};if(t.clips)for(let e=0,i=0;ethis.max&&(this.max=r),r=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)}unpack(t,e,r){return t*this.redFactor+e*this.greenFactor+r*this.blueFactor-this.baseShift}pack(t){return vl(t,this.getUnpackVector())}getPixels(){return new ll({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,a=r*this.dim+this.dim;switch(e){case -1:n=i-1;break;case 1:i=n+1;}switch(r){case -1:s=a-1;break;case 1:a=s+1;}const o=-e*this.dim,l=-r*this.dim;for(let e=s;e0)for(let i=e;i=e;i-=n)s=Zl(i/n|0,t[i],t[i+1],s);return s&&Ul(s,s.next)&&(Yl(s),s=s.next),s}function Ml(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!Ul(n,n.next)&&0!==Rl(n.prev,n,n.next))n=n.next;else {if(Yl(n),n=e=n.prev,n===n.next)break;r=!0;}}while(r||n!==e);return e}function Il(t,e,r,n,i,s,a){if(!t)return;!a&&s&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=Fl(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let s=null;for(e=0;i;){e++;let a=i,o=0;for(let t=0;t0||l>0&&a;)0!==o&&(0===l||!a||i.z<=a.z)?(n=i,i=i.nextZ,o--):(n=a,a=a.nextZ,l--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;i=a;}s.nextZ=null,r*=2;}while(e>1)}(i);}(t,n,i,s);let o=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?Pl(t,n,i,s):zl(t))e.push(l.i,t.i,u.i),Yl(t),t=u.next,o=u.next;else if((t=u)===o){a?1===a?Il(t=Cl(Ml(t),e),e,r,n,i,s,2):2===a&&El(t,e,r,n,i,s):Il(Ml(t),e,r,n,i,s,1);break}}}function zl(t){const e=t.prev,r=t,n=t.next;if(Rl(e,r,n)>=0)return !1;const i=e.x,s=r.x,a=n.x,o=e.y,l=r.y,u=n.y,c=Math.min(i,s,a),h=Math.min(o,l,u),p=Math.max(i,s,a),f=Math.max(o,l,u);let d=n.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&Ll(i,o,s,l,a,u,d.x,d.y)&&Rl(d.prev,d,d.next)>=0)return !1;d=d.next;}return !0}function Pl(t,e,r,n){const i=t.prev,s=t,a=t.next;if(Rl(i,s,a)>=0)return !1;const o=i.x,l=s.x,u=a.x,c=i.y,h=s.y,p=a.y,f=Math.min(o,l,u),d=Math.min(c,h,p),y=Math.max(o,l,u),m=Math.max(c,h,p),g=Fl(f,d,e,r,n),x=Fl(y,m,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Ll(o,c,l,h,u,p,v.x,v.y)&&Rl(v.prev,v,v.next)>=0)return !1;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Ll(o,c,l,h,u,p,b.x,b.y)&&Rl(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}return !0}function Cl(t,e){let r=t;do{const n=r.prev,i=r.next.next;!Ul(n,i)&&jl(n,r,r.next,i)&&Gl(n,i)&&Gl(i,n)&&(e.push(n.i,r.i,i.i),Yl(r),Yl(r.next),r=t=i),r=r.next;}while(r!==t);return Ml(r)}function El(t,e,r,n,i,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Ol(a,t)){let o=Xl(a,t);return a=Ml(a,a.next),o=Ml(o,o.next),Il(a,e,r,n,i,s,0),void Il(o,e,r,n,i,s,0)}t=t.next;}a=a.next;}while(a!==t)}function Tl(t,e){let r=t.x-e.x;return 0===r&&(r=t.y-e.y,0===r)&&(r=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)),r}function Bl(t,e){const r=function(t,e){let r=e;const n=t.x,i=t.y;let s,a=-1/0;if(Ul(t,r))return r;do{if(Ul(t,r.next))return r.next;if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){const t=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(t<=n&&t>a&&(a=t,s=r.x=r.x&&r.x>=l&&n!==r.x&&Dl(is.x||r.x===s.x&&Vl(s,r)))&&(s=r,c=e);}r=r.next;}while(r!==o);return s}(t,e);if(!r)return e;const n=Xl(r,t);return Ml(n,n.next),Ml(r,r.next)}function Vl(t,e){return Rl(t.prev,t,e.prev)<0&&Rl(e.next,t,t.next)<0}function Fl(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function $l(t){let e=t,r=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(r-a)*(e-o)&&(r-a)*(s-o)>=(i-a)*(n-o)}function Ll(t,e,r,n,i,s,a,o){return !(t===a&&e===o)&&Dl(t,e,r,n,i,s,a,o)}function Ol(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&jl(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(Gl(t,e)&&Gl(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Rl(t.prev,t,e.prev)||Rl(t,e.prev,e))||Ul(t,e)&&Rl(t.prev,t,t.next)>0&&Rl(e.prev,e,e.next)>0)}function Rl(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Ul(t,e){return t.x===e.x&&t.y===e.y}function jl(t,e,r,n){const i=ql(Rl(t,e,r)),s=ql(Rl(t,e,n)),a=ql(Rl(r,n,t)),o=ql(Rl(r,n,e));return i!==s&&a!==o||!(0!==i||!Nl(t,r,e))||!(0!==s||!Nl(t,n,e))||!(0!==a||!Nl(r,t,n))||!(0!==o||!Nl(r,e,n))}function Nl(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function ql(t){return t>0?1:t<0?-1:0}function Gl(t,e){return Rl(t.prev,t,t.next)<0?Rl(t,e,t.next)>=0&&Rl(t,t.prev,e)>=0:Rl(t,e,t.prev)<0||Rl(t,t.next,e)<0}function Xl(t,e){const r=Hl(t.i,t.x,t.y),n=Hl(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function Zl(t,e,r,n){const i=Hl(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Yl(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 Hl(t,e,r){return {i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class Kl{constructor(t,e){if(e>t)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=t,this._minGranularity=e;}getGranularityForZoomLevel(t){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||e>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const r=0|Math.round(t),n=0|Math.round(e),i=this._getKey(r,n);if(this._vertexDictionary.has(i))return this._vertexDictionary.get(i);const s=this._vertexBuffer.length/2;return this._vertexDictionary.set(i,s),this._vertexBuffer.push(r,n),s}_subdivideTrianglesScanline(t){if(this._granularity<2)return function(t,e){const r=[];for(let n=0;n0?(r.push(i),r.push(a),r.push(s)):(r.push(i),r.push(s),r.push(a));}return r}(this._vertexBuffer,t);const e=[],r=t.length;for(let n=0;n=1||v<=0)||y&&(oi)){u>=n&&u<=i&&s.push(r[(t+1)%3]);continue}!y&&x>0&&s.push(this._vertexToIndex(a+p*x,o+f*x));const b=a+p*Math.max(x,0),w=a+p*Math.min(v,1);d||this._generateIntraEdgeVertices(s,a,o,l,u,b,w),!y&&v<1&&s.push(this._vertexToIndex(a+p*v,o+f*v)),(y||u>=n&&u<=i)&&s.push(r[(t+1)%3]),!y&&(u<=n||u>=i)&&this._generateInterEdgeVertices(s,a,o,l,u,c,h,w,n,i);}return s}_generateIntraEdgeVertices(t,e,r,n,i,s,a){const o=n-e,l=i-r,u=0===l,c=u?Math.min(e,n):Math.min(s,a),h=u?Math.max(e,n):Math.max(s,a),p=Math.floor(c/this._granularityCellSize)+1,f=Math.ceil(h/this._granularityCellSize)-1;if(u?e=p;n--){const i=n*this._granularityCellSize;t.push(this._vertexToIndex(i,r+l*(i-e)/o));}}_generateInterEdgeVertices(t,e,r,n,i,s,a,o,l,u){const c=i-r,h=s-n,p=a-i,f=(l-i)/p,d=(u-i)/p,y=Math.min(f,d),m=Math.max(f,d),g=n+h*y;let x=Math.floor(Math.min(g,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(g,o)/this._granularityCellSize)-1,b=o=1||m<=0){const t=r-a,n=s+(e-s)*Math.min((l-a)/t,(u-a)/t);x=Math.floor(Math.min(n,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(n,o)/this._granularityCellSize)-1,b=o0?u:l;if(b)for(let e=x;e<=v;e++)t.push(this._vertexToIndex(e*this._granularityCellSize,_));else for(let e=v;e>=x;e--)t.push(this._vertexToIndex(e*this._granularityCellSize,_));}_generateOutline(t){const e=[];for(const r of t){const t=ru(r,this._granularity,!0),n=this._pointArrayToIndices(t),i=[];for(let t=1;ti!=(s===Wl)?(t.push(e),t.push(r),t.push(this._vertexToIndex(n,s)),t.push(r),t.push(this._vertexToIndex(i,s)),t.push(this._vertexToIndex(n,s))):(t.push(r),t.push(e),t.push(this._vertexToIndex(n,s)),t.push(this._vertexToIndex(i,s)),t.push(r),t.push(this._vertexToIndex(n,s)));}_fillPoles(t,e,r){const n=this._vertexBuffer,i=P,s=t.length;for(let a=2;a80*r){o=t[0],l=t[1];let e=o,n=l;for(let s=r;se&&(e=r),i>n&&(n=i);}u=Math.max(e-o,n-l),u=0!==u?32767/u:0;}return Il(s,a,r,o,l,u,0),a}(r,n),e=this._convertIndices(r,t);i=this._subdivideTrianglesScanline(e);}catch(t){console.error(t);}let s=[];return e&&(s=this._generateOutline(t)),this._ensureNoPoleVertices(),this._handlePoles(i),{verticesFlattened:this._vertexBuffer,indicesTriangles:i,indicesLineList:s}}_convertIndices(t,e){const r=[];for(let n=0;n0?(Math.floor(x/o)+1)*o:(Math.ceil(x/o)-1)*o,e=y>0?(Math.floor(v/o)+1)*o:(Math.ceil(v/o)-1)*o,n=Math.abs(x-t),i=Math.abs(v-e),s=Math.abs(x-c),a=Math.abs(v-h),u=p?n/m:Number.POSITIVE_INFINITY,b=f?i/g:Number.POSITIVE_INFINITY;if((s<=n||!p)&&(a<=i||!f))break;if(u=0?a-1:s-1,i=(o+1)%s,l=t[2*e[n]],u=t[2*e[i]],c=t[2*e[a]],h=t[2*e[a]+1],p=t[2*e[o]+1];let f=!1;if(lu)f=!1;else {const r=p-h,s=-(t[2*e[o]]-c),a=h((u-c)*r+(t[2*e[i]+1]-h)*s)*a&&(f=!0);}if(f){const t=e[n],i=e[a],l=e[o];t!==i&&t!==l&&i!==l&&r.push(l,i,t),a--,a<0&&(a=s-1);}else {const t=e[i],n=e[a],l=e[o];t!==n&&t!==l&&n!==l&&r.push(l,n,t),o++,o>=s&&(o=0);}if(n===i)break}}function iu(t,e,r,n,i,s,a,o,l){const u=i.length/2,c=a&&o&&l;if(uZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,y=!0,m=!0,g=!0,c=0);const x=su(a,n,s,o,p,y,u),v=su(a,n,s,o,f,m,u),b=su(a,n,s,o,d,g,u);r.emplaceBack(c+x-l,c+v-l,c+b-l),u.primitiveLength++;}}(e,r,n,i,s,t),c&&function(t,e,r,n,i,s){const a=[];for(let t=0;tZa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,d=!0,y=!0,c=0);const m=su(a,n,s,o,i,d,u),g=su(a,n,s,o,h,y,u);r.emplaceBack(c+m-l,c+g-l),u.primitiveLength++;}}}(a,r,o,i,l,t),e.forceNewSegmentOnNextPrepare(),null==a||a.forceNewSegmentOnNextPrepare();}function su(t,e,r,n,i,s,a){if(s){const s=n.count;return r(e[2*i],e[2*i+1]),t[i]=n.count,n.count++,a.vertexLength++,s}return t[i]}class au{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Ba,this.indexArray=new Na,this.indexArray2=new qa,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.segments2=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("fill",this.layers,e);const n=this.layers[0].layout.get("fill-sort-key"),i=!n.isConstant(),s=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=Io(a,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),c,r))continue;const h=i?n.evaluate(c,{},r,e.availableImages):void 0,p={id:o,properties:a.properties,type:a.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:Mo(a),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("fill",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,_l),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,r,n,i,s){for(const t of Qr(e,500)){const e=eu(t,n,s.fill.getGranularityForZoomLevel(n.z)),r=this.layoutVertexArray;iu(((t,e)=>{r.emplaceBack(t,e);}),this.segments,this.layoutVertexArray,this.indexArray,e.verticesFlattened,e.indicesTriangles,this.segments2,this.indexArray2,e.indicesLineList);}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}}let ou,lu;as("FillBucket",au,{omit:["layers","patternFeatures"]});var uu={get paint(){return lu=lu||new js({"fill-antialias":new Ds(xt.paint_fill["fill-antialias"]),"fill-opacity":new Ls(xt.paint_fill["fill-opacity"]),"fill-color":new Ls(xt.paint_fill["fill-color"]),"fill-outline-color":new Ls(xt.paint_fill["fill-outline-color"]),"fill-translate":new Ds(xt.paint_fill["fill-translate"]),"fill-translate-anchor":new Ds(xt.paint_fill["fill-translate-anchor"]),"fill-pattern":new Os(xt.paint_fill["fill-pattern"])})},get layout(){return ou=ou||new js({"fill-sort-key":new Ls(xt.layout_fill["fill-sort-key"])})}};class cu extends qs{constructor(t,e){super(t,uu,e);}recalculate(t,e){super.recalculate(t,e);const r=this.paint._values["fill-outline-color"];"constant"===r.value.kind&&void 0===r.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);}createBucket(t){return new au(t)}queryRadius(){return No(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:t,geometry:e,transform:r,pixelsToTileUnits:n}){return Bo(qo(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-r.bearingInRadians,n),e)}isTileClipped(){return !0}}const hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),pu=Ys([{name:"a_centroid",components:2,type:"Int16"}],4),{members:fu}=hu;class du{constructor(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this.id=void 0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(yu,this,e);}loadGeometry(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos,n=[];let i,s=1,a=0,o=0,l=0;for(;t.pos>3;}if(a--,1===s||2===s)o+=t.readSVarint(),l+=t.readSVarint(),1===s&&(i&&n.push(i),i=[]),i&&i.push(new r(o,l));else {if(7!==s)throw new Error(`unknown command ${s}`);i&&i.push(i[0].clone());}}return i&&n.push(i),n}bbox(){const t=this._pbf;t.pos=this._geometry;const e=t.readVarint()+t.pos;let r=1,n=0,i=0,s=0,a=1/0,o=-1/0,l=1/0,u=-1/0;for(;t.pos>3;}if(n--,1===r||2===r)i+=t.readSVarint(),s+=t.readSVarint(),io&&(o=i),su&&(u=s);else if(7!==r)throw new Error(`unknown command ${r}`)}return [a,l,o,u]}toGeoJSON(t,e,r){const n=this.extent*Math.pow(2,r),i=this.extent*t,s=this.extent*e,a=this.loadGeometry();function o(t){return [360*(t.x+i)/n-180,360/Math.PI*Math.atan(Math.exp((1-2*(t.y+s)/n)*Math.PI))-90]}function l(t){return t.map(o)}let u;if(1===this.type){const t=[];for(const e of a)t.push(e[0]);const e=l(t);u=1===t.length?{type:"Point",coordinates:e[0]}:{type:"MultiPoint",coordinates:e};}else if(2===this.type){const t=a.map(l);u=1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t};}else {if(3!==this.type)throw new Error("unknown feature type");{const t=function(t){const e=t.length;if(e<=1)return [t];const r=[];let n,i;for(let s=0;s=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];const e=this._pbf.readVarint()+this._pbf.pos;return new du(this._pbf,e,this.extent,this._keys,this._values)}}function xu(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){let e=null;const r=t.readVarint()+t.pos;for(;t.pos>3;e=1===r?t.readString():2===r?t.readFloat():3===r?t.readDouble():4===r?t.readVarint64():5===r?t.readVarint():6===r?t.readSVarint():7===r?t.readBoolean():null;}if(null==e)throw new Error("unknown feature value");return e}(r));}class vu{constructor(t,e){this.layers=t.readFields(bu,{},e);}}function bu(t,e,r){if(3===t){const t=new gu(r,r.readVarint()+r.pos);t.length&&(e[t.name]=t);}}const wu=Math.pow(2,13);function _u(t,e,r,n,i,s,a,o){t.emplaceBack(e,r,2*Math.floor(n*wu)+a,i*wu*2,s*wu*2,Math.round(o));}class Su{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Va,this.centroidVertexArray=new Ea,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.features=[],this.hasPattern=Sl("fill-extrusion",this.layers,e);for(const{feature:n,id:i,index:s,sourceLayerIndex:a}of t){const t=this.layers[0]._featureFilter.needGeometry,o=Io(n,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),o,r))continue;const l={id:i,sourceLayerIndex:a,index:s,geometry:t?o.geometry:Mo(n),properties:n.properties,type:n.type,patterns:{}};this.hasPattern?this.features.push(Al("fill-extrusion",this.layers,l,{zoom:this.zoom},e)):this.addFeature(l,l.geometry,s,r,{},e.subdivisionGranularity),e.featureIndex.insert(n,l.geometry,s,a,this.index,!0);}}addFeatures(t,e,r){for(const n of this.features){const{geometry:i}=n;this.addFeature(n,i,n.index,e,r,t.subdivisionGranularity);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,fu),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,pu.members,!0),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy());}addFeature(t,e,r,n,i,s){for(const r of Qr(e,500)){const e={x:0,y:0,sampleCount:0},i=this.layoutVertexArray.length;this.processPolygon(e,n,t,r,s);const a=this.layoutVertexArray.length-i,o=Math.floor(e.x/e.sampleCount),l=Math.floor(e.y/e.sampleCount);for(let t=0;t{_u(u,t,e,0,0,1,1,0);}),this.segments,this.layoutVertexArray,this.indexArray,l.verticesFlattened,l.indicesTriangles);}_generateSideFaces(t,e){let r=0;for(let n=1;nZa.MAX_VERTEX_ARRAY_LENGTH&&(e.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const a=i.sub(s)._perp()._unit(),o=s.dist(i);r+o>32768&&(r=0),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,1,r),r+=o,_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,0,r),_u(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,1,r);const l=e.segment.vertexLength;this.indexArray.emplaceBack(l,l+2,l+1),this.indexArray.emplaceBack(l+1,l+2,l+3),e.segment.vertexLength+=4,e.segment.primitiveLength+=2;}}}function Au(t,e){for(let r=0;rP)||t.y===e.y&&(t.y<0||t.y>P)}function Mu(t){return t.every((t=>t.x<0))||t.every((t=>t.x>P))||t.every((t=>t.y<0))||t.every((t=>t.y>P))}let Iu;as("FillExtrusionBucket",Su,{omit:["layers","features"]});var zu={get paint(){return Iu=Iu||new js({"fill-extrusion-opacity":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Os(xt["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Ls(xt["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new Ds(xt["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class Pu extends qs{constructor(t,e){super(t,zu,e);}createBucket(t){return new Su(t)}queryRadius(){return No(this.paint.get("fill-extrusion-translate"))}is3D(){return !0}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a,pixelPosMatrix:o}){const l=qo(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-s.bearingInRadians,a),u=this.paint.get("fill-extrusion-height").evaluate(e,n),c=this.paint.get("fill-extrusion-base").evaluate(e,n),h=function(t,e){const n=[];for(const i of t){const t=[i.x,i.y,0,1];A(t,t,e),n.push(new r(t[0]/t[3],t[1]/t[3]));}return n}(l,o),p=function(t,e,n,i){const s=[],a=[],o=i[8]*e,l=i[9]*e,u=i[10]*e,c=i[11]*e,h=i[8]*n,p=i[9]*n,f=i[10]*n,d=i[11]*n;for(const e of t){const t=[],n=[];for(const s of e){const e=s.x,a=s.y,y=i[0]*e+i[4]*a+i[12],m=i[1]*e+i[5]*a+i[13],g=i[2]*e+i[6]*a+i[14],x=i[3]*e+i[7]*a+i[15],v=g+u,b=x+c,w=y+h,_=m+p,S=g+f,A=x+d,k=new r((y+o)/b,(m+l)/b);k.z=v/b,t.push(k);const M=new r(w/A,_/A);M.z=S/A,n.push(M);}s.push(t),a.push(n);}return [s,a]}(i,c,u,o);return function(t,e,r){let n=1/0;Bo(r,e)&&(n=Eu(r,e[0]));for(let i=0;it.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new Fa,this.layoutVertexArray2=new $a,this.indexArray=new Na,this.programConfigurations=new wo(t.layers,t.zoom),this.segments=new Za,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Sl("line",this.layers,e);const n=this.layers[0].layout.get("line-sort-key"),i=!n.isConstant(),s=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=Io(e,t);if(!this.layers[0]._featureFilter.filter(new Is(this.zoom),u,r))continue;const c=i?n.evaluate(u,{},r):void 0,h={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Mo(e),patterns:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Al("line",this.layers,n,{zoom:this.zoom},e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,{imagePositions:r});}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,Fu)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Bu),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return {start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i,s){const a=this.layers[0].layout,o=a.get("line-join").evaluate(t,{}),l=a.get("line-cap"),u=a.get("line-miter-limit"),c=a.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,o,l,u,c,n,s);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{imagePositions:i,canonical:n});}addLine(t,e,r,n,i,s,a,o){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,t=ru(t,a?o.line.getGranularityForZoomLevel(a.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[u-1].equals(t[u-2]);)u--;let c=0;for(;c0;if(w&&e>c){const t=f.dist(d);if(t>2*h){const e=f.sub(f.sub(d)._mult(h/t)._round());this.updateDistance(d,e),this.addCurrentVertex(e,m,0,0,p),d=e;}}const S=d&&y;let A=S?r:l?"butt":n;if(S&&"round"===A&&(vi&&(A="bevel"),"bevel"===A&&(v>2&&(A="flipbevel"),v100)a=g.mult(-1);else {const t=v*m.add(g).mag()/m.sub(g).mag();a._perp()._mult(t*(_?-1:1));}this.addCurrentVertex(f,a,0,0,p),this.addCurrentVertex(f,a.mult(-1),0,0,p);}else if("bevel"===A||"fakeround"===A){const t=-Math.sqrt(v*v-1),e=_?t:0,r=_?0:t;if(d&&this.addCurrentVertex(f,m,e,r,p),"fakeround"===A){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*h){const e=f.add(y.sub(f)._mult(h/t)._round());this.updateDistance(f,e),this.addCurrentVertex(e,g,0,0,p),f=e;}}}}addCurrentVertex(t,e,r,n,i,s=!1){const a=e.y*n-e.x,o=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,!1,r,i),this.addHalfVertex(t,a,o,s,!0,-n,i),this.distance>Du/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,r,n,i,s));}addHalfVertex({x:t,y:e},r,n,i,s,a,o){const l=.5*(this.lineClips?this.scaledDistance*(Du-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,u,this.e2),o.primitiveLength++),s?this.e2=u:this.e1=u;}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}}let Ou,Ru;as("LineBucket",Lu,{omit:["layers","patternFeatures"]});var Uu={get paint(){return Ru=Ru||new js({"line-opacity":new Ls(xt.paint_line["line-opacity"]),"line-color":new Ls(xt.paint_line["line-color"]),"line-translate":new Ds(xt.paint_line["line-translate"]),"line-translate-anchor":new Ds(xt.paint_line["line-translate-anchor"]),"line-width":new Ls(xt.paint_line["line-width"]),"line-gap-width":new Ls(xt.paint_line["line-gap-width"]),"line-offset":new Ls(xt.paint_line["line-offset"]),"line-blur":new Ls(xt.paint_line["line-blur"]),"line-dasharray":new Rs(xt.paint_line["line-dasharray"]),"line-pattern":new Os(xt.paint_line["line-pattern"]),"line-gradient":new Us(xt.paint_line["line-gradient"])})},get layout(){return Ou=Ou||new js({"line-cap":new Ds(xt.layout_line["line-cap"]),"line-join":new Ls(xt.layout_line["line-join"]),"line-miter-limit":new Ds(xt.layout_line["line-miter-limit"]),"line-round-limit":new Ds(xt.layout_line["line-round-limit"]),"line-sort-key":new Ls(xt.layout_line["line-sort-key"])})}};class ju extends Ls{possiblyEvaluate(t,e){return e=new Is(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=L({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}let Nu;class qu extends qs{constructor(t,e){super(t,Uu,e),this.gradientVersion=0,Nu||(Nu=new ju(Uu.paint.properties["line-width"].specification),Nu.useIntegerZoom=!0);}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return void 0!==t._styleExpression}(t)&&t._styleExpression.expression instanceof ar,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=Nu.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t);}createBucket(t){return new Lu(t)}queryRadius(t){const e=t,r=Gu(jo("line-width",this,e),jo("line-gap-width",this,e)),n=jo("line-offset",this,e);return r/2+Math.abs(n)+No(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:n,geometry:i,transform:s,pixelsToTileUnits:a}){const o=qo(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-s.bearingInRadians,a),l=a/2*Gu(this.paint.get("line-width").evaluate(e,n),this.paint.get("line-gap-width").evaluate(e,n)),u=this.paint.get("line-offset").evaluate(e,n);return u&&(i=function(t,e){const n=[];for(let i=0;i=3)for(let e=0;e0?e+2*t:t}const Xu=Ys([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Zu=Ys([{name:"a_projected_pos",components:3,type:"Float32"}],4);Ys([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Yu=Ys([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Ys([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const Hu=Ys([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Ku=Ys([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Ju(t,e,r){return t.sections.forEach((t=>{t.text=function(t,e,r){const n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Ms.applyArabicShaping&&(t=Ms.applyArabicShaping(t)),t}(t.text,e,r);})),t}Ys([{name:"triangle",components:3,type:"Uint16"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Ys([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Ys([{type:"Float32",name:"offsetX"}]),Ys([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Ys([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const Wu={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Qu=24;const tc=4294967296,ec=1/tc,rc="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class nc{constructor(t=new Uint8Array(16)){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length;}readFields(t,e,r=this.length){for(;this.pos>3,i=this.pos;this.type=7&r,t(n,e,this),this.pos===i&&this.skip(r);}return e}readMessage(t,e){return this.readFields(t,e,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*tc;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*tc;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const e=this.buf;let r,n;return n=e[this.pos++],r=127&n,n<128?r:(n=e[this.pos++],r|=(127&n)<<7,n<128?r:(n=e[this.pos++],r|=(127&n)<<14,n<128?r:(n=e[this.pos++],r|=(127&n)<<21,n<128?r:(n=e[this.pos],r|=(15&n)<<28,function(t,e,r){const n=r.buf;let i,s;if(s=n[r.pos++],i=(112&s)>>4,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<3,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<10,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<17,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(127&s)<<24,s<128)return ic(t,i,e);if(s=n[r.pos++],i|=(1&s)<<31,s<128)return ic(t,i,e);throw new Error("Expected varint not more than 10 bytes")}(r,t,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2==1?(t+1)/-2:t/2}readBoolean(){return Boolean(this.readVarint())}readString(){const t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&rc?rc.decode(this.buf.subarray(e,t)):function(t,e,r){let n="",i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+u>r)break;1===u?e<128&&(l=e):2===u?(s=t[i+1],128==(192&s)&&(l=(31&e)<<6|63&s,l<=127&&(l=null))):3===u?(s=t[i+1],a=t[i+2],128==(192&s)&&128==(192&a)&&(l=(15&e)<<12|(63&s)<<6|63&a,(l<=2047||l>=55296&&l<=57343)&&(l=null))):4===u&&(s=t[i+1],a=t[i+2],o=t[i+3],128==(192&s)&&128==(192&a)&&128==(192&o)&&(l=(15&e)<<18|(63&s)<<12|(63&a)<<6|63&o,(l<=65535||l>=1114112)&&(l=null))),null===l?(l=65533,u=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=u;}return n}(this.buf,e,t)}readBytes(){const t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e}readPackedVarint(t=[],e){const r=this.readPackedEnd();for(;this.pos127;);else if(2===e)this.pos=this.readVarint()+this.pos;else if(5===e)this.pos+=4;else {if(1!==e)throw new Error(`Unimplemented type: ${e}`);this.pos+=8;}}writeTag(t,e){this.writeVarint(t<<3|e);}realloc(t){let e=this.length||16;for(;e268435455||t<0?function(t,e){let r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(r=~(-t%4294967296),n=~(-t/4294967296),4294967295^r?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){const r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(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(t){this.writeVarint(t<0?2*-t-1:2*t);}writeBoolean(t){this.writeVarint(+t);}writeString(t){t=String(t),this.realloc(4*t.length),this.pos++;const e=this.pos;this.pos=function(t,e,r){for(let n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);const r=this.pos-e;r>=128&&sc(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4;}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8;}writeBytes(t){const e=t.length;this.writeVarint(e),this.realloc(e);for(let r=0;r=128&&sc(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;}writeMessage(t,e,r){this.writeTag(t,2),this.writeRawMessage(e,r);}writePackedVarint(t,e){e.length&&this.writeMessage(t,ac,e);}writePackedSVarint(t,e){e.length&&this.writeMessage(t,oc,e);}writePackedBoolean(t,e){e.length&&this.writeMessage(t,cc,e);}writePackedFloat(t,e){e.length&&this.writeMessage(t,lc,e);}writePackedDouble(t,e){e.length&&this.writeMessage(t,uc,e);}writePackedFixed32(t,e){e.length&&this.writeMessage(t,hc,e);}writePackedSFixed32(t,e){e.length&&this.writeMessage(t,pc,e);}writePackedFixed64(t,e){e.length&&this.writeMessage(t,fc,e);}writePackedSFixed64(t,e){e.length&&this.writeMessage(t,dc,e);}writeBytesField(t,e){this.writeTag(t,2),this.writeBytes(e);}writeFixed32Field(t,e){this.writeTag(t,5),this.writeFixed32(e);}writeSFixed32Field(t,e){this.writeTag(t,5),this.writeSFixed32(e);}writeFixed64Field(t,e){this.writeTag(t,1),this.writeFixed64(e);}writeSFixed64Field(t,e){this.writeTag(t,1),this.writeSFixed64(e);}writeVarintField(t,e){this.writeTag(t,0),this.writeVarint(e);}writeSVarintField(t,e){this.writeTag(t,0),this.writeSVarint(e);}writeStringField(t,e){this.writeTag(t,2),this.writeString(e);}writeFloatField(t,e){this.writeTag(t,5),this.writeFloat(e);}writeDoubleField(t,e){this.writeTag(t,1),this.writeDouble(e);}writeBooleanField(t,e){this.writeVarintField(t,+e);}}function ic(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function sc(t,e,r){const n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(let e=r.pos-1;e>=t;e--)r.buf[e+n]=r.buf[e];}function ac(t,e){for(let r=0;re.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();e&&t=0&&r>=t&&kc[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e);}substring(t,e){const r=new Sc;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}getMaxImageSize(t){let e=0,r=0;for(let n=0;n=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Ac(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=Sc.fromFeature(e,s);let g;p===t.ao.vertical&&m.verticalizePunctuation();const{processBidirectionalText:x,processStyledBidirectionalText:v}=Ms;if(x&&1===m.sections.length){g=[];const t=x(m.toString(),Bc(m,c,a,r,i,d));for(const e of t){const t=new Sc;t.text=e,t.sections=m.sections;for(let r=0;r=0;let u=0;for(let r=0;ru){const t=Math.ceil(s/u);i*=t/a,a=t;}return {x1:n,y1:i,x2:n+s,y2:i+a}}function Nc(t,e,r,n,i,s){const a=t.image;let o;if(a.content){const t=a.content,e=a.pixelRatio||1;o=[t[0]/e,t[1]/e,a.displaySize[0]-t[2]/e,a.displaySize[1]-t[3]/e];}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===r||"both"===r?(f=i[0]+l-n[3],h=i[0]+u+n[1]):(f=i[0]+(l+u-a.displaySize[0])/2,h=f+a.displaySize[0]);const d=e.top*s,y=e.bottom*s;return "height"===r||"both"===r?(c=i[1]+d-n[0],p=i[1]+y+n[2]):(c=i[1]+(d+y-a.displaySize[1])/2,p=c+a.displaySize[1]),{image:a,top:c,right:h,bottom:p,left:f,collisionPadding:o}}const qc=128,Gc=32640;function Xc(t,e){const{expression:r}=e;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new Is(t+1))};if("source"===r.kind)return {kind:"source"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;it.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];const r=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Xc(this.zoom,r["text-size"]),this.iconSizeData=Xc(this.zoom,r["icon-size"]);const n=this.layers[0].layout,i=n.get("symbol-sort-key"),s=n.get("symbol-z-order");this.canOverlap="never"!==Zc(n,"text-overlap","text-allow-overlap")||"never"!==Zc(n,"icon-overlap","icon-allow-overlap")||n.get("text-ignore-placement")||n.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!i.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===n.get("symbol-placement")&&(this.writingModes=n.get("text-writing-mode").map((e=>t.ao[e]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID;}createArrays(){this.text=new Wc(new wo(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new Wc(new wo(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new ka,this.lineVertexArray=new Ma,this.symbolInstances=new Aa,this.textAnchorOffsets=new za;}calculateGlyphDependencies(t,e,r,n,i){for(let s=0;s0)&&("constant"!==a.value.kind||a.value.value.length>0),c="constant"!==l.value.kind||!!l.value.value||Object.keys(l.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!u&&!c)return;const p=r.iconDependencies,f=r.glyphDependencies,d=r.availableImages,y=new Is(this.zoom);for(const{feature:r,id:o,index:l,sourceLayerIndex:m}of e){const e=i._featureFilter.needGeometry,g=Io(r,e);if(!i._featureFilter.filter(y,g,n))continue;let x,v;if(e||(g.geometry=Mo(r)),u){const t=i.getValueAndResolveTokens("text-field",g,n,d),e=Ce.factory(t),r=this.hasRTLText=this.hasRTLText||Jc(e);(!r||"unavailable"===Ms.getRTLTextPluginStatus()||r&&Ms.isParsed())&&(x=Ju(e,i,g));}if(c){const t=i.getValueAndResolveTokens("icon-image",g,n,d);v=t instanceof De?t:De.fromString(t);}if(!x&&!v)continue;const b=this.sortFeaturesByKey?h.evaluate(g,{},n):void 0;if(this.features.push({id:o,text:x,icon:v,index:l,sourceLayerIndex:m,geometry:g.geometry,properties:r.properties,type:du.types[r.type],sortKey:b}),v&&(p[v.name]=!0),x){const e=a.evaluate(g,{},n).join(","),r="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(t.ao.vertical)>=0;for(const t of x.sections)if(t.image)p[t.image.name]=!0;else {const n=ds(x.toString()),i=t.fontStack||e,s=f[i]=f[i]||{};this.calculateGlyphDependencies(t.text,s,r,this.allowVerticalPlacement,n);}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++;}function a(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function o(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return `${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,{imagePositions:r}));}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(void 0!==t.segment){let r=t.dist(e[t.segment+1]),n=t.dist(e[t.segment]);const i={};for(let n=t.segment+1;n=0;r--)i[r]={x:e[r].x,y:e[r].y,tileUnitDistanceFromAnchor:n},r>0&&(n+=e[r-1].dist(e[r]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,r)=>{t>=0&&r.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t);})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}let eh,rh;as("SymbolBucket",th,{omit:["layers","collisionBoxArray","features","compareText"]}),th.MAX_GLYPHS=65535,th.addDynamicAttributes=Kc;var nh={get paint(){return rh=rh||new js({"icon-opacity":new Ls(xt.paint_symbol["icon-opacity"]),"icon-color":new Ls(xt.paint_symbol["icon-color"]),"icon-halo-color":new Ls(xt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Ls(xt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Ls(xt.paint_symbol["icon-halo-blur"]),"icon-translate":new Ds(xt.paint_symbol["icon-translate"]),"icon-translate-anchor":new Ds(xt.paint_symbol["icon-translate-anchor"]),"text-opacity":new Ls(xt.paint_symbol["text-opacity"]),"text-color":new Ls(xt.paint_symbol["text-color"],{runtimeType:Lt,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new Ls(xt.paint_symbol["text-halo-color"]),"text-halo-width":new Ls(xt.paint_symbol["text-halo-width"]),"text-halo-blur":new Ls(xt.paint_symbol["text-halo-blur"]),"text-translate":new Ds(xt.paint_symbol["text-translate"]),"text-translate-anchor":new Ds(xt.paint_symbol["text-translate-anchor"])})},get layout(){return eh=eh||new js({"symbol-placement":new Ds(xt.layout_symbol["symbol-placement"]),"symbol-spacing":new Ds(xt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Ds(xt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Ls(xt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Ds(xt.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new Ds(xt.layout_symbol["icon-allow-overlap"]),"icon-overlap":new Ds(xt.layout_symbol["icon-overlap"]),"icon-ignore-placement":new Ds(xt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Ds(xt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Ds(xt.layout_symbol["icon-rotation-alignment"]),"icon-size":new Ls(xt.layout_symbol["icon-size"]),"icon-text-fit":new Ds(xt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Ds(xt.layout_symbol["icon-text-fit-padding"]),"icon-image":new Ls(xt.layout_symbol["icon-image"]),"icon-rotate":new Ls(xt.layout_symbol["icon-rotate"]),"icon-padding":new Ls(xt.layout_symbol["icon-padding"]),"icon-keep-upright":new Ds(xt.layout_symbol["icon-keep-upright"]),"icon-offset":new Ls(xt.layout_symbol["icon-offset"]),"icon-anchor":new Ls(xt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Ds(xt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Ds(xt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Ds(xt.layout_symbol["text-rotation-alignment"]),"text-field":new Ls(xt.layout_symbol["text-field"]),"text-font":new Ls(xt.layout_symbol["text-font"]),"text-size":new Ls(xt.layout_symbol["text-size"]),"text-max-width":new Ls(xt.layout_symbol["text-max-width"]),"text-line-height":new Ds(xt.layout_symbol["text-line-height"]),"text-letter-spacing":new Ls(xt.layout_symbol["text-letter-spacing"]),"text-justify":new Ls(xt.layout_symbol["text-justify"]),"text-radial-offset":new Ls(xt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Ds(xt.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Ls(xt.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Ls(xt.layout_symbol["text-anchor"]),"text-max-angle":new Ds(xt.layout_symbol["text-max-angle"]),"text-writing-mode":new Ds(xt.layout_symbol["text-writing-mode"]),"text-rotate":new Ls(xt.layout_symbol["text-rotate"]),"text-padding":new Ds(xt.layout_symbol["text-padding"]),"text-keep-upright":new Ds(xt.layout_symbol["text-keep-upright"]),"text-transform":new Ls(xt.layout_symbol["text-transform"]),"text-offset":new Ls(xt.layout_symbol["text-offset"]),"text-allow-overlap":new Ds(xt.layout_symbol["text-allow-overlap"]),"text-overlap":new Ds(xt.layout_symbol["text-overlap"]),"text-ignore-placement":new Ds(xt.layout_symbol["text-ignore-placement"]),"text-optional":new Ds(xt.layout_symbol["text-optional"])})}};class ih{constructor(t){if(void 0===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:Vt,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return !1}serialize(){return null}}as("FormatSectionOverride",ih,{omit:["defaultValue"]});class sh extends qs{constructor(t,e){super(t,nh,e);}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const r of t)e.indexOf(r)<0&&e.push(r);this.layout._values["text-writing-mode"]=e;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||ei(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>t&&r in t?String(t[r]):""))}(e.properties,i)}createBucket(t){return new th(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of nh.paint.overridableProperties){if(!sh.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new ih(e),n=new ti(r,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new ni("source",n):new ii("composite",n,e.value.zoomStops),this.paint._values[t]=new Fs(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,r){return !(!this.layout||e.isDataDriven()||r.isDataDriven())&&sh.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get("text-field"),n=nh.paint.properties[e];let i=!1;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=!0)};if("constant"===r.value.kind&&r.value.value instanceof Ce)s(r.value.value.sections);else if("source"===r.value.kind||"composite"===r.value.kind){const t=e=>{i||(e instanceof Ne&&Ue(e.value)===Nt?s(e.value.sections):e instanceof Ir?s(e.sections):e.eachChild(t));},e=r.value;e._styleExpression&&t(e._styleExpression.expression);}return i}}let ah;var oh={get paint(){return ah=ah||new js({"background-color":new Ds(xt.paint_background["background-color"]),"background-pattern":new Rs(xt.paint_background["background-pattern"]),"background-opacity":new Ds(xt.paint_background["background-opacity"])})}};class lh extends qs{constructor(t,e){super(t,oh,e);}}let uh;var ch={get paint(){return uh=uh||new js({"raster-opacity":new Ds(xt.paint_raster["raster-opacity"]),"raster-hue-rotate":new Ds(xt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Ds(xt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Ds(xt.paint_raster["raster-brightness-max"]),"raster-saturation":new Ds(xt.paint_raster["raster-saturation"]),"raster-contrast":new Ds(xt.paint_raster["raster-contrast"]),"raster-resampling":new Ds(xt.paint_raster["raster-resampling"]),"raster-fade-duration":new Ds(xt.paint_raster["raster-fade-duration"])})}};class hh extends qs{constructor(t,e){super(t,ch,e);}}class ph extends qs{constructor(t,e){super(t,{},e),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},this.implementation=t;}is3D(){return "3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return !1}serialize(){throw new Error("Custom layers cannot be serialized")}}class fh{constructor(t){this._methodToThrottle=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle();});}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle();}),0));}remove(){delete this._channel,this._methodToThrottle=()=>{};}}const dh={once:!0},yh=6371008.8;class mh{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new mh(D(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return yh*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof mh)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new mh(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new mh(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const gh=2*Math.PI*yh;function xh(t){return gh*Math.cos(t*Math.PI/180)}function vh(t){return (180+t)/360}function bh(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function wh(t,e){return t/xh(e)}function _h(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}function Sh(t,e){return t*xh(_h(e))}class Ah{constructor(t,e,r=0){this.x=+t,this.y=+e,this.z=+r;}static fromLngLat(t,e=0){const r=mh.convert(t);return new Ah(vh(r.lng),bh(r.lat),wh(e,r.lat))}toLngLat(){return new mh(360*this.x-180,_h(this.y))}toAltitude(){return Sh(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/gh*(t=_h(this.y),1/Math.cos(t*Math.PI/180));var t;}}function kh(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}class Mh{constructor(t,e,r){if(!function(t,e,r){return !(t<0||t>25||r<0||r>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,r))throw new Error(`x=${e}, y=${r}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=r,this.key=Ph(0,t,t,e,r);}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,r){const n=(s=this.y,a=this.z,o=kh(256*(i=this.x),256*(s=Math.pow(2,a)-s-1),a),l=kh(256*(i+1),256*(s+1),a),o[0]+","+o[1]+","+l[0]+","+l[1]);var i,s,a,o,l;const u=function(t,e,r){let n,i="";for(let s=t;s>0;s--)n=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,n)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new r((t.x*e-this.x)*P,(t.y*e-this.y)*P)}toString(){return `${this.z}/${this.x}/${this.y}`}}class Ih{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Ph(t,e.z,e.z,e.x,e.y);}}class zh{constructor(t,e,r,n,i){if(this.terrainRttPosMatrix32f=null,t= z; overscaledZ = ${t}; z = ${r}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Mh(r,+n,+i),this.key=Ph(e,t,r,n,i);}clone(){return new zh(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new zh(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new zh(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const r=this.canonical.z-t;return t>this.canonical.z?Ph(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Ph(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}isChildOf(t){if(t.wrap!==this.wrap)return !1;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new zh(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new zh(e,this.wrap,e,r,n),new zh(e,this.wrap,e,r+1,n),new zh(e,this.wrap,e,r,n+1),new zh(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.ythis.maxX||this.minY>this.maxY)&&(this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0),this}shrinkBy(t){return this.expandBy(-t)}map(t){const e=new Eh;return e.extend(t(new r(this.minX,this.minY))),e.extend(t(new r(this.maxX,this.minY))),e.extend(t(new r(this.minX,this.maxY))),e.extend(t(new r(this.maxX,this.maxY))),e}static fromPoints(t){const e=new Eh;for(const r of t)e.extend(r);return e}contains(t){return t.x>=this.minX&&t.x<=this.maxX&&t.y>=this.minY&&t.y<=this.maxY}empty(){return this.minX>this.maxX}width(){return this.maxX-this.minX}height(){return this.maxY-this.minY}covers(t){return !this.empty()&&!t.empty()&&t.minX>=this.minX&&t.maxX<=this.maxX&&t.minY>=this.minY&&t.maxY<=this.maxY}intersects(t){return !this.empty()&&!t.empty()&&t.minX<=this.maxX&&t.maxX>=this.minX&&t.minY<=this.maxY&&t.maxY>=this.minY}}class Th{constructor(t){this._stringToNumber={},this._numberToString=[];for(let e=0;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class Bh{constructor(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}class Vh{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new is(P,16,0),this.grid3D=new is(P,16,0),this.featureIndexArray=new Ca,this.promoteId=e;}insert(t,e,r,n,i,s){const a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);const o=s?this.grid3D:this.grid;for(let t=0;t=0&&n[3]>=0&&o.insert(a,n[0],n[1],n[2],n[3]);}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new vu(new nc(this.rawTileData)).layers,this.sourceLayerCoder=new Th(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,n,i){this.loadVTLayers();const s=t.params,a=P/t.tileSize/t.scale,o=hi(s.filter,s.globalState),l=t.queryGeometry,u=t.queryPadding*a,c=Eh.fromPoints(l),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=Eh.fromPoints(t.cameraQueryGeometry).expandBy(u),f=this.grid3D.query(p.minX,p.minY,p.maxX,p.maxY,((e,n,i,s)=>function(t,e,n,i,s){for(const r of t)if(e<=r.x&&n<=r.y&&i>=r.x&&s>=r.y)return !0;const a=[new r(e,n),new r(e,s),new r(i,s),new r(i,n)];if(t.length>2)for(const e of a)if(Ro(t,e))return !0;for(let e=0;e(p||(p=Mo(e)),r.queryIntersectsFeature({queryGeometry:l,feature:e,featureState:n,geometry:p,zoom:this.z,transform:t.transform,pixelsToTileUnits:a,pixelPosMatrix:t.pixelPosMatrix,unwrappedTileID:this.tileID.toUnwrapped(),getElevation:t.getElevation}))));}return d}loadMatchingFeature(t,e,r,n,i,s,a,o,l,u,c){const h=this.bucketLayerIDs[e];if(s&&!h.some((t=>s.has(t))))return;const p=this.sourceLayerCoder.decode(r),f=this.vtLayers[p].feature(n);if(i.needGeometry){const t=Io(f,!0);if(!i.filter(new Is(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new Is(this.tileID.overscaledZ),f))return;const d=this.getId(f,p);for(let e=0;e{const a=e instanceof $s?e.get(s):null;return a&&a.evaluate?a.evaluate(r,n,i):a}))}function $h(t,e){return e-t}function Dh(t,e,n,i,s){const a=[];for(let o=0;o=i&&c.x>=i||(o.x>=i?o=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round():c.x>=i&&(c=new r(i,o.y+(i-o.x)/(c.x-o.x)*(c.y-o.y))._round()),o.y>=s&&c.y>=s||(o.y>=s?o=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round():c.y>=s&&(c=new r(o.x+(s-o.y)/(c.y-o.y)*(c.x-o.x),s)._round()),u&&o.equals(u[u.length-1])||(u=[o],a.push(u)),u.push(c)))));}}return a}as("FeatureIndex",Vh,{omit:["rawTileData","sourceLayerCoder"]});class Lh extends r{constructor(t,e,r,n){super(t,e),this.angle=r,void 0!==n&&(this.segment=n);}clone(){return new Lh(this.x,this.y,this.angle,this.segment)}}function Oh(t,e,r,n,i){if(void 0===e.segment||0===r)return !0;let s=e,a=e.segment+1,o=0;for(;o>-r/2;){if(a--,a<0)return !1;o-=t[a].dist(s),s=t[a];}o+=t[a].dist(t[a+1]),a++;const l=[];let u=0;for(;on;)u-=l.shift().angleDelta;if(u>i)return !1;a++,o+=e.dist(r);}return !0}function Rh(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=dr.number(n.x,i.x,c),p=dr.number(n.y,i.y,c),f=new Lh(h,p,i.angleTo(n),r);return f._round(),!a||Oh(t,f,o,a,e)?f:void 0}l+=s;}}function qh(t,e,r,n,i,s,a,o,l){const u=Uh(n,s,a),c=jh(n,i),h=c*a,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new Lh(g,x,y,e);r._round(),n&&!Oh(t,r,s,n,i)||f.push(r);}}h+=d;}return o||f.length||a||(f=Gh(t,h/2,r,n,i,s,a,!0,l)),f}function Xh(t,e,n,i){const s=[],a=t.image,o=a.pixelRatio,l=a.paddedRect.w-2,u=a.paddedRect.h-2;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=a.stretchX||[[0,l]],p=a.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=l-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,S=m,A=0,k=g;if(a.content&&i){const e=a.content,r=e[2]-e[0],n=e[3]-e[1];(a.textFitWidth||a.textFitHeight)&&(c=jc(t)),x=Zh(h,0,e[0]),b=Zh(p,0,e[1]),v=Zh(h,e[0],e[2]),w=Zh(p,e[1],e[3]),_=e[0]-x,A=e[1]-b,S=r-v,k=n-w;}const M=c.x1,I=c.y1,z=c.x2-M,P=c.y2-I,C=(t,i,s,l)=>{const u=Hh(t.stretch-x,v,z,M),c=Kh(t.fixed-_,S,t.stretch,d),h=Hh(i.stretch-b,w,P,I),p=Kh(i.fixed-A,k,i.stretch,y),f=Hh(s.stretch-x,v,z,M),m=Kh(s.fixed-_,S,s.stretch,d),g=Hh(l.stretch-b,w,P,I),C=Kh(l.fixed-A,k,l.stretch,y),E=new r(u,h),T=new r(f,h),B=new r(f,g),V=new r(u,g),F=new r(c/o,p/o),$=new r(m/o,C/o),D=e*Math.PI/180;if(D){const t=Math.sin(D),e=Math.cos(D),r=[e,-t,t,e];E._matMult(r),T._matMult(r),V._matMult(r),B._matMult(r);}const L=t.stretch+t.fixed,O=i.stretch+i.fixed;return {tl:E,tr:T,bl:V,br:B,tex:{x:a.paddedRect.x+1+L,y:a.paddedRect.y+1+O,w:s.stretch+s.fixed-L,h:l.stretch+l.fixed-O},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:F,pixelOffsetBR:$,minFontScaleX:S/o/z,minFontScaleY:k/o/P,isSDF:n}};if(i&&(a.stretchX||a.stretchY)){const t=Yh(h,m,d),e=Yh(p,g,y);for(let r=0;r0&&(n=Math.max(10,n),this.circleDiameter=n);}else {const u=(null===(h=a.image)||void 0===h?void 0:h.content)&&(a.image.textFitWidth||a.image.textFitHeight)?jc(a):{x1:a.left,y1:a.top,x2:a.right,y2:a.bottom};u.y1=u.y1*o-l[0],u.y2=u.y2*o+l[2],u.x1=u.x1*o-l[3],u.x2=u.x2*o+l[1];const p=a.collisionPadding;if(p&&(u.x1-=p[0]*o,u.y1-=p[1]*o,u.x2+=p[2]*o,u.y2+=p[3]*o),c){const t=new r(u.x1,u.y1),e=new r(u.x2,u.y1),n=new r(u.x1,u.y2),i=new r(u.x2,u.y2),s=c*Math.PI/180;t._rotate(s),e._rotate(s),n._rotate(s),i._rotate(s),u.x1=Math.min(t.x,e.x,n.x,i.x),u.x2=Math.max(t.x,e.x,n.x,i.x),u.y1=Math.min(t.y,e.y,n.y,i.y),u.y2=Math.max(t.y,e.y,n.y,i.y);}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,n,i,s);}this.boxEndIndex=t.length;}}class Wh{constructor(t=[],e=(t,e)=>te?1:0){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}}function Qh(t,e=1,n=!1){const i=Eh.fromPoints(t[0]),s=Math.min(i.width(),i.height());let a=s/2;const o=new Wh([],tp),{minX:l,minY:u,maxX:c,maxY:h}=i;if(0===s)return new r(l,u);for(let e=l;ep.d||!p.d)&&(p=r,n&&console.log("found best %d after %d probes",Math.round(1e4*r.d)/1e4,f)),r.max-p.d<=e||(a=r.h/2,o.push(new ep(r.p.x-a,r.p.y-a,a,t)),o.push(new ep(r.p.x+a,r.p.y-a,a,t)),o.push(new ep(r.p.x-a,r.p.y+a,a,t)),o.push(new ep(r.p.x+a,r.p.y+a,a,t)),f+=4);}return n&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function tp(t,e){return e.max-t.max}function ep(t,e,n,i){this.p=new r(t,e),this.h=n,this.d=function(t,e){let r=!1,n=1/0;for(let i=0;it.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(r=!r),n=Math.min(n,Lo(t,i,o));}}return (r?1:-1)*Math.sqrt(n)}(this.p,i),this.max=this.d+this.h*Math.SQRT2;}var rp;t.aE=void 0,(rp=t.aE||(t.aE={}))[rp.center=1]="center",rp[rp.left=2]="left",rp[rp.right=3]="right",rp[rp.top=4]="top",rp[rp.bottom=5]="bottom",rp[rp["top-left"]=6]="top-left",rp[rp["top-right"]=7]="top-right",rp[rp["bottom-left"]=8]="bottom-left",rp[rp["bottom-right"]=9]="bottom-right";const np=Number.POSITIVE_INFINITY;function ip(t,e){return e[1]!==np?function(t,e,r){let n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case "top-right":case "top-left":case "top":i=r-7;break;case "bottom-right":case "bottom-left":case "bottom":i=7-r;}switch(t){case "top-right":case "bottom-right":case "right":n=-e;break;case "top-left":case "bottom-left":case "left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){let r=0,n=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case "top-right":case "top-left":n=i-7;break;case "bottom-right":case "bottom-left":n=7-i;break;case "bottom":n=7-e;break;case "top":n=e-7;}switch(t){case "top-right":case "bottom-right":r=-i;break;case "top-left":case "bottom-left":r=i;break;case "left":r=e;break;case "right":r=-e;}return [r,n]}(t,e[0])}function sp(t,e,r){var n;const i=t.layout,s=null===(n=i.get("text-variable-anchor-offset"))||void 0===n?void 0:n.evaluate(e,{},r);if(s){const t=s.values,e=[];for(let r=0;rt*Qu));n.startsWith("top")?i[1]-=7:n.startsWith("bottom")&&(i[1]+=7),e[r+1]=i;}return new $e(e)}const a=i.get("text-variable-anchor");if(a){let n;n=void 0!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},r)*Qu,np]:i.get("text-offset").evaluate(e,{},r).map((t=>t*Qu));const s=[];for(const t of a)s.push(t,ip(t,n));return new $e(s)}return null}function ap(t){switch(t){case "right":case "top-right":case "bottom-right":return "right";case "left":case "top-left":case "bottom-left":return "left"}return "center"}function op(e,r,n,i,s,a,o,l,u,c,h,p){let f=a.textMaxSize.evaluate(r,{});void 0===f&&(f=o);const d=e.layers[0].layout,y=d.get("icon-offset").evaluate(r,{},h),m=up(n.horizontal),g=o/24,x=e.tilePixelRatio*g,v=e.tilePixelRatio*f/24,b=e.tilePixelRatio*l,w=e.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*e.tilePixelRatio,S=function(t,e,r,n=1){const i=t.get("icon-padding").evaluate(e,{},r),s=i&&i.values;return [s[0]*n,s[1]*n,s[2]*n,s[3]*n]}(d,r,h,e.tilePixelRatio),A=d.get("text-max-angle")/180*Math.PI,k="viewport"!==d.get("text-rotation-alignment")&&"point"!==d.get("symbol-placement"),M="map"===d.get("icon-rotation-alignment")&&"point"!==d.get("symbol-placement"),I=d.get("symbol-placement"),z=w/2,C=d.get("icon-text-fit");let E;i&&"none"!==C&&(e.allowVerticalPlacement&&n.vertical&&(E=Nc(i,n.vertical,C,d.get("icon-text-fit-padding"),y,g)),m&&(i=Nc(i,m,C,d.get("icon-text-fit-padding"),y,g)));const T=h?p.line.getGranularityForZoomLevel(h.z):1,B=(l,p)=>{p.x<0||p.x>=P||p.y<0||p.y>=P||function(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k){const M=e.addToLineVertexArray(r,n);let I,z,P,C,E=0,T=0,B=0,V=0,F=-1,$=-1;const D={};let L=no("");if(e.allowVerticalPlacement&&i.vertical){const t=l.layout.get("text-rotate").evaluate(w,{},A)+90;P=new Jh(u,r,c,h,p,i.vertical,f,d,y,t),o&&(C=new Jh(u,r,c,h,p,o,g,x,y,t));}if(s){const n=l.layout.get("icon-rotate").evaluate(w,{}),i="none"!==l.layout.get("icon-text-fit"),a=Xh(s,n,S,i),f=o?Xh(o,n,S,i):void 0;z=new Jh(u,r,c,h,p,s,g,x,!1,n),E=4*a.length;const d=e.iconSizeData;let y=null;"source"===d.kind?(y=[qc*l.layout.get("icon-size").evaluate(w,{})],y[0]>Gc&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)):"composite"===d.kind&&(y=[qc*_.compositeIconSizes[0].evaluate(w,{},A),qc*_.compositeIconSizes[1].evaluate(w,{},A)],(y[0]>Gc||y[1]>Gc)&&q(`${e.layerIds[0]}: Value for "icon-size" is >= 255. Reduce your "icon-size".`)),e.addSymbols(e.icon,a,y,b,v,w,t.ao.none,r,M.lineStartIndex,M.lineLength,-1,A),F=e.icon.placedSymbolArray.length-1,f&&(T=4*f.length,e.addSymbols(e.icon,f,y,b,v,w,t.ao.vertical,r,M.lineStartIndex,M.lineLength,-1,A),$=e.icon.placedSymbolArray.length-1);}const O=Object.keys(i.horizontal);for(const n of O){const s=i.horizontal[n];if(!I){L=no(s.text);const t=l.layout.get("text-rotate").evaluate(w,{},A);I=new Jh(u,r,c,h,p,s,f,d,y,t);}const o=1===s.positionedLines.length;if(B+=lp(e,r,s,a,l,y,w,m,M,i.vertical?t.ao.horizontal:t.ao.horizontalOnly,o?O:[n],D,F,_,A),o)break}i.vertical&&(V+=lp(e,r,i.vertical,a,l,y,w,m,M,t.ao.vertical,["vertical"],D,$,_,A));const R=I?I.boxStartIndex:e.collisionBoxArray.length,U=I?I.boxEndIndex:e.collisionBoxArray.length,j=P?P.boxStartIndex:e.collisionBoxArray.length,N=P?P.boxEndIndex:e.collisionBoxArray.length,G=z?z.boxStartIndex:e.collisionBoxArray.length,X=z?z.boxEndIndex:e.collisionBoxArray.length,Z=C?C.boxStartIndex:e.collisionBoxArray.length,Y=C?C.boxEndIndex:e.collisionBoxArray.length;let H=-1;const K=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=K(I,H),H=K(P,H),H=K(z,H),H=K(C,H);const J=H>-1?1:0;J&&(H*=k/Qu),e.glyphOffsetArray.length>=th.MAX_GLYPHS&&q("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==w.sortKey&&e.addToSortKeyRanges(e.symbolInstances.length,w.sortKey);const W=sp(l,w,A),[Q,tt]=function(e,r){const n=e.length,i=null==r?void 0:r.values;if((null==i?void 0:i.length)>0)for(let r=0;r=0?D.right:-1,D.center>=0?D.center:-1,D.left>=0?D.left:-1,D.vertical||-1,F,$,L,R,U,j,N,G,X,Z,Y,c,B,V,E,T,J,0,f,H,Q,tt);}(e,p,l,n,i,s,E,e.layers[0],e.collisionBoxArray,r.index,r.sourceLayerIndex,e.index,x,[_,_,_,_],k,u,b,S,M,y,r,a,c,h,o);};if("line"===I)for(const t of Dh(r.geometry,0,0,P,P)){const r=ru(t,T),s=qh(r,w,A,n.vertical||m,i,24,v,e.overscaling,P);for(const t of s)m&&cp(e,m.text,z,t)||B(r,t);}else if("line-center"===I){for(const t of r.geometry)if(t.length>1){const e=ru(t,T),r=Nh(e,A,n.vertical||m,i,24,v);r&&B(e,r);}}else if("Polygon"===r.type)for(const t of Qr(r.geometry,0)){const e=Qh(t,16);B(ru(t[0],T,!0),new Lh(e.x,e.y,0));}else if("LineString"===r.type)for(const t of r.geometry){const e=ru(t,T);B(e,new Lh(e[0].x,e[0].y,0));}else if("Point"===r.type)for(const t of r.geometry)for(const e of t)B([e],new Lh(e.x,e.y,0));}function lp(t,e,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=function(t,e,n,i,s,a,o,l){const u=i.layout.get("text-rotate").evaluate(a,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const i of t.positionedGlyphs){if(!i.rect)continue;const a=i.rect||{};let h=4,p=!0,f=1,d=0;const y=(s||l)&&i.vertical,m=i.metrics.advance*i.scale/2;if(l&&e.verticalizable&&(d=t.lineOffset/2-(i.imageName?-(Qu-i.metrics.width*i.scale)/2:(i.scale-1)*Qu)),i.imageName){const t=o[i.imageName];p=t.sdf,f=t.pixelRatio,h=1/f;}const g=s?[i.x+m,i.y]:[0,0];let x=s?[0,0]:[i.x+m+n[0],i.y+n[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=i.metrics.isDoubleResolution?2:1,w=(i.metrics.left-h)*i.scale-m+x[0],_=(-i.metrics.top-h)*i.scale+x[1],S=w+a.w/b*i.scale/f,A=_+a.h/b*i.scale/f,k=new r(w,_),M=new r(S,_),I=new r(w,A),z=new r(S,A);if(y){const t=new r(-m,m- -17),e=-Math.PI/2,n=12-m,s=new r(22-n,-(i.imageName?n:0)),a=new r(...v);k._rotateAround(e,t)._add(s)._add(a),M._rotateAround(e,t)._add(s)._add(a),I._rotateAround(e,t)._add(s)._add(a),z._rotateAround(e,t)._add(s)._add(a);}if(u){const t=Math.sin(u),e=Math.cos(u),r=[e,-t,t,e];k._matMult(r),M._matMult(r),I._matMult(r),z._matMult(r);}const P=new r(0,0),C=new r(0,0);c.push({tl:k,tr:M,bl:I,br:z,tex:a,writingMode:e.writingMode,glyphOffset:g,sectionIndex:i.sectionIndex,isSDF:p,pixelOffsetTL:P,pixelOffsetBR:C,minFontScaleX:0,minFontScaleY:0});}return c}(0,n,l,s,a,o,i,t.allowVerticalPlacement),g=t.textSizeData;let x=null;"source"===g.kind?(x=[qc*s.layout.get("text-size").evaluate(o,{})],x[0]>Gc&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)):"composite"===g.kind&&(x=[qc*d.compositeTextSizes[0].evaluate(o,{},y),qc*d.compositeTextSizes[1].evaluate(o,{},y)],(x[0]>Gc||x[1]>Gc)&&q(`${t.layerIds[0]}: Value for "text-size" is >= 255. Reduce your "text-size".`)),t.addSymbols(t.text,m,x,l,a,o,c,e,u.lineStartIndex,u.lineLength,f,y);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*m.length}function up(t){for(const e in t)return t[e];return null}function cp(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=hp[15&r];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new pp(a,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=hp.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+s+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return fp(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,r,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:a}=this,o=[0,i.length-1,0],l=[];for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=a){for(let a=h;a<=c;a++){const o=s[2*a],u=s[2*a+1];o>=t&&o<=r&&u>=e&&u<=n&&l.push(i[a]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?r>=f:n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return l}within(t,e,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:n,coords:i,nodeSize:s}=this,a=[0,n.length-1,0],o=[],l=r*r;for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)gp(i[2*r],i[2*r+1],t,e)<=l&&o.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];gp(f,d,t,e)<=l&&o.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return o}}function fp(t,e,r,n,i,s){if(i-n<=r)return;const a=n+i>>1;dp(t,e,a,n,i,s),fp(t,e,r,n,a-1,1-s),fp(t,e,r,a+1,i,1-s);}function dp(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const a=i-n+1,o=r-n+1,l=Math.log(a),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(a-u)/a)*(o-a/2<0?-1:1);dp(t,e,r,Math.max(n,Math.floor(r-o*u/a+c)),Math.min(i,Math.floor(r+(a-o)*u/a+c)),s);}const a=e[2*r+s];let o=n,l=i;for(yp(t,e,n,r),e[2*i+s]>a&&yp(t,e,n,i);oa;)l--;}e[2*n+s]===a?yp(t,e,n,l):(l++,yp(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1);}}function yp(t,e,r,n){mp(t,r,n),mp(e,2*r,2*n),mp(e,2*r+1,2*n+1);}function mp(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function gp(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}var xp;t.cx=void 0,(xp=t.cx||(t.cx={})).create="create",xp.load="load",xp.fullLoad="fullLoad";let vp=null,bp=[];const wp=1e3/60,_p="loadTime",Sp="fullLoadTime",Ap={mark(t){performance.mark(t);},frame(t){const e=t;null!=vp&&bp.push(e-vp),vp=e;},clearMetrics(){vp=null,bp=[],performance.clearMeasures(_p),performance.clearMeasures(Sp);for(const e in t.cx)performance.clearMarks(t.cx[e]);},getPerformanceMetrics(){performance.measure(_p,t.cx.create,t.cx.load),performance.measure(Sp,t.cx.create,t.cx.fullLoad);const e=performance.getEntriesByName(_p)[0].duration,r=performance.getEntriesByName(Sp)[0].duration,n=bp.length,i=1/(bp.reduce(((t,e)=>t+e),0)/n/1e3),s=bp.filter((t=>t>wp)).reduce(((t,e)=>t+(e-wp)/wp),0);return {loadTime:e,fullLoadTime:r,fps:i,percentDroppedFrames:s/(n+s)*100,totalFrames:n}}};t.$=P,t.A=f,t.B=function([t,e,r]){return e+=90,e*=Math.PI/180,r*=Math.PI/180,{x:t*Math.cos(e)*Math.sin(r),y:t*Math.sin(e)*Math.sin(r),z:t*Math.cos(r)}},t.C=dr,t.D=Ds,t.E=gt,t.F=Is,t.G=ts,t.H=function(t){if(null==Z){const e=t.navigator?t.navigator.userAgent:null;Z=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return Z},t.I=vc,t.J=class{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new fh((()=>this.process())),this.subscription=Q(this.target,"message",(t=>this.receive(t)),!1),this.globalScope=X(self)?t:window;}registerMessageHandler(t,e){this.messageHandlers[t]=e;}sendAsync(t,e){return new Promise(((r,n)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10),s=e?Q(e.signal,"abort",(()=>{null==s||s.unsubscribe(),delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e);}),dh):null;this.resolveRejects[i]={resolve:t=>{null==s||s.unsubscribe(),r(t);},reject:t=>{null==s||s.unsubscribe(),n(t);}};const a=[],o=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:cs(t.data,a)});this.target.postMessage(o,{transfer:a});}))}receive(t){const e=t.data,r=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[r];const t=this.abortControllers[r];return delete this.abortControllers[r],void(t&&t.abort())}if(X(self)||e.mustQueue)return this.tasks[r]=e,this.taskQueue.push(r),void this.invoker.trigger();this.processTask(r,e);}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e);}processTask(t,r){return e(this,void 0,void 0,(function*(){if(""===r.type){const e=this.resolveRejects[t];if(delete this.resolveRejects[t],!e)return;return void(r.error?e.reject(hs(r.error)):e.resolve(hs(r.data)))}if(!this.messageHandlers[r.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${r.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const e=hs(r.data),n=new AbortController;this.abortControllers[t]=n;try{const i=yield this.messageHandlers[r.type](r.sourceMapId,e,n);this.completeTask(t,null,i);}catch(e){this.completeTask(t,e);}}))}completeTask(t,e,r){const n=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?cs(e):null,data:cs(r,n)};this.target.postMessage(i,{transfer:n});}remove(){this.invoker.remove(),this.subscription.unsubscribe();}},t.K=lt,t.L=function(){var t=new f(16);return f!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.M=function(t,e,r){var n,i,s,a,o,l,u,c,h,p,f,d,y=r[0],m=r[1],g=r[2];return e===t?(t[12]=e[0]*y+e[4]*m+e[8]*g+e[12],t[13]=e[1]*y+e[5]*m+e[9]*g+e[13],t[14]=e[2]*y+e[6]*m+e[10]*g+e[14],t[15]=e[3]*y+e[7]*m+e[11]*g+e[15]):(i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=n=e[0],t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=n*y+o*m+h*g+e[12],t[13]=i*y+l*m+p*g+e[13],t[14]=s*y+u*m+f*g+e[14],t[15]=a*y+c*m+d*g+e[15]),t},t.N=function(t,e,r){var n=r[0],i=r[1],s=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.O=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],y=e[12],m=e[13],g=e[14],x=e[15],v=r[0],b=r[1],w=r[2],_=r[3];return t[0]=v*n+b*o+w*h+_*y,t[1]=v*i+b*l+w*p+_*m,t[2]=v*s+b*u+w*f+_*g,t[3]=v*a+b*c+w*d+_*x,t[4]=(v=r[4])*n+(b=r[5])*o+(w=r[6])*h+(_=r[7])*y,t[5]=v*i+b*l+w*p+_*m,t[6]=v*s+b*u+w*f+_*g,t[7]=v*a+b*c+w*d+_*x,t[8]=(v=r[8])*n+(b=r[9])*o+(w=r[10])*h+(_=r[11])*y,t[9]=v*i+b*l+w*p+_*m,t[10]=v*s+b*u+w*f+_*g,t[11]=v*a+b*c+w*d+_*x,t[12]=(v=r[12])*n+(b=r[13])*o+(w=r[14])*h+(_=r[15])*y,t[13]=v*i+b*l+w*p+_*m,t[14]=v*s+b*u+w*f+_*g,t[15]=v*a+b*c+w*d+_*x,t},t.P=r,t.Q=function(t,e){const r={};for(let n=0;n!n.has(t.id)))),o.update&&(o.update=o.update.filter((t=>!n.has(t.id))));const i=new Set((null!==(r=t.add)&&void 0!==r?r:[]).map((t=>t.id)));e.remove=e.remove.filter((t=>!i.has(t)));}if(e.remove){const t=new Set(o.remove?o.remove.concat(e.remove):e.remove);o.remove=Array.from(t.values());}if(e.add){const t=o.add?o.add.concat(e.add):e.add,r=new Map(t.map((t=>[t.id,t])));o.add=Array.from(r.values());}if(e.update){const t=new Map(null===(n=o.update)||void 0===n?void 0:n.map((t=>[t.id,t])));for(const r of e.update){const e=null!==(i=t.get(r.id))&&void 0!==i?i:{id:r.id};r.newGeometry&&(e.newGeometry=r.newGeometry),r.addOrUpdateProperties&&(e.addOrUpdateProperties=(null!==(s=e.addOrUpdateProperties)&&void 0!==s?s:[]).concat(r.addOrUpdateProperties)),r.removeProperties&&(e.removeProperties=(null!==(a=e.removeProperties)&&void 0!==a?a:[]).concat(r.removeProperties)),r.removeAllProperties&&(e.removeAllProperties=!0),t.set(r.id,e);}o.update=Array.from(t.values());}return o.remove&&o.add&&(o.remove=o.remove.filter((t=>-1===o.add.findIndex((e=>e.id===t))))),o},t.a1=Ah,t.a2=Eh,t.a3=25,t.a4=Mh,t.a5=t=>{const e=window.document.createElement("video");return e.muted=!0,new Promise((r=>{e.onloadstart=()=>{r(e);};for(const r of t){const t=window.document.createElement("source");pt(r)||(e.crossOrigin="Anonymous"),t.src=r,e.appendChild(t);}}))},t.a6=Ct,t.a7=function(){return O++},t.a8=ba,t.a9=th,t.aA=function(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return [e,r,n,i]},t.aB=Qu,t.aC=C,t.aD=function(t,e,r,n,i=!1){if(!r[0]&&!r[1])return [0,0];const s=i?"map"===n?-t.bearingInRadians:0:"viewport"===n?t.bearingInRadians:0;if(s){const t=Math.sin(s),e=Math.cos(s);r=[r[0]*e-r[1]*t,r[0]*t+r[1]*e];}return [i?r[0]:C(e,r[0],t.zoom),i?r[1]:C(e,r[1],t.zoom)]},t.aF=Zc,t.aG=ap,t.aH=Vc,t.aI=pp,t.aJ=Ys,t.aK=Jl,t.aL=Ea,t.aM=Za,t.aN=Na,t.aO=D,t.aP=et,t.aQ=Sh,t.aR=b,t.aS=v,t.aT=function(t){var e=new f(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.aU=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t},t.aV=function(t,e){var r=e[0],n=e[1],i=e[2],s=r*r+n*n+i*i;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t},t.aW=w,t.aX=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.aY=function(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t},t.aZ=g,t.a_=function(t,e,r){const n=e[0]*r[0]+e[1]*r[1]+e[2]*r[2];return 0===n?null:(-(t[0]*r[0]+t[1]*r[1]+t[2]*r[2])-r[3])/n},t.aa=hi,t.ab=Io,t.ac=Bh,t.ad=function(t){const e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,r,n,i)=>{const s=n||i;return e[r]=!s||s.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t;}return e},t.ae=tt,t.af=function(t){return Math.pow(2,t)},t.ag=y,t.ah=$,t.ai=85.051129,t.aj=wh,t.ak=function(t){return Math.log(t)/Math.LN2},t.al=function(t){var e=t[0],r=t[1];return e*e+r*r},t.am=function(t,e){const r=[];for(const n in t)n in e||r.push(n);return r},t.an=function(t,e){let r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){const{interpolationType:i,minZoom:s,maxZoom:a}=t,o=i?$(pr.interpolationFactor(i,e,s,a),0,1):0;"camera"===t.kind?n=dr.number(t.minSize,t.maxSize,o):r=o;}return {uSizeT:r,uSize:n}},t.ap=function(t,{uSize:e,uSizeT:r},{lowerSize:n,upperSize:i}){return "source"===t.kind?n/qc:"composite"===t.kind?dr.number(n/qc,i/qc,r):e},t.aq=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],y=e[13],m=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,w=n*l-i*o,_=n*u-s*o,S=i*u-s*l,A=c*y-h*d,k=c*m-p*d,M=c*g-f*d,I=h*m-p*y,z=h*g-f*y,P=p*g-f*m,C=x*P-v*z+b*I+w*M-_*k+S*A;return C?(t[0]=(o*P-l*z+u*I)*(C=1/C),t[1]=(i*z-n*P-s*I)*C,t[2]=(y*S-m*_+g*w)*C,t[3]=(p*_-h*S-f*w)*C,t[4]=(l*M-a*P-u*k)*C,t[5]=(r*P-i*M+s*k)*C,t[6]=(m*b-d*S-g*v)*C,t[7]=(c*S-p*b+f*v)*C,t[8]=(a*z-o*M+u*A)*C,t[9]=(n*M-r*z-s*A)*C,t[10]=(d*_-y*b+g*x)*C,t[11]=(h*b-c*_-f*x)*C,t[12]=(o*k-a*I-l*A)*C,t[13]=(r*I-n*k+i*A)*C,t[14]=(y*v-d*w-m*x)*C,t[15]=(c*w-h*v+p*x)*C,t):null},t.ar=I,t.as=function(t){var e=t[0],r=t[1];return Math.sqrt(e*e+r*r)},t.at=function(t){return t[0]=0,t[1]=0,t},t.au=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t},t.av=Kc,t.aw=A,t.ax=function(t,e,n,i){const s=e.y-t.y,a=e.x-t.x,o=i.y-n.y,l=i.x-n.x,u=o*a-l*s;if(0===u)return null;const c=(l*(t.y-n.y)-o*(t.x-n.x))/u;return new r(t.x+c*a,t.y+c*s)},t.ay=Dh,t.az=Eo,t.b=Y,t.b$=class extends la{},t.b0=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t},t.b1=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]},t.b2=Ih,t.b3=Ph,t.b4=function(t,e,r,n,i){var s=1/Math.tan(e/2);if(t[0]=s/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=s,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0){var a=1/(n-i);t[10]=(i+n)*a,t[14]=2*i*n*a;}else t[10]=-1,t[14]=-2*n;return t},t.b5=function(t){var e=new f(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.b6=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[4],c=e[5],h=e[6],p=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i+u*n,t[1]=a*i+c*n,t[2]=o*i+h*n,t[3]=l*i+p*n,t[4]=u*i-s*n,t[5]=c*i-a*n,t[6]=h*i-o*n,t[7]=p*i-l*n,t},t.b7=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=s*i+u*n,t[5]=a*i+c*n,t[6]=o*i+h*n,t[7]=l*i+p*n,t[8]=u*i-s*n,t[9]=c*i-a*n,t[10]=h*i-o*n,t[11]=p*i-l*n,t},t.b8=function(){const t=new Float32Array(16);return y(t),t},t.b9=function(){const t=new Float64Array(16);return y(t),t},t.bA=function(t,e){const r=E(t,360),n=E(e,360),i=n-r,s=n>r?i-360:i+360;return Math.abs(i)0?a:-a},t.bD=function(t,e){const r=E(t,2*Math.PI),n=E(e,2*Math.PI);return Math.min(Math.abs(r-n),Math.abs(r-n+2*Math.PI),Math.abs(r-n-2*Math.PI))},t.bE=function(){const t={},e=xt.$version;for(const r in xt.$root){const n=xt.$root[r];if(n.required){let i=null;i="version"===r?e:"array"===n.type?[]:{},null!=i&&(t[r]=i);}}return t},t.bF=ps,t.bG=ct,t.bH=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(let n=0;n{"source"in t&&n[t.source]?r.push({command:"removeLayer",args:[t.id]}):s.push(t);})),r=r.concat(i),function(t,e,r){e=e||[];const n=(t=t||[]).map(zt),i=e.map(zt),s=t.reduce(Pt,{}),a=e.reduce(Pt,{}),o=n.slice(),l=Object.create(null);let u,c,h,p,f;for(let t=0,e=0;tp?(i=Math.acos(s),a=Math.sin(i),o=Math.sin((1-n)*i)/a,l=Math.sin(n*i)/a):(o=1-n,l=n),t[0]=o*u+l*d,t[1]=o*c+l*y,t[2]=o*h+l*m,t[3]=o*f+l*g,t},t.bd=function(t){const e=new Float64Array(9);var r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v;h=(i=(n=t)[0])*(l=i+i),p=(s=n[1])*l,d=(a=n[2])*l,y=a*(u=s+s),g=(o=n[3])*l,x=o*u,v=o*(c=a+a),(r=e)[0]=1-(f=s*u)-(m=a*c),r[3]=p-v,r[6]=d+x,r[1]=p+v,r[4]=1-h-m,r[7]=y-g,r[2]=d-x,r[5]=y+g,r[8]=1-h-f;const b=et(-Math.asin($(e[2],-1,1)));let w,_;return Math.hypot(e[5],e[8])<.001?(w=0,_=-et(Math.atan2(e[3],e[4]))):(w=et(0===e[5]&&0===e[8]?0:Math.atan2(e[5],e[8])),_=et(0===e[1]&&0===e[0]?0:Math.atan2(e[1],e[0]))),{roll:w,pitch:b+90,bearing:_}},t.be=function(t,e){return t.roll==e.roll&&t.pitch==e.pitch&&t.bearing==e.bearing},t.bf=Me,t.bg=uo,t.bh=Wl,t.bi=Ql,t.bj=Kl,t.bk=T,t.bl=B,t.bm=Le,t.bn=function(t,e,r,n,i){return T(n,i,$((t-e)/(r-e),0,1))},t.bo=E,t.bp=function(){return new Float64Array(3)},t.bq=function(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t},t.br=M,t.bs=function(t,e,r){var n=r[0],i=r[1],s=r[2],a=r[3],o=e[0],l=e[1],u=e[2],c=i*u-s*l,h=s*o-n*u,p=n*l-i*o;return t[0]=o+a*(c+=c)+i*(p+=p)-s*(h+=h),t[1]=l+a*h+s*c-n*p,t[2]=u+a*p+n*h-i*c,t},t.bt=function(t,e,r){const n=(i=[t[0],t[1],t[2],e[0],e[1],e[2],r[0],r[1],r[2]])[0]*((c=i[8])*(a=i[4])-(o=i[5])*(u=i[7]))+i[1]*(-c*(s=i[3])+o*(l=i[6]))+i[2]*(u*s-a*l);var i,s,a,o,l,u,c;if(0===n)return null;const h=w([],[e[0],e[1],e[2]],[r[0],r[1],r[2]]),p=w([],[r[0],r[1],r[2]],[t[0],t[1],t[2]]),f=w([],[t[0],t[1],t[2]],[e[0],e[1],e[2]]),d=b([],h,-t[3]);return v(d,d,b([],p,-e[3])),v(d,d,b([],f,-r[3])),b(d,d,1/n),d},t.bu=yh,t.bv=function(){return new Float64Array(4)},t.bw=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),s[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),s[2]=i[2],t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bx=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0],s[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),s[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.by=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),s[1]=i[1],s[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bz=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i-u*n,t[1]=a*i-c*n,t[2]=o*i-h*n,t[3]=l*i-p*n,t[8]=s*n+u*i,t[9]=a*n+c*i,t[10]=o*n+h*i,t[11]=l*n+p*i,t},t.c=st,t.c0=Ku,t.c1=class extends ca{},t.c2=cl,t.c3=function(t){return t<=1?1:Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},t.c4=ul,t.c5=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[3]*n+r[7]*i+r[11]*s+r[15];return t[0]=(r[0]*n+r[4]*i+r[8]*s+r[12])/(a=a||1),t[1]=(r[1]*n+r[5]*i+r[9]*s+r[13])/a,t[2]=(r[2]*n+r[6]*i+r[10]*s+r[14])/a,t},t.c6=class extends Ws{},t.c7=class extends ga{},t.c8=function(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[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]},t.c9=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=t[9],f=t[10],d=t[11],y=t[12],m=t[13],g=t[14],x=t[15],v=e[0],b=e[1],w=e[2],_=e[3],S=e[4],A=e[5],k=e[6],M=e[7],I=e[8],z=e[9],P=e[10],C=e[11],E=e[12],T=e[13],B=e[14],V=e[15];return Math.abs(r-v)<=p*Math.max(1,Math.abs(r),Math.abs(v))&&Math.abs(n-b)<=p*Math.max(1,Math.abs(n),Math.abs(b))&&Math.abs(i-w)<=p*Math.max(1,Math.abs(i),Math.abs(w))&&Math.abs(s-_)<=p*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(a-S)<=p*Math.max(1,Math.abs(a),Math.abs(S))&&Math.abs(o-A)<=p*Math.max(1,Math.abs(o),Math.abs(A))&&Math.abs(l-k)<=p*Math.max(1,Math.abs(l),Math.abs(k))&&Math.abs(u-M)<=p*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(c-I)<=p*Math.max(1,Math.abs(c),Math.abs(I))&&Math.abs(h-z)<=p*Math.max(1,Math.abs(h),Math.abs(z))&&Math.abs(f-P)<=p*Math.max(1,Math.abs(f),Math.abs(P))&&Math.abs(d-C)<=p*Math.max(1,Math.abs(d),Math.abs(C))&&Math.abs(y-E)<=p*Math.max(1,Math.abs(y),Math.abs(E))&&Math.abs(m-T)<=p*Math.max(1,Math.abs(m),Math.abs(T))&&Math.abs(g-B)<=p*Math.max(1,Math.abs(g),Math.abs(B))&&Math.abs(x-V)<=p*Math.max(1,Math.abs(x),Math.abs(V))},t.cA=function(t,e){at.REGISTERED_PROTOCOLS[t]=e;},t.cB=function(t){delete at.REGISTERED_PROTOCOLS[t];},t.cC=function(t,e){const r={};for(let n=0;nt*Qu));}let v=o?"center":n.get("text-justify").evaluate(i,{},e.canonical);const b="point"===n.get("symbol-placement")?n.get("text-max-width").evaluate(i,{},e.canonical)*Qu:1/0,w=()=>{e.bucket.allowVerticalPlacement&&ds(s)&&(d.vertical=Ac(y,e.glyphMap,e.glyphPositions,e.imagePositions,c,b,a,m,"left",f,g,t.ao.vertical,!0,p,h));};if(!o&&x){const r=new Set;if("auto"===v)for(let t=0;t0||(null===(i=r.addOrUpdateProperties)||void 0===i?void 0:i.length)>0);if((r.newGeometry||r.removeAllProperties||o)&&(e=Object.assign({},e),t.set(r.id,e),o&&(e.properties=Object.assign({},e.properties))),r.newGeometry&&(e.geometry=r.newGeometry),r.removeAllProperties)e.properties={};else if((null===(s=r.removeProperties)||void 0===s?void 0:s.length)>0)for(const t of r.removeProperties)Object.prototype.hasOwnProperty.call(e.properties,t)&&delete e.properties[t];if((null===(a=r.addOrUpdateProperties)||void 0===a?void 0:a.length)>0)for(const{key:t,value:n}of r.addOrUpdateProperties)e.properties[t]=n;}},t.cX=Ms,t.ca=function(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[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.cb=t=>"symbol"===t.type,t.cc=t=>"circle"===t.type,t.cd=t=>"heatmap"===t.type,t.ce=t=>"line"===t.type,t.cf=t=>"fill"===t.type,t.cg=t=>"fill-extrusion"===t.type,t.ch=t=>"hillshade"===t.type,t.ci=t=>"color-relief"===t.type,t.cj=t=>"raster"===t.type,t.ck=t=>"background"===t.type,t.cl=t=>"custom"===t.type,t.cm=V,t.cn=function(t,e,r){const n=z(e.x-r.x,e.y-r.y),i=z(t.x-r.x,t.y-r.y);var s,a;return et(Math.atan2(n[0]*i[1]-n[1]*i[0],(s=n)[0]*(a=i)[0]+s[1]*a[1]))},t.co=F,t.cp=function(t,e){return nt[e]&&(t instanceof MouseEvent||t instanceof WheelEvent)},t.cq=function(t,e){return rt[e]&&"touches"in t},t.cr=function(t){return rt[t]||nt[t]},t.cs=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t},t.ct=function(t,e){const{x:r,y:n}=Ah.fromLngLat(e);return !(t<0||t>25||n<0||n>=1||r<0||r>=1)},t.cu=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.cv=class extends Js{},t.cw=Ap,t.cy=function(t){return t.message===it},t.cz=ut,t.d=pt,t.e=L,t.f=t=>e(void 0,void 0,void 0,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),t.g=ot,t.h=t=>new Promise(((e,r)=>{const n=new Image;n.onload=()=>{e(n),URL.revokeObjectURL(n.src),n.onload=null,window.requestAnimationFrame((()=>{n.src=H;}));},n.onerror=()=>r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const i=new Blob([new Uint8Array(t)],{type:"image/png"});n.src=t.byteLength?URL.createObjectURL(i):H;})),t.i=X,t.j=(t,e)=>ht(L(t,{type:"json"}),e),t.k=mt,t.l=yt,t.m=ht,t.n=(t,e)=>ht(L(t,{type:"arrayBuffer"}),e),t.o=function(t){return new nc(t).readFields(yc,[])},t.p=xc,t.q=ol,t.r=js,t.s=Q,t.t=Es,t.u=fs,t.v=xt,t.w=q,t.x=Qi,t.y=ns,t.z=Wi;})); + +define("worker",["./shared"],(function(e){"use strict";class t{constructor(e,t){this.keyCache={},e&&this.replace(e,t);}replace(e,t){this._layerConfigs={},this._layers={},this.update(e,[],t);}update(t,i,o){for(const i of t){this._layerConfigs[i.id]=i;const t=this._layers[i.id]=e.bJ(i,o);t._featureFilter=e.aa(t.filter,o),this.keyCache[i.id]&&delete this.keyCache[i.id];}for(const e of i)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const s=e.cC(Object.values(this._layerConfigs),this.keyCache);for(const e of s){const t=e.map((e=>this._layers[e.id])),i=t[0];if("none"===i.visibility)continue;const o=i.source||"";let s=this.familiesBySource[o];s||(s=this.familiesBySource[o]={});const n=i.sourceLayer||"_geojsonTileLayer";let r=s[n];r||(r=s[n]=[]),r.push(t);}}}class i{constructor(t){const i={},o=[];for(const e in t){const s=t[e],n=i[e]={};for(const e in s){const t=s[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const i={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};o.push(i),n[e]={rect:i,metrics:t.metrics};}}const{w:s,h:n}=e.p(o),r=new e.q({width:s||1,height:n||1});for(const o in t){const s=t[o];for(const t in s){const n=s[+t];if(!n||0===n.bitmap.width||0===n.bitmap.height)continue;const a=i[o][t].rect;e.q.copy(n.bitmap,r,{x:0,y:0},{x:a.x+1,y:a.y+1},n.bitmap);}}this.image=r,this.positions=i;}}e.cD("GlyphAtlas",i);class o{constructor(t){this.tileID=new e.Z(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[];}parse(t,o,n,r,a){return e._(this,void 0,void 0,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.a8;const l=new e.cE(Object.keys(t.layers).sort()),c=new e.cF(this.tileID,this.promoteId);c.bucketLayerIDs=[];const u={},h={featureIndex:c,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:n,subdivisionGranularity:a},d=o.familiesBySource[this.source];for(const i in d){const o=t.layers[i];if(!o)continue;1===o.version&&e.w(`Vector tile source "${this.source}" layer "${i}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const r=l.encode(i),a=[];for(let e=0;e=i.maxzoom||"none"!==i.visibility&&(s(t,this.zoom,n),(u[i.id]=i.createBucket({index:c.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:r,sourceID:this.source})).populate(a,h,this.tileID.canonical),c.bucketLayerIDs.push(t.map((e=>e.id))));}}const f=e.bN(h.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?void 0:e.abort())),this.inFlightDependencies=[];let g=Promise.resolve({});if(Object.keys(f).length){const e=new AbortController;this.inFlightDependencies.push(e),g=r.sendAsync({type:"GG",data:{stacks:f,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const p=Object.keys(h.iconDependencies);let m=Promise.resolve({});if(p.length){const e=new AbortController;this.inFlightDependencies.push(e),m=r.sendAsync({type:"GI",data:{icons:p,source:this.source,tileID:this.tileID,type:"icons"}},e);}const y=Object.keys(h.patternDependencies);let v=Promise.resolve({});if(y.length){const e=new AbortController;this.inFlightDependencies.push(e),v=r.sendAsync({type:"GI",data:{icons:y,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const[w,x,b]=yield Promise.all([g,m,v]),S=new i(w),_=new e.cG(x,b);for(const t in u){const i=u[t];i instanceof e.a9?(s(i.layers,this.zoom,n),e.cH({bucket:i,glyphMap:w,glyphPositions:S.positions,imageMap:x,imagePositions:_.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:h.subdivisionGranularity})):i.hasPattern&&(i instanceof e.cI||i instanceof e.cJ||i instanceof e.cK)&&(s(i.layers,this.zoom,n),i.addFeatures(h,this.tileID.canonical,_.patternPositions));}return this.status="done",{buckets:Object.values(u).filter((e=>!e.isEmpty())),featureIndex:c,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:S.image,imageAtlas:_,glyphMap:this.returnDependencies?w:null,iconMap:this.returnDependencies?x:null,glyphPositions:this.returnDependencies?S.positions:null}}))}}function s(t,i,o){const s=new e.F(i);for(const e of t)e.recalculate(s,o);}class n{constructor(e,t,i){this.actor=e,this.layerIndex=t,this.availableImages=i,this.fetching={},this.loading={},this.loaded={};}loadVectorTile(t,i){return e._(this,void 0,void 0,(function*(){const o=yield e.n(t.request,i);try{return {vectorTile:new e.cL(new e.cM(o.data)),rawData:o.data,cacheControl:o.cacheControl,expires:o.expires}}catch(e){const i=new Uint8Array(o.data);let s=`Unable to parse the tile at ${t.request.url}, `;throw s+=31===i[0]&&139===i[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${e.message}`,new Error(s)}}))}loadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid,s=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.cN(t.request),n=new o(t);this.loading[i]=n;const r=new AbortController;n.abort=r;try{const o=yield this.loadVectorTile(t,r);if(delete this.loading[i],!o)return null;const a=o.rawData,l={};o.expires&&(l.expires=o.expires),o.cacheControl&&(l.cacheControl=o.cacheControl);const c={};if(s){const e=s.finish();e&&(c.resourceTiming=JSON.parse(JSON.stringify(e)));}n.vectorTile=o.vectorTile;const u=n.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);this.loaded[i]=n,this.fetching[i]={rawTileData:a,cacheControl:l,resourceTiming:c};try{const t=yield u;return e.e({rawTileData:a.slice(0)},t,l,c)}finally{delete this.fetching[i];}}catch(e){throw delete this.loading[i],n.status="done",this.loaded[i]=n,e}}))}reloadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.uid;if(!this.loaded||!this.loaded[i])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const o=this.loaded[i];if(o.showCollisionBoxes=t.showCollisionBoxes,"parsing"===o.status){const s=yield o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);let n;if(this.fetching[i]){const{rawTileData:t,cacheControl:o,resourceTiming:r}=this.fetching[i];delete this.fetching[i],n=e.e({rawTileData:t.slice(0)},s,o,r);}else n=s;return n}if("done"===o.status&&o.vectorTile)return o.parse(o.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity)}))}abortTile(t){return e._(this,void 0,void 0,(function*(){const e=this.loading,i=t.uid;e&&e[i]&&e[i].abort&&(e[i].abort.abort(),delete e[i]);}))}removeTile(t){return e._(this,void 0,void 0,(function*(){this.loaded&&this.loaded[t.uid]&&delete this.loaded[t.uid];}))}}class r{constructor(){this.loaded={};}loadTile(t){return e._(this,void 0,void 0,(function*(){const{uid:i,encoding:o,rawImageData:s,redFactor:n,greenFactor:r,blueFactor:a,baseShift:l}=t,c=s.width+2,u=s.height+2,h=e.b(s)?new e.R({width:c,height:u},yield e.cO(s,-1,-1,c,u)):s,d=new e.cP(i,h,o,n,r,a,l);return this.loaded=this.loaded||{},this.loaded[i]=d,d}))}removeTile(e){const t=this.loaded,i=e.uid;t&&t[i]&&delete t[i];}}var a,l,c=function(){if(l)return a;function e(e,i){if(0!==e.length){t(e[0],i);for(var o=1;o=Math.abs(a)?i-l+a:a-l+i,i=l;}i+o>=0!=!!t&&e.reverse();}return l=1,a=function t(i,o){var s,n=i&&i.type;if("FeatureCollection"===n)for(s=0;s>31}function v(e,t){const i=e.loadGeometry(),o=e.type;let s=0,n=0;for(const r of i){let i=1;1===o&&(i=r.length),t.writeVarint(m(1,i));const a=3===o?r.length-1:r.length;for(let e=0;ee},b=Math.fround||(S=new Float32Array(1),e=>(S[0]=+e,S[0]));var S;class _{constructor(e){this.options=Object.assign(Object.create(x),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:i,maxZoom:o}=this.options;t&&console.time("total time");const s=`prepare ${e.length} points`;t&&console.time(s),this.points=e;const n=[];for(let t=0;t=i;e--){const i=+Date.now();r=this.trees[e]=this._createTree(this._cluster(r,e)),t&&console.log("z%d: %d clusters in %dms",e,r.numItems,+Date.now()-i);}return t&&console.timeEnd("total time"),this}getClusters(e,t){let i=((e[0]+180)%360+360)%360-180;const o=Math.max(-90,Math.min(90,e[1]));let s=180===e[2]?180:((e[2]+180)%360+360)%360-180;const n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)i=-180,s=180;else if(i>s){const e=this.getClusters([i,o,180,n],t),r=this.getClusters([-180,o,s,n],t);return e.concat(r)}const r=this.trees[this._limitZoom(t)],a=r.range(k(i),P(n),k(s),P(o)),l=r.data,c=[];for(const e of a){const t=this.stride*e;c.push(l[t+5]>1?M(l,t,this.clusterProps):this.points[l[t+3]]);}return c}getChildren(e){const t=this._getOriginId(e),i=this._getOriginZoom(e),o="No cluster with the specified id.",s=this.trees[i];if(!s)throw new Error(o);const n=s.data;if(t*this.stride>=n.length)throw new Error(o);const r=this.options.radius/(this.options.extent*Math.pow(2,i-1)),a=s.within(n[t*this.stride],n[t*this.stride+1],r),l=[];for(const t of a){const i=t*this.stride;n[i+4]===e&&l.push(n[i+5]>1?M(n,i,this.clusterProps):this.points[n[i+3]]);}if(0===l.length)throw new Error(o);return l}getLeaves(e,t,i){const o=[];return this._appendLeaves(o,e,t=t||10,i=i||0,0),o}getTile(e,t,i){const o=this.trees[this._limitZoom(e)],s=Math.pow(2,e),{extent:n,radius:r}=this.options,a=r/n,l=(i-a)/s,c=(i+1+a)/s,u={features:[]};return this._addTileFeatures(o.range((t-a)/s,l,(t+1+a)/s,c),o.data,t,i,s,u),0===t&&this._addTileFeatures(o.range(1-a/s,l,1,c),o.data,s,i,s,u),t===s-1&&this._addTileFeatures(o.range(0,l,a/s,c),o.data,-1,i,s,u),u.features.length?u:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const i=this.getChildren(e);if(t++,1!==i.length)break;e=i[0].properties.cluster_id;}return t}_appendLeaves(e,t,i,o,s){const n=this.getChildren(t);for(const t of n){const n=t.properties;if(n&&n.cluster?s+n.point_count<=o?s+=n.point_count:s=this._appendLeaves(e,n.cluster_id,i,o,s):s1;let l,c,u;if(a)l=I(t,e,this.clusterProps),c=t[e],u=t[e+1];else {const i=this.points[t[e+3]];l=i.properties;const[o,s]=i.geometry.coordinates;c=k(o),u=P(s);}const h={type:1,geometry:[[Math.round(this.options.extent*(c*s-i)),Math.round(this.options.extent*(u*s-o))]],tags:l};let d;d=a||this.options.generateId?t[e+3]:this.points[t[e+3]].id,void 0!==d&&(h.id=d),n.features.push(h);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:i,extent:o,reduce:s,minPoints:n}=this.options,r=i/(o*Math.pow(2,t)),a=e.data,l=[],c=this.stride;for(let i=0;it&&(f+=a[i+5]);}if(f>d&&f>=n){let e,n=o*d,r=u*d,g=-1;const p=(i/c<<5)+(t+1)+this.points.length;for(const o of h){const l=o*c;if(a[l+2]<=t)continue;a[l+2]=t;const u=a[l+5];n+=a[l]*u,r+=a[l+1]*u,a[l+4]=p,s&&(e||(e=this._map(a,i,!0),g=this.clusterProps.length,this.clusterProps.push(e)),s(e,this._map(a,l)));}a[i+4]=p,l.push(n/f,r/f,1/0,p,-1,f),s&&l.push(g);}else {for(let e=0;e1)for(const e of h){const i=e*c;if(!(a[i+2]<=t)){a[i+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,i){if(e[t+5]>1){const o=this.clusterProps[e[t+6]];return i?Object.assign({},o):o}const o=this.points[e[t+3]].properties,s=this.options.map(o);return i&&s===o?Object.assign({},s):s}}function M(e,t,i){return {type:"Feature",id:e[t+3],properties:I(e,t,i),geometry:{type:"Point",coordinates:[(o=e[t],360*(o-.5)),T(e[t+1])]}};var o;}function I(e,t,i){const o=e[t+5],s=o>=1e4?`${Math.round(o/1e3)}k`:o>=1e3?Math.round(o/100)/10+"k":o,n=e[t+6],r=-1===n?{}:Object.assign({},i[n]);return Object.assign(r,{cluster:!0,cluster_id:e[t+3],point_count:o,point_count_abbreviated:s})}function k(e){return e/360+.5}function P(e){const t=Math.sin(e*Math.PI/180),i=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return i<0?0:i>1?1:i}function T(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function D(e,t,i,o){let s=o;const n=t+(i-t>>1);let r,a=i-t;const l=e[t],c=e[t+1],u=e[i],h=e[i+1];for(let o=t+3;os)r=o,s=t;else if(t===s){const e=Math.abs(o-n);eo&&(r-t>3&&D(e,t,r,o),e[r+2]=s,i-r>3&&D(e,r,i,o));}function C(e,t,i,o,s,n){let r=s-i,a=n-o;if(0!==r||0!==a){const l=((e-i)*r+(t-o)*a)/(r*r+a*a);l>1?(i=s,o=n):l>0&&(i+=r*l,o+=a*l);}return r=e-i,a=t-o,r*r+a*a}function L(e,t,i,o){const s={id:null==e?null:e,type:t,geometry:i,tags:o,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===t||"MultiPoint"===t||"LineString"===t)O(s,i);else if("Polygon"===t)O(s,i[0]);else if("MultiLineString"===t)for(const e of i)O(s,e);else if("MultiPolygon"===t)for(const e of i)O(s,e[0]);return s}function O(e,t){for(let i=0;i0&&(r+=o?(s*l-a*n)/2:Math.sqrt(Math.pow(a-s,2)+Math.pow(l-n,2))),s=a,n=l;}const a=t.length-3;t[2]=1,D(t,0,a,i),t[a+2]=1,t.size=Math.abs(r),t.start=0,t.end=t.size;}function G(e,t,i,o){for(let s=0;s1?1:i}function j(e,t,i,o,s,n,r,a){if(o/=t,n>=(i/=t)&&r=o)return null;const l=[];for(const t of e){const e=t.geometry;let n=t.type;const r=0===s?t.minX:t.minY,c=0===s?t.maxX:t.maxY;if(r>=i&&c=o)continue;let u=[];if("Point"===n||"MultiPoint"===n)N(e,u,i,o,s);else if("LineString"===n)R(e,u,i,o,s,!1,a.lineMetrics);else if("MultiLineString"===n)J(e,u,i,o,s,!1);else if("Polygon"===n)J(e,u,i,o,s,!0);else if("MultiPolygon"===n)for(const t of e){const e=[];J(t,e,i,o,s,!0),e.length&&u.push(e);}if(u.length){if(a.lineMetrics&&"LineString"===n){for(const e of u)l.push(L(t.id,n,e,t.tags));continue}"LineString"!==n&&"MultiLineString"!==n||(1===u.length?(n="LineString",u=u[0]):n="MultiLineString"),"Point"!==n&&"MultiPoint"!==n||(n=3===u.length?"Point":"MultiPoint"),l.push(L(t.id,n,u,t.tags));}}return l.length?l:null}function N(e,t,i,o,s){for(let n=0;n=i&&r<=o&&Y(t,e[n],e[n+1],e[n+2]);}}function R(e,t,i,o,s,n,r){let a=W(e);const l=0===s?q:X;let c,u,h=e.start;for(let d=0;di&&(u=l(a,f,g,m,y,i),r&&(a.start=h+c*u)):v>o?w=i&&(u=l(a,f,g,m,y,i),x=!0),w>o&&v<=o&&(u=l(a,f,g,m,y,o),x=!0),!n&&x&&(r&&(a.end=h+c*u),t.push(a),a=W(e)),r&&(h+=c);}let d=e.length-3;const f=e[d],g=e[d+1],p=0===s?f:g;p>=i&&p<=o&&Y(a,f,g,e[d+2]),d=a.length-3,n&&d>=3&&(a[d]!==a[0]||a[d+1]!==a[1])&&Y(a,a[0],a[1],a[2]),a.length&&t.push(a);}function W(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function J(e,t,i,o,s,n){for(const r of e)R(r,t,i,o,s,n,!1);}function Y(e,t,i,o){e.push(t,i,o);}function q(e,t,i,o,s,n){const r=(n-t)/(o-t);return Y(e,n,i+(s-i)*r,1),r}function X(e,t,i,o,s,n){const r=(n-i)/(s-i);return Y(e,t+(o-t)*r,n,1),r}function H(e,t){const i=[];for(let o=0;o0&&t.size<(s?r:o))return void(i.numPoints+=t.length/3);const a=[];for(let e=0;er)&&(i.numSimplified++,a.push(t[e],t[e+1])),i.numPoints++;s&&function(e,t){let i=0;for(let t=0,o=e.length,s=o-2;t0===t)for(let t=0,i=e.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");let o=function(e,t){const i=[];if("FeatureCollection"===e.type)for(let o=0;o1&&console.time("creation"),d=this.tiles[h]=U(e,t,i,o,l),this.tileCoords.push({z:t,x:i,y:o}),c)){c>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,i,o,d.numFeatures,d.numPoints,d.numSimplified),console.timeEnd("creation"));const e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++;}if(d.source=e,null==s){if(t===l.indexMaxZoom||d.numPoints<=l.indexMaxPoints)continue}else {if(t===l.maxZoom||t===s)continue;if(null!=s){const e=s-t;if(i!==n>>e||o!==r>>e)continue}}if(d.source=null,0===e.length)continue;c>1&&console.time("clipping");const f=.5*l.buffer/l.extent,g=.5-f,p=.5+f,m=1+f;let y=null,v=null,w=null,x=null,b=j(e,u,i-f,i+p,0,d.minX,d.maxX,l),S=j(e,u,i+g,i+m,0,d.minX,d.maxX,l);e=null,b&&(y=j(b,u,o-f,o+p,1,d.minY,d.maxY,l),v=j(b,u,o+g,o+m,1,d.minY,d.maxY,l),b=null),S&&(w=j(S,u,o-f,o+p,1,d.minY,d.maxY,l),x=j(S,u,o+g,o+m,1,d.minY,d.maxY,l),S=null),c>1&&console.timeEnd("clipping"),a.push(y||[],t+1,2*i,2*o),a.push(v||[],t+1,2*i,2*o+1),a.push(w||[],t+1,2*i+1,2*o),a.push(x||[],t+1,2*i+1,2*o+1);}}getTile(e,t,i){e=+e,t=+t,i=+i;const o=this.options,{extent:s,debug:n}=o;if(e<0||e>24)return null;const r=1<1&&console.log("drilling down to z%d-%d-%d",e,t,i);let l,c=e,u=t,h=i;for(;!l&&c>0;)c--,u>>=1,h>>=1,l=this.tiles[ie(c,u,h)];return l&&l.source?(n>1&&(console.log("found parent tile z%d-%d-%d",c,u,h),console.time("drilling down")),this.splitTile(l.source,c,u,h,e,t,i),n>1&&console.timeEnd("drilling down"),this.tiles[a]?B(this.tiles[a],s):null):null}}function ie(e,t,i){return 32*((1<{r.properties=e;const t={};for(const e of a)t[e]=o[e].evaluate(n,r);return t},t.reduce=(e,t)=>{r.properties=t;for(const t of a)n.accumulated=e[t],e[t]=s[t].evaluate(n,r);},t}(t)).load(i.features):function(e,t){return new te(e,t)}(i,t.geojsonVtOptions),this.loaded={};const s={data:i};if(o){const e=o.finish();e&&(s.resourceTiming={},s.resourceTiming[t.source]=JSON.parse(JSON.stringify(e)));}return s}catch(t){if(delete this._pendingRequest,e.cy(t))return {abandoned:!0};throw t}}))}getData(){return e._(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(e){const t=this.loaded;return t&&t[e.uid]?super.reloadTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){let o=yield this.loadGeoJSON(t,i);if(delete this._pendingRequest,"object"!=typeof o)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(u(o,!0),t.filter){const i=e.cT(t.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===i.result)throw new Error(i.value.map((e=>`${e.key}: ${e.message}`)).join(", "));const s=o.features.filter((e=>i.value.evaluate({zoom:0},e)));o={type:"FeatureCollection",features:s};}return o}))}loadGeoJSON(t,i){return e._(this,void 0,void 0,(function*(){const{promoteId:o}=t;if(t.request){const s=yield e.j(t.request,i);return this._dataUpdateable=e.cV(s.data,o)?e.cU(s.data,o):void 0,s.data}if("string"==typeof t.data)try{const i=JSON.parse(t.data);return this._dataUpdateable=e.cV(i,o)?e.cU(i,o):void 0,i}catch(e){throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}if(!t.dataDiff)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${t.source}`);return e.cW(this._dataUpdateable,t.dataDiff,o),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(t){return e._(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset)}}class se{constructor(t){this.self=t,this.actor=new e.J(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=new Map,this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.cA,this.self.removeProtocol=e.cB,this.self.registerRTLTextPlugin=t=>{e.cX.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,i)=>e._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(t,i.source).removeTile(i);})))),this.actor.registerMessageHandler("GCEZ",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterExpansionZoom(i)})))),this.actor.registerMessageHandler("GCC",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterChildren(i)})))),this.actor.registerMessageHandler("GCL",((t,i)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,i.type,i.source).getClusterLeaves(i)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("GD",((e,t)=>this._getWorkerSource(e,t.type,t.source).getData())),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,i)=>e._(this,void 0,void 0,(function*(){if(!this.workerSources[t]||!this.workerSources[t][i.type]||!this.workerSources[t][i.type][i.source])return;const e=this.workerSources[t][i.type][i.source];delete this.workerSources[t][i.type][i.source],void 0!==e.removeSource&&e.removeSource(i);})))),this.actor.registerMessageHandler("RM",(t=>e._(this,void 0,void 0,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t],this.globalStates.delete(t);})))),this.actor.registerMessageHandler("SR",((t,i)=>e._(this,void 0,void 0,(function*(){this.referrer=i;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,i)=>e._(this,void 0,void 0,(function*(){this.self.importScripts(i);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).update(i.layers,i.removedIds,this._getGlobalState(t));})))),this.actor.registerMessageHandler("UGS",((t,i)=>e._(this,void 0,void 0,(function*(){const e=this._getGlobalState(t);for(const t in i)e[t]=i[t];})))),this.actor.registerMessageHandler("SL",((t,i)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).replace(i,this._getGlobalState(t));}))));}_getGlobalState(e){let t=this.globalStates.get(e);return t||(t={},this.globalStates.set(e,t)),t}_setImages(t,i){return e._(this,void 0,void 0,(function*(){this.availableImages[t]=i;for(const e in this.workerSources[t]){const o=this.workerSources[t][e];for(const e in o)o[e].availableImages=i;}}))}_syncRTLPluginState(t,i){return e._(this,void 0,void 0,(function*(){return yield e.cX.syncState(i,this.self.importScripts)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(e){let i=this.layerIndexes[e];return i||(i=this.layerIndexes[e]=new t),i}_getWorkerSource(e,t,i){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][i]){const o={sendAsync:(t,i)=>(t.targetMapId=e,this.actor.sendAsync(t,i))};switch(t){case "vector":this.workerSources[e][t][i]=new n(o,this._getLayerIndex(e),this._getAvailableImages(e));break;case "geojson":this.workerSources[e][t][i]=new oe(o,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][i]=new this.externalWorkerSourceTypes[t](o,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][t][i]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new r),this.demWorkerSources[e][t]}}return e.i(self)&&(self.worker=new se(self)),se})); + +define("index",["exports","./shared"],(function(e,t){"use strict";var i="5.7.2";function o(){var e=new t.A(4);return t.A!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}let r,a;const s={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frame(e,i,o){const r=requestAnimationFrame((e=>{a(),i(e);})),{unsubscribe:a}=t.s(e.signal,"abort",(()=>{a(),cancelAnimationFrame(r),o(t.c());}),!1);},frameAsync(e){return new Promise(((t,i)=>{this.frame(e,t,i);}))},getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(r||(r=document.createElement("a")),r.href=e,r.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==a&&(a=matchMedia("(prefers-reduced-motion: reduce)")),a.matches)}};class n{static testProp(e){if(!n.docStyle)return e[0];for(let t=0;t{window.removeEventListener("click",n.suppressClickInternal,!0);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,o){const r=i.boundingClientRect;return new t.P((o.clientX-r.left)/i.x-e.clientLeft,(o.clientY-r.top)/i.y-e.clientTop)}static mousePos(e,t){const i=n.getScale(e);return n.getPoint(e,i,t)}static touchPos(e,t){const i=[],o=n.getScale(e);for(let r=0;r{c&&_(c),c=null,d=!0;},h.onerror=()=>{u=!0,c=null;},h.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(e){let i,o,r,a;e.resetRequestQueue=()=>{i=[],o=0,r=0,a={};},e.addThrottleControl=e=>{const t=r++;return a[t]=e,t},e.removeThrottleControl=e=>{delete a[e],n();},e.getImage=(e,o,r=!0)=>new Promise(((a,s)=>{l.supported&&(e.headers||(e.headers={}),e.headers.accept="image/webp,*/*"),t.e(e,{type:"image"}),i.push({abortController:o,requestParameters:e,supportImageRefresh:r,state:"queued",onError:e=>{s(e);},onSuccess:e=>{a(e);}}),n();}));const s=e=>t._(this,void 0,void 0,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:r,onError:a,onSuccess:s,abortController:l}=e,h=!1===r&&!t.i(self)&&!t.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),!0));o++;const u=h?c(i,l):t.m(i,l);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.b(i.data)?s(i):i.data&&s({data:yield(d=i.data,"function"==typeof createImageBitmap?t.f(d):t.h(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,a(t);}finally{o--,n();}var d;})),n=()=>{const e=(()=>{for(const e of Object.keys(a))if(a[e]())return !0;return !1})()?t.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=o;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:s(e);}},c=(e,i)=>new Promise(((o,r)=>{const a=new Image,s=e.url,n=e.credentials;n&&"include"===n?a.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.d(s))&&(a.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{a.src="",r(t.c());})),a.fetchPriority="high",a.onload=()=>{a.onerror=a.onload=null,o({data:a});},a.onerror=()=>{a.onerror=a.onload=null,i.signal.aborted||r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));},a.src=s;}));}(p||(p={})),p.resetRequestQueue();class m{constructor(e){this._transformRequestFn=null!=e?e:null;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}function f(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:o,url:r}of e){const e=`${o}${r}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:o,url:r}));}}return t}function g(e,t,i){try{const o=new URL(e);return o.pathname+=`${t}${i}`,o.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}function v(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),!0)}class b extends t.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.R({width:1,height:1}),this.dirty=!0;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.R({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let o=!0;const r=i.data||i.spriteData;return this._validateStretch(i.stretchX,r&&r.width)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchX" value`))),o=!1),this._validateStretch(i.stretchY,r&&r.height)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "stretchY" value`))),o=!1),this._validateContent(i.content,i)||(this.fire(new t.k(new Error(`Image "${e}" has invalid "content" value`))),o=!1),o}_validateStretch(e,t){if(!e)return !0;let i=0;for(const o of e){if(o[0]{let o=!0;if(!this.isLoaded())for(const t of e)this.images[t]||(o=!1);this.isLoaded()||o?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const o of e){let e=this.getImage(o);e||(this.fire(new t.l("styleimagemissing",{id:o})),e=this.getImage(o)),e?i[o]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.w(`Image "${o}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);}return i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],o=this.getImage(e);if(!o)return null;if(i&&i.position.version===o.version)return i.position;if(i)i.position.version=o.version;else {const i={w:o.data.width+2,h:o.data.height+2,x:0,y:0},r=new t.I(i,o);this.patterns[e]={bin:i,position:r};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const i=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new t.T(e,this.atlasImage,i.RGBA),this.atlasTexture.bind(i.LINEAR,i.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:o}=t.p(e),r=this.atlasImage;r.resize({width:i||1,height:o||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],o=i.x+1,a=i.y+1,s=this.getImage(e).data,n=s.width,l=s.height;t.R.copy(s,r,{x:0,y:0},{x:o,y:a},{width:n,height:l}),t.R.copy(s,r,{x:0,y:l-1},{x:o,y:a-1},{width:n,height:1}),t.R.copy(s,r,{x:0,y:0},{x:o,y:a+l},{width:n,height:1}),t.R.copy(s,r,{x:n-1,y:0},{x:o-1,y:a},{width:1,height:l}),t.R.copy(s,r,{x:0,y:0},{x:o+n,y:a},{width:1,height:l});}this.dirty=!0;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=!0;const e=this.getImage(i);e||t.w(`Image with ID: "${i}" was not found`),v(e)&&this.updateImage(i,e);}}}const x=1e20;function y(e,t,i,o,r,a,s,n,l){for(let c=t;c-1);l++,a[l]=n,s[l]=c,s[l+1]=x;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(t.ranges[r])return {stack:e,id:i,glyph:o};if(!this.url)throw new Error("glyphsUrl is not set");if(!t.requests[r]){const i=T.loadGlyphRange(e,r,this.url,this.requestManager);t.requests[r]=i;}const a=yield t.requests[r];for(const e in a)this._doesCharSupportLocalGlyph(+e)||(t.glyphs[+e]=a[+e]);return t.ranges[r]=!0,{stack:e,id:i,glyph:a[i]||null}}))}_doesCharSupportLocalGlyph(e){return !!this.localIdeographFontFamily&&(/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(e))||t.u["CJK Unified Ideographs"](e)||t.u["Hangul Syllables"](e)||t.u.Hiragana(e)||t.u.Katakana(e)||t.u["CJK Symbols and Punctuation"](e)||t.u["Halfwidth and Fullwidth Forms"](e))}_tinySDF(e,i,o){const r=this.localIdeographFontFamily;if(!r)return;if(!this._doesCharSupportLocalGlyph(o))return;let a=e.tinySDF;if(!a){let t="400";/bold/i.test(i)?t="900":/medium/i.test(i)?t="500":/light/i.test(i)&&(t="200"),a=e.tinySDF=new T.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,lang:this.lang,fontFamily:r,fontWeight:t});}const s=a.draw(String.fromCharCode(o));return {id:o,bitmap:new t.q({width:s.width||60,height:s.height||60},s.data),metrics:{width:s.glyphWidth/2||24,height:s.glyphHeight/2||24,left:s.glyphLeft/2+.5||0,top:s.glyphTop/2-27.5||-8,advance:s.glyphAdvance/2||24,isDoubleResolution:!0}}}}T.loadGlyphRange=function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=256*i,s=a+255,n=r.transformRequest(o.replace("{fontstack}",e).replace("{range}",`${a}-${s}`),"Glyphs"),l=yield t.n(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${a}-${s}`);const c={};for(const e of t.o(l.data))c[e.id]=e;return c}))},T.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:o=.25,fontFamily:r="sans-serif",fontWeight:a="normal",fontStyle:s="normal",lang:n=null}={}){this.buffer=t,this.cutoff=o,this.radius=i,this.lang=n;const l=this.size=e+4*t,c=this._createCanvas(l),h=this.ctx=c.getContext("2d",{willReadFrequently:!0});h.font=`${s} ${a} ${e}px ${r}`,h.textBaseline="alphabetic",h.textAlign="left",h.fillStyle="black",this.gridOuter=new Float64Array(l*l),this.gridInner=new Float64Array(l*l),this.f=new Float64Array(l),this.z=new Float64Array(l+1),this.v=new Uint16Array(l);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:o,actualBoundingBoxLeft:r,actualBoundingBoxRight:a}=this.ctx.measureText(e),s=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(a-r))),l=Math.min(this.size-this.buffer,s+Math.ceil(o)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:s,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;this.lang&&(p.lang=this.lang),p.clearRect(m,m,n,l),p.fillText(e,m,m+s);const v=p.getImageData(m,m,n,l);g.fill(x,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[o]=e<0?e*e:0;}}y(g,0,0,c,h,c,this.f,this.v,this.z),y(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(s=e[++a]);const l=Math.abs(n-s.left),c=Math.abs(n-s.right),h=Math.min(l,c);let u;const d=t/i*(o+1);if(s.isDash){const e=o-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=o-Math.sqrt(h*h+d*d);this.data[r+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],o=e[t+1];i.zeroLength?e.splice(t,1):o&&o.isDash===i.isDash&&(o.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const o=this.width*this.nextRow;let r=0,a=e[r];for(let t=0;t1&&(a=e[++r]);const i=Math.abs(t-a.left),s=Math.abs(t-a.right),n=Math.min(i,s);this.data[o+t]=Math.max(0,Math.min(255,(a.isDash?n:-n)+128));}}addDash(e,i){const o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.w("LineAtlas out of space"),null;let a=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[R]}numActive(){return Object.keys(this.active).length}}const D=Math.floor(s.hardwareConcurrency/2);let A,L;function k(){return A||(A=new z),A}z.workerCount=t.H(globalThis)?Math.max(Math.min(D,3),1):1;class F{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const o=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}}function B(){return L||(L=new F(k(),t.K),L.registerMessageHandler("GR",((e,i,o)=>t.m(i,o)))),L}function O(e,i){const o=t.L();return t.M(o,o,[1,1,0]),t.N(o,o,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.O(o,o,e.calculatePosMatrix(i.toUnwrapped())):o}function j(e,t,i,o,r,a,s){var n;const l=function(e,t,i){if(e)for(const o of e){const e=t[o];if(e&&e.source===i&&"fill-extrusion"===e.type)return !0}else for(const e in t){const o=t[e];if(o.source===i&&"fill-extrusion"===o.type)return !0}return !1}(null!==(n=null==r?void 0:r.layers)&&void 0!==n?n:null,t,e.id),c=a.maxPitchScaleFactor(),h=e.tilesIn(o,c,l);h.sort(N);const u=[];for(const o of h)u.push({wrappedTileID:o.tileID.wrapped().key,queryResults:o.tile.queryRenderedFeatures(t,i,e._state,o.queryGeometry,o.cameraQueryGeometry,o.scale,r,a,c,O(e.transform,o.tileID),s?(e,t)=>s(o.tileID,e,t):void 0)});return function(e,t){for(const i in e)for(const o of e[i])U(o,t);return e}(function(e){const t={},i={};for(const o of e){const e=o.queryResults,r=o.wrappedTileID,a=i[r]=i[r]||{};for(const i in e){const o=e[i],r=a[i]=a[i]||{},s=t[i]=t[i]||[];for(const e of o)r[e.featureIndex]||(r[e.featureIndex]=!0,s.push(e));}}return t}(u),e)}function N(e,t){const i=e.tileID,o=t.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}function U(e,t){const i=e.feature,o=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=o;}function Z(e,i,o){return t._(this,void 0,void 0,(function*(){let r=e;if(e.url?r=(yield t.j(i.transformRequest(e.url,"Source"),o)).data:yield s.frameAsync(o),!r)return null;const a=t.Q(t.e(r,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in r&&r.vector_layers&&(a.vectorLayerIds=r.vector_layers.map((e=>e.id))),a}))}class G{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.S?new t.S(e.lng,e.lat):t.S.convert(e),this}extend(e){const i=this._sw,o=this._ne;let r,a;if(e instanceof t.S)r=e,a=e;else {if(!(e instanceof G))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(G.convert(e)):this.extend(t.S.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.S.convert(e)):this;if(r=e._sw,a=e._ne,!r||!a)return this}return i||o?(i.lng=Math.min(r.lng,i.lng),i.lat=Math.min(r.lat,i.lat),o.lng=Math.max(a.lng,o.lng),o.lat=Math.max(a.lat,o.lat)):(this._sw=new t.S(r.lng,r.lat),this._ne=new t.S(a.lng,a.lat)),this}getCenter(){return new t.S((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new t.S(this.getWest(),this.getNorth())}getSouthEast(){return new t.S(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(e){const{lng:i,lat:o}=t.S.convert(e);let r=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(r=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=o&&o<=this._ne.lat&&r}static convert(e){return e instanceof G?e:e?new G(e):e}static fromLngLat(e,i=0){const o=360*i/40075017,r=o/Math.cos(Math.PI/180*e.lat);return new G(new t.S(e.lng-r,e.lat-o),new t.S(e.lng+r,e.lat+o))}adjustAntiMeridian(){const e=new t.S(this._sw.lng,this._sw.lat),i=new t.S(this._ne.lng,this._ne.lat);return new G(e,e.lng>i.lng?new t.S(i.lng+360,i.lat):i)}}class V{constructor(e,t,i){this.bounds=G.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),o=Math.floor(t.V(this.bounds.getWest())*i),r=Math.floor(t.U(this.bounds.getNorth())*i),a=Math.ceil(t.V(this.bounds.getEast())*i),s=Math.ceil(t.U(this.bounds.getSouth())*i);return e.x>=o&&e.x=r&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.e({},this._options)}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};i.request.collectResourceTiming=this._collectResourceTiming;let o="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),o="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:o,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_afterTileLoadWorkerResponse(e,t){if(t&&t.resourceTiming&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return !1}}class q extends t.E{constructor(e,i,o,r){super(),this.id=e,this.dispatcher=o,this.setEventedParent(r),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.e({type:"raster"},i),t.e(this,t.Q(i,["url","scheme","tileSize"]));}load(){return t._(this,arguments,void 0,(function*(e=!1){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield Z(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,i&&(t.e(this,i),i.bounds&&(this.tileBounds=new V(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.l("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(!0);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.e({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const o=yield p.getImage(this.map._requestManager.transformRequest(i,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(o&&o.data){this.map._refreshExpiredTiles&&(o.cacheControl||o.expires)&&e.setExpiryData({cacheControl:o.cacheControl,expires:o.expires});const i=this.map.painter.context,r=i.gl,a=o.data;e.texture=this.map.painter.getTileTexture(a.width),e.texture?e.texture.update(a,{useMipmap:!0}):(e.texture=new t.T(i,a,r.RGBA,{useMipmap:!0}),e.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return !1}}class W extends q{constructor(e,i,o,r){super(e,i,o,r),this.type="raster-dem",this.maxzoom=22,this._options=t.e({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t._(this,void 0,void 0,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),o=this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield p.getImage(o,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const o=i.data;this.map._refreshExpiredTiles&&(i.cacheControl||i.expires)&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const r=t.b(o)&&t.W()?o:yield this.readImageNow(o),a={type:this.type,uid:e.uid,source:this.id,rawImageData:r,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!e.actor||"expired"===e.state){e.actor=this.dispatcher.getActor();const t=yield e.actor.sendAsync({type:"LDT",data:a});e.dem=t,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t._(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&t.X()){const i=e.width+2,o=e.height+2;try{return new t.R({width:i,height:o},yield t.Y(e,-1,-1,i,o))}catch(e){}}return s.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,o=Math.pow(2,i.z),r=(i.x-1+o)%o,a=0===i.x?e.wrap-1:e.wrap,s=(i.x+1+o)%o,n=i.x+1===o?e.wrap+1:e.wrap,l={};return l[new t.Z(e.overscaledZ,a,i.z,r,i.y).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y).key]={backfilled:!1},i.y>0&&(l[new t.Z(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.Z(e.overscaledZ,n,i.z,s,i.y-1).key]={backfilled:!1}),i.y+1e.coordinates)).flat(1/0):e.coordinates.flat(1/0)}getBounds(){return t._(this,void 0,void 0,(function*(){const e=new G,t=yield this.getData();let i;switch(t.type){case "FeatureCollection":i=t.features.map((e=>this.getCoordinatesFromGeometry(e.geometry))).flat(1/0);break;case "Feature":i=this.getCoordinatesFromGeometry(t.geometry);break;default:i=this.getCoordinatesFromGeometry(t);}if(0==i.length)return e;for(let t=0;t0&&t.e(r,{resourceTiming:i}),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"metadata"}))),this.fire(new t.l("data",Object.assign(Object.assign({},r),{sourceDataType:"content"})));}catch(e){if(this._isUpdatingWorker=!1,this._removed)return void this.fire(new t.l("dataabort",{dataType:"source"}));this.fire(new t.k(e));}finally{(this._pendingWorkerUpdate.data||this._pendingWorkerUpdate.diff)&&this._updateWorkerData();}}))}loaded(){return !this._isUpdatingWorker&&void 0===this._pendingWorkerUpdate.data&&void 0===this._pendingWorkerUpdate.diff}loadTile(e){return t._(this,void 0,void 0,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};e.abortController=new AbortController;const o=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(o,this.map.painter,"RT"===t);}))}abortTile(e){return t._(this,void 0,void 0,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=!0;}))}unloadTile(e){return t._(this,void 0,void 0,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return !1}}class X extends t.E{constructor(e,t,i,o){super(),this.flippedWindingOrder=!1,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(o),this.options=t;}load(e){return t._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new t.l("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield p.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=!0,this.fire(new t.k(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.l("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.a1.fromLngLat);var o;return this.tileID=function(e){const i=t.a2.fromPoints(e),o=i.width(),r=i.height(),a=Math.max(o,r),s=Math.max(0,Math.floor(-Math.log(a)/Math.LN2)),n=Math.pow(2,s);return new t.a4(s,Math.floor((i.minX+i.maxX)/2*n),Math.floor((i.minY+i.maxY)/2*n))}(i),this.terrainTileRanges=this._getOverlappingTileRanges(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((o=this.tileCoords)[1].x-o[0].x)*(o[2].y-o[0].y)-(o[1].y-o[0].y)*(o[2].x-o[0].x)<0,this.fire(new t.l("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new t.T(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t._(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return !1}_getOverlappingTileRanges(e){const{minX:i,minY:o,maxX:r,maxY:a}=t.a2.fromPoints(e),s={};for(let e=0;e<=t.a3;e++){const t=Math.pow(2,e),n=Math.floor(i*t),l=Math.floor(o*t),c=Math.floor(r*t),h=Math.floor(a*t);s[e]={minTileX:n,minTileY:l,maxTileX:c,maxTileY:h};}return s}}class K extends X{constructor(e,t,i,o){super(e,t,i,o),this.roundZoom=!0,this.type="video",this.options=t;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!1;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,"Source").url);try{const e=yield t.a5(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.k(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.k(new t.a6(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.T(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let o=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=!0);}o&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class Y extends X{constructor(e,i,o,r){super(e,i,o,r),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.k(new t.a6(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.k(new t.a6(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.k(new t.a6(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){return t._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.k(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,o=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.T(i,this.canvas,o.RGBA,{premultiply:!0});let r=!1;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=!0);}r&&this.fire(new t.l("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return !0;return !1}}const Q={},J=e=>{switch(e){case "geojson":return H;case "image":return X;case "raster":return q;case "raster-dem":return W;case "vector":return $;case "video":return K;case "canvas":return Y}return Q[e]},ee="RTLPluginLoaded";class te extends t.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=B();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t._(this,arguments,void 0,(function*(e,t=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=s.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.l(ee));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let ie=null;function oe(){return ie||(ie=new te),ie}class re{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=e,this.uid=t.a7(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(e){const t=e+this.timeAdded;tt.getLayer(e))).filter(Boolean);if(0!==e.length){o.layers=e,o.stateDependentLayerIds&&(o.stateDependentLayers=o.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=o;}}return i}(e.buckets,null==i?void 0:i.style),this.hasSymbolBuckets=!1;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9){if(this.hasSymbolBuckets=!0,!o)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a9&&i.hasRTLText){this.hasRTLText=!0,oe().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.a8;}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const i=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new t.T(e,this.imageAtlas.image,i.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new t.T(e,this.glyphAtlasImage,i.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,o,r,a,s,n,l,c,h){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:o,cameraQueryGeometry:r,scale:a,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:s,queryPadding:this.queryPadding*l,getElevation:h},e,t,i):{}}querySourceFeatures(e,i){const o=this.latestFeatureIndex;if(!o||!o.rawTileData)return;const r=o.loadVTLayers(),a=i&&i.sourceLayer?i.sourceLayer:"",s=r._geojsonTileLayer||r[a];if(!s)return;const n=t.aa(null==i?void 0:i.filter,null==i?void 0:i.globalState),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=!1;else if(i)if(this.expirationTime{this.remove(e,r);}),i)),this.data[o].push(r),this.order.push(o),this.order.length>this.max){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}has(e){return e.wrapped().key in this.data}getAndRemove(e){return this.has(e)?this._getAndRemoveByKey(e.wrapped().key):null}_getAndRemoveByKey(e){const t=this.data[e].shift();return t.timeout&&clearTimeout(t.timeout),0===this.data[e].length&&delete this.data[e],this.order.splice(this.order.indexOf(e),1),t.value}getByKey(e){const t=this.data[e];return t?t[0].value:null}get(e){return this.has(e)?this.data[e.wrapped().key][0].value:null}remove(e,t){if(!this.has(e))return this;const i=e.wrapped().key,o=void 0===t?0:this.data[i].indexOf(t),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(e){for(this.max=e;this.order.length>this.max;){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}filter(e){const t=[];for(const i in this.data)for(const o of this.data[i])e(o.value)||t.push(o);for(const e of t)this.remove(e.value.tileID,e);}}class se{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(e,i,o){const r=String(i);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][r]=this.stateChanges[e][r]||{},t.e(this.stateChanges[e][r],o),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==r&&(this.deletedStates[e][t]=null);}else if(this.deletedStates[e]&&null===this.deletedStates[e][r]){this.deletedStates[e][r]={};for(const t in this.state[e][r])o[t]||(this.deletedStates[e][r][t]=null);}else for(const t in o)this.deletedStates[e]&&this.deletedStates[e][r]&&null===this.deletedStates[e][r][t]&&delete this.deletedStates[e][r][t];}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const o=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&void 0!==t)null!==this.deletedStates[e][o]&&(this.deletedStates[e][o]=this.deletedStates[e][o]||{},this.deletedStates[e][o][i]=null);else if(void 0!==t)if(this.stateChanges[e]&&this.stateChanges[e][o])for(i in this.deletedStates[e][o]={},this.stateChanges[e][o])this.deletedStates[e][o][i]=null;else this.deletedStates[e][o]=null;else this.deletedStates[e]=null;}getState(e,i){const o=String(i),r=t.e({},(this.state[e]||{})[o],(this.stateChanges[e]||{})[o]);if(null===this.deletedStates[e])return {};if(this.deletedStates[e]){const t=this.deletedStates[e][i];if(null===t)return {};for(const e in t)delete r[e];}return r}initializeTileState(e,t){e.setFeatureState(this.state,t);}coalesceChanges(e,i){const o={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const i={};for(const o in this.stateChanges[e])this.state[e][o]||(this.state[e][o]={}),t.e(this.state[e][o],this.stateChanges[e][o]),i[o]=this.state[e][o];o[e]=i;}for(const e in this.deletedStates){this.state[e]=this.state[e]||{};const i={};if(null===this.deletedStates[e])for(const t in this.state[e])i[t]={},this.state[e][t]={};else for(const t in this.deletedStates[e]){if(null===this.deletedStates[e][t])this.state[e][t]={};else for(const i of Object.keys(this.deletedStates[e][t]))delete this.state[e][t][i];i[t]=this.state[e][t];}o[e]=o[e]||{},t.e(o[e],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(o).length)for(const t in e)e[t].setFeatureState(o,i);}}const ne=89.25;function le(e,i){const o=t.ah(i.lat,-t.ai,t.ai);return new t.P(t.V(i.lng)*e,t.U(o)*e)}function ce(e,i){return new t.a1(i.x/e,i.y/e).toLngLat()}function he(e){return e.cameraToCenterDistance*Math.min(.85*Math.tan(t.ae(90-e.pitch)),Math.tan(t.ae(ne-e.pitch)))}function ue(e,i){const o=e.canonical,r=i/t.af(o.z),a=o.x+Math.pow(2,o.z)*e.wrap,s=t.ag(new Float64Array(16));return t.M(s,s,[a*r,o.y*r,0]),t.N(s,s,[r/t.$,r/t.$,1]),s}function de(e,i,o,r,a){const s=t.a1.fromLngLat(e,i),n=a*t.aj(1,e.lat),l=n*Math.cos(t.ae(o)),c=Math.sqrt(n*n-l*l),h=c*Math.sin(t.ae(-r)),u=c*Math.cos(t.ae(-r));return new t.a1(s.x+h,s.y+u,s.z+l)}function _e(e,t,i){const o=t.intersectsFrustum(e);if(!i||0===o)return o;const r=t.intersectsPlane(i);return 0===r?0:2===o&&2===r?2:1}function pe(e,t,i){let o=0;const r=(i-t)/10;for(let a=0;a<10;a++)o+=r*Math.pow(Math.cos(t+(a+.5)/10*(i-t)),e);return o}function me(e,i){return function(o,r,a,s,n){const l=2*((e-1)/t.ak(Math.cos(t.ae(ne-n))/Math.cos(t.ae(ne)))-1),c=Math.acos(a/s),h=2*pe(l-1,0,t.ae(n/2)),u=Math.min(t.ae(ne),c+t.ae(n/2)),d=pe(l-1,Math.min(u,c-t.ae(n/2)),u),_=Math.atan(r/a),p=Math.hypot(r,a);let m=o;return m+=t.ak(s/p/Math.max(.5,Math.cos(t.ae(n/2)))),m+=l*t.ak(Math.cos(_))/2,m-=t.ak(Math.max(1,d/h/i))/2,m}}const fe=me(9.314,3);function ge(e,i){const o=(i.roundZoom?Math.round:Math.floor)(e.zoom+t.ak(e.tileSize/i.tileSize));return Math.max(0,o)}function ve(e,i){const o=e.getCameraFrustum(),r=e.getClippingPlane(),a=e.screenPointToMercatorCoordinate(e.getCameraPoint()),s=t.a1.fromLngLat(e.center,e.elevation);a.z=s.z+Math.cos(e.pitchInRadians)*e.cameraToCenterDistance/e.worldSize;const n=e.getCoveringTilesDetailsProvider(),l=n.allowVariableZoom(e,i),c=ge(e,i),h=i.minzoom||0,u=void 0!==i.maxzoom?i.maxzoom:e.maxZoom,d=Math.min(Math.max(0,c),u),_=Math.pow(2,d),p=[_*a.x,_*a.y,0],m=[_*s.x,_*s.y,0],f=Math.hypot(s.x-a.x,s.y-a.y),g=Math.abs(s.z-a.z),v=Math.hypot(f,g),b=e=>({zoom:0,x:0,y:0,wrap:e,fullyVisible:!1}),x=[],y=[];if(e.renderWorldCopies&&n.allowWorldCopies())for(let e=1;e<=3;e++)x.push(b(-e)),x.push(b(e));for(x.push(b(0));x.length>0;){const _=x.pop(),f=_.x,b=_.y;let w=_.fullyVisible;const T={x:f,y:b,z:_.zoom},P=n.getTileBoundingVolume(T,_.wrap,e.elevation,i);if(!w){const e=_e(o,P,r);if(0===e)continue;w=2===e;}const C=n.distanceToTile2d(a.x,a.y,T,P);let I=c;l&&(I=(i.calculateTileZoom||fe)(e.zoom+t.ak(e.tileSize/i.tileSize),C,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const M=Math.min(I,u);if(_.wrap=n.getWrap(s,T,_.wrap),_.zoom>=M){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return y.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}const be=t.a2.fromPoints([new t.P(0,0),new t.P(t.$,t.$)]);class xe extends t.E{constructor(e,t,i){super(),this.id=e,this.dispatcher=i,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=!1;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,o)=>{const r=new(J(t.type))(e,t,i,o);if(r.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${r.id}`);return r})(e,t,i,this),this._tiles={},this._cache=new ae(0,(e=>this._unloadTile(e))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new se,this._didEmitContent=!1,this._updated=!1;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e);}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return !0;if(!this._updated)return !1;for(const e in this._tiles){const t=this._tiles[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}return !0}getSource(){return this._source}pause(){this._paused=!0;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,o){return t._(this,void 0,void 0,(function*(){try{yield this._source.loadTile(e),this._tileLoaded(e,i,o);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.k(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.l("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const t in this._tiles){const i=this._tiles[t];i.upload(e),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(ye).map((e=>e.key))}getRenderableIds(e){const i=[];for(const t in this._tiles)this._isIdRenderable(t,e)&&i.push(this._tiles[t]);return e?i.sort(((e,i)=>{const o=e.tileID,r=i.tileID,a=new t.P(o.canonical.x,o.canonical.y)._rotate(-this.transform.bearingInRadians),s=new t.P(r.canonical.x,r.canonical.y)._rotate(-this.transform.bearingInRadians);return o.overscaledZ-r.overscaledZ||s.y-a.y||s.x-a.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(ye).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return !!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())}reload(e){if(this._paused)this._shouldReloadOnResume=!0;else {this._cache.reset();for(const t in this._tiles)e?this._reloadTile(t,"expired"):"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading");}}_reloadTile(e,i){return t._(this,void 0,void 0,(function*(){const t=this._tiles[e];t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,o){e.timeAdded=s.now(),"expired"===o&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.l("data",{dataType:"source",tile:e,coord:e.tileID}));}_backfillDEM(e){const t=this.getRenderableIds();for(let o=0;o1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,o),e.neighboringTiles&&e.neighboringTiles[a]&&(e.neighboringTiles[a].backfilled=!0)));}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,o){for(const r in this._tiles){let a=this._tiles[r];if(o[r]||!a.hasData()||a.tileID.overscaledZ<=t||a.tileID.overscaledZ>i)continue;let s=a.tileID;for(;a&&a.tileID.overscaledZ>t+1;){const e=a.tileID.scaledTo(a.tileID.overscaledZ-1);a=this._tiles[e.key],a&&a.hasData()&&(s=e);}let n=s;for(;n.overscaledZ>t;)if(n=n.scaledTo(n.overscaledZ-1),e[n.key]||e[n.canonical.key]){o[s.key]=s;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),o=this._getLoadedTile(t);if(o)return o}}findLoadedSibling(e){return this._getLoadedTile(e)}_getLoadedTile(e){const t=this._tiles[e.key];return t&&t.hasData()?t:this._cache.getByKey(e.wrapped().key)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,o=Math.ceil(e.height/this._source.tileSize)+1,r=Math.floor(i*o*(null===this._maxTileCacheZoomLevels?t.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),a="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(a);}handleWrapJump(e){const t=Math.round((e-(void 0===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e={};for(const i in this._tiles){const o=this._tiles[i];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),e[o.tileID.key]=o;}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(e,this._tiles[e]);}}_updateCoveredAndRetainedTiles(e,t,i,o,r,a){const n={},l={},c=Object.keys(e),h=s.now();for(const i of c){const o=e[i],r=this._tiles[i];if(!r||0!==r.fadeEndTime&&r.fadeEndTime<=h)continue;const a=this.findLoadedParent(o,t),s=this.findLoadedSibling(o),c=a||s||null;c&&(this._addTile(c.tileID),n[c.tileID.key]=c.tileID),l[i]=o;}this._retainLoadedChildren(l,o,i,e);for(const t in n)e[t]||(this._coveredTiles[t]=!0,e[t]=n[t]);if(a){const t={},i={};for(const e of r)this._tiles[e.key].hasData()?t[e.key]=e:i[e.key]=e;for(const o in i){const r=i[o].children(this._source.maxzoom);this._tiles[r[0].key]&&this._tiles[r[1].key]&&this._tiles[r[2].key]&&this._tiles[r[3].key]&&(t[r[0].key]=e[r[0].key]=r[0],t[r[1].key]=e[r[1].key]=r[1],t[r[2].key]=e[r[2].key]=r[2],t[r[3].key]=e[r[3].key]=r[3],delete i[o]);}for(const o in i){const r=i[o],a=this.findLoadedParent(r,this._source.minzoom),s=this.findLoadedSibling(r),n=a||s||null;if(n){t[n.tileID.key]=e[n.tileID.key]=n.tileID;for(const e in t)t[e].isChildOf(n.tileID)&&delete t[e];}}for(const e in this._tiles)t[e]||(this._coveredTiles[e]=!0);}}update(e,i){if(!this._sourceLoaded||this._paused)return;let o;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?o=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.Z(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(o=ve(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(o=o.filter((e=>this._source.hasTile(e))))):o=[];const r=ge(e,this._source),a=Math.max(r-xe.maxOverzooming,this._source.minzoom),s=Math.max(r+xe.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const e={};for(const t of o)if(t.canonical.z>this._source.minzoom){const i=t.scaledTo(t.canonical.z-1);e[i.key]=i;const o=t.scaledTo(Math.max(this._source.minzoom,Math.min(t.canonical.z,5)));e[o.key]=o;}o=o.concat(Object.values(e));}const n=0===o.length&&!this._updated&&this._didEmitContent;this._updated=!0,n&&this.fire(new t.l("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(o,r);we(this._source.type)&&this._updateCoveredAndRetainedTiles(l,a,s,r,o,i);for(const e in l)this._tiles[e].clearFadeHold();const c=t.am(this._tiles,l);for(const e of c){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const o={},r={},a=Math.max(t-xe.maxOverzooming,this._source.minzoom),s=Math.max(t+xe.maxUnderzooming,this._source.minzoom),n={};for(const i of e){const e=this._addTile(i);o[i.key]=i,e.hasData()||tthis._source.maxzoom){const e=s.children(this._source.maxzoom)[0],t=this.getTile(e);if(t&&t.hasData()){o[e.key]=e;continue}}else {const e=s.children(this._source.maxzoom);if(4===e.length&&o[e[0].key]&&o[e[1].key]&&o[e[2].key]&&o[e[3].key])continue;if(1===e.length&&o[e[0].key])continue}let n=e.wasRequested();for(let t=s.overscaledZ-1;t>=a;--t){const a=s.scaledTo(t);if(r[a.key])break;if(r[a.key]=!0,e=this.getTile(a),!e&&n&&(e=this._addTile(a)),e){const t=e.hasData();if((t||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||n)&&(o[a.key]=a),n=e.wasRequested(),t)break}}}return o}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,o=this._tiles[e].tileID;for(;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}t.push(o.key);const e=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;o=e;}for(const e of t)this._loadedParentTiles[e]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const e in this._tiles){const t=this._tiles[e].tileID,i=this._getLoadedTile(t);this._loadedSiblingTiles[t.key]=i;}}_addTile(e){let i=this._tiles[e.key];if(i)return i;i=this._cache.getAndRemove(e),i&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));const o=i;return i||(i=new re(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._tiles[e.key]=i,o||this._source.fire(new t.l("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}refreshTiles(e){for(const t in this._tiles)(this._isIdRenderable(t)||"errored"==this._tiles[t].state)&&e.some((e=>e.equals(this._tiles[t].tileID.canonical)))&&this._reloadTile(t,"expired");}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=!0,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){const t=e.sourceDataType;"source"===e.dataType&&"metadata"===t&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===t&&(this.reload(e.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0);}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const e in this._tiles)this._removeTile(e);this._cache.reset();}tilesIn(e,i,o){const r=[],a=this.transform;if(!a)return r;const s=a.getCoveringTilesDetailsProvider().allowWorldCopies(),n=o?a.getCameraQueryGeometry(e):e,l=e=>a.screenPointToMercatorCoordinate(e,this.terrain),c=this.transformBbox(e,l,!s),h=this.transformBbox(n,l,!s),u=this.getIds(),d=t.a2.fromPoints(h);for(let e=0;ee.getTilePoint(new t.a1(i.x,i.y))));if(i.expandBy(_),i.intersects(be)){const t=c.map((t=>e.getTilePoint(t))),i=h.map((t=>e.getTilePoint(t)));r.push({tile:o,tileID:s?e:e.unwrapTo(0),queryGeometry:t,cameraQueryGeometry:i,scale:l});}}}return r}transformBbox(e,i,o){let r=e.map(i);if(o){const o=t.a2.fromPoints(e);o.shrinkBy(.001*Math.min(o.width(),o.height()));const a=o.map(i);t.a2.fromPoints(r).covers(a)||(r=r.map((e=>e.x>.5?new t.a1(e.x-1,e.y,e.z):e)));}return r}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._tiles[e].tileID));return this.transform&&this.transform.populateCache(t),t}hasTransition(){if(this._source.hasTransition())return !0;if(we(this._source.type)){const e=s.now();for(const t in this._tiles)if(this._tiles[t].fadeEndTime>=e)return !0}return !1}setFeatureState(e,t,i){this._state.updateState(e=e||"_geojsonTileLayer",t,i);}removeFeatureState(e,t,i){this._state.removeFeatureState(e=e||"_geojsonTileLayer",t,i);}getFeatureState(e,t){return this._state.getState(e=e||"_geojsonTileLayer",t)}setDependencies(e,t,i){const o=this._tiles[e];o&&o.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)));}}function ye(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),o=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||o-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function we(e){return "raster"===e||"image"===e||"video"===e}xe.maxOverzooming=10,xe.maxUnderzooming=3;class Te{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(r-s)/n:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))}}function Pe(e,t){let i=!0;return "always"===e||"never"!==e&&"never"!==t||(i=!1),i}class Ce{constructor(e,t,i){const o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||o<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=o){if(r)return [{key:null,x1:e,y1:t,x2:i,y2:o}];for(let e=0;e0}hitTestCircle(e,t,i,o,r){const a=e-i,s=e+i,n=t-i,l=t+i;if(s<0||a>this.width||l<0||n>this.height)return !1;const c=[];return this._forEachCell(a,n,s,l,this._queryCellCircle,c,{hitTest:!0,overlapMode:o,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},r),c.length>0}_queryCell(e,t,i,o,r,a,s,n){const{seenUids:l,hitTest:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const r=this.bboxes;for(const s of u)if(!l.box[s]){l.box[s]=!0;const u=4*s,d=this.boxKeys[s];if(e<=r[u+2]&&t<=r[u+3]&&i>=r[u+0]&&o>=r[u+1]&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))&&(a.push({key:d,x1:r[u],y1:r[u+1],x2:r[u+2],y2:r[u+3]}),c))return !0}}const d=this.circleCells[r];if(null!==d){const r=this.circles;for(const s of d)if(!l.circle[s]){l.circle[s]=!0;const u=3*s,d=this.circleKeys[s];if(this._circleAndRectCollide(r[u],r[u+1],r[u+2],e,t,i,o)&&(!n||n(d))&&(!c||!Pe(h,d.overlapMode))){const e=r[u],t=r[u+1],i=r[u+2];if(a.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return !0}}}return !1}_queryCellCircle(e,t,i,o,r,a,s,n){const{circle:l,seenUids:c,overlapMode:h}=s,u=this.boxCells[r];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=!0;const i=4*t,o=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}const d=this.circleCells[r];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=!0;const i=3*t,o=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(o))&&!Pe(h,o.overlapMode))return a.push(!0),!0}}}_forEachCell(e,t,i,o,r,a,s,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(o);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(r.call(this,e,t,i,o,this.xCellCount*l+d,a,s,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,o,r,a){const s=o-e,n=r-t,l=i+a;return l*l>s*s+n*n}_circleAndRectCollide(e,t,i,o,r,a,s){const n=(a-o)/2,l=Math.abs(e-(o+n));if(l>n+i)return !1;const c=(s-r)/2,h=Math.abs(t-(r+c));if(h>c+i)return !1;if(l<=n||h<=c)return !0;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function Ie(e,i,r){const a=t.L();if(!e){const{vecSouth:e,vecEast:t}=Se(i),r=o();r[0]=t[0],r[1]=t[1],r[2]=e[0],r[3]=e[1],s=r,(d=(l=(n=r)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(s[0]=u*(d=1/d),s[1]=-c*d,s[2]=-h*d,s[3]=l*d),a[0]=r[0],a[1]=r[1],a[4]=r[2],a[5]=r[3];}var s,n,l,c,h,u,d;return t.N(a,a,[1/r,1/r,1]),a}function Me(e,i,o,r){if(e){const e=t.L();if(!i){const{vecSouth:t,vecEast:i}=Se(o);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.N(e,e,[r,r,1]),e}return o.pixelsToClipSpaceMatrix}function Se(e){const i=Math.cos(e.rollInRadians),o=Math.sin(e.rollInRadians),r=Math.cos(e.pitchInRadians),a=Math.cos(e.bearingInRadians),s=Math.sin(e.bearingInRadians),n=t.ar();n[0]=-a*r*o-s*i,n[1]=-s*r*o+a*i;const l=t.as(n);l<1e-9?t.at(n):t.au(n,n,1/l);const c=t.ar();c[0]=a*r*i-s*o,c[1]=s*r*i+a*o;const h=t.as(c);return h<1e-9?t.at(c):t.au(c,c,1/h),{vecEast:c,vecSouth:n}}function Ee(e,i,o,r){let a;r?(a=[e,i,r(e,i),1],t.aw(a,a,o)):(a=[e,i,0,1],qe(a,a,o));const s=a[3];return {point:new t.P(a[0]/s,a[1]/s),signedDistanceFromCamera:s,isOccluded:!1}}function Re(e,t){return .5+e/t*.5}function ze(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function De(e,i,o,r,a,s,n,l,c,h,u,d,_){const p=o?e.textSizeData:e.iconSizeData,m=t.an(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=o?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,b=o?e.text.placedSymbolArray:e.icon.placedSymbolArray,x=i.transform.width/i.transform.height;let y=!1;for(let o=0;oMath.abs(o.x-i.x)*r?{useVertical:!0}:(e===t.ao.vertical?i.yo.x)?{needsFlipping:!0}:null}function ke(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:o,symbol:r,fontSize:a,flip:s,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=a/24,_=r.lineOffsetX*d,p=r.lineOffsetY*d;let m;if(r.numGlyphs>1){const e=r.glyphStartIndex+r.numGlyphs,t=r.lineStartIndex,a=r.lineStartIndex+r.lineLength,c=Ae(d,l,_,p,s,r,u,i);if(!c)return {notEnoughRoom:!0};const f=je(c.first.point.x,c.first.point.y,i,o),g=je(c.last.point.x,c.last.point.y,i,o);if(n&&!s){const e=Le(r.writingMode,f,g,h);if(e)return e}m=[c.first];for(let o=r.glyphStartIndex+1;o0?n.point:Fe(i.tileAnchorPoint,s,e,1,i),c=je(e.x,e.y,i,o),u=je(l.x,l.y,i,o),d=Le(r.writingMode,c,u,h);if(d)return d}const e=Ge(d*l.getoffsetX(r.glyphStartIndex),_,p,s,r.segment,r.lineStartIndex,r.lineStartIndex+r.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:!0};m=[e];}for(const e of m)t.av(c,e.point,e.angle);return {}}function Fe(e,t,i,o,r){const a=e.add(e.sub(t)._unit()),s=Oe(a.x,a.y,r).point,n=i.sub(s);return i.add(n._mult(o/n.mag()))}function Be(e,i,o){const r=i.projectionCache;if(r.projections[e])return r.projections[e];const a=new t.P(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),s=Oe(a.x,a.y,i);if(s.signedDistanceFromCamera>0)return r.projections[e]=s.point,r.anyProjectionOccluded=r.anyProjectionOccluded||s.isOccluded,s.point;const n=e-o.direction;return Fe(0===o.distanceFromAnchor?i.tileAnchorPoint:new t.P(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),a,o.previousVertex,o.absOffsetX-o.distanceFromAnchor+1,i)}function Oe(e,t,i){const o=e+i.translation[0],r=t+i.translation[1];let a;return i.pitchWithMap?(a=Ee(o,r,i.pitchedLabelPlaneMatrix,i.getElevation),a.isOccluded=!1):(a=i.transform.projectTileCoordinates(o,r,i.unwrappedTileID,i.getElevation),a.point.x=(.5*a.point.x+.5)*i.width,a.point.y=(.5*-a.point.y+.5)*i.height),a}function je(e,i,o,r){if(o.pitchWithMap){const a=[e,i,0,1];return t.aw(a,a,r),o.transform.projectTileCoordinates(a[0]/a[3],a[1]/a[3],o.unwrappedTileID,o.getElevation).point}return {x:e/o.width*2-1,y:1-i/o.height*2}}function Ne(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function Ue(e,t,i){return e._unit()._perp()._mult(t*i)}function Ze(e,i,o,r,a,s,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=o.add(i);if(e+c.direction=a)return l.projectionCache.offsets[e]=h,h;const u=Be(e+c.direction,l,c),d=Ue(u.sub(o),n,c.direction),_=o.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.ax(s,h,_,p)||h,l.projectionCache.offsets[e]}function Ge(e,t,i,o,r,a,s,n,l){const c=o?e-t:e+t;let h=c>0?1:-1,u=0;o&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?a+r:a+r+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Oe(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,b=0;const x=Math.abs(c),y=[];let w;for(;v+b<=x;){if(_+=h,_=s)return null;v+=b,g=f,m=p;const e={absOffsetX:x,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=Be(_,n,e),0===i)y.push(g),w=f.sub(g);else {let t;const o=f.sub(g);t=0===o.mag()?Ue(Be(_+h,n,e).sub(f),i,h):Ue(o,i,h),m||(m=g.add(t)),p=Ze(_,t,f,a,s,m,i,n,e),y.push(m),w=p.sub(m);}b=w.mag();}const T=w._mult((x-v)/b)._add(m||g),P=u+Math.atan2(f.y-g.y,f.x-g.x);return y.push(T),{point:T,angle:l?P:0,path:y}}const Ve=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function $e(e,t){for(let i=0;i=1;e--)_.push(s.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=o.x&&i.x<=r.x&&e.y>=o.y&&i.y<=r.y?[_]:i.xr.x||i.yr.y?[]:t.ay([_],o.x,o.y,r.x,r.y);}for(const t of f){a.reset(t,.25*i);let o=0;o=a.length<=.5*i?1:Math.ceil(a.paddedLength/p)+1;for(let t=0;t{const t=Ee(e.x,e.y,o,i.getElevation),r=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return r.point.x=(.5*r.point.x+.5)*i.width,r.point.y=(.5*-r.point.y+.5)*i.height,r}))}(e,i);return function(e){let t=0,i=0,o=0,r=0;for(let a=0;ai&&(i=r,t=o));return e.slice(t,t+i)}(o)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[],o=new t.a2;for(const r of e){const e=new t.P(r.x+We,r.y+We);o.extend(e),i.push(e);}const{minX:r,minY:a,maxX:s,maxY:n}=o,l=this.grid.query(r,a,s,n).concat(this.ignoredGrid.query(r,a,s,n)),c={},h={};for(const e of l){const o=e.key;if(void 0===c[o.bucketInstanceId]&&(c[o.bucketInstanceId]={}),c[o.bucketInstanceId][o.featureIndex])continue;const r=[new t.P(e.x1,e.y1),new t.P(e.x2,e.y1),new t.P(e.x2,e.y2),new t.P(e.x1,e.y2)];t.az(i,r)&&(c[o.bucketInstanceId][o.featureIndex]=!0,void 0===h[o.bucketInstanceId]&&(h[o.bucketInstanceId]=[]),h[o.bucketInstanceId].push(o.featureIndex));}return h}insertCollisionBox(e,t,i,o,r,a){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,o,r,a){const s=i?this.ignoredGrid:this.grid,n={bucketInstanceId:o,featureIndex:r,collisionGroupID:a,overlapMode:t};for(let t=0;t=this.screenRightBoundary||othis.screenBottomBoundary}isInsideGrid(e,t,i,o){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,r,c,u)));E=e.some((e=>!e.isOccluded)),S=e.map((e=>new t.P(e.x,e.y)));}else E=!0;return {box:t.aA(S),allPointsOccluded:!E}}}class Xe{constructor(e,t,i,o){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):o&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class Ke{constructor(e,t,i,o,r){this.text=new Xe(e?e.text:null,t,i,r),this.icon=new Xe(e?e.icon:null,t,o,r);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ye{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class Qe{constructor(e,t,i,o,r){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=r;}}class Je{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function et(e,i,o,r,a){const{horizontalAlign:s,verticalAlign:n}=t.aH(e);return new t.P(-(s-.5)*i+r[0]*a,-(n-.5)*o+r[1]*a)}class tt{constructor(e,t,i,o,r){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new He(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new Je(o),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=r,r&&(r.prevPlacement=void 0),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,o)=>t.getElevation(e,i,o):null}getBucketParts(e,i,o,r){const a=o.getBucket(i),s=o.latestFeatureIndex;if(!a||!s||i.id!==a.layerIds[0])return;const n=o.collisionBoxArray,l=a.layers[0].layout,c=a.layers[0].paint,h=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),u=o.tileSize/t.$,d=o.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.aC(o,1,this.transform.zoom),m=t.aD(this.collisionIndex.transform,o,c.get("text-translate"),c.get("text-translate-anchor")),f=t.aD(this.collisionIndex.transform,o,c.get("icon-translate"),c.get("icon-translate-anchor")),g=Ie(_,this.transform,p);this.retainedQueryData[a.bucketInstanceId]=new Qe(a.bucketInstanceId,s,a.sourceLayerIndex,a.index,o.tileID);const v={bucket:a,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:o.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.an(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(r)for(const t of a.sortKeyRanges){const{sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r}=t;e.push({sortKey:i,symbolInstanceStart:o,symbolInstanceEnd:r,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v,b,x){const y=t.aE[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=et(y,o,r,w,a),P=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,s,f,u.predicate,b,T,x);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,s,g,u.predicate,b,T,x).placeable)&&P.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:o,height:r,anchor:y,textBoxScale:a,prevAnchor:e},this.markUsedJustification(p,y,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:P}}}placeLayerBucketPart(e,i,o){const{bucket:r,layout:a,translationText:s,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=a.get("text-optional"),f=a.get("icon-optional"),g=t.aF(a,"text-overlap","text-allow-overlap"),v="always"===g,b=t.aF(a,"icon-overlap","icon-allow-overlap"),x="always"===b,y="map"===a.get("text-rotation-alignment"),w="map"===a.get("text-pitch-alignment"),T="none"!==a.get("icon-text-fit"),P="viewport-y"===a.get("symbol-z-order"),C=v&&(x||!r.hasIconData()||f),I=x&&(v||!r.hasTextData()||m);!r.collisionArrays&&d&&r.deserializeCollisionBoxes(d);const M=this.retainedQueryData[r.bucketInstanceId].tileID,S=this._getTerrainElevationFunc(M),E=this.transform.getFastPathSimpleProjectionMatrix(M),R=(e,d,x)=>{var P,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new Ye(!1,!1,!1));let z=!1,D=!1,A=!0,L=null,k={box:null,placeable:!1,offscreen:null,occluded:!1},F={placeable:!1},B=null,O=null,j=null,N=0,U=0,Z=0;d.textFeatureIndex?N=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(N=e.featureIndex),d.verticalTextFeatureIndex&&(U=d.verticalTextFeatureIndex);const G=d.textBox;if(G){const i=i=>{let o=t.ao.horizontal;if(r.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,o=t,this.markUsedOrientation(r,o,e));}return o},a=(i,o)=>{if(r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of r.writingModes)if(e===t.ao.vertical?(k=o(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const o=(t,i)=>{const o=this.collisionIndex.placeCollisionBox(t,g,h,M,l,w,y,s,p.predicate,S,void 0,E);return o&&o.placeable&&(this.markUsedOrientation(r,i,e),this.placedOrientations[e.crossTileID]=i),o};a((()=>o(G,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?o(i,t.ao.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.aE[null===(R=null===(P=this.prevPlacement)||void 0===P?void 0:P.variableOffsets[e.crossTileID])||void 0===R?void 0:R.anchor];const m=(t,i,a)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===b?i:null;let x=null,P="never"===g?1:2,C="never";_&&P++;for(let i=0;im(G,d.iconBox,t.ao.horizontal)),(()=>{const i=d.verticalTextBox;return r.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.ao.vertical):{box:null,occluded:!0,offscreen:null}})),k&&(z=k.placeable,A=k.offscreen);const f=i(k&&k.placeable);if(!z&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(r,t.anchor,e,f));}}}if(B=k,z=B&&B.placeable,A=B&&B.offscreen,e.useRuntimeCollisionCircles){const i=r.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.ap(r.textSizeData,_,i),h=a.get("text-padding");O=this.collisionIndex.placeCollisionCircles(g,i,r.lineVertexArray,r.glyphOffsetArray,n,l,c,o,w,p.predicate,e.collisionCircleDiameter,h,s,S),O.circles.length&&O.collisionDetected&&!o&&t.w("Collisions detected, but collision boxes are not shown"),z=v||O.circles.length>0&&!O.collisionDetected,A=A&&O.offscreen;}if(d.iconFeatureIndex&&(Z=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,b,h,M,l,w,y,n,p.predicate,S,T&&L?L:void 0,E);F&&F.placeable&&d.verticalIconBox?(j=e(d.verticalIconBox),D=j.placeable):(j=e(d.iconBox),D=j.placeable),A=A&&j.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,$=f||0===e.numIconVertices;V||$?$?V||(D=D&&z):z=D&&z:D=z=D&&z;const q=D&&j.placeable;if(z&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,a.get("text-ignore-placement"),r.bucketInstanceId,F&&F.placeable&&U?U:N,p.ID),q&&this.collisionIndex.insertCollisionBox(j.box,b,a.get("icon-ignore-placement"),r.bucketInstanceId,Z,p.ID),O&&z&&this.collisionIndex.insertCollisionCircles(O.circles,g,a.get("text-ignore-placement"),r.bucketInstanceId,N,p.ID),o&&this.storeCollisionData(r.bucketInstanceId,x,d,B,j,O),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===r.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new Ye((z||C)&&!(null==B?void 0:B.occluded),(D||I)&&!(null==j?void 0:j.occluded),A||r.justReloaded),i[e.crossTileID]=!0;};if(P){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=r.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(r.symbolInstances.get(i),r.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=a>=0&&t!==a?0:o.crossTileID);}markUsedOrientation(e,i,o){const r=i===t.ao.horizontal||i===t.ao.horizontalOnly?i:0,a=i===t.ao.vertical?i:0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];for(const t of s)e.text.placedSymbolArray.get(t).placedOrientation=r;o.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).placedOrientation=a);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=!1;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const o=t?t.symbolFadeChange(e):1,r=t?t.opacities:{},a=t?t.variableOffsets:{},s=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],a=r[e];a?(this.opacities[e]=new Ke(a,o,t.text,t.icon),i=i||t.text!==a.text.placed||t.icon!==a.icon.placed):(this.opacities[e]=new Ke(null,o,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in r){const t=r[e];if(!this.opacities[e]){const r=new Ke(t,o,!1,!1);r.isHidden()||(this.opacities[e]=r,i=i||t.text.placed||t.icon.placed);}}for(const e in a)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=a[e]);for(const e in s)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=s[e]);if(t&&void 0===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const o of t){const t=o.getBucket(e);t&&o.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,o.tileID,i,o.collisionBoxArray);}}updateBucketOpacities(e,i,o,r){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=!1),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=!1),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const a=e.layers[0],s=a.layout,n=new Ke(null,0,!1,!1,!0),l=s.get("text-allow-overlap"),c=s.get("icon-allow-overlap"),h=a._unevaluatedLayout.hasValue("text-variable-anchor")||a._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===s.get("text-rotation-alignment"),d="map"===s.get("text-pitch-alignment"),_="none"!==s.get("icon-text-fit"),p=new Ke(null,0,l&&(c||!e.hasIconData()||s.get("icon-optional")),c&&(l||!e.hasTextData()||s.get("text-optional")),!0);!e.collisionArrays&&r&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(r);const m=(e,t,i)=>{for(let o=0;o0,v=this.placedOrientations[r.crossTileID],b=v===t.ao.vertical,x=v===t.ao.horizontal||v===t.ao.horizontalOnly;if(a>0||s>0){const t=ht(c.text);m(e.text,a,b?ut:t),m(e.text,s,x?ut:t);const i=c.text.isHidden();[r.rightJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||b?1:0);})),r.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).hidden=i||x?1:0);const o=this.variableOffsets[r.crossTileID];o&&this.markUsedJustification(e,o.anchor,r,v);const n=this.placedOrientations[r.crossTileID];n&&(this.markUsedJustification(e,"left",r,n),this.markUsedOrientation(e,n,r));}if(g){const t=ht(c.icon),i=!(_&&r.verticalPlacedIconSymbolIndex&&b);r.placedIconSymbolIndex>=0&&(m(e.icon,r.numIconVertices,i?t:ut),e.icon.placedSymbolArray.get(r.placedIconSymbolIndex).hidden=c.icon.isHidden()),r.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,r.numVerticalIconVertices,i?ut:t),e.icon.placedSymbolArray.get(r.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const y=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const o=e.collisionArrays[i];if(o){let i=new t.P(0,0);if(o.textBox||o.verticalTextBox){let t=!0;if(h){const e=this.variableOffsets[l];e?(i=et(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=!1;}if(o.textBox||o.verticalTextBox){let r;o.textBox&&(r=b),o.verticalTextBox&&(r=x),it(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||r,y.text,i.x,i.y);}}if(o.iconBox||o.verticalIconBox){const t=Boolean(!x&&o.verticalIconBox);let r;o.iconBox&&(r=t),o.verticalIconBox&&(r=!t),it(e.iconCollisionBox.collisionVertexArray,c.icon.placed,r,y.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=!0;}}function it(e,t,i,o,r,a){o&&0!==o.length||(o=[0,0,0,0]);const s=o[0]-We,n=o[1]-We,l=o[2]-We,c=o[3]-We;e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,n),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,l,c),e.emplaceBack(t?1:0,i?1:0,r||0,a||0,s,c);}const ot=Math.pow(2,25),rt=Math.pow(2,24),at=Math.pow(2,17),st=Math.pow(2,16),nt=Math.pow(2,9),lt=Math.pow(2,8),ct=Math.pow(2,1);function ht(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*ot+t*rt+i*at+t*st+i*nt+t*lt+i*ct+t}const ut=0;class dt{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,o,r){const a=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&s.now()-o>2;for(;this._currentPlacementIndex>=0;){const o=t[e[this._currentPlacementIndex]],a=this.placement.collisionIndex.transform.zoom;if("symbol"===o.type&&(!o.minzoom||o.minzoom<=a)&&(!o.maxzoom||o.maxzoom>a)){if(this._inProgressLayer||(this._inProgressLayer=new dt(o)),this._inProgressLayer.continuePlacement(i[o.source],this.placement,this._showCollisionBoxes,o,r))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(e){return this.placement.commit(e),this.placement}}const pt=512/t.$/2;class mt{constructor(e,i,o){this.tileID=e,this.bucketInstanceId=o,this._symbolsByKey={};const r=new Map;for(let e=0;e({x:Math.floor(e.anchorX*pt),y:Math.floor(e.anchorY*pt)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(o.positions.length>128){const e=new t.aI(o.positions.length,16,Uint16Array);for(const{x:t,y:i}of o.positions)e.add(t,i);e.finish(),delete o.positions,o.index=e;}this._symbolsByKey[e]=o;}}getScaledCoordinates(e,i){const{x:o,y:r,z:a}=this.tileID.canonical,{x:s,y:n,z:l}=i.canonical,c=pt/Math.pow(2,l-a),h=(n*t.$+e.anchorY)*c,u=r*t.$*pt;return {x:Math.floor((s*t.$+e.anchorX)*c-o*t.$*pt),y:Math.floor(h-u)}}findMatches(e,t,i){const o=this.tileID.canonical.ze))}}class ft{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class gt{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],o={};for(const e in i){const r=i[e];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+t),o[r.tileID.key]=r;}this.indexes[e]=o;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in r){const a=r[i];a.tileID.isChildOf(e)&&a.findMatches(t.symbolInstances,e,o);}else {const a=r[e.scaledTo(Number(i)).key];a&&a.findMatches(t.symbolInstances,e,o);}}for(let e=0;e{t[e]=!0;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var bt="void main() {fragColor=vec4(1.0);}";const xt={prelude:yt("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:yt("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:yt("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:yt("uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:yt("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:yt("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:yt(bt,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:yt("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:yt("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:yt("in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:yt("in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),colorRelief:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform int u_color_ramp_size;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {float x=(float(stop)+0.5)/float(u_color_ramp_size);vec4 data=texture(u_elevation_stops,vec2(x,0))*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int r=(u_color_ramp_size-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else\n{l=m;el_l=el_m;}}float x=(float(l)+(el-el_l)/(el_r-el_l)+0.5)/float(u_color_ramp_size);fragColor=u_opacity*texture(u_color_stops,vec2(x,0));\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_dimension;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),debug:yt("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}","in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:yt(bt,"in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:yt("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:yt("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:yt("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:yt("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:yt("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {vec2 epsilon=1.0/u_dimension;float tileSize=u_dimension.x-2.0;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))*tileSize/pow(2.0,exaggeration+(28.2562-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+0.5,deriv.y/8.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:yt("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];\n#define PI 3.141592653589793\n#define STANDARD 0\n#define COMBINED 1\n#define IGOR 2\n#define MULTIDIRECTIONAL 3\n#define BASIC 4\nfloat get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);}void igor_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float aspect=get_aspect(deriv);float azimuth=u_azimuths[0]+PI;float slope_stength=atan(length(deriv))*2.0/PI;float aspect_strength=1.0-abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);float shadow_strength=slope_stength*aspect_strength;float highlight_strength=slope_stength*(1.0-aspect_strength);fragColor=u_shadows[0]*shadow_strength+u_highlights[0]*highlight_strength;}void standard_hillshade(vec2 deriv){float azimuth=u_azimuths[0]+PI;float slope=atan(0.625*length(deriv));float aspect=get_aspect(deriv);float intensity=u_exaggeration;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadows[0],u_highlights[0],shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;}void basic_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor=u_highlights[0]*(2.0*shade-1.0);}else\n{fragColor=u_shadows[0]*(1.0-2.0*shade);}}void multidirectional_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;fragColor=vec4(0,0,0,0);for(int i=0; i < NUM_ILLUMINATION_SOURCES; i++){float cos_alt=cos(u_altitudes[i]);float sin_alt=sin(u_altitudes[i]);float cos_az=-cos(u_azimuths[i]);float sin_az=-sin(u_azimuths[i]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor+=u_highlights[i]*(2.0*shade-1.0)/float(NUM_ILLUMINATION_SOURCES);}else\n{fragColor+=u_shadows[i]*(1.0-2.0*shade)/float(NUM_ILLUMINATION_SOURCES);}}}void combined_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=acos((sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv)));cang=clamp(cang,0.0,PI/2.0);float shade=cang*atan(length(deriv))*4.0/PI/PI;float highlight=(PI/2.0-cang)*atan(length(deriv))*4.0/PI/PI;fragColor=u_shadows[0]*shade+u_highlights[0]*highlight;}void main() {vec4 pixel=texture(u_image,v_pos);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));vec2 deriv=((pixel.rg*8.0)-4.0)/scaleFactor;if (u_method==BASIC) {basic_hillshade(deriv);} else if (u_method==COMBINED) {combined_hillshade(deriv);} else if (u_method==IGOR) {igor_hillshade(deriv);} else if (u_method==MULTIDIRECTIONAL) {multidirectional_hillshade(deriv);} else if (u_method==STANDARD) {standard_hillshade(deriv);} else {standard_hillshade(deriv);}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:yt("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:yt("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:yt("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:yt("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0);vec4 color1=texture(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:yt("uniform sampler2D u_texture;in vec2 v_tex;in float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;fragColor=texture(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_tex;out float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:yt("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:yt("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;fragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:yt("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}","in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:yt("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}","in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:yt("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:yt("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:yt("in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}","in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:yt("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function yt(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o=t.match(/in ([\w]+) ([\w]+)/g),r=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=a?a.concat(r):r,n={};return {fragmentSource:e=e.replace(i,((e,t,i,o,r)=>(n[r]=!0,"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nin ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = u_${r};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,o,r)=>{const a="float"===o?"vec2":"vec4",s=r.match(/color/)?"color":a;return n[r]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\nout ${i} ${o} ${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${r}\nuniform lowp float u_${r}_t;\nin ${i} ${a} a_${r};\n#else\nuniform ${i} ${o} u_${r};\n#endif\n`:"vec4"===s?`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = a_${r};\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${r}\n ${i} ${o} ${r} = unpack_mix_${s}(a_${r}, u_${r}_t);\n#else\n ${i} ${o} ${r} = u_${r};\n#endif\n`})),staticAttributes:o,staticUniforms:s}}class wt{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var Tt=t.aJ([{name:"a_pos",type:"Int16",components:2}]);const Pt="#define PROJECTION_MERCATOR",Ct="mercator";class It{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return !1}get shaderVariantName(){return Ct}get shaderDefine(){return Pt}get shaderPreludeCode(){return xt.projectionMercator}get vertexShaderPreludeCode(){return xt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.aK.noSubdivision}get useGlobeControls(){return !1}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(e){}getMeshFromTileID(e,i,o,r,a){if(this._cachedMesh)return this._cachedMesh;const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(t.$,0),s.emplaceBack(0,t.$),s.emplaceBack(t.$,t.$);const n=e.createVertexBuffer(s,Tt.members),l=t.aM.simpleSegment(0,0,4,2),c=new t.aN;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new wt(n,h,l),this._cachedMesh}recalculate(){}hasTransition(){return !1}setErrorQueryLatitudeDegrees(e){}}class Mt{constructor(e=0,t=0,i=0,o=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=o;}interpolate(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.C.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.C.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.C.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.C.number(e.right,i.right,o)),this}getCenter(e,i){const o=t.ah((this.left+e-this.right)/2,0,e),r=t.ah((this.top+i-this.bottom)/2,0,i);return new t.P(o,r)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new Mt(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function St(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function Et(e){return Math.max(0,Math.floor(e))}class Rt{constructor(e,i,o,r,a,s){this._callbacks=e,this._tileSize=512,this._renderWorldCopies=void 0===s||!!s,this._minZoom=i||0,this._maxZoom=o||22,this._minPitch=null==r?0:r,this._maxPitch=null==a?60:a,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.S(0,0),this._elevation=0,this._zoom=0,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new Mt,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=!0;}apply(e,i,o){this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=Et(this._zoom),this._scale=t.af(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new Mt(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,this._cameraToCenterDistance=e.cameraToCenterDistance,this._nearZ=e.nearZ,this._farZ=e.farZ,this._autoCalculateNearFarZ=!o&&e.autoCalculateNearFarZ,i&&this._constrain(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){void 0===e?e=!0:null===e&&(e=!1),this._renderWorldCopies=e;}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const i=t.aO(e,-180,180)*Math.PI/180;var r,a,s,n,l,c,h,u,d;this._bearingInRadians!==i&&(this._unmodified=!1,this._bearingInRadians=i,this._calcMatrices(),this._rotationMatrix=o(),r=this._rotationMatrix,s=-this._bearingInRadians,n=(a=this._rotationMatrix)[0],l=a[1],c=a[2],h=a[3],u=Math.sin(s),d=Math.cos(s),r[0]=n*d+c*u,r[1]=l*d+h*u,r[2]=n*-u+c*d,r[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.ah(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=!1,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=!1,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.aP(this._fovInRadians)}setFov(e){e=t.ah(e,.1,150),this.fov!==e&&(this._unmodified=!1,this._fovInRadians=t.ae(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const i=this.getConstrained(this._center,e).zoom;this._zoom!==i&&(this._unmodified=!1,this._zoom=i,this._tileZoom=Math.max(0,Math.floor(i)),this._scale=t.af(i),this._constrain(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=!1,this._center=e,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(e,t){this._autoCalculateNearFarZ=!1,this._nearZ=e,this._farZ=t,this._calcMatrices();}clearNearFarZOverride(){this._autoCalculateNearFarZ=!0,this._calcMatrices();}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=!1,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices();}resize(e,t,i=!0){this._width=e,this._height=t,i&&this._constrain(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new G([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-t.ai,t.ai]);}getConstrained(e,t){return this._callbacks.getConstrained(e,t)}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{const{minX:o,minY:r,maxX:a,maxY:s}=t.a2.fromPoints(i).extend(e);return [new t.P(o,r),new t.P(a,r),new t.P(a,s),new t.P(o,s),new t.P(o,r)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const e=this._unmodified,{center:t,zoom:i}=this.getConstrained(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=!1;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.ag(new Float64Array(16));t.N(e,e,[this._width/2,-this._height/2,1]),t.M(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.ag(new Float64Array(16)),t.N(e,e,[1,-1,1]),t.M(e,e,[-1,-1,0]),t.N(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height;}this._callbacks.calcMatrices();}calculateCenterFromCameraLngLatAlt(e,i,o,r){const a=void 0!==o?o:this.bearing,s=r=void 0!==r?r:this.pitch,n=t.a1.fromLngLat(e,i),l=-Math.cos(t.ae(s)),c=Math.sin(t.ae(s)),h=c*Math.sin(t.ae(a)),u=-c*Math.cos(t.ae(a));let d=this.elevation;const _=i-d;let p;l*_>=0||Math.abs(l)<.1?(p=1e4,d=i+p*l):p=-_/l;let m,f,g=t.aQ(1,n.y),v=0;do{if(v+=1,v>10)break;f=p/g,m=new t.a1(n.x+h*f,n.y+u*f),g=1/m.meterInMercatorCoordinateUnits();}while(Math.abs(p-f*g)>1e-12);return {center:m.toLngLat(),elevation:d,zoom:t.ak(this.height/2/Math.tan(this.fovInRadians/2)/f/this.tileSize)}}recalculateZoomAndCenter(e){if(this.elevation-e==0)return;const i=t.aj(1,this.center.lat)*this.worldSize,o=this.cameraToCenterDistance/i,r=t.a1.fromLngLat(this.center,this.elevation),a=de(this.center,this.elevation,this.pitch,this.bearing,o);this._elevation=e;const s=this.calculateCenterFromCameraLngLatAlt(a.toLngLat(),t.aQ(a.z,r.y),this.bearing,this.pitch);this._elevation=s.elevation,this._center=s.center,this.setZoom(s.zoom);}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.P(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/e).toLngLat()}getMercatorTileCoordinates(e){if(!e)return [0,0,1,1];const i=e.canonical.z>=0?1<this.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[o]*this.min[o],i+=e[o]*this.max[o]):(i+=e[o]*this.min[o],t+=e[o]*this.max[o]);return t>=0?2:i<0?0:1}}class Dt{distanceToTile2d(e,t,i,o){const r=o.distanceX([e,t]),a=o.distanceY([e,t]);return Math.hypot(r,a)}getWrap(e,t,i){return i}getTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}const c=1<r}allowWorldCopies(){return !0}prepareNextFrame(){}}class At{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,o=0,r,a){const s=a?[[6,5,4],[0,1,2],[0,3,7],[2,1,5],[3,2,6],[0,4,5]]:[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]],n=Math.pow(2,o),l=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((o=>function(e,i,o,r){const a=t.aw([],e,i),s=1/a[3]/o*r;return t.aY(a,a,[s,s,1/a[3],s])}(o,e,i,n)));r&&function(e,i,o,r){const a=r?4:0,s=r?0:4;let n=0;const l=[],c=[];for(let i=0;i<4;i++){const o=t.aU([],e[i+s],e[i+a]),r=t.aZ(o);t.aR(o,o,1/r),l.push(r),c.push(o);}for(let i=0;i<4;i++){const r=t.a_(e[i+a],c[i],o);n=null!==r&&r>=0?Math.max(n,r):Math.max(n,l[i]);}const h=function(e,i){const o=t.aU([],e[i[0]],e[i[1]]),r=t.aU([],e[i[2]],e[i[1]]),a=[0,0,0,0];return t.aV(a,t.aW([],o,r)),a[3]=-t.aX(a,e[i[0]]),a}(e,i),u=function(e,i){const o=t.a$(e),r=t.b0([],e,1/o),a=t.aU([],i,t.aR([],r,t.aX(i,r))),s=t.a$(a);if(s>0){const e=Math.sqrt(1-r[3]*r[3]),o=t.aR([],r,-r[3]),n=t.aS([],o,t.aR([],a,e/s));return t.b1(i,n)}return null}(o,h);if(null!==u){const e=u/t.aX(c[0],h);n=Math.min(n,e);}for(let t=0;t<4;t++){const i=Math.min(n,l[t]);e[t+s]=[e[t+a][0]+c[t][0]*i,e[t+a][1]+c[t][1]*i,e[t+a][2]+c[t][2]*i,1];}}(l,s[0],r,a);const c=s.map((e=>{const i=t.aU([],l[e[0]],l[e[1]]),o=t.aU([],l[e[2]],l[e[1]]),r=t.aV([],t.aW([],i,o)),a=-t.aX(r,l[e[1]]);return r.concat(a)})),h=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of l)for(let t=0;t<3;t++)h[t]=Math.min(h[t],e[t]),u[t]=Math.max(u[t],e[t]);return new At(l,c,new zt(h,u))}}class Lt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e,t){}constructor(e,t,i,o,r){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)},e,t,i,o,r),this._coveringTilesDetailsProvider=new Dt;}clone(){const e=new Lt;return e.apply(this),e}apply(e,t,i){this._helper.apply(e,t,i);}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.b2(0,e)];if(this._helper._renderWorldCopies){const o=this.screenPointToMercatorCoordinate(new t.P(0,0)),r=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,0)),a=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,this._helper._height)),s=this.screenPointToMercatorCoordinate(new t.P(0,this._helper._height)),n=Math.floor(Math.min(o.x,r.x,a.x,s.x)),l=Math.floor(Math.max(o.x,r.x,a.x,s.x)),c=1;for(let o=n-c;o<=l+c;o++)0!==o&&i.push(new t.b2(o,e));}return i}getCameraFrustum(){return At.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const t=this.screenPointToLocation(this.centerPoint,e),i=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(i);}setLocationAtPoint(e,i){const o=t.aj(this.elevation,this.center.lat),r=this.screenPointToMercatorCoordinateAtZ(i,o),a=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,o),s=t.a1.fromLngLat(e),n=new t.a1(s.x-(r.x-a.x),s.y-(r.y-a.y));this.setCenter(null==n?void 0:n.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,i){return i?this.coordinatePoint(t.a1.fromLngLat(e),i.getElevationForLngLatZoom(e,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(t.a1.fromLngLat(e))}screenPointToLocation(e,t){var i;return null===(i=this.screenPointToMercatorCoordinate(e,t))||void 0===i?void 0:i.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const o=i||0,r=[e.x,e.y,0,1],a=[e.x,e.y,1,1];t.aw(r,r,this._pixelMatrixInverse),t.aw(a,a,this._pixelMatrixInverse);const s=r[3],n=a[3],l=r[1]/s,c=a[1]/n,h=r[2]/s,u=a[2]/n,d=h===u?0:(o-h)/(u-h);return new t.a1(t.C.number(r[0]/s,a[0]/n,d)/this.worldSize,t.C.number(l,c,d)/this.worldSize,o)}coordinatePoint(e,i=0,o=this._pixelMatrix){const r=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.aw(r,r,o),new t.P(r[0]/r[3],r[1]/r[3])}getBounds(){const e=Math.max(0,this._helper._height/2-he(this));return (new G).extend(this.screenPointToLocation(new t.P(0,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.P(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-he(this)}calculatePosMatrix(e,i=!1,o){var r;const a=null!==(r=e.key)&&void 0!==r?r:t.b3(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),s=i?this._alignedPosMatrixCache:this._posMatrixCache;if(s.has(a)){const e=s.get(a);return o?e.f32:e.f64}const n=ue(e,this.worldSize);t.O(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return s.set(a,l),o?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,o=this._fogMatrixCacheF32;if(o.has(i))return o.get(i);const r=ue(e,this.worldSize);return t.O(r,this._fogMatrix,r),o.set(i,new Float32Array(r)),o.get(i)}getConstrained(e,i){i=t.ah(+i,this.minZoom,this.maxZoom);const o={center:new t.S(e.lng,e.lat),zoom:i};let r=this._helper._lngRange;if(!this._helper._renderWorldCopies&&null===r){const e=180-1e-10;r=[-e,e];}const a=this.tileSize*t.af(o.zoom);let s=0,n=a,l=0,c=a,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;s=t.U(e[1])*a,n=t.U(e[0])*a,n-s<_&&(h=_/(n-s));}r&&(l=t.aO(t.V(r[0])*a,0,a),c=t.aO(t.V(r[1])*a,0,a),cn&&(g=n-e);}if(r){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.aO(p,e-a/2,e+a/2));const o=d/2;i-oc&&(f=c-o);}if(void 0!==f||void 0!==g){const e=new t.P(null!=f?f:p,null!=g?g:m);o.center=ce(a,e).wrap();}return o}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}_calculateNearFarZIfNeeded(e,i,o){if(!this._helper.autoCalculateNearFarZ)return;const r=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),a=e-r*this._helper._pixelPerMeter/Math.cos(i),s=r<0?a:e,n=Math.PI/2+this.pitchInRadians,l=t.ae(this.fov)*(Math.abs(Math.cos(t.ae(this.roll)))*this.height+Math.abs(Math.sin(t.ae(this.roll)))*this.width)/this.height*(.5+o.y/this.height),c=Math.sin(l)*s/Math.sin(t.ah(Math.PI-n-l,.01,Math.PI-.01)),h=he(this),u=Math.atan(h/this._helper.cameraToCenterDistance),d=t.ae(.75),_=u>d?2*u*(.5+o.y/(2*h)):d,p=Math.sin(_)*s/Math.sin(t.ah(Math.PI-n-_,.01,Math.PI-.01)),m=Math.min(c,p);this._helper._farZ=1.01*(Math.cos(Math.PI/2-i)*m+s),this._helper._nearZ=this._helper._height/50;}_calcMatrices(){if(!this._helper._height)return;const e=this.centerOffset,i=le(this.worldSize,this.center),o=i.x,r=i.y;this._helper._pixelPerMeter=t.aj(1,this.center.lat)*this.worldSize;const a=t.ae(Math.min(this.pitch,ne)),s=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(a));let n;this._calculateNearFarZIfNeeded(s,a,e),n=new Float64Array(16),t.b4(n,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),t.aq(this._invProjMatrix,n),n[8]=2*-e.x/this._helper._width,n[9]=2*e.y/this._helper._height,this._projectionMatrix=t.b5(n),t.N(n,n,[1,-1,1]),t.M(n,n,[0,0,-this._helper.cameraToCenterDistance]),t.b6(n,n,-this.rollInRadians),t.b7(n,n,this.pitchInRadians),t.b6(n,n,-this.bearingInRadians),t.M(n,n,[-o,-r,0]),this._mercatorMatrix=t.N([],n,[this.worldSize,this.worldSize,this.worldSize]),t.N(n,n,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n),t.M(n,n,[0,0,-this.elevation]),this._viewProjMatrix=n,this._invViewProjMatrix=t.aq([],n);const l=[0,0,-1,1];t.aw(l,l,this._invViewProjMatrix),this._cameraPosition=[l[0]/l[3],l[1]/l[3],l[2]/l[3]],this._fogMatrix=new Float64Array(16),t.b4(this._fogMatrix,this.fovInRadians,this.width/this.height,s,this._helper._farZ),this._fogMatrix[8]=2*-e.x/this.width,this._fogMatrix[9]=2*e.y/this.height,t.N(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.b6(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.b7(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.b6(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.M(this._fogMatrix,this._fogMatrix,[-o,-r,0]),t.N(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.M(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.O(new Float64Array(16),this.clipSpaceToPixelsMatrix,n);const c=this._helper._width%2/2,h=this._helper._height%2/2,u=Math.cos(this.bearingInRadians),d=Math.sin(-this.bearingInRadians),_=o-Math.round(o)+u*c+d*h,p=r-Math.round(r)+u*h+d*c,m=new Float64Array(n);if(t.M(m,m,[_>.5?_-1:_,p>.5?p-1:p,0]),this._alignedProjMatrix=m,n=t.aq(new Float64Array(16),this._pixelMatrix),!n)throw new Error("failed to invert matrix");this._pixelMatrixInverse=n,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.P(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.aw(i,i,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const e=t.aj(1,this.center.lat)*this.worldSize;return de(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/e).toLngLat()}lngLatToCameraDepth(e,i){const o=t.a1.fromLngLat(e),r=[o.x*this.worldSize,o.y*this.worldSize,i,1];return t.aw(r,r,this._viewProjMatrix),r[2]/r[3]}getProjectionData(e){const{overscaledTileID:i,aligned:o,applyTerrainMatrix:r}=e,a=this._helper.getMercatorTileCoordinates(i),s=i?this.calculatePosMatrix(i,o,!0):null;let n;return n=i&&i.terrainRttPosMatrix32f&&r?i.terrainRttPosMatrix32f:s||t.b8(),{mainMatrix:n,tileMercatorCoords:a,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:n}}isLocationOccluded(e){return !1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,i){return 1}transformLightDirection(e){return t.aT(e)}getRayDirectionFromPixel(e){throw new Error("Not implemented.")}projectTileCoordinates(e,i,o,r){const a=this.calculatePosMatrix(o);let s;r?(s=[e,i,r(e,i),1],t.aw(s,s,a)):(s=[e,i,0,1],qe(s,s,a));const n=s[3];return {point:new t.P(s[0]/n,s[1]/n),signedDistanceFromCamera:n,isOccluded:!1}}populateCache(e){for(const t of e)this.calculatePosMatrix(t);}getMatrixForModel(e,i){const o=t.a1.fromLngLat(e,i),r=o.meterInMercatorCoordinateUnits(),a=t.b9();return t.M(a,a,[o.x,o.y,o.z]),t.b6(a,a,Math.PI),t.b7(a,a,Math.PI/2),t.N(a,a,[-r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=new t.Z(0,0,0,0,0),o=this.getProjectionData({overscaledTileID:i,applyGlobeMatrix:e}),r=ue(i,this.worldSize);t.O(r,this._viewProjMatrix,r),o.tileMercatorCoords=[0,0,1,1];const a=[t.$,t.$,this.worldSize/this._helper.pixelsPerMeter],s=t.ba();return t.N(s,r,a),o.fallbackMatrix=s,o.mainMatrix=s,o}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}}function kt(){t.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");}function Ft(e){if(e.useSlerp)if(e.k<1){const i=t.bb(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),o=t.bb(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),r=new Float64Array(4);t.bc(r,i,o,e.k);const a=t.bd(r);e.tr.setRoll(a.roll),e.tr.setPitch(a.pitch),e.tr.setBearing(a.bearing);}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(t.C.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(t.C.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(t.C.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k));}function Bt(e,i,o,r,a){const s=a.padding,n=le(a.worldSize,o.getNorthWest()),l=le(a.worldSize,o.getNorthEast()),c=le(a.worldSize,o.getSouthEast()),h=le(a.worldSize,o.getSouthWest()),u=t.ae(-r),d=n.rotate(u),_=l.rotate(u),p=c.rotate(u),m=h.rotate(u),f=new t.P(Math.max(d.x,_.x,m.x,p.x),Math.max(d.y,_.y,m.y,p.y)),g=new t.P(Math.min(d.x,_.x,m.x,p.x),Math.min(d.y,_.y,m.y,p.y)),v=f.sub(g),b=(a.width-(s.left+s.right+i.left+i.right))/v.x,x=(a.height-(s.top+s.bottom+i.top+i.bottom))/v.y;if(x<0||b<0)return void kt();const y=Math.min(t.ak(a.scale*Math.min(b,x)),e.maxZoom),w=t.P.convert(e.offset),T=new t.P((i.left-i.right)/2,(i.top-i.bottom)/2).rotate(t.ae(r)),P=w.add(T).mult(a.scale/t.af(y));return {center:ce(a.worldSize,n.add(c).div(2).sub(P)),zoom:y,bearing:r}}class Ot{get useGlobeControls(){return !1}handlePanInertia(e,t){const i=e.mag(),o=Math.abs(he(t));return {easingOffset:e.mult(Math.min(.75*o/i,1)),easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta);}handleMapControlsPan(e,t,i){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(i,e.around);}cameraForBoxAndBearing(e,t,i,o,r){return Bt(e,t,i,o,r)}handleJumpToCenterZoom(e,i){e.zoom!==(void 0!==i.zoom?+i.zoom:e.zoom)&&e.setZoom(+i.zoom),void 0!==i.center&&e.setCenter(t.S.convert(i.center));}handleEaseTo(e,i){const o=e.zoom,r=e.padding,a={roll:e.roll,pitch:e.pitch,bearing:e.bearing},s={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},n=void 0!==i.zoom,l=!e.isPaddingEqual(i.padding);let c=!1;const h=n?+i.zoom:e.zoom;let u=e.centerPoint.add(i.offsetAsPoint);const d=e.screenPointToLocation(u),{center:_,zoom:p}=e.getConstrained(t.S.convert(i.center||d),null!=h?h:o);St(e,_);const m=le(e.worldSize,d),f=le(e.worldSize,_).sub(m),g=t.af(p-o);return c=p!==o,{easeFunc:n=>{if(c&&e.setZoom(t.C.number(o,p,n)),t.be(a,s)||Ft({startEulerAngles:a,endEulerAngles:s,tr:e,k:n,useSlerp:a.roll!=s.roll}),l&&(e.interpolatePadding(r,i.padding,n),u=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const i=t.af(e.zoom-o),r=p>o?Math.min(2,g):Math.max(.5,g),a=Math.pow(r,1-n),s=ce(e.worldSize,m.add(f.mult(n*a)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?s.wrap():s,u);}},isZooming:c,elevationCenter:_}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.zoom,a=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),o?+i.zoom:r),s=a.center,n=a.zoom;St(e,s);const l=le(e.worldSize,i.locationAtOffset),c=le(e.worldSize,s).sub(l),h=c.mag(),u=t.af(n-r);let d;if(void 0!==i.minZoom){const o=Math.min(+i.minZoom,r,n),a=e.getConstrained(s,o).zoom;d=t.af(a-r);}return {easeFunc:(i,o,a,h)=>{e.setZoom(1===i?n:r+t.ak(o));const u=1===i?s:ce(e.worldSize,l.add(c.mult(a)).mult(o));e.setLocationAtPoint(e.renderWorldCopies?u.wrap():u,h);},scaleOfZoom:u,targetCenter:s,scaleOfMinZoom:d,pixelPathLength:h}}}class jt{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}jt.Replace=[1,0],jt.disabled=new jt(jt.Replace,t.bf.transparent,[!1,!1,!1,!1]),jt.unblended=new jt(jt.Replace,t.bf.transparent,[!0,!0,!0,!0]),jt.alphaBlended=new jt([1,771],t.bf.transparent,[!0,!0,!0,!0]);const Nt=2305;class Ut{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}Ut.disabled=new Ut(!1,1029,Nt),Ut.backCCW=new Ut(!0,1029,Nt),Ut.frontCCW=new Ut(!0,1028,Nt);class Zt{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Zt.ReadOnly=!1,Zt.ReadWrite=!0,Zt.disabled=new Zt(519,Zt.ReadOnly,[0,1]);const Gt=7680;class Vt{constructor(e,t,i,o,r,a){this.test=e,this.ref=t,this.mask=i,this.fail=o,this.depthFail=r,this.pass=a;}}Vt.disabled=new Vt({func:519,mask:0},0,0,Gt,Gt,Gt);const $t=new WeakMap;function qt(e){var t;if($t.has(e))return $t.get(e);{const i=null===(t=e.getParameter(e.VERSION))||void 0===t?void 0:t.startsWith("WebGL 2.0");return $t.set(e,i),i}}class Wt{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,o=i.gl;this._texFormat=o.RGBA,this._texType=o.UNSIGNED_BYTE;const r=new t.aL;r.emplaceBack(-1,-1),r.emplaceBack(2,-1),r.emplaceBack(-1,2);const a=new t.aN;a.emplaceBack(0,1,2),this._fullscreenTriangle=new wt(i.createVertexBuffer(r,Tt.members),i.createIndexBuffer(a),t.aM.simpleSegment(0,0,r.length,a.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(o.TEXTURE1);const s=o.createTexture();o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texImage2D(o.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(s),qt(o)&&(this._pbo=o.createBuffer(),o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.bufferData(o.PIXEL_PACK_BUFFER,4,o.STREAM_READ),o.bindBuffer(o.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const o=this._cachedRenderContext.context,r=o.gl;if(this._bindFramebuffer(),o.viewport.set([0,0,this._texWidth,this._texHeight]),o.clear({color:t.bf.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(o,r.TRIANGLES,Zt.disabled,Vt.disabled,jt.unblended,Ut.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&qt(r)){r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.readBuffer(r.COLOR_ATTACHMENT0),r.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),r.bindBuffer(r.PIXEL_PACK_BUFFER,null);const e=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);r.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&qt(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=Wt._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const Ht=t.$/128;function Xt(e,i){const o=void 0!==e.granularity?Math.max(e.granularity,1):1,r=o+(e.generateBorders?2:0),a=o+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),s=r+1,n=a+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=o+(e.generateBorders?1:0),u=o+(e.generateBorders||e.extendToSouthPole?1:0),d=s*n,_=r*a*6,p=s*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g=0;for(let i=c;i<=u;i++)for(let r=l;r<=h;r++){let a=r/o*t.$;-1===r&&(a=-Ht),r===o+1&&(a=t.$+Ht);let s=i/o*t.$;-1===i&&(s=e.extendToNorthPole?t.bh:-Ht),i===o+1&&(s=e.extendToSouthPole?t.bi:t.$+Ht),f[g++]=a,f[g++]=s;}const v=m?new Uint32Array(_):new Uint16Array(_);let b=0;for(let e=0;e0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return "globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy();}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e);}getMeshFromTileID(e,t,i,o,r){return this.currentProjection.getMeshFromTileID(e,t,i,o,r)}setProjection(e){this._transitionable.setValue("type",(null==e?void 0:e.type)||"mercator");}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e);}}function ei(e){const t=oi(e.worldSize,e.center.lat);return 2*Math.PI*t}function ti(e,i,o,r,a){const s=1/(1<1e-6){const r=e[0]/o,a=Math.acos(e[2]/o),s=(r>0?a:-a)/Math.PI*180;return new t.S(t.aO(s,-180,180),i)}return new t.S(0,i)}function ai(e){return Math.cos(e*Math.PI/180)}function si(e,i){const o=ai(e),r=ai(i);return t.ak(r/o)}function ni(e,i){const o=e.rotate(i.bearingInRadians),r=i.zoom+si(i.center.lat,0),a=t.bk(1/ai(i.center.lat),1/ai(Math.min(Math.abs(i.center.lat),60)),t.bn(r,7,3,0,1)),s=360/ei({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.S(i.center.lng-o.x*s*a,t.ah(i.center.lat+o.y*s,-t.ai,t.ai))}function li(e){const t=.5*e,i=Math.sin(t),o=Math.cos(t);return Math.log(i+o)-Math.log(o-i)}function ci(e,i,o,r){const a=e.lat+o*r;if(Math.abs(o)>1){const s=(Math.sign(e.lat+o)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+o)*Math.PI/180,l=li(s+r*(n-s)),c=li(s),h=li(n);return new t.S(e.lng+i*((l-c)/(h-c)),a)}return new t.S(e.lng+i*r,a)}class hi{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._boundingVolumeFactory=e;}swapBuffers(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=!1;}getTileBoundingVolume(e,t,i,o){const r=`${e.z}_${e.x}_${e.y}_${(null==o?void 0:o.terrain)?"t":""}`,a=this._cache.get(r);if(a)return a;const s=this._cachePrevious.get(r);if(s)return this._cache.set(r,s),s;const n=this._boundingVolumeFactory(e,t,i,o);return this._cache.set(r,n),this._hadAnyChanges=!0,n}}class ui{constructor(e,t,i,o){this.min=i,this.max=o,this.points=e,this.planes=t;}static fromAabb(e,t){const i=[];for(let o=0;o<8;o++)i.push([1&~o?e[0]:t[0],1==(o>>1&1)?t[1]:e[1],1==(o>>2&1)?t[2]:e[2]]);return new ui(i,[[-1,0,0,t[0]],[1,0,0,-e[0]],[0,-1,0,t[1]],[0,1,0,-e[1]],[0,0,-1,t[2]],[0,0,1,-e[2]]],e,t)}static fromCenterSizeAngles(e,i,o){const r=t.br([],o[0],o[1],o[2]),a=t.bs([],[i[0],0,0],r),s=t.bs([],[0,i[1],0],r),n=t.bs([],[0,0,i[2]],r),l=[...e],c=[...e];for(let t=0;t<8;t++)for(let i=0;i<3;i++){const o=e[i]+a[i]*(1&~t?-1:1)+s[i]*(1==(t>>1&1)?1:-1)+n[i]*(1==(t>>2&1)?1:-1);l[i]=Math.min(l[i],o),c[i]=Math.max(c[i],o);}const h=[];for(let i=0;i<8;i++){const o=[...e];t.aS(o,o,t.aR([],a,1&~i?-1:1)),t.aS(o,o,t.aR([],s,1==(i>>1&1)?1:-1)),t.aS(o,o,t.aR([],n,1==(i>>2&1)?1:-1)),h.push(o);}return new ui(h,[[...a,-t.aX(a,h[0])],[...s,-t.aX(s,h[0])],[...n,-t.aX(n,h[0])],[-a[0],-a[1],-a[2],-t.aX(a,h[7])],[-s[0],-s[1],-s[2],-t.aX(s,h[7])],[-n[0],-n[1],-n[2],-t.aX(n,h[7])]],l,c)}intersectsFrustum(e){let t=!0;const i=this.points.length,o=this.planes.length,r=e.planes.length,a=e.points.length;for(let o=0;o=0&&a++;}if(0===a)return 0;a=0&&o++;}if(0===o)return 0}return 1}intersectsPlane(e){const t=this.points.length;let i=0;for(let o=0;o=0&&i++;}return i===t?2:0===i?0:1}}function di(e,t,i){const o=e-t;return o<0?-o:Math.max(0,o-i)}function _i(e,t,i,o,r){const a=e-i;let s;return s=a<0?Math.min(-a,1+a-r):a>1?Math.min(Math.max(a-r,0),1-a):0,Math.max(s,di(t,o,r))}class pi{constructor(){this._boundingVolumeCache=new hi(this._computeTileBoundingVolume);}prepareNextFrame(){this._boundingVolumeCache.swapBuffers();}distanceToTile2d(e,t,i,o){const r=1<4}allowWorldCopies(){return !1}getTileBoundingVolume(e,t,i,o){return this._boundingVolumeCache.getTileBoundingVolume(e,t,i,o)}_computeTileBoundingVolume(e,i,o,r){var a,s;let n=0,l=0;if(null==r?void 0:r.terrain){const c=new t.Z(e.z,i,e.z,e.x,e.y),h=r.terrain.getMinMaxElevation(c);n=null!==(a=h.minElevation)&&void 0!==a?a:Math.min(0,o),l=null!==(s=h.maxElevation)&&void 0!==s?s:Math.max(0,o);}if(n/=t.bu,l/=t.bu,n+=1,l+=1,e.z<=0)return ui.fromAabb([-l,-l,-l],[l,l,l]);if(1===e.z)return ui.fromAabb([0===e.x?-l:0,0===e.y?0:-l,-l],[0===e.x?0:l,0===e.y?l:0,l]);{const i=[ti(0,0,e.x,e.y,e.z),ti(t.$,0,e.x,e.y,e.z),ti(t.$,t.$,e.x,e.y,e.z),ti(0,t.$,e.x,e.y,e.z)],o=[];for(const e of i)o.push(t.aR([],e,l));if(l!==n)for(const e of i)o.push(t.aR([],e,n));0===e.y&&o.push([0,1,0]),e.y===(1<=(1<{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._coveringTilesDetailsProvider=new pi;}clone(){const e=new fi;return e.apply(this),e}apply(e,t){this._globeLatitudeErrorCorrectionRadians=t||0,this._helper.apply(e);}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const e=t.bp();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(e){const{overscaledTileID:t,applyGlobeMatrix:i}=e,o=this._helper.getMercatorTileCoordinates(t);return {mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:o,clippingPlane:this._cachedClippingPlane,projectionTransition:i?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(e){const i=this.pitchInRadians,o=this.cameraToCenterDistance/e,r=Math.sin(i)*o,a=Math.cos(i)*o+1,s=1/Math.sqrt(r*r+a*a)*1;let n=-r,l=a;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];t.bw(h,h,[0,0,0],-this.bearingInRadians),t.bx(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.by(h,h,[0,0,0],this.center.lng*Math.PI/180);const u=1/t.aZ(h);return t.aR(h,h,u),[...h,-s*u]}isLocationOccluded(e){return !this.isSurfacePointVisible(ii(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,o=this._helper._center.lat*Math.PI/180,r=Math.cos(o),a=[Math.sin(i)*r,Math.sin(o),Math.cos(i)*r],s=[a[2],0,-a[0]],n=[0,0,0];t.aW(n,s,a),t.aV(s,s),t.aV(n,n);const l=[0,0,0];return t.aV(l,[s[0]*e[0]+n[0]*e[1]+a[0]*e[2],s[1]*e[0]+n[1]*e[1]+a[1]*e[2],s[2]*e[0]+n[2]*e[1]+a[2]*e[2]]),l}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(e,i,o){const r=function(e,i,o){const r=1/(1<a&&(a=i),on&&(n=o);}const h=[c.lng+s,c.lat+l,c.lng+a,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new G(h)}getConstrained(e,i){const o=t.ah(e.lat,-t.ai,t.ai),r=t.ah(+i,this.minZoom+si(0,o),this.maxZoom);return {center:new t.S(e.lng,o),zoom:r}}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,i){const o=ii(this.unprojectScreenPoint(i)),r=ii(e),a=t.bp();t.bB(a);const s=t.bp();t.by(s,o,a,-this.center.lng*Math.PI/180),t.bx(s,s,a,this.center.lat*Math.PI/180);const n=r[0]*r[0]+r[2]*r[2],l=s[0]*s[0];if(n=-g&&p<=g,b=f>=-g&&f<=g;let x,y;if(v&&b){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.bD(u,e)+t.bD(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return !1;const i=t.bv();return t.aw(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const o=t.aX(e,i),r=t.bp(),a=t.bp();t.aR(a,i,o),t.aU(r,e,a);const s=1-t.aX(r,r);if(s<0)return null;const n=t.aX(e,e)-1,l=-o+(o<0?1:-1)*Math.sqrt(s),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,o=this.getRayDirectionFromPixel(e),r=this.rayPlanetIntersection(i,o);if(r){const e=t.bp();t.aS(e,i,[o[0]*r.tMin,o[1]*r.tMin,o[2]*r.tMin]);const a=t.bp();return t.aV(a,e),ri(a)}const a=this._cachedClippingPlane,s=a[0]*o[0]+a[1]*o[1]+a[2]*o[2],n=-t.b1(a,i)/s,l=t.bp();if(n>0)t.aS(l,i,[o[0]*n,o[1]*n,o[2]*n]);else {const e=t.bp();t.aS(e,i,[2*o[0],2*o[1],2*o[2]]);const r=t.b1(this._cachedClippingPlane,e);t.aU(l,e,[this._cachedClippingPlane[0]*r,this._cachedClippingPlane[1]*r,this._cachedClippingPlane[2]*r]);}const c=function(e){const i=t.bp();return i[0]=e[0]*-e[3],i[1]=e[1]*-e[3],i[2]=e[2]*-e[3],{center:i,radius:Math.sqrt(1-e[3]*e[3])}}(a);return ri(function(e,i,o){const r=t.bp();t.aU(r,o,e);const a=t.bp();return t.bq(a,e,r,i/t.a$(r)),a}(c.center,c.radius,l))}getMatrixForModel(e,i){const o=t.S.convert(e),r=1/t.bu,a=t.b9();return t.bz(a,a,o.lng/180*Math.PI),t.b7(a,a,-o.lat/180*Math.PI),t.M(a,a,[0,0,1+i/t.bu]),t.b7(a,a,.5*Math.PI),t.N(a,a,[r,r,r]),a}getProjectionDataForCustomLayer(e=!0){const i=this.getProjectionData({overscaledTileID:new t.Z(0,0,0,0,0),applyGlobeMatrix:e});return i.tileMercatorCoords=[0,0,1,1],i}getFastPathSimpleProjectionMatrix(e){}}class gi{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=!0){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame(),this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame();}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._helper=new Rt({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._globeness=1,this._mercatorTransform=new Lt,this._verticalPerspectiveTransform=new fi;}clone(){const e=new gi;return e._globeness=this._globeness,e._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,e.apply(this),e}apply(e){this._helper.apply(e),this._mercatorTransform.apply(this),this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians);}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){const t=this._mercatorTransform.getProjectionData(e),i=this._verticalPerspectiveTransform.getProjectionData(e);return {mainMatrix:this.isGlobeRendering?i.mainMatrix:t.mainMatrix,clippingPlane:i.clippingPlane,tileMercatorCoords:i.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return t.bk(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return t.bk(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,i,o){const r=this._mercatorTransform.getPitchedTextCorrection(e,i,o),a=this._verticalPerspectiveTransform.getPitchedTextCorrection(e,i,o);return t.bk(r,a,this._globeness)}projectTileCoordinates(e,t,i,o){return this.currentTransform.projectTileCoordinates(e,t,i,o)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ);}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this._mercatorTransform.recalculateZoomAndCenter(e),this._verticalPerspectiveTransform.recalculateZoomAndCenter(e);}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e);}getBounds(){return this.currentTransform.getBounds()}getConstrained(e,t){return this.currentTransform.getConstrained(e,t)}calculateCenterFromCameraLngLatAlt(e,t,i,o){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,o)}setLocationAtPoint(e,t){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,t),void this.apply(this._mercatorTransform);this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform);}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getMatrixForModel(e,t){return this.currentTransform.getMatrixForModel(e,t)}getProjectionDataForCustomLayer(e=!0){const t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;const i=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return i.fallbackMatrix=t.mainMatrix,i}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}}class vi{get useGlobeControls(){return !0}handlePanInertia(e,i){const o=ni(e,i);return Math.abs(o.lng-i.center.lng)>180&&(o.lng=i.center.lng+179.5*Math.sign(o.lng-i.center.lng)),{easingCenter:o,easingOffset:new t.P(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){const o=e.around,r=i.screenPointToLocation(o);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const a=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const s=i.zoom-a;if(0===s)return;const n=t.bA(i.center.lng,r.lng),l=n/(Math.abs(n/180)+1),c=t.bA(i.center.lat,r.lat),h=i.getRayDirectionFromPixel(o),u=i.cameraPosition,d=-1*t.aX(u,h),_=t.bp();t.aS(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.aZ(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=oi(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.bn(f,.9,.5,1,.25),v=(1-t.af(-s))*Math.min(m,g),b=i.center.lat,x=i.zoom,y=new t.S(i.center.lng+l*v,t.ah(i.center.lat+c*v,-t.ai,t.ai));i.setLocationAtPoint(r,o);const w=i.center,T=t.bn(Math.abs(n),45,85,0,1),P=t.bn(f,.75,.35,0,1),C=Math.pow(Math.max(T,P),.25),I=t.bA(w.lng,y.lng),M=t.bA(w.lat,y.lat);i.setCenter(new t.S(w.lng+I*C,w.lat+M*C).wrap()),i.setZoom(x+si(b,i.center.lat));}handleMapControlsPan(e,t,i){if(!e.panDelta)return;const o=t.center.lat,r=t.zoom;t.setCenter(ni(e.panDelta,t).wrap()),t.setZoom(r+si(o,t.center.lat));}cameraForBoxAndBearing(e,i,o,r,a){const s=Bt(e,i,o,r,a),n=i.left/a.width*2-1,l=(a.width-i.right)/a.width*2-1,c=i.top/a.height*-2+1,h=(a.height-i.bottom)/a.height*-2+1,u=t.bA(o.getWest(),o.getEast())<0,d=u?o.getEast():o.getWest(),_=u?o.getWest():o.getEast(),p=Math.max(o.getNorth(),o.getSouth()),m=Math.min(o.getNorth(),o.getSouth()),f=d+.5*t.bA(d,_),g=p+.5*t.bA(p,m),v=a.clone();v.setCenter(s.center),v.setBearing(s.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(s.zoom);const b=v.modelViewProjectionMatrix,x=[ii(o.getNorthWest()),ii(o.getNorthEast()),ii(o.getSouthWest()),ii(o.getSouthEast()),ii(new t.S(_,g)),ii(new t.S(d,g)),ii(new t.S(f,p)),ii(new t.S(f,m))],y=ii(s.center);let w=Number.POSITIVE_INFINITY;for(const e of x)n<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",n))),l>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"x",l))),c>0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",c))),h<0&&(w=vi.getLesserNonNegativeNonNull(w,vi.solveVectorScale(e,y,b,"y",h)));if(Number.isFinite(w)&&0!==w)return s.zoom=v.zoom+t.ak(w),s;kt();}handleJumpToCenterZoom(e,i){const o=e.center.lat,r=e.getConstrained(i.center?t.S.convert(i.center):e.center,e.zoom).center;e.setCenter(r.wrap());const a=void 0!==i.zoom?+i.zoom:e.zoom+si(o,r.lat);e.zoom!==a&&e.setZoom(a);}handleEaseTo(e,i){const o=e.zoom,r=e.center,a=e.padding,s={roll:e.roll,pitch:e.pitch,bearing:e.bearing},n={roll:void 0===i.roll?e.roll:i.roll,pitch:void 0===i.pitch?e.pitch:i.pitch,bearing:void 0===i.bearing?e.bearing:i.bearing},l=void 0!==i.zoom,c=!e.isPaddingEqual(i.padding);let h=!1;const u=i.center?t.S.convert(i.center):r,d=e.getConstrained(u,o).center;St(e,d);const _=e.clone();_.setCenter(d),_.setZoom(l?+i.zoom:o+si(r.lat,u.lat)),_.setBearing(i.bearing);const p=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));_.setLocationAtPoint(d,p);const m=(i.offset&&i.offsetAsPoint.mag())>0?_.center:d,f=l?+i.zoom:o+si(r.lat,m.lat),g=o+si(r.lat,0),v=f+si(m.lat,0),b=t.bA(r.lng,m.lng),x=t.bA(r.lat,m.lat),y=t.af(v-g);return h=f!==o,{easeFunc:o=>{if(t.be(s,n)||Ft({startEulerAngles:s,endEulerAngles:n,tr:e,k:o,useSlerp:s.roll!=n.roll}),c&&e.interpolatePadding(a,i.padding,o),i.around)t.w("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=v>g?Math.min(2,y):Math.max(.5,y),i=Math.pow(t,1-o),a=ci(r,b,x,o*i);e.setCenter(a.wrap());}if(h){const i=t.C.number(g,v,o)+si(0,e.center.lat);e.setZoom(i);}},isZooming:h,elevationCenter:m}}handleFlyTo(e,i){const o=void 0!==i.zoom,r=e.center,a=e.zoom,s=e.padding,n=!e.isPaddingEqual(i.padding),l=e.getConstrained(t.S.convert(i.center||i.locationAtOffset),a).center,c=o?+i.zoom:e.zoom+si(e.center.lat,l.lat),h=e.clone();h.setCenter(l),h.setZoom(c),h.setBearing(i.bearing);const u=new t.P(t.ah(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ah(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));h.setLocationAtPoint(l,u);const d=h.center;St(e,d);const _=function(e,i,o){const r=ii(i),a=ii(o),s=t.aX(r,a),n=Math.acos(s),l=ei(e);return n/(2*Math.PI)*l}(e,r,d),p=a+si(r.lat,0),m=c+si(d.lat,0),f=t.af(m-p);let g;if("number"==typeof i.minZoom){const o=+i.minZoom+si(d.lat,0),r=Math.min(o,p,m)+si(0,d.lat),a=e.getConstrained(d,r).zoom+si(d.lat,0);g=t.af(a-p);}const v=t.bA(r.lng,d.lng),b=t.bA(r.lat,d.lat);return {easeFunc:(o,a,l,h)=>{const u=ci(r,v,b,l);n&&e.interpolatePadding(s,i.padding,o);const _=1===o?d:u;e.setCenter(_.wrap());const m=p+t.ak(a);e.setZoom(1===o?c:m+si(0,_.lat));},scaleOfZoom:f,targetCenter:d,scaleOfMinZoom:g,pixelPathLength:_}}static solveVectorScale(e,t,i,o,r){const a="x"===o?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],s=[i[3],i[7],i[11],i[15]],n=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],l=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],c=t[0]*a[0]+t[1]*a[1]+t[2]*a[2],h=t[0]*s[0]+t[1]*s[1]+t[2]*s[2];return c+r*l===n+r*h||s[3]*(n-c)+a[3]*(h-l)+n*h==c*l?null:(c+a[3]-r*h-r*s[3])/(c-n-r*h+r*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.y(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),yi=t.bE();class wi extends t.E{constructor(e,i={}){var o,r;super(),this._rtlPluginLoaded=()=>{for(const e in this.sourceCaches){const t=this.sourceCaches[e].getSource().type;"vector"!==t&&"geojson"!==t||this.sourceCaches[e].reload();}},this.map=e,this.dispatcher=new F(k(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.imageManager=new b,this.imageManager.setEventedParent(this);const a=(null===(o=e._container)||void 0===o?void 0:o.lang)||"undefined"!=typeof document&&(null===(r=document.documentElement)||void 0===r?void 0:r.lang)||void 0;this.glyphManager=new T(e._requestManager,i.localIdeographFontFamily,a),this.lineAtlas=new E(256,512),this.crossTileSymbolIndex=new vt,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.bF,this._loaded=!1,this._availableImages=[],this._globalState={},this._resetUpdates(),this.dispatcher.broadcast("SR",t.bG()),oe().on(ee,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.sourceCaches[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}setGlobalStateProperty(e,i){var o,r,a;this._checkLoaded();const s=null===i?null!==(a=null===(r=null===(o=this.stylesheet.state)||void 0===o?void 0:o[e])||void 0===r?void 0:r.default)&&void 0!==a?a:null:i;if(t.bH(s,this._globalState[e]))return this;this._globalState[e]=s,this._applyGlobalStateChanges([e]);}getGlobalState(){return this._globalState}setGlobalState(e){this._checkLoaded();const i=[];for(const o in e)!t.bH(this._globalState[o],e[o].default)&&(i.push(o),this._globalState[o]=e[o].default);this._applyGlobalStateChanges(i);}_applyGlobalStateChanges(e){if(0===e.length)return;const t=new Set,i={};for(const o of e){i[o]=this._globalState[o];for(const e in this._layers){const i=this._layers[e],r=i.getLayoutAffectingGlobalStateRefs(),a=i.getPaintAffectingGlobalStateRefs();if(r.has(o)&&t.add(i.source),a.has(o))for(const{name:e,value:t}of a.get(o))this._updatePaintProperty(i,e,t);}}this.dispatcher.broadcast("UGS",i);for(const e in this.sourceCaches)t.has(e)&&(this._reloadSource(e),this._changed=!0);}loadURL(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const r=this.map._requestManager.transformRequest(e,"Style");this._loadStyleRequest=new AbortController;const a=this._loadStyleRequest;t.j(r,this._loadStyleRequest).then((e=>{this._loadStyleRequest=null,this._load(e.data,i,o);})).catch((e=>{this._loadStyleRequest=null,e&&!a.signal.aborted&&this.fire(new t.k(e));}));}loadJSON(e,i={},o){this.fire(new t.l("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,s.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=!1!==i.validate,this._load(e,i,o);})).catch((()=>{}));}loadEmpty(){this.fire(new t.l("dataloading",{dataType:"style"})),this._load(yi,{validate:!1});}_load(e,i,o){var r,a;let s=i.transformStyle?i.transformStyle(o,e):e;if(!i.validate||!xi(this,t.z(s))){s=Object.assign({},s),this._loaded=!0,this.stylesheet=s;for(const e in s.sources)this.addSource(e,s.sources[e],{validate:!1});s.sprite?this._loadSprite(s.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(s.glyphs),this._createLayers(),this.light=new I(this.stylesheet.light),this._setProjectionInternal((null===(r=this.stylesheet.projection)||void 0===r?void 0:r.type)||"mercator"),this.sky=new S(this.stylesheet.sky),this.map.setTerrain(null!==(a=this.stylesheet.terrain)&&void 0!==a?a:null),this.fire(new t.l("data",{dataType:"style"})),this.fire(new t.l("style.load"));}}_createLayers(){var e;const i=t.bI(this.stylesheet.layers);this.setGlobalState(null!==(e=this.stylesheet.state)&&void 0!==e?e:null),this.dispatcher.broadcast("SL",i),this._order=i.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const e of i){const i=t.bJ(e,this._globalState);i.setEventedParent(this,{layer:{id:e.id}}),this._layers[e.id]=i;}}_loadSprite(e,i=!1,o=void 0){let r;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(e,i,o,r){return t._(this,void 0,void 0,(function*(){const a=f(e),n=o>1?"@2x":"",l={},c={};for(const{id:e,url:o}of a){const a=i.transformRequest(g(o,n,".json"),"SpriteJSON");l[e]=t.j(a,r);const s=i.transformRequest(g(o,n,".png"),"SpriteImage");c[e]=p.getImage(s,r);}return yield Promise.all([...Object.values(l),...Object.values(c)]),function(e,i){return t._(this,void 0,void 0,(function*(){const t={};for(const o in e){t[o]={};const r=s.getImageCanvasContext((yield i[o]).data),a=(yield e[o]).data;for(const e in a){const{width:i,height:s,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=a[e];t[o][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:s,x:n,y:l,context:r}};}}return t}))}(l,c)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const o=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of o)this.imageManager.removeImage(e),this._changedImages[e]=!0;for(const o in e[t]){const r="default"===t?o:`${t}:${o}`;this._spritesImagesIds[t].push(r),r in this.imageManager.images?this.imageManager.updateImage(r,e[t][o],!1):this.imageManager.addImage(r,e[t][o]),i&&(this._changedImages[r]=!0);}}})).catch((e=>{this._spriteRequest=null,r=e,this.fire(new t.k(r));})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),i&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"})),o&&o(r);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}_validateLayer(e){const i=this.sourceCaches[e.source];if(!i)return;const o=e.sourceLayer;if(!o)return;const r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.k(new Error(`Source layer "${o}" does not exist on source "${r.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(const e in this.sourceCaches)if(!this.sourceCaches[e].loaded())return !1;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=!1){const o=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.bK(o):o);const r=[];for(const a of e)if(o[a]){const e=i?t.bK(o[a]):o[a];r.push(e);}return r}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){var e,t,i;if(null===(e=this.light)||void 0===e?void 0:e.hasTransition())return !0;if(null===(t=this.sky)||void 0===t?void 0:t.hasTransition())return !0;if(null===(i=this.projection)||void 0===i?void 0:i.hasTransition())return !0;for(const e in this.sourceCaches)if(this.sourceCaches[e].hasTransition())return !0;for(const e in this._layers)if(this._layers[e].hasTransition())return !0;return !1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const o={};for(const e in this.sourceCaches){const t=this.sourceCaches[e];o[e]=t.used,t.used=!1;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.sourceCaches[i.source].used=!0);}for(const e in o){const i=this.sourceCaches[e];!!o[e]!=!!i.used&&i.fire(new t.l("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.projection.recalculate(e),this.z=e.zoom,i&&this.fire(new t.l("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,!1),removedIds:t});}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1;}setState(e,i={}){var o;this._checkLoaded();const r=this.serialize();if(e=i.transformStyle?i.transformStyle(r,e):e,(null===(o=i.validate)||void 0===o||o)&&xi(this,t.z(e)))return !1;(e=t.bK(e)).layers=t.bI(e.layers);const a=t.bL(r,e),s=this._getOperationsToPerform(a);if(s.unimplemented.length>0)throw new Error(`Unimplemented: ${s.unimplemented.join(", ")}.`);if(0===s.operations.length)return !1;for(const e of s.operations)e();return this.stylesheet=e,this._serializedLayers=null,!0}_getOperationsToPerform(e){const t=[],i=[];for(const o of e)switch(o.command){case "setCenter":case "setZoom":case "setBearing":case "setPitch":case "setRoll":continue;case "addLayer":t.push((()=>this.addLayer.apply(this,o.args)));break;case "removeLayer":t.push((()=>this.removeLayer.apply(this,o.args)));break;case "setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,o.args)));break;case "setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,o.args)));break;case "setFilter":t.push((()=>this.setFilter.apply(this,o.args)));break;case "addSource":t.push((()=>this.addSource.apply(this,o.args)));break;case "removeSource":t.push((()=>this.removeSource.apply(this,o.args)));break;case "setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,o.args)));break;case "setLight":t.push((()=>this.setLight.apply(this,o.args)));break;case "setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,o.args)));break;case "setGlyphs":t.push((()=>this.setGlyphs.apply(this,o.args)));break;case "setSprite":t.push((()=>this.setSprite.apply(this,o.args)));break;case "setTerrain":t.push((()=>this.map.setTerrain.apply(this,o.args)));break;case "setSky":t.push((()=>this.setSky.apply(this,o.args)));break;case "setProjection":this.setProjection.apply(this,o.args);break;case "setGlobalState":t.push((()=>this.setGlobalState.apply(this,o.args)));break;case "setTransition":t.push((()=>{}));break;default:i.push(o.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.k(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,o={}){if(this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.z.source,`sources.${e}`,i,null,o))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const r=this.sourceCaches[e]=new xe(e,i,this.dispatcher);r.style=this,r.setEventedParent(this,(()=>({isSourceLoaded:r.loaded(),source:r.serialize(),sourceId:e}))),r.onAdd(this.map),this._changed=!0;}removeSource(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.k(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],i.fire(new t.l("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=!0;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error(`There is no source with this ID=${e}`);const i=this.sourceCaches[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=!0;}getSource(e){return this.sourceCaches[e]&&this.sourceCaches[e].getSource()}addLayer(e,i,o={}){this._checkLoaded();const r=e.id;if(this.getLayer(r))return void this.fire(new t.k(new Error(`Layer "${r}" already exists on this map.`)));let a;if("custom"===e.type){if(xi(this,t.bM(e)))return;a=t.bJ(e,this._globalState);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(r,e.source),e=t.bK(e),e=t.e(e,{source:r})),this._validate(t.z.layer,`layers.${r}`,e,{arrayIndex:-1},o))return;a=t.bJ(e,this._globalState),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}});}const s=i?this._order.indexOf(i):this._order.length;if(i&&-1===s)this.fire(new t.k(new Error(`Cannot add layer "${r}" before non-existing layer "${i}".`)));else {if(this._order.splice(s,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){const e=this._removedLayers[r];delete this._removedLayers[r],e.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=!0,!this._layers[e])return void this.fire(new t.k(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const o=this._order.indexOf(e);this._order.splice(o,1);const r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.k(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.k(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,o){this._checkLoaded();const r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.k(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,o={}){this._checkLoaded();const r=this.getLayer(e);if(r){if(!t.bH(r.filter,i))return null==i?(r.setFilter(void 0),void this._updateLayer(r)):void(this._validate(t.z.filter,`layers.${r.id}.filter`,i,null,o)||(r.setFilter(t.bK(i)),this._updateLayer(r)))}else this.fire(new t.k(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.bK(this.getLayer(e).filter)}setLayoutProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.k(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,o,r={}){this._checkLoaded();const a=this.getLayer(e);a?t.bH(a.getPaintProperty(i),o)||this._updatePaintProperty(a,i,o,r):this.fire(new t.k(new Error(`Cannot style non-existing layer "${e}".`)));}_updatePaintProperty(e,t,i,o={}){e.setPaintProperty(t,i,o)&&this._updateLayer(e),this._changed=!0,this._updatedPaintProps[e.id]=!0,this._serializedLayers=null;}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0===a)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const s=a.getSource().type;"geojson"===s&&r?this.fire(new t.k(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==s||r?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const o=e.source,r=this.sourceCaches[o];if(void 0===r)return void this.fire(new t.k(new Error(`The source '${o}' does not exist in the map's style.`)));const a=r.getSource().type,s="vector"===a?e.sourceLayer:void 0;"vector"!==a||s?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.k(new Error("A feature id is required to remove its specific state property."))):r.removeFeatureState(s,e.id,i):this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r)return "vector"!==r.getSource().type||o?(void 0===e.id&&this.fire(new t.k(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id)):void this.fire(new t.k(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.k(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.bN(this.sourceCaches,(e=>e.serialize())),i=this._serializeByIds(this._order,!0),o=this.map.getTerrain()||void 0,r=this.stylesheet;return t.bO({version:r.version,name:r.name,metadata:r.metadata,light:r.light,sky:r.sky,center:r.center,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,sprite:r.sprite,glyphs:r.glyphs,transition:r.transition,projection:r.projection,sources:e,layers:i,terrain:o},(e=>void 0!==e))}_updateLayer(e){this._updatedLayers[e.id]=!0,e.source&&!this._updatedSources[e.source]&&"raster"!==this.sourceCaches[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.sourceCaches[e.source].pause()),this._serializedLayers=null,this._changed=!0;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},o=[];for(let r=this._order.length-1;r>=0;r--){const a=this._order[r];if(t(a)){i[a]=r;for(const t of e){const e=t[a];if(e)for(const t of e)o.push(t);}}}o.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const r=[];for(let a=this._order.length-1;a>=0;a--){const s=this._order[a];if(t(s))for(let e=o.length-1;e>=0;e--){const t=o[e].feature;if(i[t.layer.id]this.map.terrain.getElevation(e,t,i):void 0));return this.placement&&a.push(function(e,t,i,o,r,a,s){const n={},l=a.queryRenderedSymbols(o),c=[];for(const e of Object.keys(l).map(Number))c.push(s[e]);c.sort(N);for(const i of c){const o=i.featureIndex.lookupSymbolFeatures(l[i.bucketInstanceId],t,i.bucketIndex,i.sourceLayerIndex,{filterSpec:r.filter,globalState:r.globalState},r.layers,r.availableImages,e);for(const e in o){const t=n[e]=n[e]||[],r=o[e];r.sort(((e,t)=>{const o=i.featureSortOrder;if(o){const i=o.indexOf(e.featureIndex);return o.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of r)t.push(e);}}return function(e,t,i){for(const o in e)for(const r of e[o])U(r,i[t[o].source]);return e}(n,e,i)}(this._layers,s,this.sourceCaches,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(a)}querySourceFeatures(e,i){(null==i?void 0:i.filter)&&this._validate(t.z.filter,"querySourceFeatures.filter",i.filter,null,i);const o=this.sourceCaches[e];return o?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),o=[],r={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const o=this.crossTileSymbolIndex.addLayer(i,l[i.source],e.center.lng);a=a||o;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((r=r||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(s.now(),e.zoom))&&(this.pauseablePlacement=new _t(e,this.map.terrain,this._order,r,t,i,o,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(s.now()),n=!0),a&&this.pauseablePlacement.placement.setStale()),n||a)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,l[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(s.now())}_releaseSymbolFadeTiles(){for(const e in this.sourceCaches)this.sourceCaches[e].releaseSymbolFadeTiles();}getImages(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t._(this,void 0,void 0,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.z.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}addSprite(e,i,o={},r){this._checkLoaded();const a=[{id:e,url:i}],s=[...f(this.stylesheet.sprite),...a];this._validate(t.z.sprite,"sprite",s,null,o)||(this.stylesheet.sprite=s,this._loadSprite(a,!0,r));}removeSprite(e){this._checkLoaded();const i=f(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=!0;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:void 0,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.l("data",{dataType:"style"}));}else this.fire(new t.k(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return f(this.stylesheet.sprite)}setSprite(e,i={},o){this._checkLoaded(),e&&this._validate(t.z.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,!0,o):(this._unloadSprite(),o&&o(null)));}}var Ti=t.aJ([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class Pi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;}bind(e,t,i,o,r,a,s,n,l){this.context=e;let c=this.boundPaintVertexBuffers.length!==o.length;for(let e=0;!c&&e({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:o?o.properties.get("fog-color"):t.bf.white,u_fog_ground_blend:o?o.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:a?0:o?o.calculateFogBlendOpacity(r):0,u_horizon_color:o?o.properties.get("horizon-color"):t.bf.white,u_horizon_fog_blend:o?o.properties.get("horizon-fog-blend"):1,u_is_globe_mode:a?1:0}),Ii={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function Mi(e){const t=[];for(let i=0;i({u_depth:new t.bP(e,i.u_depth),u_terrain:new t.bP(e,i.u_terrain),u_terrain_dim:new t.bg(e,i.u_terrain_dim),u_terrain_matrix:new t.bR(e,i.u_terrain_matrix),u_terrain_unpack:new t.bS(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.bg(e,i.u_terrain_exaggeration)}))(e,C),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.bR(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.bS(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.bS(e,i.u_projection_clipping_plane),u_projection_transition:new t.bg(e,i.u_projection_transition),u_projection_fallback_matrix:new t.bR(e,i.u_projection_fallback_matrix)}))(e,C),this.binderUniforms=o?o.getUniforms(e,C):[];}draw(e,t,i,o,r,a,s,n,l,c,h,u,d,_,p,m,f,g,v){const b=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(o),e.setColorMode(r),e.setCullFace(a),n){e.activeTexture.set(b.TEXTURE2),b.bindTexture(b.TEXTURE_2D,n.depthTexture),e.activeTexture.set(b.TEXTURE3),b.bindTexture(b.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[Ii[e]].set(l[e]);if(s)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(s[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let x=0;switch(t){case b.LINES:x=2;break;case b.TRIANGLES:x=3;break;case b.LINE_STRIP:x=1;}for(const i of d.get()){const o=i.vaos||(i.vaos={});(o[c]||(o[c]=new Pi)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),b.drawElements(t,i.primitiveLength*x,b.UNSIGNED_SHORT,i.primitiveOffset*x*2);}}}function Ei(e,i,o){const r=1/t.aC(o,1,i.transform.tileZoom),a=Math.pow(2,o.tileID.overscaledZ),s=o.tileSize*Math.pow(2,i.transform.tileZoom)/a,n=s*(o.tileID.canonical.x+o.tileID.wrap*a),l=s*o.tileID.canonical.y;return {u_image:0,u_texsize:o.imageAtlasTexture.size,u_scale:[r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Ri=(e,i,o,r)=>{const a=e.style.light,s=a.properties.get("position"),n=[s.x,s.y,s.z],l=t.bV();"viewport"===a.properties.get("anchor")&&t.bW(l,e.transform.bearingInRadians),t.bX(n,n,l);const c=e.transform.transformLightDirection(n),h=a.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:o,u_fill_translate:r}},zi=(e,i,o,r,a,s,n)=>t.e(Ri(e,i,o,r),Ei(s,e,n),{u_height_factor:-Math.pow(2,a.overscaledZ)/n.tileSize/8}),Di=(e,i,o,r)=>t.e(Ei(i,e,o),{u_fill_translate:r}),Ai=(e,t)=>({u_world:e,u_fill_translate:t}),Li=(e,i,o,r,a)=>t.e(Di(e,i,o,a),{u_world:r}),ki=(e,i,o,r,a)=>{const s=e.transform;let n,l,c=0;if("map"===o.paint.get("circle-pitch-alignment")){const e=t.aC(i,1,s.zoom);n=!0,l=[e,e],c=e/(t.$*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*a;}else n=!1,l=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===o.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:r}},Fi=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),Bi=e=>({u_viewport_size:[e.width,e.height]}),Oi=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),ji=(e,i,o,r)=>{const a=t.aC(e,1,i)/(t.$*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*r;return {u_extrude_scale:t.aC(e,1,i),u_intensity:o,u_globe_extrude_scale:a}},Ni=(e,i,o,r)=>{const a=t.L();t.bY(a,0,e.width,e.height,0,0,1);const s=e.context.gl;return {u_matrix:a,u_world:[s.drawingBufferWidth,s.drawingBufferHeight],u_image:o,u_color_ramp:r,u_opacity:i.paint.get("heatmap-opacity")}},Ui=(e,t,i)=>{const o=i.paint.get("hillshade-accent-color");let r;switch(i.paint.get("hillshade-method")){case "basic":r=4;break;case "combined":r=1;break;case "igor":r=2;break;case "multidirectional":r=3;break;default:r=0;}const a=i.getIlluminationProperties();for(let t=0;t{const o=i.stride,r=t.L();return t.bY(r,0,t.$,-t.$,0,0,1),t.M(r,r,[0,-t.$,0]),{u_matrix:r,u_image:1,u_dimension:[o,o],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function Gi(e,i){const o=Math.pow(2,i.canonical.z),r=i.canonical.y;return [new t.a1(0,r/o).toLngLat().lat,new t.a1(0,(r+1)/o).toLngLat().lat]}const Vi=(e,t,i=0)=>({u_image:0,u_unpack:t.getUnpackVector(),u_dimension:[t.stride,t.stride],u_elevation_stops:1,u_color_stops:4,u_color_ramp_size:i,u_opacity:e.paint.get("color-relief-opacity")}),$i=(e,i,o,r)=>{const a=e.transform;return {u_translation:Ki(e,i,o),u_ratio:r/t.aC(i,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},qi=(e,i,o,r,a)=>t.e($i(e,i,o,r),{u_image:0,u_image_height:a}),Wi=(e,i,o,r,a)=>{const s=e.transform,n=Xi(i,s);return {u_translation:Ki(e,i,o),u_texsize:i.imageAtlasTexture.size,u_ratio:r/t.aC(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},Hi=(e,i,o,r,a,s)=>{const n=e.lineAtlas,l=Xi(i,e.transform),c="round"===o.layout.get("line-cap"),h=n.getDash(a.from,c),u=n.getDash(a.to,c),d=h.width*s.fromScale,_=u.width*s.toScale;return t.e($i(e,i,o,r),{u_patternscale_a:[l/d,-h.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*e.pixelRatio)/2,u_image:0,u_tex_y_a:h.y,u_tex_y_b:u.y,u_mix:s.t})};function Xi(e,i){return 1/t.aC(e,1,i.tileZoom)}function Ki(e,i,o){return t.aD(e.transform,i,o.paint.get("line-translate"),o.paint.get("line-translate-anchor"))}const Yi=(e,t,i,o,r)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*o.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:o.paint.get("raster-brightness-min"),u_brightness_high:o.paint.get("raster-brightness-max"),u_saturation_factor:(s=o.paint.get("raster-saturation"),s>0?1-1/(1.001-s):-s),u_contrast_factor:(a=o.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Qi(o.paint.get("raster-hue-rotate")),u_coords_top:[r[0].x,r[0].y,r[1].x,r[1].y],u_coords_bottom:[r[3].x,r[3].y,r[2].x,r[2].y]};var a,s;};function Qi(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const Ji=(e,t,i,o,r,a,s,n,l,c,h,u,d)=>{const _=s.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:s.options.fadeDuration?s.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+o,u_is_along_line:r,u_is_variable_anchor:a,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},eo=(e,i,o,r,a,s,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.e(Ji(e,i,o,r,a,s,n,l,c,h,u,d,p),{u_gamma_scale:r?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:1})},to=(e,i,o,r,a,s,n,l,c,h,u,d,_)=>t.e(eo(e,i,o,r,a,s,n,l,c,h,!0,u,0,_),{u_texsize_icon:d,u_texture_icon:1}),io=(e,t)=>({u_opacity:e,u_color:t}),oo=(e,i,o,r,a)=>t.e(function(e,i,o,r){const a=o.imageManager.getPattern(e.from.toString()),s=o.imageManager.getPattern(e.to.toString()),{width:n,height:l}=o.imageManager.getPixelSize(),c=Math.pow(2,r.tileID.overscaledZ),h=r.tileSize*Math.pow(2,o.transform.tileZoom)/c,u=h*(r.tileID.canonical.x+r.tileID.wrap*c),d=h*r.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:s.tl,u_pattern_br_b:s.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:s.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.aC(r,1,o.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(o,a,i,r),{u_opacity:e}),ro=(e,t)=>{},ao={fillExtrusion:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.bT(e,i.u_lightpos),u_lightpos_globe:new t.bT(e,i.u_lightpos_globe),u_lightintensity:new t.bg(e,i.u_lightintensity),u_lightcolor:new t.bT(e,i.u_lightcolor),u_vertical_gradient:new t.bg(e,i.u_vertical_gradient),u_height_factor:new t.bg(e,i.u_height_factor),u_opacity:new t.bg(e,i.u_opacity),u_fill_translate:new t.bU(e,i.u_fill_translate),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.bU(e,i.u_world),u_fill_translate:new t.bU(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_texsize:new t.bU(e,i.u_texsize),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade),u_fill_translate:new t.bU(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_scale_with_map:new t.bP(e,i.u_scale_with_map),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_extrude_scale:new t.bU(e,i.u_extrude_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale),u_translate:new t.bU(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.bU(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.bU(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.bQ(e,i.u_color),u_overlay:new t.bP(e,i.u_overlay),u_overlay_scale:new t.bg(e,i.u_overlay_scale)}),depth:ro,clippingMask:ro,heatmap:(e,i)=>({u_extrude_scale:new t.bg(e,i.u_extrude_scale),u_intensity:new t.bg(e,i.u_intensity),u_globe_extrude_scale:new t.bg(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_world:new t.bU(e,i.u_world),u_image:new t.bP(e,i.u_image),u_color_ramp:new t.bP(e,i.u_color_ramp),u_opacity:new t.bg(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.bP(e,i.u_image),u_latrange:new t.bU(e,i.u_latrange),u_exaggeration:new t.bg(e,i.u_exaggeration),u_altitudes:new t.b_(e,i.u_altitudes),u_azimuths:new t.b_(e,i.u_azimuths),u_accent:new t.bQ(e,i.u_accent),u_method:new t.bP(e,i.u_method),u_shadows:new t.bZ(e,i.u_shadows),u_highlights:new t.bZ(e,i.u_highlights)}),hillshadePrepare:(e,i)=>({u_matrix:new t.bR(e,i.u_matrix),u_image:new t.bP(e,i.u_image),u_dimension:new t.bU(e,i.u_dimension),u_zoom:new t.bg(e,i.u_zoom),u_unpack:new t.bS(e,i.u_unpack)}),colorRelief:(e,i)=>({u_image:new t.bP(e,i.u_image),u_unpack:new t.bS(e,i.u_unpack),u_dimension:new t.bU(e,i.u_dimension),u_elevation_stops:new t.bP(e,i.u_elevation_stops),u_color_stops:new t.bP(e,i.u_color_stops),u_color_ramp_size:new t.bP(e,i.u_color_ramp_size),u_opacity:new t.bg(e,i.u_opacity)}),line:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_image:new t.bP(e,i.u_image),u_image_height:new t.bg(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_texsize:new t.bU(e,i.u_texsize),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_image:new t.bP(e,i.u_image),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_scale:new t.bT(e,i.u_scale),u_fade:new t.bg(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.bU(e,i.u_translation),u_ratio:new t.bg(e,i.u_ratio),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bU(e,i.u_units_to_pixels),u_patternscale_a:new t.bU(e,i.u_patternscale_a),u_patternscale_b:new t.bU(e,i.u_patternscale_b),u_sdfgamma:new t.bg(e,i.u_sdfgamma),u_image:new t.bP(e,i.u_image),u_tex_y_a:new t.bg(e,i.u_tex_y_a),u_tex_y_b:new t.bg(e,i.u_tex_y_b),u_mix:new t.bg(e,i.u_mix)}),raster:(e,i)=>({u_tl_parent:new t.bU(e,i.u_tl_parent),u_scale_parent:new t.bg(e,i.u_scale_parent),u_buffer_scale:new t.bg(e,i.u_buffer_scale),u_fade_t:new t.bg(e,i.u_fade_t),u_opacity:new t.bg(e,i.u_opacity),u_image0:new t.bP(e,i.u_image0),u_image1:new t.bP(e,i.u_image1),u_brightness_low:new t.bg(e,i.u_brightness_low),u_brightness_high:new t.bg(e,i.u_brightness_high),u_saturation_factor:new t.bg(e,i.u_saturation_factor),u_contrast_factor:new t.bg(e,i.u_contrast_factor),u_spin_weights:new t.bT(e,i.u_spin_weights),u_coords_top:new t.bS(e,i.u_coords_top),u_coords_bottom:new t.bS(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texture:new t.bP(e,i.u_texture),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.bP(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bP(e,i.u_is_size_feature_constant),u_size_t:new t.bg(e,i.u_size_t),u_size:new t.bg(e,i.u_size),u_camera_to_center_distance:new t.bg(e,i.u_camera_to_center_distance),u_pitch:new t.bg(e,i.u_pitch),u_rotate_symbol:new t.bP(e,i.u_rotate_symbol),u_aspect_ratio:new t.bg(e,i.u_aspect_ratio),u_fade_change:new t.bg(e,i.u_fade_change),u_label_plane_matrix:new t.bR(e,i.u_label_plane_matrix),u_coord_matrix:new t.bR(e,i.u_coord_matrix),u_is_text:new t.bP(e,i.u_is_text),u_pitch_with_map:new t.bP(e,i.u_pitch_with_map),u_is_along_line:new t.bP(e,i.u_is_along_line),u_is_variable_anchor:new t.bP(e,i.u_is_variable_anchor),u_texsize:new t.bU(e,i.u_texsize),u_texsize_icon:new t.bU(e,i.u_texsize_icon),u_texture:new t.bP(e,i.u_texture),u_texture_icon:new t.bP(e,i.u_texture_icon),u_gamma_scale:new t.bg(e,i.u_gamma_scale),u_device_pixel_ratio:new t.bg(e,i.u_device_pixel_ratio),u_is_halo:new t.bP(e,i.u_is_halo),u_translation:new t.bU(e,i.u_translation),u_pitched_scale:new t.bg(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_color:new t.bQ(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.bg(e,i.u_opacity),u_image:new t.bP(e,i.u_image),u_pattern_tl_a:new t.bU(e,i.u_pattern_tl_a),u_pattern_br_a:new t.bU(e,i.u_pattern_br_a),u_pattern_tl_b:new t.bU(e,i.u_pattern_tl_b),u_pattern_br_b:new t.bU(e,i.u_pattern_br_b),u_texsize:new t.bU(e,i.u_texsize),u_mix:new t.bg(e,i.u_mix),u_pattern_size_a:new t.bU(e,i.u_pattern_size_a),u_pattern_size_b:new t.bU(e,i.u_pattern_size_b),u_scale_a:new t.bg(e,i.u_scale_a),u_scale_b:new t.bg(e,i.u_scale_b),u_pixel_coord_upper:new t.bU(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bU(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.bg(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_ele_delta:new t.bg(e,i.u_ele_delta),u_fog_matrix:new t.bR(e,i.u_fog_matrix),u_fog_color:new t.bQ(e,i.u_fog_color),u_fog_ground_blend:new t.bg(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.bg(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon_fog_blend:new t.bg(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.bg(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.bg(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.bP(e,i.u_texture),u_terrain_coords_id:new t.bg(e,i.u_terrain_coords_id),u_ele_delta:new t.bg(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.bg(e,i.u_input),u_output_expected:new t.bg(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.bT(e,i.u_sun_pos),u_atmosphere_blend:new t.bg(e,i.u_atmosphere_blend),u_globe_position:new t.bT(e,i.u_globe_position),u_globe_radius:new t.bg(e,i.u_globe_radius),u_inv_proj_matrix:new t.bR(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.bQ(e,i.u_sky_color),u_horizon_color:new t.bQ(e,i.u_horizon_color),u_horizon:new t.bU(e,i.u_horizon),u_horizon_normal:new t.bU(e,i.u_horizon_normal),u_sky_horizon_blend:new t.bg(e,i.u_sky_horizon_blend),u_sky_blend:new t.bg(e,i.u_sky_blend)})};class so{constructor(e,t,i){this.context=e;const o=e.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const no={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class lo{constructor(e,t,i,o){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=o,this.context=e;const r=e.gl;this.buffer=r.createBuffer(),e.bindVertexBuffer.set(this.buffer),r.bufferData(r.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(s,l.LINES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Fi(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),o.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!a||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.b$;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:S,angle:E});}else $e(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===o.layout.get("text-rotation-alignment");De(c,e,a,O,j,v,h,i,l.toUnwrapped(),f.width,f.height,U,t);}const $=a&&P||V,q=b||$?Yo:v?O:e.transform.clipSpaceToPixelsMatrix,W=p&&0!==o.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1);let H;H=p?c.iconsInText?to(T.kind,E,x,v,b,$,e,q,N,U,z,k,I):eo(T.kind,E,x,v,b,$,e,q,N,U,a,z,0,I):Ji(T.kind,E,x,v,b,$,e,q,N,U,a,z,I);const X={program:S,buffers:u,uniformValues:H,projectionData:Z,atlasTexture:D,atlasTextureIcon:F,atlasInterpolation:A,atlasInterpolationIcon:L,isSDF:p,hasHalo:W};if(y&&c.canOverlap){w=!0;const e=u.segments.get();for(const i of e)C.push({segments:new t.aM([i]),sortKey:i.sortKey,state:X,terrainData:R});}else C.push({segments:u.segments,sortKey:0,state:X,terrainData:R});}w&&C.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of C){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const r=i.uniformValues;i.hasHalo&&(r.u_is_halo=1,or(i.buffers,t.segments,o,e,i.program,T,u,d,r,i.projectionData,t.terrainData)),r.u_is_halo=0;}or(i.buffers,t.segments,o,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function or(e,t,i,o,r,a,s,n,l,c,h){const u=o.context;r.draw(u,u.gl.TRIANGLES,a,s,n,Ut.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,o.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function rr(e,i,o,r,a){const s=e.context,n=s.gl,l=Vt.disabled,c=new jt([n.ONE,n.ONE],t.bf.transparent,[!0,!0,!0,!0]),h=i.getBucket(o);if(!h)return;const u=r.key;let d=o.heatmapFbos.get(u);d||(d=sr(s,i.tileSize,i.tileSize),o.heatmapFbos.set(u,d)),s.bindFramebuffer.set(d.framebuffer),s.viewport.set([0,0,i.tileSize,i.tileSize]),s.clear({color:t.bf.transparent});const _=h.programConfigurations.get(o.id),p=e.useProgram("heatmap",_,!a),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),f=e.style.map.terrain.getTerrainData(r);p.draw(s,n.TRIANGLES,Zt.disabled,l,c,Ut.disabled,ji(i,e.transform.zoom,o.paint.get("heatmap-intensity"),1),f,m,o.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,o.paint,e.transform.zoom,_);}function ar(e,t,i,o,r){const a=e.context,s=a.gl,n=e.transform;a.setColorMode(e.colorModeForRenderPass());const l=nr(a,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,h.colorAttachment.get()),a.activeTexture.set(s.TEXTURE1),l.bind(s.LINEAR,s.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:r,applyGlobeMatrix:!o});e.useProgram("heatmapTexture").draw(a,s.TRIANGLES,Zt.disabled,Vt.disabled,e.colorModeForRenderPass(),Ut.disabled,Ni(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function sr(e,t,i){var o,r;const a=e.gl,s=a.createTexture();a.bindTexture(a.TEXTURE_2D,s),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR);const n=null!==(o=e.HALF_FLOAT)&&void 0!==o?o:a.UNSIGNED_BYTE,l=null!==(r=e.RGBA16F)&&void 0!==r?r:a.RGBA;a.texImage2D(a.TEXTURE_2D,0,l,t,i,0,a.RGBA,n,null);const c=e.createFramebuffer(t,i,!1,!1);return c.colorAttachment.set(s),c}function nr(e,i){return i.colorRampTexture||(i.colorRampTexture=new t.T(e,i.colorRamp,e.gl.RGBA)),i.colorRampTexture}function lr(e,t,i,o,r){if(!i||!o||!o.imageAtlas)return;const a=o.imageAtlas.patternPositions;let s=a[i.to.toString()],n=a[i.from.toString()];if(!s&&n&&(s=n),!n&&s&&(n=s),!s||!n){const e=r.getPaintProperty(t);s=a[e],n=a[e];}s&&n&&e.setConstantPatternPositions(s,n);}function cr(e,i,o,r,a,s,n,l){const c=e.context.gl,h="fill-pattern",u=o.paint.get(h),d=u&&u.constantOr(1),_=o.getCrossfadeParameters();let p,m,f,g,v;const b=e.transform,x=o.paint.get("fill-translate"),y=o.paint.get("fill-translate-anchor");n?(m=d&&!o.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",p=c.LINES):(m=d?"fillPattern":"fill",p=c.TRIANGLES);const w=u.constantOr(null);for(const u of r){const r=i.getTile(u);if(d&&!r.patternsLoaded())continue;const T=r.getBucket(o);if(!T)continue;const P=T.programConfigurations.get(o.id),C=e.useProgram(m,P),I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(u);d&&(e.context.activeTexture.set(c.TEXTURE0),r.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),P.updatePaintBuffers(_)),lr(P,h,w,r,o);const M=b.getProjectionData({overscaledTileID:u,applyGlobeMatrix:!l,applyTerrainMatrix:!0}),S=t.aD(b,r,x,y);if(n){g=T.indexBuffer2,v=T.segments2;const t=[c.drawingBufferWidth,c.drawingBufferHeight];f="fillOutlinePattern"===m&&d?Li(e,_,r,t,S):Ai(t,S);}else g=T.indexBuffer,v=T.segments,f=d?Di(e,_,r,S):{u_fill_translate:S};const E=e.stencilModeForClipping(u);C.draw(e.context,p,a,E,s,Ut.backCCW,f,I,M,o.id,T.layoutVertexBuffer,g,v,o.paint,e.transform.zoom,P);}}function hr(e,i,o,r,a,s,n,l){const c=e.context,h=c.gl,u="fill-extrusion-pattern",d=o.paint.get(u),_=d.constantOr(1),p=o.getCrossfadeParameters(),m=o.paint.get("fill-extrusion-opacity"),f=d.constantOr(null),g=e.transform;for(const d of r){const r=i.getTile(d),v=r.getBucket(o);if(!v)continue;const b=e.style.map.terrain&&e.style.map.terrain.getTerrainData(d),x=v.programConfigurations.get(o.id),y=e.useProgram(_?"fillExtrusionPattern":"fillExtrusion",x);_&&(e.context.activeTexture.set(h.TEXTURE0),r.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),x.updatePaintBuffers(p));const w=g.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!l,applyTerrainMatrix:!0});lr(x,u,f,r,o);const T=t.aD(g,r,o.paint.get("fill-extrusion-translate"),o.paint.get("fill-extrusion-translate-anchor")),P=o.paint.get("fill-extrusion-vertical-gradient"),C=_?zi(e,P,m,T,d,p,r):Ri(e,P,m,T);y.draw(c,c.gl.TRIANGLES,a,s,n,Ut.backCCW,C,b,w,o.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,o.paint,e.transform.zoom,x,e.style.map.terrain&&v.centroidVertexBuffer);}}function ur(e,t,i,o,r,a,s,n,l){var c;const h=e.style.projection,u=e.context,d=e.transform,_=u.gl,p=[`#define NUM_ILLUMINATION_SOURCES ${i.paint.get("hillshade-highlight-color").values.length}`],m=e.useProgram("hillshade",null,!1,p),f=!e.options.moving;for(const p of o){const o=t.getTile(p),g=o.fbo;if(!g)continue;const v=h.getMeshFromTileID(u,p.canonical,n,!0,"raster"),b=null===(c=e.style.map.terrain)||void 0===c?void 0:c.getTerrainData(p);u.activeTexture.set(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g.colorAttachment.get());const x=d.getProjectionData({overscaledTileID:p,aligned:f,applyGlobeMatrix:!l,applyTerrainMatrix:!0});m.draw(u,_.TRIANGLES,a,r[p.overscaledZ],s,Ut.backCCW,Ui(e,o,i),b,x,i.id,v.vertexBuffer,v.indexBuffer,v.segments);}}function dr(e,i,o,r,a,s,n,l,c){var h;const u=e.style.projection,d=e.context,_=e.transform,p=d.gl,m=e.useProgram("colorRelief"),f=!e.options.moving;let g=!0,v=0;for(const b of r){const r=i.getTile(b),x=r.dem;if(g){const e=p.getParameter(p.MAX_TEXTURE_SIZE),{elevationTexture:t,colorTexture:i}=o.getColorRampTextures(d,e,x.getUnpackVector());d.activeTexture.set(p.TEXTURE1),t.bind(p.NEAREST,p.CLAMP_TO_EDGE),d.activeTexture.set(p.TEXTURE4),i.bind(p.LINEAR,p.CLAMP_TO_EDGE),g=!1,v=t.size[0];}if(!x||!x.data)continue;const y=x.stride,w=x.getPixels();if(d.activeTexture.set(p.TEXTURE0),d.pixelStoreUnpackPremultiplyAlpha.set(!1),r.demTexture=r.demTexture||e.getTileTexture(y),r.demTexture){const e=r.demTexture;e.update(w,{premultiply:!1}),e.bind(p.LINEAR,p.CLAMP_TO_EDGE);}else r.demTexture=new t.T(d,w,p.RGBA,{premultiply:!1}),r.demTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE);const T=u.getMeshFromTileID(d,b.canonical,l,!0,"raster"),P=null===(h=e.style.map.terrain)||void 0===h?void 0:h.getTerrainData(b),C=_.getProjectionData({overscaledTileID:b,aligned:f,applyGlobeMatrix:!c,applyTerrainMatrix:!0});m.draw(d,p.TRIANGLES,s,a[b.overscaledZ],n,Ut.backCCW,Vi(o,r.dem,v),P,C,o.id,T.vertexBuffer,T.indexBuffer,T.segments);}}const _r=[new t.P(0,0),new t.P(t.$,0),new t.P(t.$,t.$),new t.P(0,t.$)];function pr(e,t,i,o,r,a,s,n,l=!1,c=!1){const h=o[o.length-1].overscaledZ,u=e.context,d=u.gl,_=e.useProgram("raster"),p=e.transform,m=e.style.projection,f=e.colorModeForRenderPass(),g=!e.options.moving;for(const v of o){const o=e.getDepthModeForSublayer(v.overscaledZ-h,1===i.paint.get("raster-opacity")?Zt.ReadWrite:Zt.ReadOnly,d.LESS),b=t.getTile(v);b.registerFadeDuration(i.paint.get("raster-fade-duration"));const x=t.findLoadedParent(v,0),y=t.findLoadedSibling(v),w=mr(b,x||y||null,t,i,e.transform,e.style.map.terrain);let T,P;const C="nearest"===i.paint.get("raster-resampling")?d.NEAREST:d.LINEAR;u.activeTexture.set(d.TEXTURE0),b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),u.activeTexture.set(d.TEXTURE1),x?(x.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),T=Math.pow(2,x.tileID.overscaledZ-b.tileID.overscaledZ),P=[b.tileID.canonical.x*T%1,b.tileID.canonical.y*T%1]):b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),b.texture.useMipmap&&u.extTextureFilterAnisotropic&&e.transform.pitch>20&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(v),M=p.getProjectionData({overscaledTileID:v,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:!0}),S=Yi(P||[0,0],T||1,w,i,n),E=m.getMeshFromTileID(u,v.canonical,a,s,"raster");_.draw(u,d.TRIANGLES,o,r?r[v.overscaledZ]:Vt.disabled,f,l?Ut.frontCCW:Ut.backCCW,S,I,M,i.id,E.vertexBuffer,E.indexBuffer,E.segments);}}function mr(e,i,o,r,a,n){const l=r.paint.get("raster-fade-duration");if(!n&&l>0){const r=s.now(),n=(r-e.timeAdded)/l,c=i?(r-i.timeAdded)/l:-1,h=o.getSource(),u=ge(a,{tileSize:h.tileSize,roundZoom:h.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-u)>Math.abs(e.tileID.overscaledZ-u),_=d&&e.refreshedUponExpiration?1:t.ah(d?n:1-c,0,1);return e.refreshedUponExpiration&&n>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-_}:{opacity:_,mix:0}}return {opacity:1,mix:0}}const fr=new t.bf(1,0,0,1),gr=new t.bf(0,1,0,1),vr=new t.bf(0,0,1,1),br=new t.bf(1,0,1,1),xr=new t.bf(0,1,1,1);function yr(e,t,i,o){Tr(e,0,t+i/2,e.transform.width,i,o);}function wr(e,t,i,o){Tr(e,t-i/2,0,i,e.transform.height,o);}function Tr(e,t,i,o,r,a){const s=e.context,n=s.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,o*e.pixelRatio,r*e.pixelRatio),s.clear({color:a}),n.disable(n.SCISSOR_TEST);}function Pr(e,i,o){const r=e.context,a=r.gl,s=e.useProgram("debug"),n=Zt.disabled,l=Vt.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(o);r.activeTexture.set(a.TEXTURE0);const d=i.getTileByID(o.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(o).tileSize,m=512/Math.min(p,512)*(o.overscaledZ/e.transform.zoom)*.5;let f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=` => ${o.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,o=e.context.gl,r=e.debugOverlayCanvas.getContext("2d");r.clearRect(0,0,i.width,i.height),r.shadowColor="white",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle="white",r.textBaseline="top",r.font="bold 36px Open Sans, sans-serif",r.fillText(t,5,5),r.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:o,applyGlobeMatrix:!0,applyTerrainMatrix:!0});s.draw(r,a.TRIANGLES,n,l,jt.alphaBlended,Ut.disabled,Oi(t.bf.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),s.draw(r,a.LINE_STRIP,n,l,c,Ut.disabled,Oi(t.bf.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function Cr(e,t,i,o){const{isRenderingGlobe:r}=o,a=e.context,s=a.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain");a.bindFramebuffer.set(null),a.viewport.set([0,0,e.width,e.height]);for(const o of i){const i=t.getTerrainMesh(o.tileID),u=e.renderToTexture.getTexture(o),d=t.getTerrainData(o.tileID);a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,u.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(o.tileID.toUnwrapped()),m=Ci(_,p,e.style.sky,n.pitch,r),f=n.getProjectionData({overscaledTileID:o.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});h.draw(a,s.TRIANGLES,c,Vt.disabled,l,Ut.backCCW,m,d,f,"terrain",i.vertexBuffer,i.indexBuffer,i.segments);}}function Ir(e,i){if(!i.mesh){const o=new t.aL;o.emplaceBack(-1,-1),o.emplaceBack(1,-1),o.emplaceBack(1,1),o.emplaceBack(-1,1);const r=new t.aN;r.emplaceBack(0,1,2),r.emplaceBack(0,2,3),i.mesh=new wt(e.createVertexBuffer(o,Tt.members),e.createIndexBuffer(r),t.aM.simpleSegment(0,0,o.length,r.length));}return i.mesh}class Mr{constructor(e,i){this.context=new Ho(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:t.ag(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=xe.maxUnderzooming+xe.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new vt;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.aL;i.emplaceBack(0,0),i.emplaceBack(t.$,0),i.emplaceBack(0,t.$),i.emplaceBack(t.$,t.$),this.tileExtentBuffer=e.createVertexBuffer(i,Tt.members),this.tileExtentSegments=t.aM.simpleSegment(0,0,4,2);const o=new t.aL;o.emplaceBack(0,0),o.emplaceBack(t.$,0),o.emplaceBack(0,t.$),o.emplaceBack(t.$,t.$),this.debugBuffer=e.createVertexBuffer(o,Tt.members),this.debugSegments=t.aM.simpleSegment(0,0,4,5);const r=new t.c6;r.emplaceBack(0,0,0,0),r.emplaceBack(t.$,0,t.$,0),r.emplaceBack(0,t.$,0,t.$),r.emplaceBack(t.$,t.$,t.$,t.$),this.rasterBoundsBuffer=e.createVertexBuffer(r,Ti.members),this.rasterBoundsSegments=t.aM.simpleSegment(0,0,4,2);const a=new t.aL;a.emplaceBack(0,0),a.emplaceBack(t.$,0),a.emplaceBack(0,t.$),a.emplaceBack(t.$,t.$),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(a,Tt.members),this.rasterBoundsSegmentsPosOnly=t.aM.simpleSegment(0,0,4,5);const s=new t.aL;s.emplaceBack(0,0),s.emplaceBack(1,0),s.emplaceBack(0,1),s.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(s,Tt.members),this.viewportSegments=t.aM.simpleSegment(0,0,4,2);const n=new t.c7;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.aN;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new Vt({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new wt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const o=t.L();t.bY(o,0,this.width,this.height,0,0,1),t.N(o,o,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const r={mainMatrix:o,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:o};this.useProgram("clippingMask",null,!0).draw(e,i.TRIANGLES,Zt.disabled,this.stencilClearMode,jt.disabled,Ut.disabled,null,null,r,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const o=this.context;o.setColorMode(jt.disabled),o.setDepthMode(Zt.disabled);const r={};for(const e of t)r[e.key]=this.nextStencilID++;this._renderTileMasks(r,t,i,!0),this._renderTileMasks(r,t,i,!1),this._tileClippingMaskIDs=r;}_renderTileMasks(e,t,i,o){const r=this.context,a=r.gl,s=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=s.getMeshFromTileID(this.context,c.canonical,o,!0,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:!i,applyTerrainMatrix:!0});l.draw(r,a.TRIANGLES,Zt.disabled,new Vt({func:a.ALWAYS,mask:0},t,255,a.KEEP,a.KEEP,a.REPLACE),jt.disabled,i?Ut.disabled:Ut.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,o=this.transform,r=this.useProgram("depth"),a=this.getDepthModeFor3D(),s=ve(o,{tileSize:o.tileSize});for(const n of s){const s=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,!0,!0,"raster"),c=o.getProjectionData({overscaledTileID:n,applyGlobeMatrix:!0,applyTerrainMatrix:!0});r.draw(e,t.TRIANGLES,a,Vt.disabled,jt.disabled,Ut.backCCW,null,s,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new Vt({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new Vt({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(r>1){this.currentStencilSource=void 0,this.nextStencilID+r>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),o=i[i.length-1].overscaledZ,r=i[0].overscaledZ-o+1;if(this.clearStencil(),r>1){const e={},a={};for(let i=0;i0};for(const e in n){const t=n[e];t.used&&t.prepare(this.context),l[e]=t.getVisibleCoordinates(!1),c[e]=l[e].slice().reverse(),h[e]=t.getVisibleCoordinates(!0).reverse();}this.opaquePassCutoff=1/0;for(let e=0;ethis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.bf.black:t.bf.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,o=i.gl,r=((e,t,i)=>{const o=Math.cos(t.rollInRadians),r=Math.sin(t.rollInRadians),a=he(t),s=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-a*r)*i,(t.height/2+a*o)*i],u_horizon_normal:[-r,o],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:s}})(t,e.style.map.transform,e.pixelRatio),a=new Zt(o.LEQUAL,Zt.ReadWrite,[0,1]),s=Vt.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=Ir(i,t);l.draw(i,o.TRIANGLES,a,s,n,Ut.disabled,r,null,void 0,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=a.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[a[this.currentLayer]],t=n[e.source],i=l[e.source];this._renderTileClippingMasks(e,i,!1),this.renderLayer(this,t,e,i,u);}this.renderPass="translucent";let d=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:o,u_inv_proj_matrix:r}))(c,u,[p[0],p[1],p[2]],d,_),f=Ir(r,i);s.draw(r,a.TRIANGLES,n,Vt.disabled,jt.alphaBlended,Ut.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const o=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.sourceCaches[i.source]]:[])),r=o.filter((e=>"vector"===e.getSource().type)),a=o.filter((e=>"vector"!==e.getSource().type)),s=e=>{(!i||i.getSource().maxzooms(e))),i||a.forEach((e=>s(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let o=0;ou.getElevation(a,e,t):null;er(s,d,_,c,h,f,i,p,g,t.aD(h,e,n,l),a.toUnwrapped(),o);}}}(r,e,o,i,o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),a),0!==o.paint.get("icon-opacity").constantOr(1)&&ir(e,i,o,r,!1,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),o.layout.get("icon-rotation-alignment"),o.layout.get("icon-pitch-alignment"),o.layout.get("icon-keep-upright"),l,c,n),0!==o.paint.get("text-opacity").constantOr(1)&&ir(e,i,o,r,!0,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&(Ko(e,i,o,r,!0),Ko(e,i,o,r,!1));}(e,i,o,r,this.style.placement.variableOffsets,a):t.cc(o)?function(e,i,o,r,a){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:s}=a,n=o.paint.get("circle-opacity"),l=o.paint.get("circle-stroke-width"),c=o.paint.get("circle-stroke-opacity"),h=!o.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Zt.ReadOnly),m=Vt.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let a=0;ae.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:r,layoutVertexBuffer:a,indexBuffer:s,uniformValues:n,terrainData:l,projectionData:c}=t.state;r.draw(u,d.TRIANGLES,p,m,f,Ut.backCCW,n,l,c,o.id,a,s,t.segments,o.paint,e.transform.zoom,i);}}(e,i,o,r,a):t.cd(o)?function(e,i,o,r,a){if(0===o.paint.get("heatmap-opacity"))return;const s=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=a;if(e.style.map.terrain){for(const t of r){const r=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?rr(e,r,o,t,l):"translucent"===e.renderPass&&ar(e,o,t,n,l));}s.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,o,r){const a=e.context,s=a.gl,n=e.transform,l=Vt.disabled,c=new jt([s.ONE,s.ONE],t.bf.transparent,[!0,!0,!0,!0]);((function(e,i,o){const r=e.gl;e.activeTexture.set(r.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let a=o.heatmapFbos.get(t.c2);a?(r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),e.bindFramebuffer.set(a.framebuffer)):(a=sr(e,i.width/4,i.height/4),o.heatmapFbos.set(t.c2,a));}))(a,e,o),a.clear({color:t.bf.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return !1;if(!e.from||!e.to)return !0;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=!1,o=[]){this.cache=this.cache||{};const r=!!this.style.map.terrain,a=this.style.projection,s=i?xt.projectionMercator:a.shaderPreludeCode,n=i?Pt:a.shaderDefine,l=e+(t?t.cacheKey:"")+`/${i?Ct:a.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(r?"/terrain":"")+(o?`/${o.join("/")}`:"");return this.cache[l]||(this.cache[l]=new Si(this.context,xt[e],t,ao[e],this._showOverdrawInspector,r,s,n,o)),this.cache[l]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const e=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function Sr(e,t){let i,o=!1,r=null,a=null;const s=()=>{r=null,o&&(e.apply(a,i),r=setTimeout(s,t),o=!1);};return (...e)=>(o=!0,a=this,i=e,r||s(),r)}class Er{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(!this._isValidHash(e))return !1;const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),!0},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let o=window.location.hash.replace(i,"");o.startsWith("#&")?o=o.slice(0,1)+o.slice(2):"#"===o&&(o="");let r=window.location.href.replace(/(#.+)?$/,o);r=r.replace("&&","&"),window.history.replaceState(window.history.state,null,r);},this._updateHash=Sr(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,o=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),r=Math.pow(10,o),a=Math.round(t.lng*r)/r,s=Math.round(t.lat*r)/r,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${a}/${s}/${i}`:`${i}/${s}/${a}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const o=i.split("=")[0];return o===e?(t=!0,`${o}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return !1;try{new t.S(+e[2],+e[1]);}catch(e){return !1}const i=+e[0],o=+(e[3]||0),r=+(e[4]||0);return i>=this._map.getMinZoom()&&i<=this._map.getMaxZoom()&&o>=-180&&o<=180&&r>=this._map.getMinPitch()&&r<=this._map.getMaxPitch()}}const Rr={linearity:.3,easing:t.cm(0,0,.3,1)},zr=t.e({deceleration:2500,maxSpeed:1400},Rr),Dr=t.e({deceleration:20,maxSpeed:1400},Rr),Ar=t.e({deceleration:1e3,maxSpeed:360},Rr),Lr=t.e({deceleration:1e3,maxSpeed:90},Rr),kr=t.e({deceleration:1e3,maxSpeed:360},Rr);class Fr{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:s.now(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=s.now();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const o=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,r={};if(i.pan.mag()){const a=Or(i.pan.mag(),o,t.e({},zr,e||{})),s=i.pan.mult(a.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(s,this._map.transform);r.center=n.easingCenter,r.offset=n.easingOffset,Br(r,a);}if(i.zoom){const e=Or(i.zoom,o,Dr);r.zoom=this._map.transform.zoom+e.amount,Br(r,e);}if(i.bearing){const e=Or(i.bearing,o,Ar);r.bearing=this._map.transform.bearing+t.ah(e.amount,-179,179),Br(r,e);}if(i.pitch){const e=Or(i.pitch,o,Lr);r.pitch=this._map.transform.pitch+e.amount,Br(r,e);}if(i.roll){const e=Or(i.roll,o,kr);r.roll=this._map.transform.roll+t.ah(e.amount,-179,179),Br(r,e);}if(r.zoom||r.bearing){const e=void 0===i.pinchAround?i.around:i.pinchAround;r.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.e(r,{noMoveStart:!0})}}function Br(e,t){(!e.duration||e.durationi.unproject(e))),l=a.reduce(((e,t,i,o)=>e.add(t.div(o.length))),new t.P(0,0));super(e,{points:a,point:l,lngLats:s,lngLat:i.unproject(l),originalEvent:o}),this._defaultPrevented=!1;}}class Ur extends t.l{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=!1;}}class Zr{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new Ur(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new jr(e.type,this._map,e))}mouseup(e){this._map.fire(new jr(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new jr(e.type,this._map,e));}dblclick(e){return this._firePreventable(new jr(e.type,this._map,e))}mouseover(e){this._map.fire(new jr(e.type,this._map,e));}mouseout(e){this._map.fire(new jr(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Nr(e.type,this._map,e))}touchmove(e){this._map.fire(new Nr(e.type,this._map,e));}touchend(e){this._map.fire(new Nr(e.type,this._map,e));}touchcancel(e){this._map.fire(new Nr(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Gr{constructor(e){this._map=e;}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new jr(e.type,this._map,e));}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new jr("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new jr(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Vr{constructor(e){this._map=e;}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return {lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class $r{constructor(e,t){this._map=e,this._tr=new Vr(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(n.disableDrag(),this._startPos=this._lastPos=t,this._active=!0);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(o,r,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.l(e,{originalEvent:i}))}}function qr(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let o=0;othis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){const i=new t.P(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=qr(o,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const o=qr(i,t);for(const e in this.touches){const t=o[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=!0);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Hr{constructor(e){this.singleTap=new Wr(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const o=this.singleTap.touchend(e,t,i);if(o){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(o)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}}}class Xr{constructor(e){this._tr=new Vr(e),this._zoomIn=new Hr({numTouches:1,numTaps:2}),this._zoomOut=new Hr({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const o=this._zoomIn.touchend(e,t,i),r=this._zoomOut.touchend(e,t,i),a=this._tr;return o?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom+1,around:a.unproject(o)},{originalEvent:e})}):r?(this._active=!0,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:a.zoom-1,around:a.unproject(r)},{originalEvent:e})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class Kr{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=!0,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=!0));}dragMove(e,t){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const o=Array.isArray(t)?t[0]:t;return !this._moved&&o.dist(i)!0}),t=new ta){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t;}_executeRelevantHandler(e,t,i){return e instanceof MouseEvent?t(e):"undefined"!=typeof TouchEvent&&e instanceof TouchEvent?i(e):void 0}startMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.startMove(e)),(e=>this.oneFingerTouchMoveStateManager.startMove(e)));}endMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.endMove(e)),(e=>this.oneFingerTouchMoveStateManager.endMove(e)));}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}const oa=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};class ra{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=!1,this._touches={},this._sum=new t.P(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,o){o.length>0&&(this._active=!0);const r=qr(o,i),a=new t.P(0,0),s=new t.P(0,0);let n=0;for(const e in r){const t=r[e],i=this._touches[e];i&&(a._add(t),s._add(t.sub(i)),n++,r[e]=t);}if(this._touches=r,this._shouldBePrevented(n)||!s.mag())return;const l=s.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class da extends aa{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,ua(e[0].sub(e[1]))&&(this._valid=!1);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const o=e[0].sub(this._lastPoints[0]),r=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),this._valid?(this._lastPoints=e,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5}):void 0}gestureBeginsVertically(e,t,i){if(void 0!==this._valid)return this._valid;const o=e.mag()>=2,r=t.mag()>=2;if(!o&&!r)return;if(!o||!r)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const a=e.y>0==t.y>0;return ua(e)&&ua(t)&&a}}const _a={panStep:100,bearingStep:15,pitchStep:10};class pa{constructor(e){this._tr=new Vr(e);const t=_a;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=!1;}reset(){this._active=!1;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,o=0,r=0,a=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),r=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),r=1);break;case 38:e.shiftKey?o=1:(e.preventDefault(),a=-1);break;case 40:e.shiftKey?o=-1:(e.preventDefault(),a=1);break;default:return}return this._rotationDisabled&&(i=0,o=0),{cameraAnimation:s=>{const n=this._tr;s.easeTo({duration:300,easeId:"keyboardHandler",easing:ma,zoom:t?Math.round(n.zoom)+t*(e.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+o*this._pitchStep,offset:[-r*this._panStep,-a*this._panStep],center:n.center},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function ma(e){return e*(2-e)}const fa=4.000244140625,ga=1/450;class va{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new Vr(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=ga;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=!1);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=s.now(),o=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%fa==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":o>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(o*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=n.mousePos(this._map.getCanvas(),e),o=this._tr;this._aroundPoint=this._aroundCenter?o.transform.locationToScreenPoint(t.S.convert(o.center)):i,this._frameId||(this._frameId=!0,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>fa?this._wheelZoomRate:this._defaultZoomRate;let o=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==o&&(o=1/o);const r="number"!=typeof this._targetZoom?e.scale:t.af(this._targetZoom);this._targetZoom=e.getConstrained(e.getCameraLngLat(),t.ak(r*o)).zoom,"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,o=this._startZoom,r=this._easing;let a,n=!1;if("wheel"===this._type&&o&&r){const e=s.now()-this._lastWheelEventTime,l=Math.min((e+5)/200,1),c=r(l);a=t.C.number(o,i,c),l<1?this._frameId||(this._frameId=!0):n=!0;}else a=i,n=!0;return this._active=!0,n&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=a,{noInertia:!0,needsRenderFrame:!n,zoomDelta:a-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.co;if(this._prevEase){const e=this._prevEase,o=(s.now()-e.start)/e.duration,r=e.easing(o+.01)-e.easing(o),a=.27/Math.sqrt(r*r+1e-4)*.01,n=Math.sqrt(.0729-a*a);i=t.cm(a,n,.25,1);}return this._prevEase={start:s.now(),duration:e,easing:i},i}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class ba{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class xa{constructor(e){this._tr=new Vr(e),this.reset();}reset(){this._active=!1;}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ya{constructor(){this._tap=new Hr({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const o=t[0],r=e.timeStamp-this._tapTime<500,a=this._tapPoint.dist(o)<30;r&&a?i.length>0&&(this._swipePoint=o,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const o=t[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,e.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const o=this._tap.touchend(e,t,i);o&&(this._tapTime=e.timeStamp,this._tapPoint=o);}}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class wa{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Ta{constructor(e,t,i,o){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=o;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class Pa{constructor(e,t,i,o){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class Ca{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=!1;}isActive(){return !1}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=n.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),o=document.createElement("div");o.className="maplibregl-desktop-message",o.textContent=t,this._container.appendChild(o);const r=document.createElement("div");r.className="maplibregl-mobile-message",r.textContent=i,this._container.appendChild(r),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(n.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=!0;}disable(){this._enabled=!1,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.l("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const Ia=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class Ma extends t.l{}function Sa(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class Ea{constructor(e,i){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,i)=>{if("blur"===e.type)return void this.stop(!0);this._updatingCamera=!0;const o="renderFrame"===e.type?void 0:e,r={needsRenderFrame:!1},a={},s={};for(const{handlerName:l,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let u;if(this._blockedByActive(s,h,l))c.reset();else if(c[i||e.type]){if(t.cp(e,i||e.type)){const t=n.mousePos(this._map.getCanvas(),e);u=c[i||e.type](e,t);}else if(t.cq(e,i||e.type)){const t=this._getMapTouches(e.touches),o=n.touchPos(this._map.getCanvas(),t);u=c[i||e.type](e,o,t);}else t.cr(i||e.type)||(u=c[i||e.type](e));this.mergeHandlerResult(r,a,u,l,o),u&&u.needsRenderFrame&&this._triggerRenderFrame();}(u||c.isActive())&&(s[l]=c);}const l={};for(const e in this._previousActiveHandlers)s[e]||(l[e]=o);this._previousActiveHandlers=s,(Object.keys(l).length||Sa(r))&&(this._changes.push([r,a,l]),this._triggerRenderFrame()),(Object.keys(s).length||Sa(r))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:c}=r;c&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],c(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Fr(e),this._bearingSnap=i.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(i);const o=this._el;this._listeners=[[o,"touchstart",{passive:!0}],[o,"touchmove",{passive:!1}],[o,"touchend",void 0],[o,"touchcancel",void 0],[o,"mousedown",void 0],[o,"mousemove",void 0],[o,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[o,"mouseover",void 0],[o,"mouseout",void 0],[o,"dblclick",void 0],[o,"click",void 0],[o,"keydown",{capture:!1}],[o,"keyup",void 0],[o,"wheel",{passive:!1}],[o,"contextmenu",void 0],[window,"blur",void 0]];for(const[e,t,i]of this._listeners)n.addEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)n.removeEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const i=this._map,o=i.getCanvasContainer();this._add("mapEvent",new Zr(i,e));const r=i.boxZoom=new $r(i,e);this._add("boxZoom",r),e.interactive&&e.boxZoom&&r.enable();const a=i.cooperativeGestures=new Ca(i,e.cooperativeGestures);this._add("cooperativeGestures",a),e.cooperativeGestures&&a.enable();const s=new Xr(i),l=new xa(i);i.doubleClickZoom=new ba(l,s),this._add("tapZoom",s),this._add("clickZoom",l),e.interactive&&e.doubleClickZoom&&i.doubleClickZoom.enable();const c=new ya;this._add("tapDragZoom",c);const h=i.touchPitch=new da(i);this._add("touchPitch",h),e.interactive&&e.touchPitch&&i.touchPitch.enable(e.touchPitch);const u=()=>i.project(i.getCenter()),d=function({enable:e,clickTolerance:i,aroundCenter:o=!0,minPixelCenterThreshold:r=100,rotateDegreesPerPixelMoved:a=.8},s){const l=new ea({checkCorrectEvent:e=>0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:i,move:(e,i)=>{const n=s();if(o&&Math.abs(n.y-e.y)>r)return {bearingDelta:t.cn(new t.P(e.x,i.y),i,n)};let l=(i.x-e.x)*a;return o&&i.y0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)});return new Kr({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:o,enable:e,assignEvents:oa})}(e),p=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3},o){const r=new ea({checkCorrectEvent:e=>2===n.mouseButton(e)&&e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>{const r=o();let a=(t.x-e.x)*i;return t.y0===n.mouseButton(e)&&!e.ctrlKey});return new Kr({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:!0,moveStateManager:i,enable:e,assignEvents:oa})}(e),f=new ra(e,i);i.dragPan=new wa(o,m,f),this._add("mousePan",m),this._add("touchPan",f,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&i.dragPan.enable(e.dragPan);const g=new ha,v=new la;i.touchZoomRotate=new Pa(o,v,g,c),this._add("touchRotate",g,["touchPan","touchZoom"]),this._add("touchZoom",v,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&i.touchZoomRotate.enable(e.touchZoomRotate);const b=i.scrollZoom=new va(i,(()=>this._triggerRenderFrame()));this._add("scrollZoom",b,["mousePan"]),e.interactive&&e.scrollZoom&&i.scrollZoom.enable(e.scrollZoom);const x=i.keyboard=new pa(i);this._add("keyboard",x),e.interactive&&e.keyboard&&i.keyboard.enable(),this._add("blockableMapEvent",new Gr(i));}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(Ia(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const o in e)if(o!==i&&(!t||t.indexOf(o)<0))return !0;return !1}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,o,r,a){if(!o)return;t.e(e,o);const s={handlerName:r,originalEvent:o.originalEvent||a};void 0!==o.zoomDelta&&(i.zoom=s),void 0!==o.panDelta&&(i.drag=s),void 0!==o.rollDelta&&(i.roll=s),void 0!==o.pitchDelta&&(i.pitch=s),void 0!==o.bearingDelta&&(i.rotate=s);}_applyChanges(){const e={},i={},o={};for(const[r,a,s]of this._changes)r.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(r.panDelta)),r.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+r.zoomDelta),r.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+r.bearingDelta),r.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+r.pitchDelta),r.rollDelta&&(e.rollDelta=(e.rollDelta||0)+r.rollDelta),void 0!==r.around&&(e.around=r.around),void 0!==r.pinchAround&&(e.pinchAround=r.pinchAround),r.noInertia&&(e.noInertia=r.noInertia),t.e(i,a),t.e(o,s);this._updateMapTransform(e,i,o),this._changes=[];}_updateMapTransform(e,t,i){const o=this._map,r=o._getTransformForUpdate(),a=o.terrain;if(!(Sa(e)||a&&this._terrainMovement))return this._fireEvents(t,i,!0);o._stop(!0);let{panDelta:s,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;void 0!==d&&(u=d),u=u||o.transform.centerPoint,a&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const _={panDelta:s,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!r.isPointOnMapSurface(u)&&(u=r.centerPoint);const p=u.distSqr(r.centerPoint)<.01?r.center:r.screenPointToLocation(s?u.sub(s):u);a?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._terrainMovement||!t.drag&&!t.zoom?t.drag&&this._terrainMovement?r.setCenter(r.screenPointToLocation(r.centerPoint.sub(s))):this._map.cameraHelper.handleMapControlsPan(_,r,p):(this._terrainMovement=!0,this._map._elevationFreeze=!0,this._map.cameraHelper.handleMapControlsPan(_,r,p))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,r),this._map.cameraHelper.handleMapControlsPan(_,r,p)),o._applyUpdatedTransform(r),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,!0);}_fireEvents(e,i,o){const r=Ia(this._eventsInProgress),a=Ia(e),n={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(n[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!r&&a&&this._fireEvent("movestart",a.originalEvent);for(const e in n)this._fireEvent(e,n[e]);a&&this._fireEvent("move",a.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const l={};let c;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:o}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],c=i[t]||o,l[`${e}end`]=c);}for(const e in l)this._fireEvent(e,l[e]);const h=Ia(this._eventsInProgress),u=(r||a)&&!h;if(u&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(o&&u){this._updatingCamera=!0;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new Ma("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}class Ra extends t.E{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((s.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=!1,this._zooming=!1,this.transform=e,this._bearingSnap=i.bearingSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.S(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,o){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},i),o)}panTo(e,i,o){return this.easeTo(t.e({center:e},i),o)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,o){return this.easeTo(t.e({zoom:e},i),o)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.l("movestart",i)).fire(new t.l("move",i)).fire(new t.l("moveend",i))),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,o){return this.easeTo(t.e({bearing:e},i),o)}resetNorth(e,i){return this.rotateTo(0,t.e({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){f.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,o={}){this._moving=!0,i||o.moving||this.fire(new t.l("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.l("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.l("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.l("pitchstart",e)),this._rolling&&!o.rolling&&this.fire(new t.l("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=!0;}_updateElevation(e){void 0!==this._elevationStart&&void 0!==this._elevationCenter||this._prepareElevation(this.transform.center),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.C.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),o=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:o,zoom:r,roll:a,pitch:s,bearing:n,elevation:l}=e(t);o&&t.setCenter(o),void 0!==l&&t.setElevation(l),void 0!==r&&t.setZoom(r),void 0!==a&&t.setRoll(a),void 0!==s&&t.setPitch(s),void 0!==n&&t.setBearing(n),i.apply(t);}this.transform.apply(i);}_fireMoveEvents(e){this.fire(new t.l("move",e)),this._zooming&&this.fire(new t.l("zoom",e)),this._rotating&&this.fire(new t.l("rotate",e)),this._pitching&&this.fire(new t.l("pitch",e)),this._rolling&&this.fire(new t.l("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const o=this._zooming,r=this._rotating,a=this._pitching,s=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,o&&this.fire(new t.l("zoomend",e)),r&&this.fire(new t.l("rotateend",e)),a&&this.fire(new t.l("pitchend",e)),s&&this.fire(new t.l("rollend",e)),this.fire(new t.l("moveend",e));}flyTo(e,i){if(!e.essential&&s.prefersReducedMotion){const o=t.Q(e,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(o,i)}this.stop(),e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.co},e);const o=this._getTransformForUpdate(),r=o.bearing,a=o.pitch,n=o.roll,l=o.padding,c="bearing"in e?this._normalizeBearing(e.bearing,r):r,h="pitch"in e?+e.pitch:a,u="roll"in e?this._normalizeBearing(e.roll,n):n,d="padding"in e?e.padding:o.padding,_=t.P.convert(e.offset);let p=o.centerPoint.add(_);const m=o.screenPointToLocation(p),f=this.cameraHelper.handleFlyTo(o,{bearing:c,pitch:h,roll:u,padding:d,locationAtOffset:m,offsetAsPoint:_,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(o.width,o.height),b=v/f.scaleOfZoom,x=f.pixelPathLength;"number"==typeof f.scaleOfMinZoom&&(g=Math.sqrt(v/f.scaleOfMinZoom/x*2));const y=g*g;function w(e){const t=(b*b-v*v+(e?-1:1)*y*y*x*x)/(2*(e?b:v)*y*x);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function P(e){return (Math.exp(e)+Math.exp(-e))/2}const C=w(!1);let I=function(e){return P(C)/P(C+g*e)},M=function(e){return v*((P(C)*(T(t=C+g*e)/P(t))-T(C))/y)/x;var t;},S=(w(!0)-C)/g;if(Math.abs(x)<2e-6||!isFinite(S)){if(Math.abs(v-b)<1e-6)return this.easeTo(e,i);const t=b0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*S/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=r!==c,this._pitching=h!==a,this._rolling=u!==n,this._padding=!o.isPaddingEqual(d),this._prepareEase(i,!1),this.terrain&&this._prepareElevation(f.targetCenter),this._ease((s=>{const m=s*S,g=1/I(m),v=M(m);this._rotating&&o.setBearing(t.C.number(r,c,s)),this._pitching&&o.setPitch(t.C.number(a,h,s)),this._rolling&&o.setRoll(t.C.number(n,u,s)),this._padding&&(o.interpolatePadding(l,d,s),p=o.centerPoint.add(_)),f.easeFunc(s,g,v,p),this.terrain&&!e.freezeElevation&&this._updateElevation(s),this._applyUpdatedTransform(o),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(e,t,i){!1===i.animate||0===i.duration?(e(1),t()):(this._easeStart=s.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.aO(e,-180,180);const o=Math.abs(e-i);return Math.abs(e-360-i)MapLibre'};class Da{constructor(e=za){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=n.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=n.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=n.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.sourceCaches;for(const i in t){const o=t[i];if(o.used||o.usedForTerrain){const t=o.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let o=i+1;o=0)return !1;return !0}));const i=e.join(" | ");i!==this._attribHTML&&(this._attribHTML=i,e.length?(this._innerContainer.innerHTML=n.sanitize(i),this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Aa{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=n.create("div","maplibregl-ctrl");const t=n.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){n.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0;}}class La{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:!1}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=!0)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}var ka=t.aJ([{name:"a_pos3d",type:"Int16",components:3}]);class Fa extends t.E{constructor(e){super(),this._lastTilesetChange=s.now(),this.sourceCache=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=!0,e.tileSize=this.tileSize;}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null;}update(e,i){this.sourceCache.update(e,i),this._renderableTilesKeys=[];const o={};for(const r of ve(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:i,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))o[r.key]=!0,this._renderableTilesKeys.push(r.key),this._tiles[r.key]||(r.terrainRttPosMatrix32f=new Float64Array(16),t.bY(r.terrainRttPosMatrix32f,0,t.$,t.$,0,0,1),this._tiles[r.key]=new re(r,this.tileSize),this._lastTilesetChange=s.now());for(const e in this._tiles)o[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e,t){return t?this._getTerrainCoordsForTileRanges(e,t):this._getTerrainCoordsForRegularTile(e)}_getTerrainCoordsForRegularTile(e){const i={};for(const o of this._renderableTilesKeys){const r=this._tiles[o].tileID,a=e.clone(),s=t.ba();if(r.canonical.equals(e.canonical))t.bY(s,0,t.$,t.$,0,0,1);else if(r.canonical.isChildOf(e.canonical)){const i=r.canonical.z-e.canonical.z,o=r.canonical.x-(r.canonical.x>>i<>i<>i;t.bY(s,0,n,n,0,0,1),t.M(s,s,[-o*n,-a*n,0]);}else {if(!e.canonical.isChildOf(r.canonical))continue;{const i=e.canonical.z-r.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i;t.bY(s,0,t.$,t.$,0,0,1),t.M(s,s,[o*n,a*n,0]),t.N(s,s,[1/2**i,1/2**i,0]);}}a.terrainRttPosMatrix32f=new Float32Array(s),i[o]=a;}return i}_getTerrainCoordsForTileRanges(e,i){const o={};for(const r of this._renderableTilesKeys){const a=this._tiles[r].tileID;if(!this._isWithinTileRanges(a,i))continue;const s=e.clone(),n=t.ba();if(a.canonical.z===e.canonical.z){const i=e.canonical.x-a.canonical.x,o=e.canonical.y-a.canonical.y;t.bY(n,0,t.$,t.$,0,0,1),t.M(n,n,[i*t.$,o*t.$,0]);}else if(a.canonical.z>e.canonical.z){const i=a.canonical.z-e.canonical.z,o=a.canonical.x-(a.canonical.x>>i<>i<>i),l=e.canonical.y-(a.canonical.y>>i),c=t.$>>i;t.bY(n,0,c,c,0,0,1),t.M(n,n,[-o*c+s*t.$,-r*c+l*t.$,0]);}else {const i=e.canonical.z-a.canonical.z,o=e.canonical.x-(e.canonical.x>>i<>i<>i)-a.canonical.x,l=(e.canonical.y>>i)-a.canonical.y,c=t.$<i.maxzoom&&(o=i.maxzoom),o=i.minzoom&&(!r||!r.dem);)r=this.sourceCache.getTileByID(e.scaledTo(o--).key);return r}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}_isWithinTileRanges(e,t){return t[e.canonical.z]&&e.canonical.x>=t[e.canonical.z].minTileX&&e.canonical.x<=t[e.canonical.z].maxTileX&&e.canonical.y>=t[e.canonical.z].minTileY&&e.canonical.y<=t[e.canonical.z].maxTileY}}class Ba{constructor(e,t,i){this._meshCache={},this.painter=e,this.sourceCache=new Fa(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(e,i,o,r=t.$){var a;if(!(i>=0&&i=0&&oe.canonical.z&&(e.canonical.z>=o?r=e.canonical.z-o:t.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const a=e.canonical.x-(e.canonical.x>>r<>r<>8<<4|e>>8,i[t+3]=0;const o=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),r=new t.T(e,o,e.gl.RGBA,{premultiply:!1});return r.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=r,r}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(!0);const i=new Uint8Array(4),o=this.painter.context,r=o.gl,a=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),s=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);o.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),r.readPixels(a,n-s-1,1,1,r.RGBA,r.UNSIGNED_BYTE,i),o.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.sourceCache.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<0,r=o&&0===e.canonical.y,a=o&&e.canonical.y===(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=!1;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const ja={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0,"color-relief":!0};class Na{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new Oa(e.context,30,t.sourceCache.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.sourceCaches){this._coordsAscending[t]={};const i=e.sourceCaches[t].getVisibleCoordinates(),o=e.sourceCaches[t].getSource(),r=o instanceof X?o.terrainTileRanges:null;for(const e of i){const i=this.terrain.sourceCache.getTerrainCoords(e,r);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._coordsAscendingStr={};for(const t of e._order){const i=e._layers[t],o=i.source;if(ja[i.type]&&!this._coordsAscendingStr[o]){this._coordsAscendingStr[o]={};for(const e in this._coordsAscending[o])this._coordsAscendingStr[o][e]=this._coordsAscending[o][e].map((e=>e.key)).sort().join();}}for(const e of this._renderableTiles)for(const t in this._coordsAscendingStr){const i=this._coordsAscendingStr[t][e.tileID.key];i&&i!==e.rttCoords[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return !1;const o=Object.assign(Object.assign({},i),{isRenderingToTexture:!0}),r=e.type,a=this.painter,s=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(ja[r]&&(this._prevType&&ja[this._prevType]||this._stacks.push([]),this._prevType=r,this._stacks[this._stacks.length-1].push(e.id),!s))return !0;if(ja[this._prevType]||ja[r]&&s){this._prevType=r;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const r of this._renderableTiles){if(this.pool.isFull()&&(Cr(this.painter,this.terrain,this._rttTiles,o),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(r),r.rtt[e]){const t=this.pool.getObjectForId(r.rtt[e].id);if(t.stamp===r.rtt[e].stamp){this.pool.useObject(t);continue}}const s=this.pool.getOrCreateFreeObject();this.pool.useObject(s),this.pool.stampObject(s),r.rtt[e]={id:s.id,stamp:s.stamp},a.context.bindFramebuffer.set(s.fbo.framebuffer),a.context.clear({color:t.bf.transparent,stencil:0}),a.currentStencilSource=void 0;for(let e=0;e{this.startMove(e,n.mousePos(this.element,e)),n.addEventListener(window,"mousemove",this.mousemove),n.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=e=>{this.move(e,n.mousePos(this.element,e));},this.mouseup=e=>{this._rotatePitchHandler.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),n.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.addEventListener(window,"touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHandler.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10,this.element=i;const r=new ia;this._rotatePitchHandler=new Kr({clickTolerance:3,move:(e,r)=>{const a=i.getBoundingClientRect(),s=new t.P((a.bottom-a.top)/2,(a.right-a.left)/2);return {bearingDelta:t.cn(new t.P(e.x,r.y),r,s),pitchDelta:o?-.5*(r.y-e.y):void 0}},moveStateManager:r,enable:!0,assignEvents:()=>{}}),this.map=e,n.addEventListener(i,"mousedown",this.mousedown),n.addEventListener(i,"touchstart",this.touchstart,{passive:!1}),n.addEventListener(i,"touchcancel",this.reset);}startMove(e,t){this._rotatePitchHandler.dragStart(e,t),n.disableDrag();}move(e,t){const i=this.map,{bearingDelta:o,pitchDelta:r}=this._rotatePitchHandler.dragMove(e,t)||{};o&&i.setBearing(i.getBearing()+o),r&&i.setPitch(i.getPitch()+r);}off(){const e=this.element;n.removeEventListener(e,"mousedown",this.mousedown),n.removeEventListener(e,"touchstart",this.touchstart,{passive:!1}),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend),n.removeEventListener(e,"touchcancel",this.reset),this.offTemp();}offTemp(){n.enableDrag(),n.removeEventListener(window,"mousemove",this.mousemove),n.removeEventListener(window,"mouseup",this.mouseup),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend);}}let qa;function Wa(e,i,o,r=!1){if(r||!o.getCoveringTilesDetailsProvider().allowWorldCopies())return null==e?void 0:e.wrap();const a=new t.S(e.lng,e.lat);if(e=new t.S(e.lng,e.lat),i){const r=new t.S(e.lng-360,e.lat),a=new t.S(e.lng+360,e.lat),s=o.locationToScreenPoint(e).distSqr(i);o.locationToScreenPoint(r).distSqr(i)180;){const t=o.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=o.width&&t.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==a.lng&&o.isPointOnMapSurface(o.locationToScreenPoint(e))?e:a}const Ha={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Xa(e,t,i){const o=e.classList;for(const e in Ha)o.remove(`maplibregl-${i}-anchor-${e}`);o.add(`maplibregl-${i}-anchor-${t}`);}class Ka extends t.E{constructor(e){if(super(),this._onKeyPress=e=>{const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{if(!this._map)return;const t=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?void 0:e.type)||"render"===(null==e?void 0:e.type)&&!t)&&this._map.once("render",this._update),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let i="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?i=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(i=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),n.setTransform(this._element,`${Ha[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${i}`),s.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.l("dragstart"))),this.fire(new t.l("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.l("dragend")),this._state="inactive";},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||!1,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(null==e?void 0:e.opacity,null==e?void 0:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.P.convert(e&&e.offset||[0,0]);else {this._defaultMarker=!0,this._element=n.create("div");const i=n.createNS("http://www.w3.org/2000/svg","svg"),o=41,r=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${o}px`),i.setAttributeNS(null,"width",`${r}px`),i.setAttributeNS(null,"viewBox",`0 0 ${r} ${o}`);const a=n.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"stroke","none"),a.setAttributeNS(null,"stroke-width","1"),a.setAttributeNS(null,"fill","none"),a.setAttributeNS(null,"fill-rule","evenodd");const s=n.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"fill-rule","nonzero");const l=n.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"transform","translate(3.0, 29.0)"),l.setAttributeNS(null,"fill","#000000");const c=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const e of c){const t=n.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),l.appendChild(t);}const h=n.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);const u=n.createNS("http://www.w3.org/2000/svg","path");u.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(u);const d=n.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");const _=n.createNS("http://www.w3.org/2000/svg","path");_.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(_);const p=n.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const m=n.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(8.0, 8.0)");const f=n.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#000000"),f.setAttributeNS(null,"opacity","0.25"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962");const g=n.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#FFFFFF"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962"),m.appendChild(f),m.appendChild(g),s.appendChild(l),s.appendChild(h),s.appendChild(d),s.appendChild(p),s.appendChild(m),i.appendChild(s),i.setAttributeNS(null,"height",o*this._scale+"px"),i.setAttributeNS(null,"width",r*this._scale+"px"),this._element.appendChild(i),this._offset=t.P.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),Xa(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),n.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,o=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-t],"bottom-left":[o,-1*(t-i+o)],"bottom-right":[-o,-1*(t-i+o)],left:[i,-1*(t-i)],right:[-i,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=!1){var i,o;const r=null===(i=this._map)||void 0===i?void 0:i.terrain,a=this._map.transform.isLocationOccluded(this._lngLat);if(!r||a){const e=a?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const s=this._map,n=s.terrain.depthAtPoint(this._pos),l=s.terrain.getElevationForLngLatZoom(this._lngLat,s.transform.tileZoom);if(s.transform.lngLatToCameraDepth(this._lngLat,l)-n<.006)return void(this._element.style.opacity=this._opacity);const c=-this._offset.y/s.transform.pixelsPerMeter,h=Math.sin(s.getPitch()*Math.PI/180)*c,u=s.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),d=s.transform.lngLatToCameraDepth(this._lngLat,l+h)-u>.006;(null===(o=this._popup)||void 0===o?void 0:o.isOpen())&&d&&this._popup.remove(),this._element.style.opacity=d?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return (void 0===this._opacity||void 0===e&&void 0===t)&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==e&&(this._opacity=e),void 0!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(!0),this}}const Ya={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let Qa=0,Ja=!1;const es={maxWidth:100,unit:"metric"};function ts(e,t,i){const o=i&&i.maxWidth||100,r=e._container.clientHeight/2,a=e._container.clientWidth/2,s=e.unproject([a-o/2,r]),n=e.unproject([a+o/2,r]),l=Math.round(e.project(n).x-e.project(s).x),c=Math.min(o,l,e._container.clientWidth),h=s.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?is(t,c,i/5280,e._getUIString("ScaleControl.Miles")):is(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?is(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?is(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):is(t,c,h,e._getUIString("ScaleControl.Meters"));}function is(e,t,i,o){const r=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(r/i)+"px",e.innerHTML=`${r} ${o}`;}const os={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1,locationOccludedOpacity:void 0},rs=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function as(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(i,i),"top-right":new t.P(-i,i),bottom:new t.P(0,-e),"bottom-left":new t.P(i,-i),"bottom-right":new t.P(-i,-i),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){const i=t.P.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e["top-left"]||[0,0]),"top-right":t.P.convert(e["top-right"]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e["bottom-left"]||[0,0]),"bottom-right":t.P.convert(e["bottom-right"]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return as(new t.P(0,0))}const ss=i;e.AJAXError=t.cz,e.Event=t.l,e.Evented=t.E,e.LngLat=t.S,e.MercatorCoordinate=t.a1,e.Point=t.P,e.addProtocol=t.cA,e.config=t.a,e.removeProtocol=t.cB,e.AttributionControl=Da,e.BoxZoomHandler=$r,e.CanvasSource=Y,e.CooperativeGesturesHandler=Ca,e.DoubleClickZoomHandler=ba,e.DragPanHandler=wa,e.DragRotateHandler=Ta,e.EdgeInsets=Mt,e.FullscreenControl=class extends t.E{constructor(e={}){super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(e=null==t?void 0:t.shadowRoot)||void 0===e?void 0:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=!1,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){n.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=n.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);n.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new t.l("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.l("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=H,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.l("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "BACKGROUND":case "BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.l("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.S(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.e({bearing:r},this.options.fitBoundsOptions),s=G.fromLngLat(i,o);this._map.fitBounds(s,a,{geolocateSource:!0});},this._updateMarker=e=>{if(e){const i=new t.S(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this._updateCircleRadiusIfNeeded();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onUpdate=()=>{this._updateCircleRadiusIfNeeded();},this._onError=e=>{if(this._map){if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Ja)return;this.options.trackUserLocation&&this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.l("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=n.create("button","maplibregl-ctrl-geolocate",this._container),n.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0);},this._finishSetupUI=e=>{if(this._map){if(!1===e){t.w("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=n.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new Ka({element:this._dotElement}),this._circleElement=n.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ka({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onUpdate),this._map.on("move",this._onUpdate),this._map.on("rotate",this._onUpdate),this._map.on("pitch",this._onUpdate)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(e=>{const i=(null==e?void 0:e[0])instanceof ResizeObserverEntry;e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||i||this._map.isZooming()||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.l("trackuserlocationend")),this.fire(new t.l("userlocationlostfocus")));}));}},this.options=t.e({},Ya,e);}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t._(this,arguments,void 0,(function*(e=!1){if(void 0!==qa&&!e)return qa;if(void 0===window.navigator.permissions)return qa=!!window.navigator.geolocation,qa;try{const e=yield window.navigator.permissions.query({name:"geolocation"});qa="denied"!==e.state;}catch(e){qa=!!window.navigator.geolocation;}return qa}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),n.remove(this._container),this._map.off("zoom",this._onUpdate),this._map.off("move",this._onUpdate),this._map.off("rotate",this._onUpdate),this._map.off("pitch",this._onUpdate),this._map=void 0,Qa=0,Ja=!1;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case "WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case "ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case "ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadiusIfNeeded(){const e=this._userLocationDotMarker.getLngLat();if(!(this.options.showUserLocation&&this.options.showAccuracyCircle&&this._accuracy&&e))return;const t=this._map.project(e),i=this._map.unproject([t.x+100,t.y]),o=e.distanceTo(i)/100,r=2*this._accuracy/o;this._circleElement.style.width=`${r.toFixed(2)}px`,this._circleElement.style.height=`${r.toFixed(2)}px`;}trigger(){if(!this._setup)return t.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case "OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.l("trackuserlocationstart"));break;case "WAITING_ACTIVE":case "ACTIVE_LOCK":case "ACTIVE_ERROR":case "BACKGROUND_ERROR":Qa--,Ja=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new t.l("trackuserlocationend"));break;case "BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.l("trackuserlocationstart")),this.fire(new t.l("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case "WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case "OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),Qa++,Qa>1?(e={maximumAge:6e5,timeout:0},Ja=!0):(e=this.options.positionOptions,Ja=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||void 0===e?void 0:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||void 0===e?void 0:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=n.create("button","maplibregl-ctrl-globe",this._container),n.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0;}},e.Hash=Er,e.ImageSource=X,e.KeyboardHandler=pa,e.LngLatBounds=G,e.LogoControl=Aa,e.Map=class extends Ra{constructor(e){var i,o;t.cw.mark(t.cx.create);const r=Object.assign(Object.assign(Object.assign({},Ga),e),{canvasContextAttributes:Object.assign(Object.assign({},Ga.canvasContextAttributes),e.canvasContextAttributes)});if(null!=r.minZoom&&null!=r.maxZoom&&r.minZoom>r.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=r.minPitch&&null!=r.maxPitch&&r.minPitch>r.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=r.minPitch&&r.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=r.maxPitch&&r.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const a=new Lt,s=new Ot;if(void 0!==r.minZoom&&a.setMinZoom(r.minZoom),void 0!==r.maxZoom&&a.setMaxZoom(r.maxZoom),void 0!==r.minPitch&&a.setMinPitch(r.minPitch),void 0!==r.maxPitch&&a.setMaxPitch(r.maxPitch),void 0!==r.renderWorldCopies&&a.setRenderWorldCopies(r.renderWorldCopies),super(a,s,{bearingSnap:r.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new La,this._controls=[],this._mapId=t.a7(),this._contextLost=e=>{e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new t.l("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._setupPainter(),this.resize(),this._update(),this.fire(new t.l("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update();},this._interactive=r.interactive,this._maxTileCacheSize=r.maxTileCacheSize,this._maxTileCacheZoomLevels=r.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},r.canvasContextAttributes),this._trackResize=!0===r.trackResize,this._bearingSnap=r.bearingSnap,this._centerClampedToGround=r.centerClampedToGround,this._refreshExpiredTiles=!0===r.refreshExpiredTiles,this._fadeDuration=r.fadeDuration,this._crossSourceCollisions=!0===r.crossSourceCollisions,this._collectResourceTiming=!0===r.collectResourceTiming,this._locale=Object.assign(Object.assign({},Ua),r.locale),this._clickTolerance=r.clickTolerance,this._overridePixelRatio=r.pixelRatio,this._maxCanvasSize=r.maxCanvasSize,this.transformCameraUpdate=r.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===r.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=p.addThrottleControl((()=>this.isMoving())),this._requestManager=new m(r.transformRequest),"string"==typeof r.container){if(this._container=document.getElementById(r.container),!this._container)throw new Error(`Container '${r.container}' not found.`)}else {if(!(r.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=r.container;}if(r.maxBounds&&this.setMaxBounds(r.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0);})),this.once("idle",(()=>{this._idleTriggered=!0;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let e=!1;const t=Sr((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{e?t(i):e=!0;})),this._resizeObserver.observe(this._container);}this.handlers=new Ea(this,r),this._hash=r.hash&&new Er("string"==typeof r.hash&&r.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:r.center,elevation:r.elevation,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,roll:r.roll}),r.bounds&&(this.resize(),this.fitBounds(r.bounds,t.e({},r.fitBoundsOptions,{duration:0}))));const n="string"==typeof r.style||!("globe"===(null===(o=null===(i=r.style)||void 0===i?void 0:i.projection)||void 0===o?void 0:o.type));this.resize(null,n),this._localIdeographFontFamily=r.localIdeographFontFamily,this._validateStyle=r.validateStyle,r.style&&this.setStyle(r.style,{localIdeographFontFamily:r.localIdeographFontFamily}),r.attributionControl&&this.addControl(new Da("boolean"==typeof r.attributionControl?void 0:r.attributionControl)),r.maplibreLogo&&this.addControl(new Aa,r.logoPosition),this.on("style.load",(()=>{if(n||this._resizeTransform(),this.transform.unmodified){const e=t.Q(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.l(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.l(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.l("sourcedataabort",e));}));}_getMapId(){return this._mapId}setGlobalStateProperty(e,t){return this.style.setGlobalStateProperty(e,t),this._update(!0)}getGlobalState(){return this.style.getGlobalState()}addControl(e,i){if(void 0===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.k(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const o=e.onAdd(this);this._controls.push(e);const r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.k(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}coveringTiles(e){return ve(this.transform,e)}calculateCameraOptionsFromTo(e,t,i,o){return null==o&&this.terrain&&(o=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(e,t,i,o)}resize(e,i=!0){const[o,r]=this._containerDimensions(),a=this._getClampedPixelRatio(o,r);if(this._resizeCanvas(o,r,a),this.painter.resize(o,r,a),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const t=this._getClampedPixelRatio(o,r);this._resizeCanvas(o,r,t),this.painter.resize(o,r,t);}this._resizeTransform(i);const s=!this._moving;return s&&(this.stop(),this.fire(new t.l("movestart",e)).fire(new t.l("move",e))),this.fire(new t.l("resize",e)),s&&this.fire(new t.l("moveend",e)),this}_resizeTransform(e=!0){var t;const[i,o]=this._containerDimensions();this.transform.resize(i,o,e),null===(t=this._requestedCameraState)||void 0===t||t.resize(i,o,e);}_getClampedPixelRatio(e,t){const{0:i,1:o}=this._maxCanvasSize,r=this.getPixelRatio(),a=e*r,s=t*r;return Math.min(a>i?i/a:1,s>o?o/s:1)*r}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&void 0!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(G.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom)return this.transform.setMinZoom(e),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(e),this._update(),this.getZoom()>e&&this.setZoom(e),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.setMinPitch(e),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch)return this.transform.setMaxPitch(e),this._update(),this.getPitch()>e&&this.setPitch(e),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.S.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||void 0===e?void 0:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||void 0===e?void 0:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||void 0===e?void 0:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e))),s=0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[];s.length?o||(o=!0,i.call(this,new jr(e,this,r.originalEvent,{features:s}))):o=!1;};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:()=>{o=!1;}}}}if("mouseleave"===e||"mouseout"===e){let o=!1;const r=r=>{const a=t.filter((e=>this.getLayer(e)));(0!==a.length?this.queryRenderedFeatures(r.point,{layers:a}):[]).length?o=!0:o&&(o=!1,i.call(this,new jr(e,this,r.originalEvent)));},a=t=>{o&&(o=!1,i.call(this,new jr(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:r,mouseout:a}}}{const o=e=>{const o=t.filter((e=>this.getLayer(e))),r=0!==o.length?this.queryRenderedFeatures(e.point,{layers:o}):[];r.length&&(e.features=r,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:o}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const o=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in r.delegates)this.off(e,r.delegates[e]);return void o.splice(e,1)}}}on(e,t,i){if(void 0===i)return super.on(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);this._saveDelegatedListener(e,r);for(const e in r.delegates)this.on(e,r.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,o,i);}}}once(e,t,i){if(void 0===i)return super.once(e,t);const o="string"==typeof t?[t]:t,r=this._createDelegatedListener(e,o,i);for(const t in r.delegates){const a=r.delegates[t];r.delegates[t]=(...t)=>{this._removeDelegatedListener(e,o,i),a(...t);};}this._saveDelegatedListener(e,r);for(const e in r.delegates)this.once(e,r.delegates[e]);return this}off(e,t,i){return void 0===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let o;const r=e instanceof t.P||Array.isArray(e),a=r?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(r?{}:e)||{},a instanceof t.P||"number"==typeof a[0])o=[t.P.convert(a)];else {const e=t.P.convert(a[0]),i=t.P.convert(a[1]);o=[e,new t.P(i.x,e.y),i,new t.P(e.x,i.y),e];}return this.style.queryRenderedFeatures(o,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return !1!==(i=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,o;if(t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const r=this.style&&t.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new wi(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,r):this.style.loadJSON(e,t,r),this):(null===(o=null===(i=this.style)||void 0===i?void 0:i.projection)||void 0===o||o.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new wi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){if("string"==typeof e){const o=this._requestManager.transformRequest(e,"Style");t.j(o,new AbortController).then((e=>{this._updateDiff(e.data,i);})).catch((e=>{e&&this.fire(new t.k(e));}));}else "object"==typeof e&&this._updateDiff(e,i);}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(o){t.w(`Unable to perform style diff: ${o.message||o.error||o}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():t.w("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(!0)}isSourceLoaded(e){const i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.k(new Error(`There is no source with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.sourceCaches[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const o=this.style._layers[i];"hillshade"===o.type&&o.source===e.source&&t.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality."),"color-relief"===o.type&&o.source===e.source&&t.w("You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");}this.terrain=new Ba(this.painter,i,e),this.painter.renderToTexture=new Na(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{var i;"style"===t.dataType?this.terrain.sourceCache.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),"image"===(null===(i=t.source)||void 0===i?void 0:i.type)?this.terrain.sourceCache.freeRtt():this.terrain.sourceCache.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.l("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||void 0===e?void 0:e.options)&&void 0!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.sourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return !1}}return !0}removeSource(e){return this.style.removeSource(e),this._update(!0)}getSource(e){return this.style.getSource(e)}setSourceTileLodParams(e,t,i){if(i){const o=this.getSource(i);if(!o)throw new Error(`There is no source with ID "${i}", cannot set LOD parameters`);o.calculateTileZoom=me(Math.max(1,e),Math.max(1,t));}else for(const i in this.style.sourceCaches)this.style.sourceCaches[i].getSource().calculateTileZoom=me(Math.max(1,e),Math.max(1,t));return this._update(!0),this}refreshTiles(e,i){const o=this.style.sourceCaches[e];if(!o)throw new Error(`There is no source cache with ID "${e}", cannot refresh tile`);void 0===i?o.reload(!0):o.refreshTiles(i.map((e=>new t.a4(e.z,e.x,e.y))));}addImage(e,i,o={}){const{pixelRatio:r=1,sdf:a=!1,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u}=o;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.b(i))){if(void 0===i.width||void 0===i.height)return this.fire(new t.k(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:o,height:s,data:d}=i,_=i;return this.style.addImage(e,{data:new t.R({width:o,height:s},new Uint8Array(d)),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:o,height:d,data:_}=s.getImageData(i);this.style.addImage(e,{data:new t.R({width:o,height:d},_),pixelRatio:r,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:a,version:0});}}updateImage(e,i){const o=this.style.getImage(e);if(!o)return this.fire(new t.k(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const r=i instanceof HTMLImageElement||t.b(i)?s.getImageData(i):i,{width:a,height:n,data:l}=r;if(void 0===a||void 0===n)return this.fire(new t.k(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(a!==o.data.width||n!==o.data.height)return this.fire(new t.k(new Error("The width and height of the updated image must be that same as the previous version of the image")));const c=!(i instanceof HTMLImageElement||t.b(i));return o.data.replace(l,c),this.style.updateImage(e,o),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.k(new Error("Missing required image id"))),!1)}removeImage(e){this.style.removeImage(e);}loadImage(e){return p.getImage(this._requestManager.transformRequest(e,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(!0)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(!0)}removeLayer(e){return this.style.removeLayer(e),this._update(!0)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(!0)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(!0)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,o={}){return this.style.setPaintProperty(e,t,i,o),this._update(!0)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,o={}){return this.style.setLayoutProperty(e,t,i,o),this._update(!0)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(!0);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(!0);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(!0)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=n.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=n.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),o=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],o);const r=this._controlContainer=n.create("div","maplibregl-control-container",e),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{a[e]=n.create("div",`maplibregl-ctrl-${e} `,r);})),this._container.addEventListener("scroll",this._onMapScroll,!1);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0});let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:!0});let i=null;if(i=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e),!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new Mr(i,this.transform),l.testSupport(i);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.l("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){var i,o,r,a,n;const l=this._idleTriggered?this._fadeDuration:0,c=(null===(i=this.style.projection)||void 0===i?void 0:i.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let h=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const e=this.transform.zoom,i=s.now();this.style.zoomHistory.update(e,i);const o=new t.F(e,{now:i,fadeDuration:l,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),r=o.crossFadingFactor();1===r&&r===this._crossFadingFactor||(h=!0,this._crossFadingFactor=r),this.style.update(o);}const u=(null===(o=this.style.projection)||void 0===o?void 0:o.transitionState)>0!==c;null===(r=this.style.projection)||void 0===r||r.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(a=this.style.projection)||void 0===a?void 0:a.transitionState,null===(n=this.style.projection)||void 0===n?void 0:n.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||u)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,l,this._crossSourceCollisions,u),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:l,showPadding:this.showPadding}),this.fire(new t.l("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,t.cw.mark(t.cx.load),this.fire(new t.l("load"))),this.style&&(this.style.hasTransitions()||h)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const d=this._sourcesDirty||this._styleDirty||this._placementDirty;return d||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.l("idle")),!this._loaded||this._fullyLoaded||d||(this._fullyLoaded=!0,t.cw.mark(t.cx.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),p.removeThrottleControl(this._imageQueueHandle),null===(e=this._resizeObserver)||void 0===e||e.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?void 0:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),n.remove(this._canvasContainer),n.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),t.cw.clearMetrics(),this._removed=!0,this.fire(new t.l("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,s.frame(this._frameRequest,(e=>{t.cw.frame(e),this._frameRequest=null;try{this._render(e);}catch(e){if(!t.cy(e)&&!function(e){return e.message===qo}(e))throw e}}),(()=>{})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return Za}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(!0)}},e.MapMouseEvent=jr,e.MapTouchEvent=Nr,e.MapWheelEvent=Ur,e.Marker=Ka,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.e({},Va,e),this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=n.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new $a(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){n.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=n.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.E{constructor(e){super(),this._updateOpacity=()=>{void 0!==this.options.locationOccludedOpacity&&(this._container.style.opacity=this._map.transform.isLocationOccluded(this.getLngLat())?`${this.options.locationOccludedOpacity}`:"");},this.remove=()=>(this._content&&n.remove(this._content),this._container&&(n.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new t.l("close"))),this),this._onMouseUp=e=>{this._update(e.point);},this._onMouseMove=e=>{this._update(e.point);},this._onDrag=e=>{this._update(e.point);},this._update=e=>{if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=n.create("div","maplibregl-popup",this._map.getContainer()),this._tip=n.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer");}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=Wa(this._lngLat,this._flatPos,this._map.transform,this._trackPointer),this._trackPointer&&!e)return;const t=this._flatPos=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&e?e:this._map.transform.locationToScreenPoint(this._lngLat));let i=this.options.anchor;const o=as(this.options.offset);if(!i){const e=this._container.offsetWidth,r=this._container.offsetHeight;let a;a=t.y+o.bottom.ythis._map.transform.height-r?["bottom"]:[],t.xthis._map.transform.width-e/2&&a.push("right"),i=0===a.length?"bottom":a.join("-");}let r=t.add(o[i]);this.options.subpixelPositioning||(r=r.round()),n.setTransform(this._container,`${Ha[i]} translate(${r.x}px,${r.y}px)`),Xa(this._container,i,"popup"),this._updateOpacity();},this._onClose=()=>{this.remove();},this.options=t.e(Object.create(os),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.l("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.S.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let o;for(i.innerHTML=e;o=i.firstChild,o;)t.appendChild(o);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||void 0===e?void 0:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=n.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}_createCloseButton(){this.options.closeButton&&(this._closeButton=n.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(rs);e&&e.focus();}},e.RasterDEMTileSource=W,e.RasterTileSource=q,e.ScaleControl=class{constructor(e){this._onMove=()=>{ts(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,ts(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},es),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){n.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;}},e.ScrollZoomHandler=va,e.Style=wi,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=n.create("button","maplibregl-ctrl-terrain",this._container),n.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){n.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0;}},e.TwoFingersTouchPitchHandler=da,e.TwoFingersTouchRotateHandler=ha,e.TwoFingersTouchZoomHandler=la,e.TwoFingersTouchZoomRotateHandler=Pa,e.VectorTileSource=$,e.VideoSource=K,e.addSourceType=(e,i)=>t._(void 0,void 0,void 0,(function*(){if(J(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{Q[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=A;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(R),A=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},e.createTileMesh=Xt,e.getMaxParallelImageRequests=function(){return t.a.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},e.getVersion=function(){return ss},e.getWorkerCount=function(){return z.workerCount},e.getWorkerUrl=function(){return t.a.WORKER_URL},e.importScriptInWorkers=function(e){return B().broadcast("IS",e)},e.prewarm=function(){k().acquire(R);},e.setMaxParallelImageRequests=function(e){t.a.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setRTLTextPlugin=function(e,t){return oe().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){z.workerCount=e;},e.setWorkerUrl=function(e){t.a.WORKER_URL=e;};})); + +// +// Our custom intro provides a specialized "define()" function, called by the +// AMD modules below, that sets up the worker blob URL and then executes the +// main module, storing its exported value as 'maplibregl' + + +var maplibregl$1 = maplibregl; + +return maplibregl$1; + +})); +//# sourceMappingURL=maplibre-gl.js.map diff --git a/docs/articles/turf_files/maplibre-gl-geocoder-1.5.0/maplibre-gl-geocoder.css b/docs/articles/turf_files/maplibre-gl-geocoder-1.5.0/maplibre-gl-geocoder.css new file mode 100644 index 0000000..dc17b14 --- /dev/null +++ b/docs/articles/turf_files/maplibre-gl-geocoder-1.5.0/maplibre-gl-geocoder.css @@ -0,0 +1,284 @@ +/* Basics */ +.maplibregl-ctrl-geocoder, +.maplibregl-ctrl-geocoder *, +.maplibregl-ctrl-geocoder *:after, +.maplibregl-ctrl-geocoder *:before { + box-sizing: border-box; +} + +.maplibregl-ctrl-geocoder { + font-size: 18px; + line-height: 24px; + font-family: "Open Sans", "Helvetica Neue", Arial, Helvetica, sans-serif; + position: relative; + background-color: #fff; + width: 100%; + min-width: 240px; + z-index: 1; + border-radius: 4px; + transition: width 0.25s, min-width 0.25s; +} + +.maplibregl-ctrl-geocoder--input { + font: inherit; + width: 100%; + border: 0; + background-color: transparent; + margin: 0; + height: 50px; + color: #404040; /* fallback */ + color: rgba(0, 0, 0, 0.75); + padding: 6px 45px; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; +} + +.maplibregl-ctrl-geocoder--input::-ms-clear { + display: none; /* hide input clear button in IE */ +} + +.maplibregl-ctrl-geocoder--input:focus { + color: #404040; /* fallback */ + color: rgba(0, 0, 0, 0.75); + outline: 0; + box-shadow: none; + outline: thin dotted; +} + +.maplibregl-ctrl-geocoder .maplibregl-ctrl-geocoder--pin-right > * { + z-index: 2; + position: absolute; + right: 8px; + top: 7px; + display: none; +} + +.maplibregl-ctrl-geocoder, +.maplibregl-ctrl-geocoder .suggestions { + box-shadow: 0 0 10px 2px rgba(0, 0, 0, 0.1); +} + +/* Collapsed */ +.maplibregl-ctrl-geocoder.maplibregl-ctrl-geocoder--collapsed { + width: 50px; + min-width: 50px; + transition: width 0.25s, min-width 0.25s; +} + +/* Suggestions */ +.maplibregl-ctrl-geocoder .suggestions { + background-color: #fff; + border-radius: 4px; + left: 0; + list-style: none; + margin: 0; + padding: 0; + position: absolute; + width: 100%; + top: 110%; /* fallback */ + top: calc(100% + 6px); + z-index: 1000; + overflow: hidden; + font-size: 15px; +} + +.maplibregl-ctrl-bottom-left .suggestions, +.maplibregl-ctrl-bottom-right .suggestions { + top: auto; + bottom: 100%; +} + +.maplibregl-ctrl-geocoder .suggestions > li > a { + cursor: default; + display: block; + padding: 6px 12px; + color: #404040; +} + +.maplibregl-ctrl-geocoder .suggestions > .active > a, +.maplibregl-ctrl-geocoder .suggestions > li > a:hover { + color: #404040; + background-color: #f3f3f3; + text-decoration: none; + cursor: pointer; +} + +.maplibregl-ctrl-geocoder--suggestion { + display: flex; + flex-direction: row; + align-items: center; +} + +.maplibre-ctrl-geocoder--suggestion-icon { + min-width: 30px; + min-height: 24px; + max-width: 30px; + max-height: 24px; + padding-right: 12px; +} + +.maplibregl-ctrl-geocoder--suggestion-info { + display: flex; + flex-direction: column; +} + +.maplibregl-ctrl-geocoder--suggestion-match { + font-weight: bold; +} + +.maplibregl-ctrl-geocoder--suggestion-title, +.maplibregl-ctrl-geocoder--suggestion-address { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +.maplibregl-ctrl-geocoder--result { + display: flex; + flex-direction: row; + align-items: center; +} + +.maplibre-ctrl-geocoder--result-icon { + min-width: 30px; + min-height: 24px; + max-width: 30px; + max-height: 24px; + padding-right: 12px; +} + +.maplibregl-ctrl-geocoder--result-title { + font-weight: bold; +} + +.maplibregl-ctrl-geocoder--result-title, +.maplibregl-ctrl-geocoder--result-address { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +/* Icons */ +.maplibregl-ctrl-geocoder--icon { + display: inline-block; + vertical-align: middle; + speak: none; + fill: #757575; + top: 15px; +} + +.maplibregl-ctrl-geocoder--icon-search { + position: absolute; + top: 13px; + left: 12px; + width: 23px; + height: 23px; +} + +.maplibregl-ctrl-geocoder--button { + padding: 0; + margin: 0; + border: none; + cursor: pointer; + background: #fff; + line-height: 1; +} + +.maplibregl-ctrl-geocoder--icon-close { + width: 20px; + height: 20px; + margin-top: 8px; + margin-right: 3px; +} + +.maplibregl-ctrl-geocoder--button:hover .maplibregl-ctrl-geocoder--icon-close { + fill: #909090; +} + +.maplibregl-ctrl-geocoder--icon-loading { + width: 26px; + height: 26px; + margin-top: 5px; + margin-right: 0px; + -moz-animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); + -webkit-animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); + animation: rotate 0.8s infinite cubic-bezier(0.45, 0.05, 0.55, 0.95); +} + +/* Animation */ +@-webkit-keyframes rotate { + from { + -webkit-transform: rotate(0); + transform: rotate(0); + } + to { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +@keyframes rotate { + from { + -webkit-transform: rotate(0); + transform: rotate(0); + } + to { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +/* Media queries*/ +@media screen and (min-width: 640px) { + .maplibregl-ctrl-geocoder.maplibregl-ctrl-geocoder--collapsed { + width: 36px; + min-width: 36px; + } + + .maplibregl-ctrl-geocoder { + width: 33.3333%; + font-size: 15px; + line-height: 20px; + max-width: 360px; + } + .maplibregl-ctrl-geocoder .suggestions { + font-size: 13px; + } + + .maplibregl-ctrl-geocoder--icon { + top: 8px; + } + + .maplibregl-ctrl-geocoder--icon-close { + width: 16px; + height: 16px; + margin-top: 3px; + margin-right: 0; + } + + .maplibregl-ctrl-geocoder--icon-search { + left: 7px; + width: 20px; + height: 20px; + } + + .maplibregl-ctrl-geocoder--input { + height: 36px; + padding: 6px 35px; + } + + .maplibregl-ctrl-geocoder--icon-loading { + width: 26px; + height: 26px; + margin-top: -2px; + margin-right: -5px; + } + + .maplibre-gl-geocoder--error { + color: #909090; + padding: 6px 12px; + font-size: 16px; + text-align: center; + } +} diff --git a/docs/articles/turf_files/maplibre-gl-geocoder-1.5.0/maplibre-gl-geocoder.min.js b/docs/articles/turf_files/maplibre-gl-geocoder-1.5.0/maplibre-gl-geocoder.min.js new file mode 100644 index 0000000..e285a1a --- /dev/null +++ b/docs/articles/turf_files/maplibre-gl-geocoder-1.5.0/maplibre-gl-geocoder.min.js @@ -0,0 +1,2 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.MaplibreGeocoder=t()}}(function(){return function(){function t(e,i,n){function s(o,l){if(!i[o]){if(!e[o]){var a="function"==typeof require&&require;if(!l&&a)return a(o,!0);if(r)return r(o,!0);var h=new Error("Cannot find module '"+o+"'");throw h.code="MODULE_NOT_FOUND",h}var u=i[o]={exports:{}};e[o][0].call(u.exports,function(t){return s(e[o][1][t]||t)},u,u.exports,t,e,i,n)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o
'+e[0]+'
'+e.splice(1,e.length).join(",")+"